@proteos/sdk 0.46.0 → 0.47.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/{chunk-Y4CEHIRX.js → chunk-5KEJKXO5.js} +38 -15
- package/dist/chunk-5KEJKXO5.js.map +1 -0
- package/dist/{chunk-F5DHWOGW.cjs → chunk-Z7LC3GGU.cjs} +38 -15
- package/dist/chunk-Z7LC3GGU.cjs.map +1 -0
- package/dist/index.cjs +105 -97
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -9
- package/dist/index.d.ts +18 -9
- package/dist/index.js +11 -3
- package/dist/index.js.map +1 -1
- package/dist/meta/index.cjs +57 -57
- package/dist/meta/index.d.cts +1 -1
- package/dist/meta/index.d.ts +1 -1
- package/dist/meta/index.js +1 -1
- package/dist/{types-D1PRIsSO.d.cts → types-oECz4xTQ.d.cts} +210 -56
- package/dist/{types-D1PRIsSO.d.ts → types-oECz4xTQ.d.ts} +210 -56
- package/package.json +1 -1
- package/src/functions/actions.ts +29 -0
- package/src/functions/types.ts +6 -4
- package/src/meta/layout/control-registry.json +4 -2
- package/src/meta/layout/elements.ts +86 -0
- package/src/meta/layout/index.ts +2 -0
- package/src/meta/types.ts +85 -39
- package/dist/chunk-F5DHWOGW.cjs.map +0 -1
- package/dist/chunk-Y4CEHIRX.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/agents.ts","../src/agent/mcp-servers.ts","../src/agent/prompts.ts","../src/agent/sessions.ts","../src/agent/skills.ts","../src/agent/tools.ts","../src/agent/toolsets.ts","../src/agent/index.ts","../src/auth/me.ts","../src/auth/organizations.ts","../src/auth/roles.ts","../src/errors.ts","../src/auth/shares.ts","../src/auth/teams.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/index.ts","../src/data/queries.ts","../src/data/records.ts","../src/data/types.ts","../src/data/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/spaces.ts","../src/knowledge/record-links.ts","../src/knowledge/types.ts","../src/knowledge/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","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,EA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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\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\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n AppendEventRequest,\n ContentBlock,\n CreateSessionRequest,\n FileBlock,\n ListSessionsOptions,\n ResultBlock,\n Session,\n SessionEvent,\n SessionEventsOptions,\n SessionStreamOptions,\n Turn,\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 /**\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.\n */\n sendUserMessage(\n id: string,\n input: { text?: string; files?: FileBlock[]; turnId?: string },\n ): Promise<SessionEvent>\n /** Convenience: appends a `user.interrupt` to halt the running turn. */\n interrupt(id: string): Promise<SessionEvent>\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\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 return this.client.requestWithQuery<ListResult<Session>>('GET', SESSIONS_BASE_PATH, options)\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 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: { text?: string; files?: FileBlock[]; turnId?: string },\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 return this.appendEvent(id, {\n type: 'user.message',\n ...(input.turnId ? { turn_id: input.turnId } : {}),\n payload: { content },\n })\n }\n\n async interrupt(id: string): Promise<SessionEvent> {\n return this.appendEvent(id, { type: 'user.interrupt' })\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\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(bundle: Blob | File, options?: { displayName?: string; moduleSlug?: string }): 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\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\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'\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 /** 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 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","import type { ProteosClient } from '../client.js'\nimport { type AgentService, AgentServiceImpl } from './agents.js'\nimport { type McpServerService, McpServerServiceImpl } from './mcp-servers.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`.\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 */\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 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.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'\nexport type { PromptService } from './prompts.js'\n// Re-export session types\nexport type {\n AgentArtifactsPayload,\n AgentMessagePayload,\n AppendEventRequest,\n ClientEventType,\n ClientToolSchema,\n ContentBlock,\n ContextCompactedPayload,\n CreateSessionRequest,\n EmptyPayload,\n ErrorPayload,\n EventType,\n FileBlock,\n ListSessionsOptions,\n ModelRequestEndPayload,\n ModelRequestStartPayload,\n ModelUsage,\n ReasoningPayload,\n ResultBlock,\n Session,\n SessionEvent,\n SessionEventEnvelope,\n SessionEventsOptions,\n SessionIdlePayload,\n SessionStatus,\n SessionStreamOptions,\n SessionUpdatedPayload,\n StopReason,\n TextBlock,\n ToolConfirmationPayload,\n ToolResultPayload,\n ToolUsePayload,\n Turn,\n UserMessagePayload,\n} 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 CreateAgentRequest,\n CreateMcpServerRequest,\n CreatePromptRequest,\n CreateToolRequest,\n DependentAgent,\n DependentSyncResult,\n ListAgentsOptions,\n ListMcpServersOptions,\n ListPromptsOptions,\n ListSkillsOptions,\n ListToolsOptions,\n McpBinding,\n McpConnectionState,\n McpConnectionStatus,\n McpServer,\n McpServerAuth,\n McpServerOAuth,\n McpToolSummary,\n ModelConfig,\n Prompt,\n PromptVersion,\n Skill,\n SkillBundle,\n SkillVersion,\n StartMcpOAuthResponse,\n PlatformBinding,\n QueryBinding,\n Tool,\n ToolBinding,\n ToolKind,\n Toolset,\n ToolsetKind,\n ToolsetToolSummary,\n CreateToolsetRequest,\n UpdateToolsetRequest,\n ListToolsetsOptions,\n UpdateAgentRequest,\n UpdateMcpServerRequest,\n UpdatePromptRequest,\n UpdateToolRequest,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { Organization, 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/**\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","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 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} 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 constructor(message: string, httpStatus: number, code: ErrorCodeType | string) {\n super(message)\n this.name = 'ProteosError'\n this.httpStatus = httpStatus\n this.code = code\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}\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\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 } 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)\n}\n","import type { ProteosClient } from '../client.js'\nimport type { PrincipalRef } from '../meta/types.js'\nimport { ProteosError } from '../errors.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 // 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: the other services get the endpoint\n * in later phases, and until then a share must fail with a clear message rather\n * than a bare 404 that reads like the record does not exist.\n */\nconst SERVICES_WITH_SHARING: ReadonlySet<string> = new Set(['/data', '/knowledge'])\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 { 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 UpdateUserRequest,\n User,\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 * 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 *\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 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 // 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 { 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 // 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 // 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 // Connectors (connector-service). `connections` above is shared; this is the\n // manifest catalog.\n { slug: 'connectors', name: 'Connectors' },\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[] = ['knowledge-nodes']\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// 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 RoleService, RoleServiceImpl } from './roles.js'\nimport { type ShareService, ShareServiceImpl } from './shares.js'\nimport { type TeamService, TeamServiceImpl } from './teams.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 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.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 { RoleService } from './roles.js'\nexport type { TeamService } from './teams.js'\nexport type { UserRoleAssignmentService } from './user-role-assignments.js'\n// Re-export types\nexport type {\n // Api key types\n ApiKey,\n AddTeamMemberRequest,\n AssignPermissionRequest,\n AssignRoleRequest,\n // Shared types\n AuthListOptions,\n CreateApiKeyRequest,\n CreatedApiKey,\n CreateOrganizationRequest,\n CreateRoleRequest,\n CreateTeamRequest,\n CreateUserRequest,\n ListOrganizationsOptions,\n ListRolePermissionsOptions,\n ListRolesOptions,\n ListTeamMembersOptions,\n ListTeamsOptions,\n ListOrgUserRoleAssignmentsOptions,\n ListUserRoleAssignmentsOptions,\n ListUsersOptions,\n // Organization types\n Organization,\n // Permission types\n Permission,\n // Role types\n Role,\n RoleEntityPermission,\n // Team types\n Team,\n TeamMember,\n UpdateMeRequest,\n UpdateOrganizationRequest,\n UpdateRoleRequest,\n UpdateTeamRequest,\n UpdateUserRequest,\n // User types\n User,\n // Share types\n SharePermission,\n ShareRequest,\n ShareRow,\n // User role assignment types\n UserRoleAssignment,\n} from './types.js'\n// Re-export Zod schemas\nexport {\n ApiKeySchema,\n OrganizationSchema,\n SharePermissionSchema,\n ShareRequestSchema,\n RoleEntityPermissionSchema,\n RoleSchema,\n TeamMemberSchema,\n TeamSchema,\n UserRoleAssignmentSchema,\n UserSchema,\n} from './types.js'\n// Re-export service interfaces\nexport type { UserService } from './users.js'\n// Share routing — exported so a UI can hide a share affordance it cannot serve.\nexport { isShareable, type ShareService, shareRouteFor } from './shares.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 * 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","import { type EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-source'\nimport { 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 * 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.options.fetch(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 // 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.options.fetch(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.options.fetch(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 type {\n Connector,\n ConnectorConnection,\n ConnectorMethod,\n ConnectionTokenResponse,\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('GET', `${CONNECTOR_BASE_PATH}/connectors/${encodeURIComponent(key)}`)\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('GET', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`)\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('PATCH', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`)\n }\n\n install(id: string): Promise<InstallConnectorConnectionResponse> {\n return this.client.request('POST', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/install`)\n }\n\n token(id: string): Promise<ConnectionTokenResponse> {\n return this.client.request('POST', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/token`)\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 )\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","import type { ProteosClient } from '../client.js'\nimport type {\n AcceptMistranscribedTermRequest,\n AgentListener,\n AttachContactAddressRequest,\n BlockContactRequest,\n Connection,\n Contact,\n ContactAddress,\n ContactErasureRequest,\n ContactGroup,\n ContactMergeProposal,\n Conversation,\n ConversationFilter,\n ConversationFilterEvent,\n ConversationType,\n CreateAgentListenerRequest,\n CreateConnectionRequest,\n CreateContactGroupRequest,\n CreateContactRequest,\n ContactRecordLink,\n CreateContactRecordLinkRequest,\n ListContactRecordLinksQuery,\n CreateConversationFilterRequest,\n CreateConversationTypeRequest,\n CreateGlossaryTermRequest,\n CreateToneProfileSetupRequest,\n CreateTranscriptionRequest,\n DeleteConnectionQuery,\n DispatchMeetingBotRequest,\n GlossaryTerm,\n InstallConnectionResponse,\n ListAgentListenersQuery,\n ListConnectionsQuery,\n ListContactAddressesQuery,\n ListContactGroupsQuery,\n ListContactMergeProposalsQuery,\n ListContactsQuery,\n ListConversationFilterEventsQuery,\n ListConversationFiltersQuery,\n ListConversationsQuery,\n ListConversationTypesQuery,\n ListGlossaryTermsQuery,\n ListMessagesQuery,\n ListMistranscribedTermsQuery,\n ListReactionsResponse,\n ListResponse,\n ListRoomsQuery,\n ListToneProfileSetupsQuery,\n ListToneProfilesQuery,\n ListTranscriptionsQuery,\n MaterializeTranscriptionRequest,\n MergeContactsRequest,\n Message,\n MistranscribedTerm,\n Reaction,\n RecordPermissionEventRequest,\n ResolveToneProfileQuery,\n Room,\n SendMessageRequest,\n SyncConnectionRequest,\n ToneProfile,\n ToneProfileSetup,\n Transcription,\n UnreadCounts,\n UpdateAgentListenerRequest,\n UpdateConnectionRequest,\n UpdateContactGroupRequest,\n UpdateContactRequest,\n UpdateConversationFilterRequest,\n UpdateConversationRequest,\n UpdateConversationTypeRequest,\n UpdateDraftRequest,\n UpdateGlossaryTermRequest,\n UpdateTranscriptionRequest,\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 /** 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 /** 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, remove from a meeting. */\n readonly meetings: MeetingService\n /** Realtime speech-to-text (dictation) — moved here from agent-service. */\n readonly voice: VoiceService\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.glossaryTerms = new GlossaryTermServiceImpl(client)\n this.conversationTypes = new ConversationTypeServiceImpl(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.voice = new VoiceServiceImpl(client)\n }\n}\n\n/** Meeting bots (Ava) — dispatch by meeting URL and removal. */\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 /** Make the bot leave the meeting and end the conversation (by conversation id). */\n remove(conversationId: string): 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 remove(conversationId: string): Promise<Conversation> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/meetings/${encodeURIComponent(conversationId)}`,\n )\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/** 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 /** Begin the connector's install flow; open the returned URL in a popup. */\n install(id: string): 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\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): Promise<InstallConnectionResponse> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}/install`,\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\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 /** Manually mint a contact (sync dedup — 409 contact_address_taken on any owned address). */\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 recordPermissionEvent(contactId: string, request: RecordPermissionEventRequest): Promise<Contact>\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(query: ListContactRecordLinksQuery = {}): 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 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 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 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(): 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 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(): Promise<UnreadCounts> {\n return this.client.request('GET', `${CONVERSATION_BASE_PATH}/conversations/unread-counts`)\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 * 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 /** 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 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 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 * 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\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\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 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 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\nexport type * 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","import type { ProteosClient } from '../client.js'\n\nconst QUERY_BASE_PATH = '/data/v1/query'\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 * Service for the raw-SQL query endpoint of the data-service.\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\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","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 ListRecordsOptions,\n RecordData,\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\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 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","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]`, `[starts_with]`,\n * `[ends_with]`, `[empty]`, `[not_empty]`. Missing operator defaults to `[eq]`.\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","import type { ProteosClient } from '../client.js'\nimport { type QueryService, QueryServiceImpl } from './queries.js'\nimport { type RecordService, RecordServiceImpl } 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\n constructor(client: ProteosClient) {\n this.records = new RecordServiceImpl(client)\n this.queries = new QueryServiceImpl(client)\n }\n}\n\n// Re-export service interfaces\n// Re-export types\nexport type {\n QueryExecuteMeta,\n QueryExecuteResponse,\n QueryRow,\n QueryService,\n QueryValidateMeta,\n QueryValidateResponse,\n} from './queries.js'\nexport type { RecordService } from './records.js'\nexport type {\n BatchTransactionError,\n BatchTransactionStatus,\n BatchUpsertRecordsResponse,\n BatchUpsertTransaction,\n BatchUpsertTransactionResult,\n ListRecordsOptions,\n RecordData,\n} from './types.js'\n\n// Re-export Zod schemas\nexport {\n BatchTransactionErrorSchema,\n BatchUpsertRecordsResponseSchema,\n BatchUpsertTransactionResultSchema,\n BatchUpsertTransactionSchema,\n} from './types.js'\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<{ data: PlatformEvent[] }, ListEventsOptions>(\n 'GET',\n `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/events`,\n options,\n )\n return response.data ?? []\n }\n\n async *tail(topic: string, options: TailOptions = {}): 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 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/**\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 )\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 },\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 )\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; `global` actions take no record context.\n */\nexport type ActionScope = 'entity' | 'global'\n\nexport const ActionScopeSchema = z.enum(['entity', '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 === 'entity'`. */\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 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(id: string, content: string): 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(id: string, content: string): Promise<WriteContentResponse> {\n return this.client.request<WriteContentResponse>('PUT', `${NODES_BASE_PATH}/${id}/content`, {\n content,\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 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 /** 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 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 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 { 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'\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}\n\nexport interface WriteContentResponse {\n id: string\n lines_total: number\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\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// 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']),\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']),\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 SpaceService, SpaceServiceImpl } from './spaces.js'\nimport { type RecordLinkService, RecordLinkServiceImpl } from './record-links.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\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 }\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 { SpaceService } from './spaces.js'\nexport type { RecordLinkService } from './record-links.js'\n\n// Re-export types\nexport type {\n ContentMatch,\n ContentResponse,\n CreateLabelRequest,\n CreateLinkRequest,\n CreateNodeRequest,\n CreateRecordLinkRequest,\n CreateSpaceRequest,\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 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 UpdateLabelRequest,\n UpdateLinkRequest,\n UpdateNodeRequest,\n UpdateSpaceRequest,\n WriteContentResponse,\n} from './types.js'\n\n// Re-export the reserved space-filter sentinel (a value, not a type).\nexport { UNASSIGNED_SPACE_SLUG } from './types.js'\n\n// Re-export Zod schemas\nexport {\n KnowledgeLabelSchema,\n KnowledgeLinkSchema,\n KnowledgeNodeLabelSchema,\n KnowledgeNodeMetadataSchema,\n KnowledgeNodeSchema,\n KnowledgeNodeSearchResultSchema,\n KnowledgeRecordLinkSchema,\n NodeNeighborhoodSchema,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { PublicAccessOperation } from '../meta/types.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): 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(\n 'metadata',\n new Blob([JSON.stringify(metadata)], { type: 'application/json' }),\n )\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 async download(id: string): Promise<Blob> {\n const { response } = await this.client.requestRaw('GET', `${FILES_BASE_PATH}/${id}/download`)\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 the `on_error: continue_error_output` policy\n * routes failed items to, when the node's descriptor declares it.\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 | '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\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 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\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 /** 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/prompts.ts","../src/agent/sessions.ts","../src/agent/skills.ts","../src/agent/tools.ts","../src/agent/toolsets.ts","../src/agent/index.ts","../src/auth/me.ts","../src/auth/organizations.ts","../src/auth/roles.ts","../src/errors.ts","../src/auth/shares.ts","../src/auth/teams.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/index.ts","../src/data/queries.ts","../src/data/records.ts","../src/data/types.ts","../src/data/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/spaces.ts","../src/knowledge/record-links.ts","../src/knowledge/types.ts","../src/knowledge/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","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,G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AAM,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\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\n","import type { ProteosClient } from '../client.js'\nimport { PageIterator } from '../iterator.js'\nimport type { ListResult } from '../types/common.js'\nimport type {\n AppendEventRequest,\n ContentBlock,\n CreateSessionRequest,\n FileBlock,\n ListSessionsOptions,\n ResultBlock,\n Session,\n SessionEvent,\n SessionEventsOptions,\n SessionStreamOptions,\n Turn,\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 /**\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.\n */\n sendUserMessage(\n id: string,\n input: { text?: string; files?: FileBlock[]; turnId?: string },\n ): Promise<SessionEvent>\n /** Convenience: appends a `user.interrupt` to halt the running turn. */\n interrupt(id: string): Promise<SessionEvent>\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\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 return this.client.requestWithQuery<ListResult<Session>>('GET', SESSIONS_BASE_PATH, options)\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 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: { text?: string; files?: FileBlock[]; turnId?: string },\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 return this.appendEvent(id, {\n type: 'user.message',\n ...(input.turnId ? { turn_id: input.turnId } : {}),\n payload: { content },\n })\n }\n\n async interrupt(id: string): Promise<SessionEvent> {\n return this.appendEvent(id, { type: 'user.interrupt' })\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\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(bundle: Blob | File, options?: { displayName?: string; moduleSlug?: string }): 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\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\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'\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 /** 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 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","import type { ProteosClient } from '../client.js'\nimport { type AgentService, AgentServiceImpl } from './agents.js'\nimport { type McpServerService, McpServerServiceImpl } from './mcp-servers.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`.\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 */\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 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.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'\nexport type { PromptService } from './prompts.js'\n// Re-export session types\nexport type {\n AgentArtifactsPayload,\n AgentMessagePayload,\n AppendEventRequest,\n ClientEventType,\n ClientToolSchema,\n ContentBlock,\n ContextCompactedPayload,\n CreateSessionRequest,\n EmptyPayload,\n ErrorPayload,\n EventType,\n FileBlock,\n ListSessionsOptions,\n ModelRequestEndPayload,\n ModelRequestStartPayload,\n ModelUsage,\n ReasoningPayload,\n ResultBlock,\n Session,\n SessionEvent,\n SessionEventEnvelope,\n SessionEventsOptions,\n SessionIdlePayload,\n SessionStatus,\n SessionStreamOptions,\n SessionUpdatedPayload,\n StopReason,\n TextBlock,\n ToolConfirmationPayload,\n ToolResultPayload,\n ToolUsePayload,\n Turn,\n UserMessagePayload,\n} 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 CreateAgentRequest,\n CreateMcpServerRequest,\n CreatePromptRequest,\n CreateToolRequest,\n DependentAgent,\n DependentSyncResult,\n ListAgentsOptions,\n ListMcpServersOptions,\n ListPromptsOptions,\n ListSkillsOptions,\n ListToolsOptions,\n McpBinding,\n McpConnectionState,\n McpConnectionStatus,\n McpServer,\n McpServerAuth,\n McpServerOAuth,\n McpToolSummary,\n ModelConfig,\n Prompt,\n PromptVersion,\n Skill,\n SkillBundle,\n SkillVersion,\n StartMcpOAuthResponse,\n PlatformBinding,\n QueryBinding,\n Tool,\n ToolBinding,\n ToolKind,\n Toolset,\n ToolsetKind,\n ToolsetToolSummary,\n CreateToolsetRequest,\n UpdateToolsetRequest,\n ListToolsetsOptions,\n UpdateAgentRequest,\n UpdateMcpServerRequest,\n UpdatePromptRequest,\n UpdateToolRequest,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { Organization, 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/**\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","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 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} 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 constructor(message: string, httpStatus: number, code: ErrorCodeType | string) {\n super(message)\n this.name = 'ProteosError'\n this.httpStatus = httpStatus\n this.code = code\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}\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\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 } 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)\n}\n","import type { ProteosClient } from '../client.js'\nimport type { PrincipalRef } from '../meta/types.js'\nimport { ProteosError } from '../errors.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 // 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: the other services get the endpoint\n * in later phases, and until then a share must fail with a clear message rather\n * than a bare 404 that reads like the record does not exist.\n */\nconst SERVICES_WITH_SHARING: ReadonlySet<string> = new Set(['/data', '/knowledge'])\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 { 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 UpdateUserRequest,\n User,\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 * 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 *\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 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 // 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 { 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 // 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 // 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 // Connectors (connector-service). `connections` above is shared; this is the\n // manifest catalog.\n { slug: 'connectors', name: 'Connectors' },\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[] = ['knowledge-nodes']\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// 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 RoleService, RoleServiceImpl } from './roles.js'\nimport { type ShareService, ShareServiceImpl } from './shares.js'\nimport { type TeamService, TeamServiceImpl } from './teams.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 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.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 { RoleService } from './roles.js'\nexport type { TeamService } from './teams.js'\nexport type { UserRoleAssignmentService } from './user-role-assignments.js'\n// Re-export types\nexport type {\n // Api key types\n ApiKey,\n AddTeamMemberRequest,\n AssignPermissionRequest,\n AssignRoleRequest,\n // Shared types\n AuthListOptions,\n CreateApiKeyRequest,\n CreatedApiKey,\n CreateOrganizationRequest,\n CreateRoleRequest,\n CreateTeamRequest,\n CreateUserRequest,\n ListOrganizationsOptions,\n ListRolePermissionsOptions,\n ListRolesOptions,\n ListTeamMembersOptions,\n ListTeamsOptions,\n ListOrgUserRoleAssignmentsOptions,\n ListUserRoleAssignmentsOptions,\n ListUsersOptions,\n // Organization types\n Organization,\n // Permission types\n Permission,\n // Role types\n Role,\n RoleEntityPermission,\n // Team types\n Team,\n TeamMember,\n UpdateMeRequest,\n UpdateOrganizationRequest,\n UpdateRoleRequest,\n UpdateTeamRequest,\n UpdateUserRequest,\n // User types\n User,\n // Share types\n SharePermission,\n ShareRequest,\n ShareRow,\n // User role assignment types\n UserRoleAssignment,\n} from './types.js'\n// Re-export Zod schemas\nexport {\n ApiKeySchema,\n OrganizationSchema,\n SharePermissionSchema,\n ShareRequestSchema,\n RoleEntityPermissionSchema,\n RoleSchema,\n TeamMemberSchema,\n TeamSchema,\n UserRoleAssignmentSchema,\n UserSchema,\n} from './types.js'\n// Re-export service interfaces\nexport type { UserService } from './users.js'\n// Share routing — exported so a UI can hide a share affordance it cannot serve.\nexport { isShareable, type ShareService, shareRouteFor } from './shares.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 * 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","import { type EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-source'\nimport { 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 * 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.options.fetch(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 // 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.options.fetch(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.options.fetch(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 type {\n Connector,\n ConnectorConnection,\n ConnectorMethod,\n ConnectionTokenResponse,\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('GET', `${CONNECTOR_BASE_PATH}/connectors/${encodeURIComponent(key)}`)\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('GET', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`)\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('PATCH', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`, request)\n }\n\n async delete(id: string): Promise<void> {\n await this.client.request('DELETE', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}`)\n }\n\n install(id: string): Promise<InstallConnectorConnectionResponse> {\n return this.client.request('POST', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/install`)\n }\n\n token(id: string): Promise<ConnectionTokenResponse> {\n return this.client.request('POST', `${CONNECTOR_BASE_PATH}/connections/${encodeURIComponent(id)}/token`)\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 )\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","import type { ProteosClient } from '../client.js'\nimport type {\n AcceptMistranscribedTermRequest,\n AgentListener,\n AttachContactAddressRequest,\n BlockContactRequest,\n Connection,\n Contact,\n ContactAddress,\n ContactErasureRequest,\n ContactGroup,\n ContactMergeProposal,\n Conversation,\n ConversationFilter,\n ConversationFilterEvent,\n ConversationType,\n CreateAgentListenerRequest,\n CreateConnectionRequest,\n CreateContactGroupRequest,\n CreateContactRequest,\n ContactRecordLink,\n CreateContactRecordLinkRequest,\n ListContactRecordLinksQuery,\n CreateConversationFilterRequest,\n CreateConversationTypeRequest,\n CreateGlossaryTermRequest,\n CreateToneProfileSetupRequest,\n CreateTranscriptionRequest,\n DeleteConnectionQuery,\n DispatchMeetingBotRequest,\n GlossaryTerm,\n InstallConnectionResponse,\n ListAgentListenersQuery,\n ListConnectionsQuery,\n ListContactAddressesQuery,\n ListContactGroupsQuery,\n ListContactMergeProposalsQuery,\n ListContactsQuery,\n ListConversationFilterEventsQuery,\n ListConversationFiltersQuery,\n ListConversationsQuery,\n ListConversationTypesQuery,\n ListGlossaryTermsQuery,\n ListMessagesQuery,\n ListMistranscribedTermsQuery,\n ListReactionsResponse,\n ListResponse,\n ListRoomsQuery,\n ListToneProfileSetupsQuery,\n ListToneProfilesQuery,\n ListTranscriptionsQuery,\n MaterializeTranscriptionRequest,\n MergeContactsRequest,\n Message,\n MistranscribedTerm,\n Reaction,\n RecordPermissionEventRequest,\n ResolveToneProfileQuery,\n Room,\n SendMessageRequest,\n SyncConnectionRequest,\n ToneProfile,\n ToneProfileSetup,\n Transcription,\n UnreadCounts,\n UpdateAgentListenerRequest,\n UpdateConnectionRequest,\n UpdateContactGroupRequest,\n UpdateContactRequest,\n UpdateConversationFilterRequest,\n UpdateConversationRequest,\n UpdateConversationTypeRequest,\n UpdateDraftRequest,\n UpdateGlossaryTermRequest,\n UpdateTranscriptionRequest,\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 /** 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 /** 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, remove from a meeting. */\n readonly meetings: MeetingService\n /** Realtime speech-to-text (dictation) — moved here from agent-service. */\n readonly voice: VoiceService\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.glossaryTerms = new GlossaryTermServiceImpl(client)\n this.conversationTypes = new ConversationTypeServiceImpl(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.voice = new VoiceServiceImpl(client)\n }\n}\n\n/** Meeting bots (Ava) — dispatch by meeting URL and removal. */\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 /** Make the bot leave the meeting and end the conversation (by conversation id). */\n remove(conversationId: string): 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 remove(conversationId: string): Promise<Conversation> {\n return this.client.request(\n 'DELETE',\n `${CONVERSATION_BASE_PATH}/meetings/${encodeURIComponent(conversationId)}`,\n )\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/** 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 /** Begin the connector's install flow; open the returned URL in a popup. */\n install(id: string): 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\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): Promise<InstallConnectionResponse> {\n return this.client.request(\n 'POST',\n `${CONVERSATION_BASE_PATH}/connections/${encodeURIComponent(id)}/install`,\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\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 /** Manually mint a contact (sync dedup — 409 contact_address_taken on any owned address). */\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 recordPermissionEvent(contactId: string, request: RecordPermissionEventRequest): Promise<Contact>\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(query: ListContactRecordLinksQuery = {}): 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 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 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 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(): 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 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(): Promise<UnreadCounts> {\n return this.client.request('GET', `${CONVERSATION_BASE_PATH}/conversations/unread-counts`)\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 * 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 /** 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 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 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 * 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\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\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 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 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\nexport type * 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","import type { ProteosClient } from '../client.js'\n\nconst QUERY_BASE_PATH = '/data/v1/query'\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 * Service for the raw-SQL query endpoint of the data-service.\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\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","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 ListRecordsOptions,\n RecordData,\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\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 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","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]`, `[starts_with]`,\n * `[ends_with]`, `[empty]`, `[not_empty]`. Missing operator defaults to `[eq]`.\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","import type { ProteosClient } from '../client.js'\nimport { type QueryService, QueryServiceImpl } from './queries.js'\nimport { type RecordService, RecordServiceImpl } 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\n constructor(client: ProteosClient) {\n this.records = new RecordServiceImpl(client)\n this.queries = new QueryServiceImpl(client)\n }\n}\n\n// Re-export service interfaces\n// Re-export types\nexport type {\n QueryExecuteMeta,\n QueryExecuteResponse,\n QueryRow,\n QueryService,\n QueryValidateMeta,\n QueryValidateResponse,\n} from './queries.js'\nexport type { RecordService } from './records.js'\nexport type {\n BatchTransactionError,\n BatchTransactionStatus,\n BatchUpsertRecordsResponse,\n BatchUpsertTransaction,\n BatchUpsertTransactionResult,\n ListRecordsOptions,\n RecordData,\n} from './types.js'\n\n// Re-export Zod schemas\nexport {\n BatchTransactionErrorSchema,\n BatchUpsertRecordsResponseSchema,\n BatchUpsertTransactionResultSchema,\n BatchUpsertTransactionSchema,\n} from './types.js'\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<{ data: PlatformEvent[] }, ListEventsOptions>(\n 'GET',\n `${EVENTS_BASE_PATH}/topics/${encodeURIComponent(topic)}/events`,\n options,\n )\n return response.data ?? []\n }\n\n async *tail(topic: string, options: TailOptions = {}): 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 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 )\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 },\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 )\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 )\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 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(id: string, content: string): 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(id: string, content: string): Promise<WriteContentResponse> {\n return this.client.request<WriteContentResponse>('PUT', `${NODES_BASE_PATH}/${id}/content`, {\n content,\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 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 /** 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 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 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 { 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'\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}\n\nexport interface WriteContentResponse {\n id: string\n lines_total: number\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\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// 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']),\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']),\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 SpaceService, SpaceServiceImpl } from './spaces.js'\nimport { type RecordLinkService, RecordLinkServiceImpl } from './record-links.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\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 }\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 { SpaceService } from './spaces.js'\nexport type { RecordLinkService } from './record-links.js'\n\n// Re-export types\nexport type {\n ContentMatch,\n ContentResponse,\n CreateLabelRequest,\n CreateLinkRequest,\n CreateNodeRequest,\n CreateRecordLinkRequest,\n CreateSpaceRequest,\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 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 UpdateLabelRequest,\n UpdateLinkRequest,\n UpdateNodeRequest,\n UpdateSpaceRequest,\n WriteContentResponse,\n} from './types.js'\n\n// Re-export the reserved space-filter sentinel (a value, not a type).\nexport { UNASSIGNED_SPACE_SLUG } from './types.js'\n\n// Re-export Zod schemas\nexport {\n KnowledgeLabelSchema,\n KnowledgeLinkSchema,\n KnowledgeNodeLabelSchema,\n KnowledgeNodeMetadataSchema,\n KnowledgeNodeSchema,\n KnowledgeNodeSearchResultSchema,\n KnowledgeRecordLinkSchema,\n NodeNeighborhoodSchema,\n} from './types.js'\n","import type { ProteosClient } from '../client.js'\nimport type { PublicAccessOperation } from '../meta/types.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): 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(\n 'metadata',\n new Blob([JSON.stringify(metadata)], { type: 'application/json' }),\n )\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 async download(id: string): Promise<Blob> {\n const { response } = await this.client.requestRaw('GET', `${FILES_BASE_PATH}/${id}/download`)\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 the `on_error: continue_error_output` policy\n * routes failed items to, when the node's descriptor declares it.\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 | '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\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 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\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 /** 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"]}
|