@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
package/dist/proxy.js CHANGED
@@ -48,13 +48,56 @@ function pickTraceHeader(request) {
48
48
  if (fromQuery) return { "x-trace-parent": fromQuery };
49
49
  return {};
50
50
  }
51
+ var DECISION_HEADER_NAMES = [
52
+ "taskid",
53
+ "parenttaskid",
54
+ "sessionid",
55
+ "userid",
56
+ "assistantid",
57
+ "agentspaceid",
58
+ "channelid",
59
+ "depth",
60
+ // Runtime v0.5.1: `CommonAttributes.version_tag` (alias `versiontag`)
61
+ // pins the decision to the agentspace version that ran the turn.
62
+ "versiontag"
63
+ ];
51
64
  function createAlquimiaProxyHandler(config) {
52
65
  const baseUrl = config.assistantBaseUrl.replace(/\/$/, "");
53
66
  const inferRoute = config.inferRoute ?? "event/infer";
54
67
  const streamRoute = config.streamRoute ?? "event/stream";
55
68
  const blobUploadRoute = config.blobUploadRoute ?? "context/blob/upload";
56
69
  const toolCompletionRoute = config.toolCompletionRoute ?? "event/tool-completion";
70
+ const toolApprovalRoute = config.toolApprovalRoute ?? "event/tool-approval";
57
71
  const authHeader = { Authorization: `Bearer ${config.apiKey}` };
72
+ async function forwardDecision(request, route, name) {
73
+ try {
74
+ const body = await request.text();
75
+ const headers = {
76
+ "Content-Type": "application/json",
77
+ ...authHeader
78
+ };
79
+ for (const name2 of DECISION_HEADER_NAMES) {
80
+ const value = request.headers.get(name2);
81
+ if (value) headers[name2] = value;
82
+ }
83
+ Object.assign(headers, pickTraceHeader(request));
84
+ const response = await fetch(`${baseUrl}/${route}`, {
85
+ method: "POST",
86
+ headers,
87
+ body
88
+ });
89
+ return new Response(await response.text(), {
90
+ status: response.status,
91
+ headers: { "Content-Type": "application/json" }
92
+ });
93
+ } catch (error) {
94
+ console.error(`AlquimiaProxy ${name} exception:`, error);
95
+ return new Response(
96
+ JSON.stringify({ error: `Failed to forward ${name} request` }),
97
+ { status: 500, headers: { "Content-Type": "application/json" } }
98
+ );
99
+ }
100
+ }
58
101
  return {
59
102
  async handleInfer(request, pathSuffix) {
60
103
  try {
@@ -182,46 +225,10 @@ function createAlquimiaProxyHandler(config) {
182
225
  }
183
226
  },
184
227
  async handleToolCompletion(request) {
185
- try {
186
- const body = await request.text();
187
- const headers = {
188
- "Content-Type": "application/json",
189
- ...authHeader
190
- };
191
- const CORRELATION_HEADERS = [
192
- "taskid",
193
- "parenttaskid",
194
- "sessionid",
195
- "userid",
196
- "assistantid",
197
- "agentspaceid",
198
- "channelid",
199
- "depth",
200
- // Runtime v0.5.1: `CommonAttributes.version_tag` (alias `versiontag`)
201
- // pins the tool-completion to the agentspace version that ran the turn.
202
- "versiontag"
203
- ];
204
- for (const name of CORRELATION_HEADERS) {
205
- const value = request.headers.get(name);
206
- if (value) headers[name] = value;
207
- }
208
- Object.assign(headers, pickTraceHeader(request));
209
- const response = await fetch(`${baseUrl}/${toolCompletionRoute}`, {
210
- method: "POST",
211
- headers,
212
- body
213
- });
214
- return new Response(await response.text(), {
215
- status: response.status,
216
- headers: { "Content-Type": "application/json" }
217
- });
218
- } catch (error) {
219
- console.error("AlquimiaProxy handleToolCompletion exception:", error);
220
- return new Response(
221
- JSON.stringify({ error: "Failed to forward tool-completion request" }),
222
- { status: 500, headers: { "Content-Type": "application/json" } }
223
- );
224
- }
228
+ return forwardDecision(request, toolCompletionRoute, "tool-completion");
229
+ },
230
+ async handleToolApproval(request) {
231
+ return forwardDecision(request, toolApprovalRoute, "tool-approval");
225
232
  }
226
233
  };
227
234
  }
package/dist/proxy.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["export interface ProxyConfig {\n assistantBaseUrl: string;\n apiKey: string;\n inferRoute?: string; // default: 'event/infer'\n streamRoute?: string; // default: 'event/stream'\n blobUploadRoute?: string; // default: 'context/blob/upload'\n toolCompletionRoute?: string; // default: 'event/tool-completion'\n}\n\nexport interface AlquimiaProxyHandler {\n handleInfer(_request: Request, _pathSuffix: string): Promise<Response>;\n handleStream(_request: Request, _pathSuffix: string): Promise<Response>;\n handleBlobUpload(_request: Request): Promise<Response>;\n handleToolCompletion(_request: Request): Promise<Response>;\n}\n\nconst IDENTITY_HEADER_NAMES = [\n 'task-id',\n 'parent-task-id',\n 'session-id',\n 'user-id',\n 'assistant-id',\n 'agentspace-id',\n 'channel-id',\n 'depth',\n] as const;\n\nfunction pickIdentityHeaders(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of IDENTITY_HEADER_NAMES) {\n const value = request.headers.get(name);\n if (value) out[name] = value;\n }\n return out;\n}\n\n/**\n * Trace-context propagation. The proxy builds a fresh request against the\n * runtime, so anything the caller set is dropped unless it is copied over\n * explicitly — which is how `x-trace-parent` stopped reaching the runtime when\n * the direct-to-runtime client was replaced by this proxy.\n *\n * The header is the transport wherever the caller can set one. `EventSource`\n * cannot, so the stream route also accepts the same value as a `trace_parent`\n * query param.\n */\nfunction pickTraceHeader(request: Request): Record<string, string> {\n const fromHeader = request.headers.get('x-trace-parent');\n if (fromHeader) return { 'x-trace-parent': fromHeader };\n\n const fromQuery = new URL(request.url).searchParams.get('trace_parent');\n if (fromQuery) return { 'x-trace-parent': fromQuery };\n\n return {};\n}\n\nexport function createAlquimiaProxyHandler(config: ProxyConfig): AlquimiaProxyHandler {\n const baseUrl = config.assistantBaseUrl.replace(/\\/$/, '');\n const inferRoute = config.inferRoute ?? 'event/infer';\n const streamRoute = config.streamRoute ?? 'event/stream';\n const blobUploadRoute = config.blobUploadRoute ?? 'context/blob/upload';\n const toolCompletionRoute = config.toolCompletionRoute ?? 'event/tool-completion';\n const authHeader = { Authorization: `Bearer ${config.apiKey}` };\n\n return {\n async handleInfer(request: Request, pathSuffix: string): Promise<Response> {\n try {\n const body = await request.json();\n const url = new URL(request.url);\n const querySuffix = url.searchParams.toString()\n ? `?${url.searchParams.toString()}`\n : '';\n const slug = pathSuffix.replace(/^\\/+|\\/+$/g, '');\n const targetUrl = `${baseUrl}/${inferRoute}/${slug}${querySuffix}`;\n\n\n const response = await fetch(targetUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...authHeader,\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorJson = await response.json().catch(() => ({}));\n console.error('AlquimiaProxy handleInfer error:', {\n status: response.status,\n statusText: response.statusText,\n body: errorJson,\n });\n return new Response(\n JSON.stringify({\n status: response.status,\n statusText: response.statusText,\n ...errorJson,\n }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n return new Response(response.body, {\n status: 200,\n headers: {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Content-Encoding',\n },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleInfer exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward infer request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleStream(request: Request, pathSuffix: string): Promise<Response> {\n try {\n const targetUrl = `${baseUrl}/${streamRoute}/${pathSuffix}`;\n\n const response = await fetch(targetUrl, {\n headers: {\n 'Content-Type': 'application/json',\n ...authHeader,\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n });\n\n if (!response.ok) {\n const errorJson = await response.json().catch(() => ({}));\n console.error('AlquimiaProxy handleStream error:', {\n status: response.status,\n statusText: response.statusText,\n body: errorJson,\n });\n return new Response(\n JSON.stringify({\n error: errorJson.message || response.statusText || 'Failed to forward stream',\n ...errorJson,\n }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n return new Response(response.body, {\n status: 200,\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleStream exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward stream request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleBlobUpload(request: Request): Promise<Response> {\n try {\n const targetUrl = `${baseUrl}/${blobUploadRoute}`;\n const contentType = request.headers.get('Content-Type') ?? '';\n\n const response = await fetch(targetUrl, {\n method: 'POST',\n headers: {\n ...authHeader,\n ...(contentType && { 'Content-Type': contentType }),\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n body: request.body,\n duplex: 'half',\n } as RequestInit);\n\n if (!response.ok) {\n return new Response(\n JSON.stringify({ error: 'Failed to upload blob', status: response.status }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n const responseText = await response.text();\n return new Response(responseText, {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleBlobUpload exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward blob upload request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleToolCompletion(request: Request): Promise<Response> {\n try {\n const body = await request.text();\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...authHeader,\n };\n // Forward the runtime's tool-completion correlation headers verbatim\n // (non-hyphenated names, per the runtime OpenAPI). These route the\n // completion to the parked task so the SSE stream resumes.\n const CORRELATION_HEADERS = [\n 'taskid',\n 'parenttaskid',\n 'sessionid',\n 'userid',\n 'assistantid',\n 'agentspaceid',\n 'channelid',\n 'depth',\n // Runtime v0.5.1: `CommonAttributes.version_tag` (alias `versiontag`)\n // pins the tool-completion to the agentspace version that ran the turn.\n 'versiontag',\n ];\n for (const name of CORRELATION_HEADERS) {\n const value = request.headers.get(name);\n if (value) headers[name] = value;\n }\n Object.assign(headers, pickTraceHeader(request));\n\n const response = await fetch(`${baseUrl}/${toolCompletionRoute}`, {\n method: 'POST',\n headers,\n body,\n });\n\n return new Response(await response.text(), {\n status: response.status,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleToolCompletion exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward tool-completion request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,oBAAoB,SAA0C;AACrE,QAAM,MAA8B,CAAC;AACrC,aAAW,QAAQ,uBAAuB;AACxC,UAAM,QAAQ,QAAQ,QAAQ,IAAI,IAAI;AACtC,QAAI,MAAO,KAAI,IAAI,IAAI;AAAA,EACzB;AACA,SAAO;AACT;AAYA,SAAS,gBAAgB,SAA0C;AACjE,QAAM,aAAa,QAAQ,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 {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["export interface ProxyConfig {\n assistantBaseUrl: string;\n apiKey: string;\n inferRoute?: string; // default: 'event/infer'\n streamRoute?: string; // default: 'event/stream'\n blobUploadRoute?: string; // default: 'context/blob/upload'\n toolCompletionRoute?: string; // default: 'event/tool-completion'\n toolApprovalRoute?: string; // default: 'event/tool-approval'\n}\n\nexport interface AlquimiaProxyHandler {\n handleInfer(_request: Request, _pathSuffix: string): Promise<Response>;\n handleStream(_request: Request, _pathSuffix: string): Promise<Response>;\n handleBlobUpload(_request: Request): Promise<Response>;\n handleToolCompletion(_request: Request): Promise<Response>;\n handleToolApproval(_request: Request): Promise<Response>;\n}\n\nconst IDENTITY_HEADER_NAMES = [\n 'task-id',\n 'parent-task-id',\n 'session-id',\n 'user-id',\n 'assistant-id',\n 'agentspace-id',\n 'channel-id',\n 'depth',\n] as const;\n\nfunction pickIdentityHeaders(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of IDENTITY_HEADER_NAMES) {\n const value = request.headers.get(name);\n if (value) out[name] = value;\n }\n return out;\n}\n\n/**\n * Trace-context propagation. The proxy builds a fresh request against the\n * runtime, so anything the caller set is dropped unless it is copied over\n * explicitly — which is how `x-trace-parent` stopped reaching the runtime when\n * the direct-to-runtime client was replaced by this proxy.\n *\n * The header is the transport wherever the caller can set one. `EventSource`\n * cannot, so the stream route also accepts the same value as a `trace_parent`\n * query param.\n */\nfunction pickTraceHeader(request: Request): Record<string, string> {\n const fromHeader = request.headers.get('x-trace-parent');\n if (fromHeader) return { 'x-trace-parent': fromHeader };\n\n const fromQuery = new URL(request.url).searchParams.get('trace_parent');\n if (fromQuery) return { 'x-trace-parent': fromQuery };\n\n return {};\n}\n\n/**\n * Correlation headers for tool-completion and tool-approval. Both routes bind\n * them through the runtime's `CommonAttributes` header model, whose aliases\n * have no separator — not the kebab-case identity set infer/stream use. They\n * route the decision to the parked task so the SSE stream resumes, and\n * `agentspaceid` is what the runtime authorizes a non-admin caller against.\n */\nconst DECISION_HEADER_NAMES = [\n 'taskid',\n 'parenttaskid',\n 'sessionid',\n 'userid',\n 'assistantid',\n 'agentspaceid',\n 'channelid',\n 'depth',\n // Runtime v0.5.1: `CommonAttributes.version_tag` (alias `versiontag`)\n // pins the decision to the agentspace version that ran the turn.\n 'versiontag',\n] as const;\n\nexport function createAlquimiaProxyHandler(config: ProxyConfig): AlquimiaProxyHandler {\n const baseUrl = config.assistantBaseUrl.replace(/\\/$/, '');\n const inferRoute = config.inferRoute ?? 'event/infer';\n const streamRoute = config.streamRoute ?? 'event/stream';\n const blobUploadRoute = config.blobUploadRoute ?? 'context/blob/upload';\n const toolCompletionRoute = config.toolCompletionRoute ?? 'event/tool-completion';\n const toolApprovalRoute = config.toolApprovalRoute ?? 'event/tool-approval';\n const authHeader = { Authorization: `Bearer ${config.apiKey}` };\n\n /**\n * Forward a one-shot decision (tool completion or approval). The runtime's\n * status and body pass through untouched: the 409s on these routes differ\n * only in their `detail` text, and the caller needs that to tell \"already\n * decided\" from \"answer it on the original channel\".\n */\n async function forwardDecision(request: Request, route: string, name: string): Promise<Response> {\n try {\n const body = await request.text();\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...authHeader,\n };\n for (const name of DECISION_HEADER_NAMES) {\n const value = request.headers.get(name);\n if (value) headers[name] = value;\n }\n Object.assign(headers, pickTraceHeader(request));\n\n const response = await fetch(`${baseUrl}/${route}`, {\n method: 'POST',\n headers,\n body,\n });\n\n return new Response(await response.text(), {\n status: response.status,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n console.error(`AlquimiaProxy ${name} exception:`, error);\n return new Response(\n JSON.stringify({ error: `Failed to forward ${name} request` }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n }\n\n return {\n async handleInfer(request: Request, pathSuffix: string): Promise<Response> {\n try {\n const body = await request.json();\n const url = new URL(request.url);\n const querySuffix = url.searchParams.toString()\n ? `?${url.searchParams.toString()}`\n : '';\n const slug = pathSuffix.replace(/^\\/+|\\/+$/g, '');\n const targetUrl = `${baseUrl}/${inferRoute}/${slug}${querySuffix}`;\n\n\n const response = await fetch(targetUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...authHeader,\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorJson = await response.json().catch(() => ({}));\n console.error('AlquimiaProxy handleInfer error:', {\n status: response.status,\n statusText: response.statusText,\n body: errorJson,\n });\n return new Response(\n JSON.stringify({\n status: response.status,\n statusText: response.statusText,\n ...errorJson,\n }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n return new Response(response.body, {\n status: 200,\n headers: {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Content-Encoding',\n },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleInfer exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward infer request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleStream(request: Request, pathSuffix: string): Promise<Response> {\n try {\n const targetUrl = `${baseUrl}/${streamRoute}/${pathSuffix}`;\n\n const response = await fetch(targetUrl, {\n headers: {\n 'Content-Type': 'application/json',\n ...authHeader,\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n });\n\n if (!response.ok) {\n const errorJson = await response.json().catch(() => ({}));\n console.error('AlquimiaProxy handleStream error:', {\n status: response.status,\n statusText: response.statusText,\n body: errorJson,\n });\n return new Response(\n JSON.stringify({\n error: errorJson.message || response.statusText || 'Failed to forward stream',\n ...errorJson,\n }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n return new Response(response.body, {\n status: 200,\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleStream exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward stream request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleBlobUpload(request: Request): Promise<Response> {\n try {\n const targetUrl = `${baseUrl}/${blobUploadRoute}`;\n const contentType = request.headers.get('Content-Type') ?? '';\n\n const response = await fetch(targetUrl, {\n method: 'POST',\n headers: {\n ...authHeader,\n ...(contentType && { 'Content-Type': contentType }),\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n body: request.body,\n duplex: 'half',\n } as RequestInit);\n\n if (!response.ok) {\n return new Response(\n JSON.stringify({ error: 'Failed to upload blob', status: response.status }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n const responseText = await response.text();\n return new Response(responseText, {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleBlobUpload exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward blob upload request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleToolCompletion(request: Request): Promise<Response> {\n return forwardDecision(request, toolCompletionRoute, 'tool-completion');\n },\n\n async handleToolApproval(request: Request): Promise<Response> {\n return forwardDecision(request, toolApprovalRoute, 'tool-approval');\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,oBAAoB,SAA0C;AACrE,QAAM,MAA8B,CAAC;AACrC,aAAW,QAAQ,uBAAuB;AACxC,UAAM,QAAQ,QAAQ,QAAQ,IAAI,IAAI;AACtC,QAAI,MAAO,KAAI,IAAI,IAAI;AAAA,EACzB;AACA,SAAO;AACT;AAYA,SAAS,gBAAgB,SAA0C;AACjE,QA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,mBAAmB,EAAE;AAAA,QACjE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,MAAM,qBAAqB,SAAqC;AAC9D,aAAO,gBAAgB,SAAS,qBAAqB,iBAAiB;AAAA,IACxE;AAAA,IAEA,MAAM,mBAAmB,SAAqC;AAC5D,aAAO,gBAAgB,SAAS,mBAAmB,eAAe;AAAA,IACpE;AAAA,EACF;AACF;","names":["name"]}
package/dist/proxy.mjs CHANGED
@@ -24,13 +24,56 @@ function pickTraceHeader(request) {
24
24
  if (fromQuery) return { "x-trace-parent": fromQuery };
25
25
  return {};
26
26
  }
27
+ var DECISION_HEADER_NAMES = [
28
+ "taskid",
29
+ "parenttaskid",
30
+ "sessionid",
31
+ "userid",
32
+ "assistantid",
33
+ "agentspaceid",
34
+ "channelid",
35
+ "depth",
36
+ // Runtime v0.5.1: `CommonAttributes.version_tag` (alias `versiontag`)
37
+ // pins the decision to the agentspace version that ran the turn.
38
+ "versiontag"
39
+ ];
27
40
  function createAlquimiaProxyHandler(config) {
28
41
  const baseUrl = config.assistantBaseUrl.replace(/\/$/, "");
29
42
  const inferRoute = config.inferRoute ?? "event/infer";
30
43
  const streamRoute = config.streamRoute ?? "event/stream";
31
44
  const blobUploadRoute = config.blobUploadRoute ?? "context/blob/upload";
32
45
  const toolCompletionRoute = config.toolCompletionRoute ?? "event/tool-completion";
46
+ const toolApprovalRoute = config.toolApprovalRoute ?? "event/tool-approval";
33
47
  const authHeader = { Authorization: `Bearer ${config.apiKey}` };
48
+ async function forwardDecision(request, route, name) {
49
+ try {
50
+ const body = await request.text();
51
+ const headers = {
52
+ "Content-Type": "application/json",
53
+ ...authHeader
54
+ };
55
+ for (const name2 of DECISION_HEADER_NAMES) {
56
+ const value = request.headers.get(name2);
57
+ if (value) headers[name2] = value;
58
+ }
59
+ Object.assign(headers, pickTraceHeader(request));
60
+ const response = await fetch(`${baseUrl}/${route}`, {
61
+ method: "POST",
62
+ headers,
63
+ body
64
+ });
65
+ return new Response(await response.text(), {
66
+ status: response.status,
67
+ headers: { "Content-Type": "application/json" }
68
+ });
69
+ } catch (error) {
70
+ console.error(`AlquimiaProxy ${name} exception:`, error);
71
+ return new Response(
72
+ JSON.stringify({ error: `Failed to forward ${name} request` }),
73
+ { status: 500, headers: { "Content-Type": "application/json" } }
74
+ );
75
+ }
76
+ }
34
77
  return {
35
78
  async handleInfer(request, pathSuffix) {
36
79
  try {
@@ -158,46 +201,10 @@ function createAlquimiaProxyHandler(config) {
158
201
  }
159
202
  },
160
203
  async handleToolCompletion(request) {
161
- try {
162
- const body = await request.text();
163
- const headers = {
164
- "Content-Type": "application/json",
165
- ...authHeader
166
- };
167
- const CORRELATION_HEADERS = [
168
- "taskid",
169
- "parenttaskid",
170
- "sessionid",
171
- "userid",
172
- "assistantid",
173
- "agentspaceid",
174
- "channelid",
175
- "depth",
176
- // Runtime v0.5.1: `CommonAttributes.version_tag` (alias `versiontag`)
177
- // pins the tool-completion to the agentspace version that ran the turn.
178
- "versiontag"
179
- ];
180
- for (const name of CORRELATION_HEADERS) {
181
- const value = request.headers.get(name);
182
- if (value) headers[name] = value;
183
- }
184
- Object.assign(headers, pickTraceHeader(request));
185
- const response = await fetch(`${baseUrl}/${toolCompletionRoute}`, {
186
- method: "POST",
187
- headers,
188
- body
189
- });
190
- return new Response(await response.text(), {
191
- status: response.status,
192
- headers: { "Content-Type": "application/json" }
193
- });
194
- } catch (error) {
195
- console.error("AlquimiaProxy handleToolCompletion exception:", error);
196
- return new Response(
197
- JSON.stringify({ error: "Failed to forward tool-completion request" }),
198
- { status: 500, headers: { "Content-Type": "application/json" } }
199
- );
200
- }
204
+ return forwardDecision(request, toolCompletionRoute, "tool-completion");
205
+ },
206
+ async handleToolApproval(request) {
207
+ return forwardDecision(request, toolApprovalRoute, "tool-approval");
201
208
  }
202
209
  };
203
210
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["export interface ProxyConfig {\n assistantBaseUrl: string;\n apiKey: string;\n inferRoute?: string; // default: 'event/infer'\n streamRoute?: string; // default: 'event/stream'\n blobUploadRoute?: string; // default: 'context/blob/upload'\n toolCompletionRoute?: string; // default: 'event/tool-completion'\n}\n\nexport interface AlquimiaProxyHandler {\n handleInfer(_request: Request, _pathSuffix: string): Promise<Response>;\n handleStream(_request: Request, _pathSuffix: string): Promise<Response>;\n handleBlobUpload(_request: Request): Promise<Response>;\n handleToolCompletion(_request: Request): Promise<Response>;\n}\n\nconst IDENTITY_HEADER_NAMES = [\n 'task-id',\n 'parent-task-id',\n 'session-id',\n 'user-id',\n 'assistant-id',\n 'agentspace-id',\n 'channel-id',\n 'depth',\n] as const;\n\nfunction pickIdentityHeaders(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of IDENTITY_HEADER_NAMES) {\n const value = request.headers.get(name);\n if (value) out[name] = value;\n }\n return out;\n}\n\n/**\n * Trace-context propagation. The proxy builds a fresh request against the\n * runtime, so anything the caller set is dropped unless it is copied over\n * explicitly — which is how `x-trace-parent` stopped reaching the runtime when\n * the direct-to-runtime client was replaced by this proxy.\n *\n * The header is the transport wherever the caller can set one. `EventSource`\n * cannot, so the stream route also accepts the same value as a `trace_parent`\n * query param.\n */\nfunction pickTraceHeader(request: Request): Record<string, string> {\n const fromHeader = request.headers.get('x-trace-parent');\n if (fromHeader) return { 'x-trace-parent': fromHeader };\n\n const fromQuery = new URL(request.url).searchParams.get('trace_parent');\n if (fromQuery) return { 'x-trace-parent': fromQuery };\n\n return {};\n}\n\nexport function createAlquimiaProxyHandler(config: ProxyConfig): AlquimiaProxyHandler {\n const baseUrl = config.assistantBaseUrl.replace(/\\/$/, '');\n const inferRoute = config.inferRoute ?? 'event/infer';\n const streamRoute = config.streamRoute ?? 'event/stream';\n const blobUploadRoute = config.blobUploadRoute ?? 'context/blob/upload';\n const toolCompletionRoute = config.toolCompletionRoute ?? 'event/tool-completion';\n const authHeader = { Authorization: `Bearer ${config.apiKey}` };\n\n return {\n async handleInfer(request: Request, pathSuffix: string): Promise<Response> {\n try {\n const body = await request.json();\n const url = new URL(request.url);\n const querySuffix = url.searchParams.toString()\n ? `?${url.searchParams.toString()}`\n : '';\n const slug = pathSuffix.replace(/^\\/+|\\/+$/g, '');\n const targetUrl = `${baseUrl}/${inferRoute}/${slug}${querySuffix}`;\n\n\n const response = await fetch(targetUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...authHeader,\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorJson = await response.json().catch(() => ({}));\n console.error('AlquimiaProxy handleInfer error:', {\n status: response.status,\n statusText: response.statusText,\n body: errorJson,\n });\n return new Response(\n JSON.stringify({\n status: response.status,\n statusText: response.statusText,\n ...errorJson,\n }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n return new Response(response.body, {\n status: 200,\n headers: {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Content-Encoding',\n },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleInfer exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward infer request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleStream(request: Request, pathSuffix: string): Promise<Response> {\n try {\n const targetUrl = `${baseUrl}/${streamRoute}/${pathSuffix}`;\n\n const response = await fetch(targetUrl, {\n headers: {\n 'Content-Type': 'application/json',\n ...authHeader,\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n });\n\n if (!response.ok) {\n const errorJson = await response.json().catch(() => ({}));\n console.error('AlquimiaProxy handleStream error:', {\n status: response.status,\n statusText: response.statusText,\n body: errorJson,\n });\n return new Response(\n JSON.stringify({\n error: errorJson.message || response.statusText || 'Failed to forward stream',\n ...errorJson,\n }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n return new Response(response.body, {\n status: 200,\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleStream exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward stream request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleBlobUpload(request: Request): Promise<Response> {\n try {\n const targetUrl = `${baseUrl}/${blobUploadRoute}`;\n const contentType = request.headers.get('Content-Type') ?? '';\n\n const response = await fetch(targetUrl, {\n method: 'POST',\n headers: {\n ...authHeader,\n ...(contentType && { 'Content-Type': contentType }),\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n body: request.body,\n duplex: 'half',\n } as RequestInit);\n\n if (!response.ok) {\n return new Response(\n JSON.stringify({ error: 'Failed to upload blob', status: response.status }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n const responseText = await response.text();\n return new Response(responseText, {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleBlobUpload exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward blob upload request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleToolCompletion(request: Request): Promise<Response> {\n try {\n const body = await request.text();\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...authHeader,\n };\n // Forward the runtime's tool-completion correlation headers verbatim\n // (non-hyphenated names, per the runtime OpenAPI). These route the\n // completion to the parked task so the SSE stream resumes.\n const CORRELATION_HEADERS = [\n 'taskid',\n 'parenttaskid',\n 'sessionid',\n 'userid',\n 'assistantid',\n 'agentspaceid',\n 'channelid',\n 'depth',\n // Runtime v0.5.1: `CommonAttributes.version_tag` (alias `versiontag`)\n // pins the tool-completion to the agentspace version that ran the turn.\n 'versiontag',\n ];\n for (const name of CORRELATION_HEADERS) {\n const value = request.headers.get(name);\n if (value) headers[name] = value;\n }\n Object.assign(headers, pickTraceHeader(request));\n\n const response = await fetch(`${baseUrl}/${toolCompletionRoute}`, {\n method: 'POST',\n headers,\n body,\n });\n\n return new Response(await response.text(), {\n status: response.status,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleToolCompletion exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward tool-completion request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n };\n}\n"],"mappings":";AAgBA,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,oBAAoB,SAA0C;AACrE,QAAM,MAA8B,CAAC;AACrC,aAAW,QAAQ,uBAAuB;AACxC,UAAM,QAAQ,QAAQ,QAAQ,IAAI,IAAI;AACtC,QAAI,MAAO,KAAI,IAAI,IAAI;AAAA,EACzB;AACA,SAAO;AACT;AAYA,SAAS,gBAAgB,SAA0C;AACjE,QAAM,aAAa,QAAQ,QAAQ,IAAI,gBAAgB;AACvD,MAAI,WAAY,QAAO,EAAE,kBAAkB,WAAW;AAEtD,QAAM,YAAY,IAAI,IAAI,QAAQ,GAAG,EAAE,aAAa,IAAI,cAAc;AACtE,MAAI,UAAW,QAAO,EAAE,kBAAkB,UAAU;AAEpD,SAAO,CAAC;AACV;AAEO,SAAS,2BAA2B,QAA2C;AACpF,QAAM,UAAU,OAAO,iBAAiB,QAAQ,OAAO,EAAE;AACzD,QAAM,aAAa,OAAO,cAAc;AACxC,QAAM,cAAc,OAAO,eAAe;AAC1C,QAAM,kBAAkB,OAAO,mBAAmB;AAClD,QAAM,sBAAsB,OAAO,uBAAuB;AAC1D,QAAM,aAAa,EAAE,eAAe,UAAU,OAAO,MAAM,GAAG;AAE9D,SAAO;AAAA,IACL,MAAM,YAAY,SAAkB,YAAuC;AACzE,UAAI;AACF,cAAM,OAAO,MAAM,QAAQ,KAAK;AAChC,cAA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,qBAAqB;AACtC,gBAAM,QAAQ,QAAQ,QAAQ,IAAI,IAAI;AACtC,cAAI,MAAO,SAAQ,IAAI,IAAI;AAAA,QAC7B;AACA,eAAO,OAAO,SAAS,gBAAgB,OAAO,CAAC;AAE/C,cAAM,WAAW,MAAM,MAAM,GAAG,OAAO,IAAI,mBAAmB,IAAI;AAAA,UAChE,QAAQ;AAAA,UACR;AAAA,UACA;AAAA,QACF,CAAC;AAED,eAAO,IAAI,SAAS,MAAM,SAAS,KAAK,GAAG;AAAA,UACzC,QAAQ,SAAS;AAAA,UACjB,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,QAChD,CAAC;AAAA,MACH,SAAS,OAAO;AACd,gBAAQ,MAAM,iDAAiD,KAAK;AACpE,eAAO,IAAI;AAAA,UACT,KAAK,UAAU,EAAE,OAAO,4CAA4C,CAAC;AAAA,UACrE,EAAE,QAAQ,KAAK,SAAS,EAAE,gBAAgB,mBAAmB,EAAE;AAAA,QACjE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/proxy.ts"],"sourcesContent":["export interface ProxyConfig {\n assistantBaseUrl: string;\n apiKey: string;\n inferRoute?: string; // default: 'event/infer'\n streamRoute?: string; // default: 'event/stream'\n blobUploadRoute?: string; // default: 'context/blob/upload'\n toolCompletionRoute?: string; // default: 'event/tool-completion'\n toolApprovalRoute?: string; // default: 'event/tool-approval'\n}\n\nexport interface AlquimiaProxyHandler {\n handleInfer(_request: Request, _pathSuffix: string): Promise<Response>;\n handleStream(_request: Request, _pathSuffix: string): Promise<Response>;\n handleBlobUpload(_request: Request): Promise<Response>;\n handleToolCompletion(_request: Request): Promise<Response>;\n handleToolApproval(_request: Request): Promise<Response>;\n}\n\nconst IDENTITY_HEADER_NAMES = [\n 'task-id',\n 'parent-task-id',\n 'session-id',\n 'user-id',\n 'assistant-id',\n 'agentspace-id',\n 'channel-id',\n 'depth',\n] as const;\n\nfunction pickIdentityHeaders(request: Request): Record<string, string> {\n const out: Record<string, string> = {};\n for (const name of IDENTITY_HEADER_NAMES) {\n const value = request.headers.get(name);\n if (value) out[name] = value;\n }\n return out;\n}\n\n/**\n * Trace-context propagation. The proxy builds a fresh request against the\n * runtime, so anything the caller set is dropped unless it is copied over\n * explicitly — which is how `x-trace-parent` stopped reaching the runtime when\n * the direct-to-runtime client was replaced by this proxy.\n *\n * The header is the transport wherever the caller can set one. `EventSource`\n * cannot, so the stream route also accepts the same value as a `trace_parent`\n * query param.\n */\nfunction pickTraceHeader(request: Request): Record<string, string> {\n const fromHeader = request.headers.get('x-trace-parent');\n if (fromHeader) return { 'x-trace-parent': fromHeader };\n\n const fromQuery = new URL(request.url).searchParams.get('trace_parent');\n if (fromQuery) return { 'x-trace-parent': fromQuery };\n\n return {};\n}\n\n/**\n * Correlation headers for tool-completion and tool-approval. Both routes bind\n * them through the runtime's `CommonAttributes` header model, whose aliases\n * have no separator — not the kebab-case identity set infer/stream use. They\n * route the decision to the parked task so the SSE stream resumes, and\n * `agentspaceid` is what the runtime authorizes a non-admin caller against.\n */\nconst DECISION_HEADER_NAMES = [\n 'taskid',\n 'parenttaskid',\n 'sessionid',\n 'userid',\n 'assistantid',\n 'agentspaceid',\n 'channelid',\n 'depth',\n // Runtime v0.5.1: `CommonAttributes.version_tag` (alias `versiontag`)\n // pins the decision to the agentspace version that ran the turn.\n 'versiontag',\n] as const;\n\nexport function createAlquimiaProxyHandler(config: ProxyConfig): AlquimiaProxyHandler {\n const baseUrl = config.assistantBaseUrl.replace(/\\/$/, '');\n const inferRoute = config.inferRoute ?? 'event/infer';\n const streamRoute = config.streamRoute ?? 'event/stream';\n const blobUploadRoute = config.blobUploadRoute ?? 'context/blob/upload';\n const toolCompletionRoute = config.toolCompletionRoute ?? 'event/tool-completion';\n const toolApprovalRoute = config.toolApprovalRoute ?? 'event/tool-approval';\n const authHeader = { Authorization: `Bearer ${config.apiKey}` };\n\n /**\n * Forward a one-shot decision (tool completion or approval). The runtime's\n * status and body pass through untouched: the 409s on these routes differ\n * only in their `detail` text, and the caller needs that to tell \"already\n * decided\" from \"answer it on the original channel\".\n */\n async function forwardDecision(request: Request, route: string, name: string): Promise<Response> {\n try {\n const body = await request.text();\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...authHeader,\n };\n for (const name of DECISION_HEADER_NAMES) {\n const value = request.headers.get(name);\n if (value) headers[name] = value;\n }\n Object.assign(headers, pickTraceHeader(request));\n\n const response = await fetch(`${baseUrl}/${route}`, {\n method: 'POST',\n headers,\n body,\n });\n\n return new Response(await response.text(), {\n status: response.status,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n console.error(`AlquimiaProxy ${name} exception:`, error);\n return new Response(\n JSON.stringify({ error: `Failed to forward ${name} request` }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n }\n\n return {\n async handleInfer(request: Request, pathSuffix: string): Promise<Response> {\n try {\n const body = await request.json();\n const url = new URL(request.url);\n const querySuffix = url.searchParams.toString()\n ? `?${url.searchParams.toString()}`\n : '';\n const slug = pathSuffix.replace(/^\\/+|\\/+$/g, '');\n const targetUrl = `${baseUrl}/${inferRoute}/${slug}${querySuffix}`;\n\n\n const response = await fetch(targetUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...authHeader,\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorJson = await response.json().catch(() => ({}));\n console.error('AlquimiaProxy handleInfer error:', {\n status: response.status,\n statusText: response.statusText,\n body: errorJson,\n });\n return new Response(\n JSON.stringify({\n status: response.status,\n statusText: response.statusText,\n ...errorJson,\n }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n return new Response(response.body, {\n status: 200,\n headers: {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type, Content-Encoding',\n },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleInfer exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward infer request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleStream(request: Request, pathSuffix: string): Promise<Response> {\n try {\n const targetUrl = `${baseUrl}/${streamRoute}/${pathSuffix}`;\n\n const response = await fetch(targetUrl, {\n headers: {\n 'Content-Type': 'application/json',\n ...authHeader,\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n });\n\n if (!response.ok) {\n const errorJson = await response.json().catch(() => ({}));\n console.error('AlquimiaProxy handleStream error:', {\n status: response.status,\n statusText: response.statusText,\n body: errorJson,\n });\n return new Response(\n JSON.stringify({\n error: errorJson.message || response.statusText || 'Failed to forward stream',\n ...errorJson,\n }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n return new Response(response.body, {\n status: 200,\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleStream exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward stream request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleBlobUpload(request: Request): Promise<Response> {\n try {\n const targetUrl = `${baseUrl}/${blobUploadRoute}`;\n const contentType = request.headers.get('Content-Type') ?? '';\n\n const response = await fetch(targetUrl, {\n method: 'POST',\n headers: {\n ...authHeader,\n ...(contentType && { 'Content-Type': contentType }),\n ...pickIdentityHeaders(request),\n ...pickTraceHeader(request),\n },\n body: request.body,\n duplex: 'half',\n } as RequestInit);\n\n if (!response.ok) {\n return new Response(\n JSON.stringify({ error: 'Failed to upload blob', status: response.status }),\n { status: response.status, headers: { 'Content-Type': 'application/json' } }\n );\n }\n\n const responseText = await response.text();\n return new Response(responseText, {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error) {\n console.error('AlquimiaProxy handleBlobUpload exception:', error);\n return new Response(\n JSON.stringify({ error: 'Failed to forward blob upload request' }),\n { status: 500, headers: { 'Content-Type': 'application/json' } }\n );\n }\n },\n\n async handleToolCompletion(request: Request): Promise<Response> {\n return forwardDecision(request, toolCompletionRoute, 'tool-completion');\n },\n\n async handleToolApproval(request: Request): Promise<Response> {\n return forwardDecision(request, toolApprovalRoute, 'tool-approval');\n },\n };\n}\n"],"mappings":";AAkBA,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,oBAAoB,SAA0C;AACrE,QAAM,MAA8B,CAAC;AACrC,aAAW,QAAQ,uBAAuB;AACxC,UAAM,QAAQ,QAAQ,QAAQ,IAAI,IAAI;AACtC,QAAI,MAAO,KAAI,IAAI,IAAI;AAAA,EACzB;AACA,SAAO;AACT;AAYA,SAAS,gBAAgB,SAA0C;AACjE,QAAM,aAAa,QAAQ,QAAQ,IAAI,gBAAgB;AACvD,MAAI,WAAY,QAAO,EAAE,kBAAkB,WAAW;AAEtD,QAAM,YAAY,IAAI,IAAI,QAAQ,GAAG,EAAE,aAAa,IAAI,cAAc;AACtE,MAAI,UAAW,QAAO,EAAE,kBAAkB,UAAU;AAEpD,SAAO,CAAC;AACV;AASA,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AACF;AAEO,SAAS,2BAA2B,QAA2C;AACpF,QAAM,UAAU,OAAO,iBAAiB,QAAQ,OAAO,EAAE;AACzD,QAAM,aAAa,OAAO,cAAc;AACxC,QAAM,cAAc,OAAO,eAAe;AAC1C,QAAM,kBAAkB,OAAO,mBAAmB;AAClD,QAAM,sBAAsB,OAAO,uBAAuB;AAC1D,QAAM,oBAAoB,OAAO,qBAAqB;AACtD,QAAM,aAAa,EAAE,eA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AC5B;AAAA,UACA,MAAM,QAAQ;AAAA,UACd,QAAQ;AAAA,QACV,CAAgB;AAEhB,YAAI,CAAC,SAAS,IAAI;AAChB,iBAAO,IAAI;AAAA,YACT,KAAK,UAAU,EAAE,OAAO,yBAAyB,QAAQ,SAAS,OAAO,CAAC;AAAA,YAC1E,EAAE,QAAQ,SAAS,QAAQ,SAAS,EAAE,gBAAgB,mBAAmB,EAAE;AAAA,UAC7E;AAAA,QACF;AAEA,cAAM,eAAe,MAAM,SAAS,KAAK;AACzC,eAAO,IAAI,SAAS,cAAc;AAAA,UAChC,QAAQ;AAAA,UACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,QAChD,CAAC;AAAA,MACH,SAAS,OAAO;AACd,gBAAQ,MAAM,6CAA6C,KAAK;AAChE,eAAO,IAAI;AAAA,UACT,KAAK,UAAU,EAAE,OAAO,wCAAwC,CAAC;AAAA,UACjE,EAAE,QAAQ,KAAK,SAAS,EAAE,gBAAgB,mBAAmB,EAAE;AAAA,QACjE;AAAA,MACF;AAAA,IACF;AAAA,IAEA,MAAM,qBAAqB,SAAqC;AAC9D,aAAO,gBAAgB,SAAS,qBAAqB,iBAAiB;AAAA,IACxE;AAAA,IAEA,MAAM,mBAAmB,SAAqC;AAC5D,aAAO,gBAAgB,SAAS,mBAAmB,eAAe;AAAA,IACpE;AAAA,EACF;AACF;","names":["name"]}
@@ -1,9 +1,11 @@
1
- import { W as WhisperProvider, S as StableDiffusionProvider, C as CharacterizationProvider, R as RatingsProvider, L as LoggerProvider } from '../providers-B4IOiGfr.mjs';
2
- import { i as AttachmentPayload, T as TTSResult, j as Content, w as RuntimeBlob } from '../type-61gaZga-.mjs';
3
- import { T as ToolExecutionResponse } from '../types-CMVbyEv8.mjs';
1
+ import { W as WhisperProvider, S as StableDiffusionProvider, C as CharacterizationProvider, R as RatingsProvider, L as LoggerProvider } from '../providers-YKiEag2L.mjs';
2
+ import { d as AttachmentPayload, T as TTSResult, C as Content, e as RuntimeBlob } from '../type-C_sKpIM1.mjs';
3
+ import { ToolApprovalResult } from '../types/index.mjs';
4
4
  import { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters/index.mjs';
5
+ import { T as ToolExecutionResponse } from '../types-CMVbyEv8.mjs';
5
6
  import '@elastic/apm-rum';
6
7
  import 'ai';
8
+ import '../types-lOliroPw.mjs';
7
9
 
8
10
  /** Per-turn options for {@link AlquimiaSDK.sendMessage}. */
9
11
  interface SendMessageOptions {
@@ -30,6 +32,7 @@ declare class AlquimiaSDK {
30
32
  private streamId;
31
33
  private traceParent;
32
34
  private versionTag;
35
+ private agentspaceId;
33
36
  private tools;
34
37
  private extraInstructions;
35
38
  private assistantConfig;
@@ -77,6 +80,17 @@ declare class AlquimiaSDK {
77
80
  * `context-metadata` header (taskid + sessionid).
78
81
  */
79
82
  submitToolResult(response: ToolExecutionResponse): Promise<void>;
83
+ /**
84
+ * Answer a `HumanApprovalRequired` gate: POSTs a {@link ToolApprovalEvent} to
85
+ * the runtime's `/event/tool-approval`. `controlId` is the gate's own control
86
+ * id (the `HumanApprovalRequired` record's), not the parked tool call's.
87
+ *
88
+ * Never throws for a runtime refusal — each 409 means something different to
89
+ * the UI, so the answer comes back classified as a {@link ToolApprovalResult}.
90
+ * It does throw when the adapter has no approval route, which is a wiring bug
91
+ * rather than a runtime answer.
92
+ */
93
+ submitToolApproval(controlId: string, approved: boolean, message?: string): Promise<ToolApprovalResult>;
80
94
  generateImage(query: string): Promise<string>;
81
95
  analyzeCharacterization(text: string): Promise<Record<string, any>>;
82
96
  rate(data: any): Promise<Record<string, any>>;
@@ -98,12 +112,20 @@ declare class AlquimiaSDK {
98
112
  * the rest of the runtime's internal endpoints introduced in v0.2.0→next.
99
113
  */
100
114
  private buildIdentityHeaders;
115
+ /**
116
+ * Correlation headers for tool-completion and tool-approval: the runtime's
117
+ * `CommonAttributes` header aliases, with no separator. Not interchangeable
118
+ * with the kebab-case set in {@link buildIdentityHeaders}.
119
+ */
120
+ private buildDecisionHeaders;
101
121
  getUrlStream(): string;
102
122
  getStreamId(): string | null;
103
123
  /** Alias for {@link getStreamId} — same value as infer `taskid`. */
104
124
  getTaskId(): string | null;
105
125
  /** Registry version tag resolved by the runtime for the current task, if any. */
106
126
  getVersionTag(): string | null;
127
+ /** Agentspace the runtime resolved for the current task, if any. */
128
+ getAgentspaceId(): string | null;
107
129
  }
108
130
 
109
131
  export { AlquimiaSDK };
@@ -1,9 +1,11 @@
1
- import { W as WhisperProvider, S as StableDiffusionProvider, C as CharacterizationProvider, R as RatingsProvider, L as LoggerProvider } from '../providers-mx21gNgZ.js';
2
- import { i as AttachmentPayload, T as TTSResult, j as Content, w as RuntimeBlob } from '../type-D-JaSMkV.js';
3
- import { T as ToolExecutionResponse } from '../types-CMVbyEv8.js';
1
+ import { W as WhisperProvider, S as StableDiffusionProvider, C as CharacterizationProvider, R as RatingsProvider, L as LoggerProvider } from '../providers-J_Z9rQ3Q.js';
2
+ import { d as AttachmentPayload, T as TTSResult, C as Content, e as RuntimeBlob } from '../type-BFtGEEb4.js';
3
+ import { ToolApprovalResult } from '../types/index.js';
4
4
  import { AlquimiaAdapter, AlquimiaSDKOptions } from '../adapters/index.js';
5
+ import { T as ToolExecutionResponse } from '../types-CMVbyEv8.js';
5
6
  import '@elastic/apm-rum';
6
7
  import 'ai';
8
+ import '../types-lOliroPw.js';
7
9
 
8
10
  /** Per-turn options for {@link AlquimiaSDK.sendMessage}. */
9
11
  interface SendMessageOptions {
@@ -30,6 +32,7 @@ declare class AlquimiaSDK {
30
32
  private streamId;
31
33
  private traceParent;
32
34
  private versionTag;
35
+ private agentspaceId;
33
36
  private tools;
34
37
  private extraInstructions;
35
38
  private assistantConfig;
@@ -77,6 +80,17 @@ declare class AlquimiaSDK {
77
80
  * `context-metadata` header (taskid + sessionid).
78
81
  */
79
82
  submitToolResult(response: ToolExecutionResponse): Promise<void>;
83
+ /**
84
+ * Answer a `HumanApprovalRequired` gate: POSTs a {@link ToolApprovalEvent} to
85
+ * the runtime's `/event/tool-approval`. `controlId` is the gate's own control
86
+ * id (the `HumanApprovalRequired` record's), not the parked tool call's.
87
+ *
88
+ * Never throws for a runtime refusal — each 409 means something different to
89
+ * the UI, so the answer comes back classified as a {@link ToolApprovalResult}.
90
+ * It does throw when the adapter has no approval route, which is a wiring bug
91
+ * rather than a runtime answer.
92
+ */
93
+ submitToolApproval(controlId: string, approved: boolean, message?: string): Promise<ToolApprovalResult>;
80
94
  generateImage(query: string): Promise<string>;
81
95
  analyzeCharacterization(text: string): Promise<Record<string, any>>;
82
96
  rate(data: any): Promise<Record<string, any>>;
@@ -98,12 +112,20 @@ declare class AlquimiaSDK {
98
112
  * the rest of the runtime's internal endpoints introduced in v0.2.0→next.
99
113
  */
100
114
  private buildIdentityHeaders;
115
+ /**
116
+ * Correlation headers for tool-completion and tool-approval: the runtime's
117
+ * `CommonAttributes` header aliases, with no separator. Not interchangeable
118
+ * with the kebab-case set in {@link buildIdentityHeaders}.
119
+ */
120
+ private buildDecisionHeaders;
101
121
  getUrlStream(): string;
102
122
  getStreamId(): string | null;
103
123
  /** Alias for {@link getStreamId} — same value as infer `taskid`. */
104
124
  getTaskId(): string | null;
105
125
  /** Registry version tag resolved by the runtime for the current task, if any. */
106
126
  getVersionTag(): string | null;
127
+ /** Agentspace the runtime resolved for the current task, if any. */
128
+ getAgentspaceId(): string | null;
107
129
  }
108
130
 
109
131
  export { AlquimiaSDK };
package/dist/sdk/index.js CHANGED
@@ -47,6 +47,9 @@ var AlquimiaSDK = class {
47
47
  // Registry version tag resolved by the runtime for this task (v0.5.1), so
48
48
  // the tool-completion half of the turn lands on the same agentspace version.
49
49
  this.versionTag = null;
50
+ // Agentspace the runtime resolved for this task. Tool completion and
51
+ // approval authorize a non-admin caller against it, so it is echoed back.
52
+ this.agentspaceId = null;
50
53
  this.tools = [];
51
54
  this.extraInstructions = null;
52
55
  this.assistantConfig = null;
@@ -198,6 +201,7 @@ var AlquimiaSDK = class {
198
201
  this.traceParent = opts.traceParent ?? null;
199
202
  this.streamId = result.taskid ?? null;
200
203
  this.versionTag = result.versiontag ?? this.versionTag;
204
+ this.agentspaceId = result.agentspaceid ?? null;
201
205
  this.attachmentResponses = result.attachments ?? [];
202
206
  this.attachments = [];
203
207
  return this;
@@ -217,17 +221,37 @@ var AlquimiaSDK = class {
217
221
  "AlquimiaSDK: adapter does not support tool completion (resolveToolCompletionUrl missing)"
218
222
  );
219
223
  }
220
- const adapterHeaders = this.adapter.getHeaders?.() ?? {};
221
- const headers = {
222
- "Content-Type": "application/json",
223
- assistantid: this.assistantId,
224
- ...this.streamId && { taskid: this.streamId },
225
- ...this.conversationId && { sessionid: this.conversationId },
226
- ...this.userId && { userid: this.userId },
227
- ...this.versionTag && { versiontag: this.versionTag },
228
- ...adapterHeaders
224
+ await this.axiosInstance.post(url, response, { headers: this.buildDecisionHeaders() });
225
+ }
226
+ /**
227
+ * Answer a `HumanApprovalRequired` gate: POSTs a {@link ToolApprovalEvent} to
228
+ * the runtime's `/event/tool-approval`. `controlId` is the gate's own control
229
+ * id (the `HumanApprovalRequired` record's), not the parked tool call's.
230
+ *
231
+ * Never throws for a runtime refusal — each 409 means something different to
232
+ * the UI, so the answer comes back classified as a {@link ToolApprovalResult}.
233
+ * It does throw when the adapter has no approval route, which is a wiring bug
234
+ * rather than a runtime answer.
235
+ */
236
+ async submitToolApproval(controlId, approved, message) {
237
+ const url = this.adapter.resolveToolApprovalUrl?.();
238
+ if (!url) {
239
+ throw new Error(
240
+ "AlquimiaSDK: adapter does not support tool approval (resolveToolApprovalUrl missing)"
241
+ );
242
+ }
243
+ const event = {
244
+ event_class: "ToolApprovalEvent",
245
+ control_id: controlId,
246
+ result: approved,
247
+ ...message && { message }
229
248
  };
230
- await this.axiosInstance.post(url, response, { headers });
249
+ try {
250
+ await this.axiosInstance.post(url, event, { headers: this.buildDecisionHeaders() });
251
+ return { outcome: "accepted" };
252
+ } catch (error) {
253
+ return classifyApprovalError(error);
254
+ }
231
255
  }
232
256
  async generateImage(query) {
233
257
  if (!this.stableDiffusionProvider) {
@@ -298,6 +322,23 @@ var AlquimiaSDK = class {
298
322
  if (this.streamId) headers["task-id"] = this.streamId;
299
323
  return headers;
300
324
  }
325
+ /**
326
+ * Correlation headers for tool-completion and tool-approval: the runtime's
327
+ * `CommonAttributes` header aliases, with no separator. Not interchangeable
328
+ * with the kebab-case set in {@link buildIdentityHeaders}.
329
+ */
330
+ buildDecisionHeaders() {
331
+ return {
332
+ "Content-Type": "application/json",
333
+ assistantid: this.assistantId,
334
+ ...this.streamId && { taskid: this.streamId },
335
+ ...this.conversationId && { sessionid: this.conversationId },
336
+ ...this.userId && { userid: this.userId },
337
+ ...this.agentspaceId && { agentspaceid: this.agentspaceId },
338
+ ...this.versionTag && { versiontag: this.versionTag },
339
+ ...this.adapter.getHeaders?.() ?? {}
340
+ };
341
+ }
301
342
  getUrlStream() {
302
343
  if (!this.streamId) {
303
344
  throw new Error("Stream ID not initialized. Call sendMessage() first");
@@ -318,6 +359,28 @@ var AlquimiaSDK = class {
318
359
  getVersionTag() {
319
360
  return this.versionTag;
320
361
  }
362
+ /** Agentspace the runtime resolved for the current task, if any. */
363
+ getAgentspaceId() {
364
+ return this.agentspaceId;
365
+ }
321
366
  };
367
+ function classifyApprovalError(error) {
368
+ const response = error?.response;
369
+ const status = response?.status;
370
+ const data = response?.data;
371
+ const rawDetail = typeof data === "string" ? data : data?.detail ?? data?.error ?? error?.message;
372
+ const detail = typeof rawDetail === "string" ? rawDetail : JSON.stringify(rawDetail ?? "");
373
+ let outcome = "error";
374
+ if (status === 409) {
375
+ if (/original channel/i.test(detail)) outcome = "wrong-channel";
376
+ else if (/already been recorded/i.test(detail)) outcome = "already-decided";
377
+ else if (/no pending approval/i.test(detail)) outcome = "not-pending";
378
+ } else if (status === 401 || status === 403) {
379
+ outcome = "forbidden";
380
+ } else if (status === 404) {
381
+ outcome = "not-found";
382
+ }
383
+ return { outcome, ...status !== void 0 && { status }, detail };
384
+ }
322
385
  var alquimia_sdk_default = AlquimiaSDK;
323
386
  //# sourceMappingURL=index.js.map