@alquimia-ai/tools 2.4.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +529 -19
- package/dist/actions/index.d.mts +2 -2
- package/dist/actions/index.d.ts +2 -2
- package/dist/actions/index.js +1 -1
- package/dist/actions/index.js.map +1 -1
- package/dist/actions/index.mjs +1 -1
- package/dist/actions/index.mjs.map +1 -1
- package/dist/{actions-CZU_GRy5.d.mts → actions-BjDPJdyA.d.mts} +1 -1
- package/dist/{actions-B0hfoYRd.d.ts → actions-CP1d4Ye1.d.ts} +1 -1
- package/dist/adapters/index.d.mts +2 -2
- package/dist/adapters/index.d.ts +2 -2
- package/dist/adapters/index.js.map +1 -1
- package/dist/genui/index.d.mts +3 -3
- package/dist/genui/index.d.ts +3 -3
- package/dist/genui/index.js +9 -1
- package/dist/genui/index.js.map +1 -1
- package/dist/genui/index.mjs +9 -1
- package/dist/genui/index.mjs.map +1 -1
- package/dist/hooks/index.d.mts +10 -10
- package/dist/hooks/index.d.ts +10 -10
- package/dist/hooks/index.js +88 -12
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +88 -12
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/next/index.js +23 -6
- package/dist/next/index.js.map +1 -1
- package/dist/next/index.mjs +23 -6
- package/dist/next/index.mjs.map +1 -1
- package/dist/providers/index.d.mts +4 -4
- package/dist/providers/index.d.ts +4 -4
- package/dist/providers/index.js +111 -110
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/index.mjs +111 -110
- package/dist/providers/index.mjs.map +1 -1
- package/dist/{providers-BJTXCtI3.d.ts → providers-B4IOiGfr.d.mts} +8 -8
- package/dist/{providers-0Gi78uNQ.d.mts → providers-mx21gNgZ.d.ts} +8 -8
- package/dist/proxy.d.mts +4 -4
- package/dist/proxy.d.ts +4 -4
- package/dist/proxy.js +23 -6
- package/dist/proxy.js.map +1 -1
- package/dist/proxy.mjs +23 -6
- package/dist/proxy.mjs.map +1 -1
- package/dist/sdk/index.d.mts +39 -5
- package/dist/sdk/index.d.ts +39 -5
- package/dist/sdk/index.js +49 -6
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/index.mjs +49 -6
- package/dist/sdk/index.mjs.map +1 -1
- package/dist/services/index.d.mts +3 -3
- package/dist/services/index.d.ts +3 -3
- package/dist/services/index.js.map +1 -1
- package/dist/services/index.mjs.map +1 -1
- package/dist/type-61gaZga-.d.mts +356 -0
- package/dist/type-D-JaSMkV.d.ts +356 -0
- package/dist/types/index.d.mts +80 -304
- package/dist/types/index.d.ts +80 -304
- package/dist/types/index.js.map +1 -1
- package/dist/types/index.mjs.map +1 -1
- package/dist/{types-DnfWUE9V.d.mts → types-CMVbyEv8.d.mts} +3 -2
- package/dist/{types-DnfWUE9V.d.ts → types-CMVbyEv8.d.ts} +3 -2
- package/dist/types-lOliroPw.d.mts +111 -0
- package/dist/types-lOliroPw.d.ts +111 -0
- package/dist/utils/index.d.mts +2 -2
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +1 -1
- package/dist/utils/index.mjs.map +1 -1
- package/dist/worklog/index.d.mts +5 -2
- package/dist/worklog/index.d.ts +5 -2
- package/dist/worklog/index.js +22 -1
- package/dist/worklog/index.js.map +1 -1
- package/dist/worklog/index.mjs +22 -1
- package/dist/worklog/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/types-Dvu9y4WM.d.mts +0 -53
- package/dist/types-Dvu9y4WM.d.ts +0 -53
package/dist/sdk/index.js
CHANGED
|
@@ -42,6 +42,11 @@ var AlquimiaSDK = class {
|
|
|
42
42
|
this.sessionId = null;
|
|
43
43
|
// Internal subscription id from infer (`taskid` on the wire).
|
|
44
44
|
this.streamId = null;
|
|
45
|
+
// W3C traceparent for the current turn, so infer and stream share one trace.
|
|
46
|
+
this.traceParent = null;
|
|
47
|
+
// Registry version tag resolved by the runtime for this task (v0.5.1), so
|
|
48
|
+
// the tool-completion half of the turn lands on the same agentspace version.
|
|
49
|
+
this.versionTag = null;
|
|
45
50
|
this.tools = [];
|
|
46
51
|
this.extraInstructions = null;
|
|
47
52
|
this.assistantConfig = null;
|
|
@@ -122,6 +127,19 @@ var AlquimiaSDK = class {
|
|
|
122
127
|
this.userId = userId;
|
|
123
128
|
return this;
|
|
124
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Pin inference to a cached registry version. Sent as the `version_tag`
|
|
132
|
+
* query parameter, which `POST /event/infer/{assistant_id}` accepts from
|
|
133
|
+
* **runtime v0.5.2** onward; older runtimes ignore it.
|
|
134
|
+
*
|
|
135
|
+
* Works on every version: pass a versioned assistant ref
|
|
136
|
+
* (`<agentspace>/<assistant>[:<tag>]`) as the `assistantId` instead — the
|
|
137
|
+
* runtime parses the tag out of the path itself.
|
|
138
|
+
*/
|
|
139
|
+
withVersionTag(versionTag) {
|
|
140
|
+
this.versionTag = versionTag;
|
|
141
|
+
return this;
|
|
142
|
+
}
|
|
125
143
|
getEnforceCharacterization() {
|
|
126
144
|
return this.enforceCharacterization ?? true;
|
|
127
145
|
}
|
|
@@ -137,19 +155,29 @@ var AlquimiaSDK = class {
|
|
|
137
155
|
}
|
|
138
156
|
return this.whisperProvider.speechToText(audio);
|
|
139
157
|
}
|
|
140
|
-
async sendMessage(query,
|
|
158
|
+
async sendMessage(query, options = {}) {
|
|
141
159
|
if (!this.conversationId) {
|
|
142
160
|
throw new Error(
|
|
143
161
|
"Conversation not initialized. Call withConversationId() before sendMessage()"
|
|
144
162
|
);
|
|
145
163
|
}
|
|
146
|
-
const
|
|
164
|
+
const opts = typeof options === "string" ? { traceParent: options } : options;
|
|
165
|
+
if (query === void 0 && !opts.inputAudio) {
|
|
166
|
+
throw new Error(
|
|
167
|
+
"AlquimiaSDK: sendMessage needs a query, an inputAudio blob, or both"
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
const baseInferUrl = this.adapter.resolveInferUrl(this.assistantId);
|
|
171
|
+
const inferUrl = this.versionTag ? `${baseInferUrl}${baseInferUrl.includes("?") ? "&" : "?"}version_tag=${encodeURIComponent(this.versionTag)}` : baseInferUrl;
|
|
147
172
|
const adapterHeaders = this.adapter.getHeaders?.() ?? {};
|
|
148
173
|
const hasClientTools = Array.isArray(this.tools) && this.tools.length > 0;
|
|
149
174
|
const initMessage = {
|
|
150
|
-
query,
|
|
175
|
+
...query !== void 0 && { query },
|
|
151
176
|
session_id: this.conversationId,
|
|
152
177
|
user_id: this.userId,
|
|
178
|
+
...opts.inputAudio && { input_audio: opts.inputAudio },
|
|
179
|
+
// Only sent when set: the runtime defaults `output_audio` to true.
|
|
180
|
+
...opts.outputAudio !== void 0 && { output_audio: opts.outputAudio },
|
|
153
181
|
...this.extraInstructions && { extra_instructions: this.extraInstructions },
|
|
154
182
|
...this.assistantConfig && { config: this.assistantConfig },
|
|
155
183
|
...hasClientTools && {
|
|
@@ -162,12 +190,14 @@ var AlquimiaSDK = class {
|
|
|
162
190
|
const result = (await this.axiosInstance.post(inferUrl, initMessage, {
|
|
163
191
|
headers: {
|
|
164
192
|
"Content-Type": "application/json",
|
|
165
|
-
"x-trace-parent": traceParent
|
|
193
|
+
...opts.traceParent && { "x-trace-parent": opts.traceParent },
|
|
166
194
|
...adapterHeaders,
|
|
167
195
|
...this.buildIdentityHeaders()
|
|
168
196
|
}
|
|
169
197
|
})).data;
|
|
198
|
+
this.traceParent = opts.traceParent ?? null;
|
|
170
199
|
this.streamId = result.taskid ?? null;
|
|
200
|
+
this.versionTag = result.versiontag ?? this.versionTag;
|
|
171
201
|
this.attachmentResponses = result.attachments ?? [];
|
|
172
202
|
this.attachments = [];
|
|
173
203
|
return this;
|
|
@@ -194,6 +224,7 @@ var AlquimiaSDK = class {
|
|
|
194
224
|
...this.streamId && { taskid: this.streamId },
|
|
195
225
|
...this.conversationId && { sessionid: this.conversationId },
|
|
196
226
|
...this.userId && { userid: this.userId },
|
|
227
|
+
...this.versionTag && { versiontag: this.versionTag },
|
|
197
228
|
...adapterHeaders
|
|
198
229
|
};
|
|
199
230
|
await this.axiosInstance.post(url, response, { headers });
|
|
@@ -236,18 +267,23 @@ var AlquimiaSDK = class {
|
|
|
236
267
|
getAttachmentResponses() {
|
|
237
268
|
return this.attachmentResponses;
|
|
238
269
|
}
|
|
270
|
+
/**
|
|
271
|
+
* Upload a file into the session context. Returns the runtime {@link RuntimeBlob},
|
|
272
|
+
* which is what `sendMessage`'s `inputAudio` expects for audio inference.
|
|
273
|
+
*/
|
|
239
274
|
async uploadAttachment(file, _attachmentId) {
|
|
240
275
|
const url = this.adapter.resolveBlobUploadUrl();
|
|
241
276
|
const adapterHeaders = this.adapter.getHeaders?.() ?? {};
|
|
242
277
|
const formData = new FormData();
|
|
243
278
|
formData.append("file", file);
|
|
244
|
-
await this.axiosInstance.post(url, formData, {
|
|
279
|
+
const response = await this.axiosInstance.post(url, formData, {
|
|
245
280
|
headers: {
|
|
246
281
|
"Content-Type": "multipart/form-data",
|
|
247
282
|
...adapterHeaders,
|
|
248
283
|
...this.buildIdentityHeaders()
|
|
249
284
|
}
|
|
250
285
|
});
|
|
286
|
+
return response.data;
|
|
251
287
|
}
|
|
252
288
|
/**
|
|
253
289
|
* Identity headers (kebab-case) required by `/context/blob/upload` and
|
|
@@ -266,7 +302,10 @@ var AlquimiaSDK = class {
|
|
|
266
302
|
if (!this.streamId) {
|
|
267
303
|
throw new Error("Stream ID not initialized. Call sendMessage() first");
|
|
268
304
|
}
|
|
269
|
-
|
|
305
|
+
const url = this.adapter.resolveStreamUrl(this.streamId);
|
|
306
|
+
if (!this.traceParent) return url;
|
|
307
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
308
|
+
return `${url}${separator}trace_parent=${encodeURIComponent(this.traceParent)}`;
|
|
270
309
|
}
|
|
271
310
|
getStreamId() {
|
|
272
311
|
return this.streamId;
|
|
@@ -275,6 +314,10 @@ var AlquimiaSDK = class {
|
|
|
275
314
|
getTaskId() {
|
|
276
315
|
return this.streamId;
|
|
277
316
|
}
|
|
317
|
+
/** Registry version tag resolved by the runtime for the current task, if any. */
|
|
318
|
+
getVersionTag() {
|
|
319
|
+
return this.versionTag;
|
|
320
|
+
}
|
|
278
321
|
};
|
|
279
322
|
var alquimia_sdk_default = AlquimiaSDK;
|
|
280
323
|
//# sourceMappingURL=index.js.map
|
package/dist/sdk/index.js.map
CHANGED
|
@@ -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 { AttachmentPayload, TTSResult, type CommonAttributes } from '../types';\nimport type { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters';\nimport type { ToolExecutionResponse } from '../genui/types';\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 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 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(query: string, traceParent?: string): Promise<AlquimiaSDK> {\n if (!this.conversationId) {\n throw new Error(\n 'Conversation not initialized. Call withConversationId() before sendMessage()'\n );\n }\n\n const inferUrl = this.adapter.resolveInferUrl(this.assistantId);\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,\n session_id: this.conversationId,\n user_id: this.userId,\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 'x-trace-parent': traceParent || '',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n })\n ).data as CommonAttributes;\n\n this.streamId = result.taskid ?? 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 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 ...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 async uploadAttachment(file: File, _attachmentId?: string): Promise<void> {\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 await this.axiosInstance.post(url, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n });\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 return this.adapter.resolveStreamUrl(this.streamId);\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\nexport default AlquimiaSDK;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAqC;AAYrC,IAAM,cAAN,MAAkB;AAAA,EAqBhB,YACE,aACA,SACA,UAA8B,CAAC,GAC/B;AArBF,SAAQ,iBAAgC;AACxC,SAAQ,YAA2B;AAEnC;AAAA,SAAQ,WAA0B;AAClC,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,MAA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,OAAO,IAAI;AAAA,EAC1D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,yBAAmC;AACjC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,MAAM,iBAAiB,MAAY,eAAuC;AAExE,UAAM,MAAM,KAAK,QAAQ,qBAAqB;AAC9C,UAAM,iBAAiB,KAAK,QAAQ,aAAa,KAAK,CAAC;AACvD,UAAM,WAAW,IAAI,SAAS;AAC9B,aAAS,OAAO,QAAQ,IAAI;AAC5B,UAAM,KAAK,cAAc,KAAK,KAAK,UAAU;AAAA,MAC3C,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,GAAG;AAAA,QACH,GAAG,KAAK,qBAAqB;AAAA,MAC/B;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,uBAA+C;AACrD,UAAM,UAAkC;AAAA,MACtC,gBAAgB,KAAK;AAAA,IACvB;AACA,QAAI,KAAK,eAAgB,SAAQ,YAAY,IAAI,KAAK;AACtD,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;AACA,WAAO,KAAK,QAAQ,iBAAiB,KAAK,QAAQ;AAAA,EACpD;AAAA,EAEA,cAA6B;AAC3B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,YAA2B;AACzB,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} 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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P,gBAAgB;AAAA,QAChB,GAAG;AAAA,QACH,GAAG,KAAK,qBAAqB;AAAA,MAC/B;AAAA,IACF,CAAC;AACD,WAAO,SAAS;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,uBAA+C;AACrD,UAAM,UAAkC;AAAA,MACtC,gBAAgB,KAAK;AAAA,IACvB;AACA,QAAI,KAAK,eAAgB,SAAQ,YAAY,IAAI,KAAK;AACtD,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"]}
|
package/dist/sdk/index.mjs
CHANGED
|
@@ -6,6 +6,11 @@ var AlquimiaSDK = class {
|
|
|
6
6
|
this.sessionId = null;
|
|
7
7
|
// Internal subscription id from infer (`taskid` on the wire).
|
|
8
8
|
this.streamId = null;
|
|
9
|
+
// W3C traceparent for the current turn, so infer and stream share one trace.
|
|
10
|
+
this.traceParent = null;
|
|
11
|
+
// Registry version tag resolved by the runtime for this task (v0.5.1), so
|
|
12
|
+
// the tool-completion half of the turn lands on the same agentspace version.
|
|
13
|
+
this.versionTag = null;
|
|
9
14
|
this.tools = [];
|
|
10
15
|
this.extraInstructions = null;
|
|
11
16
|
this.assistantConfig = null;
|
|
@@ -86,6 +91,19 @@ var AlquimiaSDK = class {
|
|
|
86
91
|
this.userId = userId;
|
|
87
92
|
return this;
|
|
88
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Pin inference to a cached registry version. Sent as the `version_tag`
|
|
96
|
+
* query parameter, which `POST /event/infer/{assistant_id}` accepts from
|
|
97
|
+
* **runtime v0.5.2** onward; older runtimes ignore it.
|
|
98
|
+
*
|
|
99
|
+
* Works on every version: pass a versioned assistant ref
|
|
100
|
+
* (`<agentspace>/<assistant>[:<tag>]`) as the `assistantId` instead — the
|
|
101
|
+
* runtime parses the tag out of the path itself.
|
|
102
|
+
*/
|
|
103
|
+
withVersionTag(versionTag) {
|
|
104
|
+
this.versionTag = versionTag;
|
|
105
|
+
return this;
|
|
106
|
+
}
|
|
89
107
|
getEnforceCharacterization() {
|
|
90
108
|
return this.enforceCharacterization ?? true;
|
|
91
109
|
}
|
|
@@ -101,19 +119,29 @@ var AlquimiaSDK = class {
|
|
|
101
119
|
}
|
|
102
120
|
return this.whisperProvider.speechToText(audio);
|
|
103
121
|
}
|
|
104
|
-
async sendMessage(query,
|
|
122
|
+
async sendMessage(query, options = {}) {
|
|
105
123
|
if (!this.conversationId) {
|
|
106
124
|
throw new Error(
|
|
107
125
|
"Conversation not initialized. Call withConversationId() before sendMessage()"
|
|
108
126
|
);
|
|
109
127
|
}
|
|
110
|
-
const
|
|
128
|
+
const opts = typeof options === "string" ? { traceParent: options } : options;
|
|
129
|
+
if (query === void 0 && !opts.inputAudio) {
|
|
130
|
+
throw new Error(
|
|
131
|
+
"AlquimiaSDK: sendMessage needs a query, an inputAudio blob, or both"
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
const baseInferUrl = this.adapter.resolveInferUrl(this.assistantId);
|
|
135
|
+
const inferUrl = this.versionTag ? `${baseInferUrl}${baseInferUrl.includes("?") ? "&" : "?"}version_tag=${encodeURIComponent(this.versionTag)}` : baseInferUrl;
|
|
111
136
|
const adapterHeaders = this.adapter.getHeaders?.() ?? {};
|
|
112
137
|
const hasClientTools = Array.isArray(this.tools) && this.tools.length > 0;
|
|
113
138
|
const initMessage = {
|
|
114
|
-
query,
|
|
139
|
+
...query !== void 0 && { query },
|
|
115
140
|
session_id: this.conversationId,
|
|
116
141
|
user_id: this.userId,
|
|
142
|
+
...opts.inputAudio && { input_audio: opts.inputAudio },
|
|
143
|
+
// Only sent when set: the runtime defaults `output_audio` to true.
|
|
144
|
+
...opts.outputAudio !== void 0 && { output_audio: opts.outputAudio },
|
|
117
145
|
...this.extraInstructions && { extra_instructions: this.extraInstructions },
|
|
118
146
|
...this.assistantConfig && { config: this.assistantConfig },
|
|
119
147
|
...hasClientTools && {
|
|
@@ -126,12 +154,14 @@ var AlquimiaSDK = class {
|
|
|
126
154
|
const result = (await this.axiosInstance.post(inferUrl, initMessage, {
|
|
127
155
|
headers: {
|
|
128
156
|
"Content-Type": "application/json",
|
|
129
|
-
"x-trace-parent": traceParent
|
|
157
|
+
...opts.traceParent && { "x-trace-parent": opts.traceParent },
|
|
130
158
|
...adapterHeaders,
|
|
131
159
|
...this.buildIdentityHeaders()
|
|
132
160
|
}
|
|
133
161
|
})).data;
|
|
162
|
+
this.traceParent = opts.traceParent ?? null;
|
|
134
163
|
this.streamId = result.taskid ?? null;
|
|
164
|
+
this.versionTag = result.versiontag ?? this.versionTag;
|
|
135
165
|
this.attachmentResponses = result.attachments ?? [];
|
|
136
166
|
this.attachments = [];
|
|
137
167
|
return this;
|
|
@@ -158,6 +188,7 @@ var AlquimiaSDK = class {
|
|
|
158
188
|
...this.streamId && { taskid: this.streamId },
|
|
159
189
|
...this.conversationId && { sessionid: this.conversationId },
|
|
160
190
|
...this.userId && { userid: this.userId },
|
|
191
|
+
...this.versionTag && { versiontag: this.versionTag },
|
|
161
192
|
...adapterHeaders
|
|
162
193
|
};
|
|
163
194
|
await this.axiosInstance.post(url, response, { headers });
|
|
@@ -200,18 +231,23 @@ var AlquimiaSDK = class {
|
|
|
200
231
|
getAttachmentResponses() {
|
|
201
232
|
return this.attachmentResponses;
|
|
202
233
|
}
|
|
234
|
+
/**
|
|
235
|
+
* Upload a file into the session context. Returns the runtime {@link RuntimeBlob},
|
|
236
|
+
* which is what `sendMessage`'s `inputAudio` expects for audio inference.
|
|
237
|
+
*/
|
|
203
238
|
async uploadAttachment(file, _attachmentId) {
|
|
204
239
|
const url = this.adapter.resolveBlobUploadUrl();
|
|
205
240
|
const adapterHeaders = this.adapter.getHeaders?.() ?? {};
|
|
206
241
|
const formData = new FormData();
|
|
207
242
|
formData.append("file", file);
|
|
208
|
-
await this.axiosInstance.post(url, formData, {
|
|
243
|
+
const response = await this.axiosInstance.post(url, formData, {
|
|
209
244
|
headers: {
|
|
210
245
|
"Content-Type": "multipart/form-data",
|
|
211
246
|
...adapterHeaders,
|
|
212
247
|
...this.buildIdentityHeaders()
|
|
213
248
|
}
|
|
214
249
|
});
|
|
250
|
+
return response.data;
|
|
215
251
|
}
|
|
216
252
|
/**
|
|
217
253
|
* Identity headers (kebab-case) required by `/context/blob/upload` and
|
|
@@ -230,7 +266,10 @@ var AlquimiaSDK = class {
|
|
|
230
266
|
if (!this.streamId) {
|
|
231
267
|
throw new Error("Stream ID not initialized. Call sendMessage() first");
|
|
232
268
|
}
|
|
233
|
-
|
|
269
|
+
const url = this.adapter.resolveStreamUrl(this.streamId);
|
|
270
|
+
if (!this.traceParent) return url;
|
|
271
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
272
|
+
return `${url}${separator}trace_parent=${encodeURIComponent(this.traceParent)}`;
|
|
234
273
|
}
|
|
235
274
|
getStreamId() {
|
|
236
275
|
return this.streamId;
|
|
@@ -239,6 +278,10 @@ var AlquimiaSDK = class {
|
|
|
239
278
|
getTaskId() {
|
|
240
279
|
return this.streamId;
|
|
241
280
|
}
|
|
281
|
+
/** Registry version tag resolved by the runtime for the current task, if any. */
|
|
282
|
+
getVersionTag() {
|
|
283
|
+
return this.versionTag;
|
|
284
|
+
}
|
|
242
285
|
};
|
|
243
286
|
var alquimia_sdk_default = AlquimiaSDK;
|
|
244
287
|
export {
|
package/dist/sdk/index.mjs.map
CHANGED
|
@@ -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 { AttachmentPayload, TTSResult, type CommonAttributes } from '../types';\nimport type { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters';\nimport type { ToolExecutionResponse } from '../genui/types';\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 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 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(query: string, traceParent?: string): Promise<AlquimiaSDK> {\n if (!this.conversationId) {\n throw new Error(\n 'Conversation not initialized. Call withConversationId() before sendMessage()'\n );\n }\n\n const inferUrl = this.adapter.resolveInferUrl(this.assistantId);\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,\n session_id: this.conversationId,\n user_id: this.userId,\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 'x-trace-parent': traceParent || '',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n })\n ).data as CommonAttributes;\n\n this.streamId = result.taskid ?? 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 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 ...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 async uploadAttachment(file: File, _attachmentId?: string): Promise<void> {\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 await this.axiosInstance.post(url, formData, {\n headers: {\n 'Content-Type': 'multipart/form-data',\n ...adapterHeaders,\n ...this.buildIdentityHeaders(),\n },\n });\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 return this.adapter.resolveStreamUrl(this.streamId);\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\nexport default AlquimiaSDK;\n"],"mappings":";AAAA,OAAO,WAA8B;AAYrC,IAAM,cAAN,MAAkB;AAAA,EAqBhB,YACE,aACA,SACA,UAA8B,CAAC,GAC/B;AArBF,SAAQ,iBAAgC;AACxC,SAAQ,YAA2B;AAEnC;AAAA,SAAQ,WAA0B;AAClC,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,MAAM,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,SAAK,eAAe,KAAK,aAAa,KAAK,I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iB,KAAK,QAAQ,aAAa,KAAK,CAAC;AACvD,UAAM,WAAW,IAAI,SAAS;AAC9B,aAAS,OAAO,QAAQ,IAAI;AAC5B,UAAM,KAAK,cAAc,KAAK,KAAK,UAAU;AAAA,MAC3C,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,GAAG;AAAA,QACH,GAAG,KAAK,qBAAqB;AAAA,MAC/B;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,uBAA+C;AACrD,UAAM,UAAkC;AAAA,MACtC,gBAAgB,KAAK;AAAA,IACvB;AACA,QAAI,KAAK,eAAgB,SAAQ,YAAY,IAAI,KAAK;AACtD,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;AACA,WAAO,KAAK,QAAQ,iBAAiB,KAAK,QAAQ;AAAA,EACpD;AAAA,EAEA,cAA6B;AAC3B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,YAA2B;AACzB,WAAO,KAAK;AAAA,EACd;AACF;AAEA,IAAO,uBAAQ;","names":[]}
|
|
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,UAAU;AACf,SAAK,0BAA0B,QAAQ,2BAA2B;AAElE,SAAK,gBAAgB,MAAM,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,SAAK,eAAe,KAAK,aAAa,KAAK,IAAI;AAAA,EACjD;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AC3C,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":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Transaction } from '@elastic/apm-rum';
|
|
2
|
-
import { ApmSpan } from '../
|
|
2
|
+
import { A as ApmSpan } from '../type-61gaZga-.mjs';
|
|
3
3
|
import 'ai';
|
|
4
|
-
import '../types-
|
|
4
|
+
import '../types-CMVbyEv8.mjs';
|
|
5
5
|
|
|
6
6
|
interface APMInitializerProps {
|
|
7
7
|
serviceName: string;
|
|
@@ -11,7 +11,7 @@ interface APMInitializerProps {
|
|
|
11
11
|
environment: string;
|
|
12
12
|
ignoreUrls?: Array<string | RegExp>;
|
|
13
13
|
}
|
|
14
|
-
type LabelValue = string | number | boolean
|
|
14
|
+
type LabelValue = string | number | boolean;
|
|
15
15
|
interface TransactionLabels {
|
|
16
16
|
[key: string]: LabelValue;
|
|
17
17
|
}
|
package/dist/services/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Transaction } from '@elastic/apm-rum';
|
|
2
|
-
import { ApmSpan } from '../
|
|
2
|
+
import { A as ApmSpan } from '../type-D-JaSMkV.js';
|
|
3
3
|
import 'ai';
|
|
4
|
-
import '../types-
|
|
4
|
+
import '../types-CMVbyEv8.js';
|
|
5
5
|
|
|
6
6
|
interface APMInitializerProps {
|
|
7
7
|
serviceName: string;
|
|
@@ -11,7 +11,7 @@ interface APMInitializerProps {
|
|
|
11
11
|
environment: string;
|
|
12
12
|
ignoreUrls?: Array<string | RegExp>;
|
|
13
13
|
}
|
|
14
|
-
type LabelValue = string | number | boolean
|
|
14
|
+
type LabelValue = string | number | boolean;
|
|
15
15
|
interface TransactionLabels {
|
|
16
16
|
[key: string]: LabelValue;
|
|
17
17
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/index.ts","../../src/services/apm/elastic-apm.ts"],"sourcesContent":["export * from './apm'","'use client'\n\nimport { useEffect } from 'react'\nimport { init as initApm, apm, Transaction } from '@elastic/apm-rum'\nimport { ApmSpan } from '../../types/type'\n\ninterface APMInitializerProps {\n serviceName: string\n serverUrl?: string\n serverUrlPrefix?: string | undefined\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'\n environment: string\n ignoreUrls?: Array<string | RegExp>\n}\n\ntype LabelValue = string | number | boolean
|
|
1
|
+
{"version":3,"sources":["../../src/services/index.ts","../../src/services/apm/elastic-apm.ts"],"sourcesContent":["export * from './apm'","'use client'\n\nimport { useEffect } from 'react'\nimport { init as initApm, apm, Transaction } from '@elastic/apm-rum'\nimport { ApmSpan } from '../../types/type'\n\ninterface APMInitializerProps {\n serviceName: string\n serverUrl?: string\n serverUrlPrefix?: string | undefined\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'\n environment: string\n ignoreUrls?: Array<string | RegExp>\n}\n\ntype LabelValue = string | number | boolean;\n\ninterface TransactionLabels {\n [key: string]: LabelValue;\n}\n\nexport function APMInitializer({\n serviceName,\n serverUrl,\n serverUrlPrefix = undefined,\n logLevel = 'warn',\n environment,\n ignoreUrls = []\n}: APMInitializerProps) {\n \n useEffect(() => {\n const serviceUrl = !serverUrl ? (typeof window !== 'undefined' ? window.location.origin : '') : serverUrl\n initApm({\n serviceName: serviceName,\n serverUrl: serviceUrl,\n serverUrlPrefix: serverUrlPrefix,\n serviceVersion: '1.0.0',\n logLevel: logLevel,\n environment: environment,\n ignoreTransactions: ignoreUrls\n })\n }, [])\n \n return null\n}\n\n\nexport async function handleApmTransaction(\n name: string,\n type: string,\n labels: TransactionLabels,\n callback: () => Promise<void> | void\n) {\n const transaction = apm.startTransaction(name, type);\n\n try {\n transaction?.addLabels(labels as Record<string, LabelValue>);\n await callback();\n } catch (error) {\n apm.captureError(error as Error);\n } finally {\n transaction?.end();\n }\n}\n\nexport function traceError(\n error: string | Error,\n labels?: TransactionLabels,\n customMessage?: string\n) {\n try {\n const errorObject =\n error instanceof Error\n ? error\n : new Error(customMessage ?? String(error));\n\n if (labels) {\n apm.addLabels(labels as Record<string, LabelValue>);\n }\n\n apm.captureError(errorObject);\n } catch (e) {\n throw new Error(\"Failed to capture error in APM:\", e as Error);\n }\n}\n\nexport const startManagedTransaction = (\n name: string,\n type: string = 'http-request',\n spanName: string,\n spanType: string = 'external.http'\n): { transaction: Transaction | undefined, span: ApmSpan | undefined, traceParentId: string | undefined } => {\n const transaction = apm.startTransaction(name, type, { managed: true });\n const span: ApmSpan | undefined = transaction?.startSpan(spanName, spanType);\n \n const traceParentId = span ? createTraceParentId(span.traceId || '', span.id || '') : undefined;\n \n return { transaction, span, traceParentId };\n};\n\nconst createTraceParentId = (traceId: string, spanId: string) => {\n return `00-${traceId}-${spanId}-01`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,mBAA0B;AAC1B,qBAAkD;AAkB3C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX;AAAA,EACA,aAAa,CAAC;AAChB,GAAwB;A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version":3,"sources":["../../src/services/apm/elastic-apm.ts"],"sourcesContent":["'use client'\n\nimport { useEffect } from 'react'\nimport { init as initApm, apm, Transaction } from '@elastic/apm-rum'\nimport { ApmSpan } from '../../types/type'\n\ninterface APMInitializerProps {\n serviceName: string\n serverUrl?: string\n serverUrlPrefix?: string | undefined\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'\n environment: string\n ignoreUrls?: Array<string | RegExp>\n}\n\ntype LabelValue = string | number | boolean
|
|
1
|
+
{"version":3,"sources":["../../src/services/apm/elastic-apm.ts"],"sourcesContent":["'use client'\n\nimport { useEffect } from 'react'\nimport { init as initApm, apm, Transaction } from '@elastic/apm-rum'\nimport { ApmSpan } from '../../types/type'\n\ninterface APMInitializerProps {\n serviceName: string\n serverUrl?: string\n serverUrlPrefix?: string | undefined\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'\n environment: string\n ignoreUrls?: Array<string | RegExp>\n}\n\ntype LabelValue = string | number | boolean;\n\ninterface TransactionLabels {\n [key: string]: LabelValue;\n}\n\nexport function APMInitializer({\n serviceName,\n serverUrl,\n serverUrlPrefix = undefined,\n logLevel = 'warn',\n environment,\n ignoreUrls = []\n}: APMInitializerProps) {\n \n useEffect(() => {\n const serviceUrl = !serverUrl ? (typeof window !== 'undefined' ? window.location.origin : '') : serverUrl\n initApm({\n serviceName: serviceName,\n serverUrl: serviceUrl,\n serverUrlPrefix: serverUrlPrefix,\n serviceVersion: '1.0.0',\n logLevel: logLevel,\n environment: environment,\n ignoreTransactions: ignoreUrls\n })\n }, [])\n \n return null\n}\n\n\nexport async function handleApmTransaction(\n name: string,\n type: string,\n labels: TransactionLabels,\n callback: () => Promise<void> | void\n) {\n const transaction = apm.startTransaction(name, type);\n\n try {\n transaction?.addLabels(labels as Record<string, LabelValue>);\n await callback();\n } catch (error) {\n apm.captureError(error as Error);\n } finally {\n transaction?.end();\n }\n}\n\nexport function traceError(\n error: string | Error,\n labels?: TransactionLabels,\n customMessage?: string\n) {\n try {\n const errorObject =\n error instanceof Error\n ? error\n : new Error(customMessage ?? String(error));\n\n if (labels) {\n apm.addLabels(labels as Record<string, LabelValue>);\n }\n\n apm.captureError(errorObject);\n } catch (e) {\n throw new Error(\"Failed to capture error in APM:\", e as Error);\n }\n}\n\nexport const startManagedTransaction = (\n name: string,\n type: string = 'http-request',\n spanName: string,\n spanType: string = 'external.http'\n): { transaction: Transaction | undefined, span: ApmSpan | undefined, traceParentId: string | undefined } => {\n const transaction = apm.startTransaction(name, type, { managed: true });\n const span: ApmSpan | undefined = transaction?.startSpan(spanName, spanType);\n \n const traceParentId = span ? createTraceParentId(span.traceId || '', span.id || '') : undefined;\n \n return { transaction, span, traceParentId };\n};\n\nconst createTraceParentId = (traceId: string, spanId: string) => {\n return `00-${traceId}-${spanId}-01`;\n}\n"],"mappings":";AAEA,SAAS,iBAAiB;AAC1B,SAAS,QAAQ,SAAS,WAAwB;AAkB3C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX;AAAA,EACA,aAAa,CAAC;AAChB,GAAwB;AAEtB,YAAU,MAAM;AACd,UAAM,aAAa,CAAC,YAAa,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS,KAAM;AAChG,YAAQ;AAAA,MACN;AAAA,MACA,WAAW;AAAA,MACX;AAAA,MACA,gBAAgB;AAAA,MAChB;AAAA,MACA;AAAA,MACA,oBAAoB;AAAA,IACtB,CAAC;AAAA,EACH,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;AAGA,eAAsB,qBACpB,MACA,MACA,QACA,UACA;AACA,QAAM,cAAc,IAAI,iBAAiB,MAAM,IAAI;AAEnD,MAAI;AACF,iBAAa,UAAU,MAAoC;AAC3D,UAAM,SAAS;AAAA,EACjB,SAAS,OAAO;AACd,QAAI,aAAa,KAAc;AAAA,EACjC,UAAE;AACA,iBAAa,IAAI;AAAA,EACnB;AACF;AAEO,SAAS,WACd,OACA,QAC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