@getmodus/sdk 0.11.0 → 0.12.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/modus/modus/distribution/clients/typescript/modus-sdk/dist/index.cjs","../src/_agent_run_request.ts","../src/_streaming.ts","../src/_chat.ts","../src/types/workflows.ts","../src/types/conversations.ts","../src/_generated/resources/consumption/workflows.ts","../src/resources/workflows/runs.ts","../src/resources/workflows/workflow-actions.ts","../src/resources/workflows.ts","../src/_generated/resources/consumption/connections.ts","../src/resources/connections.ts","../src/_generated/resources/consumption/context/items.ts","../src/resources/context/items.ts","../src/resources/context/context.ts","../src/resources/ingested-data.ts","../src/_generated/resources/consumption/modus/conversations.ts","../src/resources/modus/conversations.ts","../src/resources/modus/modus.ts","../src/_generated/resources/consumption/scopes.ts","../src/resources/scopes.ts","../src/resources/suggestions.ts","../src/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACnCA,gCAA2B;AAGpB,SAAS,wBAAA,CAAyB,SAAA,EAAmC;AAC1E,EAAA,GAAA,CAAI,OAAO,UAAA,IAAc,SAAA,GAAY,SAAA,CAAU,IAAA,CAAK,CAAA,EAAG,OAAO,SAAA,CAAU,IAAA,CAAK,CAAA;AAC7E,EAAA,OAAO,gCAAA,CAAW;AACpB;ADmCA;AACA;AE/BA,SAAS,SAAA,CAAU,IAAA,EAAmD;AACpE,EAAA,GAAA,CAAI,CAAC,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA,EAAG,OAAO,KAAA,CAAA;AACtC,EAAA,MAAM,IAAA,EAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,CAAE,SA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AAM,MAAA;AAAe,MAAA;AACR,MAAA;AACjC,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQkF,EAAA;AAC7D,IAAA;AAC2B,IAAA;AAC3B,MAAA;AACP,MAAA;AACX,IAAA;AACH,EAAA;AACF;ArB8nDsD;AACA;AsBxkDX;AASsB,EAAA;AAChD,IAAA;AACoC,IAAA;AACF,IAAA;AACG,IAAA;AACJ,IAAA;AACE,IAAA;AACA,IAAA;AACE,IAAA;AACpD,EAAA;AACF;AtBkkDsD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/modus/modus/distribution/clients/typescript/modus-sdk/dist/index.cjs","sourcesContent":[null,"import { randomUUID } from 'node:crypto'\n\n/** Mint or reuse a non-empty sessionId for agent-host runs. */\nexport function resolveAgentRunSessionId(sessionId?: string | null): string {\n if (typeof sessionId === 'string' && sessionId.trim()) return sessionId.trim()\n return randomUUID()\n}\n","import type {\n ApprovalRequiredEvent,\n AssistantContentResetEvent,\n CancelledEvent,\n DoneEvent,\n ErrorEvent,\n RunEvent,\n StreamTimeoutEvent,\n TokenEvent,\n} from './types/runs.js'\n\nfunction parseLine(line: string): Record<string, unknown> | undefined {\n if (!line.startsWith('data:')) return undefined\n const raw = line.slice(5).trimStart()\n if (!raw || raw === '[DONE]') return undefined\n try {\n const data = JSON.parse(raw) as unknown\n if (data && typeof data === 'object' && !Array.isArray(data)) {\n return data as Record<string, unknown>\n }\n } catch {\n return undefined\n }\n return undefined\n}\n\nfunction isAsyncIterable<T>(value: Iterable<T> | AsyncIterable<T>): value is AsyncIterable<T> {\n return Symbol.asyncIterator in Object(value)\n}\n\nconst NODE_TERMINAL_TYPES = new Set<unknown>(['done', 'error', 'cancelled', 'stream_timeout'])\n\nfunction* parseData(data: Record<string, unknown>, id: string | undefined): Generator<RunEvent> {\n const eventType = typeof data.type === 'string' ? data.type : 'unknown'\n const withId = id === undefined ? {} : { id }\n\n if (eventType === 'node_content') {\n // A workflow wraps each node's frames; the inner frame is a normal run event.\n // A node's own terminal frame does not end the workflow: only workflow_* does.\n const inner = data.event\n if (inner && typeof inner === 'object' && !Array.isArray(inner)) {\n const frame = inner as Record<string, unknown>\n if (!NODE_TERMINAL_TYPES.has(frame.type)) yield* parseData(frame, id)\n }\n } else if (eventType === 'token') {\n const event: TokenEvent = {\n type: 'token',\n content: typeof data.content === 'string' ? data.content : '',\n ...(typeof data.subAgent === 'string' ? { subAgent: data.subAgent } : {}),\n ...withId,\n }\n yield event\n } else if (eventType === 'done' || eventType === 'workflow_done') {\n const content = eventType === 'done' ? data.content : data.finalOutput\n const event: DoneEvent = {\n type: 'done',\n runId: typeof data.runId === 'string' ? data.runId : '',\n threadId: typeof data.threadId === 'string' ? data.threadId : '',\n ...(typeof content === 'string' ? { content } : {}),\n ...withId,\n }\n yield event\n } else if (eventType === 'approval_required') {\n // Project to the declared fields, as the Python parser does: unknown or mistyped frame data never reaches callers.\n const event: ApprovalRequiredEvent = { type: 'approval_required' }\n for (const key of ['toolId', 'toolName', 'title', 'description', 'nodeId', 'prompt'] as const) {\n const value = data[key]\n if (typeof value === 'string') event[key] = value\n }\n const { args, options } = data\n if (args && typeof args === 'object' && !Array.isArray(args)) event.args = args as Record<string, unknown>\n if (Array.isArray(options)) event.options = options as ApprovalRequiredEvent['options']\n yield { ...event, ...withId }\n } else if (eventType === 'workflow_cancelled') {\n const event: CancelledEvent = { type: 'cancelled', ...withId }\n yield event\n } else if (eventType === 'error' || eventType === 'workflow_error') {\n const msg =\n data.error ?? data.message ?? data.content ?? 'Unknown run error'\n const event: ErrorEvent = {\n type: 'error',\n message: String(msg),\n ...(typeof data.requestId === 'string' ? { requestId: data.requestId } : {}),\n ...withId,\n }\n yield event\n } else if (eventType === 'cancelled') {\n const event: CancelledEvent = { type: 'cancelled', ...withId }\n yield event\n } else if (eventType === 'stream_timeout') {\n const event: StreamTimeoutEvent = { type: 'stream_timeout', ...withId }\n yield event\n } else if (eventType === 'assistant_content_reset') {\n if (typeof data.content !== 'string') return\n const event: AssistantContentResetEvent = {\n type: 'assistant_content_reset',\n content: data.content,\n ...(typeof data.visibleContent === 'string'\n ? { visibleContent: data.visibleContent }\n : {}),\n attempt: typeof data.attempt === 'number' ? data.attempt : 1,\n reason: 'provider_stream_failed',\n ...(data.subAgent && typeof data.subAgent === 'object' && !Array.isArray(data.subAgent)\n ? { subAgent: data.subAgent as Record<string, unknown> }\n : {}),\n ...withId,\n }\n yield event\n }\n // Keepalives, tool and progress events, and unknown future types yield nothing.\n}\n\n/**\n * Line-at-a-time SSE parser. An `id:` line names every event after it until the next\n * `id:` line, so one parser must see every line of a stream.\n */\nfunction sseLineParser(): (line: string) => Generator<RunEvent> {\n let lastId: string | undefined\n return function* (line: string) {\n if (line.startsWith('id:')) {\n lastId = line.slice(3).trim() || undefined\n return\n }\n const data = parseLine(line)\n if (data !== undefined) yield* parseData(data, lastId)\n }\n}\n\nfunction* parseSyncSseLines(lines: Iterable<string>): Generator<RunEvent> {\n const parse = sseLineParser()\n for (const line of lines) yield* parse(line)\n}\n\nasync function* parseAsyncSseLines(lines: AsyncIterable<string>): AsyncGenerator<RunEvent> {\n const parse = sseLineParser()\n for await (const line of lines) yield* parse(line)\n}\n\n/** Convert raw SSE lines into typed run events (forward-compatible), each with its SSE `id`. */\nexport function parseSseStream(lines: Iterable<string>): Generator<RunEvent>\nexport function parseSseStream(lines: AsyncIterable<string>): AsyncGenerator<RunEvent>\nexport function parseSseStream(\n lines: Iterable<string> | AsyncIterable<string>,\n): Generator<RunEvent> | AsyncGenerator<RunEvent> {\n return isAsyncIterable(lines) ? parseAsyncSseLines(lines) : parseSyncSseLines(lines)\n}\n","import {\n ModusError,\n RunCancelledError,\n StreamTimeoutError,\n} from './_exceptions.js'\nimport { requireAgentHost, type ModusConfig } from './_config.js'\nimport { resolveAgentRunSessionId } from './_agent_run_request.js'\nimport type { HttpClient } from './_http.js'\nimport { parseSseStream } from './_streaming.js'\nimport { validateChatModel, validateId } from './_validation.js'\nimport type { ChatModel, ChatResult } from './types/chat.js'\nimport type { ApprovalRequiredEvent, RunEvent } from './types/runs.js'\n\n/** What a chat talks to: a scope, a workflow, or Modus itself. */\nexport type ChatTarget =\n | { readonly kind: 'scopes' | 'workflows'; readonly id: number | string }\n | { readonly kind: 'modus' }\n\n/** Options shared by every `chat()` method. */\nexport interface ChatOptions {\n /** Canonical model id for this run (required). See {@link ChatModel}. */\n model: ChatModel\n /** Continue this conversation; omit to start a new one. */\n threadId?: string\n}\n\ninterface ChatRequest {\n readonly path: string\n readonly body: Record<string, unknown>\n readonly sessionId: string\n readonly baseUrl: string\n}\n\nfunction effectiveThreadId(threadId?: string): string | undefined {\n if (threadId === undefined || !threadId.trim()) return undefined\n return threadId\n}\n\nfunction runsPath(target: ChatTarget): string {\n if (target.kind === 'modus') return '/agent/v1/modus/runs'\n return `/agent/v1/${target.kind}/${encodeURIComponent(String(target.id))}/runs`\n}\n\nfunction raiseForEvent(event: RunEvent): RunEvent {\n if (event.type === 'error') throw new ModusError(event.message, { requestId: event.requestId })\n if (event.type === 'cancelled') throw new RunCancelledError()\n if (event.type === 'stream_timeout') throw new StreamTimeoutError()\n return event\n}\n\n/**\n * One chat turn, streamed live from the agent host.\n *\n * Iterate {@link ChatSession.textStream} for tokens as they arrive, or\n * `await` the session for the final {@link ChatResult}. The request is sent\n * once: iterating again, or awaiting after iterating, replays what arrived.\n *\n * @example\n * ```ts\n * const chat = client.scopes.chat(scopeId, 'What is our ARR trend?', { model: 'claude-sonnet-5.5' })\n * for await (const token of chat.textStream()) process.stdout.write(token)\n * const { threadId } = await chat\n * ```\n */\nexport class ChatSession implements PromiseLike<ChatResult> {\n private readonly received: RunEvent[] = []\n private live: AsyncGenerator<RunEvent> | undefined\n private finished = false\n private failure: unknown\n private final: ChatResult | undefined\n private approval: ApprovalRequiredEvent | undefined\n\n /**\n * @internal A session built with `failure` never sends; every read rejects\n * with it, as the promise `chat()` used to return did.\n */\n constructor(\n private readonly http: HttpClient,\n private readonly request: ChatRequest | undefined,\n failure?: unknown,\n ) {\n if (failure !== undefined) {\n this.failure = failure\n this.finished = true\n }\n }\n\n /**\n * The assistant's reply as text chunks, as they arrive. Sub-agent output is\n * left out.\n *\n * @throws {ModusError} When the run reports an error.\n * @throws {RunCancelledError} When the run is cancelled.\n * @throws {StreamTimeoutError} When the run times out.\n */\n async *textStream(): AsyncGenerator<string> {\n // A replay of a protocol-2 stream can hold resets; text before the last one was replaced.\n // ponytail: a reset arriving live after text was yielded cannot be taken back.\n const lastReset = this.received.findLastIndex(\n (event) => event.type === 'assistant_content_reset' && event.subAgent === undefined,\n )\n let index = 0\n for await (const event of this.replay(false)) {\n const at = index++\n if (at < lastReset) continue\n if (at === lastReset && event.type === 'assistant_content_reset') {\n if (event.content) yield event.content\n } else if (event.type === 'token' && event.subAgent === undefined) {\n yield event.content\n }\n }\n }\n\n /**\n * Every run event (tokens, approvals, `done`, …) as it arrives.\n *\n * @throws {ModusError} When the run reports an error.\n * @throws {RunCancelledError} When the run is cancelled.\n * @throws {StreamTimeoutError} When the run times out.\n */\n eventStream(): AsyncGenerator<RunEvent> {\n return this.replay(true)\n }\n\n /**\n * Waits for the run to finish and returns its final answer. `approval` is\n * set when the run stopped for a decision; continue with {@link resume}.\n *\n * @throws {ModusError} When the run reports an error or ends without finishing.\n */\n async result(): Promise<ChatResult> {\n for await (const _event of this.replay(true)) {\n // drain\n }\n if (this.final === undefined) throw new ModusError('Chat stream ended without a done event')\n return this.final\n }\n\n /** Resolve with the final {@link ChatResult}, so the session can be awaited. */\n then<TResult1 = ChatResult, TResult2 = never>(\n onfulfilled?: ((value: ChatResult) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.result().then(onfulfilled, onrejected)\n }\n\n /** Handle a failed run, as on the promise `chat()` used to return. */\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n ): Promise<ChatResult | TResult> {\n return this.result().catch(onrejected)\n }\n\n /** Run `onfinally` once the run settles, as on the promise `chat()` used to return. */\n finally(onfinally?: (() => void) | null): Promise<ChatResult> {\n return this.result().finally(onfinally)\n }\n\n /**\n * Approve or deny the action this run stopped for, continuing the same\n * conversation.\n *\n * @param input.decision - `approve` or `deny`.\n * @returns A new session for the continued run.\n * @throws {ModusError} When called before the run has finished.\n *\n * @example\n * ```ts\n * const chat = client.modus.chat('Fix the typo in accounts', { model: 'claude-sonnet-5.5' })\n * const first = await chat\n * if (first.approval) {\n * const done = await chat.resume({ decision: 'approve' })\n * }\n * ```\n */\n resume(input: { decision: 'approve' | 'deny' }): ChatSession {\n if (this.final === undefined) {\n throw new ModusError('resume() needs a finished run: await the chat first')\n }\n const { runId, threadId } = this.final\n validateId(runId, 'run_id')\n return new ChatSession(this.http, {\n path: `/agent/v1/runs/${encodeURIComponent(runId)}/resume`,\n body: { sessionId: threadId, decision: input.decision },\n sessionId: threadId,\n baseUrl: this.request!.baseUrl,\n })\n }\n\n /**\n * Stop reading the run and release its connection. Call it when you stop\n * iterating before the run ends; a session that reached `done` has already\n * let go. The run itself keeps going on the server.\n */\n async close(): Promise<void> {\n this.finished = true\n await this.live?.return(undefined)\n }\n\n // ponytail: one consumer at a time; concurrent iterators would race on `live`.\n private async *replay(resetAware: boolean): AsyncGenerator<RunEvent> {\n let index = 0\n while (true) {\n if (index < this.received.length) {\n yield this.received[index++]!\n continue\n }\n if (this.failure !== undefined) throw this.failure\n if (this.finished) return\n this.live ??= this.open(resetAware)\n try {\n const next = await this.live.next()\n if (next.done) {\n this.finished = true\n } else {\n this.received.push(next.value)\n // done is the last event: release the connection now, even if the consumer stops here.\n if (next.value.type === 'done') await this.close()\n }\n } catch (error) {\n this.failure = error\n throw error\n }\n }\n }\n\n private async *open(resetAware: boolean): AsyncGenerator<RunEvent> {\n const request = this.request!\n const body = resetAware ? { ...request.body, streamProtocolVersion: 2 } : request.body\n const lines = this.http.streamPost(request.path, body, { baseUrl: request.baseUrl })\n for await (const event of parseSseStream(lines)) {\n raiseForEvent(event)\n if (event.type === 'approval_required') this.approval = event\n if (event.type === 'done') {\n // Recorded before yielding: a consumer may stop at done and resume().\n this.final = {\n content: event.content ?? '',\n threadId: event.threadId || this.request!.sessionId,\n runId: event.runId,\n ...(this.approval !== undefined ? { approval: this.approval } : {}),\n }\n yield event\n return\n }\n yield event\n }\n }\n}\n\nexport function startChat(\n http: HttpClient,\n config: ModusConfig,\n target: ChatTarget,\n message: string,\n options: ChatOptions,\n): ChatSession {\n try {\n return new ChatSession(http, chatRequest(config, target, message, options))\n } catch (error) {\n return new ChatSession(http, undefined, error)\n }\n}\n\nfunction chatRequest(\n config: ModusConfig,\n target: ChatTarget,\n message: string,\n options: ChatOptions,\n): ChatRequest {\n if (target.kind !== 'modus') validateId(target.id, `${target.kind.slice(0, -1)}_id`)\n validateChatModel(options.model)\n const baseUrl = requireAgentHost(config)\n const sessionId = resolveAgentRunSessionId(effectiveThreadId(options.threadId))\n return {\n path: runsPath(target),\n body: {\n message,\n config: { model: options.model },\n sessionId,\n ...(config.organizationId !== undefined ? { organizationId: config.organizationId } : {}),\n },\n sessionId,\n baseUrl,\n }\n}\n","import type { components } from '../_generated/v1.js'\n\n/** Canonical public type for a Modus workflow (OpenAPI `WorkflowDto`). */\nexport type Workflow = components['schemas']['WorkflowDto']\n\n/** Runtime + type for workflow kinds (use `WorkflowType.task`, not only as a type). */\nexport const WorkflowType = {\n task: 'task',\n workflow: 'workflow',\n} as const\n\nexport type WorkflowType = (typeof WorkflowType)[keyof typeof WorkflowType]\n\n/** @deprecated Use `Workflow` instead. */\nexport type Agent = Workflow\n/** @deprecated Use `WorkflowType` instead. */\nexport type AgentType = WorkflowType\n/** @deprecated Use `WorkflowType` instead. */\nexport const AgentType = WorkflowType\n","import type { components } from '../_generated/v1.js'\n\nexport type Conversation = components['schemas']['ConversationDto']\nexport type ConversationListItem = components['schemas']['ConversationListItemDto']\nexport type Message = components['schemas']['ConversationMessageDto']\nexport type ConversationKind = 'all' | 'modus' | 'scopes'\n\n/** Scope id for a list item, or undefined for direct Modus chats (scopeId 0). */\nexport function conversationScopeId(item: ConversationListItem): number | undefined {\n return item.scopeId === 0 ? undefined : item.scopeId\n}\n\n/**\n * @deprecated Use `conversationScopeId` instead.\n * Preserves the legacy `0` sentinel for direct Modus chats (unlike\n * `conversationScopeId`, which returns `undefined` for id `0`).\n */\nexport function conversationSkillId(item: ConversationListItem): number | undefined {\n return item.scopeId\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../_config.js'\nimport type { HttpClient } from '../../../_http.js'\nimport { aipListParams, buildAipPage, type Page } from '../../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../../_request.js'\nimport { validatePageSize } from '../../../_validation.js'\nimport type { VariationView } from '../../../types/views.js'\nimport type { Workflow, WorkflowType } from '../../../types/workflows.js'\n\n/** Generated base for the consumption `workflows` resource. */\nexport class WorkflowsResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * List workflows.\n *\n * Returns a paginated page of workflows the caller can at least `use`. Workflows the caller\n * cannot see are filtered out. Pagination uses an opaque token returned in `nextPageToken`.\n *\n * **Requires:** `workflows:read`\n *\n * @param options.pageSize - Items per page. Defaults to 25.\n * @param options.pageToken - Opaque page token from a previous response's `nextPageToken`. Omit\n * for the first page.\n * @param options.search - Case-insensitive substring filter on workflow name.\n * @param options.type - Filter by workflow type.\n * @param options.view - Variation view. `active` reads the deployed version. `draft` reads the\n * latest builder snapshot. `published` reads only a published workflow of type workflow that\n * you can use; tasks are excluded.\n * @param options.includeVariation - Include the requested variation payload (`trigger`,\n * `workflowStructure`, `agentSelection`) on list rows.\n * @returns A page of workflows.\n *\n * @example\n * ```ts\n * for await (const wf of (await client.workflows.list({ search: 'digest' })).autoPagingIter()) {\n * console.log(wf.id, wf.name, wf.status)\n * }\n * ```\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n search?: string\n type?: WorkflowType\n view?: VariationView\n includeVariation?: boolean\n } = {}): Promise<Page<Workflow>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, options.search, options.type, options.view, options.includeVariation)\n }\n\n protected async listPage(\n pageSize: number,\n pageToken: string | undefined,\n search?: string,\n type?: WorkflowType,\n view?: VariationView,\n includeVariation?: boolean,\n ): Promise<Page<Workflow>> {\n const extra: Record<string, string | boolean> = {}\n if (search !== undefined) extra.search = search\n if (type !== undefined) extra.type = type\n if (view !== undefined) extra.view = view\n if (includeVariation !== undefined) extra.includeVariation = includeVariation\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'WorkflowsController_list', {\n query: aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | undefined | null\n >,\n }),\n )\n return buildAipPage(\n data,\n 'workflows',\n (raw) => raw as Workflow,\n (token) => this.listPage(pageSize, token, search, type, view, includeVariation),\n )\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { ModusConfig } from '../../_config.js'\nimport { resolveAgentRunSessionId } from '../../_agent_run_request.js'\nimport { ModusError, ValidationError } from '../../_exceptions.js'\nimport type { OperationId } from '../../_generated/operations.js'\nimport {\n formatOperationPath,\n getOperation,\n operationBaseUrl,\n} from '../../_openapi-invoke.js'\nimport type { HttpClient } from '../../_http.js'\nimport { Page, normalizePageToken } from '../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../_request.js'\nimport { parseSseStream } from '../../_streaming.js'\nimport { validateId, validatePageSize } from '../../_validation.js'\nimport type {\n AgentRun,\n AgentRunListItem,\n AgentRunCreateRequest,\n ApprovalScope,\n CreateAgentRunRequest,\n FollowUpRunRequest,\n ModusRunCreateRequest,\n ResumeRunRequest,\n RunAdmission,\n RunEventsPollResponse,\n RunStatus,\n RunTimeframe,\n SkillRunCreateRequest,\n} from '../../types/agent-runs.js'\nimport type { ActiveConversationRun, RunEvent } from '../../types/runs.js'\n\nconst RUNS_MAX_PAGE_SIZE = 100\n\nfunction runsListParams(\n pageSize: number,\n pageToken: string | undefined,\n status?: RunStatus,\n timeframe?: RunTimeframe,\n approvalScope?: ApprovalScope,\n search?: string,\n): Record<string, string | number | boolean | undefined | null> {\n const params: Record<string, string | number | boolean | undefined | null> = { pageSize }\n const token = normalizePageToken(pageToken)\n if (token !== undefined) params.pageToken = token\n if (status !== undefined) params.status = status\n if (timeframe !== undefined) params.timeframe = timeframe\n if (approvalScope !== undefined) params.approvalScope = approvalScope\n if (search !== undefined) params.search = search\n return params\n}\n\nfunction activeRunsParams(\n pageSize: number,\n pageToken: string | undefined,\n): Record<string, string | number> {\n const params: Record<string, string | number> = { pageSize }\n const token = normalizePageToken(pageToken)\n if (token !== undefined) params.pageToken = token\n return params\n}\n\nfunction parseRun(raw: unknown): AgentRun {\n return raw as AgentRun\n}\n\nfunction parseActiveRunsArray(raw: unknown): ActiveConversationRun[] {\n const data = asRecord(raw)\n const runs = data.runs\n if (!Array.isArray(runs)) {\n throw new ModusError(\n `Unexpected active runs response shape: runs must be a list, got ${typeof runs}.`,\n )\n }\n return runs as ActiveConversationRun[]\n}\n\nfunction parseActiveRunsPage(\n raw: unknown,\n fetchPage: (token: string) => Promise<Page<ActiveConversationRun>>,\n): Page<ActiveConversationRun> {\n const data = asRecord(raw)\n const runs = data.runs\n if (!Array.isArray(runs)) {\n throw new ModusError(\n `Unexpected active runs response shape: runs must be a list, got ${typeof runs}.`,\n )\n }\n return new Page(\n runs as ActiveConversationRun[],\n normalizePageToken(\n typeof data.nextPageToken === 'string' ? data.nextPageToken : undefined,\n ),\n fetchPage,\n )\n}\n\nfunction randomRunId(): string {\n return randomUUID()\n}\n\nfunction sessionIdFromBody(body: { sessionId?: string }): string {\n return resolveAgentRunSessionId(body.sessionId)\n}\n\n/** Interrupt, queue-edit and resume continue an existing conversation, so a sessionId is never minted. */\nfunction requireSessionId(sessionId: string | undefined): void {\n if (!sessionId?.trim()) {\n throw new ValidationError(\"sessionId must be the run's conversation id (a non-empty string)\")\n }\n}\n\nexport interface AgentRunStream extends AsyncIterable<RunEvent> {\n readonly runId: string\n readonly events: AsyncIterable<RunEvent>\n}\n\nexport function makeAgentRunStream(runId: string, events: AsyncIterable<RunEvent>): AgentRunStream {\n return {\n runId,\n events,\n [Symbol.asyncIterator]() {\n return events[Symbol.asyncIterator]()\n },\n }\n}\n\n/**\n * Start, inspect, and control workflow runs.\n *\n * Typical path: `create` (or `createScope` / `createModus`) → stream events →\n * `list` / `get` history → `cancel` or `resume` when needed.\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.create(workflowId, {\n * message: \"Summarize yesterday's sales\",\n * config: { model: 'claude-sonnet-5' },\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\nexport class WorkflowRunsResource {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {}\n\n /**\n * List runs for a workflow.\n *\n * @param workflowId - Numeric workflow id.\n * @param options.pageSize - Maximum items per page (default 25, max 100).\n * @param options.pageToken - Opaque token from a previous page.\n * @param options.status - Filter by run status.\n * @param options.timeframe - Filter by recency (`last_hour`, `last_day`, or `last_week`).\n * @param options.approvalScope - Filter approval-related runs (`mine` or `all`).\n * @param options.search - Free-text search filter.\n * @returns A page of run summaries — use `.autoPagingIter()` for all pages.\n *\n * @example\n * ```ts\n * for await (const run of (\n * await client.workflows.runs.list(workflowId, { status: 'completed' })\n * ).autoPagingIter()) {\n * console.log(run.workflowId, run.status, run.startedAt)\n * }\n * ```\n */\n list(\n workflowId: number | string,\n options: {\n pageSize?: number\n pageToken?: string\n status?: RunStatus\n timeframe?: RunTimeframe\n approvalScope?: ApprovalScope\n search?: string\n } = {},\n ): Promise<Page<AgentRunListItem>> {\n validateId(workflowId, 'workflow_id')\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize, RUNS_MAX_PAGE_SIZE)\n return this.listPage(workflowId, pageSize, options.pageToken, options)\n }\n\n private async listPage(\n workflowId: number | string,\n pageSize: number,\n pageToken: string | undefined,\n filters: {\n status?: RunStatus\n timeframe?: RunTimeframe\n approvalScope?: ApprovalScope\n search?: string\n },\n ): Promise<Page<AgentRunListItem>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'WorkflowRunsController_list', {\n pathParams: { id: workflowId },\n query: runsListParams(\n pageSize,\n pageToken,\n filters.status,\n filters.timeframe,\n filters.approvalScope,\n filters.search,\n ),\n }),\n )\n const runs = data.runs\n if (!Array.isArray(runs)) {\n throw new ModusError(\n `Unexpected list response shape: runs must be a list, got ${typeof runs}.`,\n )\n }\n return new Page(\n runs as AgentRunListItem[],\n normalizePageToken(\n typeof data.nextPageToken === 'string' ? data.nextPageToken : undefined,\n ),\n (token: string) => this.listPage(workflowId, pageSize, token, filters),\n )\n }\n\n /**\n * Retrieve a workflow run by id.\n *\n * @param workflowId - Numeric workflow id the run belongs to.\n * @param runId - Run id (the list row's `workflowId` field, not the composite `id`).\n * @param options.temporalRunId - Optional internal execution id when disambiguating retries.\n * @returns Run details including status and output.\n * @throws {NotFoundError} When the run does not exist.\n *\n * @example\n * ```ts\n * const run = await client.workflows.runs.get(workflowId, runId)\n * console.log(run.status)\n * ```\n */\n async get(\n workflowId: number | string,\n runId: string,\n options: { temporalRunId?: string } = {},\n ): Promise<AgentRun> {\n validateId(workflowId, 'workflow_id')\n if (!runId.trim()) throw new ValidationError('run_id must be a non-empty string')\n const query =\n options.temporalRunId !== undefined\n ? { temporalRunId: options.temporalRunId }\n : undefined\n const data = await invokeWithRetry(this.config, this.http, 'WorkflowRunsController_get', {\n pathParams: { id: workflowId, runId },\n query,\n })\n return parseRun(data)\n }\n\n /**\n * Start a workflow run and stream run events.\n *\n * @param workflowId - Numeric workflow id to run.\n * @param body - Run body (`message`, optional `sessionId`, optional `version` as `published` or `draft`).\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events (tokens, completion, errors, and related signals).\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.create(workflowId, {\n * message: \"Summarize yesterday's sales\",\n * config: { model: 'claude-sonnet-5' },\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * if (event.type === 'done') break\n * }\n * ```\n */\n create(\n workflowId: number | string,\n body: CreateAgentRunRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n validateId(workflowId, 'workflow_id')\n return this.createRun('WorkflowRunsController_create', body, { id: workflowId }, options)\n }\n\n /**\n * Start a scope run and stream run events.\n *\n * Same event stream shape as {@link create}, but targets a published scope.\n *\n * @param scopeId - Scope id to run.\n * @param body - Run body (`message`, optional `sessionId`, optional `version` as `published` or `draft`).\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events.\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.createScope(scopeId, {\n * message: 'What is our ARR trend?',\n * config: { model: 'claude-sonnet-5' },\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\n createScope(\n scopeId: number | string,\n body: SkillRunCreateRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n validateId(scopeId, 'scope_id')\n return this.createRun('ScopeRunsController_create', body, { id: scopeId }, options)\n }\n\n /**\n * Start a Modus org-assistant run and stream run events.\n *\n * @param body - Run body (`message`, optional `sessionId`, optional `subordinateSkillIds` to narrow context).\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events.\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.createModus({\n * message: 'Summarize ARR in three bullets.',\n * config: { model: 'claude-sonnet-5' },\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\n createModus(\n body: ModusRunCreateRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n return this.createRun('ModusRunsController_create', body, {}, options)\n }\n\n /**\n * Resume a run paused at an approval or connect interrupt, and stream the continuation's events.\n *\n * The decision is the whole turn: send no `message` (a non-empty one is rejected).\n *\n * @param runId - Id of the interrupted run.\n * @param body - `sessionId` (the run's conversation id, required) and `decision`\n * (`approve` / `deny` / `connected` / `cancelled`); optional `approvalTarget`.\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events.\n * @throws {ValidationError} When `sessionId` is blank, before any request is sent.\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.resume(runId, {\n * decision: 'approve',\n * sessionId,\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\n resume(\n runId: string,\n body: ResumeRunRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n validateId(runId, 'run_id')\n requireSessionId(body.sessionId)\n return this.createRun('ResumeRunsController_create', body, { runId }, options)\n }\n\n /**\n * Cancel a run that is still in progress.\n *\n * @param runId - Run id to cancel.\n *\n * @example\n * ```ts\n * await client.workflows.runs.cancel(runId)\n * ```\n */\n async cancel(runId: string): Promise<void> {\n validateId(runId, 'run_id')\n await invokeWithRetry(this.config, this.http, 'RunLifecycleController_cancel', {\n pathParams: { runId },\n jsonBody: {},\n })\n }\n\n /**\n * Poll a run's buffered events once (the JSON transport, not SSE).\n *\n * @param runId - Run id.\n * @returns The poll response: `events` (each with its stream `id` and `type`), `cursor`,\n * `status` and `done`.\n */\n async events(runId: string): Promise<RunEventsPollResponse> {\n validateId(runId, 'run_id')\n return (await invokeWithRetry(this.config, this.http, 'RunLifecycleController_events', {\n pathParams: { runId },\n })) as RunEventsPollResponse\n }\n\n /**\n * Supersede a run's current turn with a follow-up turn.\n *\n * The run is cancelled and `nextRun` starts as a new run on the same conversation.\n * On a run that has already finished nothing is cancelled, and `nextRun` simply\n * starts a follow-up turn. `nextRun.runId` is pinned (a new uuid when you do not\n * set one), so a retried request returns the same run instead of starting another.\n *\n * @param runId - Run id to interrupt.\n * @param nextRun - The follow-up turn: `message` and `sessionId` (the run's conversation id).\n * @param options.lastSeenEventId - Id of the last event you rendered, so the cancelled\n * turn's saved output stops there.\n * @returns The new run (`runId`, `status`); follow it with {@link stream}.\n * @throws {ValidationError} When `nextRun.sessionId` is blank, before any request is sent.\n *\n * @example\n * ```ts\n * const { runId: nextRunId } = await client.workflows.runs.interrupt(runId, {\n * message: 'Only count EMEA.',\n * sessionId,\n * })\n * for await (const event of client.workflows.runs.stream(nextRunId)) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\n async interrupt(\n runId: string,\n nextRun: FollowUpRunRequest,\n options: { lastSeenEventId?: string } = {},\n ): Promise<RunAdmission> {\n validateId(runId, 'run_id')\n requireSessionId(nextRun.sessionId)\n const jsonBody = {\n nextRun: { ...nextRun, runId: nextRun.runId?.trim() || randomRunId() },\n ...(options.lastSeenEventId ? { lastSeenEventId: options.lastSeenEventId } : {}),\n }\n return (await invokeWithRetry(this.config, this.http, 'RunLifecycleController_interrupt', {\n pathParams: { runId },\n jsonBody,\n })) as RunAdmission\n }\n\n /**\n * Replace the turn of a run that is still queued (not yet started).\n *\n * @param runId - Queued run id.\n * @param nextRun - The replacement turn: `message` and `sessionId` (the run's conversation id).\n * @returns The edited run (`runId`, `status`).\n * @throws {ValidationError} When `nextRun.sessionId` is blank, before any request is sent.\n * @throws {ConflictError} When the run has already started.\n *\n * @example\n * ```ts\n * await client.workflows.runs.editQueued(queuedRunId, {\n * message: 'Summarize last week instead.',\n * sessionId,\n * })\n * ```\n */\n async editQueued(runId: string, nextRun: FollowUpRunRequest): Promise<RunAdmission> {\n validateId(runId, 'run_id')\n requireSessionId(nextRun.sessionId)\n return (await invokeWithRetry(this.config, this.http, 'RunLifecycleController_editQueued', {\n pathParams: { runId },\n jsonBody: { nextRun },\n })) as RunAdmission\n }\n\n /**\n * List active conversation runs across the organization.\n *\n * @param options.pageSize - Maximum items per page (default 50, max 100).\n * @param options.pageToken - Opaque token from a previous page.\n * @returns A page of active runs with session and status metadata.\n */\n active(options: {\n pageSize?: number\n pageToken?: string\n } = {}): Promise<Page<ActiveConversationRun>> {\n const pageSize = options.pageSize ?? 50\n validatePageSize(pageSize, RUNS_MAX_PAGE_SIZE)\n return this.activePage(pageSize, options.pageToken)\n }\n\n private async activePage(\n pageSize: number,\n pageToken: string | undefined,\n ): Promise<Page<ActiveConversationRun>> {\n return parseActiveRunsPage(\n await invokeWithRetry(this.config, this.http, 'RunLifecycleController_active', {\n query: activeRunsParams(pageSize, pageToken),\n }),\n (token: string) => this.activePage(pageSize, token),\n )\n }\n\n /**\n * Look up active runs for specific conversation sessions.\n *\n * @param sessionIds - Up to 100 session ids.\n * @returns Active runs matching any of the given sessions.\n * @throws {ValidationError} When more than 100 session ids are provided.\n */\n async activeBySession(sessionIds: readonly string[]): Promise<ActiveConversationRun[]> {\n const uniqueSessionIds = [...new Set(sessionIds.map((id) => id.trim()).filter(Boolean))]\n if (uniqueSessionIds.length > 100) {\n throw new ValidationError('sessionIds must contain at most 100 ids')\n }\n return parseActiveRunsArray(\n await invokeWithRetry(this.config, this.http, 'RunLifecycleController_activeBySession', {\n jsonBody: { sessionIds: uniqueSessionIds },\n }),\n )\n }\n\n /**\n * Reconnect to a run and stream its events.\n *\n * @param runId - Run id to follow.\n * @param options.lastEventId - The `id` of the last event you handled; the stream resumes\n * after it. Omit to replay the run from its first event.\n * @returns A stream of run events.\n *\n * @example\n * ```ts\n * let lastEventId: string | undefined\n * for await (const event of client.workflows.runs.stream(runId, { lastEventId })) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * lastEventId = event.id // after handling it: reconnect with it if the connection drops\n * }\n * ```\n */\n stream(runId: string, options: { lastEventId?: string } = {}): AgentRunStream {\n validateId(runId, 'run_id')\n const op = getOperation('RunLifecycleController_stream')\n const path = formatOperationPath('RunLifecycleController_stream', { runId })\n const lines = this.http.streamGet(path, undefined, {\n baseUrl: operationBaseUrl(this.http, op),\n headers: options.lastEventId ? { 'Last-Event-ID': options.lastEventId } : undefined,\n })\n return makeAgentRunStream(runId, this.parseEvents(lines))\n }\n\n private createRun(\n operationId: OperationId,\n body: AgentRunCreateRequest | SkillRunCreateRequest | ModusRunCreateRequest | ResumeRunRequest,\n pathParams: Record<string, unknown>,\n options: { idempotencyKey?: string },\n ): AgentRunStream {\n const runId = options.idempotencyKey?.trim() || body.runId?.trim() || randomRunId()\n const sessionId = sessionIdFromBody(body as { sessionId?: string })\n const op = getOperation(operationId)\n const path = formatOperationPath(operationId, pathParams)\n const lines = this.http.streamPost(path, {\n ...body,\n sessionId,\n streamProtocolVersion: 2,\n }, {\n baseUrl: operationBaseUrl(this.http, op),\n headers: { 'Idempotency-Key': runId },\n })\n return makeAgentRunStream(runId, this.parseEvents(lines))\n }\n\n private async *parseEvents(lines: AsyncIterable<string>): AsyncGenerator<RunEvent> {\n yield* parseSseStream(lines)\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { ModusConfig } from '../../_config.js'\nimport {\n formatOperationPath,\n getOperation,\n operationBaseUrl,\n} from '../../_openapi-invoke.js'\nimport type { HttpClient } from '../../_http.js'\nimport { invokeWithRetry } from '../../_request.js'\nimport { parseSseStream } from '../../_streaming.js'\nimport { validateId } from '../../_validation.js'\nimport type { WorkflowActionRequest } from '../../types/agent-runs.js'\nimport type { RunEvent } from '../../types/runs.js'\nimport { makeAgentRunStream, type AgentRunStream } from './runs.js'\n\nfunction randomRunId(): string {\n return randomUUID()\n}\n\nexport class AgentWorkflowActionsResource {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {}\n\n /**\n * Execute a workflow action and stream run events.\n *\n * @param body - Action body (`organizationId`, `sessionId`, `workflowAction`, optional `previousOutputs`).\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events for the action execution.\n */\n execute(\n body: WorkflowActionRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n const runId = options.idempotencyKey?.trim() || body.runId?.trim() || randomRunId()\n const op = getOperation('WorkflowActionsController_execute')\n const path = formatOperationPath('WorkflowActionsController_execute')\n const lines = this.http.streamPost(path, body, {\n baseUrl: operationBaseUrl(this.http, op),\n headers: { 'Idempotency-Key': runId },\n })\n return makeAgentRunStream(runId, this.parseEvents(lines))\n }\n\n /**\n * Cancel a workflow action run.\n *\n * @param runId - Action run id to cancel.\n */\n async cancel(runId: string): Promise<void> {\n validateId(runId, 'run_id')\n await invokeWithRetry(this.config, this.http, 'WorkflowActionsController_cancel', {\n pathParams: { runId },\n jsonBody: {},\n })\n }\n\n private async *parseEvents(lines: AsyncIterable<string>): AsyncGenerator<RunEvent> {\n yield* parseSseStream(lines)\n }\n}\n","import { WorkflowsResourceBase } from '../_generated/resources/consumption/workflows.js'\nimport type { ModusConfig } from '../_config.js'\nimport type { HttpClient } from '../_http.js'\nimport { startChat, type ChatOptions, type ChatSession } from '../_chat.js'\nimport { invokeWithRetry } from '../_request.js'\nimport { validateId } from '../_validation.js'\nimport type { Workflow } from '../types/workflows.js'\nimport type { VariationView } from '../types/views.js'\nimport { WorkflowRunsResource } from './workflows/runs.js'\nimport { AgentWorkflowActionsResource } from './workflows/workflow-actions.js'\n\nfunction parseWorkflow(raw: unknown): Workflow {\n return raw as Workflow\n}\n\n/**\n * Read and run access to Modus workflows.\n *\n * - `list` / `get` — browse workflows (`view: 'active'`, `'draft'`, or `'published'`)\n * - `chat` — send a workflow a message and stream its reply\n * - {@link WorkflowRunsResource runs} — start, monitor, and control workflow runs\n * - {@link AgentWorkflowActionsResource workflowActions} — execute workflow actions\n *\n * @example\n * ```ts\n * import { Modus } from '@getmodus/sdk'\n * const client = new Modus()\n * for await (const wf of (await client.workflows.list()).autoPagingIter()) {\n * console.log(wf.id, wf.name, wf.status)\n * }\n * ```\n */\nexport class WorkflowsResource extends WorkflowsResourceBase {\n readonly runs: WorkflowRunsResource\n readonly workflowActions: AgentWorkflowActionsResource\n\n /** @internal */\n constructor(\n http: HttpClient,\n config: ModusConfig,\n ) {\n super(http, config)\n this.runs = new WorkflowRunsResource(http, config)\n this.workflowActions = new AgentWorkflowActionsResource(http, config)\n }\n\n /**\n * Retrieve a workflow by its numeric id.\n *\n * @param workflowId - Numeric workflow id.\n * @param options.view - Which saved version to return (`active` or `draft`).\n * @param options.includeVariation - Include variation metadata when supported.\n * @returns The workflow (`id`, `name`, `status`, …).\n * @throws {NotFoundError} When no workflow has this id.\n *\n * @example\n * ```ts\n * const [first] = (await client.workflows.list()).items\n * const wf = await client.workflows.get(first.id)\n * console.log(wf.name, wf.status)\n * ```\n */\n async get(\n workflowId: number | string,\n options: { view?: VariationView; includeVariation?: boolean } = {},\n ): Promise<Workflow> {\n validateId(workflowId, 'workflow_id')\n const query: Record<string, string | boolean> = {}\n if (options.view !== undefined) query.view = options.view\n if (options.includeVariation !== undefined) {\n query.includeVariation = options.includeVariation\n }\n const data = await invokeWithRetry(this.config, this.http, 'WorkflowsController_get', {\n pathParams: { id: workflowId },\n query: Object.keys(query).length > 0 ? query : undefined,\n })\n return parseWorkflow(data)\n }\n\n /**\n * Chat with a published workflow. Node output streams live from the agent\n * host: iterate `textStream()` for tokens, or `await` the result for the\n * workflow's final output.\n *\n * @param workflowId - Numeric workflow id.\n * @param message - User message text.\n * @param options.model - Required model id (e.g. `\"claude-sonnet-5.5\"`).\n * @param options.threadId - Continue an existing conversation; omit to start new.\n * @returns A chat session — iterate it or `await` it for `content`, `threadId`, `runId`.\n * @throws {ModusError} When no agent host is known for a custom `baseUrl`.\n *\n * @example\n * ```ts\n * const { content } = await client.workflows.chat(workflowId, 'Run this week\\'s digest', {\n * model: 'claude-sonnet-5.5',\n * })\n * console.log(content)\n * ```\n */\n chat(workflowId: number | string, message: string, options: ChatOptions): ChatSession {\n return startChat(this.http, this.config, { kind: 'workflows', id: workflowId }, message, options)\n }\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../_config.js'\nimport type { HttpClient } from '../../../_http.js'\nimport { aipListParams, buildAipPage, type Page } from '../../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../../_request.js'\nimport { validatePageSize } from '../../../_validation.js'\nimport type { Connection } from '../../../types/connections.js'\n\n/** Generated base for the consumption `connections` resource. */\nexport class ConnectionsResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * List connections.\n *\n * Returns a paginated page of warehouse and SaaS integration connections the caller can `use`.\n * Connections the caller cannot access are filtered out. Use the returned `id` when creating\n * saved-query context items. Pagination uses an opaque token returned in `nextPageToken`.\n *\n * **Requires:** `context:read`\n *\n * @param options.pageSize - Items per page. Defaults to 25.\n * @param options.pageToken - Opaque page token from a previous response's `nextPageToken`. Omit\n * for the first page.\n * @param options.type - Filter by effective integration category (case-sensitive exact match).\n * @returns A page of connections.\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n type?: string\n } = {}): Promise<Page<Connection>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, options.type)\n }\n\n protected async listPage(\n pageSize: number,\n pageToken: string | undefined,\n type?: string,\n ): Promise<Page<Connection>> {\n const extra: Record<string, string> = {}\n if (type !== undefined) extra.type = type\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ConnectionsController_list', {\n query: aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | undefined | null\n >,\n }),\n )\n return buildAipPage(\n data,\n 'connections',\n (raw) => raw as Connection,\n (token) => this.listPage(pageSize, token, type),\n )\n }\n}\n","import { ConnectionsResourceBase } from '../_generated/resources/consumption/connections.js'\nimport { aipListParams, buildAipPage, type Page } from '../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../_request.js'\nimport { validateId, validatePageSize } from '../_validation.js'\nimport type { Connection, ConnectionSelection } from '../types/connections.js'\n\n/**\n * Read access to integration connections.\n */\nexport class ConnectionsResource extends ConnectionsResourceBase {\n /**\n * Find the first connection whose name matches (case-insensitive).\n *\n * Pages through {@link ConnectionsResource.list} until a match is found.\n *\n * @param options.name - Connection name to search for.\n * @param options.type - Optional integration category filter.\n * @param options.pageSize - Page size when scanning (default 25).\n * @returns The matching connection, or `undefined` if none is found.\n */\n async find(options: {\n name: string\n type?: string\n pageSize?: number\n }): Promise<Connection | undefined> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n const target = options.name.trim().toLowerCase()\n let token: string | undefined\n do {\n const page = await this.listPage(pageSize, token, options.type)\n const match = page.items.find((c) => c.name?.toLowerCase() === target)\n if (match) return match\n if (!page.hasNextPage()) break\n token = page.nextPageToken\n } while (token !== undefined)\n return undefined\n }\n\n /**\n * List the selectable units on a connection (a repository, a schema, a project).\n *\n * @param connectionId - Connection id.\n * @param options.pageSize - Maximum items per page (default 25).\n * @param options.pageToken - Opaque token from a previous page.\n * @returns A page of selectable units — use {@link iterSelections} or `.autoPagingIter()` for every page.\n * @example\n * for await (const unit of client.connections.iterSelections('7a3f9d2c-1111-4000-a000-000000000abc')) {\n * console.log(unit.objectType, unit.path)\n * }\n */\n listSelections(\n connectionId: string,\n options: { pageSize?: number; pageToken?: string } = {},\n ): Promise<Page<ConnectionSelection>> {\n validateId(connectionId, 'connection_id')\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listSelectionsPage(connectionId, pageSize, options.pageToken)\n }\n\n private async listSelectionsPage(\n connectionId: string,\n pageSize: number,\n pageToken: string | undefined,\n ): Promise<Page<ConnectionSelection>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ConnectionsController_listSelections', {\n pathParams: { connectionId },\n query: aipListParams(pageSize, pageToken) as Record<\n string,\n string | number | boolean | undefined | null\n >,\n }),\n )\n return buildAipPage(\n data,\n 'selections',\n (raw) => raw as ConnectionSelection,\n (token) => this.listSelectionsPage(connectionId, pageSize, token),\n )\n }\n\n /**\n * Yield every selectable unit on a connection, following pages.\n *\n * @param connectionId - Connection id.\n * @param options.pageSize - Maximum items per page (default 25).\n * @example\n * for await (const unit of client.connections.iterSelections('7a3f9d2c-1111-4000-a000-000000000abc')) {\n * console.log(unit.objectType, unit.displayName)\n * }\n */\n async *iterSelections(\n connectionId: string,\n options: { pageSize?: number } = {},\n ): AsyncGenerator<ConnectionSelection> {\n const page = await this.listSelections(connectionId, options)\n yield* page.autoPagingIter()\n }\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../../_config.js'\nimport type { HttpClient } from '../../../../_http.js'\nimport { invokeWithRetry, omitUndefined } from '../../../../_request.js'\nimport type { ContextItemsQuery, ContextItemsQueryResult } from '../../../../types/context.js'\n\n/** Generated base for the consumption `context.items` resource. */\nexport class ContextItemsResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * Query context items with SQL.\n *\n * Runs one read-only SQL statement over the `context_items` table and returns its rows. The query\n * sees only the items you can read. A query that is not read-only or not valid returns 400; one\n * that runs past 20 s returns 422.\n *\n * **Requires:** `context:read`\n *\n * @param query - Request body; see `ContextItemsQuery`.\n *\n * @example\n * ```ts\n * const result = await modus.context.items.query({\n * sql: 'SELECT context_type, count(*) AS items FROM context_items GROUP BY context_type',\n * })\n * result.rows\n * ```\n */\n async query(query: ContextItemsQuery): Promise<ContextItemsQueryResult> {\n const data = await invokeWithRetry(this.config, this.http, 'ContextItemsQueryController_query', {\n jsonBody: omitUndefined(query as Record<string, unknown>),\n })\n return data as ContextItemsQueryResult\n }\n}\n","import { ContextItemsResourceBase } from '../../_generated/resources/consumption/context/items.js'\nimport { NotFoundError } from '../../_exceptions.js'\nimport { aipListParams, buildAipPage, type Page } from '../../_pagination.js'\nimport { asRecord, invokeWithRetry, omitUndefined } from '../../_request.js'\nimport { DEFAULT_MAX_PAGE_SIZE, validatePageSize } from '../../_validation.js'\nimport type { ContextItem, ContextItemLookupRow } from '../../types/context.js'\nimport type { ContextValueRow } from '../../types/context-values.js'\nimport type { ContentProjection, JsonObjectInput } from '../../types/json-blob.js'\n\nfunction contextListParams(\n pageSize: number,\n pageToken: string | undefined,\n filters: ListContextItemsFilters = {},\n): Record<string, string | number | boolean | readonly string[] | undefined | null> {\n const extra: Record<string, string | readonly string[]> = {}\n if (filters.contextType !== undefined) extra.contextTypes = [filters.contextType]\n if (filters.parentUids !== undefined) {\n extra.parentUids = filters.parentUids.length === 0 ? '' : [...filters.parentUids]\n }\n if (filters.ancestorUids !== undefined) {\n extra.ancestorUids = filters.ancestorUids.length === 0 ? '' : [...filters.ancestorUids]\n }\n if (filters.connectionIds !== undefined) {\n extra.connectionIds = filters.connectionIds.length === 0 ? '' : [...filters.connectionIds]\n }\n return aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | readonly string[] | undefined | null\n >\n}\n\ntype ListContextItemsFilters = {\n contextType?: string\n parentUids?: readonly string[]\n ancestorUids?: readonly string[]\n connectionIds?: readonly string[]\n}\n\nfunction parseContextItem(raw: unknown): ContextItem {\n return raw as ContextItem\n}\n\nfunction parseContextValueRow(raw: unknown): ContextValueRow {\n return raw as ContextValueRow\n}\n\nfunction parseLookupResponse(raw: Record<string, unknown>): ContextItemLookupRow | undefined {\n const item = raw.item\n if (item === null || item === undefined) return undefined\n return item as ContextItemLookupRow\n}\n\n/**\n * Read the org knowledge base (notes, metrics, saved queries, integration items).\n *\n * Use `client.context.items` after `new Modus()`. Prefer `list` / `get` /\n * `lookup` for discovery; use `listValues` when a field holds a large array\n * inside `content`.\n *\n * @example\n * ```ts\n * import { Modus } from '@getmodus/sdk'\n * const client = new Modus()\n * for await (const item of (await client.context.items.list({ pageSize: 25 })).autoPagingIter()) {\n * console.log(item.contextType, item.description ?? item.uid)\n * }\n * ```\n */\nexport class ContextItemsResource extends ContextItemsResourceBase {\n /**\n * List knowledge-base items.\n *\n * @param options.pageSize - Maximum items per page (default 25).\n * @param options.pageToken - Opaque token from a previous page.\n * @param options.contextType - Filter to a single context type (e.g. `\"note\"`).\n * @param options.parentUids - Exact ordered native ancestry chain for direct\n * children. Omit to leave parent unrestricted; pass `[]` for the known-empty\n * root. Native UIDs are exact tokens (including whitespace); do not use the\n * hashed context-item `uid`. For a folder's children, send that item's\n * `ancestry` UIDs plus its last `dataPath` token.\n * @param options.ancestorUids - Ordered UID ancestry prefix for strict\n * descendants. Omit to leave unrestricted; pass `[]` for every item with\n * non-null ancestry.\n * @param options.connectionIds - Restrict to these connection ids. Omit to\n * leave unfiltered; pass `[]` to match none. The Files root is\n * `connectionIds: ['files']` with `parentUids: []`.\n * @returns A page of context items — use `.autoPagingIter()` for all pages.\n *\n * @example\n * ```ts\n * const notes = await client.context.items.list({ contextType: 'note', pageSize: 50 })\n * for (const item of notes.items) {\n * console.log(item.description ?? item.uid, item.uid)\n * }\n * ```\n *\n * @example\n * ```ts\n * const rootFolders = await client.context.items.list({\n * connectionIds: ['files'],\n * contextType: 'file_folder_metadata',\n * parentUids: [],\n * })\n * const folder = rootFolders.items[0]\n * const nativeUid = folder?.dataPath?.at(-1)\n * // Known ancestry only — never treat null/omitted ancestry as a root chain.\n * if (folder?.ancestry != null && nativeUid !== undefined) {\n * const filesInFolder = await client.context.items.list({\n * connectionIds: ['files'],\n * contextType: 'file_upload',\n * parentUids: [...folder.ancestry.map((a) => a.uid), nativeUid],\n * })\n * }\n * ```\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n contextType?: string\n parentUids?: readonly string[]\n ancestorUids?: readonly string[]\n connectionIds?: readonly string[]\n } = {}): Promise<Page<ContextItem>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, {\n contextType: options.contextType,\n parentUids: options.parentUids,\n ancestorUids: options.ancestorUids,\n connectionIds: options.connectionIds,\n })\n }\n\n private async listPage(\n pageSize: number,\n pageToken: string | undefined,\n filters: ListContextItemsFilters,\n ): Promise<Page<ContextItem>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ContextItemsController_list', {\n query: contextListParams(pageSize, pageToken, filters),\n }),\n )\n return buildAipPage(data, 'contextItems', parseContextItem, (token) =>\n this.listPage(pageSize, token, filters),\n )\n }\n\n /**\n * Retrieve a knowledge-base item by uid.\n *\n * @param uid - Item uid.\n * @returns The context item (`uid`, `contextType`, `content`, …).\n * @throws {NotFoundError} When no item matches the uid.\n *\n * @example\n * ```ts\n * const item = await client.context.items.get(uid)\n * console.log(item.contextType, item.description ?? item.uid)\n * ```\n */\n async get(uid: string): Promise<ContextItem> {\n const data = await invokeWithRetry(this.config, this.http, 'ContextItemsController_get', {\n pathParams: { uid },\n })\n return parseContextItem(data)\n }\n\n /**\n * Look up a knowledge-base item by type and data path.\n *\n * @param options.contextType - Context type to match (e.g. `\"note\"`).\n * @param options.dataPath - Hierarchical path segments that identify the item.\n * @param options.contentProjection - Optional fields to include from item content.\n * @returns The matching row, or `undefined` when no item is found (404).\n *\n * @example\n * ```ts\n * const found = await client.context.items.lookup({\n * contextType: 'note',\n * dataPath: ['finance', 'arr-definition'],\n * })\n * if (found) console.log(found.uid, found.content)\n * ```\n */\n async lookup(options: {\n contextType: string\n dataPath: string[]\n contentProjection?: JsonObjectInput | ContentProjection\n }): Promise<ContextItemLookupRow | undefined> {\n const body = omitUndefined({\n contextType: options.contextType,\n dataPath: options.dataPath,\n contentProjection: options.contentProjection,\n })\n try {\n const raw = asRecord(\n await invokeWithRetry(this.config, this.http, 'ContextItemsController_lookup', {\n jsonBody: body,\n }),\n )\n return parseLookupResponse(raw)\n } catch (error) {\n if (error instanceof NotFoundError) return undefined\n throw error\n }\n }\n\n /**\n * Page through the elements of an array field inside one context item's content.\n *\n * Each row is `{ index, value }`: the element's position in the array and the\n * element itself. A field that is not an array reads as one element; a missing\n * field as none. Rejects with a not-found error when the item does not exist,\n * you cannot read it, or its context type is not `contextType`.\n *\n * @param uid - Item uid.\n * @param contextType - Context type of the item.\n * @param contentKeyPath - Dot path to the array inside item content (e.g. `\"enumValues\"`).\n * @param options.pageSize - Maximum elements per page (default 25).\n * @param options.pageToken - Opaque token from a previous page of the same item.\n * @returns A page of `{ index, value }` rows.\n *\n * @example\n * ```ts\n * // Replace PLACEHOLDER_UID with a real uid whose content has enumValues.\n * const page = await client.context.items.listValues(\n * 'PLACEHOLDER_UID',\n * 'table_column',\n * 'enumValues',\n * { pageSize: 25 },\n * )\n * for (const row of page.items) console.log(row.index, row.value)\n * ```\n */\n listValues(\n uid: string,\n contextType: string,\n contentKeyPath: string,\n options: { pageSize?: number; pageToken?: string } = {},\n ): Promise<Page<ContextValueRow>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize, DEFAULT_MAX_PAGE_SIZE)\n return this.listValuesPage(uid, contextType, contentKeyPath, pageSize, options.pageToken)\n }\n\n /**\n * Page through an array field of a context item already loaded via {@link ContextItemsResource.list} or {@link ContextItemsResource.get}.\n *\n * @param item - Context item (uses `item.uid` and `item.contextType`).\n * @param contentKeyPath - Dot path to the array inside item content.\n * @param options.pageSize - Maximum elements per page (default 25).\n * @param options.pageToken - Opaque token from a previous page of the same item.\n * @returns A page of `{ index, value }` rows.\n *\n * @example\n * ```ts\n * // Replace PLACEHOLDER_UID with a real uid that has enumValues in content.\n * const item = await client.context.items.get('PLACEHOLDER_UID')\n * const page = await client.context.items.listValuesFor(item, 'enumValues')\n * for (const row of page.items) console.log(row)\n * ```\n */\n listValuesFor(\n item: ContextItem,\n contentKeyPath: string,\n options: { pageSize?: number; pageToken?: string } = {},\n ): Promise<Page<ContextValueRow>> {\n return this.listValues(item.uid, item.contextType, contentKeyPath, options)\n }\n\n private async listValuesPage(\n uid: string,\n contextType: string,\n contentKeyPath: string,\n pageSize: number,\n pageToken: string | undefined,\n ): Promise<Page<ContextValueRow>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ContextItemsController_listValues', {\n pathParams: { uid },\n query: aipListParams(pageSize, pageToken, {\n contextType,\n contentKeyPath,\n }) as Record<string, string | number | boolean | undefined | null>,\n }),\n )\n return buildAipPage(data, 'values', parseContextValueRow, (token) =>\n this.listValuesPage(uid, contextType, contentKeyPath, pageSize, token),\n )\n }\n}\n","import type { ModusConfig } from '../../_config.js'\nimport type { HttpClient } from '../../_http.js'\nimport { CustomContextItemsResource } from './custom-items.js'\nimport { ContextItemsResource } from './items.js'\n\n/**\n * Read access to the Modus knowledge base.\n *\n * - {@link ContextItemsResource items} — list and look up indexed knowledge-base items.\n * - {@link CustomContextItemsResource customItems} — create and manage custom context items.\n *\n * Call path: `client.context` after `new Modus(...)`.\n */\nexport class ContextResource {\n readonly items: ContextItemsResource\n readonly customItems: CustomContextItemsResource\n\n /** @internal */\n constructor(http: HttpClient, config: ModusConfig) {\n this.items = new ContextItemsResource(http, config)\n this.customItems = new CustomContextItemsResource(http, config)\n }\n}\n","import type { ModusConfig } from '../_config.js'\nimport type { HttpClient } from '../_http.js'\nimport { invokeWithRetry } from '../_request.js'\nimport type {\n IngestedDataUploadResult,\n UploadIngestedDataOptions,\n} from '../types/ingested-data.js'\n\n/** Store exact integration requests and responses as immutable ingested data. */\nexport class IngestedDataResource {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {}\n\n /**\n * Store a complete SQL or HTTP request and response exactly once.\n *\n * Identity covers the complete organization, integration, request, and response\n * content. A duplicate raises `ConflictError`, which means the identical payload\n * is already stored and may be treated as a safe retry outcome.\n *\n * @param options.integrationType - Canonical Modus integration identifier.\n * @param options.request - Exact SQL or HTTP request that produced the response.\n * @param options.response - Response format, optional source HTTP status, and exact string content. SQL requires CSV.\n * @returns The checksum of the stored envelope.\n * @throws {ConflictError} When the complete payload is already stored.\n *\n * @example\n * ```ts\n * const stored = await client.ingestedData.upload({\n * integrationType: 'generic',\n * request: { type: 'sql', query: 'SELECT id, total FROM orders' },\n * response: { format: 'csv', content: 'id,total\\n1,42.00\\n' },\n * })\n * console.log(stored.checksum)\n * ```\n */\n async upload(options: UploadIngestedDataOptions): Promise<IngestedDataUploadResult> {\n const data = await invokeWithRetry(this.config, this.http, 'IngestedDataController_upload', {\n jsonBody: {\n integration_type: options.integrationType,\n request: options.request,\n response: options.response,\n },\n })\n return data as IngestedDataUploadResult\n }\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../../_config.js'\nimport type { HttpClient } from '../../../../_http.js'\nimport { invokeWithRetry } from '../../../../_request.js'\nimport { validateId } from '../../../../_validation.js'\nimport type { Conversation } from '../../../../types/conversations.js'\n\n/** Generated base for the consumption `modus.conversations` resource. */\nexport class ModusConversationsResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * Get a Modus conversation.\n *\n * Returns the full message history for a conversation thread.\n *\n * **Requires:** `scopes:read`\n *\n * @param threadId - Thread id from a conversation list or chat response.\n */\n async get(threadId: string): Promise<Conversation> {\n validateId(threadId, 'thread_id')\n const data = await invokeWithRetry(this.config, this.http, 'ModusConversationsController_get', {\n pathParams: { threadId },\n })\n return data as Conversation\n }\n}\n","import { ValidationError } from '../../_exceptions.js'\nimport type { ModusConfig } from '../../_config.js'\nimport { ModusConversationsResourceBase } from '../../_generated/resources/consumption/modus/conversations.js'\nimport type { HttpClient } from '../../_http.js'\nimport { aipListParams, buildAipPage, type Page } from '../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../_request.js'\nimport { validatePageSize } from '../../_validation.js'\nimport type {\n ConversationKind,\n ConversationListItem,\n} from '../../types/conversations.js'\n\nconst ALLOWED_KINDS = new Set<ConversationKind>(['all', 'modus', 'scopes'])\n\nfunction listParams(\n pageSize: number,\n pageToken: string | undefined,\n kind?: ConversationKind,\n source?: string,\n sourceRef?: string,\n): Record<string, string | number | boolean | undefined | null> {\n if (kind !== undefined && !ALLOWED_KINDS.has(kind)) {\n throw new ValidationError(\n `kind must be one of ${[...ALLOWED_KINDS].sort().join(', ')}, got ${JSON.stringify(kind)}`,\n )\n }\n const extra: Record<string, string> = {}\n if (kind !== undefined) extra.kind = kind\n if (source !== undefined) extra.source = source\n if (sourceRef !== undefined) extra.sourceRef = sourceRef\n return aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | undefined | null\n >\n}\n\nfunction parseListItem(raw: unknown): ConversationListItem {\n return raw as ConversationListItem\n}\n\n/** List and retrieve Modus / scope conversations. */\nexport class ModusConversationsResource extends ModusConversationsResourceBase {\n constructor(\n http: HttpClient,\n config: ModusConfig,\n ) {\n super(http, config)\n }\n\n /**\n * List conversations.\n *\n * @param options.pageSize - Items per page (default 25).\n * @param options.pageToken - Opaque token from a previous page.\n * @param options.kind - `\"modus\"`, `\"scopes\"`, or `\"all\"`.\n * @param options.source - Restrict to conversations started from this UI surface\n * (e.g. `\"context_chat\"`, `\"dashboard_copilot\"`, `\"slack\"`). Only valid with an\n * omitted `kind` or `kind: \"all\"`; the API throws an `UnprocessableError` (422)\n * if combined with `kind: \"modus\"` or `kind: \"scopes\"`.\n * @param options.sourceRef - Narrow `source` to one instance of that surface — for\n * `\"dashboard_copilot\"`, a dashboard id. Requires `source`; the API throws an\n * `UnprocessableError` (422) if sent on its own. Conversations recorded before\n * this filter shipped carry no instance key and never match it.\n * @returns Page of conversation list items.\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n kind?: ConversationKind\n source?: string\n sourceRef?: string\n } = {}): Promise<Page<ConversationListItem>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, options.kind, options.source, options.sourceRef)\n }\n\n private async listPage(\n pageSize: number,\n pageToken: string | undefined,\n kind?: ConversationKind,\n source?: string,\n sourceRef?: string,\n ): Promise<Page<ConversationListItem>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ModusConversationsController_list', {\n query: listParams(pageSize, pageToken, kind, source, sourceRef),\n }),\n )\n return buildAipPage(data, 'conversations', parseListItem, (token) =>\n this.listPage(pageSize, token, kind, source, sourceRef),\n )\n }\n}\n","import { startChat, type ChatOptions, type ChatSession } from '../../_chat.js'\nimport type { ModusConfig } from '../../_config.js'\nimport type { HttpClient } from '../../_http.js'\nimport { invokeWithRetry, omitUndefined } from '../../_request.js'\nimport type { ModusContextComposition } from '../../types/context-compose.js'\n\nimport { ModusConversationsResource } from './conversations.js'\n\n/**\n * Org-wide Modus assistant (full environment context and tools).\n *\n * Prefer `client.modus` over `client.scopes` when the question is not tied to one\n * published scope. Construct with `new Modus()` (reads `MODUS_API_KEY`).\n *\n * - `chat` — stream a reply live, or `await` it for the complete answer\n * - `getContext` — preview composed context without a chat turn\n * - `conversations` — list/get prior Modus threads\n *\n * @example\n * ```ts\n * import { Modus } from '@getmodus/sdk'\n * const client = new Modus()\n * const result = await client.modus.chat('What tables describe revenue?', {\n * model: 'claude-sonnet-5',\n * })\n * console.log(result.content, result.threadId)\n * ```\n */\nexport class ModusResource {\n readonly conversations: ModusConversationsResource\n\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {\n this.conversations = new ModusConversationsResource(http, config)\n }\n\n /**\n * Compose full-environment context for an intent without running chat.\n *\n * Runs on the agent host, like `chat`, so a compose may take up to 90 seconds; keep `timeoutMs`\n * above that. A compose still running at 90 seconds fails with `UPSTREAM_TIMEOUT` (504).\n *\n * @param message - Natural-language intent used to select context.\n * @param options.limit - Maximum context items to return. Omit to return all selected items.\n * @returns Composition metadata (counts / session id). Use `chat` for a reply.\n *\n * @example\n * ```ts\n * const ctx = await client.modus.getContext('What tables describe revenue?', { limit: 5 })\n * console.log(ctx.originalCount, ctx.sessionId)\n * ```\n */\n async getContext(\n message: string,\n options: { limit?: number } = {},\n ): Promise<ModusContextComposition> {\n const data = await invokeWithRetry(this.config, this.http, 'ModusContextComposeController_compose', {\n jsonBody: omitUndefined({ message, limit: options.limit }),\n })\n return data as ModusContextComposition\n }\n\n /**\n * Chat with Modus, the org-wide assistant. The reply streams live from the\n * agent host: iterate `textStream()` for tokens, or `await` the result for\n * the final answer. Pass the returned `threadId` back to continue.\n *\n * @param message - User message text.\n * @param options.model - Required model id (e.g. `\"claude-sonnet-5.5\"`).\n * @param options.threadId - Continue an existing conversation; omit to start new.\n * @returns A chat session — iterate it or `await` it for `content`, `threadId`, `runId`.\n * @throws {ModusError} When no agent host is known for a custom `baseUrl`.\n *\n * @example\n * ```ts\n * const result = await client.modus.chat('What tables describe revenue?', {\n * model: 'claude-sonnet-5.5',\n * })\n * console.log(result.content)\n * const follow = client.modus.chat('Break that down by region.', {\n * model: 'claude-sonnet-5.5',\n * threadId: result.threadId,\n * })\n * for await (const token of follow.textStream()) process.stdout.write(token)\n * ```\n */\n chat(message: string, options: ChatOptions): ChatSession {\n return startChat(this.http, this.config, { kind: 'modus' }, message, options)\n }\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../_config.js'\nimport type { HttpClient } from '../../../_http.js'\nimport { aipListParams, buildAipPage, type Page } from '../../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../../_request.js'\nimport { validateId, validatePageSize } from '../../../_validation.js'\nimport type { Scope } from '../../../types/scopes.js'\nimport type { VariationView } from '../../../types/views.js'\n\n/** Generated base for the consumption `scopes` resource. */\nexport class ScopesResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * List scopes.\n *\n * Returns a paginated page of scopes the caller can at least `use`. Scopes the caller cannot see\n * are filtered out. Pagination uses an opaque token returned in `nextPageToken`.\n *\n * **Requires:** `scopes:read`\n *\n * @param options.pageSize - Items per page. Defaults to 25.\n * @param options.pageToken - Opaque page token from a previous response's `nextPageToken`. Omit\n * for the first page.\n * @param options.search - Case-insensitive substring filter on scope name.\n * @param options.view - Variation view. `active` reads the deployed version, or the latest draft\n * when nothing is published. `draft` reads the latest builder snapshot. `published` reads only\n * the published version, and only scopes you can use.\n * @param options.managerId - Return only scopes supervised by this manager scope id.\n * @returns A page of scopes.\n *\n * @example\n * ```ts\n * for await (const scope of (await client.scopes.list()).autoPagingIter()) {\n * console.log(scope.id, scope.name, scope.status)\n * }\n * ```\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n search?: string\n view?: VariationView\n managerId?: number\n } = {}): Promise<Page<Scope>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, options.search, options.view, options.managerId)\n }\n\n protected async listPage(\n pageSize: number,\n pageToken: string | undefined,\n search?: string,\n view?: VariationView,\n managerId?: number,\n ): Promise<Page<Scope>> {\n const extra: Record<string, string | number> = {}\n if (search !== undefined) extra.search = search\n if (view !== undefined) extra.view = view\n if (managerId !== undefined) extra.managerId = managerId\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ScopesController_list', {\n query: aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | undefined | null\n >,\n }),\n )\n return buildAipPage(\n data,\n 'scopes',\n (raw) => raw as Scope,\n (token) => this.listPage(pageSize, token, search, view, managerId),\n )\n }\n\n /**\n * Get a scope.\n *\n * Returns a scope. `view=active` (default) is the deployed version, or the latest draft when\n * nothing is published. `view=draft` is the latest edits. `view=published` is only the published\n * version, and only if you can use the scope. Returns 404 if you cannot access it.\n *\n * **Requires:** `scopes:read`\n *\n * @param scopeId - Numeric scope id.\n * @param options.view - Which version to read. Defaults to `active`. `published` is only the\n * published version, and only if you can use the scope.\n *\n * @example\n * ```ts\n * const [first] = (await client.scopes.list()).items\n * const scope = await client.scopes.get(first.id)\n * console.log(scope.name, scope.status)\n * ```\n */\n async get(\n scopeId: number | string,\n options: { view?: VariationView } = {},\n ): Promise<Scope> {\n validateId(scopeId, 'scope_id')\n const data = await invokeWithRetry(this.config, this.http, 'ScopesController_get', {\n pathParams: { id: scopeId },\n query: { view: options.view },\n })\n return data as Scope\n }\n}\n","import { ScopesResourceBase } from '../_generated/resources/consumption/scopes.js'\nimport { startChat, type ChatOptions, type ChatSession } from '../_chat.js'\nimport { invokeWithRetry, omitUndefined } from '../_request.js'\nimport { validateId } from '../_validation.js'\nimport type { SkillContextComposition } from '../types/context-compose.js'\nimport { ScopeConversationsResource } from './scopes/conversations.js'\n\n/**\n * Read / chat with published scopes.\n *\n * Call path: `client.scopes` after `new Modus(...)`. Prefer `client.modus` for\n * the org-wide assistant. Create/deploy via `ModusManagement`.\n *\n * @example\n * ```ts\n * const [scope] = (await client.scopes.list()).items\n * const result = await client.scopes.chat(scope.id, 'What is our ARR trend?', {\n * model: 'claude-sonnet-5',\n * })\n * console.log(result.content, result.threadId)\n * ```\n */\nexport class ScopesResource extends ScopesResourceBase {\n\n /**\n * Return the conversations sub-resource scoped to `scopeId`.\n *\n * @param scopeId - Numeric scope id.\n * @returns Conversations resource for the scope.\n *\n * @example\n * ```ts\n * for await (const row of (\n * await client.scopes.conversations(scopeId).list({ pageSize: 10 })\n * ).autoPagingIter()) {\n * console.log(row.threadId, row.firstMessage)\n * }\n * ```\n */\n conversations(scopeId: number | string): ScopeConversationsResource {\n return new ScopeConversationsResource(this.http, this.config, scopeId)\n }\n\n /**\n * Compose context this scope would use for an intent, without running chat.\n *\n * Large bodies are bounded inline previews. This REST method does not expose file references\n * or a full-content fetch operation. Runs on the agent host, like `chat`, so a compose may take\n * up to 90 seconds; keep `timeoutMs` above that. A compose still running at 90 seconds fails\n * with `UPSTREAM_TIMEOUT` (504).\n *\n * @param scopeId - Numeric scope id.\n * @param message - Natural-language intent used to select context.\n * @param options.limit - Maximum context items to return. Omit to return all selected items.\n * @returns Composed context text plus selection counts, item UIDs, and correlation session id.\n *\n * @example\n * ```ts\n * const ctx = await client.scopes.getContext(scopeId, 'Which tables describe churn?', {\n * limit: 5,\n * })\n * console.log(ctx.originalCount, ctx.sessionId)\n * ```\n */\n async getContext(\n scopeId: number | string,\n message: string,\n options: { limit?: number } = {},\n ): Promise<SkillContextComposition> {\n validateId(scopeId, 'scope_id')\n const data = await invokeWithRetry(this.config, this.http, 'ScopeContextComposeController_compose', {\n pathParams: { id: scopeId },\n jsonBody: omitUndefined({ message, limit: options.limit }),\n })\n return data as SkillContextComposition\n }\n\n /**\n * Chat with a published scope. The reply streams live from the agent host:\n * iterate `textStream()` for tokens, or `await` the result for the final\n * answer. Pass the returned `threadId` back to continue the conversation.\n *\n * For the org-wide assistant use `client.modus.chat` instead.\n *\n * @param scopeId - Numeric scope id (must be active for chat).\n * @param message - User message text.\n * @param options.model - Required model id (e.g. `\"claude-sonnet-5.5\"`).\n * @param options.threadId - Continue an existing conversation; omit to start new.\n * @returns A chat session — iterate it or `await` it for `content`, `threadId`, `runId`.\n * @throws {ModusError} When no agent host is known for a custom `baseUrl`.\n *\n * @example\n * ```ts\n * const chat = client.scopes.chat(scopeId, 'What is our ARR trend?', { model: 'claude-sonnet-5.5' })\n * for await (const token of chat.textStream()) process.stdout.write(token)\n * const { threadId } = await chat\n * const follow = await client.scopes.chat(scopeId, 'Break that down by segment.', {\n * model: 'claude-sonnet-5.5',\n * threadId,\n * })\n * console.log(follow.content)\n * ```\n */\n chat(scopeId: number | string, message: string, options: ChatOptions): ChatSession {\n return startChat(this.http, this.config, { kind: 'scopes', id: scopeId }, message, options)\n }\n}\n","import type { ModusConfig } from '../_config.js'\nimport type { HttpClient } from '../_http.js'\nimport { buildAipPage, type Page } from '../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../_request.js'\nimport { ValidationError } from '../_exceptions.js'\nimport { validateId, validatePageSize } from '../_validation.js'\nimport {\n type RecordSuggestionEventRequest,\n type SuggestionQuestion,\n} from '../types/suggestions.js'\n\nconst DEFAULT_SUGGESTIONS_PAGE_SIZE = 5\nconst MAX_SUGGESTIONS_PAGE_SIZE = 12\n\nfunction parseSuggestion(raw: unknown): SuggestionQuestion {\n return raw as SuggestionQuestion\n}\n\nfunction suggestionListParams(options: {\n pageSize: number\n pageToken?: string\n scopeId?: number\n scopeIds?: readonly number[]\n}): Record<string, string | number | undefined> {\n return {\n pageSize: options.pageSize,\n pageToken: options.pageToken,\n scopeId: options.scopeId,\n scopeIds: options.scopeIds?.join(','),\n }\n}\n\n/**\n * List suggested questions and record suggestion events.\n */\nexport class SuggestionsResource {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {}\n\n /**\n * List approved suggested questions.\n *\n * @param options.pageSize - Maximum items per page (default 5, max 12).\n * @param options.pageToken - Opaque token from a previous page.\n * @param options.scopeId - Filter to a single scope.\n * @param options.scopeIds - Filter to one or more scopes. An empty list throws; omit it for every scope.\n * @returns A page of suggested questions.\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n scopeId?: number\n scopeIds?: readonly number[]\n } = {}): Promise<Page<SuggestionQuestion>> {\n const pageSize = options.pageSize ?? DEFAULT_SUGGESTIONS_PAGE_SIZE\n validatePageSize(pageSize, MAX_SUGGESTIONS_PAGE_SIZE)\n if (options.scopeIds?.length === 0) {\n throw new ValidationError('scopeIds requires at least one id; omit it to list suggestions for every scope')\n }\n return this.listPage(pageSize, options.pageToken, options.scopeId, options.scopeIds)\n }\n\n private async listPage(\n pageSize: number,\n pageToken: string | undefined,\n scopeId: number | undefined,\n scopeIds: readonly number[] | undefined,\n ): Promise<Page<SuggestionQuestion>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'SuggestionsController_listApproved', {\n query: suggestionListParams({ pageSize, pageToken, scopeId, scopeIds }),\n }),\n )\n return buildAipPage(data, 'suggestions', parseSuggestion, (token) =>\n this.listPage(pageSize, token, scopeId, scopeIds),\n )\n }\n\n /**\n * Record that a suggested question was shown, clicked, dismissed, or submitted.\n *\n * @param id - Suggestion id.\n * @param event - Event details, including `eventType` (`shown`, `clicked`, `dismissed`, or `submitted`).\n */\n async recordEvent(id: string, event: RecordSuggestionEventRequest): Promise<void> {\n validateId(id, 'id')\n await invokeWithRetry(this.config, this.http, 'SuggestionsController_recordEvent', {\n pathParams: { id },\n jsonBody: event,\n })\n }\n}\n","/**\n * @getmodus/sdk — official TypeScript client for Modus.\n */\n\nexport type { components, paths, operations } from './_generated/v1.js'\nexport type { OperationId, OperationSpec } from './_generated/operations.js'\nexport { OPERATIONS } from './_generated/operations.js'\n\nexport {\n APIConnectionError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n InternalServerError,\n ModusError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n RunCancelledError,\n StreamTimeoutError,\n UnprocessableError,\n ValidationError,\n} from './_exceptions.js'\n\nexport { ChatSession } from './_chat.js'\nexport type { ChatOptions } from './_chat.js'\nexport { Page } from './_pagination.js'\nexport type {\n AssistantContentResetEvent,\n CancelledEvent,\n DoneEvent,\n ErrorEvent,\n RunEvent,\n ApprovalRequiredEvent,\n RunEventBase,\n StreamTimeoutEvent,\n TokenEvent,\n} from './types/runs.js'\nexport type { ChatModel, ChatResult } from './types/chat.js'\nexport type { ModusOptions } from './_config.js'\nexport type { Scope, ScopeStatus, ScopeVariation, Skill, SkillStatus, SkillVariation } from './types/scopes.js'\nexport type { Workflow, Agent } from './types/workflows.js'\nexport { AgentType, WorkflowType } from './types/workflows.js'\nexport type {\n AgentRun,\n AgentRunCreateRequest,\n AgentRunListItem,\n ApprovalScope,\n CancelRunRequest,\n CreateAgentRunRequest,\n EditQueuedRunRequest,\n FollowUpRunRequest,\n InterruptRunRequest,\n ModusRunCreateRequest,\n ResumeRunRequest,\n RunAdmission,\n RunStatus,\n RunTimeframe,\n SkillRunCreateRequest,\n WorkflowActionRequest,\n} from './types/agent-runs.js'\nexport type { AgentRunStream } from './resources/workflows/runs.js'\nexport type {\n Conversation,\n ConversationKind,\n ConversationListItem,\n Message,\n} from './types/conversations.js'\nexport { conversationScopeId, conversationSkillId } from './types/conversations.js'\nexport type { Connection, ConnectionSelection } from './types/connections.js'\nexport type { SupervisionView, VariationView } from './types/views.js'\nexport type {\n ContextItem,\n ContextItemAncestor,\n ContextItemDeletion,\n ContextItemLookupRow,\n ContextItemsQuery,\n ContextItemsQueryResult,\n ContextItemMove,\n ContextItemAccessUpdate,\n UpdateContextItemAccessInput,\n ContextType,\n} from './types/context.js'\nexport type { ContextValueRow } from './types/context-values.js'\nexport type {\n ComposeSkillContextRequest,\n ModusContextComposition,\n ModusContextRequest,\n SkillContextComposition,\n} from './types/context-compose.js'\nexport type {\n RecordSuggestionEventRequest,\n SuggestionEventSource,\n SuggestionEventType,\n SuggestionQuestion,\n} from './types/suggestions.js'\nexport type {\n HttpIngestedDataRequest,\n IngestedDataRequest,\n IngestedDataResponse,\n IngestedDataResponseFormat,\n IngestedDataUploadResult,\n SqlIngestedDataRequest,\n UploadIngestedDataOptions,\n} from './types/ingested-data.js'\n\nexport type { ModusConfig } from './_config.js'\nexport type { ActiveConversationRun, ActiveConversationRunStatus } from './types/runs.js'\nexport type { RunEventsPollResponse } from './types/agent-runs.js'\nexport type { ContentProjection, JsonObjectInput } from './types/json-blob.js'\nexport type {\n CreateCustomContextItemInput,\n CreatedCustomContextItem,\n CustomAttributeInput,\n CustomContextItemDeletion,\n CustomContextItemKind,\n CustomContextItemRelationInput,\n UpdateCustomContextItemInput,\n} from './resources/context/custom-items.js'\nexport type { ScopesResource } from './resources/scopes.js'\nexport type { ScopeConversationsResource } from './resources/scopes/conversations.js'\nexport type { ModusResource } from './resources/modus/modus.js'\nexport type { ModusConversationsResource } from './resources/modus/conversations.js'\nexport type { WorkflowsResource } from './resources/workflows.js'\nexport type { WorkflowRunsResource } from './resources/workflows/runs.js'\nexport type { AgentWorkflowActionsResource } from './resources/workflows/workflow-actions.js'\nexport type { ContextResource } from './resources/context/context.js'\nexport type { ContextItemsResource } from './resources/context/items.js'\nexport type { CustomContextItemsResource } from './resources/context/custom-items.js'\nexport type { ConnectionsResource } from './resources/connections.js'\nexport type { SuggestionsResource } from './resources/suggestions.js'\nexport type { IngestedDataResource } from './resources/ingested-data.js'\n\nimport { ModusClientBase } from './_client-base.js'\nimport { WorkflowsResource } from './resources/workflows.js'\nimport { ConnectionsResource } from './resources/connections.js'\nimport { ContextResource } from './resources/context/context.js'\nimport { IngestedDataResource } from './resources/ingested-data.js'\nimport { ModusResource } from './resources/modus/modus.js'\nimport { ScopesResource } from './resources/scopes.js'\nimport { SuggestionsResource } from './resources/suggestions.js'\n\n/**\n * Read / invoke client for Modus scopes, workflows, connections, and more.\n *\n * Call path: `const client = new Modus(...)` then `client.scopes`, `client.context`, …\n *\n * @param options - Client configuration (`apiKey`, `baseUrl`, `timeoutMs`, `maxRetries`).\n */\nexport class Modus extends ModusClientBase {\n readonly scopes: ScopesResource\n readonly modus: ModusResource\n readonly workflows: WorkflowsResource\n readonly context: ContextResource\n readonly connections: ConnectionsResource\n readonly suggestions: SuggestionsResource\n readonly ingestedData: IngestedDataResource\n\n constructor(options: import('./_config.js').ModusOptions = {}) {\n super(options)\n this.scopes = new ScopesResource(this.http, this.config)\n this.modus = new ModusResource(this.http, this.config)\n this.workflows = new WorkflowsResource(this.http, this.config)\n this.context = new ContextResource(this.http, this.config)\n this.connections = new ConnectionsResource(this.http, this.config)\n this.suggestions = new SuggestionsResource(this.http, this.config)\n this.ingestedData = new IngestedDataResource(this.http, this.config)\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/modus/modus/distribution/clients/typescript/modus-sdk/dist/index.cjs","../src/_agent_run_request.ts","../src/_streaming.ts","../src/_chat.ts","../src/types/workflows.ts","../src/types/conversations.ts","../src/_generated/resources/consumption/workflows.ts","../src/resources/workflows/runs.ts","../src/resources/workflows/workflow-actions.ts","../src/resources/workflows.ts","../src/_generated/resources/consumption/connections.ts","../src/resources/connections.ts","../src/_generated/resources/consumption/context/items.ts","../src/resources/context/items.ts","../src/resources/context/context.ts","../src/resources/ingested-data.ts","../src/_generated/resources/consumption/modus/conversations.ts","../src/resources/modus/conversations.ts","../src/resources/modus/modus.ts","../src/_generated/resources/consumption/scopes.ts","../src/resources/scopes.ts","../src/resources/suggestions.ts","../src/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BmF,EAAA;AAChC,IAAA;AACnD,EAAA;AACF;ApBijDsD;AACA;AqBjpDhB;AACJ;AAEyB;AAClD,EAAA;AACT;AAOgD;AACvC,EAAA;AACa,IAAA;AACC,IAAA;AACF,IAAA;AACmB,IAAA;AACtC,EAAA;AACF;AAKiC;AAAA;AAK7B,EAAA;AAFiB,IAAA;AACA,IAAA;AAChB,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBwC,EAAA;AACJ,IAAA;AACV,IAAA;AACS,IAAA;AACR,MAAA;AAC5B,IAAA;AACkD,IAAA;AACpD,EAAA;AAME,EAAA;AAEa,IAAA;AACmC,MAAA;AACJ,QAAA;AACzC,MAAA;AACH,IAAA;AACO,IAAA;AAAa,MAAA;AAAM,MAAA;AAAe,MAAA;AACR,MAAA;AACjC,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQkF,EAAA;AAC7D,IAAA;AAC2B,IAAA;AAC3B,MAAA;AACP,MAAA;AACX,IAAA;AACH,EAAA;AACF;ArB8nDsD;AACA;AsBtkDX;AASsB,EAAA;AAChD,IAAA;AACoC,IAAA;AACF,IAAA;AACG,IAAA;AACJ,IAAA;AACE,IAAA;AACA,IAAA;AACE,IAAA;AACpD,EAAA;AACF;AtBgkDsD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/modus/modus/distribution/clients/typescript/modus-sdk/dist/index.cjs","sourcesContent":[null,"import { randomUUID } from 'node:crypto'\n\n/** Mint or reuse a non-empty sessionId for agent-host runs. */\nexport function resolveAgentRunSessionId(sessionId?: string | null): string {\n if (typeof sessionId === 'string' && sessionId.trim()) return sessionId.trim()\n return randomUUID()\n}\n","import type {\n ApprovalRequiredEvent,\n AssistantContentResetEvent,\n CancelledEvent,\n DoneEvent,\n ErrorEvent,\n RunEvent,\n StreamTimeoutEvent,\n TokenEvent,\n} from './types/runs.js'\n\nfunction parseLine(line: string): Record<string, unknown> | undefined {\n if (!line.startsWith('data:')) return undefined\n const raw = line.slice(5).trimStart()\n if (!raw || raw === '[DONE]') return undefined\n try {\n const data = JSON.parse(raw) as unknown\n if (data && typeof data === 'object' && !Array.isArray(data)) {\n return data as Record<string, unknown>\n }\n } catch {\n return undefined\n }\n return undefined\n}\n\nfunction isAsyncIterable<T>(value: Iterable<T> | AsyncIterable<T>): value is AsyncIterable<T> {\n return Symbol.asyncIterator in Object(value)\n}\n\nconst NODE_TERMINAL_TYPES = new Set<unknown>(['done', 'error', 'cancelled', 'stream_timeout'])\n\nfunction* parseData(data: Record<string, unknown>, id: string | undefined): Generator<RunEvent> {\n const eventType = typeof data.type === 'string' ? data.type : 'unknown'\n const withId = id === undefined ? {} : { id }\n\n if (eventType === 'node_content') {\n // A workflow wraps each node's frames; the inner frame is a normal run event.\n // A node's own terminal frame does not end the workflow: only workflow_* does.\n const inner = data.event\n if (inner && typeof inner === 'object' && !Array.isArray(inner)) {\n const frame = inner as Record<string, unknown>\n if (!NODE_TERMINAL_TYPES.has(frame.type)) yield* parseData(frame, id)\n }\n } else if (eventType === 'token') {\n const event: TokenEvent = {\n type: 'token',\n content: typeof data.content === 'string' ? data.content : '',\n ...(typeof data.subAgent === 'string' ? { subAgent: data.subAgent } : {}),\n ...withId,\n }\n yield event\n } else if (eventType === 'done' || eventType === 'workflow_done') {\n const content = eventType === 'done' ? data.content : data.finalOutput\n const event: DoneEvent = {\n type: 'done',\n runId: typeof data.runId === 'string' ? data.runId : '',\n threadId: typeof data.threadId === 'string' ? data.threadId : '',\n ...(typeof content === 'string' ? { content } : {}),\n ...withId,\n }\n yield event\n } else if (eventType === 'approval_required') {\n // Project to the declared fields, as the Python parser does: unknown or mistyped frame data never reaches callers.\n const event: ApprovalRequiredEvent = { type: 'approval_required' }\n for (const key of ['toolId', 'toolName', 'title', 'description', 'nodeId', 'prompt'] as const) {\n const value = data[key]\n if (typeof value === 'string') event[key] = value\n }\n const { args, options } = data\n if (args && typeof args === 'object' && !Array.isArray(args)) event.args = args as Record<string, unknown>\n if (Array.isArray(options)) event.options = options as ApprovalRequiredEvent['options']\n yield { ...event, ...withId }\n } else if (eventType === 'workflow_cancelled') {\n const event: CancelledEvent = { type: 'cancelled', ...withId }\n yield event\n } else if (eventType === 'error' || eventType === 'workflow_error') {\n const msg =\n data.error ?? data.message ?? data.content ?? 'Unknown run error'\n const event: ErrorEvent = {\n type: 'error',\n message: String(msg),\n ...(typeof data.requestId === 'string' ? { requestId: data.requestId } : {}),\n ...withId,\n }\n yield event\n } else if (eventType === 'cancelled') {\n const event: CancelledEvent = { type: 'cancelled', ...withId }\n yield event\n } else if (eventType === 'stream_timeout') {\n const event: StreamTimeoutEvent = { type: 'stream_timeout', ...withId }\n yield event\n } else if (eventType === 'assistant_content_reset') {\n if (typeof data.content !== 'string') return\n const event: AssistantContentResetEvent = {\n type: 'assistant_content_reset',\n content: data.content,\n ...(typeof data.visibleContent === 'string'\n ? { visibleContent: data.visibleContent }\n : {}),\n attempt: typeof data.attempt === 'number' ? data.attempt : 1,\n reason: 'provider_stream_failed',\n ...(data.subAgent && typeof data.subAgent === 'object' && !Array.isArray(data.subAgent)\n ? { subAgent: data.subAgent as Record<string, unknown> }\n : {}),\n ...withId,\n }\n yield event\n }\n // Keepalives, tool and progress events, and unknown future types yield nothing.\n}\n\n/**\n * Line-at-a-time SSE parser. An `id:` line names every event after it until the next\n * `id:` line, so one parser must see every line of a stream.\n */\nfunction sseLineParser(): (line: string) => Generator<RunEvent> {\n let lastId: string | undefined\n return function* (line: string) {\n if (line.startsWith('id:')) {\n lastId = line.slice(3).trim() || undefined\n return\n }\n const data = parseLine(line)\n if (data !== undefined) yield* parseData(data, lastId)\n }\n}\n\nfunction* parseSyncSseLines(lines: Iterable<string>): Generator<RunEvent> {\n const parse = sseLineParser()\n for (const line of lines) yield* parse(line)\n}\n\nasync function* parseAsyncSseLines(lines: AsyncIterable<string>): AsyncGenerator<RunEvent> {\n const parse = sseLineParser()\n for await (const line of lines) yield* parse(line)\n}\n\n/** Convert raw SSE lines into typed run events (forward-compatible), each with its SSE `id`. */\nexport function parseSseStream(lines: Iterable<string>): Generator<RunEvent>\nexport function parseSseStream(lines: AsyncIterable<string>): AsyncGenerator<RunEvent>\nexport function parseSseStream(\n lines: Iterable<string> | AsyncIterable<string>,\n): Generator<RunEvent> | AsyncGenerator<RunEvent> {\n return isAsyncIterable(lines) ? parseAsyncSseLines(lines) : parseSyncSseLines(lines)\n}\n","import {\n ModusError,\n RunCancelledError,\n StreamTimeoutError,\n} from './_exceptions.js'\nimport { requireAgentHost, type ModusConfig } from './_config.js'\nimport { resolveAgentRunSessionId } from './_agent_run_request.js'\nimport type { HttpClient } from './_http.js'\nimport { parseSseStream } from './_streaming.js'\nimport { validateChatModel, validateId } from './_validation.js'\nimport type { ChatModel, ChatResult } from './types/chat.js'\nimport type { ApprovalRequiredEvent, RunEvent } from './types/runs.js'\n\n/** What a chat talks to: a scope, a workflow, or Modus itself. */\nexport type ChatTarget =\n | { readonly kind: 'scopes' | 'workflows'; readonly id: number | string }\n | { readonly kind: 'modus' }\n\n/** Options shared by every `chat()` method. */\nexport interface ChatOptions {\n /** Canonical model id for this run (required). See {@link ChatModel}. */\n model: ChatModel\n /** Continue this conversation; omit to start a new one. */\n threadId?: string\n}\n\n/** Options for `workflows.chat()`. A workflow's steps run with the models set in the workflow. */\nexport interface WorkflowChatOptions {\n /** @deprecated Ignored: each step of the workflow uses the model set in the workflow. */\n model?: ChatModel\n /** Continue this conversation; omit to start a new one. */\n threadId?: string\n}\n\ninterface ChatRequest {\n readonly path: string\n readonly body: Record<string, unknown>\n readonly sessionId: string\n readonly baseUrl: string\n}\n\nfunction effectiveThreadId(threadId?: string): string | undefined {\n if (threadId === undefined || !threadId.trim()) return undefined\n return threadId\n}\n\nfunction runsPath(target: ChatTarget): string {\n if (target.kind === 'modus') return '/agent/v1/modus/runs'\n return `/agent/v1/${target.kind}/${encodeURIComponent(String(target.id))}/runs`\n}\n\nfunction raiseForEvent(event: RunEvent): RunEvent {\n if (event.type === 'error') throw new ModusError(event.message, { requestId: event.requestId })\n if (event.type === 'cancelled') throw new RunCancelledError()\n if (event.type === 'stream_timeout') throw new StreamTimeoutError()\n return event\n}\n\n/**\n * One chat turn, streamed live from the agent host.\n *\n * Iterate {@link ChatSession.textStream} for tokens as they arrive, or\n * `await` the session for the final {@link ChatResult}. The request is sent\n * once: iterating again, or awaiting after iterating, replays what arrived.\n *\n * @example\n * ```ts\n * const chat = client.scopes.chat(scopeId, 'What is our ARR trend?', { model: 'claude-sonnet-5.5' })\n * for await (const token of chat.textStream()) process.stdout.write(token)\n * const { threadId } = await chat\n * ```\n */\nexport class ChatSession implements PromiseLike<ChatResult> {\n private readonly received: RunEvent[] = []\n private live: AsyncGenerator<RunEvent> | undefined\n private finished = false\n private failure: unknown\n private final: ChatResult | undefined\n private approval: ApprovalRequiredEvent | undefined\n\n /**\n * @internal A session built with `failure` never sends; every read rejects\n * with it, as the promise `chat()` used to return did.\n */\n constructor(\n private readonly http: HttpClient,\n private readonly request: ChatRequest | undefined,\n failure?: unknown,\n ) {\n if (failure !== undefined) {\n this.failure = failure\n this.finished = true\n }\n }\n\n /**\n * The assistant's reply as text chunks, as they arrive. Sub-agent output is\n * left out.\n *\n * @throws {ModusError} When the run reports an error.\n * @throws {RunCancelledError} When the run is cancelled.\n * @throws {StreamTimeoutError} When the run times out.\n */\n async *textStream(): AsyncGenerator<string> {\n // A replay of a protocol-2 stream can hold resets; text before the last one was replaced.\n // ponytail: a reset arriving live after text was yielded cannot be taken back.\n const lastReset = this.received.findLastIndex(\n (event) => event.type === 'assistant_content_reset' && event.subAgent === undefined,\n )\n let index = 0\n for await (const event of this.replay(false)) {\n const at = index++\n if (at < lastReset) continue\n if (at === lastReset && event.type === 'assistant_content_reset') {\n if (event.content) yield event.content\n } else if (event.type === 'token' && event.subAgent === undefined) {\n yield event.content\n }\n }\n }\n\n /**\n * Every run event (tokens, approvals, `done`, …) as it arrives.\n *\n * @throws {ModusError} When the run reports an error.\n * @throws {RunCancelledError} When the run is cancelled.\n * @throws {StreamTimeoutError} When the run times out.\n */\n eventStream(): AsyncGenerator<RunEvent> {\n return this.replay(true)\n }\n\n /**\n * Waits for the run to finish and returns its final answer. `approval` is\n * set when the run stopped for a decision; continue with {@link resume}.\n *\n * @throws {ModusError} When the run reports an error or ends without finishing.\n */\n async result(): Promise<ChatResult> {\n for await (const _event of this.replay(true)) {\n // drain\n }\n if (this.final === undefined) throw new ModusError('Chat stream ended without a done event')\n return this.final\n }\n\n /** Resolve with the final {@link ChatResult}, so the session can be awaited. */\n then<TResult1 = ChatResult, TResult2 = never>(\n onfulfilled?: ((value: ChatResult) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.result().then(onfulfilled, onrejected)\n }\n\n /** Handle a failed run, as on the promise `chat()` used to return. */\n catch<TResult = never>(\n onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,\n ): Promise<ChatResult | TResult> {\n return this.result().catch(onrejected)\n }\n\n /** Run `onfinally` once the run settles, as on the promise `chat()` used to return. */\n finally(onfinally?: (() => void) | null): Promise<ChatResult> {\n return this.result().finally(onfinally)\n }\n\n /**\n * Approve or deny the action this run stopped for, continuing the same\n * conversation.\n *\n * @param input.decision - `approve` or `deny`.\n * @returns A new session for the continued run.\n * @throws {ModusError} When called before the run has finished.\n *\n * @example\n * ```ts\n * const chat = client.modus.chat('Fix the typo in accounts', { model: 'claude-sonnet-5.5' })\n * const first = await chat\n * if (first.approval) {\n * const done = await chat.resume({ decision: 'approve' })\n * }\n * ```\n */\n resume(input: { decision: 'approve' | 'deny' }): ChatSession {\n if (this.final === undefined) {\n throw new ModusError('resume() needs a finished run: await the chat first')\n }\n const { runId, threadId } = this.final\n validateId(runId, 'run_id')\n return new ChatSession(this.http, {\n path: `/agent/v1/runs/${encodeURIComponent(runId)}/resume`,\n body: { sessionId: threadId, decision: input.decision },\n sessionId: threadId,\n baseUrl: this.request!.baseUrl,\n })\n }\n\n /**\n * Stop reading the run and release its connection. Call it when you stop\n * iterating before the run ends; a session that reached `done` has already\n * let go. The run itself keeps going on the server.\n */\n async close(): Promise<void> {\n this.finished = true\n await this.live?.return(undefined)\n }\n\n // ponytail: one consumer at a time; concurrent iterators would race on `live`.\n private async *replay(resetAware: boolean): AsyncGenerator<RunEvent> {\n let index = 0\n while (true) {\n if (index < this.received.length) {\n yield this.received[index++]!\n continue\n }\n if (this.failure !== undefined) throw this.failure\n if (this.finished) return\n this.live ??= this.open(resetAware)\n try {\n const next = await this.live.next()\n if (next.done) {\n this.finished = true\n } else {\n this.received.push(next.value)\n // done is the last event: release the connection now, even if the consumer stops here.\n if (next.value.type === 'done') await this.close()\n }\n } catch (error) {\n this.failure = error\n throw error\n }\n }\n }\n\n private async *open(resetAware: boolean): AsyncGenerator<RunEvent> {\n const request = this.request!\n const body = resetAware ? { ...request.body, streamProtocolVersion: 2 } : request.body\n const lines = this.http.streamPost(request.path, body, { baseUrl: request.baseUrl })\n for await (const event of parseSseStream(lines)) {\n raiseForEvent(event)\n if (event.type === 'approval_required') this.approval = event\n if (event.type === 'done') {\n // Recorded before yielding: a consumer may stop at done and resume().\n this.final = {\n content: event.content ?? '',\n threadId: event.threadId || this.request!.sessionId,\n runId: event.runId,\n ...(this.approval !== undefined ? { approval: this.approval } : {}),\n }\n yield event\n return\n }\n yield event\n }\n }\n}\n\nexport function startChat(\n http: HttpClient,\n config: ModusConfig,\n target: ChatTarget,\n message: string,\n options: ChatOptions | WorkflowChatOptions,\n): ChatSession {\n try {\n return new ChatSession(http, chatRequest(config, target, message, options))\n } catch (error) {\n return new ChatSession(http, undefined, error)\n }\n}\n\nfunction chatRequest(\n config: ModusConfig,\n target: ChatTarget,\n message: string,\n options: ChatOptions | WorkflowChatOptions,\n): ChatRequest {\n if (target.kind !== 'modus') validateId(target.id, `${target.kind.slice(0, -1)}_id`)\n const runsWithOwnModels = target.kind === 'workflows'\n if (!runsWithOwnModels) validateChatModel(options.model)\n const baseUrl = requireAgentHost(config)\n const sessionId = resolveAgentRunSessionId(effectiveThreadId(options.threadId))\n return {\n path: runsPath(target),\n body: {\n message,\n ...(runsWithOwnModels ? {} : { config: { model: options.model } }),\n sessionId,\n ...(config.organizationId !== undefined ? { organizationId: config.organizationId } : {}),\n },\n sessionId,\n baseUrl,\n }\n}\n","import type { components } from '../_generated/v1.js'\n\n/** Canonical public type for a Modus workflow (OpenAPI `WorkflowDto`). */\nexport type Workflow = components['schemas']['WorkflowDto']\n\n/** Runtime + type for workflow kinds (use `WorkflowType.task`, not only as a type). */\nexport const WorkflowType = {\n task: 'task',\n workflow: 'workflow',\n} as const\n\nexport type WorkflowType = (typeof WorkflowType)[keyof typeof WorkflowType]\n\n/** @deprecated Use `Workflow` instead. */\nexport type Agent = Workflow\n/** @deprecated Use `WorkflowType` instead. */\nexport type AgentType = WorkflowType\n/** @deprecated Use `WorkflowType` instead. */\nexport const AgentType = WorkflowType\n","import type { components } from '../_generated/v1.js'\n\nexport type Conversation = components['schemas']['ConversationDto']\nexport type ConversationListItem = components['schemas']['ConversationListItemDto']\nexport type Message = components['schemas']['ConversationMessageDto']\nexport type ConversationKind = 'all' | 'modus' | 'scopes'\n\n/** Scope id for a list item, or undefined for direct Modus chats (scopeId 0). */\nexport function conversationScopeId(item: ConversationListItem): number | undefined {\n return item.scopeId === 0 ? undefined : item.scopeId\n}\n\n/**\n * @deprecated Use `conversationScopeId` instead.\n * Preserves the legacy `0` sentinel for direct Modus chats (unlike\n * `conversationScopeId`, which returns `undefined` for id `0`).\n */\nexport function conversationSkillId(item: ConversationListItem): number | undefined {\n return item.scopeId\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../_config.js'\nimport type { HttpClient } from '../../../_http.js'\nimport { aipListParams, buildAipPage, type Page } from '../../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../../_request.js'\nimport { validatePageSize } from '../../../_validation.js'\nimport type { VariationView } from '../../../types/views.js'\nimport type { Workflow, WorkflowType } from '../../../types/workflows.js'\n\n/** Generated base for the consumption `workflows` resource. */\nexport class WorkflowsResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * List workflows.\n *\n * Returns a paginated page of workflows the caller can at least `use`. Workflows the caller\n * cannot see are filtered out. Pagination uses an opaque token returned in `nextPageToken`.\n *\n * **Requires:** `workflows:read`\n *\n * @param options.pageSize - Items per page. Defaults to 25.\n * @param options.pageToken - Opaque page token from a previous response's `nextPageToken`. Omit\n * for the first page.\n * @param options.search - Case-insensitive substring filter on workflow name.\n * @param options.type - Filter by workflow type.\n * @param options.view - Variation view. `active` reads the deployed version. `draft` reads the\n * latest builder snapshot. `published` reads only a published workflow of type workflow that\n * you can use; tasks are excluded.\n * @param options.includeVariation - Include the requested variation payload (`trigger`,\n * `workflowStructure`, `agentSelection`) on list rows.\n * @returns A page of workflows.\n *\n * @example\n * ```ts\n * for await (const wf of (await client.workflows.list({ search: 'digest' })).autoPagingIter()) {\n * console.log(wf.id, wf.name, wf.status)\n * }\n * ```\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n search?: string\n type?: WorkflowType\n view?: VariationView\n includeVariation?: boolean\n } = {}): Promise<Page<Workflow>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, options.search, options.type, options.view, options.includeVariation)\n }\n\n protected async listPage(\n pageSize: number,\n pageToken: string | undefined,\n search?: string,\n type?: WorkflowType,\n view?: VariationView,\n includeVariation?: boolean,\n ): Promise<Page<Workflow>> {\n const extra: Record<string, string | boolean> = {}\n if (search !== undefined) extra.search = search\n if (type !== undefined) extra.type = type\n if (view !== undefined) extra.view = view\n if (includeVariation !== undefined) extra.includeVariation = includeVariation\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'WorkflowsController_list', {\n query: aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | undefined | null\n >,\n }),\n )\n return buildAipPage(\n data,\n 'workflows',\n (raw) => raw as Workflow,\n (token) => this.listPage(pageSize, token, search, type, view, includeVariation),\n )\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { ModusConfig } from '../../_config.js'\nimport { resolveAgentRunSessionId } from '../../_agent_run_request.js'\nimport { ModusError, ValidationError } from '../../_exceptions.js'\nimport type { OperationId } from '../../_generated/operations.js'\nimport {\n formatOperationPath,\n getOperation,\n operationBaseUrl,\n} from '../../_openapi-invoke.js'\nimport type { HttpClient } from '../../_http.js'\nimport { Page, normalizePageToken } from '../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../_request.js'\nimport { parseSseStream } from '../../_streaming.js'\nimport { validateId, validatePageSize } from '../../_validation.js'\nimport type {\n AgentRun,\n AgentRunListItem,\n AgentRunCreateRequest,\n ApprovalScope,\n CreateAgentRunRequest,\n FollowUpRunRequest,\n ModusRunCreateRequest,\n ResumeRunRequest,\n RunAdmission,\n RunEventsPollResponse,\n RunStatus,\n RunTimeframe,\n SkillRunCreateRequest,\n} from '../../types/agent-runs.js'\nimport type { ActiveConversationRun, RunEvent } from '../../types/runs.js'\n\nconst RUNS_MAX_PAGE_SIZE = 100\n\nfunction runsListParams(\n pageSize: number,\n pageToken: string | undefined,\n status?: RunStatus,\n timeframe?: RunTimeframe,\n approvalScope?: ApprovalScope,\n search?: string,\n): Record<string, string | number | boolean | undefined | null> {\n const params: Record<string, string | number | boolean | undefined | null> = { pageSize }\n const token = normalizePageToken(pageToken)\n if (token !== undefined) params.pageToken = token\n if (status !== undefined) params.status = status\n if (timeframe !== undefined) params.timeframe = timeframe\n if (approvalScope !== undefined) params.approvalScope = approvalScope\n if (search !== undefined) params.search = search\n return params\n}\n\nfunction activeRunsParams(\n pageSize: number,\n pageToken: string | undefined,\n): Record<string, string | number> {\n const params: Record<string, string | number> = { pageSize }\n const token = normalizePageToken(pageToken)\n if (token !== undefined) params.pageToken = token\n return params\n}\n\nfunction parseRun(raw: unknown): AgentRun {\n return raw as AgentRun\n}\n\nfunction parseActiveRunsArray(raw: unknown): ActiveConversationRun[] {\n const data = asRecord(raw)\n const runs = data.runs\n if (!Array.isArray(runs)) {\n throw new ModusError(\n `Unexpected active runs response shape: runs must be a list, got ${typeof runs}.`,\n )\n }\n return runs as ActiveConversationRun[]\n}\n\nfunction parseActiveRunsPage(\n raw: unknown,\n fetchPage: (token: string) => Promise<Page<ActiveConversationRun>>,\n): Page<ActiveConversationRun> {\n const data = asRecord(raw)\n const runs = data.runs\n if (!Array.isArray(runs)) {\n throw new ModusError(\n `Unexpected active runs response shape: runs must be a list, got ${typeof runs}.`,\n )\n }\n return new Page(\n runs as ActiveConversationRun[],\n normalizePageToken(\n typeof data.nextPageToken === 'string' ? data.nextPageToken : undefined,\n ),\n fetchPage,\n )\n}\n\nfunction randomRunId(): string {\n return randomUUID()\n}\n\nfunction sessionIdFromBody(body: { sessionId?: string }): string {\n return resolveAgentRunSessionId(body.sessionId)\n}\n\n/** Interrupt, queue-edit and resume continue an existing conversation, so a sessionId is never minted. */\nfunction requireSessionId(sessionId: string | undefined): void {\n if (!sessionId?.trim()) {\n throw new ValidationError(\"sessionId must be the run's conversation id (a non-empty string)\")\n }\n}\n\nexport interface AgentRunStream extends AsyncIterable<RunEvent> {\n readonly runId: string\n readonly events: AsyncIterable<RunEvent>\n}\n\nexport function makeAgentRunStream(runId: string, events: AsyncIterable<RunEvent>): AgentRunStream {\n return {\n runId,\n events,\n [Symbol.asyncIterator]() {\n return events[Symbol.asyncIterator]()\n },\n }\n}\n\n/**\n * Start, inspect, and control workflow runs.\n *\n * Typical path: `create` (or `createScope` / `createModus`) → stream events →\n * `list` / `get` history → `cancel` or `resume` when needed.\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.create(workflowId, {\n * message: \"Summarize yesterday's sales\",\n * config: { model: 'claude-sonnet-5' },\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\nexport class WorkflowRunsResource {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {}\n\n /**\n * List runs for a workflow.\n *\n * @param workflowId - Numeric workflow id.\n * @param options.pageSize - Maximum items per page (default 25, max 100).\n * @param options.pageToken - Opaque token from a previous page.\n * @param options.status - Filter by run status.\n * @param options.timeframe - Filter by recency (`last_hour`, `last_day`, or `last_week`).\n * @param options.approvalScope - Filter approval-related runs (`mine` or `all`).\n * @param options.search - Free-text search filter.\n * @returns A page of run summaries — use `.autoPagingIter()` for all pages.\n *\n * @example\n * ```ts\n * for await (const run of (\n * await client.workflows.runs.list(workflowId, { status: 'completed' })\n * ).autoPagingIter()) {\n * console.log(run.workflowId, run.status, run.startedAt)\n * }\n * ```\n */\n list(\n workflowId: number | string,\n options: {\n pageSize?: number\n pageToken?: string\n status?: RunStatus\n timeframe?: RunTimeframe\n approvalScope?: ApprovalScope\n search?: string\n } = {},\n ): Promise<Page<AgentRunListItem>> {\n validateId(workflowId, 'workflow_id')\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize, RUNS_MAX_PAGE_SIZE)\n return this.listPage(workflowId, pageSize, options.pageToken, options)\n }\n\n private async listPage(\n workflowId: number | string,\n pageSize: number,\n pageToken: string | undefined,\n filters: {\n status?: RunStatus\n timeframe?: RunTimeframe\n approvalScope?: ApprovalScope\n search?: string\n },\n ): Promise<Page<AgentRunListItem>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'WorkflowRunsController_list', {\n pathParams: { id: workflowId },\n query: runsListParams(\n pageSize,\n pageToken,\n filters.status,\n filters.timeframe,\n filters.approvalScope,\n filters.search,\n ),\n }),\n )\n const runs = data.runs\n if (!Array.isArray(runs)) {\n throw new ModusError(\n `Unexpected list response shape: runs must be a list, got ${typeof runs}.`,\n )\n }\n return new Page(\n runs as AgentRunListItem[],\n normalizePageToken(\n typeof data.nextPageToken === 'string' ? data.nextPageToken : undefined,\n ),\n (token: string) => this.listPage(workflowId, pageSize, token, filters),\n )\n }\n\n /**\n * Retrieve a workflow run by id.\n *\n * @param workflowId - Numeric workflow id the run belongs to.\n * @param runId - Run id (the list row's `workflowId` field, not the composite `id`).\n * @param options.temporalRunId - Optional internal execution id when disambiguating retries.\n * @returns Run details including status and output.\n * @throws {NotFoundError} When the run does not exist.\n *\n * @example\n * ```ts\n * const run = await client.workflows.runs.get(workflowId, runId)\n * console.log(run.status)\n * ```\n */\n async get(\n workflowId: number | string,\n runId: string,\n options: { temporalRunId?: string } = {},\n ): Promise<AgentRun> {\n validateId(workflowId, 'workflow_id')\n if (!runId.trim()) throw new ValidationError('run_id must be a non-empty string')\n const query =\n options.temporalRunId !== undefined\n ? { temporalRunId: options.temporalRunId }\n : undefined\n const data = await invokeWithRetry(this.config, this.http, 'WorkflowRunsController_get', {\n pathParams: { id: workflowId, runId },\n query,\n })\n return parseRun(data)\n }\n\n /**\n * Start a workflow run and stream run events.\n *\n * @param workflowId - Numeric workflow id to run.\n * @param body - Run body (`message`, optional `sessionId`, optional `version` as `published` or `draft`).\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events (tokens, completion, errors, and related signals).\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.create(workflowId, {\n * message: \"Summarize yesterday's sales\",\n * config: { model: 'claude-sonnet-5' },\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * if (event.type === 'done') break\n * }\n * ```\n */\n create(\n workflowId: number | string,\n body: CreateAgentRunRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n validateId(workflowId, 'workflow_id')\n return this.createRun('WorkflowRunsController_create', body, { id: workflowId }, options)\n }\n\n /**\n * Start a scope run and stream run events.\n *\n * Same event stream shape as {@link create}, but targets a published scope.\n *\n * @param scopeId - Scope id to run.\n * @param body - Run body (`message`, optional `sessionId`, optional `version` as `published` or `draft`).\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events.\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.createScope(scopeId, {\n * message: 'What is our ARR trend?',\n * config: { model: 'claude-sonnet-5' },\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\n createScope(\n scopeId: number | string,\n body: SkillRunCreateRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n validateId(scopeId, 'scope_id')\n return this.createRun('ScopeRunsController_create', body, { id: scopeId }, options)\n }\n\n /**\n * Start a Modus org-assistant run and stream run events.\n *\n * @param body - Run body (`message`, optional `sessionId`, optional `subordinateSkillIds` to narrow context).\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events.\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.createModus({\n * message: 'Summarize ARR in three bullets.',\n * config: { model: 'claude-sonnet-5' },\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\n createModus(\n body: ModusRunCreateRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n return this.createRun('ModusRunsController_create', body, {}, options)\n }\n\n /**\n * Resume a run paused at an approval or connect interrupt, and stream the continuation's events.\n *\n * The decision is the whole turn: send no `message` (a non-empty one is rejected).\n *\n * @param runId - Id of the interrupted run.\n * @param body - `sessionId` (the run's conversation id, required) and `decision`\n * (`approve` / `deny` / `connected` / `cancelled`); optional `approvalTarget`.\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events.\n * @throws {ValidationError} When `sessionId` is blank, before any request is sent.\n *\n * @example\n * ```ts\n * const stream = client.workflows.runs.resume(runId, {\n * decision: 'approve',\n * sessionId,\n * })\n * for await (const event of stream) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\n resume(\n runId: string,\n body: ResumeRunRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n validateId(runId, 'run_id')\n requireSessionId(body.sessionId)\n return this.createRun('ResumeRunsController_create', body, { runId }, options)\n }\n\n /**\n * Cancel a run that is still in progress.\n *\n * @param runId - Run id to cancel.\n *\n * @example\n * ```ts\n * await client.workflows.runs.cancel(runId)\n * ```\n */\n async cancel(runId: string): Promise<void> {\n validateId(runId, 'run_id')\n await invokeWithRetry(this.config, this.http, 'RunLifecycleController_cancel', {\n pathParams: { runId },\n jsonBody: {},\n })\n }\n\n /**\n * Poll a run's buffered events once (the JSON transport, not SSE).\n *\n * @param runId - Run id.\n * @returns The poll response: `events` (each with its stream `id` and `type`), `cursor`,\n * `status` and `done`.\n */\n async events(runId: string): Promise<RunEventsPollResponse> {\n validateId(runId, 'run_id')\n return (await invokeWithRetry(this.config, this.http, 'RunLifecycleController_events', {\n pathParams: { runId },\n })) as RunEventsPollResponse\n }\n\n /**\n * Supersede a run's current turn with a follow-up turn.\n *\n * The run is cancelled and `nextRun` starts as a new run on the same conversation.\n * On a run that has already finished nothing is cancelled, and `nextRun` simply\n * starts a follow-up turn. `nextRun.runId` is pinned (a new uuid when you do not\n * set one), so a retried request returns the same run instead of starting another.\n *\n * @param runId - Run id to interrupt.\n * @param nextRun - The follow-up turn: `message` and `sessionId` (the run's conversation id).\n * @param options.lastSeenEventId - Id of the last event you rendered, so the cancelled\n * turn's saved output stops there.\n * @returns The new run (`runId`, `status`); follow it with {@link stream}.\n * @throws {ValidationError} When `nextRun.sessionId` is blank, before any request is sent.\n *\n * @example\n * ```ts\n * const { runId: nextRunId } = await client.workflows.runs.interrupt(runId, {\n * message: 'Only count EMEA.',\n * sessionId,\n * })\n * for await (const event of client.workflows.runs.stream(nextRunId)) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * }\n * ```\n */\n async interrupt(\n runId: string,\n nextRun: FollowUpRunRequest,\n options: { lastSeenEventId?: string } = {},\n ): Promise<RunAdmission> {\n validateId(runId, 'run_id')\n requireSessionId(nextRun.sessionId)\n const jsonBody = {\n nextRun: { ...nextRun, runId: nextRun.runId?.trim() || randomRunId() },\n ...(options.lastSeenEventId ? { lastSeenEventId: options.lastSeenEventId } : {}),\n }\n return (await invokeWithRetry(this.config, this.http, 'RunLifecycleController_interrupt', {\n pathParams: { runId },\n jsonBody,\n })) as RunAdmission\n }\n\n /**\n * Replace the turn of a run that is still queued (not yet started).\n *\n * @param runId - Queued run id.\n * @param nextRun - The replacement turn: `message` and `sessionId` (the run's conversation id).\n * @returns The edited run (`runId`, `status`).\n * @throws {ValidationError} When `nextRun.sessionId` is blank, before any request is sent.\n * @throws {ConflictError} When the run has already started.\n *\n * @example\n * ```ts\n * await client.workflows.runs.editQueued(queuedRunId, {\n * message: 'Summarize last week instead.',\n * sessionId,\n * })\n * ```\n */\n async editQueued(runId: string, nextRun: FollowUpRunRequest): Promise<RunAdmission> {\n validateId(runId, 'run_id')\n requireSessionId(nextRun.sessionId)\n return (await invokeWithRetry(this.config, this.http, 'RunLifecycleController_editQueued', {\n pathParams: { runId },\n jsonBody: { nextRun },\n })) as RunAdmission\n }\n\n /**\n * List active conversation runs across the organization.\n *\n * @param options.pageSize - Maximum items per page (default 50, max 100).\n * @param options.pageToken - Opaque token from a previous page.\n * @returns A page of active runs with session and status metadata.\n */\n active(options: {\n pageSize?: number\n pageToken?: string\n } = {}): Promise<Page<ActiveConversationRun>> {\n const pageSize = options.pageSize ?? 50\n validatePageSize(pageSize, RUNS_MAX_PAGE_SIZE)\n return this.activePage(pageSize, options.pageToken)\n }\n\n private async activePage(\n pageSize: number,\n pageToken: string | undefined,\n ): Promise<Page<ActiveConversationRun>> {\n return parseActiveRunsPage(\n await invokeWithRetry(this.config, this.http, 'RunLifecycleController_active', {\n query: activeRunsParams(pageSize, pageToken),\n }),\n (token: string) => this.activePage(pageSize, token),\n )\n }\n\n /**\n * Look up active runs for specific conversation sessions.\n *\n * @param sessionIds - Up to 100 session ids.\n * @returns Active runs matching any of the given sessions.\n * @throws {ValidationError} When more than 100 session ids are provided.\n */\n async activeBySession(sessionIds: readonly string[]): Promise<ActiveConversationRun[]> {\n const uniqueSessionIds = [...new Set(sessionIds.map((id) => id.trim()).filter(Boolean))]\n if (uniqueSessionIds.length > 100) {\n throw new ValidationError('sessionIds must contain at most 100 ids')\n }\n return parseActiveRunsArray(\n await invokeWithRetry(this.config, this.http, 'RunLifecycleController_activeBySession', {\n jsonBody: { sessionIds: uniqueSessionIds },\n }),\n )\n }\n\n /**\n * Reconnect to a run and stream its events.\n *\n * @param runId - Run id to follow.\n * @param options.lastEventId - The `id` of the last event you handled; the stream resumes\n * after it. Omit to replay the run from its first event.\n * @returns A stream of run events.\n *\n * @example\n * ```ts\n * let lastEventId: string | undefined\n * for await (const event of client.workflows.runs.stream(runId, { lastEventId })) {\n * if (event.type === 'token') process.stdout.write(event.content)\n * lastEventId = event.id // after handling it: reconnect with it if the connection drops\n * }\n * ```\n */\n stream(runId: string, options: { lastEventId?: string } = {}): AgentRunStream {\n validateId(runId, 'run_id')\n const op = getOperation('RunLifecycleController_stream')\n const path = formatOperationPath('RunLifecycleController_stream', { runId })\n const lines = this.http.streamGet(path, undefined, {\n baseUrl: operationBaseUrl(this.http, op),\n headers: options.lastEventId ? { 'Last-Event-ID': options.lastEventId } : undefined,\n })\n return makeAgentRunStream(runId, this.parseEvents(lines))\n }\n\n private createRun(\n operationId: OperationId,\n body: AgentRunCreateRequest | SkillRunCreateRequest | ModusRunCreateRequest | ResumeRunRequest,\n pathParams: Record<string, unknown>,\n options: { idempotencyKey?: string },\n ): AgentRunStream {\n const runId = options.idempotencyKey?.trim() || body.runId?.trim() || randomRunId()\n const sessionId = sessionIdFromBody(body as { sessionId?: string })\n const op = getOperation(operationId)\n const path = formatOperationPath(operationId, pathParams)\n const lines = this.http.streamPost(path, {\n ...body,\n sessionId,\n streamProtocolVersion: 2,\n }, {\n baseUrl: operationBaseUrl(this.http, op),\n headers: { 'Idempotency-Key': runId },\n })\n return makeAgentRunStream(runId, this.parseEvents(lines))\n }\n\n private async *parseEvents(lines: AsyncIterable<string>): AsyncGenerator<RunEvent> {\n yield* parseSseStream(lines)\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { ModusConfig } from '../../_config.js'\nimport {\n formatOperationPath,\n getOperation,\n operationBaseUrl,\n} from '../../_openapi-invoke.js'\nimport type { HttpClient } from '../../_http.js'\nimport { invokeWithRetry } from '../../_request.js'\nimport { parseSseStream } from '../../_streaming.js'\nimport { validateId } from '../../_validation.js'\nimport type { WorkflowActionRequest } from '../../types/agent-runs.js'\nimport type { RunEvent } from '../../types/runs.js'\nimport { makeAgentRunStream, type AgentRunStream } from './runs.js'\n\nfunction randomRunId(): string {\n return randomUUID()\n}\n\nexport class AgentWorkflowActionsResource {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {}\n\n /**\n * Execute a workflow action and stream run events.\n *\n * @param body - Action body (`organizationId`, `sessionId`, `workflowAction`, optional `previousOutputs`).\n * @param options.idempotencyKey - Client-supplied idempotency key; defaults to `body.runId` or a new uuid.\n * @returns A stream of run events for the action execution.\n */\n execute(\n body: WorkflowActionRequest,\n options: { idempotencyKey?: string } = {},\n ): AgentRunStream {\n const runId = options.idempotencyKey?.trim() || body.runId?.trim() || randomRunId()\n const op = getOperation('WorkflowActionsController_execute')\n const path = formatOperationPath('WorkflowActionsController_execute')\n const lines = this.http.streamPost(path, body, {\n baseUrl: operationBaseUrl(this.http, op),\n headers: { 'Idempotency-Key': runId },\n })\n return makeAgentRunStream(runId, this.parseEvents(lines))\n }\n\n /**\n * Cancel a workflow action run.\n *\n * @param runId - Action run id to cancel.\n */\n async cancel(runId: string): Promise<void> {\n validateId(runId, 'run_id')\n await invokeWithRetry(this.config, this.http, 'WorkflowActionsController_cancel', {\n pathParams: { runId },\n jsonBody: {},\n })\n }\n\n private async *parseEvents(lines: AsyncIterable<string>): AsyncGenerator<RunEvent> {\n yield* parseSseStream(lines)\n }\n}\n","import { WorkflowsResourceBase } from '../_generated/resources/consumption/workflows.js'\nimport type { ModusConfig } from '../_config.js'\nimport type { HttpClient } from '../_http.js'\nimport { startChat, type ChatSession, type WorkflowChatOptions } from '../_chat.js'\nimport { invokeWithRetry } from '../_request.js'\nimport { validateId } from '../_validation.js'\nimport type { Workflow } from '../types/workflows.js'\nimport type { VariationView } from '../types/views.js'\nimport { WorkflowRunsResource } from './workflows/runs.js'\nimport { AgentWorkflowActionsResource } from './workflows/workflow-actions.js'\n\nfunction parseWorkflow(raw: unknown): Workflow {\n return raw as Workflow\n}\n\n/**\n * Read and run access to Modus workflows.\n *\n * - `list` / `get` — browse workflows (`view: 'active'`, `'draft'`, or `'published'`)\n * - `chat` — send a workflow a message and stream its reply\n * - {@link WorkflowRunsResource runs} — start, monitor, and control workflow runs\n * - {@link AgentWorkflowActionsResource workflowActions} — execute workflow actions\n *\n * @example\n * ```ts\n * import { Modus } from '@getmodus/sdk'\n * const client = new Modus()\n * for await (const wf of (await client.workflows.list()).autoPagingIter()) {\n * console.log(wf.id, wf.name, wf.status)\n * }\n * ```\n */\nexport class WorkflowsResource extends WorkflowsResourceBase {\n readonly runs: WorkflowRunsResource\n readonly workflowActions: AgentWorkflowActionsResource\n\n /** @internal */\n constructor(\n http: HttpClient,\n config: ModusConfig,\n ) {\n super(http, config)\n this.runs = new WorkflowRunsResource(http, config)\n this.workflowActions = new AgentWorkflowActionsResource(http, config)\n }\n\n /**\n * Retrieve a workflow by its numeric id.\n *\n * @param workflowId - Numeric workflow id.\n * @param options.view - Which saved version to return (`active` or `draft`).\n * @param options.includeVariation - Include variation metadata when supported.\n * @returns The workflow (`id`, `name`, `status`, …).\n * @throws {NotFoundError} When no workflow has this id.\n *\n * @example\n * ```ts\n * const [first] = (await client.workflows.list()).items\n * const wf = await client.workflows.get(first.id)\n * console.log(wf.name, wf.status)\n * ```\n */\n async get(\n workflowId: number | string,\n options: { view?: VariationView; includeVariation?: boolean } = {},\n ): Promise<Workflow> {\n validateId(workflowId, 'workflow_id')\n const query: Record<string, string | boolean> = {}\n if (options.view !== undefined) query.view = options.view\n if (options.includeVariation !== undefined) {\n query.includeVariation = options.includeVariation\n }\n const data = await invokeWithRetry(this.config, this.http, 'WorkflowsController_get', {\n pathParams: { id: workflowId },\n query: Object.keys(query).length > 0 ? query : undefined,\n })\n return parseWorkflow(data)\n }\n\n /**\n * Run a published workflow and stream its node output live from the agent\n * host: iterate `textStream()` for tokens, or `await` the result for the\n * workflow's final output. Call it with no message to trigger a run with no input.\n *\n * @param workflowId - Numeric workflow id.\n * @param message - The run's input; omit it for a run with no input.\n * @param options.threadId - Continue an existing conversation; omit to start new.\n * @param options.model - Deprecated and ignored: each step uses the model set in the workflow.\n * @returns A chat session — iterate it or `await` it for `content`, `threadId`, `runId`.\n * @throws {ModusError} When no agent host is known for a custom `baseUrl`.\n *\n * @example\n * ```ts\n * const { content } = await client.workflows.chat(workflowId)\n * const digest = await client.workflows.chat(workflowId, \"Run this week's digest\")\n * console.log(content, digest.content)\n * ```\n */\n chat(workflowId: number | string, message = '', options: WorkflowChatOptions = {}): ChatSession {\n return startChat(this.http, this.config, { kind: 'workflows', id: workflowId }, message, options)\n }\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../_config.js'\nimport type { HttpClient } from '../../../_http.js'\nimport { aipListParams, buildAipPage, type Page } from '../../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../../_request.js'\nimport { validatePageSize } from '../../../_validation.js'\nimport type { Connection } from '../../../types/connections.js'\n\n/** Generated base for the consumption `connections` resource. */\nexport class ConnectionsResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * List connections.\n *\n * Returns a paginated page of warehouse and SaaS integration connections the caller can `use`.\n * Connections the caller cannot access are filtered out. Use the returned `id` when creating\n * saved-query context items. Pagination uses an opaque token returned in `nextPageToken`.\n *\n * **Requires:** `context:read`\n *\n * @param options.pageSize - Items per page. Defaults to 25.\n * @param options.pageToken - Opaque page token from a previous response's `nextPageToken`. Omit\n * for the first page.\n * @param options.type - Filter by effective integration category (case-sensitive exact match).\n * @returns A page of connections.\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n type?: string\n } = {}): Promise<Page<Connection>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, options.type)\n }\n\n protected async listPage(\n pageSize: number,\n pageToken: string | undefined,\n type?: string,\n ): Promise<Page<Connection>> {\n const extra: Record<string, string> = {}\n if (type !== undefined) extra.type = type\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ConnectionsController_list', {\n query: aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | undefined | null\n >,\n }),\n )\n return buildAipPage(\n data,\n 'connections',\n (raw) => raw as Connection,\n (token) => this.listPage(pageSize, token, type),\n )\n }\n}\n","import { ConnectionsResourceBase } from '../_generated/resources/consumption/connections.js'\nimport { aipListParams, buildAipPage, type Page } from '../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../_request.js'\nimport { validateId, validatePageSize } from '../_validation.js'\nimport type { Connection, ConnectionSelection } from '../types/connections.js'\n\n/**\n * Read access to integration connections.\n */\nexport class ConnectionsResource extends ConnectionsResourceBase {\n /**\n * Find the first connection whose name matches (case-insensitive).\n *\n * Pages through {@link ConnectionsResource.list} until a match is found.\n *\n * @param options.name - Connection name to search for.\n * @param options.type - Optional integration category filter.\n * @param options.pageSize - Page size when scanning (default 25).\n * @returns The matching connection, or `undefined` if none is found.\n */\n async find(options: {\n name: string\n type?: string\n pageSize?: number\n }): Promise<Connection | undefined> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n const target = options.name.trim().toLowerCase()\n let token: string | undefined\n do {\n const page = await this.listPage(pageSize, token, options.type)\n const match = page.items.find((c) => c.name?.toLowerCase() === target)\n if (match) return match\n if (!page.hasNextPage()) break\n token = page.nextPageToken\n } while (token !== undefined)\n return undefined\n }\n\n /**\n * List the selectable units on a connection (a repository, a schema, a project).\n *\n * @param connectionId - Connection id.\n * @param options.pageSize - Maximum items per page (default 25).\n * @param options.pageToken - Opaque token from a previous page.\n * @returns A page of selectable units — use {@link iterSelections} or `.autoPagingIter()` for every page.\n * @example\n * for await (const unit of client.connections.iterSelections('7a3f9d2c-1111-4000-a000-000000000abc')) {\n * console.log(unit.objectType, unit.path)\n * }\n */\n listSelections(\n connectionId: string,\n options: { pageSize?: number; pageToken?: string } = {},\n ): Promise<Page<ConnectionSelection>> {\n validateId(connectionId, 'connection_id')\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listSelectionsPage(connectionId, pageSize, options.pageToken)\n }\n\n private async listSelectionsPage(\n connectionId: string,\n pageSize: number,\n pageToken: string | undefined,\n ): Promise<Page<ConnectionSelection>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ConnectionsController_listSelections', {\n pathParams: { connectionId },\n query: aipListParams(pageSize, pageToken) as Record<\n string,\n string | number | boolean | undefined | null\n >,\n }),\n )\n return buildAipPage(\n data,\n 'selections',\n (raw) => raw as ConnectionSelection,\n (token) => this.listSelectionsPage(connectionId, pageSize, token),\n )\n }\n\n /**\n * Yield every selectable unit on a connection, following pages.\n *\n * @param connectionId - Connection id.\n * @param options.pageSize - Maximum items per page (default 25).\n * @example\n * for await (const unit of client.connections.iterSelections('7a3f9d2c-1111-4000-a000-000000000abc')) {\n * console.log(unit.objectType, unit.displayName)\n * }\n */\n async *iterSelections(\n connectionId: string,\n options: { pageSize?: number } = {},\n ): AsyncGenerator<ConnectionSelection> {\n const page = await this.listSelections(connectionId, options)\n yield* page.autoPagingIter()\n }\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../../_config.js'\nimport type { HttpClient } from '../../../../_http.js'\nimport { invokeWithRetry, omitUndefined } from '../../../../_request.js'\nimport type { ContextItemsQuery, ContextItemsQueryResult } from '../../../../types/context.js'\n\n/** Generated base for the consumption `context.items` resource. */\nexport class ContextItemsResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * Query context items with SQL.\n *\n * Runs one read-only SQL statement over the `context_items` table and returns its rows. The query\n * sees only the items you can read. A query that is not read-only or not valid returns 400; one\n * that runs past 20 s returns 422.\n *\n * **Requires:** `context:read`\n *\n * @param query - Request body; see `ContextItemsQuery`.\n *\n * @example\n * ```ts\n * const result = await modus.context.items.query({\n * sql: 'SELECT context_type, count(*) AS items FROM context_items GROUP BY context_type',\n * })\n * result.rows\n * ```\n */\n async query(query: ContextItemsQuery): Promise<ContextItemsQueryResult> {\n const data = await invokeWithRetry(this.config, this.http, 'ContextItemsQueryController_query', {\n jsonBody: omitUndefined(query as Record<string, unknown>),\n })\n return data as ContextItemsQueryResult\n }\n}\n","import { ContextItemsResourceBase } from '../../_generated/resources/consumption/context/items.js'\nimport { NotFoundError } from '../../_exceptions.js'\nimport { aipListParams, buildAipPage, type Page } from '../../_pagination.js'\nimport { asRecord, invokeWithRetry, omitUndefined } from '../../_request.js'\nimport { DEFAULT_MAX_PAGE_SIZE, validatePageSize } from '../../_validation.js'\nimport type { ContextItem, ContextItemLookupRow } from '../../types/context.js'\nimport type { ContextValueRow } from '../../types/context-values.js'\nimport type { ContentProjection, JsonObjectInput } from '../../types/json-blob.js'\n\nfunction contextListParams(\n pageSize: number,\n pageToken: string | undefined,\n filters: ListContextItemsFilters = {},\n): Record<string, string | number | boolean | readonly string[] | undefined | null> {\n const extra: Record<string, string | readonly string[]> = {}\n if (filters.contextType !== undefined) extra.contextTypes = [filters.contextType]\n if (filters.parentUids !== undefined) {\n extra.parentUids = filters.parentUids.length === 0 ? '' : [...filters.parentUids]\n }\n if (filters.ancestorUids !== undefined) {\n extra.ancestorUids = filters.ancestorUids.length === 0 ? '' : [...filters.ancestorUids]\n }\n if (filters.connectionIds !== undefined) {\n extra.connectionIds = filters.connectionIds.length === 0 ? '' : [...filters.connectionIds]\n }\n return aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | readonly string[] | undefined | null\n >\n}\n\ntype ListContextItemsFilters = {\n contextType?: string\n parentUids?: readonly string[]\n ancestorUids?: readonly string[]\n connectionIds?: readonly string[]\n}\n\nfunction parseContextItem(raw: unknown): ContextItem {\n return raw as ContextItem\n}\n\nfunction parseContextValueRow(raw: unknown): ContextValueRow {\n return raw as ContextValueRow\n}\n\nfunction parseLookupResponse(raw: Record<string, unknown>): ContextItemLookupRow | undefined {\n const item = raw.item\n if (item === null || item === undefined) return undefined\n return item as ContextItemLookupRow\n}\n\n/**\n * Read the org knowledge base (notes, metrics, saved queries, integration items).\n *\n * Use `client.context.items` after `new Modus()`. Prefer `list` / `get` /\n * `lookup` for discovery; use `listValues` when a field holds a large array\n * inside `content`.\n *\n * @example\n * ```ts\n * import { Modus } from '@getmodus/sdk'\n * const client = new Modus()\n * for await (const item of (await client.context.items.list({ pageSize: 25 })).autoPagingIter()) {\n * console.log(item.contextType, item.description ?? item.uid)\n * }\n * ```\n */\nexport class ContextItemsResource extends ContextItemsResourceBase {\n /**\n * List knowledge-base items.\n *\n * @param options.pageSize - Maximum items per page (default 25).\n * @param options.pageToken - Opaque token from a previous page.\n * @param options.contextType - Filter to a single context type (e.g. `\"note\"`).\n * @param options.parentUids - Exact ordered native ancestry chain for direct\n * children. Omit to leave parent unrestricted; pass `[]` for the known-empty\n * root. Native UIDs are exact tokens (including whitespace); do not use the\n * hashed context-item `uid`. For a folder's children, send that item's\n * `ancestry` UIDs plus its last `dataPath` token.\n * @param options.ancestorUids - Ordered UID ancestry prefix for strict\n * descendants. Omit to leave unrestricted; pass `[]` for every item with\n * non-null ancestry.\n * @param options.connectionIds - Restrict to these connection ids. Omit to\n * leave unfiltered; pass `[]` to match none. The Files root is\n * `connectionIds: ['files']` with `parentUids: []`.\n * @returns A page of context items — use `.autoPagingIter()` for all pages.\n *\n * @example\n * ```ts\n * const notes = await client.context.items.list({ contextType: 'note', pageSize: 50 })\n * for (const item of notes.items) {\n * console.log(item.description ?? item.uid, item.uid)\n * }\n * ```\n *\n * @example\n * ```ts\n * const rootFolders = await client.context.items.list({\n * connectionIds: ['files'],\n * contextType: 'file_folder_metadata',\n * parentUids: [],\n * })\n * const folder = rootFolders.items[0]\n * const nativeUid = folder?.dataPath?.at(-1)\n * // Known ancestry only — never treat null/omitted ancestry as a root chain.\n * if (folder?.ancestry != null && nativeUid !== undefined) {\n * const filesInFolder = await client.context.items.list({\n * connectionIds: ['files'],\n * contextType: 'file_upload',\n * parentUids: [...folder.ancestry.map((a) => a.uid), nativeUid],\n * })\n * }\n * ```\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n contextType?: string\n parentUids?: readonly string[]\n ancestorUids?: readonly string[]\n connectionIds?: readonly string[]\n } = {}): Promise<Page<ContextItem>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, {\n contextType: options.contextType,\n parentUids: options.parentUids,\n ancestorUids: options.ancestorUids,\n connectionIds: options.connectionIds,\n })\n }\n\n private async listPage(\n pageSize: number,\n pageToken: string | undefined,\n filters: ListContextItemsFilters,\n ): Promise<Page<ContextItem>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ContextItemsController_list', {\n query: contextListParams(pageSize, pageToken, filters),\n }),\n )\n return buildAipPage(data, 'contextItems', parseContextItem, (token) =>\n this.listPage(pageSize, token, filters),\n )\n }\n\n /**\n * Retrieve a knowledge-base item by uid.\n *\n * @param uid - Item uid.\n * @returns The context item (`uid`, `contextType`, `content`, …).\n * @throws {NotFoundError} When no item matches the uid.\n *\n * @example\n * ```ts\n * const item = await client.context.items.get(uid)\n * console.log(item.contextType, item.description ?? item.uid)\n * ```\n */\n async get(uid: string): Promise<ContextItem> {\n const data = await invokeWithRetry(this.config, this.http, 'ContextItemsController_get', {\n pathParams: { uid },\n })\n return parseContextItem(data)\n }\n\n /**\n * Look up a knowledge-base item by type and data path.\n *\n * @param options.contextType - Context type to match (e.g. `\"note\"`).\n * @param options.dataPath - Hierarchical path segments that identify the item.\n * @param options.contentProjection - Optional fields to include from item content.\n * @returns The matching row, or `undefined` when no item is found (404).\n *\n * @example\n * ```ts\n * const found = await client.context.items.lookup({\n * contextType: 'note',\n * dataPath: ['finance', 'arr-definition'],\n * })\n * if (found) console.log(found.uid, found.content)\n * ```\n */\n async lookup(options: {\n contextType: string\n dataPath: string[]\n contentProjection?: JsonObjectInput | ContentProjection\n }): Promise<ContextItemLookupRow | undefined> {\n const body = omitUndefined({\n contextType: options.contextType,\n dataPath: options.dataPath,\n contentProjection: options.contentProjection,\n })\n try {\n const raw = asRecord(\n await invokeWithRetry(this.config, this.http, 'ContextItemsController_lookup', {\n jsonBody: body,\n }),\n )\n return parseLookupResponse(raw)\n } catch (error) {\n if (error instanceof NotFoundError) return undefined\n throw error\n }\n }\n\n /**\n * Page through the elements of an array field inside one context item's content.\n *\n * Each row is `{ index, value }`: the element's position in the array and the\n * element itself. A field that is not an array reads as one element; a missing\n * field as none. Rejects with a not-found error when the item does not exist,\n * you cannot read it, or its context type is not `contextType`.\n *\n * @param uid - Item uid.\n * @param contextType - Context type of the item.\n * @param contentKeyPath - Dot path to the array inside item content (e.g. `\"enumValues\"`).\n * @param options.pageSize - Maximum elements per page (default 25).\n * @param options.pageToken - Opaque token from a previous page of the same item.\n * @returns A page of `{ index, value }` rows.\n *\n * @example\n * ```ts\n * // Replace PLACEHOLDER_UID with a real uid whose content has enumValues.\n * const page = await client.context.items.listValues(\n * 'PLACEHOLDER_UID',\n * 'table_column',\n * 'enumValues',\n * { pageSize: 25 },\n * )\n * for (const row of page.items) console.log(row.index, row.value)\n * ```\n */\n listValues(\n uid: string,\n contextType: string,\n contentKeyPath: string,\n options: { pageSize?: number; pageToken?: string } = {},\n ): Promise<Page<ContextValueRow>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize, DEFAULT_MAX_PAGE_SIZE)\n return this.listValuesPage(uid, contextType, contentKeyPath, pageSize, options.pageToken)\n }\n\n /**\n * Page through an array field of a context item already loaded via {@link ContextItemsResource.list} or {@link ContextItemsResource.get}.\n *\n * @param item - Context item (uses `item.uid` and `item.contextType`).\n * @param contentKeyPath - Dot path to the array inside item content.\n * @param options.pageSize - Maximum elements per page (default 25).\n * @param options.pageToken - Opaque token from a previous page of the same item.\n * @returns A page of `{ index, value }` rows.\n *\n * @example\n * ```ts\n * // Replace PLACEHOLDER_UID with a real uid that has enumValues in content.\n * const item = await client.context.items.get('PLACEHOLDER_UID')\n * const page = await client.context.items.listValuesFor(item, 'enumValues')\n * for (const row of page.items) console.log(row)\n * ```\n */\n listValuesFor(\n item: ContextItem,\n contentKeyPath: string,\n options: { pageSize?: number; pageToken?: string } = {},\n ): Promise<Page<ContextValueRow>> {\n return this.listValues(item.uid, item.contextType, contentKeyPath, options)\n }\n\n private async listValuesPage(\n uid: string,\n contextType: string,\n contentKeyPath: string,\n pageSize: number,\n pageToken: string | undefined,\n ): Promise<Page<ContextValueRow>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ContextItemsController_listValues', {\n pathParams: { uid },\n query: aipListParams(pageSize, pageToken, {\n contextType,\n contentKeyPath,\n }) as Record<string, string | number | boolean | undefined | null>,\n }),\n )\n return buildAipPage(data, 'values', parseContextValueRow, (token) =>\n this.listValuesPage(uid, contextType, contentKeyPath, pageSize, token),\n )\n }\n}\n","import type { ModusConfig } from '../../_config.js'\nimport type { HttpClient } from '../../_http.js'\nimport { CustomContextItemsResource } from './custom-items.js'\nimport { ContextItemsResource } from './items.js'\n\n/**\n * Read access to the Modus knowledge base.\n *\n * - {@link ContextItemsResource items} — list and look up indexed knowledge-base items.\n * - {@link CustomContextItemsResource customItems} — create and manage custom context items.\n *\n * Call path: `client.context` after `new Modus(...)`.\n */\nexport class ContextResource {\n readonly items: ContextItemsResource\n readonly customItems: CustomContextItemsResource\n\n /** @internal */\n constructor(http: HttpClient, config: ModusConfig) {\n this.items = new ContextItemsResource(http, config)\n this.customItems = new CustomContextItemsResource(http, config)\n }\n}\n","import type { ModusConfig } from '../_config.js'\nimport type { HttpClient } from '../_http.js'\nimport { invokeWithRetry } from '../_request.js'\nimport type {\n IngestedDataUploadResult,\n UploadIngestedDataOptions,\n} from '../types/ingested-data.js'\n\n/** Store exact integration requests and responses as immutable ingested data. */\nexport class IngestedDataResource {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {}\n\n /**\n * Store a complete SQL or HTTP request and response exactly once.\n *\n * Identity covers the complete organization, integration, request, and response\n * content. A duplicate raises `ConflictError`, which means the identical payload\n * is already stored and may be treated as a safe retry outcome.\n *\n * @param options.integrationType - Canonical Modus integration identifier.\n * @param options.request - Exact SQL or HTTP request that produced the response.\n * @param options.response - Response format, optional source HTTP status, and exact string content. SQL requires CSV.\n * @returns The checksum of the stored envelope.\n * @throws {ConflictError} When the complete payload is already stored.\n *\n * @example\n * ```ts\n * const stored = await client.ingestedData.upload({\n * integrationType: 'generic',\n * request: { type: 'sql', query: 'SELECT id, total FROM orders' },\n * response: { format: 'csv', content: 'id,total\\n1,42.00\\n' },\n * })\n * console.log(stored.checksum)\n * ```\n */\n async upload(options: UploadIngestedDataOptions): Promise<IngestedDataUploadResult> {\n const data = await invokeWithRetry(this.config, this.http, 'IngestedDataController_upload', {\n jsonBody: {\n integration_type: options.integrationType,\n request: options.request,\n response: options.response,\n },\n })\n return data as IngestedDataUploadResult\n }\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../../_config.js'\nimport type { HttpClient } from '../../../../_http.js'\nimport { invokeWithRetry } from '../../../../_request.js'\nimport { validateId } from '../../../../_validation.js'\nimport type { Conversation } from '../../../../types/conversations.js'\n\n/** Generated base for the consumption `modus.conversations` resource. */\nexport class ModusConversationsResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * Get a Modus conversation.\n *\n * Returns the full message history for a conversation thread.\n *\n * **Requires:** `scopes:read`\n *\n * @param threadId - Thread id from a conversation list or chat response.\n */\n async get(threadId: string): Promise<Conversation> {\n validateId(threadId, 'thread_id')\n const data = await invokeWithRetry(this.config, this.http, 'ModusConversationsController_get', {\n pathParams: { threadId },\n })\n return data as Conversation\n }\n}\n","import { ValidationError } from '../../_exceptions.js'\nimport type { ModusConfig } from '../../_config.js'\nimport { ModusConversationsResourceBase } from '../../_generated/resources/consumption/modus/conversations.js'\nimport type { HttpClient } from '../../_http.js'\nimport { aipListParams, buildAipPage, type Page } from '../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../_request.js'\nimport { validatePageSize } from '../../_validation.js'\nimport type {\n ConversationKind,\n ConversationListItem,\n} from '../../types/conversations.js'\n\nconst ALLOWED_KINDS = new Set<ConversationKind>(['all', 'modus', 'scopes'])\n\nfunction listParams(\n pageSize: number,\n pageToken: string | undefined,\n kind?: ConversationKind,\n source?: string,\n sourceRef?: string,\n): Record<string, string | number | boolean | undefined | null> {\n if (kind !== undefined && !ALLOWED_KINDS.has(kind)) {\n throw new ValidationError(\n `kind must be one of ${[...ALLOWED_KINDS].sort().join(', ')}, got ${JSON.stringify(kind)}`,\n )\n }\n const extra: Record<string, string> = {}\n if (kind !== undefined) extra.kind = kind\n if (source !== undefined) extra.source = source\n if (sourceRef !== undefined) extra.sourceRef = sourceRef\n return aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | undefined | null\n >\n}\n\nfunction parseListItem(raw: unknown): ConversationListItem {\n return raw as ConversationListItem\n}\n\n/** List and retrieve Modus / scope conversations. */\nexport class ModusConversationsResource extends ModusConversationsResourceBase {\n constructor(\n http: HttpClient,\n config: ModusConfig,\n ) {\n super(http, config)\n }\n\n /**\n * List conversations.\n *\n * @param options.pageSize - Items per page (default 25).\n * @param options.pageToken - Opaque token from a previous page.\n * @param options.kind - `\"modus\"`, `\"scopes\"`, or `\"all\"`.\n * @param options.source - Restrict to conversations started from this UI surface\n * (e.g. `\"context_chat\"`, `\"dashboard_copilot\"`, `\"slack\"`). Only valid with an\n * omitted `kind` or `kind: \"all\"`; the API throws an `UnprocessableError` (422)\n * if combined with `kind: \"modus\"` or `kind: \"scopes\"`.\n * @param options.sourceRef - Narrow `source` to one instance of that surface — for\n * `\"dashboard_copilot\"`, a dashboard id. Requires `source`; the API throws an\n * `UnprocessableError` (422) if sent on its own. Conversations recorded before\n * this filter shipped carry no instance key and never match it.\n * @returns Page of conversation list items.\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n kind?: ConversationKind\n source?: string\n sourceRef?: string\n } = {}): Promise<Page<ConversationListItem>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, options.kind, options.source, options.sourceRef)\n }\n\n private async listPage(\n pageSize: number,\n pageToken: string | undefined,\n kind?: ConversationKind,\n source?: string,\n sourceRef?: string,\n ): Promise<Page<ConversationListItem>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ModusConversationsController_list', {\n query: listParams(pageSize, pageToken, kind, source, sourceRef),\n }),\n )\n return buildAipPage(data, 'conversations', parseListItem, (token) =>\n this.listPage(pageSize, token, kind, source, sourceRef),\n )\n }\n}\n","import { startChat, type ChatOptions, type ChatSession } from '../../_chat.js'\nimport type { ModusConfig } from '../../_config.js'\nimport type { HttpClient } from '../../_http.js'\nimport { invokeWithRetry, omitUndefined } from '../../_request.js'\nimport type { ModusContextComposition } from '../../types/context-compose.js'\n\nimport { ModusConversationsResource } from './conversations.js'\n\n/**\n * Org-wide Modus assistant (full environment context and tools).\n *\n * Prefer `client.modus` over `client.scopes` when the question is not tied to one\n * published scope. Construct with `new Modus()` (reads `MODUS_API_KEY`).\n *\n * - `chat` — stream a reply live, or `await` it for the complete answer\n * - `getContext` — preview composed context without a chat turn\n * - `conversations` — list/get prior Modus threads\n *\n * @example\n * ```ts\n * import { Modus } from '@getmodus/sdk'\n * const client = new Modus()\n * const result = await client.modus.chat('What tables describe revenue?', {\n * model: 'claude-sonnet-5',\n * })\n * console.log(result.content, result.threadId)\n * ```\n */\nexport class ModusResource {\n readonly conversations: ModusConversationsResource\n\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {\n this.conversations = new ModusConversationsResource(http, config)\n }\n\n /**\n * Compose full-environment context for an intent without running chat.\n *\n * Runs on the agent host, like `chat`, so a compose may take up to 90 seconds; keep `timeoutMs`\n * above that. A compose still running at 90 seconds fails with `UPSTREAM_TIMEOUT` (504).\n *\n * @param message - Natural-language intent used to select context.\n * @param options.limit - Maximum context items to return. Omit to return all selected items.\n * @returns Composition metadata (counts / session id). Use `chat` for a reply.\n *\n * @example\n * ```ts\n * const ctx = await client.modus.getContext('What tables describe revenue?', { limit: 5 })\n * console.log(ctx.originalCount, ctx.sessionId)\n * ```\n */\n async getContext(\n message: string,\n options: { limit?: number } = {},\n ): Promise<ModusContextComposition> {\n const data = await invokeWithRetry(this.config, this.http, 'ModusContextComposeController_compose', {\n jsonBody: omitUndefined({ message, limit: options.limit }),\n })\n return data as ModusContextComposition\n }\n\n /**\n * Chat with Modus, the org-wide assistant. The reply streams live from the\n * agent host: iterate `textStream()` for tokens, or `await` the result for\n * the final answer. Pass the returned `threadId` back to continue.\n *\n * @param message - User message text.\n * @param options.model - Required model id (e.g. `\"claude-sonnet-5.5\"`).\n * @param options.threadId - Continue an existing conversation; omit to start new.\n * @returns A chat session — iterate it or `await` it for `content`, `threadId`, `runId`.\n * @throws {ModusError} When no agent host is known for a custom `baseUrl`.\n *\n * @example\n * ```ts\n * const result = await client.modus.chat('What tables describe revenue?', {\n * model: 'claude-sonnet-5.5',\n * })\n * console.log(result.content)\n * const follow = client.modus.chat('Break that down by region.', {\n * model: 'claude-sonnet-5.5',\n * threadId: result.threadId,\n * })\n * for await (const token of follow.textStream()) process.stdout.write(token)\n * ```\n */\n chat(message: string, options: ChatOptions): ChatSession {\n return startChat(this.http, this.config, { kind: 'modus' }, message, options)\n }\n}\n","// Auto-generated resource bases. Do not edit by hand.\n\nimport type { ModusConfig } from '../../../_config.js'\nimport type { HttpClient } from '../../../_http.js'\nimport { aipListParams, buildAipPage, type Page } from '../../../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../../../_request.js'\nimport { validateId, validatePageSize } from '../../../_validation.js'\nimport type { Scope } from '../../../types/scopes.js'\nimport type { VariationView } from '../../../types/views.js'\n\n/** Generated base for the consumption `scopes` resource. */\nexport class ScopesResourceBase {\n /** @internal */\n constructor(\n protected readonly http: HttpClient,\n protected readonly config: ModusConfig,\n ) {}\n\n /**\n * List scopes.\n *\n * Returns a paginated page of scopes the caller can at least `use`. Scopes the caller cannot see\n * are filtered out. Pagination uses an opaque token returned in `nextPageToken`.\n *\n * **Requires:** `scopes:read`\n *\n * @param options.pageSize - Items per page. Defaults to 25.\n * @param options.pageToken - Opaque page token from a previous response's `nextPageToken`. Omit\n * for the first page.\n * @param options.search - Case-insensitive substring filter on scope name.\n * @param options.view - Variation view. `active` reads the deployed version, or the latest draft\n * when nothing is published. `draft` reads the latest builder snapshot. `published` reads only\n * the published version, and only scopes you can use.\n * @param options.managerId - Return only scopes supervised by this manager scope id.\n * @returns A page of scopes.\n *\n * @example\n * ```ts\n * for await (const scope of (await client.scopes.list()).autoPagingIter()) {\n * console.log(scope.id, scope.name, scope.status)\n * }\n * ```\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n search?: string\n view?: VariationView\n managerId?: number\n } = {}): Promise<Page<Scope>> {\n const pageSize = options.pageSize ?? 25\n validatePageSize(pageSize)\n return this.listPage(pageSize, options.pageToken, options.search, options.view, options.managerId)\n }\n\n protected async listPage(\n pageSize: number,\n pageToken: string | undefined,\n search?: string,\n view?: VariationView,\n managerId?: number,\n ): Promise<Page<Scope>> {\n const extra: Record<string, string | number> = {}\n if (search !== undefined) extra.search = search\n if (view !== undefined) extra.view = view\n if (managerId !== undefined) extra.managerId = managerId\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'ScopesController_list', {\n query: aipListParams(pageSize, pageToken, extra) as Record<\n string,\n string | number | boolean | undefined | null\n >,\n }),\n )\n return buildAipPage(\n data,\n 'scopes',\n (raw) => raw as Scope,\n (token) => this.listPage(pageSize, token, search, view, managerId),\n )\n }\n\n /**\n * Get a scope.\n *\n * Returns a scope. `view=active` (default) is the deployed version, or the latest draft when\n * nothing is published. `view=draft` is the latest edits. `view=published` is only the published\n * version, and only if you can use the scope. Returns 404 if you cannot access it.\n *\n * **Requires:** `scopes:read`\n *\n * @param scopeId - Numeric scope id.\n * @param options.view - Which version to read. Defaults to `active`. `published` is only the\n * published version, and only if you can use the scope.\n *\n * @example\n * ```ts\n * const [first] = (await client.scopes.list()).items\n * const scope = await client.scopes.get(first.id)\n * console.log(scope.name, scope.status)\n * ```\n */\n async get(\n scopeId: number | string,\n options: { view?: VariationView } = {},\n ): Promise<Scope> {\n validateId(scopeId, 'scope_id')\n const data = await invokeWithRetry(this.config, this.http, 'ScopesController_get', {\n pathParams: { id: scopeId },\n query: { view: options.view },\n })\n return data as Scope\n }\n}\n","import { ScopesResourceBase } from '../_generated/resources/consumption/scopes.js'\nimport { startChat, type ChatOptions, type ChatSession } from '../_chat.js'\nimport { invokeWithRetry, omitUndefined } from '../_request.js'\nimport { validateId } from '../_validation.js'\nimport type { SkillContextComposition } from '../types/context-compose.js'\nimport { ScopeConversationsResource } from './scopes/conversations.js'\n\n/**\n * Read / chat with published scopes.\n *\n * Call path: `client.scopes` after `new Modus(...)`. Prefer `client.modus` for\n * the org-wide assistant. Create/deploy via `ModusManagement`.\n *\n * @example\n * ```ts\n * const [scope] = (await client.scopes.list()).items\n * const result = await client.scopes.chat(scope.id, 'What is our ARR trend?', {\n * model: 'claude-sonnet-5',\n * })\n * console.log(result.content, result.threadId)\n * ```\n */\nexport class ScopesResource extends ScopesResourceBase {\n\n /**\n * Return the conversations sub-resource scoped to `scopeId`.\n *\n * @param scopeId - Numeric scope id.\n * @returns Conversations resource for the scope.\n *\n * @example\n * ```ts\n * for await (const row of (\n * await client.scopes.conversations(scopeId).list({ pageSize: 10 })\n * ).autoPagingIter()) {\n * console.log(row.threadId, row.firstMessage)\n * }\n * ```\n */\n conversations(scopeId: number | string): ScopeConversationsResource {\n return new ScopeConversationsResource(this.http, this.config, scopeId)\n }\n\n /**\n * Compose context this scope would use for an intent, without running chat.\n *\n * Large bodies are bounded inline previews. This REST method does not expose file references\n * or a full-content fetch operation. Runs on the agent host, like `chat`, so a compose may take\n * up to 90 seconds; keep `timeoutMs` above that. A compose still running at 90 seconds fails\n * with `UPSTREAM_TIMEOUT` (504).\n *\n * @param scopeId - Numeric scope id.\n * @param message - Natural-language intent used to select context.\n * @param options.limit - Maximum context items to return. Omit to return all selected items.\n * @returns Composed context text plus selection counts, item UIDs, and correlation session id.\n *\n * @example\n * ```ts\n * const ctx = await client.scopes.getContext(scopeId, 'Which tables describe churn?', {\n * limit: 5,\n * })\n * console.log(ctx.originalCount, ctx.sessionId)\n * ```\n */\n async getContext(\n scopeId: number | string,\n message: string,\n options: { limit?: number } = {},\n ): Promise<SkillContextComposition> {\n validateId(scopeId, 'scope_id')\n const data = await invokeWithRetry(this.config, this.http, 'ScopeContextComposeController_compose', {\n pathParams: { id: scopeId },\n jsonBody: omitUndefined({ message, limit: options.limit }),\n })\n return data as SkillContextComposition\n }\n\n /**\n * Chat with a published scope. The reply streams live from the agent host:\n * iterate `textStream()` for tokens, or `await` the result for the final\n * answer. Pass the returned `threadId` back to continue the conversation.\n *\n * For the org-wide assistant use `client.modus.chat` instead.\n *\n * @param scopeId - Numeric scope id (must be active for chat).\n * @param message - User message text.\n * @param options.model - Required model id (e.g. `\"claude-sonnet-5.5\"`).\n * @param options.threadId - Continue an existing conversation; omit to start new.\n * @returns A chat session — iterate it or `await` it for `content`, `threadId`, `runId`.\n * @throws {ModusError} When no agent host is known for a custom `baseUrl`.\n *\n * @example\n * ```ts\n * const chat = client.scopes.chat(scopeId, 'What is our ARR trend?', { model: 'claude-sonnet-5.5' })\n * for await (const token of chat.textStream()) process.stdout.write(token)\n * const { threadId } = await chat\n * const follow = await client.scopes.chat(scopeId, 'Break that down by segment.', {\n * model: 'claude-sonnet-5.5',\n * threadId,\n * })\n * console.log(follow.content)\n * ```\n */\n chat(scopeId: number | string, message: string, options: ChatOptions): ChatSession {\n return startChat(this.http, this.config, { kind: 'scopes', id: scopeId }, message, options)\n }\n}\n","import type { ModusConfig } from '../_config.js'\nimport type { HttpClient } from '../_http.js'\nimport { buildAipPage, type Page } from '../_pagination.js'\nimport { asRecord, invokeWithRetry } from '../_request.js'\nimport { ValidationError } from '../_exceptions.js'\nimport { validateId, validatePageSize } from '../_validation.js'\nimport {\n type RecordSuggestionEventRequest,\n type SuggestionQuestion,\n} from '../types/suggestions.js'\n\nconst DEFAULT_SUGGESTIONS_PAGE_SIZE = 5\nconst MAX_SUGGESTIONS_PAGE_SIZE = 12\n\nfunction parseSuggestion(raw: unknown): SuggestionQuestion {\n return raw as SuggestionQuestion\n}\n\nfunction suggestionListParams(options: {\n pageSize: number\n pageToken?: string\n scopeId?: number\n scopeIds?: readonly number[]\n}): Record<string, string | number | undefined> {\n return {\n pageSize: options.pageSize,\n pageToken: options.pageToken,\n scopeId: options.scopeId,\n scopeIds: options.scopeIds?.join(','),\n }\n}\n\n/**\n * List suggested questions and record suggestion events.\n */\nexport class SuggestionsResource {\n /** @internal */\n constructor(\n private readonly http: HttpClient,\n private readonly config: ModusConfig,\n ) {}\n\n /**\n * List approved suggested questions.\n *\n * @param options.pageSize - Maximum items per page (default 5, max 12).\n * @param options.pageToken - Opaque token from a previous page.\n * @param options.scopeId - Filter to a single scope.\n * @param options.scopeIds - Filter to one or more scopes. An empty list throws; omit it for every scope.\n * @returns A page of suggested questions.\n */\n list(options: {\n pageSize?: number\n pageToken?: string\n scopeId?: number\n scopeIds?: readonly number[]\n } = {}): Promise<Page<SuggestionQuestion>> {\n const pageSize = options.pageSize ?? DEFAULT_SUGGESTIONS_PAGE_SIZE\n validatePageSize(pageSize, MAX_SUGGESTIONS_PAGE_SIZE)\n if (options.scopeIds?.length === 0) {\n throw new ValidationError('scopeIds requires at least one id; omit it to list suggestions for every scope')\n }\n return this.listPage(pageSize, options.pageToken, options.scopeId, options.scopeIds)\n }\n\n private async listPage(\n pageSize: number,\n pageToken: string | undefined,\n scopeId: number | undefined,\n scopeIds: readonly number[] | undefined,\n ): Promise<Page<SuggestionQuestion>> {\n const data = asRecord(\n await invokeWithRetry(this.config, this.http, 'SuggestionsController_listApproved', {\n query: suggestionListParams({ pageSize, pageToken, scopeId, scopeIds }),\n }),\n )\n return buildAipPage(data, 'suggestions', parseSuggestion, (token) =>\n this.listPage(pageSize, token, scopeId, scopeIds),\n )\n }\n\n /**\n * Record that a suggested question was shown, clicked, dismissed, or submitted.\n *\n * @param id - Suggestion id.\n * @param event - Event details, including `eventType` (`shown`, `clicked`, `dismissed`, or `submitted`).\n */\n async recordEvent(id: string, event: RecordSuggestionEventRequest): Promise<void> {\n validateId(id, 'id')\n await invokeWithRetry(this.config, this.http, 'SuggestionsController_recordEvent', {\n pathParams: { id },\n jsonBody: event,\n })\n }\n}\n","/**\n * @getmodus/sdk — official TypeScript client for Modus.\n */\n\nexport type { components, paths, operations } from './_generated/v1.js'\nexport type { OperationId, OperationSpec } from './_generated/operations.js'\nexport { OPERATIONS } from './_generated/operations.js'\n\nexport {\n APIConnectionError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n InternalServerError,\n ModusError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n RunCancelledError,\n StreamTimeoutError,\n UnprocessableError,\n ValidationError,\n} from './_exceptions.js'\n\nexport { ChatSession } from './_chat.js'\nexport type { ChatOptions, WorkflowChatOptions } from './_chat.js'\nexport { Page } from './_pagination.js'\nexport type {\n AssistantContentResetEvent,\n CancelledEvent,\n DoneEvent,\n ErrorEvent,\n RunEvent,\n ApprovalRequiredEvent,\n RunEventBase,\n StreamTimeoutEvent,\n TokenEvent,\n} from './types/runs.js'\nexport type { ChatModel, ChatResult } from './types/chat.js'\nexport type { ModusOptions } from './_config.js'\nexport type { Scope, ScopeStatus, ScopeVariation, Skill, SkillStatus, SkillVariation } from './types/scopes.js'\nexport type { Workflow, Agent } from './types/workflows.js'\nexport { AgentType, WorkflowType } from './types/workflows.js'\nexport type {\n AgentRun,\n AgentRunCreateRequest,\n AgentRunListItem,\n ApprovalScope,\n CancelRunRequest,\n CreateAgentRunRequest,\n EditQueuedRunRequest,\n FollowUpRunRequest,\n InterruptRunRequest,\n ModusRunCreateRequest,\n ResumeRunRequest,\n RunAdmission,\n RunStatus,\n RunTimeframe,\n SkillRunCreateRequest,\n WorkflowActionRequest,\n} from './types/agent-runs.js'\nexport type { AgentRunStream } from './resources/workflows/runs.js'\nexport type {\n Conversation,\n ConversationKind,\n ConversationListItem,\n Message,\n} from './types/conversations.js'\nexport { conversationScopeId, conversationSkillId } from './types/conversations.js'\nexport type { Connection, ConnectionSelection } from './types/connections.js'\nexport type { SupervisionView, VariationView } from './types/views.js'\nexport type {\n ContextItem,\n ContextItemAncestor,\n ContextItemDeletion,\n ContextItemLookupRow,\n ContextItemsQuery,\n ContextItemsQueryResult,\n ContextItemMove,\n ContextItemAccessUpdate,\n UpdateContextItemAccessInput,\n ContextType,\n} from './types/context.js'\nexport type { ContextValueRow } from './types/context-values.js'\nexport type {\n ComposeSkillContextRequest,\n ModusContextComposition,\n ModusContextRequest,\n SkillContextComposition,\n} from './types/context-compose.js'\nexport type {\n RecordSuggestionEventRequest,\n SuggestionEventSource,\n SuggestionEventType,\n SuggestionQuestion,\n} from './types/suggestions.js'\nexport type {\n HttpIngestedDataRequest,\n IngestedDataRequest,\n IngestedDataResponse,\n IngestedDataResponseFormat,\n IngestedDataUploadResult,\n SqlIngestedDataRequest,\n UploadIngestedDataOptions,\n} from './types/ingested-data.js'\n\nexport type { ModusConfig } from './_config.js'\nexport type { ActiveConversationRun, ActiveConversationRunStatus } from './types/runs.js'\nexport type { RunEventsPollResponse } from './types/agent-runs.js'\nexport type { ContentProjection, JsonObjectInput } from './types/json-blob.js'\nexport type {\n BatchDeleteCustomContextItemsInput,\n BatchDeleteCustomContextItemsResult,\n CreateCustomContextItemInput,\n CreatedCustomContextItem,\n CustomAttributeInput,\n CustomContextItemDeletion,\n CustomContextItemKind,\n CustomContextItemRelationInput,\n UpdateCustomContextItemInput,\n} from './resources/context/custom-items.js'\nexport type { ScopesResource } from './resources/scopes.js'\nexport type { ScopeConversationsResource } from './resources/scopes/conversations.js'\nexport type { ModusResource } from './resources/modus/modus.js'\nexport type { ModusConversationsResource } from './resources/modus/conversations.js'\nexport type { WorkflowsResource } from './resources/workflows.js'\nexport type { WorkflowRunsResource } from './resources/workflows/runs.js'\nexport type { AgentWorkflowActionsResource } from './resources/workflows/workflow-actions.js'\nexport type { ContextResource } from './resources/context/context.js'\nexport type { ContextItemsResource } from './resources/context/items.js'\nexport type { CustomContextItemsResource } from './resources/context/custom-items.js'\nexport type { ConnectionsResource } from './resources/connections.js'\nexport type { SuggestionsResource } from './resources/suggestions.js'\nexport type { IngestedDataResource } from './resources/ingested-data.js'\n\nimport { ModusClientBase } from './_client-base.js'\nimport { WorkflowsResource } from './resources/workflows.js'\nimport { ConnectionsResource } from './resources/connections.js'\nimport { ContextResource } from './resources/context/context.js'\nimport { IngestedDataResource } from './resources/ingested-data.js'\nimport { ModusResource } from './resources/modus/modus.js'\nimport { ScopesResource } from './resources/scopes.js'\nimport { SuggestionsResource } from './resources/suggestions.js'\n\n/**\n * Read / invoke client for Modus scopes, workflows, connections, and more.\n *\n * Call path: `const client = new Modus(...)` then `client.scopes`, `client.context`, …\n *\n * @param options - Client configuration (`apiKey`, `baseUrl`, `timeoutMs`, `maxRetries`).\n */\nexport class Modus extends ModusClientBase {\n readonly scopes: ScopesResource\n readonly modus: ModusResource\n readonly workflows: WorkflowsResource\n readonly context: ContextResource\n readonly connections: ConnectionsResource\n readonly suggestions: SuggestionsResource\n readonly ingestedData: IngestedDataResource\n\n constructor(options: import('./_config.js').ModusOptions = {}) {\n super(options)\n this.scopes = new ScopesResource(this.http, this.config)\n this.modus = new ModusResource(this.http, this.config)\n this.workflows = new WorkflowsResource(this.http, this.config)\n this.context = new ContextResource(this.http, this.config)\n this.connections = new ConnectionsResource(this.http, this.config)\n this.suggestions = new SuggestionsResource(this.http, this.config)\n this.ingestedData = new IngestedDataResource(this.http, this.config)\n }\n}\n"]}