mui-hermes-chat 0.0.0-stage → 0.2.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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +103 -2
  3. package/dist/adapter/adapter.d.ts +20 -0
  4. package/dist/adapter/adapter.js +179 -0
  5. package/dist/adapter/index.d.ts +2 -0
  6. package/dist/adapter/index.js +2 -0
  7. package/dist/core/events.d.ts +59 -0
  8. package/dist/core/events.js +57 -0
  9. package/dist/core/index.d.ts +5 -0
  10. package/dist/core/index.js +5 -0
  11. package/dist/core/initials.d.ts +5 -0
  12. package/dist/core/initials.js +28 -0
  13. package/dist/core/transport.d.ts +20 -0
  14. package/dist/core/transport.js +89 -0
  15. package/dist/core/types.d.ts +58 -0
  16. package/dist/core/types.js +2 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +9 -0
  19. package/dist/react/avatar/ParticipantAvatar.d.ts +6 -0
  20. package/dist/react/avatar/ParticipantAvatar.js +25 -0
  21. package/dist/react/avatar/accent.d.ts +3 -0
  22. package/dist/react/avatar/accent.js +9 -0
  23. package/dist/react/avatar/index.d.ts +3 -0
  24. package/dist/react/avatar/index.js +3 -0
  25. package/dist/react/chat/Approval.d.ts +11 -0
  26. package/dist/react/chat/Approval.js +41 -0
  27. package/dist/react/chat/HermesChat.d.ts +43 -0
  28. package/dist/react/chat/HermesChat.js +124 -0
  29. package/dist/react/chat/index.d.ts +6 -0
  30. package/dist/react/chat/index.js +6 -0
  31. package/dist/react/chat/labels.d.ts +41 -0
  32. package/dist/react/chat/labels.js +42 -0
  33. package/dist/react/chat/parts.d.ts +41 -0
  34. package/dist/react/chat/parts.js +112 -0
  35. package/dist/react/chat/useFitHeight.d.ts +12 -0
  36. package/dist/react/chat/useFitHeight.js +42 -0
  37. package/dist/react/composer/ChatComposer.d.ts +7 -0
  38. package/dist/react/composer/ChatComposer.js +44 -0
  39. package/dist/react/composer/JumpToLatest.d.ts +4 -0
  40. package/dist/react/composer/JumpToLatest.js +26 -0
  41. package/dist/react/composer/SendOrStopButton.d.ts +9 -0
  42. package/dist/react/composer/SendOrStopButton.js +21 -0
  43. package/dist/react/composer/index.d.ts +6 -0
  44. package/dist/react/composer/index.js +6 -0
  45. package/dist/react/composer/labels.d.ts +10 -0
  46. package/dist/react/composer/labels.js +8 -0
  47. package/dist/react/composer/slots.d.ts +8 -0
  48. package/dist/react/composer/slots.js +12 -0
  49. package/dist/react/info/SessionInfo.d.ts +37 -0
  50. package/dist/react/info/SessionInfo.js +91 -0
  51. package/dist/react/info/index.d.ts +3 -0
  52. package/dist/react/info/index.js +2 -0
  53. package/dist/react/tools/JsonTree.d.ts +8 -0
  54. package/dist/react/tools/JsonTree.js +25 -0
  55. package/dist/react/tools/ToolDetailDrawer.d.ts +9 -0
  56. package/dist/react/tools/ToolDetailDrawer.js +47 -0
  57. package/dist/react/tools/ToolPreviewView.d.ts +6 -0
  58. package/dist/react/tools/ToolPreviewView.js +32 -0
  59. package/dist/react/tools/ToolRow.d.ts +11 -0
  60. package/dist/react/tools/ToolRow.js +45 -0
  61. package/dist/react/tools/ToolStepGroup.d.ts +10 -0
  62. package/dist/react/tools/ToolStepGroup.js +28 -0
  63. package/dist/react/tools/family.d.ts +19 -0
  64. package/dist/react/tools/family.js +107 -0
  65. package/dist/react/tools/format.d.ts +19 -0
  66. package/dist/react/tools/format.js +37 -0
  67. package/dist/react/tools/icons.d.ts +5 -0
  68. package/dist/react/tools/icons.js +25 -0
  69. package/dist/react/tools/index.d.ts +10 -0
  70. package/dist/react/tools/index.js +10 -0
  71. package/dist/react/tools/labels.d.ts +23 -0
  72. package/dist/react/tools/labels.js +7 -0
  73. package/dist/react/tools/toolPreview.d.ts +74 -0
  74. package/dist/react/tools/toolPreview.js +156 -0
  75. package/package.json +48 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ejlevin1
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # mui-hermes-chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Embeddable Hermes chat for React 19 + MUI 9 apps, built on `@mui/x-chat` (pinned alpha). One package include gives
4
+ a full chat screen (avatars, composer, streamed replies, Jarvis-style tool rows, approvals, progressive history,
5
+ session info), plus the lower layers on their own (event parser, transport, x-chat adapter).
6
+
7
+ ## Install
8
+ ```sh
9
+ npm install mui-hermes-chat
10
+ ```
11
+
12
+ Installing from a git tag (`github:ejlevin1/mui-hermes-chat#v0.1.x`) is legacy: `dist/` is no longer committed, so
13
+ only the v0.1.x tags carry a built `dist/`. Use the npm package from 0.2.0 on.
14
+
15
+ Peer deps: `react` 19, `react-dom`, `@mui/material` 9, `@mui/icons-material` 9, `@emotion/react`, `@emotion/styled`,
16
+ `@mui/x-chat` exactly `9.0.0-alpha.22`.
17
+
18
+ ## Embed
19
+ ```tsx
20
+ import { HermesChat } from "mui-hermes-chat";
21
+
22
+ <HermesChat
23
+ urls={chat.urls} // { turn, approval, new, history, messages }
24
+ target={{ board: "main", task: "t_123" }} // sent as query/body to every call
25
+ csrf={async (refresh) => getCsrfToken(refresh)}
26
+ history={{ messages: chat.messages, cursor: chat.history_page.cursor, hasMore: chat.history_page.has_more }}
27
+ renderHtml={(html) => <SafeHtml html={html} />} // your sanitising renderer; the package never injects html
28
+ participants={{
29
+ user: { name: me.viewer.name || me.email },
30
+ agent: { name: chat.agent.label, initials: chat.agent.initials, color: chat.agent.color },
31
+ }}
32
+ session={sessionInfo} // optional: enables the Info button
33
+ onTurnEnd={refetch}
34
+ />
35
+ ```
36
+
37
+ ## Props (`HermesChatProps`)
38
+ | prop | type | notes |
39
+ |---|---|---|
40
+ | `urls`, `target`, `csrf` | `ChatUrls`, `Target`, `CsrfSource` | server endpoints, subject, token source |
41
+ | `history` | `{ messages, cursor, hasMore }` | newest page; older pages load via `urls.messages` |
42
+ | `renderHtml` | `(html) => ReactNode` | renders server-sanitised assistant html |
43
+ | `participants` | `{ user, agent }` | `Participant = { name, initials?, color?, avatarUrl? }` |
44
+ | `session?` | `SessionInfo` | enables the Info button and drawer |
45
+ | `labels?` | `Partial<ChatLabels>` | every user-visible string; English defaults |
46
+ | `maxMessage?` | number | composer length limit |
47
+ | `notice?`, `linkedNote?`, `changed?` | string / boolean | server notice, linked-subject note, "subject changed" note |
48
+ | `hasEarlier?`, `earlierHref?` | boolean / string | link to earlier conversations in the toolbar |
49
+ | `onTurnEnd?` | `() => void` | after each finished turn and after New chat |
50
+ | `mode?` | `inline \| sheet \| auto` | `auto` = sheet on phones |
51
+ | `fit?` | `{ minHeight?, bottomGap? }` | fit the card to the viewport (theme spacing units) |
52
+ | `toolbarActions?` | `ReactNode` | extra toolbar content |
53
+
54
+ ## Labels
55
+ Pass `labels={{ newChat: "Neuer Chat", ... }}`. Keys come from `ChatLabels` (chat, composer, tools and session-info
56
+ areas merged); defaults are exported as `defaultChatLabels`, `defaultComposerLabels`, `defaultToolLabels`,
57
+ `DEFAULT_INFO_LABELS`. Function labels such as `steps(n)` take the count.
58
+
59
+ ## Theming
60
+ Colours are palette roles, so light and dark work. Participant colours are accent names:
61
+ `indigo | blue | teal | green | orange | red | purple | pink | gray`. `color: null` hashes the key onto the list
62
+ (`avatarColor(key)`). Initials come from `initials(name)` (email local part, first+last word, or first two letters;
63
+ empty shows a person icon).
64
+
65
+ ## CSP
66
+ No inline `<style>`, no `eval`, no `innerHTML` in the package: assistant html goes only through your `renderHtml`.
67
+ Styling is MUI `sx`/`styled`, so a nonce'd Emotion cache on the consumer side is all that is needed. Tool args and
68
+ previews are rendered as text, never html.
69
+
70
+ ## Event contract `hermes-chat-events/2`
71
+ `POST urls.turn` answers `text/event-stream`, frames `data: {json}`. v1 frames `run, delta, thinking, tool, approval,
72
+ reply, error, end` are unchanged; unknown fields and frames are ignored, so a v1 server works.
73
+
74
+ | `t` | fields |
75
+ |---|---|
76
+ | `tool` | `name`, `state: start\|done\|failed`, `id?`, `preview?` (≤300 chars), `args?` (redacted, ≤4 KB else `args_clipped: true`), `duration_s?`, `result_preview?` (≤500 chars) |
77
+ | `commentary` | `text`: interim note shown muted, never the final answer |
78
+
79
+ Server redacts secrets before clipping; nothing here is rendered as html.
80
+
81
+ ## History paging
82
+ Read model carries the newest page (≤30 user turns) as `history`. `GET <urls.messages>?<target>&cursor=<c>` returns
83
+ `{ messages, cursor, has_more }`, the next older page, chronological. Cursors are opaque and server-signed; a bad one
84
+ answers 400 `bad_cursor`, anything not allowed 404. The client dedupes by message `id`. Messages are
85
+ `HermesMessage { id, role, text, html, created?, tools? }`.
86
+
87
+ ## Use only the core / adapter
88
+ Everything is exported from the root. Without React: `parseChatEvents`, `runTurn`, `sendApproval`, `startOver`,
89
+ `fetchHistoryPage`, `initials`, `avatarColor` (`src/core` imports no React or MUI). With your own UI on x-chat:
90
+
91
+ ```ts
92
+ import { hermesChatAdapter } from "mui-hermes-chat";
93
+ const adapter = hermesChatAdapter({ urls, target, csrf, initialPage: { messages, cursor, hasMore } });
94
+ // pass to <ChatProvider adapter={adapter} /> from @mui/x-chat
95
+ ```
96
+
97
+ Layers: `src/core` (pure TS) · `src/adapter` (x-chat `ChatAdapter`) · `src/react/<area>`.
98
+
99
+ ## Contributing
100
+ Run `npm run hooks` once per clone: it enables the gitleaks pre-commit and pre-push hooks (`brew install gitleaks`).
101
+ Use synthetic names, emails and paths in code and fixtures.
102
+
103
+ ## License
104
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,20 @@
1
+ /** `hermesChatAdapter`: maps `hermes-chat-events/2` turns and the paged history onto the @mui/x-chat `ChatAdapter`. */
2
+ import type { ChatAdapter } from "@mui/x-chat/headless";
3
+ import type { ChatMessage } from "@mui/x-chat/types";
4
+ import type { ChatUrls, CsrfSource, HermesMessage, HistoryPage, Target } from "../core/types";
5
+ export interface HermesAdapterOptions {
6
+ urls: Pick<ChatUrls, "turn" | "messages">;
7
+ target: Target;
8
+ csrf: CsrfSource;
9
+ /** The newest history page from the read model; `listMessages` without a cursor returns it. */
10
+ initialPage?: HistoryPage;
11
+ /** Shown as the error part when the connection drops with no server text. */
12
+ networkErrorText?: string;
13
+ }
14
+ export declare const NOTE_NETWORK = "The connection to Hermes was lost. Your message is still in the box: send it again.";
15
+ /**
16
+ * History rows → x-chat messages. User: one text part. Assistant: a `data-tools` part (`HermesToolCall[]`)
17
+ * when it carries tools, then a `data-reply` part (`{text, html}`) when it has html, else a text part.
18
+ */
19
+ export declare function toChatMessages(messages: HermesMessage[]): ChatMessage[];
20
+ export declare function hermesChatAdapter(opts: HermesAdapterOptions): ChatAdapter;
@@ -0,0 +1,179 @@
1
+ import { ChatHttpError, fetchHistoryPage, runTurn } from "../core/transport";
2
+ let seq = 0;
3
+ const nextId = (p) => `${p}-${Date.now().toString(36)}-${(seq++).toString(36)}`;
4
+ export const NOTE_NETWORK = "The connection to Hermes was lost. Your message is still in the box: send it again.";
5
+ const toolInput = (e) => e.args ?? (e.preview !== undefined ? { preview: e.preview } : {});
6
+ function toolOutput(e) {
7
+ const out = {};
8
+ if (e.result_preview !== undefined)
9
+ out.result_preview = e.result_preview;
10
+ if (e.duration_s !== undefined)
11
+ out.duration_s = e.duration_s;
12
+ return out;
13
+ }
14
+ /**
15
+ * History rows → x-chat messages. User: one text part. Assistant: a `data-tools` part (`HermesToolCall[]`)
16
+ * when it carries tools, then a `data-reply` part (`{text, html}`) when it has html, else a text part.
17
+ */
18
+ export function toChatMessages(messages) {
19
+ return messages.map((m) => {
20
+ const parts = [];
21
+ if (m.role === "assistant") {
22
+ if (m.tools?.length)
23
+ parts.push({ type: "data-tools", id: `${m.id}-tools`, data: m.tools });
24
+ if (m.html)
25
+ parts.push({ type: "data-reply", id: "reply", data: { text: m.text, html: m.html } });
26
+ else if (m.text)
27
+ parts.push({ type: "text", text: m.text });
28
+ }
29
+ else {
30
+ parts.push({ type: "text", text: m.text });
31
+ }
32
+ const msg = { id: m.id, role: m.role, parts, status: "sent" };
33
+ if (typeof m.created === "number")
34
+ msg.createdAt = new Date(m.created * 1000).toISOString();
35
+ return msg;
36
+ });
37
+ }
38
+ export function hermesChatAdapter(opts) {
39
+ const seen = new Set();
40
+ const fresh = (ms) => ms.filter((m) => {
41
+ if (!m?.id || seen.has(m.id))
42
+ return false;
43
+ seen.add(m.id);
44
+ return true;
45
+ });
46
+ const result = (page, ms) => ({
47
+ messages: toChatMessages(ms),
48
+ cursor: page.cursor ?? undefined,
49
+ hasMore: page.hasMore && page.cursor !== null,
50
+ });
51
+ return {
52
+ async listMessages({ cursor }) {
53
+ if (cursor === undefined) {
54
+ // Initial load: the newest page the read model already carries.
55
+ seen.clear();
56
+ const page = opts.initialPage ?? { messages: [], cursor: null, hasMore: false };
57
+ return result(page, fresh(page.messages));
58
+ }
59
+ if (!opts.urls.messages)
60
+ return { messages: [], hasMore: false };
61
+ const page = await fetchHistoryPage(opts.urls.messages, opts.target, cursor, opts.csrf);
62
+ return result(page, fresh(page.messages));
63
+ },
64
+ async sendMessage({ message, signal }) {
65
+ const text = message.parts.map((p) => (p.type === "text" ? p.text : "")).join("");
66
+ const messageId = nextId("hermes");
67
+ let closed = false;
68
+ return new ReadableStream({
69
+ start(c) {
70
+ let textId = "";
71
+ let reasonId = "";
72
+ /** Open tool calls: event `id` (v2) or tool name (v1) → toolCallId. */
73
+ const tools = new Map();
74
+ const closeText = () => {
75
+ if (textId) {
76
+ c.enqueue({ type: "text-end", id: textId });
77
+ textId = "";
78
+ }
79
+ };
80
+ const closeReason = () => {
81
+ if (reasonId) {
82
+ c.enqueue({ type: "reasoning-end", id: reasonId });
83
+ reasonId = "";
84
+ }
85
+ };
86
+ const finish = (reason) => {
87
+ if (closed)
88
+ return;
89
+ closeReason();
90
+ closeText();
91
+ c.enqueue({ type: "finish", messageId, finishReason: reason });
92
+ closed = true;
93
+ c.close();
94
+ };
95
+ c.enqueue({ type: "start", messageId });
96
+ const onTool = (e) => {
97
+ const st = e.state || "start";
98
+ const key = e.id ?? e.name;
99
+ let id = tools.get(key);
100
+ if (st === "start" || !id) {
101
+ id = e.id ?? nextId("tool");
102
+ tools.set(key, id);
103
+ c.enqueue({ type: "tool-input-start", toolCallId: id, toolName: e.name });
104
+ c.enqueue({ type: "tool-input-available", toolCallId: id, toolName: e.name, input: toolInput(e) });
105
+ }
106
+ if (st === "done") {
107
+ c.enqueue({ type: "tool-output-available", toolCallId: id, output: toolOutput(e) });
108
+ tools.delete(key);
109
+ }
110
+ else if (st === "failed") {
111
+ c.enqueue({ type: "tool-output-error", toolCallId: id, errorText: e.result_preview || "failed" });
112
+ tools.delete(key);
113
+ }
114
+ };
115
+ const on = (e) => {
116
+ if (closed)
117
+ return;
118
+ switch (e.t) {
119
+ case "delta":
120
+ closeReason();
121
+ if (!textId) {
122
+ textId = nextId("t");
123
+ c.enqueue({ type: "text-start", id: textId });
124
+ }
125
+ c.enqueue({ type: "text-delta", id: textId, delta: e.text });
126
+ break;
127
+ case "thinking":
128
+ if (!reasonId) {
129
+ reasonId = nextId("r");
130
+ c.enqueue({ type: "reasoning-start", id: reasonId });
131
+ }
132
+ c.enqueue({ type: "reasoning-delta", id: reasonId, delta: e.text });
133
+ break;
134
+ case "commentary":
135
+ closeReason();
136
+ closeText();
137
+ c.enqueue({ type: "data-commentary", id: nextId("c"), data: { text: e.text } });
138
+ break;
139
+ case "tool":
140
+ onTool(e);
141
+ break;
142
+ case "approval":
143
+ c.enqueue({ type: "data-approval", id: e.request_id, data: e });
144
+ break;
145
+ case "reply":
146
+ closeText();
147
+ c.enqueue({ type: "data-reply", id: "reply", data: { text: e.text, html: e.html } });
148
+ break;
149
+ case "error":
150
+ c.enqueue({ type: "data-error", id: "error", data: { text: e.text || "Something went wrong.", code: e.code } });
151
+ break;
152
+ case "end":
153
+ finish("stop");
154
+ break;
155
+ default:
156
+ break; // `run` carries only the run id; unknown frames are ignored
157
+ }
158
+ };
159
+ runTurn(opts.urls.turn, opts.target, text, on, opts.csrf, signal).then(() => finish("stop"), (err) => {
160
+ if (closed)
161
+ return;
162
+ if (signal.aborted) {
163
+ closed = true;
164
+ c.enqueue({ type: "abort", messageId });
165
+ c.close();
166
+ return;
167
+ }
168
+ const msg = err instanceof ChatHttpError ? err.message : "";
169
+ on({ t: "error", text: msg || opts.networkErrorText || NOTE_NETWORK });
170
+ finish("error");
171
+ });
172
+ },
173
+ cancel() {
174
+ closed = true;
175
+ },
176
+ });
177
+ },
178
+ };
179
+ }
@@ -0,0 +1,2 @@
1
+ /** x-chat adapter layer: Hermes turns + paged history as a `ChatAdapter`. */
2
+ export { hermesChatAdapter, toChatMessages, NOTE_NETWORK, type HermesAdapterOptions } from "./adapter";
@@ -0,0 +1,2 @@
1
+ /** x-chat adapter layer: Hermes turns + paged history as a `ChatAdapter`. */
2
+ export { hermesChatAdapter, toChatMessages, NOTE_NETWORK } from "./adapter";
@@ -0,0 +1,59 @@
1
+ /** Event contract `hermes-chat-events/2`: the SSE frames of POST <urls.turn> and an incremental parser (pure TS). */
2
+ export declare const CHAT_EVENTS_CONTRACT = "hermes-chat-events/2";
3
+ export type ChatEvent = {
4
+ t: "run";
5
+ run_id?: string;
6
+ } | {
7
+ t: "delta";
8
+ text: string;
9
+ } | {
10
+ t: "thinking";
11
+ text: string;
12
+ } | {
13
+ t: "tool";
14
+ name: string;
15
+ state?: "start" | "done" | "failed";
16
+ /** v2: unique per turn (upstream tool_call_id, else `<name>#<n>`). */
17
+ id?: string;
18
+ preview?: string;
19
+ args?: Record<string, unknown>;
20
+ args_clipped?: boolean;
21
+ duration_s?: number;
22
+ result_preview?: string;
23
+ } | {
24
+ t: "commentary";
25
+ text: string;
26
+ } | {
27
+ t: "approval";
28
+ run_id: string;
29
+ request_id: string;
30
+ execution_generation: string | number;
31
+ title?: string;
32
+ text?: string;
33
+ expires_s?: number;
34
+ } | {
35
+ t: "reply";
36
+ text: string;
37
+ html: string;
38
+ } | {
39
+ t: "error";
40
+ code?: string;
41
+ text: string;
42
+ } | {
43
+ t: "end";
44
+ };
45
+ export type ApprovalEvent = Extract<ChatEvent, {
46
+ t: "approval";
47
+ }>;
48
+ export type ToolEvent = Extract<ChatEvent, {
49
+ t: "tool";
50
+ }>;
51
+ /**
52
+ * Incremental SSE parser: feed it text in any split (mid-line, mid-frame, mid-JSON, CRLF), call
53
+ * `end()` once. The event type is `data.t`, else the `event:` line. Unusable frames are dropped;
54
+ * unknown fields and frame types pass through untouched (consumers ignore what they don't know).
55
+ */
56
+ export declare function parseChatEvents(onEvent: (e: ChatEvent) => void): {
57
+ push: (c: string) => void;
58
+ end: () => void;
59
+ };
@@ -0,0 +1,57 @@
1
+ /** Event contract `hermes-chat-events/2`: the SSE frames of POST <urls.turn> and an incremental parser (pure TS). */
2
+ export const CHAT_EVENTS_CONTRACT = "hermes-chat-events/2";
3
+ /**
4
+ * Incremental SSE parser: feed it text in any split (mid-line, mid-frame, mid-JSON, CRLF), call
5
+ * `end()` once. The event type is `data.t`, else the `event:` line. Unusable frames are dropped;
6
+ * unknown fields and frame types pass through untouched (consumers ignore what they don't know).
7
+ */
8
+ export function parseChatEvents(onEvent) {
9
+ let buf = "";
10
+ const frame = (text) => {
11
+ const data = [];
12
+ let name = "";
13
+ for (const line of text.split(/\r?\n/)) {
14
+ if (!line || line[0] === ":")
15
+ continue;
16
+ if (line.startsWith("event:"))
17
+ name = line.slice(6).trim();
18
+ else if (line.startsWith("data:"))
19
+ data.push(line.slice(5).replace(/^ /, ""));
20
+ }
21
+ if (!data.length)
22
+ return;
23
+ let obj;
24
+ try {
25
+ obj = JSON.parse(data.join("\n"));
26
+ }
27
+ catch {
28
+ return; // unusable frame
29
+ }
30
+ if (obj && typeof obj === "object" && !Array.isArray(obj)) {
31
+ const o = obj;
32
+ const t = typeof o.t === "string" ? o.t : name;
33
+ if (t)
34
+ onEvent({ ...o, t });
35
+ }
36
+ };
37
+ const drain = (all) => {
38
+ for (;;) {
39
+ const m = /\r?\n\r?\n/.exec(buf);
40
+ if (!m)
41
+ break;
42
+ frame(buf.slice(0, m.index));
43
+ buf = buf.slice(m.index + m[0].length);
44
+ }
45
+ if (all && buf.trim())
46
+ frame(buf);
47
+ if (all)
48
+ buf = "";
49
+ };
50
+ return {
51
+ push: (c) => {
52
+ buf += c;
53
+ drain(false);
54
+ },
55
+ end: () => drain(true),
56
+ };
57
+ }
@@ -0,0 +1,5 @@
1
+ /** Pure core (no React/MUI): contract types, avatar helpers, event parser, transport. */
2
+ export * from "./types";
3
+ export { initials, avatarColor } from "./initials";
4
+ export { parseChatEvents, CHAT_EVENTS_CONTRACT, type ChatEvent, type ApprovalEvent, type ToolEvent } from "./events";
5
+ export { runTurn, sendApproval, startOver, fetchHistoryPage, ChatHttpError } from "./transport";
@@ -0,0 +1,5 @@
1
+ /** Pure core (no React/MUI): contract types, avatar helpers, event parser, transport. */
2
+ export * from "./types";
3
+ export { initials, avatarColor } from "./initials";
4
+ export { parseChatEvents, CHAT_EVENTS_CONTRACT } from "./events";
5
+ export { runTurn, sendApproval, startOver, fetchHistoryPage, ChatHttpError } from "./transport";
@@ -0,0 +1,5 @@
1
+ /** Avatar helpers: initials from a name/email and a stable accent colour per key. */
2
+ import { type AccentName } from "./types";
3
+ export declare function initials(name: string): string;
4
+ /** Stable FNV-1a hash of `key` onto the accent list. */
5
+ export declare function avatarColor(key: string): AccentName;
@@ -0,0 +1,28 @@
1
+ /** Avatar helpers: initials from a name/email and a stable accent colour per key. */
2
+ import { ACCENTS } from "./types";
3
+ export function initials(name) {
4
+ let s = (name ?? "").trim();
5
+ const at = s.indexOf("@");
6
+ if (at >= 0)
7
+ s = s.slice(0, at);
8
+ const words = s
9
+ .split(/[\s\-_.]+/u)
10
+ .map((w) => w.replace(/[^\p{L}\p{N}]/gu, ""))
11
+ .filter(Boolean)
12
+ .map((w) => Array.from(w));
13
+ if (words.length === 0)
14
+ return "";
15
+ const out = words.length >= 2
16
+ ? words[0][0] + words[words.length - 1][0]
17
+ : words[0].slice(0, 2).join("");
18
+ return out.toUpperCase();
19
+ }
20
+ /** Stable FNV-1a hash of `key` onto the accent list. */
21
+ export function avatarColor(key) {
22
+ let h = 0x811c9dc5;
23
+ for (let i = 0; i < key.length; i++) {
24
+ h ^= key.charCodeAt(i);
25
+ h = Math.imul(h, 0x01000193) >>> 0;
26
+ }
27
+ return ACCENTS[h % ACCENTS.length];
28
+ }
@@ -0,0 +1,20 @@
1
+ /** Transport for the Hermes chat endpoints: streamed turns, approval/new form posts and history paging (CSRF injected). */
2
+ import { type ChatEvent } from "./events";
3
+ import type { CsrfSource, HistoryPage, Target } from "./types";
4
+ /** A non-OK chat reply carrying the server's own `text` (or `error` code) as message. */
5
+ export declare class ChatHttpError extends Error {
6
+ status: number;
7
+ code?: string | undefined;
8
+ name: string;
9
+ constructor(status: number, message: string, code?: string | undefined);
10
+ }
11
+ /** Run one turn; resolves when the stream is over. Throws on transport failure or a stream that ended with no reply/error. */
12
+ export declare function runTurn(url: string, target: Target, message: string, onEvent: (e: ChatEvent) => void, csrf: CsrfSource, signal?: AbortSignal): Promise<void>;
13
+ export declare function sendApproval(url: string, target: Target, a: {
14
+ run_id: string;
15
+ request_id: string;
16
+ execution_generation: string | number;
17
+ }, choice: "once" | "deny", csrf: CsrfSource, signal?: AbortSignal): Promise<boolean>;
18
+ export declare function startOver(url: string, target: Target, csrf: CsrfSource, signal?: AbortSignal): Promise<boolean>;
19
+ /** GET the next older history page (`<url>?<target>&cursor=<c>`); throws `ChatHttpError` (e.g. 400 `bad_cursor`, 404). */
20
+ export declare function fetchHistoryPage(url: string, target: Target, cursor: string, csrf?: CsrfSource, signal?: AbortSignal): Promise<HistoryPage>;
@@ -0,0 +1,89 @@
1
+ /** Transport for the Hermes chat endpoints: streamed turns, approval/new form posts and history paging (CSRF injected). */
2
+ import { parseChatEvents } from "./events";
3
+ /** A non-OK chat reply carrying the server's own `text` (or `error` code) as message. */
4
+ export class ChatHttpError extends Error {
5
+ status;
6
+ code;
7
+ name = "ChatHttpError";
8
+ constructor(status, message, code) {
9
+ super(message);
10
+ this.status = status;
11
+ this.code = code;
12
+ }
13
+ }
14
+ async function formOnce(url, fields, accept, csrf, refresh, signal) {
15
+ const token = await csrf(refresh);
16
+ return fetch(url, {
17
+ method: "POST",
18
+ credentials: "same-origin",
19
+ signal,
20
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: accept, "X-KT-CSRF": token },
21
+ body: new URLSearchParams({ ...fields, csrf: token }).toString(),
22
+ });
23
+ }
24
+ async function isCsrfReject(res) {
25
+ if (res.status !== 403)
26
+ return false;
27
+ const body = (await res.clone().json().catch(() => null));
28
+ const e = body?.error;
29
+ return e === "csrf" || (!!e && typeof e === "object" && e.code === "csrf");
30
+ }
31
+ /** POST a form; on 403 `{error:"csrf"}` retry exactly once with a refreshed token. */
32
+ async function form(url, fields, accept, csrf, signal) {
33
+ const res = await formOnce(url, fields, accept, csrf, false, signal);
34
+ if (await isCsrfReject(res))
35
+ return formOnce(url, fields, accept, csrf, true, signal);
36
+ return res;
37
+ }
38
+ async function httpError(res) {
39
+ const j = (await res.json().catch(() => null));
40
+ const code = typeof j?.error === "string" ? j.error : undefined;
41
+ return new ChatHttpError(res.status, typeof j?.text === "string" ? j.text : "", code);
42
+ }
43
+ /** Run one turn; resolves when the stream is over. Throws on transport failure or a stream that ended with no reply/error. */
44
+ export async function runTurn(url, target, message, onEvent, csrf, signal) {
45
+ const res = await form(url, { ...target, message }, "text/event-stream", csrf, signal);
46
+ if (!res.ok || !res.body)
47
+ throw await httpError(res);
48
+ let finished = false;
49
+ const parser = parseChatEvents((e) => {
50
+ if (e.t === "reply" || e.t === "error")
51
+ finished = true;
52
+ onEvent(e);
53
+ });
54
+ const reader = res.body.getReader();
55
+ const dec = new TextDecoder();
56
+ for (;;) {
57
+ const { value, done } = await reader.read();
58
+ if (done)
59
+ break;
60
+ parser.push(dec.decode(value, { stream: true }));
61
+ }
62
+ parser.push(dec.decode());
63
+ parser.end();
64
+ if (!finished)
65
+ throw new Error("stream ended early");
66
+ }
67
+ export async function sendApproval(url, target, a, choice, csrf, signal) {
68
+ const res = await form(url, { ...target, run_id: a.run_id, request_id: a.request_id, execution_generation: String(a.execution_generation ?? ""), choice }, "application/json", csrf, signal);
69
+ return res.ok;
70
+ }
71
+ export async function startOver(url, target, csrf, signal) {
72
+ const res = await form(url, { ...target }, "application/json", csrf, signal);
73
+ return res.ok || res.redirected;
74
+ }
75
+ /** GET the next older history page (`<url>?<target>&cursor=<c>`); throws `ChatHttpError` (e.g. 400 `bad_cursor`, 404). */
76
+ export async function fetchHistoryPage(url, target, cursor, csrf, signal) {
77
+ const q = new URLSearchParams({ ...target, cursor }).toString();
78
+ const full = url + (url.includes("?") ? "&" : "?") + q;
79
+ const headers = { Accept: "application/json" };
80
+ if (csrf)
81
+ headers["X-KT-CSRF"] = await csrf(false);
82
+ const res = await fetch(full, { method: "GET", credentials: "same-origin", signal, headers });
83
+ if (!res.ok)
84
+ throw await httpError(res);
85
+ const j = (await res.json().catch(() => null));
86
+ const messages = Array.isArray(j?.messages) ? j.messages : [];
87
+ const next = typeof j?.cursor === "string" && j.cursor ? j.cursor : null;
88
+ return { messages, cursor: next, hasMore: j?.has_more === true && next !== null };
89
+ }