@alquimia-ai/tools 2.7.0 → 2.8.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.
Files changed (63) hide show
  1. package/README.md +88 -12
  2. package/dist/actions/index.d.mts +1 -1
  3. package/dist/actions/index.d.ts +1 -1
  4. package/dist/adapters/fetch.d.mts +1 -0
  5. package/dist/adapters/fetch.d.ts +1 -0
  6. package/dist/adapters/fetch.js +4 -0
  7. package/dist/adapters/fetch.js.map +1 -1
  8. package/dist/adapters/fetch.mjs +4 -0
  9. package/dist/adapters/fetch.mjs.map +1 -1
  10. package/dist/adapters/index.d.mts +1 -0
  11. package/dist/adapters/index.d.ts +1 -0
  12. package/dist/adapters/index.js.map +1 -1
  13. package/dist/adapters/next.d.mts +1 -0
  14. package/dist/adapters/next.d.ts +1 -0
  15. package/dist/adapters/next.js +4 -0
  16. package/dist/adapters/next.js.map +1 -1
  17. package/dist/adapters/next.mjs +4 -0
  18. package/dist/adapters/next.mjs.map +1 -1
  19. package/dist/approvals-CcnmqUkQ.d.ts +59 -0
  20. package/dist/approvals-dn4sd_Ot.d.mts +59 -0
  21. package/dist/hooks/index.d.mts +36 -5
  22. package/dist/hooks/index.d.ts +36 -5
  23. package/dist/hooks/index.js +208 -12
  24. package/dist/hooks/index.js.map +1 -1
  25. package/dist/hooks/index.mjs +208 -12
  26. package/dist/hooks/index.mjs.map +1 -1
  27. package/dist/next/index.d.mts +7 -0
  28. package/dist/next/index.d.ts +7 -0
  29. package/dist/next/index.js +56 -40
  30. package/dist/next/index.js.map +1 -1
  31. package/dist/next/index.mjs +56 -40
  32. package/dist/next/index.mjs.map +1 -1
  33. package/dist/providers/index.d.mts +3 -3
  34. package/dist/providers/index.d.ts +3 -3
  35. package/dist/{providers-mx21gNgZ.d.ts → providers-J_Z9rQ3Q.d.ts} +1 -1
  36. package/dist/{providers-B4IOiGfr.d.mts → providers-YKiEag2L.d.mts} +1 -1
  37. package/dist/proxy.d.mts +2 -0
  38. package/dist/proxy.d.ts +2 -0
  39. package/dist/proxy.js +47 -40
  40. package/dist/proxy.js.map +1 -1
  41. package/dist/proxy.mjs +47 -40
  42. package/dist/proxy.mjs.map +1 -1
  43. package/dist/sdk/index.d.mts +25 -3
  44. package/dist/sdk/index.d.ts +25 -3
  45. package/dist/sdk/index.js +73 -10
  46. package/dist/sdk/index.js.map +1 -1
  47. package/dist/sdk/index.mjs +73 -10
  48. package/dist/sdk/index.mjs.map +1 -1
  49. package/dist/services/index.d.mts +1 -1
  50. package/dist/services/index.d.ts +1 -1
  51. package/dist/{type-D-JaSMkV.d.ts → type-BFtGEEb4.d.ts} +1 -1
  52. package/dist/{type-61gaZga-.d.mts → type-C_sKpIM1.d.mts} +1 -1
  53. package/dist/types/index.d.mts +23 -2
  54. package/dist/types/index.d.ts +23 -2
  55. package/dist/utils/index.d.mts +1 -1
  56. package/dist/utils/index.d.ts +1 -1
  57. package/dist/worklog/index.d.mts +1 -0
  58. package/dist/worklog/index.d.ts +1 -0
  59. package/dist/worklog/index.js +75 -2
  60. package/dist/worklog/index.js.map +1 -1
  61. package/dist/worklog/index.mjs +75 -2
  62. package/dist/worklog/index.mjs.map +1 -1
  63. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sdk/index.ts","../../src/sdk/alquimia-sdk.ts"],"sourcesContent":["export { default as AlquimiaSDK } from './alquimia-sdk';","import axios, { AxiosInstance } from 'axios';\nimport {\n StableDiffusionProvider,\n WhisperProvider,\n CharacterizationProvider,\n RatingsProvider,\n LoggerProvider,\n} from '../providers';\nimport {\n AttachmentPayload,\n TTSResult,\n type CommonAttributes,\n type Content,\n type RuntimeBlob,\n} from '../types';\nimport type { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters';\nimport type { ToolExecutionResponse } from '../genui/types';\n\n/** Per-turn options for {@link AlquimiaSDK.sendMessage}. */\nexport interface SendMessageOptions {\n /** W3C traceparent, so infer and stream share one trace. */\n traceParent?: string;\n /**\n * Audio input for this turn (runtime v0.5.1). Upload it with\n * {@link AlquimiaSDK.uploadAttachment} first and pass the blob it returns.\n * May be sent with or instead of `query`.\n */\n inputAudio?: RuntimeBlob;\n /**\n * Set to `false` to force a text-only reply from an audio-enabled agent.\n * The runtime defaults to `true`, so leaving this unset keeps its behaviour.\n */\n outputAudio?: boolean;\n}\n\nclass AlquimiaSDK {\n private adapter: AlquimiaAdapter;\n private assistantId: string;\n private axiosInstance: AxiosInstance;\n private conversationId: string | null = null;\n private sessionId: string | null = null;\n // Internal subscription id from infer (`taskid` on the wire).\n private streamId: string | null = null;\n // W3C traceparent for the current turn, so infer and stream share one trace.\n private traceParent: string | null = null;\n // Registry version tag resolved by the runtime for this task (v0.5.1), so\n // the tool-completion half of the turn lands on the same agentspace version.\n private versionTag: string | null = null;\n private tools: any = [];\n private extraInstructions: Record<string, string> | null = null;\n private assistantConfig: any = null;\n private userId: string | null = null;\n private whisperProvider?: WhisperProvider;\n private stableDiffusionProvider?: StableDiffusionProvider;\n private analyzeCharacterizationProvider?: CharacterizationProvider;\n private ratingsProvider?: RatingsProvider;\n private loggerProvider?: LoggerProvider;\n private enforceCharacterization?: boolean;\n private attachments: AttachmentPayload[] = [];\n private attachmentResponses: string[] = [];\n\n constructor(\n assistantId: string,\n adapter: AlquimiaAdapter,\n options: AlquimiaSDKOptions = {}\n ) {\n if (!assistantId) {\n throw new Error('AlquimiaSDK: assistantId is required');\n }\n if (!adapter) {\n throw new Error(\n 'AlquimiaSDK: adapter is required. Use createNextJsAdapter() or createFetchAdapter()'\n );\n }\n\n this.assistantId = assistantId;\n this.adapter = adapter;\n this.enforceCharacterization = options.enforceCharacterization ?? true;\n\n this.axiosInstance = axios.create();\n this.axiosInstance.interceptors.response.use(\n (response) => response,\n async (error) => {\n if (error.response?.status && this.loggerProvider) {\n await this.loggerProvider.logError('Server Error', error, {\n url: error.config.url,\n method: error.config.method,\n data: error.config.data,\n status: error.response.status,\n responseData: error.response.data,\n });\n }\n return Promise.reject(error);\n }\n );\n\n this.textToSpeech = this.textToSpeech.bind(this);\n this.speechToText = this.speechToText.bind(this);\n }\n\n withConversationId(conversationId: string): AlquimiaSDK {\n this.conversationId = conversationId;\n return this;\n }\n\n withAttachments(attachments: AttachmentPayload[]): AlquimiaSDK {\n this.attachments = attachments;\n return this;\n }\n\n withWhisperProvider(provider: WhisperProvider): AlquimiaSDK {\n this.whisperProvider = provider;\n return this;\n }\n\n withStableDiffusionProvider(provider: StableDiffusionProvider): AlquimiaSDK {\n this.stableDiffusionProvider = provider;\n return this;\n }\n\n withAnalyzeCharacterizationProvider(provider: CharacterizationProvider): AlquimiaSDK {\n this.analyzeCharacterizationProvider = provider;\n return this;\n }\n\n withRatingsProvider(provider: RatingsProvider): AlquimiaSDK {\n this.ratingsProvider = provider;\n return this;\n }\n\n withLoggerProvider(provider: LoggerProvider): AlquimiaSDK {\n this.loggerProvider = provider;\n return this;\n }\n\n withTools(tools: any): AlquimiaSDK {\n this.tools = tools;\n return this;\n }\n\n withExtraInstructions(extraInstructions: Record<string, string>): AlquimiaSDK {\n this.extraInstructions = extraInstructions;\n return this;\n }\n\n withAssistantConfig(assistantConfig: any): AlquimiaSDK {\n this.assistantConfig = assistantConfig;\n return this;\n }\n\n withUserId(userId: string): AlquimiaSDK {\n this.userId = userId;\n return this;\n }\n\n /**\n * Pin inference to a cached registry version. Sent as the `version_tag`\n * query parameter, which `POST /event/infer/{assistant_id}` accepts from\n * **runtime v0.5.2** onward; older runtimes ignore it.\n *\n * Works on every version: pass a versioned assistant ref\n * (`<agentspace>/<assistant>[:<tag>]`) as the `assistantId` instead — the\n * runtime parses the tag out of the path itself.\n */\n withVersionTag(versionTag: string): AlquimiaSDK {\n this.versionTag = versionTag;\n return this;\n }\n\n getEnforceCharacterization(): boolean {\n return this.enforceCharacterization ?? true;\n }\n\n textToSpeech(text: string): Promise<TTSResult> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.textToSpeech(text);\n }\n\n speechToText(audio: string): Promise<string> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.speechToText(audio);\n }\n\n async sendMessage(\n query?: Content,\n options: string | SendMessageOptions = {}\n ): Promise<AlquimiaSDK> {\n if (!this.conversationId) {\n throw new Error(\n 'Conversation not initialized. Call withConversationId() before sendMessage()'\n );\n }\n\n // Backwards-compat: the previous signature was sendMessage(query, traceParent?).\n const opts: SendMessageOptions =\n typeof options === 'string' ? { traceParent: options } : options;\n\n if (query === undefined && !opts.inputAudio) {\n throw new Error(\n 'AlquimiaSDK: sendMessage needs a query, an inputAudio blob, or both'\n );\n }\n\n const baseInferUrl = this.adapter.resolveInferUrl(this.assistantId);\n // `version_tag` is a query parameter on infer (runtime v0.5.2+), never a\n // header — the runtime reads it with `Query(...)`.\n const inferUrl = this.versionTag\n ? `${baseInferUrl}${baseInferUrl.includes('?') ? '&' : '?'}version_tag=${encodeURIComponent(this.versionTag)}`\n : baseInferUrl;\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const hasClientTools = Array.isArray(this.tools) && this.tools.length > 0;\n\n const initMessage: Record<string, unknown> = {\n ...(query !== undefined && { query }),\n session_id: this.conversationId,\n user_id: this.userId,\n ...(opts.inputAudio && { input_audio: opts.inputAudio }),\n // Only sent when set: the runtime defaults `output_audio` to true.\n ...(opts.outputAudio !== undefined && { output_audio: opts.outputAudio }),\n ...(this.extraInstructions && { extra_instructions: this.extraInstructions }),\n ...(this.assistantConfig && { config: this.assistantConfig }),\n ...(hasClientTools && {\n evaluation_strategy: {\n evaluation_strategy_id: 'native',\n tool_schemas: this.tools,\n },\n }),\n };\n\n const result = (\n await this.axiosInstance.post(inferUrl, initMessage, {\n headers: {\n 'Content-Type': 'application/json',\n ...(opts.traceParent && { 'x-trace-parent': opts.traceParent }),\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n })\n ).data as CommonAttributes;\n\n this.traceParent = opts.traceParent ?? null;\n this.streamId = result.taskid ?? null;\n this.versionTag = result.versiontag ?? this.versionTag;\n this.attachmentResponses = result.attachments ?? [];\n this.attachments = [];\n\n return this;\n }\n\n /**\n * Complete a pending client-tool execution (the missing \"submit half\" of the\n * client-tool loop). POSTs a {@link ToolExecutionResponse} to the runtime's\n * `/event/tool-completion`. For interactive `render_ui` surfaces `result` is\n * the user's data; for display-only surfaces the SDK sends `{ shown: true }`.\n * The pending call is correlated by `control_id` in the body + the\n * `context-metadata` header (taskid + sessionid).\n */\n async submitToolResult(response: ToolExecutionResponse): Promise<void> {\n const url = this.adapter.resolveToolCompletionUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)'\n );\n }\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n assistantid: this.assistantId,\n ...(this.streamId && { taskid: this.streamId }),\n ...(this.conversationId && { sessionid: this.conversationId }),\n ...(this.userId && { userid: this.userId }),\n ...(this.versionTag && { versiontag: this.versionTag }),\n ...adapterHeaders,\n };\n await this.axiosInstance.post(url, response, { headers });\n }\n\n async generateImage(query: string): Promise<string> {\n if (!this.stableDiffusionProvider) {\n throw new Error('Stable Diffusion provider not initialized');\n }\n return this.stableDiffusionProvider.generateImage(query);\n }\n\n async analyzeCharacterization(text: string): Promise<Record<string, any>> {\n if (!this.analyzeCharacterizationProvider) {\n throw new Error('Analyze characterization provider not initialized');\n }\n return this.analyzeCharacterizationProvider.analyzeCharacterization(text);\n }\n\n async rate(data: any): Promise<Record<string, any>> {\n if (!this.ratingsProvider) {\n throw new Error('Ratings provider not initialized');\n }\n return this.ratingsProvider.rate(data);\n }\n\n async logInfo(message: string, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logInfo(message, data);\n }\n\n async logError(message: string, error: Error, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logError(message, error, data);\n }\n\n /**\n * @deprecated The runtime no longer returns attachment IDs from the infer\n * response — attachments are uploaded as standalone blobs and linked to the\n * session via headers. Always returns `[]`; kept for source compatibility.\n */\n getAttachmentResponses(): string[] {\n return this.attachmentResponses;\n }\n\n /**\n * Upload a file into the session context. Returns the runtime {@link RuntimeBlob},\n * which is what `sendMessage`'s `inputAudio` expects for audio inference.\n */\n async uploadAttachment(file: File, _attachmentId?: string): Promise<RuntimeBlob> {\n void _attachmentId;\n const url = this.adapter.resolveBlobUploadUrl();\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n const formData = new FormData();\n formData.append('file', file);\n const response = await this.axiosInstance.post(url, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n });\n return response.data as RuntimeBlob;\n }\n\n /**\n * Identity headers (kebab-case) required by `/context/blob/upload` and\n * the rest of the runtime's internal endpoints introduced in v0.2.0→next.\n */\n private buildIdentityHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'assistant-id': this.assistantId,\n };\n if (this.conversationId) headers['session-id'] = this.conversationId;\n if (this.userId) headers['user-id'] = this.userId;\n if (this.streamId) headers['task-id'] = this.streamId;\n return headers;\n }\n\n getUrlStream(): string {\n if (!this.streamId) {\n throw new Error('Stream ID not initialized. Call sendMessage() first');\n }\n\n const url = this.adapter.resolveStreamUrl(this.streamId);\n if (!this.traceParent) return url;\n\n // `EventSource` cannot set request headers, so the turn's traceparent rides\n // the URL. The proxy turns it back into `x-trace-parent` and does not pass\n // the param upstream; without this the stream leg — where the whole\n // inference actually happens — lands in a different trace than the infer.\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}trace_parent=${encodeURIComponent(this.traceParent)}`;\n }\n\n getStreamId(): string | null {\n return this.streamId;\n }\n\n /** Alias for {@link getStreamId} — same value as infer `taskid`. */\n getTaskId(): string | null {\n return this.streamId;\n }\n\n /** Registry version tag resolved by the runtime for the current task, if any. */\n getVersionTag(): string | null {\n return this.versionTag;\n }\n}\n\nexport default AlquimiaSDK;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAqC;AAmCrC,IAAM,cAAN,MAAkB;AAAA,EA0BhB,YACE,aACA,SACA,UAA8B,CAAC,GAC/B;AA1BF,SAAQ,iBAAgC;AACxC,SAAQ,YAA2B;AAEnC;AAAA,SAAQ,WAA0B;AAElC;AAAA,SAAQ,cAA6B;AAGrC;AAAA;AAAA,SAAQ,aAA4B;AACpC,SAAQ,QAAa,CAAC;AACtB,SAAQ,oBAAmD;AAC3D,SAAQ,kBAAuB;AAC/B,SAAQ,SAAwB;AAOhC,SAAQ,cAAmC,CAAC;AAC5C,SAAQ,sBAAgC,CAAC;AAOvC,QAAI,CAAC,aAAa;AAChB,YAAM,IAAI,MAAM,sCAAsC;AAAA,IACxD;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,cAAc;AACnB,SAAK,UAAU;AACf,SAAK,0BAA0B,QAAQ,2BAA2B;AAElE,SAAK,gBAAgB,aAAAA,QAAM,OAAO;AAClC,SAAK,cAAc,aAAa,SAAS;AAAA,MACvC,CAAC,aAAa;AAAA,MACd,OAAO,UAAU;AACf,YAAI,MAAM,UAAU,UAAU,KAAK,gBAAgB;AACjD,gBAAM,KAAK,eAAe,SAAS,gBAAgB,OAAO;AAAA,YACxD,KAAK,MAAM,OAAO;AAAA,YAClB,QAAQ,MAAM,OAAO;AAAA,YACrB,MAAM,MAAM,OAAO;AAAA,YACnB,QAAQ,MAAM,SAAS;AAAA,YACvB,cAAc,MAAM,SAAS;AAAA,UAC/B,CAAC;AAAA,QACH;AACA,eAAO,QAAQ,OAAO,KAAK;AAAA,MAC7B;AAAA,IACF;AAEA,SAAK,eAAe,KAAK,aAAa,KAAK,IAAI;AAC/C,SA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QAAI,KAAK,OAAQ,SAAQ,SAAS,IAAI,KAAK;AAC3C,QAAI,KAAK,SAAU,SAAQ,SAAS,IAAI,KAAK;AAC7C,WAAO;AAAA,EACT;AAAA,EAEA,eAAuB;AACrB,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,qDAAqD;AAAA,IACvE;AAEA,UAAM,MAAM,KAAK,QAAQ,iBAAiB,KAAK,QAAQ;AACvD,QAAI,CAAC,KAAK,YAAa,QAAO;AAM9B,UAAM,YAAY,IAAI,SAAS,GAAG,IAAI,MAAM;AAC5C,WAAO,GAAG,GAAG,GAAG,SAAS,gBAAgB,mBAAmB,KAAK,WAAW,CAAC;AAAA,EAC/E;AAAA,EAEA,cAA6B;AAC3B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,YAA2B;AACzB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,gBAA+B;AAC7B,WAAO,KAAK;AAAA,EACd;AACF;AAEA,IAAO,uBAAQ;","names":["axios"]}
1
+ {"version":3,"sources":["../../src/sdk/index.ts","../../src/sdk/alquimia-sdk.ts"],"sourcesContent":["export { default as AlquimiaSDK } from './alquimia-sdk';","import axios, { AxiosInstance } from 'axios';\nimport {\n StableDiffusionProvider,\n WhisperProvider,\n CharacterizationProvider,\n RatingsProvider,\n LoggerProvider,\n} from '../providers';\nimport {\n AttachmentPayload,\n TTSResult,\n type CommonAttributes,\n type Content,\n type RuntimeBlob,\n type ToolApprovalEvent,\n type ToolApprovalOutcome,\n type ToolApprovalResult,\n} from '../types';\nimport type { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters';\nimport type { ToolExecutionResponse } from '../genui/types';\n\n/** Per-turn options for {@link AlquimiaSDK.sendMessage}. */\nexport interface SendMessageOptions {\n /** W3C traceparent, so infer and stream share one trace. */\n traceParent?: string;\n /**\n * Audio input for this turn (runtime v0.5.1). Upload it with\n * {@link AlquimiaSDK.uploadAttachment} first and pass the blob it returns.\n * May be sent with or instead of `query`.\n */\n inputAudio?: RuntimeBlob;\n /**\n * Set to `false` to force a text-only reply from an audio-enabled agent.\n * The runtime defaults to `true`, so leaving this unset keeps its behaviour.\n */\n outputAudio?: boolean;\n}\n\nclass AlquimiaSDK {\n private adapter: AlquimiaAdapter;\n private assistantId: string;\n private axiosInstance: AxiosInstance;\n private conversationId: string | null = null;\n private sessionId: string | null = null;\n // Internal subscription id from infer (`taskid` on the wire).\n private streamId: string | null = null;\n // W3C traceparent for the current turn, so infer and stream share one trace.\n private traceParent: string | null = null;\n // Registry version tag resolved by the runtime for this task (v0.5.1), so\n // the tool-completion half of the turn lands on the same agentspace version.\n private versionTag: string | null = null;\n // Agentspace the runtime resolved for this task. Tool completion and\n // approval authorize a non-admin caller against it, so it is echoed back.\n private agentspaceId: string | null = null;\n private tools: any = [];\n private extraInstructions: Record<string, string> | null = null;\n private assistantConfig: any = null;\n private userId: string | null = null;\n private whisperProvider?: WhisperProvider;\n private stableDiffusionProvider?: StableDiffusionProvider;\n private analyzeCharacterizationProvider?: CharacterizationProvider;\n private ratingsProvider?: RatingsProvider;\n private loggerProvider?: LoggerProvider;\n private enforceCharacterization?: boolean;\n private attachments: AttachmentPayload[] = [];\n private attachmentResponses: string[] = [];\n\n constructor(\n assistantId: string,\n adapter: AlquimiaAdapter,\n options: AlquimiaSDKOptions = {}\n ) {\n if (!assistantId) {\n throw new Error('AlquimiaSDK: assistantId is required');\n }\n if (!adapter) {\n throw new Error(\n 'AlquimiaSDK: adapter is required. Use createNextJsAdapter() or createFetchAdapter()'\n );\n }\n\n this.assistantId = assistantId;\n this.adapter = adapter;\n this.enforceCharacterization = options.enforceCharacterization ?? true;\n\n this.axiosInstance = axios.create();\n this.axiosInstance.interceptors.response.use(\n (response) => response,\n async (error) => {\n if (error.response?.status && this.loggerProvider) {\n await this.loggerProvider.logError('Server Error', error, {\n url: error.config.url,\n method: error.config.method,\n data: error.config.data,\n status: error.response.status,\n responseData: error.response.data,\n });\n }\n return Promise.reject(error);\n }\n );\n\n this.textToSpeech = this.textToSpeech.bind(this);\n this.speechToText = this.speechToText.bind(this);\n }\n\n withConversationId(conversationId: string): AlquimiaSDK {\n this.conversationId = conversationId;\n return this;\n }\n\n withAttachments(attachments: AttachmentPayload[]): AlquimiaSDK {\n this.attachments = attachments;\n return this;\n }\n\n withWhisperProvider(provider: WhisperProvider): AlquimiaSDK {\n this.whisperProvider = provider;\n return this;\n }\n\n withStableDiffusionProvider(provider: StableDiffusionProvider): AlquimiaSDK {\n this.stableDiffusionProvider = provider;\n return this;\n }\n\n withAnalyzeCharacterizationProvider(provider: CharacterizationProvider): AlquimiaSDK {\n this.analyzeCharacterizationProvider = provider;\n return this;\n }\n\n withRatingsProvider(provider: RatingsProvider): AlquimiaSDK {\n this.ratingsProvider = provider;\n return this;\n }\n\n withLoggerProvider(provider: LoggerProvider): AlquimiaSDK {\n this.loggerProvider = provider;\n return this;\n }\n\n withTools(tools: any): AlquimiaSDK {\n this.tools = tools;\n return this;\n }\n\n withExtraInstructions(extraInstructions: Record<string, string>): AlquimiaSDK {\n this.extraInstructions = extraInstructions;\n return this;\n }\n\n withAssistantConfig(assistantConfig: any): AlquimiaSDK {\n this.assistantConfig = assistantConfig;\n return this;\n }\n\n withUserId(userId: string): AlquimiaSDK {\n this.userId = userId;\n return this;\n }\n\n /**\n * Pin inference to a cached registry version. Sent as the `version_tag`\n * query parameter, which `POST /event/infer/{assistant_id}` accepts from\n * **runtime v0.5.2** onward; older runtimes ignore it.\n *\n * Works on every version: pass a versioned assistant ref\n * (`<agentspace>/<assistant>[:<tag>]`) as the `assistantId` instead — the\n * runtime parses the tag out of the path itself.\n */\n withVersionTag(versionTag: string): AlquimiaSDK {\n this.versionTag = versionTag;\n return this;\n }\n\n getEnforceCharacterization(): boolean {\n return this.enforceCharacterization ?? true;\n }\n\n textToSpeech(text: string): Promise<TTSResult> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.textToSpeech(text);\n }\n\n speechToText(audio: string): Promise<string> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.speechToText(audio);\n }\n\n async sendMessage(\n query?: Content,\n options: string | SendMessageOptions = {}\n ): Promise<AlquimiaSDK> {\n if (!this.conversationId) {\n throw new Error(\n 'Conversation not initialized. Call withConversationId() before sendMessage()'\n );\n }\n\n // Backwards-compat: the previous signature was sendMessage(query, traceParent?).\n const opts: SendMessageOptions =\n typeof options === 'string' ? { traceParent: options } : options;\n\n if (query === undefined && !opts.inputAudio) {\n throw new Error(\n 'AlquimiaSDK: sendMessage needs a query, an inputAudio blob, or both'\n );\n }\n\n const baseInferUrl = this.adapter.resolveInferUrl(this.assistantId);\n // `version_tag` is a query parameter on infer (runtime v0.5.2+), never a\n // header — the runtime reads it with `Query(...)`.\n const inferUrl = this.versionTag\n ? `${baseInferUrl}${baseInferUrl.includes('?') ? '&' : '?'}version_tag=${encodeURIComponent(this.versionTag)}`\n : baseInferUrl;\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const hasClientTools = Array.isArray(this.tools) && this.tools.length > 0;\n\n const initMessage: Record<string, unknown> = {\n ...(query !== undefined && { query }),\n session_id: this.conversationId,\n user_id: this.userId,\n ...(opts.inputAudio && { input_audio: opts.inputAudio }),\n // Only sent when set: the runtime defaults `output_audio` to true.\n ...(opts.outputAudio !== undefined && { output_audio: opts.outputAudio }),\n ...(this.extraInstructions && { extra_instructions: this.extraInstructions }),\n ...(this.assistantConfig && { config: this.assistantConfig }),\n ...(hasClientTools && {\n evaluation_strategy: {\n evaluation_strategy_id: 'native',\n tool_schemas: this.tools,\n },\n }),\n };\n\n const result = (\n await this.axiosInstance.post(inferUrl, initMessage, {\n headers: {\n 'Content-Type': 'application/json',\n ...(opts.traceParent && { 'x-trace-parent': opts.traceParent }),\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n })\n ).data as CommonAttributes;\n\n this.traceParent = opts.traceParent ?? null;\n this.streamId = result.taskid ?? null;\n this.versionTag = result.versiontag ?? this.versionTag;\n this.agentspaceId = result.agentspaceid ?? null;\n this.attachmentResponses = result.attachments ?? [];\n this.attachments = [];\n\n return this;\n }\n\n /**\n * Complete a pending client-tool execution (the missing \"submit half\" of the\n * client-tool loop). POSTs a {@link ToolExecutionResponse} to the runtime's\n * `/event/tool-completion`. For interactive `render_ui` surfaces `result` is\n * the user's data; for display-only surfaces the SDK sends `{ shown: true }`.\n * The pending call is correlated by `control_id` in the body + the\n * `context-metadata` header (taskid + sessionid).\n */\n async submitToolResult(response: ToolExecutionResponse): Promise<void> {\n const url = this.adapter.resolveToolCompletionUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)'\n );\n }\n await this.axiosInstance.post(url, response, { headers: this.buildDecisionHeaders() });\n }\n\n /**\n * Answer a `HumanApprovalRequired` gate: POSTs a {@link ToolApprovalEvent} to\n * the runtime's `/event/tool-approval`. `controlId` is the gate's own control\n * id (the `HumanApprovalRequired` record's), not the parked tool call's.\n *\n * Never throws for a runtime refusal — each 409 means something different to\n * the UI, so the answer comes back classified as a {@link ToolApprovalResult}.\n * It does throw when the adapter has no approval route, which is a wiring bug\n * rather than a runtime answer.\n */\n async submitToolApproval(\n controlId: string,\n approved: boolean,\n message?: string\n ): Promise<ToolApprovalResult> {\n const url = this.adapter.resolveToolApprovalUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool approval (resolveToolApprovalUrl missing)'\n );\n }\n\n const event: ToolApprovalEvent = {\n event_class: 'ToolApprovalEvent',\n control_id: controlId,\n result: approved,\n ...(message && { message }),\n };\n\n try {\n await this.axiosInstance.post(url, event, { headers: this.buildDecisionHeaders() });\n return { outcome: 'accepted' };\n } catch (error) {\n return classifyApprovalError(error);\n }\n }\n\n async generateImage(query: string): Promise<string> {\n if (!this.stableDiffusionProvider) {\n throw new Error('Stable Diffusion provider not initialized');\n }\n return this.stableDiffusionProvider.generateImage(query);\n }\n\n async analyzeCharacterization(text: string): Promise<Record<string, any>> {\n if (!this.analyzeCharacterizationProvider) {\n throw new Error('Analyze characterization provider not initialized');\n }\n return this.analyzeCharacterizationProvider.analyzeCharacterization(text);\n }\n\n async rate(data: any): Promise<Record<string, any>> {\n if (!this.ratingsProvider) {\n throw new Error('Ratings provider not initialized');\n }\n return this.ratingsProvider.rate(data);\n }\n\n async logInfo(message: string, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logInfo(message, data);\n }\n\n async logError(message: string, error: Error, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logError(message, error, data);\n }\n\n /**\n * @deprecated The runtime no longer returns attachment IDs from the infer\n * response — attachments are uploaded as standalone blobs and linked to the\n * session via headers. Always returns `[]`; kept for source compatibility.\n */\n getAttachmentResponses(): string[] {\n return this.attachmentResponses;\n }\n\n /**\n * Upload a file into the session context. Returns the runtime {@link RuntimeBlob},\n * which is what `sendMessage`'s `inputAudio` expects for audio inference.\n */\n async uploadAttachment(file: File, _attachmentId?: string): Promise<RuntimeBlob> {\n void _attachmentId;\n const url = this.adapter.resolveBlobUploadUrl();\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n const formData = new FormData();\n formData.append('file', file);\n const response = await this.axiosInstance.post(url, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n });\n return response.data as RuntimeBlob;\n }\n\n /**\n * Identity headers (kebab-case) required by `/context/blob/upload` and\n * the rest of the runtime's internal endpoints introduced in v0.2.0→next.\n */\n private buildIdentityHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'assistant-id': this.assistantId,\n };\n if (this.conversationId) headers['session-id'] = this.conversationId;\n if (this.userId) headers['user-id'] = this.userId;\n if (this.streamId) headers['task-id'] = this.streamId;\n return headers;\n }\n\n /**\n * Correlation headers for tool-completion and tool-approval: the runtime's\n * `CommonAttributes` header aliases, with no separator. Not interchangeable\n * with the kebab-case set in {@link buildIdentityHeaders}.\n */\n private buildDecisionHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n assistantid: this.assistantId,\n ...(this.streamId && { taskid: this.streamId }),\n ...(this.conversationId && { sessionid: this.conversationId }),\n ...(this.userId && { userid: this.userId }),\n ...(this.agentspaceId && { agentspaceid: this.agentspaceId }),\n ...(this.versionTag && { versiontag: this.versionTag }),\n ...(this.adapter.getHeaders?.() ?? {}),\n };\n }\n\n getUrlStream(): string {\n if (!this.streamId) {\n throw new Error('Stream ID not initialized. Call sendMessage() first');\n }\n\n const url = this.adapter.resolveStreamUrl(this.streamId);\n if (!this.traceParent) return url;\n\n // `EventSource` cannot set request headers, so the turn's traceparent rides\n // the URL. The proxy turns it back into `x-trace-parent` and does not pass\n // the param upstream; without this the stream leg — where the whole\n // inference actually happens — lands in a different trace than the infer.\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}trace_parent=${encodeURIComponent(this.traceParent)}`;\n }\n\n getStreamId(): string | null {\n return this.streamId;\n }\n\n /** Alias for {@link getStreamId} — same value as infer `taskid`. */\n getTaskId(): string | null {\n return this.streamId;\n }\n\n /** Registry version tag resolved by the runtime for the current task, if any. */\n getVersionTag(): string | null {\n return this.versionTag;\n }\n\n /** Agentspace the runtime resolved for the current task, if any. */\n getAgentspaceId(): string | null {\n return this.agentspaceId;\n }\n}\n\n/**\n * Map a failed `/event/tool-approval` call onto an outcome. The runtime's 409s\n * share a status and differ only in `detail` (`routers/event.py`), so matching\n * the text is the contract, not a shortcut.\n */\nfunction classifyApprovalError(error: unknown): ToolApprovalResult {\n const response = (error as { response?: { status?: number; data?: unknown } })?.response;\n const status = response?.status;\n const data = response?.data as { detail?: unknown; error?: unknown } | string | undefined;\n const rawDetail =\n typeof data === 'string' ? data : data?.detail ?? data?.error ?? (error as Error)?.message;\n const detail = typeof rawDetail === 'string' ? rawDetail : JSON.stringify(rawDetail ?? '');\n\n let outcome: ToolApprovalOutcome = 'error';\n if (status === 409) {\n if (/original channel/i.test(detail)) outcome = 'wrong-channel';\n else if (/already been recorded/i.test(detail)) outcome = 'already-decided';\n else if (/no pending approval/i.test(detail)) outcome = 'not-pending';\n } else if (status === 401 || status === 403) {\n outcome = 'forbidden';\n } else if (status === 404) {\n outcome = 'not-found';\n }\n\n return { outcome, ...(status !== undefined && { status }), detail };\n}\n\nexport default AlquimiaSDK;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAqC;AAsCrC,IAAM,cAAN,MAAkB;AAAA,EA6BhB,YACE,aACA,SACA,UAA8B,CAAC,GAC/B;AA7BF,SAAQ,iBAAgC;AACxC,SAAQ,YAA2B;AAEnC;AAAA,SAAQ,WAA0B;AAElC;AAAA,SAAQ,cAA6B;AAGrC;AAAA;AAAA,SAAQ,aAA4B;AAGpC;AAAA;AAAA,SAAQ,eAA8B;AACtC,SAAQ,QAAa,CAAC;AACtB,SAAQ,oBAAmD;AAC3D,SAAQ,kBAAuB;AAC/B,SAAQ,SAAwB;AAOhC,SAAQ,cAAmC,CAAC;AAC5C,SAAQ,sBAAgC,CAAC;AAOvC,QAAI,CAAC,aAAa;AAChB,YAAM,IAAI,MAAM,sCAAsC;AAAA,IACxD;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,cAAc;AACnB,SAAK,UAAU;AACf,SAAK,0BAA0B,QAAQ,2BAA2B;AAElE,SAAK,gBAAgB,aAAAA,QAAM,OAAO;AAClC,SAAK,cAAc,aAAa,SAAS;AAAA,MACvC,CAAC,aAAa;AAAA,MACd,OAAO,UAAU;AACf,YAAI,MAAM,UAAU,UAAU,KAAK,gBAAgB;AACjD,gBAAM,KAAK,eAAe,SAAS,gBAAgB,OAAO;AAAA,YACxD,KAAK,MAAM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AK,YAAa,QAAO;AAM9B,UAAM,YAAY,IAAI,SAAS,GAAG,IAAI,MAAM;AAC5C,WAAO,GAAG,GAAG,GAAG,SAAS,gBAAgB,mBAAmB,KAAK,WAAW,CAAC;AAAA,EAC/E;AAAA,EAEA,cAA6B;AAC3B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,YAA2B;AACzB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,gBAA+B;AAC7B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,kBAAiC;AAC/B,WAAO,KAAK;AAAA,EACd;AACF;AAOA,SAAS,sBAAsB,OAAoC;AACjE,QAAM,WAAY,OAA8D;AAChF,QAAM,SAAS,UAAU;AACzB,QAAM,OAAO,UAAU;AACvB,QAAM,YACJ,OAAO,SAAS,WAAW,OAAO,MAAM,UAAU,MAAM,SAAU,OAAiB;AACrF,QAAM,SAAS,OAAO,cAAc,WAAW,YAAY,KAAK,UAAU,aAAa,EAAE;AAEzF,MAAI,UAA+B;AACnC,MAAI,WAAW,KAAK;AAClB,QAAI,oBAAoB,KAAK,MAAM,EAAG,WAAU;AAAA,aACvC,yBAAyB,KAAK,MAAM,EAAG,WAAU;AAAA,aACjD,uBAAuB,KAAK,MAAM,EAAG,WAAU;AAAA,EAC1D,WAAW,WAAW,OAAO,WAAW,KAAK;AAC3C,cAAU;AAAA,EACZ,WAAW,WAAW,KAAK;AACzB,cAAU;AAAA,EACZ;AAEA,SAAO,EAAE,SAAS,GAAI,WAAW,UAAa,EAAE,OAAO,GAAI,OAAO;AACpE;AAEA,IAAO,uBAAQ;","names":["axios"]}
@@ -11,6 +11,9 @@ var AlquimiaSDK = class {
11
11
  // Registry version tag resolved by the runtime for this task (v0.5.1), so
12
12
  // the tool-completion half of the turn lands on the same agentspace version.
13
13
  this.versionTag = null;
14
+ // Agentspace the runtime resolved for this task. Tool completion and
15
+ // approval authorize a non-admin caller against it, so it is echoed back.
16
+ this.agentspaceId = null;
14
17
  this.tools = [];
15
18
  this.extraInstructions = null;
16
19
  this.assistantConfig = null;
@@ -162,6 +165,7 @@ var AlquimiaSDK = class {
162
165
  this.traceParent = opts.traceParent ?? null;
163
166
  this.streamId = result.taskid ?? null;
164
167
  this.versionTag = result.versiontag ?? this.versionTag;
168
+ this.agentspaceId = result.agentspaceid ?? null;
165
169
  this.attachmentResponses = result.attachments ?? [];
166
170
  this.attachments = [];
167
171
  return this;
@@ -181,17 +185,37 @@ var AlquimiaSDK = class {
181
185
  "AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)"
182
186
  );
183
187
  }
184
- const adapterHeaders = this.adapter.getHeaders?.() ?? {};
185
- const headers = {
186
- "Content-Type": "application/json",
187
- assistantid: this.assistantId,
188
- ...this.streamId && { taskid: this.streamId },
189
- ...this.conversationId && { sessionid: this.conversationId },
190
- ...this.userId && { userid: this.userId },
191
- ...this.versionTag && { versiontag: this.versionTag },
192
- ...adapterHeaders
188
+ await this.axiosInstance.post(url, response, { headers: this.buildDecisionHeaders() });
189
+ }
190
+ /**
191
+ * Answer a `HumanApprovalRequired` gate: POSTs a {@link ToolApprovalEvent} to
192
+ * the runtime's `/event/tool-approval`. `controlId` is the gate's own control
193
+ * id (the `HumanApprovalRequired` record's), not the parked tool call's.
194
+ *
195
+ * Never throws for a runtime refusal — each 409 means something different to
196
+ * the UI, so the answer comes back classified as a {@link ToolApprovalResult}.
197
+ * It does throw when the adapter has no approval route, which is a wiring bug
198
+ * rather than a runtime answer.
199
+ */
200
+ async submitToolApproval(controlId, approved, message) {
201
+ const url = this.adapter.resolveToolApprovalUrl?.();
202
+ if (!url) {
203
+ throw new Error(
204
+ "AlquimiaSDK: adapter does not support tool approval (resolveToolApprovalUrl missing)"
205
+ );
206
+ }
207
+ const event = {
208
+ event_class: "ToolApprovalEvent",
209
+ control_id: controlId,
210
+ result: approved,
211
+ ...message && { message }
193
212
  };
194
- await this.axiosInstance.post(url, response, { headers });
213
+ try {
214
+ await this.axiosInstance.post(url, event, { headers: this.buildDecisionHeaders() });
215
+ return { outcome: "accepted" };
216
+ } catch (error) {
217
+ return classifyApprovalError(error);
218
+ }
195
219
  }
196
220
  async generateImage(query) {
197
221
  if (!this.stableDiffusionProvider) {
@@ -262,6 +286,23 @@ var AlquimiaSDK = class {
262
286
  if (this.streamId) headers["task-id"] = this.streamId;
263
287
  return headers;
264
288
  }
289
+ /**
290
+ * Correlation headers for tool-completion and tool-approval: the runtime's
291
+ * `CommonAttributes` header aliases, with no separator. Not interchangeable
292
+ * with the kebab-case set in {@link buildIdentityHeaders}.
293
+ */
294
+ buildDecisionHeaders() {
295
+ return {
296
+ "Content-Type": "application/json",
297
+ assistantid: this.assistantId,
298
+ ...this.streamId && { taskid: this.streamId },
299
+ ...this.conversationId && { sessionid: this.conversationId },
300
+ ...this.userId && { userid: this.userId },
301
+ ...this.agentspaceId && { agentspaceid: this.agentspaceId },
302
+ ...this.versionTag && { versiontag: this.versionTag },
303
+ ...this.adapter.getHeaders?.() ?? {}
304
+ };
305
+ }
265
306
  getUrlStream() {
266
307
  if (!this.streamId) {
267
308
  throw new Error("Stream ID not initialized. Call sendMessage() first");
@@ -282,7 +323,29 @@ var AlquimiaSDK = class {
282
323
  getVersionTag() {
283
324
  return this.versionTag;
284
325
  }
326
+ /** Agentspace the runtime resolved for the current task, if any. */
327
+ getAgentspaceId() {
328
+ return this.agentspaceId;
329
+ }
285
330
  };
331
+ function classifyApprovalError(error) {
332
+ const response = error?.response;
333
+ const status = response?.status;
334
+ const data = response?.data;
335
+ const rawDetail = typeof data === "string" ? data : data?.detail ?? data?.error ?? error?.message;
336
+ const detail = typeof rawDetail === "string" ? rawDetail : JSON.stringify(rawDetail ?? "");
337
+ let outcome = "error";
338
+ if (status === 409) {
339
+ if (/original channel/i.test(detail)) outcome = "wrong-channel";
340
+ else if (/already been recorded/i.test(detail)) outcome = "already-decided";
341
+ else if (/no pending approval/i.test(detail)) outcome = "not-pending";
342
+ } else if (status === 401 || status === 403) {
343
+ outcome = "forbidden";
344
+ } else if (status === 404) {
345
+ outcome = "not-found";
346
+ }
347
+ return { outcome, ...status !== void 0 && { status }, detail };
348
+ }
286
349
  var alquimia_sdk_default = AlquimiaSDK;
287
350
  export {
288
351
  alquimia_sdk_default as AlquimiaSDK
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sdk/alquimia-sdk.ts"],"sourcesContent":["import axios, { AxiosInstance } from 'axios';\nimport {\n StableDiffusionProvider,\n WhisperProvider,\n CharacterizationProvider,\n RatingsProvider,\n LoggerProvider,\n} from '../providers';\nimport {\n AttachmentPayload,\n TTSResult,\n type CommonAttributes,\n type Content,\n type RuntimeBlob,\n} from '../types';\nimport type { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters';\nimport type { ToolExecutionResponse } from '../genui/types';\n\n/** Per-turn options for {@link AlquimiaSDK.sendMessage}. */\nexport interface SendMessageOptions {\n /** W3C traceparent, so infer and stream share one trace. */\n traceParent?: string;\n /**\n * Audio input for this turn (runtime v0.5.1). Upload it with\n * {@link AlquimiaSDK.uploadAttachment} first and pass the blob it returns.\n * May be sent with or instead of `query`.\n */\n inputAudio?: RuntimeBlob;\n /**\n * Set to `false` to force a text-only reply from an audio-enabled agent.\n * The runtime defaults to `true`, so leaving this unset keeps its behaviour.\n */\n outputAudio?: boolean;\n}\n\nclass AlquimiaSDK {\n private adapter: AlquimiaAdapter;\n private assistantId: string;\n private axiosInstance: AxiosInstance;\n private conversationId: string | null = null;\n private sessionId: string | null = null;\n // Internal subscription id from infer (`taskid` on the wire).\n private streamId: string | null = null;\n // W3C traceparent for the current turn, so infer and stream share one trace.\n private traceParent: string | null = null;\n // Registry version tag resolved by the runtime for this task (v0.5.1), so\n // the tool-completion half of the turn lands on the same agentspace version.\n private versionTag: string | null = null;\n private tools: any = [];\n private extraInstructions: Record<string, string> | null = null;\n private assistantConfig: any = null;\n private userId: string | null = null;\n private whisperProvider?: WhisperProvider;\n private stableDiffusionProvider?: StableDiffusionProvider;\n private analyzeCharacterizationProvider?: CharacterizationProvider;\n private ratingsProvider?: RatingsProvider;\n private loggerProvider?: LoggerProvider;\n private enforceCharacterization?: boolean;\n private attachments: AttachmentPayload[] = [];\n private attachmentResponses: string[] = [];\n\n constructor(\n assistantId: string,\n adapter: AlquimiaAdapter,\n options: AlquimiaSDKOptions = {}\n ) {\n if (!assistantId) {\n throw new Error('AlquimiaSDK: assistantId is required');\n }\n if (!adapter) {\n throw new Error(\n 'AlquimiaSDK: adapter is required. Use createNextJsAdapter() or createFetchAdapter()'\n );\n }\n\n this.assistantId = assistantId;\n this.adapter = adapter;\n this.enforceCharacterization = options.enforceCharacterization ?? true;\n\n this.axiosInstance = axios.create();\n this.axiosInstance.interceptors.response.use(\n (response) => response,\n async (error) => {\n if (error.response?.status && this.loggerProvider) {\n await this.loggerProvider.logError('Server Error', error, {\n url: error.config.url,\n method: error.config.method,\n data: error.config.data,\n status: error.response.status,\n responseData: error.response.data,\n });\n }\n return Promise.reject(error);\n }\n );\n\n this.textToSpeech = this.textToSpeech.bind(this);\n this.speechToText = this.speechToText.bind(this);\n }\n\n withConversationId(conversationId: string): AlquimiaSDK {\n this.conversationId = conversationId;\n return this;\n }\n\n withAttachments(attachments: AttachmentPayload[]): AlquimiaSDK {\n this.attachments = attachments;\n return this;\n }\n\n withWhisperProvider(provider: WhisperProvider): AlquimiaSDK {\n this.whisperProvider = provider;\n return this;\n }\n\n withStableDiffusionProvider(provider: StableDiffusionProvider): AlquimiaSDK {\n this.stableDiffusionProvider = provider;\n return this;\n }\n\n withAnalyzeCharacterizationProvider(provider: CharacterizationProvider): AlquimiaSDK {\n this.analyzeCharacterizationProvider = provider;\n return this;\n }\n\n withRatingsProvider(provider: RatingsProvider): AlquimiaSDK {\n this.ratingsProvider = provider;\n return this;\n }\n\n withLoggerProvider(provider: LoggerProvider): AlquimiaSDK {\n this.loggerProvider = provider;\n return this;\n }\n\n withTools(tools: any): AlquimiaSDK {\n this.tools = tools;\n return this;\n }\n\n withExtraInstructions(extraInstructions: Record<string, string>): AlquimiaSDK {\n this.extraInstructions = extraInstructions;\n return this;\n }\n\n withAssistantConfig(assistantConfig: any): AlquimiaSDK {\n this.assistantConfig = assistantConfig;\n return this;\n }\n\n withUserId(userId: string): AlquimiaSDK {\n this.userId = userId;\n return this;\n }\n\n /**\n * Pin inference to a cached registry version. Sent as the `version_tag`\n * query parameter, which `POST /event/infer/{assistant_id}` accepts from\n * **runtime v0.5.2** onward; older runtimes ignore it.\n *\n * Works on every version: pass a versioned assistant ref\n * (`<agentspace>/<assistant>[:<tag>]`) as the `assistantId` instead — the\n * runtime parses the tag out of the path itself.\n */\n withVersionTag(versionTag: string): AlquimiaSDK {\n this.versionTag = versionTag;\n return this;\n }\n\n getEnforceCharacterization(): boolean {\n return this.enforceCharacterization ?? true;\n }\n\n textToSpeech(text: string): Promise<TTSResult> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.textToSpeech(text);\n }\n\n speechToText(audio: string): Promise<string> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.speechToText(audio);\n }\n\n async sendMessage(\n query?: Content,\n options: string | SendMessageOptions = {}\n ): Promise<AlquimiaSDK> {\n if (!this.conversationId) {\n throw new Error(\n 'Conversation not initialized. Call withConversationId() before sendMessage()'\n );\n }\n\n // Backwards-compat: the previous signature was sendMessage(query, traceParent?).\n const opts: SendMessageOptions =\n typeof options === 'string' ? { traceParent: options } : options;\n\n if (query === undefined && !opts.inputAudio) {\n throw new Error(\n 'AlquimiaSDK: sendMessage needs a query, an inputAudio blob, or both'\n );\n }\n\n const baseInferUrl = this.adapter.resolveInferUrl(this.assistantId);\n // `version_tag` is a query parameter on infer (runtime v0.5.2+), never a\n // header — the runtime reads it with `Query(...)`.\n const inferUrl = this.versionTag\n ? `${baseInferUrl}${baseInferUrl.includes('?') ? '&' : '?'}version_tag=${encodeURIComponent(this.versionTag)}`\n : baseInferUrl;\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const hasClientTools = Array.isArray(this.tools) && this.tools.length > 0;\n\n const initMessage: Record<string, unknown> = {\n ...(query !== undefined && { query }),\n session_id: this.conversationId,\n user_id: this.userId,\n ...(opts.inputAudio && { input_audio: opts.inputAudio }),\n // Only sent when set: the runtime defaults `output_audio` to true.\n ...(opts.outputAudio !== undefined && { output_audio: opts.outputAudio }),\n ...(this.extraInstructions && { extra_instructions: this.extraInstructions }),\n ...(this.assistantConfig && { config: this.assistantConfig }),\n ...(hasClientTools && {\n evaluation_strategy: {\n evaluation_strategy_id: 'native',\n tool_schemas: this.tools,\n },\n }),\n };\n\n const result = (\n await this.axiosInstance.post(inferUrl, initMessage, {\n headers: {\n 'Content-Type': 'application/json',\n ...(opts.traceParent && { 'x-trace-parent': opts.traceParent }),\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n })\n ).data as CommonAttributes;\n\n this.traceParent = opts.traceParent ?? null;\n this.streamId = result.taskid ?? null;\n this.versionTag = result.versiontag ?? this.versionTag;\n this.attachmentResponses = result.attachments ?? [];\n this.attachments = [];\n\n return this;\n }\n\n /**\n * Complete a pending client-tool execution (the missing \"submit half\" of the\n * client-tool loop). POSTs a {@link ToolExecutionResponse} to the runtime's\n * `/event/tool-completion`. For interactive `render_ui` surfaces `result` is\n * the user's data; for display-only surfaces the SDK sends `{ shown: true }`.\n * The pending call is correlated by `control_id` in the body + the\n * `context-metadata` header (taskid + sessionid).\n */\n async submitToolResult(response: ToolExecutionResponse): Promise<void> {\n const url = this.adapter.resolveToolCompletionUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)'\n );\n }\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n assistantid: this.assistantId,\n ...(this.streamId && { taskid: this.streamId }),\n ...(this.conversationId && { sessionid: this.conversationId }),\n ...(this.userId && { userid: this.userId }),\n ...(this.versionTag && { versiontag: this.versionTag }),\n ...adapterHeaders,\n };\n await this.axiosInstance.post(url, response, { headers });\n }\n\n async generateImage(query: string): Promise<string> {\n if (!this.stableDiffusionProvider) {\n throw new Error('Stable Diffusion provider not initialized');\n }\n return this.stableDiffusionProvider.generateImage(query);\n }\n\n async analyzeCharacterization(text: string): Promise<Record<string, any>> {\n if (!this.analyzeCharacterizationProvider) {\n throw new Error('Analyze characterization provider not initialized');\n }\n return this.analyzeCharacterizationProvider.analyzeCharacterization(text);\n }\n\n async rate(data: any): Promise<Record<string, any>> {\n if (!this.ratingsProvider) {\n throw new Error('Ratings provider not initialized');\n }\n return this.ratingsProvider.rate(data);\n }\n\n async logInfo(message: string, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logInfo(message, data);\n }\n\n async logError(message: string, error: Error, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logError(message, error, data);\n }\n\n /**\n * @deprecated The runtime no longer returns attachment IDs from the infer\n * response — attachments are uploaded as standalone blobs and linked to the\n * session via headers. Always returns `[]`; kept for source compatibility.\n */\n getAttachmentResponses(): string[] {\n return this.attachmentResponses;\n }\n\n /**\n * Upload a file into the session context. Returns the runtime {@link RuntimeBlob},\n * which is what `sendMessage`'s `inputAudio` expects for audio inference.\n */\n async uploadAttachment(file: File, _attachmentId?: string): Promise<RuntimeBlob> {\n void _attachmentId;\n const url = this.adapter.resolveBlobUploadUrl();\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n const formData = new FormData();\n formData.append('file', file);\n const response = await this.axiosInstance.post(url, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n });\n return response.data as RuntimeBlob;\n }\n\n /**\n * Identity headers (kebab-case) required by `/context/blob/upload` and\n * the rest of the runtime's internal endpoints introduced in v0.2.0→next.\n */\n private buildIdentityHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'assistant-id': this.assistantId,\n };\n if (this.conversationId) headers['session-id'] = this.conversationId;\n if (this.userId) headers['user-id'] = this.userId;\n if (this.streamId) headers['task-id'] = this.streamId;\n return headers;\n }\n\n getUrlStream(): string {\n if (!this.streamId) {\n throw new Error('Stream ID not initialized. Call sendMessage() first');\n }\n\n const url = this.adapter.resolveStreamUrl(this.streamId);\n if (!this.traceParent) return url;\n\n // `EventSource` cannot set request headers, so the turn's traceparent rides\n // the URL. The proxy turns it back into `x-trace-parent` and does not pass\n // the param upstream; without this the stream leg — where the whole\n // inference actually happens — lands in a different trace than the infer.\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}trace_parent=${encodeURIComponent(this.traceParent)}`;\n }\n\n getStreamId(): string | null {\n return this.streamId;\n }\n\n /** Alias for {@link getStreamId} — same value as infer `taskid`. */\n getTaskId(): string | null {\n return this.streamId;\n }\n\n /** Registry version tag resolved by the runtime for the current task, if any. */\n getVersionTag(): string | null {\n return this.versionTag;\n }\n}\n\nexport default AlquimiaSDK;\n"],"mappings":";AAAA,OAAO,WAA8B;AAmCrC,IAAM,cAAN,MAAkB;AAAA,EA0BhB,YACE,aACA,SACA,UAA8B,CAAC,GAC/B;AA1BF,SAAQ,iBAAgC;AACxC,SAAQ,YAA2B;AAEnC;AAAA,SAAQ,WAA0B;AAElC;AAAA,SAAQ,cAA6B;AAGrC;AAAA;AAAA,SAAQ,aAA4B;AACpC,SAAQ,QAAa,CAAC;AACtB,SAAQ,oBAAmD;AAC3D,SAAQ,kBAAuB;AAC/B,SAAQ,SAAwB;AAOhC,SAAQ,cAAmC,CAAC;AAC5C,SAAQ,sBAAgC,CAAC;AAOvC,QAAI,CAAC,aAAa;AAChB,YAAM,IAAI,MAAM,sCAAsC;AAAA,IACxD;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,SAAK,cAAc;AACnB,SAAK,UAA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\nimport {\n StableDiffusionProvider,\n WhisperProvider,\n CharacterizationProvider,\n RatingsProvider,\n LoggerProvider,\n} from '../providers';\nimport {\n AttachmentPayload,\n TTSResult,\n type CommonAttributes,\n type Content,\n type RuntimeBlob,\n type ToolApprovalEvent,\n type ToolApprovalOutcome,\n type ToolApprovalResult,\n} from '../types';\nimport type { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters';\nimport type { ToolExecutionResponse } from '../genui/types';\n\n/** Per-turn options for {@link AlquimiaSDK.sendMessage}. */\nexport interface SendMessageOptions {\n /** W3C traceparent, so infer and stream share one trace. */\n traceParent?: string;\n /**\n * Audio input for this turn (runtime v0.5.1). Upload it with\n * {@link AlquimiaSDK.uploadAttachment} first and pass the blob it returns.\n * May be sent with or instead of `query`.\n */\n inputAudio?: RuntimeBlob;\n /**\n * Set to `false` to force a text-only reply from an audio-enabled agent.\n * The runtime defaults to `true`, so leaving this unset keeps its behaviour.\n */\n outputAudio?: boolean;\n}\n\nclass AlquimiaSDK {\n private adapter: AlquimiaAdapter;\n private assistantId: string;\n private axiosInstance: AxiosInstance;\n private conversationId: string | null = null;\n private sessionId: string | null = null;\n // Internal subscription id from infer (`taskid` on the wire).\n private streamId: string | null = null;\n // W3C traceparent for the current turn, so infer and stream share one trace.\n private traceParent: string | null = null;\n // Registry version tag resolved by the runtime for this task (v0.5.1), so\n // the tool-completion half of the turn lands on the same agentspace version.\n private versionTag: string | null = null;\n // Agentspace the runtime resolved for this task. Tool completion and\n // approval authorize a non-admin caller against it, so it is echoed back.\n private agentspaceId: string | null = null;\n private tools: any = [];\n private extraInstructions: Record<string, string> | null = null;\n private assistantConfig: any = null;\n private userId: string | null = null;\n private whisperProvider?: WhisperProvider;\n private stableDiffusionProvider?: StableDiffusionProvider;\n private analyzeCharacterizationProvider?: CharacterizationProvider;\n private ratingsProvider?: RatingsProvider;\n private loggerProvider?: LoggerProvider;\n private enforceCharacterization?: boolean;\n private attachments: AttachmentPayload[] = [];\n private attachmentResponses: string[] = [];\n\n constructor(\n assistantId: string,\n adapter: AlquimiaAdapter,\n options: AlquimiaSDKOptions = {}\n ) {\n if (!assistantId) {\n throw new Error('AlquimiaSDK: assistantId is required');\n }\n if (!adapter) {\n throw new Error(\n 'AlquimiaSDK: adapter is required. Use createNextJsAdapter() or createFetchAdapter()'\n );\n }\n\n this.assistantId = assistantId;\n this.adapter = adapter;\n this.enforceCharacterization = options.enforceCharacterization ?? true;\n\n this.axiosInstance = axios.create();\n this.axiosInstance.interceptors.response.use(\n (response) => response,\n async (error) => {\n if (error.response?.status && this.loggerProvider) {\n await this.loggerProvider.logError('Server Error', error, {\n url: error.config.url,\n method: error.config.method,\n data: error.config.data,\n status: error.response.status,\n responseData: error.response.data,\n });\n }\n return Promise.reject(error);\n }\n );\n\n this.textToSpeech = this.textToSpeech.bind(this);\n this.speechToText = this.speechToText.bind(this);\n }\n\n withConversationId(conversationId: string): AlquimiaSDK {\n this.conversationId = conversationId;\n return this;\n }\n\n withAttachments(attachments: AttachmentPayload[]): AlquimiaSDK {\n this.attachments = attachments;\n return this;\n }\n\n withWhisperProvider(provider: WhisperProvider): AlquimiaSDK {\n this.whisperProvider = provider;\n return this;\n }\n\n withStableDiffusionProvider(provider: StableDiffusionProvider): AlquimiaSDK {\n this.stableDiffusionProvider = provider;\n return this;\n }\n\n withAnalyzeCharacterizationProvider(provider: CharacterizationProvider): AlquimiaSDK {\n this.analyzeCharacterizationProvider = provider;\n return this;\n }\n\n withRatingsProvider(provider: RatingsProvider): AlquimiaSDK {\n this.ratingsProvider = provider;\n return this;\n }\n\n withLoggerProvider(provider: LoggerProvider): AlquimiaSDK {\n this.loggerProvider = provider;\n return this;\n }\n\n withTools(tools: any): AlquimiaSDK {\n this.tools = tools;\n return this;\n }\n\n withExtraInstructions(extraInstructions: Record<string, string>): AlquimiaSDK {\n this.extraInstructions = extraInstructions;\n return this;\n }\n\n withAssistantConfig(assistantConfig: any): AlquimiaSDK {\n this.assistantConfig = assistantConfig;\n return this;\n }\n\n withUserId(userId: string): AlquimiaSDK {\n this.userId = userId;\n return this;\n }\n\n /**\n * Pin inference to a cached registry version. Sent as the `version_tag`\n * query parameter, which `POST /event/infer/{assistant_id}` accepts from\n * **runtime v0.5.2** onward; older runtimes ignore it.\n *\n * Works on every version: pass a versioned assistant ref\n * (`<agentspace>/<assistant>[:<tag>]`) as the `assistantId` instead — the\n * runtime parses the tag out of the path itself.\n */\n withVersionTag(versionTag: string): AlquimiaSDK {\n this.versionTag = versionTag;\n return this;\n }\n\n getEnforceCharacterization(): boolean {\n return this.enforceCharacterization ?? true;\n }\n\n textToSpeech(text: string): Promise<TTSResult> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.textToSpeech(text);\n }\n\n speechToText(audio: string): Promise<string> {\n if (!this.whisperProvider) {\n throw new Error('Whisper provider not initialized');\n }\n return this.whisperProvider.speechToText(audio);\n }\n\n async sendMessage(\n query?: Content,\n options: string | SendMessageOptions = {}\n ): Promise<AlquimiaSDK> {\n if (!this.conversationId) {\n throw new Error(\n 'Conversation not initialized. Call withConversationId() before sendMessage()'\n );\n }\n\n // Backwards-compat: the previous signature was sendMessage(query, traceParent?).\n const opts: SendMessageOptions =\n typeof options === 'string' ? { traceParent: options } : options;\n\n if (query === undefined && !opts.inputAudio) {\n throw new Error(\n 'AlquimiaSDK: sendMessage needs a query, an inputAudio blob, or both'\n );\n }\n\n const baseInferUrl = this.adapter.resolveInferUrl(this.assistantId);\n // `version_tag` is a query parameter on infer (runtime v0.5.2+), never a\n // header — the runtime reads it with `Query(...)`.\n const inferUrl = this.versionTag\n ? `${baseInferUrl}${baseInferUrl.includes('?') ? '&' : '?'}version_tag=${encodeURIComponent(this.versionTag)}`\n : baseInferUrl;\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n\n const hasClientTools = Array.isArray(this.tools) && this.tools.length > 0;\n\n const initMessage: Record<string, unknown> = {\n ...(query !== undefined && { query }),\n session_id: this.conversationId,\n user_id: this.userId,\n ...(opts.inputAudio && { input_audio: opts.inputAudio }),\n // Only sent when set: the runtime defaults `output_audio` to true.\n ...(opts.outputAudio !== undefined && { output_audio: opts.outputAudio }),\n ...(this.extraInstructions && { extra_instructions: this.extraInstructions }),\n ...(this.assistantConfig && { config: this.assistantConfig }),\n ...(hasClientTools && {\n evaluation_strategy: {\n evaluation_strategy_id: 'native',\n tool_schemas: this.tools,\n },\n }),\n };\n\n const result = (\n await this.axiosInstance.post(inferUrl, initMessage, {\n headers: {\n 'Content-Type': 'application/json',\n ...(opts.traceParent && { 'x-trace-parent': opts.traceParent }),\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n })\n ).data as CommonAttributes;\n\n this.traceParent = opts.traceParent ?? null;\n this.streamId = result.taskid ?? null;\n this.versionTag = result.versiontag ?? this.versionTag;\n this.agentspaceId = result.agentspaceid ?? null;\n this.attachmentResponses = result.attachments ?? [];\n this.attachments = [];\n\n return this;\n }\n\n /**\n * Complete a pending client-tool execution (the missing \"submit half\" of the\n * client-tool loop). POSTs a {@link ToolExecutionResponse} to the runtime's\n * `/event/tool-completion`. For interactive `render_ui` surfaces `result` is\n * the user's data; for display-only surfaces the SDK sends `{ shown: true }`.\n * The pending call is correlated by `control_id` in the body + the\n * `context-metadata` header (taskid + sessionid).\n */\n async submitToolResult(response: ToolExecutionResponse): Promise<void> {\n const url = this.adapter.resolveToolCompletionUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)'\n );\n }\n await this.axiosInstance.post(url, response, { headers: this.buildDecisionHeaders() });\n }\n\n /**\n * Answer a `HumanApprovalRequired` gate: POSTs a {@link ToolApprovalEvent} to\n * the runtime's `/event/tool-approval`. `controlId` is the gate's own control\n * id (the `HumanApprovalRequired` record's), not the parked tool call's.\n *\n * Never throws for a runtime refusal — each 409 means something different to\n * the UI, so the answer comes back classified as a {@link ToolApprovalResult}.\n * It does throw when the adapter has no approval route, which is a wiring bug\n * rather than a runtime answer.\n */\n async submitToolApproval(\n controlId: string,\n approved: boolean,\n message?: string\n ): Promise<ToolApprovalResult> {\n const url = this.adapter.resolveToolApprovalUrl?.();\n if (!url) {\n throw new Error(\n 'AlquimiaSDK: adapter does not support tool approval (resolveToolApprovalUrl missing)'\n );\n }\n\n const event: ToolApprovalEvent = {\n event_class: 'ToolApprovalEvent',\n control_id: controlId,\n result: approved,\n ...(message && { message }),\n };\n\n try {\n await this.axiosInstance.post(url, event, { headers: this.buildDecisionHeaders() });\n return { outcome: 'accepted' };\n } catch (error) {\n return classifyApprovalError(error);\n }\n }\n\n async generateImage(query: string): Promise<string> {\n if (!this.stableDiffusionProvider) {\n throw new Error('Stable Diffusion provider not initialized');\n }\n return this.stableDiffusionProvider.generateImage(query);\n }\n\n async analyzeCharacterization(text: string): Promise<Record<string, any>> {\n if (!this.analyzeCharacterizationProvider) {\n throw new Error('Analyze characterization provider not initialized');\n }\n return this.analyzeCharacterizationProvider.analyzeCharacterization(text);\n }\n\n async rate(data: any): Promise<Record<string, any>> {\n if (!this.ratingsProvider) {\n throw new Error('Ratings provider not initialized');\n }\n return this.ratingsProvider.rate(data);\n }\n\n async logInfo(message: string, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logInfo(message, data);\n }\n\n async logError(message: string, error: Error, data: any): Promise<void> {\n if (!this.loggerProvider) {\n throw new Error('Logger provider not initialized');\n }\n return this.loggerProvider.logError(message, error, data);\n }\n\n /**\n * @deprecated The runtime no longer returns attachment IDs from the infer\n * response — attachments are uploaded as standalone blobs and linked to the\n * session via headers. Always returns `[]`; kept for source compatibility.\n */\n getAttachmentResponses(): string[] {\n return this.attachmentResponses;\n }\n\n /**\n * Upload a file into the session context. Returns the runtime {@link RuntimeBlob},\n * which is what `sendMessage`'s `inputAudio` expects for audio inference.\n */\n async uploadAttachment(file: File, _attachmentId?: string): Promise<RuntimeBlob> {\n void _attachmentId;\n const url = this.adapter.resolveBlobUploadUrl();\n const adapterHeaders = this.adapter.getHeaders?.() ?? {};\n const formData = new FormData();\n formData.append('file', file);\n const response = await this.axiosInstance.post(url, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n });\n return response.data as RuntimeBlob;\n }\n\n /**\n * Identity headers (kebab-case) required by `/context/blob/upload` and\n * the rest of the runtime's internal endpoints introduced in v0.2.0→next.\n */\n private buildIdentityHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n 'assistant-id': this.assistantId,\n };\n if (this.conversationId) headers['session-id'] = this.conversationId;\n if (this.userId) headers['user-id'] = this.userId;\n if (this.streamId) headers['task-id'] = this.streamId;\n return headers;\n }\n\n /**\n * Correlation headers for tool-completion and tool-approval: the runtime's\n * `CommonAttributes` header aliases, with no separator. Not interchangeable\n * with the kebab-case set in {@link buildIdentityHeaders}.\n */\n private buildDecisionHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n assistantid: this.assistantId,\n ...(this.streamId && { taskid: this.streamId }),\n ...(this.conversationId && { sessionid: this.conversationId }),\n ...(this.userId && { userid: this.userId }),\n ...(this.agentspaceId && { agentspaceid: this.agentspaceId }),\n ...(this.versionTag && { versiontag: this.versionTag }),\n ...(this.adapter.getHeaders?.() ?? {}),\n };\n }\n\n getUrlStream(): string {\n if (!this.streamId) {\n throw new Error('Stream ID not initialized. Call sendMessage() first');\n }\n\n const url = this.adapter.resolveStreamUrl(this.streamId);\n if (!this.traceParent) return url;\n\n // `EventSource` cannot set request headers, so the turn's traceparent rides\n // the URL. The proxy turns it back into `x-trace-parent` and does not pass\n // the param upstream; without this the stream leg — where the whole\n // inference actually happens — lands in a different trace than the infer.\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}trace_parent=${encodeURIComponent(this.traceParent)}`;\n }\n\n getStreamId(): string | null {\n return this.streamId;\n }\n\n /** Alias for {@link getStreamId} — same value as infer `taskid`. */\n getTaskId(): string | null {\n return this.streamId;\n }\n\n /** Registry version tag resolved by the runtime for the current task, if any. */\n getVersionTag(): string | null {\n return this.versionTag;\n }\n\n /** Agentspace the runtime resolved for the current task, if any. */\n getAgentspaceId(): string | null {\n return this.agentspaceId;\n }\n}\n\n/**\n * Map a failed `/event/tool-approval` call onto an outcome. The runtime's 409s\n * share a status and differ only in `detail` (`routers/event.py`), so matching\n * the text is the contract, not a shortcut.\n */\nfunction classifyApprovalError(error: unknown): ToolApprovalResult {\n const response = (error as { response?: { status?: number; data?: unknown } })?.response;\n const status = response?.status;\n const data = response?.data as { detail?: unknown; error?: unknown } | string | undefined;\n const rawDetail =\n typeof data === 'string' ? data : data?.detail ?? data?.error ?? (error as Error)?.message;\n const detail = typeof rawDetail === 'string' ? rawDetail : JSON.stringify(rawDetail ?? '');\n\n let outcome: ToolApprovalOutcome = 'error';\n if (status === 409) {\n if (/original channel/i.test(detail)) outcome = 'wrong-channel';\n else if (/already been recorded/i.test(detail)) outcome = 'already-decided';\n else if (/no pending approval/i.test(detail)) outcome = 'not-pending';\n } else if (status === 401 || status === 403) {\n outcome = 'forbidden';\n } else if (status === 404) {\n outcome = 'not-found';\n }\n\n return { outcome, ...(status !== undefined && { status }), detail };\n}\n\nexport default AlquimiaSDK;\n"],"mappings":";AAAA,OAAO,WAA8B;AAsCrC,IAAM,cAAN,MAAkB;AAAA,EA6BhB,YACE,aACA,SACA,UAA8B,CAAC,GAC/B;AA7BF,SAAQ,iBAAgC;AACxC,SAAQ,YAA2B;AAEnC;AAAA,SAAQ,WAA0B;AAElC;AAAA,SAAQ,cAA6B;AAGrC;AAAA;AAAA,SAAQ,aAA4B;AAGpC;AAAA;AAAA,SAAQ,eAA8B;AACtC,SAAQ,QAAa,CAAC;AACtB,SAAQ,oBAAmD;AAC3D,SAAQ,kBAAuB;AAC/B,SAAQ,SAAwB;AAOhC,SAAQ,cAAmC,CAAC;AAC5C,SAAQ,sBAAgC,CAAC;AAOvC,QAAI,CAAC,aAAa;AAChB,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KAAK;AAC3C,cAAU;AAAA,EACZ,WAAW,WAAW,KAAK;AACzB,cAAU;AAAA,EACZ;AAEA,SAAO,EAAE,SAAS,GAAI,WAAW,UAAa,EAAE,OAAO,GAAI,OAAO;AACpE;AAEA,IAAO,uBAAQ;","names":[]}
@@ -1,5 +1,5 @@
1
1
  import { Transaction } from '@elastic/apm-rum';
2
- import { A as ApmSpan } from '../type-61gaZga-.mjs';
2
+ import { A as ApmSpan } from '../type-C_sKpIM1.mjs';
3
3
  import 'ai';
4
4
  import '../types-CMVbyEv8.mjs';
5
5
 
@@ -1,5 +1,5 @@
1
1
  import { Transaction } from '@elastic/apm-rum';
2
- import { A as ApmSpan } from '../type-D-JaSMkV.js';
2
+ import { A as ApmSpan } from '../type-BFtGEEb4.js';
3
3
  import 'ai';
4
4
  import '../types-CMVbyEv8.js';
5
5
 
@@ -353,4 +353,4 @@ interface GenuiSurfaceItem {
353
353
  dismissedWith?: string;
354
354
  }
355
355
 
356
- export { type ApmSpan as A, type BaseAPIConfig as B, type CommonAttributes as C, type DocumentSearchResult as D, type ElevenLabsRequestSpecs as E, type ToolEvent as F, type GenuiSurfaceItem as G, ToolFactory as H, type IToolSpec as I, type ToolOutput as J, type ToolSummary as K, type Tooler as L, type NativeToolsEvaluationStrategy as N, type OneShootEvaluationStrategy as O, type RatingData as R, type TTSResult as T, type UsageMetadata as U, type AIMessageChunk as a, type AIMessageChunkData as b, type ActionResponse as c, type AlquimiaEventData as d, type AlquimiaMessage as e, type ApiError as f, type AssistantInferenceResponse as g, type AssistantResponseData as h, type AttachmentPayload as i, type Content as j, type ContentPart as k, type ConversationsMap as l, type ElevenLabsVoiceSettings as m, type EvaluationStrategy as n, type ExpertInferenceResponse as o, type ExtraDataContext as p, type ITooler as q, type ImageContentPart as r, type InferInitResponse as s, type NonStandardContentPart as t, type RawToolsEvaluationStrategy as u, type ResponseMetadata as v, type RuntimeBlob as w, type TextContentPart as x, type ThinkingsInferenceResponse as y, type TokenUsage as z };
356
+ export { type ApmSpan as A, type BaseAPIConfig as B, type Content as C, type DocumentSearchResult as D, type ElevenLabsRequestSpecs as E, type TokenUsage as F, type GenuiSurfaceItem as G, ToolFactory as H, type IToolSpec as I, type ToolOutput as J, type ToolSummary as K, type Tooler as L, type NativeToolsEvaluationStrategy as N, type OneShootEvaluationStrategy as O, type RatingData as R, type TTSResult as T, type UsageMetadata as U, type AlquimiaMessage as a, type ToolEvent as b, type AIMessageChunk as c, type AttachmentPayload as d, type RuntimeBlob as e, type AIMessageChunkData as f, type ActionResponse as g, type AlquimiaEventData as h, type ApiError as i, type AssistantInferenceResponse as j, type AssistantResponseData as k, type CommonAttributes as l, type ContentPart as m, type ConversationsMap as n, type ElevenLabsVoiceSettings as o, type EvaluationStrategy as p, type ExpertInferenceResponse as q, type ExtraDataContext as r, type ITooler as s, type ImageContentPart as t, type InferInitResponse as u, type NonStandardContentPart as v, type RawToolsEvaluationStrategy as w, type ResponseMetadata as x, type TextContentPart as y, type ThinkingsInferenceResponse as z };
@@ -353,4 +353,4 @@ interface GenuiSurfaceItem {
353
353
  dismissedWith?: string;
354
354
  }
355
355
 
356
- export { type ApmSpan as A, type BaseAPIConfig as B, type CommonAttributes as C, type DocumentSearchResult as D, type ElevenLabsRequestSpecs as E, type ToolEvent as F, type GenuiSurfaceItem as G, ToolFactory as H, type IToolSpec as I, type ToolOutput as J, type ToolSummary as K, type Tooler as L, type NativeToolsEvaluationStrategy as N, type OneShootEvaluationStrategy as O, type RatingData as R, type TTSResult as T, type UsageMetadata as U, type AIMessageChunk as a, type AIMessageChunkData as b, type ActionResponse as c, type AlquimiaEventData as d, type AlquimiaMessage as e, type ApiError as f, type AssistantInferenceResponse as g, type AssistantResponseData as h, type AttachmentPayload as i, type Content as j, type ContentPart as k, type ConversationsMap as l, type ElevenLabsVoiceSettings as m, type EvaluationStrategy as n, type ExpertInferenceResponse as o, type ExtraDataContext as p, type ITooler as q, type ImageContentPart as r, type InferInitResponse as s, type NonStandardContentPart as t, type RawToolsEvaluationStrategy as u, type ResponseMetadata as v, type RuntimeBlob as w, type TextContentPart as x, type ThinkingsInferenceResponse as y, type TokenUsage as z };
356
+ export { type ApmSpan as A, type BaseAPIConfig as B, type Content as C, type DocumentSearchResult as D, type ElevenLabsRequestSpecs as E, type TokenUsage as F, type GenuiSurfaceItem as G, ToolFactory as H, type IToolSpec as I, type ToolOutput as J, type ToolSummary as K, type Tooler as L, type NativeToolsEvaluationStrategy as N, type OneShootEvaluationStrategy as O, type RatingData as R, type TTSResult as T, type UsageMetadata as U, type AlquimiaMessage as a, type ToolEvent as b, type AIMessageChunk as c, type AttachmentPayload as d, type RuntimeBlob as e, type AIMessageChunkData as f, type ActionResponse as g, type AlquimiaEventData as h, type ApiError as i, type AssistantInferenceResponse as j, type AssistantResponseData as k, type CommonAttributes as l, type ContentPart as m, type ConversationsMap as n, type ElevenLabsVoiceSettings as o, type EvaluationStrategy as p, type ExpertInferenceResponse as q, type ExtraDataContext as r, type ITooler as s, type ImageContentPart as t, type InferInitResponse as u, type NonStandardContentPart as v, type RawToolsEvaluationStrategy as w, type ResponseMetadata as x, type TextContentPart as y, type ThinkingsInferenceResponse as z };
@@ -1,4 +1,4 @@
1
- export { a as AIMessageChunk, b as AIMessageChunkData, c as ActionResponse, d as AlquimiaEventData, e as AlquimiaMessage, f as ApiError, A as ApmSpan, g as AssistantInferenceResponse, h as AssistantResponseData, i as AttachmentPayload, B as BaseAPIConfig, C as CommonAttributes, j as Content, k as ContentPart, l as ConversationsMap, D as DocumentSearchResult, E as ElevenLabsRequestSpecs, m as ElevenLabsVoiceSettings, n as EvaluationStrategy, o as ExpertInferenceResponse, p as ExtraDataContext, G as GenuiSurfaceItem, I as IToolSpec, q as ITooler, r as ImageContentPart, s as InferInitResponse, N as NativeToolsEvaluationStrategy, t as NonStandardContentPart, O as OneShootEvaluationStrategy, R as RatingData, u as RawToolsEvaluationStrategy, v as ResponseMetadata, w as RuntimeBlob, T as TTSResult, x as TextContentPart, y as ThinkingsInferenceResponse, z as TokenUsage, F as ToolEvent, H as ToolFactory, J as ToolOutput, K as ToolSummary, L as Tooler, U as UsageMetadata } from '../type-61gaZga-.mjs';
1
+ export { c as AIMessageChunk, f as AIMessageChunkData, g as ActionResponse, h as AlquimiaEventData, a as AlquimiaMessage, i as ApiError, A as ApmSpan, j as AssistantInferenceResponse, k as AssistantResponseData, d as AttachmentPayload, B as BaseAPIConfig, l as CommonAttributes, C as Content, m as ContentPart, n as ConversationsMap, D as DocumentSearchResult, E as ElevenLabsRequestSpecs, o as ElevenLabsVoiceSettings, p as EvaluationStrategy, q as ExpertInferenceResponse, r as ExtraDataContext, G as GenuiSurfaceItem, I as IToolSpec, s as ITooler, t as ImageContentPart, u as InferInitResponse, N as NativeToolsEvaluationStrategy, v as NonStandardContentPart, O as OneShootEvaluationStrategy, R as RatingData, w as RawToolsEvaluationStrategy, x as ResponseMetadata, e as RuntimeBlob, T as TTSResult, y as TextContentPart, z as ThinkingsInferenceResponse, F as TokenUsage, b as ToolEvent, H as ToolFactory, J as ToolOutput, K as ToolSummary, L as Tooler, U as UsageMetadata } from '../type-C_sKpIM1.mjs';
2
2
  import { T as ToolExecutionResponse } from '../types-CMVbyEv8.mjs';
3
3
  import { W as WorklogRecord } from '../types-lOliroPw.mjs';
4
4
  import '@elastic/apm-rum';
@@ -62,6 +62,27 @@ interface ToolApprovalEvent extends RuntimeEventBase {
62
62
  /** Optional reason or note attached to the decision. */
63
63
  message?: string;
64
64
  }
65
+ /**
66
+ * How the runtime answered a {@link ToolApprovalEvent}. `POST /event/tool-approval`
67
+ * answers every refusal with a 409 and only the `detail` text tells them apart,
68
+ * so the SDK classifies it once here instead of every caller string-matching.
69
+ *
70
+ * - `accepted` — the decision was recorded and the parked tool call resumes (or is dropped).
71
+ * - `already-decided` — someone else (another operator, the originating channel) answered first.
72
+ * - `wrong-channel` — the gate must be answered on the channel that raised it; HTTP never will.
73
+ * - `not-pending` — the control id is stale or already resolved.
74
+ * - `forbidden` — the caller lacks an approver role or is not bound to the task's agentspace.
75
+ * - `not-found` — the task is gone (finished or expired).
76
+ * - `error` — anything else: transport failure, 5xx, an unrecognized 409.
77
+ */
78
+ type ToolApprovalOutcome = "accepted" | "already-decided" | "wrong-channel" | "not-pending" | "forbidden" | "not-found" | "error";
79
+ interface ToolApprovalResult {
80
+ outcome: ToolApprovalOutcome;
81
+ /** HTTP status, when a response came back at all. */
82
+ status?: number;
83
+ /** The runtime's `detail`, verbatim, for anything but `accepted`. */
84
+ detail?: string;
85
+ }
65
86
  /** POST /event/tool-completion (client-side tool execution result). */
66
87
  interface ToolCompletionEvent extends ToolExecutionResponse {
67
88
  event_class: "ToolCompletionEvent";
@@ -85,4 +106,4 @@ interface HeartbeatEvent extends RuntimeEventBase {
85
106
  /** Discriminated union of all runtime v0.5.1 event payloads. */
86
107
  type RuntimeEvent = SessionStartEvent | SessionEndEvent | UserMessageEvent | AgentMessageEvent | ToolApprovalEvent | ToolCompletionEvent | RuntimeErrorEvent | BusModeEvent | HeartbeatEvent;
87
108
 
88
- export type { AgentMessageEvent, BusModeEvent, HeartbeatEvent, RuntimeErrorEvent, RuntimeEvent, RuntimeEventBase, SessionEndEvent, SessionStartEvent, ToolApprovalEvent, ToolCompletionEvent, UserMessageEvent };
109
+ export type { AgentMessageEvent, BusModeEvent, HeartbeatEvent, RuntimeErrorEvent, RuntimeEvent, RuntimeEventBase, SessionEndEvent, SessionStartEvent, ToolApprovalEvent, ToolApprovalOutcome, ToolApprovalResult, ToolCompletionEvent, UserMessageEvent };
@@ -1,4 +1,4 @@
1
- export { a as AIMessageChunk, b as AIMessageChunkData, c as ActionResponse, d as AlquimiaEventData, e as AlquimiaMessage, f as ApiError, A as ApmSpan, g as AssistantInferenceResponse, h as AssistantResponseData, i as AttachmentPayload, B as BaseAPIConfig, C as CommonAttributes, j as Content, k as ContentPart, l as ConversationsMap, D as DocumentSearchResult, E as ElevenLabsRequestSpecs, m as ElevenLabsVoiceSettings, n as EvaluationStrategy, o as ExpertInferenceResponse, p as ExtraDataContext, G as GenuiSurfaceItem, I as IToolSpec, q as ITooler, r as ImageContentPart, s as InferInitResponse, N as NativeToolsEvaluationStrategy, t as NonStandardContentPart, O as OneShootEvaluationStrategy, R as RatingData, u as RawToolsEvaluationStrategy, v as ResponseMetadata, w as RuntimeBlob, T as TTSResult, x as TextContentPart, y as ThinkingsInferenceResponse, z as TokenUsage, F as ToolEvent, H as ToolFactory, J as ToolOutput, K as ToolSummary, L as Tooler, U as UsageMetadata } from '../type-D-JaSMkV.js';
1
+ export { c as AIMessageChunk, f as AIMessageChunkData, g as ActionResponse, h as AlquimiaEventData, a as AlquimiaMessage, i as ApiError, A as ApmSpan, j as AssistantInferenceResponse, k as AssistantResponseData, d as AttachmentPayload, B as BaseAPIConfig, l as CommonAttributes, C as Content, m as ContentPart, n as ConversationsMap, D as DocumentSearchResult, E as ElevenLabsRequestSpecs, o as ElevenLabsVoiceSettings, p as EvaluationStrategy, q as ExpertInferenceResponse, r as ExtraDataContext, G as GenuiSurfaceItem, I as IToolSpec, s as ITooler, t as ImageContentPart, u as InferInitResponse, N as NativeToolsEvaluationStrategy, v as NonStandardContentPart, O as OneShootEvaluationStrategy, R as RatingData, w as RawToolsEvaluationStrategy, x as ResponseMetadata, e as RuntimeBlob, T as TTSResult, y as TextContentPart, z as ThinkingsInferenceResponse, F as TokenUsage, b as ToolEvent, H as ToolFactory, J as ToolOutput, K as ToolSummary, L as Tooler, U as UsageMetadata } from '../type-BFtGEEb4.js';
2
2
  import { T as ToolExecutionResponse } from '../types-CMVbyEv8.js';
3
3
  import { W as WorklogRecord } from '../types-lOliroPw.js';
4
4
  import '@elastic/apm-rum';
@@ -62,6 +62,27 @@ interface ToolApprovalEvent extends RuntimeEventBase {
62
62
  /** Optional reason or note attached to the decision. */
63
63
  message?: string;
64
64
  }
65
+ /**
66
+ * How the runtime answered a {@link ToolApprovalEvent}. `POST /event/tool-approval`
67
+ * answers every refusal with a 409 and only the `detail` text tells them apart,
68
+ * so the SDK classifies it once here instead of every caller string-matching.
69
+ *
70
+ * - `accepted` — the decision was recorded and the parked tool call resumes (or is dropped).
71
+ * - `already-decided` — someone else (another operator, the originating channel) answered first.
72
+ * - `wrong-channel` — the gate must be answered on the channel that raised it; HTTP never will.
73
+ * - `not-pending` — the control id is stale or already resolved.
74
+ * - `forbidden` — the caller lacks an approver role or is not bound to the task's agentspace.
75
+ * - `not-found` — the task is gone (finished or expired).
76
+ * - `error` — anything else: transport failure, 5xx, an unrecognized 409.
77
+ */
78
+ type ToolApprovalOutcome = "accepted" | "already-decided" | "wrong-channel" | "not-pending" | "forbidden" | "not-found" | "error";
79
+ interface ToolApprovalResult {
80
+ outcome: ToolApprovalOutcome;
81
+ /** HTTP status, when a response came back at all. */
82
+ status?: number;
83
+ /** The runtime's `detail`, verbatim, for anything but `accepted`. */
84
+ detail?: string;
85
+ }
65
86
  /** POST /event/tool-completion (client-side tool execution result). */
66
87
  interface ToolCompletionEvent extends ToolExecutionResponse {
67
88
  event_class: "ToolCompletionEvent";
@@ -85,4 +106,4 @@ interface HeartbeatEvent extends RuntimeEventBase {
85
106
  /** Discriminated union of all runtime v0.5.1 event payloads. */
86
107
  type RuntimeEvent = SessionStartEvent | SessionEndEvent | UserMessageEvent | AgentMessageEvent | ToolApprovalEvent | ToolCompletionEvent | RuntimeErrorEvent | BusModeEvent | HeartbeatEvent;
87
108
 
88
- export type { AgentMessageEvent, BusModeEvent, HeartbeatEvent, RuntimeErrorEvent, RuntimeEvent, RuntimeEventBase, SessionEndEvent, SessionStartEvent, ToolApprovalEvent, ToolCompletionEvent, UserMessageEvent };
109
+ export type { AgentMessageEvent, BusModeEvent, HeartbeatEvent, RuntimeErrorEvent, RuntimeEvent, RuntimeEventBase, SessionEndEvent, SessionStartEvent, ToolApprovalEvent, ToolApprovalOutcome, ToolApprovalResult, ToolCompletionEvent, UserMessageEvent };
@@ -1,4 +1,4 @@
1
- import { B as BaseAPIConfig, y as ThinkingsInferenceResponse, L as Tooler, F as ToolEvent, l as ConversationsMap } from '../type-61gaZga-.mjs';
1
+ import { B as BaseAPIConfig, z as ThinkingsInferenceResponse, L as Tooler, b as ToolEvent, n as ConversationsMap } from '../type-C_sKpIM1.mjs';
2
2
  import { C as CatalogManifest } from '../registry-Bcu_ZYL1.mjs';
3
3
  import '@elastic/apm-rum';
4
4
  import 'ai';
@@ -1,4 +1,4 @@
1
- import { B as BaseAPIConfig, y as ThinkingsInferenceResponse, L as Tooler, F as ToolEvent, l as ConversationsMap } from '../type-D-JaSMkV.js';
1
+ import { B as BaseAPIConfig, z as ThinkingsInferenceResponse, L as Tooler, b as ToolEvent, n as ConversationsMap } from '../type-BFtGEEb4.js';
2
2
  import { C as CatalogManifest } from '../registry-Bcu_ZYL1.js';
3
3
  import '@elastic/apm-rum';
4
4
  import 'ai';
@@ -1,5 +1,6 @@
1
1
  import { E as EventInterpreter, W as WorklogRecord, a as WorklogState } from '../types-lOliroPw.mjs';
2
2
  export { b as EventRole, N as NodeKind, c as NodeStatus, R as RunStatus, d as WorklogDetail, e as WorklogEventDetail, f as WorklogEventPage, g as WorklogNode, h as WorklogPage, i as WorklogSummary, j as WorklogVerificationResult, k as initialWorklogState } from '../types-lOliroPw.mjs';
3
+ export { a as ApprovalDecision, A as ApprovalRequest, b as ApprovalsState, f as foldApprovals, i as initialApprovalsState, l as listApprovals, p as pendingApprovals, r as reduceApprovals } from '../approvals-dn4sd_Ot.mjs';
3
4
 
4
5
  declare const EVENT_REGISTRY: Record<string, EventInterpreter>;
5
6
  declare function resolveInterpreter(eventClass: string): EventInterpreter;
@@ -1,5 +1,6 @@
1
1
  import { E as EventInterpreter, W as WorklogRecord, a as WorklogState } from '../types-lOliroPw.js';
2
2
  export { b as EventRole, N as NodeKind, c as NodeStatus, R as RunStatus, d as WorklogDetail, e as WorklogEventDetail, f as WorklogEventPage, g as WorklogNode, h as WorklogPage, i as WorklogSummary, j as WorklogVerificationResult, k as initialWorklogState } from '../types-lOliroPw.js';
3
+ export { a as ApprovalDecision, A as ApprovalRequest, b as ApprovalsState, f as foldApprovals, i as initialApprovalsState, l as listApprovals, p as pendingApprovals, r as reduceApprovals } from '../approvals-CcnmqUkQ.js';
3
4
 
4
5
  declare const EVENT_REGISTRY: Record<string, EventInterpreter>;
5
6
  declare function resolveInterpreter(eventClass: string): EventInterpreter;
@@ -21,9 +21,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var worklog_exports = {};
22
22
  __export(worklog_exports, {
23
23
  EVENT_REGISTRY: () => EVENT_REGISTRY,
24
+ foldApprovals: () => foldApprovals,
24
25
  foldWorklog: () => foldWorklog,
25
26
  frameToRecord: () => frameToRecord,
27
+ initialApprovalsState: () => initialApprovalsState,
26
28
  initialWorklogState: () => initialWorklogState,
29
+ listApprovals: () => listApprovals,
30
+ pendingApprovals: () => pendingApprovals,
31
+ reduceApprovals: () => reduceApprovals,
27
32
  reduceWorklog: () => reduceWorklog,
28
33
  resolveInterpreter: () => resolveInterpreter,
29
34
  useWorklog: () => useWorklog
@@ -46,6 +51,10 @@ var agentTitle = (r) => {
46
51
  return typeof name === "string" && name.length > 0 ? `Agent: ${name}` : "Agent-to-agent";
47
52
  };
48
53
  var constTitle = (label) => () => label;
54
+ var approvalTitle = (r) => {
55
+ const name = asRecord(asRecord(r.data).parameters).name;
56
+ return typeof name === "string" && name.length > 0 ? `Approval required: ${name}` : "Human approval required";
57
+ };
49
58
  var shieldBlockTitle = (r) => {
50
59
  const id = asRecord(r.data).shield_id;
51
60
  return typeof id === "string" && id.length > 0 ? `Blocked by ${id}` : "Blocked by safeguard";
@@ -97,7 +106,7 @@ var EVENT_REGISTRY = {
97
106
  HumanApprovalRequired: {
98
107
  kind: "tool",
99
108
  role: "open",
100
- title: constTitle("Human approval required"),
109
+ title: approvalTitle,
101
110
  pending: true
102
111
  },
103
112
  HumanApprovalRequiredResponse: { kind: "tool", role: "close", title: constTitle("Human approval") }
@@ -186,7 +195,12 @@ function reduceWorklog(state, record) {
186
195
  const pos = Object.prototype.hasOwnProperty.call(next.index, key) ? next.index[key] : void 0;
187
196
  if (pos != null) {
188
197
  const existing = next.nodes[pos];
189
- next.nodes[pos] = { ...existing, raw: [...existing.raw, record] };
198
+ next.nodes[pos] = {
199
+ ...existing,
200
+ command: existing.command ?? record.data,
201
+ title: existing.command === void 0 ? interp.title(record) : existing.title,
202
+ raw: [...existing.raw, record]
203
+ };
190
204
  } else {
191
205
  next.index[key] = next.nodes.length;
192
206
  next.nodes.push(makeOpenNode(record, interp, key));
@@ -236,4 +250,63 @@ function frameToRecord(frame) {
236
250
  previous_hash: frame.previous_hash ?? null
237
251
  };
238
252
  }
253
+
254
+ // src/worklog/approvals.ts
255
+ function initialApprovalsState() {
256
+ return { order: [], byId: {} };
257
+ }
258
+ var asObject = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : null;
259
+ var MCP_APPROVAL_EXTENSION = "mcp_approval";
260
+ function describeRequest(record) {
261
+ const execution = asObject(asObject(record.data)?.parameters) ?? {};
262
+ const name = execution.name;
263
+ const callId = execution.control_id;
264
+ const args = execution.tool_call_parameters !== void 0 && execution.tool_call_parameters !== null ? execution.tool_call_parameters : execution.parameters;
265
+ const extensions = asObject(execution.parameters)?.runtime_extensions;
266
+ return {
267
+ toolName: typeof name === "string" && name.length > 0 ? name : null,
268
+ toolCallId: typeof callId === "string" ? callId : null,
269
+ arguments: args ?? null,
270
+ channelOwned: Array.isArray(extensions) && extensions.includes(MCP_APPROVAL_EXTENSION)
271
+ };
272
+ }
273
+ function describeDecision(record) {
274
+ const approved = record.data === true;
275
+ return {
276
+ approved,
277
+ reason: !approved && typeof record.data === "string" && record.data.length > 0 ? record.data : null,
278
+ decidedAt: record.date_submitted
279
+ };
280
+ }
281
+ var blank = (controlId) => ({
282
+ controlId,
283
+ toolName: null,
284
+ toolCallId: null,
285
+ arguments: null,
286
+ channelOwned: false,
287
+ requestedAt: null,
288
+ decision: null
289
+ });
290
+ function reduceApprovals(state, record) {
291
+ const isRequest = record.event_class === "HumanApprovalRequired";
292
+ const isResponse = record.event_class === "HumanApprovalRequiredResponse";
293
+ if (!isRequest && !isResponse || !record.control_id) return state;
294
+ const id = record.control_id;
295
+ const known = state.byId[id];
296
+ const current = known ?? blank(id);
297
+ const next = isRequest ? { ...current, ...describeRequest(record), requestedAt: record.date_submitted } : { ...current, decision: current.decision ?? describeDecision(record) };
298
+ return {
299
+ order: known ? state.order : [...state.order, id],
300
+ byId: { ...state.byId, [id]: next }
301
+ };
302
+ }
303
+ function foldApprovals(records) {
304
+ return records.reduce(reduceApprovals, initialApprovalsState());
305
+ }
306
+ function listApprovals(state) {
307
+ return state.order.map((id) => state.byId[id]);
308
+ }
309
+ function pendingApprovals(state) {
310
+ return listApprovals(state).filter((a) => a.decision === null);
311
+ }
239
312
  //# sourceMappingURL=index.js.map