@runappsai/agent 0.0.0-stage → 0.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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +162 -2
  3. package/dist/agent-core.umd.js +266 -0
  4. package/dist/agent.d.ts +222 -0
  5. package/dist/agent.js +1331 -0
  6. package/dist/agent.umd.js +732 -0
  7. package/dist/browser.d.ts +2 -0
  8. package/dist/browser.js +4 -0
  9. package/dist/chat-theme.d.ts +24 -0
  10. package/dist/chat-theme.js +101 -0
  11. package/dist/chat.d.ts +271 -0
  12. package/dist/chat.js +4099 -0
  13. package/dist/compaction.d.ts +48 -0
  14. package/dist/compaction.js +208 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.js +88 -0
  17. package/dist/context.d.ts +44 -0
  18. package/dist/context.js +177 -0
  19. package/dist/debug-panel.d.ts +40 -0
  20. package/dist/debug-panel.js +262 -0
  21. package/dist/dialogs.d.ts +7 -0
  22. package/dist/dialogs.js +231 -0
  23. package/dist/directory-fs.d.ts +5 -0
  24. package/dist/directory-fs.js +118 -0
  25. package/dist/dom.d.ts +83 -0
  26. package/dist/dom.js +163 -0
  27. package/dist/edit.d.ts +22 -0
  28. package/dist/edit.js +133 -0
  29. package/dist/file-guard.d.ts +46 -0
  30. package/dist/file-guard.js +153 -0
  31. package/dist/file-tools.d.ts +16 -0
  32. package/dist/file-tools.js +339 -0
  33. package/dist/files-panel.d.ts +60 -0
  34. package/dist/files-panel.js +613 -0
  35. package/dist/index.cjs +4848 -0
  36. package/dist/index.d.ts +37 -0
  37. package/dist/index.js +44 -0
  38. package/dist/json-schema.d.ts +3 -0
  39. package/dist/json-schema.js +141 -0
  40. package/dist/llm.d.ts +95 -0
  41. package/dist/llm.js +5 -0
  42. package/dist/markdown.d.ts +4 -0
  43. package/dist/markdown.js +265 -0
  44. package/dist/mcp.d.ts +82 -0
  45. package/dist/mcp.js +325 -0
  46. package/dist/node.cjs +402 -0
  47. package/dist/node.d.ts +78 -0
  48. package/dist/node.js +432 -0
  49. package/dist/pdf.d.ts +52 -0
  50. package/dist/pdf.js +77 -0
  51. package/dist/provider.d.ts +135 -0
  52. package/dist/provider.js +181 -0
  53. package/dist/sandbox.d.ts +33 -0
  54. package/dist/sandbox.js +219 -0
  55. package/dist/select.d.ts +30 -0
  56. package/dist/select.js +185 -0
  57. package/dist/skill-zips.d.ts +28 -0
  58. package/dist/skill-zips.js +123 -0
  59. package/dist/skills.d.ts +20 -0
  60. package/dist/skills.js +111 -0
  61. package/dist/templates.d.ts +24 -0
  62. package/dist/templates.js +136 -0
  63. package/dist/tool.d.ts +28 -0
  64. package/dist/tool.js +102 -0
  65. package/dist/types.d.ts +571 -0
  66. package/dist/types.js +7 -0
  67. package/dist/ui.cjs +6247 -0
  68. package/dist/ui.d.ts +6 -0
  69. package/dist/ui.js +11 -0
  70. package/dist/vlist.d.ts +80 -0
  71. package/dist/vlist.js +277 -0
  72. package/dist/workspace.d.ts +343 -0
  73. package/dist/workspace.js +1203 -0
  74. package/dist/zip.d.ts +26 -0
  75. package/dist/zip.js +204 -0
  76. package/docs/agent.md +228 -0
  77. package/docs/chat-ui.md +307 -0
  78. package/docs/node.md +135 -0
  79. package/docs/providers.md +176 -0
  80. package/docs/reference.md +143 -0
  81. package/docs/skills.md +131 -0
  82. package/docs/tools.md +254 -0
  83. package/docs/workspace.md +198 -0
  84. package/package.json +59 -4
@@ -0,0 +1,307 @@
1
+ # Chat UI
2
+
3
+ `renderChat(element, options)` turns an element into a complete chat with an agent. Plain DOM, no framework; its styles are injected once. Give the element a height. It comes from `@runappsai/agent/ui` (the browser script has it on `RunAppsAgent`), and runs on the core: the agent, workspace and providers are the ones from `@runappsai/agent`.
4
+
5
+ ```html
6
+ <div id="assistant" style="height: 100vh"></div>
7
+ <script type="module">
8
+ import { openWorkspace, openAIProvider } from "@runappsai/agent";
9
+ import { renderChat } from "@runappsai/agent/ui";
10
+
11
+ const provider = openAIProvider({ baseURL: "/api/llm", models: "fetch" });
12
+ const chat = renderChat(document.getElementById("assistant"), {
13
+ provider,
14
+ appName: "Acme Docs",
15
+ instructions: "You help users write and edit their documents.",
16
+ tools: [myTool],
17
+ workspace: (sessionId) => openWorkspace(provider, { id: sessionId }),
18
+ suggestions: ["Summarise the open document", "/skill:review"],
19
+ });
20
+ await chat.ready;
21
+ </script>
22
+ ```
23
+
24
+ ## What the user gets
25
+
26
+ - **Replies** — streaming Markdown (code blocks with copy, tables, links). While the agent works, the end of the reply shows what it is doing — *Thinking*, *Running code*, *Reading plan.md* — over a few lines that scroll as it goes: its latest thinking, the code being run, a tool's progress. When the run ends, its thinking and tool calls fold into one line, *Worked for 1m 12s ›*, above the answer.
27
+ - **Tool calls** — one quiet line per chain of calls, worded from the tools ("read 2 files, edited 1 file"), opening to a card per call with arguments, result (pictures a tool returned shown under it), duration and status.
28
+ - **Questions** — `ask_user` and confirmations appear inline above the composer; while one waits the composer folds to a line, and answering brings the view back to the latest output. A short chat (under 420 px) keeps its composer compact.
29
+ - **The composer** — Enter sends (the ↵ button appears once there is something to send), Shift+Enter breaks a line. While the agent runs, the ↵ becomes a stop square, Enter **steers** (inserts into the current task) and ⌘↵ / Ctrl+↵ **queues** a follow-up (with typed text, *Steer* and *Follow-up* buttons appear too); queued messages sit in a card above the box with *send now*, *edit* and *remove*.
30
+ - **Attachments** — paperclip, drag and drop, or paste. Files are saved under `/uploads/` in the conversation's directory and named in the message; pictures also go to the model as images — unless the model is known to be text-only: then they stay files and the user is told the model cannot see them. A video (25 MB at most) goes to the model as a video unless the model is known not to take one. Without a directory, a text file or a PDF's text goes into the message itself. 20 MB per file.
31
+ - **Files** — the header's *Files* button opens the directory: a tree, an editor (⌘S, word wrap, Markdown preview), picture and PDF previews, upload, new file, download (folders as zip). File paths in replies open there. Live: changes by the agent show at once.
32
+ - **Skills** — the *Skills* button lists the skills (with a count), uploads zips, removes the user's own.
33
+ - **Chats** — the conversation list (the open one first), new chat, delete. Conversations keep running when you switch away (up to three in the background).
34
+ - **Settings** — the gear: model (with context and output limits, and which models see pictures), thinking level when the model has one, max turns, max output, tool permissions. Kept per app in the browser and applied to every conversation; only what differs from the app's defaults is kept, and a saved model the catalogue no longer lists is dropped (the default applies again).
35
+ - **Reply actions** — hover a reply: copy its answer, *answer again* (rewinds to its question, with the same restore choices, and sends it again), delete the question and its answer; on the right what the reply cost (its `runUsage`, in the model's `price.currency`), the tokens and calls in its tooltip.
36
+ - **Rewind** — hover a user message: when it was sent, copy, *rewind to here* (the conversation after it is dropped, the message goes back into the composer, and the directory's files can be restored to that moment).
37
+ - **How a run ended** — *Stopped.*, the turn limit with *Continue*, an error with *Retry*; kept across reloads until the next run.
38
+ - **Context and spending** — a ring in the header shows how full the model's window is; a click opens a panel with the figures (used / window, model), what the conversation has cost (cost, input and output tokens, calls), when it compacts on its own, and *Compact now*. Older turns are summarised automatically.
39
+ - **Time** — "Today 22:15" above messages that start a conversation or follow a pause.
40
+
41
+ ## Slash commands
42
+
43
+ Typing `/` lists the built-in commands, then the directory's prompt templates and skills.
44
+
45
+ | Command | |
46
+ |---|---|
47
+ | `/help` | The commands |
48
+ | `/new` (`/clear`) | A new conversation |
49
+ | `/resume` | The conversation list |
50
+ | `/compact [focus]` | Summarise older turns now, keeping `focus` above all |
51
+ | `/continue` | Carry on after the turn limit or an error |
52
+ | `/model [name]` | Switch model (no name: open the settings) |
53
+ | `/effort [level]` | Set the thinking level (no level: list them) |
54
+ | `/context` | Model, context use, cost, the directory |
55
+ | `/export` | Download the conversation as Markdown |
56
+ | `/files`, `/settings`, `/debug` | Open those panels |
57
+ | `/name args` | A prompt template from `/prompts/name.md` |
58
+ | `/skill:name args` | Use a skill |
59
+
60
+ ## Options
61
+
62
+ `renderChat` takes every [agent option](agent.md#options) (`model`, `tools`, `instructions`, `permissions`, `compaction`, …) plus:
63
+
64
+ | Option | Default | |
65
+ |---|---|---|
66
+ | `provider` | | A `ModelProvider` (or a RunApps client). |
67
+ | `client` | | A RunApps client — the same as `provider: runappsProvider(client)`. |
68
+ | `workspace` | | A `Workspace` shared by every conversation, or `(sessionId) => Workspace` for a directory per conversation. |
69
+ | `agent` | | Show an `Agent` you built yourself instead (its own `ui` answers questions; no conversation list). |
70
+ | `resume` | `true` | Reopen the conversation this app last had open in this browser; a session id; or `false` for a new one. |
71
+ | `title` | `appName` | Header title; `false` hides the whole header. |
72
+ | `placeholder` | | Composer placeholder. |
73
+ | `emptyState` | | What an empty conversation shows: text, your own element, or `{ icon, title, text, align }`. |
74
+ | `suggestions` | | Starter prompts shown in the empty state. |
75
+ | `sessions` | on with a workspace | The conversation list and *New chat*. `false` (or your own `agent`): one conversation, and a *Clear* button that starts it over. |
76
+ | `skillsMenu` | on with a workspace | The *Skills* button. |
77
+ | `settings` | on | The settings gear. |
78
+ | `attachments` | on | Paperclip, drop and paste. |
79
+ | `uploadsDir` | `/uploads` | Where attachments are saved (with a workspace and file tools; with `fileTools: false` a text file goes into the message itself, so the model can read it). |
80
+ | `showUsage` | on | The context ring in the header and its panel (context use, spending, *Compact now*). |
81
+ | `locale` | the document's | `"en"` or `"zh"`. |
82
+ | `theme` | `"auto"` | `"auto"`, `"light"`, `"dark"`. |
83
+ | `palette` | `"claude"` | `"claude"`, `"violet"`, `"slate"`, `"forest"`, or your own. |
84
+ | `vars` | | Colour and font overrides (see Theming). |
85
+ | `className` | | Extra classes on the chat's root. |
86
+ | `debug` | `false` | The *Debug* panel. |
87
+ | `onOpenFile(path)` | | Open file links yourself instead of in the files panel. |
88
+ | `nextPrompt` | `false` | Suggest the user's next message: the model calls a built-in `suggest_next_prompt` tool with its final reply when an obvious next request follows (it ends the run, so no further call); the suggestion shows greyed in the empty input, Tab takes it, typing or Esc drops it. Needs the chat to own its agent. |
89
+ | `onLink(href, text)` | | Called when a link in the conversation (a reply, its thinking, a tool card) is clicked, before the chat's own handling; return `true` when you handled it (e.g. your app's own documentation links open in your viewer). |
90
+ | `files` | on with a workspace | The *Files* button and panel; `false` for a host with its own file view (links go to `onOpenFile`). |
91
+ | `headerActions` | | Buttons of your own for the header, placed before the settings gear. |
92
+ | `headerEnd` | | Buttons of your own after the settings gear (a close button). |
93
+ | `composerActions` | | Buttons of your own in the composer's toolbar (see below). |
94
+ | `settingsTabs` | | Tabs of your own in the settings panel (see below). |
95
+ | `permissionsSetting` | on | The *Tool permissions* choice in the settings; `false` for an app that decides when to ask itself. |
96
+ | `rewindState` | | `{ label, take(), restore(value) }`: your app's own state (an editor's text, a form) snapshotted as each message is sent; rewinding offers `label` as a checkbox and calls `restore` with that snapshot. Needs a workspace. |
97
+ | `onSession(agent)` | | Called with each conversation's agent as it opens. |
98
+
99
+ ## The empty conversation: a greeting and starter prompts
100
+
101
+ While a conversation is empty the chat shows a line of text and, under it, buttons of starter prompts. Both are yours:
102
+
103
+ ```js
104
+ renderChat(el, {
105
+ provider,
106
+ emptyState: "What can I help you with?", // the text (default "Start a conversation")
107
+ suggestions: [ // the buttons; a click puts the text in the composer
108
+ "Summarise the open document",
109
+ "List what changed this week",
110
+ "/skill:review", // a skill or a template works too
111
+ ],
112
+ });
113
+ ```
114
+
115
+ For an icon, a heading and a line under it, pass them as an object (`icon` is SVG markup or an element; `align: "start"` sets it to the left):
116
+
117
+ ```js
118
+ renderChat(el, {
119
+ provider,
120
+ emptyState: { icon: '<svg viewBox="0 0 24 24">…</svg>', title: "Let's build something useful.", text: "Tell me what it should do.", align: "start" },
121
+ });
122
+ ```
123
+
124
+ `emptyState` can also be an element of your own — any HTML: a logo, a paragraph, links — or `null` for nothing:
125
+
126
+ ```js
127
+ const welcome = document.createElement("div");
128
+ welcome.innerHTML = `<img src="/logo.svg" width="40" alt=""><p>Ask about your orders, invoices or shipping.</p>`;
129
+ renderChat(el, { provider, emptyState: welcome, suggestions: ["Where is my last order?"] });
130
+ ```
131
+
132
+ Leave `suggestions` out for no buttons. The text of a button goes into the composer rather than being sent, so the user can change it first; to send one at once from your own UI, call `chat.prompt(text)`.
133
+
134
+ ## The handle
135
+
136
+ ```js
137
+ const chat = renderChat(el, options);
138
+ await chat.ready; // the first conversation is open
139
+
140
+ chat.agent; // the open conversation's Agent (events, messages, usage…)
141
+ chat.prompt("Hello"); // send as if typed
142
+ chat.setInput("Draft: "); // fill the composer
143
+ chat.insertText("[12] Shot 3"); // put text at the cursor, keeping what was typed
144
+ chat.addContext({ id, label, text }); // a chip in the composer, sent with the next message (below)
145
+ await chat.newSession();
146
+ await chat.resume(id);
147
+ await chat.deleteSession(id);
148
+ await chat.clear(); // start the open conversation over (the Clear button)
149
+ await chat.refresh(); // re-read skills and templates for the / menu
150
+ chat.setDebug(true);
151
+ chat.setAppearance({ theme: "dark", palette: "slate" });
152
+ chat.ui; // the inline dialogs — your own tools can use them
153
+ chat.unmount(); // remove it; agents the chat made are stopped
154
+ ```
155
+
156
+ ### What `unmount()` releases
157
+
158
+ Everything the chat set up for itself: its element, the listeners it put on `document`, `window` and the colour-scheme query, its resize observer, timers and animation frames, open dropdowns and dialogs (a pending question is dismissed), the object URLs of attachment previews, the debug panel's subscriptions. Agents the chat made are aborted, and the workspaces it opened through a `workspace` function are closed (their database connections and the cross-tab channel). A conversation still running in the background is stopped too.
159
+
160
+ What stays, on purpose:
161
+
162
+ - **Yours.** An `agent` or a `workspace` you passed in is not aborted or closed — you made it, you release it (`workspace.close()`).
163
+ - **Shared by the page.** The injected `<style>` (one for every chat on the page); pdf.js and its worker once a PDF was read; the module's caches of parsed skill zips (at most 64) and fetched skill URLs. A later `renderChat` reuses them.
164
+ - **Saved data.** Conversations, files and settings stay in the browser's storage — that is what lets the next mount resume. `workspace.sessions.clear()` or `workspace.destroy()` remove them.
165
+
166
+ `onSession` is the place to attach your own listeners, since every new or resumed conversation has a new agent:
167
+
168
+ ```js
169
+ renderChat(el, {
170
+ provider,
171
+ onSession: (agent) => {
172
+ agent.on("tool_end", (e) => analytics.track("tool", { name: e.name, status: e.status }));
173
+ },
174
+ });
175
+ ```
176
+
177
+ ## Your own pieces: header buttons, `composerTop`, toolbar buttons, the empty state
178
+
179
+ `headerActions` (buttons before the settings gear), `headerEnd` (buttons after it, at the far end — a close or collapse button), `composerTop` (a panel right above the composer — a plan to approve, a status line) and an element given as `emptyState` are yours: you fill and update them (a React portal works), and the chat's own button and input resets do not touch them (they get the class `ra-host`), so your styles apply as they are. Content a tool's `display.render` returns is treated the same way.
180
+
181
+ `composerActions` puts buttons of yours into the composer's toolbar, after the attach button. An element goes in as it is (and keeps your styles); a plain object is drawn like the chat's own toolbar buttons and is changed later by its `id`:
182
+
183
+ ```js
184
+ const chat = renderChat(host, {
185
+ // …
186
+ composerActions: [
187
+ { id: "analyze", label: "Analyse the backtest", icon: "<svg …>", hidden: true,
188
+ onClick: () => chat.prompt("Analyse my latest backtest") },
189
+ ],
190
+ });
191
+ // later, when there is something to analyse
192
+ chat.updateComposerAction("analyze", { hidden: false });
193
+ chat.updateComposerAction("analyze", { disabled: true, label: "Backtest running…" });
194
+ ```
195
+
196
+ `iconOnly: true` draws only the icon, with the label as its tooltip.
197
+
198
+ `settingsTabs` adds tabs of yours to the gear's panel, after the chat's own "Model" tab, so a host needs no second settings button and the panel stays short. In a tab the chat draws a `toggle` or a `select`, reads it back when the user presses Apply (calling `onChange` only for a value that changed) and puts back `default` on Reset; you keep the value and act on it. An element goes in as it is. The panel reopens on the tab last shown.
199
+
200
+ ```js
201
+ renderChat(host, {
202
+ // …
203
+ settingsTabs: [{
204
+ label: "Editor",
205
+ fields: [
206
+ { id: "autoApply", type: "toggle", label: "Apply changes automatically", hint: "Off: ask before every change",
207
+ default: true, value: () => prefs.autoApply, onChange: (v) => { prefs.autoApply = v; save(prefs); } },
208
+ { id: "market", type: "select", label: "Market", options: [{ value: "spot", label: "Spot" }, { value: "swap", label: "Perpetual" }],
209
+ value: () => prefs.market, onChange: (v) => { prefs.market = v; save(prefs); } },
210
+ ],
211
+ }],
212
+ });
213
+ ```
214
+
215
+ ## Context from your page: `addContext`
216
+
217
+ What the user picked or selected in your app — an element in a preview, a passage of a document, a row of a table — goes into the next message as a chip in the composer, beside the attached files:
218
+
219
+ ```js
220
+ const remove = chat.addContext({
221
+ id: "selection", // a later item with the same id replaces this one
222
+ label: "button.primary", // the chip, and the line that names it in the message
223
+ title: "<button class=…>", // the chip's tooltip (default: the label)
224
+ icon: "<svg …>", // the chip's icon (default: a pointer)
225
+ text: JSON.stringify(selection), // what the model reads
226
+ });
227
+ remove(); // take it out again
228
+ ```
229
+
230
+ The user can remove it with its ×; sending takes it, and a message may be only context. The model gets one text part per item after the typed words, `[context] <label>` on the first line and `text` below; the user's bubble shows the chip, not the text. Rewinding to the message puts the items back into the composer. Mark page content as untrusted in `text` yourself when it is.
231
+
232
+ ## One conversation: `sessions: false`
233
+
234
+ An app with one conversation per document or project turns the list off:
235
+
236
+ ```js
237
+ renderChat(el, { provider, workspace: projectWorkspace, sessions: false });
238
+ ```
239
+
240
+ The header then has no *Chats* or *New chat*; a **Clear** button (after a confirmation) starts the conversation over — the messages, the queue and the usage go, the conversation keeps its id, the files stay. `/new` and `/clear` do the same, `/resume` is not offered, and `chat.clear()` does it from your code. A chat showing your own `agent` works the same way.
241
+
242
+ ## Inside your app's layout
243
+
244
+ The chat fills the element you give it and can live in a side panel of your own page. Things to know when it does:
245
+
246
+ - **Moving it** — taking the element out of the page and putting it back (a framework re-render) resets its scroll position, as for any scrolled element. Keep the element where it is, or save `element.querySelector(".ra-log").scrollTop` before and set it after.
247
+ - **Your file view** — `files: false` hides the chat's Files panel; file paths in replies call `onOpenFile(path)`.
248
+ - **Your buttons** — `headerActions: [button]` puts them in the chat's header; give each an `aria-label` (in a narrow chat the labels fold to icons).
249
+ - **Your colours** — `palette: { light: {…}, dark: {…} }` with your page's tokens, and `vars: { font }`.
250
+ - **Your focus styles** — a generic rule of yours such as `textarea:focus-visible { outline: … }` does not reach the composer's text area: the rounded box shows focus.
251
+
252
+ ## Using your own agent
253
+
254
+ ```js
255
+ const agent = createAgent(provider, { tools, workspace, ui: myDialogs });
256
+ renderChat(el, { agent });
257
+ ```
258
+
259
+ The chat shows that agent; it does not make new ones (no conversation list or *New chat*; *Clear* starts it over).
260
+
261
+ ## Theming
262
+
263
+ Every colour and font is a CSS custom property on the chat's root: `--ra-bg`, `--ra-panel`, `--ra-subtle`, `--ra-muted`, `--ra-fg`, `--ra-fg-muted`, `--ra-border`, `--ra-accent`, `--ra-accent-fg`, `--ra-accent-subtle`, `--ra-accent-muted`, `--ra-user-bg`, `--ra-link`, `--ra-ok`, `--ra-red`, `--ra-red-subtle`, `--ra-warn-fg`, `--ra-warn-bg`, `--ra-warn-border`, `--ra-shadow`, `--ra-shadow-md`, `--ra-font`, `--ra-mono`.
264
+
265
+ ```js
266
+ renderChat(el, { provider, palette: "slate", theme: "dark" }); // a built-in palette
267
+ renderChat(el, { provider, vars: { accent: "#e11d48", font: "Inter, sans-serif" } }); // override some tokens
268
+ renderChat(el, { provider, vars: { light: { bg: "#fff" }, dark: { bg: "#0b0b0c" } } }); // per scheme
269
+ renderChat(el, { provider, palette: { light: { accent: "#0a7" }, dark: { accent: "#3c9" } } }); // your own palette
270
+ chat.setAppearance({ palette: "forest", theme: "light" }); // live
271
+ ```
272
+
273
+ Or from your stylesheet — the chat's own rules weigh nothing, so yours win:
274
+
275
+ ```css
276
+ .ra-chat { --ra-accent: #e11d48; --ra-font: "Inter", sans-serif; }
277
+ .ra-chat[data-scheme="dark"] { --ra-bg: #0b0b0c; }
278
+ .ra-chat .ra-bubble { border-radius: 8px; } /* restyle a part */
279
+ ```
280
+
281
+ ## Dropdowns for your page
282
+
283
+ The settings menu uses the chat's own dropdown. Use it in your page too:
284
+
285
+ ```js
286
+ import { selectBox, enhanceSelect } from "@runappsai/agent/ui";
287
+
288
+ // Give an existing <select> the same look; its .value and change events keep working.
289
+ const lang = enhanceSelect(document.querySelector("#language"), document.querySelector("aside"));
290
+ lang.destroy(); // later: the plain <select> again
291
+
292
+ // Or build one.
293
+ const box = selectBox(document.querySelector("aside"), {
294
+ options: [{ value: "en", label: "English" }, { value: "zh", label: "中文", note: "Chinese" }],
295
+ value: "en",
296
+ });
297
+ box.el.addEventListener("change", () => console.log(box.value));
298
+ container.append(box.el);
299
+ box.close(); // close its list (it closes itself on a choice, Escape or a click outside)
300
+ ```
301
+
302
+ The second argument is where the list opens: a positioned element (`position: relative`) with the class **`ra-ui`**, which gives it the chat's colours (dark follows the system unless `data-scheme="light"`; `data-palette` picks a palette).
303
+
304
+ ## Debug
305
+
306
+ `debug: true` (or `chat.setDebug(true)`) adds a *Debug* button: the call chain run by run and turn by turn, every request sent to the model and what came back, the event log, the context (system prompt, messages, limits) and the tools declared to the model.
307
+
package/docs/node.md ADDED
@@ -0,0 +1,135 @@
1
+ # Node and the command line
2
+
3
+ The core (`@runappsai/agent`) runs in Node as it is. What a browser gives it for free — IndexedDB to keep things, dialogs to ask the user — `@runappsai/agent/node` provides for Node 18+:
4
+
5
+ | | |
6
+ |---|---|
7
+ | `nodeFS(folder, options)` | A folder on disk as the workspace's directory. |
8
+ | `nodeStore(folder)` | The workspace's storage on disk: sessions, the user's skills, meta data (and the files, when there is no `dir`). |
9
+ | `terminalUI(options)` | Confirmations, choices and questions in the terminal. |
10
+ | `lineReader(options)` | One queued reader of the terminal's lines, shared by your prompt loop and `terminalUI`. |
11
+ | `nodePdf()` | PDFs read with the `pdfjs-dist` package. |
12
+
13
+ ## A command-line agent
14
+
15
+ ```js
16
+ import { createAgent, openAIProvider, openWorkspace } from "@runappsai/agent";
17
+ import { nodeFS, nodeStore, terminalUI } from "@runappsai/agent/node";
18
+
19
+ const provider = openAIProvider({
20
+ baseURL: process.env.OPENAI_BASE_URL ?? "https://api.openai.com/v1",
21
+ apiKey: process.env.OPENAI_API_KEY,
22
+ models: "fetch",
23
+ });
24
+
25
+ const workspace = await openWorkspace(provider, {
26
+ project: "my-cli", // names the storage
27
+ id: `dir:${process.cwd()}`, // one set of sessions per folder
28
+ dir: nodeFS(process.cwd()), // the agent reads and writes this folder
29
+ store: nodeStore(), // ~/.runapps-agent/…
30
+ });
31
+
32
+ const agent = createAgent(provider, {
33
+ workspace,
34
+ ui: terminalUI(),
35
+ instructions: "You are a coding assistant in the user's project. Be brief.",
36
+ });
37
+
38
+ agent.on("text_delta", (e) => process.stdout.write(e.delta));
39
+ agent.on("tool_start", (e) => process.stdout.write(`\n⚙ ${e.name}`));
40
+ agent.on("tool_end", (e) => process.stdout.write(e.status === "ok" ? " ✓" : ` ${e.status}`));
41
+
42
+ const result = await agent.prompt(process.argv.slice(2).join(" ") || "What is in this folder?");
43
+ console.log(`\n${result.reason} · ${agent.usage.calls} calls`);
44
+ ```
45
+
46
+ `examples/cli.mjs` is a complete terminal chat built this way: a prompt loop, streaming thinking and text, tool lines, `/new`, `/sessions`, `/resume <id>`, `/compact`, `--resume` to continue the last conversation in a folder, and Ctrl+C to stop the running task.
47
+
48
+ ```sh
49
+ OPENAI_BASE_URL=https://api.deepseek.com/v1 OPENAI_API_KEY=sk-… node examples/cli.mjs --dir ./my-project
50
+ ```
51
+
52
+ ## `nodeFS(folder, options)`
53
+
54
+ ```js
55
+ nodeFS("/path/to/project", {
56
+ description: "the user's project", // what the model is told the folder is
57
+ readonly: false, // true: no write or delete
58
+ ignore: [".git", "node_modules"], // folder names left out of listings and searches (the default)
59
+ })
60
+ ```
61
+
62
+ Paths cannot leave the folder: `/../x` is refused, and so is a path that goes through a symbolic link pointing outside it (links are not listed either). `nodeFS("/")` makes the whole disk the folder. A file reads as text when it is UTF-8 without control characters, as bytes otherwise.
63
+
64
+ ## `nodeStore(folder)`
65
+
66
+ ```js
67
+ nodeStore() // ~/.runapps-agent
68
+ nodeStore("./.agent-data") // somewhere of your own
69
+ ```
70
+
71
+ Without a store, a workspace in Node keeps everything in memory, and it is gone when the process ends. With one, the layout is:
72
+
73
+ ```
74
+ <folder>/<app>/spaces/<directory id>/files/… the directory's files (when there is no `dir`)
75
+ <folder>/<app>/spaces/<directory id>/meta/*.json its meta data
76
+ <folder>/<app>/spaces/%00skills/files/… the user's skills (/skills/)
77
+ <folder>/<app>/sessions/<directory id>/<session>.json
78
+ ```
79
+
80
+ Files are written to a temporary name and renamed, so a crash never leaves half a file. It is meant for one process at a time per folder.
81
+
82
+ Any storage works the same way: implement `WorkspaceStoreFactory` (`open(dbName, space)` → a `WorkspaceStore`) and pass it as `store` — a database, a cloud bucket. `nodeStore` in `src/node.ts` is a complete example; its optional `stat` and `listStats` let the workspace list and check files without reading their contents. Ids are percent-encoded into names (dots too), so no id can point outside its folder.
83
+
84
+ ## `terminalUI(options)`
85
+
86
+ ```js
87
+ terminalUI() // process.stdin / process.stdout (through lineReader)
88
+ terminalUI({ input, output }) // other streams
89
+ terminalUI({ ask: reader.ask }) // the reader your own prompt loop uses
90
+ terminalUI({ ask: (prompt, signal) => … }) // any input of yours: write prompt, resolve the line (null: dismissed)
91
+ terminalUI({ rl }) // a readline interface (its question(); lines typed ahead are lost)
92
+ ```
93
+
94
+ - `confirm` — `Delete /notes.md? … [y/N]`; only y / yes counts.
95
+ - `select` — a numbered list; a number (or several, comma-separated, when multiple answers are allowed), or free text when the question allows it.
96
+ - `input` — a line; multi-line answers end with a blank line.
97
+ - `notify` — a line with `i`, `!` or `✗`.
98
+
99
+ A question whose run is stopped is dismissed.
100
+
101
+ ### Reading lines: `lineReader`
102
+
103
+ readline's own `question()` loses a line that arrives while nobody is asking — typed ahead while the agent works, or piped in. `lineReader()` queues them: each `ask(prompt)` gets the next line, whenever it came, and questions asked at the same time (two tools asking at once) are answered in turn. There is one reader per input stream, so your prompt loop and `terminalUI` take turns on the same queue. The prompt goes through readline, so it stays on screen while the user edits the line. A terminal keeps being read between questions — Ctrl+C reaches the reader's `rl` "SIGINT" event even while the agent runs — without keeping the process alive; a pipe is paused between questions.
104
+
105
+ ```js
106
+ import { lineReader, terminalUI } from "@runappsai/agent/node";
107
+
108
+ const reader = lineReader(); // process.stdin / stdout
109
+ const ui = terminalUI({ ask: reader.ask }); // the agent's questions read from the same queue
110
+ reader.rl.on("SIGINT", () => agent.busy ? agent.abort() : process.exit(0)); // Ctrl+C
111
+
112
+ for (;;) {
113
+ const line = await reader.ask("› ");
114
+ if (line === null) break; // the input ended
115
+ await agent.prompt(line);
116
+ }
117
+ reader.close();
118
+ ```
119
+
120
+ ## PDFs
121
+
122
+ The browser loads pdf.js from a CDN; Node cannot. Install it and switch to it once at start-up:
123
+
124
+ ```sh
125
+ npm i pdfjs-dist
126
+ ```
127
+
128
+ ```js
129
+ import { nodePdf } from "@runappsai/agent/node";
130
+ nodePdf();
131
+ ```
132
+
133
+ ## The sandbox
134
+
135
+ `run_js` runs in Node through `worker_threads`, with the same limits as in a browser: no network, a time limit, `fs` bound to the workspace. Remove it with `sandbox: false`.
@@ -0,0 +1,176 @@
1
+ # Providers
2
+
3
+ The agent never talks to a model API directly. It calls a **`ModelProvider`**: an object with one required method that streams a Chat Completions call. Two providers come with the package, and you can write your own in a few lines.
4
+
5
+ ```js
6
+ createAgent(provider, options)
7
+ renderChat(element, { provider, ... })
8
+ openWorkspace(provider, options) // the provider is only needed for `files:` skill sources and the storage name
9
+ ```
10
+
11
+ ## `openAIProvider` — any OpenAI-compatible API
12
+
13
+ ```js
14
+ import { openAIProvider } from "@runappsai/agent";
15
+
16
+ const provider = openAIProvider({
17
+ baseURL: "https://api.openai.com/v1", // the API root; /chat/completions is appended
18
+ apiKey: "sk-…", // sent as Authorization: Bearer …
19
+ models: "fetch", // optional: read GET /models for the model list
20
+ });
21
+ ```
22
+
23
+ It uses plain `fetch` and parses the server-sent event stream itself, so it works in browsers, Node 18+, Deno and workers.
24
+
25
+ | Option | |
26
+ |---|---|
27
+ | `baseURL` | API root, e.g. `https://api.openai.com/v1`, `https://api.deepseek.com/v1`, `https://openrouter.ai/api/v1`, `http://localhost:11434/v1` (Ollama), or a path on your own server (`/api/llm`). |
28
+ | `apiKey` | Optional. Leave it out when your proxy adds the key. |
29
+ | `headers` | More request headers. An `Authorization` here replaces the one from `apiKey`. |
30
+ | `models` | The catalogue: an array of `ModelInfo`, `"fetch"` for `GET /models` (ids, plus limits and capability where the endpoint lists them), or nothing. |
31
+ | `streamUsage` | Ask for `usage` in the last chunk (`stream_options.include_usage`). Default `true`; set `false` for servers that reject the field. |
32
+ | `fetch` | A `fetch` of your own (tests, a proxy-aware one). |
33
+ | `name` | Names the app's IndexedDB storage when `openWorkspace` gets no `project`. |
34
+
35
+ ### Don't put API keys in a page
36
+
37
+ Anyone can read a key shipped to the browser. Put the key on your server and let the page call a small proxy that forwards to the provider:
38
+
39
+ ```js
40
+ // Browser
41
+ const provider = openAIProvider({ baseURL: "/api/llm", models: [
42
+ { id: "gpt-4.1", is_default: true, max_input_tokens: 1_000_000, max_tokens: 32_768 },
43
+ { id: "gpt-4.1-mini", max_input_tokens: 1_000_000, max_tokens: 32_768 },
44
+ ] });
45
+ ```
46
+
47
+ ```js
48
+ // Server (Express): forward the request body and stream the answer back.
49
+ app.post("/api/llm/chat/completions", async (req, res) => {
50
+ if (!req.user) return res.status(401).end(); // your own auth
51
+ const upstream = await fetch("https://api.openai.com/v1/chat/completions", {
52
+ method: "POST",
53
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
54
+ body: JSON.stringify(req.body),
55
+ });
56
+ res.status(upstream.status);
57
+ res.setHeader("Content-Type", upstream.headers.get("Content-Type") ?? "application/json");
58
+ for await (const chunk of upstream.body) res.write(chunk);
59
+ res.end();
60
+ });
61
+ ```
62
+
63
+ ### Telling the agent about models
64
+
65
+ With `models`, the agent knows each model's context window (`max_input_tokens`) and longest reply (`max_tokens`): it sizes replies to the model's maximum, compacts the conversation before the window is full, and the chat's settings menu offers the list. Without it, the agent assumes a 128 000-token window and 8 192-token replies.
66
+
67
+ A model may also carry its `price`: `{ input, output }` per million tokens, `per_call` for a fixed amount added to each call, and `currency` (an ISO code, default `"USD"`). The chat shows it in the settings and in `/context`, and shows spending in that currency — so a provider's `usage.total_cost` must be in it too.
68
+
69
+ ```js
70
+ const models = [
71
+ {
72
+ id: "deepseek-reasoner",
73
+ is_default: true, // used when the agent names no model
74
+ capability: "text", // "text" and "vision" models are offered in the chat's picker
75
+ max_input_tokens: 128_000,
76
+ max_tokens: 64_000,
77
+ input_modalities: ["text"], // what it takes: add "image" (or "video", "audio") for a model that sees them
78
+ options: { inputs: { reasoning_effort: { enum: ["low", "medium", "high"], default: "medium" } } },
79
+ },
80
+ ];
81
+ ```
82
+
83
+ `options.inputs.reasoning_effort` lists the thinking levels a model takes; the chat's settings menu offers them and sends the choice as `reasoning_effort`.
84
+
85
+ `input_modalities` says what a model takes besides text (RunApps' `/v1/models` lists it for every model; a `vision` capability also counts as pictures). `modelAccepts(model, "image")` reads it: `true`, `false`, or `undefined` when the catalogue does not say. See [Pictures and models that see them](agent.md#pictures-and-models-that-see-them).
86
+
87
+ ## `runappsProvider` — RunApps
88
+
89
+ With the [RunApps SDK](https://github.com/runapps/sdk-js), users sign in with RunApps and pay for their own usage; the model catalogue (with limits and thinking levels), cost per call and `files:` storage come from the platform.
90
+
91
+ ```html
92
+ <script src="https://www.runapps.ai/sdk/latest.js"></script>
93
+ <script>
94
+ const client = new RunApps({ project: "my-app" }); // your app's slug
95
+ const provider = RunAppsAgent.runappsProvider(client);
96
+ </script>
97
+ ```
98
+
99
+ Passing the client itself works everywhere a provider is expected — `createAgent(client)`, `renderChat(el, { client })`, `openWorkspace(client, …)` — it is wrapped for you. The client's project also names the app's IndexedDB storage.
100
+
101
+ ## Writing your own
102
+
103
+ A provider is any object with a `stream` method. This one wraps a server endpoint that answers with OpenAI chunks, one JSON object per line:
104
+
105
+ ```js
106
+ import { ProviderError } from "@runappsai/agent";
107
+
108
+ const provider = {
109
+ name: "my-app",
110
+ async *stream(params, { signal } = {}) {
111
+ const res = await fetch("/api/chat", { method: "POST", body: JSON.stringify(params), signal });
112
+ if (!res.ok) throw new ProviderError(res.status, await res.text(), { retryAfter: Number(res.headers.get("Retry-After")) || undefined });
113
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
114
+ let buf = "";
115
+ for (;;) {
116
+ const { done, value } = await reader.read();
117
+ if (done) break;
118
+ buf += value;
119
+ let nl;
120
+ while ((nl = buf.indexOf("\n")) >= 0) {
121
+ const line = buf.slice(0, nl).trim();
122
+ buf = buf.slice(nl + 1);
123
+ if (line) yield JSON.parse(line);
124
+ }
125
+ }
126
+ },
127
+ async models() {
128
+ return [{ id: "my-model", is_default: true, max_input_tokens: 200_000, max_tokens: 16_000 }];
129
+ },
130
+ };
131
+ ```
132
+
133
+ If your endpoint speaks server-sent events, `sseData(response.body, signal)` (exported) yields each event's `data:` payload.
134
+
135
+ ### The interface
136
+
137
+ ```ts
138
+ interface ModelProvider {
139
+ /** Required: one streamed chat completion. */
140
+ stream(params: ChatCompletionParams, init?: { signal?: AbortSignal }): AsyncIterable<ChatCompletionChunk>;
141
+ /** A whole completion (used to write compaction summaries). Without it, stream() is collected. */
142
+ complete?(params: ChatCompletionParams, init?: { signal?: AbortSignal }): Promise<ChatCompletion>;
143
+ /** The model catalogue. Without it: 128k window, 8k replies, no model list in the settings. */
144
+ models?(opts?: { capability?: string }): Promise<ModelInfo[]>;
145
+ /** A file from your storage, for `files:<path>` skill sources; answer null when `etag` still matches. */
146
+ readFile?(path: string, opts?: { etag?: string }): Promise<{ bytes: Uint8Array; etag?: string } | null>;
147
+ /** Names the app's IndexedDB storage when openWorkspace gets no `project`. */
148
+ name?: string;
149
+ }
150
+ ```
151
+
152
+ **What `stream` receives** — an OpenAI Chat Completions request:
153
+
154
+ - `model` — absent when the agent names no model (your provider picks its default).
155
+ - `messages` — `system`, `user` (text, or content parts with `image_url` pictures), `assistant` (with `tool_calls`, and `reasoning_content` for thinking models on tool-calling turns), `tool` (results).
156
+ - `tools` — function definitions with JSON Schema parameters.
157
+ - `max_tokens`, sometimes `reasoning_effort`, `temperature`, `top_p`, and whatever the app put in `extra`.
158
+
159
+ **What it yields** — OpenAI `chat.completion.chunk` objects:
160
+
161
+ - `choices[0].delta.content` — text.
162
+ - `choices[0].delta.reasoning_content` (or `reasoning`) — the model's thinking, shown folded.
163
+ - `choices[0].delta.tool_calls` — tool call fragments, joined by `index` (`id` and `function.name` in the first fragment, `function.arguments` spread over several).
164
+ - `choices[0].finish_reason` — `"stop"`, `"tool_calls"`, `"length"`. A stream that ends without one is treated as cut off, and its tool calls are not run.
165
+ - `usage` — `prompt_tokens`, `completion_tokens`, and `total_cost` in USD if you know it (`agent.usage` adds them up).
166
+
167
+ ### Errors and retries
168
+
169
+ Throw a `ProviderError(status, message, { code, retryAfter })` — or any error with a numeric `status` or `statusCode` — when a call fails:
170
+
171
+ | Status | What the agent does |
172
+ |---|---|
173
+ | `408`, `429`, `5xx`, `0` (no answer, network) | Tries again with backoff — three attempts in all — waiting `retryAfter` seconds when given. Text already shown is discarded first (`message_reset` event). |
174
+ | anything else | Ends the run with `reason: "error"`; the chat shows the message with a Retry button. |
175
+
176
+ Errors without a status are retried only when they look like network failures.