mui-hermes-chat 0.0.0-stage → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +103 -2
- package/dist/adapter/adapter.d.ts +22 -0
- package/dist/adapter/adapter.js +183 -0
- package/dist/adapter/index.d.ts +2 -0
- package/dist/adapter/index.js +2 -0
- package/dist/core/events.d.ts +59 -0
- package/dist/core/events.js +57 -0
- package/dist/core/index.d.ts +5 -0
- package/dist/core/index.js +5 -0
- package/dist/core/initials.d.ts +5 -0
- package/dist/core/initials.js +28 -0
- package/dist/core/transport.d.ts +20 -0
- package/dist/core/transport.js +89 -0
- package/dist/core/types.d.ts +58 -0
- package/dist/core/types.js +2 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +9 -0
- package/dist/react/avatar/ParticipantAvatar.d.ts +6 -0
- package/dist/react/avatar/ParticipantAvatar.js +25 -0
- package/dist/react/avatar/accent.d.ts +3 -0
- package/dist/react/avatar/accent.js +9 -0
- package/dist/react/avatar/index.d.ts +3 -0
- package/dist/react/avatar/index.js +3 -0
- package/dist/react/chat/Approval.d.ts +11 -0
- package/dist/react/chat/Approval.js +41 -0
- package/dist/react/chat/HermesChat.d.ts +43 -0
- package/dist/react/chat/HermesChat.js +124 -0
- package/dist/react/chat/index.d.ts +6 -0
- package/dist/react/chat/index.js +6 -0
- package/dist/react/chat/labels.d.ts +41 -0
- package/dist/react/chat/labels.js +42 -0
- package/dist/react/chat/parts.d.ts +41 -0
- package/dist/react/chat/parts.js +112 -0
- package/dist/react/chat/useFitHeight.d.ts +12 -0
- package/dist/react/chat/useFitHeight.js +42 -0
- package/dist/react/composer/ChatComposer.d.ts +7 -0
- package/dist/react/composer/ChatComposer.js +44 -0
- package/dist/react/composer/JumpToLatest.d.ts +4 -0
- package/dist/react/composer/JumpToLatest.js +26 -0
- package/dist/react/composer/SendOrStopButton.d.ts +9 -0
- package/dist/react/composer/SendOrStopButton.js +22 -0
- package/dist/react/composer/index.d.ts +6 -0
- package/dist/react/composer/index.js +6 -0
- package/dist/react/composer/labels.d.ts +10 -0
- package/dist/react/composer/labels.js +8 -0
- package/dist/react/composer/slots.d.ts +8 -0
- package/dist/react/composer/slots.js +12 -0
- package/dist/react/info/SessionInfo.d.ts +37 -0
- package/dist/react/info/SessionInfo.js +91 -0
- package/dist/react/info/index.d.ts +3 -0
- package/dist/react/info/index.js +2 -0
- package/dist/react/tools/JsonTree.d.ts +8 -0
- package/dist/react/tools/JsonTree.js +25 -0
- package/dist/react/tools/ToolDetailDrawer.d.ts +9 -0
- package/dist/react/tools/ToolDetailDrawer.js +47 -0
- package/dist/react/tools/ToolPreviewView.d.ts +6 -0
- package/dist/react/tools/ToolPreviewView.js +32 -0
- package/dist/react/tools/ToolRow.d.ts +11 -0
- package/dist/react/tools/ToolRow.js +45 -0
- package/dist/react/tools/ToolStepGroup.d.ts +10 -0
- package/dist/react/tools/ToolStepGroup.js +28 -0
- package/dist/react/tools/family.d.ts +19 -0
- package/dist/react/tools/family.js +107 -0
- package/dist/react/tools/format.d.ts +19 -0
- package/dist/react/tools/format.js +37 -0
- package/dist/react/tools/icons.d.ts +5 -0
- package/dist/react/tools/icons.js +25 -0
- package/dist/react/tools/index.d.ts +10 -0
- package/dist/react/tools/index.js +10 -0
- package/dist/react/tools/labels.d.ts +23 -0
- package/dist/react/tools/labels.js +7 -0
- package/dist/react/tools/toolPreview.d.ts +74 -0
- package/dist/react/tools/toolPreview.js +156 -0
- 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
|
-
#
|
|
1
|
+
# mui-hermes-chat
|
|
2
2
|
|
|
3
|
-
|
|
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,22 @@
|
|
|
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
|
+
export declare const USER_AUTHOR_ID = "user";
|
|
16
|
+
export declare const AGENT_AUTHOR_ID = "hermes";
|
|
17
|
+
/**
|
|
18
|
+
* History rows → x-chat messages. User: one text part. Assistant: a `data-tools` part (`HermesToolCall[]`)
|
|
19
|
+
* when it carries tools, then a `data-reply` part (`{text, html}`) when it has html, else a text part.
|
|
20
|
+
*/
|
|
21
|
+
export declare function toChatMessages(messages: HermesMessage[]): ChatMessage[];
|
|
22
|
+
export declare function hermesChatAdapter(opts: HermesAdapterOptions): ChatAdapter;
|
|
@@ -0,0 +1,183 @@
|
|
|
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
|
+
export const USER_AUTHOR_ID = "user";
|
|
15
|
+
export const AGENT_AUTHOR_ID = "hermes";
|
|
16
|
+
/**
|
|
17
|
+
* History rows → x-chat messages. User: one text part. Assistant: a `data-tools` part (`HermesToolCall[]`)
|
|
18
|
+
* when it carries tools, then a `data-reply` part (`{text, html}`) when it has html, else a text part.
|
|
19
|
+
*/
|
|
20
|
+
export function toChatMessages(messages) {
|
|
21
|
+
return messages.map((m) => {
|
|
22
|
+
const parts = [];
|
|
23
|
+
if (m.role === "assistant") {
|
|
24
|
+
if (m.tools?.length)
|
|
25
|
+
parts.push({ type: "data-tools", id: `${m.id}-tools`, data: m.tools });
|
|
26
|
+
if (m.html)
|
|
27
|
+
parts.push({ type: "data-reply", id: "reply", data: { text: m.text, html: m.html } });
|
|
28
|
+
else if (m.text)
|
|
29
|
+
parts.push({ type: "text", text: m.text });
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
parts.push({ type: "text", text: m.text });
|
|
33
|
+
}
|
|
34
|
+
// Author ids match `currentUser`/`members` in HermesChat: x-chat decides viewer ownership by author id.
|
|
35
|
+
const author = { id: m.role === "user" ? USER_AUTHOR_ID : AGENT_AUTHOR_ID };
|
|
36
|
+
const msg = { id: m.id, role: m.role, author, parts, status: "sent" };
|
|
37
|
+
if (typeof m.created === "number")
|
|
38
|
+
msg.createdAt = new Date(m.created * 1000).toISOString();
|
|
39
|
+
return msg;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
export function hermesChatAdapter(opts) {
|
|
43
|
+
const seen = new Set();
|
|
44
|
+
const fresh = (ms) => ms.filter((m) => {
|
|
45
|
+
if (!m?.id || seen.has(m.id))
|
|
46
|
+
return false;
|
|
47
|
+
seen.add(m.id);
|
|
48
|
+
return true;
|
|
49
|
+
});
|
|
50
|
+
const result = (page, ms) => ({
|
|
51
|
+
messages: toChatMessages(ms),
|
|
52
|
+
cursor: page.cursor ?? undefined,
|
|
53
|
+
hasMore: page.hasMore && page.cursor !== null,
|
|
54
|
+
});
|
|
55
|
+
return {
|
|
56
|
+
async listMessages({ cursor }) {
|
|
57
|
+
if (cursor === undefined) {
|
|
58
|
+
// Initial load: the newest page the read model already carries.
|
|
59
|
+
seen.clear();
|
|
60
|
+
const page = opts.initialPage ?? { messages: [], cursor: null, hasMore: false };
|
|
61
|
+
return result(page, fresh(page.messages));
|
|
62
|
+
}
|
|
63
|
+
if (!opts.urls.messages)
|
|
64
|
+
return { messages: [], hasMore: false };
|
|
65
|
+
const page = await fetchHistoryPage(opts.urls.messages, opts.target, cursor, opts.csrf);
|
|
66
|
+
return result(page, fresh(page.messages));
|
|
67
|
+
},
|
|
68
|
+
async sendMessage({ message, signal }) {
|
|
69
|
+
const text = message.parts.map((p) => (p.type === "text" ? p.text : "")).join("");
|
|
70
|
+
const messageId = nextId("hermes");
|
|
71
|
+
let closed = false;
|
|
72
|
+
return new ReadableStream({
|
|
73
|
+
start(c) {
|
|
74
|
+
let textId = "";
|
|
75
|
+
let reasonId = "";
|
|
76
|
+
/** Open tool calls: event `id` (v2) or tool name (v1) → toolCallId. */
|
|
77
|
+
const tools = new Map();
|
|
78
|
+
const closeText = () => {
|
|
79
|
+
if (textId) {
|
|
80
|
+
c.enqueue({ type: "text-end", id: textId });
|
|
81
|
+
textId = "";
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
const closeReason = () => {
|
|
85
|
+
if (reasonId) {
|
|
86
|
+
c.enqueue({ type: "reasoning-end", id: reasonId });
|
|
87
|
+
reasonId = "";
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
const finish = (reason) => {
|
|
91
|
+
if (closed)
|
|
92
|
+
return;
|
|
93
|
+
closeReason();
|
|
94
|
+
closeText();
|
|
95
|
+
c.enqueue({ type: "finish", messageId, finishReason: reason });
|
|
96
|
+
closed = true;
|
|
97
|
+
c.close();
|
|
98
|
+
};
|
|
99
|
+
c.enqueue({ type: "start", messageId });
|
|
100
|
+
const onTool = (e) => {
|
|
101
|
+
const st = e.state || "start";
|
|
102
|
+
const key = e.id ?? e.name;
|
|
103
|
+
let id = tools.get(key);
|
|
104
|
+
if (st === "start" || !id) {
|
|
105
|
+
id = e.id ?? nextId("tool");
|
|
106
|
+
tools.set(key, id);
|
|
107
|
+
c.enqueue({ type: "tool-input-start", toolCallId: id, toolName: e.name });
|
|
108
|
+
c.enqueue({ type: "tool-input-available", toolCallId: id, toolName: e.name, input: toolInput(e) });
|
|
109
|
+
}
|
|
110
|
+
if (st === "done") {
|
|
111
|
+
c.enqueue({ type: "tool-output-available", toolCallId: id, output: toolOutput(e) });
|
|
112
|
+
tools.delete(key);
|
|
113
|
+
}
|
|
114
|
+
else if (st === "failed") {
|
|
115
|
+
c.enqueue({ type: "tool-output-error", toolCallId: id, errorText: e.result_preview || "failed" });
|
|
116
|
+
tools.delete(key);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const on = (e) => {
|
|
120
|
+
if (closed)
|
|
121
|
+
return;
|
|
122
|
+
switch (e.t) {
|
|
123
|
+
case "delta":
|
|
124
|
+
closeReason();
|
|
125
|
+
if (!textId) {
|
|
126
|
+
textId = nextId("t");
|
|
127
|
+
c.enqueue({ type: "text-start", id: textId });
|
|
128
|
+
}
|
|
129
|
+
c.enqueue({ type: "text-delta", id: textId, delta: e.text });
|
|
130
|
+
break;
|
|
131
|
+
case "thinking":
|
|
132
|
+
if (!reasonId) {
|
|
133
|
+
reasonId = nextId("r");
|
|
134
|
+
c.enqueue({ type: "reasoning-start", id: reasonId });
|
|
135
|
+
}
|
|
136
|
+
c.enqueue({ type: "reasoning-delta", id: reasonId, delta: e.text });
|
|
137
|
+
break;
|
|
138
|
+
case "commentary":
|
|
139
|
+
closeReason();
|
|
140
|
+
closeText();
|
|
141
|
+
c.enqueue({ type: "data-commentary", id: nextId("c"), data: { text: e.text } });
|
|
142
|
+
break;
|
|
143
|
+
case "tool":
|
|
144
|
+
onTool(e);
|
|
145
|
+
break;
|
|
146
|
+
case "approval":
|
|
147
|
+
c.enqueue({ type: "data-approval", id: e.request_id, data: e });
|
|
148
|
+
break;
|
|
149
|
+
case "reply":
|
|
150
|
+
closeText();
|
|
151
|
+
c.enqueue({ type: "data-reply", id: "reply", data: { text: e.text, html: e.html } });
|
|
152
|
+
break;
|
|
153
|
+
case "error":
|
|
154
|
+
c.enqueue({ type: "data-error", id: "error", data: { text: e.text || "Something went wrong.", code: e.code } });
|
|
155
|
+
break;
|
|
156
|
+
case "end":
|
|
157
|
+
finish("stop");
|
|
158
|
+
break;
|
|
159
|
+
default:
|
|
160
|
+
break; // `run` carries only the run id; unknown frames are ignored
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
runTurn(opts.urls.turn, opts.target, text, on, opts.csrf, signal).then(() => finish("stop"), (err) => {
|
|
164
|
+
if (closed)
|
|
165
|
+
return;
|
|
166
|
+
if (signal.aborted) {
|
|
167
|
+
closed = true;
|
|
168
|
+
c.enqueue({ type: "abort", messageId });
|
|
169
|
+
c.close();
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const msg = err instanceof ChatHttpError ? err.message : "";
|
|
173
|
+
on({ t: "error", text: msg || opts.networkErrorText || NOTE_NETWORK });
|
|
174
|
+
finish("error");
|
|
175
|
+
});
|
|
176
|
+
},
|
|
177
|
+
cancel() {
|
|
178
|
+
closed = true;
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
@@ -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
|
+
}
|