@solidxai/core-ui 0.1.21-beta.5 → 0.1.22-beta.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 (106) hide show
  1. package/dist/components/core/card/SolidCardViewConfigure.js +1 -1
  2. package/dist/components/core/card/SolidCardViewConfigure.js.map +1 -1
  3. package/dist/components/core/card/SolidCardViewConfigure.tsx +1 -1
  4. package/dist/components/core/form/SolidFormView.d.ts.map +1 -1
  5. package/dist/components/core/form/SolidFormView.js +3 -2
  6. package/dist/components/core/form/SolidFormView.js.map +1 -1
  7. package/dist/components/core/form/SolidFormView.tsx +3 -1
  8. package/dist/components/core/form/fields/ISolidField.d.ts +1 -0
  9. package/dist/components/core/form/fields/ISolidField.d.ts.map +1 -1
  10. package/dist/components/core/form/fields/ISolidField.js.map +1 -1
  11. package/dist/components/core/form/fields/ISolidField.tsx +1 -0
  12. package/dist/components/core/form/fields/relations/SolidRelationManyToManyField.d.ts.map +1 -1
  13. package/dist/components/core/form/fields/relations/SolidRelationManyToManyField.js +1 -1
  14. package/dist/components/core/form/fields/relations/SolidRelationManyToManyField.js.map +1 -1
  15. package/dist/components/core/form/fields/relations/SolidRelationManyToManyField.tsx +1 -0
  16. package/dist/components/core/kanban/SolidKanbanView.d.ts.map +1 -1
  17. package/dist/components/core/kanban/SolidKanbanView.js +20 -17
  18. package/dist/components/core/kanban/SolidKanbanView.js.map +1 -1
  19. package/dist/components/core/kanban/SolidKanbanView.tsx +3 -2
  20. package/dist/components/core/kanban/SolidKanbanViewConfigure.js +1 -1
  21. package/dist/components/core/kanban/SolidKanbanViewConfigure.js.map +1 -1
  22. package/dist/components/core/kanban/SolidKanbanViewConfigure.tsx +1 -1
  23. package/dist/components/core/solid-agent/SolidAgent.module.css +11 -0
  24. package/dist/components/core/solid-agent/SolidAgentChat.d.ts.map +1 -1
  25. package/dist/components/core/solid-agent/SolidAgentChat.js +16 -6
  26. package/dist/components/core/solid-agent/SolidAgentChat.js.map +1 -1
  27. package/dist/components/core/solid-agent/SolidAgentChat.tsx +20 -4
  28. package/dist/components/core/solid-agent/SolidAgentMarkdown.d.ts +7 -3
  29. package/dist/components/core/solid-agent/SolidAgentMarkdown.d.ts.map +1 -1
  30. package/dist/components/core/solid-agent/SolidAgentMarkdown.js +17 -12
  31. package/dist/components/core/solid-agent/SolidAgentMarkdown.js.map +1 -1
  32. package/dist/components/core/solid-agent/SolidAgentMarkdown.tsx +18 -11
  33. package/dist/components/core/solid-agent/agentMarkdown.d.ts +20 -0
  34. package/dist/components/core/solid-agent/agentMarkdown.d.ts.map +1 -0
  35. package/dist/components/core/solid-agent/agentMarkdown.js +140 -0
  36. package/dist/components/core/solid-agent/agentMarkdown.js.map +1 -0
  37. package/dist/components/core/solid-agent/agentMarkdown.ts +140 -0
  38. package/dist/components/core/solid-agent/client/agentRuntime.d.ts.map +1 -1
  39. package/dist/components/core/solid-agent/client/agentRuntime.js +22 -14
  40. package/dist/components/core/solid-agent/client/agentRuntime.js.map +1 -1
  41. package/dist/components/core/solid-agent/client/agentRuntime.ts +8 -1
  42. package/dist/components/core/solid-agent/client/agentSocket.d.ts.map +1 -1
  43. package/dist/components/core/solid-agent/client/agentSocket.js +4 -4
  44. package/dist/components/core/solid-agent/client/agentSocket.js.map +1 -1
  45. package/dist/components/core/solid-agent/client/agentSocket.ts +5 -2
  46. package/dist/components/core/solid-agent/embed/AgentEmbeddingPanel.js +1 -1
  47. package/dist/components/core/solid-agent/embed/AgentEmbeddingPanel.js.map +1 -1
  48. package/dist/components/core/solid-agent/embed/AgentEmbeddingPanel.tsx +1 -1
  49. package/dist/components/core/solid-agent/embed/agentEmbedProtocol.d.ts.map +1 -1
  50. package/dist/components/core/solid-agent/embed/agentEmbedProtocol.js +2 -0
  51. package/dist/components/core/solid-agent/embed/agentEmbedProtocol.js.map +1 -1
  52. package/dist/components/core/solid-agent/embed/agentEmbedProtocol.ts +1 -0
  53. package/dist/components/core/solid-agent/embed/agentEmbedSamples.js +7 -7
  54. package/dist/components/core/solid-agent/embed/agentEmbedSamples.js.map +1 -1
  55. package/dist/components/core/solid-agent/embed/agentEmbedSamples.ts +24 -24
  56. package/dist/components/core/solid-agent/thread/inlineWidget.d.ts +1 -2
  57. package/dist/components/core/solid-agent/thread/inlineWidget.d.ts.map +1 -1
  58. package/dist/components/core/solid-agent/thread/inlineWidget.js +82 -42
  59. package/dist/components/core/solid-agent/thread/inlineWidget.js.map +1 -1
  60. package/dist/components/core/solid-agent/thread/inlineWidget.ts +69 -39
  61. package/dist/components/core/solid-agent/types.d.ts +4 -0
  62. package/dist/components/core/solid-agent/types.d.ts.map +1 -1
  63. package/dist/components/core/solid-agent/types.js.map +1 -1
  64. package/dist/components/core/solid-agent/types.ts +4 -0
  65. package/dist/components/core/solid-agent/widgets/SolidDiffListChatWidget.d.ts.map +1 -1
  66. package/dist/components/core/solid-agent/widgets/SolidDiffListChatWidget.js +12 -3
  67. package/dist/components/core/solid-agent/widgets/SolidDiffListChatWidget.js.map +1 -1
  68. package/dist/components/core/solid-agent/widgets/SolidDiffListChatWidget.tsx +13 -4
  69. package/dist/components/core/solid-agent/widgets/SolidStatusChatWidget.d.ts +3 -2
  70. package/dist/components/core/solid-agent/widgets/SolidStatusChatWidget.d.ts.map +1 -1
  71. package/dist/components/core/solid-agent/widgets/SolidStatusChatWidget.js +7 -3
  72. package/dist/components/core/solid-agent/widgets/SolidStatusChatWidget.js.map +1 -1
  73. package/dist/components/core/solid-agent/widgets/SolidStatusChatWidget.tsx +19 -3
  74. package/dist/components/core/solid-agent/widgets/solidChatWidgets.module.css +3 -0
  75. package/dist/components/shad-cn-ui/SolidDialog.js +1 -1
  76. package/dist/components/shad-cn-ui/SolidDialog.js.map +1 -1
  77. package/dist/components/shad-cn-ui/SolidDialog.tsx +1 -1
  78. package/dist/redux/api/solidEntityApi.d.ts +1 -0
  79. package/dist/redux/api/solidEntityApi.d.ts.map +1 -1
  80. package/dist/redux/api/solidEntityApi.js +14 -0
  81. package/dist/redux/api/solidEntityApi.js.map +1 -1
  82. package/dist/redux/api/solidEntityApi.tsx +8 -0
  83. package/dist/redux/api/solidMenuApi.d.ts +11 -11
  84. package/dist/redux/api/solidMenuApi.d.ts.map +1 -1
  85. package/dist/redux/api/solidMenuApi.js +2 -0
  86. package/dist/redux/api/solidMenuApi.js.map +1 -1
  87. package/dist/redux/api/solidMenuApi.ts +2 -0
  88. package/dist/redux/features/agentSlice.d.ts +3 -1
  89. package/dist/redux/features/agentSlice.d.ts.map +1 -1
  90. package/dist/redux/features/agentSlice.js +7 -4
  91. package/dist/redux/features/agentSlice.js.map +1 -1
  92. package/dist/redux/features/agentSlice.ts +9 -3
  93. package/dist/redux/store/defaultStoreConfig.d.ts +8 -8
  94. package/dist/resources/stylesheets/_main.scss +41 -16
  95. package/dist/routes/AppEventListener.d.ts.map +1 -1
  96. package/dist/routes/AppEventListener.js +16 -0
  97. package/dist/routes/AppEventListener.js.map +1 -1
  98. package/dist/routes/AppEventListener.tsx +16 -0
  99. package/dist/routes/pages/admin/core/AgentRegistryEditorPage.js +4 -4
  100. package/dist/routes/pages/admin/core/AgentRegistryEditorPage.js.map +1 -1
  101. package/dist/routes/pages/admin/core/AgentRegistryEditorPage.tsx +4 -4
  102. package/dist/routes/pages/admin/core/DatasourceIntrospectionPage.d.ts.map +1 -1
  103. package/dist/routes/pages/admin/core/DatasourceIntrospectionPage.js +3 -0
  104. package/dist/routes/pages/admin/core/DatasourceIntrospectionPage.js.map +1 -1
  105. package/dist/routes/pages/admin/core/DatasourceIntrospectionPage.tsx +3 -0
  106. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"agentSocket.js","sourceRoot":"","sources":["../../../../../src/components/core/solid-agent/client/agentSocket.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,uBAAuB,EAAE,aAAa,EAAE,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,CAAC,EAAA;;4BAAzC,IAAI,CAAC,CAAC,SAAmC,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,IAAI,IAAI,CAAC,OAAO,KAAK,aAAa,EAAE;gCAChG,iFAAiF;gCACjF,gFAAgF;gCAChF,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;6BACjC;;;4BAED,IAAI,CAAC,2BAA2B,GAAG,KAAK,CAAC;;;;;;SAEhD;;;;;;eAED,UAAkB,MAAuB;YACrC,IAAI,IAAI,CAAC,UAAU;gBAAE,OAAO,CAAC,IAAI,CAAC,0CAA0C,EAAE,EAAE,MAAM,QAAA,EAAE,CAAC,CAAC;YAC1F,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,UAAC,QAAQ,IAAK,OAAA,QAAQ,CAAC,MAAM,CAAC,EAAhB,CAAgB,CAAC,CAAC;QACjE,CAAC;;;;;;eAED,UAAqB,GAAmB;YAAnB,oBAAA,EAAA,MAAM,IAAI,CAAC,QAAQ;YACpC,IAAI;gBACA,IAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;gBAC5B,OAAO,UAAG,MAAM,CAAC,MAAM,SAAG,MAAM,CAAC,QAAQ,CAAE,CAAC;aAC/C;YAAC,WAAM;gBACJ,OAAO,aAAa,CAAC;aACxB;QACL,CAAC;;IACL,kBAAC;AAAD,CAAC,AA3YD,IA2YC","sourcesContent":["import type { AgentAction, AgentConnection, AgentRuntimeType, AgentSessionOptions, AgentWireFrame } from \"../types\";\nimport type { AgentChatWidgetMetadata } from \"../../../../types/extension-registry\";\nimport { agentWsUrl, clearAgentAuth, isAgentProcessAvailable, loadAgentAuth, onAgentAuthChange } from \"./agentAuth\";\n\n/**\n * WebSocket client for the agent, connecting to the full `wsUrl` named at sign-in (agentAuth.ts).\n *\n * Held outside Redux because sockets are not serializable; the host wires its listeners to\n * dispatch into agentSlice. Every outbound frame carries the `agentToken` from the agent login;\n * there is no socket until the user has signed in with an API key, and signing out closes it. Unexpected closes\n * reconnect with backoff (1s, 2s, 4s, then 15s) and re-send `resume_session`; frames sent\n * while disconnected are queued and flushed once the session is re-established.\n */\n\nconst BACKOFF_MS = [1000, 2000, 4000, 8000, 15000];\n\ntype EventListener = (frame: AgentWireFrame) => void;\ntype StatusListener = (status: AgentConnection) => void;\ntype SentListener = (action: AgentAction) => void;\n\nexport class AgentSocket {\n private ws: WebSocket | null = null;\n private attempt = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private closedByUser = false;\n private queue: AgentAction[] = [];\n private eventListeners = new Set<EventListener>();\n private statusListeners = new Set<StatusListener>();\n private sentListeners = new Set<SentListener>();\n private sessionId: string | null = null;\n private provider: string | null = null;\n private model: string | null = null;\n private sessionOptions: AgentSessionOptions = {};\n /** False until the agent confirms the session (session_started) on the current socket. */\n private sessionReady = false;\n private checkingProcessAvailability = false;\n private unacknowledgedMessage: AgentAction | null = null;\n private onSessionExpiredHook: (() => void) | null = null;\n\n private offAuthChange: () => void;\n private readonly debugEmbed: boolean;\n\n constructor(\n private agentUrl: string,\n private initialSessionId: string | null = null,\n private checkProcessAvailability = false,\n initialProvider: string | null = null,\n initialModel: string | null = null,\n initialOptions?: AgentSessionOptions,\n private widgetCatalog: AgentChatWidgetMetadata[] = [],\n ) {\n this.sessionId = initialSessionId;\n this.provider = initialProvider;\n this.model = initialModel;\n if (initialOptions) this.sessionOptions = { ...initialOptions };\n this.debugEmbed = !checkProcessAvailability;\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] socket created\", { endpoint: this.safeEndpoint(), hasInitialSession: !!initialSessionId, provider: initialProvider, model: initialModel, options: initialOptions });\n // Signing in opens the socket on the wsUrl it named; signing out (or the token expiring) closes it.\n this.offAuthChange = onAgentAuthChange(agentUrl, () => {\n if (this.closedByUser) return;\n if (agentWsUrl(agentUrl)) this.connect();\n else this.disconnect();\n });\n }\n\n get runtime(): AgentRuntimeType {\n return this.checkProcessAvailability ? \"agentHub\" : \"solidx\";\n }\n\n private openSession() {\n const provider = this.provider ?? undefined;\n const model = this.model ?? undefined;\n const runtime = this.runtime;\n void this.sendRaw(\n this.sessionId\n ? { action: \"resume_session\", session_id: this.sessionId, provider, model, runtime, ...this.sessionOptions }\n : { action: \"start_session\", provider, model, runtime, ...this.sessionOptions }\n );\n }\n\n get currentSessionId() {\n return this.sessionId;\n }\n\n get currentProvider() {\n return this.provider;\n }\n\n get currentModel() {\n return this.model;\n }\n\n get currentSessionOptions(): Readonly<AgentSessionOptions> {\n return this.sessionOptions;\n }\n\n setProvider(provider: string, model?: string) {\n this.provider = provider;\n if (model !== undefined) this.model = model;\n }\n\n setOnSessionExpired(listener: () => void) {\n this.onSessionExpiredHook = listener;\n }\n\n onEvent(listener: EventListener) {\n this.eventListeners.add(listener);\n return () => this.eventListeners.delete(listener);\n }\n\n onStatus(listener: StatusListener) {\n this.statusListeners.add(listener);\n return () => this.statusListeners.delete(listener);\n }\n\n onSent(listener: SentListener) {\n this.sentListeners.add(listener);\n return () => this.sentListeners.delete(listener);\n }\n\n connect() {\n if (this.closedByUser) return;\n const state = this.ws?.readyState;\n if (state === WebSocket.OPEN || state === WebSocket.CONNECTING) return;\n this.closedByUser = false;\n const url = agentWsUrl(this.agentUrl);\n if (!url) {\n if (this.debugEmbed) console.warn(\"[agent-embed][runtime] no WebSocket URL is available from auth yet\");\n // Not signed in: the auth listener connects once sign-in names the wsUrl.\n this.setStatus(\"idle\");\n return;\n }\n this.setStatus(this.attempt === 0 ? \"connecting\" : \"reconnecting\");\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] opening WebSocket\", { endpoint: this.safeEndpoint(url), attempt: this.attempt + 1 });\n\n let ws: WebSocket;\n try {\n ws = new WebSocket(url);\n } catch (error) {\n if (this.debugEmbed) console.error(\"[agent-embed][runtime] WebSocket construction failed\", { name: error instanceof Error ? error.name : \"unknown\", message: error instanceof Error ? error.message : String(error) });\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n\n ws.onopen = () => {\n if (this.ws !== ws) return;\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] WebSocket open\");\n this.attempt = 0;\n this.sessionReady = false;\n this.setStatus(\"open\");\n this.openSession();\n };\n\n ws.onmessage = (message) => {\n if (this.ws !== ws) return;\n let frame: AgentWireFrame;\n try {\n frame = JSON.parse(message.data);\n } catch {\n return;\n }\n const eventType = frame.event_type ?? frame.type;\n const payload = frame.event_data ?? frame.data;\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] WebSocket frame\", { eventType, hasSessionId: !!(frame.session_id ?? payload?.session_id), isError: eventType === \"error\" });\n if (eventType === \"session_started\" || eventType === \"session_updated\") {\n // After an agent restart the old session is gone and resume returns a new id.\n this.sessionId = frame.session_id ?? payload?.session_id ?? this.sessionId;\n const p = frame.provider ?? payload?.provider;\n if (p) this.provider = p;\n const m = frame.model ?? payload?.model;\n if (m) this.model = m;\n if (eventType === \"session_started\") {\n this.sessionReady = true;\n this.flushQueue();\n }\n } else if (eventType === \"error\" && /agent token/i.test(String(payload?.error ?? \"\"))) {\n // The agent forgot the token (idle 30 min or restarted): sign in again.\n this.sessionReady = false;\n if (this.unacknowledgedMessage) this.queue.push(this.unacknowledgedMessage);\n this.unacknowledgedMessage = null;\n clearAgentAuth(this.agentUrl);\n } else if (\n eventType === \"error\" &&\n (payload?.code === \"SESSION_NOT_FOUND\" ||\n payload?.code === \"SESSION_EXPIRED\" ||\n frame?.code === \"SESSION_NOT_FOUND\" ||\n frame?.code === \"SESSION_EXPIRED\" ||\n /session (?:not found|does not exist|expired)|unknown session/i.test(String(payload?.error ?? frame?.error ?? \"\")))\n ) {\n // The session no longer exists on the agent server (e.g. server restarted or CLI session expired).\n if (this.debugEmbed) console.warn(\"[agent-embed][runtime] session not found or expired; recovering with fresh session\", { error: payload?.error, code: payload?.code });\n this.sessionId = null;\n this.sessionReady = false;\n if (this.unacknowledgedMessage) this.queue.push(this.unacknowledgedMessage);\n this.unacknowledgedMessage = null;\n this.onSessionExpiredHook?.();\n const provider = this.provider ?? undefined;\n const model = this.model ?? undefined;\n void this.sendRaw({\n action: \"start_session\",\n provider,\n model,\n runtime: this.runtime,\n ...this.sessionOptions,\n });\n return;\n } else if (eventType === \"error\" && !this.sessionReady) {\n // Start/resume failed (e.g. auth); stop holding messages so their errors show.\n this.sessionReady = true;\n this.flushQueue();\n }\n if (eventType === \"UserMessage\" || eventType === \"turn_complete\" || eventType === \"error\") {\n this.unacknowledgedMessage = null;\n }\n // Drop frames for a different session (e.g. background session still running or after a switch).\n const frameSession = frame.session_id ?? payload?.session_id;\n if (eventType !== \"session_started\") {\n if (frameSession && frameSession !== this.sessionId) return;\n if (!frameSession && this.sessionId && eventType !== \"error\") return;\n if (!this.sessionId && eventType !== \"error\") return;\n }\n this.eventListeners.forEach((listener) => listener(frame));\n };\n\n ws.onclose = (event) => {\n if (this.ws !== ws) return;\n if (this.debugEmbed) console.warn(\"[agent-embed][runtime] WebSocket closed\", { code: event.code, reason: event.reason, clean: event.wasClean });\n this.ws = null;\n this.sessionReady = false;\n if (this.closedByUser) {\n this.setStatus(\"idle\");\n return;\n }\n this.scheduleReconnect();\n };\n\n ws.onerror = () => {\n if (this.debugEmbed) console.error(\"[agent-embed][runtime] WebSocket error event\");\n // onclose follows and handles the reconnect.\n };\n }\n\n /** Sends an action, or queues it until the socket and session are ready. */\n send(action: AgentAction) {\n if (this.closedByUser) return;\n const resolvedAction: AgentAction =\n action.action === \"message\"\n ? { ...this.sessionOptions, ...action }\n : action;\n if (this.ws?.readyState === WebSocket.OPEN && this.sessionId && this.sessionReady) {\n void this.sendRaw(resolvedAction);\n } else {\n this.queue.push(resolvedAction);\n this.connect();\n }\n }\n\n /** Starts a fresh conversation (drops the current session id). */\n newSession(opts?: { provider?: string; model?: string } & AgentSessionOptions) {\n if (opts?.provider) this.provider = opts.provider;\n if (opts?.model !== undefined) this.model = opts.model;\n if (opts) {\n const { provider: _p, model: _m, ...rest } = opts;\n this.sessionOptions = { ...this.sessionOptions, ...rest };\n }\n this.unacknowledgedMessage = null;\n this.sessionId = null;\n this.sessionReady = false;\n this.queue = [];\n const payload: AgentAction = {\n action: \"start_session\",\n provider: this.provider ?? undefined,\n model: this.model ?? undefined,\n runtime: this.runtime,\n ...this.sessionOptions,\n };\n if (this.ws?.readyState === WebSocket.OPEN) void this.sendRaw(payload);\n else this.connect();\n }\n\n /** Updates provider, model, or parameters for the active session. */\n updateSession(opts: { provider?: string; model?: string } & AgentSessionOptions) {\n if (opts.provider) this.provider = opts.provider;\n if (opts.model !== undefined) this.model = opts.model;\n const { provider: _p, model: _m, ...rest } = opts;\n this.sessionOptions = { ...this.sessionOptions, ...rest };\n if (this.sessionId && this.ws?.readyState === WebSocket.OPEN) {\n void this.sendRaw({\n action: \"update_session\",\n session_id: this.sessionId,\n provider: this.provider ?? undefined,\n model: this.model ?? undefined,\n runtime: this.runtime,\n ...this.sessionOptions,\n });\n }\n }\n\n /** Switches to an existing conversation. */\n resume(sessionId: string, opts?: { provider?: string; model?: string } & AgentSessionOptions) {\n if (opts?.provider) this.provider = opts.provider;\n if (opts?.model !== undefined) this.model = opts.model;\n if (opts) {\n const { provider: _p, model: _m, ...rest } = opts;\n this.sessionOptions = { ...this.sessionOptions, ...rest };\n }\n this.sessionId = sessionId;\n this.sessionReady = false;\n if (this.ws?.readyState === WebSocket.OPEN) {\n void this.sendRaw({\n action: \"resume_session\",\n session_id: sessionId,\n provider: this.provider ?? undefined,\n model: this.model ?? undefined,\n runtime: this.runtime,\n ...this.sessionOptions,\n });\n } else {\n this.connect();\n }\n }\n\n /** Closes for good (the runtime is being disposed). */\n close() {\n this.offAuthChange();\n this.closedByUser = true;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.ws?.close();\n this.ws = null;\n }\n\n /** Drops the socket after sign-out; the next sign-in reconnects. */\n private disconnect() {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.attempt = 0;\n this.sessionReady = false;\n if (this.ws) {\n this.ws.onclose = null; // No reconnect.\n this.ws.close();\n this.ws = null;\n }\n this.setStatus(\"idle\");\n }\n\n private flushQueue() {\n const pending = this.queue;\n this.queue = [];\n pending.forEach((action) => {\n // Queued messages were addressed before a session existed; point them at the current one.\n const addressed = \"session_id\" in action && this.sessionId ? { ...action, session_id: this.sessionId } : action;\n void this.sendRaw(addressed as AgentAction);\n });\n }\n\n private async sendRaw(action: AgentAction) {\n const agentToken = (await loadAgentAuth(this.agentUrl))?.agentToken;\n if (!agentToken || this.ws?.readyState !== WebSocket.OPEN) {\n if (this.debugEmbed) console.warn(\"[agent-embed][runtime] skipped outbound frame\", { action: action.action, hasAgentToken: !!agentToken, socketOpen: this.ws?.readyState === WebSocket.OPEN });\n if (action.action !== \"start_session\" && action.action !== \"resume_session\") this.queue.push(action);\n return;\n }\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] sending WebSocket action\", { action: action.action });\n this.ws.send(JSON.stringify({ ...action, agentToken }));\n if (action.action === \"message\") {\n this.unacknowledgedMessage = action;\n this.sentListeners.forEach((listener) => listener(action));\n }\n }\n\n private scheduleReconnect() {\n if (this.timer) return;\n const delay = BACKOFF_MS[Math.min(this.attempt, BACKOFF_MS.length - 1)];\n this.attempt += 1;\n this.setStatus(this.attempt > BACKOFF_MS.length ? \"offline\" : \"reconnecting\");\n if (this.checkProcessAvailability && this.attempt >= 2 && this.attempt % 3 === 2) {\n void this.checkAgentProcess(this.attempt);\n }\n this.timer = setTimeout(() => {\n this.timer = null;\n this.connect();\n }, delay);\n }\n\n private async checkAgentProcess(failedAttempt: number) {\n if (this.checkingProcessAvailability) return;\n this.checkingProcessAvailability = true;\n try {\n const auth = await loadAgentAuth(this.agentUrl);\n if (!auth || this.closedByUser || this.attempt !== failedAttempt) return;\n if (!(await isAgentProcessAvailable(auth)) && !this.closedByUser && this.attempt === failedAttempt) {\n // Repeated WebSocket failures plus a failed process health check mean the stored\n // endpoint is stale. Returning to sign-in lets the manager issue a fresh wsUrl.\n clearAgentAuth(this.agentUrl);\n }\n } finally {\n this.checkingProcessAvailability = false;\n }\n }\n\n private setStatus(status: AgentConnection) {\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] connection status\", { status });\n this.statusListeners.forEach((listener) => listener(status));\n }\n\n private safeEndpoint(url = this.agentUrl) {\n try {\n const parsed = new URL(url);\n return `${parsed.origin}${parsed.pathname}`;\n } catch {\n return \"invalid-url\";\n }\n }\n}\n"]}
1
+ {"version":3,"file":"agentSocket.js","sourceRoot":"","sources":["../../../../../src/components/core/solid-agent/client/agentSocket.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,uBAAuB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEpH;;;;;;;;GAQG;AAEH,IAAM,UAAU,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;AAMnD;IAsBI,qBACY,QAAgB,EAChB,gBAAsC,EACtC,wBAAgC,EACxC,eAAqC,EACrC,YAAkC,EAClC,cAAoC,EAC5B,aAA6C;QAPzD,iBAqBC;QAnBW,iCAAA,EAAA,uBAAsC;QACtC,yCAAA,EAAA,gCAAgC;QACxC,gCAAA,EAAA,sBAAqC;QACrC,6BAAA,EAAA,mBAAkC;QAE1B,8BAAA,EAAA,kBAA6C;QANrD;;;;mBAAQ,QAAQ;WAAQ;QACxB;;;;mBAAQ,gBAAgB;WAAsB;QAC9C;;;;mBAAQ,wBAAwB;WAAQ;QAIxC;;;;mBAAQ,aAAa;WAAgC;QA5BjD;;;;mBAAuB,IAAI;WAAC;QAC5B;;;;mBAAU,CAAC;WAAC;QACZ;;;;mBAA8C,IAAI;WAAC;QACnD;;;;mBAAe,KAAK;WAAC;QACrB;;;;mBAAuB,EAAE;WAAC;QAC1B;;;;mBAAiB,IAAI,GAAG,EAAiB;WAAC;QAC1C;;;;mBAAkB,IAAI,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AA,MAAM,IAAI,CAAC,QAAQ;YACpC,IAAI;gBACA,IAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;gBAC5B,OAAO,UAAG,MAAM,CAAC,MAAM,SAAG,MAAM,CAAC,QAAQ,CAAE,CAAC;aAC/C;YAAC,WAAM;gBACJ,OAAO,aAAa,CAAC;aACxB;QACL,CAAC;;IACL,kBAAC;AAAD,CAAC,AA9YD,IA8YC","sourcesContent":["import type { AgentAction, AgentConnection, AgentRuntimeType, AgentSessionOptions, AgentWireFrame } from \"../types\";\nimport type { AgentChatWidgetMetadata } from \"../../../../types/extension-registry\";\nimport { agentWsUrl, clearAgentAuth, isAgentProcessAvailable, loadAgentAuth, onAgentAuthChange } from \"./agentAuth\";\n\n/**\n * WebSocket client for the agent, connecting to the full `wsUrl` named at sign-in (agentAuth.ts).\n *\n * Held outside Redux because sockets are not serializable; the host wires its listeners to\n * dispatch into agentSlice. Every outbound frame carries the `agentToken` from the agent login;\n * there is no socket until the user has signed in with an API key, and signing out closes it. Unexpected closes\n * reconnect with backoff (1s, 2s, 4s, then 15s) and re-send `resume_session`; frames sent\n * while disconnected are queued and flushed once the session is re-established.\n */\n\nconst BACKOFF_MS = [1000, 2000, 4000, 8000, 15000];\n\ntype EventListener = (frame: AgentWireFrame) => void;\ntype StatusListener = (status: AgentConnection) => void;\ntype SentListener = (action: AgentAction) => void;\n\nexport class AgentSocket {\n private ws: WebSocket | null = null;\n private attempt = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private closedByUser = false;\n private queue: AgentAction[] = [];\n private eventListeners = new Set<EventListener>();\n private statusListeners = new Set<StatusListener>();\n private sentListeners = new Set<SentListener>();\n private sessionId: string | null = null;\n private provider: string | null = null;\n private model: string | null = null;\n private sessionOptions: AgentSessionOptions = {};\n /** False until the agent confirms the session (session_started) on the current socket. */\n private sessionReady = false;\n private checkingProcessAvailability = false;\n private unacknowledgedMessage: AgentAction | null = null;\n private onSessionExpiredHook: (() => void) | null = null;\n\n private offAuthChange: () => void;\n private readonly debugEmbed: boolean;\n\n constructor(\n private agentUrl: string,\n private initialSessionId: string | null = null,\n private checkProcessAvailability = false,\n initialProvider: string | null = null,\n initialModel: string | null = null,\n initialOptions?: AgentSessionOptions,\n private widgetCatalog: AgentChatWidgetMetadata[] = [],\n ) {\n this.sessionId = initialSessionId;\n this.provider = initialProvider;\n this.model = initialModel;\n if (initialOptions) this.sessionOptions = { ...initialOptions };\n this.debugEmbed = !checkProcessAvailability;\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] socket created\", { endpoint: this.safeEndpoint(), hasInitialSession: !!initialSessionId, provider: initialProvider, model: initialModel, options: initialOptions });\n // Signing in opens the socket on the wsUrl it named; signing out (or the token expiring) closes it.\n this.offAuthChange = onAgentAuthChange(agentUrl, () => {\n if (this.closedByUser) return;\n if (agentWsUrl(agentUrl)) this.connect();\n else this.disconnect();\n });\n }\n\n get runtime(): AgentRuntimeType {\n return this.checkProcessAvailability ? \"agentHub\" : \"solidx\";\n }\n\n private openSession() {\n const provider = this.provider ?? undefined;\n const model = this.model ?? undefined;\n const runtime = this.runtime;\n void this.sendRaw(\n this.sessionId\n ? { action: \"resume_session\", session_id: this.sessionId, provider, model, runtime, widget_catalog: this.widgetCatalog, ...this.sessionOptions }\n : { action: \"start_session\", provider, model, runtime, widget_catalog: this.widgetCatalog, ...this.sessionOptions }\n );\n }\n\n get currentSessionId() {\n return this.sessionId;\n }\n\n get currentProvider() {\n return this.provider;\n }\n\n get currentModel() {\n return this.model;\n }\n\n get currentSessionOptions(): Readonly<AgentSessionOptions> {\n return this.sessionOptions;\n }\n\n setProvider(provider: string, model?: string) {\n this.provider = provider;\n if (model !== undefined) this.model = model;\n }\n\n setOnSessionExpired(listener: () => void) {\n this.onSessionExpiredHook = listener;\n }\n\n onEvent(listener: EventListener) {\n this.eventListeners.add(listener);\n return () => this.eventListeners.delete(listener);\n }\n\n onStatus(listener: StatusListener) {\n this.statusListeners.add(listener);\n return () => this.statusListeners.delete(listener);\n }\n\n onSent(listener: SentListener) {\n this.sentListeners.add(listener);\n return () => this.sentListeners.delete(listener);\n }\n\n connect() {\n if (this.closedByUser) return;\n const state = this.ws?.readyState;\n if (state === WebSocket.OPEN || state === WebSocket.CONNECTING) return;\n this.closedByUser = false;\n const url = agentWsUrl(this.agentUrl);\n if (!url) {\n if (this.debugEmbed) console.warn(\"[agent-embed][runtime] no WebSocket URL is available from auth yet\");\n // Not signed in: the auth listener connects once sign-in names the wsUrl.\n this.setStatus(\"idle\");\n return;\n }\n this.setStatus(this.attempt === 0 ? \"connecting\" : \"reconnecting\");\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] opening WebSocket\", { endpoint: this.safeEndpoint(url), attempt: this.attempt + 1 });\n\n let ws: WebSocket;\n try {\n ws = new WebSocket(url);\n } catch (error) {\n if (this.debugEmbed) console.error(\"[agent-embed][runtime] WebSocket construction failed\", { name: error instanceof Error ? error.name : \"unknown\", message: error instanceof Error ? error.message : String(error) });\n this.scheduleReconnect();\n return;\n }\n this.ws = ws;\n\n ws.onopen = () => {\n if (this.ws !== ws) return;\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] WebSocket open\");\n this.attempt = 0;\n this.sessionReady = false;\n this.setStatus(\"open\");\n this.openSession();\n };\n\n ws.onmessage = (message) => {\n if (this.ws !== ws) return;\n let frame: AgentWireFrame;\n try {\n frame = JSON.parse(message.data);\n } catch {\n return;\n }\n const eventType = frame.event_type ?? frame.type;\n const payload = frame.event_data ?? frame.data;\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] WebSocket frame\", { eventType, hasSessionId: !!(frame.session_id ?? payload?.session_id), isError: eventType === \"error\" });\n if (eventType === \"session_started\" || eventType === \"session_updated\") {\n // After an agent restart the old session is gone and resume returns a new id.\n this.sessionId = frame.session_id ?? payload?.session_id ?? this.sessionId;\n const p = frame.provider ?? payload?.provider;\n if (p) this.provider = p;\n const m = frame.model ?? payload?.model;\n if (m) this.model = m;\n if (eventType === \"session_started\") {\n this.sessionReady = true;\n this.flushQueue();\n }\n } else if (eventType === \"error\" && /agent token/i.test(String(payload?.error ?? \"\"))) {\n // The agent forgot the token (idle 30 min or restarted): sign in again.\n this.sessionReady = false;\n if (this.unacknowledgedMessage) this.queue.push(this.unacknowledgedMessage);\n this.unacknowledgedMessage = null;\n clearAgentAuth(this.agentUrl);\n } else if (\n eventType === \"error\" &&\n (payload?.code === \"SESSION_NOT_FOUND\" ||\n payload?.code === \"SESSION_EXPIRED\" ||\n frame?.code === \"SESSION_NOT_FOUND\" ||\n frame?.code === \"SESSION_EXPIRED\" ||\n /session (?:not found|does not exist|expired)|unknown session/i.test(String(payload?.error ?? frame?.error ?? \"\")))\n ) {\n // The session no longer exists on the agent server (e.g. server restarted or CLI session expired).\n if (this.debugEmbed) console.warn(\"[agent-embed][runtime] session not found or expired; recovering with fresh session\", { error: payload?.error, code: payload?.code });\n this.sessionId = null;\n this.sessionReady = false;\n if (this.unacknowledgedMessage) this.queue.push(this.unacknowledgedMessage);\n this.unacknowledgedMessage = null;\n this.onSessionExpiredHook?.();\n const provider = this.provider ?? undefined;\n const model = this.model ?? undefined;\n void this.sendRaw({\n action: \"start_session\",\n provider,\n model,\n runtime: this.runtime,\n widget_catalog: this.widgetCatalog,\n ...this.sessionOptions,\n });\n return;\n } else if (eventType === \"error\" && !this.sessionReady) {\n // Start/resume failed (e.g. auth); stop holding messages so their errors show.\n this.sessionReady = true;\n this.flushQueue();\n }\n if (eventType === \"UserMessage\" || eventType === \"turn_complete\" || eventType === \"error\") {\n this.unacknowledgedMessage = null;\n }\n // Drop frames for a different session (e.g. background session still running or after a switch).\n const frameSession = frame.session_id ?? payload?.session_id;\n if (eventType !== \"session_started\") {\n if (frameSession && frameSession !== this.sessionId) return;\n if (!frameSession && this.sessionId && eventType !== \"error\") return;\n if (!this.sessionId && eventType !== \"error\") return;\n }\n this.eventListeners.forEach((listener) => listener(frame));\n };\n\n ws.onclose = (event) => {\n if (this.ws !== ws) return;\n if (this.debugEmbed) console.warn(\"[agent-embed][runtime] WebSocket closed\", { code: event.code, reason: event.reason, clean: event.wasClean });\n this.ws = null;\n this.sessionReady = false;\n if (this.closedByUser) {\n this.setStatus(\"idle\");\n return;\n }\n this.scheduleReconnect();\n };\n\n ws.onerror = () => {\n if (this.debugEmbed) console.error(\"[agent-embed][runtime] WebSocket error event\");\n // onclose follows and handles the reconnect.\n };\n }\n\n /** Sends an action, or queues it until the socket and session are ready. */\n send(action: AgentAction) {\n if (this.closedByUser) return;\n const resolvedAction: AgentAction =\n action.action === \"message\"\n ? { ...this.sessionOptions, ...action }\n : action;\n if (this.ws?.readyState === WebSocket.OPEN && this.sessionId && this.sessionReady) {\n void this.sendRaw(resolvedAction);\n } else {\n this.queue.push(resolvedAction);\n this.connect();\n }\n }\n\n /** Starts a fresh conversation (drops the current session id). */\n newSession(opts?: { provider?: string; model?: string } & AgentSessionOptions) {\n if (opts?.provider) this.provider = opts.provider;\n if (opts?.model !== undefined) this.model = opts.model;\n if (opts) {\n const { provider: _p, model: _m, ...rest } = opts;\n this.sessionOptions = { ...this.sessionOptions, ...rest };\n }\n this.unacknowledgedMessage = null;\n this.sessionId = null;\n this.sessionReady = false;\n this.queue = [];\n const payload: AgentAction = {\n action: \"start_session\",\n provider: this.provider ?? undefined,\n model: this.model ?? undefined,\n runtime: this.runtime,\n widget_catalog: this.widgetCatalog,\n ...this.sessionOptions,\n };\n if (this.ws?.readyState === WebSocket.OPEN) void this.sendRaw(payload);\n else this.connect();\n }\n\n /** Updates provider, model, or parameters for the active session. */\n updateSession(opts: { provider?: string; model?: string } & AgentSessionOptions) {\n if (opts.provider) this.provider = opts.provider;\n if (opts.model !== undefined) this.model = opts.model;\n const { provider: _p, model: _m, ...rest } = opts;\n this.sessionOptions = { ...this.sessionOptions, ...rest };\n if (this.sessionId && this.ws?.readyState === WebSocket.OPEN) {\n void this.sendRaw({\n action: \"update_session\",\n session_id: this.sessionId,\n provider: this.provider ?? undefined,\n model: this.model ?? undefined,\n runtime: this.runtime,\n ...this.sessionOptions,\n });\n }\n }\n\n /** Switches to an existing conversation. */\n resume(sessionId: string, opts?: { provider?: string; model?: string } & AgentSessionOptions) {\n if (opts?.provider) this.provider = opts.provider;\n if (opts?.model !== undefined) this.model = opts.model;\n if (opts) {\n const { provider: _p, model: _m, ...rest } = opts;\n this.sessionOptions = { ...this.sessionOptions, ...rest };\n }\n this.sessionId = sessionId;\n this.sessionReady = false;\n if (this.ws?.readyState === WebSocket.OPEN) {\n void this.sendRaw({\n action: \"resume_session\",\n session_id: sessionId,\n provider: this.provider ?? undefined,\n model: this.model ?? undefined,\n runtime: this.runtime,\n widget_catalog: this.widgetCatalog,\n ...this.sessionOptions,\n });\n } else {\n this.connect();\n }\n }\n\n /** Closes for good (the runtime is being disposed). */\n close() {\n this.offAuthChange();\n this.closedByUser = true;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.ws?.close();\n this.ws = null;\n }\n\n /** Drops the socket after sign-out; the next sign-in reconnects. */\n private disconnect() {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.attempt = 0;\n this.sessionReady = false;\n if (this.ws) {\n this.ws.onclose = null; // No reconnect.\n this.ws.close();\n this.ws = null;\n }\n this.setStatus(\"idle\");\n }\n\n private flushQueue() {\n const pending = this.queue;\n this.queue = [];\n pending.forEach((action) => {\n // Queued messages were addressed before a session existed; point them at the current one.\n const addressed = \"session_id\" in action && this.sessionId ? { ...action, session_id: this.sessionId } : action;\n void this.sendRaw(addressed as AgentAction);\n });\n }\n\n private async sendRaw(action: AgentAction) {\n const agentToken = (await loadAgentAuth(this.agentUrl))?.agentToken;\n if (!agentToken || this.ws?.readyState !== WebSocket.OPEN) {\n if (this.debugEmbed) console.warn(\"[agent-embed][runtime] skipped outbound frame\", { action: action.action, hasAgentToken: !!agentToken, socketOpen: this.ws?.readyState === WebSocket.OPEN });\n if (action.action !== \"start_session\" && action.action !== \"resume_session\") this.queue.push(action);\n return;\n }\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] sending WebSocket action\", { action: action.action });\n this.ws.send(JSON.stringify({ ...action, agentToken }));\n if (action.action === \"message\") {\n this.unacknowledgedMessage = action;\n this.sentListeners.forEach((listener) => listener(action));\n }\n }\n\n private scheduleReconnect() {\n if (this.timer) return;\n const delay = BACKOFF_MS[Math.min(this.attempt, BACKOFF_MS.length - 1)];\n this.attempt += 1;\n this.setStatus(this.attempt > BACKOFF_MS.length ? \"offline\" : \"reconnecting\");\n if (this.checkProcessAvailability && this.attempt >= 2 && this.attempt % 3 === 2) {\n void this.checkAgentProcess(this.attempt);\n }\n this.timer = setTimeout(() => {\n this.timer = null;\n this.connect();\n }, delay);\n }\n\n private async checkAgentProcess(failedAttempt: number) {\n if (this.checkingProcessAvailability) return;\n this.checkingProcessAvailability = true;\n try {\n const auth = await loadAgentAuth(this.agentUrl);\n if (!auth || this.closedByUser || this.attempt !== failedAttempt) return;\n if (!(await isAgentProcessAvailable(auth)) && !this.closedByUser && this.attempt === failedAttempt) {\n // Repeated WebSocket failures plus a failed process health check mean the stored\n // endpoint is stale. Returning to sign-in lets the manager issue a fresh wsUrl.\n clearAgentAuth(this.agentUrl);\n }\n } finally {\n this.checkingProcessAvailability = false;\n }\n }\n\n private setStatus(status: AgentConnection) {\n if (this.debugEmbed) console.info(\"[agent-embed][runtime] connection status\", { status });\n this.statusListeners.forEach((listener) => listener(status));\n }\n\n private safeEndpoint(url = this.agentUrl) {\n try {\n const parsed = new URL(url);\n return `${parsed.origin}${parsed.pathname}`;\n } catch {\n return \"invalid-url\";\n }\n }\n}\n"]}
@@ -73,8 +73,8 @@ export class AgentSocket {
73
73
  const runtime = this.runtime;
74
74
  void this.sendRaw(
75
75
  this.sessionId
76
- ? { action: "resume_session", session_id: this.sessionId, provider, model, runtime, ...this.sessionOptions }
77
- : { action: "start_session", provider, model, runtime, ...this.sessionOptions }
76
+ ? { action: "resume_session", session_id: this.sessionId, provider, model, runtime, widget_catalog: this.widgetCatalog, ...this.sessionOptions }
77
+ : { action: "start_session", provider, model, runtime, widget_catalog: this.widgetCatalog, ...this.sessionOptions }
78
78
  );
79
79
  }
80
80
 
@@ -202,6 +202,7 @@ export class AgentSocket {
202
202
  provider,
203
203
  model,
204
204
  runtime: this.runtime,
205
+ widget_catalog: this.widgetCatalog,
205
206
  ...this.sessionOptions,
206
207
  });
207
208
  return;
@@ -273,6 +274,7 @@ export class AgentSocket {
273
274
  provider: this.provider ?? undefined,
274
275
  model: this.model ?? undefined,
275
276
  runtime: this.runtime,
277
+ widget_catalog: this.widgetCatalog,
276
278
  ...this.sessionOptions,
277
279
  };
278
280
  if (this.ws?.readyState === WebSocket.OPEN) void this.sendRaw(payload);
@@ -314,6 +316,7 @@ export class AgentSocket {
314
316
  provider: this.provider ?? undefined,
315
317
  model: this.model ?? undefined,
316
318
  runtime: this.runtime,
319
+ widget_catalog: this.widgetCatalog,
317
320
  ...this.sessionOptions,
318
321
  });
319
322
  } else {
@@ -72,7 +72,7 @@ export function AgentEmbeddingPanel(_a) {
72
72
  }
73
73
  var code = function (value, language) { return _jsx(SolidCodeEditor, { readOnly: true, value: value, language: language, fontSize: 11, height: "420px" }); };
74
74
  var copyButton = function (key, value) { return _jsxs(SolidButton, { variant: "secondary", size: "small", onClick: function () { return void copy(key, value); }, children: [copied === key ? _jsx(Check, { size: 14 }) : _jsx(Copy, { size: 14 }), " ", copied === key ? "Copied" : "Copy code"] }); };
75
- return _jsxs("div", { className: "agent-editor__stack", children: [!active && _jsx("p", { role: "status", className: "agent-editor__hint", children: "Activate this agent before embedding it. Samples use the saved agent definition." }), _jsxs("section", { className: "agent-editor__section", children: [_jsx("h2", { children: "1. Keep your API key on your server" }), _jsxs("p", { children: ["Configure ", _jsx("code", { children: "AGENTHUB_API_KEY" }), ", ", _jsx("code", { children: "AGENTHUB_AGENT_ID" }), ", and ", _jsx("code", { children: "AGENTHUB_BACKEND_URL" }), " on the server that hosts your app API. Never expose the API key or AgentHub runtime URL in browser code. The browser receives only the short-lived embed response through the SDK handshake."] })] }), _jsxs("section", { className: "agent-editor__section", children: [_jsx("h2", { children: "2. Create your token endpoint" }), _jsxs("p", { children: ["Your app API accepts the SDK's token request, ignores any client-selected backend or API key, and uses the configured agent ID to call ", _jsx("code", { children: "/api/agent/api-keys/embedded/me" }), " on AgentHub Runtime. Return the successful JSON response unchanged with ", _jsx("code", { children: "Cache-Control: no-store" }), "; never cache or log credentials or tokens."] }), _jsxs("p", { children: ["Anonymous embeds can expose this endpoint publicly, as in the demo. Add rate limiting at your API or gateway and use your app's authorization policy when chat access should require sign-in. ", _jsx("code", { children: "externalUserId" }), " is optional: when the trusted auth layer supplies a stable user ID, send a namespaced value; omit it for anonymous visitors. The runtime manages chat sessions independently."] }), _jsx(SolidTabGroup, { tabs: [
75
+ return _jsxs("div", { className: "agent-editor__stack", children: [!active && _jsx("p", { role: "status", className: "agent-editor__hint", children: "Activate this agent before embedding it. Samples use the saved agent definition." }), _jsxs("section", { className: "agent-editor__section", children: [_jsx("h2", { children: "1. Keep your API key on your server" }), _jsxs("p", { children: ["Configure ", _jsx("code", { children: "AGENT_HUB_API_KEY" }), ", ", _jsx("code", { children: "AGENT_HUB_AGENT_ID" }), ", and ", _jsx("code", { children: "AGENT_HUB_BACKEND_URL" }), " on the server that hosts your app API. Never expose the API key or AgentHub runtime URL in browser code. The browser receives only the short-lived embed response through the SDK handshake."] })] }), _jsxs("section", { className: "agent-editor__section", children: [_jsx("h2", { children: "2. Create your token endpoint" }), _jsxs("p", { children: ["Your app API accepts the SDK's token request, ignores any client-selected backend or API key, and uses the configured agent ID to call ", _jsx("code", { children: "/api/agent/api-keys/embedded/me" }), " on AgentHub Runtime. Return the successful JSON response unchanged with ", _jsx("code", { children: "Cache-Control: no-store" }), "; never cache or log credentials or tokens."] }), _jsxs("p", { children: ["Anonymous embeds can expose this endpoint publicly, as in the demo. Add rate limiting at your API or gateway and use your app's authorization policy when chat access should require sign-in. ", _jsx("code", { children: "externalUserId" }), " is optional: when the trusted auth layer supplies a stable user ID, send a namespaced value; omit it for anonymous visitors. The runtime manages chat sessions independently."] }), _jsx(SolidTabGroup, { tabs: [
76
76
  { value: "python", label: "Python / FastAPI", content: code(samples.python, "python") },
77
77
  { value: "nestjs", label: "NestJS", content: code(samples.nestjs, "typescript") },
78
78
  { value: "express", label: "Express", content: code(samples.express, "javascript") },
@@ -1 +1 @@
1
- {"version":3,"file":"AgentEmbeddingPanel.js","sourceRoot":"","sources":["../../../../../src/components/core/solid-agent/embed/AgentEmbeddingPanel.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAc,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACxC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAElF,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,MAAM,UAAU,mBAAmB,CAAC,EAAyH;QAAvH,OAAO,aAAA,EAAE,MAAM,YAAA,EAAE,MAAM,YAAA,EAAE,MAAM,YAAA;IAC3D,IAAA,KAAgB,QAAQ,CAAC,YAAY,CAAC,EAArC,GAAG,QAAA,EAAE,MAAM,QAA0B,CAAC;IACvC,IAAA,KAAwB,QAAQ,CAAC,SAAS,CAAC,EAA1C,OAAO,QAAA,EAAE,UAAU,QAAuB,CAAC;IAC5C,IAAA,KAAsB,QAAQ,CAAC,EAAE,CAAC,EAAjC,MAAM,QAAA,EAAE,SAAS,QAAgB,CAAC;IACnC,IAAA,KAA4B,QAAQ,CAAC,EAAE,CAAC,EAAvC,SAAS,QAAA,EAAE,YAAY,QAAgB,CAAC;IAC/C,IAAM,MAAM,GAAG,UAAG,GAAG,CAAC,6BAA6B,CAAC,CAAC,OAAO,CAAC,KAAK,EAA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CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,YAAY,CAAC,GAAM,EAAA,uBAAK,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,GAAM,KAAzR,KAAK,CAAC,IAAI,CAAoR,EAAvS,CAAuS,CAAC,GAAS,IAAQ;wBACvV,CAAC,CAAC,oDAAgC,EACtC,uVAAmU,IAC7T,EACV,mBAAS,SAAS,EAAC,uBAAuB,aAAC,kDAA+B,EAAA,iCAAQ,4CAAoB,OAAO,IAAQ,8CAAwC,gDAA+B,kRAA8Q,IAAU,EACnd,SAAS,IAAI,YAAG,IAAI,EAAC,OAAO,YAAE,SAAS,GAAK,IAC3C,CAAC;AACX,CAAC","sourcesContent":["import React, { useState } from \"react\";\nimport { Copy, Check } from \"lucide-react\";\nimport { env } from \"../../../../adapters/env\";\nimport { SolidButton, SolidCodeEditor, SolidTabGroup } from \"../../../shad-cn-ui\";\nimport type { AgentInputDefinition } from \"./agentEmbedProtocol\";\nimport { embedSamples } from \"./agentEmbedSamples\";\n\nexport function AgentEmbeddingPanel({ agentId, fields, hubUrl, active }: { agentId: number; fields: AgentInputDefinition[]; hubUrl: string; active: boolean }) {\n const [tab, setTab] = useState(\"javascript\");\n const [backend, setBackend] = useState(\"express\");\n const [copied, setCopied] = useState(\"\");\n const [copyError, setCopyError] = useState(\"\");\n const sdkUrl = `${env(\"NEXT_PUBLIC_BACKEND_API_URL\").replace(/\\/$/, \"\")}/api/agent-embed/sdk.js?v=4`;\n const samples = embedSamples(agentId, fields, sdkUrl, hubUrl || \"https://agenthub.example.com\");\n async function copy(key: string, code: string) {\n try { await navigator.clipboard.writeText(code); setCopied(key); setCopyError(\"\"); }\n catch { setCopyError(\"Clipboard access is unavailable. Select and copy the code below.\"); }\n }\n const code = (value: string, language: string) => <SolidCodeEditor readOnly value={value} language={language} fontSize={11} height=\"420px\" />;\n const copyButton = (key: string, value: string) => <SolidButton variant=\"secondary\" size=\"small\" onClick={() => void copy(key, value)}>\n {copied === key ? <Check size={14} /> : <Copy size={14} />} {copied === key ? \"Copied\" : \"Copy code\"}\n </SolidButton>;\n return <div className=\"agent-editor__stack\">\n {!active && <p role=\"status\" className=\"agent-editor__hint\">Activate this agent before embedding it. Samples use the saved agent definition.</p>}\n <section className=\"agent-editor__section\"><h2>1. Keep your API key on your server</h2>\n <p>Configure <code>AGENTHUB_API_KEY</code>, <code>AGENTHUB_AGENT_ID</code>, and <code>AGENTHUB_BACKEND_URL</code> on the server that hosts your app API. Never expose the API key or AgentHub runtime URL in browser code. The browser receives only the short-lived embed response through the SDK handshake.</p>\n </section>\n <section className=\"agent-editor__section\"><h2>2. Create your token endpoint</h2>\n <p>Your app API accepts the SDK's token request, ignores any client-selected backend or API key, and uses the configured agent ID to call <code>/api/agent/api-keys/embedded/me</code> on AgentHub Runtime. Return the successful JSON response unchanged with <code>Cache-Control: no-store</code>; never cache or log credentials or tokens.</p>\n <p>Anonymous embeds can expose this endpoint publicly, as in the demo. Add rate limiting at your API or gateway and use your app's authorization policy when chat access should require sign-in. <code>externalUserId</code> is optional: when the trusted auth layer supplies a stable user ID, send a namespaced value; omit it for anonymous visitors. The runtime manages chat sessions independently.</p>\n <SolidTabGroup tabs={[\n { value: \"python\", label: \"Python / FastAPI\", content: code(samples.python, \"python\") },\n { value: \"nestjs\", label: \"NestJS\", content: code(samples.nestjs, \"typescript\") },\n { value: \"express\", label: \"Express\", content: code(samples.express, \"javascript\") },\n { value: \"java\", label: \"Java / Spring Boot\", content: code(samples.java, \"java\") },\n { value: \"dotnet\", label: \".NET / ASP.NET Core\", content: code(samples.dotnet, \"csharp\") },\n ]} value={backend} onValueChange={setBackend} extra={copyButton(backend, samples[backend as keyof typeof samples])} />\n </section>\n <section className=\"agent-editor__section\"><h2>3. Embed the chat</h2>\n <p>Load the SDK from the public SDK URL shown below and mount it into a browser container. The SDK calls your app's <code>tokenEndpoint</code>, passes the response to the hosted chat in memory, and manages the iframe handshake and token renewal. No SolidX npm dependency is required.</p>\n <p><code>mode: \"popup\"</code> is the default and provides a floating launcher. <code>mode: \"inline\"</code> fills your container; your app controls its size and layout. Keep the instance mounted across client-side navigation to preserve the live chat.</p>\n <p>Use a same-origin path such as <code>/api/agent-chat/token</code> when possible. If your app API has another origin, give <code>tokenEndpoint</code> its absolute URL and configure that API's CORS policy for the browser app origin.</p>\n <p>The SDK-serving SolidX API selects the hosted chat UI from its server-side <code>AGENT_EMBED_UI_URL</code> setting. The consuming app does not supply an <code>embedUrl</code> or choose the iframe host. Keep the SDK script URL and the configured hosted UI origin aligned to the same SolidX deployment.</p>\n <p>Pass the current page's required input values in <code>inputs</code> using the names and types in this agent's schema. These values provide task context; they are not authorization to access records. Enforce access to protected data in your own API/tools. For a logged-in app, use <code>getTokenHeaders</code> to send the app's normal bearer or CSRF header to your app API; do not send the AgentHub API key from the browser.</p>\n <SolidTabGroup tabs={[\n { value: \"javascript\", label: \"JavaScript\", content: code(samples.javascript, \"html\") },\n { value: \"inline\", label: \"Inline\", content: code(samples.inline, \"html\") },\n { value: \"react\", label: \"React\", content: code(samples.react, \"javascript\") },\n ]} value={tab} onValueChange={setTab} extra={copyButton(tab, samples[tab as \"javascript\" | \"inline\" | \"react\"])} />\n </section>\n <section className=\"agent-editor__section\"><h2>Inputs</h2>\n {fields.length ? <table style={{ width: \"100%\", textAlign: \"left\" }}><thead><tr><th>Variable</th><th>Data type</th><th>Description</th><th>Default value</th><th>Optional</th></tr></thead>\n <tbody>{fields.map((field) => <tr key={field.name}><td><code>{field.name}</code></td><td>{field.dataType}</td><td>{field.description}</td><td>{field.defaultValue == null ? \"—\" : typeof field.defaultValue === \"string\" ? field.defaultValue : JSON.stringify(field.defaultValue)}</td><td>{field.optional ? \"Yes\" : \"No\"}</td></tr>)}</tbody></table>\n : <p>This agent has no inputs.</p>}\n <p>Replace sample values with the current page's values and preserve each declared type. Default values are used when an input is omitted; optional inputs may be omitted without a default. Inputs are fixed after the first message; start a new chat to change them. They describe the task and do not grant access to data.</p>\n </section>\n <section className=\"agent-editor__section\"><h2>Hosting and deployment</h2><p>Make <code>/embed/agent/{agentId}</code> available on the hosted UI selected by <code>AGENT_EMBED_UI_URL</code>. Allow the consuming app origin in the hosted UI's frame-ancestors policy, the AgentHub Runtime origin in its CORS configuration, and the SDK/API/iframe origins in the consuming app's CSP. Use HTTPS for the consuming page, SDK, hosted UI, and runtime in production.</p></section>\n {copyError && <p role=\"alert\">{copyError}</p>}\n </div>;\n}\n"]}
1
+ {"version":3,"file":"AgentEmbeddingPanel.js","sourceRoot":"","sources":["../../../../../src/components/core/solid-agent/embed/AgentEmbeddingPanel.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAc,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACxC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAElF,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,MAAM,UAAU,mBAAmB,CAAC,EAAyH;QAAvH,OAAO,aAAA,EAAE,MAAM,YAAA,EAAE,MAAM,YAAA,EAAE,MAAM,YAAA;IAC3D,IAAA,KAAgB,QAAQ,CAAC,YAAY,CAAC,EAArC,GAAG,QAAA,EAAE,MAAM,QAA0B,CAAC;IACvC,IAAA,KAAwB,QAAQ,CAAC,SAAS,CAAC,EAA1C,OAAO,QAAA,EAAE,UAAU,QAAuB,CAAC;IAC5C,IAAA,KAAsB,QAAQ,CAAC,EAAE,CAAC,EAAjC,MAAM,QAAA,EAAE,SAAS,QAAgB,CAAC;IACnC,IAAA,KAA4B,QAAQ,CAAC,EAAE,CAAC,EAAvC,SAAS,QAAA,EA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AAY,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC,YAAY,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,YAAY,CAAC,GAAM,EAAA,uBAAK,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,GAAM,KAAzR,KAAK,CAAC,IAAI,CAAoR,EAAvS,CAAuS,CAAC,GAAS,IAAQ;wBACvV,CAAC,CAAC,oDAAgC,EACtC,uVAAmU,IAC7T,EACV,mBAAS,SAAS,EAAC,uBAAuB,aAAC,kDAA+B,EAAA,iCAAQ,4CAAoB,OAAO,IAAQ,8CAAwC,gDAA+B,kRAA8Q,IAAU,EACnd,SAAS,IAAI,YAAG,IAAI,EAAC,OAAO,YAAE,SAAS,GAAK,IAC3C,CAAC;AACX,CAAC","sourcesContent":["import React, { useState } from \"react\";\nimport { Copy, Check } from \"lucide-react\";\nimport { env } from \"../../../../adapters/env\";\nimport { SolidButton, SolidCodeEditor, SolidTabGroup } from \"../../../shad-cn-ui\";\nimport type { AgentInputDefinition } from \"./agentEmbedProtocol\";\nimport { embedSamples } from \"./agentEmbedSamples\";\n\nexport function AgentEmbeddingPanel({ agentId, fields, hubUrl, active }: { agentId: number; fields: AgentInputDefinition[]; hubUrl: string; active: boolean }) {\n const [tab, setTab] = useState(\"javascript\");\n const [backend, setBackend] = useState(\"express\");\n const [copied, setCopied] = useState(\"\");\n const [copyError, setCopyError] = useState(\"\");\n const sdkUrl = `${env(\"NEXT_PUBLIC_BACKEND_API_URL\").replace(/\\/$/, \"\")}/api/agent-embed/sdk.js?v=4`;\n const samples = embedSamples(agentId, fields, sdkUrl, hubUrl || \"https://agenthub.example.com\");\n async function copy(key: string, code: string) {\n try { await navigator.clipboard.writeText(code); setCopied(key); setCopyError(\"\"); }\n catch { setCopyError(\"Clipboard access is unavailable. Select and copy the code below.\"); }\n }\n const code = (value: string, language: string) => <SolidCodeEditor readOnly value={value} language={language} fontSize={11} height=\"420px\" />;\n const copyButton = (key: string, value: string) => <SolidButton variant=\"secondary\" size=\"small\" onClick={() => void copy(key, value)}>\n {copied === key ? <Check size={14} /> : <Copy size={14} />} {copied === key ? \"Copied\" : \"Copy code\"}\n </SolidButton>;\n return <div className=\"agent-editor__stack\">\n {!active && <p role=\"status\" className=\"agent-editor__hint\">Activate this agent before embedding it. Samples use the saved agent definition.</p>}\n <section className=\"agent-editor__section\"><h2>1. Keep your API key on your server</h2>\n <p>Configure <code>AGENT_HUB_API_KEY</code>, <code>AGENT_HUB_AGENT_ID</code>, and <code>AGENT_HUB_BACKEND_URL</code> on the server that hosts your app API. Never expose the API key or AgentHub runtime URL in browser code. The browser receives only the short-lived embed response through the SDK handshake.</p>\n </section>\n <section className=\"agent-editor__section\"><h2>2. Create your token endpoint</h2>\n <p>Your app API accepts the SDK's token request, ignores any client-selected backend or API key, and uses the configured agent ID to call <code>/api/agent/api-keys/embedded/me</code> on AgentHub Runtime. Return the successful JSON response unchanged with <code>Cache-Control: no-store</code>; never cache or log credentials or tokens.</p>\n <p>Anonymous embeds can expose this endpoint publicly, as in the demo. Add rate limiting at your API or gateway and use your app's authorization policy when chat access should require sign-in. <code>externalUserId</code> is optional: when the trusted auth layer supplies a stable user ID, send a namespaced value; omit it for anonymous visitors. The runtime manages chat sessions independently.</p>\n <SolidTabGroup tabs={[\n { value: \"python\", label: \"Python / FastAPI\", content: code(samples.python, \"python\") },\n { value: \"nestjs\", label: \"NestJS\", content: code(samples.nestjs, \"typescript\") },\n { value: \"express\", label: \"Express\", content: code(samples.express, \"javascript\") },\n { value: \"java\", label: \"Java / Spring Boot\", content: code(samples.java, \"java\") },\n { value: \"dotnet\", label: \".NET / ASP.NET Core\", content: code(samples.dotnet, \"csharp\") },\n ]} value={backend} onValueChange={setBackend} extra={copyButton(backend, samples[backend as keyof typeof samples])} />\n </section>\n <section className=\"agent-editor__section\"><h2>3. Embed the chat</h2>\n <p>Load the SDK from the public SDK URL shown below and mount it into a browser container. The SDK calls your app's <code>tokenEndpoint</code>, passes the response to the hosted chat in memory, and manages the iframe handshake and token renewal. No SolidX npm dependency is required.</p>\n <p><code>mode: \"popup\"</code> is the default and provides a floating launcher. <code>mode: \"inline\"</code> fills your container; your app controls its size and layout. Keep the instance mounted across client-side navigation to preserve the live chat.</p>\n <p>Use a same-origin path such as <code>/api/agent-chat/token</code> when possible. If your app API has another origin, give <code>tokenEndpoint</code> its absolute URL and configure that API's CORS policy for the browser app origin.</p>\n <p>The SDK-serving SolidX API selects the hosted chat UI from its server-side <code>AGENT_EMBED_UI_URL</code> setting. The consuming app does not supply an <code>embedUrl</code> or choose the iframe host. Keep the SDK script URL and the configured hosted UI origin aligned to the same SolidX deployment.</p>\n <p>Pass the current page's required input values in <code>inputs</code> using the names and types in this agent's schema. These values provide task context; they are not authorization to access records. Enforce access to protected data in your own API/tools. For a logged-in app, use <code>getTokenHeaders</code> to send the app's normal bearer or CSRF header to your app API; do not send the AgentHub API key from the browser.</p>\n <SolidTabGroup tabs={[\n { value: \"javascript\", label: \"JavaScript\", content: code(samples.javascript, \"html\") },\n { value: \"inline\", label: \"Inline\", content: code(samples.inline, \"html\") },\n { value: \"react\", label: \"React\", content: code(samples.react, \"javascript\") },\n ]} value={tab} onValueChange={setTab} extra={copyButton(tab, samples[tab as \"javascript\" | \"inline\" | \"react\"])} />\n </section>\n <section className=\"agent-editor__section\"><h2>Inputs</h2>\n {fields.length ? <table style={{ width: \"100%\", textAlign: \"left\" }}><thead><tr><th>Variable</th><th>Data type</th><th>Description</th><th>Default value</th><th>Optional</th></tr></thead>\n <tbody>{fields.map((field) => <tr key={field.name}><td><code>{field.name}</code></td><td>{field.dataType}</td><td>{field.description}</td><td>{field.defaultValue == null ? \"—\" : typeof field.defaultValue === \"string\" ? field.defaultValue : JSON.stringify(field.defaultValue)}</td><td>{field.optional ? \"Yes\" : \"No\"}</td></tr>)}</tbody></table>\n : <p>This agent has no inputs.</p>}\n <p>Replace sample values with the current page's values and preserve each declared type. Default values are used when an input is omitted; optional inputs may be omitted without a default. Inputs are fixed after the first message; start a new chat to change them. They describe the task and do not grant access to data.</p>\n </section>\n <section className=\"agent-editor__section\"><h2>Hosting and deployment</h2><p>Make <code>/embed/agent/{agentId}</code> available on the hosted UI selected by <code>AGENT_EMBED_UI_URL</code>. Allow the consuming app origin in the hosted UI's frame-ancestors policy, the AgentHub Runtime origin in its CORS configuration, and the SDK/API/iframe origins in the consuming app's CSP. Use HTTPS for the consuming page, SDK, hosted UI, and runtime in production.</p></section>\n {copyError && <p role=\"alert\">{copyError}</p>}\n </div>;\n}\n"]}
@@ -23,7 +23,7 @@ export function AgentEmbeddingPanel({ agentId, fields, hubUrl, active }: { agent
23
23
  return <div className="agent-editor__stack">
24
24
  {!active && <p role="status" className="agent-editor__hint">Activate this agent before embedding it. Samples use the saved agent definition.</p>}
25
25
  <section className="agent-editor__section"><h2>1. Keep your API key on your server</h2>
26
- <p>Configure <code>AGENTHUB_API_KEY</code>, <code>AGENTHUB_AGENT_ID</code>, and <code>AGENTHUB_BACKEND_URL</code> on the server that hosts your app API. Never expose the API key or AgentHub runtime URL in browser code. The browser receives only the short-lived embed response through the SDK handshake.</p>
26
+ <p>Configure <code>AGENT_HUB_API_KEY</code>, <code>AGENT_HUB_AGENT_ID</code>, and <code>AGENT_HUB_BACKEND_URL</code> on the server that hosts your app API. Never expose the API key or AgentHub runtime URL in browser code. The browser receives only the short-lived embed response through the SDK handshake.</p>
27
27
  </section>
28
28
  <section className="agent-editor__section"><h2>2. Create your token endpoint</h2>
29
29
  <p>Your app API accepts the SDK's token request, ignores any client-selected backend or API key, and uses the configured agent ID to call <code>/api/agent/api-keys/embedded/me</code> on AgentHub Runtime. Return the successful JSON response unchanged with <code>Cache-Control: no-store</code>; never cache or log credentials or tokens.</p>
@@ -1 +1 @@
1
- {"version":3,"file":"agentEmbedProt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;IAClC,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE;gBAApB,UAAU,EAAE,MAAM,EAAE;CAI5C;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,mBAAmB,CA8B1E;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,mBAAmB,CAWtF;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,oBAAoB,EAAE,EAAE,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CA6BlH"}
@@ -111,6 +111,8 @@ export function validateEmbedInputs(fields, suppliedValues) {
111
111
  for (var _b = 0, fields_1 = fields; _b < fields_1.length; _b++) {
112
112
  var field = fields_1[_b];
113
113
  var value = values[field.name];
114
+ if (field.optional && (value === undefined || value === null || (typeof value === "string" && !value.trim())))
115
+ continue;
114
116
  var valid = false;
115
117
  switch (field.dataType) {
116
118
  case "string":
@@ -1 +1 @@
1
- {"version":3,"file":"agentEmbedProtocol.js","sourceRoot":"","sources":["../../../../../src/components/core/solid-agent/embed/agentEmbedProtocol.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,MAAM,CAAC,IAAM,aAAa,GAAG,oBAAoB,CAAC;AAClD,MAAM,CAAC,IAAM,6BAA6B,GAAG,CAAC,CAAC;AAC/C,MAAM,CAAC,IAAM,+BAA+B,GAAG,EAAE,GAAG,IAAI,CAAC;AAsBzD;IAA6C,2CAAK;IAC9C,iCAAqB,UAAoB;QAAzC,YACI,kBAAM,uCAAgC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAE,CAAC,SAEjE;QAHW;;;;mBAAS,UAAU;WAAU;QAErC,KAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;;IAC1C,CAAC;IACL,8BAAC;AAAD,CAAC,AALD,CAA6C,KAAK,GAKjD;;AAED,MAAM,UAAU,sBAAsB,CAAC,KAAc;IACjD,IAAI,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I,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,gBAAS,KAAK,CAAC,IAAI,kCAAwB,KAAK,CAAC,QAAQ,MAAG,CAAC,CAAC;KAC7F;AACL,CAAC","sourcesContent":["import type { AgentBootstrap } from \"../client/agentAuth\";\n\nexport const EMBED_CHANNEL = \"solidx-agent-embed\";\nexport const EMBED_PUBLIC_PROTOCOL_VERSION = 2;\nexport const EMBED_MESSAGE_CONTEXT_MAX_BYTES = 32 * 1024;\nexport type EmbedJson = null | boolean | number | string | EmbedJson[] | { [key: string]: EmbedJson };\nexport type EmbedContextContribution = { context: EmbedJson; revision: string; displaySummary?: string };\nexport type EmbedMessageContext = { schemaVersion: 1; namespaces: Record<string, EmbedContextContribution> };\nexport type BeforeUserMessageSendRequest = {\n text: string;\n source: \"composer\" | \"sdk\" | \"prefill\" | \"widget\";\n attachments: Array<{ name: string; mimeType: string; size: number }>;\n contextRevision?: string;\n};\nexport type BeforeUserMessageSendListener = (\n request: BeforeUserMessageSendRequest,\n signal: AbortSignal,\n) => Promise<EmbedContextContribution | { cancelled: true; reason?: string }>;\nexport type AgentInputDefinition = { name: string; description: string; dataType: string; defaultValue?: unknown; optional?: boolean };\nexport type AgentEmbedBootstrap = AgentBootstrap & {\n embed: true;\n agentId: number;\n title?: string;\n requiredInputs: AgentInputDefinition[];\n};\n\nexport class MissingAgentInputsError extends Error {\n constructor(readonly inputNames: string[]) {\n super(`Required inputs are missing: ${inputNames.join(\", \")}`);\n this.name = \"MissingAgentInputsError\";\n }\n}\n\nexport function validateMessageContext(value: unknown): EmbedMessageContext {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"message_context must be an object.\");\n const context = value as Partial<EmbedMessageContext>;\n if (context.schemaVersion !== 1 || !context.namespaces || typeof context.namespaces !== \"object\"\n || Array.isArray(context.namespaces) || Object.keys(context.namespaces).length > 32)\n throw new Error(\"message_context must use schemaVersion 1 and contain a namespaces object.\");\n for (const [namespace, contribution] of Object.entries(context.namespaces)) {\n if (!namespace || namespace.length > 80 || !contribution || typeof contribution !== \"object\"\n || typeof contribution.revision !== \"string\" || contribution.revision.length > 256 || !(\"context\" in contribution)\n || (contribution.displaySummary !== undefined && (typeof contribution.displaySummary !== \"string\" || contribution.displaySummary.length > 1024)))\n throw new Error(\"message_context contains an invalid namespace contribution.\");\n }\n const isJson = (item: unknown, depth = 0): boolean => {\n if (depth > 12) return false;\n if (item === null || typeof item === \"string\" || typeof item === \"boolean\") return true;\n if (typeof item === \"number\") return Number.isFinite(item);\n if (Array.isArray(item)) return item.length <= 1024 && item.every((child) => isJson(child, depth + 1));\n if (typeof item !== \"object\" || Object.getPrototypeOf(item) !== Object.prototype) return false;\n return Object.values(item as Record<string, unknown>).every((child) => isJson(child, depth + 1));\n };\n let serialized: string;\n try {\n if (!isJson(value)) throw new Error(\"message_context contains unsupported JSON values.\");\n serialized = JSON.stringify(value);\n } catch {\n throw new Error(\"message_context contains unsupported JSON values.\");\n }\n if (new TextEncoder().encode(serialized).length > EMBED_MESSAGE_CONTEXT_MAX_BYTES)\n throw new Error(\"message_context exceeds 32 KiB.\");\n return value as EmbedMessageContext;\n}\n\nexport function validateBootstrap(value: unknown, agentId: number): AgentEmbedBootstrap {\n const body = value as AgentEmbedBootstrap;\n if (!body || body.embed !== true || body.agentId !== agentId || typeof body.agentToken !== \"string\" || !body.agentToken\n || !Array.isArray(body.requiredInputs)) throw new Error(\"The token endpoint returned an invalid embed response.\");\n const ws = new URL(body.wsUrl), http = new URL(body.httpUrl);\n if (![\"ws:\", \"wss:\"].includes(ws.protocol) || ![\"http:\", \"https:\"].includes(http.protocol)\n || ws.username || ws.password || http.username || http.password || ws.search || http.search || ws.hash || http.hash)\n throw new Error(\"The token endpoint returned invalid connection URLs.\");\n if (window.location.protocol === \"https:\" && (ws.protocol !== \"wss:\" || http.protocol !== \"https:\"))\n throw new Error(\"HTTPS embeds require HTTPS and WSS AgentHub endpoints.\");\n return body;\n}\n\nexport function validateEmbedInputs(fields: AgentInputDefinition[], suppliedValues?: Record<string, unknown>): void {\n const values = suppliedValues ?? {};\n if (typeof values !== \"object\" || Array.isArray(values)) throw new Error(\"inputs must be an object.\");\n const names = new Set(fields.map((field) => field.name));\n for (const name of Object.keys(values)) if (!names.has(name)) throw new Error(`Unknown input: ${name}`);\n const missing = fields\n .filter(({ name, optional }) => {\n const value = values[name];\n return !optional && (value === undefined || value === null || (typeof value === \"string\" && !value.trim()));\n })\n .map(({ name }) => name);\n if (missing.length) throw new MissingAgentInputsError(missing);\n for (const field of fields) {\n const value = values[field.name];\n let valid = false;\n switch (field.dataType) {\n case \"string\": valid = typeof value === \"string\"; break;\n case \"number\": valid = typeof value === \"number\" && Number.isFinite(value); break;\n case \"integer\": valid = typeof value === \"number\" && Number.isSafeInteger(value); break;\n case \"boolean\": valid = typeof value === \"boolean\"; break;\n case \"array\": valid = Array.isArray(value); break;\n case \"object\": valid = typeof value === \"object\" && value !== null && !Array.isArray(value); break;\n case \"date\": valid = typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}$/.test(value)\n && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value; break;\n case \"datetime\": valid = typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !Number.isNaN(Date.parse(value)); break;\n }\n if (!valid) throw new Error(`Input ${field.name} must have data type ${field.dataType}.`);\n }\n}\n"]}
1
+ {"version":3,"file":"agentEmbedProtocol.js","sourceRoot":"","sources":["../../../../../src/components/core/solid-agent/embed/agentEmbedProtocol.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,MAAM,CAAC,IAAM,aAAa,GAAG,oBAAoB,CAAC;AAClD,MAAM,CAAC,IAAM,6BAA6B,GAAG,CAAC,CAAC;AAC/C,MAAM,CAAC,IAAM,+BAA+B,GAAG,EAAE,GAAG,IAAI,CAAC;AAsBzD;IAA6C,2CAAK;IAC9C,iCAAqB,UAAoB;QAAzC,YACI,kBAAM,uCAAgC,UAAU,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,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,CAAC;gBAAC,MAAM;YACvG,KAAK,UAAU;gBAAE,KAAK,GAAG,OAAO,KAAK,KAAK,QAAQ,IAAI,qBAAqB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;gBAAC,MAAM;SACtI;QACD,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,gBAAS,KAAK,CAAC,IAAI,kCAAwB,KAAK,CAAC,QAAQ,MAAG,CAAC,CAAC;KAC7F;AACL,CAAC","sourcesContent":["import type { AgentBootstrap } from \"../client/agentAuth\";\n\nexport const EMBED_CHANNEL = \"solidx-agent-embed\";\nexport const EMBED_PUBLIC_PROTOCOL_VERSION = 2;\nexport const EMBED_MESSAGE_CONTEXT_MAX_BYTES = 32 * 1024;\nexport type EmbedJson = null | boolean | number | string | EmbedJson[] | { [key: string]: EmbedJson };\nexport type EmbedContextContribution = { context: EmbedJson; revision: string; displaySummary?: string };\nexport type EmbedMessageContext = { schemaVersion: 1; namespaces: Record<string, EmbedContextContribution> };\nexport type BeforeUserMessageSendRequest = {\n text: string;\n source: \"composer\" | \"sdk\" | \"prefill\" | \"widget\";\n attachments: Array<{ name: string; mimeType: string; size: number }>;\n contextRevision?: string;\n};\nexport type BeforeUserMessageSendListener = (\n request: BeforeUserMessageSendRequest,\n signal: AbortSignal,\n) => Promise<EmbedContextContribution | { cancelled: true; reason?: string }>;\nexport type AgentInputDefinition = { name: string; description: string; dataType: string; defaultValue?: unknown; optional?: boolean };\nexport type AgentEmbedBootstrap = AgentBootstrap & {\n embed: true;\n agentId: number;\n title?: string;\n requiredInputs: AgentInputDefinition[];\n};\n\nexport class MissingAgentInputsError extends Error {\n constructor(readonly inputNames: string[]) {\n super(`Required inputs are missing: ${inputNames.join(\", \")}`);\n this.name = \"MissingAgentInputsError\";\n }\n}\n\nexport function validateMessageContext(value: unknown): EmbedMessageContext {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"message_context must be an object.\");\n const context = value as Partial<EmbedMessageContext>;\n if (context.schemaVersion !== 1 || !context.namespaces || typeof context.namespaces !== \"object\"\n || Array.isArray(context.namespaces) || Object.keys(context.namespaces).length > 32)\n throw new Error(\"message_context must use schemaVersion 1 and contain a namespaces object.\");\n for (const [namespace, contribution] of Object.entries(context.namespaces)) {\n if (!namespace || namespace.length > 80 || !contribution || typeof contribution !== \"object\"\n || typeof contribution.revision !== \"string\" || contribution.revision.length > 256 || !(\"context\" in contribution)\n || (contribution.displaySummary !== undefined && (typeof contribution.displaySummary !== \"string\" || contribution.displaySummary.length > 1024)))\n throw new Error(\"message_context contains an invalid namespace contribution.\");\n }\n const isJson = (item: unknown, depth = 0): boolean => {\n if (depth > 12) return false;\n if (item === null || typeof item === \"string\" || typeof item === \"boolean\") return true;\n if (typeof item === \"number\") return Number.isFinite(item);\n if (Array.isArray(item)) return item.length <= 1024 && item.every((child) => isJson(child, depth + 1));\n if (typeof item !== \"object\" || Object.getPrototypeOf(item) !== Object.prototype) return false;\n return Object.values(item as Record<string, unknown>).every((child) => isJson(child, depth + 1));\n };\n let serialized: string;\n try {\n if (!isJson(value)) throw new Error(\"message_context contains unsupported JSON values.\");\n serialized = JSON.stringify(value);\n } catch {\n throw new Error(\"message_context contains unsupported JSON values.\");\n }\n if (new TextEncoder().encode(serialized).length > EMBED_MESSAGE_CONTEXT_MAX_BYTES)\n throw new Error(\"message_context exceeds 32 KiB.\");\n return value as EmbedMessageContext;\n}\n\nexport function validateBootstrap(value: unknown, agentId: number): AgentEmbedBootstrap {\n const body = value as AgentEmbedBootstrap;\n if (!body || body.embed !== true || body.agentId !== agentId || typeof body.agentToken !== \"string\" || !body.agentToken\n || !Array.isArray(body.requiredInputs)) throw new Error(\"The token endpoint returned an invalid embed response.\");\n const ws = new URL(body.wsUrl), http = new URL(body.httpUrl);\n if (![\"ws:\", \"wss:\"].includes(ws.protocol) || ![\"http:\", \"https:\"].includes(http.protocol)\n || ws.username || ws.password || http.username || http.password || ws.search || http.search || ws.hash || http.hash)\n throw new Error(\"The token endpoint returned invalid connection URLs.\");\n if (window.location.protocol === \"https:\" && (ws.protocol !== \"wss:\" || http.protocol !== \"https:\"))\n throw new Error(\"HTTPS embeds require HTTPS and WSS AgentHub endpoints.\");\n return body;\n}\n\nexport function validateEmbedInputs(fields: AgentInputDefinition[], suppliedValues?: Record<string, unknown>): void {\n const values = suppliedValues ?? {};\n if (typeof values !== \"object\" || Array.isArray(values)) throw new Error(\"inputs must be an object.\");\n const names = new Set(fields.map((field) => field.name));\n for (const name of Object.keys(values)) if (!names.has(name)) throw new Error(`Unknown input: ${name}`);\n const missing = fields\n .filter(({ name, optional }) => {\n const value = values[name];\n return !optional && (value === undefined || value === null || (typeof value === \"string\" && !value.trim()));\n })\n .map(({ name }) => name);\n if (missing.length) throw new MissingAgentInputsError(missing);\n for (const field of fields) {\n const value = values[field.name];\n if (field.optional && (value === undefined || value === null || (typeof value === \"string\" && !value.trim()))) continue;\n let valid = false;\n switch (field.dataType) {\n case \"string\": valid = typeof value === \"string\"; break;\n case \"number\": valid = typeof value === \"number\" && Number.isFinite(value); break;\n case \"integer\": valid = typeof value === \"number\" && Number.isSafeInteger(value); break;\n case \"boolean\": valid = typeof value === \"boolean\"; break;\n case \"array\": valid = Array.isArray(value); break;\n case \"object\": valid = typeof value === \"object\" && value !== null && !Array.isArray(value); break;\n case \"date\": valid = typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}$/.test(value)\n && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value; break;\n case \"datetime\": valid = typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}T/.test(value) && !Number.isNaN(Date.parse(value)); break;\n }\n if (!valid) throw new Error(`Input ${field.name} must have data type ${field.dataType}.`);\n }\n}\n"]}
@@ -90,6 +90,7 @@ export function validateEmbedInputs(fields: AgentInputDefinition[], suppliedValu
90
90
  if (missing.length) throw new MissingAgentInputsError(missing);
91
91
  for (const field of fields) {
92
92
  const value = values[field.name];
93
+ if (field.optional && (value === undefined || value === null || (typeof value === "string" && !value.trim()))) continue;
93
94
  let valid = false;
94
95
  switch (field.dataType) {
95
96
  case "string": valid = typeof value === "string"; break;
@@ -5,18 +5,18 @@ export function embedSamples(agentId, fields, sdkUrl, hubBase) {
5
5
  var values = Object.fromEntries(fields.map(function (field) { var _a; return [field.name, (_a = examples[field.dataType]) !== null && _a !== void 0 ? _a : "Replace with your value"]; }));
6
6
  var valuesJson = js(values).replace(/\n/g, "\n ");
7
7
  var backendUrl = hubBase.replace(/\/$/, "");
8
- var environmentNote = "# AGENTHUB_BACKEND_URL=".concat(backendUrl);
9
- var environmentNoteSlash = "// AGENTHUB_BACKEND_URL=".concat(backendUrl);
8
+ var environmentNote = "# AGENT_HUB_BACKEND_URL=".concat(backendUrl);
9
+ var environmentNoteSlash = "// AGENT_HUB_BACKEND_URL=".concat(backendUrl);
10
10
  var config = "agentId: ".concat(agentId, ",\n tokenEndpoint: \"/api/agent-chat/token\",\n inputs: ").concat(valuesJson);
11
11
  return {
12
12
  javascript: "<div id=\"agent-chat\"></div>\n<script src=".concat(JSON.stringify(sdkUrl).replace(/</g, "&lt;"), "></script>\n<script>\n // Values should come from the current page or trusted app state.\n // The API key and AgentHub URL stay on your server.\n const chat = SolidAgentEmbed.mount({\n container: \"#agent-chat\",\n ").concat(config, "\n });\n // For app auth/CSRF, add getTokenHeaders: () => yourAppAuthHeaders().\n // Optional lifecycle methods: chat.open(), chat.close(), chat.destroy().\n // Update context before the first message or after starting a new chat:\n // await chat.setInputs({ ... });\n</script>"),
13
13
  inline: "<div id=\"agent-chat\" style=\"width:420px;height:600px\"></div>\n<script src=".concat(JSON.stringify(sdkUrl).replace(/</g, "&lt;"), "></script>\n<script>\n // Your app owns this container's size, position, and visibility.\n // Keep the same instance mounted when navigating within your app.\n const chat = SolidAgentEmbed.mount({\n mode: \"inline\",\n container: \"#agent-chat\",\n ").concat(config, "\n });\n chat.open();\n // chat.close() hides the iframe without ending the chat.\n // chat.destroy() removes the iframe when the user signs out.\n</script>"),
14
14
  react: "\"use client\";\nimport { useEffect, useRef } from \"react\";\n\ntype AgentEmbed = { destroy: () => void };\ntype AgentEmbedSdk = { mount: (options: {\n container: HTMLElement; mode?: \"popup\" | \"inline\"; agentId: number; tokenEndpoint: string;\n inputs: Record<string, unknown>; label?: string; title?: string;\n getTokenHeaders?: () => Record<string, string>;\n}) => AgentEmbed };\ndeclare global { interface Window { SolidAgentEmbed?: AgentEmbedSdk } }\n\nconst SDK_URL = ".concat(js(sdkUrl), ";\nlet sdkPromise: Promise<AgentEmbedSdk> | undefined;\nfunction loadSdk() {\n if (window.SolidAgentEmbed) return Promise.resolve(window.SolidAgentEmbed);\n if (!sdkPromise) sdkPromise = new Promise((resolve, reject) => {\n const script = document.createElement(\"script\");\n script.src = SDK_URL;\n script.async = true;\n script.onload = () => window.SolidAgentEmbed\n ? resolve(window.SolidAgentEmbed)\n : reject(new Error(\"Agent embed SDK did not initialize\"));\n script.onerror = () => { script.remove(); sdkPromise = undefined; reject(new Error(\"Could not load Agent embed SDK\")); };\n document.head.appendChild(script);\n });\n return sdkPromise;\n}\n\nexport function AgentChat() {\n const containerRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n let disposed = false;\n let chat: AgentEmbed | undefined;\n void loadSdk().then((sdk) => {\n if (disposed || !containerRef.current) return;\n chat = sdk.mount({\n container: containerRef.current,\n ").concat(config.replace(/\n/g, "\n "), "\n });\n }).catch((error: unknown) => {\n if (!disposed) console.error(\"Could not initialize agent chat\", error);\n });\n return () => { disposed = true; chat?.destroy(); };\n }, []);\n return <div ref={containerRef} />;\n}"),
15
- python: "# FastAPI. Install httpx; mount this router in your application.\n# Keep these server-only environment variables out of the browser bundle:\n# AGENTHUB_API_KEY, AGENTHUB_AGENT_ID, AGENTHUB_BACKEND_URL\n".concat(environmentNote, "\nimport os\nimport httpx\nfrom fastapi import APIRouter, HTTPException, Request, Response\nfrom pydantic import BaseModel\n\nrouter = APIRouter()\nAGENTHUB_URL = (os.getenv(\"AGENTHUB_BACKEND_URL\") or \"\").rstrip(\"/\")\n\nclass TokenRequest(BaseModel):\n agentId: int\n\n@router.post(\"/api/agent-chat/token\")\nasync def create_agent_token(body: TokenRequest, request: Request, response: Response):\n response.headers[\"Cache-Control\"] = \"no-store\"\n try:\n agent_id = int(os.environ.get(\"AGENTHUB_AGENT_ID\", \"0\"))\n except ValueError:\n agent_id = 0\n api_key = os.getenv(\"AGENTHUB_API_KEY\")\n if not api_key or not AGENTHUB_URL or agent_id <= 0:\n raise HTTPException(status_code=503, detail=\"Chat is temporarily unavailable\")\n if body.agentId != agent_id:\n raise HTTPException(status_code=400, detail=\"Agent is not configured for this application\")\n # If trusted optional-auth middleware populated request.state.user, pass its stable ID.\n user = getattr(request.state, \"user\", None)\n external_id = user.get(\"id\") if isinstance(user, dict) else getattr(user, \"id\", None)\n payload = {\"apiKey\": api_key, \"agentId\": agent_id}\n if external_id is not None:\n payload[\"externalUserId\"] = f\"my-app:{external_id}\"\n try:\n async with httpx.AsyncClient(timeout=15) as client:\n upstream = await client.post(f\"{AGENTHUB_URL}/api/agent/api-keys/embedded/me\", json=payload)\n if not upstream.is_success:\n raise HTTPException(status_code=502, detail=\"Chat is temporarily unavailable\")\n return upstream.json() # forward the token response; never cache or log it\n except httpx.HTTPError as exc:\n raise HTTPException(status_code=503, detail=\"Chat is temporarily unavailable\") from exc\n"),
16
- nestjs: "// NestJS. Uses the app's existing ConfigService and optional auth middleware.\n// Add a distributed rate limit at the gateway or with your Nest throttler.\nimport { Body, Controller, HttpException, HttpStatus, Post, Req, Res } from \"@nestjs/common\";\nimport { ConfigService } from \"@nestjs/config\";\nimport { Public } from \"@solidxai/core\";\nimport { Request, Response } from \"express\";\n\n// Server environment: AGENTHUB_API_KEY=...; AGENTHUB_AGENT_ID=".concat(agentId, "\n").concat(environmentNoteSlash, "\ntype EmbedRequest = Request & { user?: { id?: string | number; sub?: string | number } };\n@Controller(\"agent-chat\")\nexport class AgentChatController {\n constructor(private readonly config: ConfigService) {}\n\n @Post(\"token\")\n @Public() // allow anonymous use; remove/replace with your app policy for login-only chat\n async createToken(@Body() body: { agentId: number }, @Req() req: EmbedRequest, @Res() res: Response) {\n res.setHeader(\"Cache-Control\", \"no-store\");\n const agentId = Number(this.config.get(\"AGENTHUB_AGENT_ID\")); // fixed; never trust browser selection\n const apiKey = this.config.get<string>(\"AGENTHUB_API_KEY\");\n const baseUrl = this.config.get<string>(\"AGENTHUB_BACKEND_URL\")?.replace(/\\/$/, \"\");\n if (!apiKey || !baseUrl || !Number.isSafeInteger(agentId) || agentId <= 0)\n throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.SERVICE_UNAVAILABLE);\n if (body.agentId !== agentId) throw new HttpException(\"Agent is not configured\", HttpStatus.BAD_REQUEST);\n const userId = req.user?.id ?? req.user?.sub; // set only by trusted auth middleware\n const payload = { apiKey, agentId, ...(userId != null ? { externalUserId: \"my-app:\" + userId } : {}) };\n try {\n const upstream = await fetch(baseUrl + \"/api/agent/api-keys/embedded/me\", {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000),\n });\n if (!upstream.ok) throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.BAD_GATEWAY);\n res.status(200).type(\"application/json\").send(await upstream.text());\n } catch (error) {\n if (error instanceof HttpException) throw error;\n throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.SERVICE_UNAVAILABLE);\n }\n }\n}\n// Mount behind trusted proxy configuration and rate limiting. Apply the app's\n// authentication/authorization guard instead of @Public() when access is restricted."),
17
- express: "// Express (Node.js 20+). Mount after any optional authentication middleware.\n// Protect this public endpoint with a distributed/IP-aware rate limiter in production.\n// Server environment: AGENTHUB_API_KEY=...; AGENTHUB_AGENT_ID=".concat(agentId, "\n").concat(environmentNoteSlash, "\nimport express from \"express\";\n\nconst router = express.Router();\nrouter.post(\"/api/agent-chat/token\", async (req, res) => {\n res.set(\"Cache-Control\", \"no-store\");\n const agentId = Number(process.env.AGENTHUB_AGENT_ID); // fixed server-side allowlist\n const apiKey = process.env.AGENTHUB_API_KEY;\n const baseUrl = process.env.AGENTHUB_BACKEND_URL?.replace(/\\/$/, \"\");\n if (!apiKey || !baseUrl || !Number.isSafeInteger(agentId) || agentId <= 0)\n return res.status(503).json({ error: \"Chat is temporarily unavailable\" });\n if (Number(req.body?.agentId) !== agentId)\n return res.status(400).json({ error: \"Agent is not configured for this application\" });\n const userId = req.user?.id ?? req.user?.sub; // optional identity from trusted middleware\n try {\n const upstream = await fetch(baseUrl + \"/api/agent/api-keys/embedded/me\", {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ apiKey, agentId, ...(userId != null ? { externalUserId: \"my-app:\" + userId } : {}) }),\n signal: AbortSignal.timeout(15_000),\n });\n if (!upstream.ok) return res.status(502).json({ error: \"Chat is temporarily unavailable\" });\n return res.status(200).type(\"application/json\").send(await upstream.text());\n } catch {\n return res.status(503).json({ error: \"Chat is temporarily unavailable\" });\n }\n});\nexport default router;\n// Ensure express.json() is installed. Never accept API key/backend URL from req.body."),
18
- java: "// Spring Boot 3 / Java 17+. Keep this route public for anonymous embeds,\n// or apply your application's authorization policy. Add a distributed rate limiter.\n// Server environment: AGENTHUB_API_KEY=...; AGENTHUB_AGENT_ID=".concat(agentId, "\n").concat(environmentNoteSlash, "\n@RestController\npublic class AgentEmbedController {\n private final java.net.http.HttpClient client = java.net.http.HttpClient.newBuilder()\n .connectTimeout(java.time.Duration.ofSeconds(5)).build();\n private final com.fasterxml.jackson.databind.ObjectMapper json = new com.fasterxml.jackson.databind.ObjectMapper();\n\n @Value(\"${AGENTHUB_API_KEY}\") private String apiKey;\n @Value(\"${AGENTHUB_AGENT_ID}\") private int agentId;\n @Value(\"${AGENTHUB_BACKEND_URL}\") private String agentHubUrl;\n\n @PostMapping(\"/api/agent-chat/token\")\n public ResponseEntity<String> token(@RequestBody Map<String, Object> request,\n org.springframework.security.core.Authentication authentication) throws Exception {\n if (!Integer.valueOf(agentId).equals(request.get(\"agentId\")))\n return ResponseEntity.badRequest().cacheControl(CacheControl.noStore()).build();\n Map<String, Object> payload = new java.util.HashMap<>();\n payload.put(\"apiKey\", apiKey); payload.put(\"agentId\", agentId);\n // Omit externalUserId for anonymous access; ignore anonymous security principals.\n if (authentication != null && authentication.isAuthenticated() &&\n !(authentication instanceof org.springframework.security.authentication.AnonymousAuthenticationToken))\n payload.put(\"externalUserId\", \"my-app:\" + authentication.getName());\n var upstreamRequest = java.net.http.HttpRequest.newBuilder()\n .uri(java.net.URI.create(agentHubUrl.replaceAll(\"/+$\", \"\") + \"/api/agent/api-keys/embedded/me\"))\n .timeout(java.time.Duration.ofSeconds(15)).header(\"Content-Type\", \"application/json\")\n .POST(java.net.http.HttpRequest.BodyPublishers.ofString(json.writeValueAsString(payload))).build();\n try {\n var upstream = client.send(upstreamRequest, java.net.http.HttpResponse.BodyHandlers.ofString());\n if (upstream.statusCode() != 200)\n return ResponseEntity.status(502).cacheControl(CacheControl.noStore()).build();\n return ResponseEntity.ok().cacheControl(CacheControl.noStore())\n .contentType(MediaType.APPLICATION_JSON).body(upstream.body());\n } catch (java.io.IOException | InterruptedException error) {\n if (error instanceof InterruptedException) Thread.currentThread().interrupt();\n return ResponseEntity.status(503).cacheControl(CacheControl.noStore()).build();\n }\n }\n}\n// Imports: org.springframework.beans.factory.annotation.Value, web.bind.annotation.*,\n// org.springframework.http.*, java.util.Map. Do not log the key or token response."),
19
- dotnet: "// ASP.NET Core Minimal API. Configure an IP/user rate-limit policy in production.\n// Authentication can be optional (anonymous demo) or required by your app's policy.\n// Server environment: AGENTHUB_API_KEY=...; AGENTHUB_AGENT_ID=".concat(agentId, "\n").concat(environmentNoteSlash, "\nusing System.Security.Claims;\nusing System.Collections.Generic;\nusing System.Net.Http.Json;\n\nbuilder.Services.AddHttpClient(\"AgentHub\", client => client.Timeout = TimeSpan.FromSeconds(15));\napp.MapPost(\"/api/agent-chat/token\", async (AgentTokenRequest body, HttpContext context, IHttpClientFactory clients, IConfiguration config) => {\n context.Response.Headers.CacheControl = \"no-store\";\n if (!int.TryParse(config[\"AGENTHUB_AGENT_ID\"], out var agentId) || agentId <= 0)\n return Results.StatusCode(503);\n var apiKey = config[\"AGENTHUB_API_KEY\"];\n var baseUrl = config[\"AGENTHUB_BACKEND_URL\"]?.TrimEnd('/');\n if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(baseUrl))\n return Results.StatusCode(503);\n if (body.AgentId != agentId)\n return Results.BadRequest(new { error = \"Agent is not configured for this application\" });\n var subject = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;\n var payload = new Dictionary<string, object?> { [\"apiKey\"] = apiKey, [\"agentId\"] = agentId };\n if (context.User.Identity?.IsAuthenticated == true && !string.IsNullOrEmpty(subject))\n payload[\"externalUserId\"] = \"my-app:\" + subject;\n try {\n var upstream = await clients.CreateClient(\"AgentHub\").PostAsJsonAsync(\n baseUrl + \"/api/agent/api-keys/embedded/me\", payload, context.RequestAborted);\n if (!upstream.IsSuccessStatusCode) return Results.StatusCode(502);\n return Results.Text(await upstream.Content.ReadAsStringAsync(context.RequestAborted), \"application/json\");\n } catch (HttpRequestException) { return Results.StatusCode(503); }\n}).AllowAnonymous(); // Replace with .RequireAuthorization() for login-only chat.\npublic sealed record AgentTokenRequest(int AgentId);\n// Imports: Microsoft.AspNetCore.Http, System.Net.Http.Json, System.Collections.Generic.\n// Add a distributed rate limiter and trusted-proxy configuration for public deployments."),
15
+ python: "# FastAPI. Install httpx; mount this router in your application.\n# Keep these server-only environment variables out of the browser bundle:\n# AGENT_HUB_API_KEY, AGENT_HUB_AGENT_ID, AGENT_HUB_BACKEND_URL\n".concat(environmentNote, "\nimport os\nimport httpx\nfrom fastapi import APIRouter, HTTPException, Request, Response\nfrom pydantic import BaseModel\n\nrouter = APIRouter()\nAGENT_HUB_URL = (os.getenv(\"AGENT_HUB_BACKEND_URL\") or \"\").rstrip(\"/\")\n\nclass TokenRequest(BaseModel):\n agentId: int\n\n@router.post(\"/api/agent-chat/token\")\nasync def create_agent_token(body: TokenRequest, request: Request, response: Response):\n response.headers[\"Cache-Control\"] = \"no-store\"\n try:\n agent_id = int(os.environ.get(\"AGENT_HUB_AGENT_ID\", \"0\"))\n except ValueError:\n agent_id = 0\n api_key = os.getenv(\"AGENT_HUB_API_KEY\")\n if not api_key or not AGENT_HUB_URL or agent_id <= 0:\n raise HTTPException(status_code=503, detail=\"Chat is temporarily unavailable\")\n if body.agentId != agent_id:\n raise HTTPException(status_code=400, detail=\"Agent is not configured for this application\")\n # If trusted optional-auth middleware populated request.state.user, pass its stable ID.\n user = getattr(request.state, \"user\", None)\n external_id = user.get(\"id\") if isinstance(user, dict) else getattr(user, \"id\", None)\n payload = {\"apiKey\": api_key, \"agentId\": agent_id}\n if external_id is not None:\n payload[\"externalUserId\"] = f\"my-app:{external_id}\"\n try:\n async with httpx.AsyncClient(timeout=15) as client:\n upstream = await client.post(f\"{AGENT_HUB_URL}/api/agent/api-keys/embedded/me\", json=payload)\n if not upstream.is_success:\n raise HTTPException(status_code=502, detail=\"Chat is temporarily unavailable\")\n return upstream.json() # forward the token response; never cache or log it\n except httpx.HTTPError as exc:\n raise HTTPException(status_code=503, detail=\"Chat is temporarily unavailable\") from exc\n"),
16
+ nestjs: "// NestJS. Uses the app's existing ConfigService and optional auth middleware.\n// Add a distributed rate limit at the gateway or with your Nest throttler.\nimport { Body, Controller, HttpException, HttpStatus, Post, Req, Res } from \"@nestjs/common\";\nimport { ConfigService } from \"@nestjs/config\";\nimport { Public } from \"@solidxai/core\";\nimport { Request, Response } from \"express\";\n\n// Server environment: AGENT_HUB_API_KEY=...; AGENT_HUB_AGENT_ID=".concat(agentId, "\n").concat(environmentNoteSlash, "\ntype EmbedRequest = Request & { user?: { id?: string | number; sub?: string | number } };\n@Controller(\"agent-chat\")\nexport class AgentChatController {\n constructor(private readonly config: ConfigService) {}\n\n @Post(\"token\")\n @Public() // allow anonymous use; remove/replace with your app policy for login-only chat\n async createToken(@Body() body: { agentId: number }, @Req() req: EmbedRequest, @Res() res: Response) {\n res.setHeader(\"Cache-Control\", \"no-store\");\n const agentId = Number(this.config.get(\"AGENT_HUB_AGENT_ID\")); // fixed; never trust browser selection\n const apiKey = this.config.get<string>(\"AGENT_HUB_API_KEY\");\n const baseUrl = this.config.get<string>(\"AGENT_HUB_BACKEND_URL\")?.replace(/\\/$/, \"\");\n if (!apiKey || !baseUrl || !Number.isSafeInteger(agentId) || agentId <= 0)\n throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.SERVICE_UNAVAILABLE);\n if (body.agentId !== agentId) throw new HttpException(\"Agent is not configured\", HttpStatus.BAD_REQUEST);\n const userId = req.user?.id ?? req.user?.sub; // set only by trusted auth middleware\n const payload = { apiKey, agentId, ...(userId != null ? { externalUserId: \"my-app:\" + userId } : {}) };\n try {\n const upstream = await fetch(baseUrl + \"/api/agent/api-keys/embedded/me\", {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000),\n });\n if (!upstream.ok) throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.BAD_GATEWAY);\n res.status(200).type(\"application/json\").send(await upstream.text());\n } catch (error) {\n if (error instanceof HttpException) throw error;\n throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.SERVICE_UNAVAILABLE);\n }\n }\n}\n// Mount behind trusted proxy configuration and rate limiting. Apply the app's\n// authentication/authorization guard instead of @Public() when access is restricted."),
17
+ express: "// Express (Node.js 20+). Mount after any optional authentication middleware.\n// Protect this public endpoint with a distributed/IP-aware rate limiter in production.\n// Server environment: AGENT_HUB_API_KEY=...; AGENT_HUB_AGENT_ID=".concat(agentId, "\n").concat(environmentNoteSlash, "\nimport express from \"express\";\n\nconst router = express.Router();\nrouter.post(\"/api/agent-chat/token\", async (req, res) => {\n res.set(\"Cache-Control\", \"no-store\");\n const agentId = Number(process.env.AGENT_HUB_AGENT_ID); // fixed server-side allowlist\n const apiKey = process.env.AGENT_HUB_API_KEY;\n const baseUrl = process.env.AGENT_HUB_BACKEND_URL?.replace(/\\/$/, \"\");\n if (!apiKey || !baseUrl || !Number.isSafeInteger(agentId) || agentId <= 0)\n return res.status(503).json({ error: \"Chat is temporarily unavailable\" });\n if (Number(req.body?.agentId) !== agentId)\n return res.status(400).json({ error: \"Agent is not configured for this application\" });\n const userId = req.user?.id ?? req.user?.sub; // optional identity from trusted middleware\n try {\n const upstream = await fetch(baseUrl + \"/api/agent/api-keys/embedded/me\", {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ apiKey, agentId, ...(userId != null ? { externalUserId: \"my-app:\" + userId } : {}) }),\n signal: AbortSignal.timeout(15_000),\n });\n if (!upstream.ok) return res.status(502).json({ error: \"Chat is temporarily unavailable\" });\n return res.status(200).type(\"application/json\").send(await upstream.text());\n } catch {\n return res.status(503).json({ error: \"Chat is temporarily unavailable\" });\n }\n});\nexport default router;\n// Ensure express.json() is installed. Never accept API key/backend URL from req.body."),
18
+ java: "// Spring Boot 3 / Java 17+. Keep this route public for anonymous embeds,\n// or apply your application's authorization policy. Add a distributed rate limiter.\n// Server environment: AGENT_HUB_API_KEY=...; AGENT_HUB_AGENT_ID=".concat(agentId, "\n").concat(environmentNoteSlash, "\n@RestController\npublic class AgentEmbedController {\n private final java.net.http.HttpClient client = java.net.http.HttpClient.newBuilder()\n .connectTimeout(java.time.Duration.ofSeconds(5)).build();\n private final com.fasterxml.jackson.databind.ObjectMapper json = new com.fasterxml.jackson.databind.ObjectMapper();\n\n @Value(\"${AGENT_HUB_API_KEY}\") private String apiKey;\n @Value(\"${AGENT_HUB_AGENT_ID}\") private int agentId;\n @Value(\"${AGENT_HUB_BACKEND_URL}\") private String agentHubUrl;\n\n @PostMapping(\"/api/agent-chat/token\")\n public ResponseEntity<String> token(@RequestBody Map<String, Object> request,\n org.springframework.security.core.Authentication authentication) throws Exception {\n if (!Integer.valueOf(agentId).equals(request.get(\"agentId\")))\n return ResponseEntity.badRequest().cacheControl(CacheControl.noStore()).build();\n Map<String, Object> payload = new java.util.HashMap<>();\n payload.put(\"apiKey\", apiKey); payload.put(\"agentId\", agentId);\n // Omit externalUserId for anonymous access; ignore anonymous security principals.\n if (authentication != null && authentication.isAuthenticated() &&\n !(authentication instanceof org.springframework.security.authentication.AnonymousAuthenticationToken))\n payload.put(\"externalUserId\", \"my-app:\" + authentication.getName());\n var upstreamRequest = java.net.http.HttpRequest.newBuilder()\n .uri(java.net.URI.create(agentHubUrl.replaceAll(\"/+$\", \"\") + \"/api/agent/api-keys/embedded/me\"))\n .timeout(java.time.Duration.ofSeconds(15)).header(\"Content-Type\", \"application/json\")\n .POST(java.net.http.HttpRequest.BodyPublishers.ofString(json.writeValueAsString(payload))).build();\n try {\n var upstream = client.send(upstreamRequest, java.net.http.HttpResponse.BodyHandlers.ofString());\n if (upstream.statusCode() != 200)\n return ResponseEntity.status(502).cacheControl(CacheControl.noStore()).build();\n return ResponseEntity.ok().cacheControl(CacheControl.noStore())\n .contentType(MediaType.APPLICATION_JSON).body(upstream.body());\n } catch (java.io.IOException | InterruptedException error) {\n if (error instanceof InterruptedException) Thread.currentThread().interrupt();\n return ResponseEntity.status(503).cacheControl(CacheControl.noStore()).build();\n }\n }\n}\n// Imports: org.springframework.beans.factory.annotation.Value, web.bind.annotation.*,\n// org.springframework.http.*, java.util.Map. Do not log the key or token response."),
19
+ dotnet: "// ASP.NET Core Minimal API. Configure an IP/user rate-limit policy in production.\n// Authentication can be optional (anonymous demo) or required by your app's policy.\n// Server environment: AGENT_HUB_API_KEY=...; AGENT_HUB_AGENT_ID=".concat(agentId, "\n").concat(environmentNoteSlash, "\nusing System.Security.Claims;\nusing System.Collections.Generic;\nusing System.Net.Http.Json;\n\nbuilder.Services.AddHttpClient(\"AgentHub\", client => client.Timeout = TimeSpan.FromSeconds(15));\napp.MapPost(\"/api/agent-chat/token\", async (AgentTokenRequest body, HttpContext context, IHttpClientFactory clients, IConfiguration config) => {\n context.Response.Headers.CacheControl = \"no-store\";\n if (!int.TryParse(config[\"AGENT_HUB_AGENT_ID\"], out var agentId) || agentId <= 0)\n return Results.StatusCode(503);\n var apiKey = config[\"AGENT_HUB_API_KEY\"];\n var baseUrl = config[\"AGENT_HUB_BACKEND_URL\"]?.TrimEnd('/');\n if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(baseUrl))\n return Results.StatusCode(503);\n if (body.AgentId != agentId)\n return Results.BadRequest(new { error = \"Agent is not configured for this application\" });\n var subject = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;\n var payload = new Dictionary<string, object?> { [\"apiKey\"] = apiKey, [\"agentId\"] = agentId };\n if (context.User.Identity?.IsAuthenticated == true && !string.IsNullOrEmpty(subject))\n payload[\"externalUserId\"] = \"my-app:\" + subject;\n try {\n var upstream = await clients.CreateClient(\"AgentHub\").PostAsJsonAsync(\n baseUrl + \"/api/agent/api-keys/embedded/me\", payload, context.RequestAborted);\n if (!upstream.IsSuccessStatusCode) return Results.StatusCode(502);\n return Results.Text(await upstream.Content.ReadAsStringAsync(context.RequestAborted), \"application/json\");\n } catch (HttpRequestException) { return Results.StatusCode(503); }\n}).AllowAnonymous(); // Replace with .RequireAuthorization() for login-only chat.\npublic sealed record AgentTokenRequest(int AgentId);\n// Imports: Microsoft.AspNetCore.Http, System.Net.Http.Json, System.Collections.Generic.\n// Add a distributed rate limiter and trusted-proxy configuration for public deployments."),
20
20
  };
21
21
  }
22
22
  //# sourceMappingURL=agentEmbedSamples.js.map
@@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AU,CAAE,CAAC;IAC9G,OAAO;QACH,UAAU,EAAE,qDACN,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,6OAMpD,MAAM,+RAMF;QACF,MAAM,EAAE,wFACF,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,kRAOpD,MAAM,qKAKF;QACF,KAAK,EAAE,2eAWG,EAAE,CAAC,MAAM,CAAC,uhCA0BlB,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,YAAY,CAAC,2PAQ3C;QACM,MAAM,EAAE,oNAGd,eAAe,8zDAsChB;QACO,MAAM,EAAE,wdAOiD,OAAO,eACtE,oBAAoB,2hEAgCgE;QAC9E,OAAO,EAAE,iPAEgD,OAAO,eACtE,oBAAoB,6/CA2BiE;QAC/E,IAAI,EAAE,0OAEmD,OAAO,eACtE,oBAAoB,ojFAuC8D;QAC5E,MAAM,EAAE,mPAEiD,OAAO,eACtE,oBAAoB,g+DA6BoE;KACrF,CAAC;AACN,CAAC","sourcesContent":["import type { AgentInputDefinition } from \"./agentEmbedProtocol\";\n\nconst js = (value: unknown) => JSON.stringify(value, null, 2).replace(/</g, \"\\\\u003c\").replace(/\\u2028/g, \"\\\\u2028\").replace(/\\u2029/g, \"\\\\u2029\");\nconst examples: Record<string, unknown> = { string: \"Replace with your value\", number: 0, integer: 0, boolean: false,\n date: \"2026-01-01\", datetime: \"2026-01-01T09:00:00Z\", object: {}, array: [] };\n\nexport function embedSamples(agentId: number, fields: AgentInputDefinition[], sdkUrl: string, hubBase: string) {\n const values = Object.fromEntries(fields.map((field) => [field.name, examples[field.dataType] ?? \"Replace with your value\"]));\n const valuesJson = js(values).replace(/\\n/g, \"\\n \");\n const backendUrl = hubBase.replace(/\\/$/, \"\");\n const environmentNote = `# AGENTHUB_BACKEND_URL=${backendUrl}`;\n const environmentNoteSlash = `// AGENTHUB_BACKEND_URL=${backendUrl}`;\n const config = `agentId: ${agentId},\\n tokenEndpoint: \"/api/agent-chat/token\",\\n inputs: ${valuesJson}`;\n return {\n javascript: `<div id=\"agent-chat\"></div>\n<script src=${JSON.stringify(sdkUrl).replace(/</g, \"&lt;\")}></script>\n<script>\n // Values should come from the current page or trusted app state.\n // The API key and AgentHub URL stay on your server.\n const chat = SolidAgentEmbed.mount({\n container: \"#agent-chat\",\n ${config}\n });\n // For app auth/CSRF, add getTokenHeaders: () => yourAppAuthHeaders().\n // Optional lifecycle methods: chat.open(), chat.close(), chat.destroy().\n // Update context before the first message or after starting a new chat:\n // await chat.setInputs({ ... });\n</script>`,\n inline: `<div id=\"agent-chat\" style=\"width:420px;height:600px\"></div>\n<script src=${JSON.stringify(sdkUrl).replace(/</g, \"&lt;\")}></script>\n<script>\n // Your app owns this container's size, position, and visibility.\n // Keep the same instance mounted when navigating within your app.\n const chat = SolidAgentEmbed.mount({\n mode: \"inline\",\n container: \"#agent-chat\",\n ${config}\n });\n chat.open();\n // chat.close() hides the iframe without ending the chat.\n // chat.destroy() removes the iframe when the user signs out.\n</script>`,\n react: `\"use client\";\nimport { useEffect, useRef } from \"react\";\n\ntype AgentEmbed = { destroy: () => void };\ntype AgentEmbedSdk = { mount: (options: {\n container: HTMLElement; mode?: \"popup\" | \"inline\"; agentId: number; tokenEndpoint: string;\n inputs: Record<string, unknown>; label?: string; title?: string;\n getTokenHeaders?: () => Record<string, string>;\n}) => AgentEmbed };\ndeclare global { interface Window { SolidAgentEmbed?: AgentEmbedSdk } }\n\nconst SDK_URL = ${js(sdkUrl)};\nlet sdkPromise: Promise<AgentEmbedSdk> | undefined;\nfunction loadSdk() {\n if (window.SolidAgentEmbed) return Promise.resolve(window.SolidAgentEmbed);\n if (!sdkPromise) sdkPromise = new Promise((resolve, reject) => {\n const script = document.createElement(\"script\");\n script.src = SDK_URL;\n script.async = true;\n script.onload = () => window.SolidAgentEmbed\n ? resolve(window.SolidAgentEmbed)\n : reject(new Error(\"Agent embed SDK did not initialize\"));\n script.onerror = () => { script.remove(); sdkPromise = undefined; reject(new Error(\"Could not load Agent embed SDK\")); };\n document.head.appendChild(script);\n });\n return sdkPromise;\n}\n\nexport function AgentChat() {\n const containerRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n let disposed = false;\n let chat: AgentEmbed | undefined;\n void loadSdk().then((sdk) => {\n if (disposed || !containerRef.current) return;\n chat = sdk.mount({\n container: containerRef.current,\n ${config.replace(/\\n/g, \"\\n \")}\n });\n }).catch((error: unknown) => {\n if (!disposed) console.error(\"Could not initialize agent chat\", error);\n });\n return () => { disposed = true; chat?.destroy(); };\n }, []);\n return <div ref={containerRef} />;\n}`,\n python: `# FastAPI. Install httpx; mount this router in your application.\n# Keep these server-only environment variables out of the browser bundle:\n# AGENTHUB_API_KEY, AGENTHUB_AGENT_ID, AGENTHUB_BACKEND_URL\n${environmentNote}\nimport os\nimport httpx\nfrom fastapi import APIRouter, HTTPException, Request, Response\nfrom pydantic import BaseModel\n\nrouter = APIRouter()\nAGENTHUB_URL = (os.getenv(\"AGENTHUB_BACKEND_URL\") or \"\").rstrip(\"/\")\n\nclass TokenRequest(BaseModel):\n agentId: int\n\n@router.post(\"/api/agent-chat/token\")\nasync def create_agent_token(body: TokenRequest, request: Request, response: Response):\n response.headers[\"Cache-Control\"] = \"no-store\"\n try:\n agent_id = int(os.environ.get(\"AGENTHUB_AGENT_ID\", \"0\"))\n except ValueError:\n agent_id = 0\n api_key = os.getenv(\"AGENTHUB_API_KEY\")\n if not api_key or not AGENTHUB_URL or agent_id <= 0:\n raise HTTPException(status_code=503, detail=\"Chat is temporarily unavailable\")\n if body.agentId != agent_id:\n raise HTTPException(status_code=400, detail=\"Agent is not configured for this application\")\n # If trusted optional-auth middleware populated request.state.user, pass its stable ID.\n user = getattr(request.state, \"user\", None)\n external_id = user.get(\"id\") if isinstance(user, dict) else getattr(user, \"id\", None)\n payload = {\"apiKey\": api_key, \"agentId\": agent_id}\n if external_id is not None:\n payload[\"externalUserId\"] = f\"my-app:{external_id}\"\n try:\n async with httpx.AsyncClient(timeout=15) as client:\n upstream = await client.post(f\"{AGENTHUB_URL}/api/agent/api-keys/embedded/me\", json=payload)\n if not upstream.is_success:\n raise HTTPException(status_code=502, detail=\"Chat is temporarily unavailable\")\n return upstream.json() # forward the token response; never cache or log it\n except httpx.HTTPError as exc:\n raise HTTPException(status_code=503, detail=\"Chat is temporarily unavailable\") from exc\n`,\n nestjs: `// NestJS. Uses the app's existing ConfigService and optional auth middleware.\n// Add a distributed rate limit at the gateway or with your Nest throttler.\nimport { Body, Controller, HttpException, HttpStatus, Post, Req, Res } from \"@nestjs/common\";\nimport { ConfigService } from \"@nestjs/config\";\nimport { Public } from \"@solidxai/core\";\nimport { Request, Response } from \"express\";\n\n// Server environment: AGENTHUB_API_KEY=...; AGENTHUB_AGENT_ID=${agentId}\n${environmentNoteSlash}\ntype EmbedRequest = Request & { user?: { id?: string | number; sub?: string | number } };\n@Controller(\"agent-chat\")\nexport class AgentChatController {\n constructor(private readonly config: ConfigService) {}\n\n @Post(\"token\")\n @Public() // allow anonymous use; remove/replace with your app policy for login-only chat\n async createToken(@Body() body: { agentId: number }, @Req() req: EmbedRequest, @Res() res: Response) {\n res.setHeader(\"Cache-Control\", \"no-store\");\n const agentId = Number(this.config.get(\"AGENTHUB_AGENT_ID\")); // fixed; never trust browser selection\n const apiKey = this.config.get<string>(\"AGENTHUB_API_KEY\");\n const baseUrl = this.config.get<string>(\"AGENTHUB_BACKEND_URL\")?.replace(/\\\\/$/, \"\");\n if (!apiKey || !baseUrl || !Number.isSafeInteger(agentId) || agentId <= 0)\n throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.SERVICE_UNAVAILABLE);\n if (body.agentId !== agentId) throw new HttpException(\"Agent is not configured\", HttpStatus.BAD_REQUEST);\n const userId = req.user?.id ?? req.user?.sub; // set only by trusted auth middleware\n const payload = { apiKey, agentId, ...(userId != null ? { externalUserId: \"my-app:\" + userId } : {}) };\n try {\n const upstream = await fetch(baseUrl + \"/api/agent/api-keys/embedded/me\", {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000),\n });\n if (!upstream.ok) throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.BAD_GATEWAY);\n res.status(200).type(\"application/json\").send(await upstream.text());\n } catch (error) {\n if (error instanceof HttpException) throw error;\n throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.SERVICE_UNAVAILABLE);\n }\n }\n}\n// Mount behind trusted proxy configuration and rate limiting. Apply the app's\n// authentication/authorization guard instead of @Public() when access is restricted.`,\n express: `// Express (Node.js 20+). Mount after any optional authentication middleware.\n// Protect this public endpoint with a distributed/IP-aware rate limiter in production.\n// Server environment: AGENTHUB_API_KEY=...; AGENTHUB_AGENT_ID=${agentId}\n${environmentNoteSlash}\nimport express from \"express\";\n\nconst router = express.Router();\nrouter.post(\"/api/agent-chat/token\", async (req, res) => {\n res.set(\"Cache-Control\", \"no-store\");\n const agentId = Number(process.env.AGENTHUB_AGENT_ID); // fixed server-side allowlist\n const apiKey = process.env.AGENTHUB_API_KEY;\n const baseUrl = process.env.AGENTHUB_BACKEND_URL?.replace(/\\\\/$/, \"\");\n if (!apiKey || !baseUrl || !Number.isSafeInteger(agentId) || agentId <= 0)\n return res.status(503).json({ error: \"Chat is temporarily unavailable\" });\n if (Number(req.body?.agentId) !== agentId)\n return res.status(400).json({ error: \"Agent is not configured for this application\" });\n const userId = req.user?.id ?? req.user?.sub; // optional identity from trusted middleware\n try {\n const upstream = await fetch(baseUrl + \"/api/agent/api-keys/embedded/me\", {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ apiKey, agentId, ...(userId != null ? { externalUserId: \"my-app:\" + userId } : {}) }),\n signal: AbortSignal.timeout(15_000),\n });\n if (!upstream.ok) return res.status(502).json({ error: \"Chat is temporarily unavailable\" });\n return res.status(200).type(\"application/json\").send(await upstream.text());\n } catch {\n return res.status(503).json({ error: \"Chat is temporarily unavailable\" });\n }\n});\nexport default router;\n// Ensure express.json() is installed. Never accept API key/backend URL from req.body.`,\n java: `// Spring Boot 3 / Java 17+. Keep this route public for anonymous embeds,\n// or apply your application's authorization policy. Add a distributed rate limiter.\n// Server environment: AGENTHUB_API_KEY=...; AGENTHUB_AGENT_ID=${agentId}\n${environmentNoteSlash}\n@RestController\npublic class AgentEmbedController {\n private final java.net.http.HttpClient client = java.net.http.HttpClient.newBuilder()\n .connectTimeout(java.time.Duration.ofSeconds(5)).build();\n private final com.fasterxml.jackson.databind.ObjectMapper json = new com.fasterxml.jackson.databind.ObjectMapper();\n\n @Value(\"\\${AGENTHUB_API_KEY}\") private String apiKey;\n @Value(\"\\${AGENTHUB_AGENT_ID}\") private int agentId;\n @Value(\"\\${AGENTHUB_BACKEND_URL}\") private String agentHubUrl;\n\n @PostMapping(\"/api/agent-chat/token\")\n public ResponseEntity<String> token(@RequestBody Map<String, Object> request,\n org.springframework.security.core.Authentication authentication) throws Exception {\n if (!Integer.valueOf(agentId).equals(request.get(\"agentId\")))\n return ResponseEntity.badRequest().cacheControl(CacheControl.noStore()).build();\n Map<String, Object> payload = new java.util.HashMap<>();\n payload.put(\"apiKey\", apiKey); payload.put(\"agentId\", agentId);\n // Omit externalUserId for anonymous access; ignore anonymous security principals.\n if (authentication != null && authentication.isAuthenticated() &&\n !(authentication instanceof org.springframework.security.authentication.AnonymousAuthenticationToken))\n payload.put(\"externalUserId\", \"my-app:\" + authentication.getName());\n var upstreamRequest = java.net.http.HttpRequest.newBuilder()\n .uri(java.net.URI.create(agentHubUrl.replaceAll(\"/+$\", \"\") + \"/api/agent/api-keys/embedded/me\"))\n .timeout(java.time.Duration.ofSeconds(15)).header(\"Content-Type\", \"application/json\")\n .POST(java.net.http.HttpRequest.BodyPublishers.ofString(json.writeValueAsString(payload))).build();\n try {\n var upstream = client.send(upstreamRequest, java.net.http.HttpResponse.BodyHandlers.ofString());\n if (upstream.statusCode() != 200)\n return ResponseEntity.status(502).cacheControl(CacheControl.noStore()).build();\n return ResponseEntity.ok().cacheControl(CacheControl.noStore())\n .contentType(MediaType.APPLICATION_JSON).body(upstream.body());\n } catch (java.io.IOException | InterruptedException error) {\n if (error instanceof InterruptedException) Thread.currentThread().interrupt();\n return ResponseEntity.status(503).cacheControl(CacheControl.noStore()).build();\n }\n }\n}\n// Imports: org.springframework.beans.factory.annotation.Value, web.bind.annotation.*,\n// org.springframework.http.*, java.util.Map. Do not log the key or token response.`,\n dotnet: `// ASP.NET Core Minimal API. Configure an IP/user rate-limit policy in production.\n// Authentication can be optional (anonymous demo) or required by your app's policy.\n// Server environment: AGENTHUB_API_KEY=...; AGENTHUB_AGENT_ID=${agentId}\n${environmentNoteSlash}\nusing System.Security.Claims;\nusing System.Collections.Generic;\nusing System.Net.Http.Json;\n\nbuilder.Services.AddHttpClient(\"AgentHub\", client => client.Timeout = TimeSpan.FromSeconds(15));\napp.MapPost(\"/api/agent-chat/token\", async (AgentTokenRequest body, HttpContext context, IHttpClientFactory clients, IConfiguration config) => {\n context.Response.Headers.CacheControl = \"no-store\";\n if (!int.TryParse(config[\"AGENTHUB_AGENT_ID\"], out var agentId) || agentId <= 0)\n return Results.StatusCode(503);\n var apiKey = config[\"AGENTHUB_API_KEY\"];\n var baseUrl = config[\"AGENTHUB_BACKEND_URL\"]?.TrimEnd('/');\n if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(baseUrl))\n return Results.StatusCode(503);\n if (body.AgentId != agentId)\n return Results.BadRequest(new { error = \"Agent is not configured for this application\" });\n var subject = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;\n var payload = new Dictionary<string, object?> { [\"apiKey\"] = apiKey, [\"agentId\"] = agentId };\n if (context.User.Identity?.IsAuthenticated == true && !string.IsNullOrEmpty(subject))\n payload[\"externalUserId\"] = \"my-app:\" + subject;\n try {\n var upstream = await clients.CreateClient(\"AgentHub\").PostAsJsonAsync(\n baseUrl + \"/api/agent/api-keys/embedded/me\", payload, context.RequestAborted);\n if (!upstream.IsSuccessStatusCode) return Results.StatusCode(502);\n return Results.Text(await upstream.Content.ReadAsStringAsync(context.RequestAborted), \"application/json\");\n } catch (HttpRequestException) { return Results.StatusCode(503); }\n}).AllowAnonymous(); // Replace with .RequireAuthorization() for login-only chat.\npublic sealed record AgentTokenRequest(int AgentId);\n// Imports: Microsoft.AspNetCore.Http, System.Net.Http.Json, System.Collections.Generic.\n// Add a distributed rate limiter and trusted-proxy configuration for public deployments.`,\n };\n}\n"]}
1
+ {"version":3,"file":"agentEmbedSamples.js","sourceRoot":"","sources":["../../../../../src/components/core/solid-agent/embed/agentEmbedSamples.ts"],"names":[],"mappings":"AAEA,IAAM,EAAE,GAAG,UAAC,KAAc,IAAK,OAAA,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,EAAnH,CAAmH,CAAC;AACnJ,IAAM,QAAQ,GAA4B,EAAE,MAAM,EAAE,yBAAyB,EAAE,MAAM,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK;IAChH,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;AAElF,MAAM,UAAU,YAAY,CAAC,OAAe,EAAE,MAA8B,EAAE,MAAc,EAAE,OAAe;IACzG,IAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,UAAC,KAAK,YAAK,OAAA,CAAC,KAAK,CAAC,IAAI,EAAE,MAAA,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,mCAAI,yBAAyB,CAAC,CAAA,EAAA,CAAC,CAAC,CAAC;IAC9H,IAAM,UAAU,GAAG,EAAE,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IACvD,IAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAC9C,IAAM,eAAe,GAAG,kCAA2B,UAAU,CAAE,CAAC;IAChE,IAAM,oBAAoB,GAAG,mCAA4B,UAAU,CAAE,CAAC;IACtE,IAAM,MAAM,GAAG,mBAAY,OAAO,2EAA+D,UAAU,CAAE,CAAC;IAC9G,OAAO;QACH,UAAU,EAAE,qDACN,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,6OAMpD,MAAM,+RAMF;QACF,MAAM,EAAE,wFACF,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,kRAOpD,MAAM,qKAKF;QACF,KAAK,EAAE,2eAWG,EAAE,CAAC,MAAM,CAAC,uhCA0BlB,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,YAAY,CAAC,2PAQ3C;QACM,MAAM,EAAE,uNAGd,eAAe,o0DAsChB;QACO,MAAM,EAAE,0dAOmD,OAAO,eACxE,oBAAoB,8hEAgCgE;QAC9E,OAAO,EAAE,mPAEkD,OAAO,eACxE,oBAAoB,ggDA2BiE;QAC/E,IAAI,EAAE,4OAEqD,OAAO,eACxE,oBAAoB,ujFAuC8D;QAC5E,MAAM,EAAE,qPAEmD,OAAO,eACxE,oBAAoB,m+DA6BoE;KACrF,CAAC;AACN,CAAC","sourcesContent":["import type { AgentInputDefinition } from \"./agentEmbedProtocol\";\n\nconst js = (value: unknown) => JSON.stringify(value, null, 2).replace(/</g, \"\\\\u003c\").replace(/\\u2028/g, \"\\\\u2028\").replace(/\\u2029/g, \"\\\\u2029\");\nconst examples: Record<string, unknown> = { string: \"Replace with your value\", number: 0, integer: 0, boolean: false,\n date: \"2026-01-01\", datetime: \"2026-01-01T09:00:00Z\", object: {}, array: [] };\n\nexport function embedSamples(agentId: number, fields: AgentInputDefinition[], sdkUrl: string, hubBase: string) {\n const values = Object.fromEntries(fields.map((field) => [field.name, examples[field.dataType] ?? \"Replace with your value\"]));\n const valuesJson = js(values).replace(/\\n/g, \"\\n \");\n const backendUrl = hubBase.replace(/\\/$/, \"\");\n const environmentNote = `# AGENT_HUB_BACKEND_URL=${backendUrl}`;\n const environmentNoteSlash = `// AGENT_HUB_BACKEND_URL=${backendUrl}`;\n const config = `agentId: ${agentId},\\n tokenEndpoint: \"/api/agent-chat/token\",\\n inputs: ${valuesJson}`;\n return {\n javascript: `<div id=\"agent-chat\"></div>\n<script src=${JSON.stringify(sdkUrl).replace(/</g, \"&lt;\")}></script>\n<script>\n // Values should come from the current page or trusted app state.\n // The API key and AgentHub URL stay on your server.\n const chat = SolidAgentEmbed.mount({\n container: \"#agent-chat\",\n ${config}\n });\n // For app auth/CSRF, add getTokenHeaders: () => yourAppAuthHeaders().\n // Optional lifecycle methods: chat.open(), chat.close(), chat.destroy().\n // Update context before the first message or after starting a new chat:\n // await chat.setInputs({ ... });\n</script>`,\n inline: `<div id=\"agent-chat\" style=\"width:420px;height:600px\"></div>\n<script src=${JSON.stringify(sdkUrl).replace(/</g, \"&lt;\")}></script>\n<script>\n // Your app owns this container's size, position, and visibility.\n // Keep the same instance mounted when navigating within your app.\n const chat = SolidAgentEmbed.mount({\n mode: \"inline\",\n container: \"#agent-chat\",\n ${config}\n });\n chat.open();\n // chat.close() hides the iframe without ending the chat.\n // chat.destroy() removes the iframe when the user signs out.\n</script>`,\n react: `\"use client\";\nimport { useEffect, useRef } from \"react\";\n\ntype AgentEmbed = { destroy: () => void };\ntype AgentEmbedSdk = { mount: (options: {\n container: HTMLElement; mode?: \"popup\" | \"inline\"; agentId: number; tokenEndpoint: string;\n inputs: Record<string, unknown>; label?: string; title?: string;\n getTokenHeaders?: () => Record<string, string>;\n}) => AgentEmbed };\ndeclare global { interface Window { SolidAgentEmbed?: AgentEmbedSdk } }\n\nconst SDK_URL = ${js(sdkUrl)};\nlet sdkPromise: Promise<AgentEmbedSdk> | undefined;\nfunction loadSdk() {\n if (window.SolidAgentEmbed) return Promise.resolve(window.SolidAgentEmbed);\n if (!sdkPromise) sdkPromise = new Promise((resolve, reject) => {\n const script = document.createElement(\"script\");\n script.src = SDK_URL;\n script.async = true;\n script.onload = () => window.SolidAgentEmbed\n ? resolve(window.SolidAgentEmbed)\n : reject(new Error(\"Agent embed SDK did not initialize\"));\n script.onerror = () => { script.remove(); sdkPromise = undefined; reject(new Error(\"Could not load Agent embed SDK\")); };\n document.head.appendChild(script);\n });\n return sdkPromise;\n}\n\nexport function AgentChat() {\n const containerRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n let disposed = false;\n let chat: AgentEmbed | undefined;\n void loadSdk().then((sdk) => {\n if (disposed || !containerRef.current) return;\n chat = sdk.mount({\n container: containerRef.current,\n ${config.replace(/\\n/g, \"\\n \")}\n });\n }).catch((error: unknown) => {\n if (!disposed) console.error(\"Could not initialize agent chat\", error);\n });\n return () => { disposed = true; chat?.destroy(); };\n }, []);\n return <div ref={containerRef} />;\n}`,\n python: `# FastAPI. Install httpx; mount this router in your application.\n# Keep these server-only environment variables out of the browser bundle:\n# AGENT_HUB_API_KEY, AGENT_HUB_AGENT_ID, AGENT_HUB_BACKEND_URL\n${environmentNote}\nimport os\nimport httpx\nfrom fastapi import APIRouter, HTTPException, Request, Response\nfrom pydantic import BaseModel\n\nrouter = APIRouter()\nAGENT_HUB_URL = (os.getenv(\"AGENT_HUB_BACKEND_URL\") or \"\").rstrip(\"/\")\n\nclass TokenRequest(BaseModel):\n agentId: int\n\n@router.post(\"/api/agent-chat/token\")\nasync def create_agent_token(body: TokenRequest, request: Request, response: Response):\n response.headers[\"Cache-Control\"] = \"no-store\"\n try:\n agent_id = int(os.environ.get(\"AGENT_HUB_AGENT_ID\", \"0\"))\n except ValueError:\n agent_id = 0\n api_key = os.getenv(\"AGENT_HUB_API_KEY\")\n if not api_key or not AGENT_HUB_URL or agent_id <= 0:\n raise HTTPException(status_code=503, detail=\"Chat is temporarily unavailable\")\n if body.agentId != agent_id:\n raise HTTPException(status_code=400, detail=\"Agent is not configured for this application\")\n # If trusted optional-auth middleware populated request.state.user, pass its stable ID.\n user = getattr(request.state, \"user\", None)\n external_id = user.get(\"id\") if isinstance(user, dict) else getattr(user, \"id\", None)\n payload = {\"apiKey\": api_key, \"agentId\": agent_id}\n if external_id is not None:\n payload[\"externalUserId\"] = f\"my-app:{external_id}\"\n try:\n async with httpx.AsyncClient(timeout=15) as client:\n upstream = await client.post(f\"{AGENT_HUB_URL}/api/agent/api-keys/embedded/me\", json=payload)\n if not upstream.is_success:\n raise HTTPException(status_code=502, detail=\"Chat is temporarily unavailable\")\n return upstream.json() # forward the token response; never cache or log it\n except httpx.HTTPError as exc:\n raise HTTPException(status_code=503, detail=\"Chat is temporarily unavailable\") from exc\n`,\n nestjs: `// NestJS. Uses the app's existing ConfigService and optional auth middleware.\n// Add a distributed rate limit at the gateway or with your Nest throttler.\nimport { Body, Controller, HttpException, HttpStatus, Post, Req, Res } from \"@nestjs/common\";\nimport { ConfigService } from \"@nestjs/config\";\nimport { Public } from \"@solidxai/core\";\nimport { Request, Response } from \"express\";\n\n// Server environment: AGENT_HUB_API_KEY=...; AGENT_HUB_AGENT_ID=${agentId}\n${environmentNoteSlash}\ntype EmbedRequest = Request & { user?: { id?: string | number; sub?: string | number } };\n@Controller(\"agent-chat\")\nexport class AgentChatController {\n constructor(private readonly config: ConfigService) {}\n\n @Post(\"token\")\n @Public() // allow anonymous use; remove/replace with your app policy for login-only chat\n async createToken(@Body() body: { agentId: number }, @Req() req: EmbedRequest, @Res() res: Response) {\n res.setHeader(\"Cache-Control\", \"no-store\");\n const agentId = Number(this.config.get(\"AGENT_HUB_AGENT_ID\")); // fixed; never trust browser selection\n const apiKey = this.config.get<string>(\"AGENT_HUB_API_KEY\");\n const baseUrl = this.config.get<string>(\"AGENT_HUB_BACKEND_URL\")?.replace(/\\\\/$/, \"\");\n if (!apiKey || !baseUrl || !Number.isSafeInteger(agentId) || agentId <= 0)\n throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.SERVICE_UNAVAILABLE);\n if (body.agentId !== agentId) throw new HttpException(\"Agent is not configured\", HttpStatus.BAD_REQUEST);\n const userId = req.user?.id ?? req.user?.sub; // set only by trusted auth middleware\n const payload = { apiKey, agentId, ...(userId != null ? { externalUserId: \"my-app:\" + userId } : {}) };\n try {\n const upstream = await fetch(baseUrl + \"/api/agent/api-keys/embedded/me\", {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000),\n });\n if (!upstream.ok) throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.BAD_GATEWAY);\n res.status(200).type(\"application/json\").send(await upstream.text());\n } catch (error) {\n if (error instanceof HttpException) throw error;\n throw new HttpException(\"Chat is temporarily unavailable\", HttpStatus.SERVICE_UNAVAILABLE);\n }\n }\n}\n// Mount behind trusted proxy configuration and rate limiting. Apply the app's\n// authentication/authorization guard instead of @Public() when access is restricted.`,\n express: `// Express (Node.js 20+). Mount after any optional authentication middleware.\n// Protect this public endpoint with a distributed/IP-aware rate limiter in production.\n// Server environment: AGENT_HUB_API_KEY=...; AGENT_HUB_AGENT_ID=${agentId}\n${environmentNoteSlash}\nimport express from \"express\";\n\nconst router = express.Router();\nrouter.post(\"/api/agent-chat/token\", async (req, res) => {\n res.set(\"Cache-Control\", \"no-store\");\n const agentId = Number(process.env.AGENT_HUB_AGENT_ID); // fixed server-side allowlist\n const apiKey = process.env.AGENT_HUB_API_KEY;\n const baseUrl = process.env.AGENT_HUB_BACKEND_URL?.replace(/\\\\/$/, \"\");\n if (!apiKey || !baseUrl || !Number.isSafeInteger(agentId) || agentId <= 0)\n return res.status(503).json({ error: \"Chat is temporarily unavailable\" });\n if (Number(req.body?.agentId) !== agentId)\n return res.status(400).json({ error: \"Agent is not configured for this application\" });\n const userId = req.user?.id ?? req.user?.sub; // optional identity from trusted middleware\n try {\n const upstream = await fetch(baseUrl + \"/api/agent/api-keys/embedded/me\", {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ apiKey, agentId, ...(userId != null ? { externalUserId: \"my-app:\" + userId } : {}) }),\n signal: AbortSignal.timeout(15_000),\n });\n if (!upstream.ok) return res.status(502).json({ error: \"Chat is temporarily unavailable\" });\n return res.status(200).type(\"application/json\").send(await upstream.text());\n } catch {\n return res.status(503).json({ error: \"Chat is temporarily unavailable\" });\n }\n});\nexport default router;\n// Ensure express.json() is installed. Never accept API key/backend URL from req.body.`,\n java: `// Spring Boot 3 / Java 17+. Keep this route public for anonymous embeds,\n// or apply your application's authorization policy. Add a distributed rate limiter.\n// Server environment: AGENT_HUB_API_KEY=...; AGENT_HUB_AGENT_ID=${agentId}\n${environmentNoteSlash}\n@RestController\npublic class AgentEmbedController {\n private final java.net.http.HttpClient client = java.net.http.HttpClient.newBuilder()\n .connectTimeout(java.time.Duration.ofSeconds(5)).build();\n private final com.fasterxml.jackson.databind.ObjectMapper json = new com.fasterxml.jackson.databind.ObjectMapper();\n\n @Value(\"\\${AGENT_HUB_API_KEY}\") private String apiKey;\n @Value(\"\\${AGENT_HUB_AGENT_ID}\") private int agentId;\n @Value(\"\\${AGENT_HUB_BACKEND_URL}\") private String agentHubUrl;\n\n @PostMapping(\"/api/agent-chat/token\")\n public ResponseEntity<String> token(@RequestBody Map<String, Object> request,\n org.springframework.security.core.Authentication authentication) throws Exception {\n if (!Integer.valueOf(agentId).equals(request.get(\"agentId\")))\n return ResponseEntity.badRequest().cacheControl(CacheControl.noStore()).build();\n Map<String, Object> payload = new java.util.HashMap<>();\n payload.put(\"apiKey\", apiKey); payload.put(\"agentId\", agentId);\n // Omit externalUserId for anonymous access; ignore anonymous security principals.\n if (authentication != null && authentication.isAuthenticated() &&\n !(authentication instanceof org.springframework.security.authentication.AnonymousAuthenticationToken))\n payload.put(\"externalUserId\", \"my-app:\" + authentication.getName());\n var upstreamRequest = java.net.http.HttpRequest.newBuilder()\n .uri(java.net.URI.create(agentHubUrl.replaceAll(\"/+$\", \"\") + \"/api/agent/api-keys/embedded/me\"))\n .timeout(java.time.Duration.ofSeconds(15)).header(\"Content-Type\", \"application/json\")\n .POST(java.net.http.HttpRequest.BodyPublishers.ofString(json.writeValueAsString(payload))).build();\n try {\n var upstream = client.send(upstreamRequest, java.net.http.HttpResponse.BodyHandlers.ofString());\n if (upstream.statusCode() != 200)\n return ResponseEntity.status(502).cacheControl(CacheControl.noStore()).build();\n return ResponseEntity.ok().cacheControl(CacheControl.noStore())\n .contentType(MediaType.APPLICATION_JSON).body(upstream.body());\n } catch (java.io.IOException | InterruptedException error) {\n if (error instanceof InterruptedException) Thread.currentThread().interrupt();\n return ResponseEntity.status(503).cacheControl(CacheControl.noStore()).build();\n }\n }\n}\n// Imports: org.springframework.beans.factory.annotation.Value, web.bind.annotation.*,\n// org.springframework.http.*, java.util.Map. Do not log the key or token response.`,\n dotnet: `// ASP.NET Core Minimal API. Configure an IP/user rate-limit policy in production.\n// Authentication can be optional (anonymous demo) or required by your app's policy.\n// Server environment: AGENT_HUB_API_KEY=...; AGENT_HUB_AGENT_ID=${agentId}\n${environmentNoteSlash}\nusing System.Security.Claims;\nusing System.Collections.Generic;\nusing System.Net.Http.Json;\n\nbuilder.Services.AddHttpClient(\"AgentHub\", client => client.Timeout = TimeSpan.FromSeconds(15));\napp.MapPost(\"/api/agent-chat/token\", async (AgentTokenRequest body, HttpContext context, IHttpClientFactory clients, IConfiguration config) => {\n context.Response.Headers.CacheControl = \"no-store\";\n if (!int.TryParse(config[\"AGENT_HUB_AGENT_ID\"], out var agentId) || agentId <= 0)\n return Results.StatusCode(503);\n var apiKey = config[\"AGENT_HUB_API_KEY\"];\n var baseUrl = config[\"AGENT_HUB_BACKEND_URL\"]?.TrimEnd('/');\n if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(baseUrl))\n return Results.StatusCode(503);\n if (body.AgentId != agentId)\n return Results.BadRequest(new { error = \"Agent is not configured for this application\" });\n var subject = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;\n var payload = new Dictionary<string, object?> { [\"apiKey\"] = apiKey, [\"agentId\"] = agentId };\n if (context.User.Identity?.IsAuthenticated == true && !string.IsNullOrEmpty(subject))\n payload[\"externalUserId\"] = \"my-app:\" + subject;\n try {\n var upstream = await clients.CreateClient(\"AgentHub\").PostAsJsonAsync(\n baseUrl + \"/api/agent/api-keys/embedded/me\", payload, context.RequestAborted);\n if (!upstream.IsSuccessStatusCode) return Results.StatusCode(502);\n return Results.Text(await upstream.Content.ReadAsStringAsync(context.RequestAborted), \"application/json\");\n } catch (HttpRequestException) { return Results.StatusCode(503); }\n}).AllowAnonymous(); // Replace with .RequireAuthorization() for login-only chat.\npublic sealed record AgentTokenRequest(int AgentId);\n// Imports: Microsoft.AspNetCore.Http, System.Net.Http.Json, System.Collections.Generic.\n// Add a distributed rate limiter and trusted-proxy configuration for public deployments.`,\n };\n}\n"]}