@proteos/sdk 0.94.1 → 0.96.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +67 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +260 -9
- package/dist/index.d.ts +260 -9
- package/dist/index.js +67 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/auth/platform-entities.ts +3 -0
- package/src/enrichment/index.ts +51 -0
- package/src/enrichment/types.ts +154 -5
- package/src/index.ts +27 -0
- package/src/usage/index.ts +49 -0
- package/src/usage/types.ts +93 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/agents.ts","../src/agent/mcp-servers.ts","../src/agent/models.ts","../src/agent/prompts.ts","../src/agent/sessions.ts","../src/agent/skills.ts","../src/agent/tools.ts","../src/agent/toolsets.ts","../src/agent/session-types.ts","../src/agent/index.ts","../src/auth/me.ts","../src/auth/organizations.ts","../src/auth/profiles.ts","../src/auth/roles.ts","../src/errors.ts","../src/auth/shares.ts","../src/auth/teams.ts","../src/auth/user-profile-assignments.ts","../src/auth/user-role-assignments.ts","../src/auth/users.ts","../src/auth/platform-entities.ts","../src/auth/types.ts","../src/auth/index.ts","../src/http/query-params.ts","../src/types/options.ts","../src/client.ts","../src/connector/index.ts","../src/conversation/voice.ts","../src/conversation/types.ts","../src/conversation/index.ts","../src/data/entity-indexes.ts","../src/data/queries.ts","../src/data/record-drafts.ts","../src/data/records.ts","../src/data/types.ts","../src/data/index.ts","../src/discovery/index.ts","../src/enrichment/index.ts","../src/events/index.ts","../src/functions/actions.ts","../src/functions/types.ts","../src/functions/index.ts","../src/knowledge/graph.ts","../src/knowledge/labels.ts","../src/knowledge/links.ts","../src/knowledge/nodes.ts","../src/knowledge/record-links.ts","../src/knowledge/spaces.ts","../src/knowledge/whiteboard-templates.ts","../src/knowledge/types.ts","../src/knowledge/index.ts","../src/scheduling/index.ts","../src/storage/files.ts","../src/storage/index.ts","../src/workflow/executions.ts","../src/workflow/node-types.ts","../src/workflow/workflows.ts","../src/workflow/types.ts","../src/workflow/index.ts"],"names":["z","encode","WORKFLOWS_BASE_PATH"],"mappings":";;;;;;AAKA,IAAM,gBAAA,GAAmB,mBAAA;AAqBlB,IAAM,mBAAN,MAA+C;AAAA,EACpD,YAA6B,MAAA,EAAuB;AAAvB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAAwB;AAAA,EAAxB,MAAA;AAAA,EAE7B,IAAA,CAAK,OAAA,GAA6B,EAAC,EAA2C;AAC5E,IAAA,OAAO,IAAI,aAAa,CAAC,IAAA,KAAS,KAAK,QAAA,CAAS,IAAI,GAAG,OAAO,CAAA;AAAA,EAChE;AAAA,EAEA,MAAM,QAAA,CAAS,OAAA,GAA6B,EAAC,EAA+B;AAC1E,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,gBAAA,CAAoC,KAAA,EAAO,kBAAkB,OAAO,CAAA;AAAA,EACzF;AAAA,EAEA,MAAM,IAAI,GAAA,EAA6B;AACrC,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAe,KAAA,EAAO,GAAG,gBAAgB,CAAA,CAAA,EAAI,GAAG,CAAA,CAAE,CAAA;AAAA,EACvE;AAAA,EAEA,MAAM,OAAO,OAAA,EAA6C;AACxD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAe,MAAA,EAAQ,kBAAkB,OAAO,CAAA;AAAA,EACrE;AAAA,EAEA,MAAM,MAAA,CAAO,GAAA,EAAa,OAAA,EAA6C;AACrE,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAe,OAAA,EAAS,GAAG,gBAAgB,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,EAAI,OAAO,CAAA;AAAA,EAClF;AAAA,EAEA,MAAM,OAAO,GAAA,EAA4B;AACvC,IAAA,MAAM,IAAA,CAAK,OAAO,OAAA,CAAc,QAAA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AA;AAAA,EAC7E;AAAA,EAEA,MAAM,gBAAA,CACJ,GAAA,EACA,OAAA,GAAuB,EAAC,EACqB;AAC7C,IAAA,OAAO,KAAK,MAAA,CAAO,gBAAA;AAAA,MACjB,KAAA;AAAA,MACA,CAAA,EAAGA,oBAAmB,CAAA,CAAA,EAAI,GAAG,CAAA,SAAA,CAAA;AAAA,MAC7B;AAAA,KACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAA,CAAW,GAAA,EAAa,OAAA,EAA2C;AACvE,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,KAAA;AAAA,MACA,CAAA,EAAGA,oBAAmB,CAAA,CAAA,EAAI,GAAG,aAAa,OAAO,CAAA;AAAA,KACnD;AAAA,EACF;AAAA,EAEA,MAAM,cAAA,CAAe,GAAA,EAAa,OAAA,EAAoC;AACpE,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,MAAA;AAAA,MACA,CAAA,EAAGA,oBAAmB,CAAA,CAAA,EAAI,GAAG,aAAa,OAAO,CAAA,QAAA,CAAA;AAAA,MACjD;AAAC,KACH;AAAA,EACF;AACF,CAAA;;;ACjFO,IAAM,YAAA,GAAe;AASrB,IAAM,UAAA,GAAa;;;ACtDnB,IAAM,iBAAN,MAAqB;AAAA;AAAA,EAEjB,SAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,YAAY,MAAA,EAAuB;AACjC,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,mBAAA,CAAoB,MAAM,CAAA;AAC/C,IAAA,IAAA,CAAK,UAAA,GAAa,IAAI,oBAAA,CAAqB,MAAM,CAAA;AACjD,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,mBAAA,CAAoB,MAAM,CAAA;AAAA,EACjD;AACF","file":"index.js","sourcesContent":["import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type { Agent, CreateAgentRequest, ListAgentsOptions, UpdateAgentRequest } from './types.js'\n\nconst AGENTS_BASE_PATH = '/agents/v1/agents'\n\n/**\n * Service for managing Agents — configured personas (system prompt + model\n * config + the skills/tools/sub-agents they can use). Keyed by immutable `key`.\n */\nexport interface AgentService {\n /** Lists agents, auto-paginating. */\n list(options?: ListAgentsOptions): PageIterator<Agent, ListAgentsOptions>\n /** Fetches a single page of agents with pagination metadata. */\n listPage(options?: ListAgentsOptions): Promise<ListResult<Agent>>\n /** Gets a single agent by key. @throws {ProteosError} 404 if not found. */\n get(key: string): Promise<Agent>\n /** Creates a new agent. @throws {ProteosError} 400/409. */\n create(request: CreateAgentRequest): Promise<Agent>\n /** Patches an existing agent (partial). @throws {ProteosError} 404/400. */\n update(key: string, request: UpdateAgentRequest): Promise<Agent>\n /** Deletes an agent. @throws {ProteosError} 404 if not found. */\n delete(key: string): Promise<void>\n}\n\nexport class AgentServiceImpl implements AgentService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListAgentsOptions = {}): PageIterator<Agent, ListAgentsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListAgentsOptions = {}): Promise<ListResult<Agent>> {\n return this.client.requestWithQuery<ListResult<Agent>>('GET', AGENTS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Agent> {\n return this.client.request<Agent>('GET', `${AGENTS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreateAgentRequest): Promise<Agent> {\n return this.client.request<Agent>('POST', AGENTS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateAgentRequest): Promise<Agent> {\n return this.client.request<Agent>('PATCH', `${AGENTS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${AGENTS_BASE_PATH}/${key}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateMcpServerRequest,\n DependentAgent,\n DependentSyncResult,\n ListMcpServersOptions,\n McpConnectionStatus,\n McpServer,\n McpToolSummary,\n StartMcpOAuthResponse,\n UpdateMcpServerRequest,\n} from './types.js'\n\nconst MCP_SERVERS_BASE_PATH = '/agents/v1/mcp-servers'\n\n/**\n * Service for managing MCP Servers — the consumer-side registry of MCP servers\n * an org's agents can call (the source of `kind=mcp` tools). When `auth.is_secret`\n * is set, the token is redacted to `''` on read; send a new token only to change\n * it.\n */\nexport interface McpServerService {\n /** Lists MCP servers, auto-paginating. */\n list(options?: ListMcpServersOptions): PageIterator<McpServer, ListMcpServersOptions>\n /** Fetches a single page of MCP servers with pagination metadata. */\n listPage(options?: ListMcpServersOptions): Promise<ListResult<McpServer>>\n /** Gets a single MCP server by key (token redacted if secret). @throws {ProteosError} 404. */\n get(key: string): Promise<McpServer>\n /** Registers a new MCP server. @throws {ProteosError} 400/409. */\n create(request: CreateMcpServerRequest): Promise<McpServer>\n /** Patches an MCP server (partial). @throws {ProteosError} 404/400. */\n update(key: string, request: UpdateMcpServerRequest): Promise<McpServer>\n /** Deletes an MCP server. @throws {ProteosError} 404. */\n delete(key: string): Promise<void>\n /** Lists the live tools of a (connected) MCP server via tools/list. @throws {ProteosError} 404/502. */\n listTools(key: string): Promise<McpToolSummary[]>\n /** Reports a server's derived OAuth connection state. @throws {ProteosError} 404. */\n getConnectionStatus(key: string): Promise<McpConnectionStatus>\n /** Starts the OAuth connect flow; open the returned `authorization_url` in a popup. @throws {ProteosError} 400/404. */\n startOAuth(key: string): Promise<StartMcpOAuthResponse>\n /** Drops a server's stored OAuth tokens. @throws {ProteosError} 400/404. */\n disconnectOAuth(key: string): Promise<void>\n /**\n * Lists the agents referencing this MCP server, each stamped stale when the MCP server\n * changed after the agent's last successful runtime sync. @throws {ProteosError} 404.\n */\n listDependents(key: string): Promise<DependentAgent[]>\n /**\n * Re-syncs every STALE dependent agent onto the runtime (the one-click \"update\n * dependent agents\" action). Returns a per-agent result. @throws {ProteosError} 404.\n */\n syncDependents(key: string): Promise<DependentSyncResult[]>\n}\n\nexport class McpServerServiceImpl implements McpServerService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListMcpServersOptions = {}): PageIterator<McpServer, ListMcpServersOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListMcpServersOptions = {}): Promise<ListResult<McpServer>> {\n return this.client.requestWithQuery<ListResult<McpServer>>(\n 'GET',\n MCP_SERVERS_BASE_PATH,\n options,\n )\n }\n\n async get(key: string): Promise<McpServer> {\n return this.client.request<McpServer>('GET', `${MCP_SERVERS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreateMcpServerRequest): Promise<McpServer> {\n return this.client.request<McpServer>('POST', MCP_SERVERS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateMcpServerRequest): Promise<McpServer> {\n return this.client.request<McpServer>('PATCH', `${MCP_SERVERS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${MCP_SERVERS_BASE_PATH}/${key}`)\n }\n\n async listTools(key: string): Promise<McpToolSummary[]> {\n const response = await this.client.request<{ data: McpToolSummary[] }>(\n 'GET',\n `${MCP_SERVERS_BASE_PATH}/${key}/tools`,\n )\n return response.data\n }\n\n async getConnectionStatus(key: string): Promise<McpConnectionStatus> {\n const response = await this.client.request<{ data: McpConnectionStatus }>(\n 'GET',\n `${MCP_SERVERS_BASE_PATH}/${key}/connection`,\n )\n return response.data\n }\n\n async startOAuth(key: string): Promise<StartMcpOAuthResponse> {\n return this.client.request<StartMcpOAuthResponse>(\n 'POST',\n `${MCP_SERVERS_BASE_PATH}/${key}/oauth/connect`,\n )\n }\n\n async disconnectOAuth(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${MCP_SERVERS_BASE_PATH}/${key}/oauth/connect`)\n }\n async listDependents(key: string): Promise<DependentAgent[]> {\n const response = await this.client.request<{ data: DependentAgent[] }>(\n 'GET',\n `${MCP_SERVERS_BASE_PATH}/${key}/dependents`,\n )\n return response.data\n }\n\n async syncDependents(key: string): Promise<DependentSyncResult[]> {\n const response = await this.client.request<{ data: DependentSyncResult[] }>(\n 'POST',\n `${MCP_SERVERS_BASE_PATH}/${key}/dependents/sync`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n DecideRequest,\n DecisionQuestions,\n DecisionResult,\n GenerateRequest,\n GenerationResult,\n ModelInfo,\n} from './model-types.js'\n\nconst MODELS_BASE_PATH = '/agents/v1/models'\n\n/**\n * Service for the model catalog and the stateless model calls — one request in,\n * one reply out, no session, no event log:\n *\n * - `list` — the models an agent can be configured with. Needs `agents:read`.\n * - `generate` — free text or schema-constrained structured output from an LLM.\n * - `decide` — calibrated typed answers (boolean | choice | score) with\n * probabilities and confidence, for snap judgments inside code paths\n * (routing, triage, classification, gates). No prose comes back; compose the\n * answers in code and threshold on `confidence`.\n *\n * `generate` and `decide` need the `agent-sessions:write` permission.\n */\nexport interface ModelService {\n /**\n * Lists the models an agent can be configured with: those of the model\n * providers the service has credentials for, each provider's newest first.\n * `runtimes` says which agent runtimes can run a model.\n */\n list(): Promise<ModelInfo[]>\n /**\n * Runs a single model call and returns the assistant message.\n * @throws {ProteosError} 400 `invalid_generation_request` / `unsupported_file_type` /\n * `model_provider_rejected_request`; 429 `model_provider_rate_limited`;\n * 502 `model_provider_failed`.\n */\n generate(request: GenerateRequest): Promise<GenerationResult>\n /**\n * Answers typed questions about a text state with calibrated probabilities.\n * `answers` is typed from the `questions` you pass, so\n * `result.answers.topic.choice` narrows to the option names you declared.\n *\n * Semantic limits (option / level counts, empty questions, unknown model ids)\n * are the provider's and surface as `decision_provider_rejected_request` with\n * its message.\n * @throws {ProteosError} 400 `invalid_decision_request` (shape) /\n * `decision_provider_rejected_request` (provider rule); 429\n * `decision_provider_rate_limited`; 502 `decision_provider_failed` /\n * `decision_provider_invalid_response`; 503 `decision_provider_unavailable`\n * when the provider key is not configured.\n */\n decide<Questions extends DecisionQuestions>(\n request: DecideRequest<Questions>,\n ): Promise<DecisionResult<Questions>>\n}\n\nexport class ModelServiceImpl implements ModelService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<ModelInfo[]> {\n const response = await this.client.request<{ data: ModelInfo[] }>('GET', MODELS_BASE_PATH)\n return response.data\n }\n\n async generate(request: GenerateRequest): Promise<GenerationResult> {\n return this.client.request<GenerationResult>('POST', `${MODELS_BASE_PATH}/generate`, request)\n }\n\n async decide<Questions extends DecisionQuestions>(\n request: DecideRequest<Questions>,\n ): Promise<DecisionResult<Questions>> {\n return this.client.request<DecisionResult<Questions>>(\n 'POST',\n `${MODELS_BASE_PATH}/decide`,\n request,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreatePromptRequest,\n DependentAgent,\n DependentSyncResult,\n ListPromptsOptions,\n Prompt,\n PromptVersion,\n UpdatePromptRequest,\n} from './types.js'\n\nconst PROMPTS_BASE_PATH = '/agents/v1/prompts'\n\n/**\n * Service for managing Prompts — reusable, Liquid-templated instruction texts,\n * versioned like storage files. A `body` change on update forks a new immutable\n * version; metadata-only updates do not.\n */\nexport interface PromptService {\n /** Lists prompts, auto-paginating. */\n list(options?: ListPromptsOptions): PageIterator<Prompt, ListPromptsOptions>\n /** Fetches a single page of prompts with pagination metadata. */\n listPage(options?: ListPromptsOptions): Promise<ListResult<Prompt>>\n /** Gets a prompt (with its current version) by key. @throws {ProteosError} 404. */\n get(key: string): Promise<Prompt>\n /** Creates a new prompt with version 1. @throws {ProteosError} 400/409. */\n create(request: CreatePromptRequest): Promise<Prompt>\n /** Patches a prompt; a new `body` forks a version. @throws {ProteosError} 404/400. */\n update(key: string, request: UpdatePromptRequest): Promise<Prompt>\n /** Deletes a prompt and all its versions. @throws {ProteosError} 404. */\n delete(key: string): Promise<void>\n /** Lists all immutable versions of a prompt, newest first. */\n listVersions(key: string): Promise<PromptVersion[]>\n /** Gets a specific immutable version by number. @throws {ProteosError} 404. */\n getVersion(key: string, number: number): Promise<PromptVersion>\n /**\n * Lists the agents referencing this prompt, each stamped stale when the prompt\n * changed after the agent's last successful runtime sync. @throws {ProteosError} 404.\n */\n listDependents(key: string): Promise<DependentAgent[]>\n /**\n * Re-syncs every STALE dependent agent onto the runtime (the one-click \"update\n * dependent agents\" action). Returns a per-agent result. @throws {ProteosError} 404.\n */\n syncDependents(key: string): Promise<DependentSyncResult[]>\n}\n\nexport class PromptServiceImpl implements PromptService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListPromptsOptions = {}): PageIterator<Prompt, ListPromptsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListPromptsOptions = {}): Promise<ListResult<Prompt>> {\n return this.client.requestWithQuery<ListResult<Prompt>>('GET', PROMPTS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Prompt> {\n return this.client.request<Prompt>('GET', `${PROMPTS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreatePromptRequest): Promise<Prompt> {\n return this.client.request<Prompt>('POST', PROMPTS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdatePromptRequest): Promise<Prompt> {\n return this.client.request<Prompt>('PATCH', `${PROMPTS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${PROMPTS_BASE_PATH}/${key}`)\n }\n\n async listVersions(key: string): Promise<PromptVersion[]> {\n // The versions endpoint wraps in `{ data }` (no pagination meta).\n const response = await this.client.request<{ data: PromptVersion[] }>(\n 'GET',\n `${PROMPTS_BASE_PATH}/${key}/versions`,\n )\n return response.data\n }\n\n async getVersion(key: string, number: number): Promise<PromptVersion> {\n return this.client.request<PromptVersion>(\n 'GET',\n `${PROMPTS_BASE_PATH}/${key}/versions/${number}`,\n )\n }\n async listDependents(key: string): Promise<DependentAgent[]> {\n const response = await this.client.request<{ data: DependentAgent[] }>(\n 'GET',\n `${PROMPTS_BASE_PATH}/${key}/dependents`,\n )\n return response.data\n }\n\n async syncDependents(key: string): Promise<DependentSyncResult[]> {\n const response = await this.client.request<{ data: DependentSyncResult[] }>(\n 'POST',\n `${PROMPTS_BASE_PATH}/${key}/dependents/sync`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type { RequestOptions } from '../types/options.js'\nimport type {\n AppendEventRequest,\n AppendSpeechRequest,\n ClientToolSchema,\n ContentBlock,\n CreateSessionRequest,\n EndVoiceRequest,\n FileBlock,\n ListSessionsOptions,\n ResultBlock,\n Session,\n SessionDeltaEntry,\n SessionDeltaStreamOptions,\n SessionEvent,\n SessionEventsOptions,\n SessionPreview,\n SessionStreamOptions,\n StartVoiceRequest,\n StartVoiceResponse,\n TransferVoiceRequest,\n TransferVoiceResponse,\n Turn,\n VoiceSession,\n} from './session-types.js'\n\nconst SESSIONS_BASE_PATH = '/agents/v1/sessions'\n\n/**\n * Service for managing agent Sessions — a conversation with a configured Agent,\n * backed by an append-only event log. Covers the full agent-service session\n * surface: CRUD, the durable event history, posting client events, the derived\n * turns projection, and the live SSE stream.\n */\nexport interface SessionService {\n /** Lists sessions, auto-paginating. */\n list(options?: ListSessionsOptions): PageIterator<Session, ListSessionsOptions>\n /** Fetches a single page of sessions with pagination metadata. */\n listPage(options?: ListSessionsOptions): Promise<ListResult<Session>>\n /** Gets a single session by id. @throws {ProteosError} 404 if not found. */\n get(id: string): Promise<Session>\n /** Opens a new session against a configured agent. @throws {ProteosError} 400. */\n create(request: CreateSessionRequest): Promise<Session>\n\n /**\n * Reads a page of the durable event log (Postgres), a forward `after_seq`\n * cursor ordered ascending by default. The live channel is {@link stream}.\n */\n events(id: string, options?: SessionEventsOptions): Promise<SessionEvent[]>\n /** Posts a client (`user.*`) event onto a session. @throws {ProteosError} 400/409. */\n appendEvent(id: string, request: AppendEventRequest): Promise<SessionEvent>\n /** The server-side `GroupByTurn` projection of the full event log. */\n turns(id: string): Promise<Turn[]>\n\n /**\n * Live-tails the session's event stream over SSE, yielding each\n * {@link SessionEvent} as it arrives. Replays from `afterSeq` (exclusive) then\n * follows live; reconnects resume gap-free. Runs until the `AbortSignal` fires.\n */\n stream(id: string, options?: SessionStreamOptions): AsyncGenerator<SessionEvent, void, unknown>\n /**\n * Live-tails the session's delta channel over SSE: every whole event\n * {@link stream} carries, and between them the chunk frames of the message,\n * reasoning or tool call the agent is writing — what a chat renders from while\n * a reply is in progress. Replays from `after` (exclusive) then follows live;\n * reconnects resume from the last entry received. Runs until the `AbortSignal`\n * fires. Tell the two kinds of entry apart with `isDeltaFrame`.\n */\n streamDelta(\n id: string,\n options?: SessionDeltaStreamOptions,\n ): AsyncGenerator<SessionDeltaEntry, void, unknown>\n\n /**\n * Convenience: appends a `user.message` with a single text block. Pass\n * `turnId` (a UUID) to supply the turn's id so the caller can render the\n * message optimistically under an id matching the echoed event.\n */\n sendMessage(id: string, text: string, turnId?: string): Promise<SessionEvent>\n /**\n * Convenience: appends a `user.message` built from optional text and file\n * attachments. Each {@link FileBlock} carries the storage-service `file_id`; the\n * backend uploads it to the model provider and mounts it into the agent's sandbox\n * at send time. Pass `turnId` (a UUID) for optimistic rendering. At least one of\n * `text` / `files` should be present. `context` rides the payload for the model\n * only (see {@link UserMessagePayload.context}). `clientTools` attaches the\n * sending surface's client tools to a session it did not create (see\n * {@link AppendEventRequest.client_tools}). A message to a session whose turn\n * runs is queued for the model; `rejectIfRunning` asks for the 409 instead (see\n * {@link AppendEventRequest.reject_if_running}).\n */\n sendUserMessage(\n id: string,\n input: {\n text?: string\n files?: FileBlock[]\n turnId?: string\n context?: string\n clientTools?: ClientToolSchema[]\n rejectIfRunning?: boolean\n },\n ): Promise<SessionEvent>\n /** Convenience: appends a `user.interrupt` to halt the running turn. */\n interrupt(id: string): Promise<SessionEvent>\n /**\n * Ends the session (`status: 'ended'`). A running turn is interrupted first and\n * the session ends once it has closed, so the returned session can still read\n * `running`. The next `user.message` reopens an ended session.\n */\n end(id: string): Promise<Session>\n /**\n * Makes the live preview of what the session's agent builds in its sandbox\n * reachable for the caller's browser and returns where it is. Starts the\n * session's sandbox when it is stopped; every call returns a new address.\n * Only the person who started the session may call it.\n * @throws {ProteosError} 400 `session_preview_unavailable` for a session\n * that is not on the `sandbox` runtime; 403 `sandbox_session_owner_only`.\n */\n openPreview(id: string): Promise<SessionPreview>\n /**\n * Convenience: appends a `user.tool_result` answering a client tool the agent\n * called (an `agent.tool_use` with `tool_kind: 'client'`). `toolUseId` is that\n * tool-use event's id (carried in the idle event's `event_ids`); the backend\n * relays the result to Anthropic as a `user.custom_tool_result` to resume the turn.\n * `outcome` defaults to `'success'`.\n */\n submitToolResult(\n id: string,\n input: { toolUseId: string; result: ResultBlock[]; outcome?: 'success' | 'error' },\n ): Promise<SessionEvent>\n\n /**\n * Enters voice on a session: sends the WebRTC offer of the page's peer\n * connection and returns the voice provider's answer, so the page never holds\n * the provider's key. The page drives the voice session from then on, reports\n * what is said with {@link appendSpeech}, and leaves with {@link endVoice}. A\n * voice session still active on the session is ended first.\n * @throws {ProteosError} 409 `voice_not_supported` when the session cannot be\n * talked to by voice; 501 `voice_disabled`; 502 `voice_provider_failed`.\n */\n startVoice(id: string, request: StartVoiceRequest): Promise<StartVoiceResponse>\n /**\n * Moves the session's active voice session to a session it delegated to, or\n * to the one that delegated to it: the person was handed over and talks to\n * that session's agent from here on. The page keeps its connection to the\n * voice provider and reports to the target session from then on.\n * @throws {ProteosError} 400 `invalid_voice_request` when the target is\n * neither; 409 `voice_not_supported` when the target is over; 409\n * `voice_session_not_active`.\n */\n transferVoice(id: string, request: TransferVoiceRequest): Promise<TransferVoiceResponse>\n /**\n * Reports what was said in the session's active voice session and returns the\n * events written. With `starts_turn` the last of them is the\n * `user.voice_request` that starts a turn.\n * @throws {ProteosError} 409 `voice_session_not_active`.\n */\n appendSpeech(\n id: string,\n request: AppendSpeechRequest,\n requestOptions?: RequestOptions,\n ): Promise<SessionEvent[]>\n /**\n * Leaves voice. Closing the connection to the voice provider is the page's job.\n * A page that is being closed passes `keepalive` so its last report and its\n * end still arrive.\n * @throws {ProteosError} 409 `voice_session_not_active`.\n */\n endVoice(\n id: string,\n request: EndVoiceRequest,\n requestOptions?: RequestOptions,\n ): Promise<VoiceSession>\n /**\n * The voice provider's recording of an ended voice session of the session, for\n * a session created with `is_voice_recorded`: a WAV file (16-bit PCM, stereo,\n * the person on the left channel and the voice assistant on the right). The\n * ids of a session's voice sessions are in its `session.voice_started` and\n * `session.voice_ended` events. `options.timeout` covers reading the whole\n * file, so raise it for a long recording.\n * @throws {ProteosError} 404 `voice_recording_not_found` when the voice session\n * is not one of this session or was not recorded; 409\n * `voice_recording_not_ready` while the voice session is active or the provider\n * does not have the recording yet (ask again).\n */\n getVoiceRecording(\n id: string,\n voiceSessionId: string,\n requestOptions?: RequestOptions,\n ): Promise<Blob>\n}\n\nexport class SessionServiceImpl implements SessionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListSessionsOptions = {}): PageIterator<Session, ListSessionsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListSessionsOptions = {}): Promise<ListResult<Session>> {\n // The API takes several statuses as one comma-separated value, not as a\n // repeated parameter.\n const query = Array.isArray(options.status)\n ? { ...options, status: options.status.join(',') }\n : options\n return this.client.requestWithQuery<ListResult<Session>>('GET', SESSIONS_BASE_PATH, query)\n }\n\n async get(id: string): Promise<Session> {\n return this.client.request<Session>('GET', `${SESSIONS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateSessionRequest): Promise<Session> {\n return this.client.request<Session>('POST', SESSIONS_BASE_PATH, request)\n }\n\n async events(id: string, options: SessionEventsOptions = {}): Promise<SessionEvent[]> {\n // The backend reads `types` as a single comma-separated query param (a string\n // it splits into a `type IN (...)` filter), so join the array rather than\n // letting the serializer emit repeated `types=` params.\n const { types, ...rest } = options\n const query = {\n ...rest,\n ...(types && types.length > 0 ? { types: types.join(',') } : {}),\n }\n const response = await this.client.requestWithQuery<{ data: SessionEvent[] }>(\n 'GET',\n `${SESSIONS_BASE_PATH}/${id}/events`,\n query,\n )\n return response.data ?? []\n }\n\n async appendEvent(id: string, request: AppendEventRequest): Promise<SessionEvent> {\n return this.client.request<SessionEvent>('POST', `${SESSIONS_BASE_PATH}/${id}/events`, request)\n }\n\n async turns(id: string): Promise<Turn[]> {\n const response = await this.client.request<{ data: Turn[] }>(\n 'GET',\n `${SESSIONS_BASE_PATH}/${id}/turns`,\n )\n return response.data ?? []\n }\n\n async *stream(\n id: string,\n options: SessionStreamOptions = {},\n ): AsyncGenerator<SessionEvent, void, unknown> {\n const query = options.afterSeq ? `?after_seq=${options.afterSeq}` : ''\n const path = `${SESSIONS_BASE_PATH}/${id}/events/stream${query}`\n const streamOptions = options.signal ? { signal: options.signal } : {}\n for await (const frame of this.client.streamEvents(path, streamOptions)) {\n const event = parseEvent(frame.data)\n if (event) yield event\n }\n }\n\n async *streamDelta(\n id: string,\n options: SessionDeltaStreamOptions = {},\n ): AsyncGenerator<SessionDeltaEntry, void, unknown> {\n const after = options.after === undefined || options.after === 0 ? '' : String(options.after)\n const query = after ? `?after_seq=${encodeURIComponent(after)}` : ''\n const path = `${SESSIONS_BASE_PATH}/${id}/events/delta${query}`\n const streamOptions = options.signal ? { signal: options.signal } : {}\n for await (const frame of this.client.streamEvents(path, streamOptions)) {\n const event = parseEvent(frame.data) as SessionDeltaEntry['event'] | null\n if (event && frame.id) yield { position: frame.id, event }\n }\n }\n\n async sendMessage(id: string, text: string, turnId?: string): Promise<SessionEvent> {\n return this.sendUserMessage(id, { text, ...(turnId ? { turnId } : {}) })\n }\n\n async sendUserMessage(\n id: string,\n input: {\n text?: string\n files?: FileBlock[]\n turnId?: string\n context?: string\n clientTools?: ClientToolSchema[]\n rejectIfRunning?: boolean\n },\n ): Promise<SessionEvent> {\n const content: ContentBlock[] = []\n const text = input.text?.trim()\n if (text) content.push({ type: 'text', text })\n for (const file of input.files ?? []) {\n content.push({ type: 'file', ...file })\n }\n const context = input.context?.trim()\n return this.appendEvent(id, {\n type: 'user.message',\n ...(input.turnId ? { turn_id: input.turnId } : {}),\n payload: { content, ...(context ? { context } : {}) },\n ...(input.clientTools?.length ? { client_tools: input.clientTools } : {}),\n ...(input.rejectIfRunning ? { reject_if_running: true } : {}),\n })\n }\n\n async interrupt(id: string): Promise<SessionEvent> {\n return this.appendEvent(id, { type: 'user.interrupt' })\n }\n\n async end(id: string): Promise<Session> {\n return this.client.request<Session>('POST', `${SESSIONS_BASE_PATH}/${id}/end`)\n }\n\n async openPreview(id: string): Promise<SessionPreview> {\n return this.client.request<SessionPreview>('POST', `${SESSIONS_BASE_PATH}/${id}/preview`)\n }\n\n async submitToolResult(\n id: string,\n input: { toolUseId: string; result: ResultBlock[]; outcome?: 'success' | 'error' },\n ): Promise<SessionEvent> {\n return this.appendEvent(id, {\n type: 'user.tool_result',\n payload: {\n tool_use_id: input.toolUseId,\n result: input.result,\n outcome: input.outcome ?? 'success',\n },\n })\n }\n\n async startVoice(id: string, request: StartVoiceRequest): Promise<StartVoiceResponse> {\n return this.client.request<StartVoiceResponse>(\n 'POST',\n `${SESSIONS_BASE_PATH}/${id}/voice`,\n request,\n )\n }\n\n async transferVoice(id: string, request: TransferVoiceRequest): Promise<TransferVoiceResponse> {\n return this.client.request<TransferVoiceResponse>(\n 'POST',\n `${SESSIONS_BASE_PATH}/${id}/voice/transfer`,\n request,\n )\n }\n\n async appendSpeech(\n id: string,\n request: AppendSpeechRequest,\n requestOptions?: RequestOptions,\n ): Promise<SessionEvent[]> {\n const response = await this.client.request<{ data: SessionEvent[] }>(\n 'POST',\n `${SESSIONS_BASE_PATH}/${id}/voice/speech`,\n request,\n requestOptions,\n )\n return response.data\n }\n\n async endVoice(\n id: string,\n request: EndVoiceRequest,\n requestOptions?: RequestOptions,\n ): Promise<VoiceSession> {\n return this.client.request<VoiceSession>(\n 'DELETE',\n `${SESSIONS_BASE_PATH}/${id}/voice`,\n request,\n requestOptions,\n )\n }\n\n async getVoiceRecording(\n id: string,\n voiceSessionId: string,\n requestOptions?: RequestOptions,\n ): Promise<Blob> {\n const { response } = await this.client.requestRaw(\n 'GET',\n `${SESSIONS_BASE_PATH}/${id}/voice/${voiceSessionId}/recording`,\n undefined,\n requestOptions,\n )\n return await response.blob()\n }\n}\n\n/**\n * Parses one SSE frame's `data` into a SessionEvent, returning null for an empty\n * or unparseable frame — a single bad frame is skipped, not fatal to the stream.\n */\nfunction parseEvent(data: string): SessionEvent | null {\n if (!data) return null\n try {\n return JSON.parse(data) as SessionEvent\n } catch {\n return null\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n DependentAgent,\n DependentSyncResult,\n ListSkillsOptions,\n Skill,\n SkillVersion,\n} from './types.js'\n\nconst SKILLS_BASE_PATH = '/agents/v1/skills'\n\n/**\n * Service for managing Skills — versioned bundles of instructions + files in the\n * Anthropic Agent-Skills shape. Skills are created and updated only via\n * {@link SkillService.deploy} (a multipart bundle upload); there is no JSON\n * create/update.\n */\nexport interface SkillService {\n /** Lists skills, auto-paginating. */\n list(options?: ListSkillsOptions): PageIterator<Skill, ListSkillsOptions>\n /** Fetches a single page of skills with pagination metadata. */\n listPage(options?: ListSkillsOptions): Promise<ListResult<Skill>>\n /** Gets a skill (with its current version + bundle pin) by key. @throws {ProteosError} 404. */\n get(key: string): Promise<Skill>\n /**\n * Deploys a skill bundle (a `.tar.gz` containing `SKILL.md` at the root plus\n * supporting files). The skill's key — its canonical identifier — is read\n * from the bundle's `SKILL.md` frontmatter `name`, so no key is supplied here.\n * Creates the skill on first deploy and a new immutable version each time.\n *\n * @param bundle - The `.tar.gz` bundle bytes.\n * @param options.displayName - Optional human-readable display name.\n * @param options.moduleSlug - Optional owning module slug (tags the skill so it\n * can be filtered + round-tripped by module). Empty for a standalone deploy.\n */\n deploy(\n bundle: Blob | File,\n options?: { displayName?: string; moduleSlug?: string },\n ): Promise<Skill>\n /** Deletes a skill and all its versions. @throws {ProteosError} 404. */\n delete(key: string): Promise<void>\n /** Lists all immutable versions of a skill, newest first. */\n listVersions(key: string): Promise<SkillVersion[]>\n /** Gets a specific immutable version by number. @throws {ProteosError} 404. */\n getVersion(key: string, number: number): Promise<SkillVersion>\n /**\n * Lists the agents referencing this skill, each stamped stale when the skill\n * changed after the agent's last successful runtime sync. @throws {ProteosError} 404.\n */\n listDependents(key: string): Promise<DependentAgent[]>\n /**\n * Re-syncs every STALE dependent agent onto the runtime (the one-click \"update\n * dependent agents\" action). Returns a per-agent result. @throws {ProteosError} 404.\n */\n syncDependents(key: string): Promise<DependentSyncResult[]>\n}\n\nexport class SkillServiceImpl implements SkillService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListSkillsOptions = {}): PageIterator<Skill, ListSkillsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListSkillsOptions = {}): Promise<ListResult<Skill>> {\n return this.client.requestWithQuery<ListResult<Skill>>('GET', SKILLS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Skill> {\n return this.client.request<Skill>('GET', `${SKILLS_BASE_PATH}/${key}`)\n }\n\n async deploy(\n bundle: Blob | File,\n options?: { displayName?: string; moduleSlug?: string },\n ): Promise<Skill> {\n const formData = new FormData()\n const filename = bundle instanceof File ? bundle.name : 'skill.tar.gz'\n formData.append('bundle', bundle, filename)\n if (options?.displayName) {\n formData.append('display_name', options.displayName)\n }\n if (options?.moduleSlug) {\n formData.append('module_slug', options.moduleSlug)\n }\n // Returns a bare Skill (no `{ data }` envelope). The key is derived from the\n // bundle's SKILL.md frontmatter server-side.\n return this.client.requestMultipart<Skill>('POST', `${SKILLS_BASE_PATH}/deploy`, formData)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${SKILLS_BASE_PATH}/${key}`)\n }\n\n async listVersions(key: string): Promise<SkillVersion[]> {\n const response = await this.client.request<{ data: SkillVersion[] }>(\n 'GET',\n `${SKILLS_BASE_PATH}/${key}/versions`,\n )\n return response.data\n }\n\n async getVersion(key: string, number: number): Promise<SkillVersion> {\n return this.client.request<SkillVersion>('GET', `${SKILLS_BASE_PATH}/${key}/versions/${number}`)\n }\n async listDependents(key: string): Promise<DependentAgent[]> {\n const response = await this.client.request<{ data: DependentAgent[] }>(\n 'GET',\n `${SKILLS_BASE_PATH}/${key}/dependents`,\n )\n return response.data\n }\n\n async syncDependents(key: string): Promise<DependentSyncResult[]> {\n const response = await this.client.request<{ data: DependentSyncResult[] }>(\n 'POST',\n `${SKILLS_BASE_PATH}/${key}/dependents/sync`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateToolRequest,\n DependentAgent,\n DependentSyncResult,\n ListToolsOptions,\n Tool,\n UpdateToolRequest,\n} from './types.js'\n\nconst TOOLS_BASE_PATH = '/agents/v1/tools'\n\n/**\n * Service for managing Tools — thin registry entries over one of three binding\n * sources (action / mcp / client). `update` fully replaces the definition.\n */\nexport interface ToolService {\n /** Lists tools, auto-paginating. Filterable by `kind`. */\n list(options?: ListToolsOptions): PageIterator<Tool, ListToolsOptions>\n /** Fetches a single page of tools with pagination metadata. */\n listPage(options?: ListToolsOptions): Promise<ListResult<Tool>>\n /** Gets a single tool by key. @throws {ProteosError} 404. */\n get(key: string): Promise<Tool>\n /** Creates a new tool. @throws {ProteosError} 400/409. */\n create(request: CreateToolRequest): Promise<Tool>\n /** Fully replaces a tool's definition. @throws {ProteosError} 404/400. */\n update(key: string, request: UpdateToolRequest): Promise<Tool>\n /** Deletes a tool. @throws {ProteosError} 404. */\n delete(key: string): Promise<void>\n /**\n * Lists the agents referencing this tool, each stamped stale when the tool\n * changed after the agent's last successful runtime sync. @throws {ProteosError} 404.\n */\n listDependents(key: string): Promise<DependentAgent[]>\n /**\n * Re-syncs every STALE dependent agent onto the runtime (the one-click \"update\n * dependent agents\" action). Returns a per-agent result. @throws {ProteosError} 404.\n */\n syncDependents(key: string): Promise<DependentSyncResult[]>\n}\n\nexport class ToolServiceImpl implements ToolService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListToolsOptions = {}): PageIterator<Tool, ListToolsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListToolsOptions = {}): Promise<ListResult<Tool>> {\n return this.client.requestWithQuery<ListResult<Tool>>('GET', TOOLS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Tool> {\n return this.client.request<Tool>('GET', `${TOOLS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreateToolRequest): Promise<Tool> {\n return this.client.request<Tool>('POST', TOOLS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateToolRequest): Promise<Tool> {\n return this.client.request<Tool>('PATCH', `${TOOLS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${TOOLS_BASE_PATH}/${key}`)\n }\n async listDependents(key: string): Promise<DependentAgent[]> {\n const response = await this.client.request<{ data: DependentAgent[] }>(\n 'GET',\n `${TOOLS_BASE_PATH}/${key}/dependents`,\n )\n return response.data\n }\n\n async syncDependents(key: string): Promise<DependentSyncResult[]> {\n const response = await this.client.request<{ data: DependentSyncResult[] }>(\n 'POST',\n `${TOOLS_BASE_PATH}/${key}/dependents/sync`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateToolsetRequest,\n ListToolsetsOptions,\n Toolset,\n ToolsetToolSummary,\n UpdateToolsetRequest,\n} from './types.js'\n\nconst TOOLSETS_BASE_PATH = '/agents/v1/toolsets'\nconst PLATFORM_TOOLS_PATH = '/agents/v1/platform-tools'\n\n/**\n * Service for managing Toolsets — the hardcoded platform toolsets (read-only)\n * merged with the org's custom groups of its own tools. Writes apply to custom\n * toolsets only; a platform key is rejected with `toolset_read_only`.\n */\nexport interface ToolsetService {\n /** Lists toolsets (platform + custom merged), auto-paginating. Filterable by `kind`. */\n list(options?: ListToolsetsOptions): PageIterator<Toolset, ListToolsetsOptions>\n /** Fetches a single page of toolsets with pagination metadata. */\n listPage(options?: ListToolsetsOptions): Promise<ListResult<Toolset>>\n /** Gets a single toolset by key (platform or custom). @throws {ProteosError} 404. */\n get(key: string): Promise<Toolset>\n /**\n * Lists the tools inside a toolset — platform members proxied from the\n * platform MCP server, custom members summarized from the org's Tool rows.\n * @throws {ProteosError} 404.\n */\n listTools(key: string): Promise<ToolsetToolSummary[]>\n /**\n * Lists every platform tool once, each with the platform toolset that serves\n * it. An agent may list any of these names in its `tools` as it is: no Tool\n * of that key is needed. A Tool the org saves under the same key replaces the\n * platform tool for its agents. A name several toolsets serve is the first\n * one's, in the order `list({ kind: 'platform' })` returns them.\n */\n listPlatformTools(): Promise<ToolsetToolSummary[]>\n /** Creates a custom toolset. @throws {ProteosError} 400/409. */\n create(request: CreateToolsetRequest): Promise<Toolset>\n /** Fully replaces a custom toolset's definition. @throws {ProteosError} 404/400. */\n update(key: string, request: UpdateToolsetRequest): Promise<Toolset>\n /** Creates or fully replaces a custom toolset (idempotent deploy entry point). */\n upsert(key: string, request: CreateToolsetRequest): Promise<Toolset>\n /** Deletes a custom toolset. @throws {ProteosError} 404/400. */\n delete(key: string): Promise<void>\n}\n\nexport class ToolsetServiceImpl implements ToolsetService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListToolsetsOptions = {}): PageIterator<Toolset, ListToolsetsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListToolsetsOptions = {}): Promise<ListResult<Toolset>> {\n return this.client.requestWithQuery<ListResult<Toolset>>('GET', TOOLSETS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Toolset> {\n return this.client.request<Toolset>('GET', `${TOOLSETS_BASE_PATH}/${key}`)\n }\n\n async listTools(key: string): Promise<ToolsetToolSummary[]> {\n const response = await this.client.request<{ data: ToolsetToolSummary[] }>(\n 'GET',\n `${TOOLSETS_BASE_PATH}/${key}/tools`,\n )\n return response.data\n }\n\n async listPlatformTools(): Promise<ToolsetToolSummary[]> {\n const response = await this.client.request<{ data: ToolsetToolSummary[] }>(\n 'GET',\n PLATFORM_TOOLS_PATH,\n )\n return response.data\n }\n\n async create(request: CreateToolsetRequest): Promise<Toolset> {\n return this.client.request<Toolset>('POST', TOOLSETS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateToolsetRequest): Promise<Toolset> {\n return this.client.request<Toolset>('PATCH', `${TOOLSETS_BASE_PATH}/${key}`, request)\n }\n\n async upsert(key: string, request: CreateToolsetRequest): Promise<Toolset> {\n return this.client.request<Toolset>('PUT', `${TOOLSETS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${TOOLSETS_BASE_PATH}/${key}`)\n }\n}\n","/**\n * Types for the agent-service Sessions API — a conversation with a configured\n * Agent.\n *\n * Hand-written mirror of the Go models in `go.proteos.ai/model/agent`\n * (`session.go`, `session-event.go`, `session-event-type.go`, `session-payload.go`,\n * `session-content.go` + `api/session-requests.go`). Field names match the\n * snake_case wire format exactly, including enum values.\n *\n * A Session is a thin mutable parent over an append-only `SessionEvent` log: the\n * events are the source of truth, the session carries only identity, the agent it\n * runs, a title and the latest lifecycle status. A {@link Turn} is a derived\n * projection of the log (never stored).\n */\n\nimport type { AuditFields, ListOptions, UserRef } from '../types/common.js'\nimport type { AgentRuntime, AgentVoiceStyle, ToolKind } from './types.js'\n\nexport type { ToolKind } from './types.js'\n\n// ---------------------------------------------------------------------------\n// Session\n// ---------------------------------------------------------------------------\n\n/**\n * The latest lifecycle state of a session, projected from the `session.status_*`\n * events. `idle` = ready for the next user message; `running` = a turn is in\n * flight; `terminated` = the provider session is gone; `error` = the last turn\n * failed; `ended` = a person ended it — the next `user.message` reopens it.\n */\nexport type SessionStatus = 'idle' | 'running' | 'terminated' | 'error' | 'ended'\n\n/**\n * The rolled-up token accounting for a session — the sum of every model request's\n * usage plus the request count, projected from the `span.model_request_end` events\n * and kept on the session row so listings/headers can show cost without replaying\n * the log. `total_tokens` is the derived input+output sum.\n *\n * `model` is the model the usage is attributed to. Managed Agents reports no model\n * id on its usage events, so it is seeded once at session create from the agent's\n * configured model and preserved across recomputes (empty on sessions created\n * before usage tracking existed).\n */\nexport interface SessionUsage {\n model: string\n input_tokens: number\n output_tokens: number\n cache_read_input_tokens: number\n cache_creation_input_tokens: number\n total_tokens: number\n request_count: number\n}\n\n/**\n * One conversation with a configured Agent. Surrogate-keyed by `id` (a session is\n * a graph node referenced by every event). `status` is denormalized from the\n * event log for cheap listing; `usage` is the denormalized token total.\n */\nexport interface Session extends AuditFields {\n org_id: string\n id: string\n agent_key: string\n /** What runs this session: the agent's runtime when the session was created. */\n runtime: AgentRuntime\n /**\n * Set on a delegated session: the session whose agent handed this one its work\n * with the `delegate` tool, and whose log gets a `delegated_session.updated`\n * event when a turn of this one ends. Null for a session a person or a surface\n * opened.\n */\n parent_session_id: string | null\n title: string\n status: SessionStatus\n usage: SessionUsage\n /** When the session was ended; null unless `status` is `ended`. */\n ended_at: string | null\n /** Who ended it; null unless `status` is `ended` (and on sessions ended by the platform). */\n ended_by: UserRef | null\n /**\n * Whether the voice provider records the voice sessions of this session (see\n * {@link CreateSessionRequest.is_voice_recorded}). Set at create, never changed.\n */\n is_voice_recorded: boolean\n}\n\n/**\n * What a session's preview shows: `serving` at `url`; `no_module` when the\n * session's sandbox holds no module to preview yet; `not_started` when the\n * session has no sandbox yet (its first message creates one).\n */\nexport type SessionPreviewStatus = 'serving' | 'no_module' | 'not_started'\n\n/**\n * The live preview of the module an agent works on in its session's sandbox\n * (sessions on the `sandbox` runtime), as a page to show in a frame.\n */\nexport interface SessionPreview {\n status: SessionPreviewStatus\n /**\n * The preview's address; null unless `status` is `serving`. The address is\n * the whole credential: whoever has it sees the preview until `expires_at`,\n * so show it to the session's owner only and do not store it.\n */\n url: string | null\n /** When `url` stops working (RFC 3339); null without one. */\n expires_at: string | null\n}\n\n// ---------------------------------------------------------------------------\n// Event types (the discriminant)\n// ---------------------------------------------------------------------------\n\n/**\n * The discriminant of a {@link SessionEvent} — it selects which payload shape the\n * event carries. These are the WHOLE events of the stored log; the chunk frames\n * of an event still being written are {@link DeltaEventType}.\n */\nexport type EventType =\n // User-originated (posted via the API or echoed back by the provider).\n | 'user.message'\n | 'user.interrupt'\n | 'user.tool_confirmation'\n | 'user.tool_result'\n // Voice: what was said aloud, and the voice assistant handing a request over.\n | 'user.speech'\n | 'user.voice_request'\n // Agent-originated.\n | 'agent.message'\n | 'agent.speech'\n | 'agent.reasoning'\n | 'agent.tool_use'\n | 'agent.tool_result'\n | 'agent.context_compacted'\n | 'agent.artifacts'\n // Session lifecycle.\n | 'session.status_running'\n | 'session.status_idle'\n | 'session.status_terminated'\n | 'session.status_ended'\n | 'session.error'\n | 'session.updated'\n | 'session.voice_started'\n | 'session.voice_ended'\n // The service asking the agent to open the conversation; shows nothing.\n // A report on a session this one delegated to.\n | 'delegated_session.updated'\n // Span (observability).\n | 'span.model_request_start'\n | 'span.model_request_end'\n\n/**\n * The client-postable subset (everything else is produced by the runtime). The\n * voice events are written by the voice routes, never posted as events.\n */\nexport type ClientEventType =\n | 'user.message'\n | 'user.interrupt'\n | 'user.tool_confirmation'\n | 'user.tool_result'\n\n// ---------------------------------------------------------------------------\n// Content blocks (the self-tagged pieces of heterogeneous payloads)\n// ---------------------------------------------------------------------------\n\n/** A plain text block. Agent messages are text-only. */\nexport interface TextBlock {\n type: 'text'\n text: string\n}\n\n/**\n * A file value object: a reference to a stored File (storage-service) plus light\n * metadata. Embedded inline in a user-message {@link ContentBlock} (`type=file`)\n * and nested under `image` in a tool {@link ResultBlock}.\n */\nexport interface FileBlock {\n file_id?: string\n file_name?: string\n mime_type?: string\n size_in_bytes?: number\n}\n\n/**\n * One block of a user/agent message body. For `type=text` only `text` is set; for\n * `type=file` the {@link FileBlock} fields are promoted inline.\n */\nexport interface ContentBlock extends FileBlock {\n type: 'text' | 'file'\n text?: string\n}\n\n/**\n * One block of a tool result. Unlike message file blocks, an image nests its file\n * under `image`; `json` carries an arbitrary raw object.\n */\nexport interface ResultBlock {\n type: 'text' | 'image' | 'file' | 'json'\n text?: string\n /** A stored image (type `image`). The model sees it when it reads images. */\n image?: FileBlock\n /** Any other stored file, such as a PDF (type `file`). */\n file?: FileBlock\n json?: unknown\n}\n\n// ---------------------------------------------------------------------------\n// Event payloads (discriminated by the sibling event `type`)\n// ---------------------------------------------------------------------------\n\n/**\n * A user message body (text + file blocks). `context` is what the launching\n * surface hands the model alongside the message (a call's summary and linked\n * records, say): stored with the event, sent to the model as an extra text\n * block, never rendered as part of the person's message. On the first message\n * of a session whose agent has memory, the service appends the owner's memory\n * block to it. Not for secrets: everyone who can read the session reads it back\n * through the events API.\n */\nexport interface UserMessagePayload {\n content: ContentBlock[]\n context?: string\n}\n\n/** An agent message body (text blocks only). */\nexport interface AgentMessagePayload {\n content: TextBlock[]\n}\n\n/**\n * Files the agent produced in its sandbox this turn (reconciled from the session\n * outputs), surfaced as downloadable attachments on the agent turn. A turn can\n * produce several. Each {@link FileBlock} carries the storage-service `file_id`.\n */\nexport interface AgentArtifactsPayload {\n files: FileBlock[]\n}\n\n/**\n * An agent reasoning (\"thinking\") block. v1 whole-events carry no text/signature\n * from the provider, so both are typically empty. `signature` is opaque: it\n * means something only to the model `provider` that wrote the block.\n */\nexport interface ReasoningPayload {\n text: string\n signature?: string\n provider?: string\n}\n\n/**\n * A tool invocation. `id` is the provider's tool_use event id — the correlation\n * key a matching {@link ToolResultPayload}'s `tool_use_id` points back to.\n * `tool_kind` is the execution location (action | mcp | client).\n */\nexport interface ToolUsePayload {\n id: string\n name: string\n input: unknown\n tool_kind: SessionToolKind\n}\n\n/**\n * Where a tool a session's agent called is run. Besides the kinds a registered\n * tool can have ({@link ToolKind}), a session whose agent can delegate has the\n * `delegation` tools (`delegate`, `list_delegated_sessions`, …), which the agent\n * service runs itself and which cannot be registered. Every agent also has the\n * `system` tools (`new_phase`), which the agent service answers itself and which\n * cannot be registered either.\n */\nexport type SessionToolKind = ToolKind | 'delegation' | 'system'\n\n/** The result of a tool invocation, linked to its use by `tool_use_id`. */\nexport interface ToolResultPayload {\n tool_use_id: string\n result: ResultBlock[]\n /** \"success\" | \"error\" (open string for forward-compat). */\n outcome: string\n}\n\n/** A user's decision on a tool that requested approval. */\nexport interface ToolConfirmationPayload {\n tool_use_id: string\n /** \"approved\" | \"denied\" (open string for forward-compat). */\n decision: string\n}\n\n/**\n * Announces that earlier context was summarized. On the embedded runtime the\n * agent continues from `summary` in place of the events up to and including seq\n * `through_seq`; the events themselves stay in the log. A durable session's\n * provider compacts on its own and sets neither.\n */\nexport interface ContextCompactedPayload {\n summary: string\n through_seq?: number\n}\n\n/** A session-level error. */\nexport interface ErrorPayload {\n message: string\n code?: string\n}\n\n/**\n * Why a turn went idle. `type` is an open string (\"turn_ended\" |\n * \"user_action_required\" | \"budget_reached\" | …) so new provider reasons don't\n * break decoding. \"budget_reached\": the session used up the spend ceiling it was\n * created with; a message sent to it is refused (409 `session_budget_reached`).\n */\nexport interface StopReason {\n type: string\n}\n\n/**\n * Ends a turn — published once per turn by the server, not an echo of the upstream\n * provider's session status (which flips idle/running once per server-side tool\n * round, mid-turn).\n *\n * `event_ids` is set only with `stop_reason.type: 'user_action_required'`, and lists\n * the tool_use events still OUTSTANDING — the ones a client must answer. Tools the\n * server executes itself are resolved before this event exists, so seeing this event\n * at all means the turn cannot continue without you: answer each id with a\n * `user.tool_result`.\n */\nexport interface SessionIdlePayload {\n stop_reason: StopReason\n event_ids?: string[]\n}\n\n/**\n * A server-side session metadata change — v1 carries the (often auto-generated)\n * title. Projected onto {@link Session.title}; emitted only when the title changed.\n */\nexport interface SessionUpdatedPayload {\n title?: string\n}\n\n/** A tool call a session is waiting on: what it asks, for whoever answers it. */\nexport interface AwaitingToolUse {\n tool_use_id: string\n name: string\n input: unknown\n}\n\n/**\n * Where a delegated session stands at the end of one of its turns, written to the\n * log of the session that delegated to it (see {@link Session.parent_session_id}).\n *\n * `status` is the delegated session's status at that moment. `stop_reason` is set\n * only with status `idle`: `turn_ended`, or `user_action_required` when it waits\n * for an answer, in which case `awaiting_tool_uses` lists the calls it waits on.\n * `summary` is the last thing its agent wrote, cut to a bound; the whole\n * conversation is in the delegated session. `is_stopped_by_parent` is true when\n * the delegating agent interrupted the turn itself. `is_handed_back` is true when\n * the person was talking to the delegated agent in its session and that agent\n * handed them back (the `hand_back_session` client tool); `summary` is then what\n * the agent gave the delegating agent with that call, when it gave one.\n */\nexport interface DelegatedSessionUpdatedPayload {\n session_id: string\n agent_key: string\n title: string\n status: SessionStatus\n stop_reason?: StopReason\n awaiting_tool_uses?: AwaitingToolUse[]\n is_stopped_by_parent?: boolean\n is_handed_back?: boolean\n summary: string\n}\n\n/**\n * One utterance of a voice session, of the person (`user.speech`) or of the voice\n * assistant (`agent.speech`): the text as the voice provider transcribed it, and\n * when it was said, in milliseconds from the start of the voice session. Speech\n * starts no turn; the agent reads it with what opens the next one.\n */\nexport interface SpeechPayload {\n voice_session_id: string\n text: string\n start_ms: number\n end_ms: number\n}\n\n/**\n * The voice assistant handing what the person asked for to the agent: it starts a\n * turn, or is queued behind the one that runs, like a `user.message`. The request\n * itself is the speech before the event.\n */\nexport interface VoiceRequestPayload {\n voice_session_id: string\n /** The voice model's delegation the request is of, as the page reported it.\n * The page speaks the turn's answer as that delegation's result. */\n delegation_id?: string\n /** Model-only text the page sent with the request; never rendered. */\n context?: string\n}\n\n/**\n * Voice was entered on the session. `transferred_from_session_id` is set when\n * it was not entered here but came with the person: the session they were\n * handed over from, or handed back from.\n */\nexport interface VoiceStartedPayload {\n voice_session_id: string\n transferred_from_session_id?: string\n}\n\n/**\n * Why a voice session ended. `superseded` and `transferred` are never reported\n * by a page. `transferred` is the reason of the `session.voice_ended` in the log\n * of a session the person was handed over from: the voice session itself goes on\n * in the session they were handed to.\n */\nexport type VoiceEndReason =\n | 'user'\n | 'idle'\n | 'max_duration'\n | 'session_ended'\n | 'browser_left'\n | 'provider_closed'\n | 'superseded'\n | 'transferred'\n\n/**\n * Voice was left: why, and how long the voice session lasted: what the voice\n * provider says, or the time since voice was entered when the page went away\n * without it (null when nobody learned it). With `transferred` the voice session\n * goes on in `transferred_to_session_id`, and no duration is known yet.\n */\nexport interface VoiceEndedPayload {\n voice_session_id: string\n end_reason: VoiceEndReason\n duration_seconds: number | null\n transferred_to_session_id?: string\n}\n\n/** Opens a model-request span. */\nexport interface ModelRequestStartPayload {\n model_id: string\n}\n\n/** Per-request token accounting. */\nexport interface ModelUsage {\n input_tokens: number\n output_tokens: number\n cache_read_input_tokens?: number\n cache_creation_input_tokens?: number\n}\n\n/** Closes a model-request span with usage. */\nexport interface ModelRequestEndPayload {\n model_usage: ModelUsage\n}\n\n/**\n * Opens a turn. `acting_user_id` is the person the turn's tools run as, which is\n * not always the author of the message that opened it (a message an agent posts\n * to a session it delegated to). Absent on turns started before it was recorded.\n */\nexport interface SessionRunningPayload {\n acting_user_id?: string\n}\n\n/**\n * The body of events that carry no fields (`user.interrupt`,\n * `session.status_terminated`, `session.status_ended`).\n */\nexport type EmptyPayload = Record<string, never>\n\n// ---------------------------------------------------------------------------\n// SessionEvent (the append-only log envelope)\n// ---------------------------------------------------------------------------\n\n/** Shared envelope fields carried by every {@link SessionEvent}. */\nexport interface SessionEventEnvelope {\n /** Dedupe key: our uuid for user events, the provider's id for agent events. */\n id: string\n session_id: string\n org_id: string\n /** Groups events into user/agent turns. */\n turn_id: string\n /** Per-session monotonic cursor (the SSE frame `id`). */\n seq: number\n created_by: UserRef\n /** Meaningful only for user events: null = queued, timestamp = consumed. */\n processed_at: string | null\n created_at: string\n}\n\n/**\n * One entry of the append-only session log — discriminated by `type`. The same\n * envelope is delivered byte-for-byte over both the durable (REST) and live (SSE)\n * channels, keyed by the same `seq`, so the two merge into one ordered log.\n */\nexport type SessionEvent = SessionEventEnvelope &\n (\n | { type: 'user.message'; payload: UserMessagePayload }\n | { type: 'user.interrupt'; payload: EmptyPayload }\n | { type: 'user.tool_confirmation'; payload: ToolConfirmationPayload }\n | { type: 'user.tool_result'; payload: ToolResultPayload }\n | { type: 'user.speech'; payload: SpeechPayload }\n | { type: 'user.voice_request'; payload: VoiceRequestPayload }\n | { type: 'agent.message'; payload: AgentMessagePayload }\n | { type: 'agent.speech'; payload: SpeechPayload }\n | { type: 'agent.reasoning'; payload: ReasoningPayload }\n | { type: 'agent.tool_use'; payload: ToolUsePayload }\n | { type: 'agent.tool_result'; payload: ToolResultPayload }\n | { type: 'agent.context_compacted'; payload: ContextCompactedPayload }\n | { type: 'agent.artifacts'; payload: AgentArtifactsPayload }\n | { type: 'session.status_running'; payload: SessionRunningPayload }\n | { type: 'session.status_idle'; payload: SessionIdlePayload }\n | { type: 'session.status_terminated'; payload: EmptyPayload }\n | { type: 'session.status_ended'; payload: EmptyPayload }\n | { type: 'session.error'; payload: ErrorPayload }\n | { type: 'session.updated'; payload: SessionUpdatedPayload }\n | { type: 'session.voice_started'; payload: VoiceStartedPayload }\n | { type: 'session.voice_ended'; payload: VoiceEndedPayload }\n | { type: 'delegated_session.updated'; payload: DelegatedSessionUpdatedPayload }\n | { type: 'span.model_request_start'; payload: ModelRequestStartPayload }\n | { type: 'span.model_request_end'; payload: ModelRequestEndPayload }\n )\n// A closed discriminated union (the v1 event set) so consumers narrow `payload`\n// by `type`. An unrecognized future event type still parses at runtime (it is cast\n// from JSON) — a switch over `type` simply won't match it, which is the intended\n// skip-and-ignore behavior.\n\n/**\n * The `GroupByTurn` projection — NEVER stored, recomputed from the event log.\n * `events` hold the envelopes verbatim, grouped by `turn_id` and ordered by `seq`.\n * The web folds this client-side from the live event stream; this type mirrors the\n * server's `GET /sessions/:id/turns` for completeness.\n */\nexport interface Turn {\n id: string\n role: 'user' | 'agent'\n events: SessionEvent[]\n}\n\n// ---------------------------------------------------------------------------\n// Requests / query options\n// ---------------------------------------------------------------------------\n\n/**\n * A client tool the launching surface advertises when it opens a session: a custom\n * tool the agent calls but the browser renders/executes, returning the result. Only\n * these three fields cross the wire — the render slot and React component are\n * frontend-only. `input_schema` is a JSON Schema (draft-07) object.\n */\nexport interface ClientToolSchema {\n name: string\n description: string\n input_schema: Record<string, unknown>\n}\n\n/**\n * Opens a session against a configured agent. `title` is optional. `client_tools` is\n * the launching surface's client-tool catalog, attached to this session only — a\n * surface that can't render them simply omits the field, so the agent never gets a\n * tool nobody can answer.\n */\nexport interface CreateSessionRequest {\n agent_key: string\n title?: string\n client_tools?: ClientToolSchema[]\n /**\n * Replaces the voice assistant's instructions in the voice sessions of this\n * session, at most 40,000 characters. `{{delegate}}` and `{{do_not_delegate}}` in them stand\n * for the words the voice model in use is told to hand a request over with, and\n * not to; the service fills them in. No response or event returns them.\n */\n voice_instructions?: string\n /**\n * The voice provider records the voice sessions of this session; a recording\n * is read with `sessions.getVoiceRecording`.\n */\n is_voice_recorded?: boolean\n}\n\n/**\n * Posts a client event onto a session. Only client-postable `user.*` types are\n * accepted; `payload` is the matching payload for the `type`.\n */\nexport interface AppendEventRequest {\n type: ClientEventType\n /**\n * Optionally supply the turn's id (a UUID) so the client can render the message\n * optimistically under a stable identity that matches the event echoed back\n * over the stream. Omitted, the service mints one.\n */\n turn_id?: string\n payload?: unknown\n /**\n * The sending surface's client-tool catalog, `user.message` only. A surface that\n * opened a session it did not create attaches its tools this way: when the names\n * differ from the session's client tools they replace them before the turn runs.\n * Omitted, the session's tools are left as they are.\n */\n client_tools?: ClientToolSchema[]\n /**\n * Refuse a `user.message` posted while a turn runs with 409 `session_running`\n * instead of queueing it. Queueing is the default: the running turn reads the\n * message with its next tool results where the runtime allows, and it opens the\n * session's next turn otherwise. For a caller that pairs each message with the\n * turn it starts and would rather retry later.\n */\n reject_if_running?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Voice\n// ---------------------------------------------------------------------------\n\n/**\n * One time a person talked to a session's agent through the voice assistant. The\n * assistant listens and speaks; what was said is in the session's event log\n * (`user.speech`, `agent.speech`) and everything asked for runs as turns of the\n * session. A session has at most one active voice session. A hand-over moves the\n * voice session to the session the person is handed to, and back.\n */\nexport interface VoiceSession {\n id: string\n org_id: string\n /** The session the person talks to. */\n session_id: string\n status: 'active' | 'ended'\n /** Null while it is active. */\n end_reason: VoiceEndReason | null\n /** How long it lasted: what the voice provider says, or the time since voice\n * was entered when the page went away without it. Null when not known. */\n duration_seconds: number | null\n /** How much of `duration_seconds` the voice model was paused (standby):\n * nobody spoke, and the provider bills that time at its lower rate. Null when\n * not known. */\n standby_seconds: number | null\n created_by: UserRef\n created_at: string\n ended_at: string | null\n}\n\n/** Enters voice on a session with the WebRTC offer of the page's peer connection. */\nexport interface StartVoiceRequest {\n sdp_offer: string\n}\n\n/**\n * The voice session that started, the voice provider's answer to the page's offer,\n * and the limits the page enforces by leaving voice.\n */\nexport interface StartVoiceResponse {\n voice_session: VoiceSession\n sdp_answer: string\n /** How long nobody may speak, while the voice model listens, before the page\n * leaves voice. */\n idle_timeout_seconds: number\n /** How long a voice session may last at most. */\n max_duration_seconds: number\n /** How long nobody speaks before the voice provider pauses the voice model\n * (standby); speech wakes it. 0: it never pauses. */\n standby_after_seconds: number\n /** How long the voice model may stay paused in one stretch before the page\n * leaves voice. */\n max_standby_seconds: number\n /** When the voice of the session's agent speaks: the page tells a\n * moderator's voice model when the conversation has gone quiet. */\n voice_style: AgentVoiceStyle\n}\n\n/** One finished utterance as the page heard it from the voice provider. */\nexport interface SpeechSegment {\n speaker: 'user' | 'agent'\n text: string\n /** Milliseconds from the start of the voice session. */\n start_ms: number\n end_ms: number\n}\n\n/**\n * Reports what was said in the session's active voice session since the last\n * report, in the order said. `starts_turn` says the voice assistant handed a\n * request over: after the segments a `user.voice_request` starts a turn, or is\n * queued behind the one that runs. `client_tools` is honoured with `starts_turn`\n * only (see {@link AppendEventRequest.client_tools}). `voice_session_id` is the\n * voice session the page started: a report for one that was replaced since (the\n * same person entered voice again, in another tab) is refused with 409\n * `voice_session_not_active`.\n */\nexport interface AppendSpeechRequest {\n voice_session_id: string\n segments: SpeechSegment[]\n starts_turn?: boolean\n /** The voice model's delegation the request is of, with `starts_turn` only.\n * A request is written once per delegation, however often it is reported. */\n delegation_id?: string\n client_tools?: ClientToolSchema[]\n /** Model-only text for the request, with `starts_turn` only (see\n * {@link UserMessagePayload.context}). */\n context?: string\n}\n\n/**\n * Leaves voice: why, and how long the voice provider says the session lasted (it\n * tells the page when the session closes). `voice_session_id` is the voice\n * session the page started (see {@link AppendSpeechRequest}).\n */\nexport interface EndVoiceRequest {\n voice_session_id: string\n end_reason: Exclude<VoiceEndReason, 'superseded' | 'transferred'>\n duration_seconds?: number | null\n /** How much of `duration_seconds` the voice model was paused, as the voice\n * provider says. */\n standby_seconds?: number | null\n /** What was said since the last speech report: a page that is being closed\n * has one request left to send. */\n segments?: SpeechSegment[]\n}\n\n/**\n * Moves the session's active voice session to another session, when the person\n * is handed over to it or handed back. The connection to the voice provider\n * stays as it is; what the person asks for next runs as turns of the target.\n */\nexport interface TransferVoiceRequest {\n /** The voice session the page started (see {@link AppendSpeechRequest}). */\n voice_session_id: string\n /** A session the session delegated to, or the one that delegated to it. */\n target_session_id: string\n}\n\n/**\n * The voice session on its new session, and the `session.voice_started` written\n * to that session's log: what the log holds up to it was not said to the voice\n * model.\n */\nexport interface TransferVoiceResponse {\n voice_session: VoiceSession\n started: SessionEvent\n /** The voice style of the agent the voice speaks for now. */\n voice_style: AgentVoiceStyle\n /** Whether a turn of that session runs, as its log says up to `started`.\n * The page follows the log from `started` on. */\n is_turn_running: boolean\n}\n\n/** List filter for sessions (in addition to pagination/sorting). */\nexport interface ListSessionsOptions extends ListOptions {\n /** Filter by the agent the session runs. */\n agent_key?: string\n /** Keep sessions in this status, or in any of several. */\n status?: SessionStatus | SessionStatus[]\n /** Keep sessions whose title contains this text, ignoring case. */\n title?: string\n /**\n * Keep the sessions one user started: a user id, or `'me'` for the caller.\n * It narrows what the caller may see and never widens it.\n */\n created_by?: string\n /** Keep the sessions one session delegated to. */\n parent_session_id?: string\n}\n\n/**\n * Forward cursor over the durable event log. `after_seq` is the exclusive lower\n * bound (the last-seen seq); `order` defaults to asc (chronological). `types`\n * restricts the result to specific event types (e.g. `['agent.message']`);\n * omitted, every type is returned.\n */\nexport interface SessionEventsOptions {\n after_seq?: number\n limit?: number\n order?: 'asc' | 'desc'\n types?: EventType[]\n}\n\n/** Options for opening the live SSE stream. */\nexport interface SessionStreamOptions {\n /** Replay from this seq (exclusive) before following live. */\n afterSeq?: number\n /** Abort to tear the stream down. */\n signal?: AbortSignal\n}\n\n// ---------------------------------------------------------------------------\n// The live delta channel\n// ---------------------------------------------------------------------------\n\n/**\n * The chunk frames of the three long agent events, sent on the delta channel\n * while the model writes the event: the whole event's type plus `.start`,\n * `.delta` or `.end`. Frames are never stored and never posted by a client.\n */\nexport type DeltaEventType =\n | 'agent.message.start'\n | 'agent.message.delta'\n | 'agent.message.end'\n | 'agent.reasoning.start'\n | 'agent.reasoning.delta'\n | 'agent.reasoning.end'\n | 'agent.tool_use.start'\n | 'agent.tool_use.delta'\n | 'agent.tool_use.end'\n\n/** Opens or closes the frames of one content part. */\nexport interface DeltaBoundaryPayload {\n part_index: number\n}\n\n/** The next piece of a message's text. Append the pieces in order. */\nexport interface MessageDeltaPayload {\n part_index: number\n text: string\n}\n\n/** The next piece of the reasoning text, or the signature that closes it. */\nexport interface ReasoningDeltaPayload {\n part_index: number\n text?: string\n signature?: string\n}\n\n/** A tool call is known by id, name and kind before its input has been written. */\nexport interface ToolUseStartPayload {\n part_index: number\n id: string\n name: string\n tool_kind: SessionToolKind\n}\n\n/** The next piece of a tool call's input, as JSON text. */\nexport interface ToolUseDeltaPayload {\n part_index: number\n partial_json: string\n}\n\n/**\n * One chunk frame. It uses the envelope of the whole event it belongs to: `id`\n * and `turn_id` are that event's, so a client builds a draft from the frames and\n * drops it when the whole event with the same `id` arrives. `seq` is 0 — a frame\n * has no place in the log.\n */\nexport type SessionDeltaFrame = SessionEventEnvelope &\n (\n | { type: 'agent.message.start'; payload: DeltaBoundaryPayload }\n | { type: 'agent.message.delta'; payload: MessageDeltaPayload }\n | { type: 'agent.message.end'; payload: DeltaBoundaryPayload }\n | { type: 'agent.reasoning.start'; payload: DeltaBoundaryPayload }\n | { type: 'agent.reasoning.delta'; payload: ReasoningDeltaPayload }\n | { type: 'agent.reasoning.end'; payload: DeltaBoundaryPayload }\n | { type: 'agent.tool_use.start'; payload: ToolUseStartPayload }\n | { type: 'agent.tool_use.delta'; payload: ToolUseDeltaPayload }\n | { type: 'agent.tool_use.end'; payload: DeltaBoundaryPayload }\n )\n\n/**\n * One entry of the delta channel: a whole event of the log, or a chunk frame of\n * the event being written after it. `position` is the entry's place on the\n * channel, `<seq>-<n>`: a whole event is `<seq>-0`, the frames after it count up\n * from 1. Pass it back as {@link SessionDeltaStreamOptions.after} to resume.\n */\nexport interface SessionDeltaEntry {\n position: string\n event: SessionEvent | SessionDeltaFrame\n}\n\n/** Options for opening the live delta stream. */\nexport interface SessionDeltaStreamOptions {\n /** Replay from here (exclusive) before following live: a position, or a bare seq. */\n after?: string | number\n /** Abort to tear the stream down. */\n signal?: AbortSignal\n}\n\nconst DELTA_EVENT_TYPE = /^agent\\.(message|reasoning|tool_use)\\.(start|delta|end)$/\n\n/** Whether an entry of the delta channel is a chunk frame, not a whole event. */\nexport function isDeltaFrame(event: SessionEvent | SessionDeltaFrame): event is SessionDeltaFrame {\n return DELTA_EVENT_TYPE.test(event.type)\n}\n","import type { ProteosClient } from '../client.js'\nimport { type AgentService, AgentServiceImpl } from './agents.js'\nimport { type McpServerService, McpServerServiceImpl } from './mcp-servers.js'\nimport { type ModelService, ModelServiceImpl } from './models.js'\nimport { type PromptService, PromptServiceImpl } from './prompts.js'\nimport { type SessionService, SessionServiceImpl } from './sessions.js'\nimport { type SkillService, SkillServiceImpl } from './skills.js'\nimport { type ToolService, ToolServiceImpl } from './tools.js'\nimport { type ToolsetService, ToolsetServiceImpl } from './toolsets.js'\n\n/**\n * Client for the Proteos Agent Service API.\n *\n * Manages the AI-agent configuration domain: Agents, Prompts (versioned),\n * Skills (versioned bundles), Tools, and MCP Servers — all org-scoped and keyed\n * by an immutable kebab-case `key` — plus the stateless model calls\n * (`models.generate`, `models.decide`) and chat sessions.\n *\n * @example\n * ```ts\n * import { ProteosClient, AgentClient } from '@proteos/sdk';\n *\n * const client = new ProteosClient({ baseUrl, token });\n * const agent = new AgentClient(client);\n *\n * const agents = await agent.agents.list().all();\n * const prompt = await agent.prompts.get('revenue-brief');\n *\n * const { answers } = await agent.models.decide({\n * state: { message: 'My card was charged twice!' },\n * questions: {\n * refund_requested: { type: 'boolean', instructions: 'Does the customer ask for money back?' },\n * topic: { type: 'choice', instructions: 'Topic?', criteria: { billing: 'charges', other: 'else' } },\n * },\n * });\n * if (answers.topic.confidence > 0.8) route(answers.topic.choice);\n * ```\n */\nexport class AgentClient {\n /** Service for managing agents. */\n readonly agents: AgentService\n /** Service for managing prompts (versioned). */\n readonly prompts: PromptService\n /** Service for managing skills (versioned bundles). */\n readonly skills: SkillService\n /** Service for managing tools. */\n readonly tools: ToolService\n /** Service for managing toolsets (platform + custom tool groups). */\n readonly toolsets: ToolsetService\n /** Service for managing MCP server registrations. */\n readonly mcpServers: McpServerService\n /** Service for stateless model calls: `generate` (one message out) and `decide` (calibrated typed answers). */\n readonly models: ModelService\n /** Service for managing chat sessions (conversations + event log + stream). */\n readonly sessions: SessionService\n\n /**\n * Creates a new AgentClient instance.\n *\n * @param client - The base ProteosClient to use for API requests\n */\n constructor(client: ProteosClient) {\n this.agents = new AgentServiceImpl(client)\n this.prompts = new PromptServiceImpl(client)\n this.skills = new SkillServiceImpl(client)\n this.tools = new ToolServiceImpl(client)\n this.toolsets = new ToolsetServiceImpl(client)\n this.mcpServers = new McpServerServiceImpl(client)\n this.models = new ModelServiceImpl(client)\n this.sessions = new SessionServiceImpl(client)\n }\n}\n\n// Re-export service interfaces\nexport type { AgentService } from './agents.js'\nexport type { McpServerService } from './mcp-servers.js'\n// Re-export model-call types (generate + decide)\nexport type {\n BooleanAnswer,\n BooleanCriteria,\n BooleanQuestion,\n ChoiceAnswer,\n ChoiceQuestion,\n DecideRequest,\n DecisionAnswer,\n DecisionAnswerFor,\n DecisionQuestion,\n DecisionQuestions,\n DecisionQuestionType,\n DecisionResult,\n GenerateRequest,\n GenerationResult,\n ModelInfo,\n ModelProviderName,\n ModelStopReason,\n ScoreAnswer,\n ScoreQuestion,\n StructuredText,\n} from './model-types.js'\nexport type { ModelService } from './models.js'\nexport type { PromptService } from './prompts.js'\n// Re-export session types\nexport type {\n AgentArtifactsPayload,\n AgentMessagePayload,\n AppendEventRequest,\n AppendSpeechRequest,\n AwaitingToolUse,\n ClientEventType,\n ClientToolSchema,\n ContentBlock,\n ContextCompactedPayload,\n CreateSessionRequest,\n DelegatedSessionUpdatedPayload,\n DeltaBoundaryPayload,\n DeltaEventType,\n EmptyPayload,\n EndVoiceRequest,\n ErrorPayload,\n EventType,\n FileBlock,\n ListSessionsOptions,\n MessageDeltaPayload,\n ModelRequestEndPayload,\n ModelRequestStartPayload,\n ModelUsage,\n ReasoningDeltaPayload,\n ReasoningPayload,\n ResultBlock,\n Session,\n SessionDeltaEntry,\n SessionDeltaFrame,\n SessionDeltaStreamOptions,\n SessionEvent,\n SessionEventEnvelope,\n SessionEventsOptions,\n SessionIdlePayload,\n SessionPreview,\n SessionPreviewStatus,\n SessionRunningPayload,\n SessionStatus,\n SessionStreamOptions,\n SessionToolKind,\n SessionUpdatedPayload,\n SpeechPayload,\n SpeechSegment,\n StartVoiceRequest,\n StartVoiceResponse,\n StopReason,\n TextBlock,\n ToolConfirmationPayload,\n ToolResultPayload,\n ToolUseDeltaPayload,\n ToolUsePayload,\n ToolUseStartPayload,\n TransferVoiceRequest,\n TransferVoiceResponse,\n Turn,\n UserMessagePayload,\n VoiceEndedPayload,\n VoiceEndReason,\n VoiceRequestPayload,\n VoiceSession,\n VoiceStartedPayload,\n} from './session-types.js'\nexport { isDeltaFrame } from './session-types.js'\nexport type { SessionService } from './sessions.js'\nexport type { SkillService } from './skills.js'\nexport type { ToolService } from './tools.js'\nexport type { ToolsetService } from './toolsets.js'\n// Re-export types\nexport type {\n ActionBinding,\n Agent,\n AgentResourceListOptions,\n AgentRuntime,\n AgentVoiceStyle,\n CreateAgentRequest,\n CreateMcpServerRequest,\n CreatePromptRequest,\n CreateToolRequest,\n CreateToolsetRequest,\n DependentAgent,\n DependentSyncResult,\n ListAgentsOptions,\n ListMcpServersOptions,\n ListPromptsOptions,\n ListSkillsOptions,\n ListToolsetsOptions,\n ListToolsOptions,\n McpBinding,\n McpConnectionState,\n McpConnectionStatus,\n McpServer,\n McpServerAuth,\n McpServerOAuth,\n McpToolSummary,\n ModelConfig,\n PlatformBinding,\n Prompt,\n PromptVersion,\n QueryBinding,\n Skill,\n SkillBundle,\n SkillVersion,\n StartMcpOAuthResponse,\n Tool,\n ToolBinding,\n ToolKind,\n Toolset,\n ToolsetKind,\n ToolsetToolSummary,\n UpdateAgentRequest,\n UpdateMcpServerRequest,\n UpdatePromptRequest,\n UpdateToolRequest,\n UpdateToolsetRequest,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { Organization, Profile, UpdateMeRequest, User } from './types.js'\n\nconst ME_BASE_PATH = '/accounts/v1/me'\n\n/**\n * Service for caller-scoped queries — answers about the authenticated user\n * (from the token), not an arbitrary user id.\n */\nexport interface MeService {\n /**\n * Gets the caller's own user record, resolved from the token's user id.\n * The canonical \"who am I\" — use this instead of filtering `users.list`\n * by email.\n *\n * @returns The calling user\n */\n get(): Promise<User>\n\n /**\n * Updates the caller's own profile (name, photo). Requires a JWT session —\n * requests authenticated with an API key are rejected.\n *\n * @param request - Fields to update; `profile_image: null` removes the photo\n * @returns The updated user\n */\n update(request: UpdateMeRequest): Promise<User>\n\n /**\n * Lists the organizations the caller can act in (all orgs for a platform\n * admin; otherwise the orgs they're a member of). Powers the org-switcher.\n *\n * @returns The caller's organizations\n */\n organizations(): Promise<Organization[]>\n\n /**\n * Gets the caller's profile in the token org — the subject app\n * configurations are resolved against.\n *\n * @throws {ProteosError} 404 when the caller has no profile\n */\n profile(): Promise<Profile>\n}\n\n/**\n * Implementation of MeService.\n */\nexport class MeServiceImpl implements MeService {\n constructor(private readonly client: ProteosClient) {}\n\n async get(): Promise<User> {\n return this.client.request<User>('GET', ME_BASE_PATH)\n }\n\n async update(request: UpdateMeRequest): Promise<User> {\n return this.client.request<User>('PATCH', ME_BASE_PATH, request)\n }\n\n async organizations(): Promise<Organization[]> {\n const response = await this.client.request<{ data: Organization[] }>(\n 'GET',\n `${ME_BASE_PATH}/organizations`,\n )\n return response.data\n }\n\n async profile(): Promise<Profile> {\n return this.client.request<Profile>('GET', `${ME_BASE_PATH}/profile`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateOrganizationRequest,\n ListOrganizationsOptions,\n Organization,\n UpdateOrganizationRequest,\n} from './types.js'\n\nconst ORGANIZATIONS_BASE_PATH = '/accounts/v1/organizations'\n\n/**\n * Service for managing organizations.\n * Handles organization CRUD operations.\n */\nexport interface OrganizationService {\n /**\n * Lists organizations with optional filtering.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param options - Filter and pagination options\n * @returns Async iterator over organizations\n *\n * @example\n * ```ts\n * // Iterate over all organizations\n * for await (const org of service.list()) {\n * console.log(org.name);\n * }\n *\n * // With filtering\n * for await (const org of service.list({ name: 'Acme Corp' })) {\n * console.log(org.id);\n * }\n * ```\n */\n list(options?: ListOrganizationsOptions): PageIterator<Organization, ListOrganizationsOptions>\n\n /**\n * Fetches a single page of organizations.\n *\n * @param options - Filter and pagination options (including `page`)\n * @returns A single page of organizations with pagination metadata\n */\n listPage(options?: ListOrganizationsOptions): Promise<ListResult<Organization>>\n\n /**\n * Gets a single organization by ID.\n *\n * @param id - Organization ID\n * @returns The organization\n * @throws {ProteosError} If organization not found (404)\n */\n get(id: string): Promise<Organization>\n\n /**\n * Creates a new organization.\n *\n * @param request - Organization creation request\n * @returns The created organization\n * @throws {ProteosError} If validation fails (400) or conflict (409)\n *\n * @example\n * ```ts\n * const org = await service.create({\n * name: 'Acme Corporation',\n * description: 'Main organization',\n * });\n * ```\n */\n create(request: CreateOrganizationRequest): Promise<Organization>\n\n /**\n * Updates an existing organization.\n *\n * @param id - Organization ID\n * @param request - Fields to update\n * @returns The updated organization\n * @throws {ProteosError} If organization not found (404) or validation fails (400)\n */\n update(id: string, request: UpdateOrganizationRequest): Promise<Organization>\n\n /**\n * Deletes an organization.\n *\n * @param id - Organization ID\n * @throws {ProteosError} If organization not found (404)\n */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of OrganizationService.\n */\nexport class OrganizationServiceImpl implements OrganizationService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListOrganizationsOptions = {},\n ): PageIterator<Organization, ListOrganizationsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListOrganizationsOptions = {}): Promise<ListResult<Organization>> {\n return this.client.requestWithQuery<ListResult<Organization>>(\n 'GET',\n ORGANIZATIONS_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<Organization> {\n return this.client.request<Organization>('GET', `${ORGANIZATIONS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateOrganizationRequest): Promise<Organization> {\n return this.client.request<Organization>('POST', ORGANIZATIONS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateOrganizationRequest): Promise<Organization> {\n return this.client.request<Organization>('PATCH', `${ORGANIZATIONS_BASE_PATH}/${id}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${ORGANIZATIONS_BASE_PATH}/${id}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateProfileRequest,\n ListProfilesOptions,\n Profile,\n UpdateProfileRequest,\n} from './types.js'\n\nconst PROFILES_BASE_PATH = '/accounts/v1/profiles'\n\n/**\n * Service for managing profiles — the org's user-types (ONE per user per\n * org). Per-user assignment lives on {@link UserService} (`getProfile` /\n * `setProfile` / `clearProfile`); the org-wide roster on\n * {@link UserProfileAssignmentService}.\n */\nexport interface ProfileService {\n /** Lists profiles (auto-paginating iterator). */\n list(options?: ListProfilesOptions): PageIterator<Profile, ListProfilesOptions>\n\n /** Fetches a single page of profiles. */\n listPage(options?: ListProfilesOptions): Promise<ListResult<Profile>>\n\n /** Gets a profile by slug (404 when unknown). */\n get(slug: string): Promise<Profile>\n\n /** Creates a profile. The org is taken from the caller's token. */\n create(request: CreateProfileRequest): Promise<Profile>\n\n /**\n * Creates or updates a profile idempotently by slug\n * (`PUT /accounts/v1/profiles/:slug`). The URL slug wins on mismatch.\n */\n upsert(slug: string, request: CreateProfileRequest): Promise<Profile>\n\n /** Partially updates a profile. */\n update(slug: string, request: UpdateProfileRequest): Promise<Profile>\n\n /**\n * Deletes a profile.\n * @throws {ProteosError} 409 `profile_in_use` while users still hold it —\n * move them first.\n */\n delete(slug: string): Promise<void>\n}\n\nexport class ProfileServiceImpl implements ProfileService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListProfilesOptions = {}): PageIterator<Profile, ListProfilesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListProfilesOptions = {}): Promise<ListResult<Profile>> {\n return this.client.requestWithQuery<ListResult<Profile>>('GET', PROFILES_BASE_PATH, options)\n }\n\n async get(slug: string): Promise<Profile> {\n return this.client.request<Profile>('GET', `${PROFILES_BASE_PATH}/${slug}`)\n }\n\n async create(request: CreateProfileRequest): Promise<Profile> {\n return this.client.request<Profile>('POST', PROFILES_BASE_PATH, request)\n }\n\n async upsert(slug: string, request: CreateProfileRequest): Promise<Profile> {\n return this.client.request<Profile>('PUT', `${PROFILES_BASE_PATH}/${slug}`, {\n ...request,\n slug,\n })\n }\n\n async update(slug: string, request: UpdateProfileRequest): Promise<Profile> {\n return this.client.request<Profile>('PATCH', `${PROFILES_BASE_PATH}/${slug}`, request)\n }\n\n async delete(slug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${PROFILES_BASE_PATH}/${slug}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n AssignPermissionRequest,\n CreateRoleRequest,\n ListRolePermissionsOptions,\n ListRolesOptions,\n Role,\n RoleEntityPermission,\n UpdateRoleRequest,\n} from './types.js'\n\nconst ROLES_BASE_PATH = '/accounts/v1/roles'\n\n/**\n * Service for managing roles.\n * Handles role CRUD operations and permission assignments.\n */\nexport interface RoleService {\n /**\n * Lists roles with optional filtering.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param options - Filter and pagination options\n * @returns Async iterator over roles\n *\n * @example\n * ```ts\n * // Iterate over all roles\n * for await (const role of service.list()) {\n * console.log(role.name);\n * }\n *\n * // With filtering\n * for await (const role of service.list({ org_id: 'org-123' })) {\n * console.log(role.slug);\n * }\n * ```\n */\n list(options?: ListRolesOptions): PageIterator<Role, ListRolesOptions>\n\n /**\n * Gets a single role by slug.\n *\n * @param slug - Role slug\n * @returns The role\n * @throws {ProteosError} If role not found (404)\n */\n get(slug: string): Promise<Role>\n\n /**\n * Creates a new role.\n *\n * @param request - Role creation request\n * @returns The created role\n * @throws {ProteosError} If validation fails (400) or conflict (409)\n *\n * @example\n * ```ts\n * const role = await service.create({\n * org_id: 'org-123',\n * slug: 'admin',\n * name: 'Administrator',\n * description: 'Full system access',\n * });\n * ```\n */\n create(request: CreateRoleRequest): Promise<Role>\n\n /**\n * Creates or updates a role idempotently by slug. The URL slug wins on\n * mismatch with the body's slug field (`PUT /accounts/v1/roles/:slug`). The\n * org is taken from the caller's token, not the body.\n *\n * @param slug - Role slug\n * @param request - Full role body\n * @returns The created or updated role\n */\n upsert(slug: string, request: CreateRoleRequest): Promise<Role>\n\n /**\n * Updates an existing role.\n *\n * @param slug - Role slug\n * @param request - Fields to update\n * @returns The updated role\n * @throws {ProteosError} If role not found (404) or validation fails (400)\n */\n update(slug: string, request: UpdateRoleRequest): Promise<Role>\n\n /**\n * Deletes a role.\n *\n * @param slug - Role slug\n * @throws {ProteosError} If role not found (404), or if the role still has\n * entity permissions attached (400 `role_deletion_not_allowed`) — remove\n * the grants first\n */\n delete(slug: string): Promise<void>\n\n /**\n * Fetches a single page of roles.\n *\n * @param options - Filter and pagination options (including `page`)\n * @returns A single page of roles with pagination metadata\n */\n listPage(options?: ListRolesOptions): Promise<ListResult<Role>>\n\n /**\n * Gets permissions assigned to a role.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param roleSlug - Role slug\n * @param options - Filter and pagination options\n * @returns Async iterator over role entity permissions\n */\n getPermissions(\n roleSlug: string,\n options?: ListRolePermissionsOptions,\n ): PageIterator<RoleEntityPermission, ListRolePermissionsOptions>\n\n /**\n * Assigns a permission to a role for an entity.\n *\n * @param roleSlug - Role slug\n * @param request - Permission assignment request\n * @returns The created role entity permission\n * @throws {ProteosError} If role or entity not found (404)\n */\n assignPermission(\n roleSlug: string,\n request: AssignPermissionRequest,\n ): Promise<RoleEntityPermission>\n\n /**\n * Removes a permission from a role.\n *\n * @param roleSlug - Role slug\n * @param permissionId - Permission ID to remove\n * @throws {ProteosError} If permission not found (404)\n */\n removePermission(roleSlug: string, permissionId: string): Promise<void>\n}\n\n/**\n * Implementation of RoleService.\n */\nexport class RoleServiceImpl implements RoleService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListRolesOptions = {}): PageIterator<Role, ListRolesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListRolesOptions = {}): Promise<ListResult<Role>> {\n return this.client.requestWithQuery<ListResult<Role>>('GET', ROLES_BASE_PATH, options)\n }\n\n async get(slug: string): Promise<Role> {\n return this.client.request<Role>('GET', `${ROLES_BASE_PATH}/${slug}`)\n }\n\n async create(request: CreateRoleRequest): Promise<Role> {\n return this.client.request<Role>('POST', ROLES_BASE_PATH, request)\n }\n\n async upsert(slug: string, request: CreateRoleRequest): Promise<Role> {\n return this.client.request<Role>('PUT', `${ROLES_BASE_PATH}/${slug}`, { ...request, slug })\n }\n\n async update(slug: string, request: UpdateRoleRequest): Promise<Role> {\n return this.client.request<Role>('PATCH', `${ROLES_BASE_PATH}/${slug}`, request)\n }\n\n async delete(slug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${ROLES_BASE_PATH}/${slug}`)\n }\n\n getPermissions(\n roleSlug: string,\n options: ListRolePermissionsOptions = {},\n ): PageIterator<RoleEntityPermission, ListRolePermissionsOptions> {\n return new PageIterator((opts) => this.fetchPermissionsPage(roleSlug, opts), options)\n }\n\n async assignPermission(\n roleSlug: string,\n request: AssignPermissionRequest,\n ): Promise<RoleEntityPermission> {\n return this.client.request<RoleEntityPermission>(\n 'POST',\n `${ROLES_BASE_PATH}/${roleSlug}/permissions`,\n request,\n )\n }\n\n async removePermission(roleSlug: string, permissionId: string): Promise<void> {\n await this.client.request<void>(\n 'DELETE',\n `${ROLES_BASE_PATH}/${roleSlug}/permissions/${permissionId}`,\n )\n }\n\n private async fetchPermissionsPage(\n roleSlug: string,\n options: ListRolePermissionsOptions,\n ): Promise<ListResult<RoleEntityPermission>> {\n return this.client.requestWithQuery<ListResult<RoleEntityPermission>>(\n 'GET',\n `${ROLES_BASE_PATH}/${roleSlug}/permissions`,\n options,\n )\n }\n}\n","/**\n * Common error codes returned by the Proteos API.\n */\nexport const ErrorCode = {\n NOT_FOUND: 'not_found',\n UNAUTHORIZED: 'unauthorized',\n FORBIDDEN: 'forbidden',\n BAD_REQUEST: 'bad_request',\n CONFLICT: 'conflict',\n INTERNAL_SERVER_ERROR: 'internal_server_error',\n INVALID_PAYLOAD: 'invalid_payload',\n INVALID_PERSONA: 'invalid_persona',\n /** The server was never reached: DNS, connection refused, network down.\n * Carried with httpStatus 0. */\n NETWORK_ERROR: 'network_error',\n /** The request timed out client-side. Carried with httpStatus 0. */\n REQUEST_TIMEOUT: 'request_timeout',\n} as const\n\nexport type ErrorCodeType = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Error returned by the Proteos API.\n * Contains HTTP status code, error code, and human-readable message.\n */\nexport class ProteosError extends Error {\n /** HTTP status code of the response */\n readonly httpStatus: number\n /** API error code (e.g., 'not_found', 'unauthorized') */\n readonly code: ErrorCodeType | string\n /**\n * Optional machine-readable payload beside the message — e.g. a denied send's\n * `earliest_allowed_at` / `rule_id`, the offending `contact_id`. Absent on\n * most errors.\n */\n readonly details: Record<string, unknown> | undefined\n\n constructor(\n message: string,\n httpStatus: number,\n code: ErrorCodeType | string,\n details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'ProteosError'\n this.httpStatus = httpStatus\n this.code = code\n this.details = details\n\n // V8-specific API for cleaner stack traces; not present in all runtimes\n const v8Capture = (Error as unknown as { captureStackTrace?: (t: object, c: unknown) => void })\n .captureStackTrace\n if (v8Capture) v8Capture(this, this.constructor)\n }\n\n /**\n * Returns a formatted string representation of the error.\n */\n override toString(): string {\n return `${this.code}: ${this.message} (HTTP ${this.httpStatus})`\n }\n}\n\n/**\n * Type guard to check if an error is a ProteosError.\n */\nexport function isProteosError(error: unknown): error is ProteosError {\n return error instanceof ProteosError\n}\n\n/**\n * Type guard to check if an error is a 404 Not Found error.\n */\nexport function isNotFound(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 404\n}\n\n/**\n * Type guard to check if an error is a 401 Unauthorized error.\n */\nexport function isUnauthorized(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 401\n}\n\n/**\n * Type guard to check if an error is a 403 Forbidden error.\n */\nexport function isForbidden(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 403\n}\n\n/**\n * Type guard to check if an error is a 400 Bad Request error.\n */\nexport function isBadRequest(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 400\n}\n\n/**\n * Type guard to check if an error is a 409 Conflict error.\n */\nexport function isConflict(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 409\n}\n\n/**\n * Maps HTTP status codes to default error codes.\n */\nexport function getDefaultErrorCode(httpStatus: number): ErrorCodeType | string {\n switch (httpStatus) {\n case 400:\n return ErrorCode.BAD_REQUEST\n case 401:\n return ErrorCode.UNAUTHORIZED\n case 403:\n return ErrorCode.FORBIDDEN\n case 404:\n return ErrorCode.NOT_FOUND\n case 409:\n return ErrorCode.CONFLICT\n default:\n return ErrorCode.INTERNAL_SERVER_ERROR\n }\n}\n\n/**\n * Response shape for API error responses.\n */\nexport interface ApiErrorResponse {\n code?: string\n message?: string\n details?: Record<string, unknown>\n}\n\n/**\n * Parses an error response from the API and creates a ProteosError.\n */\nexport async function parseErrorResponse(response: Response): Promise<ProteosError> {\n const httpStatus = response.status\n let code: string = getDefaultErrorCode(httpStatus)\n let message = 'Unknown error'\n let details: Record<string, unknown> | undefined\n\n try {\n const body = await response.text()\n\n // Try to parse as JSON\n try {\n const json = JSON.parse(body) as ApiErrorResponse\n if (json.code) {\n code = json.code\n }\n if (json.message) {\n message = json.message\n } else {\n message = body || `HTTP ${httpStatus}`\n }\n if (json.details && typeof json.details === 'object') {\n details = json.details\n }\n } catch {\n // Not JSON, use body as message\n message = body.trim() || `HTTP ${httpStatus}`\n }\n } catch {\n message = `HTTP ${httpStatus}`\n }\n\n return new ProteosError(message, httpStatus, code, details)\n}\n","import type { ProteosClient } from '../client.js'\nimport { ProteosError } from '../errors.js'\nimport type { PrincipalRef } from '../meta/types.js'\nimport type { SharePermission, ShareRequest, ShareRow } from './types.js'\n\n/**\n * Which service owns each shareable platform entity.\n *\n * Sharing is decided by the service that OWNS the resource — whether a caller\n * may grant depends on what the row itself grants them (its granting\n * attributes, or an owner column), which only that service can read. So the\n * write endpoint is per-service by necessity.\n *\n * This map is the client-side seam that hides that. Callers name an entity, not\n * a service, so if sharing is ever centralized behind one endpoint the change is\n * a one-line edit here and no caller moves.\n *\n * Anything NOT listed is a user-defined entity, which data-service owns — that\n * set is unbounded and appears at runtime, so it is the default rather than an\n * enumeration.\n */\nconst PLATFORM_ENTITY_SERVICE: Readonly<Record<string, string>> = {\n // Agent suite (agent-service)\n agents: '/agents',\n prompts: '/agents',\n skills: '/agents',\n tools: '/agents',\n toolsets: '/agents',\n 'mcp-servers': '/agents',\n 'agent-sessions': '/agents',\n // Knowledge (knowledge-service)\n 'knowledge-spaces': '/knowledge',\n 'knowledge-nodes': '/knowledge',\n // Conversations (conversation-service)\n conversations: '/conversations',\n connections: '/conversations',\n}\n\n/**\n * The services that actually serve `/v1/shares` today.\n *\n * Deliberately separate from the map above: a service that has not adopted\n * the endpoint yet must fail with a clear message rather than a bare 404 that\n * reads like the record does not exist.\n */\nconst SERVICES_WITH_SHARING: ReadonlySet<string> = new Set([\n '/data',\n '/knowledge',\n '/agents',\n '/conversations',\n])\n\n/** Records live in data-service; user-defined entities are the unlisted majority. */\nconst DEFAULT_SERVICE = '/data'\n\n/**\n * Resolves the share endpoint for an entity slug.\n *\n * Exported for tests and for callers that want to check support before offering\n * a share affordance in a UI.\n */\nexport function shareRouteFor(entitySlug: string): string {\n const service = PLATFORM_ENTITY_SERVICE[entitySlug] ?? DEFAULT_SERVICE\n if (!SERVICES_WITH_SHARING.has(service)) {\n throw new ProteosError(\n `Sharing is not available for '${entitySlug}' yet — ${service.slice(1)}-service does not serve a share endpoint.`,\n 501,\n 'sharing_not_supported',\n )\n }\n return `${service}/v1/shares`\n}\n\n/** True when `entitySlug` can be shared today. */\nexport function isShareable(entitySlug: string): boolean {\n const service = PLATFORM_ENTITY_SERVICE[entitySlug] ?? DEFAULT_SERVICE\n return SERVICES_WITH_SHARING.has(service)\n}\n\n/**\n * Sharing an individual resource with a principal — a person, an agent, an API\n * client, a team, or the whole organization.\n *\n * A share grants access to ONE resource, which is a different thing from a role:\n * a role grants a permission on an entity TYPE (every deal), a share grants it\n * on an INSTANCE (this deal). The two compose — a share gives nothing to someone\n * holding no grant on the entity type at all, which bounds its blast radius to a\n * population already authorized for that kind of resource.\n *\n * Callers name an ENTITY, never a service. Which service handles the write is\n * this module's problem.\n *\n * Who may share: the resource's owner, or someone holding the plain (unscoped)\n * permission on the entity. Notably NOT a share recipient — access held only\n * through a share cannot be passed on, and cannot be turned into ownership.\n */\nexport interface ShareService {\n /**\n * Grants a principal access to one resource.\n *\n * Granting `write` or `delete` implies `read`: a principal who cannot see a\n * resource must never be able to edit it, so the read is granted alongside.\n *\n * @throws {ProteosError} 403 `share_not_permitted` when the caller holds their\n * own access only through a share; 403 `principal_not_in_org` when the\n * recipient is outside the caller's organization (rejected outright rather\n * than written inert, which would become a live grant the moment they joined);\n * 404 when the resource does not exist or is not visible to the caller;\n * 501 `sharing_not_supported` when the owning service has no share endpoint.\n */\n share(\n entitySlug: string,\n recordId: string,\n principal: PrincipalRef,\n permission: SharePermission,\n ): Promise<void>\n\n /**\n * Revokes a principal's access to one resource.\n *\n * Revoking `read` CASCADES to `write` and `delete` — an edit right on\n * something someone can no longer see would be incoherent.\n *\n * Revocation is deliberately wider than granting: the owner, anyone holding\n * the unscoped `write` permission, and platform admins may all revoke. Erring\n * permissive costs nothing here, while erring strict would strand grants\n * nobody could clean up.\n */\n unshare(\n entitySlug: string,\n recordId: string,\n principal: PrincipalRef,\n permission: SharePermission,\n ): Promise<void>\n\n /**\n * Lists a resource's shares.\n *\n * Gated to the population that may REVOKE them — the owner, unscoped-write\n * holders, and platform admins. Record read is deliberately not enough: a\n * share list discloses org structure (\"this deal is visible to team:legal\").\n *\n * @throws {ProteosError} 403 `share_listing_not_permitted` otherwise.\n */\n listShares(entitySlug: string, recordId: string): Promise<ShareRow[]>\n}\n\nexport class ShareServiceImpl implements ShareService {\n constructor(private readonly client: ProteosClient) {}\n\n async share(\n entitySlug: string,\n recordId: string,\n principal: PrincipalRef,\n permission: SharePermission,\n ): Promise<void> {\n await this.client.request<void>('POST', shareRouteFor(entitySlug), {\n entity_slug: entitySlug,\n record_id: recordId,\n principal,\n permission,\n } satisfies ShareRequest)\n }\n\n async unshare(\n entitySlug: string,\n recordId: string,\n principal: PrincipalRef,\n permission: SharePermission,\n ): Promise<void> {\n await this.client.request<void>('DELETE', shareRouteFor(entitySlug), {\n entity_slug: entitySlug,\n record_id: recordId,\n principal,\n permission,\n } satisfies ShareRequest)\n }\n\n async listShares(entitySlug: string, recordId: string): Promise<ShareRow[]> {\n const query = new URLSearchParams({ entity_slug: entitySlug, record_id: recordId })\n const response = await this.client.request<{ shares: ShareRow[] }>(\n 'GET',\n `${shareRouteFor(entitySlug)}?${query.toString()}`,\n )\n return response.shares ?? []\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n AddTeamMemberRequest,\n CreateTeamRequest,\n ListTeamMembersOptions,\n ListTeamsOptions,\n Team,\n TeamMember,\n UpdateTeamRequest,\n} from './types.js'\n\nconst TEAMS_BASE_PATH = '/accounts/v1/teams'\n\n/**\n * Service for managing teams — the org's structure, and a principal that can\n * hold access anywhere a user can.\n *\n * Team hierarchy rolls UP: a member of a child team counts as a member of every\n * ancestor **for grants made to that ancestor**. Granting `sales` reaches the\n * members of `sales-emea`; granting `sales-emea` never reaches someone who is\n * only in `sales`. This is the direction people get backwards.\n */\nexport interface TeamService {\n /**\n * Lists teams with optional filtering.\n * Returns an async iterator that automatically handles pagination.\n */\n list(options?: ListTeamsOptions): PageIterator<Team, ListTeamsOptions>\n\n /** Fetches a single page of teams. */\n listPage(options?: ListTeamsOptions): Promise<ListResult<Team>>\n\n /**\n * Gets a single team by slug.\n * @throws {ProteosError} If the team is not found (404)\n */\n get(slug: string): Promise<Team>\n\n /**\n * Creates a team, optionally nested under an existing one.\n * @throws {ProteosError} If the parent would create a cycle or exceed the\n * maximum depth (400 `team_hierarchy_invalid`)\n */\n create(request: CreateTeamRequest): Promise<Team>\n\n /**\n * Updates a team's name, description or parent.\n *\n * The slug cannot be changed: it is half the primary key and every grant\n * references `team:<orgId>/<slug>`, so a rename would orphan them. Pass an\n * empty `parent_team_slug` to promote the team to a root.\n */\n update(slug: string, request: UpdateTeamRequest): Promise<Team>\n\n /**\n * Deletes a team.\n * @throws {ProteosError} If the team still has members or child teams\n * (400 `team_deletion_not_allowed`)\n */\n delete(slug: string): Promise<void>\n\n /**\n * Lists a team's DIRECT members. Membership of ancestor teams is derived, not\n * stored, so it does not appear here.\n */\n getMembers(\n slug: string,\n options?: ListTeamMembersOptions,\n ): PageIterator<TeamMember, ListTeamMembersOptions>\n\n /** Adds a user to a team. */\n addMember(slug: string, request: AddTeamMemberRequest): Promise<TeamMember>\n\n /** Removes a user from a team. */\n removeMember(slug: string, userId: string): Promise<void>\n}\n\n/**\n * Implementation of TeamService.\n */\nexport class TeamServiceImpl implements TeamService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListTeamsOptions = {}): PageIterator<Team, ListTeamsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListTeamsOptions = {}): Promise<ListResult<Team>> {\n return this.client.requestWithQuery<ListResult<Team>>('GET', TEAMS_BASE_PATH, options)\n }\n\n async get(slug: string): Promise<Team> {\n return this.client.request<Team>('GET', `${TEAMS_BASE_PATH}/${slug}`)\n }\n\n async create(request: CreateTeamRequest): Promise<Team> {\n return this.client.request<Team>('POST', TEAMS_BASE_PATH, request)\n }\n\n async update(slug: string, request: UpdateTeamRequest): Promise<Team> {\n return this.client.request<Team>('PATCH', `${TEAMS_BASE_PATH}/${slug}`, request)\n }\n\n async delete(slug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${TEAMS_BASE_PATH}/${slug}`)\n }\n\n getMembers(\n slug: string,\n options: ListTeamMembersOptions = {},\n ): PageIterator<TeamMember, ListTeamMembersOptions> {\n return new PageIterator((opts) => this.fetchMembersPage(slug, opts), options)\n }\n\n async addMember(slug: string, request: AddTeamMemberRequest): Promise<TeamMember> {\n return this.client.request<TeamMember>('POST', `${TEAMS_BASE_PATH}/${slug}/members`, request)\n }\n\n async removeMember(slug: string, userId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${TEAMS_BASE_PATH}/${slug}/members/${userId}`)\n }\n\n private async fetchMembersPage(\n slug: string,\n options: ListTeamMembersOptions,\n ): Promise<ListResult<TeamMember>> {\n return this.client.requestWithQuery<ListResult<TeamMember>>(\n 'GET',\n `${TEAMS_BASE_PATH}/${slug}/members`,\n options,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type { ListUserProfileAssignmentsOptions, UserProfileAssignment } from './types.js'\n\nconst USER_PROFILE_ASSIGNMENTS_BASE_PATH = '/accounts/v1/user-profile-assignments'\n\n/**\n * Service for the org-wide user-profile-assignment listing: \"who holds which\n * profile\" in one request (a profile's member roster, profile badges on a\n * user list). Per-user reads and writes stay on {@link UserService}.\n */\nexport interface UserProfileAssignmentService {\n /** Lists profile assignments across all users of the caller's org. */\n list(\n options?: ListUserProfileAssignmentsOptions,\n ): PageIterator<UserProfileAssignment, ListUserProfileAssignmentsOptions>\n\n /** Fetches a single page of profile assignments. */\n listPage(options?: ListUserProfileAssignmentsOptions): Promise<ListResult<UserProfileAssignment>>\n}\n\nexport class UserProfileAssignmentServiceImpl implements UserProfileAssignmentService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListUserProfileAssignmentsOptions = {},\n ): PageIterator<UserProfileAssignment, ListUserProfileAssignmentsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(\n options: ListUserProfileAssignmentsOptions = {},\n ): Promise<ListResult<UserProfileAssignment>> {\n return this.client.requestWithQuery<ListResult<UserProfileAssignment>>(\n 'GET',\n USER_PROFILE_ASSIGNMENTS_BASE_PATH,\n options,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type { ListOrgUserRoleAssignmentsOptions, UserRoleAssignment } from './types.js'\n\nconst USER_ROLE_ASSIGNMENTS_BASE_PATH = '/accounts/v1/user-role-assignments'\n\n/**\n * Service for the org-wide user-role-assignment listing.\n *\n * One request answers \"who holds which role\" across the whole org — the admin\n * view joining users to their roles (role badges on a user list, a role's\n * member roster, member counts) without a per-user fan-out. Per-user reads and\n * writes stay on {@link UserService} (`users.getRoles` / `assignRole` /\n * `unassignRole`).\n */\nexport interface UserRoleAssignmentService {\n /**\n * Lists role assignments across all users of the caller's org.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param options - Filter and pagination options (`role_slug`, `user_id`)\n * @returns Async iterator over user role assignments\n *\n * @example\n * ```ts\n * // Everyone holding the sales role\n * const sales = await service.list({ role_slug: 'sales' }).all();\n * ```\n */\n list(\n options?: ListOrgUserRoleAssignmentsOptions,\n ): PageIterator<UserRoleAssignment, ListOrgUserRoleAssignmentsOptions>\n\n /**\n * Fetches a single page of role assignments.\n *\n * @param options - Filter and pagination options (including `page`)\n * @returns A single page of assignments with pagination metadata\n */\n listPage(options?: ListOrgUserRoleAssignmentsOptions): Promise<ListResult<UserRoleAssignment>>\n}\n\n/**\n * Implementation of UserRoleAssignmentService.\n */\nexport class UserRoleAssignmentServiceImpl implements UserRoleAssignmentService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListOrgUserRoleAssignmentsOptions = {},\n ): PageIterator<UserRoleAssignment, ListOrgUserRoleAssignmentsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(\n options: ListOrgUserRoleAssignmentsOptions = {},\n ): Promise<ListResult<UserRoleAssignment>> {\n return this.client.requestWithQuery<ListResult<UserRoleAssignment>>(\n 'GET',\n USER_ROLE_ASSIGNMENTS_BASE_PATH,\n options,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n ApiKey,\n AssignRoleRequest,\n CreateApiKeyRequest,\n CreatedApiKey,\n CreateUserRequest,\n ListUserRoleAssignmentsOptions,\n ListUsersOptions,\n SetProfileRequest,\n UpdateUserRequest,\n User,\n UserProfileAssignment,\n UserRoleAssignment,\n} from './types.js'\n\nconst USERS_BASE_PATH = '/accounts/v1/users'\n\n/**\n * Service for managing users.\n * Handles user CRUD operations and role assignments.\n */\nexport interface UserService {\n /**\n * Lists users with optional filtering.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param options - Filter and pagination options\n * @returns Async iterator over users\n *\n * @example\n * ```ts\n * // Iterate over all users\n * for await (const user of service.list()) {\n * console.log(user.email);\n * }\n *\n * // With filtering\n * for await (const user of service.list({ email: 'john@example.com' })) {\n * console.log(user.given_name);\n * }\n * ```\n */\n list(options?: ListUsersOptions): PageIterator<User, ListUsersOptions>\n\n /**\n * Gets a single user by ID.\n *\n * @param id - User ID\n * @returns The user\n * @throws {ProteosError} If user not found (404)\n */\n get(id: string): Promise<User>\n\n /**\n * Creates a new user.\n *\n * @param request - User creation request\n * @returns The created user\n * @throws {ProteosError} If validation fails (400) or conflict (409)\n *\n * @example\n * ```ts\n * const user = await service.create({\n * given_name: 'John',\n * family_name: 'Doe',\n * email: 'john.doe@example.com',\n * });\n * ```\n */\n create(request: CreateUserRequest): Promise<User>\n\n /**\n * Updates an existing user.\n *\n * @param id - User ID\n * @param request - Fields to update\n * @returns The updated user\n * @throws {ProteosError} If user not found (404) or validation fails (400)\n */\n update(id: string, request: UpdateUserRequest): Promise<User>\n\n /**\n * Fetches a single page of users.\n *\n * @param options - Filter and pagination options (including `page`)\n * @returns A single page of users with pagination metadata\n */\n listPage(options?: ListUsersOptions): Promise<ListResult<User>>\n\n /**\n * Gets roles assigned to a user.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param userId - User ID\n * @param options - Filter and pagination options\n * @returns Async iterator over user role assignments\n */\n getRoles(\n userId: string,\n options?: ListUserRoleAssignmentsOptions,\n ): PageIterator<UserRoleAssignment, ListUserRoleAssignmentsOptions>\n\n /**\n * Assigns a role to a user.\n *\n * @param userId - User ID\n * @param request - Role assignment request\n * @returns The created user role assignment\n * @throws {ProteosError} If user or role not found (404)\n */\n assignRole(userId: string, request: AssignRoleRequest): Promise<UserRoleAssignment>\n\n /**\n * Removes a role from a user.\n *\n * @param userId - User ID\n * @param roleSlug - Role slug to unassign\n * @throws {ProteosError} If assignment not found (404)\n */\n unassignRole(userId: string, roleSlug: string): Promise<void>\n\n /**\n * Gets the user's profile assignment in the caller's org.\n *\n * @throws {ProteosError} 404 when the user has no profile\n */\n getProfile(userId: string): Promise<UserProfileAssignment>\n\n /**\n * Sets (replaces) the user's profile in the caller's org — one profile per\n * user per org.\n *\n * @throws {ProteosError} 404 when the user or the profile slug is unknown;\n * 400 `user_not_in_org` when the user holds no role in the org\n */\n setProfile(userId: string, request: SetProfileRequest): Promise<UserProfileAssignment>\n\n /** Clears the user's profile (back to every app's default configuration). */\n clearProfile(userId: string): Promise<void>\n\n /**\n * Lists a user's API keys (display hints only — never tokens).\n *\n * @param userId - User ID, or `'me'` for the calling user\n */\n listApiKeys(userId: string): Promise<ApiKey[]>\n\n /**\n * Creates an API key for the user. The response carries the full token\n * exactly once; it cannot be read again. Requires a JWT session — requests\n * authenticated with an API key are rejected (403).\n *\n * @param userId - User ID, or `'me'` for the calling user\n * @param request - Key name, optional org binding and expiry\n */\n createApiKey(userId: string, request: CreateApiKeyRequest): Promise<CreatedApiKey>\n\n /**\n * Deletes (revokes) an API key. Other services may keep accepting the key\n * for up to their verification-cache TTL (~60s).\n * Unlike create and list, it also works when the request is authenticated\n * with an API key, so a key can revoke itself.\n *\n * @param userId - User ID, or `'me'` for the calling user\n * @param keyId - API key ID\n * @throws {ProteosError} If the key is not found under this user (404)\n */\n deleteApiKey(userId: string, keyId: string): Promise<void>\n}\n\n/**\n * Implementation of UserService.\n */\nexport class UserServiceImpl implements UserService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListUsersOptions = {}): PageIterator<User, ListUsersOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListUsersOptions = {}): Promise<ListResult<User>> {\n return this.client.requestWithQuery<ListResult<User>>('GET', USERS_BASE_PATH, options)\n }\n\n async get(id: string): Promise<User> {\n return this.client.request<User>('GET', `${USERS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateUserRequest): Promise<User> {\n return this.client.request<User>('POST', USERS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateUserRequest): Promise<User> {\n return this.client.request<User>('PATCH', `${USERS_BASE_PATH}/${id}`, request)\n }\n\n getRoles(\n userId: string,\n options: ListUserRoleAssignmentsOptions = {},\n ): PageIterator<UserRoleAssignment, ListUserRoleAssignmentsOptions> {\n return new PageIterator((opts) => this.fetchRolesPage(userId, opts), options)\n }\n\n async assignRole(userId: string, request: AssignRoleRequest): Promise<UserRoleAssignment> {\n return this.client.request<UserRoleAssignment>(\n 'POST',\n `${USERS_BASE_PATH}/${userId}/roles`,\n request,\n )\n }\n\n async unassignRole(userId: string, roleSlug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${USERS_BASE_PATH}/${userId}/roles/${roleSlug}`)\n }\n\n async getProfile(userId: string): Promise<UserProfileAssignment> {\n return this.client.request<UserProfileAssignment>('GET', `${USERS_BASE_PATH}/${userId}/profile`)\n }\n\n async setProfile(userId: string, request: SetProfileRequest): Promise<UserProfileAssignment> {\n return this.client.request<UserProfileAssignment>(\n 'PUT',\n `${USERS_BASE_PATH}/${userId}/profile`,\n request,\n )\n }\n\n async clearProfile(userId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${USERS_BASE_PATH}/${userId}/profile`)\n }\n\n async listApiKeys(userId: string): Promise<ApiKey[]> {\n const response = await this.client.request<{ data: ApiKey[] }>(\n 'GET',\n `${USERS_BASE_PATH}/${userId}/api-keys`,\n )\n return response.data\n }\n\n async createApiKey(userId: string, request: CreateApiKeyRequest): Promise<CreatedApiKey> {\n return this.client.request<CreatedApiKey>(\n 'POST',\n `${USERS_BASE_PATH}/${userId}/api-keys`,\n request,\n )\n }\n\n async deleteApiKey(userId: string, keyId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${USERS_BASE_PATH}/${userId}/api-keys/${keyId}`)\n }\n\n private async fetchRolesPage(\n userId: string,\n options: ListUserRoleAssignmentsOptions,\n ): Promise<ListResult<UserRoleAssignment>> {\n return this.client.requestWithQuery<ListResult<UserRoleAssignment>>(\n 'GET',\n `${USERS_BASE_PATH}/${userId}/roles`,\n options,\n )\n }\n}\n","/**\n * Canonical platform entities — the built-in system resources (users, roles,\n * files, entities, …) that are permission targets alongside user-defined\n * entities. Hand-maintained mirror of the Go registry in\n * packages/go/model/platform/entities.go — keep the two in sync.\n *\n * Used by the role-permission UI to list grantable platform entities next to\n * user-defined entities (from `meta.entities.list()`); permissions key on a\n * free-form `entity_slug`, so the two are assigned uniformly.\n */\nexport interface PlatformEntity {\n slug: string\n /** Display label for the role-permission dropdown. */\n name: string\n}\n\n/** The canonical platform entities, in display order. */\nexport const PLATFORM_ENTITIES: readonly PlatformEntity[] = [\n // Access (account-service)\n { slug: 'organizations', name: 'Organizations' },\n { slug: 'users', name: 'Users' },\n { slug: 'roles', name: 'Roles' },\n { slug: 'user-role-assignments', name: 'User Role Assignments' },\n { slug: 'role-entity-permissions', name: 'Role Entity Permissions' },\n // Teams are the org's structure and a principal that can hold access anywhere\n // a user can. Membership is a separate slug: seeing the org chart and changing\n // who is in it are different decisions, and membership is what moves access.\n { slug: 'teams', name: 'Teams' },\n { slug: 'team-members', name: 'Team Members' },\n // Profiles are the org's user-types (UI defaults; app configurations key on\n // them). ONE per user per org. Managing and assigning are separate grants.\n { slug: 'profiles', name: 'Profiles' },\n { slug: 'user-profile-assignments', name: 'User Profile Assignments' },\n // The share audit trail — a distinct grant from the resources it references.\n // Schema / content (metadata-service)\n { slug: 'entities', name: 'Entities' },\n { slug: 'pages', name: 'Pages' },\n { slug: 'menu-configurations', name: 'Menu Configurations' },\n { slug: 'apps', name: 'Apps' },\n // Typed (app × profile) binding rows: home, menu, agents, record pages.\n { slug: 'app-configurations', name: 'App Configurations' },\n { slug: 'components', name: 'Components' },\n { slug: 'lists', name: 'Lists' },\n { slug: 'list-views', name: 'List Views' },\n { slug: 'design-references', name: 'Design References' },\n // System (metadata-service)\n { slug: 'modules', name: 'Modules' },\n { slug: 'variables', name: 'Variables' },\n { slug: 'deployments', name: 'Deployments' },\n // Records (data-service): proposed record writes awaiting review. read =\n // list/get drafts; write = propose, reject and (with the entity's own\n // write/delete) approve.\n { slug: 'record-drafts', name: 'Record Drafts' },\n // Stored SQL queries — what the Reports tab saves and shares. Scoped by\n // default: a member with no grant reaches their own queries and those\n // shared with them; the unscoped grant reaches every query in the org.\n { slug: 'queries', name: 'Queries' },\n // Storage (storage-service)\n { slug: 'files', name: 'Files' },\n // Automation (function-service)\n { slug: 'hooks', name: 'Hooks' },\n { slug: 'actions', name: 'Actions' },\n // Workflows (workflow-service)\n { slug: 'workflows', name: 'Workflows' },\n { slug: 'workflow-executions', name: 'Workflow Executions' },\n // Knowledge (knowledge-service)\n { slug: 'knowledge-nodes', name: 'Knowledge Nodes' },\n { slug: 'knowledge-links', name: 'Knowledge Links' },\n { slug: 'knowledge-labels', name: 'Knowledge Labels' },\n { slug: 'knowledge-spaces', name: 'Knowledge Spaces' },\n // Agent suite (agent-service)\n { slug: 'agents', name: 'Agents' },\n { slug: 'prompts', name: 'Prompts' },\n { slug: 'skills', name: 'Skills' },\n { slug: 'tools', name: 'Tools' },\n { slug: 'toolsets', name: 'Toolsets' },\n { slug: 'mcp-servers', name: 'MCP Servers' },\n { slug: 'agent-sessions', name: 'Agent Sessions' },\n // Messaging bus (event-service)\n { slug: 'topics', name: 'Topics' },\n { slug: 'events', name: 'Events' },\n // Conversations (conversation-service). NOTE: `connections` is enforced by\n // BOTH conversation-service and connector-service (2026-07 decision) — same\n // concept in both; conversation connections migrate onto connector-service\n // later.\n { slug: 'connections', name: 'Connections' },\n { slug: 'conversations', name: 'Conversations' },\n { slug: 'messages', name: 'Messages' },\n { slug: 'agent-listeners', name: 'Agent Listeners' },\n { slug: 'transcriptions', name: 'Transcriptions' },\n { slug: 'glossary-terms', name: 'Glossary Terms' },\n // Mistranscribed terms proposed by the post-transcription review pass.\n { slug: 'mistranscribed-terms', name: 'Mistranscribed Terms' },\n // Live speech-to-text (the dictation stream) — `read` opens a stream.\n { slug: 'voice', name: 'Voice' },\n // The person-level identity layer (contacts + addresses + merges + consent +\n // erasure) — one grant governs the whole aggregate.\n { slug: 'contacts', name: 'Contacts' },\n // Ingest-time filter rules + their drop-audit events.\n { slug: 'conversation-filters', name: 'Conversation Filters' },\n // The org's conversation taxonomy (read by the pre-summary classifier).\n { slug: 'conversation-types', name: 'Conversation Types' },\n // Generic org-shared audience taxonomy; membership lives on the contact.\n { slug: 'contact-groups', name: 'Contact Groups' },\n // Tone-of-voice synthesis: per-user setups + generated instruction profiles.\n { slug: 'tone-profiles', name: 'Tone Profiles' },\n // Outbound send constraints (windows, connection limits, frequency caps) +\n // their preset catalog.\n { slug: 'sending-rules', name: 'Sending Rules' },\n { slug: 'email-signatures', name: 'Email Signatures' },\n // Reusable messages and snippets, the organisation's and each person's own.\n { slug: 'message-templates', name: 'Message Templates' },\n // The channel_action ledger: acts through a connection that are neither a\n // message nor a reaction (LinkedIn invitations, profile visits, InMail).\n { slug: 'channel-actions', name: 'Channel Actions' },\n // The channel_event ledger: provider-observed delivery / engagement events\n // about outbound messages (delivered, bounced, opened, unsubscribed).\n { slug: 'channel-events', name: 'Channel Events' },\n // Conversation briefs: guidance prepared ahead of a conversation (call, meeting) with a contact.\n { slug: 'conversation-briefs', name: 'Conversation Briefs' },\n // Conversation notes: what a person recorded about a conversation (append log, author-stamped).\n { slug: 'conversation-notes', name: 'Conversation Notes' },\n // Conversation intelligence: the typed questions asked of conversations\n // (definitions), where/when they are evaluated (sets), and the observations\n // they produce incl. their evaluation history (tags).\n { slug: 'conversation-tag-definitions', name: 'Conversation Tag Definitions' },\n { slug: 'conversation-tag-sets', name: 'Conversation Tag Sets' },\n { slug: 'conversation-tags', name: 'Conversation Tags' },\n // Conversation objectives: what a conversation should achieve (definitions)\n // and each definition's standing per conversation (objectives, read-only ledger).\n { slug: 'conversation-objective-definitions', name: 'Conversation Objective Definitions' },\n { slug: 'conversation-objectives', name: 'Conversation Objectives' },\n // Connectors (connector-service). `connections` above is shared; this is the\n // manifest catalog.\n { slug: 'connectors', name: 'Connectors' },\n // Scheduling (scheduling-service)\n { slug: 'calendar-connections', name: 'Calendar Connections' },\n { slug: 'calendars', name: 'Calendars' },\n { slug: 'calendar-events', name: 'Calendar Events' },\n { slug: 'calendar-event-types', name: 'Calendar Event Types' },\n { slug: 'scheduling-links', name: 'Scheduling Links' },\n { slug: 'scheduling-profiles', name: 'Scheduling Profiles' },\n { slug: 'availability-constraints', name: 'Availability Constraints' },\n // Discovery (discovery-service): what users send Proteos to show how they\n // work — screenshots, recordings, written feedback. Mass noun, no plural.\n { slug: 'discovery-evidence', name: 'Discovery Evidence' },\n // Interview guides an admin writes; whoever reads a definition reads its\n // interviews, and whoever writes it invites people.\n { slug: 'discovery-interview-definitions', name: 'Discovery Interview Definitions' },\n // Enrichment (enrichment-service): filling fields through provider\n // waterfalls on the platform's keys. write = start an enrichment run.\n { slug: 'enrichment-runs', name: 'Enrichment Runs' },\n // An entity's enrichment configuration: which attributes get filled, from\n // what, and on which triggers.\n { slug: 'enrichment-mappings', name: 'Enrichment Mappings' },\n // Usage (usage-service): the metering ledger. Read-only and org-level —\n // whoever reads usage reads all of the org's usage.\n { slug: 'usage-records', name: 'Usage Records' },\n] as const\n\n/** Just the platform entity slugs, in canonical order. */\nexport const PLATFORM_ENTITY_SLUGS: readonly string[] = PLATFORM_ENTITIES.map(\n (entity) => entity.slug,\n)\n\n/**\n * Platform entities whose owning service actually enforces the `*_scoped`\n * permission verbs (record-level access grants). Granting `read_scoped` on any\n * other platform entity is legal on the wire but inert — no service narrows\n * by it — so permission UIs only offer the scoped column for these. Extend as\n * services adopt scoped enforcement.\n */\nexport const SCOPED_PLATFORM_ENTITY_SLUGS: readonly string[] = [\n 'knowledge-nodes',\n // agent-service: sessions are owned by their starter; the six config\n // resources by their creator. Scoped lists + /agents/v1/shares.\n 'agent-sessions',\n 'agents',\n 'prompts',\n 'skills',\n 'tools',\n 'toolsets',\n 'mcp-servers',\n // conversation-service: a connection is owned by its owner (user-scoped) or\n // open to the org through its org share (org-scoped); a conversation's rows\n // are stamped once at creation from its connection / parent and extended by\n // shares; messages inherit their conversation. /conversations/v1/shares.\n 'connections',\n 'conversations',\n 'messages',\n // discovery-service: evidence is owned by its creator; a caller holding no\n // grant at all is treated as scoped (own rows), so every org member can\n // send feedback and see what they sent.\n 'discovery-evidence',\n // discovery-service: an interview definition is owned by its creator; its\n // interviews follow it.\n 'discovery-interview-definitions',\n]\n\n/** True when `slug` belongs to a platform entity (reserved; can't be user-created). */\nexport function isPlatformEntity(slug: string): boolean {\n return PLATFORM_ENTITY_SLUGS.includes(slug)\n}\n","import { z } from 'zod'\n\nimport { type PrincipalRef, PrincipalRefSchema } from '../meta/types.js'\nimport type { AuditFields, FileRef, ListOptions } from '../types/common.js'\nimport { AuditFieldsSchema, FileRefSchema } from '../types/common.js'\n\n// ============================================================================\n// Shared Auth Types\n// ============================================================================\n\n/**\n * Base list options with source filters for the auth namespace.\n */\nexport interface AuthListOptions extends ListOptions {\n created_by?: string\n updated_by?: string\n}\n\n// ============================================================================\n// Permission Types\n// ============================================================================\n\n/**\n * Permission level for entity access.\n */\nexport type Permission =\n | 'read'\n | 'write'\n | 'delete'\n // Scoped twins. The grant a role holds decides how much it sees: `read` means\n // every record of the entity in the org, `read_scoped` means only those whose\n // access grants intersect the caller's principals (owned by them, owned by a\n // team they are in, shared with them, or org-wide).\n //\n // The verbs stay independent, so `read` + `write_scoped` reads as \"see every\n // deal, edit only your own\".\n | 'read_scoped'\n | 'write_scoped'\n | 'delete_scoped'\n\n/**\n * Role entity permission - permission granted to a role for a specific entity.\n */\nexport interface RoleEntityPermission extends AuditFields {\n id: string\n org_id: string\n role_slug: string\n entity_slug: string\n permission: Permission\n}\n\nexport const RoleEntityPermissionSchema = AuditFieldsSchema.extend({\n id: z.string(),\n role_slug: z.string(),\n entity_slug: z.string(),\n permission: z.enum(['read', 'write', 'delete', 'read_scoped', 'write_scoped', 'delete_scoped']),\n})\n\n/**\n * Request to assign a permission to a role.\n */\nexport interface AssignPermissionRequest {\n entity_slug: string\n permission: Permission\n}\n\n/**\n * Options for listing role permissions.\n */\nexport interface ListRolePermissionsOptions extends AuthListOptions {\n id?: string\n entity_slug?: string\n permission?: Permission\n}\n\n// ============================================================================\n// User Role Assignment Types\n// ============================================================================\n\n/**\n * User role assignment - a role assigned to a user.\n */\nexport interface UserRoleAssignment extends AuditFields {\n id: string\n user_id: string\n role_slug: string\n org_id: string\n}\n\nexport const UserRoleAssignmentSchema = AuditFieldsSchema.extend({\n id: z.string(),\n user_id: z.string(),\n role_slug: z.string(),\n org_id: z.string(),\n})\n\n/**\n * Request to assign a role to a user.\n */\nexport interface AssignRoleRequest {\n role_slug: string\n}\n\n/**\n * Options for listing user role assignments.\n */\nexport interface ListUserRoleAssignmentsOptions extends AuthListOptions {\n id?: string\n role_slug?: string\n}\n\n/**\n * Options for the org-wide assignment listing (`GET /user-role-assignments`).\n * Unlike {@link ListUserRoleAssignmentsOptions} (which is bound to one user via\n * the path), this one may also filter by `user_id`.\n */\nexport interface ListOrgUserRoleAssignmentsOptions extends AuthListOptions {\n id?: string\n user_id?: string\n role_slug?: string\n}\n\n// ============================================================================\n// User Types\n// ============================================================================\n\n/**\n * User in the system.\n */\nexport interface User extends AuditFields {\n id: string\n email: string\n given_name: string\n family_name: string\n external_id: string\n default_org_id: string\n /**\n * Reference to the user's photo in the storage-service. Absent/null = no\n * photo (clients render initials).\n */\n profile_image?: FileRef | null\n}\n\nexport const UserSchema = AuditFieldsSchema.extend({\n id: z.string(),\n email: z.string(),\n given_name: z.string(),\n family_name: z.string(),\n external_id: z.string(),\n default_org_id: z.string(),\n profile_image: FileRefSchema.nullish(),\n})\n\n/**\n * Request to create a user.\n */\nexport interface CreateUserRequest {\n given_name: string\n family_name: string\n email: string\n default_org_id?: string\n}\n\n/**\n * Request to update a user.\n */\nexport interface UpdateUserRequest {\n given_name?: string\n family_name?: string\n default_org_id?: string\n /**\n * Tri-state: omit = leave unchanged, `null` = remove the photo, a FileRef =\n * set it. Upload the file to the storage-service first and reference it here.\n */\n profile_image?: FileRef | null\n}\n\n/**\n * Caller-scoped `PATCH /me` body. Deliberately narrower than\n * {@link UpdateUserRequest}: a user may edit their own name and photo, but not\n * re-home their account (no `default_org_id`).\n */\nexport interface UpdateMeRequest {\n given_name?: string\n family_name?: string\n /** Tri-state — see {@link UpdateUserRequest.profile_image}. */\n profile_image?: FileRef | null\n}\n\n/**\n * Options for listing users.\n */\nexport interface ListUsersOptions extends AuthListOptions {\n id?: string\n given_name?: string\n family_name?: string\n email?: string\n default_org_id?: string\n}\n\n// ============================================================================\n// Api Key Types\n// ============================================================================\n\n/**\n * A user-scoped API key (pak_ token). Only the display hints\n * (token_prefix/token_suffix) are readable after creation — the full token\n * appears exactly once in {@link CreatedApiKey}.\n */\nexport interface ApiKey extends AuditFields {\n id: string\n user_id: string\n org_id: string\n name: string\n token_prefix: string\n token_suffix: string\n /** ISO timestamp; null = the key never expires. */\n expires_at: string | null\n last_used_at: string | null\n}\n\nexport const ApiKeySchema = AuditFieldsSchema.extend({\n id: z.string(),\n user_id: z.string(),\n org_id: z.string(),\n name: z.string(),\n token_prefix: z.string(),\n token_suffix: z.string(),\n expires_at: z.string().nullable(),\n last_used_at: z.string().nullable(),\n})\n\n/**\n * Create response: the key plus the full token, returned exactly once.\n * Store it immediately — it is not retrievable afterwards.\n */\nexport interface CreatedApiKey extends ApiKey {\n token: string\n}\n\n/**\n * Request to create an API key. Omitting expires_at creates a key that never\n * expires; omitting org_id binds the key to the user's default org.\n */\nexport interface CreateApiKeyRequest {\n name: string\n org_id?: string\n expires_at?: string\n}\n\n// ============================================================================\n// Profile Types\n// ============================================================================\n\n/**\n * Profile — the org's user-type. ONE per user per org (unlike roles, which\n * are many and only decide access). Owns the defaults keyed by subject alone:\n * the app opened after login and the app-switcher allowlist. Metadata app\n * configurations bind per-app defaults (home, menu, agents, record pages) to a\n * profile by slug.\n */\nexport interface Profile extends AuditFields {\n slug: string\n name: string\n org_id: string\n description: string\n /** Module that shipped the profile; '' when authored in the org. */\n module_slug: string\n /** App opened after login; clients fail open to the first visible app. */\n default_app_slug: string\n /** App-switcher allowlist; empty = every app in the org. */\n app_slugs: string[]\n /**\n * Platform-feature allowlist: the areas (`config`, `reports`, `knowledge`,\n * `calendar`, `conversations_own`, `conversations_all`) and Configuration\n * parts (`config_<part>`) the profile shows; empty = every feature,\n * `['none']` = no feature (apps only; `none` cannot be combined). Stored\n * canonical: `conversations_all` ⇒ `conversations_own`, `config_*` ⇒ `config`.\n */\n platform_features: string[]\n}\n\nexport const ProfileSchema = AuditFieldsSchema.extend({\n slug: z.string(),\n name: z.string(),\n org_id: z.string(),\n description: z.string(),\n module_slug: z.string(),\n default_app_slug: z.string(),\n app_slugs: z.array(z.string()),\n // Optional for responses from servers that predate the column.\n platform_features: z.array(z.string()).default([]),\n})\n\nexport interface CreateProfileRequest {\n slug: string\n name: string\n description?: string\n module_slug?: string\n default_app_slug?: string\n app_slugs?: string[]\n platform_features?: string[]\n}\n\nexport interface UpdateProfileRequest {\n name?: string\n description?: string\n module_slug?: string\n default_app_slug?: string\n app_slugs?: string[]\n platform_features?: string[]\n}\n\nexport interface ListProfilesOptions extends AuthListOptions {\n slug?: string\n name?: string\n module_slug?: string\n default_app_slug?: string\n}\n\n/**\n * User profile assignment — a user's ONE profile in an org.\n */\nexport interface UserProfileAssignment extends AuditFields {\n id: string\n user_id: string\n profile_slug: string\n org_id: string\n}\n\nexport const UserProfileAssignmentSchema = AuditFieldsSchema.extend({\n id: z.string(),\n user_id: z.string(),\n profile_slug: z.string(),\n org_id: z.string(),\n})\n\n/** Body of `PUT /users/:id/profile` — replaces the user's profile. */\nexport interface SetProfileRequest {\n profile_slug: string\n}\n\n/** Filters for the org-wide `GET /user-profile-assignments` listing. */\nexport interface ListUserProfileAssignmentsOptions extends AuthListOptions {\n id?: string\n user_id?: string\n profile_slug?: string\n}\n\n// ============================================================================\n// Role Types\n// ============================================================================\n\n/**\n * Role in the system.\n */\nexport interface Role extends AuditFields {\n slug: string\n name: string\n org_id: string\n description: string\n}\n\nexport const RoleSchema = AuditFieldsSchema.extend({\n slug: z.string(),\n name: z.string(),\n org_id: z.string(),\n description: z.string(),\n})\n\n/**\n * Request to create a role.\n */\nexport interface CreateRoleRequest {\n org_id: string\n slug: string\n name: string\n description?: string\n}\n\n/**\n * Request to update a role.\n */\nexport interface UpdateRoleRequest {\n org_id?: string\n name?: string\n description?: string\n}\n\n/**\n * Options for listing roles.\n */\nexport interface ListRolesOptions extends AuthListOptions {\n org_id?: string\n slug?: string\n name?: string\n description?: string\n}\n\n// ============================================================================\n// Team Types\n// ============================================================================\n\n/**\n * A team — a node in the org's structure, and a principal that can hold access\n * anywhere a user can.\n *\n * Hierarchy rolls UP: a member of a child team counts as a member of every\n * ancestor **for grants made to that ancestor**. Granting `sales` reaches the\n * members of `sales-emea`; granting `sales-emea` never reaches someone who is\n * only in `sales`.\n *\n * The slug is immutable — it is half the primary key, and grants reference\n * `team:<orgId>/<slug>`.\n */\nexport interface Team extends AuditFields {\n slug: string\n name: string\n org_id: string\n description: string\n /** This team's parent within the same org; empty for a root team. */\n parent_team_slug: string\n}\n\nexport const TeamSchema = AuditFieldsSchema.extend({\n slug: z.string(),\n name: z.string(),\n org_id: z.string(),\n description: z.string(),\n parent_team_slug: z.string(),\n})\n\n/**\n * One user's DIRECT membership of one team. Membership of ancestor teams is\n * derived rather than stored, so it never appears as a row here.\n */\nexport interface TeamMember extends AuditFields {\n id: string\n org_id: string\n team_slug: string\n user_id: string\n}\n\nexport const TeamMemberSchema = AuditFieldsSchema.extend({\n id: z.string(),\n org_id: z.string(),\n team_slug: z.string(),\n user_id: z.string(),\n})\n\n/**\n * Request to create a team.\n */\nexport interface CreateTeamRequest {\n org_id?: string\n slug: string\n name: string\n description?: string\n /** Nests the team under an existing one in the same org. Omit for a root. */\n parent_team_slug?: string\n}\n\n/**\n * Request to update a team.\n *\n * `slug` is deliberately absent: it is half the primary key and is referenced by\n * every grant as `team:<orgId>/<slug>`, so renaming would orphan them.\n */\nexport interface UpdateTeamRequest {\n name?: string\n description?: string\n /** Re-parents the team; an explicit empty string promotes it to a root. */\n parent_team_slug?: string\n}\n\nexport interface ListTeamsOptions extends AuthListOptions {\n org_id?: string\n slug?: string\n name?: string\n description?: string\n parent_team_slug?: string\n}\n\n/**\n * Request to add a user to a team.\n */\nexport interface AddTeamMemberRequest {\n user_id: string\n}\n\nexport interface ListTeamMembersOptions extends AuthListOptions {\n org_id?: string\n team_slug?: string\n user_id?: string\n}\n\n// ============================================================================\n// Organization Types\n// ============================================================================\n\n/**\n * Organization in the system.\n */\nexport interface Organization extends AuditFields {\n id: string\n name: string\n description: string\n}\n\nexport const OrganizationSchema = AuditFieldsSchema.extend({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n})\n\n/**\n * Request to create an organization.\n */\nexport interface CreateOrganizationRequest {\n name: string\n description?: string\n}\n\n/**\n * Request to update an organization.\n */\nexport interface UpdateOrganizationRequest {\n name?: string\n description?: string\n}\n\n/**\n * Options for listing organizations.\n */\nexport interface ListOrganizationsOptions extends AuthListOptions {\n id?: string\n name?: string\n description?: string\n}\n\n/**\n * The verbs a share can grant. Only these three — a typo'd permission is\n * rejected rather than accepted as a grant that confers nothing.\n */\nexport type SharePermission = 'read' | 'write' | 'delete'\n\n/**\n * The wire shape of a share write. Identical for granting and revoking, and\n * shaped like the grant it produces, so ONE endpoint per owning service serves\n * every entity rather than one endpoint per entity.\n */\nexport interface ShareRequest {\n entity_slug: string\n record_id: string\n principal: PrincipalRef\n permission: SharePermission\n}\n\nexport const SharePermissionSchema = z.enum(['read', 'write', 'delete'])\n\n/**\n * One stored share: a principal holding one verb on one record, with the\n * grantor as provenance. Every row is an explicit share — ownership and\n * granting attributes are evaluated live and never stored.\n */\nexport interface ShareRow {\n entity_slug: string\n record_id: string\n /** Rendered principal string: `user:<id>` | `team:<orgId>/<slug>` | `org:<orgId>`. */\n principal: string\n permission: SharePermission\n created_by?: { type: string; id: string }\n created_at?: string\n}\n\nexport const ShareRequestSchema = z.object({\n entity_slug: z.string(),\n record_id: z.string(),\n principal: PrincipalRefSchema,\n permission: SharePermissionSchema,\n})\n","import type { ProteosClient } from '../client.js'\nimport { type MeService, MeServiceImpl } from './me.js'\nimport { type OrganizationService, OrganizationServiceImpl } from './organizations.js'\nimport { type ProfileService, ProfileServiceImpl } from './profiles.js'\nimport { type RoleService, RoleServiceImpl } from './roles.js'\nimport { type ShareService, ShareServiceImpl } from './shares.js'\nimport { type TeamService, TeamServiceImpl } from './teams.js'\nimport {\n type UserProfileAssignmentService,\n UserProfileAssignmentServiceImpl,\n} from './user-profile-assignments.js'\nimport {\n type UserRoleAssignmentService,\n UserRoleAssignmentServiceImpl,\n} from './user-role-assignments.js'\nimport { type UserService, UserServiceImpl } from './users.js'\n\n/**\n * Client for the Proteos Auth Service API.\n * Provides access to all authentication and authorization services.\n *\n * @example\n * ```ts\n * import { ProteosClient, AccountClient } from 'proteos-sdk';\n *\n * const client = new ProteosClient({\n * baseUrl: 'https://api.proteos.ai',\n * token: 'your-api-token',\n * });\n *\n * const auth = new AccountClient(client);\n *\n * // Use services\n * const users = await auth.users.list().all();\n * const role = await auth.roles.get('admin');\n * const org = await auth.organizations.get('org-123');\n * ```\n */\nexport class AccountClient {\n /**\n * Service for caller-scoped queries (\"who am I\", my organizations).\n */\n readonly me: MeService\n\n /**\n * Service for managing users and their role assignments.\n */\n readonly users: UserService\n\n /**\n * Service for managing roles and their entity permissions.\n */\n readonly roles: RoleService\n\n /**\n * Service for the org-wide user-role-assignment listing (\"who holds which\n * role\" in one request).\n */\n readonly userRoleAssignments: UserRoleAssignmentService\n\n /**\n * Service for managing profiles (the org's user-types, one per user).\n */\n readonly profiles: ProfileService\n\n /**\n * Service for the org-wide user-profile-assignment listing.\n */\n readonly userProfileAssignments: UserProfileAssignmentService\n\n /**\n * Service for managing organizations.\n */\n readonly organizations: OrganizationService\n\n /**\n * Service for managing teams and their membership.\n */\n readonly teams: TeamService\n\n /**\n * Service for sharing individual resources with a principal.\n *\n * Lives here rather than on the owning resource's client because sharing is\n * ONE concept across every resource type — a deal, a conversation, a\n * knowledge space. Callers name an entity; which service handles the write is\n * the SDK's problem, so centralizing it server-side later moves no caller.\n */\n readonly shares: ShareService\n\n /**\n * Creates a new AccountClient instance.\n *\n * @param client - The base ProteosClient to use for API requests\n */\n constructor(client: ProteosClient) {\n this.me = new MeServiceImpl(client)\n this.users = new UserServiceImpl(client)\n this.roles = new RoleServiceImpl(client)\n this.userRoleAssignments = new UserRoleAssignmentServiceImpl(client)\n this.profiles = new ProfileServiceImpl(client)\n this.userProfileAssignments = new UserProfileAssignmentServiceImpl(client)\n this.organizations = new OrganizationServiceImpl(client)\n this.teams = new TeamServiceImpl(client)\n this.shares = new ShareServiceImpl(client)\n }\n}\n\nexport type { MeService } from './me.js'\nexport type { OrganizationService } from './organizations.js'\n// Re-export platform entities (canonical mirror of the Go registry)\nexport type { PlatformEntity } from './platform-entities.js'\nexport {\n isPlatformEntity,\n PLATFORM_ENTITIES,\n PLATFORM_ENTITY_SLUGS,\n SCOPED_PLATFORM_ENTITY_SLUGS,\n} from './platform-entities.js'\nexport type { ProfileService } from './profiles.js'\nexport type { RoleService } from './roles.js'\n// Share routing — exported so a UI can hide a share affordance it cannot serve.\nexport { isShareable, type ShareService, shareRouteFor } from './shares.js'\nexport type { TeamService } from './teams.js'\n// Re-export types\nexport type {\n AddTeamMemberRequest,\n // Api key types\n ApiKey,\n AssignPermissionRequest,\n AssignRoleRequest,\n // Shared types\n AuthListOptions,\n CreateApiKeyRequest,\n CreatedApiKey,\n CreateOrganizationRequest,\n CreateProfileRequest,\n CreateRoleRequest,\n CreateTeamRequest,\n CreateUserRequest,\n ListOrganizationsOptions,\n ListOrgUserRoleAssignmentsOptions,\n ListProfilesOptions,\n ListRolePermissionsOptions,\n ListRolesOptions,\n ListTeamMembersOptions,\n ListTeamsOptions,\n ListUserProfileAssignmentsOptions,\n ListUserRoleAssignmentsOptions,\n ListUsersOptions,\n // Organization types\n Organization,\n // Permission types\n Permission,\n // Profile types\n Profile,\n // Role types\n Role,\n RoleEntityPermission,\n SetProfileRequest,\n // Share types\n SharePermission,\n ShareRequest,\n ShareRow,\n // Team types\n Team,\n TeamMember,\n UpdateMeRequest,\n UpdateOrganizationRequest,\n UpdateProfileRequest,\n UpdateRoleRequest,\n UpdateTeamRequest,\n UpdateUserRequest,\n // User types\n User,\n UserProfileAssignment,\n // User role assignment types\n UserRoleAssignment,\n} from './types.js'\n// Re-export Zod schemas\nexport {\n ApiKeySchema,\n OrganizationSchema,\n ProfileSchema,\n RoleEntityPermissionSchema,\n RoleSchema,\n SharePermissionSchema,\n ShareRequestSchema,\n TeamMemberSchema,\n TeamSchema,\n UserProfileAssignmentSchema,\n UserRoleAssignmentSchema,\n UserSchema,\n} from './types.js'\nexport type { UserProfileAssignmentService } from './user-profile-assignments.js'\nexport type { UserRoleAssignmentService } from './user-role-assignments.js'\n// Re-export service interfaces\nexport type { UserService } from './users.js'\n","/**\n * Value types that can be converted to query parameters.\n */\nexport type QueryValue = string | number | boolean | null | undefined\n\n/**\n * Object that can be converted to query parameters.\n * Supports nested objects (which are skipped during conversion).\n */\nexport type QueryObject = Record<string, QueryValue | QueryValue[] | Record<string, unknown>>\n\n/**\n * Converts an object to URLSearchParams for use in query strings.\n * Handles nested objects by flattening them (skips complex nested structures).\n * Skips null and undefined values.\n *\n * @param obj - Object to convert\n * @returns URLSearchParams instance\n *\n * @example\n * ```ts\n * toQueryParams({ page: 1, name: 'test', is_active: true })\n * // => URLSearchParams { page: '1', name: 'test', is_active: 'true' }\n *\n * toQueryParams({ filter: { slug: 'my-slug' } })\n * // => URLSearchParams {} (nested objects are skipped)\n * ```\n */\nexport function toQueryParams(obj: object | undefined | null): URLSearchParams {\n const params = new URLSearchParams()\n\n if (!obj) {\n return params\n }\n\n for (const [key, value] of Object.entries(obj)) {\n appendQueryParam(params, key, value as QueryValue | QueryValue[] | Record<string, unknown>)\n }\n\n return params\n}\n\n/**\n * Appends a single value to URLSearchParams.\n */\nfunction appendQueryParam(\n params: URLSearchParams,\n key: string,\n value: QueryValue | QueryValue[] | Record<string, unknown>,\n): void {\n // Skip null and undefined\n if (value === null || value === undefined) {\n return\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item !== null && item !== undefined) {\n params.append(key, String(item))\n }\n }\n return\n }\n\n // Skip nested objects (complex types)\n if (typeof value === 'object') {\n return\n }\n\n // Convert primitives to string\n params.set(key, String(value))\n}\n\n/**\n * Converts a URLSearchParams instance to a query string.\n * Returns empty string if no parameters.\n *\n * @param params - URLSearchParams to convert\n * @returns Query string (without leading '?')\n */\nexport function toQueryString(params: URLSearchParams): string {\n const str = params.toString()\n return str\n}\n\n/**\n * Builds a full URL with query parameters.\n *\n * @param baseUrl - Base URL (may already have query params)\n * @param path - Path to append\n * @param query - Query parameters to add\n * @returns Full URL string\n */\nexport function buildUrl(baseUrl: string, path: string, query?: object): string {\n const url = new URL(path, baseUrl)\n\n if (query) {\n const params = toQueryParams(query)\n params.forEach((value, key) => {\n url.searchParams.append(key, value)\n })\n }\n\n return url.toString()\n}\n","/**\n * Token provider function for dynamic authentication.\n * Can return a token synchronously or asynchronously.\n */\nexport type TokenProvider = () => string | Promise<string>\n\n/**\n * Configuration options for the ProteosClient.\n */\nexport interface ClientOptions {\n /**\n * Base URL for API requests.\n * Example: 'https://api.proteos.ai'\n */\n baseUrl: string\n\n /**\n * Static bearer token for authentication.\n * Use this for simple authentication scenarios.\n */\n token?: string\n\n /**\n * Dynamic token provider function.\n * Called before each request to get the current token.\n * Takes precedence over static token if both are provided.\n * Useful for token refresh scenarios.\n */\n tokenProvider?: TokenProvider\n\n /**\n * Request timeout in milliseconds.\n * Default: 30000 (30 seconds)\n */\n timeout?: number\n\n /**\n * Custom fetch implementation.\n * Useful for testing or environments without native fetch.\n * Default: global fetch\n */\n fetch?: typeof fetch\n\n /**\n * Custom headers to include in all requests.\n * Authorization header is set automatically from token/tokenProvider.\n */\n headers?: Record<string, string>\n}\n\n/**\n * Internal resolved options with defaults applied.\n */\nexport interface ResolvedClientOptions {\n baseUrl: string\n token?: string\n tokenProvider?: TokenProvider\n timeout: number\n fetch: typeof fetch\n headers: Record<string, string>\n}\n\n/**\n * Default client options.\n */\nexport const DEFAULT_OPTIONS = {\n timeout: 30000,\n headers: {},\n} as const\n\n/**\n * Request timeout for invoking an action or connector method. Function-service\n * lets one invocation run for 60s and connector-service waits 70s for it, so\n * the caller waits longer than both: the invocation's result, or its own\n * timeout error, reaches the caller instead of a client-side abort.\n */\nexport const INVOKE_TIMEOUT_MS = 75_000\n\n/** Request timeout for a batch action invocation (5 min server budget). */\nexport const BATCH_INVOKE_TIMEOUT_MS = 315_000\n\n/**\n * Resolves client options by applying defaults.\n */\nexport function resolveOptions(options: ClientOptions): ResolvedClientOptions {\n return {\n baseUrl: options.baseUrl.replace(/\\/$/, ''), // Remove trailing slash\n ...(options.token !== undefined ? { token: options.token } : {}),\n ...(options.tokenProvider !== undefined ? { tokenProvider: options.tokenProvider } : {}),\n timeout: options.timeout ?? DEFAULT_OPTIONS.timeout,\n fetch: (options.fetch ?? globalThis.fetch).bind(globalThis),\n headers: { ...DEFAULT_OPTIONS.headers, ...options.headers },\n }\n}\n\n/**\n * Options for individual requests.\n */\nexport interface RequestOptions {\n /** Request timeout in milliseconds (overrides client default) */\n timeout?: number\n /**\n * Skip attaching the Authorization header. Only meaningful for the public,\n * unauthenticated endpoints (`/meta/v1/public/*`, `/functions/v1/public/*`)\n * — every other endpoint 401s without a bearer.\n */\n skipAuth?: boolean\n /** Additional headers for this request */\n headers?: Record<string, string>\n /** AbortSignal for request cancellation */\n signal?: AbortSignal\n /**\n * Let the request outlive the page that sent it (fetch `keepalive`): for the\n * last report a page sends as it is closed. Browsers cap the body of such\n * requests at 64 KB in total.\n */\n keepalive?: boolean\n}\n","import { type EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-source'\nimport { ErrorCode, ProteosError, parseErrorResponse } from './errors.js'\nimport { toQueryParams } from './http/query-params.js'\nimport {\n type ClientOptions,\n type RequestOptions,\n type ResolvedClientOptions,\n resolveOptions,\n} from './types/options.js'\n\n/** One parsed Server-Sent-Events frame yielded by {@link ProteosClient.streamEvents}. */\nexport interface SseFrame {\n /** The frame `id:` line — Proteos services use the per-stream monotonic seq. */\n id?: string\n /** The frame `event:` line — the named event type. */\n event?: string\n /** The frame `data:` line — the raw payload (typically JSON). */\n data: string\n}\n\n/** Options for opening an SSE stream. */\nexport interface StreamOptions {\n /** Abort to tear the stream down (the normal stop path). */\n signal?: AbortSignal\n}\n\n/** True when an error is an AbortError (a stream's normal teardown). */\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === 'AbortError'\n}\n\n/**\n * Base HTTP client for all Proteos services.\n * Handles authentication, request/response formatting, and error handling.\n */\nexport class ProteosClient {\n private readonly options: ResolvedClientOptions\n\n /**\n * Creates a new ProteosClient instance.\n *\n * @param options - Client configuration options\n *\n * @example\n * ```ts\n * // With static token\n * const client = new ProteosClient({\n * baseUrl: 'https://api.proteos.ai',\n * token: 'your-api-token',\n * });\n *\n * // With dynamic token provider\n * const client = new ProteosClient({\n * baseUrl: 'https://api.proteos.ai',\n * tokenProvider: async () => {\n * return await authService.getAccessToken();\n * },\n * });\n * ```\n */\n constructor(options: ClientOptions) {\n this.options = resolveOptions(options)\n }\n\n /**\n * Returns the base URL configured for this client.\n */\n get baseUrl(): string {\n return this.options.baseUrl\n }\n\n /**\n * Gets the current authentication token.\n * Calls tokenProvider if available, otherwise returns static token.\n */\n private async getToken(): Promise<string | undefined> {\n if (this.options.tokenProvider) {\n return await this.options.tokenProvider()\n }\n return this.options.token\n }\n\n /**\n * Builds the headers for a request.\n */\n private async buildHeaders(requestOptions?: RequestOptions): Promise<Headers> {\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...this.options.headers,\n ...requestOptions?.headers,\n })\n\n if (!requestOptions?.skipAuth) {\n const token = await this.getToken()\n if (token) {\n headers.set('Authorization', `Bearer ${token}`)\n }\n }\n\n return headers\n }\n\n /**\n * Creates an AbortSignal with timeout.\n */\n private createTimeoutSignal(requestOptions?: RequestOptions): AbortSignal {\n const timeout = requestOptions?.timeout ?? this.options.timeout\n\n // Combine user signal with timeout signal if both exist\n if (requestOptions?.signal) {\n const controller = new AbortController()\n\n // Abort when user signal aborts\n requestOptions.signal.addEventListener('abort', () => {\n controller.abort(requestOptions.signal?.reason)\n })\n\n // Abort on timeout\n const timeoutId = setTimeout(() => {\n controller.abort(new Error(`Request timeout after ${timeout}ms`))\n }, timeout)\n\n // Clean up timeout if aborted early\n controller.signal.addEventListener('abort', () => {\n clearTimeout(timeoutId)\n })\n\n return controller.signal\n }\n\n return AbortSignal.timeout(timeout)\n }\n\n /**\n * Runs fetch and turns a transport failure — DNS, connection refused, the\n * network being down, the timeout signal firing — into a ProteosError with\n * httpStatus 0, so callers can tell \"the server said no\" from \"the server\n * was never reached\" (the latter is worth retrying). An abort the caller\n * asked for is theirs and passes through untouched.\n */\n private async send(url: string, init: RequestInit): Promise<Response> {\n try {\n return await this.options.fetch(url, init)\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error\n const message = error instanceof Error ? error.message : 'Network request failed'\n const isTimeout =\n error instanceof Error &&\n (error.name === 'TimeoutError' || error.message.startsWith('Request timeout'))\n throw new ProteosError(\n message,\n 0,\n isTimeout ? ErrorCode.REQUEST_TIMEOUT : ErrorCode.NETWORK_ERROR,\n )\n }\n }\n\n /**\n * Performs an HTTP request and decodes the JSON response.\n *\n * @param method - HTTP method (GET, POST, PATCH, DELETE, etc.)\n * @param path - Request path (appended to baseUrl)\n * @param body - Request body (will be JSON-serialized)\n * @param requestOptions - Optional request configuration\n * @returns Decoded response body\n * @throws {ProteosError} If the response status is >= 400\n */\n async request<T>(\n method: string,\n path: string,\n body?: unknown,\n requestOptions?: RequestOptions,\n ): Promise<T> {\n return this.requestWithQuery(method, path, undefined, body, requestOptions)\n }\n\n /**\n * Performs an HTTP request with query parameters.\n *\n * @param method - HTTP method\n * @param path - Request path\n * @param query - Query parameters object\n * @param body - Request body\n * @param requestOptions - Optional request configuration\n * @returns Decoded response body\n * @throws {ProteosError} If the response status is >= 400\n */\n async requestWithQuery<T, Q extends object = object>(\n method: string,\n path: string,\n query?: Q,\n body?: unknown,\n requestOptions?: RequestOptions,\n ): Promise<T> {\n let url = `${this.options.baseUrl}${path}`\n\n if (query) {\n const params = toQueryParams(query)\n const queryString = params.toString()\n if (queryString) {\n url += `?${queryString}`\n }\n }\n\n const headers = await this.buildHeaders(requestOptions)\n const signal = this.createTimeoutSignal(requestOptions)\n\n const response = await this.send(url, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : null,\n signal,\n ...(requestOptions?.keepalive ? { keepalive: true } : {}),\n })\n\n if (response.status >= 400) {\n throw await parseErrorResponse(response)\n }\n\n // No content response\n if (response.status === 204) {\n return undefined as T\n }\n\n // Parse JSON response\n const text = await response.text()\n if (!text) {\n return undefined as T\n }\n\n try {\n return JSON.parse(text) as T\n } catch {\n throw new ProteosError(\n `Failed to parse response as JSON: ${text.slice(0, 100)}`,\n response.status,\n 'parse_error',\n )\n }\n }\n\n /**\n * Performs a multipart form request (for file uploads).\n *\n * @param method - HTTP method\n * @param path - Request path\n * @param formData - FormData instance with files and fields\n * @param requestOptions - Optional request configuration\n * @returns Decoded response body\n * @throws {ProteosError} If the response status is >= 400\n */\n async requestMultipart<T>(\n method: string,\n path: string,\n formData: FormData,\n requestOptions?: RequestOptions,\n ): Promise<T> {\n const url = `${this.options.baseUrl}${path}`\n\n // Don't set Content-Type - let fetch set it with boundary\n const headers = new Headers({\n Accept: 'application/json',\n ...this.options.headers,\n ...requestOptions?.headers,\n })\n\n const token = await this.getToken()\n if (token) {\n headers.set('Authorization', `Bearer ${token}`)\n }\n\n const signal = this.createTimeoutSignal(requestOptions)\n\n const response = await this.send(url, {\n method,\n headers,\n body: formData,\n signal,\n })\n\n if (response.status >= 400) {\n throw await parseErrorResponse(response)\n }\n\n if (response.status === 204) {\n return undefined as T\n }\n\n return (await response.json()) as T\n }\n\n /**\n * Performs an HTTP request and returns the raw response.\n * Used for downloading files or streaming responses.\n *\n * @param method - HTTP method\n * @param path - Request path\n * @param body - Request body\n * @param requestOptions - Optional request configuration\n * @returns Object with response body stream and full Response object\n * @throws {ProteosError} If the response status is >= 400\n */\n async requestRaw(\n method: string,\n path: string,\n body?: unknown,\n requestOptions?: RequestOptions,\n ): Promise<{ body: ReadableStream<Uint8Array> | null; response: Response }> {\n const url = `${this.options.baseUrl}${path}`\n\n const headers = await this.buildHeaders(requestOptions)\n const signal = this.createTimeoutSignal(requestOptions)\n\n const response = await this.send(url, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : null,\n signal,\n })\n\n if (response.status >= 400) {\n throw await parseErrorResponse(response)\n }\n\n return {\n body: response.body,\n response,\n }\n }\n\n /**\n * Opens a Server-Sent-Events stream and yields each frame as it arrives.\n *\n * Built on `@microsoft/fetch-event-source` (not the browser-native\n * `EventSource`, which can't set an `Authorization` header) so the bearer token\n * is attached like any other request. The library tracks `Last-Event-ID` and\n * reconnects with exponential backoff on transient errors; a 4xx is fatal and\n * rejects. The stream runs until the caller's `AbortSignal` fires.\n *\n * The token is resolved once at stream start; teardown is the caller's signal.\n *\n * @param path - Request path (appended to baseUrl)\n * @param requestOptions - Optional request configuration (signal)\n * @returns Async generator of parsed {@link SseFrame}s\n * @throws {ProteosError} On a non-retryable (4xx) response\n */\n async *streamEvents(\n path: string,\n requestOptions?: StreamOptions,\n ): AsyncGenerator<SseFrame, void, unknown> {\n const url = `${this.options.baseUrl}${path}`\n\n const headers: Record<string, string> = { ...this.options.headers }\n const token = await this.getToken()\n if (token) {\n headers.Authorization = `Bearer ${token}`\n }\n\n // Bridge fetch-event-source's callbacks into an async generator: producer\n // pushes frames onto a queue, the consumer (this generator) drains it,\n // parking on a promise whenever the queue is empty.\n const queue: SseFrame[] = []\n let wake: (() => void) | null = null\n let finished = false\n let failure: unknown\n\n const notify = () => {\n wake?.()\n wake = null\n }\n const push = (frame: SseFrame) => {\n queue.push(frame)\n notify()\n }\n const finish = (error?: unknown) => {\n if (error !== undefined) failure = error\n finished = true\n notify()\n }\n\n const controller = new AbortController()\n const onExternalAbort = () => controller.abort()\n if (requestOptions?.signal) {\n if (requestOptions.signal.aborted) controller.abort()\n else requestOptions.signal.addEventListener('abort', onExternalAbort, { once: true })\n }\n\n const streaming = fetchEventSource(url, {\n method: 'GET',\n headers,\n signal: controller.signal,\n fetch: this.options.fetch,\n // Keep streaming when the tab is backgrounded (default would disconnect).\n openWhenHidden: true,\n onopen: async (response: Response) => {\n if (response.status >= 400) {\n throw await parseErrorResponse(response)\n }\n },\n onmessage: (message: EventSourceMessage) => {\n push({\n id: message.id || undefined,\n event: message.event || undefined,\n data: message.data,\n })\n },\n onerror: (error: unknown) => {\n // Abort + 4xx are fatal (rethrow to stop). Everything else is transient\n // — return a backoff so the library reconnects (Last-Event-ID resumes).\n if (isAbortError(error)) throw error\n if (error instanceof ProteosError && error.httpStatus >= 400 && error.httpStatus < 500) {\n throw error\n }\n return 2000\n },\n })\n .then(() => finish())\n .catch((error: unknown) => finish(error))\n\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift() as SseFrame\n continue\n }\n if (finished) break\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n }\n if (failure !== undefined && !isAbortError(failure)) throw failure\n } finally {\n controller.abort()\n requestOptions?.signal?.removeEventListener('abort', onExternalAbort)\n await streaming.catch(() => {})\n }\n }\n\n /**\n * Opens an authenticated WebSocket to a service path and resolves once it is\n * open.\n *\n * The browser-native `WebSocket` can't set an `Authorization` header, so the\n * access token is passed via the `bearer` subprotocol (`[\"bearer\", token]`),\n * which the gateway lifts back into the auth header — the same token resolved\n * for every other request. The `http(s)` base URL is rewritten to `ws(s)`.\n *\n * @param path - Request path (appended to baseUrl), including any query string\n * @returns The open WebSocket\n */\n async openWebSocket(path: string): Promise<WebSocket> {\n const wsBaseUrl = this.options.baseUrl.replace(/^http/, 'ws')\n const url = `${wsBaseUrl}${path}`\n\n const token = await this.getToken()\n const socket = token ? new WebSocket(url, ['bearer', token]) : new WebSocket(url)\n\n await new Promise<void>((resolve, reject) => {\n socket.onopen = () => resolve()\n socket.onerror = () => reject(new ProteosError('WebSocket connection failed', 0, 'ws_error'))\n })\n // Clear the bootstrap handlers so the caller owns the socket cleanly.\n socket.onopen = null\n socket.onerror = null\n return socket\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { INVOKE_TIMEOUT_MS } from '../types/options.js'\nimport type {\n ConnectionTokenResponse,\n Connector,\n ConnectorConnection,\n ConnectorMethod,\n CreateConnectorConnectionRequest,\n InstallConnectorConnectionResponse,\n InvokeMethodResponse,\n ListConnectorConnectionsQuery,\n ListConnectorsQuery,\n ListResponse,\n UpdateConnectorConnectionRequest,\n} from './types.js'\n\nexport * from './types.js'\n\nconst CONNECTOR_BASE_PATH = '/connectors/v1'\n\n/**\n * Facade for connector-service: the connector manifest catalog and\n * connections (install flow, token release, connector-method invocation).\n *\n * ```ts\n * const connector = new ConnectorClient(client)\n * const catalog = await connector.connectors.list()\n * const { authorization_url } = await connector.connections.install(id)\n * const events = await connector.connections.invokeMethod(id, 'list_events', {})\n * ```\n */\nexport class ConnectorClient {\n readonly connectors: ConnectorCatalogService\n readonly connections: ConnectorConnectionService\n\n constructor(client: ProteosClient) {\n this.connectors = new ConnectorCatalogServiceImpl(client)\n this.connections = new ConnectorConnectionServiceImpl(client)\n }\n}\n\n/** The connector manifest catalog (pre-built + org-custom). */\nexport interface ConnectorCatalogService {\n list(query?: ListConnectorsQuery): Promise<ListResponse<Connector>>\n get(key: string): Promise<Connector>\n /** A connector's callable methods (sugar over get().methods). */\n listMethods(key: string): Promise<ConnectorMethod[]>\n}\n\nclass ConnectorCatalogServiceImpl implements ConnectorCatalogService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConnectorsQuery = {}): Promise<ListResponse<Connector>> {\n return this.client.requestWithQuery('GET', `${CONNECTOR_BASE_PATH}/connectors`, query)\n }\n\n get(key: string): Promise<Connector> {\n return this.client.request(\n 'GET',\n `${CONNECTOR_BASE_PATH}/connectors/${encodeURIComponent(key)}`,\n )\n }\n\n async listMethods(key: string): Promise<ConnectorMethod[]> {\n const connector = await this.get(key)\n return connector.methods ?? []\n }\n}\n\n/** Configured integration instances + method invocation. */\nexport interface ConnectorConnectionService {\n list(query?: ListConnectorConnectionsQuery): Promise<ListResponse<ConnectorConnection>>\n get(id: string): Promise<ConnectorConnection>\n create(request: CreateConnectorConnectionRequest): Promise<ConnectorConnection>\n update(id: string, request: UpdateConnectorConnectionRequest): Promise<ConnectorConnection>\n delete(id: string): Promise<void>\n /** Begin the OAuth install flow; open the returned URL in a popup. */\n install(id: string): Promise<InstallConnectorConnectionResponse>\n /** Release the connection's usable token material (requires connections write). */\n token(id: string): Promise<ConnectionTokenResponse>\n /** Invoke a connector method; returns the unwrapped result. */\n invokeMethod<T = unknown>(id: string, method: string, params?: unknown): Promise<T>\n}\n\nclass ConnectorConnectionServiceImpl implements ConnectorConnectionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConnectorConnectionsQuery = {}): Promise<ListResponse<ConnectorConnection>> {\n return this.client.requestWithQuery('GET', `${CONNECTOR_BASE_PATH}/connections`, query)\n }\n\n get(id: string): Promise<ConnectorConnection> {\n return this.client.request(\n 'GET',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateConnectorConnectionRequest): Promise<ConnectorConnection> {\n return this.client.request('POST', `${CONNECTOR_BASE_PATH}/connections`, request)\n }\n\n update(id: string, request: UpdateConnectorConnectionRequest): Promise<ConnectorConnection> {\n return this.client.request(\n 'PATCH',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n )\n }\n\n install(id: string): Promise<InstallConnectorConnectionResponse> {\n return this.client.request(\n 'POST',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/install`,\n )\n }\n\n token(id: string): Promise<ConnectionTokenResponse> {\n return this.client.request(\n 'POST',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/token`,\n )\n }\n\n async invokeMethod<T = unknown>(id: string, method: string, params: unknown = {}): Promise<T> {\n const response = await this.client.request<InvokeMethodResponse<T>>(\n 'POST',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/methods/${encodeURIComponent(method)}/invoke`,\n params,\n { timeout: INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n}\n","import type { ProteosClient } from '../client.js'\n\nconst VOICE_BASE_PATH = '/conversations/v1/voice'\n\n/** One normalized transcription update streamed back from the server. */\nexport interface TranscriptResult {\n /** The recognized text for this segment. */\n transcript: string\n /** True once this segment is final and will not change. */\n is_final: boolean\n /** True when the server detected end-of-speech (a natural pause). */\n speech_final: boolean\n /** Recognition confidence, 0–1. */\n confidence: number\n}\n\n/** Options for opening a live transcription stream. */\nexport interface TranscribeStreamOptions {\n /** BCP-47 language code (e.g. `en`, `de`). Defaults to the server's default. */\n language?: string\n /** Stream interim (non-final) results as audio arrives. Defaults to `true`. */\n interimResults?: boolean\n /** Add punctuation to results. Defaults to `true`. */\n punctuate?: boolean\n /** Format entities (numbers, dates…) in results. Defaults to `true`. */\n smartFormat?: boolean\n /**\n * Raw audio encoding (e.g. `linear16`). Omit for containerized audio\n * (WebM/Opus from MediaRecorder), which the server auto-detects.\n */\n encoding?: string\n /** Sample rate in Hz. Required only when `encoding` is set. */\n sampleRate?: number\n /** Called for each transcription result. */\n onResult: (result: TranscriptResult) => void\n /** Called if the stream errors. */\n onError?: (error: Event) => void\n /** Called when the stream closes (either side). */\n onClose?: () => void\n}\n\n/** A live transcription session: push audio in, results arrive via `onResult`. */\nexport interface VoiceTranscriptionStream {\n /** Forward one audio chunk (binary) to the server. */\n sendAudio(chunk: Blob | ArrayBufferView | ArrayBuffer): void\n /** Ask the server to flush pending results without closing the stream. */\n finalize(): void\n /** Close the stream. */\n close(): void\n}\n\n/**\n * Service for realtime speech-to-text on conversation-service.\n *\n * Transcription is a WebSocket: open a stream, push audio chunks, and receive\n * {@link TranscriptResult}s. The transcription provider is a server-side concern\n * and is not exposed here.\n *\n * @example\n * ```ts\n * const stream = await agent.voice.transcribeStream({\n * onResult: (r) => console.log(r.transcript, r.is_final),\n * });\n * recorder.ondataavailable = (e) => stream.sendAudio(e.data);\n * // …later: stream.finalize(); stream.close();\n * ```\n */\nexport interface VoiceService {\n /**\n * Opens a live transcription stream and resolves once it is connected.\n *\n * @param options - Stream configuration and result/lifecycle callbacks\n * @returns A handle to push audio and control the stream\n */\n transcribeStream(options: TranscribeStreamOptions): Promise<VoiceTranscriptionStream>\n}\n\nexport class VoiceServiceImpl implements VoiceService {\n constructor(private readonly client: ProteosClient) {}\n\n async transcribeStream(options: TranscribeStreamOptions): Promise<VoiceTranscriptionStream> {\n const query = buildQuery(options)\n const socket = await this.client.openWebSocket(`${VOICE_BASE_PATH}/transcribe/stream${query}`)\n socket.binaryType = 'arraybuffer'\n\n socket.onmessage = (event: MessageEvent) => {\n if (typeof event.data !== 'string') return\n try {\n options.onResult(JSON.parse(event.data) as TranscriptResult)\n } catch {\n // Ignore malformed frames.\n }\n }\n if (options.onError) socket.onerror = options.onError\n socket.onclose = () => options.onClose?.()\n\n const isOpen = () => socket.readyState === WebSocket.OPEN\n\n return {\n sendAudio: (chunk) => {\n if (isOpen()) socket.send(chunk)\n },\n finalize: () => {\n if (isOpen()) socket.send(JSON.stringify({ type: 'finalize' }))\n },\n close: () => socket.close(),\n }\n }\n}\n\n/** Serializes options into the endpoint's query string (snake_case wire format). */\nfunction buildQuery(options: TranscribeStreamOptions): string {\n const params = new URLSearchParams()\n if (options.language) params.set('language', options.language)\n if (options.interimResults !== undefined)\n params.set('interim_results', String(options.interimResults))\n if (options.punctuate !== undefined) params.set('punctuate', String(options.punctuate))\n if (options.smartFormat !== undefined) params.set('smart_format', String(options.smartFormat))\n if (options.encoding) params.set('encoding', options.encoding)\n if (options.sampleRate !== undefined) params.set('sample_rate', String(options.sampleRate))\n const queryString = params.toString()\n return queryString ? `?${queryString}` : ''\n}\n","/**\n * Wire types for conversation-service (/conversations/v1) — hand-maintained\n * mirror of packages/go/model/conversation (snake_case, Is-prefixed booleans).\n */\n\nimport type { PageAction, PrincipalRef } from '../meta/types.js'\nimport type { FileRef } from '../types/common.js'\n\n/**\n * Platform medium a conversation lives on (closed enum; platform identity).\n * Where a provider brand spans both a chat product and a meeting platform the\n * channel is suffixed -chat / -meeting (teams-chat vs teams-meeting). The\n * *-meeting channels are the platforms the Ava meeting-bot family serves;\n * `meeting` stays the generic fallback for unclassified platforms.\n */\nexport type Channel =\n | 'slack'\n | 'email'\n | 'linkedin'\n | 'sms'\n | 'teams-chat'\n | 'telegram'\n | 'whatsapp'\n | 'meeting'\n | 'zoom-meeting'\n | 'google-meet'\n | 'teams-meeting'\n | 'webex-meeting'\n | 'adhoc'\n | 'phone'\n | 'instagram'\n | 'messenger'\n | 'x'\n\n/**\n * Concrete integration serving a channel (typed union — one value per shipped\n * connector; runtime availability is decided by the service's registry).\n * The unipile-* family serves the six messaging systems aggregated through\n * Unipile — one key per messaging system. The meeting keys are the Ava\n * meeting-bot family: adhoc-meeting dispatches by meeting URL; the calendar\n * keys auto-join through a user's connected calendar.\n */\nexport type ConnectorKey =\n | 'slack'\n | 'gmail'\n | 'outlook'\n | 'echo'\n | 'unipile-whatsapp'\n | 'unipile-linkedin'\n | 'unipile-telegram'\n | 'unipile-instagram'\n | 'unipile-messenger'\n | 'unipile-x'\n | 'adhoc-meeting'\n | 'google-calendar-meeting'\n | 'microsoft-calendar-meeting'\n | 'twilio-phone'\n | 'aircall'\n | 'webhook-cti'\n | 'sendgrid'\n | 'microsoft-teams'\n | 'platform-email'\n\n/**\n * Telephony lifecycle of one phone call, carried in the call conversation's\n * `metadata.call_status` (a call is a conversation plus call facts — no\n * dedicated resource). Status callbacks apply through a monotonic guard, so a\n * terminal value never regresses.\n */\n/**\n * Body of POST /conversations/v1/calls/token — the softphone's browser-calling\n * grant for one connection. The client identity is derived server-side from\n * the authenticated user.\n */\nexport interface MintCallTokenRequest {\n connection_id: string\n}\n\n/**\n * PUT /conversations/:id/recording — the in-call recording control on a live\n * phone conversation: true starts (or resumes) the recording, false pauses\n * it. A recording that did not run from answer to hangup is marked\n * `has_partial_recording` on the conversation's metadata.\n */\nexport interface SetCallRecordingRequest {\n is_recording_enabled: boolean\n}\n\n/**\n * Which system answers a provider phone number: connected to this platform,\n * in use by another integration (connecting takes it over, disconnecting\n * restores it), or configured nowhere (available).\n */\nexport type PhoneNumberStatus = 'connected' | 'available' | 'in_use'\n\n/** One dispatch target: a platform user (id) or a team (slug). */\nexport interface RoutingTarget {\n type: 'user' | 'team'\n id: string\n}\n\n/**\n * A connected number's user-level dispatch: who a call rings. v1 rings every\n * expanded target in parallel (teams expand to their direct members at ring\n * time); the object shape leaves room for later strategy options. Empty\n * targets fall back to the connection-wide routing, then busy.\n */\nexport interface PhoneNumberRouting {\n targets: RoutingTarget[]\n}\n\n/** One provider phone number on a phone connection. */\nexport interface PhoneNumber {\n /** Provider-side number identity (vendor vocabulary stays in the adapter). */\n external_id: string\n phone_number: string\n friendly_name: string\n status: PhoneNumberStatus\n /** Display-only description of what an in_use number is used by. */\n used_by?: string\n routing: PhoneNumberRouting\n}\n\n/** Routing update for one phone number (connect/disconnect are actions). */\nexport interface UpdatePhoneNumberRequest {\n routing?: PhoneNumberRouting\n}\n\n/**\n * twilio-phone `connection.settings.voicemail` — what a caller hears when no\n * agent takes the ring. The greeting is spoken by the provider's text-to-speech\n * in `language`; absent or blank fields fall back to platform defaults.\n */\nexport interface TwilioPhoneVoicemailSettings {\n is_enabled: boolean\n /** Empty = the platform's default English text. At most 1000 characters. */\n greeting?: string\n /** BCP-47, one of the supported TTS languages; default en-US. */\n language?: string\n /** 10..300, default 120. */\n max_duration_seconds?: number\n}\n\n/**\n * The typed slice of a twilio-phone `connection.settings` the softphone reads\n * (`Connection.settings` stays an open map on the wire).\n */\nexport interface TwilioPhoneSettings {\n is_softphone_enabled?: boolean\n is_recording_enabled?: boolean\n is_realtime_transcription_enabled?: boolean\n /** How long the parallel ring waits before the call counts as missed; 5..60, default 25. */\n ring_timeout_seconds?: number\n voicemail?: TwilioPhoneVoicemailSettings\n}\n\n/** Why an inbound ring ended without one of our people on the line. */\nexport type CallDialStatus =\n | 'no_answer'\n | 'busy'\n | 'failed'\n | 'canceled'\n /** Nobody was routed to the number. */\n | 'unrouted'\n /** The caller left while it rang. */\n | 'caller_hung_up'\n\n/**\n * The call facts a phone conversation carries in `metadata` (mirrors the\n * backend's logic/call-status.go + call-voicemail.go). Every key is optional\n * on the wire; read defensively.\n */\nexport interface CallMetadata {\n call_direction?: 'inbound' | 'outbound'\n call_status?: CallStatus\n from_number?: string\n to_number?: string\n /** Provider talk time; on a missed call it includes greeting + voicemail. */\n duration_seconds?: number\n recording_external_id?: string\n recording_file_id?: string\n is_recording_enabled?: boolean\n has_partial_recording?: boolean\n /** No agent took the inbound call. */\n is_missed?: boolean\n dial_status?: CallDialStatus\n /** `offered` once the greeting played, `recorded` once the message landed. */\n voicemail_status?: 'offered' | 'recorded'\n voicemail_duration_seconds?: number\n}\n\n/** The minted grant the Voice JS SDK consumes (`new Device(token, { edge })`). */\nexport interface CallTokenResponse {\n token: string\n identity: string\n /** Vendor edge to connect through ('dublin' for the EU default). */\n edge?: string\n expires_at: string\n}\n\nexport type CallStatus =\n | 'queued'\n | 'ringing'\n | 'in_progress'\n | 'completed'\n | 'no_answer'\n | 'busy'\n | 'failed'\n | 'canceled'\n\n/**\n * Who operates the integration mechanics behind a connector: Proteos' own\n * integration (native), an account aggregated through Unipile (unipile), or\n * the Ava meeting-bot family (ava). Computed on connection reads; the UI\n * groups the connector catalog by it.\n */\nexport type ConnectorProvider = 'native' | 'unipile' | 'ava'\n\nexport type MessageDirection = 'inbound' | 'outbound'\n/**\n * Delivery state. `draft` = agent-prepared, awaiting human review (a human\n * sends it → pending → sent/failed, or rejects it → `rejected`, terminal).\n */\nexport type MessageStatus = 'received' | 'pending' | 'sent' | 'failed' | 'draft' | 'rejected'\nexport type ConnectionScope = 'org' | 'user'\nexport type ConnectionStatus = 'pending' | 'active' | 'error' | 'revoked'\n/**\n * `draft` marks a conversation minted BY a draft message (originate-mode\n * drafting) — hidden from the default list until the first successful send.\n */\nexport type ConversationStatus = 'active' | 'ended' | 'archived' | 'draft'\n/**\n * Generation lifecycle of a conversation's `summary`. `none` is the resting\n * default — no summary exists and none is being produced, the state of every\n * conversation that is not a transcript-backed meeting. `processing` is claimed\n * for the duration of one generation run (automatic at transcript attach, or a\n * manual `meetings.summarize()`), so any client can render \"Summarizing…\"\n * without having started the run itself.\n */\nexport type ConversationSummaryStatus = 'none' | 'processing' | 'completed' | 'failed'\nexport type AgentListenerTriggerType = 'always' | 'mention' | 'channel' | 'keyword'\n\nexport interface UserRef {\n type: string\n id: string\n}\n\n/**\n * Inline snapshot of a person on a message/reaction — the integration-side\n * identity plus, when resolved, the platform user and the contact id.\n * (Renamed from ParticipantRef in the contacts model; wire keys unchanged.)\n */\nexport interface ContactRef {\n external_id?: string\n name: string\n email?: string\n /** The resolved person; absent on pre-contacts snapshots and wire fallbacks. */\n contact_id?: string\n /** Resolved platform identity (email match); absent when unresolved. */\n platform_user?: UserRef\n}\n\n/**\n * One member of a conversation's roster — everyone in the thread, INCLUDING the\n * connected account itself. The account's own entries carry is_self=true; a UI\n * renders \"who it's with\" as the non-self subset (1 → single avatar, ≥2 →\n * stacked).\n */\nexport interface ConversationParticipant extends ContactRef {\n is_self: boolean\n}\n\n/** How a MessageRecipient was addressed: primary, carbon copy, blind copy. */\nexport type RecipientRole = 'to' | 'cc' | 'bcc'\n\n/**\n * One addressee of a message with the role it was addressed under. Bcc is only\n * present on messages the platform itself sent (inbound bcc is SMTP-stripped).\n */\nexport interface MessageRecipient extends ContactRef {\n role: RecipientRole\n}\n\n/**\n * One unit of message content — what was SAID. Files a message CARRIED are\n * NOT content: they are Attachment rows (Message.attachments).\n */\nexport interface ContentBlock {\n type: 'text' | 'html'\n text?: string\n /**\n * Sanitized rich email body (ingest-time allowlist: layout tables, inline\n * styles, https images; no scripts/forms/handlers). Rides ALONGSIDE the\n * canonical text block. Render only in an isolated, script-less surface.\n */\n html?: string\n}\n\n/** Secret material is redacted on every read (\"********\" when set). */\nexport interface ConnectionCredentials {\n bot_token?: string\n bot_user_id?: string\n refresh_token?: string\n access_token?: string\n token_expires_at?: string\n granted_scopes?: string\n /** Aggregator-hosted account identity (unipile-*) — nothing secret. */\n account_id?: string\n owner_provider_id?: string\n}\n\n/** How a channel's reaction vocabulary is shaped. */\nexport type ReactionSetKind = 'open' | 'fixed'\n\n/** One entry of a fixed reaction vocabulary (token = the value to send). */\nexport interface ReactionOption {\n token: string\n unicode?: string\n label?: string\n}\n\n/**\n * A connector's declarative reaction capability, projected onto the\n * connection read: open → show an emoji picker; fixed → exactly the allowed\n * buttons; absent (connection.reactions undefined) → no affordance.\n */\nexport interface ReactionCapability {\n kind: ReactionSetKind\n allowed?: ReactionOption[]\n /** 0 = unbounded (Slack); 1 = single-slot (a new reaction replaces the old). */\n max_per_actor: number\n}\n\n/** How far back a historical backfill (\"sync all\") reaches. */\nexport type ConnectionSyncRange = '30d' | '90d' | '365d' | 'all'\n\n/**\n * Lifecycle of a historical backfill, carried as settings.sync_status.\n * Absent key = 'none' (never synced). 'in_progress' is claimed before the\n * trigger request returns — poll get(id) until it flips to done/failed.\n */\nexport type ConnectionSyncStatus = 'none' | 'in_progress' | 'done' | 'failed'\n\nexport interface SyncConnectionRequest {\n range: ConnectionSyncRange\n}\n\nexport interface Connection {\n id: string\n org_id: string\n connector_key: ConnectorKey\n channel: Channel\n name: string\n scope: ConnectionScope\n /** Set only when scope=user (the connecting user); absent for org-wide. */\n owner?: UserRef\n external_account_id: string\n credentials: ConnectionCredentials\n /**\n * Connector-shaped configuration + state. A historical backfill writes the\n * sync_* keys here: sync_status (ConnectionSyncStatus), sync_range,\n * sync_started_at, sync_completed_at, sync_synced_count, sync_error.\n */\n settings: Record<string, unknown>\n status: ConnectionStatus\n /** Computed on read: the connector implements the reaction capability. */\n supports_reactions: boolean\n /** The capability descriptor; absent when unsupported. */\n reactions?: ReactionCapability\n /**\n * Computed on read: the connector sends a message's html block as the\n * body's html part, so a composer can offer rich formatting.\n */\n supports_html: boolean\n /**\n * Computed on read like reactions: the channel actions the connector\n * performs through this connection (invitation, profile_visit, inmail, …).\n * A separate list from reactions — a reaction toggles an edge on a\n * message, an action is a performed act with its own lifecycle. Absent\n * when the connector performs none.\n */\n actions?: ChannelActionCapability[]\n /**\n * Computed on read like supports_reactions: who operates the integration\n * (native | unipile). Absent when the connector is not registered in this\n * environment.\n */\n provider?: ConnectorProvider\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface Conversation {\n id: string\n org_id: string\n connection_id: string\n channel: Channel\n external_conversation_id: string\n subject: string\n /**\n * Markdown summary — auto-generated at transcript attach for meeting\n * conversations, editable via update(). Absent when no summary exists.\n */\n summary?: string\n /**\n * Generation lifecycle of `summary`. Poll `conversations.get(id)` while this\n * reads `processing` to pick up the finished summary.\n */\n summary_status: ConversationSummaryStatus\n /**\n * When the current `processing` run was claimed; absent otherwise. Bounds the\n * claim server-side and gives clients an elapsed time to show.\n */\n summary_started_at?: string\n /**\n * ConversationType key the pre-summary classifier assigned; absent when never\n * classified or no type matched.\n */\n type_key?: string\n /** How the conversation ended — one of its type's outcome keys; absent = none yet. */\n outcome_key?: string\n /** Who set the outcome: `user` (never overridden by the model) or `model`. */\n outcome_source?: ConversationOutcomeSource\n outcome_set_by?: UserRef\n outcome_set_at?: string\n /** The conversation currently holds objective rows (maintained by the objective sync). */\n has_objectives: boolean\n status: ConversationStatus\n /**\n * Room directory row a room-borne thread (Slack channel conversation) lives\n * in; absent for DMs, email, meeting, adhoc.\n */\n room_id?: string\n /**\n * Main conversation a child conversation forked from (Slack: the channel's\n * main conversation; provider-side the child is a native Slack thread);\n * absent for main/DM/email/meeting/adhoc.\n */\n parent_conversation_id?: string\n /**\n * iCalendar UID of the calendar meeting this conversation was born from\n * (stamped when the meeting bot starts); absent for everything else. With\n * `started_at` it names the meeting INSTANCE on every invitee's calendar —\n * Google's UID names a series, Microsoft's one occurrence.\n */\n calendar_event_ical_uid?: string\n /**\n * The brief this phone call was dialled with, or the first brief attached to\n * it by hand; the first value stays. Absent on everything else: a meeting may\n * carry several briefs (list them with `conversationBriefs.list`).\n */\n brief_id?: string\n /**\n * Message id of the child conversation's root message, which lives in the\n * parent conversation; absent when the root is unknown (predates ingest).\n */\n started_by_message_id?: string\n started_at?: string\n ended_at?: string\n /**\n * The thread's complete roster — everyone in it, including the connected\n * account (its own entries marked is_self). Deduped by external_id; the\n * queryable person dimension. Replaces the old single `counterpart`.\n */\n participants?: ConversationParticipant[]\n last_message_at: string\n metadata: Record<string, unknown>\n /**\n * Messages summary — present only when the list opted in via\n * include: 'messages_summary'. Renders a hub stream row (root on Slack,\n * latest on email, reply affordance) without a per-conversation fetch.\n */\n root_message?: MessagePreview\n latest_message?: MessagePreview\n messages_total?: number\n /** Up to 3 most recent distinct senders excluding the root sender. */\n last_repliers?: ContactRef[]\n /** Requesting user's read marker; absent = never opened. */\n last_read_at?: string\n /**\n * Server-computed unread predicate for the requesting user: activity after\n * the marker AND the latest message is inbound.\n */\n is_unread: boolean\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Compact snapshot of one message riding on conversation reads\n * (include: 'messages_summary'): enough for a stream row — who, the first\n * ~500 chars of text, direction/status for outbound identity.\n */\nexport interface MessagePreview {\n sender: ContactRef\n text: string\n direction: MessageDirection\n status: MessageStatus\n occurred_at: string\n}\n\n/**\n * Aggregated unread-conversation counts for the requesting user (unit:\n * conversations, not messages) — the envelope total and per-channel badges.\n */\nexport interface UnreadCounts {\n total: number\n channels: Partial<Record<Channel, number>>\n}\n\n/**\n * One file that arrived with a message. `file` is the platform FileRef —\n * bytes live in storage-service; size and content type resolve from storage\n * by id. content_id/is_inline carry the MIME inline-image semantics\n * (cid: references in the html body vs user-facing downloads).\n */\nexport interface Attachment {\n id: string\n org_id: string\n message_id: string\n connection_id: string\n file: FileRef\n content_id?: string\n is_inline: boolean\n created_at: string\n created_by: UserRef\n}\n\n/** Aggregated reactions on a message: one entry per emoji (native token). */\nexport interface Reaction {\n emoji: string\n count: number\n participants: ContactRef[]\n}\n\nexport interface Message {\n id: string\n org_id: string\n conversation_id: string\n connection_id: string\n channel: Channel\n direction: MessageDirection\n /** A draft's edited subject, held until send. Absent means the conversation's; empty is a subject deliberately cleared on a new email. */\n subject?: string\n /** The tone profile this draft was written in, when known. May no longer resolve. */\n tone_profile_id?: string\n /** The reviewer took the quoted previous message off this reply. */\n is_quote_removed?: boolean\n /** The signature chosen for this email. Absent means the default that applies when it is sent. May no longer resolve. */\n signature_id?: string\n /** This email goes out without a signature. */\n is_signature_removed?: boolean\n /**\n * The signature the email carries below the body and above the quote. On a\n * sent message, the snapshot of what went out. On a single draft read, what\n * a send would add now. Never part of `content`.\n */\n signature?: MessageSignature\n /**\n * This email is sent with an unsubscribe link of its own. The link exists\n * only in what the recipient gets; `content` keeps `UNSUBSCRIBE_URL_PLACEHOLDER`\n * or nothing.\n */\n has_unsubscribe_link?: boolean\n /**\n * Why the message is sent: the purpose the recipients' consent was checked\n * for. Absent when the sender did not say.\n */\n purpose?: Purpose\n /** The layout chosen for this email (a message template of kind `layout`). Absent means none. May no longer resolve, which fails the send. */\n layout_id?: string\n /**\n * The frame the email carries around its body. On a sent message, the\n * snapshot of what went out. On a single draft read, what a send would use\n * now. Never part of `content`.\n */\n layout?: MessageLayout\n /** The platform wrote this message (a send or a draft): its content is what the person wrote, without the quote the email carried. Absent on mail imported from the mailbox. */\n is_sent_from_platform?: boolean\n /** The newest entry in this draft's history; absent until its first change. */\n draft_version?: number\n /** On a single draft read: the quote its send would carry below the text. Never stored. */\n quoted_text?: string\n external_message_id: string\n sender: ContactRef\n /** Who the message was addressed to (To/Cc/Bcc), each tagged with its role. */\n recipients?: MessageRecipient[]\n content: ContentBlock[]\n status: MessageStatus\n /**\n * The message this one was targeted at (thread-mode send/draft anchor);\n * absent for everything else.\n */\n reply_to_message_id?: string\n occurred_at: string\n /** Read-time projection; absent/empty on channels without reactions. */\n reactions?: Reaction[]\n /** Read-time projection of the message's attachment rows; absent without files. */\n attachments?: Attachment[]\n /**\n * Child-conversation projection (read-time, per-conversation lists): the\n * conversation rooted at this message and its message count — the \"N\n * replies\" affordance. Absent for messages no child conversation forked\n * from.\n */\n child_conversation_id?: string\n child_messages_total?: number\n /**\n * Provider-side outcome + engagement projection of an OUTBOUND message on\n * a sending platform (folded from the channel_event ledger); absent on\n * channels that report nothing and on inbound rows.\n */\n delivery?: MessageDelivery\n metadata: Record<string, unknown>\n error: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Provider-side outcome of an outbound message — a separate axis from\n * MessageStatus (the message stays `sent` at the platform level once the\n * provider accepted it): sent → delivered | deferred | bounced | dropped.\n */\nexport type MessageDeliveryStatus = 'sent' | 'delivered' | 'deferred' | 'bounced' | 'dropped'\n\n/** The read-side fold of a message's channel events. */\nexport interface MessageDelivery {\n status: MessageDeliveryStatus\n delivered_at?: string\n bounced_at?: string\n dropped_at?: string\n /** First HUMAN open / click; totals count every event (machine opens excluded). */\n opened_at?: string\n opens_total?: number\n clicked_at?: string\n clicks_total?: number\n spam_reported_at?: string\n unsubscribed_at?: string\n /** Latest bounce / drop / deferral text. */\n reason?: string\n last_event_at?: string\n}\n\n/**\n * Per-trigger configuration, discriminated by the sibling trigger_type: channel\n * carries external_channel_id, keyword carries phrases, always/mention carry\n * neither. (Serialized as the bare variant; both fields optional here.)\n */\nexport interface AgentListenerTriggerConfig {\n external_channel_id?: string\n phrases?: string[]\n}\n\n/**\n * How the dispatcher immediately acknowledges a triggering message once the\n * agent turn is queued: '' = none, 'reaction' places an emoji on the message\n * (reaction-capable connections only), 'message' posts a short text.\n */\nexport type AgentListenerAcknowledgementType = '' | 'reaction' | 'message'\n\n/**\n * Discriminated by the sibling acknowledgement_type; serialized as the bare\n * variant, both fields optional here.\n */\nexport interface AgentListenerAcknowledgementConfig {\n /** Reaction type: connector-native emoji token (\"eyes\", no colons). */\n emoji?: string\n /** Message type: the acknowledgement text. */\n text?: string\n}\n\n/**\n * Where the dispatcher takes its acting user from: 'defined' (the listener's\n * stored acting_user — the default) or 'inferred' (the triggering message\n * sender's resolved platform user, with acting_user as OPTIONAL fallback — no\n * platform user and no fallback means the dispatch is skipped).\n */\nexport type AgentListenerActingUserMode = 'defined' | 'inferred'\n\nexport interface AgentListener {\n id: string\n org_id: string\n connection_id: string\n conversation_id: string\n /**\n * Optionally NARROWS a connection-bound listener to one room — the internal\n * room id (`Room.id`), matched against the conversation's room at dispatch.\n * Absent/empty ⇒ the whole connection. The most specific scope wins:\n * conversation > room > connection; priority orders within a tier.\n */\n room_id?: string\n name: string\n agent_key: string\n trigger_type: AgentListenerTriggerType\n trigger_config: AgentListenerTriggerConfig\n /**\n * When set, gates the listener behind a wake word: the trigger stays dormant\n * until a message containing this phrase starts a session; once a session is\n * connected the trigger drives it normally. Empty/absent ⇒ no gate.\n */\n wake_phrase?: string\n /**\n * Immediate platform acknowledgement of the triggering message, executed by\n * the dispatcher once the agent turn is queued ('' = none). The agent is\n * told not to acknowledge again.\n */\n acknowledgement_type: AgentListenerAcknowledgementType\n acknowledgement_config?: AgentListenerAcknowledgementConfig\n acting_user_mode: AgentListenerActingUserMode\n /**\n * The user the dispatcher acts as (mode 'defined'), or the optional fallback\n * when the sender has no platform user (mode 'inferred'; an empty ref means\n * no fallback).\n */\n acting_user: UserRef\n is_enabled: boolean\n /**\n * How the agent's reply reaches the conversation. `true` (default) ⇒ the\n * platform posts the agent's text reply automatically. `false` ⇒ the platform\n * forwards nothing; the agent is told (in the session preamble) to reply\n * itself via the send_message/reply tool.\n */\n is_auto_forward_agent_replies_enabled: boolean\n priority: number\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateConnectionRequest {\n connector_key: ConnectorKey\n name: string\n scope: ConnectionScope\n settings?: Record<string, unknown>\n}\n\nexport interface UpdateConnectionRequest {\n name?: string\n settings?: Record<string, unknown>\n}\n\n/**\n * Optional body of POST /connections/:id/install. `input` carries\n * user-supplied install credentials for direct-install connectors\n * (twilio-phone, aircall, webhook-cti — connector-documented snake_case\n * keys); omit it for OAuth/hosted connectors.\n */\nexport interface InstallConnectionRequest {\n input?: Record<string, string>\n}\n\nexport interface InstallConnectionResponse {\n /** OAuth/hosted installs: open this in a popup. Absent on direct installs. */\n authorization_url?: string\n /** Direct installs complete server-side in this request. */\n is_completed?: boolean\n /**\n * A direct-install connector's one-time setup handout (callback URLs to\n * paste provider-side; a minted token shown exactly once — only its hash is\n * stored server-side). Never retrievable again.\n */\n setup?: Record<string, string>\n}\n\nexport interface SendMessageRequest {\n /** Records the tone a draft was written in. Stored by draft; send ignores it. */\n tone_profile_id?: string\n /**\n * The email signature: `default` (or omitted) for the default that applies,\n * `none` for no signature, or a signature id. Added below the body at send,\n * never part of `content`. Ignored on every channel but email.\n */\n signature?: SignatureChoice\n /**\n * Sends a stored message template instead of `content`: its id or key. It is\n * rendered with `variables` at this moment and stored on the message like any\n * content. `subject`, when omitted, is the template's.\n */\n template?: string\n /** The names the template's Liquid reads. Ignored without `template`. */\n variables?: Record<string, unknown>\n /**\n * `link` gives the email an unsubscribe link of its own that records an\n * opt-out in the contact's permission ledger; `none` (or omitted) gives it\n * none. The link replaces every `UNSUBSCRIBE_URL_PLACEHOLDER` in the body\n * (what `{{ unsubscribe_url }}` renders to) and goes into a footer line when\n * the body has none. Email only, to exactly one recipient: anything else is\n * refused with 400 `unsubscribe_not_possible`.\n */\n unsubscribe?: UnsubscribeChoice\n /**\n * Why the message is sent. The recipients' consent is checked for it: one\n * who opted out of it (or of everything) is refused with 403\n * `contact_opted_out`. Omitted takes the template's purpose, else none, and\n * then only an opt-out from everything stops the send. `transactional`\n * skips consent and cannot carry an unsubscribe link.\n */\n purpose?: Purpose\n /**\n * Wraps the body in a stored layout when the email is sent: the id or key\n * of a message template of kind `layout`, `none` (or omitted) for no layout.\n * `content` stays as written; the message keeps a snapshot of the layout\n * that went out. Ignored on every channel but email.\n */\n layout?: string\n /** Reply mode: send into this existing conversation. */\n conversation_id?: string\n /**\n * Targeted reply: reply aimed at ONE message (mutually exclusive with the\n * other modes). Slack starts/continues the child conversation rooted at\n * that message (carrying parent_conversation_id/started_by_message_id —\n * provider-side a native Slack thread); email replies in the same\n * conversation with In-Reply-To anchored at the target; channels without\n * message-targeted replies reject with `child_conversation_not_supported`.\n */\n reply_to_message_id?: string\n /** Originate mode (omit conversation_id): connection_id + at least one To are required. */\n connection_id?: string\n /**\n * Primary destinations for originate: one room (Slack channel) OR one-or-more\n * participants (email To, a Slack DM, or several users → a Slack MPIM).\n */\n to?: SendRecipient[]\n /** Carbon-copy participants (email only). */\n cc?: SendRecipient[]\n /** Blind-carbon-copy participants (email only). */\n bcc?: SendRecipient[]\n /** Optional subject, used by email when originating. */\n subject?: string\n /** May be empty when attachments are present. */\n content: ContentBlock[]\n /**\n * Files to send with the message. Pre-upload each file to storage-service\n * and reference it here ({id, name}); the server downloads the bytes and\n * hands them to the channel connector (Slack: one native message with the\n * text as its comment; Gmail: multipart/mixed mail; ≤25MB per file, Slack\n * ≤10 files per message). Channels without file support reject with\n * `unsupported_content`.\n */\n attachments?: FileRef[]\n /**\n * Overrides the sending identity on a sending-platform email connection: a\n * contact address id on the connection's sender domain\n * (`connections.listSenders`). Without it: the conversation's pinned sender\n * → the acting user's own address on the domain → the connection's default.\n * Off-domain ids fail with `sender_not_found`; connections without a sender\n * domain refuse it with `sender_domain_not_available`.\n */\n sender_address_id?: string\n}\n\n/**\n * Edits a status=draft message — full replacement of the editable surface\n * (PUT semantics; always send the complete state, including attachments you\n * want to keep). The addressing MODE is immutable. `subject` applies only\n * while the draft's conversation is itself status=draft (originate drafts) —\n * replies derive their subject from the thread.\n *\n * Recipient groups are PRESENCE-based: a group that is present (including an\n * explicit empty `[]` — a clear) replaces the stored recipients from exactly\n * the provided groups; omitting all three keeps the stored recipients. On any\n * recipient edit, send all three groups.\n */\n/** How a version of a draft came to be. */\nexport type MessageDraftVersionKind = 'drafted' | 'edited' | 'redrafted' | 'restored'\n\n/** One step in a draft message's history. */\nexport interface MessageDraftVersion {\n id: string\n org_id: string\n message_id: string\n version: number\n kind: MessageDraftVersionKind\n /** The effective subject at this version, wherever it is stored. */\n subject: string\n recipients: MessageRecipient[]\n content: ContentBlock[]\n tone_profile_id?: string\n /** The reviewer's redraft prompt (kind=redrafted). */\n instruction?: string\n /** The version a restore copied from (kind=restored). */\n source_version?: number\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** One field that differs between what was proposed and the latest version. */\nexport interface MessageDraftChange {\n field: 'body' | 'subject' | 'to' | 'cc' | 'bcc'\n from: unknown\n to: unknown\n}\n\n/** A draft's history, oldest first, plus what changed across it. */\nexport interface MessageDraftVersions {\n data: MessageDraftVersion[]\n changes: MessageDraftChange[]\n}\n\nexport interface UpdateDraftRequest {\n to?: SendRecipient[]\n /** Email only. */\n cc?: SendRecipient[]\n /** Email only. */\n bcc?: SendRecipient[]\n subject?: string\n /** May be empty when attachments are present. */\n content: ContentBlock[]\n /** The complete attachment set to keep (omitting one removes its row). */\n attachments?: FileRef[]\n /**\n * The `updated_at` the editor last saw. A draft that has moved on since fails\n * with 409 `draft_conflict` instead of being overwritten. Omit for last write wins.\n */\n expected_updated_at?: string\n /** Takes the quoted previous message off (true) or puts it back on (false). */\n is_quote_removed?: boolean\n /** Replaces the tone recorded on the draft. Omit to keep it. */\n tone_profile_id?: string\n /**\n * Replaces the draft's signature choice. Omit to keep it. The response then\n * carries the `signature` the draft now resolves to.\n */\n signature?: SignatureChoice\n /** Replaces the draft's unsubscribe choice. Omit to keep it. */\n unsubscribe?: UnsubscribeChoice\n /** Replaces the draft's purpose; `''` clears it. Omit to keep it. */\n purpose?: Purpose | ''\n /** Replaces the draft's layout: `none`, or a layout's id or key. Omit to keep it. */\n layout?: string\n /** What this edit is in the draft's history. Defaults to `edited`. */\n version_kind?: Exclude<MessageDraftVersionKind, 'drafted'>\n /** The reviewer's prompt behind a redraft. */\n instruction?: string\n /** The version a restore copies from. */\n source_version?: number\n}\n\nexport interface CreateAgentListenerRequest {\n connection_id?: string\n conversation_id?: string\n /**\n * Only with `connection_id`: narrow the listener to one room. Pass the\n * internal room id (`Room.id` from listRooms), NOT the provider channel id.\n */\n room_id?: string\n name: string\n agent_key: string\n trigger_type: AgentListenerTriggerType\n trigger_config?: AgentListenerTriggerConfig\n /** Gate the listener behind a wake word; omit or leave empty for no gate. */\n wake_phrase?: string\n /**\n * Immediate platform acknowledgement; omit or '' for none. 'reaction'\n * requires a reaction-capable connection and { emoji } in the config;\n * 'message' requires { text }.\n */\n acknowledgement_type?: AgentListenerAcknowledgementType\n acknowledgement_config?: AgentListenerAcknowledgementConfig\n /** Omit to default to 'defined'. */\n acting_user_mode?: AgentListenerActingUserMode\n /**\n * A bare user id; the service wraps it into a person UserRef. Required in\n * 'defined' mode (the default); optional in 'inferred' mode, where it is the\n * fallback when the sender has no platform user.\n */\n acting_user_id?: string\n /** Omit to default to enabled. */\n is_enabled?: boolean\n /**\n * Whether the platform auto-forwards the agent's text reply. Omit to default\n * to `true` (historic behavior). `false` ⇒ the agent replies itself via the\n * send_message/reply tool.\n */\n is_auto_forward_agent_replies_enabled?: boolean\n priority?: number\n}\n\nexport interface UpdateAgentListenerRequest {\n /**\n * Set to narrow the listener to a room (internal `Room.id`); pass \"\" to\n * clear. Only valid on connection-scoped listeners — the connection/\n * conversation target itself is fixed at creation.\n */\n room_id?: string\n name?: string\n agent_key?: string\n trigger_type?: AgentListenerTriggerType\n trigger_config?: AgentListenerTriggerConfig\n /** Set to gate the listener; pass \"\" to clear an existing wake phrase. */\n wake_phrase?: string\n /**\n * Set to change the acknowledgement; pass '' to clear. A non-empty type\n * requires acknowledgement_config in the same request.\n */\n acknowledgement_type?: AgentListenerAcknowledgementType\n acknowledgement_config?: AgentListenerAcknowledgementConfig\n /** Switching to 'defined' requires an effective acting user (stored or in this request). */\n acting_user_mode?: AgentListenerActingUserMode\n /** Pass \"\" to clear the user — only valid when the effective mode is 'inferred'. */\n acting_user_id?: string\n is_enabled?: boolean\n /** Toggle whether the platform auto-forwards the agent's text reply. */\n is_auto_forward_agent_replies_enabled?: boolean\n priority?: number\n}\n\n/**\n * A per-org glossary term: custom vocabulary that improves transcription\n * accuracy. `term` is the boost phrase injected into the provider's keyterm\n * prompting; `definition` is human/agent documentation only. `priority` ranks a\n * term for injection (prioritized terms outrank unprioritized; lower number\n * first) and decides which terms win when the org exceeds the provider's 100-term\n * per-request cap.\n */\nexport interface GlossaryTerm {\n id: string\n org_id: string\n term: string\n definition?: string\n priority?: number\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateGlossaryTermRequest {\n term: string\n definition?: string\n priority?: number\n}\n\nexport interface UpdateGlossaryTermRequest {\n term?: string\n definition?: string\n priority?: number\n /** Removes the term's priority (unprioritizes it) regardless of `priority`. */\n is_priority_cleared?: boolean\n}\n\nexport interface ListGlossaryTermsQuery extends PaginationQuery {\n /** Case-insensitive substring match on the term text. */\n search?: string\n}\n\n/** Optional per-type behavior configuration. */\nexport interface ConversationTypeConfig {\n /**\n * Agent-service prompt key whose CURRENT version body replaces the built-in\n * summary system prompt for conversations classified as this type. Absent ⇒\n * built-in prompt.\n */\n summary_prompt_key?: string\n}\n\n/**\n * A per-org conversation taxonomy entry. Before a meeting summary is\n * generated, a cheap classifier reads the transcript head plus every type's\n * `definition` and picks the matching `key` (or none); the result lands on\n * `Conversation.type_key` and `config.summary_prompt_key` may swap the summary\n * system prompt. Module-deployable (conversation-types/<key>.json).\n */\n/**\n * One way a conversation of a type can end — \"booked\", \"not_interested\",\n * \"callback\". The type's list is the vocabulary a person picks from (the\n * softphone after a call, the conversation header) and the choice a\n * `role: 'outcome'` tag definition detects among. `description` is what the\n * model reads to tell outcomes apart (the name when empty).\n */\nexport interface ConversationOutcome {\n /** Platform key — the value stored on `Conversation.outcome_key`. */\n key: string\n name: string\n description?: string\n}\n\n/**\n * One stage a conversation of a type moves through — \"intro\", \"discovery\",\n * \"close\". The type's list is ordered; progress through it is DERIVED from\n * the objectives pinned to each phase (every measured objective of a phase\n * achieved ⇒ the phase is done), never detected on its own. `description`\n * is for humans (the checklist, the summary prompt).\n */\nexport interface ConversationPhase {\n key: string\n name: string\n description?: string\n}\n\nexport interface ConversationType {\n org_id: string\n /** Immutable identity within the org — what the classifier answers with. */\n key: string\n name?: string\n /** When a conversation IS this type — injected verbatim into the classifier prompt. */\n definition: string\n config: ConversationTypeConfig\n /** Ordered; empty = the type tracks no outcome. */\n outcomes: ConversationOutcome[]\n /** Ordered; empty = the type tracks no phases. */\n phases: ConversationPhase[]\n /**\n * The type's action buttons — one strip in the footer of the call or\n * meeting surface, the same place during the conversation and in its\n * wrap-up. Same contract as `Page.actions`; each button's `visible_when`\n * reads the conversation scope (`conversation.status` for the stage,\n * `conversation.outcome_key`, `records_by_entity.<slug>`,\n * `tags_by_definition.<key>`, …); no rule = offered throughout. The rule\n * decides when a button appears; once pressed it stays for the rest of\n * the conversation. Ordered; empty = none.\n */\n actions: PageAction[]\n /** Module that deployed the type; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateConversationTypeRequest {\n /** Lowercase kebab/snake/camel handle — no spaces. */\n key: string\n name?: string\n definition: string\n config?: ConversationTypeConfig\n /** Replaces the list wholesale; omit = none. */\n outcomes?: ConversationOutcome[]\n /** Replaces the list wholesale; omit = none. */\n phases?: ConversationPhase[]\n /** Replaces the list wholesale; omit = none. */\n actions?: PageAction[]\n module_slug?: string\n}\n\nexport interface UpdateConversationTypeRequest {\n name?: string\n definition?: string\n /** Replaces the stored config wholesale; send `{}` to clear the prompt link. */\n config?: ConversationTypeConfig\n /** Replaces the list wholesale; `[]` clears it. */\n outcomes?: ConversationOutcome[]\n /** Replaces the list wholesale; `[]` clears it. */\n phases?: ConversationPhase[]\n /** Replaces the list wholesale; `[]` clears it. */\n actions?: PageAction[]\n}\n\nexport interface ListConversationTypesQuery extends PaginationQuery {\n /** Case-insensitive substring match on key or name. */\n search?: string\n module_slug?: string\n}\n\n// ---------------------------------------------------------------------------\n// Conversation intelligence — tag definitions, tag sets, tags, evaluations.\n// Hand-maintained mirror of conversation-tag-*.go + api/conversation-tag-*.go.\n// ---------------------------------------------------------------------------\n\n/**\n * Discriminates a tag definition's question (1:1 with the agent-service\n * decision question types): boolean (\"is this present?\"), choice (\"which\n * one?\"), score (\"where on this ordered scale?\").\n */\nexport type ConversationTagQuestionType = 'boolean' | 'choice' | 'score'\n\n/**\n * What a tag anchors to: the whole conversation (one value per conversation),\n * one message (a verdict per message), or a span (character ranges inside a\n * message, or message-to-message ranges). `span` REQUIRES evaluator kind\n * `reason` — only a reasoning generation can localise verbatim quotes.\n */\nexport type ConversationTagScope = 'conversation' | 'message' | 'span'\n\n/**\n * The model path a definition is judged by: `decide` (agent-service's\n * calibrated typed decision — probabilities, no prose, no localisation) or\n * `reason` (a schema-constrained generation that returns rationale + verbatim\n * anchors; required for span scope).\n */\nexport type ConversationTagEvaluatorKind = 'decide' | 'reason'\n\n/**\n * What a definition is judged over: `conversation` (its messages, windowed per\n * trigger — the default) or `summary` (the conversation's final summary plus\n * the humans' notes; conversation scope only; planned only once the\n * conversation has a summary, so never by a realtime evaluation).\n */\nexport type ConversationTagBasis = 'conversation' | 'summary'\n\n/**\n * Who set a conversation's outcome: a person (never overridden), the model\n * (a `role: 'outcome'` tag) or the service itself from a channel fact (a call\n * nobody answered, a meeting nobody joined).\n */\nexport type ConversationOutcomeSource = 'user' | 'model' | 'system'\n\n/**\n * One outcome a conversation may take, as `conversations.listOutcomes`\n * lists them: the type's outcomes (`source: 'type'`) followed by the\n * channel's system outcomes (`source: 'system'` — phone: not_reached /\n * voicemail / wrong_number; meetings: no_show / cancelled; email: no_reply /\n * bounced / declined; chat: no_reply / declined). The service sets the ones\n * it can tell by itself; a person may pick any.\n */\nexport interface ConversationOutcomeOption {\n key: string\n name: string\n description?: string\n source: 'type' | 'system'\n}\n\n/**\n * The special part a definition plays beyond being an observation. `outcome`\n * = THE result of the conversation: a choice question at conversation scope,\n * one value per conversation, the human's choice beats the model's (an\n * evaluation never asks the model an outcome a user already set), surfaced in\n * the softphone and the conversation header. `phase` is reserved.\n */\nexport type ConversationTagRole = 'outcome'\n\n/**\n * WHY an evaluation ran: `realtime` (the debounced window after new messages),\n * `completion` (the conversation completed — final transcript + summary for\n * spoken media, End for the rest) or `manual` (`conversationTags.evaluate`).\n * A tag set's `evaluate_on` lists the automatic ones it subscribes to; manual\n * ignores it.\n */\nexport type ConversationTagTrigger = 'realtime' | 'completion' | 'manual'\n\n/** Who produced a tag: the evaluator (`model`) or a person (`user`). */\nexport type ConversationTagSource = 'model' | 'user'\n\n/**\n * `pending` = a provisional realtime observation on a spoken-medium\n * conversation that is still live (a completion evaluation will replace it);\n * `active` = current; `dismissed` = a person rejected it — kept as feedback\n * and never re-created by a later evaluation.\n */\nexport type ConversationTagStatus = 'pending' | 'active' | 'dismissed'\n\n/**\n * One evaluation's lifecycle: `pending` (a manual evaluation was accepted and\n * not yet started), `running`, `done`, `failed`.\n */\nexport type ConversationTagEvaluationStatus = 'pending' | 'running' | 'done' | 'failed'\n\n/**\n * Spells out what makes a boolean question hold (`true`) or not (`false`)\n * when the boundary is subtle.\n */\nexport interface BooleanTagCriteria {\n true: string\n false: string\n}\n\n/**\n * Populated per question type: boolean → `boolean` (optional, both\n * descriptions or neither), choice → `choice` (option key → description,\n * ≥ 2), score → `score` (ordered level descriptions, ≥ 2; the tag value is\n * the 0-based level index). Descriptions are handed to the evaluator\n * verbatim, so they should describe the observable content, not internal\n * process.\n */\nexport interface ConversationTagCriteria {\n boolean?: BooleanTagCriteria\n choice?: Record<string, string>\n score?: string[]\n}\n\n/**\n * The decide-shaped question a definition asks over a conversation — the\n * same three types as the agent-service decision question, with criteria in\n * an explicit struct so manifests and SDKs need no tagged-union decoder.\n * `type` is immutable after create: tag values are typed by it.\n */\nexport interface ConversationTagQuestion {\n type: ConversationTagQuestionType\n instructions: string\n /** Always on the wire; pass `{}` for a boolean question without descriptions. */\n criteria: ConversationTagCriteria\n}\n\n/**\n * Makes a `reason` definition ask the cheap decide model first whether it\n * applies anywhere in the judged window (its own boolean question, one answer\n * per window); only a definition that passes (probability ≥ `min_probability`)\n * reaches the reasoning call, which is skipped entirely when nothing passes. A\n * screened-out definition's stale tags are still replaced. Boolean questions\n * only — choice and score always have an answer. Omitted = screening on with\n * the service default threshold (0.3, `CONVERSATION_TAG_SCREENING_MIN_PROBABILITY`);\n * `{ is_enabled: false }` turns it off. The service rejects `screening` on a\n * `decide` evaluator or on a choice/score question, and a `min_probability`\n * outside 0..1.\n */\nexport interface ConversationTagScreening {\n is_enabled: boolean\n /** Pass threshold in 0..1; absent = the service default. */\n min_probability?: number\n}\n\n/**\n * Selects the model path. `model_id` is only meaningful for `reason` (absent =\n * the service default); `decide` always uses the service-wide decision model.\n * `screening` is only meaningful for `reason` with a boolean question; absent =\n * screening on with the service default threshold.\n */\nexport interface ConversationTagEvaluator {\n kind: ConversationTagEvaluatorKind\n model_id?: string\n screening?: ConversationTagScreening\n}\n\n/**\n * Describes WHAT to look for in a conversation: one typed question plus where\n * its answers anchor (`scope`) and which model path answers it (`evaluator`).\n * WHERE and WHEN a definition is evaluated is a ConversationTagSet's business\n * — a definition that no enabled set references is never evaluated. Keyed\n * (org_id, key) and module-deployable (conversation-tag-definitions/<key>.json),\n * like conversation types.\n */\nexport interface ConversationTagDefinition {\n org_id: string\n /** Immutable identity within the org — the value every tag carries as `definition_key`. */\n key: string\n name: string\n /** Free grouping for UIs (\"content\", \"sentiment\", \"signal\"). */\n group?: string\n question: ConversationTagQuestion\n /** `span` requires `evaluator.kind = 'reason'`. */\n scope: ConversationTagScope\n evaluator: ConversationTagEvaluator\n /** `summary` requires conversation scope. */\n basis: ConversationTagBasis\n /** Absent = a plain observation. `outcome` requires a choice question at conversation scope. */\n role?: ConversationTagRole\n /**\n * Narrows message/span-scope judging to messages of these directions (e.g.\n * inbound only for customer sentiment); empty = all. Ignored for\n * conversation scope.\n */\n directions: MessageDirection[]\n /**\n * Observations below it are dropped, for every question type — an absent\n * tag means \"not determined\", not \"false\".\n */\n min_confidence: number\n /** Optional UI hint (any CSS color token the client accepts). */\n color?: string\n is_enabled: boolean\n /** Module that deployed the definition; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Describes WHERE and WHEN a group of tag definitions is evaluated. A\n * conversation matches a set when every NON-EMPTY selector contains it:\n * `channels`, `connection_ids`, `type_keys` (an empty conversation `type_key`\n * never matches a type-scoped set, so type-scoped sets only apply once a\n * conversation has been classified). At least one of those three must be\n * non-empty — tagging is opt-in, never org-wide by accident. `directions` is\n * a message-level filter on top (which messages arm / are judged), not a\n * conversation selector. Matched sets union their definition keys; timing\n * takes the minimum quiet window and max wait over the matched sets that\n * evaluate in realtime. Keyed (org_id, key) and module-deployable\n * (conversation-tag-sets/<key>.json).\n */\nexport interface ConversationTagSet {\n org_id: string\n key: string\n name: string\n /**\n * The definitions this set evaluates (≥ 1; each must exist in the org at\n * write time — a definition deleted later is skipped).\n */\n definition_keys: string[]\n channels: Channel[]\n connection_ids: string[]\n type_keys: string[]\n /**\n * Narrows which NEW messages arm a realtime evaluation (and which messages a\n * completion evaluation judges for message/span scope): inbound only,\n * outbound only, or both when empty. A definition's own `directions`\n * narrows further.\n */\n directions: MessageDirection[]\n /**\n * A non-empty subset of [realtime, completion]: realtime = the debounced\n * window after new messages arrive; completion = once the conversation\n * completed (final transcript + summary for spoken media, End for the\n * rest). Manual evaluations ignore it.\n */\n evaluate_on: ConversationTagTrigger[]\n /** A realtime evaluation fires this long after the LAST new message (default 90, min 5). */\n quiet_window_seconds: number\n /**\n * Bounds the wait since the FIRST unjudged message (default 600, ≥ quiet\n * window) so a busy stream is still tagged periodically.\n */\n max_wait_seconds: number\n is_enabled: boolean\n /** Module that deployed the set; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * One observation a definition made on a conversation.\n *\n * Anchors encode the definition's scope: conversation scope = every anchor\n * field absent; message scope = `start_message_id === end_message_id` with no\n * offsets; span = offsets set (a span may cross messages, then start/end\n * message ids differ). Offsets are UNICODE CODE POINT indexes into the\n * message's first text content block, end exclusive — JS strings are UTF-16,\n * so convert (e.g. via `Array.from(text)` / code-point iteration) before\n * slicing. `quote` (and `end_quote` for a span that continues into a later\n * message) is the verbatim text at the anchor: the reason evaluator emits\n * quotes because a model cannot count characters, the service resolves them\n * to offsets, and afterwards the quote is the evidence that survives a message\n * row change (the final transcript swaps realtime message ids; a term\n * correction edits text) — a tag whose anchors no longer resolve still shows\n * its quote and can be re-anchored by search.\n *\n * `value` is normalized per question type: `\"true\"` for a boolean (false is\n * never stored), the option key for a choice, the 0-based level index AS A\n * STRING for a score. Status `pending` marks a provisional realtime\n * observation on a live spoken-medium conversation; a completion evaluation\n * replaces it. Dismissed tags are feedback: a later evaluation never\n * re-creates a tag matching a dismissed one on (definition_key, value,\n * start/end message).\n */\nexport interface ConversationTag {\n id: string\n org_id: string\n conversation_id: string\n /**\n * Denormalized from the conversation so org-wide lists and counts group by\n * channel without a join.\n */\n channel: Channel\n definition_key: string\n /** `\"true\"` | choice option key | score level index as a string. */\n value: string\n confidence: number\n /**\n * The raw decide distribution (`{\"true\":p,\"false\":1-p}`, option → p, or\n * `{\"levels\":[…],\"mean\":x}`); a screened reason tag carries\n * `{\"screening\":p}` instead; absent for unscreened reason and user tags.\n */\n probabilities?: Record<string, unknown>\n /** The reason evaluator's one-line rationale; absent for decide. */\n why?: string\n source: ConversationTagSource\n status: ConversationTagStatus\n /** Links a model tag to the evaluation that produced it. */\n evaluation_id?: string\n start_message_id?: string\n /** Unicode code-point index, inclusive. */\n start_offset?: number\n end_message_id?: string\n /** Unicode code-point index, exclusive. */\n end_offset?: number\n start_occurred_at?: string\n end_occurred_at?: string\n quote?: string\n end_quote?: string\n /**\n * When the observed thing happened (the end message's `occurred_at`, else\n * the last message's) — the time-series axis.\n */\n observed_at: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * One row of `conversationTags.counts`: the grouped columns that were\n * requested plus the count.\n */\nexport interface ConversationTagCount {\n definition_key?: string\n value?: string\n channel?: Channel\n count: number\n}\n\n/**\n * The model spend of one evaluation, summed over its decide and generate\n * calls.\n */\nexport interface ConversationTagUsage {\n input_tokens: number\n output_tokens: number\n request_count: number\n}\n\n/**\n * One screening verdict of an evaluation: the decide probability that the\n * definition applies in the judged window and whether that passed the\n * threshold. `probability` is absent (and `error` set) when the screening\n * could not be asked — it then passes, fail-open.\n */\nexport interface ConversationTagScreeningResult {\n definition_key: string\n probability?: number\n is_passed: boolean\n error?: string\n}\n\n/**\n * Records one time the tagger ran on a conversation: why (`trigger`), what it\n * judged (`definition_keys`, the message window), with which models, what it\n * cost, and how it ended. Model tags reference it through `evaluation_id`\n * (provenance), the UI polls it after a manual evaluate (202), and the latest\n * done realtime/completion evaluation's `window_end_occurred_at` is the\n * watermark the next realtime window starts after.\n *\n * Window = the messages JUDGED by this evaluation. realtime: everything after\n * the previous watermark (older messages ride along as context only);\n * completion/manual: all messages. Lifecycle: manual creates `pending` on the\n * 202 then flips to `running`; realtime/completion create `running` directly;\n * ends `done` or `failed`.\n */\nexport interface ConversationTagEvaluation {\n id: string\n org_id: string\n conversation_id: string\n trigger: ConversationTagTrigger\n status: ConversationTagEvaluationStatus\n definition_keys: string[]\n model_ids: string[]\n usage: ConversationTagUsage\n /**\n * The rendered state exceeded the cap and older context (or, for a huge\n * window, the newest window messages — deferred to the next evaluation) was\n * dropped.\n */\n is_truncated: boolean\n window_start_occurred_at?: string\n window_end_occurred_at?: string\n window_message_ids: string[]\n /**\n * Every screened reason definition's verdict, so \"why was nothing tagged\"\n * is answerable and thresholds can be tuned. Empty when no definition was\n * screened.\n */\n screenings: ConversationTagScreeningResult[]\n error?: string\n started_at: string\n finished_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * The `conversation.tagged` event payload: the conversation, the evaluation\n * that landed, and every tag it produced (status pending or active — the\n * event header carries the status so a consumer can filter provisional\n * realtime observations without decoding).\n */\nexport interface ConversationTaggedEvent {\n conversation: Conversation\n evaluation: ConversationTagEvaluation\n tags: ConversationTag[]\n}\n\n/**\n * Creates one tag definition. `key` is the immutable identity (kebab/snake,\n * like every platform key); `question` is the decide-shaped question the\n * evaluator answers; `scope` and `evaluator` say where answers anchor and\n * which model path answers (`span` requires `evaluator.kind = 'reason'`).\n * `is_enabled` omitted ⇒ true (manifests may omit it). `module_slug` is\n * stamped by `pro module deploy` — interactive callers leave it empty.\n */\nexport interface CreateConversationTagDefinitionRequest {\n key: string\n name?: string\n group?: string\n question: ConversationTagQuestion\n scope: ConversationTagScope\n evaluator: ConversationTagEvaluator\n /** Omitted ⇒ `conversation`. */\n basis?: ConversationTagBasis\n /** Omitted ⇒ none. */\n role?: ConversationTagRole | ''\n directions?: MessageDirection[]\n /** 0..1 */\n min_confidence?: number\n color?: string\n is_enabled?: boolean\n module_slug?: string\n}\n\n/**\n * Partial update — an omitted field leaves the stored value untouched.\n * `question`, when present, replaces the stored question wholesale but must\n * keep its `type` (400 `conversation_tag_question_type_immutable` otherwise).\n * `directions` replaces wholesale. `key` is immutable.\n */\nexport interface UpdateConversationTagDefinitionRequest {\n name?: string\n group?: string\n question?: ConversationTagQuestion\n scope?: ConversationTagScope\n evaluator?: ConversationTagEvaluator\n basis?: ConversationTagBasis\n /** Empty string clears the role. */\n role?: ConversationTagRole | ''\n directions?: MessageDirection[]\n /** 0..1 */\n min_confidence?: number\n color?: string\n is_enabled?: boolean\n}\n\nexport interface ListConversationTagDefinitionsQuery extends PaginationQuery {\n /** Definitions deployed by one module — the `pro module` remote-state discovery door. */\n module_slug?: string\n /** Exact filter. */\n group?: string\n /** Exact filter. */\n scope?: string\n /** Exact filter — `outcome` lists the outcome definitions. */\n role?: string\n is_enabled?: boolean\n /** Case-insensitive substring match on key or name. */\n search?: string\n}\n\n/**\n * Creates one tag set: which definitions to evaluate (`definition_keys`, ≥ 1,\n * each must exist), for which conversations (at least one of `channels` /\n * `connection_ids` / `type_keys` non-empty; `directions` additionally limits\n * which messages arm/are judged — empty = both), when (`evaluate_on` ⊆\n * [realtime, completion], ≥ 1) and the realtime timing (omitted ⇒ defaults:\n * quiet 90s, max wait 600s). `is_enabled` omitted ⇒ true. `module_slug` is\n * stamped by `pro module deploy`.\n */\nexport interface CreateConversationTagSetRequest {\n key: string\n name?: string\n definition_keys: string[]\n channels?: Channel[]\n connection_ids?: string[]\n type_keys?: string[]\n directions?: MessageDirection[]\n evaluate_on: ConversationTagTrigger[]\n quiet_window_seconds?: number\n max_wait_seconds?: number\n is_enabled?: boolean\n module_slug?: string\n}\n\n/**\n * Partial update — an omitted field leaves the stored value untouched; arrays\n * replace wholesale. `key` is immutable.\n */\nexport interface UpdateConversationTagSetRequest {\n name?: string\n definition_keys?: string[]\n channels?: Channel[]\n connection_ids?: string[]\n type_keys?: string[]\n directions?: MessageDirection[]\n evaluate_on?: ConversationTagTrigger[]\n quiet_window_seconds?: number\n max_wait_seconds?: number\n is_enabled?: boolean\n}\n\nexport interface ListConversationTagSetsQuery extends PaginationQuery {\n /** Sets deployed by one module. */\n module_slug?: string\n /** Sets that reference the definition. */\n definition_key?: string\n is_enabled?: boolean\n /** Case-insensitive substring match on key or name. */\n search?: string\n}\n\n// ── Conversation objectives ──────────────────────────────────────────────\n\n/**\n * How an objective definition's achievement is told: `tag` (a tag on a tag\n * definition meets a value condition) or `outcome` (the conversation's\n * outcome is one of a set).\n */\nexport type ConversationObjectiveMeasureKind = 'tag' | 'outcome'\n\n/**\n * The value condition — exactly one field set, matched to the question type\n * of the measured tag definition (boolean / choice / score) or, for kind\n * `outcome`, `choice_in` over outcome keys. `score_min` is the 0-based level\n * index a score tag must reach (tag values store the level index).\n */\nexport interface ConversationObjectiveAchievedWhen {\n boolean?: boolean\n choice_in?: string[]\n score_min?: number\n}\n\n/**\n * How an objective's achievement is told:\n *\n * - kind `tag`: a non-dismissed tag on `tag_definition_key` whose value meets\n * `achieved_when` (a pending tag ⇒ achieved, provisional). The tag\n * definition must be conversation-scoped and role-less — a person ticks the\n * objective by creating a user tag on it, unticks by deleting that tag.\n * - kind `outcome`: the conversation's `outcome_key` is one of\n * `achieved_when.choice_in` (the type's outcomes and the channel's system\n * outcomes) — ticked through the outcome picker.\n */\nexport interface ConversationObjectiveMeasure {\n kind: ConversationObjectiveMeasureKind\n /** Required for kind `tag`; absent for kind `outcome`. */\n tag_definition_key?: string\n achieved_when: ConversationObjectiveAchievedWhen\n}\n\n/**\n * One thing a conversation should achieve — \"confirm the budget\", \"agree a\n * next step\", \"book the demo\". Applies to every conversation (`type_key`\n * absent) or to conversations of one type, may be pinned to one of that\n * type's phases (the checklist groups by phase, and a phase counts as done\n * once every measured objective in it is achieved), and may be MEASURED so\n * the platform tells whether it was achieved (no `measure` = guidance only,\n * a line on the checklist). Its instance on a conversation is a\n * ConversationObjective — the same definition → instance split as\n * ConversationTagDefinition → ConversationTag. Keyed by `key`;\n * module-deployable (conversation-objective-definitions/<key>.json).\n */\nexport interface ConversationObjectiveDefinition {\n org_id: string\n key: string\n name: string\n description?: string\n /** Restricts the objective to one conversation type; absent = every conversation. */\n type_key?: string\n /** Pins the objective to one of the type's phases (requires `type_key`); absent = ungrouped. */\n phase_key?: string\n /** How achievement is told; absent = guidance only. */\n measure?: ConversationObjectiveMeasure\n is_enabled: boolean\n /** Module that deployed the definition; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Creates one objective definition. `phase_key` requires `type_key` and must\n * be one of that type's phases. A `tag` measure names a CONVERSATION-scoped,\n * role-less tag definition and its `achieved_when` must match the question\n * type (boolean ⇒ `{boolean: true}`; choice ⇒ `{choice_in ⊆ options}`; score\n * ⇒ `{score_min: level index}`); an `outcome` measure takes `{choice_in}` over\n * outcome keys (the type's outcomes ∪ the channel system outcomes when\n * typed). `is_enabled` omitted ⇒ true. `module_slug` is stamped by\n * `pro module deploy`.\n */\nexport interface CreateConversationObjectiveDefinitionRequest {\n key: string\n name: string\n description?: string\n type_key?: string\n phase_key?: string\n measure?: ConversationObjectiveMeasure\n is_enabled?: boolean\n module_slug?: string\n}\n\n/**\n * Partial update — an omitted field leaves the stored value untouched.\n * `measure` is tri-state: omitted keeps it, `null` clears it (guidance only),\n * a value replaces it wholesale. `key` is immutable.\n */\nexport interface UpdateConversationObjectiveDefinitionRequest {\n name?: string\n description?: string\n type_key?: string\n phase_key?: string\n measure?: ConversationObjectiveMeasure | null\n is_enabled?: boolean\n}\n\nexport interface GetManyConversationObjectiveDefinitionsQuery extends PaginationQuery {\n /** Definitions deployed by one module. */\n module_slug?: string\n type_key?: string\n phase_key?: string\n is_enabled?: boolean\n /** Case-insensitive substring match on key or name. */\n search?: string\n}\n\n/**\n * An objective's standing on a conversation: open (not yet, or no longer,\n * achieved) or achieved. Whether an achieved standing is still provisional is\n * the separate `is_provisional` flag, never a third status.\n */\nexport type ConversationObjectiveStatus = 'open' | 'achieved'\n\n/**\n * Who achieved an objective: a person (a user tag or a hand-picked outcome),\n * the model (a detected tag or outcome) or the system (a channel-level\n * outcome the service set by itself).\n */\nexport type ConversationObjectiveSource = 'user' | 'model' | 'system'\n\n/** Where a conversation stands in one of its type's phases. */\nexport type ConversationPhaseStatus = 'done' | 'current' | 'upcoming' | 'untracked'\n\n/**\n * One objective definition's standing on one conversation: open or achieved,\n * by whom, when, and on which tag. Resolved live for the per-conversation\n * read (ConversationObjectiveProgress) AND persisted as the ledger row of\n * the same shape — one row per APPLICABLE definition, open rows included,\n * rewritten at every change point. Never user-written.\n */\nexport interface ConversationObjective {\n org_id: string\n conversation_id: string\n definition_key: string\n /** The conversation's channel, denormalized at resolution time. */\n channel: Channel\n /** The conversation's type, denormalized at resolution time. */\n type_key?: string\n /** The definition's phase, denormalized at resolution time. */\n phase_key?: string\n status: ConversationObjectiveStatus\n /** Who achieved it; absent while open. */\n source?: ConversationObjectiveSource\n /**\n * The backing tag is still `pending` — a realtime detection on a live\n * spoken conversation the completion pass has not confirmed. Never true for\n * a user or system source.\n */\n is_provisional: boolean\n achieved_at?: string\n /**\n * The tag that achieved a tag-measured objective (the one to delete to\n * untick when `source` is user); absent for outcome measures.\n */\n tag_id?: string\n /** The conversation's status at resolution time — an open objective on an ended conversation was missed. */\n is_conversation_ended: boolean\n /** When this standing was resolved (the ledger write). */\n recorded_at: string\n}\n\n/**\n * One row of `conversationObjectives.counts`: the grouped columns that were\n * requested plus the count.\n */\nexport interface ConversationObjectiveCount {\n definition_key?: string\n status?: ConversationObjectiveStatus\n source?: ConversationObjectiveSource\n is_provisional?: boolean\n type_key?: string\n phase_key?: string\n channel?: Channel\n count: number\n}\n\n/**\n * One of the type's phases as the conversation stands in it, derived from\n * the objectives pinned to the phase: `done` = every measured objective\n * achieved (≥ 1 measured; provisional counts); `current` = the first phase\n * in type order that is not done and has a measured objective; `upcoming` =\n * after the current one; `untracked` = no measured objective, so progress\n * cannot be told (dim, never current). `completed_at` is the latest\n * `achieved_at` among the phase's measured objectives once done.\n */\nexport interface ConversationPhaseProgress extends ConversationPhase {\n status: ConversationPhaseStatus\n completed_at?: string\n}\n\n/**\n * `conversations.getObjectiveProgress`: where the conversation stands — the\n * current phase key (`''` when the type has no phases or every tracked phase\n * is done), every phase with its status, every applicable objective with its\n * standing, and the applicable definitions the objectives reference by\n * `definition_key` (join `objectives[].definition_key` → `definitions[].key`\n * for name / description / measure). Objectives are ordered: ungrouped first,\n * then by the type's phase order, then name.\n */\nexport interface ConversationObjectiveProgress {\n phase_key: string\n phases: ConversationPhaseProgress[]\n objectives: ConversationObjective[]\n definitions: ConversationObjectiveDefinition[]\n}\n\n/** The org-wide ledger read (`conversationObjectives.list`); `since`/`until` bound `recorded_at`. */\nexport interface GetManyConversationObjectivesQuery extends PaginationQuery {\n conversation_id?: string\n definition_key?: string\n type_key?: string\n phase_key?: string\n channel?: string\n status?: string\n source?: string\n is_provisional?: boolean\n is_conversation_ended?: boolean\n /** Lower bound on `recorded_at` (inclusive), RFC 3339. */\n since?: string\n /** Upper bound on `recorded_at` (exclusive), RFC 3339. */\n until?: string\n}\n\n/**\n * Groups the ledger for dashboards. `group_by` is a COMMA-JOINED string (not\n * an array — the query serializer repeats array keys) whitelisted to\n * definition_key, status, source, is_provisional, type_key, phase_key,\n * channel (order kept; default `definition_key,status`).\n */\nexport interface CountConversationObjectivesQuery {\n group_by?: string\n definition_key?: string\n type_key?: string\n phase_key?: string\n channel?: string\n status?: string\n source?: string\n is_provisional?: boolean\n is_conversation_ended?: boolean\n /** Lower bound on `recorded_at` (inclusive), RFC 3339. */\n since?: string\n /** Upper bound on `recorded_at` (exclusive), RFC 3339. */\n until?: string\n}\n\nexport interface CountConversationObjectivesResponse {\n data: ConversationObjectiveCount[]\n}\n\n/**\n * The manual door (`conversationTags.create`): a person tags a conversation,\n * a message or a span. Anchors follow the definition's scope (conversation:\n * none; message: start == end message, no offsets; span: UNICODE CODE POINT\n * offsets into the message's first text block, end exclusive — convert from\n * UTF-16 indexes before sending). The service stamps `source = 'user'`,\n * confidence 1, and fills `quote` from the anchored text.\n */\nexport interface CreateConversationTagRequest {\n definition_key: string\n /** `\"true\"` | choice option key | score level index as a string. */\n value: string\n why?: string\n start_message_id?: string\n /** Unicode code-point index, inclusive. */\n start_offset?: number\n end_message_id?: string\n /** Unicode code-point index, exclusive. */\n end_offset?: number\n}\n\n/**\n * Patches a tag: `status` flips it between `active` and `dismissed` (the\n * feedback loop), `why` annotates it, and `value` / the anchors correct it —\n * absent fields keep the stored value and the merged tag is validated against\n * its definition like a manual tag. `definition_key` is immutable. A value or\n * anchor change turns the tag into a user tag (confidence 1, no\n * probabilities, no evaluation) so a later evaluation no longer replaces it;\n * a corrected `pending` tag becomes `active` unless `status` says otherwise.\n */\nexport interface UpdateConversationTagRequest {\n status?: ConversationTagStatus\n why?: string\n /** `\"true\"` | choice option key | score level index as a string. */\n value?: string\n /** Anchors are tri-state: omit = keep, `null` = clear, a value = set. */\n start_message_id?: string | null\n /** Unicode code-point index, inclusive. */\n start_offset?: number | null\n end_message_id?: string | null\n /** Unicode code-point index, exclusive. */\n end_offset?: number | null\n}\n\n/**\n * Starts a manual evaluation (`conversationTags.evaluate`, 202). Omitted or\n * empty `definition_keys` = every definition the currently matching sets\n * reference (and every model tag on the conversation is replaced); a list\n * narrows both the questions and the replacement to those keys.\n */\nexport interface EvaluateConversationTagsRequest {\n definition_keys?: string[]\n}\n\n/**\n * Serves both `conversationTags.listByConversation` (the service forces\n * `conversation_id` from the path) and the org-wide `conversationTags.list`.\n */\nexport interface ListConversationTagsQuery extends PaginationQuery {\n conversation_id?: string\n definition_key?: string\n value?: string\n channel?: string\n source?: string\n status?: string\n /** Tags anchored on the message at either end. */\n message_id?: string\n /** Tags on conversations whose roster contains the contact. */\n contact_id?: string\n /** Lower bound on `observed_at` (inclusive), RFC 3339. */\n since?: string\n /** Upper bound on `observed_at` (exclusive), RFC 3339. */\n until?: string\n}\n\n/**\n * Groups active tags for dashboards. `group_by` is a COMMA-JOINED string\n * (`'definition_key,value'`) — not an array, because the query serializer\n * repeats array keys — whitelisted to definition_key, value, channel (order\n * kept).\n */\nexport interface CountConversationTagsQuery {\n group_by?: string\n definition_key?: string\n channel?: string\n source?: string\n status?: string\n /** Lower bound on `observed_at` (inclusive), RFC 3339. */\n since?: string\n /** Upper bound on `observed_at` (exclusive), RFC 3339. */\n until?: string\n}\n\nexport interface CountConversationTagsResponse {\n data: ConversationTagCount[]\n}\n\nexport interface ListConversationTagEvaluationsQuery extends PaginationQuery {\n trigger?: string\n status?: string\n}\n\n/** Who assigned a contact's group membership. */\nexport type ContactGroupSource = 'manual' | 'model'\n\n/**\n * A generic org-shared audience taxonomy entry (\"external-client\",\n * \"internal-colleague\", …) — NOT tone-specific. Membership lives on the\n * contact (`Contact.group_key`, one group per contact) and is assignable by\n * any flow; tone-of-voice synthesis both reads and auto-assigns groups.\n * Module-deployable (contact-groups/<key>.json).\n */\nexport interface ContactGroup {\n org_id: string\n /** Immutable identity within the org — what models answer with. */\n key: string\n name: string\n /** Who belongs in the group — injected verbatim into the synthesis prompt. */\n description?: string\n /** True when tone synthesis proposed the group. Server-owned. */\n is_auto_created: boolean\n /** Module that deployed the group; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateContactGroupRequest {\n /** Lowercase kebab/snake/camel handle — no spaces. */\n key: string\n name: string\n description?: string\n module_slug?: string\n}\n\nexport interface UpdateContactGroupRequest {\n name?: string\n description?: string\n}\n\nexport interface ListContactGroupsQuery extends PaginationQuery {\n /** Case-insensitive substring match on key or name. */\n search?: string\n module_slug?: string\n}\n\n/** The whole-user synthesis lifecycle on a tone profile setup. */\nexport type ToneProfileSetupStatus = 'empty' | 'processing' | 'ready'\n\n/** A tone profile row's tier — derived, most specific wins at read time. */\nexport type ToneProfileScope = 'user' | 'channel' | 'group' | 'contact'\n\n/**\n * Who wrote a tone profile, and therefore who may change it. `manual` rows are\n * hand-authored and authoritative: synthesis never overwrites or prunes them,\n * and deleting the user's setup (the AI opt-in) leaves them standing. `model`\n * rows belong to the synthesis sweep, which owns them outright.\n */\nexport type ToneProfileSource = 'manual' | 'model'\n\n/**\n * The per-user opt-in for tone-of-voice synthesis: only set-up users are\n * swept. Also carries the whole-user synthesis claim (status/started_at).\n */\nexport interface ToneProfileSetup {\n id: string\n org_id: string\n /** The profiled platform user. */\n owned_by: UserRef\n status: ToneProfileSetupStatus\n started_at?: string\n last_synthesized_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * One tone-of-voice instruction row — synthesized or hand-authored (`source`).\n * Rows form a specificity\n * hierarchy — user aggregate (the constant voice), per-channel base, per\n * contact-group, per individual contact — and every row is SELF-CONTAINED: a\n * drafting consumer injects exactly one row's `instructions` verbatim (use\n * the resolve endpoint), never a concatenation of tiers.\n */\nexport interface ToneProfile {\n id: string\n org_id: string\n /** The profiled platform user. */\n owned_by: UserRef\n /** Absent = the cross-channel user aggregate (the voice proper). */\n channel?: Channel\n /** Scopes the row to one contact group; absent = the (user, channel) base. */\n contact_group_key?: string\n /** Scopes the row to one individual contact within the group. */\n contact_id?: string\n scope: ToneProfileScope\n /** Who owns this row — see ToneProfileSource. */\n source: ToneProfileSource\n /** COMPLETE markdown instruction set, served verbatim to a drafting model. */\n instructions: string\n /** Short delta vs the tier above — what a human scans; empty on root tiers. */\n differences?: string\n sample_count: number\n last_message_at?: string\n last_synthesized_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateToneProfileSetupRequest {\n /** Bare platform user id; the service resolves the full ref. */\n owned_by_id: string\n}\n\nexport type ListToneProfileSetupsQuery = PaginationQuery\n\nexport interface ListToneProfilesQuery extends PaginationQuery {\n owned_by_id?: string\n channel?: Channel\n scope?: ToneProfileScope\n /** Narrow to hand-authored (`manual`) or synthesized (`model`) rows. */\n source?: ToneProfileSource\n}\n\n/**\n * Writes ONE hand-authored tone profile. The identity is the scope tuple, not\n * an id — re-sending the same scope updates the row it created. The row lands\n * `source: 'manual'`, which locks that scope against synthesis; it also takes\n * the scope over from a `model` row already sitting there.\n *\n * Scope grammar (mirrors the resolve precedence): omit `channel` for the\n * cross-channel base voice; `contact_group_key` needs a `channel`;\n * `contact_id` needs both, because resolution reaches a contact row only\n * through its group.\n */\nexport interface UpsertToneProfileRequest {\n owned_by_id: string\n channel?: Channel\n contact_group_key?: string\n contact_id?: string\n /** COMPLETE markdown style guide for this tier; never a delta. */\n instructions: string\n /** Optional human-facing note on how this tier differs from the one above. */\n differences?: string\n}\n\n/**\n * A drafting context to resolve the single most-specific profile for:\n * contact → group → channel base → user aggregate.\n */\nexport interface ResolveToneProfileQuery {\n owned_by_id: string\n channel?: Channel\n contact_id?: string\n}\n\nexport interface PaginationQuery {\n page?: number\n page_size?: number\n sort_by?: string\n sort_direction?: 'asc' | 'desc'\n}\n\nexport interface ListConnectionsQuery extends PaginationQuery {\n connector_key?: string\n channel?: string\n scope?: string\n /**\n * Narrows to the user-scoped connections one person owns. Org-scoped\n * connections have no owner and never match.\n */\n owner_id?: string\n status?: string\n /**\n * The caller's intent: `read` (default) lists every connection they reach;\n * `write` only those they may send through — the compose picker's question.\n */\n permission?: 'read' | 'write'\n}\n\n/**\n * The delete's escape hatch. A connection delete makes the connector release\n * its provider-side registration first and refuses with a 502\n * `connector_uninstall_failed` when that fails — the row is the only handle on\n * that state. `is_forced` drops the row anyway, leaving the provider-side\n * leftovers as a manual cleanup.\n */\nexport interface DeleteConnectionQuery {\n is_forced?: boolean\n}\n\nexport interface ListConversationsQuery extends PaginationQuery {\n channel?: string\n status?: string\n connection_id?: string\n type_key?: string\n /** The meeting conversations born from one calendar event UID. */\n calendar_event_ical_uid?: string\n /** The calls dialled with one brief, or later given it. */\n brief_id?: string\n /**\n * Conversations whose row changed at or after this ISO instant: an outcome\n * set, a call ended, but also any other write such as a summary.\n */\n updated_after?: string\n /** How conversations ended (one of a type's outcome keys). */\n outcome_key?: string\n /**\n * Conversations of one room (Slack channel) — the room stream. A\n * present-but-EMPTY string is meaningful: it filters to the room-LESS\n * conversations (DMs, email, meetings), used to resolve a DM's main. The\n * value is applied verbatim server-side (`room_id = ''`), so only omit the\n * key (not set it to `''`) to mean \"any room\".\n */\n room_id?: string\n /**\n * Child conversations forked from one main conversation. A present-but-EMPTY\n * string filters to the MAINS (and DMs) — the conversations that are not\n * thread children (`parent_conversation_id = ''`); used to resolve a\n * channel's main conversation. Omit the key to mean \"children and mains\n * alike\".\n */\n parent_conversation_id?: string\n /** Threads whose roster contains this external party — the person stream. */\n /** Contact stream: threads whose roster contains the resolved person. */\n contact_id?: string\n /** \"Sent as\" stream: threads pinned to one sending identity (a contact address id). */\n sender_address_id?: string\n /** Opt into the root/latest message projection on each row. */\n include?: 'messages_summary'\n /**\n * Conversations carrying an ACTIVE conversation tag of this definition —\n * the \"which conversations talk about billing\" stream.\n */\n tag_key?: string\n /** With `tag_key`: only conversations whose tag has this value. */\n tag_value?: string\n /**\n * The hub's Mine / All axis. `own`: threads on the caller's own\n * connections and the org-wide ones (on a shared sending connection only\n * threads the caller is in), plus connection-less threads they created.\n * `all` (the default when omitted): everything the caller may read.\n */\n conversation_scope?: ConversationScope\n}\n\n/** `?conversation_scope=` values — see ListConversationsQuery. */\nexport type ConversationScope = 'own' | 'all'\n\n/** Unread counts follow the same Mine / All axis as the list. */\nexport interface UnreadCountsQuery {\n conversation_scope?: ConversationScope\n}\n\n/**\n * User-editable surface of a conversation (PATCH); everything else is owned by\n * ingest.\n */\nexport interface UpdateConversationRequest {\n subject?: string\n /** Markdown summary (auto-generated for meetings, freely editable). */\n summary?: string\n status?: ConversationStatus\n metadata?: Record<string, unknown>\n /** Set the type by hand (must exist; `''` clears). Leaves the outcome alone. */\n type_key?: string\n /**\n * How the conversation ended — one of `conversations.listOutcomes(id)`\n * (its type's outcomes or its channel's system outcomes; `''` clears). The\n * person's choice: never overridden by the model or the service. 400\n * `conversation_outcome_unknown` when the key is in neither list.\n */\n outcome_key?: string\n}\n\nexport interface ListMessagesQuery extends PaginationQuery {\n direction?: string\n status?: string\n}\n\nexport interface ListAgentListenersQuery extends PaginationQuery {\n connection_id?: string\n conversation_id?: string\n room_id?: string\n agent_key?: string\n is_enabled?: boolean\n}\n\n/**\n * Conversation filters: rules that drop matching inbound messages BEFORE\n * persistence (no message, no contact — only a content-free audit event) and,\n * on meeting calendar connections, gate whether the meeting bot is scheduled\n * at all (pre-join enforcement of the same rules — earliest possible point).\n * Scope-first evaluation: connection-scoped rules are final when one matches;\n * global rules apply otherwise. Specificity within a scope:\n * address > domain > title_keyword > role_based > automated >\n * self_originated > internal_participant > internal_conversations > all,\n * allow beats block within a class; an allow match is a final keep, which is\n * the auto-join composition mechanism (e.g. \"organized by me\" = a\n * connection-scoped all-block plus a self_originated allow).\n *\n * Channel matrix: address/self_originated/all act on every channel;\n * domain/title_keyword/internal_participant/internal_conversations act on\n * email + meeting connections; role_based/automated are email-only. A\n * connection-scoped rule of a type inert on that connection's channel is\n * rejected (invalid_filter_config); global rules are unrestricted and stay\n * inert where their facts are missing.\n */\nexport type ConversationFilterType =\n | 'address'\n | 'domain'\n | 'title_keyword'\n | 'role_based'\n | 'automated'\n | 'self_originated'\n | 'internal_participant'\n | 'internal_conversations'\n | 'all'\n/**\n * block drops the message; allow keeps it. restrict and share keep it too\n * (they rank as allow) and decide who sees the thread the message CREATES:\n * restrict writes only the rule's principals onto the new thread, share adds\n * them on top of what the thread inherits. Applied once, at creation.\n */\nexport type ConversationFilterAction = 'block' | 'allow' | 'restrict' | 'share'\n/** Which side of the message address/domain rules test (default: sender). */\nexport type FilterMatchOn = 'sender' | 'any_participant'\n/** Deterministic machine-mail header signals the automated filter matches. */\nexport type AutomatedSignal =\n | 'auto_submitted'\n | 'bulk'\n | 'mailing_list'\n | 'bounce'\n | 'auto_response_suppress'\n\n/** Exact canonical address (lowercased email / E.164 phone / provider id), any channel kind. */\nexport interface AddressFilterConfig {\n kind: ContactAddressKind\n value: string\n match_on?: FilterMatchOn\n}\n/** Equals on the parsed email domain (lowercase, no leading '@'). */\nexport interface DomainFilterConfig {\n domain: string\n match_on?: FilterMatchOn\n}\n/** Sender local-part is a role mailbox; empty prefixes = the built-in set. Email-only. */\nexport interface RoleBasedFilterConfig {\n prefixes?: string[]\n}\n/** Header-signal machine-mail detection; empty signals = all. Email-only. */\nexport interface AutomatedFilterConfig {\n signals?: AutomatedSignal[]\n}\n/** Title/subject contains any keyword (case-insensitive substring; stored lowercased). */\nexport interface TitleKeywordFilterConfig {\n keywords: string[]\n}\n/** Conversation originates from the connection owner (meeting organizer / self sender). Empty config. */\nexport type SelfOriginatedFilterConfig = Record<string, never>\n/** ≥1 participant OTHER than the connection self is on one of these domains (any-internal). */\nexport interface InternalParticipantFilterConfig {\n domains: string[]\n}\n/** Drops only when sender AND every recipient are on these domains. Always block. */\nexport interface InternalConversationsFilterConfig {\n domains: string[]\n}\n/** Matches every message (empty config) — the scope-control primitive. */\nexport type AllFilterConfig = Record<string, never>\n\nexport type ConversationFilterConfig =\n | AddressFilterConfig\n | DomainFilterConfig\n | TitleKeywordFilterConfig\n | RoleBasedFilterConfig\n | AutomatedFilterConfig\n | SelfOriginatedFilterConfig\n | InternalParticipantFilterConfig\n | InternalConversationsFilterConfig\n | AllFilterConfig\n\nexport interface ConversationFilter {\n id: string\n org_id: string\n /** Empty = global (org-wide); set = scoped to that connection. */\n connection_id: string\n filter_type: ConversationFilterType\n action: ConversationFilterAction\n filter_config?: ConversationFilterConfig\n is_enabled: boolean\n /** restrict / share only: who the created thread is opened to. */\n principals?: PrincipalRef[]\n /** restrict / share only: read or write (write implies read; the default). */\n permission?: 'read' | 'write'\n /** Read-only rollup: messages this rule matched in the last 30 days. */\n recent_event_count?: number\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** One drop-audit entry (content-free: routing/identity facts only). */\nexport interface ConversationFilterEvent {\n id: string\n org_id: string\n connection_id: string\n conversation_filter_id: string\n filter_type: ConversationFilterType\n reason: string\n sender_kind?: ContactAddressKind\n sender_value?: string\n external_message_id?: string\n /** The thread a restrict / share match applied to; empty on a drop. */\n conversation_id?: string\n occurred_at: string\n}\n\nexport interface CreateConversationFilterRequest {\n connection_id?: string\n filter_type: ConversationFilterType\n action: ConversationFilterAction\n filter_config?: Record<string, unknown>\n is_enabled?: boolean\n /** Required for restrict / share, empty otherwise. */\n principals?: PrincipalRef[]\n permission?: 'read' | 'write'\n /** Opts past the own-domain guard (self_domain_block). */\n is_self_domain_acknowledged?: boolean\n}\n\nexport interface UpdateConversationFilterRequest {\n /** filter_type and filter_config must be sent together. */\n filter_type?: ConversationFilterType\n action?: ConversationFilterAction\n filter_config?: Record<string, unknown>\n is_enabled?: boolean\n principals?: PrincipalRef[]\n permission?: 'read' | 'write'\n is_self_domain_acknowledged?: boolean\n}\n\nexport interface ListConversationFiltersQuery extends PaginationQuery {\n /** Omit = all; '' = global-only; an id = that connection's rules. */\n connection_id?: string\n filter_type?: ConversationFilterType\n action?: ConversationFilterAction\n is_enabled?: boolean\n}\n\nexport type ListConversationFilterEventsQuery = PaginationQuery\n\n/**\n * Discriminates a send target: a person's contact address or a venue. The\n * server also accepts the legacy 'participant' value as an alias for\n * 'contact-address'.\n */\nexport type RecipientKind = 'contact-address' | 'room'\nexport type ContactAddressKind =\n | 'email'\n | 'phone'\n | 'slack'\n /** A Microsoft Teams user's Entra object id (lowercase GUID), scoped to the tenant. */\n | 'teams'\n /** LinkedIn's stable profile id (ACoAA… / ACwAA… / AE…) — what sending needs. */\n | 'linkedin_id'\n /** The `/in/<slug>` public identifier — what humans and records hold. */\n | 'linkedin_public_identifier'\n /** Legacy alias of `linkedin_id` (rows written before the kind split); read-only. */\n | 'linkedin'\n | 'telegram'\n | 'instagram'\n | 'messenger'\n | 'x'\n | 'whatsapp'\nexport type ContactAddressSource = 'sync' | 'ingest' | 'manual' | 'merge'\nexport type ContactSource = 'sync' | 'ingest' | 'manual' | 'merge'\nexport type ContactStatus = 'active' | 'merged' | 'archived' | 'erased'\nexport type ConsentStatus = 'unknown' | 'opted_in' | 'opted_out'\n/** `opt_in_requested`: a double opt-in waits for confirmation; it changes no consent. */\nexport type PermissionEventType = 'opt_in' | 'opt_out' | 'block' | 'unblock' | 'opt_in_requested'\n/**\n * Why a message is sent — the unit a person consents to. A fixed set.\n * `transactional` is never consent-gated (only blocks and erasure stop it).\n */\nexport type Purpose = 'transactional' | 'service' | 'sales' | 'marketing' | 'newsletter'\n/**\n * Where a permission event came from. `provider` = the sending platform\n * observed it (its unsubscribe link, a spam complaint relayed by the mailbox\n * provider, a hard bounce); `link_click` stays for OUR unsubscribe links.\n */\nexport type PermissionEventSource =\n | 'manual'\n | 'import'\n | 'link_click'\n | 'reply'\n | 'api'\n | 'system'\n | 'provider'\nexport type MergeProposalStatus = 'proposed' | 'approved' | 'rejected' | 'superseded'\nexport type ErasureRequestStatus = 'requested' | 'completed'\nexport type RoomSource = 'sync' | 'ingest'\n\n/**\n * Send-time addressing VO: who/where an originated message goes. Points at a\n * ContactAddress or a Room by kind + external id (never a stored entity itself).\n */\nexport interface SendRecipient {\n kind: RecipientKind\n /** The connector-side id: a room's (Slack channel id) or a contact address's wire identifier (Slack user id, email address). */\n external_id: string\n}\n\n/** The actual PERSON an org communicates with — org-scoped, channel-agnostic. */\nexport interface Contact {\n id: string\n org_id: string\n name: string\n status: ContactStatus\n /** Person-level suppression — only block/unblock events move it. */\n is_blocked: boolean\n has_legal_hold: boolean\n consent_status: ConsentStatus\n consent_updated_at?: string\n /** Resolved platform identity when the person is a colleague. */\n platform_user?: UserRef\n /** Merge tombstone redirect (set when status is 'merged'). */\n merged_into_contact_id?: string\n source: ContactSource\n /** IANA zone name (Europe/Berlin); absent = unknown. Filled from directory sweeps while empty. */\n timezone?: string\n /**\n * BCP-47 language tag with optional region (de, de-CH, pt-BR); absent =\n * unknown. Named locale, not language: the region carries formatting\n * conventions on top of the language.\n */\n locale?: string\n /** ContactGroup membership (one group per contact); absent = unassigned. */\n group_key?: string\n /**\n * Who assigned the group: 'manual' assignments are authoritative (tone\n * synthesis never overrides them), 'model' ones may be reassigned by a run.\n */\n group_source?: ContactGroupSource\n has_manual_edits: boolean\n /** The contact's reachable endpoints, embedded on reads. */\n addresses?: ContactAddress[]\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** ONE canonical digital endpoint to reach a contact — the dedup backbone. */\nexport interface ContactAddress {\n id: string\n org_id: string\n contact_id: string\n kind: ContactAddressKind\n /** Provider-tenant qualifier (Slack workspace id); empty for global kinds. */\n scope?: string\n /** Canonical scalar (lowercased email, E.164 phone) — the lookup key. */\n value: string\n /** The identifier as observed on the wire (WhatsApp JID, original casing). */\n raw_value?: string\n /** Per-channel display name. */\n name: string\n consent_status: ConsentStatus\n consent_updated_at?: string\n is_blocked: boolean\n source: ContactAddressSource\n metadata: Record<string, unknown>\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** One entry in the append-only permission ledger (consent + suppression). */\nexport interface ContactPermissionEvent {\n id: string\n org_id: string\n contact_id: string\n /** Scopes the event to one address; absent/empty = contact-level. */\n contact_address_id?: string\n event: PermissionEventType\n /** Narrows a consent event to one purpose; absent = all purposes. */\n purpose?: Purpose\n basis?: string\n source: PermissionEventSource\n occurred_at: string\n note?: string\n evidence?: Record<string, unknown>\n /** The caller's key for the fact; unique per org when set. */\n external_ref?: string\n created_at: string\n created_by: UserRef\n}\n\n/** A contact's consent for one purpose, derived from the ledger (not stored). */\nexport interface ContactPurposeStatus {\n purpose: Exclude<Purpose, 'transactional'>\n status: ConsentStatus\n /** The ledger event that set `status`; absent when unknown. */\n decided_by_event_id?: string\n /** True when that event applies to all purposes. */\n is_inherited: boolean\n /** Addresses opted out of this purpose (or all) on their own scope. */\n opted_out_address_ids: string[]\n /** Addresses opted in to this purpose (or all) on their own scope, such as a double opt-in for one address. */\n opted_in_address_ids: string[]\n /** Addresses with a double opt-in for this purpose waiting to be confirmed. */\n pending_address_ids: string[]\n /** Addresses whose double opt-in for this purpose was not confirmed in time. */\n expired_address_ids: string[]\n}\n\n/** One double opt-in: a confirmation email asking one address for one purpose. */\nexport interface ConsentRequest {\n id: string\n org_id: string\n contact_id: string\n address: string\n purpose: Exclude<Purpose, 'transactional'>\n /** The mailbox the confirmation went out from. */\n connection_id: string\n message_id?: string\n /** The opt_in_requested event in the contact's ledger. */\n requested_event_id?: string\n evidence?: Record<string, unknown>\n expires_at: string\n confirmed_at?: string\n created_at: string\n}\n\n/** A contact's ledger, newest first, with the per-purpose consent. */\nexport interface ListPermissionEventsResponse {\n data: ContactPermissionEvent[]\n purposes: ContactPurposeStatus[]\n}\n\n/** One candidate duplicate pair awaiting review. */\nexport interface ContactMergeProposal {\n id: string\n org_id: string\n contact_a_id: string\n contact_b_id: string\n suggested_winner_id?: string\n confidence?: number\n evidence?: Record<string, unknown>\n verdict?: Record<string, unknown>\n status: MergeProposalStatus\n resolved_by?: UserRef\n resolved_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** A GDPR Art. 17 erasure request (requested → completed). */\nexport interface ContactErasureRequest {\n id: string\n org_id: string\n contact_id: string\n identifier_hashes: Array<{ kind: ContactAddressKind; hmac: string }>\n status: ErasureRequestStatus\n completed_at?: string\n stats?: Record<string, unknown>\n created_at: string\n created_by: UserRef\n}\n\n/** An addressable VENUE on a connection (Slack channel; later meeting rooms). */\nexport interface Room {\n id: string\n org_id: string\n connection_id: string\n /** Slack channel id — the id to post into. */\n external_id: string\n name: string\n metadata: Record<string, unknown>\n /** How the row was populated: a directory sweep or minted at ingest. */\n source: RoomSource\n last_seen_at: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface ListContactAddressesQuery extends PaginationQuery {\n /** Free-text needle matched against display name + canonical value. */\n q?: string\n kinds?: ContactAddressKind[]\n scope?: string\n}\n\nexport interface ListContactsQuery extends PaginationQuery {\n /** Free-text needle matched against contact name + address values. */\n q?: string\n status?: ContactStatus\n /** Members of one contact group (drives group-member lists). */\n group_key?: string\n /**\n * The contact bound to one platform user (at most one active contact per\n * user per org); `'me'` resolves to the caller — a client's way to its own\n * contact.\n */\n platform_user_id?: string\n}\n\nexport interface UpdateContactRequest {\n name?: string\n status?: 'active' | 'archived'\n has_legal_hold?: boolean\n /** IANA zone name; normalized server-side, 400 contact_timezone_invalid when unparseable; '' clears. */\n timezone?: string\n /** BCP-47 language tag; normalized server-side, 400 contact_locale_invalid when unparseable; '' clears. */\n locale?: string\n /**\n * Assigns the contact to a contact group ('' clears). A PATCH assignment is\n * stamped group_source='manual' — tone synthesis never overrides it.\n */\n group_key?: string\n}\n\n/**\n * Manually mints a contact with at least one address. Addresses are\n * canonicalized server-side; any address already owned by another contact\n * rejects the create with 409 contact_address_taken.\n */\nexport interface CreateContactRequest {\n /** Required without platform_user_id; with it, fills an empty name only. */\n name?: string\n /** Required (≥1) without platform_user_id; with it, attached to the colleague's contact. */\n addresses?: AttachContactAddressRequest[]\n /**\n * Colleague mode: ensure the contact bound to this platform user (created\n * from the account directory, or the existing one — every colleague has\n * exactly one) and attach the addresses to it. 200 when it already\n * existed, 201 when created; 404 `platform_user_not_found`, 409\n * `contact_platform_user_conflict`.\n */\n platform_user_id?: string\n /** IANA zone name; optional, validated as on update. */\n timezone?: string\n /** BCP-47 language tag; optional, validated as on update. */\n locale?: string\n}\n\nexport interface AttachContactAddressRequest {\n kind: ContactAddressKind\n scope?: string\n value: string\n name?: string\n}\n\n/** How a contact→record edge came to be: a user's explicit link, or the\n * binding maintained from the record's contact-address attributes (exactly one\n * per record; never unlinked by hand). */\nexport type ContactRecordLinkSource = 'manual' | 'record'\n\n/** One canonical address key of a contact (the dedup backbone). */\nexport interface ContactAddressKey {\n kind: ContactAddressKind\n value: string\n scope?: string\n raw_value?: string\n}\n\n/**\n * A directed edge from a contact to a business record (entity_slug +\n * record_id). Bare — no role; the relationship's semantics come from the\n * target entity. A `manual` link is immutable once created; a `record`\n * binding repoints/refreshes as the record's addresses change and carries the\n * keys the record contributed (`address_keys`).\n */\nexport interface ContactRecordLink {\n id: string\n org_id: string\n contact_id: string\n entity_slug: string\n record_id: string\n source: ContactRecordLinkSource\n address_keys?: ContactAddressKey[]\n created_at: string\n created_by: UserRef\n updated_at?: string\n updated_by?: UserRef\n}\n\nexport interface CreateContactRecordLinkRequest {\n contact_id: string\n entity_slug: string\n record_id: string\n}\n\nexport interface ListContactRecordLinksQuery extends PaginationQuery {\n contact_id?: string\n entity_slug?: string\n record_id?: string\n source?: ContactRecordLinkSource\n}\n\nexport interface MergeContactsRequest {\n source_contact_id: string\n}\n\nexport interface RecordPermissionEventRequest {\n contact_address_id?: string\n /**\n * Scopes the event to the contact's address with this value (an email\n * address, a phone number) when the caller does not know its id. Refused\n * with 400 when the contact has no such address. Ignored when\n * `contact_address_id` is set.\n */\n address?: string\n event: PermissionEventType\n /** One purpose; absent = all purposes. Consent events only; never `transactional`. */\n purpose?: Purpose\n basis?: string\n source?: PermissionEventSource\n occurred_at?: string\n note?: string\n evidence?: Record<string, unknown>\n /**\n * A key for the fact this event records (a sync's id for one upstream\n * status). When the org already has an event with this key, nothing is\n * recorded and the contact comes back unchanged.\n */\n external_ref?: string\n}\n\nexport interface BlockContactRequest {\n contact_address_id?: string\n note?: string\n}\n\nexport interface ListContactMergeProposalsQuery extends PaginationQuery {\n status?: MergeProposalStatus\n}\n\nexport interface ListRoomsQuery extends PaginationQuery {\n /** Free-text needle matched against name + external id. */\n q?: string\n}\n\nexport interface AddReactionRequest {\n /** Connector-native token (Slack shortcode like \"thumbsup\"). */\n emoji: string\n}\n\nexport interface ListReactionsResponse {\n data: Reaction[]\n}\n\nexport interface ResponseMeta {\n page: number\n page_size: number\n items_total: number\n pages_total: number\n}\n\nexport interface ListResponse<T> {\n meta: ResponseMeta\n data: T[]\n}\n\nexport type TranscriptionStatus = 'pending' | 'processing' | 'completed' | 'failed'\n\n/**\n * Post-transcription review lifecycle — the glossary-aware LLM pass that hunts\n * mistranscribed terms. `feedback_pending` means proposed mistranscribed terms\n * await human resolution; resolving the last one flips it to `completed`.\n */\nexport type TranscriptionReviewStatus =\n | 'open'\n | 'processing'\n | 'feedback_pending'\n | 'completed'\n | 'failed'\n\nexport interface TranscriptTurn {\n speaker: number\n speaker_label: string\n text: string\n start_ms: number\n end_ms: number\n confidence: number\n}\n\nexport interface Transcription {\n id: string\n org_id: string\n source_file_id: string\n audio_file_id: string\n transcript_file_id: string\n status: TranscriptionStatus\n review_status: TranscriptionReviewStatus\n review_started_at?: string\n language: string\n duration_seconds: number\n model: string\n is_diarized: boolean\n turns: TranscriptTurn[]\n speaker_count: number\n /**\n * Index-aligned speaker identities: `speakers[turn.speaker]` is the person\n * behind the turn (provider participant id, name, email, resolved contact).\n * Empty for transcriptions whose source carries no speaker identities.\n */\n speakers?: ContactRef[]\n provider_request_id: string\n conversation_id: string\n error: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Transcribes a storage-service audio file. Asynchronous: the row lands\n * `processing` and the caller polls until `completed`.\n */\nexport interface CreateTranscriptionRequest {\n file_id: string\n language?: string\n model?: string\n is_diarized?: boolean\n}\n\n/**\n * Lands an ALREADY WRITTEN transcript — no provider runs and the row is\n * `completed` when the call returns. This is how a transcript, and through\n * `materialize` a conversation, is authored from text with nothing to upload.\n * `source_file_id` stays empty, which is how a reader tells the two kinds apart.\n *\n * Timings are optional: plain text has none, and materialization then sequences\n * the turns by their position instead of by `start_ms`.\n */\n/**\n * One turn of an authored transcript. Distinct from TranscriptTurn (the read\n * shape, always fully populated) because everything but who-said-what is\n * derived server-side: an unlabelled speaker becomes \"Speaker N\", and text with\n * no timings is sequenced by position at materialization.\n */\nexport interface AuthoredTranscriptTurn {\n /** Speaker index — the same number means the same person. */\n speaker: number\n speaker_label?: string\n text: string\n start_ms?: number\n end_ms?: number\n confidence?: number\n}\n\nexport interface CreateTranscriptionFromTextRequest {\n turns: AuthoredTranscriptTurn[]\n language?: string\n /** Defaults to whether the turns name more than one speaker. */\n is_diarized?: boolean\n}\n\n/**\n * Edits a COMPLETED transcription in place. `turns`, when present, replace the\n * diarized turns wholesale; `speaker_labels` maps diarized speaker indexes\n * (\"0\", \"1\", …) to display labels and is applied across all turns. Editing\n * does NOT retro-update messages of an already-materialized conversation.\n */\nexport interface UpdateTranscriptionRequest {\n turns?: TranscriptTurn[]\n speaker_labels?: Record<string, string>\n language?: string\n}\n\n/** Channel defaults to adhoc; meeting is the only other allowed target. */\nexport interface MaterializeTranscriptionRequest {\n channel?: Channel\n subject?: string\n /** Maps diarized speaker indexes (\"0\", \"1\", …) to display names. */\n speaker_names?: Record<string, string>\n}\n\nexport interface ListTranscriptionsQuery extends PaginationQuery {\n status?: string\n /** List a conversation's transcription artifacts. */\n conversation_id?: string\n /** Narrow to the provider-side transcript identity. */\n provider_request_id?: string\n}\n\nexport type MistranscribedTermStatus = 'auto_replaced' | 'proposed' | 'accepted' | 'rejected'\n\nexport type MistranscriptionSuggestionSource = 'glossary' | 'model'\n\n/**\n * One term the post-transcription review pass judged likely misheard. High-\n * confidence findings are auto-replaced; the rest await accept/reject. An\n * accepted row referencing the glossary term it became (glossary_term_id) is a\n * known \"misheard → term\" mapping future passes replace deterministically.\n */\nexport interface MistranscribedTerm {\n id: string\n org_id: string\n transcription_id: string\n conversation_id?: string\n /** The text as transcribed. */\n term: string\n context_snippet?: string\n /** Indexes into the transcription's turns where the term occurs. */\n turn_indexes: number[]\n suggested_replacement?: string\n suggestion_source?: MistranscriptionSuggestionSource\n glossary_term_id?: string\n /** Confidence (0..1) the term IS mistranscribed. */\n misheard_confidence: number\n /** Confidence (0..1) the suggested replacement fits. */\n replacement_confidence: number\n status: MistranscribedTermStatus\n /** The text actually written into the transcript, once applied. */\n applied_replacement?: string\n resolved_by?: UserRef\n resolved_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Accepts a proposed finding: `replacement` overrides the reviewer's\n * suggestion when set; `create_glossary_term` promotes the applied replacement\n * into the org glossary and links the finding to it.\n */\nexport interface AcceptMistranscribedTermRequest {\n replacement?: string\n create_glossary_term?: {\n definition?: string\n priority?: number\n }\n}\n\nexport interface ListMistranscribedTermsQuery extends PaginationQuery {\n status?: MistranscribedTermStatus\n transcription_id?: string\n conversation_id?: string\n}\n\n/**\n * Sends a meeting bot (Ava) into a meeting through an active meeting\n * connection (adhoc-meeting). join_at schedules the bot ahead of time (ISO\n * instant; a scheduled bot joins reliably on time — omit to join now); title\n * seeds the meeting conversation's subject.\n */\nexport interface DispatchMeetingBotRequest {\n connection_id: string\n meeting_url: string\n title?: string\n join_at?: string\n /**\n * BCP-47 spoken-language hint for transcription (e.g. 'en', 'de'). Omit to\n * auto-detect (Deepgram multilingual). Only used when the deployment's\n * transcription provider is deepgram_streaming.\n */\n language?: string\n /**\n * The calendar meeting instance the bot is sent for — `calendar_event_ical_uid`\n * with `start_at` (the instance start, ISO) link the meeting conversation and\n * its bot to the calendar so the event's surface can follow them.\n */\n calendar_event_ical_uid?: string\n start_at?: string\n}\n\n/**\n * Lifecycle of an Ava bot: `scheduled` (sent, not yet in the call) → `joining`\n * → `recording` → `ended` | `failed`, or `removed` (a person withdrew Ava —\n * terminal; a removed meeting is not scheduled again).\n */\nexport type MeetingBotStatus =\n | 'scheduled'\n | 'joining'\n | 'recording'\n | 'ended'\n | 'failed'\n | 'removed'\n\n/**\n * The platform's memory of one Ava bot — \"Ava joins this meeting\", whoever's\n * calendar scheduled her. One bot per meeting instance per org when bot\n * deduplication is on; several rows can share an instance when it is off.\n */\nexport interface MeetingBot {\n id: string\n org_id: string\n /** The connection (calendar / adhoc) that scheduled the bot. */\n connection_id: string\n /** The provider's bot id; the meeting conversation's external id once begun. */\n external_bot_id: string\n /** The provider calendar-event id the bot was scheduled on; absent for adhoc. */\n provider_event_id?: string\n calendar_event_ical_uid?: string\n start_at?: string\n meeting_url?: string\n title?: string\n status: MeetingBotStatus\n /**\n * Platform users among the invitees: they see the bot — and may withdraw\n * Ava from their meeting — without owning the connection that scheduled her.\n */\n invitee_user_ids: string[]\n /** The meeting conversation; absent until the bot starts the meeting. */\n conversation_id?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface ListMeetingBotsQuery extends PaginationQuery {\n /** Meetings starting at/after this ISO instant. */\n start_after?: string\n /** Meetings starting before this ISO instant. */\n start_before?: string\n /** One calendar meeting (pair with the window to name an instance). */\n calendar_event_ical_uid?: string\n status?: MeetingBotStatus\n}\n\n// ── Sending rules ─────────────────────────────────────────────────────────────\n\n/**\n * Discriminates a sending rule: window (WHEN sending is allowed, recipient-\n * local weekday ranges), limit (HOW MUCH one connection may send per rolling\n * period), frequency_cap (HOW OFTEN one contact may be contacted per rolling\n * period).\n */\nexport type SendingRuleType = 'window' | 'limit' | 'frequency_cap' | 'warmup'\n/** Rolling lookback (\"last 24 hours from now\") — never a calendar day. */\nexport type SendingPeriod = 'rolling_24h' | 'rolling_7d' | 'rolling_30d'\n/**\n * ONE kind of act performed through a channel connection — shared by a\n * limit's `action` (what it counts), a channel action's `action_type` (what\n * was performed) and the eligibility check. `message` is the plain send\n * (valid on a limit, never on a channel action row). `profile_lookup` is the\n * silent twin of `profile_visit`: one provider read the platform performs to\n * learn a person's full identity (LinkedIn profile id + public identifier),\n * ledgered and limited like any other act.\n */\nexport type ChannelActionType =\n | 'message'\n | 'invitation'\n | 'inmail'\n | 'profile_visit'\n | 'profile_lookup'\nexport type Weekday =\n | 'monday'\n | 'tuesday'\n | 'wednesday'\n | 'thursday'\n | 'friday'\n | 'saturday'\n | 'sunday'\n\n/** One open range on one weekday, \"HH:MM\" wall-clock, from < until, same day. */\nexport interface WindowDay {\n day: Weekday\n from: string\n until: string\n}\nexport interface WindowRuleConfig {\n days: WindowDay[]\n /** IANA zone used for contacts without a timezone. */\n fallback_timezone: string\n}\nexport interface LimitRuleConfig {\n action: ChannelActionType\n max_count: number\n period: SendingPeriod\n /** Minimum spacing between consecutive sends; 0/absent = none. */\n min_gap_seconds?: number\n}\nexport interface FrequencyCapRuleConfig {\n max_count: number\n period: SendingPeriod\n}\n/**\n * A limit that RAMPS: `start_count` acts of `action` per rolling `period` on\n * the day the warmup started, growing by `daily_increase` (a count, or a\n * percent of the previous day's allowance when `is_increase_percent`) every\n * UTC calendar day until `max_count`, after which it behaves as a plain\n * limit. `started_at` may be omitted on create — the server stamps now.\n */\nexport interface WarmupRuleConfig {\n action: ChannelActionType\n start_count: number\n daily_increase: number\n is_increase_percent?: boolean\n max_count: number\n period: SendingPeriod\n started_at: string\n}\nexport type SendingRuleConfig =\n | WindowRuleConfig\n | LimitRuleConfig\n | FrequencyCapRuleConfig\n | WarmupRuleConfig\n\n/**\n * One outbound send constraint, defined once and LINKED to any number of\n * connections and/or channels (both empty = org-wide). Per rule type the most\n * specific tier wins at send time: names the connection > names the channel >\n * org-wide. Replies skip the rule when `is_reply_exempt`.\n */\n// ── Conversation briefs ──────────────────────────────────────────────────────────────\n\n/**\n * Lifecycle of a conversation brief: `prepared` (open — editable, waiting for its\n * call), `used` (attached to a call conversation; terminal), `discarded`\n * (declined without a call; terminal).\n */\nexport type ConversationBriefStatus = 'prepared' | 'used' | 'discarded'\n\n/**\n * Guidance prepared AHEAD of a conversation — \"talk to these people about\n * this\" — the conversation sibling of a draft message. Binding to a\n * conversation is always explicit: the softphone carries the brief id into\n * the call (attached at call start), or `attach` names the conversation.\n * Nothing matches by contact or number, and any number of briefs may be open\n * for the same people at once. Records that want a brief (an activity) store\n * its id; every UI surface renders from the id.\n */\nexport interface ConversationBrief {\n id: string\n org_id: string\n /** Human label (\"Renewal call with Dana\"); may be empty. */\n subject: string\n /** The people the conversation is with (deduplicated, sorted; may be empty — a phone brief has ≥ 1). */\n contact_ids: string[]\n /** How the conversation should happen (phone opens the softphone); absent = unspecified. */\n channel?: Channel\n /** ConversationType key the conversation is meant to be; stamped on attach. */\n type_key?: string\n /**\n * The calendar event (one person's copy) the brief prepares; attached to\n * the meeting's conversation when the meeting bot starts. Absent = no meeting.\n */\n calendar_event_id?: string\n /** The brief is every invitee's, not only the event owner's. */\n is_shared_with_participants: boolean\n /** The meeting instance the event belongs to (resolved from the event; read-only). */\n calendar_event_ical_uid?: string\n calendar_event_start_at?: string\n /**\n * The platform users the brief is for (the event owner; every resolved\n * invitee when shared) — they read it next to its creator. Read-only.\n */\n invitee_user_ids: string[]\n /** The conversation the brief was used on; absent until used. A conversation may carry several briefs. */\n conversation_id?: string\n status: ConversationBriefStatus\n /** Guidance text (markdown allowed). */\n content: string\n used_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateConversationBriefRequest {\n subject?: string\n /** The people the conversation is with (may be empty). */\n contact_ids?: string[]\n /** Must be a known channel when set. */\n channel?: Channel\n /** Must name an existing conversation type when set. */\n type_key?: string\n content: string\n /** The caller's view of a calendar event the brief prepares (the caller must be able to read it). */\n calendar_event_id?: string\n /** Every invitee's brief instead of only the event owner's (requires calendar_event_id). */\n is_shared_with_participants?: boolean\n}\n\n/** PATCH semantics — absent fields keep their value. Only open briefs. */\nexport interface UpdateConversationBriefRequest {\n subject?: string\n /** Replaces the set wholesale. */\n contact_ids?: string[]\n /** Empty string clears the channel. */\n channel?: Channel | ''\n content?: string\n type_key?: string\n /** Re-ties the brief; empty string unties it (and drops the sharing). */\n calendar_event_id?: string\n is_shared_with_participants?: boolean\n}\n\n/** Binds an open brief to a conversation explicitly. */\nexport interface AttachConversationBriefRequest {\n conversation_id: string\n}\n\nexport interface ListConversationBriefsQuery extends PaginationQuery {\n /** Briefs naming this person. */\n contact_id?: string\n conversation_id?: string\n /** The briefs for one person's copy of a calendar event. */\n calendar_event_id?: string\n /** Every visible brief of a meeting, across invitees' copies (+ start to pin one instance). */\n calendar_event_ical_uid?: string\n calendar_event_start_at?: string\n /** The briefs of the meetings starting in [after, before) — a calendar's visible range. */\n calendar_event_start_after?: string\n calendar_event_start_before?: string\n channel?: Channel\n type_key?: string\n status?: ConversationBriefStatus\n sort_by?: string\n sort?: 'asc' | 'desc'\n}\n\n/** Which emails a default signature is picked for. */\nexport type EmailSignatureAppliesTo = 'all' | 'new' | 'reply'\n\n/** A send's, draft's or draft edit's pick of a signature: the default, none, or a signature id. */\nexport type SignatureChoice = 'default' | 'none' | (string & {})\n\n/**\n * The block an email send adds below what the person wrote and above the\n * quote. Belongs to one person (`owned_by`) or, without one, to the\n * organisation; `connection_id` ties it to one mailbox. Among the defaults a\n * send picks the sending mailbox's, then the sender's own, then the\n * organisation's.\n */\nexport interface EmailSignature {\n id: string\n org_id: string\n name: string\n /** Sanitized like every stored email html. */\n html: string\n /** The plain-text part; derived from `html` unless `is_text_custom`. */\n text: string\n is_text_custom: boolean\n /** The person it belongs to; absent for the organisation. */\n owned_by?: UserRef\n /** The mailbox it is tied to; absent for every mailbox. */\n connection_id?: string\n is_default: boolean\n applies_to: EmailSignatureAppliesTo\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** A signature as one email carries it. */\nexport interface MessageSignature {\n id: string\n name: string\n html: string\n text: string\n}\n\n/** A send's, draft's or draft edit's pick of an unsubscribe link: none, or a link of the email's own. */\nexport type UnsubscribeChoice = 'none' | 'link'\n\n/**\n * What `{{ unsubscribe_url }}` renders to before a message exists. A send with\n * `unsubscribe: 'link'` swaps every occurrence for the recipient's own link;\n * an email sent without one (a test send, a preview) gets the address of a\n * page that says so.\n */\nexport const UNSUBSCRIBE_URL_PLACEHOLDER = 'https://unsubscribe.invalid/link'\n\n/** The layout an email went out in, as stored on the message: a snapshot, since the layout itself may change or go. */\nexport interface MessageLayout {\n id: string\n key?: string\n name: string\n /** The frame, with `{{ content }}` where the body goes. */\n html: string\n /** The frame of the plain part; absent leaves the text as written. */\n text?: string\n}\n\nexport interface CreateEmailSignatureRequest {\n name: string\n /** `html` or `text` is required. */\n html?: string\n /** Left empty, it is derived from `html`. */\n text?: string\n /** Empty or omitted makes it the organisation's. */\n owned_by_id?: string\n /** Empty or omitted makes it apply to every mailbox. */\n connection_id?: string\n /** Defaults to false. Becoming the default takes the flag off the others of the same owner, mailbox and kind. */\n is_default?: boolean\n /** Defaults to `all`. */\n applies_to?: EmailSignatureAppliesTo\n}\n\n/** Omitted fields keep what is stored. `text` sent empty goes back to being derived. */\nexport type UpdateEmailSignatureRequest = Partial<CreateEmailSignatureRequest>\n\nexport interface ListEmailSignaturesQuery extends PaginationQuery {\n owned_by_id?: string\n /** true: the organisation's own; false: everyone's personal ones. */\n is_organisation?: boolean\n connection_id?: string\n is_default?: boolean\n}\n\nexport interface ResolveEmailSignatureQuery {\n connection_id?: string\n /** Whose personal default counts; the caller when omitted. */\n owned_by_id?: string\n is_reply?: boolean\n}\n\n/**\n * What a message template holds: a whole message, a piece of a body, or a\n * layout. A layout is the frame of a designed email: html (and optionally\n * text) with `{{ content }}` where the body goes. A send names it with\n * `layout`; it is never sent on its own.\n */\nexport type MessageTemplateKind = 'message' | 'snippet' | 'layout'\n\n/**\n * A reusable message, or a reusable piece of one. `subject`, `html` and `text`\n * are Liquid templates: `{{ contact.first_name }}` is filled in from the\n * variables a render or a send passes.\n *\n * A template is copied into what uses it (a sequence step, a reply), never\n * referenced from it. A send that names one renders it at that moment.\n */\nexport interface MessageTemplate {\n id: string\n org_id: string\n /** The name modules and workflows use; absent for a template nothing refers to. */\n key?: string\n name: string\n description?: string\n kind: MessageTemplateKind\n /** The one channel it is written for; absent for any. */\n channel?: Channel\n /** The language it is written in, such as `de` or `en-GB`. */\n language?: string\n /** Why messages from it are sent; a send of it that names no purpose takes this one. */\n purpose?: Purpose\n tags: string[]\n /** A snippet has none. */\n subject?: string\n /** Sanitized like every stored email html, its Liquid kept as written. Empty for a text-only template. */\n html: string\n /** The plain body; derived from `html` unless `is_text_custom`. */\n text: string\n is_text_custom: boolean\n /** The person it belongs to; absent for the organisation. */\n owned_by?: UserRef\n /** The module that deployed it; absent for one made by hand. */\n module_slug?: string\n is_archived: boolean\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateMessageTemplateRequest {\n key?: string\n name: string\n description?: string\n /** Defaults to `message`. */\n kind?: MessageTemplateKind\n /** Empty or omitted writes it for any channel. */\n channel?: Channel | ''\n language?: string\n /** Empty or omitted leaves it unsaid. */\n purpose?: Purpose | ''\n tags?: string[]\n subject?: string\n /** `html` or `text` is required. */\n html?: string\n /** Left empty, it is derived from `html`. */\n text?: string\n /** Empty or omitted makes it the organisation's. */\n owned_by_id?: string\n module_slug?: string\n is_archived?: boolean\n}\n\n/**\n * Omitted fields keep what is stored. `text` sent empty goes back to being\n * derived; `key` sent empty takes the name away.\n */\nexport type UpdateMessageTemplateRequest = Partial<\n Omit<CreateMessageTemplateRequest, 'module_slug'>\n>\n\nexport interface ListMessageTemplatesQuery extends PaginationQuery {\n kind?: MessageTemplateKind\n /** Also finds templates written for any channel. */\n channel?: Channel\n language?: string\n module_slug?: string\n tag?: string\n /** Matches the name, the key and the description. */\n search?: string\n owned_by_id?: string\n /** true: the organisation's own; false: everyone's personal ones. */\n is_organisation?: boolean\n /** Archived templates are left out unless this is true. */\n is_archived?: boolean\n}\n\n/**\n * Fills in a template's variables. `template` names a stored template by id\n * or key; without it `subject`, `html` and `text` are the template itself.\n */\nexport interface RenderMessageTemplateRequest {\n template?: string\n subject?: string\n html?: string\n text?: string\n /** The names the Liquid reads: `{{ contact.first_name }}` reads `variables.contact.first_name`. */\n variables?: Record<string, unknown>\n /** Picked as a send picks it, for `connection_id`, `owned_by_id` and `is_reply`. */\n signature?: SignatureChoice\n connection_id?: string\n owned_by_id?: string\n is_reply?: boolean\n /** The layout the email would be sent in: its id or key, `none` or omitted for none. The answer carries it beside the body, which comes back without it. */\n layout?: string\n}\n\n/** What a send of the template would store, and the signature that would go below it. */\nexport interface RenderedMessageTemplate {\n subject: string\n /** Sanitized, with the editor's look. Empty for a text-only template. */\n html: string\n text: string\n signature: MessageSignature | null\n /** The frame the email would go out in, `{{ content }}` marking where the body and the signature go. Null or absent without one. */\n layout?: MessageLayout | null\n}\n\nexport interface SendingRule {\n id: string\n org_id: string\n name: string\n connection_ids: string[]\n channels: Channel[]\n rule_type: SendingRuleType\n rule_config?: SendingRuleConfig\n is_enabled: boolean\n is_reply_exempt: boolean\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateSendingRuleRequest {\n name?: string\n connection_ids?: string[]\n channels?: Channel[]\n rule_type: SendingRuleType\n rule_config: Record<string, unknown>\n /** Defaults to true. */\n is_enabled?: boolean\n /** Defaults per type: window + frequency_cap true, limit false. */\n is_reply_exempt?: boolean\n}\n\nexport interface UpdateSendingRuleRequest {\n name?: string\n /** Replaces the stored links wholesale when present. */\n connection_ids?: string[]\n channels?: Channel[]\n /** rule_type and rule_config must be sent together. */\n rule_type?: SendingRuleType\n rule_config?: Record<string, unknown>\n is_enabled?: boolean\n is_reply_exempt?: boolean\n}\n\nexport interface ListSendingRulesQuery extends PaginationQuery {\n /** Rules LINKED to this connection. */\n connection_id?: string\n channel?: Channel\n rule_type?: SendingRuleType\n is_enabled?: boolean\n}\n\n/** A recommended limit bundle for one class of sender account (static catalog). */\nexport interface SendingLimitPreset {\n key: string\n name: string\n description: string\n connector_keys: ConnectorKey[]\n is_recommended: boolean\n rules: (\n | { rule_type: 'limit'; rule_config: LimitRuleConfig }\n | { rule_type: 'warmup'; rule_config: WarmupRuleConfig }\n )[]\n}\n\nexport interface ListSendingLimitPresetsQuery {\n connector_key?: ConnectorKey\n}\n\nexport interface ApplySendingLimitPresetRequest {\n connection_ids: string[]\n preset_key: string\n}\n\n/** Dry-run twin of SendMessageRequest: addressing only, nothing minted. */\nexport interface SendEligibilityRequest {\n conversation_id?: string\n reply_to_message_id?: string\n connection_id?: string\n to?: SendRecipient[]\n cc?: SendRecipient[]\n bcc?: SendRecipient[]\n /**\n * Widens the check to a channel action (invitation, profile_visit, inmail):\n * originate mode only, the first `to` recipient is the target. Absent =\n * message.\n */\n action_type?: ChannelActionType\n /** The purpose the send would have; consent is checked for it. */\n purpose?: Purpose\n}\n\n/**\n * \"May this send go out now?\" — `reason` is the error code a real send would\n * fail with (sending_window_closed | sending_limit_reached |\n * frequency_cap_reached | contact_blocked | contact_opted_out);\n * `earliest_allowed_at` is set for the temporal three.\n */\nexport interface SendEligibility {\n is_allowed: boolean\n reason?: string\n rule_id?: string\n rule_type?: SendingRuleType\n earliest_allowed_at?: string\n contact_id?: string\n contact_address_id?: string\n}\n\n// ── Connector catalog ─────────────────────────────────────────────────────────\n\n/**\n * One connector WIRED in this deployment (registry membership decides\n * availability). `install_modes` lists the install variants the environment\n * supports for a direct-install connector (a sending platform's own_account /\n * managed); empty for OAuth / install-free connectors.\n */\n/**\n * ONE sending identity of a domain-authenticated email connection: an email\n * contact address on the connection's sender domain. A personal sender belongs\n * to a colleague's contact (`platform_user` set); a shared mailbox (sales@) to\n * a role contact without one. Computed from the contact directory on read.\n */\nexport interface EmailSender {\n contact_address_id: string\n contact_id: string\n from_email: string\n from_name: string\n platform_user?: UserRef\n /** The connection's fallback sender when neither the thread nor the user pins one. */\n is_default: boolean\n}\n\n/** Pins a connection's default sender (an address on its sender domain). */\nexport interface SetDefaultSenderRequest {\n contact_address_id: string\n}\n\nexport interface ConnectorCatalogEntry {\n key: ConnectorKey\n channel: Channel\n provider: ConnectorProvider\n install_modes: string[]\n}\n\n// ── Email deliverability (sending-platform connections) ──────────────────────\n\n/** One of a sending platform's suppression lists. */\nexport type EmailSuppressionKind =\n | 'bounces'\n | 'blocks'\n | 'spam_reports'\n | 'invalid_emails'\n | 'unsubscribes'\n\n/**\n * Ledger rollup over the last `days` days: DISTINCT messages per event type\n * (machine opens excluded). Rates are fractions (0–1): delivery / bounce /\n * hard-bounce over sent, open / click / spam / unsubscribe over delivered.\n */\nexport interface EmailHealthWindow {\n days: number\n sent: number\n delivered: number\n deferred: number\n bounced: number\n hard_bounced: number\n dropped: number\n opened: number\n clicked: number\n spam_reported: number\n unsubscribed: number\n delivery_rate: number\n bounce_rate: number\n hard_bounce_rate: number\n open_rate: number\n click_rate: number\n spam_rate: number\n unsubscribe_rate: number\n}\n\n/** The provider's composite sender-quality score (1–5, computed daily). */\nexport interface EmailEngagementQuality {\n date: string\n score: number\n bounce_classification: number\n bounce_rate: number\n engagement_recency: number\n open_rate: number\n spam_rate: number\n}\n\n/** The provider's own counters for this connection's traffic (its category). */\nexport interface EmailProviderStats {\n days: number\n requests: number\n processed: number\n delivered: number\n deferred: number\n bounces: number\n blocks: number\n bounce_drops: number\n invalid_emails: number\n opens: number\n unique_opens: number\n clicks: number\n unique_clicks: number\n spam_reports: number\n spam_report_drops: number\n unsubscribes: number\n unsubscribe_drops: number\n}\n\nexport interface EmailSuppressionCounts {\n bounces: number\n blocks: number\n spam_reports: number\n invalid_emails: number\n unsubscribes: number\n /** A list hit the page cap — the count is a floor. */\n is_approximate?: boolean\n}\n\nexport interface EmailDnsRecord {\n host: string\n type: string\n data: string\n is_valid: boolean\n reason?: string\n}\n\nexport interface EmailDomainStatus {\n domain: string\n is_valid: boolean\n dns: EmailDnsRecord[]\n}\n\nexport interface EmailSenderStatus {\n from_email: string\n /** authenticated_domain | single_sender */\n mode: string\n is_verified: boolean\n}\n\n/** One dedicated IP of the account with its warmup state. */\nexport interface EmailIp {\n ip: string\n is_warming_up: boolean\n warmup_started_at?: string\n pools: string[]\n}\n\n/**\n * The provider's account-level snapshot (refreshed daily by the connector's\n * sweep, or on demand with `refresh`). Every section is optional — a plan\n * without the feature or a failed pull leaves it absent and adds a warning.\n */\nexport interface EmailProviderHealth {\n engagement_quality?: EmailEngagementQuality\n stats?: EmailProviderStats\n suppressions?: EmailSuppressionCounts\n domain?: EmailDomainStatus\n sender?: EmailSenderStatus\n ips: EmailIp[]\n warnings?: string[]\n refreshed_at: string\n}\n\n/** GET /connections/:id/health — ledger windows + the provider snapshot. */\nexport interface EmailHealth {\n connection_id: string\n windows: EmailHealthWindow[]\n provider?: EmailProviderHealth\n}\n\nexport interface GetConnectionHealthQuery {\n /** Force a live provider pull (slow — several provider calls). */\n refresh?: boolean\n}\n\n/** One address on a provider suppression list. */\nexport interface EmailSuppression {\n kind: EmailSuppressionKind\n email: string\n reason?: string\n status?: string\n created_at: string\n}\n\n// ── Channel events ────────────────────────────────────────────────────────────\n\n/**\n * ONE provider-observed occurrence about an outbound message on a sending\n * platform: the delivery lifecycle (processed → delivered | deferred |\n * bounced | dropped) and engagement (opened, clicked, spam_reported,\n * unsubscribed, resubscribed). Provider vocabularies map onto these inside\n * the connector.\n */\nexport type ChannelEventType =\n | 'processed'\n | 'delivered'\n | 'deferred'\n | 'bounced'\n | 'dropped'\n | 'opened'\n | 'clicked'\n | 'spam_reported'\n | 'unsubscribed'\n | 'resubscribed'\n\n/** hard = the address is gone (suppressed); soft = this attempt was refused. */\nexport type BounceKind = 'hard' | 'soft'\n\n/** The provider's category of a bounce / block. */\nexport type BounceClassification =\n | 'invalid_address'\n | 'technical_failure'\n | 'content'\n | 'reputation'\n | 'volume'\n | 'mailbox_unavailable'\n | 'unclassified'\n\n/**\n * One row of the channel_event ledger — the sibling of channel actions (acts\n * WE perform) and reactions (edges): something the provider or the recipient\n * did that we record. Append-only, deduped on the provider's event id.\n * Message.delivery and provider-sourced contact permission events derive\n * from it.\n */\nexport interface ChannelEvent {\n id: string\n org_id: string\n connection_id: string\n connector_key: ConnectorKey\n channel: Channel\n /** The message the event is about; absent when unresolvable. */\n message_id?: string\n conversation_id?: string\n contact_id?: string\n contact_address_id?: string\n /** The provider's recipient (lowercased email). */\n recipient_address: string\n event_type: ChannelEventType\n external_event_id: string\n external_message_id?: string\n occurred_at: string\n /** Bounce / deferral / drop text (the SMTP response, the drop reason). */\n reason?: string\n response?: string\n bounce_kind?: BounceKind\n bounce_classification?: BounceClassification\n /** The clicked link (clicked events). */\n url?: string\n /** An opened event a mail client's privacy proxy generated, not the person. */\n is_machine_open?: boolean\n metadata: Record<string, unknown>\n created_at: string\n created_by: UserRef\n}\n\nexport interface ListChannelEventsQuery extends PaginationQuery {\n connection_id?: string\n message_id?: string\n conversation_id?: string\n contact_id?: string\n event_type?: ChannelEventType\n /** ISO instants bounding occurred_at (from inclusive, until exclusive). */\n from?: string\n until?: string\n sort_by?: string\n sort?: 'asc' | 'desc'\n}\n\n// ── Channel actions ───────────────────────────────────────────────────────────\n\n/**\n * Lifecycle of a channel action. Execution: pending → performed | failed.\n * Outcome (invitations): performed → accepted | declined | withdrawn |\n * expired; an inbound received invitation starts pending and ends\n * accepted | declined | expired.\n */\nexport type ChannelActionStatus =\n | 'pending'\n | 'performed'\n | 'failed'\n | 'accepted'\n | 'declined'\n | 'withdrawn'\n | 'expired'\n/** Our answer to an inbound channel action (a received invitation). */\nexport type ChannelActionResponse = 'accept' | 'decline'\n/** What an action type acts on: a person on the channel, or an external object. */\nexport type ChannelActionTargetKind = 'contact-address' | 'external'\n\n/**\n * One action type a connector performs, projected onto `connection.actions`.\n */\nexport interface ChannelActionCapability {\n action_type: ChannelActionType\n target_kind: ChannelActionTargetKind\n /** The act can be withdrawn after performing (an invitation). */\n is_cancelable: boolean\n /** An inbound act of this type can be answered (accept / decline). */\n is_respondable: boolean\n /** Performing also sends a message that lands as a Message + Conversation (InMail). */\n is_message_minting: boolean\n /** Bound of the free-text note the act carries (LinkedIn invitation: 300). */\n max_note_length?: number\n}\n\nexport interface InvitationParams {\n note?: string\n email?: string\n}\nexport type ProfileVisitParams = Record<string, never>\nexport interface InmailParams {\n subject?: string\n content: ContentBlock[]\n}\nexport type ChannelActionParams = InvitationParams | ProfileVisitParams | InmailParams\n\n/**\n * One act performed through a channel connection that is neither a message\n * nor a reaction — a LinkedIn invitation, a profile visit, an InMail (which\n * ALSO mints a message, see message_id). A LEDGER row: appended, transitioned\n * along its lifecycle, never toggled. `direction` outbound = we acted;\n * inbound = someone acted on us (a received invitation you may answer).\n * `created_by` is the performer on outbound rows (user or agent), the system\n * on ingested inbound rows; `updated_by` who accepted / declined / withdrew.\n */\nexport interface ChannelAction {\n id: string\n org_id: string\n connection_id: string\n connector_key: ConnectorKey\n channel: Channel\n action_type: ChannelActionType\n direction: MessageDirection\n status: ChannelActionStatus\n contact_id?: string\n contact_address_id?: string\n /** The provider-side identity acted on (a LinkedIn member id). */\n target_external_id: string\n contact: ContactRef\n /** An InMail's minted message; an invitation's note-chat once accepted. */\n message_id?: string\n conversation_id?: string\n params?: ChannelActionParams\n /** The provider handle (Unipile invitation id) — cancel / respond key. */\n external_action_id?: string\n error?: string\n occurred_at: string\n resolved_at?: string\n /** Provider enrichment: invitation usage %, network_distance, … */\n metadata: Record<string, unknown>\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** Performs one act. `target` is the person acted on (kind contact-address + the connector-side external id). */\nexport interface PerformChannelActionRequest {\n connection_id: string\n action_type: ChannelActionType\n target: SendRecipient\n /** Per-type input: invitation {note?, email?}; profile_visit {}; inmail {subject?, content}. */\n params?: Record<string, unknown>\n}\n\nexport interface RespondChannelActionRequest {\n response: ChannelActionResponse\n}\n\nexport interface ListChannelActionsQuery extends PaginationQuery {\n channel?: Channel\n connection_id?: string\n action_type?: ChannelActionType\n direction?: MessageDirection\n status?: ChannelActionStatus\n contact_id?: string\n}\n\n/**\n * What a PERSON recorded about a conversation — during a call, after a\n * meeting, while reading a thread. An append log, author-stamped, never\n * merged. Notes feed the summary (what the human found important) and the\n * summary-basis tag evaluations. As visible as the conversation; only the\n * author edits or deletes.\n */\nexport interface ConversationNote {\n id: string\n org_id: string\n conversation_id: string\n /** Markdown allowed. */\n content: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateConversationNoteRequest {\n content: string\n}\n\nexport interface UpdateConversationNoteRequest {\n content: string\n}\n\nexport interface ListConversationNotesQuery extends PaginationQuery {\n sort_by?: string\n sort?: 'asc' | 'desc'\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n AcceptMistranscribedTermRequest,\n AgentListener,\n ApplySendingLimitPresetRequest,\n AttachContactAddressRequest,\n AttachConversationBriefRequest,\n BlockContactRequest,\n CallTokenResponse,\n ChannelAction,\n ChannelEvent,\n Connection,\n ConnectorCatalogEntry,\n ConsentRequest,\n Contact,\n ContactAddress,\n ContactErasureRequest,\n ContactGroup,\n ContactMergeProposal,\n ContactRecordLink,\n Conversation,\n ConversationBrief,\n ConversationFilter,\n ConversationFilterEvent,\n ConversationNote,\n ConversationObjective,\n ConversationObjectiveDefinition,\n ConversationObjectiveProgress,\n ConversationOutcomeOption,\n ConversationTag,\n ConversationTagDefinition,\n ConversationTagEvaluation,\n ConversationTagSet,\n ConversationType,\n CountConversationObjectivesQuery,\n CountConversationObjectivesResponse,\n CountConversationTagsQuery,\n CountConversationTagsResponse,\n CreateAgentListenerRequest,\n CreateConnectionRequest,\n CreateContactGroupRequest,\n CreateContactRecordLinkRequest,\n CreateContactRequest,\n CreateConversationBriefRequest,\n CreateConversationFilterRequest,\n CreateConversationNoteRequest,\n CreateConversationObjectiveDefinitionRequest,\n CreateConversationTagDefinitionRequest,\n CreateConversationTagRequest,\n CreateConversationTagSetRequest,\n CreateConversationTypeRequest,\n CreateEmailSignatureRequest,\n CreateGlossaryTermRequest,\n CreateMessageTemplateRequest,\n CreateSendingRuleRequest,\n CreateToneProfileSetupRequest,\n CreateTranscriptionFromTextRequest,\n CreateTranscriptionRequest,\n DeleteConnectionQuery,\n DispatchMeetingBotRequest,\n EmailDomainStatus,\n EmailHealth,\n EmailSender,\n EmailSignature,\n EmailSuppression,\n EmailSuppressionKind,\n EvaluateConversationTagsRequest,\n GetConnectionHealthQuery,\n GetManyConversationObjectiveDefinitionsQuery,\n GetManyConversationObjectivesQuery,\n GlossaryTerm,\n InstallConnectionRequest,\n InstallConnectionResponse,\n ListAgentListenersQuery,\n ListChannelActionsQuery,\n ListChannelEventsQuery,\n ListConnectionsQuery,\n ListContactAddressesQuery,\n ListContactGroupsQuery,\n ListContactMergeProposalsQuery,\n ListContactRecordLinksQuery,\n ListContactsQuery,\n ListConversationBriefsQuery,\n ListConversationFilterEventsQuery,\n ListConversationFiltersQuery,\n ListConversationNotesQuery,\n ListConversationsQuery,\n ListConversationTagDefinitionsQuery,\n ListConversationTagEvaluationsQuery,\n ListConversationTagSetsQuery,\n ListConversationTagsQuery,\n ListConversationTypesQuery,\n ListEmailSignaturesQuery,\n ListGlossaryTermsQuery,\n ListMeetingBotsQuery,\n ListMessagesQuery,\n ListMessageTemplatesQuery,\n ListMistranscribedTermsQuery,\n ListPermissionEventsResponse,\n ListReactionsResponse,\n ListResponse,\n ListRoomsQuery,\n ListSendingLimitPresetsQuery,\n ListSendingRulesQuery,\n ListToneProfileSetupsQuery,\n ListToneProfilesQuery,\n ListTranscriptionsQuery,\n MaterializeTranscriptionRequest,\n MeetingBot,\n MergeContactsRequest,\n Message,\n MessageDraftVersions,\n MessageSignature,\n MessageTemplate,\n MintCallTokenRequest,\n MistranscribedTerm,\n PerformChannelActionRequest,\n PhoneNumber,\n Reaction,\n RecordPermissionEventRequest,\n RenderedMessageTemplate,\n RenderMessageTemplateRequest,\n ResolveEmailSignatureQuery,\n ResolveToneProfileQuery,\n RespondChannelActionRequest,\n Room,\n SendEligibility,\n SendEligibilityRequest,\n SendingLimitPreset,\n SendingRule,\n SendMessageRequest,\n SetCallRecordingRequest,\n SetDefaultSenderRequest,\n SyncConnectionRequest,\n ToneProfile,\n ToneProfileSetup,\n Transcription,\n UnreadCounts,\n UnreadCountsQuery,\n UpdateAgentListenerRequest,\n UpdateConnectionRequest,\n UpdateContactGroupRequest,\n UpdateContactRequest,\n UpdateConversationBriefRequest,\n UpdateConversationFilterRequest,\n UpdateConversationNoteRequest,\n UpdateConversationObjectiveDefinitionRequest,\n UpdateConversationRequest,\n UpdateConversationTagDefinitionRequest,\n UpdateConversationTagRequest,\n UpdateConversationTagSetRequest,\n UpdateConversationTypeRequest,\n UpdateDraftRequest,\n UpdateEmailSignatureRequest,\n UpdateGlossaryTermRequest,\n UpdateMessageTemplateRequest,\n UpdatePhoneNumberRequest,\n UpdateSendingRuleRequest,\n UpdateTranscriptionRequest,\n UpsertToneProfileRequest,\n} from './types.js'\nimport { type VoiceService, VoiceServiceImpl } from './voice.js'\n\nconst CONVERSATION_BASE_PATH = '/conversations/v1'\n\n/**\n * Facade for conversation-service: connections (channel-connector instances),\n * conversations + messages (THE platform Message), and agent listeners.\n *\n * ```ts\n * const conversation = new ConversationClient(client)\n * const { authorization_url } = await conversation.connections.install(id)\n * const inbox = await conversation.conversations.list({ channel: 'slack' })\n * ```\n */\nexport class ConversationClient {\n readonly connections: ConnectionService\n readonly conversations: ConversationService\n /** The person-level identity layer: contacts, addresses, merges, permissions. */\n readonly contacts: ContactService\n readonly messages: MessageService\n readonly agentListeners: AgentListenerService\n /** Ingest-time filter rules (drop-with-audit) + their event trail. */\n readonly conversationFilters: ConversationFilterService\n /** Outbound send constraints: windows, connection limits, frequency caps + presets. */\n readonly sendingRules: SendingRuleService\n readonly emailSignatures: EmailSignatureService\n /** Reusable messages and snippets, and rendering one for a recipient. */\n readonly messageTemplates: MessageTemplateService\n /**\n * Channel actions: acts performed through a connection that are neither a\n * message nor a reaction — LinkedIn invitations, profile visits, InMail.\n */\n readonly channelActions: ChannelActionService\n readonly channelEvents: ChannelEventService\n /** Per-org glossary: custom vocabulary that boosts transcription accuracy. */\n readonly glossaryTerms: GlossaryTermService\n /** Conversation taxonomy: the types the pre-summary classifier assigns. */\n readonly conversationTypes: ConversationTypeService\n /** Conversation intelligence: WHAT to look for — typed questions asked of conversations. */\n readonly conversationTagDefinitions: ConversationTagDefinitionService\n /** Conversation intelligence: WHERE and WHEN definitions are evaluated. */\n readonly conversationTagSets: ConversationTagSetService\n /** Conversation intelligence: the observations produced + their evaluation history. */\n readonly conversationTags: ConversationTagService\n /** Conversation objectives: WHAT a conversation should achieve (config, keyed, module-deployable). */\n readonly conversationObjectiveDefinitions: ConversationObjectiveDefinitionService\n /** Conversation objectives: the org-wide ledger of standings + grouped counts (read-only). */\n readonly conversationObjectives: ConversationObjectiveService\n /** Generic audience taxonomy; membership lives on the contact. */\n readonly contactGroups: ContactGroupService\n /** Tone-of-voice synthesis: per-user setups + the generated profiles. */\n readonly toneProfiles: ToneProfileService\n readonly transcriptions: TranscriptionService\n /** Review-pass findings: likely misheard terms awaiting accept/reject. */\n readonly mistranscribedTerms: MistranscribedTermService\n /** Meeting bots (Ava): dispatch into a meeting URL, summaries. */\n readonly meetings: MeetingService\n /** Ava's bots as remembered by the platform: list them, withdraw her from a meeting. */\n readonly meetingBots: MeetingBotService\n /** Realtime speech-to-text (dictation) — moved here from agent-service. */\n readonly voice: VoiceService\n readonly calls: CallService\n /** Conversation briefs: guidance prepared ahead of a conversation (call, meeting) with a contact. */\n readonly conversationBriefs: ConversationBriefService\n /** Conversation notes: what a person recorded about a conversation (append log, author-stamped). */\n readonly conversationNotes: ConversationNoteService\n\n constructor(client: ProteosClient) {\n this.connections = new ConnectionServiceImpl(client)\n this.conversations = new ConversationServiceImpl(client)\n this.contacts = new ContactServiceImpl(client)\n this.messages = new MessageServiceImpl(client)\n this.agentListeners = new AgentListenerServiceImpl(client)\n this.conversationFilters = new ConversationFilterServiceImpl(client)\n this.sendingRules = new SendingRuleServiceImpl(client)\n this.emailSignatures = new EmailSignatureServiceImpl(client)\n this.messageTemplates = new MessageTemplateServiceImpl(client)\n this.channelActions = new ChannelActionServiceImpl(client)\n this.channelEvents = new ChannelEventServiceImpl(client)\n this.glossaryTerms = new GlossaryTermServiceImpl(client)\n this.conversationTypes = new ConversationTypeServiceImpl(client)\n this.conversationTagDefinitions = new ConversationTagDefinitionServiceImpl(client)\n this.conversationTagSets = new ConversationTagSetServiceImpl(client)\n this.conversationTags = new ConversationTagServiceImpl(client)\n this.conversationObjectiveDefinitions = new ConversationObjectiveDefinitionServiceImpl(client)\n this.conversationObjectives = new ConversationObjectiveServiceImpl(client)\n this.contactGroups = new ContactGroupServiceImpl(client)\n this.toneProfiles = new ToneProfileServiceImpl(client)\n this.transcriptions = new TranscriptionServiceImpl(client)\n this.mistranscribedTerms = new MistranscribedTermServiceImpl(client)\n this.meetings = new MeetingServiceImpl(client)\n this.meetingBots = new MeetingBotServiceImpl(client)\n this.voice = new VoiceServiceImpl(client)\n this.calls = new CallServiceImpl(client)\n this.conversationBriefs = new ConversationBriefServiceImpl(client)\n this.conversationNotes = new ConversationNoteServiceImpl(client)\n }\n}\n\n/** Conversation notes — what a person recorded about a conversation. */\nexport interface ConversationNoteService {\n /** A conversation's notes, oldest first by default. */\n list(\n conversationId: string,\n query?: ListConversationNotesQuery,\n ): Promise<ListResponse<ConversationNote>>\n create(conversationId: string, request: CreateConversationNoteRequest): Promise<ConversationNote>\n /** Author only (403 `conversation_note_not_author`). */\n update(id: string, request: UpdateConversationNoteRequest): Promise<ConversationNote>\n /** Author only (403 `conversation_note_not_author`). */\n delete(id: string): Promise<void>\n}\n\nclass ConversationNoteServiceImpl implements ConversationNoteService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n conversationId: string,\n query: ListConversationNotesQuery = {},\n ): Promise<ListResponse<ConversationNote>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/notes`,\n query,\n )\n }\n\n create(\n conversationId: string,\n request: CreateConversationNoteRequest,\n ): Promise<ConversationNote> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/notes`,\n request,\n )\n }\n\n update(id: string, request: UpdateConversationNoteRequest): Promise<ConversationNote> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-notes/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n delete(id: string): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-notes/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/** Meeting bots (Ava) — dispatch by meeting URL, summaries. */\nexport interface MeetingService {\n /**\n * Send Ava to a meeting URL. Resolves with the pre-minted meeting\n * conversation (channel = the platform classified from the URL); transcript\n * turns then stream in as inbound messages while the meeting runs.\n */\n dispatch(request: DispatchMeetingBotRequest): Promise<Conversation>\n /**\n * START regenerating this meeting conversation's markdown summary from its\n * stored transcript, overwriting any existing one when it lands. Generation\n * runs server-side beyond this request, so the promise resolves as soon as the\n * conversation is CLAIMED — with `summary_status: 'processing'` and the OLD\n * `summary` still attached. Poll `conversations.get(id)` until\n * `summary_status` is `completed` (or `failed`) to read the new one.\n *\n * Rejects with `no_transcript` when the conversation has no completed\n * transcript to summarize, `summarization_unavailable` when the environment\n * has no generator configured, and `summary_in_progress` when a generation is\n * already running for this conversation.\n */\n summarize(conversationId: string): Promise<Conversation>\n}\n\nclass MeetingServiceImpl implements MeetingService {\n constructor(private readonly client: ProteosClient) {}\n\n dispatch(request: DispatchMeetingBotRequest): Promise<Conversation> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/meetings`, request)\n }\n\n summarize(conversationId: string): Promise<Conversation> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/meetings/${encodeURIComponent(conversationId)}/summarize`,\n )\n }\n}\n\n/**\n * Ava's bots as the platform remembers them: what a client shows as \"Ava joins\"\n * for a meeting, and the door to withdraw her.\n */\nexport interface MeetingBotService {\n /** The bots the caller may see, soonest meeting first. */\n list(query?: ListMeetingBotsQuery): Promise<ListResponse<MeetingBot>>\n /**\n * Withdraw Ava from the meeting this bot belongs to: every bot of that\n * meeting instance the caller may act on (scheduled from their connection,\n * or on a meeting they are invited to) is cancelled (scheduled) or leaves\n * the call (live), the rows become `removed`, and the calendar will not\n * schedule her again. Re-add her explicitly with `meetings.dispatch`.\n */\n remove(id: string): Promise<MeetingBot>\n}\n\nclass MeetingBotServiceImpl implements MeetingBotService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListMeetingBotsQuery = {}): Promise<ListResponse<MeetingBot>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/meeting-bots`, query)\n }\n\n remove(id: string): Promise<MeetingBot> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/meeting-bots/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/** Configured integration instances (Slack workspace, Gmail grant, …). */\nexport interface ConnectionService {\n list(query?: ListConnectionsQuery): Promise<ListResponse<Connection>>\n get(id: string): Promise<Connection>\n create(request: CreateConnectionRequest): Promise<Connection>\n update(id: string, request: UpdateConnectionRequest): Promise<Connection>\n /**\n * Delete a connection. The connector first releases its provider-side\n * registration (a Recall calendar and the OAuth grant behind it); when that\n * fails the delete is refused with a `connector_uninstall_failed` 502 rather\n * than orphaning it. Pass `{ is_forced: true }` to drop the row anyway and\n * clean up at the provider by hand.\n */\n delete(id: string, query?: DeleteConnectionQuery): Promise<void>\n /**\n * Begin the connector's install flow. OAuth connectors return an\n * `authorization_url` to open in a popup; direct-install connectors take\n * `{ input }` (user-supplied credentials) and complete server-side,\n * returning `is_completed` plus a one-time `setup` handout.\n */\n install(id: string, request?: InstallConnectionRequest): Promise<InstallConnectionResponse>\n /**\n * Trigger a historical backfill (\"sync all\") on an email connection: the\n * server fetches provider mail in the chosen range and ingests it through\n * the normal pipeline (conversation filters, dedupe, agent listeners).\n * Returns 202 with the connection already showing\n * settings.sync_status='in_progress' — poll get(id) until it flips to\n * done/failed. A running sync answers 409 (sync_already_running).\n */\n sync(id: string, request: SyncConnectionRequest): Promise<Connection>\n /** Search the contact addresses this connection can reach (org-deduped) for the compose picker. */\n listContactAddresses(\n connectionId: string,\n query?: ListContactAddressesQuery,\n ): Promise<ListResponse<ContactAddress>>\n /** Search a connection's addressable VENUES (Slack channels) for the compose picker. */\n listRooms(connectionId: string, query?: ListRoomsQuery): Promise<ListResponse<Room>>\n /**\n * Deliverability of a sending-platform connection (SendGrid): rates from\n * the channel_event ledger + the provider's snapshot (engagement quality,\n * counters, suppression counts, domain/sender state, dedicated IPs).\n * `email_provider_not_supported` on mailbox connectors.\n */\n getHealth(connectionId: string, query?: GetConnectionHealthQuery): Promise<EmailHealth>\n /** Ask the provider to re-check the sending domain's DNS. */\n validateDomain(connectionId: string): Promise<EmailDomainStatus>\n /** Re-send the single-sender verification mail (no-op on an authenticated domain). */\n resendSenderVerification(connectionId: string): Promise<void>\n /** Read one provider suppression list live. */\n listSuppressions(connectionId: string, kind: EmailSuppressionKind): Promise<EmailSuppression[]>\n /** Take an address off one provider suppression list (a false positive). */\n removeSuppression(connectionId: string, kind: EmailSuppressionKind, email: string): Promise<void>\n /** Start / stop the provider's automated warmup on a dedicated IP. */\n setIpWarmup(connectionId: string, ip: string, isEnabled: boolean): Promise<void>\n /** The runtime connector catalog: what is wired in this environment + install modes. */\n listConnectors(): Promise<ConnectorCatalogEntry[]>\n /**\n * The sender directory of a domain-authenticated email connection: every\n * email contact address on its domain (colleagues + shared mailboxes), the\n * default flagged. Empty on connections without a sender domain.\n */\n listSenders(connectionId: string): Promise<EmailSender[]>\n /** Pin the connection's fallback sender; returns the refreshed directory. */\n setDefaultSender(connectionId: string, request: SetDefaultSenderRequest): Promise<EmailSender[]>\n}\n\nclass ConnectionServiceImpl implements ConnectionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConnectionsQuery = {}): Promise<ListResponse<Connection>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/connections`, query)\n }\n\n get(id: string): Promise<Connection> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateConnectionRequest): Promise<Connection> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/connections`, request)\n }\n\n update(id: string, request: UpdateConnectionRequest): Promise<Connection> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string, query: DeleteConnectionQuery = {}): Promise<void> {\n await this.client.requestWithQuery(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n query,\n )\n }\n\n install(id: string, request?: InstallConnectionRequest): Promise<InstallConnectionResponse> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}/install`,\n request,\n )\n }\n\n sync(id: string, request: SyncConnectionRequest): Promise<Connection> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}/sync`,\n request,\n )\n }\n\n listContactAddresses(\n connectionId: string,\n query: ListContactAddressesQuery = {},\n ): Promise<ListResponse<ContactAddress>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/contact-addresses`,\n query,\n )\n }\n\n listRooms(connectionId: string, query: ListRoomsQuery = {}): Promise<ListResponse<Room>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/rooms`,\n query,\n )\n }\n\n getHealth(connectionId: string, query: GetConnectionHealthQuery = {}): Promise<EmailHealth> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/health`,\n query,\n )\n }\n\n validateDomain(connectionId: string): Promise<EmailDomainStatus> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/domain/validate`,\n )\n }\n\n resendSenderVerification(connectionId: string): Promise<void> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/sender/verify`,\n )\n }\n\n async listSuppressions(\n connectionId: string,\n kind: EmailSuppressionKind,\n ): Promise<EmailSuppression[]> {\n const response: { data: EmailSuppression[] } = await this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/suppressions`,\n { kind },\n )\n return response.data\n }\n\n removeSuppression(\n connectionId: string,\n kind: EmailSuppressionKind,\n email: string,\n ): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/suppressions/${encodeURIComponent(kind)}/${encodeURIComponent(email)}`,\n )\n }\n\n setIpWarmup(connectionId: string, ip: string, isEnabled: boolean): Promise<void> {\n return this.client.request(\n isEnabled ? 'POST' : 'DELETE',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/ip-warmup/${encodeURIComponent(ip)}`,\n )\n }\n\n async listConnectors(): Promise<ConnectorCatalogEntry[]> {\n const response: { data: ConnectorCatalogEntry[] } = await this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connectors`,\n )\n return response.data\n }\n\n async listSenders(connectionId: string): Promise<EmailSender[]> {\n const response: { data: EmailSender[] } = await this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/senders`,\n )\n return response.data\n }\n\n async setDefaultSender(\n connectionId: string,\n request: SetDefaultSenderRequest,\n ): Promise<EmailSender[]> {\n const response: { data: EmailSender[] } = await this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/senders/default`,\n request,\n )\n return response.data\n }\n}\n\n/** The person-level identity layer: contacts, addresses, merges, permissions, erasure. */\nexport interface ContactService {\n list(query?: ListContactsQuery): Promise<ListResponse<Contact>>\n get(id: string): Promise<Contact>\n /**\n * Manually mint a contact (sync dedup — 409 contact_address_taken on any\n * owned address), or with `platform_user_id` ensure a colleague's bound\n * contact and attach the addresses to it.\n */\n create(request: CreateContactRequest): Promise<Contact>\n update(id: string, request: UpdateContactRequest): Promise<Contact>\n attachAddress(contactId: string, request: AttachContactAddressRequest): Promise<Contact>\n detachAddress(contactId: string, addressId: string): Promise<Contact>\n /** Link the contact to a business record (bare edge; 409 contact_record_link_exists on duplicates). */\n linkRecord(request: CreateContactRecordLinkRequest): Promise<ContactRecordLink>\n /** Page contact→record edges by contact_id, or by entity_slug + record_id. */\n listRecordLinks(query?: ListContactRecordLinksQuery): Promise<ListResponse<ContactRecordLink>>\n getRecordLink(linkId: string): Promise<ContactRecordLink>\n unlinkRecord(linkId: string): Promise<void>\n /** Fold source_contact_id into contactId (contactId wins). */\n merge(contactId: string, request: MergeContactsRequest): Promise<Contact>\n /** The contact's permission ledger, newest first, with per-purpose consent. */\n listPermissionEvents(contactId: string): Promise<ListPermissionEventsResponse>\n recordPermissionEvent(contactId: string, request: RecordPermissionEventRequest): Promise<Contact>\n /**\n * Send a new confirmation for a double opt-in that was not confirmed (new\n * link and expiry, same mailbox, address and purpose); 409\n * consent_request_confirmed once it was.\n */\n resendConsentRequest(requestId: string): Promise<ConsentRequest>\n block(contactId: string, request?: BlockContactRequest): Promise<Contact>\n unblock(contactId: string, request?: BlockContactRequest): Promise<Contact>\n requestErasure(contactId: string): Promise<ContactErasureRequest>\n listErasureRequests(contactId: string): Promise<ContactErasureRequest[]>\n listMergeProposals(\n query?: ListContactMergeProposalsQuery,\n ): Promise<ListResponse<ContactMergeProposal>>\n approveMergeProposal(proposalId: string): Promise<ContactMergeProposal>\n rejectMergeProposal(proposalId: string): Promise<ContactMergeProposal>\n}\n\nclass ContactServiceImpl implements ContactService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListContactsQuery = {}): Promise<ListResponse<Contact>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/contacts`, query)\n }\n\n get(id: string): Promise<Contact> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateContactRequest): Promise<Contact> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/contacts`, request)\n }\n\n update(id: string, request: UpdateContactRequest): Promise<Contact> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n attachAddress(contactId: string, request: AttachContactAddressRequest): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/addresses`,\n request,\n )\n }\n\n detachAddress(contactId: string, addressId: string): Promise<Contact> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/addresses/${encodeURIComponent(addressId)}`,\n )\n }\n\n linkRecord(request: CreateContactRecordLinkRequest): Promise<ContactRecordLink> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/contact-record-links`, request)\n }\n\n listRecordLinks(\n query: ListContactRecordLinksQuery = {},\n ): Promise<ListResponse<ContactRecordLink>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contact-record-links`,\n query,\n )\n }\n\n getRecordLink(linkId: string): Promise<ContactRecordLink> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contact-record-links/${encodeURIComponent(linkId)}`,\n )\n }\n\n unlinkRecord(linkId: string): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/contact-record-links/${encodeURIComponent(linkId)}`,\n )\n }\n\n merge(contactId: string, request: MergeContactsRequest): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/merge`,\n request,\n )\n }\n\n listPermissionEvents(contactId: string): Promise<ListPermissionEventsResponse> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/permission-events`,\n )\n }\n\n recordPermissionEvent(\n contactId: string,\n request: RecordPermissionEventRequest,\n ): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/permission-events`,\n request,\n )\n }\n\n resendConsentRequest(requestId: string): Promise<ConsentRequest> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/consent-requests/${encodeURIComponent(requestId)}/resend`,\n )\n }\n\n block(contactId: string, request: BlockContactRequest = {}): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/block`,\n request,\n )\n }\n\n unblock(contactId: string, request: BlockContactRequest = {}): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/unblock`,\n request,\n )\n }\n\n requestErasure(contactId: string): Promise<ContactErasureRequest> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/erasure-requests`,\n )\n }\n\n listErasureRequests(contactId: string): Promise<ContactErasureRequest[]> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/erasure-requests`,\n )\n }\n\n listMergeProposals(\n query: ListContactMergeProposalsQuery = {},\n ): Promise<ListResponse<ContactMergeProposal>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contact-merge-proposals`,\n query,\n )\n }\n\n approveMergeProposal(proposalId: string): Promise<ContactMergeProposal> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contact-merge-proposals/${encodeURIComponent(proposalId)}/approve`,\n )\n }\n\n rejectMergeProposal(proposalId: string): Promise<ContactMergeProposal> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contact-merge-proposals/${encodeURIComponent(proposalId)}/reject`,\n )\n }\n}\n\n/** Conversation threads across every channel (inbox order: last_message_at). */\nexport interface ConversationService {\n list(query?: ListConversationsQuery): Promise<ListResponse<Conversation>>\n get(id: string): Promise<Conversation>\n /** Patch the user-editable surface (subject, summary, status, metadata). */\n update(id: string, request: UpdateConversationRequest): Promise<Conversation>\n /**\n * What the conversation may end with: its type's outcomes, then its\n * channel's system outcomes — the picker's list and the valid\n * `outcome_key` values for `update`.\n */\n listOutcomes(id: string): Promise<{ data: ConversationOutcomeOption[] }>\n /**\n * Where the conversation stands against its objectives: the current phase,\n * every phase's status, every applicable objective's standing and the\n * definitions they reference — the checklist from one read.\n */\n getObjectiveProgress(id: string): Promise<ConversationObjectiveProgress>\n end(id: string): Promise<Conversation>\n /**\n * Hard-delete the conversation, its thread children, and every dependent\n * row (messages, attachments, read markers, transcriptions). Irreversible.\n */\n delete(id: string): Promise<void>\n /** Upsert the requesting user's read marker to now (open a conversation). */\n markRead(id: string): Promise<void>\n /** Remove the marker — the conversation reads as unread again. */\n markUnread(id: string): Promise<void>\n /** Unread-conversation counts for the requesting user (envelope + badges). */\n unreadCounts(query?: UnreadCountsQuery): Promise<UnreadCounts>\n}\n\nclass ConversationServiceImpl implements ConversationService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationsQuery = {}): Promise<ListResponse<Conversation>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/conversations`, query)\n }\n\n get(id: string): Promise<Conversation> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}`,\n )\n }\n\n listOutcomes(id: string): Promise<{ data: ConversationOutcomeOption[] }> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/outcomes`,\n )\n }\n\n async getObjectiveProgress(id: string): Promise<ConversationObjectiveProgress> {\n const response = await this.client.request<{ data: ConversationObjectiveProgress }>(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/objective-progress`,\n )\n return response.data\n }\n\n update(id: string, request: UpdateConversationRequest): Promise<Conversation> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n end(id: string): Promise<Conversation> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/end`,\n )\n }\n\n delete(id: string): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}`,\n )\n }\n\n markRead(id: string): Promise<void> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/read`,\n )\n }\n\n markUnread(id: string): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/read`,\n )\n }\n\n unreadCounts(query?: UnreadCountsQuery): Promise<UnreadCounts> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/unread-counts`,\n query,\n )\n }\n}\n\n/** Messages within a conversation (ordered by occurred_at) + outbound send + drafts + reactions. */\nexport interface MessageService {\n listByConversation(\n conversationId: string,\n query?: ListMessagesQuery,\n ): Promise<ListResponse<Message>>\n /** One message with its read-time projections (reactions, attachments). */\n get(messageId: string): Promise<Message>\n send(request: SendMessageRequest): Promise<Message>\n /**\n * Dry-run of the sending gate: same addressing as send, no content, nothing\n * minted. Answers whether the send may go out now and, when held, the\n * earliest instant it may (`earliest_allowed_at`).\n */\n checkSendEligibility(request: SendEligibilityRequest): Promise<SendEligibility>\n /**\n * Store an outbound message for human review (status=draft) — same request\n * shape as send, nothing reaches the connector until sendDraft. Originate\n * mode mints a hidden status=draft conversation.\n */\n draft(request: SendMessageRequest): Promise<Message>\n /**\n * Replace a draft's editable surface (full state, PUT semantics). 409\n * `draft_not_editable` once the draft was sent or rejected.\n */\n updateDraft(messageId: string, request: UpdateDraftRequest): Promise<Message>\n /** A draft's history, oldest first, plus what changed. Also readable after send. */\n listDraftVersions(messageId: string): Promise<MessageDraftVersions>\n /** Deliver a draft (draft → pending → sent/failed). 409 on a lost race. */\n sendDraft(messageId: string): Promise<Message>\n /** Decline a draft (draft → rejected, terminal). 409 on a lost race. */\n rejectDraft(messageId: string): Promise<Message>\n /** Aggregated reactions on one message (also rides on Message.reactions). */\n getReactions(messageId: string): Promise<Reaction[]>\n /**\n * Place an emoji (connector-native token) via the message's connector.\n * Rejected with `reactions_not_supported` on reaction-less channels — gate\n * the affordance on the connection's `supports_reactions` / `reactions`.\n */\n addReaction(messageId: string, emoji: string): Promise<Reaction[]>\n removeReaction(messageId: string, emoji: string): Promise<Reaction[]>\n}\n\nclass MessageServiceImpl implements MessageService {\n constructor(private readonly client: ProteosClient) {}\n\n listByConversation(\n conversationId: string,\n query: ListMessagesQuery = {},\n ): Promise<ListResponse<Message>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/messages`,\n query,\n )\n }\n\n get(messageId: string): Promise<Message> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}`,\n )\n }\n\n send(request: SendMessageRequest): Promise<Message> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/messages/send`, request)\n }\n\n checkSendEligibility(request: SendEligibilityRequest): Promise<SendEligibility> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/messages/send-eligibility`,\n request,\n )\n }\n\n draft(request: SendMessageRequest): Promise<Message> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/messages/draft`, request)\n }\n\n updateDraft(messageId: string, request: UpdateDraftRequest): Promise<Message> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/draft`,\n request,\n )\n }\n\n listDraftVersions(messageId: string): Promise<MessageDraftVersions> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/draft-versions`,\n )\n }\n\n sendDraft(messageId: string): Promise<Message> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/send`,\n )\n }\n\n rejectDraft(messageId: string): Promise<Message> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/reject`,\n )\n }\n\n async getReactions(messageId: string): Promise<Reaction[]> {\n const response: ListReactionsResponse = await this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/reactions`,\n )\n return response.data\n }\n\n async addReaction(messageId: string, emoji: string): Promise<Reaction[]> {\n const response: ListReactionsResponse = await this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/reactions`,\n { emoji },\n )\n return response.data\n }\n\n async removeReaction(messageId: string, emoji: string): Promise<Reaction[]> {\n const response: ListReactionsResponse = await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/reactions/${encodeURIComponent(emoji)}`,\n )\n return response.data\n }\n}\n\n/** Rules binding inbound messages to agents. */\nexport interface AgentListenerService {\n list(query?: ListAgentListenersQuery): Promise<ListResponse<AgentListener>>\n get(id: string): Promise<AgentListener>\n create(request: CreateAgentListenerRequest): Promise<AgentListener>\n update(id: string, request: UpdateAgentListenerRequest): Promise<AgentListener>\n delete(id: string): Promise<void>\n}\n\nclass AgentListenerServiceImpl implements AgentListenerService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListAgentListenersQuery = {}): Promise<ListResponse<AgentListener>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/agent-listeners`, query)\n }\n\n get(id: string): Promise<AgentListener> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/agent-listeners/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateAgentListenerRequest): Promise<AgentListener> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/agent-listeners`, request)\n }\n\n update(id: string, request: UpdateAgentListenerRequest): Promise<AgentListener> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/agent-listeners/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/agent-listeners/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/**\n * Ingest-time conversation filters: block/allow rules that drop matching\n * inbound messages before persistence, scoped globally or per connection.\n * listEvents pages a rule's drop-audit trail (who got dropped, when, why).\n */\nexport interface ConversationFilterService {\n list(query?: ListConversationFiltersQuery): Promise<ListResponse<ConversationFilter>>\n get(id: string): Promise<ConversationFilter>\n create(request: CreateConversationFilterRequest): Promise<ConversationFilter>\n update(id: string, request: UpdateConversationFilterRequest): Promise<ConversationFilter>\n delete(id: string): Promise<void>\n listEvents(\n id: string,\n query?: ListConversationFilterEventsQuery,\n ): Promise<ListResponse<ConversationFilterEvent>>\n}\n\nclass ConversationFilterServiceImpl implements ConversationFilterService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationFiltersQuery = {}): Promise<ListResponse<ConversationFilter>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-filters`,\n query,\n )\n }\n\n get(id: string): Promise<ConversationFilter> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-filters/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateConversationFilterRequest): Promise<ConversationFilter> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/conversation-filters`, request)\n }\n\n update(id: string, request: UpdateConversationFilterRequest): Promise<ConversationFilter> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-filters/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-filters/${encodeURIComponent(id)}`,\n )\n }\n\n listEvents(\n id: string,\n query: ListConversationFilterEventsQuery = {},\n ): Promise<ListResponse<ConversationFilterEvent>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-filters/${encodeURIComponent(id)}/events`,\n query,\n )\n }\n}\n\n/**\n * Per-org glossary: custom-vocabulary terms that boost transcription accuracy.\n * A term feeds the transcription provider's keyterm prompting; `priority` ranks\n * a term (prioritized terms are injected first, then unprioritized), which\n * decides the top 100 sent when an org stores more than the provider's cap.\n */\nexport interface GlossaryTermService {\n list(query?: ListGlossaryTermsQuery): Promise<ListResponse<GlossaryTerm>>\n get(id: string): Promise<GlossaryTerm>\n create(request: CreateGlossaryTermRequest): Promise<GlossaryTerm>\n update(id: string, request: UpdateGlossaryTermRequest): Promise<GlossaryTerm>\n delete(id: string): Promise<void>\n}\n\nclass GlossaryTermServiceImpl implements GlossaryTermService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListGlossaryTermsQuery = {}): Promise<ListResponse<GlossaryTerm>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/glossary-terms`, query)\n }\n\n get(id: string): Promise<GlossaryTerm> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/glossary-terms/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateGlossaryTermRequest): Promise<GlossaryTerm> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/glossary-terms`, request)\n }\n\n update(id: string, request: UpdateGlossaryTermRequest): Promise<GlossaryTerm> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/glossary-terms/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/glossary-terms/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/**\n * The org's conversation taxonomy. Before a meeting summary is generated, a\n * cheap classifier reads the transcript head plus every type's `definition`\n * and picks the matching `key` — the result lands on `Conversation.type_key`,\n * and a type whose `config.summary_prompt_key` names an agent-service prompt\n * swaps the summary system prompt for that prompt's current body. Keyed by\n * `key` (not id); `upsert` is the idempotent module-deploy door.\n */\nexport interface ConversationTypeService {\n list(query?: ListConversationTypesQuery): Promise<ListResponse<ConversationType>>\n get(key: string): Promise<ConversationType>\n create(request: CreateConversationTypeRequest): Promise<ConversationType>\n update(key: string, request: UpdateConversationTypeRequest): Promise<ConversationType>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(key: string, request: CreateConversationTypeRequest): Promise<ConversationType>\n delete(key: string): Promise<void>\n}\n\nclass ConversationTypeServiceImpl implements ConversationTypeService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationTypesQuery = {}): Promise<ListResponse<ConversationType>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-types`,\n query,\n )\n }\n\n get(key: string): Promise<ConversationType> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-types/${encodeURIComponent(key)}`,\n )\n }\n\n create(request: CreateConversationTypeRequest): Promise<ConversationType> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/conversation-types`, request)\n }\n\n update(key: string, request: UpdateConversationTypeRequest): Promise<ConversationType> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-types/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(key: string, request: CreateConversationTypeRequest): Promise<ConversationType> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversation-types/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-types/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Conversation tag definitions: WHAT to look for in a conversation — one\n * typed question (boolean / choice / score) plus where its answers anchor\n * (`scope`) and which model path answers (`evaluator`). A definition is only\n * evaluated through the tag sets that reference it. Keyed by `key` (not id);\n * `upsert` is the idempotent module-deploy door.\n */\nexport interface ConversationTagDefinitionService {\n list(\n query?: ListConversationTagDefinitionsQuery,\n ): Promise<ListResponse<ConversationTagDefinition>>\n get(key: string): Promise<ConversationTagDefinition>\n create(request: CreateConversationTagDefinitionRequest): Promise<ConversationTagDefinition>\n update(\n key: string,\n request: UpdateConversationTagDefinitionRequest,\n ): Promise<ConversationTagDefinition>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(\n key: string,\n request: CreateConversationTagDefinitionRequest,\n ): Promise<ConversationTagDefinition>\n delete(key: string): Promise<void>\n}\n\nclass ConversationTagDefinitionServiceImpl implements ConversationTagDefinitionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n query: ListConversationTagDefinitionsQuery = {},\n ): Promise<ListResponse<ConversationTagDefinition>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions`,\n query,\n )\n }\n\n get(key: string): Promise<ConversationTagDefinition> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions/${encodeURIComponent(key)}`,\n )\n }\n\n create(request: CreateConversationTagDefinitionRequest): Promise<ConversationTagDefinition> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions`,\n request,\n )\n }\n\n update(\n key: string,\n request: UpdateConversationTagDefinitionRequest,\n ): Promise<ConversationTagDefinition> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(\n key: string,\n request: CreateConversationTagDefinitionRequest,\n ): Promise<ConversationTagDefinition> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Conversation tag sets: WHERE and WHEN a group of definitions is evaluated.\n * A set needs at least one conversation selector (`channels`,\n * `connection_ids`, `type_keys`) — tagging is opt-in, never org-wide by\n * accident — and `evaluate_on` is a non-empty subset of realtime|completion.\n * Keyed by `key` (not id); `upsert` is the idempotent module-deploy door.\n */\nexport interface ConversationTagSetService {\n list(query?: ListConversationTagSetsQuery): Promise<ListResponse<ConversationTagSet>>\n get(key: string): Promise<ConversationTagSet>\n create(request: CreateConversationTagSetRequest): Promise<ConversationTagSet>\n update(key: string, request: UpdateConversationTagSetRequest): Promise<ConversationTagSet>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(key: string, request: CreateConversationTagSetRequest): Promise<ConversationTagSet>\n delete(key: string): Promise<void>\n}\n\nclass ConversationTagSetServiceImpl implements ConversationTagSetService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationTagSetsQuery = {}): Promise<ListResponse<ConversationTagSet>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets`,\n query,\n )\n }\n\n get(key: string): Promise<ConversationTagSet> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets/${encodeURIComponent(key)}`,\n )\n }\n\n create(request: CreateConversationTagSetRequest): Promise<ConversationTagSet> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/conversation-tag-sets`, request)\n }\n\n update(key: string, request: UpdateConversationTagSetRequest): Promise<ConversationTagSet> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(key: string, request: CreateConversationTagSetRequest): Promise<ConversationTagSet> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Conversation tags: the observations definitions make on conversations,\n * plus the evaluations that produced them. Per-conversation reads/writes\n * hang off the conversation; `update`/`delete` address a tag by id; `list`\n * and `counts` are the org-wide streams. Span offsets are UNICODE CODE POINT\n * indexes (end exclusive) — convert to/from UTF-16 before slicing JS strings.\n */\nexport interface ConversationTagService {\n /** Tags on one conversation (pending, active and dismissed unless `status` filters). */\n listByConversation(\n conversationId: string,\n query?: ListConversationTagsQuery,\n ): Promise<ListResponse<ConversationTag>>\n /** A person tags a conversation, a message or a span (source = user, confidence 1). */\n create(conversationId: string, request: CreateConversationTagRequest): Promise<ConversationTag>\n /**\n * Start a manual evaluation (202). Resolves with the PENDING evaluation as\n * soon as it is accepted — the tagger runs server-side beyond this request.\n * Poll `listEvaluations(conversationId)` until that evaluation's status is\n * `done` | `failed`, then re-read the tags. 409\n * `conversation_tag_set_not_matched` when no enabled set matches the\n * conversation; 409 `conversation_tag_evaluation_in_progress` while another\n * evaluation is still running.\n */\n evaluate(\n conversationId: string,\n request?: EvaluateConversationTagsRequest,\n ): Promise<ConversationTagEvaluation>\n /** The evaluation history of one conversation (newest first by default). */\n listEvaluations(\n conversationId: string,\n query?: ListConversationTagEvaluationsQuery,\n ): Promise<ListResponse<ConversationTagEvaluation>>\n /**\n * Flip a tag between active and dismissed (the feedback loop), annotate why,\n * and/or correct its value and anchors (a correction makes it a user tag).\n */\n update(id: string, request: UpdateConversationTagRequest): Promise<ConversationTag>\n delete(id: string): Promise<void>\n /** Org-wide tag stream (filter by definition, value, channel, contact, time window). */\n list(query?: ListConversationTagsQuery): Promise<ListResponse<ConversationTag>>\n /** Grouped counts for dashboards — `group_by` is a comma-joined string. */\n counts(query?: CountConversationTagsQuery): Promise<CountConversationTagsResponse>\n /**\n * The enabled definitions the enabled sets select for the conversation right\n * now (`evaluate_on` ignored, like a manual evaluation) — what a person may\n * tag it with, incl. its outcome definition(s) (`role === 'outcome'`).\n */\n listApplicableDefinitions(\n conversationId: string,\n ): Promise<ListResponse<ConversationTagDefinition>>\n}\n\nclass ConversationTagServiceImpl implements ConversationTagService {\n constructor(private readonly client: ProteosClient) {}\n\n listByConversation(\n conversationId: string,\n query: ListConversationTagsQuery = {},\n ): Promise<ListResponse<ConversationTag>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tags`,\n query,\n )\n }\n\n create(conversationId: string, request: CreateConversationTagRequest): Promise<ConversationTag> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tags`,\n request,\n )\n }\n\n listApplicableDefinitions(\n conversationId: string,\n ): Promise<ListResponse<ConversationTagDefinition>> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tag-definitions`,\n )\n }\n\n evaluate(\n conversationId: string,\n request: EvaluateConversationTagsRequest = {},\n ): Promise<ConversationTagEvaluation> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tags/evaluate`,\n request,\n )\n }\n\n listEvaluations(\n conversationId: string,\n query: ListConversationTagEvaluationsQuery = {},\n ): Promise<ListResponse<ConversationTagEvaluation>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tag-evaluations`,\n query,\n )\n }\n\n update(id: string, request: UpdateConversationTagRequest): Promise<ConversationTag> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-tags/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-tags/${encodeURIComponent(id)}`,\n )\n }\n\n list(query: ListConversationTagsQuery = {}): Promise<ListResponse<ConversationTag>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/conversation-tags`, query)\n }\n\n counts(query: CountConversationTagsQuery = {}): Promise<CountConversationTagsResponse> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tags/counts`,\n query,\n )\n }\n}\n\n/**\n * Conversation objective definitions: WHAT a conversation should achieve —\n * \"confirm the budget\", \"book the demo\" — org-wide or per conversation type,\n * optionally pinned to one of the type's phases, optionally MEASURED (a tag\n * value condition or an outcome set) so the platform can tell when it was\n * achieved. Keyed by `key` (not id); `upsert` is the idempotent module-deploy\n * door.\n */\nexport interface ConversationObjectiveDefinitionService {\n list(\n query?: GetManyConversationObjectiveDefinitionsQuery,\n ): Promise<ListResponse<ConversationObjectiveDefinition>>\n /** One page, explicitly (`query.page`) — the door a page walker calls; same wire call as `list`. */\n listPage(\n query?: GetManyConversationObjectiveDefinitionsQuery,\n ): Promise<ListResponse<ConversationObjectiveDefinition>>\n get(key: string): Promise<ConversationObjectiveDefinition>\n create(\n request: CreateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition>\n /** Partial update; `measure: null` clears the measure (guidance only). */\n update(\n key: string,\n request: UpdateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(\n key: string,\n request: CreateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition>\n delete(key: string): Promise<void>\n}\n\nclass ConversationObjectiveDefinitionServiceImpl implements ConversationObjectiveDefinitionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n query: GetManyConversationObjectiveDefinitionsQuery = {},\n ): Promise<ListResponse<ConversationObjectiveDefinition>> {\n return this.listPage(query)\n }\n\n listPage(\n query: GetManyConversationObjectiveDefinitionsQuery = {},\n ): Promise<ListResponse<ConversationObjectiveDefinition>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions`,\n query,\n )\n }\n\n get(key: string): Promise<ConversationObjectiveDefinition> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions/${encodeURIComponent(key)}`,\n )\n }\n\n create(\n request: CreateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions`,\n request,\n )\n }\n\n update(\n key: string,\n request: UpdateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(\n key: string,\n request: CreateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Conversation objectives: the org-wide ledger of every applicable\n * definition's standing on every conversation (open rows included), plus\n * grouped counts for dashboards. Read-only — a standing is resolved by the\n * service from the conversation's tags and outcome; the per-conversation\n * checklist is `conversations.getObjectiveProgress`.\n */\nexport interface ConversationObjectiveService {\n /** The ledger (filter by conversation, definition, type, phase, channel, status, source, time window on `recorded_at`). */\n list(query?: GetManyConversationObjectivesQuery): Promise<ListResponse<ConversationObjective>>\n /** Grouped counts for dashboards — `group_by` is a comma-joined string. */\n counts(query?: CountConversationObjectivesQuery): Promise<CountConversationObjectivesResponse>\n}\n\nclass ConversationObjectiveServiceImpl implements ConversationObjectiveService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n query: GetManyConversationObjectivesQuery = {},\n ): Promise<ListResponse<ConversationObjective>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-objectives`,\n query,\n )\n }\n\n counts(\n query: CountConversationObjectivesQuery = {},\n ): Promise<CountConversationObjectivesResponse> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-objectives/counts`,\n query,\n )\n }\n}\n\n/**\n * Contact groups: the generic org-shared audience taxonomy. Membership lives\n * on the contact (`Contact.group_key`, one group per contact — assign via\n * `contacts.update`); tone-of-voice synthesis reads the groups and\n * auto-assigns ungrouped correspondents. Keyed by `key` (not id); `upsert` is\n * the idempotent module-deploy door. Deleting a group clears its members'\n * membership and purges its tone profile rows.\n */\nexport interface ContactGroupService {\n list(query?: ListContactGroupsQuery): Promise<ListResponse<ContactGroup>>\n get(key: string): Promise<ContactGroup>\n create(request: CreateContactGroupRequest): Promise<ContactGroup>\n update(key: string, request: UpdateContactGroupRequest): Promise<ContactGroup>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(key: string, request: CreateContactGroupRequest): Promise<ContactGroup>\n delete(key: string): Promise<void>\n}\n\nclass ContactGroupServiceImpl implements ContactGroupService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListContactGroupsQuery = {}): Promise<ListResponse<ContactGroup>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/contact-groups`, query)\n }\n\n get(key: string): Promise<ContactGroup> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contact-groups/${encodeURIComponent(key)}`,\n )\n }\n\n create(request: CreateContactGroupRequest): Promise<ContactGroup> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/contact-groups`, request)\n }\n\n update(key: string, request: UpdateContactGroupRequest): Promise<ContactGroup> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/contact-groups/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(key: string, request: CreateContactGroupRequest): Promise<ContactGroup> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/contact-groups/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/contact-groups/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Tone-of-voice synthesis. A setup opts one platform user in (only set-up\n * users are swept); `synthesize` triggers a whole-user run immediately (202;\n * 409 `synthesis_in_progress` while one is live). Generated profiles form a\n * specificity hierarchy — fetch a user's rows with `listProfiles`, or let the\n * server pick the single most-specific row for a drafting context with\n * `resolve` (each row is self-contained; never concatenate tiers).\n */\nexport interface ToneProfileService {\n listSetups(query?: ListToneProfileSetupsQuery): Promise<ListResponse<ToneProfileSetup>>\n createSetup(request: CreateToneProfileSetupRequest): Promise<ToneProfileSetup>\n /** Removes the setup AND the user's generated profiles. */\n deleteSetup(id: string): Promise<void>\n /** Kicks a whole-user synthesis run off-request (bypasses cadence checks). */\n synthesize(setupId: string): Promise<void>\n listProfiles(query?: ListToneProfilesQuery): Promise<ListResponse<ToneProfile>>\n getProfile(id: string): Promise<ToneProfile>\n /** The single most-specific profile for a drafting context; 404 when none. */\n resolve(query: ResolveToneProfileQuery): Promise<ToneProfile>\n /**\n * Writes a HAND-AUTHORED profile, addressed by its scope tuple rather than an\n * id — so re-sending the same scope updates the row it created. The row lands\n * `source: 'manual'`, which locks that scope against synthesis forever after;\n * it also takes the scope over from a `model` row already there. Needs no\n * setup: a setup is the opt-in to AI synthesis, and writing a voice by hand is\n * the opposite of asking for one.\n */\n upsertProfile(request: UpsertToneProfileRequest): Promise<ToneProfile>\n /**\n * Removes one profile row, manual or model. A deleted model row comes back on\n * the next run; a deleted manual row hands its scope back to synthesis.\n */\n deleteProfile(id: string): Promise<void>\n}\n\nclass ToneProfileServiceImpl implements ToneProfileService {\n constructor(private readonly client: ProteosClient) {}\n\n listSetups(query: ListToneProfileSetupsQuery = {}): Promise<ListResponse<ToneProfileSetup>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/tone-profile-setups`,\n query,\n )\n }\n\n createSetup(request: CreateToneProfileSetupRequest): Promise<ToneProfileSetup> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/tone-profile-setups`, request)\n }\n\n async deleteSetup(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/tone-profile-setups/${encodeURIComponent(id)}`,\n )\n }\n\n async synthesize(setupId: string): Promise<void> {\n await this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/tone-profile-setups/${encodeURIComponent(setupId)}/synthesize`,\n )\n }\n\n listProfiles(query: ListToneProfilesQuery = {}): Promise<ListResponse<ToneProfile>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/tone-profiles`, query)\n }\n\n getProfile(id: string): Promise<ToneProfile> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/tone-profiles/${encodeURIComponent(id)}`,\n )\n }\n\n resolve(query: ResolveToneProfileQuery): Promise<ToneProfile> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/tone-profiles/resolve`,\n query,\n )\n }\n\n upsertProfile(request: UpsertToneProfileRequest): Promise<ToneProfile> {\n return this.client.request('PUT', `${CONVERSATION_BASE_PATH}/tone-profiles`, request)\n }\n\n async deleteProfile(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/tone-profiles/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/** Batch transcription of stored audio files + materialization. */\nexport interface TranscriptionService {\n /**\n * Kicks off transcription asynchronously — resolves immediately with a\n * PROCESSING entity; the provider runs off-request. Poll `get(id)` until the\n * status is `completed` (or `failed`), then `materialize`.\n */\n createFromFile(request: CreateTranscriptionRequest): Promise<Transcription>\n /**\n * Lands an ALREADY WRITTEN transcript. Synchronous — no provider runs, and\n * the entity comes back `completed`, ready to `materialize` straight away.\n * The door for authoring a transcript (and so a conversation) from text with\n * nothing to upload. Same endpoint as `createFromFile`; the shape of the body\n * chooses the mode, and exactly one of the two is allowed.\n */\n createFromText(request: CreateTranscriptionFromTextRequest): Promise<Transcription>\n list(query?: ListTranscriptionsQuery): Promise<ListResponse<Transcription>>\n get(id: string): Promise<Transcription>\n /**\n * Edits a completed transcription (turn text, speaker labels, language).\n * Does NOT retro-update messages of an already-materialized conversation.\n */\n update(id: string, request: UpdateTranscriptionRequest): Promise<Transcription>\n /**\n * Kicks off the mistranscription review pass (glossary-aware LLM hunt for\n * misheard terms) — resolves immediately with review_status `processing`;\n * poll `get(id)` until it flips to feedback_pending/completed/failed.\n */\n review(id: string): Promise<Transcription>\n /** Turns a completed transcription into an adhoc/meeting conversation. */\n materialize(id: string, request?: MaterializeTranscriptionRequest): Promise<Conversation>\n}\n\nclass TranscriptionServiceImpl implements TranscriptionService {\n constructor(private readonly client: ProteosClient) {}\n\n createFromFile(request: CreateTranscriptionRequest): Promise<Transcription> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/transcriptions`, request)\n }\n\n createFromText(request: CreateTranscriptionFromTextRequest): Promise<Transcription> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/transcriptions`, request)\n }\n\n list(query: ListTranscriptionsQuery = {}): Promise<ListResponse<Transcription>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/transcriptions`, query)\n }\n\n get(id: string): Promise<Transcription> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/transcriptions/${encodeURIComponent(id)}`,\n )\n }\n\n update(id: string, request: UpdateTranscriptionRequest): Promise<Transcription> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/transcriptions/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n review(id: string): Promise<Transcription> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/transcriptions/${encodeURIComponent(id)}/review`,\n {},\n )\n }\n\n materialize(id: string, request: MaterializeTranscriptionRequest = {}): Promise<Conversation> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/transcriptions/${encodeURIComponent(id)}/materialize`,\n request,\n )\n }\n}\n\n/**\n * Findings of the post-transcription review pass: terms likely misheard by the\n * transcription provider, awaiting accept/reject. Accepting applies the\n * replacement to the transcription's turns and (optionally) promotes it into\n * the glossary; resolving the last open finding flips the transcription's\n * review_status to completed.\n */\nexport interface MistranscribedTermService {\n list(query?: ListMistranscribedTermsQuery): Promise<ListResponse<MistranscribedTerm>>\n get(id: string): Promise<MistranscribedTerm>\n accept(id: string, request?: AcceptMistranscribedTermRequest): Promise<MistranscribedTerm>\n reject(id: string): Promise<MistranscribedTerm>\n}\n\nclass MistranscribedTermServiceImpl implements MistranscribedTermService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListMistranscribedTermsQuery = {}): Promise<ListResponse<MistranscribedTerm>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/mistranscribed-terms`,\n query,\n )\n }\n\n get(id: string): Promise<MistranscribedTerm> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/mistranscribed-terms/${encodeURIComponent(id)}`,\n )\n }\n\n accept(id: string, request: AcceptMistranscribedTermRequest = {}): Promise<MistranscribedTerm> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/mistranscribed-terms/${encodeURIComponent(id)}/accept`,\n request,\n )\n }\n\n reject(id: string): Promise<MistranscribedTerm> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/mistranscribed-terms/${encodeURIComponent(id)}/reject`,\n {},\n )\n }\n}\n\n/**\n * Softphone calling: the browser Voice token grant. The client identity is\n * derived server-side from the authenticated user; refresh by minting again\n * (the Voice SDK's tokenWillExpire event is the cue).\n */\nexport interface CallService {\n mintToken(request: MintCallTokenRequest): Promise<CallTokenResponse>\n /**\n * The conversation a provider call became — the softphone's outbound\n * browser-leg CallSid. 404 `call_not_found` until the call-start callback\n * minted it (poll briefly).\n */\n getCallConversation(connectionId: string, externalCallId: string): Promise<Conversation>\n /** Start / resume (true) or pause (false) the recording of a live phone conversation. */\n setRecording(conversationId: string, request: SetCallRecordingRequest): Promise<Conversation>\n /** A phone connection's provider numbers with status + routing. */\n listPhoneNumbers(connectionId: string): Promise<{ data: PhoneNumber[] }>\n /** Replace one number's routing (who it rings). Returns the refreshed list. */\n updatePhoneNumber(\n connectionId: string,\n numberExternalId: string,\n request: UpdatePhoneNumberRequest,\n ): Promise<{ data: PhoneNumber[] }>\n /** Point one number at the platform. Returns the refreshed list. */\n connectPhoneNumber(\n connectionId: string,\n numberExternalId: string,\n ): Promise<{ data: PhoneNumber[] }>\n /** Release one number (restores its previous handler). Returns the refreshed list. */\n disconnectPhoneNumber(\n connectionId: string,\n numberExternalId: string,\n ): Promise<{ data: PhoneNumber[] }>\n}\n\nclass CallServiceImpl implements CallService {\n constructor(private readonly client: ProteosClient) {}\n\n mintToken(request: MintCallTokenRequest): Promise<CallTokenResponse> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/calls/token`, request)\n }\n\n getCallConversation(connectionId: string, externalCallId: string): Promise<Conversation> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/calls/${encodeURIComponent(externalCallId)}`,\n )\n }\n\n setRecording(conversationId: string, request: SetCallRecordingRequest): Promise<Conversation> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/recording`,\n request,\n )\n }\n\n listPhoneNumbers(connectionId: string): Promise<{ data: PhoneNumber[] }> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/phone-numbers`,\n )\n }\n\n updatePhoneNumber(\n connectionId: string,\n numberExternalId: string,\n request: UpdatePhoneNumberRequest,\n ): Promise<{ data: PhoneNumber[] }> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/phone-numbers/${encodeURIComponent(numberExternalId)}`,\n request,\n )\n }\n\n connectPhoneNumber(\n connectionId: string,\n numberExternalId: string,\n ): Promise<{ data: PhoneNumber[] }> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/phone-numbers/${encodeURIComponent(numberExternalId)}/connect`,\n )\n }\n\n disconnectPhoneNumber(\n connectionId: string,\n numberExternalId: string,\n ): Promise<{ data: PhoneNumber[] }> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/phone-numbers/${encodeURIComponent(numberExternalId)}/disconnect`,\n )\n }\n}\n\nexport type * from './types.js'\nexport { UNSUBSCRIBE_URL_PLACEHOLDER } from './types.js'\n// Re-export voice types (the live dictation stream lives on this service now)\nexport type {\n TranscribeStreamOptions,\n TranscriptResult,\n VoiceService,\n VoiceTranscriptionStream,\n} from './voice.js'\n\n/**\n * Conversation briefs — guidance prepared ahead of a conversation (\"talk to\n * these people about this\"; the conversation sibling of message drafts).\n * Binding is explicit: the softphone carries the brief id into the call, a\n * brief naming a calendar event attaches to that meeting's conversation when\n * the meeting bot starts, or `attach` names the conversation. Any number of\n * briefs may be open for the same people or meeting, and a conversation may\n * carry several. Edits/attach on a non-open brief fail 409\n * `conversation_brief_not_editable`.\n */\nexport interface ConversationBriefService {\n list(query?: ListConversationBriefsQuery): Promise<ListResponse<ConversationBrief>>\n get(id: string): Promise<ConversationBrief>\n create(request: CreateConversationBriefRequest): Promise<ConversationBrief>\n update(id: string, request: UpdateConversationBriefRequest): Promise<ConversationBrief>\n /** Decline an open brief (prepared → discarded, terminal). */\n discard(id: string): Promise<ConversationBrief>\n /** Bind an open brief to a conversation explicitly (prepared → used). */\n attach(id: string, request: AttachConversationBriefRequest): Promise<ConversationBrief>\n delete(id: string): Promise<void>\n}\n\nclass ConversationBriefServiceImpl implements ConversationBriefService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationBriefsQuery = {}): Promise<ListResponse<ConversationBrief>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-briefs`,\n query,\n )\n }\n\n get(id: string): Promise<ConversationBrief> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateConversationBriefRequest): Promise<ConversationBrief> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/conversation-briefs`, request)\n }\n\n update(id: string, request: UpdateConversationBriefRequest): Promise<ConversationBrief> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n discard(id: string): Promise<ConversationBrief> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}/discard`,\n )\n }\n\n attach(id: string, request: AttachConversationBriefRequest): Promise<ConversationBrief> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}/attach`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/**\n * Sending rules — outbound send constraints (windows, connection limits,\n * frequency caps), the static limit-preset catalog and its apply expansion.\n * A denied send/reply/sendDraft fails with a ProteosError whose `details`\n * carry `earliest_allowed_at` (429) or the blocked contact (403).\n */\nexport interface SendingRuleService {\n list(query?: ListSendingRulesQuery): Promise<ListResponse<SendingRule>>\n get(id: string): Promise<SendingRule>\n create(request: CreateSendingRuleRequest): Promise<SendingRule>\n update(id: string, request: UpdateSendingRuleRequest): Promise<SendingRule>\n delete(id: string): Promise<void>\n /** The static preset catalog, optionally narrowed to one connector. */\n listPresets(query?: ListSendingLimitPresetsQuery): Promise<{ data: SendingLimitPreset[] }>\n /**\n * Expand a preset into limit rules linked to the given connections,\n * replacing the limit rules they were linked to before.\n */\n applyPreset(request: ApplySendingLimitPresetRequest): Promise<{ data: SendingRule[] }>\n}\n\nclass SendingRuleServiceImpl implements SendingRuleService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListSendingRulesQuery = {}): Promise<ListResponse<SendingRule>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/sending-rules`, query)\n }\n\n get(id: string): Promise<SendingRule> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/sending-rules/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateSendingRuleRequest): Promise<SendingRule> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/sending-rules`, request)\n }\n\n update(id: string, request: UpdateSendingRuleRequest): Promise<SendingRule> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/sending-rules/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/sending-rules/${encodeURIComponent(id)}`,\n )\n }\n\n listPresets(query: ListSendingLimitPresetsQuery = {}): Promise<{ data: SendingLimitPreset[] }> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/sending-rules/presets`,\n query,\n )\n }\n\n applyPreset(request: ApplySendingLimitPresetRequest): Promise<{ data: SendingRule[] }> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/sending-rules/apply-preset`,\n request,\n )\n }\n}\n\n/**\n * Email signatures: the block an email send adds below the body and above\n * the quote. A send, draft or draft edit picks one with its `signature`\n * field; without it the default applies.\n */\nexport interface EmailSignatureService {\n list(query?: ListEmailSignaturesQuery): Promise<ListResponse<EmailSignature>>\n get(id: string): Promise<EmailSignature>\n create(request: CreateEmailSignatureRequest): Promise<EmailSignature>\n update(id: string, request: UpdateEmailSignatureRequest): Promise<EmailSignature>\n delete(id: string): Promise<void>\n /** The default signature an email would get; `data` is null when none applies. */\n resolve(query?: ResolveEmailSignatureQuery): Promise<{ data: MessageSignature | null }>\n}\n\nclass EmailSignatureServiceImpl implements EmailSignatureService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListEmailSignaturesQuery = {}): Promise<ListResponse<EmailSignature>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/email-signatures`, query)\n }\n\n get(id: string): Promise<EmailSignature> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/email-signatures/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateEmailSignatureRequest): Promise<EmailSignature> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/email-signatures`, request)\n }\n\n update(id: string, request: UpdateEmailSignatureRequest): Promise<EmailSignature> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/email-signatures/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/email-signatures/${encodeURIComponent(id)}`,\n )\n }\n\n resolve(query: ResolveEmailSignatureQuery = {}): Promise<{ data: MessageSignature | null }> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/email-signatures/resolve`,\n query,\n )\n }\n}\n\n/**\n * Message templates: reusable messages and snippets whose subject and body are\n * Liquid templates. A send or a draft names one with its `template` field.\n */\nexport interface MessageTemplateService {\n list(query?: ListMessageTemplatesQuery): Promise<ListResponse<MessageTemplate>>\n /** By id or by key. */\n get(idOrKey: string): Promise<MessageTemplate>\n create(request: CreateMessageTemplateRequest): Promise<MessageTemplate>\n update(id: string, request: UpdateMessageTemplateRequest): Promise<MessageTemplate>\n /** Creates or replaces the template a key names; an equivalent body writes nothing. */\n upsertByKey(\n key: string,\n request: Omit<CreateMessageTemplateRequest, 'key'>,\n ): Promise<MessageTemplate>\n delete(id: string): Promise<void>\n /**\n * Fills in a stored or an inline template: what a send of it would store,\n * with the signature the email would get.\n */\n render(request: RenderMessageTemplateRequest): Promise<RenderedMessageTemplate>\n}\n\nclass MessageTemplateServiceImpl implements MessageTemplateService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListMessageTemplatesQuery = {}): Promise<ListResponse<MessageTemplate>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/message-templates`, query)\n }\n\n get(idOrKey: string): Promise<MessageTemplate> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/message-templates/${encodeURIComponent(idOrKey)}`,\n )\n }\n\n create(request: CreateMessageTemplateRequest): Promise<MessageTemplate> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/message-templates`, request)\n }\n\n update(id: string, request: UpdateMessageTemplateRequest): Promise<MessageTemplate> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/message-templates/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n upsertByKey(\n key: string,\n request: Omit<CreateMessageTemplateRequest, 'key'>,\n ): Promise<MessageTemplate> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/message-templates/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/message-templates/${encodeURIComponent(id)}`,\n )\n }\n\n render(request: RenderMessageTemplateRequest): Promise<RenderedMessageTemplate> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/message-templates/render`,\n request,\n )\n }\n}\n\n/**\n * Channel actions — the ledger of acts performed through a connection that\n * are neither a message nor a reaction (LinkedIn invitations, profile visits,\n * InMail). A denied perform fails like a denied send (ProteosError with\n * `details.earliest_allowed_at`); a provider refusal carries its own code\n * (already_connected, already_invited_recently, invitation_already_received,\n * connection_limit_reached, insufficient_inmail_credits, inmail_not_allowed,\n * not_connected_with_recipient). An invitation is pre-flighted with one silent\n * profile read before anything is sent, so those refusals never mint a\n * phantom act.\n */\nexport interface ChannelActionService {\n list(query?: ListChannelActionsQuery): Promise<ListResponse<ChannelAction>>\n get(id: string): Promise<ChannelAction>\n /** Performs one act; resolves to the row in its post-perform status. */\n perform(request: PerformChannelActionRequest): Promise<ChannelAction>\n /** Withdraws a performed outbound act (an invitation). */\n cancel(id: string): Promise<ChannelAction>\n /** Answers an inbound act (a received invitation). */\n respond(id: string, request: RespondChannelActionRequest): Promise<ChannelAction>\n}\n\nclass ChannelActionServiceImpl implements ChannelActionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListChannelActionsQuery = {}): Promise<ListResponse<ChannelAction>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/channel-actions`, query)\n }\n\n get(id: string): Promise<ChannelAction> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/channel-actions/${encodeURIComponent(id)}`,\n )\n }\n\n perform(request: PerformChannelActionRequest): Promise<ChannelAction> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/channel-actions`, request)\n }\n\n cancel(id: string): Promise<ChannelAction> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/channel-actions/${encodeURIComponent(id)}/cancel`,\n )\n }\n\n respond(id: string, request: RespondChannelActionRequest): Promise<ChannelAction> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/channel-actions/${encodeURIComponent(id)}/respond`,\n request,\n )\n }\n}\n\n/**\n * The channel_event ledger — provider-observed delivery / engagement events\n * about outbound messages (delivered, bounced, opened, clicked,\n * spam_reported, unsubscribed, …). Read-only: rows are appended by webhook\n * ingest. `listByMessage` is the per-message history, oldest first.\n */\nexport interface ChannelEventService {\n list(query?: ListChannelEventsQuery): Promise<ListResponse<ChannelEvent>>\n get(id: string): Promise<ChannelEvent>\n listByMessage(messageId: string): Promise<ListResponse<ChannelEvent>>\n}\n\nclass ChannelEventServiceImpl implements ChannelEventService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListChannelEventsQuery = {}): Promise<ListResponse<ChannelEvent>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/channel-events`, query)\n }\n\n get(id: string): Promise<ChannelEvent> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/channel-events/${encodeURIComponent(id)}`,\n )\n }\n\n listByMessage(messageId: string): Promise<ListResponse<ChannelEvent>> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/events`,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type { CreateEntityIndexRequest, EntityIndex, IndexRecommendation } from './types.js'\n\nconst ENTITIES_BASE_PATH = '/data/v1/entities'\n\n/**\n * Per-entity indexes on the record table and the advisor's recommendations.\n * Admin surface: gated on the `entities` permission, not on record access.\n */\nexport interface EntityIndexService {\n /** Every index of the entity (declared, automatic, applied) with live state. */\n list(entitySlug: string): Promise<EntityIndex[]>\n /** The advisor's current suggestions for the entity. */\n recommendations(entitySlug: string): Promise<IndexRecommendation[]>\n /** Applies one lookup/search index; returns it in `building` state. */\n create(entitySlug: string, request: CreateEntityIndexRequest): Promise<EntityIndex>\n /** Removes one APPLIED index (declared/automatic → 409 entity_index_not_deletable). */\n delete(entitySlug: string, name: string): Promise<void>\n}\n\nexport class EntityIndexServiceImpl implements EntityIndexService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(entitySlug: string): Promise<EntityIndex[]> {\n const response = await this.client.request<{ data: EntityIndex[] }>(\n 'GET',\n `${ENTITIES_BASE_PATH}/${encodeURIComponent(entitySlug)}/indexes`,\n )\n return response.data\n }\n\n async recommendations(entitySlug: string): Promise<IndexRecommendation[]> {\n const response = await this.client.request<{ data: IndexRecommendation[] }>(\n 'GET',\n `${ENTITIES_BASE_PATH}/${encodeURIComponent(entitySlug)}/index-recommendations`,\n )\n return response.data\n }\n\n async create(entitySlug: string, request: CreateEntityIndexRequest): Promise<EntityIndex> {\n return this.client.request<EntityIndex>(\n 'POST',\n `${ENTITIES_BASE_PATH}/${encodeURIComponent(entitySlug)}/indexes`,\n request,\n )\n }\n\n async delete(entitySlug: string, name: string): Promise<void> {\n await this.client.request<void>(\n 'DELETE',\n `${ENTITIES_BASE_PATH}/${encodeURIComponent(entitySlug)}/indexes/${encodeURIComponent(name)}`,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type { FilterGroup } from '../meta/filters.js'\nimport type { ListResult, UserRef } from '../types/common.js'\n\nconst QUERY_BASE_PATH = '/data/v1/query'\nconst QUERIES_BASE_PATH = '/data/v1/queries'\n\n/**\n * A single row from a query result. Keys match the result-set columns\n * (camelCase, with `id`/`created_at`/`updated_at` reserved). The data-service\n * hoists JSONB columns into nested objects, so values can be primitives,\n * nested records, or arrays.\n */\nexport type QueryRow = Record<string, unknown>\n\nexport interface QueryExecuteMeta {\n columns: string[]\n items: number\n limit_applied: number\n /** Only present when `true`. */\n was_default_limit_applied?: boolean\n execution_time_ms: number\n}\n\nexport interface QueryExecuteResponse {\n data: QueryRow[]\n meta?: QueryExecuteMeta\n}\n\nexport interface QueryValidateMeta {\n limit_applied: number\n was_default_limit_applied?: boolean\n}\n\nexport interface QueryValidateResponse {\n valid: boolean\n /** The SQL the server would execute (entity-rewritten, schema-qualified). */\n rewritten_sql?: string\n tables?: string[]\n meta?: QueryValidateMeta\n}\n\n/**\n * The visual editor's state for a {@link Query}: the entity it reads, the\n * selected column paths (relation fields are prefixed with the foreign-key\n * attribute, e.g. `accountId.name`) and the filter. It only reopens the\n * editor — `sql` is what runs.\n */\nexport interface QueryBuilder {\n entity_slug: string\n columns: string[]\n filter?: FilterGroup\n}\n\n/**\n * A stored SQL query. Running it is `execute(query.sql)` as the viewer, so a\n * query never carries data access with it. `created_by` is the owner;\n * everyone else reaches it through a share on the `queries` slug.\n */\nexport interface Query {\n id: string\n org_id: string\n name: string\n sql: string\n /** Absent for a query that was never built visually. */\n builder?: QueryBuilder\n /** Whether the caller may update this query. Computed per request. */\n can_write: boolean\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateQueryRequest {\n name: string\n sql: string\n builder?: QueryBuilder\n}\n\n/** An absent field keeps its value. */\nexport interface UpdateQueryRequest {\n name?: string\n sql?: string\n builder?: QueryBuilder\n}\n\nexport interface ListQueriesQuery {\n page?: number\n page_size?: number\n}\n\n/**\n * Service for the query endpoints of the data-service: running raw SQL and\n * storing queries to run again.\n *\n * Accepts SELECT-only Postgres SQL with bare attribute references; the\n * server rewrites bare attributes into JSONB accessors against the\n * tenant's schema and runs per-table OpenFGA authorization checks.\n */\nexport interface QueryService {\n /** Executes the SQL and returns the result rows + meta. */\n execute(sql: string): Promise<QueryExecuteResponse>\n /** Parses + authorizes the SQL without running it. */\n validate(sql: string): Promise<QueryValidateResponse>\n\n /** The caller's own queries and those shared with them, ordered by name. */\n list(query?: ListQueriesQuery): Promise<ListResult<Query>>\n /** 404 `query_not_found` when the caller cannot see the query. */\n get(id: string): Promise<Query>\n /** Stores the query; the caller becomes its owner. Nothing is executed. */\n create(request: CreateQueryRequest): Promise<Query>\n /** 403 `queries_write_not_permitted` when the caller can only read it. */\n update(id: string, request: UpdateQueryRequest): Promise<Query>\n /** Deletes the query and its shares. */\n delete(id: string): Promise<void>\n}\n\nexport class QueryServiceImpl implements QueryService {\n constructor(private readonly client: ProteosClient) {}\n\n async execute(sql: string): Promise<QueryExecuteResponse> {\n return this.client.request<QueryExecuteResponse>('POST', `${QUERY_BASE_PATH}/execute`, { sql })\n }\n\n async validate(sql: string): Promise<QueryValidateResponse> {\n return this.client.request<QueryValidateResponse>('POST', `${QUERY_BASE_PATH}/validate`, {\n sql,\n })\n }\n\n async list(query: ListQueriesQuery = {}): Promise<ListResult<Query>> {\n return this.client.requestWithQuery<ListResult<Query>>('GET', QUERIES_BASE_PATH, query)\n }\n\n async get(id: string): Promise<Query> {\n return this.client.request<Query>('GET', `${QUERIES_BASE_PATH}/${encodeURIComponent(id)}`)\n }\n\n async create(request: CreateQueryRequest): Promise<Query> {\n return this.client.request<Query>('POST', QUERIES_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateQueryRequest): Promise<Query> {\n return this.client.request<Query>(\n 'PATCH',\n `${QUERIES_BASE_PATH}/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${QUERIES_BASE_PATH}/${encodeURIComponent(id)}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n ApproveRecordDraftRequest,\n CreateRecordDraftRequest,\n ListRecordDraftsQuery,\n ProposedValuesQuery,\n RecordDraft,\n RecordDraftProposedValue,\n RecordDraftVersions,\n RejectRecordDraftRequest,\n UpdateRecordDraftRequest,\n} from './types.js'\n\nconst RECORD_DRAFTS_BASE_PATH = '/data/v1/record-drafts'\n\n/**\n * Proposed record writes awaiting a verdict. `create` needs\n * `record-drafts:write`; `approve` additionally needs `write` (create / update /\n * upsert) or `delete` (delete) on every entity whose items are applied,\n * because the writes run as the caller. A draft can hold items of several\n * entities that reference each other by `transaction_id`. The status is\n * derived server-side from the per-item verdicts.\n */\nexport interface RecordDraftService {\n /** The org's drafts — `proposed` by default. */\n list(query?: ListRecordDraftsQuery): Promise<ListResult<RecordDraft>>\n get(id: string): Promise<RecordDraft>\n create(request: CreateRecordDraftRequest): Promise<RecordDraft>\n /**\n * Saves a proposed draft's items (a proposer's revision or a reviewer's\n * edit) — nothing is written to the records. 409 `record_draft_conflict`\n * when `expected_updated_at` is stale, `record_draft_not_proposed` once\n * resolved.\n */\n update(id: string, request: UpdateRecordDraftRequest): Promise<RecordDraft>\n /** The draft's history and what reviewers changed so far. */\n listVersions(id: string): Promise<RecordDraftVersions>\n /**\n * Applies the draft as the caller. No `items` = its items as they stand;\n * `items` = the reviewer's edit, saved first. `transaction_ids` /\n * `attributes` apply only that part (plus the not-yet-written items it\n * references). Always 200 with the draft: `status` is terminal once every\n * item has a verdict, else still `proposed` with `verdicts` (what is\n * decided) and per-item `results` (what failed, to fix and re-approve). 409\n * `record_draft_not_proposed` once resolved, `record_draft_already_decided`\n * when the scope holds nothing undecided.\n */\n approve(id: string, request?: ApproveRecordDraftRequest): Promise<RecordDraft>\n /**\n * Declines the draft, or the part `transaction_ids` / `attributes` name —\n * nothing is written. 409 `record_draft_not_proposed` once resolved.\n */\n reject(id: string, request?: RejectRecordDraftRequest): Promise<RecordDraft>\n /**\n * What proposed drafts would still write to records of one entity, one row\n * per value, with the record's current value and the proposer's evidence.\n * Needs `read` on the entity; records and attributes the caller may not\n * read are left out.\n */\n proposedValues(query: ProposedValuesQuery): Promise<RecordDraftProposedValue[]>\n}\n\nexport class RecordDraftServiceImpl implements RecordDraftService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(query: ListRecordDraftsQuery = {}): Promise<ListResult<RecordDraft>> {\n return this.client.requestWithQuery<ListResult<RecordDraft>>(\n 'GET',\n RECORD_DRAFTS_BASE_PATH,\n query,\n )\n }\n\n async get(id: string): Promise<RecordDraft> {\n return this.client.request<RecordDraft>(\n 'GET',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}`,\n )\n }\n\n async create(request: CreateRecordDraftRequest): Promise<RecordDraft> {\n return this.client.request<RecordDraft>('POST', RECORD_DRAFTS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateRecordDraftRequest): Promise<RecordDraft> {\n return this.client.request<RecordDraft>(\n 'PUT',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async listVersions(id: string): Promise<RecordDraftVersions> {\n return this.client.request<RecordDraftVersions>(\n 'GET',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}/versions`,\n )\n }\n\n async approve(id: string, request: ApproveRecordDraftRequest = {}): Promise<RecordDraft> {\n return this.client.request<RecordDraft>(\n 'POST',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}/approve`,\n request,\n )\n }\n\n async reject(id: string, request: RejectRecordDraftRequest = {}): Promise<RecordDraft> {\n return this.client.request<RecordDraft>(\n 'POST',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}/reject`,\n request,\n )\n }\n\n async proposedValues(query: ProposedValuesQuery): Promise<RecordDraftProposedValue[]> {\n const response = await this.client.requestWithQuery<{ data: RecordDraftProposedValue[] }>(\n 'GET',\n `${RECORD_DRAFTS_BASE_PATH}/proposed-values`,\n {\n entity_slug: query.entity_slug,\n ...(query.record_ids && query.record_ids.length > 0\n ? { record_ids: query.record_ids.join(',') }\n : {}),\n },\n )\n return response.data ?? []\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n BatchUpsertRecordsResponse,\n BatchUpsertTransaction,\n ListRecordDuplicatesQuery,\n ListRecordsOptions,\n PublishContactObservationsResponse,\n RecordData,\n RecordDuplicate,\n} from './types.js'\n\nconst RECORDS_BASE_PATH = '/data/v1/records'\nconst BATCH_RECORDS_BASE_PATH = '/data/v1/batch/records'\nconst PUBLIC_RECORDS_BASE_PATH = '/data/v1/public/orgs'\n\n/**\n * Service for managing records (per-entity data rows) via the data-service.\n *\n * Records are opaque JSON objects whose schema is defined per-entity in the\n * metadata service. An entity must be registered (via metadata-service, which\n * in turn provisions a Postgres table) before records for it can be created.\n */\nexport interface RecordService {\n /**\n * Lists records for an entity as an async iterator. Pages are 0-indexed\n * (first page is 0); `PageIterator` starts there automatically.\n */\n list(\n entitySlug: string,\n options?: ListRecordsOptions,\n ): PageIterator<RecordData, ListRecordsOptions>\n\n /**\n * Fetches a single page of records.\n */\n listPage(entitySlug: string, options?: ListRecordsOptions): Promise<ListResult<RecordData>>\n\n /**\n * Gets a single record by id.\n * @throws {ProteosError} If the record is not found (404).\n */\n get(entitySlug: string, id: string): Promise<RecordData>\n\n /**\n * Creates a new record for the given entity.\n */\n create(entitySlug: string, data: RecordData): Promise<RecordData>\n\n /**\n * Partially updates a record.\n */\n update(entitySlug: string, id: string, data: Partial<RecordData>): Promise<RecordData>\n\n /**\n * Deletes a record.\n */\n delete(entitySlug: string, id: string): Promise<void>\n\n /**\n * Batch-upserts records. Each transaction succeeds/fails independently;\n * the response contains a per-transaction status so callers (e.g. import\n * flows) can render per-row feedback.\n */\n batchUpsert(\n entitySlug: string,\n transactions: BatchUpsertTransaction[],\n ): Promise<BatchUpsertRecordsResponse>\n\n /**\n * Lists records of a public-read entity through the UNAUTHENTICATED\n * public endpoint (no Authorization header) as an async iterator. A\n * non-public or missing entity 404s identically.\n */\n listPublic(\n orgId: string,\n entitySlug: string,\n options?: ListRecordsOptions,\n ): PageIterator<RecordData, ListRecordsOptions>\n\n /**\n * Fetches a single page of records through the unauthenticated public\n * endpoint. Same filter grammar and pagination as `listPage`.\n */\n listPublicPage(\n orgId: string,\n entitySlug: string,\n options?: ListRecordsOptions,\n ): Promise<ListResult<RecordData>>\n\n /**\n * Gets a single record of a public-read entity through the\n * unauthenticated public endpoint. Knowledge-text values stay unenriched\n * (bare refs) on this path.\n */\n getPublic(orgId: string, entitySlug: string, id: string): Promise<RecordData>\n /**\n * Replays ONE page of the entity's records as record_contact_observation\n * events (the backfill after an attribute became contact-address). Requires\n * unscoped write on the entity; loop until `page + 1 >= pages_total`.\n */\n publishContactObservations(\n entitySlug: string,\n options?: { page?: number; page_size?: number },\n ): Promise<PublishContactObservationsResponse>\n}\n\n/**\n * Record duplicates — \"these two records may be the same thing\" pairs of one\n * entity (see `RecordDuplicate`). Reading = entity read, dismissing = entity write.\n */\nexport interface RecordDuplicateService {\n list(entitySlug: string, query?: ListRecordDuplicatesQuery): Promise<ListResult<RecordDuplicate>>\n get(entitySlug: string, id: string): Promise<RecordDuplicate>\n /** Closes a pair as \"not a duplicate\" (409 `record_duplicate_not_open` when already closed). */\n dismiss(entitySlug: string, id: string): Promise<RecordDuplicate>\n}\n\n/**\n * Implementation of RecordService.\n */\nexport class RecordServiceImpl implements RecordService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n entitySlug: string,\n options: ListRecordsOptions = {},\n ): PageIterator<RecordData, ListRecordsOptions> {\n return new PageIterator((opts) => this.listPage(entitySlug, opts), options)\n }\n\n async listPage(\n entitySlug: string,\n options: ListRecordsOptions = {},\n ): Promise<ListResult<RecordData>> {\n return this.client.requestWithQuery<ListResult<RecordData>>(\n 'GET',\n `${RECORDS_BASE_PATH}/${entitySlug}`,\n options,\n )\n }\n\n async get(entitySlug: string, id: string): Promise<RecordData> {\n return this.client.request<RecordData>('GET', `${RECORDS_BASE_PATH}/${entitySlug}/${id}`)\n }\n\n async create(entitySlug: string, data: RecordData): Promise<RecordData> {\n return this.client.request<RecordData>('POST', `${RECORDS_BASE_PATH}/${entitySlug}`, data)\n }\n\n async update(entitySlug: string, id: string, data: Partial<RecordData>): Promise<RecordData> {\n return this.client.request<RecordData>(\n 'PATCH',\n `${RECORDS_BASE_PATH}/${entitySlug}/${id}`,\n data,\n )\n }\n\n async delete(entitySlug: string, id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${RECORDS_BASE_PATH}/${entitySlug}/${id}`)\n }\n\n async batchUpsert(\n entitySlug: string,\n transactions: BatchUpsertTransaction[],\n ): Promise<BatchUpsertRecordsResponse> {\n return this.client.request<BatchUpsertRecordsResponse>(\n 'POST',\n `${BATCH_RECORDS_BASE_PATH}/${entitySlug}/upsert`,\n transactions,\n )\n }\n\n async publishContactObservations(\n entitySlug: string,\n options: { page?: number; page_size?: number } = {},\n ): Promise<PublishContactObservationsResponse> {\n return this.client.requestWithQuery<PublishContactObservationsResponse>(\n 'POST',\n `${RECORDS_BASE_PATH}/${entitySlug}/contact-observations`,\n options,\n )\n }\n\n listPublic(\n orgId: string,\n entitySlug: string,\n options: ListRecordsOptions = {},\n ): PageIterator<RecordData, ListRecordsOptions> {\n return new PageIterator((opts) => this.listPublicPage(orgId, entitySlug, opts), options)\n }\n\n async listPublicPage(\n orgId: string,\n entitySlug: string,\n options: ListRecordsOptions = {},\n ): Promise<ListResult<RecordData>> {\n return this.client.requestWithQuery<ListResult<RecordData>>(\n 'GET',\n `${PUBLIC_RECORDS_BASE_PATH}/${encodeURIComponent(orgId)}/records/${encodeURIComponent(entitySlug)}`,\n options,\n undefined,\n { skipAuth: true },\n )\n }\n\n async getPublic(orgId: string, entitySlug: string, id: string): Promise<RecordData> {\n return this.client.request<RecordData>(\n 'GET',\n `${PUBLIC_RECORDS_BASE_PATH}/${encodeURIComponent(orgId)}/records/${encodeURIComponent(entitySlug)}/${encodeURIComponent(id)}`,\n undefined,\n { skipAuth: true },\n )\n }\n}\n\nexport class RecordDuplicateServiceImpl implements RecordDuplicateService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(\n entitySlug: string,\n query: ListRecordDuplicatesQuery = {},\n ): Promise<ListResult<RecordDuplicate>> {\n return this.client.requestWithQuery<ListResult<RecordDuplicate>>(\n 'GET',\n `${RECORDS_BASE_PATH}/${entitySlug}/duplicates`,\n query,\n )\n }\n\n async get(entitySlug: string, id: string): Promise<RecordDuplicate> {\n return this.client.request<RecordDuplicate>(\n 'GET',\n `${RECORDS_BASE_PATH}/${entitySlug}/duplicates/${encodeURIComponent(id)}`,\n )\n }\n\n async dismiss(entitySlug: string, id: string): Promise<RecordDuplicate> {\n return this.client.request<RecordDuplicate>(\n 'POST',\n `${RECORDS_BASE_PATH}/${entitySlug}/duplicates/${encodeURIComponent(id)}/dismiss`,\n )\n }\n}\n","import { z } from 'zod'\n\n/**\n * A record is an open-shape JSON object whose keys are the entity's attribute\n * names plus system fields (`id`, `created_at`, `updated_at`, `created_by`,\n * `updated_by`). Because attributes vary per entity, values are typed as `any`\n * at the SDK layer — consumers narrow or cast as needed.\n */\nexport type RecordData = Record<string, any>\n\n/**\n * Options for listing records.\n *\n * Sorting: use `sort: \"field:asc\"` for single-column; pipe-separated for\n * multi-column (`\"field1:asc|field2:desc\"`). Defaults to `created_at:desc`.\n *\n * Arbitrary filter keys pass through as query params. Supported operators\n * (via bracket syntax) include `[eq]`, `[ne]`, `[gt]`, `[gte]`, `[lt]`,\n * `[lte]`, `[in]` (pipe-separated), `[not_in]`, `[contains]`, `[not_contains]`,\n * `[contains_all]` (pipe-separated, arrays only), `[starts_with]`, `[ends_with]`,\n * `[empty]`, `[not_empty]`. Missing operator defaults to `[eq]`. On array\n * attributes contains / not_contains / in / not_in / contains_all are\n * set-membership tests (has / does not have / has any of / has none of / has all of).\n * A filter key may reach one hop through a relation attribute with a dotted\n * path (`\"company_id.name[contains]\": \"acme\"`).\n *\n * For nested AND/OR trees, pass a filter group (the same wire dialect as\n * `List.filters` / `visible_when`: `{logical_operator, elements: [{field,\n * operator, value}], groups}`, string values, pipe-joined for in/not_in/contains_all)\n * JSON-encoded under the reserved `_filter` key:\n * `{ _filter: JSON.stringify(group) }`. The server ANDs it with any flat\n * filter params.\n */\nexport interface ListRecordsOptions {\n /** Page number (0-indexed). First page is 0. */\n page?: number\n /** Number of items per page (default: 20 per backend) */\n page_size?: number\n /**\n * Sort spec. Format: `\"field:direction\"`, or pipe-separated for multi-column:\n * `\"field1:asc|field2:desc\"`. Direction is `asc` | `desc`.\n */\n sort?: string\n /** Arbitrary attribute filters (flat query-string params). */\n [key: string]: unknown\n}\n\n// ============================================================================\n// Batch operations\n// ============================================================================\n\n/**\n * One transaction within a batch operation.\n * `transaction_id` is client-supplied so you can match results back to your\n * source rows (used e.g. by import flows).\n */\nexport interface BatchUpsertTransaction {\n transaction_id: string\n data: Record<string, unknown>\n}\n\nexport type BatchTransactionStatus = 'success' | 'error'\n\nexport interface BatchTransactionError {\n code: string\n message: string\n}\n\nexport interface BatchUpsertTransactionResult {\n transaction_id: string\n status: BatchTransactionStatus\n record?: RecordData\n error?: BatchTransactionError\n}\n\nexport interface BatchUpsertRecordsResponse {\n results: BatchUpsertTransactionResult[]\n}\n\n// Zod schemas for runtime validation (optional, for consumers who want it)\n\nexport const BatchUpsertTransactionSchema = z.object({\n transaction_id: z.string(),\n data: z.record(z.unknown()),\n})\n\nexport const BatchTransactionErrorSchema = z.object({\n code: z.string(),\n message: z.string(),\n})\n\nexport const BatchUpsertTransactionResultSchema = z.object({\n transaction_id: z.string(),\n status: z.enum(['success', 'error']),\n record: z.record(z.unknown()).optional(),\n error: BatchTransactionErrorSchema.optional(),\n})\n\nexport const BatchUpsertRecordsResponseSchema = z.object({\n results: z.array(BatchUpsertTransactionResultSchema),\n})\n\n// ── Record duplicates ─────────────────────────────────────────────────────────\n\n/** How a duplicate pair was detected. `contact_binding` = two records bound to\n * the same conversation contact through their contact-address attributes. */\nexport type RecordDuplicateSource = 'contact_binding' | (string & {})\n\nexport type RecordDuplicateStatus = 'open' | 'dismissed' | 'resolved'\n\n/**\n * \"These two records of one entity may be the same thing.\" Asymmetric:\n * `primary_record_id` is the record to keep, `secondary_record_id` the\n * newcomer. A group of colliding records has ONE primary and one row per other\n * member (four records = three rows). `evidence` is shaped by `source` — for\n * `contact_binding`: `{ contact_id, address_keys: [{kind, value}] }`.\n */\nexport interface RecordDuplicate {\n id: string\n org_id: string\n entity_slug: string\n primary_record_id: string\n secondary_record_id: string\n source: RecordDuplicateSource\n evidence: Record<string, unknown>\n status: RecordDuplicateStatus\n resolved_by?: { type: string; id: string }\n resolved_at?: string\n created_at: string\n created_by: { type: string; id: string }\n updated_at: string\n updated_by: { type: string; id: string }\n}\n\nexport interface ListRecordDuplicatesQuery {\n /** Only pairs this record takes part in (either side). */\n record_id?: string\n /** Defaults to `open` on the server. */\n status?: RecordDuplicateStatus\n page?: number\n page_size?: number\n}\n\n// ── Record drafts ─────────────────────────────────────────────────────────────\n\n/** WHAT a draft proposes to do to the entity's records. Record-only, hence the\n * short verbs; the page-button intent vocabulary (`create_record`, …) is mapped\n * at the UI boundary. */\nexport type RecordDraftIntent = 'create' | 'update' | 'delete' | 'upsert'\n\n/** The review lifecycle: `proposed` awaits a verdict; `approved` was applied\n * exactly as proposed; `approved_with_changes` was edited, then applied\n * (`changes` says what the reviewer altered); `rejected` was never applied.\n * The last three are terminal. The status is DERIVED by the server from the\n * per-item `verdicts` and `changes` — a resolver never names the outcome: a\n * draft stays `proposed` until every item has a verdict; then all accepted ⇒\n * `approved`, all rejected ⇒ `rejected`, anything else ⇒\n * `approved_with_changes`. */\nexport type RecordDraftStatus = 'proposed' | 'approved' | 'approved_with_changes' | 'rejected'\n\n/**\n * ONE proposed write, keyed like a batch transaction. Shape per intent —\n * create: `data`, no `id` · update: `id` + `data` · delete: `id`, no `data` ·\n * upsert: `data`, `id` optional (present ⇒ update, absent ⇒ create). `id` never\n * rides inside `data`. Update/upsert `data` is a partial merge (only the keys\n * present change).\n *\n * `entity_slug` is the entity this item writes; absent = the draft's own. A\n * relation attribute in `data` can point at ANOTHER ITEM of the draft instead\n * of a record id — `{ transaction_id: '1' }` ({@link RecordDraftReference}) —\n * and is resolved to that item's record id on approve, parents first.\n * `evidence` says where a proposed value came from, per attribute of `data`.\n */\nexport interface RecordDraftItem {\n transaction_id: string\n entity_slug?: string\n id?: string\n data?: Record<string, unknown>\n evidence?: Record<string, RecordDraftEvidence>\n}\n\n/** A relation value pointing at another item of the same draft. */\nexport interface RecordDraftReference {\n transaction_id: string\n}\n\n/** Whether a proposed value is a {@link RecordDraftReference}: an object\n * whose only key is a string `transaction_id`. */\nexport function isRecordDraftReference(value: unknown): value is RecordDraftReference {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const keys = Object.keys(value)\n return (\n keys.length === 1 &&\n keys[0] === 'transaction_id' &&\n typeof (value as RecordDraftReference).transaction_id === 'string'\n )\n}\n\n/** One source behind a proposed value. */\nexport interface RecordDraftCitation {\n title?: string\n url?: string\n snippet?: string\n}\n\n/** Why the proposer believes ONE proposed value: a short label, how sure it\n * is (0..1) and the sources. All optional. */\nexport interface RecordDraftEvidence {\n label?: string\n confidence?: number\n citations?: RecordDraftCitation[]\n}\n\n/** A reviewer's decision on an item or on one attribute of it. `edited` (items\n * only): written, but not exactly as proposed. */\nexport type RecordDraftVerdict = 'accepted' | 'edited' | 'rejected'\n\n/** What has been decided about ONE item so far. `verdict` is set once the\n * whole item is decided; while only some attributes are, it is absent and\n * `attributes` names them. */\nexport interface RecordDraftItemVerdict {\n transaction_id: string\n verdict?: RecordDraftVerdict\n attributes?: Record<string, Exclude<RecordDraftVerdict, 'edited'>>\n}\n\n/** Narrows an approve or a reject to part of a draft: `transaction_ids` picks\n * the items (absent = every undecided item), `attributes` the attributes of\n * those items (absent = all). An item that would create a record is decided\n * whole — naming it together with attributes fails with 400\n * `record_draft_scope_invalid`. */\nexport interface RecordDraftScope {\n transaction_ids?: string[]\n attributes?: string[]\n}\n\n/**\n * ONE value a proposed draft would write, next to what the record holds now —\n * the flat read model behind the suggestions overlay. `record_id` is absent\n * for a value of a record the draft would create. Only undecided values of\n * proposed drafts appear, never an attribute the reader may not read.\n */\nexport interface RecordDraftProposedValue {\n record_id?: string\n attribute: string\n current: unknown\n proposed: unknown\n evidence?: RecordDraftEvidence\n record_draft_id: string\n transaction_id: string\n created_at: string\n /**\n * The draft's `updated_at` when the value was read. Pass it as\n * `expected_updated_at` when approving or rejecting this value: a draft\n * revised since is refused (409 `record_draft_conflict`) instead of deciding\n * a value nobody saw.\n */\n record_draft_updated_at: string\n}\n\nexport interface ProposedValuesQuery {\n entity_slug: string\n /** At most 200. Values of records a draft would create are returned either way. */\n record_ids?: string[]\n}\n\nexport type RecordDraftItemResultStatus = 'success' | 'error'\n\n/** The same facts the single-record endpoint would have answered with. */\nexport interface RecordDraftItemError {\n code: string\n message: string\n status?: number\n details?: Record<string, unknown>\n}\n\n/** The outcome of applying one item — the batch result minus the record. */\nexport interface RecordDraftItemResult {\n transaction_id: string\n status: RecordDraftItemResultStatus\n record_id?: string\n error?: RecordDraftItemError\n}\n\n/** ONE thing the reviewer altered before applying. */\nexport type RecordDraftChangeKind =\n | 'item_dropped'\n | 'attribute_changed'\n | 'attribute_removed'\n | 'attribute_added'\n /** The reviewer added a whole item (a row); `applied` carries its data. */\n | 'item_added'\n\n/**\n * One entry of the reviewer's delta, diffed against the proposer's LATEST\n * version (the proposal, or the proposer's last revision of it).\n * `proposed` and `applied` are always present — `null` means \"cleared\".\n * `current` is the record's value BEFORE the write, captured for existing\n * targets (`has_current` says whether it was); it is STORED for the proposer\n * to learn from but NOT yet exposed by the API — responses carry it redacted\n * (`has_current: false`, `current: null`) because a draft reader may not be\n * allowed to read the record or that attribute.\n */\nexport interface RecordDraftChange {\n transaction_id: string\n kind: RecordDraftChangeKind\n attribute?: string\n has_current: boolean\n current: unknown\n proposed: unknown\n applied: unknown\n}\n\n/**\n * A PROPOSED record write awaiting a verdict — the record sibling of a draft\n * message. `items` is the draft as it stands now: the proposal, as revised by\n * its proposer and edited by reviewers while proposed (each save is a\n * {@link RecordDraftVersion}; `version` is the newest one's number);\n * `applied_items` what approves have sent so far; `results` the latest outcome\n * per transaction_id; `verdicts` what has been decided, per item and — for a\n * scoped approve or reject — per attribute (an approve only sends what is\n * undecided, so a re-approve never repeats a write); `changes` the reviewer's\n * delta. `entity_slug` is the entity of every item that names none,\n * `entity_slugs` every entity the items write. `source` is caller-supplied\n * provenance (`agent_key`, `session_id`, …); `created_by` is the acting user.\n */\nexport interface RecordDraft {\n id: string\n org_id: string\n entity_slug: string\n entity_slugs: string[]\n intent: RecordDraftIntent\n status: RecordDraftStatus\n summary: string\n items: RecordDraftItem[]\n version: number\n applied_items?: RecordDraftItem[]\n results?: RecordDraftItemResult[]\n changes?: RecordDraftChange[]\n verdicts?: RecordDraftItemVerdict[]\n source?: Record<string, unknown>\n reason?: string\n resolved_by?: { type: string; id: string }\n resolved_at?: string\n created_at: string\n created_by: { type: string; id: string }\n updated_at: string\n updated_by: { type: string; id: string }\n /** Set while an approve is writing the draft's records: saves, rejects and\n * other approves get 409 `record_draft_applying` until it is done. */\n applying_since?: string\n}\n\nexport interface CreateRecordDraftRequest {\n /** The entity of every item that names none. May be left out when every\n * item carries its own `entity_slug`. */\n entity_slug?: string\n intent: RecordDraftIntent\n /** 1..200 items; a missing `transaction_id` becomes the 1-based index. */\n items: RecordDraftItem[]\n /** The proposer's one-line why — required. */\n summary: string\n source?: Record<string, unknown>\n}\n\n/** An item as a save or an approve sends it: an existing item keeps its\n * `transaction_id`; an added one leaves it out and the server assigns one. */\nexport type RecordDraftItemInput = Omit<RecordDraftItem, 'transaction_id'> & {\n transaction_id?: string\n}\n\n/** `items` absent = apply the draft's items as they stand; present = save them\n * first as the reviewer's edit, then apply them. `transaction_ids` /\n * `attributes` apply only that part; the rest stays proposed. */\nexport interface ApproveRecordDraftRequest extends RecordDraftScope {\n items?: RecordDraftItemInput[]\n /** The `updated_at` the reviewer last saw: a draft that moved on since fails\n * with 409 `record_draft_conflict` instead of applying what they never saw. */\n expected_updated_at?: string\n}\n\n/**\n * How a version of a draft came to be: `proposed` (version 1), `revised` (the\n * proposer changed its proposal — it becomes the baseline reviewer changes\n * are measured against) or `edited` (a reviewer's edit; one reviewer's\n * consecutive saves update one version).\n */\nexport type RecordDraftVersionKind = 'proposed' | 'revised' | 'edited'\n\n/** One step of a draft's history: its complete items as they stood after it. */\nexport interface RecordDraftVersion {\n id: string\n org_id: string\n record_draft_id: string\n version: number\n kind: RecordDraftVersionKind\n summary: string\n items: RecordDraftItem[]\n created_at: string\n created_by: { type: string; id: string }\n updated_at: string\n updated_by: { type: string; id: string }\n}\n\n/**\n * Saves a PROPOSED draft's items — the complete set: an item left out is\n * dropped, an item without `transaction_id` is added (the server gives it a\n * fresh one). An existing item keeps its record `id`; an item an earlier\n * approve already wrote must stay exactly as applied. Nothing is written to\n * the records.\n */\nexport interface UpdateRecordDraftRequest {\n items: RecordDraftItemInput[]\n /** Absent keeps the summary. */\n summary?: string\n /** `revised` = the proposer; `edited` = a reviewer. */\n kind: Exclude<RecordDraftVersionKind, 'proposed'>\n /** The `updated_at` the editor last saw: a draft that moved on since fails\n * with 409 `record_draft_conflict`. Omit for last write wins. */\n expected_updated_at?: string\n}\n\n/** A draft's history (oldest first) and what reviewers changed so far. */\nexport interface RecordDraftVersions {\n data: RecordDraftVersion[]\n changes: RecordDraftChange[]\n}\n\n/** `transaction_ids` / `attributes` decline only that part; without either\n * everything still undecided is declined. */\nexport interface RejectRecordDraftRequest extends RecordDraftScope {\n reason?: string\n /** The `updated_at` the reviewer last saw: a draft that moved on since fails\n * with 409 `record_draft_conflict` instead of declining what they never saw. */\n expected_updated_at?: string\n}\n\nexport interface ListRecordDraftsQuery {\n /** Drafts holding an item of this entity. */\n entity_slug?: string\n /** Defaults to `proposed` on the server. */\n status?: RecordDraftStatus\n intent?: RecordDraftIntent\n /** Only drafts whose items name this record. */\n record_id?: string\n page?: number\n page_size?: number\n}\n\nexport const RecordDraftEvidenceSchema = z.object({\n label: z.string().optional(),\n confidence: z.number().min(0).max(1).optional(),\n citations: z\n .array(\n z.object({\n title: z.string().optional(),\n url: z.string().optional(),\n snippet: z.string().optional(),\n }),\n )\n .optional(),\n})\n\nexport const RecordDraftItemSchema = z.object({\n transaction_id: z.string(),\n entity_slug: z.string().optional(),\n id: z.string().optional(),\n data: z.record(z.string(), z.unknown()).optional(),\n evidence: z.record(z.string(), RecordDraftEvidenceSchema).optional(),\n})\n\nexport const RecordDraftItemResultSchema = z.object({\n transaction_id: z.string(),\n status: z.enum(['success', 'error']),\n record_id: z.string().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n status: z.number().optional(),\n details: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n})\n\nexport const RecordDraftChangeSchema = z.object({\n transaction_id: z.string(),\n kind: z.enum([\n 'item_dropped',\n 'attribute_changed',\n 'attribute_removed',\n 'attribute_added',\n 'item_added',\n ]),\n attribute: z.string().optional(),\n has_current: z.boolean(),\n current: z.unknown(),\n proposed: z.unknown(),\n applied: z.unknown(),\n})\n\n/** ONE page of an entity's records replayed as contact observations. */\nexport interface PublishContactObservationsResponse {\n entity_slug: string\n page: number\n page_size: number\n pages_total: number\n items_total: number\n published: number\n skipped: number\n}\n\n// ============================================================================\n// Entity indexes (per-org indexes on an entity's record table)\n// ============================================================================\n\n/** Named by what it does: lookup (=, IN, ranges, sort), unique (lookup that\n * refuses duplicates), search (substring match on one string attribute). */\nexport type EntityIndexType = 'lookup' | 'unique' | 'search'\n\n/** declared = from the entity (is_unique / unique_constraints); automatic =\n * the platform's relation/user indexes; applied = added per org by an admin. */\nexport type EntityIndexSource = 'declared' | 'automatic' | 'applied'\n\nexport type EntityIndexState = 'ready' | 'building' | 'invalid' | 'missing'\n\nexport interface EntityIndex {\n name: string\n type: EntityIndexType\n attributes: string[]\n source: EntityIndexSource\n state?: EntityIndexState\n size_bytes?: number\n scans?: number\n created_at?: string\n}\n\nexport const EntityIndexSchema = z.object({\n name: z.string(),\n type: z.enum(['lookup', 'unique', 'search']),\n attributes: z.array(z.string()),\n source: z.enum(['declared', 'automatic', 'applied']),\n state: z.enum(['ready', 'building', 'invalid', 'missing']).optional(),\n size_bytes: z.number().optional(),\n scans: z.number().optional(),\n created_at: z.string().optional(),\n})\n\n/** Only slow runs (>= the advisor's slow threshold) are recorded, so\n * `slow_queries` is the whole sample and `avg_ms` their average. */\nexport interface IndexEvidence {\n slow_queries: number\n avg_ms: number\n rows: number\n scans: number\n reason: string\n}\n\nexport interface IndexRecommendation {\n action: 'add' | 'remove'\n index: EntityIndex\n evidence: IndexEvidence\n /** On an `add`: applied lookups the new index supersedes. Pass through as\n * `CreateEntityIndexRequest.replaces` so the create swaps them. */\n replaces?: string[]\n}\n\n/** Only lookup and search can be applied; uniqueness is declared on the entity. */\nexport interface CreateEntityIndexRequest {\n /** Derived from the attributes when omitted (by_<a>_<b>, search_<a>). */\n name?: string\n type: 'lookup' | 'search'\n attributes: string[]\n /** Applied lookups this index supersedes (each must be covered by it);\n * removed in the same step. Required whenever one exists, else 400 index_redundant. */\n replaces?: string[]\n}\n","import type { ProteosClient } from '../client.js'\nimport { type EntityIndexService, EntityIndexServiceImpl } from './entity-indexes.js'\nimport { type QueryService, QueryServiceImpl } from './queries.js'\nimport { type RecordDraftService, RecordDraftServiceImpl } from './record-drafts.js'\nimport {\n type RecordDuplicateService,\n RecordDuplicateServiceImpl,\n type RecordService,\n RecordServiceImpl,\n} from './records.js'\n\n/**\n * Facade for the data-service (records + raw-SQL query API).\n *\n * Usage:\n * ```ts\n * const client = new ProteosClient({ baseUrl, tokenProvider });\n * const data = new DataClient(client);\n * const page = await data.records.listPage('customer');\n * const result = await data.queries.execute('SELECT id, stage FROM opportunity');\n * ```\n */\nexport class DataClient {\n readonly records: RecordService\n readonly queries: QueryService\n /** Duplicate pairs of an entity's records (raised by contact binding). */\n readonly recordDuplicates: RecordDuplicateService\n /** Per-entity indexes on the record table + the advisor's recommendations. */\n readonly entityIndexes: EntityIndexService\n /** Proposed record writes awaiting a human (or reviewing agent) verdict. */\n readonly recordDrafts: RecordDraftService\n\n constructor(client: ProteosClient) {\n this.records = new RecordServiceImpl(client)\n this.queries = new QueryServiceImpl(client)\n this.recordDuplicates = new RecordDuplicateServiceImpl(client)\n this.entityIndexes = new EntityIndexServiceImpl(client)\n this.recordDrafts = new RecordDraftServiceImpl(client)\n }\n}\n\nexport type { EntityIndexService } from './entity-indexes.js'\n// Re-export service interfaces\n// Re-export types\nexport type {\n CreateQueryRequest,\n ListQueriesQuery,\n Query,\n QueryBuilder,\n QueryExecuteMeta,\n QueryExecuteResponse,\n QueryRow,\n QueryService,\n QueryValidateMeta,\n QueryValidateResponse,\n UpdateQueryRequest,\n} from './queries.js'\nexport type { RecordDraftService } from './record-drafts.js'\nexport type { RecordDuplicateService, RecordService } from './records.js'\nexport type {\n ApproveRecordDraftRequest,\n BatchTransactionError,\n BatchTransactionStatus,\n BatchUpsertRecordsResponse,\n BatchUpsertTransaction,\n BatchUpsertTransactionResult,\n CreateEntityIndexRequest,\n CreateRecordDraftRequest,\n EntityIndex,\n EntityIndexSource,\n EntityIndexState,\n EntityIndexType,\n IndexEvidence,\n IndexRecommendation,\n ListRecordDraftsQuery,\n ListRecordDuplicatesQuery,\n ListRecordsOptions,\n ProposedValuesQuery,\n PublishContactObservationsResponse,\n RecordData,\n RecordDraft,\n RecordDraftChange,\n RecordDraftChangeKind,\n RecordDraftCitation,\n RecordDraftEvidence,\n RecordDraftIntent,\n RecordDraftItem,\n RecordDraftItemError,\n RecordDraftItemInput,\n RecordDraftItemResult,\n RecordDraftItemResultStatus,\n RecordDraftItemVerdict,\n RecordDraftProposedValue,\n RecordDraftReference,\n RecordDraftScope,\n RecordDraftStatus,\n RecordDraftVerdict,\n RecordDraftVersion,\n RecordDraftVersionKind,\n RecordDraftVersions,\n RecordDuplicate,\n RecordDuplicateSource,\n RecordDuplicateStatus,\n RejectRecordDraftRequest,\n UpdateRecordDraftRequest,\n} from './types.js'\n\n// Re-export Zod schemas\nexport {\n BatchTransactionErrorSchema,\n BatchUpsertRecordsResponseSchema,\n BatchUpsertTransactionResultSchema,\n BatchUpsertTransactionSchema,\n isRecordDraftReference,\n RecordDraftChangeSchema,\n RecordDraftEvidenceSchema,\n RecordDraftItemResultSchema,\n RecordDraftItemSchema,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type {\n CreateDiscoveryEvidenceNarrationRequest,\n CreateDiscoveryEvidenceRequest,\n CreateDiscoveryInterviewDefinitionRequest,\n DiscoveryEvidence,\n DiscoveryEvidenceDownloadUrl,\n DiscoveryEvidenceNarration,\n DiscoveryEvidenceOrgSummary,\n DiscoveryInterview,\n DiscoveryInterviewDefinition,\n DiscoveryInterviewParticipation,\n InviteDiscoveryInterviewParticipantsRequest,\n ListDiscoveryEvidenceQuery,\n ListDiscoveryInterviewDefinitionsQuery,\n ListDiscoveryInterviewsQuery,\n ListPlatformDiscoveryEvidenceQuery,\n ListResponse,\n StartDiscoveryInterviewParticipationRequest,\n UpdateDiscoveryEvidenceRequest,\n UpdateDiscoveryEvidenceStatusRequest,\n UpdateDiscoveryInterviewDefinitionRequest,\n} from './types.js'\n\nexport * from './types.js'\n\nconst DISCOVERY_BASE_PATH = '/discovery/v1'\n\nconst encode = encodeURIComponent\n\n/**\n * Facade for discovery-service: the evidence users send Proteos (screenshots,\n * screen recordings with ink-annotated frames, written feedback).\n *\n * `evidence` acts in the caller's org — own rows under a scoped grant, every\n * row under the unscoped read. `narrations` are the jobs that draft feedback\n * from what was said in a recording. `platform` is the Proteos-side view\n * across every org; it answers only to platform admins.\n *\n * `interviewDefinitions` are the interview guides an admin writes and\n * `interviews` what each participant's interview came to. Both also carry the\n * participant's own calls (`getParticipation`, `startParticipation`,\n * `complete`), which answer to the person interviewed, not to a grant.\n *\n * ```ts\n * const discovery = new DiscoveryClient(client)\n * const sent = await discovery.evidence.create({ kind: 'feedback', source: 'web', notes, context })\n * const { data: mine } = await discovery.evidence.list()\n * const { url } = await discovery.evidence.createDownloadUrl(sent.id, fileId)\n * ```\n */\nexport class DiscoveryClient {\n readonly evidence: DiscoveryEvidenceService\n readonly narrations: DiscoveryEvidenceNarrationService\n readonly platform: PlatformDiscoveryEvidenceService\n readonly interviewDefinitions: DiscoveryInterviewDefinitionService\n readonly interviews: DiscoveryInterviewService\n\n constructor(client: ProteosClient) {\n this.evidence = new DiscoveryEvidenceServiceImpl(client)\n this.narrations = new DiscoveryEvidenceNarrationServiceImpl(client)\n this.platform = new PlatformDiscoveryEvidenceServiceImpl(client)\n this.interviewDefinitions = new DiscoveryInterviewDefinitionServiceImpl(client)\n this.interviews = new DiscoveryInterviewServiceImpl(client)\n }\n}\n\n/** The submitter's door: create, read back, edit the words, withdraw. */\nexport interface DiscoveryEvidenceService {\n create(request: CreateDiscoveryEvidenceRequest): Promise<DiscoveryEvidence>\n list(query?: ListDiscoveryEvidenceQuery): Promise<ListResponse<DiscoveryEvidence>>\n /** The detail read; carries the frames. */\n get(id: string): Promise<DiscoveryEvidence>\n update(id: string, request: UpdateDiscoveryEvidenceRequest): Promise<DiscoveryEvidence>\n /** Withdraws the evidence; its files are removed best-effort. */\n delete(id: string): Promise<void>\n /** Mints a presigned URL for one of the evidence's files (recording, frame image). */\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl>\n}\n\n/**\n * Narration jobs of the capture UI: started when a recording with sound stops,\n * polled until `completed` or `failed`, named on the create request.\n */\nexport interface DiscoveryEvidenceNarrationService {\n create(request: CreateDiscoveryEvidenceNarrationRequest): Promise<DiscoveryEvidenceNarration>\n get(id: string): Promise<DiscoveryEvidenceNarration>\n /** Discards a job that was not sent with evidence, along with its audio file. */\n delete(id: string): Promise<void>\n}\n\n/** The Proteos-side view across orgs. Platform admins only. */\nexport interface PlatformDiscoveryEvidenceService {\n list(query?: ListPlatformDiscoveryEvidenceQuery): Promise<ListResponse<DiscoveryEvidence>>\n /** Per-org counts: how much evidence, how much still new, the newest arrival. */\n summary(): Promise<DiscoveryEvidenceOrgSummary[]>\n get(id: string): Promise<DiscoveryEvidence>\n updateStatus(\n id: string,\n request: UpdateDiscoveryEvidenceStatusRequest,\n ): Promise<DiscoveryEvidence>\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl>\n}\n\n/**\n * Interview definitions: the guide (objective, questions, agent) and who it is\n * for. The last two methods are the participant's: what their page shows\n * before the interview, and starting or resuming their own interview.\n */\nexport interface DiscoveryInterviewDefinitionService {\n create(request: CreateDiscoveryInterviewDefinitionRequest): Promise<DiscoveryInterviewDefinition>\n list(\n query?: ListDiscoveryInterviewDefinitionsQuery,\n ): Promise<ListResponse<DiscoveryInterviewDefinition>>\n /** The detail read; carries `guide_findings`. */\n get(id: string): Promise<DiscoveryInterviewDefinition>\n update(\n id: string,\n request: UpdateDiscoveryInterviewDefinitionRequest,\n ): Promise<DiscoveryInterviewDefinition>\n /** Deletes the definition with its interviews and their recordings. */\n delete(id: string): Promise<void>\n publish(id: string): Promise<DiscoveryInterviewDefinition>\n /** Nobody can start or continue; results stay readable. */\n close(id: string): Promise<DiscoveryInterviewDefinition>\n reopen(id: string): Promise<DiscoveryInterviewDefinition>\n /** Assigns users; people already assigned are returned unchanged. */\n invite(\n id: string,\n request: InviteDiscoveryInterviewParticipantsRequest,\n ): Promise<DiscoveryInterview[]>\n getParticipation(id: string): Promise<DiscoveryInterviewParticipation>\n startParticipation(\n id: string,\n request: StartDiscoveryInterviewParticipationRequest,\n ): Promise<DiscoveryInterviewParticipation>\n}\n\n/**\n * Interviews of a definition, for whoever can read it. `complete` and\n * `getParticipation` are the participant's.\n */\nexport interface DiscoveryInterviewService {\n list(query: ListDiscoveryInterviewsQuery): Promise<ListResponse<DiscoveryInterview>>\n /** The detail read; carries the guide snapshot and the transcript. */\n get(id: string): Promise<DiscoveryInterview>\n /** Sends the invitation again. */\n remind(id: string): Promise<void>\n /** Reruns a synthesis that failed. */\n synthesize(id: string): Promise<DiscoveryInterview>\n /** Withdraws an invitation or deletes a result with its recordings. */\n delete(id: string): Promise<void>\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl>\n /** Ends the caller's interview and starts the synthesis. Safe to repeat. */\n complete(id: string): Promise<DiscoveryInterviewParticipation>\n getParticipation(id: string): Promise<DiscoveryInterviewParticipation>\n}\n\nclass DiscoveryEvidenceServiceImpl implements DiscoveryEvidenceService {\n constructor(private readonly client: ProteosClient) {}\n\n create(request: CreateDiscoveryEvidenceRequest): Promise<DiscoveryEvidence> {\n return this.client.request('POST', `${DISCOVERY_BASE_PATH}/evidence`, request)\n }\n\n list(query: ListDiscoveryEvidenceQuery = {}): Promise<ListResponse<DiscoveryEvidence>> {\n return this.client.requestWithQuery('GET', `${DISCOVERY_BASE_PATH}/evidence`, query)\n }\n\n get(id: string): Promise<DiscoveryEvidence> {\n return this.client.request('GET', `${DISCOVERY_BASE_PATH}/evidence/${encode(id)}`)\n }\n\n update(id: string, request: UpdateDiscoveryEvidenceRequest): Promise<DiscoveryEvidence> {\n return this.client.request('PATCH', `${DISCOVERY_BASE_PATH}/evidence/${encode(id)}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', `${DISCOVERY_BASE_PATH}/evidence/${encode(id)}`)\n }\n\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl> {\n return this.client.request(\n 'POST',\n `${DISCOVERY_BASE_PATH}/evidence/${encode(id)}/files/${encode(fileId)}/download-url`,\n )\n }\n}\n\nclass DiscoveryEvidenceNarrationServiceImpl implements DiscoveryEvidenceNarrationService {\n constructor(private readonly client: ProteosClient) {}\n\n create(request: CreateDiscoveryEvidenceNarrationRequest): Promise<DiscoveryEvidenceNarration> {\n return this.client.request('POST', `${DISCOVERY_BASE_PATH}/evidence-narrations`, request)\n }\n\n get(id: string): Promise<DiscoveryEvidenceNarration> {\n return this.client.request('GET', `${DISCOVERY_BASE_PATH}/evidence-narrations/${encode(id)}`)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', `${DISCOVERY_BASE_PATH}/evidence-narrations/${encode(id)}`)\n }\n}\n\nclass PlatformDiscoveryEvidenceServiceImpl implements PlatformDiscoveryEvidenceService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListPlatformDiscoveryEvidenceQuery = {}): Promise<ListResponse<DiscoveryEvidence>> {\n return this.client.requestWithQuery('GET', `${DISCOVERY_BASE_PATH}/platform/evidence`, query)\n }\n\n async summary(): Promise<DiscoveryEvidenceOrgSummary[]> {\n const response = await this.client.request<{ data: DiscoveryEvidenceOrgSummary[] }>(\n 'GET',\n `${DISCOVERY_BASE_PATH}/platform/evidence/summary`,\n )\n return response.data\n }\n\n get(id: string): Promise<DiscoveryEvidence> {\n return this.client.request('GET', `${DISCOVERY_BASE_PATH}/platform/evidence/${encode(id)}`)\n }\n\n updateStatus(\n id: string,\n request: UpdateDiscoveryEvidenceStatusRequest,\n ): Promise<DiscoveryEvidence> {\n return this.client.request(\n 'PATCH',\n `${DISCOVERY_BASE_PATH}/platform/evidence/${encode(id)}/status`,\n request,\n )\n }\n\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl> {\n return this.client.request(\n 'POST',\n `${DISCOVERY_BASE_PATH}/platform/evidence/${encode(id)}/files/${encode(fileId)}/download-url`,\n )\n }\n}\n\nclass DiscoveryInterviewDefinitionServiceImpl implements DiscoveryInterviewDefinitionService {\n constructor(private readonly client: ProteosClient) {}\n\n private path(id?: string, suffix = ''): string {\n const base = `${DISCOVERY_BASE_PATH}/interview-definitions`\n return id === undefined ? base : `${base}/${encode(id)}${suffix}`\n }\n\n create(\n request: CreateDiscoveryInterviewDefinitionRequest,\n ): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('POST', this.path(), request)\n }\n\n list(\n query: ListDiscoveryInterviewDefinitionsQuery = {},\n ): Promise<ListResponse<DiscoveryInterviewDefinition>> {\n return this.client.requestWithQuery('GET', this.path(), query)\n }\n\n get(id: string): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('GET', this.path(id))\n }\n\n update(\n id: string,\n request: UpdateDiscoveryInterviewDefinitionRequest,\n ): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('PATCH', this.path(id), request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', this.path(id))\n }\n\n publish(id: string): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('POST', this.path(id, '/publish'))\n }\n\n close(id: string): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('POST', this.path(id, '/close'))\n }\n\n reopen(id: string): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('POST', this.path(id, '/reopen'))\n }\n\n async invite(\n id: string,\n request: InviteDiscoveryInterviewParticipantsRequest,\n ): Promise<DiscoveryInterview[]> {\n const response = await this.client.request<{ data: DiscoveryInterview[] }>(\n 'POST',\n this.path(id, '/interviews'),\n request,\n )\n return response.data\n }\n\n getParticipation(id: string): Promise<DiscoveryInterviewParticipation> {\n return this.client.request('GET', this.path(id, '/participation'))\n }\n\n startParticipation(\n id: string,\n request: StartDiscoveryInterviewParticipationRequest,\n ): Promise<DiscoveryInterviewParticipation> {\n return this.client.request('POST', this.path(id, '/participation/start'), request)\n }\n}\n\nclass DiscoveryInterviewServiceImpl implements DiscoveryInterviewService {\n constructor(private readonly client: ProteosClient) {}\n\n private path(id: string, suffix = ''): string {\n return `${DISCOVERY_BASE_PATH}/interviews/${encode(id)}${suffix}`\n }\n\n list(query: ListDiscoveryInterviewsQuery): Promise<ListResponse<DiscoveryInterview>> {\n return this.client.requestWithQuery('GET', `${DISCOVERY_BASE_PATH}/interviews`, query)\n }\n\n get(id: string): Promise<DiscoveryInterview> {\n return this.client.request('GET', this.path(id))\n }\n\n async remind(id: string): Promise<void> {\n await this.client.request('POST', this.path(id, '/remind'))\n }\n\n synthesize(id: string): Promise<DiscoveryInterview> {\n return this.client.request('POST', this.path(id, '/synthesize'))\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', this.path(id))\n }\n\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl> {\n return this.client.request('POST', this.path(id, `/files/${encode(fileId)}/download-url`))\n }\n\n complete(id: string): Promise<DiscoveryInterviewParticipation> {\n return this.client.request('POST', this.path(id, '/complete'), {})\n }\n\n getParticipation(id: string): Promise<DiscoveryInterviewParticipation> {\n return this.client.request('GET', this.path(id, '/participation'))\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n CreateEnrichmentConnectionRequest,\n CreateEnrichmentRunRequest,\n CreateResearchDefinitionRequest,\n CreateSignalMonitorRequest,\n CreateWaterfallRequest,\n EnrichmentBlock,\n EnrichmentConnection,\n EnrichmentEntry,\n EnrichmentItem,\n EnrichmentMapping,\n EnrichmentProvenance,\n EnrichmentProvider,\n EnrichmentRun,\n EnrichmentRunList,\n EnrichmentRunResponse,\n EnrichmentTypesResponse,\n EnrichRequest,\n EnrichResponse,\n ListEnrichmentRunsQuery,\n ListResearchRunsQuery,\n ListSignalsQuery,\n PatchEnrichmentConnectionRequest,\n PatchResearchDefinitionRequest,\n PatchSignalMonitorRequest,\n PatchWaterfallRequest,\n PutSignalMappingRequest,\n ReplaceEnrichmentMappingRequest,\n ResearchDefinition,\n ResearchResult,\n ResearchRun,\n ResearchRunList,\n SignalList,\n SignalMapping,\n SignalMonitor,\n Waterfall,\n} from './types.js'\n\nexport * from './types.js'\n\nconst ENRICHMENT_BASE_PATH = '/enrichment/v1'\n\nconst encode = encodeURIComponent\n\n/**\n * `POST /enrich` waits for its waterfalls and `POST /enrichment-runs` for up\n * to `wait_seconds`: 30 seconds each at most by default, which is the\n * client's default timeout. They get longer, so the service's answer comes\n * back instead of a client timeout.\n */\nconst WAITING_REQUEST_TIMEOUT_MS = 75_000\n\n/**\n * Facade for enrichment-service: filling attributes from providers through\n * waterfalls.\n *\n * `enrich` returns values and writes nothing. `runs` enrich records and write\n * or propose what they find (a record draft), as each attribute's apply level\n * says. `mappings` say what each attribute of an entity does in enrichment,\n * `waterfalls` are an org's own step lists, `research` finds companies and\n * people that are no records yet and proposes them as record drafts,\n * `signals` are the changes a scheduled refresh or a web monitor detected and\n * what they propose, and `catalog` is what can be asked for and who supplies\n * it.\n *\n * Single resources come back bare; the lists (run items, waterfalls,\n * providers) are unwrapped from `{data}` and are not paged.\n *\n * ```ts\n * const enrichment = new EnrichmentClient(client)\n * const found = await enrichment.enrich({ entity_slug: 'contact', record_id: id, attributes: ['email'] })\n * const run = await enrichment.runs.create({ entity_slug: 'contact', record_ids: ids, wait_seconds: 20 })\n * const items = await enrichment.runs.listItems(run.enrichment_run_id)\n * await enrichment.mappings.setEntry('contact', 'email', { enrichment_type: 'work_email' })\n * const researchRun = await enrichment.research.startRun(definitionId)\n * const rows = await enrichment.research.listResults(researchRun.id)\n * ```\n */\nexport class EnrichmentClient {\n readonly runs: EnrichmentRunService\n readonly mappings: EnrichmentMappingService\n readonly waterfalls: WaterfallService\n readonly connections: EnrichmentConnectionService\n readonly research: ResearchService\n readonly signals: SignalService\n readonly catalog: EnrichmentCatalogService\n\n constructor(private readonly client: ProteosClient) {\n this.runs = new EnrichmentRunServiceImpl(client)\n this.mappings = new EnrichmentMappingServiceImpl(client)\n this.waterfalls = new WaterfallServiceImpl(client)\n this.connections = new EnrichmentConnectionServiceImpl(client)\n this.research = new ResearchServiceImpl(client)\n this.signals = new SignalServiceImpl(client)\n this.catalog = new EnrichmentCatalogServiceImpl(client)\n }\n\n /** Fills attributes ad hoc: the values are returned, nothing is written. */\n enrich(request: EnrichRequest): Promise<EnrichResponse> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/enrich`, request, {\n timeout: WAITING_REQUEST_TIMEOUT_MS,\n })\n }\n}\n\n/** Runs over records. */\nexport interface EnrichmentRunService {\n /**\n * Starts a run. Answers once the run has finished or `wait_seconds` are\n * over, whichever is first; a run that is still running is followed with\n * `get`.\n */\n create(request: CreateEnrichmentRunRequest): Promise<EnrichmentRunResponse>\n /** One page of the org's runs, newest first, without their `resolved_attributes`. */\n list(query?: ListEnrichmentRunsQuery): Promise<EnrichmentRunList>\n get(id: string): Promise<EnrichmentRun>\n /** A run's items with their results. */\n listItems(id: string): Promise<EnrichmentItem[]>\n /** Stops the records whose turn has not come, and the ones that wait for a provider's answer. */\n cancel(id: string): Promise<EnrichmentRun>\n /**\n * Where the values of one record came from: per attribute, the enrichment\n * that found the value the record holds now and wrote it, or suggested it\n * to a reviewer who accepted it.\n */\n provenance(entitySlug: string, recordId: string): Promise<EnrichmentProvenance>\n}\n\n/** The enrichment mapping of an entity. */\nexport interface EnrichmentMappingService {\n /** An entity's mapping, its orphaned entries marked. */\n get(entitySlug: string): Promise<EnrichmentMapping>\n /** Writes the whole mapping; 409 when it changed meanwhile. */\n replace(entitySlug: string, request: ReplaceEnrichmentMappingRequest): Promise<EnrichmentMapping>\n getEntry(entitySlug: string, attribute: string): Promise<EnrichmentEntry>\n /** Writes one attribute's entry and touches no other. */\n setEntry(entitySlug: string, attribute: string, block: EnrichmentBlock): Promise<EnrichmentEntry>\n deleteEntry(entitySlug: string, attribute: string): Promise<void>\n}\n\n/** An org's waterfalls. Platform defaults are listed and read-only. */\nexport interface WaterfallService {\n /** The org's waterfalls, active or not, and the platform defaults. */\n list(): Promise<Waterfall[]>\n get(id: string): Promise<Waterfall>\n /** 409 while another active waterfall holds its attribute, or is the default of its enrichment type. */\n create(request: CreateWaterfallRequest): Promise<Waterfall>\n patch(id: string, request: PatchWaterfallRequest): Promise<Waterfall>\n delete(id: string): Promise<void>\n}\n\n/**\n * An org's enrichment connections: its bindings to its own connections (its\n * Clay key), which the `connection` steps of its waterfalls run on.\n */\nexport interface EnrichmentConnectionService {\n list(): Promise<EnrichmentConnection[]>\n get(id: string): Promise<EnrichmentConnection>\n /** Binds one of the org's connections. A person's own connection can only be bound by that person. */\n create(request: CreateEnrichmentConnectionRequest): Promise<EnrichmentConnection>\n patch(id: string, request: PatchEnrichmentConnectionRequest): Promise<EnrichmentConnection>\n /** A waterfall step that names it is skipped from then on. */\n delete(id: string): Promise<void>\n}\n\n/**\n * Research definitions and their runs. A definition says what to find on the\n * web and how a found row maps onto the org's entities; a run finds the rows\n * and proposes the new ones as record drafts. Nothing is written to a record\n * until a reviewer accepts a draft in data-service.\n */\nexport interface ResearchService {\n listDefinitions(): Promise<ResearchDefinition[]>\n getDefinition(id: string): Promise<ResearchDefinition>\n /** Every entity the definition maps onto needs an enrichment mapping. */\n createDefinition(request: CreateResearchDefinitionRequest): Promise<ResearchDefinition>\n patchDefinition(id: string, request: PatchResearchDefinitionRequest): Promise<ResearchDefinition>\n /** Removes the definition with its runs and their rows. The record drafts its runs proposed stay. */\n deleteDefinition(id: string): Promise<void>\n /**\n * Starts a run and returns it while it is still running; follow it with\n * `getRun`. 409 while the definition has a run that is still running.\n */\n startRun(definitionId: string): Promise<ResearchRun>\n /** One page of the org's research runs, newest first. */\n listRuns(query?: ListResearchRunsQuery): Promise<ResearchRunList>\n getRun(id: string): Promise<ResearchRun>\n /** The rows a run found, each as a reviewer left it. */\n listResults(runId: string): Promise<ResearchResult[]>\n /** Stops a running run. Drafts it proposed already stay. */\n cancelRun(id: string): Promise<ResearchRun>\n}\n\n/**\n * Signals: the log of detected changes, the signal mapping of each kind\n * (which records a signal creates and what it proposes on the record it is\n * about), and signal monitors (standing web monitors for news, funding and\n * hiring about some records). A scheduled refresh detects `field_change`,\n * `job_change` and `headcount_change` by itself; turn it on with the\n * `on_schedule` trigger and `refresh_every_days` of a mapping entry.\n */\nexport interface SignalService {\n /** One page of the org's signals, newest first. */\n list(query?: ListSignalsQuery): Promise<SignalList>\n listMappings(): Promise<SignalMapping[]>\n getMapping(kind: string): Promise<SignalMapping>\n /** Writes the whole of what a signal of the kind does to records. */\n putMapping(kind: string, request: PutSignalMappingRequest): Promise<SignalMapping>\n /** The kind's signals are still logged and published, and propose nothing. */\n deleteMapping(kind: string): Promise<void>\n listMonitors(): Promise<SignalMonitor[]>\n getMonitor(id: string): Promise<SignalMonitor>\n /**\n * An active monitor checks for the first time within a minute and then every\n * `schedule.every_days`; every check costs money.\n */\n createMonitor(request: CreateSignalMonitorRequest): Promise<SignalMonitor>\n patchMonitor(id: string, request: PatchSignalMonitorRequest): Promise<SignalMonitor>\n /** The signals the monitor detected stay. */\n deleteMonitor(id: string): Promise<void>\n}\n\n/** What can be asked for and who supplies it. The same for every org. */\nexport interface EnrichmentCatalogService {\n enrichmentTypes(): Promise<EnrichmentTypesResponse>\n providers(): Promise<EnrichmentProvider[]>\n}\n\nclass EnrichmentRunServiceImpl implements EnrichmentRunService {\n constructor(private readonly client: ProteosClient) {}\n\n create(request: CreateEnrichmentRunRequest): Promise<EnrichmentRunResponse> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/enrichment-runs`, request, {\n timeout: WAITING_REQUEST_TIMEOUT_MS,\n })\n }\n\n list(query: ListEnrichmentRunsQuery = {}): Promise<EnrichmentRunList> {\n return this.client.requestWithQuery('GET', `${ENRICHMENT_BASE_PATH}/enrichment-runs`, query)\n }\n\n get(id: string): Promise<EnrichmentRun> {\n return this.client.request('GET', `${ENRICHMENT_BASE_PATH}/enrichment-runs/${encode(id)}`)\n }\n\n async listItems(id: string): Promise<EnrichmentItem[]> {\n const response = await this.client.request<{ data: EnrichmentItem[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/enrichment-runs/${encode(id)}/items`,\n )\n return response.data\n }\n\n cancel(id: string): Promise<EnrichmentRun> {\n return this.client.request(\n 'POST',\n `${ENRICHMENT_BASE_PATH}/enrichment-runs/${encode(id)}/cancel`,\n )\n }\n\n provenance(entitySlug: string, recordId: string): Promise<EnrichmentProvenance> {\n return this.client.requestWithQuery('GET', `${ENRICHMENT_BASE_PATH}/provenance`, {\n entity_slug: entitySlug,\n record_id: recordId,\n })\n }\n}\n\nclass EnrichmentMappingServiceImpl implements EnrichmentMappingService {\n constructor(private readonly client: ProteosClient) {}\n\n private entryPath(entitySlug: string, attribute: string): string {\n return `${ENRICHMENT_BASE_PATH}/mappings/${encode(entitySlug)}/attributes/${encode(attribute)}`\n }\n\n get(entitySlug: string): Promise<EnrichmentMapping> {\n return this.client.request('GET', `${ENRICHMENT_BASE_PATH}/mappings/${encode(entitySlug)}`)\n }\n\n replace(\n entitySlug: string,\n request: ReplaceEnrichmentMappingRequest,\n ): Promise<EnrichmentMapping> {\n return this.client.request(\n 'PUT',\n `${ENRICHMENT_BASE_PATH}/mappings/${encode(entitySlug)}`,\n request,\n )\n }\n\n getEntry(entitySlug: string, attribute: string): Promise<EnrichmentEntry> {\n return this.client.request('GET', this.entryPath(entitySlug, attribute))\n }\n\n setEntry(\n entitySlug: string,\n attribute: string,\n block: EnrichmentBlock,\n ): Promise<EnrichmentEntry> {\n return this.client.request('PUT', this.entryPath(entitySlug, attribute), block)\n }\n\n async deleteEntry(entitySlug: string, attribute: string): Promise<void> {\n await this.client.request('DELETE', this.entryPath(entitySlug, attribute))\n }\n}\n\nclass WaterfallServiceImpl implements WaterfallService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<Waterfall[]> {\n const response = await this.client.request<{ data: Waterfall[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/waterfalls`,\n )\n return response.data\n }\n\n get(id: string): Promise<Waterfall> {\n return this.client.request('GET', `${ENRICHMENT_BASE_PATH}/waterfalls/${encode(id)}`)\n }\n\n create(request: CreateWaterfallRequest): Promise<Waterfall> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/waterfalls`, request)\n }\n\n patch(id: string, request: PatchWaterfallRequest): Promise<Waterfall> {\n return this.client.request('PATCH', `${ENRICHMENT_BASE_PATH}/waterfalls/${encode(id)}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', `${ENRICHMENT_BASE_PATH}/waterfalls/${encode(id)}`)\n }\n}\n\nclass EnrichmentConnectionServiceImpl implements EnrichmentConnectionService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<EnrichmentConnection[]> {\n const response = await this.client.request<{ data: EnrichmentConnection[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections`,\n )\n return response.data\n }\n\n get(id: string): Promise<EnrichmentConnection> {\n return this.client.request(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections/${encode(id)}`,\n )\n }\n\n create(request: CreateEnrichmentConnectionRequest): Promise<EnrichmentConnection> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/enrichment-connections`, request)\n }\n\n patch(id: string, request: PatchEnrichmentConnectionRequest): Promise<EnrichmentConnection> {\n return this.client.request(\n 'PATCH',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections/${encode(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections/${encode(id)}`,\n )\n }\n}\n\nclass SignalServiceImpl implements SignalService {\n constructor(private readonly client: ProteosClient) {}\n\n private mappingPath(kind: string): string {\n return `${ENRICHMENT_BASE_PATH}/signal-mappings/${encode(kind)}`\n }\n\n private monitorPath(id: string): string {\n return `${ENRICHMENT_BASE_PATH}/signal-monitors/${encode(id)}`\n }\n\n list(query: ListSignalsQuery = {}): Promise<SignalList> {\n return this.client.requestWithQuery('GET', `${ENRICHMENT_BASE_PATH}/signals`, query)\n }\n\n async listMappings(): Promise<SignalMapping[]> {\n const response = await this.client.request<{ data: SignalMapping[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/signal-mappings`,\n )\n return response.data\n }\n\n getMapping(kind: string): Promise<SignalMapping> {\n return this.client.request('GET', this.mappingPath(kind))\n }\n\n putMapping(kind: string, request: PutSignalMappingRequest): Promise<SignalMapping> {\n return this.client.request('PUT', this.mappingPath(kind), request)\n }\n\n async deleteMapping(kind: string): Promise<void> {\n await this.client.request('DELETE', this.mappingPath(kind))\n }\n\n async listMonitors(): Promise<SignalMonitor[]> {\n const response = await this.client.request<{ data: SignalMonitor[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/signal-monitors`,\n )\n return response.data\n }\n\n getMonitor(id: string): Promise<SignalMonitor> {\n return this.client.request('GET', this.monitorPath(id))\n }\n\n createMonitor(request: CreateSignalMonitorRequest): Promise<SignalMonitor> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/signal-monitors`, request)\n }\n\n patchMonitor(id: string, request: PatchSignalMonitorRequest): Promise<SignalMonitor> {\n return this.client.request('PATCH', this.monitorPath(id), request)\n }\n\n async deleteMonitor(id: string): Promise<void> {\n await this.client.request('DELETE', this.monitorPath(id))\n }\n}\n\nclass ResearchServiceImpl implements ResearchService {\n constructor(private readonly client: ProteosClient) {}\n\n private definitionPath(id: string): string {\n return `${ENRICHMENT_BASE_PATH}/research-definitions/${encode(id)}`\n }\n\n private runPath(id: string): string {\n return `${ENRICHMENT_BASE_PATH}/research-runs/${encode(id)}`\n }\n\n async listDefinitions(): Promise<ResearchDefinition[]> {\n const response = await this.client.request<{ data: ResearchDefinition[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/research-definitions`,\n )\n return response.data\n }\n\n getDefinition(id: string): Promise<ResearchDefinition> {\n return this.client.request('GET', this.definitionPath(id))\n }\n\n createDefinition(request: CreateResearchDefinitionRequest): Promise<ResearchDefinition> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/research-definitions`, request)\n }\n\n patchDefinition(\n id: string,\n request: PatchResearchDefinitionRequest,\n ): Promise<ResearchDefinition> {\n return this.client.request('PATCH', this.definitionPath(id), request)\n }\n\n async deleteDefinition(id: string): Promise<void> {\n await this.client.request('DELETE', this.definitionPath(id))\n }\n\n startRun(definitionId: string): Promise<ResearchRun> {\n return this.client.request('POST', `${this.definitionPath(definitionId)}/runs`)\n }\n\n listRuns(query: ListResearchRunsQuery = {}): Promise<ResearchRunList> {\n return this.client.requestWithQuery('GET', `${ENRICHMENT_BASE_PATH}/research-runs`, query)\n }\n\n getRun(id: string): Promise<ResearchRun> {\n return this.client.request('GET', this.runPath(id))\n }\n\n async listResults(runId: string): Promise<ResearchResult[]> {\n const response = await this.client.request<{ data: ResearchResult[] }>(\n 'GET',\n `${this.runPath(runId)}/results`,\n )\n return response.data\n }\n\n cancelRun(id: string): Promise<ResearchRun> {\n return this.client.request('POST', `${this.runPath(id)}/cancel`)\n }\n}\n\nclass EnrichmentCatalogServiceImpl implements EnrichmentCatalogService {\n constructor(private readonly client: ProteosClient) {}\n\n enrichmentTypes(): Promise<EnrichmentTypesResponse> {\n return this.client.request('GET', `${ENRICHMENT_BASE_PATH}/enrichment-types`)\n }\n\n async providers(): Promise<EnrichmentProvider[]> {\n const response = await this.client.request<{ data: EnrichmentProvider[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/providers`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n ListEventsOptions,\n PlatformEvent,\n PublishEventRequest,\n RedriveResult,\n TailOptions,\n Topic,\n} from './types.js'\n\nconst EVENTS_BASE_PATH = '/events/v1'\n\n// A live tail is a long-poll; override the client's default request timeout so\n// it isn't aborted mid-stream. ~24h is well under the setTimeout overflow bound\n// and acts as a practical cap on a single tail session. Real teardown is the\n// caller's AbortSignal.\nconst TAIL_TIMEOUT_MS = 24 * 60 * 60 * 1000\n\n/**\n * Facade for event-service: a read/admin view over the Redis-Streams bus.\n * Everything is topic-centric, so the surface lives on `topics`.\n *\n * ```ts\n * const events = new EventsClient(client)\n * const topics = await events.topics.list()\n * const recent = await events.topics.events('record.contact.events', { limit: 50 })\n * for await (const msg of events.topics.tail('record.contact.events', { signal })) {\n * // append msg\n * }\n * ```\n */\nexport class EventsClient {\n readonly topics: TopicService\n\n constructor(client: ProteosClient) {\n this.topics = new TopicServiceImpl(client)\n }\n}\n\n/** Topic discovery, event reads + live tail, and admin actions. */\nexport interface TopicService {\n /** List the caller-org's topics. */\n list(): Promise<Topic[]>\n /** Read the most-recent events on a topic (newest first). */\n events(topic: string, options?: ListEventsOptions): Promise<PlatformEvent[]>\n /**\n * Live-tail new events on a topic until the AbortSignal fires. Yields each\n * event as it arrives (chunked NDJSON under the hood).\n */\n tail(topic: string, options?: TailOptions): AsyncGenerator<PlatformEvent, void, unknown>\n /** Publish a test event onto a topic — delivered to real consumers. */\n publish(topic: string, request: PublishEventRequest): Promise<PlatformEvent>\n /** Move a dead-letter stream back to its source topic for re-processing. */\n redrive(topic: string): Promise<RedriveResult>\n /** Empty a topic's stream (keeps consumer groups). Destructive. */\n purge(topic: string): Promise<void>\n}\n\nclass TopicServiceImpl implements TopicService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<Topic[]> {\n const response = await this.client.request<{ data: Topic[] }>(\n 'GET',\n `${EVENTS_BASE_PATH}/topics`,\n )\n return response.data ?? []\n }\n\n async events(topic: string, options: ListEventsOptions = {}): Promise<PlatformEvent[]> {\n const response = await this.client.requestWithQuery<\n { data: PlatformEvent[] },\n ListEventsOptions\n >('GET', `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/events`, options)\n return response.data ?? []\n }\n\n async *tail(\n topic: string,\n options: TailOptions = {},\n ): AsyncGenerator<PlatformEvent, void, unknown> {\n const path = `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/events?follow=true`\n let body: ReadableStream<Uint8Array> | null\n try {\n ;({ body } = await this.client.requestRaw('GET', path, undefined, {\n timeout: TAIL_TIMEOUT_MS,\n ...(options.signal ? { signal: options.signal } : {}),\n headers: { Accept: 'application/x-ndjson' },\n }))\n } catch (error) {\n if (isAbort(error)) return\n throw error\n }\n if (!body) return\n\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n let newlineIndex = buffer.indexOf('\\n')\n while (newlineIndex !== -1) {\n const line = buffer.slice(0, newlineIndex).trim()\n buffer = buffer.slice(newlineIndex + 1)\n const event = parseLine(line)\n if (event) yield event\n newlineIndex = buffer.indexOf('\\n')\n }\n }\n const remainder = parseLine(buffer.trim())\n if (remainder) yield remainder\n } catch (error) {\n if (!isAbort(error)) throw error\n } finally {\n reader.releaseLock()\n void body.cancel().catch(() => {})\n }\n }\n\n async publish(topic: string, request: PublishEventRequest): Promise<PlatformEvent> {\n return this.client.request<PlatformEvent>(\n 'POST',\n `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/events`,\n request,\n )\n }\n\n async redrive(topic: string): Promise<RedriveResult> {\n return this.client.request<RedriveResult>(\n 'POST',\n `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/redrive`,\n )\n }\n\n async purge(topic: string): Promise<void> {\n await this.client.request<void>(\n 'POST',\n `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/purge`,\n )\n }\n}\n\n/** True when an error is an AbortError (the tail's normal stop path). */\nfunction isAbort(error: unknown): boolean {\n return error instanceof DOMException && error.name === 'AbortError'\n}\n\n/**\n * Parses one NDJSON line into a PlatformEvent, returning null for a blank or\n * unparseable line. A single bad frame should be skipped, not tear down the\n * whole tail.\n */\nfunction parseLine(line: string): PlatformEvent | null {\n if (!line) return null\n try {\n return JSON.parse(line) as PlatformEvent\n } catch {\n return null\n }\n}\n\nexport type {\n ConsumerGroup,\n ListEventsOptions,\n PlatformEvent,\n PublishEventRequest,\n RedriveResult,\n TailOptions,\n Topic,\n TopicKind,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport { BATCH_INVOKE_TIMEOUT_MS, INVOKE_TIMEOUT_MS } from '../types/options.js'\nimport type { Action, InvokeActionResponse, ListActionsOptions } from './types.js'\n\nconst ACTIONS_BASE_PATH = '/functions/v1/actions'\n\n/**\n * Service for managing deployed actions (function-service).\n *\n * Actions are user-invokable operations. `params` and `returns` follow the\n * same `Attribute` schema language as entity attributes — the UI form\n * renderer consumes them directly.\n */\nexport interface ActionService {\n /**\n * Lists deployed actions as an async iterator.\n */\n list(options?: ListActionsOptions): PageIterator<Action, ListActionsOptions>\n\n /**\n * Fetches a single page of actions.\n */\n listPage(options?: ListActionsOptions): Promise<ListResult<Action>>\n\n /**\n * Gets a single action by slug. The returned `Action` carries the full\n * `params` and `returns` schemas, suitable for driving an invocation form.\n *\n * @throws {ProteosError} If the action is not found (404).\n */\n get(slug: string): Promise<Action>\n\n /**\n * Invokes a global-scoped action. Returns the unwrapped `result`\n * payload — the wire envelope `{ result }` is unwrapped by the SDK.\n *\n * @throws {ProteosError} On guest validation failures (400, `GUEST_ERROR`),\n * timeouts (504, `TIMEOUT`), traps (500, `TRAP`), or other failure kinds.\n */\n invokeGlobal(slug: string, params: Record<string, unknown>): Promise<unknown>\n\n /**\n * Invokes a PUBLIC (`is_public`) global action without authentication — no\n * Authorization header is sent. This is the only data path available to\n * components on a public page. The action runs server-side as its creator\n * (org + user injected via a machine token); non-public actions 404.\n *\n * @param orgId - Org id (public routes carry the org in the path — there is\n * no token to scope from)\n */\n invokePublic(orgId: string, slug: string, params: Record<string, unknown>): Promise<unknown>\n\n /**\n * Invokes an entity-scoped action against a specific record. Returns the\n * unwrapped `result` payload.\n */\n invokeEntity(\n entitySlug: string,\n recordId: string,\n slug: string,\n params: Record<string, unknown>,\n ): Promise<unknown>\n\n /**\n * Invokes an `entity_batch` action against a SET of records. The whole id\n * array reaches the action in ONE invocation, so the result is a single\n * aggregate payload, not one per record. `recordIds` must be non-empty;\n * the server dedupes it, preserving order. Returns the unwrapped `result`.\n */\n invokeBatch(\n entitySlug: string,\n slug: string,\n recordIds: string[],\n params: Record<string, unknown>,\n ): Promise<unknown>\n}\n\n/**\n * Implementation of ActionService.\n */\nexport class ActionServiceImpl implements ActionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListActionsOptions = {}): PageIterator<Action, ListActionsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListActionsOptions = {}): Promise<ListResult<Action>> {\n return this.client.requestWithQuery<ListResult<Action>>('GET', ACTIONS_BASE_PATH, options)\n }\n\n async get(slug: string): Promise<Action> {\n return this.client.request<Action>('GET', `${ACTIONS_BASE_PATH}/${slug}`)\n }\n\n async invokeGlobal(slug: string, params: Record<string, unknown>): Promise<unknown> {\n const response = await this.client.request<InvokeActionResponse>(\n 'POST',\n `${ACTIONS_BASE_PATH}/${slug}/invoke`,\n params,\n { timeout: INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n\n async invokePublic(\n orgId: string,\n slug: string,\n params: Record<string, unknown>,\n ): Promise<unknown> {\n const response = await this.client.request<InvokeActionResponse>(\n 'POST',\n `/functions/v1/public/orgs/${encodeURIComponent(orgId)}/actions/${encodeURIComponent(slug)}/invoke`,\n params,\n { skipAuth: true, timeout: INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n\n async invokeEntity(\n entitySlug: string,\n recordId: string,\n slug: string,\n params: Record<string, unknown>,\n ): Promise<unknown> {\n const response = await this.client.request<InvokeActionResponse>(\n 'POST',\n `/functions/v1/entities/${entitySlug}/records/${recordId}/actions/${slug}/invoke`,\n params,\n { timeout: INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n\n async invokeBatch(\n entitySlug: string,\n slug: string,\n recordIds: string[],\n params: Record<string, unknown>,\n ): Promise<unknown> {\n // The one invoke route whose body is an envelope rather than the params\n // object itself — an id array has nowhere to live in the path.\n const response = await this.client.request<InvokeActionResponse>(\n 'POST',\n `/functions/v1/entities/${entitySlug}/actions/${slug}/invoke`,\n { record_ids: recordIds, params },\n { timeout: BATCH_INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n}\n","import { z } from 'zod'\n\nimport { type Attribute, AttributeSchema } from '../meta/types.js'\nimport { type AuditFields, AuditFieldsSchema } from '../types/common.js'\n\n/**\n * Scope of an action. `entity`-scoped actions are invoked against a\n * specific record; `entity_batch` actions against a SET of records of one\n * entity (one invocation carrying every id, never one per record — they back\n * a list's toolbar buttons); `global` actions take no record context.\n */\nexport type ActionScope = 'entity' | 'entity_batch' | 'global'\n\nexport const ActionScopeSchema = z.enum(['entity', 'entity_batch', 'global'])\n\n/**\n * Deployable, user-invokable operation. Mirrors `functionsmodel.Action`\n * in the Go SDK. `params` and `returns` reuse the same `Attribute` schema\n * language as entity attributes — the renderer consumes them directly.\n */\nexport interface Action extends AuditFields {\n slug: string\n org_id: string\n module_slug: string\n scope: ActionScope\n /** Present only when `scope` is `entity` or `entity_batch`. */\n entity?: string\n name: string\n is_active: boolean\n /**\n * When true (global actions only), the action is invokable on the\n * unauthenticated public endpoint\n * `POST /functions/v1/public/orgs/{orgId}/actions/{slug}/invoke`.\n */\n is_public: boolean\n file_id: string\n params: Attribute[]\n returns: Attribute[]\n}\n\nexport const ActionSchema = AuditFieldsSchema.extend({\n slug: z.string(),\n org_id: z.string(),\n module_slug: z.string(),\n scope: ActionScopeSchema,\n entity: z.string().optional(),\n name: z.string(),\n is_active: z.boolean(),\n file_id: z.string(),\n params: z.array(AttributeSchema),\n returns: z.array(AttributeSchema),\n})\n\n/**\n * Options for listing actions.\n */\nexport interface ListActionsOptions {\n page?: number\n page_size?: number\n sort?: string\n scope?: ActionScope\n module_slug?: string\n entity?: string\n is_active?: boolean\n}\n\n/**\n * Wire envelope returned by the invoke endpoints. The SDK unwraps `result`\n * before returning to callers; this type is exported for completeness.\n */\nexport interface InvokeActionResponse {\n result: unknown\n}\n","import type { ProteosClient } from '../client.js'\nimport { type ActionService, ActionServiceImpl } from './actions.js'\n\n/**\n * Facade for the function-service (deployed actions + hooks).\n *\n * @example\n * ```ts\n * const client = new ProteosClient({ baseUrl, tokenProvider });\n * const functions = new FunctionsClient(client);\n * const action = await functions.actions.get('mark-as-signed');\n * const result = await functions.actions.invokeEntity(\n * 'document', recordId, 'mark-as-signed', { signatureType: 'ELECTRONIC' },\n * );\n * ```\n */\nexport class FunctionsClient {\n readonly actions: ActionService\n\n constructor(client: ProteosClient) {\n this.actions = new ActionServiceImpl(client)\n }\n}\n\n// Re-export service interfaces\nexport type { ActionService } from './actions.js'\n\n// Re-export types\nexport type { Action, ActionScope, InvokeActionResponse, ListActionsOptions } from './types.js'\n\n// Re-export Zod schemas\nexport { ActionSchema, ActionScopeSchema } from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { GetGraphOptions, KnowledgeGraph } from './types.js'\n\nconst GRAPH_BASE_PATH = '/knowledge/v1/graph'\n\n/**\n * Service for the whole-org knowledge graph (bulk read backing the radiant graph\n * view). One request returns lean nodes (with per-node label ids + degree),\n * links, the org label set and the total node count.\n */\nexport interface GraphService {\n /**\n * Reads the whole org graph in one payload. `options.label_ids` prunes to\n * nodes carrying ANY of the given labels (union) and `options.space_slugs` to\n * nodes in ANY of the given spaces; omitted returns everything.\n */\n get(options?: GetGraphOptions): Promise<KnowledgeGraph>\n}\n\n/**\n * Implementation of GraphService.\n */\nexport class GraphServiceImpl implements GraphService {\n constructor(private readonly client: ProteosClient) {}\n\n async get(options: GetGraphOptions = {}): Promise<KnowledgeGraph> {\n // The server reads label_ids as a single comma-separated query param (the\n // query binder takes only the first value of a repeated param), so the\n // union list is joined here rather than appended as repeated params.\n const query: { label_ids?: string; space_slugs?: string } = {}\n if (options.label_ids && options.label_ids.length > 0) {\n query.label_ids = options.label_ids.join(',')\n }\n if (options.space_slugs && options.space_slugs.length > 0) {\n query.space_slugs = options.space_slugs.join(',')\n }\n return this.client.requestWithQuery<KnowledgeGraph>('GET', GRAPH_BASE_PATH, query)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateLabelRequest,\n KnowledgeLabel,\n ListLabelsOptions,\n UpdateLabelRequest,\n} from './types.js'\n\nconst LABELS_BASE_PATH = '/knowledge/v1/labels'\n\n/**\n * Service for knowledge labels (categorization handles). To attach/detach a\n * label to a node, use the node service's label methods.\n */\nexport interface LabelService {\n /** Lists labels as an async iterator (pages are 0-indexed). */\n list(options?: ListLabelsOptions): PageIterator<KnowledgeLabel, ListLabelsOptions>\n\n /** Fetches a single page of labels. */\n listPage(options?: ListLabelsOptions): Promise<ListResult<KnowledgeLabel>>\n\n /** Gets a single label by id. */\n get(id: string): Promise<KnowledgeLabel>\n\n /** Creates a label. */\n create(request: CreateLabelRequest): Promise<KnowledgeLabel>\n\n /** Updates a label. */\n update(id: string, request: UpdateLabelRequest): Promise<KnowledgeLabel>\n\n /** Deletes a label; its node associations cascade. */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of LabelService.\n */\nexport class LabelServiceImpl implements LabelService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListLabelsOptions = {}): PageIterator<KnowledgeLabel, ListLabelsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListLabelsOptions = {}): Promise<ListResult<KnowledgeLabel>> {\n return this.client.requestWithQuery<ListResult<KnowledgeLabel>>(\n 'GET',\n LABELS_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<KnowledgeLabel> {\n return this.client.request<KnowledgeLabel>('GET', `${LABELS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateLabelRequest): Promise<KnowledgeLabel> {\n return this.client.request<KnowledgeLabel>('POST', LABELS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateLabelRequest): Promise<KnowledgeLabel> {\n return this.client.request<KnowledgeLabel>('PATCH', `${LABELS_BASE_PATH}/${id}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${LABELS_BASE_PATH}/${id}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateLinkRequest,\n KnowledgeLink,\n ListLinksOptions,\n UpdateLinkRequest,\n} from './types.js'\n\nconst LINKS_BASE_PATH = '/knowledge/v1/links'\n\n/**\n * Service for typed edges (links) between knowledge nodes.\n */\nexport interface LinkService {\n /** Lists links as an async iterator (pages are 0-indexed). */\n list(options?: ListLinksOptions): PageIterator<KnowledgeLink, ListLinksOptions>\n\n /** Fetches a single page of links. */\n listPage(options?: ListLinksOptions): Promise<ListResult<KnowledgeLink>>\n\n /** Gets a single link by id. */\n get(id: string): Promise<KnowledgeLink>\n\n /** Creates a typed edge between two nodes. */\n create(request: CreateLinkRequest): Promise<KnowledgeLink>\n\n /** Updates a link's type / description. */\n update(id: string, request: UpdateLinkRequest): Promise<KnowledgeLink>\n\n /** Deletes a link. */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of LinkService.\n */\nexport class LinkServiceImpl implements LinkService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListLinksOptions = {}): PageIterator<KnowledgeLink, ListLinksOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListLinksOptions = {}): Promise<ListResult<KnowledgeLink>> {\n return this.client.requestWithQuery<ListResult<KnowledgeLink>>('GET', LINKS_BASE_PATH, options)\n }\n\n async get(id: string): Promise<KnowledgeLink> {\n return this.client.request<KnowledgeLink>('GET', `${LINKS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateLinkRequest): Promise<KnowledgeLink> {\n return this.client.request<KnowledgeLink>('POST', LINKS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateLinkRequest): Promise<KnowledgeLink> {\n return this.client.request<KnowledgeLink>('PATCH', `${LINKS_BASE_PATH}/${id}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${LINKS_BASE_PATH}/${id}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n ContentResponse,\n CreateNodeRequest,\n EditContentRequest,\n EditContentResponse,\n KnowledgeLabel,\n KnowledgeNode,\n KnowledgeNodeLabel,\n KnowledgeNodeMetadata,\n KnowledgeNodeSearchResult,\n ListNodesOptions,\n NeighborsOptions,\n NodeNeighborhood,\n OutlineRequest,\n OutlineResponse,\n SearchContentRequest,\n SearchContentResponse,\n SearchNodesRequest,\n UpdateNodeRequest,\n WriteContentOptions,\n WriteContentResponse,\n} from './types.js'\n\nconst NODES_BASE_PATH = '/knowledge/v1/nodes'\n\n/**\n * Service for knowledge nodes and their content, search, graph neighbors and\n * labels. Reads return node metadata (no body) by default; the body is fetched\n * explicitly with {@link NodeService.getContent}.\n */\nexport interface NodeService {\n /** Lists node metadata as an async iterator (pages are 0-indexed). */\n list(options?: ListNodesOptions): PageIterator<KnowledgeNodeMetadata, ListNodesOptions>\n\n /** Fetches a single page of node metadata. */\n listPage(options?: ListNodesOptions): Promise<ListResult<KnowledgeNodeMetadata>>\n\n /** Gets a node's metadata (body excluded). */\n get(id: string): Promise<KnowledgeNodeMetadata>\n\n /** Creates a node, optionally connecting it to labels/links in one call. */\n create(request: CreateNodeRequest): Promise<KnowledgeNode>\n\n /** Updates a node's metadata (title / status / summary). */\n update(id: string, request: UpdateNodeRequest): Promise<KnowledgeNodeMetadata>\n\n /** Hard-deletes a node; its links and label associations cascade. */\n delete(id: string): Promise<void>\n\n /**\n * Hybrid retrieval. Only `keyword` is wired today; `semantic`/`hybrid` throw a\n * 501 ProteosError until embeddings land.\n */\n search(request: SearchNodesRequest): Promise<ListResult<KnowledgeNodeSearchResult>>\n\n /** Depth-bounded graph walk from a node. */\n neighbors(id: string, options?: NeighborsOptions): Promise<NodeNeighborhood>\n\n /** Reads a node's raw content body plus its line count. */\n getContent(id: string): Promise<ContentResponse>\n\n /** Overwrites a node's content body. Rejects derived (file/url) nodes. */\n writeContent(\n id: string,\n content: string,\n options?: WriteContentOptions,\n ): Promise<WriteContentResponse>\n\n /** Applies a surgical anchored edit to a node's content body. */\n editContent(id: string, request: EditContentRequest): Promise<EditContentResponse>\n\n /**\n * Maps each requested node's body by its markdown heading structure (one or\n * several nodes) — skim a large node, then read just a section's line range.\n */\n getOutline(request: OutlineRequest): Promise<OutlineResponse>\n\n /** Greps each requested node's body for a pattern, with matching lines + context. */\n searchContent(request: SearchContentRequest): Promise<SearchContentResponse>\n\n /** Lists the labels attached to a node. */\n listLabels(id: string): Promise<KnowledgeLabel[]>\n\n /** Attaches an existing label to a node. */\n attachLabel(id: string, labelId: string): Promise<KnowledgeNodeLabel>\n\n /** Detaches a label from a node. */\n detachLabel(id: string, labelId: string): Promise<void>\n}\n\n/**\n * Implementation of NodeService.\n */\nexport class NodeServiceImpl implements NodeService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListNodesOptions = {}): PageIterator<KnowledgeNodeMetadata, ListNodesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListNodesOptions = {}): Promise<ListResult<KnowledgeNodeMetadata>> {\n // The server reads label_ids as a single comma-separated query param (the query\n // binder takes only the first value of a repeated param), so the union list is\n // joined here rather than appended as repeated params (mirrors GraphService.get).\n const { label_ids, space_slugs, ...rest } = options\n const query: Record<string, unknown> = { ...rest }\n if (label_ids && label_ids.length > 0) {\n query.label_ids = label_ids.join(',')\n }\n if (space_slugs && space_slugs.length > 0) {\n query.space_slugs = space_slugs.join(',')\n }\n return this.client.requestWithQuery<ListResult<KnowledgeNodeMetadata>>(\n 'GET',\n NODES_BASE_PATH,\n query,\n )\n }\n\n async get(id: string): Promise<KnowledgeNodeMetadata> {\n return this.client.request<KnowledgeNodeMetadata>('GET', `${NODES_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateNodeRequest): Promise<KnowledgeNode> {\n return this.client.request<KnowledgeNode>('POST', NODES_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateNodeRequest): Promise<KnowledgeNodeMetadata> {\n return this.client.request<KnowledgeNodeMetadata>('PATCH', `${NODES_BASE_PATH}/${id}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${NODES_BASE_PATH}/${id}`)\n }\n\n async search(request: SearchNodesRequest): Promise<ListResult<KnowledgeNodeSearchResult>> {\n return this.client.request<ListResult<KnowledgeNodeSearchResult>>(\n 'POST',\n `${NODES_BASE_PATH}/actions/search`,\n request,\n )\n }\n\n async neighbors(id: string, options: NeighborsOptions = {}): Promise<NodeNeighborhood> {\n return this.client.requestWithQuery<NodeNeighborhood>(\n 'GET',\n `${NODES_BASE_PATH}/${id}/neighbors`,\n options,\n )\n }\n\n async getContent(id: string): Promise<ContentResponse> {\n return this.client.request<ContentResponse>('GET', `${NODES_BASE_PATH}/${id}/content`)\n }\n\n async writeContent(\n id: string,\n content: string,\n options: WriteContentOptions = {},\n ): Promise<WriteContentResponse> {\n return this.client.request<WriteContentResponse>('PUT', `${NODES_BASE_PATH}/${id}/content`, {\n content,\n ...options,\n })\n }\n\n async editContent(id: string, request: EditContentRequest): Promise<EditContentResponse> {\n return this.client.request<EditContentResponse>(\n 'POST',\n `${NODES_BASE_PATH}/${id}/content/actions/edit`,\n request,\n )\n }\n\n async getOutline(request: OutlineRequest): Promise<OutlineResponse> {\n return this.client.request<OutlineResponse>(\n 'POST',\n `${NODES_BASE_PATH}/content/actions/outline`,\n request,\n )\n }\n\n async searchContent(request: SearchContentRequest): Promise<SearchContentResponse> {\n return this.client.request<SearchContentResponse>(\n 'POST',\n `${NODES_BASE_PATH}/content/actions/search`,\n request,\n )\n }\n\n async listLabels(id: string): Promise<KnowledgeLabel[]> {\n const result = await this.client.request<{ data: KnowledgeLabel[] }>(\n 'GET',\n `${NODES_BASE_PATH}/${id}/labels`,\n )\n return result.data\n }\n\n async attachLabel(id: string, labelId: string): Promise<KnowledgeNodeLabel> {\n return this.client.request<KnowledgeNodeLabel>('POST', `${NODES_BASE_PATH}/${id}/labels`, {\n label_id: labelId,\n })\n }\n\n async detachLabel(id: string, labelId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${NODES_BASE_PATH}/${id}/labels/${labelId}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateRecordLinkRequest,\n KnowledgeRecordLink,\n ListRecordLinksOptions,\n} from './types.js'\n\nconst RECORD_LINKS_BASE_PATH = '/knowledge/v1/record-links'\n\n/**\n * Service for node→record edges: links from a knowledge node to a business\n * record (data-service, identified by `entity_slug` + `record_id`). Immutable —\n * create / delete only, no update. Filter by `node_id` (a node's records) or by\n * `entity_slug` + `record_id` (a record's nodes).\n */\nexport interface RecordLinkService {\n /** Lists record links as an async iterator (pages are 0-indexed). */\n list(options?: ListRecordLinksOptions): PageIterator<KnowledgeRecordLink, ListRecordLinksOptions>\n\n /** Fetches a single page of record links. */\n listPage(options?: ListRecordLinksOptions): Promise<ListResult<KnowledgeRecordLink>>\n\n /** Gets a single record link by id. */\n get(id: string): Promise<KnowledgeRecordLink>\n\n /** Links a node to a business record. */\n create(request: CreateRecordLinkRequest): Promise<KnowledgeRecordLink>\n\n /** Removes a record link. */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of RecordLinkService.\n */\nexport class RecordLinkServiceImpl implements RecordLinkService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListRecordLinksOptions = {},\n ): PageIterator<KnowledgeRecordLink, ListRecordLinksOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListRecordLinksOptions = {}): Promise<ListResult<KnowledgeRecordLink>> {\n return this.client.requestWithQuery<ListResult<KnowledgeRecordLink>>(\n 'GET',\n RECORD_LINKS_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<KnowledgeRecordLink> {\n return this.client.request<KnowledgeRecordLink>('GET', `${RECORD_LINKS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateRecordLinkRequest): Promise<KnowledgeRecordLink> {\n return this.client.request<KnowledgeRecordLink>('POST', RECORD_LINKS_BASE_PATH, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${RECORD_LINKS_BASE_PATH}/${id}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateSpaceRequest,\n KnowledgeSpace,\n ListSpacesOptions,\n UpdateSpaceRequest,\n} from './types.js'\n\nconst SPACES_BASE_PATH = '/knowledge/v1/spaces'\n\n/**\n * Service for knowledge spaces — the containers nodes live in.\n *\n * Every method is keyed by SLUG rather than id: a space's slug is half its\n * primary key and is immutable, so there is no second identifier. To file a node\n * into a space, set `space_slug` on the node (see `NodeService`).\n *\n * Granting access to a space is NOT done here — it goes through the shared\n * `auth.shares` API, which routes `knowledge-spaces` to knowledge-service:\n *\n * ```ts\n * await auth.shares.share('knowledge-spaces', 'engineering', { type: 'team', id: 'platform' }, 'read')\n * ```\n */\nexport interface SpaceService {\n /** Lists spaces as an async iterator (pages are 0-indexed). */\n list(options?: ListSpacesOptions): PageIterator<KnowledgeSpace, ListSpacesOptions>\n\n /** Fetches a single page of spaces. */\n listPage(options?: ListSpacesOptions): Promise<ListResult<KnowledgeSpace>>\n\n /** Gets a single space by slug. */\n get(slug: string): Promise<KnowledgeSpace>\n\n /** Creates a space. The slug is permanent. */\n create(request: CreateSpaceRequest): Promise<KnowledgeSpace>\n\n /**\n * Returns the calling user's own personal space, creating it on first use.\n * Takes no arguments: whose space it is comes from the token. A personal\n * space is created holding grants for its owner only.\n */\n ensurePersonal(): Promise<KnowledgeSpace>\n\n /** Updates a space's presentation. The slug cannot be changed. */\n update(slug: string, request: UpdateSpaceRequest): Promise<KnowledgeSpace>\n\n /**\n * Deletes a space and its access grants.\n *\n * Refused with 409 `knowledge_space_not_empty` while any node still lives in\n * it — deleting a space never deletes the knowledge inside it, and never\n * silently makes it org-visible by unfiling it. Move or delete the nodes first.\n */\n delete(slug: string): Promise<void>\n}\n\n/**\n * Implementation of SpaceService.\n */\nexport class SpaceServiceImpl implements SpaceService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListSpacesOptions = {}): PageIterator<KnowledgeSpace, ListSpacesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListSpacesOptions = {}): Promise<ListResult<KnowledgeSpace>> {\n return this.client.requestWithQuery<ListResult<KnowledgeSpace>>(\n 'GET',\n SPACES_BASE_PATH,\n options,\n )\n }\n\n async get(slug: string): Promise<KnowledgeSpace> {\n return this.client.request<KnowledgeSpace>('GET', `${SPACES_BASE_PATH}/${slug}`)\n }\n\n async create(request: CreateSpaceRequest): Promise<KnowledgeSpace> {\n return this.client.request<KnowledgeSpace>('POST', SPACES_BASE_PATH, request)\n }\n\n async ensurePersonal(): Promise<KnowledgeSpace> {\n return this.client.request<KnowledgeSpace>(\n 'POST',\n `${SPACES_BASE_PATH}/actions/ensure-personal`,\n )\n }\n\n async update(slug: string, request: UpdateSpaceRequest): Promise<KnowledgeSpace> {\n return this.client.request<KnowledgeSpace>('PATCH', `${SPACES_BASE_PATH}/${slug}`, request)\n }\n\n async delete(slug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${SPACES_BASE_PATH}/${slug}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateWhiteboardTemplateRequest,\n ListWhiteboardTemplatesOptions,\n UpdateWhiteboardTemplateRequest,\n WhiteboardTemplate,\n WhiteboardTemplateMetadata,\n} from './types.js'\n\nconst WHITEBOARD_TEMPLATES_BASE_PATH = '/knowledge/v1/whiteboard-templates'\n\n/**\n * Service for whiteboard templates: reusable pieces of a whiteboard, shared\n * with the whole org. Everyone who may write knowledge adds templates; only a\n * template's creator or an admin changes or deletes it. No versions: an\n * update overwrites.\n */\nexport interface WhiteboardTemplateService {\n /** Lists templates (metadata only) as an async iterator. */\n list(\n options?: ListWhiteboardTemplatesOptions,\n ): PageIterator<WhiteboardTemplateMetadata, ListWhiteboardTemplatesOptions>\n\n /** Fetches a single page of templates (metadata only). */\n listPage(\n options?: ListWhiteboardTemplatesOptions,\n ): Promise<ListResult<WhiteboardTemplateMetadata>>\n\n /** Gets a template with its elements. */\n get(id: string): Promise<WhiteboardTemplate>\n\n /** Adds a template. */\n create(request: CreateWhiteboardTemplateRequest): Promise<WhiteboardTemplate>\n\n /** Updates a template (its creator or an admin). */\n update(id: string, request: UpdateWhiteboardTemplateRequest): Promise<WhiteboardTemplate>\n\n /** Deletes a template (its creator or an admin). */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of WhiteboardTemplateService.\n */\nexport class WhiteboardTemplateServiceImpl implements WhiteboardTemplateService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListWhiteboardTemplatesOptions = {},\n ): PageIterator<WhiteboardTemplateMetadata, ListWhiteboardTemplatesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(\n options: ListWhiteboardTemplatesOptions = {},\n ): Promise<ListResult<WhiteboardTemplateMetadata>> {\n return this.client.requestWithQuery<ListResult<WhiteboardTemplateMetadata>>(\n 'GET',\n WHITEBOARD_TEMPLATES_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<WhiteboardTemplate> {\n return this.client.request<WhiteboardTemplate>('GET', `${WHITEBOARD_TEMPLATES_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateWhiteboardTemplateRequest): Promise<WhiteboardTemplate> {\n return this.client.request<WhiteboardTemplate>('POST', WHITEBOARD_TEMPLATES_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateWhiteboardTemplateRequest): Promise<WhiteboardTemplate> {\n return this.client.request<WhiteboardTemplate>(\n 'PATCH',\n `${WHITEBOARD_TEMPLATES_BASE_PATH}/${id}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${WHITEBOARD_TEMPLATES_BASE_PATH}/${id}`)\n }\n}\n","import { z } from 'zod'\nimport {\n type AuditFields,\n AuditFieldsSchema,\n type ListOptions,\n type UserRef,\n UserRefSchema,\n} from '../types/common.js'\n\n// ============================================================================\n// Enums\n// ============================================================================\n\n/** A node's kind. `markdown` is authored; `file`/`url` bodies are derived. */\nexport type NodeType = 'markdown' | 'file' | 'url' | 'whiteboard'\n\n/** Lifecycle state of a node. */\nexport type NodeStatus = 'draft' | 'published' | 'archived'\n\n/** Typed edge kinds in the knowledge graph. */\nexport type LinkType =\n | 'references'\n | 'relates_to'\n | 'depends_on'\n | 'part_of'\n | 'derived_from'\n | 'contradicts'\n | 'supports'\n | 'duplicates'\n | 'superseded_by'\n\n/**\n * Retrieval mode for `nodes.search`. Only `keyword` is wired today; `semantic`\n * and `hybrid` are reserved (the server returns 501 until embeddings land).\n */\nexport type MatchMode = 'hybrid' | 'semantic' | 'keyword'\n\n/** Traversal direction for `nodes.neighbors`. */\nexport type NeighborDirection = 'out' | 'in' | 'both'\n\n// ============================================================================\n// Entity Types\n// ============================================================================\n\n/**\n * A node's metadata — everything except the (potentially huge) `content` body\n * and the derived embedding vector. This is what list / get / search / neighbors\n * return by default.\n */\nexport interface KnowledgeNodeMetadata extends AuditFields {\n id: string\n org_id: string\n title: string\n type: NodeType\n status: NodeStatus\n /** Embedding provenance (null until ingestion runs). */\n embedding_model?: string | null\n embedded_at?: string | null\n /**\n * The space this node lives in, or null when UNASSIGNED. An unassigned node\n * is visible to anyone holding knowledge-nodes:read — the behaviour every\n * node had before spaces existed.\n */\n space_slug?: string | null\n /** Source pointer for `file` nodes (storage-service file id). */\n file_id?: string | null\n /** Source pointer for `url` nodes. */\n url?: string | null\n summary?: string | null\n /**\n * Temporal validity window (RFC3339), decoupled from `created_at`. `valid_from`\n * is when the asserted fact starts being true, `valid_until` when it stops.\n * Either null = unbounded on that side (both null = always valid). Half-open\n * `[valid_from, valid_until)`.\n */\n valid_from?: string | null\n valid_until?: string | null\n}\n\n/** A full node: its metadata plus the markdown `content` body. */\nexport interface KnowledgeNode extends KnowledgeNodeMetadata {\n content: string\n}\n\n/** A node returned by search, with its relevance `score`. */\nexport interface KnowledgeNodeSearchResult extends KnowledgeNodeMetadata {\n score: number\n}\n\n/** A typed, directed edge between two nodes. */\nexport interface KnowledgeLink extends AuditFields {\n id: string\n org_id: string\n from_id: string\n to_id: string\n type: LinkType\n description?: string | null\n}\n\n/**\n * A directed edge from a knowledge node to a business record (data-service,\n * identified by `entity_slug` + `record_id`). Immutable once created — only\n * `created_*` audit fields, no update path — so it does NOT extend AuditFields\n * (which carries `updated_*`).\n */\nexport interface KnowledgeRecordLink {\n id: string\n org_id: string\n node_id: string\n entity_slug: string\n record_id: string\n created_at: string\n created_by: UserRef\n}\n\n/** A categorization handle. `slug` is unique within an org. */\nexport interface KnowledgeLabel extends AuditFields {\n id: string\n org_id: string\n name: string\n slug: string\n description?: string | null\n color?: string | null\n icon?: string | null\n}\n\n/** The node↔label association row. */\nexport interface KnowledgeNodeLabel {\n org_id: string\n node_id: string\n label_id: string\n created_at: string\n created_by: UserRef\n}\n\n// ============================================================================\n// Node requests\n// ============================================================================\n\n/** A typed edge from a node being created to an existing node (create-and-connect). */\nexport interface InlineLinkRequest {\n to_id: string\n type: LinkType\n description?: string\n}\n\n/**\n * Create a node, optionally connecting it to the graph in one call. `label_ids`\n * attaches existing labels; `links` creates edges FROM the new node. Both are\n * applied atomically with the node insert.\n */\nexport interface CreateNodeRequest {\n title: string\n type: NodeType\n status: NodeStatus\n content?: string\n /** File the node into a space. Omitted = unassigned. */\n space_slug?: string\n file_id?: string\n url?: string\n summary?: string\n /** Validity window (RFC3339). Omitted = unbounded (NULL). */\n valid_from?: string\n valid_until?: string\n label_ids?: string[]\n links?: InlineLinkRequest[]\n}\n\n/** Partial metadata update. Content is updated via the content methods, not here. */\nexport interface UpdateNodeRequest {\n title?: string\n status?: NodeStatus\n summary?: string\n /**\n * Validity window (RFC3339), tri-state: omit the key to leave unchanged, pass\n * `null` to clear it back to unbounded (re-open validity), or a timestamp to\n * set it. Setting `valid_until` to an instant ends a fact's validity.\n */\n valid_from?: string | null\n valid_until?: string | null\n /**\n * Move the node between spaces, tri-state like the validity window: omit to\n * leave it where it is, pass `null` to move it back to unassigned, or a slug\n * to file it into that space.\n */\n space_slug?: string | null\n}\n\n/** Filters for listing nodes. */\nexport interface ListNodesOptions extends ListOptions {\n type?: NodeType\n status?: NodeStatus\n title?: string\n 'title[contains]'?: string\n /** Keep only nodes carrying ANY of these labels (union). */\n label_ids?: string[]\n /**\n * Keep only nodes living in ANY of these spaces (union). Use\n * `UNASSIGNED_SPACE_SLUG` to ask for nodes belonging to no space.\n */\n space_slugs?: string[]\n /** Created on/after this RFC3339 timestamp (inclusive). */\n created_after?: string\n /** Created on/before this RFC3339 timestamp (inclusive). */\n created_before?: string\n /** Updated on/after this RFC3339 timestamp (inclusive). */\n updated_after?: string\n /** Updated on/before this RFC3339 timestamp (inclusive). */\n updated_before?: string\n /** Validity boundary range filters (RFC3339) — filter on where a node's window start/end falls. */\n valid_from_after?: string\n valid_from_before?: string\n valid_until_after?: string\n valid_until_before?: string\n /**\n * Point-in-time validity filter (RFC3339): keep only nodes valid AT this\n * instant (null-aware, half-open). Set `is_valid: false` to invert it (nodes\n * INVALID at the instant). `is_valid` defaults to true.\n */\n is_valid_at?: string\n is_valid?: boolean\n}\n\n// ── Content sub-resource ────────────────────────────────────────────────\n\n/** A node's raw body plus its line count. */\nexport interface ContentResponse {\n id: string\n content: string\n lines_total: number\n /** Hex SHA-256 of the body — the version token to pass back as\n * `expected_content_hash` when writing, so a newer change is not overwritten. */\n content_hash: string\n}\n\n/**\n * Options for `nodes.writeContent`. `expected_content_hash` makes the write\n * conditional: the server refuses it with 409 `content_conflict` when the\n * stored body no longer hashes to it (someone else wrote it since).\n */\nexport interface WriteContentOptions {\n expected_content_hash?: string\n}\n\nexport interface WriteContentResponse {\n id: string\n lines_total: number\n /** Hash of the body just written. */\n content_hash: string\n}\n\n/** A surgical anchored edit (mirrors Claude Code's `Edit`). */\nexport interface EditContentRequest {\n old_string: string\n new_string: string\n replace_all?: boolean\n}\n\nexport interface EditContentResponse {\n id: string\n replacements: number\n lines_total: number\n}\n\n// ── Within-node navigation: outline & grep ─────────────────────────────────\n\n/** One markdown heading in a node's outline, with the line range of its section. */\nexport interface OutlineHeading {\n level: number\n title: string\n line_start: number\n line_end: number\n}\n\n/** One node's structural map. `headings` is empty for a body with no headings. */\nexport interface NodeOutline {\n node_id: string\n title: string\n lines_total: number\n headings: OutlineHeading[]\n}\n\n/** Outline one or several nodes' bodies in a single call. */\nexport interface OutlineRequest {\n node_ids: string[]\n}\n\nexport interface OutlineResponse {\n results: NodeOutline[]\n}\n\n/** One grep hit: the matching line, the snippet's line range, and the cat -n snippet. */\nexport interface ContentMatch {\n line: number\n line_start: number\n line_end: number\n snippet: string\n}\n\n/** One node's grep result. `match_count` is the true total; `matches` is capped. */\nexport interface NodeContentMatches {\n node_id: string\n title: string\n lines_total: number\n match_count: number\n truncated: boolean\n matches: ContentMatch[]\n}\n\n/** Grep one or several node bodies. Substring by default; set `is_regex` for a regex. */\nexport interface SearchContentRequest {\n node_ids: string[]\n pattern: string\n is_regex?: boolean\n is_case_sensitive?: boolean\n context_lines?: number\n max_matches_per_node?: number\n}\n\nexport interface SearchContentResponse {\n results: NodeContentMatches[]\n}\n\n// ── Search ───────────────────────────────────────────────────────────────\n\n/** Hybrid retrieval request. `match_mode` defaults to `keyword`. */\nexport interface SearchNodesRequest {\n query: string\n match_mode?: MatchMode\n type?: NodeType\n status?: NodeStatus\n /** Match nodes carrying ANY of these labels. */\n label_ids?: string[]\n /**\n * Match nodes living in ANY of these spaces (union). Use\n * `UNASSIGNED_SPACE_SLUG` for nodes belonging to no space.\n */\n space_slugs?: string[]\n /** Match nodes connected (either direction) to this node. */\n linked_to_id?: string\n /**\n * Date-range filters (RFC3339). These only narrow the candidate set; results\n * stay relevance-ordered, so a date filter never reorders hits.\n */\n created_after?: string\n created_before?: string\n updated_after?: string\n updated_before?: string\n /**\n * Point-in-time validity filter (RFC3339): restrict hits to nodes valid AT\n * this instant (or INVALID when `is_valid` is false; defaults to true). Narrows\n * the candidate set only — ordering stays relevance-based.\n */\n is_valid_at?: string\n is_valid?: boolean\n page?: number\n page_size?: number\n}\n\n// ── Neighbors ──────────────────────────────────────────────────────────────\n\n/** Options for a neighbors graph walk. */\nexport interface NeighborsOptions {\n direction?: NeighborDirection\n /** Comma-separated link types to follow (e.g. \"part_of,depends_on\"). */\n link_types?: string\n depth?: number\n}\n\nexport interface NeighborNode {\n id: string\n title: string\n type: NodeType\n status: NodeStatus\n distance: number\n}\n\nexport interface NeighborEdge {\n id: string\n from_id: string\n to_id: string\n type: LinkType\n}\n\nexport interface NodeNeighborhood {\n nodes: NeighborNode[]\n edges: NeighborEdge[]\n}\n\n// ============================================================================\n// Graph (whole-org bulk read for the radiant graph view)\n// ============================================================================\n\n/**\n * A lean node in the whole-graph payload — only what the graph renderer needs.\n * `label_ids` are ordered by attachment time, so `label_ids[0]` is the \"first\"\n * label (the one the UI colours the node by). `degree` is the in+out link count\n * within the returned graph (drives node size).\n */\nexport interface KnowledgeGraphNode {\n id: string\n title: string\n type: NodeType\n status: NodeStatus\n label_ids: string[]\n /** The node's space, or null when unassigned. */\n space_slug?: string | null\n degree: number\n}\n\n/** A lean directed edge in the whole-graph payload. */\nexport interface KnowledgeGraphLink {\n id: string\n from_id: string\n to_id: string\n type: LinkType\n}\n\n/**\n * The whole org graph in one payload: lean nodes + links, the full org label set\n * (sent once — colours every node and powers the filter bar even when the graph\n * is pruned), and `total`, the unfiltered org node count (lets the client decide\n * whether to load the whole graph or switch to progressive/LOD loading).\n */\nexport interface KnowledgeGraph {\n nodes: KnowledgeGraphNode[]\n links: KnowledgeGraphLink[]\n labels: KnowledgeLabel[]\n /**\n * The full org space set, sent once for the same reason as `labels`: the\n * client renders the space navigator and filters by space without a second\n * request, even when the graph is pruned to one space.\n */\n spaces: KnowledgeSpace[]\n total: number\n}\n\n/**\n * Options for `getGraph`. `label_ids` prunes the graph to nodes carrying ANY of\n * the given labels (union); omitted/empty returns the whole org graph.\n */\nexport interface GetGraphOptions {\n label_ids?: string[]\n /** Prune to nodes in ANY of these spaces (union). */\n space_slugs?: string[]\n}\n\n// ============================================================================\n// Link requests\n// ============================================================================\n\nexport interface CreateLinkRequest {\n from_id: string\n to_id: string\n type: LinkType\n description?: string\n}\n\nexport interface UpdateLinkRequest {\n type?: LinkType\n description?: string\n}\n\nexport interface ListLinksOptions extends ListOptions {\n from_id?: string\n to_id?: string\n type?: LinkType\n /** Created on/after this RFC3339 timestamp (inclusive). */\n created_after?: string\n /** Created on/before this RFC3339 timestamp (inclusive). */\n created_before?: string\n /** Updated on/after this RFC3339 timestamp (inclusive). */\n updated_after?: string\n /** Updated on/before this RFC3339 timestamp (inclusive). */\n updated_before?: string\n}\n\n// ============================================================================\n// Record-link requests\n// ============================================================================\n\nexport interface CreateRecordLinkRequest {\n node_id: string\n entity_slug: string\n record_id: string\n}\n\nexport interface ListRecordLinksOptions extends ListOptions {\n node_id?: string\n entity_slug?: string\n record_id?: string\n}\n\n// ============================================================================\n// Spaces\n// ============================================================================\n\n/**\n * A knowledge space: the container a node lives in. A node belongs to at most\n * one space; a node with no space is unassigned.\n *\n * A space is NOT a label. Labels are many-per-node, overlapping, non-security\n * tags; a space is the single place a node lives, and it is what instance-level\n * access is evaluated against.\n *\n * Keyed by `slug`, which is IMMUTABLE — it is half the primary key, node rows\n * reference it and access grants name it, so renaming would orphan both. There\n * is no id.\n */\nexport interface KnowledgeSpace extends AuditFields {\n org_id: string\n slug: string\n name: string\n description?: string | null\n color?: string | null\n icon?: string | null\n /**\n * Who the space is for: `shared` (an ordinary org space) or `personal` (one\n * person's own space, where their assistants keep memory notes). Set at\n * creation and never changed.\n */\n scope: SpaceScope\n /**\n * The person a personal space belongs to; absent on a shared space. It says\n * whose space this is — access still comes only from the space's grants.\n */\n owner_user_id?: string | null\n}\n\nexport type SpaceScope = 'shared' | 'personal'\n\n/**\n * The reserved filter value meaning \"nodes that belong to no space at all\".\n * Deliberately not a legal slug (slugs are kebab-case), so it can never collide\n * with a space an org creates.\n */\nexport const UNASSIGNED_SPACE_SLUG = '__unassigned__'\n\nexport interface CreateSpaceRequest {\n /** Permanent — it is half the primary key and cannot be changed later. */\n slug: string\n name: string\n description?: string\n color?: string\n icon?: string\n}\n\n/** Partial update. `slug` is absent because it is immutable. */\nexport interface UpdateSpaceRequest {\n name?: string\n description?: string\n color?: string\n icon?: string\n}\n\nexport interface ListSpacesOptions extends ListOptions {\n slug?: string\n name?: string\n 'name[contains]'?: string\n}\n\n// ============================================================================\n// Label requests\n// ============================================================================\n\nexport interface CreateLabelRequest {\n name: string\n slug: string\n description?: string\n color?: string\n icon?: string\n}\n\nexport interface UpdateLabelRequest {\n name?: string\n description?: string\n color?: string\n icon?: string\n}\n\nexport interface ListLabelsOptions extends ListOptions {\n slug?: string\n name?: string\n 'name[contains]'?: string\n}\n\n// ============================================================================\n// Whiteboard templates\n// ============================================================================\n\n/**\n * A reusable piece of a whiteboard (a layout, a card, a notation shape),\n * shared with the whole org. Lists return this; `get` adds the elements.\n */\nexport interface WhiteboardTemplateMetadata extends AuditFields {\n id: string\n org_id: string\n name: string\n description?: string | null\n /** Groups templates in the Library sidebar, e.g. \"BPMN\". */\n category?: string | null\n element_count: number\n}\n\n/** A whiteboard template with its Excalidraw elements (unchecked JSON). */\nexport interface WhiteboardTemplate extends WhiteboardTemplateMetadata {\n elements: unknown[]\n}\n\nexport interface CreateWhiteboardTemplateRequest {\n name: string\n description?: string\n category?: string\n /** Excalidraw elements: at most 1,000, 2 MB, board element types only. */\n elements: unknown[]\n}\n\n/** Only the fields present change; `elements` replaces the elements whole. */\nexport interface UpdateWhiteboardTemplateRequest {\n name?: string\n description?: string\n category?: string\n elements?: unknown[]\n}\n\nexport interface ListWhiteboardTemplatesOptions extends ListOptions {\n category?: string\n 'name[contains]'?: string\n}\n\n// ============================================================================\n// Zod schemas (optional runtime validation for consumers who want it)\n// ============================================================================\n\nexport const KnowledgeNodeMetadataSchema = z\n .object({\n id: z.string(),\n org_id: z.string(),\n title: z.string(),\n type: z.enum(['markdown', 'file', 'url', 'whiteboard']),\n status: z.enum(['draft', 'published', 'archived']),\n embedding_model: z.string().nullish(),\n embedded_at: z.string().nullish(),\n file_id: z.string().nullish(),\n url: z.string().nullish(),\n summary: z.string().nullish(),\n valid_from: z.string().nullish(),\n valid_until: z.string().nullish(),\n })\n .merge(AuditFieldsSchema)\n\nexport const KnowledgeNodeSchema = KnowledgeNodeMetadataSchema.extend({\n content: z.string(),\n})\n\nexport const KnowledgeNodeSearchResultSchema = KnowledgeNodeMetadataSchema.extend({\n score: z.number(),\n})\n\nexport const KnowledgeLinkSchema = z\n .object({\n id: z.string(),\n org_id: z.string(),\n from_id: z.string(),\n to_id: z.string(),\n type: z.enum([\n 'references',\n 'relates_to',\n 'depends_on',\n 'part_of',\n 'derived_from',\n 'contradicts',\n 'supports',\n 'duplicates',\n 'superseded_by',\n ]),\n description: z.string().nullish(),\n })\n .merge(AuditFieldsSchema)\n\nexport const KnowledgeRecordLinkSchema = z.object({\n id: z.string(),\n org_id: z.string(),\n node_id: z.string(),\n entity_slug: z.string(),\n record_id: z.string(),\n created_at: z.string(),\n created_by: UserRefSchema,\n})\n\nexport const KnowledgeLabelSchema = z\n .object({\n id: z.string(),\n org_id: z.string(),\n name: z.string(),\n slug: z.string(),\n description: z.string().nullish(),\n color: z.string().nullish(),\n icon: z.string().nullish(),\n })\n .merge(AuditFieldsSchema)\n\nexport const KnowledgeNodeLabelSchema = z.object({\n org_id: z.string(),\n node_id: z.string(),\n label_id: z.string(),\n created_at: z.string(),\n created_by: UserRefSchema,\n})\n\nexport const NodeNeighborhoodSchema = z.object({\n nodes: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n type: z.enum(['markdown', 'file', 'url', 'whiteboard']),\n status: z.enum(['draft', 'published', 'archived']),\n distance: z.number(),\n }),\n ),\n edges: z.array(\n z.object({\n id: z.string(),\n from_id: z.string(),\n to_id: z.string(),\n type: z.string(),\n }),\n ),\n})\n","import type { ProteosClient } from '../client.js'\nimport { type GraphService, GraphServiceImpl } from './graph.js'\nimport { type LabelService, LabelServiceImpl } from './labels.js'\nimport { type LinkService, LinkServiceImpl } from './links.js'\nimport { type NodeService, NodeServiceImpl } from './nodes.js'\nimport { type RecordLinkService, RecordLinkServiceImpl } from './record-links.js'\nimport { type SpaceService, SpaceServiceImpl } from './spaces.js'\nimport {\n type WhiteboardTemplateService,\n WhiteboardTemplateServiceImpl,\n} from './whiteboard-templates.js'\n\n/**\n * Facade for the knowledge-service (graph-native knowledge base: nodes, typed\n * links, labels, content sub-resource, keyword search and neighbor traversal).\n *\n * Usage:\n * ```ts\n * const client = new ProteosClient({ baseUrl, tokenProvider });\n * const knowledge = new KnowledgeClient(client);\n * const node = await knowledge.nodes.create({ title: 'ADR 1', type: 'markdown', status: 'draft', content: '# ...' });\n * const hits = await knowledge.nodes.search({ query: 'invoicing' });\n * ```\n */\nexport class KnowledgeClient {\n readonly nodes: NodeService\n readonly links: LinkService\n /** Node→record edges (links to data-service records): `knowledge.recordLinks`. */\n readonly recordLinks: RecordLinkService\n readonly labels: LabelService\n /**\n * Knowledge spaces — the containers nodes live in: `knowledge.spaces`.\n * Access to a space is granted through `auth.shares`, not here.\n */\n readonly spaces: SpaceService\n /** Whole-org graph bulk read (radiant graph view): `knowledge.graph.get()`. */\n readonly graph: GraphService\n /** Org-wide whiteboard templates: `knowledge.whiteboardTemplates`. */\n readonly whiteboardTemplates: WhiteboardTemplateService\n\n constructor(client: ProteosClient) {\n this.nodes = new NodeServiceImpl(client)\n this.links = new LinkServiceImpl(client)\n this.recordLinks = new RecordLinkServiceImpl(client)\n this.labels = new LabelServiceImpl(client)\n this.spaces = new SpaceServiceImpl(client)\n this.graph = new GraphServiceImpl(client)\n this.whiteboardTemplates = new WhiteboardTemplateServiceImpl(client)\n }\n}\n\n// Re-export service interfaces\nexport type { GraphService } from './graph.js'\nexport type { LabelService } from './labels.js'\nexport type { LinkService } from './links.js'\nexport type { NodeService } from './nodes.js'\nexport type { RecordLinkService } from './record-links.js'\nexport type { SpaceService } from './spaces.js'\n// Re-export types\nexport type {\n ContentMatch,\n ContentResponse,\n CreateLabelRequest,\n CreateLinkRequest,\n CreateNodeRequest,\n CreateRecordLinkRequest,\n CreateSpaceRequest,\n CreateWhiteboardTemplateRequest,\n EditContentRequest,\n EditContentResponse,\n GetGraphOptions,\n InlineLinkRequest,\n KnowledgeGraph,\n KnowledgeGraphLink,\n KnowledgeGraphNode,\n KnowledgeLabel,\n KnowledgeLink,\n KnowledgeNode,\n KnowledgeNodeLabel,\n KnowledgeNodeMetadata,\n KnowledgeNodeSearchResult,\n KnowledgeRecordLink,\n KnowledgeSpace,\n LinkType,\n ListLabelsOptions,\n ListLinksOptions,\n ListNodesOptions,\n ListRecordLinksOptions,\n ListSpacesOptions,\n ListWhiteboardTemplatesOptions,\n MatchMode,\n NeighborDirection,\n NeighborEdge,\n NeighborNode,\n NeighborsOptions,\n NodeContentMatches,\n NodeNeighborhood,\n NodeOutline,\n NodeStatus,\n NodeType,\n OutlineHeading,\n OutlineRequest,\n OutlineResponse,\n SearchContentRequest,\n SearchContentResponse,\n SearchNodesRequest,\n SpaceScope,\n UpdateLabelRequest,\n UpdateLinkRequest,\n UpdateNodeRequest,\n UpdateSpaceRequest,\n UpdateWhiteboardTemplateRequest,\n WhiteboardTemplate,\n WhiteboardTemplateMetadata,\n WriteContentOptions,\n WriteContentResponse,\n} from './types.js'\n// Re-export the reserved space-filter sentinel (a value, not a type).\n// Re-export Zod schemas\nexport {\n KnowledgeLabelSchema,\n KnowledgeLinkSchema,\n KnowledgeNodeLabelSchema,\n KnowledgeNodeMetadataSchema,\n KnowledgeNodeSchema,\n KnowledgeNodeSearchResultSchema,\n KnowledgeRecordLinkSchema,\n NodeNeighborhoodSchema,\n UNASSIGNED_SPACE_SLUG,\n} from './types.js'\nexport type { WhiteboardTemplateService } from './whiteboard-templates.js'\n","import type { ProteosClient } from '../client.js'\nimport type {\n AvailabilityConstraint,\n BookSchedulingLinkRequest,\n BookSchedulingLinkResponse,\n Calendar,\n CalendarConnection,\n CalendarEvent,\n CalendarEventsResponse,\n CalendarEventType,\n CancelPublicCalendarEventRequest,\n CreateAvailabilityConstraintRequest,\n CreateCalendarConnectionRequest,\n CreateCalendarEventRequest,\n CreateSchedulingLinkRequest,\n GetPublicSlotsQuery,\n GetSlotsRequest,\n GetSlotsResponse,\n ListAvailabilityConstraintsQuery,\n ListCalendarConnectionsQuery,\n ListCalendarEventsQuery,\n ListCalendarEventTypesQuery,\n ListCalendarsQuery,\n ListResponse,\n ListSchedulingLinksQuery,\n PublicBookSchedulingLinkResponse,\n PublicCalendarEvent,\n PublicSchedulingLink,\n PutCalendarEventTypeRequest,\n PutSchedulingProfileRequest,\n RecurrenceScope,\n ReschedulePublicCalendarEventRequest,\n RespondCalendarEventRequest,\n SchedulingLink,\n SchedulingProfile,\n UpdateAvailabilityConstraintRequest,\n UpdateCalendarConnectionRequest,\n UpdateCalendarEventRequest,\n UpdateCalendarEventTypeRequest,\n UpdateCalendarRequest,\n UpdateCalendarSyncRequest,\n UpdateSchedulingLinkRequest,\n} from './types.js'\n\nexport * from './types.js'\n\nconst SCHEDULING_BASE_PATH = '/scheduling/v1'\n\nconst encode = encodeURIComponent\n\n/**\n * Facade for scheduling-service: calendar connections (bindings to\n * connector-service google-calendar / microsoft-calendar grants), the\n * calendars under them with their platform roles, per-user scheduling\n * profiles, and the two-way calendar_event mirror.\n *\n * `*Mine` methods act on the caller's own rows (`/me/...`); `*ForUser`\n * methods are the admin path (`/users/:userId/...`).\n *\n * ```ts\n * const scheduling = new SchedulingClient(client)\n * const connection = await scheduling.calendarConnections.connect({ connection_id })\n * const { data: calendars } = await scheduling.calendars.listMine()\n * await scheduling.calendars.updateMine(calendars[0].id, { is_synced: true })\n * const { data: events } = await scheduling.calendarEvents.list({ from, to })\n * ```\n */\nexport class SchedulingClient {\n readonly calendarConnections: CalendarConnectionService\n readonly calendars: CalendarService\n readonly schedulingProfiles: SchedulingProfileService\n readonly calendarEvents: CalendarEventService\n readonly calendarEventTypes: CalendarEventTypeService\n readonly availabilityConstraints: AvailabilityConstraintService\n readonly slots: SlotService\n readonly schedulingLinks: SchedulingLinkService\n /** The unauthenticated scheduling page + manage page (no Authorization header). */\n readonly public: PublicSchedulingService\n\n constructor(client: ProteosClient) {\n this.schedulingLinks = new SchedulingLinkServiceImpl(client)\n this.public = new PublicSchedulingServiceImpl(client)\n this.calendarConnections = new CalendarConnectionServiceImpl(client)\n this.calendars = new CalendarServiceImpl(client)\n this.schedulingProfiles = new SchedulingProfileServiceImpl(client)\n this.calendarEvents = new CalendarEventServiceImpl(client)\n this.calendarEventTypes = new CalendarEventTypeServiceImpl(client)\n this.availabilityConstraints = new AvailabilityConstraintServiceImpl(client)\n this.slots = new SlotServiceImpl(client)\n }\n}\n\n/** Bindings to connector-service calendar grants. */\nexport interface CalendarConnectionService {\n listMine(query?: ListCalendarConnectionsQuery): Promise<ListResponse<CalendarConnection>>\n /** Bind one of the caller's user-scope calendar connector connections; discovers its calendars. */\n connect(request: CreateCalendarConnectionRequest): Promise<CalendarConnection>\n updateMine(id: string, request: UpdateCalendarConnectionRequest): Promise<CalendarConnection>\n disconnectMine(id: string): Promise<void>\n /** Enqueue a sync of every synced calendar under the connection. */\n syncMine(id: string, request?: UpdateCalendarSyncRequest): Promise<CalendarConnection>\n listForUser(\n userId: string,\n query?: ListCalendarConnectionsQuery,\n ): Promise<ListResponse<CalendarConnection>>\n updateForUser(\n userId: string,\n id: string,\n request: UpdateCalendarConnectionRequest,\n ): Promise<CalendarConnection>\n disconnectForUser(userId: string, id: string): Promise<void>\n}\n\nclass CalendarConnectionServiceImpl implements CalendarConnectionService {\n constructor(private readonly client: ProteosClient) {}\n\n listMine(query: ListCalendarConnectionsQuery = {}): Promise<ListResponse<CalendarConnection>> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/me/calendar-connections`,\n query,\n )\n }\n\n connect(request: CreateCalendarConnectionRequest): Promise<CalendarConnection> {\n return this.client.request('POST', `${SCHEDULING_BASE_PATH}/me/calendar-connections`, request)\n }\n\n updateMine(id: string, request: UpdateCalendarConnectionRequest): Promise<CalendarConnection> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/me/calendar-connections/${encode(id)}`,\n request,\n )\n }\n\n async disconnectMine(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${SCHEDULING_BASE_PATH}/me/calendar-connections/${encode(id)}`,\n )\n }\n\n syncMine(id: string, request: UpdateCalendarSyncRequest = {}): Promise<CalendarConnection> {\n return this.client.request<CalendarConnection>(\n 'POST',\n `${SCHEDULING_BASE_PATH}/me/calendar-connections/${encode(id)}/sync`,\n request,\n )\n }\n\n listForUser(\n userId: string,\n query: ListCalendarConnectionsQuery = {},\n ): Promise<ListResponse<CalendarConnection>> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendar-connections`,\n query,\n )\n }\n\n updateForUser(\n userId: string,\n id: string,\n request: UpdateCalendarConnectionRequest,\n ): Promise<CalendarConnection> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendar-connections/${encode(id)}`,\n request,\n )\n }\n\n async disconnectForUser(userId: string, id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendar-connections/${encode(id)}`,\n )\n }\n}\n\n/** Provider calendars under a connection + their platform roles. */\nexport interface CalendarService {\n listMine(query?: ListCalendarsQuery): Promise<ListResponse<Calendar>>\n getMine(id: string): Promise<Calendar>\n updateMine(id: string, request: UpdateCalendarRequest): Promise<Calendar>\n listForUser(userId: string, query?: ListCalendarsQuery): Promise<ListResponse<Calendar>>\n getForUser(userId: string, id: string): Promise<Calendar>\n updateForUser(userId: string, id: string, request: UpdateCalendarRequest): Promise<Calendar>\n}\n\nclass CalendarServiceImpl implements CalendarService {\n constructor(private readonly client: ProteosClient) {}\n\n listMine(query: ListCalendarsQuery = {}): Promise<ListResponse<Calendar>> {\n return this.client.requestWithQuery('GET', `${SCHEDULING_BASE_PATH}/me/calendars`, query)\n }\n\n getMine(id: string): Promise<Calendar> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/me/calendars/${encode(id)}`)\n }\n\n updateMine(id: string, request: UpdateCalendarRequest): Promise<Calendar> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/me/calendars/${encode(id)}`,\n request,\n )\n }\n\n listForUser(userId: string, query: ListCalendarsQuery = {}): Promise<ListResponse<Calendar>> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendars`,\n query,\n )\n }\n\n getForUser(userId: string, id: string): Promise<Calendar> {\n return this.client.request(\n 'GET',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendars/${encode(id)}`,\n )\n }\n\n updateForUser(userId: string, id: string, request: UpdateCalendarRequest): Promise<Calendar> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendars/${encode(id)}`,\n request,\n )\n }\n}\n\n/** Per-user scheduling settings (one per org + user; defaults when absent). */\nexport interface SchedulingProfileService {\n getMine(): Promise<SchedulingProfile>\n putMine(request: PutSchedulingProfileRequest): Promise<SchedulingProfile>\n getForUser(userId: string): Promise<SchedulingProfile>\n putForUser(userId: string, request: PutSchedulingProfileRequest): Promise<SchedulingProfile>\n}\n\nclass SchedulingProfileServiceImpl implements SchedulingProfileService {\n constructor(private readonly client: ProteosClient) {}\n\n getMine(): Promise<SchedulingProfile> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/me/scheduling-profile`)\n }\n\n putMine(request: PutSchedulingProfileRequest): Promise<SchedulingProfile> {\n return this.client.request('PUT', `${SCHEDULING_BASE_PATH}/me/scheduling-profile`, request)\n }\n\n getForUser(userId: string): Promise<SchedulingProfile> {\n return this.client.request(\n 'GET',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/scheduling-profile`,\n )\n }\n\n putForUser(userId: string, request: PutSchedulingProfileRequest): Promise<SchedulingProfile> {\n return this.client.request(\n 'PUT',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/scheduling-profile`,\n request,\n )\n }\n}\n\n/** The two-way calendar_event mirror. */\nexport interface CalendarEventService {\n /** A window of events (from/to required, ≤ 93 days); colleagues' events come back projected. */\n list(query: ListCalendarEventsQuery): Promise<CalendarEventsResponse>\n get(id: string): Promise<CalendarEvent>\n /** Write an event through to the provider (calendar_id = own calendar, or hosts). */\n create(request: CreateCalendarEventRequest): Promise<CalendarEvent>\n /** Partial update; `scope` picks the instance or the whole series on recurring events. */\n update(\n id: string,\n request: UpdateCalendarEventRequest,\n scope?: RecurrenceScope,\n ): Promise<CalendarEvent>\n delete(id: string, scope?: RecurrenceScope): Promise<void>\n /** Record the caller's RSVP. */\n respond(id: string, request: RespondCalendarEventRequest): Promise<CalendarEvent>\n}\n\nclass CalendarEventServiceImpl implements CalendarEventService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListCalendarEventsQuery): Promise<CalendarEventsResponse> {\n return this.client.requestWithQuery('GET', `${SCHEDULING_BASE_PATH}/calendar-events`, query)\n }\n\n get(id: string): Promise<CalendarEvent> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/calendar-events/${encode(id)}`)\n }\n\n create(request: CreateCalendarEventRequest): Promise<CalendarEvent> {\n return this.client.request('POST', `${SCHEDULING_BASE_PATH}/calendar-events`, request)\n }\n\n update(\n id: string,\n request: UpdateCalendarEventRequest,\n scope?: RecurrenceScope,\n ): Promise<CalendarEvent> {\n return this.client.requestWithQuery(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/calendar-events/${encode(id)}`,\n scope ? { scope } : undefined,\n request,\n )\n }\n\n async delete(id: string, scope?: RecurrenceScope): Promise<void> {\n await this.client.requestWithQuery(\n 'DELETE',\n `${SCHEDULING_BASE_PATH}/calendar-events/${encode(id)}`,\n scope ? { scope } : undefined,\n )\n }\n\n respond(id: string, request: RespondCalendarEventRequest): Promise<CalendarEvent> {\n return this.client.request(\n 'POST',\n `${SCHEDULING_BASE_PATH}/calendar-events/${encode(id)}/respond`,\n request,\n )\n }\n}\n\n/** The slot-rules catalog: calendar event types, keyed by (org, key). */\nexport interface CalendarEventTypeService {\n list(query?: ListCalendarEventTypesQuery): Promise<ListResponse<CalendarEventType>>\n get(key: string): Promise<CalendarEventType>\n /** Create or replace (PUT semantics: every field is the new value). */\n put(key: string, request: PutCalendarEventTypeRequest): Promise<CalendarEventType>\n update(key: string, request: UpdateCalendarEventTypeRequest): Promise<CalendarEventType>\n delete(key: string): Promise<void>\n}\n\nclass CalendarEventTypeServiceImpl implements CalendarEventTypeService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListCalendarEventTypesQuery = {}): Promise<ListResponse<CalendarEventType>> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/calendar-event-types`,\n query,\n )\n }\n\n get(key: string): Promise<CalendarEventType> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/calendar-event-types/${encode(key)}`)\n }\n\n put(key: string, request: PutCalendarEventTypeRequest): Promise<CalendarEventType> {\n return this.client.request(\n 'PUT',\n `${SCHEDULING_BASE_PATH}/calendar-event-types/${encode(key)}`,\n request,\n )\n }\n\n update(key: string, request: UpdateCalendarEventTypeRequest): Promise<CalendarEventType> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/calendar-event-types/${encode(key)}`,\n request,\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${SCHEDULING_BASE_PATH}/calendar-event-types/${encode(key)}`,\n )\n }\n}\n\n/** A user's hours and blocks. `*Mine` = the caller's own; `*ForUser` = admin path. */\nexport interface AvailabilityConstraintService {\n listMine(query?: ListAvailabilityConstraintsQuery): Promise<ListResponse<AvailabilityConstraint>>\n getMine(id: string): Promise<AvailabilityConstraint>\n createMine(request: CreateAvailabilityConstraintRequest): Promise<AvailabilityConstraint>\n updateMine(\n id: string,\n request: UpdateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint>\n deleteMine(id: string): Promise<void>\n listForUser(\n userId: string,\n query?: ListAvailabilityConstraintsQuery,\n ): Promise<ListResponse<AvailabilityConstraint>>\n getForUser(userId: string, id: string): Promise<AvailabilityConstraint>\n createForUser(\n userId: string,\n request: CreateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint>\n updateForUser(\n userId: string,\n id: string,\n request: UpdateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint>\n deleteForUser(userId: string, id: string): Promise<void>\n}\n\nclass AvailabilityConstraintServiceImpl implements AvailabilityConstraintService {\n constructor(private readonly client: ProteosClient) {}\n\n private base(userId?: string): string {\n return userId\n ? `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/availability-constraints`\n : `${SCHEDULING_BASE_PATH}/me/availability-constraints`\n }\n\n listMine(\n query: ListAvailabilityConstraintsQuery = {},\n ): Promise<ListResponse<AvailabilityConstraint>> {\n return this.client.requestWithQuery('GET', this.base(), query)\n }\n\n getMine(id: string): Promise<AvailabilityConstraint> {\n return this.client.request('GET', `${this.base()}/${encode(id)}`)\n }\n\n createMine(request: CreateAvailabilityConstraintRequest): Promise<AvailabilityConstraint> {\n return this.client.request('POST', this.base(), request)\n }\n\n updateMine(\n id: string,\n request: UpdateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint> {\n return this.client.request('PATCH', `${this.base()}/${encode(id)}`, request)\n }\n\n async deleteMine(id: string): Promise<void> {\n await this.client.request('DELETE', `${this.base()}/${encode(id)}`)\n }\n\n listForUser(\n userId: string,\n query: ListAvailabilityConstraintsQuery = {},\n ): Promise<ListResponse<AvailabilityConstraint>> {\n return this.client.requestWithQuery('GET', this.base(userId), query)\n }\n\n getForUser(userId: string, id: string): Promise<AvailabilityConstraint> {\n return this.client.request('GET', `${this.base(userId)}/${encode(id)}`)\n }\n\n createForUser(\n userId: string,\n request: CreateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint> {\n return this.client.request('POST', this.base(userId), request)\n }\n\n updateForUser(\n userId: string,\n id: string,\n request: UpdateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint> {\n return this.client.request('PATCH', `${this.base(userId)}/${encode(id)}`, request)\n }\n\n async deleteForUser(userId: string, id: string): Promise<void> {\n await this.client.request('DELETE', `${this.base(userId)}/${encode(id)}`)\n }\n}\n\n/** The slot engine: bookable starts of some hosts under a type's / explicit rules. */\nexport interface SlotService {\n get(request: GetSlotsRequest): Promise<GetSlotsResponse>\n}\n\nclass SlotServiceImpl implements SlotService {\n constructor(private readonly client: ProteosClient) {}\n\n get(request: GetSlotsRequest): Promise<GetSlotsResponse> {\n return this.client.request('POST', `${SCHEDULING_BASE_PATH}/slots`, request)\n }\n}\n\n/** Scheduling links: the entry points for taking a slot, plus booking through one. */\nexport interface SchedulingLinkService {\n list(query?: ListSchedulingLinksQuery): Promise<ListResponse<SchedulingLink>>\n get(key: string): Promise<SchedulingLink>\n create(request: CreateSchedulingLinkRequest): Promise<SchedulingLink>\n update(key: string, request: UpdateSchedulingLinkRequest): Promise<SchedulingLink>\n delete(key: string): Promise<void>\n /** The link as an embedded scheduling picker renders it (types, hosts, policy) — private links included. */\n getPage(key: string, contactId?: string): Promise<PublicSchedulingLink>\n /** The link's slots (its hosts + assignment, its type's rules). */\n getSlots(key: string, query: GetPublicSlotsQuery): Promise<GetSlotsResponse>\n /** Take a slot through the link (scheduling-links:read); an empty contact books for the caller. */\n book(key: string, request: BookSchedulingLinkRequest): Promise<BookSchedulingLinkResponse>\n}\n\nclass SchedulingLinkServiceImpl implements SchedulingLinkService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListSchedulingLinksQuery = {}): Promise<ListResponse<SchedulingLink>> {\n return this.client.requestWithQuery('GET', `${SCHEDULING_BASE_PATH}/scheduling-links`, query)\n }\n\n get(key: string): Promise<SchedulingLink> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}`)\n }\n\n create(request: CreateSchedulingLinkRequest): Promise<SchedulingLink> {\n return this.client.request('POST', `${SCHEDULING_BASE_PATH}/scheduling-links`, request)\n }\n\n update(key: string, request: UpdateSchedulingLinkRequest): Promise<SchedulingLink> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}`,\n request,\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request('DELETE', `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}`)\n }\n\n getPage(key: string, contactId?: string): Promise<PublicSchedulingLink> {\n const suffix = contactId ? `?contact_id=${encode(contactId)}` : ''\n return this.client.request(\n 'GET',\n `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}/page${suffix}`,\n )\n }\n\n getSlots(key: string, query: GetPublicSlotsQuery): Promise<GetSlotsResponse> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}/slots`,\n query,\n )\n }\n\n book(key: string, request: BookSchedulingLinkRequest): Promise<BookSchedulingLinkResponse> {\n return this.client.request(\n 'POST',\n `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}/calendar-events`,\n request,\n )\n }\n}\n\n/**\n * The unauthenticated scheduling surface: every call sends NO Authorization\n * header (skipAuth), so it is safe on the anonymous /s/ routes. Links answer\n * only when public + enabled; events only with their manage token.\n */\nexport interface PublicSchedulingService {\n getLink(orgId: string, key: string, contactId?: string): Promise<PublicSchedulingLink>\n getSlots(orgId: string, key: string, query: GetPublicSlotsQuery): Promise<GetSlotsResponse>\n book(\n orgId: string,\n key: string,\n request: BookSchedulingLinkRequest,\n ): Promise<PublicBookSchedulingLinkResponse>\n getEvent(orgId: string, id: string, token: string): Promise<PublicCalendarEvent>\n cancel(\n orgId: string,\n id: string,\n request: CancelPublicCalendarEventRequest,\n ): Promise<PublicCalendarEvent>\n reschedule(\n orgId: string,\n id: string,\n request: ReschedulePublicCalendarEventRequest,\n ): Promise<PublicBookSchedulingLinkResponse>\n}\n\nclass PublicSchedulingServiceImpl implements PublicSchedulingService {\n constructor(private readonly client: ProteosClient) {}\n\n private base(orgId: string): string {\n return `${SCHEDULING_BASE_PATH}/public/orgs/${encode(orgId)}`\n }\n\n getLink(orgId: string, key: string, contactId?: string): Promise<PublicSchedulingLink> {\n const suffix = contactId ? `?contact_id=${encode(contactId)}` : ''\n return this.client.request(\n 'GET',\n `${this.base(orgId)}/links/${encode(key)}${suffix}`,\n undefined,\n { skipAuth: true },\n )\n }\n\n getSlots(orgId: string, key: string, query: GetPublicSlotsQuery): Promise<GetSlotsResponse> {\n const params = new URLSearchParams({ from: query.from, to: query.to, timezone: query.timezone })\n if (query.host_user_id) params.set('host_user_id', query.host_user_id)\n if (query.type_key) params.set('type_key', query.type_key)\n return this.client.request(\n 'GET',\n `${this.base(orgId)}/links/${encode(key)}/slots?${params.toString()}`,\n undefined,\n { skipAuth: true },\n )\n }\n\n book(\n orgId: string,\n key: string,\n request: BookSchedulingLinkRequest,\n ): Promise<PublicBookSchedulingLinkResponse> {\n return this.client.request(\n 'POST',\n `${this.base(orgId)}/links/${encode(key)}/calendar-events`,\n request,\n { skipAuth: true },\n )\n }\n\n getEvent(orgId: string, id: string, token: string): Promise<PublicCalendarEvent> {\n return this.client.request(\n 'GET',\n `${this.base(orgId)}/calendar-events/${encode(id)}?token=${encode(token)}`,\n undefined,\n { skipAuth: true },\n )\n }\n\n cancel(\n orgId: string,\n id: string,\n request: CancelPublicCalendarEventRequest,\n ): Promise<PublicCalendarEvent> {\n return this.client.request(\n 'POST',\n `${this.base(orgId)}/calendar-events/${encode(id)}/cancel`,\n request,\n { skipAuth: true },\n )\n }\n\n reschedule(\n orgId: string,\n id: string,\n request: ReschedulePublicCalendarEventRequest,\n ): Promise<PublicBookSchedulingLinkResponse> {\n return this.client.request(\n 'POST',\n `${this.base(orgId)}/calendar-events/${encode(id)}/reschedule`,\n request,\n { skipAuth: true },\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type { PublicAccessOperation } from '../meta/types.js'\nimport type { RequestOptions } from '../types/options.js'\nimport type {\n CreateFileMetadata,\n FileVersionContent,\n StorageFile,\n UpdateFileMetadata,\n} from './types.js'\n\nconst FILES_BASE_PATH = '/storage/v1/files'\n\n/**\n * Service for storing and retrieving files via the storage-service.\n *\n * The storage-service is one-blob-per-id (no directories); each `upload` creates\n * a brand-new file. A `file`-typed record attribute stores only the resulting\n * `{ id, name }` (a `FileRef`); size and content type are resolved on read via\n * {@link FileService.get}.\n */\nexport interface FileService {\n /**\n * Uploads bytes and creates a new file. Returns the created file (including\n * `current_version.size_in_bytes` and `content_type`). The caller derives the\n * `FileRef { id, name }` it stores on the record from the result.\n *\n * `name` defaults to the `File`'s own name; `contentType` to its MIME type.\n * `publicAccess: [\"read\"]` exposes the file on the UNAUTHENTICATED public\n * download route; omit for a private file (the default).\n */\n upload(\n file: File,\n options?: { name?: string; contentType?: string; publicAccess?: PublicAccessOperation[] },\n ): Promise<StorageFile>\n\n /**\n * Creates a file's metadata only (no bytes) — the first step of the upload-URL\n * flow for large files. The returned file is not yet persisted; mint an upload URL\n * with {@link FileService.createUploadUrl} and PUT the bytes to it.\n */\n create(metadata: CreateFileMetadata): Promise<StorageFile>\n\n /**\n * Updates a file's metadata (name, `public_access`) and, when `file` is\n * given, replaces the bytes IN PLACE — a new version under the SAME id, so\n * every `FileRef { id }` pointing at it now resolves to the new content.\n * Only the metadata fields present are changed. Setting\n * `public_access: [\"read\"]` exposes the file on the UNAUTHENTICATED public\n * download route; `[]` revokes it. Replacing a locked file is rejected by\n * the storage-service.\n */\n update(id: string, metadata: UpdateFileMetadata, file?: File): Promise<StorageFile>\n\n /**\n * Mints a short-lived upload URL for a file. The bytes are PUT directly to this URL\n * (raw body, no auth) — keeping large files off the SDK/MCP path. Single-use, ~3 min.\n */\n createUploadUrl(id: string): Promise<{ url: string; expires_at: string }>\n\n /**\n * Triggers content extraction for the file's current version. Asynchronous: returns\n * a `processing` row (or cached `ready` content); poll {@link FileService.getContent}\n * for the terminal status.\n */\n parse(id: string, options?: { parser?: string; force?: boolean }): Promise<FileVersionContent>\n\n /**\n * Fetches the parsed content of the file's current version.\n * @throws {ProteosError} If the file has never been parsed (404).\n */\n getContent(id: string): Promise<FileVersionContent>\n\n /**\n * Fetches a file's metadata by id (name, content type, current version size).\n * @throws {ProteosError} If the file is not found (404).\n */\n get(id: string): Promise<StorageFile>\n\n /**\n * Mints a short-lived public download URL for a file (the token in the URL is\n * the sole credential — no auth header needed). Default: single-use, ≈5 min\n * TTL, suitable for click-to-download. `allowsMultiUse` mints a token that\n * survives repeated GETs (≈1 h TTL) for consumers that probe the URL before\n * downloading.\n */\n /**\n * Permanently deletes a file: every version's stored bytes, its access\n * tokens and parsed content. Irreversible. Locked files are refused\n * (409 `delete_locked_file`) — unlock via {@link FileService.update} first.\n */\n delete(id: string): Promise<void>\n\n /**\n * Permanently deletes a single non-current version and its stored bytes.\n * Irreversible. Deleting the current version is refused\n * (409 `delete_current_version`), as are locked files (409 `delete_locked_file`).\n */\n deleteVersion(id: string, versionId: string): Promise<void>\n\n createDownloadUrl(\n id: string,\n options?: { allowsMultiUse?: boolean },\n ): Promise<{ url: string; expires_at: string }>\n\n /**\n * Downloads the file's current version as a Blob (authenticated). Prefer\n * {@link FileService.createDownloadUrl} for browser click-to-download.\n */\n download(id: string, options?: RequestOptions): Promise<Blob>\n\n /**\n * Downloads the current version of a public-read file through the\n * UNAUTHENTICATED public endpoint (no Authorization header). A non-public\n * or missing file 404s identically.\n */\n downloadPublic(orgId: string, id: string): Promise<Blob>\n\n /**\n * Builds the unauthenticated public download URL for a public-read\n * file — usable directly as an <img src> / <a href> on public pages.\n */\n publicDownloadUrl(orgId: string, id: string): string\n}\n\n/**\n * Implementation of FileService.\n */\nexport class FileServiceImpl implements FileService {\n constructor(private readonly client: ProteosClient) {}\n\n async upload(\n file: File,\n options?: { name?: string; contentType?: string; publicAccess?: PublicAccessOperation[] },\n ): Promise<StorageFile> {\n const metadata: CreateFileMetadata = {\n name: options?.name ?? file.name,\n content_type: options?.contentType ?? file.type ?? 'application/octet-stream',\n ...(options?.publicAccess ? { public_access: options.publicAccess } : {}),\n }\n\n // The storage-service reads multipart parts in order: `metadata` (JSON)\n // first, then `file` (bytes). FormData preserves append order, so the\n // metadata Blob MUST be appended before the file.\n const formData = new FormData()\n formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }))\n formData.append('file', file, metadata.name)\n\n const response = await this.client.requestMultipart<{ data: StorageFile }>(\n 'POST',\n FILES_BASE_PATH,\n formData,\n )\n return response.data\n }\n\n async create(metadata: CreateFileMetadata): Promise<StorageFile> {\n const formData = new FormData()\n formData.append(\n 'metadata',\n new Blob(\n [\n JSON.stringify({\n name: metadata.name,\n content_type: metadata.content_type ?? 'application/octet-stream',\n ...(metadata.public_access ? { public_access: metadata.public_access } : {}),\n }),\n ],\n { type: 'application/json' },\n ),\n )\n const response = await this.client.requestMultipart<{ data: StorageFile }>(\n 'POST',\n FILES_BASE_PATH,\n formData,\n )\n return response.data\n }\n\n async update(id: string, metadata: UpdateFileMetadata, file?: File): Promise<StorageFile> {\n // Part order is load-bearing: the storage-service reads `metadata` first\n // and stops consuming parts at `file` — metadata appended after the file\n // part would be silently dropped.\n const formData = new FormData()\n formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }))\n if (file) formData.append('file', file, metadata.name ?? file.name)\n const response = await this.client.requestMultipart<{ data: StorageFile }>(\n 'PATCH',\n `${FILES_BASE_PATH}/${id}`,\n formData,\n )\n return response.data\n }\n\n async createUploadUrl(id: string): Promise<{ url: string; expires_at: string }> {\n const response = await this.client.request<{ data: { url: string; expires_at: string } }>(\n 'POST',\n `${FILES_BASE_PATH}/${id}/generate-upload-url`,\n )\n return response.data\n }\n\n async parse(\n id: string,\n options?: { parser?: string; force?: boolean },\n ): Promise<FileVersionContent> {\n const response = await this.client.request<{ data: FileVersionContent }>(\n 'POST',\n `${FILES_BASE_PATH}/${id}/parse`,\n options ?? {},\n )\n return response.data\n }\n\n async getContent(id: string): Promise<FileVersionContent> {\n const response = await this.client.request<{ data: FileVersionContent }>(\n 'GET',\n `${FILES_BASE_PATH}/${id}/content`,\n )\n return response.data\n }\n\n async get(id: string): Promise<StorageFile> {\n const response = await this.client.request<{ data: StorageFile }>(\n 'GET',\n `${FILES_BASE_PATH}/${id}`,\n )\n return response.data\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${FILES_BASE_PATH}/${id}`)\n }\n\n async deleteVersion(id: string, versionId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${FILES_BASE_PATH}/${id}/versions/${versionId}`)\n }\n\n async createDownloadUrl(\n id: string,\n options?: { allowsMultiUse?: boolean },\n ): Promise<{ url: string; expires_at: string }> {\n const body =\n options?.allowsMultiUse !== undefined\n ? { allows_multi_use: options.allowsMultiUse }\n : undefined\n const response = await this.client.request<{ data: { url: string; expires_at: string } }>(\n 'POST',\n `${FILES_BASE_PATH}/${id}/generate-download-url`,\n body,\n )\n return response.data\n }\n\n /**\n * The file's bytes. `options.timeout` covers reading the whole body, so raise\n * it for large files; `options.signal` aborts the download.\n */\n async download(id: string, options?: RequestOptions): Promise<Blob> {\n const { response } = await this.client.requestRaw(\n 'GET',\n `${FILES_BASE_PATH}/${id}/download`,\n undefined,\n options,\n )\n return await response.blob()\n }\n\n async downloadPublic(orgId: string, id: string): Promise<Blob> {\n const { response } = await this.client.requestRaw(\n 'GET',\n this.publicDownloadPath(orgId, id),\n undefined,\n { skipAuth: true },\n )\n return await response.blob()\n }\n\n publicDownloadUrl(orgId: string, id: string): string {\n return `${this.client.baseUrl}${this.publicDownloadPath(orgId, id)}`\n }\n\n private publicDownloadPath(orgId: string, id: string): string {\n return `/storage/v1/public/orgs/${encodeURIComponent(orgId)}/files/${encodeURIComponent(id)}/download`\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { type FileService, FileServiceImpl } from './files.js'\n\n/**\n * Facade for the storage-service (file upload / download / metadata).\n *\n * Usage:\n * ```ts\n * const client = new ProteosClient({ baseUrl, tokenProvider });\n * const storage = new StorageClient(client);\n * const file = await storage.files.upload(picked); // -> { id, name, ... }\n * const { url } = await storage.files.createDownloadUrl(file.id);\n * ```\n */\nexport class StorageClient {\n readonly files: FileService\n\n constructor(client: ProteosClient) {\n this.files = new FileServiceImpl(client)\n }\n}\n\n// Re-export service interface\nexport type { FileService } from './files.js'\n\n// Re-export types\nexport type {\n CreateFileMetadata,\n FileVersionContent,\n ParseStatus,\n StorageFile,\n StorageFileVersion,\n UpdateFileMetadata,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n GetExecutionDetailResponse,\n GetNodeExecutionItemsOptions,\n GetNodeExecutionItemsResponse,\n ListExecutionsOptions,\n WorkflowExecution,\n} from './types.js'\n\nconst EXECUTIONS_BASE_PATH = '/workflows/v1/executions'\nconst WORKFLOWS_BASE_PATH = '/workflows/v1/workflows'\n\n/**\n * Service for reading Workflow Executions — append-only per-firing run records,\n * keyed by surrogate `id`, referencing their workflow by `workflow_key`.\n */\nexport interface ExecutionService {\n /** Lists executions, auto-paginating. */\n list(options?: ListExecutionsOptions): PageIterator<WorkflowExecution, ListExecutionsOptions>\n /** Fetches a single page of executions with pagination metadata. */\n listPage(options?: ListExecutionsOptions): Promise<ListResult<WorkflowExecution>>\n /** Gets a single execution by id. @throws {ProteosError} 404 if not found. */\n get(id: string): Promise<WorkflowExecution>\n /**\n * Gets the execution detail: the header row plus its append-only node\n * executions (ordered by started_at, then run_index).\n */\n getDetail(id: string): Promise<GetExecutionDetailResponse>\n /**\n * Windows into one node run's stored output items on one port (defaults:\n * port `main`, offset 0, server-side default limit).\n */\n getNodeItems(\n executionId: string,\n nodeId: string,\n runIndex: number,\n options?: GetNodeExecutionItemsOptions,\n ): Promise<GetNodeExecutionItemsResponse>\n /** Lists executions of one workflow (by key). */\n listForWorkflow(\n key: string,\n options?: ListExecutionsOptions,\n ): Promise<ListResult<WorkflowExecution>>\n}\n\nexport class ExecutionServiceImpl implements ExecutionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListExecutionsOptions = {},\n ): PageIterator<WorkflowExecution, ListExecutionsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListExecutionsOptions = {}): Promise<ListResult<WorkflowExecution>> {\n return this.client.requestWithQuery<ListResult<WorkflowExecution>>(\n 'GET',\n EXECUTIONS_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<WorkflowExecution> {\n return this.client.request<WorkflowExecution>('GET', `${EXECUTIONS_BASE_PATH}/${id}`)\n }\n\n async getDetail(id: string): Promise<GetExecutionDetailResponse> {\n return this.client.request<GetExecutionDetailResponse>(\n 'GET',\n `${EXECUTIONS_BASE_PATH}/${id}/detail`,\n )\n }\n\n async getNodeItems(\n executionId: string,\n nodeId: string,\n runIndex: number,\n options: GetNodeExecutionItemsOptions = {},\n ): Promise<GetNodeExecutionItemsResponse> {\n return this.client.requestWithQuery<GetNodeExecutionItemsResponse>(\n 'GET',\n `${EXECUTIONS_BASE_PATH}/${executionId}/nodes/${nodeId}/runs/${runIndex}/items`,\n options,\n )\n }\n\n async listForWorkflow(\n key: string,\n options: ListExecutionsOptions = {},\n ): Promise<ListResult<WorkflowExecution>> {\n return this.client.requestWithQuery<ListResult<WorkflowExecution>>(\n 'GET',\n `${WORKFLOWS_BASE_PATH}/${key}/executions`,\n options,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n GetNodeTypesResponse,\n InvokeNodeMethodRequest,\n InvokeNodeMethodResponse,\n NodeTypeKey,\n WorkflowNodeType,\n} from './types.js'\n\nconst NODE_TYPES_BASE_PATH = '/workflows/v1/node-types'\n\n/**\n * Service for the node-type catalog — the registered NodeDescriptors that\n * drive the editor's picker and parameter forms — and for proxying editor\n * dynamic-method calls (load_options / list_search / …) to the node host.\n */\nexport interface NodeTypeService {\n /**\n * Lists the catalog visible to the caller's org (platform-global +\n * org-installed types, all registered versions, active only).\n */\n list(): Promise<WorkflowNodeType[]>\n /**\n * Invokes a dynamic method on a node type (e.g. `load_options:listEntities`\n * — pass the full `<kind>:<method_name>` string; it is URL-encoded here).\n */\n invokeMethod(\n type: NodeTypeKey,\n method: string,\n request?: InvokeNodeMethodRequest,\n ): Promise<InvokeNodeMethodResponse>\n}\n\nexport class NodeTypeServiceImpl implements NodeTypeService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<WorkflowNodeType[]> {\n const response = await this.client.request<GetNodeTypesResponse>('GET', NODE_TYPES_BASE_PATH)\n return response.data\n }\n\n async invokeMethod(\n type: NodeTypeKey,\n method: string,\n request: InvokeNodeMethodRequest = {},\n ): Promise<InvokeNodeMethodResponse> {\n const path = `${NODE_TYPES_BASE_PATH}/${encodeURIComponent(type)}/methods/${encodeURIComponent(method)}`\n return this.client.request<InvokeNodeMethodResponse>('POST', path, request)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListOptions, ListResult } from '../types/common.js'\nimport type {\n CreateWorkflowRequest,\n ListWorkflowsOptions,\n RunWorkflowRequest,\n TestNodeRequest,\n TestNodeResponse,\n UpdateWorkflowRequest,\n Workflow,\n WorkflowExecution,\n WorkflowVersion,\n WorkflowVersionSummary,\n} from './types.js'\n\nconst WORKFLOWS_BASE_PATH = '/workflows/v1/workflows'\n\n/**\n * Service for managing Workflows — n8n-shaped automation definitions keyed by an\n * immutable kebab-case `key`. Run/pause/unpause drive the Temporal-backed runtime.\n */\nexport interface WorkflowService {\n /** Lists workflows, auto-paginating. */\n list(options?: ListWorkflowsOptions): PageIterator<Workflow, ListWorkflowsOptions>\n /** Fetches a single page of workflows with pagination metadata. */\n listPage(options?: ListWorkflowsOptions): Promise<ListResult<Workflow>>\n /** Gets a single workflow by key. @throws {ProteosError} 404 if not found. */\n get(key: string): Promise<Workflow>\n /** Creates a new workflow. @throws {ProteosError} 400/409. */\n create(request: CreateWorkflowRequest): Promise<Workflow>\n /** Fully replaces a workflow's metadata + graph (version bumped server-side). */\n update(key: string, request: UpdateWorkflowRequest): Promise<Workflow>\n /** Deletes a workflow. @throws {ProteosError} 404 if not found. */\n delete(key: string): Promise<void>\n /**\n * Triggers one manual run; returns the pending execution. Pass\n * `destination_node_id` for a partial \"run until here\" execution (only the\n * destination's ancestors run).\n */\n run(key: string, request?: RunWorkflowRequest): Promise<WorkflowExecution>\n /**\n * Runs ONE node ephemerally against its last-known (or pinned) input and\n * blocks for the result — the editor's \"Run this node\". No execution rows\n * are written; side effects are real.\n */\n testNode(key: string, nodeId: string, request: TestNodeRequest): Promise<TestNodeResponse>\n /** Pauses scheduled/triggered firings. */\n pause(key: string): Promise<Workflow>\n /** Resumes a paused workflow. */\n unpause(key: string): Promise<Workflow>\n /** Lists a workflow's version history (newest first), auto-paginating. */\n listVersions(\n key: string,\n options?: ListOptions,\n ): PageIterator<WorkflowVersionSummary, ListOptions>\n /** Fetches a single page of a workflow's version history (newest first). */\n listVersionsPage(key: string, options?: ListOptions): Promise<ListResult<WorkflowVersionSummary>>\n /** Gets one immutable version of a workflow, graph included. @throws {ProteosError} 404. */\n getVersion(key: string, version: number): Promise<WorkflowVersion>\n /**\n * Restores an old version by saving its graph as a NEW bumped version;\n * returns the updated workflow (its `.version` is the new current version).\n * @throws {ProteosError} 400 when restoring the current version.\n */\n restoreVersion(key: string, version: number): Promise<Workflow>\n}\n\nexport class WorkflowServiceImpl implements WorkflowService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListWorkflowsOptions = {}): PageIterator<Workflow, ListWorkflowsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListWorkflowsOptions = {}): Promise<ListResult<Workflow>> {\n return this.client.requestWithQuery<ListResult<Workflow>>('GET', WORKFLOWS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Workflow> {\n return this.client.request<Workflow>('GET', `${WORKFLOWS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreateWorkflowRequest): Promise<Workflow> {\n return this.client.request<Workflow>('POST', WORKFLOWS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateWorkflowRequest): Promise<Workflow> {\n return this.client.request<Workflow>('PATCH', `${WORKFLOWS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${WORKFLOWS_BASE_PATH}/${key}`)\n }\n\n async run(key: string, request: RunWorkflowRequest = {}): Promise<WorkflowExecution> {\n return this.client.request<WorkflowExecution>(\n 'POST',\n `${WORKFLOWS_BASE_PATH}/${key}/run`,\n request,\n )\n }\n\n async testNode(key: string, nodeId: string, request: TestNodeRequest): Promise<TestNodeResponse> {\n return this.client.request<TestNodeResponse>(\n 'POST',\n `${WORKFLOWS_BASE_PATH}/${key}/nodes/${nodeId}/test`,\n request,\n )\n }\n\n async pause(key: string): Promise<Workflow> {\n return this.client.request<Workflow>('POST', `${WORKFLOWS_BASE_PATH}/${key}/pause`, {})\n }\n\n async unpause(key: string): Promise<Workflow> {\n return this.client.request<Workflow>('POST', `${WORKFLOWS_BASE_PATH}/${key}/unpause`, {})\n }\n\n listVersions(\n key: string,\n options: ListOptions = {},\n ): PageIterator<WorkflowVersionSummary, ListOptions> {\n return new PageIterator((opts) => this.listVersionsPage(key, opts), options)\n }\n\n async listVersionsPage(\n key: string,\n options: ListOptions = {},\n ): Promise<ListResult<WorkflowVersionSummary>> {\n return this.client.requestWithQuery<ListResult<WorkflowVersionSummary>>(\n 'GET',\n `${WORKFLOWS_BASE_PATH}/${key}/versions`,\n options,\n )\n }\n\n async getVersion(key: string, version: number): Promise<WorkflowVersion> {\n return this.client.request<WorkflowVersion>(\n 'GET',\n `${WORKFLOWS_BASE_PATH}/${key}/versions/${version}`,\n )\n }\n\n async restoreVersion(key: string, version: number): Promise<Workflow> {\n return this.client.request<Workflow>(\n 'POST',\n `${WORKFLOWS_BASE_PATH}/${key}/versions/${version}/restore`,\n {},\n )\n }\n}\n","/**\n * Types for the Proteos Workflow Service API (engine v2).\n *\n * Hand-written mirror of the Go models in `go.proteos.ai/model/workflow`\n * (`workflow.go`, `graph.go`, `node-type.go`, `execution.go`, `item.go` +\n * `api/*-requests.go`). Field names match the snake_case wire format exactly,\n * including enum values.\n *\n * A Workflow is an n8n-shaped automation definition keyed by an immutable\n * kebab-case `key` ((org_id, key) PK). Its graph is catalog-driven: every node\n * references a registered node type (a NodeDescriptor) by an open string type\n * key plus a pinned `type_version`. A WorkflowExecution is one firing of a\n * workflow; per-node results live in append-only NodeExecution rows.\n */\n\nimport type { Attribute } from '../meta/types.js'\nimport type { AuditFields, ListOptions, UserRef } from '../types/common.js'\n\n// ---------------------------------------------------------------------------\n// Graph (v2)\n// ---------------------------------------------------------------------------\n\nexport type WorkflowStatus = 'active' | 'paused' | 'archived'\n\n/**\n * A node's registered type key — open string. Catalog types follow\n * `<package>.<node>` (e.g. `proteos-nodes-core.http-request`); engine-native\n * trigger types keep their legacy `trigger.<kind>` keys.\n */\nexport type NodeTypeKey = string\n\nexport interface NodePosition {\n x: number\n y: number\n}\n\n/** How the interpreter routes a failed node run. */\nexport type OnErrorPolicy = 'stop' | 'continue' | 'continue_error_output'\n\n/**\n * Per-node activity retry policy. `max_attempts: 1` disables retries; zero\n * values fall back to the descriptor's defaults, then the engine defaults.\n */\nexport interface NodeRetryPolicy {\n max_attempts?: number\n backoff_seconds?: number\n}\n\n/**\n * One node in the graph. `parameters` holds the RAW parameter values for the\n * node's descriptor properties (Liquid expressions unresolved — resolution\n * happens at ExecuteNode time).\n */\nexport interface WorkflowNode {\n id: string\n type: NodeTypeKey\n /** Pins one registered descriptor version of `type`. */\n type_version?: number\n name: string\n parameters?: Record<string, unknown>\n /** Credential-type slug → metadata variable key or id. */\n credential_refs?: Record<string, string>\n position?: NodePosition\n is_disabled?: boolean\n notes?: string\n on_error?: OnErrorPolicy\n retry?: NodeRetryPolicy\n}\n\n/** The single-port key used when a connection endpoint omits the port. */\nexport const DEFAULT_PORT = 'main'\n\n/**\n * The reserved output-port key every non-trigger node implicitly has. Under\n * `on_error: continue_error_output` the engine emits one item per input item\n * on it: the input's `json` plus an `error` object (`code`, `message`,\n * `details`, `is_user_error`), paired to the input index. Descriptors never\n * declare this port.\n */\nexport const ERROR_PORT = 'error'\n\n/**\n * One side of a connection: a node by id and one of its ports by key.\n * Connections are id-keyed (renaming a node never breaks the graph) and\n * port-keyed (never index-keyed).\n */\nexport interface ConnectionEndpoint {\n node_id: string\n port: string\n}\n\n/** A directed edge from one node's output port to another node's input port. */\nexport interface WorkflowConnection {\n from: ConnectionEndpoint\n to: ConnectionEndpoint\n}\n\nexport interface WorkflowGraph {\n nodes: WorkflowNode[]\n connections: WorkflowConnection[]\n /**\n * Editor-only per-node pinned output items (keyed by node id) used for\n * partial executions; the production interpreter ignores it unless a run\n * explicitly opts in.\n */\n pin_data?: Record<string, Item[]>\n}\n\n// ---------------------------------------------------------------------------\n// Items\n// ---------------------------------------------------------------------------\n\n/** A storage-service file reference carried by an item (never inline bytes). */\nexport interface BinaryRef {\n file_id: string\n mime_type?: string\n file_name?: string\n size_bytes?: number\n}\n\n/**\n * Item lineage: which input item (and port) produced an output item. The wire\n * shape also allows an int shorthand equivalent to `{ item: n }`.\n */\nexport interface PairedItem {\n item: number\n input?: string\n}\n\n/**\n * The unit of data flowing between workflow nodes (n8n 1:1). Node input/output\n * is a map of port key → `Item[]`.\n */\nexport interface Item {\n json: Record<string, unknown>\n binary?: Record<string, BinaryRef>\n paired_item?: PairedItem | number\n}\n\n// ---------------------------------------------------------------------------\n// Node descriptors (catalog)\n// ---------------------------------------------------------------------------\n\n/**\n * Which runtime executes a node type. `go` nodes are first-party, compiled\n * into the node host; `wasm` nodes are user-defined sandboxed bundles;\n * `intrinsic` types are executed by the interpreter / workflow-service itself.\n */\nexport type NodeRuntime = 'go' | 'wasm' | 'intrinsic'\n\n/** Coarse catalog grouping of a node type. */\nexport type NodeGroup = 'trigger' | 'action' | 'transform' | 'flow'\n\n/** Control type of one descriptor property (n8n INodeProperties paradigm). */\nexport type PropertyType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'options'\n | 'multi_options'\n | 'json'\n | 'date_time'\n | 'color'\n | 'notice'\n | 'hidden'\n | 'collection'\n | 'fixed_collection'\n | 'credentials_select'\n | 'button'\n /** Edits a platform attribute list (`Attribute[]`) via the shared attribute schema builder. */\n /** Edits a decision-question map (model-decide `questions`) via the questions builder, with a raw-JSON mode. */\n | 'decision_questions'\n | 'attribute_schema'\n // Wave 2 (editor support lands with Phase 3):\n | 'resource_locator'\n | 'resource_mapper'\n | 'filter'\n | 'assignment_collection'\n\n/**\n * One named input or output port. Port keys are stable identifiers referenced\n * by connections (never indexes).\n */\nexport interface PortSpec {\n key: string\n display_name?: string\n is_required?: boolean\n max_connections?: number\n}\n\n/**\n * Gates a property's visibility on sibling parameter values. The editor\n * re-evaluates reactively; the backend applies the same rule during validation\n * (hidden properties are ignored). `hide` wins over `show`.\n */\nexport interface DisplayOptions {\n show?: Record<string, unknown[]>\n hide?: Record<string, unknown[]>\n}\n\n/**\n * One entry of an options/multi_options list, one repeatable sub-property\n * group of a collection, or one named group of a fixed_collection (in which\n * case `values` carries the group's fixed sub-fields).\n */\nexport interface PropertyOption {\n name: string\n value?: unknown\n display_name?: string\n description?: string\n values?: NodeProperty[]\n}\n\n/**\n * One parameter in a descriptor's schema. `name` is the verbatim key under\n * `node.parameters` (never case-converted). Every value-bearing property\n * accepts a Liquid expression unless `no_data_expression` is true.\n */\nexport interface NodeProperty {\n display_name: string\n name: string\n type: PropertyType\n default?: unknown\n description?: string\n placeholder?: string\n hint?: string\n is_required?: boolean\n no_data_expression?: boolean\n options?: PropertyOption[]\n display_options?: DisplayOptions\n /**\n * v1 subset: `load_options_method`, `load_options_depends_on`,\n * `multiple_values`, `multiple_value_button_text`, `rows`, `password`,\n * `min_value`, `max_value`, `editor`.\n */\n type_options?: Record<string, unknown>\n}\n\n/** Declares that a node type uses a credential of the given type slug. */\nexport interface CredentialSpec {\n type: string\n is_required?: boolean\n display_options?: DisplayOptions\n}\n\n/**\n * The full, self-describing contract of one node type: drives the editor's\n * picker and parameter form, backend validation, and dispatch.\n */\nexport interface NodeDescriptor {\n type: NodeTypeKey\n display_name: string\n description?: string\n /** Lucide icon name, PascalCase. */\n icon?: string\n group: NodeGroup\n version: number\n runtime: NodeRuntime\n task_queue?: string\n inputs: PortSpec[]\n outputs: PortSpec[]\n properties: NodeProperty[]\n credentials?: CredentialSpec[]\n /** Dynamic methods the host answers, as `\"<kind>:<method_name>\"`. */\n methods?: string[]\n /** Declarative routing spec (Phase 4). */\n routing?: unknown\n documentation_url?: string\n /** Liquid over parameters, shown on the canvas node card. */\n subtitle?: string\n /**\n * Retry policy a node of this type runs with when the graph node sets none.\n * Non-idempotent types pin `max_attempts: 1`; absent = engine defaults.\n */\n default_retry?: NodeRetryPolicy\n}\n\n/** Registry lifecycle of one (type, version) row. */\nexport type NodeTypeStatus = 'active' | 'inactive'\n\n/**\n * One node-type registry row: a registered (package, name, version) with its\n * full descriptor. `org_id` is empty for platform-global types and set for\n * org-installed (wasm) types.\n */\nexport interface WorkflowNodeType {\n package: string\n name: string\n version: number\n runtime: NodeRuntime\n task_queue?: string\n descriptor: NodeDescriptor\n status: NodeTypeStatus\n org_id?: string\n created_at: string\n updated_at: string\n}\n\n// ---------------------------------------------------------------------------\n// Node-type API shapes\n// ---------------------------------------------------------------------------\n\nexport interface GetNodeTypesResponse {\n data: WorkflowNodeType[]\n}\n\n/**\n * An editor dynamic-method call (load_options / list_search /\n * resource_mapper_fields / credential_test) proxied to the node host.\n * `parameters` carries the node's current (partial) parameter values.\n */\nexport interface InvokeNodeMethodRequest {\n type_version?: number\n parameters?: Record<string, unknown>\n credential_refs?: Record<string, string>\n filter?: string\n pagination_token?: string\n}\n\n/** One dynamic dropdown entry returned by a load_options method. */\nexport interface NodeMethodOption {\n name: string\n value: unknown\n description?: string\n}\n\nexport interface InvokeNodeMethodResponse {\n /** load_options */\n options?: NodeMethodOption[]\n /** list_search */\n results?: unknown\n pagination_token?: string\n /** resource_mapper_fields */\n fields?: unknown\n /** credential_test */\n is_valid?: boolean\n message?: string\n}\n\n// ---------------------------------------------------------------------------\n// Engine-native trigger / agent parameters\n// ---------------------------------------------------------------------------\n// Trigger nodes are executed by workflow-service itself; their parameters stay\n// typed. Action/transform/flow node parameters are descriptor-driven raw JSON.\n\nexport interface CronTriggerParams {\n cron_expression: string\n timezone: string\n}\n\n/**\n * Manual trigger configuration. `input_schema` declares the typed inputs a\n * manual run may provide (validated on run; they become the trigger item,\n * addressable as `{{ $json.<name> }}`). Empty = the run takes no inputs.\n */\nexport interface ManualTriggerParams {\n input_schema?: Attribute[]\n}\n\nexport interface WebhookTriggerParams {\n token: string\n}\n\nexport type EventVerb = 'created' | 'updated' | 'deleted'\n\nexport interface EventTriggerParams {\n entity_slug: string\n verbs: EventVerb[]\n}\n\nexport interface MessageTriggerParams {\n direction?: string\n channels?: string[]\n connection_id?: string\n event_types?: string[]\n}\n\n/** Matches every event type on the subscribed topic. */\nexport const PLATFORM_EVENT_WILDCARD = '*'\n\n/**\n * Fires the workflow when an event whose type is in `event_types` arrives on\n * the named platform bus topic. Unlike {@link EventTriggerParams} (records\n * only), any per-org topic in the event catalog is a valid target.\n *\n * `event_types` may hold the single wildcard `'*'` to match every type — custom\n * topics have no catalogued type list, so there is nothing to enumerate.\n */\nexport interface PlatformEventTriggerParams {\n topic: string\n event_types: string[]\n}\n\nexport type KickoffType = 'message' | 'outcome'\n\n/**\n * Where a kickoff slot draws its instruction text from: typed inline\n * (`manual`) or resolved from a reusable agent-service Prompt by key\n * (`prompt`) at run time.\n */\nexport type KickoffSource = 'manual' | 'prompt'\n\n/**\n * Flat, descriptor-driven parameters of the `action.agent` node (gated by\n * display_options on `kickoff_type` / `*_source`). `output_schema` declares\n * the node's structured output as platform attributes — the agent records it\n * via the session-scoped `set_output` tool; `is_output_required` fails the\n * node when the agent finishes without setting it.\n */\nexport interface AgentActionParams {\n agent_key: string\n kickoff_type: KickoffType\n message_source?: KickoffSource\n message_text?: string\n message_prompt_key?: string\n description_source?: KickoffSource\n description?: string\n description_prompt_key?: string\n rubric_source?: KickoffSource\n rubric_type?: 'text' | 'file'\n rubric_content?: string\n rubric_file_id?: string\n rubric_prompt_key?: string\n max_iterations?: number\n output_schema?: Attribute[]\n is_output_required?: boolean\n}\n\n/**\n * Where a model call's optional system instruction comes from. Empty/absent\n * defaults to `none`.\n */\nexport type SystemSource = 'none' | 'manual' | 'prompt'\n\n/**\n * Flat, descriptor-driven parameters of the `proteos-nodes-core.model-call`\n * node: one stateless LLM call per input item. The prompt and the optional\n * system instruction are independently sourced — typed inline (`manual`,\n * Liquid-resolved per item) or resolved verbatim from a reusable Prompt by key\n * (`prompt`). With `has_structured_output`, `output_schema` declares the\n * reply's shape as platform attributes: generation is schema-constrained\n * (forced tool) AND the node validates the returned JSON, failing the item\n * after one automatic repair attempt.\n */\nexport interface ModelCallParams {\n /** Empty resolves to the platform default model. */\n model_id?: string\n temperature?: number\n max_tokens?: number\n prompt_source?: KickoffSource\n prompt_text?: string\n prompt_key?: string\n system_source?: SystemSource\n system_text?: string\n system_prompt_key?: string\n has_structured_output?: boolean\n output_schema?: Attribute[]\n}\n\n// ---------------------------------------------------------------------------\n// Workflow\n// ---------------------------------------------------------------------------\n\nexport interface Workflow extends AuditFields {\n org_id: string\n key: string\n name: string\n description: string\n /** Slug of the module that deployed this workflow; empty when it is org-owned. */\n module_slug: string\n status: WorkflowStatus\n graph: WorkflowGraph\n version: number\n}\n\nexport interface CreateWorkflowRequest {\n key: string\n name: string\n description?: string\n graph: WorkflowGraph\n}\n\nexport interface UpdateWorkflowRequest {\n name: string\n description?: string\n graph: WorkflowGraph\n}\n\n/**\n * Body of a manual \"run now\" call. `destination_node_id` turns the run into a\n * partial \"run until here\" execution: only nodes on a path from the trigger to\n * the destination (inclusive) execute.\n */\nexport interface RunWorkflowRequest {\n destination_node_id?: string\n /** Values for the manual trigger's `input_schema`; seed the trigger item. */\n inputs?: Record<string, unknown>\n}\n\n/** Where a standalone node test's input comes from. */\nexport type TestNodeInputSource = 'last_execution' | 'pinned'\n\n/**\n * The candidate node definition under test — the editor's in-memory (possibly\n * unsaved) state. Parameters stay raw; Liquid resolves on the node host per\n * item, exactly like a real run.\n */\nexport interface TestNodeCandidate {\n type: NodeTypeKey\n type_version?: number\n name?: string\n parameters?: Record<string, unknown>\n credential_refs?: Record<string, string>\n}\n\n/**\n * Runs ONE node ephemerally — no execution rows, real side effects. Input is\n * seeded from the last execution's mirrored input (default) or from the\n * pinned output of the node's upstream neighbors.\n */\nexport interface TestNodeRequest {\n node: TestNodeCandidate\n input_source?: TestNodeInputSource\n}\n\n/**\n * The full test round trip: the input that was fed in (shown even when the\n * node fails) and the produced output, items inline per port. Both sides are\n * capped (`is_truncated`).\n */\nexport interface TestNodeResponse {\n status: 'succeeded' | 'failed' | 'skipped'\n input_source: TestNodeInputSource\n /** False when the workflow (or this node) never ran — nothing was fed in. */\n has_prior_execution: boolean\n input: Record<string, Item[]>\n output: Record<string, Item[]>\n item_counts: Record<string, number>\n error?: ExecutionError\n metadata?: Record<string, unknown>\n is_truncated: boolean\n}\n\nexport interface ListWorkflowsOptions extends ListOptions {\n name?: string\n 'name[contains]'?: string\n status?: WorkflowStatus\n /**\n * Restrict to one module's workflows. The empty string is meaningful: it\n * matches only the org-owned workflows no module deployed.\n *\n * `sort_by` additionally accepts a comma-separated list of sortable fields\n * (`module_slug,name`) so a grouped list can order by its grouping column\n * first; `sort_direction` applies to all of them.\n */\n module_slug?: string\n}\n\n// ---------------------------------------------------------------------------\n// Versions\n// ---------------------------------------------------------------------------\n\n/**\n * The author of a workflow version — a common {@link UserRef} that the\n * versions endpoints enrich with a resolved display `name` when available.\n */\nexport interface WorkflowVersionAuthor extends UserRef {\n name?: string\n}\n\n/**\n * One row of a workflow's version history (newest first). Lightweight — the\n * graph itself is fetched per version via `getVersion`.\n */\nexport interface WorkflowVersionSummary {\n version: number\n nodes_total: number\n created_at: string\n created_by: WorkflowVersionAuthor\n}\n\n/**\n * One immutable, fully materialized workflow version: the graph exactly as it\n * was saved at that version. Versions are append-only — restoring an old\n * version writes its graph as a NEW bumped version, never rewrites history.\n */\nexport interface WorkflowVersion {\n org_id: string\n workflow_key: string\n version: number\n graph: WorkflowGraph\n created_at: string\n created_by: WorkflowVersionAuthor\n}\n\n// ---------------------------------------------------------------------------\n// Execution\n// ---------------------------------------------------------------------------\n\n/**\n * Coarse status of one workflow firing (and of one node run — `skipped` is\n * node-execution-only: the node never ran because no items reached it).\n */\nexport type ExecutionStatus =\n | 'pending'\n | 'running'\n | 'succeeded'\n | 'failed'\n | 'cancelled'\n | 'skipped'\n\nexport type TriggerKind =\n | 'schedule'\n | 'manual'\n | 'webhook'\n | 'event'\n | 'message'\n | 'connector'\n | 'platform_event'\n | 'workflow'\n\n/**\n * Why and how an execution fired. Flat, kind-discriminated: `kind` selects\n * which optional fields are meaningful. `payload` carries the trigger's data\n * payload and seeds the workflow's first item.\n */\nexport interface ExecutionTriggerContext {\n kind: TriggerKind\n // schedule\n scheduled_at?: string\n // manual — the actor, and the partial-run bound when `destination_node_id` was passed\n actor?: UserRef\n destination_node_id?: string\n // webhook\n received_at?: string\n // event\n topic?: string\n event_type?: string\n record_id?: string\n // message\n conversation_id?: string\n channel?: string\n // connector\n connector_key?: string\n connection_id?: string\n // workflow (child executions)\n parent_execution_id?: string\n payload?: unknown\n}\n\nexport interface ExecutionError {\n code: string\n message: string\n /** Machine-readable payload of the node error (a held send's earliest_allowed_at / rule_id, http_status …). */\n details?: Record<string, unknown>\n /** Marks business failures the user can fix, vs infrastructure faults. */\n is_user_error?: boolean\n}\n\n/**\n * One firing of a Workflow. It pins the immutable workflow version it ran\n * against; per-node results live in the append-only NodeExecution rows keyed\n * by (execution_id, node_id, run_index).\n */\nexport interface WorkflowExecution {\n org_id: string\n id: string\n workflow_key: string\n workflow_version: number\n status: ExecutionStatus\n trigger_context: ExecutionTriggerContext\n temporal_workflow_id?: string\n temporal_run_id?: string\n error?: ExecutionError\n started_at?: string\n finished_at?: string\n created_at: string\n created_by: UserRef\n}\n\n/**\n * One run of one node within an execution — append-only, a new row per\n * (node_id, run_index) so loops and retries never overwrite history.\n * `item_counts` counts output items per port; `metadata` carries node-specific\n * extras (e.g. the agent session id).\n */\nexport interface NodeExecution {\n org_id: string\n execution_id: string\n node_id: string\n run_index: number\n node_name: string\n node_type: NodeTypeKey\n status: ExecutionStatus\n input_counts?: Record<string, number>\n item_counts?: Record<string, number>\n error?: ExecutionError\n metadata?: Record<string, unknown>\n started_at?: string\n finished_at?: string\n created_at: string\n}\n\nexport interface ListExecutionsOptions extends ListOptions {\n workflow_key?: string\n status?: ExecutionStatus\n}\n\n// ---------------------------------------------------------------------------\n// Execution API shapes\n// ---------------------------------------------------------------------------\n\n/**\n * Execution detail: the header row plus its append-only node executions.\n * `nodes_total` is the number of nodes the pinned graph schedules for THIS run\n * (reachable from the trigger, scoped to the destination path on a partial run;\n * dead-branch and disabled nodes end as `skipped` rows) — the progress\n * denominator.\n */\nexport interface GetExecutionDetailResponse {\n execution: WorkflowExecution\n node_executions: NodeExecution[]\n nodes_total: number\n}\n\n/** Windows into one node run's stored items on one port. */\nexport interface GetNodeExecutionItemsOptions {\n port?: string\n /**\n * Which side of the node run to read: its own output ports (default) or the\n * mirrored copy of what fed it.\n */\n side?: 'input' | 'output'\n offset?: number\n limit?: number\n}\n\n/** One window of items plus the true total. */\nexport interface GetNodeExecutionItemsResponse {\n items: Item[]\n items_total: number\n offset: number\n limit: number\n}\n","import type { ProteosClient } from '../client.js'\nimport { type ExecutionService, ExecutionServiceImpl } from './executions.js'\nimport { type NodeTypeService, NodeTypeServiceImpl } from './node-types.js'\nimport { type WorkflowService, WorkflowServiceImpl } from './workflows.js'\n\n/**\n * Client for the Proteos Workflow Service API.\n *\n * Manages n8n-shaped automation workflows (keyed by immutable `key`), the\n * node-type catalog (NodeDescriptors) that drives the editor, and workflow\n * executions (Temporal-backed, surrogate-id'd).\n *\n * @example\n * ```ts\n * import { ProteosClient, WorkflowClient } from '@proteos/sdk';\n *\n * const client = new ProteosClient({ baseUrl, token });\n * const workflow = new WorkflowClient(client);\n *\n * const catalog = await workflow.nodeTypes.list();\n * const workflows = await workflow.workflows.list().all();\n * const execution = await workflow.workflows.run('nightly-triage');\n * const detail = await workflow.executions.getDetail(execution.id);\n * ```\n */\nexport class WorkflowClient {\n /** Service for managing workflow definitions. */\n readonly workflows: WorkflowService\n /** Service for reading workflow executions. */\n readonly executions: ExecutionService\n /** Service for the node-type catalog + dynamic node methods. */\n readonly nodeTypes: NodeTypeService\n\n constructor(client: ProteosClient) {\n this.workflows = new WorkflowServiceImpl(client)\n this.executions = new ExecutionServiceImpl(client)\n this.nodeTypes = new NodeTypeServiceImpl(client)\n }\n}\n\nexport type { ExecutionService } from './executions.js'\nexport type { NodeTypeService } from './node-types.js'\nexport type {\n AgentActionParams,\n BinaryRef,\n ConnectionEndpoint,\n CreateWorkflowRequest,\n CredentialSpec,\n CronTriggerParams,\n DisplayOptions,\n EventTriggerParams,\n EventVerb,\n ExecutionError,\n ExecutionStatus,\n ExecutionTriggerContext,\n GetExecutionDetailResponse,\n GetNodeExecutionItemsOptions,\n GetNodeExecutionItemsResponse,\n GetNodeTypesResponse,\n InvokeNodeMethodRequest,\n InvokeNodeMethodResponse,\n Item,\n KickoffSource,\n KickoffType,\n ListExecutionsOptions,\n ListWorkflowsOptions,\n ManualTriggerParams,\n MessageTriggerParams,\n ModelCallParams,\n NodeDescriptor,\n NodeExecution,\n NodeGroup,\n NodeMethodOption,\n NodePosition,\n NodeProperty,\n NodeRetryPolicy,\n NodeRuntime,\n NodeTypeKey,\n NodeTypeStatus,\n OnErrorPolicy,\n PairedItem,\n PortSpec,\n PropertyOption,\n PropertyType,\n RunWorkflowRequest,\n SystemSource,\n TestNodeCandidate,\n TestNodeInputSource,\n TestNodeRequest,\n TestNodeResponse,\n TriggerKind,\n UpdateWorkflowRequest,\n WebhookTriggerParams,\n Workflow,\n WorkflowConnection,\n WorkflowExecution,\n WorkflowGraph,\n WorkflowNode,\n WorkflowNodeType,\n WorkflowStatus,\n WorkflowVersion,\n WorkflowVersionAuthor,\n WorkflowVersionSummary,\n} from './types.js'\nexport { DEFAULT_PORT, ERROR_PORT } from './types.js'\nexport type { WorkflowService } from './workflows.js'\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/agent/agents.ts","../src/agent/mcp-servers.ts","../src/agent/models.ts","../src/agent/prompts.ts","../src/agent/sessions.ts","../src/agent/skills.ts","../src/agent/tools.ts","../src/agent/toolsets.ts","../src/agent/session-types.ts","../src/agent/index.ts","../src/auth/me.ts","../src/auth/organizations.ts","../src/auth/profiles.ts","../src/auth/roles.ts","../src/errors.ts","../src/auth/shares.ts","../src/auth/teams.ts","../src/auth/user-profile-assignments.ts","../src/auth/user-role-assignments.ts","../src/auth/users.ts","../src/auth/platform-entities.ts","../src/auth/types.ts","../src/auth/index.ts","../src/http/query-params.ts","../src/types/options.ts","../src/client.ts","../src/connector/index.ts","../src/conversation/voice.ts","../src/conversation/types.ts","../src/conversation/index.ts","../src/data/entity-indexes.ts","../src/data/queries.ts","../src/data/record-drafts.ts","../src/data/records.ts","../src/data/types.ts","../src/data/index.ts","../src/discovery/index.ts","../src/enrichment/index.ts","../src/events/index.ts","../src/functions/actions.ts","../src/functions/types.ts","../src/functions/index.ts","../src/knowledge/graph.ts","../src/knowledge/labels.ts","../src/knowledge/links.ts","../src/knowledge/nodes.ts","../src/knowledge/record-links.ts","../src/knowledge/spaces.ts","../src/knowledge/whiteboard-templates.ts","../src/knowledge/types.ts","../src/knowledge/index.ts","../src/scheduling/index.ts","../src/storage/files.ts","../src/storage/index.ts","../src/usage/index.ts","../src/workflow/executions.ts","../src/workflow/node-types.ts","../src/workflow/workflows.ts","../src/workflow/types.ts","../src/workflow/index.ts"],"names":["z","encode","WORKFLOWS_BASE_PATH"],"mappings":";;;;;;AAKA,IAAM,gBAAA,GAAmB,mBAAA;AAqBlB,IAAM,mBAAN,MAA+C;AAAA,EACpD,YAA6B,MAAA,EAAuB;AAAvB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAAwB;AAAA,EAAxB,MAAA;AAAA,EAE7B,IAAA,CAAK,OAAA,GAA6B,EAAC,EAA2C;AAC5E,IAAA,OAAO,IAAI,aAAa,CAAC,IAAA,KAAS,KAAK,QAAA,CAAS,IAAI,GAAG,OAAO,CAAA;AAAA,EAChE;AAAA,EAEA,MAAM,QAAA,CAAS,OAAA,GAA6B,EAAC,EAA+B;AAC1E,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,gBAAA,CAAoC,KAAA,EAAO,kBAAkB,OAAO,CAAA;AAAA,EACzF;AAAA,EAEA,MAAM,IAAI,GAAA,EAA6B;AACrC,IAAA,OAAO,IAAA,CAAK,OAAO,OAAA,CAAe,KAAA,EAAO,GAAG,gBAAgB,CAAA,CAAA,EAAI,GAAG,CAAA,CAAE,CAAA;AAAA,EACvE;AAAA,EAEA,MAAM,OAAO,OAAA,EAA6C;AACxD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAe,MAAA,EAAQ,kBAAkB,OAAO,CAAA;AAAA,EACrE;AAAA,EAEA,MAAM,MAAA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,CAAA;AAAA,MAC7B;AAAA,KACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAA,CAAW,GAAA,EAAa,OAAA,EAA2C;AACvE,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,KAAA;AAAA,MACA,CAAA,EAAGA,oBAAmB,CAAA,CAAA,EAAI,GAAG,aAAa,OAAO,CAAA;AAAA,KACnD;AAAA,EACF;AAAA,EAEA,MAAM,cAAA,CAAe,GAAA,EAAa,OAAA,EAAoC;AACpE,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA;AAAA,MACjB,MAAA;AAAA,MACA,CAAA,EAAGA,oBAAmB,CAAA,CAAA,EAAI,GAAG,aAAa,OAAO,CAAA,QAAA,CAAA;AAAA,MACjD;AAAC,KACH;AAAA,EACF;AACF,CAAA;;;ACjFO,IAAM,YAAA,GAAe;AASrB,IAAM,UAAA,GAAa;;;ACtDnB,IAAM,iBAAN,MAAqB;AAAA;AAAA,EAEjB,SAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EAET,YAAY,MAAA,EAAuB;AACjC,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,mBAAA,CAAoB,MAAM,CAAA;AAC/C,IAAA,IAAA,CAAK,UAAA,GAAa,IAAI,oBAAA,CAAqB,MAAM,CAAA;AACjD,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,mBAAA,CAAoB,MAAM,CAAA;AAAA,EACjD;AACF","file":"index.js","sourcesContent":["import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type { Agent, CreateAgentRequest, ListAgentsOptions, UpdateAgentRequest } from './types.js'\n\nconst AGENTS_BASE_PATH = '/agents/v1/agents'\n\n/**\n * Service for managing Agents — configured personas (system prompt + model\n * config + the skills/tools/sub-agents they can use). Keyed by immutable `key`.\n */\nexport interface AgentService {\n /** Lists agents, auto-paginating. */\n list(options?: ListAgentsOptions): PageIterator<Agent, ListAgentsOptions>\n /** Fetches a single page of agents with pagination metadata. */\n listPage(options?: ListAgentsOptions): Promise<ListResult<Agent>>\n /** Gets a single agent by key. @throws {ProteosError} 404 if not found. */\n get(key: string): Promise<Agent>\n /** Creates a new agent. @throws {ProteosError} 400/409. */\n create(request: CreateAgentRequest): Promise<Agent>\n /** Patches an existing agent (partial). @throws {ProteosError} 404/400. */\n update(key: string, request: UpdateAgentRequest): Promise<Agent>\n /** Deletes an agent. @throws {ProteosError} 404 if not found. */\n delete(key: string): Promise<void>\n}\n\nexport class AgentServiceImpl implements AgentService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListAgentsOptions = {}): PageIterator<Agent, ListAgentsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListAgentsOptions = {}): Promise<ListResult<Agent>> {\n return this.client.requestWithQuery<ListResult<Agent>>('GET', AGENTS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Agent> {\n return this.client.request<Agent>('GET', `${AGENTS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreateAgentRequest): Promise<Agent> {\n return this.client.request<Agent>('POST', AGENTS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateAgentRequest): Promise<Agent> {\n return this.client.request<Agent>('PATCH', `${AGENTS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${AGENTS_BASE_PATH}/${key}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateMcpServerRequest,\n DependentAgent,\n DependentSyncResult,\n ListMcpServersOptions,\n McpConnectionStatus,\n McpServer,\n McpToolSummary,\n StartMcpOAuthResponse,\n UpdateMcpServerRequest,\n} from './types.js'\n\nconst MCP_SERVERS_BASE_PATH = '/agents/v1/mcp-servers'\n\n/**\n * Service for managing MCP Servers — the consumer-side registry of MCP servers\n * an org's agents can call (the source of `kind=mcp` tools). When `auth.is_secret`\n * is set, the token is redacted to `''` on read; send a new token only to change\n * it.\n */\nexport interface McpServerService {\n /** Lists MCP servers, auto-paginating. */\n list(options?: ListMcpServersOptions): PageIterator<McpServer, ListMcpServersOptions>\n /** Fetches a single page of MCP servers with pagination metadata. */\n listPage(options?: ListMcpServersOptions): Promise<ListResult<McpServer>>\n /** Gets a single MCP server by key (token redacted if secret). @throws {ProteosError} 404. */\n get(key: string): Promise<McpServer>\n /** Registers a new MCP server. @throws {ProteosError} 400/409. */\n create(request: CreateMcpServerRequest): Promise<McpServer>\n /** Patches an MCP server (partial). @throws {ProteosError} 404/400. */\n update(key: string, request: UpdateMcpServerRequest): Promise<McpServer>\n /** Deletes an MCP server. @throws {ProteosError} 404. */\n delete(key: string): Promise<void>\n /** Lists the live tools of a (connected) MCP server via tools/list. @throws {ProteosError} 404/502. */\n listTools(key: string): Promise<McpToolSummary[]>\n /** Reports a server's derived OAuth connection state. @throws {ProteosError} 404. */\n getConnectionStatus(key: string): Promise<McpConnectionStatus>\n /** Starts the OAuth connect flow; open the returned `authorization_url` in a popup. @throws {ProteosError} 400/404. */\n startOAuth(key: string): Promise<StartMcpOAuthResponse>\n /** Drops a server's stored OAuth tokens. @throws {ProteosError} 400/404. */\n disconnectOAuth(key: string): Promise<void>\n /**\n * Lists the agents referencing this MCP server, each stamped stale when the MCP server\n * changed after the agent's last successful runtime sync. @throws {ProteosError} 404.\n */\n listDependents(key: string): Promise<DependentAgent[]>\n /**\n * Re-syncs every STALE dependent agent onto the runtime (the one-click \"update\n * dependent agents\" action). Returns a per-agent result. @throws {ProteosError} 404.\n */\n syncDependents(key: string): Promise<DependentSyncResult[]>\n}\n\nexport class McpServerServiceImpl implements McpServerService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListMcpServersOptions = {}): PageIterator<McpServer, ListMcpServersOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListMcpServersOptions = {}): Promise<ListResult<McpServer>> {\n return this.client.requestWithQuery<ListResult<McpServer>>(\n 'GET',\n MCP_SERVERS_BASE_PATH,\n options,\n )\n }\n\n async get(key: string): Promise<McpServer> {\n return this.client.request<McpServer>('GET', `${MCP_SERVERS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreateMcpServerRequest): Promise<McpServer> {\n return this.client.request<McpServer>('POST', MCP_SERVERS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateMcpServerRequest): Promise<McpServer> {\n return this.client.request<McpServer>('PATCH', `${MCP_SERVERS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${MCP_SERVERS_BASE_PATH}/${key}`)\n }\n\n async listTools(key: string): Promise<McpToolSummary[]> {\n const response = await this.client.request<{ data: McpToolSummary[] }>(\n 'GET',\n `${MCP_SERVERS_BASE_PATH}/${key}/tools`,\n )\n return response.data\n }\n\n async getConnectionStatus(key: string): Promise<McpConnectionStatus> {\n const response = await this.client.request<{ data: McpConnectionStatus }>(\n 'GET',\n `${MCP_SERVERS_BASE_PATH}/${key}/connection`,\n )\n return response.data\n }\n\n async startOAuth(key: string): Promise<StartMcpOAuthResponse> {\n return this.client.request<StartMcpOAuthResponse>(\n 'POST',\n `${MCP_SERVERS_BASE_PATH}/${key}/oauth/connect`,\n )\n }\n\n async disconnectOAuth(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${MCP_SERVERS_BASE_PATH}/${key}/oauth/connect`)\n }\n async listDependents(key: string): Promise<DependentAgent[]> {\n const response = await this.client.request<{ data: DependentAgent[] }>(\n 'GET',\n `${MCP_SERVERS_BASE_PATH}/${key}/dependents`,\n )\n return response.data\n }\n\n async syncDependents(key: string): Promise<DependentSyncResult[]> {\n const response = await this.client.request<{ data: DependentSyncResult[] }>(\n 'POST',\n `${MCP_SERVERS_BASE_PATH}/${key}/dependents/sync`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n DecideRequest,\n DecisionQuestions,\n DecisionResult,\n GenerateRequest,\n GenerationResult,\n ModelInfo,\n} from './model-types.js'\n\nconst MODELS_BASE_PATH = '/agents/v1/models'\n\n/**\n * Service for the model catalog and the stateless model calls — one request in,\n * one reply out, no session, no event log:\n *\n * - `list` — the models an agent can be configured with. Needs `agents:read`.\n * - `generate` — free text or schema-constrained structured output from an LLM.\n * - `decide` — calibrated typed answers (boolean | choice | score) with\n * probabilities and confidence, for snap judgments inside code paths\n * (routing, triage, classification, gates). No prose comes back; compose the\n * answers in code and threshold on `confidence`.\n *\n * `generate` and `decide` need the `agent-sessions:write` permission.\n */\nexport interface ModelService {\n /**\n * Lists the models an agent can be configured with: those of the model\n * providers the service has credentials for, each provider's newest first.\n * `runtimes` says which agent runtimes can run a model.\n */\n list(): Promise<ModelInfo[]>\n /**\n * Runs a single model call and returns the assistant message.\n * @throws {ProteosError} 400 `invalid_generation_request` / `unsupported_file_type` /\n * `model_provider_rejected_request`; 429 `model_provider_rate_limited`;\n * 502 `model_provider_failed`.\n */\n generate(request: GenerateRequest): Promise<GenerationResult>\n /**\n * Answers typed questions about a text state with calibrated probabilities.\n * `answers` is typed from the `questions` you pass, so\n * `result.answers.topic.choice` narrows to the option names you declared.\n *\n * Semantic limits (option / level counts, empty questions, unknown model ids)\n * are the provider's and surface as `decision_provider_rejected_request` with\n * its message.\n * @throws {ProteosError} 400 `invalid_decision_request` (shape) /\n * `decision_provider_rejected_request` (provider rule); 429\n * `decision_provider_rate_limited`; 502 `decision_provider_failed` /\n * `decision_provider_invalid_response`; 503 `decision_provider_unavailable`\n * when the provider key is not configured.\n */\n decide<Questions extends DecisionQuestions>(\n request: DecideRequest<Questions>,\n ): Promise<DecisionResult<Questions>>\n}\n\nexport class ModelServiceImpl implements ModelService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<ModelInfo[]> {\n const response = await this.client.request<{ data: ModelInfo[] }>('GET', MODELS_BASE_PATH)\n return response.data\n }\n\n async generate(request: GenerateRequest): Promise<GenerationResult> {\n return this.client.request<GenerationResult>('POST', `${MODELS_BASE_PATH}/generate`, request)\n }\n\n async decide<Questions extends DecisionQuestions>(\n request: DecideRequest<Questions>,\n ): Promise<DecisionResult<Questions>> {\n return this.client.request<DecisionResult<Questions>>(\n 'POST',\n `${MODELS_BASE_PATH}/decide`,\n request,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreatePromptRequest,\n DependentAgent,\n DependentSyncResult,\n ListPromptsOptions,\n Prompt,\n PromptVersion,\n UpdatePromptRequest,\n} from './types.js'\n\nconst PROMPTS_BASE_PATH = '/agents/v1/prompts'\n\n/**\n * Service for managing Prompts — reusable, Liquid-templated instruction texts,\n * versioned like storage files. A `body` change on update forks a new immutable\n * version; metadata-only updates do not.\n */\nexport interface PromptService {\n /** Lists prompts, auto-paginating. */\n list(options?: ListPromptsOptions): PageIterator<Prompt, ListPromptsOptions>\n /** Fetches a single page of prompts with pagination metadata. */\n listPage(options?: ListPromptsOptions): Promise<ListResult<Prompt>>\n /** Gets a prompt (with its current version) by key. @throws {ProteosError} 404. */\n get(key: string): Promise<Prompt>\n /** Creates a new prompt with version 1. @throws {ProteosError} 400/409. */\n create(request: CreatePromptRequest): Promise<Prompt>\n /** Patches a prompt; a new `body` forks a version. @throws {ProteosError} 404/400. */\n update(key: string, request: UpdatePromptRequest): Promise<Prompt>\n /** Deletes a prompt and all its versions. @throws {ProteosError} 404. */\n delete(key: string): Promise<void>\n /** Lists all immutable versions of a prompt, newest first. */\n listVersions(key: string): Promise<PromptVersion[]>\n /** Gets a specific immutable version by number. @throws {ProteosError} 404. */\n getVersion(key: string, number: number): Promise<PromptVersion>\n /**\n * Lists the agents referencing this prompt, each stamped stale when the prompt\n * changed after the agent's last successful runtime sync. @throws {ProteosError} 404.\n */\n listDependents(key: string): Promise<DependentAgent[]>\n /**\n * Re-syncs every STALE dependent agent onto the runtime (the one-click \"update\n * dependent agents\" action). Returns a per-agent result. @throws {ProteosError} 404.\n */\n syncDependents(key: string): Promise<DependentSyncResult[]>\n}\n\nexport class PromptServiceImpl implements PromptService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListPromptsOptions = {}): PageIterator<Prompt, ListPromptsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListPromptsOptions = {}): Promise<ListResult<Prompt>> {\n return this.client.requestWithQuery<ListResult<Prompt>>('GET', PROMPTS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Prompt> {\n return this.client.request<Prompt>('GET', `${PROMPTS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreatePromptRequest): Promise<Prompt> {\n return this.client.request<Prompt>('POST', PROMPTS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdatePromptRequest): Promise<Prompt> {\n return this.client.request<Prompt>('PATCH', `${PROMPTS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${PROMPTS_BASE_PATH}/${key}`)\n }\n\n async listVersions(key: string): Promise<PromptVersion[]> {\n // The versions endpoint wraps in `{ data }` (no pagination meta).\n const response = await this.client.request<{ data: PromptVersion[] }>(\n 'GET',\n `${PROMPTS_BASE_PATH}/${key}/versions`,\n )\n return response.data\n }\n\n async getVersion(key: string, number: number): Promise<PromptVersion> {\n return this.client.request<PromptVersion>(\n 'GET',\n `${PROMPTS_BASE_PATH}/${key}/versions/${number}`,\n )\n }\n async listDependents(key: string): Promise<DependentAgent[]> {\n const response = await this.client.request<{ data: DependentAgent[] }>(\n 'GET',\n `${PROMPTS_BASE_PATH}/${key}/dependents`,\n )\n return response.data\n }\n\n async syncDependents(key: string): Promise<DependentSyncResult[]> {\n const response = await this.client.request<{ data: DependentSyncResult[] }>(\n 'POST',\n `${PROMPTS_BASE_PATH}/${key}/dependents/sync`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type { RequestOptions } from '../types/options.js'\nimport type {\n AppendEventRequest,\n AppendSpeechRequest,\n ClientToolSchema,\n ContentBlock,\n CreateSessionRequest,\n EndVoiceRequest,\n FileBlock,\n ListSessionsOptions,\n ResultBlock,\n Session,\n SessionDeltaEntry,\n SessionDeltaStreamOptions,\n SessionEvent,\n SessionEventsOptions,\n SessionPreview,\n SessionStreamOptions,\n StartVoiceRequest,\n StartVoiceResponse,\n TransferVoiceRequest,\n TransferVoiceResponse,\n Turn,\n VoiceSession,\n} from './session-types.js'\n\nconst SESSIONS_BASE_PATH = '/agents/v1/sessions'\n\n/**\n * Service for managing agent Sessions — a conversation with a configured Agent,\n * backed by an append-only event log. Covers the full agent-service session\n * surface: CRUD, the durable event history, posting client events, the derived\n * turns projection, and the live SSE stream.\n */\nexport interface SessionService {\n /** Lists sessions, auto-paginating. */\n list(options?: ListSessionsOptions): PageIterator<Session, ListSessionsOptions>\n /** Fetches a single page of sessions with pagination metadata. */\n listPage(options?: ListSessionsOptions): Promise<ListResult<Session>>\n /** Gets a single session by id. @throws {ProteosError} 404 if not found. */\n get(id: string): Promise<Session>\n /** Opens a new session against a configured agent. @throws {ProteosError} 400. */\n create(request: CreateSessionRequest): Promise<Session>\n\n /**\n * Reads a page of the durable event log (Postgres), a forward `after_seq`\n * cursor ordered ascending by default. The live channel is {@link stream}.\n */\n events(id: string, options?: SessionEventsOptions): Promise<SessionEvent[]>\n /** Posts a client (`user.*`) event onto a session. @throws {ProteosError} 400/409. */\n appendEvent(id: string, request: AppendEventRequest): Promise<SessionEvent>\n /** The server-side `GroupByTurn` projection of the full event log. */\n turns(id: string): Promise<Turn[]>\n\n /**\n * Live-tails the session's event stream over SSE, yielding each\n * {@link SessionEvent} as it arrives. Replays from `afterSeq` (exclusive) then\n * follows live; reconnects resume gap-free. Runs until the `AbortSignal` fires.\n */\n stream(id: string, options?: SessionStreamOptions): AsyncGenerator<SessionEvent, void, unknown>\n /**\n * Live-tails the session's delta channel over SSE: every whole event\n * {@link stream} carries, and between them the chunk frames of the message,\n * reasoning or tool call the agent is writing — what a chat renders from while\n * a reply is in progress. Replays from `after` (exclusive) then follows live;\n * reconnects resume from the last entry received. Runs until the `AbortSignal`\n * fires. Tell the two kinds of entry apart with `isDeltaFrame`.\n */\n streamDelta(\n id: string,\n options?: SessionDeltaStreamOptions,\n ): AsyncGenerator<SessionDeltaEntry, void, unknown>\n\n /**\n * Convenience: appends a `user.message` with a single text block. Pass\n * `turnId` (a UUID) to supply the turn's id so the caller can render the\n * message optimistically under an id matching the echoed event.\n */\n sendMessage(id: string, text: string, turnId?: string): Promise<SessionEvent>\n /**\n * Convenience: appends a `user.message` built from optional text and file\n * attachments. Each {@link FileBlock} carries the storage-service `file_id`; the\n * backend uploads it to the model provider and mounts it into the agent's sandbox\n * at send time. Pass `turnId` (a UUID) for optimistic rendering. At least one of\n * `text` / `files` should be present. `context` rides the payload for the model\n * only (see {@link UserMessagePayload.context}). `clientTools` attaches the\n * sending surface's client tools to a session it did not create (see\n * {@link AppendEventRequest.client_tools}). A message to a session whose turn\n * runs is queued for the model; `rejectIfRunning` asks for the 409 instead (see\n * {@link AppendEventRequest.reject_if_running}).\n */\n sendUserMessage(\n id: string,\n input: {\n text?: string\n files?: FileBlock[]\n turnId?: string\n context?: string\n clientTools?: ClientToolSchema[]\n rejectIfRunning?: boolean\n },\n ): Promise<SessionEvent>\n /** Convenience: appends a `user.interrupt` to halt the running turn. */\n interrupt(id: string): Promise<SessionEvent>\n /**\n * Ends the session (`status: 'ended'`). A running turn is interrupted first and\n * the session ends once it has closed, so the returned session can still read\n * `running`. The next `user.message` reopens an ended session.\n */\n end(id: string): Promise<Session>\n /**\n * Makes the live preview of what the session's agent builds in its sandbox\n * reachable for the caller's browser and returns where it is. Starts the\n * session's sandbox when it is stopped; every call returns a new address.\n * Only the person who started the session may call it.\n * @throws {ProteosError} 400 `session_preview_unavailable` for a session\n * that is not on the `sandbox` runtime; 403 `sandbox_session_owner_only`.\n */\n openPreview(id: string): Promise<SessionPreview>\n /**\n * Convenience: appends a `user.tool_result` answering a client tool the agent\n * called (an `agent.tool_use` with `tool_kind: 'client'`). `toolUseId` is that\n * tool-use event's id (carried in the idle event's `event_ids`); the backend\n * relays the result to Anthropic as a `user.custom_tool_result` to resume the turn.\n * `outcome` defaults to `'success'`.\n */\n submitToolResult(\n id: string,\n input: { toolUseId: string; result: ResultBlock[]; outcome?: 'success' | 'error' },\n ): Promise<SessionEvent>\n\n /**\n * Enters voice on a session: sends the WebRTC offer of the page's peer\n * connection and returns the voice provider's answer, so the page never holds\n * the provider's key. The page drives the voice session from then on, reports\n * what is said with {@link appendSpeech}, and leaves with {@link endVoice}. A\n * voice session still active on the session is ended first.\n * @throws {ProteosError} 409 `voice_not_supported` when the session cannot be\n * talked to by voice; 501 `voice_disabled`; 502 `voice_provider_failed`.\n */\n startVoice(id: string, request: StartVoiceRequest): Promise<StartVoiceResponse>\n /**\n * Moves the session's active voice session to a session it delegated to, or\n * to the one that delegated to it: the person was handed over and talks to\n * that session's agent from here on. The page keeps its connection to the\n * voice provider and reports to the target session from then on.\n * @throws {ProteosError} 400 `invalid_voice_request` when the target is\n * neither; 409 `voice_not_supported` when the target is over; 409\n * `voice_session_not_active`.\n */\n transferVoice(id: string, request: TransferVoiceRequest): Promise<TransferVoiceResponse>\n /**\n * Reports what was said in the session's active voice session and returns the\n * events written. With `starts_turn` the last of them is the\n * `user.voice_request` that starts a turn.\n * @throws {ProteosError} 409 `voice_session_not_active`.\n */\n appendSpeech(\n id: string,\n request: AppendSpeechRequest,\n requestOptions?: RequestOptions,\n ): Promise<SessionEvent[]>\n /**\n * Leaves voice. Closing the connection to the voice provider is the page's job.\n * A page that is being closed passes `keepalive` so its last report and its\n * end still arrive.\n * @throws {ProteosError} 409 `voice_session_not_active`.\n */\n endVoice(\n id: string,\n request: EndVoiceRequest,\n requestOptions?: RequestOptions,\n ): Promise<VoiceSession>\n /**\n * The voice provider's recording of an ended voice session of the session, for\n * a session created with `is_voice_recorded`: a WAV file (16-bit PCM, stereo,\n * the person on the left channel and the voice assistant on the right). The\n * ids of a session's voice sessions are in its `session.voice_started` and\n * `session.voice_ended` events. `options.timeout` covers reading the whole\n * file, so raise it for a long recording.\n * @throws {ProteosError} 404 `voice_recording_not_found` when the voice session\n * is not one of this session or was not recorded; 409\n * `voice_recording_not_ready` while the voice session is active or the provider\n * does not have the recording yet (ask again).\n */\n getVoiceRecording(\n id: string,\n voiceSessionId: string,\n requestOptions?: RequestOptions,\n ): Promise<Blob>\n}\n\nexport class SessionServiceImpl implements SessionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListSessionsOptions = {}): PageIterator<Session, ListSessionsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListSessionsOptions = {}): Promise<ListResult<Session>> {\n // The API takes several statuses as one comma-separated value, not as a\n // repeated parameter.\n const query = Array.isArray(options.status)\n ? { ...options, status: options.status.join(',') }\n : options\n return this.client.requestWithQuery<ListResult<Session>>('GET', SESSIONS_BASE_PATH, query)\n }\n\n async get(id: string): Promise<Session> {\n return this.client.request<Session>('GET', `${SESSIONS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateSessionRequest): Promise<Session> {\n return this.client.request<Session>('POST', SESSIONS_BASE_PATH, request)\n }\n\n async events(id: string, options: SessionEventsOptions = {}): Promise<SessionEvent[]> {\n // The backend reads `types` as a single comma-separated query param (a string\n // it splits into a `type IN (...)` filter), so join the array rather than\n // letting the serializer emit repeated `types=` params.\n const { types, ...rest } = options\n const query = {\n ...rest,\n ...(types && types.length > 0 ? { types: types.join(',') } : {}),\n }\n const response = await this.client.requestWithQuery<{ data: SessionEvent[] }>(\n 'GET',\n `${SESSIONS_BASE_PATH}/${id}/events`,\n query,\n )\n return response.data ?? []\n }\n\n async appendEvent(id: string, request: AppendEventRequest): Promise<SessionEvent> {\n return this.client.request<SessionEvent>('POST', `${SESSIONS_BASE_PATH}/${id}/events`, request)\n }\n\n async turns(id: string): Promise<Turn[]> {\n const response = await this.client.request<{ data: Turn[] }>(\n 'GET',\n `${SESSIONS_BASE_PATH}/${id}/turns`,\n )\n return response.data ?? []\n }\n\n async *stream(\n id: string,\n options: SessionStreamOptions = {},\n ): AsyncGenerator<SessionEvent, void, unknown> {\n const query = options.afterSeq ? `?after_seq=${options.afterSeq}` : ''\n const path = `${SESSIONS_BASE_PATH}/${id}/events/stream${query}`\n const streamOptions = options.signal ? { signal: options.signal } : {}\n for await (const frame of this.client.streamEvents(path, streamOptions)) {\n const event = parseEvent(frame.data)\n if (event) yield event\n }\n }\n\n async *streamDelta(\n id: string,\n options: SessionDeltaStreamOptions = {},\n ): AsyncGenerator<SessionDeltaEntry, void, unknown> {\n const after = options.after === undefined || options.after === 0 ? '' : String(options.after)\n const query = after ? `?after_seq=${encodeURIComponent(after)}` : ''\n const path = `${SESSIONS_BASE_PATH}/${id}/events/delta${query}`\n const streamOptions = options.signal ? { signal: options.signal } : {}\n for await (const frame of this.client.streamEvents(path, streamOptions)) {\n const event = parseEvent(frame.data) as SessionDeltaEntry['event'] | null\n if (event && frame.id) yield { position: frame.id, event }\n }\n }\n\n async sendMessage(id: string, text: string, turnId?: string): Promise<SessionEvent> {\n return this.sendUserMessage(id, { text, ...(turnId ? { turnId } : {}) })\n }\n\n async sendUserMessage(\n id: string,\n input: {\n text?: string\n files?: FileBlock[]\n turnId?: string\n context?: string\n clientTools?: ClientToolSchema[]\n rejectIfRunning?: boolean\n },\n ): Promise<SessionEvent> {\n const content: ContentBlock[] = []\n const text = input.text?.trim()\n if (text) content.push({ type: 'text', text })\n for (const file of input.files ?? []) {\n content.push({ type: 'file', ...file })\n }\n const context = input.context?.trim()\n return this.appendEvent(id, {\n type: 'user.message',\n ...(input.turnId ? { turn_id: input.turnId } : {}),\n payload: { content, ...(context ? { context } : {}) },\n ...(input.clientTools?.length ? { client_tools: input.clientTools } : {}),\n ...(input.rejectIfRunning ? { reject_if_running: true } : {}),\n })\n }\n\n async interrupt(id: string): Promise<SessionEvent> {\n return this.appendEvent(id, { type: 'user.interrupt' })\n }\n\n async end(id: string): Promise<Session> {\n return this.client.request<Session>('POST', `${SESSIONS_BASE_PATH}/${id}/end`)\n }\n\n async openPreview(id: string): Promise<SessionPreview> {\n return this.client.request<SessionPreview>('POST', `${SESSIONS_BASE_PATH}/${id}/preview`)\n }\n\n async submitToolResult(\n id: string,\n input: { toolUseId: string; result: ResultBlock[]; outcome?: 'success' | 'error' },\n ): Promise<SessionEvent> {\n return this.appendEvent(id, {\n type: 'user.tool_result',\n payload: {\n tool_use_id: input.toolUseId,\n result: input.result,\n outcome: input.outcome ?? 'success',\n },\n })\n }\n\n async startVoice(id: string, request: StartVoiceRequest): Promise<StartVoiceResponse> {\n return this.client.request<StartVoiceResponse>(\n 'POST',\n `${SESSIONS_BASE_PATH}/${id}/voice`,\n request,\n )\n }\n\n async transferVoice(id: string, request: TransferVoiceRequest): Promise<TransferVoiceResponse> {\n return this.client.request<TransferVoiceResponse>(\n 'POST',\n `${SESSIONS_BASE_PATH}/${id}/voice/transfer`,\n request,\n )\n }\n\n async appendSpeech(\n id: string,\n request: AppendSpeechRequest,\n requestOptions?: RequestOptions,\n ): Promise<SessionEvent[]> {\n const response = await this.client.request<{ data: SessionEvent[] }>(\n 'POST',\n `${SESSIONS_BASE_PATH}/${id}/voice/speech`,\n request,\n requestOptions,\n )\n return response.data\n }\n\n async endVoice(\n id: string,\n request: EndVoiceRequest,\n requestOptions?: RequestOptions,\n ): Promise<VoiceSession> {\n return this.client.request<VoiceSession>(\n 'DELETE',\n `${SESSIONS_BASE_PATH}/${id}/voice`,\n request,\n requestOptions,\n )\n }\n\n async getVoiceRecording(\n id: string,\n voiceSessionId: string,\n requestOptions?: RequestOptions,\n ): Promise<Blob> {\n const { response } = await this.client.requestRaw(\n 'GET',\n `${SESSIONS_BASE_PATH}/${id}/voice/${voiceSessionId}/recording`,\n undefined,\n requestOptions,\n )\n return await response.blob()\n }\n}\n\n/**\n * Parses one SSE frame's `data` into a SessionEvent, returning null for an empty\n * or unparseable frame — a single bad frame is skipped, not fatal to the stream.\n */\nfunction parseEvent(data: string): SessionEvent | null {\n if (!data) return null\n try {\n return JSON.parse(data) as SessionEvent\n } catch {\n return null\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n DependentAgent,\n DependentSyncResult,\n ListSkillsOptions,\n Skill,\n SkillVersion,\n} from './types.js'\n\nconst SKILLS_BASE_PATH = '/agents/v1/skills'\n\n/**\n * Service for managing Skills — versioned bundles of instructions + files in the\n * Anthropic Agent-Skills shape. Skills are created and updated only via\n * {@link SkillService.deploy} (a multipart bundle upload); there is no JSON\n * create/update.\n */\nexport interface SkillService {\n /** Lists skills, auto-paginating. */\n list(options?: ListSkillsOptions): PageIterator<Skill, ListSkillsOptions>\n /** Fetches a single page of skills with pagination metadata. */\n listPage(options?: ListSkillsOptions): Promise<ListResult<Skill>>\n /** Gets a skill (with its current version + bundle pin) by key. @throws {ProteosError} 404. */\n get(key: string): Promise<Skill>\n /**\n * Deploys a skill bundle (a `.tar.gz` containing `SKILL.md` at the root plus\n * supporting files). The skill's key — its canonical identifier — is read\n * from the bundle's `SKILL.md` frontmatter `name`, so no key is supplied here.\n * Creates the skill on first deploy and a new immutable version each time.\n *\n * @param bundle - The `.tar.gz` bundle bytes.\n * @param options.displayName - Optional human-readable display name.\n * @param options.moduleSlug - Optional owning module slug (tags the skill so it\n * can be filtered + round-tripped by module). Empty for a standalone deploy.\n */\n deploy(\n bundle: Blob | File,\n options?: { displayName?: string; moduleSlug?: string },\n ): Promise<Skill>\n /** Deletes a skill and all its versions. @throws {ProteosError} 404. */\n delete(key: string): Promise<void>\n /** Lists all immutable versions of a skill, newest first. */\n listVersions(key: string): Promise<SkillVersion[]>\n /** Gets a specific immutable version by number. @throws {ProteosError} 404. */\n getVersion(key: string, number: number): Promise<SkillVersion>\n /**\n * Lists the agents referencing this skill, each stamped stale when the skill\n * changed after the agent's last successful runtime sync. @throws {ProteosError} 404.\n */\n listDependents(key: string): Promise<DependentAgent[]>\n /**\n * Re-syncs every STALE dependent agent onto the runtime (the one-click \"update\n * dependent agents\" action). Returns a per-agent result. @throws {ProteosError} 404.\n */\n syncDependents(key: string): Promise<DependentSyncResult[]>\n}\n\nexport class SkillServiceImpl implements SkillService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListSkillsOptions = {}): PageIterator<Skill, ListSkillsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListSkillsOptions = {}): Promise<ListResult<Skill>> {\n return this.client.requestWithQuery<ListResult<Skill>>('GET', SKILLS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Skill> {\n return this.client.request<Skill>('GET', `${SKILLS_BASE_PATH}/${key}`)\n }\n\n async deploy(\n bundle: Blob | File,\n options?: { displayName?: string; moduleSlug?: string },\n ): Promise<Skill> {\n const formData = new FormData()\n const filename = bundle instanceof File ? bundle.name : 'skill.tar.gz'\n formData.append('bundle', bundle, filename)\n if (options?.displayName) {\n formData.append('display_name', options.displayName)\n }\n if (options?.moduleSlug) {\n formData.append('module_slug', options.moduleSlug)\n }\n // Returns a bare Skill (no `{ data }` envelope). The key is derived from the\n // bundle's SKILL.md frontmatter server-side.\n return this.client.requestMultipart<Skill>('POST', `${SKILLS_BASE_PATH}/deploy`, formData)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${SKILLS_BASE_PATH}/${key}`)\n }\n\n async listVersions(key: string): Promise<SkillVersion[]> {\n const response = await this.client.request<{ data: SkillVersion[] }>(\n 'GET',\n `${SKILLS_BASE_PATH}/${key}/versions`,\n )\n return response.data\n }\n\n async getVersion(key: string, number: number): Promise<SkillVersion> {\n return this.client.request<SkillVersion>('GET', `${SKILLS_BASE_PATH}/${key}/versions/${number}`)\n }\n async listDependents(key: string): Promise<DependentAgent[]> {\n const response = await this.client.request<{ data: DependentAgent[] }>(\n 'GET',\n `${SKILLS_BASE_PATH}/${key}/dependents`,\n )\n return response.data\n }\n\n async syncDependents(key: string): Promise<DependentSyncResult[]> {\n const response = await this.client.request<{ data: DependentSyncResult[] }>(\n 'POST',\n `${SKILLS_BASE_PATH}/${key}/dependents/sync`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateToolRequest,\n DependentAgent,\n DependentSyncResult,\n ListToolsOptions,\n Tool,\n UpdateToolRequest,\n} from './types.js'\n\nconst TOOLS_BASE_PATH = '/agents/v1/tools'\n\n/**\n * Service for managing Tools — thin registry entries over one of three binding\n * sources (action / mcp / client). `update` fully replaces the definition.\n */\nexport interface ToolService {\n /** Lists tools, auto-paginating. Filterable by `kind`. */\n list(options?: ListToolsOptions): PageIterator<Tool, ListToolsOptions>\n /** Fetches a single page of tools with pagination metadata. */\n listPage(options?: ListToolsOptions): Promise<ListResult<Tool>>\n /** Gets a single tool by key. @throws {ProteosError} 404. */\n get(key: string): Promise<Tool>\n /** Creates a new tool. @throws {ProteosError} 400/409. */\n create(request: CreateToolRequest): Promise<Tool>\n /** Fully replaces a tool's definition. @throws {ProteosError} 404/400. */\n update(key: string, request: UpdateToolRequest): Promise<Tool>\n /** Deletes a tool. @throws {ProteosError} 404. */\n delete(key: string): Promise<void>\n /**\n * Lists the agents referencing this tool, each stamped stale when the tool\n * changed after the agent's last successful runtime sync. @throws {ProteosError} 404.\n */\n listDependents(key: string): Promise<DependentAgent[]>\n /**\n * Re-syncs every STALE dependent agent onto the runtime (the one-click \"update\n * dependent agents\" action). Returns a per-agent result. @throws {ProteosError} 404.\n */\n syncDependents(key: string): Promise<DependentSyncResult[]>\n}\n\nexport class ToolServiceImpl implements ToolService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListToolsOptions = {}): PageIterator<Tool, ListToolsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListToolsOptions = {}): Promise<ListResult<Tool>> {\n return this.client.requestWithQuery<ListResult<Tool>>('GET', TOOLS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Tool> {\n return this.client.request<Tool>('GET', `${TOOLS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreateToolRequest): Promise<Tool> {\n return this.client.request<Tool>('POST', TOOLS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateToolRequest): Promise<Tool> {\n return this.client.request<Tool>('PATCH', `${TOOLS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${TOOLS_BASE_PATH}/${key}`)\n }\n async listDependents(key: string): Promise<DependentAgent[]> {\n const response = await this.client.request<{ data: DependentAgent[] }>(\n 'GET',\n `${TOOLS_BASE_PATH}/${key}/dependents`,\n )\n return response.data\n }\n\n async syncDependents(key: string): Promise<DependentSyncResult[]> {\n const response = await this.client.request<{ data: DependentSyncResult[] }>(\n 'POST',\n `${TOOLS_BASE_PATH}/${key}/dependents/sync`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateToolsetRequest,\n ListToolsetsOptions,\n Toolset,\n ToolsetToolSummary,\n UpdateToolsetRequest,\n} from './types.js'\n\nconst TOOLSETS_BASE_PATH = '/agents/v1/toolsets'\nconst PLATFORM_TOOLS_PATH = '/agents/v1/platform-tools'\n\n/**\n * Service for managing Toolsets — the hardcoded platform toolsets (read-only)\n * merged with the org's custom groups of its own tools. Writes apply to custom\n * toolsets only; a platform key is rejected with `toolset_read_only`.\n */\nexport interface ToolsetService {\n /** Lists toolsets (platform + custom merged), auto-paginating. Filterable by `kind`. */\n list(options?: ListToolsetsOptions): PageIterator<Toolset, ListToolsetsOptions>\n /** Fetches a single page of toolsets with pagination metadata. */\n listPage(options?: ListToolsetsOptions): Promise<ListResult<Toolset>>\n /** Gets a single toolset by key (platform or custom). @throws {ProteosError} 404. */\n get(key: string): Promise<Toolset>\n /**\n * Lists the tools inside a toolset — platform members proxied from the\n * platform MCP server, custom members summarized from the org's Tool rows.\n * @throws {ProteosError} 404.\n */\n listTools(key: string): Promise<ToolsetToolSummary[]>\n /**\n * Lists every platform tool once, each with the platform toolset that serves\n * it. An agent may list any of these names in its `tools` as it is: no Tool\n * of that key is needed. A Tool the org saves under the same key replaces the\n * platform tool for its agents. A name several toolsets serve is the first\n * one's, in the order `list({ kind: 'platform' })` returns them.\n */\n listPlatformTools(): Promise<ToolsetToolSummary[]>\n /** Creates a custom toolset. @throws {ProteosError} 400/409. */\n create(request: CreateToolsetRequest): Promise<Toolset>\n /** Fully replaces a custom toolset's definition. @throws {ProteosError} 404/400. */\n update(key: string, request: UpdateToolsetRequest): Promise<Toolset>\n /** Creates or fully replaces a custom toolset (idempotent deploy entry point). */\n upsert(key: string, request: CreateToolsetRequest): Promise<Toolset>\n /** Deletes a custom toolset. @throws {ProteosError} 404/400. */\n delete(key: string): Promise<void>\n}\n\nexport class ToolsetServiceImpl implements ToolsetService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListToolsetsOptions = {}): PageIterator<Toolset, ListToolsetsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListToolsetsOptions = {}): Promise<ListResult<Toolset>> {\n return this.client.requestWithQuery<ListResult<Toolset>>('GET', TOOLSETS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Toolset> {\n return this.client.request<Toolset>('GET', `${TOOLSETS_BASE_PATH}/${key}`)\n }\n\n async listTools(key: string): Promise<ToolsetToolSummary[]> {\n const response = await this.client.request<{ data: ToolsetToolSummary[] }>(\n 'GET',\n `${TOOLSETS_BASE_PATH}/${key}/tools`,\n )\n return response.data\n }\n\n async listPlatformTools(): Promise<ToolsetToolSummary[]> {\n const response = await this.client.request<{ data: ToolsetToolSummary[] }>(\n 'GET',\n PLATFORM_TOOLS_PATH,\n )\n return response.data\n }\n\n async create(request: CreateToolsetRequest): Promise<Toolset> {\n return this.client.request<Toolset>('POST', TOOLSETS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateToolsetRequest): Promise<Toolset> {\n return this.client.request<Toolset>('PATCH', `${TOOLSETS_BASE_PATH}/${key}`, request)\n }\n\n async upsert(key: string, request: CreateToolsetRequest): Promise<Toolset> {\n return this.client.request<Toolset>('PUT', `${TOOLSETS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${TOOLSETS_BASE_PATH}/${key}`)\n }\n}\n","/**\n * Types for the agent-service Sessions API — a conversation with a configured\n * Agent.\n *\n * Hand-written mirror of the Go models in `go.proteos.ai/model/agent`\n * (`session.go`, `session-event.go`, `session-event-type.go`, `session-payload.go`,\n * `session-content.go` + `api/session-requests.go`). Field names match the\n * snake_case wire format exactly, including enum values.\n *\n * A Session is a thin mutable parent over an append-only `SessionEvent` log: the\n * events are the source of truth, the session carries only identity, the agent it\n * runs, a title and the latest lifecycle status. A {@link Turn} is a derived\n * projection of the log (never stored).\n */\n\nimport type { AuditFields, ListOptions, UserRef } from '../types/common.js'\nimport type { AgentRuntime, AgentVoiceStyle, ToolKind } from './types.js'\n\nexport type { ToolKind } from './types.js'\n\n// ---------------------------------------------------------------------------\n// Session\n// ---------------------------------------------------------------------------\n\n/**\n * The latest lifecycle state of a session, projected from the `session.status_*`\n * events. `idle` = ready for the next user message; `running` = a turn is in\n * flight; `terminated` = the provider session is gone; `error` = the last turn\n * failed; `ended` = a person ended it — the next `user.message` reopens it.\n */\nexport type SessionStatus = 'idle' | 'running' | 'terminated' | 'error' | 'ended'\n\n/**\n * The rolled-up token accounting for a session — the sum of every model request's\n * usage plus the request count, projected from the `span.model_request_end` events\n * and kept on the session row so listings/headers can show cost without replaying\n * the log. `total_tokens` is the derived input+output sum.\n *\n * `model` is the model the usage is attributed to. Managed Agents reports no model\n * id on its usage events, so it is seeded once at session create from the agent's\n * configured model and preserved across recomputes (empty on sessions created\n * before usage tracking existed).\n */\nexport interface SessionUsage {\n model: string\n input_tokens: number\n output_tokens: number\n cache_read_input_tokens: number\n cache_creation_input_tokens: number\n total_tokens: number\n request_count: number\n}\n\n/**\n * One conversation with a configured Agent. Surrogate-keyed by `id` (a session is\n * a graph node referenced by every event). `status` is denormalized from the\n * event log for cheap listing; `usage` is the denormalized token total.\n */\nexport interface Session extends AuditFields {\n org_id: string\n id: string\n agent_key: string\n /** What runs this session: the agent's runtime when the session was created. */\n runtime: AgentRuntime\n /**\n * Set on a delegated session: the session whose agent handed this one its work\n * with the `delegate` tool, and whose log gets a `delegated_session.updated`\n * event when a turn of this one ends. Null for a session a person or a surface\n * opened.\n */\n parent_session_id: string | null\n title: string\n status: SessionStatus\n usage: SessionUsage\n /** When the session was ended; null unless `status` is `ended`. */\n ended_at: string | null\n /** Who ended it; null unless `status` is `ended` (and on sessions ended by the platform). */\n ended_by: UserRef | null\n /**\n * Whether the voice provider records the voice sessions of this session (see\n * {@link CreateSessionRequest.is_voice_recorded}). Set at create, never changed.\n */\n is_voice_recorded: boolean\n}\n\n/**\n * What a session's preview shows: `serving` at `url`; `no_module` when the\n * session's sandbox holds no module to preview yet; `not_started` when the\n * session has no sandbox yet (its first message creates one).\n */\nexport type SessionPreviewStatus = 'serving' | 'no_module' | 'not_started'\n\n/**\n * The live preview of the module an agent works on in its session's sandbox\n * (sessions on the `sandbox` runtime), as a page to show in a frame.\n */\nexport interface SessionPreview {\n status: SessionPreviewStatus\n /**\n * The preview's address; null unless `status` is `serving`. The address is\n * the whole credential: whoever has it sees the preview until `expires_at`,\n * so show it to the session's owner only and do not store it.\n */\n url: string | null\n /** When `url` stops working (RFC 3339); null without one. */\n expires_at: string | null\n}\n\n// ---------------------------------------------------------------------------\n// Event types (the discriminant)\n// ---------------------------------------------------------------------------\n\n/**\n * The discriminant of a {@link SessionEvent} — it selects which payload shape the\n * event carries. These are the WHOLE events of the stored log; the chunk frames\n * of an event still being written are {@link DeltaEventType}.\n */\nexport type EventType =\n // User-originated (posted via the API or echoed back by the provider).\n | 'user.message'\n | 'user.interrupt'\n | 'user.tool_confirmation'\n | 'user.tool_result'\n // Voice: what was said aloud, and the voice assistant handing a request over.\n | 'user.speech'\n | 'user.voice_request'\n // Agent-originated.\n | 'agent.message'\n | 'agent.speech'\n | 'agent.reasoning'\n | 'agent.tool_use'\n | 'agent.tool_result'\n | 'agent.context_compacted'\n | 'agent.artifacts'\n // Session lifecycle.\n | 'session.status_running'\n | 'session.status_idle'\n | 'session.status_terminated'\n | 'session.status_ended'\n | 'session.error'\n | 'session.updated'\n | 'session.voice_started'\n | 'session.voice_ended'\n // The service asking the agent to open the conversation; shows nothing.\n // A report on a session this one delegated to.\n | 'delegated_session.updated'\n // Span (observability).\n | 'span.model_request_start'\n | 'span.model_request_end'\n\n/**\n * The client-postable subset (everything else is produced by the runtime). The\n * voice events are written by the voice routes, never posted as events.\n */\nexport type ClientEventType =\n | 'user.message'\n | 'user.interrupt'\n | 'user.tool_confirmation'\n | 'user.tool_result'\n\n// ---------------------------------------------------------------------------\n// Content blocks (the self-tagged pieces of heterogeneous payloads)\n// ---------------------------------------------------------------------------\n\n/** A plain text block. Agent messages are text-only. */\nexport interface TextBlock {\n type: 'text'\n text: string\n}\n\n/**\n * A file value object: a reference to a stored File (storage-service) plus light\n * metadata. Embedded inline in a user-message {@link ContentBlock} (`type=file`)\n * and nested under `image` in a tool {@link ResultBlock}.\n */\nexport interface FileBlock {\n file_id?: string\n file_name?: string\n mime_type?: string\n size_in_bytes?: number\n}\n\n/**\n * One block of a user/agent message body. For `type=text` only `text` is set; for\n * `type=file` the {@link FileBlock} fields are promoted inline.\n */\nexport interface ContentBlock extends FileBlock {\n type: 'text' | 'file'\n text?: string\n}\n\n/**\n * One block of a tool result. Unlike message file blocks, an image nests its file\n * under `image`; `json` carries an arbitrary raw object.\n */\nexport interface ResultBlock {\n type: 'text' | 'image' | 'file' | 'json'\n text?: string\n /** A stored image (type `image`). The model sees it when it reads images. */\n image?: FileBlock\n /** Any other stored file, such as a PDF (type `file`). */\n file?: FileBlock\n json?: unknown\n}\n\n// ---------------------------------------------------------------------------\n// Event payloads (discriminated by the sibling event `type`)\n// ---------------------------------------------------------------------------\n\n/**\n * A user message body (text + file blocks). `context` is what the launching\n * surface hands the model alongside the message (a call's summary and linked\n * records, say): stored with the event, sent to the model as an extra text\n * block, never rendered as part of the person's message. On the first message\n * of a session whose agent has memory, the service appends the owner's memory\n * block to it. Not for secrets: everyone who can read the session reads it back\n * through the events API.\n */\nexport interface UserMessagePayload {\n content: ContentBlock[]\n context?: string\n}\n\n/** An agent message body (text blocks only). */\nexport interface AgentMessagePayload {\n content: TextBlock[]\n}\n\n/**\n * Files the agent produced in its sandbox this turn (reconciled from the session\n * outputs), surfaced as downloadable attachments on the agent turn. A turn can\n * produce several. Each {@link FileBlock} carries the storage-service `file_id`.\n */\nexport interface AgentArtifactsPayload {\n files: FileBlock[]\n}\n\n/**\n * An agent reasoning (\"thinking\") block. v1 whole-events carry no text/signature\n * from the provider, so both are typically empty. `signature` is opaque: it\n * means something only to the model `provider` that wrote the block.\n */\nexport interface ReasoningPayload {\n text: string\n signature?: string\n provider?: string\n}\n\n/**\n * A tool invocation. `id` is the provider's tool_use event id — the correlation\n * key a matching {@link ToolResultPayload}'s `tool_use_id` points back to.\n * `tool_kind` is the execution location (action | mcp | client).\n */\nexport interface ToolUsePayload {\n id: string\n name: string\n input: unknown\n tool_kind: SessionToolKind\n}\n\n/**\n * Where a tool a session's agent called is run. Besides the kinds a registered\n * tool can have ({@link ToolKind}), a session whose agent can delegate has the\n * `delegation` tools (`delegate`, `list_delegated_sessions`, …), which the agent\n * service runs itself and which cannot be registered. Every agent also has the\n * `system` tools (`new_phase`), which the agent service answers itself and which\n * cannot be registered either.\n */\nexport type SessionToolKind = ToolKind | 'delegation' | 'system'\n\n/** The result of a tool invocation, linked to its use by `tool_use_id`. */\nexport interface ToolResultPayload {\n tool_use_id: string\n result: ResultBlock[]\n /** \"success\" | \"error\" (open string for forward-compat). */\n outcome: string\n}\n\n/** A user's decision on a tool that requested approval. */\nexport interface ToolConfirmationPayload {\n tool_use_id: string\n /** \"approved\" | \"denied\" (open string for forward-compat). */\n decision: string\n}\n\n/**\n * Announces that earlier context was summarized. On the embedded runtime the\n * agent continues from `summary` in place of the events up to and including seq\n * `through_seq`; the events themselves stay in the log. A durable session's\n * provider compacts on its own and sets neither.\n */\nexport interface ContextCompactedPayload {\n summary: string\n through_seq?: number\n}\n\n/** A session-level error. */\nexport interface ErrorPayload {\n message: string\n code?: string\n}\n\n/**\n * Why a turn went idle. `type` is an open string (\"turn_ended\" |\n * \"user_action_required\" | \"budget_reached\" | …) so new provider reasons don't\n * break decoding. \"budget_reached\": the session used up the spend ceiling it was\n * created with; a message sent to it is refused (409 `session_budget_reached`).\n */\nexport interface StopReason {\n type: string\n}\n\n/**\n * Ends a turn — published once per turn by the server, not an echo of the upstream\n * provider's session status (which flips idle/running once per server-side tool\n * round, mid-turn).\n *\n * `event_ids` is set only with `stop_reason.type: 'user_action_required'`, and lists\n * the tool_use events still OUTSTANDING — the ones a client must answer. Tools the\n * server executes itself are resolved before this event exists, so seeing this event\n * at all means the turn cannot continue without you: answer each id with a\n * `user.tool_result`.\n */\nexport interface SessionIdlePayload {\n stop_reason: StopReason\n event_ids?: string[]\n}\n\n/**\n * A server-side session metadata change — v1 carries the (often auto-generated)\n * title. Projected onto {@link Session.title}; emitted only when the title changed.\n */\nexport interface SessionUpdatedPayload {\n title?: string\n}\n\n/** A tool call a session is waiting on: what it asks, for whoever answers it. */\nexport interface AwaitingToolUse {\n tool_use_id: string\n name: string\n input: unknown\n}\n\n/**\n * Where a delegated session stands at the end of one of its turns, written to the\n * log of the session that delegated to it (see {@link Session.parent_session_id}).\n *\n * `status` is the delegated session's status at that moment. `stop_reason` is set\n * only with status `idle`: `turn_ended`, or `user_action_required` when it waits\n * for an answer, in which case `awaiting_tool_uses` lists the calls it waits on.\n * `summary` is the last thing its agent wrote, cut to a bound; the whole\n * conversation is in the delegated session. `is_stopped_by_parent` is true when\n * the delegating agent interrupted the turn itself. `is_handed_back` is true when\n * the person was talking to the delegated agent in its session and that agent\n * handed them back (the `hand_back_session` client tool); `summary` is then what\n * the agent gave the delegating agent with that call, when it gave one.\n */\nexport interface DelegatedSessionUpdatedPayload {\n session_id: string\n agent_key: string\n title: string\n status: SessionStatus\n stop_reason?: StopReason\n awaiting_tool_uses?: AwaitingToolUse[]\n is_stopped_by_parent?: boolean\n is_handed_back?: boolean\n summary: string\n}\n\n/**\n * One utterance of a voice session, of the person (`user.speech`) or of the voice\n * assistant (`agent.speech`): the text as the voice provider transcribed it, and\n * when it was said, in milliseconds from the start of the voice session. Speech\n * starts no turn; the agent reads it with what opens the next one.\n */\nexport interface SpeechPayload {\n voice_session_id: string\n text: string\n start_ms: number\n end_ms: number\n}\n\n/**\n * The voice assistant handing what the person asked for to the agent: it starts a\n * turn, or is queued behind the one that runs, like a `user.message`. The request\n * itself is the speech before the event.\n */\nexport interface VoiceRequestPayload {\n voice_session_id: string\n /** The voice model's delegation the request is of, as the page reported it.\n * The page speaks the turn's answer as that delegation's result. */\n delegation_id?: string\n /** Model-only text the page sent with the request; never rendered. */\n context?: string\n}\n\n/**\n * Voice was entered on the session. `transferred_from_session_id` is set when\n * it was not entered here but came with the person: the session they were\n * handed over from, or handed back from.\n */\nexport interface VoiceStartedPayload {\n voice_session_id: string\n transferred_from_session_id?: string\n}\n\n/**\n * Why a voice session ended. `superseded` and `transferred` are never reported\n * by a page. `transferred` is the reason of the `session.voice_ended` in the log\n * of a session the person was handed over from: the voice session itself goes on\n * in the session they were handed to.\n */\nexport type VoiceEndReason =\n | 'user'\n | 'idle'\n | 'max_duration'\n | 'session_ended'\n | 'browser_left'\n | 'provider_closed'\n | 'superseded'\n | 'transferred'\n\n/**\n * Voice was left: why, and how long the voice session lasted: what the voice\n * provider says, or the time since voice was entered when the page went away\n * without it (null when nobody learned it). With `transferred` the voice session\n * goes on in `transferred_to_session_id`, and no duration is known yet.\n */\nexport interface VoiceEndedPayload {\n voice_session_id: string\n end_reason: VoiceEndReason\n duration_seconds: number | null\n transferred_to_session_id?: string\n}\n\n/** Opens a model-request span. */\nexport interface ModelRequestStartPayload {\n model_id: string\n}\n\n/** Per-request token accounting. */\nexport interface ModelUsage {\n input_tokens: number\n output_tokens: number\n cache_read_input_tokens?: number\n cache_creation_input_tokens?: number\n}\n\n/** Closes a model-request span with usage. */\nexport interface ModelRequestEndPayload {\n model_usage: ModelUsage\n}\n\n/**\n * Opens a turn. `acting_user_id` is the person the turn's tools run as, which is\n * not always the author of the message that opened it (a message an agent posts\n * to a session it delegated to). Absent on turns started before it was recorded.\n */\nexport interface SessionRunningPayload {\n acting_user_id?: string\n}\n\n/**\n * The body of events that carry no fields (`user.interrupt`,\n * `session.status_terminated`, `session.status_ended`).\n */\nexport type EmptyPayload = Record<string, never>\n\n// ---------------------------------------------------------------------------\n// SessionEvent (the append-only log envelope)\n// ---------------------------------------------------------------------------\n\n/** Shared envelope fields carried by every {@link SessionEvent}. */\nexport interface SessionEventEnvelope {\n /** Dedupe key: our uuid for user events, the provider's id for agent events. */\n id: string\n session_id: string\n org_id: string\n /** Groups events into user/agent turns. */\n turn_id: string\n /** Per-session monotonic cursor (the SSE frame `id`). */\n seq: number\n created_by: UserRef\n /** Meaningful only for user events: null = queued, timestamp = consumed. */\n processed_at: string | null\n created_at: string\n}\n\n/**\n * One entry of the append-only session log — discriminated by `type`. The same\n * envelope is delivered byte-for-byte over both the durable (REST) and live (SSE)\n * channels, keyed by the same `seq`, so the two merge into one ordered log.\n */\nexport type SessionEvent = SessionEventEnvelope &\n (\n | { type: 'user.message'; payload: UserMessagePayload }\n | { type: 'user.interrupt'; payload: EmptyPayload }\n | { type: 'user.tool_confirmation'; payload: ToolConfirmationPayload }\n | { type: 'user.tool_result'; payload: ToolResultPayload }\n | { type: 'user.speech'; payload: SpeechPayload }\n | { type: 'user.voice_request'; payload: VoiceRequestPayload }\n | { type: 'agent.message'; payload: AgentMessagePayload }\n | { type: 'agent.speech'; payload: SpeechPayload }\n | { type: 'agent.reasoning'; payload: ReasoningPayload }\n | { type: 'agent.tool_use'; payload: ToolUsePayload }\n | { type: 'agent.tool_result'; payload: ToolResultPayload }\n | { type: 'agent.context_compacted'; payload: ContextCompactedPayload }\n | { type: 'agent.artifacts'; payload: AgentArtifactsPayload }\n | { type: 'session.status_running'; payload: SessionRunningPayload }\n | { type: 'session.status_idle'; payload: SessionIdlePayload }\n | { type: 'session.status_terminated'; payload: EmptyPayload }\n | { type: 'session.status_ended'; payload: EmptyPayload }\n | { type: 'session.error'; payload: ErrorPayload }\n | { type: 'session.updated'; payload: SessionUpdatedPayload }\n | { type: 'session.voice_started'; payload: VoiceStartedPayload }\n | { type: 'session.voice_ended'; payload: VoiceEndedPayload }\n | { type: 'delegated_session.updated'; payload: DelegatedSessionUpdatedPayload }\n | { type: 'span.model_request_start'; payload: ModelRequestStartPayload }\n | { type: 'span.model_request_end'; payload: ModelRequestEndPayload }\n )\n// A closed discriminated union (the v1 event set) so consumers narrow `payload`\n// by `type`. An unrecognized future event type still parses at runtime (it is cast\n// from JSON) — a switch over `type` simply won't match it, which is the intended\n// skip-and-ignore behavior.\n\n/**\n * The `GroupByTurn` projection — NEVER stored, recomputed from the event log.\n * `events` hold the envelopes verbatim, grouped by `turn_id` and ordered by `seq`.\n * The web folds this client-side from the live event stream; this type mirrors the\n * server's `GET /sessions/:id/turns` for completeness.\n */\nexport interface Turn {\n id: string\n role: 'user' | 'agent'\n events: SessionEvent[]\n}\n\n// ---------------------------------------------------------------------------\n// Requests / query options\n// ---------------------------------------------------------------------------\n\n/**\n * A client tool the launching surface advertises when it opens a session: a custom\n * tool the agent calls but the browser renders/executes, returning the result. Only\n * these three fields cross the wire — the render slot and React component are\n * frontend-only. `input_schema` is a JSON Schema (draft-07) object.\n */\nexport interface ClientToolSchema {\n name: string\n description: string\n input_schema: Record<string, unknown>\n}\n\n/**\n * Opens a session against a configured agent. `title` is optional. `client_tools` is\n * the launching surface's client-tool catalog, attached to this session only — a\n * surface that can't render them simply omits the field, so the agent never gets a\n * tool nobody can answer.\n */\nexport interface CreateSessionRequest {\n agent_key: string\n title?: string\n client_tools?: ClientToolSchema[]\n /**\n * Replaces the voice assistant's instructions in the voice sessions of this\n * session, at most 40,000 characters. `{{delegate}}` and `{{do_not_delegate}}` in them stand\n * for the words the voice model in use is told to hand a request over with, and\n * not to; the service fills them in. No response or event returns them.\n */\n voice_instructions?: string\n /**\n * The voice provider records the voice sessions of this session; a recording\n * is read with `sessions.getVoiceRecording`.\n */\n is_voice_recorded?: boolean\n}\n\n/**\n * Posts a client event onto a session. Only client-postable `user.*` types are\n * accepted; `payload` is the matching payload for the `type`.\n */\nexport interface AppendEventRequest {\n type: ClientEventType\n /**\n * Optionally supply the turn's id (a UUID) so the client can render the message\n * optimistically under a stable identity that matches the event echoed back\n * over the stream. Omitted, the service mints one.\n */\n turn_id?: string\n payload?: unknown\n /**\n * The sending surface's client-tool catalog, `user.message` only. A surface that\n * opened a session it did not create attaches its tools this way: when the names\n * differ from the session's client tools they replace them before the turn runs.\n * Omitted, the session's tools are left as they are.\n */\n client_tools?: ClientToolSchema[]\n /**\n * Refuse a `user.message` posted while a turn runs with 409 `session_running`\n * instead of queueing it. Queueing is the default: the running turn reads the\n * message with its next tool results where the runtime allows, and it opens the\n * session's next turn otherwise. For a caller that pairs each message with the\n * turn it starts and would rather retry later.\n */\n reject_if_running?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Voice\n// ---------------------------------------------------------------------------\n\n/**\n * One time a person talked to a session's agent through the voice assistant. The\n * assistant listens and speaks; what was said is in the session's event log\n * (`user.speech`, `agent.speech`) and everything asked for runs as turns of the\n * session. A session has at most one active voice session. A hand-over moves the\n * voice session to the session the person is handed to, and back.\n */\nexport interface VoiceSession {\n id: string\n org_id: string\n /** The session the person talks to. */\n session_id: string\n status: 'active' | 'ended'\n /** Null while it is active. */\n end_reason: VoiceEndReason | null\n /** How long it lasted: what the voice provider says, or the time since voice\n * was entered when the page went away without it. Null when not known. */\n duration_seconds: number | null\n /** How much of `duration_seconds` the voice model was paused (standby):\n * nobody spoke, and the provider bills that time at its lower rate. Null when\n * not known. */\n standby_seconds: number | null\n created_by: UserRef\n created_at: string\n ended_at: string | null\n}\n\n/** Enters voice on a session with the WebRTC offer of the page's peer connection. */\nexport interface StartVoiceRequest {\n sdp_offer: string\n}\n\n/**\n * The voice session that started, the voice provider's answer to the page's offer,\n * and the limits the page enforces by leaving voice.\n */\nexport interface StartVoiceResponse {\n voice_session: VoiceSession\n sdp_answer: string\n /** How long nobody may speak, while the voice model listens, before the page\n * leaves voice. */\n idle_timeout_seconds: number\n /** How long a voice session may last at most. */\n max_duration_seconds: number\n /** How long nobody speaks before the voice provider pauses the voice model\n * (standby); speech wakes it. 0: it never pauses. */\n standby_after_seconds: number\n /** How long the voice model may stay paused in one stretch before the page\n * leaves voice. */\n max_standby_seconds: number\n /** When the voice of the session's agent speaks: the page tells a\n * moderator's voice model when the conversation has gone quiet. */\n voice_style: AgentVoiceStyle\n}\n\n/** One finished utterance as the page heard it from the voice provider. */\nexport interface SpeechSegment {\n speaker: 'user' | 'agent'\n text: string\n /** Milliseconds from the start of the voice session. */\n start_ms: number\n end_ms: number\n}\n\n/**\n * Reports what was said in the session's active voice session since the last\n * report, in the order said. `starts_turn` says the voice assistant handed a\n * request over: after the segments a `user.voice_request` starts a turn, or is\n * queued behind the one that runs. `client_tools` is honoured with `starts_turn`\n * only (see {@link AppendEventRequest.client_tools}). `voice_session_id` is the\n * voice session the page started: a report for one that was replaced since (the\n * same person entered voice again, in another tab) is refused with 409\n * `voice_session_not_active`.\n */\nexport interface AppendSpeechRequest {\n voice_session_id: string\n segments: SpeechSegment[]\n starts_turn?: boolean\n /** The voice model's delegation the request is of, with `starts_turn` only.\n * A request is written once per delegation, however often it is reported. */\n delegation_id?: string\n client_tools?: ClientToolSchema[]\n /** Model-only text for the request, with `starts_turn` only (see\n * {@link UserMessagePayload.context}). */\n context?: string\n}\n\n/**\n * Leaves voice: why, and how long the voice provider says the session lasted (it\n * tells the page when the session closes). `voice_session_id` is the voice\n * session the page started (see {@link AppendSpeechRequest}).\n */\nexport interface EndVoiceRequest {\n voice_session_id: string\n end_reason: Exclude<VoiceEndReason, 'superseded' | 'transferred'>\n duration_seconds?: number | null\n /** How much of `duration_seconds` the voice model was paused, as the voice\n * provider says. */\n standby_seconds?: number | null\n /** What was said since the last speech report: a page that is being closed\n * has one request left to send. */\n segments?: SpeechSegment[]\n}\n\n/**\n * Moves the session's active voice session to another session, when the person\n * is handed over to it or handed back. The connection to the voice provider\n * stays as it is; what the person asks for next runs as turns of the target.\n */\nexport interface TransferVoiceRequest {\n /** The voice session the page started (see {@link AppendSpeechRequest}). */\n voice_session_id: string\n /** A session the session delegated to, or the one that delegated to it. */\n target_session_id: string\n}\n\n/**\n * The voice session on its new session, and the `session.voice_started` written\n * to that session's log: what the log holds up to it was not said to the voice\n * model.\n */\nexport interface TransferVoiceResponse {\n voice_session: VoiceSession\n started: SessionEvent\n /** The voice style of the agent the voice speaks for now. */\n voice_style: AgentVoiceStyle\n /** Whether a turn of that session runs, as its log says up to `started`.\n * The page follows the log from `started` on. */\n is_turn_running: boolean\n}\n\n/** List filter for sessions (in addition to pagination/sorting). */\nexport interface ListSessionsOptions extends ListOptions {\n /** Filter by the agent the session runs. */\n agent_key?: string\n /** Keep sessions in this status, or in any of several. */\n status?: SessionStatus | SessionStatus[]\n /** Keep sessions whose title contains this text, ignoring case. */\n title?: string\n /**\n * Keep the sessions one user started: a user id, or `'me'` for the caller.\n * It narrows what the caller may see and never widens it.\n */\n created_by?: string\n /** Keep the sessions one session delegated to. */\n parent_session_id?: string\n}\n\n/**\n * Forward cursor over the durable event log. `after_seq` is the exclusive lower\n * bound (the last-seen seq); `order` defaults to asc (chronological). `types`\n * restricts the result to specific event types (e.g. `['agent.message']`);\n * omitted, every type is returned.\n */\nexport interface SessionEventsOptions {\n after_seq?: number\n limit?: number\n order?: 'asc' | 'desc'\n types?: EventType[]\n}\n\n/** Options for opening the live SSE stream. */\nexport interface SessionStreamOptions {\n /** Replay from this seq (exclusive) before following live. */\n afterSeq?: number\n /** Abort to tear the stream down. */\n signal?: AbortSignal\n}\n\n// ---------------------------------------------------------------------------\n// The live delta channel\n// ---------------------------------------------------------------------------\n\n/**\n * The chunk frames of the three long agent events, sent on the delta channel\n * while the model writes the event: the whole event's type plus `.start`,\n * `.delta` or `.end`. Frames are never stored and never posted by a client.\n */\nexport type DeltaEventType =\n | 'agent.message.start'\n | 'agent.message.delta'\n | 'agent.message.end'\n | 'agent.reasoning.start'\n | 'agent.reasoning.delta'\n | 'agent.reasoning.end'\n | 'agent.tool_use.start'\n | 'agent.tool_use.delta'\n | 'agent.tool_use.end'\n\n/** Opens or closes the frames of one content part. */\nexport interface DeltaBoundaryPayload {\n part_index: number\n}\n\n/** The next piece of a message's text. Append the pieces in order. */\nexport interface MessageDeltaPayload {\n part_index: number\n text: string\n}\n\n/** The next piece of the reasoning text, or the signature that closes it. */\nexport interface ReasoningDeltaPayload {\n part_index: number\n text?: string\n signature?: string\n}\n\n/** A tool call is known by id, name and kind before its input has been written. */\nexport interface ToolUseStartPayload {\n part_index: number\n id: string\n name: string\n tool_kind: SessionToolKind\n}\n\n/** The next piece of a tool call's input, as JSON text. */\nexport interface ToolUseDeltaPayload {\n part_index: number\n partial_json: string\n}\n\n/**\n * One chunk frame. It uses the envelope of the whole event it belongs to: `id`\n * and `turn_id` are that event's, so a client builds a draft from the frames and\n * drops it when the whole event with the same `id` arrives. `seq` is 0 — a frame\n * has no place in the log.\n */\nexport type SessionDeltaFrame = SessionEventEnvelope &\n (\n | { type: 'agent.message.start'; payload: DeltaBoundaryPayload }\n | { type: 'agent.message.delta'; payload: MessageDeltaPayload }\n | { type: 'agent.message.end'; payload: DeltaBoundaryPayload }\n | { type: 'agent.reasoning.start'; payload: DeltaBoundaryPayload }\n | { type: 'agent.reasoning.delta'; payload: ReasoningDeltaPayload }\n | { type: 'agent.reasoning.end'; payload: DeltaBoundaryPayload }\n | { type: 'agent.tool_use.start'; payload: ToolUseStartPayload }\n | { type: 'agent.tool_use.delta'; payload: ToolUseDeltaPayload }\n | { type: 'agent.tool_use.end'; payload: DeltaBoundaryPayload }\n )\n\n/**\n * One entry of the delta channel: a whole event of the log, or a chunk frame of\n * the event being written after it. `position` is the entry's place on the\n * channel, `<seq>-<n>`: a whole event is `<seq>-0`, the frames after it count up\n * from 1. Pass it back as {@link SessionDeltaStreamOptions.after} to resume.\n */\nexport interface SessionDeltaEntry {\n position: string\n event: SessionEvent | SessionDeltaFrame\n}\n\n/** Options for opening the live delta stream. */\nexport interface SessionDeltaStreamOptions {\n /** Replay from here (exclusive) before following live: a position, or a bare seq. */\n after?: string | number\n /** Abort to tear the stream down. */\n signal?: AbortSignal\n}\n\nconst DELTA_EVENT_TYPE = /^agent\\.(message|reasoning|tool_use)\\.(start|delta|end)$/\n\n/** Whether an entry of the delta channel is a chunk frame, not a whole event. */\nexport function isDeltaFrame(event: SessionEvent | SessionDeltaFrame): event is SessionDeltaFrame {\n return DELTA_EVENT_TYPE.test(event.type)\n}\n","import type { ProteosClient } from '../client.js'\nimport { type AgentService, AgentServiceImpl } from './agents.js'\nimport { type McpServerService, McpServerServiceImpl } from './mcp-servers.js'\nimport { type ModelService, ModelServiceImpl } from './models.js'\nimport { type PromptService, PromptServiceImpl } from './prompts.js'\nimport { type SessionService, SessionServiceImpl } from './sessions.js'\nimport { type SkillService, SkillServiceImpl } from './skills.js'\nimport { type ToolService, ToolServiceImpl } from './tools.js'\nimport { type ToolsetService, ToolsetServiceImpl } from './toolsets.js'\n\n/**\n * Client for the Proteos Agent Service API.\n *\n * Manages the AI-agent configuration domain: Agents, Prompts (versioned),\n * Skills (versioned bundles), Tools, and MCP Servers — all org-scoped and keyed\n * by an immutable kebab-case `key` — plus the stateless model calls\n * (`models.generate`, `models.decide`) and chat sessions.\n *\n * @example\n * ```ts\n * import { ProteosClient, AgentClient } from '@proteos/sdk';\n *\n * const client = new ProteosClient({ baseUrl, token });\n * const agent = new AgentClient(client);\n *\n * const agents = await agent.agents.list().all();\n * const prompt = await agent.prompts.get('revenue-brief');\n *\n * const { answers } = await agent.models.decide({\n * state: { message: 'My card was charged twice!' },\n * questions: {\n * refund_requested: { type: 'boolean', instructions: 'Does the customer ask for money back?' },\n * topic: { type: 'choice', instructions: 'Topic?', criteria: { billing: 'charges', other: 'else' } },\n * },\n * });\n * if (answers.topic.confidence > 0.8) route(answers.topic.choice);\n * ```\n */\nexport class AgentClient {\n /** Service for managing agents. */\n readonly agents: AgentService\n /** Service for managing prompts (versioned). */\n readonly prompts: PromptService\n /** Service for managing skills (versioned bundles). */\n readonly skills: SkillService\n /** Service for managing tools. */\n readonly tools: ToolService\n /** Service for managing toolsets (platform + custom tool groups). */\n readonly toolsets: ToolsetService\n /** Service for managing MCP server registrations. */\n readonly mcpServers: McpServerService\n /** Service for stateless model calls: `generate` (one message out) and `decide` (calibrated typed answers). */\n readonly models: ModelService\n /** Service for managing chat sessions (conversations + event log + stream). */\n readonly sessions: SessionService\n\n /**\n * Creates a new AgentClient instance.\n *\n * @param client - The base ProteosClient to use for API requests\n */\n constructor(client: ProteosClient) {\n this.agents = new AgentServiceImpl(client)\n this.prompts = new PromptServiceImpl(client)\n this.skills = new SkillServiceImpl(client)\n this.tools = new ToolServiceImpl(client)\n this.toolsets = new ToolsetServiceImpl(client)\n this.mcpServers = new McpServerServiceImpl(client)\n this.models = new ModelServiceImpl(client)\n this.sessions = new SessionServiceImpl(client)\n }\n}\n\n// Re-export service interfaces\nexport type { AgentService } from './agents.js'\nexport type { McpServerService } from './mcp-servers.js'\n// Re-export model-call types (generate + decide)\nexport type {\n BooleanAnswer,\n BooleanCriteria,\n BooleanQuestion,\n ChoiceAnswer,\n ChoiceQuestion,\n DecideRequest,\n DecisionAnswer,\n DecisionAnswerFor,\n DecisionQuestion,\n DecisionQuestions,\n DecisionQuestionType,\n DecisionResult,\n GenerateRequest,\n GenerationResult,\n ModelInfo,\n ModelProviderName,\n ModelStopReason,\n ScoreAnswer,\n ScoreQuestion,\n StructuredText,\n} from './model-types.js'\nexport type { ModelService } from './models.js'\nexport type { PromptService } from './prompts.js'\n// Re-export session types\nexport type {\n AgentArtifactsPayload,\n AgentMessagePayload,\n AppendEventRequest,\n AppendSpeechRequest,\n AwaitingToolUse,\n ClientEventType,\n ClientToolSchema,\n ContentBlock,\n ContextCompactedPayload,\n CreateSessionRequest,\n DelegatedSessionUpdatedPayload,\n DeltaBoundaryPayload,\n DeltaEventType,\n EmptyPayload,\n EndVoiceRequest,\n ErrorPayload,\n EventType,\n FileBlock,\n ListSessionsOptions,\n MessageDeltaPayload,\n ModelRequestEndPayload,\n ModelRequestStartPayload,\n ModelUsage,\n ReasoningDeltaPayload,\n ReasoningPayload,\n ResultBlock,\n Session,\n SessionDeltaEntry,\n SessionDeltaFrame,\n SessionDeltaStreamOptions,\n SessionEvent,\n SessionEventEnvelope,\n SessionEventsOptions,\n SessionIdlePayload,\n SessionPreview,\n SessionPreviewStatus,\n SessionRunningPayload,\n SessionStatus,\n SessionStreamOptions,\n SessionToolKind,\n SessionUpdatedPayload,\n SpeechPayload,\n SpeechSegment,\n StartVoiceRequest,\n StartVoiceResponse,\n StopReason,\n TextBlock,\n ToolConfirmationPayload,\n ToolResultPayload,\n ToolUseDeltaPayload,\n ToolUsePayload,\n ToolUseStartPayload,\n TransferVoiceRequest,\n TransferVoiceResponse,\n Turn,\n UserMessagePayload,\n VoiceEndedPayload,\n VoiceEndReason,\n VoiceRequestPayload,\n VoiceSession,\n VoiceStartedPayload,\n} from './session-types.js'\nexport { isDeltaFrame } from './session-types.js'\nexport type { SessionService } from './sessions.js'\nexport type { SkillService } from './skills.js'\nexport type { ToolService } from './tools.js'\nexport type { ToolsetService } from './toolsets.js'\n// Re-export types\nexport type {\n ActionBinding,\n Agent,\n AgentResourceListOptions,\n AgentRuntime,\n AgentVoiceStyle,\n CreateAgentRequest,\n CreateMcpServerRequest,\n CreatePromptRequest,\n CreateToolRequest,\n CreateToolsetRequest,\n DependentAgent,\n DependentSyncResult,\n ListAgentsOptions,\n ListMcpServersOptions,\n ListPromptsOptions,\n ListSkillsOptions,\n ListToolsetsOptions,\n ListToolsOptions,\n McpBinding,\n McpConnectionState,\n McpConnectionStatus,\n McpServer,\n McpServerAuth,\n McpServerOAuth,\n McpToolSummary,\n ModelConfig,\n PlatformBinding,\n Prompt,\n PromptVersion,\n QueryBinding,\n Skill,\n SkillBundle,\n SkillVersion,\n StartMcpOAuthResponse,\n Tool,\n ToolBinding,\n ToolKind,\n Toolset,\n ToolsetKind,\n ToolsetToolSummary,\n UpdateAgentRequest,\n UpdateMcpServerRequest,\n UpdatePromptRequest,\n UpdateToolRequest,\n UpdateToolsetRequest,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { Organization, Profile, UpdateMeRequest, User } from './types.js'\n\nconst ME_BASE_PATH = '/accounts/v1/me'\n\n/**\n * Service for caller-scoped queries — answers about the authenticated user\n * (from the token), not an arbitrary user id.\n */\nexport interface MeService {\n /**\n * Gets the caller's own user record, resolved from the token's user id.\n * The canonical \"who am I\" — use this instead of filtering `users.list`\n * by email.\n *\n * @returns The calling user\n */\n get(): Promise<User>\n\n /**\n * Updates the caller's own profile (name, photo). Requires a JWT session —\n * requests authenticated with an API key are rejected.\n *\n * @param request - Fields to update; `profile_image: null` removes the photo\n * @returns The updated user\n */\n update(request: UpdateMeRequest): Promise<User>\n\n /**\n * Lists the organizations the caller can act in (all orgs for a platform\n * admin; otherwise the orgs they're a member of). Powers the org-switcher.\n *\n * @returns The caller's organizations\n */\n organizations(): Promise<Organization[]>\n\n /**\n * Gets the caller's profile in the token org — the subject app\n * configurations are resolved against.\n *\n * @throws {ProteosError} 404 when the caller has no profile\n */\n profile(): Promise<Profile>\n}\n\n/**\n * Implementation of MeService.\n */\nexport class MeServiceImpl implements MeService {\n constructor(private readonly client: ProteosClient) {}\n\n async get(): Promise<User> {\n return this.client.request<User>('GET', ME_BASE_PATH)\n }\n\n async update(request: UpdateMeRequest): Promise<User> {\n return this.client.request<User>('PATCH', ME_BASE_PATH, request)\n }\n\n async organizations(): Promise<Organization[]> {\n const response = await this.client.request<{ data: Organization[] }>(\n 'GET',\n `${ME_BASE_PATH}/organizations`,\n )\n return response.data\n }\n\n async profile(): Promise<Profile> {\n return this.client.request<Profile>('GET', `${ME_BASE_PATH}/profile`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateOrganizationRequest,\n ListOrganizationsOptions,\n Organization,\n UpdateOrganizationRequest,\n} from './types.js'\n\nconst ORGANIZATIONS_BASE_PATH = '/accounts/v1/organizations'\n\n/**\n * Service for managing organizations.\n * Handles organization CRUD operations.\n */\nexport interface OrganizationService {\n /**\n * Lists organizations with optional filtering.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param options - Filter and pagination options\n * @returns Async iterator over organizations\n *\n * @example\n * ```ts\n * // Iterate over all organizations\n * for await (const org of service.list()) {\n * console.log(org.name);\n * }\n *\n * // With filtering\n * for await (const org of service.list({ name: 'Acme Corp' })) {\n * console.log(org.id);\n * }\n * ```\n */\n list(options?: ListOrganizationsOptions): PageIterator<Organization, ListOrganizationsOptions>\n\n /**\n * Fetches a single page of organizations.\n *\n * @param options - Filter and pagination options (including `page`)\n * @returns A single page of organizations with pagination metadata\n */\n listPage(options?: ListOrganizationsOptions): Promise<ListResult<Organization>>\n\n /**\n * Gets a single organization by ID.\n *\n * @param id - Organization ID\n * @returns The organization\n * @throws {ProteosError} If organization not found (404)\n */\n get(id: string): Promise<Organization>\n\n /**\n * Creates a new organization.\n *\n * @param request - Organization creation request\n * @returns The created organization\n * @throws {ProteosError} If validation fails (400) or conflict (409)\n *\n * @example\n * ```ts\n * const org = await service.create({\n * name: 'Acme Corporation',\n * description: 'Main organization',\n * });\n * ```\n */\n create(request: CreateOrganizationRequest): Promise<Organization>\n\n /**\n * Updates an existing organization.\n *\n * @param id - Organization ID\n * @param request - Fields to update\n * @returns The updated organization\n * @throws {ProteosError} If organization not found (404) or validation fails (400)\n */\n update(id: string, request: UpdateOrganizationRequest): Promise<Organization>\n\n /**\n * Deletes an organization.\n *\n * @param id - Organization ID\n * @throws {ProteosError} If organization not found (404)\n */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of OrganizationService.\n */\nexport class OrganizationServiceImpl implements OrganizationService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListOrganizationsOptions = {},\n ): PageIterator<Organization, ListOrganizationsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListOrganizationsOptions = {}): Promise<ListResult<Organization>> {\n return this.client.requestWithQuery<ListResult<Organization>>(\n 'GET',\n ORGANIZATIONS_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<Organization> {\n return this.client.request<Organization>('GET', `${ORGANIZATIONS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateOrganizationRequest): Promise<Organization> {\n return this.client.request<Organization>('POST', ORGANIZATIONS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateOrganizationRequest): Promise<Organization> {\n return this.client.request<Organization>('PATCH', `${ORGANIZATIONS_BASE_PATH}/${id}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${ORGANIZATIONS_BASE_PATH}/${id}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateProfileRequest,\n ListProfilesOptions,\n Profile,\n UpdateProfileRequest,\n} from './types.js'\n\nconst PROFILES_BASE_PATH = '/accounts/v1/profiles'\n\n/**\n * Service for managing profiles — the org's user-types (ONE per user per\n * org). Per-user assignment lives on {@link UserService} (`getProfile` /\n * `setProfile` / `clearProfile`); the org-wide roster on\n * {@link UserProfileAssignmentService}.\n */\nexport interface ProfileService {\n /** Lists profiles (auto-paginating iterator). */\n list(options?: ListProfilesOptions): PageIterator<Profile, ListProfilesOptions>\n\n /** Fetches a single page of profiles. */\n listPage(options?: ListProfilesOptions): Promise<ListResult<Profile>>\n\n /** Gets a profile by slug (404 when unknown). */\n get(slug: string): Promise<Profile>\n\n /** Creates a profile. The org is taken from the caller's token. */\n create(request: CreateProfileRequest): Promise<Profile>\n\n /**\n * Creates or updates a profile idempotently by slug\n * (`PUT /accounts/v1/profiles/:slug`). The URL slug wins on mismatch.\n */\n upsert(slug: string, request: CreateProfileRequest): Promise<Profile>\n\n /** Partially updates a profile. */\n update(slug: string, request: UpdateProfileRequest): Promise<Profile>\n\n /**\n * Deletes a profile.\n * @throws {ProteosError} 409 `profile_in_use` while users still hold it —\n * move them first.\n */\n delete(slug: string): Promise<void>\n}\n\nexport class ProfileServiceImpl implements ProfileService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListProfilesOptions = {}): PageIterator<Profile, ListProfilesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListProfilesOptions = {}): Promise<ListResult<Profile>> {\n return this.client.requestWithQuery<ListResult<Profile>>('GET', PROFILES_BASE_PATH, options)\n }\n\n async get(slug: string): Promise<Profile> {\n return this.client.request<Profile>('GET', `${PROFILES_BASE_PATH}/${slug}`)\n }\n\n async create(request: CreateProfileRequest): Promise<Profile> {\n return this.client.request<Profile>('POST', PROFILES_BASE_PATH, request)\n }\n\n async upsert(slug: string, request: CreateProfileRequest): Promise<Profile> {\n return this.client.request<Profile>('PUT', `${PROFILES_BASE_PATH}/${slug}`, {\n ...request,\n slug,\n })\n }\n\n async update(slug: string, request: UpdateProfileRequest): Promise<Profile> {\n return this.client.request<Profile>('PATCH', `${PROFILES_BASE_PATH}/${slug}`, request)\n }\n\n async delete(slug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${PROFILES_BASE_PATH}/${slug}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n AssignPermissionRequest,\n CreateRoleRequest,\n ListRolePermissionsOptions,\n ListRolesOptions,\n Role,\n RoleEntityPermission,\n UpdateRoleRequest,\n} from './types.js'\n\nconst ROLES_BASE_PATH = '/accounts/v1/roles'\n\n/**\n * Service for managing roles.\n * Handles role CRUD operations and permission assignments.\n */\nexport interface RoleService {\n /**\n * Lists roles with optional filtering.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param options - Filter and pagination options\n * @returns Async iterator over roles\n *\n * @example\n * ```ts\n * // Iterate over all roles\n * for await (const role of service.list()) {\n * console.log(role.name);\n * }\n *\n * // With filtering\n * for await (const role of service.list({ org_id: 'org-123' })) {\n * console.log(role.slug);\n * }\n * ```\n */\n list(options?: ListRolesOptions): PageIterator<Role, ListRolesOptions>\n\n /**\n * Gets a single role by slug.\n *\n * @param slug - Role slug\n * @returns The role\n * @throws {ProteosError} If role not found (404)\n */\n get(slug: string): Promise<Role>\n\n /**\n * Creates a new role.\n *\n * @param request - Role creation request\n * @returns The created role\n * @throws {ProteosError} If validation fails (400) or conflict (409)\n *\n * @example\n * ```ts\n * const role = await service.create({\n * org_id: 'org-123',\n * slug: 'admin',\n * name: 'Administrator',\n * description: 'Full system access',\n * });\n * ```\n */\n create(request: CreateRoleRequest): Promise<Role>\n\n /**\n * Creates or updates a role idempotently by slug. The URL slug wins on\n * mismatch with the body's slug field (`PUT /accounts/v1/roles/:slug`). The\n * org is taken from the caller's token, not the body.\n *\n * @param slug - Role slug\n * @param request - Full role body\n * @returns The created or updated role\n */\n upsert(slug: string, request: CreateRoleRequest): Promise<Role>\n\n /**\n * Updates an existing role.\n *\n * @param slug - Role slug\n * @param request - Fields to update\n * @returns The updated role\n * @throws {ProteosError} If role not found (404) or validation fails (400)\n */\n update(slug: string, request: UpdateRoleRequest): Promise<Role>\n\n /**\n * Deletes a role.\n *\n * @param slug - Role slug\n * @throws {ProteosError} If role not found (404), or if the role still has\n * entity permissions attached (400 `role_deletion_not_allowed`) — remove\n * the grants first\n */\n delete(slug: string): Promise<void>\n\n /**\n * Fetches a single page of roles.\n *\n * @param options - Filter and pagination options (including `page`)\n * @returns A single page of roles with pagination metadata\n */\n listPage(options?: ListRolesOptions): Promise<ListResult<Role>>\n\n /**\n * Gets permissions assigned to a role.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param roleSlug - Role slug\n * @param options - Filter and pagination options\n * @returns Async iterator over role entity permissions\n */\n getPermissions(\n roleSlug: string,\n options?: ListRolePermissionsOptions,\n ): PageIterator<RoleEntityPermission, ListRolePermissionsOptions>\n\n /**\n * Assigns a permission to a role for an entity.\n *\n * @param roleSlug - Role slug\n * @param request - Permission assignment request\n * @returns The created role entity permission\n * @throws {ProteosError} If role or entity not found (404)\n */\n assignPermission(\n roleSlug: string,\n request: AssignPermissionRequest,\n ): Promise<RoleEntityPermission>\n\n /**\n * Removes a permission from a role.\n *\n * @param roleSlug - Role slug\n * @param permissionId - Permission ID to remove\n * @throws {ProteosError} If permission not found (404)\n */\n removePermission(roleSlug: string, permissionId: string): Promise<void>\n}\n\n/**\n * Implementation of RoleService.\n */\nexport class RoleServiceImpl implements RoleService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListRolesOptions = {}): PageIterator<Role, ListRolesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListRolesOptions = {}): Promise<ListResult<Role>> {\n return this.client.requestWithQuery<ListResult<Role>>('GET', ROLES_BASE_PATH, options)\n }\n\n async get(slug: string): Promise<Role> {\n return this.client.request<Role>('GET', `${ROLES_BASE_PATH}/${slug}`)\n }\n\n async create(request: CreateRoleRequest): Promise<Role> {\n return this.client.request<Role>('POST', ROLES_BASE_PATH, request)\n }\n\n async upsert(slug: string, request: CreateRoleRequest): Promise<Role> {\n return this.client.request<Role>('PUT', `${ROLES_BASE_PATH}/${slug}`, { ...request, slug })\n }\n\n async update(slug: string, request: UpdateRoleRequest): Promise<Role> {\n return this.client.request<Role>('PATCH', `${ROLES_BASE_PATH}/${slug}`, request)\n }\n\n async delete(slug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${ROLES_BASE_PATH}/${slug}`)\n }\n\n getPermissions(\n roleSlug: string,\n options: ListRolePermissionsOptions = {},\n ): PageIterator<RoleEntityPermission, ListRolePermissionsOptions> {\n return new PageIterator((opts) => this.fetchPermissionsPage(roleSlug, opts), options)\n }\n\n async assignPermission(\n roleSlug: string,\n request: AssignPermissionRequest,\n ): Promise<RoleEntityPermission> {\n return this.client.request<RoleEntityPermission>(\n 'POST',\n `${ROLES_BASE_PATH}/${roleSlug}/permissions`,\n request,\n )\n }\n\n async removePermission(roleSlug: string, permissionId: string): Promise<void> {\n await this.client.request<void>(\n 'DELETE',\n `${ROLES_BASE_PATH}/${roleSlug}/permissions/${permissionId}`,\n )\n }\n\n private async fetchPermissionsPage(\n roleSlug: string,\n options: ListRolePermissionsOptions,\n ): Promise<ListResult<RoleEntityPermission>> {\n return this.client.requestWithQuery<ListResult<RoleEntityPermission>>(\n 'GET',\n `${ROLES_BASE_PATH}/${roleSlug}/permissions`,\n options,\n )\n }\n}\n","/**\n * Common error codes returned by the Proteos API.\n */\nexport const ErrorCode = {\n NOT_FOUND: 'not_found',\n UNAUTHORIZED: 'unauthorized',\n FORBIDDEN: 'forbidden',\n BAD_REQUEST: 'bad_request',\n CONFLICT: 'conflict',\n INTERNAL_SERVER_ERROR: 'internal_server_error',\n INVALID_PAYLOAD: 'invalid_payload',\n INVALID_PERSONA: 'invalid_persona',\n /** The server was never reached: DNS, connection refused, network down.\n * Carried with httpStatus 0. */\n NETWORK_ERROR: 'network_error',\n /** The request timed out client-side. Carried with httpStatus 0. */\n REQUEST_TIMEOUT: 'request_timeout',\n} as const\n\nexport type ErrorCodeType = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Error returned by the Proteos API.\n * Contains HTTP status code, error code, and human-readable message.\n */\nexport class ProteosError extends Error {\n /** HTTP status code of the response */\n readonly httpStatus: number\n /** API error code (e.g., 'not_found', 'unauthorized') */\n readonly code: ErrorCodeType | string\n /**\n * Optional machine-readable payload beside the message — e.g. a denied send's\n * `earliest_allowed_at` / `rule_id`, the offending `contact_id`. Absent on\n * most errors.\n */\n readonly details: Record<string, unknown> | undefined\n\n constructor(\n message: string,\n httpStatus: number,\n code: ErrorCodeType | string,\n details?: Record<string, unknown>,\n ) {\n super(message)\n this.name = 'ProteosError'\n this.httpStatus = httpStatus\n this.code = code\n this.details = details\n\n // V8-specific API for cleaner stack traces; not present in all runtimes\n const v8Capture = (Error as unknown as { captureStackTrace?: (t: object, c: unknown) => void })\n .captureStackTrace\n if (v8Capture) v8Capture(this, this.constructor)\n }\n\n /**\n * Returns a formatted string representation of the error.\n */\n override toString(): string {\n return `${this.code}: ${this.message} (HTTP ${this.httpStatus})`\n }\n}\n\n/**\n * Type guard to check if an error is a ProteosError.\n */\nexport function isProteosError(error: unknown): error is ProteosError {\n return error instanceof ProteosError\n}\n\n/**\n * Type guard to check if an error is a 404 Not Found error.\n */\nexport function isNotFound(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 404\n}\n\n/**\n * Type guard to check if an error is a 401 Unauthorized error.\n */\nexport function isUnauthorized(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 401\n}\n\n/**\n * Type guard to check if an error is a 403 Forbidden error.\n */\nexport function isForbidden(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 403\n}\n\n/**\n * Type guard to check if an error is a 400 Bad Request error.\n */\nexport function isBadRequest(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 400\n}\n\n/**\n * Type guard to check if an error is a 409 Conflict error.\n */\nexport function isConflict(error: unknown): error is ProteosError {\n return isProteosError(error) && error.httpStatus === 409\n}\n\n/**\n * Maps HTTP status codes to default error codes.\n */\nexport function getDefaultErrorCode(httpStatus: number): ErrorCodeType | string {\n switch (httpStatus) {\n case 400:\n return ErrorCode.BAD_REQUEST\n case 401:\n return ErrorCode.UNAUTHORIZED\n case 403:\n return ErrorCode.FORBIDDEN\n case 404:\n return ErrorCode.NOT_FOUND\n case 409:\n return ErrorCode.CONFLICT\n default:\n return ErrorCode.INTERNAL_SERVER_ERROR\n }\n}\n\n/**\n * Response shape for API error responses.\n */\nexport interface ApiErrorResponse {\n code?: string\n message?: string\n details?: Record<string, unknown>\n}\n\n/**\n * Parses an error response from the API and creates a ProteosError.\n */\nexport async function parseErrorResponse(response: Response): Promise<ProteosError> {\n const httpStatus = response.status\n let code: string = getDefaultErrorCode(httpStatus)\n let message = 'Unknown error'\n let details: Record<string, unknown> | undefined\n\n try {\n const body = await response.text()\n\n // Try to parse as JSON\n try {\n const json = JSON.parse(body) as ApiErrorResponse\n if (json.code) {\n code = json.code\n }\n if (json.message) {\n message = json.message\n } else {\n message = body || `HTTP ${httpStatus}`\n }\n if (json.details && typeof json.details === 'object') {\n details = json.details\n }\n } catch {\n // Not JSON, use body as message\n message = body.trim() || `HTTP ${httpStatus}`\n }\n } catch {\n message = `HTTP ${httpStatus}`\n }\n\n return new ProteosError(message, httpStatus, code, details)\n}\n","import type { ProteosClient } from '../client.js'\nimport { ProteosError } from '../errors.js'\nimport type { PrincipalRef } from '../meta/types.js'\nimport type { SharePermission, ShareRequest, ShareRow } from './types.js'\n\n/**\n * Which service owns each shareable platform entity.\n *\n * Sharing is decided by the service that OWNS the resource — whether a caller\n * may grant depends on what the row itself grants them (its granting\n * attributes, or an owner column), which only that service can read. So the\n * write endpoint is per-service by necessity.\n *\n * This map is the client-side seam that hides that. Callers name an entity, not\n * a service, so if sharing is ever centralized behind one endpoint the change is\n * a one-line edit here and no caller moves.\n *\n * Anything NOT listed is a user-defined entity, which data-service owns — that\n * set is unbounded and appears at runtime, so it is the default rather than an\n * enumeration.\n */\nconst PLATFORM_ENTITY_SERVICE: Readonly<Record<string, string>> = {\n // Agent suite (agent-service)\n agents: '/agents',\n prompts: '/agents',\n skills: '/agents',\n tools: '/agents',\n toolsets: '/agents',\n 'mcp-servers': '/agents',\n 'agent-sessions': '/agents',\n // Knowledge (knowledge-service)\n 'knowledge-spaces': '/knowledge',\n 'knowledge-nodes': '/knowledge',\n // Conversations (conversation-service)\n conversations: '/conversations',\n connections: '/conversations',\n}\n\n/**\n * The services that actually serve `/v1/shares` today.\n *\n * Deliberately separate from the map above: a service that has not adopted\n * the endpoint yet must fail with a clear message rather than a bare 404 that\n * reads like the record does not exist.\n */\nconst SERVICES_WITH_SHARING: ReadonlySet<string> = new Set([\n '/data',\n '/knowledge',\n '/agents',\n '/conversations',\n])\n\n/** Records live in data-service; user-defined entities are the unlisted majority. */\nconst DEFAULT_SERVICE = '/data'\n\n/**\n * Resolves the share endpoint for an entity slug.\n *\n * Exported for tests and for callers that want to check support before offering\n * a share affordance in a UI.\n */\nexport function shareRouteFor(entitySlug: string): string {\n const service = PLATFORM_ENTITY_SERVICE[entitySlug] ?? DEFAULT_SERVICE\n if (!SERVICES_WITH_SHARING.has(service)) {\n throw new ProteosError(\n `Sharing is not available for '${entitySlug}' yet — ${service.slice(1)}-service does not serve a share endpoint.`,\n 501,\n 'sharing_not_supported',\n )\n }\n return `${service}/v1/shares`\n}\n\n/** True when `entitySlug` can be shared today. */\nexport function isShareable(entitySlug: string): boolean {\n const service = PLATFORM_ENTITY_SERVICE[entitySlug] ?? DEFAULT_SERVICE\n return SERVICES_WITH_SHARING.has(service)\n}\n\n/**\n * Sharing an individual resource with a principal — a person, an agent, an API\n * client, a team, or the whole organization.\n *\n * A share grants access to ONE resource, which is a different thing from a role:\n * a role grants a permission on an entity TYPE (every deal), a share grants it\n * on an INSTANCE (this deal). The two compose — a share gives nothing to someone\n * holding no grant on the entity type at all, which bounds its blast radius to a\n * population already authorized for that kind of resource.\n *\n * Callers name an ENTITY, never a service. Which service handles the write is\n * this module's problem.\n *\n * Who may share: the resource's owner, or someone holding the plain (unscoped)\n * permission on the entity. Notably NOT a share recipient — access held only\n * through a share cannot be passed on, and cannot be turned into ownership.\n */\nexport interface ShareService {\n /**\n * Grants a principal access to one resource.\n *\n * Granting `write` or `delete` implies `read`: a principal who cannot see a\n * resource must never be able to edit it, so the read is granted alongside.\n *\n * @throws {ProteosError} 403 `share_not_permitted` when the caller holds their\n * own access only through a share; 403 `principal_not_in_org` when the\n * recipient is outside the caller's organization (rejected outright rather\n * than written inert, which would become a live grant the moment they joined);\n * 404 when the resource does not exist or is not visible to the caller;\n * 501 `sharing_not_supported` when the owning service has no share endpoint.\n */\n share(\n entitySlug: string,\n recordId: string,\n principal: PrincipalRef,\n permission: SharePermission,\n ): Promise<void>\n\n /**\n * Revokes a principal's access to one resource.\n *\n * Revoking `read` CASCADES to `write` and `delete` — an edit right on\n * something someone can no longer see would be incoherent.\n *\n * Revocation is deliberately wider than granting: the owner, anyone holding\n * the unscoped `write` permission, and platform admins may all revoke. Erring\n * permissive costs nothing here, while erring strict would strand grants\n * nobody could clean up.\n */\n unshare(\n entitySlug: string,\n recordId: string,\n principal: PrincipalRef,\n permission: SharePermission,\n ): Promise<void>\n\n /**\n * Lists a resource's shares.\n *\n * Gated to the population that may REVOKE them — the owner, unscoped-write\n * holders, and platform admins. Record read is deliberately not enough: a\n * share list discloses org structure (\"this deal is visible to team:legal\").\n *\n * @throws {ProteosError} 403 `share_listing_not_permitted` otherwise.\n */\n listShares(entitySlug: string, recordId: string): Promise<ShareRow[]>\n}\n\nexport class ShareServiceImpl implements ShareService {\n constructor(private readonly client: ProteosClient) {}\n\n async share(\n entitySlug: string,\n recordId: string,\n principal: PrincipalRef,\n permission: SharePermission,\n ): Promise<void> {\n await this.client.request<void>('POST', shareRouteFor(entitySlug), {\n entity_slug: entitySlug,\n record_id: recordId,\n principal,\n permission,\n } satisfies ShareRequest)\n }\n\n async unshare(\n entitySlug: string,\n recordId: string,\n principal: PrincipalRef,\n permission: SharePermission,\n ): Promise<void> {\n await this.client.request<void>('DELETE', shareRouteFor(entitySlug), {\n entity_slug: entitySlug,\n record_id: recordId,\n principal,\n permission,\n } satisfies ShareRequest)\n }\n\n async listShares(entitySlug: string, recordId: string): Promise<ShareRow[]> {\n const query = new URLSearchParams({ entity_slug: entitySlug, record_id: recordId })\n const response = await this.client.request<{ shares: ShareRow[] }>(\n 'GET',\n `${shareRouteFor(entitySlug)}?${query.toString()}`,\n )\n return response.shares ?? []\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n AddTeamMemberRequest,\n CreateTeamRequest,\n ListTeamMembersOptions,\n ListTeamsOptions,\n Team,\n TeamMember,\n UpdateTeamRequest,\n} from './types.js'\n\nconst TEAMS_BASE_PATH = '/accounts/v1/teams'\n\n/**\n * Service for managing teams — the org's structure, and a principal that can\n * hold access anywhere a user can.\n *\n * Team hierarchy rolls UP: a member of a child team counts as a member of every\n * ancestor **for grants made to that ancestor**. Granting `sales` reaches the\n * members of `sales-emea`; granting `sales-emea` never reaches someone who is\n * only in `sales`. This is the direction people get backwards.\n */\nexport interface TeamService {\n /**\n * Lists teams with optional filtering.\n * Returns an async iterator that automatically handles pagination.\n */\n list(options?: ListTeamsOptions): PageIterator<Team, ListTeamsOptions>\n\n /** Fetches a single page of teams. */\n listPage(options?: ListTeamsOptions): Promise<ListResult<Team>>\n\n /**\n * Gets a single team by slug.\n * @throws {ProteosError} If the team is not found (404)\n */\n get(slug: string): Promise<Team>\n\n /**\n * Creates a team, optionally nested under an existing one.\n * @throws {ProteosError} If the parent would create a cycle or exceed the\n * maximum depth (400 `team_hierarchy_invalid`)\n */\n create(request: CreateTeamRequest): Promise<Team>\n\n /**\n * Updates a team's name, description or parent.\n *\n * The slug cannot be changed: it is half the primary key and every grant\n * references `team:<orgId>/<slug>`, so a rename would orphan them. Pass an\n * empty `parent_team_slug` to promote the team to a root.\n */\n update(slug: string, request: UpdateTeamRequest): Promise<Team>\n\n /**\n * Deletes a team.\n * @throws {ProteosError} If the team still has members or child teams\n * (400 `team_deletion_not_allowed`)\n */\n delete(slug: string): Promise<void>\n\n /**\n * Lists a team's DIRECT members. Membership of ancestor teams is derived, not\n * stored, so it does not appear here.\n */\n getMembers(\n slug: string,\n options?: ListTeamMembersOptions,\n ): PageIterator<TeamMember, ListTeamMembersOptions>\n\n /** Adds a user to a team. */\n addMember(slug: string, request: AddTeamMemberRequest): Promise<TeamMember>\n\n /** Removes a user from a team. */\n removeMember(slug: string, userId: string): Promise<void>\n}\n\n/**\n * Implementation of TeamService.\n */\nexport class TeamServiceImpl implements TeamService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListTeamsOptions = {}): PageIterator<Team, ListTeamsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListTeamsOptions = {}): Promise<ListResult<Team>> {\n return this.client.requestWithQuery<ListResult<Team>>('GET', TEAMS_BASE_PATH, options)\n }\n\n async get(slug: string): Promise<Team> {\n return this.client.request<Team>('GET', `${TEAMS_BASE_PATH}/${slug}`)\n }\n\n async create(request: CreateTeamRequest): Promise<Team> {\n return this.client.request<Team>('POST', TEAMS_BASE_PATH, request)\n }\n\n async update(slug: string, request: UpdateTeamRequest): Promise<Team> {\n return this.client.request<Team>('PATCH', `${TEAMS_BASE_PATH}/${slug}`, request)\n }\n\n async delete(slug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${TEAMS_BASE_PATH}/${slug}`)\n }\n\n getMembers(\n slug: string,\n options: ListTeamMembersOptions = {},\n ): PageIterator<TeamMember, ListTeamMembersOptions> {\n return new PageIterator((opts) => this.fetchMembersPage(slug, opts), options)\n }\n\n async addMember(slug: string, request: AddTeamMemberRequest): Promise<TeamMember> {\n return this.client.request<TeamMember>('POST', `${TEAMS_BASE_PATH}/${slug}/members`, request)\n }\n\n async removeMember(slug: string, userId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${TEAMS_BASE_PATH}/${slug}/members/${userId}`)\n }\n\n private async fetchMembersPage(\n slug: string,\n options: ListTeamMembersOptions,\n ): Promise<ListResult<TeamMember>> {\n return this.client.requestWithQuery<ListResult<TeamMember>>(\n 'GET',\n `${TEAMS_BASE_PATH}/${slug}/members`,\n options,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type { ListUserProfileAssignmentsOptions, UserProfileAssignment } from './types.js'\n\nconst USER_PROFILE_ASSIGNMENTS_BASE_PATH = '/accounts/v1/user-profile-assignments'\n\n/**\n * Service for the org-wide user-profile-assignment listing: \"who holds which\n * profile\" in one request (a profile's member roster, profile badges on a\n * user list). Per-user reads and writes stay on {@link UserService}.\n */\nexport interface UserProfileAssignmentService {\n /** Lists profile assignments across all users of the caller's org. */\n list(\n options?: ListUserProfileAssignmentsOptions,\n ): PageIterator<UserProfileAssignment, ListUserProfileAssignmentsOptions>\n\n /** Fetches a single page of profile assignments. */\n listPage(options?: ListUserProfileAssignmentsOptions): Promise<ListResult<UserProfileAssignment>>\n}\n\nexport class UserProfileAssignmentServiceImpl implements UserProfileAssignmentService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListUserProfileAssignmentsOptions = {},\n ): PageIterator<UserProfileAssignment, ListUserProfileAssignmentsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(\n options: ListUserProfileAssignmentsOptions = {},\n ): Promise<ListResult<UserProfileAssignment>> {\n return this.client.requestWithQuery<ListResult<UserProfileAssignment>>(\n 'GET',\n USER_PROFILE_ASSIGNMENTS_BASE_PATH,\n options,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type { ListOrgUserRoleAssignmentsOptions, UserRoleAssignment } from './types.js'\n\nconst USER_ROLE_ASSIGNMENTS_BASE_PATH = '/accounts/v1/user-role-assignments'\n\n/**\n * Service for the org-wide user-role-assignment listing.\n *\n * One request answers \"who holds which role\" across the whole org — the admin\n * view joining users to their roles (role badges on a user list, a role's\n * member roster, member counts) without a per-user fan-out. Per-user reads and\n * writes stay on {@link UserService} (`users.getRoles` / `assignRole` /\n * `unassignRole`).\n */\nexport interface UserRoleAssignmentService {\n /**\n * Lists role assignments across all users of the caller's org.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param options - Filter and pagination options (`role_slug`, `user_id`)\n * @returns Async iterator over user role assignments\n *\n * @example\n * ```ts\n * // Everyone holding the sales role\n * const sales = await service.list({ role_slug: 'sales' }).all();\n * ```\n */\n list(\n options?: ListOrgUserRoleAssignmentsOptions,\n ): PageIterator<UserRoleAssignment, ListOrgUserRoleAssignmentsOptions>\n\n /**\n * Fetches a single page of role assignments.\n *\n * @param options - Filter and pagination options (including `page`)\n * @returns A single page of assignments with pagination metadata\n */\n listPage(options?: ListOrgUserRoleAssignmentsOptions): Promise<ListResult<UserRoleAssignment>>\n}\n\n/**\n * Implementation of UserRoleAssignmentService.\n */\nexport class UserRoleAssignmentServiceImpl implements UserRoleAssignmentService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListOrgUserRoleAssignmentsOptions = {},\n ): PageIterator<UserRoleAssignment, ListOrgUserRoleAssignmentsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(\n options: ListOrgUserRoleAssignmentsOptions = {},\n ): Promise<ListResult<UserRoleAssignment>> {\n return this.client.requestWithQuery<ListResult<UserRoleAssignment>>(\n 'GET',\n USER_ROLE_ASSIGNMENTS_BASE_PATH,\n options,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n ApiKey,\n AssignRoleRequest,\n CreateApiKeyRequest,\n CreatedApiKey,\n CreateUserRequest,\n ListUserRoleAssignmentsOptions,\n ListUsersOptions,\n SetProfileRequest,\n UpdateUserRequest,\n User,\n UserProfileAssignment,\n UserRoleAssignment,\n} from './types.js'\n\nconst USERS_BASE_PATH = '/accounts/v1/users'\n\n/**\n * Service for managing users.\n * Handles user CRUD operations and role assignments.\n */\nexport interface UserService {\n /**\n * Lists users with optional filtering.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param options - Filter and pagination options\n * @returns Async iterator over users\n *\n * @example\n * ```ts\n * // Iterate over all users\n * for await (const user of service.list()) {\n * console.log(user.email);\n * }\n *\n * // With filtering\n * for await (const user of service.list({ email: 'john@example.com' })) {\n * console.log(user.given_name);\n * }\n * ```\n */\n list(options?: ListUsersOptions): PageIterator<User, ListUsersOptions>\n\n /**\n * Gets a single user by ID.\n *\n * @param id - User ID\n * @returns The user\n * @throws {ProteosError} If user not found (404)\n */\n get(id: string): Promise<User>\n\n /**\n * Creates a new user.\n *\n * @param request - User creation request\n * @returns The created user\n * @throws {ProteosError} If validation fails (400) or conflict (409)\n *\n * @example\n * ```ts\n * const user = await service.create({\n * given_name: 'John',\n * family_name: 'Doe',\n * email: 'john.doe@example.com',\n * });\n * ```\n */\n create(request: CreateUserRequest): Promise<User>\n\n /**\n * Updates an existing user.\n *\n * @param id - User ID\n * @param request - Fields to update\n * @returns The updated user\n * @throws {ProteosError} If user not found (404) or validation fails (400)\n */\n update(id: string, request: UpdateUserRequest): Promise<User>\n\n /**\n * Fetches a single page of users.\n *\n * @param options - Filter and pagination options (including `page`)\n * @returns A single page of users with pagination metadata\n */\n listPage(options?: ListUsersOptions): Promise<ListResult<User>>\n\n /**\n * Gets roles assigned to a user.\n * Returns an async iterator that automatically handles pagination.\n *\n * @param userId - User ID\n * @param options - Filter and pagination options\n * @returns Async iterator over user role assignments\n */\n getRoles(\n userId: string,\n options?: ListUserRoleAssignmentsOptions,\n ): PageIterator<UserRoleAssignment, ListUserRoleAssignmentsOptions>\n\n /**\n * Assigns a role to a user.\n *\n * @param userId - User ID\n * @param request - Role assignment request\n * @returns The created user role assignment\n * @throws {ProteosError} If user or role not found (404)\n */\n assignRole(userId: string, request: AssignRoleRequest): Promise<UserRoleAssignment>\n\n /**\n * Removes a role from a user.\n *\n * @param userId - User ID\n * @param roleSlug - Role slug to unassign\n * @throws {ProteosError} If assignment not found (404)\n */\n unassignRole(userId: string, roleSlug: string): Promise<void>\n\n /**\n * Gets the user's profile assignment in the caller's org.\n *\n * @throws {ProteosError} 404 when the user has no profile\n */\n getProfile(userId: string): Promise<UserProfileAssignment>\n\n /**\n * Sets (replaces) the user's profile in the caller's org — one profile per\n * user per org.\n *\n * @throws {ProteosError} 404 when the user or the profile slug is unknown;\n * 400 `user_not_in_org` when the user holds no role in the org\n */\n setProfile(userId: string, request: SetProfileRequest): Promise<UserProfileAssignment>\n\n /** Clears the user's profile (back to every app's default configuration). */\n clearProfile(userId: string): Promise<void>\n\n /**\n * Lists a user's API keys (display hints only — never tokens).\n *\n * @param userId - User ID, or `'me'` for the calling user\n */\n listApiKeys(userId: string): Promise<ApiKey[]>\n\n /**\n * Creates an API key for the user. The response carries the full token\n * exactly once; it cannot be read again. Requires a JWT session — requests\n * authenticated with an API key are rejected (403).\n *\n * @param userId - User ID, or `'me'` for the calling user\n * @param request - Key name, optional org binding and expiry\n */\n createApiKey(userId: string, request: CreateApiKeyRequest): Promise<CreatedApiKey>\n\n /**\n * Deletes (revokes) an API key. Other services may keep accepting the key\n * for up to their verification-cache TTL (~60s).\n * Unlike create and list, it also works when the request is authenticated\n * with an API key, so a key can revoke itself.\n *\n * @param userId - User ID, or `'me'` for the calling user\n * @param keyId - API key ID\n * @throws {ProteosError} If the key is not found under this user (404)\n */\n deleteApiKey(userId: string, keyId: string): Promise<void>\n}\n\n/**\n * Implementation of UserService.\n */\nexport class UserServiceImpl implements UserService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListUsersOptions = {}): PageIterator<User, ListUsersOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListUsersOptions = {}): Promise<ListResult<User>> {\n return this.client.requestWithQuery<ListResult<User>>('GET', USERS_BASE_PATH, options)\n }\n\n async get(id: string): Promise<User> {\n return this.client.request<User>('GET', `${USERS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateUserRequest): Promise<User> {\n return this.client.request<User>('POST', USERS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateUserRequest): Promise<User> {\n return this.client.request<User>('PATCH', `${USERS_BASE_PATH}/${id}`, request)\n }\n\n getRoles(\n userId: string,\n options: ListUserRoleAssignmentsOptions = {},\n ): PageIterator<UserRoleAssignment, ListUserRoleAssignmentsOptions> {\n return new PageIterator((opts) => this.fetchRolesPage(userId, opts), options)\n }\n\n async assignRole(userId: string, request: AssignRoleRequest): Promise<UserRoleAssignment> {\n return this.client.request<UserRoleAssignment>(\n 'POST',\n `${USERS_BASE_PATH}/${userId}/roles`,\n request,\n )\n }\n\n async unassignRole(userId: string, roleSlug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${USERS_BASE_PATH}/${userId}/roles/${roleSlug}`)\n }\n\n async getProfile(userId: string): Promise<UserProfileAssignment> {\n return this.client.request<UserProfileAssignment>('GET', `${USERS_BASE_PATH}/${userId}/profile`)\n }\n\n async setProfile(userId: string, request: SetProfileRequest): Promise<UserProfileAssignment> {\n return this.client.request<UserProfileAssignment>(\n 'PUT',\n `${USERS_BASE_PATH}/${userId}/profile`,\n request,\n )\n }\n\n async clearProfile(userId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${USERS_BASE_PATH}/${userId}/profile`)\n }\n\n async listApiKeys(userId: string): Promise<ApiKey[]> {\n const response = await this.client.request<{ data: ApiKey[] }>(\n 'GET',\n `${USERS_BASE_PATH}/${userId}/api-keys`,\n )\n return response.data\n }\n\n async createApiKey(userId: string, request: CreateApiKeyRequest): Promise<CreatedApiKey> {\n return this.client.request<CreatedApiKey>(\n 'POST',\n `${USERS_BASE_PATH}/${userId}/api-keys`,\n request,\n )\n }\n\n async deleteApiKey(userId: string, keyId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${USERS_BASE_PATH}/${userId}/api-keys/${keyId}`)\n }\n\n private async fetchRolesPage(\n userId: string,\n options: ListUserRoleAssignmentsOptions,\n ): Promise<ListResult<UserRoleAssignment>> {\n return this.client.requestWithQuery<ListResult<UserRoleAssignment>>(\n 'GET',\n `${USERS_BASE_PATH}/${userId}/roles`,\n options,\n )\n }\n}\n","/**\n * Canonical platform entities — the built-in system resources (users, roles,\n * files, entities, …) that are permission targets alongside user-defined\n * entities. Hand-maintained mirror of the Go registry in\n * packages/go/model/platform/entities.go — keep the two in sync.\n *\n * Used by the role-permission UI to list grantable platform entities next to\n * user-defined entities (from `meta.entities.list()`); permissions key on a\n * free-form `entity_slug`, so the two are assigned uniformly.\n */\nexport interface PlatformEntity {\n slug: string\n /** Display label for the role-permission dropdown. */\n name: string\n}\n\n/** The canonical platform entities, in display order. */\nexport const PLATFORM_ENTITIES: readonly PlatformEntity[] = [\n // Access (account-service)\n { slug: 'organizations', name: 'Organizations' },\n { slug: 'users', name: 'Users' },\n { slug: 'roles', name: 'Roles' },\n { slug: 'user-role-assignments', name: 'User Role Assignments' },\n { slug: 'role-entity-permissions', name: 'Role Entity Permissions' },\n // Teams are the org's structure and a principal that can hold access anywhere\n // a user can. Membership is a separate slug: seeing the org chart and changing\n // who is in it are different decisions, and membership is what moves access.\n { slug: 'teams', name: 'Teams' },\n { slug: 'team-members', name: 'Team Members' },\n // Profiles are the org's user-types (UI defaults; app configurations key on\n // them). ONE per user per org. Managing and assigning are separate grants.\n { slug: 'profiles', name: 'Profiles' },\n { slug: 'user-profile-assignments', name: 'User Profile Assignments' },\n // The share audit trail — a distinct grant from the resources it references.\n // Schema / content (metadata-service)\n { slug: 'entities', name: 'Entities' },\n { slug: 'pages', name: 'Pages' },\n { slug: 'menu-configurations', name: 'Menu Configurations' },\n { slug: 'apps', name: 'Apps' },\n // Typed (app × profile) binding rows: home, menu, agents, record pages.\n { slug: 'app-configurations', name: 'App Configurations' },\n { slug: 'components', name: 'Components' },\n { slug: 'lists', name: 'Lists' },\n { slug: 'list-views', name: 'List Views' },\n { slug: 'design-references', name: 'Design References' },\n // System (metadata-service)\n { slug: 'modules', name: 'Modules' },\n { slug: 'variables', name: 'Variables' },\n { slug: 'deployments', name: 'Deployments' },\n // Records (data-service): proposed record writes awaiting review. read =\n // list/get drafts; write = propose, reject and (with the entity's own\n // write/delete) approve.\n { slug: 'record-drafts', name: 'Record Drafts' },\n // Stored SQL queries — what the Reports tab saves and shares. Scoped by\n // default: a member with no grant reaches their own queries and those\n // shared with them; the unscoped grant reaches every query in the org.\n { slug: 'queries', name: 'Queries' },\n // Storage (storage-service)\n { slug: 'files', name: 'Files' },\n // Automation (function-service)\n { slug: 'hooks', name: 'Hooks' },\n { slug: 'actions', name: 'Actions' },\n // Workflows (workflow-service)\n { slug: 'workflows', name: 'Workflows' },\n { slug: 'workflow-executions', name: 'Workflow Executions' },\n // Knowledge (knowledge-service)\n { slug: 'knowledge-nodes', name: 'Knowledge Nodes' },\n { slug: 'knowledge-links', name: 'Knowledge Links' },\n { slug: 'knowledge-labels', name: 'Knowledge Labels' },\n { slug: 'knowledge-spaces', name: 'Knowledge Spaces' },\n // Agent suite (agent-service)\n { slug: 'agents', name: 'Agents' },\n { slug: 'prompts', name: 'Prompts' },\n { slug: 'skills', name: 'Skills' },\n { slug: 'tools', name: 'Tools' },\n { slug: 'toolsets', name: 'Toolsets' },\n { slug: 'mcp-servers', name: 'MCP Servers' },\n { slug: 'agent-sessions', name: 'Agent Sessions' },\n // Messaging bus (event-service)\n { slug: 'topics', name: 'Topics' },\n { slug: 'events', name: 'Events' },\n // Conversations (conversation-service). NOTE: `connections` is enforced by\n // BOTH conversation-service and connector-service (2026-07 decision) — same\n // concept in both; conversation connections migrate onto connector-service\n // later.\n { slug: 'connections', name: 'Connections' },\n { slug: 'conversations', name: 'Conversations' },\n { slug: 'messages', name: 'Messages' },\n { slug: 'agent-listeners', name: 'Agent Listeners' },\n { slug: 'transcriptions', name: 'Transcriptions' },\n { slug: 'glossary-terms', name: 'Glossary Terms' },\n // Mistranscribed terms proposed by the post-transcription review pass.\n { slug: 'mistranscribed-terms', name: 'Mistranscribed Terms' },\n // Live speech-to-text (the dictation stream) — `read` opens a stream.\n { slug: 'voice', name: 'Voice' },\n // The person-level identity layer (contacts + addresses + merges + consent +\n // erasure) — one grant governs the whole aggregate.\n { slug: 'contacts', name: 'Contacts' },\n // Ingest-time filter rules + their drop-audit events.\n { slug: 'conversation-filters', name: 'Conversation Filters' },\n // The org's conversation taxonomy (read by the pre-summary classifier).\n { slug: 'conversation-types', name: 'Conversation Types' },\n // Generic org-shared audience taxonomy; membership lives on the contact.\n { slug: 'contact-groups', name: 'Contact Groups' },\n // Tone-of-voice synthesis: per-user setups + generated instruction profiles.\n { slug: 'tone-profiles', name: 'Tone Profiles' },\n // Outbound send constraints (windows, connection limits, frequency caps) +\n // their preset catalog.\n { slug: 'sending-rules', name: 'Sending Rules' },\n { slug: 'email-signatures', name: 'Email Signatures' },\n // Reusable messages and snippets, the organisation's and each person's own.\n { slug: 'message-templates', name: 'Message Templates' },\n // The channel_action ledger: acts through a connection that are neither a\n // message nor a reaction (LinkedIn invitations, profile visits, InMail).\n { slug: 'channel-actions', name: 'Channel Actions' },\n // The channel_event ledger: provider-observed delivery / engagement events\n // about outbound messages (delivered, bounced, opened, unsubscribed).\n { slug: 'channel-events', name: 'Channel Events' },\n // Conversation briefs: guidance prepared ahead of a conversation (call, meeting) with a contact.\n { slug: 'conversation-briefs', name: 'Conversation Briefs' },\n // Conversation notes: what a person recorded about a conversation (append log, author-stamped).\n { slug: 'conversation-notes', name: 'Conversation Notes' },\n // Conversation intelligence: the typed questions asked of conversations\n // (definitions), where/when they are evaluated (sets), and the observations\n // they produce incl. their evaluation history (tags).\n { slug: 'conversation-tag-definitions', name: 'Conversation Tag Definitions' },\n { slug: 'conversation-tag-sets', name: 'Conversation Tag Sets' },\n { slug: 'conversation-tags', name: 'Conversation Tags' },\n // Conversation objectives: what a conversation should achieve (definitions)\n // and each definition's standing per conversation (objectives, read-only ledger).\n { slug: 'conversation-objective-definitions', name: 'Conversation Objective Definitions' },\n { slug: 'conversation-objectives', name: 'Conversation Objectives' },\n // Connectors (connector-service). `connections` above is shared; this is the\n // manifest catalog.\n { slug: 'connectors', name: 'Connectors' },\n // Scheduling (scheduling-service)\n { slug: 'calendar-connections', name: 'Calendar Connections' },\n { slug: 'calendars', name: 'Calendars' },\n { slug: 'calendar-events', name: 'Calendar Events' },\n { slug: 'calendar-event-types', name: 'Calendar Event Types' },\n { slug: 'scheduling-links', name: 'Scheduling Links' },\n { slug: 'scheduling-profiles', name: 'Scheduling Profiles' },\n { slug: 'availability-constraints', name: 'Availability Constraints' },\n // Discovery (discovery-service): what users send Proteos to show how they\n // work — screenshots, recordings, written feedback. Mass noun, no plural.\n { slug: 'discovery-evidence', name: 'Discovery Evidence' },\n // Interview guides an admin writes; whoever reads a definition reads its\n // interviews, and whoever writes it invites people.\n { slug: 'discovery-interview-definitions', name: 'Discovery Interview Definitions' },\n // Enrichment (enrichment-service): filling fields through provider\n // waterfalls on the platform's keys. write = start an enrichment run.\n { slug: 'enrichment-runs', name: 'Enrichment Runs' },\n // An entity's enrichment configuration: which attributes get filled, from\n // what, and on which triggers.\n { slug: 'enrichment-mappings', name: 'Enrichment Mappings' },\n // Usage (usage-service): the metering ledger. Read-only and org-level —\n // whoever reads usage reads all of the org's usage.\n { slug: 'usage-records', name: 'Usage Records' },\n // The org's usage limits per meter and period (stacking contributions).\n // Org-level; org roles read, only platform admins write.\n { slug: 'usage-limits', name: 'Usage Limits' },\n] as const\n\n/** Just the platform entity slugs, in canonical order. */\nexport const PLATFORM_ENTITY_SLUGS: readonly string[] = PLATFORM_ENTITIES.map(\n (entity) => entity.slug,\n)\n\n/**\n * Platform entities whose owning service actually enforces the `*_scoped`\n * permission verbs (record-level access grants). Granting `read_scoped` on any\n * other platform entity is legal on the wire but inert — no service narrows\n * by it — so permission UIs only offer the scoped column for these. Extend as\n * services adopt scoped enforcement.\n */\nexport const SCOPED_PLATFORM_ENTITY_SLUGS: readonly string[] = [\n 'knowledge-nodes',\n // agent-service: sessions are owned by their starter; the six config\n // resources by their creator. Scoped lists + /agents/v1/shares.\n 'agent-sessions',\n 'agents',\n 'prompts',\n 'skills',\n 'tools',\n 'toolsets',\n 'mcp-servers',\n // conversation-service: a connection is owned by its owner (user-scoped) or\n // open to the org through its org share (org-scoped); a conversation's rows\n // are stamped once at creation from its connection / parent and extended by\n // shares; messages inherit their conversation. /conversations/v1/shares.\n 'connections',\n 'conversations',\n 'messages',\n // discovery-service: evidence is owned by its creator; a caller holding no\n // grant at all is treated as scoped (own rows), so every org member can\n // send feedback and see what they sent.\n 'discovery-evidence',\n // discovery-service: an interview definition is owned by its creator; its\n // interviews follow it.\n 'discovery-interview-definitions',\n]\n\n/** True when `slug` belongs to a platform entity (reserved; can't be user-created). */\nexport function isPlatformEntity(slug: string): boolean {\n return PLATFORM_ENTITY_SLUGS.includes(slug)\n}\n","import { z } from 'zod'\n\nimport { type PrincipalRef, PrincipalRefSchema } from '../meta/types.js'\nimport type { AuditFields, FileRef, ListOptions } from '../types/common.js'\nimport { AuditFieldsSchema, FileRefSchema } from '../types/common.js'\n\n// ============================================================================\n// Shared Auth Types\n// ============================================================================\n\n/**\n * Base list options with source filters for the auth namespace.\n */\nexport interface AuthListOptions extends ListOptions {\n created_by?: string\n updated_by?: string\n}\n\n// ============================================================================\n// Permission Types\n// ============================================================================\n\n/**\n * Permission level for entity access.\n */\nexport type Permission =\n | 'read'\n | 'write'\n | 'delete'\n // Scoped twins. The grant a role holds decides how much it sees: `read` means\n // every record of the entity in the org, `read_scoped` means only those whose\n // access grants intersect the caller's principals (owned by them, owned by a\n // team they are in, shared with them, or org-wide).\n //\n // The verbs stay independent, so `read` + `write_scoped` reads as \"see every\n // deal, edit only your own\".\n | 'read_scoped'\n | 'write_scoped'\n | 'delete_scoped'\n\n/**\n * Role entity permission - permission granted to a role for a specific entity.\n */\nexport interface RoleEntityPermission extends AuditFields {\n id: string\n org_id: string\n role_slug: string\n entity_slug: string\n permission: Permission\n}\n\nexport const RoleEntityPermissionSchema = AuditFieldsSchema.extend({\n id: z.string(),\n role_slug: z.string(),\n entity_slug: z.string(),\n permission: z.enum(['read', 'write', 'delete', 'read_scoped', 'write_scoped', 'delete_scoped']),\n})\n\n/**\n * Request to assign a permission to a role.\n */\nexport interface AssignPermissionRequest {\n entity_slug: string\n permission: Permission\n}\n\n/**\n * Options for listing role permissions.\n */\nexport interface ListRolePermissionsOptions extends AuthListOptions {\n id?: string\n entity_slug?: string\n permission?: Permission\n}\n\n// ============================================================================\n// User Role Assignment Types\n// ============================================================================\n\n/**\n * User role assignment - a role assigned to a user.\n */\nexport interface UserRoleAssignment extends AuditFields {\n id: string\n user_id: string\n role_slug: string\n org_id: string\n}\n\nexport const UserRoleAssignmentSchema = AuditFieldsSchema.extend({\n id: z.string(),\n user_id: z.string(),\n role_slug: z.string(),\n org_id: z.string(),\n})\n\n/**\n * Request to assign a role to a user.\n */\nexport interface AssignRoleRequest {\n role_slug: string\n}\n\n/**\n * Options for listing user role assignments.\n */\nexport interface ListUserRoleAssignmentsOptions extends AuthListOptions {\n id?: string\n role_slug?: string\n}\n\n/**\n * Options for the org-wide assignment listing (`GET /user-role-assignments`).\n * Unlike {@link ListUserRoleAssignmentsOptions} (which is bound to one user via\n * the path), this one may also filter by `user_id`.\n */\nexport interface ListOrgUserRoleAssignmentsOptions extends AuthListOptions {\n id?: string\n user_id?: string\n role_slug?: string\n}\n\n// ============================================================================\n// User Types\n// ============================================================================\n\n/**\n * User in the system.\n */\nexport interface User extends AuditFields {\n id: string\n email: string\n given_name: string\n family_name: string\n external_id: string\n default_org_id: string\n /**\n * Reference to the user's photo in the storage-service. Absent/null = no\n * photo (clients render initials).\n */\n profile_image?: FileRef | null\n}\n\nexport const UserSchema = AuditFieldsSchema.extend({\n id: z.string(),\n email: z.string(),\n given_name: z.string(),\n family_name: z.string(),\n external_id: z.string(),\n default_org_id: z.string(),\n profile_image: FileRefSchema.nullish(),\n})\n\n/**\n * Request to create a user.\n */\nexport interface CreateUserRequest {\n given_name: string\n family_name: string\n email: string\n default_org_id?: string\n}\n\n/**\n * Request to update a user.\n */\nexport interface UpdateUserRequest {\n given_name?: string\n family_name?: string\n default_org_id?: string\n /**\n * Tri-state: omit = leave unchanged, `null` = remove the photo, a FileRef =\n * set it. Upload the file to the storage-service first and reference it here.\n */\n profile_image?: FileRef | null\n}\n\n/**\n * Caller-scoped `PATCH /me` body. Deliberately narrower than\n * {@link UpdateUserRequest}: a user may edit their own name and photo, but not\n * re-home their account (no `default_org_id`).\n */\nexport interface UpdateMeRequest {\n given_name?: string\n family_name?: string\n /** Tri-state — see {@link UpdateUserRequest.profile_image}. */\n profile_image?: FileRef | null\n}\n\n/**\n * Options for listing users.\n */\nexport interface ListUsersOptions extends AuthListOptions {\n id?: string\n given_name?: string\n family_name?: string\n email?: string\n default_org_id?: string\n}\n\n// ============================================================================\n// Api Key Types\n// ============================================================================\n\n/**\n * A user-scoped API key (pak_ token). Only the display hints\n * (token_prefix/token_suffix) are readable after creation — the full token\n * appears exactly once in {@link CreatedApiKey}.\n */\nexport interface ApiKey extends AuditFields {\n id: string\n user_id: string\n org_id: string\n name: string\n token_prefix: string\n token_suffix: string\n /** ISO timestamp; null = the key never expires. */\n expires_at: string | null\n last_used_at: string | null\n}\n\nexport const ApiKeySchema = AuditFieldsSchema.extend({\n id: z.string(),\n user_id: z.string(),\n org_id: z.string(),\n name: z.string(),\n token_prefix: z.string(),\n token_suffix: z.string(),\n expires_at: z.string().nullable(),\n last_used_at: z.string().nullable(),\n})\n\n/**\n * Create response: the key plus the full token, returned exactly once.\n * Store it immediately — it is not retrievable afterwards.\n */\nexport interface CreatedApiKey extends ApiKey {\n token: string\n}\n\n/**\n * Request to create an API key. Omitting expires_at creates a key that never\n * expires; omitting org_id binds the key to the user's default org.\n */\nexport interface CreateApiKeyRequest {\n name: string\n org_id?: string\n expires_at?: string\n}\n\n// ============================================================================\n// Profile Types\n// ============================================================================\n\n/**\n * Profile — the org's user-type. ONE per user per org (unlike roles, which\n * are many and only decide access). Owns the defaults keyed by subject alone:\n * the app opened after login and the app-switcher allowlist. Metadata app\n * configurations bind per-app defaults (home, menu, agents, record pages) to a\n * profile by slug.\n */\nexport interface Profile extends AuditFields {\n slug: string\n name: string\n org_id: string\n description: string\n /** Module that shipped the profile; '' when authored in the org. */\n module_slug: string\n /** App opened after login; clients fail open to the first visible app. */\n default_app_slug: string\n /** App-switcher allowlist; empty = every app in the org. */\n app_slugs: string[]\n /**\n * Platform-feature allowlist: the areas (`config`, `reports`, `knowledge`,\n * `calendar`, `conversations_own`, `conversations_all`) and Configuration\n * parts (`config_<part>`) the profile shows; empty = every feature,\n * `['none']` = no feature (apps only; `none` cannot be combined). Stored\n * canonical: `conversations_all` ⇒ `conversations_own`, `config_*` ⇒ `config`.\n */\n platform_features: string[]\n}\n\nexport const ProfileSchema = AuditFieldsSchema.extend({\n slug: z.string(),\n name: z.string(),\n org_id: z.string(),\n description: z.string(),\n module_slug: z.string(),\n default_app_slug: z.string(),\n app_slugs: z.array(z.string()),\n // Optional for responses from servers that predate the column.\n platform_features: z.array(z.string()).default([]),\n})\n\nexport interface CreateProfileRequest {\n slug: string\n name: string\n description?: string\n module_slug?: string\n default_app_slug?: string\n app_slugs?: string[]\n platform_features?: string[]\n}\n\nexport interface UpdateProfileRequest {\n name?: string\n description?: string\n module_slug?: string\n default_app_slug?: string\n app_slugs?: string[]\n platform_features?: string[]\n}\n\nexport interface ListProfilesOptions extends AuthListOptions {\n slug?: string\n name?: string\n module_slug?: string\n default_app_slug?: string\n}\n\n/**\n * User profile assignment — a user's ONE profile in an org.\n */\nexport interface UserProfileAssignment extends AuditFields {\n id: string\n user_id: string\n profile_slug: string\n org_id: string\n}\n\nexport const UserProfileAssignmentSchema = AuditFieldsSchema.extend({\n id: z.string(),\n user_id: z.string(),\n profile_slug: z.string(),\n org_id: z.string(),\n})\n\n/** Body of `PUT /users/:id/profile` — replaces the user's profile. */\nexport interface SetProfileRequest {\n profile_slug: string\n}\n\n/** Filters for the org-wide `GET /user-profile-assignments` listing. */\nexport interface ListUserProfileAssignmentsOptions extends AuthListOptions {\n id?: string\n user_id?: string\n profile_slug?: string\n}\n\n// ============================================================================\n// Role Types\n// ============================================================================\n\n/**\n * Role in the system.\n */\nexport interface Role extends AuditFields {\n slug: string\n name: string\n org_id: string\n description: string\n}\n\nexport const RoleSchema = AuditFieldsSchema.extend({\n slug: z.string(),\n name: z.string(),\n org_id: z.string(),\n description: z.string(),\n})\n\n/**\n * Request to create a role.\n */\nexport interface CreateRoleRequest {\n org_id: string\n slug: string\n name: string\n description?: string\n}\n\n/**\n * Request to update a role.\n */\nexport interface UpdateRoleRequest {\n org_id?: string\n name?: string\n description?: string\n}\n\n/**\n * Options for listing roles.\n */\nexport interface ListRolesOptions extends AuthListOptions {\n org_id?: string\n slug?: string\n name?: string\n description?: string\n}\n\n// ============================================================================\n// Team Types\n// ============================================================================\n\n/**\n * A team — a node in the org's structure, and a principal that can hold access\n * anywhere a user can.\n *\n * Hierarchy rolls UP: a member of a child team counts as a member of every\n * ancestor **for grants made to that ancestor**. Granting `sales` reaches the\n * members of `sales-emea`; granting `sales-emea` never reaches someone who is\n * only in `sales`.\n *\n * The slug is immutable — it is half the primary key, and grants reference\n * `team:<orgId>/<slug>`.\n */\nexport interface Team extends AuditFields {\n slug: string\n name: string\n org_id: string\n description: string\n /** This team's parent within the same org; empty for a root team. */\n parent_team_slug: string\n}\n\nexport const TeamSchema = AuditFieldsSchema.extend({\n slug: z.string(),\n name: z.string(),\n org_id: z.string(),\n description: z.string(),\n parent_team_slug: z.string(),\n})\n\n/**\n * One user's DIRECT membership of one team. Membership of ancestor teams is\n * derived rather than stored, so it never appears as a row here.\n */\nexport interface TeamMember extends AuditFields {\n id: string\n org_id: string\n team_slug: string\n user_id: string\n}\n\nexport const TeamMemberSchema = AuditFieldsSchema.extend({\n id: z.string(),\n org_id: z.string(),\n team_slug: z.string(),\n user_id: z.string(),\n})\n\n/**\n * Request to create a team.\n */\nexport interface CreateTeamRequest {\n org_id?: string\n slug: string\n name: string\n description?: string\n /** Nests the team under an existing one in the same org. Omit for a root. */\n parent_team_slug?: string\n}\n\n/**\n * Request to update a team.\n *\n * `slug` is deliberately absent: it is half the primary key and is referenced by\n * every grant as `team:<orgId>/<slug>`, so renaming would orphan them.\n */\nexport interface UpdateTeamRequest {\n name?: string\n description?: string\n /** Re-parents the team; an explicit empty string promotes it to a root. */\n parent_team_slug?: string\n}\n\nexport interface ListTeamsOptions extends AuthListOptions {\n org_id?: string\n slug?: string\n name?: string\n description?: string\n parent_team_slug?: string\n}\n\n/**\n * Request to add a user to a team.\n */\nexport interface AddTeamMemberRequest {\n user_id: string\n}\n\nexport interface ListTeamMembersOptions extends AuthListOptions {\n org_id?: string\n team_slug?: string\n user_id?: string\n}\n\n// ============================================================================\n// Organization Types\n// ============================================================================\n\n/**\n * Organization in the system.\n */\nexport interface Organization extends AuditFields {\n id: string\n name: string\n description: string\n}\n\nexport const OrganizationSchema = AuditFieldsSchema.extend({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n})\n\n/**\n * Request to create an organization.\n */\nexport interface CreateOrganizationRequest {\n name: string\n description?: string\n}\n\n/**\n * Request to update an organization.\n */\nexport interface UpdateOrganizationRequest {\n name?: string\n description?: string\n}\n\n/**\n * Options for listing organizations.\n */\nexport interface ListOrganizationsOptions extends AuthListOptions {\n id?: string\n name?: string\n description?: string\n}\n\n/**\n * The verbs a share can grant. Only these three — a typo'd permission is\n * rejected rather than accepted as a grant that confers nothing.\n */\nexport type SharePermission = 'read' | 'write' | 'delete'\n\n/**\n * The wire shape of a share write. Identical for granting and revoking, and\n * shaped like the grant it produces, so ONE endpoint per owning service serves\n * every entity rather than one endpoint per entity.\n */\nexport interface ShareRequest {\n entity_slug: string\n record_id: string\n principal: PrincipalRef\n permission: SharePermission\n}\n\nexport const SharePermissionSchema = z.enum(['read', 'write', 'delete'])\n\n/**\n * One stored share: a principal holding one verb on one record, with the\n * grantor as provenance. Every row is an explicit share — ownership and\n * granting attributes are evaluated live and never stored.\n */\nexport interface ShareRow {\n entity_slug: string\n record_id: string\n /** Rendered principal string: `user:<id>` | `team:<orgId>/<slug>` | `org:<orgId>`. */\n principal: string\n permission: SharePermission\n created_by?: { type: string; id: string }\n created_at?: string\n}\n\nexport const ShareRequestSchema = z.object({\n entity_slug: z.string(),\n record_id: z.string(),\n principal: PrincipalRefSchema,\n permission: SharePermissionSchema,\n})\n","import type { ProteosClient } from '../client.js'\nimport { type MeService, MeServiceImpl } from './me.js'\nimport { type OrganizationService, OrganizationServiceImpl } from './organizations.js'\nimport { type ProfileService, ProfileServiceImpl } from './profiles.js'\nimport { type RoleService, RoleServiceImpl } from './roles.js'\nimport { type ShareService, ShareServiceImpl } from './shares.js'\nimport { type TeamService, TeamServiceImpl } from './teams.js'\nimport {\n type UserProfileAssignmentService,\n UserProfileAssignmentServiceImpl,\n} from './user-profile-assignments.js'\nimport {\n type UserRoleAssignmentService,\n UserRoleAssignmentServiceImpl,\n} from './user-role-assignments.js'\nimport { type UserService, UserServiceImpl } from './users.js'\n\n/**\n * Client for the Proteos Auth Service API.\n * Provides access to all authentication and authorization services.\n *\n * @example\n * ```ts\n * import { ProteosClient, AccountClient } from 'proteos-sdk';\n *\n * const client = new ProteosClient({\n * baseUrl: 'https://api.proteos.ai',\n * token: 'your-api-token',\n * });\n *\n * const auth = new AccountClient(client);\n *\n * // Use services\n * const users = await auth.users.list().all();\n * const role = await auth.roles.get('admin');\n * const org = await auth.organizations.get('org-123');\n * ```\n */\nexport class AccountClient {\n /**\n * Service for caller-scoped queries (\"who am I\", my organizations).\n */\n readonly me: MeService\n\n /**\n * Service for managing users and their role assignments.\n */\n readonly users: UserService\n\n /**\n * Service for managing roles and their entity permissions.\n */\n readonly roles: RoleService\n\n /**\n * Service for the org-wide user-role-assignment listing (\"who holds which\n * role\" in one request).\n */\n readonly userRoleAssignments: UserRoleAssignmentService\n\n /**\n * Service for managing profiles (the org's user-types, one per user).\n */\n readonly profiles: ProfileService\n\n /**\n * Service for the org-wide user-profile-assignment listing.\n */\n readonly userProfileAssignments: UserProfileAssignmentService\n\n /**\n * Service for managing organizations.\n */\n readonly organizations: OrganizationService\n\n /**\n * Service for managing teams and their membership.\n */\n readonly teams: TeamService\n\n /**\n * Service for sharing individual resources with a principal.\n *\n * Lives here rather than on the owning resource's client because sharing is\n * ONE concept across every resource type — a deal, a conversation, a\n * knowledge space. Callers name an entity; which service handles the write is\n * the SDK's problem, so centralizing it server-side later moves no caller.\n */\n readonly shares: ShareService\n\n /**\n * Creates a new AccountClient instance.\n *\n * @param client - The base ProteosClient to use for API requests\n */\n constructor(client: ProteosClient) {\n this.me = new MeServiceImpl(client)\n this.users = new UserServiceImpl(client)\n this.roles = new RoleServiceImpl(client)\n this.userRoleAssignments = new UserRoleAssignmentServiceImpl(client)\n this.profiles = new ProfileServiceImpl(client)\n this.userProfileAssignments = new UserProfileAssignmentServiceImpl(client)\n this.organizations = new OrganizationServiceImpl(client)\n this.teams = new TeamServiceImpl(client)\n this.shares = new ShareServiceImpl(client)\n }\n}\n\nexport type { MeService } from './me.js'\nexport type { OrganizationService } from './organizations.js'\n// Re-export platform entities (canonical mirror of the Go registry)\nexport type { PlatformEntity } from './platform-entities.js'\nexport {\n isPlatformEntity,\n PLATFORM_ENTITIES,\n PLATFORM_ENTITY_SLUGS,\n SCOPED_PLATFORM_ENTITY_SLUGS,\n} from './platform-entities.js'\nexport type { ProfileService } from './profiles.js'\nexport type { RoleService } from './roles.js'\n// Share routing — exported so a UI can hide a share affordance it cannot serve.\nexport { isShareable, type ShareService, shareRouteFor } from './shares.js'\nexport type { TeamService } from './teams.js'\n// Re-export types\nexport type {\n AddTeamMemberRequest,\n // Api key types\n ApiKey,\n AssignPermissionRequest,\n AssignRoleRequest,\n // Shared types\n AuthListOptions,\n CreateApiKeyRequest,\n CreatedApiKey,\n CreateOrganizationRequest,\n CreateProfileRequest,\n CreateRoleRequest,\n CreateTeamRequest,\n CreateUserRequest,\n ListOrganizationsOptions,\n ListOrgUserRoleAssignmentsOptions,\n ListProfilesOptions,\n ListRolePermissionsOptions,\n ListRolesOptions,\n ListTeamMembersOptions,\n ListTeamsOptions,\n ListUserProfileAssignmentsOptions,\n ListUserRoleAssignmentsOptions,\n ListUsersOptions,\n // Organization types\n Organization,\n // Permission types\n Permission,\n // Profile types\n Profile,\n // Role types\n Role,\n RoleEntityPermission,\n SetProfileRequest,\n // Share types\n SharePermission,\n ShareRequest,\n ShareRow,\n // Team types\n Team,\n TeamMember,\n UpdateMeRequest,\n UpdateOrganizationRequest,\n UpdateProfileRequest,\n UpdateRoleRequest,\n UpdateTeamRequest,\n UpdateUserRequest,\n // User types\n User,\n UserProfileAssignment,\n // User role assignment types\n UserRoleAssignment,\n} from './types.js'\n// Re-export Zod schemas\nexport {\n ApiKeySchema,\n OrganizationSchema,\n ProfileSchema,\n RoleEntityPermissionSchema,\n RoleSchema,\n SharePermissionSchema,\n ShareRequestSchema,\n TeamMemberSchema,\n TeamSchema,\n UserProfileAssignmentSchema,\n UserRoleAssignmentSchema,\n UserSchema,\n} from './types.js'\nexport type { UserProfileAssignmentService } from './user-profile-assignments.js'\nexport type { UserRoleAssignmentService } from './user-role-assignments.js'\n// Re-export service interfaces\nexport type { UserService } from './users.js'\n","/**\n * Value types that can be converted to query parameters.\n */\nexport type QueryValue = string | number | boolean | null | undefined\n\n/**\n * Object that can be converted to query parameters.\n * Supports nested objects (which are skipped during conversion).\n */\nexport type QueryObject = Record<string, QueryValue | QueryValue[] | Record<string, unknown>>\n\n/**\n * Converts an object to URLSearchParams for use in query strings.\n * Handles nested objects by flattening them (skips complex nested structures).\n * Skips null and undefined values.\n *\n * @param obj - Object to convert\n * @returns URLSearchParams instance\n *\n * @example\n * ```ts\n * toQueryParams({ page: 1, name: 'test', is_active: true })\n * // => URLSearchParams { page: '1', name: 'test', is_active: 'true' }\n *\n * toQueryParams({ filter: { slug: 'my-slug' } })\n * // => URLSearchParams {} (nested objects are skipped)\n * ```\n */\nexport function toQueryParams(obj: object | undefined | null): URLSearchParams {\n const params = new URLSearchParams()\n\n if (!obj) {\n return params\n }\n\n for (const [key, value] of Object.entries(obj)) {\n appendQueryParam(params, key, value as QueryValue | QueryValue[] | Record<string, unknown>)\n }\n\n return params\n}\n\n/**\n * Appends a single value to URLSearchParams.\n */\nfunction appendQueryParam(\n params: URLSearchParams,\n key: string,\n value: QueryValue | QueryValue[] | Record<string, unknown>,\n): void {\n // Skip null and undefined\n if (value === null || value === undefined) {\n return\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item !== null && item !== undefined) {\n params.append(key, String(item))\n }\n }\n return\n }\n\n // Skip nested objects (complex types)\n if (typeof value === 'object') {\n return\n }\n\n // Convert primitives to string\n params.set(key, String(value))\n}\n\n/**\n * Converts a URLSearchParams instance to a query string.\n * Returns empty string if no parameters.\n *\n * @param params - URLSearchParams to convert\n * @returns Query string (without leading '?')\n */\nexport function toQueryString(params: URLSearchParams): string {\n const str = params.toString()\n return str\n}\n\n/**\n * Builds a full URL with query parameters.\n *\n * @param baseUrl - Base URL (may already have query params)\n * @param path - Path to append\n * @param query - Query parameters to add\n * @returns Full URL string\n */\nexport function buildUrl(baseUrl: string, path: string, query?: object): string {\n const url = new URL(path, baseUrl)\n\n if (query) {\n const params = toQueryParams(query)\n params.forEach((value, key) => {\n url.searchParams.append(key, value)\n })\n }\n\n return url.toString()\n}\n","/**\n * Token provider function for dynamic authentication.\n * Can return a token synchronously or asynchronously.\n */\nexport type TokenProvider = () => string | Promise<string>\n\n/**\n * Configuration options for the ProteosClient.\n */\nexport interface ClientOptions {\n /**\n * Base URL for API requests.\n * Example: 'https://api.proteos.ai'\n */\n baseUrl: string\n\n /**\n * Static bearer token for authentication.\n * Use this for simple authentication scenarios.\n */\n token?: string\n\n /**\n * Dynamic token provider function.\n * Called before each request to get the current token.\n * Takes precedence over static token if both are provided.\n * Useful for token refresh scenarios.\n */\n tokenProvider?: TokenProvider\n\n /**\n * Request timeout in milliseconds.\n * Default: 30000 (30 seconds)\n */\n timeout?: number\n\n /**\n * Custom fetch implementation.\n * Useful for testing or environments without native fetch.\n * Default: global fetch\n */\n fetch?: typeof fetch\n\n /**\n * Custom headers to include in all requests.\n * Authorization header is set automatically from token/tokenProvider.\n */\n headers?: Record<string, string>\n}\n\n/**\n * Internal resolved options with defaults applied.\n */\nexport interface ResolvedClientOptions {\n baseUrl: string\n token?: string\n tokenProvider?: TokenProvider\n timeout: number\n fetch: typeof fetch\n headers: Record<string, string>\n}\n\n/**\n * Default client options.\n */\nexport const DEFAULT_OPTIONS = {\n timeout: 30000,\n headers: {},\n} as const\n\n/**\n * Request timeout for invoking an action or connector method. Function-service\n * lets one invocation run for 60s and connector-service waits 70s for it, so\n * the caller waits longer than both: the invocation's result, or its own\n * timeout error, reaches the caller instead of a client-side abort.\n */\nexport const INVOKE_TIMEOUT_MS = 75_000\n\n/** Request timeout for a batch action invocation (5 min server budget). */\nexport const BATCH_INVOKE_TIMEOUT_MS = 315_000\n\n/**\n * Resolves client options by applying defaults.\n */\nexport function resolveOptions(options: ClientOptions): ResolvedClientOptions {\n return {\n baseUrl: options.baseUrl.replace(/\\/$/, ''), // Remove trailing slash\n ...(options.token !== undefined ? { token: options.token } : {}),\n ...(options.tokenProvider !== undefined ? { tokenProvider: options.tokenProvider } : {}),\n timeout: options.timeout ?? DEFAULT_OPTIONS.timeout,\n fetch: (options.fetch ?? globalThis.fetch).bind(globalThis),\n headers: { ...DEFAULT_OPTIONS.headers, ...options.headers },\n }\n}\n\n/**\n * Options for individual requests.\n */\nexport interface RequestOptions {\n /** Request timeout in milliseconds (overrides client default) */\n timeout?: number\n /**\n * Skip attaching the Authorization header. Only meaningful for the public,\n * unauthenticated endpoints (`/meta/v1/public/*`, `/functions/v1/public/*`)\n * — every other endpoint 401s without a bearer.\n */\n skipAuth?: boolean\n /** Additional headers for this request */\n headers?: Record<string, string>\n /** AbortSignal for request cancellation */\n signal?: AbortSignal\n /**\n * Let the request outlive the page that sent it (fetch `keepalive`): for the\n * last report a page sends as it is closed. Browsers cap the body of such\n * requests at 64 KB in total.\n */\n keepalive?: boolean\n}\n","import { type EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-source'\nimport { ErrorCode, ProteosError, parseErrorResponse } from './errors.js'\nimport { toQueryParams } from './http/query-params.js'\nimport {\n type ClientOptions,\n type RequestOptions,\n type ResolvedClientOptions,\n resolveOptions,\n} from './types/options.js'\n\n/** One parsed Server-Sent-Events frame yielded by {@link ProteosClient.streamEvents}. */\nexport interface SseFrame {\n /** The frame `id:` line — Proteos services use the per-stream monotonic seq. */\n id?: string\n /** The frame `event:` line — the named event type. */\n event?: string\n /** The frame `data:` line — the raw payload (typically JSON). */\n data: string\n}\n\n/** Options for opening an SSE stream. */\nexport interface StreamOptions {\n /** Abort to tear the stream down (the normal stop path). */\n signal?: AbortSignal\n}\n\n/** True when an error is an AbortError (a stream's normal teardown). */\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === 'AbortError'\n}\n\n/**\n * Base HTTP client for all Proteos services.\n * Handles authentication, request/response formatting, and error handling.\n */\nexport class ProteosClient {\n private readonly options: ResolvedClientOptions\n\n /**\n * Creates a new ProteosClient instance.\n *\n * @param options - Client configuration options\n *\n * @example\n * ```ts\n * // With static token\n * const client = new ProteosClient({\n * baseUrl: 'https://api.proteos.ai',\n * token: 'your-api-token',\n * });\n *\n * // With dynamic token provider\n * const client = new ProteosClient({\n * baseUrl: 'https://api.proteos.ai',\n * tokenProvider: async () => {\n * return await authService.getAccessToken();\n * },\n * });\n * ```\n */\n constructor(options: ClientOptions) {\n this.options = resolveOptions(options)\n }\n\n /**\n * Returns the base URL configured for this client.\n */\n get baseUrl(): string {\n return this.options.baseUrl\n }\n\n /**\n * Gets the current authentication token.\n * Calls tokenProvider if available, otherwise returns static token.\n */\n private async getToken(): Promise<string | undefined> {\n if (this.options.tokenProvider) {\n return await this.options.tokenProvider()\n }\n return this.options.token\n }\n\n /**\n * Builds the headers for a request.\n */\n private async buildHeaders(requestOptions?: RequestOptions): Promise<Headers> {\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...this.options.headers,\n ...requestOptions?.headers,\n })\n\n if (!requestOptions?.skipAuth) {\n const token = await this.getToken()\n if (token) {\n headers.set('Authorization', `Bearer ${token}`)\n }\n }\n\n return headers\n }\n\n /**\n * Creates an AbortSignal with timeout.\n */\n private createTimeoutSignal(requestOptions?: RequestOptions): AbortSignal {\n const timeout = requestOptions?.timeout ?? this.options.timeout\n\n // Combine user signal with timeout signal if both exist\n if (requestOptions?.signal) {\n const controller = new AbortController()\n\n // Abort when user signal aborts\n requestOptions.signal.addEventListener('abort', () => {\n controller.abort(requestOptions.signal?.reason)\n })\n\n // Abort on timeout\n const timeoutId = setTimeout(() => {\n controller.abort(new Error(`Request timeout after ${timeout}ms`))\n }, timeout)\n\n // Clean up timeout if aborted early\n controller.signal.addEventListener('abort', () => {\n clearTimeout(timeoutId)\n })\n\n return controller.signal\n }\n\n return AbortSignal.timeout(timeout)\n }\n\n /**\n * Runs fetch and turns a transport failure — DNS, connection refused, the\n * network being down, the timeout signal firing — into a ProteosError with\n * httpStatus 0, so callers can tell \"the server said no\" from \"the server\n * was never reached\" (the latter is worth retrying). An abort the caller\n * asked for is theirs and passes through untouched.\n */\n private async send(url: string, init: RequestInit): Promise<Response> {\n try {\n return await this.options.fetch(url, init)\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error\n const message = error instanceof Error ? error.message : 'Network request failed'\n const isTimeout =\n error instanceof Error &&\n (error.name === 'TimeoutError' || error.message.startsWith('Request timeout'))\n throw new ProteosError(\n message,\n 0,\n isTimeout ? ErrorCode.REQUEST_TIMEOUT : ErrorCode.NETWORK_ERROR,\n )\n }\n }\n\n /**\n * Performs an HTTP request and decodes the JSON response.\n *\n * @param method - HTTP method (GET, POST, PATCH, DELETE, etc.)\n * @param path - Request path (appended to baseUrl)\n * @param body - Request body (will be JSON-serialized)\n * @param requestOptions - Optional request configuration\n * @returns Decoded response body\n * @throws {ProteosError} If the response status is >= 400\n */\n async request<T>(\n method: string,\n path: string,\n body?: unknown,\n requestOptions?: RequestOptions,\n ): Promise<T> {\n return this.requestWithQuery(method, path, undefined, body, requestOptions)\n }\n\n /**\n * Performs an HTTP request with query parameters.\n *\n * @param method - HTTP method\n * @param path - Request path\n * @param query - Query parameters object\n * @param body - Request body\n * @param requestOptions - Optional request configuration\n * @returns Decoded response body\n * @throws {ProteosError} If the response status is >= 400\n */\n async requestWithQuery<T, Q extends object = object>(\n method: string,\n path: string,\n query?: Q,\n body?: unknown,\n requestOptions?: RequestOptions,\n ): Promise<T> {\n let url = `${this.options.baseUrl}${path}`\n\n if (query) {\n const params = toQueryParams(query)\n const queryString = params.toString()\n if (queryString) {\n url += `?${queryString}`\n }\n }\n\n const headers = await this.buildHeaders(requestOptions)\n const signal = this.createTimeoutSignal(requestOptions)\n\n const response = await this.send(url, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : null,\n signal,\n ...(requestOptions?.keepalive ? { keepalive: true } : {}),\n })\n\n if (response.status >= 400) {\n throw await parseErrorResponse(response)\n }\n\n // No content response\n if (response.status === 204) {\n return undefined as T\n }\n\n // Parse JSON response\n const text = await response.text()\n if (!text) {\n return undefined as T\n }\n\n try {\n return JSON.parse(text) as T\n } catch {\n throw new ProteosError(\n `Failed to parse response as JSON: ${text.slice(0, 100)}`,\n response.status,\n 'parse_error',\n )\n }\n }\n\n /**\n * Performs a multipart form request (for file uploads).\n *\n * @param method - HTTP method\n * @param path - Request path\n * @param formData - FormData instance with files and fields\n * @param requestOptions - Optional request configuration\n * @returns Decoded response body\n * @throws {ProteosError} If the response status is >= 400\n */\n async requestMultipart<T>(\n method: string,\n path: string,\n formData: FormData,\n requestOptions?: RequestOptions,\n ): Promise<T> {\n const url = `${this.options.baseUrl}${path}`\n\n // Don't set Content-Type - let fetch set it with boundary\n const headers = new Headers({\n Accept: 'application/json',\n ...this.options.headers,\n ...requestOptions?.headers,\n })\n\n const token = await this.getToken()\n if (token) {\n headers.set('Authorization', `Bearer ${token}`)\n }\n\n const signal = this.createTimeoutSignal(requestOptions)\n\n const response = await this.send(url, {\n method,\n headers,\n body: formData,\n signal,\n })\n\n if (response.status >= 400) {\n throw await parseErrorResponse(response)\n }\n\n if (response.status === 204) {\n return undefined as T\n }\n\n return (await response.json()) as T\n }\n\n /**\n * Performs an HTTP request and returns the raw response.\n * Used for downloading files or streaming responses.\n *\n * @param method - HTTP method\n * @param path - Request path\n * @param body - Request body\n * @param requestOptions - Optional request configuration\n * @returns Object with response body stream and full Response object\n * @throws {ProteosError} If the response status is >= 400\n */\n async requestRaw(\n method: string,\n path: string,\n body?: unknown,\n requestOptions?: RequestOptions,\n ): Promise<{ body: ReadableStream<Uint8Array> | null; response: Response }> {\n const url = `${this.options.baseUrl}${path}`\n\n const headers = await this.buildHeaders(requestOptions)\n const signal = this.createTimeoutSignal(requestOptions)\n\n const response = await this.send(url, {\n method,\n headers,\n body: body !== undefined ? JSON.stringify(body) : null,\n signal,\n })\n\n if (response.status >= 400) {\n throw await parseErrorResponse(response)\n }\n\n return {\n body: response.body,\n response,\n }\n }\n\n /**\n * Opens a Server-Sent-Events stream and yields each frame as it arrives.\n *\n * Built on `@microsoft/fetch-event-source` (not the browser-native\n * `EventSource`, which can't set an `Authorization` header) so the bearer token\n * is attached like any other request. The library tracks `Last-Event-ID` and\n * reconnects with exponential backoff on transient errors; a 4xx is fatal and\n * rejects. The stream runs until the caller's `AbortSignal` fires.\n *\n * The token is resolved once at stream start; teardown is the caller's signal.\n *\n * @param path - Request path (appended to baseUrl)\n * @param requestOptions - Optional request configuration (signal)\n * @returns Async generator of parsed {@link SseFrame}s\n * @throws {ProteosError} On a non-retryable (4xx) response\n */\n async *streamEvents(\n path: string,\n requestOptions?: StreamOptions,\n ): AsyncGenerator<SseFrame, void, unknown> {\n const url = `${this.options.baseUrl}${path}`\n\n const headers: Record<string, string> = { ...this.options.headers }\n const token = await this.getToken()\n if (token) {\n headers.Authorization = `Bearer ${token}`\n }\n\n // Bridge fetch-event-source's callbacks into an async generator: producer\n // pushes frames onto a queue, the consumer (this generator) drains it,\n // parking on a promise whenever the queue is empty.\n const queue: SseFrame[] = []\n let wake: (() => void) | null = null\n let finished = false\n let failure: unknown\n\n const notify = () => {\n wake?.()\n wake = null\n }\n const push = (frame: SseFrame) => {\n queue.push(frame)\n notify()\n }\n const finish = (error?: unknown) => {\n if (error !== undefined) failure = error\n finished = true\n notify()\n }\n\n const controller = new AbortController()\n const onExternalAbort = () => controller.abort()\n if (requestOptions?.signal) {\n if (requestOptions.signal.aborted) controller.abort()\n else requestOptions.signal.addEventListener('abort', onExternalAbort, { once: true })\n }\n\n const streaming = fetchEventSource(url, {\n method: 'GET',\n headers,\n signal: controller.signal,\n fetch: this.options.fetch,\n // Keep streaming when the tab is backgrounded (default would disconnect).\n openWhenHidden: true,\n onopen: async (response: Response) => {\n if (response.status >= 400) {\n throw await parseErrorResponse(response)\n }\n },\n onmessage: (message: EventSourceMessage) => {\n push({\n id: message.id || undefined,\n event: message.event || undefined,\n data: message.data,\n })\n },\n onerror: (error: unknown) => {\n // Abort + 4xx are fatal (rethrow to stop). Everything else is transient\n // — return a backoff so the library reconnects (Last-Event-ID resumes).\n if (isAbortError(error)) throw error\n if (error instanceof ProteosError && error.httpStatus >= 400 && error.httpStatus < 500) {\n throw error\n }\n return 2000\n },\n })\n .then(() => finish())\n .catch((error: unknown) => finish(error))\n\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift() as SseFrame\n continue\n }\n if (finished) break\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n }\n if (failure !== undefined && !isAbortError(failure)) throw failure\n } finally {\n controller.abort()\n requestOptions?.signal?.removeEventListener('abort', onExternalAbort)\n await streaming.catch(() => {})\n }\n }\n\n /**\n * Opens an authenticated WebSocket to a service path and resolves once it is\n * open.\n *\n * The browser-native `WebSocket` can't set an `Authorization` header, so the\n * access token is passed via the `bearer` subprotocol (`[\"bearer\", token]`),\n * which the gateway lifts back into the auth header — the same token resolved\n * for every other request. The `http(s)` base URL is rewritten to `ws(s)`.\n *\n * @param path - Request path (appended to baseUrl), including any query string\n * @returns The open WebSocket\n */\n async openWebSocket(path: string): Promise<WebSocket> {\n const wsBaseUrl = this.options.baseUrl.replace(/^http/, 'ws')\n const url = `${wsBaseUrl}${path}`\n\n const token = await this.getToken()\n const socket = token ? new WebSocket(url, ['bearer', token]) : new WebSocket(url)\n\n await new Promise<void>((resolve, reject) => {\n socket.onopen = () => resolve()\n socket.onerror = () => reject(new ProteosError('WebSocket connection failed', 0, 'ws_error'))\n })\n // Clear the bootstrap handlers so the caller owns the socket cleanly.\n socket.onopen = null\n socket.onerror = null\n return socket\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { INVOKE_TIMEOUT_MS } from '../types/options.js'\nimport type {\n ConnectionTokenResponse,\n Connector,\n ConnectorConnection,\n ConnectorMethod,\n CreateConnectorConnectionRequest,\n InstallConnectorConnectionResponse,\n InvokeMethodResponse,\n ListConnectorConnectionsQuery,\n ListConnectorsQuery,\n ListResponse,\n UpdateConnectorConnectionRequest,\n} from './types.js'\n\nexport * from './types.js'\n\nconst CONNECTOR_BASE_PATH = '/connectors/v1'\n\n/**\n * Facade for connector-service: the connector manifest catalog and\n * connections (install flow, token release, connector-method invocation).\n *\n * ```ts\n * const connector = new ConnectorClient(client)\n * const catalog = await connector.connectors.list()\n * const { authorization_url } = await connector.connections.install(id)\n * const events = await connector.connections.invokeMethod(id, 'list_events', {})\n * ```\n */\nexport class ConnectorClient {\n readonly connectors: ConnectorCatalogService\n readonly connections: ConnectorConnectionService\n\n constructor(client: ProteosClient) {\n this.connectors = new ConnectorCatalogServiceImpl(client)\n this.connections = new ConnectorConnectionServiceImpl(client)\n }\n}\n\n/** The connector manifest catalog (pre-built + org-custom). */\nexport interface ConnectorCatalogService {\n list(query?: ListConnectorsQuery): Promise<ListResponse<Connector>>\n get(key: string): Promise<Connector>\n /** A connector's callable methods (sugar over get().methods). */\n listMethods(key: string): Promise<ConnectorMethod[]>\n}\n\nclass ConnectorCatalogServiceImpl implements ConnectorCatalogService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConnectorsQuery = {}): Promise<ListResponse<Connector>> {\n return this.client.requestWithQuery('GET', `${CONNECTOR_BASE_PATH}/connectors`, query)\n }\n\n get(key: string): Promise<Connector> {\n return this.client.request(\n 'GET',\n `${CONNECTOR_BASE_PATH}/connectors/${encodeURIComponent(key)}`,\n )\n }\n\n async listMethods(key: string): Promise<ConnectorMethod[]> {\n const connector = await this.get(key)\n return connector.methods ?? []\n }\n}\n\n/** Configured integration instances + method invocation. */\nexport interface ConnectorConnectionService {\n list(query?: ListConnectorConnectionsQuery): Promise<ListResponse<ConnectorConnection>>\n get(id: string): Promise<ConnectorConnection>\n create(request: CreateConnectorConnectionRequest): Promise<ConnectorConnection>\n update(id: string, request: UpdateConnectorConnectionRequest): Promise<ConnectorConnection>\n delete(id: string): Promise<void>\n /** Begin the OAuth install flow; open the returned URL in a popup. */\n install(id: string): Promise<InstallConnectorConnectionResponse>\n /** Release the connection's usable token material (requires connections write). */\n token(id: string): Promise<ConnectionTokenResponse>\n /** Invoke a connector method; returns the unwrapped result. */\n invokeMethod<T = unknown>(id: string, method: string, params?: unknown): Promise<T>\n}\n\nclass ConnectorConnectionServiceImpl implements ConnectorConnectionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConnectorConnectionsQuery = {}): Promise<ListResponse<ConnectorConnection>> {\n return this.client.requestWithQuery('GET', `${CONNECTOR_BASE_PATH}/connections`, query)\n }\n\n get(id: string): Promise<ConnectorConnection> {\n return this.client.request(\n 'GET',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateConnectorConnectionRequest): Promise<ConnectorConnection> {\n return this.client.request('POST', `${CONNECTOR_BASE_PATH}/connections`, request)\n }\n\n update(id: string, request: UpdateConnectorConnectionRequest): Promise<ConnectorConnection> {\n return this.client.request(\n 'PATCH',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n )\n }\n\n install(id: string): Promise<InstallConnectorConnectionResponse> {\n return this.client.request(\n 'POST',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/install`,\n )\n }\n\n token(id: string): Promise<ConnectionTokenResponse> {\n return this.client.request(\n 'POST',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/token`,\n )\n }\n\n async invokeMethod<T = unknown>(id: string, method: string, params: unknown = {}): Promise<T> {\n const response = await this.client.request<InvokeMethodResponse<T>>(\n 'POST',\n `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/methods/${encodeURIComponent(method)}/invoke`,\n params,\n { timeout: INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n}\n","import type { ProteosClient } from '../client.js'\n\nconst VOICE_BASE_PATH = '/conversations/v1/voice'\n\n/** One normalized transcription update streamed back from the server. */\nexport interface TranscriptResult {\n /** The recognized text for this segment. */\n transcript: string\n /** True once this segment is final and will not change. */\n is_final: boolean\n /** True when the server detected end-of-speech (a natural pause). */\n speech_final: boolean\n /** Recognition confidence, 0–1. */\n confidence: number\n}\n\n/** Options for opening a live transcription stream. */\nexport interface TranscribeStreamOptions {\n /** BCP-47 language code (e.g. `en`, `de`). Defaults to the server's default. */\n language?: string\n /** Stream interim (non-final) results as audio arrives. Defaults to `true`. */\n interimResults?: boolean\n /** Add punctuation to results. Defaults to `true`. */\n punctuate?: boolean\n /** Format entities (numbers, dates…) in results. Defaults to `true`. */\n smartFormat?: boolean\n /**\n * Raw audio encoding (e.g. `linear16`). Omit for containerized audio\n * (WebM/Opus from MediaRecorder), which the server auto-detects.\n */\n encoding?: string\n /** Sample rate in Hz. Required only when `encoding` is set. */\n sampleRate?: number\n /** Called for each transcription result. */\n onResult: (result: TranscriptResult) => void\n /** Called if the stream errors. */\n onError?: (error: Event) => void\n /** Called when the stream closes (either side). */\n onClose?: () => void\n}\n\n/** A live transcription session: push audio in, results arrive via `onResult`. */\nexport interface VoiceTranscriptionStream {\n /** Forward one audio chunk (binary) to the server. */\n sendAudio(chunk: Blob | ArrayBufferView | ArrayBuffer): void\n /** Ask the server to flush pending results without closing the stream. */\n finalize(): void\n /** Close the stream. */\n close(): void\n}\n\n/**\n * Service for realtime speech-to-text on conversation-service.\n *\n * Transcription is a WebSocket: open a stream, push audio chunks, and receive\n * {@link TranscriptResult}s. The transcription provider is a server-side concern\n * and is not exposed here.\n *\n * @example\n * ```ts\n * const stream = await agent.voice.transcribeStream({\n * onResult: (r) => console.log(r.transcript, r.is_final),\n * });\n * recorder.ondataavailable = (e) => stream.sendAudio(e.data);\n * // …later: stream.finalize(); stream.close();\n * ```\n */\nexport interface VoiceService {\n /**\n * Opens a live transcription stream and resolves once it is connected.\n *\n * @param options - Stream configuration and result/lifecycle callbacks\n * @returns A handle to push audio and control the stream\n */\n transcribeStream(options: TranscribeStreamOptions): Promise<VoiceTranscriptionStream>\n}\n\nexport class VoiceServiceImpl implements VoiceService {\n constructor(private readonly client: ProteosClient) {}\n\n async transcribeStream(options: TranscribeStreamOptions): Promise<VoiceTranscriptionStream> {\n const query = buildQuery(options)\n const socket = await this.client.openWebSocket(`${VOICE_BASE_PATH}/transcribe/stream${query}`)\n socket.binaryType = 'arraybuffer'\n\n socket.onmessage = (event: MessageEvent) => {\n if (typeof event.data !== 'string') return\n try {\n options.onResult(JSON.parse(event.data) as TranscriptResult)\n } catch {\n // Ignore malformed frames.\n }\n }\n if (options.onError) socket.onerror = options.onError\n socket.onclose = () => options.onClose?.()\n\n const isOpen = () => socket.readyState === WebSocket.OPEN\n\n return {\n sendAudio: (chunk) => {\n if (isOpen()) socket.send(chunk)\n },\n finalize: () => {\n if (isOpen()) socket.send(JSON.stringify({ type: 'finalize' }))\n },\n close: () => socket.close(),\n }\n }\n}\n\n/** Serializes options into the endpoint's query string (snake_case wire format). */\nfunction buildQuery(options: TranscribeStreamOptions): string {\n const params = new URLSearchParams()\n if (options.language) params.set('language', options.language)\n if (options.interimResults !== undefined)\n params.set('interim_results', String(options.interimResults))\n if (options.punctuate !== undefined) params.set('punctuate', String(options.punctuate))\n if (options.smartFormat !== undefined) params.set('smart_format', String(options.smartFormat))\n if (options.encoding) params.set('encoding', options.encoding)\n if (options.sampleRate !== undefined) params.set('sample_rate', String(options.sampleRate))\n const queryString = params.toString()\n return queryString ? `?${queryString}` : ''\n}\n","/**\n * Wire types for conversation-service (/conversations/v1) — hand-maintained\n * mirror of packages/go/model/conversation (snake_case, Is-prefixed booleans).\n */\n\nimport type { PageAction, PrincipalRef } from '../meta/types.js'\nimport type { FileRef } from '../types/common.js'\n\n/**\n * Platform medium a conversation lives on (closed enum; platform identity).\n * Where a provider brand spans both a chat product and a meeting platform the\n * channel is suffixed -chat / -meeting (teams-chat vs teams-meeting). The\n * *-meeting channels are the platforms the Ava meeting-bot family serves;\n * `meeting` stays the generic fallback for unclassified platforms.\n */\nexport type Channel =\n | 'slack'\n | 'email'\n | 'linkedin'\n | 'sms'\n | 'teams-chat'\n | 'telegram'\n | 'whatsapp'\n | 'meeting'\n | 'zoom-meeting'\n | 'google-meet'\n | 'teams-meeting'\n | 'webex-meeting'\n | 'adhoc'\n | 'phone'\n | 'instagram'\n | 'messenger'\n | 'x'\n\n/**\n * Concrete integration serving a channel (typed union — one value per shipped\n * connector; runtime availability is decided by the service's registry).\n * The unipile-* family serves the six messaging systems aggregated through\n * Unipile — one key per messaging system. The meeting keys are the Ava\n * meeting-bot family: adhoc-meeting dispatches by meeting URL; the calendar\n * keys auto-join through a user's connected calendar.\n */\nexport type ConnectorKey =\n | 'slack'\n | 'gmail'\n | 'outlook'\n | 'echo'\n | 'unipile-whatsapp'\n | 'unipile-linkedin'\n | 'unipile-telegram'\n | 'unipile-instagram'\n | 'unipile-messenger'\n | 'unipile-x'\n | 'adhoc-meeting'\n | 'google-calendar-meeting'\n | 'microsoft-calendar-meeting'\n | 'twilio-phone'\n | 'aircall'\n | 'webhook-cti'\n | 'sendgrid'\n | 'microsoft-teams'\n | 'platform-email'\n\n/**\n * Telephony lifecycle of one phone call, carried in the call conversation's\n * `metadata.call_status` (a call is a conversation plus call facts — no\n * dedicated resource). Status callbacks apply through a monotonic guard, so a\n * terminal value never regresses.\n */\n/**\n * Body of POST /conversations/v1/calls/token — the softphone's browser-calling\n * grant for one connection. The client identity is derived server-side from\n * the authenticated user.\n */\nexport interface MintCallTokenRequest {\n connection_id: string\n}\n\n/**\n * PUT /conversations/:id/recording — the in-call recording control on a live\n * phone conversation: true starts (or resumes) the recording, false pauses\n * it. A recording that did not run from answer to hangup is marked\n * `has_partial_recording` on the conversation's metadata.\n */\nexport interface SetCallRecordingRequest {\n is_recording_enabled: boolean\n}\n\n/**\n * Which system answers a provider phone number: connected to this platform,\n * in use by another integration (connecting takes it over, disconnecting\n * restores it), or configured nowhere (available).\n */\nexport type PhoneNumberStatus = 'connected' | 'available' | 'in_use'\n\n/** One dispatch target: a platform user (id) or a team (slug). */\nexport interface RoutingTarget {\n type: 'user' | 'team'\n id: string\n}\n\n/**\n * A connected number's user-level dispatch: who a call rings. v1 rings every\n * expanded target in parallel (teams expand to their direct members at ring\n * time); the object shape leaves room for later strategy options. Empty\n * targets fall back to the connection-wide routing, then busy.\n */\nexport interface PhoneNumberRouting {\n targets: RoutingTarget[]\n}\n\n/** One provider phone number on a phone connection. */\nexport interface PhoneNumber {\n /** Provider-side number identity (vendor vocabulary stays in the adapter). */\n external_id: string\n phone_number: string\n friendly_name: string\n status: PhoneNumberStatus\n /** Display-only description of what an in_use number is used by. */\n used_by?: string\n routing: PhoneNumberRouting\n}\n\n/** Routing update for one phone number (connect/disconnect are actions). */\nexport interface UpdatePhoneNumberRequest {\n routing?: PhoneNumberRouting\n}\n\n/**\n * twilio-phone `connection.settings.voicemail` — what a caller hears when no\n * agent takes the ring. The greeting is spoken by the provider's text-to-speech\n * in `language`; absent or blank fields fall back to platform defaults.\n */\nexport interface TwilioPhoneVoicemailSettings {\n is_enabled: boolean\n /** Empty = the platform's default English text. At most 1000 characters. */\n greeting?: string\n /** BCP-47, one of the supported TTS languages; default en-US. */\n language?: string\n /** 10..300, default 120. */\n max_duration_seconds?: number\n}\n\n/**\n * The typed slice of a twilio-phone `connection.settings` the softphone reads\n * (`Connection.settings` stays an open map on the wire).\n */\nexport interface TwilioPhoneSettings {\n is_softphone_enabled?: boolean\n is_recording_enabled?: boolean\n is_realtime_transcription_enabled?: boolean\n /** How long the parallel ring waits before the call counts as missed; 5..60, default 25. */\n ring_timeout_seconds?: number\n voicemail?: TwilioPhoneVoicemailSettings\n}\n\n/** Why an inbound ring ended without one of our people on the line. */\nexport type CallDialStatus =\n | 'no_answer'\n | 'busy'\n | 'failed'\n | 'canceled'\n /** Nobody was routed to the number. */\n | 'unrouted'\n /** The caller left while it rang. */\n | 'caller_hung_up'\n\n/**\n * The call facts a phone conversation carries in `metadata` (mirrors the\n * backend's logic/call-status.go + call-voicemail.go). Every key is optional\n * on the wire; read defensively.\n */\nexport interface CallMetadata {\n call_direction?: 'inbound' | 'outbound'\n call_status?: CallStatus\n from_number?: string\n to_number?: string\n /** Provider talk time; on a missed call it includes greeting + voicemail. */\n duration_seconds?: number\n recording_external_id?: string\n recording_file_id?: string\n is_recording_enabled?: boolean\n has_partial_recording?: boolean\n /** No agent took the inbound call. */\n is_missed?: boolean\n dial_status?: CallDialStatus\n /** `offered` once the greeting played, `recorded` once the message landed. */\n voicemail_status?: 'offered' | 'recorded'\n voicemail_duration_seconds?: number\n}\n\n/** The minted grant the Voice JS SDK consumes (`new Device(token, { edge })`). */\nexport interface CallTokenResponse {\n token: string\n identity: string\n /** Vendor edge to connect through ('dublin' for the EU default). */\n edge?: string\n expires_at: string\n}\n\nexport type CallStatus =\n | 'queued'\n | 'ringing'\n | 'in_progress'\n | 'completed'\n | 'no_answer'\n | 'busy'\n | 'failed'\n | 'canceled'\n\n/**\n * Who operates the integration mechanics behind a connector: Proteos' own\n * integration (native), an account aggregated through Unipile (unipile), or\n * the Ava meeting-bot family (ava). Computed on connection reads; the UI\n * groups the connector catalog by it.\n */\nexport type ConnectorProvider = 'native' | 'unipile' | 'ava'\n\nexport type MessageDirection = 'inbound' | 'outbound'\n/**\n * Delivery state. `draft` = agent-prepared, awaiting human review (a human\n * sends it → pending → sent/failed, or rejects it → `rejected`, terminal).\n */\nexport type MessageStatus = 'received' | 'pending' | 'sent' | 'failed' | 'draft' | 'rejected'\nexport type ConnectionScope = 'org' | 'user'\nexport type ConnectionStatus = 'pending' | 'active' | 'error' | 'revoked'\n/**\n * `draft` marks a conversation minted BY a draft message (originate-mode\n * drafting) — hidden from the default list until the first successful send.\n */\nexport type ConversationStatus = 'active' | 'ended' | 'archived' | 'draft'\n/**\n * Generation lifecycle of a conversation's `summary`. `none` is the resting\n * default — no summary exists and none is being produced, the state of every\n * conversation that is not a transcript-backed meeting. `processing` is claimed\n * for the duration of one generation run (automatic at transcript attach, or a\n * manual `meetings.summarize()`), so any client can render \"Summarizing…\"\n * without having started the run itself.\n */\nexport type ConversationSummaryStatus = 'none' | 'processing' | 'completed' | 'failed'\nexport type AgentListenerTriggerType = 'always' | 'mention' | 'channel' | 'keyword'\n\nexport interface UserRef {\n type: string\n id: string\n}\n\n/**\n * Inline snapshot of a person on a message/reaction — the integration-side\n * identity plus, when resolved, the platform user and the contact id.\n * (Renamed from ParticipantRef in the contacts model; wire keys unchanged.)\n */\nexport interface ContactRef {\n external_id?: string\n name: string\n email?: string\n /** The resolved person; absent on pre-contacts snapshots and wire fallbacks. */\n contact_id?: string\n /** Resolved platform identity (email match); absent when unresolved. */\n platform_user?: UserRef\n}\n\n/**\n * One member of a conversation's roster — everyone in the thread, INCLUDING the\n * connected account itself. The account's own entries carry is_self=true; a UI\n * renders \"who it's with\" as the non-self subset (1 → single avatar, ≥2 →\n * stacked).\n */\nexport interface ConversationParticipant extends ContactRef {\n is_self: boolean\n}\n\n/** How a MessageRecipient was addressed: primary, carbon copy, blind copy. */\nexport type RecipientRole = 'to' | 'cc' | 'bcc'\n\n/**\n * One addressee of a message with the role it was addressed under. Bcc is only\n * present on messages the platform itself sent (inbound bcc is SMTP-stripped).\n */\nexport interface MessageRecipient extends ContactRef {\n role: RecipientRole\n}\n\n/**\n * One unit of message content — what was SAID. Files a message CARRIED are\n * NOT content: they are Attachment rows (Message.attachments).\n */\nexport interface ContentBlock {\n type: 'text' | 'html'\n text?: string\n /**\n * Sanitized rich email body (ingest-time allowlist: layout tables, inline\n * styles, https images; no scripts/forms/handlers). Rides ALONGSIDE the\n * canonical text block. Render only in an isolated, script-less surface.\n */\n html?: string\n}\n\n/** Secret material is redacted on every read (\"********\" when set). */\nexport interface ConnectionCredentials {\n bot_token?: string\n bot_user_id?: string\n refresh_token?: string\n access_token?: string\n token_expires_at?: string\n granted_scopes?: string\n /** Aggregator-hosted account identity (unipile-*) — nothing secret. */\n account_id?: string\n owner_provider_id?: string\n}\n\n/** How a channel's reaction vocabulary is shaped. */\nexport type ReactionSetKind = 'open' | 'fixed'\n\n/** One entry of a fixed reaction vocabulary (token = the value to send). */\nexport interface ReactionOption {\n token: string\n unicode?: string\n label?: string\n}\n\n/**\n * A connector's declarative reaction capability, projected onto the\n * connection read: open → show an emoji picker; fixed → exactly the allowed\n * buttons; absent (connection.reactions undefined) → no affordance.\n */\nexport interface ReactionCapability {\n kind: ReactionSetKind\n allowed?: ReactionOption[]\n /** 0 = unbounded (Slack); 1 = single-slot (a new reaction replaces the old). */\n max_per_actor: number\n}\n\n/** How far back a historical backfill (\"sync all\") reaches. */\nexport type ConnectionSyncRange = '30d' | '90d' | '365d' | 'all'\n\n/**\n * Lifecycle of a historical backfill, carried as settings.sync_status.\n * Absent key = 'none' (never synced). 'in_progress' is claimed before the\n * trigger request returns — poll get(id) until it flips to done/failed.\n */\nexport type ConnectionSyncStatus = 'none' | 'in_progress' | 'done' | 'failed'\n\nexport interface SyncConnectionRequest {\n range: ConnectionSyncRange\n}\n\nexport interface Connection {\n id: string\n org_id: string\n connector_key: ConnectorKey\n channel: Channel\n name: string\n scope: ConnectionScope\n /** Set only when scope=user (the connecting user); absent for org-wide. */\n owner?: UserRef\n external_account_id: string\n credentials: ConnectionCredentials\n /**\n * Connector-shaped configuration + state. A historical backfill writes the\n * sync_* keys here: sync_status (ConnectionSyncStatus), sync_range,\n * sync_started_at, sync_completed_at, sync_synced_count, sync_error.\n */\n settings: Record<string, unknown>\n status: ConnectionStatus\n /** Computed on read: the connector implements the reaction capability. */\n supports_reactions: boolean\n /** The capability descriptor; absent when unsupported. */\n reactions?: ReactionCapability\n /**\n * Computed on read: the connector sends a message's html block as the\n * body's html part, so a composer can offer rich formatting.\n */\n supports_html: boolean\n /**\n * Computed on read like reactions: the channel actions the connector\n * performs through this connection (invitation, profile_visit, inmail, …).\n * A separate list from reactions — a reaction toggles an edge on a\n * message, an action is a performed act with its own lifecycle. Absent\n * when the connector performs none.\n */\n actions?: ChannelActionCapability[]\n /**\n * Computed on read like supports_reactions: who operates the integration\n * (native | unipile). Absent when the connector is not registered in this\n * environment.\n */\n provider?: ConnectorProvider\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface Conversation {\n id: string\n org_id: string\n connection_id: string\n channel: Channel\n external_conversation_id: string\n subject: string\n /**\n * Markdown summary — auto-generated at transcript attach for meeting\n * conversations, editable via update(). Absent when no summary exists.\n */\n summary?: string\n /**\n * Generation lifecycle of `summary`. Poll `conversations.get(id)` while this\n * reads `processing` to pick up the finished summary.\n */\n summary_status: ConversationSummaryStatus\n /**\n * When the current `processing` run was claimed; absent otherwise. Bounds the\n * claim server-side and gives clients an elapsed time to show.\n */\n summary_started_at?: string\n /**\n * ConversationType key the pre-summary classifier assigned; absent when never\n * classified or no type matched.\n */\n type_key?: string\n /** How the conversation ended — one of its type's outcome keys; absent = none yet. */\n outcome_key?: string\n /** Who set the outcome: `user` (never overridden by the model) or `model`. */\n outcome_source?: ConversationOutcomeSource\n outcome_set_by?: UserRef\n outcome_set_at?: string\n /** The conversation currently holds objective rows (maintained by the objective sync). */\n has_objectives: boolean\n status: ConversationStatus\n /**\n * Room directory row a room-borne thread (Slack channel conversation) lives\n * in; absent for DMs, email, meeting, adhoc.\n */\n room_id?: string\n /**\n * Main conversation a child conversation forked from (Slack: the channel's\n * main conversation; provider-side the child is a native Slack thread);\n * absent for main/DM/email/meeting/adhoc.\n */\n parent_conversation_id?: string\n /**\n * iCalendar UID of the calendar meeting this conversation was born from\n * (stamped when the meeting bot starts); absent for everything else. With\n * `started_at` it names the meeting INSTANCE on every invitee's calendar —\n * Google's UID names a series, Microsoft's one occurrence.\n */\n calendar_event_ical_uid?: string\n /**\n * The brief this phone call was dialled with, or the first brief attached to\n * it by hand; the first value stays. Absent on everything else: a meeting may\n * carry several briefs (list them with `conversationBriefs.list`).\n */\n brief_id?: string\n /**\n * Message id of the child conversation's root message, which lives in the\n * parent conversation; absent when the root is unknown (predates ingest).\n */\n started_by_message_id?: string\n started_at?: string\n ended_at?: string\n /**\n * The thread's complete roster — everyone in it, including the connected\n * account (its own entries marked is_self). Deduped by external_id; the\n * queryable person dimension. Replaces the old single `counterpart`.\n */\n participants?: ConversationParticipant[]\n last_message_at: string\n metadata: Record<string, unknown>\n /**\n * Messages summary — present only when the list opted in via\n * include: 'messages_summary'. Renders a hub stream row (root on Slack,\n * latest on email, reply affordance) without a per-conversation fetch.\n */\n root_message?: MessagePreview\n latest_message?: MessagePreview\n messages_total?: number\n /** Up to 3 most recent distinct senders excluding the root sender. */\n last_repliers?: ContactRef[]\n /** Requesting user's read marker; absent = never opened. */\n last_read_at?: string\n /**\n * Server-computed unread predicate for the requesting user: activity after\n * the marker AND the latest message is inbound.\n */\n is_unread: boolean\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Compact snapshot of one message riding on conversation reads\n * (include: 'messages_summary'): enough for a stream row — who, the first\n * ~500 chars of text, direction/status for outbound identity.\n */\nexport interface MessagePreview {\n sender: ContactRef\n text: string\n direction: MessageDirection\n status: MessageStatus\n occurred_at: string\n}\n\n/**\n * Aggregated unread-conversation counts for the requesting user (unit:\n * conversations, not messages) — the envelope total and per-channel badges.\n */\nexport interface UnreadCounts {\n total: number\n channels: Partial<Record<Channel, number>>\n}\n\n/**\n * One file that arrived with a message. `file` is the platform FileRef —\n * bytes live in storage-service; size and content type resolve from storage\n * by id. content_id/is_inline carry the MIME inline-image semantics\n * (cid: references in the html body vs user-facing downloads).\n */\nexport interface Attachment {\n id: string\n org_id: string\n message_id: string\n connection_id: string\n file: FileRef\n content_id?: string\n is_inline: boolean\n created_at: string\n created_by: UserRef\n}\n\n/** Aggregated reactions on a message: one entry per emoji (native token). */\nexport interface Reaction {\n emoji: string\n count: number\n participants: ContactRef[]\n}\n\nexport interface Message {\n id: string\n org_id: string\n conversation_id: string\n connection_id: string\n channel: Channel\n direction: MessageDirection\n /** A draft's edited subject, held until send. Absent means the conversation's; empty is a subject deliberately cleared on a new email. */\n subject?: string\n /** The tone profile this draft was written in, when known. May no longer resolve. */\n tone_profile_id?: string\n /** The reviewer took the quoted previous message off this reply. */\n is_quote_removed?: boolean\n /** The signature chosen for this email. Absent means the default that applies when it is sent. May no longer resolve. */\n signature_id?: string\n /** This email goes out without a signature. */\n is_signature_removed?: boolean\n /**\n * The signature the email carries below the body and above the quote. On a\n * sent message, the snapshot of what went out. On a single draft read, what\n * a send would add now. Never part of `content`.\n */\n signature?: MessageSignature\n /**\n * This email is sent with an unsubscribe link of its own. The link exists\n * only in what the recipient gets; `content` keeps `UNSUBSCRIBE_URL_PLACEHOLDER`\n * or nothing.\n */\n has_unsubscribe_link?: boolean\n /**\n * Why the message is sent: the purpose the recipients' consent was checked\n * for. Absent when the sender did not say.\n */\n purpose?: Purpose\n /** The layout chosen for this email (a message template of kind `layout`). Absent means none. May no longer resolve, which fails the send. */\n layout_id?: string\n /**\n * The frame the email carries around its body. On a sent message, the\n * snapshot of what went out. On a single draft read, what a send would use\n * now. Never part of `content`.\n */\n layout?: MessageLayout\n /** The platform wrote this message (a send or a draft): its content is what the person wrote, without the quote the email carried. Absent on mail imported from the mailbox. */\n is_sent_from_platform?: boolean\n /** The newest entry in this draft's history; absent until its first change. */\n draft_version?: number\n /** On a single draft read: the quote its send would carry below the text. Never stored. */\n quoted_text?: string\n external_message_id: string\n sender: ContactRef\n /** Who the message was addressed to (To/Cc/Bcc), each tagged with its role. */\n recipients?: MessageRecipient[]\n content: ContentBlock[]\n status: MessageStatus\n /**\n * The message this one was targeted at (thread-mode send/draft anchor);\n * absent for everything else.\n */\n reply_to_message_id?: string\n occurred_at: string\n /** Read-time projection; absent/empty on channels without reactions. */\n reactions?: Reaction[]\n /** Read-time projection of the message's attachment rows; absent without files. */\n attachments?: Attachment[]\n /**\n * Child-conversation projection (read-time, per-conversation lists): the\n * conversation rooted at this message and its message count — the \"N\n * replies\" affordance. Absent for messages no child conversation forked\n * from.\n */\n child_conversation_id?: string\n child_messages_total?: number\n /**\n * Provider-side outcome + engagement projection of an OUTBOUND message on\n * a sending platform (folded from the channel_event ledger); absent on\n * channels that report nothing and on inbound rows.\n */\n delivery?: MessageDelivery\n metadata: Record<string, unknown>\n error: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Provider-side outcome of an outbound message — a separate axis from\n * MessageStatus (the message stays `sent` at the platform level once the\n * provider accepted it): sent → delivered | deferred | bounced | dropped.\n */\nexport type MessageDeliveryStatus = 'sent' | 'delivered' | 'deferred' | 'bounced' | 'dropped'\n\n/** The read-side fold of a message's channel events. */\nexport interface MessageDelivery {\n status: MessageDeliveryStatus\n delivered_at?: string\n bounced_at?: string\n dropped_at?: string\n /** First HUMAN open / click; totals count every event (machine opens excluded). */\n opened_at?: string\n opens_total?: number\n clicked_at?: string\n clicks_total?: number\n spam_reported_at?: string\n unsubscribed_at?: string\n /** Latest bounce / drop / deferral text. */\n reason?: string\n last_event_at?: string\n}\n\n/**\n * Per-trigger configuration, discriminated by the sibling trigger_type: channel\n * carries external_channel_id, keyword carries phrases, always/mention carry\n * neither. (Serialized as the bare variant; both fields optional here.)\n */\nexport interface AgentListenerTriggerConfig {\n external_channel_id?: string\n phrases?: string[]\n}\n\n/**\n * How the dispatcher immediately acknowledges a triggering message once the\n * agent turn is queued: '' = none, 'reaction' places an emoji on the message\n * (reaction-capable connections only), 'message' posts a short text.\n */\nexport type AgentListenerAcknowledgementType = '' | 'reaction' | 'message'\n\n/**\n * Discriminated by the sibling acknowledgement_type; serialized as the bare\n * variant, both fields optional here.\n */\nexport interface AgentListenerAcknowledgementConfig {\n /** Reaction type: connector-native emoji token (\"eyes\", no colons). */\n emoji?: string\n /** Message type: the acknowledgement text. */\n text?: string\n}\n\n/**\n * Where the dispatcher takes its acting user from: 'defined' (the listener's\n * stored acting_user — the default) or 'inferred' (the triggering message\n * sender's resolved platform user, with acting_user as OPTIONAL fallback — no\n * platform user and no fallback means the dispatch is skipped).\n */\nexport type AgentListenerActingUserMode = 'defined' | 'inferred'\n\nexport interface AgentListener {\n id: string\n org_id: string\n connection_id: string\n conversation_id: string\n /**\n * Optionally NARROWS a connection-bound listener to one room — the internal\n * room id (`Room.id`), matched against the conversation's room at dispatch.\n * Absent/empty ⇒ the whole connection. The most specific scope wins:\n * conversation > room > connection; priority orders within a tier.\n */\n room_id?: string\n name: string\n agent_key: string\n trigger_type: AgentListenerTriggerType\n trigger_config: AgentListenerTriggerConfig\n /**\n * When set, gates the listener behind a wake word: the trigger stays dormant\n * until a message containing this phrase starts a session; once a session is\n * connected the trigger drives it normally. Empty/absent ⇒ no gate.\n */\n wake_phrase?: string\n /**\n * Immediate platform acknowledgement of the triggering message, executed by\n * the dispatcher once the agent turn is queued ('' = none). The agent is\n * told not to acknowledge again.\n */\n acknowledgement_type: AgentListenerAcknowledgementType\n acknowledgement_config?: AgentListenerAcknowledgementConfig\n acting_user_mode: AgentListenerActingUserMode\n /**\n * The user the dispatcher acts as (mode 'defined'), or the optional fallback\n * when the sender has no platform user (mode 'inferred'; an empty ref means\n * no fallback).\n */\n acting_user: UserRef\n is_enabled: boolean\n /**\n * How the agent's reply reaches the conversation. `true` (default) ⇒ the\n * platform posts the agent's text reply automatically. `false` ⇒ the platform\n * forwards nothing; the agent is told (in the session preamble) to reply\n * itself via the send_message/reply tool.\n */\n is_auto_forward_agent_replies_enabled: boolean\n priority: number\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateConnectionRequest {\n connector_key: ConnectorKey\n name: string\n scope: ConnectionScope\n settings?: Record<string, unknown>\n}\n\nexport interface UpdateConnectionRequest {\n name?: string\n settings?: Record<string, unknown>\n}\n\n/**\n * Optional body of POST /connections/:id/install. `input` carries\n * user-supplied install credentials for direct-install connectors\n * (twilio-phone, aircall, webhook-cti — connector-documented snake_case\n * keys); omit it for OAuth/hosted connectors.\n */\nexport interface InstallConnectionRequest {\n input?: Record<string, string>\n}\n\nexport interface InstallConnectionResponse {\n /** OAuth/hosted installs: open this in a popup. Absent on direct installs. */\n authorization_url?: string\n /** Direct installs complete server-side in this request. */\n is_completed?: boolean\n /**\n * A direct-install connector's one-time setup handout (callback URLs to\n * paste provider-side; a minted token shown exactly once — only its hash is\n * stored server-side). Never retrievable again.\n */\n setup?: Record<string, string>\n}\n\nexport interface SendMessageRequest {\n /** Records the tone a draft was written in. Stored by draft; send ignores it. */\n tone_profile_id?: string\n /**\n * The email signature: `default` (or omitted) for the default that applies,\n * `none` for no signature, or a signature id. Added below the body at send,\n * never part of `content`. Ignored on every channel but email.\n */\n signature?: SignatureChoice\n /**\n * Sends a stored message template instead of `content`: its id or key. It is\n * rendered with `variables` at this moment and stored on the message like any\n * content. `subject`, when omitted, is the template's.\n */\n template?: string\n /** The names the template's Liquid reads. Ignored without `template`. */\n variables?: Record<string, unknown>\n /**\n * `link` gives the email an unsubscribe link of its own that records an\n * opt-out in the contact's permission ledger; `none` (or omitted) gives it\n * none. The link replaces every `UNSUBSCRIBE_URL_PLACEHOLDER` in the body\n * (what `{{ unsubscribe_url }}` renders to) and goes into a footer line when\n * the body has none. Email only, to exactly one recipient: anything else is\n * refused with 400 `unsubscribe_not_possible`.\n */\n unsubscribe?: UnsubscribeChoice\n /**\n * Why the message is sent. The recipients' consent is checked for it: one\n * who opted out of it (or of everything) is refused with 403\n * `contact_opted_out`. Omitted takes the template's purpose, else none, and\n * then only an opt-out from everything stops the send. `transactional`\n * skips consent and cannot carry an unsubscribe link.\n */\n purpose?: Purpose\n /**\n * Wraps the body in a stored layout when the email is sent: the id or key\n * of a message template of kind `layout`, `none` (or omitted) for no layout.\n * `content` stays as written; the message keeps a snapshot of the layout\n * that went out. Ignored on every channel but email.\n */\n layout?: string\n /** Reply mode: send into this existing conversation. */\n conversation_id?: string\n /**\n * Targeted reply: reply aimed at ONE message (mutually exclusive with the\n * other modes). Slack starts/continues the child conversation rooted at\n * that message (carrying parent_conversation_id/started_by_message_id —\n * provider-side a native Slack thread); email replies in the same\n * conversation with In-Reply-To anchored at the target; channels without\n * message-targeted replies reject with `child_conversation_not_supported`.\n */\n reply_to_message_id?: string\n /** Originate mode (omit conversation_id): connection_id + at least one To are required. */\n connection_id?: string\n /**\n * Primary destinations for originate: one room (Slack channel) OR one-or-more\n * participants (email To, a Slack DM, or several users → a Slack MPIM).\n */\n to?: SendRecipient[]\n /** Carbon-copy participants (email only). */\n cc?: SendRecipient[]\n /** Blind-carbon-copy participants (email only). */\n bcc?: SendRecipient[]\n /** Optional subject, used by email when originating. */\n subject?: string\n /** May be empty when attachments are present. */\n content: ContentBlock[]\n /**\n * Files to send with the message. Pre-upload each file to storage-service\n * and reference it here ({id, name}); the server downloads the bytes and\n * hands them to the channel connector (Slack: one native message with the\n * text as its comment; Gmail: multipart/mixed mail; ≤25MB per file, Slack\n * ≤10 files per message). Channels without file support reject with\n * `unsupported_content`.\n */\n attachments?: FileRef[]\n /**\n * Overrides the sending identity on a sending-platform email connection: a\n * contact address id on the connection's sender domain\n * (`connections.listSenders`). Without it: the conversation's pinned sender\n * → the acting user's own address on the domain → the connection's default.\n * Off-domain ids fail with `sender_not_found`; connections without a sender\n * domain refuse it with `sender_domain_not_available`.\n */\n sender_address_id?: string\n}\n\n/**\n * Edits a status=draft message — full replacement of the editable surface\n * (PUT semantics; always send the complete state, including attachments you\n * want to keep). The addressing MODE is immutable. `subject` applies only\n * while the draft's conversation is itself status=draft (originate drafts) —\n * replies derive their subject from the thread.\n *\n * Recipient groups are PRESENCE-based: a group that is present (including an\n * explicit empty `[]` — a clear) replaces the stored recipients from exactly\n * the provided groups; omitting all three keeps the stored recipients. On any\n * recipient edit, send all three groups.\n */\n/** How a version of a draft came to be. */\nexport type MessageDraftVersionKind = 'drafted' | 'edited' | 'redrafted' | 'restored'\n\n/** One step in a draft message's history. */\nexport interface MessageDraftVersion {\n id: string\n org_id: string\n message_id: string\n version: number\n kind: MessageDraftVersionKind\n /** The effective subject at this version, wherever it is stored. */\n subject: string\n recipients: MessageRecipient[]\n content: ContentBlock[]\n tone_profile_id?: string\n /** The reviewer's redraft prompt (kind=redrafted). */\n instruction?: string\n /** The version a restore copied from (kind=restored). */\n source_version?: number\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** One field that differs between what was proposed and the latest version. */\nexport interface MessageDraftChange {\n field: 'body' | 'subject' | 'to' | 'cc' | 'bcc'\n from: unknown\n to: unknown\n}\n\n/** A draft's history, oldest first, plus what changed across it. */\nexport interface MessageDraftVersions {\n data: MessageDraftVersion[]\n changes: MessageDraftChange[]\n}\n\nexport interface UpdateDraftRequest {\n to?: SendRecipient[]\n /** Email only. */\n cc?: SendRecipient[]\n /** Email only. */\n bcc?: SendRecipient[]\n subject?: string\n /** May be empty when attachments are present. */\n content: ContentBlock[]\n /** The complete attachment set to keep (omitting one removes its row). */\n attachments?: FileRef[]\n /**\n * The `updated_at` the editor last saw. A draft that has moved on since fails\n * with 409 `draft_conflict` instead of being overwritten. Omit for last write wins.\n */\n expected_updated_at?: string\n /** Takes the quoted previous message off (true) or puts it back on (false). */\n is_quote_removed?: boolean\n /** Replaces the tone recorded on the draft. Omit to keep it. */\n tone_profile_id?: string\n /**\n * Replaces the draft's signature choice. Omit to keep it. The response then\n * carries the `signature` the draft now resolves to.\n */\n signature?: SignatureChoice\n /** Replaces the draft's unsubscribe choice. Omit to keep it. */\n unsubscribe?: UnsubscribeChoice\n /** Replaces the draft's purpose; `''` clears it. Omit to keep it. */\n purpose?: Purpose | ''\n /** Replaces the draft's layout: `none`, or a layout's id or key. Omit to keep it. */\n layout?: string\n /** What this edit is in the draft's history. Defaults to `edited`. */\n version_kind?: Exclude<MessageDraftVersionKind, 'drafted'>\n /** The reviewer's prompt behind a redraft. */\n instruction?: string\n /** The version a restore copies from. */\n source_version?: number\n}\n\nexport interface CreateAgentListenerRequest {\n connection_id?: string\n conversation_id?: string\n /**\n * Only with `connection_id`: narrow the listener to one room. Pass the\n * internal room id (`Room.id` from listRooms), NOT the provider channel id.\n */\n room_id?: string\n name: string\n agent_key: string\n trigger_type: AgentListenerTriggerType\n trigger_config?: AgentListenerTriggerConfig\n /** Gate the listener behind a wake word; omit or leave empty for no gate. */\n wake_phrase?: string\n /**\n * Immediate platform acknowledgement; omit or '' for none. 'reaction'\n * requires a reaction-capable connection and { emoji } in the config;\n * 'message' requires { text }.\n */\n acknowledgement_type?: AgentListenerAcknowledgementType\n acknowledgement_config?: AgentListenerAcknowledgementConfig\n /** Omit to default to 'defined'. */\n acting_user_mode?: AgentListenerActingUserMode\n /**\n * A bare user id; the service wraps it into a person UserRef. Required in\n * 'defined' mode (the default); optional in 'inferred' mode, where it is the\n * fallback when the sender has no platform user.\n */\n acting_user_id?: string\n /** Omit to default to enabled. */\n is_enabled?: boolean\n /**\n * Whether the platform auto-forwards the agent's text reply. Omit to default\n * to `true` (historic behavior). `false` ⇒ the agent replies itself via the\n * send_message/reply tool.\n */\n is_auto_forward_agent_replies_enabled?: boolean\n priority?: number\n}\n\nexport interface UpdateAgentListenerRequest {\n /**\n * Set to narrow the listener to a room (internal `Room.id`); pass \"\" to\n * clear. Only valid on connection-scoped listeners — the connection/\n * conversation target itself is fixed at creation.\n */\n room_id?: string\n name?: string\n agent_key?: string\n trigger_type?: AgentListenerTriggerType\n trigger_config?: AgentListenerTriggerConfig\n /** Set to gate the listener; pass \"\" to clear an existing wake phrase. */\n wake_phrase?: string\n /**\n * Set to change the acknowledgement; pass '' to clear. A non-empty type\n * requires acknowledgement_config in the same request.\n */\n acknowledgement_type?: AgentListenerAcknowledgementType\n acknowledgement_config?: AgentListenerAcknowledgementConfig\n /** Switching to 'defined' requires an effective acting user (stored or in this request). */\n acting_user_mode?: AgentListenerActingUserMode\n /** Pass \"\" to clear the user — only valid when the effective mode is 'inferred'. */\n acting_user_id?: string\n is_enabled?: boolean\n /** Toggle whether the platform auto-forwards the agent's text reply. */\n is_auto_forward_agent_replies_enabled?: boolean\n priority?: number\n}\n\n/**\n * A per-org glossary term: custom vocabulary that improves transcription\n * accuracy. `term` is the boost phrase injected into the provider's keyterm\n * prompting; `definition` is human/agent documentation only. `priority` ranks a\n * term for injection (prioritized terms outrank unprioritized; lower number\n * first) and decides which terms win when the org exceeds the provider's 100-term\n * per-request cap.\n */\nexport interface GlossaryTerm {\n id: string\n org_id: string\n term: string\n definition?: string\n priority?: number\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateGlossaryTermRequest {\n term: string\n definition?: string\n priority?: number\n}\n\nexport interface UpdateGlossaryTermRequest {\n term?: string\n definition?: string\n priority?: number\n /** Removes the term's priority (unprioritizes it) regardless of `priority`. */\n is_priority_cleared?: boolean\n}\n\nexport interface ListGlossaryTermsQuery extends PaginationQuery {\n /** Case-insensitive substring match on the term text. */\n search?: string\n}\n\n/** Optional per-type behavior configuration. */\nexport interface ConversationTypeConfig {\n /**\n * Agent-service prompt key whose CURRENT version body replaces the built-in\n * summary system prompt for conversations classified as this type. Absent ⇒\n * built-in prompt.\n */\n summary_prompt_key?: string\n}\n\n/**\n * A per-org conversation taxonomy entry. Before a meeting summary is\n * generated, a cheap classifier reads the transcript head plus every type's\n * `definition` and picks the matching `key` (or none); the result lands on\n * `Conversation.type_key` and `config.summary_prompt_key` may swap the summary\n * system prompt. Module-deployable (conversation-types/<key>.json).\n */\n/**\n * One way a conversation of a type can end — \"booked\", \"not_interested\",\n * \"callback\". The type's list is the vocabulary a person picks from (the\n * softphone after a call, the conversation header) and the choice a\n * `role: 'outcome'` tag definition detects among. `description` is what the\n * model reads to tell outcomes apart (the name when empty).\n */\nexport interface ConversationOutcome {\n /** Platform key — the value stored on `Conversation.outcome_key`. */\n key: string\n name: string\n description?: string\n}\n\n/**\n * One stage a conversation of a type moves through — \"intro\", \"discovery\",\n * \"close\". The type's list is ordered; progress through it is DERIVED from\n * the objectives pinned to each phase (every measured objective of a phase\n * achieved ⇒ the phase is done), never detected on its own. `description`\n * is for humans (the checklist, the summary prompt).\n */\nexport interface ConversationPhase {\n key: string\n name: string\n description?: string\n}\n\nexport interface ConversationType {\n org_id: string\n /** Immutable identity within the org — what the classifier answers with. */\n key: string\n name?: string\n /** When a conversation IS this type — injected verbatim into the classifier prompt. */\n definition: string\n config: ConversationTypeConfig\n /** Ordered; empty = the type tracks no outcome. */\n outcomes: ConversationOutcome[]\n /** Ordered; empty = the type tracks no phases. */\n phases: ConversationPhase[]\n /**\n * The type's action buttons — one strip in the footer of the call or\n * meeting surface, the same place during the conversation and in its\n * wrap-up. Same contract as `Page.actions`; each button's `visible_when`\n * reads the conversation scope (`conversation.status` for the stage,\n * `conversation.outcome_key`, `records_by_entity.<slug>`,\n * `tags_by_definition.<key>`, …); no rule = offered throughout. The rule\n * decides when a button appears; once pressed it stays for the rest of\n * the conversation. Ordered; empty = none.\n */\n actions: PageAction[]\n /** Module that deployed the type; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateConversationTypeRequest {\n /** Lowercase kebab/snake/camel handle — no spaces. */\n key: string\n name?: string\n definition: string\n config?: ConversationTypeConfig\n /** Replaces the list wholesale; omit = none. */\n outcomes?: ConversationOutcome[]\n /** Replaces the list wholesale; omit = none. */\n phases?: ConversationPhase[]\n /** Replaces the list wholesale; omit = none. */\n actions?: PageAction[]\n module_slug?: string\n}\n\nexport interface UpdateConversationTypeRequest {\n name?: string\n definition?: string\n /** Replaces the stored config wholesale; send `{}` to clear the prompt link. */\n config?: ConversationTypeConfig\n /** Replaces the list wholesale; `[]` clears it. */\n outcomes?: ConversationOutcome[]\n /** Replaces the list wholesale; `[]` clears it. */\n phases?: ConversationPhase[]\n /** Replaces the list wholesale; `[]` clears it. */\n actions?: PageAction[]\n}\n\nexport interface ListConversationTypesQuery extends PaginationQuery {\n /** Case-insensitive substring match on key or name. */\n search?: string\n module_slug?: string\n}\n\n// ---------------------------------------------------------------------------\n// Conversation intelligence — tag definitions, tag sets, tags, evaluations.\n// Hand-maintained mirror of conversation-tag-*.go + api/conversation-tag-*.go.\n// ---------------------------------------------------------------------------\n\n/**\n * Discriminates a tag definition's question (1:1 with the agent-service\n * decision question types): boolean (\"is this present?\"), choice (\"which\n * one?\"), score (\"where on this ordered scale?\").\n */\nexport type ConversationTagQuestionType = 'boolean' | 'choice' | 'score'\n\n/**\n * What a tag anchors to: the whole conversation (one value per conversation),\n * one message (a verdict per message), or a span (character ranges inside a\n * message, or message-to-message ranges). `span` REQUIRES evaluator kind\n * `reason` — only a reasoning generation can localise verbatim quotes.\n */\nexport type ConversationTagScope = 'conversation' | 'message' | 'span'\n\n/**\n * The model path a definition is judged by: `decide` (agent-service's\n * calibrated typed decision — probabilities, no prose, no localisation) or\n * `reason` (a schema-constrained generation that returns rationale + verbatim\n * anchors; required for span scope).\n */\nexport type ConversationTagEvaluatorKind = 'decide' | 'reason'\n\n/**\n * What a definition is judged over: `conversation` (its messages, windowed per\n * trigger — the default) or `summary` (the conversation's final summary plus\n * the humans' notes; conversation scope only; planned only once the\n * conversation has a summary, so never by a realtime evaluation).\n */\nexport type ConversationTagBasis = 'conversation' | 'summary'\n\n/**\n * Who set a conversation's outcome: a person (never overridden), the model\n * (a `role: 'outcome'` tag) or the service itself from a channel fact (a call\n * nobody answered, a meeting nobody joined).\n */\nexport type ConversationOutcomeSource = 'user' | 'model' | 'system'\n\n/**\n * One outcome a conversation may take, as `conversations.listOutcomes`\n * lists them: the type's outcomes (`source: 'type'`) followed by the\n * channel's system outcomes (`source: 'system'` — phone: not_reached /\n * voicemail / wrong_number; meetings: no_show / cancelled; email: no_reply /\n * bounced / declined; chat: no_reply / declined). The service sets the ones\n * it can tell by itself; a person may pick any.\n */\nexport interface ConversationOutcomeOption {\n key: string\n name: string\n description?: string\n source: 'type' | 'system'\n}\n\n/**\n * The special part a definition plays beyond being an observation. `outcome`\n * = THE result of the conversation: a choice question at conversation scope,\n * one value per conversation, the human's choice beats the model's (an\n * evaluation never asks the model an outcome a user already set), surfaced in\n * the softphone and the conversation header. `phase` is reserved.\n */\nexport type ConversationTagRole = 'outcome'\n\n/**\n * WHY an evaluation ran: `realtime` (the debounced window after new messages),\n * `completion` (the conversation completed — final transcript + summary for\n * spoken media, End for the rest) or `manual` (`conversationTags.evaluate`).\n * A tag set's `evaluate_on` lists the automatic ones it subscribes to; manual\n * ignores it.\n */\nexport type ConversationTagTrigger = 'realtime' | 'completion' | 'manual'\n\n/** Who produced a tag: the evaluator (`model`) or a person (`user`). */\nexport type ConversationTagSource = 'model' | 'user'\n\n/**\n * `pending` = a provisional realtime observation on a spoken-medium\n * conversation that is still live (a completion evaluation will replace it);\n * `active` = current; `dismissed` = a person rejected it — kept as feedback\n * and never re-created by a later evaluation.\n */\nexport type ConversationTagStatus = 'pending' | 'active' | 'dismissed'\n\n/**\n * One evaluation's lifecycle: `pending` (a manual evaluation was accepted and\n * not yet started), `running`, `done`, `failed`.\n */\nexport type ConversationTagEvaluationStatus = 'pending' | 'running' | 'done' | 'failed'\n\n/**\n * Spells out what makes a boolean question hold (`true`) or not (`false`)\n * when the boundary is subtle.\n */\nexport interface BooleanTagCriteria {\n true: string\n false: string\n}\n\n/**\n * Populated per question type: boolean → `boolean` (optional, both\n * descriptions or neither), choice → `choice` (option key → description,\n * ≥ 2), score → `score` (ordered level descriptions, ≥ 2; the tag value is\n * the 0-based level index). Descriptions are handed to the evaluator\n * verbatim, so they should describe the observable content, not internal\n * process.\n */\nexport interface ConversationTagCriteria {\n boolean?: BooleanTagCriteria\n choice?: Record<string, string>\n score?: string[]\n}\n\n/**\n * The decide-shaped question a definition asks over a conversation — the\n * same three types as the agent-service decision question, with criteria in\n * an explicit struct so manifests and SDKs need no tagged-union decoder.\n * `type` is immutable after create: tag values are typed by it.\n */\nexport interface ConversationTagQuestion {\n type: ConversationTagQuestionType\n instructions: string\n /** Always on the wire; pass `{}` for a boolean question without descriptions. */\n criteria: ConversationTagCriteria\n}\n\n/**\n * Makes a `reason` definition ask the cheap decide model first whether it\n * applies anywhere in the judged window (its own boolean question, one answer\n * per window); only a definition that passes (probability ≥ `min_probability`)\n * reaches the reasoning call, which is skipped entirely when nothing passes. A\n * screened-out definition's stale tags are still replaced. Boolean questions\n * only — choice and score always have an answer. Omitted = screening on with\n * the service default threshold (0.3, `CONVERSATION_TAG_SCREENING_MIN_PROBABILITY`);\n * `{ is_enabled: false }` turns it off. The service rejects `screening` on a\n * `decide` evaluator or on a choice/score question, and a `min_probability`\n * outside 0..1.\n */\nexport interface ConversationTagScreening {\n is_enabled: boolean\n /** Pass threshold in 0..1; absent = the service default. */\n min_probability?: number\n}\n\n/**\n * Selects the model path. `model_id` is only meaningful for `reason` (absent =\n * the service default); `decide` always uses the service-wide decision model.\n * `screening` is only meaningful for `reason` with a boolean question; absent =\n * screening on with the service default threshold.\n */\nexport interface ConversationTagEvaluator {\n kind: ConversationTagEvaluatorKind\n model_id?: string\n screening?: ConversationTagScreening\n}\n\n/**\n * Describes WHAT to look for in a conversation: one typed question plus where\n * its answers anchor (`scope`) and which model path answers it (`evaluator`).\n * WHERE and WHEN a definition is evaluated is a ConversationTagSet's business\n * — a definition that no enabled set references is never evaluated. Keyed\n * (org_id, key) and module-deployable (conversation-tag-definitions/<key>.json),\n * like conversation types.\n */\nexport interface ConversationTagDefinition {\n org_id: string\n /** Immutable identity within the org — the value every tag carries as `definition_key`. */\n key: string\n name: string\n /** Free grouping for UIs (\"content\", \"sentiment\", \"signal\"). */\n group?: string\n question: ConversationTagQuestion\n /** `span` requires `evaluator.kind = 'reason'`. */\n scope: ConversationTagScope\n evaluator: ConversationTagEvaluator\n /** `summary` requires conversation scope. */\n basis: ConversationTagBasis\n /** Absent = a plain observation. `outcome` requires a choice question at conversation scope. */\n role?: ConversationTagRole\n /**\n * Narrows message/span-scope judging to messages of these directions (e.g.\n * inbound only for customer sentiment); empty = all. Ignored for\n * conversation scope.\n */\n directions: MessageDirection[]\n /**\n * Observations below it are dropped, for every question type — an absent\n * tag means \"not determined\", not \"false\".\n */\n min_confidence: number\n /** Optional UI hint (any CSS color token the client accepts). */\n color?: string\n is_enabled: boolean\n /** Module that deployed the definition; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Describes WHERE and WHEN a group of tag definitions is evaluated. A\n * conversation matches a set when every NON-EMPTY selector contains it:\n * `channels`, `connection_ids`, `type_keys` (an empty conversation `type_key`\n * never matches a type-scoped set, so type-scoped sets only apply once a\n * conversation has been classified). At least one of those three must be\n * non-empty — tagging is opt-in, never org-wide by accident. `directions` is\n * a message-level filter on top (which messages arm / are judged), not a\n * conversation selector. Matched sets union their definition keys; timing\n * takes the minimum quiet window and max wait over the matched sets that\n * evaluate in realtime. Keyed (org_id, key) and module-deployable\n * (conversation-tag-sets/<key>.json).\n */\nexport interface ConversationTagSet {\n org_id: string\n key: string\n name: string\n /**\n * The definitions this set evaluates (≥ 1; each must exist in the org at\n * write time — a definition deleted later is skipped).\n */\n definition_keys: string[]\n channels: Channel[]\n connection_ids: string[]\n type_keys: string[]\n /**\n * Narrows which NEW messages arm a realtime evaluation (and which messages a\n * completion evaluation judges for message/span scope): inbound only,\n * outbound only, or both when empty. A definition's own `directions`\n * narrows further.\n */\n directions: MessageDirection[]\n /**\n * A non-empty subset of [realtime, completion]: realtime = the debounced\n * window after new messages arrive; completion = once the conversation\n * completed (final transcript + summary for spoken media, End for the\n * rest). Manual evaluations ignore it.\n */\n evaluate_on: ConversationTagTrigger[]\n /** A realtime evaluation fires this long after the LAST new message (default 90, min 5). */\n quiet_window_seconds: number\n /**\n * Bounds the wait since the FIRST unjudged message (default 600, ≥ quiet\n * window) so a busy stream is still tagged periodically.\n */\n max_wait_seconds: number\n is_enabled: boolean\n /** Module that deployed the set; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * One observation a definition made on a conversation.\n *\n * Anchors encode the definition's scope: conversation scope = every anchor\n * field absent; message scope = `start_message_id === end_message_id` with no\n * offsets; span = offsets set (a span may cross messages, then start/end\n * message ids differ). Offsets are UNICODE CODE POINT indexes into the\n * message's first text content block, end exclusive — JS strings are UTF-16,\n * so convert (e.g. via `Array.from(text)` / code-point iteration) before\n * slicing. `quote` (and `end_quote` for a span that continues into a later\n * message) is the verbatim text at the anchor: the reason evaluator emits\n * quotes because a model cannot count characters, the service resolves them\n * to offsets, and afterwards the quote is the evidence that survives a message\n * row change (the final transcript swaps realtime message ids; a term\n * correction edits text) — a tag whose anchors no longer resolve still shows\n * its quote and can be re-anchored by search.\n *\n * `value` is normalized per question type: `\"true\"` for a boolean (false is\n * never stored), the option key for a choice, the 0-based level index AS A\n * STRING for a score. Status `pending` marks a provisional realtime\n * observation on a live spoken-medium conversation; a completion evaluation\n * replaces it. Dismissed tags are feedback: a later evaluation never\n * re-creates a tag matching a dismissed one on (definition_key, value,\n * start/end message).\n */\nexport interface ConversationTag {\n id: string\n org_id: string\n conversation_id: string\n /**\n * Denormalized from the conversation so org-wide lists and counts group by\n * channel without a join.\n */\n channel: Channel\n definition_key: string\n /** `\"true\"` | choice option key | score level index as a string. */\n value: string\n confidence: number\n /**\n * The raw decide distribution (`{\"true\":p,\"false\":1-p}`, option → p, or\n * `{\"levels\":[…],\"mean\":x}`); a screened reason tag carries\n * `{\"screening\":p}` instead; absent for unscreened reason and user tags.\n */\n probabilities?: Record<string, unknown>\n /** The reason evaluator's one-line rationale; absent for decide. */\n why?: string\n source: ConversationTagSource\n status: ConversationTagStatus\n /** Links a model tag to the evaluation that produced it. */\n evaluation_id?: string\n start_message_id?: string\n /** Unicode code-point index, inclusive. */\n start_offset?: number\n end_message_id?: string\n /** Unicode code-point index, exclusive. */\n end_offset?: number\n start_occurred_at?: string\n end_occurred_at?: string\n quote?: string\n end_quote?: string\n /**\n * When the observed thing happened (the end message's `occurred_at`, else\n * the last message's) — the time-series axis.\n */\n observed_at: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * One row of `conversationTags.counts`: the grouped columns that were\n * requested plus the count.\n */\nexport interface ConversationTagCount {\n definition_key?: string\n value?: string\n channel?: Channel\n count: number\n}\n\n/**\n * The model spend of one evaluation, summed over its decide and generate\n * calls.\n */\nexport interface ConversationTagUsage {\n input_tokens: number\n output_tokens: number\n request_count: number\n}\n\n/**\n * One screening verdict of an evaluation: the decide probability that the\n * definition applies in the judged window and whether that passed the\n * threshold. `probability` is absent (and `error` set) when the screening\n * could not be asked — it then passes, fail-open.\n */\nexport interface ConversationTagScreeningResult {\n definition_key: string\n probability?: number\n is_passed: boolean\n error?: string\n}\n\n/**\n * Records one time the tagger ran on a conversation: why (`trigger`), what it\n * judged (`definition_keys`, the message window), with which models, what it\n * cost, and how it ended. Model tags reference it through `evaluation_id`\n * (provenance), the UI polls it after a manual evaluate (202), and the latest\n * done realtime/completion evaluation's `window_end_occurred_at` is the\n * watermark the next realtime window starts after.\n *\n * Window = the messages JUDGED by this evaluation. realtime: everything after\n * the previous watermark (older messages ride along as context only);\n * completion/manual: all messages. Lifecycle: manual creates `pending` on the\n * 202 then flips to `running`; realtime/completion create `running` directly;\n * ends `done` or `failed`.\n */\nexport interface ConversationTagEvaluation {\n id: string\n org_id: string\n conversation_id: string\n trigger: ConversationTagTrigger\n status: ConversationTagEvaluationStatus\n definition_keys: string[]\n model_ids: string[]\n usage: ConversationTagUsage\n /**\n * The rendered state exceeded the cap and older context (or, for a huge\n * window, the newest window messages — deferred to the next evaluation) was\n * dropped.\n */\n is_truncated: boolean\n window_start_occurred_at?: string\n window_end_occurred_at?: string\n window_message_ids: string[]\n /**\n * Every screened reason definition's verdict, so \"why was nothing tagged\"\n * is answerable and thresholds can be tuned. Empty when no definition was\n * screened.\n */\n screenings: ConversationTagScreeningResult[]\n error?: string\n started_at: string\n finished_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * The `conversation.tagged` event payload: the conversation, the evaluation\n * that landed, and every tag it produced (status pending or active — the\n * event header carries the status so a consumer can filter provisional\n * realtime observations without decoding).\n */\nexport interface ConversationTaggedEvent {\n conversation: Conversation\n evaluation: ConversationTagEvaluation\n tags: ConversationTag[]\n}\n\n/**\n * Creates one tag definition. `key` is the immutable identity (kebab/snake,\n * like every platform key); `question` is the decide-shaped question the\n * evaluator answers; `scope` and `evaluator` say where answers anchor and\n * which model path answers (`span` requires `evaluator.kind = 'reason'`).\n * `is_enabled` omitted ⇒ true (manifests may omit it). `module_slug` is\n * stamped by `pro module deploy` — interactive callers leave it empty.\n */\nexport interface CreateConversationTagDefinitionRequest {\n key: string\n name?: string\n group?: string\n question: ConversationTagQuestion\n scope: ConversationTagScope\n evaluator: ConversationTagEvaluator\n /** Omitted ⇒ `conversation`. */\n basis?: ConversationTagBasis\n /** Omitted ⇒ none. */\n role?: ConversationTagRole | ''\n directions?: MessageDirection[]\n /** 0..1 */\n min_confidence?: number\n color?: string\n is_enabled?: boolean\n module_slug?: string\n}\n\n/**\n * Partial update — an omitted field leaves the stored value untouched.\n * `question`, when present, replaces the stored question wholesale but must\n * keep its `type` (400 `conversation_tag_question_type_immutable` otherwise).\n * `directions` replaces wholesale. `key` is immutable.\n */\nexport interface UpdateConversationTagDefinitionRequest {\n name?: string\n group?: string\n question?: ConversationTagQuestion\n scope?: ConversationTagScope\n evaluator?: ConversationTagEvaluator\n basis?: ConversationTagBasis\n /** Empty string clears the role. */\n role?: ConversationTagRole | ''\n directions?: MessageDirection[]\n /** 0..1 */\n min_confidence?: number\n color?: string\n is_enabled?: boolean\n}\n\nexport interface ListConversationTagDefinitionsQuery extends PaginationQuery {\n /** Definitions deployed by one module — the `pro module` remote-state discovery door. */\n module_slug?: string\n /** Exact filter. */\n group?: string\n /** Exact filter. */\n scope?: string\n /** Exact filter — `outcome` lists the outcome definitions. */\n role?: string\n is_enabled?: boolean\n /** Case-insensitive substring match on key or name. */\n search?: string\n}\n\n/**\n * Creates one tag set: which definitions to evaluate (`definition_keys`, ≥ 1,\n * each must exist), for which conversations (at least one of `channels` /\n * `connection_ids` / `type_keys` non-empty; `directions` additionally limits\n * which messages arm/are judged — empty = both), when (`evaluate_on` ⊆\n * [realtime, completion], ≥ 1) and the realtime timing (omitted ⇒ defaults:\n * quiet 90s, max wait 600s). `is_enabled` omitted ⇒ true. `module_slug` is\n * stamped by `pro module deploy`.\n */\nexport interface CreateConversationTagSetRequest {\n key: string\n name?: string\n definition_keys: string[]\n channels?: Channel[]\n connection_ids?: string[]\n type_keys?: string[]\n directions?: MessageDirection[]\n evaluate_on: ConversationTagTrigger[]\n quiet_window_seconds?: number\n max_wait_seconds?: number\n is_enabled?: boolean\n module_slug?: string\n}\n\n/**\n * Partial update — an omitted field leaves the stored value untouched; arrays\n * replace wholesale. `key` is immutable.\n */\nexport interface UpdateConversationTagSetRequest {\n name?: string\n definition_keys?: string[]\n channels?: Channel[]\n connection_ids?: string[]\n type_keys?: string[]\n directions?: MessageDirection[]\n evaluate_on?: ConversationTagTrigger[]\n quiet_window_seconds?: number\n max_wait_seconds?: number\n is_enabled?: boolean\n}\n\nexport interface ListConversationTagSetsQuery extends PaginationQuery {\n /** Sets deployed by one module. */\n module_slug?: string\n /** Sets that reference the definition. */\n definition_key?: string\n is_enabled?: boolean\n /** Case-insensitive substring match on key or name. */\n search?: string\n}\n\n// ── Conversation objectives ──────────────────────────────────────────────\n\n/**\n * How an objective definition's achievement is told: `tag` (a tag on a tag\n * definition meets a value condition) or `outcome` (the conversation's\n * outcome is one of a set).\n */\nexport type ConversationObjectiveMeasureKind = 'tag' | 'outcome'\n\n/**\n * The value condition — exactly one field set, matched to the question type\n * of the measured tag definition (boolean / choice / score) or, for kind\n * `outcome`, `choice_in` over outcome keys. `score_min` is the 0-based level\n * index a score tag must reach (tag values store the level index).\n */\nexport interface ConversationObjectiveAchievedWhen {\n boolean?: boolean\n choice_in?: string[]\n score_min?: number\n}\n\n/**\n * How an objective's achievement is told:\n *\n * - kind `tag`: a non-dismissed tag on `tag_definition_key` whose value meets\n * `achieved_when` (a pending tag ⇒ achieved, provisional). The tag\n * definition must be conversation-scoped and role-less — a person ticks the\n * objective by creating a user tag on it, unticks by deleting that tag.\n * - kind `outcome`: the conversation's `outcome_key` is one of\n * `achieved_when.choice_in` (the type's outcomes and the channel's system\n * outcomes) — ticked through the outcome picker.\n */\nexport interface ConversationObjectiveMeasure {\n kind: ConversationObjectiveMeasureKind\n /** Required for kind `tag`; absent for kind `outcome`. */\n tag_definition_key?: string\n achieved_when: ConversationObjectiveAchievedWhen\n}\n\n/**\n * One thing a conversation should achieve — \"confirm the budget\", \"agree a\n * next step\", \"book the demo\". Applies to every conversation (`type_key`\n * absent) or to conversations of one type, may be pinned to one of that\n * type's phases (the checklist groups by phase, and a phase counts as done\n * once every measured objective in it is achieved), and may be MEASURED so\n * the platform tells whether it was achieved (no `measure` = guidance only,\n * a line on the checklist). Its instance on a conversation is a\n * ConversationObjective — the same definition → instance split as\n * ConversationTagDefinition → ConversationTag. Keyed by `key`;\n * module-deployable (conversation-objective-definitions/<key>.json).\n */\nexport interface ConversationObjectiveDefinition {\n org_id: string\n key: string\n name: string\n description?: string\n /** Restricts the objective to one conversation type; absent = every conversation. */\n type_key?: string\n /** Pins the objective to one of the type's phases (requires `type_key`); absent = ungrouped. */\n phase_key?: string\n /** How achievement is told; absent = guidance only. */\n measure?: ConversationObjectiveMeasure\n is_enabled: boolean\n /** Module that deployed the definition; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Creates one objective definition. `phase_key` requires `type_key` and must\n * be one of that type's phases. A `tag` measure names a CONVERSATION-scoped,\n * role-less tag definition and its `achieved_when` must match the question\n * type (boolean ⇒ `{boolean: true}`; choice ⇒ `{choice_in ⊆ options}`; score\n * ⇒ `{score_min: level index}`); an `outcome` measure takes `{choice_in}` over\n * outcome keys (the type's outcomes ∪ the channel system outcomes when\n * typed). `is_enabled` omitted ⇒ true. `module_slug` is stamped by\n * `pro module deploy`.\n */\nexport interface CreateConversationObjectiveDefinitionRequest {\n key: string\n name: string\n description?: string\n type_key?: string\n phase_key?: string\n measure?: ConversationObjectiveMeasure\n is_enabled?: boolean\n module_slug?: string\n}\n\n/**\n * Partial update — an omitted field leaves the stored value untouched.\n * `measure` is tri-state: omitted keeps it, `null` clears it (guidance only),\n * a value replaces it wholesale. `key` is immutable.\n */\nexport interface UpdateConversationObjectiveDefinitionRequest {\n name?: string\n description?: string\n type_key?: string\n phase_key?: string\n measure?: ConversationObjectiveMeasure | null\n is_enabled?: boolean\n}\n\nexport interface GetManyConversationObjectiveDefinitionsQuery extends PaginationQuery {\n /** Definitions deployed by one module. */\n module_slug?: string\n type_key?: string\n phase_key?: string\n is_enabled?: boolean\n /** Case-insensitive substring match on key or name. */\n search?: string\n}\n\n/**\n * An objective's standing on a conversation: open (not yet, or no longer,\n * achieved) or achieved. Whether an achieved standing is still provisional is\n * the separate `is_provisional` flag, never a third status.\n */\nexport type ConversationObjectiveStatus = 'open' | 'achieved'\n\n/**\n * Who achieved an objective: a person (a user tag or a hand-picked outcome),\n * the model (a detected tag or outcome) or the system (a channel-level\n * outcome the service set by itself).\n */\nexport type ConversationObjectiveSource = 'user' | 'model' | 'system'\n\n/** Where a conversation stands in one of its type's phases. */\nexport type ConversationPhaseStatus = 'done' | 'current' | 'upcoming' | 'untracked'\n\n/**\n * One objective definition's standing on one conversation: open or achieved,\n * by whom, when, and on which tag. Resolved live for the per-conversation\n * read (ConversationObjectiveProgress) AND persisted as the ledger row of\n * the same shape — one row per APPLICABLE definition, open rows included,\n * rewritten at every change point. Never user-written.\n */\nexport interface ConversationObjective {\n org_id: string\n conversation_id: string\n definition_key: string\n /** The conversation's channel, denormalized at resolution time. */\n channel: Channel\n /** The conversation's type, denormalized at resolution time. */\n type_key?: string\n /** The definition's phase, denormalized at resolution time. */\n phase_key?: string\n status: ConversationObjectiveStatus\n /** Who achieved it; absent while open. */\n source?: ConversationObjectiveSource\n /**\n * The backing tag is still `pending` — a realtime detection on a live\n * spoken conversation the completion pass has not confirmed. Never true for\n * a user or system source.\n */\n is_provisional: boolean\n achieved_at?: string\n /**\n * The tag that achieved a tag-measured objective (the one to delete to\n * untick when `source` is user); absent for outcome measures.\n */\n tag_id?: string\n /** The conversation's status at resolution time — an open objective on an ended conversation was missed. */\n is_conversation_ended: boolean\n /** When this standing was resolved (the ledger write). */\n recorded_at: string\n}\n\n/**\n * One row of `conversationObjectives.counts`: the grouped columns that were\n * requested plus the count.\n */\nexport interface ConversationObjectiveCount {\n definition_key?: string\n status?: ConversationObjectiveStatus\n source?: ConversationObjectiveSource\n is_provisional?: boolean\n type_key?: string\n phase_key?: string\n channel?: Channel\n count: number\n}\n\n/**\n * One of the type's phases as the conversation stands in it, derived from\n * the objectives pinned to the phase: `done` = every measured objective\n * achieved (≥ 1 measured; provisional counts); `current` = the first phase\n * in type order that is not done and has a measured objective; `upcoming` =\n * after the current one; `untracked` = no measured objective, so progress\n * cannot be told (dim, never current). `completed_at` is the latest\n * `achieved_at` among the phase's measured objectives once done.\n */\nexport interface ConversationPhaseProgress extends ConversationPhase {\n status: ConversationPhaseStatus\n completed_at?: string\n}\n\n/**\n * `conversations.getObjectiveProgress`: where the conversation stands — the\n * current phase key (`''` when the type has no phases or every tracked phase\n * is done), every phase with its status, every applicable objective with its\n * standing, and the applicable definitions the objectives reference by\n * `definition_key` (join `objectives[].definition_key` → `definitions[].key`\n * for name / description / measure). Objectives are ordered: ungrouped first,\n * then by the type's phase order, then name.\n */\nexport interface ConversationObjectiveProgress {\n phase_key: string\n phases: ConversationPhaseProgress[]\n objectives: ConversationObjective[]\n definitions: ConversationObjectiveDefinition[]\n}\n\n/** The org-wide ledger read (`conversationObjectives.list`); `since`/`until` bound `recorded_at`. */\nexport interface GetManyConversationObjectivesQuery extends PaginationQuery {\n conversation_id?: string\n definition_key?: string\n type_key?: string\n phase_key?: string\n channel?: string\n status?: string\n source?: string\n is_provisional?: boolean\n is_conversation_ended?: boolean\n /** Lower bound on `recorded_at` (inclusive), RFC 3339. */\n since?: string\n /** Upper bound on `recorded_at` (exclusive), RFC 3339. */\n until?: string\n}\n\n/**\n * Groups the ledger for dashboards. `group_by` is a COMMA-JOINED string (not\n * an array — the query serializer repeats array keys) whitelisted to\n * definition_key, status, source, is_provisional, type_key, phase_key,\n * channel (order kept; default `definition_key,status`).\n */\nexport interface CountConversationObjectivesQuery {\n group_by?: string\n definition_key?: string\n type_key?: string\n phase_key?: string\n channel?: string\n status?: string\n source?: string\n is_provisional?: boolean\n is_conversation_ended?: boolean\n /** Lower bound on `recorded_at` (inclusive), RFC 3339. */\n since?: string\n /** Upper bound on `recorded_at` (exclusive), RFC 3339. */\n until?: string\n}\n\nexport interface CountConversationObjectivesResponse {\n data: ConversationObjectiveCount[]\n}\n\n/**\n * The manual door (`conversationTags.create`): a person tags a conversation,\n * a message or a span. Anchors follow the definition's scope (conversation:\n * none; message: start == end message, no offsets; span: UNICODE CODE POINT\n * offsets into the message's first text block, end exclusive — convert from\n * UTF-16 indexes before sending). The service stamps `source = 'user'`,\n * confidence 1, and fills `quote` from the anchored text.\n */\nexport interface CreateConversationTagRequest {\n definition_key: string\n /** `\"true\"` | choice option key | score level index as a string. */\n value: string\n why?: string\n start_message_id?: string\n /** Unicode code-point index, inclusive. */\n start_offset?: number\n end_message_id?: string\n /** Unicode code-point index, exclusive. */\n end_offset?: number\n}\n\n/**\n * Patches a tag: `status` flips it between `active` and `dismissed` (the\n * feedback loop), `why` annotates it, and `value` / the anchors correct it —\n * absent fields keep the stored value and the merged tag is validated against\n * its definition like a manual tag. `definition_key` is immutable. A value or\n * anchor change turns the tag into a user tag (confidence 1, no\n * probabilities, no evaluation) so a later evaluation no longer replaces it;\n * a corrected `pending` tag becomes `active` unless `status` says otherwise.\n */\nexport interface UpdateConversationTagRequest {\n status?: ConversationTagStatus\n why?: string\n /** `\"true\"` | choice option key | score level index as a string. */\n value?: string\n /** Anchors are tri-state: omit = keep, `null` = clear, a value = set. */\n start_message_id?: string | null\n /** Unicode code-point index, inclusive. */\n start_offset?: number | null\n end_message_id?: string | null\n /** Unicode code-point index, exclusive. */\n end_offset?: number | null\n}\n\n/**\n * Starts a manual evaluation (`conversationTags.evaluate`, 202). Omitted or\n * empty `definition_keys` = every definition the currently matching sets\n * reference (and every model tag on the conversation is replaced); a list\n * narrows both the questions and the replacement to those keys.\n */\nexport interface EvaluateConversationTagsRequest {\n definition_keys?: string[]\n}\n\n/**\n * Serves both `conversationTags.listByConversation` (the service forces\n * `conversation_id` from the path) and the org-wide `conversationTags.list`.\n */\nexport interface ListConversationTagsQuery extends PaginationQuery {\n conversation_id?: string\n definition_key?: string\n value?: string\n channel?: string\n source?: string\n status?: string\n /** Tags anchored on the message at either end. */\n message_id?: string\n /** Tags on conversations whose roster contains the contact. */\n contact_id?: string\n /** Lower bound on `observed_at` (inclusive), RFC 3339. */\n since?: string\n /** Upper bound on `observed_at` (exclusive), RFC 3339. */\n until?: string\n}\n\n/**\n * Groups active tags for dashboards. `group_by` is a COMMA-JOINED string\n * (`'definition_key,value'`) — not an array, because the query serializer\n * repeats array keys — whitelisted to definition_key, value, channel (order\n * kept).\n */\nexport interface CountConversationTagsQuery {\n group_by?: string\n definition_key?: string\n channel?: string\n source?: string\n status?: string\n /** Lower bound on `observed_at` (inclusive), RFC 3339. */\n since?: string\n /** Upper bound on `observed_at` (exclusive), RFC 3339. */\n until?: string\n}\n\nexport interface CountConversationTagsResponse {\n data: ConversationTagCount[]\n}\n\nexport interface ListConversationTagEvaluationsQuery extends PaginationQuery {\n trigger?: string\n status?: string\n}\n\n/** Who assigned a contact's group membership. */\nexport type ContactGroupSource = 'manual' | 'model'\n\n/**\n * A generic org-shared audience taxonomy entry (\"external-client\",\n * \"internal-colleague\", …) — NOT tone-specific. Membership lives on the\n * contact (`Contact.group_key`, one group per contact) and is assignable by\n * any flow; tone-of-voice synthesis both reads and auto-assigns groups.\n * Module-deployable (contact-groups/<key>.json).\n */\nexport interface ContactGroup {\n org_id: string\n /** Immutable identity within the org — what models answer with. */\n key: string\n name: string\n /** Who belongs in the group — injected verbatim into the synthesis prompt. */\n description?: string\n /** True when tone synthesis proposed the group. Server-owned. */\n is_auto_created: boolean\n /** Module that deployed the group; absent when not module-owned. */\n module_slug?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateContactGroupRequest {\n /** Lowercase kebab/snake/camel handle — no spaces. */\n key: string\n name: string\n description?: string\n module_slug?: string\n}\n\nexport interface UpdateContactGroupRequest {\n name?: string\n description?: string\n}\n\nexport interface ListContactGroupsQuery extends PaginationQuery {\n /** Case-insensitive substring match on key or name. */\n search?: string\n module_slug?: string\n}\n\n/** The whole-user synthesis lifecycle on a tone profile setup. */\nexport type ToneProfileSetupStatus = 'empty' | 'processing' | 'ready'\n\n/** A tone profile row's tier — derived, most specific wins at read time. */\nexport type ToneProfileScope = 'user' | 'channel' | 'group' | 'contact'\n\n/**\n * Who wrote a tone profile, and therefore who may change it. `manual` rows are\n * hand-authored and authoritative: synthesis never overwrites or prunes them,\n * and deleting the user's setup (the AI opt-in) leaves them standing. `model`\n * rows belong to the synthesis sweep, which owns them outright.\n */\nexport type ToneProfileSource = 'manual' | 'model'\n\n/**\n * The per-user opt-in for tone-of-voice synthesis: only set-up users are\n * swept. Also carries the whole-user synthesis claim (status/started_at).\n */\nexport interface ToneProfileSetup {\n id: string\n org_id: string\n /** The profiled platform user. */\n owned_by: UserRef\n status: ToneProfileSetupStatus\n started_at?: string\n last_synthesized_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * One tone-of-voice instruction row — synthesized or hand-authored (`source`).\n * Rows form a specificity\n * hierarchy — user aggregate (the constant voice), per-channel base, per\n * contact-group, per individual contact — and every row is SELF-CONTAINED: a\n * drafting consumer injects exactly one row's `instructions` verbatim (use\n * the resolve endpoint), never a concatenation of tiers.\n */\nexport interface ToneProfile {\n id: string\n org_id: string\n /** The profiled platform user. */\n owned_by: UserRef\n /** Absent = the cross-channel user aggregate (the voice proper). */\n channel?: Channel\n /** Scopes the row to one contact group; absent = the (user, channel) base. */\n contact_group_key?: string\n /** Scopes the row to one individual contact within the group. */\n contact_id?: string\n scope: ToneProfileScope\n /** Who owns this row — see ToneProfileSource. */\n source: ToneProfileSource\n /** COMPLETE markdown instruction set, served verbatim to a drafting model. */\n instructions: string\n /** Short delta vs the tier above — what a human scans; empty on root tiers. */\n differences?: string\n sample_count: number\n last_message_at?: string\n last_synthesized_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateToneProfileSetupRequest {\n /** Bare platform user id; the service resolves the full ref. */\n owned_by_id: string\n}\n\nexport type ListToneProfileSetupsQuery = PaginationQuery\n\nexport interface ListToneProfilesQuery extends PaginationQuery {\n owned_by_id?: string\n channel?: Channel\n scope?: ToneProfileScope\n /** Narrow to hand-authored (`manual`) or synthesized (`model`) rows. */\n source?: ToneProfileSource\n}\n\n/**\n * Writes ONE hand-authored tone profile. The identity is the scope tuple, not\n * an id — re-sending the same scope updates the row it created. The row lands\n * `source: 'manual'`, which locks that scope against synthesis; it also takes\n * the scope over from a `model` row already sitting there.\n *\n * Scope grammar (mirrors the resolve precedence): omit `channel` for the\n * cross-channel base voice; `contact_group_key` needs a `channel`;\n * `contact_id` needs both, because resolution reaches a contact row only\n * through its group.\n */\nexport interface UpsertToneProfileRequest {\n owned_by_id: string\n channel?: Channel\n contact_group_key?: string\n contact_id?: string\n /** COMPLETE markdown style guide for this tier; never a delta. */\n instructions: string\n /** Optional human-facing note on how this tier differs from the one above. */\n differences?: string\n}\n\n/**\n * A drafting context to resolve the single most-specific profile for:\n * contact → group → channel base → user aggregate.\n */\nexport interface ResolveToneProfileQuery {\n owned_by_id: string\n channel?: Channel\n contact_id?: string\n}\n\nexport interface PaginationQuery {\n page?: number\n page_size?: number\n sort_by?: string\n sort_direction?: 'asc' | 'desc'\n}\n\nexport interface ListConnectionsQuery extends PaginationQuery {\n connector_key?: string\n channel?: string\n scope?: string\n /**\n * Narrows to the user-scoped connections one person owns. Org-scoped\n * connections have no owner and never match.\n */\n owner_id?: string\n status?: string\n /**\n * The caller's intent: `read` (default) lists every connection they reach;\n * `write` only those they may send through — the compose picker's question.\n */\n permission?: 'read' | 'write'\n}\n\n/**\n * The delete's escape hatch. A connection delete makes the connector release\n * its provider-side registration first and refuses with a 502\n * `connector_uninstall_failed` when that fails — the row is the only handle on\n * that state. `is_forced` drops the row anyway, leaving the provider-side\n * leftovers as a manual cleanup.\n */\nexport interface DeleteConnectionQuery {\n is_forced?: boolean\n}\n\nexport interface ListConversationsQuery extends PaginationQuery {\n channel?: string\n status?: string\n connection_id?: string\n type_key?: string\n /** The meeting conversations born from one calendar event UID. */\n calendar_event_ical_uid?: string\n /** The calls dialled with one brief, or later given it. */\n brief_id?: string\n /**\n * Conversations whose row changed at or after this ISO instant: an outcome\n * set, a call ended, but also any other write such as a summary.\n */\n updated_after?: string\n /** How conversations ended (one of a type's outcome keys). */\n outcome_key?: string\n /**\n * Conversations of one room (Slack channel) — the room stream. A\n * present-but-EMPTY string is meaningful: it filters to the room-LESS\n * conversations (DMs, email, meetings), used to resolve a DM's main. The\n * value is applied verbatim server-side (`room_id = ''`), so only omit the\n * key (not set it to `''`) to mean \"any room\".\n */\n room_id?: string\n /**\n * Child conversations forked from one main conversation. A present-but-EMPTY\n * string filters to the MAINS (and DMs) — the conversations that are not\n * thread children (`parent_conversation_id = ''`); used to resolve a\n * channel's main conversation. Omit the key to mean \"children and mains\n * alike\".\n */\n parent_conversation_id?: string\n /** Threads whose roster contains this external party — the person stream. */\n /** Contact stream: threads whose roster contains the resolved person. */\n contact_id?: string\n /** \"Sent as\" stream: threads pinned to one sending identity (a contact address id). */\n sender_address_id?: string\n /** Opt into the root/latest message projection on each row. */\n include?: 'messages_summary'\n /**\n * Conversations carrying an ACTIVE conversation tag of this definition —\n * the \"which conversations talk about billing\" stream.\n */\n tag_key?: string\n /** With `tag_key`: only conversations whose tag has this value. */\n tag_value?: string\n /**\n * The hub's Mine / All axis. `own`: threads on the caller's own\n * connections and the org-wide ones (on a shared sending connection only\n * threads the caller is in), plus connection-less threads they created.\n * `all` (the default when omitted): everything the caller may read.\n */\n conversation_scope?: ConversationScope\n}\n\n/** `?conversation_scope=` values — see ListConversationsQuery. */\nexport type ConversationScope = 'own' | 'all'\n\n/** Unread counts follow the same Mine / All axis as the list. */\nexport interface UnreadCountsQuery {\n conversation_scope?: ConversationScope\n}\n\n/**\n * User-editable surface of a conversation (PATCH); everything else is owned by\n * ingest.\n */\nexport interface UpdateConversationRequest {\n subject?: string\n /** Markdown summary (auto-generated for meetings, freely editable). */\n summary?: string\n status?: ConversationStatus\n metadata?: Record<string, unknown>\n /** Set the type by hand (must exist; `''` clears). Leaves the outcome alone. */\n type_key?: string\n /**\n * How the conversation ended — one of `conversations.listOutcomes(id)`\n * (its type's outcomes or its channel's system outcomes; `''` clears). The\n * person's choice: never overridden by the model or the service. 400\n * `conversation_outcome_unknown` when the key is in neither list.\n */\n outcome_key?: string\n}\n\nexport interface ListMessagesQuery extends PaginationQuery {\n direction?: string\n status?: string\n}\n\nexport interface ListAgentListenersQuery extends PaginationQuery {\n connection_id?: string\n conversation_id?: string\n room_id?: string\n agent_key?: string\n is_enabled?: boolean\n}\n\n/**\n * Conversation filters: rules that drop matching inbound messages BEFORE\n * persistence (no message, no contact — only a content-free audit event) and,\n * on meeting calendar connections, gate whether the meeting bot is scheduled\n * at all (pre-join enforcement of the same rules — earliest possible point).\n * Scope-first evaluation: connection-scoped rules are final when one matches;\n * global rules apply otherwise. Specificity within a scope:\n * address > domain > title_keyword > role_based > automated >\n * self_originated > internal_participant > internal_conversations > all,\n * allow beats block within a class; an allow match is a final keep, which is\n * the auto-join composition mechanism (e.g. \"organized by me\" = a\n * connection-scoped all-block plus a self_originated allow).\n *\n * Channel matrix: address/self_originated/all act on every channel;\n * domain/title_keyword/internal_participant/internal_conversations act on\n * email + meeting connections; role_based/automated are email-only. A\n * connection-scoped rule of a type inert on that connection's channel is\n * rejected (invalid_filter_config); global rules are unrestricted and stay\n * inert where their facts are missing.\n */\nexport type ConversationFilterType =\n | 'address'\n | 'domain'\n | 'title_keyword'\n | 'role_based'\n | 'automated'\n | 'self_originated'\n | 'internal_participant'\n | 'internal_conversations'\n | 'all'\n/**\n * block drops the message; allow keeps it. restrict and share keep it too\n * (they rank as allow) and decide who sees the thread the message CREATES:\n * restrict writes only the rule's principals onto the new thread, share adds\n * them on top of what the thread inherits. Applied once, at creation.\n */\nexport type ConversationFilterAction = 'block' | 'allow' | 'restrict' | 'share'\n/** Which side of the message address/domain rules test (default: sender). */\nexport type FilterMatchOn = 'sender' | 'any_participant'\n/** Deterministic machine-mail header signals the automated filter matches. */\nexport type AutomatedSignal =\n | 'auto_submitted'\n | 'bulk'\n | 'mailing_list'\n | 'bounce'\n | 'auto_response_suppress'\n\n/** Exact canonical address (lowercased email / E.164 phone / provider id), any channel kind. */\nexport interface AddressFilterConfig {\n kind: ContactAddressKind\n value: string\n match_on?: FilterMatchOn\n}\n/** Equals on the parsed email domain (lowercase, no leading '@'). */\nexport interface DomainFilterConfig {\n domain: string\n match_on?: FilterMatchOn\n}\n/** Sender local-part is a role mailbox; empty prefixes = the built-in set. Email-only. */\nexport interface RoleBasedFilterConfig {\n prefixes?: string[]\n}\n/** Header-signal machine-mail detection; empty signals = all. Email-only. */\nexport interface AutomatedFilterConfig {\n signals?: AutomatedSignal[]\n}\n/** Title/subject contains any keyword (case-insensitive substring; stored lowercased). */\nexport interface TitleKeywordFilterConfig {\n keywords: string[]\n}\n/** Conversation originates from the connection owner (meeting organizer / self sender). Empty config. */\nexport type SelfOriginatedFilterConfig = Record<string, never>\n/** ≥1 participant OTHER than the connection self is on one of these domains (any-internal). */\nexport interface InternalParticipantFilterConfig {\n domains: string[]\n}\n/** Drops only when sender AND every recipient are on these domains. Always block. */\nexport interface InternalConversationsFilterConfig {\n domains: string[]\n}\n/** Matches every message (empty config) — the scope-control primitive. */\nexport type AllFilterConfig = Record<string, never>\n\nexport type ConversationFilterConfig =\n | AddressFilterConfig\n | DomainFilterConfig\n | TitleKeywordFilterConfig\n | RoleBasedFilterConfig\n | AutomatedFilterConfig\n | SelfOriginatedFilterConfig\n | InternalParticipantFilterConfig\n | InternalConversationsFilterConfig\n | AllFilterConfig\n\nexport interface ConversationFilter {\n id: string\n org_id: string\n /** Empty = global (org-wide); set = scoped to that connection. */\n connection_id: string\n filter_type: ConversationFilterType\n action: ConversationFilterAction\n filter_config?: ConversationFilterConfig\n is_enabled: boolean\n /** restrict / share only: who the created thread is opened to. */\n principals?: PrincipalRef[]\n /** restrict / share only: read or write (write implies read; the default). */\n permission?: 'read' | 'write'\n /** Read-only rollup: messages this rule matched in the last 30 days. */\n recent_event_count?: number\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** One drop-audit entry (content-free: routing/identity facts only). */\nexport interface ConversationFilterEvent {\n id: string\n org_id: string\n connection_id: string\n conversation_filter_id: string\n filter_type: ConversationFilterType\n reason: string\n sender_kind?: ContactAddressKind\n sender_value?: string\n external_message_id?: string\n /** The thread a restrict / share match applied to; empty on a drop. */\n conversation_id?: string\n occurred_at: string\n}\n\nexport interface CreateConversationFilterRequest {\n connection_id?: string\n filter_type: ConversationFilterType\n action: ConversationFilterAction\n filter_config?: Record<string, unknown>\n is_enabled?: boolean\n /** Required for restrict / share, empty otherwise. */\n principals?: PrincipalRef[]\n permission?: 'read' | 'write'\n /** Opts past the own-domain guard (self_domain_block). */\n is_self_domain_acknowledged?: boolean\n}\n\nexport interface UpdateConversationFilterRequest {\n /** filter_type and filter_config must be sent together. */\n filter_type?: ConversationFilterType\n action?: ConversationFilterAction\n filter_config?: Record<string, unknown>\n is_enabled?: boolean\n principals?: PrincipalRef[]\n permission?: 'read' | 'write'\n is_self_domain_acknowledged?: boolean\n}\n\nexport interface ListConversationFiltersQuery extends PaginationQuery {\n /** Omit = all; '' = global-only; an id = that connection's rules. */\n connection_id?: string\n filter_type?: ConversationFilterType\n action?: ConversationFilterAction\n is_enabled?: boolean\n}\n\nexport type ListConversationFilterEventsQuery = PaginationQuery\n\n/**\n * Discriminates a send target: a person's contact address or a venue. The\n * server also accepts the legacy 'participant' value as an alias for\n * 'contact-address'.\n */\nexport type RecipientKind = 'contact-address' | 'room'\nexport type ContactAddressKind =\n | 'email'\n | 'phone'\n | 'slack'\n /** A Microsoft Teams user's Entra object id (lowercase GUID), scoped to the tenant. */\n | 'teams'\n /** LinkedIn's stable profile id (ACoAA… / ACwAA… / AE…) — what sending needs. */\n | 'linkedin_id'\n /** The `/in/<slug>` public identifier — what humans and records hold. */\n | 'linkedin_public_identifier'\n /** Legacy alias of `linkedin_id` (rows written before the kind split); read-only. */\n | 'linkedin'\n | 'telegram'\n | 'instagram'\n | 'messenger'\n | 'x'\n | 'whatsapp'\nexport type ContactAddressSource = 'sync' | 'ingest' | 'manual' | 'merge'\nexport type ContactSource = 'sync' | 'ingest' | 'manual' | 'merge'\nexport type ContactStatus = 'active' | 'merged' | 'archived' | 'erased'\nexport type ConsentStatus = 'unknown' | 'opted_in' | 'opted_out'\n/** `opt_in_requested`: a double opt-in waits for confirmation; it changes no consent. */\nexport type PermissionEventType = 'opt_in' | 'opt_out' | 'block' | 'unblock' | 'opt_in_requested'\n/**\n * Why a message is sent — the unit a person consents to. A fixed set.\n * `transactional` is never consent-gated (only blocks and erasure stop it).\n */\nexport type Purpose = 'transactional' | 'service' | 'sales' | 'marketing' | 'newsletter'\n/**\n * Where a permission event came from. `provider` = the sending platform\n * observed it (its unsubscribe link, a spam complaint relayed by the mailbox\n * provider, a hard bounce); `link_click` stays for OUR unsubscribe links.\n */\nexport type PermissionEventSource =\n | 'manual'\n | 'import'\n | 'link_click'\n | 'reply'\n | 'api'\n | 'system'\n | 'provider'\nexport type MergeProposalStatus = 'proposed' | 'approved' | 'rejected' | 'superseded'\nexport type ErasureRequestStatus = 'requested' | 'completed'\nexport type RoomSource = 'sync' | 'ingest'\n\n/**\n * Send-time addressing VO: who/where an originated message goes. Points at a\n * ContactAddress or a Room by kind + external id (never a stored entity itself).\n */\nexport interface SendRecipient {\n kind: RecipientKind\n /** The connector-side id: a room's (Slack channel id) or a contact address's wire identifier (Slack user id, email address). */\n external_id: string\n}\n\n/** The actual PERSON an org communicates with — org-scoped, channel-agnostic. */\nexport interface Contact {\n id: string\n org_id: string\n name: string\n status: ContactStatus\n /** Person-level suppression — only block/unblock events move it. */\n is_blocked: boolean\n has_legal_hold: boolean\n consent_status: ConsentStatus\n consent_updated_at?: string\n /** Resolved platform identity when the person is a colleague. */\n platform_user?: UserRef\n /** Merge tombstone redirect (set when status is 'merged'). */\n merged_into_contact_id?: string\n source: ContactSource\n /** IANA zone name (Europe/Berlin); absent = unknown. Filled from directory sweeps while empty. */\n timezone?: string\n /**\n * BCP-47 language tag with optional region (de, de-CH, pt-BR); absent =\n * unknown. Named locale, not language: the region carries formatting\n * conventions on top of the language.\n */\n locale?: string\n /** ContactGroup membership (one group per contact); absent = unassigned. */\n group_key?: string\n /**\n * Who assigned the group: 'manual' assignments are authoritative (tone\n * synthesis never overrides them), 'model' ones may be reassigned by a run.\n */\n group_source?: ContactGroupSource\n has_manual_edits: boolean\n /** The contact's reachable endpoints, embedded on reads. */\n addresses?: ContactAddress[]\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** ONE canonical digital endpoint to reach a contact — the dedup backbone. */\nexport interface ContactAddress {\n id: string\n org_id: string\n contact_id: string\n kind: ContactAddressKind\n /** Provider-tenant qualifier (Slack workspace id); empty for global kinds. */\n scope?: string\n /** Canonical scalar (lowercased email, E.164 phone) — the lookup key. */\n value: string\n /** The identifier as observed on the wire (WhatsApp JID, original casing). */\n raw_value?: string\n /** Per-channel display name. */\n name: string\n consent_status: ConsentStatus\n consent_updated_at?: string\n is_blocked: boolean\n source: ContactAddressSource\n metadata: Record<string, unknown>\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** One entry in the append-only permission ledger (consent + suppression). */\nexport interface ContactPermissionEvent {\n id: string\n org_id: string\n contact_id: string\n /** Scopes the event to one address; absent/empty = contact-level. */\n contact_address_id?: string\n event: PermissionEventType\n /** Narrows a consent event to one purpose; absent = all purposes. */\n purpose?: Purpose\n basis?: string\n source: PermissionEventSource\n occurred_at: string\n note?: string\n evidence?: Record<string, unknown>\n /** The caller's key for the fact; unique per org when set. */\n external_ref?: string\n created_at: string\n created_by: UserRef\n}\n\n/** A contact's consent for one purpose, derived from the ledger (not stored). */\nexport interface ContactPurposeStatus {\n purpose: Exclude<Purpose, 'transactional'>\n status: ConsentStatus\n /** The ledger event that set `status`; absent when unknown. */\n decided_by_event_id?: string\n /** True when that event applies to all purposes. */\n is_inherited: boolean\n /** Addresses opted out of this purpose (or all) on their own scope. */\n opted_out_address_ids: string[]\n /** Addresses opted in to this purpose (or all) on their own scope, such as a double opt-in for one address. */\n opted_in_address_ids: string[]\n /** Addresses with a double opt-in for this purpose waiting to be confirmed. */\n pending_address_ids: string[]\n /** Addresses whose double opt-in for this purpose was not confirmed in time. */\n expired_address_ids: string[]\n}\n\n/** One double opt-in: a confirmation email asking one address for one purpose. */\nexport interface ConsentRequest {\n id: string\n org_id: string\n contact_id: string\n address: string\n purpose: Exclude<Purpose, 'transactional'>\n /** The mailbox the confirmation went out from. */\n connection_id: string\n message_id?: string\n /** The opt_in_requested event in the contact's ledger. */\n requested_event_id?: string\n evidence?: Record<string, unknown>\n expires_at: string\n confirmed_at?: string\n created_at: string\n}\n\n/** A contact's ledger, newest first, with the per-purpose consent. */\nexport interface ListPermissionEventsResponse {\n data: ContactPermissionEvent[]\n purposes: ContactPurposeStatus[]\n}\n\n/** One candidate duplicate pair awaiting review. */\nexport interface ContactMergeProposal {\n id: string\n org_id: string\n contact_a_id: string\n contact_b_id: string\n suggested_winner_id?: string\n confidence?: number\n evidence?: Record<string, unknown>\n verdict?: Record<string, unknown>\n status: MergeProposalStatus\n resolved_by?: UserRef\n resolved_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** A GDPR Art. 17 erasure request (requested → completed). */\nexport interface ContactErasureRequest {\n id: string\n org_id: string\n contact_id: string\n identifier_hashes: Array<{ kind: ContactAddressKind; hmac: string }>\n status: ErasureRequestStatus\n completed_at?: string\n stats?: Record<string, unknown>\n created_at: string\n created_by: UserRef\n}\n\n/** An addressable VENUE on a connection (Slack channel; later meeting rooms). */\nexport interface Room {\n id: string\n org_id: string\n connection_id: string\n /** Slack channel id — the id to post into. */\n external_id: string\n name: string\n metadata: Record<string, unknown>\n /** How the row was populated: a directory sweep or minted at ingest. */\n source: RoomSource\n last_seen_at: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface ListContactAddressesQuery extends PaginationQuery {\n /** Free-text needle matched against display name + canonical value. */\n q?: string\n kinds?: ContactAddressKind[]\n scope?: string\n}\n\nexport interface ListContactsQuery extends PaginationQuery {\n /** Free-text needle matched against contact name + address values. */\n q?: string\n status?: ContactStatus\n /** Members of one contact group (drives group-member lists). */\n group_key?: string\n /**\n * The contact bound to one platform user (at most one active contact per\n * user per org); `'me'` resolves to the caller — a client's way to its own\n * contact.\n */\n platform_user_id?: string\n}\n\nexport interface UpdateContactRequest {\n name?: string\n status?: 'active' | 'archived'\n has_legal_hold?: boolean\n /** IANA zone name; normalized server-side, 400 contact_timezone_invalid when unparseable; '' clears. */\n timezone?: string\n /** BCP-47 language tag; normalized server-side, 400 contact_locale_invalid when unparseable; '' clears. */\n locale?: string\n /**\n * Assigns the contact to a contact group ('' clears). A PATCH assignment is\n * stamped group_source='manual' — tone synthesis never overrides it.\n */\n group_key?: string\n}\n\n/**\n * Manually mints a contact with at least one address. Addresses are\n * canonicalized server-side; any address already owned by another contact\n * rejects the create with 409 contact_address_taken.\n */\nexport interface CreateContactRequest {\n /** Required without platform_user_id; with it, fills an empty name only. */\n name?: string\n /** Required (≥1) without platform_user_id; with it, attached to the colleague's contact. */\n addresses?: AttachContactAddressRequest[]\n /**\n * Colleague mode: ensure the contact bound to this platform user (created\n * from the account directory, or the existing one — every colleague has\n * exactly one) and attach the addresses to it. 200 when it already\n * existed, 201 when created; 404 `platform_user_not_found`, 409\n * `contact_platform_user_conflict`.\n */\n platform_user_id?: string\n /** IANA zone name; optional, validated as on update. */\n timezone?: string\n /** BCP-47 language tag; optional, validated as on update. */\n locale?: string\n}\n\nexport interface AttachContactAddressRequest {\n kind: ContactAddressKind\n scope?: string\n value: string\n name?: string\n}\n\n/** How a contact→record edge came to be: a user's explicit link, or the\n * binding maintained from the record's contact-address attributes (exactly one\n * per record; never unlinked by hand). */\nexport type ContactRecordLinkSource = 'manual' | 'record'\n\n/** One canonical address key of a contact (the dedup backbone). */\nexport interface ContactAddressKey {\n kind: ContactAddressKind\n value: string\n scope?: string\n raw_value?: string\n}\n\n/**\n * A directed edge from a contact to a business record (entity_slug +\n * record_id). Bare — no role; the relationship's semantics come from the\n * target entity. A `manual` link is immutable once created; a `record`\n * binding repoints/refreshes as the record's addresses change and carries the\n * keys the record contributed (`address_keys`).\n */\nexport interface ContactRecordLink {\n id: string\n org_id: string\n contact_id: string\n entity_slug: string\n record_id: string\n source: ContactRecordLinkSource\n address_keys?: ContactAddressKey[]\n created_at: string\n created_by: UserRef\n updated_at?: string\n updated_by?: UserRef\n}\n\nexport interface CreateContactRecordLinkRequest {\n contact_id: string\n entity_slug: string\n record_id: string\n}\n\nexport interface ListContactRecordLinksQuery extends PaginationQuery {\n contact_id?: string\n entity_slug?: string\n record_id?: string\n source?: ContactRecordLinkSource\n}\n\nexport interface MergeContactsRequest {\n source_contact_id: string\n}\n\nexport interface RecordPermissionEventRequest {\n contact_address_id?: string\n /**\n * Scopes the event to the contact's address with this value (an email\n * address, a phone number) when the caller does not know its id. Refused\n * with 400 when the contact has no such address. Ignored when\n * `contact_address_id` is set.\n */\n address?: string\n event: PermissionEventType\n /** One purpose; absent = all purposes. Consent events only; never `transactional`. */\n purpose?: Purpose\n basis?: string\n source?: PermissionEventSource\n occurred_at?: string\n note?: string\n evidence?: Record<string, unknown>\n /**\n * A key for the fact this event records (a sync's id for one upstream\n * status). When the org already has an event with this key, nothing is\n * recorded and the contact comes back unchanged.\n */\n external_ref?: string\n}\n\nexport interface BlockContactRequest {\n contact_address_id?: string\n note?: string\n}\n\nexport interface ListContactMergeProposalsQuery extends PaginationQuery {\n status?: MergeProposalStatus\n}\n\nexport interface ListRoomsQuery extends PaginationQuery {\n /** Free-text needle matched against name + external id. */\n q?: string\n}\n\nexport interface AddReactionRequest {\n /** Connector-native token (Slack shortcode like \"thumbsup\"). */\n emoji: string\n}\n\nexport interface ListReactionsResponse {\n data: Reaction[]\n}\n\nexport interface ResponseMeta {\n page: number\n page_size: number\n items_total: number\n pages_total: number\n}\n\nexport interface ListResponse<T> {\n meta: ResponseMeta\n data: T[]\n}\n\nexport type TranscriptionStatus = 'pending' | 'processing' | 'completed' | 'failed'\n\n/**\n * Post-transcription review lifecycle — the glossary-aware LLM pass that hunts\n * mistranscribed terms. `feedback_pending` means proposed mistranscribed terms\n * await human resolution; resolving the last one flips it to `completed`.\n */\nexport type TranscriptionReviewStatus =\n | 'open'\n | 'processing'\n | 'feedback_pending'\n | 'completed'\n | 'failed'\n\nexport interface TranscriptTurn {\n speaker: number\n speaker_label: string\n text: string\n start_ms: number\n end_ms: number\n confidence: number\n}\n\nexport interface Transcription {\n id: string\n org_id: string\n source_file_id: string\n audio_file_id: string\n transcript_file_id: string\n status: TranscriptionStatus\n review_status: TranscriptionReviewStatus\n review_started_at?: string\n language: string\n duration_seconds: number\n model: string\n is_diarized: boolean\n turns: TranscriptTurn[]\n speaker_count: number\n /**\n * Index-aligned speaker identities: `speakers[turn.speaker]` is the person\n * behind the turn (provider participant id, name, email, resolved contact).\n * Empty for transcriptions whose source carries no speaker identities.\n */\n speakers?: ContactRef[]\n provider_request_id: string\n conversation_id: string\n error: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Transcribes a storage-service audio file. Asynchronous: the row lands\n * `processing` and the caller polls until `completed`.\n */\nexport interface CreateTranscriptionRequest {\n file_id: string\n language?: string\n model?: string\n is_diarized?: boolean\n}\n\n/**\n * Lands an ALREADY WRITTEN transcript — no provider runs and the row is\n * `completed` when the call returns. This is how a transcript, and through\n * `materialize` a conversation, is authored from text with nothing to upload.\n * `source_file_id` stays empty, which is how a reader tells the two kinds apart.\n *\n * Timings are optional: plain text has none, and materialization then sequences\n * the turns by their position instead of by `start_ms`.\n */\n/**\n * One turn of an authored transcript. Distinct from TranscriptTurn (the read\n * shape, always fully populated) because everything but who-said-what is\n * derived server-side: an unlabelled speaker becomes \"Speaker N\", and text with\n * no timings is sequenced by position at materialization.\n */\nexport interface AuthoredTranscriptTurn {\n /** Speaker index — the same number means the same person. */\n speaker: number\n speaker_label?: string\n text: string\n start_ms?: number\n end_ms?: number\n confidence?: number\n}\n\nexport interface CreateTranscriptionFromTextRequest {\n turns: AuthoredTranscriptTurn[]\n language?: string\n /** Defaults to whether the turns name more than one speaker. */\n is_diarized?: boolean\n}\n\n/**\n * Edits a COMPLETED transcription in place. `turns`, when present, replace the\n * diarized turns wholesale; `speaker_labels` maps diarized speaker indexes\n * (\"0\", \"1\", …) to display labels and is applied across all turns. Editing\n * does NOT retro-update messages of an already-materialized conversation.\n */\nexport interface UpdateTranscriptionRequest {\n turns?: TranscriptTurn[]\n speaker_labels?: Record<string, string>\n language?: string\n}\n\n/** Channel defaults to adhoc; meeting is the only other allowed target. */\nexport interface MaterializeTranscriptionRequest {\n channel?: Channel\n subject?: string\n /** Maps diarized speaker indexes (\"0\", \"1\", …) to display names. */\n speaker_names?: Record<string, string>\n}\n\nexport interface ListTranscriptionsQuery extends PaginationQuery {\n status?: string\n /** List a conversation's transcription artifacts. */\n conversation_id?: string\n /** Narrow to the provider-side transcript identity. */\n provider_request_id?: string\n}\n\nexport type MistranscribedTermStatus = 'auto_replaced' | 'proposed' | 'accepted' | 'rejected'\n\nexport type MistranscriptionSuggestionSource = 'glossary' | 'model'\n\n/**\n * One term the post-transcription review pass judged likely misheard. High-\n * confidence findings are auto-replaced; the rest await accept/reject. An\n * accepted row referencing the glossary term it became (glossary_term_id) is a\n * known \"misheard → term\" mapping future passes replace deterministically.\n */\nexport interface MistranscribedTerm {\n id: string\n org_id: string\n transcription_id: string\n conversation_id?: string\n /** The text as transcribed. */\n term: string\n context_snippet?: string\n /** Indexes into the transcription's turns where the term occurs. */\n turn_indexes: number[]\n suggested_replacement?: string\n suggestion_source?: MistranscriptionSuggestionSource\n glossary_term_id?: string\n /** Confidence (0..1) the term IS mistranscribed. */\n misheard_confidence: number\n /** Confidence (0..1) the suggested replacement fits. */\n replacement_confidence: number\n status: MistranscribedTermStatus\n /** The text actually written into the transcript, once applied. */\n applied_replacement?: string\n resolved_by?: UserRef\n resolved_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/**\n * Accepts a proposed finding: `replacement` overrides the reviewer's\n * suggestion when set; `create_glossary_term` promotes the applied replacement\n * into the org glossary and links the finding to it.\n */\nexport interface AcceptMistranscribedTermRequest {\n replacement?: string\n create_glossary_term?: {\n definition?: string\n priority?: number\n }\n}\n\nexport interface ListMistranscribedTermsQuery extends PaginationQuery {\n status?: MistranscribedTermStatus\n transcription_id?: string\n conversation_id?: string\n}\n\n/**\n * Sends a meeting bot (Ava) into a meeting through an active meeting\n * connection (adhoc-meeting). join_at schedules the bot ahead of time (ISO\n * instant; a scheduled bot joins reliably on time — omit to join now); title\n * seeds the meeting conversation's subject.\n */\nexport interface DispatchMeetingBotRequest {\n connection_id: string\n meeting_url: string\n title?: string\n join_at?: string\n /**\n * BCP-47 spoken-language hint for transcription (e.g. 'en', 'de'). Omit to\n * auto-detect (Deepgram multilingual). Only used when the deployment's\n * transcription provider is deepgram_streaming.\n */\n language?: string\n /**\n * The calendar meeting instance the bot is sent for — `calendar_event_ical_uid`\n * with `start_at` (the instance start, ISO) link the meeting conversation and\n * its bot to the calendar so the event's surface can follow them.\n */\n calendar_event_ical_uid?: string\n start_at?: string\n}\n\n/**\n * Lifecycle of an Ava bot: `scheduled` (sent, not yet in the call) → `joining`\n * → `recording` → `ended` | `failed`, or `removed` (a person withdrew Ava —\n * terminal; a removed meeting is not scheduled again).\n */\nexport type MeetingBotStatus =\n | 'scheduled'\n | 'joining'\n | 'recording'\n | 'ended'\n | 'failed'\n | 'removed'\n\n/**\n * The platform's memory of one Ava bot — \"Ava joins this meeting\", whoever's\n * calendar scheduled her. One bot per meeting instance per org when bot\n * deduplication is on; several rows can share an instance when it is off.\n */\nexport interface MeetingBot {\n id: string\n org_id: string\n /** The connection (calendar / adhoc) that scheduled the bot. */\n connection_id: string\n /** The provider's bot id; the meeting conversation's external id once begun. */\n external_bot_id: string\n /** The provider calendar-event id the bot was scheduled on; absent for adhoc. */\n provider_event_id?: string\n calendar_event_ical_uid?: string\n start_at?: string\n meeting_url?: string\n title?: string\n status: MeetingBotStatus\n /**\n * Platform users among the invitees: they see the bot — and may withdraw\n * Ava from their meeting — without owning the connection that scheduled her.\n */\n invitee_user_ids: string[]\n /** The meeting conversation; absent until the bot starts the meeting. */\n conversation_id?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface ListMeetingBotsQuery extends PaginationQuery {\n /** Meetings starting at/after this ISO instant. */\n start_after?: string\n /** Meetings starting before this ISO instant. */\n start_before?: string\n /** One calendar meeting (pair with the window to name an instance). */\n calendar_event_ical_uid?: string\n status?: MeetingBotStatus\n}\n\n// ── Sending rules ─────────────────────────────────────────────────────────────\n\n/**\n * Discriminates a sending rule: window (WHEN sending is allowed, recipient-\n * local weekday ranges), limit (HOW MUCH one connection may send per rolling\n * period), frequency_cap (HOW OFTEN one contact may be contacted per rolling\n * period).\n */\nexport type SendingRuleType = 'window' | 'limit' | 'frequency_cap' | 'warmup'\n/** Rolling lookback (\"last 24 hours from now\") — never a calendar day. */\nexport type SendingPeriod = 'rolling_24h' | 'rolling_7d' | 'rolling_30d'\n/**\n * ONE kind of act performed through a channel connection — shared by a\n * limit's `action` (what it counts), a channel action's `action_type` (what\n * was performed) and the eligibility check. `message` is the plain send\n * (valid on a limit, never on a channel action row). `profile_lookup` is the\n * silent twin of `profile_visit`: one provider read the platform performs to\n * learn a person's full identity (LinkedIn profile id + public identifier),\n * ledgered and limited like any other act.\n */\nexport type ChannelActionType =\n | 'message'\n | 'invitation'\n | 'inmail'\n | 'profile_visit'\n | 'profile_lookup'\nexport type Weekday =\n | 'monday'\n | 'tuesday'\n | 'wednesday'\n | 'thursday'\n | 'friday'\n | 'saturday'\n | 'sunday'\n\n/** One open range on one weekday, \"HH:MM\" wall-clock, from < until, same day. */\nexport interface WindowDay {\n day: Weekday\n from: string\n until: string\n}\nexport interface WindowRuleConfig {\n days: WindowDay[]\n /** IANA zone used for contacts without a timezone. */\n fallback_timezone: string\n}\nexport interface LimitRuleConfig {\n action: ChannelActionType\n max_count: number\n period: SendingPeriod\n /** Minimum spacing between consecutive sends; 0/absent = none. */\n min_gap_seconds?: number\n}\nexport interface FrequencyCapRuleConfig {\n max_count: number\n period: SendingPeriod\n}\n/**\n * A limit that RAMPS: `start_count` acts of `action` per rolling `period` on\n * the day the warmup started, growing by `daily_increase` (a count, or a\n * percent of the previous day's allowance when `is_increase_percent`) every\n * UTC calendar day until `max_count`, after which it behaves as a plain\n * limit. `started_at` may be omitted on create — the server stamps now.\n */\nexport interface WarmupRuleConfig {\n action: ChannelActionType\n start_count: number\n daily_increase: number\n is_increase_percent?: boolean\n max_count: number\n period: SendingPeriod\n started_at: string\n}\nexport type SendingRuleConfig =\n | WindowRuleConfig\n | LimitRuleConfig\n | FrequencyCapRuleConfig\n | WarmupRuleConfig\n\n/**\n * One outbound send constraint, defined once and LINKED to any number of\n * connections and/or channels (both empty = org-wide). Per rule type the most\n * specific tier wins at send time: names the connection > names the channel >\n * org-wide. Replies skip the rule when `is_reply_exempt`.\n */\n// ── Conversation briefs ──────────────────────────────────────────────────────────────\n\n/**\n * Lifecycle of a conversation brief: `prepared` (open — editable, waiting for its\n * call), `used` (attached to a call conversation; terminal), `discarded`\n * (declined without a call; terminal).\n */\nexport type ConversationBriefStatus = 'prepared' | 'used' | 'discarded'\n\n/**\n * Guidance prepared AHEAD of a conversation — \"talk to these people about\n * this\" — the conversation sibling of a draft message. Binding to a\n * conversation is always explicit: the softphone carries the brief id into\n * the call (attached at call start), or `attach` names the conversation.\n * Nothing matches by contact or number, and any number of briefs may be open\n * for the same people at once. Records that want a brief (an activity) store\n * its id; every UI surface renders from the id.\n */\nexport interface ConversationBrief {\n id: string\n org_id: string\n /** Human label (\"Renewal call with Dana\"); may be empty. */\n subject: string\n /** The people the conversation is with (deduplicated, sorted; may be empty — a phone brief has ≥ 1). */\n contact_ids: string[]\n /** How the conversation should happen (phone opens the softphone); absent = unspecified. */\n channel?: Channel\n /** ConversationType key the conversation is meant to be; stamped on attach. */\n type_key?: string\n /**\n * The calendar event (one person's copy) the brief prepares; attached to\n * the meeting's conversation when the meeting bot starts. Absent = no meeting.\n */\n calendar_event_id?: string\n /** The brief is every invitee's, not only the event owner's. */\n is_shared_with_participants: boolean\n /** The meeting instance the event belongs to (resolved from the event; read-only). */\n calendar_event_ical_uid?: string\n calendar_event_start_at?: string\n /**\n * The platform users the brief is for (the event owner; every resolved\n * invitee when shared) — they read it next to its creator. Read-only.\n */\n invitee_user_ids: string[]\n /** The conversation the brief was used on; absent until used. A conversation may carry several briefs. */\n conversation_id?: string\n status: ConversationBriefStatus\n /** Guidance text (markdown allowed). */\n content: string\n used_at?: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateConversationBriefRequest {\n subject?: string\n /** The people the conversation is with (may be empty). */\n contact_ids?: string[]\n /** Must be a known channel when set. */\n channel?: Channel\n /** Must name an existing conversation type when set. */\n type_key?: string\n content: string\n /** The caller's view of a calendar event the brief prepares (the caller must be able to read it). */\n calendar_event_id?: string\n /** Every invitee's brief instead of only the event owner's (requires calendar_event_id). */\n is_shared_with_participants?: boolean\n}\n\n/** PATCH semantics — absent fields keep their value. Only open briefs. */\nexport interface UpdateConversationBriefRequest {\n subject?: string\n /** Replaces the set wholesale. */\n contact_ids?: string[]\n /** Empty string clears the channel. */\n channel?: Channel | ''\n content?: string\n type_key?: string\n /** Re-ties the brief; empty string unties it (and drops the sharing). */\n calendar_event_id?: string\n is_shared_with_participants?: boolean\n}\n\n/** Binds an open brief to a conversation explicitly. */\nexport interface AttachConversationBriefRequest {\n conversation_id: string\n}\n\nexport interface ListConversationBriefsQuery extends PaginationQuery {\n /** Briefs naming this person. */\n contact_id?: string\n conversation_id?: string\n /** The briefs for one person's copy of a calendar event. */\n calendar_event_id?: string\n /** Every visible brief of a meeting, across invitees' copies (+ start to pin one instance). */\n calendar_event_ical_uid?: string\n calendar_event_start_at?: string\n /** The briefs of the meetings starting in [after, before) — a calendar's visible range. */\n calendar_event_start_after?: string\n calendar_event_start_before?: string\n channel?: Channel\n type_key?: string\n status?: ConversationBriefStatus\n sort_by?: string\n sort?: 'asc' | 'desc'\n}\n\n/** Which emails a default signature is picked for. */\nexport type EmailSignatureAppliesTo = 'all' | 'new' | 'reply'\n\n/** A send's, draft's or draft edit's pick of a signature: the default, none, or a signature id. */\nexport type SignatureChoice = 'default' | 'none' | (string & {})\n\n/**\n * The block an email send adds below what the person wrote and above the\n * quote. Belongs to one person (`owned_by`) or, without one, to the\n * organisation; `connection_id` ties it to one mailbox. Among the defaults a\n * send picks the sending mailbox's, then the sender's own, then the\n * organisation's.\n */\nexport interface EmailSignature {\n id: string\n org_id: string\n name: string\n /** Sanitized like every stored email html. */\n html: string\n /** The plain-text part; derived from `html` unless `is_text_custom`. */\n text: string\n is_text_custom: boolean\n /** The person it belongs to; absent for the organisation. */\n owned_by?: UserRef\n /** The mailbox it is tied to; absent for every mailbox. */\n connection_id?: string\n is_default: boolean\n applies_to: EmailSignatureAppliesTo\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** A signature as one email carries it. */\nexport interface MessageSignature {\n id: string\n name: string\n html: string\n text: string\n}\n\n/** A send's, draft's or draft edit's pick of an unsubscribe link: none, or a link of the email's own. */\nexport type UnsubscribeChoice = 'none' | 'link'\n\n/**\n * What `{{ unsubscribe_url }}` renders to before a message exists. A send with\n * `unsubscribe: 'link'` swaps every occurrence for the recipient's own link;\n * an email sent without one (a test send, a preview) gets the address of a\n * page that says so.\n */\nexport const UNSUBSCRIBE_URL_PLACEHOLDER = 'https://unsubscribe.invalid/link'\n\n/** The layout an email went out in, as stored on the message: a snapshot, since the layout itself may change or go. */\nexport interface MessageLayout {\n id: string\n key?: string\n name: string\n /** The frame, with `{{ content }}` where the body goes. */\n html: string\n /** The frame of the plain part; absent leaves the text as written. */\n text?: string\n}\n\nexport interface CreateEmailSignatureRequest {\n name: string\n /** `html` or `text` is required. */\n html?: string\n /** Left empty, it is derived from `html`. */\n text?: string\n /** Empty or omitted makes it the organisation's. */\n owned_by_id?: string\n /** Empty or omitted makes it apply to every mailbox. */\n connection_id?: string\n /** Defaults to false. Becoming the default takes the flag off the others of the same owner, mailbox and kind. */\n is_default?: boolean\n /** Defaults to `all`. */\n applies_to?: EmailSignatureAppliesTo\n}\n\n/** Omitted fields keep what is stored. `text` sent empty goes back to being derived. */\nexport type UpdateEmailSignatureRequest = Partial<CreateEmailSignatureRequest>\n\nexport interface ListEmailSignaturesQuery extends PaginationQuery {\n owned_by_id?: string\n /** true: the organisation's own; false: everyone's personal ones. */\n is_organisation?: boolean\n connection_id?: string\n is_default?: boolean\n}\n\nexport interface ResolveEmailSignatureQuery {\n connection_id?: string\n /** Whose personal default counts; the caller when omitted. */\n owned_by_id?: string\n is_reply?: boolean\n}\n\n/**\n * What a message template holds: a whole message, a piece of a body, or a\n * layout. A layout is the frame of a designed email: html (and optionally\n * text) with `{{ content }}` where the body goes. A send names it with\n * `layout`; it is never sent on its own.\n */\nexport type MessageTemplateKind = 'message' | 'snippet' | 'layout'\n\n/**\n * A reusable message, or a reusable piece of one. `subject`, `html` and `text`\n * are Liquid templates: `{{ contact.first_name }}` is filled in from the\n * variables a render or a send passes.\n *\n * A template is copied into what uses it (a sequence step, a reply), never\n * referenced from it. A send that names one renders it at that moment.\n */\nexport interface MessageTemplate {\n id: string\n org_id: string\n /** The name modules and workflows use; absent for a template nothing refers to. */\n key?: string\n name: string\n description?: string\n kind: MessageTemplateKind\n /** The one channel it is written for; absent for any. */\n channel?: Channel\n /** The language it is written in, such as `de` or `en-GB`. */\n language?: string\n /** Why messages from it are sent; a send of it that names no purpose takes this one. */\n purpose?: Purpose\n tags: string[]\n /** A snippet has none. */\n subject?: string\n /** Sanitized like every stored email html, its Liquid kept as written. Empty for a text-only template. */\n html: string\n /** The plain body; derived from `html` unless `is_text_custom`. */\n text: string\n is_text_custom: boolean\n /** The person it belongs to; absent for the organisation. */\n owned_by?: UserRef\n /** The module that deployed it; absent for one made by hand. */\n module_slug?: string\n is_archived: boolean\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateMessageTemplateRequest {\n key?: string\n name: string\n description?: string\n /** Defaults to `message`. */\n kind?: MessageTemplateKind\n /** Empty or omitted writes it for any channel. */\n channel?: Channel | ''\n language?: string\n /** Empty or omitted leaves it unsaid. */\n purpose?: Purpose | ''\n tags?: string[]\n subject?: string\n /** `html` or `text` is required. */\n html?: string\n /** Left empty, it is derived from `html`. */\n text?: string\n /** Empty or omitted makes it the organisation's. */\n owned_by_id?: string\n module_slug?: string\n is_archived?: boolean\n}\n\n/**\n * Omitted fields keep what is stored. `text` sent empty goes back to being\n * derived; `key` sent empty takes the name away.\n */\nexport type UpdateMessageTemplateRequest = Partial<\n Omit<CreateMessageTemplateRequest, 'module_slug'>\n>\n\nexport interface ListMessageTemplatesQuery extends PaginationQuery {\n kind?: MessageTemplateKind\n /** Also finds templates written for any channel. */\n channel?: Channel\n language?: string\n module_slug?: string\n tag?: string\n /** Matches the name, the key and the description. */\n search?: string\n owned_by_id?: string\n /** true: the organisation's own; false: everyone's personal ones. */\n is_organisation?: boolean\n /** Archived templates are left out unless this is true. */\n is_archived?: boolean\n}\n\n/**\n * Fills in a template's variables. `template` names a stored template by id\n * or key; without it `subject`, `html` and `text` are the template itself.\n */\nexport interface RenderMessageTemplateRequest {\n template?: string\n subject?: string\n html?: string\n text?: string\n /** The names the Liquid reads: `{{ contact.first_name }}` reads `variables.contact.first_name`. */\n variables?: Record<string, unknown>\n /** Picked as a send picks it, for `connection_id`, `owned_by_id` and `is_reply`. */\n signature?: SignatureChoice\n connection_id?: string\n owned_by_id?: string\n is_reply?: boolean\n /** The layout the email would be sent in: its id or key, `none` or omitted for none. The answer carries it beside the body, which comes back without it. */\n layout?: string\n}\n\n/** What a send of the template would store, and the signature that would go below it. */\nexport interface RenderedMessageTemplate {\n subject: string\n /** Sanitized, with the editor's look. Empty for a text-only template. */\n html: string\n text: string\n signature: MessageSignature | null\n /** The frame the email would go out in, `{{ content }}` marking where the body and the signature go. Null or absent without one. */\n layout?: MessageLayout | null\n}\n\nexport interface SendingRule {\n id: string\n org_id: string\n name: string\n connection_ids: string[]\n channels: Channel[]\n rule_type: SendingRuleType\n rule_config?: SendingRuleConfig\n is_enabled: boolean\n is_reply_exempt: boolean\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateSendingRuleRequest {\n name?: string\n connection_ids?: string[]\n channels?: Channel[]\n rule_type: SendingRuleType\n rule_config: Record<string, unknown>\n /** Defaults to true. */\n is_enabled?: boolean\n /** Defaults per type: window + frequency_cap true, limit false. */\n is_reply_exempt?: boolean\n}\n\nexport interface UpdateSendingRuleRequest {\n name?: string\n /** Replaces the stored links wholesale when present. */\n connection_ids?: string[]\n channels?: Channel[]\n /** rule_type and rule_config must be sent together. */\n rule_type?: SendingRuleType\n rule_config?: Record<string, unknown>\n is_enabled?: boolean\n is_reply_exempt?: boolean\n}\n\nexport interface ListSendingRulesQuery extends PaginationQuery {\n /** Rules LINKED to this connection. */\n connection_id?: string\n channel?: Channel\n rule_type?: SendingRuleType\n is_enabled?: boolean\n}\n\n/** A recommended limit bundle for one class of sender account (static catalog). */\nexport interface SendingLimitPreset {\n key: string\n name: string\n description: string\n connector_keys: ConnectorKey[]\n is_recommended: boolean\n rules: (\n | { rule_type: 'limit'; rule_config: LimitRuleConfig }\n | { rule_type: 'warmup'; rule_config: WarmupRuleConfig }\n )[]\n}\n\nexport interface ListSendingLimitPresetsQuery {\n connector_key?: ConnectorKey\n}\n\nexport interface ApplySendingLimitPresetRequest {\n connection_ids: string[]\n preset_key: string\n}\n\n/** Dry-run twin of SendMessageRequest: addressing only, nothing minted. */\nexport interface SendEligibilityRequest {\n conversation_id?: string\n reply_to_message_id?: string\n connection_id?: string\n to?: SendRecipient[]\n cc?: SendRecipient[]\n bcc?: SendRecipient[]\n /**\n * Widens the check to a channel action (invitation, profile_visit, inmail):\n * originate mode only, the first `to` recipient is the target. Absent =\n * message.\n */\n action_type?: ChannelActionType\n /** The purpose the send would have; consent is checked for it. */\n purpose?: Purpose\n}\n\n/**\n * \"May this send go out now?\" — `reason` is the error code a real send would\n * fail with (sending_window_closed | sending_limit_reached |\n * frequency_cap_reached | contact_blocked | contact_opted_out);\n * `earliest_allowed_at` is set for the temporal three.\n */\nexport interface SendEligibility {\n is_allowed: boolean\n reason?: string\n rule_id?: string\n rule_type?: SendingRuleType\n earliest_allowed_at?: string\n contact_id?: string\n contact_address_id?: string\n}\n\n// ── Connector catalog ─────────────────────────────────────────────────────────\n\n/**\n * One connector WIRED in this deployment (registry membership decides\n * availability). `install_modes` lists the install variants the environment\n * supports for a direct-install connector (a sending platform's own_account /\n * managed); empty for OAuth / install-free connectors.\n */\n/**\n * ONE sending identity of a domain-authenticated email connection: an email\n * contact address on the connection's sender domain. A personal sender belongs\n * to a colleague's contact (`platform_user` set); a shared mailbox (sales@) to\n * a role contact without one. Computed from the contact directory on read.\n */\nexport interface EmailSender {\n contact_address_id: string\n contact_id: string\n from_email: string\n from_name: string\n platform_user?: UserRef\n /** The connection's fallback sender when neither the thread nor the user pins one. */\n is_default: boolean\n}\n\n/** Pins a connection's default sender (an address on its sender domain). */\nexport interface SetDefaultSenderRequest {\n contact_address_id: string\n}\n\nexport interface ConnectorCatalogEntry {\n key: ConnectorKey\n channel: Channel\n provider: ConnectorProvider\n install_modes: string[]\n}\n\n// ── Email deliverability (sending-platform connections) ──────────────────────\n\n/** One of a sending platform's suppression lists. */\nexport type EmailSuppressionKind =\n | 'bounces'\n | 'blocks'\n | 'spam_reports'\n | 'invalid_emails'\n | 'unsubscribes'\n\n/**\n * Ledger rollup over the last `days` days: DISTINCT messages per event type\n * (machine opens excluded). Rates are fractions (0–1): delivery / bounce /\n * hard-bounce over sent, open / click / spam / unsubscribe over delivered.\n */\nexport interface EmailHealthWindow {\n days: number\n sent: number\n delivered: number\n deferred: number\n bounced: number\n hard_bounced: number\n dropped: number\n opened: number\n clicked: number\n spam_reported: number\n unsubscribed: number\n delivery_rate: number\n bounce_rate: number\n hard_bounce_rate: number\n open_rate: number\n click_rate: number\n spam_rate: number\n unsubscribe_rate: number\n}\n\n/** The provider's composite sender-quality score (1–5, computed daily). */\nexport interface EmailEngagementQuality {\n date: string\n score: number\n bounce_classification: number\n bounce_rate: number\n engagement_recency: number\n open_rate: number\n spam_rate: number\n}\n\n/** The provider's own counters for this connection's traffic (its category). */\nexport interface EmailProviderStats {\n days: number\n requests: number\n processed: number\n delivered: number\n deferred: number\n bounces: number\n blocks: number\n bounce_drops: number\n invalid_emails: number\n opens: number\n unique_opens: number\n clicks: number\n unique_clicks: number\n spam_reports: number\n spam_report_drops: number\n unsubscribes: number\n unsubscribe_drops: number\n}\n\nexport interface EmailSuppressionCounts {\n bounces: number\n blocks: number\n spam_reports: number\n invalid_emails: number\n unsubscribes: number\n /** A list hit the page cap — the count is a floor. */\n is_approximate?: boolean\n}\n\nexport interface EmailDnsRecord {\n host: string\n type: string\n data: string\n is_valid: boolean\n reason?: string\n}\n\nexport interface EmailDomainStatus {\n domain: string\n is_valid: boolean\n dns: EmailDnsRecord[]\n}\n\nexport interface EmailSenderStatus {\n from_email: string\n /** authenticated_domain | single_sender */\n mode: string\n is_verified: boolean\n}\n\n/** One dedicated IP of the account with its warmup state. */\nexport interface EmailIp {\n ip: string\n is_warming_up: boolean\n warmup_started_at?: string\n pools: string[]\n}\n\n/**\n * The provider's account-level snapshot (refreshed daily by the connector's\n * sweep, or on demand with `refresh`). Every section is optional — a plan\n * without the feature or a failed pull leaves it absent and adds a warning.\n */\nexport interface EmailProviderHealth {\n engagement_quality?: EmailEngagementQuality\n stats?: EmailProviderStats\n suppressions?: EmailSuppressionCounts\n domain?: EmailDomainStatus\n sender?: EmailSenderStatus\n ips: EmailIp[]\n warnings?: string[]\n refreshed_at: string\n}\n\n/** GET /connections/:id/health — ledger windows + the provider snapshot. */\nexport interface EmailHealth {\n connection_id: string\n windows: EmailHealthWindow[]\n provider?: EmailProviderHealth\n}\n\nexport interface GetConnectionHealthQuery {\n /** Force a live provider pull (slow — several provider calls). */\n refresh?: boolean\n}\n\n/** One address on a provider suppression list. */\nexport interface EmailSuppression {\n kind: EmailSuppressionKind\n email: string\n reason?: string\n status?: string\n created_at: string\n}\n\n// ── Channel events ────────────────────────────────────────────────────────────\n\n/**\n * ONE provider-observed occurrence about an outbound message on a sending\n * platform: the delivery lifecycle (processed → delivered | deferred |\n * bounced | dropped) and engagement (opened, clicked, spam_reported,\n * unsubscribed, resubscribed). Provider vocabularies map onto these inside\n * the connector.\n */\nexport type ChannelEventType =\n | 'processed'\n | 'delivered'\n | 'deferred'\n | 'bounced'\n | 'dropped'\n | 'opened'\n | 'clicked'\n | 'spam_reported'\n | 'unsubscribed'\n | 'resubscribed'\n\n/** hard = the address is gone (suppressed); soft = this attempt was refused. */\nexport type BounceKind = 'hard' | 'soft'\n\n/** The provider's category of a bounce / block. */\nexport type BounceClassification =\n | 'invalid_address'\n | 'technical_failure'\n | 'content'\n | 'reputation'\n | 'volume'\n | 'mailbox_unavailable'\n | 'unclassified'\n\n/**\n * One row of the channel_event ledger — the sibling of channel actions (acts\n * WE perform) and reactions (edges): something the provider or the recipient\n * did that we record. Append-only, deduped on the provider's event id.\n * Message.delivery and provider-sourced contact permission events derive\n * from it.\n */\nexport interface ChannelEvent {\n id: string\n org_id: string\n connection_id: string\n connector_key: ConnectorKey\n channel: Channel\n /** The message the event is about; absent when unresolvable. */\n message_id?: string\n conversation_id?: string\n contact_id?: string\n contact_address_id?: string\n /** The provider's recipient (lowercased email). */\n recipient_address: string\n event_type: ChannelEventType\n external_event_id: string\n external_message_id?: string\n occurred_at: string\n /** Bounce / deferral / drop text (the SMTP response, the drop reason). */\n reason?: string\n response?: string\n bounce_kind?: BounceKind\n bounce_classification?: BounceClassification\n /** The clicked link (clicked events). */\n url?: string\n /** An opened event a mail client's privacy proxy generated, not the person. */\n is_machine_open?: boolean\n metadata: Record<string, unknown>\n created_at: string\n created_by: UserRef\n}\n\nexport interface ListChannelEventsQuery extends PaginationQuery {\n connection_id?: string\n message_id?: string\n conversation_id?: string\n contact_id?: string\n event_type?: ChannelEventType\n /** ISO instants bounding occurred_at (from inclusive, until exclusive). */\n from?: string\n until?: string\n sort_by?: string\n sort?: 'asc' | 'desc'\n}\n\n// ── Channel actions ───────────────────────────────────────────────────────────\n\n/**\n * Lifecycle of a channel action. Execution: pending → performed | failed.\n * Outcome (invitations): performed → accepted | declined | withdrawn |\n * expired; an inbound received invitation starts pending and ends\n * accepted | declined | expired.\n */\nexport type ChannelActionStatus =\n | 'pending'\n | 'performed'\n | 'failed'\n | 'accepted'\n | 'declined'\n | 'withdrawn'\n | 'expired'\n/** Our answer to an inbound channel action (a received invitation). */\nexport type ChannelActionResponse = 'accept' | 'decline'\n/** What an action type acts on: a person on the channel, or an external object. */\nexport type ChannelActionTargetKind = 'contact-address' | 'external'\n\n/**\n * One action type a connector performs, projected onto `connection.actions`.\n */\nexport interface ChannelActionCapability {\n action_type: ChannelActionType\n target_kind: ChannelActionTargetKind\n /** The act can be withdrawn after performing (an invitation). */\n is_cancelable: boolean\n /** An inbound act of this type can be answered (accept / decline). */\n is_respondable: boolean\n /** Performing also sends a message that lands as a Message + Conversation (InMail). */\n is_message_minting: boolean\n /** Bound of the free-text note the act carries (LinkedIn invitation: 300). */\n max_note_length?: number\n}\n\nexport interface InvitationParams {\n note?: string\n email?: string\n}\nexport type ProfileVisitParams = Record<string, never>\nexport interface InmailParams {\n subject?: string\n content: ContentBlock[]\n}\nexport type ChannelActionParams = InvitationParams | ProfileVisitParams | InmailParams\n\n/**\n * One act performed through a channel connection that is neither a message\n * nor a reaction — a LinkedIn invitation, a profile visit, an InMail (which\n * ALSO mints a message, see message_id). A LEDGER row: appended, transitioned\n * along its lifecycle, never toggled. `direction` outbound = we acted;\n * inbound = someone acted on us (a received invitation you may answer).\n * `created_by` is the performer on outbound rows (user or agent), the system\n * on ingested inbound rows; `updated_by` who accepted / declined / withdrew.\n */\nexport interface ChannelAction {\n id: string\n org_id: string\n connection_id: string\n connector_key: ConnectorKey\n channel: Channel\n action_type: ChannelActionType\n direction: MessageDirection\n status: ChannelActionStatus\n contact_id?: string\n contact_address_id?: string\n /** The provider-side identity acted on (a LinkedIn member id). */\n target_external_id: string\n contact: ContactRef\n /** An InMail's minted message; an invitation's note-chat once accepted. */\n message_id?: string\n conversation_id?: string\n params?: ChannelActionParams\n /** The provider handle (Unipile invitation id) — cancel / respond key. */\n external_action_id?: string\n error?: string\n occurred_at: string\n resolved_at?: string\n /** Provider enrichment: invitation usage %, network_distance, … */\n metadata: Record<string, unknown>\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\n/** Performs one act. `target` is the person acted on (kind contact-address + the connector-side external id). */\nexport interface PerformChannelActionRequest {\n connection_id: string\n action_type: ChannelActionType\n target: SendRecipient\n /** Per-type input: invitation {note?, email?}; profile_visit {}; inmail {subject?, content}. */\n params?: Record<string, unknown>\n}\n\nexport interface RespondChannelActionRequest {\n response: ChannelActionResponse\n}\n\nexport interface ListChannelActionsQuery extends PaginationQuery {\n channel?: Channel\n connection_id?: string\n action_type?: ChannelActionType\n direction?: MessageDirection\n status?: ChannelActionStatus\n contact_id?: string\n}\n\n/**\n * What a PERSON recorded about a conversation — during a call, after a\n * meeting, while reading a thread. An append log, author-stamped, never\n * merged. Notes feed the summary (what the human found important) and the\n * summary-basis tag evaluations. As visible as the conversation; only the\n * author edits or deletes.\n */\nexport interface ConversationNote {\n id: string\n org_id: string\n conversation_id: string\n /** Markdown allowed. */\n content: string\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateConversationNoteRequest {\n content: string\n}\n\nexport interface UpdateConversationNoteRequest {\n content: string\n}\n\nexport interface ListConversationNotesQuery extends PaginationQuery {\n sort_by?: string\n sort?: 'asc' | 'desc'\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n AcceptMistranscribedTermRequest,\n AgentListener,\n ApplySendingLimitPresetRequest,\n AttachContactAddressRequest,\n AttachConversationBriefRequest,\n BlockContactRequest,\n CallTokenResponse,\n ChannelAction,\n ChannelEvent,\n Connection,\n ConnectorCatalogEntry,\n ConsentRequest,\n Contact,\n ContactAddress,\n ContactErasureRequest,\n ContactGroup,\n ContactMergeProposal,\n ContactRecordLink,\n Conversation,\n ConversationBrief,\n ConversationFilter,\n ConversationFilterEvent,\n ConversationNote,\n ConversationObjective,\n ConversationObjectiveDefinition,\n ConversationObjectiveProgress,\n ConversationOutcomeOption,\n ConversationTag,\n ConversationTagDefinition,\n ConversationTagEvaluation,\n ConversationTagSet,\n ConversationType,\n CountConversationObjectivesQuery,\n CountConversationObjectivesResponse,\n CountConversationTagsQuery,\n CountConversationTagsResponse,\n CreateAgentListenerRequest,\n CreateConnectionRequest,\n CreateContactGroupRequest,\n CreateContactRecordLinkRequest,\n CreateContactRequest,\n CreateConversationBriefRequest,\n CreateConversationFilterRequest,\n CreateConversationNoteRequest,\n CreateConversationObjectiveDefinitionRequest,\n CreateConversationTagDefinitionRequest,\n CreateConversationTagRequest,\n CreateConversationTagSetRequest,\n CreateConversationTypeRequest,\n CreateEmailSignatureRequest,\n CreateGlossaryTermRequest,\n CreateMessageTemplateRequest,\n CreateSendingRuleRequest,\n CreateToneProfileSetupRequest,\n CreateTranscriptionFromTextRequest,\n CreateTranscriptionRequest,\n DeleteConnectionQuery,\n DispatchMeetingBotRequest,\n EmailDomainStatus,\n EmailHealth,\n EmailSender,\n EmailSignature,\n EmailSuppression,\n EmailSuppressionKind,\n EvaluateConversationTagsRequest,\n GetConnectionHealthQuery,\n GetManyConversationObjectiveDefinitionsQuery,\n GetManyConversationObjectivesQuery,\n GlossaryTerm,\n InstallConnectionRequest,\n InstallConnectionResponse,\n ListAgentListenersQuery,\n ListChannelActionsQuery,\n ListChannelEventsQuery,\n ListConnectionsQuery,\n ListContactAddressesQuery,\n ListContactGroupsQuery,\n ListContactMergeProposalsQuery,\n ListContactRecordLinksQuery,\n ListContactsQuery,\n ListConversationBriefsQuery,\n ListConversationFilterEventsQuery,\n ListConversationFiltersQuery,\n ListConversationNotesQuery,\n ListConversationsQuery,\n ListConversationTagDefinitionsQuery,\n ListConversationTagEvaluationsQuery,\n ListConversationTagSetsQuery,\n ListConversationTagsQuery,\n ListConversationTypesQuery,\n ListEmailSignaturesQuery,\n ListGlossaryTermsQuery,\n ListMeetingBotsQuery,\n ListMessagesQuery,\n ListMessageTemplatesQuery,\n ListMistranscribedTermsQuery,\n ListPermissionEventsResponse,\n ListReactionsResponse,\n ListResponse,\n ListRoomsQuery,\n ListSendingLimitPresetsQuery,\n ListSendingRulesQuery,\n ListToneProfileSetupsQuery,\n ListToneProfilesQuery,\n ListTranscriptionsQuery,\n MaterializeTranscriptionRequest,\n MeetingBot,\n MergeContactsRequest,\n Message,\n MessageDraftVersions,\n MessageSignature,\n MessageTemplate,\n MintCallTokenRequest,\n MistranscribedTerm,\n PerformChannelActionRequest,\n PhoneNumber,\n Reaction,\n RecordPermissionEventRequest,\n RenderedMessageTemplate,\n RenderMessageTemplateRequest,\n ResolveEmailSignatureQuery,\n ResolveToneProfileQuery,\n RespondChannelActionRequest,\n Room,\n SendEligibility,\n SendEligibilityRequest,\n SendingLimitPreset,\n SendingRule,\n SendMessageRequest,\n SetCallRecordingRequest,\n SetDefaultSenderRequest,\n SyncConnectionRequest,\n ToneProfile,\n ToneProfileSetup,\n Transcription,\n UnreadCounts,\n UnreadCountsQuery,\n UpdateAgentListenerRequest,\n UpdateConnectionRequest,\n UpdateContactGroupRequest,\n UpdateContactRequest,\n UpdateConversationBriefRequest,\n UpdateConversationFilterRequest,\n UpdateConversationNoteRequest,\n UpdateConversationObjectiveDefinitionRequest,\n UpdateConversationRequest,\n UpdateConversationTagDefinitionRequest,\n UpdateConversationTagRequest,\n UpdateConversationTagSetRequest,\n UpdateConversationTypeRequest,\n UpdateDraftRequest,\n UpdateEmailSignatureRequest,\n UpdateGlossaryTermRequest,\n UpdateMessageTemplateRequest,\n UpdatePhoneNumberRequest,\n UpdateSendingRuleRequest,\n UpdateTranscriptionRequest,\n UpsertToneProfileRequest,\n} from './types.js'\nimport { type VoiceService, VoiceServiceImpl } from './voice.js'\n\nconst CONVERSATION_BASE_PATH = '/conversations/v1'\n\n/**\n * Facade for conversation-service: connections (channel-connector instances),\n * conversations + messages (THE platform Message), and agent listeners.\n *\n * ```ts\n * const conversation = new ConversationClient(client)\n * const { authorization_url } = await conversation.connections.install(id)\n * const inbox = await conversation.conversations.list({ channel: 'slack' })\n * ```\n */\nexport class ConversationClient {\n readonly connections: ConnectionService\n readonly conversations: ConversationService\n /** The person-level identity layer: contacts, addresses, merges, permissions. */\n readonly contacts: ContactService\n readonly messages: MessageService\n readonly agentListeners: AgentListenerService\n /** Ingest-time filter rules (drop-with-audit) + their event trail. */\n readonly conversationFilters: ConversationFilterService\n /** Outbound send constraints: windows, connection limits, frequency caps + presets. */\n readonly sendingRules: SendingRuleService\n readonly emailSignatures: EmailSignatureService\n /** Reusable messages and snippets, and rendering one for a recipient. */\n readonly messageTemplates: MessageTemplateService\n /**\n * Channel actions: acts performed through a connection that are neither a\n * message nor a reaction — LinkedIn invitations, profile visits, InMail.\n */\n readonly channelActions: ChannelActionService\n readonly channelEvents: ChannelEventService\n /** Per-org glossary: custom vocabulary that boosts transcription accuracy. */\n readonly glossaryTerms: GlossaryTermService\n /** Conversation taxonomy: the types the pre-summary classifier assigns. */\n readonly conversationTypes: ConversationTypeService\n /** Conversation intelligence: WHAT to look for — typed questions asked of conversations. */\n readonly conversationTagDefinitions: ConversationTagDefinitionService\n /** Conversation intelligence: WHERE and WHEN definitions are evaluated. */\n readonly conversationTagSets: ConversationTagSetService\n /** Conversation intelligence: the observations produced + their evaluation history. */\n readonly conversationTags: ConversationTagService\n /** Conversation objectives: WHAT a conversation should achieve (config, keyed, module-deployable). */\n readonly conversationObjectiveDefinitions: ConversationObjectiveDefinitionService\n /** Conversation objectives: the org-wide ledger of standings + grouped counts (read-only). */\n readonly conversationObjectives: ConversationObjectiveService\n /** Generic audience taxonomy; membership lives on the contact. */\n readonly contactGroups: ContactGroupService\n /** Tone-of-voice synthesis: per-user setups + the generated profiles. */\n readonly toneProfiles: ToneProfileService\n readonly transcriptions: TranscriptionService\n /** Review-pass findings: likely misheard terms awaiting accept/reject. */\n readonly mistranscribedTerms: MistranscribedTermService\n /** Meeting bots (Ava): dispatch into a meeting URL, summaries. */\n readonly meetings: MeetingService\n /** Ava's bots as remembered by the platform: list them, withdraw her from a meeting. */\n readonly meetingBots: MeetingBotService\n /** Realtime speech-to-text (dictation) — moved here from agent-service. */\n readonly voice: VoiceService\n readonly calls: CallService\n /** Conversation briefs: guidance prepared ahead of a conversation (call, meeting) with a contact. */\n readonly conversationBriefs: ConversationBriefService\n /** Conversation notes: what a person recorded about a conversation (append log, author-stamped). */\n readonly conversationNotes: ConversationNoteService\n\n constructor(client: ProteosClient) {\n this.connections = new ConnectionServiceImpl(client)\n this.conversations = new ConversationServiceImpl(client)\n this.contacts = new ContactServiceImpl(client)\n this.messages = new MessageServiceImpl(client)\n this.agentListeners = new AgentListenerServiceImpl(client)\n this.conversationFilters = new ConversationFilterServiceImpl(client)\n this.sendingRules = new SendingRuleServiceImpl(client)\n this.emailSignatures = new EmailSignatureServiceImpl(client)\n this.messageTemplates = new MessageTemplateServiceImpl(client)\n this.channelActions = new ChannelActionServiceImpl(client)\n this.channelEvents = new ChannelEventServiceImpl(client)\n this.glossaryTerms = new GlossaryTermServiceImpl(client)\n this.conversationTypes = new ConversationTypeServiceImpl(client)\n this.conversationTagDefinitions = new ConversationTagDefinitionServiceImpl(client)\n this.conversationTagSets = new ConversationTagSetServiceImpl(client)\n this.conversationTags = new ConversationTagServiceImpl(client)\n this.conversationObjectiveDefinitions = new ConversationObjectiveDefinitionServiceImpl(client)\n this.conversationObjectives = new ConversationObjectiveServiceImpl(client)\n this.contactGroups = new ContactGroupServiceImpl(client)\n this.toneProfiles = new ToneProfileServiceImpl(client)\n this.transcriptions = new TranscriptionServiceImpl(client)\n this.mistranscribedTerms = new MistranscribedTermServiceImpl(client)\n this.meetings = new MeetingServiceImpl(client)\n this.meetingBots = new MeetingBotServiceImpl(client)\n this.voice = new VoiceServiceImpl(client)\n this.calls = new CallServiceImpl(client)\n this.conversationBriefs = new ConversationBriefServiceImpl(client)\n this.conversationNotes = new ConversationNoteServiceImpl(client)\n }\n}\n\n/** Conversation notes — what a person recorded about a conversation. */\nexport interface ConversationNoteService {\n /** A conversation's notes, oldest first by default. */\n list(\n conversationId: string,\n query?: ListConversationNotesQuery,\n ): Promise<ListResponse<ConversationNote>>\n create(conversationId: string, request: CreateConversationNoteRequest): Promise<ConversationNote>\n /** Author only (403 `conversation_note_not_author`). */\n update(id: string, request: UpdateConversationNoteRequest): Promise<ConversationNote>\n /** Author only (403 `conversation_note_not_author`). */\n delete(id: string): Promise<void>\n}\n\nclass ConversationNoteServiceImpl implements ConversationNoteService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n conversationId: string,\n query: ListConversationNotesQuery = {},\n ): Promise<ListResponse<ConversationNote>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/notes`,\n query,\n )\n }\n\n create(\n conversationId: string,\n request: CreateConversationNoteRequest,\n ): Promise<ConversationNote> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/notes`,\n request,\n )\n }\n\n update(id: string, request: UpdateConversationNoteRequest): Promise<ConversationNote> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-notes/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n delete(id: string): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-notes/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/** Meeting bots (Ava) — dispatch by meeting URL, summaries. */\nexport interface MeetingService {\n /**\n * Send Ava to a meeting URL. Resolves with the pre-minted meeting\n * conversation (channel = the platform classified from the URL); transcript\n * turns then stream in as inbound messages while the meeting runs.\n */\n dispatch(request: DispatchMeetingBotRequest): Promise<Conversation>\n /**\n * START regenerating this meeting conversation's markdown summary from its\n * stored transcript, overwriting any existing one when it lands. Generation\n * runs server-side beyond this request, so the promise resolves as soon as the\n * conversation is CLAIMED — with `summary_status: 'processing'` and the OLD\n * `summary` still attached. Poll `conversations.get(id)` until\n * `summary_status` is `completed` (or `failed`) to read the new one.\n *\n * Rejects with `no_transcript` when the conversation has no completed\n * transcript to summarize, `summarization_unavailable` when the environment\n * has no generator configured, and `summary_in_progress` when a generation is\n * already running for this conversation.\n */\n summarize(conversationId: string): Promise<Conversation>\n}\n\nclass MeetingServiceImpl implements MeetingService {\n constructor(private readonly client: ProteosClient) {}\n\n dispatch(request: DispatchMeetingBotRequest): Promise<Conversation> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/meetings`, request)\n }\n\n summarize(conversationId: string): Promise<Conversation> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/meetings/${encodeURIComponent(conversationId)}/summarize`,\n )\n }\n}\n\n/**\n * Ava's bots as the platform remembers them: what a client shows as \"Ava joins\"\n * for a meeting, and the door to withdraw her.\n */\nexport interface MeetingBotService {\n /** The bots the caller may see, soonest meeting first. */\n list(query?: ListMeetingBotsQuery): Promise<ListResponse<MeetingBot>>\n /**\n * Withdraw Ava from the meeting this bot belongs to: every bot of that\n * meeting instance the caller may act on (scheduled from their connection,\n * or on a meeting they are invited to) is cancelled (scheduled) or leaves\n * the call (live), the rows become `removed`, and the calendar will not\n * schedule her again. Re-add her explicitly with `meetings.dispatch`.\n */\n remove(id: string): Promise<MeetingBot>\n}\n\nclass MeetingBotServiceImpl implements MeetingBotService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListMeetingBotsQuery = {}): Promise<ListResponse<MeetingBot>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/meeting-bots`, query)\n }\n\n remove(id: string): Promise<MeetingBot> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/meeting-bots/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/** Configured integration instances (Slack workspace, Gmail grant, …). */\nexport interface ConnectionService {\n list(query?: ListConnectionsQuery): Promise<ListResponse<Connection>>\n get(id: string): Promise<Connection>\n create(request: CreateConnectionRequest): Promise<Connection>\n update(id: string, request: UpdateConnectionRequest): Promise<Connection>\n /**\n * Delete a connection. The connector first releases its provider-side\n * registration (a Recall calendar and the OAuth grant behind it); when that\n * fails the delete is refused with a `connector_uninstall_failed` 502 rather\n * than orphaning it. Pass `{ is_forced: true }` to drop the row anyway and\n * clean up at the provider by hand.\n */\n delete(id: string, query?: DeleteConnectionQuery): Promise<void>\n /**\n * Begin the connector's install flow. OAuth connectors return an\n * `authorization_url` to open in a popup; direct-install connectors take\n * `{ input }` (user-supplied credentials) and complete server-side,\n * returning `is_completed` plus a one-time `setup` handout.\n */\n install(id: string, request?: InstallConnectionRequest): Promise<InstallConnectionResponse>\n /**\n * Trigger a historical backfill (\"sync all\") on an email connection: the\n * server fetches provider mail in the chosen range and ingests it through\n * the normal pipeline (conversation filters, dedupe, agent listeners).\n * Returns 202 with the connection already showing\n * settings.sync_status='in_progress' — poll get(id) until it flips to\n * done/failed. A running sync answers 409 (sync_already_running).\n */\n sync(id: string, request: SyncConnectionRequest): Promise<Connection>\n /** Search the contact addresses this connection can reach (org-deduped) for the compose picker. */\n listContactAddresses(\n connectionId: string,\n query?: ListContactAddressesQuery,\n ): Promise<ListResponse<ContactAddress>>\n /** Search a connection's addressable VENUES (Slack channels) for the compose picker. */\n listRooms(connectionId: string, query?: ListRoomsQuery): Promise<ListResponse<Room>>\n /**\n * Deliverability of a sending-platform connection (SendGrid): rates from\n * the channel_event ledger + the provider's snapshot (engagement quality,\n * counters, suppression counts, domain/sender state, dedicated IPs).\n * `email_provider_not_supported` on mailbox connectors.\n */\n getHealth(connectionId: string, query?: GetConnectionHealthQuery): Promise<EmailHealth>\n /** Ask the provider to re-check the sending domain's DNS. */\n validateDomain(connectionId: string): Promise<EmailDomainStatus>\n /** Re-send the single-sender verification mail (no-op on an authenticated domain). */\n resendSenderVerification(connectionId: string): Promise<void>\n /** Read one provider suppression list live. */\n listSuppressions(connectionId: string, kind: EmailSuppressionKind): Promise<EmailSuppression[]>\n /** Take an address off one provider suppression list (a false positive). */\n removeSuppression(connectionId: string, kind: EmailSuppressionKind, email: string): Promise<void>\n /** Start / stop the provider's automated warmup on a dedicated IP. */\n setIpWarmup(connectionId: string, ip: string, isEnabled: boolean): Promise<void>\n /** The runtime connector catalog: what is wired in this environment + install modes. */\n listConnectors(): Promise<ConnectorCatalogEntry[]>\n /**\n * The sender directory of a domain-authenticated email connection: every\n * email contact address on its domain (colleagues + shared mailboxes), the\n * default flagged. Empty on connections without a sender domain.\n */\n listSenders(connectionId: string): Promise<EmailSender[]>\n /** Pin the connection's fallback sender; returns the refreshed directory. */\n setDefaultSender(connectionId: string, request: SetDefaultSenderRequest): Promise<EmailSender[]>\n}\n\nclass ConnectionServiceImpl implements ConnectionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConnectionsQuery = {}): Promise<ListResponse<Connection>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/connections`, query)\n }\n\n get(id: string): Promise<Connection> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateConnectionRequest): Promise<Connection> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/connections`, request)\n }\n\n update(id: string, request: UpdateConnectionRequest): Promise<Connection> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string, query: DeleteConnectionQuery = {}): Promise<void> {\n await this.client.requestWithQuery(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}`,\n query,\n )\n }\n\n install(id: string, request?: InstallConnectionRequest): Promise<InstallConnectionResponse> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}/install`,\n request,\n )\n }\n\n sync(id: string, request: SyncConnectionRequest): Promise<Connection> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}/sync`,\n request,\n )\n }\n\n listContactAddresses(\n connectionId: string,\n query: ListContactAddressesQuery = {},\n ): Promise<ListResponse<ContactAddress>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/contact-addresses`,\n query,\n )\n }\n\n listRooms(connectionId: string, query: ListRoomsQuery = {}): Promise<ListResponse<Room>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/rooms`,\n query,\n )\n }\n\n getHealth(connectionId: string, query: GetConnectionHealthQuery = {}): Promise<EmailHealth> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/health`,\n query,\n )\n }\n\n validateDomain(connectionId: string): Promise<EmailDomainStatus> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/domain/validate`,\n )\n }\n\n resendSenderVerification(connectionId: string): Promise<void> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/sender/verify`,\n )\n }\n\n async listSuppressions(\n connectionId: string,\n kind: EmailSuppressionKind,\n ): Promise<EmailSuppression[]> {\n const response: { data: EmailSuppression[] } = await this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/suppressions`,\n { kind },\n )\n return response.data\n }\n\n removeSuppression(\n connectionId: string,\n kind: EmailSuppressionKind,\n email: string,\n ): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/suppressions/${encodeURIComponent(kind)}/${encodeURIComponent(email)}`,\n )\n }\n\n setIpWarmup(connectionId: string, ip: string, isEnabled: boolean): Promise<void> {\n return this.client.request(\n isEnabled ? 'POST' : 'DELETE',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/ip-warmup/${encodeURIComponent(ip)}`,\n )\n }\n\n async listConnectors(): Promise<ConnectorCatalogEntry[]> {\n const response: { data: ConnectorCatalogEntry[] } = await this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connectors`,\n )\n return response.data\n }\n\n async listSenders(connectionId: string): Promise<EmailSender[]> {\n const response: { data: EmailSender[] } = await this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/senders`,\n )\n return response.data\n }\n\n async setDefaultSender(\n connectionId: string,\n request: SetDefaultSenderRequest,\n ): Promise<EmailSender[]> {\n const response: { data: EmailSender[] } = await this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/senders/default`,\n request,\n )\n return response.data\n }\n}\n\n/** The person-level identity layer: contacts, addresses, merges, permissions, erasure. */\nexport interface ContactService {\n list(query?: ListContactsQuery): Promise<ListResponse<Contact>>\n get(id: string): Promise<Contact>\n /**\n * Manually mint a contact (sync dedup — 409 contact_address_taken on any\n * owned address), or with `platform_user_id` ensure a colleague's bound\n * contact and attach the addresses to it.\n */\n create(request: CreateContactRequest): Promise<Contact>\n update(id: string, request: UpdateContactRequest): Promise<Contact>\n attachAddress(contactId: string, request: AttachContactAddressRequest): Promise<Contact>\n detachAddress(contactId: string, addressId: string): Promise<Contact>\n /** Link the contact to a business record (bare edge; 409 contact_record_link_exists on duplicates). */\n linkRecord(request: CreateContactRecordLinkRequest): Promise<ContactRecordLink>\n /** Page contact→record edges by contact_id, or by entity_slug + record_id. */\n listRecordLinks(query?: ListContactRecordLinksQuery): Promise<ListResponse<ContactRecordLink>>\n getRecordLink(linkId: string): Promise<ContactRecordLink>\n unlinkRecord(linkId: string): Promise<void>\n /** Fold source_contact_id into contactId (contactId wins). */\n merge(contactId: string, request: MergeContactsRequest): Promise<Contact>\n /** The contact's permission ledger, newest first, with per-purpose consent. */\n listPermissionEvents(contactId: string): Promise<ListPermissionEventsResponse>\n recordPermissionEvent(contactId: string, request: RecordPermissionEventRequest): Promise<Contact>\n /**\n * Send a new confirmation for a double opt-in that was not confirmed (new\n * link and expiry, same mailbox, address and purpose); 409\n * consent_request_confirmed once it was.\n */\n resendConsentRequest(requestId: string): Promise<ConsentRequest>\n block(contactId: string, request?: BlockContactRequest): Promise<Contact>\n unblock(contactId: string, request?: BlockContactRequest): Promise<Contact>\n requestErasure(contactId: string): Promise<ContactErasureRequest>\n listErasureRequests(contactId: string): Promise<ContactErasureRequest[]>\n listMergeProposals(\n query?: ListContactMergeProposalsQuery,\n ): Promise<ListResponse<ContactMergeProposal>>\n approveMergeProposal(proposalId: string): Promise<ContactMergeProposal>\n rejectMergeProposal(proposalId: string): Promise<ContactMergeProposal>\n}\n\nclass ContactServiceImpl implements ContactService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListContactsQuery = {}): Promise<ListResponse<Contact>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/contacts`, query)\n }\n\n get(id: string): Promise<Contact> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateContactRequest): Promise<Contact> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/contacts`, request)\n }\n\n update(id: string, request: UpdateContactRequest): Promise<Contact> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n attachAddress(contactId: string, request: AttachContactAddressRequest): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/addresses`,\n request,\n )\n }\n\n detachAddress(contactId: string, addressId: string): Promise<Contact> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/addresses/${encodeURIComponent(addressId)}`,\n )\n }\n\n linkRecord(request: CreateContactRecordLinkRequest): Promise<ContactRecordLink> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/contact-record-links`, request)\n }\n\n listRecordLinks(\n query: ListContactRecordLinksQuery = {},\n ): Promise<ListResponse<ContactRecordLink>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contact-record-links`,\n query,\n )\n }\n\n getRecordLink(linkId: string): Promise<ContactRecordLink> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contact-record-links/${encodeURIComponent(linkId)}`,\n )\n }\n\n unlinkRecord(linkId: string): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/contact-record-links/${encodeURIComponent(linkId)}`,\n )\n }\n\n merge(contactId: string, request: MergeContactsRequest): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/merge`,\n request,\n )\n }\n\n listPermissionEvents(contactId: string): Promise<ListPermissionEventsResponse> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/permission-events`,\n )\n }\n\n recordPermissionEvent(\n contactId: string,\n request: RecordPermissionEventRequest,\n ): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/permission-events`,\n request,\n )\n }\n\n resendConsentRequest(requestId: string): Promise<ConsentRequest> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/consent-requests/${encodeURIComponent(requestId)}/resend`,\n )\n }\n\n block(contactId: string, request: BlockContactRequest = {}): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/block`,\n request,\n )\n }\n\n unblock(contactId: string, request: BlockContactRequest = {}): Promise<Contact> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/unblock`,\n request,\n )\n }\n\n requestErasure(contactId: string): Promise<ContactErasureRequest> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/erasure-requests`,\n )\n }\n\n listErasureRequests(contactId: string): Promise<ContactErasureRequest[]> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contacts/${encodeURIComponent(contactId)}/erasure-requests`,\n )\n }\n\n listMergeProposals(\n query: ListContactMergeProposalsQuery = {},\n ): Promise<ListResponse<ContactMergeProposal>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contact-merge-proposals`,\n query,\n )\n }\n\n approveMergeProposal(proposalId: string): Promise<ContactMergeProposal> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contact-merge-proposals/${encodeURIComponent(proposalId)}/approve`,\n )\n }\n\n rejectMergeProposal(proposalId: string): Promise<ContactMergeProposal> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/contact-merge-proposals/${encodeURIComponent(proposalId)}/reject`,\n )\n }\n}\n\n/** Conversation threads across every channel (inbox order: last_message_at). */\nexport interface ConversationService {\n list(query?: ListConversationsQuery): Promise<ListResponse<Conversation>>\n get(id: string): Promise<Conversation>\n /** Patch the user-editable surface (subject, summary, status, metadata). */\n update(id: string, request: UpdateConversationRequest): Promise<Conversation>\n /**\n * What the conversation may end with: its type's outcomes, then its\n * channel's system outcomes — the picker's list and the valid\n * `outcome_key` values for `update`.\n */\n listOutcomes(id: string): Promise<{ data: ConversationOutcomeOption[] }>\n /**\n * Where the conversation stands against its objectives: the current phase,\n * every phase's status, every applicable objective's standing and the\n * definitions they reference — the checklist from one read.\n */\n getObjectiveProgress(id: string): Promise<ConversationObjectiveProgress>\n end(id: string): Promise<Conversation>\n /**\n * Hard-delete the conversation, its thread children, and every dependent\n * row (messages, attachments, read markers, transcriptions). Irreversible.\n */\n delete(id: string): Promise<void>\n /** Upsert the requesting user's read marker to now (open a conversation). */\n markRead(id: string): Promise<void>\n /** Remove the marker — the conversation reads as unread again. */\n markUnread(id: string): Promise<void>\n /** Unread-conversation counts for the requesting user (envelope + badges). */\n unreadCounts(query?: UnreadCountsQuery): Promise<UnreadCounts>\n}\n\nclass ConversationServiceImpl implements ConversationService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationsQuery = {}): Promise<ListResponse<Conversation>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/conversations`, query)\n }\n\n get(id: string): Promise<Conversation> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}`,\n )\n }\n\n listOutcomes(id: string): Promise<{ data: ConversationOutcomeOption[] }> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/outcomes`,\n )\n }\n\n async getObjectiveProgress(id: string): Promise<ConversationObjectiveProgress> {\n const response = await this.client.request<{ data: ConversationObjectiveProgress }>(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/objective-progress`,\n )\n return response.data\n }\n\n update(id: string, request: UpdateConversationRequest): Promise<Conversation> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n end(id: string): Promise<Conversation> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/end`,\n )\n }\n\n delete(id: string): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}`,\n )\n }\n\n markRead(id: string): Promise<void> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/read`,\n )\n }\n\n markUnread(id: string): Promise<void> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(id)}/read`,\n )\n }\n\n unreadCounts(query?: UnreadCountsQuery): Promise<UnreadCounts> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/unread-counts`,\n query,\n )\n }\n}\n\n/** Messages within a conversation (ordered by occurred_at) + outbound send + drafts + reactions. */\nexport interface MessageService {\n listByConversation(\n conversationId: string,\n query?: ListMessagesQuery,\n ): Promise<ListResponse<Message>>\n /** One message with its read-time projections (reactions, attachments). */\n get(messageId: string): Promise<Message>\n send(request: SendMessageRequest): Promise<Message>\n /**\n * Dry-run of the sending gate: same addressing as send, no content, nothing\n * minted. Answers whether the send may go out now and, when held, the\n * earliest instant it may (`earliest_allowed_at`).\n */\n checkSendEligibility(request: SendEligibilityRequest): Promise<SendEligibility>\n /**\n * Store an outbound message for human review (status=draft) — same request\n * shape as send, nothing reaches the connector until sendDraft. Originate\n * mode mints a hidden status=draft conversation.\n */\n draft(request: SendMessageRequest): Promise<Message>\n /**\n * Replace a draft's editable surface (full state, PUT semantics). 409\n * `draft_not_editable` once the draft was sent or rejected.\n */\n updateDraft(messageId: string, request: UpdateDraftRequest): Promise<Message>\n /** A draft's history, oldest first, plus what changed. Also readable after send. */\n listDraftVersions(messageId: string): Promise<MessageDraftVersions>\n /** Deliver a draft (draft → pending → sent/failed). 409 on a lost race. */\n sendDraft(messageId: string): Promise<Message>\n /** Decline a draft (draft → rejected, terminal). 409 on a lost race. */\n rejectDraft(messageId: string): Promise<Message>\n /** Aggregated reactions on one message (also rides on Message.reactions). */\n getReactions(messageId: string): Promise<Reaction[]>\n /**\n * Place an emoji (connector-native token) via the message's connector.\n * Rejected with `reactions_not_supported` on reaction-less channels — gate\n * the affordance on the connection's `supports_reactions` / `reactions`.\n */\n addReaction(messageId: string, emoji: string): Promise<Reaction[]>\n removeReaction(messageId: string, emoji: string): Promise<Reaction[]>\n}\n\nclass MessageServiceImpl implements MessageService {\n constructor(private readonly client: ProteosClient) {}\n\n listByConversation(\n conversationId: string,\n query: ListMessagesQuery = {},\n ): Promise<ListResponse<Message>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/messages`,\n query,\n )\n }\n\n get(messageId: string): Promise<Message> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}`,\n )\n }\n\n send(request: SendMessageRequest): Promise<Message> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/messages/send`, request)\n }\n\n checkSendEligibility(request: SendEligibilityRequest): Promise<SendEligibility> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/messages/send-eligibility`,\n request,\n )\n }\n\n draft(request: SendMessageRequest): Promise<Message> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/messages/draft`, request)\n }\n\n updateDraft(messageId: string, request: UpdateDraftRequest): Promise<Message> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/draft`,\n request,\n )\n }\n\n listDraftVersions(messageId: string): Promise<MessageDraftVersions> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/draft-versions`,\n )\n }\n\n sendDraft(messageId: string): Promise<Message> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/send`,\n )\n }\n\n rejectDraft(messageId: string): Promise<Message> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/reject`,\n )\n }\n\n async getReactions(messageId: string): Promise<Reaction[]> {\n const response: ListReactionsResponse = await this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/reactions`,\n )\n return response.data\n }\n\n async addReaction(messageId: string, emoji: string): Promise<Reaction[]> {\n const response: ListReactionsResponse = await this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/reactions`,\n { emoji },\n )\n return response.data\n }\n\n async removeReaction(messageId: string, emoji: string): Promise<Reaction[]> {\n const response: ListReactionsResponse = await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/reactions/${encodeURIComponent(emoji)}`,\n )\n return response.data\n }\n}\n\n/** Rules binding inbound messages to agents. */\nexport interface AgentListenerService {\n list(query?: ListAgentListenersQuery): Promise<ListResponse<AgentListener>>\n get(id: string): Promise<AgentListener>\n create(request: CreateAgentListenerRequest): Promise<AgentListener>\n update(id: string, request: UpdateAgentListenerRequest): Promise<AgentListener>\n delete(id: string): Promise<void>\n}\n\nclass AgentListenerServiceImpl implements AgentListenerService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListAgentListenersQuery = {}): Promise<ListResponse<AgentListener>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/agent-listeners`, query)\n }\n\n get(id: string): Promise<AgentListener> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/agent-listeners/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateAgentListenerRequest): Promise<AgentListener> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/agent-listeners`, request)\n }\n\n update(id: string, request: UpdateAgentListenerRequest): Promise<AgentListener> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/agent-listeners/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/agent-listeners/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/**\n * Ingest-time conversation filters: block/allow rules that drop matching\n * inbound messages before persistence, scoped globally or per connection.\n * listEvents pages a rule's drop-audit trail (who got dropped, when, why).\n */\nexport interface ConversationFilterService {\n list(query?: ListConversationFiltersQuery): Promise<ListResponse<ConversationFilter>>\n get(id: string): Promise<ConversationFilter>\n create(request: CreateConversationFilterRequest): Promise<ConversationFilter>\n update(id: string, request: UpdateConversationFilterRequest): Promise<ConversationFilter>\n delete(id: string): Promise<void>\n listEvents(\n id: string,\n query?: ListConversationFilterEventsQuery,\n ): Promise<ListResponse<ConversationFilterEvent>>\n}\n\nclass ConversationFilterServiceImpl implements ConversationFilterService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationFiltersQuery = {}): Promise<ListResponse<ConversationFilter>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-filters`,\n query,\n )\n }\n\n get(id: string): Promise<ConversationFilter> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-filters/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateConversationFilterRequest): Promise<ConversationFilter> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/conversation-filters`, request)\n }\n\n update(id: string, request: UpdateConversationFilterRequest): Promise<ConversationFilter> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-filters/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-filters/${encodeURIComponent(id)}`,\n )\n }\n\n listEvents(\n id: string,\n query: ListConversationFilterEventsQuery = {},\n ): Promise<ListResponse<ConversationFilterEvent>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-filters/${encodeURIComponent(id)}/events`,\n query,\n )\n }\n}\n\n/**\n * Per-org glossary: custom-vocabulary terms that boost transcription accuracy.\n * A term feeds the transcription provider's keyterm prompting; `priority` ranks\n * a term (prioritized terms are injected first, then unprioritized), which\n * decides the top 100 sent when an org stores more than the provider's cap.\n */\nexport interface GlossaryTermService {\n list(query?: ListGlossaryTermsQuery): Promise<ListResponse<GlossaryTerm>>\n get(id: string): Promise<GlossaryTerm>\n create(request: CreateGlossaryTermRequest): Promise<GlossaryTerm>\n update(id: string, request: UpdateGlossaryTermRequest): Promise<GlossaryTerm>\n delete(id: string): Promise<void>\n}\n\nclass GlossaryTermServiceImpl implements GlossaryTermService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListGlossaryTermsQuery = {}): Promise<ListResponse<GlossaryTerm>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/glossary-terms`, query)\n }\n\n get(id: string): Promise<GlossaryTerm> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/glossary-terms/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateGlossaryTermRequest): Promise<GlossaryTerm> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/glossary-terms`, request)\n }\n\n update(id: string, request: UpdateGlossaryTermRequest): Promise<GlossaryTerm> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/glossary-terms/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/glossary-terms/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/**\n * The org's conversation taxonomy. Before a meeting summary is generated, a\n * cheap classifier reads the transcript head plus every type's `definition`\n * and picks the matching `key` — the result lands on `Conversation.type_key`,\n * and a type whose `config.summary_prompt_key` names an agent-service prompt\n * swaps the summary system prompt for that prompt's current body. Keyed by\n * `key` (not id); `upsert` is the idempotent module-deploy door.\n */\nexport interface ConversationTypeService {\n list(query?: ListConversationTypesQuery): Promise<ListResponse<ConversationType>>\n get(key: string): Promise<ConversationType>\n create(request: CreateConversationTypeRequest): Promise<ConversationType>\n update(key: string, request: UpdateConversationTypeRequest): Promise<ConversationType>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(key: string, request: CreateConversationTypeRequest): Promise<ConversationType>\n delete(key: string): Promise<void>\n}\n\nclass ConversationTypeServiceImpl implements ConversationTypeService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationTypesQuery = {}): Promise<ListResponse<ConversationType>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-types`,\n query,\n )\n }\n\n get(key: string): Promise<ConversationType> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-types/${encodeURIComponent(key)}`,\n )\n }\n\n create(request: CreateConversationTypeRequest): Promise<ConversationType> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/conversation-types`, request)\n }\n\n update(key: string, request: UpdateConversationTypeRequest): Promise<ConversationType> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-types/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(key: string, request: CreateConversationTypeRequest): Promise<ConversationType> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversation-types/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-types/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Conversation tag definitions: WHAT to look for in a conversation — one\n * typed question (boolean / choice / score) plus where its answers anchor\n * (`scope`) and which model path answers (`evaluator`). A definition is only\n * evaluated through the tag sets that reference it. Keyed by `key` (not id);\n * `upsert` is the idempotent module-deploy door.\n */\nexport interface ConversationTagDefinitionService {\n list(\n query?: ListConversationTagDefinitionsQuery,\n ): Promise<ListResponse<ConversationTagDefinition>>\n get(key: string): Promise<ConversationTagDefinition>\n create(request: CreateConversationTagDefinitionRequest): Promise<ConversationTagDefinition>\n update(\n key: string,\n request: UpdateConversationTagDefinitionRequest,\n ): Promise<ConversationTagDefinition>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(\n key: string,\n request: CreateConversationTagDefinitionRequest,\n ): Promise<ConversationTagDefinition>\n delete(key: string): Promise<void>\n}\n\nclass ConversationTagDefinitionServiceImpl implements ConversationTagDefinitionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n query: ListConversationTagDefinitionsQuery = {},\n ): Promise<ListResponse<ConversationTagDefinition>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions`,\n query,\n )\n }\n\n get(key: string): Promise<ConversationTagDefinition> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions/${encodeURIComponent(key)}`,\n )\n }\n\n create(request: CreateConversationTagDefinitionRequest): Promise<ConversationTagDefinition> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions`,\n request,\n )\n }\n\n update(\n key: string,\n request: UpdateConversationTagDefinitionRequest,\n ): Promise<ConversationTagDefinition> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(\n key: string,\n request: CreateConversationTagDefinitionRequest,\n ): Promise<ConversationTagDefinition> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-tag-definitions/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Conversation tag sets: WHERE and WHEN a group of definitions is evaluated.\n * A set needs at least one conversation selector (`channels`,\n * `connection_ids`, `type_keys`) — tagging is opt-in, never org-wide by\n * accident — and `evaluate_on` is a non-empty subset of realtime|completion.\n * Keyed by `key` (not id); `upsert` is the idempotent module-deploy door.\n */\nexport interface ConversationTagSetService {\n list(query?: ListConversationTagSetsQuery): Promise<ListResponse<ConversationTagSet>>\n get(key: string): Promise<ConversationTagSet>\n create(request: CreateConversationTagSetRequest): Promise<ConversationTagSet>\n update(key: string, request: UpdateConversationTagSetRequest): Promise<ConversationTagSet>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(key: string, request: CreateConversationTagSetRequest): Promise<ConversationTagSet>\n delete(key: string): Promise<void>\n}\n\nclass ConversationTagSetServiceImpl implements ConversationTagSetService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationTagSetsQuery = {}): Promise<ListResponse<ConversationTagSet>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets`,\n query,\n )\n }\n\n get(key: string): Promise<ConversationTagSet> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets/${encodeURIComponent(key)}`,\n )\n }\n\n create(request: CreateConversationTagSetRequest): Promise<ConversationTagSet> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/conversation-tag-sets`, request)\n }\n\n update(key: string, request: UpdateConversationTagSetRequest): Promise<ConversationTagSet> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(key: string, request: CreateConversationTagSetRequest): Promise<ConversationTagSet> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-tag-sets/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Conversation tags: the observations definitions make on conversations,\n * plus the evaluations that produced them. Per-conversation reads/writes\n * hang off the conversation; `update`/`delete` address a tag by id; `list`\n * and `counts` are the org-wide streams. Span offsets are UNICODE CODE POINT\n * indexes (end exclusive) — convert to/from UTF-16 before slicing JS strings.\n */\nexport interface ConversationTagService {\n /** Tags on one conversation (pending, active and dismissed unless `status` filters). */\n listByConversation(\n conversationId: string,\n query?: ListConversationTagsQuery,\n ): Promise<ListResponse<ConversationTag>>\n /** A person tags a conversation, a message or a span (source = user, confidence 1). */\n create(conversationId: string, request: CreateConversationTagRequest): Promise<ConversationTag>\n /**\n * Start a manual evaluation (202). Resolves with the PENDING evaluation as\n * soon as it is accepted — the tagger runs server-side beyond this request.\n * Poll `listEvaluations(conversationId)` until that evaluation's status is\n * `done` | `failed`, then re-read the tags. 409\n * `conversation_tag_set_not_matched` when no enabled set matches the\n * conversation; 409 `conversation_tag_evaluation_in_progress` while another\n * evaluation is still running.\n */\n evaluate(\n conversationId: string,\n request?: EvaluateConversationTagsRequest,\n ): Promise<ConversationTagEvaluation>\n /** The evaluation history of one conversation (newest first by default). */\n listEvaluations(\n conversationId: string,\n query?: ListConversationTagEvaluationsQuery,\n ): Promise<ListResponse<ConversationTagEvaluation>>\n /**\n * Flip a tag between active and dismissed (the feedback loop), annotate why,\n * and/or correct its value and anchors (a correction makes it a user tag).\n */\n update(id: string, request: UpdateConversationTagRequest): Promise<ConversationTag>\n delete(id: string): Promise<void>\n /** Org-wide tag stream (filter by definition, value, channel, contact, time window). */\n list(query?: ListConversationTagsQuery): Promise<ListResponse<ConversationTag>>\n /** Grouped counts for dashboards — `group_by` is a comma-joined string. */\n counts(query?: CountConversationTagsQuery): Promise<CountConversationTagsResponse>\n /**\n * The enabled definitions the enabled sets select for the conversation right\n * now (`evaluate_on` ignored, like a manual evaluation) — what a person may\n * tag it with, incl. its outcome definition(s) (`role === 'outcome'`).\n */\n listApplicableDefinitions(\n conversationId: string,\n ): Promise<ListResponse<ConversationTagDefinition>>\n}\n\nclass ConversationTagServiceImpl implements ConversationTagService {\n constructor(private readonly client: ProteosClient) {}\n\n listByConversation(\n conversationId: string,\n query: ListConversationTagsQuery = {},\n ): Promise<ListResponse<ConversationTag>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tags`,\n query,\n )\n }\n\n create(conversationId: string, request: CreateConversationTagRequest): Promise<ConversationTag> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tags`,\n request,\n )\n }\n\n listApplicableDefinitions(\n conversationId: string,\n ): Promise<ListResponse<ConversationTagDefinition>> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tag-definitions`,\n )\n }\n\n evaluate(\n conversationId: string,\n request: EvaluateConversationTagsRequest = {},\n ): Promise<ConversationTagEvaluation> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tags/evaluate`,\n request,\n )\n }\n\n listEvaluations(\n conversationId: string,\n query: ListConversationTagEvaluationsQuery = {},\n ): Promise<ListResponse<ConversationTagEvaluation>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/tag-evaluations`,\n query,\n )\n }\n\n update(id: string, request: UpdateConversationTagRequest): Promise<ConversationTag> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-tags/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-tags/${encodeURIComponent(id)}`,\n )\n }\n\n list(query: ListConversationTagsQuery = {}): Promise<ListResponse<ConversationTag>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/conversation-tags`, query)\n }\n\n counts(query: CountConversationTagsQuery = {}): Promise<CountConversationTagsResponse> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-tags/counts`,\n query,\n )\n }\n}\n\n/**\n * Conversation objective definitions: WHAT a conversation should achieve —\n * \"confirm the budget\", \"book the demo\" — org-wide or per conversation type,\n * optionally pinned to one of the type's phases, optionally MEASURED (a tag\n * value condition or an outcome set) so the platform can tell when it was\n * achieved. Keyed by `key` (not id); `upsert` is the idempotent module-deploy\n * door.\n */\nexport interface ConversationObjectiveDefinitionService {\n list(\n query?: GetManyConversationObjectiveDefinitionsQuery,\n ): Promise<ListResponse<ConversationObjectiveDefinition>>\n /** One page, explicitly (`query.page`) — the door a page walker calls; same wire call as `list`. */\n listPage(\n query?: GetManyConversationObjectiveDefinitionsQuery,\n ): Promise<ListResponse<ConversationObjectiveDefinition>>\n get(key: string): Promise<ConversationObjectiveDefinition>\n create(\n request: CreateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition>\n /** Partial update; `measure: null` clears the measure (guidance only). */\n update(\n key: string,\n request: UpdateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(\n key: string,\n request: CreateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition>\n delete(key: string): Promise<void>\n}\n\nclass ConversationObjectiveDefinitionServiceImpl implements ConversationObjectiveDefinitionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n query: GetManyConversationObjectiveDefinitionsQuery = {},\n ): Promise<ListResponse<ConversationObjectiveDefinition>> {\n return this.listPage(query)\n }\n\n listPage(\n query: GetManyConversationObjectiveDefinitionsQuery = {},\n ): Promise<ListResponse<ConversationObjectiveDefinition>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions`,\n query,\n )\n }\n\n get(key: string): Promise<ConversationObjectiveDefinition> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions/${encodeURIComponent(key)}`,\n )\n }\n\n create(\n request: CreateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions`,\n request,\n )\n }\n\n update(\n key: string,\n request: UpdateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(\n key: string,\n request: CreateConversationObjectiveDefinitionRequest,\n ): Promise<ConversationObjectiveDefinition> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-objective-definitions/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Conversation objectives: the org-wide ledger of every applicable\n * definition's standing on every conversation (open rows included), plus\n * grouped counts for dashboards. Read-only — a standing is resolved by the\n * service from the conversation's tags and outcome; the per-conversation\n * checklist is `conversations.getObjectiveProgress`.\n */\nexport interface ConversationObjectiveService {\n /** The ledger (filter by conversation, definition, type, phase, channel, status, source, time window on `recorded_at`). */\n list(query?: GetManyConversationObjectivesQuery): Promise<ListResponse<ConversationObjective>>\n /** Grouped counts for dashboards — `group_by` is a comma-joined string. */\n counts(query?: CountConversationObjectivesQuery): Promise<CountConversationObjectivesResponse>\n}\n\nclass ConversationObjectiveServiceImpl implements ConversationObjectiveService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n query: GetManyConversationObjectivesQuery = {},\n ): Promise<ListResponse<ConversationObjective>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-objectives`,\n query,\n )\n }\n\n counts(\n query: CountConversationObjectivesQuery = {},\n ): Promise<CountConversationObjectivesResponse> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-objectives/counts`,\n query,\n )\n }\n}\n\n/**\n * Contact groups: the generic org-shared audience taxonomy. Membership lives\n * on the contact (`Contact.group_key`, one group per contact — assign via\n * `contacts.update`); tone-of-voice synthesis reads the groups and\n * auto-assigns ungrouped correspondents. Keyed by `key` (not id); `upsert` is\n * the idempotent module-deploy door. Deleting a group clears its members'\n * membership and purges its tone profile rows.\n */\nexport interface ContactGroupService {\n list(query?: ListContactGroupsQuery): Promise<ListResponse<ContactGroup>>\n get(key: string): Promise<ContactGroup>\n create(request: CreateContactGroupRequest): Promise<ContactGroup>\n update(key: string, request: UpdateContactGroupRequest): Promise<ContactGroup>\n /** Idempotent create-or-update by key (PUT) — what `pro module deploy` calls. */\n upsert(key: string, request: CreateContactGroupRequest): Promise<ContactGroup>\n delete(key: string): Promise<void>\n}\n\nclass ContactGroupServiceImpl implements ContactGroupService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListContactGroupsQuery = {}): Promise<ListResponse<ContactGroup>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/contact-groups`, query)\n }\n\n get(key: string): Promise<ContactGroup> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/contact-groups/${encodeURIComponent(key)}`,\n )\n }\n\n create(request: CreateContactGroupRequest): Promise<ContactGroup> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/contact-groups`, request)\n }\n\n update(key: string, request: UpdateContactGroupRequest): Promise<ContactGroup> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/contact-groups/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n upsert(key: string, request: CreateContactGroupRequest): Promise<ContactGroup> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/contact-groups/${encodeURIComponent(key)}`,\n { ...request, key },\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/contact-groups/${encodeURIComponent(key)}`,\n )\n }\n}\n\n/**\n * Tone-of-voice synthesis. A setup opts one platform user in (only set-up\n * users are swept); `synthesize` triggers a whole-user run immediately (202;\n * 409 `synthesis_in_progress` while one is live). Generated profiles form a\n * specificity hierarchy — fetch a user's rows with `listProfiles`, or let the\n * server pick the single most-specific row for a drafting context with\n * `resolve` (each row is self-contained; never concatenate tiers).\n */\nexport interface ToneProfileService {\n listSetups(query?: ListToneProfileSetupsQuery): Promise<ListResponse<ToneProfileSetup>>\n createSetup(request: CreateToneProfileSetupRequest): Promise<ToneProfileSetup>\n /** Removes the setup AND the user's generated profiles. */\n deleteSetup(id: string): Promise<void>\n /** Kicks a whole-user synthesis run off-request (bypasses cadence checks). */\n synthesize(setupId: string): Promise<void>\n listProfiles(query?: ListToneProfilesQuery): Promise<ListResponse<ToneProfile>>\n getProfile(id: string): Promise<ToneProfile>\n /** The single most-specific profile for a drafting context; 404 when none. */\n resolve(query: ResolveToneProfileQuery): Promise<ToneProfile>\n /**\n * Writes a HAND-AUTHORED profile, addressed by its scope tuple rather than an\n * id — so re-sending the same scope updates the row it created. The row lands\n * `source: 'manual'`, which locks that scope against synthesis forever after;\n * it also takes the scope over from a `model` row already there. Needs no\n * setup: a setup is the opt-in to AI synthesis, and writing a voice by hand is\n * the opposite of asking for one.\n */\n upsertProfile(request: UpsertToneProfileRequest): Promise<ToneProfile>\n /**\n * Removes one profile row, manual or model. A deleted model row comes back on\n * the next run; a deleted manual row hands its scope back to synthesis.\n */\n deleteProfile(id: string): Promise<void>\n}\n\nclass ToneProfileServiceImpl implements ToneProfileService {\n constructor(private readonly client: ProteosClient) {}\n\n listSetups(query: ListToneProfileSetupsQuery = {}): Promise<ListResponse<ToneProfileSetup>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/tone-profile-setups`,\n query,\n )\n }\n\n createSetup(request: CreateToneProfileSetupRequest): Promise<ToneProfileSetup> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/tone-profile-setups`, request)\n }\n\n async deleteSetup(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/tone-profile-setups/${encodeURIComponent(id)}`,\n )\n }\n\n async synthesize(setupId: string): Promise<void> {\n await this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/tone-profile-setups/${encodeURIComponent(setupId)}/synthesize`,\n )\n }\n\n listProfiles(query: ListToneProfilesQuery = {}): Promise<ListResponse<ToneProfile>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/tone-profiles`, query)\n }\n\n getProfile(id: string): Promise<ToneProfile> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/tone-profiles/${encodeURIComponent(id)}`,\n )\n }\n\n resolve(query: ResolveToneProfileQuery): Promise<ToneProfile> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/tone-profiles/resolve`,\n query,\n )\n }\n\n upsertProfile(request: UpsertToneProfileRequest): Promise<ToneProfile> {\n return this.client.request('PUT', `${CONVERSATION_BASE_PATH}/tone-profiles`, request)\n }\n\n async deleteProfile(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/tone-profiles/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/** Batch transcription of stored audio files + materialization. */\nexport interface TranscriptionService {\n /**\n * Kicks off transcription asynchronously — resolves immediately with a\n * PROCESSING entity; the provider runs off-request. Poll `get(id)` until the\n * status is `completed` (or `failed`), then `materialize`.\n */\n createFromFile(request: CreateTranscriptionRequest): Promise<Transcription>\n /**\n * Lands an ALREADY WRITTEN transcript. Synchronous — no provider runs, and\n * the entity comes back `completed`, ready to `materialize` straight away.\n * The door for authoring a transcript (and so a conversation) from text with\n * nothing to upload. Same endpoint as `createFromFile`; the shape of the body\n * chooses the mode, and exactly one of the two is allowed.\n */\n createFromText(request: CreateTranscriptionFromTextRequest): Promise<Transcription>\n list(query?: ListTranscriptionsQuery): Promise<ListResponse<Transcription>>\n get(id: string): Promise<Transcription>\n /**\n * Edits a completed transcription (turn text, speaker labels, language).\n * Does NOT retro-update messages of an already-materialized conversation.\n */\n update(id: string, request: UpdateTranscriptionRequest): Promise<Transcription>\n /**\n * Kicks off the mistranscription review pass (glossary-aware LLM hunt for\n * misheard terms) — resolves immediately with review_status `processing`;\n * poll `get(id)` until it flips to feedback_pending/completed/failed.\n */\n review(id: string): Promise<Transcription>\n /** Turns a completed transcription into an adhoc/meeting conversation. */\n materialize(id: string, request?: MaterializeTranscriptionRequest): Promise<Conversation>\n}\n\nclass TranscriptionServiceImpl implements TranscriptionService {\n constructor(private readonly client: ProteosClient) {}\n\n createFromFile(request: CreateTranscriptionRequest): Promise<Transcription> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/transcriptions`, request)\n }\n\n createFromText(request: CreateTranscriptionFromTextRequest): Promise<Transcription> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/transcriptions`, request)\n }\n\n list(query: ListTranscriptionsQuery = {}): Promise<ListResponse<Transcription>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/transcriptions`, query)\n }\n\n get(id: string): Promise<Transcription> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/transcriptions/${encodeURIComponent(id)}`,\n )\n }\n\n update(id: string, request: UpdateTranscriptionRequest): Promise<Transcription> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/transcriptions/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n review(id: string): Promise<Transcription> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/transcriptions/${encodeURIComponent(id)}/review`,\n {},\n )\n }\n\n materialize(id: string, request: MaterializeTranscriptionRequest = {}): Promise<Conversation> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/transcriptions/${encodeURIComponent(id)}/materialize`,\n request,\n )\n }\n}\n\n/**\n * Findings of the post-transcription review pass: terms likely misheard by the\n * transcription provider, awaiting accept/reject. Accepting applies the\n * replacement to the transcription's turns and (optionally) promotes it into\n * the glossary; resolving the last open finding flips the transcription's\n * review_status to completed.\n */\nexport interface MistranscribedTermService {\n list(query?: ListMistranscribedTermsQuery): Promise<ListResponse<MistranscribedTerm>>\n get(id: string): Promise<MistranscribedTerm>\n accept(id: string, request?: AcceptMistranscribedTermRequest): Promise<MistranscribedTerm>\n reject(id: string): Promise<MistranscribedTerm>\n}\n\nclass MistranscribedTermServiceImpl implements MistranscribedTermService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListMistranscribedTermsQuery = {}): Promise<ListResponse<MistranscribedTerm>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/mistranscribed-terms`,\n query,\n )\n }\n\n get(id: string): Promise<MistranscribedTerm> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/mistranscribed-terms/${encodeURIComponent(id)}`,\n )\n }\n\n accept(id: string, request: AcceptMistranscribedTermRequest = {}): Promise<MistranscribedTerm> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/mistranscribed-terms/${encodeURIComponent(id)}/accept`,\n request,\n )\n }\n\n reject(id: string): Promise<MistranscribedTerm> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/mistranscribed-terms/${encodeURIComponent(id)}/reject`,\n {},\n )\n }\n}\n\n/**\n * Softphone calling: the browser Voice token grant. The client identity is\n * derived server-side from the authenticated user; refresh by minting again\n * (the Voice SDK's tokenWillExpire event is the cue).\n */\nexport interface CallService {\n mintToken(request: MintCallTokenRequest): Promise<CallTokenResponse>\n /**\n * The conversation a provider call became — the softphone's outbound\n * browser-leg CallSid. 404 `call_not_found` until the call-start callback\n * minted it (poll briefly).\n */\n getCallConversation(connectionId: string, externalCallId: string): Promise<Conversation>\n /** Start / resume (true) or pause (false) the recording of a live phone conversation. */\n setRecording(conversationId: string, request: SetCallRecordingRequest): Promise<Conversation>\n /** A phone connection's provider numbers with status + routing. */\n listPhoneNumbers(connectionId: string): Promise<{ data: PhoneNumber[] }>\n /** Replace one number's routing (who it rings). Returns the refreshed list. */\n updatePhoneNumber(\n connectionId: string,\n numberExternalId: string,\n request: UpdatePhoneNumberRequest,\n ): Promise<{ data: PhoneNumber[] }>\n /** Point one number at the platform. Returns the refreshed list. */\n connectPhoneNumber(\n connectionId: string,\n numberExternalId: string,\n ): Promise<{ data: PhoneNumber[] }>\n /** Release one number (restores its previous handler). Returns the refreshed list. */\n disconnectPhoneNumber(\n connectionId: string,\n numberExternalId: string,\n ): Promise<{ data: PhoneNumber[] }>\n}\n\nclass CallServiceImpl implements CallService {\n constructor(private readonly client: ProteosClient) {}\n\n mintToken(request: MintCallTokenRequest): Promise<CallTokenResponse> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/calls/token`, request)\n }\n\n getCallConversation(connectionId: string, externalCallId: string): Promise<Conversation> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/calls/${encodeURIComponent(externalCallId)}`,\n )\n }\n\n setRecording(conversationId: string, request: SetCallRecordingRequest): Promise<Conversation> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/conversations/${encodeURIComponent(conversationId)}/recording`,\n request,\n )\n }\n\n listPhoneNumbers(connectionId: string): Promise<{ data: PhoneNumber[] }> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/phone-numbers`,\n )\n }\n\n updatePhoneNumber(\n connectionId: string,\n numberExternalId: string,\n request: UpdatePhoneNumberRequest,\n ): Promise<{ data: PhoneNumber[] }> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/phone-numbers/${encodeURIComponent(numberExternalId)}`,\n request,\n )\n }\n\n connectPhoneNumber(\n connectionId: string,\n numberExternalId: string,\n ): Promise<{ data: PhoneNumber[] }> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/phone-numbers/${encodeURIComponent(numberExternalId)}/connect`,\n )\n }\n\n disconnectPhoneNumber(\n connectionId: string,\n numberExternalId: string,\n ): Promise<{ data: PhoneNumber[] }> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(connectionId)}/phone-numbers/${encodeURIComponent(numberExternalId)}/disconnect`,\n )\n }\n}\n\nexport type * from './types.js'\nexport { UNSUBSCRIBE_URL_PLACEHOLDER } from './types.js'\n// Re-export voice types (the live dictation stream lives on this service now)\nexport type {\n TranscribeStreamOptions,\n TranscriptResult,\n VoiceService,\n VoiceTranscriptionStream,\n} from './voice.js'\n\n/**\n * Conversation briefs — guidance prepared ahead of a conversation (\"talk to\n * these people about this\"; the conversation sibling of message drafts).\n * Binding is explicit: the softphone carries the brief id into the call, a\n * brief naming a calendar event attaches to that meeting's conversation when\n * the meeting bot starts, or `attach` names the conversation. Any number of\n * briefs may be open for the same people or meeting, and a conversation may\n * carry several. Edits/attach on a non-open brief fail 409\n * `conversation_brief_not_editable`.\n */\nexport interface ConversationBriefService {\n list(query?: ListConversationBriefsQuery): Promise<ListResponse<ConversationBrief>>\n get(id: string): Promise<ConversationBrief>\n create(request: CreateConversationBriefRequest): Promise<ConversationBrief>\n update(id: string, request: UpdateConversationBriefRequest): Promise<ConversationBrief>\n /** Decline an open brief (prepared → discarded, terminal). */\n discard(id: string): Promise<ConversationBrief>\n /** Bind an open brief to a conversation explicitly (prepared → used). */\n attach(id: string, request: AttachConversationBriefRequest): Promise<ConversationBrief>\n delete(id: string): Promise<void>\n}\n\nclass ConversationBriefServiceImpl implements ConversationBriefService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListConversationBriefsQuery = {}): Promise<ListResponse<ConversationBrief>> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-briefs`,\n query,\n )\n }\n\n get(id: string): Promise<ConversationBrief> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateConversationBriefRequest): Promise<ConversationBrief> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/conversation-briefs`, request)\n }\n\n update(id: string, request: UpdateConversationBriefRequest): Promise<ConversationBrief> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n discard(id: string): Promise<ConversationBrief> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}/discard`,\n )\n }\n\n attach(id: string, request: AttachConversationBriefRequest): Promise<ConversationBrief> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}/attach`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/conversation-briefs/${encodeURIComponent(id)}`,\n )\n }\n}\n\n/**\n * Sending rules — outbound send constraints (windows, connection limits,\n * frequency caps), the static limit-preset catalog and its apply expansion.\n * A denied send/reply/sendDraft fails with a ProteosError whose `details`\n * carry `earliest_allowed_at` (429) or the blocked contact (403).\n */\nexport interface SendingRuleService {\n list(query?: ListSendingRulesQuery): Promise<ListResponse<SendingRule>>\n get(id: string): Promise<SendingRule>\n create(request: CreateSendingRuleRequest): Promise<SendingRule>\n update(id: string, request: UpdateSendingRuleRequest): Promise<SendingRule>\n delete(id: string): Promise<void>\n /** The static preset catalog, optionally narrowed to one connector. */\n listPresets(query?: ListSendingLimitPresetsQuery): Promise<{ data: SendingLimitPreset[] }>\n /**\n * Expand a preset into limit rules linked to the given connections,\n * replacing the limit rules they were linked to before.\n */\n applyPreset(request: ApplySendingLimitPresetRequest): Promise<{ data: SendingRule[] }>\n}\n\nclass SendingRuleServiceImpl implements SendingRuleService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListSendingRulesQuery = {}): Promise<ListResponse<SendingRule>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/sending-rules`, query)\n }\n\n get(id: string): Promise<SendingRule> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/sending-rules/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateSendingRuleRequest): Promise<SendingRule> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/sending-rules`, request)\n }\n\n update(id: string, request: UpdateSendingRuleRequest): Promise<SendingRule> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/sending-rules/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/sending-rules/${encodeURIComponent(id)}`,\n )\n }\n\n listPresets(query: ListSendingLimitPresetsQuery = {}): Promise<{ data: SendingLimitPreset[] }> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/sending-rules/presets`,\n query,\n )\n }\n\n applyPreset(request: ApplySendingLimitPresetRequest): Promise<{ data: SendingRule[] }> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/sending-rules/apply-preset`,\n request,\n )\n }\n}\n\n/**\n * Email signatures: the block an email send adds below the body and above\n * the quote. A send, draft or draft edit picks one with its `signature`\n * field; without it the default applies.\n */\nexport interface EmailSignatureService {\n list(query?: ListEmailSignaturesQuery): Promise<ListResponse<EmailSignature>>\n get(id: string): Promise<EmailSignature>\n create(request: CreateEmailSignatureRequest): Promise<EmailSignature>\n update(id: string, request: UpdateEmailSignatureRequest): Promise<EmailSignature>\n delete(id: string): Promise<void>\n /** The default signature an email would get; `data` is null when none applies. */\n resolve(query?: ResolveEmailSignatureQuery): Promise<{ data: MessageSignature | null }>\n}\n\nclass EmailSignatureServiceImpl implements EmailSignatureService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListEmailSignaturesQuery = {}): Promise<ListResponse<EmailSignature>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/email-signatures`, query)\n }\n\n get(id: string): Promise<EmailSignature> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/email-signatures/${encodeURIComponent(id)}`,\n )\n }\n\n create(request: CreateEmailSignatureRequest): Promise<EmailSignature> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/email-signatures`, request)\n }\n\n update(id: string, request: UpdateEmailSignatureRequest): Promise<EmailSignature> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/email-signatures/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/email-signatures/${encodeURIComponent(id)}`,\n )\n }\n\n resolve(query: ResolveEmailSignatureQuery = {}): Promise<{ data: MessageSignature | null }> {\n return this.client.requestWithQuery(\n 'GET',\n `${CONVERSATION_BASE_PATH}/email-signatures/resolve`,\n query,\n )\n }\n}\n\n/**\n * Message templates: reusable messages and snippets whose subject and body are\n * Liquid templates. A send or a draft names one with its `template` field.\n */\nexport interface MessageTemplateService {\n list(query?: ListMessageTemplatesQuery): Promise<ListResponse<MessageTemplate>>\n /** By id or by key. */\n get(idOrKey: string): Promise<MessageTemplate>\n create(request: CreateMessageTemplateRequest): Promise<MessageTemplate>\n update(id: string, request: UpdateMessageTemplateRequest): Promise<MessageTemplate>\n /** Creates or replaces the template a key names; an equivalent body writes nothing. */\n upsertByKey(\n key: string,\n request: Omit<CreateMessageTemplateRequest, 'key'>,\n ): Promise<MessageTemplate>\n delete(id: string): Promise<void>\n /**\n * Fills in a stored or an inline template: what a send of it would store,\n * with the signature the email would get.\n */\n render(request: RenderMessageTemplateRequest): Promise<RenderedMessageTemplate>\n}\n\nclass MessageTemplateServiceImpl implements MessageTemplateService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListMessageTemplatesQuery = {}): Promise<ListResponse<MessageTemplate>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/message-templates`, query)\n }\n\n get(idOrKey: string): Promise<MessageTemplate> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/message-templates/${encodeURIComponent(idOrKey)}`,\n )\n }\n\n create(request: CreateMessageTemplateRequest): Promise<MessageTemplate> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/message-templates`, request)\n }\n\n update(id: string, request: UpdateMessageTemplateRequest): Promise<MessageTemplate> {\n return this.client.request(\n 'PATCH',\n `${CONVERSATION_BASE_PATH}/message-templates/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n upsertByKey(\n key: string,\n request: Omit<CreateMessageTemplateRequest, 'key'>,\n ): Promise<MessageTemplate> {\n return this.client.request(\n 'PUT',\n `${CONVERSATION_BASE_PATH}/message-templates/${encodeURIComponent(key)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/message-templates/${encodeURIComponent(id)}`,\n )\n }\n\n render(request: RenderMessageTemplateRequest): Promise<RenderedMessageTemplate> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/message-templates/render`,\n request,\n )\n }\n}\n\n/**\n * Channel actions — the ledger of acts performed through a connection that\n * are neither a message nor a reaction (LinkedIn invitations, profile visits,\n * InMail). A denied perform fails like a denied send (ProteosError with\n * `details.earliest_allowed_at`); a provider refusal carries its own code\n * (already_connected, already_invited_recently, invitation_already_received,\n * connection_limit_reached, insufficient_inmail_credits, inmail_not_allowed,\n * not_connected_with_recipient). An invitation is pre-flighted with one silent\n * profile read before anything is sent, so those refusals never mint a\n * phantom act.\n */\nexport interface ChannelActionService {\n list(query?: ListChannelActionsQuery): Promise<ListResponse<ChannelAction>>\n get(id: string): Promise<ChannelAction>\n /** Performs one act; resolves to the row in its post-perform status. */\n perform(request: PerformChannelActionRequest): Promise<ChannelAction>\n /** Withdraws a performed outbound act (an invitation). */\n cancel(id: string): Promise<ChannelAction>\n /** Answers an inbound act (a received invitation). */\n respond(id: string, request: RespondChannelActionRequest): Promise<ChannelAction>\n}\n\nclass ChannelActionServiceImpl implements ChannelActionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListChannelActionsQuery = {}): Promise<ListResponse<ChannelAction>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/channel-actions`, query)\n }\n\n get(id: string): Promise<ChannelAction> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/channel-actions/${encodeURIComponent(id)}`,\n )\n }\n\n perform(request: PerformChannelActionRequest): Promise<ChannelAction> {\n return this.client.request('POST', `${CONVERSATION_BASE_PATH}/channel-actions`, request)\n }\n\n cancel(id: string): Promise<ChannelAction> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/channel-actions/${encodeURIComponent(id)}/cancel`,\n )\n }\n\n respond(id: string, request: RespondChannelActionRequest): Promise<ChannelAction> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/channel-actions/${encodeURIComponent(id)}/respond`,\n request,\n )\n }\n}\n\n/**\n * The channel_event ledger — provider-observed delivery / engagement events\n * about outbound messages (delivered, bounced, opened, clicked,\n * spam_reported, unsubscribed, …). Read-only: rows are appended by webhook\n * ingest. `listByMessage` is the per-message history, oldest first.\n */\nexport interface ChannelEventService {\n list(query?: ListChannelEventsQuery): Promise<ListResponse<ChannelEvent>>\n get(id: string): Promise<ChannelEvent>\n listByMessage(messageId: string): Promise<ListResponse<ChannelEvent>>\n}\n\nclass ChannelEventServiceImpl implements ChannelEventService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListChannelEventsQuery = {}): Promise<ListResponse<ChannelEvent>> {\n return this.client.requestWithQuery('GET', `${CONVERSATION_BASE_PATH}/channel-events`, query)\n }\n\n get(id: string): Promise<ChannelEvent> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/channel-events/${encodeURIComponent(id)}`,\n )\n }\n\n listByMessage(messageId: string): Promise<ListResponse<ChannelEvent>> {\n return this.client.request(\n 'GET',\n `${CONVERSATION_BASE_PATH}/messages/${encodeURIComponent(messageId)}/events`,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type { CreateEntityIndexRequest, EntityIndex, IndexRecommendation } from './types.js'\n\nconst ENTITIES_BASE_PATH = '/data/v1/entities'\n\n/**\n * Per-entity indexes on the record table and the advisor's recommendations.\n * Admin surface: gated on the `entities` permission, not on record access.\n */\nexport interface EntityIndexService {\n /** Every index of the entity (declared, automatic, applied) with live state. */\n list(entitySlug: string): Promise<EntityIndex[]>\n /** The advisor's current suggestions for the entity. */\n recommendations(entitySlug: string): Promise<IndexRecommendation[]>\n /** Applies one lookup/search index; returns it in `building` state. */\n create(entitySlug: string, request: CreateEntityIndexRequest): Promise<EntityIndex>\n /** Removes one APPLIED index (declared/automatic → 409 entity_index_not_deletable). */\n delete(entitySlug: string, name: string): Promise<void>\n}\n\nexport class EntityIndexServiceImpl implements EntityIndexService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(entitySlug: string): Promise<EntityIndex[]> {\n const response = await this.client.request<{ data: EntityIndex[] }>(\n 'GET',\n `${ENTITIES_BASE_PATH}/${encodeURIComponent(entitySlug)}/indexes`,\n )\n return response.data\n }\n\n async recommendations(entitySlug: string): Promise<IndexRecommendation[]> {\n const response = await this.client.request<{ data: IndexRecommendation[] }>(\n 'GET',\n `${ENTITIES_BASE_PATH}/${encodeURIComponent(entitySlug)}/index-recommendations`,\n )\n return response.data\n }\n\n async create(entitySlug: string, request: CreateEntityIndexRequest): Promise<EntityIndex> {\n return this.client.request<EntityIndex>(\n 'POST',\n `${ENTITIES_BASE_PATH}/${encodeURIComponent(entitySlug)}/indexes`,\n request,\n )\n }\n\n async delete(entitySlug: string, name: string): Promise<void> {\n await this.client.request<void>(\n 'DELETE',\n `${ENTITIES_BASE_PATH}/${encodeURIComponent(entitySlug)}/indexes/${encodeURIComponent(name)}`,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type { FilterGroup } from '../meta/filters.js'\nimport type { ListResult, UserRef } from '../types/common.js'\n\nconst QUERY_BASE_PATH = '/data/v1/query'\nconst QUERIES_BASE_PATH = '/data/v1/queries'\n\n/**\n * A single row from a query result. Keys match the result-set columns\n * (camelCase, with `id`/`created_at`/`updated_at` reserved). The data-service\n * hoists JSONB columns into nested objects, so values can be primitives,\n * nested records, or arrays.\n */\nexport type QueryRow = Record<string, unknown>\n\nexport interface QueryExecuteMeta {\n columns: string[]\n items: number\n limit_applied: number\n /** Only present when `true`. */\n was_default_limit_applied?: boolean\n execution_time_ms: number\n}\n\nexport interface QueryExecuteResponse {\n data: QueryRow[]\n meta?: QueryExecuteMeta\n}\n\nexport interface QueryValidateMeta {\n limit_applied: number\n was_default_limit_applied?: boolean\n}\n\nexport interface QueryValidateResponse {\n valid: boolean\n /** The SQL the server would execute (entity-rewritten, schema-qualified). */\n rewritten_sql?: string\n tables?: string[]\n meta?: QueryValidateMeta\n}\n\n/**\n * The visual editor's state for a {@link Query}: the entity it reads, the\n * selected column paths (relation fields are prefixed with the foreign-key\n * attribute, e.g. `accountId.name`) and the filter. It only reopens the\n * editor — `sql` is what runs.\n */\nexport interface QueryBuilder {\n entity_slug: string\n columns: string[]\n filter?: FilterGroup\n}\n\n/**\n * A stored SQL query. Running it is `execute(query.sql)` as the viewer, so a\n * query never carries data access with it. `created_by` is the owner;\n * everyone else reaches it through a share on the `queries` slug.\n */\nexport interface Query {\n id: string\n org_id: string\n name: string\n sql: string\n /** Absent for a query that was never built visually. */\n builder?: QueryBuilder\n /** Whether the caller may update this query. Computed per request. */\n can_write: boolean\n created_at: string\n created_by: UserRef\n updated_at: string\n updated_by: UserRef\n}\n\nexport interface CreateQueryRequest {\n name: string\n sql: string\n builder?: QueryBuilder\n}\n\n/** An absent field keeps its value. */\nexport interface UpdateQueryRequest {\n name?: string\n sql?: string\n builder?: QueryBuilder\n}\n\nexport interface ListQueriesQuery {\n page?: number\n page_size?: number\n}\n\n/**\n * Service for the query endpoints of the data-service: running raw SQL and\n * storing queries to run again.\n *\n * Accepts SELECT-only Postgres SQL with bare attribute references; the\n * server rewrites bare attributes into JSONB accessors against the\n * tenant's schema and runs per-table OpenFGA authorization checks.\n */\nexport interface QueryService {\n /** Executes the SQL and returns the result rows + meta. */\n execute(sql: string): Promise<QueryExecuteResponse>\n /** Parses + authorizes the SQL without running it. */\n validate(sql: string): Promise<QueryValidateResponse>\n\n /** The caller's own queries and those shared with them, ordered by name. */\n list(query?: ListQueriesQuery): Promise<ListResult<Query>>\n /** 404 `query_not_found` when the caller cannot see the query. */\n get(id: string): Promise<Query>\n /** Stores the query; the caller becomes its owner. Nothing is executed. */\n create(request: CreateQueryRequest): Promise<Query>\n /** 403 `queries_write_not_permitted` when the caller can only read it. */\n update(id: string, request: UpdateQueryRequest): Promise<Query>\n /** Deletes the query and its shares. */\n delete(id: string): Promise<void>\n}\n\nexport class QueryServiceImpl implements QueryService {\n constructor(private readonly client: ProteosClient) {}\n\n async execute(sql: string): Promise<QueryExecuteResponse> {\n return this.client.request<QueryExecuteResponse>('POST', `${QUERY_BASE_PATH}/execute`, { sql })\n }\n\n async validate(sql: string): Promise<QueryValidateResponse> {\n return this.client.request<QueryValidateResponse>('POST', `${QUERY_BASE_PATH}/validate`, {\n sql,\n })\n }\n\n async list(query: ListQueriesQuery = {}): Promise<ListResult<Query>> {\n return this.client.requestWithQuery<ListResult<Query>>('GET', QUERIES_BASE_PATH, query)\n }\n\n async get(id: string): Promise<Query> {\n return this.client.request<Query>('GET', `${QUERIES_BASE_PATH}/${encodeURIComponent(id)}`)\n }\n\n async create(request: CreateQueryRequest): Promise<Query> {\n return this.client.request<Query>('POST', QUERIES_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateQueryRequest): Promise<Query> {\n return this.client.request<Query>(\n 'PATCH',\n `${QUERIES_BASE_PATH}/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${QUERIES_BASE_PATH}/${encodeURIComponent(id)}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n ApproveRecordDraftRequest,\n CreateRecordDraftRequest,\n ListRecordDraftsQuery,\n ProposedValuesQuery,\n RecordDraft,\n RecordDraftProposedValue,\n RecordDraftVersions,\n RejectRecordDraftRequest,\n UpdateRecordDraftRequest,\n} from './types.js'\n\nconst RECORD_DRAFTS_BASE_PATH = '/data/v1/record-drafts'\n\n/**\n * Proposed record writes awaiting a verdict. `create` needs\n * `record-drafts:write`; `approve` additionally needs `write` (create / update /\n * upsert) or `delete` (delete) on every entity whose items are applied,\n * because the writes run as the caller. A draft can hold items of several\n * entities that reference each other by `transaction_id`. The status is\n * derived server-side from the per-item verdicts.\n */\nexport interface RecordDraftService {\n /** The org's drafts — `proposed` by default. */\n list(query?: ListRecordDraftsQuery): Promise<ListResult<RecordDraft>>\n get(id: string): Promise<RecordDraft>\n create(request: CreateRecordDraftRequest): Promise<RecordDraft>\n /**\n * Saves a proposed draft's items (a proposer's revision or a reviewer's\n * edit) — nothing is written to the records. 409 `record_draft_conflict`\n * when `expected_updated_at` is stale, `record_draft_not_proposed` once\n * resolved.\n */\n update(id: string, request: UpdateRecordDraftRequest): Promise<RecordDraft>\n /** The draft's history and what reviewers changed so far. */\n listVersions(id: string): Promise<RecordDraftVersions>\n /**\n * Applies the draft as the caller. No `items` = its items as they stand;\n * `items` = the reviewer's edit, saved first. `transaction_ids` /\n * `attributes` apply only that part (plus the not-yet-written items it\n * references). Always 200 with the draft: `status` is terminal once every\n * item has a verdict, else still `proposed` with `verdicts` (what is\n * decided) and per-item `results` (what failed, to fix and re-approve). 409\n * `record_draft_not_proposed` once resolved, `record_draft_already_decided`\n * when the scope holds nothing undecided.\n */\n approve(id: string, request?: ApproveRecordDraftRequest): Promise<RecordDraft>\n /**\n * Declines the draft, or the part `transaction_ids` / `attributes` name —\n * nothing is written. 409 `record_draft_not_proposed` once resolved.\n */\n reject(id: string, request?: RejectRecordDraftRequest): Promise<RecordDraft>\n /**\n * What proposed drafts would still write to records of one entity, one row\n * per value, with the record's current value and the proposer's evidence.\n * Needs `read` on the entity; records and attributes the caller may not\n * read are left out.\n */\n proposedValues(query: ProposedValuesQuery): Promise<RecordDraftProposedValue[]>\n}\n\nexport class RecordDraftServiceImpl implements RecordDraftService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(query: ListRecordDraftsQuery = {}): Promise<ListResult<RecordDraft>> {\n return this.client.requestWithQuery<ListResult<RecordDraft>>(\n 'GET',\n RECORD_DRAFTS_BASE_PATH,\n query,\n )\n }\n\n async get(id: string): Promise<RecordDraft> {\n return this.client.request<RecordDraft>(\n 'GET',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}`,\n )\n }\n\n async create(request: CreateRecordDraftRequest): Promise<RecordDraft> {\n return this.client.request<RecordDraft>('POST', RECORD_DRAFTS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateRecordDraftRequest): Promise<RecordDraft> {\n return this.client.request<RecordDraft>(\n 'PUT',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}`,\n request,\n )\n }\n\n async listVersions(id: string): Promise<RecordDraftVersions> {\n return this.client.request<RecordDraftVersions>(\n 'GET',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}/versions`,\n )\n }\n\n async approve(id: string, request: ApproveRecordDraftRequest = {}): Promise<RecordDraft> {\n return this.client.request<RecordDraft>(\n 'POST',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}/approve`,\n request,\n )\n }\n\n async reject(id: string, request: RejectRecordDraftRequest = {}): Promise<RecordDraft> {\n return this.client.request<RecordDraft>(\n 'POST',\n `${RECORD_DRAFTS_BASE_PATH}/${encodeURIComponent(id)}/reject`,\n request,\n )\n }\n\n async proposedValues(query: ProposedValuesQuery): Promise<RecordDraftProposedValue[]> {\n const response = await this.client.requestWithQuery<{ data: RecordDraftProposedValue[] }>(\n 'GET',\n `${RECORD_DRAFTS_BASE_PATH}/proposed-values`,\n {\n entity_slug: query.entity_slug,\n ...(query.record_ids && query.record_ids.length > 0\n ? { record_ids: query.record_ids.join(',') }\n : {}),\n },\n )\n return response.data ?? []\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n BatchUpsertRecordsResponse,\n BatchUpsertTransaction,\n ListRecordDuplicatesQuery,\n ListRecordsOptions,\n PublishContactObservationsResponse,\n RecordData,\n RecordDuplicate,\n} from './types.js'\n\nconst RECORDS_BASE_PATH = '/data/v1/records'\nconst BATCH_RECORDS_BASE_PATH = '/data/v1/batch/records'\nconst PUBLIC_RECORDS_BASE_PATH = '/data/v1/public/orgs'\n\n/**\n * Service for managing records (per-entity data rows) via the data-service.\n *\n * Records are opaque JSON objects whose schema is defined per-entity in the\n * metadata service. An entity must be registered (via metadata-service, which\n * in turn provisions a Postgres table) before records for it can be created.\n */\nexport interface RecordService {\n /**\n * Lists records for an entity as an async iterator. Pages are 0-indexed\n * (first page is 0); `PageIterator` starts there automatically.\n */\n list(\n entitySlug: string,\n options?: ListRecordsOptions,\n ): PageIterator<RecordData, ListRecordsOptions>\n\n /**\n * Fetches a single page of records.\n */\n listPage(entitySlug: string, options?: ListRecordsOptions): Promise<ListResult<RecordData>>\n\n /**\n * Gets a single record by id.\n * @throws {ProteosError} If the record is not found (404).\n */\n get(entitySlug: string, id: string): Promise<RecordData>\n\n /**\n * Creates a new record for the given entity.\n */\n create(entitySlug: string, data: RecordData): Promise<RecordData>\n\n /**\n * Partially updates a record.\n */\n update(entitySlug: string, id: string, data: Partial<RecordData>): Promise<RecordData>\n\n /**\n * Deletes a record.\n */\n delete(entitySlug: string, id: string): Promise<void>\n\n /**\n * Batch-upserts records. Each transaction succeeds/fails independently;\n * the response contains a per-transaction status so callers (e.g. import\n * flows) can render per-row feedback.\n */\n batchUpsert(\n entitySlug: string,\n transactions: BatchUpsertTransaction[],\n ): Promise<BatchUpsertRecordsResponse>\n\n /**\n * Lists records of a public-read entity through the UNAUTHENTICATED\n * public endpoint (no Authorization header) as an async iterator. A\n * non-public or missing entity 404s identically.\n */\n listPublic(\n orgId: string,\n entitySlug: string,\n options?: ListRecordsOptions,\n ): PageIterator<RecordData, ListRecordsOptions>\n\n /**\n * Fetches a single page of records through the unauthenticated public\n * endpoint. Same filter grammar and pagination as `listPage`.\n */\n listPublicPage(\n orgId: string,\n entitySlug: string,\n options?: ListRecordsOptions,\n ): Promise<ListResult<RecordData>>\n\n /**\n * Gets a single record of a public-read entity through the\n * unauthenticated public endpoint. Knowledge-text values stay unenriched\n * (bare refs) on this path.\n */\n getPublic(orgId: string, entitySlug: string, id: string): Promise<RecordData>\n /**\n * Replays ONE page of the entity's records as record_contact_observation\n * events (the backfill after an attribute became contact-address). Requires\n * unscoped write on the entity; loop until `page + 1 >= pages_total`.\n */\n publishContactObservations(\n entitySlug: string,\n options?: { page?: number; page_size?: number },\n ): Promise<PublishContactObservationsResponse>\n}\n\n/**\n * Record duplicates — \"these two records may be the same thing\" pairs of one\n * entity (see `RecordDuplicate`). Reading = entity read, dismissing = entity write.\n */\nexport interface RecordDuplicateService {\n list(entitySlug: string, query?: ListRecordDuplicatesQuery): Promise<ListResult<RecordDuplicate>>\n get(entitySlug: string, id: string): Promise<RecordDuplicate>\n /** Closes a pair as \"not a duplicate\" (409 `record_duplicate_not_open` when already closed). */\n dismiss(entitySlug: string, id: string): Promise<RecordDuplicate>\n}\n\n/**\n * Implementation of RecordService.\n */\nexport class RecordServiceImpl implements RecordService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n entitySlug: string,\n options: ListRecordsOptions = {},\n ): PageIterator<RecordData, ListRecordsOptions> {\n return new PageIterator((opts) => this.listPage(entitySlug, opts), options)\n }\n\n async listPage(\n entitySlug: string,\n options: ListRecordsOptions = {},\n ): Promise<ListResult<RecordData>> {\n return this.client.requestWithQuery<ListResult<RecordData>>(\n 'GET',\n `${RECORDS_BASE_PATH}/${entitySlug}`,\n options,\n )\n }\n\n async get(entitySlug: string, id: string): Promise<RecordData> {\n return this.client.request<RecordData>('GET', `${RECORDS_BASE_PATH}/${entitySlug}/${id}`)\n }\n\n async create(entitySlug: string, data: RecordData): Promise<RecordData> {\n return this.client.request<RecordData>('POST', `${RECORDS_BASE_PATH}/${entitySlug}`, data)\n }\n\n async update(entitySlug: string, id: string, data: Partial<RecordData>): Promise<RecordData> {\n return this.client.request<RecordData>(\n 'PATCH',\n `${RECORDS_BASE_PATH}/${entitySlug}/${id}`,\n data,\n )\n }\n\n async delete(entitySlug: string, id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${RECORDS_BASE_PATH}/${entitySlug}/${id}`)\n }\n\n async batchUpsert(\n entitySlug: string,\n transactions: BatchUpsertTransaction[],\n ): Promise<BatchUpsertRecordsResponse> {\n return this.client.request<BatchUpsertRecordsResponse>(\n 'POST',\n `${BATCH_RECORDS_BASE_PATH}/${entitySlug}/upsert`,\n transactions,\n )\n }\n\n async publishContactObservations(\n entitySlug: string,\n options: { page?: number; page_size?: number } = {},\n ): Promise<PublishContactObservationsResponse> {\n return this.client.requestWithQuery<PublishContactObservationsResponse>(\n 'POST',\n `${RECORDS_BASE_PATH}/${entitySlug}/contact-observations`,\n options,\n )\n }\n\n listPublic(\n orgId: string,\n entitySlug: string,\n options: ListRecordsOptions = {},\n ): PageIterator<RecordData, ListRecordsOptions> {\n return new PageIterator((opts) => this.listPublicPage(orgId, entitySlug, opts), options)\n }\n\n async listPublicPage(\n orgId: string,\n entitySlug: string,\n options: ListRecordsOptions = {},\n ): Promise<ListResult<RecordData>> {\n return this.client.requestWithQuery<ListResult<RecordData>>(\n 'GET',\n `${PUBLIC_RECORDS_BASE_PATH}/${encodeURIComponent(orgId)}/records/${encodeURIComponent(entitySlug)}`,\n options,\n undefined,\n { skipAuth: true },\n )\n }\n\n async getPublic(orgId: string, entitySlug: string, id: string): Promise<RecordData> {\n return this.client.request<RecordData>(\n 'GET',\n `${PUBLIC_RECORDS_BASE_PATH}/${encodeURIComponent(orgId)}/records/${encodeURIComponent(entitySlug)}/${encodeURIComponent(id)}`,\n undefined,\n { skipAuth: true },\n )\n }\n}\n\nexport class RecordDuplicateServiceImpl implements RecordDuplicateService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(\n entitySlug: string,\n query: ListRecordDuplicatesQuery = {},\n ): Promise<ListResult<RecordDuplicate>> {\n return this.client.requestWithQuery<ListResult<RecordDuplicate>>(\n 'GET',\n `${RECORDS_BASE_PATH}/${entitySlug}/duplicates`,\n query,\n )\n }\n\n async get(entitySlug: string, id: string): Promise<RecordDuplicate> {\n return this.client.request<RecordDuplicate>(\n 'GET',\n `${RECORDS_BASE_PATH}/${entitySlug}/duplicates/${encodeURIComponent(id)}`,\n )\n }\n\n async dismiss(entitySlug: string, id: string): Promise<RecordDuplicate> {\n return this.client.request<RecordDuplicate>(\n 'POST',\n `${RECORDS_BASE_PATH}/${entitySlug}/duplicates/${encodeURIComponent(id)}/dismiss`,\n )\n }\n}\n","import { z } from 'zod'\n\n/**\n * A record is an open-shape JSON object whose keys are the entity's attribute\n * names plus system fields (`id`, `created_at`, `updated_at`, `created_by`,\n * `updated_by`). Because attributes vary per entity, values are typed as `any`\n * at the SDK layer — consumers narrow or cast as needed.\n */\nexport type RecordData = Record<string, any>\n\n/**\n * Options for listing records.\n *\n * Sorting: use `sort: \"field:asc\"` for single-column; pipe-separated for\n * multi-column (`\"field1:asc|field2:desc\"`). Defaults to `created_at:desc`.\n *\n * Arbitrary filter keys pass through as query params. Supported operators\n * (via bracket syntax) include `[eq]`, `[ne]`, `[gt]`, `[gte]`, `[lt]`,\n * `[lte]`, `[in]` (pipe-separated), `[not_in]`, `[contains]`, `[not_contains]`,\n * `[contains_all]` (pipe-separated, arrays only), `[starts_with]`, `[ends_with]`,\n * `[empty]`, `[not_empty]`. Missing operator defaults to `[eq]`. On array\n * attributes contains / not_contains / in / not_in / contains_all are\n * set-membership tests (has / does not have / has any of / has none of / has all of).\n * A filter key may reach one hop through a relation attribute with a dotted\n * path (`\"company_id.name[contains]\": \"acme\"`).\n *\n * For nested AND/OR trees, pass a filter group (the same wire dialect as\n * `List.filters` / `visible_when`: `{logical_operator, elements: [{field,\n * operator, value}], groups}`, string values, pipe-joined for in/not_in/contains_all)\n * JSON-encoded under the reserved `_filter` key:\n * `{ _filter: JSON.stringify(group) }`. The server ANDs it with any flat\n * filter params.\n */\nexport interface ListRecordsOptions {\n /** Page number (0-indexed). First page is 0. */\n page?: number\n /** Number of items per page (default: 20 per backend) */\n page_size?: number\n /**\n * Sort spec. Format: `\"field:direction\"`, or pipe-separated for multi-column:\n * `\"field1:asc|field2:desc\"`. Direction is `asc` | `desc`.\n */\n sort?: string\n /** Arbitrary attribute filters (flat query-string params). */\n [key: string]: unknown\n}\n\n// ============================================================================\n// Batch operations\n// ============================================================================\n\n/**\n * One transaction within a batch operation.\n * `transaction_id` is client-supplied so you can match results back to your\n * source rows (used e.g. by import flows).\n */\nexport interface BatchUpsertTransaction {\n transaction_id: string\n data: Record<string, unknown>\n}\n\nexport type BatchTransactionStatus = 'success' | 'error'\n\nexport interface BatchTransactionError {\n code: string\n message: string\n}\n\nexport interface BatchUpsertTransactionResult {\n transaction_id: string\n status: BatchTransactionStatus\n record?: RecordData\n error?: BatchTransactionError\n}\n\nexport interface BatchUpsertRecordsResponse {\n results: BatchUpsertTransactionResult[]\n}\n\n// Zod schemas for runtime validation (optional, for consumers who want it)\n\nexport const BatchUpsertTransactionSchema = z.object({\n transaction_id: z.string(),\n data: z.record(z.unknown()),\n})\n\nexport const BatchTransactionErrorSchema = z.object({\n code: z.string(),\n message: z.string(),\n})\n\nexport const BatchUpsertTransactionResultSchema = z.object({\n transaction_id: z.string(),\n status: z.enum(['success', 'error']),\n record: z.record(z.unknown()).optional(),\n error: BatchTransactionErrorSchema.optional(),\n})\n\nexport const BatchUpsertRecordsResponseSchema = z.object({\n results: z.array(BatchUpsertTransactionResultSchema),\n})\n\n// ── Record duplicates ─────────────────────────────────────────────────────────\n\n/** How a duplicate pair was detected. `contact_binding` = two records bound to\n * the same conversation contact through their contact-address attributes. */\nexport type RecordDuplicateSource = 'contact_binding' | (string & {})\n\nexport type RecordDuplicateStatus = 'open' | 'dismissed' | 'resolved'\n\n/**\n * \"These two records of one entity may be the same thing.\" Asymmetric:\n * `primary_record_id` is the record to keep, `secondary_record_id` the\n * newcomer. A group of colliding records has ONE primary and one row per other\n * member (four records = three rows). `evidence` is shaped by `source` — for\n * `contact_binding`: `{ contact_id, address_keys: [{kind, value}] }`.\n */\nexport interface RecordDuplicate {\n id: string\n org_id: string\n entity_slug: string\n primary_record_id: string\n secondary_record_id: string\n source: RecordDuplicateSource\n evidence: Record<string, unknown>\n status: RecordDuplicateStatus\n resolved_by?: { type: string; id: string }\n resolved_at?: string\n created_at: string\n created_by: { type: string; id: string }\n updated_at: string\n updated_by: { type: string; id: string }\n}\n\nexport interface ListRecordDuplicatesQuery {\n /** Only pairs this record takes part in (either side). */\n record_id?: string\n /** Defaults to `open` on the server. */\n status?: RecordDuplicateStatus\n page?: number\n page_size?: number\n}\n\n// ── Record drafts ─────────────────────────────────────────────────────────────\n\n/** WHAT a draft proposes to do to the entity's records. Record-only, hence the\n * short verbs; the page-button intent vocabulary (`create_record`, …) is mapped\n * at the UI boundary. */\nexport type RecordDraftIntent = 'create' | 'update' | 'delete' | 'upsert'\n\n/** The review lifecycle: `proposed` awaits a verdict; `approved` was applied\n * exactly as proposed; `approved_with_changes` was edited, then applied\n * (`changes` says what the reviewer altered); `rejected` was never applied.\n * The last three are terminal. The status is DERIVED by the server from the\n * per-item `verdicts` and `changes` — a resolver never names the outcome: a\n * draft stays `proposed` until every item has a verdict; then all accepted ⇒\n * `approved`, all rejected ⇒ `rejected`, anything else ⇒\n * `approved_with_changes`. */\nexport type RecordDraftStatus = 'proposed' | 'approved' | 'approved_with_changes' | 'rejected'\n\n/**\n * ONE proposed write, keyed like a batch transaction. Shape per intent —\n * create: `data`, no `id` · update: `id` + `data` · delete: `id`, no `data` ·\n * upsert: `data`, `id` optional (present ⇒ update, absent ⇒ create). `id` never\n * rides inside `data`. Update/upsert `data` is a partial merge (only the keys\n * present change).\n *\n * `entity_slug` is the entity this item writes; absent = the draft's own. A\n * relation attribute in `data` can point at ANOTHER ITEM of the draft instead\n * of a record id — `{ transaction_id: '1' }` ({@link RecordDraftReference}) —\n * and is resolved to that item's record id on approve, parents first.\n * `evidence` says where a proposed value came from, per attribute of `data`.\n */\nexport interface RecordDraftItem {\n transaction_id: string\n entity_slug?: string\n id?: string\n data?: Record<string, unknown>\n evidence?: Record<string, RecordDraftEvidence>\n}\n\n/** A relation value pointing at another item of the same draft. */\nexport interface RecordDraftReference {\n transaction_id: string\n}\n\n/** Whether a proposed value is a {@link RecordDraftReference}: an object\n * whose only key is a string `transaction_id`. */\nexport function isRecordDraftReference(value: unknown): value is RecordDraftReference {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const keys = Object.keys(value)\n return (\n keys.length === 1 &&\n keys[0] === 'transaction_id' &&\n typeof (value as RecordDraftReference).transaction_id === 'string'\n )\n}\n\n/** One source behind a proposed value. */\nexport interface RecordDraftCitation {\n title?: string\n url?: string\n snippet?: string\n}\n\n/** Why the proposer believes ONE proposed value: a short label, how sure it\n * is (0..1) and the sources. All optional. */\nexport interface RecordDraftEvidence {\n label?: string\n confidence?: number\n citations?: RecordDraftCitation[]\n}\n\n/** A reviewer's decision on an item or on one attribute of it. `edited` (items\n * only): written, but not exactly as proposed. */\nexport type RecordDraftVerdict = 'accepted' | 'edited' | 'rejected'\n\n/** What has been decided about ONE item so far. `verdict` is set once the\n * whole item is decided; while only some attributes are, it is absent and\n * `attributes` names them. */\nexport interface RecordDraftItemVerdict {\n transaction_id: string\n verdict?: RecordDraftVerdict\n attributes?: Record<string, Exclude<RecordDraftVerdict, 'edited'>>\n}\n\n/** Narrows an approve or a reject to part of a draft: `transaction_ids` picks\n * the items (absent = every undecided item), `attributes` the attributes of\n * those items (absent = all). An item that would create a record is decided\n * whole — naming it together with attributes fails with 400\n * `record_draft_scope_invalid`. */\nexport interface RecordDraftScope {\n transaction_ids?: string[]\n attributes?: string[]\n}\n\n/**\n * ONE value a proposed draft would write, next to what the record holds now —\n * the flat read model behind the suggestions overlay. `record_id` is absent\n * for a value of a record the draft would create. Only undecided values of\n * proposed drafts appear, never an attribute the reader may not read.\n */\nexport interface RecordDraftProposedValue {\n record_id?: string\n attribute: string\n current: unknown\n proposed: unknown\n evidence?: RecordDraftEvidence\n record_draft_id: string\n transaction_id: string\n created_at: string\n /**\n * The draft's `updated_at` when the value was read. Pass it as\n * `expected_updated_at` when approving or rejecting this value: a draft\n * revised since is refused (409 `record_draft_conflict`) instead of deciding\n * a value nobody saw.\n */\n record_draft_updated_at: string\n}\n\nexport interface ProposedValuesQuery {\n entity_slug: string\n /** At most 200. Values of records a draft would create are returned either way. */\n record_ids?: string[]\n}\n\nexport type RecordDraftItemResultStatus = 'success' | 'error'\n\n/** The same facts the single-record endpoint would have answered with. */\nexport interface RecordDraftItemError {\n code: string\n message: string\n status?: number\n details?: Record<string, unknown>\n}\n\n/** The outcome of applying one item — the batch result minus the record. */\nexport interface RecordDraftItemResult {\n transaction_id: string\n status: RecordDraftItemResultStatus\n record_id?: string\n error?: RecordDraftItemError\n}\n\n/** ONE thing the reviewer altered before applying. */\nexport type RecordDraftChangeKind =\n | 'item_dropped'\n | 'attribute_changed'\n | 'attribute_removed'\n | 'attribute_added'\n /** The reviewer added a whole item (a row); `applied` carries its data. */\n | 'item_added'\n\n/**\n * One entry of the reviewer's delta, diffed against the proposer's LATEST\n * version (the proposal, or the proposer's last revision of it).\n * `proposed` and `applied` are always present — `null` means \"cleared\".\n * `current` is the record's value BEFORE the write, captured for existing\n * targets (`has_current` says whether it was); it is STORED for the proposer\n * to learn from but NOT yet exposed by the API — responses carry it redacted\n * (`has_current: false`, `current: null`) because a draft reader may not be\n * allowed to read the record or that attribute.\n */\nexport interface RecordDraftChange {\n transaction_id: string\n kind: RecordDraftChangeKind\n attribute?: string\n has_current: boolean\n current: unknown\n proposed: unknown\n applied: unknown\n}\n\n/**\n * A PROPOSED record write awaiting a verdict — the record sibling of a draft\n * message. `items` is the draft as it stands now: the proposal, as revised by\n * its proposer and edited by reviewers while proposed (each save is a\n * {@link RecordDraftVersion}; `version` is the newest one's number);\n * `applied_items` what approves have sent so far; `results` the latest outcome\n * per transaction_id; `verdicts` what has been decided, per item and — for a\n * scoped approve or reject — per attribute (an approve only sends what is\n * undecided, so a re-approve never repeats a write); `changes` the reviewer's\n * delta. `entity_slug` is the entity of every item that names none,\n * `entity_slugs` every entity the items write. `source` is caller-supplied\n * provenance (`agent_key`, `session_id`, …); `created_by` is the acting user.\n */\nexport interface RecordDraft {\n id: string\n org_id: string\n entity_slug: string\n entity_slugs: string[]\n intent: RecordDraftIntent\n status: RecordDraftStatus\n summary: string\n items: RecordDraftItem[]\n version: number\n applied_items?: RecordDraftItem[]\n results?: RecordDraftItemResult[]\n changes?: RecordDraftChange[]\n verdicts?: RecordDraftItemVerdict[]\n source?: Record<string, unknown>\n reason?: string\n resolved_by?: { type: string; id: string }\n resolved_at?: string\n created_at: string\n created_by: { type: string; id: string }\n updated_at: string\n updated_by: { type: string; id: string }\n /** Set while an approve is writing the draft's records: saves, rejects and\n * other approves get 409 `record_draft_applying` until it is done. */\n applying_since?: string\n}\n\nexport interface CreateRecordDraftRequest {\n /** The entity of every item that names none. May be left out when every\n * item carries its own `entity_slug`. */\n entity_slug?: string\n intent: RecordDraftIntent\n /** 1..200 items; a missing `transaction_id` becomes the 1-based index. */\n items: RecordDraftItem[]\n /** The proposer's one-line why — required. */\n summary: string\n source?: Record<string, unknown>\n}\n\n/** An item as a save or an approve sends it: an existing item keeps its\n * `transaction_id`; an added one leaves it out and the server assigns one. */\nexport type RecordDraftItemInput = Omit<RecordDraftItem, 'transaction_id'> & {\n transaction_id?: string\n}\n\n/** `items` absent = apply the draft's items as they stand; present = save them\n * first as the reviewer's edit, then apply them. `transaction_ids` /\n * `attributes` apply only that part; the rest stays proposed. */\nexport interface ApproveRecordDraftRequest extends RecordDraftScope {\n items?: RecordDraftItemInput[]\n /** The `updated_at` the reviewer last saw: a draft that moved on since fails\n * with 409 `record_draft_conflict` instead of applying what they never saw. */\n expected_updated_at?: string\n}\n\n/**\n * How a version of a draft came to be: `proposed` (version 1), `revised` (the\n * proposer changed its proposal — it becomes the baseline reviewer changes\n * are measured against) or `edited` (a reviewer's edit; one reviewer's\n * consecutive saves update one version).\n */\nexport type RecordDraftVersionKind = 'proposed' | 'revised' | 'edited'\n\n/** One step of a draft's history: its complete items as they stood after it. */\nexport interface RecordDraftVersion {\n id: string\n org_id: string\n record_draft_id: string\n version: number\n kind: RecordDraftVersionKind\n summary: string\n items: RecordDraftItem[]\n created_at: string\n created_by: { type: string; id: string }\n updated_at: string\n updated_by: { type: string; id: string }\n}\n\n/**\n * Saves a PROPOSED draft's items — the complete set: an item left out is\n * dropped, an item without `transaction_id` is added (the server gives it a\n * fresh one). An existing item keeps its record `id`; an item an earlier\n * approve already wrote must stay exactly as applied. Nothing is written to\n * the records.\n */\nexport interface UpdateRecordDraftRequest {\n items: RecordDraftItemInput[]\n /** Absent keeps the summary. */\n summary?: string\n /** `revised` = the proposer; `edited` = a reviewer. */\n kind: Exclude<RecordDraftVersionKind, 'proposed'>\n /** The `updated_at` the editor last saw: a draft that moved on since fails\n * with 409 `record_draft_conflict`. Omit for last write wins. */\n expected_updated_at?: string\n}\n\n/** A draft's history (oldest first) and what reviewers changed so far. */\nexport interface RecordDraftVersions {\n data: RecordDraftVersion[]\n changes: RecordDraftChange[]\n}\n\n/** `transaction_ids` / `attributes` decline only that part; without either\n * everything still undecided is declined. */\nexport interface RejectRecordDraftRequest extends RecordDraftScope {\n reason?: string\n /** The `updated_at` the reviewer last saw: a draft that moved on since fails\n * with 409 `record_draft_conflict` instead of declining what they never saw. */\n expected_updated_at?: string\n}\n\nexport interface ListRecordDraftsQuery {\n /** Drafts holding an item of this entity. */\n entity_slug?: string\n /** Defaults to `proposed` on the server. */\n status?: RecordDraftStatus\n intent?: RecordDraftIntent\n /** Only drafts whose items name this record. */\n record_id?: string\n page?: number\n page_size?: number\n}\n\nexport const RecordDraftEvidenceSchema = z.object({\n label: z.string().optional(),\n confidence: z.number().min(0).max(1).optional(),\n citations: z\n .array(\n z.object({\n title: z.string().optional(),\n url: z.string().optional(),\n snippet: z.string().optional(),\n }),\n )\n .optional(),\n})\n\nexport const RecordDraftItemSchema = z.object({\n transaction_id: z.string(),\n entity_slug: z.string().optional(),\n id: z.string().optional(),\n data: z.record(z.string(), z.unknown()).optional(),\n evidence: z.record(z.string(), RecordDraftEvidenceSchema).optional(),\n})\n\nexport const RecordDraftItemResultSchema = z.object({\n transaction_id: z.string(),\n status: z.enum(['success', 'error']),\n record_id: z.string().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n status: z.number().optional(),\n details: z.record(z.string(), z.unknown()).optional(),\n })\n .optional(),\n})\n\nexport const RecordDraftChangeSchema = z.object({\n transaction_id: z.string(),\n kind: z.enum([\n 'item_dropped',\n 'attribute_changed',\n 'attribute_removed',\n 'attribute_added',\n 'item_added',\n ]),\n attribute: z.string().optional(),\n has_current: z.boolean(),\n current: z.unknown(),\n proposed: z.unknown(),\n applied: z.unknown(),\n})\n\n/** ONE page of an entity's records replayed as contact observations. */\nexport interface PublishContactObservationsResponse {\n entity_slug: string\n page: number\n page_size: number\n pages_total: number\n items_total: number\n published: number\n skipped: number\n}\n\n// ============================================================================\n// Entity indexes (per-org indexes on an entity's record table)\n// ============================================================================\n\n/** Named by what it does: lookup (=, IN, ranges, sort), unique (lookup that\n * refuses duplicates), search (substring match on one string attribute). */\nexport type EntityIndexType = 'lookup' | 'unique' | 'search'\n\n/** declared = from the entity (is_unique / unique_constraints); automatic =\n * the platform's relation/user indexes; applied = added per org by an admin. */\nexport type EntityIndexSource = 'declared' | 'automatic' | 'applied'\n\nexport type EntityIndexState = 'ready' | 'building' | 'invalid' | 'missing'\n\nexport interface EntityIndex {\n name: string\n type: EntityIndexType\n attributes: string[]\n source: EntityIndexSource\n state?: EntityIndexState\n size_bytes?: number\n scans?: number\n created_at?: string\n}\n\nexport const EntityIndexSchema = z.object({\n name: z.string(),\n type: z.enum(['lookup', 'unique', 'search']),\n attributes: z.array(z.string()),\n source: z.enum(['declared', 'automatic', 'applied']),\n state: z.enum(['ready', 'building', 'invalid', 'missing']).optional(),\n size_bytes: z.number().optional(),\n scans: z.number().optional(),\n created_at: z.string().optional(),\n})\n\n/** Only slow runs (>= the advisor's slow threshold) are recorded, so\n * `slow_queries` is the whole sample and `avg_ms` their average. */\nexport interface IndexEvidence {\n slow_queries: number\n avg_ms: number\n rows: number\n scans: number\n reason: string\n}\n\nexport interface IndexRecommendation {\n action: 'add' | 'remove'\n index: EntityIndex\n evidence: IndexEvidence\n /** On an `add`: applied lookups the new index supersedes. Pass through as\n * `CreateEntityIndexRequest.replaces` so the create swaps them. */\n replaces?: string[]\n}\n\n/** Only lookup and search can be applied; uniqueness is declared on the entity. */\nexport interface CreateEntityIndexRequest {\n /** Derived from the attributes when omitted (by_<a>_<b>, search_<a>). */\n name?: string\n type: 'lookup' | 'search'\n attributes: string[]\n /** Applied lookups this index supersedes (each must be covered by it);\n * removed in the same step. Required whenever one exists, else 400 index_redundant. */\n replaces?: string[]\n}\n","import type { ProteosClient } from '../client.js'\nimport { type EntityIndexService, EntityIndexServiceImpl } from './entity-indexes.js'\nimport { type QueryService, QueryServiceImpl } from './queries.js'\nimport { type RecordDraftService, RecordDraftServiceImpl } from './record-drafts.js'\nimport {\n type RecordDuplicateService,\n RecordDuplicateServiceImpl,\n type RecordService,\n RecordServiceImpl,\n} from './records.js'\n\n/**\n * Facade for the data-service (records + raw-SQL query API).\n *\n * Usage:\n * ```ts\n * const client = new ProteosClient({ baseUrl, tokenProvider });\n * const data = new DataClient(client);\n * const page = await data.records.listPage('customer');\n * const result = await data.queries.execute('SELECT id, stage FROM opportunity');\n * ```\n */\nexport class DataClient {\n readonly records: RecordService\n readonly queries: QueryService\n /** Duplicate pairs of an entity's records (raised by contact binding). */\n readonly recordDuplicates: RecordDuplicateService\n /** Per-entity indexes on the record table + the advisor's recommendations. */\n readonly entityIndexes: EntityIndexService\n /** Proposed record writes awaiting a human (or reviewing agent) verdict. */\n readonly recordDrafts: RecordDraftService\n\n constructor(client: ProteosClient) {\n this.records = new RecordServiceImpl(client)\n this.queries = new QueryServiceImpl(client)\n this.recordDuplicates = new RecordDuplicateServiceImpl(client)\n this.entityIndexes = new EntityIndexServiceImpl(client)\n this.recordDrafts = new RecordDraftServiceImpl(client)\n }\n}\n\nexport type { EntityIndexService } from './entity-indexes.js'\n// Re-export service interfaces\n// Re-export types\nexport type {\n CreateQueryRequest,\n ListQueriesQuery,\n Query,\n QueryBuilder,\n QueryExecuteMeta,\n QueryExecuteResponse,\n QueryRow,\n QueryService,\n QueryValidateMeta,\n QueryValidateResponse,\n UpdateQueryRequest,\n} from './queries.js'\nexport type { RecordDraftService } from './record-drafts.js'\nexport type { RecordDuplicateService, RecordService } from './records.js'\nexport type {\n ApproveRecordDraftRequest,\n BatchTransactionError,\n BatchTransactionStatus,\n BatchUpsertRecordsResponse,\n BatchUpsertTransaction,\n BatchUpsertTransactionResult,\n CreateEntityIndexRequest,\n CreateRecordDraftRequest,\n EntityIndex,\n EntityIndexSource,\n EntityIndexState,\n EntityIndexType,\n IndexEvidence,\n IndexRecommendation,\n ListRecordDraftsQuery,\n ListRecordDuplicatesQuery,\n ListRecordsOptions,\n ProposedValuesQuery,\n PublishContactObservationsResponse,\n RecordData,\n RecordDraft,\n RecordDraftChange,\n RecordDraftChangeKind,\n RecordDraftCitation,\n RecordDraftEvidence,\n RecordDraftIntent,\n RecordDraftItem,\n RecordDraftItemError,\n RecordDraftItemInput,\n RecordDraftItemResult,\n RecordDraftItemResultStatus,\n RecordDraftItemVerdict,\n RecordDraftProposedValue,\n RecordDraftReference,\n RecordDraftScope,\n RecordDraftStatus,\n RecordDraftVerdict,\n RecordDraftVersion,\n RecordDraftVersionKind,\n RecordDraftVersions,\n RecordDuplicate,\n RecordDuplicateSource,\n RecordDuplicateStatus,\n RejectRecordDraftRequest,\n UpdateRecordDraftRequest,\n} from './types.js'\n\n// Re-export Zod schemas\nexport {\n BatchTransactionErrorSchema,\n BatchUpsertRecordsResponseSchema,\n BatchUpsertTransactionResultSchema,\n BatchUpsertTransactionSchema,\n isRecordDraftReference,\n RecordDraftChangeSchema,\n RecordDraftEvidenceSchema,\n RecordDraftItemResultSchema,\n RecordDraftItemSchema,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type {\n CreateDiscoveryEvidenceNarrationRequest,\n CreateDiscoveryEvidenceRequest,\n CreateDiscoveryInterviewDefinitionRequest,\n DiscoveryEvidence,\n DiscoveryEvidenceDownloadUrl,\n DiscoveryEvidenceNarration,\n DiscoveryEvidenceOrgSummary,\n DiscoveryInterview,\n DiscoveryInterviewDefinition,\n DiscoveryInterviewParticipation,\n InviteDiscoveryInterviewParticipantsRequest,\n ListDiscoveryEvidenceQuery,\n ListDiscoveryInterviewDefinitionsQuery,\n ListDiscoveryInterviewsQuery,\n ListPlatformDiscoveryEvidenceQuery,\n ListResponse,\n StartDiscoveryInterviewParticipationRequest,\n UpdateDiscoveryEvidenceRequest,\n UpdateDiscoveryEvidenceStatusRequest,\n UpdateDiscoveryInterviewDefinitionRequest,\n} from './types.js'\n\nexport * from './types.js'\n\nconst DISCOVERY_BASE_PATH = '/discovery/v1'\n\nconst encode = encodeURIComponent\n\n/**\n * Facade for discovery-service: the evidence users send Proteos (screenshots,\n * screen recordings with ink-annotated frames, written feedback).\n *\n * `evidence` acts in the caller's org — own rows under a scoped grant, every\n * row under the unscoped read. `narrations` are the jobs that draft feedback\n * from what was said in a recording. `platform` is the Proteos-side view\n * across every org; it answers only to platform admins.\n *\n * `interviewDefinitions` are the interview guides an admin writes and\n * `interviews` what each participant's interview came to. Both also carry the\n * participant's own calls (`getParticipation`, `startParticipation`,\n * `complete`), which answer to the person interviewed, not to a grant.\n *\n * ```ts\n * const discovery = new DiscoveryClient(client)\n * const sent = await discovery.evidence.create({ kind: 'feedback', source: 'web', notes, context })\n * const { data: mine } = await discovery.evidence.list()\n * const { url } = await discovery.evidence.createDownloadUrl(sent.id, fileId)\n * ```\n */\nexport class DiscoveryClient {\n readonly evidence: DiscoveryEvidenceService\n readonly narrations: DiscoveryEvidenceNarrationService\n readonly platform: PlatformDiscoveryEvidenceService\n readonly interviewDefinitions: DiscoveryInterviewDefinitionService\n readonly interviews: DiscoveryInterviewService\n\n constructor(client: ProteosClient) {\n this.evidence = new DiscoveryEvidenceServiceImpl(client)\n this.narrations = new DiscoveryEvidenceNarrationServiceImpl(client)\n this.platform = new PlatformDiscoveryEvidenceServiceImpl(client)\n this.interviewDefinitions = new DiscoveryInterviewDefinitionServiceImpl(client)\n this.interviews = new DiscoveryInterviewServiceImpl(client)\n }\n}\n\n/** The submitter's door: create, read back, edit the words, withdraw. */\nexport interface DiscoveryEvidenceService {\n create(request: CreateDiscoveryEvidenceRequest): Promise<DiscoveryEvidence>\n list(query?: ListDiscoveryEvidenceQuery): Promise<ListResponse<DiscoveryEvidence>>\n /** The detail read; carries the frames. */\n get(id: string): Promise<DiscoveryEvidence>\n update(id: string, request: UpdateDiscoveryEvidenceRequest): Promise<DiscoveryEvidence>\n /** Withdraws the evidence; its files are removed best-effort. */\n delete(id: string): Promise<void>\n /** Mints a presigned URL for one of the evidence's files (recording, frame image). */\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl>\n}\n\n/**\n * Narration jobs of the capture UI: started when a recording with sound stops,\n * polled until `completed` or `failed`, named on the create request.\n */\nexport interface DiscoveryEvidenceNarrationService {\n create(request: CreateDiscoveryEvidenceNarrationRequest): Promise<DiscoveryEvidenceNarration>\n get(id: string): Promise<DiscoveryEvidenceNarration>\n /** Discards a job that was not sent with evidence, along with its audio file. */\n delete(id: string): Promise<void>\n}\n\n/** The Proteos-side view across orgs. Platform admins only. */\nexport interface PlatformDiscoveryEvidenceService {\n list(query?: ListPlatformDiscoveryEvidenceQuery): Promise<ListResponse<DiscoveryEvidence>>\n /** Per-org counts: how much evidence, how much still new, the newest arrival. */\n summary(): Promise<DiscoveryEvidenceOrgSummary[]>\n get(id: string): Promise<DiscoveryEvidence>\n updateStatus(\n id: string,\n request: UpdateDiscoveryEvidenceStatusRequest,\n ): Promise<DiscoveryEvidence>\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl>\n}\n\n/**\n * Interview definitions: the guide (objective, questions, agent) and who it is\n * for. The last two methods are the participant's: what their page shows\n * before the interview, and starting or resuming their own interview.\n */\nexport interface DiscoveryInterviewDefinitionService {\n create(request: CreateDiscoveryInterviewDefinitionRequest): Promise<DiscoveryInterviewDefinition>\n list(\n query?: ListDiscoveryInterviewDefinitionsQuery,\n ): Promise<ListResponse<DiscoveryInterviewDefinition>>\n /** The detail read; carries `guide_findings`. */\n get(id: string): Promise<DiscoveryInterviewDefinition>\n update(\n id: string,\n request: UpdateDiscoveryInterviewDefinitionRequest,\n ): Promise<DiscoveryInterviewDefinition>\n /** Deletes the definition with its interviews and their recordings. */\n delete(id: string): Promise<void>\n publish(id: string): Promise<DiscoveryInterviewDefinition>\n /** Nobody can start or continue; results stay readable. */\n close(id: string): Promise<DiscoveryInterviewDefinition>\n reopen(id: string): Promise<DiscoveryInterviewDefinition>\n /** Assigns users; people already assigned are returned unchanged. */\n invite(\n id: string,\n request: InviteDiscoveryInterviewParticipantsRequest,\n ): Promise<DiscoveryInterview[]>\n getParticipation(id: string): Promise<DiscoveryInterviewParticipation>\n startParticipation(\n id: string,\n request: StartDiscoveryInterviewParticipationRequest,\n ): Promise<DiscoveryInterviewParticipation>\n}\n\n/**\n * Interviews of a definition, for whoever can read it. `complete` and\n * `getParticipation` are the participant's.\n */\nexport interface DiscoveryInterviewService {\n list(query: ListDiscoveryInterviewsQuery): Promise<ListResponse<DiscoveryInterview>>\n /** The detail read; carries the guide snapshot and the transcript. */\n get(id: string): Promise<DiscoveryInterview>\n /** Sends the invitation again. */\n remind(id: string): Promise<void>\n /** Reruns a synthesis that failed. */\n synthesize(id: string): Promise<DiscoveryInterview>\n /** Withdraws an invitation or deletes a result with its recordings. */\n delete(id: string): Promise<void>\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl>\n /** Ends the caller's interview and starts the synthesis. Safe to repeat. */\n complete(id: string): Promise<DiscoveryInterviewParticipation>\n getParticipation(id: string): Promise<DiscoveryInterviewParticipation>\n}\n\nclass DiscoveryEvidenceServiceImpl implements DiscoveryEvidenceService {\n constructor(private readonly client: ProteosClient) {}\n\n create(request: CreateDiscoveryEvidenceRequest): Promise<DiscoveryEvidence> {\n return this.client.request('POST', `${DISCOVERY_BASE_PATH}/evidence`, request)\n }\n\n list(query: ListDiscoveryEvidenceQuery = {}): Promise<ListResponse<DiscoveryEvidence>> {\n return this.client.requestWithQuery('GET', `${DISCOVERY_BASE_PATH}/evidence`, query)\n }\n\n get(id: string): Promise<DiscoveryEvidence> {\n return this.client.request('GET', `${DISCOVERY_BASE_PATH}/evidence/${encode(id)}`)\n }\n\n update(id: string, request: UpdateDiscoveryEvidenceRequest): Promise<DiscoveryEvidence> {\n return this.client.request('PATCH', `${DISCOVERY_BASE_PATH}/evidence/${encode(id)}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', `${DISCOVERY_BASE_PATH}/evidence/${encode(id)}`)\n }\n\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl> {\n return this.client.request(\n 'POST',\n `${DISCOVERY_BASE_PATH}/evidence/${encode(id)}/files/${encode(fileId)}/download-url`,\n )\n }\n}\n\nclass DiscoveryEvidenceNarrationServiceImpl implements DiscoveryEvidenceNarrationService {\n constructor(private readonly client: ProteosClient) {}\n\n create(request: CreateDiscoveryEvidenceNarrationRequest): Promise<DiscoveryEvidenceNarration> {\n return this.client.request('POST', `${DISCOVERY_BASE_PATH}/evidence-narrations`, request)\n }\n\n get(id: string): Promise<DiscoveryEvidenceNarration> {\n return this.client.request('GET', `${DISCOVERY_BASE_PATH}/evidence-narrations/${encode(id)}`)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', `${DISCOVERY_BASE_PATH}/evidence-narrations/${encode(id)}`)\n }\n}\n\nclass PlatformDiscoveryEvidenceServiceImpl implements PlatformDiscoveryEvidenceService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListPlatformDiscoveryEvidenceQuery = {}): Promise<ListResponse<DiscoveryEvidence>> {\n return this.client.requestWithQuery('GET', `${DISCOVERY_BASE_PATH}/platform/evidence`, query)\n }\n\n async summary(): Promise<DiscoveryEvidenceOrgSummary[]> {\n const response = await this.client.request<{ data: DiscoveryEvidenceOrgSummary[] }>(\n 'GET',\n `${DISCOVERY_BASE_PATH}/platform/evidence/summary`,\n )\n return response.data\n }\n\n get(id: string): Promise<DiscoveryEvidence> {\n return this.client.request('GET', `${DISCOVERY_BASE_PATH}/platform/evidence/${encode(id)}`)\n }\n\n updateStatus(\n id: string,\n request: UpdateDiscoveryEvidenceStatusRequest,\n ): Promise<DiscoveryEvidence> {\n return this.client.request(\n 'PATCH',\n `${DISCOVERY_BASE_PATH}/platform/evidence/${encode(id)}/status`,\n request,\n )\n }\n\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl> {\n return this.client.request(\n 'POST',\n `${DISCOVERY_BASE_PATH}/platform/evidence/${encode(id)}/files/${encode(fileId)}/download-url`,\n )\n }\n}\n\nclass DiscoveryInterviewDefinitionServiceImpl implements DiscoveryInterviewDefinitionService {\n constructor(private readonly client: ProteosClient) {}\n\n private path(id?: string, suffix = ''): string {\n const base = `${DISCOVERY_BASE_PATH}/interview-definitions`\n return id === undefined ? base : `${base}/${encode(id)}${suffix}`\n }\n\n create(\n request: CreateDiscoveryInterviewDefinitionRequest,\n ): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('POST', this.path(), request)\n }\n\n list(\n query: ListDiscoveryInterviewDefinitionsQuery = {},\n ): Promise<ListResponse<DiscoveryInterviewDefinition>> {\n return this.client.requestWithQuery('GET', this.path(), query)\n }\n\n get(id: string): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('GET', this.path(id))\n }\n\n update(\n id: string,\n request: UpdateDiscoveryInterviewDefinitionRequest,\n ): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('PATCH', this.path(id), request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', this.path(id))\n }\n\n publish(id: string): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('POST', this.path(id, '/publish'))\n }\n\n close(id: string): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('POST', this.path(id, '/close'))\n }\n\n reopen(id: string): Promise<DiscoveryInterviewDefinition> {\n return this.client.request('POST', this.path(id, '/reopen'))\n }\n\n async invite(\n id: string,\n request: InviteDiscoveryInterviewParticipantsRequest,\n ): Promise<DiscoveryInterview[]> {\n const response = await this.client.request<{ data: DiscoveryInterview[] }>(\n 'POST',\n this.path(id, '/interviews'),\n request,\n )\n return response.data\n }\n\n getParticipation(id: string): Promise<DiscoveryInterviewParticipation> {\n return this.client.request('GET', this.path(id, '/participation'))\n }\n\n startParticipation(\n id: string,\n request: StartDiscoveryInterviewParticipationRequest,\n ): Promise<DiscoveryInterviewParticipation> {\n return this.client.request('POST', this.path(id, '/participation/start'), request)\n }\n}\n\nclass DiscoveryInterviewServiceImpl implements DiscoveryInterviewService {\n constructor(private readonly client: ProteosClient) {}\n\n private path(id: string, suffix = ''): string {\n return `${DISCOVERY_BASE_PATH}/interviews/${encode(id)}${suffix}`\n }\n\n list(query: ListDiscoveryInterviewsQuery): Promise<ListResponse<DiscoveryInterview>> {\n return this.client.requestWithQuery('GET', `${DISCOVERY_BASE_PATH}/interviews`, query)\n }\n\n get(id: string): Promise<DiscoveryInterview> {\n return this.client.request('GET', this.path(id))\n }\n\n async remind(id: string): Promise<void> {\n await this.client.request('POST', this.path(id, '/remind'))\n }\n\n synthesize(id: string): Promise<DiscoveryInterview> {\n return this.client.request('POST', this.path(id, '/synthesize'))\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', this.path(id))\n }\n\n createDownloadUrl(id: string, fileId: string): Promise<DiscoveryEvidenceDownloadUrl> {\n return this.client.request('POST', this.path(id, `/files/${encode(fileId)}/download-url`))\n }\n\n complete(id: string): Promise<DiscoveryInterviewParticipation> {\n return this.client.request('POST', this.path(id, '/complete'), {})\n }\n\n getParticipation(id: string): Promise<DiscoveryInterviewParticipation> {\n return this.client.request('GET', this.path(id, '/participation'))\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n CreateEnrichmentConnectionRequest,\n CreateEnrichmentRunRequest,\n CreateEnrichmentTypeRequest,\n CreateResearchDefinitionRequest,\n CreateSignalMonitorRequest,\n CreateWaterfallRequest,\n EnrichmentBlock,\n EnrichmentConnection,\n EnrichmentEntry,\n EnrichmentItem,\n EnrichmentMapping,\n EnrichmentProvenance,\n EnrichmentProvider,\n EnrichmentRun,\n EnrichmentRunList,\n EnrichmentRunResponse,\n EnrichmentType,\n EnrichmentTypesResponse,\n EnrichRequest,\n EnrichResponse,\n ListEnrichmentRunsQuery,\n ListResearchRunsQuery,\n ListSignalsQuery,\n PatchEnrichmentConnectionRequest,\n PatchEnrichmentTypeRequest,\n PatchResearchDefinitionRequest,\n PatchSignalMonitorRequest,\n PatchWaterfallRequest,\n PutSignalMappingRequest,\n ReplaceEnrichmentMappingRequest,\n ResearchDefinition,\n ResearchResult,\n ResearchRun,\n ResearchRunList,\n SignalList,\n SignalMapping,\n SignalMonitor,\n TestEnrichmentConnectionRequest,\n TestEnrichmentConnectionResponse,\n Waterfall,\n} from './types.js'\n\nexport * from './types.js'\n\nconst ENRICHMENT_BASE_PATH = '/enrichment/v1'\n\nconst encode = encodeURIComponent\n\n/**\n * `POST /enrich` waits for its waterfalls and `POST /enrichment-runs` for up\n * to `wait_seconds`: 30 seconds each at most by default, which is the\n * client's default timeout. They get longer, so the service's answer comes\n * back instead of a client timeout.\n */\nconst WAITING_REQUEST_TIMEOUT_MS = 75_000\n\n/**\n * Facade for enrichment-service: filling attributes from providers through\n * waterfalls.\n *\n * `enrich` returns values and writes nothing. `runs` enrich records and write\n * or propose what they find (a record draft), as each attribute's apply level\n * says. `mappings` say what each attribute of an entity does in enrichment,\n * `waterfalls` are an org's own step lists, `research` finds companies and\n * people that are no records yet and proposes them as record drafts,\n * `signals` are the changes a scheduled refresh or a web monitor detected and\n * what they propose, and `catalog` is what can be asked for and who supplies\n * it.\n *\n * Single resources come back bare; the lists (run items, waterfalls,\n * providers) are unwrapped from `{data}` and are not paged.\n *\n * ```ts\n * const enrichment = new EnrichmentClient(client)\n * const found = await enrichment.enrich({ entity_slug: 'contact', record_id: id, attributes: ['email'] })\n * const run = await enrichment.runs.create({ entity_slug: 'contact', record_ids: ids, wait_seconds: 20 })\n * const items = await enrichment.runs.listItems(run.enrichment_run_id)\n * await enrichment.mappings.setEntry('contact', 'email', { enrichment_type: 'work_email' })\n * const researchRun = await enrichment.research.startRun(definitionId)\n * const rows = await enrichment.research.listResults(researchRun.id)\n * ```\n */\nexport class EnrichmentClient {\n readonly runs: EnrichmentRunService\n readonly mappings: EnrichmentMappingService\n readonly waterfalls: WaterfallService\n readonly connections: EnrichmentConnectionService\n readonly research: ResearchService\n readonly signals: SignalService\n readonly catalog: EnrichmentCatalogService\n\n constructor(private readonly client: ProteosClient) {\n this.runs = new EnrichmentRunServiceImpl(client)\n this.mappings = new EnrichmentMappingServiceImpl(client)\n this.waterfalls = new WaterfallServiceImpl(client)\n this.connections = new EnrichmentConnectionServiceImpl(client)\n this.research = new ResearchServiceImpl(client)\n this.signals = new SignalServiceImpl(client)\n this.catalog = new EnrichmentCatalogServiceImpl(client)\n }\n\n /** Fills attributes ad hoc: the values are returned, nothing is written. */\n enrich(request: EnrichRequest): Promise<EnrichResponse> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/enrich`, request, {\n timeout: WAITING_REQUEST_TIMEOUT_MS,\n })\n }\n}\n\n/** Runs over records. */\nexport interface EnrichmentRunService {\n /**\n * Starts a run. Answers once the run has finished or `wait_seconds` are\n * over, whichever is first; a run that is still running is followed with\n * `get`.\n */\n create(request: CreateEnrichmentRunRequest): Promise<EnrichmentRunResponse>\n /** One page of the org's runs, newest first, without their `resolved_attributes`. */\n list(query?: ListEnrichmentRunsQuery): Promise<EnrichmentRunList>\n get(id: string): Promise<EnrichmentRun>\n /** A run's items with their results. */\n listItems(id: string): Promise<EnrichmentItem[]>\n /** Stops the records whose turn has not come, and the ones that wait for a provider's answer. */\n cancel(id: string): Promise<EnrichmentRun>\n /**\n * Where the values of one record came from: per attribute, the enrichment\n * that found the value the record holds now and wrote it, or suggested it\n * to a reviewer who accepted it.\n */\n provenance(entitySlug: string, recordId: string): Promise<EnrichmentProvenance>\n /**\n * What the latest runs over records found for one record, newest first\n * (at most 20), whatever their status. An ad-hoc `enrich` is not listed.\n */\n listRecordItems(entitySlug: string, recordId: string): Promise<EnrichmentItem[]>\n}\n\n/** The enrichment mapping of an entity. */\nexport interface EnrichmentMappingService {\n /** An entity's mapping, its orphaned entries marked. */\n get(entitySlug: string): Promise<EnrichmentMapping>\n /** Writes the whole mapping; 409 when it changed meanwhile. */\n replace(entitySlug: string, request: ReplaceEnrichmentMappingRequest): Promise<EnrichmentMapping>\n getEntry(entitySlug: string, attribute: string): Promise<EnrichmentEntry>\n /** Writes one attribute's entry and touches no other. */\n setEntry(entitySlug: string, attribute: string, block: EnrichmentBlock): Promise<EnrichmentEntry>\n deleteEntry(entitySlug: string, attribute: string): Promise<void>\n}\n\n/** An org's waterfalls. Platform defaults are listed and read-only. */\nexport interface WaterfallService {\n /** The org's waterfalls, active or not, and the platform defaults. */\n list(): Promise<Waterfall[]>\n get(id: string): Promise<Waterfall>\n /** 409 while another active waterfall holds its attribute, or is the default of its enrichment type. */\n create(request: CreateWaterfallRequest): Promise<Waterfall>\n patch(id: string, request: PatchWaterfallRequest): Promise<Waterfall>\n delete(id: string): Promise<void>\n}\n\n/**\n * An org's enrichment connections: its bindings to its own connections (its\n * Clay key), which the `connection` steps of its waterfalls run on.\n */\nexport interface EnrichmentConnectionService {\n list(): Promise<EnrichmentConnection[]>\n get(id: string): Promise<EnrichmentConnection>\n /** Binds one of the org's connections. A person's own connection can only be bound by that person. */\n create(request: CreateEnrichmentConnectionRequest): Promise<EnrichmentConnection>\n patch(id: string, request: PatchEnrichmentConnectionRequest): Promise<EnrichmentConnection>\n /** A waterfall step that names it is skipped from then on. */\n delete(id: string): Promise<void>\n /** Runs a routine once with a config that may not be saved yet, on the org's own credits. Saves nothing. */\n test(request: TestEnrichmentConnectionRequest): Promise<TestEnrichmentConnectionResponse>\n}\n\n/**\n * Research definitions and their runs. A definition says what to find on the\n * web and how a found row maps onto the org's entities; a run finds the rows\n * and proposes the new ones as record drafts. Nothing is written to a record\n * until a reviewer accepts a draft in data-service.\n */\nexport interface ResearchService {\n listDefinitions(): Promise<ResearchDefinition[]>\n getDefinition(id: string): Promise<ResearchDefinition>\n /** Every entity the definition maps onto needs an enrichment mapping. */\n createDefinition(request: CreateResearchDefinitionRequest): Promise<ResearchDefinition>\n patchDefinition(id: string, request: PatchResearchDefinitionRequest): Promise<ResearchDefinition>\n /** Removes the definition with its runs and their rows. The record drafts its runs proposed stay. */\n deleteDefinition(id: string): Promise<void>\n /**\n * Starts a run and returns it while it is still running; follow it with\n * `getRun`. 409 while the definition has a run that is still running.\n */\n startRun(definitionId: string): Promise<ResearchRun>\n /** One page of the org's research runs, newest first. */\n listRuns(query?: ListResearchRunsQuery): Promise<ResearchRunList>\n getRun(id: string): Promise<ResearchRun>\n /** The rows a run found, each as a reviewer left it. */\n listResults(runId: string): Promise<ResearchResult[]>\n /** Stops a running run. Drafts it proposed already stay. */\n cancelRun(id: string): Promise<ResearchRun>\n}\n\n/**\n * Signals: the log of detected changes, the signal mapping of each kind\n * (which records a signal creates and what it proposes on the record it is\n * about), and signal monitors (standing web monitors for news, funding and\n * hiring about some records). A scheduled refresh detects `field_change`,\n * `job_change` and `headcount_change` by itself; turn it on with the\n * `on_schedule` trigger and `refresh_every_days` of a mapping entry.\n */\nexport interface SignalService {\n /** One page of the org's signals, newest first. */\n list(query?: ListSignalsQuery): Promise<SignalList>\n listMappings(): Promise<SignalMapping[]>\n getMapping(kind: string): Promise<SignalMapping>\n /** Writes the whole of what a signal of the kind does to records. */\n putMapping(kind: string, request: PutSignalMappingRequest): Promise<SignalMapping>\n /** The kind's signals are still logged and published, and propose nothing. */\n deleteMapping(kind: string): Promise<void>\n listMonitors(): Promise<SignalMonitor[]>\n getMonitor(id: string): Promise<SignalMonitor>\n /**\n * An active monitor checks for the first time within a minute and then every\n * `schedule.every_days`; every check costs money.\n */\n createMonitor(request: CreateSignalMonitorRequest): Promise<SignalMonitor>\n patchMonitor(id: string, request: PatchSignalMonitorRequest): Promise<SignalMonitor>\n /** The signals the monitor detected stay. */\n deleteMonitor(id: string): Promise<void>\n}\n\n/** What can be asked for and who supplies it. The same for every org. */\nexport interface EnrichmentCatalogService {\n /** The platform's types, then the org's own. */\n enrichmentTypes(): Promise<EnrichmentTypesResponse>\n providers(): Promise<EnrichmentProvider[]>\n /** Defines one of the org's own enrichment types. */\n createEnrichmentType(request: CreateEnrichmentTypeRequest): Promise<EnrichmentType>\n patchEnrichmentType(key: string, request: PatchEnrichmentTypeRequest): Promise<EnrichmentType>\n /** Refused while one of the org's waterfalls fills it. */\n deleteEnrichmentType(key: string): Promise<void>\n}\n\nclass EnrichmentRunServiceImpl implements EnrichmentRunService {\n constructor(private readonly client: ProteosClient) {}\n\n create(request: CreateEnrichmentRunRequest): Promise<EnrichmentRunResponse> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/enrichment-runs`, request, {\n timeout: WAITING_REQUEST_TIMEOUT_MS,\n })\n }\n\n list(query: ListEnrichmentRunsQuery = {}): Promise<EnrichmentRunList> {\n return this.client.requestWithQuery('GET', `${ENRICHMENT_BASE_PATH}/enrichment-runs`, query)\n }\n\n get(id: string): Promise<EnrichmentRun> {\n return this.client.request('GET', `${ENRICHMENT_BASE_PATH}/enrichment-runs/${encode(id)}`)\n }\n\n async listItems(id: string): Promise<EnrichmentItem[]> {\n const response = await this.client.request<{ data: EnrichmentItem[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/enrichment-runs/${encode(id)}/items`,\n )\n return response.data\n }\n\n cancel(id: string): Promise<EnrichmentRun> {\n return this.client.request(\n 'POST',\n `${ENRICHMENT_BASE_PATH}/enrichment-runs/${encode(id)}/cancel`,\n )\n }\n\n provenance(entitySlug: string, recordId: string): Promise<EnrichmentProvenance> {\n return this.client.requestWithQuery('GET', `${ENRICHMENT_BASE_PATH}/provenance`, {\n entity_slug: entitySlug,\n record_id: recordId,\n })\n }\n\n async listRecordItems(entitySlug: string, recordId: string): Promise<EnrichmentItem[]> {\n const response = await this.client.requestWithQuery<{ data: EnrichmentItem[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/enrichment-items`,\n { entity_slug: entitySlug, record_id: recordId },\n )\n return response.data\n }\n}\n\nclass EnrichmentMappingServiceImpl implements EnrichmentMappingService {\n constructor(private readonly client: ProteosClient) {}\n\n private entryPath(entitySlug: string, attribute: string): string {\n return `${ENRICHMENT_BASE_PATH}/mappings/${encode(entitySlug)}/attributes/${encode(attribute)}`\n }\n\n get(entitySlug: string): Promise<EnrichmentMapping> {\n return this.client.request('GET', `${ENRICHMENT_BASE_PATH}/mappings/${encode(entitySlug)}`)\n }\n\n replace(\n entitySlug: string,\n request: ReplaceEnrichmentMappingRequest,\n ): Promise<EnrichmentMapping> {\n return this.client.request(\n 'PUT',\n `${ENRICHMENT_BASE_PATH}/mappings/${encode(entitySlug)}`,\n request,\n )\n }\n\n getEntry(entitySlug: string, attribute: string): Promise<EnrichmentEntry> {\n return this.client.request('GET', this.entryPath(entitySlug, attribute))\n }\n\n setEntry(\n entitySlug: string,\n attribute: string,\n block: EnrichmentBlock,\n ): Promise<EnrichmentEntry> {\n return this.client.request('PUT', this.entryPath(entitySlug, attribute), block)\n }\n\n async deleteEntry(entitySlug: string, attribute: string): Promise<void> {\n await this.client.request('DELETE', this.entryPath(entitySlug, attribute))\n }\n}\n\nclass WaterfallServiceImpl implements WaterfallService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<Waterfall[]> {\n const response = await this.client.request<{ data: Waterfall[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/waterfalls`,\n )\n return response.data\n }\n\n get(id: string): Promise<Waterfall> {\n return this.client.request('GET', `${ENRICHMENT_BASE_PATH}/waterfalls/${encode(id)}`)\n }\n\n create(request: CreateWaterfallRequest): Promise<Waterfall> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/waterfalls`, request)\n }\n\n patch(id: string, request: PatchWaterfallRequest): Promise<Waterfall> {\n return this.client.request('PATCH', `${ENRICHMENT_BASE_PATH}/waterfalls/${encode(id)}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', `${ENRICHMENT_BASE_PATH}/waterfalls/${encode(id)}`)\n }\n}\n\nclass EnrichmentConnectionServiceImpl implements EnrichmentConnectionService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<EnrichmentConnection[]> {\n const response = await this.client.request<{ data: EnrichmentConnection[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections`,\n )\n return response.data\n }\n\n get(id: string): Promise<EnrichmentConnection> {\n return this.client.request(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections/${encode(id)}`,\n )\n }\n\n create(request: CreateEnrichmentConnectionRequest): Promise<EnrichmentConnection> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/enrichment-connections`, request)\n }\n\n patch(id: string, request: PatchEnrichmentConnectionRequest): Promise<EnrichmentConnection> {\n return this.client.request(\n 'PATCH',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections/${encode(id)}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections/${encode(id)}`,\n )\n }\n\n test(request: TestEnrichmentConnectionRequest): Promise<TestEnrichmentConnectionResponse> {\n return this.client.request(\n 'POST',\n `${ENRICHMENT_BASE_PATH}/enrichment-connections/test`,\n request,\n )\n }\n}\n\nclass SignalServiceImpl implements SignalService {\n constructor(private readonly client: ProteosClient) {}\n\n private mappingPath(kind: string): string {\n return `${ENRICHMENT_BASE_PATH}/signal-mappings/${encode(kind)}`\n }\n\n private monitorPath(id: string): string {\n return `${ENRICHMENT_BASE_PATH}/signal-monitors/${encode(id)}`\n }\n\n list(query: ListSignalsQuery = {}): Promise<SignalList> {\n return this.client.requestWithQuery('GET', `${ENRICHMENT_BASE_PATH}/signals`, query)\n }\n\n async listMappings(): Promise<SignalMapping[]> {\n const response = await this.client.request<{ data: SignalMapping[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/signal-mappings`,\n )\n return response.data\n }\n\n getMapping(kind: string): Promise<SignalMapping> {\n return this.client.request('GET', this.mappingPath(kind))\n }\n\n putMapping(kind: string, request: PutSignalMappingRequest): Promise<SignalMapping> {\n return this.client.request('PUT', this.mappingPath(kind), request)\n }\n\n async deleteMapping(kind: string): Promise<void> {\n await this.client.request('DELETE', this.mappingPath(kind))\n }\n\n async listMonitors(): Promise<SignalMonitor[]> {\n const response = await this.client.request<{ data: SignalMonitor[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/signal-monitors`,\n )\n return response.data\n }\n\n getMonitor(id: string): Promise<SignalMonitor> {\n return this.client.request('GET', this.monitorPath(id))\n }\n\n createMonitor(request: CreateSignalMonitorRequest): Promise<SignalMonitor> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/signal-monitors`, request)\n }\n\n patchMonitor(id: string, request: PatchSignalMonitorRequest): Promise<SignalMonitor> {\n return this.client.request('PATCH', this.monitorPath(id), request)\n }\n\n async deleteMonitor(id: string): Promise<void> {\n await this.client.request('DELETE', this.monitorPath(id))\n }\n}\n\nclass ResearchServiceImpl implements ResearchService {\n constructor(private readonly client: ProteosClient) {}\n\n private definitionPath(id: string): string {\n return `${ENRICHMENT_BASE_PATH}/research-definitions/${encode(id)}`\n }\n\n private runPath(id: string): string {\n return `${ENRICHMENT_BASE_PATH}/research-runs/${encode(id)}`\n }\n\n async listDefinitions(): Promise<ResearchDefinition[]> {\n const response = await this.client.request<{ data: ResearchDefinition[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/research-definitions`,\n )\n return response.data\n }\n\n getDefinition(id: string): Promise<ResearchDefinition> {\n return this.client.request('GET', this.definitionPath(id))\n }\n\n createDefinition(request: CreateResearchDefinitionRequest): Promise<ResearchDefinition> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/research-definitions`, request)\n }\n\n patchDefinition(\n id: string,\n request: PatchResearchDefinitionRequest,\n ): Promise<ResearchDefinition> {\n return this.client.request('PATCH', this.definitionPath(id), request)\n }\n\n async deleteDefinition(id: string): Promise<void> {\n await this.client.request('DELETE', this.definitionPath(id))\n }\n\n startRun(definitionId: string): Promise<ResearchRun> {\n return this.client.request('POST', `${this.definitionPath(definitionId)}/runs`)\n }\n\n listRuns(query: ListResearchRunsQuery = {}): Promise<ResearchRunList> {\n return this.client.requestWithQuery('GET', `${ENRICHMENT_BASE_PATH}/research-runs`, query)\n }\n\n getRun(id: string): Promise<ResearchRun> {\n return this.client.request('GET', this.runPath(id))\n }\n\n async listResults(runId: string): Promise<ResearchResult[]> {\n const response = await this.client.request<{ data: ResearchResult[] }>(\n 'GET',\n `${this.runPath(runId)}/results`,\n )\n return response.data\n }\n\n cancelRun(id: string): Promise<ResearchRun> {\n return this.client.request('POST', `${this.runPath(id)}/cancel`)\n }\n}\n\nclass EnrichmentCatalogServiceImpl implements EnrichmentCatalogService {\n constructor(private readonly client: ProteosClient) {}\n\n enrichmentTypes(): Promise<EnrichmentTypesResponse> {\n return this.client.request('GET', `${ENRICHMENT_BASE_PATH}/enrichment-types`)\n }\n\n async providers(): Promise<EnrichmentProvider[]> {\n const response = await this.client.request<{ data: EnrichmentProvider[] }>(\n 'GET',\n `${ENRICHMENT_BASE_PATH}/providers`,\n )\n return response.data\n }\n\n createEnrichmentType(request: CreateEnrichmentTypeRequest): Promise<EnrichmentType> {\n return this.client.request('POST', `${ENRICHMENT_BASE_PATH}/enrichment-types`, request)\n }\n\n patchEnrichmentType(key: string, request: PatchEnrichmentTypeRequest): Promise<EnrichmentType> {\n return this.client.request(\n 'PATCH',\n `${ENRICHMENT_BASE_PATH}/enrichment-types/${encode(key)}`,\n request,\n )\n }\n\n async deleteEnrichmentType(key: string): Promise<void> {\n await this.client.request('DELETE', `${ENRICHMENT_BASE_PATH}/enrichment-types/${encode(key)}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n ListEventsOptions,\n PlatformEvent,\n PublishEventRequest,\n RedriveResult,\n TailOptions,\n Topic,\n} from './types.js'\n\nconst EVENTS_BASE_PATH = '/events/v1'\n\n// A live tail is a long-poll; override the client's default request timeout so\n// it isn't aborted mid-stream. ~24h is well under the setTimeout overflow bound\n// and acts as a practical cap on a single tail session. Real teardown is the\n// caller's AbortSignal.\nconst TAIL_TIMEOUT_MS = 24 * 60 * 60 * 1000\n\n/**\n * Facade for event-service: a read/admin view over the Redis-Streams bus.\n * Everything is topic-centric, so the surface lives on `topics`.\n *\n * ```ts\n * const events = new EventsClient(client)\n * const topics = await events.topics.list()\n * const recent = await events.topics.events('record.contact.events', { limit: 50 })\n * for await (const msg of events.topics.tail('record.contact.events', { signal })) {\n * // append msg\n * }\n * ```\n */\nexport class EventsClient {\n readonly topics: TopicService\n\n constructor(client: ProteosClient) {\n this.topics = new TopicServiceImpl(client)\n }\n}\n\n/** Topic discovery, event reads + live tail, and admin actions. */\nexport interface TopicService {\n /** List the caller-org's topics. */\n list(): Promise<Topic[]>\n /** Read the most-recent events on a topic (newest first). */\n events(topic: string, options?: ListEventsOptions): Promise<PlatformEvent[]>\n /**\n * Live-tail new events on a topic until the AbortSignal fires. Yields each\n * event as it arrives (chunked NDJSON under the hood).\n */\n tail(topic: string, options?: TailOptions): AsyncGenerator<PlatformEvent, void, unknown>\n /** Publish a test event onto a topic — delivered to real consumers. */\n publish(topic: string, request: PublishEventRequest): Promise<PlatformEvent>\n /** Move a dead-letter stream back to its source topic for re-processing. */\n redrive(topic: string): Promise<RedriveResult>\n /** Empty a topic's stream (keeps consumer groups). Destructive. */\n purge(topic: string): Promise<void>\n}\n\nclass TopicServiceImpl implements TopicService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<Topic[]> {\n const response = await this.client.request<{ data: Topic[] }>(\n 'GET',\n `${EVENTS_BASE_PATH}/topics`,\n )\n return response.data ?? []\n }\n\n async events(topic: string, options: ListEventsOptions = {}): Promise<PlatformEvent[]> {\n const response = await this.client.requestWithQuery<\n { data: PlatformEvent[] },\n ListEventsOptions\n >('GET', `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/events`, options)\n return response.data ?? []\n }\n\n async *tail(\n topic: string,\n options: TailOptions = {},\n ): AsyncGenerator<PlatformEvent, void, unknown> {\n const path = `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/events?follow=true`\n let body: ReadableStream<Uint8Array> | null\n try {\n ;({ body } = await this.client.requestRaw('GET', path, undefined, {\n timeout: TAIL_TIMEOUT_MS,\n ...(options.signal ? { signal: options.signal } : {}),\n headers: { Accept: 'application/x-ndjson' },\n }))\n } catch (error) {\n if (isAbort(error)) return\n throw error\n }\n if (!body) return\n\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n let newlineIndex = buffer.indexOf('\\n')\n while (newlineIndex !== -1) {\n const line = buffer.slice(0, newlineIndex).trim()\n buffer = buffer.slice(newlineIndex + 1)\n const event = parseLine(line)\n if (event) yield event\n newlineIndex = buffer.indexOf('\\n')\n }\n }\n const remainder = parseLine(buffer.trim())\n if (remainder) yield remainder\n } catch (error) {\n if (!isAbort(error)) throw error\n } finally {\n reader.releaseLock()\n void body.cancel().catch(() => {})\n }\n }\n\n async publish(topic: string, request: PublishEventRequest): Promise<PlatformEvent> {\n return this.client.request<PlatformEvent>(\n 'POST',\n `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/events`,\n request,\n )\n }\n\n async redrive(topic: string): Promise<RedriveResult> {\n return this.client.request<RedriveResult>(\n 'POST',\n `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/redrive`,\n )\n }\n\n async purge(topic: string): Promise<void> {\n await this.client.request<void>(\n 'POST',\n `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/purge`,\n )\n }\n}\n\n/** True when an error is an AbortError (the tail's normal stop path). */\nfunction isAbort(error: unknown): boolean {\n return error instanceof DOMException && error.name === 'AbortError'\n}\n\n/**\n * Parses one NDJSON line into a PlatformEvent, returning null for a blank or\n * unparseable line. A single bad frame should be skipped, not tear down the\n * whole tail.\n */\nfunction parseLine(line: string): PlatformEvent | null {\n if (!line) return null\n try {\n return JSON.parse(line) as PlatformEvent\n } catch {\n return null\n }\n}\n\nexport type {\n ConsumerGroup,\n ListEventsOptions,\n PlatformEvent,\n PublishEventRequest,\n RedriveResult,\n TailOptions,\n Topic,\n TopicKind,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport { BATCH_INVOKE_TIMEOUT_MS, INVOKE_TIMEOUT_MS } from '../types/options.js'\nimport type { Action, InvokeActionResponse, ListActionsOptions } from './types.js'\n\nconst ACTIONS_BASE_PATH = '/functions/v1/actions'\n\n/**\n * Service for managing deployed actions (function-service).\n *\n * Actions are user-invokable operations. `params` and `returns` follow the\n * same `Attribute` schema language as entity attributes — the UI form\n * renderer consumes them directly.\n */\nexport interface ActionService {\n /**\n * Lists deployed actions as an async iterator.\n */\n list(options?: ListActionsOptions): PageIterator<Action, ListActionsOptions>\n\n /**\n * Fetches a single page of actions.\n */\n listPage(options?: ListActionsOptions): Promise<ListResult<Action>>\n\n /**\n * Gets a single action by slug. The returned `Action` carries the full\n * `params` and `returns` schemas, suitable for driving an invocation form.\n *\n * @throws {ProteosError} If the action is not found (404).\n */\n get(slug: string): Promise<Action>\n\n /**\n * Invokes a global-scoped action. Returns the unwrapped `result`\n * payload — the wire envelope `{ result }` is unwrapped by the SDK.\n *\n * @throws {ProteosError} On guest validation failures (400, `GUEST_ERROR`),\n * timeouts (504, `TIMEOUT`), traps (500, `TRAP`), or other failure kinds.\n */\n invokeGlobal(slug: string, params: Record<string, unknown>): Promise<unknown>\n\n /**\n * Invokes a PUBLIC (`is_public`) global action without authentication — no\n * Authorization header is sent. This is the only data path available to\n * components on a public page. The action runs server-side as its creator\n * (org + user injected via a machine token); non-public actions 404.\n *\n * @param orgId - Org id (public routes carry the org in the path — there is\n * no token to scope from)\n */\n invokePublic(orgId: string, slug: string, params: Record<string, unknown>): Promise<unknown>\n\n /**\n * Invokes an entity-scoped action against a specific record. Returns the\n * unwrapped `result` payload.\n */\n invokeEntity(\n entitySlug: string,\n recordId: string,\n slug: string,\n params: Record<string, unknown>,\n ): Promise<unknown>\n\n /**\n * Invokes an `entity_batch` action against a SET of records. The whole id\n * array reaches the action in ONE invocation, so the result is a single\n * aggregate payload, not one per record. `recordIds` must be non-empty;\n * the server dedupes it, preserving order. Returns the unwrapped `result`.\n */\n invokeBatch(\n entitySlug: string,\n slug: string,\n recordIds: string[],\n params: Record<string, unknown>,\n ): Promise<unknown>\n}\n\n/**\n * Implementation of ActionService.\n */\nexport class ActionServiceImpl implements ActionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListActionsOptions = {}): PageIterator<Action, ListActionsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListActionsOptions = {}): Promise<ListResult<Action>> {\n return this.client.requestWithQuery<ListResult<Action>>('GET', ACTIONS_BASE_PATH, options)\n }\n\n async get(slug: string): Promise<Action> {\n return this.client.request<Action>('GET', `${ACTIONS_BASE_PATH}/${slug}`)\n }\n\n async invokeGlobal(slug: string, params: Record<string, unknown>): Promise<unknown> {\n const response = await this.client.request<InvokeActionResponse>(\n 'POST',\n `${ACTIONS_BASE_PATH}/${slug}/invoke`,\n params,\n { timeout: INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n\n async invokePublic(\n orgId: string,\n slug: string,\n params: Record<string, unknown>,\n ): Promise<unknown> {\n const response = await this.client.request<InvokeActionResponse>(\n 'POST',\n `/functions/v1/public/orgs/${encodeURIComponent(orgId)}/actions/${encodeURIComponent(slug)}/invoke`,\n params,\n { skipAuth: true, timeout: INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n\n async invokeEntity(\n entitySlug: string,\n recordId: string,\n slug: string,\n params: Record<string, unknown>,\n ): Promise<unknown> {\n const response = await this.client.request<InvokeActionResponse>(\n 'POST',\n `/functions/v1/entities/${entitySlug}/records/${recordId}/actions/${slug}/invoke`,\n params,\n { timeout: INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n\n async invokeBatch(\n entitySlug: string,\n slug: string,\n recordIds: string[],\n params: Record<string, unknown>,\n ): Promise<unknown> {\n // The one invoke route whose body is an envelope rather than the params\n // object itself — an id array has nowhere to live in the path.\n const response = await this.client.request<InvokeActionResponse>(\n 'POST',\n `/functions/v1/entities/${entitySlug}/actions/${slug}/invoke`,\n { record_ids: recordIds, params },\n { timeout: BATCH_INVOKE_TIMEOUT_MS },\n )\n return response.result\n }\n}\n","import { z } from 'zod'\n\nimport { type Attribute, AttributeSchema } from '../meta/types.js'\nimport { type AuditFields, AuditFieldsSchema } from '../types/common.js'\n\n/**\n * Scope of an action. `entity`-scoped actions are invoked against a\n * specific record; `entity_batch` actions against a SET of records of one\n * entity (one invocation carrying every id, never one per record — they back\n * a list's toolbar buttons); `global` actions take no record context.\n */\nexport type ActionScope = 'entity' | 'entity_batch' | 'global'\n\nexport const ActionScopeSchema = z.enum(['entity', 'entity_batch', 'global'])\n\n/**\n * Deployable, user-invokable operation. Mirrors `functionsmodel.Action`\n * in the Go SDK. `params` and `returns` reuse the same `Attribute` schema\n * language as entity attributes — the renderer consumes them directly.\n */\nexport interface Action extends AuditFields {\n slug: string\n org_id: string\n module_slug: string\n scope: ActionScope\n /** Present only when `scope` is `entity` or `entity_batch`. */\n entity?: string\n name: string\n is_active: boolean\n /**\n * When true (global actions only), the action is invokable on the\n * unauthenticated public endpoint\n * `POST /functions/v1/public/orgs/{orgId}/actions/{slug}/invoke`.\n */\n is_public: boolean\n file_id: string\n params: Attribute[]\n returns: Attribute[]\n}\n\nexport const ActionSchema = AuditFieldsSchema.extend({\n slug: z.string(),\n org_id: z.string(),\n module_slug: z.string(),\n scope: ActionScopeSchema,\n entity: z.string().optional(),\n name: z.string(),\n is_active: z.boolean(),\n file_id: z.string(),\n params: z.array(AttributeSchema),\n returns: z.array(AttributeSchema),\n})\n\n/**\n * Options for listing actions.\n */\nexport interface ListActionsOptions {\n page?: number\n page_size?: number\n sort?: string\n scope?: ActionScope\n module_slug?: string\n entity?: string\n is_active?: boolean\n}\n\n/**\n * Wire envelope returned by the invoke endpoints. The SDK unwraps `result`\n * before returning to callers; this type is exported for completeness.\n */\nexport interface InvokeActionResponse {\n result: unknown\n}\n","import type { ProteosClient } from '../client.js'\nimport { type ActionService, ActionServiceImpl } from './actions.js'\n\n/**\n * Facade for the function-service (deployed actions + hooks).\n *\n * @example\n * ```ts\n * const client = new ProteosClient({ baseUrl, tokenProvider });\n * const functions = new FunctionsClient(client);\n * const action = await functions.actions.get('mark-as-signed');\n * const result = await functions.actions.invokeEntity(\n * 'document', recordId, 'mark-as-signed', { signatureType: 'ELECTRONIC' },\n * );\n * ```\n */\nexport class FunctionsClient {\n readonly actions: ActionService\n\n constructor(client: ProteosClient) {\n this.actions = new ActionServiceImpl(client)\n }\n}\n\n// Re-export service interfaces\nexport type { ActionService } from './actions.js'\n\n// Re-export types\nexport type { Action, ActionScope, InvokeActionResponse, ListActionsOptions } from './types.js'\n\n// Re-export Zod schemas\nexport { ActionSchema, ActionScopeSchema } from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { GetGraphOptions, KnowledgeGraph } from './types.js'\n\nconst GRAPH_BASE_PATH = '/knowledge/v1/graph'\n\n/**\n * Service for the whole-org knowledge graph (bulk read backing the radiant graph\n * view). One request returns lean nodes (with per-node label ids + degree),\n * links, the org label set and the total node count.\n */\nexport interface GraphService {\n /**\n * Reads the whole org graph in one payload. `options.label_ids` prunes to\n * nodes carrying ANY of the given labels (union) and `options.space_slugs` to\n * nodes in ANY of the given spaces; omitted returns everything.\n */\n get(options?: GetGraphOptions): Promise<KnowledgeGraph>\n}\n\n/**\n * Implementation of GraphService.\n */\nexport class GraphServiceImpl implements GraphService {\n constructor(private readonly client: ProteosClient) {}\n\n async get(options: GetGraphOptions = {}): Promise<KnowledgeGraph> {\n // The server reads label_ids as a single comma-separated query param (the\n // query binder takes only the first value of a repeated param), so the\n // union list is joined here rather than appended as repeated params.\n const query: { label_ids?: string; space_slugs?: string } = {}\n if (options.label_ids && options.label_ids.length > 0) {\n query.label_ids = options.label_ids.join(',')\n }\n if (options.space_slugs && options.space_slugs.length > 0) {\n query.space_slugs = options.space_slugs.join(',')\n }\n return this.client.requestWithQuery<KnowledgeGraph>('GET', GRAPH_BASE_PATH, query)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateLabelRequest,\n KnowledgeLabel,\n ListLabelsOptions,\n UpdateLabelRequest,\n} from './types.js'\n\nconst LABELS_BASE_PATH = '/knowledge/v1/labels'\n\n/**\n * Service for knowledge labels (categorization handles). To attach/detach a\n * label to a node, use the node service's label methods.\n */\nexport interface LabelService {\n /** Lists labels as an async iterator (pages are 0-indexed). */\n list(options?: ListLabelsOptions): PageIterator<KnowledgeLabel, ListLabelsOptions>\n\n /** Fetches a single page of labels. */\n listPage(options?: ListLabelsOptions): Promise<ListResult<KnowledgeLabel>>\n\n /** Gets a single label by id. */\n get(id: string): Promise<KnowledgeLabel>\n\n /** Creates a label. */\n create(request: CreateLabelRequest): Promise<KnowledgeLabel>\n\n /** Updates a label. */\n update(id: string, request: UpdateLabelRequest): Promise<KnowledgeLabel>\n\n /** Deletes a label; its node associations cascade. */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of LabelService.\n */\nexport class LabelServiceImpl implements LabelService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListLabelsOptions = {}): PageIterator<KnowledgeLabel, ListLabelsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListLabelsOptions = {}): Promise<ListResult<KnowledgeLabel>> {\n return this.client.requestWithQuery<ListResult<KnowledgeLabel>>(\n 'GET',\n LABELS_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<KnowledgeLabel> {\n return this.client.request<KnowledgeLabel>('GET', `${LABELS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateLabelRequest): Promise<KnowledgeLabel> {\n return this.client.request<KnowledgeLabel>('POST', LABELS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateLabelRequest): Promise<KnowledgeLabel> {\n return this.client.request<KnowledgeLabel>('PATCH', `${LABELS_BASE_PATH}/${id}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${LABELS_BASE_PATH}/${id}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateLinkRequest,\n KnowledgeLink,\n ListLinksOptions,\n UpdateLinkRequest,\n} from './types.js'\n\nconst LINKS_BASE_PATH = '/knowledge/v1/links'\n\n/**\n * Service for typed edges (links) between knowledge nodes.\n */\nexport interface LinkService {\n /** Lists links as an async iterator (pages are 0-indexed). */\n list(options?: ListLinksOptions): PageIterator<KnowledgeLink, ListLinksOptions>\n\n /** Fetches a single page of links. */\n listPage(options?: ListLinksOptions): Promise<ListResult<KnowledgeLink>>\n\n /** Gets a single link by id. */\n get(id: string): Promise<KnowledgeLink>\n\n /** Creates a typed edge between two nodes. */\n create(request: CreateLinkRequest): Promise<KnowledgeLink>\n\n /** Updates a link's type / description. */\n update(id: string, request: UpdateLinkRequest): Promise<KnowledgeLink>\n\n /** Deletes a link. */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of LinkService.\n */\nexport class LinkServiceImpl implements LinkService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListLinksOptions = {}): PageIterator<KnowledgeLink, ListLinksOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListLinksOptions = {}): Promise<ListResult<KnowledgeLink>> {\n return this.client.requestWithQuery<ListResult<KnowledgeLink>>('GET', LINKS_BASE_PATH, options)\n }\n\n async get(id: string): Promise<KnowledgeLink> {\n return this.client.request<KnowledgeLink>('GET', `${LINKS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateLinkRequest): Promise<KnowledgeLink> {\n return this.client.request<KnowledgeLink>('POST', LINKS_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateLinkRequest): Promise<KnowledgeLink> {\n return this.client.request<KnowledgeLink>('PATCH', `${LINKS_BASE_PATH}/${id}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${LINKS_BASE_PATH}/${id}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n ContentResponse,\n CreateNodeRequest,\n EditContentRequest,\n EditContentResponse,\n KnowledgeLabel,\n KnowledgeNode,\n KnowledgeNodeLabel,\n KnowledgeNodeMetadata,\n KnowledgeNodeSearchResult,\n ListNodesOptions,\n NeighborsOptions,\n NodeNeighborhood,\n OutlineRequest,\n OutlineResponse,\n SearchContentRequest,\n SearchContentResponse,\n SearchNodesRequest,\n UpdateNodeRequest,\n WriteContentOptions,\n WriteContentResponse,\n} from './types.js'\n\nconst NODES_BASE_PATH = '/knowledge/v1/nodes'\n\n/**\n * Service for knowledge nodes and their content, search, graph neighbors and\n * labels. Reads return node metadata (no body) by default; the body is fetched\n * explicitly with {@link NodeService.getContent}.\n */\nexport interface NodeService {\n /** Lists node metadata as an async iterator (pages are 0-indexed). */\n list(options?: ListNodesOptions): PageIterator<KnowledgeNodeMetadata, ListNodesOptions>\n\n /** Fetches a single page of node metadata. */\n listPage(options?: ListNodesOptions): Promise<ListResult<KnowledgeNodeMetadata>>\n\n /** Gets a node's metadata (body excluded). */\n get(id: string): Promise<KnowledgeNodeMetadata>\n\n /** Creates a node, optionally connecting it to labels/links in one call. */\n create(request: CreateNodeRequest): Promise<KnowledgeNode>\n\n /** Updates a node's metadata (title / status / summary). */\n update(id: string, request: UpdateNodeRequest): Promise<KnowledgeNodeMetadata>\n\n /** Hard-deletes a node; its links and label associations cascade. */\n delete(id: string): Promise<void>\n\n /**\n * Hybrid retrieval. Only `keyword` is wired today; `semantic`/`hybrid` throw a\n * 501 ProteosError until embeddings land.\n */\n search(request: SearchNodesRequest): Promise<ListResult<KnowledgeNodeSearchResult>>\n\n /** Depth-bounded graph walk from a node. */\n neighbors(id: string, options?: NeighborsOptions): Promise<NodeNeighborhood>\n\n /** Reads a node's raw content body plus its line count. */\n getContent(id: string): Promise<ContentResponse>\n\n /** Overwrites a node's content body. Rejects derived (file/url) nodes. */\n writeContent(\n id: string,\n content: string,\n options?: WriteContentOptions,\n ): Promise<WriteContentResponse>\n\n /** Applies a surgical anchored edit to a node's content body. */\n editContent(id: string, request: EditContentRequest): Promise<EditContentResponse>\n\n /**\n * Maps each requested node's body by its markdown heading structure (one or\n * several nodes) — skim a large node, then read just a section's line range.\n */\n getOutline(request: OutlineRequest): Promise<OutlineResponse>\n\n /** Greps each requested node's body for a pattern, with matching lines + context. */\n searchContent(request: SearchContentRequest): Promise<SearchContentResponse>\n\n /** Lists the labels attached to a node. */\n listLabels(id: string): Promise<KnowledgeLabel[]>\n\n /** Attaches an existing label to a node. */\n attachLabel(id: string, labelId: string): Promise<KnowledgeNodeLabel>\n\n /** Detaches a label from a node. */\n detachLabel(id: string, labelId: string): Promise<void>\n}\n\n/**\n * Implementation of NodeService.\n */\nexport class NodeServiceImpl implements NodeService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListNodesOptions = {}): PageIterator<KnowledgeNodeMetadata, ListNodesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListNodesOptions = {}): Promise<ListResult<KnowledgeNodeMetadata>> {\n // The server reads label_ids as a single comma-separated query param (the query\n // binder takes only the first value of a repeated param), so the union list is\n // joined here rather than appended as repeated params (mirrors GraphService.get).\n const { label_ids, space_slugs, ...rest } = options\n const query: Record<string, unknown> = { ...rest }\n if (label_ids && label_ids.length > 0) {\n query.label_ids = label_ids.join(',')\n }\n if (space_slugs && space_slugs.length > 0) {\n query.space_slugs = space_slugs.join(',')\n }\n return this.client.requestWithQuery<ListResult<KnowledgeNodeMetadata>>(\n 'GET',\n NODES_BASE_PATH,\n query,\n )\n }\n\n async get(id: string): Promise<KnowledgeNodeMetadata> {\n return this.client.request<KnowledgeNodeMetadata>('GET', `${NODES_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateNodeRequest): Promise<KnowledgeNode> {\n return this.client.request<KnowledgeNode>('POST', NODES_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateNodeRequest): Promise<KnowledgeNodeMetadata> {\n return this.client.request<KnowledgeNodeMetadata>('PATCH', `${NODES_BASE_PATH}/${id}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${NODES_BASE_PATH}/${id}`)\n }\n\n async search(request: SearchNodesRequest): Promise<ListResult<KnowledgeNodeSearchResult>> {\n return this.client.request<ListResult<KnowledgeNodeSearchResult>>(\n 'POST',\n `${NODES_BASE_PATH}/actions/search`,\n request,\n )\n }\n\n async neighbors(id: string, options: NeighborsOptions = {}): Promise<NodeNeighborhood> {\n return this.client.requestWithQuery<NodeNeighborhood>(\n 'GET',\n `${NODES_BASE_PATH}/${id}/neighbors`,\n options,\n )\n }\n\n async getContent(id: string): Promise<ContentResponse> {\n return this.client.request<ContentResponse>('GET', `${NODES_BASE_PATH}/${id}/content`)\n }\n\n async writeContent(\n id: string,\n content: string,\n options: WriteContentOptions = {},\n ): Promise<WriteContentResponse> {\n return this.client.request<WriteContentResponse>('PUT', `${NODES_BASE_PATH}/${id}/content`, {\n content,\n ...options,\n })\n }\n\n async editContent(id: string, request: EditContentRequest): Promise<EditContentResponse> {\n return this.client.request<EditContentResponse>(\n 'POST',\n `${NODES_BASE_PATH}/${id}/content/actions/edit`,\n request,\n )\n }\n\n async getOutline(request: OutlineRequest): Promise<OutlineResponse> {\n return this.client.request<OutlineResponse>(\n 'POST',\n `${NODES_BASE_PATH}/content/actions/outline`,\n request,\n )\n }\n\n async searchContent(request: SearchContentRequest): Promise<SearchContentResponse> {\n return this.client.request<SearchContentResponse>(\n 'POST',\n `${NODES_BASE_PATH}/content/actions/search`,\n request,\n )\n }\n\n async listLabels(id: string): Promise<KnowledgeLabel[]> {\n const result = await this.client.request<{ data: KnowledgeLabel[] }>(\n 'GET',\n `${NODES_BASE_PATH}/${id}/labels`,\n )\n return result.data\n }\n\n async attachLabel(id: string, labelId: string): Promise<KnowledgeNodeLabel> {\n return this.client.request<KnowledgeNodeLabel>('POST', `${NODES_BASE_PATH}/${id}/labels`, {\n label_id: labelId,\n })\n }\n\n async detachLabel(id: string, labelId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${NODES_BASE_PATH}/${id}/labels/${labelId}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateRecordLinkRequest,\n KnowledgeRecordLink,\n ListRecordLinksOptions,\n} from './types.js'\n\nconst RECORD_LINKS_BASE_PATH = '/knowledge/v1/record-links'\n\n/**\n * Service for node→record edges: links from a knowledge node to a business\n * record (data-service, identified by `entity_slug` + `record_id`). Immutable —\n * create / delete only, no update. Filter by `node_id` (a node's records) or by\n * `entity_slug` + `record_id` (a record's nodes).\n */\nexport interface RecordLinkService {\n /** Lists record links as an async iterator (pages are 0-indexed). */\n list(options?: ListRecordLinksOptions): PageIterator<KnowledgeRecordLink, ListRecordLinksOptions>\n\n /** Fetches a single page of record links. */\n listPage(options?: ListRecordLinksOptions): Promise<ListResult<KnowledgeRecordLink>>\n\n /** Gets a single record link by id. */\n get(id: string): Promise<KnowledgeRecordLink>\n\n /** Links a node to a business record. */\n create(request: CreateRecordLinkRequest): Promise<KnowledgeRecordLink>\n\n /** Removes a record link. */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of RecordLinkService.\n */\nexport class RecordLinkServiceImpl implements RecordLinkService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListRecordLinksOptions = {},\n ): PageIterator<KnowledgeRecordLink, ListRecordLinksOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListRecordLinksOptions = {}): Promise<ListResult<KnowledgeRecordLink>> {\n return this.client.requestWithQuery<ListResult<KnowledgeRecordLink>>(\n 'GET',\n RECORD_LINKS_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<KnowledgeRecordLink> {\n return this.client.request<KnowledgeRecordLink>('GET', `${RECORD_LINKS_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateRecordLinkRequest): Promise<KnowledgeRecordLink> {\n return this.client.request<KnowledgeRecordLink>('POST', RECORD_LINKS_BASE_PATH, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${RECORD_LINKS_BASE_PATH}/${id}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateSpaceRequest,\n KnowledgeSpace,\n ListSpacesOptions,\n UpdateSpaceRequest,\n} from './types.js'\n\nconst SPACES_BASE_PATH = '/knowledge/v1/spaces'\n\n/**\n * Service for knowledge spaces — the containers nodes live in.\n *\n * Every method is keyed by SLUG rather than id: a space's slug is half its\n * primary key and is immutable, so there is no second identifier. To file a node\n * into a space, set `space_slug` on the node (see `NodeService`).\n *\n * Granting access to a space is NOT done here — it goes through the shared\n * `auth.shares` API, which routes `knowledge-spaces` to knowledge-service:\n *\n * ```ts\n * await auth.shares.share('knowledge-spaces', 'engineering', { type: 'team', id: 'platform' }, 'read')\n * ```\n */\nexport interface SpaceService {\n /** Lists spaces as an async iterator (pages are 0-indexed). */\n list(options?: ListSpacesOptions): PageIterator<KnowledgeSpace, ListSpacesOptions>\n\n /** Fetches a single page of spaces. */\n listPage(options?: ListSpacesOptions): Promise<ListResult<KnowledgeSpace>>\n\n /** Gets a single space by slug. */\n get(slug: string): Promise<KnowledgeSpace>\n\n /** Creates a space. The slug is permanent. */\n create(request: CreateSpaceRequest): Promise<KnowledgeSpace>\n\n /**\n * Returns the calling user's own personal space, creating it on first use.\n * Takes no arguments: whose space it is comes from the token. A personal\n * space is created holding grants for its owner only.\n */\n ensurePersonal(): Promise<KnowledgeSpace>\n\n /** Updates a space's presentation. The slug cannot be changed. */\n update(slug: string, request: UpdateSpaceRequest): Promise<KnowledgeSpace>\n\n /**\n * Deletes a space and its access grants.\n *\n * Refused with 409 `knowledge_space_not_empty` while any node still lives in\n * it — deleting a space never deletes the knowledge inside it, and never\n * silently makes it org-visible by unfiling it. Move or delete the nodes first.\n */\n delete(slug: string): Promise<void>\n}\n\n/**\n * Implementation of SpaceService.\n */\nexport class SpaceServiceImpl implements SpaceService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListSpacesOptions = {}): PageIterator<KnowledgeSpace, ListSpacesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListSpacesOptions = {}): Promise<ListResult<KnowledgeSpace>> {\n return this.client.requestWithQuery<ListResult<KnowledgeSpace>>(\n 'GET',\n SPACES_BASE_PATH,\n options,\n )\n }\n\n async get(slug: string): Promise<KnowledgeSpace> {\n return this.client.request<KnowledgeSpace>('GET', `${SPACES_BASE_PATH}/${slug}`)\n }\n\n async create(request: CreateSpaceRequest): Promise<KnowledgeSpace> {\n return this.client.request<KnowledgeSpace>('POST', SPACES_BASE_PATH, request)\n }\n\n async ensurePersonal(): Promise<KnowledgeSpace> {\n return this.client.request<KnowledgeSpace>(\n 'POST',\n `${SPACES_BASE_PATH}/actions/ensure-personal`,\n )\n }\n\n async update(slug: string, request: UpdateSpaceRequest): Promise<KnowledgeSpace> {\n return this.client.request<KnowledgeSpace>('PATCH', `${SPACES_BASE_PATH}/${slug}`, request)\n }\n\n async delete(slug: string): Promise<void> {\n await this.client.request<void>('DELETE', `${SPACES_BASE_PATH}/${slug}`)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n CreateWhiteboardTemplateRequest,\n ListWhiteboardTemplatesOptions,\n UpdateWhiteboardTemplateRequest,\n WhiteboardTemplate,\n WhiteboardTemplateMetadata,\n} from './types.js'\n\nconst WHITEBOARD_TEMPLATES_BASE_PATH = '/knowledge/v1/whiteboard-templates'\n\n/**\n * Service for whiteboard templates: reusable pieces of a whiteboard, shared\n * with the whole org. Everyone who may write knowledge adds templates; only a\n * template's creator or an admin changes or deletes it. No versions: an\n * update overwrites.\n */\nexport interface WhiteboardTemplateService {\n /** Lists templates (metadata only) as an async iterator. */\n list(\n options?: ListWhiteboardTemplatesOptions,\n ): PageIterator<WhiteboardTemplateMetadata, ListWhiteboardTemplatesOptions>\n\n /** Fetches a single page of templates (metadata only). */\n listPage(\n options?: ListWhiteboardTemplatesOptions,\n ): Promise<ListResult<WhiteboardTemplateMetadata>>\n\n /** Gets a template with its elements. */\n get(id: string): Promise<WhiteboardTemplate>\n\n /** Adds a template. */\n create(request: CreateWhiteboardTemplateRequest): Promise<WhiteboardTemplate>\n\n /** Updates a template (its creator or an admin). */\n update(id: string, request: UpdateWhiteboardTemplateRequest): Promise<WhiteboardTemplate>\n\n /** Deletes a template (its creator or an admin). */\n delete(id: string): Promise<void>\n}\n\n/**\n * Implementation of WhiteboardTemplateService.\n */\nexport class WhiteboardTemplateServiceImpl implements WhiteboardTemplateService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListWhiteboardTemplatesOptions = {},\n ): PageIterator<WhiteboardTemplateMetadata, ListWhiteboardTemplatesOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(\n options: ListWhiteboardTemplatesOptions = {},\n ): Promise<ListResult<WhiteboardTemplateMetadata>> {\n return this.client.requestWithQuery<ListResult<WhiteboardTemplateMetadata>>(\n 'GET',\n WHITEBOARD_TEMPLATES_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<WhiteboardTemplate> {\n return this.client.request<WhiteboardTemplate>('GET', `${WHITEBOARD_TEMPLATES_BASE_PATH}/${id}`)\n }\n\n async create(request: CreateWhiteboardTemplateRequest): Promise<WhiteboardTemplate> {\n return this.client.request<WhiteboardTemplate>('POST', WHITEBOARD_TEMPLATES_BASE_PATH, request)\n }\n\n async update(id: string, request: UpdateWhiteboardTemplateRequest): Promise<WhiteboardTemplate> {\n return this.client.request<WhiteboardTemplate>(\n 'PATCH',\n `${WHITEBOARD_TEMPLATES_BASE_PATH}/${id}`,\n request,\n )\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${WHITEBOARD_TEMPLATES_BASE_PATH}/${id}`)\n }\n}\n","import { z } from 'zod'\nimport {\n type AuditFields,\n AuditFieldsSchema,\n type ListOptions,\n type UserRef,\n UserRefSchema,\n} from '../types/common.js'\n\n// ============================================================================\n// Enums\n// ============================================================================\n\n/** A node's kind. `markdown` is authored; `file`/`url` bodies are derived. */\nexport type NodeType = 'markdown' | 'file' | 'url' | 'whiteboard'\n\n/** Lifecycle state of a node. */\nexport type NodeStatus = 'draft' | 'published' | 'archived'\n\n/** Typed edge kinds in the knowledge graph. */\nexport type LinkType =\n | 'references'\n | 'relates_to'\n | 'depends_on'\n | 'part_of'\n | 'derived_from'\n | 'contradicts'\n | 'supports'\n | 'duplicates'\n | 'superseded_by'\n\n/**\n * Retrieval mode for `nodes.search`. Only `keyword` is wired today; `semantic`\n * and `hybrid` are reserved (the server returns 501 until embeddings land).\n */\nexport type MatchMode = 'hybrid' | 'semantic' | 'keyword'\n\n/** Traversal direction for `nodes.neighbors`. */\nexport type NeighborDirection = 'out' | 'in' | 'both'\n\n// ============================================================================\n// Entity Types\n// ============================================================================\n\n/**\n * A node's metadata — everything except the (potentially huge) `content` body\n * and the derived embedding vector. This is what list / get / search / neighbors\n * return by default.\n */\nexport interface KnowledgeNodeMetadata extends AuditFields {\n id: string\n org_id: string\n title: string\n type: NodeType\n status: NodeStatus\n /** Embedding provenance (null until ingestion runs). */\n embedding_model?: string | null\n embedded_at?: string | null\n /**\n * The space this node lives in, or null when UNASSIGNED. An unassigned node\n * is visible to anyone holding knowledge-nodes:read — the behaviour every\n * node had before spaces existed.\n */\n space_slug?: string | null\n /** Source pointer for `file` nodes (storage-service file id). */\n file_id?: string | null\n /** Source pointer for `url` nodes. */\n url?: string | null\n summary?: string | null\n /**\n * Temporal validity window (RFC3339), decoupled from `created_at`. `valid_from`\n * is when the asserted fact starts being true, `valid_until` when it stops.\n * Either null = unbounded on that side (both null = always valid). Half-open\n * `[valid_from, valid_until)`.\n */\n valid_from?: string | null\n valid_until?: string | null\n}\n\n/** A full node: its metadata plus the markdown `content` body. */\nexport interface KnowledgeNode extends KnowledgeNodeMetadata {\n content: string\n}\n\n/** A node returned by search, with its relevance `score`. */\nexport interface KnowledgeNodeSearchResult extends KnowledgeNodeMetadata {\n score: number\n}\n\n/** A typed, directed edge between two nodes. */\nexport interface KnowledgeLink extends AuditFields {\n id: string\n org_id: string\n from_id: string\n to_id: string\n type: LinkType\n description?: string | null\n}\n\n/**\n * A directed edge from a knowledge node to a business record (data-service,\n * identified by `entity_slug` + `record_id`). Immutable once created — only\n * `created_*` audit fields, no update path — so it does NOT extend AuditFields\n * (which carries `updated_*`).\n */\nexport interface KnowledgeRecordLink {\n id: string\n org_id: string\n node_id: string\n entity_slug: string\n record_id: string\n created_at: string\n created_by: UserRef\n}\n\n/** A categorization handle. `slug` is unique within an org. */\nexport interface KnowledgeLabel extends AuditFields {\n id: string\n org_id: string\n name: string\n slug: string\n description?: string | null\n color?: string | null\n icon?: string | null\n}\n\n/** The node↔label association row. */\nexport interface KnowledgeNodeLabel {\n org_id: string\n node_id: string\n label_id: string\n created_at: string\n created_by: UserRef\n}\n\n// ============================================================================\n// Node requests\n// ============================================================================\n\n/** A typed edge from a node being created to an existing node (create-and-connect). */\nexport interface InlineLinkRequest {\n to_id: string\n type: LinkType\n description?: string\n}\n\n/**\n * Create a node, optionally connecting it to the graph in one call. `label_ids`\n * attaches existing labels; `links` creates edges FROM the new node. Both are\n * applied atomically with the node insert.\n */\nexport interface CreateNodeRequest {\n title: string\n type: NodeType\n status: NodeStatus\n content?: string\n /** File the node into a space. Omitted = unassigned. */\n space_slug?: string\n file_id?: string\n url?: string\n summary?: string\n /** Validity window (RFC3339). Omitted = unbounded (NULL). */\n valid_from?: string\n valid_until?: string\n label_ids?: string[]\n links?: InlineLinkRequest[]\n}\n\n/** Partial metadata update. Content is updated via the content methods, not here. */\nexport interface UpdateNodeRequest {\n title?: string\n status?: NodeStatus\n summary?: string\n /**\n * Validity window (RFC3339), tri-state: omit the key to leave unchanged, pass\n * `null` to clear it back to unbounded (re-open validity), or a timestamp to\n * set it. Setting `valid_until` to an instant ends a fact's validity.\n */\n valid_from?: string | null\n valid_until?: string | null\n /**\n * Move the node between spaces, tri-state like the validity window: omit to\n * leave it where it is, pass `null` to move it back to unassigned, or a slug\n * to file it into that space.\n */\n space_slug?: string | null\n}\n\n/** Filters for listing nodes. */\nexport interface ListNodesOptions extends ListOptions {\n type?: NodeType\n status?: NodeStatus\n title?: string\n 'title[contains]'?: string\n /** Keep only nodes carrying ANY of these labels (union). */\n label_ids?: string[]\n /**\n * Keep only nodes living in ANY of these spaces (union). Use\n * `UNASSIGNED_SPACE_SLUG` to ask for nodes belonging to no space.\n */\n space_slugs?: string[]\n /** Created on/after this RFC3339 timestamp (inclusive). */\n created_after?: string\n /** Created on/before this RFC3339 timestamp (inclusive). */\n created_before?: string\n /** Updated on/after this RFC3339 timestamp (inclusive). */\n updated_after?: string\n /** Updated on/before this RFC3339 timestamp (inclusive). */\n updated_before?: string\n /** Validity boundary range filters (RFC3339) — filter on where a node's window start/end falls. */\n valid_from_after?: string\n valid_from_before?: string\n valid_until_after?: string\n valid_until_before?: string\n /**\n * Point-in-time validity filter (RFC3339): keep only nodes valid AT this\n * instant (null-aware, half-open). Set `is_valid: false` to invert it (nodes\n * INVALID at the instant). `is_valid` defaults to true.\n */\n is_valid_at?: string\n is_valid?: boolean\n}\n\n// ── Content sub-resource ────────────────────────────────────────────────\n\n/** A node's raw body plus its line count. */\nexport interface ContentResponse {\n id: string\n content: string\n lines_total: number\n /** Hex SHA-256 of the body — the version token to pass back as\n * `expected_content_hash` when writing, so a newer change is not overwritten. */\n content_hash: string\n}\n\n/**\n * Options for `nodes.writeContent`. `expected_content_hash` makes the write\n * conditional: the server refuses it with 409 `content_conflict` when the\n * stored body no longer hashes to it (someone else wrote it since).\n */\nexport interface WriteContentOptions {\n expected_content_hash?: string\n}\n\nexport interface WriteContentResponse {\n id: string\n lines_total: number\n /** Hash of the body just written. */\n content_hash: string\n}\n\n/** A surgical anchored edit (mirrors Claude Code's `Edit`). */\nexport interface EditContentRequest {\n old_string: string\n new_string: string\n replace_all?: boolean\n}\n\nexport interface EditContentResponse {\n id: string\n replacements: number\n lines_total: number\n}\n\n// ── Within-node navigation: outline & grep ─────────────────────────────────\n\n/** One markdown heading in a node's outline, with the line range of its section. */\nexport interface OutlineHeading {\n level: number\n title: string\n line_start: number\n line_end: number\n}\n\n/** One node's structural map. `headings` is empty for a body with no headings. */\nexport interface NodeOutline {\n node_id: string\n title: string\n lines_total: number\n headings: OutlineHeading[]\n}\n\n/** Outline one or several nodes' bodies in a single call. */\nexport interface OutlineRequest {\n node_ids: string[]\n}\n\nexport interface OutlineResponse {\n results: NodeOutline[]\n}\n\n/** One grep hit: the matching line, the snippet's line range, and the cat -n snippet. */\nexport interface ContentMatch {\n line: number\n line_start: number\n line_end: number\n snippet: string\n}\n\n/** One node's grep result. `match_count` is the true total; `matches` is capped. */\nexport interface NodeContentMatches {\n node_id: string\n title: string\n lines_total: number\n match_count: number\n truncated: boolean\n matches: ContentMatch[]\n}\n\n/** Grep one or several node bodies. Substring by default; set `is_regex` for a regex. */\nexport interface SearchContentRequest {\n node_ids: string[]\n pattern: string\n is_regex?: boolean\n is_case_sensitive?: boolean\n context_lines?: number\n max_matches_per_node?: number\n}\n\nexport interface SearchContentResponse {\n results: NodeContentMatches[]\n}\n\n// ── Search ───────────────────────────────────────────────────────────────\n\n/** Hybrid retrieval request. `match_mode` defaults to `keyword`. */\nexport interface SearchNodesRequest {\n query: string\n match_mode?: MatchMode\n type?: NodeType\n status?: NodeStatus\n /** Match nodes carrying ANY of these labels. */\n label_ids?: string[]\n /**\n * Match nodes living in ANY of these spaces (union). Use\n * `UNASSIGNED_SPACE_SLUG` for nodes belonging to no space.\n */\n space_slugs?: string[]\n /** Match nodes connected (either direction) to this node. */\n linked_to_id?: string\n /**\n * Date-range filters (RFC3339). These only narrow the candidate set; results\n * stay relevance-ordered, so a date filter never reorders hits.\n */\n created_after?: string\n created_before?: string\n updated_after?: string\n updated_before?: string\n /**\n * Point-in-time validity filter (RFC3339): restrict hits to nodes valid AT\n * this instant (or INVALID when `is_valid` is false; defaults to true). Narrows\n * the candidate set only — ordering stays relevance-based.\n */\n is_valid_at?: string\n is_valid?: boolean\n page?: number\n page_size?: number\n}\n\n// ── Neighbors ──────────────────────────────────────────────────────────────\n\n/** Options for a neighbors graph walk. */\nexport interface NeighborsOptions {\n direction?: NeighborDirection\n /** Comma-separated link types to follow (e.g. \"part_of,depends_on\"). */\n link_types?: string\n depth?: number\n}\n\nexport interface NeighborNode {\n id: string\n title: string\n type: NodeType\n status: NodeStatus\n distance: number\n}\n\nexport interface NeighborEdge {\n id: string\n from_id: string\n to_id: string\n type: LinkType\n}\n\nexport interface NodeNeighborhood {\n nodes: NeighborNode[]\n edges: NeighborEdge[]\n}\n\n// ============================================================================\n// Graph (whole-org bulk read for the radiant graph view)\n// ============================================================================\n\n/**\n * A lean node in the whole-graph payload — only what the graph renderer needs.\n * `label_ids` are ordered by attachment time, so `label_ids[0]` is the \"first\"\n * label (the one the UI colours the node by). `degree` is the in+out link count\n * within the returned graph (drives node size).\n */\nexport interface KnowledgeGraphNode {\n id: string\n title: string\n type: NodeType\n status: NodeStatus\n label_ids: string[]\n /** The node's space, or null when unassigned. */\n space_slug?: string | null\n degree: number\n}\n\n/** A lean directed edge in the whole-graph payload. */\nexport interface KnowledgeGraphLink {\n id: string\n from_id: string\n to_id: string\n type: LinkType\n}\n\n/**\n * The whole org graph in one payload: lean nodes + links, the full org label set\n * (sent once — colours every node and powers the filter bar even when the graph\n * is pruned), and `total`, the unfiltered org node count (lets the client decide\n * whether to load the whole graph or switch to progressive/LOD loading).\n */\nexport interface KnowledgeGraph {\n nodes: KnowledgeGraphNode[]\n links: KnowledgeGraphLink[]\n labels: KnowledgeLabel[]\n /**\n * The full org space set, sent once for the same reason as `labels`: the\n * client renders the space navigator and filters by space without a second\n * request, even when the graph is pruned to one space.\n */\n spaces: KnowledgeSpace[]\n total: number\n}\n\n/**\n * Options for `getGraph`. `label_ids` prunes the graph to nodes carrying ANY of\n * the given labels (union); omitted/empty returns the whole org graph.\n */\nexport interface GetGraphOptions {\n label_ids?: string[]\n /** Prune to nodes in ANY of these spaces (union). */\n space_slugs?: string[]\n}\n\n// ============================================================================\n// Link requests\n// ============================================================================\n\nexport interface CreateLinkRequest {\n from_id: string\n to_id: string\n type: LinkType\n description?: string\n}\n\nexport interface UpdateLinkRequest {\n type?: LinkType\n description?: string\n}\n\nexport interface ListLinksOptions extends ListOptions {\n from_id?: string\n to_id?: string\n type?: LinkType\n /** Created on/after this RFC3339 timestamp (inclusive). */\n created_after?: string\n /** Created on/before this RFC3339 timestamp (inclusive). */\n created_before?: string\n /** Updated on/after this RFC3339 timestamp (inclusive). */\n updated_after?: string\n /** Updated on/before this RFC3339 timestamp (inclusive). */\n updated_before?: string\n}\n\n// ============================================================================\n// Record-link requests\n// ============================================================================\n\nexport interface CreateRecordLinkRequest {\n node_id: string\n entity_slug: string\n record_id: string\n}\n\nexport interface ListRecordLinksOptions extends ListOptions {\n node_id?: string\n entity_slug?: string\n record_id?: string\n}\n\n// ============================================================================\n// Spaces\n// ============================================================================\n\n/**\n * A knowledge space: the container a node lives in. A node belongs to at most\n * one space; a node with no space is unassigned.\n *\n * A space is NOT a label. Labels are many-per-node, overlapping, non-security\n * tags; a space is the single place a node lives, and it is what instance-level\n * access is evaluated against.\n *\n * Keyed by `slug`, which is IMMUTABLE — it is half the primary key, node rows\n * reference it and access grants name it, so renaming would orphan both. There\n * is no id.\n */\nexport interface KnowledgeSpace extends AuditFields {\n org_id: string\n slug: string\n name: string\n description?: string | null\n color?: string | null\n icon?: string | null\n /**\n * Who the space is for: `shared` (an ordinary org space) or `personal` (one\n * person's own space, where their assistants keep memory notes). Set at\n * creation and never changed.\n */\n scope: SpaceScope\n /**\n * The person a personal space belongs to; absent on a shared space. It says\n * whose space this is — access still comes only from the space's grants.\n */\n owner_user_id?: string | null\n}\n\nexport type SpaceScope = 'shared' | 'personal'\n\n/**\n * The reserved filter value meaning \"nodes that belong to no space at all\".\n * Deliberately not a legal slug (slugs are kebab-case), so it can never collide\n * with a space an org creates.\n */\nexport const UNASSIGNED_SPACE_SLUG = '__unassigned__'\n\nexport interface CreateSpaceRequest {\n /** Permanent — it is half the primary key and cannot be changed later. */\n slug: string\n name: string\n description?: string\n color?: string\n icon?: string\n}\n\n/** Partial update. `slug` is absent because it is immutable. */\nexport interface UpdateSpaceRequest {\n name?: string\n description?: string\n color?: string\n icon?: string\n}\n\nexport interface ListSpacesOptions extends ListOptions {\n slug?: string\n name?: string\n 'name[contains]'?: string\n}\n\n// ============================================================================\n// Label requests\n// ============================================================================\n\nexport interface CreateLabelRequest {\n name: string\n slug: string\n description?: string\n color?: string\n icon?: string\n}\n\nexport interface UpdateLabelRequest {\n name?: string\n description?: string\n color?: string\n icon?: string\n}\n\nexport interface ListLabelsOptions extends ListOptions {\n slug?: string\n name?: string\n 'name[contains]'?: string\n}\n\n// ============================================================================\n// Whiteboard templates\n// ============================================================================\n\n/**\n * A reusable piece of a whiteboard (a layout, a card, a notation shape),\n * shared with the whole org. Lists return this; `get` adds the elements.\n */\nexport interface WhiteboardTemplateMetadata extends AuditFields {\n id: string\n org_id: string\n name: string\n description?: string | null\n /** Groups templates in the Library sidebar, e.g. \"BPMN\". */\n category?: string | null\n element_count: number\n}\n\n/** A whiteboard template with its Excalidraw elements (unchecked JSON). */\nexport interface WhiteboardTemplate extends WhiteboardTemplateMetadata {\n elements: unknown[]\n}\n\nexport interface CreateWhiteboardTemplateRequest {\n name: string\n description?: string\n category?: string\n /** Excalidraw elements: at most 1,000, 2 MB, board element types only. */\n elements: unknown[]\n}\n\n/** Only the fields present change; `elements` replaces the elements whole. */\nexport interface UpdateWhiteboardTemplateRequest {\n name?: string\n description?: string\n category?: string\n elements?: unknown[]\n}\n\nexport interface ListWhiteboardTemplatesOptions extends ListOptions {\n category?: string\n 'name[contains]'?: string\n}\n\n// ============================================================================\n// Zod schemas (optional runtime validation for consumers who want it)\n// ============================================================================\n\nexport const KnowledgeNodeMetadataSchema = z\n .object({\n id: z.string(),\n org_id: z.string(),\n title: z.string(),\n type: z.enum(['markdown', 'file', 'url', 'whiteboard']),\n status: z.enum(['draft', 'published', 'archived']),\n embedding_model: z.string().nullish(),\n embedded_at: z.string().nullish(),\n file_id: z.string().nullish(),\n url: z.string().nullish(),\n summary: z.string().nullish(),\n valid_from: z.string().nullish(),\n valid_until: z.string().nullish(),\n })\n .merge(AuditFieldsSchema)\n\nexport const KnowledgeNodeSchema = KnowledgeNodeMetadataSchema.extend({\n content: z.string(),\n})\n\nexport const KnowledgeNodeSearchResultSchema = KnowledgeNodeMetadataSchema.extend({\n score: z.number(),\n})\n\nexport const KnowledgeLinkSchema = z\n .object({\n id: z.string(),\n org_id: z.string(),\n from_id: z.string(),\n to_id: z.string(),\n type: z.enum([\n 'references',\n 'relates_to',\n 'depends_on',\n 'part_of',\n 'derived_from',\n 'contradicts',\n 'supports',\n 'duplicates',\n 'superseded_by',\n ]),\n description: z.string().nullish(),\n })\n .merge(AuditFieldsSchema)\n\nexport const KnowledgeRecordLinkSchema = z.object({\n id: z.string(),\n org_id: z.string(),\n node_id: z.string(),\n entity_slug: z.string(),\n record_id: z.string(),\n created_at: z.string(),\n created_by: UserRefSchema,\n})\n\nexport const KnowledgeLabelSchema = z\n .object({\n id: z.string(),\n org_id: z.string(),\n name: z.string(),\n slug: z.string(),\n description: z.string().nullish(),\n color: z.string().nullish(),\n icon: z.string().nullish(),\n })\n .merge(AuditFieldsSchema)\n\nexport const KnowledgeNodeLabelSchema = z.object({\n org_id: z.string(),\n node_id: z.string(),\n label_id: z.string(),\n created_at: z.string(),\n created_by: UserRefSchema,\n})\n\nexport const NodeNeighborhoodSchema = z.object({\n nodes: z.array(\n z.object({\n id: z.string(),\n title: z.string(),\n type: z.enum(['markdown', 'file', 'url', 'whiteboard']),\n status: z.enum(['draft', 'published', 'archived']),\n distance: z.number(),\n }),\n ),\n edges: z.array(\n z.object({\n id: z.string(),\n from_id: z.string(),\n to_id: z.string(),\n type: z.string(),\n }),\n ),\n})\n","import type { ProteosClient } from '../client.js'\nimport { type GraphService, GraphServiceImpl } from './graph.js'\nimport { type LabelService, LabelServiceImpl } from './labels.js'\nimport { type LinkService, LinkServiceImpl } from './links.js'\nimport { type NodeService, NodeServiceImpl } from './nodes.js'\nimport { type RecordLinkService, RecordLinkServiceImpl } from './record-links.js'\nimport { type SpaceService, SpaceServiceImpl } from './spaces.js'\nimport {\n type WhiteboardTemplateService,\n WhiteboardTemplateServiceImpl,\n} from './whiteboard-templates.js'\n\n/**\n * Facade for the knowledge-service (graph-native knowledge base: nodes, typed\n * links, labels, content sub-resource, keyword search and neighbor traversal).\n *\n * Usage:\n * ```ts\n * const client = new ProteosClient({ baseUrl, tokenProvider });\n * const knowledge = new KnowledgeClient(client);\n * const node = await knowledge.nodes.create({ title: 'ADR 1', type: 'markdown', status: 'draft', content: '# ...' });\n * const hits = await knowledge.nodes.search({ query: 'invoicing' });\n * ```\n */\nexport class KnowledgeClient {\n readonly nodes: NodeService\n readonly links: LinkService\n /** Node→record edges (links to data-service records): `knowledge.recordLinks`. */\n readonly recordLinks: RecordLinkService\n readonly labels: LabelService\n /**\n * Knowledge spaces — the containers nodes live in: `knowledge.spaces`.\n * Access to a space is granted through `auth.shares`, not here.\n */\n readonly spaces: SpaceService\n /** Whole-org graph bulk read (radiant graph view): `knowledge.graph.get()`. */\n readonly graph: GraphService\n /** Org-wide whiteboard templates: `knowledge.whiteboardTemplates`. */\n readonly whiteboardTemplates: WhiteboardTemplateService\n\n constructor(client: ProteosClient) {\n this.nodes = new NodeServiceImpl(client)\n this.links = new LinkServiceImpl(client)\n this.recordLinks = new RecordLinkServiceImpl(client)\n this.labels = new LabelServiceImpl(client)\n this.spaces = new SpaceServiceImpl(client)\n this.graph = new GraphServiceImpl(client)\n this.whiteboardTemplates = new WhiteboardTemplateServiceImpl(client)\n }\n}\n\n// Re-export service interfaces\nexport type { GraphService } from './graph.js'\nexport type { LabelService } from './labels.js'\nexport type { LinkService } from './links.js'\nexport type { NodeService } from './nodes.js'\nexport type { RecordLinkService } from './record-links.js'\nexport type { SpaceService } from './spaces.js'\n// Re-export types\nexport type {\n ContentMatch,\n ContentResponse,\n CreateLabelRequest,\n CreateLinkRequest,\n CreateNodeRequest,\n CreateRecordLinkRequest,\n CreateSpaceRequest,\n CreateWhiteboardTemplateRequest,\n EditContentRequest,\n EditContentResponse,\n GetGraphOptions,\n InlineLinkRequest,\n KnowledgeGraph,\n KnowledgeGraphLink,\n KnowledgeGraphNode,\n KnowledgeLabel,\n KnowledgeLink,\n KnowledgeNode,\n KnowledgeNodeLabel,\n KnowledgeNodeMetadata,\n KnowledgeNodeSearchResult,\n KnowledgeRecordLink,\n KnowledgeSpace,\n LinkType,\n ListLabelsOptions,\n ListLinksOptions,\n ListNodesOptions,\n ListRecordLinksOptions,\n ListSpacesOptions,\n ListWhiteboardTemplatesOptions,\n MatchMode,\n NeighborDirection,\n NeighborEdge,\n NeighborNode,\n NeighborsOptions,\n NodeContentMatches,\n NodeNeighborhood,\n NodeOutline,\n NodeStatus,\n NodeType,\n OutlineHeading,\n OutlineRequest,\n OutlineResponse,\n SearchContentRequest,\n SearchContentResponse,\n SearchNodesRequest,\n SpaceScope,\n UpdateLabelRequest,\n UpdateLinkRequest,\n UpdateNodeRequest,\n UpdateSpaceRequest,\n UpdateWhiteboardTemplateRequest,\n WhiteboardTemplate,\n WhiteboardTemplateMetadata,\n WriteContentOptions,\n WriteContentResponse,\n} from './types.js'\n// Re-export the reserved space-filter sentinel (a value, not a type).\n// Re-export Zod schemas\nexport {\n KnowledgeLabelSchema,\n KnowledgeLinkSchema,\n KnowledgeNodeLabelSchema,\n KnowledgeNodeMetadataSchema,\n KnowledgeNodeSchema,\n KnowledgeNodeSearchResultSchema,\n KnowledgeRecordLinkSchema,\n NodeNeighborhoodSchema,\n UNASSIGNED_SPACE_SLUG,\n} from './types.js'\nexport type { WhiteboardTemplateService } from './whiteboard-templates.js'\n","import type { ProteosClient } from '../client.js'\nimport type {\n AvailabilityConstraint,\n BookSchedulingLinkRequest,\n BookSchedulingLinkResponse,\n Calendar,\n CalendarConnection,\n CalendarEvent,\n CalendarEventsResponse,\n CalendarEventType,\n CancelPublicCalendarEventRequest,\n CreateAvailabilityConstraintRequest,\n CreateCalendarConnectionRequest,\n CreateCalendarEventRequest,\n CreateSchedulingLinkRequest,\n GetPublicSlotsQuery,\n GetSlotsRequest,\n GetSlotsResponse,\n ListAvailabilityConstraintsQuery,\n ListCalendarConnectionsQuery,\n ListCalendarEventsQuery,\n ListCalendarEventTypesQuery,\n ListCalendarsQuery,\n ListResponse,\n ListSchedulingLinksQuery,\n PublicBookSchedulingLinkResponse,\n PublicCalendarEvent,\n PublicSchedulingLink,\n PutCalendarEventTypeRequest,\n PutSchedulingProfileRequest,\n RecurrenceScope,\n ReschedulePublicCalendarEventRequest,\n RespondCalendarEventRequest,\n SchedulingLink,\n SchedulingProfile,\n UpdateAvailabilityConstraintRequest,\n UpdateCalendarConnectionRequest,\n UpdateCalendarEventRequest,\n UpdateCalendarEventTypeRequest,\n UpdateCalendarRequest,\n UpdateCalendarSyncRequest,\n UpdateSchedulingLinkRequest,\n} from './types.js'\n\nexport * from './types.js'\n\nconst SCHEDULING_BASE_PATH = '/scheduling/v1'\n\nconst encode = encodeURIComponent\n\n/**\n * Facade for scheduling-service: calendar connections (bindings to\n * connector-service google-calendar / microsoft-calendar grants), the\n * calendars under them with their platform roles, per-user scheduling\n * profiles, and the two-way calendar_event mirror.\n *\n * `*Mine` methods act on the caller's own rows (`/me/...`); `*ForUser`\n * methods are the admin path (`/users/:userId/...`).\n *\n * ```ts\n * const scheduling = new SchedulingClient(client)\n * const connection = await scheduling.calendarConnections.connect({ connection_id })\n * const { data: calendars } = await scheduling.calendars.listMine()\n * await scheduling.calendars.updateMine(calendars[0].id, { is_synced: true })\n * const { data: events } = await scheduling.calendarEvents.list({ from, to })\n * ```\n */\nexport class SchedulingClient {\n readonly calendarConnections: CalendarConnectionService\n readonly calendars: CalendarService\n readonly schedulingProfiles: SchedulingProfileService\n readonly calendarEvents: CalendarEventService\n readonly calendarEventTypes: CalendarEventTypeService\n readonly availabilityConstraints: AvailabilityConstraintService\n readonly slots: SlotService\n readonly schedulingLinks: SchedulingLinkService\n /** The unauthenticated scheduling page + manage page (no Authorization header). */\n readonly public: PublicSchedulingService\n\n constructor(client: ProteosClient) {\n this.schedulingLinks = new SchedulingLinkServiceImpl(client)\n this.public = new PublicSchedulingServiceImpl(client)\n this.calendarConnections = new CalendarConnectionServiceImpl(client)\n this.calendars = new CalendarServiceImpl(client)\n this.schedulingProfiles = new SchedulingProfileServiceImpl(client)\n this.calendarEvents = new CalendarEventServiceImpl(client)\n this.calendarEventTypes = new CalendarEventTypeServiceImpl(client)\n this.availabilityConstraints = new AvailabilityConstraintServiceImpl(client)\n this.slots = new SlotServiceImpl(client)\n }\n}\n\n/** Bindings to connector-service calendar grants. */\nexport interface CalendarConnectionService {\n listMine(query?: ListCalendarConnectionsQuery): Promise<ListResponse<CalendarConnection>>\n /** Bind one of the caller's user-scope calendar connector connections; discovers its calendars. */\n connect(request: CreateCalendarConnectionRequest): Promise<CalendarConnection>\n updateMine(id: string, request: UpdateCalendarConnectionRequest): Promise<CalendarConnection>\n disconnectMine(id: string): Promise<void>\n /** Enqueue a sync of every synced calendar under the connection. */\n syncMine(id: string, request?: UpdateCalendarSyncRequest): Promise<CalendarConnection>\n listForUser(\n userId: string,\n query?: ListCalendarConnectionsQuery,\n ): Promise<ListResponse<CalendarConnection>>\n updateForUser(\n userId: string,\n id: string,\n request: UpdateCalendarConnectionRequest,\n ): Promise<CalendarConnection>\n disconnectForUser(userId: string, id: string): Promise<void>\n}\n\nclass CalendarConnectionServiceImpl implements CalendarConnectionService {\n constructor(private readonly client: ProteosClient) {}\n\n listMine(query: ListCalendarConnectionsQuery = {}): Promise<ListResponse<CalendarConnection>> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/me/calendar-connections`,\n query,\n )\n }\n\n connect(request: CreateCalendarConnectionRequest): Promise<CalendarConnection> {\n return this.client.request('POST', `${SCHEDULING_BASE_PATH}/me/calendar-connections`, request)\n }\n\n updateMine(id: string, request: UpdateCalendarConnectionRequest): Promise<CalendarConnection> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/me/calendar-connections/${encode(id)}`,\n request,\n )\n }\n\n async disconnectMine(id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${SCHEDULING_BASE_PATH}/me/calendar-connections/${encode(id)}`,\n )\n }\n\n syncMine(id: string, request: UpdateCalendarSyncRequest = {}): Promise<CalendarConnection> {\n return this.client.request<CalendarConnection>(\n 'POST',\n `${SCHEDULING_BASE_PATH}/me/calendar-connections/${encode(id)}/sync`,\n request,\n )\n }\n\n listForUser(\n userId: string,\n query: ListCalendarConnectionsQuery = {},\n ): Promise<ListResponse<CalendarConnection>> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendar-connections`,\n query,\n )\n }\n\n updateForUser(\n userId: string,\n id: string,\n request: UpdateCalendarConnectionRequest,\n ): Promise<CalendarConnection> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendar-connections/${encode(id)}`,\n request,\n )\n }\n\n async disconnectForUser(userId: string, id: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendar-connections/${encode(id)}`,\n )\n }\n}\n\n/** Provider calendars under a connection + their platform roles. */\nexport interface CalendarService {\n listMine(query?: ListCalendarsQuery): Promise<ListResponse<Calendar>>\n getMine(id: string): Promise<Calendar>\n updateMine(id: string, request: UpdateCalendarRequest): Promise<Calendar>\n listForUser(userId: string, query?: ListCalendarsQuery): Promise<ListResponse<Calendar>>\n getForUser(userId: string, id: string): Promise<Calendar>\n updateForUser(userId: string, id: string, request: UpdateCalendarRequest): Promise<Calendar>\n}\n\nclass CalendarServiceImpl implements CalendarService {\n constructor(private readonly client: ProteosClient) {}\n\n listMine(query: ListCalendarsQuery = {}): Promise<ListResponse<Calendar>> {\n return this.client.requestWithQuery('GET', `${SCHEDULING_BASE_PATH}/me/calendars`, query)\n }\n\n getMine(id: string): Promise<Calendar> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/me/calendars/${encode(id)}`)\n }\n\n updateMine(id: string, request: UpdateCalendarRequest): Promise<Calendar> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/me/calendars/${encode(id)}`,\n request,\n )\n }\n\n listForUser(userId: string, query: ListCalendarsQuery = {}): Promise<ListResponse<Calendar>> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendars`,\n query,\n )\n }\n\n getForUser(userId: string, id: string): Promise<Calendar> {\n return this.client.request(\n 'GET',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendars/${encode(id)}`,\n )\n }\n\n updateForUser(userId: string, id: string, request: UpdateCalendarRequest): Promise<Calendar> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/calendars/${encode(id)}`,\n request,\n )\n }\n}\n\n/** Per-user scheduling settings (one per org + user; defaults when absent). */\nexport interface SchedulingProfileService {\n getMine(): Promise<SchedulingProfile>\n putMine(request: PutSchedulingProfileRequest): Promise<SchedulingProfile>\n getForUser(userId: string): Promise<SchedulingProfile>\n putForUser(userId: string, request: PutSchedulingProfileRequest): Promise<SchedulingProfile>\n}\n\nclass SchedulingProfileServiceImpl implements SchedulingProfileService {\n constructor(private readonly client: ProteosClient) {}\n\n getMine(): Promise<SchedulingProfile> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/me/scheduling-profile`)\n }\n\n putMine(request: PutSchedulingProfileRequest): Promise<SchedulingProfile> {\n return this.client.request('PUT', `${SCHEDULING_BASE_PATH}/me/scheduling-profile`, request)\n }\n\n getForUser(userId: string): Promise<SchedulingProfile> {\n return this.client.request(\n 'GET',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/scheduling-profile`,\n )\n }\n\n putForUser(userId: string, request: PutSchedulingProfileRequest): Promise<SchedulingProfile> {\n return this.client.request(\n 'PUT',\n `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/scheduling-profile`,\n request,\n )\n }\n}\n\n/** The two-way calendar_event mirror. */\nexport interface CalendarEventService {\n /** A window of events (from/to required, ≤ 93 days); colleagues' events come back projected. */\n list(query: ListCalendarEventsQuery): Promise<CalendarEventsResponse>\n get(id: string): Promise<CalendarEvent>\n /** Write an event through to the provider (calendar_id = own calendar, or hosts). */\n create(request: CreateCalendarEventRequest): Promise<CalendarEvent>\n /** Partial update; `scope` picks the instance or the whole series on recurring events. */\n update(\n id: string,\n request: UpdateCalendarEventRequest,\n scope?: RecurrenceScope,\n ): Promise<CalendarEvent>\n delete(id: string, scope?: RecurrenceScope): Promise<void>\n /** Record the caller's RSVP. */\n respond(id: string, request: RespondCalendarEventRequest): Promise<CalendarEvent>\n}\n\nclass CalendarEventServiceImpl implements CalendarEventService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListCalendarEventsQuery): Promise<CalendarEventsResponse> {\n return this.client.requestWithQuery('GET', `${SCHEDULING_BASE_PATH}/calendar-events`, query)\n }\n\n get(id: string): Promise<CalendarEvent> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/calendar-events/${encode(id)}`)\n }\n\n create(request: CreateCalendarEventRequest): Promise<CalendarEvent> {\n return this.client.request('POST', `${SCHEDULING_BASE_PATH}/calendar-events`, request)\n }\n\n update(\n id: string,\n request: UpdateCalendarEventRequest,\n scope?: RecurrenceScope,\n ): Promise<CalendarEvent> {\n return this.client.requestWithQuery(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/calendar-events/${encode(id)}`,\n scope ? { scope } : undefined,\n request,\n )\n }\n\n async delete(id: string, scope?: RecurrenceScope): Promise<void> {\n await this.client.requestWithQuery(\n 'DELETE',\n `${SCHEDULING_BASE_PATH}/calendar-events/${encode(id)}`,\n scope ? { scope } : undefined,\n )\n }\n\n respond(id: string, request: RespondCalendarEventRequest): Promise<CalendarEvent> {\n return this.client.request(\n 'POST',\n `${SCHEDULING_BASE_PATH}/calendar-events/${encode(id)}/respond`,\n request,\n )\n }\n}\n\n/** The slot-rules catalog: calendar event types, keyed by (org, key). */\nexport interface CalendarEventTypeService {\n list(query?: ListCalendarEventTypesQuery): Promise<ListResponse<CalendarEventType>>\n get(key: string): Promise<CalendarEventType>\n /** Create or replace (PUT semantics: every field is the new value). */\n put(key: string, request: PutCalendarEventTypeRequest): Promise<CalendarEventType>\n update(key: string, request: UpdateCalendarEventTypeRequest): Promise<CalendarEventType>\n delete(key: string): Promise<void>\n}\n\nclass CalendarEventTypeServiceImpl implements CalendarEventTypeService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListCalendarEventTypesQuery = {}): Promise<ListResponse<CalendarEventType>> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/calendar-event-types`,\n query,\n )\n }\n\n get(key: string): Promise<CalendarEventType> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/calendar-event-types/${encode(key)}`)\n }\n\n put(key: string, request: PutCalendarEventTypeRequest): Promise<CalendarEventType> {\n return this.client.request(\n 'PUT',\n `${SCHEDULING_BASE_PATH}/calendar-event-types/${encode(key)}`,\n request,\n )\n }\n\n update(key: string, request: UpdateCalendarEventTypeRequest): Promise<CalendarEventType> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/calendar-event-types/${encode(key)}`,\n request,\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${SCHEDULING_BASE_PATH}/calendar-event-types/${encode(key)}`,\n )\n }\n}\n\n/** A user's hours and blocks. `*Mine` = the caller's own; `*ForUser` = admin path. */\nexport interface AvailabilityConstraintService {\n listMine(query?: ListAvailabilityConstraintsQuery): Promise<ListResponse<AvailabilityConstraint>>\n getMine(id: string): Promise<AvailabilityConstraint>\n createMine(request: CreateAvailabilityConstraintRequest): Promise<AvailabilityConstraint>\n updateMine(\n id: string,\n request: UpdateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint>\n deleteMine(id: string): Promise<void>\n listForUser(\n userId: string,\n query?: ListAvailabilityConstraintsQuery,\n ): Promise<ListResponse<AvailabilityConstraint>>\n getForUser(userId: string, id: string): Promise<AvailabilityConstraint>\n createForUser(\n userId: string,\n request: CreateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint>\n updateForUser(\n userId: string,\n id: string,\n request: UpdateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint>\n deleteForUser(userId: string, id: string): Promise<void>\n}\n\nclass AvailabilityConstraintServiceImpl implements AvailabilityConstraintService {\n constructor(private readonly client: ProteosClient) {}\n\n private base(userId?: string): string {\n return userId\n ? `${SCHEDULING_BASE_PATH}/users/${encode(userId)}/availability-constraints`\n : `${SCHEDULING_BASE_PATH}/me/availability-constraints`\n }\n\n listMine(\n query: ListAvailabilityConstraintsQuery = {},\n ): Promise<ListResponse<AvailabilityConstraint>> {\n return this.client.requestWithQuery('GET', this.base(), query)\n }\n\n getMine(id: string): Promise<AvailabilityConstraint> {\n return this.client.request('GET', `${this.base()}/${encode(id)}`)\n }\n\n createMine(request: CreateAvailabilityConstraintRequest): Promise<AvailabilityConstraint> {\n return this.client.request('POST', this.base(), request)\n }\n\n updateMine(\n id: string,\n request: UpdateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint> {\n return this.client.request('PATCH', `${this.base()}/${encode(id)}`, request)\n }\n\n async deleteMine(id: string): Promise<void> {\n await this.client.request('DELETE', `${this.base()}/${encode(id)}`)\n }\n\n listForUser(\n userId: string,\n query: ListAvailabilityConstraintsQuery = {},\n ): Promise<ListResponse<AvailabilityConstraint>> {\n return this.client.requestWithQuery('GET', this.base(userId), query)\n }\n\n getForUser(userId: string, id: string): Promise<AvailabilityConstraint> {\n return this.client.request('GET', `${this.base(userId)}/${encode(id)}`)\n }\n\n createForUser(\n userId: string,\n request: CreateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint> {\n return this.client.request('POST', this.base(userId), request)\n }\n\n updateForUser(\n userId: string,\n id: string,\n request: UpdateAvailabilityConstraintRequest,\n ): Promise<AvailabilityConstraint> {\n return this.client.request('PATCH', `${this.base(userId)}/${encode(id)}`, request)\n }\n\n async deleteForUser(userId: string, id: string): Promise<void> {\n await this.client.request('DELETE', `${this.base(userId)}/${encode(id)}`)\n }\n}\n\n/** The slot engine: bookable starts of some hosts under a type's / explicit rules. */\nexport interface SlotService {\n get(request: GetSlotsRequest): Promise<GetSlotsResponse>\n}\n\nclass SlotServiceImpl implements SlotService {\n constructor(private readonly client: ProteosClient) {}\n\n get(request: GetSlotsRequest): Promise<GetSlotsResponse> {\n return this.client.request('POST', `${SCHEDULING_BASE_PATH}/slots`, request)\n }\n}\n\n/** Scheduling links: the entry points for taking a slot, plus booking through one. */\nexport interface SchedulingLinkService {\n list(query?: ListSchedulingLinksQuery): Promise<ListResponse<SchedulingLink>>\n get(key: string): Promise<SchedulingLink>\n create(request: CreateSchedulingLinkRequest): Promise<SchedulingLink>\n update(key: string, request: UpdateSchedulingLinkRequest): Promise<SchedulingLink>\n delete(key: string): Promise<void>\n /** The link as an embedded scheduling picker renders it (types, hosts, policy) — private links included. */\n getPage(key: string, contactId?: string): Promise<PublicSchedulingLink>\n /** The link's slots (its hosts + assignment, its type's rules). */\n getSlots(key: string, query: GetPublicSlotsQuery): Promise<GetSlotsResponse>\n /** Take a slot through the link (scheduling-links:read); an empty contact books for the caller. */\n book(key: string, request: BookSchedulingLinkRequest): Promise<BookSchedulingLinkResponse>\n}\n\nclass SchedulingLinkServiceImpl implements SchedulingLinkService {\n constructor(private readonly client: ProteosClient) {}\n\n list(query: ListSchedulingLinksQuery = {}): Promise<ListResponse<SchedulingLink>> {\n return this.client.requestWithQuery('GET', `${SCHEDULING_BASE_PATH}/scheduling-links`, query)\n }\n\n get(key: string): Promise<SchedulingLink> {\n return this.client.request('GET', `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}`)\n }\n\n create(request: CreateSchedulingLinkRequest): Promise<SchedulingLink> {\n return this.client.request('POST', `${SCHEDULING_BASE_PATH}/scheduling-links`, request)\n }\n\n update(key: string, request: UpdateSchedulingLinkRequest): Promise<SchedulingLink> {\n return this.client.request(\n 'PATCH',\n `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}`,\n request,\n )\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request('DELETE', `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}`)\n }\n\n getPage(key: string, contactId?: string): Promise<PublicSchedulingLink> {\n const suffix = contactId ? `?contact_id=${encode(contactId)}` : ''\n return this.client.request(\n 'GET',\n `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}/page${suffix}`,\n )\n }\n\n getSlots(key: string, query: GetPublicSlotsQuery): Promise<GetSlotsResponse> {\n return this.client.requestWithQuery(\n 'GET',\n `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}/slots`,\n query,\n )\n }\n\n book(key: string, request: BookSchedulingLinkRequest): Promise<BookSchedulingLinkResponse> {\n return this.client.request(\n 'POST',\n `${SCHEDULING_BASE_PATH}/scheduling-links/${encode(key)}/calendar-events`,\n request,\n )\n }\n}\n\n/**\n * The unauthenticated scheduling surface: every call sends NO Authorization\n * header (skipAuth), so it is safe on the anonymous /s/ routes. Links answer\n * only when public + enabled; events only with their manage token.\n */\nexport interface PublicSchedulingService {\n getLink(orgId: string, key: string, contactId?: string): Promise<PublicSchedulingLink>\n getSlots(orgId: string, key: string, query: GetPublicSlotsQuery): Promise<GetSlotsResponse>\n book(\n orgId: string,\n key: string,\n request: BookSchedulingLinkRequest,\n ): Promise<PublicBookSchedulingLinkResponse>\n getEvent(orgId: string, id: string, token: string): Promise<PublicCalendarEvent>\n cancel(\n orgId: string,\n id: string,\n request: CancelPublicCalendarEventRequest,\n ): Promise<PublicCalendarEvent>\n reschedule(\n orgId: string,\n id: string,\n request: ReschedulePublicCalendarEventRequest,\n ): Promise<PublicBookSchedulingLinkResponse>\n}\n\nclass PublicSchedulingServiceImpl implements PublicSchedulingService {\n constructor(private readonly client: ProteosClient) {}\n\n private base(orgId: string): string {\n return `${SCHEDULING_BASE_PATH}/public/orgs/${encode(orgId)}`\n }\n\n getLink(orgId: string, key: string, contactId?: string): Promise<PublicSchedulingLink> {\n const suffix = contactId ? `?contact_id=${encode(contactId)}` : ''\n return this.client.request(\n 'GET',\n `${this.base(orgId)}/links/${encode(key)}${suffix}`,\n undefined,\n { skipAuth: true },\n )\n }\n\n getSlots(orgId: string, key: string, query: GetPublicSlotsQuery): Promise<GetSlotsResponse> {\n const params = new URLSearchParams({ from: query.from, to: query.to, timezone: query.timezone })\n if (query.host_user_id) params.set('host_user_id', query.host_user_id)\n if (query.type_key) params.set('type_key', query.type_key)\n return this.client.request(\n 'GET',\n `${this.base(orgId)}/links/${encode(key)}/slots?${params.toString()}`,\n undefined,\n { skipAuth: true },\n )\n }\n\n book(\n orgId: string,\n key: string,\n request: BookSchedulingLinkRequest,\n ): Promise<PublicBookSchedulingLinkResponse> {\n return this.client.request(\n 'POST',\n `${this.base(orgId)}/links/${encode(key)}/calendar-events`,\n request,\n { skipAuth: true },\n )\n }\n\n getEvent(orgId: string, id: string, token: string): Promise<PublicCalendarEvent> {\n return this.client.request(\n 'GET',\n `${this.base(orgId)}/calendar-events/${encode(id)}?token=${encode(token)}`,\n undefined,\n { skipAuth: true },\n )\n }\n\n cancel(\n orgId: string,\n id: string,\n request: CancelPublicCalendarEventRequest,\n ): Promise<PublicCalendarEvent> {\n return this.client.request(\n 'POST',\n `${this.base(orgId)}/calendar-events/${encode(id)}/cancel`,\n request,\n { skipAuth: true },\n )\n }\n\n reschedule(\n orgId: string,\n id: string,\n request: ReschedulePublicCalendarEventRequest,\n ): Promise<PublicBookSchedulingLinkResponse> {\n return this.client.request(\n 'POST',\n `${this.base(orgId)}/calendar-events/${encode(id)}/reschedule`,\n request,\n { skipAuth: true },\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type { PublicAccessOperation } from '../meta/types.js'\nimport type { RequestOptions } from '../types/options.js'\nimport type {\n CreateFileMetadata,\n FileVersionContent,\n StorageFile,\n UpdateFileMetadata,\n} from './types.js'\n\nconst FILES_BASE_PATH = '/storage/v1/files'\n\n/**\n * Service for storing and retrieving files via the storage-service.\n *\n * The storage-service is one-blob-per-id (no directories); each `upload` creates\n * a brand-new file. A `file`-typed record attribute stores only the resulting\n * `{ id, name }` (a `FileRef`); size and content type are resolved on read via\n * {@link FileService.get}.\n */\nexport interface FileService {\n /**\n * Uploads bytes and creates a new file. Returns the created file (including\n * `current_version.size_in_bytes` and `content_type`). The caller derives the\n * `FileRef { id, name }` it stores on the record from the result.\n *\n * `name` defaults to the `File`'s own name; `contentType` to its MIME type.\n * `publicAccess: [\"read\"]` exposes the file on the UNAUTHENTICATED public\n * download route; omit for a private file (the default).\n */\n upload(\n file: File,\n options?: { name?: string; contentType?: string; publicAccess?: PublicAccessOperation[] },\n ): Promise<StorageFile>\n\n /**\n * Creates a file's metadata only (no bytes) — the first step of the upload-URL\n * flow for large files. The returned file is not yet persisted; mint an upload URL\n * with {@link FileService.createUploadUrl} and PUT the bytes to it.\n */\n create(metadata: CreateFileMetadata): Promise<StorageFile>\n\n /**\n * Updates a file's metadata (name, `public_access`) and, when `file` is\n * given, replaces the bytes IN PLACE — a new version under the SAME id, so\n * every `FileRef { id }` pointing at it now resolves to the new content.\n * Only the metadata fields present are changed. Setting\n * `public_access: [\"read\"]` exposes the file on the UNAUTHENTICATED public\n * download route; `[]` revokes it. Replacing a locked file is rejected by\n * the storage-service.\n */\n update(id: string, metadata: UpdateFileMetadata, file?: File): Promise<StorageFile>\n\n /**\n * Mints a short-lived upload URL for a file. The bytes are PUT directly to this URL\n * (raw body, no auth) — keeping large files off the SDK/MCP path. Single-use, ~3 min.\n */\n createUploadUrl(id: string): Promise<{ url: string; expires_at: string }>\n\n /**\n * Triggers content extraction for the file's current version. Asynchronous: returns\n * a `processing` row (or cached `ready` content); poll {@link FileService.getContent}\n * for the terminal status.\n */\n parse(id: string, options?: { parser?: string; force?: boolean }): Promise<FileVersionContent>\n\n /**\n * Fetches the parsed content of the file's current version.\n * @throws {ProteosError} If the file has never been parsed (404).\n */\n getContent(id: string): Promise<FileVersionContent>\n\n /**\n * Fetches a file's metadata by id (name, content type, current version size).\n * @throws {ProteosError} If the file is not found (404).\n */\n get(id: string): Promise<StorageFile>\n\n /**\n * Mints a short-lived public download URL for a file (the token in the URL is\n * the sole credential — no auth header needed). Default: single-use, ≈5 min\n * TTL, suitable for click-to-download. `allowsMultiUse` mints a token that\n * survives repeated GETs (≈1 h TTL) for consumers that probe the URL before\n * downloading.\n */\n /**\n * Permanently deletes a file: every version's stored bytes, its access\n * tokens and parsed content. Irreversible. Locked files are refused\n * (409 `delete_locked_file`) — unlock via {@link FileService.update} first.\n */\n delete(id: string): Promise<void>\n\n /**\n * Permanently deletes a single non-current version and its stored bytes.\n * Irreversible. Deleting the current version is refused\n * (409 `delete_current_version`), as are locked files (409 `delete_locked_file`).\n */\n deleteVersion(id: string, versionId: string): Promise<void>\n\n createDownloadUrl(\n id: string,\n options?: { allowsMultiUse?: boolean },\n ): Promise<{ url: string; expires_at: string }>\n\n /**\n * Downloads the file's current version as a Blob (authenticated). Prefer\n * {@link FileService.createDownloadUrl} for browser click-to-download.\n */\n download(id: string, options?: RequestOptions): Promise<Blob>\n\n /**\n * Downloads the current version of a public-read file through the\n * UNAUTHENTICATED public endpoint (no Authorization header). A non-public\n * or missing file 404s identically.\n */\n downloadPublic(orgId: string, id: string): Promise<Blob>\n\n /**\n * Builds the unauthenticated public download URL for a public-read\n * file — usable directly as an <img src> / <a href> on public pages.\n */\n publicDownloadUrl(orgId: string, id: string): string\n}\n\n/**\n * Implementation of FileService.\n */\nexport class FileServiceImpl implements FileService {\n constructor(private readonly client: ProteosClient) {}\n\n async upload(\n file: File,\n options?: { name?: string; contentType?: string; publicAccess?: PublicAccessOperation[] },\n ): Promise<StorageFile> {\n const metadata: CreateFileMetadata = {\n name: options?.name ?? file.name,\n content_type: options?.contentType ?? file.type ?? 'application/octet-stream',\n ...(options?.publicAccess ? { public_access: options.publicAccess } : {}),\n }\n\n // The storage-service reads multipart parts in order: `metadata` (JSON)\n // first, then `file` (bytes). FormData preserves append order, so the\n // metadata Blob MUST be appended before the file.\n const formData = new FormData()\n formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }))\n formData.append('file', file, metadata.name)\n\n const response = await this.client.requestMultipart<{ data: StorageFile }>(\n 'POST',\n FILES_BASE_PATH,\n formData,\n )\n return response.data\n }\n\n async create(metadata: CreateFileMetadata): Promise<StorageFile> {\n const formData = new FormData()\n formData.append(\n 'metadata',\n new Blob(\n [\n JSON.stringify({\n name: metadata.name,\n content_type: metadata.content_type ?? 'application/octet-stream',\n ...(metadata.public_access ? { public_access: metadata.public_access } : {}),\n }),\n ],\n { type: 'application/json' },\n ),\n )\n const response = await this.client.requestMultipart<{ data: StorageFile }>(\n 'POST',\n FILES_BASE_PATH,\n formData,\n )\n return response.data\n }\n\n async update(id: string, metadata: UpdateFileMetadata, file?: File): Promise<StorageFile> {\n // Part order is load-bearing: the storage-service reads `metadata` first\n // and stops consuming parts at `file` — metadata appended after the file\n // part would be silently dropped.\n const formData = new FormData()\n formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }))\n if (file) formData.append('file', file, metadata.name ?? file.name)\n const response = await this.client.requestMultipart<{ data: StorageFile }>(\n 'PATCH',\n `${FILES_BASE_PATH}/${id}`,\n formData,\n )\n return response.data\n }\n\n async createUploadUrl(id: string): Promise<{ url: string; expires_at: string }> {\n const response = await this.client.request<{ data: { url: string; expires_at: string } }>(\n 'POST',\n `${FILES_BASE_PATH}/${id}/generate-upload-url`,\n )\n return response.data\n }\n\n async parse(\n id: string,\n options?: { parser?: string; force?: boolean },\n ): Promise<FileVersionContent> {\n const response = await this.client.request<{ data: FileVersionContent }>(\n 'POST',\n `${FILES_BASE_PATH}/${id}/parse`,\n options ?? {},\n )\n return response.data\n }\n\n async getContent(id: string): Promise<FileVersionContent> {\n const response = await this.client.request<{ data: FileVersionContent }>(\n 'GET',\n `${FILES_BASE_PATH}/${id}/content`,\n )\n return response.data\n }\n\n async get(id: string): Promise<StorageFile> {\n const response = await this.client.request<{ data: StorageFile }>(\n 'GET',\n `${FILES_BASE_PATH}/${id}`,\n )\n return response.data\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request<void>('DELETE', `${FILES_BASE_PATH}/${id}`)\n }\n\n async deleteVersion(id: string, versionId: string): Promise<void> {\n await this.client.request<void>('DELETE', `${FILES_BASE_PATH}/${id}/versions/${versionId}`)\n }\n\n async createDownloadUrl(\n id: string,\n options?: { allowsMultiUse?: boolean },\n ): Promise<{ url: string; expires_at: string }> {\n const body =\n options?.allowsMultiUse !== undefined\n ? { allows_multi_use: options.allowsMultiUse }\n : undefined\n const response = await this.client.request<{ data: { url: string; expires_at: string } }>(\n 'POST',\n `${FILES_BASE_PATH}/${id}/generate-download-url`,\n body,\n )\n return response.data\n }\n\n /**\n * The file's bytes. `options.timeout` covers reading the whole body, so raise\n * it for large files; `options.signal` aborts the download.\n */\n async download(id: string, options?: RequestOptions): Promise<Blob> {\n const { response } = await this.client.requestRaw(\n 'GET',\n `${FILES_BASE_PATH}/${id}/download`,\n undefined,\n options,\n )\n return await response.blob()\n }\n\n async downloadPublic(orgId: string, id: string): Promise<Blob> {\n const { response } = await this.client.requestRaw(\n 'GET',\n this.publicDownloadPath(orgId, id),\n undefined,\n { skipAuth: true },\n )\n return await response.blob()\n }\n\n publicDownloadUrl(orgId: string, id: string): string {\n return `${this.client.baseUrl}${this.publicDownloadPath(orgId, id)}`\n }\n\n private publicDownloadPath(orgId: string, id: string): string {\n return `/storage/v1/public/orgs/${encodeURIComponent(orgId)}/files/${encodeURIComponent(id)}/download`\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { type FileService, FileServiceImpl } from './files.js'\n\n/**\n * Facade for the storage-service (file upload / download / metadata).\n *\n * Usage:\n * ```ts\n * const client = new ProteosClient({ baseUrl, tokenProvider });\n * const storage = new StorageClient(client);\n * const file = await storage.files.upload(picked); // -> { id, name, ... }\n * const { url } = await storage.files.createDownloadUrl(file.id);\n * ```\n */\nexport class StorageClient {\n readonly files: FileService\n\n constructor(client: ProteosClient) {\n this.files = new FileServiceImpl(client)\n }\n}\n\n// Re-export service interface\nexport type { FileService } from './files.js'\n\n// Re-export types\nexport type {\n CreateFileMetadata,\n FileVersionContent,\n ParseStatus,\n StorageFile,\n StorageFileVersion,\n UpdateFileMetadata,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { EffectiveUsageLimit, Meter, UsageSummaryQuery, UsageSummaryRow } from './types.js'\n\nexport * from './types.js'\n\nconst USAGE_BASE_PATH = '/usage/v1'\n\n/**\n * Facade for usage-service: the metering ledger (read-only) and the org's\n * usage limits. Quantities only, never money.\n *\n * ```ts\n * const usage = new UsageClient(client)\n * const meters = await usage.meters()\n * const rows = await usage.summary({ from, to, group_by: 'day' })\n * const limits = await usage.limits()\n * ```\n */\nexport class UsageClient {\n constructor(private readonly client: ProteosClient) {}\n\n /** The meter catalogue. */\n async meters(): Promise<Meter[]> {\n const response = await this.client.request<{ data: Meter[] }>(\n 'GET',\n `${USAGE_BASE_PATH}/meters`,\n )\n return response.data\n }\n\n /** Totals per meter over a period: sum meters from the ledger, latest meters from snapshots. */\n async summary(query: UsageSummaryQuery): Promise<UsageSummaryRow[]> {\n const response = await this.client.requestWithQuery<{ data: UsageSummaryRow[] }>(\n 'GET',\n `${USAGE_BASE_PATH}/summary`,\n query,\n )\n return response.data\n }\n\n /** The org's limits active now, with their usage in the current window. */\n async limits(): Promise<EffectiveUsageLimit[]> {\n const response = await this.client.request<{ data: EffectiveUsageLimit[] }>(\n 'GET',\n `${USAGE_BASE_PATH}/limits`,\n )\n return response.data\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n GetExecutionDetailResponse,\n GetNodeExecutionItemsOptions,\n GetNodeExecutionItemsResponse,\n ListExecutionsOptions,\n WorkflowExecution,\n} from './types.js'\n\nconst EXECUTIONS_BASE_PATH = '/workflows/v1/executions'\nconst WORKFLOWS_BASE_PATH = '/workflows/v1/workflows'\n\n/**\n * Service for reading Workflow Executions — append-only per-firing run records,\n * keyed by surrogate `id`, referencing their workflow by `workflow_key`.\n */\nexport interface ExecutionService {\n /** Lists executions, auto-paginating. */\n list(options?: ListExecutionsOptions): PageIterator<WorkflowExecution, ListExecutionsOptions>\n /** Fetches a single page of executions with pagination metadata. */\n listPage(options?: ListExecutionsOptions): Promise<ListResult<WorkflowExecution>>\n /** Gets a single execution by id. @throws {ProteosError} 404 if not found. */\n get(id: string): Promise<WorkflowExecution>\n /**\n * Gets the execution detail: the header row plus its append-only node\n * executions (ordered by started_at, then run_index).\n */\n getDetail(id: string): Promise<GetExecutionDetailResponse>\n /**\n * Windows into one node run's stored output items on one port (defaults:\n * port `main`, offset 0, server-side default limit).\n */\n getNodeItems(\n executionId: string,\n nodeId: string,\n runIndex: number,\n options?: GetNodeExecutionItemsOptions,\n ): Promise<GetNodeExecutionItemsResponse>\n /** Lists executions of one workflow (by key). */\n listForWorkflow(\n key: string,\n options?: ListExecutionsOptions,\n ): Promise<ListResult<WorkflowExecution>>\n}\n\nexport class ExecutionServiceImpl implements ExecutionService {\n constructor(private readonly client: ProteosClient) {}\n\n list(\n options: ListExecutionsOptions = {},\n ): PageIterator<WorkflowExecution, ListExecutionsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListExecutionsOptions = {}): Promise<ListResult<WorkflowExecution>> {\n return this.client.requestWithQuery<ListResult<WorkflowExecution>>(\n 'GET',\n EXECUTIONS_BASE_PATH,\n options,\n )\n }\n\n async get(id: string): Promise<WorkflowExecution> {\n return this.client.request<WorkflowExecution>('GET', `${EXECUTIONS_BASE_PATH}/${id}`)\n }\n\n async getDetail(id: string): Promise<GetExecutionDetailResponse> {\n return this.client.request<GetExecutionDetailResponse>(\n 'GET',\n `${EXECUTIONS_BASE_PATH}/${id}/detail`,\n )\n }\n\n async getNodeItems(\n executionId: string,\n nodeId: string,\n runIndex: number,\n options: GetNodeExecutionItemsOptions = {},\n ): Promise<GetNodeExecutionItemsResponse> {\n return this.client.requestWithQuery<GetNodeExecutionItemsResponse>(\n 'GET',\n `${EXECUTIONS_BASE_PATH}/${executionId}/nodes/${nodeId}/runs/${runIndex}/items`,\n options,\n )\n }\n\n async listForWorkflow(\n key: string,\n options: ListExecutionsOptions = {},\n ): Promise<ListResult<WorkflowExecution>> {\n return this.client.requestWithQuery<ListResult<WorkflowExecution>>(\n 'GET',\n `${WORKFLOWS_BASE_PATH}/${key}/executions`,\n options,\n )\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport type {\n GetNodeTypesResponse,\n InvokeNodeMethodRequest,\n InvokeNodeMethodResponse,\n NodeTypeKey,\n WorkflowNodeType,\n} from './types.js'\n\nconst NODE_TYPES_BASE_PATH = '/workflows/v1/node-types'\n\n/**\n * Service for the node-type catalog — the registered NodeDescriptors that\n * drive the editor's picker and parameter forms — and for proxying editor\n * dynamic-method calls (load_options / list_search / …) to the node host.\n */\nexport interface NodeTypeService {\n /**\n * Lists the catalog visible to the caller's org (platform-global +\n * org-installed types, all registered versions, active only).\n */\n list(): Promise<WorkflowNodeType[]>\n /**\n * Invokes a dynamic method on a node type (e.g. `load_options:listEntities`\n * — pass the full `<kind>:<method_name>` string; it is URL-encoded here).\n */\n invokeMethod(\n type: NodeTypeKey,\n method: string,\n request?: InvokeNodeMethodRequest,\n ): Promise<InvokeNodeMethodResponse>\n}\n\nexport class NodeTypeServiceImpl implements NodeTypeService {\n constructor(private readonly client: ProteosClient) {}\n\n async list(): Promise<WorkflowNodeType[]> {\n const response = await this.client.request<GetNodeTypesResponse>('GET', NODE_TYPES_BASE_PATH)\n return response.data\n }\n\n async invokeMethod(\n type: NodeTypeKey,\n method: string,\n request: InvokeNodeMethodRequest = {},\n ): Promise<InvokeNodeMethodResponse> {\n const path = `${NODE_TYPES_BASE_PATH}/${encodeURIComponent(type)}/methods/${encodeURIComponent(method)}`\n return this.client.request<InvokeNodeMethodResponse>('POST', path, request)\n }\n}\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListOptions, ListResult } from '../types/common.js'\nimport type {\n CreateWorkflowRequest,\n ListWorkflowsOptions,\n RunWorkflowRequest,\n TestNodeRequest,\n TestNodeResponse,\n UpdateWorkflowRequest,\n Workflow,\n WorkflowExecution,\n WorkflowVersion,\n WorkflowVersionSummary,\n} from './types.js'\n\nconst WORKFLOWS_BASE_PATH = '/workflows/v1/workflows'\n\n/**\n * Service for managing Workflows — n8n-shaped automation definitions keyed by an\n * immutable kebab-case `key`. Run/pause/unpause drive the Temporal-backed runtime.\n */\nexport interface WorkflowService {\n /** Lists workflows, auto-paginating. */\n list(options?: ListWorkflowsOptions): PageIterator<Workflow, ListWorkflowsOptions>\n /** Fetches a single page of workflows with pagination metadata. */\n listPage(options?: ListWorkflowsOptions): Promise<ListResult<Workflow>>\n /** Gets a single workflow by key. @throws {ProteosError} 404 if not found. */\n get(key: string): Promise<Workflow>\n /** Creates a new workflow. @throws {ProteosError} 400/409. */\n create(request: CreateWorkflowRequest): Promise<Workflow>\n /** Fully replaces a workflow's metadata + graph (version bumped server-side). */\n update(key: string, request: UpdateWorkflowRequest): Promise<Workflow>\n /** Deletes a workflow. @throws {ProteosError} 404 if not found. */\n delete(key: string): Promise<void>\n /**\n * Triggers one manual run; returns the pending execution. Pass\n * `destination_node_id` for a partial \"run until here\" execution (only the\n * destination's ancestors run).\n */\n run(key: string, request?: RunWorkflowRequest): Promise<WorkflowExecution>\n /**\n * Runs ONE node ephemerally against its last-known (or pinned) input and\n * blocks for the result — the editor's \"Run this node\". No execution rows\n * are written; side effects are real.\n */\n testNode(key: string, nodeId: string, request: TestNodeRequest): Promise<TestNodeResponse>\n /** Pauses scheduled/triggered firings. */\n pause(key: string): Promise<Workflow>\n /** Resumes a paused workflow. */\n unpause(key: string): Promise<Workflow>\n /** Lists a workflow's version history (newest first), auto-paginating. */\n listVersions(\n key: string,\n options?: ListOptions,\n ): PageIterator<WorkflowVersionSummary, ListOptions>\n /** Fetches a single page of a workflow's version history (newest first). */\n listVersionsPage(key: string, options?: ListOptions): Promise<ListResult<WorkflowVersionSummary>>\n /** Gets one immutable version of a workflow, graph included. @throws {ProteosError} 404. */\n getVersion(key: string, version: number): Promise<WorkflowVersion>\n /**\n * Restores an old version by saving its graph as a NEW bumped version;\n * returns the updated workflow (its `.version` is the new current version).\n * @throws {ProteosError} 400 when restoring the current version.\n */\n restoreVersion(key: string, version: number): Promise<Workflow>\n}\n\nexport class WorkflowServiceImpl implements WorkflowService {\n constructor(private readonly client: ProteosClient) {}\n\n list(options: ListWorkflowsOptions = {}): PageIterator<Workflow, ListWorkflowsOptions> {\n return new PageIterator((opts) => this.listPage(opts), options)\n }\n\n async listPage(options: ListWorkflowsOptions = {}): Promise<ListResult<Workflow>> {\n return this.client.requestWithQuery<ListResult<Workflow>>('GET', WORKFLOWS_BASE_PATH, options)\n }\n\n async get(key: string): Promise<Workflow> {\n return this.client.request<Workflow>('GET', `${WORKFLOWS_BASE_PATH}/${key}`)\n }\n\n async create(request: CreateWorkflowRequest): Promise<Workflow> {\n return this.client.request<Workflow>('POST', WORKFLOWS_BASE_PATH, request)\n }\n\n async update(key: string, request: UpdateWorkflowRequest): Promise<Workflow> {\n return this.client.request<Workflow>('PATCH', `${WORKFLOWS_BASE_PATH}/${key}`, request)\n }\n\n async delete(key: string): Promise<void> {\n await this.client.request<void>('DELETE', `${WORKFLOWS_BASE_PATH}/${key}`)\n }\n\n async run(key: string, request: RunWorkflowRequest = {}): Promise<WorkflowExecution> {\n return this.client.request<WorkflowExecution>(\n 'POST',\n `${WORKFLOWS_BASE_PATH}/${key}/run`,\n request,\n )\n }\n\n async testNode(key: string, nodeId: string, request: TestNodeRequest): Promise<TestNodeResponse> {\n return this.client.request<TestNodeResponse>(\n 'POST',\n `${WORKFLOWS_BASE_PATH}/${key}/nodes/${nodeId}/test`,\n request,\n )\n }\n\n async pause(key: string): Promise<Workflow> {\n return this.client.request<Workflow>('POST', `${WORKFLOWS_BASE_PATH}/${key}/pause`, {})\n }\n\n async unpause(key: string): Promise<Workflow> {\n return this.client.request<Workflow>('POST', `${WORKFLOWS_BASE_PATH}/${key}/unpause`, {})\n }\n\n listVersions(\n key: string,\n options: ListOptions = {},\n ): PageIterator<WorkflowVersionSummary, ListOptions> {\n return new PageIterator((opts) => this.listVersionsPage(key, opts), options)\n }\n\n async listVersionsPage(\n key: string,\n options: ListOptions = {},\n ): Promise<ListResult<WorkflowVersionSummary>> {\n return this.client.requestWithQuery<ListResult<WorkflowVersionSummary>>(\n 'GET',\n `${WORKFLOWS_BASE_PATH}/${key}/versions`,\n options,\n )\n }\n\n async getVersion(key: string, version: number): Promise<WorkflowVersion> {\n return this.client.request<WorkflowVersion>(\n 'GET',\n `${WORKFLOWS_BASE_PATH}/${key}/versions/${version}`,\n )\n }\n\n async restoreVersion(key: string, version: number): Promise<Workflow> {\n return this.client.request<Workflow>(\n 'POST',\n `${WORKFLOWS_BASE_PATH}/${key}/versions/${version}/restore`,\n {},\n )\n }\n}\n","/**\n * Types for the Proteos Workflow Service API (engine v2).\n *\n * Hand-written mirror of the Go models in `go.proteos.ai/model/workflow`\n * (`workflow.go`, `graph.go`, `node-type.go`, `execution.go`, `item.go` +\n * `api/*-requests.go`). Field names match the snake_case wire format exactly,\n * including enum values.\n *\n * A Workflow is an n8n-shaped automation definition keyed by an immutable\n * kebab-case `key` ((org_id, key) PK). Its graph is catalog-driven: every node\n * references a registered node type (a NodeDescriptor) by an open string type\n * key plus a pinned `type_version`. A WorkflowExecution is one firing of a\n * workflow; per-node results live in append-only NodeExecution rows.\n */\n\nimport type { Attribute } from '../meta/types.js'\nimport type { AuditFields, ListOptions, UserRef } from '../types/common.js'\n\n// ---------------------------------------------------------------------------\n// Graph (v2)\n// ---------------------------------------------------------------------------\n\nexport type WorkflowStatus = 'active' | 'paused' | 'archived'\n\n/**\n * A node's registered type key — open string. Catalog types follow\n * `<package>.<node>` (e.g. `proteos-nodes-core.http-request`); engine-native\n * trigger types keep their legacy `trigger.<kind>` keys.\n */\nexport type NodeTypeKey = string\n\nexport interface NodePosition {\n x: number\n y: number\n}\n\n/** How the interpreter routes a failed node run. */\nexport type OnErrorPolicy = 'stop' | 'continue' | 'continue_error_output'\n\n/**\n * Per-node activity retry policy. `max_attempts: 1` disables retries; zero\n * values fall back to the descriptor's defaults, then the engine defaults.\n */\nexport interface NodeRetryPolicy {\n max_attempts?: number\n backoff_seconds?: number\n}\n\n/**\n * One node in the graph. `parameters` holds the RAW parameter values for the\n * node's descriptor properties (Liquid expressions unresolved — resolution\n * happens at ExecuteNode time).\n */\nexport interface WorkflowNode {\n id: string\n type: NodeTypeKey\n /** Pins one registered descriptor version of `type`. */\n type_version?: number\n name: string\n parameters?: Record<string, unknown>\n /** Credential-type slug → metadata variable key or id. */\n credential_refs?: Record<string, string>\n position?: NodePosition\n is_disabled?: boolean\n notes?: string\n on_error?: OnErrorPolicy\n retry?: NodeRetryPolicy\n}\n\n/** The single-port key used when a connection endpoint omits the port. */\nexport const DEFAULT_PORT = 'main'\n\n/**\n * The reserved output-port key every non-trigger node implicitly has. Under\n * `on_error: continue_error_output` the engine emits one item per input item\n * on it: the input's `json` plus an `error` object (`code`, `message`,\n * `details`, `is_user_error`), paired to the input index. Descriptors never\n * declare this port.\n */\nexport const ERROR_PORT = 'error'\n\n/**\n * One side of a connection: a node by id and one of its ports by key.\n * Connections are id-keyed (renaming a node never breaks the graph) and\n * port-keyed (never index-keyed).\n */\nexport interface ConnectionEndpoint {\n node_id: string\n port: string\n}\n\n/** A directed edge from one node's output port to another node's input port. */\nexport interface WorkflowConnection {\n from: ConnectionEndpoint\n to: ConnectionEndpoint\n}\n\nexport interface WorkflowGraph {\n nodes: WorkflowNode[]\n connections: WorkflowConnection[]\n /**\n * Editor-only per-node pinned output items (keyed by node id) used for\n * partial executions; the production interpreter ignores it unless a run\n * explicitly opts in.\n */\n pin_data?: Record<string, Item[]>\n}\n\n// ---------------------------------------------------------------------------\n// Items\n// ---------------------------------------------------------------------------\n\n/** A storage-service file reference carried by an item (never inline bytes). */\nexport interface BinaryRef {\n file_id: string\n mime_type?: string\n file_name?: string\n size_bytes?: number\n}\n\n/**\n * Item lineage: which input item (and port) produced an output item. The wire\n * shape also allows an int shorthand equivalent to `{ item: n }`.\n */\nexport interface PairedItem {\n item: number\n input?: string\n}\n\n/**\n * The unit of data flowing between workflow nodes (n8n 1:1). Node input/output\n * is a map of port key → `Item[]`.\n */\nexport interface Item {\n json: Record<string, unknown>\n binary?: Record<string, BinaryRef>\n paired_item?: PairedItem | number\n}\n\n// ---------------------------------------------------------------------------\n// Node descriptors (catalog)\n// ---------------------------------------------------------------------------\n\n/**\n * Which runtime executes a node type. `go` nodes are first-party, compiled\n * into the node host; `wasm` nodes are user-defined sandboxed bundles;\n * `intrinsic` types are executed by the interpreter / workflow-service itself.\n */\nexport type NodeRuntime = 'go' | 'wasm' | 'intrinsic'\n\n/** Coarse catalog grouping of a node type. */\nexport type NodeGroup = 'trigger' | 'action' | 'transform' | 'flow'\n\n/** Control type of one descriptor property (n8n INodeProperties paradigm). */\nexport type PropertyType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'options'\n | 'multi_options'\n | 'json'\n | 'date_time'\n | 'color'\n | 'notice'\n | 'hidden'\n | 'collection'\n | 'fixed_collection'\n | 'credentials_select'\n | 'button'\n /** Edits a platform attribute list (`Attribute[]`) via the shared attribute schema builder. */\n /** Edits a decision-question map (model-decide `questions`) via the questions builder, with a raw-JSON mode. */\n | 'decision_questions'\n | 'attribute_schema'\n // Wave 2 (editor support lands with Phase 3):\n | 'resource_locator'\n | 'resource_mapper'\n | 'filter'\n | 'assignment_collection'\n\n/**\n * One named input or output port. Port keys are stable identifiers referenced\n * by connections (never indexes).\n */\nexport interface PortSpec {\n key: string\n display_name?: string\n is_required?: boolean\n max_connections?: number\n}\n\n/**\n * Gates a property's visibility on sibling parameter values. The editor\n * re-evaluates reactively; the backend applies the same rule during validation\n * (hidden properties are ignored). `hide` wins over `show`.\n */\nexport interface DisplayOptions {\n show?: Record<string, unknown[]>\n hide?: Record<string, unknown[]>\n}\n\n/**\n * One entry of an options/multi_options list, one repeatable sub-property\n * group of a collection, or one named group of a fixed_collection (in which\n * case `values` carries the group's fixed sub-fields).\n */\nexport interface PropertyOption {\n name: string\n value?: unknown\n display_name?: string\n description?: string\n values?: NodeProperty[]\n}\n\n/**\n * One parameter in a descriptor's schema. `name` is the verbatim key under\n * `node.parameters` (never case-converted). Every value-bearing property\n * accepts a Liquid expression unless `no_data_expression` is true.\n */\nexport interface NodeProperty {\n display_name: string\n name: string\n type: PropertyType\n default?: unknown\n description?: string\n placeholder?: string\n hint?: string\n is_required?: boolean\n no_data_expression?: boolean\n options?: PropertyOption[]\n display_options?: DisplayOptions\n /**\n * v1 subset: `load_options_method`, `load_options_depends_on`,\n * `multiple_values`, `multiple_value_button_text`, `rows`, `password`,\n * `min_value`, `max_value`, `editor`.\n */\n type_options?: Record<string, unknown>\n}\n\n/** Declares that a node type uses a credential of the given type slug. */\nexport interface CredentialSpec {\n type: string\n is_required?: boolean\n display_options?: DisplayOptions\n}\n\n/**\n * The full, self-describing contract of one node type: drives the editor's\n * picker and parameter form, backend validation, and dispatch.\n */\nexport interface NodeDescriptor {\n type: NodeTypeKey\n display_name: string\n description?: string\n /** Lucide icon name, PascalCase. */\n icon?: string\n group: NodeGroup\n version: number\n runtime: NodeRuntime\n task_queue?: string\n inputs: PortSpec[]\n outputs: PortSpec[]\n properties: NodeProperty[]\n credentials?: CredentialSpec[]\n /** Dynamic methods the host answers, as `\"<kind>:<method_name>\"`. */\n methods?: string[]\n /** Declarative routing spec (Phase 4). */\n routing?: unknown\n documentation_url?: string\n /** Liquid over parameters, shown on the canvas node card. */\n subtitle?: string\n /**\n * Retry policy a node of this type runs with when the graph node sets none.\n * Non-idempotent types pin `max_attempts: 1`; absent = engine defaults.\n */\n default_retry?: NodeRetryPolicy\n}\n\n/** Registry lifecycle of one (type, version) row. */\nexport type NodeTypeStatus = 'active' | 'inactive'\n\n/**\n * One node-type registry row: a registered (package, name, version) with its\n * full descriptor. `org_id` is empty for platform-global types and set for\n * org-installed (wasm) types.\n */\nexport interface WorkflowNodeType {\n package: string\n name: string\n version: number\n runtime: NodeRuntime\n task_queue?: string\n descriptor: NodeDescriptor\n status: NodeTypeStatus\n org_id?: string\n created_at: string\n updated_at: string\n}\n\n// ---------------------------------------------------------------------------\n// Node-type API shapes\n// ---------------------------------------------------------------------------\n\nexport interface GetNodeTypesResponse {\n data: WorkflowNodeType[]\n}\n\n/**\n * An editor dynamic-method call (load_options / list_search /\n * resource_mapper_fields / credential_test) proxied to the node host.\n * `parameters` carries the node's current (partial) parameter values.\n */\nexport interface InvokeNodeMethodRequest {\n type_version?: number\n parameters?: Record<string, unknown>\n credential_refs?: Record<string, string>\n filter?: string\n pagination_token?: string\n}\n\n/** One dynamic dropdown entry returned by a load_options method. */\nexport interface NodeMethodOption {\n name: string\n value: unknown\n description?: string\n}\n\nexport interface InvokeNodeMethodResponse {\n /** load_options */\n options?: NodeMethodOption[]\n /** list_search */\n results?: unknown\n pagination_token?: string\n /** resource_mapper_fields */\n fields?: unknown\n /** credential_test */\n is_valid?: boolean\n message?: string\n}\n\n// ---------------------------------------------------------------------------\n// Engine-native trigger / agent parameters\n// ---------------------------------------------------------------------------\n// Trigger nodes are executed by workflow-service itself; their parameters stay\n// typed. Action/transform/flow node parameters are descriptor-driven raw JSON.\n\nexport interface CronTriggerParams {\n cron_expression: string\n timezone: string\n}\n\n/**\n * Manual trigger configuration. `input_schema` declares the typed inputs a\n * manual run may provide (validated on run; they become the trigger item,\n * addressable as `{{ $json.<name> }}`). Empty = the run takes no inputs.\n */\nexport interface ManualTriggerParams {\n input_schema?: Attribute[]\n}\n\nexport interface WebhookTriggerParams {\n token: string\n}\n\nexport type EventVerb = 'created' | 'updated' | 'deleted'\n\nexport interface EventTriggerParams {\n entity_slug: string\n verbs: EventVerb[]\n}\n\nexport interface MessageTriggerParams {\n direction?: string\n channels?: string[]\n connection_id?: string\n event_types?: string[]\n}\n\n/** Matches every event type on the subscribed topic. */\nexport const PLATFORM_EVENT_WILDCARD = '*'\n\n/**\n * Fires the workflow when an event whose type is in `event_types` arrives on\n * the named platform bus topic. Unlike {@link EventTriggerParams} (records\n * only), any per-org topic in the event catalog is a valid target.\n *\n * `event_types` may hold the single wildcard `'*'` to match every type — custom\n * topics have no catalogued type list, so there is nothing to enumerate.\n */\nexport interface PlatformEventTriggerParams {\n topic: string\n event_types: string[]\n}\n\nexport type KickoffType = 'message' | 'outcome'\n\n/**\n * Where a kickoff slot draws its instruction text from: typed inline\n * (`manual`) or resolved from a reusable agent-service Prompt by key\n * (`prompt`) at run time.\n */\nexport type KickoffSource = 'manual' | 'prompt'\n\n/**\n * Flat, descriptor-driven parameters of the `action.agent` node (gated by\n * display_options on `kickoff_type` / `*_source`). `output_schema` declares\n * the node's structured output as platform attributes — the agent records it\n * via the session-scoped `set_output` tool; `is_output_required` fails the\n * node when the agent finishes without setting it.\n */\nexport interface AgentActionParams {\n agent_key: string\n kickoff_type: KickoffType\n message_source?: KickoffSource\n message_text?: string\n message_prompt_key?: string\n description_source?: KickoffSource\n description?: string\n description_prompt_key?: string\n rubric_source?: KickoffSource\n rubric_type?: 'text' | 'file'\n rubric_content?: string\n rubric_file_id?: string\n rubric_prompt_key?: string\n max_iterations?: number\n output_schema?: Attribute[]\n is_output_required?: boolean\n}\n\n/**\n * Where a model call's optional system instruction comes from. Empty/absent\n * defaults to `none`.\n */\nexport type SystemSource = 'none' | 'manual' | 'prompt'\n\n/**\n * Flat, descriptor-driven parameters of the `proteos-nodes-core.model-call`\n * node: one stateless LLM call per input item. The prompt and the optional\n * system instruction are independently sourced — typed inline (`manual`,\n * Liquid-resolved per item) or resolved verbatim from a reusable Prompt by key\n * (`prompt`). With `has_structured_output`, `output_schema` declares the\n * reply's shape as platform attributes: generation is schema-constrained\n * (forced tool) AND the node validates the returned JSON, failing the item\n * after one automatic repair attempt.\n */\nexport interface ModelCallParams {\n /** Empty resolves to the platform default model. */\n model_id?: string\n temperature?: number\n max_tokens?: number\n prompt_source?: KickoffSource\n prompt_text?: string\n prompt_key?: string\n system_source?: SystemSource\n system_text?: string\n system_prompt_key?: string\n has_structured_output?: boolean\n output_schema?: Attribute[]\n}\n\n// ---------------------------------------------------------------------------\n// Workflow\n// ---------------------------------------------------------------------------\n\nexport interface Workflow extends AuditFields {\n org_id: string\n key: string\n name: string\n description: string\n /** Slug of the module that deployed this workflow; empty when it is org-owned. */\n module_slug: string\n status: WorkflowStatus\n graph: WorkflowGraph\n version: number\n}\n\nexport interface CreateWorkflowRequest {\n key: string\n name: string\n description?: string\n graph: WorkflowGraph\n}\n\nexport interface UpdateWorkflowRequest {\n name: string\n description?: string\n graph: WorkflowGraph\n}\n\n/**\n * Body of a manual \"run now\" call. `destination_node_id` turns the run into a\n * partial \"run until here\" execution: only nodes on a path from the trigger to\n * the destination (inclusive) execute.\n */\nexport interface RunWorkflowRequest {\n destination_node_id?: string\n /** Values for the manual trigger's `input_schema`; seed the trigger item. */\n inputs?: Record<string, unknown>\n}\n\n/** Where a standalone node test's input comes from. */\nexport type TestNodeInputSource = 'last_execution' | 'pinned'\n\n/**\n * The candidate node definition under test — the editor's in-memory (possibly\n * unsaved) state. Parameters stay raw; Liquid resolves on the node host per\n * item, exactly like a real run.\n */\nexport interface TestNodeCandidate {\n type: NodeTypeKey\n type_version?: number\n name?: string\n parameters?: Record<string, unknown>\n credential_refs?: Record<string, string>\n}\n\n/**\n * Runs ONE node ephemerally — no execution rows, real side effects. Input is\n * seeded from the last execution's mirrored input (default) or from the\n * pinned output of the node's upstream neighbors.\n */\nexport interface TestNodeRequest {\n node: TestNodeCandidate\n input_source?: TestNodeInputSource\n}\n\n/**\n * The full test round trip: the input that was fed in (shown even when the\n * node fails) and the produced output, items inline per port. Both sides are\n * capped (`is_truncated`).\n */\nexport interface TestNodeResponse {\n status: 'succeeded' | 'failed' | 'skipped'\n input_source: TestNodeInputSource\n /** False when the workflow (or this node) never ran — nothing was fed in. */\n has_prior_execution: boolean\n input: Record<string, Item[]>\n output: Record<string, Item[]>\n item_counts: Record<string, number>\n error?: ExecutionError\n metadata?: Record<string, unknown>\n is_truncated: boolean\n}\n\nexport interface ListWorkflowsOptions extends ListOptions {\n name?: string\n 'name[contains]'?: string\n status?: WorkflowStatus\n /**\n * Restrict to one module's workflows. The empty string is meaningful: it\n * matches only the org-owned workflows no module deployed.\n *\n * `sort_by` additionally accepts a comma-separated list of sortable fields\n * (`module_slug,name`) so a grouped list can order by its grouping column\n * first; `sort_direction` applies to all of them.\n */\n module_slug?: string\n}\n\n// ---------------------------------------------------------------------------\n// Versions\n// ---------------------------------------------------------------------------\n\n/**\n * The author of a workflow version — a common {@link UserRef} that the\n * versions endpoints enrich with a resolved display `name` when available.\n */\nexport interface WorkflowVersionAuthor extends UserRef {\n name?: string\n}\n\n/**\n * One row of a workflow's version history (newest first). Lightweight — the\n * graph itself is fetched per version via `getVersion`.\n */\nexport interface WorkflowVersionSummary {\n version: number\n nodes_total: number\n created_at: string\n created_by: WorkflowVersionAuthor\n}\n\n/**\n * One immutable, fully materialized workflow version: the graph exactly as it\n * was saved at that version. Versions are append-only — restoring an old\n * version writes its graph as a NEW bumped version, never rewrites history.\n */\nexport interface WorkflowVersion {\n org_id: string\n workflow_key: string\n version: number\n graph: WorkflowGraph\n created_at: string\n created_by: WorkflowVersionAuthor\n}\n\n// ---------------------------------------------------------------------------\n// Execution\n// ---------------------------------------------------------------------------\n\n/**\n * Coarse status of one workflow firing (and of one node run — `skipped` is\n * node-execution-only: the node never ran because no items reached it).\n */\nexport type ExecutionStatus =\n | 'pending'\n | 'running'\n | 'succeeded'\n | 'failed'\n | 'cancelled'\n | 'skipped'\n\nexport type TriggerKind =\n | 'schedule'\n | 'manual'\n | 'webhook'\n | 'event'\n | 'message'\n | 'connector'\n | 'platform_event'\n | 'workflow'\n\n/**\n * Why and how an execution fired. Flat, kind-discriminated: `kind` selects\n * which optional fields are meaningful. `payload` carries the trigger's data\n * payload and seeds the workflow's first item.\n */\nexport interface ExecutionTriggerContext {\n kind: TriggerKind\n // schedule\n scheduled_at?: string\n // manual — the actor, and the partial-run bound when `destination_node_id` was passed\n actor?: UserRef\n destination_node_id?: string\n // webhook\n received_at?: string\n // event\n topic?: string\n event_type?: string\n record_id?: string\n // message\n conversation_id?: string\n channel?: string\n // connector\n connector_key?: string\n connection_id?: string\n // workflow (child executions)\n parent_execution_id?: string\n payload?: unknown\n}\n\nexport interface ExecutionError {\n code: string\n message: string\n /** Machine-readable payload of the node error (a held send's earliest_allowed_at / rule_id, http_status …). */\n details?: Record<string, unknown>\n /** Marks business failures the user can fix, vs infrastructure faults. */\n is_user_error?: boolean\n}\n\n/**\n * One firing of a Workflow. It pins the immutable workflow version it ran\n * against; per-node results live in the append-only NodeExecution rows keyed\n * by (execution_id, node_id, run_index).\n */\nexport interface WorkflowExecution {\n org_id: string\n id: string\n workflow_key: string\n workflow_version: number\n status: ExecutionStatus\n trigger_context: ExecutionTriggerContext\n temporal_workflow_id?: string\n temporal_run_id?: string\n error?: ExecutionError\n started_at?: string\n finished_at?: string\n created_at: string\n created_by: UserRef\n}\n\n/**\n * One run of one node within an execution — append-only, a new row per\n * (node_id, run_index) so loops and retries never overwrite history.\n * `item_counts` counts output items per port; `metadata` carries node-specific\n * extras (e.g. the agent session id).\n */\nexport interface NodeExecution {\n org_id: string\n execution_id: string\n node_id: string\n run_index: number\n node_name: string\n node_type: NodeTypeKey\n status: ExecutionStatus\n input_counts?: Record<string, number>\n item_counts?: Record<string, number>\n error?: ExecutionError\n metadata?: Record<string, unknown>\n started_at?: string\n finished_at?: string\n created_at: string\n}\n\nexport interface ListExecutionsOptions extends ListOptions {\n workflow_key?: string\n status?: ExecutionStatus\n}\n\n// ---------------------------------------------------------------------------\n// Execution API shapes\n// ---------------------------------------------------------------------------\n\n/**\n * Execution detail: the header row plus its append-only node executions.\n * `nodes_total` is the number of nodes the pinned graph schedules for THIS run\n * (reachable from the trigger, scoped to the destination path on a partial run;\n * dead-branch and disabled nodes end as `skipped` rows) — the progress\n * denominator.\n */\nexport interface GetExecutionDetailResponse {\n execution: WorkflowExecution\n node_executions: NodeExecution[]\n nodes_total: number\n}\n\n/** Windows into one node run's stored items on one port. */\nexport interface GetNodeExecutionItemsOptions {\n port?: string\n /**\n * Which side of the node run to read: its own output ports (default) or the\n * mirrored copy of what fed it.\n */\n side?: 'input' | 'output'\n offset?: number\n limit?: number\n}\n\n/** One window of items plus the true total. */\nexport interface GetNodeExecutionItemsResponse {\n items: Item[]\n items_total: number\n offset: number\n limit: number\n}\n","import type { ProteosClient } from '../client.js'\nimport { type ExecutionService, ExecutionServiceImpl } from './executions.js'\nimport { type NodeTypeService, NodeTypeServiceImpl } from './node-types.js'\nimport { type WorkflowService, WorkflowServiceImpl } from './workflows.js'\n\n/**\n * Client for the Proteos Workflow Service API.\n *\n * Manages n8n-shaped automation workflows (keyed by immutable `key`), the\n * node-type catalog (NodeDescriptors) that drives the editor, and workflow\n * executions (Temporal-backed, surrogate-id'd).\n *\n * @example\n * ```ts\n * import { ProteosClient, WorkflowClient } from '@proteos/sdk';\n *\n * const client = new ProteosClient({ baseUrl, token });\n * const workflow = new WorkflowClient(client);\n *\n * const catalog = await workflow.nodeTypes.list();\n * const workflows = await workflow.workflows.list().all();\n * const execution = await workflow.workflows.run('nightly-triage');\n * const detail = await workflow.executions.getDetail(execution.id);\n * ```\n */\nexport class WorkflowClient {\n /** Service for managing workflow definitions. */\n readonly workflows: WorkflowService\n /** Service for reading workflow executions. */\n readonly executions: ExecutionService\n /** Service for the node-type catalog + dynamic node methods. */\n readonly nodeTypes: NodeTypeService\n\n constructor(client: ProteosClient) {\n this.workflows = new WorkflowServiceImpl(client)\n this.executions = new ExecutionServiceImpl(client)\n this.nodeTypes = new NodeTypeServiceImpl(client)\n }\n}\n\nexport type { ExecutionService } from './executions.js'\nexport type { NodeTypeService } from './node-types.js'\nexport type {\n AgentActionParams,\n BinaryRef,\n ConnectionEndpoint,\n CreateWorkflowRequest,\n CredentialSpec,\n CronTriggerParams,\n DisplayOptions,\n EventTriggerParams,\n EventVerb,\n ExecutionError,\n ExecutionStatus,\n ExecutionTriggerContext,\n GetExecutionDetailResponse,\n GetNodeExecutionItemsOptions,\n GetNodeExecutionItemsResponse,\n GetNodeTypesResponse,\n InvokeNodeMethodRequest,\n InvokeNodeMethodResponse,\n Item,\n KickoffSource,\n KickoffType,\n ListExecutionsOptions,\n ListWorkflowsOptions,\n ManualTriggerParams,\n MessageTriggerParams,\n ModelCallParams,\n NodeDescriptor,\n NodeExecution,\n NodeGroup,\n NodeMethodOption,\n NodePosition,\n NodeProperty,\n NodeRetryPolicy,\n NodeRuntime,\n NodeTypeKey,\n NodeTypeStatus,\n OnErrorPolicy,\n PairedItem,\n PortSpec,\n PropertyOption,\n PropertyType,\n RunWorkflowRequest,\n SystemSource,\n TestNodeCandidate,\n TestNodeInputSource,\n TestNodeRequest,\n TestNodeResponse,\n TriggerKind,\n UpdateWorkflowRequest,\n WebhookTriggerParams,\n Workflow,\n WorkflowConnection,\n WorkflowExecution,\n WorkflowGraph,\n WorkflowNode,\n WorkflowNodeType,\n WorkflowStatus,\n WorkflowVersion,\n WorkflowVersionAuthor,\n WorkflowVersionSummary,\n} from './types.js'\nexport { DEFAULT_PORT, ERROR_PORT } from './types.js'\nexport type { WorkflowService } from './workflows.js'\n"]}
|