@maggioli-rd/aicore-agent-chat 1.0.1 → 1.1.1

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.
@@ -368,6 +368,10 @@ var AICORE_EVENTS = {
368
368
  /** Reopenings in a row without a new event before a cut stream is an error. */
369
369
  var RESUME_ATTEMPTS = 3;
370
370
  var RESUME_DELAY_MS = 1e3;
371
+ /** Page size of the agents and of the history. AI-CORE documents `limit` up
372
+ * to 200, but its gateway asks the agents service for `limit + 1`, past that
373
+ * service's own maximum of 200: 200 gets a 422 (api-gateway#44). */
374
+ var PAGE_LIMIT = "100";
371
375
  function apiBaseOf(baseUrl) {
372
376
  const trimmed = baseUrl.trim().replace(/\/+$/, "");
373
377
  return trimmed.endsWith("/api/v1") ? trimmed : `${trimmed}/api/v1`;
@@ -525,7 +529,7 @@ var AicoreChatClient = class extends EventTarget {
525
529
  if (error.kind === "tenant_refused") this.dispatchEvent(new CustomEvent(AICORE_EVENTS.tenantRefused, { detail: error }));
526
530
  }
527
531
  listAgents(cursor) {
528
- const query = new URLSearchParams({ limit: "200" });
532
+ const query = new URLSearchParams({ limit: PAGE_LIMIT });
529
533
  if (cursor) query.set("cursor", cursor);
530
534
  return this.#json(`/agents?${query.toString()}`);
531
535
  }
@@ -556,7 +560,7 @@ var AicoreChatClient = class extends EventTarget {
556
560
  const items = [];
557
561
  let cursor = null;
558
562
  do {
559
- const query = new URLSearchParams({ limit: "100" });
563
+ const query = new URLSearchParams({ limit: PAGE_LIMIT });
560
564
  if (cursor) query.set("cursor", cursor);
561
565
  const page = await this.#json(`/conversations/${encodeURIComponent(idConv)}/messages?${query.toString()}`);
562
566
  items.push(...page.items);
@@ -883,6 +887,28 @@ var AicoreChatSession = class extends EventTarget {
883
887
  });
884
888
  if (epoch === this.#epoch) this.#set({ loadingHistory: false });
885
889
  }
890
+ /** Gives `idConv` the title `title`, trimmed; an empty one is ignored. The
891
+ * list shows it at once, and the old title again if AI-CORE refuses it. */
892
+ async rename(idConv, title) {
893
+ const { agentId, conversations } = this.#state;
894
+ const value = title.trim();
895
+ const before = conversations.find((c) => c.id === idConv);
896
+ if (!agentId || !value || before?.title === value) return;
897
+ const current = this.#forAgent(agentId);
898
+ const patch = (change) => this.#update((s) => ({ conversations: s.conversations.map((c) => c.id === idConv ? {
899
+ ...c,
900
+ ...change(c)
901
+ } : c) }));
902
+ patch(() => ({ title: value }));
903
+ try {
904
+ const renamed = await this.client.renameConversation(idConv, value);
905
+ if (current()) patch(() => renamed);
906
+ } catch (err) {
907
+ if (!current()) return;
908
+ if (before) patch((c) => c.title === value ? { title: before.title } : null);
909
+ this.#set({ error: toAicoreError(err) });
910
+ }
911
+ }
886
912
  async remove(idConv) {
887
913
  const { agentId } = this.#state;
888
914
  if (!agentId) return;
@@ -968,8 +994,11 @@ var AicoreChatSession = class extends EventTarget {
968
994
  this.#update((s) => ({ files: s.files.filter((f) => f.id_file !== idFile) }));
969
995
  });
970
996
  }
971
- /** Sends `text` with the ready attachments and streams the answer. */
972
- async send(text) {
997
+ /** Sends `text` with the ready attachments and streams the answer.
998
+ * `context`: the data of the user's page for this turn only (see
999
+ * {@link SendOptions}). */
1000
+ async send(text, options = {}) {
1001
+ const { context } = options;
973
1002
  const { agentId, activeId, files, uploading } = this.#state;
974
1003
  const value = text.trim();
975
1004
  if (!agentId || this.busy || !value) return;
@@ -1003,7 +1032,8 @@ var AicoreChatSession = class extends EventTarget {
1003
1032
  idConv: activeId,
1004
1033
  request: {
1005
1034
  text: value,
1006
- ...ready.length > 0 ? { attachments: ready.map((f) => ({ id_file: f.id_file })) } : {}
1035
+ ...ready.length > 0 ? { attachments: ready.map((f) => ({ id_file: f.id_file })) } : {},
1036
+ ...context ? { context } : {}
1007
1037
  },
1008
1038
  signal: abort.signal,
1009
1039
  onConversation: (idConv) => {
@@ -1087,4 +1117,4 @@ var AicoreChatSession = class extends EventTarget {
1087
1117
  };
1088
1118
  export { parseBearerChallenge as C, kindOf as S, isRecord as T, jwtExpiry as _, messagesFromHistory as a, isAbortError as b, apiBaseOf as c, answerOf as d, foldTurn as f, decodeJwtClaims as g, TokenCache as h, RATING_UP as i, randomId as l, EXPIRY_SKEW_MS as m, CHAT_CHANGE as n, AICORE_EVENTS as o, turnErrorText as p, RATING_DOWN as r, AicoreChatClient as s, AicoreChatSession as t, EMPTY_TURN as u, AicoreError as v, toAicoreError as w, isInvalidToken as x, errorFromResponse as y };
1089
1119
 
1090
- //# sourceMappingURL=core-CdSjbHFC.js.map
1120
+ //# sourceMappingURL=core-Db3hnKpM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-Db3hnKpM.js","names":[],"sources":["../../src/core/record.ts","../../src/core/errors.ts","../../src/core/sse.ts","../../src/core/token.ts","../../src/core/turn.ts","../../src/core/client.ts","../../src/core/session.ts"],"sourcesContent":["/** A plain JSON object (not null, not an array). */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { isRecord } from \"./record\";\n\n/** Why a call failed, as a host needs to tell it apart. */\nexport type AicoreErrorKind =\n /** The token was refused even after a fresh one: the host must log in again. */\n | \"auth_required\"\n /** The token is valid but does not admit the tenant (400 `tenant_required`,\n * 403 `tenant_not_allowed` / `tenant_not_registered`). */\n | \"tenant_refused\"\n /** The token is bound to another agent (403 `insufficient_scope`). */\n | \"forbidden\"\n | \"not_found\"\n /** A turn is already running on the conversation (409). */\n | \"busy\"\n /** The conversation is disabled (423). */\n | \"locked\"\n | \"rate_limited\"\n | \"network\"\n | \"http\";\n\nexport interface AicoreErrorInit {\n status: number;\n message: string;\n errorCode?: string;\n requestId?: string;\n retryAfter?: number;\n /** `error_description` of `WWW-Authenticate`, for a refused token. */\n authDescription?: string;\n}\n\nexport class AicoreError extends Error {\n readonly status: number;\n readonly kind: AicoreErrorKind;\n readonly errorCode?: string;\n readonly requestId?: string;\n readonly retryAfter?: number;\n readonly authDescription?: string;\n\n constructor(init: AicoreErrorInit, kind?: AicoreErrorKind) {\n super(init.message || `HTTP ${init.status}`);\n this.name = \"AicoreError\";\n this.status = init.status;\n this.errorCode = init.errorCode;\n this.requestId = init.requestId;\n this.retryAfter = init.retryAfter;\n this.authDescription = init.authDescription;\n this.kind = kind ?? kindOf(init);\n }\n}\n\nconst TENANT_CODES = new Set([\n \"tenant_required\",\n \"tenant_not_allowed\",\n \"tenant_not_registered\",\n]);\n\nexport function kindOf({\n status,\n errorCode,\n}: AicoreErrorInit): AicoreErrorKind {\n if (status === 0) return \"network\";\n if (errorCode && TENANT_CODES.has(errorCode)) return \"tenant_refused\";\n if (status === 401) return \"auth_required\";\n if (status === 403) return \"forbidden\";\n if (status === 404) return \"not_found\";\n if (status === 409) return \"busy\";\n if (status === 423) return \"locked\";\n if (status === 429) return \"rate_limited\";\n return \"http\";\n}\n\n/** Any failure as an {@link AicoreError}: an unknown one reads as a network\n * failure. */\nexport function toAicoreError(err: unknown): AicoreError {\n return err instanceof AicoreError\n ? err\n : new AicoreError({ status: 0, message: String(err) });\n}\n\n/** The work was aborted on purpose (the user stopped or moved on). */\nexport function isAbortError(err: unknown, signal?: AbortSignal): boolean {\n return (\n (err instanceof DOMException && err.name === \"AbortError\") ||\n signal?.aborted === true\n );\n}\n\n/** `error` and `error_description` of a `WWW-Authenticate: Bearer …` header. */\nexport function parseBearerChallenge(header: string | null): {\n error?: string;\n description?: string;\n} {\n if (!header) return {};\n const param = (name: string) =>\n new RegExp(`${name}=\"([^\"]*)\"`).exec(header)?.[1];\n return { error: param(\"error\"), description: param(\"error_description\") };\n}\n\n/** A token the gateway refused as invalid (expired, wrong signature, …):\n * a fresh token may succeed. Any other 401/403 would fail the same way. */\nexport function isInvalidToken(res: Response): boolean {\n return (\n res.status === 401 &&\n parseBearerChallenge(res.headers.get(\"WWW-Authenticate\")).error ===\n \"invalid_token\"\n );\n}\n\n/** The failure a non-2xx response describes. The gateway's errors are\n * `{code, message, detail?, request_id?, error_code?}`; anything else (a\n * proxy's HTML page) leaves the status to speak alone. */\nexport async function errorFromResponse(res: Response): Promise<AicoreError> {\n const retry = res.headers.get(\"Retry-After\")?.trim();\n const init: AicoreErrorInit = {\n status: res.status,\n message: \"\",\n requestId: res.headers.get(\"X-Request-Id\") ?? undefined,\n retryAfter: retry && /^\\d+$/.test(retry) ? Number(retry) : undefined,\n authDescription: parseBearerChallenge(res.headers.get(\"WWW-Authenticate\"))\n .description,\n };\n try {\n const body: unknown = await res.json();\n if (isRecord(body)) {\n const parts: string[] = [];\n if (typeof body.message === \"string\" && body.message)\n parts.push(body.message);\n if (typeof body.detail === \"string\" && body.detail)\n parts.push(body.detail);\n init.message = [...new Set(parts)].join(\": \");\n if (typeof body.error_code === \"string\") init.errorCode = body.error_code;\n if (typeof body.request_id === \"string\") init.requestId = body.request_id;\n }\n } catch {\n // Not JSON: the status says it all.\n }\n return new AicoreError(init);\n}\n","// SSE framing over `fetch`: `EventSource` cannot send `Authorization`.\n// Ported from the AI-CORE console (webapp `src/api/sse.ts`).\n\n/** One whole event block, exactly as it came off the wire. */\nexport interface RawSseEvent {\n /** \"message\" when the block had no `event:` line, as the SSE spec says. */\n event: string;\n /** Every `data:` line of the block joined by \"\\n\". */\n data: string;\n /** Only the block's own `id:`: a keepalive must show that it has none,\n * since resuming from it is not possible. */\n id?: string;\n}\n\n/** Incremental SSE framing: feed it decoded text in any split. Lines end at\n * CRLF, LF or a lone CR; a blank line dispatches the block. */\nexport class SseFramer {\n #buffer = \"\";\n #event = \"\";\n #data: string[] = [];\n #id: string | undefined;\n // A chunk ending with \"\\r\" may be half of a CRLF: the \"\\n\" arriving with\n // the next chunk must not read as a second, blank line.\n #pendingCr = false;\n\n push(text: string): RawSseEvent[] {\n let input = text;\n if (this.#pendingCr && input.startsWith(\"\\n\")) input = input.slice(1);\n this.#pendingCr = false;\n this.#buffer += input;\n\n const out: RawSseEvent[] = [];\n const lineEnd = /\\r\\n|\\r|\\n/g;\n let start = 0;\n let match: RegExpExecArray | null;\n while ((match = lineEnd.exec(this.#buffer)) !== null) {\n if (match[0] === \"\\r\" && match.index === this.#buffer.length - 1) {\n this.#pendingCr = true;\n const event = this.#line(this.#buffer.slice(start, match.index));\n if (event) out.push(event);\n start = this.#buffer.length;\n break;\n }\n const event = this.#line(this.#buffer.slice(start, match.index));\n if (event) out.push(event);\n start = match.index + match[0].length;\n }\n this.#buffer = this.#buffer.slice(start);\n return out;\n }\n\n /** The stream ended. A block without its closing blank line is dropped:\n * a proxy timeout can cut a frame in half, and half an event is not one. */\n end(): void {\n this.#buffer = \"\";\n this.#reset();\n }\n\n #line(line: string): RawSseEvent | null {\n if (line === \"\") return this.#dispatch();\n if (line.startsWith(\":\")) return null;\n const colon = line.indexOf(\":\");\n const field = colon >= 0 ? line.slice(0, colon) : line;\n let value = colon >= 0 ? line.slice(colon + 1) : \"\";\n if (value.startsWith(\" \")) value = value.slice(1);\n if (field === \"event\") this.#event = value;\n else if (field === \"data\") this.#data.push(value);\n else if (field === \"id\" && !value.includes(\"\\0\")) this.#id = value;\n return null;\n }\n\n #dispatch(): RawSseEvent | null {\n if (this.#data.length === 0 && this.#event === \"\") {\n this.#reset();\n return null;\n }\n const event: RawSseEvent = {\n event: this.#event || \"message\",\n data: this.#data.join(\"\\n\"),\n };\n if (this.#id !== undefined) event.id = this.#id;\n this.#reset();\n return event;\n }\n\n #reset() {\n this.#event = \"\";\n this.#data = [];\n this.#id = undefined;\n }\n}\n\n/** Every whole event of `stream`. */\nexport async function* parseSseFrames(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<RawSseEvent> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n const framer = new SseFramer();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n const text = done\n ? decoder.decode()\n : decoder.decode(value, { stream: true });\n yield* framer.push(text);\n if (done) break;\n }\n framer.end();\n } finally {\n await reader.cancel().catch(() => reader.releaseLock());\n }\n}\n\n/** `data` as JSON, or `{ raw }` when it is not. */\nexport function dataOf(raw: RawSseEvent): unknown {\n try {\n return raw.data ? JSON.parse(raw.data) : {};\n } catch {\n return { raw: raw.data };\n }\n}\n","import { AicoreError } from \"./errors\";\nimport { isRecord } from \"./record\";\n\n/** The host's token source, the `getToken` property of `<aicore-agent-chat>`.\n * `retry` is true after AI-CORE refused the previous token: the host must not\n * hand back a cached one (Firebase: `getIdToken(true)`). It may answer\n * synchronously or with a promise; null means no signed-in user. */\nexport type GetToken = (options: {\n retry: boolean;\n}) => Promise<string | null | undefined> | string | null | undefined;\n\n/** A token is reused until this long before its `exp`. */\nexport const EXPIRY_SKEW_MS = 30_000;\n\nfunction base64UrlDecode(segment: string): string {\n const b64 = segment.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = b64 + \"=\".repeat((4 - (b64.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));\n return new TextDecoder().decode(bytes);\n}\n\n/** The JWT's claims, decoded and NOT verified: for timing and diagnostics\n * only. AI-CORE is the one that verifies the signature. */\nexport function decodeJwtClaims(token: string): Record<string, unknown> | null {\n const payload = token.split(\".\")[1];\n if (!payload) return null;\n try {\n const claims: unknown = JSON.parse(base64UrlDecode(payload));\n return isRecord(claims) ? claims : null;\n } catch {\n return null;\n }\n}\n\n/** `exp` in epoch milliseconds, or null when the token has none. */\nexport function jwtExpiry(token: string): number | null {\n const exp = decodeJwtClaims(token)?.exp;\n return typeof exp === \"number\" ? exp * 1000 : null;\n}\n\n/** Keeps the host's token in memory until shortly before it expires, and\n * shares one in-flight request among concurrent callers. */\nexport class TokenCache {\n readonly #getToken: GetToken;\n readonly #now: () => number;\n #token: string | null = null;\n #expiresAt = 0;\n #pending: Promise<string> | null = null;\n /** The in-flight request asked for a fresh token. */\n #pendingFresh = false;\n /** Bumped by every request and by `clear()`: only the newest answer is\n * cached, so a slow plain request never overwrites a fresher token. */\n #generation = 0;\n\n constructor(getToken: GetToken, now: () => number = Date.now) {\n this.#getToken = getToken;\n this.#now = now;\n }\n\n /** A token still valid for at least {@link EXPIRY_SKEW_MS}. */\n get(): Promise<string> {\n if (this.#token && this.#now() < this.#expiresAt - EXPIRY_SKEW_MS) {\n return Promise.resolve(this.#token);\n }\n return this.#fetch(false);\n }\n\n /** Drops the cached token and asks the host for a fresh one. Concurrent\n * refreshes (several calls refused at once) share one request. */\n refresh(): Promise<string> {\n this.#token = null;\n this.#expiresAt = 0;\n return this.#fetch(true);\n }\n\n /** Forgets the cached token, e.g. when the host's user may have changed. */\n clear(): void {\n this.#token = null;\n this.#expiresAt = 0;\n this.#pending = null;\n this.#pendingFresh = false;\n this.#generation++;\n }\n\n #fetch(fresh: boolean): Promise<string> {\n // A refresh must not ride on a plain request already in flight: that one\n // may return the very token AI-CORE just refused.\n if (this.#pending && (this.#pendingFresh || !fresh)) return this.#pending;\n const generation = ++this.#generation;\n const pending = Promise.resolve()\n .then(() => this.#getToken({ retry: fresh }))\n .then((token) => {\n if (!token) {\n throw new AicoreError(\n { status: 401, message: \"No token available for the user\" },\n \"auth_required\",\n );\n }\n if (generation === this.#generation) {\n this.#token = token;\n // A token without `exp` is not cached: the host decides every time.\n this.#expiresAt = jwtExpiry(token) ?? 0;\n }\n return token;\n })\n .finally(() => {\n if (this.#pending === pending) {\n this.#pending = null;\n this.#pendingFresh = false;\n }\n });\n this.#pending = pending;\n this.#pendingFresh = fresh;\n return pending;\n }\n}\n","// What a turn of the agents stream has said so far. Same folding rules as the\n// AI-CORE console (webapp `src/api/agentTurn.ts`), so every client of the\n// stream shows a turn the same way.\nimport { isRecord } from \"./record\";\nimport { type Source } from \"./types\";\n\nexport interface TurnError {\n code: number;\n /** The server's sentence; absent when the `error` event had none. */\n message?: string;\n /** e.g. `model_context_overflow`. */\n errorCode?: string;\n /** The model provider's own sentence, when it failed. */\n detail?: string;\n /** The turn's trace id, to quote when reporting the error. */\n traceId?: string;\n}\n\nexport interface TurnState {\n /** The `token` texts, joined. */\n text: string;\n /** The `result` payload: structured or status turns send one, no tokens. */\n result: unknown;\n sources: Source[];\n /** The last informative `nop` message (\"Sto usando lo strumento…\"). */\n activity: string | null;\n /** The conversation title the agent proposed, when it sent one. */\n title: string | null;\n error: TurnError | null;\n /** `done` arrived. */\n finished: boolean;\n}\n\nexport const EMPTY_TURN: TurnState = {\n text: \"\",\n result: null,\n sources: [],\n activity: null,\n title: null,\n error: null,\n finished: false,\n};\n\nconst fieldsOf = (data: unknown): Record<string, unknown> =>\n isRecord(data) ? data : {};\n\n/** One event applied to the turn. Unknown kinds change nothing, as the\n * contract asks: new kinds arrive without a version bump. */\nexport function foldTurn(\n turn: TurnState,\n kind: string,\n data: unknown,\n): TurnState {\n const fields = fieldsOf(data);\n const text = (key: string): string | undefined => {\n const value = fields[key];\n return typeof value === \"string\" && value ? value : undefined;\n };\n switch (kind) {\n case \"token\":\n return typeof fields.text === \"string\"\n ? { ...turn, text: turn.text + fields.text }\n : turn;\n // The turn moved to another replica, which repeats the cut step: the\n // tokens that follow restate the answer from the start.\n case \"truncate\":\n return { ...turn, text: \"\" };\n case \"result\":\n return { ...turn, result: fields.payload ?? null };\n case \"context\":\n return {\n ...turn,\n sources: Array.isArray(fields.context)\n ? (fields.context as Source[])\n : [],\n };\n case \"title\":\n return { ...turn, title: text(\"title\") ?? turn.title };\n case \"nop\":\n return text(\"message\") ? { ...turn, activity: text(\"message\")! } : turn;\n case \"error\": {\n const errorCode = text(\"error_code\");\n const detail = text(\"detail\");\n const traceId = text(\"trace_id\");\n return {\n ...turn,\n error: {\n code: typeof fields.code === \"number\" ? fields.code : 500,\n ...(text(\"message\") ? { message: text(\"message\") } : {}),\n ...(errorCode ? { errorCode } : {}),\n ...(detail ? { detail } : {}),\n ...(traceId ? { traceId } : {}),\n },\n };\n }\n case \"done\":\n return { ...turn, finished: true, activity: null };\n default:\n return turn;\n }\n}\n\n/** The answer as chat content: the text, or else the result. A status turn's\n * payload `{\"text\": \"…\"}` reads as text; any other shows as a JSON block. */\nexport function answerOf({\n text,\n result,\n}: Pick<TurnState, \"text\" | \"result\">): string {\n if (text || result === null || result === undefined) return text;\n if (\n typeof result === \"object\" &&\n !Array.isArray(result) &&\n Object.keys(result).length === 1 &&\n \"text\" in result &&\n typeof result.text === \"string\"\n ) {\n return result.text;\n }\n return \"```json\\n\" + JSON.stringify(result, null, 2) + \"\\n```\";\n}\n\n/** An error as the user reads it: message, provider detail, trace. The\n * labels default to English; `<aicore-agent-chat>` passes its language's. */\nexport function turnErrorText(\n { message, detail, traceId }: TurnError,\n labels: { failed?: string; trace?: (traceId: string) => string } = {},\n): string {\n const {\n failed = \"The agent could not answer.\",\n trace = (id) => `Trace ${id}`,\n } = labels;\n const lines = [message ?? failed];\n if (detail) lines.push(detail);\n if (traceId && !message?.includes(traceId)) lines.push(trace(traceId));\n return lines.join(\"\\n\");\n}\n","import {\n AicoreError,\n errorFromResponse,\n isAbortError,\n isInvalidToken,\n toAicoreError,\n} from \"./errors\";\nimport { dataOf, parseSseFrames } from \"./sse\";\nimport { decodeJwtClaims, type GetToken, TokenCache } from \"./token\";\nimport { EMPTY_TURN, foldTurn, type TurnState } from \"./turn\";\nimport {\n type AgentSummary,\n type ConversationFile,\n type ConversationSummary,\n type HistoryMessage,\n type OpenedConversation,\n type Page,\n type SendMessageRequest,\n type SendMessageResponse,\n type TurnEvent,\n} from \"./types\";\n\n/** DOM events of `<aicore-agent-chat>`. The client\n * dispatches them on itself; the web component re-dispatches them. */\nexport const AICORE_EVENTS = {\n conversation: \"aicore-conversation\",\n turn: \"aicore-turn\",\n error: \"aicore-error\",\n authRequired: \"aicore-auth-required\",\n tenantRefused: \"aicore-tenant-refused\",\n} as const;\n\nexport interface ConversationEventDetail {\n /** null: `<aicore-agent-chat>` shows a blank conversation, which AI-CORE\n * opens with its first message. The client always sends an id. */\n idConv: string | null;\n idAgent: string;\n}\n\nexport interface TurnEventDetail {\n idConv: string;\n idQuery: string;\n turn: TurnState;\n}\n\n/** One HTTP exchange, for a host's diagnostics. Never carries the token. */\nexport interface RequestLogEntry {\n method: string;\n path: string;\n status: number;\n requestId?: string;\n durationMs: number;\n /** The first attempt got 401 `invalid_token` and this is the retry. */\n retriedWithFreshToken: boolean;\n}\n\nexport interface AicoreChatClientOptions {\n /** AI-CORE origin (`https://aicore-test.maggioliresearch.net`), with or\n * without the `/api/v1` suffix. */\n baseUrl: string;\n getToken: GetToken;\n /** Needed when the token admits more than one tenant: only the host page\n * knows which workspace is open. Sent as `X-Tenant`. */\n tenant?: string | null;\n onRequest?: (entry: RequestLogEntry) => void;\n /** The user behind the token (`sub`) is not the one of the previous token:\n * whatever was read for the previous user must go. */\n onIdentityChange?: () => void;\n fetch?: typeof fetch;\n}\n\ninterface CallOptions {\n method?: string;\n body?: unknown;\n form?: FormData;\n signal?: AbortSignal;\n accept?: string;\n idempotent?: boolean;\n lastEventId?: string;\n /** false: the caller may recover, and reports the failure itself. */\n report?: boolean;\n}\n\n/** Reopenings in a row without a new event before a cut stream is an error. */\nconst RESUME_ATTEMPTS = 3;\nconst RESUME_DELAY_MS = 1000;\n/** Page size of the agents and of the history. AI-CORE documents `limit` up\n * to 200, but its gateway asks the agents service for `limit + 1`, past that\n * service's own maximum of 200: 200 gets a 422 (api-gateway#44). */\nconst PAGE_LIMIT = \"100\";\n\nexport function apiBaseOf(baseUrl: string): string {\n const trimmed = baseUrl.trim().replace(/\\/+$/, \"\");\n return trimmed.endsWith(\"/api/v1\") ? trimmed : `${trimmed}/api/v1`;\n}\n\n/** A random UUID v4. `crypto.randomUUID` exists only in secure contexts\n * (HTTPS, localhost); an intranet host on plain HTTP still has\n * `getRandomValues`. */\nexport function randomId(): string {\n if (typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nconst transient = (err: unknown) =>\n err instanceof AicoreError && (err.status === 0 || err.status >= 502);\n\nfunction pause(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) return resolve();\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n resolve();\n },\n { once: true },\n );\n });\n}\n\n/**\n * Browser client of the AI-CORE agents API on the token lane: the page sends\n * its user's JWT (`Authorization: Bearer`), no API key, no proxy. Framework\n * agnostic on purpose: it is the transport of `<aicore-agent-chat>`, and a\n * host can build its own interface on it.\n */\nexport class AicoreChatClient extends EventTarget {\n readonly apiBase: string;\n tenant: string | null;\n readonly #tokens: TokenCache;\n readonly #fetch: typeof fetch;\n readonly #onRequest?: (entry: RequestLogEntry) => void;\n readonly #onIdentityChange?: () => void;\n /** `sub` of the last token (null: it had none); undefined until the first. */\n #subject: string | null | undefined;\n #lastToken: string | null = null;\n\n constructor(options: AicoreChatClientOptions) {\n super();\n this.apiBase = apiBaseOf(options.baseUrl);\n this.tenant = options.tenant ?? null;\n this.#tokens = new TokenCache(options.getToken);\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#onRequest = options.onRequest;\n this.#onIdentityChange = options.onIdentityChange;\n }\n\n /** Forgets the cached token: the next call asks the host again. */\n clearToken(): void {\n this.#tokens.clear();\n }\n\n /** Asks the host for a token now and reports a different user through\n * `onIdentityChange`. A host with no token is left to the next call. */\n async checkIdentity(): Promise<void> {\n try {\n await this.#token(false);\n } catch {\n // No token: the next call reports `aicore-auth-required`.\n }\n }\n\n // ---- transport -------------------------------------------------------\n\n #init(token: string, options: CallOptions, idempotencyKey?: string) {\n const headers = new Headers({\n Accept: options.accept ?? \"application/json\",\n Authorization: `Bearer ${token}`,\n });\n if (this.tenant) headers.set(\"X-Tenant\", this.tenant);\n if (options.body !== undefined)\n headers.set(\"Content-Type\", \"application/json\");\n if (idempotencyKey) headers.set(\"Idempotency-Key\", idempotencyKey);\n if (options.lastEventId) headers.set(\"Last-Event-ID\", options.lastEventId);\n return {\n method: options.method ?? \"GET\",\n headers,\n body:\n options.form ??\n (options.body === undefined ? undefined : JSON.stringify(options.body)),\n // The token travels in the header only; the gateway's CORS has no credentials.\n credentials: \"omit\",\n // A response carrying a tenant's data has no business in the HTTP cache.\n cache: \"no-store\",\n signal: options.signal,\n } satisfies RequestInit;\n }\n\n async #send(path: string, init: RequestInit, retried: boolean) {\n const started = performance.now();\n let res: Response;\n try {\n res = await this.#fetch(this.apiBase + path, init);\n } catch (err) {\n if (isAbortError(err, init.signal ?? undefined)) throw err;\n this.#log(init, path, 0, started, retried);\n throw new AicoreError({\n status: 0,\n message: \"AI-CORE unreachable\",\n });\n }\n this.#log(init, path, res.status, started, retried, res);\n return res;\n }\n\n #log(\n init: RequestInit,\n path: string,\n status: number,\n started: number,\n retried: boolean,\n res?: Response,\n ) {\n this.#onRequest?.({\n method: init.method ?? \"GET\",\n path,\n status,\n requestId: res?.headers.get(\"X-Request-Id\") ?? undefined,\n durationMs: Math.round(performance.now() - started),\n retriedWithFreshToken: retried,\n });\n }\n\n /** A token from the host. A host that cannot give one (login expired,\n * refresh refused) means a login to redo, never a network failure. */\n async #token(fresh: boolean): Promise<string> {\n let token: string;\n try {\n token = await (fresh ? this.#tokens.refresh() : this.#tokens.get());\n } catch (err) {\n if (err instanceof AicoreError) throw err;\n throw new AicoreError(\n {\n status: 0,\n message: `No token available: ${err instanceof Error ? err.message : String(err)}`,\n },\n \"auth_required\",\n );\n }\n const sub = decodeJwtClaims(token)?.sub;\n const subject = typeof sub === \"string\" && sub !== \"\" ? sub : null;\n // Fails closed: when either token has no `sub`, any other token counts\n // as another user.\n const changed =\n this.#subject !== undefined &&\n (subject === null || this.#subject === null\n ? token !== this.#lastToken\n : subject !== this.#subject);\n this.#subject = subject;\n this.#lastToken = token;\n if (changed) this.#onIdentityChange?.();\n return token;\n }\n\n /** One call. A 401 `invalid_token` gets one retry with a fresh token, then\n * `aicore-auth-required`. Any failure is thrown as an {@link AicoreError}\n * and, unless `report` is false, dispatched as `aicore-error`. */\n async #call(path: string, options: CallOptions = {}): Promise<Response> {\n // The same key on the retry: the gateway answers a replay, never a duplicate.\n const idempotencyKey = options.idempotent ? randomId() : undefined;\n try {\n let token = await this.#token(false);\n let res = await this.#send(\n path,\n this.#init(token, options, idempotencyKey),\n false,\n );\n if (isInvalidToken(res)) {\n token = await this.#token(true);\n res = await this.#send(\n path,\n this.#init(token, options, idempotencyKey),\n true,\n );\n }\n if (!res.ok) throw await errorFromResponse(res);\n return res;\n } catch (err) {\n if (isAbortError(err, options.signal)) throw err;\n const error = toAicoreError(err);\n if (options.report !== false) this.#report(error);\n throw error;\n }\n }\n\n async #json<T>(path: string, options?: CallOptions): Promise<T> {\n const res = await this.#call(path, options);\n return (await res.json()) as T;\n }\n\n #report(error: AicoreError) {\n this.dispatchEvent(new CustomEvent(AICORE_EVENTS.error, { detail: error }));\n if (error.kind === \"auth_required\")\n this.dispatchEvent(\n new CustomEvent(AICORE_EVENTS.authRequired, { detail: error }),\n );\n if (error.kind === \"tenant_refused\")\n this.dispatchEvent(\n new CustomEvent(AICORE_EVENTS.tenantRefused, { detail: error }),\n );\n }\n\n // ---- REST ------------------------------------------------------------\n\n listAgents(cursor?: string): Promise<Page<AgentSummary>> {\n const query = new URLSearchParams({ limit: PAGE_LIMIT });\n if (cursor) query.set(\"cursor\", cursor);\n return this.#json(`/agents?${query.toString()}`);\n }\n\n getAgent(idAgent: string): Promise<AgentSummary> {\n return this.#json(`/agents/${encodeURIComponent(idAgent)}`);\n }\n\n listConversations(\n idAgent: string,\n cursor?: string,\n ): Promise<Page<ConversationSummary>> {\n const query = new URLSearchParams({ id_agent: idAgent, limit: \"50\" });\n if (cursor) query.set(\"cursor\", cursor);\n return this.#json(`/conversations?${query.toString()}`);\n }\n\n async openConversation(idAgent: string): Promise<OpenedConversation> {\n const opened = await this.#json<OpenedConversation>(\n `/agents/${encodeURIComponent(idAgent)}/conversations`,\n { method: \"POST\", idempotent: true },\n );\n this.dispatchEvent(\n new CustomEvent<ConversationEventDetail>(AICORE_EVENTS.conversation, {\n detail: { idConv: opened.id_conv, idAgent },\n }),\n );\n return opened;\n }\n\n /** The whole history, oldest first. */\n async history(idConv: string): Promise<HistoryMessage[]> {\n const items: HistoryMessage[] = [];\n let cursor: string | null = null;\n do {\n const query = new URLSearchParams({ limit: PAGE_LIMIT });\n if (cursor) query.set(\"cursor\", cursor);\n const page: Page<HistoryMessage> = await this.#json(\n `/conversations/${encodeURIComponent(idConv)}/messages?${query.toString()}`,\n );\n items.push(...page.items);\n cursor = page.next_cursor;\n } while (cursor);\n return items;\n }\n\n renameConversation(\n idConv: string,\n title: string,\n ): Promise<ConversationSummary> {\n return this.#json(`/conversations/${encodeURIComponent(idConv)}`, {\n method: \"PATCH\",\n body: { title },\n });\n }\n\n async deleteConversation(idConv: string): Promise<void> {\n await this.#call(`/conversations/${encodeURIComponent(idConv)}`, {\n method: \"DELETE\",\n });\n }\n\n sendMessage(\n idConv: string,\n request: SendMessageRequest,\n ): Promise<SendMessageResponse> {\n return this.#json(`/conversations/${encodeURIComponent(idConv)}/messages`, {\n method: \"POST\",\n body: request,\n idempotent: true,\n });\n }\n\n uploadFile(idConv: string, file: File): Promise<ConversationFile> {\n const form = new FormData();\n form.append(\"file\", file, file.name);\n return this.#json(`/conversations/${encodeURIComponent(idConv)}/files`, {\n method: \"POST\",\n form,\n });\n }\n\n listFiles(idConv: string): Promise<ConversationFile[]> {\n return this.#json(`/conversations/${encodeURIComponent(idConv)}/files`);\n }\n\n async deleteFile(idConv: string, idFile: string): Promise<void> {\n await this.#call(\n `/conversations/${encodeURIComponent(idConv)}/files/${encodeURIComponent(idFile)}`,\n { method: \"DELETE\" },\n );\n }\n\n async sendFeedback(\n idConv: string,\n idQuery: string,\n rating: number,\n text?: string,\n ): Promise<void> {\n await this.#call(\n `/conversations/${encodeURIComponent(idConv)}/messages/${encodeURIComponent(idQuery)}/feedback`,\n { method: \"PUT\", body: text ? { rating, text } : { rating } },\n );\n }\n\n // ---- stream ----------------------------------------------------------\n\n /** The events of one turn, until `done`. A stream cut before `done` is\n * reopened with `Last-Event-ID` and goes on after the last event it\n * delivered. An abort ends it quietly. Closing the stream does NOT stop the\n * turn on the server (there is no cancel route yet: agents#66). It does not\n * dispatch `aicore-error`: a reopening may fail and the next one succeed,\n * and a 410 is recovered by {@link ask}, which reports the rest. */\n async *streamTurn(\n idConv: string,\n idQuery: string,\n signal?: AbortSignal,\n ): AsyncGenerator<TurnEvent> {\n const path = `/conversations/${encodeURIComponent(idConv)}/stream?id_query=${encodeURIComponent(idQuery)}`;\n let lastId: string | undefined;\n let failures = 0;\n for (let reopening = false; ; reopening = true) {\n const from = lastId;\n let res: Response | null = null;\n try {\n res = await this.#call(path, {\n signal,\n accept: \"text/event-stream\",\n lastEventId: lastId,\n report: false,\n });\n } catch (err) {\n if (isAbortError(err, signal)) return;\n // The outage that cut the stream can refuse the reopening for a while.\n if (!reopening || !transient(err)) throw err;\n }\n\n if (res?.body) {\n try {\n for await (const raw of parseSseFrames(res.body)) {\n if (raw.id !== undefined) lastId = raw.id;\n yield { kind: raw.event, data: dataOf(raw), id: raw.id };\n if (raw.event === \"done\") return;\n }\n } catch (err) {\n if (isAbortError(err, signal)) return;\n }\n }\n\n if (lastId !== from) failures = 0;\n if (++failures > RESUME_ATTEMPTS) {\n throw new AicoreError({\n status: 0,\n message: \"Connection lost while streaming\",\n });\n }\n await pause(RESUME_DELAY_MS * 2 ** (failures - 1), signal);\n if (signal?.aborted) return;\n }\n }\n\n /**\n * One user turn end to end: opens the conversation when there is none,\n * posts the message, follows the stream and folds it. `onUpdate` sees every\n * intermediate state. A stream that is gone (410) is recovered from the\n * history: the message is never sent twice.\n */\n async ask(params: {\n idAgent: string;\n idConv?: string | null;\n request: SendMessageRequest;\n signal?: AbortSignal;\n onUpdate?: (turn: TurnState, event: TurnEvent) => void;\n /** Called once the conversation exists, before the turn starts. */\n onConversation?: (idConv: string) => void;\n }): Promise<{ idConv: string; idQuery: string; turn: TurnState }> {\n // Not aborted by `signal`: once sent, the server may already have taken\n // the message, and its `id_query` keeps the transcript tied to the turn.\n // A stop only skips the stream.\n const idConv =\n params.idConv ?? (await this.openConversation(params.idAgent)).id_conv;\n params.onConversation?.(idConv);\n const { id_query: idQuery } = await this.sendMessage(\n idConv,\n params.request,\n );\n\n let turn = EMPTY_TURN;\n let gone = false;\n try {\n for await (const event of this.streamTurn(\n idConv,\n idQuery,\n params.signal,\n )) {\n turn = foldTurn(turn, event.kind, event.data);\n params.onUpdate?.(turn, event);\n }\n } catch (err) {\n // The events expired (as an HTTP status rather than an `error` event):\n // recovered below, so not an error for the host.\n if (err instanceof AicoreError && err.status === 410) gone = true;\n else {\n if (err instanceof AicoreError) this.#report(err);\n throw err;\n }\n }\n\n if (gone || turn.error?.code === 410)\n turn = await this.#recover(idConv, idQuery);\n\n this.dispatchEvent(\n new CustomEvent<TurnEventDetail>(AICORE_EVENTS.turn, {\n detail: { idConv, idQuery, turn },\n }),\n );\n return { idConv, idQuery, turn };\n }\n\n /** The answer of a turn whose events expired, read from the history. */\n async #recover(idConv: string, idQuery: string): Promise<TurnState> {\n const messages = await this.history(idConv);\n const answer = messages.find(\n (m) => m.role === \"assistant\" && m.id_query === idQuery,\n );\n return {\n ...EMPTY_TURN,\n text: answer?.content ?? \"\",\n sources: answer?.sources ?? [],\n finished: true,\n };\n }\n}\n","import {\n AicoreChatClient,\n type AicoreChatClientOptions,\n type RequestLogEntry,\n} from \"./client\";\nimport { type AicoreError, isAbortError, toAicoreError } from \"./errors\";\nimport { answerOf, EMPTY_TURN, type TurnError, type TurnState } from \"./turn\";\nimport {\n type AgentSummary,\n type ConversationFile,\n type ConversationSummary,\n type HistoryMessage,\n type MessageAttachment,\n type Source,\n} from \"./types\";\n\nexport type ChatMessage =\n | { role: \"user\"; text: string; attachments: MessageAttachment[] }\n | {\n role: \"assistant\";\n text: string;\n sources: Source[];\n idQuery: string | null;\n error: TurnError | null;\n /** 0–5, as `PUT …/feedback` takes it; null until rated. */\n rating: number | null;\n /** The user stopped reading the stream before `done`. */\n interrupted: boolean;\n };\n\n/** A turn event for the developer panel. `token` events are only counted. */\nexport interface TraceEvent {\n at: number;\n kind: string;\n id?: string;\n data: unknown;\n}\n\nexport interface ChatState {\n agentId: string | null;\n agent: AgentSummary | null;\n conversations: ConversationSummary[];\n conversationsLoading: boolean;\n /** The list could not be read (the reason is in `error`). */\n conversationsFailed: boolean;\n activeId: string | null;\n messages: ChatMessage[];\n /** The turn being streamed; null between turns. */\n turn: TurnState | null;\n /** When the last turn was sent: the developer panel's time origin. */\n turnStartedAt: number | null;\n loadingHistory: boolean;\n error: AicoreError | null;\n /** Files attached to the open conversation and not sent yet. */\n files: ConversationFile[];\n /** Uploads in flight: a message waits for them. */\n uploading: number;\n requests: RequestLogEntry[];\n events: TraceEvent[];\n tokens: number;\n}\n\nexport interface SendOptions {\n /** The data of the page the user is on (the open record, the chosen\n * period), sent as the message's `context`: the agent's prompt reads it as\n * `{{context.key}}`. For this turn only: AI-CORE does not keep it. A JSON\n * object of at most 16 384 bytes, each value the prompt reads at most\n * 2 048; it authorises nothing and shows in the agent's traces. */\n context?: Record<string, unknown> | null;\n}\n\nexport const CHAT_CHANGE = \"change\";\n\n/** The ratings a thumb gives (`PUT …/feedback` takes 0–5). */\nexport const RATING_UP = 5;\nexport const RATING_DOWN = 1;\n\nconst MAX_LOG = 50;\nconst FILE_POLL_MS = 1500;\nconst FILE_POLL_MAX = 60;\n\nconst INITIAL: ChatState = {\n agentId: null,\n agent: null,\n conversations: [],\n conversationsLoading: false,\n conversationsFailed: false,\n activeId: null,\n messages: [],\n turn: null,\n turnStartedAt: null,\n loadingHistory: false,\n error: null,\n files: [],\n uploading: 0,\n requests: [],\n events: [],\n tokens: 0,\n};\n\nconst keep = <T>(list: T[], item: T) => [item, ...list].slice(0, MAX_LOG);\n\nconst ratingOf = (feedback: HistoryMessage[\"feedback\"]) =>\n typeof feedback?.rating === \"number\" ? feedback.rating : null;\n\nexport function messagesFromHistory(items: HistoryMessage[]): ChatMessage[] {\n return items.map((m) =>\n m.role === \"user\"\n ? { role: \"user\", text: m.content, attachments: m.attachments ?? [] }\n : {\n role: \"assistant\",\n text: m.content,\n sources: m.sources ?? [],\n idQuery: m.id_query ?? null,\n error: null,\n rating: ratingOf(m.feedback),\n interrupted: false,\n },\n );\n}\n\n/**\n * One agent chat: conversations, history, the streamed turn, attachments,\n * feedback and the developer log, as an observable state. Framework\n * agnostic: `<aicore-agent-chat>` renders it, and a React wrapper can\n * subscribe to the same `change` event.\n */\nexport class AicoreChatSession extends EventTarget {\n readonly client: AicoreChatClient;\n #state: ChatState = INITIAL;\n /** Bumped by every switch of conversation or agent: an answer of an older\n * epoch arrives too late and is dropped. */\n #epoch = 0;\n /** The send in flight, from the question until its last state update. */\n #abort: AbortController | null = null;\n /** Bumped when the host's user changes: a list or agent read with the\n * previous user's token arrives too late and is dropped. */\n #identity = 0;\n /** The conversation being opened for an upload, shared by concurrent ones. */\n #opening: { epoch: number; promise: Promise<string> } | null = null;\n\n constructor(\n options: Omit<AicoreChatClientOptions, \"onRequest\" | \"onIdentityChange\">,\n ) {\n super();\n this.client = new AicoreChatClient({\n ...options,\n onRequest: (entry) =>\n this.#update((s) => ({ requests: keep(s.requests, entry) })),\n onIdentityChange: () => this.#identityChanged(),\n });\n }\n\n get state(): ChatState {\n return this.#state;\n }\n\n /** A message is being sent, streamed or recorded: another one must wait,\n * and switching conversation would abort it. */\n get busy(): boolean {\n return this.#abort !== null;\n }\n\n #update(patch: (state: ChatState) => Partial<ChatState>) {\n this.#state = { ...this.#state, ...patch(this.#state) };\n this.dispatchEvent(new Event(CHAT_CHANGE));\n }\n\n #set(patch: Partial<ChatState>) {\n this.#update(() => patch);\n }\n\n /** `run`, keeping its failure as the visible error unless the user moved\n * on meanwhile (`current` false). */\n async #guard(current: () => boolean, run: () => Promise<void>) {\n try {\n await run();\n } catch (err) {\n if (!isAbortError(err) && current())\n this.#set({ error: toAicoreError(err) });\n }\n }\n\n #inEpoch(epoch = this.#epoch) {\n return () => epoch === this.#epoch;\n }\n\n #forAgent(agentId: string) {\n const identity = this.#identity;\n return () => this.#state.agentId === agentId && identity === this.#identity;\n }\n\n #clearConversation() {\n this.#abort?.abort();\n this.#abort = null;\n this.#opening = null;\n this.#epoch++;\n this.#set({\n activeId: null,\n messages: [],\n turn: null,\n turnStartedAt: null,\n loadingHistory: false,\n files: [],\n uploading: 0,\n error: null,\n });\n }\n\n /** Another user signed in on the host: nothing of the previous one stays. */\n #identityChanged() {\n this.#identity++;\n this.#clearConversation();\n // The developer log too: it lists the previous user's conversations.\n this.#set({\n conversations: [],\n conversationsFailed: false,\n conversationsLoading: false,\n requests: [],\n events: [],\n tokens: 0,\n });\n void this.refreshConversations();\n }\n\n // ---- agent and conversations -------------------------------------------\n\n /** Shows `agentId`'s chat: its details and its conversations. */\n async setAgent(agentId: string | null): Promise<void> {\n if (agentId === this.#state.agentId) return;\n this.#clearConversation();\n this.#set({\n agentId,\n agent: null,\n conversations: [],\n conversationsFailed: false,\n });\n if (!agentId) return;\n // Bound to the agent, not to the epoch: opening a conversation meanwhile\n // must not drop the agent's details.\n const current = this.#forAgent(agentId);\n await Promise.all([\n this.#guard(current, async () => {\n const agent = await this.client.getAgent(agentId);\n if (current()) this.#set({ agent });\n }),\n this.refreshConversations(),\n ]);\n }\n\n async refreshConversations(): Promise<void> {\n const { agentId } = this.#state;\n if (!agentId) return;\n const current = this.#forAgent(agentId);\n this.#set({ conversationsLoading: true });\n let failed = true;\n await this.#guard(current, async () => {\n const page = await this.client.listConversations(agentId);\n failed = false;\n if (!current()) return;\n this.#set({\n conversations: [...page.items].sort(\n (a, b) => b.last_message_at - a.last_message_at,\n ),\n });\n });\n if (current())\n this.#set({ conversationsLoading: false, conversationsFailed: failed });\n }\n\n /** A blank conversation: AI-CORE opens it with the first message. */\n newConversation(): void {\n this.#clearConversation();\n }\n\n /** Opens an existing conversation and reads its history. */\n async open(idConv: string): Promise<void> {\n if (idConv === this.#state.activeId) return;\n this.#clearConversation();\n const epoch = this.#epoch;\n this.#set({ activeId: idConv, loadingHistory: true });\n await this.#guard(this.#inEpoch(epoch), async () => {\n const history = await this.client.history(idConv);\n if (epoch === this.#epoch)\n this.#set({ messages: messagesFromHistory(history) });\n });\n if (epoch === this.#epoch) this.#set({ loadingHistory: false });\n }\n\n /** Gives `idConv` the title `title`, trimmed; an empty one is ignored. The\n * list shows it at once, and the old title again if AI-CORE refuses it. */\n async rename(idConv: string, title: string): Promise<void> {\n const { agentId, conversations } = this.#state;\n const value = title.trim();\n const before = conversations.find((c) => c.id === idConv);\n if (!agentId || !value || before?.title === value) return;\n const current = this.#forAgent(agentId);\n const patch = (\n change: (c: ConversationSummary) => Partial<ConversationSummary> | null,\n ) =>\n this.#update((s) => ({\n conversations: s.conversations.map((c) =>\n c.id === idConv ? { ...c, ...change(c) } : c,\n ),\n }));\n patch(() => ({ title: value }));\n try {\n const renamed = await this.client.renameConversation(idConv, value);\n if (current()) patch(() => renamed);\n } catch (err) {\n if (!current()) return;\n // Unless a fresher list arrived meanwhile.\n if (before)\n patch((c) => (c.title === value ? { title: before.title } : null));\n this.#set({ error: toAicoreError(err) });\n }\n }\n\n async remove(idConv: string): Promise<void> {\n const { agentId } = this.#state;\n if (!agentId) return;\n await this.#guard(this.#forAgent(agentId), async () => {\n await this.client.deleteConversation(idConv);\n if (idConv === this.#state.activeId) this.#clearConversation();\n this.#update((s) => ({\n conversations: s.conversations.filter((c) => c.id !== idConv),\n }));\n });\n }\n\n // ---- attachments -------------------------------------------------------\n\n /** The open conversation, opened now when there is none: an upload needs\n * one. Uploads started together share the same opening. */\n #ensureConversation(agentId: string): Promise<string> {\n if (this.#state.activeId) return Promise.resolve(this.#state.activeId);\n const epoch = this.#epoch;\n if (this.#opening?.epoch === epoch) return this.#opening.promise;\n const promise = this.client.openConversation(agentId).then((opened) => {\n // The user opened another conversation meanwhile: this one stays empty.\n if (epoch !== this.#epoch)\n throw new DOMException(\"moved on\", \"AbortError\");\n this.#opening = null;\n this.#set({ activeId: opened.id_conv });\n void this.refreshConversations();\n return opened.id_conv;\n });\n this.#opening = { epoch, promise };\n promise.catch(() => {\n if (this.#opening?.promise === promise) this.#opening = null;\n });\n return promise;\n }\n\n /** Follows a file until AI-CORE has read it. One that does not get there\n * (too slow, gone, or the poll failed) becomes an error chip rather than\n * hold back every message. */\n async #pollFile(epoch: number, idConv: string, idFile: string) {\n let settled = false;\n try {\n for (let i = 0; i < FILE_POLL_MAX; i++) {\n await new Promise((r) => setTimeout(r, FILE_POLL_MS));\n if (epoch !== this.#epoch) return;\n const current = (await this.client.listFiles(idConv)).find(\n (f) => f.id_file === idFile,\n );\n if (epoch !== this.#epoch || !current) return;\n this.#update((s) => ({\n files: s.files.map((f) => (f.id_file === idFile ? current : f)),\n }));\n if (current.status !== \"processing\") {\n settled = true;\n return;\n }\n }\n } finally {\n if (!settled && epoch === this.#epoch)\n this.#update((s) => ({\n files: s.files.map((f) =>\n f.id_file === idFile && f.status === \"processing\"\n ? { ...f, status: \"error\", error: \"Processing did not finish\" }\n : f,\n ),\n }));\n }\n }\n\n async attach(files: Iterable<File>): Promise<void> {\n const { agentId } = this.#state;\n if (!agentId || this.busy) return;\n this.#set({ error: null });\n const epoch = this.#epoch;\n const current = this.#inEpoch(epoch);\n this.#update((s) => ({ uploading: s.uploading + 1 }));\n try {\n await this.#guard(current, async () => {\n const idConv = await this.#ensureConversation(agentId);\n for (const file of files) {\n const uploaded = await this.client.uploadFile(idConv, file);\n if (epoch !== this.#epoch) return;\n this.#update((s) => ({ files: [...s.files, uploaded] }));\n if (uploaded.status === \"processing\")\n void this.#guard(current, () =>\n this.#pollFile(epoch, idConv, uploaded.id_file),\n );\n }\n });\n } finally {\n // A switch of conversation already reset the count.\n if (epoch === this.#epoch)\n this.#update((s) => ({ uploading: Math.max(0, s.uploading - 1) }));\n }\n }\n\n async detach(idFile: string): Promise<void> {\n const { activeId } = this.#state;\n if (!activeId) return;\n await this.#guard(this.#inEpoch(), async () => {\n await this.client.deleteFile(activeId, idFile);\n this.#update((s) => ({\n files: s.files.filter((f) => f.id_file !== idFile),\n }));\n });\n }\n\n // ---- turns -------------------------------------------------------------\n\n /** Sends `text` with the ready attachments and streams the answer.\n * `context`: the data of the user's page for this turn only (see\n * {@link SendOptions}). */\n async send(text: string, options: SendOptions = {}): Promise<void> {\n const { context } = options;\n const { agentId, activeId, files, uploading } = this.#state;\n const value = text.trim();\n if (!agentId || this.busy || !value) return;\n if (uploading > 0 || files.some((f) => f.status === \"processing\")) return;\n\n const ready = files.filter((f) => f.status === \"ready\");\n const epoch = this.#epoch;\n const abort = new AbortController();\n this.#abort = abort;\n this.#update((s) => ({\n error: null,\n files: [],\n turn: EMPTY_TURN,\n turnStartedAt: Date.now(),\n events: [],\n tokens: 0,\n messages: [\n ...s.messages,\n {\n role: \"user\",\n text: value,\n attachments: ready.map(({ id_file, name, mime, size }) => ({\n id_file,\n name,\n mime,\n size,\n })),\n },\n ],\n }));\n\n const current = () => epoch === this.#epoch && !abort.signal.aborted;\n try {\n const result = await this.client.ask({\n idAgent: agentId,\n idConv: activeId,\n request: {\n text: value,\n ...(ready.length > 0\n ? { attachments: ready.map((f) => ({ id_file: f.id_file })) }\n : {}),\n ...(context ? { context } : {}),\n },\n signal: abort.signal,\n // Recorded even after Stop: the conversation exists on AI-CORE, and\n // the next message must go on in it.\n onConversation: (idConv) => {\n if (epoch === this.#epoch) this.#set({ activeId: idConv });\n },\n onUpdate: (turn, event) => {\n if (!current()) return;\n this.#update((s) =>\n event.kind === \"token\"\n ? { turn, tokens: s.tokens + 1 }\n : {\n turn,\n events: keep(s.events, {\n at: Date.now(),\n kind: event.kind,\n id: event.id,\n data: event.data,\n }),\n },\n );\n },\n });\n if (epoch !== this.#epoch) return;\n // The answer moves from the live turn to the transcript in one update.\n this.#update((s) => ({\n turn: null,\n messages: [\n ...s.messages,\n {\n role: \"assistant\",\n text: answerOf(result.turn),\n sources: result.turn.sources,\n idQuery: result.idQuery,\n error: result.turn.error,\n rating: null,\n // `ask` returns what was read when the stream is stopped.\n interrupted: !result.turn.finished,\n },\n ],\n }));\n if (activeId === null || result.turn.title)\n await this.refreshConversations();\n } catch (err) {\n if (current()) this.#set({ error: toAicoreError(err) });\n // Stopped before the stream opened: the server may run the turn anyway,\n // and the transcript says so rather than end on the question.\n else if (epoch === this.#epoch)\n this.#update((s) => ({\n messages: [\n ...s.messages,\n {\n role: \"assistant\",\n text: \"\",\n sources: [],\n idQuery: null,\n error: null,\n rating: null,\n interrupted: true,\n },\n ],\n }));\n } finally {\n // Not busy any more before the last update, so its listeners see it.\n if (this.#abort === abort) this.#abort = null;\n // `turnStartedAt` stays: the developer panel times the last turn's events.\n if (epoch === this.#epoch) this.#set({ turn: null });\n }\n }\n\n /** Stops reading the stream. The turn goes on server-side (no cancel\n * route yet, agents#66): a new message may get 409 until it ends. */\n stop(): void {\n this.#abort?.abort();\n }\n\n async rate(idQuery: string, rating: number): Promise<void> {\n const { activeId } = this.#state;\n if (!activeId) return;\n const setRating = (value: number | null) =>\n this.#update((s) => ({\n messages: s.messages.map((m) =>\n m.role === \"assistant\" && m.idQuery === idQuery\n ? { ...m, rating: value }\n : m,\n ),\n }));\n const before = this.#state.messages.find(\n (m) => m.role === \"assistant\" && m.idQuery === idQuery,\n );\n setRating(rating);\n try {\n await this.client.sendFeedback(activeId, idQuery, rating);\n } catch (err) {\n setRating(before?.role === \"assistant\" ? before.rating : null);\n this.#set({ error: toAicoreError(err) });\n }\n }\n\n dismissError(): void {\n this.#set({ error: null });\n }\n\n /** Stops the stream and drops every late answer. */\n dispose(): void {\n this.#abort?.abort();\n this.#epoch++;\n }\n}\n"],"mappings":";;AACA,SAAgB,SAAS,OAAkD;CACzE,OAAO,OAAO,UAAU,YAAY,UAAU,QAA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Aa;EACX,KAAK,QAAQ,MAAM;CACrB;CAEA,MAAM,KAAK,SAAiB,QAA+B;EACzD,MAAM,EAAE,aAAa,KAAK;EAC1B,IAAI,CAAC,UAAU;EACf,MAAM,aAAa,UACjB,KAAK,SAAS,OAAO,EACnB,UAAU,EAAE,SAAS,KAAK,MACxB,EAAE,SAAS,eAAe,EAAE,YAAY,UACpC;GAAE,GAAG;GAAG,QAAQ;EAAM,IACtB,CACN,EACF,EAAE;EACJ,MAAM,SAAS,KAAK,OAAO,SAAS,MACjC,MAAM,EAAE,SAAS,eAAe,EAAE,YAAY,OACjD;EACA,UAAU,MAAM;EAChB,IAAI;GACF,MAAM,KAAK,OAAO,aAAa,UAAU,SAAS,MAAM;EAC1D,SAAS,KAAK;GACZ,UAAU,QAAQ,SAAS,cAAc,OAAO,SAAS,IAAI;GAC7D,KAAK,KAAK,EAAE,OAAO,cAAc,GAAG,EAAE,CAAC;EACzC;CACF;CAEA,eAAqB;EACnB,KAAK,KAAK,EAAE,OAAO,KAAK,CAAC;CAC3B;;CAGA,UAAgB;EACd,KAAK,QAAQ,MAAM;EACnB,KAAK;CACP;AACF"}
@@ -1,4 +1,4 @@
1
- import { T as isRecord, n as CHAT_CHANGE, o as AICORE_EVENTS, p as turnErrorText, t as AicoreChatSession } from "./core-CdSjbHFC.js";
1
+ import { T as isRecord, n as CHAT_CHANGE, o as AICORE_EVENTS, p as turnErrorText, t as AicoreChatSession } from "./core-Db3hnKpM.js";
2
2
  import createDOMPurify from "dompurify";
3
3
  import { Marked } from "marked";
4
4
  // src/element/markdown.ts
@@ -79,6 +79,10 @@ var it = {
79
79
  loading: "Caricamento…",
80
80
  untitled: "Senza titolo",
81
81
  disabled: "disabilitata",
82
+ renameConversation: (title) => `Rinomina «${title}»`,
83
+ newTitle: "Nuovo titolo",
84
+ save: "Salva",
85
+ cancel: "Annulla",
82
86
  deleteConversation: (title) => `Elimina «${title}»`,
83
87
  confirmDelete: (title) => `Eliminare la conversazione «${title}»?`,
84
88
  confirmDeleteShort: "Elimina?",
@@ -130,6 +134,7 @@ var it = {
130
134
  publishedVersion: "Versione pubblicata",
131
135
  notPublished: "non pubblicato",
132
136
  conversation: "Conversazione",
137
+ context: "Contesto del turno",
133
138
  none: "—"
134
139
  };
135
140
  var en = {
@@ -141,6 +146,10 @@ var en = {
141
146
  loading: "Loading…",
142
147
  untitled: "Untitled",
143
148
  disabled: "disabled",
149
+ renameConversation: (title) => `Rename “${title}”`,
150
+ newTitle: "New title",
151
+ save: "Save",
152
+ cancel: "Cancel",
144
153
  deleteConversation: (title) => `Delete “${title}”`,
145
154
  confirmDelete: (title) => `Delete the conversation “${title}”?`,
146
155
  confirmDeleteShort: "Delete?",
@@ -192,6 +201,7 @@ var en = {
192
201
  publishedVersion: "Published version",
193
202
  notPublished: "not published",
194
203
  conversation: "Conversation",
204
+ context: "Turn context",
195
205
  none: "—"
196
206
  };
197
207
  /** The built-in texts for `lang`: Italian for `it…` or no language at all,
@@ -225,7 +235,8 @@ var PATHS = {
225
235
  thumbUp: "M9 21h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.58 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2zM9 9l4.34-4.34L12 10h9v2l-3 7H9V9zM1 9h4v12H1z",
226
236
  thumbDown: "M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v2c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm0 12-4.34 4.34L12 14H3v-2l3-7h9v10zm4-12h4v12h-4z",
227
237
  close: "M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z",
228
- menu: "M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"
238
+ menu: "M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z",
239
+ edit: "M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"
229
240
  };
230
241
  var SVG_NS = "http://www.w3.org/2000/svg";
231
242
  function icon(name) {
@@ -406,6 +417,27 @@ button:focus-visible, summary:focus-visible {
406
417
  }
407
418
  .conversation.active .title { font-weight: 600; }
408
419
  .conversation .meta { color: var(--_muted); font-size: calc(var(--_fs) * 12 / 15); }
420
+ .conversation .rename {
421
+ display: flex;
422
+ flex: 1;
423
+ align-items: center;
424
+ gap: 2px;
425
+ min-inline-size: 0;
426
+ padding-block: 4px;
427
+ }
428
+ .rename input {
429
+ flex: 1;
430
+ min-inline-size: 0;
431
+ padding: 4px 8px;
432
+ border: 1px solid var(--_border);
433
+ border-radius: var(--_radius-sm);
434
+ outline: none;
435
+ background: var(--_bg);
436
+ color: inherit;
437
+ font: inherit;
438
+ font-size: calc(var(--_fs) * 14 / 15);
439
+ }
440
+ .rename input:focus { border-color: var(--_accent); box-shadow: 0 0 0 1px var(--_accent); }
409
441
 
410
442
  /* ---- header and banner ------------------------------------------------- */
411
443
 
@@ -656,6 +688,7 @@ var CONFIRM_MS = 4e3;
656
688
  var UPGRADED = [
657
689
  "getToken",
658
690
  "strings",
691
+ "context",
659
692
  "baseUrl",
660
693
  "agent",
661
694
  "tenant",
@@ -748,7 +781,8 @@ function setRating(node, rating) {
748
781
  * workspace, sent as `X-Tenant`), `conversation` (to open), `lang` (`it`,
749
782
  * `en`; else the page's language), `developer` (requests, turn events, agent
750
783
  * version).
751
- * Properties: `getToken({ retry })`, `strings` (text overrides), `state`.
784
+ * Properties: `getToken({ retry })`, `strings` (text overrides), `context`
785
+ * (the page's data, sent with every message), `state`.
752
786
  * Events (bubbling, composed): `aicore-conversation`, `aicore-turn`,
753
787
  * `aicore-error`, `aicore-auth-required`, `aicore-tenant-refused`.
754
788
  */
@@ -763,6 +797,12 @@ var AicoreAgentChat = class extends Base {
763
797
  ];
764
798
  #getToken = null;
765
799
  #overrides = null;
800
+ #context = null;
801
+ /** `context` changed since the developer panel last showed it. */
802
+ #contextChanged = false;
803
+ /** The conversation whose title is being edited, and its field: kept
804
+ * across renders of the list, so what the user typed stays. */
805
+ #renaming = null;
766
806
  /** The conversation whose delete button waits for its second click. */
767
807
  #confirming = null;
768
808
  #confirmTimer = null;
@@ -919,6 +959,16 @@ var AicoreAgentChat = class extends Base {
919
959
  developerBody
920
960
  };
921
961
  root.addEventListener("click", (e) => this.#onClick(e));
962
+ conversations.addEventListener("submit", (e) => {
963
+ e.preventDefault();
964
+ this.#commitRename();
965
+ });
966
+ conversations.addEventListener("keydown", (e) => {
967
+ if (e.key === "Escape" && this.#renaming) {
968
+ e.preventDefault();
969
+ this.#stopRename(true);
970
+ }
971
+ });
922
972
  thread.addEventListener("toggle", (e) => this.#onToggle(e), true);
923
973
  composer.addEventListener("submit", (e) => {
924
974
  e.preventDefault();
@@ -967,6 +1017,18 @@ var AicoreAgentChat = class extends Base {
967
1017
  this.#overrides = isRecord(value) ? value : null;
968
1018
  this.#scheduleRender(true);
969
1019
  }
1020
+ /** The data of the page the user is on (the open record, the chosen
1021
+ * period), sent with every message as `context`: the agent's prompt reads
1022
+ * it as `{{context.key}}`. A JSON object of at most 16 KB, or null. Set it
1023
+ * again when the page changes: AI-CORE keeps it for one turn only. */
1024
+ get context() {
1025
+ return this.#context;
1026
+ }
1027
+ set context(value) {
1028
+ this.#context = isRecord(value) ? value : null;
1029
+ this.#contextChanged = true;
1030
+ this.#scheduleRender();
1031
+ }
970
1032
  get baseUrl() {
971
1033
  return this.getAttribute("base-url");
972
1034
  }
@@ -1128,6 +1190,7 @@ var AicoreAgentChat = class extends Base {
1128
1190
  this.#ui.layout.classList.remove("rail-open");
1129
1191
  }
1130
1192
  const { id } = target?.dataset ?? {};
1193
+ if (this.#renaming && !event.target?.closest(".rename")) this.#stopRename(false);
1131
1194
  if (this.#confirming !== null && !(target?.dataset.action === "delete" && id === this.#confirming)) this.#confirmDelete(null);
1132
1195
  if (!target || target.disabled) return;
1133
1196
  const session = this.#session;
@@ -1142,6 +1205,12 @@ var AicoreAgentChat = class extends Base {
1142
1205
  this.#stick = true;
1143
1206
  if (id) session?.open(id);
1144
1207
  break;
1208
+ case "rename":
1209
+ if (id) this.#startRename(id);
1210
+ break;
1211
+ case "cancel-rename":
1212
+ this.#stopRename(true);
1213
+ break;
1145
1214
  case "delete":
1146
1215
  if (!id) break;
1147
1216
  if (this.#confirming === id) {
@@ -1177,10 +1246,49 @@ var AicoreAgentChat = class extends Base {
1177
1246
  this.#confirmTimer = id === null ? null : setTimeout(() => this.#confirmDelete(null), CONFIRM_MS);
1178
1247
  if (this.#confirming === id) return;
1179
1248
  this.#confirming = id;
1249
+ this.#rerenderRail();
1250
+ if (id !== null) this.#focusAction("delete", id);
1251
+ }
1252
+ #rerenderRail() {
1180
1253
  this.#renderRail(this.#strings(), this.#session?.state ?? null, this.#session?.busy ?? false);
1181
- if (id !== null) {
1182
- for (const button of this.#ui.conversations.querySelectorAll("[data-action=\"delete\"]")) if (button.dataset.id === id) button.focus();
1183
- }
1254
+ }
1255
+ #startRename(id) {
1256
+ const conversation = this.#session?.state.conversations.find((c) => c.id === id);
1257
+ if (!conversation) return;
1258
+ const input = h("input", { attrs: {
1259
+ type: "text",
1260
+ "aria-label": this.#strings().newTitle
1261
+ } });
1262
+ input.value = conversation.title ?? "";
1263
+ input.addEventListener("input", () => {
1264
+ const save = input.parentElement?.querySelector("[type=submit]");
1265
+ if (save) save.disabled = !input.value.trim();
1266
+ });
1267
+ this.#renaming = {
1268
+ id,
1269
+ input
1270
+ };
1271
+ this.#rerenderRail();
1272
+ input.focus();
1273
+ input.select();
1274
+ }
1275
+ /** Drops the edit; `refocus` puts the keyboard back on its button. */
1276
+ #stopRename(refocus) {
1277
+ const id = this.#renaming?.id;
1278
+ if (id === void 0) return;
1279
+ this.#renaming = null;
1280
+ this.#rerenderRail();
1281
+ if (refocus) this.#focusAction("rename", id);
1282
+ }
1283
+ #commitRename() {
1284
+ const renaming = this.#renaming;
1285
+ const title = renaming?.input.value.trim();
1286
+ if (!renaming || !title || this.#session?.busy) return;
1287
+ this.#stopRename(true);
1288
+ this.#session?.rename(renaming.id, title);
1289
+ }
1290
+ #focusAction(action, id) {
1291
+ for (const button of this.#ui.conversations.querySelectorAll(`[data-action="${action}"]`)) if (button.dataset.id === id) button.focus();
1184
1292
  }
1185
1293
  #copy(button, index) {
1186
1294
  const message = this.#session?.state.messages[index];
@@ -1222,7 +1330,7 @@ var AicoreAgentChat = class extends Base {
1222
1330
  if (!session || !text || this.#ui.send.disabled) return;
1223
1331
  this.#ui.input.value = "";
1224
1332
  this.#stick = true;
1225
- session.send(text);
1333
+ session.send(text, { context: this.#context });
1226
1334
  this.#updateSend();
1227
1335
  }
1228
1336
  /** `lang` of the element, else of its closest ancestor, else of the page. */
@@ -1263,7 +1371,9 @@ var AicoreAgentChat = class extends Base {
1263
1371
  if (busyChanged || changed("files", "agentId")) this.#renderComposer(t, state, busy);
1264
1372
  const developer = this.hasAttribute("developer");
1265
1373
  this.#ui.developer.hidden = !developer;
1266
- if (developer && changed("requests", "events", "error", "agent", "activeId")) this.#renderDeveloper(t, state);
1374
+ const contextChanged = this.#contextChanged;
1375
+ this.#contextChanged = false;
1376
+ if (developer && (contextChanged || changed("requests", "events", "error", "agent", "activeId"))) this.#renderDeveloper(t, state);
1267
1377
  else if (developer && changed("tokens") && this.#eventsHeading && state) this.#eventsHeading.textContent = t.events(state.tokens);
1268
1378
  this.#ui.layout.classList.toggle("rail-open", this.#railOpen);
1269
1379
  if (this.#stick) this.#ui.transcript.scrollTop = this.#ui.transcript.scrollHeight;
@@ -1295,7 +1405,19 @@ var AicoreAgentChat = class extends Base {
1295
1405
  const status = !state?.agentId || list.length > 0 ? "" : state.conversationsLoading ? t.loading : state.conversationsFailed ? t.conversationsFailed : t.noConversations;
1296
1406
  ui.railStatus.textContent = status;
1297
1407
  ui.railStatus.hidden = status === "";
1408
+ const renaming = this.#renaming;
1409
+ if (renaming && !list.some((c) => c.id === renaming.id)) this.#renaming = null;
1410
+ const focused = this.shadowRoot?.activeElement;
1411
+ const inList = focused ? ui.conversations.contains(focused) : false;
1412
+ const field = this.#renaming?.input;
1413
+ const typing = inList && focused === field;
1414
+ const selection = typing ? [field.selectionStart, field.selectionEnd] : [];
1415
+ const { action, id } = inList && !typing ? focused?.dataset ?? {} : {};
1298
1416
  ui.conversations.replaceChildren(...list.map((c) => this.#conversationItem(t, c, c.id === state?.activeId, busy)));
1417
+ if (typing && field.isConnected) {
1418
+ field.focus();
1419
+ field.setSelectionRange(selection[0] ?? null, selection[1] ?? null);
1420
+ } else if (action && id) this.#focusAction(action, id);
1299
1421
  }
1300
1422
  #when(t, ms) {
1301
1423
  return new Intl.DateTimeFormat(t.locale, {
@@ -1323,6 +1445,19 @@ var AicoreAgentChat = class extends Base {
1323
1445
  }));
1324
1446
  if (active) open.setAttribute("aria-current", "true");
1325
1447
  open.disabled = busy;
1448
+ const item = h("li", { class: active ? "conversation active" : "conversation" });
1449
+ if (this.#renaming?.id === conversation.id) {
1450
+ const { input } = this.#renaming;
1451
+ const save = iconButton("check", t.save, { type: "submit" });
1452
+ save.disabled = busy || !input.value.trim();
1453
+ item.append(h("form", { class: "rename" }, input, save, iconButton("close", t.cancel, { "data-action": "cancel-rename" })));
1454
+ return item;
1455
+ }
1456
+ const rename = iconButton("edit", t.renameConversation(title), {
1457
+ "data-action": "rename",
1458
+ "data-id": conversation.id
1459
+ });
1460
+ rename.disabled = busy;
1326
1461
  const confirming = this.#confirming === conversation.id;
1327
1462
  const remove = iconButton("delete", confirming ? t.confirmDelete(title) : t.deleteConversation(title), {
1328
1463
  "data-action": "delete",
@@ -1330,7 +1465,8 @@ var AicoreAgentChat = class extends Base {
1330
1465
  }, confirming ? "danger confirming" : "danger");
1331
1466
  if (confirming) remove.replaceChildren(t.confirmDeleteShort);
1332
1467
  remove.disabled = busy;
1333
- return h("li", { class: active ? "conversation active" : "conversation" }, open, remove);
1468
+ item.append(open, rename, remove);
1469
+ return item;
1334
1470
  }
1335
1471
  #renderHeader(t, state) {
1336
1472
  const ui = this.#ui;
@@ -1506,6 +1642,18 @@ var AicoreAgentChat = class extends Base {
1506
1642
  const uploading = (state?.uploading ?? 0) > 0 || (state?.files.some((f) => f.status === "processing") ?? false);
1507
1643
  this.#ui.send.disabled = !state?.agentId || (this.#session?.busy ?? false) || uploading || !this.#ui.input.value.trim();
1508
1644
  }
1645
+ /** The `context` the next message sends, shortened, with its size. */
1646
+ #contextLine() {
1647
+ if (!this.#context) return null;
1648
+ let json;
1649
+ try {
1650
+ json = JSON.stringify(this.#context);
1651
+ } catch {
1652
+ return "?";
1653
+ }
1654
+ const bytes = new TextEncoder().encode(json).length;
1655
+ return `${json.length > PREVIEW_CHARS ? `${json.slice(0, PREVIEW_CHARS)}…` : json} · ${bytes} B`;
1656
+ }
1509
1657
  #renderDeveloper(t, state) {
1510
1658
  const ui = this.#ui;
1511
1659
  if (!state || !this.#session) {
@@ -1519,7 +1667,8 @@ var AicoreAgentChat = class extends Base {
1519
1667
  ["X-Tenant", this.getAttribute("tenant") ?? t.none],
1520
1668
  [t.agent, state.agentId ?? t.none],
1521
1669
  [t.publishedVersion, !agent ? t.none : agent.published_version_number === null ? t.notPublished : `v${agent.published_version_number}`],
1522
- [t.conversation, state.activeId ?? t.none]
1670
+ [t.conversation, state.activeId ?? t.none],
1671
+ [t.context, this.#contextLine() ?? t.none]
1523
1672
  ])];
1524
1673
  if (error) parts.push(h("h4", { text: t.lastError }), list([
1525
1674
  ["status", `${error.status} · ${error.kind}`],
@@ -1543,4 +1692,4 @@ function defineAicoreAgentChat(tag = AICORE_AGENT_CHAT_TAG) {
1543
1692
  }
1544
1693
  export { AicoreAgentChat as n, defineAicoreAgentChat as r, AICORE_AGENT_CHAT_TAG as t };
1545
1694
 
1546
- //# sourceMappingURL=src-CfPZVl62.js.map
1695
+ //# sourceMappingURL=src-DPfU5Bd2.js.map