@clowdops/tsclient 0.6.6 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/http/HttpError.ts","../src/http/BaseClient.ts","../src/modules/auth/AuthClient.ts","../src/common/envelope.ts","../src/modules/mfa/MfaClient.ts","../src/modules/user/UserClient.ts","../src/modules/organization/OrganizationClient.ts","../src/modules/projects/types.ts","../src/adapters/projectAdapter.ts","../src/modules/projects/ProjectsClient.ts","../src/adapters/sandboxAdapter.ts","../src/modules/sandboxes/SandboxesClient.ts","../src/modules/credentials/types.ts","../src/modules/credentials/AgentTokensClient.ts","../src/modules/credentials/GatewayTokensClient.ts","../src/modules/credentials/TelegramClient.ts","../src/modules/credentials/CredentialsClient.ts","../src/modules/chat/ChatStream.ts","../src/modules/chat/ChatClient.ts","../src/modules/agentEngine/TemplatesClient.ts","../src/modules/agentEngine/ScheduledTasksClient.ts","../src/modules/resources/ResourcesClient.ts","../src/modules/systemEvents/types.ts","../src/modules/systemEvents/SystemEventsClient.ts","../src/modules/billing/SubscriptionsClient.ts","../src/modules/billing/CreditsClient.ts","../src/modules/usage/UsageClient.ts","../src/modules/approvals/ApprovalsClient.ts","../src/modules/budgets/BudgetsClient.ts","../src/modules/metering/MeteringClient.ts","../src/modules/referrals/ReferralsClient.ts","../src/modules/reseller/ResellerClient.ts","../src/modules/platformAdmin/PlatformAdminClient.ts","../src/modules/deployments/DeploymentsClient.ts","../src/modules/capacity/CapacityClient.ts","../src/modules/bi/BIClient.ts","../src/modules/dashboards/DashboardsClient.ts","../src/modules/connections/ConnectionsClient.ts","../src/modules/connect/types.ts","../src/modules/connect/validate.ts","../src/modules/connect/ConnectClient.ts","../src/modules/capabilities/CapabilitiesClient.ts","../src/modules/contacts/ContactsClient.ts","../src/modules/facts/FactsClient.ts","../src/modules/packs/PacksClient.ts","../src/modules/brandAuthority/BrandAuthorityClient.ts","../src/modules/marketingConsent/MarketingConsentClient.ts","../src/modules/meetingMinutes/MeetingMinutesClient.ts","../src/modules/followThrough/FollowThroughClient.ts","../src/modules/crmHandoffs/CrmHandoffsClient.ts","../src/modules/personExport/PersonExportClient.ts","../src/modules/artifacts/ArtifactsClient.ts","../src/modules/signals/SignalsClient.ts","../src/client.ts","../src/common/types.ts","../src/modules/mfa/types.ts","../src/modules/projects/pmCoverage.ts","../src/modules/projects/pmDocuments.ts","../src/modules/projects/pmStatus.ts","../src/modules/credentials/providers.ts","../src/modules/chat/types.ts","../src/modules/chat/cards.ts","../src/modules/capabilities/types.ts","../src/modules/budgets/types.ts","../src/modules/dashboards/types.ts","../src/modules/dashboards/validate.ts","../src/modules/dashboards/schema.json","../src/modules/dashboards/schema.ts"],"names":["normalize","BASE_PATH","scopeHeaders","BASE","ProviderType","AccessType","OrgRoles","MFAType","isRecord","title","summary","status"],"mappings":";AAAO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAMnC,WAAA,CAAY,MAAA,EAAgB,UAAA,EAAoB,IAAA,EAAe;AAC7D,IAAA,MAAM,SAAA,GAAY,iBAAiB,IAAI,CAAA;AACvC,IAAA,MAAM,UAAU,cAAA,CAAe,IAAI,KAAK,CAAA,EAAG,MAAM,IAAI,UAAU,CAAA,CAAA;AAC/D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAClB,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEA,SAAS,iBAAiB,IAAA,EAA8B;AACtD,EAAA,IAAI,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACpC,IAAA,MAAM,IAAA,GACH,IAAA,CAAiC,UAAA,IAC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,kBAAA,EAAmB,EAAE;AAAE,SACpE;AAAA,QACA;AAAA,UACE,EAAA,EAAM,EAAE,UAAA,EAAc,EAAE,IAAA,EAAQ,EAAE,KAAA,EAAS,OAAA,EAAQ,EAAE,EAAG,QAAA,EAAY,CAAC,MAAM,CAAA,EAAE;AAAA,UAC7E,IAAA,EAAQ,EAAE,UAAA,EAAc,EAAE,KAAO,EAAE,IAAA,EAAQ,kBAAA,EAAmB,EAAE;AAAE,SACpE;AAAA,QACA;AAAA,UACE,EAAA,EAAM;AAAA,YACJ,UAAA,EAAc,EAAE,IAAA,EAAQ,EAAE,MAAQ,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,SAAS,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,MAAM,GAAE,EAAE;AAAA,YACpG,QAAA,EAAY,CAAC,MAAM;AAAA,WACrB;AAAA,UACA,IAAA,EAAQ,EAAE,UAAA,EAAc,EAAE,KAAO,EAAE,IAAA,EAAQ,kBAAA,EAAmB,EAAE;AAAE;AACpE;AACF;AACF;AAEJ,CAAA;;;ACpgBO,IAAM,gBAAA,GAAsD","file":"index.js","sourcesContent":["export class HttpError extends Error {\n readonly status: number;\n readonly statusText: string;\n readonly errorCode: string | null;\n readonly body: unknown;\n\n constructor(status: number, statusText: string, body: unknown) {\n const errorCode = extractErrorCode(body);\n const message = extractMessage(body) ?? `${status} ${statusText}`;\n super(message);\n this.name = 'HttpError';\n this.status = status;\n this.statusText = statusText;\n this.errorCode = errorCode;\n this.body = body;\n }\n}\n\nfunction extractErrorCode(body: unknown): string | null {\n if (body && typeof body === 'object') {\n const code =\n (body as Record<string, unknown>).error_code ??\n (body as Record<string, unknown>).errorCode ??\n (body as Record<string, unknown>).code;\n if (typeof code === 'string') return code;\n }\n return null;\n}\n\nfunction extractMessage(body: unknown): string | null {\n if (body && typeof body === 'object') {\n const msg = (body as Record<string, unknown>).message ?? (body as Record<string, unknown>).error;\n if (typeof msg === 'string') return msg;\n }\n return null;\n}\n\nexport class NotImplementedError extends Error {\n constructor(method: string) {\n super(`${method} is not implemented in the cloud-agent backend yet.`);\n this.name = 'NotImplementedError';\n }\n}\n","import { HttpError } from './HttpError.js';\nimport type { TokenProvider, UnauthorizedHandler } from './tokenProvider.js';\n\n/**\n * Returns the org id the platform admin is currently impersonating, or\n * undefined when not impersonating. Resolved per-request so a UI toggle\n * takes effect on the next call without rebuilding the client. Honored\n * by the server only for users in the configured ADMIN_ORGANIZATION;\n * non-admins receive a 403.\n */\nexport type ImpersonationProvider = () => string | undefined | Promise<string | undefined>;\n\nexport interface BaseClientOptions {\n baseUrl: string;\n getToken?: TokenProvider;\n onUnauthorized?: UnauthorizedHandler;\n fetch?: typeof fetch;\n debug?: boolean;\n defaultHeaders?: Record<string, string>;\n getImpersonateOrgId?: ImpersonationProvider;\n /**\n * fetch credentials mode. Defaults to 'include' so the shared-domain\n * `fb_session` cookie is stored on login and sent to /session/bootstrap —\n * including in dev, where the SPA origin (app.localtest.me:3001) and the\n * API (api.localtest.me:3000) are same-site but cross-origin. Server-side\n * (Node) fetch ignores it. Requires the API's CORS to allow credentials\n * for the exact origin (it does).\n */\n credentials?: RequestCredentials;\n}\n\nexport type QueryValue = string | number | boolean | string[] | null | undefined;\nexport type Query = Record<string, QueryValue>;\n\nexport interface RequestOptions {\n /**\n * Query string params. Plain object; we serialize string/number/boolean,\n * repeat arrays, and drop undefined/null values.\n */\n query?: object;\n body?: unknown;\n headers?: Record<string, string>;\n /** Skip the bearer token (used for public endpoints like /user/login). */\n skipAuth?: boolean;\n}\n\nexport class BaseClient {\n readonly baseUrl: string;\n private readonly getToken?: TokenProvider;\n private readonly onUnauthorized?: UnauthorizedHandler;\n private readonly fetchImpl: typeof fetch;\n private readonly debug: boolean;\n private readonly defaultHeaders: Record<string, string>;\n private readonly getImpersonateOrgId?: ImpersonationProvider;\n private readonly credentials: RequestCredentials;\n\n constructor(options: BaseClientOptions) {\n if (!options.baseUrl) throw new Error('CloudAgentClient: baseUrl is required');\n this.baseUrl = options.baseUrl.replace(/\\/$/, '');\n this.getToken = options.getToken;\n this.onUnauthorized = options.onUnauthorized;\n this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.debug = options.debug ?? false;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.getImpersonateOrgId = options.getImpersonateOrgId;\n this.credentials = options.credentials ?? 'include';\n }\n\n get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, options);\n }\n post<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, options);\n }\n put<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('PUT', path, options);\n }\n patch<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('PATCH', path, options);\n }\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n async request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n // Internal: set on the single post-refresh retry so a persistent 401\n // can't loop. Not part of the public surface.\n retrying = false,\n ): Promise<T> {\n const url = this.buildUrl(path, options.query);\n const headers: Record<string, string> = { ...this.defaultHeaders, ...(options.headers ?? {}) };\n\n if (!options.skipAuth && this.getToken) {\n const token = await this.getToken();\n if (token) headers['Authorization'] = `Bearer ${token}`;\n }\n\n // Impersonation header is opt-in via the constructor callback. The\n // explicit per-request `headers` win — call sites that already supply\n // an X-Impersonate-Org-Id (tests, edge cases) keep precedence.\n if (\n !options.skipAuth &&\n this.getImpersonateOrgId &&\n !('X-Impersonate-Org-Id' in headers) &&\n !('x-impersonate-org-id' in headers)\n ) {\n const target = await this.getImpersonateOrgId();\n if (target) headers['X-Impersonate-Org-Id'] = target;\n }\n\n let body: BodyInit | undefined;\n if (options.body !== undefined && options.body !== null) {\n if (options.body instanceof FormData) {\n body = options.body;\n } else {\n if (!('Content-Type' in headers) && !('content-type' in headers)) {\n headers['Content-Type'] = 'application/json';\n }\n body = JSON.stringify(options.body);\n }\n }\n\n if (this.debug) {\n // eslint-disable-next-line no-console\n console.debug('[clowdops/tsclient] →', method, url, options.body ?? '');\n }\n\n const res = await this.fetchImpl(url, { method, headers, body, credentials: this.credentials });\n\n let parsed: unknown = null;\n const text = await res.text();\n if (text.length > 0) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = text;\n }\n }\n\n if (this.debug) {\n // eslint-disable-next-line no-console\n console.debug('[clowdops/tsclient] ←', res.status, url, parsed);\n }\n\n if (!res.ok) {\n // On a 401 for an authed request, give the handler a chance to refresh\n // the access token, then retry the original request exactly once with\n // the new token. `retrying` guards against an infinite loop when the\n // refreshed token still 401s; `skipAuth` requests (login etc.) carry no\n // token to refresh, so a 401 there is a real failure, not staleness.\n if (res.status === 401 && this.onUnauthorized && !options.skipAuth && !retrying) {\n let refreshed = false;\n try {\n // void return ⇒ assume retry is worthwhile (legacy handlers);\n // explicit false ⇒ refresh failed, surface the original 401.\n refreshed = (await this.onUnauthorized()) !== false;\n } catch {\n // swallow handler failures — the original 401 is still surfaced\n }\n if (refreshed) {\n return this.request<T>(method, path, options, true);\n }\n }\n throw new HttpError(res.status, res.statusText, parsed);\n }\n\n return parsed as T;\n }\n\n private buildUrl(path: string, query?: object): string {\n const base = path.startsWith('http') ? path : `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n if (!query) return base;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query as Record<string, unknown>)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const v of value) params.append(key, String(v));\n } else {\n params.set(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `${base}?${qs}` : base;\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n ActivateRequest,\n ExchangeCodeRequest,\n ExchangeOIDCRequest,\n LoginRequest,\n PublicConfig,\n RefreshRequest,\n RegisterRequest,\n ResetPasswordRequest,\n SessionResponse,\n SimpleResponse,\n} from './types.js';\n\nexport class AuthClient {\n constructor(private readonly http: BaseClient) {}\n\n login(body: LoginRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/user/login', { body, skipAuth: true });\n }\n\n register(body: RegisterRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/user/register', { body, skipAuth: true });\n }\n\n /**\n * Unauthenticated boot config. The SPA reads `openRegistration` to decide\n * whether to render the self-service signup form (false => invite-only /\n * preview mode). Safe to call before any session exists.\n */\n publicConfig(): Promise<PublicConfig> {\n return this.http.get<PublicConfig>('/public-config', { skipAuth: true });\n }\n\n logout(refreshToken?: string): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>('/user/logout', {\n body: { refreshToken },\n });\n }\n\n refresh(body: RefreshRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/user/refresh', { body, skipAuth: true });\n }\n\n activate(body: ActivateRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/user/activate', { body, skipAuth: true });\n }\n\n requestVerification(email: string): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>('/user/request-verification', {\n body: { email },\n skipAuth: true,\n });\n }\n\n requestPasswordReset(email: string): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>('/user/request-reset-password', {\n body: { email },\n skipAuth: true,\n });\n }\n\n resetPassword(body: ResetPasswordRequest): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>('/user/reset-password', { body, skipAuth: true });\n }\n\n exchangeGoogle(body: ExchangeCodeRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/auth/google/exchange', { body, skipAuth: true });\n }\n\n /** Generic OIDC code exchange (unified-auth plan, Issue 3). */\n exchangeOIDC(body: ExchangeOIDCRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/auth/oidc/exchange', { body, skipAuth: true });\n }\n\n /**\n * Mint a fresh access token from the shared-domain `fb_session` cookie\n * (unified-auth plan, Issue 1). The cookie is the credential — no body, no\n * bearer; the custom header is CSRF defense-in-depth (CORS-allow-listed).\n * 401 error_code values: no_session_cookie | invalid_session |\n * session_revoked. Never returns a refresh token (cookie-only refresh).\n */\n sessionBootstrap(): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/session/bootstrap', {\n skipAuth: true,\n headers: { 'X-Session-Bootstrap': '1' },\n });\n }\n}\n","/**\n * Most cloud-agent endpoints return `{ success: true, data: T }` or\n * `{ success: true, <key>: T }`. A few (system events, exchange) return\n * bare shapes. These helpers keep envelope handling out of the per-domain\n * clients.\n */\n\nexport interface SuccessEnvelope<T> {\n success: boolean;\n data?: T;\n message?: string;\n error_code?: string;\n}\n\nexport function unwrapData<T>(payload: { success?: boolean; data?: T } | undefined | null): T {\n if (!payload || payload.data === undefined) {\n throw new Error('Response envelope missing `data` field.');\n }\n return payload.data;\n}\n\nexport function unwrapKey<T>(payload: Record<string, unknown> | undefined | null, key: string): T {\n if (!payload || payload[key] === undefined) {\n throw new Error(`Response envelope missing \\`${key}\\` field.`);\n }\n return payload[key] as T;\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n MagicLinkActivateRequest,\n MagicLinkSendResponse,\n MFASetupResponse,\n MFASimpleResponse,\n MFAStatus,\n MFAType,\n MFAVerifyLoginRequest,\n MFAVerifyLoginResponse,\n MFAVerifySetupRequest,\n} from './types.js';\n\nexport class MfaClient {\n constructor(private readonly http: BaseClient) {}\n\n async getStatus(): Promise<MFAStatus> {\n const res = await this.http.get<{ success: boolean; data: MFAStatus }>('/mfa/status');\n return unwrapData(res);\n }\n\n async getMethods(): Promise<MFAType[]> {\n const res = await this.http.get<{ success: boolean; data: { methods: MFAType[] } }>('/mfa/methods');\n return res.data?.methods ?? [];\n }\n\n setup(body: { mfaType: MFAType; email?: string }): Promise<MFASetupResponse> {\n return this.http.post<MFASetupResponse>('/mfa/setup', { body });\n }\n\n verifySetup(body: MFAVerifySetupRequest): Promise<MFASimpleResponse> {\n return this.http.post<MFASimpleResponse>('/mfa/verify-setup', { body });\n }\n\n enable(mfaType: MFAType): Promise<MFASimpleResponse> {\n return this.http.post<MFASimpleResponse>('/mfa/enable', { body: { mfaType } });\n }\n\n disable(mfaType: MFAType): Promise<MFASimpleResponse> {\n return this.http.post<MFASimpleResponse>('/mfa/disable', { body: { mfaType } });\n }\n\n setPrimary(mfaType: MFAType): Promise<MFASimpleResponse> {\n return this.http.post<MFASimpleResponse>('/mfa/primary', { body: { mfaType } });\n }\n\n sendMagicLink(): Promise<MagicLinkSendResponse> {\n return this.http.post<MagicLinkSendResponse>('/mfa/magic-link/send', {});\n }\n\n activateMagicLink(body: MagicLinkActivateRequest): Promise<MFAVerifyLoginResponse> {\n return this.http.post<MFAVerifyLoginResponse>('/mfa/magic-link/activate', { body, skipAuth: true });\n }\n\n verifyLogin(body: MFAVerifyLoginRequest): Promise<MFAVerifyLoginResponse> {\n return this.http.post<MFAVerifyLoginResponse>('/mfa/verify-login', { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type { UpdateUserRequest, UpdateUserResponse, UserProfile } from './types.js';\n\nexport class UserClient {\n constructor(private readonly http: BaseClient) {}\n\n async getProfile(): Promise<UserProfile> {\n const res = await this.http.get<{ success: boolean; data: UserProfile }>('/me');\n return unwrapData(res);\n }\n\n update(body: UpdateUserRequest): Promise<UpdateUserResponse> {\n return this.http.put<UpdateUserResponse>('/user', { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type { ProductKind } from '../projects/types.js';\nimport type {\n AcceptInviteRequest,\n AddUserToOrgRequest,\n AddUserToOrgResult,\n AdjustOrgCreditsRequest,\n AdjustOrgCreditsResult,\n AdminOrgSummaryQuery,\n AdminOrgSummaryResponse,\n CreateOrganizationRequest,\n CreateOrganizationUserRequest,\n InviteOrgRequest,\n InviteOrgResult,\n OrgCreditBalance,\n OrgInvite,\n OrgNotifySubscriptions,\n OrgSearchResult,\n Organization,\n OrganizationUser,\n SetOrgNotifySubscriptionsRequest,\n SimpleOrgResponse,\n UpdateOrganizationRequest,\n UpdateOrgUserRequest,\n} from './types.js';\n\nexport class OrganizationClient {\n constructor(private readonly http: BaseClient) {}\n\n async get(orgId: string): Promise<Organization> {\n const res = await this.http.get<{ success: boolean; data: Organization }>(`/organization/${orgId}`);\n return unwrapData(res);\n }\n\n async update(orgId: string, body: UpdateOrganizationRequest): Promise<Organization> {\n const res = await this.http.put<{ success: boolean; data: Organization }>(`/organization/${orgId}`, { body });\n return unwrapData(res);\n }\n\n /**\n * Self-service: create an org for the current (orgless) user and assign them\n * as Owner. Used by the onboarding wizard so the org exists before the limits\n * and project/sandbox steps. Fails if the user already belongs to an org.\n */\n async create(body: CreateOrganizationRequest): Promise<Organization> {\n const res = await this.http.post<{ success: boolean; data: Organization }>('/organization', { body });\n return unwrapData(res);\n }\n\n /**\n * Fetch the org's default-notification-channel config: the per-event\n * subscriptions, the notify channels available to route to, and whether the\n * caller's org is the platform-admin org (which unlocks the cross-org\n * `engine_failure` / `infra_outage` event types).\n */\n async getNotifySubscriptions(): Promise<OrgNotifySubscriptions> {\n const res = await this.http.get<{ success: boolean; data: OrgNotifySubscriptions }>(\n '/organization/notify-subscriptions',\n );\n return unwrapData(res);\n }\n\n /**\n * Replace the org's notify subscriptions (replace-set). Each edge is\n * validated server-side: the credential must be a notify channel in the org,\n * and admin-only event types require a platform-admin caller.\n */\n setNotifySubscriptions(body: SetOrgNotifySubscriptionsRequest): Promise<SimpleOrgResponse> {\n return this.http.put<SimpleOrgResponse>('/organization/notify-subscriptions', { body });\n }\n\n async listUsers(): Promise<OrganizationUser[]> {\n const res = await this.http.get<{ success: boolean; data: OrganizationUser[] }>('/organization/users');\n return res.data ?? [];\n }\n\n updateUser(userId: string, body: UpdateOrgUserRequest): Promise<SimpleOrgResponse> {\n return this.http.put<SimpleOrgResponse>(`/organization/users/${userId}`, { body });\n }\n\n /** Backend currently returns 501. Surfaced for forward-compat. */\n createUser(body: CreateOrganizationUserRequest): Promise<SimpleOrgResponse> {\n return this.http.post<SimpleOrgResponse>('/organization/users', { body });\n }\n\n /** Backend currently returns 501. Surfaced for forward-compat. */\n deleteUser(userId: string): Promise<SimpleOrgResponse> {\n return this.http.delete<SimpleOrgResponse>(`/organization/users/${userId}`);\n }\n\n /** Accept an org invite: verifies the one-time token and sets the user's password. */\n acceptInvite(body: AcceptInviteRequest): Promise<SimpleOrgResponse> {\n return this.http.post<SimpleOrgResponse>('/organization/invite/accept', { body });\n }\n\n /**\n * Platform-admin only: list every org for the impersonation picker.\n * The server returns 403 when the caller's home org is not the\n * configured ADMIN_ORGANIZATION; render the picker only when the\n * authenticated user has `isPlatformAdmin === true`.\n */\n async listAll(): Promise<Array<{ id: string; name: string; allowDebug: boolean }>> {\n const res = await this.http.get<{\n success: boolean;\n data: Array<{ id: string; name: string; allowDebug: boolean }>;\n }>('/orgs/list-all');\n return res.data ?? [];\n }\n\n /**\n * Platform-admin only: typeahead org search. Returns up to `limit` matches\n * (id+name) for the case-insensitive name substring `q` (or the first\n * `limit` orgs when `q` is empty) plus the total match count, so a picker\n * can show \"N more — refine your search\". Returns 403 unless platform admin.\n */\n async searchOrgs(q = '', limit = 10): Promise<OrgSearchResult> {\n const res = await this.http.get<{ success: boolean; data: OrgSearchResult }>('/orgs/search', {\n query: { q, limit },\n });\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: one page of the service-wide org summary — per-org\n * user/project/sandbox counts, trailing 7d/30d metered usage, billed-to-\n * balance, lifetime purchases and current credit balance — searchable by\n * name and pageable. Backs the admin Summary screen. Returns 403 unless the\n * caller's home org is the configured ADMIN_ORGANIZATION.\n */\n async adminOrgSummary(query: AdminOrgSummaryQuery = {}): Promise<AdminOrgSummaryResponse> {\n const res = await this.http.get<{ success: boolean; data: AdminOrgSummaryResponse }>(\n '/admin/orgs/summary',\n { query: query as Record<string, unknown> },\n );\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: provision a new organization + founding owner and\n * email the owner an invite link. The invite-only counterpart to public\n * self-service registration (used while the backend has OPEN_REGISTRATION\n * disabled). Returns 403 unless the caller's home org is the configured\n * ADMIN_ORGANIZATION; 409 when the owner email already exists.\n */\n async inviteOrg(body: InviteOrgRequest): Promise<InviteOrgResult> {\n const res = await this.http.post<{ success: boolean; data: InviteOrgResult }>(\n '/organization/invite-org',\n { body },\n );\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: list every outstanding org + member invite (founding-\n * owner invites from `inviteOrg` and members added via `addUserToOrg`) with\n * derived status, newest first. Cancelled invites (soft-deleted) and live\n * non-invited orgs are excluded. Returns 403 unless platform admin.\n */\n async listOrgInvites(): Promise<OrgInvite[]> {\n const res = await this.http.get<{ success: boolean; data: OrgInvite[] }>('/admin/org-invites');\n return res.data ?? [];\n }\n\n /**\n * Platform-admin only: re-send an invite — mints a fresh 7-day token and\n * re-emails the link. Returns 403 unless platform admin; 404 when no pending\n * invite exists; 409 once the invite has been redeemed.\n */\n resendOrgInvite(userId: string): Promise<SimpleOrgResponse> {\n return this.http.post<SimpleOrgResponse>(`/admin/org-invites/${userId}/resend`, {});\n }\n\n /**\n * Platform-admin only: cancel a pending invite. Soft-deletes the invited user\n * (and the shell org, for a never-redeemed founding-owner invite with no other\n * members) and revokes the token, freeing the email for re-invite. Returns 403\n * unless platform admin; 404 when absent; 409 once the invite has been redeemed.\n */\n cancelOrgInvite(userId: string): Promise<SimpleOrgResponse> {\n return this.http.post<SimpleOrgResponse>(`/admin/org-invites/${userId}/cancel`, {});\n }\n\n /**\n * Platform-admin only: enable or disable the debug surface for an org.\n * Returns the updated org entry with the new allowDebug value.\n */\n async setAllowDebug(orgId: string, allow: boolean): Promise<{ id: string; name: string; allowDebug: boolean }> {\n const res = await this.http.patch<{\n success: boolean;\n data: { id: string; name: string; allowDebug: boolean };\n }>(`/orgs/${orgId}/allow-debug`, { body: { allow } });\n return res.data!;\n }\n\n /**\n * Platform-admin only: replace an org's product entitlement. `products` is\n * the full desired set ('cloud' | 'bi'); unknown codes are rejected 400.\n * Returns the updated org's id, name and enabledProducts.\n */\n async setEnabledProducts(\n orgId: string,\n products: ProductKind[],\n ): Promise<{ id: string; name: string; enabledProducts: ProductKind[] }> {\n const res = await this.http.patch<{\n success: boolean;\n data: { id: string; name: string; enabledProducts: ProductKind[] };\n }>(`/orgs/${orgId}/enabled-products`, { body: { products } });\n return res.data!;\n }\n\n /**\n * Platform-admin only: add a new member to an existing org.\n * Creates the user without a password and sends an invite email via the\n * same TokenOrgInvite flow as the regular member invite.\n * Returns 403 unless platform admin; 409 when the email already exists.\n */\n async addUserToOrg(orgId: string, body: AddUserToOrgRequest): Promise<AddUserToOrgResult> {\n const res = await this.http.post<{ success: boolean; data: AddUserToOrgResult }>(\n `/orgs/${orgId}/users`,\n { body },\n );\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: fetch an org's two-bucket credit balance.\n * Returns 403 unless platform admin; 404 when the org doesn't exist.\n */\n async getOrgCreditBalance(orgId: string): Promise<OrgCreditBalance> {\n const res = await this.http.get<{ success: boolean; data: OrgCreditBalance }>(\n `/orgs/${orgId}/credits`,\n );\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: grant or revoke credits on an org.\n * amountMicros is signed: positive = grant, negative = revoke.\n * Records a CreditKindAdminAdjust ledger entry and returns the updated balance.\n */\n async adjustOrgCredits(orgId: string, body: AdjustOrgCreditsRequest): Promise<AdjustOrgCreditsResult> {\n const res = await this.http.post<{ success: boolean; data: AdjustOrgCreditsResult }>(\n `/orgs/${orgId}/credits/adjust`,\n { body },\n );\n return unwrapData(res);\n }\n}\n","import type { AccessType, UserSummary } from '../../common/types.js';\n\nexport interface ProjectMember {\n userId: string;\n role: string;\n user: UserSummary;\n}\n\n/** AI providers eligible for the per-project platform-keys opt-in. */\nexport type PreferredAiProvider = 'OPENAI' | 'ANTHROPIC' | 'GEMINI' | 'BEDROCK';\n\nexport interface Project {\n id: string;\n name: string;\n orgId: string;\n default: boolean;\n /**\n * Marks the admin org's global-AI-key project (its AI credentials form the\n * platform-wide pool). Meaningful only for the platform-admin org.\n */\n isReferenceProject?: boolean;\n /**\n * When set on a project with no BYOK AI credentials, routes that project's\n * LLM calls to the platform (\"global\") keys for this provider. Mutually\n * exclusive with BYOK AI keys. Null/absent = BYOK.\n */\n preferredAiProvider?: PreferredAiProvider | null;\n /**\n * Product partition the project belongs to — 'cloud' (cloud-ops, the\n * default), 'bi' (Talk-to-Your-BI), 'meeting' (ClowdMeeting), 'marketing'\n * (ClowdMarketing), 'pm' (ClowdPM) or 'startup' (ClowdStartup). Each frontend\n * lists only its own product's projects. A UX partition, not a security\n * boundary.\n */\n product?: ProductKind;\n users: ProjectMember[];\n}\n\n/**\n * The product verticals a project can belong to.\n *\n * Mirrors the backend's closed `products.Product` enum and its migration CHECK\n * constraints (0065 for the first four, 0110 for `'pm'`, 0127 for `'startup'`).\n * Adding a member here without adding it there means the server rejects a value\n * this client says is valid. `'pm'` is ClowdPM (PJM-D1); its project, memory and\n * document surfaces use the same product partition without treating it as an\n * authority grant. `'startup'` is ClowdStartup, the Bueeld server-to-server\n * integration: its projects are provisioned by the backend, never from a\n * browser, so it is a grant an admin can give an org rather than a workspace a\n * console creates.\n */\nexport const PRODUCT_KINDS = ['cloud', 'bi', 'meeting', 'marketing', 'pm', 'startup'] as const;\n\nexport type ProductKind = (typeof PRODUCT_KINDS)[number];\n\n/**\n * Runtime guard for product values received over JSON.\n *\n * A TypeScript union disappears at runtime, so casting an arbitrary server\n * string to ProductKind would make an unsupported/newer product look supported\n * to downstream switches. Keep the runtime vocabulary beside the wire type so\n * adapters can fail closed instead.\n */\nexport function isProductKind(value: unknown): value is ProductKind {\n return typeof value === 'string' && (PRODUCT_KINDS as readonly string[]).includes(value);\n}\n\ninterface CreateProjectRequestBase {\n name: string;\n}\n\n/**\n * Project creation request. ClowdPM creation deliberately requires a caller-\n * stable request key: if the response is lost, a key minted only by the server\n * cannot be recovered and a retry could create a second project. Other products\n * retain their rolling-compatible keyless request shape.\n */\nexport type CreateProjectRequest =\n | (CreateProjectRequestBase & {\n product: 'pm';\n /**\n * Caller-supplied idempotency handle for durable ClowdPM creation. It\n * identifies the REQUEST, not the project. Mint it once with\n * {@link newProjectRequestKey}, persist it for the attempt-chain, and\n * resend the same value on every retry.\n */\n requestKey: string;\n })\n | (CreateProjectRequestBase & {\n /** Defaults to 'cloud' server-side when omitted. */\n product?: Exclude<ProductKind, 'pm'>;\n /** Idempotency is currently defined only for ClowdPM creation. */\n requestKey?: never;\n });\n\n/**\n * Mint a fresh idempotency handle for {@link CreateProjectRequest.requestKey}.\n *\n * This is a REQUEST handle, not an identity: it lets a retried ClowdPM creation\n * converge on the same server-minted project. Generate it once when the user\n * initiates creation and reuse the same value across retries; never regenerate\n * it per attempt. Uses WebCrypto's `randomUUID` where available (browsers and\n * Node ≥ 16.7), with a non-cryptographic fallback that is still adequately\n * unique for an idempotency key.\n */\nexport function newProjectRequestKey(): string {\n const webcrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (typeof webcrypto?.randomUUID === 'function') return webcrypto.randomUUID();\n return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n}\n\nexport interface UpdateProjectRequest {\n name?: string;\n isReferenceProject?: boolean;\n /** Empty string clears the platform-keys opt-in (back to BYOK). */\n preferredAiProvider?: PreferredAiProvider | '' | null;\n}\n\nexport interface AddMemberRequest {\n userId: string;\n role: AccessType | string;\n}\n\nexport interface UpdateMemberRoleRequest {\n role: AccessType | string;\n}\n\n/**\n * ClowdPM (`pm`) project membership role vocabulary (PJM-IP01 §2.3). It is a\n * DISTINCT vocabulary from the legacy `AccessType` (READ|WRITE|ADMIN): a pm\n * project's roster is `manager | member | reader`, derived server-side and\n * mapped to the authorization decision table by the backend. The legacy\n * `addMember`/`removeMember` routes are refused for a pm project — governed\n * membership goes through `grantPMMember`/`revokePMMember` below.\n */\nexport type PmRole = 'manager' | 'member' | 'reader';\n\n/**\n * Grant a principal a ClowdPM project role. This is the governed\n * `pm.membership.change` act (manager-directed = proposal and approval in one\n * recorded step). It is value-idempotent and read-back verified server-side; the\n * caller who is not an active project MANAGER — including a non-member\n * organization administrator — is refused. The client asserts no authority.\n */\nexport interface PmGrantMemberRequest {\n userId: string;\n role: PmRole;\n}\n\nexport interface PmGrantMemberResponse {\n success: boolean;\n granted: boolean;\n role: PmRole;\n}\n\n/**\n * Revoke a principal's ClowdPM project membership. A revoke of an already-revoked\n * or never-granted principal is a recorded no-op: `revoked` is then `false`, and\n * that is a success, not an error.\n */\nexport interface PmRevokeMemberResponse {\n success: boolean;\n revoked: boolean;\n}\n\n/**\n * Last-manager recovery (PJM-IP01 §2.4 / `pm.recover-management`): the narrow,\n * audited path where an organization administrator appoints a NAMED replacement\n * manager for a project that has NO active manager. It grants the invoking\n * administrator no ordinary project read.\n */\nexport interface PmRecoverManagementRequest {\n replacementUserId: string;\n reason: string;\n}\n\nexport interface PmRecoverManagementResponse {\n success: boolean;\n recovered: boolean;\n replacementUserId: string;\n}\n\n/**\n * ClowdPM project-memory record families (PJM-IP02, context model §2). The\n * thirteen families seeded by migration 0113. This is the set this client knows\n * how to suggest, not a closed wire enum: a later backend migration may add a\n * family to `pm_record_family`, and older clients must still round-trip it.\n */\nexport const PM_RECORD_FAMILIES = [\n 'tailoring',\n 'phase_gate',\n 'baseline',\n 'deliverable',\n 'wbs_node',\n 'activity',\n 'decision',\n 'action',\n 'risk',\n 'stakeholder',\n 'issue',\n 'assumption',\n 'communication',\n] as const;\n\nexport type PmKnownRecordFamily = (typeof PM_RECORD_FAMILIES)[number];\nexport type PmRecordFamily = string;\n\n/** Runtime wire guard. Support is server-catalogued; non-blank newer families are valid. */\nexport function isPmRecordFamily(value: unknown): value is PmRecordFamily {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/**\n * Provenance origin of a revision's value. A `human` value is authoritative and\n * carries NO confidence hedge; an `extracted` value is visibly `provisional` and\n * — by backend schema CHECK, not convention — can never reach accepted ownership\n * until a human confirms it.\n */\nexport type PmOrigin = 'human' | 'extracted';\n\n/**\n * Accountable-owner state. Ownership beyond `unassigned` requires a named person\n * (`accountableContactId`). An `extracted` value may be `proposed` but never\n * `accepted` — the consequence an owned commitment rests on.\n */\nexport type PmAccountableState = 'unassigned' | 'proposed' | 'accepted' | 'declined';\n\n/** Shallow work state for work-bearing families (no schedule/dependency algebra). */\nexport type PmWorkState = 'todo' | 'in_progress' | 'blocked' | 'done' | 'cancelled';\n\n/**\n * Derived, read-only readiness of a record's current revision. The backend\n * computes it for the `risk` family only (`ready` requires a human value, an\n * `accepted` accountable state AND a named person); every other family is `n/a`.\n * Never stored, never client-asserted — a risk with no named accountable owner is\n * retained `incomplete`, never ready.\n */\nexport type PmReadiness = 'ready' | 'incomplete' | 'n/a';\n\n/**\n * One append-only revision in the shared record envelope (PJM-IP02). Human values\n * are authoritative; extracted values are visibly `provisional`. The envelope is\n * never overwritten — a correction supersedes, and the prior revision is retained.\n */\nexport interface PmRevision {\n id: string;\n recordId: string;\n revision: number;\n /** Family-specific detail; opaque JSON to the client. */\n payload: unknown;\n origin: PmOrigin;\n confidence?: number | null;\n asOf?: string | null;\n accountableContactId?: string | null;\n /** Registry status; a non-active owner never counts as viable/ready. */\n accountableContactStatus?: 'active' | 'merged' | 'erased' | null;\n accountableState: PmAccountableState;\n workState?: PmWorkState | null;\n dueAt?: string | null;\n note?: string | null;\n /** Server-derived authoring principal; never a client field. */\n authoredBy: string;\n authoredAt: string;\n supersedesRevisionId?: string | null;\n /** Null/absent means this revision is the current one. */\n supersededByRevisionId?: string | null;\n // Derived, never stored (server-computed, read-only).\n family: PmRecordFamily;\n provisional: boolean;\n readiness: PmReadiness;\n}\n\n/** A logical project-memory record with its current revision resolved. */\nexport interface PmRecord {\n id: string;\n projectId: string;\n family: PmRecordFamily;\n /** Catalog policy; optional only for rolling compatibility with an older server. */\n requiresAccountableOwner?: boolean;\n /** Catalog policy; future subject-bearing families do not need a client enum change. */\n requiresSubjectContact?: boolean;\n /** Canonical registry identity for subject-bearing records (not copied PII). */\n subjectContactId?: string | null;\n subjectContactStatus?: 'active' | 'merged' | 'erased' | null;\n createdBy: string;\n createdAt: string;\n /** The current (non-superseded) revision. Present by construction. */\n current?: PmRevision;\n}\n\n/**\n * The write envelope for a new revision — the `first` revision of a created\n * record, or an appended/superseding one. `authoredBy`, `authoredAt` and\n * `revision` are SERVER-derived and must not be sent. This user-facing client\n * reaches the direct member route, so provenance is always human and derived by\n * the server. Extracted proposals require a separate governed internal surface.\n */\nexport interface PmRevisionInput {\n /** Direct member writes are server-derived human provenance. */\n origin?: 'human';\n /** Family-specific detail; defaults to `{}` server-side when omitted. */\n payload?: unknown;\n asOf?: string;\n accountableContactId?: string;\n accountableState?: PmAccountableState;\n workState?: PmWorkState;\n dueAt?: string;\n note?: string;\n}\n\n/** Create a record with its first revision in one POST (record-and-first-revision). */\nexport interface PmCreateRecordRequest {\n family: PmRecordFamily;\n /** Required by the backend for stakeholder records. */\n subjectContactId?: string;\n first: PmRevisionInput;\n}\n\n/**\n * Append/supersede the current revision. `expectedCurrentRevisionId` is the\n * required optimistic-concurrency handle: pass the revision id you read, and a\n * concurrent write is refused with a 409 carrying the new current revision (see\n * {@link PmRevisionConflict}) rather than silently overwriting. There is no\n * unconditional supersede path.\n */\nexport type PmAppendRevisionRequest = PmRevisionInput & {\n expectedCurrentRevisionId: string;\n};\n\n/** `{ success, record }` envelope for create/get/append. */\nexport interface PmRecordResponse {\n success: boolean;\n record: PmRecord;\n}\n\n/** `{ success, records }` envelope for list. `records` is `null` when empty. */\nexport interface PmRecordsResponse {\n success: boolean;\n records: PmRecord[] | null;\n}\n\n/** `{ success, revisions }` envelope for history. `revisions` is `null` when empty. */\nexport interface PmRevisionsResponse {\n success: boolean;\n revisions: PmRevision[] | null;\n}\n\n/**\n * The 409 body an append returns when `expectedCurrentRevisionId` is stale. It\n * carries the CURRENT revision so the caller can reconcile and retry — nothing\n * was written. On the wire this arrives as the thrown `HttpError.body`.\n */\nexport interface PmRevisionConflict {\n success: false;\n message: string;\n current: PmRevision;\n}\n\n// ── Customer documents (PJM-IP03 / IMP-PJ-DOC-CORE) ──────────────────────────\n//\n// Documents enter the project as immutable artifact-substrate versions of kind\n// `pm.customer-document`, carrying provenance (uploader, uploaded-at, declared\n// source), an authority-to-share attestation, and a governed deletion\n// disposition. The BYTES are the substrate's job — stored ENCRYPTED for a\n// confidential/restricted class and REFUSED (never plaintext) when the\n// deployment's encryption posture is unavailable (A-11); this client wraps only\n// the member-scoped metadata surface. Deletion is a GOVERNED disposition, not a\n// request-triggered act: there is deliberately NO delete / execute method here,\n// because execution is non-expressible until the shared governed-disposition\n// contract (F-PJM-047) lands.\n\n/** Derived authority-to-share state of a document. Never a mutable flag. */\nexport type PmAttestationState = 'attested' | 'missing';\n\n/** Attestation lifecycle event types (append-only, ask-once, attest-once). */\nexport type PmAttestationEventType = 'gap' | 'ask' | 'attest';\n\n/** One append-only authority-to-share lifecycle event. */\nexport interface PmDocumentAttestationEvent {\n id: string;\n eventType: PmAttestationEventType;\n note?: string | null;\n authoredBy: string;\n authoredAt: string;\n}\n\n/**\n * A customer document's product-owned metadata. `attestationState` is DERIVED\n * (`attested` iff an attest event exists), never a settable field. `headVersionId`\n * is the exact, citable artifact version — grounding pins a claim to it.\n */\nexport interface PmCustomerDocument {\n id: string;\n projectId: string;\n orgId: string;\n artifactId: string;\n /** The exact current artifact version id — the citable version for grounding. */\n headVersionId: string;\n /** Lowercase SHA-256 of the immutable version's canonical plaintext bytes. */\n contentHash: string;\n classification: string;\n declaredSource?: string | null;\n title: string;\n uploadedBy: string;\n uploadedAt: string;\n createdAt: string;\n attestationState: PmAttestationState;\n /** Whether the single ask has already been recorded (ask-once). */\n askRecorded: boolean;\n attestation: PmDocumentAttestationEvent[];\n}\n\n/**\n * Upload request. `classification` is DECLARED — the substrate never defaults\n * one, and a confidential/restricted class routes through encrypted-or-refused\n * storage. `attested: true` records the intake attestation now; `false` (the\n * default) records the intake gap, asked exactly once later and never nagged.\n */\nexport interface PmDocumentUploadRequest {\n title: string;\n classification: string;\n /** Defaults to text server-side when omitted. */\n contentType?: string;\n content: string;\n declaredSource?: string;\n attested?: boolean;\n attestNote?: string;\n}\n\n/**\n * The upload result. `document` is the recorded metadata; `handle`/`version` are\n * the substrate's citable version handle. A confidential upload on a deployment\n * with no encryption posture does NOT reach here — it fails closed as a thrown\n * `HttpError` (422) whose body carries the substrate refusal, and no document is\n * recorded (nothing stored, nothing downgraded).\n */\nexport interface PmDocumentUploadResult {\n success: boolean;\n document: PmCustomerDocument;\n handle?: unknown;\n version?: unknown;\n}\n\n/** `{ success, documents }` list envelope. `documents` is `null` when empty. */\nexport interface PmDocumentsResponse {\n success: boolean;\n documents: PmCustomerDocument[] | null;\n}\n\n/** `{ success, document }` envelope for get/attest. */\nexport interface PmDocumentResponse {\n success: boolean;\n document: PmCustomerDocument;\n}\n\n/**\n * Records the single ask or the terminal attest — the only two events a caller\n * drives (the intake `gap` is system-recorded and cannot be driven here).\n * Ask-once and attest-once are structural: a repeat is refused (409), not nagged.\n */\nexport interface PmAttestationRequest {\n eventType: 'ask' | 'attest';\n note?: string;\n}\n\n// ── Governed disposition (deletion is a decision, not a click) ───────────────\n\n/**\n * Disposition request states. Deliberately NO `approved`/`executed`: an approve\n * decision settles to `held`, because deletion execution is non-expressible\n * until the shared governed-disposition contract (F-PJM-047) lands.\n */\nexport type PmDispositionState = 'requested' | 'under_review' | 'denied' | 'deferred' | 'held';\n\n/** A decision a resolved authority may record. `approved` settles to `held`. */\nexport type PmDispositionDecision = 'denied' | 'deferred' | 'approved';\n\n/** Who asked for disposition. Input to review, never deletion authority. */\nexport type PmDispositionRequesterParty =\n | 'customer'\n | 'counterparty'\n | 'data_subject'\n | 'project_manager'\n | 'administrator'\n | 'other';\n\n/** Resolved PJ-D039 authority kinds. */\nexport type PmAuthorityKind = 'explicit' | 'project_manager' | 'unresolved';\n\n/**\n * A durable deletion-disposition request. A request from any party is INPUT, not\n * authority. It never deletes: the terminal reachable state is `held`\n * (approved-in-principle, execution withheld) / `denied` / `deferred`, each\n * persisted with its reason and policy basis.\n */\nexport interface PmDispositionRequest {\n id: string;\n documentId: string;\n orgId: string;\n /** Server-derived immutable target; never trusted from the requester. */\n targetArtifactId: string;\n targetVersionId: string;\n targetContentHash: string;\n /** Who ASKED (customer, counterparty, data subject, PM, admin) — input only. */\n requesterParty: PmDispositionRequesterParty;\n recordedBy: string;\n requestReason?: string | null;\n state: PmDispositionState;\n resolvedAuthorityUserId?: string | null;\n authorityKind?: PmAuthorityKind | null;\n decision?: PmDispositionDecision | null;\n /** The authority's human rationale, retained separately from a held-state explanation. */\n decisionReason?: string | null;\n decidedBy?: string | null;\n decidedAt?: string | null;\n resolutionReason?: string | null;\n policyBasis?: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Records a deletion request. `requesterParty` is who asked (input, not authority). */\nexport interface PmDispositionRequestInput {\n requesterParty: PmDispositionRequesterParty;\n /** Optional stale-write assertion; the server always derives the actual target. */\n targetVersionId?: string;\n requestReason?: string;\n}\n\n/**\n * An authority's decision. `approved` cannot delete — it settles to `held` with\n * an honest hold statement; `denied`/`deferred` persist with the reason. The\n * store enforces that only the PJ-D039-resolved authority may decide.\n */\nexport interface PmDispositionDecisionInput {\n decision: PmDispositionDecision;\n reason: string;\n /** Required for every outcome; a missing policy basis fails closed. */\n policyBasis: string;\n}\n\n/** The resolved PJ-D039 disposition authority for a project. */\nexport interface PmDispositionAuthority {\n kind: PmAuthorityKind;\n /** Empty/absent when unresolved. */\n userId?: string;\n}\n\n/** `{ success, request }` envelope for create/review/decide. */\nexport interface PmDispositionResponse {\n success: boolean;\n request: PmDispositionRequest;\n}\n\n/** `{ success, requests }` list envelope. `requests` is `null` when empty. */\nexport interface PmDispositionsResponse {\n success: boolean;\n requests: PmDispositionRequest[] | null;\n}\n\n/** Sets the explicit disposition-authority designation. Empty clears it. */\nexport interface PmDispositionAuthorityInput {\n /** Empty string clears the designation (falling back to the current PM). */\n authorityUserId: string;\n}\n\n/** `{ success, resolvedAuthority }` envelope for the authority write. */\nexport interface PmDispositionAuthorityResponse {\n success: boolean;\n resolvedAuthority: PmDispositionAuthority;\n}\n\n// ── Status reports (PJM-IP04 / IMP-PJ-STATUS) ────────────────────────────────\n//\n// A member generates a versioned, evidence-linked status DRAFT from the\n// member-scoped project memory. Every claim carries its class; every material\n// number cites the recorded computation that produced it. The narrative is\n// stored as an immutable, versioned `pm.status-report` artifact (each generation\n// a new version diffed against the prior — never a regeneration over the old).\n\n/** A status claim's class: what is recorded, what is inferred, what is advised. */\nexport type PmClaimClass = 'fact' | 'interpretation' | 'recommendation';\n\n/** A coverage state under the five-state §8 law. `current` is unreachable in the\n * MVP++ core (no declared cadence is modelled — honestly capped at `partial`). */\nexport type PmReportCoverageState = 'n/a' | 'none' | 'thin' | 'partial' | 'current';\n\n/** A cited record revision behind a claim — a fact opens its record. */\nexport interface PmRecordRef {\n recordId: string;\n revision: number;\n family: string;\n}\n\n/** What a claim resolves to. `computations` are computation KEYS; resolve them\n * against the report's `computations` for the version being viewed. */\nexport interface PmClaimEvidence {\n records?: PmRecordRef[];\n /** Computation keys the numbers in this claim cite. */\n computations?: string[];\n documents?: string[];\n}\n\n/** One classed narrative segment. */\nexport interface PmStatusClaim {\n key: string;\n class: PmClaimClass;\n text: string;\n evidence: PmClaimEvidence;\n /** Set when a claim was held/limited by authority-to-share. */\n limitation?: string;\n /** True only for a marked, unconfirmed interpretation. */\n unconfirmed?: boolean;\n}\n\nexport interface PmPhaseInfo {\n name: string;\n evidence: PmRecordRef;\n}\nexport interface PmGateInfo {\n name: string;\n decision: string;\n evidence: PmRecordRef;\n}\n\n/** The current phase + latest applicable gate, honest when absent. */\nexport interface PmPhaseGate {\n /** Null when no phase is recorded — never invented. */\n phase: PmPhaseInfo | null;\n /** Null when no gate decision is recorded — never invented. */\n latestGate: PmGateInfo | null;\n statement: string;\n}\n\n/** One discipline's derived coverage — a computed value, not an editable field. */\nexport interface PmCoverageAreaReport {\n area: string;\n state: PmReportCoverageState;\n reason: string;\n computationKey: string;\n tailoredOut?: boolean;\n}\n\n/** The embedded, non-editable coverage statement. */\nexport interface PmStatusCoverage {\n areas: PmCoverageAreaReport[];\n statement: string;\n /** Recorded computation behind the aggregate numbers in `statement`. */\n summaryComputationKey: string;\n}\n\n/** A recorded structural refusal (e.g. a per-person ranking request). */\nexport interface PmStatusRefusal {\n request: string;\n rule: string;\n message: string;\n}\n\nexport interface PmStatusDiffChange {\n key: string;\n from: string;\n to: string;\n}\nexport interface PmStatusCoverageChange {\n area: string;\n from: string;\n to: string;\n}\n\n/** The useful diff a new version carries against the prior one. */\nexport interface PmStatusDiff {\n fromOrdinal: number;\n added: string[];\n removed: string[];\n changed: PmStatusDiffChange[];\n coverageChanges: PmStatusCoverageChange[];\n phaseGateChanged: boolean;\n summary: string;\n}\n\n/** The full status-report narrative stored in the immutable artifact version. */\nexport interface PmStatusNarrative {\n schema: string;\n projectId: string;\n generatedAt: string;\n phaseGate: PmPhaseGate;\n coverage: PmStatusCoverage;\n claims: PmStatusClaim[];\n exclusions: string[];\n gaps: string[];\n refusals?: PmStatusRefusal[];\n partial: boolean;\n /** Always true — the coverage statement cannot be edited away. */\n coverageLocked: boolean;\n /** Absent on the first version. */\n diff?: PmStatusDiff;\n}\n\n/** One recorded computation behind a number — the \"number opens its calculation\". */\nexport interface PmComputation {\n id: string;\n projectId: string;\n reportArtifactId: string;\n reportVersionId: string;\n computationKey: string;\n method: string;\n /** The exact inputs: the record revision ids read + the coverage denominator. */\n inputs: unknown;\n /** The derived result: the value plus its unit/label. */\n result: unknown;\n asOf: string;\n createdBy: string;\n createdAt: string;\n}\n\n/** The one logical status report per project, pointing at its substrate artifact. */\nexport interface PmStatusReportPointer {\n projectId: string;\n artifactId: string;\n headVersionId: string;\n latestOrdinal: number;\n createdBy: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/** A status-report artifact version's metadata (mirrors the substrate meta). */\nexport interface PmStatusVersion {\n id: string;\n artifactId: string;\n versionRef: string;\n ordinal: number;\n parentVersionId?: string;\n contentType: string;\n authoredBy: string;\n contentHash: string;\n changeNote?: string;\n createdAt: string;\n}\n\n/** A generated/read status report: the narrative, the version it is stored as,\n * and the computations a reader resolves numbers against. */\nexport interface PmStatusReport {\n pointer: PmStatusReportPointer | null;\n version: PmStatusVersion;\n narrative: PmStatusNarrative;\n computations: PmComputation[];\n}\n\n/** `{ success, report }` envelope for generate/get. */\nexport interface PmStatusReportResponse {\n success: boolean;\n report: PmStatusReport;\n}\n\n/** `{ success, pointer, versions }` envelope for the version list. `pointer` is\n * null and `versions` empty when no report has been generated. */\nexport interface PmStatusReportsResponse {\n success: boolean;\n pointer: PmStatusReportPointer | null;\n versions: PmStatusVersion[] | null;\n}\n\n/** `{ success, computation }` envelope for the computation click-through. */\nexport interface PmComputationResponse {\n success: boolean;\n computation: PmComputation;\n}\n\n/** Options for a status generation request. */\nexport interface PmGenerateStatusOptions {\n /** `'people'` requests a per-person ranking — the server refuses and records it. */\n focus?: 'people' | string;\n}\n\n// ── Status distribution — the attended-delivery preflight (PJM-IP05) ──\n//\n// The member-scoped, buildable-now product computation that PRECEDES a governed\n// distribution proposal: resolve recipients through the project stakeholder\n// register (refuse an outsider at proposal time) and re-run the authority-to-share\n// gate over the exact version. It queues and sends NOTHING — the durable proposal,\n// owner+PM approval binding, execution on the shared act rail and per-destination\n// receipts are the shared approvals surface (`ApprovalsClient` /\n// `DeliveryEvidenceLevel` / `ActDestinationReceipt`), reused rather than cloned.\n\n/** Refusal code for a recipient outside the project's stakeholder register. */\nexport const PM_RECIPIENT_NOT_REGISTERED = 'recipient-not-registered';\n\n/** One resolved recipient in the distribution plan. `registered:false` carries the\n * cited refusal (the typo'd outsider, refused at proposal time). */\nexport interface PmDistributionRecipient {\n contactId: string;\n registered: boolean;\n refusalCode?: string;\n refusalReason?: string;\n}\n\n/** A fact claim the authority-to-share re-check held out of the distributable\n * version (its document grounding is no longer attested shareable). */\nexport interface PmHeldClaim {\n key: string;\n class: string;\n limitation: string;\n}\n\n/** The version's re-checked authority-to-share posture. When `cleared` is false the\n * held claims must be re-generated or disclosed before the version can be sent. */\nexport interface PmAuthorityToShare {\n cleared: boolean;\n reason?: string;\n heldClaims?: PmHeldClaim[];\n}\n\n/** The honest execution/configuration posture. `ready:false` with a bounded reason\n * is the \"delivery not yet configured\" setup state the console surfaces. */\nexport interface PmDeliveryReadiness {\n ready: boolean;\n reason?: string;\n}\n\n/** The reviewable distribution plan a member inspects before approving a send. */\nexport interface PmDistributionPlan {\n projectId: string;\n versionId: string;\n versionRef: string;\n artifactId: string;\n /** Fully qualified immutable artifact/version/digest handle frozen by approval. */\n artifactRef: string;\n recipients: PmDistributionRecipient[];\n authorityToShare: PmAuthorityToShare;\n delivery: PmDeliveryReadiness;\n}\n\n/** `{ success, plan }` envelope for the distribution preflight. */\nexport interface PmDistributionPlanResponse {\n success: boolean;\n plan: PmDistributionPlan;\n}\n\n/** Durable shared-rail proposal created after the server repeats preflight. */\nexport interface PmDistributionProposal {\n status: 'queued_for_approval' | 'already_executed' | string;\n pendingActionId: string;\n}\n\nexport interface PmDistributionProposalResponse {\n success: boolean;\n proposal: PmDistributionProposal;\n}\n\n// ClowdPM attended assistance (IMP-PJ-ASSIST) — drift/sweep findings, coverage\n// and the shared signals a member reviews, dismisses or consumes.\n\n/** A single record/revision the finding cites as its evidence. */\nexport interface PmAssistEvidenceRef {\n recordId: string;\n revisionId?: string;\n family: string;\n detail?: string;\n}\n\n/** One drift or risk-candidate finding about a subject record. */\nexport interface PmAssistFinding {\n kind: string;\n subjectRecordId: string;\n family: string;\n discipline: string;\n summary: string;\n evidence: PmAssistEvidenceRef[];\n accountableContactId?: string;\n ownerErased?: boolean;\n}\n\n/** Coverage state for one discipline. */\nexport interface PmAssistCoverage {\n discipline: string;\n state: 'n/a' | 'none' | 'thin' | 'partial' | 'current';\n reason: string;\n}\n\n/** A thin mirror of the shared signal a member reviews on the assist surface. */\nexport interface PmSignal {\n id: string;\n kind: string;\n title: string;\n summary: string;\n priority: string;\n sightingCount: number;\n scopeLevel: string;\n scopeRef?: string;\n status: string;\n dismissalRationale?: string;\n}\n\n/** The read-only drift assist result. */\nexport interface PmAssistDriftResult {\n drift: PmAssistFinding[];\n coverage: PmAssistCoverage[];\n}\n\n/** The sweep result, which also raises durable signals. */\nexport interface PmAssistSweepResult {\n drift: PmAssistFinding[];\n riskCandidates: PmAssistFinding[];\n coverage: PmAssistCoverage[];\n raised: number;\n signals: PmSignal[];\n}\n\n/** `{ success, drift, coverage }` envelope for the drift assist. */\nexport interface PmAssistDriftResponse {\n success: boolean;\n drift: PmAssistFinding[];\n coverage: PmAssistCoverage[];\n}\n\n/** `{ success, drift, riskCandidates, coverage, raised, signals }` sweep envelope. */\nexport interface PmAssistSweepResponse {\n success: boolean;\n drift: PmAssistFinding[];\n riskCandidates: PmAssistFinding[];\n coverage: PmAssistCoverage[];\n raised: number;\n signals: PmSignal[];\n}\n\n/** `{ success, signal }` envelope for a signal dismiss/consume. */\nexport interface PmSignalResponse {\n success: boolean;\n signal: PmSignal;\n}\n\n// ── Risk register with teeth (PJM-S03 / PJM-IP08) ────────────────────────────\n//\n// The durable S03 journey over the EXISTING primitives (COR-PJ-S03-CORE): a\n// told/derived risk becomes a CONFIRMED, human-authored `risk`-family record; the\n// named accountable owner explicitly accepts or declines (and only that owner\n// may); acceptance appends an immutable `pm.risk-register` artifact version; the\n// approved response is recorded as an OWNED `action`-family commitment linked to\n// the entry; and owner notification originates a trusted proposal on the EXISTING\n// `pm.notify.stakeholder` shared act rail. Delivery is NEVER asserted here — the\n// owner is queued, and \"notified\" is proven only by the shared-rail receipt read\n// on the approvals/activity surface. Confirmed risk + register version + response\n// survive any ownership decline or notification failure.\n//\n// The risk itself is a `PmRecord` (family `risk`); the response is a `PmRecord`\n// (family `action`). Only the request/notification shapes are risk-specific.\n\n/** The named owner's explicit decision on a proposed-owner risk. */\nexport type PmRiskDecision = 'accepted' | 'declined';\n\n/** The four typed response outcomes, including deliberate acceptance-with-rationale. */\nexport type PmRiskResponseType = 'mitigate' | 'transfer' | 'escalate' | 'accept';\n\n/** Grounds one confirmed field in its source so the register never presents an\n * inference as a fact — the chat moment or a recorded schedule/milestone record. */\nexport interface PmRiskCitation {\n field?: string;\n /** `chat` | `pm-record` | `pm-computation`. */\n kind: string;\n ref: string;\n}\n\n/**\n * Confirm a told/derived risk. The caller (a member with WRITE) is the confirming\n * human, so the entry is authored `human` — a derived candidate's citation is\n * preserved but never promoted on its own. A named `ownerContactId` is PROPOSED\n * (not assigned) and must resolve to a registered stakeholder of this project. A\n * told risk that duplicates an active entry's condition is refused (409) so the\n * caller updates the existing entry rather than forking a second one.\n */\nexport interface PmRiskConfirmRequest {\n condition: string;\n consequence?: string;\n /** Opaque JSON on the project's declared probability/impact scale. */\n assessment?: unknown;\n /** Proposed accountable owner — a registered stakeholder contact id. */\n ownerContactId?: string;\n citations?: PmRiskCitation[];\n /** Provenance pointer to the derived candidate this confirms, when any. */\n candidateRef?: string;\n}\n\n/**\n * The named owner's explicit accept/decline. The decision is the OWNER's alone:\n * the server refuses a generic member — even a manager — with `decision-not-by-owner`\n * (403). `expectedCurrentRevisionId` is the optimistic-concurrency handle; a stale\n * value is refused (409) rather than silently overwriting. Acceptance appends the\n * immutable register version; a decline leaves the risk confirmed-but-unowned.\n */\nexport interface PmRiskOwnershipRequest {\n decision: PmRiskDecision;\n expectedCurrentRevisionId: string;\n}\n\n/**\n * PROPOSE the typed response for the owner+PM decision (PJM-IP08 §7.10). This does\n * NOT create the owned commitment — that is materialized only when the decision\n * completes (see decidePMRiskResponse). A generic member may propose (member-write),\n * but the acceptance is the project owner+PM's alone. `dueAt` is MANDATORY: a\n * response is owner + due, or it is nothing. It requires an accepted, named, active\n * owner (else 422) and optimistic concurrency via `expectedCurrentRevisionId` (409).\n * Re-proposing the same response is idempotent; a changed response while one is live\n * conflicts (409).\n */\nexport interface PmRiskResponseRequest {\n type: PmRiskResponseType;\n description: string;\n /** REQUIRED ISO-8601 target date for the owned commitment (owner + due). */\n dueAt: string;\n expectedCurrentRevisionId: string;\n}\n\n/** The honest state of a proposed response awaiting / carrying the owner+PM decision. */\nexport type PmRiskResponseState = 'proposed' | 'accepted' | 'rejected';\n\n/**\n * A response proposal bound to the exact risk revision and register version, carrying\n * its decision state. It never exposes the resolved owner/PM identities.\n */\nexport interface PmRiskResponseProposal {\n id: string;\n riskRecordId: string;\n riskRevisionId: string;\n registerVersionRef: string;\n ownerContactId: string;\n responseType: PmRiskResponseType;\n description: string;\n dueAt?: string | null;\n /** True when the project owner and PM are distinct people (two approvals needed). */\n requiresTwo: boolean;\n state: PmRiskResponseState;\n}\n\n/**\n * The owner's or PM's decision on a proposed response (PJ-D028 owner+PM path). A\n * generic member is refused (403). Only a completing acceptance materializes the\n * owned commitment; a rejection keeps the risk confirmed, response pending.\n */\nexport interface PmRiskResponseDecisionRequest {\n proposalId: string;\n decision: 'accept' | 'reject';\n}\n\n/** The register version handle returned when an accept/response appends a version. */\nexport interface PmRiskOwnershipResult {\n risk: PmRecord;\n registerVersionRef?: string;\n}\n\n/** The result of PROPOSING a response: the risk and the pending proposal. */\nexport interface PmRiskResponseResult {\n risk: PmRecord;\n responseProposal: PmRiskResponseProposal;\n registerVersionRef?: string;\n}\n\n/** The result of a response DECISION. `status` mirrors the honest server state. */\nexport interface PmRiskResponseDecisionResult {\n risk: PmRecord;\n status: 'accepted' | 'pending' | 'rejected';\n /** The materialized owned `action`-family commitment — present only on acceptance. */\n response?: PmRecord;\n responseRecordId?: string;\n registerVersionRef?: string;\n note?: string;\n}\n\n/** `{ success, risk }` envelope for confirm. */\nexport interface PmRiskConfirmResponse {\n success: boolean;\n risk: PmRecord;\n}\n\n/** `{ success, risk, registerVersionRef }` envelope for the ownership decision. */\nexport interface PmRiskOwnershipResponse {\n success: boolean;\n risk: PmRecord;\n registerVersionRef?: string;\n}\n\n/** `{ success, risk, responseProposal, registerVersionRef }` envelope for a propose. */\nexport interface PmRiskResponseResponse {\n success: boolean;\n risk: PmRecord;\n responseProposal: PmRiskResponseProposal;\n registerVersionRef?: string;\n}\n\n/** `{ success, risk, status, response?, ... }` envelope for a response decision. */\nexport interface PmRiskResponseDecisionResponse {\n success: boolean;\n risk: PmRecord;\n status: 'accepted' | 'pending' | 'rejected';\n response?: PmRecord;\n responseRecordId?: string;\n registerVersionRef?: string;\n note?: string;\n}\n\n/** The queued shared-rail proposal — the owner is queued, NEVER yet notified. */\nexport interface PmRiskNotificationProposal {\n status: 'queued_for_approval' | string;\n pendingActionId: string;\n}\n\n/**\n * The notify result. `note` carries the honest \"owner not yet notified\" statement:\n * the notification is queued for owner+PM approval and delivery is proven only by a\n * shared-rail receipt — never by the presence of this proposal.\n */\nexport interface PmRiskNotifyResult {\n proposal: PmRiskNotificationProposal;\n note?: string;\n}\n\n/** `{ success, proposal, note }` envelope for the notify origination (201/200). */\nexport interface PmRiskNotifyResponse {\n success: boolean;\n proposal: PmRiskNotificationProposal;\n note?: string;\n}\n","import {\n isProductKind,\n type PreferredAiProvider,\n type ProductKind,\n type Project,\n} from '../modules/projects/types.js';\n\ninterface WireProject {\n id: string;\n name: string;\n orgId: string;\n default?: boolean;\n isReferenceProject?: boolean;\n preferredAiProvider?: string | null;\n product?: string;\n users?: unknown[];\n}\n\nexport const projectAdapter = {\n fromListResponse(payload: unknown): Project[] {\n const list = (payload as { workspaces?: WireProject[]; projects?: WireProject[] } | null)?.workspaces\n ?? (payload as { projects?: WireProject[] } | null)?.projects\n ?? [];\n // A mixed-version backend may know a product this client does not. Keep the\n // rest of the list usable, but do not misrepresent that row as a supported\n // ProductKind or silently coerce it to Cloud.\n return list.filter((wire) => wire.product == null || isProductKind(wire.product)).map(normalize);\n },\n\n fromGetResponse(payload: unknown): Project {\n const wire = (payload as { workspace?: WireProject; project?: WireProject; data?: WireProject } | null);\n const value = wire?.workspace ?? wire?.project ?? wire?.data;\n if (!value) throw new Error('Project response missing body.');\n return normalize(value);\n },\n\n normalize,\n};\n\nfunction normalize(wire: WireProject): Project {\n const product = normalizeProduct(wire.product);\n return {\n id: wire.id,\n name: wire.name,\n orgId: wire.orgId,\n default: wire.default ?? false,\n isReferenceProject: wire.isReferenceProject ?? false,\n preferredAiProvider: (wire.preferredAiProvider ?? null) as PreferredAiProvider | null,\n product,\n users: (wire.users ?? []) as Project['users'],\n };\n}\n\nfunction normalizeProduct(raw: string | undefined): ProductKind {\n // Missing is the legacy pre-partition wire shape and remains Cloud. An\n // explicit empty/unknown value is not the legacy absence and must fail closed.\n if (raw == null) return 'cloud';\n if (isProductKind(raw)) return raw;\n throw new Error(`Unsupported project product ${JSON.stringify(raw)}.`);\n}\n\n// TODO(backend-cleanup): cloud-agent-backend internal/http/routes/project/project.go\n// still returns `workspaces` / `workspace` keys. When those are renamed to\n// `projects` / `project`, this adapter can fall through to a plain unwrap.\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { projectAdapter } from '../../adapters/projectAdapter.js';\nimport type {\n AddMemberRequest,\n CreateProjectRequest,\n PmAppendRevisionRequest,\n PmAssistDriftResponse,\n PmAssistDriftResult,\n PmAssistSweepResponse,\n PmAssistSweepResult,\n PmSignal,\n PmSignalResponse,\n PmAttestationRequest,\n PmComputation,\n PmComputationResponse,\n PmCreateRecordRequest,\n PmCustomerDocument,\n PmDistributionPlan,\n PmDistributionPlanResponse,\n PmDistributionProposal,\n PmDistributionProposalResponse,\n PmGenerateStatusOptions,\n PmStatusReport,\n PmStatusReportPointer,\n PmStatusReportResponse,\n PmStatusReportsResponse,\n PmStatusVersion,\n PmDispositionAuthority,\n PmDispositionAuthorityInput,\n PmDispositionAuthorityResponse,\n PmDispositionDecisionInput,\n PmDispositionRequest,\n PmDispositionRequestInput,\n PmDispositionResponse,\n PmDispositionsResponse,\n PmDocumentResponse,\n PmDocumentsResponse,\n PmDocumentUploadRequest,\n PmDocumentUploadResult,\n PmGrantMemberRequest,\n PmGrantMemberResponse,\n PmRecord,\n PmRecordFamily,\n PmRecordResponse,\n PmRecordsResponse,\n PmRecoverManagementRequest,\n PmRecoverManagementResponse,\n PmRevision,\n PmRevisionsResponse,\n PmRevokeMemberResponse,\n PmRiskConfirmRequest,\n PmRiskConfirmResponse,\n PmRiskNotifyResponse,\n PmRiskNotifyResult,\n PmRiskOwnershipRequest,\n PmRiskOwnershipResponse,\n PmRiskOwnershipResult,\n PmRiskResponseDecisionRequest,\n PmRiskResponseDecisionResponse,\n PmRiskResponseDecisionResult,\n PmRiskResponseRequest,\n PmRiskResponseResponse,\n PmRiskResponseResult,\n ProductKind,\n Project,\n UpdateMemberRoleRequest,\n UpdateProjectRequest,\n} from './types.js';\n\ninterface SimpleResponse {\n success: boolean;\n message?: string;\n}\n\nfunction directHumanRevisionError(input: unknown): Error | undefined {\n const wire = input as { origin?: unknown; confidence?: unknown };\n if (wire.origin !== undefined && wire.origin !== 'human') {\n return new Error('Direct project-memory writes are human-authored.');\n }\n if (wire.confidence !== undefined && wire.confidence !== null) {\n return new Error('A direct human-authored project-memory write cannot assert confidence.');\n }\n return undefined;\n}\n\nexport class ProjectsClient {\n constructor(private readonly http: BaseClient) {}\n\n /**\n * Lists the caller's projects in one product partition. Omitting `product`\n * defaults to 'cloud' server-side (the cloud UI). The BI frontend passes\n * 'bi' so it only ever sees data projects.\n */\n async list(product?: ProductKind): Promise<Project[]> {\n const path = product ? `/project?product=${encodeURIComponent(product)}` : '/project';\n const res = await this.http.get<unknown>(path);\n return projectAdapter.fromListResponse(res);\n }\n\n async get(projectId: string): Promise<Project> {\n const res = await this.http.get<unknown>(`/project/${projectId}`);\n return projectAdapter.fromGetResponse(res);\n }\n\n /**\n * Creates a project and returns it. For ClowdPM (`product: 'pm'`) pass a\n * stable `requestKey` (minted with `newProjectRequestKey`) and resend the SAME\n * value on retry: the\n * server drives a durable creation state machine keyed on it, so a retried\n * POST converges on the one already-created project rather than a duplicate.\n * The key is required by the type and checked again at runtime, then forwarded\n * verbatim — this method never mints or rewrites it, and never mints the\n * project identity (always server-derived).\n */\n async create(body: CreateProjectRequest): Promise<Project> {\n if (body.product === 'pm' && (typeof body.requestKey !== 'string' || body.requestKey.trim().length === 0)) {\n throw new Error('ClowdPM project creation requires a non-blank requestKey.');\n }\n const res = await this.http.post<unknown>('/project', { body });\n return projectAdapter.fromGetResponse(res);\n }\n\n async update(projectId: string, body: UpdateProjectRequest): Promise<Project> {\n const res = await this.http.put<unknown>(`/project/${projectId}`, { body });\n return projectAdapter.fromGetResponse(res);\n }\n\n delete(projectId: string): Promise<SimpleResponse> {\n return this.http.delete<SimpleResponse>(`/project/${projectId}`);\n }\n\n addMember(projectId: string, body: AddMemberRequest): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>(`/project/${projectId}/users`, { body });\n }\n\n updateMemberRole(projectId: string, userId: string, body: UpdateMemberRoleRequest): Promise<SimpleResponse> {\n return this.http.put<SimpleResponse>(`/project/${projectId}/users/${userId}`, { body });\n }\n\n removeMember(projectId: string, userId: string): Promise<SimpleResponse> {\n return this.http.delete<SimpleResponse>(`/project/${projectId}/users/${userId}`);\n }\n\n /**\n * Grants a ClowdPM (`pm`) project role through the governed\n * `pm.membership.change` act (PJM-IP01 §7.1). Distinct from the legacy\n * `addMember`, which the backend refuses for a pm project: this moves the\n * `pm_project_member` role record and the workspace floor together. The caller\n * must be an active project MANAGER; a non-member — including a non-member\n * organization administrator — is refused server-side. The role is a `PmRole`\n * (`manager | member | reader`), never an `AccessType`. This method asserts no\n * authority and mints no identity; it forwards the exact tuple.\n */\n grantPMMember(projectId: string, body: PmGrantMemberRequest): Promise<PmGrantMemberResponse> {\n return this.http.post<PmGrantMemberResponse>(`/project/${projectId}/pm-membership`, {\n body: { userId: body.userId, action: 'grant', role: body.role },\n });\n }\n\n /**\n * Revokes a principal's ClowdPM project membership (the governed\n * `pm.membership.change` act, revoke direction). Value-idempotent: revoking a\n * principal who is already revoked or was never a member returns\n * `{ revoked: false }`, a recorded success rather than an error.\n */\n revokePMMember(projectId: string, userId: string): Promise<PmRevokeMemberResponse> {\n return this.http.post<PmRevokeMemberResponse>(`/project/${projectId}/pm-membership`, {\n body: { userId, action: 'revoke' },\n });\n }\n\n /**\n * Runs last-manager recovery (PJM-IP01 §7.4 / `pm.recover-management`): an\n * organization administrator appoints a named replacement manager for a project\n * with NO active manager, recording the reason. It grants the invoking\n * administrator no ordinary project read. Refused (409) while a manager still\n * exists — the governed grant/revoke is the tool then.\n */\n recoverPMManagement(\n projectId: string,\n body: PmRecoverManagementRequest,\n ): Promise<PmRecoverManagementResponse> {\n return this.http.post<PmRecoverManagementResponse>(`/project/${projectId}/pm-recover-management`, {\n body,\n });\n }\n\n /**\n * Lists a project's ClowdPM memory records (PJM-IP02), optionally filtered to\n * one `family`. Each record carries its resolved current revision. Read is\n * member-scoped server-side (the central predicate `M`): a non-member —\n * including a non-member organization administrator — gets a bounded 404, not\n * a leaked list. An empty result is a real \"no records yet\" state, normalized\n * to `[]` (the wire sends a nil slice as `null`).\n */\n listPMRecords(projectId: string, family?: PmRecordFamily): Promise<PmRecord[]> {\n const path = family\n ? `/project/${projectId}/pm/records?family=${encodeURIComponent(family)}`\n : `/project/${projectId}/pm/records`;\n return this.http.get<PmRecordsResponse>(path).then((res) => res.records ?? []);\n }\n\n /**\n * Creates a project-memory record with its first revision in one POST. The\n * caller (an active member with WRITE) supplies the `family` and the `first`\n * revision envelope; the server derives authorship (`authoredBy`) and the\n * revision number and human provenance. Extracted proposals use a distinct\n * governed internal surface and cannot be forged through this member route.\n * Returns the created record with its current revision.\n */\n createPMRecord(projectId: string, body: PmCreateRecordRequest): Promise<PmRecord> {\n const invalid = directHumanRevisionError(body.first);\n if (invalid) return Promise.reject(invalid);\n return this.http\n .post<PmRecordResponse>(`/project/${projectId}/pm/records`, { body })\n .then((res) => res.record);\n }\n\n /** Gets one project-memory record with its current revision (member-scoped). */\n getPMRecord(projectId: string, recordId: string): Promise<PmRecord> {\n return this.http\n .get<PmRecordResponse>(`/project/${projectId}/pm/records/${recordId}`)\n .then((res) => res.record);\n }\n\n /**\n * Appends a revision that supersedes the record's current one — the edit path.\n * Nothing is overwritten; the prior revision is retained as history. Pass\n * `expectedCurrentRevisionId` (the revision id you read) for optimistic\n * concurrency: if it is stale, the server writes nothing and returns a 409 —\n * surfaced here as a thrown `HttpError` whose `body` is a `PmRevisionConflict`\n * carrying the new current revision to reconcile against. Returns the record\n * with its new current revision on success.\n */\n appendPMRevision(\n projectId: string,\n recordId: string,\n body: PmAppendRevisionRequest,\n ): Promise<PmRecord> {\n if (!body.expectedCurrentRevisionId?.trim()) {\n return Promise.reject(new Error('expectedCurrentRevisionId is required to prevent a stale overwrite.'));\n }\n const invalid = directHumanRevisionError(body);\n if (invalid) return Promise.reject(invalid);\n return this.http\n .post<PmRecordResponse>(`/project/${projectId}/pm/records/${recordId}/revisions`, { body })\n .then((res) => res.record);\n }\n\n /**\n * Lists a record's full append-only revision history, oldest first — the\n * provenance/supersession trail. Member-scoped; normalized to `[]` when empty.\n */\n listPMRevisions(projectId: string, recordId: string): Promise<PmRevision[]> {\n return this.http\n .get<PmRevisionsResponse>(`/project/${projectId}/pm/records/${recordId}/revisions`)\n .then((res) => res.revisions ?? []);\n }\n\n // ── Customer documents (PJM-IP03) ──────────────────────────────────────────\n\n /**\n * Uploads a customer document (immutable v1) and records its provenance +\n * intake attestation. Requires an active member with WRITE. `classification`\n * is DECLARED; a confidential/restricted class routes through the substrate's\n * encrypted-or-refused storage. When the deployment has no encryption posture,\n * a confidential upload FAILS CLOSED as a thrown `HttpError` (422) whose body\n * carries the substrate refusal — nothing is stored and nothing is downgraded\n * to plaintext. When the substrate capability is absent the upload fails closed\n * (503). This client mints no identity and stores no plaintext fallback.\n */\n uploadPMDocument(projectId: string, body: PmDocumentUploadRequest): Promise<PmDocumentUploadResult> {\n return this.http.post<PmDocumentUploadResult>(`/project/${projectId}/pm/documents`, { body });\n }\n\n /**\n * Lists a project's customer documents with derived attestation state.\n * Member-scoped server-side (the central predicate `M`): a non-member —\n * including a non-member organization administrator — gets a bounded 404, not\n * a leaked list. `documents` is normalized to `[]` when empty.\n */\n listPMDocuments(projectId: string): Promise<PmCustomerDocument[]> {\n return this.http\n .get<PmDocumentsResponse>(`/project/${projectId}/pm/documents`)\n .then((res) => res.documents ?? []);\n }\n\n /** Gets one document with its full append-only attestation history (member-scoped). */\n getPMDocument(projectId: string, documentId: string): Promise<PmCustomerDocument> {\n return this.http\n .get<PmDocumentResponse>(`/project/${projectId}/pm/documents/${documentId}`)\n .then((res) => res.document);\n }\n\n /**\n * Appends an authority-to-share attestation event — the single `ask` or the\n * terminal `attest`. Append-only: ask-once and attest-once are structural, so a\n * repeat is refused (409), never nagged or double-attested. The intake `gap` is\n * system-recorded and cannot be driven here. Requires a member with WRITE.\n */\n recordPMDocumentAttestation(\n projectId: string,\n documentId: string,\n body: PmAttestationRequest,\n ): Promise<PmCustomerDocument> {\n return this.http\n .post<PmDocumentResponse>(`/project/${projectId}/pm/documents/${documentId}/attestation`, { body })\n .then((res) => res.document);\n }\n\n // ── Governed disposition (deletion is a decision, not a click) ─────────────\n\n /**\n * Files a deletion-disposition request against a document — INPUT, not\n * authority. Any active member may file one (a request never deletes on its\n * own). It lands in `requested` and is routed through review by the resolved\n * PJ-D039 authority. There is deliberately NO method that deletes a document or\n * executes a disposition on this client: execution is non-expressible until the\n * shared governed-disposition contract (F-PJM-047) lands.\n */\n requestPMDocumentDisposition(\n projectId: string,\n documentId: string,\n body: PmDispositionRequestInput,\n ): Promise<PmDispositionRequest> {\n return this.http\n .post<PmDispositionResponse>(`/project/${projectId}/pm/documents/${documentId}/disposition-requests`, { body })\n .then((res) => res.request);\n }\n\n /** Lists a project's disposition requests (member-scoped; normalized to `[]`). */\n listPMDispositionRequests(projectId: string): Promise<PmDispositionRequest[]> {\n return this.http\n .get<PmDispositionsResponse>(`/project/${projectId}/pm/disposition-requests`)\n .then((res) => res.requests ?? []);\n }\n\n /**\n * Moves a request to `under_review`, resolving the PJ-D039 authority (or to the\n * fail-closed `held` state when no authority resolves). Requires a project\n * MANAGER to initiate review.\n */\n reviewPMDispositionRequest(projectId: string, requestId: string): Promise<PmDispositionRequest> {\n return this.http\n .post<PmDispositionResponse>(`/project/${projectId}/pm/disposition-requests/${requestId}/review`, { body: {} })\n .then((res) => res.request);\n }\n\n /**\n * Records the resolved authority's decision. `denied`/`deferred` persist with\n * the reason and policy basis; `approved` CANNOT delete — it settles to `held`\n * with an honest hold statement (the shared execution contract has not landed).\n * The server rejects a caller who is not the PJ-D039-resolved authority (403).\n */\n decidePMDispositionRequest(\n projectId: string,\n requestId: string,\n body: PmDispositionDecisionInput,\n ): Promise<PmDispositionRequest> {\n return this.http\n .post<PmDispositionResponse>(`/project/${projectId}/pm/disposition-requests/${requestId}/decision`, { body })\n .then((res) => res.request);\n }\n\n /**\n * Sets (or clears) the explicit PJ-D039 disposition-authority designation and\n * returns the newly resolved authority. An empty `authorityUserId` clears the\n * designation, falling back to the current PM at resolve time. Requires a\n * project MANAGER.\n */\n setPMDispositionAuthority(\n projectId: string,\n body: PmDispositionAuthorityInput,\n ): Promise<PmDispositionAuthority> {\n return this.http\n .put<PmDispositionAuthorityResponse>(`/project/${projectId}/pm/disposition-authority`, { body })\n .then((res) => res.resolvedAuthority);\n }\n\n // ── Status reports (PJM-IP04) ──────────────────────────────────────────────\n\n /**\n * Generates a status DRAFT from the project's member-scoped memory (PJM-IP04).\n * Every claim carries its class; every material number cites its recorded\n * computation. The draft is stored as a NEW immutable `pm.status-report`\n * artifact version — never a regeneration over the prior — and the returned\n * narrative embeds a diff against the previous version when one exists.\n * Requires an active member with WRITE. Passing `focus: 'people'` requests a\n * per-person ranking; the server refuses it and records the refusal (this\n * product reports items and blocked chains, not per-person scoreboards). When\n * the artifact substrate is absent this fails closed as a thrown 503.\n */\n generatePMStatusReport(projectId: string, opts?: PmGenerateStatusOptions): Promise<PmStatusReport> {\n const focus = opts?.focus?.trim();\n const path = focus\n ? `/project/${projectId}/pm/status-reports?focus=${encodeURIComponent(focus)}`\n : `/project/${projectId}/pm/status-reports`;\n return this.http.post<PmStatusReportResponse>(path, { body: {} }).then((res) => res.report);\n }\n\n /**\n * Lists a project's status-report versions (oldest first) with the report\n * pointer. Member-scoped server-side (the central predicate `M`): a non-member\n * — including a non-member organization administrator — gets a bounded 404.\n * `pointer` is null and `versions` empty when no report has been generated.\n */\n listPMStatusReports(\n projectId: string,\n ): Promise<{ pointer: PmStatusReportPointer | null; versions: PmStatusVersion[] }> {\n return this.http\n .get<PmStatusReportsResponse>(`/project/${projectId}/pm/status-reports`)\n .then((res) => ({ pointer: res.pointer ?? null, versions: res.versions ?? [] }));\n }\n\n /**\n * Reads one status-report version: its narrative (claims, coverage, phase/gate,\n * diff) and the computations a reader resolves its numbers against. A prior\n * version stays readable after a newer one is generated (versions are\n * immutable). Member-scoped; a non-member gets a bounded 404.\n */\n getPMStatusReport(projectId: string, versionId: string): Promise<PmStatusReport> {\n return this.http\n .get<PmStatusReportResponse>(`/project/${projectId}/pm/status-reports/${versionId}`)\n .then((res) => res.report);\n }\n\n /**\n * Resolves one recorded computation by id — the production-side \"a number opens\n * its computation\" click-through. Returns the method, the exact inputs (the\n * record revision ids read + the coverage denominator) and the result.\n * Member-scoped; a cross-project or cross-tenant id is a bounded 404.\n */\n getPMComputation(projectId: string, computationId: string): Promise<PmComputation> {\n return this.http\n .get<PmComputationResponse>(`/project/${projectId}/pm/computations/${computationId}`)\n .then((res) => res.computation);\n }\n\n /**\n * The attended-delivery PREFLIGHT for a status-report version (PJM-IP05): the\n * buildable-now product computation that precedes a governed distribution\n * proposal. It resolves the proposed recipients through THIS project's\n * stakeholder register — refusing an outsider at proposal time with the rule\n * cited — and re-runs the authority-to-share gate over the exact version's\n * claims against current document attestation, holding a fact whose grounding\n * is no longer attested shareable. Passing an empty `recipientContactIds`\n * returns the project's registered stakeholders as the candidate recipients.\n *\n * It QUEUES and SENDS nothing: the durable proposal, the owner+PM approval\n * binding, the execution on the shared person-directed act rail and the\n * per-destination receipts are the shared approvals surface (`ApprovalsClient`,\n * `DeliveryEvidenceLevel`, `ActDestinationReceipt`). `plan.delivery.ready` is\n * false with a bounded reason until the ClowdPM outbound rail is enabled — the\n * \"delivery not yet configured\" setup state. Requires an active member with\n * WRITE; a reader gets a 403, a non-member a bounded 404.\n */\n previewPMStatusDistribution(\n projectId: string,\n versionId: string,\n recipientContactIds: string[] = [],\n ): Promise<PmDistributionPlan> {\n return this.http\n .post<PmDistributionPlanResponse>(\n `/project/${projectId}/pm/status-reports/${versionId}/distribution-preflight`,\n { body: { recipientContactIds } },\n )\n .then((res) => res.plan);\n }\n\n /**\n * Repeats the exact-version/register/sharing preflight on the server and\n * creates a durable approval. Report bytes, artifact identity and transport\n * routing are intentionally not accepted from the client.\n */\n proposePMStatusDistribution(\n projectId: string,\n versionId: string,\n recipientContactIds: string[],\n ): Promise<PmDistributionProposal> {\n return this.http\n .post<PmDistributionProposalResponse>(\n `/project/${projectId}/pm/status-reports/${versionId}/distribution-proposals`,\n { body: { recipientContactIds } },\n )\n .then((res) => res.proposal);\n }\n\n /**\n * Reads drift assistance for the project: findings whose subject records have\n * gone stale past the freshness window, plus per-discipline coverage. Reads\n * only — no durable signal is raised. Requires an active member.\n */\n pmAssistDrift(\n projectId: string,\n freshnessWindowDays?: number,\n ): Promise<PmAssistDriftResult> {\n return this.http\n .post<PmAssistDriftResponse>(`/project/${projectId}/pm/assist/drift`, {\n body: { freshnessWindowDays },\n })\n .then((res) => ({\n drift: res.drift ?? [],\n coverage: res.coverage ?? [],\n }));\n }\n\n /**\n * Runs the assist sweep: drift + risk-candidate findings and coverage, and\n * raises durable shared signals for a member to triage. Returns the raised\n * count and the signals alongside the findings.\n */\n pmAssistSweep(\n projectId: string,\n freshnessWindowDays?: number,\n ): Promise<PmAssistSweepResult> {\n return this.http\n .post<PmAssistSweepResponse>(`/project/${projectId}/pm/assist/sweep`, {\n body: { freshnessWindowDays },\n })\n .then((res) => ({\n drift: res.drift ?? [],\n riskCandidates: res.riskCandidates ?? [],\n coverage: res.coverage ?? [],\n raised: res.raised,\n signals: res.signals ?? [],\n }));\n }\n\n /**\n * Dismisses a raised assist signal with a required rationale, returning the\n * updated signal.\n */\n dismissPMAssistSignal(\n projectId: string,\n signalId: string,\n rationale: string,\n ): Promise<PmSignal> {\n return this.http\n .post<PmSignalResponse>(\n `/project/${projectId}/pm/assist/signals/${signalId}/dismiss`,\n { body: { rationale } },\n )\n .then((res) => res.signal);\n }\n\n /**\n * Records that a raised assist signal was acted on — the member consumed it\n * into a durable artifact identified by `kind`/`ref` — optionally marking it\n * consumed. Returns the updated signal.\n */\n consumePMAssistSignal(\n projectId: string,\n signalId: string,\n kind: string,\n ref: string,\n markConsumed: boolean,\n ): Promise<PmSignal> {\n return this.http\n .post<PmSignalResponse>(\n `/project/${projectId}/pm/assist/signals/${signalId}/consume`,\n { body: { kind, ref, markConsumed } },\n )\n .then((res) => res.signal);\n }\n\n // ── Risk register with teeth (PJM-S03 / PJM-IP08) ──────────────────────────\n //\n // The one durable S03 journey over the EXISTING primitives: confirm a risk →\n // the named owner accepts/declines → an immutable register version is appended →\n // the approved response is an owned commitment → owner notification originates on\n // the shared `pm.notify.stakeholder` rail. This client asserts NO authority and\n // mints NO identity — it forwards the exact tuple and renders the server's answer.\n // It never fabricates a receipt: the notify method returns only the QUEUED\n // proposal and the honest \"owner not yet notified\" note; delivery is proven only\n // by the shared-rail receipt read on the approvals/activity surface. The confirmed\n // risk, its register version and the response survive an owner decline or a\n // notification failure.\n\n /**\n * Confirms a told/derived risk as a human-authored `risk` record (member with\n * WRITE). A named `ownerContactId` is PROPOSED — never assigned — and must be a\n * registered stakeholder of this project (else a 422). A told risk duplicating an\n * active entry's condition is refused (409 carrying the existing id) so the caller\n * updates that entry rather than forking a second one. Returns the created risk\n * record with its current revision.\n */\n confirmPMRisk(projectId: string, body: PmRiskConfirmRequest): Promise<PmRecord> {\n if (!body.condition?.trim()) {\n return Promise.reject(new Error('A risk condition is required.'));\n }\n return this.http\n .post<PmRiskConfirmResponse>(`/project/${projectId}/pm/risks`, { body })\n .then((res) => res.risk);\n }\n\n /**\n * Records the named owner's explicit accept/decline. The decision is the OWNER's\n * alone: the server refuses a generic member — even a manager — with a 403\n * (`decision-not-by-owner`), and an inactive/erased or unlinked owner fails\n * honestly. `expectedCurrentRevisionId` (the revision id you read) is the\n * optimistic-concurrency handle — a stale value is a 409 (thrown `HttpError`),\n * never a silent overwrite. Acceptance appends the immutable register version;\n * a decline leaves the risk confirmed-but-unowned. Returns the updated risk and\n * the appended register version handle.\n */\n decidePMRiskOwnership(\n projectId: string,\n riskId: string,\n body: PmRiskOwnershipRequest,\n ): Promise<PmRiskOwnershipResult> {\n if (body.decision !== 'accepted' && body.decision !== 'declined') {\n return Promise.reject(new Error(\"An ownership decision must be 'accepted' or 'declined'.\"));\n }\n if (!body.expectedCurrentRevisionId?.trim()) {\n return Promise.reject(new Error('expectedCurrentRevisionId is required to prevent a stale overwrite.'));\n }\n return this.http\n .post<PmRiskOwnershipResponse>(`/project/${projectId}/pm/risks/${riskId}/ownership`, { body })\n .then((res) => ({ risk: res.risk, registerVersionRef: res.registerVersionRef }));\n }\n\n /**\n * PROPOSES the typed response for the owner+PM decision (PJM-IP08 §7.10). It does\n * NOT create the owned commitment — that is materialized only when the decision\n * completes (see decidePMRiskResponse). A generic member may propose (member-write),\n * but the acceptance is the project owner+PM's alone. `dueAt` is MANDATORY (owner +\n * due). Requires an accepted, named, active owner (else 422). Optimistic concurrency\n * via `expectedCurrentRevisionId` (409). Re-proposing the same response is idempotent;\n * a changed response while one is live conflicts (409). Returns the risk and the\n * pending proposal — never a delivery or an approval this client did not observe.\n */\n proposePMRiskResponse(\n projectId: string,\n riskId: string,\n body: PmRiskResponseRequest,\n ): Promise<PmRiskResponseResult> {\n if (!body.description?.trim()) {\n return Promise.reject(new Error('A response description is required.'));\n }\n if (!body.dueAt?.trim()) {\n return Promise.reject(new Error('A response due date is required — a response is owner + due.'));\n }\n if (!body.expectedCurrentRevisionId?.trim()) {\n return Promise.reject(new Error('expectedCurrentRevisionId is required to prevent a stale overwrite.'));\n }\n return this.http\n .post<PmRiskResponseResponse>(`/project/${projectId}/pm/risks/${riskId}/response`, { body })\n .then((res) => ({\n risk: res.risk,\n responseProposal: res.responseProposal,\n registerVersionRef: res.registerVersionRef,\n }));\n }\n\n /**\n * Records the project owner's or PM's decision on a proposed response through the\n * existing PJ-D028 owner+PM path (identity collapse, current-authority recheck). The\n * server refuses a generic member (403) — this client asserts no authority. Only a\n * completing acceptance materializes exactly one owned commitment and re-versions the\n * register; a rejection keeps the risk confirmed, response pending. Returns the honest\n * `status` (accepted | pending | rejected) and, on acceptance, the owned commitment.\n */\n decidePMRiskResponse(\n projectId: string,\n riskId: string,\n body: PmRiskResponseDecisionRequest,\n ): Promise<PmRiskResponseDecisionResult> {\n if (!body.proposalId?.trim()) {\n return Promise.reject(new Error('A proposalId is required to decide a response.'));\n }\n if (body.decision !== 'accept' && body.decision !== 'reject') {\n return Promise.reject(new Error(\"A response decision must be 'accept' or 'reject'.\"));\n }\n return this.http\n .post<PmRiskResponseDecisionResponse>(`/project/${projectId}/pm/risks/${riskId}/response/decision`, { body })\n .then((res) => ({\n risk: res.risk,\n status: res.status,\n response: res.response,\n responseRecordId: res.responseRecordId,\n registerVersionRef: res.registerVersionRef,\n note: res.note,\n }));\n }\n\n /**\n * Originates the owner-notification: it produces the per-risk immutable\n * notification artifact and a trusted proposal on the EXISTING\n * `pm.notify.stakeholder` shared act rail (recipient = the accepted owner). It\n * requires an accepted owner who is a registered stakeholder AND a recorded owned\n * response. The server records only the QUEUED pending action — never a\n * \"notified\"/\"delivered\" flag; the returned `note` is the honest \"owner not yet\n * notified\" statement. It is idempotent (a duplicate returns the existing queued\n * action). A transport/proposal failure is a thrown `HttpError` (502) with the\n * confirmed risk, register version and response left intact. Delivery is proven\n * ONLY by the shared-rail receipt — never inferred from this proposal.\n */\n proposePMRiskNotification(projectId: string, riskId: string): Promise<PmRiskNotifyResult> {\n return this.http\n .post<PmRiskNotifyResponse>(`/project/${projectId}/pm/risks/${riskId}/notify`, { body: {} })\n .then((res) => ({ proposal: res.proposal, note: res.note }));\n }\n}\n","import type { Sandbox } from '../modules/sandboxes/types.js';\n\ninterface WireSandbox {\n id: string;\n name: string;\n storageType: string;\n mode: string;\n orgId: string;\n userId: string;\n createdAt: string;\n disabled?: boolean;\n // Legacy wire alternates: backend may send projectId or workspaceId.\n projectId?: string | null;\n workspaceId?: string | null;\n}\n\nexport const sandboxAdapter = {\n fromListResponse(payload: unknown): Sandbox[] {\n const list = (payload as { repos?: WireSandbox[]; sandboxes?: WireSandbox[] } | null)?.repos\n ?? (payload as { sandboxes?: WireSandbox[] } | null)?.sandboxes\n ?? [];\n return list.map(normalize);\n },\n\n fromGetResponse(payload: unknown): Sandbox {\n const wire = payload as { repo?: WireSandbox; sandbox?: WireSandbox; data?: WireSandbox } | null;\n const value = wire?.repo ?? wire?.sandbox ?? wire?.data;\n if (!value) throw new Error('Sandbox response missing body.');\n return normalize(value);\n },\n\n normalize,\n};\n\nfunction normalize(wire: WireSandbox): Sandbox {\n return {\n id: wire.id,\n name: wire.name,\n storageType: wire.storageType,\n mode: wire.mode,\n orgId: wire.orgId,\n userId: wire.userId,\n projectId: wire.projectId ?? wire.workspaceId ?? null,\n createdAt: wire.createdAt,\n disabled: wire.disabled ?? false,\n };\n}\n\n// TODO(backend-cleanup): cloud-agent-backend internal/http/routes/sandbox/sandbox.go\n// still returns `repos` / `repo` response keys, and Sandbox JSON may carry\n// `workspaceId` instead of `projectId` (internal/domain/types.go). When both\n// are renamed, this adapter collapses to a plain unwrap.\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { sandboxAdapter } from '../../adapters/sandboxAdapter.js';\nimport type {\n CreateSandboxRequest,\n ListSandboxesQuery,\n Sandbox,\n UpdateSandboxRequest,\n} from './types.js';\n\ninterface SimpleResponse {\n success: boolean;\n message?: string;\n}\n\nexport class SandboxesClient {\n constructor(private readonly http: BaseClient) {}\n\n async list(query: ListSandboxesQuery = {}): Promise<Sandbox[]> {\n const res = await this.http.get<unknown>('/sandbox', {\n query: { projectId: query.projectId },\n });\n return sandboxAdapter.fromListResponse(res);\n }\n\n async get(sandboxId: string): Promise<Sandbox> {\n const res = await this.http.get<unknown>(`/sandbox/${sandboxId}`);\n return sandboxAdapter.fromGetResponse(res);\n }\n\n async create(body: CreateSandboxRequest): Promise<Sandbox> {\n const res = await this.http.post<unknown>('/sandbox', {\n body: {\n name: body.name,\n projectId: body.projectId,\n storageType: body.storageType ?? 'S3',\n mode: body.mode ?? 'NORMAL',\n },\n });\n return sandboxAdapter.fromGetResponse(res);\n }\n\n async update(sandboxId: string, body: UpdateSandboxRequest): Promise<Sandbox> {\n const res = await this.http.put<unknown>(`/sandbox/${sandboxId}`, { body });\n return sandboxAdapter.fromGetResponse(res);\n }\n\n delete(sandboxId: string): Promise<SimpleResponse> {\n return this.http.delete<SimpleResponse>(`/sandbox/${sandboxId}`);\n }\n}\n","// Credential types for @clowdops/tsclient.\n//\n// Schema mirrors cloud-agent-backend's Credential row (renamed from APIKey\n// in migration 0010). Every provider — cloud (AWS/GCP/AZURE), infra\n// (SSH), VCS (GitHub/GitLab/Azure DevOps), AI/LLM (OpenAI/Anthropic) —\n// uses the same `(provider, label, secret, metadata)` shape.\n// Provider-specific fields live in `metadata`; the catalog at\n// ./providers.ts is the source of truth for what each provider's fields\n// look like.\n//\n// Sandbox-scoped FOA bearer tokens (formerly RepoAiApiKey) are now\n// modelled separately as GatewayToken — see below.\n\n// ProviderID is open: the catalog defines a default set, but we allow\n// any string so customer-extended catalogs are still typed.\nexport type ProviderID = 'AWS' | 'BEDROCK' | 'GCP' | 'AZURE' | 'OCI' | 'SSH' | 'GITHUB' | 'GITLAB' | 'AZURE_DEVOPS' | 'OPENAI' | 'ANTHROPIC' | 'GEMINI' | string;\n\n// ── Universal credential ─────────────────────────────────────────────\n\n// Credential is the read-projection of one row in the Credential table.\n// Never includes the secret. `displayHint` is the catalog-computed\n// snippet for listings (e.g. \"AKIATEST… / us-east-1\",\n// \"ubuntu@vps.example.com:22\").\nexport interface Credential {\n id: string;\n provider: ProviderID;\n label: string;\n metadata: Record<string, unknown>;\n displayHint?: string;\n createdAt: string;\n}\n\n// CreateCredentialRequest is the universal create body. Provider-specific\n// fields go inside `metadata`; the catalog validates the shape both\n// client-side (./providers.ts:validate) and server-side.\nexport interface CreateCredentialRequest {\n provider: ProviderID;\n label: string;\n secret: string;\n metadata?: Record<string, unknown>;\n projectId: string;\n}\n\n// UpdateCredentialRequest is partial. Provider is immutable on update; to\n// change provider, delete and re-create. `metadata` is replace-wholesale\n// when present.\nexport interface UpdateCredentialRequest {\n label?: string;\n secret?: string;\n metadata?: Record<string, unknown>;\n}\n\n// PublishBICredentialRequest is the body for POST /credentials/:id/bi-publish\n// (BI-RLS-01): the explicit owner/admin sign-off that turns a shared BI\n// credential from credless into usable by every viewer. Both fields are\n// required — the server rejects a blank classification or label, and rejects\n// a per-user-scoped credential outright (it is already viewer-scoped).\nexport interface PublishBICredentialRequest {\n /** Data classification the underlying connection exposes, e.g. \"internal\", \"confidential\". */\n classification: string;\n /** Shown to every viewer of a dashboard backed by this connection, e.g. \"Sales shared account\". */\n runsAsLabel: string;\n}\n\n// RevokeBIPublishRequest is the optional body for DELETE /credentials/:id/bi-publish.\nexport interface RevokeBIPublishRequest {\n reason?: string;\n}\n\n// ListCredentialsQuery narrows /credentials by project and optionally by\n// provider id or capability bit (storage|ai|compute|vcs|notify).\nexport interface ListCredentialsQuery {\n projectId: string;\n provider?: ProviderID;\n capability?: 'storage' | 'ai' | 'compute' | 'vcs' | 'notify';\n}\n\n// SandboxCredential is one row in the SandboxCredential join table —\n// links a sandbox to a project-level credential. The PK is\n// (sandboxId, credentialId), so association identity is the pair itself\n// (no synthetic association id).\nexport interface SandboxCredential {\n sandboxId: string;\n credentialId: string;\n provider: ProviderID;\n label: string;\n displayHint?: string;\n createdAt: string;\n}\n\n// ── Sandbox gateway tokens ───────────────────────────────────────────\n\n// GatewayToken is a sandbox-scoped, OpenAI-compatible bearer used by the\n// agent engine to authenticate to FlashOnAI. The plaintext secret is\n// returned exactly once — at creation — and never re-fetchable.\nexport interface GatewayToken {\n id: string;\n sandboxId: string;\n label: string;\n createdAt: string;\n}\n\nexport interface CreateGatewayTokenRequest {\n label: string;\n}\n\n// CreateGatewayTokenResponse is the create-time-only shape — `secret`\n// holds the plaintext bearer the caller must surface (\"copy now\")\n// before navigating away.\nexport interface CreateGatewayTokenResponse {\n token: GatewayToken;\n secret: string;\n}\n\n// AgentToken is a sandbox-scoped bearer an EXTERNAL agent (Claude Code,\n// Cursor, Codex, …) presents to the MCP server (/mcp) to drive this\n// sandbox's cloud agent. Only a hash is stored server-side; the plaintext\n// (`secret`) is returned exactly once at creation. `tokenPrefix` is a\n// non-secret display fragment (\"fba_AbCd…\") so a list can disambiguate\n// rotated tokens.\nexport interface AgentToken {\n id: string;\n sandboxId: string;\n label: string;\n tokenPrefix: string;\n lastUsedAt?: string;\n createdAt: string;\n}\n\nexport interface CreateAgentTokenRequest {\n label: string;\n}\n\n// CreateAgentTokenResponse is the create-time-only shape — `secret` holds\n// the plaintext bearer the caller must surface (\"copy now\") before\n// navigating away.\nexport interface CreateAgentTokenResponse {\n token: AgentToken;\n secret: string;\n}\n\n// ── Common envelope ──────────────────────────────────────────────────\n\nexport interface SimpleKeysResponse {\n success: boolean;\n message?: string;\n data?: unknown;\n}\n\n// ── Wire shapes (legacy field-name aliases collapse here) ────────────\n\nexport interface WireSandboxCredential {\n // Backend wire emits sandboxId; older clients may still see repoId.\n // Normaliser collapses both into SandboxCredential.sandboxId.\n sandboxId?: string;\n repoId?: string;\n credentialId: string;\n provider: string;\n label: string;\n displayHint?: string | null;\n createdAt: string;\n}\n\nexport interface WireGatewayToken {\n id: string;\n // Backend wire emits sandboxId via \"repoId\" today (StorageRepo/Sandbox\n // alias); accept both.\n sandboxId?: string;\n repoId?: string;\n label: string;\n createdAt: string;\n}\n\nexport function normalizeSandboxCredential(wire: WireSandboxCredential): SandboxCredential {\n return {\n sandboxId: wire.sandboxId ?? wire.repoId ?? '',\n credentialId: wire.credentialId,\n provider: wire.provider,\n label: wire.label,\n displayHint: wire.displayHint ?? undefined,\n createdAt: wire.createdAt,\n };\n}\n\nexport function normalizeGatewayToken(wire: WireGatewayToken): GatewayToken {\n return {\n id: wire.id,\n sandboxId: wire.sandboxId ?? wire.repoId ?? '',\n label: wire.label,\n createdAt: wire.createdAt,\n };\n}\n\nexport interface WireAgentToken {\n id: string;\n // Backend emits sandboxId; accept repoId too for forward/backward compat.\n sandboxId?: string;\n repoId?: string;\n label: string;\n tokenPrefix: string;\n lastUsedAt?: string | null;\n createdAt: string;\n}\n\nexport function normalizeAgentToken(wire: WireAgentToken): AgentToken {\n return {\n id: wire.id,\n sandboxId: wire.sandboxId ?? wire.repoId ?? '',\n label: wire.label,\n tokenPrefix: wire.tokenPrefix,\n lastUsedAt: wire.lastUsedAt ?? undefined,\n createdAt: wire.createdAt,\n };\n}\n","// AgentTokensClient covers sandbox-scoped agent access tokens — the bearers\n// an EXTERNAL agent (Claude Code, Cursor, Codex, …) presents to the MCP\n// server (/mcp) to drive this sandbox's cloud agent. Each sandbox can have\n// multiple tokens (one per client, rotation).\n//\n// The plaintext bearer is returned EXACTLY ONCE — at create time. The\n// frontend must surface it (\"copy now\") before navigating away; the server\n// stores only a sha256 hash, so a lost plaintext is unrecoverable (delete +\n// recreate).\nimport type { BaseClient } from '../../http/BaseClient.js';\nimport {\n AgentToken,\n CreateAgentTokenRequest,\n CreateAgentTokenResponse,\n SimpleKeysResponse,\n WireAgentToken,\n normalizeAgentToken,\n} from './types.js';\n\nexport class AgentTokensClient {\n constructor(private readonly http: BaseClient) {}\n\n async list(sandboxId: string): Promise<AgentToken[]> {\n const res = await this.http.get<{ success: boolean; tokens?: WireAgentToken[]; data?: WireAgentToken[] }>(\n `/sandbox/${sandboxId}/agent-token`,\n );\n const list = res.tokens ?? res.data ?? [];\n return list.map(normalizeAgentToken);\n }\n\n /**\n * create returns both the persisted token row and the plaintext bearer\n * (`secret`). The bearer is shown only here; surface it to the user\n * immediately. If they navigate away without copying, they must delete the\n * token and create a new one.\n */\n async create(sandboxId: string, body: CreateAgentTokenRequest): Promise<CreateAgentTokenResponse> {\n const res = await this.http.post<{\n success: boolean;\n token?: WireAgentToken;\n secret?: string;\n }>(`/sandbox/${sandboxId}/agent-token`, { body });\n if (!res.token || !res.secret) {\n throw new Error('createAgentToken response missing token or secret.');\n }\n return {\n token: normalizeAgentToken(res.token),\n secret: res.secret,\n };\n }\n\n delete(sandboxId: string, tokenId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/sandbox/${sandboxId}/agent-token/${tokenId}`);\n }\n}\n","// GatewayTokensClient covers sandbox-scoped FOA bearer tokens (the\n// post-redesign replacement for the legacy RepoAiApiKey rows). Each\n// sandbox can have multiple tokens for rotation / dev-prod separation.\n//\n// The plaintext bearer is returned EXACTLY ONCE — at create time. The\n// frontend must surface it (\"copy now\") before navigating away; once\n// the response is dropped, only the encrypted envelope persists and the\n// plaintext is unrecoverable.\nimport type { BaseClient } from '../../http/BaseClient.js';\nimport {\n CreateGatewayTokenRequest,\n CreateGatewayTokenResponse,\n GatewayToken,\n SimpleKeysResponse,\n WireGatewayToken,\n normalizeGatewayToken,\n} from './types.js';\n\nexport class GatewayTokensClient {\n constructor(private readonly http: BaseClient) {}\n\n async list(sandboxId: string): Promise<GatewayToken[]> {\n const res = await this.http.get<{ success: boolean; tokens?: WireGatewayToken[]; data?: WireGatewayToken[] }>(\n `/sandbox/${sandboxId}/gateway-token`,\n );\n const list = res.tokens ?? res.data ?? [];\n return list.map(normalizeGatewayToken);\n }\n\n /**\n * create returns both the persisted token row and the plaintext bearer\n * (`secret`). The bearer is shown only here; surface it to the user\n * immediately. If they navigate away without copying, they have to\n * delete the token and create a new one.\n */\n async create(sandboxId: string, body: CreateGatewayTokenRequest): Promise<CreateGatewayTokenResponse> {\n const res = await this.http.post<{\n success: boolean;\n token?: WireGatewayToken;\n secret?: string;\n }>(`/sandbox/${sandboxId}/gateway-token`, { body });\n if (!res.token || !res.secret) {\n throw new Error('createGatewayToken response missing token or secret.');\n }\n return {\n token: normalizeGatewayToken(res.token),\n secret: res.secret,\n };\n }\n\n delete(sandboxId: string, tokenId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/sandbox/${sandboxId}/gateway-token/${tokenId}`);\n }\n}\n","// TelegramClient covers the inbound-control surface for a sandbox's Telegram\n// bot (Feature 2). The bot is a project-scoped TELEGRAM credential attached to\n// the sandbox; these endpoints enable the inbound webhook, mint single-use link\n// codes (pasted in Telegram as `/link <code>`), and list/revoke chat bindings.\n//\n// The link code is returned EXACTLY ONCE at mint time — surface it immediately.\n// The backend stores only its hash.\nimport type { BaseClient } from '../../http/BaseClient.js';\n\nexport interface TelegramBinding {\n id: string;\n telegramChatId: string;\n telegramUserId?: string | null;\n label?: string | null;\n status: string;\n createdAt: string;\n lastUsedAt?: string | null;\n}\n\nexport interface MintLinkCodeResponse {\n code: string;\n expiresInSeconds: number;\n}\n\n/** A chat the bot has seen, surfaced for chat-ID auto-fill during enrolment. */\nexport interface TelegramDiscoveredChat {\n id: string;\n /** private | group | supergroup | channel */\n type: string;\n /** friendly display name (group/channel title, or the user's name) */\n title: string;\n}\n\n/**\n * A chat already linked to a bot credential (via `/link`). Surfaced as a\n * pick-list for the default outbound Chat ID when inbound is enabled and live\n * getUpdates detection is therefore unavailable.\n */\nexport interface TelegramKnownChat {\n id: string;\n /** friendly name captured at link time; absent for older bindings */\n label?: string | null;\n}\n\n/** The bot's identity + state, used to build the \"open your bot\" deep link. */\nexport interface TelegramBotInfo {\n /** bot @username (without the @) — link is https://t.me/<username> */\n username: string;\n name: string;\n /** true when a webhook is set (inbound enabled) — chat detection won't work */\n webhookSet: boolean;\n}\n\nexport class TelegramClient {\n constructor(private readonly http: BaseClient) {}\n\n /**\n * Look up a bot's identity (and whether inbound/webhook is active) from its\n * token, so the UI can show a one-click \"open @bot in Telegram\" link. The\n * token is used server-side transiently and not stored.\n */\n async botInfo(token: string): Promise<TelegramBotInfo> {\n const res = await this.http.post<{ success: boolean; bot?: { username: string; name: string; webhook_set: boolean } }>(\n '/credentials/telegram/bot-info',\n { body: { token } },\n );\n const b = res.bot;\n if (!b) throw new Error('botInfo response missing bot.');\n return { username: b.username, name: b.name, webhookSet: b.webhook_set };\n }\n\n /**\n * Discover the chats a bot can post to, for chat-ID auto-fill during\n * enrolment. The user creates the bot, sends it a message (or adds it to a\n * group/channel), then this returns the chats it has seen — no manual\n * getUpdates call. The token is used server-side transiently and not stored.\n * Returns [] when the bot hasn't been messaged yet.\n */\n async discoverChats(token: string): Promise<TelegramDiscoveredChat[]> {\n const res = await this.http.post<{ success: boolean; chats?: TelegramDiscoveredChat[] }>(\n '/credentials/telegram/discover-chats',\n { body: { token } },\n );\n return res.chats ?? [];\n }\n\n /**\n * List the chats already linked to a bot credential (from `/link`\n * redemptions). Unlike discoverChats (which calls getUpdates and fails while\n * a webhook is active), this reads our stored bindings, so it works precisely\n * when inbound is enabled. Returns [] when nothing has linked yet.\n */\n async knownChats(credentialId: string): Promise<TelegramKnownChat[]> {\n const res = await this.http.get<{ success: boolean; chats?: TelegramKnownChat[] }>(\n `/credentials/telegram/${credentialId}/chats`,\n );\n return res.chats ?? [];\n }\n\n /**\n * Remove the bot's webhook on Telegram (deleteWebhook) so getUpdates chat\n * detection works again. Used to reclaim a bot that still has a webhook from a\n * previous setup (an orphan whose owning credential is gone). Note this frees\n * the bot globally — any inbound on it stops until re-enabled. The token is\n * used server-side transiently and not stored.\n */\n async clearWebhook(token: string): Promise<void> {\n await this.http.post<{ success: boolean }>('/credentials/telegram/clear-webhook', { body: { token } });\n }\n\n /** Enable inbound: register the bot's webhook (anchored at this sandbox). */\n enableInbound(sandboxId: string, credentialId: string): Promise<{ success: boolean }> {\n return this.http.post<{ success: boolean }>(`/sandbox/${sandboxId}/telegram/enable`, {\n body: { credential_id: credentialId },\n });\n }\n\n /** Disable inbound for the bot (bindings are kept; re-enable rekeys). */\n disableInbound(sandboxId: string, credentialId: string): Promise<{ success: boolean }> {\n return this.http.post<{ success: boolean }>(`/sandbox/${sandboxId}/telegram/disable`, {\n body: { credential_id: credentialId },\n });\n }\n\n /**\n * Mint a single-use link code. The plaintext `code` is returned once — show\n * it to the user to paste in Telegram as `/link <code>`.\n */\n async mintLinkCode(sandboxId: string, credentialId: string): Promise<MintLinkCodeResponse> {\n const res = await this.http.post<{ success: boolean; code?: string; expires_in_seconds?: number }>(\n `/sandbox/${sandboxId}/telegram/link-code`,\n { body: { credential_id: credentialId } },\n );\n if (!res.code) {\n throw new Error('mintLinkCode response missing code.');\n }\n return { code: res.code, expiresInSeconds: res.expires_in_seconds ?? 0 };\n }\n\n /** List active chat bindings for this sandbox. */\n async listBindings(sandboxId: string): Promise<TelegramBinding[]> {\n const res = await this.http.get<{ success: boolean; bindings?: TelegramBinding[] }>(\n `/sandbox/${sandboxId}/telegram/bindings`,\n );\n return res.bindings ?? [];\n }\n\n /** Revoke a chat binding — the chat stops driving the agent immediately. */\n revokeBinding(sandboxId: string, bindingId: string): Promise<{ success: boolean }> {\n return this.http.delete<{ success: boolean }>(`/sandbox/${sandboxId}/telegram/bindings/${bindingId}`);\n }\n}\n","// Universal credentials client. Post-credential-redesign (cloud-agent-\n// backend migration 0010) one schema covers every provider: cloud, SSH,\n// GitHub, GitLab, Azure DevOps, OpenAI, Anthropic. Provider-specific\n// fields live inside `metadata`; the catalog at ./providers.ts is the\n// authoritative shape per provider.\n//\n// Surface:\n// apiClient.credentials.list() — every credential in the project\n// apiClient.credentials.create() — one create endpoint, any provider\n// apiClient.credentials.update() — partial update\n// apiClient.credentials.delete() — remove\n// apiClient.credentials.providers() — fetch the catalog\n// apiClient.credentials.sandbox.* — sandbox associations (any provider)\n// apiClient.credentials.gatewayTokens.* — sandbox FOA bearer tokens\n// apiClient.credentials.agentTokens.* — sandbox MCP agent access tokens\nimport type { BaseClient } from '../../http/BaseClient.js';\nimport { AgentTokensClient } from './AgentTokensClient.js';\nimport { GatewayTokensClient } from './GatewayTokensClient.js';\nimport { TelegramClient } from './TelegramClient.js';\nimport {\n Credential,\n CreateCredentialRequest,\n ListCredentialsQuery,\n ProviderID,\n PublishBICredentialRequest,\n RevokeBIPublishRequest,\n SandboxCredential,\n SimpleKeysResponse,\n UpdateCredentialRequest,\n WireSandboxCredential,\n normalizeSandboxCredential,\n} from './types.js';\nimport type { ProviderSpec } from './providers.js';\n\n// ── Sandbox associations ───────────────────────────────────────────────\n\nclass SandboxCredentialScope {\n constructor(private readonly http: BaseClient) {}\n\n async list(sandboxId: string): Promise<SandboxCredential[]> {\n const res = await this.http.get<{ success: boolean; items?: WireSandboxCredential[]; data?: WireSandboxCredential[] }>(\n `/sandbox/${sandboxId}/credential`,\n );\n const list = res.items ?? res.data ?? [];\n return list.map(normalizeSandboxCredential);\n }\n\n attach(sandboxId: string, credentialId: string): Promise<SimpleKeysResponse> {\n return this.http.post<SimpleKeysResponse>(`/sandbox/${sandboxId}/credential`, {\n body: { credentialId },\n });\n }\n\n detach(sandboxId: string, credentialId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/sandbox/${sandboxId}/credential/${credentialId}`);\n }\n}\n\n// ── Top-level credentials client ──────────────────────────────────────\n\nexport class CredentialsClient {\n readonly sandbox: SandboxCredentialScope;\n readonly gatewayTokens: GatewayTokensClient;\n /** Sandbox agent access tokens — bearers external agents use against /mcp. */\n readonly agentTokens: AgentTokensClient;\n /** Sandbox Telegram inbound control — enable webhook, link codes, bindings. */\n readonly telegram: TelegramClient;\n\n constructor(private readonly http: BaseClient) {\n this.sandbox = new SandboxCredentialScope(http);\n this.gatewayTokens = new GatewayTokensClient(http);\n this.agentTokens = new AgentTokensClient(http);\n this.telegram = new TelegramClient(http);\n }\n\n async list(query: ListCredentialsQuery): Promise<Credential[]> {\n const res = await this.http.get<{ success: boolean; credentials?: Credential[]; data?: Credential[] }>(\n '/credentials',\n {\n query: {\n projectId: query.projectId,\n provider: query.provider,\n capability: query.capability,\n },\n },\n );\n return res.credentials ?? res.data ?? [];\n }\n\n async create(body: CreateCredentialRequest): Promise<Credential> {\n const res = await this.http.post<{ success: boolean; data?: Credential; credential?: Credential }>(\n '/credentials',\n { body },\n );\n const value = res.data ?? res.credential;\n if (!value) throw new Error('createCredential response missing body.');\n return value;\n }\n\n async update(credentialId: string, body: UpdateCredentialRequest): Promise<Credential> {\n const res = await this.http.put<{ success: boolean; credential?: Credential; data?: Credential }>(\n `/credentials/${credentialId}`,\n { body },\n );\n const value = res.credential ?? res.data;\n if (!value) throw new Error('updateCredential response missing body.');\n return value;\n }\n\n delete(credentialId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/credentials/${credentialId}`);\n }\n\n /**\n * publishBI (BI-RLS-01) turns a shared/service BI credential from credless\n * into usable by every viewer — the explicit owner/admin sign-off the\n * engine's run-as-viewer gate requires before it will query a shared\n * connection. No-op-equivalent (400) on a per-user-scoped credential, which\n * is already viewer-scoped and never needs publishing.\n */\n async publishBI(credentialId: string, body: PublishBICredentialRequest): Promise<Credential> {\n const res = await this.http.post<{ success: boolean; credential?: Credential; data?: Credential }>(\n `/credentials/${credentialId}/bi-publish`,\n { body },\n );\n const value = res.credential ?? res.data;\n if (!value) throw new Error('publishBI response missing body.');\n return value;\n }\n\n /**\n * revokeBIPublish (BI-RLS-01) reverts a shared BI credential to credless.\n * The prior approval (classification, runsAsLabel, approvedBy/At) is kept\n * on the credential for audit history; only revocation attribution is added.\n */\n async revokeBIPublish(credentialId: string, body: RevokeBIPublishRequest = {}): Promise<Credential> {\n const res = await this.http.delete<{ success: boolean; credential?: Credential; data?: Credential }>(\n `/credentials/${credentialId}/bi-publish`,\n { body },\n );\n const value = res.credential ?? res.data;\n if (!value) throw new Error('revokeBIPublish response missing body.');\n return value;\n }\n\n /**\n * listOrgNotify returns the org-scoped notification credentials (Slack /\n * Teams / PagerDuty / SMTP, workspaceId NULL) — the channels the org owns\n * for platform-event notifications, managed on Settings → System\n * notifications. Distinct from project-scoped notify credentials.\n */\n async listOrgNotify(): Promise<Credential[]> {\n const res = await this.http.get<{ success: boolean; credentials?: Credential[]; data?: Credential[] }>(\n '/credentials/org-notify',\n );\n return res.credentials ?? res.data ?? [];\n }\n\n /**\n * createOrgNotify creates an org-scoped notification credential. The body is\n * the universal credential shape minus projectId/workspaceId (the server\n * pins workspaceId to NULL); provider must be a notify transport.\n */\n async createOrgNotify(\n body: Omit<CreateCredentialRequest, 'projectId' | 'workspaceId'>,\n ): Promise<Credential> {\n const res = await this.http.post<{ success: boolean; data?: Credential; credential?: Credential }>(\n '/credentials/org-notify',\n { body },\n );\n const value = res.data ?? res.credential;\n if (!value) throw new Error('createOrgNotify response missing body.');\n return value;\n }\n\n /**\n * updateOrgNotify applies a partial update to an org-scoped notification\n * credential. Secret is optional — omit it to keep the stored one, supply a\n * new value to rotate it. The server republishes the org topology so the\n * change reaches consumers without a refresh round-trip.\n */\n async updateOrgNotify(credentialId: string, body: UpdateCredentialRequest): Promise<Credential> {\n const res = await this.http.put<{ success: boolean; credential?: Credential; data?: Credential }>(\n `/credentials/org-notify/${credentialId}`,\n { body },\n );\n const value = res.credential ?? res.data;\n if (!value) throw new Error('updateOrgNotify response missing body.');\n return value;\n }\n\n deleteOrgNotify(credentialId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/credentials/org-notify/${credentialId}`);\n }\n\n /**\n * adminDeliver seeds a credential into ANOTHER org's project — the\n * platform-admin delivery path for eval-sandbox credentials. The caller\n * must be a platform admin; the target org comes from the path (no\n * impersonation involved) and the audit event lands in the target org's\n * trail. The server accepts cloud (storage-capable) providers only.\n * Optional `metadata.expiresAt` (RFC3339) marks a time-bound credential\n * so the tenant UI can badge the upcoming sandbox expiry.\n */\n async adminDeliver(orgId: string, body: CreateCredentialRequest): Promise<Credential> {\n const res = await this.http.post<{ success: boolean; data?: Credential; credential?: Credential }>(\n `/admin/orgs/${orgId}/credentials`,\n { body },\n );\n const value = res.data ?? res.credential;\n if (!value) throw new Error('adminDeliver response missing body.');\n return value;\n }\n\n /**\n * providers fetches the server-side catalog — the RUNTIME SOURCE OF TRUTH\n * for credential creation/editing and provider categories. It picks up\n * providers added server-side (including the MKT/MTG and BI families, and\n * any customer extension) without a tsclient/frontend release. The static\n * ./providers.ts catalog is an offline fallback only (resolveProviderCatalog).\n *\n * @param product optional product partition ('cloud' | 'bi' | 'meeting' |\n * 'marketing'); the backend filters the catalog to that surface. Omitted →\n * the backend default ('cloud').\n */\n async providers(product?: string): Promise<ProviderSpec[]> {\n const res = await this.http.get<{ success: boolean; providers?: ProviderSpec[]; data?: ProviderSpec[] }>(\n '/providers',\n product ? { query: { product } } : undefined,\n );\n return res.providers ?? res.data ?? [];\n }\n\n /**\n * globalAiProviders returns the AI provider ids the platform \"global\" key\n * pool (admin org's reference project) can serve, e.g. ['ANTHROPIC']. Empty\n * when no platform keys are configured — the UI then hides the non-BYOK\n * provider picker entirely (BYOK-only, as before the feature).\n */\n async globalAiProviders(): Promise<ProviderID[]> {\n const res = await this.http.get<{ success: boolean; providers?: ProviderID[]; data?: ProviderID[] }>(\n '/credentials/global-ai-providers',\n );\n return res.providers ?? res.data ?? [];\n }\n}\n\nexport type { ProviderID };\n","import type { TokenProvider } from '../../http/tokenProvider.js';\nimport type { ChatEvent, ChatScope } from './types.js';\n\nexport interface OpenChatStreamOptions {\n scope: ChatScope;\n conversationId: string;\n onEvent: (event: ChatEvent) => void;\n onError?: (err: Event) => void;\n lastEventId?: string;\n /** Heartbeat in ms before the polyfill considers the connection stale. Default: 60000. */\n heartbeatTimeout?: number;\n}\n\nexport interface ChatStreamHandle {\n close(): void;\n}\n\nexport interface ChatStreamDeps {\n baseUrl: string;\n getToken?: TokenProvider;\n}\n\nconst STREAM_PATH = '/api/agentengine/v1/agent/chat/sessions';\n\n/**\n * Opens an SSE connection to the chat stream. Requires the consumer to have\n * `event-source-polyfill` installed (peer dep). Browsers' native EventSource\n * does not support custom headers, which we need for auth + scope.\n */\nexport async function openChatStream(\n deps: ChatStreamDeps,\n options: OpenChatStreamOptions,\n): Promise<ChatStreamHandle> {\n // Lazy import so consumers in non-browser contexts (or those who don't use\n // the chat stream at all) aren't forced to install the polyfill.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const mod: any = await import('event-source-polyfill');\n const Polyfill = mod.EventSourcePolyfill ?? mod.default?.EventSourcePolyfill ?? mod.default;\n if (!Polyfill) {\n throw new Error('event-source-polyfill is required for client.chat.openStream(). Install it as a peer dep.');\n }\n\n const url = `${deps.baseUrl.replace(/\\/$/, '')}${STREAM_PATH}/${options.conversationId}/stream`;\n\n const headers: Record<string, string> = {\n 'X-Org-Id': options.scope.orgId,\n 'X-User-Id': options.scope.userId,\n 'X-Sandbox-Id': options.scope.sandboxId ?? options.scope.repoId ?? '',\n 'X-Repo-Id': options.scope.sandboxId ?? options.scope.repoId ?? '',\n };\n if (options.scope.projectId ?? options.scope.workspaceId) {\n headers['X-Project-Id'] = options.scope.projectId ?? options.scope.workspaceId ?? '';\n headers['X-Workspace-Id'] = options.scope.projectId ?? options.scope.workspaceId ?? '';\n }\n if (deps.getToken) {\n const token = await deps.getToken();\n if (token) headers['Authorization'] = `Bearer ${token}`;\n }\n if (options.lastEventId) headers['Last-Event-ID'] = options.lastEventId;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const es = new (Polyfill as any)(url, {\n headers,\n heartbeatTimeout: options.heartbeatTimeout ?? 60_000,\n });\n\n // The backend sends named SSE events (event: phase, event: question, …).\n // onmessage only fires for the default unnamed type; addEventListener is required for named events.\n const KNOWN_EVENTS = [\n 'phase', 'question', 'plan_draft',\n 'step_started', 'step_completed', 'step_failed', 'step_progress',\n 'narration', 'assistant_message', 'done',\n 'session_title',\n 'tool_call_started', 'tool_call_finished',\n 'llm_call_finished',\n 'tool_call_confirmation_required',\n 'pending_action_queued', 'artifact_drafted', 'artifact_referenced',\n ];\n\n const handleRaw = (raw: MessageEvent) => {\n try {\n const parsed = JSON.parse(raw.data) as ChatEvent;\n options.onEvent(parsed);\n } catch {\n // Ignore malformed events\n }\n };\n\n for (const name of KNOWN_EVENTS) {\n es.addEventListener(name, handleRaw);\n }\n\n if (options.onError) {\n es.onerror = (event: Event) => options.onError?.(event);\n }\n\n return { close: () => es.close() };\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type { TokenProvider } from '../../http/tokenProvider.js';\nimport { openChatStream, type ChatStreamHandle, type OpenChatStreamOptions } from './ChatStream.js';\nimport type {\n AnswerChatQuestionRequest,\n AnswerChatQuestionResponse,\n CancelChatTurnResponse,\n ChatFeedbackEnvelope,\n ChatScheduleEnvelope,\n ChatScope,\n ConfirmChatToolCallRequest,\n ConfirmChatToolCallResponse,\n CreateChatScheduleRequest,\n CreateChatSessionRequest,\n CreateChatSessionResponse,\n DebugPayload,\n GetChatSessionResponse,\n ListChatFeedbackResponse,\n ListChatSchedulesResponse,\n ListChatScheduleRunsResponse,\n RerunScheduleOccurrenceResponse,\n ListChatSessionsQuery,\n ListChatSessionsResponse,\n PostChatMessageRequest,\n PostChatMessageResponse,\n SubmitChatFeedbackRequest,\n UpdateChatScheduleRequest,\n} from './types.js';\n\nconst BASE_PATH = '/api/agentengine/v1/agent/chat/sessions';\n\nfunction scopeHeaders(scope: ChatScope): Record<string, string> {\n const sandboxId = scope.sandboxId ?? scope.repoId ?? '';\n const projectId = scope.projectId ?? scope.workspaceId;\n const headers: Record<string, string> = {\n 'X-Org-Id': scope.orgId,\n 'X-User-Id': scope.userId,\n 'X-Sandbox-Id': sandboxId,\n 'X-Repo-Id': sandboxId,\n };\n if (projectId) {\n headers['X-Project-Id'] = projectId;\n headers['X-Workspace-Id'] = projectId;\n }\n return headers;\n}\n\nclass ChatSessionsScope {\n constructor(private readonly http: BaseClient) {}\n\n create(scope: ChatScope, body: CreateChatSessionRequest): Promise<CreateChatSessionResponse> {\n return this.http.post<CreateChatSessionResponse>(BASE_PATH, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n list(scope: ChatScope, query: ListChatSessionsQuery = {}): Promise<ListChatSessionsResponse> {\n return this.http.get<ListChatSessionsResponse>(BASE_PATH, {\n query,\n headers: scopeHeaders(scope),\n });\n }\n\n get(scope: ChatScope, conversationId: string): Promise<GetChatSessionResponse> {\n return this.http.get<GetChatSessionResponse>(`${BASE_PATH}/${conversationId}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n delete(scope: ChatScope, conversationId: string): Promise<void> {\n return this.http.delete<void>(`${BASE_PATH}/${conversationId}`, {\n headers: scopeHeaders(scope),\n });\n }\n}\n\nclass ChatMessagesScope {\n constructor(private readonly http: BaseClient) {}\n\n post(scope: ChatScope, conversationId: string, body: PostChatMessageRequest): Promise<PostChatMessageResponse> {\n return this.http.post<PostChatMessageResponse>(`${BASE_PATH}/${conversationId}/messages`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Interrupts an in-flight chat-loop turn. The engine cancels the turn's\n * Go context and asks the sandbox service to kill any in-flight docker\n * exec inside the per-session container (the container itself survives\n * so the next turn keeps its filesystem state). Returns 404 when no\n * turn matches `turnId` — covers the race where the user clicks Stop\n * just after the turn already finished.\n *\n * The engine still emits a terminal `done` SSE event with\n * status=\"context_cancelled\" after this returns; the frontend should\n * render its \"Cancelled\" marker on that event rather than on this\n * response, so a reload mid-cancel still ends in the same UI state.\n */\n cancel(scope: ChatScope, conversationId: string, turnId: string): Promise<CancelChatTurnResponse> {\n return this.http.post<CancelChatTurnResponse>(\n `${BASE_PATH}/${conversationId}/messages/${turnId}/cancel`,\n { headers: scopeHeaders(scope) },\n );\n }\n\n /**\n * Deliver the user's allow/deny decision on an M3 confirmation modal\n * (fired when the policy hook emits a\n * `tool_call_confirmation_required` SSE event). The chat-loop has\n * suspended waiting on this call; on allow it dispatches the tool, on\n * deny it synthesises a \"DENIED:\" tool result so the model can react.\n * Returns 404 when no pending confirmation exists for the given\n * (turn, tool_call) — usually means the 4-minute confirmer timeout\n * already elapsed.\n */\n confirmToolCall(\n scope: ChatScope,\n conversationId: string,\n turnId: string,\n toolCallId: string,\n body: ConfirmChatToolCallRequest,\n ): Promise<ConfirmChatToolCallResponse> {\n return this.http.post<ConfirmChatToolCallResponse>(\n `${BASE_PATH}/${conversationId}/messages/${turnId}/confirm/${toolCallId}`,\n { body, headers: scopeHeaders(scope) },\n );\n }\n}\n\nclass ChatQuestionsScope {\n constructor(private readonly http: BaseClient) {}\n\n answer(\n scope: ChatScope,\n conversationId: string,\n turnId: string,\n body: AnswerChatQuestionRequest,\n ): Promise<AnswerChatQuestionResponse> {\n return this.http.post<AnswerChatQuestionResponse>(\n `${BASE_PATH}/${conversationId}/messages/${turnId}/answers`,\n { body, headers: scopeHeaders(scope) },\n );\n }\n}\n\n/**\n * Debug scope — fetches the consolidated payload (session, messages) used by\n * the dashboard Debug tab. Keyed by conversation ID.\n */\nclass ChatDebugScope {\n constructor(private readonly http: BaseClient) {}\n\n getByConversation(scope: ChatScope, conversationId: string): Promise<DebugPayload> {\n return this.http.get<DebugPayload>(`${BASE_PATH}/${conversationId}/debug`, {\n headers: scopeHeaders(scope),\n });\n }\n}\n\n/**\n * Schedules scope — manages the M3 Stage 4 cron-driven prompt\n * schedules. Repo-scoped: list / create / get / update / delete are\n * keyed by (repo, schedule_id). The dispatcher fires due schedules\n * server-side on its tick; the SDK only handles the CRUD surface.\n *\n * Endpoint shape:\n * GET /v1/agent/repos/:repo_id/schedules\n * POST /v1/agent/repos/:repo_id/schedules\n * GET /v1/agent/repos/:repo_id/schedules/:id\n * PUT /v1/agent/repos/:repo_id/schedules/:id\n * DELETE /v1/agent/repos/:repo_id/schedules/:id\n */\nclass ChatSchedulesScope {\n constructor(private readonly http: BaseClient) {}\n\n private repoPath(scope: ChatScope): string {\n const repoID = scope.sandboxId ?? scope.repoId ?? '';\n return `/api/agentengine/v1/agent/repos/${repoID}/schedules`;\n }\n\n list(scope: ChatScope): Promise<ListChatSchedulesResponse> {\n return this.http.get<ListChatSchedulesResponse>(this.repoPath(scope), {\n headers: scopeHeaders(scope),\n });\n }\n\n create(scope: ChatScope, body: CreateChatScheduleRequest): Promise<ChatScheduleEnvelope> {\n return this.http.post<ChatScheduleEnvelope>(this.repoPath(scope), {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n get(scope: ChatScope, scheduleId: string): Promise<ChatScheduleEnvelope> {\n return this.http.get<ChatScheduleEnvelope>(`${this.repoPath(scope)}/${scheduleId}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n update(\n scope: ChatScope,\n scheduleId: string,\n body: UpdateChatScheduleRequest,\n ): Promise<ChatScheduleEnvelope> {\n return this.http.put<ChatScheduleEnvelope>(`${this.repoPath(scope)}/${scheduleId}`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n delete(scope: ChatScope, scheduleId: string): Promise<{ status: 'deleted' }> {\n return this.http.delete<{ status: 'deleted' }>(`${this.repoPath(scope)}/${scheduleId}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * List recent chat sessions spawned by a schedule's cron tick — used\n * by the SchedulesTab \"Runs\" panel to surface real audit trail\n * instead of dumping the user into the global chat list.\n *\n * Each entry is a full ChatSession row; `.id` is the conversation id\n * the dashboard navigates to (`/chat/:conversationId`). All rows are\n * unattended (the scheduler is the only writer of `schedule_id`),\n * which makes the chat session viewer render the \"Scheduled run\"\n * ribbon and hide the composer.\n *\n * Server returns the 50 most-recent rows; no cursor pagination in\n * v1 (deferred until the long-tail audit case proves real).\n */\n listRuns(scope: ChatScope, scheduleId: string): Promise<ListChatScheduleRunsResponse> {\n return this.http.get<ListChatScheduleRunsResponse>(\n `${this.repoPath(scope)}/${scheduleId}/runs`,\n { headers: scopeHeaders(scope) },\n );\n }\n\n /**\n * Manually re-run ONE occurrence of a product schedule (SHR-IP06 §6 item 4 /\n * REV-07) — the owner's explicit recovery of a superseded/expired occurrence,\n * or any due window they choose to re-run. `dueWindow` is the occurrence's\n * scheduled instant (RFC3339); the server derives the occurrence key from\n * (schedule, dueWindow), so a re-run against an in-flight occurrence coalesces\n * to one run. The run is asynchronous — the server returns 202 with the\n * derived `occurrence_key`.\n */\n rerunOccurrence(\n scope: ChatScope,\n scheduleId: string,\n dueWindow: string,\n ): Promise<RerunScheduleOccurrenceResponse> {\n return this.http.post<RerunScheduleOccurrenceResponse>(\n `${this.repoPath(scope)}/${scheduleId}/rerun`,\n { body: { due_window: dueWindow }, headers: scopeHeaders(scope) },\n );\n }\n}\n\n/**\n * Feedback scope — a user's \"Satisfied? Yes/No\" rating + optional comment on a\n * chat session, and the list of feedback recorded for it (so the UI can\n * pre-fill and so an org admin can review past ratings). Conversation-scoped;\n * pass `turn_id` in the body to scope feedback to a single turn.\n *\n * Endpoint shape:\n * POST /v1/agent/chat/sessions/:id/feedback\n * GET /v1/agent/chat/sessions/:id/feedback\n */\nclass ChatFeedbackScope {\n constructor(private readonly http: BaseClient) {}\n\n submit(\n scope: ChatScope,\n conversationId: string,\n body: SubmitChatFeedbackRequest,\n ): Promise<ChatFeedbackEnvelope> {\n return this.http.post<ChatFeedbackEnvelope>(`${BASE_PATH}/${conversationId}/feedback`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n list(scope: ChatScope, conversationId: string): Promise<ListChatFeedbackResponse> {\n return this.http.get<ListChatFeedbackResponse>(`${BASE_PATH}/${conversationId}/feedback`, {\n headers: scopeHeaders(scope),\n });\n }\n}\n\nexport class ChatClient {\n readonly sessions: ChatSessionsScope;\n readonly messages: ChatMessagesScope;\n readonly questions: ChatQuestionsScope;\n readonly debug: ChatDebugScope;\n readonly schedules: ChatSchedulesScope;\n readonly feedback: ChatFeedbackScope;\n\n constructor(\n private readonly http: BaseClient,\n private readonly streamDeps: { baseUrl: string; getToken?: TokenProvider },\n ) {\n this.sessions = new ChatSessionsScope(http);\n this.messages = new ChatMessagesScope(http);\n this.questions = new ChatQuestionsScope(http);\n this.debug = new ChatDebugScope(http);\n this.schedules = new ChatSchedulesScope(http);\n this.feedback = new ChatFeedbackScope(http);\n }\n\n openStream(options: OpenChatStreamOptions): Promise<ChatStreamHandle> {\n return openChatStream(this.streamDeps, options);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n CreateAgentTemplateRequest,\n ListAgentTemplatesQuery,\n ListAgentTemplatesResponse,\n SimpleAgentResponse,\n Template,\n} from './types.js';\n\nconst BASE_PATH = '/api/agentengine/v1/agent/templates';\n\nexport class TemplatesClient {\n constructor(private readonly http: BaseClient) {}\n\n list(query: ListAgentTemplatesQuery = {}): Promise<ListAgentTemplatesResponse> {\n return this.http.get<ListAgentTemplatesResponse>(BASE_PATH, { query });\n }\n\n create(body: CreateAgentTemplateRequest): Promise<Template> {\n return this.http.post<Template>(BASE_PATH, { body });\n }\n\n delete(templateId: string): Promise<SimpleAgentResponse> {\n return this.http.delete<SimpleAgentResponse>(`${BASE_PATH}/${templateId}`);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n CreateScheduledTaskRequest,\n ListScheduledTasksQuery,\n ListScheduledTasksResponse,\n ScheduledTask,\n SimpleAgentResponse,\n} from './types.js';\n\nconst BASE_PATH = '/api/agentengine/v1/agent/scheduled-tasks';\n\nexport class ScheduledTasksClient {\n constructor(private readonly http: BaseClient) {}\n\n list(query: ListScheduledTasksQuery): Promise<ListScheduledTasksResponse> {\n return this.http.get<ListScheduledTasksResponse>(BASE_PATH, { query });\n }\n\n create(body: CreateScheduledTaskRequest): Promise<ScheduledTask> {\n return this.http.post<ScheduledTask>(BASE_PATH, { body });\n }\n\n delete(taskId: string, orgId: string): Promise<SimpleAgentResponse> {\n return this.http.delete<SimpleAgentResponse>(`${BASE_PATH}/${taskId}`, {\n query: { org_id: orgId },\n });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n AcquireScanLeaseRequest,\n AcquireScanLeaseResponse,\n ListScanHistoryQuery,\n ListScanHistoryResponse,\n PeekScanLeaseResponse,\n ResourceTreeQuery,\n ResourceTreeResponse,\n SubgraphRequest,\n SubgraphResponse,\n} from './types.js';\n\nexport class ResourcesClient {\n constructor(private readonly http: BaseClient) {}\n\n getTree(repoId: string, query?: ResourceTreeQuery): Promise<ResourceTreeResponse> {\n const params = new URLSearchParams();\n const search = query?.search?.trim();\n if (search) params.set('search', search);\n if (query?.showDefault === true) params.set('showDefault', 'true');\n const qs = params.size > 0 ? `?${params.toString()}` : '';\n return this.http.get<ResourceTreeResponse>(`/repos/${repoId}/resources/tree${qs}`);\n }\n\n /**\n * BFS-walks the dependency graph starting from `seedResourceIds` (or\n * `seedNameTokens`) and returns the matching nodes + edges. Use this\n * to render an inbound/outbound dependency view for a selected\n * resource. The server caps the result at maxNodes (default 80,\n * hard cap 200) and sets `truncated` when the cap was hit.\n */\n getSubgraph(repoId: string, request: SubgraphRequest): Promise<SubgraphResponse> {\n return this.http.post<SubgraphResponse>(`/repos/${repoId}/resources/subgraph`, { body: request });\n }\n\n /**\n * Returns recent scan history for a repo, optionally filtered by\n * credential. Backed by CloudScanHistory rows written when the\n * agent's discovery orchestrator releases a lease (or when the\n * backend's cleanup job sweeps an expired one). Use this to render\n * \"last refreshed N min ago\" badges and per-scope add/remove counts\n * next to the resource tree.\n */\n listScans(repoId: string, query?: ListScanHistoryQuery): Promise<ListScanHistoryResponse> {\n const params = new URLSearchParams();\n if (query?.credentialId) params.set('credentialId', query.credentialId);\n if (query?.limit != null) params.set('limit', String(query.limit));\n const qs = params.size > 0 ? `?${params.toString()}` : '';\n return this.http.get<ListScanHistoryResponse>(`/repos/${repoId}/scans${qs}`);\n }\n\n /**\n * Peeks the active scan lease (if any) for the given credential. Used\n * by the dashboard to display a \"scan in progress\" badge without\n * attempting to acquire the lease. Returns `lease: null` when no\n * scan is running. Expired leases are returned with their stale\n * timestamps — callers should compare `expiresAt` to `Date.now()`\n * before treating them as active.\n */\n peekScanLease(repoId: string, credentialId: string): Promise<PeekScanLeaseResponse> {\n const params = new URLSearchParams();\n params.set('credentialId', credentialId);\n return this.http.get<PeekScanLeaseResponse>(`/repos/${repoId}/scans/lease?${params.toString()}`);\n }\n\n /**\n * Attempts to claim a scan lease. Returns the acquired lease on\n * success. The server responds 409 with a `ScanInProgressError`-\n * shaped body when another scan is already in flight — callers\n * should catch the HttpError, parse the body, and surface a polite\n * \"another scan is running\" notice rather than retry automatically.\n *\n * NOTE: routine use is the agent's job. The dashboard typically only\n * calls peekScanLease + listScans; this method is exposed for power-\n * user tooling and automated test harnesses.\n */\n acquireScanLease(repoId: string, request: AcquireScanLeaseRequest): Promise<AcquireScanLeaseResponse> {\n return this.http.post<AcquireScanLeaseResponse>(`/repos/${repoId}/scans/lease`, { body: request });\n }\n}\n","export interface SystemEvent {\n id: number;\n timestamp: string;\n contextId: string;\n context: string;\n event: string;\n orgId: string;\n userId: string;\n userName: string;\n userEmail: string;\n projectId: string | null;\n jsonData: string | null;\n showUnread: boolean;\n}\n\nexport interface WireSystemEvent extends Omit<SystemEvent, 'projectId'> {\n workspaceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface SystemEventQuery {\n from_timestamp?: number;\n to_timestamp?: number;\n contextId?: string;\n context?: string;\n event?: string;\n userId?: string;\n projectId?: string;\n /** @deprecated use `projectId` */\n workspaceId?: string;\n showUnread?: boolean;\n skip?: number;\n take?: number;\n}\n\nexport interface SystemEventQueryResponse {\n events: SystemEvent[];\n total: number;\n skip: number;\n take: number;\n}\n\nexport interface SystemEventReadResponse {\n success: true;\n}\n\nexport function normalizeSystemEvent(wire: WireSystemEvent): SystemEvent {\n return {\n id: wire.id,\n timestamp: wire.timestamp,\n contextId: wire.contextId,\n context: wire.context,\n event: wire.event,\n orgId: wire.orgId,\n userId: wire.userId,\n userName: wire.userName,\n userEmail: wire.userEmail,\n projectId: wire.projectId ?? wire.workspaceId ?? null,\n jsonData: wire.jsonData ?? null,\n showUnread: wire.showUnread,\n };\n}\n\n// TODO(backend-cleanup): cloud-agent-backend/internal/domain/types.go SystemEvent\n// still emits `workspaceId`. When that becomes `projectId`, this normalizer\n// collapses to identity.\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport {\n normalizeSystemEvent,\n SystemEventQuery,\n SystemEventQueryResponse,\n SystemEventReadResponse,\n WireSystemEvent,\n} from './types.js';\n\ninterface WireQueryResponse {\n events: WireSystemEvent[];\n total: number;\n skip: number;\n take: number;\n}\n\nexport class SystemEventsClient {\n constructor(private readonly http: BaseClient) {}\n\n async query(body: SystemEventQuery): Promise<SystemEventQueryResponse> {\n const wire = await this.http.post<WireQueryResponse>('/systemevent', { body });\n return {\n events: (wire.events ?? []).map(normalizeSystemEvent),\n total: wire.total ?? 0,\n skip: wire.skip ?? 0,\n take: wire.take ?? 0,\n };\n }\n\n markRead(eventIdOrIds: number | number[]): Promise<SystemEventReadResponse> {\n const body = Array.isArray(eventIdOrIds) ? { ids: eventIdOrIds } : { id: eventIdOrIds };\n return this.http.post<SystemEventReadResponse>('/systemevent/read', { body });\n }\n\n markUnread(eventIdOrIds: number | number[]): Promise<SystemEventReadResponse> {\n const body = Array.isArray(eventIdOrIds) ? { ids: eventIdOrIds } : { id: eventIdOrIds };\n return this.http.delete<SystemEventReadResponse>('/systemevent/read', { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n BuySubscriptionRequest,\n BuySubscriptionResponse,\n CancelSubscriptionResponse,\n ListPaymentsResponse,\n OrgSubscription,\n Payment,\n PreviewChangeRequest,\n PreviewChangeResponse,\n Subscription,\n} from './types.js';\n\nexport class SubscriptionsClient {\n constructor(private readonly http: BaseClient) {}\n\n async listCatalog(): Promise<Subscription[]> {\n const res = await this.http.get<{ success: boolean; data: Subscription[] }>('/subscriptions', { skipAuth: true });\n return res.data ?? [];\n }\n\n async getMine(): Promise<OrgSubscription | null> {\n const res = await this.http.get<{ success: boolean; data: OrgSubscription | null }>('/subscriptions/my');\n return res.data ?? null;\n }\n\n buy(body: BuySubscriptionRequest): Promise<BuySubscriptionResponse> {\n return this.http.post<BuySubscriptionResponse>('/subscriptions/buy', { body });\n }\n\n /**\n * Preview the cost/credit impact of a plan change (pro-rated charge,\n * credit delta, effective dates) for the confirmation modal — no change\n * is made. kind=\"new\" means a first purchase that would go via Checkout.\n */\n previewChange(body: PreviewChangeRequest): Promise<PreviewChangeResponse> {\n return this.http.post<PreviewChangeResponse>('/subscriptions/preview-change', { body });\n }\n\n cancel(): Promise<CancelSubscriptionResponse> {\n return this.http.post<CancelSubscriptionResponse>('/subscriptions/cancel', {});\n }\n\n async listPayments(): Promise<Payment[]> {\n const res = await this.http.get<ListPaymentsResponse>('/subscriptions/payments');\n return res.data ?? [];\n }\n\n /** Stripe-hosted billing portal URL. */\n async portal(): Promise<{ url: string }> {\n const res = await this.http.post<{ success: boolean; data: { url: string } }>('/subscriptions/portal', {});\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n BuyCreditPackRequest,\n BuyCreditPackResponse,\n BuyCustomCreditRequest,\n BuyCustomCreditResponse,\n CreditBalance,\n CreditPack,\n CustomCreditPurchaseConfig,\n ListCreditsTransactionsQuery,\n ListCreditsTransactionsResponse,\n MonthlyCreditStats,\n} from './types.js';\n\nexport class CreditsClient {\n constructor(private readonly http: BaseClient) {}\n\n async getBalance(): Promise<CreditBalance> {\n const res = await this.http.get<{ success: boolean; data: CreditBalance }>('/credits/balance');\n return unwrapData(res);\n }\n\n listTransactions(query: ListCreditsTransactionsQuery = {}): Promise<ListCreditsTransactionsResponse> {\n return this.http.get<ListCreditsTransactionsResponse>('/credits/transactions', { query });\n }\n\n /** Per-month credit activity (consumption / purchases / grants). */\n async getMonthlyStats(): Promise<MonthlyCreditStats[]> {\n const res = await this.http.get<{ success: boolean; data: MonthlyCreditStats[] }>('/credits/stats/monthly');\n return res.data ?? [];\n }\n\n /** Fixed credit-pack catalog. Public endpoint. */\n async listPacks(): Promise<CreditPack[]> {\n const res = await this.http.get<{ success: boolean; data: CreditPack[] }>('/credits/packs', { skipAuth: true });\n return res.data ?? [];\n }\n\n /**\n * Buy a fixed credit pack. Requires an active paid subscription\n * (the backend 403s free-tier orgs with SUBSCRIPTION_REQUIRED) and\n * caps purchases per pack per billing cycle. Returns a Stripe\n * Checkout URL to redirect to.\n */\n buyPack(body: BuyCreditPackRequest): Promise<BuyCreditPackResponse> {\n return this.http.post<BuyCreditPackResponse>('/credits/packs/buy', { body });\n }\n\n /**\n * \"Other amount\" PAYG config — bounds + presets for the\n * arbitrary-dollar tile. Public endpoint; returns a disabled\n * shape (`enabled: false`) when the feature is off so the\n * frontend can hide the tile without throwing.\n */\n async getCustomConfig(): Promise<CustomCreditPurchaseConfig> {\n const res = await this.http.get<{ success: boolean; data: CustomCreditPurchaseConfig }>('/credits/packs/custom-config');\n return unwrapData(res);\n }\n\n /**\n * Buy an arbitrary-dollar PAYG amount. The Stripe Checkout\n * session is built with `price_data` inline (no pre-created\n * Price), so the catalog has nothing to provision for this — it\n * is purely a per-purchase flow.\n */\n buyCustom(body: BuyCustomCreditRequest): Promise<BuyCustomCreditResponse> {\n return this.http.post<BuyCustomCreditResponse>('/credits/packs/buy-custom', { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n GetUsageSummaryQuery,\n GetUsageSummaryResponse,\n UsageByModelQuery,\n UsageByModelResponse,\n UsageReportQuery,\n UsageReportResponse,\n UsageSummaryQuery,\n UsageSummaryResponse,\n} from './types.js';\n\nconst LEGACY_AGENT_PATH = '/api/agentengine/v1/usage'; // legacy proxy path\nconst SCOPED_BASE = '/usage'; // new backend-scoped surface (RBAC + scope routing)\n\nexport class UsageClient {\n constructor(private readonly http: BaseClient) {}\n\n // ── legacy ─────────────────────────────────────────────────────────────────\n // Existing Settings → Usage page calls this. Kept for back-compat until the\n // new dashboard fully replaces the JSON dump.\n getSummary(query: GetUsageSummaryQuery): Promise<GetUsageSummaryResponse> {\n return this.http.get<GetUsageSummaryResponse>(`${LEGACY_AGENT_PATH}/summary`, { query });\n }\n\n // ── new scoped surface ─────────────────────────────────────────────────────\n // Hits the backend-side RBAC wrapper; the backend re-injects the scope id\n // into the agent query so we don't have to.\n org(query: UsageSummaryQuery = {}): Promise<UsageSummaryResponse> {\n return this.http.get(`${SCOPED_BASE}/org`, { query: query as Record<string, string> });\n }\n project(projectId: string, query: UsageSummaryQuery = {}): Promise<UsageSummaryResponse> {\n return this.http.get(`${SCOPED_BASE}/project/${encodeURIComponent(projectId)}`, { query: query as Record<string, string> });\n }\n sandbox(sandboxId: string, query: UsageSummaryQuery = {}): Promise<UsageSummaryResponse> {\n return this.http.get(`${SCOPED_BASE}/sandbox/${encodeURIComponent(sandboxId)}`, { query: query as Record<string, string> });\n }\n chat(chatId: string, query: UsageSummaryQuery = {}): Promise<UsageSummaryResponse> {\n return this.http.get(`${SCOPED_BASE}/chat/${encodeURIComponent(chatId)}`, { query: query as Record<string, string> });\n }\n\n // Each report variant exists so the dashboard chart can request hourly /\n // daily buckets without leaking scope routing into the caller.\n orgReport(query: UsageReportQuery = {}): Promise<UsageReportResponse> {\n return this.http.get(`${SCOPED_BASE}/org`, { query: { ...(query as Record<string, string>), kind: 'report' } });\n }\n projectReport(projectId: string, query: UsageReportQuery = {}): Promise<UsageReportResponse> {\n return this.http.get(`${SCOPED_BASE}/project/${encodeURIComponent(projectId)}`, { query: { ...(query as Record<string, string>), kind: 'report' } });\n }\n sandboxReport(sandboxId: string, query: UsageReportQuery = {}): Promise<UsageReportResponse> {\n return this.http.get(`${SCOPED_BASE}/sandbox/${encodeURIComponent(sandboxId)}`, { query: { ...(query as Record<string, string>), kind: 'report' } });\n }\n chatReport(chatId: string, query: UsageReportQuery = {}): Promise<UsageReportResponse> {\n return this.http.get(`${SCOPED_BASE}/chat/${encodeURIComponent(chatId)}`, { query: { ...(query as Record<string, string>), kind: 'report' } });\n }\n\n // Per-model breakdown — drives the table under the bar chart.\n orgByModel(query: UsageByModelQuery = {}): Promise<UsageByModelResponse> {\n return this.http.get(`${SCOPED_BASE}/org`, { query: { ...(query as Record<string, string>), kind: 'by_model' } });\n }\n projectByModel(projectId: string, query: UsageByModelQuery = {}): Promise<UsageByModelResponse> {\n return this.http.get(`${SCOPED_BASE}/project/${encodeURIComponent(projectId)}`, { query: { ...(query as Record<string, string>), kind: 'by_model' } });\n }\n sandboxByModel(sandboxId: string, query: UsageByModelQuery = {}): Promise<UsageByModelResponse> {\n return this.http.get(`${SCOPED_BASE}/sandbox/${encodeURIComponent(sandboxId)}`, { query: { ...(query as Record<string, string>), kind: 'by_model' } });\n }\n chatByModel(chatId: string, query: UsageByModelQuery = {}): Promise<UsageByModelResponse> {\n return this.http.get(`${SCOPED_BASE}/chat/${encodeURIComponent(chatId)}`, { query: { ...(query as Record<string, string>), kind: 'by_model' } });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n ActReceiptLinesResponse,\n ActRunsResponse,\n ActionApproversResponse,\n ActionClassesResponse,\n ActionPoliciesResponse,\n ActionPolicyEventsResponse,\n ApprovalStats,\n ApprovalsScope,\n DeleteActionPolicyRequest,\n ListApprovalsQuery,\n ListApprovalsResponse,\n PendingAction,\n PolicyScopeType,\n RebindApprovalResponse,\n ResolveApprovalRequest,\n ResolveApprovalResponse,\n ResolveBatchRequest,\n ResolveBatchResponse,\n ResolveOutcomeRequest,\n ResolveOutcomeResponse,\n SetActionApproversRequest,\n SetActionPolicyRequest,\n} from './types.js';\n\n/**\n * Action Policy client.\n *\n * Two API families, gated in different places, because the engine never sees\n * org roles:\n *\n * - the QUEUE (read, resolve, batch, class registry) is member-level and goes\n * straight through the wildcard agent-engine proxy;\n * - POLICY and APPROVER writes are org-admin-only and go through thin backend\n * routes, because that is where roles live. The proxy denies the equivalent\n * engine paths, so these methods are the only way in.\n */\nconst QUEUE_BASE = '/api/agentengine/v1/agent';\nconst ORG_BASE = '/organization';\n\nfunction scopeHeaders(scope: ApprovalsScope): Record<string, string> {\n const headers: Record<string, string> = {\n 'X-Org-Id': scope.orgId,\n 'X-User-Id': scope.userId,\n };\n if (scope.sandboxId) {\n headers['X-Sandbox-Id'] = scope.sandboxId;\n headers['X-Repo-Id'] = scope.sandboxId;\n }\n return headers;\n}\n\nfunction queryString(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n}\n\nexport class ApprovalsClient {\n constructor(private readonly http: BaseClient) {}\n\n // ── queue (member-level) ────────────────────────────────────────────────\n\n /** List queue entries and execution receipts. `tool_args` is omitted here. */\n list(scope: ApprovalsScope, query: ListApprovalsQuery = {}): Promise<ListApprovalsResponse> {\n return this.http.get(`${QUEUE_BASE}/approvals${queryString({ ...query })}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /** Queue telemetry — powers the sidebar badge and the health view. */\n stats(scope: ApprovalsScope): Promise<ApprovalStats> {\n return this.http.get(`${QUEUE_BASE}/approvals/stats`, { headers: scopeHeaders(scope) });\n }\n\n /** Full detail for one entry, including the frozen `tool_args`. */\n get(scope: ApprovalsScope, id: string): Promise<PendingAction> {\n return this.http.get(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Approve or reject one entry.\n *\n * Throws on 409 when somebody else already resolved it; the response body\n * carries the status it actually has now, so the caller should refetch\n * rather than retry.\n */\n resolve(\n scope: ApprovalsScope,\n id: string,\n body: ResolveApprovalRequest,\n ): Promise<ResolveApprovalResponse> {\n return this.http.post(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}/resolve`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Point a PENDING artifact-backed action at a newer version of the same\n * artifact — the edit-under-queue rebind.\n *\n * An explicit one-click act, not something that happens on every save: the\n * old proposal's frozen payload is never mutated. The old row is cancelled\n * and a new one inserted IN ONE TRANSACTION, so a partial failure can never\n * leave two live approvals for one intent.\n *\n * `newHandle` is the handle of the version to send instead. 409 means\n * somebody resolved the old row first; 400 means it carries no artifact.\n */\n rebind(scope: ApprovalsScope, id: string, newHandle: string): Promise<RebindApprovalResponse> {\n return this.http.post(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}/rebind`, {\n body: { new_handle: newHandle },\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Resolve many entries at once. Per-entry outcomes: an id somebody else\n * already resolved lands in `skipped` rather than failing the batch.\n */\n resolveBatch(scope: ApprovalsScope, body: ResolveBatchRequest): Promise<ResolveBatchResponse> {\n return this.http.post(`${QUEUE_BASE}/approvals/resolve-batch`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Per-destination receipt lines for one entry — the durable ledger behind\n * the receipt's `destinations` array. Each line carries the evidence level\n * the destination actually earned, never a bare \"delivered\".\n */\n receiptLines(scope: ApprovalsScope, id: string): Promise<ActReceiptLinesResponse> {\n return this.http.get(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}/receipt-lines`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Close an `outcome_unknown` entry through the closed manual-resolution\n * set: confirmed-effect, confirmed-no-effect, or abandoned. The note is\n * required — the engine rejects an empty one with 400. Throws on 409\n * `already_resolved` when somebody else closed it first; the body carries\n * the status it actually has now, so refetch rather than retry.\n */\n resolveOutcome(\n scope: ApprovalsScope,\n id: string,\n body: ResolveOutcomeRequest,\n ): Promise<ResolveOutcomeResponse> {\n return this.http.post(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}/resolve-outcome`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n /** Recent act-run occurrence records — the per-trigger execution ledger. */\n listRuns(scope: ApprovalsScope, limit?: number): Promise<ActRunsResponse> {\n return this.http.get(`${QUEUE_BASE}/act-runs${queryString({ limit })}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * The compiled class registry. Pass a sandbox id to also resolve each\n * class's effective policy for that scope chain.\n */\n listClasses(scope: ApprovalsScope, sandboxId?: string): Promise<ActionClassesResponse> {\n return this.http.get(`${QUEUE_BASE}/action-classes${queryString({ repo_id: sandboxId })}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /** Policy audit history, newest first. */\n listPolicyEvents(scope: ApprovalsScope, limit?: number): Promise<ActionPolicyEventsResponse> {\n return this.http.get(`${QUEUE_BASE}/action-policy-events${queryString({ limit })}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n // ── policy configuration (org-admin, via backend) ───────────────────────\n\n /** Read the per-scope overrides at one scope. */\n getPolicies(scopeType: PolicyScopeType, scopeId: string): Promise<ActionPoliciesResponse> {\n return this.http.get(\n `${ORG_BASE}/action-policies${queryString({ scope_type: scopeType, scope_id: scopeId })}`,\n );\n }\n\n /**\n * Set one class's state at a scope.\n *\n * Rejected with 422 `loosens_parent` when the value would widen autonomy\n * relative to the scopes above it: a child may only tighten.\n */\n setPolicy(body: SetActionPolicyRequest): Promise<{ ok: boolean }> {\n return this.http.put(`${ORG_BASE}/action-policies`, { body });\n }\n\n /** Remove an override so the class inherits again. */\n clearPolicy(body: DeleteActionPolicyRequest): Promise<{ ok: boolean }> {\n return this.http.delete(`${ORG_BASE}/action-policies`, { body });\n }\n\n /** The ordered escalation list. */\n getApprovers(): Promise<ActionApproversResponse> {\n return this.http.get(`${ORG_BASE}/action-approvers`);\n }\n\n /** Replace the escalation list; array order is the escalation order. */\n setApprovers(body: SetActionApproversRequest): Promise<{ ok: boolean }> {\n return this.http.put(`${ORG_BASE}/action-approvers`, { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n ChatBudget,\n EffectiveChatBudget,\n OrgBudget,\n ScopedBudget,\n UpdateChatBudgetRequest,\n UpdateCostLimitRequest,\n UpdateOrgBudgetRequest,\n UpdateScopedBudgetRequest,\n} from './types.js';\n\n// Backend routes hang off the root authed group — see internal/http/routes/budgets\n// in cloud-agent-backend. The backend resolves project_id → sandbox_id mapping\n// and handles RBAC; the frontend just hands it the scope ids.\nconst BASE = '/budgets';\n\nexport class BudgetsClient {\n constructor(private readonly http: BaseClient) {}\n\n // ── org ──\n getOrg(): Promise<{ budget: OrgBudget }> {\n return this.http.get(`${BASE}/org`);\n }\n updateOrg(body: UpdateOrgBudgetRequest): Promise<{ budget: OrgBudget; message: string }> {\n return this.http.put(`${BASE}/org`, { body });\n }\n\n // ── project (workspace) ──\n getProject(projectId: string): Promise<{ budget: ScopedBudget }> {\n return this.http.get(`${BASE}/project/${encodeURIComponent(projectId)}`);\n }\n updateProject(projectId: string, body: UpdateScopedBudgetRequest): Promise<{ budget: ScopedBudget; message: string }> {\n return this.http.put(`${BASE}/project/${encodeURIComponent(projectId)}`, { body });\n }\n\n // ── sandbox (repo) ──\n getSandbox(sandboxId: string): Promise<{ budget: ScopedBudget }> {\n return this.http.get(`${BASE}/sandbox/${encodeURIComponent(sandboxId)}`);\n }\n updateSandbox(sandboxId: string, body: UpdateScopedBudgetRequest): Promise<{ budget: ScopedBudget; message: string }> {\n return this.http.put(`${BASE}/sandbox/${encodeURIComponent(sandboxId)}`, { body });\n }\n\n // ── chat session ──\n getChat(chatId: string): Promise<{ budget: ChatBudget }> {\n return this.http.get(`${BASE}/chat/${encodeURIComponent(chatId)}`);\n }\n updateChat(chatId: string, body: UpdateChatBudgetRequest): Promise<{ message: string }> {\n return this.http.put(`${BASE}/chat/${encodeURIComponent(chatId)}`, { body });\n }\n // Resolves chat → sandbox → project → org and returns the first non-zero\n // per-chat USD cap plus the level it came from. Powers the chat header\n // budget badge — UI labels inherited values.\n getEffectiveChat(chatId: string): Promise<EffectiveChatBudget> {\n return this.http.get(`${BASE}/chat/${encodeURIComponent(chatId)}/effective`);\n }\n\n // ── per-template / per-scheduled USD caps ──\n updateTemplateCostLimit(templateId: string, body: UpdateCostLimitRequest) {\n return this.http.put(`${BASE}/template/${encodeURIComponent(templateId)}/cost_limit`, { body });\n }\n updateScheduleCostLimit(scheduleId: string, body: UpdateCostLimitRequest) {\n return this.http.put(`${BASE}/schedule/${encodeURIComponent(scheduleId)}/cost_limit`, { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type { ProviderCapConfig, SetProviderCapRequest } from './types.js';\n\n// SHR-IP08 per-provider cap configuration. Backend routes hang off the root\n// authed group — see internal/http/routes/provider_caps in cloud-agent-backend.\n// The LIST is a member read; SET and DELETE are admin-only (the backend gates\n// them in-handler and blocks them under impersonation). The org is taken from\n// the session, never a request field.\nconst BASE = '/provider-caps';\n\nexport class MeteringClient {\n constructor(private readonly http: BaseClient) {}\n\n /** List the org's configured per-provider caps. Empty when none are set —\n * every unset provider is the MM-O021 owner gate, not a zero cap. */\n async listCaps(): Promise<ProviderCapConfig[]> {\n const res = await this.http.get<{ items: ProviderCapConfig[] }>(BASE);\n return res.items ?? [];\n }\n\n /** Set (or replace) one provider's cap. Admin-only. The server refuses a\n * non-positive limit or a cap with no scope / reset clock (400). */\n async setCap(provider: string, body: SetProviderCapRequest): Promise<ProviderCapConfig> {\n const res = await this.http.put<{ cap: ProviderCapConfig }>(\n `${BASE}/${encodeURIComponent(provider)}`,\n { body },\n );\n return res.cap;\n }\n\n /** Remove one provider's cap, returning it to the unset MM-O021 gate.\n * Admin-only. Returns whether a cap was removed. */\n async deleteCap(provider: string): Promise<boolean> {\n const res = await this.http.delete<{ deleted: boolean }>(\n `${BASE}/${encodeURIComponent(provider)}`,\n );\n return res.deleted ?? false;\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n MintReferralCodeRequest,\n RedeemReferralCodeRequest,\n ReferralAdminOverview,\n ReferralCode,\n ReferralRedemption,\n ReferralStats,\n} from './types.js';\n\n/**\n * Org self-service referrals. Any org can mint codes and redeem one (subject\n * to server-side guards: never-attributed, not reseller-associated, and\n * pre-first-purchase). Two-sided credits fire once the referred org's\n * cumulative spend reaches the snapshotted threshold.\n */\nexport class ReferralsClient {\n constructor(private readonly http: BaseClient) {}\n\n /** Mint a new referral code for the caller's org. */\n async mintCode(body: MintReferralCodeRequest = {}): Promise<ReferralCode> {\n const res = await this.http.post<{ success: boolean; data: ReferralCode }>('/referrals/codes', { body });\n return unwrapData(res);\n }\n\n /** List the caller org's codes with per-code redeemed/qualified counts. */\n async listCodes(): Promise<ReferralCode[]> {\n const res = await this.http.get<{ success: boolean; data: ReferralCode[] }>('/referrals/codes');\n return res.data ?? [];\n }\n\n /** Activate or deactivate one of the caller org's codes. */\n async setCodeActive(codeId: string, isActive: boolean): Promise<ReferralCode> {\n const res = await this.http.patch<{ success: boolean; data: ReferralCode }>(\n `/referrals/codes/${codeId}`,\n { body: { isActive } },\n );\n return unwrapData(res);\n }\n\n /** Caller org's referral summary as referrer (redemptions, qualified, credits earned). */\n async stats(): Promise<ReferralStats> {\n const res = await this.http.get<{ success: boolean; data: ReferralStats }>('/referrals/stats');\n return unwrapData(res);\n }\n\n /**\n * Redeem a referral code for the caller's org. Fails (4xx with an\n * `error_code`) when a guard rejects it: `code_inactive`, `self_referral`,\n * `already_redeemed`, `already_associated`, or `has_purchases`.\n */\n async redeem(body: RedeemReferralCodeRequest): Promise<ReferralRedemption> {\n const res = await this.http.post<{ success: boolean; data: ReferralRedemption }>(\n '/referrals/redeem',\n { body },\n );\n return unwrapData(res);\n }\n\n // --- Platform-admin only ---\n\n /**\n * Platform-wide referral monitor: rollup stats + every redemption (with the\n * code string and both org names). Returns 403 unless platform admin.\n */\n async adminOverview(): Promise<ReferralAdminOverview> {\n const res = await this.http.get<{ success: boolean; data: ReferralAdminOverview }>('/admin/referrals');\n return unwrapData(res);\n }\n\n /**\n * Void a PENDING redemption (abuse control) so it can never qualify. Fails\n * with 409 `not_pending` if the redemption is missing, already qualified, or\n * already void. Platform-admin only.\n */\n async voidRedemption(redemptionId: string): Promise<void> {\n await this.http.post<{ success: boolean }>(`/admin/referrals/${redemptionId}/void`, { body: {} });\n }\n\n /**\n * Force-qualify a PENDING non-reseller redemption: grants the snapshotted\n * referrer reward + referred welcome credit immediately, bypassing the spend\n * threshold. Fails with 409 `not_pending` (missing/qualified/void) or 400\n * `reseller_code`. Platform-admin only. Returns the updated redemption.\n */\n async qualifyRedemption(redemptionId: string): Promise<ReferralRedemption> {\n const res = await this.http.post<{ success: boolean; data: ReferralRedemption }>(\n `/admin/referrals/${redemptionId}/qualify`,\n { body: {} },\n );\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type { Organization } from '../organization/types.js';\nimport type {\n AppendProgramConfigRequest,\n AssociatedOrg,\n BillingProgramConfig,\n GeneratePayoutsRequest,\n ResellerCommission,\n ResellerPayout,\n ResellerPerformance,\n SetResellerRequest,\n UpdatePayoutRequest,\n} from './types.js';\n\n/**\n * Reseller surface. The first three methods are self-service for an org with\n * `isReseller === true` (the server gates on it). The remaining methods are\n * platform-admin only (gated on the caller's home org being the admin org).\n */\nexport class ResellerClient {\n constructor(private readonly http: BaseClient) {}\n\n // --- Reseller self-service (org.isReseller) ---\n\n /** Orgs associated to the caller reseller, with gross + commission rollups. */\n async listAssociatedOrgs(): Promise<AssociatedOrg[]> {\n const res = await this.http.get<{ success: boolean; data: AssociatedOrg[] }>('/reseller/associated-orgs');\n return res.data ?? [];\n }\n\n /** The caller reseller's commission ledger. */\n async listCommissions(): Promise<ResellerCommission[]> {\n const res = await this.http.get<{ success: boolean; data: ResellerCommission[] }>('/reseller/commissions');\n return res.data ?? [];\n }\n\n /** The caller reseller's payout history. */\n async listPayouts(): Promise<ResellerPayout[]> {\n const res = await this.http.get<{ success: boolean; data: ResellerPayout[] }>('/reseller/payouts');\n return res.data ?? [];\n }\n\n // --- Platform-admin only ---\n\n /** List all reseller orgs with aggregate performance. */\n async listResellers(): Promise<ResellerPerformance[]> {\n const res = await this.http.get<{ success: boolean; data: ResellerPerformance[] }>('/admin/resellers');\n return res.data ?? [];\n }\n\n /** Designate an org as a reseller (optionally with a per-reseller bps override). */\n async setReseller(orgId: string, body: SetResellerRequest = {}): Promise<Organization> {\n const res = await this.http.post<{ success: boolean; data: Organization }>(\n `/admin/orgs/${orgId}/reseller`,\n { body },\n );\n return unwrapData(res);\n }\n\n /** Revoke an org's reseller status. */\n async revokeReseller(orgId: string): Promise<Organization> {\n const res = await this.http.delete<{ success: boolean; data: Organization }>(`/admin/orgs/${orgId}/reseller`);\n return unwrapData(res);\n }\n\n /** End an org's reseller association (stamps resellerDetachedAt). */\n async detachAssociation(orgId: string): Promise<Organization> {\n const res = await this.http.post<{ success: boolean; data: Organization }>(\n `/admin/orgs/${orgId}/detach-reseller`,\n { body: {} },\n );\n return unwrapData(res);\n }\n\n /** The billing-program-config journal, newest first. */\n async getProgramConfig(): Promise<BillingProgramConfig[]> {\n const res = await this.http.get<{ success: boolean; data: BillingProgramConfig[] }>(\n '/admin/billing-program-config',\n );\n return res.data ?? [];\n }\n\n /** Append a new program-config period (closes the prior open row). */\n async appendProgramConfig(body: AppendProgramConfigRequest): Promise<BillingProgramConfig> {\n const res = await this.http.post<{ success: boolean; data: BillingProgramConfig }>(\n '/admin/billing-program-config',\n { body },\n );\n return unwrapData(res);\n }\n\n /** Draft payouts from accrued commissions in the given period. */\n async generatePayouts(body: GeneratePayoutsRequest): Promise<ResellerPayout[]> {\n const res = await this.http.post<{ success: boolean; data: ResellerPayout[] }>(\n '/admin/reseller-payouts/generate',\n { body },\n );\n return res.data ?? [];\n }\n\n /** Approve or mark-paid a payout (and optionally record an external ref). */\n async updatePayout(payoutId: string, body: UpdatePayoutRequest): Promise<ResellerPayout> {\n const res = await this.http.patch<{ success: boolean; data: ResellerPayout }>(\n `/admin/reseller-payouts/${payoutId}`,\n { body },\n );\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n AvailableModels,\n ModelPricingRow,\n ModelSelection,\n PatchModelSelectionRequest,\n PlatformSettings,\n UpdatePlatformSettingsRequest,\n} from './types.js';\n\n/**\n * Platform-admin global config. All endpoints are gated server-side on the\n * caller's home org being a platform-admin org. The model-selection / pricing\n * methods are proxied through the backend to the cloud-agent service.\n */\nexport class PlatformAdminClient {\n constructor(private readonly http: BaseClient) {}\n\n // --- Global backend settings (open registration + free-tier credits) ---\n\n /** Current global settings. */\n async getPlatformSettings(): Promise<PlatformSettings> {\n const res = await this.http.get<{ success: boolean; data: PlatformSettings }>('/admin/platform-settings');\n return unwrapData(res);\n }\n\n /** Update the global settings. */\n async updatePlatformSettings(body: UpdatePlatformSettingsRequest): Promise<PlatformSettings> {\n const res = await this.http.put<{ success: boolean; data: PlatformSettings }>('/admin/platform-settings', {\n body,\n });\n return unwrapData(res);\n }\n\n /** Models the aigateway currently exposes (for validating selection/pricing). */\n async listAvailableModels(): Promise<AvailableModels> {\n const res = await this.http.get<{ success: boolean; data: AvailableModels }>(\n '/admin/available-models',\n );\n return unwrapData(res);\n }\n\n // --- Chat-model selection (bridged to cloud-agent) ---\n\n /** Current model selection (provider priority + per-provider/role models). */\n async getModelSelection(): Promise<ModelSelection> {\n const res = await this.http.get<{ success: boolean; data: ModelSelection }>('/admin/model-selection');\n return unwrapData(res);\n }\n\n /** Full replace of the model selection. Returns the fresh selection. */\n async putModelSelection(body: ModelSelection): Promise<ModelSelection> {\n const res = await this.http.put<{ success: boolean; data: ModelSelection }>('/admin/model-selection', { body });\n return unwrapData(res);\n }\n\n /** Upsert a single (provider, role) → model slot. Returns the fresh selection. */\n async patchModelSelection(body: PatchModelSelectionRequest): Promise<ModelSelection> {\n const res = await this.http.patch<{ success: boolean; data: ModelSelection }>('/admin/model-selection', {\n body,\n });\n return unwrapData(res);\n }\n\n // --- Model pricing / surcharge (bridged to cloud-agent) ---\n\n /** All model_pricing rows. */\n async listModelPricing(): Promise<ModelPricingRow[]> {\n const res = await this.http.get<{ success: boolean; data: { pricing: ModelPricingRow[] } }>(\n '/admin/model-pricing',\n );\n return unwrapData(res).pricing ?? [];\n }\n\n /** Upsert one model_pricing row (also used to add a new row). Returns the fresh list. */\n async putModelPricing(row: ModelPricingRow): Promise<ModelPricingRow[]> {\n const res = await this.http.put<{ success: boolean; data: { pricing: ModelPricingRow[] } }>(\n '/admin/model-pricing',\n { body: row },\n );\n return unwrapData(res).pricing ?? [];\n }\n\n /** Delete a model_pricing row by model id. Returns the fresh list. */\n async deleteModelPricing(model: string): Promise<ModelPricingRow[]> {\n const res = await this.http.delete<{ success: boolean; data: { pricing: ModelPricingRow[] } }>(\n `/admin/model-pricing?model=${encodeURIComponent(model)}`,\n );\n return unwrapData(res).pricing ?? [];\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n Deployment,\n RegisterDeploymentRequest,\n RegisterDeploymentResponse,\n UpdateDeploymentRequest,\n DeploymentQuota,\n DeploymentQuotas,\n SetDeploymentQuotaRequest,\n OrgUsageResponse,\n DeploymentUsageResponse,\n FederationStatus,\n MeteringPolicy,\n MeteringReconciliation,\n} from './types.js';\n\n// Org-scoped private/sovereign deployment management. Backend routes hang off\n// the root authed group — see internal/http/routes/federation (RegisterPortal)\n// in cloud-agent-backend. The matching machine edge (/federation/enroll,\n// /heartbeat) is driven by the appliance itself, not this SDK.\nconst BASE = '/deployments';\n\nexport class DeploymentsClient {\n constructor(private readonly http: BaseClient) {}\n\n /** List the org's deployments, newest first. */\n list(): Promise<{ deployments: Deployment[] }> {\n return this.http.get(BASE);\n }\n\n /** Fetch one deployment by id. */\n get(id: string): Promise<{ deployment: Deployment }> {\n return this.http.get(`${BASE}/${encodeURIComponent(id)}`);\n }\n\n /**\n * Register a new deployment: reserves a quota slot and mints a one-time\n * enrollment voucher. The voucher + install command in the response are shown\n * ONCE (only the voucher hash is stored server-side).\n */\n register(body: RegisterDeploymentRequest): Promise<RegisterDeploymentResponse> {\n return this.http.post(BASE, { body });\n }\n\n /**\n * Edit the mutable slice of a deployment at its authority: the product set,\n * and — flat masters at Central — the vCPU tree budget. Propagates to the box\n * via the heartbeat licenseStale downlink + forced renewal (no restart).\n */\n update(id: string, body: UpdateDeploymentRequest): Promise<{ deployment: Deployment }> {\n return this.http.patch(`${BASE}/${encodeURIComponent(id)}`, { body });\n }\n\n /** Decommission a deployment, freeing its quota slot. */\n decommission(id: string): Promise<{ success: boolean }> {\n return this.http.post(`${BASE}/${encodeURIComponent(id)}/decommission`);\n }\n\n /**\n * The caller's org deployment quotas: deployment count plus flat capacity in\n * UNITS (1 unit = 1 vCPU × 1 product; used = Σ budget × |products| over flat\n * masters, max = Σ active capacity grants). Org-scoped: a platform admin\n * sending X-Impersonate-Org-Id sees the impersonated org's quotas.\n */\n getQuota(): Promise<DeploymentQuotas> {\n return this.http.get(`${BASE}/quota`);\n }\n\n /**\n * Platform-admin only: set an org's deployment cap (null → revert to the\n * platform default). Operates on the explicit orgId via the admin pool, so it\n * is independent of impersonation. Returns the refreshed quota.\n * (The flat-capacity pool is grant-based — see capacity.listGrants/addGrant.)\n */\n setOrgQuota(orgId: string, body: SetDeploymentQuotaRequest): Promise<{ quota: DeploymentQuota }> {\n return this.http.put(`/admin/orgs/${encodeURIComponent(orgId)}/deployment-quota`, { body });\n }\n\n /**\n * Permanently remove a DECOMMISSIONED deployment row from the registry\n * (decommission first — a live row is rejected with 409).\n */\n delete(id: string): Promise<{ success: boolean }> {\n return this.http.delete(`${BASE}/${encodeURIComponent(id)}`);\n }\n\n // ── Consumption reporting (channel plan §4.3/§4.11) ────────────────────────\n\n /** Org usage roll-up over [from, to) (RFC3339 or YYYY-MM-DD; default 30d). */\n getOrgUsage(params?: { from?: string; to?: string }): Promise<OrgUsageResponse> {\n return this.http.get(`${BASE}/usage`, { query: params });\n }\n\n /** One deployment's usage period detail (direct or estate-reported). */\n getUsage(id: string, params?: { from?: string; to?: string }): Promise<DeploymentUsageResponse> {\n return this.http.get(`${BASE}/${encodeURIComponent(id)}/usage`, { query: params });\n }\n\n // ── Box-side federation panel + the offline file pipe (channel plan §4.8) ──\n\n /** This private box's federation snapshot (503 on the SaaS / Central). */\n getFederationStatus(): Promise<{ federation: FederationStatus }> {\n return this.http.get('/federation/status');\n }\n\n /**\n * Seal the pending outbox (+ a liveness heartbeat) into the operator-carried\n * export file. The result is the JSON document to download/carry.\n */\n exportFederationFile(): Promise<unknown> {\n return this.http.get('/federation/export');\n }\n\n /** Apply the authority's response file on the box (acks + license adoption). */\n importFederationResponse(file: unknown): Promise<{ applied: number; refused: number }> {\n return this.http.post('/federation/import-response', { body: file });\n }\n\n /** Box-initiated retire: queues the signed decommission for the authority. */\n retire(reason?: string): Promise<{ success: boolean }> {\n return this.http.post('/federation/retire', { body: { reason: reason ?? '' } });\n }\n\n /**\n * Authority-side import of an operator-carried export file; returns the\n * response file (JSON) to carry back to the deployment.\n */\n importFederationFile(file: unknown): Promise<unknown> {\n return this.http.post(`${BASE}/import`, { body: file });\n }\n\n // ── Model-B metering policy (platform-admin; close-out P2) ─────────────────\n\n getMeteringPolicy(orgId: string): Promise<{ policy: MeteringPolicy; exists: boolean }> {\n return this.http.get(`/admin/orgs/${encodeURIComponent(orgId)}/metering-policy`);\n }\n\n setMeteringPolicy(orgId: string, policy: Omit<MeteringPolicy, 'orgId'>): Promise<{ success: boolean }> {\n return this.http.put(`/admin/orgs/${encodeURIComponent(orgId)}/metering-policy`, { body: policy });\n }\n\n /** Reported-vs-rated totals — the rating worker's health check. */\n getMeteringReconciliation(\n orgId: string,\n params?: { from?: string; to?: string },\n ): Promise<{ reconciliation: MeteringReconciliation }> {\n return this.http.get(`/admin/orgs/${encodeURIComponent(orgId)}/metering-reconciliation`, { query: params });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n AddCapacityGrantRequest,\n CapacityCheckoutRequest,\n CapacityCheckoutResponse,\n CapacityGrantsResponse,\n CapacityPreviewResponse,\n CapacityState,\n} from './types.js';\n\n// Flat-capacity self-serve purchase (SaaS/Central only; the backend hides the\n// whole surface on a private appliance). Increases apply immediately\n// (prorated); decreases and cancellation take effect at period end. See\n// cloud-agent/docs/design/current/federation/flat-capacity-payment-gateway.md.\nconst BASE = '/capacity';\n\nexport class CapacityClient {\n constructor(private readonly http: BaseClient) {}\n\n /** The org's capacity state: pool, grants, subscription, catalog. */\n getState(): Promise<CapacityState> {\n return this.http.get(BASE);\n }\n\n /** Start the first purchase — returns the Stripe Checkout URL. */\n checkout(body: CapacityCheckoutRequest): Promise<CapacityCheckoutResponse> {\n return this.http.post(`${BASE}/checkout`, { body });\n }\n\n /**\n * Preview the prorated charge of changing the `interval` subscription to\n * `units` (0 for decreases).\n */\n preview(interval: 'month' | 'year', units: number): Promise<CapacityPreviewResponse> {\n return this.http.post(`${BASE}/preview`, { body: { interval, units } });\n }\n\n /**\n * Change the `interval` subscription to `units`. Increase = immediate +\n * prorated (state in the response is already updated — no webhook wait);\n * decrease = scheduled for period end, floored at the org's current draw;\n * the current quantity cancels a pending decrease.\n */\n update(interval: 'month' | 'year', units: number): Promise<CapacityState> {\n return this.http.post(`${BASE}/update`, { body: { interval, units } });\n }\n\n /**\n * Cancel the `interval` subscription at period end; deployments then run\n * into the license grace window.\n */\n cancel(interval: 'month' | 'year'): Promise<CapacityState> {\n return this.http.post(`${BASE}/cancel`, { body: { interval } });\n }\n\n /** Undo a pending cancellation on the `interval` subscription before it lapses. */\n resume(interval: 'month' | 'year'): Promise<CapacityState> {\n return this.http.post(`${BASE}/resume`, { body: { interval } });\n }\n\n // ── Platform-admin grant ledger (manual pool source; stripe rows read-only) ─\n\n listGrants(orgId: string): Promise<CapacityGrantsResponse> {\n return this.http.get(`/admin/orgs/${encodeURIComponent(orgId)}/capacity-grants`);\n }\n\n addGrant(orgId: string, body: AddCapacityGrantRequest): Promise<CapacityGrantsResponse> {\n return this.http.post(`/admin/orgs/${encodeURIComponent(orgId)}/capacity-grants`, { body });\n }\n\n deleteGrant(orgId: string, grantId: string): Promise<CapacityGrantsResponse> {\n return this.http.delete(\n `/admin/orgs/${encodeURIComponent(orgId)}/capacity-grants/${encodeURIComponent(grantId)}`,\n );\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n BICatalogSummary,\n BIEntityDetail,\n BILinkResponse,\n CreateBILinkRequest,\n ListBIDatasetsResponse,\n ListBILinksResponse,\n ListBIModelsResponse,\n SelectBIDatasetsRequest,\n SelectBIDatasetsResponse,\n TriggerBIDiscoveryResponse,\n UpdateBILinkRequest,\n} from './types.js';\n\n/**\n * BIClient is the Talk-to-Your-BI control-plane surface used by the data-agent\n * frontend: read the discovered semantic-model catalog, list connected models,\n * trigger a re-scan, and start the Power BI OAuth connect flow. All endpoints\n * are org-scoped + product-entitlement-gated server-side (requireProduct(\"bi\")).\n *\n * Catalog upsert + refresh-token rotation are machine-only (HMAC, engine→backend)\n * and deliberately NOT exposed here.\n */\nexport class BIClient {\n constructor(\n private readonly http: BaseClient,\n private readonly baseUrl: string,\n ) {}\n\n /**\n * Compact grounding catalog for a workspace's model: entities + measures +\n * relationship names, no per-column detail. Pass `entity` to get the full\n * (ranked) field list for one entity — the get_model_schema detail layer.\n */\n getCatalog(workspaceId: string, opts?: { modelId?: string; entity?: string }): Promise<BICatalogSummary | BIEntityDetail> {\n const params = new URLSearchParams();\n if (opts?.modelId) params.set('modelId', opts.modelId);\n if (opts?.entity) params.set('entity', opts.entity);\n const qs = params.size > 0 ? `?${params.toString()}` : '';\n return this.http.get<BICatalogSummary | BIEntityDetail>(`/workspaces/${workspaceId}/bi/catalog${qs}`);\n }\n\n /** Lists the connected semantic models for a data project. */\n listModels(workspaceId: string): Promise<ListBIModelsResponse> {\n return this.http.get<ListBIModelsResponse>(`/workspaces/${workspaceId}/bi/models`);\n }\n\n /**\n * Lists the connected account's workspaces + datasets for the dataset picker.\n * The backend forwards to the engine (which holds the decrypted token) to make\n * the Power BI REST calls. `credentialId` selects which connected account.\n */\n listDatasets(workspaceId: string, opts: { credentialId: string }): Promise<ListBIDatasetsResponse> {\n const qs = `?credentialId=${encodeURIComponent(opts.credentialId)}`;\n return this.http.get<ListBIDatasetsResponse>(`/workspaces/${workspaceId}/bi/datasets${qs}`);\n }\n\n /**\n * Connects the chosen datasets: creates one bi_model per selection (the\n * workspace GUID is stored on the model). Entities/measures are discovered\n * lazily on the first chat question.\n */\n selectDatasets(workspaceId: string, body: SelectBIDatasetsRequest): Promise<SelectBIDatasetsResponse> {\n return this.http.post<SelectBIDatasetsResponse>(`/workspaces/${workspaceId}/bi/models`, { body });\n }\n\n /**\n * Triggers an engine-side catalog re-scan of the workspace's connected model\n * (INFO.* discovery → bi_* upsert). Returns once the backend has accepted the\n * request; the catalog read reflects the new data when discovery completes.\n */\n triggerDiscovery(workspaceId: string): Promise<TriggerBIDiscoveryResponse> {\n return this.http.post<TriggerBIDiscoveryResponse>(`/workspaces/${workspaceId}/bi/discover`, {});\n }\n\n /**\n * The browser URL that starts the delegated Power BI OAuth flow for a data\n * project. Navigate the window here; the backend redirects to Microsoft and,\n * on the callback, creates the POWERBI credential and returns to the frontend.\n * `workspaceId` tells the backend which project to attach the credential to.\n */\n powerBIConnectUrl(workspaceId: string): string {\n return `${this.baseUrl}/connect/powerbi?workspaceId=${encodeURIComponent(workspaceId)}`;\n }\n\n // ── Cross-dataset links (governance panel) ─────────────────────────────────\n\n /** Lists the workspace's cross-dataset links (with model names + probe stats). */\n listLinks(workspaceId: string): Promise<ListBILinksResponse> {\n return this.http.get<ListBILinksResponse>(`/workspaces/${workspaceId}/bi/links`);\n }\n\n /**\n * Creates a manual, user-authored link. It is confirmed immediately (the user\n * IS the governance authority); the backend forwards a probe to the engine\n * first, so a PII-keyed link is refused and stats attach at creation.\n */\n createLink(workspaceId: string, body: CreateBILinkRequest): Promise<BILinkResponse> {\n return this.http.post<BILinkResponse>(`/workspaces/${workspaceId}/bi/links`, { body });\n }\n\n /** Confirm / reject / re-propose a link, or edit its name/description/cardinality. */\n updateLink(workspaceId: string, linkId: string, body: UpdateBILinkRequest): Promise<BILinkResponse> {\n return this.http.patch<BILinkResponse>(`/workspaces/${workspaceId}/bi/links/${encodeURIComponent(linkId)}`, { body });\n }\n\n /** Soft-deletes a link. */\n deleteLink(workspaceId: string, linkId: string): Promise<{ success: boolean }> {\n return this.http.delete<{ success: boolean }>(`/workspaces/${workspaceId}/bi/links/${encodeURIComponent(linkId)}`);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n CreateDashboardRequest,\n CreateSnapshotShareRequest,\n CreateSnapshotShareResponse,\n DashboardResponse,\n ExportAuthorization,\n ExportRequest,\n ListDashboardsResponse,\n ListDashboardVersionsResponse,\n ListSnapshotsResponse,\n ListSnapshotSharesResponse,\n OkResponse,\n PopulateDashboardParams,\n PopulateDashboardResult,\n SnapshotResponse,\n UpdateDashboardRequest,\n} from './api-types.js';\n\n/**\n * DashboardsClient is the visual-dashboard control plane (Talk-to-Your-BI block\n * B5): save/load/edit the durable Dashboard Spec, refresh it with current data\n * (run-as-owner, model-free), and freeze/share snapshots.\n *\n * Access is org-scoped + product-entitlement-gated (requireProduct(\"bi\")) +\n * project-membership-scoped server-side. Dynamic boards are same-org, member-only;\n * static snapshots are the externally-shareable, governed-PII-egress artifact.\n */\nexport class DashboardsClient {\n constructor(\n private readonly http: BaseClient,\n private readonly baseUrl: string,\n ) {}\n\n private base(workspaceId: string): string {\n return `/workspaces/${workspaceId}/bi/dashboards`;\n }\n\n /** Lists a project's saved dashboards (most-recently-updated first). */\n list(workspaceId: string): Promise<ListDashboardsResponse> {\n return this.http.get<ListDashboardsResponse>(this.base(workspaceId));\n }\n\n /** Fetches one dashboard (spec served verbatim; validate client-side). */\n get(workspaceId: string, dashboardId: string): Promise<DashboardResponse> {\n return this.http.get<DashboardResponse>(`${this.base(workspaceId)}/${dashboardId}`);\n }\n\n /** Saves a spec as a new dashboard (the spec is a validated DashboardSpec). */\n create(workspaceId: string, body: CreateDashboardRequest): Promise<DashboardResponse> {\n return this.http.post<DashboardResponse>(this.base(workspaceId), { body });\n }\n\n /**\n * Updates a dashboard. A new `spec` bumps specVersion and appends an immutable\n * version row; name/description-only edits do not bump.\n */\n update(workspaceId: string, dashboardId: string, body: UpdateDashboardRequest): Promise<DashboardResponse> {\n return this.http.patch<DashboardResponse>(`${this.base(workspaceId)}/${dashboardId}`, { body });\n }\n\n /** Soft-deletes a dashboard (owner or project ADMIN). */\n remove(workspaceId: string, dashboardId: string): Promise<OkResponse> {\n return this.http.delete<OkResponse>(`${this.base(workspaceId)}/${dashboardId}`);\n }\n\n /** Lists a dashboard's spec history (newest first). */\n listVersions(workspaceId: string, dashboardId: string): Promise<ListDashboardVersionsResponse> {\n return this.http.get<ListDashboardVersionsResponse>(`${this.base(workspaceId)}/${dashboardId}/versions`);\n }\n\n /** Restores a prior version by forward-writing it as a new version. */\n restoreVersion(workspaceId: string, dashboardId: string, specVersion: number): Promise<DashboardResponse> {\n return this.http.post<DashboardResponse>(`${this.base(workspaceId)}/${dashboardId}/versions/${specVersion}/restore`, {});\n }\n\n /**\n * Refreshes the dashboard with CURRENT data — the model-free, run-as-owner\n * populate. Returns one PanelPayload per panel. `params` are resolved control\n * values (interactivity rungs 2–3).\n */\n populate(workspaceId: string, dashboardId: string, body: PopulateDashboardParams = {}): Promise<PopulateDashboardResult> {\n return this.http.post<PopulateDashboardResult>(`${this.base(workspaceId)}/${dashboardId}/populate`, { body });\n }\n\n /**\n * Freezes a snapshot — the governed PII egress (explicit action + audit). The\n * frozen panelData carries re-hydrated names.\n */\n createSnapshot(workspaceId: string, dashboardId: string, body: PopulateDashboardParams = {}): Promise<SnapshotResponse> {\n return this.http.post<SnapshotResponse>(`${this.base(workspaceId)}/${dashboardId}/snapshots`, { body });\n }\n\n /** Lists a dashboard's snapshots (newest first). */\n listSnapshots(workspaceId: string, dashboardId: string): Promise<ListSnapshotsResponse> {\n return this.http.get<ListSnapshotsResponse>(`${this.base(workspaceId)}/${dashboardId}/snapshots`);\n }\n\n /** Reads one snapshot (same-org; no live query, no credential). */\n getSnapshot(workspaceId: string, dashboardId: string, snapshotId: string): Promise<SnapshotResponse> {\n return this.http.get<SnapshotResponse>(`${this.base(workspaceId)}/${dashboardId}/snapshots/${snapshotId}`);\n }\n\n /**\n * Mints a snapshot share — an internal/known-user grant or an anonymous link.\n * External sharing (a link or a cross-org user) requires the org's\n * allowExternalSharing flag. A minted link's raw secret is returned ONCE in\n * `linkToken`; only its hash is stored.\n */\n createSnapshotShare(\n workspaceId: string,\n dashboardId: string,\n snapshotId: string,\n body: CreateSnapshotShareRequest,\n ): Promise<CreateSnapshotShareResponse> {\n return this.http.post<CreateSnapshotShareResponse>(\n `${this.base(workspaceId)}/${dashboardId}/snapshots/${snapshotId}/shares`,\n { body },\n );\n }\n\n /** Lists a snapshot's shares (owner/ADMIN; link secrets never returned). */\n listSnapshotShares(workspaceId: string, dashboardId: string, snapshotId: string): Promise<ListSnapshotSharesResponse> {\n return this.http.get<ListSnapshotSharesResponse>(\n `${this.base(workspaceId)}/${dashboardId}/snapshots/${snapshotId}/shares`,\n );\n }\n\n /** Revokes a share/link. */\n revokeSnapshotShare(workspaceId: string, dashboardId: string, snapshotId: string, shareId: string): Promise<OkResponse> {\n return this.http.delete<OkResponse>(\n `${this.base(workspaceId)}/${dashboardId}/snapshots/${snapshotId}/shares/${shareId}`,\n );\n }\n\n /**\n * Reads a snapshot shared with the caller via an explicit user grant (internal\n * or cross-org). Not project-scoped — the grant is the authorization.\n */\n getSharedSnapshot(snapshotId: string): Promise<SnapshotResponse> {\n return this.http.get<SnapshotResponse>(`/bi/snapshots/${snapshotId}/shared`);\n }\n\n /**\n * Reads a snapshot via an anonymous link token (no session). Use `token` = the\n * raw secret returned by createSnapshotShare({ link: true }).\n */\n getPublicSnapshot(token: string): Promise<SnapshotResponse> {\n return this.http.get<SnapshotResponse>(`/public/bi/snapshots/${encodeURIComponent(token)}`);\n }\n\n /** The shareable URL for an anonymous link token (for copy-to-clipboard). */\n publicSnapshotUrl(token: string): string {\n return `${this.baseUrl}/public/bi/snapshots/${encodeURIComponent(token)}`;\n }\n\n /**\n * Authorizes + audits a client-side export BEFORE the caller serialises the file\n * (Talk-to-Your-BI block B7). This makes the O1 \"audit exports always\" guarantee\n * un-skippable: the file must not be produced until this resolves. A workspace-\n * scoped export is same-org (project membership), so it is audit-only; the\n * allowExternalSharing gate governs only the cross-org / anonymous-link recipient\n * surfaces. Throws HttpError(403) when a gated egress is disallowed.\n */\n recordExport(workspaceId: string, dashboardId: string, body: ExportRequest): Promise<ExportAuthorization> {\n return this.http.post<ExportAuthorization>(`${this.base(workspaceId)}/${dashboardId}/exports`, { body });\n }\n\n /**\n * Authorizes + audits an ad-hoc, dashboard-less export — a run_bi_query chat\n * result serialised to a file (block B7). Audited against the project with no\n * dashboard id; same \"audit exports always\" guarantee as recordExport.\n */\n recordProjectExport(workspaceId: string, body: ExportRequest): Promise<ExportAuthorization> {\n return this.http.post<ExportAuthorization>(`/workspaces/${workspaceId}/bi/exports`, { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n AttestPostureRequest,\n ConnectionDetail,\n ConnectionFact,\n ConnectionSummary,\n RecordConnectionFactRequest,\n UpdateConnectionRequest,\n} from './types.js';\n\n/**\n * Connection health & capability inventory client (common-infra component #7).\n *\n * Authority splits in two, and the split is enforced server-side — these methods\n * only mirror it:\n *\n * - MEMBERS read (filtered to the credentials they can already see) and perform\n * the maintenance that keeps an inventory honest: rename, set the owner\n * contact. Locking those behind an admin is how inventories end up full of\n * rows called \"Power BI (delegated)\".\n * - ORG ADMINS own the consequential verbs: archive, disable, and attested\n * facts.\n *\n * Two behaviours worth knowing:\n *\n * - Reads NEVER provision. An empty list means the inventory has not observed\n * anything yet (or the feature is off) — it never means \"we just created some\n * rows for you because you looked\".\n * - Impersonation is read-only here, as with credentials: every write returns\n * 403 while impersonating another organization.\n */\nexport class ConnectionsClient {\n constructor(private readonly http: BaseClient) {}\n\n /**\n * Connections reachable from one project — those with at least one member\n * credential visible to you there.\n *\n * Returns `[]` while the feature is dark, so a caller can render this\n * unconditionally and see exactly today's UI.\n */\n async list(projectId: string): Promise<ConnectionSummary[]> {\n const res = await this.http.get<{ success: boolean; connections: ConnectionSummary[] }>(\n `/connections?projectId=${encodeURIComponent(projectId)}`,\n );\n return res.connections ?? [];\n }\n\n /** One connection in full: members, current facts with provenance, and the\n * contact references. 404 when no member credential is visible to you —\n * existence is not leaked across projects. */\n async get(id: string): Promise<ConnectionDetail> {\n const res = await this.http.get<{ success: boolean; connection: ConnectionDetail }>(\n `/connections/${encodeURIComponent(id)}`,\n );\n return res.connection;\n }\n\n /** Rename and/or re-point the owner + admin contact references. Member-level. */\n async update(id: string, body: UpdateConnectionRequest): Promise<ConnectionSummary> {\n const res = await this.http.patch<{ success: boolean; connection: ConnectionSummary }>(\n `/connections/${encodeURIComponent(id)}`,\n { body },\n );\n return res.connection;\n }\n\n /** Archive a connection (org admin). Archiving frees its identity, so a later\n * re-connect to the same tenant starts clean instead of colliding. */\n async archive(id: string): Promise<void> {\n await this.http.post(`/connections/${encodeURIComponent(id)}/archive`, {});\n }\n\n /** Restore an archived connection (org admin). */\n async unarchive(id: string): Promise<void> {\n await this.http.post(`/connections/${encodeURIComponent(id)}/unarchive`, {});\n }\n\n /**\n * Disable a connection (org admin).\n *\n * NOT the same as archive: an archived connection is gone from the working\n * set, a disabled one is present and deliberately unusable — it badges\n * `disabled` and capability checks answer `no` for it.\n */\n async disable(id: string): Promise<void> {\n await this.http.post(`/connections/${encodeURIComponent(id)}/disable`, {});\n }\n\n /** Re-enable a disabled connection (org admin). */\n async enable(id: string): Promise<void> {\n await this.http.post(`/connections/${encodeURIComponent(id)}/enable`, {});\n }\n\n /** Record an ATTESTED fact (org admin): a human's assertion about a\n * connection — a completed provider review, a negotiated unit cost. */\n async recordFact(id: string, body: RecordConnectionFactRequest): Promise<ConnectionFact> {\n const res = await this.http.post<{ success: boolean; fact: ConnectionFact }>(\n `/connections/${encodeURIComponent(id)}/facts`,\n { body },\n );\n return res.fact;\n }\n\n /** Attest a connection's posture (org admin, SHR-IP03): who it acts as, who\n * governs it, its explicit target allowlist, whether unattended use is\n * allowed, and who fixes it when it breaks. Until this runs, the connection\n * is fail-closed `pending-attestation` and proposes nothing. The response is\n * the same full detail projection `get()` serves, freshly attested. */\n async attestPosture(id: string, body: AttestPostureRequest): Promise<ConnectionDetail> {\n const res = await this.http.post<{ success: boolean; connection: ConnectionDetail }>(\n `/connections/${encodeURIComponent(id)}/posture`,\n { body },\n );\n return res.connection;\n }\n\n /** The admin attestation queue: connections still pending-attestation, as\n * the same summary projection `list()` serves (the queue is a list surface —\n * fetch `get(id)` for the drawer detail). */\n async pendingPosture(): Promise<ConnectionSummary[]> {\n const res = await this.http.get<{ success: boolean; connections: ConnectionSummary[] }>(\n `/connections-posture/pending`,\n );\n return res.connections ?? [];\n }\n}\n","/**\n * Connection lifecycle over the platform-owned delegated-OAuth connect rail\n * (MVP09 C2-SDK-CONNECTION, chat-first realignment proposal §5.1).\n *\n * This is the typed surface the secure connect flow (C2-UI-CONNECTION) drives:\n * begin an authorization-code flow, read the redacted connection status under\n * the active scope, refresh one connection's status, and disconnect. It mirrors\n * the backend rail generalized in C2-BE-OAUTH-ROUTES / C2-BE-OAUTH-LIFECYCLE:\n *\n * GET /connect/<slug> — authorize start → { authUrl }\n * GET /connect/<slug>/callback — browser redirect only (NOT an SDK call)\n * GET /connections?projectId= — redacted connection inventory (status)\n * GET /connections/<id> — redacted connection detail (refresh)\n * DELETE /credentials/<id> — revoke the delegated grant (disconnect)\n *\n * Two safety laws govern every type here (proposal §5.1.1-5.1.5):\n * 1. OPAQUE STATE. The client never constructs, holds or transmits an OAuth\n * state token or PKCE verifier. authorizeStart receives ONLY an opaque\n * authorize URL; the server mints, signs, expires and PKCE-binds the state.\n * 2. NO SECRET FIELDS. No token, envelope, client secret, refresh token or\n * verifier appears on any request or projection. status/refresh reuse the\n * never-secret connection-inventory shapes; disconnect is the redacted\n * credential-delete envelope.\n */\n\nimport type {\n ConnectionSummary,\n ConnectionDetail,\n CapabilityDisplayState,\n} from '../connections/types.js';\n\n/**\n * The connect-rail provider slug. Open string like {@link\n * '../credentials/types.js'.ProviderID}: the CLOSED set of connectable families\n * is owned server-side (connect_providers.go). Today the only currently-\n * connectable family is `powerbi`; every provisional Meeting/Marketing family\n * is contained and the rail answers 503 for it — the client passes the slug\n * through and never asserts availability itself.\n */\nexport type ConnectProviderSlug = 'powerbi' | (string & {});\n\n/**\n * Input to {@link '../connect/ConnectClient.js'.ConnectClient.authorizeStart}.\n * `workspaceId` is the active sandbox (StorageRepo) the connection binds to; the\n * server proves ownership and stamps the project/sandbox binding INTO the opaque\n * signed state — the client passes only the id, never the binding authority.\n * `origin` is the SPA origin the callback returns the browser to; the server\n * allow-lists it, so a forged value cannot redirect off-list.\n */\nexport interface ConnectAuthorizeStartInput {\n provider: ConnectProviderSlug;\n workspaceId: string;\n origin?: string;\n}\n\n/**\n * The authorize-start projection: ONLY the opaque provider authorize URL the\n * secure connect surface navigates the browser to. The URL embeds the\n * server-signed state and PKCE challenge; this type has NO field for a client\n * secret, refresh token, code verifier or any other credential material, so a\n * secret structurally cannot ride back on it.\n */\nexport interface ConnectAuthorization {\n authUrl: string;\n}\n\n/** Query for the redacted connection-status projection under an active scope. */\nexport interface ConnectStatusQuery {\n projectId: string;\n}\n\n/**\n * Input to {@link '../connect/ConnectClient.js'.ConnectClient.disconnect}.\n * Disconnect IS the existing project credential-delete surface (proposal §5.1,\n * C2-BE-OAUTH-LIFECYCLE): revoking a delegated grant deletes the project\n * credential that backs it. There is no secret in this request or its result.\n */\nexport interface ConnectDisconnectInput {\n credentialId: string;\n}\n\n/**\n * The redacted lifecycle projection of one connection. Reuses the connection\n * inventory's never-secret shapes (common-infra component #7): no token,\n * envelope or fragment ever appears on a ConnectionSummary/Detail.\n */\nexport type ConnectConnectionStatus = ConnectionSummary;\nexport type ConnectConnectionDetail = ConnectionDetail;\n\n// ───────────────────────────────────────────────────────────────────────────\n// MTG-S01-PROVIDER-RAIL@v3 — the product-neutral v1 connect wire.\n//\n// These types mirror the backend connect catalog/authorize/result/disconnect\n// contracts (cloud-agent-backend internal/providers connector_domains.go\n// ConnectCatalogRow + the /connect routes). Two invariants hold across every\n// type below:\n// 1. REDACTED. No token, PKCE verifier, client secret, raw provider id,\n// browser origin or provider error body ever appears — a secret is\n// structurally absent, not merely omitted.\n// 2. SERVER-OWNED AUTHORITY. The client sends only a semantic capability set\n// and the active product/project/sandbox scope; it never sends provider\n// scope strings, credential/connection ids at start, or OAuth state.\n//\n// The five-state vocabulary is REUSED from the connections surface\n// (CapabilityDisplayState) — S01 mints no parallel connect-side state type.\n// ───────────────────────────────────────────────────────────────────────────\n\n/** The connect.authorize.v1 contract version literal. */\nexport const CONNECT_AUTHORIZE_V1 = 'connect.authorize.v1' as const;\n/** The connection.disconnect.v1 contract version literal. */\nexport const CONNECTION_DISCONNECT_V1 = 'connection.disconnect.v1' as const;\n/** The connect.result.v1 contract version literal. */\nexport const CONNECT_RESULT_V1 = 'connect.result.v1' as const;\n\n/**\n * One capability-state row on the redacted connect catalog (backend\n * providers.ConnectCapabilityStateWire). Carries the stable capability id, its\n * owning versioned surface, the reused five-state value, the execution\n * location/profile (present on the PROVIDER_LIFECYCLE probe row), and the\n * applicable condition/degradation/spike/note. It carries NO credential data.\n */\nexport interface ConnectCapabilityState {\n capability: string;\n surface: string;\n state: CapabilityDisplayState;\n executionLocation?: 'sandbox' | 'server-side';\n executionProfile?: string;\n condition?: string;\n degradation?: string;\n spike?: string;\n note?: string;\n}\n\n/**\n * One provider's redacted connect-catalog projection (backend\n * providers.ConnectCatalogRow). Domain / lifecycle-surface membership is a\n * catalog CATEGORY — never connection or execution authority. A client that\n * does not recognise a `domainSurfaceVersions` value or an incomplete\n * capability-state matrix must refuse it, never invent a category or silently\n * treat omission as unsupported.\n */\nexport interface ConnectCatalogRow {\n provider: string;\n displayName: string;\n domains: string[];\n domainSurfaceVersions: Record<string, string>;\n providerLifecycleSurfaceVersion: string;\n capabilityStates: ConnectCapabilityState[];\n}\n\n/**\n * Input to {@link ConnectClient.authorizeStartV1}. Complete/empty/null fields\n * are all invalid server-side: every field is required, and unknown\n * product/provider/capability/version is refused. There is NO browser origin,\n * provider scope string, credential id, connection id, tenant or OAuth URL —\n * those are not fields on this type by construction.\n */\nexport interface ConnectAuthorizeStartV1Input {\n product: string;\n projectId: string;\n sandboxId: string;\n provider: string;\n requestedCapabilities: string[];\n}\n\n/**\n * The authorize-start v1 projection: the opaque server-authored authorization\n * URL (embedding the server-minted one-use state + PKCE challenge) and its\n * expiry. No secret, verifier or raw state rides here.\n */\nexport interface ConnectAuthorizationV1 {\n contractVersion: typeof CONNECT_AUTHORIZE_V1;\n authorizationUrl: string;\n expiresAt: string;\n}\n\n/** The closed outcome vocabulary of a connect result. */\nexport type ConnectResultStatus = 'connected' | 'orphan_grant' | 'failed';\n\n/**\n * The redacted, one-use connect result read back by resultId after the callback\n * (backend GET /connect/results/:resultId). Discriminated on `status`:\n * - connected → identity/capability projection, no secret;\n * - orphan_grant→ token exchange succeeded but local commit failed; the user\n * must restart. Never presented as \"connected\".\n * - failed → a redacted failure class; no provider error body/token.\n */\nexport type ConnectResultV1 =\n | {\n contractVersion: typeof CONNECT_RESULT_V1;\n status: 'connected';\n resultId: string;\n provider: string;\n connectionId: string;\n accountLabel?: string;\n tenantLabel?: string;\n grantedCapabilities: string[];\n }\n | {\n contractVersion: typeof CONNECT_RESULT_V1;\n status: 'orphan_grant';\n resultId: string;\n provider: string;\n }\n | {\n contractVersion: typeof CONNECT_RESULT_V1;\n status: 'failed';\n resultId: string;\n provider: string;\n failureClass: string;\n };\n\n/**\n * Input to {@link ConnectClient.disconnectV1}. The client generates a UUID\n * idempotency key; a repeated call with the same key returns the same terminal\n * projection and performs no second revoke.\n */\nexport interface ConnectDisconnectV1Input {\n connectionId: string;\n idempotencyKey: string;\n}\n\n/**\n * The closed, truthful remote-outcome vocabulary of a disconnect. The UI must\n * never collapse these into \"revoked\": local deletion is not upstream\n * revocation (frozen law 9).\n */\nexport type ConnectDisconnectRemoteOutcome =\n | 'remote_revoked'\n | 'remote_not_supported'\n | 'manual_admin_required'\n | 'remote_unknown'\n | 'not_applicable';\n\n/**\n * The redacted disconnect projection. `localState` reflects that new execution\n * is disabled and the local secret erased; `remoteOutcome` reports the honest\n * upstream result. No secret rides here.\n */\nexport interface ConnectDisconnectV1Result {\n contractVersion: typeof CONNECTION_DISCONNECT_V1;\n connectionId: string;\n localState: 'disconnected';\n remoteOutcome: ConnectDisconnectRemoteOutcome;\n}\n","// Connect catalog / result FAIL-CLOSED validation (MTG-S01-PROVIDER-RAIL@v3,\n// REV-S01-R08 client half). The one canonical SDK connect client validates the\n// EXACT supported connector-domain / lifecycle surface versions and the complete\n// five-state capability matrix, and REFUSES an unknown/missing/extra malformed\n// row rather than inventing a category or silently treating omission as\n// unsupported (types.ts §\"ConnectCatalogRow\"). A non-validating row throws a\n// ConnectCatalogValidationError; the mounted Console (which consumes this client,\n// R01) inherits that refusal and cannot fall back to its own allowlist.\n//\n// The supported set MIRRORS the backend authority\n// (cloud-agent-backend internal/providers/connector_domains.go): six connector\n// domains, each at surface version `v1`, plus the cross-cutting\n// PROVIDER_LIFECYCLE base surface at `v1`. Bumping a version here is a reviewed\n// client change made in lockstep with the backend surface bump — never inferred.\n\nimport type {\n ConnectCatalogRow,\n ConnectCapabilityState,\n ConnectResultV1,\n} from './types.js';\nimport { CONNECT_RESULT_V1 } from './types.js';\nimport type { CapabilityDisplayState } from '../connections/types.js';\n\n/**\n * The exact connector-domain surface versions this client recognises — the six\n * backend connector domains, each at `v1`. A row naming any other domain, or a\n * recognised domain at any other version, is REFUSED (fail closed).\n */\nexport const SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS: Readonly<Record<string, string>> = Object.freeze({\n MEETING_SOURCE: 'v1',\n CRM: 'v1',\n WORK_TRACKING: 'v1',\n CALENDAR: 'v1',\n EMAIL: 'v1',\n CHANNEL_NOTIFICATION: 'v1',\n});\n\n/** The cross-cutting PROVIDER_LIFECYCLE base surface identity + supported version. */\nexport const PROVIDER_LIFECYCLE_SURFACE = 'PROVIDER_LIFECYCLE' as const;\nexport const SUPPORTED_PROVIDER_LIFECYCLE_SURFACE_VERSION = 'v1' as const;\n\n/** The complete, closed five-state capability vocabulary (reused from the\n * connections surface — the SDK mints no parallel state type). A row carrying\n * any other state value is REFUSED. */\nexport const CONNECT_CAPABILITY_DISPLAY_STATES: ReadonlySet<CapabilityDisplayState> = new Set<CapabilityDisplayState>([\n 'supported',\n 'conditional',\n 'degraded',\n 'unavailable',\n 'unknown',\n]);\n\n/** Thrown when a catalog row / result envelope does not satisfy the exact\n * supported surface-version + five-state matrix contract. */\nexport class ConnectCatalogValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConnectCatalogValidationError';\n }\n}\n\nfunction fail(message: string): never {\n throw new ConnectCatalogValidationError(message);\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction requireString(obj: Record<string, unknown>, key: string, ctx: string): string {\n const v = obj[key];\n if (typeof v !== 'string' || v.trim() === '') {\n fail(`${ctx}: field \"${key}\" must be a non-empty string`);\n }\n return v as string;\n}\n\n/** Reject any key not in the allowed set — an EXTRA field is a malformed row. */\nfunction rejectUnknownKeys(obj: Record<string, unknown>, allowed: readonly string[], ctx: string): void {\n for (const k of Object.keys(obj)) {\n if (!allowed.includes(k)) fail(`${ctx}: unexpected field \"${k}\"`);\n }\n}\n\nconst CAPABILITY_STATE_KEYS = [\n 'capability',\n 'surface',\n 'state',\n 'executionLocation',\n 'executionProfile',\n 'condition',\n 'degradation',\n 'spike',\n 'note',\n] as const;\n\nconst CATALOG_ROW_KEYS = [\n 'provider',\n 'displayName',\n 'domains',\n 'domainSurfaceVersions',\n 'providerLifecycleSurfaceVersion',\n 'capabilityStates',\n] as const;\n\n/** Parse `<DOMAIN>@<version>` and refuse an unknown domain or version. The\n * PROVIDER_LIFECYCLE base surface is accepted at its supported version. */\nfunction validateSurfaceId(surface: string, ctx: string): void {\n const at = surface.indexOf('@');\n if (at <= 0 || at === surface.length - 1) {\n fail(`${ctx}: surface \"${surface}\" is not \"<SURFACE>@<version>\"`);\n }\n const name = surface.slice(0, at);\n const version = surface.slice(at + 1);\n if (name === PROVIDER_LIFECYCLE_SURFACE) {\n if (version !== SUPPORTED_PROVIDER_LIFECYCLE_SURFACE_VERSION) {\n fail(`${ctx}: unsupported PROVIDER_LIFECYCLE surface version \"${version}\"`);\n }\n return;\n }\n const supported = SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS[name];\n if (supported === undefined) fail(`${ctx}: unknown connector surface \"${name}\"`);\n if (supported !== version) fail(`${ctx}: unsupported surface version \"${version}\" for \"${name}\"`);\n}\n\nfunction parseCapabilityState(raw: unknown, ctx: string): ConnectCapabilityState {\n if (!isRecord(raw)) fail(`${ctx}: capability state must be an object`);\n rejectUnknownKeys(raw, CAPABILITY_STATE_KEYS, ctx);\n const capability = requireString(raw, 'capability', ctx);\n const surface = requireString(raw, 'surface', ctx);\n validateSurfaceId(surface, `${ctx}.surface`);\n const state = raw.state;\n if (typeof state !== 'string' || !CONNECT_CAPABILITY_DISPLAY_STATES.has(state as CapabilityDisplayState)) {\n fail(`${ctx}: unknown capability state \"${String(state)}\"`);\n }\n const out: ConnectCapabilityState = {\n capability,\n surface,\n state: state as CapabilityDisplayState,\n };\n if (raw.executionLocation !== undefined) {\n if (raw.executionLocation !== 'sandbox' && raw.executionLocation !== 'server-side') {\n fail(`${ctx}: unknown executionLocation \"${String(raw.executionLocation)}\"`);\n }\n out.executionLocation = raw.executionLocation;\n }\n for (const opt of ['executionProfile', 'condition', 'degradation', 'spike', 'note'] as const) {\n if (raw[opt] !== undefined) {\n if (typeof raw[opt] !== 'string') fail(`${ctx}: field \"${opt}\" must be a string`);\n out[opt] = raw[opt] as string;\n }\n }\n return out;\n}\n\n/**\n * Validate one provider's connect-catalog row against the exact supported\n * surface-version + five-state matrix. Throws ConnectCatalogValidationError on\n * any unknown/missing/extra malformed field. Returns the typed row on success.\n */\nexport function parseConnectCatalogRow(raw: unknown): ConnectCatalogRow {\n if (!isRecord(raw)) fail('catalog row must be an object');\n rejectUnknownKeys(raw, CATALOG_ROW_KEYS, 'catalog row');\n const provider = requireString(raw, 'provider', 'catalog row');\n const ctx = `catalog row \"${provider}\"`;\n const displayName = requireString(raw, 'displayName', ctx);\n\n const domains = raw.domains;\n if (!Array.isArray(domains) || domains.length === 0) {\n fail(`${ctx}: \"domains\" must be a non-empty array`);\n }\n for (const d of domains) {\n if (typeof d !== 'string') fail(`${ctx}: domain entries must be strings`);\n if (SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS[d] === undefined) {\n fail(`${ctx}: unknown connector domain \"${d}\"`);\n }\n }\n const domainList = domains as string[];\n\n const dsv = raw.domainSurfaceVersions;\n if (!isRecord(dsv)) fail(`${ctx}: \"domainSurfaceVersions\" must be an object`);\n // Every listed domain has a recognised version...\n for (const d of domainList) {\n const v = dsv[d];\n if (typeof v !== 'string') fail(`${ctx}: missing surface version for domain \"${d}\"`);\n if (SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS[d] !== v) {\n fail(`${ctx}: unsupported surface version \"${v}\" for domain \"${d}\"`);\n }\n }\n // ...and no EXTRA version key that is not a listed domain.\n for (const k of Object.keys(dsv)) {\n if (!domainList.includes(k)) fail(`${ctx}: surface version for unlisted domain \"${k}\"`);\n }\n\n const plsv = requireString(raw, 'providerLifecycleSurfaceVersion', ctx);\n if (plsv !== SUPPORTED_PROVIDER_LIFECYCLE_SURFACE_VERSION) {\n fail(`${ctx}: unsupported providerLifecycleSurfaceVersion \"${plsv}\"`);\n }\n\n const capStates = raw.capabilityStates;\n if (!Array.isArray(capStates)) fail(`${ctx}: \"capabilityStates\" must be an array`);\n const capabilityStates = capStates.map((c, i) => parseCapabilityState(c, `${ctx} capabilityStates[${i}]`));\n\n return {\n provider,\n displayName,\n domains: domainList,\n domainSurfaceVersions: { ...(dsv as Record<string, string>) },\n providerLifecycleSurfaceVersion: plsv,\n capabilityStates,\n };\n}\n\n/** Validate a whole catalog: it must be an array and every row must validate.\n * One malformed row rejects the whole catalog — never silently dropped. */\nexport function parseConnectCatalog(raw: unknown): ConnectCatalogRow[] {\n if (!Array.isArray(raw)) fail('connect catalog must be an array');\n return raw.map((r) => parseConnectCatalogRow(r));\n}\n\nconst RESULT_STATUSES = new Set(['connected', 'orphan_grant', 'failed']);\n\n/**\n * Validate the redacted connect result envelope: exact contract version and a\n * known discriminated status with its required fields. Throws on an unknown\n * version/status or a missing required field (fail closed).\n */\nexport function parseConnectResultV1(raw: unknown): ConnectResultV1 {\n if (!isRecord(raw)) fail('connect result must be an object');\n if (raw.contractVersion !== CONNECT_RESULT_V1) {\n fail(`connect result: unsupported contractVersion \"${String(raw.contractVersion)}\"`);\n }\n const status = raw.status;\n if (typeof status !== 'string' || !RESULT_STATUSES.has(status)) {\n fail(`connect result: unknown status \"${String(status)}\"`);\n }\n const resultId = requireString(raw, 'resultId', 'connect result');\n const provider = requireString(raw, 'provider', 'connect result');\n if (status === 'connected') {\n const connectionId = requireString(raw, 'connectionId', 'connect result');\n const granted = raw.grantedCapabilities;\n if (!Array.isArray(granted) || granted.some((g) => typeof g !== 'string')) {\n fail('connect result: \"grantedCapabilities\" must be a string array');\n }\n const out: ConnectResultV1 = {\n contractVersion: CONNECT_RESULT_V1,\n status: 'connected',\n resultId,\n provider,\n connectionId,\n grantedCapabilities: granted as string[],\n };\n if (raw.accountLabel !== undefined) {\n if (typeof raw.accountLabel !== 'string') fail('connect result: accountLabel must be a string');\n out.accountLabel = raw.accountLabel;\n }\n if (raw.tenantLabel !== undefined) {\n if (typeof raw.tenantLabel !== 'string') fail('connect result: tenantLabel must be a string');\n out.tenantLabel = raw.tenantLabel;\n }\n return out;\n }\n if (status === 'orphan_grant') {\n return { contractVersion: CONNECT_RESULT_V1, status: 'orphan_grant', resultId, provider };\n }\n const failureClass = requireString(raw, 'failureClass', 'connect result');\n return { contractVersion: CONNECT_RESULT_V1, status: 'failed', resultId, provider, failureClass };\n}\n","// Connection lifecycle client (MVP09 C2-SDK-CONNECTION, chat-first realignment\n// proposal §5.1). The typed surface the secure connect flow (C2-UI-CONNECTION)\n// drives over the platform-owned delegated-OAuth connect rail. See ./types.ts\n// for the two safety laws (opaque state, no secret fields) and the exact\n// backend routes this mirrors (C2-BE-OAUTH-ROUTES / C2-BE-OAUTH-LIFECYCLE).\n//\n// Surface:\n// apiClient.connect.authorizeStart() — begin the authorization-code flow\n// apiClient.connect.status() — redacted connection inventory (scope)\n// apiClient.connect.refresh() — refetch one connection's redacted state\n// apiClient.connect.disconnect() — revoke the delegated grant\nimport type { BaseClient } from '../../http/BaseClient.js';\nimport type { SimpleKeysResponse } from '../credentials/types.js';\nimport {\n CONNECT_AUTHORIZE_V1,\n CONNECTION_DISCONNECT_V1,\n} from './types.js';\nimport { parseConnectCatalog, parseConnectResultV1 } from './validate.js';\nimport type {\n ConnectAuthorization,\n ConnectAuthorizeStartInput,\n ConnectConnectionDetail,\n ConnectConnectionStatus,\n ConnectDisconnectInput,\n ConnectStatusQuery,\n ConnectCatalogRow,\n ConnectAuthorizeStartV1Input,\n ConnectAuthorizationV1,\n ConnectResultV1,\n ConnectDisconnectV1Input,\n ConnectDisconnectV1Result,\n} from './types.js';\n\nexport class ConnectClient {\n constructor(private readonly http: BaseClient) {}\n\n /**\n * authorizeStart begins the delegated-OAuth authorization-code flow on the\n * platform-owned connect rail (`GET /connect/<slug>`). The server proves\n * workspace ownership, mints an expiring PKCE-bound SIGNED STATE that binds\n * the project/sandbox, and returns ONLY the opaque provider authorize URL;\n * the secure connect surface then navigates the browser to it (the top-level\n * redirect can't carry the bearer token this authed XHR uses). The client\n * sends no OAuth state and holds no secret. A contained provider family\n * answers 503 (surfaced as an HttpError) — availability is never faked here.\n */\n async authorizeStart(input: ConnectAuthorizeStartInput): Promise<ConnectAuthorization> {\n const query: Record<string, string> = { workspaceId: input.workspaceId };\n if (input.origin !== undefined && input.origin !== '') {\n query.origin = input.origin;\n }\n const res = await this.http.get<{ success: boolean; authUrl?: string }>(\n `/connect/${encodeURIComponent(input.provider)}`,\n { query },\n );\n if (!res.authUrl) {\n throw new Error('authorizeStart response missing authUrl.');\n }\n // Return ONLY the opaque URL — never spread the server envelope, so no\n // field the backend might add can smuggle credential material into the\n // projection the connect surface renders.\n return { authUrl: res.authUrl };\n }\n\n /**\n * status returns the redacted connection-status projection for the active\n * project scope (`GET /connections?projectId=`). ConnectionSummary carries\n * health, posture and capability state but NEVER a secret (component #7). An\n * empty list means the inventory has observed nothing yet — it never\n * provisions.\n */\n async status(query: ConnectStatusQuery): Promise<ConnectConnectionStatus[]> {\n const res = await this.http.get<{ success: boolean; connections?: ConnectConnectionStatus[] }>(\n '/connections',\n { query: { projectId: query.projectId } },\n );\n return res.connections ?? [];\n }\n\n /**\n * refresh refetches ONE connection's redacted status projection\n * (`GET /connections/<id>`). The \"refresh status\" connect-card action only\n * refetches the authoritative record (proposal §5.1.5); it mints nothing,\n * connects nothing, and carries no secret. 404 when no member credential is\n * visible to you — existence is not leaked across projects.\n */\n async refresh(connectionId: string): Promise<ConnectConnectionDetail> {\n const res = await this.http.get<{ success: boolean; connection: ConnectConnectionDetail }>(\n `/connections/${encodeURIComponent(connectionId)}`,\n );\n return res.connection;\n }\n\n /**\n * @deprecated Legacy LOCAL credential delete — kept operational for the BI\n * connect surface. It performs `DELETE /credentials/<id>`, which erases the\n * local project credential; it does NOT contact the provider and is NOT an\n * upstream revoke. Do not present its result as \"revoked\". For the\n * product-neutral Meeting rail use {@link ConnectClient.disconnectV1}, which\n * disables local use, advances the connection epoch and returns the honest\n * remote outcome. The redacted envelope carries no secret.\n */\n disconnect(input: ConnectDisconnectInput): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(\n `/credentials/${encodeURIComponent(input.credentialId)}`,\n );\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // MTG-S01-PROVIDER-RAIL@v3 — product-neutral v1 connect wire.\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * getCatalogV1 fetches the redacted connect catalog for a product\n * (`GET /connect/catalog?product=`). Each row carries connector-domain\n * memberships, versioned surface identities and a complete capability-state\n * matrix; the panel groups/filters from this projection and never from a\n * client-side allowlist. A contained family is absent from the catalog. The\n * returned rows carry no credential material.\n */\n async getCatalogV1(product: string): Promise<ConnectCatalogRow[]> {\n const res = await this.http.get<{ success: boolean; providers?: unknown }>(\n '/connect/catalog',\n { query: { product } },\n );\n // Fail closed (R08): validate the exact supported domain/lifecycle surface\n // versions and the complete five-state matrix. A malformed/unknown/extra row\n // REJECTS the whole catalog — never silently dropped, never invented.\n if (res.providers === undefined || res.providers === null) return [];\n return parseConnectCatalog(res.providers);\n }\n\n /**\n * authorizeStartV1 begins the product-neutral authorization-code flow\n * (`POST /connect/authorizations`, contract connect.authorize.v1). The client\n * sends only the active product/project/sandbox scope, the provider and the\n * requested SEMANTIC capabilities — never a scope string, credential id or\n * OAuth state. The server authorizes the editor + Team binding, expands the\n * capabilities to a server-owned scope ceiling, mints an opaque one-use state,\n * and returns only the authorization URL and its expiry.\n */\n async authorizeStartV1(input: ConnectAuthorizeStartV1Input): Promise<ConnectAuthorizationV1> {\n const res = await this.http.post<{\n success: boolean;\n contractVersion?: string;\n authorizationUrl?: string;\n expiresAt?: string;\n }>('/connect/authorizations', {\n body: {\n contractVersion: CONNECT_AUTHORIZE_V1,\n product: input.product,\n projectId: input.projectId,\n sandboxId: input.sandboxId,\n provider: input.provider,\n requestedCapabilities: input.requestedCapabilities,\n },\n });\n if (!res.authorizationUrl || !res.expiresAt) {\n throw new Error('authorizeStartV1 response missing authorizationUrl/expiresAt.');\n }\n // Return ONLY the redacted fields — never spread the envelope.\n return {\n contractVersion: CONNECT_AUTHORIZE_V1,\n authorizationUrl: res.authorizationUrl,\n expiresAt: res.expiresAt,\n };\n }\n\n /**\n * getConnectResultV1 reads back the redacted, bound result of a completed\n * authorization by its opaque resultId (`GET /connect/results/<resultId>`).\n * The result is scoped to the bound user/project/Team; query text is never\n * treated as success authority. The read is idempotent within the bound\n * session so a React double-fetch does not consume it twice.\n */\n async getConnectResultV1(resultId: string): Promise<ConnectResultV1> {\n const res = await this.http.get<{ success: boolean; result?: unknown }>(\n `/connect/results/${encodeURIComponent(resultId)}`,\n );\n if (res.result === undefined || res.result === null) {\n throw new Error('getConnectResultV1 response missing result.');\n }\n // Fail closed (R08): refuse an unknown contract version / status / missing\n // required field rather than trust an unvalidated envelope.\n return parseConnectResultV1(res.result);\n }\n\n /**\n * disconnectV1 disconnects a connection over the product-neutral rail\n * (`POST /connections/<id>/disconnect`, contract connection.disconnect.v1).\n * The client generates the idempotency key; the server disables local use and\n * advances the epoch BEFORE any remote action, then returns the honest remote\n * outcome. A repeated call with the same key returns the same terminal\n * projection and performs no second revoke. Local deletion is never relabelled\n * as upstream revoke.\n */\n async disconnectV1(input: ConnectDisconnectV1Input): Promise<ConnectDisconnectV1Result> {\n const res = await this.http.post<{\n success: boolean;\n contractVersion?: string;\n connectionId?: string;\n localState?: 'disconnected';\n remoteOutcome?: ConnectDisconnectV1Result['remoteOutcome'];\n }>(`/connections/${encodeURIComponent(input.connectionId)}/disconnect`, {\n body: { contractVersion: CONNECTION_DISCONNECT_V1 },\n headers: { 'Idempotency-Key': input.idempotencyKey },\n });\n if (!res.connectionId || !res.remoteOutcome || res.localState !== 'disconnected') {\n throw new Error('disconnectV1 response missing required fields.');\n }\n return {\n contractVersion: CONNECTION_DISCONNECT_V1,\n connectionId: res.connectionId,\n localState: 'disconnected',\n remoteOutcome: res.remoteOutcome,\n };\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n CapabilitiesResponse,\n ComponentId,\n EnabledComponentsResponse,\n SetEnabledComponentsRequest,\n SetEnabledComponentsResponse,\n} from './types.js';\n\n/**\n * Capability plane client.\n *\n * `get()` is the authenticated per-organization answer every UI surface should\n * gate on. `setEnabledComponents()` is the platform-admin cohort control — the\n * mechanism for enabling one component for an internal cohort only.\n */\nexport class CapabilitiesClient {\n constructor(private readonly http: BaseClient) {}\n\n /** GET /capabilities — the caller organization's effective component set. */\n async get(): Promise<CapabilitiesResponse> {\n return this.http.get<CapabilitiesResponse>('/capabilities');\n }\n\n /**\n * Whether one component may be used by the calling organization.\n *\n * Anything other than an explicit `enabled` is false, including a component\n * absent from the response: an SDK newer than its backend must not treat an\n * unknown component as permitted.\n */\n isEnabled(response: CapabilitiesResponse | undefined, id: ComponentId): boolean {\n return response?.components?.[id] === 'enabled';\n }\n\n /**\n * GET /orgs/:id/enabled-components — platform-admin only.\n *\n * The cohort editor's read: the STORED grant beside the EFFECTIVE state. The\n * READ is admin-gated as well as the write, because another organization's\n * stored grant list is cohort-rollout information.\n */\n async getEnabledComponents(orgId: string): Promise<EnabledComponentsResponse> {\n return this.http.get<EnabledComponentsResponse>(\n `/orgs/${encodeURIComponent(orgId)}/enabled-components`,\n );\n }\n\n /** PATCH /orgs/:id/enabled-components — platform-admin only. */\n async setEnabledComponents(\n orgId: string,\n body: SetEnabledComponentsRequest,\n ): Promise<SetEnabledComponentsResponse> {\n return this.http.patch<SetEnabledComponentsResponse>(\n `/orgs/${encodeURIComponent(orgId)}/enabled-components`,\n { body },\n );\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n AddContactHandleRequest,\n AddContactListMemberRequest,\n Contact,\n ContactAuditPage,\n ContactConflictPair,\n ContactHandle,\n ContactList,\n ContactListGrant,\n ContactListGrantInput,\n ContactSearchQuery,\n ContactSearchResult,\n ContactSettings,\n CreateContactListRequest,\n EraseContactResult,\n GetContactResult,\n ResolveContactRequest,\n ResolveContactResult,\n SetContactHandleFlagsRequest,\n UpdateContactListRequest,\n UpdateContactRequest,\n} from './types.js';\n\n/**\n * Contact registry client (common-infra component #1).\n *\n * Authority splits in two, and the split is enforced server-side — these\n * methods only mirror it:\n *\n * - MEMBERS read (filtered to what they may see), create, edit fields and\n * handles, and own their manual lists. A directory is crowd-maintained or it\n * is empty.\n * - ORG ADMINS additionally own the identity lifecycle: kind changes, merge /\n * unmerge, erase, link / unlink, the posture dial, list grants, tombstone\n * overrides and the audit trail. Those are the governed, audited operations.\n *\n * Impersonation is read-only here (as with credentials): every write returns\n * 403 while impersonating another organization.\n */\nexport class ContactsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n // ── directory ──────────────────────────────────────────────────────────────\n\n /** Search the directory. Results are always visibility-filtered. */\n async list(params: ContactSearchQuery = {}): Promise<ContactSearchResult> {\n const res = await this.http.get<{ success: boolean; data: ContactSearchResult }>(\n `/contacts${this.query({\n query: params.query,\n affiliation: params.affiliation,\n handleKind: params.handleKind,\n handle: params.handle,\n listId: params.listId,\n kind: params.kind,\n status: params.status,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Read one contact. A merged row returns its SURVIVOR plus `alias_of`, so a\n * stale reference degrades gracefully instead of 404-ing.\n */\n async get(id: string): Promise<GetContactResult> {\n const res = await this.http.get<{ success: boolean; data: GetContactResult }>(`/contacts/${id}`);\n return unwrapData(res);\n }\n\n /**\n * Resolve handles to a contact — and the console's CREATE path, since\n * recording a person means claiming their handles.\n *\n * Check `tombstoned` before treating the result as a contact: that outcome\n * means the person was erased and nothing was written.\n */\n async resolve(body: ResolveContactRequest): Promise<ResolveContactResult> {\n const res = await this.http.post<{ success: boolean; data: ResolveContactResult }>('/contacts/resolve', { body });\n return unwrapData(res);\n }\n\n async update(id: string, body: UpdateContactRequest): Promise<Contact> {\n const res = await this.http.put<{ success: boolean; data: Contact }>(`/contacts/${id}`, { body });\n return unwrapData(res);\n }\n\n // ── handles ────────────────────────────────────────────────────────────────\n\n async addHandle(contactId: string, body: AddContactHandleRequest): Promise<ContactHandle> {\n const res = await this.http.post<{ success: boolean; data: ContactHandle }>(`/contacts/${contactId}/handles`, {\n body,\n });\n return unwrapData(res);\n }\n\n async setHandleFlags(contactId: string, handleId: string, body: SetContactHandleFlagsRequest): Promise<void> {\n await this.http.put(`/contacts/${contactId}/handles/${handleId}`, { body });\n }\n\n /** Refused when it would leave the contact with no handles at all. */\n async removeHandle(contactId: string, handleId: string): Promise<void> {\n await this.http.delete(`/contacts/${contactId}/handles/${handleId}`);\n }\n\n // ── lists ──────────────────────────────────────────────────────────────────\n\n /** Lists the caller may see; a restricted list they cannot read is absent. */\n async listLists(): Promise<ContactList[]> {\n const res = await this.http.get<{ success: boolean; data: { items: ContactList[] } }>('/contacts/lists');\n return unwrapData(res).items;\n }\n\n async createList(body: CreateContactListRequest): Promise<ContactList> {\n const res = await this.http.post<{ success: boolean; data: ContactList }>('/contacts/lists', { body });\n return unwrapData(res);\n }\n\n async getList(id: string): Promise<ContactList> {\n const res = await this.http.get<{ success: boolean; data: ContactList }>(`/contacts/lists/${id}`);\n return unwrapData(res);\n }\n\n async updateList(id: string, body: UpdateContactListRequest): Promise<ContactList> {\n const res = await this.http.put<{ success: boolean; data: ContactList }>(`/contacts/lists/${id}`, { body });\n return unwrapData(res);\n }\n\n async deleteList(id: string): Promise<void> {\n await this.http.delete(`/contacts/lists/${id}`);\n }\n\n async listMembers(id: string, params: { skip?: number; take?: number } = {}): Promise<ContactSearchResult> {\n const res = await this.http.get<{ success: boolean; data: ContactSearchResult }>(\n `/contacts/lists/${id}/members${this.query(params)}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Add an existing contact, or an org member by `userId` — the member variant\n * provisions that colleague's contact automatically if it does not exist yet.\n */\n async addListMember(id: string, body: AddContactListMemberRequest): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/lists/${id}/members`, { body });\n return unwrapData(res);\n }\n\n async removeListMember(id: string, contactId: string): Promise<void> {\n await this.http.delete(`/contacts/lists/${id}/members/${contactId}`);\n }\n\n async getGrants(listId: string): Promise<ContactListGrant[]> {\n const res = await this.http.get<{ success: boolean; data: { items: ContactListGrant[] } }>(\n `/contacts/lists/${listId}/grants`,\n );\n return unwrapData(res).items;\n }\n\n /** Replace-set semantics: the supplied grants become the whole grant set. */\n async setGrants(listId: string, grants: ContactListGrantInput[]): Promise<ContactListGrant[]> {\n const res = await this.http.put<{ success: boolean; data: { items: ContactListGrant[] } }>(\n `/contacts/lists/${listId}/grants`,\n { body: { grants } },\n );\n return unwrapData(res).items;\n }\n\n // ── identity lifecycle (org admin) ─────────────────────────────────────────\n\n /** The only path to `guest`. `member` requires an existing user link. */\n async setKind(id: string, kind: Contact['kind']): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/${id}/kind`, { body: { kind } });\n return unwrapData(res);\n }\n\n /** Fold `loserId` into `id`. The path id is the SURVIVOR. */\n async merge(id: string, loserId: string): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/${id}/merge`, {\n body: { loserId },\n });\n return unwrapData(res);\n }\n\n /** Reverse a merge; `id` is the merged (loser) contact being restored. */\n async unmerge(id: string): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/${id}/unmerge`, { body: {} });\n return unwrapData(res);\n }\n\n /**\n * The data-subject erasure: anonymize, drop handles, write suppression\n * tombstones, cascade to product overlays, audit.\n *\n * Refused (422 `user_still_active`) while the contact is linked to an active\n * platform user — registry erasure is not account deletion. Offboard or\n * unlink first.\n */\n async erase(id: string): Promise<EraseContactResult> {\n const res = await this.http.post<{ success: boolean; data: EraseContactResult }>(`/contacts/${id}/erase`, {\n body: { ack: true },\n });\n return unwrapData(res);\n }\n\n async linkUser(id: string, userId: string): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/${id}/link`, {\n body: { userId },\n });\n return unwrapData(res);\n }\n\n async unlinkUser(id: string): Promise<Contact> {\n const res = await this.http.delete<{ success: boolean; data: Contact }>(`/contacts/${id}/link`);\n return unwrapData(res);\n }\n\n // ── governance surfaces ────────────────────────────────────────────────────\n\n async getSettings(): Promise<ContactSettings> {\n const res = await this.http.get<{ success: boolean; data: ContactSettings }>('/contacts/settings');\n return unwrapData(res);\n }\n\n /**\n * Flip the org posture. This rewrites no rows: it changes who can see what,\n * and the default visibility of newly created lists.\n */\n async setPosture(posture: ContactSettings['posture']): Promise<ContactSettings> {\n const res = await this.http.put<{ success: boolean; data: ContactSettings }>('/contacts/settings', {\n body: { posture },\n });\n return unwrapData(res);\n }\n\n /**\n * Deliberately re-enable a handle suppressed by an erasure. The tombstone is\n * stamped, never deleted — the override leaves an audited fingerprint.\n */\n async overrideTombstone(handleKind: string, value: string): Promise<void> {\n await this.http.post('/contacts/tombstones/override', { body: { handleKind, value, ack: true } });\n }\n\n async audit(params: { contactId?: string; event?: string; skip?: number; take?: number } = {}): Promise<ContactAuditPage> {\n const res = await this.http.get<{ success: boolean; data: ContactAuditPage }>(\n `/contacts/audit${this.query(params)}`,\n );\n return unwrapData(res);\n }\n\n /** Recent \"two contacts, one person\" ambiguities — the entry point to merge. */\n async conflicts(take?: number): Promise<ContactConflictPair[]> {\n const res = await this.http.get<{ success: boolean; data: { items: ContactConflictPair[] } }>(\n `/contacts/conflicts${this.query({ take })}`,\n );\n return unwrapData(res).items;\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n FactAuditPage,\n FactListResult,\n FactProposalDetail,\n FactStats,\n ListFactsQuery,\n ResolveFactRequest,\n} from './types.js';\n\n/**\n * Fact-governance client (common-infra component #4).\n *\n * The knowledge-review queue: suggested contact merges awaiting an org admin's\n * confirmation. Backend-resident, session-scoped (RLS-pinned by the org-tx\n * middleware) — no scope headers, unlike the engine-proxied action queue.\n *\n * Every route is ADMIN-ONLY (only admins resolve, and admins see all contacts);\n * `resolve` is additionally impersonation-blocked server-side (knowledge writes\n * get the PII-write posture). The MVP surface is read/resolve only — batch, the\n * org-channel notification row, and the ConflictsCard cross-link are the\n * prod-wave delta (02 §0.5).\n */\nexport class FactsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The knowledge-review queue. `state` defaults to `open`. */\n async list(params: ListFactsQuery = {}): Promise<FactListResult> {\n const res = await this.http.get<{ success: boolean; data: FactListResult }>(\n `/facts${this.query({\n category: params.category,\n state: params.state,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** Queue telemetry — powers the section badge. */\n async stats(): Promise<FactStats> {\n const res = await this.http.get<{ success: boolean; data: FactStats }>('/facts/stats');\n return unwrapData(res);\n }\n\n /** One proposal plus its category-shaped preview (the merge preview for contact-merge). */\n async get(id: string): Promise<FactProposalDetail> {\n const res = await this.http.get<{ success: boolean; data: FactProposalDetail }>(\n `/facts/${encodeURIComponent(id)}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Confirm, reject or correct one proposal.\n *\n * Confirm fires the in-process contact merge; reject writes rejection memory;\n * correct flips the survivor of the same pair and then confirms. Throws on 409\n * when somebody else already resolved it — refetch rather than retry.\n */\n async resolve(id: string, body: ResolveFactRequest): Promise<FactProposalDetail> {\n const res = await this.http.post<{ success: boolean; data: FactProposalDetail }>(\n `/facts/${encodeURIComponent(id)}/resolve`,\n { body },\n );\n return unwrapData(res);\n }\n\n /** The admin audit view. Pass a proposal id to scope to one proposal's history. */\n async audit(proposalId?: string, skip?: number, take?: number): Promise<FactAuditPage> {\n const res = await this.http.get<{ success: boolean; data: FactAuditPage }>(\n `/facts/audit${this.query({ proposalId, skip, take })}`,\n );\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n AssetDownload,\n BindRequest,\n CreatePackRequest,\n Pack,\n PackAuditPage,\n PackAuditQuery,\n PackBinding,\n PackBindingsResult,\n PackListPage,\n PackListQuery,\n PackStatus,\n PackVersion,\n PublishResult,\n UpsertDraftRequest,\n UpsertDraftResult,\n} from './types.js';\n\n/**\n * Pack registry client (common-infra component #2).\n *\n * Authority splits server-side; these methods only mirror it:\n *\n * - MEMBERS read (own-org + platform defaults) and author drafts. A draft is\n * inert until published.\n * - ORG ADMINS additionally publish, roll back (set-current), change lifecycle\n * status, bind/unbind into scopes, and org-disable a platform default.\n *\n * Impersonation is read-only here: every write returns 403 while impersonating.\n */\nexport class PacksClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n // ── reads (member-level) ─────────────────────────────────────────────────────\n\n /** List org + default packs, hydrated with current version, disable + binding counts. */\n async list(params: PackListQuery = {}): Promise<PackListPage> {\n const res = await this.http.get<{ success: boolean; data: PackListPage }>(\n `/packs${this.query({\n source: params.source,\n status: params.status,\n productScope: params.productScope,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** One pack with its version summary (stamped history is readable at any status). */\n async get(id: string): Promise<Pack> {\n const res = await this.http.get<{ success: boolean; data: Pack }>(`/packs/${id}`);\n return unwrapData(res);\n }\n\n /** One version with its content metadata (prompt text inlined) + selectors. */\n async getVersion(id: string, versionId: string): Promise<PackVersion> {\n const res = await this.http.get<{ success: boolean; data: PackVersion }>(`/packs/${id}/versions/${versionId}`);\n return unwrapData(res);\n }\n\n /** Download one asset's bytes (base64) — console preview. */\n async getAsset(id: string, versionId: string, name: string): Promise<AssetDownload> {\n const res = await this.http.get<{ success: boolean; data: AssetDownload }>(\n `/packs/${id}/versions/${versionId}/assets/${encodeURIComponent(name)}`,\n );\n return unwrapData(res);\n }\n\n /** The org's pack audit trail. */\n async audit(params: PackAuditQuery = {}): Promise<PackAuditPage> {\n const res = await this.http.get<{ success: boolean; data: PackAuditPage }>(\n `/packs/audit${this.query({\n packId: params.packId,\n event: params.event,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n // ── authoring (member-level) ──────────────────────────────────────────────────\n\n /** Register a new org pack. Source is always 'org'. */\n async create(body: CreatePackRequest): Promise<Pack> {\n const res = await this.http.post<{ success: boolean; data: Pack }>('/packs', { body });\n return unwrapData(res);\n }\n\n /** Create-or-replace the pack's single draft version, wholesale. */\n async upsertDraft(id: string, body: UpsertDraftRequest): Promise<UpsertDraftResult> {\n const res = await this.http.put<{ success: boolean; data: UpsertDraftResult }>(`/packs/${id}/draft`, { body });\n return unwrapData(res);\n }\n\n // ── governance (org-admin) ────────────────────────────────────────────────────\n\n /** Freeze the draft as the next version. Returns the version + any publish warnings. */\n async publish(id: string): Promise<PublishResult> {\n const res = await this.http.post<{ success: boolean; data: PublishResult }>(`/packs/${id}/publish`, { body: {} });\n return unwrapData(res);\n }\n\n /** Repoint currentVersionId to a published version (the rollback op). */\n async setCurrent(id: string, versionId: string): Promise<void> {\n await this.http.post(`/packs/${id}/set-current`, { body: { versionId } });\n }\n\n /** Transition a pack's lifecycle status (active / deprecated / disabled). */\n async setStatus(id: string, status: PackStatus): Promise<Pack> {\n const res = await this.http.post<{ success: boolean; data: Pack }>(`/packs/${id}/status`, { body: { status } });\n return unwrapData(res);\n }\n\n /** Org-disable a platform default pack. */\n async defaultDisable(id: string): Promise<void> {\n await this.http.post(`/packs/${id}/default-disable`, { body: {} });\n }\n\n /** Re-enable a platform default the org had disabled. */\n async defaultEnable(id: string): Promise<void> {\n await this.http.post(`/packs/${id}/default-enable`, { body: {} });\n }\n\n // ── bindings ──────────────────────────────────────────────────────────────────\n\n /** A pack's bindings for the acting org (member-readable). */\n async listBindings(id: string): Promise<PackBinding[]> {\n const res = await this.http.get<{ success: boolean; data: PackBindingsResult }>(`/packs/${id}/bindings`);\n return unwrapData(res).items;\n }\n\n /** Bind a pack into a scope, optionally pinned to a published version (org-admin). */\n async addBinding(id: string, body: BindRequest): Promise<PackBinding> {\n const res = await this.http.post<{ success: boolean; data: PackBinding }>(`/packs/${id}/bindings`, { body });\n return unwrapData(res);\n }\n\n /** Remove a binding (org-admin). */\n async removeBinding(id: string, bindingId: string): Promise<void> {\n await this.http.delete(`/packs/${id}/bindings/${bindingId}`);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n BrandCanonDiff,\n BrandCanonVersion,\n BrandCanonVersionPage,\n BrandConflict,\n BrandEnforcementHitPage,\n BrandEnforcementQuery,\n BrandPinState,\n BrandRoleAffordances,\n BrandStewardRole,\n BrandVersionQuery,\n} from './types.js';\n\n/**\n * Brand Authority client (MKT-IP01, Marketing common-infra surface).\n *\n * Reads a brand's confirmed, versioned canon and its governance state for the\n * console Brand Authority view: the published versions and their diffs, the open\n * confirmation conflicts, the enforcement hits, and the pinned-version state. A\n * brand is exactly one Marketing sandbox, so every read is sandbox-scoped.\n *\n * The routes are read-only here — propose/confirm/publish/rollback are governed\n * by the shared fact-governance loop and the pack registry (a brand fact is a\n * fact; a brand canon version is a pack version). This client's role is the\n * brand-SHAPED read model plus the pure affordance helper the view gates on. The\n * live backend routes are the backend owner's deferred step (MKT-IP01-I08).\n */\nexport class BrandAuthorityClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The published, immutable versions for a brand, newest first. */\n async versions(params: BrandVersionQuery): Promise<BrandCanonVersionPage> {\n const res = await this.http.get<{ success: boolean; data: BrandCanonVersionPage }>(\n `/brand-authority/versions${this.query({\n sandboxId: params.sandboxId,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** One published version, with its enforceable rules and declared sparseness. */\n async version(sandboxId: string, version: number): Promise<BrandCanonVersion> {\n const res = await this.http.get<{ success: boolean; data: BrandCanonVersion }>(\n `/brand-authority/versions/${encodeURIComponent(String(version))}${this.query({ sandboxId })}`,\n );\n return unwrapData(res);\n }\n\n /** The diff between two immutable versions (added / removed / changed rules). */\n async diff(sandboxId: string, fromVersion: number, toVersion: number): Promise<BrandCanonDiff> {\n const res = await this.http.get<{ success: boolean; data: BrandCanonDiff }>(\n `/brand-authority/diff${this.query({ sandboxId, from: fromVersion, to: toVersion })}`,\n );\n return unwrapData(res);\n }\n\n /** Open confirmation conflicts — each carries BOTH sides (MKT-IP01-I03). */\n async conflicts(sandboxId: string): Promise<BrandConflict[]> {\n const res = await this.http.get<{ success: boolean; data: BrandConflict[] }>(\n `/brand-authority/conflicts${this.query({ sandboxId })}`,\n );\n return unwrapData(res);\n }\n\n /** Enforcement hits (drafts refused/warned), each citing rule + canon version. */\n async enforcementHits(params: BrandEnforcementQuery): Promise<BrandEnforcementHitPage> {\n const res = await this.http.get<{ success: boolean; data: BrandEnforcementHitPage }>(\n `/brand-authority/enforcement-hits${this.query({\n sandboxId: params.sandboxId,\n canonVersion: params.canonVersion,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** The pinned-vs-current version state for a brand's running work. */\n async pinState(sandboxId: string): Promise<BrandPinState> {\n const res = await this.http.get<{ success: boolean; data: BrandPinState }>(\n `/brand-authority/pin${this.query({ sandboxId })}`,\n );\n return unwrapData(res);\n }\n}\n\n/**\n * brandRoleAffordances is the pure, fail-closed mapping from a role to the gated\n * controls it may use, at the CURRENT enforced floor (MKT-IP01-I04). Confirm,\n * publish and rollback are org-admin-only; everyone else is a viewer who may only\n * propose (a non-steward may propose only, §8). An unknown role falls through to\n * the viewer floor. This is the ONE place the console gates\n * propose/confirm/publish/rollback, so it is a pure function with an exhaustive\n * test — never a scattered boolean in the view. The per-category steward grade is\n * escalated (MKT-IP01-I04) and is intentionally not represented here.\n */\nexport function brandRoleAffordances(role: BrandStewardRole): BrandRoleAffordances {\n if (role === 'org-admin') {\n return { canPropose: true, canConfirm: true, canPublish: true, canRollback: true };\n }\n return { canPropose: true, canConfirm: false, canPublish: false, canRollback: false };\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n MarketingAudienceSummary,\n MarketingAudienceSummaryQuery,\n ImportMarketingConsentRequest,\n MarketingConsentRecord,\n MarketingConsentRecordQuery,\n} from './types.js';\n\n/**\n * Marketing consent operator client (IMP-MKT04-SURFACE, MKT-IP04 §6).\n *\n * The authenticated, tenant-scoped READ counterpart to the engine's write path:\n * an org administrator can see a subject's current consent state and the event\n * provenance that established it, and the PII-safe approved audience size and\n * exclusion breakdown for a scope+purpose. The org is derived server-side from the\n * verified session (never a request parameter), and RLS fences every read to the\n * tenant. These are read-only surfaces over the durable ledger (migration 0096);\n * the consent-event ingress and unsubscribe are the engine's HMAC machine path.\n */\nexport class MarketingConsentClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /**\n * The consent state + event provenance for one subject/purpose. Returns null\n * when the ledger has no record for the subject — deliberately distinct from a\n * missing route (which throws an HttpError), so a caller never conflates \"no\n * consent recorded\" with \"endpoint absent\".\n */\n async record(params: MarketingConsentRecordQuery): Promise<MarketingConsentRecord | null> {\n const res = await this.http.get<{ success: boolean; data: MarketingConsentRecord | null }>(\n `/marketing-consent/records/${encodeURIComponent(params.contactId)}${this.query({\n purpose: params.purpose,\n project_id: params.projectId,\n sandbox_id: params.sandboxId,\n })}`,\n );\n // A `null` data is a valid absence (the subject has no record); unwrapData only\n // rejects a missing (undefined) `data` field, so null passes through.\n return unwrapData<MarketingConsentRecord | null>(res);\n }\n\n /**\n * The PII-safe audience summary for a scope+purpose: the approved (sendable)\n * member count and the exclusion breakdown (confirmed / pending / unsubscribed).\n */\n async audienceSummary(params: MarketingAudienceSummaryQuery): Promise<MarketingAudienceSummary> {\n const res = await this.http.get<{ success: boolean; data: MarketingAudienceSummary }>(\n `/marketing-consent/audience-summary${this.query({\n purpose: params.purpose,\n project_id: params.projectId,\n sandbox_id: params.sandboxId,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** Records a confirmed, lawful-basis-documented import for an existing active\n * contact. The authenticated backend derives the organization and verifies the\n * project/sandbox parent chain before writing the authoritative projection. */\n async importConsent(body: ImportMarketingConsentRequest): Promise<MarketingConsentRecord> {\n const res = await this.http.post<{ success: boolean; data: MarketingConsentRecord }>(\n '/marketing-consent/imports',\n { body },\n );\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n MeetingCitationHydration,\n MeetingConfirmAction,\n MeetingConfirmField,\n MeetingConfirmResolution,\n MeetingFactCategory,\n MeetingFieldState,\n MeetingFilingState,\n MeetingGateBehavior,\n MeetingMinutesDraft,\n MeetingMinutesRevision,\n\n MeetingRetentionSetting,\n\n SetMeetingRetentionSettingRequest,\n CalendarWriteConsent,\n CalendarWriteConsentRequest,\n FollowThroughClassificationMutation,\n FollowThroughClassificationRequest,\n FollowThroughClassificationReview,\n MeetingPrecision,\n MeetingResolution,\n MeetingRoleAffordances,\n MeetingViewerRole,\n} from './types.js';\n\n/**\n * Meeting minutes & confirm-queue client (MTG-IP02; COR-MTG-IP02 I04).\n *\n * Reads a captured meeting's reviewed minutes drafts and its confirmation queue\n * for the console meeting view, both filing-aware (an unfiled meeting is\n * capturer-only). The reads are sandbox-scoped.\n *\n * The live backend read routes are the backend/console owners' deferred step (the\n * console source tree is absent in this working copy). This client's role is the\n * meeting-SHAPED read model plus the pure confirm-loop logic the view gates on —\n * the no-overdue safety, the resolution reducer, the gate behavior and the\n * MM-D044/MM-D041 affordances — all MANUAL-SYNC with the engine.\n */\nexport class MeetingMinutesClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The minutes drafts visible to the viewer in a sandbox (filing-aware). */\n async drafts(sandboxId: string): Promise<MeetingMinutesDraft[]> {\n const res = await this.http.get<{ success: boolean; data: MeetingMinutesDraft[] }>(\n `/meeting-minutes/drafts${this.query({ sandboxId })}`,\n );\n return unwrapData(res);\n }\n\n /** The open confirmation queue for a meeting (owner + inferred-due fields). */\n async confirmQueue(sandboxId: string, occurrence: string): Promise<MeetingConfirmField[]> {\n const res = await this.http.get<{ success: boolean; data: MeetingConfirmField[] }>(\n `/meeting-minutes/confirm-queue${this.query({ sandboxId, occurrence })}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Resolve one queued field: confirm/correct/reject. A reject writes rejection\n * memory server-side, so the same value never re-surfaces. Returns the resolved\n * proposal.\n */\n async resolveConfirmField(\n id: string,\n resolution: MeetingConfirmResolution,\n ): Promise<unknown> {\n const res = await this.http.post<{ success: boolean; data: unknown }>(\n `/meeting-minutes/confirm-queue/${encodeURIComponent(id)}/resolve`,\n { body: resolution },\n );\n return unwrapData(res);\n }\n\n /**\n * The Teams-only correction precision over the org's resolved meeting facts. The\n * number is evidence-phase (it needs real corrections); this reads what the\n * confirm resolutions durably recorded.\n */\n async precision(): Promise<MeetingPrecision> {\n const res = await this.http.get<{ success: boolean; data: MeetingPrecision }>(\n `/meeting-minutes/precision`,\n );\n return unwrapData(res);\n }\n\n /**\n * Hydrate a citation anchor (the click-through). Visibility-fenced and verbatim\n * FAIL-CLOSED — the live open against the tenant is the deferred step.\n */\n async hydrateCitation(\n sandboxId: string,\n occurrence: string,\n anchor: string,\n ): Promise<MeetingCitationHydration> {\n const res = await this.http.get<{ success: boolean; data: MeetingCitationHydration }>(\n `/meeting-minutes/citations/hydrate${this.query({ sandboxId, occurrence, anchor })}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Owner-gated (MM-D041) human minutes revision: a new artifact_substrate version.\n * Refused server-side unless the caller is the meeting owner.\n */\n async reviseMinutes(occurrence: string, revision: MeetingMinutesRevision): Promise<unknown> {\n const res = await this.http.post<{ success: boolean; data: unknown }>(\n `/meeting-minutes/minutes/${encodeURIComponent(occurrence)}/revise`,\n { body: revision },\n );\n return unwrapData(res);\n }\n\n /** Admin-only privacy-control read. The backend resolves the effective,\n * append-only setting under the caller's organization; no client window is an\n * authority for the sweep. */\n async retentionSetting(): Promise<MeetingRetentionSetting> {\n const res = await this.http.get<{ success: boolean; data: MeetingRetentionSetting }>(\n '/meeting-minutes/retention-setting',\n );\n return unwrapData(res);\n }\n\n /** Admin-only audited append of a new forward-only retention setting. */\n async setRetentionSetting(request: SetMeetingRetentionSettingRequest): Promise<MeetingRetentionSetting> {\n const res = await this.http.post<{ success: boolean; data: MeetingRetentionSetting }>(\n '/meeting-minutes/retention-setting', { body: request },\n );\n return unwrapData(res);\n }\n\n /**\n * Admin-only calendar-write consent attestation (MTG-IP05 A7). The backend\n * stamps attestedBy+attestedAt server-side and refuses (422) unless the named\n * credential's scope carries Calendars.ReadWrite. The follow-up calendar act's\n * proposal and execution gates read the resulting state.\n */\n async grantCalendarWriteConsent(request: CalendarWriteConsentRequest): Promise<CalendarWriteConsent> {\n const res = await this.http.post<{ success: boolean; data: CalendarWriteConsent }>(\n '/meeting-minutes/calendar-write-consent/grant', { body: request },\n );\n return unwrapData(res);\n }\n\n /**\n * Admin-only calendar-write consent revocation (MTG-IP05 A7). Durable\n * suppression: the backend stamps revokedBy+revokedAt and the engine gates\n * read the pair as not-granted, failing the calendar path closed.\n */\n async revokeCalendarWriteConsent(request: CalendarWriteConsentRequest): Promise<CalendarWriteConsent> {\n const res = await this.http.post<{ success: boolean; data: CalendarWriteConsent }>(\n '/meeting-minutes/calendar-write-consent/revoke', { body: request },\n );\n return unwrapData(res);\n }\n\n /** Participant-gated review projection for the latest classification epoch. */\n async followThroughClassification(\n sandboxId: string,\n occurrence: string,\n ): Promise<FollowThroughClassificationReview | null> {\n const res = await this.http.get<{\n success: boolean;\n data: FollowThroughClassificationReview | null;\n }>(`/meeting-minutes/followthrough-classification${this.query({ sandboxId, occurrence })}`);\n return unwrapData(res);\n }\n\n /** Confirm the complete family set. This authors a server-owned successor\n * sheet version but never invokes the engine or creates an act. */\n async confirmFollowThroughClassification(\n batchId: string,\n request: FollowThroughClassificationRequest,\n ): Promise<FollowThroughClassificationMutation> {\n const res = await this.http.post<{ success: boolean; data: FollowThroughClassificationMutation }>(\n `/meeting-minutes/followthrough-classification/${encodeURIComponent(batchId)}/confirm`,\n { body: request },\n );\n return unwrapData(res);\n }\n\n /** Return a confirmed, still-unlocked epoch to an empty-family draft. */\n async reviseFollowThroughClassification(\n batchId: string,\n request: FollowThroughClassificationRequest,\n ): Promise<FollowThroughClassificationMutation> {\n const res = await this.http.post<{ success: boolean; data: FollowThroughClassificationMutation }>(\n `/meeting-minutes/followthrough-classification/${encodeURIComponent(batchId)}/revise`,\n { body: request },\n );\n return unwrapData(res);\n }\n}\n\n/**\n * meetingGateBehavior is the DECLARED gate behavior of a meeting fact category\n * (MANUAL-SYNC with engine meetingdistill.CategoryGateBehavior): the two\n * high-stakes fields always confirm; a topic tag never gates.\n */\nexport function meetingGateBehavior(category: MeetingFactCategory): MeetingGateBehavior {\n return category === 'topic-tag' ? 'never-gates' : 'always-confirm';\n}\n\n/**\n * resolveMeetingField is the confirm/correct/reject reducer, MANUAL-SYNC with\n * engine meetingdistill.ResolveField: confirm keeps the extracted value as fact\n * (provenance extracted); correct replaces it as human-provided; reject suppresses\n * it (no value is fact). The console applies this to preview a resolution.\n */\nexport function resolveMeetingField(\n action: MeetingConfirmAction,\n extractedValue: string,\n correctedValue: string,\n): MeetingResolution {\n switch (action) {\n case 'confirm':\n return { state: 'confirmed', value: extractedValue, provenance: 'extracted' };\n case 'correct':\n return { state: 'corrected', value: correctedValue.trim(), provenance: 'human' };\n case 'reject':\n return { state: 'rejected', value: '', provenance: 'extracted' };\n }\n}\n\n/**\n * isMeetingCommitmentOverdue is the no-overdue-from-unconfirmed-due safety rule,\n * MANUAL-SYNC with engine meetingdistill.Overdue: overdue is a claim about a REAL\n * deadline, so it is made ONLY from a due a human confirmed or corrected. An\n * extracted (unconfirmed) inferred due — however far past — is never overdue, and\n * a field with no due never is. The console must not render \"overdue\" otherwise.\n */\nexport function isMeetingCommitmentOverdue(\n state: MeetingFieldState,\n dueISO: string | undefined,\n nowISO: string,\n): boolean {\n if (!dueISO) return false;\n if (state !== 'confirmed' && state !== 'corrected') return false;\n const due = Date.parse(dueISO);\n const now = Date.parse(nowISO);\n if (Number.isNaN(due) || Number.isNaN(now)) return false;\n return now > due;\n}\n\n/**\n * meetingRoleAffordances is the pure MM-D044/MM-D041 affordance logic the meeting\n * view gates on: an unfiled meeting is readable only by its capturer; once filed,\n * sandbox members may read it; any participant may work the confirm queue for a\n * meeting they can see; only the capturer may file; only the meeting owner may\n * revise the minutes. It is fail-closed — an outsider may do nothing.\n */\nexport function meetingRoleAffordances(\n role: MeetingViewerRole,\n filingState: MeetingFilingState,\n isOwner: boolean,\n): MeetingRoleAffordances {\n const filed = filingState === 'filed';\n const canView = role === 'capturer' || (filed && (role === 'participant' || role === 'sandbox-member'));\n return {\n canView,\n // A participant (or the capturer) who can see the meeting may resolve its queue.\n canResolveConfirmations: canView && (role === 'capturer' || role === 'participant'),\n // Only the capturer may file, and only while unfiled.\n canFile: role === 'capturer' && !filed,\n // Only the meeting owner may revise the minutes (MM-D041), once filed.\n canReviseMinutes: filed && isOwner,\n };\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n CommitmentActState,\n CommitmentAggregateStatus,\n CommitmentTracker,\n ResolveConflictRequest,\n} from './types.js';\n\n/**\n * Follow-through commitments tracker & conflict-resolution client (MTG-IP05\n * Wave 4, step 18 / §2.8).\n *\n * Reads the per-association follow-through projection over a meeting's\n * commitments — each commitment's aggregate status (§3.3), its act associations\n * (family, act state, external link, reconciliation), and its one-time nudge\n * state — and resolves a surfaced reconciliation conflict on one association.\n *\n * The tracker read is membership-gated server-side (a non-member sees nothing);\n * the conflict resolve is authority-gated (only the commitment's own owner, or an\n * activated project-owner fallback, may resolve — MM-D041). This client is the\n * read model plus the pure presentation helpers the console view gates on; the\n * authority itself is the backend's, never re-decided here.\n */\nexport class FollowThroughClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /**\n * The commitments tracker for a meeting (or the whole sandbox when occurrence\n * is omitted): one row per commitment with its aggregate status, association\n * sub-rows and nudge state. Membership-fenced server-side.\n */\n async commitments(sandboxId: string, occurrence?: string): Promise<CommitmentTracker[]> {\n const res = await this.http.get<{ success: boolean; data: CommitmentTracker[] }>(\n `/meeting-minutes/commitments${this.query({ sandboxId, occurrence })}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Resolve a surfaced reconciliation conflict on one association (link). The\n * backend applies MM-D041's ownership authority and refuses a non-owner, or a\n * project-owner fallback while the commitment owner is still active — the\n * refusal is recorded. On success the association's observation is closed.\n */\n async resolveConflict(linkId: string, request: ResolveConflictRequest): Promise<unknown> {\n const res = await this.http.post<{ success: boolean; data: unknown }>(\n `/meeting-minutes/commitments/reconciliation/${encodeURIComponent(linkId)}/resolve`,\n { body: request },\n );\n return unwrapData(res);\n }\n}\n\n/**\n * commitmentTrackerStatusLabel is the human label for a commitment's aggregate\n * status, MANUAL-SYNC with the console view-model. `confirmed` is deliberately\n * NOT \"tracked\": §3.3's honesty rule keeps a commitment whose only association is\n * preparing/blocked/failed/rejected/uncertain out of `tracked`.\n */\nexport function commitmentTrackerStatusLabel(status: CommitmentAggregateStatus): string {\n switch (status) {\n case 'proposed':\n return 'Proposed';\n case 'confirmed':\n return 'Confirmed';\n case 'tracked':\n return 'Tracked';\n case 'done':\n return 'Done';\n case 'conflicted':\n return 'Conflict — needs resolution';\n }\n}\n\n/**\n * commitmentActStateLabel renders one association's §3.3 act state honestly: a\n * `preparing` association is \"recovery needed\", never \"sent\". MANUAL-SYNC with\n * the engine's projection and the console view-model.\n */\nexport function commitmentActStateLabel(state: CommitmentActState): string {\n switch (state) {\n case 'preparing':\n return 'Preparing — recovery needed';\n case 'queued':\n return 'Queued';\n case 'executed':\n return 'Filed';\n case 'rejected':\n return 'Rejected';\n case 'blocked':\n return 'Blocked';\n case 'failed':\n return 'Failed';\n case 'uncertain':\n return 'Needs a person';\n case 'superseded':\n return 'Superseded';\n }\n}\n\n/**\n * isCommitmentConflicted reports whether a commitment's aggregate status is a\n * surfaced conflict awaiting human resolution — the single gate the console uses\n * to offer the resolve control.\n */\nexport function isCommitmentConflicted(status: CommitmentAggregateStatus): boolean {\n return status === 'conflicted';\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n CrmHandoffDetail,\n CrmHandoffDisposition,\n CrmHandoffListQuery,\n CrmHandoffOutcome,\n CrmHandoffSummary,\n RecordCrmDispositionRequest,\n} from './types.js';\n\n/**\n * Marketing CRM-handoffs operator client (MKT-IP06 §10 / IMP-MKT06-SURFACE).\n *\n * The authenticated, tenant-scoped surface an org administrator (the marketing lead\n * / sales owner) uses to see the durable CRM handoff records (migration 0094) — the\n * qualified signals that were disclosed, each transport outcome and provider ids, and\n * the current sales disposition — and to record the sales owner's accept /\n * reject-with-reason decision. The org/project are derived server-side from the\n * verified session and a caller-named sandbox; RLS fences every read to the tenant.\n *\n * This client does NOT approve the disclosure act (that binds the confidential\n * qualified-signal artifact and rides the existing approvals surface — see\n * ApprovalsClient) and does NOT report CRM connection health (that is the existing\n * connections surface). The handoff detail carries the artifact + approval refs so a\n * caller can cross-link to inspect exactly what is awaiting approval.\n */\nexport class CrmHandoffsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The sandbox's handoffs, newest first, each with its outcome and current\n * disposition. Admin-only; the scope is server-derived from the sandbox id. */\n async list(params: CrmHandoffListQuery): Promise<CrmHandoffSummary[]> {\n const res = await this.http.get<{ success: boolean; data: CrmHandoffSummary[] }>(\n `/marketing-crm-handoff/handoffs${this.query({ sandboxId: params.sandboxId })}`,\n );\n return unwrapData(res);\n }\n\n /** One handoff in full: outcome, current disposition, resolved readiness-criteria\n * version, artifact + approval refs, and the static boundary statement. */\n async get(id: string): Promise<CrmHandoffDetail> {\n const res = await this.http.get<{ success: boolean; data: CrmHandoffDetail }>(\n `/marketing-crm-handoff/handoffs/${encodeURIComponent(id)}`,\n );\n return unwrapData(res);\n }\n\n /** Record the sales owner's accept / reject-with-reason disposition, prospectively\n * (a new version each time; a prior decision is never rewritten). Returns the\n * recorded decision with its version and server-stamped decider. */\n async recordDisposition(id: string, body: RecordCrmDispositionRequest): Promise<CrmHandoffDisposition> {\n const res = await this.http.post<{ success: boolean; data: CrmHandoffDisposition }>(\n `/marketing-crm-handoff/handoffs/${encodeURIComponent(id)}/disposition`,\n { body },\n );\n return unwrapData(res);\n }\n}\n\n// ── pure presentation helpers (no I/O) ──────────────────────────────────────────\n\n/** A human label for the transport outcome. `uncertain` is deliberately not \"done\":\n * the operator must see that an ambiguous transport was never confirmed. */\nexport function crmHandoffOutcomeLabel(outcome: CrmHandoffOutcome): string {\n switch (outcome) {\n case 'complete':\n return 'Completed';\n case 'partial':\n return 'Partial — contact written, note pending';\n case 'uncertain':\n return 'Uncertain — outcome unconfirmed';\n case 'failed':\n return 'Failed';\n case 'pending':\n return 'Pending';\n default:\n return 'Unknown';\n }\n}\n\n/** Whether a handoff is still awaiting a sales-owner decision. */\nexport function crmHandoffAwaitingDisposition(h: CrmHandoffSummary): boolean {\n return h.disposition == null;\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type { PersonExportDownload, PersonExportStatus } from './types.js';\n\n/**\n * Per-person equivalent-data export client (MTG-IP08 §6 step 8, Google ToS §5.d).\n *\n * §5.d obliges the product to let a person obtain THEIR OWN equivalent data for as\n * long as it stores data derived from the provider API. This client reads that\n * export for one contact — the meetings they took part in, the decisions and\n * commitments attributed to them (by CONFIRMED contact id, never display text), span\n * locators into the exact places those came from, and the minutes they may see.\n *\n * `status` is the lightweight summary (counts + limited/incomplete state) the surface\n * shows before a download; `download` is the full payload. Both are admin-gated,\n * org-isolated reads server-side; the authority is the backend's, never re-decided\n * here. Pass the SAME `asOf` to both so their operation key and snapshot agree.\n */\nexport class PersonExportClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, v);\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The per-person export status (counts + limited/incomplete state). */\n async status(sandboxId: string, contactId: string, asOf?: string): Promise<PersonExportStatus> {\n const res = await this.http.get<{ success: boolean; data: PersonExportStatus }>(\n `/meeting-minutes/person-export/status${this.query({ sandboxId, contactId, asOf })}`,\n );\n return unwrapData(res);\n }\n\n /** The full per-person equivalent-data export. */\n async download(sandboxId: string, contactId: string, asOf?: string): Promise<PersonExportDownload> {\n const res = await this.http.get<{ success: boolean; data: PersonExportDownload }>(\n `/meeting-minutes/person-export/download${this.query({ sandboxId, contactId, asOf })}`,\n );\n return unwrapData(res);\n }\n}\n\n/**\n * personExportIsLimited reports whether an export omitted some of the person's\n * meetings (the filing fence). The surface should show `incomplete_reason` when true\n * rather than presenting a partial export as complete.\n */\nexport function personExportIsLimited(status: Pick<PersonExportStatus, 'limited'>): boolean {\n return status.limited === true;\n}\n\n/** personExportIsEmpty reports whether an export holds no equivalent data at all. */\nexport function personExportIsEmpty(\n status: Pick<PersonExportStatus, 'participation_count' | 'decision_count' | 'commitment_count' | 'artifact_count'>,\n): boolean {\n return (\n status.participation_count === 0 &&\n status.decision_count === 0 &&\n status.commitment_count === 0 &&\n status.artifact_count === 0\n );\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n AppendVersionRequest,\n AppendVersionResult,\n ApproveArtifactRequest,\n Artifact,\n ArtifactApproval,\n ArtifactAuditPage,\n ArtifactAuditQuery,\n ArtifactContainer,\n ArtifactHandle,\n ArtifactListPage,\n ArtifactListQuery,\n ArtifactVersionContent,\n ArtifactVersionMeta,\n CreateArtifactRequest,\n} from './types.js';\n\n/**\n * Artifact substrate client (common-infra component #5).\n *\n * Authority splits server-side; these methods only mirror it:\n *\n * - MEMBERS read, mint, edit (append a version) and standalone-approve, WITHIN\n * a container they can reach.\n * - ORG ADMINS additionally archive, read the audit trail, and delete content\n * under a retention policy.\n *\n * Impersonation is read-only here: every write returns 403 while impersonating.\n *\n * # TWO THINGS THAT CHANGED, AND WHY THEY MATTER TO A CALLER\n *\n * **Every call names a CONTAINER.** `containerScope` + `containerRef` are not\n * a filter — they are the confidentiality boundary. The server resolves the\n * caller's real reach from them and refuses an artifact the container does not\n * cover, so passing the project you are looking at is required rather than\n * optional. Omitting `containerScope` means `project`.\n *\n * **Versions are named by HANDLE, never by `versionRef`.** A handle\n * (`artifact:<artifactId>/<versionId>@vN#<sha256>`) is returned by every write\n * and is what you pass back to approve, or attach to an action. `versionRef`\n * is a content reference that two different artifacts can share; it is for\n * display.\n *\n * A version is immutable and content-addressed. `appendVersion` is\n * compare-and-set on head via `parentVersionId` — a stale parent returns 409\n * (`head_moved`) so the caller re-fetches rather than silently forking — and\n * saving canonically identical content is a no-op that returns the existing\n * head.\n */\nexport class ArtifactsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n private container(c: ArtifactContainer): Record<string, string | undefined> {\n return { containerScope: c.containerScope, containerRef: c.containerRef };\n }\n\n // ── reads (member-level, within a reachable container) ───────────────────────\n\n /** List artifacts in one container — the per-project library. */\n async list(params: ArtifactListQuery): Promise<ArtifactListPage> {\n const res = await this.http.get<{ success: boolean; data: ArtifactListPage }>(\n `/artifacts${this.query({\n ...this.container(params),\n status: params.status,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** One artifact (head/approved version ids, no content). */\n async get(id: string, container: ArtifactContainer): Promise<Artifact> {\n const res = await this.http.get<{ success: boolean; data: Artifact }>(\n `/artifacts/${id}${this.query(this.container(container))}`,\n );\n return unwrapData(res);\n }\n\n /** Every version of an artifact, oldest first — the version strip. */\n async listVersions(id: string, container: ArtifactContainer): Promise<{ items: ArtifactVersionMeta[] }> {\n const res = await this.http.get<{ success: boolean; data: { items: ArtifactVersionMeta[] } }>(\n `/artifacts/${id}/versions${this.query(this.container(container))}`,\n );\n return unwrapData(res);\n }\n\n /** One version's metadata plus the handle that names it. */\n async getVersion(\n id: string,\n versionId: string,\n container: ArtifactContainer,\n ): Promise<{ version: ArtifactVersionMeta; handle: ArtifactHandle }> {\n const res = await this.http.get<{\n success: boolean;\n data: { version: ArtifactVersionMeta; handle: ArtifactHandle };\n }>(`/artifacts/${id}/versions/${versionId}${this.query(this.container(container))}`);\n return unwrapData(res);\n }\n\n /**\n * One version's bytes — the panel content view.\n *\n * Throws 410 `content_retention_deleted` for a version whose content was\n * removed under a retention policy. That is a distinct outcome from an empty\n * document and should be shown as one.\n */\n async getContent(id: string, versionId: string, container: ArtifactContainer): Promise<ArtifactVersionContent> {\n const res = await this.http.get<{ success: boolean; data: ArtifactVersionContent }>(\n `/artifacts/${id}/versions/${versionId}/content${this.query(this.container(container))}`,\n );\n return unwrapData(res);\n }\n\n /** Every approval for an artifact, newest first. */\n async listApprovals(id: string, container: ArtifactContainer): Promise<{ items: ArtifactApproval[] }> {\n const res = await this.http.get<{ success: boolean; data: { items: ArtifactApproval[] } }>(\n `/artifacts/${id}/approvals${this.query(this.container(container))}`,\n );\n return unwrapData(res);\n }\n\n /** The org's artifact audit trail (org-admin). */\n async audit(params: ArtifactAuditQuery = {}): Promise<ArtifactAuditPage> {\n const res = await this.http.get<{ success: boolean; data: ArtifactAuditPage }>(\n `/artifacts/audit${this.query({\n artifactId: params.artifactId,\n event: params.event,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n // ── authoring (member-level) ──────────────────────────────────────────────────\n\n /** Mint a new artifact (v1). Returns the handle for the version it created. */\n async create(body: CreateArtifactRequest): Promise<AppendVersionResult> {\n const res = await this.http.post<{ success: boolean; data: AppendVersionResult }>('/artifacts', { body });\n return unwrapData(res);\n }\n\n /**\n * Append an immutable version — the panel's Save. CAS on `parentVersionId`:\n * throws 409 `head_moved` if the head moved since the caller last fetched it.\n */\n async appendVersion(id: string, body: AppendVersionRequest): Promise<AppendVersionResult> {\n const res = await this.http.post<{ success: boolean; data: AppendVersionResult }>(`/artifacts/${id}/versions`, {\n body,\n });\n return unwrapData(res);\n }\n\n /**\n * Standalone approval — the complete draft→edit→approve loop, with no action\n * attached.\n *\n * An approval is a fact about CONTENT. It is never permission to send or\n * publish that content: that is a separate action with its own approval.\n */\n async approve(id: string, body: ApproveArtifactRequest): Promise<ArtifactApproval> {\n const res = await this.http.post<{ success: boolean; data: ArtifactApproval }>(`/artifacts/${id}/approve`, {\n body,\n });\n return unwrapData(res);\n }\n\n // ── governance (org-admin) ────────────────────────────────────────────────────\n\n /** Archive an artifact — no further versions (org-admin). */\n async archive(id: string, container: ArtifactContainer): Promise<void> {\n await this.http.post(`/artifacts/${id}/archive${this.query(this.container(container))}`, { body: {} });\n }\n\n /**\n * Delete one version's CONTENT under a retention policy (org-admin).\n *\n * The version, its type, digest and size survive as audit metadata; only the\n * bytes go. An approved action bound to that version can no longer execute —\n * a retention policy an in-flight action could override would not be one.\n */\n async deleteContentForRetention(\n id: string,\n versionId: string,\n container: ArtifactContainer,\n reason?: string,\n ): Promise<void> {\n await this.http.delete(\n `/artifacts/${id}/versions/${versionId}/content${this.query({ ...this.container(container), reason })}`,\n );\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n ConsumeSignalRequest,\n DismissSignalRequest,\n ListSignalsQuery,\n Signal,\n SignalAuditPage,\n SignalDetail,\n SignalListResult,\n SignalStats,\n} from './types.js';\n\n/**\n * Signal-store client (common-infra component #6).\n *\n * The org's durable record of what is worth acting on — scored, deduplicated\n * and source-attributed. Backend-resident and session-scoped (RLS-pinned by the\n * org-tx middleware), so no scope headers, unlike the engine-proxied action\n * queue.\n *\n * Reads are member-level: the queue is the org's shared attention surface, and\n * hiding it from members would only make the store invisible to the people who\n * have to act on it. `dismiss` is org-admin-only server-side, because it\n * suppresses the whole org's attention.\n *\n * Reads never mutate: listing does not triage, and opening a signal does not\n * consume it.\n */\nexport class SignalsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | boolean | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /**\n * The signals queue. Returns only what is visible in the caller's scope, plus\n * a coverage envelope naming what was walled off — state that coverage rather\n * than letting two users silently get different answers.\n *\n * Expired signals are excluded unless `includeExpired` is set: they are kept\n * and queryable (that \"we saw this before\" survives is half the point), but\n * they are history, not attention.\n */\n async list(params: ListSignalsQuery = {}): Promise<SignalListResult> {\n const res = await this.http.get<{ success: boolean; data: SignalListResult }>(\n `/signals${this.query({\n kind: params.kind,\n status: params.status,\n priority: params.priority,\n scopeLevel: params.scopeLevel,\n scopeRef: params.scopeRef,\n includeExpired: params.includeExpired,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** Counts by status — powers the section badge. */\n async stats(): Promise<SignalStats> {\n const res = await this.http.get<{ success: boolean; data: SignalStats }>('/signals/stats');\n return unwrapData(res);\n }\n\n /**\n * One signal with its sightings, score + recorded method, evidence,\n * consumptions, predecessor link, and any prior dismissal that an escalation\n * later overrode.\n */\n async get(id: string): Promise<SignalDetail> {\n const res = await this.http.get<{ success: boolean; data: SignalDetail }>(\n `/signals/${encodeURIComponent(id)}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Mark a signal as picked up. An EXPLICIT act — status is org-shared, so it\n * must never be a side effect of somebody opening the page.\n */\n async triage(id: string): Promise<Signal> {\n const res = await this.http.post<{ success: boolean; data: Signal }>(\n `/signals/${encodeURIComponent(id)}/triage`,\n {},\n );\n return unwrapData(res);\n }\n\n /**\n * Deliberately set a signal aside, with a rationale. Org-admin only (403\n * otherwise).\n *\n * Dismissal suppresses DELIVERY at or below the tier the signal currently\n * holds; it never stops recording. A sighting that escalates above that tier\n * reopens the same record with this rationale disclosed — trust that can only\n * ratchet one way is not trust.\n */\n async dismiss(id: string, body: DismissSignalRequest): Promise<Signal> {\n const res = await this.http.post<{ success: boolean; data: Signal }>(\n `/signals/${encodeURIComponent(id)}/dismiss`,\n { body },\n );\n return unwrapData(res);\n }\n\n /** Link what acting on this signal produced, and (by default) mark it consumed. */\n async consume(id: string, body: ConsumeSignalRequest): Promise<Signal> {\n const res = await this.http.post<{ success: boolean; data: Signal }>(\n `/signals/${encodeURIComponent(id)}/consume`,\n { body },\n );\n return unwrapData(res);\n }\n\n /** The admin audit view. Pass a signal id to scope to one signal's history. */\n async audit(signalId?: string, skip?: number, take?: number): Promise<SignalAuditPage> {\n const res = await this.http.get<{ success: boolean; data: SignalAuditPage }>(\n `/signals/audit${this.query({ signalId, skip, take })}`,\n );\n return unwrapData(res);\n }\n}\n","import { BaseClient, type BaseClientOptions } from './http/BaseClient.js';\nimport { AuthClient } from './modules/auth/AuthClient.js';\nimport { MfaClient } from './modules/mfa/MfaClient.js';\nimport { UserClient } from './modules/user/UserClient.js';\nimport { OrganizationClient } from './modules/organization/OrganizationClient.js';\nimport { ProjectsClient } from './modules/projects/ProjectsClient.js';\nimport { SandboxesClient } from './modules/sandboxes/SandboxesClient.js';\nimport { CredentialsClient } from './modules/credentials/CredentialsClient.js';\nimport { ChatClient } from './modules/chat/ChatClient.js';\nimport { TemplatesClient } from './modules/agentEngine/TemplatesClient.js';\nimport { ScheduledTasksClient } from './modules/agentEngine/ScheduledTasksClient.js';\nimport { ResourcesClient } from './modules/resources/ResourcesClient.js';\nimport { SystemEventsClient } from './modules/systemEvents/SystemEventsClient.js';\nimport { SubscriptionsClient } from './modules/billing/SubscriptionsClient.js';\nimport { CreditsClient } from './modules/billing/CreditsClient.js';\nimport { UsageClient } from './modules/usage/UsageClient.js';\nimport { ApprovalsClient } from './modules/approvals/ApprovalsClient.js';\nimport { BudgetsClient } from './modules/budgets/BudgetsClient.js';\nimport { MeteringClient } from './modules/metering/MeteringClient.js';\nimport { ReferralsClient } from './modules/referrals/ReferralsClient.js';\nimport { ResellerClient } from './modules/reseller/ResellerClient.js';\nimport { PlatformAdminClient } from './modules/platformAdmin/PlatformAdminClient.js';\nimport { DeploymentsClient } from './modules/deployments/DeploymentsClient.js';\nimport { CapacityClient } from './modules/capacity/CapacityClient.js';\nimport { BIClient } from './modules/bi/BIClient.js';\nimport { DashboardsClient } from './modules/dashboards/DashboardsClient.js';\nimport { ConnectionsClient } from './modules/connections/ConnectionsClient.js';\nimport { ConnectClient } from './modules/connect/ConnectClient.js';\nimport { CapabilitiesClient } from './modules/capabilities/CapabilitiesClient.js';\nimport { ContactsClient } from './modules/contacts/ContactsClient.js';\nimport { FactsClient } from './modules/facts/FactsClient.js';\nimport { PacksClient } from './modules/packs/PacksClient.js';\nimport { BrandAuthorityClient } from './modules/brandAuthority/BrandAuthorityClient.js';\nimport { MarketingConsentClient } from './modules/marketingConsent/MarketingConsentClient.js';\nimport { MeetingMinutesClient } from './modules/meetingMinutes/MeetingMinutesClient.js';\nimport { FollowThroughClient } from './modules/followThrough/FollowThroughClient.js';\nimport { CrmHandoffsClient } from './modules/crmHandoffs/CrmHandoffsClient.js';\nimport { PersonExportClient } from './modules/personExport/PersonExportClient.js';\nimport { ArtifactsClient } from './modules/artifacts/ArtifactsClient.js';\nimport { SignalsClient } from './modules/signals/SignalsClient.js';\n\nexport type CloudAgentClientOptions = BaseClientOptions;\n\nclass AgentEngineFacade {\n constructor(\n public readonly templates: TemplatesClient,\n public readonly scheduledTasks: ScheduledTasksClient,\n ) {}\n}\n\nclass BillingFacade {\n constructor(\n public readonly subscriptions: SubscriptionsClient,\n public readonly credits: CreditsClient,\n ) {}\n}\n\nexport class CloudAgentClient {\n readonly http: BaseClient;\n readonly auth: AuthClient;\n readonly mfa: MfaClient;\n readonly user: UserClient;\n readonly organization: OrganizationClient;\n readonly projects: ProjectsClient;\n readonly sandboxes: SandboxesClient;\n readonly credentials: CredentialsClient;\n readonly chat: ChatClient;\n readonly agentEngine: AgentEngineFacade;\n readonly resources: ResourcesClient;\n readonly systemEvents: SystemEventsClient;\n readonly billing: BillingFacade;\n readonly usage: UsageClient;\n readonly budgets: BudgetsClient;\n /** SHR-IP08 non-LLM provider metering: per-provider spend caps. */\n readonly metering: MeteringClient;\n /** Action Policy: the approvals queue and its per-scope configuration. */\n readonly approvals: ApprovalsClient;\n readonly referrals: ReferralsClient;\n readonly reseller: ResellerClient;\n readonly platformAdmin: PlatformAdminClient;\n readonly deployments: DeploymentsClient;\n readonly capacity: CapacityClient;\n readonly bi: BIClient;\n readonly dashboards: DashboardsClient;\n /** Contact registry: the org's directory of people it knows about. */\n /** Component capability plane: which common-infrastructure components\n * this deployment has, and which the caller's organization may use. */\n readonly capabilities: CapabilitiesClient;\n readonly contacts: ContactsClient;\n /** Fact-governance: the knowledge-review queue (suggested contact merges). */\n readonly facts: FactsClient;\n readonly connections: ConnectionsClient;\n /** Connection lifecycle (MVP09 C2-SDK-CONNECTION): the typed authorize-start /\n * status / refresh / disconnect surface over the platform-owned\n * delegated-OAuth connect rail. Opaque state, no secret fields — the secure\n * connect flow drives it; secrets/OAuth input never touch chat card JSON. */\n readonly connect: ConnectClient;\n /** Pack registry: the org's published knowledge packs for agent sessions. */\n readonly packs: PacksClient;\n /** Brand Authority (MKT-IP01): a brand's confirmed, versioned canon and its\n * governance state (versions, diffs, conflicts, enforcement hits, pin state). */\n readonly brandAuthority: BrandAuthorityClient;\n /** Marketing consent (MKT-IP04): the operator READ view over the durable consent\n * ledger — a subject's consent state + event provenance, and the PII-safe\n * approved audience count + exclusion breakdown. */\n readonly marketingConsent: MarketingConsentClient;\n /** Meeting minutes (MTG-IP02): distilled minutes drafts, the confirm queue, its\n * confirm/correct/reject resolution, owner-gated minutes revision, correction\n * precision, and citation hydration. */\n readonly meetingMinutes: MeetingMinutesClient;\n /** Follow-through (MTG-IP05): the commitments tracker over per-association act\n * state, reconciliation and one-time nudge, plus surfaced-conflict resolution. */\n readonly followThrough: FollowThroughClient;\n readonly crmHandoffs: CrmHandoffsClient;\n /** Per-person equivalent-data export (MTG-IP08 §5.d): status + full download. */\n readonly personExport: PersonExportClient;\n /** Artifact substrate: versioned documents/briefs/digests with edit-then-approve. */\n readonly artifacts: ArtifactsClient;\n /** Signal store (common-infra #6): the org's durable record of what is worth\n * acting on — scored, deduplicated, and never a trigger. */\n readonly signals: SignalsClient;\n\n constructor(options: CloudAgentClientOptions) {\n this.http = new BaseClient(options);\n this.auth = new AuthClient(this.http);\n this.mfa = new MfaClient(this.http);\n this.user = new UserClient(this.http);\n this.organization = new OrganizationClient(this.http);\n this.projects = new ProjectsClient(this.http);\n this.sandboxes = new SandboxesClient(this.http);\n this.credentials = new CredentialsClient(this.http);\n this.chat = new ChatClient(this.http, { baseUrl: this.http.baseUrl, getToken: options.getToken });\n this.agentEngine = new AgentEngineFacade(\n new TemplatesClient(this.http),\n new ScheduledTasksClient(this.http),\n );\n this.resources = new ResourcesClient(this.http);\n this.systemEvents = new SystemEventsClient(this.http);\n this.billing = new BillingFacade(new SubscriptionsClient(this.http), new CreditsClient(this.http));\n this.usage = new UsageClient(this.http);\n this.budgets = new BudgetsClient(this.http);\n this.metering = new MeteringClient(this.http);\n this.approvals = new ApprovalsClient(this.http);\n this.referrals = new ReferralsClient(this.http);\n this.reseller = new ResellerClient(this.http);\n this.platformAdmin = new PlatformAdminClient(this.http);\n this.deployments = new DeploymentsClient(this.http);\n this.capacity = new CapacityClient(this.http);\n this.bi = new BIClient(this.http, this.http.baseUrl);\n this.dashboards = new DashboardsClient(this.http, this.http.baseUrl);\n this.capabilities = new CapabilitiesClient(this.http);\n this.contacts = new ContactsClient(this.http);\n this.facts = new FactsClient(this.http);\n this.connections = new ConnectionsClient(this.http);\n this.connect = new ConnectClient(this.http);\n this.packs = new PacksClient(this.http);\n this.brandAuthority = new BrandAuthorityClient(this.http);\n this.marketingConsent = new MarketingConsentClient(this.http);\n this.meetingMinutes = new MeetingMinutesClient(this.http);\n this.followThrough = new FollowThroughClient(this.http);\n this.crmHandoffs = new CrmHandoffsClient(this.http);\n this.personExport = new PersonExportClient(this.http);\n this.artifacts = new ArtifactsClient(this.http);\n this.signals = new SignalsClient(this.http);\n }\n}\n","export enum ProviderType {\n LOCAL = 'LOCAL',\n GOOGLE = 'GOOGLE',\n MICROSOFT = 'MICROSOFT',\n GITHUB = 'GITHUB',\n /** Generic OIDC provider (deployment-configured issuer). */\n OIDC = 'OIDC',\n WEB3_STELLAR = 'WEB3_STELLAR',\n}\n\nexport enum AccessType {\n READ = 'READ',\n WRITE = 'WRITE',\n ADMIN = 'ADMIN',\n}\n\nexport enum OrgRoles {\n USER = 0x00,\n BILLING = 0x01,\n WORKSPACES = 0x02,\n ADMINISTRATORS = 0xfe,\n OWNER = 0xff,\n}\n\nexport interface UserSummary {\n id: string;\n name: string;\n lastName: string;\n email: string;\n orgRole?: number | null;\n}\n","export enum MFAType {\n GOOGLE_AUTH = 'GOOGLE_AUTH',\n MAGIC_LINK = 'MAGIC_LINK',\n PASSKEY = 'PASSKEY',\n}\n\nexport interface MFAStatus {\n isEnabled: boolean;\n isRequired: boolean;\n isEnforced: boolean;\n enabledMethods: MFAType[];\n primaryMethod?: MFAType | null;\n sessionVerified: boolean;\n}\n\nexport interface MFASetupResponse {\n success: boolean;\n data?: {\n mfaType: MFAType;\n secret?: string;\n qrCode?: string;\n backupCodes?: string[];\n };\n message?: string;\n}\n\nexport interface MFAVerifySetupRequest {\n mfaType: MFAType;\n code?: string;\n credential?: Record<string, unknown>;\n}\n\nexport interface MFAVerifyLoginRequest {\n mfaType: MFAType;\n code?: string;\n credential?: Record<string, unknown>;\n}\n\nexport interface MFASimpleResponse {\n success: boolean;\n message?: string;\n data?: unknown;\n}\n\nexport interface MFAVerifyLoginResponse {\n success: boolean;\n accessToken?: string;\n refreshToken?: string;\n tokenId?: string;\n expiresAt?: number;\n user?: unknown;\n message?: string;\n error_code?: string;\n}\n\nexport interface MagicLinkSendResponse {\n success: boolean;\n message?: string;\n}\n\nexport interface MagicLinkActivateRequest {\n token: string;\n}\n","import type { PmRecord, PmRecordFamily, PmRevision } from './types.js';\nimport { PM_RECORD_FAMILIES } from './types.js';\n\n/**\n * ClowdPM project-memory coverage — the minimal, explainable completeness\n * summary (PJM-IP02 §7 step 10; architecture §4.6; context model §8 v1).\n *\n * This is the **v1 minimal** summary the surfaces slice ships: it is derived at\n * read time from the records themselves and the project's tailoring declaration,\n * and every area line carries the inputs it was derived from (a poor-man's\n * computation record). It deliberately does NOT implement the full versioned\n * coverage-derivation ENGINE — the per-family expected-set basis and the\n * cadence-freshness evaluation that lift an area to `thin`/`current` — which the\n * memory-core handoff explicitly deferred (it needs persisted computation\n * records). So in v1 an applicable area with any viable record caps at\n * `partial`, and nothing is reported `current`. That under-claim is the honest\n * choice: §4.6/E2 forbid `current` without a proven fresh cadence, and here no\n * cadence-freshness input is wired.\n *\n * Honesty properties preserved from the accepted law:\n * - a tailored-out area is `n/a`, never `none` (E4);\n * - an `extracted`/provisional value does not count as a viable record (§4.6\n * step 2) — it is surfaced separately as `provisionalCount`;\n * - every owner-required family needs an accepted, active registry contact to\n * count as viable; risk additionally requires server readiness, so a sole\n * ownerless risk in an applicable Risk area is `none` (E1);\n * - coverage is DERIVED, never asserted or edited — this function is the only\n * way to obtain it and it takes no state a caller could set.\n */\n\nexport type PmCoverageState = 'n/a' | 'none' | 'thin' | 'partial' | 'current';\n\nexport interface PmCoverageArea {\n family: PmRecordFamily;\n /** Human-friendly area name for the family (e.g. `risk` → \"Risk\"). */\n label: string;\n state: PmCoverageState;\n /** Whether the area is in the tailored (applicable) set. */\n applicable: boolean;\n /** Total records of this family (any origin). */\n totalCount: number;\n /** Records whose current revision is a viable, confirmed (human) record. */\n viableCount: number;\n /** Records whose current revision is provisional (extracted, unconfirmed). */\n provisionalCount: number;\n /** Whether any current revision declares a review cadence (surfaced, not yet used for freshness). */\n cadenceDeclared: boolean;\n /** The derivation, in one sentence — the evidence behind the state label. */\n reason: string;\n}\n\nexport interface PmCoverageSummary {\n /** Whether a `tailoring` record exists — the denominator of every claim. */\n tailoringDeclared: boolean;\n areas: PmCoverageArea[];\n /** A one-line honest caveat about what this v1 summary does and does not prove. */\n note: string;\n}\n\nconst FAMILY_LABELS: Record<string, string> = {\n tailoring: 'Tailoring',\n phase_gate: 'Phase / gate',\n baseline: 'Scope baseline',\n deliverable: 'Deliverables',\n wbs_node: 'Work breakdown',\n activity: 'Activities',\n decision: 'Decisions',\n action: 'Actions',\n risk: 'Risk',\n stakeholder: 'Stakeholders',\n issue: 'Issues',\n assumption: 'Assumptions',\n communication: 'Communications',\n};\n\n// Rolling-compatibility fallback for records read from the pre-policy wire.\n// Current servers return requiresAccountableOwner, including for new families.\nconst OWNER_REQUIRED: ReadonlySet<string> = new Set([\n 'tailoring',\n 'phase_gate',\n 'baseline',\n 'decision',\n 'action',\n 'activity',\n 'risk',\n 'stakeholder',\n 'issue',\n 'assumption',\n 'communication',\n]);\n\n/**\n * Small, non-exhaustive map from a family to the tailoring-declaration keys that\n * mark its area applicable. It is intentionally minimal (the prompt: do not\n * build exhaustive classification tables): an unmatched family defaults to\n * applicable and says so, rather than hiding the area.\n */\nconst DISCIPLINE_ALIASES: Partial<Record<PmRecordFamily, readonly string[]>> = {\n baseline: ['scope', 'schedule', 'baseline'],\n deliverable: ['scope'],\n wbs_node: ['scope'],\n activity: ['schedule'],\n risk: ['risk'],\n stakeholder: ['stakeholder', 'stakeholders'],\n communication: ['communication', 'communications'],\n decision: ['knowledge', 'change', 'decision', 'decisions'],\n issue: ['issue', 'issues', 'execution'],\n assumption: ['assumption', 'assumptions', 'constraint', 'constraints'],\n action: ['action', 'actions', 'execution'],\n};\n\n// Families always in the applicable set (Initiating is mandatory, §8.3).\nconst ALWAYS_APPLICABLE: ReadonlySet<PmRecordFamily> = new Set(['tailoring', 'phase_gate']);\n\nfunction readDisciplines(records: PmRecord[]): Record<string, boolean> | null {\n const tailoring = records\n .filter((r) => r.family === 'tailoring' && isViable(r))\n .reduce<PmRecord | undefined>((latest, candidate) => {\n if (!latest) return candidate;\n return (candidate.current?.authoredAt ?? '') > (latest.current?.authoredAt ?? '')\n ? candidate\n : latest;\n }, undefined);\n const payload = tailoring?.current?.payload;\n if (!payload || typeof payload !== 'object') return null;\n const disciplines = (payload as { disciplines?: unknown }).disciplines;\n if (!disciplines || typeof disciplines !== 'object') return null;\n const out: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(disciplines as Record<string, unknown>)) {\n out[k.toLowerCase()] = v === true;\n }\n return out;\n}\n\n/**\n * Applicability under the tailoring declaration. Returns `true`/`false` when the\n * declaration decides it, or `null` when the area is not individually declared\n * (caller defaults it to applicable and notes the gap).\n */\nfunction applicabilityOf(\n family: PmRecordFamily,\n disciplines: Record<string, boolean> | null,\n): boolean | null {\n if (ALWAYS_APPLICABLE.has(family)) return true;\n if (!disciplines) return null;\n const keys = [family, ...(DISCIPLINE_ALIASES[family] ?? [])].map((k) => k.toLowerCase());\n let sawKey = false;\n for (const key of keys) {\n if (key in disciplines) {\n sawKey = true;\n if (disciplines[key]) return true; // any matching on-key makes the area applicable\n }\n }\n return sawKey ? false : null; // all matching keys off → tailored out; none present → undeclared\n}\n\nfunction isViable(record: PmRecord): boolean {\n const rev = record.current;\n if (!rev) return false;\n if (rev.origin !== 'human') return false; // an extracted/provisional value is not a viable record\n const requiresOwner = record.requiresAccountableOwner ?? OWNER_REQUIRED.has(rev.family);\n if (requiresOwner) {\n const namedActiveOwner =\n !!rev.accountableContactId?.trim() &&\n rev.accountableContactStatus === 'active' &&\n rev.accountableState === 'accepted';\n if (!namedActiveOwner) return false;\n }\n const requiresSubject = record.requiresSubjectContact ?? rev.family === 'stakeholder';\n if (\n requiresSubject &&\n (!record.subjectContactId?.trim() || record.subjectContactStatus !== 'active')\n ) {\n return false;\n }\n if (rev.family === 'risk' && rev.readiness !== 'ready') return false;\n return true;\n}\n\nfunction declaresCadence(rev: PmRevision): boolean {\n const p = rev.payload;\n if (!p || typeof p !== 'object') return false;\n const o = p as Record<string, unknown>;\n const cadence = o.cadence ?? o.reviewCadence ?? o.review_cadence;\n return typeof cadence === 'string' && cadence.trim().length > 0;\n}\n\n/**\n * Derive the minimal completeness summary from a project's records. Pure: same\n * records in ⇒ same summary out, with no hidden state.\n */\nexport function derivePmCoverage(records: PmRecord[]): PmCoverageSummary {\n const disciplines = readDisciplines(records);\n // An extracted tailoring proposal cannot choose the completeness denominator.\n // Only a human-authored declaration may tailor an area in or out.\n const tailoringDeclared = records.some(\n (r) => r.family === 'tailoring' && isViable(r),\n );\n\n const families: PmRecordFamily[] = [\n ...PM_RECORD_FAMILIES,\n ...records\n .map((r) => r.family)\n .filter((family) => !(PM_RECORD_FAMILIES as readonly string[]).includes(family)),\n ].filter((family, index, all) => all.indexOf(family) === index);\n\n const areas: PmCoverageArea[] = families.map((family) => {\n const family_records = records.filter((r) => r.family === family && r.current);\n const totalCount = family_records.length;\n let viableCount = 0;\n let provisionalCount = 0;\n let cadenceDeclared = false;\n for (const r of family_records) {\n const rev = r.current!;\n if (isViable(r)) viableCount += 1;\n if (rev.provisional) provisionalCount += 1;\n if (declaresCadence(rev)) cadenceDeclared = true;\n }\n\n const declared = applicabilityOf(family, disciplines);\n const applicable = declared !== false; // undeclared (null) defaults to applicable, flagged below\n const label = FAMILY_LABELS[family] ?? family.split('_').join(' ');\n\n let state: PmCoverageState;\n let reason: string;\n if (declared === false) {\n state = 'n/a';\n reason = `Tailored out in the tailoring declaration; nothing is expected.`;\n } else if (viableCount === 0) {\n state = 'none';\n if (totalCount === 0) {\n reason = `Applicable, but no ${label.toLowerCase()} records are recorded yet.`;\n } else if (family === 'risk' && provisionalCount + totalCount > 0) {\n reason = `Applicable; ${totalCount} record(s) present but none viable — a risk needs an accepted, named owner to count.`;\n } else {\n reason = `Applicable; ${totalCount} record(s) present but none viable (still provisional or missing a required accepted, active owner/subject).`;\n }\n } else {\n state = 'partial';\n const undeclaredNote =\n declared === null && !ALWAYS_APPLICABLE.has(family)\n ? ' (area not individually tailored — assumed applicable)'\n : '';\n const provisionalNote = provisionalCount > 0 ? `, ${provisionalCount} still provisional` : '';\n reason = `${viableCount} of ${totalCount} record(s) viable${provisionalNote}${undeclaredNote}; caps at partial — expected-set completeness and cadence freshness are not evaluated in this minimal summary.`;\n }\n\n return {\n family,\n label,\n state,\n applicable,\n totalCount,\n viableCount,\n provisionalCount,\n cadenceDeclared,\n reason,\n };\n });\n\n const note = tailoringDeclared\n ? 'Minimal completeness summary (v1): applicability from the tailoring declaration, viability from confirmed records. Expected-set completeness and cadence freshness — which lift an area to current — are not yet evaluated, so no area reads current.'\n : 'No tailoring declaration is recorded yet, so applicability is assumed rather than authoritative. Declare tailoring to make completeness meaningful.';\n\n return { tailoringDeclared, areas, note };\n}\n","// ClowdPM customer-document grounding and disposition views (PJM-IP03 /\n// IMP-PJ-DOC-SURFACES). Pure, read-time helpers over the wire shapes in\n// `types.ts` — they assert no authority, mint no identity, and never delete.\n//\n// GROUNDING (PJM-S01 grounding half). A record or status CLAIM is grounded to a\n// customer document by CITING an exact version + span — never by copying its\n// bytes. The citation is an EvidenceRef in the ratified citation vocabulary\n// (kind `source-doc`; its target/pins bind the artifact version), carried in the\n// free-form record-revision `payload.evidence` array. It is read back with\n// the document's LIVE attestation state resolved at the citation, so a downstream\n// reader (IP04/IP05) can see whether the cited document is authorised to share.\n//\n// DISPOSITION VIEW. A disposition request is surfaced as HELD/denied/deferred and\n// — structurally — never executable: this module exposes no execute path and its\n// view says so plainly (the fail-closed hold until F-PJM-047 lands).\n\nimport type {\n PmAttestationState,\n PmCustomerDocument,\n PmDispositionRequest,\n} from './types.js';\nimport type {\n EvidenceGrade,\n EvidencePins,\n EvidenceRef,\n EvidenceRefTarget,\n} from '../chat/types.js';\n\n/** Evidence grades, mirroring the citation vocabulary (verbatim | paraphrase | derived). */\nexport type PmEvidenceGrade = EvidenceGrade;\n\n/**\n * A grounding citation to an exact customer-document version + span. It is an\n * EvidenceRef in the `source-doc` kind. The canonical locator names the scoped\n * project/document/artifact/version/span tuple; the immutable hash and capture\n * time are carried by the ratified target/pins fields. Evidence is pinned by\n * REFERENCE, never by copying content.\n */\nexport interface PmDocumentCitation extends EvidenceRef {\n /** Selects the citation resolver. Fixed to the document kind. */\n kind: 'source-doc';\n /** Ratified source-doc target. The canonical locator carries project/doc/artifact/version/span. */\n ref: EvidenceRefTarget & {\n locator: string;\n captured_at: string;\n content_hash: string;\n };\n /** Ratified reproducibility pins for the exact artifact version. */\n pins: EvidencePins & {\n dataset_refs: string[];\n captured_at: string;\n };\n}\n\n/** Parsed, validated PM fields carried inside the canonical EvidenceRef locator. */\nexport interface PmDocumentCitationParts {\n projectId: string;\n documentId: string;\n artifactId: string;\n versionId: string;\n span: string;\n}\n\n/** A citation resolved against the live document set — the read-side view. */\nexport interface PmResolvedCitation extends PmDocumentCitation {\n /** True only when the exact visible version/hash tuple is verified. */\n resolved: boolean;\n /** Distinguishes a visible document from a verified exact version. */\n documentVisible: boolean;\n versionVerified: boolean;\n projectId?: string;\n documentId?: string;\n artifactId?: string;\n versionId?: string;\n span?: string;\n title?: string;\n classification?: string;\n /**\n * Live attestation state AT the citation. `unknown` when the document is not\n * visible to this reader (non-member, or erased) — never silently `attested`.\n */\n attestationState: PmAttestationState | 'unknown';\n /**\n * True when the citation pins the document's CURRENT head version. This\n * surface deliberately refuses to claim an unverified historical version.\n */\n pinsCurrentVersion: boolean;\n}\n\n/**\n * Builds a canonical EvidenceRef for the document's exact CURRENT head + a\n * required human-readable source span. Older versions remain readable from\n * already-recorded citations, but this helper cannot assert one because the\n * document-list surface exposes only the verified current head.\n */\nexport function buildDocumentCitation(\n doc: Pick<\n PmCustomerDocument,\n 'id' | 'projectId' | 'artifactId' | 'headVersionId' | 'contentHash' | 'uploadedAt'\n >,\n opts: { span: string },\n): PmDocumentCitation {\n const projectId = doc.projectId.trim();\n const documentId = doc.id.trim();\n const artifactId = doc.artifactId.trim();\n const versionId = doc.headVersionId.trim();\n const contentHash = doc.contentHash.trim();\n const capturedAt = doc.uploadedAt.trim();\n const span = opts.span.trim();\n if (!projectId || !documentId || !artifactId || !versionId || !span) {\n throw new Error('project, document, artifact, current version and cited span are required.');\n }\n if (span.length > 512) throw new Error('cited span must be at most 512 characters.');\n if (!/^[0-9a-f]{64}$/.test(contentHash)) {\n throw new Error('document contentHash must be a lowercase SHA-256 digest.');\n }\n if (!capturedAt || Number.isNaN(Date.parse(capturedAt))) {\n throw new Error('document uploadedAt must be a valid provenance timestamp.');\n }\n const query = new URLSearchParams({\n project: projectId,\n document: documentId,\n artifact: artifactId,\n version: versionId,\n span,\n });\n return {\n kind: 'source-doc',\n ref: {\n locator: `pm-document://citation?${query.toString()}`,\n captured_at: capturedAt,\n content_hash: contentHash,\n },\n pins: {\n dataset_refs: [`artifact:${artifactId}`, `version:${versionId}`],\n captured_at: capturedAt,\n },\n };\n}\n\n/** Parses the canonical PM locator and verifies its EvidenceRef pins. */\nexport function parsePmDocumentCitation(value: unknown): PmDocumentCitationParts | undefined {\n if (!value || typeof value !== 'object') return undefined;\n const citation = value as Partial<PmDocumentCitation>;\n if (citation.kind !== 'source-doc' || !citation.ref || typeof citation.ref !== 'object') return undefined;\n const locator = citation.ref.locator;\n const contentHash = citation.ref.content_hash;\n const capturedAt = citation.ref.captured_at;\n if (typeof locator !== 'string' || typeof contentHash !== 'string' || typeof capturedAt !== 'string') return undefined;\n if (!/^[0-9a-f]{64}$/.test(contentHash) || Number.isNaN(Date.parse(capturedAt)) ||\n !citation.pins || citation.pins.captured_at !== capturedAt) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(locator);\n } catch {\n return undefined;\n }\n if (parsed.protocol !== 'pm-document:' || parsed.hostname !== 'citation' || parsed.username || parsed.password || parsed.port ||\n (parsed.pathname !== '' && parsed.pathname !== '/') || parsed.hash) return undefined;\n const allowedKeys = new Set(['project', 'document', 'artifact', 'version', 'span']);\n if ([...parsed.searchParams.keys()].some((key) => !allowedKeys.has(key))) return undefined;\n const one = (key: string): string | undefined => {\n const values = parsed.searchParams.getAll(key);\n const v = values.length === 1 ? values[0]?.trim() : '';\n return v || undefined;\n };\n const parts: PmDocumentCitationParts = {\n projectId: one('project') ?? '',\n documentId: one('document') ?? '',\n artifactId: one('artifact') ?? '',\n versionId: one('version') ?? '',\n span: one('span') ?? '',\n };\n if (Object.values(parts).some((v) => !v) || parts.span.length > 512) return undefined;\n const refs = citation.pins.dataset_refs;\n if (!Array.isArray(refs) || !refs.includes(`artifact:${parts.artifactId}`) || !refs.includes(`version:${parts.versionId}`)) {\n return undefined;\n }\n return parts;\n}\n\n/** Type guard for a canonical PM document EvidenceRef on the wire. */\nexport function isPmDocumentCitation(value: unknown): value is PmDocumentCitation {\n return parsePmDocumentCitation(value) !== undefined;\n}\n\n/** Reads the grounding citations out of a free-form record-revision payload. */\nexport function readClaimCitations(payload: unknown): PmDocumentCitation[] {\n if (!payload || typeof payload !== 'object') return [];\n const evidence = (payload as { evidence?: unknown }).evidence;\n if (!Array.isArray(evidence)) return [];\n return evidence.filter(isPmDocumentCitation);\n}\n\n/**\n * Grounds a claim by adding a document citation to a record-revision payload's\n * `evidence` array, immutably. Reuses an existing citation slot for the same\n * document version (idempotent re-grounding); otherwise appends. Returns a NEW\n * payload object — the input is never mutated. Non-object payloads are treated as\n * empty and wrapped, so a first citation is safe on a fresh record.\n */\nexport function groundClaimPayload(payload: unknown, citation: PmDocumentCitation): Record<string, unknown> {\n const incoming = parsePmDocumentCitation(citation);\n if (!incoming) throw new Error('cannot ground a claim with an invalid PM document EvidenceRef.');\n const base: Record<string, unknown> =\n payload && typeof payload === 'object' ? { ...(payload as Record<string, unknown>) } : {};\n const evidence = Array.isArray(base.evidence) ? base.evidence : [];\n // Preserve heterogeneous EvidenceRefs. The old implementation rebuilt the\n // array from PM refs only and silently deleted queries/signals/other sources.\n const withoutDuplicate = evidence.filter((entry) => {\n const existing = parsePmDocumentCitation(entry);\n return !existing || existing.projectId !== incoming.projectId ||\n existing.documentId !== incoming.documentId || existing.versionId !== incoming.versionId;\n });\n base.evidence = [...withoutDuplicate, citation];\n return base;\n}\n\n/** Removes a document-version citation from a claim payload, immutably. */\nexport function ungroundClaimPayload(\n payload: unknown,\n documentId: string,\n versionId: string,\n): Record<string, unknown> {\n const base: Record<string, unknown> =\n payload && typeof payload === 'object' ? { ...(payload as Record<string, unknown>) } : {};\n const evidence = Array.isArray(base.evidence) ? base.evidence : [];\n const kept = evidence.filter((entry) => {\n const c = parsePmDocumentCitation(entry);\n return !c || c.documentId !== documentId || c.versionId !== versionId;\n });\n if (kept.length > 0) base.evidence = kept;\n else delete base.evidence;\n return base;\n}\n\n/**\n * Resolves a citation against the documents the reader can see, surfacing the\n * live attestation state AT the citation. A citation whose document is not in\n * `docs` (a non-member reader, or an erased document) resolves to `unknown`\n * attestation — never silently treated as attested.\n */\nexport function resolveCitation(\n citation: PmDocumentCitation,\n docs: readonly PmCustomerDocument[],\n): PmResolvedCitation {\n const parts = parsePmDocumentCitation(citation);\n const doc = parts\n ? docs.find((d) => d.id === parts.documentId && d.projectId === parts.projectId && d.artifactId === parts.artifactId)\n : undefined;\n if (!doc || !parts) {\n return {\n ...citation,\n resolved: false,\n documentVisible: false,\n versionVerified: false,\n attestationState: 'unknown',\n pinsCurrentVersion: false,\n ...parts,\n };\n }\n const pinsCurrentVersion = parts.versionId === doc.headVersionId;\n const versionVerified = pinsCurrentVersion && citation.ref.content_hash === doc.contentHash;\n return {\n ...citation,\n ...parts,\n resolved: versionVerified,\n documentVisible: true,\n versionVerified,\n title: doc.title,\n classification: doc.classification,\n attestationState: doc.attestationState,\n pinsCurrentVersion,\n };\n}\n\n/** Resolves every citation on a claim payload against the visible document set. */\nexport function resolveClaimCitations(\n payload: unknown,\n docs: readonly PmCustomerDocument[],\n): PmResolvedCitation[] {\n return readClaimCitations(payload).map((c) => resolveCitation(c, docs));\n}\n\n// ── Disposition view (held / denied / deferred — never executed) ─────────────\n\n/**\n * A read-time summary of a disposition request for display. `executable` is\n * ALWAYS false: this product has no deletion-execution path (the fail-closed hold\n * until F-PJM-047 lands), so a surface built on this view can never present an\n * execute button. `heldForExecution` marks the approved-in-principle state whose\n * deletion is withheld.\n */\nexport interface PmDispositionView {\n id: string;\n documentId: string;\n state: PmDispositionRequest['state'];\n /** Structural: deletion execution is non-expressible in this release. Always false. */\n executable: false;\n /** True for the `held` state — approved in principle, execution withheld. */\n heldForExecution: boolean;\n /** True once the request has been decided (denied/deferred/held). */\n decided: boolean;\n /** A short, honest human label for the current state. */\n label: string;\n /** The persisted reason / policy basis, if any — surfaced verbatim. */\n reason?: string;\n policyBasis?: string;\n authorityKind?: PmDispositionRequest['authorityKind'];\n}\n\nconst DISPOSITION_LABELS: Record<PmDispositionRequest['state'], string> = {\n requested: 'Requested — awaiting review',\n under_review: 'Under review by the disposition authority',\n denied: 'Denied — the document is retained',\n deferred: 'Deferred — revisit later',\n held: 'Approved in principle; deletion held (governed execution not yet available)',\n};\n\n/**\n * Summarizes a disposition request for an honest, execution-free display. It\n * never fabricates an execute affordance: `executable` is structurally false.\n */\nexport function summarizeDisposition(req: PmDispositionRequest): PmDispositionView {\n const decided = req.state === 'denied' || req.state === 'deferred' || req.state === 'held';\n return {\n id: req.id,\n documentId: req.documentId,\n state: req.state,\n executable: false,\n heldForExecution: req.state === 'held',\n decided,\n label: DISPOSITION_LABELS[req.state] ?? req.state,\n reason: req.decisionReason ?? req.resolutionReason ?? req.requestReason ?? undefined,\n policyBasis: req.policyBasis ?? undefined,\n authorityKind: req.authorityKind ?? undefined,\n };\n}\n","// ClowdPM status-report read-time views (PJM-IP04 / IMP-PJ-STATUS). Pure helpers\n// over the wire shapes in `types.ts` — they compute no authority and mint no\n// identity. They exist so a surface (the console) renders an evidence-linked\n// status draft honestly: claims grouped by class, numbers resolved to their\n// recorded computation, coverage/diff summarized, and the non-editable coverage\n// statement + honest phase/gate carried through verbatim.\n\nimport type {\n PmClaimClass,\n PmComputation,\n PmReportCoverageState,\n PmStatusClaim,\n PmStatusReport,\n} from './types.js';\n\n/** Claims split by class, in the order a reader should read them. */\nexport interface PmClassedClaims {\n facts: PmStatusClaim[];\n interpretations: PmStatusClaim[];\n recommendations: PmStatusClaim[];\n}\n\n/** Groups a narrative's claims by class. A claim of an unknown class is dropped\n * from the classed view rather than silently shown as a fact. */\nexport function groupClaimsByClass(claims: readonly PmStatusClaim[]): PmClassedClaims {\n const out: PmClassedClaims = { facts: [], interpretations: [], recommendations: [] };\n for (const claim of claims) {\n switch (claim.class) {\n case 'fact':\n out.facts.push(claim);\n break;\n case 'interpretation':\n out.interpretations.push(claim);\n break;\n case 'recommendation':\n out.recommendations.push(claim);\n break;\n default:\n break;\n }\n }\n return out;\n}\n\n/**\n * Resolves a claim's cited computation KEYS against a report's recorded\n * computations — the \"a number opens its computation\" resolution, done locally\n * from the report the reader already holds. Keys with no recorded computation\n * are omitted (a number can never render without one, so this should be empty),\n * so the caller can trust every returned entry is real.\n */\nexport function resolveClaimComputations(\n claim: Pick<PmStatusClaim, 'evidence'>,\n report: Pick<PmStatusReport, 'computations'>,\n): PmComputation[] {\n const keys = claim.evidence.computations ?? [];\n const byKey = new Map(report.computations.map((c) => [c.computationKey, c]));\n const out: PmComputation[] = [];\n for (const key of keys) {\n const found = byKey.get(key);\n if (found) out.push(found);\n }\n return out;\n}\n\n/** Finds one recorded computation by its stable key within a report. */\nexport function computationByKey(\n report: Pick<PmStatusReport, 'computations'>,\n key: string,\n): PmComputation | undefined {\n return report.computations.find((c) => c.computationKey === key);\n}\n\n/** A short, honest human label for a coverage state (plain language, PJ-D014). */\nexport function coverageStateLabel(state: PmReportCoverageState): string {\n switch (state) {\n case 'n/a':\n return 'Not applicable (tailored out)';\n case 'none':\n return 'Empty';\n case 'thin':\n return 'Thin';\n case 'partial':\n return 'Partial';\n case 'current':\n return 'Current';\n default:\n return String(state);\n }\n}\n\n/** A short, honest human label for a claim class. */\nexport function claimClassLabel(cls: PmClaimClass): string {\n switch (cls) {\n case 'fact':\n return 'Fact';\n case 'interpretation':\n return 'Interpretation';\n case 'recommendation':\n return 'Recommendation';\n default:\n return String(cls);\n }\n}\n\n/**\n * True when a report has anything worth diffing shown against a prior version —\n * a surface uses it to decide whether to render the diff panel. The first\n * version has no diff.\n */\nexport function hasMaterialDiff(report: Pick<PmStatusReport, 'narrative'>): boolean {\n const diff = report.narrative.diff;\n if (!diff) return false;\n return (\n diff.added.length > 0 ||\n diff.removed.length > 0 ||\n diff.changed.length > 0 ||\n diff.coverageChanges.length > 0 ||\n diff.phaseGateChanged\n );\n}\n\n/**\n * A single, honest one-line health summary a surface can show at the top of a\n * report: the coverage statement plus the phase/gate statement. Both are the\n * producer's own non-editable/honest text — this never re-derives or softens\n * them.\n */\nexport function statusHeadline(report: Pick<PmStatusReport, 'narrative'>): string {\n const { coverage, phaseGate, partial } = report.narrative;\n const partialPrefix = partial ? 'PARTIAL — ' : '';\n return `${partialPrefix}${phaseGate.statement} ${coverage.statement}`.trim();\n}\n","// Provider catalog — TYPES + an OFFLINE FALLBACK, not the source of truth.\n//\n// The runtime source of truth is the backend's GET /providers feed\n// (cloud-agent-backend/internal/providers), fetched via\n// CredentialsClient.providers(product). A UI must render THAT list so a\n// provider added server-side — including the MKT/MTG (CapMM) and BI (CapBI)\n// families — appears without a tsclient/frontend release.\n//\n// What lives here now:\n// 1. The wire TYPES (FieldSpec / FieldType / ProviderSpec / CAP_*). These\n// are static typing the fetched JSON is decoded into — no data.\n// 2. Spec-driven, \"friendly\" client validation: validateSpec() INTERPRETS a\n// given ProviderSpec (normally the one the server returned) rather than a\n// hard-coded copy. Server validation stays authoritative; this only makes\n// the form fail fast with the same messages.\n// 3. PROVIDER_CATALOG — an explicit OFFLINE-COMPATIBILITY FALLBACK for the\n// legacy cloud/notify set, used ONLY when the server feed is unavailable\n// (resolveProviderCatalog). It can never override or hide a server\n// provider: when a server response exists, the fallback is not consulted.\n//\n// The fallback intentionally lags the backend (it does not carry the CapMM/\n// CapBI families). That is safe precisely because it is never merged over a\n// live server response — see resolveProviderCatalog.\n\n// ── Field-descriptor types ─────────────────────────────────────────────\n\nexport type FieldType = 'text' | 'password' | 'number' | 'textarea' | 'pem' | 'json' | 'stringList';\n\nexport interface FieldSpec {\n /** JSON-pointer-ish: \"secret\" | \"metadata.<key>\". */\n path: string;\n label: string;\n type: FieldType;\n required: boolean;\n /** True for fields that hold credential material — UI hides the value. */\n secret?: boolean;\n default?: unknown;\n placeholder?: string;\n help?: string;\n /**\n * Optional grant-shape scoping for multi-shape providers (ZOOM, X). When\n * non-empty the field belongs only to those shapes (the active shape is\n * carried in metadata.grantShape). Empty/absent → the field applies to\n * every shape. Mirrors FieldSpec.Shapes on the backend; the generic form\n * carries it through untouched so a shape-scoped provider round-trips.\n */\n shapes?: string[];\n}\n\n// Capability bitmask values mirrored from cloud-agent-backend's\n// internal/providers package and the \"Provider\" master table seeded by\n// migration 0005. Frontends drive tab/section filtering by AND-ing\n// against these bits — adding a new capability is a backend migration,\n// not a frontend deploy.\n//\n// CAP_STORAGE — cloud ops / resource discovery (S3/GCS/Blob, EC2, …)\n// CAP_AI — LLM / embedding inference\n// CAP_COMPUTE — SSH and similar infra-runtime credentials\n// CAP_VCS — source-code platforms (GitHub, future GitLab)\n// CAP_NOTIFY — outbound notification transports (Slack, Teams, PagerDuty, SMTP)\n// CAP_BI — business-intelligence platforms (Power BI, Looker, Tableau)\n// CAP_MM — Meeting+Marketing MVP++ provider family (MSGRAPH, JIRA, …)\n// CAP_GENERAL — catch-all for the legacy \"OTHER\" row\nexport const CAP_STORAGE = 0x1;\nexport const CAP_AI = 0x2;\nexport const CAP_COMPUTE = 0x4;\nexport const CAP_VCS = 0x8;\nexport const CAP_NOTIFY = 0x10;\n// 0x20 is reserved for CAP_MCP on the backend; CAP_BI takes 0x40 to match.\nexport const CAP_BI = 0x40;\nexport const CAP_MM = 0x80;\nexport const CAP_GENERAL = 0xff;\n\nexport interface ProviderSpec {\n id: string;\n displayName: string;\n /**\n * Bitmask of CAP_* values describing what kinds of operations this\n * credential can drive. Sourced from the Provider master table; mirror\n * declared inline below so the frontend can render its tabs / filters\n * without a runtime round-trip.\n */\n capabilities: number;\n fields: FieldSpec[];\n}\n\n// ── Offline fallback catalog ────────────────────────────────────────────\n//\n// PROVIDER_CATALOG is the OFFLINE-COMPATIBILITY FALLBACK, NOT the source of\n// truth. It carries only the legacy cloud/notify set so a form still works\n// when the backend GET /providers feed is unreachable. It is consulted ONLY\n// by resolveProviderCatalog when no server response is available, so it can\n// never override or hide a provider the server declares. Prefer the fetched\n// catalog for everything user-facing.\n\nexport const PROVIDER_CATALOG: Record<string, ProviderSpec> = {\n AWS: {\n id: 'AWS',\n displayName: 'Amazon Web Services',\n capabilities: CAP_STORAGE,\n fields: [\n { path: 'metadata.accessKeyId', label: 'Access Key ID', type: 'text', required: true,\n placeholder: 'AKIAxxxxxxxxxxxxxxxx',\n help: 'The AKIA-prefixed identifier from IAM. Stored in plain text — only the secret access key is encrypted.' },\n { path: 'secret', label: 'Secret Access Key', type: 'password', required: true, secret: true,\n help: 'The 40-character secret. Encrypted at rest.' },\n { path: 'metadata.region', label: 'Region', type: 'text', required: false,\n placeholder: 'us-east-1',\n help: 'Default region for boto3 clients. Optional — leave blank to use the SDK default.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://s3.amazonaws.com',\n help: 'Override for non-AWS S3-compatible endpoints (MinIO, Wasabi, etc.). Most users leave blank.' },\n ],\n },\n BEDROCK: {\n id: 'BEDROCK',\n displayName: 'AWS Bedrock',\n capabilities: CAP_AI,\n fields: [\n { path: 'metadata.accessKeyId', label: 'Access Key ID', type: 'text', required: true,\n placeholder: 'AKIAxxxxxxxxxxxxxxxx',\n help: 'IAM access key allowed to invoke Bedrock. Stored in plain text — only the secret access key is encrypted.' },\n { path: 'secret', label: 'Secret Access Key', type: 'password', required: true, secret: true,\n help: 'The IAM secret. Encrypted at rest.' },\n { path: 'metadata.region', label: 'Region', type: 'text', required: false,\n placeholder: 'us-east-1',\n help: 'Default region for Bedrock Runtime. Optional — leave blank to use the SDK default.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://bedrock-runtime.us-east-1.amazonaws.com',\n help: 'Override for VPC endpoints or testing. Most users leave blank.' },\n ],\n },\n GCP: {\n id: 'GCP',\n displayName: 'Google Cloud',\n capabilities: CAP_STORAGE,\n fields: [\n { path: 'secret', label: 'Service Account JSON', type: 'json', required: true, secret: true,\n placeholder: '{\"type\":\"service_account\",\"project_id\":\"…\",\"client_email\":\"…\",\"private_key\":\"…\"}',\n help: 'Paste the service-account JSON, or drop the file you downloaded from the IAM console. The full document is encrypted; project_id and client_email are extracted automatically for display.' },\n ],\n },\n AZURE: {\n id: 'AZURE',\n displayName: 'Microsoft Azure',\n capabilities: CAP_STORAGE,\n fields: [\n { path: 'metadata.clientId', label: 'Client ID (Application ID)', type: 'text', required: true,\n placeholder: '00000000-0000-0000-0000-000000000000' },\n { path: 'secret', label: 'Client Secret', type: 'password', required: true, secret: true,\n help: 'The secret value generated when you registered the app. Encrypted at rest.' },\n { path: 'metadata.tenantId', label: 'Tenant ID', type: 'text', required: true,\n placeholder: '00000000-0000-0000-0000-000000000000' },\n { path: 'metadata.subscriptionId', label: 'Subscription ID', type: 'text', required: false,\n placeholder: '00000000-0000-0000-0000-000000000000' },\n ],\n },\n OCI: {\n id: 'OCI',\n displayName: 'Oracle Cloud Infrastructure',\n capabilities: CAP_STORAGE,\n fields: [\n { path: 'metadata.tenancyOcid', label: 'Tenancy OCID', type: 'text', required: true,\n placeholder: 'ocid1.tenancy.oc1..aaaa…',\n help: \"The tenancy's OCID, from the OCI console (Profile → Tenancy).\" },\n { path: 'metadata.userOcid', label: 'User OCID', type: 'text', required: true,\n placeholder: 'ocid1.user.oc1..aaaa…',\n help: 'The OCID of the user the API signing key belongs to.' },\n { path: 'metadata.fingerprint', label: 'Key Fingerprint', type: 'text', required: true,\n placeholder: 'aa:bb:cc:dd:…',\n help: 'Fingerprint of the uploaded API signing key (shown next to the key in the console).' },\n { path: 'secret', label: 'API Private Key (PEM)', type: 'pem', required: true, secret: true,\n placeholder: '-----BEGIN PRIVATE KEY-----\\n…\\n-----END PRIVATE KEY-----',\n help: 'Paste the PEM, or drop the .pem file. Passphrase-protected keys are rejected — the agent runs unattended. Encrypted at rest.' },\n { path: 'metadata.region', label: 'Region', type: 'text', required: false,\n placeholder: 'us-phoenix-1',\n help: 'Default region for the oci CLI / SDK. Optional — leave blank to use the SDK default.' },\n ],\n },\n SSH: {\n id: 'SSH',\n displayName: 'SSH',\n capabilities: CAP_COMPUTE,\n fields: [\n { path: 'metadata.user', label: 'User', type: 'text', required: true,\n placeholder: 'ubuntu',\n help: 'Linux user the agent will SSH as.' },\n { path: 'metadata.host', label: 'Host', type: 'text', required: true,\n placeholder: 'vps.example.com or * for wildcard',\n help: \"Hostname or IP. Use '*' for a key that's valid across multiple hosts; the agent will require the prompt to name the target host.\" },\n { path: 'metadata.port', label: 'Port', type: 'number', required: false, default: 22,\n placeholder: '22' },\n { path: 'secret', label: 'PEM Private Key', type: 'pem', required: true, secret: true,\n placeholder: '-----BEGIN OPENSSH PRIVATE KEY-----\\n…\\n-----END OPENSSH PRIVATE KEY-----',\n help: 'Paste the PEM, or drop the private key file (e.g. id_ed25519). Passphrase-encrypted keys are rejected — the agent runs unattended.' },\n ],\n },\n GITHUB: {\n id: 'GITHUB',\n displayName: 'GitHub',\n capabilities: CAP_VCS,\n fields: [\n { path: 'secret', label: 'Personal Access Token (PAT)', type: 'password', required: true, secret: true,\n placeholder: 'ghp_xxxxxxxxxxxxxxxxxxxxxxxx',\n help: 'A classic or fine-grained PAT. Encrypted at rest. The first 7 characters are kept in metadata for display.' },\n { path: 'metadata.org', label: 'Org (optional)', type: 'text', required: false,\n placeholder: 'my-github-org',\n help: 'Restrict this credential to a single org if you scoped the PAT that way. Optional — leave blank for personal-account access.' },\n { path: 'metadata.repoSlugs', label: 'Allowed Repos (optional)', type: 'stringList', required: false,\n placeholder: 'owner/repo',\n help: \"Repos the agent is allowed to operate on with this credential, as 'owner/name'. Drives the awareness block injected into the planner. Leave empty to grant the full PAT scope (the agent will still only act on repos the user names in prompts).\" },\n { path: 'metadata.protectedBranches', label: 'Protected Branches (optional)', type: 'stringList', required: false,\n placeholder: 'main',\n help: \"Branches that require explicit user approval for write operations (push, merge, delete). 'main' / 'master' / 'release/*' are good defaults.\" },\n ],\n },\n GITLAB: {\n id: 'GITLAB',\n displayName: 'GitLab',\n capabilities: CAP_VCS,\n fields: [\n { path: 'secret', label: 'Access Token', type: 'password', required: true, secret: true,\n placeholder: 'glpat-xxxxxxxxxxxxxxxxxxxx',\n help: 'A personal, project, or group access token. Encrypted at rest. The first 9 characters are kept in metadata for display.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://gitlab.example.com/api/v4',\n help: 'Override for self-hosted GitLab. Leave blank to use https://gitlab.com/api/v4.' },\n { path: 'metadata.group', label: 'Top-level Group (optional)', type: 'text', required: false,\n placeholder: 'my-gitlab-group',\n help: 'Restrict this credential to a single top-level group if you scoped the token that way. Optional — leave blank for personal-account or wider scope.' },\n { path: 'metadata.repoSlugs', label: 'Allowed Projects (optional)', type: 'stringList', required: false,\n placeholder: 'group/subgroup/project',\n help: 'Project paths the agent is allowed to operate on with this credential. GitLab project paths can be arbitrarily deep (group/subgroup/.../project). Leave empty to grant the full token scope.' },\n { path: 'metadata.protectedBranches', label: 'Protected Branches (optional)', type: 'stringList', required: false,\n placeholder: 'main',\n help: \"Branches that require explicit user approval for write operations. 'main' / 'master' / 'release/*' are good defaults.\" },\n ],\n },\n AZURE_DEVOPS: {\n id: 'AZURE_DEVOPS',\n displayName: 'Azure DevOps',\n capabilities: CAP_VCS,\n fields: [\n { path: 'secret', label: 'Personal Access Token (PAT)', type: 'password', required: true, secret: true,\n placeholder: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',\n help: 'An ADO PAT with the scopes you want the agent to use (Code, Build, Release, Work Items …). Encrypted at rest. The first 7 characters are kept in metadata for display.' },\n { path: 'metadata.organization', label: 'Organization', type: 'text', required: true,\n placeholder: 'my-ado-org',\n help: 'The ADO organization name (the segment after dev.azure.com/, or the prefix in your-org.visualstudio.com).' },\n { path: 'metadata.project', label: 'Project (optional)', type: 'text', required: false,\n placeholder: 'Engineering',\n help: 'Restrict this credential to a single ADO project. Optional — leave blank if the PAT spans multiple projects in the org.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://dev.azure.com',\n help: 'Override for ADO Server (on-prem) deployments. Leave blank to use https://dev.azure.com.' },\n { path: 'metadata.repoSlugs', label: 'Allowed Repos (optional)', type: 'stringList', required: false,\n placeholder: 'project/repo',\n help: \"Repos the agent is allowed to operate on. Use 'project/repo' when 'Project' is blank, or just 'repo' when scoped to one project. Leave empty to grant the full PAT scope.\" },\n { path: 'metadata.protectedBranches', label: 'Protected Branches (optional)', type: 'stringList', required: false,\n placeholder: 'main',\n help: 'Branches that require explicit user approval for write operations and pipeline triggers.' },\n ],\n },\n OPENAI: {\n id: 'OPENAI',\n displayName: 'OpenAI',\n capabilities: CAP_AI,\n fields: [\n { path: 'secret', label: 'API Key', type: 'password', required: true, secret: true,\n placeholder: 'sk-…',\n help: 'Your OpenAI API key. Encrypted at rest. The first ~7 characters are kept in metadata for display.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://api.openai.com/v1',\n help: 'Override for OpenAI-compatible endpoints (Azure OpenAI, self-hosted gateways). Most users leave blank.' },\n ],\n },\n ANTHROPIC: {\n id: 'ANTHROPIC',\n displayName: 'Anthropic',\n capabilities: CAP_AI,\n fields: [\n { path: 'secret', label: 'API Key', type: 'password', required: true, secret: true,\n placeholder: 'sk-ant-…',\n help: 'Your Anthropic API key. Encrypted at rest. The first ~10 characters are kept in metadata for display.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://api.anthropic.com',\n help: 'Override for Anthropic-compatible endpoints. Most users leave blank.' },\n ],\n },\n GEMINI: {\n id: 'GEMINI',\n displayName: 'Google Gemini',\n capabilities: CAP_AI,\n fields: [\n { path: 'secret', label: 'API Key', type: 'password', required: true, secret: true,\n placeholder: 'AIza…',\n help: 'Your Gemini API key from Google AI Studio. Encrypted at rest. The first ~7 characters are kept in metadata for display.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://generativelanguage.googleapis.com',\n help: 'Override for proxies or regional endpoints. Most users leave blank to use the default Gemini API base URL.' },\n ],\n },\n SLACK: {\n id: 'SLACK',\n displayName: 'Slack',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'secret', label: 'Incoming Webhook URL', type: 'password', required: true, secret: true,\n placeholder: 'https://hooks.slack.com/services/T000/B000/xxxxxxxx',\n help: 'A Slack Incoming Webhook URL. The target channel is fixed by the webhook. Encrypted at rest; never injected into the sandbox.' },\n { path: 'metadata.channelHint', label: 'Channel Hint (optional)', type: 'text', required: false,\n placeholder: '#oncall',\n help: 'Display-only label for the channel this webhook posts to. Does not change routing — the webhook URL controls the destination.' },\n ],\n },\n TEAMS: {\n id: 'TEAMS',\n displayName: 'Microsoft Teams',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'secret', label: 'Incoming Webhook URL', type: 'password', required: true, secret: true,\n placeholder: 'https://outlook.office.com/webhook/...',\n help: 'A Teams Incoming Webhook (connector) URL. The target channel is fixed by the webhook. Encrypted at rest; never injected into the sandbox.' },\n ],\n },\n PAGERDUTY: {\n id: 'PAGERDUTY',\n displayName: 'PagerDuty',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'secret', label: 'Integration / Routing Key', type: 'password', required: true, secret: true,\n placeholder: 'R0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',\n help: 'An Events API v2 integration (routing) key from a PagerDuty service. Encrypted at rest; never injected into the sandbox.' },\n ],\n },\n SMTP: {\n id: 'SMTP',\n displayName: 'Email (SMTP)',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'metadata.host', label: 'SMTP Host', type: 'text', required: true,\n placeholder: 'smtp.example.com',\n help: 'Hostname of the SMTP relay.' },\n { path: 'metadata.port', label: 'Port', type: 'number', required: false, default: 587,\n placeholder: '587',\n help: 'SMTP port. Defaults to 587 (STARTTLS). TLS is always required.' },\n { path: 'metadata.fromAddress', label: 'From Address', type: 'text', required: true,\n placeholder: 'alerts@example.com',\n help: 'Envelope-from / From header for messages the agent sends. Also used as the SMTP AUTH username.' },\n { path: 'metadata.toAddresses', label: 'To Addresses', type: 'stringList', required: true,\n placeholder: 'oncall@example.com',\n help: 'One or more recipient addresses. Every notify message is sent to all of them.' },\n { path: 'secret', label: 'Password', type: 'password', required: true, secret: true,\n help: 'SMTP AUTH password for the From address. Encrypted at rest; never injected into the sandbox.' },\n ],\n },\n TELEGRAM: {\n id: 'TELEGRAM',\n displayName: 'Telegram',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'secret', label: 'Bot Token', type: 'password', required: true, secret: true,\n placeholder: '123456789:AAExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',\n help: 'Bot token from @BotFather. Encrypted at rest; never injected into the sandbox. One bot per project keeps projects isolated.' },\n { path: 'metadata.chatId', label: 'Chat ID', type: 'text', required: false,\n placeholder: '-1001234567890 or @mychannel',\n help: 'Default chat the agent posts to. Use Detect to fill it automatically, or enter a numeric id (groups are negative) / @username for a public channel. Optional — leave blank for inbound-only (driving the agent from a chat); inbound replies go to whoever messages the bot.' },\n { path: 'metadata.threadId', label: 'Topic / Thread ID (optional)', type: 'number', required: false,\n placeholder: '12',\n help: 'For forum-style groups, the message_thread_id to post into. Leave blank for the main chat.' },\n ],\n },\n};\n\n// Stable display order for the FALLBACK dropdown. Matches the Go catalog's\n// List() for the legacy set; the server feed carries its own order.\nconst PROVIDER_ORDER = ['AWS', 'BEDROCK', 'GCP', 'AZURE', 'OCI', 'SSH', 'GITHUB', 'GITLAB', 'AZURE_DEVOPS', 'OPENAI', 'ANTHROPIC', 'GEMINI', 'SLACK', 'TEAMS', 'PAGERDUTY', 'SMTP', 'TELEGRAM'];\n\n/** listProviders returns the OFFLINE FALLBACK specs. Prefer the fetched catalog. */\nexport function listProviders(): ProviderSpec[] {\n return PROVIDER_ORDER.flatMap((id) => (PROVIDER_CATALOG[id] ? [PROVIDER_CATALOG[id]] : []));\n}\n\n/** getProvider looks up a spec in the OFFLINE FALLBACK. Prefer getSpec(fetched, id). */\nexport function getProvider(id: string): ProviderSpec | undefined {\n return PROVIDER_CATALOG[id];\n}\n\n// ── Runtime catalog resolution ──────────────────────────────────────────\n\n/** Where a resolved catalog came from: the live server feed, or the offline fallback. */\nexport type ProviderCatalogSource = 'server' | 'fallback';\n\nexport interface ResolvedProviderCatalog {\n /** The specs the UI should render, in server (or fallback) order. */\n specs: ProviderSpec[];\n /** 'server' when the backend feed was used; 'fallback' when offline. */\n source: ProviderCatalogSource;\n}\n\n/**\n * resolveProviderCatalog picks the catalog a UI should render.\n *\n * When the server feed (CredentialsClient.providers()) returned a non-empty\n * list, that list is used VERBATIM — the offline fallback is not consulted,\n * so it can never override or hide a server-declared provider. Only when the\n * feed is absent/empty (offline, or a fetch error the caller maps to null)\n * does it fall back to the legacy static set, flagging source: 'fallback' so\n * the UI can say so.\n */\nexport function resolveProviderCatalog(\n fetched: ProviderSpec[] | null | undefined,\n): ResolvedProviderCatalog {\n if (Array.isArray(fetched) && fetched.length > 0) {\n return { specs: fetched, source: 'server' };\n }\n return { specs: listProviders(), source: 'fallback' };\n}\n\n/** getSpec finds a provider by id in a resolved (fetched or fallback) catalog. */\nexport function getSpec(specs: readonly ProviderSpec[], id: string): ProviderSpec | undefined {\n return specs.find((s) => s.id === id);\n}\n\n// ── Path helpers ───────────────────────────────────────────────────────\n\nconst SECRET_PATH = 'secret';\nconst METADATA_PREFIX = 'metadata.';\n\nexport function isSecretPath(path: string): boolean {\n return path === SECRET_PATH;\n}\n\nexport function isMetadataPath(path: string): path is `metadata.${string}` {\n return path.startsWith(METADATA_PREFIX);\n}\n\nexport function metadataKey(path: string): string | undefined {\n return isMetadataPath(path) ? path.slice(METADATA_PREFIX.length) : undefined;\n}\n\n/** getValueAt reads the FieldSpec.path from a separate (secret, metadata) tuple. */\nexport function getValueAt(secret: string, metadata: Record<string, unknown>, path: string): unknown {\n if (path === SECRET_PATH) return secret;\n const k = metadataKey(path);\n return k ? metadata[k] : undefined;\n}\n\n/** setValueAt writes to (secret, metadata). Returns the updated tuple. */\nexport function setValueAt(\n secret: string,\n metadata: Record<string, unknown>,\n path: string,\n value: unknown,\n): { secret: string; metadata: Record<string, unknown> } {\n if (path === SECRET_PATH) return { secret: typeof value === 'string' ? value : '', metadata };\n const k = metadataKey(path);\n if (!k) return { secret, metadata };\n const nextMeta = { ...metadata };\n if (value === undefined || value === null || value === '') delete nextMeta[k];\n else nextMeta[k] = value;\n return { secret, metadata: nextMeta };\n}\n\n// ── Validation ─────────────────────────────────────────────────────────\n\n/**\n * validateSpec runs the structural checks for a credential payload against a\n * GIVEN ProviderSpec — normally the one the server returned from GET\n * /providers. It interprets that spec's fields; it does NOT consult the\n * offline fallback catalog. This is what lets the form fail fast for a\n * provider the backend added without a tsclient release.\n *\n * Returns an error string on failure, or null on success. \"Friendly\" only —\n * the backend validator (internal/providers/validators.go) stays\n * authoritative; the messages here mirror it. Grant-shape scoped fields\n * (FieldSpec.shapes) are required only when they apply to the active shape.\n */\nexport function validateSpec(\n spec: ProviderSpec | undefined,\n label: string,\n secret: string,\n metadata: Record<string, unknown>,\n): string | null {\n if (!spec) return 'Unknown provider';\n if (!label || label.trim() === '') {\n return 'Label is required';\n }\n\n const activeShape = typeof metadata['grantShape'] === 'string' ? (metadata['grantShape'] as string) : '';\n\n // Required-field + type checks.\n for (const f of spec.fields) {\n const present = isFieldPresent(secret, metadata, f.path);\n if (f.required && !present && fieldAppliesToShape(f, activeShape)) {\n return `${spec.id}.${f.label} is required`;\n }\n if (!present) continue;\n const value = getValueAt(secret, metadata, f.path);\n const typeErr = typeCheck(f, value);\n if (typeErr) return typeErr;\n }\n\n // Reject any caller-supplied metadata keys not declared in the spec\n // and any reserved underscore-prefixed keys (catalog-managed). An unknown\n // key on a server-declared provider fails safely here, exactly as it does\n // on the backend — the generic form never smuggles an undeclared field.\n const allowed = allowedMetadataKeys(spec);\n for (const k of Object.keys(metadata)) {\n if (k.startsWith('_')) {\n return `Metadata key \"${k}\" is reserved (the leading underscore is catalog-managed); remove it from the payload`;\n }\n if (!allowed.has(k)) {\n return `Metadata key \"${k}\" is not part of the ${spec.id} spec. Allowed keys: ${[...allowed].join(', ')}`;\n }\n }\n return null;\n}\n\n/**\n * validate is the back-compat, id-keyed entry point: it resolves the provider\n * from the OFFLINE FALLBACK catalog and delegates to validateSpec. Prefer\n * validateSpec with the server-returned spec so newly-added server providers\n * validate without shipping a new tsclient. Kept for callers that still hold\n * only a provider id and the legacy set.\n */\nexport function validate(\n providerId: string,\n label: string,\n secret: string,\n metadata: Record<string, unknown>,\n): string | null {\n const spec = getProvider(providerId);\n if (!spec) {\n return `Unknown provider \"${providerId}\". Known providers: ${Object.keys(PROVIDER_CATALOG).join(', ')}`;\n }\n return validateSpec(spec, label, secret, metadata);\n}\n\n/**\n * fieldAppliesToShape reports whether a shape-scoped field belongs to the\n * active grant shape. An unscoped field (no shapes) applies to every shape.\n * Mirrors the backend's fieldAppliesToShape.\n */\nfunction fieldAppliesToShape(f: FieldSpec, shapeId: string): boolean {\n if (!f.shapes || f.shapes.length === 0) return true;\n return f.shapes.includes(shapeId);\n}\n\nfunction isFieldPresent(secret: string, metadata: Record<string, unknown>, path: string): boolean {\n const v = getValueAt(secret, metadata, path);\n if (v === undefined || v === null) return false;\n if (typeof v === 'string') return v.trim() !== '';\n // Mirror the Go getAtPath: empty arrays count as absent so required-field\n // checks fire and stringList fields can be cleared by submitting [].\n if (Array.isArray(v)) return v.length > 0;\n return true;\n}\n\nfunction typeCheck(f: FieldSpec, value: unknown): string | null {\n switch (f.type) {\n case 'text':\n case 'password':\n case 'textarea':\n return typeof value === 'string' ? null : `${f.label} must be a string`;\n case 'number':\n if (typeof value === 'number' && Number.isInteger(value) && value >= 0) return null;\n if (typeof value === 'string' && /^\\d+$/.test(value)) return null;\n return `${f.label} must be a non-negative integer`;\n case 'json':\n if (typeof value !== 'string') return `${f.label} must be a JSON string`;\n try {\n JSON.parse(value);\n return null;\n } catch {\n return `${f.label} is not valid JSON`;\n }\n case 'pem':\n if (typeof value !== 'string') return `${f.label} must be a PEM string`;\n return validatePEM(value, f.label);\n case 'stringList': {\n if (!Array.isArray(value)) return `${f.label} must be a list of strings`;\n for (let i = 0; i < value.length; i++) {\n const item = value[i];\n if (typeof item !== 'string') return `${f.label}[${i}] must be a string`;\n if (item.trim() === '') return `${f.label}[${i}] is empty`;\n }\n return null;\n }\n default:\n return `${f.label} has unsupported field type ${f.type}`;\n }\n}\n\nconst PEM_BEGIN_RE = /-----BEGIN [^-]+-----/;\nconst PEM_END_RE = /-----END [^-]+-----/;\nconst PEM_PROC_TYPE_ENCRYPTED = /^Proc-Type:\\s*\\d+,\\s*ENCRYPTED/m;\nconst PEM_DEK_INFO = /^DEK-Info:/m;\n\nfunction validatePEM(s: string, label: string): string | null {\n const t = s.trim();\n if (!t) return `${label}: empty PEM`;\n if (!PEM_BEGIN_RE.test(t) || !PEM_END_RE.test(t)) {\n return `${label}: no valid PEM block found (expected '-----BEGIN ... PRIVATE KEY-----')`;\n }\n if (PEM_PROC_TYPE_ENCRYPTED.test(t) || PEM_DEK_INFO.test(t)) {\n return `${label}: passphrase-encrypted PEM is not supported (the agent runs unattended)`;\n }\n return null;\n}\n\nfunction allowedMetadataKeys(spec: ProviderSpec): Set<string> {\n const out = new Set<string>();\n for (const f of spec.fields) {\n const k = metadataKey(f.path);\n if (k) out.add(k);\n }\n // Mirror the Go-side allow-list of SecretParser-derived metadata keys\n // so a round-trip read→edit→write doesn't trip the unknown-key check.\n switch (spec.id) {\n case 'GCP':\n out.add('clientEmail');\n out.add('projectId');\n break;\n case 'GITHUB':\n case 'AZURE_DEVOPS':\n case 'OPENAI':\n case 'ANTHROPIC':\n case 'GEMINI':\n out.add('tokenPrefix');\n break;\n case 'GITLAB':\n out.add('tokenPrefix');\n out.add('host'); // derived from endpoint by the parser\n break;\n }\n return out;\n}\n\n// ── Display hints ──────────────────────────────────────────────────────\n//\n// Used for client-side previews when forms are filled in but not yet\n// submitted. The persisted value comes from the server (cached in\n// metadata._displayHint) — this function is a fallback / preview helper.\n\nexport function computeDisplayHint(providerId: string, metadata: Record<string, unknown>): string {\n const cached = metadata['_displayHint'];\n if (typeof cached === 'string' && cached) return cached;\n\n switch (providerId) {\n case 'AWS':\n case 'BEDROCK': {\n const key = str(metadata['accessKeyId']);\n const region = str(metadata['region']);\n return shortPrefix(key, 8) + (region ? ` / ${region}` : '');\n }\n case 'GCP': {\n const email = str(metadata['clientEmail']);\n const proj = str(metadata['projectId']);\n if (!email && !proj) return '';\n if (!email) return proj;\n if (!proj) return email;\n return `${email} / ${proj}`;\n }\n case 'AZURE': {\n const client = str(metadata['clientId']);\n const sub = str(metadata['subscriptionId']);\n const head = shortPrefix(client, 8);\n return head + (sub ? ` / sub:${shortPrefix(sub, 8)}` : '');\n }\n case 'OCI': {\n const tenancy = str(metadata['tenancyOcid']);\n const region = str(metadata['region']);\n const head = shortPrefix(tenancy, 12);\n return head + (region ? ` / ${region}` : '');\n }\n case 'SSH': {\n const user = str(metadata['user']);\n const host = str(metadata['host']);\n const port = metadata['port'];\n let portStr = '';\n if (typeof port === 'number' && port > 0 && port !== 22) portStr = `:${port}`;\n else if (typeof port === 'string' && /^\\d+$/.test(port) && port !== '22') portStr = `:${port}`;\n if (!user && !host) return '';\n return `${user}@${host}${portStr}`.replace(/^@/, '');\n }\n case 'GITHUB': {\n const prefix = str(metadata['tokenPrefix']);\n const org = str(metadata['org']);\n const head = prefix ? `${prefix}…` : '';\n return [head, org].filter(Boolean).join(' / ');\n }\n case 'GITLAB': {\n const prefix = str(metadata['tokenPrefix']);\n const group = str(metadata['group']);\n let host = str(metadata['host']);\n if (!host) {\n const endpoint = str(metadata['endpoint']);\n host = endpoint ? hostFromURL(endpoint) : 'gitlab.com';\n }\n let out = prefix ? `${prefix}…` : '';\n if (group) out = out ? `${out} / ${group}` : group;\n if (host && host !== 'gitlab.com') out = out ? `${out} @ ${host}` : host;\n return out;\n }\n case 'AZURE_DEVOPS': {\n const prefix = str(metadata['tokenPrefix']);\n const org = str(metadata['organization']);\n const project = str(metadata['project']);\n let out = prefix ? `${prefix}…` : '';\n if (org) {\n const orgSeg = project ? `${org}/${project}` : org;\n out = out ? `${out} / ${orgSeg}` : orgSeg;\n }\n return out;\n }\n case 'OPENAI':\n case 'ANTHROPIC':\n case 'GEMINI': {\n const prefix = str(metadata['tokenPrefix']);\n return prefix ? `${prefix}…` : '';\n }\n case 'SLACK':\n return str(metadata['channelHint']);\n case 'TELEGRAM':\n return str(metadata['chatId']);\n case 'SMTP': {\n const from = str(metadata['fromAddress']);\n const host = str(metadata['host']);\n return from + (host ? ` @ ${host}` : '');\n }\n default:\n return '';\n }\n}\n\nfunction str(v: unknown): string {\n return typeof v === 'string' ? v : '';\n}\n\nfunction shortPrefix(s: string, n: number): string {\n if (!s) return '';\n if (s.length <= n) return s;\n return s.slice(0, n) + '…';\n}\n\nfunction hostFromURL(raw: string): string {\n let s = raw.trim();\n const schemeIdx = s.indexOf('://');\n if (schemeIdx >= 0) s = s.slice(schemeIdx + 3);\n const cut = s.search(/[/?#]/);\n if (cut >= 0) s = s.slice(0, cut);\n return s;\n}\n","/**\n * Chat-mode types for the agent engine. The new SDK speaks `sandboxId` and\n * `projectId`; the legacy `repoId` / `workspaceId` are still accepted on the\n * scope tuple as fallbacks during the frontend transition.\n */\n\nexport interface ChatScope {\n orgId: string;\n userId: string;\n sandboxId: string;\n projectId?: string;\n /** @deprecated Use `sandboxId`. Carried only to ease the cutover. */\n repoId?: string;\n /** @deprecated Use `projectId`. Carried only to ease the cutover. */\n workspaceId?: string;\n}\n\nexport type ChatSessionSource = 'adhoc' | 'template' | 'mcp' | 'telegram';\nexport type ChatMessageRole = 'user' | 'assistant' | 'system';\n\n/**\n * Status of a single chat turn (agent_chat_turns.status). The first four are\n * in-progress phases; the last three are terminal. The Chats/Runs table folds\n * the in-progress values into a single \"running\" badge and renders the\n * terminal ones directly.\n */\nexport type ChatTurnStatus =\n | 'classifying'\n | 'clarifying'\n | 'planning'\n | 'executing'\n | 'completed'\n | 'failed'\n | 'cancelled';\nexport type ChatMessageKind =\n | 'text'\n | 'question'\n | 'answer'\n | 'tool_call'\n | 'tool_result'\n // Talk-to-Your-BI careless-prompter (O2): a non-blocking transparency banner written\n // when the user's own prompt named a person / personal identifier. metadata.classes\n // carries the detected PII kinds. Mirrors cloud-agent types.ChatMessageKindPIINotice.\n | 'pii_notice'\n // MVP09 C1: an agent_chat_messages row whose metadata carries a closed\n // ChatCardV1 projection (chat-first realignment §6). Mirrors cloud-agent\n // types.ChatMessageKindCard. Parse it with chatCardOf() from ./cards; a client\n // that does not render cards can skip the kind entirely (forward-compat).\n | 'card';\n\nexport interface ChatSession {\n id: string;\n org_id: string;\n workspace_id: string;\n repo_id: string;\n user_id: string;\n title?: string;\n agent_environment_id?: string;\n source: ChatSessionSource;\n template_id?: string;\n /** M3 Stage 4: populated when this session was spawned by the\n * scheduler dispatcher firing a `ChatSchedule` row. The frontend\n * uses it to render the \"Scheduled run\" ribbon + hide the\n * composer. NULL on every attended session. */\n schedule_id?: string | null;\n /** M3 Stage 4: mirror of `schedule_id != null` — true for sessions\n * the scheduler created with `Loop.Unattended = true`. */\n unattended?: boolean;\n created_at: string;\n updated_at: string;\n last_message_at?: string | null;\n /** Sum of `cost_usd_micros` across this session's `execution_receipts`.\n * Populated only by list endpoints; absent on single-session fetches. */\n total_cost_usd_micros?: number | null;\n /** Sum of prompt + completion tokens across this session's LLM calls.\n * Populated only by list endpoints; absent on single-session fetches. */\n total_tokens?: number | null;\n /** Status of this session's most recent turn. Populated only by list\n * endpoints; null/absent when the session has no turns yet. The Runs\n * table maps the in-progress phases to a \"running\" badge and surfaces\n * completed / failed / cancelled directly. */\n latest_turn_status?: ChatTurnStatus | null;\n}\n\nexport interface ChatMessage {\n id: string;\n conversation_id: string;\n org_id: string;\n repo_id: string;\n user_id: string;\n turn_id: string;\n role: ChatMessageRole;\n kind: ChatMessageKind;\n content?: string;\n plan_id?: string;\n clarification_session_id?: string;\n metadata?: Record<string, unknown>;\n created_at: string;\n}\n\nexport interface CreateChatSessionRequest {\n title?: string;\n workspace_id: string;\n repo_id: string;\n agent_environment_id?: string;\n source?: ChatSessionSource;\n template_id?: string;\n}\n\nexport interface CreateChatSessionResponse {\n conversation_id: string;\n session: ChatSession;\n}\n\nexport interface ListChatSessionsResponse {\n sessions: ChatSession[];\n next_cursor?: string;\n}\n\nexport interface ListChatSessionsQuery {\n cursor?: string;\n limit?: number;\n /** Inclusive lower bound on `created_at`, RFC3339 timestamp. */\n from?: string;\n /** Exclusive upper bound on `created_at`, RFC3339 timestamp. */\n to?: string;\n}\n\nexport interface GetChatSessionResponse {\n session: ChatSession;\n messages: ChatMessage[];\n /**\n * Action categories the user has sticky-allowed for the rest of this chat\n * session (the ConfirmationCard \"Allow for session\" opt-in). Held in\n * engine memory, so this re-hydrates the dashboard's guardrail chips after\n * a reload while the engine process is alive; `null` (or omitted) when\n * there are none or after an engine restart.\n */\n session_allows?: ActionCategory[] | null;\n /**\n * Pack-registry active packs for this session (pack-registry SG-13): the\n * version-stamped activations — bound, model-activated and system lazy — that\n * back the console's PackChips strip. `null` (or omitted) when there are none\n * or against an older engine that does not emit the field.\n */\n active_packs?: ActivePack[] | null;\n}\n\n/** One version-stamped pack activation on a chat session (pack-registry §7.6). */\nexport interface ActivePack {\n /** Pack name (the activate_skill key). */\n name: string;\n /** 'system' (compiled engine pack) | 'default' (platform) | 'org'. */\n source: string;\n /** Display version integer; omitted for system packs. */\n version?: number;\n /** 'binding' (delivered at Run start) | 'model' (activate_skill). */\n trigger: string;\n}\n\nexport interface PostChatMessageRequest {\n text: string;\n attachments?: Array<Record<string, unknown>>;\n template_params?: Record<string, unknown>;\n auto_approve?: boolean;\n}\n\nexport interface PostChatMessageResponse {\n message_id: string;\n turn_id: string;\n}\n\n/**\n * One user's \"Satisfied? Yes/No\" rating plus an optional free-text comment on\n * the agent's behaviour (agent_chat_feedback). `turn_id` is null for\n * whole-conversation feedback; non-null scopes it to a single turn. Fields are\n * snake_case to match the wire format.\n */\nexport interface ChatFeedback {\n id: string;\n conversation_id: string;\n turn_id?: string | null;\n org_id: string;\n repo_id: string;\n user_id: string;\n satisfied: boolean;\n comment?: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface SubmitChatFeedbackRequest {\n satisfied: boolean;\n comment?: string;\n /** Omit (or null) for whole-conversation feedback; set to scope to a turn. */\n turn_id?: string;\n}\n\nexport interface ChatFeedbackEnvelope {\n feedback: ChatFeedback;\n}\n\nexport interface ListChatFeedbackResponse {\n feedback: ChatFeedback[];\n}\n\nexport interface AnswerChatQuestionRequest {\n question_id: string;\n selected_ids?: string[];\n custom_text?: string;\n}\n\nexport interface AnswerChatQuestionResponse {\n status: 'accepted';\n}\n\n/**\n * Response from POST /chat/sessions/:id/messages/:turn_id/cancel — the\n * Stop affordance the dashboard fires to interrupt an in-flight turn.\n * The engine still emits a terminal `done` SSE event with\n * status=\"context_cancelled\" after this returns; the frontend renders a\n * muted \"Cancelled\" marker on that event rather than on this response.\n */\nexport interface CancelChatTurnResponse {\n status: 'cancelling';\n turn_id: string;\n}\n\n/**\n * Body the dashboard POSTs to\n * /chat/sessions/:id/messages/:turn_id/confirm/:tool_call_id when the\n * user clicks approve / deny on the M3 confirmation modal. `note` is\n * optional free-text rationale surfaced in the synthesised\n * \"DENIED:\" tool result on deny so the model can see *why* the user\n * said no.\n *\n * `apply_to_session` opts the user into sticky-allow: when present\n * with decision='allow', every subsequent tool call in this chat\n * session that classifies into the same category dispatches without\n * re-prompting. Ignored when decision='deny'. Default: false.\n */\nexport interface ConfirmChatToolCallRequest {\n decision: 'allow' | 'deny';\n note?: string;\n apply_to_session?: boolean;\n}\n\nexport interface ConfirmChatToolCallResponse {\n status: 'accepted';\n}\n\n/**\n * Action categories the M3 policy engine recognises (see\n * docs/design/chat-loop/chat-loop-m3-safety-scheduling.md §4). `read`\n * is implicit / always allowed and never appears in a grant set —\n * include the mutating eight in the union so the schedule editor's\n * category multi-select can be typed.\n */\nexport type ActionCategory =\n | 'write_data'\n | 'create_resource'\n | 'delete_data'\n | 'destroy_resource'\n | 'scale_capacity'\n | 'modify_iam'\n | 'modify_network'\n | 'execute_runtime';\n\n/** Run status stamped on agent_chat_schedules.last_run_status.\n *\n * The legacy statuses (`success` | `blocked` | `failed` | `running`) are joined\n * by the SHR-IP06 product-schedule statuses, each a DISTINCT non-failed state a\n * renderer must show as its own pill rather than collapsing to failed:\n * - `halted_budget` — the run hit a metered budget/cap; queue intact, resumes when raised.\n * - `paused_disabled` — paused because the product_unattended_execution kill switch is off.\n * - `paused_entitlement` — paused because the org's product entitlement was revoked.\n * - `superseded` — a recurring occurrence was superseded by its next window and escalated.\n * - `coalesced` — a duplicate fire (double-fire / run-now) coalesced onto the live run.\n *\n * `paused_*` and `superseded`/`coalesced` are NOT failures — they must not read\n * as a broken schedule (SHR-IP06 REV-09). */\nexport type ChatScheduleRunStatus =\n | 'success'\n | 'blocked'\n | 'failed'\n | 'running'\n | 'halted_budget'\n | 'paused_disabled'\n | 'paused_entitlement'\n | 'superseded'\n | 'coalesced';\n\n/** Every ChatScheduleRunStatus classified by whether it reads as a FAILURE.\n *\n * Typed `Record<ChatScheduleRunStatus, boolean>` on purpose: the record is\n * EXHAUSTIVE, so removing a status from the union above makes its key an excess\n * property here and `tsc` fails, and adding a status without classifying it fails\n * too. This is what makes the SHR-IP06 statuses LOAD-BEARING (REV-09 / RV2-06) —\n * dropping `superseded`/`coalesced`/`halted_budget`/`paused_*` no longer slips\n * through a green typecheck. Every SHR-IP06 status is a NON-failure: a paused,\n * superseded or coalesced run must not render as a broken schedule. */\nexport const CHAT_SCHEDULE_RUN_STATUS_IS_FAILURE: Record<ChatScheduleRunStatus, boolean> = {\n success: false,\n blocked: false,\n failed: true,\n running: false,\n halted_budget: false,\n paused_disabled: false,\n paused_entitlement: false,\n superseded: false,\n coalesced: false,\n};\n\n/** The canonical list of every ChatScheduleRunStatus, derived from the\n * exhaustive classification above so it cannot drift from the union. */\nexport const CHAT_SCHEDULE_RUN_STATUSES = Object.keys(\n CHAT_SCHEDULE_RUN_STATUS_IS_FAILURE,\n) as ChatScheduleRunStatus[];\n\n/** Whether a schedule run status reads as a failure. The SHR-IP06 non-failed\n * states (paused_*, superseded, coalesced, halted_budget) return false. */\nexport function isFailedScheduleRunStatus(s: ChatScheduleRunStatus): boolean {\n return CHAT_SCHEDULE_RUN_STATUS_IS_FAILURE[s];\n}\n\n/**\n * ChatScheduleNotifyOn gates which run outcomes emit a completion digest to\n * the schedule's notify_channel. 'always' (the default) digests every run;\n * the others fire only on the matching outcome. Only meaningful when\n * notify_channel is set — an empty channel means no digest at all.\n */\nexport type ChatScheduleNotifyOn = 'always' | 'success' | 'failure' | 'blocked';\n\n/** What happens to an action this schedule queued for approval when its\n * window closes. Mirrors the action-policy framework's timeout policies. */\nexport type ActionScheduleTimeoutPolicy = 'block' | 'escalate' | 'execute';\n\n/**\n * ChatSchedule mirrors one row of agent_chat_schedules (M3 Stage 4).\n * The scheduler dispatcher fires due rows on its tick interval and\n * spawns an unattended chat session per firing — see ChatSession's\n * `schedule_id` / `unattended` fields for the audit linkage.\n */\n/** Parse state of a recurring-edition selector: 'present' (well-formed,\n * untampered — the identity fields are trustworthy) or 'malformed' (tampered/\n * unreadable — the untrusted identity fields are withheld and the schedule fails\n * closed at execution). */\nexport type RecurringEditionState = 'present' | 'malformed';\n\n/** Frozen-audience parse state carried in a recurring-edition summary. */\nexport type RecurringEditionAudienceState = 'present' | 'empty' | 'malformed' | 'absent';\n\n/** One bound send destination (audience list + connection). Not personal data —\n * the list object the campaign targets. */\nexport interface RecurringEditionDestination {\n kind: string;\n id: string;\n connection_id: string;\n}\n\n/**\n * Operator-safe projection of a Marketing schedule's recurring approved-edition\n * selector (IMP-MKT04-SURFACE). It names WHICH already-approved edition the\n * schedule re-sends and to HOW MANY approved recipients — never the frozen\n * audience member ids (personal data), the approved content bytes, or a secret.\n * The server NEVER serializes the raw selector; a 'malformed' state withholds the\n * untrusted identity fields and signals a degraded configuration.\n */\nexport interface RecurringEditionSummary {\n state: RecurringEditionState;\n edition_id?: string;\n approved_content_sha256?: string;\n product?: string;\n action_class?: string;\n binding_id?: string;\n binding_revision?: string;\n acting_user_id?: string;\n destinations?: RecurringEditionDestination[];\n audience_purpose?: string;\n /** Canonical authority token over the frozen consented set — the \"snapshot\n * version\": it changes iff the frozen audience changes. */\n audience_digest?: string;\n /** Number of consented contacts frozen at approval. Counts members without\n * exposing their identities. */\n approved_member_count: number;\n audience_state?: RecurringEditionAudienceState;\n}\n\nexport interface ChatSchedule {\n id: string;\n org_id: string;\n workspace_id?: string;\n repo_id: string;\n created_by_user_id: string;\n /** The schedule's DECLARED product ('cloud' | 'meeting' | 'marketing'),\n * resolved from the container at creation and persisted on the row (migration\n * 080, SHR-IP06 REV-01). Execution forks and gates on this declared fact and\n * fails closed on a mismatch with the container's current product. Omitted on\n * legacy rows (pre-080), which are all 'cloud'. */\n product?: string;\n\n name: string;\n prompt: string;\n cron_expr: string;\n /** IANA timezone name (e.g. \"Europe/Madrid\"). The cron expression\n * resolves in this timezone — \"0 9 * * *\" with timezone\n * \"Europe/Madrid\" fires at 09:00 Madrid time, including DST\n * transitions. Defaults to \"UTC\" on the server when omitted. */\n timezone: string;\n /** Subset of the repo's effective category grant. `read` is implicit\n * — empty array == read-only schedule. */\n granted_categories: ActionCategory[];\n\n enabled: boolean;\n max_runtime_minutes: number;\n max_consecutive_failures?: number;\n concurrency_policy: string;\n\n /** Logical notify-channel label a completion digest is sent to after\n * each run. Matches an attached notify credential's label\n * (case-insensitive). Empty/omitted = no digest (opt-in). */\n notify_channel?: string;\n /** Which outcomes emit a digest. Defaults to 'always'. Only relevant\n * when notify_channel is set. */\n notify_on?: ChatScheduleNotifyOn;\n\n /** Timeout policy for actions this schedule queues for approval. */\n action_timeout_policy?: ActionScheduleTimeoutPolicy;\n /** Approval-clock override in seconds; null = use the class default. */\n approval_expiry_seconds?: number | null;\n\n next_fire_at?: string;\n last_fire_at?: string;\n last_run_status?: ChatScheduleRunStatus;\n consecutive_failures: number;\n total_runs: number;\n total_successes: number;\n\n created_at: string;\n updated_at: string;\n\n /** Operator-safe recurring-edition summary for a Marketing schedule that re-sends\n * an already-approved newsletter edition (IMP-MKT04-SURFACE). Omitted on an\n * ordinary (model-loop) schedule. The raw selector — which carries the frozen\n * audience member ids and the approved content — is NEVER on the wire. */\n recurring_edition?: RecurringEditionSummary;\n}\n\nexport interface CreateChatScheduleRequest {\n workspace_id?: string;\n /** Creates an immutable recurring Marketing edition from this already-approved\n * newsletter action. The engine derives content, audience, route and actor from\n * the durable approval; clients cannot submit those authority facts directly. */\n approved_action_id?: string;\n name: string;\n prompt: string;\n cron_expr: string;\n /** IANA timezone (e.g. \"Europe/Madrid\"). Frontend should default to\n * `Intl.DateTimeFormat().resolvedOptions().timeZone`. Server\n * defaults to \"UTC\" when omitted and rejects unknown names with\n * `invalid_timezone` (HTTP 400). */\n timezone?: string;\n granted_categories?: ActionCategory[];\n /** Defaults to true on the server when omitted. */\n enabled?: boolean;\n max_runtime_minutes?: number;\n max_consecutive_failures?: number;\n concurrency_policy?: string;\n /** Notify-channel label for the completion digest. Empty/omitted = no\n * digest. */\n notify_channel?: string;\n /** When to emit the digest. Server defaults to 'always' when omitted.\n * Rejected with `invalid_notify_on` (HTTP 400) for unknown values. */\n notify_on?: ChatScheduleNotifyOn;\n /** What happens to an action this schedule queues for approval when its\n * window closes: `block` (default — the action is not taken), `escalate`\n * (route to the next approver), or `execute` (run anyway; legal only for\n * classes that could legally be AUTO at that scope). Declared at task\n * creation, never negotiated at execution time.\n *\n * `escalate` is rejected with `approvers_required` (HTTP 422) when the org\n * has no escalation list configured. */\n action_timeout_policy?: ActionScheduleTimeoutPolicy;\n /** Overrides the action class's default approval clock, in seconds.\n * Omitted/null = use the class default. */\n approval_expiry_seconds?: number | null;\n}\n\nexport interface UpdateChatScheduleRequest {\n name?: string;\n prompt?: string;\n cron_expr?: string;\n /** IANA timezone. Pass to change; omit to leave unchanged.\n * Changing timezone alone (without cron_expr) still recomputes\n * `next_fire_at` since the wall-clock target shifts. */\n timezone?: string;\n /** Pass an empty array to relax to read-only; omit to leave\n * unchanged. */\n granted_categories?: ActionCategory[];\n enabled?: boolean;\n max_runtime_minutes?: number;\n max_consecutive_failures?: number;\n concurrency_policy?: string;\n /** Pass to change the digest channel; \"\" clears it (disables digest).\n * Omit to leave unchanged. */\n notify_channel?: string;\n /** Pass to change; omit to leave unchanged. */\n notify_on?: ChatScheduleNotifyOn;\n /** What happens to an action this schedule queues for approval when its\n * window closes: `block` (default — the action is not taken), `escalate`\n * (route to the next approver), or `execute` (run anyway; legal only for\n * classes that could legally be AUTO at that scope). Declared at task\n * creation, never negotiated at execution time.\n *\n * `escalate` is rejected with `approvers_required` (HTTP 422) when the org\n * has no escalation list configured. */\n action_timeout_policy?: ActionScheduleTimeoutPolicy;\n /** Overrides the action class's default approval clock, in seconds.\n * Omitted/null = use the class default. */\n approval_expiry_seconds?: number | null;\n}\n\nexport interface ListChatSchedulesResponse {\n schedules: ChatSchedule[];\n}\n\nexport interface ChatScheduleEnvelope {\n schedule: ChatSchedule;\n}\n\n/** One per-occurrence run-history row for a product schedule (SHR-IP06 §6 item\n * 8 / REV-09). It composes SHR-IP04's `act_runs` record: the occurrence\n * identity and trigger (why it fired), what it read, produced and queued for\n * approval, and how it ended — so an operator answers \"what fired, what it read,\n * what it queued, how it ended\" from ONE row. `session_id` links to the standard\n * chat-session viewer for the full transcript. Its shape mirrors `ActRun`. */\nexport interface ScheduleOccurrence {\n id: string;\n org_id: string;\n workspace_id?: string;\n repo_id?: string;\n session_id?: string;\n schedule_id?: string;\n product: string;\n occurrence_key: string;\n /** Why it fired: 'schedule' (on time), 'schedule_late' (late), 'manual'\n * (owner run-now), or 'schedule_paused' (a gap window that did not fire). */\n trigger_kind: string;\n trigger_detail?: string;\n reads?: unknown[];\n artifacts?: unknown[];\n acts_queued?: unknown[];\n acts_executed?: unknown[];\n notifications?: unknown[];\n status: 'running' | 'completed' | 'partial' | 'failed' | 'escalated';\n failure_note?: string;\n started_at: string;\n ended_at?: string;\n}\n\n/** Response from GET /v1/agent/repos/:repo_id/schedules/:id/runs.\n *\n * `occurrences` is the per-occurrence run history (SHR-IP06 REV-09) — the\n * primary view for a product schedule. `runs` is the legacy per-session list\n * (`id` is the conversation id the SchedulesTab navigates into for the full\n * transcript); a cloud schedule carries only `runs`, a product schedule carries\n * both. */\nexport interface ListChatScheduleRunsResponse {\n runs: ChatSession[];\n occurrences?: ScheduleOccurrence[];\n}\n\n/** Response from POST /v1/agent/repos/:repo_id/schedules/:id/rerun (SHR-IP06\n * §6 item 4 / REV-07). The re-run is accepted and processed asynchronously;\n * `occurrence_key` is the derived key the run will coalesce on. */\nexport interface RerunScheduleOccurrenceResponse {\n status: 'accepted';\n schedule_id: string;\n due_window: string;\n occurrence_key: string;\n}\n\nexport interface ClarificationOption {\n id: string;\n label: string;\n description?: string;\n}\n\nexport type ChatEventType =\n | 'phase'\n | 'question'\n | 'plan_draft'\n | 'step_started'\n | 'step_completed'\n | 'step_failed'\n | 'step_progress'\n | 'narration'\n | 'assistant_message'\n | 'done'\n | 'session_title'\n | 'tool_call_started'\n | 'tool_call_finished'\n | 'llm_call_finished'\n | 'tool_call_confirmation_required'\n | 'pending_action_queued'\n | 'artifact_drafted'\n | 'artifact_referenced'\n | 'chat_compaction_fired'\n | 'chat_checkpointed';\n\nexport type ChatPhase = 'classifying' | 'clarifying' | 'executing' | 'answering' | 'done';\n\nexport interface ChatPhasePayload { phase: ChatPhase; }\n\nexport interface ChatQuestionPayload {\n question_id: string;\n prompt: string;\n kind: string;\n options?: ClarificationOption[];\n default?: string;\n role?: string;\n}\n\nexport interface ChatStepEventPayload {\n step_id: string;\n status: string;\n started_at?: string;\n completed_at?: string;\n error?: string;\n description?: string;\n}\n\n/**\n * Sent with `plan_draft` once per turn when the chat-loop's model calls\n * the report_plan tool to declare a multi-step task breakdown. The\n * dashboard renders steps as a live checklist; matching step_started /\n * step_completed / step_failed events with step_id = \"step-N\" move the\n * checklist status as the model progresses.\n */\nexport interface ChatPlanDraftPayload {\n turn_id: string;\n steps: string[];\n summary?: string;\n}\n\n/**\n * Sent with `tool_call_started`, once per chat-loop tool dispatch BEFORE\n * the tool runs. Pairs with `tool_call_finished` via tool_call_id.\n */\nexport interface ChatToolCallStartedPayload {\n turn_index: number;\n tool_name: string;\n tool_call_id: string;\n /** Short human-readable preview of the arguments, truncated. */\n summary: string;\n /**\n * Model-authored 3–10 word user-facing description of what this call\n * accomplishes (e.g. \"Listing S3 buckets\"). The dashboard renders this\n * verbatim as the live tool-call label, replacing \"Calling bash\".\n * Missing / empty → renderer falls back to the tool name.\n */\n intent?: string;\n}\n\n/**\n * Sent with `tool_call_finished`, once per chat-loop tool dispatch AFTER\n * the tool returns.\n */\nexport interface ChatToolCallFinishedPayload {\n turn_index: number;\n tool_name: string;\n tool_call_id: string;\n /** Short human-readable preview of stdout/stderr, truncated. */\n summary: string;\n}\n\n/**\n * Sent with `llm_call_finished` once per successful LLM round-trip during\n * a chat-loop turn. The dashboard's budget badge uses this as a fast\n * invalidation signal so the displayed spend tracks the persisted total\n * in near real time, instead of waiting for the 30 s poll. Failed LLM\n * calls do not emit.\n */\nexport interface ChatLLMCallFinishedPayload {\n turn_index: number;\n model: string;\n /** USD cost in micros (1e-6 USD) attributed to this LLM call. Zero\n * when no pricing row matched the model — clients should still treat\n * the event as a refetch hint. */\n cost_delta_micros: number;\n}\n\n/**\n * Sent with `tool_call_confirmation_required` when the M3 policy hook\n * classifies a tool call into a category that is permitted at the\n * org/workspace/repo level but is also in the chat session's\n * `confirm_categories` set — the user wants to approve each invocation\n * inline before the engine dispatches it. The chat loop suspends until\n * the dashboard POSTs the user's decision to\n * `/v1/agent/chat/sessions/:id/messages/:turn_id/confirm/:tool_call_id`\n * (or until the 4-minute confirmer timeout elapses, which is treated as\n * an implicit deny — safe default).\n *\n * Unattended (scheduled) runs never emit this event — confirm collapses\n * to deny when no human is connected.\n */\nexport interface ChatToolCallConfirmationRequiredPayload {\n turn_index: number;\n tool_call_id: string;\n tool_name: string;\n /** Truncated stringification of the tool args, suitable for the\n * modal preview. Full args remain in the surrounding\n * `tool_call_started` event for the debug view. */\n args_preview: string;\n /** One of the M3 action categories (write_data, create_resource,\n * delete_data, destroy_resource, scale_capacity, modify_iam,\n * modify_network, execute_runtime). */\n category: string;\n /** Human-readable explanation from the policy engine — e.g.\n * \"category \\\"delete_data\\\" requires inline confirmation\". Rendered\n * in the modal as a hint about *why* the agent is asking. */\n rationale?: string;\n /** Present only when the action-policy stage raised this card (GATE's\n * synchronous face). Absent for a plain category confirmation, so the\n * class badge renders only when there is a class. */\n action_class?: string;\n}\n\nexport interface ChatStepProgressPayload {\n step_id: string;\n message: string;\n progress_pct?: number;\n}\n\nexport interface ChatNarrationPayload {\n step_id?: string;\n text: string;\n}\n\n/* ------------------------------------------------------------------ *\n * Claim → evidence citation vocabulary (common-infra evidence-citation)\n *\n * The suite-wide \"click a claim, see its evidence\" contract. These types\n * mirror the engine's persisted encoding (cloud-agent internal/chat/citation):\n * - a `claim_annotations` sidecar on an assistant text message's `metadata`\n * (transient chat answers reconstruct citations from the transcript — the\n * resolver reads the same rows \"Show query\" reads; nothing is a second\n * store), and\n * - a `bi_verification` marker on a run_bi_query `tool_result` message's\n * `metadata` (the verifier verdict, surfaced quietly).\n * The live SSE `citations` field carries the same ClaimAnnotation[] so the\n * client can render affordances at `done`.\n * ------------------------------------------------------------------ */\n\n/** The platform-wide claim taxonomy. Only `fact` requires evidence. */\nexport type ClaimClass = 'fact' | 'interpretation' | 'recommendation';\n\n/**\n * Evidence kinds. `recorded-query` + `source-doc` are the MVP-live kinds; the\n * rest are registered by their sibling components as they ship (extensible).\n */\nexport type EvidenceKind =\n | 'recorded-query'\n | 'source-doc'\n | 'transcript-span'\n | 'model-run'\n | 'pack-fact'\n | 'connection-fact'\n | 'signal'\n | 'artifact-version';\n\n/** What the evidence IS vs what the claim SAYS. Numbers are `derived`. */\nexport type EvidenceGrade = 'verbatim' | 'paraphrase' | 'derived';\n\n/** Honest terminal state a resolver reports for a ref. */\nexport type ResolutionState = 'resolved' | 'forbidden' | 'gone' | 'stale';\n\n/** Half-open char-offset range into the final answer prose. */\nexport interface EvidenceSpan {\n start: number;\n end: number;\n}\n\n/** Typed target of an EvidenceRef (a union across the live kinds). */\nexport interface EvidenceRefTarget {\n exchange_id?: string;\n turn_id?: string;\n message_id?: string;\n /** source-doc */\n locator?: string;\n captured_at?: string;\n content_hash?: string;\n}\n\n/** Version stamps that make provenance reproducible; rendered as words. */\nexport interface EvidencePins {\n model?: string;\n dataset_refs?: string[];\n captured_at?: string;\n}\n\nexport interface EvidenceRef {\n kind: EvidenceKind;\n ref: EvidenceRefTarget;\n pins?: EvidencePins;\n}\n\n/** Points a claim at the tool_result carrying its bi_verification marker. */\nexport interface ClaimVerificationRef {\n exchange_id: string;\n}\n\nexport interface ClaimAnnotation {\n span: EvidenceSpan;\n class: ClaimClass;\n /** ≥1 iff class==='fact' AND cited; [] = an uncited fact (marked, counted). */\n evidence: EvidenceRef[];\n grade?: EvidenceGrade;\n verification_ref?: ClaimVerificationRef;\n}\n\n/** The sidecar persisted on an assistant text message's metadata. */\nexport interface ClaimAnnotations {\n schema: number;\n target_turn_id: string;\n claims: ClaimAnnotation[];\n /**\n * Claims the engine's extractor could not map to the answer prose, so they\n * are absent from `claims` entirely. Omitted when zero.\n *\n * A consumer rendering a coverage line MUST fold this in: without it the line\n * describes the annotations that survived rather than the answer, and four\n * facts with three unmappable quotes read as \"all 1 facts cited\".\n */\n unmapped_claims?: number;\n /**\n * Citations that named an exchange the turn could not back — an out-of-range\n * ordinal, an unknown tool_call_id, or a result the PII gate withheld. The\n * claim survives as an uncited fact. Omitted when zero.\n */\n unbound_refs?: number;\n}\n\n/** The verifier verdict persisted on a run_bi_query tool_result's metadata. */\nexport interface BIVerification {\n ok: boolean;\n checks: string[];\n at: string;\n}\n\n/** Metadata keys under which the two citation blobs live on ChatMessage rows. */\nexport const CLAIM_ANNOTATIONS_METADATA_KEY = 'claim_annotations';\nexport const BI_VERIFICATION_METADATA_KEY = 'bi_verification';\n\n/**\n * claimAnnotationsOf reads the claim-annotation sidecar off an assistant text\n * message. Returns undefined when the message predates citations / was produced\n * with the flag off (\"not annotated\") — distinct from a present-but-empty set\n * (a genuinely fact-free answer). No runtime validation beyond shape presence.\n */\nexport function claimAnnotationsOf(message: Pick<ChatMessage, 'metadata'>): ClaimAnnotations | undefined {\n const blob = message.metadata?.[CLAIM_ANNOTATIONS_METADATA_KEY];\n if (blob && typeof blob === 'object' && Array.isArray((blob as ClaimAnnotations).claims)) {\n return blob as ClaimAnnotations;\n }\n return undefined;\n}\n\n/**\n * biVerificationOf reads the verifier verdict off a run_bi_query tool_result\n * message. Absent for legacy exchanges and when the flag is off.\n */\nexport function biVerificationOf(message: Pick<ChatMessage, 'metadata'>): BIVerification | undefined {\n const blob = message.metadata?.[BI_VERIFICATION_METADATA_KEY];\n if (blob && typeof blob === 'object' && typeof (blob as BIVerification).ok === 'boolean') {\n return blob as BIVerification;\n }\n return undefined;\n}\n\nexport interface ChatAssistantMessagePayload {\n message_id: string;\n content: string;\n /** Live claim→evidence annotations for the answer (evidence-citation §11);\n * omitted when the flag is off or the answer carried none. */\n citations?: ClaimAnnotation[];\n}\n\nexport interface ChatDonePayload {\n turn_id: string;\n plan_id?: string;\n status?: string;\n /** LLM id the chat-loop ran this turn against (M2/I5). The badge\n * renders this next to the spend so the user can see which model\n * was selected by the per-repo provider resolver. Empty when the\n * turn aborted before the resolver picked one (rare). */\n model_used?: string;\n}\n\nexport interface ChatSessionTitlePayload {\n title: string;\n}\n\n/**\n * Sent with `chat_compaction_fired` once per Run when the chat-loop\n * mid-session replaces older history with a structured progress note\n * (chat-compact-optimization Front #1). The session-debug view uses\n * this to mark the boundary in the rendered transcript so operators\n * can see how aggressively the loop is trimming context.\n */\nexport interface ChatCompactionFiredPayload {\n turn_index: number;\n prompt_tokens_before: number;\n compactor_model: string;\n}\n\n/**\n * Sent with `chat_checkpointed` when the chat-loop, on its final\n * allowed iteration, emits a structured terminal summary instead of\n * running another open-ended LLM call (chat-compact-optimization Front\n * #2). The accompanying assistant message is the checkpoint body; the\n * dashboard should render the session's StopReason\n * (\"max_turns_checkpointed\") with a distinct chip and offer a \"Continue\n * this work\" affordance that POSTs a canned follow-up.\n */\nexport interface ChatCheckpointedPayload {\n turn_index: number;\n checkpoint_model: string;\n}\n\n/**\n * Sent with `pending_action_queued` when an unattended run defers a gated\n * action to the approvals queue (action-policy stage). Purely informational\n * for a live viewer — the durable state of record is the backend pending-action\n * row addressed by `pending_action_id`, not this event. Deliberately NOT a\n * reuse of ChatToolCallConfirmationRequiredPayload: that event gates the\n * composer and expects an answer now, whereas a queued action is resolved\n * later from a queue page. Mirrors the engine\n * types.ChatPendingActionQueuedPayload wire contract exactly.\n */\nexport interface ChatPendingActionQueuedPayload {\n turn_index: number;\n pending_action_id: string;\n action_class: string;\n tool_name: string;\n preview: string;\n /** RFC3339; omitted (engine `omitempty`) when the queued action has no expiry. */\n expires_at?: string;\n}\n\n/**\n * Sent with `artifact_drafted` when draft_artifact/revise_artifact/\n * promote_artifact mints or appends an artifact version (artifact-substrate\n * AS-8). Purely informational for a live viewer's chip strip — the durable\n * state of record is the backend row, not this event.\n */\nexport interface ChatArtifactDraftedPayload {\n turn_index: number;\n artifact_id: string;\n version_id: string;\n version_ref: string;\n /**\n * The fully-qualified handle. The split ids are carried alongside it so a\n * viewer does not have to parse the handle to build a link; the two always\n * agree, because the backend produced both from the same row.\n */\n handle: string;\n title?: string;\n kind?: string;\n}\n\n/**\n * Sent with `artifact_referenced` when a turn returns an already-existing\n * artifact version rather than minting a new one. The payload deliberately\n * mirrors `ChatArtifactDraftedPayload`, while the distinct event name keeps\n * fresh-authoring semantics honest for live viewers.\n */\nexport interface ChatArtifactReferencedPayload {\n turn_index: number;\n artifact_id: string;\n version_id: string;\n version_ref: string;\n /**\n * The fully-qualified handle. The split ids are carried alongside it so a\n * viewer does not have to parse the handle to build a link; the two always\n * agree, because the backend produced both from the same row.\n */\n handle: string;\n title?: string;\n kind?: string;\n}\n\nexport interface ChatEvent {\n conversation_id: string;\n turn_id: string;\n type: ChatEventType;\n plan_id?: string;\n step_id?: string;\n payload?:\n | ChatPhasePayload\n | ChatQuestionPayload\n | ChatPlanDraftPayload\n | ChatStepEventPayload\n | ChatStepProgressPayload\n | ChatNarrationPayload\n | ChatAssistantMessagePayload\n | ChatDonePayload\n | ChatSessionTitlePayload\n | ChatToolCallStartedPayload\n | ChatToolCallFinishedPayload\n | ChatLLMCallFinishedPayload\n | ChatToolCallConfirmationRequiredPayload\n | ChatPendingActionQueuedPayload\n | ChatArtifactDraftedPayload\n | ChatArtifactReferencedPayload\n | ChatCompactionFiredPayload\n | ChatCheckpointedPayload\n | unknown;\n timestamp: string;\n event_id?: number;\n}\n\n/**\n * Per-LLM-call audit row written by the chat-loop's recorder.Record (one row\n * per Chat.Completions.New call). Mirrors execution_receipts on the engine\n * side. All numeric token / cost fields are nullable because they weren't\n * tracked for failed calls or pre-migration rows.\n */\nexport interface DebugReceipt {\n id: string;\n flow_id: string;\n org_id: string;\n status: string;\n duration_ms?: number | null;\n model_used?: string | null;\n layer?: string;\n operation?: string;\n attempt_number: number;\n error?: string | null;\n prompt_tokens?: number | null;\n completion_tokens?: number | null;\n cached_prompt_tokens?: number | null;\n cost_usd_micros?: number | null;\n // Billing-ledger tag: 'byok' | 'platform' | 'agent'. NULL on the raw llmlog\n // call rows. Totals should sum cost over rows with a cost_kind (the metered\n // ledger) and tokens over byok/platform rows only — the raw rows and the\n // agent surcharge row otherwise double/triple-count.\n cost_kind?: 'byok' | 'platform' | 'agent' | null;\n prompt?: string | null;\n response?: string | null;\n created_at: string;\n}\n\n/**\n * Debug surface — consolidated payload returned by\n * `GET /api/agentengine/v1/agent/chat/sessions/:id/debug`.\n */\nexport interface DebugPayload {\n session: ChatSession | null;\n messages: ChatMessage[] | null;\n receipts: DebugReceipt[];\n}\n","/**\n * ChatCardV1 — the CLOSED, versioned conversation-card projection (MVP09\n * C1-SDK-CARDS, chat-first realignment proposal §6). This is the SDK mirror of\n * the engine's authority-side type: the wire shape is defined by cloud-agent\n * `internal/types/chat_cards.go` (`ChatCardV1.ToMetadata()`) and the neutral\n * builders in `internal/chat/card_adapter.go`.\n *\n * A card is a DISPLAY PROJECTION of durable product state, never the authority\n * for it. It carries server-stamped scope assertions (product / project_id /\n * sandbox_id) plus an opaque `durable_ref` to the backend row that IS\n * authoritative. It deliberately carries NO domain payload: an approver still\n * resolves the pending action against its own record, an artifact is still\n * fetched from the substrate.\n *\n * The card is persisted as the metadata of a `card`-kind `agent_chat_messages`\n * row, so a reconnecting client rehydrates it through the reload read path\n * (`client.chat.sessions.get()` -> GetChatSessionResponse.messages); the live\n * SSE `pending_action_queued` / `artifact_drafted` events (C0-SDK-STREAM) feed\n * the same projection for a connected viewer.\n *\n * Two safety laws govern this file (proposal §6, §10):\n * 1. The union is CLOSED. `card_type` and every action are enumerated. A card\n * whose `schema_version` or `card_type` this client does not recognise\n * parses to a safe, inert {@link UnknownChatCard} fallback — it is NEVER\n * cast to a typed variant, and the fallback exposes no `actions` field, so\n * it cannot be a source of dispatchable actions.\n * 2. A card action is one of the enumerated inert names and nothing else. An\n * unknown action string is dropped during parse, so it can never survive\n * into the dispatchable union. The model may propose display content but\n * never an arbitrary URL, endpoint, verb, credential or executable.\n *\n * Scope validation (rejecting a stale / cross-scope projection) is NOT done\n * here: the SDK parser has no session scope to compare against. That is the\n * engine read guard (`FilterCardMessagesForScope`, C1-BE-CARD-STORE) and the\n * console reducer (C1-UI-CARD-STATE). This file owns only the closed-union type\n * and its safe, never-executable parse.\n */\n\nimport type { ChatMessage } from './types.js';\n\n/** The only schema version this client narrows to a typed variant. A higher\n * (or zero/negative) version is treated as an opaque, inert fallback. */\nexport const CHAT_CARD_SCHEMA_VERSION = 1 as const;\n\n/** Message kind tagging an agent_chat_messages row whose metadata carries a\n * ChatCardV1 projection (mirrors cloud-agent `types.ChatMessageKindCard`). */\nexport const CHAT_MESSAGE_KIND_CARD = 'card' as const;\n\n/** The closed set of card types. Every variant of the discriminated union\n * below is keyed on one of these; anything else is an inert fallback. */\nexport const CHAT_CARD_TYPES = [\n 'connection_required',\n 'pending_action',\n 'artifact',\n 'record',\n 'receipt',\n] as const;\nexport type ChatCardType = (typeof CHAT_CARD_TYPES)[number];\n\n/** The closed set of inert card actions. `navigate` targets are allowlisted and\n * scope-bound by the UI; `refresh` only refetches the durable record;\n * `answer_question` / `decide_confirmation` submit to their existing bounded\n * endpoints. No other verb is representable. */\nexport const CHAT_CARD_ACTIONS = [\n 'navigate',\n 'answer_question',\n 'decide_confirmation',\n 'refresh',\n] as const;\nexport type ChatCardAction = (typeof CHAT_CARD_ACTIONS)[number];\n\n/** Opaque pointer to the authoritative backend row — a reference, never the\n * payload. {kind,id,version} is enough to refetch and re-authorise the current\n * state, and carries no secret or domain content. */\nexport interface ChatCardDurableRef {\n kind: string;\n id: string;\n version?: string;\n}\n\n/** Fields shared by every closed variant. `product` / `project_id` /\n * `sandbox_id` are SERVER-STAMPED scope assertions used for display and for\n * read-time rejection of a stale / cross-scope projection; they are never\n * selector inputs and cannot override the session's server-derived topology. */\ninterface ChatCardCommonV1 {\n schema_version: typeof CHAT_CARD_SCHEMA_VERSION;\n card_id: string;\n product: string;\n project_id: string;\n sandbox_id: string;\n title?: string;\n summary?: string;\n status?: string;\n durable_ref?: ChatCardDurableRef;\n /** Always the enumerated inert actions only — unknown strings are dropped at\n * parse, so this array can never carry a non-dispatchable verb. */\n actions: ChatCardAction[];\n}\n\nexport interface ConnectionRequiredCardV1 extends ChatCardCommonV1 {\n card_type: 'connection_required';\n}\nexport interface PendingActionCardV1 extends ChatCardCommonV1 {\n card_type: 'pending_action';\n}\nexport interface ArtifactCardV1 extends ChatCardCommonV1 {\n card_type: 'artifact';\n}\nexport interface RecordCardV1 extends ChatCardCommonV1 {\n card_type: 'record';\n}\nexport interface ReceiptCardV1 extends ChatCardCommonV1 {\n card_type: 'receipt';\n}\n\n/** The CLOSED discriminated union. Narrow on `card_type` to reach a variant. */\nexport type ChatCardV1 =\n | ConnectionRequiredCardV1\n | PendingActionCardV1\n | ArtifactCardV1\n | RecordCardV1\n | ReceiptCardV1;\n\n/**\n * The safe, inert fallback for a projection this client does not recognise —\n * an unknown `schema_version` or an unknown `card_type`. It deliberately has NO\n * `actions` field: a consumer cannot read a dispatchable action off it, which is\n * exactly what \"never an executable cast\" means. `raw` is the untouched\n * metadata, for inert text rendering only — never narrowed, never a source of\n * actions or navigation.\n */\nexport interface UnknownChatCard {\n card_type: 'unknown';\n reason: 'unknown_version' | 'unknown_type';\n schema_version?: number;\n card_id?: string;\n title?: string;\n summary?: string;\n status?: string;\n raw: Record<string, unknown>;\n}\n\n/** The result of {@link parseChatCard}: a typed closed variant OR the inert\n * fallback. `undefined` (from the parser) means \"not a card at all\". */\nexport type ParsedChatCard = ChatCardV1 | UnknownChatCard;\n\n/** Narrowing guard: a parsed card is a typed closed variant (not the inert\n * fallback). Use before touching `.actions` or any variant field. */\nexport function isKnownChatCard(card: ParsedChatCard): card is ChatCardV1 {\n return card.card_type !== 'unknown';\n}\n\nconst CARD_TYPE_SET: ReadonlySet<string> = new Set(CHAT_CARD_TYPES);\nconst CARD_ACTION_SET: ReadonlySet<string> = new Set(CHAT_CARD_ACTIONS);\n\n/** Reports whether `t` is a recognised closed card type. */\nexport function isKnownChatCardType(t: unknown): t is ChatCardType {\n return typeof t === 'string' && CARD_TYPE_SET.has(t);\n}\n\n/** Reports whether `a` is a recognised inert card action. */\nexport function isKnownChatCardAction(a: unknown): a is ChatCardAction {\n return typeof a === 'string' && CARD_ACTION_SET.has(a);\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction asString(v: unknown): string {\n return typeof v === 'string' ? v : '';\n}\n\nfunction optString(v: unknown): string | undefined {\n return typeof v === 'string' && v !== '' ? v : undefined;\n}\n\nfunction parseDurableRef(v: unknown): ChatCardDurableRef | undefined {\n if (!isRecord(v)) return undefined;\n const kind = asString(v.kind);\n const id = asString(v.id);\n if (kind === '' && id === '') return undefined;\n const ref: ChatCardDurableRef = { kind, id };\n const version = optString(v.version);\n if (version !== undefined) ref.version = version;\n return ref;\n}\n\n/** Keep ONLY the enumerated inert actions, in order. An unknown action string\n * is dropped so it can never survive into the dispatchable union. */\nfunction parseActions(v: unknown): ChatCardAction[] {\n if (!Array.isArray(v)) return [];\n const out: ChatCardAction[] = [];\n for (const a of v) {\n if (isKnownChatCardAction(a)) out.push(a);\n }\n return out;\n}\n\nfunction coerceVersion(v: unknown): number | undefined {\n if (typeof v === 'number') return v;\n if (typeof v === 'string' && v.trim() !== '' && !Number.isNaN(Number(v))) return Number(v);\n return undefined;\n}\n\n/**\n * Parse an arbitrary metadata blob into a closed {@link ChatCardV1} variant or\n * the inert {@link UnknownChatCard} fallback.\n *\n * - Not a card at all (non-object, or no string `card_type`) -> `undefined`.\n * - `schema_version` !== {@link CHAT_CARD_SCHEMA_VERSION} -> inert fallback\n * (`reason: 'unknown_version'`) even if the type is otherwise known: a future\n * version may reinterpret fields, so it is never narrowed to a typed cast.\n * - `card_type` outside the closed set -> inert fallback\n * (`reason: 'unknown_type'`).\n * - Otherwise a typed variant whose `actions` are filtered to the enumerated\n * inert set.\n *\n * This is total and never throws; a malformed field degrades to empty/undefined\n * rather than propagating an executable value.\n */\nexport function parseChatCard(metadata: unknown): ParsedChatCard | undefined {\n if (!isRecord(metadata)) return undefined;\n const cardType = metadata.card_type;\n // A card is identified by a string card_type. Without one this metadata is\n // something else (e.g. the claim_annotations sidecar) — not a card.\n if (typeof cardType !== 'string' || cardType === '') return undefined;\n\n const version = coerceVersion(metadata.schema_version);\n\n const fallback = (reason: UnknownChatCard['reason']): UnknownChatCard => {\n const u: UnknownChatCard = { card_type: 'unknown', reason, raw: metadata };\n if (version !== undefined) u.schema_version = version;\n const id = optString(metadata.card_id);\n if (id !== undefined) u.card_id = id;\n const title = optString(metadata.title);\n if (title !== undefined) u.title = title;\n const summary = optString(metadata.summary);\n if (summary !== undefined) u.summary = summary;\n const status = optString(metadata.status);\n if (status !== undefined) u.status = status;\n return u;\n };\n\n // Unknown/absent version is inert BEFORE any type narrowing — a v2 card must\n // never be cast to a v1 variant just because its card_type name matches.\n if (version !== CHAT_CARD_SCHEMA_VERSION) return fallback('unknown_version');\n if (!isKnownChatCardType(cardType)) return fallback('unknown_type');\n\n const card: ChatCardV1 = {\n schema_version: CHAT_CARD_SCHEMA_VERSION,\n card_type: cardType,\n card_id: asString(metadata.card_id),\n product: asString(metadata.product),\n project_id: asString(metadata.project_id),\n sandbox_id: asString(metadata.sandbox_id),\n actions: parseActions(metadata.actions),\n };\n const title = optString(metadata.title);\n if (title !== undefined) card.title = title;\n const summary = optString(metadata.summary);\n if (summary !== undefined) card.summary = summary;\n const status = optString(metadata.status);\n if (status !== undefined) card.status = status;\n const durableRef = parseDurableRef(metadata.durable_ref);\n if (durableRef !== undefined) card.durable_ref = durableRef;\n return card;\n}\n\n/**\n * Read the ChatCardV1 projection off a chat message. Returns `undefined` for\n * any message that is not a `card`-kind row, so an ordinary text / question /\n * tool message is never reinterpreted as a card even if its metadata happens to\n * be card-shaped. An in-scope card-kind message with an unknown version/type is\n * returned as the inert {@link UnknownChatCard} fallback (render as text; never\n * dispatch), matching the engine's \"retain an unknown card_type as inert\"\n * reload behavior (proposal §6, §10).\n */\nexport function chatCardOf(\n message: Pick<ChatMessage, 'kind' | 'metadata'>,\n): ParsedChatCard | undefined {\n if (message.kind !== CHAT_MESSAGE_KIND_CARD) return undefined;\n return parseChatCard(message.metadata);\n}\n","/**\n * Component capability plane — harden-merge F4 (REL-01).\n *\n * The backend is the single source of truth for whether a\n * common-infrastructure component exists in a deployment. Every consumer — the\n * console, the engine, this SDK — reads the same answer instead of deciding for\n * itself, which is the failure this closes: the console listed component\n * navigation unconditionally while four of the eight components had no backend\n * flag at all, so no single surface was wrong and none of them was dark.\n */\n\n/** The canonical component enum. Adding a ninth means changing the backend\n * enum, the database CHECK, the engine mirror and this list together. */\nexport const COMPONENT_IDS = [\n 'action_policy',\n 'connection_inventory',\n 'contact_registry',\n 'pack_registry',\n 'artifact_substrate',\n 'evidence_citation',\n 'fact_governance',\n 'signal_store',\n] as const;\n\nexport type ComponentId = (typeof COMPONENT_IDS)[number];\n\n/**\n * A component's lifecycle position for the calling organization.\n *\n * - `implemented` — the code exists; this deployment has not enabled it.\n * - `available` — the deployment enables it; no organization grant yet.\n * - `enabled` — this organization may use it.\n *\n * Only `enabled` means anything may render, register or run. The three states\n * are distinguished rather than collapsed into a boolean because \"not built\n * here\" and \"built but not granted to you\" are different answers to the same\n * support question.\n */\nexport type ComponentState = 'implemented' | 'available' | 'enabled';\n\nexport interface CapabilitiesResponse {\n /** Keyed by ComponentId; read a missing key as NOT enabled. */\n components: Record<string, ComponentState>;\n /** True when the answer describes an impersonation target rather than the\n * caller's own organization. */\n impersonating?: boolean;\n orgId?: string;\n}\n\nexport interface SetEnabledComponentsRequest {\n /** Replaces the organization's grants. An unknown id is rejected, not\n * dropped — silently ignoring a typo leaves an operator believing they\n * granted something they did not. */\n components: ComponentId[];\n}\n\nexport interface SetEnabledComponentsResponse {\n id: string;\n enabledComponents: string[];\n}\n\n/**\n * The cohort editor's READ — harden-merge F-5 / CE-6.\n *\n * `stored` and `components` deliberately differ. A grant for a component this\n * deployment does not have is accepted and stored and changes nothing:\n * composition is one-directional, so a grant waits for the deployment flag and\n * can never widen it. An editor showing only the stored list would report a\n * grant that is inert; one showing only the effective state would make the\n * operator's own write look ignored.\n */\nexport interface EnabledComponentsResponse {\n id: string;\n /** What the organization's grant row says, in manifest order. */\n stored: ComponentId[];\n /** What this DEPLOYMENT has, irrespective of any grant. */\n available: ComponentId[];\n /** The two composed. Keyed by ComponentId; a missing key is NOT enabled. */\n components: Record<string, ComponentState>;\n /** Ids present in the row that the canonical enum does not know. Reported\n * rather than dropped: hiding one would let the next write delete it. */\n unknownStored?: string[];\n}\n","// Hierarchical USD budgets. All wire values are USD micros (1 USD = 1_000_000);\n// 0 means \"no cap / inherit from parent\" — never \"free\".\n\nexport type BudgetScope = 'org' | 'workspace' | 'repo' | 'chat';\n\nexport interface OrgBudget {\n id: string;\n org_id: string;\n daily_limit: number; // legacy token caps — NOT enforced; counters below are telemetry only\n monthly_limit: number;\n tokens_today: number;\n tokens_month: number;\n daily_cost_limit_usd_micros: number;\n monthly_cost_limit_usd_micros: number;\n cost_today_usd_micros: number;\n cost_month_usd_micros: number;\n chat_session_cost_limit_usd_micros: number;\n reset_day_at: string;\n reset_month_at: string;\n updated_at: string;\n /** M3 Stage 3: action categories allowed at this scope. `read` is\n * implicit and never appears here. Lower scopes (workspace, repo,\n * schedule) intersect with this set. */\n granted_categories: string[];\n /** M3 Stage 4: inheritable schedule auto-disable threshold. Null\n * means \"inherit from parent\"; engine default is 5 when every\n * level in the chain is null. */\n max_consecutive_failures?: number;\n}\n\nexport interface ScopedBudget {\n id: string;\n org_id: string;\n workspace_id?: string;\n repo_id?: string;\n daily_cost_limit_usd_micros: number;\n monthly_cost_limit_usd_micros: number;\n chat_session_cost_limit_usd_micros: number;\n cost_today_usd_micros: number;\n cost_month_usd_micros: number;\n reset_day_at: string;\n reset_month_at: string;\n updated_at: string;\n /** M3 Stage 3: see OrgBudget.granted_categories. Subset of parent. */\n granted_categories: string[];\n /** M3 Stage 4: see OrgBudget.max_consecutive_failures. */\n max_consecutive_failures?: number;\n}\n\nexport interface ChatBudget {\n id: string;\n org_id: string;\n workspace_id: string;\n repo_id: string;\n chat_session_id: string;\n cost_limit_usd_micros: number;\n cost_total_usd_micros: number;\n created_by_user_id: string;\n updated_at: string;\n}\n\nexport interface EffectiveChatBudget {\n limit_usd_micros: number;\n source: BudgetScope;\n spent_usd_micros: number;\n}\n\nexport interface UpdateOrgBudgetRequest {\n daily_cost_limit_usd_micros?: number;\n monthly_cost_limit_usd_micros?: number;\n chat_session_cost_limit_usd_micros?: number;\n /** M3 Stage 3: replace the action-category grant set. Omit to leave\n * unchanged; empty array relaxes to read-only. */\n granted_categories?: string[];\n /** M3 Stage 4: per-scope schedule auto-disable cap. Omit to leave\n * unchanged. */\n max_consecutive_failures?: number;\n}\n\nexport interface UpdateScopedBudgetRequest {\n daily_cost_limit_usd_micros?: number;\n monthly_cost_limit_usd_micros?: number;\n chat_session_cost_limit_usd_micros?: number;\n /** M3 Stage 3: replace the action-category grant set. Server rejects\n * (422 grants_outside_parent) when the requested set isn't a subset\n * of the parent scope's effective grant. */\n granted_categories?: string[];\n /** M3 Stage 4: per-scope schedule auto-disable cap. */\n max_consecutive_failures?: number;\n}\n\nexport interface UpdateChatBudgetRequest {\n cost_limit_usd_micros: number;\n}\n\nexport interface UpdateCostLimitRequest {\n cost_limit_usd_micros: number;\n}\n\nexport const usdMicros = {\n toDollars: (micros: number): number => micros / 1_000_000,\n fromDollars: (dollars: number): number => Math.round(dollars * 1_000_000),\n};\n","// Dashboard Spec types — TypeScript mirror of the canonical JSON Schema\n// cloud-agent/internal/chat/dashboardspec/schema/flashback.dashboard.v1.schema.json\n// (copied into this package as ./schema.json). The JSON Schema is the single\n// source of truth (Visual-Dashboards block B1); these types and ./schema.json\n// must stay byte-for-shape in sync with the engine schema when it changes.\n//\n// The Dashboard Spec is the durable, data-free, PII-free recipe the BI agent's\n// compose_dashboard tool emits. Each panel carries a `binding` (a parameterized\n// query against a semantic model) and a `viz` (how to draw the result). Data is\n// transient; the spec is forever.\n\n/** The spec major-version discriminator carried in DashboardSpec.schema. */\nexport const DASHBOARD_SCHEMA_VERSION = 'flashback.dashboard/v1';\n\nexport type PanelType =\n | 'kpi' | 'gauge' | 'table'\n | 'bar' | 'line' | 'area' | 'point' | 'arc' | 'rule' | 'tick' | 'rect';\n\n/** Chart marks = the curated, recursion-stripped Vega-Lite subset. */\nexport type ChartMark = 'bar' | 'line' | 'area' | 'point' | 'arc' | 'rule' | 'tick' | 'rect';\n\n/** Semantic color roles (D6) — the spec picks a role, never a raw hex. */\nexport type ColorRole = 'sequential' | 'categorical' | 'diverging' | 'goodBad';\n\nexport type ChannelType = 'nominal' | 'quantitative' | 'temporal' | 'ordinal';\nexport type ChannelSort = '-x' | 'x' | '-y' | 'y' | 'ascending' | 'descending' | null;\n/** Inline-aggregate functions (for models without authored measures). */\nexport type AggFn = 'sum' | 'avg' | 'min' | 'max' | 'count' | 'distinctcount';\nexport type ParameterType = 'daterange' | 'dimension' | 'scalar';\nexport type FilterOp = 'eq' | 'in' | 'gt' | 'gte' | 'lt' | 'lte' | 'between';\nexport type SortDir = 'asc' | 'desc';\n/** Rehydration strategy (distinct from B0's piiClass field classification). */\nexport type PIITier = 'none' | 'rehydrate';\n\n/** The whole authored artifact. */\nexport interface DashboardSpec {\n /** Always DASHBOARD_SCHEMA_VERSION for v1. */\n schema: typeof DASHBOARD_SCHEMA_VERSION;\n title: string;\n description?: string;\n scope: DashboardScope;\n /** Dashboard-level controls; bindings reference them by id (cross-filter-ready). */\n parameters?: Parameter[];\n /** react-grid-layout-shaped 12-col grid; one entry per panel id. */\n layout: LayoutItem[];\n panels: Panel[];\n}\n\nexport interface DashboardScope {\n repoId: string;\n /** Default model for any panel binding that omits modelId. */\n defaultModelId?: string;\n}\n\nexport interface Parameter {\n id: string;\n type: ParameterType;\n label: string;\n /** Required when type === 'dimension'. A field ref, e.g. \"Branch[Name]\". */\n field?: string;\n multi?: boolean;\n /** Shape depends on type: daterange => {relative}|{from,to}; etc. */\n default?: unknown;\n}\n\nexport interface LayoutItem {\n /** Matches a Panel.id. */\n i: string;\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** A param-bound filter ({param}) or a literal ({field,op,value}). */\nexport type Filter = ParamFilter | LiteralFilter;\nexport interface ParamFilter { param: string; }\nexport interface LiteralFilter { field: string; op: FilterOp; value: unknown; }\n\nexport interface TopN { by: string; n: number; dir: SortDir; }\n\n/**\n * An inline aggregate — a measure term for models that define few/no catalog\n * measures. Aggregates a raw column; compiles to AGG('Entity'[Column]) aliased\n * `as`, whose result column is keyed \"[as]\" (referenced like a measure ref).\n */\nexport interface InlineAggregate {\n agg: AggFn;\n /** Field ref, e.g. \"Timesheet[WorkedHours]\". */\n field: string;\n /** Result alias (no brackets; unique within the binding). */\n as: string;\n}\n\n/** The unit of a dateDiff duration. */\nexport type DateDiffUnit = 'day' | 'week' | 'month' | 'quarter' | 'year';\n\n/**\n * A closed-form duration measure term (WP4): AGG of DATEDIFF(from, to, unit) over\n * the rows of the two columns' shared entity, skipping blank endpoints. from/to\n * MUST be Date columns on the SAME entity. Result column is keyed \"[as]\".\n */\nexport interface DateDiffAggregate {\n agg: 'avg' | 'min' | 'max' | 'sum';\n dateDiff: {\n /** Field ref, a Date column. */\n from: string;\n /** Field ref, a Date column on the same entity. */\n to: string;\n unit: DateDiffUnit;\n /** Skip rows where to < from instead of letting them drag the aggregate. */\n nonNegative?: boolean;\n };\n /** Result alias (no brackets; unique within the binding). */\n as: string;\n}\n\n/**\n * A measure term: a catalog measure ref (\"[Name]\"), an inline aggregate, or a\n * closed-form dateDiff duration.\n */\nexport type MeasureTerm = string | InlineAggregate | DateDiffAggregate;\n\n/**\n * A DATE-GRAIN dimension term: groups by a date column bucketed to a calendar unit\n * instead of by its raw value. Grouping a raw date column buckets by every distinct\n * timestamp, which draws as noise rather than a trend. The bucket is COMPUTED, so it\n * comes back keyed \"[as]\" (like an inline aggregate, not like a plain dimension) and\n * viz.encoding fields reference it that way, with channel type \"temporal\".\n */\nexport interface DateGrainDimension {\n /** Field ref, a Date column. */\n field: string;\n dateGrain: DateDiffUnit;\n /** Result alias (no brackets; unique across the binding's dimensions AND measures). */\n as: string;\n}\n\n/**\n * A dimension term: a plain field ref (\"Mechanic[MechanicId]\"), or a date-grain\n * term that buckets a date column.\n */\nexport type DimensionTerm = string | DateGrainDimension;\n\n/** The durable, data-free, PII-free query. */\nexport interface Binding {\n modelId?: string;\n /** Measure terms — catalog refs, inline aggregates, and/or dateDiff durations. Non-empty. */\n measures: MeasureTerm[];\n /** Dimension terms — field refs (PII ids, never names) and/or date-grain buckets. */\n dimensions?: DimensionTerm[];\n filters?: Filter[];\n /**\n * Optional. An entity localKey or \"total\" (never a column name). When omitted it\n * is derived engine-side: \"total\" for a dimension-less binding, else the first\n * dimension's entity. B3 checks it ∈ measure.validGrains.\n */\n grain?: string;\n topN?: TopN;\n}\n\n// ── Cross-dataset composite bindings (cross-dataset-links) ──────────────────\n\n/** One side of a composite panel: a role handle plus an ordinary Binding. */\nexport interface SourceBinding {\n /** Lowercase identifier, max 24 chars (e.g. \"purchases\"). */\n role: string;\n /** The sub-binding — the existing Binding shape VERBATIM, one model. */\n binding: Binding;\n /** Carried pass-through attributes of this side (engine-injected, ≤4). */\n carry?: CarryField[];\n}\n\n/**\n * One carried pass-through attribute of a source: a fieldRef in this side's\n * model that is single-valued per join key (verified engine-side at run time —\n * a violated declaration fails the query closed, never fans out the join).\n * The engine injects it into the side's grouping (never author it in\n * binding.dimensions) and the joined row exposes it under the bare alias `as`,\n * usable in output.groupBy / select / derived like a join-key alias.\n */\nexport interface CarryField {\n /** Field ref in this side's model, e.g. \"mechanic_profile[certification]\". */\n field: string;\n /** Bare joined-column alias (no brackets/dots). */\n as: string;\n}\n\n/** One visual-grain join pair: conformed dimension fieldRefs joined under `as`. */\nexport interface JoinOn {\n /** Field ref on the link's LEFT-side source, e.g. \"Date[Month]\". */\n left: string;\n /** Field ref on the link's RIGHT-side source. */\n right: string;\n /** Bare joined-column alias (no brackets/dots), e.g. \"Month\". */\n as: string;\n}\n\n/**\n * A closed-grammar expression over qualified refs (\"role.[Alias]\", \"[Alias]\",\n * bare join-key alias): + - * / ( ), numbers, datediff(day|week|month|year, a, b),\n * coalesce(...), abs(x), round(x, n). Parsed engine-side — never raw DAX/SQL.\n */\nexport interface DerivedTerm {\n expr: string;\n /** Result alias (no brackets); referenced downstream as \"[as]\". */\n as: string;\n}\n\nexport type CompositeSelectTerm =\n | { from: string; as: string }\n | { agg: 'sum' | 'avg' | 'min' | 'max' | 'count'; of: string; as: string };\n\n/**\n * The final in-engine projection: \"rows\" passes joined rows through the select\n * terms; \"aggregate\" groups by groupBy and folds aggregate terms. `derived`\n * terms are POST-aggregation expressions over the measure-shaped output\n * columns (\"[as]\"), evaluated after grouping and before topN — the home of\n * ratio-of-sums (weighted averages, margin %). Output column keys follow the\n * panel contract: measure-shaped terms come back keyed \"[as]\",\n * dimension-shaped pass-throughs bare \"as\".\n */\nexport interface CompositeOutput {\n mode: 'rows' | 'aggregate';\n groupBy?: string[];\n select: CompositeSelectTerm[];\n derived?: DerivedTerm[];\n topN?: TopN;\n}\n\n/**\n * A cross-dataset panel query (cross-dataset-links): two single-model\n * sub-bindings pushed down as ordinary aggregates, hash-joined in the engine\n * through a validated link, derived terms evaluated by the closed expression\n * grammar, then projected/re-aggregated. Entity grain joins per link key (the\n * engine injects the key columns — never author them); visual grain joins\n * visual-sized result sets on the conformed `on` dimensions. A source may\n * `carry` one-sided attributes that are single-valued per join key\n * (runtime-verified) to group the joined result by them.\n */\nexport interface CompositeBinding {\n /** Name of the bi_link (conformed entity) this panel joins through. */\n link: string;\n /** Exactly two sources. */\n sources: SourceBinding[];\n joinGrain: 'entity' | 'visual';\n /** Visual grain only; entity grain joins on the link's key pairs. */\n on?: JoinOn[];\n join?: 'inner' | 'left' | 'full';\n derived?: DerivedTerm[];\n output: CompositeOutput;\n}\n\n/** Last-mile PII re-hydration hook (resolved engine-side by B4). */\nexport interface Display {\n /** Field ref whose value fills the synthetic __label column. */\n labelField: string;\n piiTier?: PIITier;\n}\n\nexport interface ColorScale {\n scheme: { role: ColorRole };\n domainMid?: number;\n}\n\nexport interface Channel {\n /**\n * A measure ref (\"[Efficiency %]\", incl. an inline aggregate's \"[as]\" alias),\n * a field ref, or a synthetic: \"__label\" (rehydrated display name) or the fold\n * pair \"__measure\"/\"__value\" (the renderer unpivots the measure columns — the\n * way to compare several measures as categories in one chart).\n */\n field: string;\n type: ChannelType;\n sort?: ChannelSort;\n scale?: ColorScale;\n axis?: { title?: string; format?: string };\n format?: string;\n}\n\n/** Flat, fixed channel set — no layer/concat/facet (envelope's job) and no transform. */\nexport interface Encoding {\n x?: Channel;\n y?: Channel;\n color?: Channel;\n size?: Channel;\n theta?: Channel;\n row?: Channel;\n column?: Channel;\n}\n\nexport interface ChartViz { mark: ChartMark; encoding: Encoding; }\nexport interface KpiViz {\n format: string;\n delta?: { vs: 'previous_period' | 'prior_year' | 'none' };\n spark?: boolean;\n}\nexport interface GaugeViz {\n format: string;\n min: number;\n max: number;\n thresholds?: Array<{ value: number; role: ColorRole }>;\n}\nexport interface TableViz {\n columns?: Array<{ field: string; label?: string; format?: string; conditional?: boolean }>;\n sort?: { field: string; dir: SortDir };\n pageSize?: number;\n}\n\nexport type Viz = ChartViz | KpiViz | GaugeViz | TableViz;\n\n/** Cross-filter reservation (rung 3); runtime is the frontend (B6). */\nexport interface PanelInteraction {\n emits?: Array<{ param: string; from: 'x' | 'y' | 'color' | 'size' | 'theta' | 'row' | 'column' }>;\n}\n\ninterface PanelBase {\n id: string;\n title: string;\n /**\n * The single-model query. Exactly one of binding / compositeBinding is set\n * (schema oneOf) — a compositeBinding panel joins two models through a\n * validated cross-dataset link.\n */\n binding?: Binding;\n compositeBinding?: CompositeBinding;\n display?: Display;\n interaction?: PanelInteraction;\n}\n\n/** A chart panel: type is one of the curated marks; viz is the VL subset. */\nexport interface ChartPanel extends PanelBase { type: ChartMark; viz: ChartViz; }\nexport interface KpiPanel extends PanelBase { type: 'kpi'; viz: KpiViz; }\nexport interface GaugePanel extends PanelBase { type: 'gauge'; viz: GaugeViz; }\nexport interface TablePanel extends PanelBase { type: 'table'; viz: TableViz; }\n\n/** A panel — discriminated on `type` (mirrors the schema's if/then union). */\nexport type Panel = ChartPanel | KpiPanel | GaugePanel | TablePanel;\n","// Pure, dependency-free pre-validation for a Dashboard Spec — mirrors the cheap,\n// high-value checks the engine validator runs (cloud-agent\n// internal/chat/dashboardspec). This is for fast, friendly UX in the dashboard\n// editor (block B6): fail fast on obvious mistakes before a round-trip. It is\n// deliberately NOT a full JSON-Schema validator — the engine (santhosh-tekuri\n// against ./schema.json) is the authoritative safety net. Keep it consistent\n// with providers.ts's pure-validate philosophy.\n\nimport { DASHBOARD_SCHEMA_VERSION, type DashboardSpec, type PanelType } from './types.js';\n\n/** One structural problem, shaped like the engine's SpecError. */\nexport interface SpecError {\n /** JSON-pointer-ish path into the spec, e.g. \"/panels/0/binding\". */\n path: string;\n /** Short failing-rule tag, e.g. \"required\", \"enum\", \"integrity.layout\". */\n keyword: string;\n message: string;\n}\n\nexport interface ValidateResult {\n ok: boolean;\n errors: SpecError[];\n}\n\nconst PANEL_TYPES: ReadonlySet<string> = new Set<PanelType>([\n 'kpi', 'gauge', 'table', 'bar', 'line', 'area', 'point', 'arc', 'rule', 'tick', 'rect',\n]);\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction nonEmptyString(v: unknown): v is string {\n return typeof v === 'string' && v.length > 0;\n}\n\n/**\n * The result-column key a measure term produces: \"[Name]\" for a catalog ref\n * (string form), \"[as]\" for an inline aggregate (object form). Returns undefined\n * for a malformed term (the engine schema is the authority that rejects it).\n */\nfunction measureColumnKey(term: unknown): string | undefined {\n if (typeof term === 'string') return term;\n if (isObject(term) && nonEmptyString(term.as)) return `[${term.as}]`;\n return undefined;\n}\n\n/**\n * Validates the envelope + cross-reference integrity of a candidate spec. Returns\n * `{ ok, errors }`; `ok` is true only when `errors` is empty. Never throws.\n */\nexport function validateDashboardSpec(input: unknown): ValidateResult {\n const errors: SpecError[] = [];\n const push = (path: string, keyword: string, message: string) => errors.push({ path, keyword, message });\n\n if (!isObject(input)) {\n return { ok: false, errors: [{ path: '', keyword: 'type', message: 'spec must be a JSON object' }] };\n }\n\n if (input.schema !== DASHBOARD_SCHEMA_VERSION) {\n push('/schema', 'const', `schema must be \"${DASHBOARD_SCHEMA_VERSION}\"`);\n }\n if (!nonEmptyString(input.title)) {\n push('/title', 'required', 'title is required and must be a non-empty string');\n }\n if (!isObject(input.scope) || !nonEmptyString(input.scope.repoId)) {\n push('/scope', 'required', 'scope.repoId is required');\n }\n\n const layout = Array.isArray(input.layout) ? input.layout : [];\n if (layout.length === 0) {\n push('/layout', 'minItems', 'layout must have at least one entry');\n }\n const panels = Array.isArray(input.panels) ? input.panels : [];\n if (panels.length === 0) {\n push('/panels', 'minItems', 'panels must have at least one panel');\n }\n\n // Per-panel envelope checks.\n const panelIds = new Map<string, number>();\n panels.forEach((p, i) => {\n if (!isObject(p)) {\n push(`/panels/${i}`, 'type', 'panel must be an object');\n return;\n }\n if (!nonEmptyString(p.id)) {\n push(`/panels/${i}/id`, 'required', 'panel id is required');\n } else {\n if (panelIds.has(p.id)) push(`/panels/${i}/id`, 'integrity.duplicateId', `duplicate panel id \"${p.id}\"`);\n panelIds.set(p.id, i);\n }\n if (typeof p.type !== 'string' || !PANEL_TYPES.has(p.type)) {\n push(`/panels/${i}/type`, 'enum', `panel type \"${String(p.type)}\" is not a known type`);\n }\n if (!nonEmptyString(p.title)) push(`/panels/${i}/title`, 'required', 'panel title is required');\n if (!isObject(p.viz)) push(`/panels/${i}/viz`, 'required', 'panel viz is required');\n\n // Exactly one of binding / compositeBinding (the schema oneOf).\n const hasBinding = isObject(p.binding);\n const hasComposite = isObject(p.compositeBinding);\n if (!hasBinding && !hasComposite) {\n push(`/panels/${i}/binding`, 'required', 'panel needs a binding or a compositeBinding');\n } else if (hasBinding && hasComposite) {\n push(`/panels/${i}`, 'oneOf', 'panel must carry exactly one of binding / compositeBinding');\n }\n if (hasBinding) {\n validateBinding(p.binding as Record<string, unknown>, `/panels/${i}/binding`, push);\n }\n if (hasComposite) {\n validateComposite(p.compositeBinding as Record<string, unknown>, `/panels/${i}/compositeBinding`, push);\n }\n });\n\n // Integrity 1: id <-> layout 1:1.\n const layoutIds = new Map<string, number>();\n layout.forEach((l, i) => {\n if (!isObject(l) || !nonEmptyString(l.i)) {\n push(`/layout/${i}/i`, 'required', 'layout entry needs a string id \"i\"');\n return;\n }\n if (layoutIds.has(l.i)) push(`/layout/${i}/i`, 'integrity.duplicateLayout', `duplicate layout entry for id \"${l.i}\"`);\n layoutIds.set(l.i, i);\n if (!panelIds.has(l.i)) push(`/layout/${i}/i`, 'integrity.layout', `layout references id \"${l.i}\" with no matching panel`);\n });\n for (const [id, i] of panelIds) {\n if (!layoutIds.has(id)) push(`/panels/${i}`, 'integrity.layout', `panel \"${id}\" has no layout entry`);\n }\n\n // Integrity 2: param references resolve.\n const paramIds = new Set<string>();\n if (Array.isArray(input.parameters)) {\n for (const p of input.parameters) {\n if (isObject(p) && nonEmptyString(p.id)) paramIds.add(p.id);\n }\n }\n panels.forEach((p, pi) => {\n if (!isObject(p)) return;\n const b = isObject(p.binding) ? p.binding : undefined;\n const filters = b && Array.isArray(b.filters) ? b.filters : [];\n filters.forEach((f, fi) => {\n if (isObject(f) && typeof f.param === 'string' && f.param.length > 0 && !paramIds.has(f.param)) {\n push(`/panels/${pi}/binding/filters/${fi}/param`, 'integrity.paramRef', `filter references undeclared parameter \"${f.param}\"`);\n }\n });\n const cb = isObject(p.compositeBinding) ? p.compositeBinding : undefined;\n const sources = cb && Array.isArray(cb.sources) ? cb.sources : [];\n sources.forEach((s, si) => {\n if (!isObject(s) || !isObject(s.binding)) return;\n const sFilters = Array.isArray((s.binding as Record<string, unknown>).filters)\n ? ((s.binding as Record<string, unknown>).filters as unknown[])\n : [];\n sFilters.forEach((f, fi) => {\n if (isObject(f) && typeof f.param === 'string' && f.param.length > 0 && !paramIds.has(f.param)) {\n push(`/panels/${pi}/compositeBinding/sources/${si}/binding/filters/${fi}/param`, 'integrity.paramRef',\n `filter references undeclared parameter \"${f.param}\"`);\n }\n });\n });\n const inter = isObject(p.interaction) ? p.interaction : undefined;\n const emits = inter && Array.isArray(inter.emits) ? inter.emits : [];\n emits.forEach((e, ei) => {\n if (isObject(e) && typeof e.param === 'string' && e.param.length > 0 && !paramIds.has(e.param)) {\n push(`/panels/${pi}/interaction/emits/${ei}/param`, 'integrity.paramRef', `interaction emits undeclared parameter \"${e.param}\"`);\n }\n });\n });\n\n return { ok: errors.length === 0, errors };\n}\n\ntype PushFn = (path: string, keyword: string, message: string) => void;\n\n/** The shared single-model binding checks (plain panels and composite sources). */\nfunction validateBinding(b: Record<string, unknown>, base: string, push: PushFn): void {\n if (!Array.isArray(b.measures) || b.measures.length === 0) {\n push(`${base}/measures`, 'minItems', 'binding.measures must be a non-empty array');\n } else {\n // Integrity 3: measure-term result keys unique within a binding (a duplicate\n // measure ref or inline-aggregate alias would collide in the compiled output).\n const seenKeys = new Set<string>();\n b.measures.forEach((m, mi) => {\n const key = measureColumnKey(m);\n if (key === undefined) return; // malformed term; the engine schema rejects it\n const norm = key.toLowerCase();\n if (seenKeys.has(norm)) {\n push(`${base}/measures/${mi}`, 'integrity.duplicateMeasure',\n `measure term \"${key}\" duplicates an earlier term's result column in this binding`);\n }\n seenKeys.add(norm);\n });\n }\n // grain is OPTIONAL (WP3a): when present it must be a non-empty string, but an\n // omitted grain is valid and derived engine-side. A column-name grain is\n // normalized (not rejected) by the engine bind-check.\n if ('grain' in b && b.grain !== undefined && !nonEmptyString(b.grain)) {\n push(`${base}/grain`, 'type', 'binding.grain, when present, must be a non-empty string (an entity localKey or \"total\")');\n }\n}\n\n/**\n * The catalog-free compositeBinding checks — mirrors the engine's composite\n * integrity rules (roles distinct, 'on' iff visual grain, alias uniqueness,\n * output-mode coherence). Link existence, key fields, PII and the expression\n * grammar are engine-side.\n */\nfunction validateComposite(cb: Record<string, unknown>, base: string, push: PushFn): void {\n if (!nonEmptyString(cb.link)) {\n push(`${base}/link`, 'required', 'compositeBinding.link is required (the cross-dataset link name)');\n }\n const sources = Array.isArray(cb.sources) ? cb.sources : [];\n if (sources.length !== 2) {\n push(`${base}/sources`, 'minItems', 'compositeBinding needs exactly two sources');\n }\n const roles = new Set<string>();\n sources.forEach((s, si) => {\n if (!isObject(s)) {\n push(`${base}/sources/${si}`, 'type', 'source must be an object');\n return;\n }\n if (!nonEmptyString(s.role) || !/^[a-z][a-z0-9_]{0,23}$/.test(s.role)) {\n push(`${base}/sources/${si}/role`, 'pattern', 'source role must be a lowercase identifier (max 24 chars)');\n } else if (roles.has(s.role)) {\n push(`${base}/sources/${si}/role`, 'integrity.role', `source roles must be distinct (both \"${s.role}\")`);\n } else {\n roles.add(s.role);\n }\n if (!isObject(s.binding)) {\n push(`${base}/sources/${si}/binding`, 'required', 'source binding is required');\n return;\n }\n validateBinding(s.binding as Record<string, unknown>, `${base}/sources/${si}/binding`, push);\n if (cb.joinGrain === 'entity' && Array.isArray((s.binding as Record<string, unknown>).dimensions)\n && ((s.binding as Record<string, unknown>).dimensions as unknown[]).length > 0) {\n push(`${base}/sources/${si}/binding/dimensions`, 'integrity.joinOn',\n 'entity-grain sources must not author dimensions — the engine injects the link keys');\n }\n });\n\n const on = Array.isArray(cb.on) ? cb.on : [];\n if (cb.joinGrain === 'visual' && on.length === 0) {\n push(`${base}/on`, 'integrity.joinOn', 'joinGrain \"visual\" requires at least one on pair');\n } else if (cb.joinGrain === 'entity' && on.length > 0) {\n push(`${base}/on`, 'integrity.joinOn', 'joinGrain \"entity\" joins on the link\\'s key pairs — on must be empty');\n } else if (cb.joinGrain !== 'entity' && cb.joinGrain !== 'visual') {\n push(`${base}/joinGrain`, 'enum', 'joinGrain must be \"entity\" or \"visual\"');\n }\n if ('join' in cb && cb.join !== undefined && cb.join !== 'inner' && cb.join !== 'left' && cb.join !== 'full') {\n push(`${base}/join`, 'enum', 'join must be inner, left or full');\n }\n\n // Alias uniqueness across the joined-row namespace (on + carry + derived).\n const aliases = new Set<string>();\n on.forEach((o, oi) => {\n if (!isObject(o) || !nonEmptyString(o.as)) {\n push(`${base}/on/${oi}/as`, 'required', 'every on pair needs a bare alias \"as\"');\n return;\n }\n const norm = o.as.toLowerCase();\n if (aliases.has(norm)) push(`${base}/on/${oi}/as`, 'integrity.alias', `joined-column alias \"${o.as}\" is duplicated`);\n aliases.add(norm);\n });\n sources.forEach((s, si) => {\n if (!isObject(s)) return;\n const carry = Array.isArray(s.carry) ? s.carry : [];\n carry.forEach((c, ci) => {\n if (!isObject(c) || !nonEmptyString(c.as)) {\n push(`${base}/sources/${si}/carry/${ci}/as`, 'required', 'every carry field needs a bare alias \"as\"');\n return;\n }\n if (!nonEmptyString(c.field)) {\n push(`${base}/sources/${si}/carry/${ci}/field`, 'required', 'every carry field needs a field ref');\n }\n const norm = c.as.toLowerCase();\n if (aliases.has(norm)) push(`${base}/sources/${si}/carry/${ci}/as`, 'integrity.alias', `joined-column alias \"${c.as}\" is duplicated`);\n aliases.add(norm);\n });\n });\n const derived = Array.isArray(cb.derived) ? cb.derived : [];\n derived.forEach((d, di) => {\n if (!isObject(d) || !nonEmptyString(d.as)) {\n push(`${base}/derived/${di}/as`, 'required', 'every derived term needs an alias \"as\"');\n return;\n }\n if (!nonEmptyString(d.expr)) {\n push(`${base}/derived/${di}/expr`, 'required', 'every derived term needs an expr');\n }\n const norm = d.as.toLowerCase();\n if (aliases.has(norm)) push(`${base}/derived/${di}/as`, 'integrity.alias', `derived alias \"${d.as}\" duplicates a joined-column alias`);\n aliases.add(norm);\n });\n\n // Output coherence.\n const out = isObject(cb.output) ? cb.output : undefined;\n if (!out) {\n push(`${base}/output`, 'required', 'compositeBinding.output is required');\n return;\n }\n if (out.mode !== 'rows' && out.mode !== 'aggregate') {\n push(`${base}/output/mode`, 'enum', 'output.mode must be \"rows\" or \"aggregate\"');\n }\n if (Array.isArray(out.groupBy) && out.groupBy.length > 0 && out.mode !== 'aggregate') {\n push(`${base}/output/groupBy`, 'integrity.outputMode', 'output.groupBy requires output.mode=\"aggregate\"');\n }\n const select = Array.isArray(out.select) ? out.select : [];\n if (select.length === 0) {\n push(`${base}/output/select`, 'minItems', 'output.select must have at least one term');\n }\n const outAliases = new Set<string>();\n select.forEach((t, ti) => {\n if (!isObject(t) || !nonEmptyString(t.as)) {\n push(`${base}/output/select/${ti}/as`, 'required', 'every output term needs an alias \"as\"');\n return;\n }\n const norm = t.as.toLowerCase();\n if (outAliases.has(norm)) push(`${base}/output/select/${ti}/as`, 'integrity.alias', `output alias \"${t.as}\" is duplicated`);\n outAliases.add(norm);\n if (nonEmptyString(t.agg) && out.mode !== 'aggregate') {\n push(`${base}/output/select/${ti}`, 'integrity.outputMode', `output term \"${t.as}\" aggregates, which requires output.mode=\"aggregate\"`);\n }\n });\n\n // output.derived: post-aggregation terms share the output alias namespace\n // (expression parsing and ref resolution are engine-side).\n const outDerived = Array.isArray(out.derived) ? out.derived : [];\n outDerived.forEach((d, di) => {\n if (!isObject(d) || !nonEmptyString(d.as)) {\n push(`${base}/output/derived/${di}/as`, 'required', 'every output.derived term needs an alias \"as\"');\n return;\n }\n if (!nonEmptyString(d.expr)) {\n push(`${base}/output/derived/${di}/expr`, 'required', 'every output.derived term needs an expr');\n }\n const norm = d.as.toLowerCase();\n if (outAliases.has(norm)) push(`${base}/output/derived/${di}/as`, 'integrity.alias', `output.derived alias \"${d.as}\" duplicates an output column`);\n outAliases.add(norm);\n });\n}\n\n/** Convenience type guard: true when `input` passes pre-validation. */\nexport function isDashboardSpec(input: unknown): input is DashboardSpec {\n return validateDashboardSpec(input).ok;\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://flashback.tech/schemas/dashboard/v1\",\n \"title\": \"Flashback Dashboard Spec v1\",\n \"description\": \"The durable, data-free, PII-free Dashboard Spec authored by the BI agent's compose_dashboard tool. Each panel carries a binding (a parameterized query against one semantic model) OR a compositeBinding (two sub-bindings joined in-engine through a validated cross-dataset link), and a viz (how to draw the result). Data is transient; this spec is forever. Flat and recursion-free by construction so it is safe as a structured-output target and as a validation target (Visual-Dashboards design D1=B / D2=C).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"schema\", \"title\", \"scope\", \"layout\", \"panels\"],\n \"properties\": {\n \"schema\": {\n \"description\": \"Spec major-version discriminator. The validator binds to the major it embeds; forward/back compatibility is handled by upgraders-on-read, not by lax schemas (O7).\",\n \"const\": \"flashback.dashboard/v1\"\n },\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"description\": { \"type\": \"string\", \"maxLength\": 1000 },\n \"scope\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"repoId\"],\n \"properties\": {\n \"repoId\": { \"type\": \"string\", \"minLength\": 1 },\n \"defaultModelId\": {\n \"description\": \"Model used by any panel binding that omits modelId. Panels may bind different models (O3); a plain binding is one model — cross-model joins go through a compositeBinding over a validated link (cross-dataset-links).\",\n \"type\": \"string\"\n }\n }\n },\n \"parameters\": {\n \"description\": \"Dashboard-level interactive controls. binding.filters reference these by id, so one control re-filters every panel and re-population just re-reads them. Locked cross-filter-ready now; rung-2 (global controls) ships early.\",\n \"type\": \"array\",\n \"maxItems\": 24,\n \"items\": { \"$ref\": \"#/$defs/parameter\" }\n },\n \"layout\": {\n \"description\": \"react-grid-layout-shaped, 12-column grid. Persisted verbatim; user-editable. Every item.i must match a panels[].id (enforced by the Go integrity check, not the schema).\",\n \"type\": \"array\",\n \"minItems\": 1,\n \"maxItems\": 64,\n \"items\": { \"$ref\": \"#/$defs/layoutItem\" }\n },\n \"panels\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"maxItems\": 64,\n \"items\": { \"$ref\": \"#/$defs/panel\" }\n }\n },\n\n \"$defs\": {\n \"dateGrainRef\": {\n \"description\": \"A DATE-GRAIN dimension term: groups by a date column BUCKETED to a calendar unit instead of by its raw value. Use it whenever a panel is \\\"by month\\\"/\\\"by quarter\\\"/\\\"by year\\\" — grouping a raw date column buckets by every distinct timestamp, which draws as noise rather than a trend. The bucket is a COMPUTED column, so it comes back keyed \\\"[as]\\\" (like an inline aggregate, not like a plain dimension); viz.encoding fields and topN.by reference it exactly that way, and its channel type is \\\"temporal\\\". The alias may not contain brackets (un-injectable) and must be unique across the binding's dimensions AND measures (Go integrity check). B3 checks the column is actually a date.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"dateGrain\", \"as\"],\n \"properties\": {\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"dateGrain\": { \"enum\": [\"day\", \"week\", \"month\", \"quarter\", \"year\"] },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100, \"pattern\": \"^[^\\\\[\\\\]]+$\" }\n }\n },\n\n \"measureRef\": {\n \"description\": \"A measure reference, e.g. \\\"[Efficiency %]\\\". The bracketed measure name; existence is B3's catalog bind-check, not structural. The name may not contain a bracket ([ or ]) — this keeps the ref un-injectable into DAX (a bracket would break out of the [measure] identifier).\",\n \"type\": \"string\",\n \"pattern\": \"^\\\\[[^\\\\[\\\\]]+\\\\]$\"\n },\n \"fieldRef\": {\n \"description\": \"A field/dimension reference in DAX style, e.g. \\\"Mechanic[MechanicId]\\\". Entity = entity localKey (table name); Column = field column name. Neither segment may contain a bracket ([ or ]) — this makes the ref structurally un-injectable into DAX (a bracket would break out of the 'Entity'[Column] identifier and splice arbitrary columns/expressions). The synthetic \\\"__label\\\" (filled engine-side by B4) is also a legal viz field but is NOT a binding fieldRef.\",\n \"type\": \"string\",\n \"pattern\": \"^[^\\\\[\\\\]]+\\\\[[^\\\\[\\\\]]+\\\\]$\"\n },\n \"aggRef\": {\n \"description\": \"An INLINE AGGREGATE measure term, for models that define few or no catalog measures: aggregates a raw column with a constrained function. Compiles to AGG('Entity'[Column]) aliased as \\\"as\\\"; the result column comes back keyed \\\"[as]\\\", so viz.encoding fields and topN.by reference it exactly like a measureRef. Prefer a real catalog measure whenever one computes the value (bind-check doctrine). The alias may not contain brackets (un-injectable into DAX) and must be unique within the binding (Go integrity check).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"agg\", \"field\", \"as\"],\n \"properties\": {\n \"agg\": { \"enum\": [\"sum\", \"avg\", \"min\", \"max\", \"count\", \"distinctcount\"] },\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100, \"pattern\": \"^[^\\\\[\\\\]]+$\" }\n }\n },\n \"dateDiffRef\": {\n \"description\": \"Closed-form duration measure: AGG of DATEDIFF(from, to, unit) over the rows of the two columns' entity, skipping rows where either date is blank. from/to MUST be Date columns on the SAME entity. Referenced downstream as \\\"[as]\\\", exactly like an inline aggregate. Use for lead time / cycle time / aging — a row-level duration that a plain inline aggregate cannot express.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"agg\", \"dateDiff\", \"as\"],\n \"properties\": {\n \"agg\": { \"enum\": [\"avg\", \"min\", \"max\", \"sum\"] },\n \"dateDiff\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"from\", \"to\", \"unit\"],\n \"properties\": {\n \"from\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"to\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"unit\": { \"enum\": [\"day\", \"week\", \"month\", \"quarter\", \"year\"] },\n \"nonNegative\": { \"type\": \"boolean\", \"description\": \"Skip rows where to < from (data-entry noise) instead of letting them drag the aggregate.\" }\n }\n },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100, \"pattern\": \"^[^\\\\[\\\\]]+$\" }\n }\n },\n\n \"parameter\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"id\", \"type\", \"label\"],\n \"properties\": {\n \"id\": { \"type\": \"string\", \"minLength\": 1 },\n \"type\": { \"enum\": [\"daterange\", \"dimension\", \"scalar\"] },\n \"label\": { \"type\": \"string\", \"minLength\": 1 },\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"multi\": { \"type\": \"boolean\" },\n \"default\": {\n \"description\": \"Default control value. Shape depends on type: daterange => {relative} or {from,to}; dimension => null | string | array; scalar => a literal. Left unconstrained on purpose.\"\n }\n },\n \"allOf\": [\n {\n \"if\": { \"properties\": { \"type\": { \"const\": \"dimension\" } }, \"required\": [\"type\"] },\n \"then\": { \"required\": [\"field\"] }\n }\n ]\n },\n\n \"layoutItem\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"i\", \"x\", \"y\", \"w\", \"h\"],\n \"properties\": {\n \"i\": { \"type\": \"string\", \"minLength\": 1 },\n \"x\": { \"type\": \"integer\", \"minimum\": 0, \"maximum\": 11 },\n \"y\": { \"type\": \"integer\", \"minimum\": 0 },\n \"w\": { \"type\": \"integer\", \"minimum\": 1, \"maximum\": 12 },\n \"h\": { \"type\": \"integer\", \"minimum\": 1, \"maximum\": 64 }\n }\n },\n\n \"filter\": {\n \"oneOf\": [\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"param\"],\n \"properties\": { \"param\": { \"type\": \"string\", \"minLength\": 1 } }\n },\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"op\", \"value\"],\n \"properties\": {\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"op\": { \"enum\": [\"eq\", \"in\", \"gt\", \"gte\", \"lt\", \"lte\", \"between\"] },\n \"value\": {\n \"description\": \"Literal filter value. NOTE: a literal filter on a PII field is rejected by B4/B3 bind-check, not structurally.\"\n }\n }\n }\n ]\n },\n\n \"topN\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"by\", \"n\", \"dir\"],\n \"properties\": {\n \"by\": {\n \"description\": \"The ranking measure: a catalog measureRef, or an inline aggregate's alias in brackets (\\\"[Avg Worked Hours]\\\").\",\n \"$ref\": \"#/$defs/measureRef\"\n },\n \"n\": { \"type\": \"integer\", \"minimum\": 1, \"maximum\": 10000 },\n \"dir\": { \"enum\": [\"asc\", \"desc\"] }\n }\n },\n\n \"binding\": {\n \"description\": \"The durable, data-free, PII-free query. Shape only — DAX compilation (B2) and catalog bind-check (B3: existence, grain in validGrains, cardinality != 'empty', PII labelField) are downstream. A measure term is a catalog measureRef (\\\"[Efficiency %]\\\"), an inline aggRef ({agg, field, as}) for models without authored measures, or a dateDiffRef ({agg, dateDiff, as}) for a duration between two date columns (lead time / cycle time / aging). A dimension term is a plain fieldRef, or a dateGrainRef ({field, dateGrain, as}) that buckets a date column to a calendar unit.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"measures\"],\n \"properties\": {\n \"modelId\": { \"type\": \"string\" },\n \"measures\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": { \"oneOf\": [{ \"$ref\": \"#/$defs/measureRef\" }, { \"$ref\": \"#/$defs/aggRef\" }, { \"$ref\": \"#/$defs/dateDiffRef\" }] }\n },\n \"dimensions\": {\n \"type\": \"array\",\n \"items\": { \"oneOf\": [{ \"$ref\": \"#/$defs/fieldRef\" }, { \"$ref\": \"#/$defs/dateGrainRef\" }] }\n },\n \"filters\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/filter\" } },\n \"grain\": {\n \"description\": \"Optional. The grouping grain: an entity (table) name — an entity localKey — or the literal \\\"total\\\", NEVER a column name. When omitted, it is derived: \\\"total\\\" if the binding has no dimensions, else the first dimension's entity. When present but naming a dimension's column, B3 normalizes it to that dimension's entity. B3 checks grain is in the measure's validGrains (itself a list of localKeys + \\\"total\\\"). Grain is validated ONCE at authoring and trusted on every refresh (the runtime verifier ignores grain).\",\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"topN\": { \"$ref\": \"#/$defs/topN\" }\n }\n },\n\n \"qualifiedRef\": {\n \"description\": \"A joined-row column: 'role.[Alias]' (a source's measure / inline-agg result), '[Alias]' (a derived term), a join-key alias, or an on-pair alias. Bracket-free segments keep the ref structurally un-injectable, exactly like fieldRef.\",\n \"type\": \"string\",\n \"pattern\": \"^([a-z][a-z0-9_]{0,23}\\\\.)?(\\\\[[^\\\\[\\\\]]+\\\\]|[^\\\\[\\\\]\\\\.]+)$\"\n },\n\n \"sourceBinding\": {\n \"description\": \"One side of a composite panel: a role handle plus an ordinary single-model binding (the sub-binding is #/$defs/binding VERBATIM — pushed down and executed exactly like a plain panel's query). In entity grain the engine injects the link-key columns into the sub-binding's dimensions; they are never authored. 'carry' declares pass-through attributes of this side (also engine-injected, never authored).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"role\", \"binding\"],\n \"properties\": {\n \"role\": { \"type\": \"string\", \"pattern\": \"^[a-z][a-z0-9_]{0,23}$\" },\n \"binding\": { \"$ref\": \"#/$defs/binding\" },\n \"carry\": { \"type\": \"array\", \"maxItems\": 4, \"items\": { \"$ref\": \"#/$defs/carryField\" } }\n }\n },\n\n \"carryField\": {\n \"description\": \"One carried pass-through attribute of a source: a fieldRef in this side's model that is single-valued per join key (e.g. a category of the linked entity). The engine injects it into the side's grouping and VERIFIES the single-valued property at run time — a violated declaration fails the query closed, never fans out the join. The joined row exposes it under the bare alias 'as', usable in output.groupBy / select / derived like a join-key alias. On left/full joins, rows missing the carrying side group under a null (unknown) bucket.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"as\"],\n \"properties\": {\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"pattern\": \"^[^\\\\[\\\\]\\\\.]+$\" }\n }\n },\n\n \"joinOn\": {\n \"description\": \"One visual-grain join pair: conformed dimension fieldRefs on the link's left/right side sources, joined under the bare alias 'as'.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"left\", \"right\", \"as\"],\n \"properties\": {\n \"left\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"right\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"pattern\": \"^[^\\\\[\\\\]\\\\.]+$\" }\n }\n },\n\n \"derivedTerm\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"expr\", \"as\"],\n \"properties\": {\n \"expr\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 500,\n \"description\": \"Constrained expression over qualified refs: + - * / ( ), numbers, datediff(day|week|month|year, a, b), coalesce(...), abs(x), round(x, n). Parsed by the engine's closed grammar — never raw DAX/SQL.\"\n },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100, \"pattern\": \"^[^\\\\[\\\\]]+$\" }\n }\n },\n\n \"compositeOutput\": {\n \"description\": \"The final in-engine projection: mode 'rows' passes joined rows through the select terms; mode 'aggregate' groups by groupBy and folds aggregate terms. 'derived' terms are POST-aggregation expressions over the measure-shaped output columns (\\\"[as]\\\"), evaluated after grouping and before topN — use for ratio-of-sums (weighted averages, margin %), which per-joined-row derived terms cannot express. Output column keys follow the panel contract: measure-shaped terms come back keyed \\\"[as]\\\", dimension-shaped pass-throughs bare \\\"as\\\".\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"mode\", \"select\"],\n \"properties\": {\n \"mode\": { \"enum\": [\"rows\", \"aggregate\"] },\n \"groupBy\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/qualifiedRef\" } },\n \"derived\": { \"type\": \"array\", \"maxItems\": 4, \"items\": { \"$ref\": \"#/$defs/derivedTerm\" } },\n \"select\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"oneOf\": [\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"from\", \"as\"],\n \"properties\": {\n \"from\": { \"$ref\": \"#/$defs/qualifiedRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100 }\n }\n },\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"agg\", \"of\", \"as\"],\n \"properties\": {\n \"agg\": { \"enum\": [\"sum\", \"avg\", \"min\", \"max\", \"count\"] },\n \"of\": { \"$ref\": \"#/$defs/qualifiedRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100 }\n }\n }\n ]\n }\n },\n \"topN\": { \"$ref\": \"#/$defs/topN\" }\n }\n },\n\n \"compositeBinding\": {\n \"description\": \"A cross-dataset panel query (cross-dataset-links): two single-model sub-bindings pushed down as ordinary aggregates, hash-joined in the engine through a validated link ('link' names it), derived terms evaluated by the closed expression grammar, then projected/re-aggregated. Entity grain joins per link key (the engine injects the key columns); visual grain joins visual-sized result sets on conformed 'on' dimensions. A source may 'carry' one-sided attributes that are single-valued per join key (runtime-verified) to group the joined result by them. The join inputs are distinct-per-key by construction (verified at run time), so M:N fan-out is structurally absorbed.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"link\", \"sources\", \"joinGrain\", \"output\"],\n \"properties\": {\n \"link\": { \"type\": \"string\", \"minLength\": 1 },\n \"sources\": {\n \"type\": \"array\",\n \"minItems\": 2,\n \"maxItems\": 2,\n \"items\": { \"$ref\": \"#/$defs/sourceBinding\" }\n },\n \"joinGrain\": { \"enum\": [\"entity\", \"visual\"] },\n \"on\": { \"type\": \"array\", \"maxItems\": 4, \"items\": { \"$ref\": \"#/$defs/joinOn\" } },\n \"join\": { \"enum\": [\"inner\", \"left\", \"full\"] },\n \"derived\": { \"type\": \"array\", \"maxItems\": 8, \"items\": { \"$ref\": \"#/$defs/derivedTerm\" } },\n \"output\": { \"$ref\": \"#/$defs/compositeOutput\" }\n }\n },\n\n \"display\": {\n \"description\": \"The reserved last-mile PII re-hydration hook. B4 implements the two-query trick: it fills the synthetic __label column from labelField after the LLM is out of the loop. piiTier (a rehydration strategy) is distinct from B0's piiClass (a field classification).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"labelField\"],\n \"properties\": {\n \"labelField\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"piiTier\": { \"enum\": [\"none\", \"rehydrate\"] }\n }\n },\n\n \"colorScale\": {\n \"description\": \"Semantic color contract (D6): the spec picks a role, never a raw hex or vendor palette. B6's theme module maps each role to an indigo-derived palette from the theme tokens (light + dark).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"scheme\"],\n \"properties\": {\n \"scheme\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"role\"],\n \"properties\": { \"role\": { \"enum\": [\"sequential\", \"categorical\", \"diverging\", \"goodBad\"] } }\n },\n \"domainMid\": { \"type\": \"number\" }\n }\n },\n\n \"channel\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"type\"],\n \"properties\": {\n \"field\": {\n \"description\": \"A measureRef (\\\"[Efficiency %]\\\" — incl. an inline aggregate's \\\"[as]\\\" alias), a fieldRef, or a synthetic: \\\"__label\\\" (the rehydrated display name, B4), or the fold pair \\\"__measure\\\"/\\\"__value\\\" (the renderer unpivots the panel's measure columns into measure-name/measure-value rows — the way to compare several measures as categories in one chart, e.g. an arc of two averages).\",\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"type\": { \"enum\": [\"nominal\", \"quantitative\", \"temporal\", \"ordinal\"] },\n \"sort\": {\n \"anyOf\": [\n { \"enum\": [\"-x\", \"x\", \"-y\", \"y\", \"ascending\", \"descending\"] },\n { \"type\": \"null\" }\n ]\n },\n \"scale\": { \"$ref\": \"#/$defs/colorScale\" },\n \"axis\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"title\": { \"type\": \"string\" },\n \"format\": { \"type\": \"string\" }\n }\n },\n \"format\": { \"type\": \"string\" }\n }\n },\n\n \"encoding\": {\n \"description\": \"Flat, fixed channel set. No layer/concat/facet/repeat (multi-view is the envelope's job via panels[]+layout[]) and no transform/condition/expression/aggregate (anything computed is precomputed by the binding — the ONLY aggregation surface is the binding's measures). The one renderer-side reshape is the __measure/__value fold (a deterministic unpivot of the measure columns, not a computation). This flatness is what removes Vega-Lite's recursion.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"x\": { \"$ref\": \"#/$defs/channel\" },\n \"y\": { \"$ref\": \"#/$defs/channel\" },\n \"color\": { \"$ref\": \"#/$defs/channel\" },\n \"size\": { \"$ref\": \"#/$defs/channel\" },\n \"theta\": { \"$ref\": \"#/$defs/channel\" },\n \"row\": { \"$ref\": \"#/$defs/channel\" },\n \"column\": { \"$ref\": \"#/$defs/channel\" }\n }\n },\n\n \"chartViz\": {\n \"description\": \"The curated, recursion-stripped Vega-Lite subset for chart panels.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"mark\", \"encoding\"],\n \"properties\": {\n \"mark\": { \"enum\": [\"bar\", \"line\", \"area\", \"point\", \"arc\", \"rule\", \"tick\", \"rect\"] },\n \"encoding\": { \"$ref\": \"#/$defs/encoding\" }\n }\n },\n\n \"kpiViz\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"format\"],\n \"properties\": {\n \"format\": { \"type\": \"string\", \"minLength\": 1 },\n \"delta\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"vs\"],\n \"properties\": { \"vs\": { \"enum\": [\"previous_period\", \"prior_year\", \"none\"] } }\n },\n \"spark\": { \"type\": \"boolean\" }\n }\n },\n\n \"gaugeViz\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"format\", \"min\", \"max\"],\n \"properties\": {\n \"format\": { \"type\": \"string\", \"minLength\": 1 },\n \"min\": { \"type\": \"number\" },\n \"max\": { \"type\": \"number\" },\n \"thresholds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"value\", \"role\"],\n \"properties\": {\n \"value\": { \"type\": \"number\" },\n \"role\": { \"enum\": [\"sequential\", \"categorical\", \"diverging\", \"goodBad\"] }\n }\n }\n }\n }\n },\n\n \"tableViz\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"columns\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\"],\n \"properties\": {\n \"field\": { \"type\": \"string\", \"minLength\": 1 },\n \"label\": { \"type\": \"string\" },\n \"format\": { \"type\": \"string\" },\n \"conditional\": { \"type\": \"boolean\" }\n }\n }\n },\n \"sort\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"dir\"],\n \"properties\": {\n \"field\": { \"type\": \"string\", \"minLength\": 1 },\n \"dir\": { \"enum\": [\"asc\", \"desc\"] }\n }\n },\n \"pageSize\": { \"type\": \"integer\", \"minimum\": 1, \"maximum\": 1000 }\n }\n },\n\n \"interaction\": {\n \"description\": \"Cross-filter reservation (interactivity rung 3). Reserved in the schema for forward-compat; the runtime (a click writes a param) is B6, not B1.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"emits\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"param\", \"from\"],\n \"properties\": {\n \"param\": { \"type\": \"string\", \"minLength\": 1 },\n \"from\": { \"enum\": [\"x\", \"y\", \"color\", \"size\", \"theta\", \"row\", \"column\"] }\n }\n }\n }\n }\n },\n\n \"panel\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"id\", \"type\", \"title\", \"viz\"],\n \"properties\": {\n \"id\": { \"type\": \"string\", \"minLength\": 1 },\n \"type\": { \"enum\": [\"kpi\", \"gauge\", \"table\", \"bar\", \"line\", \"area\", \"point\", \"arc\", \"rule\", \"tick\", \"rect\"] },\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"binding\": { \"$ref\": \"#/$defs/binding\" },\n \"compositeBinding\": { \"$ref\": \"#/$defs/compositeBinding\" },\n \"display\": { \"$ref\": \"#/$defs/display\" },\n \"viz\": { \"type\": \"object\" },\n \"interaction\": { \"$ref\": \"#/$defs/interaction\" }\n },\n \"oneOf\": [{ \"required\": [\"binding\"] }, { \"required\": [\"compositeBinding\"] }],\n \"allOf\": [\n {\n \"if\": { \"properties\": { \"type\": { \"const\": \"kpi\" } }, \"required\": [\"type\"] },\n \"then\": { \"properties\": { \"viz\": { \"$ref\": \"#/$defs/kpiViz\" } } }\n },\n {\n \"if\": { \"properties\": { \"type\": { \"const\": \"gauge\" } }, \"required\": [\"type\"] },\n \"then\": { \"properties\": { \"viz\": { \"$ref\": \"#/$defs/gaugeViz\" } } }\n },\n {\n \"if\": { \"properties\": { \"type\": { \"const\": \"table\" } }, \"required\": [\"type\"] },\n \"then\": { \"properties\": { \"viz\": { \"$ref\": \"#/$defs/tableViz\" } } }\n },\n {\n \"if\": {\n \"properties\": { \"type\": { \"enum\": [\"bar\", \"line\", \"area\", \"point\", \"arc\", \"rule\", \"tick\", \"rect\"] } },\n \"required\": [\"type\"]\n },\n \"then\": { \"properties\": { \"viz\": { \"$ref\": \"#/$defs/chartViz\" } } }\n }\n ]\n }\n }\n}\n","// The canonical Dashboard Spec JSON Schema, exposed as an importable object\n// (Visual-Dashboards block B1). The single source of truth is the engine file\n// cloud-agent/internal/chat/dashboardspec/schema/flashback.dashboard.v1.schema.json\n// mirrored into this package as ./schema.json (byte-identical). esbuild inlines\n// this JSON import into the published bundle, so consumers get the schema as a\n// plain object — feed it straight to a JSON-Schema validator (e.g. ajv) for full\n// client-side spec validation, with no asset loading or fetch.\n//\n// Note: validate.ts is the cheap, dependency-free pre-check; DASHBOARD_SCHEMA is\n// here for callers that want full-fidelity validation against the exact engine\n// schema. Both ultimately defer to the engine validator as the safety net.\nimport schemaJson from './schema.json';\n\n/** The flashback.dashboard/v1 JSON Schema (Draft 2020-12). ajv-ready. */\nexport const DASHBOARD_SCHEMA: Readonly<Record<string, unknown>> = schemaJson as Record<string, unknown>;\n"]}
1
+ {"version":3,"sources":["../src/http/HttpError.ts","../src/http/BaseClient.ts","../src/modules/auth/AuthClient.ts","../src/common/envelope.ts","../src/modules/mfa/MfaClient.ts","../src/modules/user/UserClient.ts","../src/modules/organization/OrganizationClient.ts","../src/modules/projects/types.ts","../src/adapters/projectAdapter.ts","../src/modules/projects/ProjectsClient.ts","../src/adapters/sandboxAdapter.ts","../src/modules/sandboxes/SandboxesClient.ts","../src/modules/credentials/types.ts","../src/modules/credentials/AgentTokensClient.ts","../src/modules/credentials/GatewayTokensClient.ts","../src/modules/credentials/TelegramClient.ts","../src/modules/credentials/CredentialsClient.ts","../src/modules/chat/ChatStream.ts","../src/modules/chat/ChatClient.ts","../src/modules/agentEngine/TemplatesClient.ts","../src/modules/agentEngine/ScheduledTasksClient.ts","../src/modules/resources/ResourcesClient.ts","../src/modules/systemEvents/types.ts","../src/modules/systemEvents/SystemEventsClient.ts","../src/modules/billing/SubscriptionsClient.ts","../src/modules/billing/CreditsClient.ts","../src/modules/usage/UsageClient.ts","../src/modules/approvals/ApprovalsClient.ts","../src/modules/budgets/BudgetsClient.ts","../src/modules/metering/MeteringClient.ts","../src/modules/referrals/ReferralsClient.ts","../src/modules/reseller/ResellerClient.ts","../src/modules/platformAdmin/PlatformAdminClient.ts","../src/modules/deployments/DeploymentsClient.ts","../src/modules/capacity/CapacityClient.ts","../src/modules/bi/BIClient.ts","../src/modules/dashboards/DashboardsClient.ts","../src/modules/connections/ConnectionsClient.ts","../src/modules/connect/types.ts","../src/modules/connect/validate.ts","../src/modules/connect/ConnectClient.ts","../src/modules/capabilities/CapabilitiesClient.ts","../src/modules/contacts/ContactsClient.ts","../src/modules/facts/FactsClient.ts","../src/modules/packs/PacksClient.ts","../src/modules/brandAuthority/BrandAuthorityClient.ts","../src/modules/marketingConsent/MarketingConsentClient.ts","../src/modules/meetingMinutes/MeetingMinutesClient.ts","../src/modules/followThrough/FollowThroughClient.ts","../src/modules/crmHandoffs/CrmHandoffsClient.ts","../src/modules/personExport/PersonExportClient.ts","../src/modules/artifacts/ArtifactsClient.ts","../src/modules/signals/SignalsClient.ts","../src/client.ts","../src/common/types.ts","../src/modules/mfa/types.ts","../src/modules/projects/pmCoverage.ts","../src/modules/projects/pmDocuments.ts","../src/modules/projects/pmStatus.ts","../src/modules/credentials/providers.ts","../src/modules/chat/types.ts","../src/modules/chat/cards.ts","../src/modules/capabilities/types.ts","../src/modules/budgets/types.ts","../src/modules/dashboards/types.ts","../src/modules/dashboards/validate.ts","../src/modules/dashboards/schema.json","../src/modules/dashboards/schema.ts"],"names":["normalize","BASE_PATH","scopeHeaders","BASE","ProviderType","AccessType","OrgRoles","MFAType","isRecord","title","summary","status"],"mappings":";AAAO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAMnC,WAAA,CAAY,MAAA,EAAgB,UAAA,EAAoB,IAAA,EAAe;AAC7D,IAAA,MAAM,SAAA,GAAY,iBAAiB,IAAI,CAAA;AACvC,IAAA,MAAM,UAAU,cAAA,CAAe,IAAI,KAAK,CAAA,EAAG,MAAM,IAAI,UAAU,CAAA,CAAA;AAC/D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAClB,IAAA,IAAA,CAAK,SAAA,GAAY,SAAA;AACjB,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEA,SAAS,iBAAiB,IAAA,EAA8B;AACtD,EAAA,IAAI,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACpC,IAAA,MAAM,IAAA,GACH,IAAA,CAAiC,UAAA,IACjC,IAAA,CAAiC,aACjC,IAAA,CAAiC,IAAA;AACpC,IAAA,IAAI,OAAO,IAAA,KAAS,QAAA,EAAU,OAAO,IAAA;AAAA,EACvC;AACA,EAAA,OAAO,IAAA;AACT;AAEA,SAAS,eAAe,IAAA,EAA8B;AACpD,EAAA,IAAI,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACpC,IAAA,MAAM,GAAA,GAAO,IAAA,CAAiC,OAAA,IAAY,IAAA,CAAiC,KAAA;AAC3F,IAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,GAAA;AAAA,EACtC;AACA,EAAA,OAAO,IAA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AAM;AAAA,YACJ,UAAA,EAAc,EAAE,IAAA,EAAQ,EAAE,MAAQ,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,SAAS,KAAA,EAAO,MAAA,EAAQ,MAAA,EAAQ,MAAM,GAAE,EAAE;AAAA,YACpG,QAAA,EAAY,CAAC,MAAM;AAAA,WACrB;AAAA,UACA,IAAA,EAAQ,EAAE,UAAA,EAAc,EAAE,KAAO,EAAE,IAAA,EAAQ,kBAAA,EAAmB,EAAE;AAAE;AACpE;AACF;AACF;AAEJ,CAAA;;;ACpgBO,IAAM,gBAAA,GAAsD","file":"index.js","sourcesContent":["export class HttpError extends Error {\n readonly status: number;\n readonly statusText: string;\n readonly errorCode: string | null;\n readonly body: unknown;\n\n constructor(status: number, statusText: string, body: unknown) {\n const errorCode = extractErrorCode(body);\n const message = extractMessage(body) ?? `${status} ${statusText}`;\n super(message);\n this.name = 'HttpError';\n this.status = status;\n this.statusText = statusText;\n this.errorCode = errorCode;\n this.body = body;\n }\n}\n\nfunction extractErrorCode(body: unknown): string | null {\n if (body && typeof body === 'object') {\n const code =\n (body as Record<string, unknown>).error_code ??\n (body as Record<string, unknown>).errorCode ??\n (body as Record<string, unknown>).code;\n if (typeof code === 'string') return code;\n }\n return null;\n}\n\nfunction extractMessage(body: unknown): string | null {\n if (body && typeof body === 'object') {\n const msg = (body as Record<string, unknown>).message ?? (body as Record<string, unknown>).error;\n if (typeof msg === 'string') return msg;\n }\n return null;\n}\n\nexport class NotImplementedError extends Error {\n constructor(method: string) {\n super(`${method} is not implemented in the cloud-agent backend yet.`);\n this.name = 'NotImplementedError';\n }\n}\n","import { HttpError } from './HttpError.js';\nimport type { TokenProvider, UnauthorizedHandler } from './tokenProvider.js';\n\n/**\n * Returns the org id the platform admin is currently impersonating, or\n * undefined when not impersonating. Resolved per-request so a UI toggle\n * takes effect on the next call without rebuilding the client. Honored\n * by the server only for users in the configured ADMIN_ORGANIZATION;\n * non-admins receive a 403.\n */\nexport type ImpersonationProvider = () => string | undefined | Promise<string | undefined>;\n\nexport interface BaseClientOptions {\n baseUrl: string;\n getToken?: TokenProvider;\n onUnauthorized?: UnauthorizedHandler;\n fetch?: typeof fetch;\n debug?: boolean;\n defaultHeaders?: Record<string, string>;\n getImpersonateOrgId?: ImpersonationProvider;\n /**\n * fetch credentials mode. Defaults to 'include' so the shared-domain\n * `fb_session` cookie is stored on login and sent to /session/bootstrap —\n * including in dev, where the SPA origin (app.localtest.me:3001) and the\n * API (api.localtest.me:3000) are same-site but cross-origin. Server-side\n * (Node) fetch ignores it. Requires the API's CORS to allow credentials\n * for the exact origin (it does).\n */\n credentials?: RequestCredentials;\n}\n\nexport type QueryValue = string | number | boolean | string[] | null | undefined;\nexport type Query = Record<string, QueryValue>;\n\nexport interface RequestOptions {\n /**\n * Query string params. Plain object; we serialize string/number/boolean,\n * repeat arrays, and drop undefined/null values.\n */\n query?: object;\n body?: unknown;\n headers?: Record<string, string>;\n /** Skip the bearer token (used for public endpoints like /user/login). */\n skipAuth?: boolean;\n}\n\nexport class BaseClient {\n readonly baseUrl: string;\n private readonly getToken?: TokenProvider;\n private readonly onUnauthorized?: UnauthorizedHandler;\n private readonly fetchImpl: typeof fetch;\n private readonly debug: boolean;\n private readonly defaultHeaders: Record<string, string>;\n private readonly getImpersonateOrgId?: ImpersonationProvider;\n private readonly credentials: RequestCredentials;\n\n constructor(options: BaseClientOptions) {\n if (!options.baseUrl) throw new Error('CloudAgentClient: baseUrl is required');\n this.baseUrl = options.baseUrl.replace(/\\/$/, '');\n this.getToken = options.getToken;\n this.onUnauthorized = options.onUnauthorized;\n this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.debug = options.debug ?? false;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.getImpersonateOrgId = options.getImpersonateOrgId;\n this.credentials = options.credentials ?? 'include';\n }\n\n get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, options);\n }\n post<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, options);\n }\n put<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('PUT', path, options);\n }\n patch<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('PATCH', path, options);\n }\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n async request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n // Internal: set on the single post-refresh retry so a persistent 401\n // can't loop. Not part of the public surface.\n retrying = false,\n ): Promise<T> {\n const url = this.buildUrl(path, options.query);\n const headers: Record<string, string> = { ...this.defaultHeaders, ...(options.headers ?? {}) };\n\n if (!options.skipAuth && this.getToken) {\n const token = await this.getToken();\n if (token) headers['Authorization'] = `Bearer ${token}`;\n }\n\n // Impersonation header is opt-in via the constructor callback. The\n // explicit per-request `headers` win — call sites that already supply\n // an X-Impersonate-Org-Id (tests, edge cases) keep precedence.\n if (\n !options.skipAuth &&\n this.getImpersonateOrgId &&\n !('X-Impersonate-Org-Id' in headers) &&\n !('x-impersonate-org-id' in headers)\n ) {\n const target = await this.getImpersonateOrgId();\n if (target) headers['X-Impersonate-Org-Id'] = target;\n }\n\n let body: BodyInit | undefined;\n if (options.body !== undefined && options.body !== null) {\n if (options.body instanceof FormData) {\n body = options.body;\n } else {\n if (!('Content-Type' in headers) && !('content-type' in headers)) {\n headers['Content-Type'] = 'application/json';\n }\n body = JSON.stringify(options.body);\n }\n }\n\n if (this.debug) {\n // eslint-disable-next-line no-console\n console.debug('[clowdops/tsclient] →', method, url, options.body ?? '');\n }\n\n const res = await this.fetchImpl(url, { method, headers, body, credentials: this.credentials });\n\n let parsed: unknown = null;\n const text = await res.text();\n if (text.length > 0) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = text;\n }\n }\n\n if (this.debug) {\n // eslint-disable-next-line no-console\n console.debug('[clowdops/tsclient] ←', res.status, url, parsed);\n }\n\n if (!res.ok) {\n // On a 401 for an authed request, give the handler a chance to refresh\n // the access token, then retry the original request exactly once with\n // the new token. `retrying` guards against an infinite loop when the\n // refreshed token still 401s; `skipAuth` requests (login etc.) carry no\n // token to refresh, so a 401 there is a real failure, not staleness.\n if (res.status === 401 && this.onUnauthorized && !options.skipAuth && !retrying) {\n let refreshed = false;\n try {\n // void return ⇒ assume retry is worthwhile (legacy handlers);\n // explicit false ⇒ refresh failed, surface the original 401.\n refreshed = (await this.onUnauthorized()) !== false;\n } catch {\n // swallow handler failures — the original 401 is still surfaced\n }\n if (refreshed) {\n return this.request<T>(method, path, options, true);\n }\n }\n throw new HttpError(res.status, res.statusText, parsed);\n }\n\n return parsed as T;\n }\n\n private buildUrl(path: string, query?: object): string {\n const base = path.startsWith('http') ? path : `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n if (!query) return base;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query as Record<string, unknown>)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const v of value) params.append(key, String(v));\n } else {\n params.set(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `${base}?${qs}` : base;\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n ActivateRequest,\n ExchangeCodeRequest,\n ExchangeOIDCRequest,\n LoginRequest,\n PublicConfig,\n RefreshRequest,\n RegisterRequest,\n ResetPasswordRequest,\n SessionResponse,\n SimpleResponse,\n} from './types.js';\n\nexport class AuthClient {\n constructor(private readonly http: BaseClient) {}\n\n login(body: LoginRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/user/login', { body, skipAuth: true });\n }\n\n register(body: RegisterRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/user/register', { body, skipAuth: true });\n }\n\n /**\n * Unauthenticated boot config. The SPA reads `openRegistration` to decide\n * whether to render the self-service signup form (false => invite-only /\n * preview mode). Safe to call before any session exists.\n */\n publicConfig(): Promise<PublicConfig> {\n return this.http.get<PublicConfig>('/public-config', { skipAuth: true });\n }\n\n logout(refreshToken?: string): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>('/user/logout', {\n body: { refreshToken },\n });\n }\n\n refresh(body: RefreshRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/user/refresh', { body, skipAuth: true });\n }\n\n activate(body: ActivateRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/user/activate', { body, skipAuth: true });\n }\n\n requestVerification(email: string): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>('/user/request-verification', {\n body: { email },\n skipAuth: true,\n });\n }\n\n requestPasswordReset(email: string): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>('/user/request-reset-password', {\n body: { email },\n skipAuth: true,\n });\n }\n\n resetPassword(body: ResetPasswordRequest): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>('/user/reset-password', { body, skipAuth: true });\n }\n\n exchangeGoogle(body: ExchangeCodeRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/auth/google/exchange', { body, skipAuth: true });\n }\n\n /** Generic OIDC code exchange (unified-auth plan, Issue 3). */\n exchangeOIDC(body: ExchangeOIDCRequest): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/auth/oidc/exchange', { body, skipAuth: true });\n }\n\n /**\n * Mint a fresh access token from the shared-domain `fb_session` cookie\n * (unified-auth plan, Issue 1). The cookie is the credential — no body, no\n * bearer; the custom header is CSRF defense-in-depth (CORS-allow-listed).\n * 401 error_code values: no_session_cookie | invalid_session |\n * session_revoked. Never returns a refresh token (cookie-only refresh).\n */\n sessionBootstrap(): Promise<SessionResponse> {\n return this.http.post<SessionResponse>('/session/bootstrap', {\n skipAuth: true,\n headers: { 'X-Session-Bootstrap': '1' },\n });\n }\n}\n","/**\n * Most cloud-agent endpoints return `{ success: true, data: T }` or\n * `{ success: true, <key>: T }`. A few (system events, exchange) return\n * bare shapes. These helpers keep envelope handling out of the per-domain\n * clients.\n */\n\nexport interface SuccessEnvelope<T> {\n success: boolean;\n data?: T;\n message?: string;\n error_code?: string;\n}\n\nexport function unwrapData<T>(payload: { success?: boolean; data?: T } | undefined | null): T {\n if (!payload || payload.data === undefined) {\n throw new Error('Response envelope missing `data` field.');\n }\n return payload.data;\n}\n\nexport function unwrapKey<T>(payload: Record<string, unknown> | undefined | null, key: string): T {\n if (!payload || payload[key] === undefined) {\n throw new Error(`Response envelope missing \\`${key}\\` field.`);\n }\n return payload[key] as T;\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n MagicLinkActivateRequest,\n MagicLinkSendResponse,\n MFASetupResponse,\n MFASimpleResponse,\n MFAStatus,\n MFAType,\n MFAVerifyLoginRequest,\n MFAVerifyLoginResponse,\n MFAVerifySetupRequest,\n} from './types.js';\n\nexport class MfaClient {\n constructor(private readonly http: BaseClient) {}\n\n async getStatus(): Promise<MFAStatus> {\n const res = await this.http.get<{ success: boolean; data: MFAStatus }>('/mfa/status');\n return unwrapData(res);\n }\n\n async getMethods(): Promise<MFAType[]> {\n const res = await this.http.get<{ success: boolean; data: { methods: MFAType[] } }>('/mfa/methods');\n return res.data?.methods ?? [];\n }\n\n setup(body: { mfaType: MFAType; email?: string }): Promise<MFASetupResponse> {\n return this.http.post<MFASetupResponse>('/mfa/setup', { body });\n }\n\n verifySetup(body: MFAVerifySetupRequest): Promise<MFASimpleResponse> {\n return this.http.post<MFASimpleResponse>('/mfa/verify-setup', { body });\n }\n\n enable(mfaType: MFAType): Promise<MFASimpleResponse> {\n return this.http.post<MFASimpleResponse>('/mfa/enable', { body: { mfaType } });\n }\n\n disable(mfaType: MFAType): Promise<MFASimpleResponse> {\n return this.http.post<MFASimpleResponse>('/mfa/disable', { body: { mfaType } });\n }\n\n setPrimary(mfaType: MFAType): Promise<MFASimpleResponse> {\n return this.http.post<MFASimpleResponse>('/mfa/primary', { body: { mfaType } });\n }\n\n sendMagicLink(): Promise<MagicLinkSendResponse> {\n return this.http.post<MagicLinkSendResponse>('/mfa/magic-link/send', {});\n }\n\n activateMagicLink(body: MagicLinkActivateRequest): Promise<MFAVerifyLoginResponse> {\n return this.http.post<MFAVerifyLoginResponse>('/mfa/magic-link/activate', { body, skipAuth: true });\n }\n\n verifyLogin(body: MFAVerifyLoginRequest): Promise<MFAVerifyLoginResponse> {\n return this.http.post<MFAVerifyLoginResponse>('/mfa/verify-login', { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type { UpdateUserRequest, UpdateUserResponse, UserProfile } from './types.js';\n\nexport class UserClient {\n constructor(private readonly http: BaseClient) {}\n\n async getProfile(): Promise<UserProfile> {\n const res = await this.http.get<{ success: boolean; data: UserProfile }>('/me');\n return unwrapData(res);\n }\n\n update(body: UpdateUserRequest): Promise<UpdateUserResponse> {\n return this.http.put<UpdateUserResponse>('/user', { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type { ProductKind } from '../projects/types.js';\nimport type {\n AcceptInviteRequest,\n AddUserToOrgRequest,\n AddUserToOrgResult,\n AdjustOrgCreditsRequest,\n AdjustOrgCreditsResult,\n AdminOrgSummaryQuery,\n AdminOrgSummaryResponse,\n CreateOrganizationRequest,\n CreateOrganizationUserRequest,\n InviteOrgRequest,\n InviteOrgResult,\n OrgCreditBalance,\n OrgInvite,\n OrgNotifySubscriptions,\n OrgSearchResult,\n Organization,\n OrganizationUser,\n SetOrgNotifySubscriptionsRequest,\n SimpleOrgResponse,\n UpdateOrganizationRequest,\n UpdateOrgUserRequest,\n} from './types.js';\n\nexport class OrganizationClient {\n constructor(private readonly http: BaseClient) {}\n\n async get(orgId: string): Promise<Organization> {\n const res = await this.http.get<{ success: boolean; data: Organization }>(`/organization/${orgId}`);\n return unwrapData(res);\n }\n\n async update(orgId: string, body: UpdateOrganizationRequest): Promise<Organization> {\n const res = await this.http.put<{ success: boolean; data: Organization }>(`/organization/${orgId}`, { body });\n return unwrapData(res);\n }\n\n /**\n * Self-service: create an org for the current (orgless) user and assign them\n * as Owner. Used by the onboarding wizard so the org exists before the limits\n * and project/sandbox steps. Fails if the user already belongs to an org.\n */\n async create(body: CreateOrganizationRequest): Promise<Organization> {\n const res = await this.http.post<{ success: boolean; data: Organization }>('/organization', { body });\n return unwrapData(res);\n }\n\n /**\n * Fetch the org's default-notification-channel config: the per-event\n * subscriptions, the notify channels available to route to, and whether the\n * caller's org is the platform-admin org (which unlocks the cross-org\n * `engine_failure` / `infra_outage` event types).\n */\n async getNotifySubscriptions(): Promise<OrgNotifySubscriptions> {\n const res = await this.http.get<{ success: boolean; data: OrgNotifySubscriptions }>(\n '/organization/notify-subscriptions',\n );\n return unwrapData(res);\n }\n\n /**\n * Replace the org's notify subscriptions (replace-set). Each edge is\n * validated server-side: the credential must be a notify channel in the org,\n * and admin-only event types require a platform-admin caller.\n */\n setNotifySubscriptions(body: SetOrgNotifySubscriptionsRequest): Promise<SimpleOrgResponse> {\n return this.http.put<SimpleOrgResponse>('/organization/notify-subscriptions', { body });\n }\n\n async listUsers(): Promise<OrganizationUser[]> {\n const res = await this.http.get<{ success: boolean; data: OrganizationUser[] }>('/organization/users');\n return res.data ?? [];\n }\n\n updateUser(userId: string, body: UpdateOrgUserRequest): Promise<SimpleOrgResponse> {\n return this.http.put<SimpleOrgResponse>(`/organization/users/${userId}`, { body });\n }\n\n /** Backend currently returns 501. Surfaced for forward-compat. */\n createUser(body: CreateOrganizationUserRequest): Promise<SimpleOrgResponse> {\n return this.http.post<SimpleOrgResponse>('/organization/users', { body });\n }\n\n /** Backend currently returns 501. Surfaced for forward-compat. */\n deleteUser(userId: string): Promise<SimpleOrgResponse> {\n return this.http.delete<SimpleOrgResponse>(`/organization/users/${userId}`);\n }\n\n /** Accept an org invite: verifies the one-time token and sets the user's password. */\n acceptInvite(body: AcceptInviteRequest): Promise<SimpleOrgResponse> {\n return this.http.post<SimpleOrgResponse>('/organization/invite/accept', { body });\n }\n\n /**\n * Platform-admin only: list every org for the impersonation picker.\n * The server returns 403 when the caller's home org is not the\n * configured ADMIN_ORGANIZATION; render the picker only when the\n * authenticated user has `isPlatformAdmin === true`.\n */\n async listAll(): Promise<Array<{ id: string; name: string; allowDebug: boolean }>> {\n const res = await this.http.get<{\n success: boolean;\n data: Array<{ id: string; name: string; allowDebug: boolean }>;\n }>('/orgs/list-all');\n return res.data ?? [];\n }\n\n /**\n * Platform-admin only: typeahead org search. Returns up to `limit` matches\n * (id+name) for the case-insensitive name substring `q` (or the first\n * `limit` orgs when `q` is empty) plus the total match count, so a picker\n * can show \"N more — refine your search\". Returns 403 unless platform admin.\n */\n async searchOrgs(q = '', limit = 10): Promise<OrgSearchResult> {\n const res = await this.http.get<{ success: boolean; data: OrgSearchResult }>('/orgs/search', {\n query: { q, limit },\n });\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: one page of the service-wide org summary — per-org\n * user/project/sandbox counts, trailing 7d/30d metered usage, billed-to-\n * balance, lifetime purchases and current credit balance — searchable by\n * name and pageable. Backs the admin Summary screen. Returns 403 unless the\n * caller's home org is the configured ADMIN_ORGANIZATION.\n */\n async adminOrgSummary(query: AdminOrgSummaryQuery = {}): Promise<AdminOrgSummaryResponse> {\n const res = await this.http.get<{ success: boolean; data: AdminOrgSummaryResponse }>(\n '/admin/orgs/summary',\n { query: query as Record<string, unknown> },\n );\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: provision a new organization + founding owner and\n * email the owner an invite link. The invite-only counterpart to public\n * self-service registration (used while the backend has OPEN_REGISTRATION\n * disabled). Returns 403 unless the caller's home org is the configured\n * ADMIN_ORGANIZATION; 409 when the owner email already exists.\n */\n async inviteOrg(body: InviteOrgRequest): Promise<InviteOrgResult> {\n const res = await this.http.post<{ success: boolean; data: InviteOrgResult }>(\n '/organization/invite-org',\n { body },\n );\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: list every outstanding org + member invite (founding-\n * owner invites from `inviteOrg` and members added via `addUserToOrg`) with\n * derived status, newest first. Cancelled invites (soft-deleted) and live\n * non-invited orgs are excluded. Returns 403 unless platform admin.\n */\n async listOrgInvites(): Promise<OrgInvite[]> {\n const res = await this.http.get<{ success: boolean; data: OrgInvite[] }>('/admin/org-invites');\n return res.data ?? [];\n }\n\n /**\n * Platform-admin only: re-send an invite — mints a fresh 7-day token and\n * re-emails the link. Returns 403 unless platform admin; 404 when no pending\n * invite exists; 409 once the invite has been redeemed.\n */\n resendOrgInvite(userId: string): Promise<SimpleOrgResponse> {\n return this.http.post<SimpleOrgResponse>(`/admin/org-invites/${userId}/resend`, {});\n }\n\n /**\n * Platform-admin only: cancel a pending invite. Soft-deletes the invited user\n * (and the shell org, for a never-redeemed founding-owner invite with no other\n * members) and revokes the token, freeing the email for re-invite. Returns 403\n * unless platform admin; 404 when absent; 409 once the invite has been redeemed.\n */\n cancelOrgInvite(userId: string): Promise<SimpleOrgResponse> {\n return this.http.post<SimpleOrgResponse>(`/admin/org-invites/${userId}/cancel`, {});\n }\n\n /**\n * Platform-admin only: enable or disable the debug surface for an org.\n * Returns the updated org entry with the new allowDebug value.\n */\n async setAllowDebug(orgId: string, allow: boolean): Promise<{ id: string; name: string; allowDebug: boolean }> {\n const res = await this.http.patch<{\n success: boolean;\n data: { id: string; name: string; allowDebug: boolean };\n }>(`/orgs/${orgId}/allow-debug`, { body: { allow } });\n return res.data!;\n }\n\n /**\n * Platform-admin only: replace an org's product entitlement. `products` is\n * the full desired set ('cloud' | 'bi'); unknown codes are rejected 400.\n * Returns the updated org's id, name and enabledProducts.\n */\n async setEnabledProducts(\n orgId: string,\n products: ProductKind[],\n ): Promise<{ id: string; name: string; enabledProducts: ProductKind[] }> {\n const res = await this.http.patch<{\n success: boolean;\n data: { id: string; name: string; enabledProducts: ProductKind[] };\n }>(`/orgs/${orgId}/enabled-products`, { body: { products } });\n return res.data!;\n }\n\n /**\n * Platform-admin only: add a new member to an existing org.\n * Creates the user without a password and sends an invite email via the\n * same TokenOrgInvite flow as the regular member invite.\n * Returns 403 unless platform admin; 409 when the email already exists.\n */\n async addUserToOrg(orgId: string, body: AddUserToOrgRequest): Promise<AddUserToOrgResult> {\n const res = await this.http.post<{ success: boolean; data: AddUserToOrgResult }>(\n `/orgs/${orgId}/users`,\n { body },\n );\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: fetch an org's two-bucket credit balance.\n * Returns 403 unless platform admin; 404 when the org doesn't exist.\n */\n async getOrgCreditBalance(orgId: string): Promise<OrgCreditBalance> {\n const res = await this.http.get<{ success: boolean; data: OrgCreditBalance }>(\n `/orgs/${orgId}/credits`,\n );\n return unwrapData(res);\n }\n\n /**\n * Platform-admin only: grant or revoke credits on an org.\n * amountMicros is signed: positive = grant, negative = revoke.\n * Records a CreditKindAdminAdjust ledger entry and returns the updated balance.\n */\n async adjustOrgCredits(orgId: string, body: AdjustOrgCreditsRequest): Promise<AdjustOrgCreditsResult> {\n const res = await this.http.post<{ success: boolean; data: AdjustOrgCreditsResult }>(\n `/orgs/${orgId}/credits/adjust`,\n { body },\n );\n return unwrapData(res);\n }\n}\n","import type { AccessType, UserSummary } from '../../common/types.js';\nimport type { FactProposal } from '../facts/types.js';\n\nexport interface ProjectMember {\n userId: string;\n role: string;\n user: UserSummary;\n}\n\n/** AI providers eligible for the per-project platform-keys opt-in. */\nexport type PreferredAiProvider = 'OPENAI' | 'ANTHROPIC' | 'GEMINI' | 'BEDROCK';\n\nexport interface Project {\n id: string;\n name: string;\n orgId: string;\n default: boolean;\n /**\n * Marks the admin org's global-AI-key project (its AI credentials form the\n * platform-wide pool). Meaningful only for the platform-admin org.\n */\n isReferenceProject?: boolean;\n /**\n * When set on a project with no BYOK AI credentials, routes that project's\n * LLM calls to the platform (\"global\") keys for this provider. Mutually\n * exclusive with BYOK AI keys. Null/absent = BYOK.\n */\n preferredAiProvider?: PreferredAiProvider | null;\n /**\n * Product partition the project belongs to — 'cloud' (cloud-ops, the\n * default), 'bi' (Talk-to-Your-BI), 'meeting' (ClowdMeeting), 'marketing'\n * (ClowdMarketing), 'pm' (ClowdPM) or 'startup' (ClowdStartup). Each frontend\n * lists only its own product's projects. A UX partition, not a security\n * boundary.\n */\n product?: ProductKind;\n users: ProjectMember[];\n}\n\n/**\n * The product verticals a project can belong to.\n *\n * Mirrors the backend's closed `products.Product` enum and its migration CHECK\n * constraints (0065 for the first four, 0110 for `'pm'`, 0127 for `'startup'`).\n * Adding a member here without adding it there means the server rejects a value\n * this client says is valid. `'pm'` is ClowdPM (PJM-D1); its project, memory and\n * document surfaces use the same product partition without treating it as an\n * authority grant. `'startup'` is ClowdStartup, the Bueeld server-to-server\n * integration: its projects are provisioned by the backend, never from a\n * browser, so it is a grant an admin can give an org rather than a workspace a\n * console creates.\n */\nexport const PRODUCT_KINDS = ['cloud', 'bi', 'meeting', 'marketing', 'pm', 'startup'] as const;\n\nexport type ProductKind = (typeof PRODUCT_KINDS)[number];\n\n/**\n * Runtime guard for product values received over JSON.\n *\n * A TypeScript union disappears at runtime, so casting an arbitrary server\n * string to ProductKind would make an unsupported/newer product look supported\n * to downstream switches. Keep the runtime vocabulary beside the wire type so\n * adapters can fail closed instead.\n */\nexport function isProductKind(value: unknown): value is ProductKind {\n return typeof value === 'string' && (PRODUCT_KINDS as readonly string[]).includes(value);\n}\n\ninterface CreateProjectRequestBase {\n name: string;\n}\n\n/**\n * Project creation request. ClowdPM creation deliberately requires a caller-\n * stable request key: if the response is lost, a key minted only by the server\n * cannot be recovered and a retry could create a second project. Other products\n * retain their rolling-compatible keyless request shape.\n */\nexport type CreateProjectRequest =\n | (CreateProjectRequestBase & {\n product: 'pm';\n /**\n * Caller-supplied idempotency handle for durable ClowdPM creation. It\n * identifies the REQUEST, not the project. Mint it once with\n * {@link newProjectRequestKey}, persist it for the attempt-chain, and\n * resend the same value on every retry.\n */\n requestKey: string;\n })\n | (CreateProjectRequestBase & {\n /** Defaults to 'cloud' server-side when omitted. */\n product?: Exclude<ProductKind, 'pm'>;\n /** Idempotency is currently defined only for ClowdPM creation. */\n requestKey?: never;\n });\n\n/**\n * Mint a fresh idempotency handle for {@link CreateProjectRequest.requestKey}.\n *\n * This is a REQUEST handle, not an identity: it lets a retried ClowdPM creation\n * converge on the same server-minted project. Generate it once when the user\n * initiates creation and reuse the same value across retries; never regenerate\n * it per attempt. Uses WebCrypto's `randomUUID` where available (browsers and\n * Node ≥ 16.7), with a non-cryptographic fallback that is still adequately\n * unique for an idempotency key.\n */\nexport function newProjectRequestKey(): string {\n const webcrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (typeof webcrypto?.randomUUID === 'function') return webcrypto.randomUUID();\n return `req-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n}\n\nexport interface UpdateProjectRequest {\n name?: string;\n isReferenceProject?: boolean;\n /** Empty string clears the platform-keys opt-in (back to BYOK). */\n preferredAiProvider?: PreferredAiProvider | '' | null;\n}\n\nexport interface AddMemberRequest {\n userId: string;\n role: AccessType | string;\n}\n\nexport interface UpdateMemberRoleRequest {\n role: AccessType | string;\n}\n\n/**\n * ClowdPM (`pm`) project membership role vocabulary (PJM-IP01 §2.3). It is a\n * DISTINCT vocabulary from the legacy `AccessType` (READ|WRITE|ADMIN): a pm\n * project's roster is `manager | member | reader`, derived server-side and\n * mapped to the authorization decision table by the backend. The legacy\n * `addMember`/`removeMember` routes are refused for a pm project — governed\n * membership goes through `grantPMMember`/`revokePMMember` below.\n */\nexport type PmRole = 'manager' | 'member' | 'reader';\n\n/**\n * Grant a principal a ClowdPM project role. This is the governed\n * `pm.membership.change` act (manager-directed = proposal and approval in one\n * recorded step). It is value-idempotent and read-back verified server-side; the\n * caller who is not an active project MANAGER — including a non-member\n * organization administrator — is refused. The client asserts no authority.\n */\nexport interface PmGrantMemberRequest {\n userId: string;\n role: PmRole;\n}\n\nexport interface PmGrantMemberResponse {\n success: boolean;\n granted: boolean;\n role: PmRole;\n}\n\n/**\n * Revoke a principal's ClowdPM project membership. A revoke of an already-revoked\n * or never-granted principal is a recorded no-op: `revoked` is then `false`, and\n * that is a success, not an error.\n */\nexport interface PmRevokeMemberResponse {\n success: boolean;\n revoked: boolean;\n}\n\n/**\n * Last-manager recovery (PJM-IP01 §2.4 / `pm.recover-management`): the narrow,\n * audited path where an organization administrator appoints a NAMED replacement\n * manager for a project that has NO active manager. It grants the invoking\n * administrator no ordinary project read.\n */\nexport interface PmRecoverManagementRequest {\n replacementUserId: string;\n reason: string;\n}\n\nexport interface PmRecoverManagementResponse {\n success: boolean;\n recovered: boolean;\n replacementUserId: string;\n}\n\n/**\n * ClowdPM project-memory record families (PJM-IP02, context model §2). The\n * thirteen families seeded by migration 0113. This is the set this client knows\n * how to suggest, not a closed wire enum: a later backend migration may add a\n * family to `pm_record_family`, and older clients must still round-trip it.\n */\nexport const PM_RECORD_FAMILIES = [\n 'tailoring',\n 'phase_gate',\n 'baseline',\n 'deliverable',\n 'wbs_node',\n 'activity',\n 'decision',\n 'action',\n 'risk',\n 'stakeholder',\n 'issue',\n 'assumption',\n 'communication',\n] as const;\n\nexport type PmKnownRecordFamily = (typeof PM_RECORD_FAMILIES)[number];\nexport type PmRecordFamily = string;\n\n/** Runtime wire guard. Support is server-catalogued; non-blank newer families are valid. */\nexport function isPmRecordFamily(value: unknown): value is PmRecordFamily {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\n/**\n * Provenance origin of a revision's value. A `human` value is authoritative and\n * carries NO confidence hedge; an `extracted` value is visibly `provisional` and\n * — by backend schema CHECK, not convention — can never reach accepted ownership\n * until a human confirms it.\n */\nexport type PmOrigin = 'human' | 'extracted';\n\n/**\n * Accountable-owner state. Ownership beyond `unassigned` requires a named person\n * (`accountableContactId`). An `extracted` value may be `proposed` but never\n * `accepted` — the consequence an owned commitment rests on.\n */\nexport type PmAccountableState = 'unassigned' | 'proposed' | 'accepted' | 'declined';\n\n/** Shallow work state for work-bearing families (no schedule/dependency algebra). */\nexport type PmWorkState = 'todo' | 'in_progress' | 'blocked' | 'done' | 'cancelled';\n\n/**\n * Derived, read-only readiness of a record's current revision. The backend\n * computes it for the `risk` family only (`ready` requires a human value, an\n * `accepted` accountable state AND a named person); every other family is `n/a`.\n * Never stored, never client-asserted — a risk with no named accountable owner is\n * retained `incomplete`, never ready.\n */\nexport type PmReadiness = 'ready' | 'incomplete' | 'n/a';\n\n/**\n * One append-only revision in the shared record envelope (PJM-IP02). Human values\n * are authoritative; extracted values are visibly `provisional`. The envelope is\n * never overwritten — a correction supersedes, and the prior revision is retained.\n */\nexport interface PmRevision {\n id: string;\n recordId: string;\n revision: number;\n /** Family-specific detail; opaque JSON to the client. */\n payload: unknown;\n origin: PmOrigin;\n confidence?: number | null;\n asOf?: string | null;\n accountableContactId?: string | null;\n /** Registry status; a non-active owner never counts as viable/ready. */\n accountableContactStatus?: 'active' | 'merged' | 'erased' | null;\n accountableState: PmAccountableState;\n workState?: PmWorkState | null;\n dueAt?: string | null;\n note?: string | null;\n /** Server-derived authoring principal; never a client field. */\n authoredBy: string;\n authoredAt: string;\n supersedesRevisionId?: string | null;\n /** Null/absent means this revision is the current one. */\n supersededByRevisionId?: string | null;\n // Derived, never stored (server-computed, read-only).\n family: PmRecordFamily;\n provisional: boolean;\n readiness: PmReadiness;\n}\n\n/** A logical project-memory record with its current revision resolved. */\nexport interface PmRecord {\n id: string;\n projectId: string;\n family: PmRecordFamily;\n /** Catalog policy; optional only for rolling compatibility with an older server. */\n requiresAccountableOwner?: boolean;\n /** Catalog policy; future subject-bearing families do not need a client enum change. */\n requiresSubjectContact?: boolean;\n /** Canonical registry identity for subject-bearing records (not copied PII). */\n subjectContactId?: string | null;\n subjectContactStatus?: 'active' | 'merged' | 'erased' | null;\n createdBy: string;\n createdAt: string;\n /** The current (non-superseded) revision. Present by construction. */\n current?: PmRevision;\n}\n\n/**\n * The write envelope for a new revision — the `first` revision of a created\n * record, or an appended/superseding one. `authoredBy`, `authoredAt` and\n * `revision` are SERVER-derived and must not be sent. This user-facing client\n * reaches the direct member route, so provenance is always human and derived by\n * the server. Extracted proposals require a separate governed internal surface.\n */\nexport interface PmRevisionInput {\n /** Direct member writes are server-derived human provenance. */\n origin?: 'human';\n /** Family-specific detail; defaults to `{}` server-side when omitted. */\n payload?: unknown;\n asOf?: string;\n accountableContactId?: string;\n accountableState?: PmAccountableState;\n workState?: PmWorkState;\n dueAt?: string;\n note?: string;\n}\n\n/** Create a record with its first revision in one POST (record-and-first-revision). */\nexport interface PmCreateRecordRequest {\n family: PmRecordFamily;\n /** Required by the backend for stakeholder records. */\n subjectContactId?: string;\n first: PmRevisionInput;\n}\n\n/**\n * Append/supersede the current revision. `expectedCurrentRevisionId` is the\n * required optimistic-concurrency handle: pass the revision id you read, and a\n * concurrent write is refused with a 409 carrying the new current revision (see\n * {@link PmRevisionConflict}) rather than silently overwriting. There is no\n * unconditional supersede path.\n */\nexport type PmAppendRevisionRequest = PmRevisionInput & {\n expectedCurrentRevisionId: string;\n};\n\n/** A scoped view of an existing shared fact proposal; scope is a server assertion. */\nexport interface PmRecordProposal {\n proposal: FactProposal;\n /** Opaque immutable proposal version. Read again before a human decision. */\n expectedVersion: string;\n projectId: string;\n repoId: string;\n conversationId: string;\n /** Present only after successful application to ordinary PM memory. */\n record?: PmRecord;\n /** Current server authority for the named owner of an applied risk proposal. */\n canDecideOwnership?: boolean;\n}\n\nexport interface PmRecordProposalDecision {\n expectedVersion: string;\n decision: 'confirmed' | 'rejected';\n}\n\n/** `{ success, record }` envelope for create/get/append. */\nexport interface PmRecordResponse {\n success: boolean;\n record: PmRecord;\n}\n\n/** `{ success, records }` envelope for list. `records` is `null` when empty. */\nexport interface PmRecordsResponse {\n success: boolean;\n records: PmRecord[] | null;\n}\n\n/** `{ success, revisions }` envelope for history. `revisions` is `null` when empty. */\nexport interface PmRevisionsResponse {\n success: boolean;\n revisions: PmRevision[] | null;\n}\n\n/**\n * The 409 body an append returns when `expectedCurrentRevisionId` is stale. It\n * carries the CURRENT revision so the caller can reconcile and retry — nothing\n * was written. On the wire this arrives as the thrown `HttpError.body`.\n */\nexport interface PmRevisionConflict {\n success: false;\n message: string;\n current: PmRevision;\n}\n\n// ── Customer documents (PJM-IP03 / IMP-PJ-DOC-CORE) ──────────────────────────\n//\n// Documents enter the project as immutable artifact-substrate versions of kind\n// `pm.customer-document`, carrying provenance (uploader, uploaded-at, declared\n// source), an authority-to-share attestation, and a governed deletion\n// disposition. The BYTES are the substrate's job — stored ENCRYPTED for a\n// confidential/restricted class and REFUSED (never plaintext) when the\n// deployment's encryption posture is unavailable (A-11); this client wraps only\n// the member-scoped metadata surface. Deletion is a GOVERNED disposition, not a\n// request-triggered act: there is deliberately NO delete / execute method here,\n// because execution is non-expressible until the shared governed-disposition\n// contract (F-PJM-047) lands.\n\n/** Derived authority-to-share state of a document. Never a mutable flag. */\nexport type PmAttestationState = 'attested' | 'missing';\n\n/** Attestation lifecycle event types (append-only, ask-once, attest-once). */\nexport type PmAttestationEventType = 'gap' | 'ask' | 'attest';\n\n/** One append-only authority-to-share lifecycle event. */\nexport interface PmDocumentAttestationEvent {\n id: string;\n eventType: PmAttestationEventType;\n note?: string | null;\n authoredBy: string;\n authoredAt: string;\n}\n\n/**\n * A customer document's product-owned metadata. `attestationState` is DERIVED\n * (`attested` iff an attest event exists), never a settable field. `headVersionId`\n * is the exact, citable artifact version — grounding pins a claim to it.\n */\nexport interface PmCustomerDocument {\n id: string;\n projectId: string;\n orgId: string;\n artifactId: string;\n /** The exact current artifact version id — the citable version for grounding. */\n headVersionId: string;\n /** Lowercase SHA-256 of the immutable version's canonical plaintext bytes. */\n contentHash: string;\n classification: string;\n declaredSource?: string | null;\n title: string;\n uploadedBy: string;\n uploadedAt: string;\n createdAt: string;\n attestationState: PmAttestationState;\n /** Whether the single ask has already been recorded (ask-once). */\n askRecorded: boolean;\n attestation: PmDocumentAttestationEvent[];\n}\n\n/**\n * Upload request. `classification` is DECLARED — the substrate never defaults\n * one, and a confidential/restricted class routes through encrypted-or-refused\n * storage. `attested: true` records the intake attestation now; `false` (the\n * default) records the intake gap, asked exactly once later and never nagged.\n */\nexport interface PmDocumentUploadRequest {\n title: string;\n classification: string;\n /** Defaults to text server-side when omitted. */\n contentType?: string;\n content: string;\n declaredSource?: string;\n attested?: boolean;\n attestNote?: string;\n}\n\n/**\n * The upload result. `document` is the recorded metadata; `handle`/`version` are\n * the substrate's citable version handle. A confidential upload on a deployment\n * with no encryption posture does NOT reach here — it fails closed as a thrown\n * `HttpError` (422) whose body carries the substrate refusal, and no document is\n * recorded (nothing stored, nothing downgraded).\n */\nexport interface PmDocumentUploadResult {\n success: boolean;\n document: PmCustomerDocument;\n handle?: unknown;\n version?: unknown;\n}\n\n/** `{ success, documents }` list envelope. `documents` is `null` when empty. */\nexport interface PmDocumentsResponse {\n success: boolean;\n documents: PmCustomerDocument[] | null;\n}\n\n/** `{ success, document }` envelope for get/attest. */\nexport interface PmDocumentResponse {\n success: boolean;\n document: PmCustomerDocument;\n}\n\n/**\n * Records the single ask or the terminal attest — the only two events a caller\n * drives (the intake `gap` is system-recorded and cannot be driven here).\n * Ask-once and attest-once are structural: a repeat is refused (409), not nagged.\n */\nexport interface PmAttestationRequest {\n eventType: 'ask' | 'attest';\n note?: string;\n}\n\n// ── Governed disposition (deletion is a decision, not a click) ───────────────\n\n/**\n * Disposition request states. Deliberately NO `approved`/`executed`: an approve\n * decision settles to `held`, because deletion execution is non-expressible\n * until the shared governed-disposition contract (F-PJM-047) lands.\n */\nexport type PmDispositionState = 'requested' | 'under_review' | 'denied' | 'deferred' | 'held';\n\n/** A decision a resolved authority may record. `approved` settles to `held`. */\nexport type PmDispositionDecision = 'denied' | 'deferred' | 'approved';\n\n/** Who asked for disposition. Input to review, never deletion authority. */\nexport type PmDispositionRequesterParty =\n | 'customer'\n | 'counterparty'\n | 'data_subject'\n | 'project_manager'\n | 'administrator'\n | 'other';\n\n/** Resolved PJ-D039 authority kinds. */\nexport type PmAuthorityKind = 'explicit' | 'project_manager' | 'unresolved';\n\n/**\n * A durable deletion-disposition request. A request from any party is INPUT, not\n * authority. It never deletes: the terminal reachable state is `held`\n * (approved-in-principle, execution withheld) / `denied` / `deferred`, each\n * persisted with its reason and policy basis.\n */\nexport interface PmDispositionRequest {\n id: string;\n documentId: string;\n orgId: string;\n /** Server-derived immutable target; never trusted from the requester. */\n targetArtifactId: string;\n targetVersionId: string;\n targetContentHash: string;\n /** Who ASKED (customer, counterparty, data subject, PM, admin) — input only. */\n requesterParty: PmDispositionRequesterParty;\n recordedBy: string;\n requestReason?: string | null;\n state: PmDispositionState;\n resolvedAuthorityUserId?: string | null;\n authorityKind?: PmAuthorityKind | null;\n decision?: PmDispositionDecision | null;\n /** The authority's human rationale, retained separately from a held-state explanation. */\n decisionReason?: string | null;\n decidedBy?: string | null;\n decidedAt?: string | null;\n resolutionReason?: string | null;\n policyBasis?: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Records a deletion request. `requesterParty` is who asked (input, not authority). */\nexport interface PmDispositionRequestInput {\n requesterParty: PmDispositionRequesterParty;\n /** Optional stale-write assertion; the server always derives the actual target. */\n targetVersionId?: string;\n requestReason?: string;\n}\n\n/**\n * An authority's decision. `approved` cannot delete — it settles to `held` with\n * an honest hold statement; `denied`/`deferred` persist with the reason. The\n * store enforces that only the PJ-D039-resolved authority may decide.\n */\nexport interface PmDispositionDecisionInput {\n decision: PmDispositionDecision;\n reason: string;\n /** Required for every outcome; a missing policy basis fails closed. */\n policyBasis: string;\n}\n\n/** The resolved PJ-D039 disposition authority for a project. */\nexport interface PmDispositionAuthority {\n kind: PmAuthorityKind;\n /** Empty/absent when unresolved. */\n userId?: string;\n}\n\n/** `{ success, request }` envelope for create/review/decide. */\nexport interface PmDispositionResponse {\n success: boolean;\n request: PmDispositionRequest;\n}\n\n/** `{ success, requests }` list envelope. `requests` is `null` when empty. */\nexport interface PmDispositionsResponse {\n success: boolean;\n requests: PmDispositionRequest[] | null;\n}\n\n/** Sets the explicit disposition-authority designation. Empty clears it. */\nexport interface PmDispositionAuthorityInput {\n /** Empty string clears the designation (falling back to the current PM). */\n authorityUserId: string;\n}\n\n/** `{ success, resolvedAuthority }` envelope for the authority write. */\nexport interface PmDispositionAuthorityResponse {\n success: boolean;\n resolvedAuthority: PmDispositionAuthority;\n}\n\n// ── Status reports (PJM-IP04 / IMP-PJ-STATUS) ────────────────────────────────\n//\n// A member generates a versioned, evidence-linked status DRAFT from the\n// member-scoped project memory. Every claim carries its class; every material\n// number cites the recorded computation that produced it. The narrative is\n// stored as an immutable, versioned `pm.status-report` artifact (each generation\n// a new version diffed against the prior — never a regeneration over the old).\n\n/** A status claim's class: what is recorded, what is inferred, what is advised. */\nexport type PmClaimClass = 'fact' | 'interpretation' | 'recommendation';\n\n/** A coverage state under the five-state §8 law. `current` is unreachable in the\n * MVP++ core (no declared cadence is modelled — honestly capped at `partial`). */\nexport type PmReportCoverageState = 'n/a' | 'none' | 'thin' | 'partial' | 'current';\n\n/** A cited record revision behind a claim — a fact opens its record. */\nexport interface PmRecordRef {\n recordId: string;\n revision: number;\n family: string;\n}\n\n/** What a claim resolves to. `computations` are computation KEYS; resolve them\n * against the report's `computations` for the version being viewed. */\nexport interface PmClaimEvidence {\n records?: PmRecordRef[];\n /** Computation keys the numbers in this claim cite. */\n computations?: string[];\n documents?: string[];\n}\n\n/** One classed narrative segment. */\nexport interface PmStatusClaim {\n key: string;\n class: PmClaimClass;\n text: string;\n evidence: PmClaimEvidence;\n /** Set when a claim was held/limited by authority-to-share. */\n limitation?: string;\n /** True only for a marked, unconfirmed interpretation. */\n unconfirmed?: boolean;\n}\n\nexport interface PmPhaseInfo {\n name: string;\n evidence: PmRecordRef;\n}\nexport interface PmGateInfo {\n name: string;\n decision: string;\n evidence: PmRecordRef;\n}\n\n/** The current phase + latest applicable gate, honest when absent. */\nexport interface PmPhaseGate {\n /** Null when no phase is recorded — never invented. */\n phase: PmPhaseInfo | null;\n /** Null when no gate decision is recorded — never invented. */\n latestGate: PmGateInfo | null;\n statement: string;\n}\n\n/** One discipline's derived coverage — a computed value, not an editable field. */\nexport interface PmCoverageAreaReport {\n area: string;\n state: PmReportCoverageState;\n reason: string;\n computationKey: string;\n tailoredOut?: boolean;\n}\n\n/** The embedded, non-editable coverage statement. */\nexport interface PmStatusCoverage {\n areas: PmCoverageAreaReport[];\n statement: string;\n /** Recorded computation behind the aggregate numbers in `statement`. */\n summaryComputationKey: string;\n}\n\n/** A recorded structural refusal (e.g. a per-person ranking request). */\nexport interface PmStatusRefusal {\n request: string;\n rule: string;\n message: string;\n}\n\nexport interface PmStatusDiffChange {\n key: string;\n from: string;\n to: string;\n}\nexport interface PmStatusCoverageChange {\n area: string;\n from: string;\n to: string;\n}\n\n/** The useful diff a new version carries against the prior one. */\nexport interface PmStatusDiff {\n fromOrdinal: number;\n added: string[];\n removed: string[];\n changed: PmStatusDiffChange[];\n coverageChanges: PmStatusCoverageChange[];\n phaseGateChanged: boolean;\n summary: string;\n}\n\n/** The full status-report narrative stored in the immutable artifact version. */\nexport interface PmStatusNarrative {\n schema: string;\n projectId: string;\n generatedAt: string;\n phaseGate: PmPhaseGate;\n coverage: PmStatusCoverage;\n claims: PmStatusClaim[];\n exclusions: string[];\n gaps: string[];\n refusals?: PmStatusRefusal[];\n partial: boolean;\n /** Always true — the coverage statement cannot be edited away. */\n coverageLocked: boolean;\n /** Absent on the first version. */\n diff?: PmStatusDiff;\n}\n\n/** One recorded computation behind a number — the \"number opens its calculation\". */\nexport interface PmComputation {\n id: string;\n projectId: string;\n reportArtifactId: string;\n reportVersionId: string;\n computationKey: string;\n method: string;\n /** The exact inputs: the record revision ids read + the coverage denominator. */\n inputs: unknown;\n /** The derived result: the value plus its unit/label. */\n result: unknown;\n asOf: string;\n createdBy: string;\n createdAt: string;\n}\n\n/** The one logical status report per project, pointing at its substrate artifact. */\nexport interface PmStatusReportPointer {\n projectId: string;\n artifactId: string;\n headVersionId: string;\n latestOrdinal: number;\n createdBy: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/** A status-report artifact version's metadata (mirrors the substrate meta). */\nexport interface PmStatusVersion {\n id: string;\n artifactId: string;\n versionRef: string;\n ordinal: number;\n parentVersionId?: string;\n contentType: string;\n authoredBy: string;\n contentHash: string;\n changeNote?: string;\n createdAt: string;\n}\n\n/** A generated/read status report: the narrative, the version it is stored as,\n * and the computations a reader resolves numbers against. */\nexport interface PmStatusReport {\n pointer: PmStatusReportPointer | null;\n version: PmStatusVersion;\n narrative: PmStatusNarrative;\n computations: PmComputation[];\n}\n\n/** `{ success, report }` envelope for generate/get. */\nexport interface PmStatusReportResponse {\n success: boolean;\n report: PmStatusReport;\n}\n\n/** `{ success, pointer, versions }` envelope for the version list. `pointer` is\n * null and `versions` empty when no report has been generated. */\nexport interface PmStatusReportsResponse {\n success: boolean;\n pointer: PmStatusReportPointer | null;\n versions: PmStatusVersion[] | null;\n}\n\n/** `{ success, computation }` envelope for the computation click-through. */\nexport interface PmComputationResponse {\n success: boolean;\n computation: PmComputation;\n}\n\n/** Options for a status generation request. */\nexport interface PmGenerateStatusOptions {\n /** `'people'` requests a per-person ranking — the server refuses and records it. */\n focus?: 'people' | string;\n}\n\n// ── Status distribution — the attended-delivery preflight (PJM-IP05) ──\n//\n// The member-scoped, buildable-now product computation that PRECEDES a governed\n// distribution proposal: resolve recipients through the project stakeholder\n// register (refuse an outsider at proposal time) and re-run the authority-to-share\n// gate over the exact version. It queues and sends NOTHING — the durable proposal,\n// owner+PM approval binding, execution on the shared act rail and per-destination\n// receipts are the shared approvals surface (`ApprovalsClient` /\n// `DeliveryEvidenceLevel` / `ActDestinationReceipt`), reused rather than cloned.\n\n/** Refusal code for a recipient outside the project's stakeholder register. */\nexport const PM_RECIPIENT_NOT_REGISTERED = 'recipient-not-registered';\n\n/** One resolved recipient in the distribution plan. `registered:false` carries the\n * cited refusal (the typo'd outsider, refused at proposal time). */\nexport interface PmDistributionRecipient {\n contactId: string;\n registered: boolean;\n refusalCode?: string;\n refusalReason?: string;\n}\n\n/** A fact claim the authority-to-share re-check held out of the distributable\n * version (its document grounding is no longer attested shareable). */\nexport interface PmHeldClaim {\n key: string;\n class: string;\n limitation: string;\n}\n\n/** The version's re-checked authority-to-share posture. When `cleared` is false the\n * held claims must be re-generated or disclosed before the version can be sent. */\nexport interface PmAuthorityToShare {\n cleared: boolean;\n reason?: string;\n heldClaims?: PmHeldClaim[];\n}\n\n/** The honest execution/configuration posture. `ready:false` with a bounded reason\n * is the \"delivery not yet configured\" setup state the console surfaces. */\nexport interface PmDeliveryReadiness {\n ready: boolean;\n /** A concrete missing delivery connection can be configured in secure project settings. */\n setupRequired?: boolean;\n reason?: string;\n}\n\n/** The reviewable distribution plan a member inspects before approving a send. */\nexport interface PmDistributionPlan {\n projectId: string;\n versionId: string;\n versionRef: string;\n artifactId: string;\n /** Fully qualified immutable artifact/version/digest handle frozen by approval. */\n artifactRef: string;\n recipients: PmDistributionRecipient[];\n authorityToShare: PmAuthorityToShare;\n delivery: PmDeliveryReadiness;\n}\n\n/** `{ success, plan }` envelope for the distribution preflight. */\nexport interface PmDistributionPlanResponse {\n success: boolean;\n plan: PmDistributionPlan;\n}\n\n/** Durable shared-rail proposal created after the server repeats preflight. */\nexport interface PmDistributionProposal {\n status: 'queued_for_approval' | 'already_executed' | string;\n pendingActionId: string;\n}\n\nexport interface PmDistributionProposalResponse {\n success: boolean;\n proposal: PmDistributionProposal;\n}\n\n// ClowdPM attended assistance (IMP-PJ-ASSIST) — drift/sweep findings, coverage\n// and the shared signals a member reviews, dismisses or consumes.\n\n/** A single record/revision the finding cites as its evidence. */\nexport interface PmAssistEvidenceRef {\n recordId: string;\n revisionId?: string;\n family: string;\n detail?: string;\n}\n\n/** One drift or risk-candidate finding about a subject record. */\nexport interface PmAssistFinding {\n kind: string;\n subjectRecordId: string;\n family: string;\n discipline: string;\n summary: string;\n evidence: PmAssistEvidenceRef[];\n accountableContactId?: string;\n ownerErased?: boolean;\n}\n\n/** Coverage state for one discipline. */\nexport interface PmAssistCoverage {\n discipline: string;\n state: 'n/a' | 'none' | 'thin' | 'partial' | 'current';\n reason: string;\n}\n\n/** A thin mirror of the shared signal a member reviews on the assist surface. */\nexport interface PmSignal {\n id: string;\n kind: string;\n title: string;\n summary: string;\n priority: string;\n sightingCount: number;\n scopeLevel: string;\n scopeRef?: string;\n status: string;\n dismissalRationale?: string;\n}\n\n/** The read-only drift assist result. */\nexport interface PmAssistDriftResult {\n drift: PmAssistFinding[];\n coverage: PmAssistCoverage[];\n}\n\n/** The sweep result, which also raises durable signals. */\nexport interface PmAssistSweepResult {\n drift: PmAssistFinding[];\n riskCandidates: PmAssistFinding[];\n coverage: PmAssistCoverage[];\n raised: number;\n signals: PmSignal[];\n}\n\n/** `{ success, drift, coverage }` envelope for the drift assist. */\nexport interface PmAssistDriftResponse {\n success: boolean;\n drift: PmAssistFinding[];\n coverage: PmAssistCoverage[];\n}\n\n/** `{ success, drift, riskCandidates, coverage, raised, signals }` sweep envelope. */\nexport interface PmAssistSweepResponse {\n success: boolean;\n drift: PmAssistFinding[];\n riskCandidates: PmAssistFinding[];\n coverage: PmAssistCoverage[];\n raised: number;\n signals: PmSignal[];\n}\n\n/** `{ success, signal }` envelope for a signal dismiss/consume. */\nexport interface PmSignalResponse {\n success: boolean;\n signal: PmSignal;\n}\n\n// ── Risk register with teeth (PJM-S03 / PJM-IP08) ────────────────────────────\n//\n// The durable S03 journey over the EXISTING primitives (COR-PJ-S03-CORE): a\n// told/derived risk becomes a CONFIRMED, human-authored `risk`-family record; the\n// named accountable owner explicitly accepts or declines (and only that owner\n// may); acceptance appends an immutable `pm.risk-register` artifact version; the\n// approved response is recorded as an OWNED `action`-family commitment linked to\n// the entry; and owner notification originates a trusted proposal on the EXISTING\n// `pm.notify.stakeholder` shared act rail. Delivery is NEVER asserted here — the\n// owner is queued, and \"notified\" is proven only by the shared-rail receipt read\n// on the approvals/activity surface. Confirmed risk + register version + response\n// survive any ownership decline or notification failure.\n//\n// The risk itself is a `PmRecord` (family `risk`); the response is a `PmRecord`\n// (family `action`). Only the request/notification shapes are risk-specific.\n\n/** The named owner's explicit decision on a proposed-owner risk. */\nexport type PmRiskDecision = 'accepted' | 'declined';\n\n/** The four typed response outcomes, including deliberate acceptance-with-rationale. */\nexport type PmRiskResponseType = 'mitigate' | 'transfer' | 'escalate' | 'accept';\n\n/** Grounds one confirmed field in its source so the register never presents an\n * inference as a fact — the chat moment or a recorded schedule/milestone record. */\nexport interface PmRiskCitation {\n field?: string;\n /** `chat` | `pm-record` | `pm-computation`. */\n kind: string;\n ref: string;\n}\n\n/**\n * Confirm a told/derived risk. The caller (a member with WRITE) is the confirming\n * human, so the entry is authored `human` — a derived candidate's citation is\n * preserved but never promoted on its own. A named `ownerContactId` is PROPOSED\n * (not assigned) and must resolve to a registered stakeholder of this project. A\n * told risk that duplicates an active entry's condition is refused (409) so the\n * caller updates the existing entry rather than forking a second one.\n */\nexport interface PmRiskConfirmRequest {\n condition: string;\n consequence?: string;\n /** Opaque JSON on the project's declared probability/impact scale. */\n assessment?: unknown;\n /** Proposed accountable owner — a registered stakeholder contact id. */\n ownerContactId?: string;\n citations?: PmRiskCitation[];\n /** Provenance pointer to the derived candidate this confirms, when any. */\n candidateRef?: string;\n}\n\n/**\n * The named owner's explicit accept/decline. The decision is the OWNER's alone:\n * the server refuses a generic member — even a manager — with `decision-not-by-owner`\n * (403). `expectedCurrentRevisionId` is the optimistic-concurrency handle; a stale\n * value is refused (409) rather than silently overwriting. Acceptance appends the\n * immutable register version; a decline leaves the risk confirmed-but-unowned.\n */\nexport interface PmRiskOwnershipRequest {\n decision: PmRiskDecision;\n expectedCurrentRevisionId: string;\n}\n\n/**\n * PROPOSE the typed response for the owner+PM decision (PJM-IP08 §7.10). This does\n * NOT create the owned commitment — that is materialized only when the decision\n * completes (see decidePMRiskResponse). A generic member may propose (member-write),\n * but the acceptance is the project owner+PM's alone. `dueAt` is MANDATORY: a\n * response is owner + due, or it is nothing. It requires an accepted, named, active\n * owner (else 422) and optimistic concurrency via `expectedCurrentRevisionId` (409).\n * Re-proposing the same response is idempotent; a changed response while one is live\n * conflicts (409).\n */\nexport interface PmRiskResponseRequest {\n type: PmRiskResponseType;\n description: string;\n /** REQUIRED ISO-8601 target date for the owned commitment (owner + due). */\n dueAt: string;\n expectedCurrentRevisionId: string;\n}\n\n/** The honest state of a proposed response awaiting / carrying the owner+PM decision. */\nexport type PmRiskResponseState = 'proposed' | 'accepted' | 'rejected';\n\n/**\n * A response proposal bound to the exact risk revision and register version, carrying\n * its decision state. It never exposes the resolved owner/PM identities.\n */\nexport interface PmRiskResponseProposal {\n id: string;\n riskRecordId: string;\n riskRevisionId: string;\n registerVersionRef: string;\n ownerContactId: string;\n responseType: PmRiskResponseType;\n description: string;\n dueAt?: string | null;\n /** True when the project owner and PM are distinct people (two approvals needed). */\n requiresTwo: boolean;\n state: PmRiskResponseState;\n}\n\n/** Current persisted risk state and the caller's decision authority. */\nexport interface PmRiskView {\n projectId: string;\n risk: PmRecord;\n responseProposal?: PmRiskResponseProposal;\n registerVersionRef?: string;\n canDecideOwnership: boolean;\n canDecideResponse: boolean;\n response?: PmRecord;\n responseRecordId?: string;\n status?: 'accepted' | 'pending' | 'rejected';\n note?: string;\n}\n\nexport interface PmRiskRegister {\n projectId: string;\n risks: PmRiskView[];\n registerVersionRef?: string;\n}\n\n/**\n * The owner's or PM's decision on a proposed response (PJ-D028 owner+PM path). A\n * generic member is refused (403). Only a completing acceptance materializes the\n * owned commitment; a rejection keeps the risk confirmed, response pending.\n */\nexport interface PmRiskResponseDecisionRequest {\n proposalId: string;\n decision: 'accept' | 'reject';\n}\n\n/** The register version handle returned when an accept/response appends a version. */\nexport interface PmRiskOwnershipResult {\n risk: PmRecord;\n registerVersionRef?: string;\n}\n\n/** The result of PROPOSING a response: the risk and the pending proposal. */\nexport interface PmRiskResponseResult {\n risk: PmRecord;\n responseProposal: PmRiskResponseProposal;\n registerVersionRef?: string;\n}\n\n/** The result of a response DECISION. `status` mirrors the honest server state. */\nexport interface PmRiskResponseDecisionResult {\n risk: PmRecord;\n status: 'accepted' | 'pending' | 'rejected';\n /** The materialized owned `action`-family commitment — present only on acceptance. */\n response?: PmRecord;\n responseRecordId?: string;\n registerVersionRef?: string;\n note?: string;\n}\n\n/** `{ success, risk }` envelope for confirm. */\nexport interface PmRiskConfirmResponse {\n success: boolean;\n risk: PmRecord;\n}\n\n/** `{ success, risk, registerVersionRef }` envelope for the ownership decision. */\nexport interface PmRiskOwnershipResponse {\n success: boolean;\n risk: PmRecord;\n registerVersionRef?: string;\n}\n\n/** `{ success, risk, responseProposal, registerVersionRef }` envelope for a propose. */\nexport interface PmRiskResponseResponse {\n success: boolean;\n risk: PmRecord;\n responseProposal: PmRiskResponseProposal;\n registerVersionRef?: string;\n}\n\n/** `{ success, risk, status, response?, ... }` envelope for a response decision. */\nexport interface PmRiskResponseDecisionResponse {\n success: boolean;\n risk: PmRecord;\n status: 'accepted' | 'pending' | 'rejected';\n response?: PmRecord;\n responseRecordId?: string;\n registerVersionRef?: string;\n note?: string;\n}\n\n/** The queued shared-rail proposal — the owner is queued, NEVER yet notified. */\nexport interface PmRiskNotificationProposal {\n status: 'queued_for_approval' | string;\n pendingActionId: string;\n}\n\n/**\n * The notify result. `note` carries the honest \"owner not yet notified\" statement:\n * the notification is queued for owner+PM approval and delivery is proven only by a\n * shared-rail receipt — never by the presence of this proposal.\n */\nexport interface PmRiskNotifyResult {\n proposal: PmRiskNotificationProposal;\n note?: string;\n}\n\n/** `{ success, proposal, note }` envelope for the notify origination (201/200). */\nexport interface PmRiskNotifyResponse {\n success: boolean;\n proposal: PmRiskNotificationProposal;\n note?: string;\n}\n","import {\n isProductKind,\n type PreferredAiProvider,\n type ProductKind,\n type Project,\n} from '../modules/projects/types.js';\n\ninterface WireProject {\n id: string;\n name: string;\n orgId: string;\n default?: boolean;\n isReferenceProject?: boolean;\n preferredAiProvider?: string | null;\n product?: string;\n users?: unknown[];\n}\n\nexport const projectAdapter = {\n fromListResponse(payload: unknown): Project[] {\n const list = (payload as { workspaces?: WireProject[]; projects?: WireProject[] } | null)?.workspaces\n ?? (payload as { projects?: WireProject[] } | null)?.projects\n ?? [];\n // A mixed-version backend may know a product this client does not. Keep the\n // rest of the list usable, but do not misrepresent that row as a supported\n // ProductKind or silently coerce it to Cloud.\n return list.filter((wire) => wire.product == null || isProductKind(wire.product)).map(normalize);\n },\n\n fromGetResponse(payload: unknown): Project {\n const wire = (payload as { workspace?: WireProject; project?: WireProject; data?: WireProject } | null);\n const value = wire?.workspace ?? wire?.project ?? wire?.data;\n if (!value) throw new Error('Project response missing body.');\n return normalize(value);\n },\n\n normalize,\n};\n\nfunction normalize(wire: WireProject): Project {\n const product = normalizeProduct(wire.product);\n return {\n id: wire.id,\n name: wire.name,\n orgId: wire.orgId,\n default: wire.default ?? false,\n isReferenceProject: wire.isReferenceProject ?? false,\n preferredAiProvider: (wire.preferredAiProvider ?? null) as PreferredAiProvider | null,\n product,\n users: (wire.users ?? []) as Project['users'],\n };\n}\n\nfunction normalizeProduct(raw: string | undefined): ProductKind {\n // Missing is the legacy pre-partition wire shape and remains Cloud. An\n // explicit empty/unknown value is not the legacy absence and must fail closed.\n if (raw == null) return 'cloud';\n if (isProductKind(raw)) return raw;\n throw new Error(`Unsupported project product ${JSON.stringify(raw)}.`);\n}\n\n// TODO(backend-cleanup): cloud-agent-backend internal/http/routes/project/project.go\n// still returns `workspaces` / `workspace` keys. When those are renamed to\n// `projects` / `project`, this adapter can fall through to a plain unwrap.\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { projectAdapter } from '../../adapters/projectAdapter.js';\nimport type {\n AddMemberRequest,\n CreateProjectRequest,\n PmAppendRevisionRequest,\n PmAssistDriftResponse,\n PmAssistDriftResult,\n PmAssistSweepResponse,\n PmAssistSweepResult,\n PmSignal,\n PmSignalResponse,\n PmAttestationRequest,\n PmComputation,\n PmComputationResponse,\n PmCreateRecordRequest,\n PmCustomerDocument,\n PmDistributionPlan,\n PmDistributionPlanResponse,\n PmDistributionProposal,\n PmDistributionProposalResponse,\n PmGenerateStatusOptions,\n PmStatusReport,\n PmStatusReportPointer,\n PmStatusReportResponse,\n PmStatusReportsResponse,\n PmStatusVersion,\n PmDispositionAuthority,\n PmDispositionAuthorityInput,\n PmDispositionAuthorityResponse,\n PmDispositionDecisionInput,\n PmDispositionRequest,\n PmDispositionRequestInput,\n PmDispositionResponse,\n PmDispositionsResponse,\n PmDocumentResponse,\n PmDocumentsResponse,\n PmDocumentUploadRequest,\n PmDocumentUploadResult,\n PmGrantMemberRequest,\n PmGrantMemberResponse,\n PmRecord,\n PmRecordFamily,\n PmRecordResponse,\n PmRecordProposal,\n PmRecordProposalDecision,\n PmRecordsResponse,\n PmRecoverManagementRequest,\n PmRecoverManagementResponse,\n PmRevision,\n PmRevisionsResponse,\n PmRevokeMemberResponse,\n PmRiskView,\n PmRiskRegister,\n PmRiskConfirmRequest,\n PmRiskConfirmResponse,\n PmRiskNotifyResponse,\n PmRiskNotifyResult,\n PmRiskOwnershipRequest,\n PmRiskOwnershipResponse,\n PmRiskOwnershipResult,\n PmRiskResponseDecisionRequest,\n PmRiskResponseDecisionResponse,\n PmRiskResponseDecisionResult,\n PmRiskResponseRequest,\n PmRiskResponseResponse,\n PmRiskResponseResult,\n ProductKind,\n Project,\n UpdateMemberRoleRequest,\n UpdateProjectRequest,\n} from './types.js';\n\ninterface SimpleResponse {\n success: boolean;\n message?: string;\n}\n\nfunction directHumanRevisionError(input: unknown): Error | undefined {\n const wire = input as { origin?: unknown; confidence?: unknown };\n if (wire.origin !== undefined && wire.origin !== 'human') {\n return new Error('Direct project-memory writes are human-authored.');\n }\n if (wire.confidence !== undefined && wire.confidence !== null) {\n return new Error('A direct human-authored project-memory write cannot assert confidence.');\n }\n return undefined;\n}\n\nexport class ProjectsClient {\n constructor(private readonly http: BaseClient) {}\n\n /**\n * Lists the caller's projects in one product partition. Omitting `product`\n * defaults to 'cloud' server-side (the cloud UI). The BI frontend passes\n * 'bi' so it only ever sees data projects.\n */\n async list(product?: ProductKind): Promise<Project[]> {\n const path = product ? `/project?product=${encodeURIComponent(product)}` : '/project';\n const res = await this.http.get<unknown>(path);\n return projectAdapter.fromListResponse(res);\n }\n\n async get(projectId: string): Promise<Project> {\n const res = await this.http.get<unknown>(`/project/${projectId}`);\n return projectAdapter.fromGetResponse(res);\n }\n\n /**\n * Creates a project and returns it. For ClowdPM (`product: 'pm'`) pass a\n * stable `requestKey` (minted with `newProjectRequestKey`) and resend the SAME\n * value on retry: the\n * server drives a durable creation state machine keyed on it, so a retried\n * POST converges on the one already-created project rather than a duplicate.\n * The key is required by the type and checked again at runtime, then forwarded\n * verbatim — this method never mints or rewrites it, and never mints the\n * project identity (always server-derived).\n */\n async create(body: CreateProjectRequest): Promise<Project> {\n if (body.product === 'pm' && (typeof body.requestKey !== 'string' || body.requestKey.trim().length === 0)) {\n throw new Error('ClowdPM project creation requires a non-blank requestKey.');\n }\n const res = await this.http.post<unknown>('/project', { body });\n return projectAdapter.fromGetResponse(res);\n }\n\n async update(projectId: string, body: UpdateProjectRequest): Promise<Project> {\n const res = await this.http.put<unknown>(`/project/${projectId}`, { body });\n return projectAdapter.fromGetResponse(res);\n }\n\n delete(projectId: string): Promise<SimpleResponse> {\n return this.http.delete<SimpleResponse>(`/project/${projectId}`);\n }\n\n addMember(projectId: string, body: AddMemberRequest): Promise<SimpleResponse> {\n return this.http.post<SimpleResponse>(`/project/${projectId}/users`, { body });\n }\n\n updateMemberRole(projectId: string, userId: string, body: UpdateMemberRoleRequest): Promise<SimpleResponse> {\n return this.http.put<SimpleResponse>(`/project/${projectId}/users/${userId}`, { body });\n }\n\n removeMember(projectId: string, userId: string): Promise<SimpleResponse> {\n return this.http.delete<SimpleResponse>(`/project/${projectId}/users/${userId}`);\n }\n\n /**\n * Grants a ClowdPM (`pm`) project role through the governed\n * `pm.membership.change` act (PJM-IP01 §7.1). Distinct from the legacy\n * `addMember`, which the backend refuses for a pm project: this moves the\n * `pm_project_member` role record and the workspace floor together. The caller\n * must be an active project MANAGER; a non-member — including a non-member\n * organization administrator — is refused server-side. The role is a `PmRole`\n * (`manager | member | reader`), never an `AccessType`. This method asserts no\n * authority and mints no identity; it forwards the exact tuple.\n */\n grantPMMember(projectId: string, body: PmGrantMemberRequest): Promise<PmGrantMemberResponse> {\n return this.http.post<PmGrantMemberResponse>(`/project/${projectId}/pm-membership`, {\n body: { userId: body.userId, action: 'grant', role: body.role },\n });\n }\n\n /**\n * Revokes a principal's ClowdPM project membership (the governed\n * `pm.membership.change` act, revoke direction). Value-idempotent: revoking a\n * principal who is already revoked or was never a member returns\n * `{ revoked: false }`, a recorded success rather than an error.\n */\n revokePMMember(projectId: string, userId: string): Promise<PmRevokeMemberResponse> {\n return this.http.post<PmRevokeMemberResponse>(`/project/${projectId}/pm-membership`, {\n body: { userId, action: 'revoke' },\n });\n }\n\n /**\n * Runs last-manager recovery (PJM-IP01 §7.4 / `pm.recover-management`): an\n * organization administrator appoints a named replacement manager for a project\n * with NO active manager, recording the reason. It grants the invoking\n * administrator no ordinary project read. Refused (409) while a manager still\n * exists — the governed grant/revoke is the tool then.\n */\n recoverPMManagement(\n projectId: string,\n body: PmRecoverManagementRequest,\n ): Promise<PmRecoverManagementResponse> {\n return this.http.post<PmRecoverManagementResponse>(`/project/${projectId}/pm-recover-management`, {\n body,\n });\n }\n\n /**\n * Lists a project's ClowdPM memory records (PJM-IP02), optionally filtered to\n * one `family`. Each record carries its resolved current revision. Read is\n * member-scoped server-side (the central predicate `M`): a non-member —\n * including a non-member organization administrator — gets a bounded 404, not\n * a leaked list. An empty result is a real \"no records yet\" state, normalized\n * to `[]` (the wire sends a nil slice as `null`).\n */\n listPMRecords(projectId: string, family?: PmRecordFamily): Promise<PmRecord[]> {\n const path = family\n ? `/project/${projectId}/pm/records?family=${encodeURIComponent(family)}`\n : `/project/${projectId}/pm/records`;\n return this.http.get<PmRecordsResponse>(path).then((res) => res.records ?? []);\n }\n\n /**\n * Creates a project-memory record with its first revision in one POST. The\n * caller (an active member with WRITE) supplies the `family` and the `first`\n * revision envelope; the server derives authorship (`authoredBy`) and the\n * revision number and human provenance. Extracted proposals use a distinct\n * governed internal surface and cannot be forged through this member route.\n * Returns the created record with its current revision.\n */\n createPMRecord(projectId: string, body: PmCreateRecordRequest): Promise<PmRecord> {\n const invalid = directHumanRevisionError(body.first);\n if (invalid) return Promise.reject(invalid);\n return this.http\n .post<PmRecordResponse>(`/project/${projectId}/pm/records`, { body })\n .then((res) => res.record);\n }\n\n /** Gets one project-memory record with its current revision (member-scoped). */\n getPMRecord(projectId: string, recordId: string): Promise<PmRecord> {\n return this.http\n .get<PmRecordResponse>(`/project/${projectId}/pm/records/${recordId}`)\n .then((res) => res.record);\n }\n\n /**\n * Appends a revision that supersedes the record's current one — the edit path.\n * Nothing is overwritten; the prior revision is retained as history. Pass\n * `expectedCurrentRevisionId` (the revision id you read) for optimistic\n * concurrency: if it is stale, the server writes nothing and returns a 409 —\n * surfaced here as a thrown `HttpError` whose `body` is a `PmRevisionConflict`\n * carrying the new current revision to reconcile against. Returns the record\n * with its new current revision on success.\n */\n appendPMRevision(\n projectId: string,\n recordId: string,\n body: PmAppendRevisionRequest,\n ): Promise<PmRecord> {\n if (!body.expectedCurrentRevisionId?.trim()) {\n return Promise.reject(new Error('expectedCurrentRevisionId is required to prevent a stale overwrite.'));\n }\n const invalid = directHumanRevisionError(body);\n if (invalid) return Promise.reject(invalid);\n return this.http\n .post<PmRecordResponse>(`/project/${projectId}/pm/records/${recordId}/revisions`, { body })\n .then((res) => res.record);\n }\n\n /**\n * Lists a record's full append-only revision history, oldest first — the\n * provenance/supersession trail. Member-scoped; normalized to `[]` when empty.\n */\n listPMRevisions(projectId: string, recordId: string): Promise<PmRevision[]> {\n return this.http\n .get<PmRevisionsResponse>(`/project/${projectId}/pm/records/${recordId}/revisions`)\n .then((res) => res.revisions ?? []);\n }\n\n /** Re-read a PM chat proposal under current project membership and grants. */\n getPMRecordProposal(projectId: string, proposalId: string): Promise<PmRecordProposal> {\n return this.http.get<PmRecordProposal>(`/project/${encodeURIComponent(projectId)}/pm/chat/record-proposals/${encodeURIComponent(proposalId)}`);\n }\n\n /** Human confirmation/rejection; a stale, expired or already decided proposal is refused. */\n decidePMRecordProposal(projectId: string, proposalId: string, body: PmRecordProposalDecision): Promise<PmRecordProposal> {\n if (!body.expectedVersion?.trim()) return Promise.reject(new Error('expectedVersion is required to decide an exact proposal.'));\n if (body.decision !== 'confirmed' && body.decision !== 'rejected') return Promise.reject(new Error('A PM record proposal decision must be confirmed or rejected.'));\n return this.http.post<PmRecordProposal>(`/project/${encodeURIComponent(projectId)}/pm/chat/record-proposals/${encodeURIComponent(proposalId)}/decision`, {\n body: { expectedVersion: body.expectedVersion, decision: body.decision },\n });\n }\n\n // ── Customer documents (PJM-IP03) ──────────────────────────────────────────\n\n /**\n * Uploads a customer document (immutable v1) and records its provenance +\n * intake attestation. Requires an active member with WRITE. `classification`\n * is DECLARED; a confidential/restricted class routes through the substrate's\n * encrypted-or-refused storage. When the deployment has no encryption posture,\n * a confidential upload FAILS CLOSED as a thrown `HttpError` (422) whose body\n * carries the substrate refusal — nothing is stored and nothing is downgraded\n * to plaintext. When the substrate capability is absent the upload fails closed\n * (503). This client mints no identity and stores no plaintext fallback.\n */\n uploadPMDocument(projectId: string, body: PmDocumentUploadRequest): Promise<PmDocumentUploadResult> {\n return this.http.post<PmDocumentUploadResult>(`/project/${projectId}/pm/documents`, { body });\n }\n\n /**\n * Lists a project's customer documents with derived attestation state.\n * Member-scoped server-side (the central predicate `M`): a non-member —\n * including a non-member organization administrator — gets a bounded 404, not\n * a leaked list. `documents` is normalized to `[]` when empty.\n */\n listPMDocuments(projectId: string): Promise<PmCustomerDocument[]> {\n return this.http\n .get<PmDocumentsResponse>(`/project/${projectId}/pm/documents`)\n .then((res) => res.documents ?? []);\n }\n\n /** Gets one document with its full append-only attestation history (member-scoped). */\n getPMDocument(projectId: string, documentId: string): Promise<PmCustomerDocument> {\n return this.http\n .get<PmDocumentResponse>(`/project/${projectId}/pm/documents/${documentId}`)\n .then((res) => res.document);\n }\n\n /**\n * Appends an authority-to-share attestation event — the single `ask` or the\n * terminal `attest`. Append-only: ask-once and attest-once are structural, so a\n * repeat is refused (409), never nagged or double-attested. The intake `gap` is\n * system-recorded and cannot be driven here. Requires a member with WRITE.\n */\n recordPMDocumentAttestation(\n projectId: string,\n documentId: string,\n body: PmAttestationRequest,\n ): Promise<PmCustomerDocument> {\n return this.http\n .post<PmDocumentResponse>(`/project/${projectId}/pm/documents/${documentId}/attestation`, { body })\n .then((res) => res.document);\n }\n\n // ── Governed disposition (deletion is a decision, not a click) ─────────────\n\n /**\n * Files a deletion-disposition request against a document — INPUT, not\n * authority. Any active member may file one (a request never deletes on its\n * own). It lands in `requested` and is routed through review by the resolved\n * PJ-D039 authority. There is deliberately NO method that deletes a document or\n * executes a disposition on this client: execution is non-expressible until the\n * shared governed-disposition contract (F-PJM-047) lands.\n */\n requestPMDocumentDisposition(\n projectId: string,\n documentId: string,\n body: PmDispositionRequestInput,\n ): Promise<PmDispositionRequest> {\n return this.http\n .post<PmDispositionResponse>(`/project/${projectId}/pm/documents/${documentId}/disposition-requests`, { body })\n .then((res) => res.request);\n }\n\n /** Lists a project's disposition requests (member-scoped; normalized to `[]`). */\n listPMDispositionRequests(projectId: string): Promise<PmDispositionRequest[]> {\n return this.http\n .get<PmDispositionsResponse>(`/project/${projectId}/pm/disposition-requests`)\n .then((res) => res.requests ?? []);\n }\n\n /**\n * Moves a request to `under_review`, resolving the PJ-D039 authority (or to the\n * fail-closed `held` state when no authority resolves). Requires a project\n * MANAGER to initiate review.\n */\n reviewPMDispositionRequest(projectId: string, requestId: string): Promise<PmDispositionRequest> {\n return this.http\n .post<PmDispositionResponse>(`/project/${projectId}/pm/disposition-requests/${requestId}/review`, { body: {} })\n .then((res) => res.request);\n }\n\n /**\n * Records the resolved authority's decision. `denied`/`deferred` persist with\n * the reason and policy basis; `approved` CANNOT delete — it settles to `held`\n * with an honest hold statement (the shared execution contract has not landed).\n * The server rejects a caller who is not the PJ-D039-resolved authority (403).\n */\n decidePMDispositionRequest(\n projectId: string,\n requestId: string,\n body: PmDispositionDecisionInput,\n ): Promise<PmDispositionRequest> {\n return this.http\n .post<PmDispositionResponse>(`/project/${projectId}/pm/disposition-requests/${requestId}/decision`, { body })\n .then((res) => res.request);\n }\n\n /**\n * Sets (or clears) the explicit PJ-D039 disposition-authority designation and\n * returns the newly resolved authority. An empty `authorityUserId` clears the\n * designation, falling back to the current PM at resolve time. Requires a\n * project MANAGER.\n */\n setPMDispositionAuthority(\n projectId: string,\n body: PmDispositionAuthorityInput,\n ): Promise<PmDispositionAuthority> {\n return this.http\n .put<PmDispositionAuthorityResponse>(`/project/${projectId}/pm/disposition-authority`, { body })\n .then((res) => res.resolvedAuthority);\n }\n\n // ── Status reports (PJM-IP04) ──────────────────────────────────────────────\n\n /**\n * Generates a status DRAFT from the project's member-scoped memory (PJM-IP04).\n * Every claim carries its class; every material number cites its recorded\n * computation. The draft is stored as a NEW immutable `pm.status-report`\n * artifact version — never a regeneration over the prior — and the returned\n * narrative embeds a diff against the previous version when one exists.\n * Requires an active member with WRITE. Passing `focus: 'people'` requests a\n * per-person ranking; the server refuses it and records the refusal (this\n * product reports items and blocked chains, not per-person scoreboards). When\n * the artifact substrate is absent this fails closed as a thrown 503.\n */\n generatePMStatusReport(projectId: string, opts?: PmGenerateStatusOptions): Promise<PmStatusReport> {\n const focus = opts?.focus?.trim();\n const path = focus\n ? `/project/${projectId}/pm/status-reports?focus=${encodeURIComponent(focus)}`\n : `/project/${projectId}/pm/status-reports`;\n return this.http.post<PmStatusReportResponse>(path, { body: {} }).then((res) => res.report);\n }\n\n /**\n * Lists a project's status-report versions (oldest first) with the report\n * pointer. Member-scoped server-side (the central predicate `M`): a non-member\n * — including a non-member organization administrator — gets a bounded 404.\n * `pointer` is null and `versions` empty when no report has been generated.\n */\n listPMStatusReports(\n projectId: string,\n ): Promise<{ pointer: PmStatusReportPointer | null; versions: PmStatusVersion[] }> {\n return this.http\n .get<PmStatusReportsResponse>(`/project/${projectId}/pm/status-reports`)\n .then((res) => ({ pointer: res.pointer ?? null, versions: res.versions ?? [] }));\n }\n\n /**\n * Reads one status-report version: its narrative (claims, coverage, phase/gate,\n * diff) and the computations a reader resolves its numbers against. A prior\n * version stays readable after a newer one is generated (versions are\n * immutable). Member-scoped; a non-member gets a bounded 404.\n */\n getPMStatusReport(projectId: string, versionId: string): Promise<PmStatusReport> {\n return this.http\n .get<PmStatusReportResponse>(`/project/${projectId}/pm/status-reports/${versionId}`)\n .then((res) => res.report);\n }\n\n /**\n * Resolves one recorded computation by id — the production-side \"a number opens\n * its computation\" click-through. Returns the method, the exact inputs (the\n * record revision ids read + the coverage denominator) and the result.\n * Member-scoped; a cross-project or cross-tenant id is a bounded 404.\n */\n getPMComputation(projectId: string, computationId: string): Promise<PmComputation> {\n return this.http\n .get<PmComputationResponse>(`/project/${projectId}/pm/computations/${computationId}`)\n .then((res) => res.computation);\n }\n\n /**\n * The attended-delivery PREFLIGHT for a status-report version (PJM-IP05): the\n * buildable-now product computation that precedes a governed distribution\n * proposal. It resolves the proposed recipients through THIS project's\n * stakeholder register — refusing an outsider at proposal time with the rule\n * cited — and re-runs the authority-to-share gate over the exact version's\n * claims against current document attestation, holding a fact whose grounding\n * is no longer attested shareable. Passing an empty `recipientContactIds`\n * returns the project's registered stakeholders as the candidate recipients.\n *\n * It QUEUES and SENDS nothing: the durable proposal, the owner+PM approval\n * binding, the execution on the shared person-directed act rail and the\n * per-destination receipts are the shared approvals surface (`ApprovalsClient`,\n * `DeliveryEvidenceLevel`, `ActDestinationReceipt`). `plan.delivery.ready` is\n * false with a bounded reason until the ClowdPM outbound rail is enabled — the\n * \"delivery not yet configured\" setup state. Requires an active member with\n * WRITE; a reader gets a 403, a non-member a bounded 404.\n */\n previewPMStatusDistribution(\n projectId: string,\n versionId: string,\n recipientContactIds: string[] = [],\n ): Promise<PmDistributionPlan> {\n return this.http\n .post<PmDistributionPlanResponse>(\n `/project/${projectId}/pm/status-reports/${versionId}/distribution-preflight`,\n { body: { recipientContactIds } },\n )\n .then((res) => res.plan);\n }\n\n /**\n * Repeats the exact-version/register/sharing preflight on the server and\n * creates a durable approval. Report bytes, artifact identity and transport\n * routing are intentionally not accepted from the client.\n */\n proposePMStatusDistribution(\n projectId: string,\n versionId: string,\n recipientContactIds: string[],\n ): Promise<PmDistributionProposal> {\n return this.http\n .post<PmDistributionProposalResponse>(\n `/project/${projectId}/pm/status-reports/${versionId}/distribution-proposals`,\n { body: { recipientContactIds } },\n )\n .then((res) => res.proposal);\n }\n\n /**\n * Reads drift assistance for the project: findings whose subject records have\n * gone stale past the freshness window, plus per-discipline coverage. Reads\n * only — no durable signal is raised. Requires an active member.\n */\n pmAssistDrift(\n projectId: string,\n freshnessWindowDays?: number,\n ): Promise<PmAssistDriftResult> {\n return this.http\n .post<PmAssistDriftResponse>(`/project/${projectId}/pm/assist/drift`, {\n body: { freshnessWindowDays },\n })\n .then((res) => ({\n drift: res.drift ?? [],\n coverage: res.coverage ?? [],\n }));\n }\n\n /**\n * Runs the assist sweep: drift + risk-candidate findings and coverage, and\n * raises durable shared signals for a member to triage. Returns the raised\n * count and the signals alongside the findings.\n */\n pmAssistSweep(\n projectId: string,\n freshnessWindowDays?: number,\n ): Promise<PmAssistSweepResult> {\n return this.http\n .post<PmAssistSweepResponse>(`/project/${projectId}/pm/assist/sweep`, {\n body: { freshnessWindowDays },\n })\n .then((res) => ({\n drift: res.drift ?? [],\n riskCandidates: res.riskCandidates ?? [],\n coverage: res.coverage ?? [],\n raised: res.raised,\n signals: res.signals ?? [],\n }));\n }\n\n /**\n * Dismisses a raised assist signal with a required rationale, returning the\n * updated signal.\n */\n dismissPMAssistSignal(\n projectId: string,\n signalId: string,\n rationale: string,\n ): Promise<PmSignal> {\n return this.http\n .post<PmSignalResponse>(\n `/project/${projectId}/pm/assist/signals/${signalId}/dismiss`,\n { body: { rationale } },\n )\n .then((res) => res.signal);\n }\n\n /**\n * Records that a raised assist signal was acted on — the member consumed it\n * into a durable artifact identified by `kind`/`ref` — optionally marking it\n * consumed. Returns the updated signal.\n */\n consumePMAssistSignal(\n projectId: string,\n signalId: string,\n kind: string,\n ref: string,\n markConsumed: boolean,\n ): Promise<PmSignal> {\n return this.http\n .post<PmSignalResponse>(\n `/project/${projectId}/pm/assist/signals/${signalId}/consume`,\n { body: { kind, ref, markConsumed } },\n )\n .then((res) => res.signal);\n }\n\n // ── Risk register with teeth (PJM-S03 / PJM-IP08) ──────────────────────────\n //\n // The one durable S03 journey over the EXISTING primitives: confirm a risk →\n // the named owner accepts/declines → an immutable register version is appended →\n // the approved response is an owned commitment → owner notification originates on\n // the shared `pm.notify.stakeholder` rail. This client asserts NO authority and\n // mints NO identity — it forwards the exact tuple and renders the server's answer.\n // It never fabricates a receipt: the notify method returns only the QUEUED\n // proposal and the honest \"owner not yet notified\" note; delivery is proven only\n // by the shared-rail receipt read on the approvals/activity surface. The confirmed\n // risk, its register version and the response survive an owner decline or a\n // notification failure.\n\n /** Loads saved risk proposals and current decision authority without appending a register version. */\n getPMRiskRegister(projectId: string): Promise<PmRiskRegister> {\n return this.http.get<PmRiskRegister>(`/project/${encodeURIComponent(projectId)}/pm/chat/risk-register`);\n }\n\n /** Reloads one exact response proposal, including its terminal decision. */\n getPMRiskResponse(projectId: string, proposalId: string): Promise<PmRiskView> {\n return this.http.get<PmRiskView>(`/project/${encodeURIComponent(projectId)}/pm/chat/risk-responses/${encodeURIComponent(proposalId)}`);\n }\n\n /**\n * Confirms a told/derived risk as a human-authored `risk` record (member with\n * WRITE). A named `ownerContactId` is PROPOSED — never assigned — and must be a\n * registered stakeholder of this project (else a 422). A told risk duplicating an\n * active entry's condition is refused (409 carrying the existing id) so the caller\n * updates that entry rather than forking a second one. Returns the created risk\n * record with its current revision.\n */\n confirmPMRisk(projectId: string, body: PmRiskConfirmRequest): Promise<PmRecord> {\n if (!body.condition?.trim()) {\n return Promise.reject(new Error('A risk condition is required.'));\n }\n return this.http\n .post<PmRiskConfirmResponse>(`/project/${projectId}/pm/risks`, { body })\n .then((res) => res.risk);\n }\n\n /**\n * Records the named owner's explicit accept/decline. The decision is the OWNER's\n * alone: the server refuses a generic member — even a manager — with a 403\n * (`decision-not-by-owner`), and an inactive/erased or unlinked owner fails\n * honestly. `expectedCurrentRevisionId` (the revision id you read) is the\n * optimistic-concurrency handle — a stale value is a 409 (thrown `HttpError`),\n * never a silent overwrite. Acceptance appends the immutable register version;\n * a decline leaves the risk confirmed-but-unowned. Returns the updated risk and\n * the appended register version handle.\n */\n decidePMRiskOwnership(\n projectId: string,\n riskId: string,\n body: PmRiskOwnershipRequest,\n ): Promise<PmRiskOwnershipResult> {\n if (body.decision !== 'accepted' && body.decision !== 'declined') {\n return Promise.reject(new Error(\"An ownership decision must be 'accepted' or 'declined'.\"));\n }\n if (!body.expectedCurrentRevisionId?.trim()) {\n return Promise.reject(new Error('expectedCurrentRevisionId is required to prevent a stale overwrite.'));\n }\n return this.http\n .post<PmRiskOwnershipResponse>(`/project/${projectId}/pm/risks/${riskId}/ownership`, { body })\n .then((res) => ({ risk: res.risk, registerVersionRef: res.registerVersionRef }));\n }\n\n /**\n * PROPOSES the typed response for the owner+PM decision (PJM-IP08 §7.10). It does\n * NOT create the owned commitment — that is materialized only when the decision\n * completes (see decidePMRiskResponse). A generic member may propose (member-write),\n * but the acceptance is the project owner+PM's alone. `dueAt` is MANDATORY (owner +\n * due). Requires an accepted, named, active owner (else 422). Optimistic concurrency\n * via `expectedCurrentRevisionId` (409). Re-proposing the same response is idempotent;\n * a changed response while one is live conflicts (409). Returns the risk and the\n * pending proposal — never a delivery or an approval this client did not observe.\n */\n proposePMRiskResponse(\n projectId: string,\n riskId: string,\n body: PmRiskResponseRequest,\n ): Promise<PmRiskResponseResult> {\n if (!body.description?.trim()) {\n return Promise.reject(new Error('A response description is required.'));\n }\n if (!body.dueAt?.trim()) {\n return Promise.reject(new Error('A response due date is required — a response is owner + due.'));\n }\n if (!body.expectedCurrentRevisionId?.trim()) {\n return Promise.reject(new Error('expectedCurrentRevisionId is required to prevent a stale overwrite.'));\n }\n return this.http\n .post<PmRiskResponseResponse>(`/project/${projectId}/pm/risks/${riskId}/response`, { body })\n .then((res) => ({\n risk: res.risk,\n responseProposal: res.responseProposal,\n registerVersionRef: res.registerVersionRef,\n }));\n }\n\n /**\n * Records the project owner's or PM's decision on a proposed response through the\n * existing PJ-D028 owner+PM path (identity collapse, current-authority recheck). The\n * server refuses a generic member (403) — this client asserts no authority. Only a\n * completing acceptance materializes exactly one owned commitment and re-versions the\n * register; a rejection keeps the risk confirmed, response pending. Returns the honest\n * `status` (accepted | pending | rejected) and, on acceptance, the owned commitment.\n */\n decidePMRiskResponse(\n projectId: string,\n riskId: string,\n body: PmRiskResponseDecisionRequest,\n ): Promise<PmRiskResponseDecisionResult> {\n if (!body.proposalId?.trim()) {\n return Promise.reject(new Error('A proposalId is required to decide a response.'));\n }\n if (body.decision !== 'accept' && body.decision !== 'reject') {\n return Promise.reject(new Error(\"A response decision must be 'accept' or 'reject'.\"));\n }\n return this.http\n .post<PmRiskResponseDecisionResponse>(`/project/${projectId}/pm/risks/${riskId}/response/decision`, { body })\n .then((res) => ({\n risk: res.risk,\n status: res.status,\n response: res.response,\n responseRecordId: res.responseRecordId,\n registerVersionRef: res.registerVersionRef,\n note: res.note,\n }));\n }\n\n /**\n * Originates the owner-notification: it produces the per-risk immutable\n * notification artifact and a trusted proposal on the EXISTING\n * `pm.notify.stakeholder` shared act rail (recipient = the accepted owner). It\n * requires an accepted owner who is a registered stakeholder AND a recorded owned\n * response. The server records only the QUEUED pending action — never a\n * \"notified\"/\"delivered\" flag; the returned `note` is the honest \"owner not yet\n * notified\" statement. It is idempotent (a duplicate returns the existing queued\n * action). A transport/proposal failure is a thrown `HttpError` (502) with the\n * confirmed risk, register version and response left intact. Delivery is proven\n * ONLY by the shared-rail receipt — never inferred from this proposal.\n */\n proposePMRiskNotification(projectId: string, riskId: string): Promise<PmRiskNotifyResult> {\n return this.http\n .post<PmRiskNotifyResponse>(`/project/${projectId}/pm/risks/${riskId}/notify`, { body: {} })\n .then((res) => ({ proposal: res.proposal, note: res.note }));\n }\n}\n","import type { Sandbox } from '../modules/sandboxes/types.js';\n\ninterface WireSandbox {\n id: string;\n name: string;\n storageType: string;\n mode: string;\n orgId: string;\n userId: string;\n createdAt: string;\n disabled?: boolean;\n product?: Sandbox['product'];\n // Legacy wire alternates: backend may send projectId or workspaceId.\n projectId?: string | null;\n workspaceId?: string | null;\n}\n\nexport const sandboxAdapter = {\n fromListResponse(payload: unknown): Sandbox[] {\n const list = (payload as { repos?: WireSandbox[]; sandboxes?: WireSandbox[] } | null)?.repos\n ?? (payload as { sandboxes?: WireSandbox[] } | null)?.sandboxes\n ?? [];\n return list.map(normalize);\n },\n\n fromGetResponse(payload: unknown): Sandbox {\n const wire = payload as { repo?: WireSandbox; sandbox?: WireSandbox; data?: WireSandbox } | null;\n const value = wire?.repo ?? wire?.sandbox ?? wire?.data;\n if (!value) throw new Error('Sandbox response missing body.');\n return normalize(value);\n },\n\n normalize,\n};\n\nfunction normalize(wire: WireSandbox): Sandbox {\n return {\n id: wire.id,\n name: wire.name,\n storageType: wire.storageType,\n mode: wire.mode,\n orgId: wire.orgId,\n userId: wire.userId,\n projectId: wire.projectId ?? wire.workspaceId ?? null,\n createdAt: wire.createdAt,\n disabled: wire.disabled ?? false,\n product: wire.product,\n };\n}\n\n// TODO(backend-cleanup): cloud-agent-backend internal/http/routes/sandbox/sandbox.go\n// still returns `repos` / `repo` response keys, and Sandbox JSON may carry\n// `workspaceId` instead of `projectId` (internal/domain/types.go). When both\n// are renamed, this adapter collapses to a plain unwrap.\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { sandboxAdapter } from '../../adapters/sandboxAdapter.js';\nimport type {\n CreateSandboxRequest,\n ListSandboxesQuery,\n Sandbox,\n UpdateSandboxRequest,\n} from './types.js';\n\ninterface SimpleResponse {\n success: boolean;\n message?: string;\n}\n\nexport class SandboxesClient {\n constructor(private readonly http: BaseClient) {}\n\n async list(query: ListSandboxesQuery = {}): Promise<Sandbox[]> {\n const res = await this.http.get<unknown>('/sandbox', {\n query: { projectId: query.projectId },\n });\n return sandboxAdapter.fromListResponse(res);\n }\n\n async get(sandboxId: string): Promise<Sandbox> {\n const res = await this.http.get<unknown>(`/sandbox/${sandboxId}`);\n return sandboxAdapter.fromGetResponse(res);\n }\n\n async create(body: CreateSandboxRequest): Promise<Sandbox> {\n const res = await this.http.post<unknown>('/sandbox', {\n body: {\n name: body.name,\n projectId: body.projectId,\n storageType: body.storageType ?? 'S3',\n mode: body.mode ?? 'NORMAL',\n },\n });\n return sandboxAdapter.fromGetResponse(res);\n }\n\n async update(sandboxId: string, body: UpdateSandboxRequest): Promise<Sandbox> {\n const res = await this.http.put<unknown>(`/sandbox/${sandboxId}`, { body });\n return sandboxAdapter.fromGetResponse(res);\n }\n\n delete(sandboxId: string): Promise<SimpleResponse> {\n return this.http.delete<SimpleResponse>(`/sandbox/${sandboxId}`);\n }\n}\n","// Credential types for @clowdops/tsclient.\n//\n// Schema mirrors cloud-agent-backend's Credential row (renamed from APIKey\n// in migration 0010). Every provider — cloud (AWS/GCP/AZURE), infra\n// (SSH), VCS (GitHub/GitLab/Azure DevOps), AI/LLM (OpenAI/Anthropic) —\n// uses the same `(provider, label, secret, metadata)` shape.\n// Provider-specific fields live in `metadata`; the catalog at\n// ./providers.ts is the source of truth for what each provider's fields\n// look like.\n//\n// Sandbox-scoped FOA bearer tokens (formerly RepoAiApiKey) are now\n// modelled separately as GatewayToken — see below.\n\n// ProviderID is open: the catalog defines a default set, but we allow\n// any string so customer-extended catalogs are still typed.\nexport type ProviderID = 'AWS' | 'BEDROCK' | 'GCP' | 'AZURE' | 'OCI' | 'SSH' | 'GITHUB' | 'GITLAB' | 'AZURE_DEVOPS' | 'OPENAI' | 'ANTHROPIC' | 'GEMINI' | string;\n\n// ── Universal credential ─────────────────────────────────────────────\n\n// Credential is the read-projection of one row in the Credential table.\n// Never includes the secret. `displayHint` is the catalog-computed\n// snippet for listings (e.g. \"AKIATEST… / us-east-1\",\n// \"ubuntu@vps.example.com:22\").\nexport interface Credential {\n id: string;\n provider: ProviderID;\n label: string;\n metadata: Record<string, unknown>;\n displayHint?: string;\n createdAt: string;\n}\n\n// CreateCredentialRequest is the universal create body. Provider-specific\n// fields go inside `metadata`; the catalog validates the shape both\n// client-side (./providers.ts:validate) and server-side.\nexport interface CreateCredentialRequest {\n provider: ProviderID;\n label: string;\n secret: string;\n metadata?: Record<string, unknown>;\n projectId: string;\n}\n\n// UpdateCredentialRequest is partial. Provider is immutable on update; to\n// change provider, delete and re-create. `metadata` is replace-wholesale\n// when present.\nexport interface UpdateCredentialRequest {\n label?: string;\n secret?: string;\n metadata?: Record<string, unknown>;\n}\n\n// PublishBICredentialRequest is the body for POST /credentials/:id/bi-publish\n// (BI-RLS-01): the explicit owner/admin sign-off that turns a shared BI\n// credential from credless into usable by every viewer. Both fields are\n// required — the server rejects a blank classification or label, and rejects\n// a per-user-scoped credential outright (it is already viewer-scoped).\nexport interface PublishBICredentialRequest {\n /** Data classification the underlying connection exposes, e.g. \"internal\", \"confidential\". */\n classification: string;\n /** Shown to every viewer of a dashboard backed by this connection, e.g. \"Sales shared account\". */\n runsAsLabel: string;\n}\n\n// RevokeBIPublishRequest is the optional body for DELETE /credentials/:id/bi-publish.\nexport interface RevokeBIPublishRequest {\n reason?: string;\n}\n\n// ListCredentialsQuery narrows /credentials by project and optionally by\n// provider id or capability bit (storage|ai|compute|vcs|notify).\nexport interface ListCredentialsQuery {\n projectId: string;\n provider?: ProviderID;\n capability?: 'storage' | 'ai' | 'compute' | 'vcs' | 'notify';\n}\n\n// SandboxCredential is one row in the SandboxCredential join table —\n// links a sandbox to a project-level credential. The PK is\n// (sandboxId, credentialId), so association identity is the pair itself\n// (no synthetic association id).\nexport interface SandboxCredential {\n sandboxId: string;\n credentialId: string;\n provider: ProviderID;\n label: string;\n displayHint?: string;\n createdAt: string;\n}\n\n// ── Sandbox gateway tokens ───────────────────────────────────────────\n\n// GatewayToken is a sandbox-scoped, OpenAI-compatible bearer used by the\n// agent engine to authenticate to FlashOnAI. The plaintext secret is\n// returned exactly once — at creation — and never re-fetchable.\nexport interface GatewayToken {\n id: string;\n sandboxId: string;\n label: string;\n createdAt: string;\n}\n\nexport interface CreateGatewayTokenRequest {\n label: string;\n}\n\n// CreateGatewayTokenResponse is the create-time-only shape — `secret`\n// holds the plaintext bearer the caller must surface (\"copy now\")\n// before navigating away.\nexport interface CreateGatewayTokenResponse {\n token: GatewayToken;\n secret: string;\n}\n\n// AgentToken is a sandbox-scoped bearer an EXTERNAL agent (Claude Code,\n// Cursor, Codex, …) presents to the MCP server (/mcp) to drive this\n// sandbox's cloud agent. Only a hash is stored server-side; the plaintext\n// (`secret`) is returned exactly once at creation. `tokenPrefix` is a\n// non-secret display fragment (\"fba_AbCd…\") so a list can disambiguate\n// rotated tokens.\nexport interface AgentToken {\n id: string;\n sandboxId: string;\n label: string;\n tokenPrefix: string;\n lastUsedAt?: string;\n createdAt: string;\n}\n\nexport interface CreateAgentTokenRequest {\n label: string;\n}\n\n// CreateAgentTokenResponse is the create-time-only shape — `secret` holds\n// the plaintext bearer the caller must surface (\"copy now\") before\n// navigating away.\nexport interface CreateAgentTokenResponse {\n token: AgentToken;\n secret: string;\n}\n\n// ── Common envelope ──────────────────────────────────────────────────\n\nexport interface SimpleKeysResponse {\n success: boolean;\n message?: string;\n data?: unknown;\n}\n\n// ── Wire shapes (legacy field-name aliases collapse here) ────────────\n\nexport interface WireSandboxCredential {\n // Backend wire emits sandboxId; older clients may still see repoId.\n // Normaliser collapses both into SandboxCredential.sandboxId.\n sandboxId?: string;\n repoId?: string;\n credentialId: string;\n provider: string;\n label: string;\n displayHint?: string | null;\n createdAt: string;\n}\n\nexport interface WireGatewayToken {\n id: string;\n // Backend wire emits sandboxId via \"repoId\" today (StorageRepo/Sandbox\n // alias); accept both.\n sandboxId?: string;\n repoId?: string;\n label: string;\n createdAt: string;\n}\n\nexport function normalizeSandboxCredential(wire: WireSandboxCredential): SandboxCredential {\n return {\n sandboxId: wire.sandboxId ?? wire.repoId ?? '',\n credentialId: wire.credentialId,\n provider: wire.provider,\n label: wire.label,\n displayHint: wire.displayHint ?? undefined,\n createdAt: wire.createdAt,\n };\n}\n\nexport function normalizeGatewayToken(wire: WireGatewayToken): GatewayToken {\n return {\n id: wire.id,\n sandboxId: wire.sandboxId ?? wire.repoId ?? '',\n label: wire.label,\n createdAt: wire.createdAt,\n };\n}\n\nexport interface WireAgentToken {\n id: string;\n // Backend emits sandboxId; accept repoId too for forward/backward compat.\n sandboxId?: string;\n repoId?: string;\n label: string;\n tokenPrefix: string;\n lastUsedAt?: string | null;\n createdAt: string;\n}\n\nexport function normalizeAgentToken(wire: WireAgentToken): AgentToken {\n return {\n id: wire.id,\n sandboxId: wire.sandboxId ?? wire.repoId ?? '',\n label: wire.label,\n tokenPrefix: wire.tokenPrefix,\n lastUsedAt: wire.lastUsedAt ?? undefined,\n createdAt: wire.createdAt,\n };\n}\n","// AgentTokensClient covers sandbox-scoped agent access tokens — the bearers\n// an EXTERNAL agent (Claude Code, Cursor, Codex, …) presents to the MCP\n// server (/mcp) to drive this sandbox's cloud agent. Each sandbox can have\n// multiple tokens (one per client, rotation).\n//\n// The plaintext bearer is returned EXACTLY ONCE — at create time. The\n// frontend must surface it (\"copy now\") before navigating away; the server\n// stores only a sha256 hash, so a lost plaintext is unrecoverable (delete +\n// recreate).\nimport type { BaseClient } from '../../http/BaseClient.js';\nimport {\n AgentToken,\n CreateAgentTokenRequest,\n CreateAgentTokenResponse,\n SimpleKeysResponse,\n WireAgentToken,\n normalizeAgentToken,\n} from './types.js';\n\nexport class AgentTokensClient {\n constructor(private readonly http: BaseClient) {}\n\n async list(sandboxId: string): Promise<AgentToken[]> {\n const res = await this.http.get<{ success: boolean; tokens?: WireAgentToken[]; data?: WireAgentToken[] }>(\n `/sandbox/${sandboxId}/agent-token`,\n );\n const list = res.tokens ?? res.data ?? [];\n return list.map(normalizeAgentToken);\n }\n\n /**\n * create returns both the persisted token row and the plaintext bearer\n * (`secret`). The bearer is shown only here; surface it to the user\n * immediately. If they navigate away without copying, they must delete the\n * token and create a new one.\n */\n async create(sandboxId: string, body: CreateAgentTokenRequest): Promise<CreateAgentTokenResponse> {\n const res = await this.http.post<{\n success: boolean;\n token?: WireAgentToken;\n secret?: string;\n }>(`/sandbox/${sandboxId}/agent-token`, { body });\n if (!res.token || !res.secret) {\n throw new Error('createAgentToken response missing token or secret.');\n }\n return {\n token: normalizeAgentToken(res.token),\n secret: res.secret,\n };\n }\n\n delete(sandboxId: string, tokenId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/sandbox/${sandboxId}/agent-token/${tokenId}`);\n }\n}\n","// GatewayTokensClient covers sandbox-scoped FOA bearer tokens (the\n// post-redesign replacement for the legacy RepoAiApiKey rows). Each\n// sandbox can have multiple tokens for rotation / dev-prod separation.\n//\n// The plaintext bearer is returned EXACTLY ONCE — at create time. The\n// frontend must surface it (\"copy now\") before navigating away; once\n// the response is dropped, only the encrypted envelope persists and the\n// plaintext is unrecoverable.\nimport type { BaseClient } from '../../http/BaseClient.js';\nimport {\n CreateGatewayTokenRequest,\n CreateGatewayTokenResponse,\n GatewayToken,\n SimpleKeysResponse,\n WireGatewayToken,\n normalizeGatewayToken,\n} from './types.js';\n\nexport class GatewayTokensClient {\n constructor(private readonly http: BaseClient) {}\n\n async list(sandboxId: string): Promise<GatewayToken[]> {\n const res = await this.http.get<{ success: boolean; tokens?: WireGatewayToken[]; data?: WireGatewayToken[] }>(\n `/sandbox/${sandboxId}/gateway-token`,\n );\n const list = res.tokens ?? res.data ?? [];\n return list.map(normalizeGatewayToken);\n }\n\n /**\n * create returns both the persisted token row and the plaintext bearer\n * (`secret`). The bearer is shown only here; surface it to the user\n * immediately. If they navigate away without copying, they have to\n * delete the token and create a new one.\n */\n async create(sandboxId: string, body: CreateGatewayTokenRequest): Promise<CreateGatewayTokenResponse> {\n const res = await this.http.post<{\n success: boolean;\n token?: WireGatewayToken;\n secret?: string;\n }>(`/sandbox/${sandboxId}/gateway-token`, { body });\n if (!res.token || !res.secret) {\n throw new Error('createGatewayToken response missing token or secret.');\n }\n return {\n token: normalizeGatewayToken(res.token),\n secret: res.secret,\n };\n }\n\n delete(sandboxId: string, tokenId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/sandbox/${sandboxId}/gateway-token/${tokenId}`);\n }\n}\n","// TelegramClient covers the inbound-control surface for a sandbox's Telegram\n// bot (Feature 2). The bot is a project-scoped TELEGRAM credential attached to\n// the sandbox; these endpoints enable the inbound webhook, mint single-use link\n// codes (pasted in Telegram as `/link <code>`), and list/revoke chat bindings.\n//\n// The link code is returned EXACTLY ONCE at mint time — surface it immediately.\n// The backend stores only its hash.\nimport type { BaseClient } from '../../http/BaseClient.js';\n\nexport interface TelegramBinding {\n id: string;\n telegramChatId: string;\n telegramUserId?: string | null;\n label?: string | null;\n status: string;\n createdAt: string;\n lastUsedAt?: string | null;\n}\n\nexport interface MintLinkCodeResponse {\n code: string;\n expiresInSeconds: number;\n}\n\n/** A chat the bot has seen, surfaced for chat-ID auto-fill during enrolment. */\nexport interface TelegramDiscoveredChat {\n id: string;\n /** private | group | supergroup | channel */\n type: string;\n /** friendly display name (group/channel title, or the user's name) */\n title: string;\n}\n\n/**\n * A chat already linked to a bot credential (via `/link`). Surfaced as a\n * pick-list for the default outbound Chat ID when inbound is enabled and live\n * getUpdates detection is therefore unavailable.\n */\nexport interface TelegramKnownChat {\n id: string;\n /** friendly name captured at link time; absent for older bindings */\n label?: string | null;\n}\n\n/** The bot's identity + state, used to build the \"open your bot\" deep link. */\nexport interface TelegramBotInfo {\n /** bot @username (without the @) — link is https://t.me/<username> */\n username: string;\n name: string;\n /** true when a webhook is set (inbound enabled) — chat detection won't work */\n webhookSet: boolean;\n}\n\nexport class TelegramClient {\n constructor(private readonly http: BaseClient) {}\n\n /**\n * Look up a bot's identity (and whether inbound/webhook is active) from its\n * token, so the UI can show a one-click \"open @bot in Telegram\" link. The\n * token is used server-side transiently and not stored.\n */\n async botInfo(token: string): Promise<TelegramBotInfo> {\n const res = await this.http.post<{ success: boolean; bot?: { username: string; name: string; webhook_set: boolean } }>(\n '/credentials/telegram/bot-info',\n { body: { token } },\n );\n const b = res.bot;\n if (!b) throw new Error('botInfo response missing bot.');\n return { username: b.username, name: b.name, webhookSet: b.webhook_set };\n }\n\n /**\n * Discover the chats a bot can post to, for chat-ID auto-fill during\n * enrolment. The user creates the bot, sends it a message (or adds it to a\n * group/channel), then this returns the chats it has seen — no manual\n * getUpdates call. The token is used server-side transiently and not stored.\n * Returns [] when the bot hasn't been messaged yet.\n */\n async discoverChats(token: string): Promise<TelegramDiscoveredChat[]> {\n const res = await this.http.post<{ success: boolean; chats?: TelegramDiscoveredChat[] }>(\n '/credentials/telegram/discover-chats',\n { body: { token } },\n );\n return res.chats ?? [];\n }\n\n /**\n * List the chats already linked to a bot credential (from `/link`\n * redemptions). Unlike discoverChats (which calls getUpdates and fails while\n * a webhook is active), this reads our stored bindings, so it works precisely\n * when inbound is enabled. Returns [] when nothing has linked yet.\n */\n async knownChats(credentialId: string): Promise<TelegramKnownChat[]> {\n const res = await this.http.get<{ success: boolean; chats?: TelegramKnownChat[] }>(\n `/credentials/telegram/${credentialId}/chats`,\n );\n return res.chats ?? [];\n }\n\n /**\n * Remove the bot's webhook on Telegram (deleteWebhook) so getUpdates chat\n * detection works again. Used to reclaim a bot that still has a webhook from a\n * previous setup (an orphan whose owning credential is gone). Note this frees\n * the bot globally — any inbound on it stops until re-enabled. The token is\n * used server-side transiently and not stored.\n */\n async clearWebhook(token: string): Promise<void> {\n await this.http.post<{ success: boolean }>('/credentials/telegram/clear-webhook', { body: { token } });\n }\n\n /** Enable inbound: register the bot's webhook (anchored at this sandbox). */\n enableInbound(sandboxId: string, credentialId: string): Promise<{ success: boolean }> {\n return this.http.post<{ success: boolean }>(`/sandbox/${sandboxId}/telegram/enable`, {\n body: { credential_id: credentialId },\n });\n }\n\n /** Disable inbound for the bot (bindings are kept; re-enable rekeys). */\n disableInbound(sandboxId: string, credentialId: string): Promise<{ success: boolean }> {\n return this.http.post<{ success: boolean }>(`/sandbox/${sandboxId}/telegram/disable`, {\n body: { credential_id: credentialId },\n });\n }\n\n /**\n * Mint a single-use link code. The plaintext `code` is returned once — show\n * it to the user to paste in Telegram as `/link <code>`.\n */\n async mintLinkCode(sandboxId: string, credentialId: string): Promise<MintLinkCodeResponse> {\n const res = await this.http.post<{ success: boolean; code?: string; expires_in_seconds?: number }>(\n `/sandbox/${sandboxId}/telegram/link-code`,\n { body: { credential_id: credentialId } },\n );\n if (!res.code) {\n throw new Error('mintLinkCode response missing code.');\n }\n return { code: res.code, expiresInSeconds: res.expires_in_seconds ?? 0 };\n }\n\n /** List active chat bindings for this sandbox. */\n async listBindings(sandboxId: string): Promise<TelegramBinding[]> {\n const res = await this.http.get<{ success: boolean; bindings?: TelegramBinding[] }>(\n `/sandbox/${sandboxId}/telegram/bindings`,\n );\n return res.bindings ?? [];\n }\n\n /** Revoke a chat binding — the chat stops driving the agent immediately. */\n revokeBinding(sandboxId: string, bindingId: string): Promise<{ success: boolean }> {\n return this.http.delete<{ success: boolean }>(`/sandbox/${sandboxId}/telegram/bindings/${bindingId}`);\n }\n}\n","// Universal credentials client. Post-credential-redesign (cloud-agent-\n// backend migration 0010) one schema covers every provider: cloud, SSH,\n// GitHub, GitLab, Azure DevOps, OpenAI, Anthropic. Provider-specific\n// fields live inside `metadata`; the catalog at ./providers.ts is the\n// authoritative shape per provider.\n//\n// Surface:\n// apiClient.credentials.list() — every credential in the project\n// apiClient.credentials.create() — one create endpoint, any provider\n// apiClient.credentials.update() — partial update\n// apiClient.credentials.delete() — remove\n// apiClient.credentials.providers() — fetch the catalog\n// apiClient.credentials.sandbox.* — sandbox associations (any provider)\n// apiClient.credentials.gatewayTokens.* — sandbox FOA bearer tokens\n// apiClient.credentials.agentTokens.* — sandbox MCP agent access tokens\nimport type { BaseClient } from '../../http/BaseClient.js';\nimport { AgentTokensClient } from './AgentTokensClient.js';\nimport { GatewayTokensClient } from './GatewayTokensClient.js';\nimport { TelegramClient } from './TelegramClient.js';\nimport {\n Credential,\n CreateCredentialRequest,\n ListCredentialsQuery,\n ProviderID,\n PublishBICredentialRequest,\n RevokeBIPublishRequest,\n SandboxCredential,\n SimpleKeysResponse,\n UpdateCredentialRequest,\n WireSandboxCredential,\n normalizeSandboxCredential,\n} from './types.js';\nimport type { ProviderSpec } from './providers.js';\n\n// ── Sandbox associations ───────────────────────────────────────────────\n\nclass SandboxCredentialScope {\n constructor(private readonly http: BaseClient) {}\n\n async list(sandboxId: string): Promise<SandboxCredential[]> {\n const res = await this.http.get<{ success: boolean; items?: WireSandboxCredential[]; data?: WireSandboxCredential[] }>(\n `/sandbox/${sandboxId}/credential`,\n );\n const list = res.items ?? res.data ?? [];\n return list.map(normalizeSandboxCredential);\n }\n\n attach(sandboxId: string, credentialId: string): Promise<SimpleKeysResponse> {\n return this.http.post<SimpleKeysResponse>(`/sandbox/${sandboxId}/credential`, {\n body: { credentialId },\n });\n }\n\n detach(sandboxId: string, credentialId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/sandbox/${sandboxId}/credential/${credentialId}`);\n }\n}\n\n// ── Top-level credentials client ──────────────────────────────────────\n\nexport class CredentialsClient {\n readonly sandbox: SandboxCredentialScope;\n readonly gatewayTokens: GatewayTokensClient;\n /** Sandbox agent access tokens — bearers external agents use against /mcp. */\n readonly agentTokens: AgentTokensClient;\n /** Sandbox Telegram inbound control — enable webhook, link codes, bindings. */\n readonly telegram: TelegramClient;\n\n constructor(private readonly http: BaseClient) {\n this.sandbox = new SandboxCredentialScope(http);\n this.gatewayTokens = new GatewayTokensClient(http);\n this.agentTokens = new AgentTokensClient(http);\n this.telegram = new TelegramClient(http);\n }\n\n async list(query: ListCredentialsQuery): Promise<Credential[]> {\n const res = await this.http.get<{ success: boolean; credentials?: Credential[]; data?: Credential[] }>(\n '/credentials',\n {\n query: {\n projectId: query.projectId,\n provider: query.provider,\n capability: query.capability,\n },\n },\n );\n return res.credentials ?? res.data ?? [];\n }\n\n async create(body: CreateCredentialRequest): Promise<Credential> {\n const res = await this.http.post<{ success: boolean; data?: Credential; credential?: Credential }>(\n '/credentials',\n { body },\n );\n const value = res.data ?? res.credential;\n if (!value) throw new Error('createCredential response missing body.');\n return value;\n }\n\n async update(credentialId: string, body: UpdateCredentialRequest): Promise<Credential> {\n const res = await this.http.put<{ success: boolean; credential?: Credential; data?: Credential }>(\n `/credentials/${credentialId}`,\n { body },\n );\n const value = res.credential ?? res.data;\n if (!value) throw new Error('updateCredential response missing body.');\n return value;\n }\n\n delete(credentialId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/credentials/${credentialId}`);\n }\n\n /**\n * publishBI (BI-RLS-01) turns a shared/service BI credential from credless\n * into usable by every viewer — the explicit owner/admin sign-off the\n * engine's run-as-viewer gate requires before it will query a shared\n * connection. No-op-equivalent (400) on a per-user-scoped credential, which\n * is already viewer-scoped and never needs publishing.\n */\n async publishBI(credentialId: string, body: PublishBICredentialRequest): Promise<Credential> {\n const res = await this.http.post<{ success: boolean; credential?: Credential; data?: Credential }>(\n `/credentials/${credentialId}/bi-publish`,\n { body },\n );\n const value = res.credential ?? res.data;\n if (!value) throw new Error('publishBI response missing body.');\n return value;\n }\n\n /**\n * revokeBIPublish (BI-RLS-01) reverts a shared BI credential to credless.\n * The prior approval (classification, runsAsLabel, approvedBy/At) is kept\n * on the credential for audit history; only revocation attribution is added.\n */\n async revokeBIPublish(credentialId: string, body: RevokeBIPublishRequest = {}): Promise<Credential> {\n const res = await this.http.delete<{ success: boolean; credential?: Credential; data?: Credential }>(\n `/credentials/${credentialId}/bi-publish`,\n { body },\n );\n const value = res.credential ?? res.data;\n if (!value) throw new Error('revokeBIPublish response missing body.');\n return value;\n }\n\n /**\n * listOrgNotify returns the org-scoped notification credentials (Slack /\n * Teams / PagerDuty / SMTP, workspaceId NULL) — the channels the org owns\n * for platform-event notifications, managed on Settings → System\n * notifications. Distinct from project-scoped notify credentials.\n */\n async listOrgNotify(): Promise<Credential[]> {\n const res = await this.http.get<{ success: boolean; credentials?: Credential[]; data?: Credential[] }>(\n '/credentials/org-notify',\n );\n return res.credentials ?? res.data ?? [];\n }\n\n /**\n * createOrgNotify creates an org-scoped notification credential. The body is\n * the universal credential shape minus projectId/workspaceId (the server\n * pins workspaceId to NULL); provider must be a notify transport.\n */\n async createOrgNotify(\n body: Omit<CreateCredentialRequest, 'projectId' | 'workspaceId'>,\n ): Promise<Credential> {\n const res = await this.http.post<{ success: boolean; data?: Credential; credential?: Credential }>(\n '/credentials/org-notify',\n { body },\n );\n const value = res.data ?? res.credential;\n if (!value) throw new Error('createOrgNotify response missing body.');\n return value;\n }\n\n /**\n * updateOrgNotify applies a partial update to an org-scoped notification\n * credential. Secret is optional — omit it to keep the stored one, supply a\n * new value to rotate it. The server republishes the org topology so the\n * change reaches consumers without a refresh round-trip.\n */\n async updateOrgNotify(credentialId: string, body: UpdateCredentialRequest): Promise<Credential> {\n const res = await this.http.put<{ success: boolean; credential?: Credential; data?: Credential }>(\n `/credentials/org-notify/${credentialId}`,\n { body },\n );\n const value = res.credential ?? res.data;\n if (!value) throw new Error('updateOrgNotify response missing body.');\n return value;\n }\n\n deleteOrgNotify(credentialId: string): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(`/credentials/org-notify/${credentialId}`);\n }\n\n /**\n * adminDeliver seeds a credential into ANOTHER org's project — the\n * platform-admin delivery path for eval-sandbox credentials. The caller\n * must be a platform admin; the target org comes from the path (no\n * impersonation involved) and the audit event lands in the target org's\n * trail. The server accepts cloud (storage-capable) providers only.\n * Optional `metadata.expiresAt` (RFC3339) marks a time-bound credential\n * so the tenant UI can badge the upcoming sandbox expiry.\n */\n async adminDeliver(orgId: string, body: CreateCredentialRequest): Promise<Credential> {\n const res = await this.http.post<{ success: boolean; data?: Credential; credential?: Credential }>(\n `/admin/orgs/${orgId}/credentials`,\n { body },\n );\n const value = res.data ?? res.credential;\n if (!value) throw new Error('adminDeliver response missing body.');\n return value;\n }\n\n /**\n * providers fetches the server-side catalog — the RUNTIME SOURCE OF TRUTH\n * for credential creation/editing and provider categories. It picks up\n * providers added server-side (including the MKT/MTG and BI families, and\n * any customer extension) without a tsclient/frontend release. The static\n * ./providers.ts catalog is an offline fallback only (resolveProviderCatalog).\n *\n * @param product optional product partition ('cloud' | 'bi' | 'meeting' |\n * 'marketing'); the backend filters the catalog to that surface. Omitted →\n * the backend default ('cloud').\n */\n async providers(product?: string): Promise<ProviderSpec[]> {\n const res = await this.http.get<{ success: boolean; providers?: ProviderSpec[]; data?: ProviderSpec[] }>(\n '/providers',\n product ? { query: { product } } : undefined,\n );\n return res.providers ?? res.data ?? [];\n }\n\n /**\n * globalAiProviders returns the AI provider ids the platform \"global\" key\n * pool (admin org's reference project) can serve, e.g. ['ANTHROPIC']. Empty\n * when no platform keys are configured — the UI then hides the non-BYOK\n * provider picker entirely (BYOK-only, as before the feature).\n */\n async globalAiProviders(): Promise<ProviderID[]> {\n const res = await this.http.get<{ success: boolean; providers?: ProviderID[]; data?: ProviderID[] }>(\n '/credentials/global-ai-providers',\n );\n return res.providers ?? res.data ?? [];\n }\n}\n\nexport type { ProviderID };\n","import type { TokenProvider } from '../../http/tokenProvider.js';\nimport type { ChatEvent, ChatScope } from './types.js';\n\nexport interface OpenChatStreamOptions {\n scope: ChatScope;\n conversationId: string;\n onEvent: (event: ChatEvent) => void;\n onError?: (err: Event) => void;\n lastEventId?: string;\n /** Heartbeat in ms before the polyfill considers the connection stale. Default: 60000. */\n heartbeatTimeout?: number;\n}\n\nexport interface ChatStreamHandle {\n close(): void;\n}\n\nexport interface ChatStreamDeps {\n baseUrl: string;\n getToken?: TokenProvider;\n}\n\nconst STREAM_PATH = '/api/agentengine/v1/agent/chat/sessions';\n\n/**\n * Opens an SSE connection to the chat stream. Requires the consumer to have\n * `event-source-polyfill` installed (peer dep). Browsers' native EventSource\n * does not support custom headers, which we need for auth + scope.\n */\nexport async function openChatStream(\n deps: ChatStreamDeps,\n options: OpenChatStreamOptions,\n): Promise<ChatStreamHandle> {\n // Lazy import so consumers in non-browser contexts (or those who don't use\n // the chat stream at all) aren't forced to install the polyfill.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const mod: any = await import('event-source-polyfill');\n const Polyfill = mod.EventSourcePolyfill ?? mod.default?.EventSourcePolyfill ?? mod.default;\n if (!Polyfill) {\n throw new Error('event-source-polyfill is required for client.chat.openStream(). Install it as a peer dep.');\n }\n\n const url = `${deps.baseUrl.replace(/\\/$/, '')}${STREAM_PATH}/${options.conversationId}/stream`;\n\n const headers: Record<string, string> = {\n 'X-Org-Id': options.scope.orgId,\n 'X-User-Id': options.scope.userId,\n 'X-Sandbox-Id': options.scope.sandboxId ?? options.scope.repoId ?? '',\n 'X-Repo-Id': options.scope.sandboxId ?? options.scope.repoId ?? '',\n };\n if (options.scope.projectId ?? options.scope.workspaceId) {\n headers['X-Project-Id'] = options.scope.projectId ?? options.scope.workspaceId ?? '';\n headers['X-Workspace-Id'] = options.scope.projectId ?? options.scope.workspaceId ?? '';\n }\n if (deps.getToken) {\n const token = await deps.getToken();\n if (token) headers['Authorization'] = `Bearer ${token}`;\n }\n if (options.lastEventId) headers['Last-Event-ID'] = options.lastEventId;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const es = new (Polyfill as any)(url, {\n headers,\n heartbeatTimeout: options.heartbeatTimeout ?? 60_000,\n });\n\n // The backend sends named SSE events (event: phase, event: question, …).\n // onmessage only fires for the default unnamed type; addEventListener is required for named events.\n const KNOWN_EVENTS = [\n 'phase', 'question', 'plan_draft',\n 'step_started', 'step_completed', 'step_failed', 'step_progress',\n 'narration', 'assistant_message', 'done',\n 'session_title',\n 'tool_call_started', 'tool_call_finished',\n 'llm_call_finished',\n 'tool_call_confirmation_required',\n 'pending_action_queued', 'artifact_drafted', 'artifact_referenced',\n ];\n\n const handleRaw = (raw: MessageEvent) => {\n try {\n const parsed = JSON.parse(raw.data) as ChatEvent;\n options.onEvent(parsed);\n } catch {\n // Ignore malformed events\n }\n };\n\n for (const name of KNOWN_EVENTS) {\n es.addEventListener(name, handleRaw);\n }\n\n if (options.onError) {\n es.onerror = (event: Event) => options.onError?.(event);\n }\n\n return { close: () => es.close() };\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type { TokenProvider } from '../../http/tokenProvider.js';\nimport { openChatStream, type ChatStreamHandle, type OpenChatStreamOptions } from './ChatStream.js';\nimport type {\n AnswerChatQuestionRequest,\n AnswerChatQuestionResponse,\n CancelChatTurnResponse,\n ChatFeedbackEnvelope,\n ChatScheduleEnvelope,\n ChatScope,\n ConfirmChatToolCallRequest,\n ConfirmChatToolCallResponse,\n CreateChatScheduleRequest,\n CreateChatSessionRequest,\n CreateChatSessionResponse,\n DebugPayload,\n GetChatSessionResponse,\n ListChatFeedbackResponse,\n ListChatSchedulesResponse,\n ListChatScheduleRunsResponse,\n RerunScheduleOccurrenceResponse,\n ListChatSessionsQuery,\n ListChatSessionsResponse,\n PostChatMessageRequest,\n PostChatMessageResponse,\n SubmitChatFeedbackRequest,\n UpdateChatScheduleRequest,\n} from './types.js';\n\nconst BASE_PATH = '/api/agentengine/v1/agent/chat/sessions';\n\nfunction scopeHeaders(scope: ChatScope): Record<string, string> {\n const sandboxId = scope.sandboxId ?? scope.repoId ?? '';\n const projectId = scope.projectId ?? scope.workspaceId;\n const headers: Record<string, string> = {\n 'X-Org-Id': scope.orgId,\n 'X-User-Id': scope.userId,\n 'X-Sandbox-Id': sandboxId,\n 'X-Repo-Id': sandboxId,\n };\n if (projectId) {\n headers['X-Project-Id'] = projectId;\n headers['X-Workspace-Id'] = projectId;\n }\n return headers;\n}\n\nclass ChatSessionsScope {\n constructor(private readonly http: BaseClient) {}\n\n create(scope: ChatScope, body: CreateChatSessionRequest): Promise<CreateChatSessionResponse> {\n return this.http.post<CreateChatSessionResponse>(BASE_PATH, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n list(scope: ChatScope, query: ListChatSessionsQuery = {}): Promise<ListChatSessionsResponse> {\n return this.http.get<ListChatSessionsResponse>(BASE_PATH, {\n query,\n headers: scopeHeaders(scope),\n });\n }\n\n get(scope: ChatScope, conversationId: string): Promise<GetChatSessionResponse> {\n return this.http.get<GetChatSessionResponse>(`${BASE_PATH}/${conversationId}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n delete(scope: ChatScope, conversationId: string): Promise<void> {\n return this.http.delete<void>(`${BASE_PATH}/${conversationId}`, {\n headers: scopeHeaders(scope),\n });\n }\n}\n\nclass ChatMessagesScope {\n constructor(private readonly http: BaseClient) {}\n\n post(scope: ChatScope, conversationId: string, body: PostChatMessageRequest): Promise<PostChatMessageResponse> {\n return this.http.post<PostChatMessageResponse>(`${BASE_PATH}/${conversationId}/messages`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Interrupts an in-flight chat-loop turn. The engine cancels the turn's\n * Go context and asks the sandbox service to kill any in-flight docker\n * exec inside the per-session container (the container itself survives\n * so the next turn keeps its filesystem state). Returns 404 when no\n * turn matches `turnId` — covers the race where the user clicks Stop\n * just after the turn already finished.\n *\n * The engine still emits a terminal `done` SSE event with\n * status=\"context_cancelled\" after this returns; the frontend should\n * render its \"Cancelled\" marker on that event rather than on this\n * response, so a reload mid-cancel still ends in the same UI state.\n */\n cancel(scope: ChatScope, conversationId: string, turnId: string): Promise<CancelChatTurnResponse> {\n return this.http.post<CancelChatTurnResponse>(\n `${BASE_PATH}/${conversationId}/messages/${turnId}/cancel`,\n { headers: scopeHeaders(scope) },\n );\n }\n\n /**\n * Deliver the user's allow/deny decision on an M3 confirmation modal\n * (fired when the policy hook emits a\n * `tool_call_confirmation_required` SSE event). The chat-loop has\n * suspended waiting on this call; on allow it dispatches the tool, on\n * deny it synthesises a \"DENIED:\" tool result so the model can react.\n * Returns 404 when no pending confirmation exists for the given\n * (turn, tool_call) — usually means the 4-minute confirmer timeout\n * already elapsed.\n */\n confirmToolCall(\n scope: ChatScope,\n conversationId: string,\n turnId: string,\n toolCallId: string,\n body: ConfirmChatToolCallRequest,\n ): Promise<ConfirmChatToolCallResponse> {\n return this.http.post<ConfirmChatToolCallResponse>(\n `${BASE_PATH}/${conversationId}/messages/${turnId}/confirm/${toolCallId}`,\n { body, headers: scopeHeaders(scope) },\n );\n }\n}\n\nclass ChatQuestionsScope {\n constructor(private readonly http: BaseClient) {}\n\n answer(\n scope: ChatScope,\n conversationId: string,\n turnId: string,\n body: AnswerChatQuestionRequest,\n ): Promise<AnswerChatQuestionResponse> {\n return this.http.post<AnswerChatQuestionResponse>(\n `${BASE_PATH}/${conversationId}/messages/${turnId}/answers`,\n { body, headers: scopeHeaders(scope) },\n );\n }\n}\n\n/**\n * Debug scope — fetches the consolidated payload (session, messages) used by\n * the dashboard Debug tab. Keyed by conversation ID.\n */\nclass ChatDebugScope {\n constructor(private readonly http: BaseClient) {}\n\n getByConversation(scope: ChatScope, conversationId: string): Promise<DebugPayload> {\n return this.http.get<DebugPayload>(`${BASE_PATH}/${conversationId}/debug`, {\n headers: scopeHeaders(scope),\n });\n }\n}\n\n/**\n * Schedules scope — manages the M3 Stage 4 cron-driven prompt\n * schedules. Repo-scoped: list / create / get / update / delete are\n * keyed by (repo, schedule_id). The dispatcher fires due schedules\n * server-side on its tick; the SDK only handles the CRUD surface.\n *\n * Endpoint shape:\n * GET /v1/agent/repos/:repo_id/schedules\n * POST /v1/agent/repos/:repo_id/schedules\n * GET /v1/agent/repos/:repo_id/schedules/:id\n * PUT /v1/agent/repos/:repo_id/schedules/:id\n * DELETE /v1/agent/repos/:repo_id/schedules/:id\n */\nclass ChatSchedulesScope {\n constructor(private readonly http: BaseClient) {}\n\n private repoPath(scope: ChatScope): string {\n const repoID = scope.sandboxId ?? scope.repoId ?? '';\n return `/api/agentengine/v1/agent/repos/${repoID}/schedules`;\n }\n\n list(scope: ChatScope): Promise<ListChatSchedulesResponse> {\n return this.http.get<ListChatSchedulesResponse>(this.repoPath(scope), {\n headers: scopeHeaders(scope),\n });\n }\n\n create(scope: ChatScope, body: CreateChatScheduleRequest): Promise<ChatScheduleEnvelope> {\n return this.http.post<ChatScheduleEnvelope>(this.repoPath(scope), {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n get(scope: ChatScope, scheduleId: string): Promise<ChatScheduleEnvelope> {\n return this.http.get<ChatScheduleEnvelope>(`${this.repoPath(scope)}/${scheduleId}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n update(\n scope: ChatScope,\n scheduleId: string,\n body: UpdateChatScheduleRequest,\n ): Promise<ChatScheduleEnvelope> {\n return this.http.put<ChatScheduleEnvelope>(`${this.repoPath(scope)}/${scheduleId}`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n delete(scope: ChatScope, scheduleId: string): Promise<{ status: 'deleted' }> {\n return this.http.delete<{ status: 'deleted' }>(`${this.repoPath(scope)}/${scheduleId}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * List recent chat sessions spawned by a schedule's cron tick — used\n * by the SchedulesTab \"Runs\" panel to surface real audit trail\n * instead of dumping the user into the global chat list.\n *\n * Each entry is a full ChatSession row; `.id` is the conversation id\n * the dashboard navigates to (`/chat/:conversationId`). All rows are\n * unattended (the scheduler is the only writer of `schedule_id`),\n * which makes the chat session viewer render the \"Scheduled run\"\n * ribbon and hide the composer.\n *\n * Server returns the 50 most-recent rows; no cursor pagination in\n * v1 (deferred until the long-tail audit case proves real).\n */\n listRuns(scope: ChatScope, scheduleId: string): Promise<ListChatScheduleRunsResponse> {\n return this.http.get<ListChatScheduleRunsResponse>(\n `${this.repoPath(scope)}/${scheduleId}/runs`,\n { headers: scopeHeaders(scope) },\n );\n }\n\n /**\n * Manually re-run ONE occurrence of a product schedule (SHR-IP06 §6 item 4 /\n * REV-07) — the owner's explicit recovery of a superseded/expired occurrence,\n * or any due window they choose to re-run. `dueWindow` is the occurrence's\n * scheduled instant (RFC3339); the server derives the occurrence key from\n * (schedule, dueWindow), so a re-run against an in-flight occurrence coalesces\n * to one run. The run is asynchronous — the server returns 202 with the\n * derived `occurrence_key`.\n */\n rerunOccurrence(\n scope: ChatScope,\n scheduleId: string,\n dueWindow: string,\n ): Promise<RerunScheduleOccurrenceResponse> {\n return this.http.post<RerunScheduleOccurrenceResponse>(\n `${this.repoPath(scope)}/${scheduleId}/rerun`,\n { body: { due_window: dueWindow }, headers: scopeHeaders(scope) },\n );\n }\n}\n\n/**\n * Feedback scope — a user's \"Satisfied? Yes/No\" rating + optional comment on a\n * chat session, and the list of feedback recorded for it (so the UI can\n * pre-fill and so an org admin can review past ratings). Conversation-scoped;\n * pass `turn_id` in the body to scope feedback to a single turn.\n *\n * Endpoint shape:\n * POST /v1/agent/chat/sessions/:id/feedback\n * GET /v1/agent/chat/sessions/:id/feedback\n */\nclass ChatFeedbackScope {\n constructor(private readonly http: BaseClient) {}\n\n submit(\n scope: ChatScope,\n conversationId: string,\n body: SubmitChatFeedbackRequest,\n ): Promise<ChatFeedbackEnvelope> {\n return this.http.post<ChatFeedbackEnvelope>(`${BASE_PATH}/${conversationId}/feedback`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n list(scope: ChatScope, conversationId: string): Promise<ListChatFeedbackResponse> {\n return this.http.get<ListChatFeedbackResponse>(`${BASE_PATH}/${conversationId}/feedback`, {\n headers: scopeHeaders(scope),\n });\n }\n}\n\nexport class ChatClient {\n readonly sessions: ChatSessionsScope;\n readonly messages: ChatMessagesScope;\n readonly questions: ChatQuestionsScope;\n readonly debug: ChatDebugScope;\n readonly schedules: ChatSchedulesScope;\n readonly feedback: ChatFeedbackScope;\n\n constructor(\n private readonly http: BaseClient,\n private readonly streamDeps: { baseUrl: string; getToken?: TokenProvider },\n ) {\n this.sessions = new ChatSessionsScope(http);\n this.messages = new ChatMessagesScope(http);\n this.questions = new ChatQuestionsScope(http);\n this.debug = new ChatDebugScope(http);\n this.schedules = new ChatSchedulesScope(http);\n this.feedback = new ChatFeedbackScope(http);\n }\n\n openStream(options: OpenChatStreamOptions): Promise<ChatStreamHandle> {\n return openChatStream(this.streamDeps, options);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n CreateAgentTemplateRequest,\n ListAgentTemplatesQuery,\n ListAgentTemplatesResponse,\n SimpleAgentResponse,\n Template,\n} from './types.js';\n\nconst BASE_PATH = '/api/agentengine/v1/agent/templates';\n\nexport class TemplatesClient {\n constructor(private readonly http: BaseClient) {}\n\n list(query: ListAgentTemplatesQuery = {}): Promise<ListAgentTemplatesResponse> {\n return this.http.get<ListAgentTemplatesResponse>(BASE_PATH, { query });\n }\n\n create(body: CreateAgentTemplateRequest): Promise<Template> {\n return this.http.post<Template>(BASE_PATH, { body });\n }\n\n delete(templateId: string): Promise<SimpleAgentResponse> {\n return this.http.delete<SimpleAgentResponse>(`${BASE_PATH}/${templateId}`);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n CreateScheduledTaskRequest,\n ListScheduledTasksQuery,\n ListScheduledTasksResponse,\n ScheduledTask,\n SimpleAgentResponse,\n} from './types.js';\n\nconst BASE_PATH = '/api/agentengine/v1/agent/scheduled-tasks';\n\nexport class ScheduledTasksClient {\n constructor(private readonly http: BaseClient) {}\n\n list(query: ListScheduledTasksQuery): Promise<ListScheduledTasksResponse> {\n return this.http.get<ListScheduledTasksResponse>(BASE_PATH, { query });\n }\n\n create(body: CreateScheduledTaskRequest): Promise<ScheduledTask> {\n return this.http.post<ScheduledTask>(BASE_PATH, { body });\n }\n\n delete(taskId: string, orgId: string): Promise<SimpleAgentResponse> {\n return this.http.delete<SimpleAgentResponse>(`${BASE_PATH}/${taskId}`, {\n query: { org_id: orgId },\n });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n AcquireScanLeaseRequest,\n AcquireScanLeaseResponse,\n ListScanHistoryQuery,\n ListScanHistoryResponse,\n PeekScanLeaseResponse,\n ResourceTreeQuery,\n ResourceTreeResponse,\n SubgraphRequest,\n SubgraphResponse,\n} from './types.js';\n\nexport class ResourcesClient {\n constructor(private readonly http: BaseClient) {}\n\n getTree(repoId: string, query?: ResourceTreeQuery): Promise<ResourceTreeResponse> {\n const params = new URLSearchParams();\n const search = query?.search?.trim();\n if (search) params.set('search', search);\n if (query?.showDefault === true) params.set('showDefault', 'true');\n const qs = params.size > 0 ? `?${params.toString()}` : '';\n return this.http.get<ResourceTreeResponse>(`/repos/${repoId}/resources/tree${qs}`);\n }\n\n /**\n * BFS-walks the dependency graph starting from `seedResourceIds` (or\n * `seedNameTokens`) and returns the matching nodes + edges. Use this\n * to render an inbound/outbound dependency view for a selected\n * resource. The server caps the result at maxNodes (default 80,\n * hard cap 200) and sets `truncated` when the cap was hit.\n */\n getSubgraph(repoId: string, request: SubgraphRequest): Promise<SubgraphResponse> {\n return this.http.post<SubgraphResponse>(`/repos/${repoId}/resources/subgraph`, { body: request });\n }\n\n /**\n * Returns recent scan history for a repo, optionally filtered by\n * credential. Backed by CloudScanHistory rows written when the\n * agent's discovery orchestrator releases a lease (or when the\n * backend's cleanup job sweeps an expired one). Use this to render\n * \"last refreshed N min ago\" badges and per-scope add/remove counts\n * next to the resource tree.\n */\n listScans(repoId: string, query?: ListScanHistoryQuery): Promise<ListScanHistoryResponse> {\n const params = new URLSearchParams();\n if (query?.credentialId) params.set('credentialId', query.credentialId);\n if (query?.limit != null) params.set('limit', String(query.limit));\n const qs = params.size > 0 ? `?${params.toString()}` : '';\n return this.http.get<ListScanHistoryResponse>(`/repos/${repoId}/scans${qs}`);\n }\n\n /**\n * Peeks the active scan lease (if any) for the given credential. Used\n * by the dashboard to display a \"scan in progress\" badge without\n * attempting to acquire the lease. Returns `lease: null` when no\n * scan is running. Expired leases are returned with their stale\n * timestamps — callers should compare `expiresAt` to `Date.now()`\n * before treating them as active.\n */\n peekScanLease(repoId: string, credentialId: string): Promise<PeekScanLeaseResponse> {\n const params = new URLSearchParams();\n params.set('credentialId', credentialId);\n return this.http.get<PeekScanLeaseResponse>(`/repos/${repoId}/scans/lease?${params.toString()}`);\n }\n\n /**\n * Attempts to claim a scan lease. Returns the acquired lease on\n * success. The server responds 409 with a `ScanInProgressError`-\n * shaped body when another scan is already in flight — callers\n * should catch the HttpError, parse the body, and surface a polite\n * \"another scan is running\" notice rather than retry automatically.\n *\n * NOTE: routine use is the agent's job. The dashboard typically only\n * calls peekScanLease + listScans; this method is exposed for power-\n * user tooling and automated test harnesses.\n */\n acquireScanLease(repoId: string, request: AcquireScanLeaseRequest): Promise<AcquireScanLeaseResponse> {\n return this.http.post<AcquireScanLeaseResponse>(`/repos/${repoId}/scans/lease`, { body: request });\n }\n}\n","export interface SystemEvent {\n id: number;\n timestamp: string;\n contextId: string;\n context: string;\n event: string;\n orgId: string;\n userId: string;\n userName: string;\n userEmail: string;\n projectId: string | null;\n jsonData: string | null;\n showUnread: boolean;\n}\n\nexport interface WireSystemEvent extends Omit<SystemEvent, 'projectId'> {\n workspaceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface SystemEventQuery {\n from_timestamp?: number;\n to_timestamp?: number;\n contextId?: string;\n context?: string;\n event?: string;\n userId?: string;\n projectId?: string;\n /** @deprecated use `projectId` */\n workspaceId?: string;\n showUnread?: boolean;\n skip?: number;\n take?: number;\n}\n\nexport interface SystemEventQueryResponse {\n events: SystemEvent[];\n total: number;\n skip: number;\n take: number;\n}\n\nexport interface SystemEventReadResponse {\n success: true;\n}\n\nexport function normalizeSystemEvent(wire: WireSystemEvent): SystemEvent {\n return {\n id: wire.id,\n timestamp: wire.timestamp,\n contextId: wire.contextId,\n context: wire.context,\n event: wire.event,\n orgId: wire.orgId,\n userId: wire.userId,\n userName: wire.userName,\n userEmail: wire.userEmail,\n projectId: wire.projectId ?? wire.workspaceId ?? null,\n jsonData: wire.jsonData ?? null,\n showUnread: wire.showUnread,\n };\n}\n\n// TODO(backend-cleanup): cloud-agent-backend/internal/domain/types.go SystemEvent\n// still emits `workspaceId`. When that becomes `projectId`, this normalizer\n// collapses to identity.\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport {\n normalizeSystemEvent,\n SystemEventQuery,\n SystemEventQueryResponse,\n SystemEventReadResponse,\n WireSystemEvent,\n} from './types.js';\n\ninterface WireQueryResponse {\n events: WireSystemEvent[];\n total: number;\n skip: number;\n take: number;\n}\n\nexport class SystemEventsClient {\n constructor(private readonly http: BaseClient) {}\n\n async query(body: SystemEventQuery): Promise<SystemEventQueryResponse> {\n const wire = await this.http.post<WireQueryResponse>('/systemevent', { body });\n return {\n events: (wire.events ?? []).map(normalizeSystemEvent),\n total: wire.total ?? 0,\n skip: wire.skip ?? 0,\n take: wire.take ?? 0,\n };\n }\n\n markRead(eventIdOrIds: number | number[]): Promise<SystemEventReadResponse> {\n const body = Array.isArray(eventIdOrIds) ? { ids: eventIdOrIds } : { id: eventIdOrIds };\n return this.http.post<SystemEventReadResponse>('/systemevent/read', { body });\n }\n\n markUnread(eventIdOrIds: number | number[]): Promise<SystemEventReadResponse> {\n const body = Array.isArray(eventIdOrIds) ? { ids: eventIdOrIds } : { id: eventIdOrIds };\n return this.http.delete<SystemEventReadResponse>('/systemevent/read', { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n BuySubscriptionRequest,\n BuySubscriptionResponse,\n CancelSubscriptionResponse,\n ListPaymentsResponse,\n OrgSubscription,\n Payment,\n PreviewChangeRequest,\n PreviewChangeResponse,\n Subscription,\n} from './types.js';\n\nexport class SubscriptionsClient {\n constructor(private readonly http: BaseClient) {}\n\n async listCatalog(): Promise<Subscription[]> {\n const res = await this.http.get<{ success: boolean; data: Subscription[] }>('/subscriptions', { skipAuth: true });\n return res.data ?? [];\n }\n\n async getMine(): Promise<OrgSubscription | null> {\n const res = await this.http.get<{ success: boolean; data: OrgSubscription | null }>('/subscriptions/my');\n return res.data ?? null;\n }\n\n buy(body: BuySubscriptionRequest): Promise<BuySubscriptionResponse> {\n return this.http.post<BuySubscriptionResponse>('/subscriptions/buy', { body });\n }\n\n /**\n * Preview the cost/credit impact of a plan change (pro-rated charge,\n * credit delta, effective dates) for the confirmation modal — no change\n * is made. kind=\"new\" means a first purchase that would go via Checkout.\n */\n previewChange(body: PreviewChangeRequest): Promise<PreviewChangeResponse> {\n return this.http.post<PreviewChangeResponse>('/subscriptions/preview-change', { body });\n }\n\n cancel(): Promise<CancelSubscriptionResponse> {\n return this.http.post<CancelSubscriptionResponse>('/subscriptions/cancel', {});\n }\n\n async listPayments(): Promise<Payment[]> {\n const res = await this.http.get<ListPaymentsResponse>('/subscriptions/payments');\n return res.data ?? [];\n }\n\n /** Stripe-hosted billing portal URL. */\n async portal(): Promise<{ url: string }> {\n const res = await this.http.post<{ success: boolean; data: { url: string } }>('/subscriptions/portal', {});\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n BuyCreditPackRequest,\n BuyCreditPackResponse,\n BuyCustomCreditRequest,\n BuyCustomCreditResponse,\n CreditBalance,\n CreditPack,\n CustomCreditPurchaseConfig,\n ListCreditsTransactionsQuery,\n ListCreditsTransactionsResponse,\n MonthlyCreditStats,\n} from './types.js';\n\nexport class CreditsClient {\n constructor(private readonly http: BaseClient) {}\n\n async getBalance(): Promise<CreditBalance> {\n const res = await this.http.get<{ success: boolean; data: CreditBalance }>('/credits/balance');\n return unwrapData(res);\n }\n\n listTransactions(query: ListCreditsTransactionsQuery = {}): Promise<ListCreditsTransactionsResponse> {\n return this.http.get<ListCreditsTransactionsResponse>('/credits/transactions', { query });\n }\n\n /** Per-month credit activity (consumption / purchases / grants). */\n async getMonthlyStats(): Promise<MonthlyCreditStats[]> {\n const res = await this.http.get<{ success: boolean; data: MonthlyCreditStats[] }>('/credits/stats/monthly');\n return res.data ?? [];\n }\n\n /** Fixed credit-pack catalog. Public endpoint. */\n async listPacks(): Promise<CreditPack[]> {\n const res = await this.http.get<{ success: boolean; data: CreditPack[] }>('/credits/packs', { skipAuth: true });\n return res.data ?? [];\n }\n\n /**\n * Buy a fixed credit pack. Requires an active paid subscription\n * (the backend 403s free-tier orgs with SUBSCRIPTION_REQUIRED) and\n * caps purchases per pack per billing cycle. Returns a Stripe\n * Checkout URL to redirect to.\n */\n buyPack(body: BuyCreditPackRequest): Promise<BuyCreditPackResponse> {\n return this.http.post<BuyCreditPackResponse>('/credits/packs/buy', { body });\n }\n\n /**\n * \"Other amount\" PAYG config — bounds + presets for the\n * arbitrary-dollar tile. Public endpoint; returns a disabled\n * shape (`enabled: false`) when the feature is off so the\n * frontend can hide the tile without throwing.\n */\n async getCustomConfig(): Promise<CustomCreditPurchaseConfig> {\n const res = await this.http.get<{ success: boolean; data: CustomCreditPurchaseConfig }>('/credits/packs/custom-config');\n return unwrapData(res);\n }\n\n /**\n * Buy an arbitrary-dollar PAYG amount. The Stripe Checkout\n * session is built with `price_data` inline (no pre-created\n * Price), so the catalog has nothing to provision for this — it\n * is purely a per-purchase flow.\n */\n buyCustom(body: BuyCustomCreditRequest): Promise<BuyCustomCreditResponse> {\n return this.http.post<BuyCustomCreditResponse>('/credits/packs/buy-custom', { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n GetUsageSummaryQuery,\n GetUsageSummaryResponse,\n UsageByModelQuery,\n UsageByModelResponse,\n UsageReportQuery,\n UsageReportResponse,\n UsageSummaryQuery,\n UsageSummaryResponse,\n} from './types.js';\n\nconst LEGACY_AGENT_PATH = '/api/agentengine/v1/usage'; // legacy proxy path\nconst SCOPED_BASE = '/usage'; // new backend-scoped surface (RBAC + scope routing)\n\nexport class UsageClient {\n constructor(private readonly http: BaseClient) {}\n\n // ── legacy ─────────────────────────────────────────────────────────────────\n // Existing Settings → Usage page calls this. Kept for back-compat until the\n // new dashboard fully replaces the JSON dump.\n getSummary(query: GetUsageSummaryQuery): Promise<GetUsageSummaryResponse> {\n return this.http.get<GetUsageSummaryResponse>(`${LEGACY_AGENT_PATH}/summary`, { query });\n }\n\n // ── new scoped surface ─────────────────────────────────────────────────────\n // Hits the backend-side RBAC wrapper; the backend re-injects the scope id\n // into the agent query so we don't have to.\n org(query: UsageSummaryQuery = {}): Promise<UsageSummaryResponse> {\n return this.http.get(`${SCOPED_BASE}/org`, { query: query as Record<string, string> });\n }\n project(projectId: string, query: UsageSummaryQuery = {}): Promise<UsageSummaryResponse> {\n return this.http.get(`${SCOPED_BASE}/project/${encodeURIComponent(projectId)}`, { query: query as Record<string, string> });\n }\n sandbox(sandboxId: string, query: UsageSummaryQuery = {}): Promise<UsageSummaryResponse> {\n return this.http.get(`${SCOPED_BASE}/sandbox/${encodeURIComponent(sandboxId)}`, { query: query as Record<string, string> });\n }\n chat(chatId: string, query: UsageSummaryQuery = {}): Promise<UsageSummaryResponse> {\n return this.http.get(`${SCOPED_BASE}/chat/${encodeURIComponent(chatId)}`, { query: query as Record<string, string> });\n }\n\n // Each report variant exists so the dashboard chart can request hourly /\n // daily buckets without leaking scope routing into the caller.\n orgReport(query: UsageReportQuery = {}): Promise<UsageReportResponse> {\n return this.http.get(`${SCOPED_BASE}/org`, { query: { ...(query as Record<string, string>), kind: 'report' } });\n }\n projectReport(projectId: string, query: UsageReportQuery = {}): Promise<UsageReportResponse> {\n return this.http.get(`${SCOPED_BASE}/project/${encodeURIComponent(projectId)}`, { query: { ...(query as Record<string, string>), kind: 'report' } });\n }\n sandboxReport(sandboxId: string, query: UsageReportQuery = {}): Promise<UsageReportResponse> {\n return this.http.get(`${SCOPED_BASE}/sandbox/${encodeURIComponent(sandboxId)}`, { query: { ...(query as Record<string, string>), kind: 'report' } });\n }\n chatReport(chatId: string, query: UsageReportQuery = {}): Promise<UsageReportResponse> {\n return this.http.get(`${SCOPED_BASE}/chat/${encodeURIComponent(chatId)}`, { query: { ...(query as Record<string, string>), kind: 'report' } });\n }\n\n // Per-model breakdown — drives the table under the bar chart.\n orgByModel(query: UsageByModelQuery = {}): Promise<UsageByModelResponse> {\n return this.http.get(`${SCOPED_BASE}/org`, { query: { ...(query as Record<string, string>), kind: 'by_model' } });\n }\n projectByModel(projectId: string, query: UsageByModelQuery = {}): Promise<UsageByModelResponse> {\n return this.http.get(`${SCOPED_BASE}/project/${encodeURIComponent(projectId)}`, { query: { ...(query as Record<string, string>), kind: 'by_model' } });\n }\n sandboxByModel(sandboxId: string, query: UsageByModelQuery = {}): Promise<UsageByModelResponse> {\n return this.http.get(`${SCOPED_BASE}/sandbox/${encodeURIComponent(sandboxId)}`, { query: { ...(query as Record<string, string>), kind: 'by_model' } });\n }\n chatByModel(chatId: string, query: UsageByModelQuery = {}): Promise<UsageByModelResponse> {\n return this.http.get(`${SCOPED_BASE}/chat/${encodeURIComponent(chatId)}`, { query: { ...(query as Record<string, string>), kind: 'by_model' } });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n ActReceiptLinesResponse,\n ActRunsResponse,\n ActionApproversResponse,\n ActionClassesResponse,\n ActionPoliciesResponse,\n ActionPolicyEventsResponse,\n ApprovalStats,\n ApprovalsScope,\n DeleteActionPolicyRequest,\n ListApprovalsQuery,\n ListApprovalsResponse,\n PendingAction,\n PolicyScopeType,\n RebindApprovalResponse,\n ResolveApprovalRequest,\n ResolveApprovalResponse,\n ResolveBatchRequest,\n ResolveBatchResponse,\n ResolveOutcomeRequest,\n ResolveOutcomeResponse,\n SetActionApproversRequest,\n SetActionPolicyRequest,\n} from './types.js';\n\n/**\n * Action Policy client.\n *\n * Two API families, gated in different places, because the engine never sees\n * org roles:\n *\n * - the QUEUE (read, resolve, batch, class registry) is member-level and goes\n * straight through the wildcard agent-engine proxy;\n * - POLICY and APPROVER writes are org-admin-only and go through thin backend\n * routes, because that is where roles live. The proxy denies the equivalent\n * engine paths, so these methods are the only way in.\n */\nconst QUEUE_BASE = '/api/agentengine/v1/agent';\nconst ORG_BASE = '/organization';\n\nfunction scopeHeaders(scope: ApprovalsScope): Record<string, string> {\n const headers: Record<string, string> = {\n 'X-Org-Id': scope.orgId,\n 'X-User-Id': scope.userId,\n };\n if (scope.sandboxId) {\n headers['X-Sandbox-Id'] = scope.sandboxId;\n headers['X-Repo-Id'] = scope.sandboxId;\n }\n return headers;\n}\n\nfunction queryString(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n}\n\nexport class ApprovalsClient {\n constructor(private readonly http: BaseClient) {}\n\n // ── queue (member-level) ────────────────────────────────────────────────\n\n /** List queue entries and execution receipts. `tool_args` is omitted here. */\n list(scope: ApprovalsScope, query: ListApprovalsQuery = {}): Promise<ListApprovalsResponse> {\n return this.http.get(`${QUEUE_BASE}/approvals${queryString({ ...query })}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /** Queue telemetry — powers the sidebar badge and the health view. */\n stats(scope: ApprovalsScope): Promise<ApprovalStats> {\n return this.http.get(`${QUEUE_BASE}/approvals/stats`, { headers: scopeHeaders(scope) });\n }\n\n /** Full detail for one entry, including the frozen `tool_args`. */\n get(scope: ApprovalsScope, id: string): Promise<PendingAction> {\n return this.http.get(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Approve or reject one entry.\n *\n * Throws on 409 when somebody else already resolved it; the response body\n * carries the status it actually has now, so the caller should refetch\n * rather than retry.\n */\n resolve(\n scope: ApprovalsScope,\n id: string,\n body: ResolveApprovalRequest,\n ): Promise<ResolveApprovalResponse> {\n return this.http.post(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}/resolve`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Point a PENDING artifact-backed action at a newer version of the same\n * artifact — the edit-under-queue rebind.\n *\n * An explicit one-click act, not something that happens on every save: the\n * old proposal's frozen payload is never mutated. The old row is cancelled\n * and a new one inserted IN ONE TRANSACTION, so a partial failure can never\n * leave two live approvals for one intent.\n *\n * `newHandle` is the handle of the version to send instead. 409 means\n * somebody resolved the old row first; 400 means it carries no artifact.\n */\n rebind(scope: ApprovalsScope, id: string, newHandle: string): Promise<RebindApprovalResponse> {\n return this.http.post(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}/rebind`, {\n body: { new_handle: newHandle },\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Resolve many entries at once. Per-entry outcomes: an id somebody else\n * already resolved lands in `skipped` rather than failing the batch.\n */\n resolveBatch(scope: ApprovalsScope, body: ResolveBatchRequest): Promise<ResolveBatchResponse> {\n return this.http.post(`${QUEUE_BASE}/approvals/resolve-batch`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Per-destination receipt lines for one entry — the durable ledger behind\n * the receipt's `destinations` array. Each line carries the evidence level\n * the destination actually earned, never a bare \"delivered\".\n */\n receiptLines(scope: ApprovalsScope, id: string): Promise<ActReceiptLinesResponse> {\n return this.http.get(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}/receipt-lines`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * Close an `outcome_unknown` entry through the closed manual-resolution\n * set: confirmed-effect, confirmed-no-effect, or abandoned. The note is\n * required — the engine rejects an empty one with 400. Throws on 409\n * `already_resolved` when somebody else closed it first; the body carries\n * the status it actually has now, so refetch rather than retry.\n */\n resolveOutcome(\n scope: ApprovalsScope,\n id: string,\n body: ResolveOutcomeRequest,\n ): Promise<ResolveOutcomeResponse> {\n return this.http.post(`${QUEUE_BASE}/approvals/${encodeURIComponent(id)}/resolve-outcome`, {\n body,\n headers: scopeHeaders(scope),\n });\n }\n\n /** Recent act-run occurrence records — the per-trigger execution ledger. */\n listRuns(scope: ApprovalsScope, limit?: number): Promise<ActRunsResponse> {\n return this.http.get(`${QUEUE_BASE}/act-runs${queryString({ limit })}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /**\n * The compiled class registry. Pass a sandbox id to also resolve each\n * class's effective policy for that scope chain.\n */\n listClasses(scope: ApprovalsScope, sandboxId?: string): Promise<ActionClassesResponse> {\n return this.http.get(`${QUEUE_BASE}/action-classes${queryString({ repo_id: sandboxId })}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n /** Policy audit history, newest first. */\n listPolicyEvents(scope: ApprovalsScope, limit?: number): Promise<ActionPolicyEventsResponse> {\n return this.http.get(`${QUEUE_BASE}/action-policy-events${queryString({ limit })}`, {\n headers: scopeHeaders(scope),\n });\n }\n\n // ── policy configuration (org-admin, via backend) ───────────────────────\n\n /** Read the per-scope overrides at one scope. */\n getPolicies(scopeType: PolicyScopeType, scopeId: string): Promise<ActionPoliciesResponse> {\n return this.http.get(\n `${ORG_BASE}/action-policies${queryString({ scope_type: scopeType, scope_id: scopeId })}`,\n );\n }\n\n /**\n * Set one class's state at a scope.\n *\n * Rejected with 422 `loosens_parent` when the value would widen autonomy\n * relative to the scopes above it: a child may only tighten.\n */\n setPolicy(body: SetActionPolicyRequest): Promise<{ ok: boolean }> {\n return this.http.put(`${ORG_BASE}/action-policies`, { body });\n }\n\n /** Remove an override so the class inherits again. */\n clearPolicy(body: DeleteActionPolicyRequest): Promise<{ ok: boolean }> {\n return this.http.delete(`${ORG_BASE}/action-policies`, { body });\n }\n\n /** The ordered escalation list. */\n getApprovers(): Promise<ActionApproversResponse> {\n return this.http.get(`${ORG_BASE}/action-approvers`);\n }\n\n /** Replace the escalation list; array order is the escalation order. */\n setApprovers(body: SetActionApproversRequest): Promise<{ ok: boolean }> {\n return this.http.put(`${ORG_BASE}/action-approvers`, { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n ChatBudget,\n EffectiveChatBudget,\n OrgBudget,\n ScopedBudget,\n UpdateChatBudgetRequest,\n UpdateCostLimitRequest,\n UpdateOrgBudgetRequest,\n UpdateScopedBudgetRequest,\n} from './types.js';\n\n// Backend routes hang off the root authed group — see internal/http/routes/budgets\n// in cloud-agent-backend. The backend resolves project_id → sandbox_id mapping\n// and handles RBAC; the frontend just hands it the scope ids.\nconst BASE = '/budgets';\n\nexport class BudgetsClient {\n constructor(private readonly http: BaseClient) {}\n\n // ── org ──\n getOrg(): Promise<{ budget: OrgBudget }> {\n return this.http.get(`${BASE}/org`);\n }\n updateOrg(body: UpdateOrgBudgetRequest): Promise<{ budget: OrgBudget; message: string }> {\n return this.http.put(`${BASE}/org`, { body });\n }\n\n // ── project (workspace) ──\n getProject(projectId: string): Promise<{ budget: ScopedBudget }> {\n return this.http.get(`${BASE}/project/${encodeURIComponent(projectId)}`);\n }\n updateProject(projectId: string, body: UpdateScopedBudgetRequest): Promise<{ budget: ScopedBudget; message: string }> {\n return this.http.put(`${BASE}/project/${encodeURIComponent(projectId)}`, { body });\n }\n\n // ── sandbox (repo) ──\n getSandbox(sandboxId: string): Promise<{ budget: ScopedBudget }> {\n return this.http.get(`${BASE}/sandbox/${encodeURIComponent(sandboxId)}`);\n }\n updateSandbox(sandboxId: string, body: UpdateScopedBudgetRequest): Promise<{ budget: ScopedBudget; message: string }> {\n return this.http.put(`${BASE}/sandbox/${encodeURIComponent(sandboxId)}`, { body });\n }\n\n // ── chat session ──\n getChat(chatId: string): Promise<{ budget: ChatBudget }> {\n return this.http.get(`${BASE}/chat/${encodeURIComponent(chatId)}`);\n }\n updateChat(chatId: string, body: UpdateChatBudgetRequest): Promise<{ message: string }> {\n return this.http.put(`${BASE}/chat/${encodeURIComponent(chatId)}`, { body });\n }\n // Resolves chat → sandbox → project → org and returns the first non-zero\n // per-chat USD cap plus the level it came from. Powers the chat header\n // budget badge — UI labels inherited values.\n getEffectiveChat(chatId: string): Promise<EffectiveChatBudget> {\n return this.http.get(`${BASE}/chat/${encodeURIComponent(chatId)}/effective`);\n }\n\n // ── per-template / per-scheduled USD caps ──\n updateTemplateCostLimit(templateId: string, body: UpdateCostLimitRequest) {\n return this.http.put(`${BASE}/template/${encodeURIComponent(templateId)}/cost_limit`, { body });\n }\n updateScheduleCostLimit(scheduleId: string, body: UpdateCostLimitRequest) {\n return this.http.put(`${BASE}/schedule/${encodeURIComponent(scheduleId)}/cost_limit`, { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type { ProviderCapConfig, SetProviderCapRequest } from './types.js';\n\n// SHR-IP08 per-provider cap configuration. Backend routes hang off the root\n// authed group — see internal/http/routes/provider_caps in cloud-agent-backend.\n// The LIST is a member read; SET and DELETE are admin-only (the backend gates\n// them in-handler and blocks them under impersonation). The org is taken from\n// the session, never a request field.\nconst BASE = '/provider-caps';\n\nexport class MeteringClient {\n constructor(private readonly http: BaseClient) {}\n\n /** List the org's configured per-provider caps. Empty when none are set —\n * every unset provider is the MM-O021 owner gate, not a zero cap. */\n async listCaps(): Promise<ProviderCapConfig[]> {\n const res = await this.http.get<{ items: ProviderCapConfig[] }>(BASE);\n return res.items ?? [];\n }\n\n /** Set (or replace) one provider's cap. Admin-only. The server refuses a\n * non-positive limit or a cap with no scope / reset clock (400). */\n async setCap(provider: string, body: SetProviderCapRequest): Promise<ProviderCapConfig> {\n const res = await this.http.put<{ cap: ProviderCapConfig }>(\n `${BASE}/${encodeURIComponent(provider)}`,\n { body },\n );\n return res.cap;\n }\n\n /** Remove one provider's cap, returning it to the unset MM-O021 gate.\n * Admin-only. Returns whether a cap was removed. */\n async deleteCap(provider: string): Promise<boolean> {\n const res = await this.http.delete<{ deleted: boolean }>(\n `${BASE}/${encodeURIComponent(provider)}`,\n );\n return res.deleted ?? false;\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n MintReferralCodeRequest,\n RedeemReferralCodeRequest,\n ReferralAdminOverview,\n ReferralCode,\n ReferralRedemption,\n ReferralStats,\n} from './types.js';\n\n/**\n * Org self-service referrals. Any org can mint codes and redeem one (subject\n * to server-side guards: never-attributed, not reseller-associated, and\n * pre-first-purchase). Two-sided credits fire once the referred org's\n * cumulative spend reaches the snapshotted threshold.\n */\nexport class ReferralsClient {\n constructor(private readonly http: BaseClient) {}\n\n /** Mint a new referral code for the caller's org. */\n async mintCode(body: MintReferralCodeRequest = {}): Promise<ReferralCode> {\n const res = await this.http.post<{ success: boolean; data: ReferralCode }>('/referrals/codes', { body });\n return unwrapData(res);\n }\n\n /** List the caller org's codes with per-code redeemed/qualified counts. */\n async listCodes(): Promise<ReferralCode[]> {\n const res = await this.http.get<{ success: boolean; data: ReferralCode[] }>('/referrals/codes');\n return res.data ?? [];\n }\n\n /** Activate or deactivate one of the caller org's codes. */\n async setCodeActive(codeId: string, isActive: boolean): Promise<ReferralCode> {\n const res = await this.http.patch<{ success: boolean; data: ReferralCode }>(\n `/referrals/codes/${codeId}`,\n { body: { isActive } },\n );\n return unwrapData(res);\n }\n\n /** Caller org's referral summary as referrer (redemptions, qualified, credits earned). */\n async stats(): Promise<ReferralStats> {\n const res = await this.http.get<{ success: boolean; data: ReferralStats }>('/referrals/stats');\n return unwrapData(res);\n }\n\n /**\n * Redeem a referral code for the caller's org. Fails (4xx with an\n * `error_code`) when a guard rejects it: `code_inactive`, `self_referral`,\n * `already_redeemed`, `already_associated`, or `has_purchases`.\n */\n async redeem(body: RedeemReferralCodeRequest): Promise<ReferralRedemption> {\n const res = await this.http.post<{ success: boolean; data: ReferralRedemption }>(\n '/referrals/redeem',\n { body },\n );\n return unwrapData(res);\n }\n\n // --- Platform-admin only ---\n\n /**\n * Platform-wide referral monitor: rollup stats + every redemption (with the\n * code string and both org names). Returns 403 unless platform admin.\n */\n async adminOverview(): Promise<ReferralAdminOverview> {\n const res = await this.http.get<{ success: boolean; data: ReferralAdminOverview }>('/admin/referrals');\n return unwrapData(res);\n }\n\n /**\n * Void a PENDING redemption (abuse control) so it can never qualify. Fails\n * with 409 `not_pending` if the redemption is missing, already qualified, or\n * already void. Platform-admin only.\n */\n async voidRedemption(redemptionId: string): Promise<void> {\n await this.http.post<{ success: boolean }>(`/admin/referrals/${redemptionId}/void`, { body: {} });\n }\n\n /**\n * Force-qualify a PENDING non-reseller redemption: grants the snapshotted\n * referrer reward + referred welcome credit immediately, bypassing the spend\n * threshold. Fails with 409 `not_pending` (missing/qualified/void) or 400\n * `reseller_code`. Platform-admin only. Returns the updated redemption.\n */\n async qualifyRedemption(redemptionId: string): Promise<ReferralRedemption> {\n const res = await this.http.post<{ success: boolean; data: ReferralRedemption }>(\n `/admin/referrals/${redemptionId}/qualify`,\n { body: {} },\n );\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type { Organization } from '../organization/types.js';\nimport type {\n AppendProgramConfigRequest,\n AssociatedOrg,\n BillingProgramConfig,\n GeneratePayoutsRequest,\n ResellerCommission,\n ResellerPayout,\n ResellerPerformance,\n SetResellerRequest,\n UpdatePayoutRequest,\n} from './types.js';\n\n/**\n * Reseller surface. The first three methods are self-service for an org with\n * `isReseller === true` (the server gates on it). The remaining methods are\n * platform-admin only (gated on the caller's home org being the admin org).\n */\nexport class ResellerClient {\n constructor(private readonly http: BaseClient) {}\n\n // --- Reseller self-service (org.isReseller) ---\n\n /** Orgs associated to the caller reseller, with gross + commission rollups. */\n async listAssociatedOrgs(): Promise<AssociatedOrg[]> {\n const res = await this.http.get<{ success: boolean; data: AssociatedOrg[] }>('/reseller/associated-orgs');\n return res.data ?? [];\n }\n\n /** The caller reseller's commission ledger. */\n async listCommissions(): Promise<ResellerCommission[]> {\n const res = await this.http.get<{ success: boolean; data: ResellerCommission[] }>('/reseller/commissions');\n return res.data ?? [];\n }\n\n /** The caller reseller's payout history. */\n async listPayouts(): Promise<ResellerPayout[]> {\n const res = await this.http.get<{ success: boolean; data: ResellerPayout[] }>('/reseller/payouts');\n return res.data ?? [];\n }\n\n // --- Platform-admin only ---\n\n /** List all reseller orgs with aggregate performance. */\n async listResellers(): Promise<ResellerPerformance[]> {\n const res = await this.http.get<{ success: boolean; data: ResellerPerformance[] }>('/admin/resellers');\n return res.data ?? [];\n }\n\n /** Designate an org as a reseller (optionally with a per-reseller bps override). */\n async setReseller(orgId: string, body: SetResellerRequest = {}): Promise<Organization> {\n const res = await this.http.post<{ success: boolean; data: Organization }>(\n `/admin/orgs/${orgId}/reseller`,\n { body },\n );\n return unwrapData(res);\n }\n\n /** Revoke an org's reseller status. */\n async revokeReseller(orgId: string): Promise<Organization> {\n const res = await this.http.delete<{ success: boolean; data: Organization }>(`/admin/orgs/${orgId}/reseller`);\n return unwrapData(res);\n }\n\n /** End an org's reseller association (stamps resellerDetachedAt). */\n async detachAssociation(orgId: string): Promise<Organization> {\n const res = await this.http.post<{ success: boolean; data: Organization }>(\n `/admin/orgs/${orgId}/detach-reseller`,\n { body: {} },\n );\n return unwrapData(res);\n }\n\n /** The billing-program-config journal, newest first. */\n async getProgramConfig(): Promise<BillingProgramConfig[]> {\n const res = await this.http.get<{ success: boolean; data: BillingProgramConfig[] }>(\n '/admin/billing-program-config',\n );\n return res.data ?? [];\n }\n\n /** Append a new program-config period (closes the prior open row). */\n async appendProgramConfig(body: AppendProgramConfigRequest): Promise<BillingProgramConfig> {\n const res = await this.http.post<{ success: boolean; data: BillingProgramConfig }>(\n '/admin/billing-program-config',\n { body },\n );\n return unwrapData(res);\n }\n\n /** Draft payouts from accrued commissions in the given period. */\n async generatePayouts(body: GeneratePayoutsRequest): Promise<ResellerPayout[]> {\n const res = await this.http.post<{ success: boolean; data: ResellerPayout[] }>(\n '/admin/reseller-payouts/generate',\n { body },\n );\n return res.data ?? [];\n }\n\n /** Approve or mark-paid a payout (and optionally record an external ref). */\n async updatePayout(payoutId: string, body: UpdatePayoutRequest): Promise<ResellerPayout> {\n const res = await this.http.patch<{ success: boolean; data: ResellerPayout }>(\n `/admin/reseller-payouts/${payoutId}`,\n { body },\n );\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n AvailableModels,\n ModelPricingRow,\n ModelSelection,\n PatchModelSelectionRequest,\n PlatformSettings,\n UpdatePlatformSettingsRequest,\n} from './types.js';\n\n/**\n * Platform-admin global config. All endpoints are gated server-side on the\n * caller's home org being a platform-admin org. The model-selection / pricing\n * methods are proxied through the backend to the cloud-agent service.\n */\nexport class PlatformAdminClient {\n constructor(private readonly http: BaseClient) {}\n\n // --- Global backend settings (open registration + free-tier credits) ---\n\n /** Current global settings. */\n async getPlatformSettings(): Promise<PlatformSettings> {\n const res = await this.http.get<{ success: boolean; data: PlatformSettings }>('/admin/platform-settings');\n return unwrapData(res);\n }\n\n /** Update the global settings. */\n async updatePlatformSettings(body: UpdatePlatformSettingsRequest): Promise<PlatformSettings> {\n const res = await this.http.put<{ success: boolean; data: PlatformSettings }>('/admin/platform-settings', {\n body,\n });\n return unwrapData(res);\n }\n\n /** Models the aigateway currently exposes (for validating selection/pricing). */\n async listAvailableModels(): Promise<AvailableModels> {\n const res = await this.http.get<{ success: boolean; data: AvailableModels }>(\n '/admin/available-models',\n );\n return unwrapData(res);\n }\n\n // --- Chat-model selection (bridged to cloud-agent) ---\n\n /** Current model selection (provider priority + per-provider/role models). */\n async getModelSelection(): Promise<ModelSelection> {\n const res = await this.http.get<{ success: boolean; data: ModelSelection }>('/admin/model-selection');\n return unwrapData(res);\n }\n\n /** Full replace of the model selection. Returns the fresh selection. */\n async putModelSelection(body: ModelSelection): Promise<ModelSelection> {\n const res = await this.http.put<{ success: boolean; data: ModelSelection }>('/admin/model-selection', { body });\n return unwrapData(res);\n }\n\n /** Upsert a single (provider, role) → model slot. Returns the fresh selection. */\n async patchModelSelection(body: PatchModelSelectionRequest): Promise<ModelSelection> {\n const res = await this.http.patch<{ success: boolean; data: ModelSelection }>('/admin/model-selection', {\n body,\n });\n return unwrapData(res);\n }\n\n // --- Model pricing / surcharge (bridged to cloud-agent) ---\n\n /** All model_pricing rows. */\n async listModelPricing(): Promise<ModelPricingRow[]> {\n const res = await this.http.get<{ success: boolean; data: { pricing: ModelPricingRow[] } }>(\n '/admin/model-pricing',\n );\n return unwrapData(res).pricing ?? [];\n }\n\n /** Upsert one model_pricing row (also used to add a new row). Returns the fresh list. */\n async putModelPricing(row: ModelPricingRow): Promise<ModelPricingRow[]> {\n const res = await this.http.put<{ success: boolean; data: { pricing: ModelPricingRow[] } }>(\n '/admin/model-pricing',\n { body: row },\n );\n return unwrapData(res).pricing ?? [];\n }\n\n /** Delete a model_pricing row by model id. Returns the fresh list. */\n async deleteModelPricing(model: string): Promise<ModelPricingRow[]> {\n const res = await this.http.delete<{ success: boolean; data: { pricing: ModelPricingRow[] } }>(\n `/admin/model-pricing?model=${encodeURIComponent(model)}`,\n );\n return unwrapData(res).pricing ?? [];\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n Deployment,\n RegisterDeploymentRequest,\n RegisterDeploymentResponse,\n UpdateDeploymentRequest,\n DeploymentQuota,\n DeploymentQuotas,\n SetDeploymentQuotaRequest,\n OrgUsageResponse,\n DeploymentUsageResponse,\n FederationStatus,\n MeteringPolicy,\n MeteringReconciliation,\n} from './types.js';\n\n// Org-scoped private/sovereign deployment management. Backend routes hang off\n// the root authed group — see internal/http/routes/federation (RegisterPortal)\n// in cloud-agent-backend. The matching machine edge (/federation/enroll,\n// /heartbeat) is driven by the appliance itself, not this SDK.\nconst BASE = '/deployments';\n\nexport class DeploymentsClient {\n constructor(private readonly http: BaseClient) {}\n\n /** List the org's deployments, newest first. */\n list(): Promise<{ deployments: Deployment[] }> {\n return this.http.get(BASE);\n }\n\n /** Fetch one deployment by id. */\n get(id: string): Promise<{ deployment: Deployment }> {\n return this.http.get(`${BASE}/${encodeURIComponent(id)}`);\n }\n\n /**\n * Register a new deployment: reserves a quota slot and mints a one-time\n * enrollment voucher. The voucher + install command in the response are shown\n * ONCE (only the voucher hash is stored server-side).\n */\n register(body: RegisterDeploymentRequest): Promise<RegisterDeploymentResponse> {\n return this.http.post(BASE, { body });\n }\n\n /**\n * Edit the mutable slice of a deployment at its authority: the product set,\n * and — flat masters at Central — the vCPU tree budget. Propagates to the box\n * via the heartbeat licenseStale downlink + forced renewal (no restart).\n */\n update(id: string, body: UpdateDeploymentRequest): Promise<{ deployment: Deployment }> {\n return this.http.patch(`${BASE}/${encodeURIComponent(id)}`, { body });\n }\n\n /** Decommission a deployment, freeing its quota slot. */\n decommission(id: string): Promise<{ success: boolean }> {\n return this.http.post(`${BASE}/${encodeURIComponent(id)}/decommission`);\n }\n\n /**\n * The caller's org deployment quotas: deployment count plus flat capacity in\n * UNITS (1 unit = 1 vCPU × 1 product; used = Σ budget × |products| over flat\n * masters, max = Σ active capacity grants). Org-scoped: a platform admin\n * sending X-Impersonate-Org-Id sees the impersonated org's quotas.\n */\n getQuota(): Promise<DeploymentQuotas> {\n return this.http.get(`${BASE}/quota`);\n }\n\n /**\n * Platform-admin only: set an org's deployment cap (null → revert to the\n * platform default). Operates on the explicit orgId via the admin pool, so it\n * is independent of impersonation. Returns the refreshed quota.\n * (The flat-capacity pool is grant-based — see capacity.listGrants/addGrant.)\n */\n setOrgQuota(orgId: string, body: SetDeploymentQuotaRequest): Promise<{ quota: DeploymentQuota }> {\n return this.http.put(`/admin/orgs/${encodeURIComponent(orgId)}/deployment-quota`, { body });\n }\n\n /**\n * Permanently remove a DECOMMISSIONED deployment row from the registry\n * (decommission first — a live row is rejected with 409).\n */\n delete(id: string): Promise<{ success: boolean }> {\n return this.http.delete(`${BASE}/${encodeURIComponent(id)}`);\n }\n\n // ── Consumption reporting (channel plan §4.3/§4.11) ────────────────────────\n\n /** Org usage roll-up over [from, to) (RFC3339 or YYYY-MM-DD; default 30d). */\n getOrgUsage(params?: { from?: string; to?: string }): Promise<OrgUsageResponse> {\n return this.http.get(`${BASE}/usage`, { query: params });\n }\n\n /** One deployment's usage period detail (direct or estate-reported). */\n getUsage(id: string, params?: { from?: string; to?: string }): Promise<DeploymentUsageResponse> {\n return this.http.get(`${BASE}/${encodeURIComponent(id)}/usage`, { query: params });\n }\n\n // ── Box-side federation panel + the offline file pipe (channel plan §4.8) ──\n\n /** This private box's federation snapshot (503 on the SaaS / Central). */\n getFederationStatus(): Promise<{ federation: FederationStatus }> {\n return this.http.get('/federation/status');\n }\n\n /**\n * Seal the pending outbox (+ a liveness heartbeat) into the operator-carried\n * export file. The result is the JSON document to download/carry.\n */\n exportFederationFile(): Promise<unknown> {\n return this.http.get('/federation/export');\n }\n\n /** Apply the authority's response file on the box (acks + license adoption). */\n importFederationResponse(file: unknown): Promise<{ applied: number; refused: number }> {\n return this.http.post('/federation/import-response', { body: file });\n }\n\n /** Box-initiated retire: queues the signed decommission for the authority. */\n retire(reason?: string): Promise<{ success: boolean }> {\n return this.http.post('/federation/retire', { body: { reason: reason ?? '' } });\n }\n\n /**\n * Authority-side import of an operator-carried export file; returns the\n * response file (JSON) to carry back to the deployment.\n */\n importFederationFile(file: unknown): Promise<unknown> {\n return this.http.post(`${BASE}/import`, { body: file });\n }\n\n // ── Model-B metering policy (platform-admin; close-out P2) ─────────────────\n\n getMeteringPolicy(orgId: string): Promise<{ policy: MeteringPolicy; exists: boolean }> {\n return this.http.get(`/admin/orgs/${encodeURIComponent(orgId)}/metering-policy`);\n }\n\n setMeteringPolicy(orgId: string, policy: Omit<MeteringPolicy, 'orgId'>): Promise<{ success: boolean }> {\n return this.http.put(`/admin/orgs/${encodeURIComponent(orgId)}/metering-policy`, { body: policy });\n }\n\n /** Reported-vs-rated totals — the rating worker's health check. */\n getMeteringReconciliation(\n orgId: string,\n params?: { from?: string; to?: string },\n ): Promise<{ reconciliation: MeteringReconciliation }> {\n return this.http.get(`/admin/orgs/${encodeURIComponent(orgId)}/metering-reconciliation`, { query: params });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n AddCapacityGrantRequest,\n CapacityCheckoutRequest,\n CapacityCheckoutResponse,\n CapacityGrantsResponse,\n CapacityPreviewResponse,\n CapacityState,\n} from './types.js';\n\n// Flat-capacity self-serve purchase (SaaS/Central only; the backend hides the\n// whole surface on a private appliance). Increases apply immediately\n// (prorated); decreases and cancellation take effect at period end. See\n// cloud-agent/docs/design/current/federation/flat-capacity-payment-gateway.md.\nconst BASE = '/capacity';\n\nexport class CapacityClient {\n constructor(private readonly http: BaseClient) {}\n\n /** The org's capacity state: pool, grants, subscription, catalog. */\n getState(): Promise<CapacityState> {\n return this.http.get(BASE);\n }\n\n /** Start the first purchase — returns the Stripe Checkout URL. */\n checkout(body: CapacityCheckoutRequest): Promise<CapacityCheckoutResponse> {\n return this.http.post(`${BASE}/checkout`, { body });\n }\n\n /**\n * Preview the prorated charge of changing the `interval` subscription to\n * `units` (0 for decreases).\n */\n preview(interval: 'month' | 'year', units: number): Promise<CapacityPreviewResponse> {\n return this.http.post(`${BASE}/preview`, { body: { interval, units } });\n }\n\n /**\n * Change the `interval` subscription to `units`. Increase = immediate +\n * prorated (state in the response is already updated — no webhook wait);\n * decrease = scheduled for period end, floored at the org's current draw;\n * the current quantity cancels a pending decrease.\n */\n update(interval: 'month' | 'year', units: number): Promise<CapacityState> {\n return this.http.post(`${BASE}/update`, { body: { interval, units } });\n }\n\n /**\n * Cancel the `interval` subscription at period end; deployments then run\n * into the license grace window.\n */\n cancel(interval: 'month' | 'year'): Promise<CapacityState> {\n return this.http.post(`${BASE}/cancel`, { body: { interval } });\n }\n\n /** Undo a pending cancellation on the `interval` subscription before it lapses. */\n resume(interval: 'month' | 'year'): Promise<CapacityState> {\n return this.http.post(`${BASE}/resume`, { body: { interval } });\n }\n\n // ── Platform-admin grant ledger (manual pool source; stripe rows read-only) ─\n\n listGrants(orgId: string): Promise<CapacityGrantsResponse> {\n return this.http.get(`/admin/orgs/${encodeURIComponent(orgId)}/capacity-grants`);\n }\n\n addGrant(orgId: string, body: AddCapacityGrantRequest): Promise<CapacityGrantsResponse> {\n return this.http.post(`/admin/orgs/${encodeURIComponent(orgId)}/capacity-grants`, { body });\n }\n\n deleteGrant(orgId: string, grantId: string): Promise<CapacityGrantsResponse> {\n return this.http.delete(\n `/admin/orgs/${encodeURIComponent(orgId)}/capacity-grants/${encodeURIComponent(grantId)}`,\n );\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n BICatalogSummary,\n BIEntityDetail,\n BILinkResponse,\n CreateBILinkRequest,\n ListBIDatasetsResponse,\n ListBILinksResponse,\n ListBIModelsResponse,\n SelectBIDatasetsRequest,\n SelectBIDatasetsResponse,\n TriggerBIDiscoveryResponse,\n UpdateBILinkRequest,\n} from './types.js';\n\n/**\n * BIClient is the Talk-to-Your-BI control-plane surface used by the data-agent\n * frontend: read the discovered semantic-model catalog, list connected models,\n * trigger a re-scan, and start the Power BI OAuth connect flow. All endpoints\n * are org-scoped + product-entitlement-gated server-side (requireProduct(\"bi\")).\n *\n * Catalog upsert + refresh-token rotation are machine-only (HMAC, engine→backend)\n * and deliberately NOT exposed here.\n */\nexport class BIClient {\n constructor(\n private readonly http: BaseClient,\n private readonly baseUrl: string,\n ) {}\n\n /**\n * Compact grounding catalog for a workspace's model: entities + measures +\n * relationship names, no per-column detail. Pass `entity` to get the full\n * (ranked) field list for one entity — the get_model_schema detail layer.\n */\n getCatalog(workspaceId: string, opts?: { modelId?: string; entity?: string }): Promise<BICatalogSummary | BIEntityDetail> {\n const params = new URLSearchParams();\n if (opts?.modelId) params.set('modelId', opts.modelId);\n if (opts?.entity) params.set('entity', opts.entity);\n const qs = params.size > 0 ? `?${params.toString()}` : '';\n return this.http.get<BICatalogSummary | BIEntityDetail>(`/workspaces/${workspaceId}/bi/catalog${qs}`);\n }\n\n /** Lists the connected semantic models for a data project. */\n listModels(workspaceId: string): Promise<ListBIModelsResponse> {\n return this.http.get<ListBIModelsResponse>(`/workspaces/${workspaceId}/bi/models`);\n }\n\n /**\n * Lists the connected account's workspaces + datasets for the dataset picker.\n * The backend forwards to the engine (which holds the decrypted token) to make\n * the Power BI REST calls. `credentialId` selects which connected account.\n */\n listDatasets(workspaceId: string, opts: { credentialId: string }): Promise<ListBIDatasetsResponse> {\n const qs = `?credentialId=${encodeURIComponent(opts.credentialId)}`;\n return this.http.get<ListBIDatasetsResponse>(`/workspaces/${workspaceId}/bi/datasets${qs}`);\n }\n\n /**\n * Connects the chosen datasets: creates one bi_model per selection (the\n * workspace GUID is stored on the model). Entities/measures are discovered\n * lazily on the first chat question.\n */\n selectDatasets(workspaceId: string, body: SelectBIDatasetsRequest): Promise<SelectBIDatasetsResponse> {\n return this.http.post<SelectBIDatasetsResponse>(`/workspaces/${workspaceId}/bi/models`, { body });\n }\n\n /**\n * Triggers an engine-side catalog re-scan of the workspace's connected model\n * (INFO.* discovery → bi_* upsert). Returns once the backend has accepted the\n * request; the catalog read reflects the new data when discovery completes.\n */\n triggerDiscovery(workspaceId: string): Promise<TriggerBIDiscoveryResponse> {\n return this.http.post<TriggerBIDiscoveryResponse>(`/workspaces/${workspaceId}/bi/discover`, {});\n }\n\n /**\n * The browser URL that starts the delegated Power BI OAuth flow for a data\n * project. Navigate the window here; the backend redirects to Microsoft and,\n * on the callback, creates the POWERBI credential and returns to the frontend.\n * `workspaceId` tells the backend which project to attach the credential to.\n */\n powerBIConnectUrl(workspaceId: string): string {\n return `${this.baseUrl}/connect/powerbi?workspaceId=${encodeURIComponent(workspaceId)}`;\n }\n\n // ── Cross-dataset links (governance panel) ─────────────────────────────────\n\n /** Lists the workspace's cross-dataset links (with model names + probe stats). */\n listLinks(workspaceId: string): Promise<ListBILinksResponse> {\n return this.http.get<ListBILinksResponse>(`/workspaces/${workspaceId}/bi/links`);\n }\n\n /**\n * Creates a manual, user-authored link. It is confirmed immediately (the user\n * IS the governance authority); the backend forwards a probe to the engine\n * first, so a PII-keyed link is refused and stats attach at creation.\n */\n createLink(workspaceId: string, body: CreateBILinkRequest): Promise<BILinkResponse> {\n return this.http.post<BILinkResponse>(`/workspaces/${workspaceId}/bi/links`, { body });\n }\n\n /** Confirm / reject / re-propose a link, or edit its name/description/cardinality. */\n updateLink(workspaceId: string, linkId: string, body: UpdateBILinkRequest): Promise<BILinkResponse> {\n return this.http.patch<BILinkResponse>(`/workspaces/${workspaceId}/bi/links/${encodeURIComponent(linkId)}`, { body });\n }\n\n /** Soft-deletes a link. */\n deleteLink(workspaceId: string, linkId: string): Promise<{ success: boolean }> {\n return this.http.delete<{ success: boolean }>(`/workspaces/${workspaceId}/bi/links/${encodeURIComponent(linkId)}`);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n CreateDashboardRequest,\n CreateSnapshotShareRequest,\n CreateSnapshotShareResponse,\n DashboardResponse,\n ExportAuthorization,\n ExportRequest,\n ListDashboardsResponse,\n ListDashboardVersionsResponse,\n ListSnapshotsResponse,\n ListSnapshotSharesResponse,\n OkResponse,\n PopulateDashboardParams,\n PopulateDashboardResult,\n SnapshotResponse,\n UpdateDashboardRequest,\n} from './api-types.js';\n\n/**\n * DashboardsClient is the visual-dashboard control plane (Talk-to-Your-BI block\n * B5): save/load/edit the durable Dashboard Spec, refresh it with current data\n * (run-as-owner, model-free), and freeze/share snapshots.\n *\n * Access is org-scoped + product-entitlement-gated (requireProduct(\"bi\")) +\n * project-membership-scoped server-side. Dynamic boards are same-org, member-only;\n * static snapshots are the externally-shareable, governed-PII-egress artifact.\n */\nexport class DashboardsClient {\n constructor(\n private readonly http: BaseClient,\n private readonly baseUrl: string,\n ) {}\n\n private base(workspaceId: string): string {\n return `/workspaces/${workspaceId}/bi/dashboards`;\n }\n\n /** Lists a project's saved dashboards (most-recently-updated first). */\n list(workspaceId: string): Promise<ListDashboardsResponse> {\n return this.http.get<ListDashboardsResponse>(this.base(workspaceId));\n }\n\n /** Fetches one dashboard (spec served verbatim; validate client-side). */\n get(workspaceId: string, dashboardId: string): Promise<DashboardResponse> {\n return this.http.get<DashboardResponse>(`${this.base(workspaceId)}/${dashboardId}`);\n }\n\n /** Saves a spec as a new dashboard (the spec is a validated DashboardSpec). */\n create(workspaceId: string, body: CreateDashboardRequest): Promise<DashboardResponse> {\n return this.http.post<DashboardResponse>(this.base(workspaceId), { body });\n }\n\n /**\n * Updates a dashboard. A new `spec` bumps specVersion and appends an immutable\n * version row; name/description-only edits do not bump.\n */\n update(workspaceId: string, dashboardId: string, body: UpdateDashboardRequest): Promise<DashboardResponse> {\n return this.http.patch<DashboardResponse>(`${this.base(workspaceId)}/${dashboardId}`, { body });\n }\n\n /** Soft-deletes a dashboard (owner or project ADMIN). */\n remove(workspaceId: string, dashboardId: string): Promise<OkResponse> {\n return this.http.delete<OkResponse>(`${this.base(workspaceId)}/${dashboardId}`);\n }\n\n /** Lists a dashboard's spec history (newest first). */\n listVersions(workspaceId: string, dashboardId: string): Promise<ListDashboardVersionsResponse> {\n return this.http.get<ListDashboardVersionsResponse>(`${this.base(workspaceId)}/${dashboardId}/versions`);\n }\n\n /** Restores a prior version by forward-writing it as a new version. */\n restoreVersion(workspaceId: string, dashboardId: string, specVersion: number): Promise<DashboardResponse> {\n return this.http.post<DashboardResponse>(`${this.base(workspaceId)}/${dashboardId}/versions/${specVersion}/restore`, {});\n }\n\n /**\n * Refreshes the dashboard with CURRENT data — the model-free, run-as-owner\n * populate. Returns one PanelPayload per panel. `params` are resolved control\n * values (interactivity rungs 2–3).\n */\n populate(workspaceId: string, dashboardId: string, body: PopulateDashboardParams = {}): Promise<PopulateDashboardResult> {\n return this.http.post<PopulateDashboardResult>(`${this.base(workspaceId)}/${dashboardId}/populate`, { body });\n }\n\n /**\n * Freezes a snapshot — the governed PII egress (explicit action + audit). The\n * frozen panelData carries re-hydrated names.\n */\n createSnapshot(workspaceId: string, dashboardId: string, body: PopulateDashboardParams = {}): Promise<SnapshotResponse> {\n return this.http.post<SnapshotResponse>(`${this.base(workspaceId)}/${dashboardId}/snapshots`, { body });\n }\n\n /** Lists a dashboard's snapshots (newest first). */\n listSnapshots(workspaceId: string, dashboardId: string): Promise<ListSnapshotsResponse> {\n return this.http.get<ListSnapshotsResponse>(`${this.base(workspaceId)}/${dashboardId}/snapshots`);\n }\n\n /** Reads one snapshot (same-org; no live query, no credential). */\n getSnapshot(workspaceId: string, dashboardId: string, snapshotId: string): Promise<SnapshotResponse> {\n return this.http.get<SnapshotResponse>(`${this.base(workspaceId)}/${dashboardId}/snapshots/${snapshotId}`);\n }\n\n /**\n * Mints a snapshot share — an internal/known-user grant or an anonymous link.\n * External sharing (a link or a cross-org user) requires the org's\n * allowExternalSharing flag. A minted link's raw secret is returned ONCE in\n * `linkToken`; only its hash is stored.\n */\n createSnapshotShare(\n workspaceId: string,\n dashboardId: string,\n snapshotId: string,\n body: CreateSnapshotShareRequest,\n ): Promise<CreateSnapshotShareResponse> {\n return this.http.post<CreateSnapshotShareResponse>(\n `${this.base(workspaceId)}/${dashboardId}/snapshots/${snapshotId}/shares`,\n { body },\n );\n }\n\n /** Lists a snapshot's shares (owner/ADMIN; link secrets never returned). */\n listSnapshotShares(workspaceId: string, dashboardId: string, snapshotId: string): Promise<ListSnapshotSharesResponse> {\n return this.http.get<ListSnapshotSharesResponse>(\n `${this.base(workspaceId)}/${dashboardId}/snapshots/${snapshotId}/shares`,\n );\n }\n\n /** Revokes a share/link. */\n revokeSnapshotShare(workspaceId: string, dashboardId: string, snapshotId: string, shareId: string): Promise<OkResponse> {\n return this.http.delete<OkResponse>(\n `${this.base(workspaceId)}/${dashboardId}/snapshots/${snapshotId}/shares/${shareId}`,\n );\n }\n\n /**\n * Reads a snapshot shared with the caller via an explicit user grant (internal\n * or cross-org). Not project-scoped — the grant is the authorization.\n */\n getSharedSnapshot(snapshotId: string): Promise<SnapshotResponse> {\n return this.http.get<SnapshotResponse>(`/bi/snapshots/${snapshotId}/shared`);\n }\n\n /**\n * Reads a snapshot via an anonymous link token (no session). Use `token` = the\n * raw secret returned by createSnapshotShare({ link: true }).\n */\n getPublicSnapshot(token: string): Promise<SnapshotResponse> {\n return this.http.get<SnapshotResponse>(`/public/bi/snapshots/${encodeURIComponent(token)}`);\n }\n\n /** The shareable URL for an anonymous link token (for copy-to-clipboard). */\n publicSnapshotUrl(token: string): string {\n return `${this.baseUrl}/public/bi/snapshots/${encodeURIComponent(token)}`;\n }\n\n /**\n * Authorizes + audits a client-side export BEFORE the caller serialises the file\n * (Talk-to-Your-BI block B7). This makes the O1 \"audit exports always\" guarantee\n * un-skippable: the file must not be produced until this resolves. A workspace-\n * scoped export is same-org (project membership), so it is audit-only; the\n * allowExternalSharing gate governs only the cross-org / anonymous-link recipient\n * surfaces. Throws HttpError(403) when a gated egress is disallowed.\n */\n recordExport(workspaceId: string, dashboardId: string, body: ExportRequest): Promise<ExportAuthorization> {\n return this.http.post<ExportAuthorization>(`${this.base(workspaceId)}/${dashboardId}/exports`, { body });\n }\n\n /**\n * Authorizes + audits an ad-hoc, dashboard-less export — a run_bi_query chat\n * result serialised to a file (block B7). Audited against the project with no\n * dashboard id; same \"audit exports always\" guarantee as recordExport.\n */\n recordProjectExport(workspaceId: string, body: ExportRequest): Promise<ExportAuthorization> {\n return this.http.post<ExportAuthorization>(`/workspaces/${workspaceId}/bi/exports`, { body });\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n AttestPostureRequest,\n ConnectionDetail,\n ConnectionFact,\n ConnectionSummary,\n RecordConnectionFactRequest,\n UpdateConnectionRequest,\n} from './types.js';\n\n/**\n * Connection health & capability inventory client (common-infra component #7).\n *\n * Authority splits in two, and the split is enforced server-side — these methods\n * only mirror it:\n *\n * - MEMBERS read (filtered to the credentials they can already see) and perform\n * the maintenance that keeps an inventory honest: rename, set the owner\n * contact. Locking those behind an admin is how inventories end up full of\n * rows called \"Power BI (delegated)\".\n * - ORG ADMINS own the consequential verbs: archive, disable, and attested\n * facts.\n *\n * Two behaviours worth knowing:\n *\n * - Reads NEVER provision. An empty list means the inventory has not observed\n * anything yet (or the feature is off) — it never means \"we just created some\n * rows for you because you looked\".\n * - Impersonation is read-only here, as with credentials: every write returns\n * 403 while impersonating another organization.\n */\nexport class ConnectionsClient {\n constructor(private readonly http: BaseClient) {}\n\n /**\n * Connections reachable from one project — those with at least one member\n * credential visible to you there.\n *\n * Returns `[]` while the feature is dark, so a caller can render this\n * unconditionally and see exactly today's UI.\n */\n async list(projectId: string): Promise<ConnectionSummary[]> {\n const res = await this.http.get<{ success: boolean; connections: ConnectionSummary[] }>(\n `/connections?projectId=${encodeURIComponent(projectId)}`,\n );\n return res.connections ?? [];\n }\n\n /** One connection in full: members, current facts with provenance, and the\n * contact references. 404 when no member credential is visible to you —\n * existence is not leaked across projects. */\n async get(id: string): Promise<ConnectionDetail> {\n const res = await this.http.get<{ success: boolean; connection: ConnectionDetail }>(\n `/connections/${encodeURIComponent(id)}`,\n );\n return res.connection;\n }\n\n /** Rename and/or re-point the owner + admin contact references. Member-level. */\n async update(id: string, body: UpdateConnectionRequest): Promise<ConnectionSummary> {\n const res = await this.http.patch<{ success: boolean; connection: ConnectionSummary }>(\n `/connections/${encodeURIComponent(id)}`,\n { body },\n );\n return res.connection;\n }\n\n /** Archive a connection (org admin). Archiving frees its identity, so a later\n * re-connect to the same tenant starts clean instead of colliding. */\n async archive(id: string): Promise<void> {\n await this.http.post(`/connections/${encodeURIComponent(id)}/archive`, {});\n }\n\n /** Restore an archived connection (org admin). */\n async unarchive(id: string): Promise<void> {\n await this.http.post(`/connections/${encodeURIComponent(id)}/unarchive`, {});\n }\n\n /**\n * Disable a connection (org admin).\n *\n * NOT the same as archive: an archived connection is gone from the working\n * set, a disabled one is present and deliberately unusable — it badges\n * `disabled` and capability checks answer `no` for it.\n */\n async disable(id: string): Promise<void> {\n await this.http.post(`/connections/${encodeURIComponent(id)}/disable`, {});\n }\n\n /** Re-enable a disabled connection (org admin). */\n async enable(id: string): Promise<void> {\n await this.http.post(`/connections/${encodeURIComponent(id)}/enable`, {});\n }\n\n /** Record an ATTESTED fact (org admin): a human's assertion about a\n * connection — a completed provider review, a negotiated unit cost. */\n async recordFact(id: string, body: RecordConnectionFactRequest): Promise<ConnectionFact> {\n const res = await this.http.post<{ success: boolean; fact: ConnectionFact }>(\n `/connections/${encodeURIComponent(id)}/facts`,\n { body },\n );\n return res.fact;\n }\n\n /** Attest a connection's posture (org admin, SHR-IP03): who it acts as, who\n * governs it, its explicit target allowlist, whether unattended use is\n * allowed, and who fixes it when it breaks. Until this runs, the connection\n * is fail-closed `pending-attestation` and proposes nothing. The response is\n * the same full detail projection `get()` serves, freshly attested. */\n async attestPosture(id: string, body: AttestPostureRequest): Promise<ConnectionDetail> {\n const res = await this.http.post<{ success: boolean; connection: ConnectionDetail }>(\n `/connections/${encodeURIComponent(id)}/posture`,\n { body },\n );\n return res.connection;\n }\n\n /** The admin attestation queue: connections still pending-attestation, as\n * the same summary projection `list()` serves (the queue is a list surface —\n * fetch `get(id)` for the drawer detail). */\n async pendingPosture(): Promise<ConnectionSummary[]> {\n const res = await this.http.get<{ success: boolean; connections: ConnectionSummary[] }>(\n `/connections-posture/pending`,\n );\n return res.connections ?? [];\n }\n}\n","/**\n * Connection lifecycle over the platform-owned delegated-OAuth connect rail\n * (MVP09 C2-SDK-CONNECTION, chat-first realignment proposal §5.1).\n *\n * This is the typed surface the secure connect flow (C2-UI-CONNECTION) drives:\n * begin an authorization-code flow, read the redacted connection status under\n * the active scope, refresh one connection's status, and disconnect. It mirrors\n * the backend rail generalized in C2-BE-OAUTH-ROUTES / C2-BE-OAUTH-LIFECYCLE:\n *\n * GET /connect/<slug> — authorize start → { authUrl }\n * GET /connect/<slug>/callback — browser redirect only (NOT an SDK call)\n * GET /connections?projectId= — redacted connection inventory (status)\n * GET /connections/<id> — redacted connection detail (refresh)\n * DELETE /credentials/<id> — revoke the delegated grant (disconnect)\n *\n * Two safety laws govern every type here (proposal §5.1.1-5.1.5):\n * 1. OPAQUE STATE. The client never constructs, holds or transmits an OAuth\n * state token or PKCE verifier. authorizeStart receives ONLY an opaque\n * authorize URL; the server mints, signs, expires and PKCE-binds the state.\n * 2. NO SECRET FIELDS. No token, envelope, client secret, refresh token or\n * verifier appears on any request or projection. status/refresh reuse the\n * never-secret connection-inventory shapes; disconnect is the redacted\n * credential-delete envelope.\n */\n\nimport type {\n ConnectionSummary,\n ConnectionDetail,\n CapabilityDisplayState,\n} from '../connections/types.js';\n\n/**\n * The connect-rail provider slug. Open string like {@link\n * '../credentials/types.js'.ProviderID}: the CLOSED set of connectable families\n * is owned server-side (connect_providers.go). Today the only currently-\n * connectable family is `powerbi`; every provisional Meeting/Marketing family\n * is contained and the rail answers 503 for it — the client passes the slug\n * through and never asserts availability itself.\n */\nexport type ConnectProviderSlug = 'powerbi' | (string & {});\n\n/**\n * Input to {@link '../connect/ConnectClient.js'.ConnectClient.authorizeStart}.\n * `workspaceId` is the active sandbox (StorageRepo) the connection binds to; the\n * server proves ownership and stamps the project/sandbox binding INTO the opaque\n * signed state — the client passes only the id, never the binding authority.\n * `origin` is the SPA origin the callback returns the browser to; the server\n * allow-lists it, so a forged value cannot redirect off-list.\n */\nexport interface ConnectAuthorizeStartInput {\n provider: ConnectProviderSlug;\n workspaceId: string;\n origin?: string;\n}\n\n/**\n * The authorize-start projection: ONLY the opaque provider authorize URL the\n * secure connect surface navigates the browser to. The URL embeds the\n * server-signed state and PKCE challenge; this type has NO field for a client\n * secret, refresh token, code verifier or any other credential material, so a\n * secret structurally cannot ride back on it.\n */\nexport interface ConnectAuthorization {\n authUrl: string;\n}\n\n/** Query for the redacted connection-status projection under an active scope. */\nexport interface ConnectStatusQuery {\n projectId: string;\n}\n\n/**\n * Input to {@link '../connect/ConnectClient.js'.ConnectClient.disconnect}.\n * Disconnect IS the existing project credential-delete surface (proposal §5.1,\n * C2-BE-OAUTH-LIFECYCLE): revoking a delegated grant deletes the project\n * credential that backs it. There is no secret in this request or its result.\n */\nexport interface ConnectDisconnectInput {\n credentialId: string;\n}\n\n/**\n * The redacted lifecycle projection of one connection. Reuses the connection\n * inventory's never-secret shapes (common-infra component #7): no token,\n * envelope or fragment ever appears on a ConnectionSummary/Detail.\n */\nexport type ConnectConnectionStatus = ConnectionSummary;\nexport type ConnectConnectionDetail = ConnectionDetail;\n\n// ───────────────────────────────────────────────────────────────────────────\n// MTG-S01-PROVIDER-RAIL@v3 — the product-neutral v1 connect wire.\n//\n// These types mirror the backend connect catalog/authorize/result/disconnect\n// contracts (cloud-agent-backend internal/providers connector_domains.go\n// ConnectCatalogRow + the /connect routes). Two invariants hold across every\n// type below:\n// 1. REDACTED. No token, PKCE verifier, client secret, raw provider id,\n// browser origin or provider error body ever appears — a secret is\n// structurally absent, not merely omitted.\n// 2. SERVER-OWNED AUTHORITY. The client sends only a semantic capability set\n// and the active product/project/sandbox scope; it never sends provider\n// scope strings, credential/connection ids at start, or OAuth state.\n//\n// The five-state vocabulary is REUSED from the connections surface\n// (CapabilityDisplayState) — S01 mints no parallel connect-side state type.\n// ───────────────────────────────────────────────────────────────────────────\n\n/** The connect.authorize.v1 contract version literal. */\nexport const CONNECT_AUTHORIZE_V1 = 'connect.authorize.v1' as const;\n/** The connection.disconnect.v1 contract version literal. */\nexport const CONNECTION_DISCONNECT_V1 = 'connection.disconnect.v1' as const;\n/** The connect.result.v1 contract version literal. */\nexport const CONNECT_RESULT_V1 = 'connect.result.v1' as const;\n\n/**\n * One capability-state row on the redacted connect catalog (backend\n * providers.ConnectCapabilityStateWire). Carries the stable capability id, its\n * owning versioned surface, the reused five-state value, the execution\n * location/profile (present on the PROVIDER_LIFECYCLE probe row), and the\n * applicable condition/degradation/spike/note. It carries NO credential data.\n */\nexport interface ConnectCapabilityState {\n capability: string;\n surface: string;\n state: CapabilityDisplayState;\n executionLocation?: 'sandbox' | 'server-side';\n executionProfile?: string;\n condition?: string;\n degradation?: string;\n spike?: string;\n note?: string;\n}\n\n/**\n * One provider's redacted connect-catalog projection (backend\n * providers.ConnectCatalogRow). Domain / lifecycle-surface membership is a\n * catalog CATEGORY — never connection or execution authority. A client that\n * does not recognise a `domainSurfaceVersions` value or an incomplete\n * capability-state matrix must refuse it, never invent a category or silently\n * treat omission as unsupported.\n */\nexport interface ConnectCatalogRow {\n provider: string;\n displayName: string;\n domains: string[];\n domainSurfaceVersions: Record<string, string>;\n providerLifecycleSurfaceVersion: string;\n capabilityStates: ConnectCapabilityState[];\n}\n\n/**\n * Input to {@link ConnectClient.authorizeStartV1}. Complete/empty/null fields\n * are all invalid server-side: every field is required, and unknown\n * product/provider/capability/version is refused. There is NO browser origin,\n * provider scope string, credential id, connection id, tenant or OAuth URL —\n * those are not fields on this type by construction.\n */\nexport interface ConnectAuthorizeStartV1Input {\n product: string;\n projectId: string;\n sandboxId: string;\n provider: string;\n requestedCapabilities: string[];\n}\n\n/**\n * The authorize-start v1 projection: the opaque server-authored authorization\n * URL (embedding the server-minted one-use state + PKCE challenge) and its\n * expiry. No secret, verifier or raw state rides here.\n */\nexport interface ConnectAuthorizationV1 {\n contractVersion: typeof CONNECT_AUTHORIZE_V1;\n authorizationUrl: string;\n expiresAt: string;\n}\n\n/** The closed outcome vocabulary of a connect result. */\nexport type ConnectResultStatus = 'connected' | 'orphan_grant' | 'failed';\n\n/**\n * The redacted, one-use connect result read back by resultId after the callback\n * (backend GET /connect/results/:resultId). Discriminated on `status`:\n * - connected → identity/capability projection, no secret;\n * - orphan_grant→ token exchange succeeded but local commit failed; the user\n * must restart. Never presented as \"connected\".\n * - failed → a redacted failure class; no provider error body/token.\n */\nexport type ConnectResultV1 =\n | {\n contractVersion: typeof CONNECT_RESULT_V1;\n status: 'connected';\n resultId: string;\n provider: string;\n connectionId: string;\n accountLabel?: string;\n tenantLabel?: string;\n grantedCapabilities: string[];\n }\n | {\n contractVersion: typeof CONNECT_RESULT_V1;\n status: 'orphan_grant';\n resultId: string;\n provider: string;\n }\n | {\n contractVersion: typeof CONNECT_RESULT_V1;\n status: 'failed';\n resultId: string;\n provider: string;\n failureClass: string;\n };\n\n/**\n * Input to {@link ConnectClient.disconnectV1}. The client generates a UUID\n * idempotency key; a repeated call with the same key returns the same terminal\n * projection and performs no second revoke.\n */\nexport interface ConnectDisconnectV1Input {\n connectionId: string;\n idempotencyKey: string;\n}\n\n/**\n * The closed, truthful remote-outcome vocabulary of a disconnect. The UI must\n * never collapse these into \"revoked\": local deletion is not upstream\n * revocation (frozen law 9).\n */\nexport type ConnectDisconnectRemoteOutcome =\n | 'remote_revoked'\n | 'remote_not_supported'\n | 'manual_admin_required'\n | 'remote_unknown'\n | 'not_applicable';\n\n/**\n * The redacted disconnect projection. `localState` reflects that new execution\n * is disabled and the local secret erased; `remoteOutcome` reports the honest\n * upstream result. No secret rides here.\n */\nexport interface ConnectDisconnectV1Result {\n contractVersion: typeof CONNECTION_DISCONNECT_V1;\n connectionId: string;\n localState: 'disconnected';\n remoteOutcome: ConnectDisconnectRemoteOutcome;\n}\n","// Connect catalog / result FAIL-CLOSED validation (MTG-S01-PROVIDER-RAIL@v3,\n// REV-S01-R08 client half). The one canonical SDK connect client validates the\n// EXACT supported connector-domain / lifecycle surface versions and the complete\n// five-state capability matrix, and REFUSES an unknown/missing/extra malformed\n// row rather than inventing a category or silently treating omission as\n// unsupported (types.ts §\"ConnectCatalogRow\"). A non-validating row throws a\n// ConnectCatalogValidationError; the mounted Console (which consumes this client,\n// R01) inherits that refusal and cannot fall back to its own allowlist.\n//\n// The supported set MIRRORS the backend authority\n// (cloud-agent-backend internal/providers/connector_domains.go): six connector\n// domains, each at surface version `v1`, plus the cross-cutting\n// PROVIDER_LIFECYCLE base surface at `v1`. Bumping a version here is a reviewed\n// client change made in lockstep with the backend surface bump — never inferred.\n\nimport type {\n ConnectCatalogRow,\n ConnectCapabilityState,\n ConnectResultV1,\n} from './types.js';\nimport { CONNECT_RESULT_V1 } from './types.js';\nimport type { CapabilityDisplayState } from '../connections/types.js';\n\n/**\n * The exact connector-domain surface versions this client recognises — the six\n * backend connector domains, each at `v1`. A row naming any other domain, or a\n * recognised domain at any other version, is REFUSED (fail closed).\n */\nexport const SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS: Readonly<Record<string, string>> = Object.freeze({\n MEETING_SOURCE: 'v1',\n CRM: 'v1',\n WORK_TRACKING: 'v1',\n CALENDAR: 'v1',\n EMAIL: 'v1',\n CHANNEL_NOTIFICATION: 'v1',\n});\n\n/** The cross-cutting PROVIDER_LIFECYCLE base surface identity + supported version. */\nexport const PROVIDER_LIFECYCLE_SURFACE = 'PROVIDER_LIFECYCLE' as const;\nexport const SUPPORTED_PROVIDER_LIFECYCLE_SURFACE_VERSION = 'v1' as const;\n\n/** The complete, closed five-state capability vocabulary (reused from the\n * connections surface — the SDK mints no parallel state type). A row carrying\n * any other state value is REFUSED. */\nexport const CONNECT_CAPABILITY_DISPLAY_STATES: ReadonlySet<CapabilityDisplayState> = new Set<CapabilityDisplayState>([\n 'supported',\n 'conditional',\n 'degraded',\n 'unavailable',\n 'unknown',\n]);\n\n/** Thrown when a catalog row / result envelope does not satisfy the exact\n * supported surface-version + five-state matrix contract. */\nexport class ConnectCatalogValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConnectCatalogValidationError';\n }\n}\n\nfunction fail(message: string): never {\n throw new ConnectCatalogValidationError(message);\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction requireString(obj: Record<string, unknown>, key: string, ctx: string): string {\n const v = obj[key];\n if (typeof v !== 'string' || v.trim() === '') {\n fail(`${ctx}: field \"${key}\" must be a non-empty string`);\n }\n return v as string;\n}\n\n/** Reject any key not in the allowed set — an EXTRA field is a malformed row. */\nfunction rejectUnknownKeys(obj: Record<string, unknown>, allowed: readonly string[], ctx: string): void {\n for (const k of Object.keys(obj)) {\n if (!allowed.includes(k)) fail(`${ctx}: unexpected field \"${k}\"`);\n }\n}\n\nconst CAPABILITY_STATE_KEYS = [\n 'capability',\n 'surface',\n 'state',\n 'executionLocation',\n 'executionProfile',\n 'condition',\n 'degradation',\n 'spike',\n 'note',\n] as const;\n\nconst CATALOG_ROW_KEYS = [\n 'provider',\n 'displayName',\n 'domains',\n 'domainSurfaceVersions',\n 'providerLifecycleSurfaceVersion',\n 'capabilityStates',\n] as const;\n\n/** Parse `<DOMAIN>@<version>` and refuse an unknown domain or version. The\n * PROVIDER_LIFECYCLE base surface is accepted at its supported version. */\nfunction validateSurfaceId(surface: string, ctx: string): void {\n const at = surface.indexOf('@');\n if (at <= 0 || at === surface.length - 1) {\n fail(`${ctx}: surface \"${surface}\" is not \"<SURFACE>@<version>\"`);\n }\n const name = surface.slice(0, at);\n const version = surface.slice(at + 1);\n if (name === PROVIDER_LIFECYCLE_SURFACE) {\n if (version !== SUPPORTED_PROVIDER_LIFECYCLE_SURFACE_VERSION) {\n fail(`${ctx}: unsupported PROVIDER_LIFECYCLE surface version \"${version}\"`);\n }\n return;\n }\n const supported = SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS[name];\n if (supported === undefined) fail(`${ctx}: unknown connector surface \"${name}\"`);\n if (supported !== version) fail(`${ctx}: unsupported surface version \"${version}\" for \"${name}\"`);\n}\n\nfunction parseCapabilityState(raw: unknown, ctx: string): ConnectCapabilityState {\n if (!isRecord(raw)) fail(`${ctx}: capability state must be an object`);\n rejectUnknownKeys(raw, CAPABILITY_STATE_KEYS, ctx);\n const capability = requireString(raw, 'capability', ctx);\n const surface = requireString(raw, 'surface', ctx);\n validateSurfaceId(surface, `${ctx}.surface`);\n const state = raw.state;\n if (typeof state !== 'string' || !CONNECT_CAPABILITY_DISPLAY_STATES.has(state as CapabilityDisplayState)) {\n fail(`${ctx}: unknown capability state \"${String(state)}\"`);\n }\n const out: ConnectCapabilityState = {\n capability,\n surface,\n state: state as CapabilityDisplayState,\n };\n if (raw.executionLocation !== undefined) {\n if (raw.executionLocation !== 'sandbox' && raw.executionLocation !== 'server-side') {\n fail(`${ctx}: unknown executionLocation \"${String(raw.executionLocation)}\"`);\n }\n out.executionLocation = raw.executionLocation;\n }\n for (const opt of ['executionProfile', 'condition', 'degradation', 'spike', 'note'] as const) {\n if (raw[opt] !== undefined) {\n if (typeof raw[opt] !== 'string') fail(`${ctx}: field \"${opt}\" must be a string`);\n out[opt] = raw[opt] as string;\n }\n }\n return out;\n}\n\n/**\n * Validate one provider's connect-catalog row against the exact supported\n * surface-version + five-state matrix. Throws ConnectCatalogValidationError on\n * any unknown/missing/extra malformed field. Returns the typed row on success.\n */\nexport function parseConnectCatalogRow(raw: unknown): ConnectCatalogRow {\n if (!isRecord(raw)) fail('catalog row must be an object');\n rejectUnknownKeys(raw, CATALOG_ROW_KEYS, 'catalog row');\n const provider = requireString(raw, 'provider', 'catalog row');\n const ctx = `catalog row \"${provider}\"`;\n const displayName = requireString(raw, 'displayName', ctx);\n\n const domains = raw.domains;\n if (!Array.isArray(domains) || domains.length === 0) {\n fail(`${ctx}: \"domains\" must be a non-empty array`);\n }\n for (const d of domains) {\n if (typeof d !== 'string') fail(`${ctx}: domain entries must be strings`);\n if (SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS[d] === undefined) {\n fail(`${ctx}: unknown connector domain \"${d}\"`);\n }\n }\n const domainList = domains as string[];\n\n const dsv = raw.domainSurfaceVersions;\n if (!isRecord(dsv)) fail(`${ctx}: \"domainSurfaceVersions\" must be an object`);\n // Every listed domain has a recognised version...\n for (const d of domainList) {\n const v = dsv[d];\n if (typeof v !== 'string') fail(`${ctx}: missing surface version for domain \"${d}\"`);\n if (SUPPORTED_CONNECTOR_DOMAIN_SURFACE_VERSIONS[d] !== v) {\n fail(`${ctx}: unsupported surface version \"${v}\" for domain \"${d}\"`);\n }\n }\n // ...and no EXTRA version key that is not a listed domain.\n for (const k of Object.keys(dsv)) {\n if (!domainList.includes(k)) fail(`${ctx}: surface version for unlisted domain \"${k}\"`);\n }\n\n const plsv = requireString(raw, 'providerLifecycleSurfaceVersion', ctx);\n if (plsv !== SUPPORTED_PROVIDER_LIFECYCLE_SURFACE_VERSION) {\n fail(`${ctx}: unsupported providerLifecycleSurfaceVersion \"${plsv}\"`);\n }\n\n const capStates = raw.capabilityStates;\n if (!Array.isArray(capStates)) fail(`${ctx}: \"capabilityStates\" must be an array`);\n const capabilityStates = capStates.map((c, i) => parseCapabilityState(c, `${ctx} capabilityStates[${i}]`));\n\n return {\n provider,\n displayName,\n domains: domainList,\n domainSurfaceVersions: { ...(dsv as Record<string, string>) },\n providerLifecycleSurfaceVersion: plsv,\n capabilityStates,\n };\n}\n\n/** Validate a whole catalog: it must be an array and every row must validate.\n * One malformed row rejects the whole catalog — never silently dropped. */\nexport function parseConnectCatalog(raw: unknown): ConnectCatalogRow[] {\n if (!Array.isArray(raw)) fail('connect catalog must be an array');\n return raw.map((r) => parseConnectCatalogRow(r));\n}\n\nconst RESULT_STATUSES = new Set(['connected', 'orphan_grant', 'failed']);\n\n/**\n * Validate the redacted connect result envelope: exact contract version and a\n * known discriminated status with its required fields. Throws on an unknown\n * version/status or a missing required field (fail closed).\n */\nexport function parseConnectResultV1(raw: unknown): ConnectResultV1 {\n if (!isRecord(raw)) fail('connect result must be an object');\n if (raw.contractVersion !== CONNECT_RESULT_V1) {\n fail(`connect result: unsupported contractVersion \"${String(raw.contractVersion)}\"`);\n }\n const status = raw.status;\n if (typeof status !== 'string' || !RESULT_STATUSES.has(status)) {\n fail(`connect result: unknown status \"${String(status)}\"`);\n }\n const resultId = requireString(raw, 'resultId', 'connect result');\n const provider = requireString(raw, 'provider', 'connect result');\n if (status === 'connected') {\n const connectionId = requireString(raw, 'connectionId', 'connect result');\n const granted = raw.grantedCapabilities;\n if (!Array.isArray(granted) || granted.some((g) => typeof g !== 'string')) {\n fail('connect result: \"grantedCapabilities\" must be a string array');\n }\n const out: ConnectResultV1 = {\n contractVersion: CONNECT_RESULT_V1,\n status: 'connected',\n resultId,\n provider,\n connectionId,\n grantedCapabilities: granted as string[],\n };\n if (raw.accountLabel !== undefined) {\n if (typeof raw.accountLabel !== 'string') fail('connect result: accountLabel must be a string');\n out.accountLabel = raw.accountLabel;\n }\n if (raw.tenantLabel !== undefined) {\n if (typeof raw.tenantLabel !== 'string') fail('connect result: tenantLabel must be a string');\n out.tenantLabel = raw.tenantLabel;\n }\n return out;\n }\n if (status === 'orphan_grant') {\n return { contractVersion: CONNECT_RESULT_V1, status: 'orphan_grant', resultId, provider };\n }\n const failureClass = requireString(raw, 'failureClass', 'connect result');\n return { contractVersion: CONNECT_RESULT_V1, status: 'failed', resultId, provider, failureClass };\n}\n","// Connection lifecycle client (MVP09 C2-SDK-CONNECTION, chat-first realignment\n// proposal §5.1). The typed surface the secure connect flow (C2-UI-CONNECTION)\n// drives over the platform-owned delegated-OAuth connect rail. See ./types.ts\n// for the two safety laws (opaque state, no secret fields) and the exact\n// backend routes this mirrors (C2-BE-OAUTH-ROUTES / C2-BE-OAUTH-LIFECYCLE).\n//\n// Surface:\n// apiClient.connect.authorizeStart() — begin the authorization-code flow\n// apiClient.connect.status() — redacted connection inventory (scope)\n// apiClient.connect.refresh() — refetch one connection's redacted state\n// apiClient.connect.disconnect() — revoke the delegated grant\nimport type { BaseClient } from '../../http/BaseClient.js';\nimport type { SimpleKeysResponse } from '../credentials/types.js';\nimport {\n CONNECT_AUTHORIZE_V1,\n CONNECTION_DISCONNECT_V1,\n} from './types.js';\nimport { parseConnectCatalog, parseConnectResultV1 } from './validate.js';\nimport type {\n ConnectAuthorization,\n ConnectAuthorizeStartInput,\n ConnectConnectionDetail,\n ConnectConnectionStatus,\n ConnectDisconnectInput,\n ConnectStatusQuery,\n ConnectCatalogRow,\n ConnectAuthorizeStartV1Input,\n ConnectAuthorizationV1,\n ConnectResultV1,\n ConnectDisconnectV1Input,\n ConnectDisconnectV1Result,\n} from './types.js';\n\nexport class ConnectClient {\n constructor(private readonly http: BaseClient) {}\n\n /**\n * authorizeStart begins the delegated-OAuth authorization-code flow on the\n * platform-owned connect rail (`GET /connect/<slug>`). The server proves\n * workspace ownership, mints an expiring PKCE-bound SIGNED STATE that binds\n * the project/sandbox, and returns ONLY the opaque provider authorize URL;\n * the secure connect surface then navigates the browser to it (the top-level\n * redirect can't carry the bearer token this authed XHR uses). The client\n * sends no OAuth state and holds no secret. A contained provider family\n * answers 503 (surfaced as an HttpError) — availability is never faked here.\n */\n async authorizeStart(input: ConnectAuthorizeStartInput): Promise<ConnectAuthorization> {\n const query: Record<string, string> = { workspaceId: input.workspaceId };\n if (input.origin !== undefined && input.origin !== '') {\n query.origin = input.origin;\n }\n const res = await this.http.get<{ success: boolean; authUrl?: string }>(\n `/connect/${encodeURIComponent(input.provider)}`,\n { query },\n );\n if (!res.authUrl) {\n throw new Error('authorizeStart response missing authUrl.');\n }\n // Return ONLY the opaque URL — never spread the server envelope, so no\n // field the backend might add can smuggle credential material into the\n // projection the connect surface renders.\n return { authUrl: res.authUrl };\n }\n\n /**\n * status returns the redacted connection-status projection for the active\n * project scope (`GET /connections?projectId=`). ConnectionSummary carries\n * health, posture and capability state but NEVER a secret (component #7). An\n * empty list means the inventory has observed nothing yet — it never\n * provisions.\n */\n async status(query: ConnectStatusQuery): Promise<ConnectConnectionStatus[]> {\n const res = await this.http.get<{ success: boolean; connections?: ConnectConnectionStatus[] }>(\n '/connections',\n { query: { projectId: query.projectId } },\n );\n return res.connections ?? [];\n }\n\n /**\n * refresh refetches ONE connection's redacted status projection\n * (`GET /connections/<id>`). The \"refresh status\" connect-card action only\n * refetches the authoritative record (proposal §5.1.5); it mints nothing,\n * connects nothing, and carries no secret. 404 when no member credential is\n * visible to you — existence is not leaked across projects.\n */\n async refresh(connectionId: string): Promise<ConnectConnectionDetail> {\n const res = await this.http.get<{ success: boolean; connection: ConnectConnectionDetail }>(\n `/connections/${encodeURIComponent(connectionId)}`,\n );\n return res.connection;\n }\n\n /**\n * @deprecated Legacy LOCAL credential delete — kept operational for the BI\n * connect surface. It performs `DELETE /credentials/<id>`, which erases the\n * local project credential; it does NOT contact the provider and is NOT an\n * upstream revoke. Do not present its result as \"revoked\". For the\n * product-neutral Meeting rail use {@link ConnectClient.disconnectV1}, which\n * disables local use, advances the connection epoch and returns the honest\n * remote outcome. The redacted envelope carries no secret.\n */\n disconnect(input: ConnectDisconnectInput): Promise<SimpleKeysResponse> {\n return this.http.delete<SimpleKeysResponse>(\n `/credentials/${encodeURIComponent(input.credentialId)}`,\n );\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // MTG-S01-PROVIDER-RAIL@v3 — product-neutral v1 connect wire.\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * getCatalogV1 fetches the redacted connect catalog for a product\n * (`GET /connect/catalog?product=`). Each row carries connector-domain\n * memberships, versioned surface identities and a complete capability-state\n * matrix; the panel groups/filters from this projection and never from a\n * client-side allowlist. A contained family is absent from the catalog. The\n * returned rows carry no credential material.\n */\n async getCatalogV1(product: string): Promise<ConnectCatalogRow[]> {\n const res = await this.http.get<{ success: boolean; providers?: unknown }>(\n '/connect/catalog',\n { query: { product } },\n );\n // Fail closed (R08): validate the exact supported domain/lifecycle surface\n // versions and the complete five-state matrix. A malformed/unknown/extra row\n // REJECTS the whole catalog — never silently dropped, never invented.\n if (res.providers === undefined || res.providers === null) return [];\n return parseConnectCatalog(res.providers);\n }\n\n /**\n * authorizeStartV1 begins the product-neutral authorization-code flow\n * (`POST /connect/authorizations`, contract connect.authorize.v1). The client\n * sends only the active product/project/sandbox scope, the provider and the\n * requested SEMANTIC capabilities — never a scope string, credential id or\n * OAuth state. The server authorizes the editor + Team binding, expands the\n * capabilities to a server-owned scope ceiling, mints an opaque one-use state,\n * and returns only the authorization URL and its expiry.\n */\n async authorizeStartV1(input: ConnectAuthorizeStartV1Input): Promise<ConnectAuthorizationV1> {\n const res = await this.http.post<{\n success: boolean;\n contractVersion?: string;\n authorizationUrl?: string;\n expiresAt?: string;\n }>('/connect/authorizations', {\n body: {\n contractVersion: CONNECT_AUTHORIZE_V1,\n product: input.product,\n projectId: input.projectId,\n sandboxId: input.sandboxId,\n provider: input.provider,\n requestedCapabilities: input.requestedCapabilities,\n },\n });\n if (!res.authorizationUrl || !res.expiresAt) {\n throw new Error('authorizeStartV1 response missing authorizationUrl/expiresAt.');\n }\n // Return ONLY the redacted fields — never spread the envelope.\n return {\n contractVersion: CONNECT_AUTHORIZE_V1,\n authorizationUrl: res.authorizationUrl,\n expiresAt: res.expiresAt,\n };\n }\n\n /**\n * getConnectResultV1 reads back the redacted, bound result of a completed\n * authorization by its opaque resultId (`GET /connect/results/<resultId>`).\n * The result is scoped to the bound user/project/Team; query text is never\n * treated as success authority. The read is idempotent within the bound\n * session so a React double-fetch does not consume it twice.\n */\n async getConnectResultV1(resultId: string): Promise<ConnectResultV1> {\n const res = await this.http.get<{ success: boolean; result?: unknown }>(\n `/connect/results/${encodeURIComponent(resultId)}`,\n );\n if (res.result === undefined || res.result === null) {\n throw new Error('getConnectResultV1 response missing result.');\n }\n // Fail closed (R08): refuse an unknown contract version / status / missing\n // required field rather than trust an unvalidated envelope.\n return parseConnectResultV1(res.result);\n }\n\n /**\n * disconnectV1 disconnects a connection over the product-neutral rail\n * (`POST /connections/<id>/disconnect`, contract connection.disconnect.v1).\n * The client generates the idempotency key; the server disables local use and\n * advances the epoch BEFORE any remote action, then returns the honest remote\n * outcome. A repeated call with the same key returns the same terminal\n * projection and performs no second revoke. Local deletion is never relabelled\n * as upstream revoke.\n */\n async disconnectV1(input: ConnectDisconnectV1Input): Promise<ConnectDisconnectV1Result> {\n const res = await this.http.post<{\n success: boolean;\n contractVersion?: string;\n connectionId?: string;\n localState?: 'disconnected';\n remoteOutcome?: ConnectDisconnectV1Result['remoteOutcome'];\n }>(`/connections/${encodeURIComponent(input.connectionId)}/disconnect`, {\n body: { contractVersion: CONNECTION_DISCONNECT_V1 },\n headers: { 'Idempotency-Key': input.idempotencyKey },\n });\n if (!res.connectionId || !res.remoteOutcome || res.localState !== 'disconnected') {\n throw new Error('disconnectV1 response missing required fields.');\n }\n return {\n contractVersion: CONNECTION_DISCONNECT_V1,\n connectionId: res.connectionId,\n localState: 'disconnected',\n remoteOutcome: res.remoteOutcome,\n };\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport type {\n CapabilitiesResponse,\n ComponentId,\n EnabledComponentsResponse,\n SetEnabledComponentsRequest,\n SetEnabledComponentsResponse,\n} from './types.js';\n\n/**\n * Capability plane client.\n *\n * `get()` is the authenticated per-organization answer every UI surface should\n * gate on. `setEnabledComponents()` is the platform-admin cohort control — the\n * mechanism for enabling one component for an internal cohort only.\n */\nexport class CapabilitiesClient {\n constructor(private readonly http: BaseClient) {}\n\n /** GET /capabilities — the caller organization's effective component set. */\n async get(): Promise<CapabilitiesResponse> {\n return this.http.get<CapabilitiesResponse>('/capabilities');\n }\n\n /**\n * Whether one component may be used by the calling organization.\n *\n * Anything other than an explicit `enabled` is false, including a component\n * absent from the response: an SDK newer than its backend must not treat an\n * unknown component as permitted.\n */\n isEnabled(response: CapabilitiesResponse | undefined, id: ComponentId): boolean {\n return response?.components?.[id] === 'enabled';\n }\n\n /**\n * GET /orgs/:id/enabled-components — platform-admin only.\n *\n * The cohort editor's read: the STORED grant beside the EFFECTIVE state. The\n * READ is admin-gated as well as the write, because another organization's\n * stored grant list is cohort-rollout information.\n */\n async getEnabledComponents(orgId: string): Promise<EnabledComponentsResponse> {\n return this.http.get<EnabledComponentsResponse>(\n `/orgs/${encodeURIComponent(orgId)}/enabled-components`,\n );\n }\n\n /** PATCH /orgs/:id/enabled-components — platform-admin only. */\n async setEnabledComponents(\n orgId: string,\n body: SetEnabledComponentsRequest,\n ): Promise<SetEnabledComponentsResponse> {\n return this.http.patch<SetEnabledComponentsResponse>(\n `/orgs/${encodeURIComponent(orgId)}/enabled-components`,\n { body },\n );\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n AddContactHandleRequest,\n AddContactListMemberRequest,\n Contact,\n ContactAuditPage,\n ContactConflictPair,\n ContactHandle,\n ContactList,\n ContactListGrant,\n ContactListGrantInput,\n ContactSearchQuery,\n ContactSearchResult,\n ContactSettings,\n CreateContactListRequest,\n EraseContactResult,\n GetContactResult,\n ResolveContactRequest,\n ResolveContactResult,\n SetContactHandleFlagsRequest,\n UpdateContactListRequest,\n UpdateContactRequest,\n} from './types.js';\n\n/**\n * Contact registry client (common-infra component #1).\n *\n * Authority splits in two, and the split is enforced server-side — these\n * methods only mirror it:\n *\n * - MEMBERS read (filtered to what they may see), create, edit fields and\n * handles, and own their manual lists. A directory is crowd-maintained or it\n * is empty.\n * - ORG ADMINS additionally own the identity lifecycle: kind changes, merge /\n * unmerge, erase, link / unlink, the posture dial, list grants, tombstone\n * overrides and the audit trail. Those are the governed, audited operations.\n *\n * Impersonation is read-only here (as with credentials): every write returns\n * 403 while impersonating another organization.\n */\nexport class ContactsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n // ── directory ──────────────────────────────────────────────────────────────\n\n /** Search the directory. Results are always visibility-filtered. */\n async list(params: ContactSearchQuery = {}): Promise<ContactSearchResult> {\n const res = await this.http.get<{ success: boolean; data: ContactSearchResult }>(\n `/contacts${this.query({\n query: params.query,\n affiliation: params.affiliation,\n handleKind: params.handleKind,\n handle: params.handle,\n listId: params.listId,\n kind: params.kind,\n status: params.status,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Read one contact. A merged row returns its SURVIVOR plus `alias_of`, so a\n * stale reference degrades gracefully instead of 404-ing.\n */\n async get(id: string): Promise<GetContactResult> {\n const res = await this.http.get<{ success: boolean; data: GetContactResult }>(`/contacts/${id}`);\n return unwrapData(res);\n }\n\n /**\n * Resolve handles to a contact — and the console's CREATE path, since\n * recording a person means claiming their handles.\n *\n * Check `tombstoned` before treating the result as a contact: that outcome\n * means the person was erased and nothing was written.\n */\n async resolve(body: ResolveContactRequest): Promise<ResolveContactResult> {\n const res = await this.http.post<{ success: boolean; data: ResolveContactResult }>('/contacts/resolve', { body });\n return unwrapData(res);\n }\n\n async update(id: string, body: UpdateContactRequest): Promise<Contact> {\n const res = await this.http.put<{ success: boolean; data: Contact }>(`/contacts/${id}`, { body });\n return unwrapData(res);\n }\n\n // ── handles ────────────────────────────────────────────────────────────────\n\n async addHandle(contactId: string, body: AddContactHandleRequest): Promise<ContactHandle> {\n const res = await this.http.post<{ success: boolean; data: ContactHandle }>(`/contacts/${contactId}/handles`, {\n body,\n });\n return unwrapData(res);\n }\n\n async setHandleFlags(contactId: string, handleId: string, body: SetContactHandleFlagsRequest): Promise<void> {\n await this.http.put(`/contacts/${contactId}/handles/${handleId}`, { body });\n }\n\n /** Refused when it would leave the contact with no handles at all. */\n async removeHandle(contactId: string, handleId: string): Promise<void> {\n await this.http.delete(`/contacts/${contactId}/handles/${handleId}`);\n }\n\n // ── lists ──────────────────────────────────────────────────────────────────\n\n /** Lists the caller may see; a restricted list they cannot read is absent. */\n async listLists(): Promise<ContactList[]> {\n const res = await this.http.get<{ success: boolean; data: { items: ContactList[] } }>('/contacts/lists');\n return unwrapData(res).items;\n }\n\n async createList(body: CreateContactListRequest): Promise<ContactList> {\n const res = await this.http.post<{ success: boolean; data: ContactList }>('/contacts/lists', { body });\n return unwrapData(res);\n }\n\n async getList(id: string): Promise<ContactList> {\n const res = await this.http.get<{ success: boolean; data: ContactList }>(`/contacts/lists/${id}`);\n return unwrapData(res);\n }\n\n async updateList(id: string, body: UpdateContactListRequest): Promise<ContactList> {\n const res = await this.http.put<{ success: boolean; data: ContactList }>(`/contacts/lists/${id}`, { body });\n return unwrapData(res);\n }\n\n async deleteList(id: string): Promise<void> {\n await this.http.delete(`/contacts/lists/${id}`);\n }\n\n async listMembers(id: string, params: { skip?: number; take?: number } = {}): Promise<ContactSearchResult> {\n const res = await this.http.get<{ success: boolean; data: ContactSearchResult }>(\n `/contacts/lists/${id}/members${this.query(params)}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Add an existing contact, or an org member by `userId` — the member variant\n * provisions that colleague's contact automatically if it does not exist yet.\n */\n async addListMember(id: string, body: AddContactListMemberRequest): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/lists/${id}/members`, { body });\n return unwrapData(res);\n }\n\n async removeListMember(id: string, contactId: string): Promise<void> {\n await this.http.delete(`/contacts/lists/${id}/members/${contactId}`);\n }\n\n async getGrants(listId: string): Promise<ContactListGrant[]> {\n const res = await this.http.get<{ success: boolean; data: { items: ContactListGrant[] } }>(\n `/contacts/lists/${listId}/grants`,\n );\n return unwrapData(res).items;\n }\n\n /** Replace-set semantics: the supplied grants become the whole grant set. */\n async setGrants(listId: string, grants: ContactListGrantInput[]): Promise<ContactListGrant[]> {\n const res = await this.http.put<{ success: boolean; data: { items: ContactListGrant[] } }>(\n `/contacts/lists/${listId}/grants`,\n { body: { grants } },\n );\n return unwrapData(res).items;\n }\n\n // ── identity lifecycle (org admin) ─────────────────────────────────────────\n\n /** The only path to `guest`. `member` requires an existing user link. */\n async setKind(id: string, kind: Contact['kind']): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/${id}/kind`, { body: { kind } });\n return unwrapData(res);\n }\n\n /** Fold `loserId` into `id`. The path id is the SURVIVOR. */\n async merge(id: string, loserId: string): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/${id}/merge`, {\n body: { loserId },\n });\n return unwrapData(res);\n }\n\n /** Reverse a merge; `id` is the merged (loser) contact being restored. */\n async unmerge(id: string): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/${id}/unmerge`, { body: {} });\n return unwrapData(res);\n }\n\n /**\n * The data-subject erasure: anonymize, drop handles, write suppression\n * tombstones, cascade to product overlays, audit.\n *\n * Refused (422 `user_still_active`) while the contact is linked to an active\n * platform user — registry erasure is not account deletion. Offboard or\n * unlink first.\n */\n async erase(id: string): Promise<EraseContactResult> {\n const res = await this.http.post<{ success: boolean; data: EraseContactResult }>(`/contacts/${id}/erase`, {\n body: { ack: true },\n });\n return unwrapData(res);\n }\n\n async linkUser(id: string, userId: string): Promise<Contact> {\n const res = await this.http.post<{ success: boolean; data: Contact }>(`/contacts/${id}/link`, {\n body: { userId },\n });\n return unwrapData(res);\n }\n\n async unlinkUser(id: string): Promise<Contact> {\n const res = await this.http.delete<{ success: boolean; data: Contact }>(`/contacts/${id}/link`);\n return unwrapData(res);\n }\n\n // ── governance surfaces ────────────────────────────────────────────────────\n\n async getSettings(): Promise<ContactSettings> {\n const res = await this.http.get<{ success: boolean; data: ContactSettings }>('/contacts/settings');\n return unwrapData(res);\n }\n\n /**\n * Flip the org posture. This rewrites no rows: it changes who can see what,\n * and the default visibility of newly created lists.\n */\n async setPosture(posture: ContactSettings['posture']): Promise<ContactSettings> {\n const res = await this.http.put<{ success: boolean; data: ContactSettings }>('/contacts/settings', {\n body: { posture },\n });\n return unwrapData(res);\n }\n\n /**\n * Deliberately re-enable a handle suppressed by an erasure. The tombstone is\n * stamped, never deleted — the override leaves an audited fingerprint.\n */\n async overrideTombstone(handleKind: string, value: string): Promise<void> {\n await this.http.post('/contacts/tombstones/override', { body: { handleKind, value, ack: true } });\n }\n\n async audit(params: { contactId?: string; event?: string; skip?: number; take?: number } = {}): Promise<ContactAuditPage> {\n const res = await this.http.get<{ success: boolean; data: ContactAuditPage }>(\n `/contacts/audit${this.query(params)}`,\n );\n return unwrapData(res);\n }\n\n /** Recent \"two contacts, one person\" ambiguities — the entry point to merge. */\n async conflicts(take?: number): Promise<ContactConflictPair[]> {\n const res = await this.http.get<{ success: boolean; data: { items: ContactConflictPair[] } }>(\n `/contacts/conflicts${this.query({ take })}`,\n );\n return unwrapData(res).items;\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n FactAuditPage,\n FactListResult,\n FactProposalDetail,\n FactStats,\n ListFactsQuery,\n ResolveFactRequest,\n} from './types.js';\n\n/**\n * Fact-governance client (common-infra component #4).\n *\n * The knowledge-review queue: suggested contact merges awaiting an org admin's\n * confirmation. Backend-resident, session-scoped (RLS-pinned by the org-tx\n * middleware) — no scope headers, unlike the engine-proxied action queue.\n *\n * Every route is ADMIN-ONLY (only admins resolve, and admins see all contacts);\n * `resolve` is additionally impersonation-blocked server-side (knowledge writes\n * get the PII-write posture). The MVP surface is read/resolve only — batch, the\n * org-channel notification row, and the ConflictsCard cross-link are the\n * prod-wave delta (02 §0.5).\n */\nexport class FactsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The knowledge-review queue. `state` defaults to `open`. */\n async list(params: ListFactsQuery = {}): Promise<FactListResult> {\n const res = await this.http.get<{ success: boolean; data: FactListResult }>(\n `/facts${this.query({\n category: params.category,\n state: params.state,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** Queue telemetry — powers the section badge. */\n async stats(): Promise<FactStats> {\n const res = await this.http.get<{ success: boolean; data: FactStats }>('/facts/stats');\n return unwrapData(res);\n }\n\n /** One proposal plus its category-shaped preview (the merge preview for contact-merge). */\n async get(id: string): Promise<FactProposalDetail> {\n const res = await this.http.get<{ success: boolean; data: FactProposalDetail }>(\n `/facts/${encodeURIComponent(id)}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Confirm, reject or correct one proposal.\n *\n * Confirm fires the in-process contact merge; reject writes rejection memory;\n * correct flips the survivor of the same pair and then confirms. Throws on 409\n * when somebody else already resolved it — refetch rather than retry.\n */\n async resolve(id: string, body: ResolveFactRequest): Promise<FactProposalDetail> {\n const res = await this.http.post<{ success: boolean; data: FactProposalDetail }>(\n `/facts/${encodeURIComponent(id)}/resolve`,\n { body },\n );\n return unwrapData(res);\n }\n\n /** The admin audit view. Pass a proposal id to scope to one proposal's history. */\n async audit(proposalId?: string, skip?: number, take?: number): Promise<FactAuditPage> {\n const res = await this.http.get<{ success: boolean; data: FactAuditPage }>(\n `/facts/audit${this.query({ proposalId, skip, take })}`,\n );\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n AssetDownload,\n BindRequest,\n CreatePackRequest,\n Pack,\n PackAuditPage,\n PackAuditQuery,\n PackBinding,\n PackBindingsResult,\n PackListPage,\n PackListQuery,\n PackStatus,\n PackVersion,\n PublishResult,\n UpsertDraftRequest,\n UpsertDraftResult,\n} from './types.js';\n\n/**\n * Pack registry client (common-infra component #2).\n *\n * Authority splits server-side; these methods only mirror it:\n *\n * - MEMBERS read (own-org + platform defaults) and author drafts. A draft is\n * inert until published.\n * - ORG ADMINS additionally publish, roll back (set-current), change lifecycle\n * status, bind/unbind into scopes, and org-disable a platform default.\n *\n * Impersonation is read-only here: every write returns 403 while impersonating.\n */\nexport class PacksClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n // ── reads (member-level) ─────────────────────────────────────────────────────\n\n /** List org + default packs, hydrated with current version, disable + binding counts. */\n async list(params: PackListQuery = {}): Promise<PackListPage> {\n const res = await this.http.get<{ success: boolean; data: PackListPage }>(\n `/packs${this.query({\n source: params.source,\n status: params.status,\n productScope: params.productScope,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** One pack with its version summary (stamped history is readable at any status). */\n async get(id: string): Promise<Pack> {\n const res = await this.http.get<{ success: boolean; data: Pack }>(`/packs/${id}`);\n return unwrapData(res);\n }\n\n /** One version with its content metadata (prompt text inlined) + selectors. */\n async getVersion(id: string, versionId: string): Promise<PackVersion> {\n const res = await this.http.get<{ success: boolean; data: PackVersion }>(`/packs/${id}/versions/${versionId}`);\n return unwrapData(res);\n }\n\n /** Download one asset's bytes (base64) — console preview. */\n async getAsset(id: string, versionId: string, name: string): Promise<AssetDownload> {\n const res = await this.http.get<{ success: boolean; data: AssetDownload }>(\n `/packs/${id}/versions/${versionId}/assets/${encodeURIComponent(name)}`,\n );\n return unwrapData(res);\n }\n\n /** The org's pack audit trail. */\n async audit(params: PackAuditQuery = {}): Promise<PackAuditPage> {\n const res = await this.http.get<{ success: boolean; data: PackAuditPage }>(\n `/packs/audit${this.query({\n packId: params.packId,\n event: params.event,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n // ── authoring (member-level) ──────────────────────────────────────────────────\n\n /** Register a new org pack. Source is always 'org'. */\n async create(body: CreatePackRequest): Promise<Pack> {\n const res = await this.http.post<{ success: boolean; data: Pack }>('/packs', { body });\n return unwrapData(res);\n }\n\n /** Create-or-replace the pack's single draft version, wholesale. */\n async upsertDraft(id: string, body: UpsertDraftRequest): Promise<UpsertDraftResult> {\n const res = await this.http.put<{ success: boolean; data: UpsertDraftResult }>(`/packs/${id}/draft`, { body });\n return unwrapData(res);\n }\n\n // ── governance (org-admin) ────────────────────────────────────────────────────\n\n /** Freeze the draft as the next version. Returns the version + any publish warnings. */\n async publish(id: string): Promise<PublishResult> {\n const res = await this.http.post<{ success: boolean; data: PublishResult }>(`/packs/${id}/publish`, { body: {} });\n return unwrapData(res);\n }\n\n /** Repoint currentVersionId to a published version (the rollback op). */\n async setCurrent(id: string, versionId: string): Promise<void> {\n await this.http.post(`/packs/${id}/set-current`, { body: { versionId } });\n }\n\n /** Transition a pack's lifecycle status (active / deprecated / disabled). */\n async setStatus(id: string, status: PackStatus): Promise<Pack> {\n const res = await this.http.post<{ success: boolean; data: Pack }>(`/packs/${id}/status`, { body: { status } });\n return unwrapData(res);\n }\n\n /** Org-disable a platform default pack. */\n async defaultDisable(id: string): Promise<void> {\n await this.http.post(`/packs/${id}/default-disable`, { body: {} });\n }\n\n /** Re-enable a platform default the org had disabled. */\n async defaultEnable(id: string): Promise<void> {\n await this.http.post(`/packs/${id}/default-enable`, { body: {} });\n }\n\n // ── bindings ──────────────────────────────────────────────────────────────────\n\n /** A pack's bindings for the acting org (member-readable). */\n async listBindings(id: string): Promise<PackBinding[]> {\n const res = await this.http.get<{ success: boolean; data: PackBindingsResult }>(`/packs/${id}/bindings`);\n return unwrapData(res).items;\n }\n\n /** Bind a pack into a scope, optionally pinned to a published version (org-admin). */\n async addBinding(id: string, body: BindRequest): Promise<PackBinding> {\n const res = await this.http.post<{ success: boolean; data: PackBinding }>(`/packs/${id}/bindings`, { body });\n return unwrapData(res);\n }\n\n /** Remove a binding (org-admin). */\n async removeBinding(id: string, bindingId: string): Promise<void> {\n await this.http.delete(`/packs/${id}/bindings/${bindingId}`);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n BrandCanonDiff,\n BrandCanonVersion,\n BrandCanonVersionPage,\n BrandConflict,\n BrandEnforcementHitPage,\n BrandEnforcementQuery,\n BrandPinState,\n BrandRoleAffordances,\n BrandStewardRole,\n BrandVersionQuery,\n} from './types.js';\n\n/**\n * Brand Authority client (MKT-IP01, Marketing common-infra surface).\n *\n * Reads a brand's confirmed, versioned canon and its governance state for the\n * console Brand Authority view: the published versions and their diffs, the open\n * confirmation conflicts, the enforcement hits, and the pinned-version state. A\n * brand is exactly one Marketing sandbox, so every read is sandbox-scoped.\n *\n * The routes are read-only here — propose/confirm/publish/rollback are governed\n * by the shared fact-governance loop and the pack registry (a brand fact is a\n * fact; a brand canon version is a pack version). This client's role is the\n * brand-SHAPED read model plus the pure affordance helper the view gates on. The\n * live backend routes are the backend owner's deferred step (MKT-IP01-I08).\n */\nexport class BrandAuthorityClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The published, immutable versions for a brand, newest first. */\n async versions(params: BrandVersionQuery): Promise<BrandCanonVersionPage> {\n const res = await this.http.get<{ success: boolean; data: BrandCanonVersionPage }>(\n `/brand-authority/versions${this.query({\n sandboxId: params.sandboxId,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** One published version, with its enforceable rules and declared sparseness. */\n async version(sandboxId: string, version: number): Promise<BrandCanonVersion> {\n const res = await this.http.get<{ success: boolean; data: BrandCanonVersion }>(\n `/brand-authority/versions/${encodeURIComponent(String(version))}${this.query({ sandboxId })}`,\n );\n return unwrapData(res);\n }\n\n /** The diff between two immutable versions (added / removed / changed rules). */\n async diff(sandboxId: string, fromVersion: number, toVersion: number): Promise<BrandCanonDiff> {\n const res = await this.http.get<{ success: boolean; data: BrandCanonDiff }>(\n `/brand-authority/diff${this.query({ sandboxId, from: fromVersion, to: toVersion })}`,\n );\n return unwrapData(res);\n }\n\n /** Open confirmation conflicts — each carries BOTH sides (MKT-IP01-I03). */\n async conflicts(sandboxId: string): Promise<BrandConflict[]> {\n const res = await this.http.get<{ success: boolean; data: BrandConflict[] }>(\n `/brand-authority/conflicts${this.query({ sandboxId })}`,\n );\n return unwrapData(res);\n }\n\n /** Enforcement hits (drafts refused/warned), each citing rule + canon version. */\n async enforcementHits(params: BrandEnforcementQuery): Promise<BrandEnforcementHitPage> {\n const res = await this.http.get<{ success: boolean; data: BrandEnforcementHitPage }>(\n `/brand-authority/enforcement-hits${this.query({\n sandboxId: params.sandboxId,\n canonVersion: params.canonVersion,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** The pinned-vs-current version state for a brand's running work. */\n async pinState(sandboxId: string): Promise<BrandPinState> {\n const res = await this.http.get<{ success: boolean; data: BrandPinState }>(\n `/brand-authority/pin${this.query({ sandboxId })}`,\n );\n return unwrapData(res);\n }\n}\n\n/**\n * brandRoleAffordances is the pure, fail-closed mapping from a role to the gated\n * controls it may use, at the CURRENT enforced floor (MKT-IP01-I04). Confirm,\n * publish and rollback are org-admin-only; everyone else is a viewer who may only\n * propose (a non-steward may propose only, §8). An unknown role falls through to\n * the viewer floor. This is the ONE place the console gates\n * propose/confirm/publish/rollback, so it is a pure function with an exhaustive\n * test — never a scattered boolean in the view. The per-category steward grade is\n * escalated (MKT-IP01-I04) and is intentionally not represented here.\n */\nexport function brandRoleAffordances(role: BrandStewardRole): BrandRoleAffordances {\n if (role === 'org-admin') {\n return { canPropose: true, canConfirm: true, canPublish: true, canRollback: true };\n }\n return { canPropose: true, canConfirm: false, canPublish: false, canRollback: false };\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n MarketingAudienceSummary,\n MarketingAudienceSummaryQuery,\n ImportMarketingConsentRequest,\n MarketingConsentRecord,\n MarketingConsentRecordQuery,\n} from './types.js';\n\n/**\n * Marketing consent operator client (IMP-MKT04-SURFACE, MKT-IP04 §6).\n *\n * The authenticated, tenant-scoped READ counterpart to the engine's write path:\n * an org administrator can see a subject's current consent state and the event\n * provenance that established it, and the PII-safe approved audience size and\n * exclusion breakdown for a scope+purpose. The org is derived server-side from the\n * verified session (never a request parameter), and RLS fences every read to the\n * tenant. These are read-only surfaces over the durable ledger (migration 0096);\n * the consent-event ingress and unsubscribe are the engine's HMAC machine path.\n */\nexport class MarketingConsentClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /**\n * The consent state + event provenance for one subject/purpose. Returns null\n * when the ledger has no record for the subject — deliberately distinct from a\n * missing route (which throws an HttpError), so a caller never conflates \"no\n * consent recorded\" with \"endpoint absent\".\n */\n async record(params: MarketingConsentRecordQuery): Promise<MarketingConsentRecord | null> {\n const res = await this.http.get<{ success: boolean; data: MarketingConsentRecord | null }>(\n `/marketing-consent/records/${encodeURIComponent(params.contactId)}${this.query({\n purpose: params.purpose,\n project_id: params.projectId,\n sandbox_id: params.sandboxId,\n })}`,\n );\n // A `null` data is a valid absence (the subject has no record); unwrapData only\n // rejects a missing (undefined) `data` field, so null passes through.\n return unwrapData<MarketingConsentRecord | null>(res);\n }\n\n /**\n * The PII-safe audience summary for a scope+purpose: the approved (sendable)\n * member count and the exclusion breakdown (confirmed / pending / unsubscribed).\n */\n async audienceSummary(params: MarketingAudienceSummaryQuery): Promise<MarketingAudienceSummary> {\n const res = await this.http.get<{ success: boolean; data: MarketingAudienceSummary }>(\n `/marketing-consent/audience-summary${this.query({\n purpose: params.purpose,\n project_id: params.projectId,\n sandbox_id: params.sandboxId,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** Records a confirmed, lawful-basis-documented import for an existing active\n * contact. The authenticated backend derives the organization and verifies the\n * project/sandbox parent chain before writing the authoritative projection. */\n async importConsent(body: ImportMarketingConsentRequest): Promise<MarketingConsentRecord> {\n const res = await this.http.post<{ success: boolean; data: MarketingConsentRecord }>(\n '/marketing-consent/imports',\n { body },\n );\n return unwrapData(res);\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n MeetingCitationHydration,\n MeetingConfirmAction,\n MeetingConfirmField,\n MeetingConfirmResolution,\n MeetingFactCategory,\n MeetingFieldState,\n MeetingFilingState,\n MeetingGateBehavior,\n MeetingMinutesDraft,\n MeetingMinutesRevision,\n\n MeetingRetentionSetting,\n\n SetMeetingRetentionSettingRequest,\n CalendarWriteConsent,\n CalendarWriteConsentRequest,\n FollowThroughClassificationMutation,\n FollowThroughClassificationRequest,\n FollowThroughClassificationReview,\n MeetingPrecision,\n MeetingResolution,\n MeetingRoleAffordances,\n MeetingViewerRole,\n} from './types.js';\n\n/**\n * Meeting minutes & confirm-queue client (MTG-IP02; COR-MTG-IP02 I04).\n *\n * Reads a captured meeting's reviewed minutes drafts and its confirmation queue\n * for the console meeting view, both filing-aware (an unfiled meeting is\n * capturer-only). The reads are sandbox-scoped.\n *\n * The live backend read routes are the backend/console owners' deferred step (the\n * console source tree is absent in this working copy). This client's role is the\n * meeting-SHAPED read model plus the pure confirm-loop logic the view gates on —\n * the no-overdue safety, the resolution reducer, the gate behavior and the\n * MM-D044/MM-D041 affordances — all MANUAL-SYNC with the engine.\n */\nexport class MeetingMinutesClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The minutes drafts visible to the viewer in a sandbox (filing-aware). */\n async drafts(sandboxId: string): Promise<MeetingMinutesDraft[]> {\n const res = await this.http.get<{ success: boolean; data: MeetingMinutesDraft[] }>(\n `/meeting-minutes/drafts${this.query({ sandboxId })}`,\n );\n return unwrapData(res);\n }\n\n /** The open confirmation queue for a meeting (owner + inferred-due fields). */\n async confirmQueue(sandboxId: string, occurrence: string): Promise<MeetingConfirmField[]> {\n const res = await this.http.get<{ success: boolean; data: MeetingConfirmField[] }>(\n `/meeting-minutes/confirm-queue${this.query({ sandboxId, occurrence })}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Resolve one queued field: confirm/correct/reject. A reject writes rejection\n * memory server-side, so the same value never re-surfaces. Returns the resolved\n * proposal.\n */\n async resolveConfirmField(\n id: string,\n resolution: MeetingConfirmResolution,\n ): Promise<unknown> {\n const res = await this.http.post<{ success: boolean; data: unknown }>(\n `/meeting-minutes/confirm-queue/${encodeURIComponent(id)}/resolve`,\n { body: resolution },\n );\n return unwrapData(res);\n }\n\n /**\n * The Teams-only correction precision over the org's resolved meeting facts. The\n * number is evidence-phase (it needs real corrections); this reads what the\n * confirm resolutions durably recorded.\n */\n async precision(): Promise<MeetingPrecision> {\n const res = await this.http.get<{ success: boolean; data: MeetingPrecision }>(\n `/meeting-minutes/precision`,\n );\n return unwrapData(res);\n }\n\n /**\n * Hydrate a citation anchor (the click-through). Visibility-fenced and verbatim\n * FAIL-CLOSED — the live open against the tenant is the deferred step.\n */\n async hydrateCitation(\n sandboxId: string,\n occurrence: string,\n anchor: string,\n ): Promise<MeetingCitationHydration> {\n const res = await this.http.get<{ success: boolean; data: MeetingCitationHydration }>(\n `/meeting-minutes/citations/hydrate${this.query({ sandboxId, occurrence, anchor })}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Owner-gated (MM-D041) human minutes revision: a new artifact_substrate version.\n * Refused server-side unless the caller is the meeting owner.\n */\n async reviseMinutes(occurrence: string, revision: MeetingMinutesRevision): Promise<unknown> {\n const res = await this.http.post<{ success: boolean; data: unknown }>(\n `/meeting-minutes/minutes/${encodeURIComponent(occurrence)}/revise`,\n { body: revision },\n );\n return unwrapData(res);\n }\n\n /** Admin-only privacy-control read. The backend resolves the effective,\n * append-only setting under the caller's organization; no client window is an\n * authority for the sweep. */\n async retentionSetting(): Promise<MeetingRetentionSetting> {\n const res = await this.http.get<{ success: boolean; data: MeetingRetentionSetting }>(\n '/meeting-minutes/retention-setting',\n );\n return unwrapData(res);\n }\n\n /** Admin-only audited append of a new forward-only retention setting. */\n async setRetentionSetting(request: SetMeetingRetentionSettingRequest): Promise<MeetingRetentionSetting> {\n const res = await this.http.post<{ success: boolean; data: MeetingRetentionSetting }>(\n '/meeting-minutes/retention-setting', { body: request },\n );\n return unwrapData(res);\n }\n\n /**\n * Admin-only calendar-write consent attestation (MTG-IP05 A7). The backend\n * stamps attestedBy+attestedAt server-side and refuses (422) unless the named\n * credential's scope carries Calendars.ReadWrite. The follow-up calendar act's\n * proposal and execution gates read the resulting state.\n */\n async grantCalendarWriteConsent(request: CalendarWriteConsentRequest): Promise<CalendarWriteConsent> {\n const res = await this.http.post<{ success: boolean; data: CalendarWriteConsent }>(\n '/meeting-minutes/calendar-write-consent/grant', { body: request },\n );\n return unwrapData(res);\n }\n\n /**\n * Admin-only calendar-write consent revocation (MTG-IP05 A7). Durable\n * suppression: the backend stamps revokedBy+revokedAt and the engine gates\n * read the pair as not-granted, failing the calendar path closed.\n */\n async revokeCalendarWriteConsent(request: CalendarWriteConsentRequest): Promise<CalendarWriteConsent> {\n const res = await this.http.post<{ success: boolean; data: CalendarWriteConsent }>(\n '/meeting-minutes/calendar-write-consent/revoke', { body: request },\n );\n return unwrapData(res);\n }\n\n /** Participant-gated review projection for the latest classification epoch. */\n async followThroughClassification(\n sandboxId: string,\n occurrence: string,\n ): Promise<FollowThroughClassificationReview | null> {\n const res = await this.http.get<{\n success: boolean;\n data: FollowThroughClassificationReview | null;\n }>(`/meeting-minutes/followthrough-classification${this.query({ sandboxId, occurrence })}`);\n return unwrapData(res);\n }\n\n /** Confirm the complete family set. This authors a server-owned successor\n * sheet version but never invokes the engine or creates an act. */\n async confirmFollowThroughClassification(\n batchId: string,\n request: FollowThroughClassificationRequest,\n ): Promise<FollowThroughClassificationMutation> {\n const res = await this.http.post<{ success: boolean; data: FollowThroughClassificationMutation }>(\n `/meeting-minutes/followthrough-classification/${encodeURIComponent(batchId)}/confirm`,\n { body: request },\n );\n return unwrapData(res);\n }\n\n /** Return a confirmed, still-unlocked epoch to an empty-family draft. */\n async reviseFollowThroughClassification(\n batchId: string,\n request: FollowThroughClassificationRequest,\n ): Promise<FollowThroughClassificationMutation> {\n const res = await this.http.post<{ success: boolean; data: FollowThroughClassificationMutation }>(\n `/meeting-minutes/followthrough-classification/${encodeURIComponent(batchId)}/revise`,\n { body: request },\n );\n return unwrapData(res);\n }\n}\n\n/**\n * meetingGateBehavior is the DECLARED gate behavior of a meeting fact category\n * (MANUAL-SYNC with engine meetingdistill.CategoryGateBehavior): the two\n * high-stakes fields always confirm; a topic tag never gates.\n */\nexport function meetingGateBehavior(category: MeetingFactCategory): MeetingGateBehavior {\n return category === 'topic-tag' ? 'never-gates' : 'always-confirm';\n}\n\n/**\n * resolveMeetingField is the confirm/correct/reject reducer, MANUAL-SYNC with\n * engine meetingdistill.ResolveField: confirm keeps the extracted value as fact\n * (provenance extracted); correct replaces it as human-provided; reject suppresses\n * it (no value is fact). The console applies this to preview a resolution.\n */\nexport function resolveMeetingField(\n action: MeetingConfirmAction,\n extractedValue: string,\n correctedValue: string,\n): MeetingResolution {\n switch (action) {\n case 'confirm':\n return { state: 'confirmed', value: extractedValue, provenance: 'extracted' };\n case 'correct':\n return { state: 'corrected', value: correctedValue.trim(), provenance: 'human' };\n case 'reject':\n return { state: 'rejected', value: '', provenance: 'extracted' };\n }\n}\n\n/**\n * isMeetingCommitmentOverdue is the no-overdue-from-unconfirmed-due safety rule,\n * MANUAL-SYNC with engine meetingdistill.Overdue: overdue is a claim about a REAL\n * deadline, so it is made ONLY from a due a human confirmed or corrected. An\n * extracted (unconfirmed) inferred due — however far past — is never overdue, and\n * a field with no due never is. The console must not render \"overdue\" otherwise.\n */\nexport function isMeetingCommitmentOverdue(\n state: MeetingFieldState,\n dueISO: string | undefined,\n nowISO: string,\n): boolean {\n if (!dueISO) return false;\n if (state !== 'confirmed' && state !== 'corrected') return false;\n const due = Date.parse(dueISO);\n const now = Date.parse(nowISO);\n if (Number.isNaN(due) || Number.isNaN(now)) return false;\n return now > due;\n}\n\n/**\n * meetingRoleAffordances is the pure MM-D044/MM-D041 affordance logic the meeting\n * view gates on: an unfiled meeting is readable only by its capturer; once filed,\n * sandbox members may read it; any participant may work the confirm queue for a\n * meeting they can see; only the capturer may file; only the meeting owner may\n * revise the minutes. It is fail-closed — an outsider may do nothing.\n */\nexport function meetingRoleAffordances(\n role: MeetingViewerRole,\n filingState: MeetingFilingState,\n isOwner: boolean,\n): MeetingRoleAffordances {\n const filed = filingState === 'filed';\n const canView = role === 'capturer' || (filed && (role === 'participant' || role === 'sandbox-member'));\n return {\n canView,\n // A participant (or the capturer) who can see the meeting may resolve its queue.\n canResolveConfirmations: canView && (role === 'capturer' || role === 'participant'),\n // Only the capturer may file, and only while unfiled.\n canFile: role === 'capturer' && !filed,\n // Only the meeting owner may revise the minutes (MM-D041), once filed.\n canReviseMinutes: filed && isOwner,\n };\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n CommitmentActState,\n CommitmentAggregateStatus,\n CommitmentTracker,\n ResolveConflictRequest,\n} from './types.js';\n\n/**\n * Follow-through commitments tracker & conflict-resolution client (MTG-IP05\n * Wave 4, step 18 / §2.8).\n *\n * Reads the per-association follow-through projection over a meeting's\n * commitments — each commitment's aggregate status (§3.3), its act associations\n * (family, act state, external link, reconciliation), and its one-time nudge\n * state — and resolves a surfaced reconciliation conflict on one association.\n *\n * The tracker read is membership-gated server-side (a non-member sees nothing);\n * the conflict resolve is authority-gated (only the commitment's own owner, or an\n * activated project-owner fallback, may resolve — MM-D041). This client is the\n * read model plus the pure presentation helpers the console view gates on; the\n * authority itself is the backend's, never re-decided here.\n */\nexport class FollowThroughClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /**\n * The commitments tracker for a meeting (or the whole sandbox when occurrence\n * is omitted): one row per commitment with its aggregate status, association\n * sub-rows and nudge state. Membership-fenced server-side.\n */\n async commitments(sandboxId: string, occurrence?: string): Promise<CommitmentTracker[]> {\n const res = await this.http.get<{ success: boolean; data: CommitmentTracker[] }>(\n `/meeting-minutes/commitments${this.query({ sandboxId, occurrence })}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Resolve a surfaced reconciliation conflict on one association (link). The\n * backend applies MM-D041's ownership authority and refuses a non-owner, or a\n * project-owner fallback while the commitment owner is still active — the\n * refusal is recorded. On success the association's observation is closed.\n */\n async resolveConflict(linkId: string, request: ResolveConflictRequest): Promise<unknown> {\n const res = await this.http.post<{ success: boolean; data: unknown }>(\n `/meeting-minutes/commitments/reconciliation/${encodeURIComponent(linkId)}/resolve`,\n { body: request },\n );\n return unwrapData(res);\n }\n}\n\n/**\n * commitmentTrackerStatusLabel is the human label for a commitment's aggregate\n * status, MANUAL-SYNC with the console view-model. `confirmed` is deliberately\n * NOT \"tracked\": §3.3's honesty rule keeps a commitment whose only association is\n * preparing/blocked/failed/rejected/uncertain out of `tracked`.\n */\nexport function commitmentTrackerStatusLabel(status: CommitmentAggregateStatus): string {\n switch (status) {\n case 'proposed':\n return 'Proposed';\n case 'confirmed':\n return 'Confirmed';\n case 'tracked':\n return 'Tracked';\n case 'done':\n return 'Done';\n case 'conflicted':\n return 'Conflict — needs resolution';\n }\n}\n\n/**\n * commitmentActStateLabel renders one association's §3.3 act state honestly: a\n * `preparing` association is \"recovery needed\", never \"sent\". MANUAL-SYNC with\n * the engine's projection and the console view-model.\n */\nexport function commitmentActStateLabel(state: CommitmentActState): string {\n switch (state) {\n case 'preparing':\n return 'Preparing — recovery needed';\n case 'queued':\n return 'Queued';\n case 'executed':\n return 'Filed';\n case 'rejected':\n return 'Rejected';\n case 'blocked':\n return 'Blocked';\n case 'failed':\n return 'Failed';\n case 'uncertain':\n return 'Needs a person';\n case 'superseded':\n return 'Superseded';\n }\n}\n\n/**\n * isCommitmentConflicted reports whether a commitment's aggregate status is a\n * surfaced conflict awaiting human resolution — the single gate the console uses\n * to offer the resolve control.\n */\nexport function isCommitmentConflicted(status: CommitmentAggregateStatus): boolean {\n return status === 'conflicted';\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n CrmHandoffDetail,\n CrmHandoffDisposition,\n CrmHandoffListQuery,\n CrmHandoffOutcome,\n CrmHandoffSummary,\n RecordCrmDispositionRequest,\n} from './types.js';\n\n/**\n * Marketing CRM-handoffs operator client (MKT-IP06 §10 / IMP-MKT06-SURFACE).\n *\n * The authenticated, tenant-scoped surface an org administrator (the marketing lead\n * / sales owner) uses to see the durable CRM handoff records (migration 0094) — the\n * qualified signals that were disclosed, each transport outcome and provider ids, and\n * the current sales disposition — and to record the sales owner's accept /\n * reject-with-reason decision. The org/project are derived server-side from the\n * verified session and a caller-named sandbox; RLS fences every read to the tenant.\n *\n * This client does NOT approve the disclosure act (that binds the confidential\n * qualified-signal artifact and rides the existing approvals surface — see\n * ApprovalsClient) and does NOT report CRM connection health (that is the existing\n * connections surface). The handoff detail carries the artifact + approval refs so a\n * caller can cross-link to inspect exactly what is awaiting approval.\n */\nexport class CrmHandoffsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The sandbox's handoffs, newest first, each with its outcome and current\n * disposition. Admin-only; the scope is server-derived from the sandbox id. */\n async list(params: CrmHandoffListQuery): Promise<CrmHandoffSummary[]> {\n const res = await this.http.get<{ success: boolean; data: CrmHandoffSummary[] }>(\n `/marketing-crm-handoff/handoffs${this.query({ sandboxId: params.sandboxId })}`,\n );\n return unwrapData(res);\n }\n\n /** One handoff in full: outcome, current disposition, resolved readiness-criteria\n * version, artifact + approval refs, and the static boundary statement. */\n async get(id: string): Promise<CrmHandoffDetail> {\n const res = await this.http.get<{ success: boolean; data: CrmHandoffDetail }>(\n `/marketing-crm-handoff/handoffs/${encodeURIComponent(id)}`,\n );\n return unwrapData(res);\n }\n\n /** Record the sales owner's accept / reject-with-reason disposition, prospectively\n * (a new version each time; a prior decision is never rewritten). Returns the\n * recorded decision with its version and server-stamped decider. */\n async recordDisposition(id: string, body: RecordCrmDispositionRequest): Promise<CrmHandoffDisposition> {\n const res = await this.http.post<{ success: boolean; data: CrmHandoffDisposition }>(\n `/marketing-crm-handoff/handoffs/${encodeURIComponent(id)}/disposition`,\n { body },\n );\n return unwrapData(res);\n }\n}\n\n// ── pure presentation helpers (no I/O) ──────────────────────────────────────────\n\n/** A human label for the transport outcome. `uncertain` is deliberately not \"done\":\n * the operator must see that an ambiguous transport was never confirmed. */\nexport function crmHandoffOutcomeLabel(outcome: CrmHandoffOutcome): string {\n switch (outcome) {\n case 'complete':\n return 'Completed';\n case 'partial':\n return 'Partial — contact written, note pending';\n case 'uncertain':\n return 'Uncertain — outcome unconfirmed';\n case 'failed':\n return 'Failed';\n case 'pending':\n return 'Pending';\n default:\n return 'Unknown';\n }\n}\n\n/** Whether a handoff is still awaiting a sales-owner decision. */\nexport function crmHandoffAwaitingDisposition(h: CrmHandoffSummary): boolean {\n return h.disposition == null;\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type { PersonExportDownload, PersonExportStatus } from './types.js';\n\n/**\n * Per-person equivalent-data export client (MTG-IP08 §6 step 8, Google ToS §5.d).\n *\n * §5.d obliges the product to let a person obtain THEIR OWN equivalent data for as\n * long as it stores data derived from the provider API. This client reads that\n * export for one contact — the meetings they took part in, the decisions and\n * commitments attributed to them (by CONFIRMED contact id, never display text), span\n * locators into the exact places those came from, and the minutes they may see.\n *\n * `status` is the lightweight summary (counts + limited/incomplete state) the surface\n * shows before a download; `download` is the full payload. Both are admin-gated,\n * org-isolated reads server-side; the authority is the backend's, never re-decided\n * here. Pass the SAME `asOf` to both so their operation key and snapshot agree.\n */\nexport class PersonExportClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, v);\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /** The per-person export status (counts + limited/incomplete state). */\n async status(sandboxId: string, contactId: string, asOf?: string): Promise<PersonExportStatus> {\n const res = await this.http.get<{ success: boolean; data: PersonExportStatus }>(\n `/meeting-minutes/person-export/status${this.query({ sandboxId, contactId, asOf })}`,\n );\n return unwrapData(res);\n }\n\n /** The full per-person equivalent-data export. */\n async download(sandboxId: string, contactId: string, asOf?: string): Promise<PersonExportDownload> {\n const res = await this.http.get<{ success: boolean; data: PersonExportDownload }>(\n `/meeting-minutes/person-export/download${this.query({ sandboxId, contactId, asOf })}`,\n );\n return unwrapData(res);\n }\n}\n\n/**\n * personExportIsLimited reports whether an export omitted some of the person's\n * meetings (the filing fence). The surface should show `incomplete_reason` when true\n * rather than presenting a partial export as complete.\n */\nexport function personExportIsLimited(status: Pick<PersonExportStatus, 'limited'>): boolean {\n return status.limited === true;\n}\n\n/** personExportIsEmpty reports whether an export holds no equivalent data at all. */\nexport function personExportIsEmpty(\n status: Pick<PersonExportStatus, 'participation_count' | 'decision_count' | 'commitment_count' | 'artifact_count'>,\n): boolean {\n return (\n status.participation_count === 0 &&\n status.decision_count === 0 &&\n status.commitment_count === 0 &&\n status.artifact_count === 0\n );\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n AppendVersionRequest,\n AppendVersionResult,\n ApproveArtifactRequest,\n Artifact,\n ArtifactApproval,\n ArtifactAuditPage,\n ArtifactAuditQuery,\n ArtifactContainer,\n ArtifactHandle,\n ArtifactListPage,\n ArtifactListQuery,\n ArtifactVersionContent,\n ArtifactVersionMeta,\n CreateArtifactRequest,\n} from './types.js';\n\n/**\n * Artifact substrate client (common-infra component #5).\n *\n * Authority splits server-side; these methods only mirror it:\n *\n * - MEMBERS read, mint, edit (append a version) and standalone-approve, WITHIN\n * a container they can reach.\n * - ORG ADMINS additionally archive, read the audit trail, and delete content\n * under a retention policy.\n *\n * Impersonation is read-only here: every write returns 403 while impersonating.\n *\n * # TWO THINGS THAT CHANGED, AND WHY THEY MATTER TO A CALLER\n *\n * **Every call names a CONTAINER.** `containerScope` + `containerRef` are not\n * a filter — they are the confidentiality boundary. The server resolves the\n * caller's real reach from them and refuses an artifact the container does not\n * cover, so passing the project you are looking at is required rather than\n * optional. Omitting `containerScope` means `project`.\n *\n * **Versions are named by HANDLE, never by `versionRef`.** A handle\n * (`artifact:<artifactId>/<versionId>@vN#<sha256>`) is returned by every write\n * and is what you pass back to approve, or attach to an action. `versionRef`\n * is a content reference that two different artifacts can share; it is for\n * display.\n *\n * A version is immutable and content-addressed. `appendVersion` is\n * compare-and-set on head via `parentVersionId` — a stale parent returns 409\n * (`head_moved`) so the caller re-fetches rather than silently forking — and\n * saving canonically identical content is a no-op that returns the existing\n * head.\n */\nexport class ArtifactsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n private container(c: ArtifactContainer): Record<string, string | undefined> {\n return { containerScope: c.containerScope, containerRef: c.containerRef };\n }\n\n // ── reads (member-level, within a reachable container) ───────────────────────\n\n /** List artifacts in one container — the per-project library. */\n async list(params: ArtifactListQuery): Promise<ArtifactListPage> {\n const res = await this.http.get<{ success: boolean; data: ArtifactListPage }>(\n `/artifacts${this.query({\n ...this.container(params),\n status: params.status,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** One artifact (head/approved version ids, no content). */\n async get(id: string, container: ArtifactContainer): Promise<Artifact> {\n const res = await this.http.get<{ success: boolean; data: Artifact }>(\n `/artifacts/${id}${this.query(this.container(container))}`,\n );\n return unwrapData(res);\n }\n\n /** Every version of an artifact, oldest first — the version strip. */\n async listVersions(id: string, container: ArtifactContainer): Promise<{ items: ArtifactVersionMeta[] }> {\n const res = await this.http.get<{ success: boolean; data: { items: ArtifactVersionMeta[] } }>(\n `/artifacts/${id}/versions${this.query(this.container(container))}`,\n );\n return unwrapData(res);\n }\n\n /** One version's metadata plus the handle that names it. */\n async getVersion(\n id: string,\n versionId: string,\n container: ArtifactContainer,\n ): Promise<{ version: ArtifactVersionMeta; handle: ArtifactHandle }> {\n const res = await this.http.get<{\n success: boolean;\n data: { version: ArtifactVersionMeta; handle: ArtifactHandle };\n }>(`/artifacts/${id}/versions/${versionId}${this.query(this.container(container))}`);\n return unwrapData(res);\n }\n\n /**\n * One version's bytes — the panel content view.\n *\n * Throws 410 `content_retention_deleted` for a version whose content was\n * removed under a retention policy. That is a distinct outcome from an empty\n * document and should be shown as one.\n */\n async getContent(id: string, versionId: string, container: ArtifactContainer): Promise<ArtifactVersionContent> {\n const res = await this.http.get<{ success: boolean; data: ArtifactVersionContent }>(\n `/artifacts/${id}/versions/${versionId}/content${this.query(this.container(container))}`,\n );\n return unwrapData(res);\n }\n\n /** Every approval for an artifact, newest first. */\n async listApprovals(id: string, container: ArtifactContainer): Promise<{ items: ArtifactApproval[] }> {\n const res = await this.http.get<{ success: boolean; data: { items: ArtifactApproval[] } }>(\n `/artifacts/${id}/approvals${this.query(this.container(container))}`,\n );\n return unwrapData(res);\n }\n\n /** The org's artifact audit trail (org-admin). */\n async audit(params: ArtifactAuditQuery = {}): Promise<ArtifactAuditPage> {\n const res = await this.http.get<{ success: boolean; data: ArtifactAuditPage }>(\n `/artifacts/audit${this.query({\n artifactId: params.artifactId,\n event: params.event,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n // ── authoring (member-level) ──────────────────────────────────────────────────\n\n /** Mint a new artifact (v1). Returns the handle for the version it created. */\n async create(body: CreateArtifactRequest): Promise<AppendVersionResult> {\n const res = await this.http.post<{ success: boolean; data: AppendVersionResult }>('/artifacts', { body });\n return unwrapData(res);\n }\n\n /**\n * Append an immutable version — the panel's Save. CAS on `parentVersionId`:\n * throws 409 `head_moved` if the head moved since the caller last fetched it.\n */\n async appendVersion(id: string, body: AppendVersionRequest): Promise<AppendVersionResult> {\n const res = await this.http.post<{ success: boolean; data: AppendVersionResult }>(`/artifacts/${id}/versions`, {\n body,\n });\n return unwrapData(res);\n }\n\n /**\n * Standalone approval — the complete draft→edit→approve loop, with no action\n * attached.\n *\n * An approval is a fact about CONTENT. It is never permission to send or\n * publish that content: that is a separate action with its own approval.\n */\n async approve(id: string, body: ApproveArtifactRequest): Promise<ArtifactApproval> {\n const res = await this.http.post<{ success: boolean; data: ArtifactApproval }>(`/artifacts/${id}/approve`, {\n body,\n });\n return unwrapData(res);\n }\n\n // ── governance (org-admin) ────────────────────────────────────────────────────\n\n /** Archive an artifact — no further versions (org-admin). */\n async archive(id: string, container: ArtifactContainer): Promise<void> {\n await this.http.post(`/artifacts/${id}/archive${this.query(this.container(container))}`, { body: {} });\n }\n\n /**\n * Delete one version's CONTENT under a retention policy (org-admin).\n *\n * The version, its type, digest and size survive as audit metadata; only the\n * bytes go. An approved action bound to that version can no longer execute —\n * a retention policy an in-flight action could override would not be one.\n */\n async deleteContentForRetention(\n id: string,\n versionId: string,\n container: ArtifactContainer,\n reason?: string,\n ): Promise<void> {\n await this.http.delete(\n `/artifacts/${id}/versions/${versionId}/content${this.query({ ...this.container(container), reason })}`,\n );\n }\n}\n","import type { BaseClient } from '../../http/BaseClient.js';\nimport { unwrapData } from '../../common/envelope.js';\nimport type {\n ConsumeSignalRequest,\n DismissSignalRequest,\n ListSignalsQuery,\n Signal,\n SignalAuditPage,\n SignalDetail,\n SignalListResult,\n SignalStats,\n} from './types.js';\n\n/**\n * Signal-store client (common-infra component #6).\n *\n * The org's durable record of what is worth acting on — scored, deduplicated\n * and source-attributed. Backend-resident and session-scoped (RLS-pinned by the\n * org-tx middleware), so no scope headers, unlike the engine-proxied action\n * queue.\n *\n * Reads are member-level: the queue is the org's shared attention surface, and\n * hiding it from members would only make the store invisible to the people who\n * have to act on it. `dismiss` is org-admin-only server-side, because it\n * suppresses the whole org's attention.\n *\n * Reads never mutate: listing does not triage, and opening a signal does not\n * consume it.\n */\nexport class SignalsClient {\n constructor(private readonly http: BaseClient) {}\n\n private query(params: Record<string, string | number | boolean | undefined>): string {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== '') q.set(k, String(v));\n }\n const s = q.toString();\n return s ? `?${s}` : '';\n }\n\n /**\n * The signals queue. Returns only what is visible in the caller's scope, plus\n * a coverage envelope naming what was walled off — state that coverage rather\n * than letting two users silently get different answers.\n *\n * Expired signals are excluded unless `includeExpired` is set: they are kept\n * and queryable (that \"we saw this before\" survives is half the point), but\n * they are history, not attention.\n */\n async list(params: ListSignalsQuery = {}): Promise<SignalListResult> {\n const res = await this.http.get<{ success: boolean; data: SignalListResult }>(\n `/signals${this.query({\n kind: params.kind,\n status: params.status,\n priority: params.priority,\n scopeLevel: params.scopeLevel,\n scopeRef: params.scopeRef,\n includeExpired: params.includeExpired,\n skip: params.skip,\n take: params.take,\n })}`,\n );\n return unwrapData(res);\n }\n\n /** Counts by status — powers the section badge. */\n async stats(): Promise<SignalStats> {\n const res = await this.http.get<{ success: boolean; data: SignalStats }>('/signals/stats');\n return unwrapData(res);\n }\n\n /**\n * One signal with its sightings, score + recorded method, evidence,\n * consumptions, predecessor link, and any prior dismissal that an escalation\n * later overrode.\n */\n async get(id: string): Promise<SignalDetail> {\n const res = await this.http.get<{ success: boolean; data: SignalDetail }>(\n `/signals/${encodeURIComponent(id)}`,\n );\n return unwrapData(res);\n }\n\n /**\n * Mark a signal as picked up. An EXPLICIT act — status is org-shared, so it\n * must never be a side effect of somebody opening the page.\n */\n async triage(id: string): Promise<Signal> {\n const res = await this.http.post<{ success: boolean; data: Signal }>(\n `/signals/${encodeURIComponent(id)}/triage`,\n {},\n );\n return unwrapData(res);\n }\n\n /**\n * Deliberately set a signal aside, with a rationale. Org-admin only (403\n * otherwise).\n *\n * Dismissal suppresses DELIVERY at or below the tier the signal currently\n * holds; it never stops recording. A sighting that escalates above that tier\n * reopens the same record with this rationale disclosed — trust that can only\n * ratchet one way is not trust.\n */\n async dismiss(id: string, body: DismissSignalRequest): Promise<Signal> {\n const res = await this.http.post<{ success: boolean; data: Signal }>(\n `/signals/${encodeURIComponent(id)}/dismiss`,\n { body },\n );\n return unwrapData(res);\n }\n\n /** Link what acting on this signal produced, and (by default) mark it consumed. */\n async consume(id: string, body: ConsumeSignalRequest): Promise<Signal> {\n const res = await this.http.post<{ success: boolean; data: Signal }>(\n `/signals/${encodeURIComponent(id)}/consume`,\n { body },\n );\n return unwrapData(res);\n }\n\n /** The admin audit view. Pass a signal id to scope to one signal's history. */\n async audit(signalId?: string, skip?: number, take?: number): Promise<SignalAuditPage> {\n const res = await this.http.get<{ success: boolean; data: SignalAuditPage }>(\n `/signals/audit${this.query({ signalId, skip, take })}`,\n );\n return unwrapData(res);\n }\n}\n","import { BaseClient, type BaseClientOptions } from './http/BaseClient.js';\nimport { AuthClient } from './modules/auth/AuthClient.js';\nimport { MfaClient } from './modules/mfa/MfaClient.js';\nimport { UserClient } from './modules/user/UserClient.js';\nimport { OrganizationClient } from './modules/organization/OrganizationClient.js';\nimport { ProjectsClient } from './modules/projects/ProjectsClient.js';\nimport { SandboxesClient } from './modules/sandboxes/SandboxesClient.js';\nimport { CredentialsClient } from './modules/credentials/CredentialsClient.js';\nimport { ChatClient } from './modules/chat/ChatClient.js';\nimport { TemplatesClient } from './modules/agentEngine/TemplatesClient.js';\nimport { ScheduledTasksClient } from './modules/agentEngine/ScheduledTasksClient.js';\nimport { ResourcesClient } from './modules/resources/ResourcesClient.js';\nimport { SystemEventsClient } from './modules/systemEvents/SystemEventsClient.js';\nimport { SubscriptionsClient } from './modules/billing/SubscriptionsClient.js';\nimport { CreditsClient } from './modules/billing/CreditsClient.js';\nimport { UsageClient } from './modules/usage/UsageClient.js';\nimport { ApprovalsClient } from './modules/approvals/ApprovalsClient.js';\nimport { BudgetsClient } from './modules/budgets/BudgetsClient.js';\nimport { MeteringClient } from './modules/metering/MeteringClient.js';\nimport { ReferralsClient } from './modules/referrals/ReferralsClient.js';\nimport { ResellerClient } from './modules/reseller/ResellerClient.js';\nimport { PlatformAdminClient } from './modules/platformAdmin/PlatformAdminClient.js';\nimport { DeploymentsClient } from './modules/deployments/DeploymentsClient.js';\nimport { CapacityClient } from './modules/capacity/CapacityClient.js';\nimport { BIClient } from './modules/bi/BIClient.js';\nimport { DashboardsClient } from './modules/dashboards/DashboardsClient.js';\nimport { ConnectionsClient } from './modules/connections/ConnectionsClient.js';\nimport { ConnectClient } from './modules/connect/ConnectClient.js';\nimport { CapabilitiesClient } from './modules/capabilities/CapabilitiesClient.js';\nimport { ContactsClient } from './modules/contacts/ContactsClient.js';\nimport { FactsClient } from './modules/facts/FactsClient.js';\nimport { PacksClient } from './modules/packs/PacksClient.js';\nimport { BrandAuthorityClient } from './modules/brandAuthority/BrandAuthorityClient.js';\nimport { MarketingConsentClient } from './modules/marketingConsent/MarketingConsentClient.js';\nimport { MeetingMinutesClient } from './modules/meetingMinutes/MeetingMinutesClient.js';\nimport { FollowThroughClient } from './modules/followThrough/FollowThroughClient.js';\nimport { CrmHandoffsClient } from './modules/crmHandoffs/CrmHandoffsClient.js';\nimport { PersonExportClient } from './modules/personExport/PersonExportClient.js';\nimport { ArtifactsClient } from './modules/artifacts/ArtifactsClient.js';\nimport { SignalsClient } from './modules/signals/SignalsClient.js';\n\nexport type CloudAgentClientOptions = BaseClientOptions;\n\nclass AgentEngineFacade {\n constructor(\n public readonly templates: TemplatesClient,\n public readonly scheduledTasks: ScheduledTasksClient,\n ) {}\n}\n\nclass BillingFacade {\n constructor(\n public readonly subscriptions: SubscriptionsClient,\n public readonly credits: CreditsClient,\n ) {}\n}\n\nexport class CloudAgentClient {\n readonly http: BaseClient;\n readonly auth: AuthClient;\n readonly mfa: MfaClient;\n readonly user: UserClient;\n readonly organization: OrganizationClient;\n readonly projects: ProjectsClient;\n readonly sandboxes: SandboxesClient;\n readonly credentials: CredentialsClient;\n readonly chat: ChatClient;\n readonly agentEngine: AgentEngineFacade;\n readonly resources: ResourcesClient;\n readonly systemEvents: SystemEventsClient;\n readonly billing: BillingFacade;\n readonly usage: UsageClient;\n readonly budgets: BudgetsClient;\n /** SHR-IP08 non-LLM provider metering: per-provider spend caps. */\n readonly metering: MeteringClient;\n /** Action Policy: the approvals queue and its per-scope configuration. */\n readonly approvals: ApprovalsClient;\n readonly referrals: ReferralsClient;\n readonly reseller: ResellerClient;\n readonly platformAdmin: PlatformAdminClient;\n readonly deployments: DeploymentsClient;\n readonly capacity: CapacityClient;\n readonly bi: BIClient;\n readonly dashboards: DashboardsClient;\n /** Contact registry: the org's directory of people it knows about. */\n /** Component capability plane: which common-infrastructure components\n * this deployment has, and which the caller's organization may use. */\n readonly capabilities: CapabilitiesClient;\n readonly contacts: ContactsClient;\n /** Fact-governance: the knowledge-review queue (suggested contact merges). */\n readonly facts: FactsClient;\n readonly connections: ConnectionsClient;\n /** Connection lifecycle (MVP09 C2-SDK-CONNECTION): the typed authorize-start /\n * status / refresh / disconnect surface over the platform-owned\n * delegated-OAuth connect rail. Opaque state, no secret fields — the secure\n * connect flow drives it; secrets/OAuth input never touch chat card JSON. */\n readonly connect: ConnectClient;\n /** Pack registry: the org's published knowledge packs for agent sessions. */\n readonly packs: PacksClient;\n /** Brand Authority (MKT-IP01): a brand's confirmed, versioned canon and its\n * governance state (versions, diffs, conflicts, enforcement hits, pin state). */\n readonly brandAuthority: BrandAuthorityClient;\n /** Marketing consent (MKT-IP04): the operator READ view over the durable consent\n * ledger — a subject's consent state + event provenance, and the PII-safe\n * approved audience count + exclusion breakdown. */\n readonly marketingConsent: MarketingConsentClient;\n /** Meeting minutes (MTG-IP02): distilled minutes drafts, the confirm queue, its\n * confirm/correct/reject resolution, owner-gated minutes revision, correction\n * precision, and citation hydration. */\n readonly meetingMinutes: MeetingMinutesClient;\n /** Follow-through (MTG-IP05): the commitments tracker over per-association act\n * state, reconciliation and one-time nudge, plus surfaced-conflict resolution. */\n readonly followThrough: FollowThroughClient;\n readonly crmHandoffs: CrmHandoffsClient;\n /** Per-person equivalent-data export (MTG-IP08 §5.d): status + full download. */\n readonly personExport: PersonExportClient;\n /** Artifact substrate: versioned documents/briefs/digests with edit-then-approve. */\n readonly artifacts: ArtifactsClient;\n /** Signal store (common-infra #6): the org's durable record of what is worth\n * acting on — scored, deduplicated, and never a trigger. */\n readonly signals: SignalsClient;\n\n constructor(options: CloudAgentClientOptions) {\n this.http = new BaseClient(options);\n this.auth = new AuthClient(this.http);\n this.mfa = new MfaClient(this.http);\n this.user = new UserClient(this.http);\n this.organization = new OrganizationClient(this.http);\n this.projects = new ProjectsClient(this.http);\n this.sandboxes = new SandboxesClient(this.http);\n this.credentials = new CredentialsClient(this.http);\n this.chat = new ChatClient(this.http, { baseUrl: this.http.baseUrl, getToken: options.getToken });\n this.agentEngine = new AgentEngineFacade(\n new TemplatesClient(this.http),\n new ScheduledTasksClient(this.http),\n );\n this.resources = new ResourcesClient(this.http);\n this.systemEvents = new SystemEventsClient(this.http);\n this.billing = new BillingFacade(new SubscriptionsClient(this.http), new CreditsClient(this.http));\n this.usage = new UsageClient(this.http);\n this.budgets = new BudgetsClient(this.http);\n this.metering = new MeteringClient(this.http);\n this.approvals = new ApprovalsClient(this.http);\n this.referrals = new ReferralsClient(this.http);\n this.reseller = new ResellerClient(this.http);\n this.platformAdmin = new PlatformAdminClient(this.http);\n this.deployments = new DeploymentsClient(this.http);\n this.capacity = new CapacityClient(this.http);\n this.bi = new BIClient(this.http, this.http.baseUrl);\n this.dashboards = new DashboardsClient(this.http, this.http.baseUrl);\n this.capabilities = new CapabilitiesClient(this.http);\n this.contacts = new ContactsClient(this.http);\n this.facts = new FactsClient(this.http);\n this.connections = new ConnectionsClient(this.http);\n this.connect = new ConnectClient(this.http);\n this.packs = new PacksClient(this.http);\n this.brandAuthority = new BrandAuthorityClient(this.http);\n this.marketingConsent = new MarketingConsentClient(this.http);\n this.meetingMinutes = new MeetingMinutesClient(this.http);\n this.followThrough = new FollowThroughClient(this.http);\n this.crmHandoffs = new CrmHandoffsClient(this.http);\n this.personExport = new PersonExportClient(this.http);\n this.artifacts = new ArtifactsClient(this.http);\n this.signals = new SignalsClient(this.http);\n }\n}\n","export enum ProviderType {\n LOCAL = 'LOCAL',\n GOOGLE = 'GOOGLE',\n MICROSOFT = 'MICROSOFT',\n GITHUB = 'GITHUB',\n /** Generic OIDC provider (deployment-configured issuer). */\n OIDC = 'OIDC',\n WEB3_STELLAR = 'WEB3_STELLAR',\n}\n\nexport enum AccessType {\n READ = 'READ',\n WRITE = 'WRITE',\n ADMIN = 'ADMIN',\n}\n\nexport enum OrgRoles {\n USER = 0x00,\n BILLING = 0x01,\n WORKSPACES = 0x02,\n ADMINISTRATORS = 0xfe,\n OWNER = 0xff,\n}\n\nexport interface UserSummary {\n id: string;\n name: string;\n lastName: string;\n email: string;\n orgRole?: number | null;\n}\n","export enum MFAType {\n GOOGLE_AUTH = 'GOOGLE_AUTH',\n MAGIC_LINK = 'MAGIC_LINK',\n PASSKEY = 'PASSKEY',\n}\n\nexport interface MFAStatus {\n isEnabled: boolean;\n isRequired: boolean;\n isEnforced: boolean;\n enabledMethods: MFAType[];\n primaryMethod?: MFAType | null;\n sessionVerified: boolean;\n}\n\nexport interface MFASetupResponse {\n success: boolean;\n data?: {\n mfaType: MFAType;\n secret?: string;\n qrCode?: string;\n backupCodes?: string[];\n };\n message?: string;\n}\n\nexport interface MFAVerifySetupRequest {\n mfaType: MFAType;\n code?: string;\n credential?: Record<string, unknown>;\n}\n\nexport interface MFAVerifyLoginRequest {\n mfaType: MFAType;\n code?: string;\n credential?: Record<string, unknown>;\n}\n\nexport interface MFASimpleResponse {\n success: boolean;\n message?: string;\n data?: unknown;\n}\n\nexport interface MFAVerifyLoginResponse {\n success: boolean;\n accessToken?: string;\n refreshToken?: string;\n tokenId?: string;\n expiresAt?: number;\n user?: unknown;\n message?: string;\n error_code?: string;\n}\n\nexport interface MagicLinkSendResponse {\n success: boolean;\n message?: string;\n}\n\nexport interface MagicLinkActivateRequest {\n token: string;\n}\n","import type { PmRecord, PmRecordFamily, PmRevision } from './types.js';\nimport { PM_RECORD_FAMILIES } from './types.js';\n\n/**\n * ClowdPM project-memory coverage — the minimal, explainable completeness\n * summary (PJM-IP02 §7 step 10; architecture §4.6; context model §8 v1).\n *\n * This is the **v1 minimal** summary the surfaces slice ships: it is derived at\n * read time from the records themselves and the project's tailoring declaration,\n * and every area line carries the inputs it was derived from (a poor-man's\n * computation record). It deliberately does NOT implement the full versioned\n * coverage-derivation ENGINE — the per-family expected-set basis and the\n * cadence-freshness evaluation that lift an area to `thin`/`current` — which the\n * memory-core handoff explicitly deferred (it needs persisted computation\n * records). So in v1 an applicable area with any viable record caps at\n * `partial`, and nothing is reported `current`. That under-claim is the honest\n * choice: §4.6/E2 forbid `current` without a proven fresh cadence, and here no\n * cadence-freshness input is wired.\n *\n * Honesty properties preserved from the accepted law:\n * - a tailored-out area is `n/a`, never `none` (E4);\n * - an `extracted`/provisional value does not count as a viable record (§4.6\n * step 2) — it is surfaced separately as `provisionalCount`;\n * - every owner-required family needs an accepted, active registry contact to\n * count as viable; risk additionally requires server readiness, so a sole\n * ownerless risk in an applicable Risk area is `none` (E1);\n * - coverage is DERIVED, never asserted or edited — this function is the only\n * way to obtain it and it takes no state a caller could set.\n */\n\nexport type PmCoverageState = 'n/a' | 'none' | 'thin' | 'partial' | 'current';\n\nexport interface PmCoverageArea {\n family: PmRecordFamily;\n /** Human-friendly area name for the family (e.g. `risk` → \"Risk\"). */\n label: string;\n state: PmCoverageState;\n /** Whether the area is in the tailored (applicable) set. */\n applicable: boolean;\n /** Total records of this family (any origin). */\n totalCount: number;\n /** Records whose current revision is a viable, confirmed (human) record. */\n viableCount: number;\n /** Records whose current revision is provisional (extracted, unconfirmed). */\n provisionalCount: number;\n /** Whether any current revision declares a review cadence (surfaced, not yet used for freshness). */\n cadenceDeclared: boolean;\n /** The derivation, in one sentence — the evidence behind the state label. */\n reason: string;\n}\n\nexport interface PmCoverageSummary {\n /** Whether a `tailoring` record exists — the denominator of every claim. */\n tailoringDeclared: boolean;\n areas: PmCoverageArea[];\n /** A one-line honest caveat about what this v1 summary does and does not prove. */\n note: string;\n}\n\nconst FAMILY_LABELS: Record<string, string> = {\n tailoring: 'Tailoring',\n phase_gate: 'Phase / gate',\n baseline: 'Scope baseline',\n deliverable: 'Deliverables',\n wbs_node: 'Work breakdown',\n activity: 'Activities',\n decision: 'Decisions',\n action: 'Actions',\n risk: 'Risk',\n stakeholder: 'Stakeholders',\n issue: 'Issues',\n assumption: 'Assumptions',\n communication: 'Communications',\n};\n\n// Rolling-compatibility fallback for records read from the pre-policy wire.\n// Current servers return requiresAccountableOwner, including for new families.\nconst OWNER_REQUIRED: ReadonlySet<string> = new Set([\n 'tailoring',\n 'phase_gate',\n 'baseline',\n 'decision',\n 'action',\n 'activity',\n 'risk',\n 'stakeholder',\n 'issue',\n 'assumption',\n 'communication',\n]);\n\n/**\n * Small, non-exhaustive map from a family to the tailoring-declaration keys that\n * mark its area applicable. It is intentionally minimal (the prompt: do not\n * build exhaustive classification tables): an unmatched family defaults to\n * applicable and says so, rather than hiding the area.\n */\nconst DISCIPLINE_ALIASES: Partial<Record<PmRecordFamily, readonly string[]>> = {\n baseline: ['scope', 'schedule', 'baseline'],\n deliverable: ['scope'],\n wbs_node: ['scope'],\n activity: ['schedule'],\n risk: ['risk'],\n stakeholder: ['stakeholder', 'stakeholders'],\n communication: ['communication', 'communications'],\n decision: ['knowledge', 'change', 'decision', 'decisions'],\n issue: ['issue', 'issues', 'execution'],\n assumption: ['assumption', 'assumptions', 'constraint', 'constraints'],\n action: ['action', 'actions', 'execution'],\n};\n\n// Families always in the applicable set (Initiating is mandatory, §8.3).\nconst ALWAYS_APPLICABLE: ReadonlySet<PmRecordFamily> = new Set(['tailoring', 'phase_gate']);\n\nfunction readDisciplines(records: PmRecord[]): Record<string, boolean> | null {\n const tailoring = records\n .filter((r) => r.family === 'tailoring' && isViable(r))\n .reduce<PmRecord | undefined>((latest, candidate) => {\n if (!latest) return candidate;\n return (candidate.current?.authoredAt ?? '') > (latest.current?.authoredAt ?? '')\n ? candidate\n : latest;\n }, undefined);\n const payload = tailoring?.current?.payload;\n if (!payload || typeof payload !== 'object') return null;\n const disciplines = (payload as { disciplines?: unknown }).disciplines;\n if (!disciplines || typeof disciplines !== 'object') return null;\n const out: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(disciplines as Record<string, unknown>)) {\n out[k.toLowerCase()] = v === true;\n }\n return out;\n}\n\n/**\n * Applicability under the tailoring declaration. Returns `true`/`false` when the\n * declaration decides it, or `null` when the area is not individually declared\n * (caller defaults it to applicable and notes the gap).\n */\nfunction applicabilityOf(\n family: PmRecordFamily,\n disciplines: Record<string, boolean> | null,\n): boolean | null {\n if (ALWAYS_APPLICABLE.has(family)) return true;\n if (!disciplines) return null;\n const keys = [family, ...(DISCIPLINE_ALIASES[family] ?? [])].map((k) => k.toLowerCase());\n let sawKey = false;\n for (const key of keys) {\n if (key in disciplines) {\n sawKey = true;\n if (disciplines[key]) return true; // any matching on-key makes the area applicable\n }\n }\n return sawKey ? false : null; // all matching keys off → tailored out; none present → undeclared\n}\n\nfunction isViable(record: PmRecord): boolean {\n const rev = record.current;\n if (!rev) return false;\n if (rev.origin !== 'human') return false; // an extracted/provisional value is not a viable record\n const requiresOwner = record.requiresAccountableOwner ?? OWNER_REQUIRED.has(rev.family);\n if (requiresOwner) {\n const namedActiveOwner =\n !!rev.accountableContactId?.trim() &&\n rev.accountableContactStatus === 'active' &&\n rev.accountableState === 'accepted';\n if (!namedActiveOwner) return false;\n }\n const requiresSubject = record.requiresSubjectContact ?? rev.family === 'stakeholder';\n if (\n requiresSubject &&\n (!record.subjectContactId?.trim() || record.subjectContactStatus !== 'active')\n ) {\n return false;\n }\n if (rev.family === 'risk' && rev.readiness !== 'ready') return false;\n return true;\n}\n\nfunction declaresCadence(rev: PmRevision): boolean {\n const p = rev.payload;\n if (!p || typeof p !== 'object') return false;\n const o = p as Record<string, unknown>;\n const cadence = o.cadence ?? o.reviewCadence ?? o.review_cadence;\n return typeof cadence === 'string' && cadence.trim().length > 0;\n}\n\n/**\n * Derive the minimal completeness summary from a project's records. Pure: same\n * records in ⇒ same summary out, with no hidden state.\n */\nexport function derivePmCoverage(records: PmRecord[]): PmCoverageSummary {\n const disciplines = readDisciplines(records);\n // An extracted tailoring proposal cannot choose the completeness denominator.\n // Only a human-authored declaration may tailor an area in or out.\n const tailoringDeclared = records.some(\n (r) => r.family === 'tailoring' && isViable(r),\n );\n\n const families: PmRecordFamily[] = [\n ...PM_RECORD_FAMILIES,\n ...records\n .map((r) => r.family)\n .filter((family) => !(PM_RECORD_FAMILIES as readonly string[]).includes(family)),\n ].filter((family, index, all) => all.indexOf(family) === index);\n\n const areas: PmCoverageArea[] = families.map((family) => {\n const family_records = records.filter((r) => r.family === family && r.current);\n const totalCount = family_records.length;\n let viableCount = 0;\n let provisionalCount = 0;\n let cadenceDeclared = false;\n for (const r of family_records) {\n const rev = r.current!;\n if (isViable(r)) viableCount += 1;\n if (rev.provisional) provisionalCount += 1;\n if (declaresCadence(rev)) cadenceDeclared = true;\n }\n\n const declared = applicabilityOf(family, disciplines);\n const applicable = declared !== false; // undeclared (null) defaults to applicable, flagged below\n const label = FAMILY_LABELS[family] ?? family.split('_').join(' ');\n\n let state: PmCoverageState;\n let reason: string;\n if (declared === false) {\n state = 'n/a';\n reason = `Tailored out in the tailoring declaration; nothing is expected.`;\n } else if (viableCount === 0) {\n state = 'none';\n if (totalCount === 0) {\n reason = `Applicable, but no ${label.toLowerCase()} records are recorded yet.`;\n } else if (family === 'risk' && provisionalCount + totalCount > 0) {\n reason = `Applicable; ${totalCount} record(s) present but none viable — a risk needs an accepted, named owner to count.`;\n } else {\n reason = `Applicable; ${totalCount} record(s) present but none viable (still provisional or missing a required accepted, active owner/subject).`;\n }\n } else {\n state = 'partial';\n const undeclaredNote =\n declared === null && !ALWAYS_APPLICABLE.has(family)\n ? ' (area not individually tailored — assumed applicable)'\n : '';\n const provisionalNote = provisionalCount > 0 ? `, ${provisionalCount} still provisional` : '';\n reason = `${viableCount} of ${totalCount} record(s) viable${provisionalNote}${undeclaredNote}; caps at partial — expected-set completeness and cadence freshness are not evaluated in this minimal summary.`;\n }\n\n return {\n family,\n label,\n state,\n applicable,\n totalCount,\n viableCount,\n provisionalCount,\n cadenceDeclared,\n reason,\n };\n });\n\n const note = tailoringDeclared\n ? 'Minimal completeness summary (v1): applicability from the tailoring declaration, viability from confirmed records. Expected-set completeness and cadence freshness — which lift an area to current — are not yet evaluated, so no area reads current.'\n : 'No tailoring declaration is recorded yet, so applicability is assumed rather than authoritative. Declare tailoring to make completeness meaningful.';\n\n return { tailoringDeclared, areas, note };\n}\n","// ClowdPM customer-document grounding and disposition views (PJM-IP03 /\n// IMP-PJ-DOC-SURFACES). Pure, read-time helpers over the wire shapes in\n// `types.ts` — they assert no authority, mint no identity, and never delete.\n//\n// GROUNDING (PJM-S01 grounding half). A record or status CLAIM is grounded to a\n// customer document by CITING an exact version + span — never by copying its\n// bytes. The citation is an EvidenceRef in the ratified citation vocabulary\n// (kind `source-doc`; its target/pins bind the artifact version), carried in the\n// free-form record-revision `payload.evidence` array. It is read back with\n// the document's LIVE attestation state resolved at the citation, so a downstream\n// reader (IP04/IP05) can see whether the cited document is authorised to share.\n//\n// DISPOSITION VIEW. A disposition request is surfaced as HELD/denied/deferred and\n// — structurally — never executable: this module exposes no execute path and its\n// view says so plainly (the fail-closed hold until F-PJM-047 lands).\n\nimport type {\n PmAttestationState,\n PmCustomerDocument,\n PmDispositionRequest,\n} from './types.js';\nimport type {\n EvidenceGrade,\n EvidencePins,\n EvidenceRef,\n EvidenceRefTarget,\n} from '../chat/types.js';\n\n/** Evidence grades, mirroring the citation vocabulary (verbatim | paraphrase | derived). */\nexport type PmEvidenceGrade = EvidenceGrade;\n\n/**\n * A grounding citation to an exact customer-document version + span. It is an\n * EvidenceRef in the `source-doc` kind. The canonical locator names the scoped\n * project/document/artifact/version/span tuple; the immutable hash and capture\n * time are carried by the ratified target/pins fields. Evidence is pinned by\n * REFERENCE, never by copying content.\n */\nexport interface PmDocumentCitation extends EvidenceRef {\n /** Selects the citation resolver. Fixed to the document kind. */\n kind: 'source-doc';\n /** Ratified source-doc target. The canonical locator carries project/doc/artifact/version/span. */\n ref: EvidenceRefTarget & {\n locator: string;\n captured_at: string;\n content_hash: string;\n };\n /** Ratified reproducibility pins for the exact artifact version. */\n pins: EvidencePins & {\n dataset_refs: string[];\n captured_at: string;\n };\n}\n\n/** Parsed, validated PM fields carried inside the canonical EvidenceRef locator. */\nexport interface PmDocumentCitationParts {\n projectId: string;\n documentId: string;\n artifactId: string;\n versionId: string;\n span: string;\n}\n\n/** A citation resolved against the live document set — the read-side view. */\nexport interface PmResolvedCitation extends PmDocumentCitation {\n /** True only when the exact visible version/hash tuple is verified. */\n resolved: boolean;\n /** Distinguishes a visible document from a verified exact version. */\n documentVisible: boolean;\n versionVerified: boolean;\n projectId?: string;\n documentId?: string;\n artifactId?: string;\n versionId?: string;\n span?: string;\n title?: string;\n classification?: string;\n /**\n * Live attestation state AT the citation. `unknown` when the document is not\n * visible to this reader (non-member, or erased) — never silently `attested`.\n */\n attestationState: PmAttestationState | 'unknown';\n /**\n * True when the citation pins the document's CURRENT head version. This\n * surface deliberately refuses to claim an unverified historical version.\n */\n pinsCurrentVersion: boolean;\n}\n\n/**\n * Builds a canonical EvidenceRef for the document's exact CURRENT head + a\n * required human-readable source span. Older versions remain readable from\n * already-recorded citations, but this helper cannot assert one because the\n * document-list surface exposes only the verified current head.\n */\nexport function buildDocumentCitation(\n doc: Pick<\n PmCustomerDocument,\n 'id' | 'projectId' | 'artifactId' | 'headVersionId' | 'contentHash' | 'uploadedAt'\n >,\n opts: { span: string },\n): PmDocumentCitation {\n const projectId = doc.projectId.trim();\n const documentId = doc.id.trim();\n const artifactId = doc.artifactId.trim();\n const versionId = doc.headVersionId.trim();\n const contentHash = doc.contentHash.trim();\n const capturedAt = doc.uploadedAt.trim();\n const span = opts.span.trim();\n if (!projectId || !documentId || !artifactId || !versionId || !span) {\n throw new Error('project, document, artifact, current version and cited span are required.');\n }\n if (span.length > 512) throw new Error('cited span must be at most 512 characters.');\n if (!/^[0-9a-f]{64}$/.test(contentHash)) {\n throw new Error('document contentHash must be a lowercase SHA-256 digest.');\n }\n if (!capturedAt || Number.isNaN(Date.parse(capturedAt))) {\n throw new Error('document uploadedAt must be a valid provenance timestamp.');\n }\n const query = new URLSearchParams({\n project: projectId,\n document: documentId,\n artifact: artifactId,\n version: versionId,\n span,\n });\n return {\n kind: 'source-doc',\n ref: {\n locator: `pm-document://citation?${query.toString()}`,\n captured_at: capturedAt,\n content_hash: contentHash,\n },\n pins: {\n dataset_refs: [`artifact:${artifactId}`, `version:${versionId}`],\n captured_at: capturedAt,\n },\n };\n}\n\n/** Parses the canonical PM locator and verifies its EvidenceRef pins. */\nexport function parsePmDocumentCitation(value: unknown): PmDocumentCitationParts | undefined {\n if (!value || typeof value !== 'object') return undefined;\n const citation = value as Partial<PmDocumentCitation>;\n if (citation.kind !== 'source-doc' || !citation.ref || typeof citation.ref !== 'object') return undefined;\n const locator = citation.ref.locator;\n const contentHash = citation.ref.content_hash;\n const capturedAt = citation.ref.captured_at;\n if (typeof locator !== 'string' || typeof contentHash !== 'string' || typeof capturedAt !== 'string') return undefined;\n if (!/^[0-9a-f]{64}$/.test(contentHash) || Number.isNaN(Date.parse(capturedAt)) ||\n !citation.pins || citation.pins.captured_at !== capturedAt) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(locator);\n } catch {\n return undefined;\n }\n if (parsed.protocol !== 'pm-document:' || parsed.hostname !== 'citation' || parsed.username || parsed.password || parsed.port ||\n (parsed.pathname !== '' && parsed.pathname !== '/') || parsed.hash) return undefined;\n const allowedKeys = new Set(['project', 'document', 'artifact', 'version', 'span']);\n if ([...parsed.searchParams.keys()].some((key) => !allowedKeys.has(key))) return undefined;\n const one = (key: string): string | undefined => {\n const values = parsed.searchParams.getAll(key);\n const v = values.length === 1 ? values[0]?.trim() : '';\n return v || undefined;\n };\n const parts: PmDocumentCitationParts = {\n projectId: one('project') ?? '',\n documentId: one('document') ?? '',\n artifactId: one('artifact') ?? '',\n versionId: one('version') ?? '',\n span: one('span') ?? '',\n };\n if (Object.values(parts).some((v) => !v) || parts.span.length > 512) return undefined;\n const refs = citation.pins.dataset_refs;\n if (!Array.isArray(refs) || !refs.includes(`artifact:${parts.artifactId}`) || !refs.includes(`version:${parts.versionId}`)) {\n return undefined;\n }\n return parts;\n}\n\n/** Type guard for a canonical PM document EvidenceRef on the wire. */\nexport function isPmDocumentCitation(value: unknown): value is PmDocumentCitation {\n return parsePmDocumentCitation(value) !== undefined;\n}\n\n/** Reads the grounding citations out of a free-form record-revision payload. */\nexport function readClaimCitations(payload: unknown): PmDocumentCitation[] {\n if (!payload || typeof payload !== 'object') return [];\n const evidence = (payload as { evidence?: unknown }).evidence;\n if (!Array.isArray(evidence)) return [];\n return evidence.filter(isPmDocumentCitation);\n}\n\n/**\n * Grounds a claim by adding a document citation to a record-revision payload's\n * `evidence` array, immutably. Reuses an existing citation slot for the same\n * document version (idempotent re-grounding); otherwise appends. Returns a NEW\n * payload object — the input is never mutated. Non-object payloads are treated as\n * empty and wrapped, so a first citation is safe on a fresh record.\n */\nexport function groundClaimPayload(payload: unknown, citation: PmDocumentCitation): Record<string, unknown> {\n const incoming = parsePmDocumentCitation(citation);\n if (!incoming) throw new Error('cannot ground a claim with an invalid PM document EvidenceRef.');\n const base: Record<string, unknown> =\n payload && typeof payload === 'object' ? { ...(payload as Record<string, unknown>) } : {};\n const evidence = Array.isArray(base.evidence) ? base.evidence : [];\n // Preserve heterogeneous EvidenceRefs. The old implementation rebuilt the\n // array from PM refs only and silently deleted queries/signals/other sources.\n const withoutDuplicate = evidence.filter((entry) => {\n const existing = parsePmDocumentCitation(entry);\n return !existing || existing.projectId !== incoming.projectId ||\n existing.documentId !== incoming.documentId || existing.versionId !== incoming.versionId;\n });\n base.evidence = [...withoutDuplicate, citation];\n return base;\n}\n\n/** Removes a document-version citation from a claim payload, immutably. */\nexport function ungroundClaimPayload(\n payload: unknown,\n documentId: string,\n versionId: string,\n): Record<string, unknown> {\n const base: Record<string, unknown> =\n payload && typeof payload === 'object' ? { ...(payload as Record<string, unknown>) } : {};\n const evidence = Array.isArray(base.evidence) ? base.evidence : [];\n const kept = evidence.filter((entry) => {\n const c = parsePmDocumentCitation(entry);\n return !c || c.documentId !== documentId || c.versionId !== versionId;\n });\n if (kept.length > 0) base.evidence = kept;\n else delete base.evidence;\n return base;\n}\n\n/**\n * Resolves a citation against the documents the reader can see, surfacing the\n * live attestation state AT the citation. A citation whose document is not in\n * `docs` (a non-member reader, or an erased document) resolves to `unknown`\n * attestation — never silently treated as attested.\n */\nexport function resolveCitation(\n citation: PmDocumentCitation,\n docs: readonly PmCustomerDocument[],\n): PmResolvedCitation {\n const parts = parsePmDocumentCitation(citation);\n const doc = parts\n ? docs.find((d) => d.id === parts.documentId && d.projectId === parts.projectId && d.artifactId === parts.artifactId)\n : undefined;\n if (!doc || !parts) {\n return {\n ...citation,\n resolved: false,\n documentVisible: false,\n versionVerified: false,\n attestationState: 'unknown',\n pinsCurrentVersion: false,\n ...parts,\n };\n }\n const pinsCurrentVersion = parts.versionId === doc.headVersionId;\n const versionVerified = pinsCurrentVersion && citation.ref.content_hash === doc.contentHash;\n return {\n ...citation,\n ...parts,\n resolved: versionVerified,\n documentVisible: true,\n versionVerified,\n title: doc.title,\n classification: doc.classification,\n attestationState: doc.attestationState,\n pinsCurrentVersion,\n };\n}\n\n/** Resolves every citation on a claim payload against the visible document set. */\nexport function resolveClaimCitations(\n payload: unknown,\n docs: readonly PmCustomerDocument[],\n): PmResolvedCitation[] {\n return readClaimCitations(payload).map((c) => resolveCitation(c, docs));\n}\n\n// ── Disposition view (held / denied / deferred — never executed) ─────────────\n\n/**\n * A read-time summary of a disposition request for display. `executable` is\n * ALWAYS false: this product has no deletion-execution path (the fail-closed hold\n * until F-PJM-047 lands), so a surface built on this view can never present an\n * execute button. `heldForExecution` marks the approved-in-principle state whose\n * deletion is withheld.\n */\nexport interface PmDispositionView {\n id: string;\n documentId: string;\n state: PmDispositionRequest['state'];\n /** Structural: deletion execution is non-expressible in this release. Always false. */\n executable: false;\n /** True for the `held` state — approved in principle, execution withheld. */\n heldForExecution: boolean;\n /** True once the request has been decided (denied/deferred/held). */\n decided: boolean;\n /** A short, honest human label for the current state. */\n label: string;\n /** The persisted reason / policy basis, if any — surfaced verbatim. */\n reason?: string;\n policyBasis?: string;\n authorityKind?: PmDispositionRequest['authorityKind'];\n}\n\nconst DISPOSITION_LABELS: Record<PmDispositionRequest['state'], string> = {\n requested: 'Requested — awaiting review',\n under_review: 'Under review by the disposition authority',\n denied: 'Denied — the document is retained',\n deferred: 'Deferred — revisit later',\n held: 'Approved in principle; deletion held (governed execution not yet available)',\n};\n\n/**\n * Summarizes a disposition request for an honest, execution-free display. It\n * never fabricates an execute affordance: `executable` is structurally false.\n */\nexport function summarizeDisposition(req: PmDispositionRequest): PmDispositionView {\n const decided = req.state === 'denied' || req.state === 'deferred' || req.state === 'held';\n return {\n id: req.id,\n documentId: req.documentId,\n state: req.state,\n executable: false,\n heldForExecution: req.state === 'held',\n decided,\n label: DISPOSITION_LABELS[req.state] ?? req.state,\n reason: req.decisionReason ?? req.resolutionReason ?? req.requestReason ?? undefined,\n policyBasis: req.policyBasis ?? undefined,\n authorityKind: req.authorityKind ?? undefined,\n };\n}\n","// ClowdPM status-report read-time views (PJM-IP04 / IMP-PJ-STATUS). Pure helpers\n// over the wire shapes in `types.ts` — they compute no authority and mint no\n// identity. They exist so a surface (the console) renders an evidence-linked\n// status draft honestly: claims grouped by class, numbers resolved to their\n// recorded computation, coverage/diff summarized, and the non-editable coverage\n// statement + honest phase/gate carried through verbatim.\n\nimport type {\n PmClaimClass,\n PmComputation,\n PmReportCoverageState,\n PmStatusClaim,\n PmStatusReport,\n} from './types.js';\n\n/** Claims split by class, in the order a reader should read them. */\nexport interface PmClassedClaims {\n facts: PmStatusClaim[];\n interpretations: PmStatusClaim[];\n recommendations: PmStatusClaim[];\n}\n\n/** Groups a narrative's claims by class. A claim of an unknown class is dropped\n * from the classed view rather than silently shown as a fact. */\nexport function groupClaimsByClass(claims: readonly PmStatusClaim[]): PmClassedClaims {\n const out: PmClassedClaims = { facts: [], interpretations: [], recommendations: [] };\n for (const claim of claims) {\n switch (claim.class) {\n case 'fact':\n out.facts.push(claim);\n break;\n case 'interpretation':\n out.interpretations.push(claim);\n break;\n case 'recommendation':\n out.recommendations.push(claim);\n break;\n default:\n break;\n }\n }\n return out;\n}\n\n/**\n * Resolves a claim's cited computation KEYS against a report's recorded\n * computations — the \"a number opens its computation\" resolution, done locally\n * from the report the reader already holds. Keys with no recorded computation\n * are omitted (a number can never render without one, so this should be empty),\n * so the caller can trust every returned entry is real.\n */\nexport function resolveClaimComputations(\n claim: Pick<PmStatusClaim, 'evidence'>,\n report: Pick<PmStatusReport, 'computations'>,\n): PmComputation[] {\n const keys = claim.evidence.computations ?? [];\n const byKey = new Map(report.computations.map((c) => [c.computationKey, c]));\n const out: PmComputation[] = [];\n for (const key of keys) {\n const found = byKey.get(key);\n if (found) out.push(found);\n }\n return out;\n}\n\n/** Finds one recorded computation by its stable key within a report. */\nexport function computationByKey(\n report: Pick<PmStatusReport, 'computations'>,\n key: string,\n): PmComputation | undefined {\n return report.computations.find((c) => c.computationKey === key);\n}\n\n/** A short, honest human label for a coverage state (plain language, PJ-D014). */\nexport function coverageStateLabel(state: PmReportCoverageState): string {\n switch (state) {\n case 'n/a':\n return 'Not applicable (tailored out)';\n case 'none':\n return 'Empty';\n case 'thin':\n return 'Thin';\n case 'partial':\n return 'Partial';\n case 'current':\n return 'Current';\n default:\n return String(state);\n }\n}\n\n/** A short, honest human label for a claim class. */\nexport function claimClassLabel(cls: PmClaimClass): string {\n switch (cls) {\n case 'fact':\n return 'Fact';\n case 'interpretation':\n return 'Interpretation';\n case 'recommendation':\n return 'Recommendation';\n default:\n return String(cls);\n }\n}\n\n/**\n * True when a report has anything worth diffing shown against a prior version —\n * a surface uses it to decide whether to render the diff panel. The first\n * version has no diff.\n */\nexport function hasMaterialDiff(report: Pick<PmStatusReport, 'narrative'>): boolean {\n const diff = report.narrative.diff;\n if (!diff) return false;\n return (\n diff.added.length > 0 ||\n diff.removed.length > 0 ||\n diff.changed.length > 0 ||\n diff.coverageChanges.length > 0 ||\n diff.phaseGateChanged\n );\n}\n\n/**\n * A single, honest one-line health summary a surface can show at the top of a\n * report: the coverage statement plus the phase/gate statement. Both are the\n * producer's own non-editable/honest text — this never re-derives or softens\n * them.\n */\nexport function statusHeadline(report: Pick<PmStatusReport, 'narrative'>): string {\n const { coverage, phaseGate, partial } = report.narrative;\n const partialPrefix = partial ? 'PARTIAL — ' : '';\n return `${partialPrefix}${phaseGate.statement} ${coverage.statement}`.trim();\n}\n","// Provider catalog — TYPES + an OFFLINE FALLBACK, not the source of truth.\n//\n// The runtime source of truth is the backend's GET /providers feed\n// (cloud-agent-backend/internal/providers), fetched via\n// CredentialsClient.providers(product). A UI must render THAT list so a\n// provider added server-side — including the MKT/MTG (CapMM) and BI (CapBI)\n// families — appears without a tsclient/frontend release.\n//\n// What lives here now:\n// 1. The wire TYPES (FieldSpec / FieldType / ProviderSpec / CAP_*). These\n// are static typing the fetched JSON is decoded into — no data.\n// 2. Spec-driven, \"friendly\" client validation: validateSpec() INTERPRETS a\n// given ProviderSpec (normally the one the server returned) rather than a\n// hard-coded copy. Server validation stays authoritative; this only makes\n// the form fail fast with the same messages.\n// 3. PROVIDER_CATALOG — an explicit OFFLINE-COMPATIBILITY FALLBACK for the\n// legacy cloud/notify set, used ONLY when the server feed is unavailable\n// (resolveProviderCatalog). It can never override or hide a server\n// provider: when a server response exists, the fallback is not consulted.\n//\n// The fallback intentionally lags the backend (it does not carry the CapMM/\n// CapBI families). That is safe precisely because it is never merged over a\n// live server response — see resolveProviderCatalog.\n\n// ── Field-descriptor types ─────────────────────────────────────────────\n\nexport type FieldType = 'text' | 'password' | 'number' | 'textarea' | 'pem' | 'json' | 'stringList';\n\nexport interface FieldSpec {\n /** JSON-pointer-ish: \"secret\" | \"metadata.<key>\". */\n path: string;\n label: string;\n type: FieldType;\n required: boolean;\n /** True for fields that hold credential material — UI hides the value. */\n secret?: boolean;\n default?: unknown;\n placeholder?: string;\n help?: string;\n /**\n * Optional grant-shape scoping for multi-shape providers (ZOOM, X). When\n * non-empty the field belongs only to those shapes (the active shape is\n * carried in metadata.grantShape). Empty/absent → the field applies to\n * every shape. Mirrors FieldSpec.Shapes on the backend; the generic form\n * carries it through untouched so a shape-scoped provider round-trips.\n */\n shapes?: string[];\n}\n\n// Capability bitmask values mirrored from cloud-agent-backend's\n// internal/providers package and the \"Provider\" master table seeded by\n// migration 0005. Frontends drive tab/section filtering by AND-ing\n// against these bits — adding a new capability is a backend migration,\n// not a frontend deploy.\n//\n// CAP_STORAGE — cloud ops / resource discovery (S3/GCS/Blob, EC2, …)\n// CAP_AI — LLM / embedding inference\n// CAP_COMPUTE — SSH and similar infra-runtime credentials\n// CAP_VCS — source-code platforms (GitHub, future GitLab)\n// CAP_NOTIFY — outbound notification transports (Slack, Teams, PagerDuty, SMTP)\n// CAP_BI — business-intelligence platforms (Power BI, Looker, Tableau)\n// CAP_MM — Meeting+Marketing MVP++ provider family (MSGRAPH, JIRA, …)\n// CAP_GENERAL — catch-all for the legacy \"OTHER\" row\nexport const CAP_STORAGE = 0x1;\nexport const CAP_AI = 0x2;\nexport const CAP_COMPUTE = 0x4;\nexport const CAP_VCS = 0x8;\nexport const CAP_NOTIFY = 0x10;\n// 0x20 is reserved for CAP_MCP on the backend; CAP_BI takes 0x40 to match.\nexport const CAP_BI = 0x40;\nexport const CAP_MM = 0x80;\nexport const CAP_GENERAL = 0xff;\n\nexport interface ProviderSpec {\n id: string;\n displayName: string;\n /**\n * Bitmask of CAP_* values describing what kinds of operations this\n * credential can drive. Sourced from the Provider master table; mirror\n * declared inline below so the frontend can render its tabs / filters\n * without a runtime round-trip.\n */\n capabilities: number;\n fields: FieldSpec[];\n}\n\n// ── Offline fallback catalog ────────────────────────────────────────────\n//\n// PROVIDER_CATALOG is the OFFLINE-COMPATIBILITY FALLBACK, NOT the source of\n// truth. It carries only the legacy cloud/notify set so a form still works\n// when the backend GET /providers feed is unreachable. It is consulted ONLY\n// by resolveProviderCatalog when no server response is available, so it can\n// never override or hide a provider the server declares. Prefer the fetched\n// catalog for everything user-facing.\n\nexport const PROVIDER_CATALOG: Record<string, ProviderSpec> = {\n AWS: {\n id: 'AWS',\n displayName: 'Amazon Web Services',\n capabilities: CAP_STORAGE,\n fields: [\n { path: 'metadata.accessKeyId', label: 'Access Key ID', type: 'text', required: true,\n placeholder: 'AKIAxxxxxxxxxxxxxxxx',\n help: 'The AKIA-prefixed identifier from IAM. Stored in plain text — only the secret access key is encrypted.' },\n { path: 'secret', label: 'Secret Access Key', type: 'password', required: true, secret: true,\n help: 'The 40-character secret. Encrypted at rest.' },\n { path: 'metadata.region', label: 'Region', type: 'text', required: false,\n placeholder: 'us-east-1',\n help: 'Default region for boto3 clients. Optional — leave blank to use the SDK default.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://s3.amazonaws.com',\n help: 'Override for non-AWS S3-compatible endpoints (MinIO, Wasabi, etc.). Most users leave blank.' },\n ],\n },\n BEDROCK: {\n id: 'BEDROCK',\n displayName: 'AWS Bedrock',\n capabilities: CAP_AI,\n fields: [\n { path: 'metadata.accessKeyId', label: 'Access Key ID', type: 'text', required: true,\n placeholder: 'AKIAxxxxxxxxxxxxxxxx',\n help: 'IAM access key allowed to invoke Bedrock. Stored in plain text — only the secret access key is encrypted.' },\n { path: 'secret', label: 'Secret Access Key', type: 'password', required: true, secret: true,\n help: 'The IAM secret. Encrypted at rest.' },\n { path: 'metadata.region', label: 'Region', type: 'text', required: false,\n placeholder: 'us-east-1',\n help: 'Default region for Bedrock Runtime. Optional — leave blank to use the SDK default.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://bedrock-runtime.us-east-1.amazonaws.com',\n help: 'Override for VPC endpoints or testing. Most users leave blank.' },\n ],\n },\n GCP: {\n id: 'GCP',\n displayName: 'Google Cloud',\n capabilities: CAP_STORAGE,\n fields: [\n { path: 'secret', label: 'Service Account JSON', type: 'json', required: true, secret: true,\n placeholder: '{\"type\":\"service_account\",\"project_id\":\"…\",\"client_email\":\"…\",\"private_key\":\"…\"}',\n help: 'Paste the service-account JSON, or drop the file you downloaded from the IAM console. The full document is encrypted; project_id and client_email are extracted automatically for display.' },\n ],\n },\n AZURE: {\n id: 'AZURE',\n displayName: 'Microsoft Azure',\n capabilities: CAP_STORAGE,\n fields: [\n { path: 'metadata.clientId', label: 'Client ID (Application ID)', type: 'text', required: true,\n placeholder: '00000000-0000-0000-0000-000000000000' },\n { path: 'secret', label: 'Client Secret', type: 'password', required: true, secret: true,\n help: 'The secret value generated when you registered the app. Encrypted at rest.' },\n { path: 'metadata.tenantId', label: 'Tenant ID', type: 'text', required: true,\n placeholder: '00000000-0000-0000-0000-000000000000' },\n { path: 'metadata.subscriptionId', label: 'Subscription ID', type: 'text', required: false,\n placeholder: '00000000-0000-0000-0000-000000000000' },\n ],\n },\n OCI: {\n id: 'OCI',\n displayName: 'Oracle Cloud Infrastructure',\n capabilities: CAP_STORAGE,\n fields: [\n { path: 'metadata.tenancyOcid', label: 'Tenancy OCID', type: 'text', required: true,\n placeholder: 'ocid1.tenancy.oc1..aaaa…',\n help: \"The tenancy's OCID, from the OCI console (Profile → Tenancy).\" },\n { path: 'metadata.userOcid', label: 'User OCID', type: 'text', required: true,\n placeholder: 'ocid1.user.oc1..aaaa…',\n help: 'The OCID of the user the API signing key belongs to.' },\n { path: 'metadata.fingerprint', label: 'Key Fingerprint', type: 'text', required: true,\n placeholder: 'aa:bb:cc:dd:…',\n help: 'Fingerprint of the uploaded API signing key (shown next to the key in the console).' },\n { path: 'secret', label: 'API Private Key (PEM)', type: 'pem', required: true, secret: true,\n placeholder: '-----BEGIN PRIVATE KEY-----\\n…\\n-----END PRIVATE KEY-----',\n help: 'Paste the PEM, or drop the .pem file. Passphrase-protected keys are rejected — the agent runs unattended. Encrypted at rest.' },\n { path: 'metadata.region', label: 'Region', type: 'text', required: false,\n placeholder: 'us-phoenix-1',\n help: 'Default region for the oci CLI / SDK. Optional — leave blank to use the SDK default.' },\n ],\n },\n SSH: {\n id: 'SSH',\n displayName: 'SSH',\n capabilities: CAP_COMPUTE,\n fields: [\n { path: 'metadata.user', label: 'User', type: 'text', required: true,\n placeholder: 'ubuntu',\n help: 'Linux user the agent will SSH as.' },\n { path: 'metadata.host', label: 'Host', type: 'text', required: true,\n placeholder: 'vps.example.com or * for wildcard',\n help: \"Hostname or IP. Use '*' for a key that's valid across multiple hosts; the agent will require the prompt to name the target host.\" },\n { path: 'metadata.port', label: 'Port', type: 'number', required: false, default: 22,\n placeholder: '22' },\n { path: 'secret', label: 'PEM Private Key', type: 'pem', required: true, secret: true,\n placeholder: '-----BEGIN OPENSSH PRIVATE KEY-----\\n…\\n-----END OPENSSH PRIVATE KEY-----',\n help: 'Paste the PEM, or drop the private key file (e.g. id_ed25519). Passphrase-encrypted keys are rejected — the agent runs unattended.' },\n ],\n },\n GITHUB: {\n id: 'GITHUB',\n displayName: 'GitHub',\n capabilities: CAP_VCS,\n fields: [\n { path: 'secret', label: 'Personal Access Token (PAT)', type: 'password', required: true, secret: true,\n placeholder: 'ghp_xxxxxxxxxxxxxxxxxxxxxxxx',\n help: 'A classic or fine-grained PAT. Encrypted at rest. The first 7 characters are kept in metadata for display.' },\n { path: 'metadata.org', label: 'Org (optional)', type: 'text', required: false,\n placeholder: 'my-github-org',\n help: 'Restrict this credential to a single org if you scoped the PAT that way. Optional — leave blank for personal-account access.' },\n { path: 'metadata.repoSlugs', label: 'Allowed Repos (optional)', type: 'stringList', required: false,\n placeholder: 'owner/repo',\n help: \"Repos the agent is allowed to operate on with this credential, as 'owner/name'. Drives the awareness block injected into the planner. Leave empty to grant the full PAT scope (the agent will still only act on repos the user names in prompts).\" },\n { path: 'metadata.protectedBranches', label: 'Protected Branches (optional)', type: 'stringList', required: false,\n placeholder: 'main',\n help: \"Branches that require explicit user approval for write operations (push, merge, delete). 'main' / 'master' / 'release/*' are good defaults.\" },\n ],\n },\n GITLAB: {\n id: 'GITLAB',\n displayName: 'GitLab',\n capabilities: CAP_VCS,\n fields: [\n { path: 'secret', label: 'Access Token', type: 'password', required: true, secret: true,\n placeholder: 'glpat-xxxxxxxxxxxxxxxxxxxx',\n help: 'A personal, project, or group access token. Encrypted at rest. The first 9 characters are kept in metadata for display.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://gitlab.example.com/api/v4',\n help: 'Override for self-hosted GitLab. Leave blank to use https://gitlab.com/api/v4.' },\n { path: 'metadata.group', label: 'Top-level Group (optional)', type: 'text', required: false,\n placeholder: 'my-gitlab-group',\n help: 'Restrict this credential to a single top-level group if you scoped the token that way. Optional — leave blank for personal-account or wider scope.' },\n { path: 'metadata.repoSlugs', label: 'Allowed Projects (optional)', type: 'stringList', required: false,\n placeholder: 'group/subgroup/project',\n help: 'Project paths the agent is allowed to operate on with this credential. GitLab project paths can be arbitrarily deep (group/subgroup/.../project). Leave empty to grant the full token scope.' },\n { path: 'metadata.protectedBranches', label: 'Protected Branches (optional)', type: 'stringList', required: false,\n placeholder: 'main',\n help: \"Branches that require explicit user approval for write operations. 'main' / 'master' / 'release/*' are good defaults.\" },\n ],\n },\n AZURE_DEVOPS: {\n id: 'AZURE_DEVOPS',\n displayName: 'Azure DevOps',\n capabilities: CAP_VCS,\n fields: [\n { path: 'secret', label: 'Personal Access Token (PAT)', type: 'password', required: true, secret: true,\n placeholder: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',\n help: 'An ADO PAT with the scopes you want the agent to use (Code, Build, Release, Work Items …). Encrypted at rest. The first 7 characters are kept in metadata for display.' },\n { path: 'metadata.organization', label: 'Organization', type: 'text', required: true,\n placeholder: 'my-ado-org',\n help: 'The ADO organization name (the segment after dev.azure.com/, or the prefix in your-org.visualstudio.com).' },\n { path: 'metadata.project', label: 'Project (optional)', type: 'text', required: false,\n placeholder: 'Engineering',\n help: 'Restrict this credential to a single ADO project. Optional — leave blank if the PAT spans multiple projects in the org.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://dev.azure.com',\n help: 'Override for ADO Server (on-prem) deployments. Leave blank to use https://dev.azure.com.' },\n { path: 'metadata.repoSlugs', label: 'Allowed Repos (optional)', type: 'stringList', required: false,\n placeholder: 'project/repo',\n help: \"Repos the agent is allowed to operate on. Use 'project/repo' when 'Project' is blank, or just 'repo' when scoped to one project. Leave empty to grant the full PAT scope.\" },\n { path: 'metadata.protectedBranches', label: 'Protected Branches (optional)', type: 'stringList', required: false,\n placeholder: 'main',\n help: 'Branches that require explicit user approval for write operations and pipeline triggers.' },\n ],\n },\n OPENAI: {\n id: 'OPENAI',\n displayName: 'OpenAI',\n capabilities: CAP_AI,\n fields: [\n { path: 'secret', label: 'API Key', type: 'password', required: true, secret: true,\n placeholder: 'sk-…',\n help: 'Your OpenAI API key. Encrypted at rest. The first ~7 characters are kept in metadata for display.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://api.openai.com/v1',\n help: 'Override for OpenAI-compatible endpoints (Azure OpenAI, self-hosted gateways). Most users leave blank.' },\n ],\n },\n ANTHROPIC: {\n id: 'ANTHROPIC',\n displayName: 'Anthropic',\n capabilities: CAP_AI,\n fields: [\n { path: 'secret', label: 'API Key', type: 'password', required: true, secret: true,\n placeholder: 'sk-ant-…',\n help: 'Your Anthropic API key. Encrypted at rest. The first ~10 characters are kept in metadata for display.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://api.anthropic.com',\n help: 'Override for Anthropic-compatible endpoints. Most users leave blank.' },\n ],\n },\n GEMINI: {\n id: 'GEMINI',\n displayName: 'Google Gemini',\n capabilities: CAP_AI,\n fields: [\n { path: 'secret', label: 'API Key', type: 'password', required: true, secret: true,\n placeholder: 'AIza…',\n help: 'Your Gemini API key from Google AI Studio. Encrypted at rest. The first ~7 characters are kept in metadata for display.' },\n { path: 'metadata.endpoint', label: 'Endpoint (optional)', type: 'text', required: false,\n placeholder: 'https://generativelanguage.googleapis.com',\n help: 'Override for proxies or regional endpoints. Most users leave blank to use the default Gemini API base URL.' },\n ],\n },\n SLACK: {\n id: 'SLACK',\n displayName: 'Slack',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'secret', label: 'Incoming Webhook URL', type: 'password', required: true, secret: true,\n placeholder: 'https://hooks.slack.com/services/T000/B000/xxxxxxxx',\n help: 'A Slack Incoming Webhook URL. The target channel is fixed by the webhook. Encrypted at rest; never injected into the sandbox.' },\n { path: 'metadata.channelHint', label: 'Channel Hint (optional)', type: 'text', required: false,\n placeholder: '#oncall',\n help: 'Display-only label for the channel this webhook posts to. Does not change routing — the webhook URL controls the destination.' },\n ],\n },\n TEAMS: {\n id: 'TEAMS',\n displayName: 'Microsoft Teams',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'secret', label: 'Incoming Webhook URL', type: 'password', required: true, secret: true,\n placeholder: 'https://outlook.office.com/webhook/...',\n help: 'A Teams Incoming Webhook (connector) URL. The target channel is fixed by the webhook. Encrypted at rest; never injected into the sandbox.' },\n ],\n },\n PAGERDUTY: {\n id: 'PAGERDUTY',\n displayName: 'PagerDuty',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'secret', label: 'Integration / Routing Key', type: 'password', required: true, secret: true,\n placeholder: 'R0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',\n help: 'An Events API v2 integration (routing) key from a PagerDuty service. Encrypted at rest; never injected into the sandbox.' },\n ],\n },\n SMTP: {\n id: 'SMTP',\n displayName: 'Email (SMTP)',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'metadata.host', label: 'SMTP Host', type: 'text', required: true,\n placeholder: 'smtp.example.com',\n help: 'Hostname of the SMTP relay.' },\n { path: 'metadata.port', label: 'Port', type: 'number', required: false, default: 587,\n placeholder: '587',\n help: 'SMTP port. Defaults to 587 (STARTTLS). TLS is always required.' },\n { path: 'metadata.fromAddress', label: 'From Address', type: 'text', required: true,\n placeholder: 'alerts@example.com',\n help: 'Envelope-from / From header for messages the agent sends. Also used as the SMTP AUTH username.' },\n { path: 'metadata.toAddresses', label: 'To Addresses', type: 'stringList', required: true,\n placeholder: 'oncall@example.com',\n help: 'One or more recipient addresses. Every notify message is sent to all of them.' },\n { path: 'secret', label: 'Password', type: 'password', required: true, secret: true,\n help: 'SMTP AUTH password for the From address. Encrypted at rest; never injected into the sandbox.' },\n ],\n },\n TELEGRAM: {\n id: 'TELEGRAM',\n displayName: 'Telegram',\n capabilities: CAP_NOTIFY,\n fields: [\n { path: 'secret', label: 'Bot Token', type: 'password', required: true, secret: true,\n placeholder: '123456789:AAExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',\n help: 'Bot token from @BotFather. Encrypted at rest; never injected into the sandbox. One bot per project keeps projects isolated.' },\n { path: 'metadata.chatId', label: 'Chat ID', type: 'text', required: false,\n placeholder: '-1001234567890 or @mychannel',\n help: 'Default chat the agent posts to. Use Detect to fill it automatically, or enter a numeric id (groups are negative) / @username for a public channel. Optional — leave blank for inbound-only (driving the agent from a chat); inbound replies go to whoever messages the bot.' },\n { path: 'metadata.threadId', label: 'Topic / Thread ID (optional)', type: 'number', required: false,\n placeholder: '12',\n help: 'For forum-style groups, the message_thread_id to post into. Leave blank for the main chat.' },\n ],\n },\n};\n\n// Stable display order for the FALLBACK dropdown. Matches the Go catalog's\n// List() for the legacy set; the server feed carries its own order.\nconst PROVIDER_ORDER = ['AWS', 'BEDROCK', 'GCP', 'AZURE', 'OCI', 'SSH', 'GITHUB', 'GITLAB', 'AZURE_DEVOPS', 'OPENAI', 'ANTHROPIC', 'GEMINI', 'SLACK', 'TEAMS', 'PAGERDUTY', 'SMTP', 'TELEGRAM'];\n\n/** listProviders returns the OFFLINE FALLBACK specs. Prefer the fetched catalog. */\nexport function listProviders(): ProviderSpec[] {\n return PROVIDER_ORDER.flatMap((id) => (PROVIDER_CATALOG[id] ? [PROVIDER_CATALOG[id]] : []));\n}\n\n/** getProvider looks up a spec in the OFFLINE FALLBACK. Prefer getSpec(fetched, id). */\nexport function getProvider(id: string): ProviderSpec | undefined {\n return PROVIDER_CATALOG[id];\n}\n\n// ── Runtime catalog resolution ──────────────────────────────────────────\n\n/** Where a resolved catalog came from: the live server feed, or the offline fallback. */\nexport type ProviderCatalogSource = 'server' | 'fallback';\n\nexport interface ResolvedProviderCatalog {\n /** The specs the UI should render, in server (or fallback) order. */\n specs: ProviderSpec[];\n /** 'server' when the backend feed was used; 'fallback' when offline. */\n source: ProviderCatalogSource;\n}\n\n/**\n * resolveProviderCatalog picks the catalog a UI should render.\n *\n * When the server feed (CredentialsClient.providers()) returned a non-empty\n * list, that list is used VERBATIM — the offline fallback is not consulted,\n * so it can never override or hide a server-declared provider. Only when the\n * feed is absent/empty (offline, or a fetch error the caller maps to null)\n * does it fall back to the legacy static set, flagging source: 'fallback' so\n * the UI can say so.\n */\nexport function resolveProviderCatalog(\n fetched: ProviderSpec[] | null | undefined,\n): ResolvedProviderCatalog {\n if (Array.isArray(fetched) && fetched.length > 0) {\n return { specs: fetched, source: 'server' };\n }\n return { specs: listProviders(), source: 'fallback' };\n}\n\n/** getSpec finds a provider by id in a resolved (fetched or fallback) catalog. */\nexport function getSpec(specs: readonly ProviderSpec[], id: string): ProviderSpec | undefined {\n return specs.find((s) => s.id === id);\n}\n\n// ── Path helpers ───────────────────────────────────────────────────────\n\nconst SECRET_PATH = 'secret';\nconst METADATA_PREFIX = 'metadata.';\n\nexport function isSecretPath(path: string): boolean {\n return path === SECRET_PATH;\n}\n\nexport function isMetadataPath(path: string): path is `metadata.${string}` {\n return path.startsWith(METADATA_PREFIX);\n}\n\nexport function metadataKey(path: string): string | undefined {\n return isMetadataPath(path) ? path.slice(METADATA_PREFIX.length) : undefined;\n}\n\n/** getValueAt reads the FieldSpec.path from a separate (secret, metadata) tuple. */\nexport function getValueAt(secret: string, metadata: Record<string, unknown>, path: string): unknown {\n if (path === SECRET_PATH) return secret;\n const k = metadataKey(path);\n return k ? metadata[k] : undefined;\n}\n\n/** setValueAt writes to (secret, metadata). Returns the updated tuple. */\nexport function setValueAt(\n secret: string,\n metadata: Record<string, unknown>,\n path: string,\n value: unknown,\n): { secret: string; metadata: Record<string, unknown> } {\n if (path === SECRET_PATH) return { secret: typeof value === 'string' ? value : '', metadata };\n const k = metadataKey(path);\n if (!k) return { secret, metadata };\n const nextMeta = { ...metadata };\n if (value === undefined || value === null || value === '') delete nextMeta[k];\n else nextMeta[k] = value;\n return { secret, metadata: nextMeta };\n}\n\n// ── Validation ─────────────────────────────────────────────────────────\n\n/**\n * validateSpec runs the structural checks for a credential payload against a\n * GIVEN ProviderSpec — normally the one the server returned from GET\n * /providers. It interprets that spec's fields; it does NOT consult the\n * offline fallback catalog. This is what lets the form fail fast for a\n * provider the backend added without a tsclient release.\n *\n * Returns an error string on failure, or null on success. \"Friendly\" only —\n * the backend validator (internal/providers/validators.go) stays\n * authoritative; the messages here mirror it. Grant-shape scoped fields\n * (FieldSpec.shapes) are required only when they apply to the active shape.\n */\nexport function validateSpec(\n spec: ProviderSpec | undefined,\n label: string,\n secret: string,\n metadata: Record<string, unknown>,\n): string | null {\n if (!spec) return 'Unknown provider';\n if (!label || label.trim() === '') {\n return 'Label is required';\n }\n\n const activeShape = typeof metadata['grantShape'] === 'string' ? (metadata['grantShape'] as string) : '';\n\n // Required-field + type checks.\n for (const f of spec.fields) {\n const present = isFieldPresent(secret, metadata, f.path);\n if (f.required && !present && fieldAppliesToShape(f, activeShape)) {\n return `${spec.id}.${f.label} is required`;\n }\n if (!present) continue;\n const value = getValueAt(secret, metadata, f.path);\n const typeErr = typeCheck(f, value);\n if (typeErr) return typeErr;\n }\n\n // Reject any caller-supplied metadata keys not declared in the spec\n // and any reserved underscore-prefixed keys (catalog-managed). An unknown\n // key on a server-declared provider fails safely here, exactly as it does\n // on the backend — the generic form never smuggles an undeclared field.\n const allowed = allowedMetadataKeys(spec);\n for (const k of Object.keys(metadata)) {\n if (k.startsWith('_')) {\n return `Metadata key \"${k}\" is reserved (the leading underscore is catalog-managed); remove it from the payload`;\n }\n if (!allowed.has(k)) {\n return `Metadata key \"${k}\" is not part of the ${spec.id} spec. Allowed keys: ${[...allowed].join(', ')}`;\n }\n }\n return null;\n}\n\n/**\n * validate is the back-compat, id-keyed entry point: it resolves the provider\n * from the OFFLINE FALLBACK catalog and delegates to validateSpec. Prefer\n * validateSpec with the server-returned spec so newly-added server providers\n * validate without shipping a new tsclient. Kept for callers that still hold\n * only a provider id and the legacy set.\n */\nexport function validate(\n providerId: string,\n label: string,\n secret: string,\n metadata: Record<string, unknown>,\n): string | null {\n const spec = getProvider(providerId);\n if (!spec) {\n return `Unknown provider \"${providerId}\". Known providers: ${Object.keys(PROVIDER_CATALOG).join(', ')}`;\n }\n return validateSpec(spec, label, secret, metadata);\n}\n\n/**\n * fieldAppliesToShape reports whether a shape-scoped field belongs to the\n * active grant shape. An unscoped field (no shapes) applies to every shape.\n * Mirrors the backend's fieldAppliesToShape.\n */\nfunction fieldAppliesToShape(f: FieldSpec, shapeId: string): boolean {\n if (!f.shapes || f.shapes.length === 0) return true;\n return f.shapes.includes(shapeId);\n}\n\nfunction isFieldPresent(secret: string, metadata: Record<string, unknown>, path: string): boolean {\n const v = getValueAt(secret, metadata, path);\n if (v === undefined || v === null) return false;\n if (typeof v === 'string') return v.trim() !== '';\n // Mirror the Go getAtPath: empty arrays count as absent so required-field\n // checks fire and stringList fields can be cleared by submitting [].\n if (Array.isArray(v)) return v.length > 0;\n return true;\n}\n\nfunction typeCheck(f: FieldSpec, value: unknown): string | null {\n switch (f.type) {\n case 'text':\n case 'password':\n case 'textarea':\n return typeof value === 'string' ? null : `${f.label} must be a string`;\n case 'number':\n if (typeof value === 'number' && Number.isInteger(value) && value >= 0) return null;\n if (typeof value === 'string' && /^\\d+$/.test(value)) return null;\n return `${f.label} must be a non-negative integer`;\n case 'json':\n if (typeof value !== 'string') return `${f.label} must be a JSON string`;\n try {\n JSON.parse(value);\n return null;\n } catch {\n return `${f.label} is not valid JSON`;\n }\n case 'pem':\n if (typeof value !== 'string') return `${f.label} must be a PEM string`;\n return validatePEM(value, f.label);\n case 'stringList': {\n if (!Array.isArray(value)) return `${f.label} must be a list of strings`;\n for (let i = 0; i < value.length; i++) {\n const item = value[i];\n if (typeof item !== 'string') return `${f.label}[${i}] must be a string`;\n if (item.trim() === '') return `${f.label}[${i}] is empty`;\n }\n return null;\n }\n default:\n return `${f.label} has unsupported field type ${f.type}`;\n }\n}\n\nconst PEM_BEGIN_RE = /-----BEGIN [^-]+-----/;\nconst PEM_END_RE = /-----END [^-]+-----/;\nconst PEM_PROC_TYPE_ENCRYPTED = /^Proc-Type:\\s*\\d+,\\s*ENCRYPTED/m;\nconst PEM_DEK_INFO = /^DEK-Info:/m;\n\nfunction validatePEM(s: string, label: string): string | null {\n const t = s.trim();\n if (!t) return `${label}: empty PEM`;\n if (!PEM_BEGIN_RE.test(t) || !PEM_END_RE.test(t)) {\n return `${label}: no valid PEM block found (expected '-----BEGIN ... PRIVATE KEY-----')`;\n }\n if (PEM_PROC_TYPE_ENCRYPTED.test(t) || PEM_DEK_INFO.test(t)) {\n return `${label}: passphrase-encrypted PEM is not supported (the agent runs unattended)`;\n }\n return null;\n}\n\nfunction allowedMetadataKeys(spec: ProviderSpec): Set<string> {\n const out = new Set<string>();\n for (const f of spec.fields) {\n const k = metadataKey(f.path);\n if (k) out.add(k);\n }\n // Mirror the Go-side allow-list of SecretParser-derived metadata keys\n // so a round-trip read→edit→write doesn't trip the unknown-key check.\n switch (spec.id) {\n case 'GCP':\n out.add('clientEmail');\n out.add('projectId');\n break;\n case 'GITHUB':\n case 'AZURE_DEVOPS':\n case 'OPENAI':\n case 'ANTHROPIC':\n case 'GEMINI':\n out.add('tokenPrefix');\n break;\n case 'GITLAB':\n out.add('tokenPrefix');\n out.add('host'); // derived from endpoint by the parser\n break;\n }\n return out;\n}\n\n// ── Display hints ──────────────────────────────────────────────────────\n//\n// Used for client-side previews when forms are filled in but not yet\n// submitted. The persisted value comes from the server (cached in\n// metadata._displayHint) — this function is a fallback / preview helper.\n\nexport function computeDisplayHint(providerId: string, metadata: Record<string, unknown>): string {\n const cached = metadata['_displayHint'];\n if (typeof cached === 'string' && cached) return cached;\n\n switch (providerId) {\n case 'AWS':\n case 'BEDROCK': {\n const key = str(metadata['accessKeyId']);\n const region = str(metadata['region']);\n return shortPrefix(key, 8) + (region ? ` / ${region}` : '');\n }\n case 'GCP': {\n const email = str(metadata['clientEmail']);\n const proj = str(metadata['projectId']);\n if (!email && !proj) return '';\n if (!email) return proj;\n if (!proj) return email;\n return `${email} / ${proj}`;\n }\n case 'AZURE': {\n const client = str(metadata['clientId']);\n const sub = str(metadata['subscriptionId']);\n const head = shortPrefix(client, 8);\n return head + (sub ? ` / sub:${shortPrefix(sub, 8)}` : '');\n }\n case 'OCI': {\n const tenancy = str(metadata['tenancyOcid']);\n const region = str(metadata['region']);\n const head = shortPrefix(tenancy, 12);\n return head + (region ? ` / ${region}` : '');\n }\n case 'SSH': {\n const user = str(metadata['user']);\n const host = str(metadata['host']);\n const port = metadata['port'];\n let portStr = '';\n if (typeof port === 'number' && port > 0 && port !== 22) portStr = `:${port}`;\n else if (typeof port === 'string' && /^\\d+$/.test(port) && port !== '22') portStr = `:${port}`;\n if (!user && !host) return '';\n return `${user}@${host}${portStr}`.replace(/^@/, '');\n }\n case 'GITHUB': {\n const prefix = str(metadata['tokenPrefix']);\n const org = str(metadata['org']);\n const head = prefix ? `${prefix}…` : '';\n return [head, org].filter(Boolean).join(' / ');\n }\n case 'GITLAB': {\n const prefix = str(metadata['tokenPrefix']);\n const group = str(metadata['group']);\n let host = str(metadata['host']);\n if (!host) {\n const endpoint = str(metadata['endpoint']);\n host = endpoint ? hostFromURL(endpoint) : 'gitlab.com';\n }\n let out = prefix ? `${prefix}…` : '';\n if (group) out = out ? `${out} / ${group}` : group;\n if (host && host !== 'gitlab.com') out = out ? `${out} @ ${host}` : host;\n return out;\n }\n case 'AZURE_DEVOPS': {\n const prefix = str(metadata['tokenPrefix']);\n const org = str(metadata['organization']);\n const project = str(metadata['project']);\n let out = prefix ? `${prefix}…` : '';\n if (org) {\n const orgSeg = project ? `${org}/${project}` : org;\n out = out ? `${out} / ${orgSeg}` : orgSeg;\n }\n return out;\n }\n case 'OPENAI':\n case 'ANTHROPIC':\n case 'GEMINI': {\n const prefix = str(metadata['tokenPrefix']);\n return prefix ? `${prefix}…` : '';\n }\n case 'SLACK':\n return str(metadata['channelHint']);\n case 'TELEGRAM':\n return str(metadata['chatId']);\n case 'SMTP': {\n const from = str(metadata['fromAddress']);\n const host = str(metadata['host']);\n return from + (host ? ` @ ${host}` : '');\n }\n default:\n return '';\n }\n}\n\nfunction str(v: unknown): string {\n return typeof v === 'string' ? v : '';\n}\n\nfunction shortPrefix(s: string, n: number): string {\n if (!s) return '';\n if (s.length <= n) return s;\n return s.slice(0, n) + '…';\n}\n\nfunction hostFromURL(raw: string): string {\n let s = raw.trim();\n const schemeIdx = s.indexOf('://');\n if (schemeIdx >= 0) s = s.slice(schemeIdx + 3);\n const cut = s.search(/[/?#]/);\n if (cut >= 0) s = s.slice(0, cut);\n return s;\n}\n","/**\n * Chat-mode types for the agent engine. The new SDK speaks `sandboxId` and\n * `projectId`; the legacy `repoId` / `workspaceId` are still accepted on the\n * scope tuple as fallbacks during the frontend transition.\n */\n\nexport interface ChatScope {\n orgId: string;\n userId: string;\n sandboxId: string;\n projectId?: string;\n /** @deprecated Use `sandboxId`. Carried only to ease the cutover. */\n repoId?: string;\n /** @deprecated Use `projectId`. Carried only to ease the cutover. */\n workspaceId?: string;\n}\n\nexport type ChatSessionSource = 'adhoc' | 'template' | 'mcp' | 'telegram';\nexport type ChatMessageRole = 'user' | 'assistant' | 'system';\n\n/**\n * Status of a single chat turn (agent_chat_turns.status). The first four are\n * in-progress phases; the last three are terminal. The Chats/Runs table folds\n * the in-progress values into a single \"running\" badge and renders the\n * terminal ones directly.\n */\nexport type ChatTurnStatus =\n | 'classifying'\n | 'clarifying'\n | 'planning'\n | 'executing'\n | 'completed'\n | 'failed'\n | 'cancelled';\nexport type ChatMessageKind =\n | 'text'\n | 'question'\n | 'answer'\n | 'tool_call'\n | 'tool_result'\n // Talk-to-Your-BI careless-prompter (O2): a non-blocking transparency banner written\n // when the user's own prompt named a person / personal identifier. metadata.classes\n // carries the detected PII kinds. Mirrors cloud-agent types.ChatMessageKindPIINotice.\n | 'pii_notice'\n // MVP09 C1: an agent_chat_messages row whose metadata carries a closed\n // ChatCardV1 projection (chat-first realignment §6). Mirrors cloud-agent\n // types.ChatMessageKindCard. Parse it with chatCardOf() from ./cards; a client\n // that does not render cards can skip the kind entirely (forward-compat).\n | 'card';\n\nexport interface ChatSession {\n id: string;\n org_id: string;\n workspace_id: string;\n repo_id: string;\n user_id: string;\n title?: string;\n agent_environment_id?: string;\n source: ChatSessionSource;\n template_id?: string;\n /** M3 Stage 4: populated when this session was spawned by the\n * scheduler dispatcher firing a `ChatSchedule` row. The frontend\n * uses it to render the \"Scheduled run\" ribbon + hide the\n * composer. NULL on every attended session. */\n schedule_id?: string | null;\n /** M3 Stage 4: mirror of `schedule_id != null` — true for sessions\n * the scheduler created with `Loop.Unattended = true`. */\n unattended?: boolean;\n created_at: string;\n updated_at: string;\n last_message_at?: string | null;\n /** Sum of `cost_usd_micros` across this session's `execution_receipts`.\n * Populated only by list endpoints; absent on single-session fetches. */\n total_cost_usd_micros?: number | null;\n /** Sum of prompt + completion tokens across this session's LLM calls.\n * Populated only by list endpoints; absent on single-session fetches. */\n total_tokens?: number | null;\n /** Status of this session's most recent turn. Populated only by list\n * endpoints; null/absent when the session has no turns yet. The Runs\n * table maps the in-progress phases to a \"running\" badge and surfaces\n * completed / failed / cancelled directly. */\n latest_turn_status?: ChatTurnStatus | null;\n}\n\nexport interface ChatMessage {\n id: string;\n conversation_id: string;\n org_id: string;\n repo_id: string;\n user_id: string;\n turn_id: string;\n role: ChatMessageRole;\n kind: ChatMessageKind;\n content?: string;\n plan_id?: string;\n clarification_session_id?: string;\n metadata?: Record<string, unknown>;\n created_at: string;\n}\n\nexport interface CreateChatSessionRequest {\n title?: string;\n workspace_id: string;\n repo_id: string;\n agent_environment_id?: string;\n source?: ChatSessionSource;\n template_id?: string;\n}\n\nexport interface CreateChatSessionResponse {\n conversation_id: string;\n session: ChatSession;\n}\n\nexport interface ListChatSessionsResponse {\n sessions: ChatSession[];\n next_cursor?: string;\n}\n\nexport interface ListChatSessionsQuery {\n cursor?: string;\n limit?: number;\n /** Inclusive lower bound on `created_at`, RFC3339 timestamp. */\n from?: string;\n /** Exclusive upper bound on `created_at`, RFC3339 timestamp. */\n to?: string;\n}\n\nexport interface GetChatSessionResponse {\n session: ChatSession;\n messages: ChatMessage[];\n /**\n * Action categories the user has sticky-allowed for the rest of this chat\n * session (the ConfirmationCard \"Allow for session\" opt-in). Held in\n * engine memory, so this re-hydrates the dashboard's guardrail chips after\n * a reload while the engine process is alive; `null` (or omitted) when\n * there are none or after an engine restart.\n */\n session_allows?: ActionCategory[] | null;\n /**\n * Pack-registry active packs for this session (pack-registry SG-13): the\n * version-stamped activations — bound, model-activated and system lazy — that\n * back the console's PackChips strip. `null` (or omitted) when there are none\n * or against an older engine that does not emit the field.\n */\n active_packs?: ActivePack[] | null;\n}\n\n/** One version-stamped pack activation on a chat session (pack-registry §7.6). */\nexport interface ActivePack {\n /** Pack name (the activate_skill key). */\n name: string;\n /** 'system' (compiled engine pack) | 'default' (platform) | 'org'. */\n source: string;\n /** Display version integer; omitted for system packs. */\n version?: number;\n /** 'binding' (delivered at Run start) | 'model' (activate_skill). */\n trigger: string;\n}\n\nexport interface PostChatMessageRequest {\n text: string;\n attachments?: Array<Record<string, unknown>>;\n template_params?: Record<string, unknown>;\n auto_approve?: boolean;\n}\n\nexport interface PostChatMessageResponse {\n message_id: string;\n turn_id: string;\n}\n\n/**\n * One user's \"Satisfied? Yes/No\" rating plus an optional free-text comment on\n * the agent's behaviour (agent_chat_feedback). `turn_id` is null for\n * whole-conversation feedback; non-null scopes it to a single turn. Fields are\n * snake_case to match the wire format.\n */\nexport interface ChatFeedback {\n id: string;\n conversation_id: string;\n turn_id?: string | null;\n org_id: string;\n repo_id: string;\n user_id: string;\n satisfied: boolean;\n comment?: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface SubmitChatFeedbackRequest {\n satisfied: boolean;\n comment?: string;\n /** Omit (or null) for whole-conversation feedback; set to scope to a turn. */\n turn_id?: string;\n}\n\nexport interface ChatFeedbackEnvelope {\n feedback: ChatFeedback;\n}\n\nexport interface ListChatFeedbackResponse {\n feedback: ChatFeedback[];\n}\n\nexport interface AnswerChatQuestionRequest {\n question_id: string;\n selected_ids?: string[];\n custom_text?: string;\n}\n\nexport interface AnswerChatQuestionResponse {\n status: 'accepted';\n}\n\n/**\n * Response from POST /chat/sessions/:id/messages/:turn_id/cancel — the\n * Stop affordance the dashboard fires to interrupt an in-flight turn.\n * The engine still emits a terminal `done` SSE event with\n * status=\"context_cancelled\" after this returns; the frontend renders a\n * muted \"Cancelled\" marker on that event rather than on this response.\n */\nexport interface CancelChatTurnResponse {\n status: 'cancelling';\n turn_id: string;\n}\n\n/**\n * Body the dashboard POSTs to\n * /chat/sessions/:id/messages/:turn_id/confirm/:tool_call_id when the\n * user clicks approve / deny on the M3 confirmation modal. `note` is\n * optional free-text rationale surfaced in the synthesised\n * \"DENIED:\" tool result on deny so the model can see *why* the user\n * said no.\n *\n * `apply_to_session` opts the user into sticky-allow: when present\n * with decision='allow', every subsequent tool call in this chat\n * session that classifies into the same category dispatches without\n * re-prompting. Ignored when decision='deny'. Default: false.\n */\nexport interface ConfirmChatToolCallRequest {\n decision: 'allow' | 'deny';\n note?: string;\n apply_to_session?: boolean;\n}\n\nexport interface ConfirmChatToolCallResponse {\n status: 'accepted';\n}\n\n/**\n * Action categories the M3 policy engine recognises (see\n * docs/design/chat-loop/chat-loop-m3-safety-scheduling.md §4). `read`\n * is implicit / always allowed and never appears in a grant set —\n * include the mutating eight in the union so the schedule editor's\n * category multi-select can be typed.\n */\nexport type ActionCategory =\n | 'write_data'\n | 'create_resource'\n | 'delete_data'\n | 'destroy_resource'\n | 'scale_capacity'\n | 'modify_iam'\n | 'modify_network'\n | 'execute_runtime';\n\n/** Run status stamped on agent_chat_schedules.last_run_status.\n *\n * The legacy statuses (`success` | `blocked` | `failed` | `running`) are joined\n * by the SHR-IP06 product-schedule statuses, each a DISTINCT non-failed state a\n * renderer must show as its own pill rather than collapsing to failed:\n * - `halted_budget` — the run hit a metered budget/cap; queue intact, resumes when raised.\n * - `paused_disabled` — paused because the product_unattended_execution kill switch is off.\n * - `paused_entitlement` — paused because the org's product entitlement was revoked.\n * - `superseded` — a recurring occurrence was superseded by its next window and escalated.\n * - `coalesced` — a duplicate fire (double-fire / run-now) coalesced onto the live run.\n *\n * `paused_*` and `superseded`/`coalesced` are NOT failures — they must not read\n * as a broken schedule (SHR-IP06 REV-09). */\nexport type ChatScheduleRunStatus =\n | 'success'\n | 'blocked'\n | 'failed'\n | 'running'\n | 'halted_budget'\n | 'paused_disabled'\n | 'paused_entitlement'\n | 'superseded'\n | 'coalesced';\n\n/** Every ChatScheduleRunStatus classified by whether it reads as a FAILURE.\n *\n * Typed `Record<ChatScheduleRunStatus, boolean>` on purpose: the record is\n * EXHAUSTIVE, so removing a status from the union above makes its key an excess\n * property here and `tsc` fails, and adding a status without classifying it fails\n * too. This is what makes the SHR-IP06 statuses LOAD-BEARING (REV-09 / RV2-06) —\n * dropping `superseded`/`coalesced`/`halted_budget`/`paused_*` no longer slips\n * through a green typecheck. Every SHR-IP06 status is a NON-failure: a paused,\n * superseded or coalesced run must not render as a broken schedule. */\nexport const CHAT_SCHEDULE_RUN_STATUS_IS_FAILURE: Record<ChatScheduleRunStatus, boolean> = {\n success: false,\n blocked: false,\n failed: true,\n running: false,\n halted_budget: false,\n paused_disabled: false,\n paused_entitlement: false,\n superseded: false,\n coalesced: false,\n};\n\n/** The canonical list of every ChatScheduleRunStatus, derived from the\n * exhaustive classification above so it cannot drift from the union. */\nexport const CHAT_SCHEDULE_RUN_STATUSES = Object.keys(\n CHAT_SCHEDULE_RUN_STATUS_IS_FAILURE,\n) as ChatScheduleRunStatus[];\n\n/** Whether a schedule run status reads as a failure. The SHR-IP06 non-failed\n * states (paused_*, superseded, coalesced, halted_budget) return false. */\nexport function isFailedScheduleRunStatus(s: ChatScheduleRunStatus): boolean {\n return CHAT_SCHEDULE_RUN_STATUS_IS_FAILURE[s];\n}\n\n/**\n * ChatScheduleNotifyOn gates which run outcomes emit a completion digest to\n * the schedule's notify_channel. 'always' (the default) digests every run;\n * the others fire only on the matching outcome. Only meaningful when\n * notify_channel is set — an empty channel means no digest at all.\n */\nexport type ChatScheduleNotifyOn = 'always' | 'success' | 'failure' | 'blocked';\n\n/** What happens to an action this schedule queued for approval when its\n * window closes. Mirrors the action-policy framework's timeout policies. */\nexport type ActionScheduleTimeoutPolicy = 'block' | 'escalate' | 'execute';\n\n/**\n * ChatSchedule mirrors one row of agent_chat_schedules (M3 Stage 4).\n * The scheduler dispatcher fires due rows on its tick interval and\n * spawns an unattended chat session per firing — see ChatSession's\n * `schedule_id` / `unattended` fields for the audit linkage.\n */\n/** Parse state of a recurring-edition selector: 'present' (well-formed,\n * untampered — the identity fields are trustworthy) or 'malformed' (tampered/\n * unreadable — the untrusted identity fields are withheld and the schedule fails\n * closed at execution). */\nexport type RecurringEditionState = 'present' | 'malformed';\n\n/** Frozen-audience parse state carried in a recurring-edition summary. */\nexport type RecurringEditionAudienceState = 'present' | 'empty' | 'malformed' | 'absent';\n\n/** One bound send destination (audience list + connection). Not personal data —\n * the list object the campaign targets. */\nexport interface RecurringEditionDestination {\n kind: string;\n id: string;\n connection_id: string;\n}\n\n/**\n * Operator-safe projection of a Marketing schedule's recurring approved-edition\n * selector (IMP-MKT04-SURFACE). It names WHICH already-approved edition the\n * schedule re-sends and to HOW MANY approved recipients — never the frozen\n * audience member ids (personal data), the approved content bytes, or a secret.\n * The server NEVER serializes the raw selector; a 'malformed' state withholds the\n * untrusted identity fields and signals a degraded configuration.\n */\nexport interface RecurringEditionSummary {\n state: RecurringEditionState;\n edition_id?: string;\n approved_content_sha256?: string;\n product?: string;\n action_class?: string;\n binding_id?: string;\n binding_revision?: string;\n acting_user_id?: string;\n destinations?: RecurringEditionDestination[];\n audience_purpose?: string;\n /** Canonical authority token over the frozen consented set — the \"snapshot\n * version\": it changes iff the frozen audience changes. */\n audience_digest?: string;\n /** Number of consented contacts frozen at approval. Counts members without\n * exposing their identities. */\n approved_member_count: number;\n audience_state?: RecurringEditionAudienceState;\n}\n\nexport interface ChatSchedule {\n id: string;\n org_id: string;\n workspace_id?: string;\n repo_id: string;\n created_by_user_id: string;\n /** The schedule's DECLARED product ('cloud' | 'meeting' | 'marketing'),\n * resolved from the container at creation and persisted on the row (migration\n * 080, SHR-IP06 REV-01). Execution forks and gates on this declared fact and\n * fails closed on a mismatch with the container's current product. Omitted on\n * legacy rows (pre-080), which are all 'cloud'. */\n product?: string;\n\n name: string;\n prompt: string;\n cron_expr: string;\n /** IANA timezone name (e.g. \"Europe/Madrid\"). The cron expression\n * resolves in this timezone — \"0 9 * * *\" with timezone\n * \"Europe/Madrid\" fires at 09:00 Madrid time, including DST\n * transitions. Defaults to \"UTC\" on the server when omitted. */\n timezone: string;\n /** Subset of the repo's effective category grant. `read` is implicit\n * — empty array == read-only schedule. */\n granted_categories: ActionCategory[];\n\n enabled: boolean;\n max_runtime_minutes: number;\n max_consecutive_failures?: number;\n concurrency_policy: string;\n\n /** Logical notify-channel label a completion digest is sent to after\n * each run. Matches an attached notify credential's label\n * (case-insensitive). Empty/omitted = no digest (opt-in). */\n notify_channel?: string;\n /** Which outcomes emit a digest. Defaults to 'always'. Only relevant\n * when notify_channel is set. */\n notify_on?: ChatScheduleNotifyOn;\n\n /** Timeout policy for actions this schedule queues for approval. */\n action_timeout_policy?: ActionScheduleTimeoutPolicy;\n /** Approval-clock override in seconds; null = use the class default. */\n approval_expiry_seconds?: number | null;\n\n next_fire_at?: string;\n last_fire_at?: string;\n last_run_status?: ChatScheduleRunStatus;\n consecutive_failures: number;\n total_runs: number;\n total_successes: number;\n\n created_at: string;\n updated_at: string;\n\n /** Operator-safe recurring-edition summary for a Marketing schedule that re-sends\n * an already-approved newsletter edition (IMP-MKT04-SURFACE). Omitted on an\n * ordinary (model-loop) schedule. The raw selector — which carries the frozen\n * audience member ids and the approved content — is NEVER on the wire. */\n recurring_edition?: RecurringEditionSummary;\n}\n\nexport interface CreateChatScheduleRequest {\n workspace_id?: string;\n /** Creates an immutable recurring Marketing edition from this already-approved\n * newsletter action. The engine derives content, audience, route and actor from\n * the durable approval; clients cannot submit those authority facts directly. */\n approved_action_id?: string;\n name: string;\n prompt: string;\n cron_expr: string;\n /** IANA timezone (e.g. \"Europe/Madrid\"). Frontend should default to\n * `Intl.DateTimeFormat().resolvedOptions().timeZone`. Server\n * defaults to \"UTC\" when omitted and rejects unknown names with\n * `invalid_timezone` (HTTP 400). */\n timezone?: string;\n granted_categories?: ActionCategory[];\n /** Defaults to true on the server when omitted. */\n enabled?: boolean;\n max_runtime_minutes?: number;\n max_consecutive_failures?: number;\n concurrency_policy?: string;\n /** Notify-channel label for the completion digest. Empty/omitted = no\n * digest. */\n notify_channel?: string;\n /** When to emit the digest. Server defaults to 'always' when omitted.\n * Rejected with `invalid_notify_on` (HTTP 400) for unknown values. */\n notify_on?: ChatScheduleNotifyOn;\n /** What happens to an action this schedule queues for approval when its\n * window closes: `block` (default — the action is not taken), `escalate`\n * (route to the next approver), or `execute` (run anyway; legal only for\n * classes that could legally be AUTO at that scope). Declared at task\n * creation, never negotiated at execution time.\n *\n * `escalate` is rejected with `approvers_required` (HTTP 422) when the org\n * has no escalation list configured. */\n action_timeout_policy?: ActionScheduleTimeoutPolicy;\n /** Overrides the action class's default approval clock, in seconds.\n * Omitted/null = use the class default. */\n approval_expiry_seconds?: number | null;\n}\n\nexport interface UpdateChatScheduleRequest {\n name?: string;\n prompt?: string;\n cron_expr?: string;\n /** IANA timezone. Pass to change; omit to leave unchanged.\n * Changing timezone alone (without cron_expr) still recomputes\n * `next_fire_at` since the wall-clock target shifts. */\n timezone?: string;\n /** Pass an empty array to relax to read-only; omit to leave\n * unchanged. */\n granted_categories?: ActionCategory[];\n enabled?: boolean;\n max_runtime_minutes?: number;\n max_consecutive_failures?: number;\n concurrency_policy?: string;\n /** Pass to change the digest channel; \"\" clears it (disables digest).\n * Omit to leave unchanged. */\n notify_channel?: string;\n /** Pass to change; omit to leave unchanged. */\n notify_on?: ChatScheduleNotifyOn;\n /** What happens to an action this schedule queues for approval when its\n * window closes: `block` (default — the action is not taken), `escalate`\n * (route to the next approver), or `execute` (run anyway; legal only for\n * classes that could legally be AUTO at that scope). Declared at task\n * creation, never negotiated at execution time.\n *\n * `escalate` is rejected with `approvers_required` (HTTP 422) when the org\n * has no escalation list configured. */\n action_timeout_policy?: ActionScheduleTimeoutPolicy;\n /** Overrides the action class's default approval clock, in seconds.\n * Omitted/null = use the class default. */\n approval_expiry_seconds?: number | null;\n}\n\nexport interface ListChatSchedulesResponse {\n schedules: ChatSchedule[];\n}\n\nexport interface ChatScheduleEnvelope {\n schedule: ChatSchedule;\n}\n\n/** One per-occurrence run-history row for a product schedule (SHR-IP06 §6 item\n * 8 / REV-09). It composes SHR-IP04's `act_runs` record: the occurrence\n * identity and trigger (why it fired), what it read, produced and queued for\n * approval, and how it ended — so an operator answers \"what fired, what it read,\n * what it queued, how it ended\" from ONE row. `session_id` links to the standard\n * chat-session viewer for the full transcript. Its shape mirrors `ActRun`. */\nexport interface ScheduleOccurrence {\n id: string;\n org_id: string;\n workspace_id?: string;\n repo_id?: string;\n session_id?: string;\n schedule_id?: string;\n product: string;\n occurrence_key: string;\n /** Why it fired: 'schedule' (on time), 'schedule_late' (late), 'manual'\n * (owner run-now), or 'schedule_paused' (a gap window that did not fire). */\n trigger_kind: string;\n trigger_detail?: string;\n reads?: unknown[];\n artifacts?: unknown[];\n acts_queued?: unknown[];\n acts_executed?: unknown[];\n notifications?: unknown[];\n status: 'running' | 'completed' | 'partial' | 'failed' | 'escalated';\n failure_note?: string;\n started_at: string;\n ended_at?: string;\n}\n\n/** Response from GET /v1/agent/repos/:repo_id/schedules/:id/runs.\n *\n * `occurrences` is the per-occurrence run history (SHR-IP06 REV-09) — the\n * primary view for a product schedule. `runs` is the legacy per-session list\n * (`id` is the conversation id the SchedulesTab navigates into for the full\n * transcript); a cloud schedule carries only `runs`, a product schedule carries\n * both. */\nexport interface ListChatScheduleRunsResponse {\n runs: ChatSession[];\n occurrences?: ScheduleOccurrence[];\n}\n\n/** Response from POST /v1/agent/repos/:repo_id/schedules/:id/rerun (SHR-IP06\n * §6 item 4 / REV-07). The re-run is accepted and processed asynchronously;\n * `occurrence_key` is the derived key the run will coalesce on. */\nexport interface RerunScheduleOccurrenceResponse {\n status: 'accepted';\n schedule_id: string;\n due_window: string;\n occurrence_key: string;\n}\n\nexport interface ClarificationOption {\n id: string;\n label: string;\n description?: string;\n}\n\nexport type ChatEventType =\n | 'phase'\n | 'question'\n | 'plan_draft'\n | 'step_started'\n | 'step_completed'\n | 'step_failed'\n | 'step_progress'\n | 'narration'\n | 'assistant_message'\n | 'done'\n | 'session_title'\n | 'tool_call_started'\n | 'tool_call_finished'\n | 'llm_call_finished'\n | 'tool_call_confirmation_required'\n | 'pending_action_queued'\n | 'artifact_drafted'\n | 'artifact_referenced'\n | 'chat_compaction_fired'\n | 'chat_checkpointed';\n\nexport type ChatPhase = 'classifying' | 'clarifying' | 'executing' | 'answering' | 'done';\n\nexport interface ChatPhasePayload { phase: ChatPhase; }\n\nexport interface ChatQuestionPayload {\n question_id: string;\n prompt: string;\n kind: string;\n options?: ClarificationOption[];\n default?: string;\n role?: string;\n}\n\nexport interface ChatStepEventPayload {\n step_id: string;\n status: string;\n started_at?: string;\n completed_at?: string;\n error?: string;\n description?: string;\n}\n\n/**\n * Sent with `plan_draft` once per turn when the chat-loop's model calls\n * the report_plan tool to declare a multi-step task breakdown. The\n * dashboard renders steps as a live checklist; matching step_started /\n * step_completed / step_failed events with step_id = \"step-N\" move the\n * checklist status as the model progresses.\n */\nexport interface ChatPlanDraftPayload {\n turn_id: string;\n steps: string[];\n summary?: string;\n}\n\n/**\n * Sent with `tool_call_started`, once per chat-loop tool dispatch BEFORE\n * the tool runs. Pairs with `tool_call_finished` via tool_call_id.\n */\nexport interface ChatToolCallStartedPayload {\n turn_index: number;\n tool_name: string;\n tool_call_id: string;\n /** Short human-readable preview of the arguments, truncated. */\n summary: string;\n /**\n * Model-authored 3–10 word user-facing description of what this call\n * accomplishes (e.g. \"Listing S3 buckets\"). The dashboard renders this\n * verbatim as the live tool-call label, replacing \"Calling bash\".\n * Missing / empty → renderer falls back to the tool name.\n */\n intent?: string;\n}\n\n/**\n * Sent with `tool_call_finished`, once per chat-loop tool dispatch AFTER\n * the tool returns.\n */\nexport interface ChatToolCallFinishedPayload {\n turn_index: number;\n tool_name: string;\n tool_call_id: string;\n /** Short human-readable preview of stdout/stderr, truncated. */\n summary: string;\n}\n\n/**\n * Sent with `llm_call_finished` once per successful LLM round-trip during\n * a chat-loop turn. The dashboard's budget badge uses this as a fast\n * invalidation signal so the displayed spend tracks the persisted total\n * in near real time, instead of waiting for the 30 s poll. Failed LLM\n * calls do not emit.\n */\nexport interface ChatLLMCallFinishedPayload {\n turn_index: number;\n model: string;\n /** USD cost in micros (1e-6 USD) attributed to this LLM call. Zero\n * when no pricing row matched the model — clients should still treat\n * the event as a refetch hint. */\n cost_delta_micros: number;\n}\n\n/**\n * Sent with `tool_call_confirmation_required` when the M3 policy hook\n * classifies a tool call into a category that is permitted at the\n * org/workspace/repo level but is also in the chat session's\n * `confirm_categories` set — the user wants to approve each invocation\n * inline before the engine dispatches it. The chat loop suspends until\n * the dashboard POSTs the user's decision to\n * `/v1/agent/chat/sessions/:id/messages/:turn_id/confirm/:tool_call_id`\n * (or until the 4-minute confirmer timeout elapses, which is treated as\n * an implicit deny — safe default).\n *\n * Unattended (scheduled) runs never emit this event — confirm collapses\n * to deny when no human is connected.\n */\nexport interface ChatToolCallConfirmationRequiredPayload {\n turn_index: number;\n tool_call_id: string;\n tool_name: string;\n /** Truncated stringification of the tool args, suitable for the\n * modal preview. Full args remain in the surrounding\n * `tool_call_started` event for the debug view. */\n args_preview: string;\n /** One of the M3 action categories (write_data, create_resource,\n * delete_data, destroy_resource, scale_capacity, modify_iam,\n * modify_network, execute_runtime). */\n category: string;\n /** Human-readable explanation from the policy engine — e.g.\n * \"category \\\"delete_data\\\" requires inline confirmation\". Rendered\n * in the modal as a hint about *why* the agent is asking. */\n rationale?: string;\n /** Present only when the action-policy stage raised this card (GATE's\n * synchronous face). Absent for a plain category confirmation, so the\n * class badge renders only when there is a class. */\n action_class?: string;\n}\n\nexport interface ChatStepProgressPayload {\n step_id: string;\n message: string;\n progress_pct?: number;\n}\n\nexport interface ChatNarrationPayload {\n step_id?: string;\n text: string;\n}\n\n/* ------------------------------------------------------------------ *\n * Claim → evidence citation vocabulary (common-infra evidence-citation)\n *\n * The suite-wide \"click a claim, see its evidence\" contract. These types\n * mirror the engine's persisted encoding (cloud-agent internal/chat/citation):\n * - a `claim_annotations` sidecar on an assistant text message's `metadata`\n * (transient chat answers reconstruct citations from the transcript — the\n * resolver reads the same rows \"Show query\" reads; nothing is a second\n * store), and\n * - a `bi_verification` marker on a run_bi_query `tool_result` message's\n * `metadata` (the verifier verdict, surfaced quietly).\n * The live SSE `citations` field carries the same ClaimAnnotation[] so the\n * client can render affordances at `done`.\n * ------------------------------------------------------------------ */\n\n/** The platform-wide claim taxonomy. Only `fact` requires evidence. */\nexport type ClaimClass = 'fact' | 'interpretation' | 'recommendation';\n\n/**\n * Evidence kinds. `recorded-query` + `source-doc` are the MVP-live kinds; the\n * rest are registered by their sibling components as they ship (extensible).\n */\nexport type EvidenceKind =\n | 'recorded-query'\n | 'source-doc'\n | 'transcript-span'\n | 'model-run'\n | 'pack-fact'\n | 'connection-fact'\n | 'signal'\n | 'artifact-version';\n\n/** What the evidence IS vs what the claim SAYS. Numbers are `derived`. */\nexport type EvidenceGrade = 'verbatim' | 'paraphrase' | 'derived';\n\n/** Honest terminal state a resolver reports for a ref. */\nexport type ResolutionState = 'resolved' | 'forbidden' | 'gone' | 'stale';\n\n/** Half-open char-offset range into the final answer prose. */\nexport interface EvidenceSpan {\n start: number;\n end: number;\n}\n\n/** Typed target of an EvidenceRef (a union across the live kinds). */\nexport interface EvidenceRefTarget {\n exchange_id?: string;\n turn_id?: string;\n message_id?: string;\n /** source-doc */\n locator?: string;\n captured_at?: string;\n content_hash?: string;\n}\n\n/** Version stamps that make provenance reproducible; rendered as words. */\nexport interface EvidencePins {\n model?: string;\n dataset_refs?: string[];\n captured_at?: string;\n}\n\nexport interface EvidenceRef {\n kind: EvidenceKind;\n ref: EvidenceRefTarget;\n pins?: EvidencePins;\n}\n\n/** Points a claim at the tool_result carrying its bi_verification marker. */\nexport interface ClaimVerificationRef {\n exchange_id: string;\n}\n\nexport interface ClaimAnnotation {\n span: EvidenceSpan;\n class: ClaimClass;\n /** ≥1 iff class==='fact' AND cited; [] = an uncited fact (marked, counted). */\n evidence: EvidenceRef[];\n grade?: EvidenceGrade;\n verification_ref?: ClaimVerificationRef;\n}\n\n/** The sidecar persisted on an assistant text message's metadata. */\nexport interface ClaimAnnotations {\n schema: number;\n target_turn_id: string;\n claims: ClaimAnnotation[];\n /**\n * Claims the engine's extractor could not map to the answer prose, so they\n * are absent from `claims` entirely. Omitted when zero.\n *\n * A consumer rendering a coverage line MUST fold this in: without it the line\n * describes the annotations that survived rather than the answer, and four\n * facts with three unmappable quotes read as \"all 1 facts cited\".\n */\n unmapped_claims?: number;\n /**\n * Citations that named an exchange the turn could not back — an out-of-range\n * ordinal, an unknown tool_call_id, or a result the PII gate withheld. The\n * claim survives as an uncited fact. Omitted when zero.\n */\n unbound_refs?: number;\n}\n\n/** The verifier verdict persisted on a run_bi_query tool_result's metadata. */\nexport interface BIVerification {\n ok: boolean;\n checks: string[];\n at: string;\n}\n\n/** Metadata keys under which the two citation blobs live on ChatMessage rows. */\nexport const CLAIM_ANNOTATIONS_METADATA_KEY = 'claim_annotations';\nexport const BI_VERIFICATION_METADATA_KEY = 'bi_verification';\n\n/**\n * claimAnnotationsOf reads the claim-annotation sidecar off an assistant text\n * message. Returns undefined when the message predates citations / was produced\n * with the flag off (\"not annotated\") — distinct from a present-but-empty set\n * (a genuinely fact-free answer). No runtime validation beyond shape presence.\n */\nexport function claimAnnotationsOf(message: Pick<ChatMessage, 'metadata'>): ClaimAnnotations | undefined {\n const blob = message.metadata?.[CLAIM_ANNOTATIONS_METADATA_KEY];\n if (blob && typeof blob === 'object' && Array.isArray((blob as ClaimAnnotations).claims)) {\n return blob as ClaimAnnotations;\n }\n return undefined;\n}\n\n/**\n * biVerificationOf reads the verifier verdict off a run_bi_query tool_result\n * message. Absent for legacy exchanges and when the flag is off.\n */\nexport function biVerificationOf(message: Pick<ChatMessage, 'metadata'>): BIVerification | undefined {\n const blob = message.metadata?.[BI_VERIFICATION_METADATA_KEY];\n if (blob && typeof blob === 'object' && typeof (blob as BIVerification).ok === 'boolean') {\n return blob as BIVerification;\n }\n return undefined;\n}\n\nexport interface ChatAssistantMessagePayload {\n message_id: string;\n content: string;\n /** Live claim→evidence annotations for the answer (evidence-citation §11);\n * omitted when the flag is off or the answer carried none. */\n citations?: ClaimAnnotation[];\n}\n\nexport interface ChatDonePayload {\n turn_id: string;\n plan_id?: string;\n status?: string;\n /** LLM id the chat-loop ran this turn against (M2/I5). The badge\n * renders this next to the spend so the user can see which model\n * was selected by the per-repo provider resolver. Empty when the\n * turn aborted before the resolver picked one (rare). */\n model_used?: string;\n}\n\nexport interface ChatSessionTitlePayload {\n title: string;\n}\n\n/**\n * Sent with `chat_compaction_fired` once per Run when the chat-loop\n * mid-session replaces older history with a structured progress note\n * (chat-compact-optimization Front #1). The session-debug view uses\n * this to mark the boundary in the rendered transcript so operators\n * can see how aggressively the loop is trimming context.\n */\nexport interface ChatCompactionFiredPayload {\n turn_index: number;\n prompt_tokens_before: number;\n compactor_model: string;\n}\n\n/**\n * Sent with `chat_checkpointed` when the chat-loop, on its final\n * allowed iteration, emits a structured terminal summary instead of\n * running another open-ended LLM call (chat-compact-optimization Front\n * #2). The accompanying assistant message is the checkpoint body; the\n * dashboard should render the session's StopReason\n * (\"max_turns_checkpointed\") with a distinct chip and offer a \"Continue\n * this work\" affordance that POSTs a canned follow-up.\n */\nexport interface ChatCheckpointedPayload {\n turn_index: number;\n checkpoint_model: string;\n}\n\n/**\n * Sent with `pending_action_queued` when an unattended run defers a gated\n * action to the approvals queue (action-policy stage). Purely informational\n * for a live viewer — the durable state of record is the backend pending-action\n * row addressed by `pending_action_id`, not this event. Deliberately NOT a\n * reuse of ChatToolCallConfirmationRequiredPayload: that event gates the\n * composer and expects an answer now, whereas a queued action is resolved\n * later from a queue page. Mirrors the engine\n * types.ChatPendingActionQueuedPayload wire contract exactly.\n */\nexport interface ChatPendingActionQueuedPayload {\n turn_index: number;\n pending_action_id: string;\n action_class: string;\n tool_name: string;\n preview: string;\n /** RFC3339; omitted (engine `omitempty`) when the queued action has no expiry. */\n expires_at?: string;\n}\n\n/**\n * Sent with `artifact_drafted` when draft_artifact/revise_artifact/\n * promote_artifact mints or appends an artifact version (artifact-substrate\n * AS-8). Purely informational for a live viewer's chip strip — the durable\n * state of record is the backend row, not this event.\n */\nexport interface ChatArtifactDraftedPayload {\n turn_index: number;\n artifact_id: string;\n version_id: string;\n version_ref: string;\n /**\n * The fully-qualified handle. The split ids are carried alongside it so a\n * viewer does not have to parse the handle to build a link; the two always\n * agree, because the backend produced both from the same row.\n */\n handle: string;\n title?: string;\n kind?: string;\n}\n\n/**\n * Sent with `artifact_referenced` when a turn returns an already-existing\n * artifact version rather than minting a new one. The payload deliberately\n * mirrors `ChatArtifactDraftedPayload`, while the distinct event name keeps\n * fresh-authoring semantics honest for live viewers.\n */\nexport interface ChatArtifactReferencedPayload {\n turn_index: number;\n artifact_id: string;\n version_id: string;\n version_ref: string;\n /**\n * The fully-qualified handle. The split ids are carried alongside it so a\n * viewer does not have to parse the handle to build a link; the two always\n * agree, because the backend produced both from the same row.\n */\n handle: string;\n title?: string;\n kind?: string;\n}\n\nexport interface ChatEvent {\n conversation_id: string;\n turn_id: string;\n type: ChatEventType;\n plan_id?: string;\n step_id?: string;\n payload?:\n | ChatPhasePayload\n | ChatQuestionPayload\n | ChatPlanDraftPayload\n | ChatStepEventPayload\n | ChatStepProgressPayload\n | ChatNarrationPayload\n | ChatAssistantMessagePayload\n | ChatDonePayload\n | ChatSessionTitlePayload\n | ChatToolCallStartedPayload\n | ChatToolCallFinishedPayload\n | ChatLLMCallFinishedPayload\n | ChatToolCallConfirmationRequiredPayload\n | ChatPendingActionQueuedPayload\n | ChatArtifactDraftedPayload\n | ChatArtifactReferencedPayload\n | ChatCompactionFiredPayload\n | ChatCheckpointedPayload\n | unknown;\n timestamp: string;\n event_id?: number;\n}\n\n/**\n * Per-LLM-call audit row written by the chat-loop's recorder.Record (one row\n * per Chat.Completions.New call). Mirrors execution_receipts on the engine\n * side. All numeric token / cost fields are nullable because they weren't\n * tracked for failed calls or pre-migration rows.\n */\nexport interface DebugReceipt {\n id: string;\n flow_id: string;\n org_id: string;\n status: string;\n duration_ms?: number | null;\n model_used?: string | null;\n layer?: string;\n operation?: string;\n attempt_number: number;\n error?: string | null;\n prompt_tokens?: number | null;\n completion_tokens?: number | null;\n cached_prompt_tokens?: number | null;\n cost_usd_micros?: number | null;\n // Billing-ledger tag: 'byok' | 'platform' | 'agent'. NULL on the raw llmlog\n // call rows. Totals should sum cost over rows with a cost_kind (the metered\n // ledger) and tokens over byok/platform rows only — the raw rows and the\n // agent surcharge row otherwise double/triple-count.\n cost_kind?: 'byok' | 'platform' | 'agent' | null;\n prompt?: string | null;\n response?: string | null;\n created_at: string;\n}\n\n/**\n * Debug surface — consolidated payload returned by\n * `GET /api/agentengine/v1/agent/chat/sessions/:id/debug`.\n */\nexport interface DebugPayload {\n session: ChatSession | null;\n messages: ChatMessage[] | null;\n receipts: DebugReceipt[];\n}\n","/**\n * ChatCardV1 — the CLOSED, versioned conversation-card projection (MVP09\n * C1-SDK-CARDS, chat-first realignment proposal §6). This is the SDK mirror of\n * the engine's authority-side type: the wire shape is defined by cloud-agent\n * `internal/types/chat_cards.go` (`ChatCardV1.ToMetadata()`) and the neutral\n * builders in `internal/chat/card_adapter.go`.\n *\n * A card is a DISPLAY PROJECTION of durable product state, never the authority\n * for it. It carries server-stamped scope assertions (product / project_id /\n * sandbox_id) plus an opaque `durable_ref` to the backend row that IS\n * authoritative. It deliberately carries NO domain payload: an approver still\n * resolves the pending action against its own record, an artifact is still\n * fetched from the substrate.\n *\n * The card is persisted as the metadata of a `card`-kind `agent_chat_messages`\n * row, so a reconnecting client rehydrates it through the reload read path\n * (`client.chat.sessions.get()` -> GetChatSessionResponse.messages); the live\n * SSE `pending_action_queued` / `artifact_drafted` events (C0-SDK-STREAM) feed\n * the same projection for a connected viewer.\n *\n * Two safety laws govern this file (proposal §6, §10):\n * 1. The union is CLOSED. `card_type` and every action are enumerated. A card\n * whose `schema_version` or `card_type` this client does not recognise\n * parses to a safe, inert {@link UnknownChatCard} fallback — it is NEVER\n * cast to a typed variant, and the fallback exposes no `actions` field, so\n * it cannot be a source of dispatchable actions.\n * 2. A card action is one of the enumerated inert names and nothing else. An\n * unknown action string is dropped during parse, so it can never survive\n * into the dispatchable union. The model may propose display content but\n * never an arbitrary URL, endpoint, verb, credential or executable.\n *\n * Scope validation (rejecting a stale / cross-scope projection) is NOT done\n * here: the SDK parser has no session scope to compare against. That is the\n * engine read guard (`FilterCardMessagesForScope`, C1-BE-CARD-STORE) and the\n * console reducer (C1-UI-CARD-STATE). This file owns only the closed-union type\n * and its safe, never-executable parse.\n */\n\nimport type { ChatMessage } from './types.js';\n\n/** The only schema version this client narrows to a typed variant. A higher\n * (or zero/negative) version is treated as an opaque, inert fallback. */\nexport const CHAT_CARD_SCHEMA_VERSION = 1 as const;\n\n/** Message kind tagging an agent_chat_messages row whose metadata carries a\n * ChatCardV1 projection (mirrors cloud-agent `types.ChatMessageKindCard`). */\nexport const CHAT_MESSAGE_KIND_CARD = 'card' as const;\n\n/** The closed set of card types. Every variant of the discriminated union\n * below is keyed on one of these; anything else is an inert fallback. */\nexport const CHAT_CARD_TYPES = [\n 'connection_required',\n 'pending_action',\n 'artifact',\n 'record',\n 'receipt',\n] as const;\nexport type ChatCardType = (typeof CHAT_CARD_TYPES)[number];\n\n/** The closed set of inert card actions. `navigate` targets are allowlisted and\n * scope-bound by the UI; `refresh` only refetches the durable record;\n * `answer_question` / `decide_confirmation` submit to their existing bounded\n * endpoints. No other verb is representable. */\nexport const CHAT_CARD_ACTIONS = [\n 'navigate',\n 'answer_question',\n 'decide_confirmation',\n 'refresh',\n] as const;\nexport type ChatCardAction = (typeof CHAT_CARD_ACTIONS)[number];\n\n/** Opaque pointer to the authoritative backend row — a reference, never the\n * payload. {kind,id,version} is enough to refetch and re-authorise the current\n * state, and carries no secret or domain content. */\nexport interface ChatCardDurableRef {\n kind: string;\n id: string;\n version?: string;\n}\n\n/** Fields shared by every closed variant. `product` / `project_id` /\n * `sandbox_id` are SERVER-STAMPED scope assertions used for display and for\n * read-time rejection of a stale / cross-scope projection; they are never\n * selector inputs and cannot override the session's server-derived topology. */\ninterface ChatCardCommonV1 {\n schema_version: typeof CHAT_CARD_SCHEMA_VERSION;\n card_id: string;\n product: string;\n project_id: string;\n sandbox_id: string;\n title?: string;\n summary?: string;\n status?: string;\n durable_ref?: ChatCardDurableRef;\n /** Always the enumerated inert actions only — unknown strings are dropped at\n * parse, so this array can never carry a non-dispatchable verb. */\n actions: ChatCardAction[];\n}\n\nexport interface ConnectionRequiredCardV1 extends ChatCardCommonV1 {\n card_type: 'connection_required';\n}\nexport interface PendingActionCardV1 extends ChatCardCommonV1 {\n card_type: 'pending_action';\n}\nexport interface ArtifactCardV1 extends ChatCardCommonV1 {\n card_type: 'artifact';\n}\nexport interface RecordCardV1 extends ChatCardCommonV1 {\n card_type: 'record';\n}\nexport interface ReceiptCardV1 extends ChatCardCommonV1 {\n card_type: 'receipt';\n}\n\n/** The CLOSED discriminated union. Narrow on `card_type` to reach a variant. */\nexport type ChatCardV1 =\n | ConnectionRequiredCardV1\n | PendingActionCardV1\n | ArtifactCardV1\n | RecordCardV1\n | ReceiptCardV1;\n\n/**\n * The safe, inert fallback for a projection this client does not recognise —\n * an unknown `schema_version` or an unknown `card_type`. It deliberately has NO\n * `actions` field: a consumer cannot read a dispatchable action off it, which is\n * exactly what \"never an executable cast\" means. `raw` is the untouched\n * metadata, for inert text rendering only — never narrowed, never a source of\n * actions or navigation.\n */\nexport interface UnknownChatCard {\n card_type: 'unknown';\n reason: 'unknown_version' | 'unknown_type';\n schema_version?: number;\n card_id?: string;\n title?: string;\n summary?: string;\n status?: string;\n raw: Record<string, unknown>;\n}\n\n/** The result of {@link parseChatCard}: a typed closed variant OR the inert\n * fallback. `undefined` (from the parser) means \"not a card at all\". */\nexport type ParsedChatCard = ChatCardV1 | UnknownChatCard;\n\n/** Narrowing guard: a parsed card is a typed closed variant (not the inert\n * fallback). Use before touching `.actions` or any variant field. */\nexport function isKnownChatCard(card: ParsedChatCard): card is ChatCardV1 {\n return card.card_type !== 'unknown';\n}\n\nconst CARD_TYPE_SET: ReadonlySet<string> = new Set(CHAT_CARD_TYPES);\nconst CARD_ACTION_SET: ReadonlySet<string> = new Set(CHAT_CARD_ACTIONS);\n\n/** Reports whether `t` is a recognised closed card type. */\nexport function isKnownChatCardType(t: unknown): t is ChatCardType {\n return typeof t === 'string' && CARD_TYPE_SET.has(t);\n}\n\n/** Reports whether `a` is a recognised inert card action. */\nexport function isKnownChatCardAction(a: unknown): a is ChatCardAction {\n return typeof a === 'string' && CARD_ACTION_SET.has(a);\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction asString(v: unknown): string {\n return typeof v === 'string' ? v : '';\n}\n\nfunction optString(v: unknown): string | undefined {\n return typeof v === 'string' && v !== '' ? v : undefined;\n}\n\nfunction parseDurableRef(v: unknown): ChatCardDurableRef | undefined {\n if (!isRecord(v)) return undefined;\n const kind = asString(v.kind);\n const id = asString(v.id);\n if (kind === '' && id === '') return undefined;\n const ref: ChatCardDurableRef = { kind, id };\n const version = optString(v.version);\n if (version !== undefined) ref.version = version;\n return ref;\n}\n\n/** Keep ONLY the enumerated inert actions, in order. An unknown action string\n * is dropped so it can never survive into the dispatchable union. */\nfunction parseActions(v: unknown): ChatCardAction[] {\n if (!Array.isArray(v)) return [];\n const out: ChatCardAction[] = [];\n for (const a of v) {\n if (isKnownChatCardAction(a)) out.push(a);\n }\n return out;\n}\n\nfunction coerceVersion(v: unknown): number | undefined {\n if (typeof v === 'number') return v;\n if (typeof v === 'string' && v.trim() !== '' && !Number.isNaN(Number(v))) return Number(v);\n return undefined;\n}\n\n/**\n * Parse an arbitrary metadata blob into a closed {@link ChatCardV1} variant or\n * the inert {@link UnknownChatCard} fallback.\n *\n * - Not a card at all (non-object, or no string `card_type`) -> `undefined`.\n * - `schema_version` !== {@link CHAT_CARD_SCHEMA_VERSION} -> inert fallback\n * (`reason: 'unknown_version'`) even if the type is otherwise known: a future\n * version may reinterpret fields, so it is never narrowed to a typed cast.\n * - `card_type` outside the closed set -> inert fallback\n * (`reason: 'unknown_type'`).\n * - Otherwise a typed variant whose `actions` are filtered to the enumerated\n * inert set.\n *\n * This is total and never throws; a malformed field degrades to empty/undefined\n * rather than propagating an executable value.\n */\nexport function parseChatCard(metadata: unknown): ParsedChatCard | undefined {\n if (!isRecord(metadata)) return undefined;\n const cardType = metadata.card_type;\n // A card is identified by a string card_type. Without one this metadata is\n // something else (e.g. the claim_annotations sidecar) — not a card.\n if (typeof cardType !== 'string' || cardType === '') return undefined;\n\n const version = coerceVersion(metadata.schema_version);\n\n const fallback = (reason: UnknownChatCard['reason']): UnknownChatCard => {\n const u: UnknownChatCard = { card_type: 'unknown', reason, raw: metadata };\n if (version !== undefined) u.schema_version = version;\n const id = optString(metadata.card_id);\n if (id !== undefined) u.card_id = id;\n const title = optString(metadata.title);\n if (title !== undefined) u.title = title;\n const summary = optString(metadata.summary);\n if (summary !== undefined) u.summary = summary;\n const status = optString(metadata.status);\n if (status !== undefined) u.status = status;\n return u;\n };\n\n // Unknown/absent version is inert BEFORE any type narrowing — a v2 card must\n // never be cast to a v1 variant just because its card_type name matches.\n if (version !== CHAT_CARD_SCHEMA_VERSION) return fallback('unknown_version');\n if (!isKnownChatCardType(cardType)) return fallback('unknown_type');\n\n const card: ChatCardV1 = {\n schema_version: CHAT_CARD_SCHEMA_VERSION,\n card_type: cardType,\n card_id: asString(metadata.card_id),\n product: asString(metadata.product),\n project_id: asString(metadata.project_id),\n sandbox_id: asString(metadata.sandbox_id),\n actions: parseActions(metadata.actions),\n };\n const title = optString(metadata.title);\n if (title !== undefined) card.title = title;\n const summary = optString(metadata.summary);\n if (summary !== undefined) card.summary = summary;\n const status = optString(metadata.status);\n if (status !== undefined) card.status = status;\n const durableRef = parseDurableRef(metadata.durable_ref);\n if (durableRef !== undefined) card.durable_ref = durableRef;\n return card;\n}\n\n/**\n * Read the ChatCardV1 projection off a chat message. Returns `undefined` for\n * any message that is not a `card`-kind row, so an ordinary text / question /\n * tool message is never reinterpreted as a card even if its metadata happens to\n * be card-shaped. An in-scope card-kind message with an unknown version/type is\n * returned as the inert {@link UnknownChatCard} fallback (render as text; never\n * dispatch), matching the engine's \"retain an unknown card_type as inert\"\n * reload behavior (proposal §6, §10).\n */\nexport function chatCardOf(\n message: Pick<ChatMessage, 'kind' | 'metadata'>,\n): ParsedChatCard | undefined {\n if (message.kind !== CHAT_MESSAGE_KIND_CARD) return undefined;\n return parseChatCard(message.metadata);\n}\n","/**\n * Component capability plane — harden-merge F4 (REL-01).\n *\n * The backend is the single source of truth for whether a\n * common-infrastructure component exists in a deployment. Every consumer — the\n * console, the engine, this SDK — reads the same answer instead of deciding for\n * itself, which is the failure this closes: the console listed component\n * navigation unconditionally while four of the eight components had no backend\n * flag at all, so no single surface was wrong and none of them was dark.\n */\n\n/** The canonical component enum. Adding a ninth means changing the backend\n * enum, the database CHECK, the engine mirror and this list together. */\nexport const COMPONENT_IDS = [\n 'action_policy',\n 'connection_inventory',\n 'contact_registry',\n 'pack_registry',\n 'artifact_substrate',\n 'evidence_citation',\n 'fact_governance',\n 'signal_store',\n] as const;\n\nexport type ComponentId = (typeof COMPONENT_IDS)[number];\n\n/**\n * A component's lifecycle position for the calling organization.\n *\n * - `implemented` — the code exists; this deployment has not enabled it.\n * - `available` — the deployment enables it; no organization grant yet.\n * - `enabled` — this organization may use it.\n *\n * Only `enabled` means anything may render, register or run. The three states\n * are distinguished rather than collapsed into a boolean because \"not built\n * here\" and \"built but not granted to you\" are different answers to the same\n * support question.\n */\nexport type ComponentState = 'implemented' | 'available' | 'enabled';\n\nexport interface CapabilitiesResponse {\n /** Keyed by ComponentId; read a missing key as NOT enabled. */\n components: Record<string, ComponentState>;\n /** True when the answer describes an impersonation target rather than the\n * caller's own organization. */\n impersonating?: boolean;\n orgId?: string;\n}\n\nexport interface SetEnabledComponentsRequest {\n /** Replaces the organization's grants. An unknown id is rejected, not\n * dropped — silently ignoring a typo leaves an operator believing they\n * granted something they did not. */\n components: ComponentId[];\n}\n\nexport interface SetEnabledComponentsResponse {\n id: string;\n enabledComponents: string[];\n}\n\n/**\n * The cohort editor's READ — harden-merge F-5 / CE-6.\n *\n * `stored` and `components` deliberately differ. A grant for a component this\n * deployment does not have is accepted and stored and changes nothing:\n * composition is one-directional, so a grant waits for the deployment flag and\n * can never widen it. An editor showing only the stored list would report a\n * grant that is inert; one showing only the effective state would make the\n * operator's own write look ignored.\n */\nexport interface EnabledComponentsResponse {\n id: string;\n /** What the organization's grant row says, in manifest order. */\n stored: ComponentId[];\n /** What this DEPLOYMENT has, irrespective of any grant. */\n available: ComponentId[];\n /** The two composed. Keyed by ComponentId; a missing key is NOT enabled. */\n components: Record<string, ComponentState>;\n /** Ids present in the row that the canonical enum does not know. Reported\n * rather than dropped: hiding one would let the next write delete it. */\n unknownStored?: string[];\n}\n","// Hierarchical USD budgets. All wire values are USD micros (1 USD = 1_000_000);\n// 0 means \"no cap / inherit from parent\" — never \"free\".\n\nexport type BudgetScope = 'org' | 'workspace' | 'repo' | 'chat';\n\nexport interface OrgBudget {\n id: string;\n org_id: string;\n daily_limit: number; // legacy token caps — NOT enforced; counters below are telemetry only\n monthly_limit: number;\n tokens_today: number;\n tokens_month: number;\n daily_cost_limit_usd_micros: number;\n monthly_cost_limit_usd_micros: number;\n cost_today_usd_micros: number;\n cost_month_usd_micros: number;\n chat_session_cost_limit_usd_micros: number;\n reset_day_at: string;\n reset_month_at: string;\n updated_at: string;\n /** M3 Stage 3: action categories allowed at this scope. `read` is\n * implicit and never appears here. Lower scopes (workspace, repo,\n * schedule) intersect with this set. */\n granted_categories: string[];\n /** M3 Stage 4: inheritable schedule auto-disable threshold. Null\n * means \"inherit from parent\"; engine default is 5 when every\n * level in the chain is null. */\n max_consecutive_failures?: number;\n}\n\nexport interface ScopedBudget {\n id: string;\n org_id: string;\n workspace_id?: string;\n repo_id?: string;\n daily_cost_limit_usd_micros: number;\n monthly_cost_limit_usd_micros: number;\n chat_session_cost_limit_usd_micros: number;\n cost_today_usd_micros: number;\n cost_month_usd_micros: number;\n reset_day_at: string;\n reset_month_at: string;\n updated_at: string;\n /** M3 Stage 3: see OrgBudget.granted_categories. Subset of parent. */\n granted_categories: string[];\n /** M3 Stage 4: see OrgBudget.max_consecutive_failures. */\n max_consecutive_failures?: number;\n}\n\nexport interface ChatBudget {\n id: string;\n org_id: string;\n workspace_id: string;\n repo_id: string;\n chat_session_id: string;\n cost_limit_usd_micros: number;\n cost_total_usd_micros: number;\n created_by_user_id: string;\n updated_at: string;\n}\n\nexport interface EffectiveChatBudget {\n limit_usd_micros: number;\n source: BudgetScope;\n spent_usd_micros: number;\n}\n\nexport interface UpdateOrgBudgetRequest {\n daily_cost_limit_usd_micros?: number;\n monthly_cost_limit_usd_micros?: number;\n chat_session_cost_limit_usd_micros?: number;\n /** M3 Stage 3: replace the action-category grant set. Omit to leave\n * unchanged; empty array relaxes to read-only. */\n granted_categories?: string[];\n /** M3 Stage 4: per-scope schedule auto-disable cap. Omit to leave\n * unchanged. */\n max_consecutive_failures?: number;\n}\n\nexport interface UpdateScopedBudgetRequest {\n daily_cost_limit_usd_micros?: number;\n monthly_cost_limit_usd_micros?: number;\n chat_session_cost_limit_usd_micros?: number;\n /** M3 Stage 3: replace the action-category grant set. Server rejects\n * (422 grants_outside_parent) when the requested set isn't a subset\n * of the parent scope's effective grant. */\n granted_categories?: string[];\n /** M3 Stage 4: per-scope schedule auto-disable cap. */\n max_consecutive_failures?: number;\n}\n\nexport interface UpdateChatBudgetRequest {\n cost_limit_usd_micros: number;\n}\n\nexport interface UpdateCostLimitRequest {\n cost_limit_usd_micros: number;\n}\n\nexport const usdMicros = {\n toDollars: (micros: number): number => micros / 1_000_000,\n fromDollars: (dollars: number): number => Math.round(dollars * 1_000_000),\n};\n","// Dashboard Spec types — TypeScript mirror of the canonical JSON Schema\n// cloud-agent/internal/chat/dashboardspec/schema/flashback.dashboard.v1.schema.json\n// (copied into this package as ./schema.json). The JSON Schema is the single\n// source of truth (Visual-Dashboards block B1); these types and ./schema.json\n// must stay byte-for-shape in sync with the engine schema when it changes.\n//\n// The Dashboard Spec is the durable, data-free, PII-free recipe the BI agent's\n// compose_dashboard tool emits. Each panel carries a `binding` (a parameterized\n// query against a semantic model) and a `viz` (how to draw the result). Data is\n// transient; the spec is forever.\n\n/** The spec major-version discriminator carried in DashboardSpec.schema. */\nexport const DASHBOARD_SCHEMA_VERSION = 'flashback.dashboard/v1';\n\nexport type PanelType =\n | 'kpi' | 'gauge' | 'table'\n | 'bar' | 'line' | 'area' | 'point' | 'arc' | 'rule' | 'tick' | 'rect';\n\n/** Chart marks = the curated, recursion-stripped Vega-Lite subset. */\nexport type ChartMark = 'bar' | 'line' | 'area' | 'point' | 'arc' | 'rule' | 'tick' | 'rect';\n\n/** Semantic color roles (D6) — the spec picks a role, never a raw hex. */\nexport type ColorRole = 'sequential' | 'categorical' | 'diverging' | 'goodBad';\n\nexport type ChannelType = 'nominal' | 'quantitative' | 'temporal' | 'ordinal';\nexport type ChannelSort = '-x' | 'x' | '-y' | 'y' | 'ascending' | 'descending' | null;\n/** Inline-aggregate functions (for models without authored measures). */\nexport type AggFn = 'sum' | 'avg' | 'min' | 'max' | 'count' | 'distinctcount';\nexport type ParameterType = 'daterange' | 'dimension' | 'scalar';\nexport type FilterOp = 'eq' | 'in' | 'gt' | 'gte' | 'lt' | 'lte' | 'between';\nexport type SortDir = 'asc' | 'desc';\n/** Rehydration strategy (distinct from B0's piiClass field classification). */\nexport type PIITier = 'none' | 'rehydrate';\n\n/** The whole authored artifact. */\nexport interface DashboardSpec {\n /** Always DASHBOARD_SCHEMA_VERSION for v1. */\n schema: typeof DASHBOARD_SCHEMA_VERSION;\n title: string;\n description?: string;\n scope: DashboardScope;\n /** Dashboard-level controls; bindings reference them by id (cross-filter-ready). */\n parameters?: Parameter[];\n /** react-grid-layout-shaped 12-col grid; one entry per panel id. */\n layout: LayoutItem[];\n panels: Panel[];\n}\n\nexport interface DashboardScope {\n repoId: string;\n /** Default model for any panel binding that omits modelId. */\n defaultModelId?: string;\n}\n\nexport interface Parameter {\n id: string;\n type: ParameterType;\n label: string;\n /** Required when type === 'dimension'. A field ref, e.g. \"Branch[Name]\". */\n field?: string;\n multi?: boolean;\n /** Shape depends on type: daterange => {relative}|{from,to}; etc. */\n default?: unknown;\n}\n\nexport interface LayoutItem {\n /** Matches a Panel.id. */\n i: string;\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** A param-bound filter ({param}) or a literal ({field,op,value}). */\nexport type Filter = ParamFilter | LiteralFilter;\nexport interface ParamFilter { param: string; }\nexport interface LiteralFilter { field: string; op: FilterOp; value: unknown; }\n\nexport interface TopN { by: string; n: number; dir: SortDir; }\n\n/**\n * An inline aggregate — a measure term for models that define few/no catalog\n * measures. Aggregates a raw column; compiles to AGG('Entity'[Column]) aliased\n * `as`, whose result column is keyed \"[as]\" (referenced like a measure ref).\n */\nexport interface InlineAggregate {\n agg: AggFn;\n /** Field ref, e.g. \"Timesheet[WorkedHours]\". */\n field: string;\n /** Result alias (no brackets; unique within the binding). */\n as: string;\n}\n\n/** The unit of a dateDiff duration. */\nexport type DateDiffUnit = 'day' | 'week' | 'month' | 'quarter' | 'year';\n\n/**\n * A closed-form duration measure term (WP4): AGG of DATEDIFF(from, to, unit) over\n * the rows of the two columns' shared entity, skipping blank endpoints. from/to\n * MUST be Date columns on the SAME entity. Result column is keyed \"[as]\".\n */\nexport interface DateDiffAggregate {\n agg: 'avg' | 'min' | 'max' | 'sum';\n dateDiff: {\n /** Field ref, a Date column. */\n from: string;\n /** Field ref, a Date column on the same entity. */\n to: string;\n unit: DateDiffUnit;\n /** Skip rows where to < from instead of letting them drag the aggregate. */\n nonNegative?: boolean;\n };\n /** Result alias (no brackets; unique within the binding). */\n as: string;\n}\n\n/**\n * A measure term: a catalog measure ref (\"[Name]\"), an inline aggregate, or a\n * closed-form dateDiff duration.\n */\nexport type MeasureTerm = string | InlineAggregate | DateDiffAggregate;\n\n/**\n * A DATE-GRAIN dimension term: groups by a date column bucketed to a calendar unit\n * instead of by its raw value. Grouping a raw date column buckets by every distinct\n * timestamp, which draws as noise rather than a trend. The bucket is COMPUTED, so it\n * comes back keyed \"[as]\" (like an inline aggregate, not like a plain dimension) and\n * viz.encoding fields reference it that way, with channel type \"temporal\".\n */\nexport interface DateGrainDimension {\n /** Field ref, a Date column. */\n field: string;\n dateGrain: DateDiffUnit;\n /** Result alias (no brackets; unique across the binding's dimensions AND measures). */\n as: string;\n}\n\n/**\n * A dimension term: a plain field ref (\"Mechanic[MechanicId]\"), or a date-grain\n * term that buckets a date column.\n */\nexport type DimensionTerm = string | DateGrainDimension;\n\n/** The durable, data-free, PII-free query. */\nexport interface Binding {\n modelId?: string;\n /** Measure terms — catalog refs, inline aggregates, and/or dateDiff durations. Non-empty. */\n measures: MeasureTerm[];\n /** Dimension terms — field refs (PII ids, never names) and/or date-grain buckets. */\n dimensions?: DimensionTerm[];\n filters?: Filter[];\n /**\n * Optional. An entity localKey or \"total\" (never a column name). When omitted it\n * is derived engine-side: \"total\" for a dimension-less binding, else the first\n * dimension's entity. B3 checks it ∈ measure.validGrains.\n */\n grain?: string;\n topN?: TopN;\n}\n\n// ── Cross-dataset composite bindings (cross-dataset-links) ──────────────────\n\n/** One side of a composite panel: a role handle plus an ordinary Binding. */\nexport interface SourceBinding {\n /** Lowercase identifier, max 24 chars (e.g. \"purchases\"). */\n role: string;\n /** The sub-binding — the existing Binding shape VERBATIM, one model. */\n binding: Binding;\n /** Carried pass-through attributes of this side (engine-injected, ≤4). */\n carry?: CarryField[];\n}\n\n/**\n * One carried pass-through attribute of a source: a fieldRef in this side's\n * model that is single-valued per join key (verified engine-side at run time —\n * a violated declaration fails the query closed, never fans out the join).\n * The engine injects it into the side's grouping (never author it in\n * binding.dimensions) and the joined row exposes it under the bare alias `as`,\n * usable in output.groupBy / select / derived like a join-key alias.\n */\nexport interface CarryField {\n /** Field ref in this side's model, e.g. \"mechanic_profile[certification]\". */\n field: string;\n /** Bare joined-column alias (no brackets/dots). */\n as: string;\n}\n\n/** One visual-grain join pair: conformed dimension fieldRefs joined under `as`. */\nexport interface JoinOn {\n /** Field ref on the link's LEFT-side source, e.g. \"Date[Month]\". */\n left: string;\n /** Field ref on the link's RIGHT-side source. */\n right: string;\n /** Bare joined-column alias (no brackets/dots), e.g. \"Month\". */\n as: string;\n}\n\n/**\n * A closed-grammar expression over qualified refs (\"role.[Alias]\", \"[Alias]\",\n * bare join-key alias): + - * / ( ), numbers, datediff(day|week|month|year, a, b),\n * coalesce(...), abs(x), round(x, n). Parsed engine-side — never raw DAX/SQL.\n */\nexport interface DerivedTerm {\n expr: string;\n /** Result alias (no brackets); referenced downstream as \"[as]\". */\n as: string;\n}\n\nexport type CompositeSelectTerm =\n | { from: string; as: string }\n | { agg: 'sum' | 'avg' | 'min' | 'max' | 'count'; of: string; as: string };\n\n/**\n * The final in-engine projection: \"rows\" passes joined rows through the select\n * terms; \"aggregate\" groups by groupBy and folds aggregate terms. `derived`\n * terms are POST-aggregation expressions over the measure-shaped output\n * columns (\"[as]\"), evaluated after grouping and before topN — the home of\n * ratio-of-sums (weighted averages, margin %). Output column keys follow the\n * panel contract: measure-shaped terms come back keyed \"[as]\",\n * dimension-shaped pass-throughs bare \"as\".\n */\nexport interface CompositeOutput {\n mode: 'rows' | 'aggregate';\n groupBy?: string[];\n select: CompositeSelectTerm[];\n derived?: DerivedTerm[];\n topN?: TopN;\n}\n\n/**\n * A cross-dataset panel query (cross-dataset-links): two single-model\n * sub-bindings pushed down as ordinary aggregates, hash-joined in the engine\n * through a validated link, derived terms evaluated by the closed expression\n * grammar, then projected/re-aggregated. Entity grain joins per link key (the\n * engine injects the key columns — never author them); visual grain joins\n * visual-sized result sets on the conformed `on` dimensions. A source may\n * `carry` one-sided attributes that are single-valued per join key\n * (runtime-verified) to group the joined result by them.\n */\nexport interface CompositeBinding {\n /** Name of the bi_link (conformed entity) this panel joins through. */\n link: string;\n /** Exactly two sources. */\n sources: SourceBinding[];\n joinGrain: 'entity' | 'visual';\n /** Visual grain only; entity grain joins on the link's key pairs. */\n on?: JoinOn[];\n join?: 'inner' | 'left' | 'full';\n derived?: DerivedTerm[];\n output: CompositeOutput;\n}\n\n/** Last-mile PII re-hydration hook (resolved engine-side by B4). */\nexport interface Display {\n /** Field ref whose value fills the synthetic __label column. */\n labelField: string;\n piiTier?: PIITier;\n}\n\nexport interface ColorScale {\n scheme: { role: ColorRole };\n domainMid?: number;\n}\n\nexport interface Channel {\n /**\n * A measure ref (\"[Efficiency %]\", incl. an inline aggregate's \"[as]\" alias),\n * a field ref, or a synthetic: \"__label\" (rehydrated display name) or the fold\n * pair \"__measure\"/\"__value\" (the renderer unpivots the measure columns — the\n * way to compare several measures as categories in one chart).\n */\n field: string;\n type: ChannelType;\n sort?: ChannelSort;\n scale?: ColorScale;\n axis?: { title?: string; format?: string };\n format?: string;\n}\n\n/** Flat, fixed channel set — no layer/concat/facet (envelope's job) and no transform. */\nexport interface Encoding {\n x?: Channel;\n y?: Channel;\n color?: Channel;\n size?: Channel;\n theta?: Channel;\n row?: Channel;\n column?: Channel;\n}\n\nexport interface ChartViz { mark: ChartMark; encoding: Encoding; }\nexport interface KpiViz {\n format: string;\n delta?: { vs: 'previous_period' | 'prior_year' | 'none' };\n spark?: boolean;\n}\nexport interface GaugeViz {\n format: string;\n min: number;\n max: number;\n thresholds?: Array<{ value: number; role: ColorRole }>;\n}\nexport interface TableViz {\n columns?: Array<{ field: string; label?: string; format?: string; conditional?: boolean }>;\n sort?: { field: string; dir: SortDir };\n pageSize?: number;\n}\n\nexport type Viz = ChartViz | KpiViz | GaugeViz | TableViz;\n\n/** Cross-filter reservation (rung 3); runtime is the frontend (B6). */\nexport interface PanelInteraction {\n emits?: Array<{ param: string; from: 'x' | 'y' | 'color' | 'size' | 'theta' | 'row' | 'column' }>;\n}\n\ninterface PanelBase {\n id: string;\n title: string;\n /**\n * The single-model query. Exactly one of binding / compositeBinding is set\n * (schema oneOf) — a compositeBinding panel joins two models through a\n * validated cross-dataset link.\n */\n binding?: Binding;\n compositeBinding?: CompositeBinding;\n display?: Display;\n interaction?: PanelInteraction;\n}\n\n/** A chart panel: type is one of the curated marks; viz is the VL subset. */\nexport interface ChartPanel extends PanelBase { type: ChartMark; viz: ChartViz; }\nexport interface KpiPanel extends PanelBase { type: 'kpi'; viz: KpiViz; }\nexport interface GaugePanel extends PanelBase { type: 'gauge'; viz: GaugeViz; }\nexport interface TablePanel extends PanelBase { type: 'table'; viz: TableViz; }\n\n/** A panel — discriminated on `type` (mirrors the schema's if/then union). */\nexport type Panel = ChartPanel | KpiPanel | GaugePanel | TablePanel;\n","// Pure, dependency-free pre-validation for a Dashboard Spec — mirrors the cheap,\n// high-value checks the engine validator runs (cloud-agent\n// internal/chat/dashboardspec). This is for fast, friendly UX in the dashboard\n// editor (block B6): fail fast on obvious mistakes before a round-trip. It is\n// deliberately NOT a full JSON-Schema validator — the engine (santhosh-tekuri\n// against ./schema.json) is the authoritative safety net. Keep it consistent\n// with providers.ts's pure-validate philosophy.\n\nimport { DASHBOARD_SCHEMA_VERSION, type DashboardSpec, type PanelType } from './types.js';\n\n/** One structural problem, shaped like the engine's SpecError. */\nexport interface SpecError {\n /** JSON-pointer-ish path into the spec, e.g. \"/panels/0/binding\". */\n path: string;\n /** Short failing-rule tag, e.g. \"required\", \"enum\", \"integrity.layout\". */\n keyword: string;\n message: string;\n}\n\nexport interface ValidateResult {\n ok: boolean;\n errors: SpecError[];\n}\n\nconst PANEL_TYPES: ReadonlySet<string> = new Set<PanelType>([\n 'kpi', 'gauge', 'table', 'bar', 'line', 'area', 'point', 'arc', 'rule', 'tick', 'rect',\n]);\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction nonEmptyString(v: unknown): v is string {\n return typeof v === 'string' && v.length > 0;\n}\n\n/**\n * The result-column key a measure term produces: \"[Name]\" for a catalog ref\n * (string form), \"[as]\" for an inline aggregate (object form). Returns undefined\n * for a malformed term (the engine schema is the authority that rejects it).\n */\nfunction measureColumnKey(term: unknown): string | undefined {\n if (typeof term === 'string') return term;\n if (isObject(term) && nonEmptyString(term.as)) return `[${term.as}]`;\n return undefined;\n}\n\n/**\n * Validates the envelope + cross-reference integrity of a candidate spec. Returns\n * `{ ok, errors }`; `ok` is true only when `errors` is empty. Never throws.\n */\nexport function validateDashboardSpec(input: unknown): ValidateResult {\n const errors: SpecError[] = [];\n const push = (path: string, keyword: string, message: string) => errors.push({ path, keyword, message });\n\n if (!isObject(input)) {\n return { ok: false, errors: [{ path: '', keyword: 'type', message: 'spec must be a JSON object' }] };\n }\n\n if (input.schema !== DASHBOARD_SCHEMA_VERSION) {\n push('/schema', 'const', `schema must be \"${DASHBOARD_SCHEMA_VERSION}\"`);\n }\n if (!nonEmptyString(input.title)) {\n push('/title', 'required', 'title is required and must be a non-empty string');\n }\n if (!isObject(input.scope) || !nonEmptyString(input.scope.repoId)) {\n push('/scope', 'required', 'scope.repoId is required');\n }\n\n const layout = Array.isArray(input.layout) ? input.layout : [];\n if (layout.length === 0) {\n push('/layout', 'minItems', 'layout must have at least one entry');\n }\n const panels = Array.isArray(input.panels) ? input.panels : [];\n if (panels.length === 0) {\n push('/panels', 'minItems', 'panels must have at least one panel');\n }\n\n // Per-panel envelope checks.\n const panelIds = new Map<string, number>();\n panels.forEach((p, i) => {\n if (!isObject(p)) {\n push(`/panels/${i}`, 'type', 'panel must be an object');\n return;\n }\n if (!nonEmptyString(p.id)) {\n push(`/panels/${i}/id`, 'required', 'panel id is required');\n } else {\n if (panelIds.has(p.id)) push(`/panels/${i}/id`, 'integrity.duplicateId', `duplicate panel id \"${p.id}\"`);\n panelIds.set(p.id, i);\n }\n if (typeof p.type !== 'string' || !PANEL_TYPES.has(p.type)) {\n push(`/panels/${i}/type`, 'enum', `panel type \"${String(p.type)}\" is not a known type`);\n }\n if (!nonEmptyString(p.title)) push(`/panels/${i}/title`, 'required', 'panel title is required');\n if (!isObject(p.viz)) push(`/panels/${i}/viz`, 'required', 'panel viz is required');\n\n // Exactly one of binding / compositeBinding (the schema oneOf).\n const hasBinding = isObject(p.binding);\n const hasComposite = isObject(p.compositeBinding);\n if (!hasBinding && !hasComposite) {\n push(`/panels/${i}/binding`, 'required', 'panel needs a binding or a compositeBinding');\n } else if (hasBinding && hasComposite) {\n push(`/panels/${i}`, 'oneOf', 'panel must carry exactly one of binding / compositeBinding');\n }\n if (hasBinding) {\n validateBinding(p.binding as Record<string, unknown>, `/panels/${i}/binding`, push);\n }\n if (hasComposite) {\n validateComposite(p.compositeBinding as Record<string, unknown>, `/panels/${i}/compositeBinding`, push);\n }\n });\n\n // Integrity 1: id <-> layout 1:1.\n const layoutIds = new Map<string, number>();\n layout.forEach((l, i) => {\n if (!isObject(l) || !nonEmptyString(l.i)) {\n push(`/layout/${i}/i`, 'required', 'layout entry needs a string id \"i\"');\n return;\n }\n if (layoutIds.has(l.i)) push(`/layout/${i}/i`, 'integrity.duplicateLayout', `duplicate layout entry for id \"${l.i}\"`);\n layoutIds.set(l.i, i);\n if (!panelIds.has(l.i)) push(`/layout/${i}/i`, 'integrity.layout', `layout references id \"${l.i}\" with no matching panel`);\n });\n for (const [id, i] of panelIds) {\n if (!layoutIds.has(id)) push(`/panels/${i}`, 'integrity.layout', `panel \"${id}\" has no layout entry`);\n }\n\n // Integrity 2: param references resolve.\n const paramIds = new Set<string>();\n if (Array.isArray(input.parameters)) {\n for (const p of input.parameters) {\n if (isObject(p) && nonEmptyString(p.id)) paramIds.add(p.id);\n }\n }\n panels.forEach((p, pi) => {\n if (!isObject(p)) return;\n const b = isObject(p.binding) ? p.binding : undefined;\n const filters = b && Array.isArray(b.filters) ? b.filters : [];\n filters.forEach((f, fi) => {\n if (isObject(f) && typeof f.param === 'string' && f.param.length > 0 && !paramIds.has(f.param)) {\n push(`/panels/${pi}/binding/filters/${fi}/param`, 'integrity.paramRef', `filter references undeclared parameter \"${f.param}\"`);\n }\n });\n const cb = isObject(p.compositeBinding) ? p.compositeBinding : undefined;\n const sources = cb && Array.isArray(cb.sources) ? cb.sources : [];\n sources.forEach((s, si) => {\n if (!isObject(s) || !isObject(s.binding)) return;\n const sFilters = Array.isArray((s.binding as Record<string, unknown>).filters)\n ? ((s.binding as Record<string, unknown>).filters as unknown[])\n : [];\n sFilters.forEach((f, fi) => {\n if (isObject(f) && typeof f.param === 'string' && f.param.length > 0 && !paramIds.has(f.param)) {\n push(`/panels/${pi}/compositeBinding/sources/${si}/binding/filters/${fi}/param`, 'integrity.paramRef',\n `filter references undeclared parameter \"${f.param}\"`);\n }\n });\n });\n const inter = isObject(p.interaction) ? p.interaction : undefined;\n const emits = inter && Array.isArray(inter.emits) ? inter.emits : [];\n emits.forEach((e, ei) => {\n if (isObject(e) && typeof e.param === 'string' && e.param.length > 0 && !paramIds.has(e.param)) {\n push(`/panels/${pi}/interaction/emits/${ei}/param`, 'integrity.paramRef', `interaction emits undeclared parameter \"${e.param}\"`);\n }\n });\n });\n\n return { ok: errors.length === 0, errors };\n}\n\ntype PushFn = (path: string, keyword: string, message: string) => void;\n\n/** The shared single-model binding checks (plain panels and composite sources). */\nfunction validateBinding(b: Record<string, unknown>, base: string, push: PushFn): void {\n if (!Array.isArray(b.measures) || b.measures.length === 0) {\n push(`${base}/measures`, 'minItems', 'binding.measures must be a non-empty array');\n } else {\n // Integrity 3: measure-term result keys unique within a binding (a duplicate\n // measure ref or inline-aggregate alias would collide in the compiled output).\n const seenKeys = new Set<string>();\n b.measures.forEach((m, mi) => {\n const key = measureColumnKey(m);\n if (key === undefined) return; // malformed term; the engine schema rejects it\n const norm = key.toLowerCase();\n if (seenKeys.has(norm)) {\n push(`${base}/measures/${mi}`, 'integrity.duplicateMeasure',\n `measure term \"${key}\" duplicates an earlier term's result column in this binding`);\n }\n seenKeys.add(norm);\n });\n }\n // grain is OPTIONAL (WP3a): when present it must be a non-empty string, but an\n // omitted grain is valid and derived engine-side. A column-name grain is\n // normalized (not rejected) by the engine bind-check.\n if ('grain' in b && b.grain !== undefined && !nonEmptyString(b.grain)) {\n push(`${base}/grain`, 'type', 'binding.grain, when present, must be a non-empty string (an entity localKey or \"total\")');\n }\n}\n\n/**\n * The catalog-free compositeBinding checks — mirrors the engine's composite\n * integrity rules (roles distinct, 'on' iff visual grain, alias uniqueness,\n * output-mode coherence). Link existence, key fields, PII and the expression\n * grammar are engine-side.\n */\nfunction validateComposite(cb: Record<string, unknown>, base: string, push: PushFn): void {\n if (!nonEmptyString(cb.link)) {\n push(`${base}/link`, 'required', 'compositeBinding.link is required (the cross-dataset link name)');\n }\n const sources = Array.isArray(cb.sources) ? cb.sources : [];\n if (sources.length !== 2) {\n push(`${base}/sources`, 'minItems', 'compositeBinding needs exactly two sources');\n }\n const roles = new Set<string>();\n sources.forEach((s, si) => {\n if (!isObject(s)) {\n push(`${base}/sources/${si}`, 'type', 'source must be an object');\n return;\n }\n if (!nonEmptyString(s.role) || !/^[a-z][a-z0-9_]{0,23}$/.test(s.role)) {\n push(`${base}/sources/${si}/role`, 'pattern', 'source role must be a lowercase identifier (max 24 chars)');\n } else if (roles.has(s.role)) {\n push(`${base}/sources/${si}/role`, 'integrity.role', `source roles must be distinct (both \"${s.role}\")`);\n } else {\n roles.add(s.role);\n }\n if (!isObject(s.binding)) {\n push(`${base}/sources/${si}/binding`, 'required', 'source binding is required');\n return;\n }\n validateBinding(s.binding as Record<string, unknown>, `${base}/sources/${si}/binding`, push);\n if (cb.joinGrain === 'entity' && Array.isArray((s.binding as Record<string, unknown>).dimensions)\n && ((s.binding as Record<string, unknown>).dimensions as unknown[]).length > 0) {\n push(`${base}/sources/${si}/binding/dimensions`, 'integrity.joinOn',\n 'entity-grain sources must not author dimensions — the engine injects the link keys');\n }\n });\n\n const on = Array.isArray(cb.on) ? cb.on : [];\n if (cb.joinGrain === 'visual' && on.length === 0) {\n push(`${base}/on`, 'integrity.joinOn', 'joinGrain \"visual\" requires at least one on pair');\n } else if (cb.joinGrain === 'entity' && on.length > 0) {\n push(`${base}/on`, 'integrity.joinOn', 'joinGrain \"entity\" joins on the link\\'s key pairs — on must be empty');\n } else if (cb.joinGrain !== 'entity' && cb.joinGrain !== 'visual') {\n push(`${base}/joinGrain`, 'enum', 'joinGrain must be \"entity\" or \"visual\"');\n }\n if ('join' in cb && cb.join !== undefined && cb.join !== 'inner' && cb.join !== 'left' && cb.join !== 'full') {\n push(`${base}/join`, 'enum', 'join must be inner, left or full');\n }\n\n // Alias uniqueness across the joined-row namespace (on + carry + derived).\n const aliases = new Set<string>();\n on.forEach((o, oi) => {\n if (!isObject(o) || !nonEmptyString(o.as)) {\n push(`${base}/on/${oi}/as`, 'required', 'every on pair needs a bare alias \"as\"');\n return;\n }\n const norm = o.as.toLowerCase();\n if (aliases.has(norm)) push(`${base}/on/${oi}/as`, 'integrity.alias', `joined-column alias \"${o.as}\" is duplicated`);\n aliases.add(norm);\n });\n sources.forEach((s, si) => {\n if (!isObject(s)) return;\n const carry = Array.isArray(s.carry) ? s.carry : [];\n carry.forEach((c, ci) => {\n if (!isObject(c) || !nonEmptyString(c.as)) {\n push(`${base}/sources/${si}/carry/${ci}/as`, 'required', 'every carry field needs a bare alias \"as\"');\n return;\n }\n if (!nonEmptyString(c.field)) {\n push(`${base}/sources/${si}/carry/${ci}/field`, 'required', 'every carry field needs a field ref');\n }\n const norm = c.as.toLowerCase();\n if (aliases.has(norm)) push(`${base}/sources/${si}/carry/${ci}/as`, 'integrity.alias', `joined-column alias \"${c.as}\" is duplicated`);\n aliases.add(norm);\n });\n });\n const derived = Array.isArray(cb.derived) ? cb.derived : [];\n derived.forEach((d, di) => {\n if (!isObject(d) || !nonEmptyString(d.as)) {\n push(`${base}/derived/${di}/as`, 'required', 'every derived term needs an alias \"as\"');\n return;\n }\n if (!nonEmptyString(d.expr)) {\n push(`${base}/derived/${di}/expr`, 'required', 'every derived term needs an expr');\n }\n const norm = d.as.toLowerCase();\n if (aliases.has(norm)) push(`${base}/derived/${di}/as`, 'integrity.alias', `derived alias \"${d.as}\" duplicates a joined-column alias`);\n aliases.add(norm);\n });\n\n // Output coherence.\n const out = isObject(cb.output) ? cb.output : undefined;\n if (!out) {\n push(`${base}/output`, 'required', 'compositeBinding.output is required');\n return;\n }\n if (out.mode !== 'rows' && out.mode !== 'aggregate') {\n push(`${base}/output/mode`, 'enum', 'output.mode must be \"rows\" or \"aggregate\"');\n }\n if (Array.isArray(out.groupBy) && out.groupBy.length > 0 && out.mode !== 'aggregate') {\n push(`${base}/output/groupBy`, 'integrity.outputMode', 'output.groupBy requires output.mode=\"aggregate\"');\n }\n const select = Array.isArray(out.select) ? out.select : [];\n if (select.length === 0) {\n push(`${base}/output/select`, 'minItems', 'output.select must have at least one term');\n }\n const outAliases = new Set<string>();\n select.forEach((t, ti) => {\n if (!isObject(t) || !nonEmptyString(t.as)) {\n push(`${base}/output/select/${ti}/as`, 'required', 'every output term needs an alias \"as\"');\n return;\n }\n const norm = t.as.toLowerCase();\n if (outAliases.has(norm)) push(`${base}/output/select/${ti}/as`, 'integrity.alias', `output alias \"${t.as}\" is duplicated`);\n outAliases.add(norm);\n if (nonEmptyString(t.agg) && out.mode !== 'aggregate') {\n push(`${base}/output/select/${ti}`, 'integrity.outputMode', `output term \"${t.as}\" aggregates, which requires output.mode=\"aggregate\"`);\n }\n });\n\n // output.derived: post-aggregation terms share the output alias namespace\n // (expression parsing and ref resolution are engine-side).\n const outDerived = Array.isArray(out.derived) ? out.derived : [];\n outDerived.forEach((d, di) => {\n if (!isObject(d) || !nonEmptyString(d.as)) {\n push(`${base}/output/derived/${di}/as`, 'required', 'every output.derived term needs an alias \"as\"');\n return;\n }\n if (!nonEmptyString(d.expr)) {\n push(`${base}/output/derived/${di}/expr`, 'required', 'every output.derived term needs an expr');\n }\n const norm = d.as.toLowerCase();\n if (outAliases.has(norm)) push(`${base}/output/derived/${di}/as`, 'integrity.alias', `output.derived alias \"${d.as}\" duplicates an output column`);\n outAliases.add(norm);\n });\n}\n\n/** Convenience type guard: true when `input` passes pre-validation. */\nexport function isDashboardSpec(input: unknown): input is DashboardSpec {\n return validateDashboardSpec(input).ok;\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://flashback.tech/schemas/dashboard/v1\",\n \"title\": \"Flashback Dashboard Spec v1\",\n \"description\": \"The durable, data-free, PII-free Dashboard Spec authored by the BI agent's compose_dashboard tool. Each panel carries a binding (a parameterized query against one semantic model) OR a compositeBinding (two sub-bindings joined in-engine through a validated cross-dataset link), and a viz (how to draw the result). Data is transient; this spec is forever. Flat and recursion-free by construction so it is safe as a structured-output target and as a validation target (Visual-Dashboards design D1=B / D2=C).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"schema\", \"title\", \"scope\", \"layout\", \"panels\"],\n \"properties\": {\n \"schema\": {\n \"description\": \"Spec major-version discriminator. The validator binds to the major it embeds; forward/back compatibility is handled by upgraders-on-read, not by lax schemas (O7).\",\n \"const\": \"flashback.dashboard/v1\"\n },\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"description\": { \"type\": \"string\", \"maxLength\": 1000 },\n \"scope\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"repoId\"],\n \"properties\": {\n \"repoId\": { \"type\": \"string\", \"minLength\": 1 },\n \"defaultModelId\": {\n \"description\": \"Model used by any panel binding that omits modelId. Panels may bind different models (O3); a plain binding is one model — cross-model joins go through a compositeBinding over a validated link (cross-dataset-links).\",\n \"type\": \"string\"\n }\n }\n },\n \"parameters\": {\n \"description\": \"Dashboard-level interactive controls. binding.filters reference these by id, so one control re-filters every panel and re-population just re-reads them. Locked cross-filter-ready now; rung-2 (global controls) ships early.\",\n \"type\": \"array\",\n \"maxItems\": 24,\n \"items\": { \"$ref\": \"#/$defs/parameter\" }\n },\n \"layout\": {\n \"description\": \"react-grid-layout-shaped, 12-column grid. Persisted verbatim; user-editable. Every item.i must match a panels[].id (enforced by the Go integrity check, not the schema).\",\n \"type\": \"array\",\n \"minItems\": 1,\n \"maxItems\": 64,\n \"items\": { \"$ref\": \"#/$defs/layoutItem\" }\n },\n \"panels\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"maxItems\": 64,\n \"items\": { \"$ref\": \"#/$defs/panel\" }\n }\n },\n\n \"$defs\": {\n \"dateGrainRef\": {\n \"description\": \"A DATE-GRAIN dimension term: groups by a date column BUCKETED to a calendar unit instead of by its raw value. Use it whenever a panel is \\\"by month\\\"/\\\"by quarter\\\"/\\\"by year\\\" — grouping a raw date column buckets by every distinct timestamp, which draws as noise rather than a trend. The bucket is a COMPUTED column, so it comes back keyed \\\"[as]\\\" (like an inline aggregate, not like a plain dimension); viz.encoding fields and topN.by reference it exactly that way, and its channel type is \\\"temporal\\\". The alias may not contain brackets (un-injectable) and must be unique across the binding's dimensions AND measures (Go integrity check). B3 checks the column is actually a date.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"dateGrain\", \"as\"],\n \"properties\": {\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"dateGrain\": { \"enum\": [\"day\", \"week\", \"month\", \"quarter\", \"year\"] },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100, \"pattern\": \"^[^\\\\[\\\\]]+$\" }\n }\n },\n\n \"measureRef\": {\n \"description\": \"A measure reference, e.g. \\\"[Efficiency %]\\\". The bracketed measure name; existence is B3's catalog bind-check, not structural. The name may not contain a bracket ([ or ]) — this keeps the ref un-injectable into DAX (a bracket would break out of the [measure] identifier).\",\n \"type\": \"string\",\n \"pattern\": \"^\\\\[[^\\\\[\\\\]]+\\\\]$\"\n },\n \"fieldRef\": {\n \"description\": \"A field/dimension reference in DAX style, e.g. \\\"Mechanic[MechanicId]\\\". Entity = entity localKey (table name); Column = field column name. Neither segment may contain a bracket ([ or ]) — this makes the ref structurally un-injectable into DAX (a bracket would break out of the 'Entity'[Column] identifier and splice arbitrary columns/expressions). The synthetic \\\"__label\\\" (filled engine-side by B4) is also a legal viz field but is NOT a binding fieldRef.\",\n \"type\": \"string\",\n \"pattern\": \"^[^\\\\[\\\\]]+\\\\[[^\\\\[\\\\]]+\\\\]$\"\n },\n \"aggRef\": {\n \"description\": \"An INLINE AGGREGATE measure term, for models that define few or no catalog measures: aggregates a raw column with a constrained function. Compiles to AGG('Entity'[Column]) aliased as \\\"as\\\"; the result column comes back keyed \\\"[as]\\\", so viz.encoding fields and topN.by reference it exactly like a measureRef. Prefer a real catalog measure whenever one computes the value (bind-check doctrine). The alias may not contain brackets (un-injectable into DAX) and must be unique within the binding (Go integrity check).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"agg\", \"field\", \"as\"],\n \"properties\": {\n \"agg\": { \"enum\": [\"sum\", \"avg\", \"min\", \"max\", \"count\", \"distinctcount\"] },\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100, \"pattern\": \"^[^\\\\[\\\\]]+$\" }\n }\n },\n \"dateDiffRef\": {\n \"description\": \"Closed-form duration measure: AGG of DATEDIFF(from, to, unit) over the rows of the two columns' entity, skipping rows where either date is blank. from/to MUST be Date columns on the SAME entity. Referenced downstream as \\\"[as]\\\", exactly like an inline aggregate. Use for lead time / cycle time / aging — a row-level duration that a plain inline aggregate cannot express.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"agg\", \"dateDiff\", \"as\"],\n \"properties\": {\n \"agg\": { \"enum\": [\"avg\", \"min\", \"max\", \"sum\"] },\n \"dateDiff\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"from\", \"to\", \"unit\"],\n \"properties\": {\n \"from\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"to\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"unit\": { \"enum\": [\"day\", \"week\", \"month\", \"quarter\", \"year\"] },\n \"nonNegative\": { \"type\": \"boolean\", \"description\": \"Skip rows where to < from (data-entry noise) instead of letting them drag the aggregate.\" }\n }\n },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100, \"pattern\": \"^[^\\\\[\\\\]]+$\" }\n }\n },\n\n \"parameter\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"id\", \"type\", \"label\"],\n \"properties\": {\n \"id\": { \"type\": \"string\", \"minLength\": 1 },\n \"type\": { \"enum\": [\"daterange\", \"dimension\", \"scalar\"] },\n \"label\": { \"type\": \"string\", \"minLength\": 1 },\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"multi\": { \"type\": \"boolean\" },\n \"default\": {\n \"description\": \"Default control value. Shape depends on type: daterange => {relative} or {from,to}; dimension => null | string | array; scalar => a literal. Left unconstrained on purpose.\"\n }\n },\n \"allOf\": [\n {\n \"if\": { \"properties\": { \"type\": { \"const\": \"dimension\" } }, \"required\": [\"type\"] },\n \"then\": { \"required\": [\"field\"] }\n }\n ]\n },\n\n \"layoutItem\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"i\", \"x\", \"y\", \"w\", \"h\"],\n \"properties\": {\n \"i\": { \"type\": \"string\", \"minLength\": 1 },\n \"x\": { \"type\": \"integer\", \"minimum\": 0, \"maximum\": 11 },\n \"y\": { \"type\": \"integer\", \"minimum\": 0 },\n \"w\": { \"type\": \"integer\", \"minimum\": 1, \"maximum\": 12 },\n \"h\": { \"type\": \"integer\", \"minimum\": 1, \"maximum\": 64 }\n }\n },\n\n \"filter\": {\n \"oneOf\": [\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"param\"],\n \"properties\": { \"param\": { \"type\": \"string\", \"minLength\": 1 } }\n },\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"op\", \"value\"],\n \"properties\": {\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"op\": { \"enum\": [\"eq\", \"in\", \"gt\", \"gte\", \"lt\", \"lte\", \"between\"] },\n \"value\": {\n \"description\": \"Literal filter value. NOTE: a literal filter on a PII field is rejected by B4/B3 bind-check, not structurally.\"\n }\n }\n }\n ]\n },\n\n \"topN\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"by\", \"n\", \"dir\"],\n \"properties\": {\n \"by\": {\n \"description\": \"The ranking measure: a catalog measureRef, or an inline aggregate's alias in brackets (\\\"[Avg Worked Hours]\\\").\",\n \"$ref\": \"#/$defs/measureRef\"\n },\n \"n\": { \"type\": \"integer\", \"minimum\": 1, \"maximum\": 10000 },\n \"dir\": { \"enum\": [\"asc\", \"desc\"] }\n }\n },\n\n \"binding\": {\n \"description\": \"The durable, data-free, PII-free query. Shape only — DAX compilation (B2) and catalog bind-check (B3: existence, grain in validGrains, cardinality != 'empty', PII labelField) are downstream. A measure term is a catalog measureRef (\\\"[Efficiency %]\\\"), an inline aggRef ({agg, field, as}) for models without authored measures, or a dateDiffRef ({agg, dateDiff, as}) for a duration between two date columns (lead time / cycle time / aging). A dimension term is a plain fieldRef, or a dateGrainRef ({field, dateGrain, as}) that buckets a date column to a calendar unit.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"measures\"],\n \"properties\": {\n \"modelId\": { \"type\": \"string\" },\n \"measures\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": { \"oneOf\": [{ \"$ref\": \"#/$defs/measureRef\" }, { \"$ref\": \"#/$defs/aggRef\" }, { \"$ref\": \"#/$defs/dateDiffRef\" }] }\n },\n \"dimensions\": {\n \"type\": \"array\",\n \"items\": { \"oneOf\": [{ \"$ref\": \"#/$defs/fieldRef\" }, { \"$ref\": \"#/$defs/dateGrainRef\" }] }\n },\n \"filters\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/filter\" } },\n \"grain\": {\n \"description\": \"Optional. The grouping grain: an entity (table) name — an entity localKey — or the literal \\\"total\\\", NEVER a column name. When omitted, it is derived: \\\"total\\\" if the binding has no dimensions, else the first dimension's entity. When present but naming a dimension's column, B3 normalizes it to that dimension's entity. B3 checks grain is in the measure's validGrains (itself a list of localKeys + \\\"total\\\"). Grain is validated ONCE at authoring and trusted on every refresh (the runtime verifier ignores grain).\",\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"topN\": { \"$ref\": \"#/$defs/topN\" }\n }\n },\n\n \"qualifiedRef\": {\n \"description\": \"A joined-row column: 'role.[Alias]' (a source's measure / inline-agg result), '[Alias]' (a derived term), a join-key alias, or an on-pair alias. Bracket-free segments keep the ref structurally un-injectable, exactly like fieldRef.\",\n \"type\": \"string\",\n \"pattern\": \"^([a-z][a-z0-9_]{0,23}\\\\.)?(\\\\[[^\\\\[\\\\]]+\\\\]|[^\\\\[\\\\]\\\\.]+)$\"\n },\n\n \"sourceBinding\": {\n \"description\": \"One side of a composite panel: a role handle plus an ordinary single-model binding (the sub-binding is #/$defs/binding VERBATIM — pushed down and executed exactly like a plain panel's query). In entity grain the engine injects the link-key columns into the sub-binding's dimensions; they are never authored. 'carry' declares pass-through attributes of this side (also engine-injected, never authored).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"role\", \"binding\"],\n \"properties\": {\n \"role\": { \"type\": \"string\", \"pattern\": \"^[a-z][a-z0-9_]{0,23}$\" },\n \"binding\": { \"$ref\": \"#/$defs/binding\" },\n \"carry\": { \"type\": \"array\", \"maxItems\": 4, \"items\": { \"$ref\": \"#/$defs/carryField\" } }\n }\n },\n\n \"carryField\": {\n \"description\": \"One carried pass-through attribute of a source: a fieldRef in this side's model that is single-valued per join key (e.g. a category of the linked entity). The engine injects it into the side's grouping and VERIFIES the single-valued property at run time — a violated declaration fails the query closed, never fans out the join. The joined row exposes it under the bare alias 'as', usable in output.groupBy / select / derived like a join-key alias. On left/full joins, rows missing the carrying side group under a null (unknown) bucket.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"as\"],\n \"properties\": {\n \"field\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"pattern\": \"^[^\\\\[\\\\]\\\\.]+$\" }\n }\n },\n\n \"joinOn\": {\n \"description\": \"One visual-grain join pair: conformed dimension fieldRefs on the link's left/right side sources, joined under the bare alias 'as'.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"left\", \"right\", \"as\"],\n \"properties\": {\n \"left\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"right\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"pattern\": \"^[^\\\\[\\\\]\\\\.]+$\" }\n }\n },\n\n \"derivedTerm\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"expr\", \"as\"],\n \"properties\": {\n \"expr\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 500,\n \"description\": \"Constrained expression over qualified refs: + - * / ( ), numbers, datediff(day|week|month|year, a, b), coalesce(...), abs(x), round(x, n). Parsed by the engine's closed grammar — never raw DAX/SQL.\"\n },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100, \"pattern\": \"^[^\\\\[\\\\]]+$\" }\n }\n },\n\n \"compositeOutput\": {\n \"description\": \"The final in-engine projection: mode 'rows' passes joined rows through the select terms; mode 'aggregate' groups by groupBy and folds aggregate terms. 'derived' terms are POST-aggregation expressions over the measure-shaped output columns (\\\"[as]\\\"), evaluated after grouping and before topN — use for ratio-of-sums (weighted averages, margin %), which per-joined-row derived terms cannot express. Output column keys follow the panel contract: measure-shaped terms come back keyed \\\"[as]\\\", dimension-shaped pass-throughs bare \\\"as\\\".\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"mode\", \"select\"],\n \"properties\": {\n \"mode\": { \"enum\": [\"rows\", \"aggregate\"] },\n \"groupBy\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/qualifiedRef\" } },\n \"derived\": { \"type\": \"array\", \"maxItems\": 4, \"items\": { \"$ref\": \"#/$defs/derivedTerm\" } },\n \"select\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"oneOf\": [\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"from\", \"as\"],\n \"properties\": {\n \"from\": { \"$ref\": \"#/$defs/qualifiedRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100 }\n }\n },\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"agg\", \"of\", \"as\"],\n \"properties\": {\n \"agg\": { \"enum\": [\"sum\", \"avg\", \"min\", \"max\", \"count\"] },\n \"of\": { \"$ref\": \"#/$defs/qualifiedRef\" },\n \"as\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 100 }\n }\n }\n ]\n }\n },\n \"topN\": { \"$ref\": \"#/$defs/topN\" }\n }\n },\n\n \"compositeBinding\": {\n \"description\": \"A cross-dataset panel query (cross-dataset-links): two single-model sub-bindings pushed down as ordinary aggregates, hash-joined in the engine through a validated link ('link' names it), derived terms evaluated by the closed expression grammar, then projected/re-aggregated. Entity grain joins per link key (the engine injects the key columns); visual grain joins visual-sized result sets on conformed 'on' dimensions. A source may 'carry' one-sided attributes that are single-valued per join key (runtime-verified) to group the joined result by them. The join inputs are distinct-per-key by construction (verified at run time), so M:N fan-out is structurally absorbed.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"link\", \"sources\", \"joinGrain\", \"output\"],\n \"properties\": {\n \"link\": { \"type\": \"string\", \"minLength\": 1 },\n \"sources\": {\n \"type\": \"array\",\n \"minItems\": 2,\n \"maxItems\": 2,\n \"items\": { \"$ref\": \"#/$defs/sourceBinding\" }\n },\n \"joinGrain\": { \"enum\": [\"entity\", \"visual\"] },\n \"on\": { \"type\": \"array\", \"maxItems\": 4, \"items\": { \"$ref\": \"#/$defs/joinOn\" } },\n \"join\": { \"enum\": [\"inner\", \"left\", \"full\"] },\n \"derived\": { \"type\": \"array\", \"maxItems\": 8, \"items\": { \"$ref\": \"#/$defs/derivedTerm\" } },\n \"output\": { \"$ref\": \"#/$defs/compositeOutput\" }\n }\n },\n\n \"display\": {\n \"description\": \"The reserved last-mile PII re-hydration hook. B4 implements the two-query trick: it fills the synthetic __label column from labelField after the LLM is out of the loop. piiTier (a rehydration strategy) is distinct from B0's piiClass (a field classification).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"labelField\"],\n \"properties\": {\n \"labelField\": { \"$ref\": \"#/$defs/fieldRef\" },\n \"piiTier\": { \"enum\": [\"none\", \"rehydrate\"] }\n }\n },\n\n \"colorScale\": {\n \"description\": \"Semantic color contract (D6): the spec picks a role, never a raw hex or vendor palette. B6's theme module maps each role to an indigo-derived palette from the theme tokens (light + dark).\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"scheme\"],\n \"properties\": {\n \"scheme\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"role\"],\n \"properties\": { \"role\": { \"enum\": [\"sequential\", \"categorical\", \"diverging\", \"goodBad\"] } }\n },\n \"domainMid\": { \"type\": \"number\" }\n }\n },\n\n \"channel\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"type\"],\n \"properties\": {\n \"field\": {\n \"description\": \"A measureRef (\\\"[Efficiency %]\\\" — incl. an inline aggregate's \\\"[as]\\\" alias), a fieldRef, or a synthetic: \\\"__label\\\" (the rehydrated display name, B4), or the fold pair \\\"__measure\\\"/\\\"__value\\\" (the renderer unpivots the panel's measure columns into measure-name/measure-value rows — the way to compare several measures as categories in one chart, e.g. an arc of two averages).\",\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"type\": { \"enum\": [\"nominal\", \"quantitative\", \"temporal\", \"ordinal\"] },\n \"sort\": {\n \"anyOf\": [\n { \"enum\": [\"-x\", \"x\", \"-y\", \"y\", \"ascending\", \"descending\"] },\n { \"type\": \"null\" }\n ]\n },\n \"scale\": { \"$ref\": \"#/$defs/colorScale\" },\n \"axis\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"title\": { \"type\": \"string\" },\n \"format\": { \"type\": \"string\" }\n }\n },\n \"format\": { \"type\": \"string\" }\n }\n },\n\n \"encoding\": {\n \"description\": \"Flat, fixed channel set. No layer/concat/facet/repeat (multi-view is the envelope's job via panels[]+layout[]) and no transform/condition/expression/aggregate (anything computed is precomputed by the binding — the ONLY aggregation surface is the binding's measures). The one renderer-side reshape is the __measure/__value fold (a deterministic unpivot of the measure columns, not a computation). This flatness is what removes Vega-Lite's recursion.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"x\": { \"$ref\": \"#/$defs/channel\" },\n \"y\": { \"$ref\": \"#/$defs/channel\" },\n \"color\": { \"$ref\": \"#/$defs/channel\" },\n \"size\": { \"$ref\": \"#/$defs/channel\" },\n \"theta\": { \"$ref\": \"#/$defs/channel\" },\n \"row\": { \"$ref\": \"#/$defs/channel\" },\n \"column\": { \"$ref\": \"#/$defs/channel\" }\n }\n },\n\n \"chartViz\": {\n \"description\": \"The curated, recursion-stripped Vega-Lite subset for chart panels.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"mark\", \"encoding\"],\n \"properties\": {\n \"mark\": { \"enum\": [\"bar\", \"line\", \"area\", \"point\", \"arc\", \"rule\", \"tick\", \"rect\"] },\n \"encoding\": { \"$ref\": \"#/$defs/encoding\" }\n }\n },\n\n \"kpiViz\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"format\"],\n \"properties\": {\n \"format\": { \"type\": \"string\", \"minLength\": 1 },\n \"delta\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"vs\"],\n \"properties\": { \"vs\": { \"enum\": [\"previous_period\", \"prior_year\", \"none\"] } }\n },\n \"spark\": { \"type\": \"boolean\" }\n }\n },\n\n \"gaugeViz\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"format\", \"min\", \"max\"],\n \"properties\": {\n \"format\": { \"type\": \"string\", \"minLength\": 1 },\n \"min\": { \"type\": \"number\" },\n \"max\": { \"type\": \"number\" },\n \"thresholds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"value\", \"role\"],\n \"properties\": {\n \"value\": { \"type\": \"number\" },\n \"role\": { \"enum\": [\"sequential\", \"categorical\", \"diverging\", \"goodBad\"] }\n }\n }\n }\n }\n },\n\n \"tableViz\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"columns\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\"],\n \"properties\": {\n \"field\": { \"type\": \"string\", \"minLength\": 1 },\n \"label\": { \"type\": \"string\" },\n \"format\": { \"type\": \"string\" },\n \"conditional\": { \"type\": \"boolean\" }\n }\n }\n },\n \"sort\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"field\", \"dir\"],\n \"properties\": {\n \"field\": { \"type\": \"string\", \"minLength\": 1 },\n \"dir\": { \"enum\": [\"asc\", \"desc\"] }\n }\n },\n \"pageSize\": { \"type\": \"integer\", \"minimum\": 1, \"maximum\": 1000 }\n }\n },\n\n \"interaction\": {\n \"description\": \"Cross-filter reservation (interactivity rung 3). Reserved in the schema for forward-compat; the runtime (a click writes a param) is B6, not B1.\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"emits\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"param\", \"from\"],\n \"properties\": {\n \"param\": { \"type\": \"string\", \"minLength\": 1 },\n \"from\": { \"enum\": [\"x\", \"y\", \"color\", \"size\", \"theta\", \"row\", \"column\"] }\n }\n }\n }\n }\n },\n\n \"panel\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\"id\", \"type\", \"title\", \"viz\"],\n \"properties\": {\n \"id\": { \"type\": \"string\", \"minLength\": 1 },\n \"type\": { \"enum\": [\"kpi\", \"gauge\", \"table\", \"bar\", \"line\", \"area\", \"point\", \"arc\", \"rule\", \"tick\", \"rect\"] },\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"binding\": { \"$ref\": \"#/$defs/binding\" },\n \"compositeBinding\": { \"$ref\": \"#/$defs/compositeBinding\" },\n \"display\": { \"$ref\": \"#/$defs/display\" },\n \"viz\": { \"type\": \"object\" },\n \"interaction\": { \"$ref\": \"#/$defs/interaction\" }\n },\n \"oneOf\": [{ \"required\": [\"binding\"] }, { \"required\": [\"compositeBinding\"] }],\n \"allOf\": [\n {\n \"if\": { \"properties\": { \"type\": { \"const\": \"kpi\" } }, \"required\": [\"type\"] },\n \"then\": { \"properties\": { \"viz\": { \"$ref\": \"#/$defs/kpiViz\" } } }\n },\n {\n \"if\": { \"properties\": { \"type\": { \"const\": \"gauge\" } }, \"required\": [\"type\"] },\n \"then\": { \"properties\": { \"viz\": { \"$ref\": \"#/$defs/gaugeViz\" } } }\n },\n {\n \"if\": { \"properties\": { \"type\": { \"const\": \"table\" } }, \"required\": [\"type\"] },\n \"then\": { \"properties\": { \"viz\": { \"$ref\": \"#/$defs/tableViz\" } } }\n },\n {\n \"if\": {\n \"properties\": { \"type\": { \"enum\": [\"bar\", \"line\", \"area\", \"point\", \"arc\", \"rule\", \"tick\", \"rect\"] } },\n \"required\": [\"type\"]\n },\n \"then\": { \"properties\": { \"viz\": { \"$ref\": \"#/$defs/chartViz\" } } }\n }\n ]\n }\n }\n}\n","// The canonical Dashboard Spec JSON Schema, exposed as an importable object\n// (Visual-Dashboards block B1). The single source of truth is the engine file\n// cloud-agent/internal/chat/dashboardspec/schema/flashback.dashboard.v1.schema.json\n// mirrored into this package as ./schema.json (byte-identical). esbuild inlines\n// this JSON import into the published bundle, so consumers get the schema as a\n// plain object — feed it straight to a JSON-Schema validator (e.g. ajv) for full\n// client-side spec validation, with no asset loading or fetch.\n//\n// Note: validate.ts is the cheap, dependency-free pre-check; DASHBOARD_SCHEMA is\n// here for callers that want full-fidelity validation against the exact engine\n// schema. Both ultimately defer to the engine validator as the safety net.\nimport schemaJson from './schema.json';\n\n/** The flashback.dashboard/v1 JSON Schema (Draft 2020-12). ajv-ready. */\nexport const DASHBOARD_SCHEMA: Readonly<Record<string, unknown>> = schemaJson as Record<string, unknown>;\n"]}