@rungent/react 0.0.0 → 0.6.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.
package/dist/index.js ADDED
@@ -0,0 +1,3643 @@
1
+ import { a as submitFormAnswers, c as attachmentsOf, d as reduceThread, f as RungentRequestError, h as checkAnswers, i as submitForm, l as initialThreadState, n as answerInput, o as appendUserMessage, r as cancelAll, s as attachmentPart, t as answerApproval } from "./client-BxNE_rPk.js";
2
+ import { createContext, memo, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
3
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
+ import ReactMarkdown from "react-markdown";
5
+ import remarkGfm from "remark-gfm";
6
+ // src/dock-state.ts
7
+ /**
8
+ * The dock's state, kept outside React so that it survives the dock being mounted again (a host
9
+ * that re-renders or remounts its layout on navigation) and its first paint is already final:
10
+ * a mounted dock reads it synchronously instead of restoring it in an effect.
11
+ */
12
+ /** The panel's width: its default, and the range the user can drag it in. */
13
+ const DOCK_WIDTH = {
14
+ initial: 420,
15
+ min: 360,
16
+ max: 640
17
+ };
18
+ const DEFAULTS = {
19
+ open: false,
20
+ threadId: null,
21
+ width: DOCK_WIDTH.initial,
22
+ expanded: false,
23
+ view: "thread",
24
+ openings: 0
25
+ };
26
+ const entries = /* @__PURE__ */ new Map();
27
+ const listeners = /* @__PURE__ */ new Map();
28
+ function parse$1(raw, transient) {
29
+ try {
30
+ const value = JSON.parse(raw ?? "{}");
31
+ if (typeof value !== "object" || value === null) return {
32
+ ...DEFAULTS,
33
+ ...transient
34
+ };
35
+ const { open, threadId, width, expanded } = value;
36
+ return {
37
+ open: typeof open === "boolean" ? open : DEFAULTS.open,
38
+ threadId: typeof threadId === "string" || threadId === null ? threadId : DEFAULTS.threadId,
39
+ width: typeof width === "number" && Number.isFinite(width) ? width : DEFAULTS.width,
40
+ expanded: typeof expanded === "boolean" ? expanded : DEFAULTS.expanded,
41
+ ...transient
42
+ };
43
+ } catch {
44
+ return {
45
+ ...DEFAULTS,
46
+ ...transient
47
+ };
48
+ }
49
+ }
50
+ function stored(key) {
51
+ try {
52
+ return window.localStorage.getItem(key);
53
+ } catch {
54
+ return;
55
+ }
56
+ }
57
+ /** The dock's state under `key`: what storage holds, read again only when it changed. */
58
+ function readDock(key) {
59
+ const entry = entries.get(key);
60
+ const raw = stored(key);
61
+ if (entry && (raw === void 0 || raw === entry.raw)) return entry.state;
62
+ const { view, openings } = entry?.state ?? DEFAULTS;
63
+ const state = parse$1(raw ?? null, {
64
+ view,
65
+ openings
66
+ });
67
+ entries.set(key, {
68
+ raw: raw ?? null,
69
+ state
70
+ });
71
+ return state;
72
+ }
73
+ /** Changes the dock's state under `key`, stores it and tells every dock showing it. */
74
+ function writeDock(key, change) {
75
+ const current = readDock(key);
76
+ if (Object.entries(change).every(([name, value]) => current[name] === value)) return;
77
+ const opened = change.open === true && !current.open;
78
+ const state = {
79
+ ...current,
80
+ ...change,
81
+ openings: current.openings + (opened ? 1 : 0)
82
+ };
83
+ const { view: _, openings: __, ...persisted } = state;
84
+ const raw = JSON.stringify(persisted);
85
+ try {
86
+ window.localStorage.setItem(key, raw);
87
+ } catch {}
88
+ entries.set(key, {
89
+ raw,
90
+ state
91
+ });
92
+ for (const listener of listeners.get(key) ?? []) listener();
93
+ }
94
+ /**
95
+ * The dock's state under `key` and a function to change it. Rendered on the server, and while
96
+ * hydrating, it is the defaults; on the client the first paint already shows the stored state.
97
+ */
98
+ function useDockState(key) {
99
+ const subscribe = useCallback((listener) => {
100
+ const set = listeners.get(key) ?? /* @__PURE__ */ new Set();
101
+ listeners.set(key, set);
102
+ set.add(listener);
103
+ return () => {
104
+ set.delete(listener);
105
+ };
106
+ }, [key]);
107
+ return [useSyncExternalStore(subscribe, () => readDock(key), () => DEFAULTS), useCallback((change) => writeDock(key, change), [key])];
108
+ }
109
+ // src/strings.ts
110
+ const en = {
111
+ assistant: "{name}",
112
+ openAssistant: "Open {name}",
113
+ close: "Close",
114
+ history: "History",
115
+ newChat: "New chat",
116
+ noThreads: "No conversations yet.",
117
+ untitled: "Untitled",
118
+ deleteThread: "Delete",
119
+ loadMore: "Load more",
120
+ welcomeTitle: "What can I do for you?",
121
+ welcome: "Ask about anything in this product. I can look things up and act for you.",
122
+ suggestions: "Suggestions",
123
+ expand: "Expand",
124
+ collapse: "Back to the side panel",
125
+ resize: "Resize the panel",
126
+ jumpToLatest: "Jump to the latest",
127
+ contextTitle: "Context",
128
+ contextDetail: "{used} of {budget} tokens",
129
+ contextOver: "Over by {percent}%",
130
+ contextEstimated: "Estimated before the model answered.",
131
+ formCancel: "Cancel",
132
+ formIssues: "Fix these and submit again:",
133
+ composerPlaceholder: "Message {name}…",
134
+ composerLabel: "Message",
135
+ send: "Send",
136
+ stop: "Stop",
137
+ thinking: "Thinking…",
138
+ retrying: "Model busy, retrying ({attempt}/{max})…",
139
+ cancelled: "Stopped.",
140
+ contextUsed: "{percent}% of context used",
141
+ toolAwaitingApproval: "Awaiting approval",
142
+ toolAwaitingInput: "Waiting for the form",
143
+ toolFailed: "Did not succeed",
144
+ toolNotExecuted: "Not run",
145
+ toolDeduplicated: "Already done",
146
+ traceWorking: "Working…",
147
+ traceWriting: "Writing the answer…",
148
+ traceThought: "Thought",
149
+ traceSearching: "Searching for “{query}”…",
150
+ traceSearched: "Searched for “{query}”",
151
+ traceSearchedPlain: "Searched",
152
+ traceResult: "1 result",
153
+ traceResults: "{count} results",
154
+ traceItem: "1 item",
155
+ traceItems: "{count} items",
156
+ traceAsked: "Asked you to choose",
157
+ traceAwaitingAnswer: "Waiting for your answer",
158
+ traceWorked: "Worked",
159
+ traceSeparator: " · ",
160
+ traceMore: "+{count} more",
161
+ traceDetails: "Details",
162
+ traceArguments: "Arguments",
163
+ traceResultJson: "Result",
164
+ sources: "Sources",
165
+ "error.model_unavailable": "The model is unavailable right now. Try again later.",
166
+ "error.max_steps": "This took too many steps, so I stopped. Try a narrower request.",
167
+ "error.open_interrupts": "Answer or dismiss the open request first.",
168
+ "error.history_conflict": "This conversation changed elsewhere. Reload it.",
169
+ "error.invalid_interaction": "That answer was not accepted.",
170
+ "error.internal": "Something went wrong.",
171
+ "error.request": "Could not reach {name}.",
172
+ approvalNeeded: "Needs your approval",
173
+ approve: "Approve",
174
+ reject: "Reject",
175
+ expired: "This request expired. Ask again to retry.",
176
+ expiresAt: "Expires {time}",
177
+ target: "Target",
178
+ risk: "Risk",
179
+ "risk.low": "Low",
180
+ "risk.medium": "Medium",
181
+ "risk.high": "High",
182
+ cost: "Cost",
183
+ changes: "Changes",
184
+ arguments: "Details",
185
+ "effect.read": "Read",
186
+ "effect.create": "Create",
187
+ "effect.update": "Update",
188
+ "effect.delete": "Delete",
189
+ "effect.external": "External",
190
+ submit: "Submit",
191
+ required: "Required",
192
+ optional: "optional",
193
+ recommended: "Recommended",
194
+ other: "Other",
195
+ otherPlaceholder: "Your own answer",
196
+ "issue.required": "This is required.",
197
+ "issue.one": "Choose only one.",
198
+ taskRunning: "Waiting for {op} to finish",
199
+ cancelTask: "Cancel",
200
+ searchPlaceholder: "Search or ask {name}…",
201
+ searchLabel: "Search",
202
+ searching: "Searching…",
203
+ noResults: "No results.",
204
+ failedSources: "Some sources did not answer: {sources}",
205
+ askAssistant: "Ask {name}",
206
+ loading: "Loading…",
207
+ loadFailed: "Could not load this page.",
208
+ models: "Models",
209
+ modelsHint: "Models are tried in order. A model that is rate-limited or out of credit rests, and the next one answers.",
210
+ provider: "Provider",
211
+ model: "Model",
212
+ baseURL: "Base URL",
213
+ apiKey: "API key",
214
+ apiKeySaved: "Saved — leave empty to keep",
215
+ vision: "Images",
216
+ moveUp: "Move up",
217
+ moveDown: "Move down",
218
+ remove: "Remove",
219
+ addModel: "Add model",
220
+ save: "Save",
221
+ saved: "Saved.",
222
+ saveFailed: "Could not save: {status}",
223
+ temperature: "Temperature",
224
+ maxOutputTokens: "Max output tokens",
225
+ configuredInCode: "Configured in code; change it there.",
226
+ saveReplacesCode: "Saving replaces the models configured in code with this list.",
227
+ resetDefaults: "Reset to defaults",
228
+ resetConfirm: "Replace every model with the defaults? Stored API keys and unsaved changes are lost.",
229
+ resetDone: "Reset to defaults.",
230
+ cancel: "Cancel",
231
+ attach: "Attach files",
232
+ attachments: "Attachments",
233
+ dropFiles: "Drop files to attach",
234
+ uploading: "Uploading {file}…",
235
+ uploadFailed: "Could not upload {file}.",
236
+ removeAttachment: "Remove {file}",
237
+ openAttachment: "Open {file}",
238
+ image: "Image",
239
+ file: "File",
240
+ rateAnswer: "Rate this answer",
241
+ goodAnswer: "Good answer",
242
+ badAnswer: "Bad answer",
243
+ feedbackComment: "What went wrong? (optional)",
244
+ feedbackSend: "Send",
245
+ feedbackSkip: "Skip",
246
+ feedbackThanks: "Thanks for the feedback.",
247
+ feedbackFailed: "Could not send feedback."
248
+ };
249
+ const zhCN = {
250
+ assistant: "{name}",
251
+ openAssistant: "打开 {name}",
252
+ close: "关闭",
253
+ history: "历史",
254
+ newChat: "新对话",
255
+ noThreads: "还没有对话。",
256
+ untitled: "未命名",
257
+ deleteThread: "删除",
258
+ loadMore: "加载更多",
259
+ welcomeTitle: "有什么可以帮你?",
260
+ welcome: "问问这个产品里的任何事。我可以帮你查找,也可以替你操作。",
261
+ suggestions: "试试这样问",
262
+ expand: "展开",
263
+ collapse: "回到侧边栏",
264
+ resize: "调整面板宽度",
265
+ jumpToLatest: "回到最新",
266
+ contextTitle: "上下文",
267
+ contextDetail: "{used} / {budget} tokens",
268
+ contextOver: "超出 {percent}%",
269
+ contextEstimated: "模型回答前的估算值。",
270
+ formCancel: "取消",
271
+ formIssues: "请修改以下内容后重新提交:",
272
+ composerPlaceholder: "给 {name} 发消息…",
273
+ composerLabel: "消息",
274
+ send: "发送",
275
+ stop: "停止",
276
+ thinking: "思考中…",
277
+ retrying: "模型繁忙,重试中({attempt}/{max})…",
278
+ cancelled: "已停止。",
279
+ contextUsed: "已用上下文 {percent}%",
280
+ toolAwaitingApproval: "等待确认",
281
+ toolAwaitingInput: "等待填写表单",
282
+ toolFailed: "未成功",
283
+ toolNotExecuted: "未执行",
284
+ toolDeduplicated: "已完成过",
285
+ traceWorking: "处理中…",
286
+ traceWriting: "正在撰写回答…",
287
+ traceThought: "已思考",
288
+ traceSearching: "正在搜索“{query}”…",
289
+ traceSearched: "搜索了“{query}”",
290
+ traceSearchedPlain: "已搜索",
291
+ traceResult: "1 条结果",
292
+ traceResults: "{count} 条结果",
293
+ traceItem: "1 项",
294
+ traceItems: "{count} 项",
295
+ traceAsked: "请你选择",
296
+ traceAwaitingAnswer: "等待你的回答",
297
+ traceWorked: "已处理",
298
+ traceSeparator: " · ",
299
+ traceMore: "等 {count} 项",
300
+ traceDetails: "详情",
301
+ traceArguments: "参数",
302
+ traceResultJson: "结果",
303
+ sources: "来源",
304
+ "error.model_unavailable": "模型暂时不可用,请稍后再试。",
305
+ "error.max_steps": "步骤太多,已停止。请把请求说得更具体些。",
306
+ "error.open_interrupts": "请先回答或放弃待处理的请求。",
307
+ "error.history_conflict": "对话已在别处更改,请重新加载。",
308
+ "error.invalid_interaction": "该回答未被接受。",
309
+ "error.internal": "出错了。",
310
+ "error.request": "无法连接 {name}。",
311
+ approvalNeeded: "需要你确认",
312
+ approve: "确认",
313
+ reject: "拒绝",
314
+ expired: "该请求已过期,请重新发起。",
315
+ expiresAt: "{time} 过期",
316
+ target: "对象",
317
+ risk: "风险",
318
+ "risk.low": "低",
319
+ "risk.medium": "中",
320
+ "risk.high": "高",
321
+ cost: "费用",
322
+ changes: "变更",
323
+ arguments: "详情",
324
+ "effect.read": "读取",
325
+ "effect.create": "创建",
326
+ "effect.update": "修改",
327
+ "effect.delete": "删除",
328
+ "effect.external": "外部",
329
+ submit: "提交",
330
+ required: "必填",
331
+ optional: "选填",
332
+ recommended: "推荐",
333
+ other: "其他",
334
+ otherPlaceholder: "自己填写",
335
+ "issue.required": "此项必填。",
336
+ "issue.one": "只能选一项。",
337
+ taskRunning: "等待 {op} 完成",
338
+ cancelTask: "取消",
339
+ searchPlaceholder: "搜索或问 {name}…",
340
+ searchLabel: "搜索",
341
+ searching: "搜索中…",
342
+ noResults: "没有结果。",
343
+ failedSources: "部分来源未响应:{sources}",
344
+ askAssistant: "问 {name}",
345
+ loading: "加载中…",
346
+ loadFailed: "无法加载此页面。",
347
+ models: "模型",
348
+ modelsHint: "按顺序使用模型。被限流或余额不足的模型会暂停,由下一个接替。",
349
+ provider: "提供方",
350
+ model: "模型",
351
+ baseURL: "Base URL",
352
+ apiKey: "API 密钥",
353
+ apiKeySaved: "已保存,留空则不变",
354
+ vision: "图片",
355
+ moveUp: "上移",
356
+ moveDown: "下移",
357
+ remove: "移除",
358
+ addModel: "添加模型",
359
+ save: "保存",
360
+ saved: "已保存。",
361
+ saveFailed: "保存失败:{status}",
362
+ temperature: "温度",
363
+ maxOutputTokens: "最大输出 token",
364
+ configuredInCode: "在代码中配置,请在代码里修改。",
365
+ saveReplacesCode: "保存后,此列表将取代代码中配置的模型。",
366
+ resetDefaults: "恢复默认",
367
+ resetConfirm: "用默认设置替换所有模型?已保存的 API 密钥和未保存的更改都会丢失。",
368
+ resetDone: "已恢复默认。",
369
+ cancel: "取消",
370
+ attach: "添加附件",
371
+ attachments: "附件",
372
+ dropFiles: "拖放文件以添加附件",
373
+ uploading: "正在上传 {file}…",
374
+ uploadFailed: "无法上传 {file}。",
375
+ removeAttachment: "移除 {file}",
376
+ openAttachment: "打开 {file}",
377
+ image: "图片",
378
+ file: "文件",
379
+ rateAnswer: "评价这个回答",
380
+ goodAnswer: "回答有帮助",
381
+ badAnswer: "回答没帮助",
382
+ feedbackComment: "哪里不对?(选填)",
383
+ feedbackSend: "发送",
384
+ feedbackSkip: "跳过",
385
+ feedbackThanks: "感谢反馈。",
386
+ feedbackFailed: "反馈发送失败。"
387
+ };
388
+ /** The built-in string tables, by locale. */
389
+ const locales = {
390
+ en,
391
+ "zh-CN": zhCN
392
+ };
393
+ const fill = (text, vars) => text.replace(/\{(\w+)\}/g, (match, name) => String(vars[name] ?? match));
394
+ /**
395
+ * Looks strings up in `overrides`, then the locale's table (`zh-CN`, else `en`), then `en`,
396
+ * then gives the key itself. `{name}` is the assistant's name: the `assistant` string, which
397
+ * defaults to `name`.
398
+ */
399
+ function translator(locale, overrides, name) {
400
+ const table = locale === "zh-CN" ? zhCN : en;
401
+ const english = en;
402
+ const raw = (key) => overrides[key] ?? table[key] ?? english[key];
403
+ const assistant = fill(raw("assistant") ?? name, { name });
404
+ const find = (key, vars) => {
405
+ const text = raw(key);
406
+ return text === void 0 ? void 0 : fill(text, {
407
+ ...vars,
408
+ name: assistant
409
+ });
410
+ };
411
+ return Object.assign((key, vars) => find(key, vars) ?? key, { find });
412
+ }
413
+ // src/context.tsx
414
+ const RungentContext = createContext(null);
415
+ /** The same-origin path of `href`, or null when it leaves the page's origin. */
416
+ function samePath(href) {
417
+ const url = new URL(href, window.location.href);
418
+ if (url.origin !== window.location.origin) return null;
419
+ return `${url.pathname}${url.search}${url.hash}`;
420
+ }
421
+ function useToggle() {
422
+ const [isOpen, store] = useState(false);
423
+ const control = useRef(null);
424
+ const set = useCallback((open) => (control.current ?? store)(open), []);
425
+ return useMemo(() => ({
426
+ isOpen,
427
+ set,
428
+ store,
429
+ control
430
+ }), [isOpen, set]);
431
+ }
432
+ /** The dock's open state, in the store that outlives the dock's mounts. */
433
+ function useDockToggle(key) {
434
+ const [{ open: isOpen }, write] = useDockState(key);
435
+ const store = useCallback((open) => write({ open }), [write]);
436
+ const control = useRef(null);
437
+ const set = useCallback((open) => (control.current ?? store)(open), [store]);
438
+ return useMemo(() => ({
439
+ isOpen,
440
+ set,
441
+ store,
442
+ control
443
+ }), [
444
+ isOpen,
445
+ set,
446
+ store
447
+ ]);
448
+ }
449
+ /** A function that always calls the latest `value`, so a host's inline callbacks change nothing. */
450
+ function useLatest(value) {
451
+ const ref = useRef(value);
452
+ ref.current = value;
453
+ const stable = useCallback((...args) => ref.current(...args), []);
454
+ return value ? stable : void 0;
455
+ }
456
+ /**
457
+ * A component's open state: `open` when controlled, else the provider's. Every change goes
458
+ * through `onOpenChange`.
459
+ */
460
+ function useControlledOpen(toggle, open, onOpenChange) {
461
+ const controlled = open !== void 0;
462
+ const onChange = useRef(onOpenChange);
463
+ onChange.current = onOpenChange;
464
+ const { store, control } = toggle;
465
+ const set = useCallback((next) => {
466
+ if (!controlled) store(next);
467
+ onChange.current?.(next);
468
+ }, [controlled, store]);
469
+ useEffect(() => {
470
+ control.current = set;
471
+ return () => {
472
+ if (control.current === set) control.current = null;
473
+ };
474
+ }, [control, set]);
475
+ useEffect(() => {
476
+ if (open !== void 0) store(open);
477
+ }, [open, store]);
478
+ return [open ?? toggle.isOpen, set];
479
+ }
480
+ const DEFAULT_NAME = "Assistant";
481
+ const NO_FORMS = {};
482
+ function RungentProvider({ client, locale = "en", strings, upload, context, onOpen, theme = "system", forms = NO_FORMS, suggestions, children }) {
483
+ const dockKey = `rungent:dock:${client.baseUrl || (typeof window === "undefined" ? "" : window.location.origin)}`;
484
+ const dock = useDockToggle(dockKey);
485
+ const palette = useToggle();
486
+ const paletteSeed = useRef("");
487
+ const [ask, setAsk] = useState(null);
488
+ const askTaken = useRef(0);
489
+ const getContext = useLatest(context);
490
+ const getSuggestions = useLatest(suggestions);
491
+ const onOpenLatest = useLatest(onOpen);
492
+ const uploadLatest = useLatest(upload);
493
+ const [name, setName] = useState(DEFAULT_NAME);
494
+ useEffect(() => {
495
+ let live = true;
496
+ client.info().then((info) => live && setName(info.name), () => {});
497
+ return () => {
498
+ live = false;
499
+ };
500
+ }, [client]);
501
+ const navigate = useCallback((href) => {
502
+ const path = samePath(href);
503
+ if (path === null) window.open(href, "_blank", "noopener,noreferrer");
504
+ else if (onOpenLatest) onOpenLatest(path);
505
+ else window.location.assign(path);
506
+ }, [onOpenLatest]);
507
+ const setDock = dock.set;
508
+ const askAssistant = useCallback((query) => {
509
+ setAsk((current) => ({
510
+ id: (current?.id ?? 0) + 1,
511
+ query
512
+ }));
513
+ setDock(true);
514
+ }, [setDock]);
515
+ const t = useMemo(() => translator(locale, strings ?? {}, name), [
516
+ locale,
517
+ strings,
518
+ name
519
+ ]);
520
+ const value = useMemo(() => ({
521
+ client,
522
+ locale,
523
+ t,
524
+ theme,
525
+ upload: uploadLatest,
526
+ context: getContext,
527
+ forms,
528
+ suggestions: getSuggestions,
529
+ navigate,
530
+ dock,
531
+ dockKey,
532
+ palette,
533
+ paletteSeed,
534
+ ask,
535
+ askTaken,
536
+ askAssistant
537
+ }), [
538
+ client,
539
+ locale,
540
+ t,
541
+ theme,
542
+ uploadLatest,
543
+ getContext,
544
+ forms,
545
+ getSuggestions,
546
+ navigate,
547
+ dock,
548
+ dockKey,
549
+ palette,
550
+ ask,
551
+ askAssistant
552
+ ]);
553
+ return /* @__PURE__ */ jsx(RungentContext, {
554
+ value,
555
+ children
556
+ });
557
+ }
558
+ function useRungent() {
559
+ const value = useContext(RungentContext);
560
+ if (!value) throw new Error("rungent components must be inside <RungentProvider>");
561
+ return value;
562
+ }
563
+ /** Controls the dock from the host page, e.g. an "Ask the assistant" button. */
564
+ function useDock() {
565
+ const { dock, askAssistant } = useRungent();
566
+ return {
567
+ open: dock.isOpen,
568
+ setOpen: dock.set,
569
+ ask: askAssistant
570
+ };
571
+ }
572
+ /** Controls the search palette from the host page, e.g. a search button in the header. */
573
+ function useSearchPalette() {
574
+ const { palette, paletteSeed } = useRungent();
575
+ const { isOpen, set } = palette;
576
+ return useMemo(() => ({
577
+ isOpen,
578
+ open: (query = "") => {
579
+ paletteSeed.current = query;
580
+ set(true);
581
+ },
582
+ close: () => set(false)
583
+ }), [
584
+ isOpen,
585
+ set,
586
+ paletteSeed
587
+ ]);
588
+ }
589
+ /** Attributes for a component's outermost element, which carries the theme variables. */
590
+ function useRoot(className) {
591
+ const { theme, locale } = useRungent();
592
+ return {
593
+ className: `rungent-root ${className}`,
594
+ "data-rungent-theme": theme,
595
+ lang: locale
596
+ };
597
+ }
598
+ // src/approval.tsx
599
+ function useExpired(expiresAt) {
600
+ const deadline = expiresAt ? Date.parse(expiresAt) : NaN;
601
+ const [expired, setExpired] = useState(() => deadline <= Date.now());
602
+ useEffect(() => {
603
+ if (Number.isNaN(deadline)) return;
604
+ const left = deadline - Date.now();
605
+ if (left <= 0) {
606
+ setExpired(true);
607
+ return;
608
+ }
609
+ const timer = setTimeout(() => setExpired(true), Math.min(left, 2 ** 31 - 1));
610
+ return () => clearTimeout(timer);
611
+ }, [deadline]);
612
+ return expired;
613
+ }
614
+ function display(value) {
615
+ if (value === null || value === void 0 || value === "") return "—";
616
+ if (typeof value === "string") return value;
617
+ return JSON.stringify(value);
618
+ }
619
+ /** Asks the user to approve one write, showing exactly what will run. */
620
+ function ApprovalCard({ interrupt, onAnswer }) {
621
+ const { t, locale } = useRungent();
622
+ const root = useRoot("rungent-card rungent-approval");
623
+ const { impact, arguments: args } = interrupt.meta;
624
+ const expired = useExpired(interrupt.interrupt.expiresAt);
625
+ const [answered, setAnswered] = useState(false);
626
+ const titleId = useId();
627
+ const answer = (approved) => {
628
+ setAnswered(true);
629
+ onAnswer(approved);
630
+ };
631
+ const expiresAt = interrupt.interrupt.expiresAt;
632
+ return /* @__PURE__ */ jsxs("section", {
633
+ ...root,
634
+ "data-risk": impact.risk ?? void 0,
635
+ "data-effect": impact.effect,
636
+ "aria-labelledby": titleId,
637
+ children: [
638
+ /* @__PURE__ */ jsx("p", {
639
+ className: "rungent-card-eyebrow",
640
+ children: t("approvalNeeded")
641
+ }),
642
+ /* @__PURE__ */ jsx("h3", {
643
+ id: titleId,
644
+ className: "rungent-card-title",
645
+ children: impact.title
646
+ }),
647
+ /* @__PURE__ */ jsxs("div", {
648
+ className: "rungent-badges",
649
+ children: [/* @__PURE__ */ jsx("span", {
650
+ className: "rungent-badge",
651
+ "data-effect": impact.effect,
652
+ children: t(`effect.${impact.effect}`)
653
+ }), impact.risk ? /* @__PURE__ */ jsxs("span", {
654
+ className: "rungent-badge",
655
+ "data-risk": impact.risk,
656
+ children: [
657
+ t("risk"),
658
+ ": ",
659
+ t(`risk.${impact.risk}`)
660
+ ]
661
+ }) : null]
662
+ }),
663
+ /* @__PURE__ */ jsxs("dl", {
664
+ className: "rungent-facts",
665
+ children: [impact.target ? /* @__PURE__ */ jsxs("div", {
666
+ className: "rungent-fact",
667
+ children: [/* @__PURE__ */ jsx("dt", { children: t("target") }), /* @__PURE__ */ jsx("dd", { children: impact.target })]
668
+ }) : null, impact.costHint ? /* @__PURE__ */ jsxs("div", {
669
+ className: "rungent-fact",
670
+ children: [/* @__PURE__ */ jsx("dt", { children: t("cost") }), /* @__PURE__ */ jsx("dd", { children: impact.costHint })]
671
+ }) : null]
672
+ }),
673
+ impact.changes.length > 0 ? /* @__PURE__ */ jsx("ul", {
674
+ className: "rungent-changes",
675
+ "aria-label": t("changes"),
676
+ children: impact.changes.map((change) => /* @__PURE__ */ jsx("li", { children: change }, change))
677
+ }) : null,
678
+ Object.keys(args).length > 0 ? /* @__PURE__ */ jsxs("details", {
679
+ className: "rungent-arguments",
680
+ children: [/* @__PURE__ */ jsx("summary", { children: t("arguments") }), /* @__PURE__ */ jsx("dl", {
681
+ className: "rungent-facts rungent-mono",
682
+ children: Object.entries(args).map(([key, value]) => /* @__PURE__ */ jsxs("div", {
683
+ className: "rungent-fact",
684
+ children: [/* @__PURE__ */ jsx("dt", { children: key }), /* @__PURE__ */ jsx("dd", { children: display(value) })]
685
+ }, key))
686
+ })]
687
+ }) : null,
688
+ expired ? /* @__PURE__ */ jsx("p", {
689
+ className: "rungent-note",
690
+ role: "status",
691
+ children: t("expired")
692
+ }) : /* @__PURE__ */ jsxs("div", {
693
+ className: "rungent-actions",
694
+ children: [
695
+ expiresAt ? /* @__PURE__ */ jsx("span", {
696
+ className: "rungent-muted rungent-small",
697
+ children: t("expiresAt", { time: new Date(expiresAt).toLocaleTimeString(locale, {
698
+ hour: "2-digit",
699
+ minute: "2-digit"
700
+ }) })
701
+ }) : null,
702
+ /* @__PURE__ */ jsx("button", {
703
+ type: "button",
704
+ className: "rungent-button",
705
+ disabled: answered,
706
+ onClick: () => answer(false),
707
+ children: t("reject")
708
+ }),
709
+ /* @__PURE__ */ jsx("button", {
710
+ type: "button",
711
+ className: "rungent-button rungent-primary",
712
+ "data-danger": impact.risk === "high" || impact.effect === "delete" || void 0,
713
+ disabled: answered,
714
+ onClick: () => answer(true),
715
+ children: t("approve")
716
+ })
717
+ ]
718
+ })
719
+ ]
720
+ });
721
+ }
722
+ // src/hooks.ts
723
+ function threadReducer(state, action) {
724
+ if (action.type === "load") return action.state;
725
+ if (action.type === "user") return appendUserMessage(state, action.item);
726
+ return reduceThread(state, action.event);
727
+ }
728
+ function textOf(message) {
729
+ if (typeof message === "string") return message;
730
+ return message.map((part) => part.type === "text" ? part.text : "").join("");
731
+ }
732
+ /**
733
+ * The latest state of the threads shown on this page, so that a thread mounted again (a dock a
734
+ * host mounted again on navigation) shows at once as it was and follows on from there.
735
+ */
736
+ const shown = /* @__PURE__ */ new WeakMap();
737
+ const SHOWN_LIMIT = 8;
738
+ function remember(client, id, state) {
739
+ const threads = shown.get(client) ?? /* @__PURE__ */ new Map();
740
+ shown.set(client, threads);
741
+ threads.delete(id);
742
+ threads.set(id, state);
743
+ if (threads.size > SHOWN_LIMIT) threads.delete(threads.keys().next().value);
744
+ }
745
+ const known = (client, id) => (id ? shown.get(client)?.get(id) : void 0) ?? initialThreadState;
746
+ /** Sends a run and detaches once it started; its events arrive through `follow`. */
747
+ async function start(run) {
748
+ const events = run[Symbol.asyncIterator]();
749
+ await events.next();
750
+ await events.return?.();
751
+ }
752
+ /**
753
+ * A thread's live state: it replays the thread's events and follows them, and opens the pages
754
+ * (`rungent.ui.open`) that runs started here ask for.
755
+ */
756
+ function useThread(threadId) {
757
+ const { client, navigate, context } = useRungent();
758
+ const [createdId, setCreatedId] = useState(null);
759
+ const [shownProp, setShownProp] = useState(threadId);
760
+ if (shownProp !== threadId) {
761
+ setShownProp(threadId);
762
+ setCreatedId(null);
763
+ }
764
+ const id = threadId ?? createdId;
765
+ const [state, dispatch] = useReducer(threadReducer, id, (id) => known(client, id));
766
+ const [error, setError] = useState(null);
767
+ const created = useRef(null);
768
+ /** The thread `state` is of. */
769
+ const stateOf = useRef(id);
770
+ /** Opens with a seq above this were asked by a run started here and not yet shown. */
771
+ const openAfter = useRef(Number.POSITIVE_INFINITY);
772
+ const stateRef = useRef(state);
773
+ stateRef.current = state;
774
+ useEffect(() => {
775
+ let from = stateRef.current;
776
+ if (id !== stateOf.current && id !== created.current) {
777
+ from = known(client, id);
778
+ dispatch({
779
+ type: "load",
780
+ state: from
781
+ });
782
+ }
783
+ stateOf.current = id;
784
+ setError(null);
785
+ if (!id) return;
786
+ const controller = new AbortController();
787
+ (async () => {
788
+ const events = client.follow(id, {
789
+ after: from.lastSeq,
790
+ signal: controller.signal
791
+ });
792
+ for await (const event of events) dispatch({
793
+ type: "event",
794
+ event
795
+ });
796
+ })().catch((reason) => {
797
+ if (!controller.signal.aborted) setError(reason);
798
+ });
799
+ return () => controller.abort();
800
+ }, [client, id]);
801
+ useEffect(() => {
802
+ if (id) remember(client, id, state);
803
+ }, [
804
+ client,
805
+ id,
806
+ state
807
+ ]);
808
+ useEffect(() => {
809
+ for (const open of state.opens) if (open.seq > openAfter.current) {
810
+ openAfter.current = open.seq;
811
+ navigate(open.path);
812
+ }
813
+ }, [state.opens, navigate]);
814
+ return {
815
+ threadId: id,
816
+ state,
817
+ error,
818
+ send: useCallback(async (message) => {
819
+ setError(null);
820
+ try {
821
+ let target = id;
822
+ if (!target) {
823
+ target = (await client.createThread()).id;
824
+ created.current = target;
825
+ setCreatedId(target);
826
+ }
827
+ const open = stateRef.current.interrupts;
828
+ const run = client.run(target, {
829
+ message,
830
+ context: context?.() ?? [],
831
+ ...open.length > 0 ? { resume: cancelAll(open) } : {}
832
+ });
833
+ if (run.messageId) dispatch({
834
+ type: "user",
835
+ item: {
836
+ kind: "user",
837
+ id: run.messageId,
838
+ text: textOf(message),
839
+ attachments: attachmentsOf(message)
840
+ }
841
+ });
842
+ openAfter.current = stateRef.current.lastSeq;
843
+ await start(run);
844
+ } catch (reason) {
845
+ setError(reason);
846
+ }
847
+ }, [
848
+ client,
849
+ context,
850
+ id
851
+ ]),
852
+ resume: useCallback(async (entries) => {
853
+ if (!id) return;
854
+ setError(null);
855
+ openAfter.current = stateRef.current.lastSeq;
856
+ try {
857
+ await start(client.run(id, {
858
+ resume: entries,
859
+ context: context?.() ?? []
860
+ }));
861
+ } catch (reason) {
862
+ setError(reason);
863
+ }
864
+ }, [
865
+ client,
866
+ context,
867
+ id
868
+ ]),
869
+ cancel: useCallback(async () => {
870
+ const runId = stateRef.current.runId;
871
+ if (runId) await client.cancel(runId).catch(setError);
872
+ }, [client])
873
+ };
874
+ }
875
+ /** The user's threads, newest first. */
876
+ function useThreads() {
877
+ const { client } = useRungent();
878
+ const [threads, setThreads] = useState([]);
879
+ const [next, setNext] = useState();
880
+ const [loading, setLoading] = useState(true);
881
+ const [error, setError] = useState(null);
882
+ const [version, setVersion] = useState(0);
883
+ const load = useCallback(async (cursor, append) => {
884
+ setLoading(true);
885
+ try {
886
+ const page = await client.listThreads(cursor);
887
+ setThreads((current) => append ? [...current, ...page.items] : page.items);
888
+ setNext(page.next);
889
+ setError(null);
890
+ } catch (reason) {
891
+ setError(reason);
892
+ } finally {
893
+ setLoading(false);
894
+ }
895
+ }, [client]);
896
+ useEffect(() => {
897
+ load(void 0, false);
898
+ }, [load, version]);
899
+ return {
900
+ threads,
901
+ loading,
902
+ error,
903
+ hasMore: next !== void 0,
904
+ reload: useCallback(() => setVersion((v) => v + 1), []),
905
+ loadMore: useCallback(() => {
906
+ if (next !== void 0) load(next, true);
907
+ }, [load, next]),
908
+ remove: useCallback(async (threadId) => {
909
+ await client.deleteThread(threadId);
910
+ setThreads((current) => current.filter((thread) => thread.id !== threadId));
911
+ }, [client])
912
+ };
913
+ }
914
+ const SEARCH_DEBOUNCE_MS = 150;
915
+ /** Federated search, debounced; a newer query aborts the older request. */
916
+ function useSearch(query) {
917
+ const { client } = useRungent();
918
+ const [result, setResult] = useState(null);
919
+ const [loading, setLoading] = useState(false);
920
+ const [error, setError] = useState(null);
921
+ useEffect(() => {
922
+ const q = query.trim();
923
+ setResult(null);
924
+ setError(null);
925
+ if (!q) {
926
+ setLoading(false);
927
+ return;
928
+ }
929
+ setLoading(true);
930
+ const controller = new AbortController();
931
+ const timer = setTimeout(() => {
932
+ client.search(q, { signal: controller.signal }).then(setResult, (reason) => {
933
+ if (!controller.signal.aborted) setError(reason);
934
+ }).finally(() => {
935
+ if (!controller.signal.aborted) setLoading(false);
936
+ });
937
+ }, SEARCH_DEBOUNCE_MS);
938
+ return () => {
939
+ clearTimeout(timer);
940
+ controller.abort();
941
+ };
942
+ }, [client, query]);
943
+ return {
944
+ result,
945
+ loading,
946
+ error
947
+ };
948
+ }
949
+ /** The operations visible to this user. */
950
+ function useCatalog() {
951
+ const { client } = useRungent();
952
+ const [operations, setOperations] = useState([]);
953
+ const [loading, setLoading] = useState(true);
954
+ const [error, setError] = useState(null);
955
+ useEffect(() => {
956
+ let live = true;
957
+ client.catalog().then((list) => live && setOperations(list), (reason) => live && setError(reason)).finally(() => live && setLoading(false));
958
+ return () => {
959
+ live = false;
960
+ };
961
+ }, [client]);
962
+ return {
963
+ operations,
964
+ loading,
965
+ error
966
+ };
967
+ }
968
+ // src/scrollbar.ts
969
+ /**
970
+ * rungent's scrollbars: thin, on a transparent track, and hidden until the user scrolls (or points
971
+ * at the area). The look is CSS (`.rungent-scroll` in styles.css); this shows the thumb while the
972
+ * user scrolls, and leaves it hidden while content scrolls by itself (an answer streaming).
973
+ */
974
+ /** The class that gives a scroll container rungent's scrollbar. */
975
+ const SCROLL_CLASS = "rungent-scroll";
976
+ /** Set on the container while the user scrolls it; styles.css shows the thumb then. */
977
+ const SCROLLING_ATTRIBUTE = "data-rungent-scrolling";
978
+ /** The thumb hides this long after the last scroll. */
979
+ const SCROLL_IDLE_MS = 900;
980
+ /** A scroll this soon after the user's wheel, touch, pointer or key counts as theirs. */
981
+ const INPUT_WINDOW_MS = 1e3;
982
+ const INPUTS = [
983
+ "wheel",
984
+ "touchmove",
985
+ "pointerdown",
986
+ "keydown"
987
+ ];
988
+ /**
989
+ * Gives `element` rungent's scrollbar and shows its thumb while the user scrolls it. Works on any
990
+ * element, React or not; returns a function that stops watching.
991
+ */
992
+ function watchScrollbar(element) {
993
+ element.classList.add(SCROLL_CLASS);
994
+ let input = Number.NEGATIVE_INFINITY;
995
+ let timer;
996
+ const show = () => {
997
+ element.setAttribute(SCROLLING_ATTRIBUTE, "");
998
+ clearTimeout(timer);
999
+ timer = setTimeout(() => element.removeAttribute(SCROLLING_ATTRIBUTE), SCROLL_IDLE_MS);
1000
+ };
1001
+ const onInput = () => {
1002
+ input = Date.now();
1003
+ };
1004
+ const onScroll = () => {
1005
+ if (Date.now() - input <= INPUT_WINDOW_MS) show();
1006
+ };
1007
+ for (const type of INPUTS) element.addEventListener(type, onInput, { passive: true });
1008
+ element.addEventListener("scroll", onScroll, { passive: true });
1009
+ return () => {
1010
+ for (const type of INPUTS) element.removeEventListener(type, onInput);
1011
+ element.removeEventListener("scroll", onScroll);
1012
+ clearTimeout(timer);
1013
+ element.removeAttribute(SCROLLING_ATTRIBUTE);
1014
+ };
1015
+ }
1016
+ /**
1017
+ * `watchScrollbar` for the element in `ref`, also when it mounts later or changes (a list shown
1018
+ * only while open). Put `SCROLL_CLASS` in its `className` as well, so the first paint already
1019
+ * has the thin, hidden scrollbar.
1020
+ */
1021
+ function useScrollbar(ref) {
1022
+ const watched = useRef(null);
1023
+ useEffect(() => {
1024
+ const element = ref.current;
1025
+ if (watched.current?.element === element) return;
1026
+ watched.current?.stop();
1027
+ watched.current = element ? {
1028
+ element,
1029
+ stop: watchScrollbar(element)
1030
+ } : null;
1031
+ });
1032
+ useEffect(() => () => {
1033
+ watched.current?.stop();
1034
+ watched.current = null;
1035
+ }, []);
1036
+ }
1037
+ /** …and at most this share of the conversation's height. */
1038
+ const AUTOSIZE_MAX_SHARE = .4;
1039
+ /**
1040
+ * The height (border box) a textarea takes for content `scrollHeight` high (padding included,
1041
+ * borders not), capped at `max`, and whether its content then scrolls.
1042
+ */
1043
+ function autosizeHeight(scrollHeight, borders, max) {
1044
+ const height = Math.ceil(scrollHeight + borders);
1045
+ return height > max ? {
1046
+ height: Math.floor(max),
1047
+ scrolls: true
1048
+ } : {
1049
+ height,
1050
+ scrolls: false
1051
+ };
1052
+ }
1053
+ const px = (value) => Number.parseFloat(value) || 0;
1054
+ /**
1055
+ * Fits `element` to its text: at most `AUTOSIZE_MAX_LINES` lines and `AUTOSIZE_MAX_SHARE` of
1056
+ * `room` pixels, never less than one line. Measured and set in one go, so nothing paints between.
1057
+ */
1058
+ function fitTextarea(element, room) {
1059
+ const style = getComputedStyle(element);
1060
+ const borders = px(style.borderTopWidth) + px(style.borderBottomWidth);
1061
+ const padding = px(style.paddingTop) + px(style.paddingBottom);
1062
+ const line = px(style.lineHeight) || (px(style.fontSize) || 14) * 1.5;
1063
+ const oneLine = line + padding + borders;
1064
+ const max = Math.max(oneLine, Math.min(10 * line + padding + borders, room * AUTOSIZE_MAX_SHARE));
1065
+ const top = element.scrollTop;
1066
+ element.style.overflowY = "hidden";
1067
+ element.style.height = "auto";
1068
+ const { height, scrolls } = autosizeHeight(element.scrollHeight, borders, max);
1069
+ element.style.height = `${height}px`;
1070
+ element.style.overflowY = scrolls ? "auto" : "hidden";
1071
+ element.scrollTop = top;
1072
+ }
1073
+ /**
1074
+ * Keeps the textarea in `ref` fitted to `value`, and to its width when that changes (the panel
1075
+ * resized). `room` gives the height it may take a share of.
1076
+ */
1077
+ function useAutosize(ref, value, room) {
1078
+ const fit = useCallback(() => {
1079
+ if (ref.current) fitTextarea(ref.current, room());
1080
+ }, [ref, room]);
1081
+ useLayoutEffect(fit, [fit, value]);
1082
+ useEffect(() => {
1083
+ const element = ref.current;
1084
+ if (!element || typeof ResizeObserver === "undefined") return;
1085
+ let width = element.clientWidth;
1086
+ const observer = new ResizeObserver(() => {
1087
+ if (element.clientWidth === width) return;
1088
+ width = element.clientWidth;
1089
+ fit();
1090
+ });
1091
+ observer.observe(element);
1092
+ return () => observer.disconnect();
1093
+ }, [ref, fit]);
1094
+ }
1095
+ // src/form.tsx
1096
+ function at(values, path) {
1097
+ let current = values;
1098
+ for (const segment of path.split(".")) {
1099
+ if (typeof current !== "object" || current === null) return void 0;
1100
+ current = current[segment];
1101
+ }
1102
+ return current;
1103
+ }
1104
+ function initial(question, given) {
1105
+ const scalar = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
1106
+ if (question.kind === "text") return { text: scalar(given) ?? question.default ?? "" };
1107
+ const fromGiven = Array.isArray(given) ? given.flatMap((value) => scalar(value) ?? []) : scalar(given) !== void 0 ? [scalar(given)] : void 0;
1108
+ const fallback = question.default === void 0 ? [] : typeof question.default === "string" ? [question.default] : question.default;
1109
+ const known = new Set(question.options.map((option) => option.id));
1110
+ return {
1111
+ selected: (fromGiven ?? fallback).filter((id) => known.has(id)),
1112
+ custom: question.allowCustom ? (fromGiven ?? []).filter((id) => !known.has(id)).join(", ") : ""
1113
+ };
1114
+ }
1115
+ /** Answers as `checkAnswers` expects them; untouched optional questions are left out. */
1116
+ function collect(form, values) {
1117
+ const answers = {};
1118
+ for (const question of form.questions) {
1119
+ const value = values[question.id];
1120
+ if (!value) continue;
1121
+ if ("text" in value) {
1122
+ if (value.text.trim() || question.required) answers[question.id] = value.text;
1123
+ } else {
1124
+ const custom = value.custom.trim();
1125
+ if (value.selected.length > 0 || custom || question.required) answers[question.id] = {
1126
+ selected: value.selected,
1127
+ ...custom ? { custom } : {}
1128
+ };
1129
+ }
1130
+ }
1131
+ return answers;
1132
+ }
1133
+ const ISSUE_KEYS = {
1134
+ required: "issue.required",
1135
+ "only one answer is allowed": "issue.one"
1136
+ };
1137
+ /** A form the agent or an operation asks the user to fill in. */
1138
+ function RungentForm({ form, values: given, issues: refused = [], onSubmit, onCancel }) {
1139
+ const { t } = useRungent();
1140
+ const root = useRoot("rungent-card rungent-form");
1141
+ const baseId = useId();
1142
+ const formRef = useRef(null);
1143
+ const [values, setValues] = useState(() => Object.fromEntries(form.questions.map((question) => [question.id, initial(question, at(given, question.id))])));
1144
+ const ids = new Set(form.questions.map((question) => question.id));
1145
+ const [issues, setIssues] = useState(() => Object.fromEntries(refused.filter((issue) => ids.has(issue.path)).map((issue) => [issue.path, ISSUE_KEYS[issue.message] ? t(ISSUE_KEYS[issue.message]) : issue.message])));
1146
+ const general = refused.filter((issue) => !ids.has(issue.path));
1147
+ const [submitted, setSubmitted] = useState(false);
1148
+ const set = (id, value) => {
1149
+ setValues((current) => ({
1150
+ ...current,
1151
+ [id]: value
1152
+ }));
1153
+ setIssues(({ [id]: _, ...rest }) => rest);
1154
+ };
1155
+ const submit = (event) => {
1156
+ event.preventDefault();
1157
+ const answers = collect(form, values);
1158
+ const found = checkAnswers(form, answers);
1159
+ if (found.length > 0) {
1160
+ const messages = {};
1161
+ for (const issue of found) {
1162
+ const key = ISSUE_KEYS[issue.message];
1163
+ messages[issue.question] ??= key ? t(key) : issue.message;
1164
+ }
1165
+ setIssues(messages);
1166
+ const first = form.questions.find((question) => messages[question.id]);
1167
+ formRef.current?.querySelector(`[data-question="${first?.id}"] input`)?.focus();
1168
+ return;
1169
+ }
1170
+ setSubmitted(true);
1171
+ onSubmit(answers);
1172
+ };
1173
+ return /* @__PURE__ */ jsxs("form", {
1174
+ ...root,
1175
+ ref: formRef,
1176
+ onSubmit: submit,
1177
+ noValidate: true,
1178
+ "aria-labelledby": `${baseId}-title`,
1179
+ children: [
1180
+ /* @__PURE__ */ jsx("h3", {
1181
+ id: `${baseId}-title`,
1182
+ className: "rungent-card-title",
1183
+ children: form.prompt
1184
+ }),
1185
+ general.length > 0 ? /* @__PURE__ */ jsxs("div", {
1186
+ className: "rungent-issue",
1187
+ role: "alert",
1188
+ children: [t("formIssues"), /* @__PURE__ */ jsx("ul", { children: general.map((issue) => /* @__PURE__ */ jsxs("li", { children: [issue.path ? `${issue.path}: ` : "", issue.message] }, `${issue.path}:${issue.message}`)) })]
1189
+ }) : null,
1190
+ form.questions.map((question) => {
1191
+ const id = `${baseId}-${question.id}`;
1192
+ const value = values[question.id] ?? initial(question, void 0);
1193
+ const issue = issues[question.id];
1194
+ const describedBy = issue ? `${id}-issue` : void 0;
1195
+ const label = /* @__PURE__ */ jsxs(Fragment, { children: [question.prompt, question.required ? /* @__PURE__ */ jsxs("span", {
1196
+ className: "rungent-required",
1197
+ "aria-hidden": "true",
1198
+ children: [" ", "*"]
1199
+ }) : /* @__PURE__ */ jsxs("span", {
1200
+ className: "rungent-muted",
1201
+ children: [
1202
+ " (",
1203
+ t("optional"),
1204
+ ")"
1205
+ ]
1206
+ })] });
1207
+ return /* @__PURE__ */ jsxs("div", {
1208
+ className: "rungent-question",
1209
+ "data-question": question.id,
1210
+ children: [question.kind === "text" || !("selected" in value) ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("label", {
1211
+ htmlFor: id,
1212
+ className: "rungent-label",
1213
+ children: label
1214
+ }), /* @__PURE__ */ jsx("input", {
1215
+ id,
1216
+ className: "rungent-input",
1217
+ value: "text" in value ? value.text : "",
1218
+ placeholder: question.kind === "text" ? question.placeholder : void 0,
1219
+ required: question.required,
1220
+ "aria-invalid": issue ? true : void 0,
1221
+ "aria-describedby": describedBy,
1222
+ onChange: (event) => set(question.id, { text: event.target.value })
1223
+ })] }) : /* @__PURE__ */ jsxs("fieldset", {
1224
+ className: "rungent-choices",
1225
+ "aria-describedby": describedBy,
1226
+ "aria-invalid": issue ? true : void 0,
1227
+ children: [
1228
+ /* @__PURE__ */ jsx("legend", {
1229
+ className: "rungent-label",
1230
+ children: label
1231
+ }),
1232
+ question.options.map((option) => {
1233
+ const checked = value.selected.includes(option.id);
1234
+ return /* @__PURE__ */ jsxs("label", {
1235
+ className: "rungent-choice",
1236
+ children: [/* @__PURE__ */ jsx("input", {
1237
+ type: question.multiple ? "checkbox" : "radio",
1238
+ name: id,
1239
+ checked,
1240
+ onChange: () => set(question.id, {
1241
+ custom: question.multiple ? value.custom : "",
1242
+ selected: question.multiple ? checked ? value.selected.filter((selected) => selected !== option.id) : [...value.selected, option.id] : [option.id]
1243
+ })
1244
+ }), /* @__PURE__ */ jsxs("span", { children: [
1245
+ option.label,
1246
+ option.recommended ? /* @__PURE__ */ jsx("span", {
1247
+ className: "rungent-badge rungent-recommended",
1248
+ children: t("recommended")
1249
+ }) : null,
1250
+ option.description ? /* @__PURE__ */ jsx("span", {
1251
+ className: "rungent-choice-description",
1252
+ children: option.description
1253
+ }) : null
1254
+ ] })]
1255
+ }, option.id);
1256
+ }),
1257
+ question.allowCustom ? /* @__PURE__ */ jsx("input", {
1258
+ className: "rungent-input",
1259
+ "aria-label": `${question.prompt}: ${t("other")}`,
1260
+ placeholder: t("otherPlaceholder"),
1261
+ value: value.custom,
1262
+ onChange: (event) => set(question.id, {
1263
+ custom: event.target.value,
1264
+ selected: question.multiple || !event.target.value ? value.selected : []
1265
+ })
1266
+ }) : null
1267
+ ]
1268
+ }), issue ? /* @__PURE__ */ jsx("p", {
1269
+ id: `${id}-issue`,
1270
+ className: "rungent-issue",
1271
+ role: "alert",
1272
+ children: issue
1273
+ }) : null]
1274
+ }, question.id);
1275
+ }),
1276
+ /* @__PURE__ */ jsxs("div", {
1277
+ className: "rungent-actions",
1278
+ children: [onCancel ? /* @__PURE__ */ jsx("button", {
1279
+ type: "button",
1280
+ className: "rungent-button rungent-ghost",
1281
+ onClick: onCancel,
1282
+ disabled: submitted,
1283
+ children: t("formCancel")
1284
+ }) : null, /* @__PURE__ */ jsx("button", {
1285
+ type: "submit",
1286
+ className: "rungent-button rungent-primary",
1287
+ disabled: submitted,
1288
+ children: t("submit")
1289
+ })]
1290
+ })
1291
+ ]
1292
+ });
1293
+ }
1294
+ // src/stream.ts
1295
+ /** Streaming text: a steady reveal of what arrived, and Markdown that is safe to show half-done. */
1296
+ /** At least this many characters a frame, so a slow stream still moves. */
1297
+ const MIN_PER_FRAME = 2;
1298
+ /** A backlog is caught up over about this many frames, so a burst does not lag behind. */
1299
+ const CATCH_UP_FRAMES = 24;
1300
+ function reducedMotion() {
1301
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1302
+ }
1303
+ /**
1304
+ * The part of `text` to show: while it streams, characters appear at a steady pace instead of in
1305
+ * the bursts the network delivers; they keep appearing after the stream ends until all are shown.
1306
+ * Text that was complete when it mounted (history) shows at once.
1307
+ */
1308
+ function useSmoothText(text, streaming) {
1309
+ const [shown, setShown] = useState(() => streaming ? 0 : text.length);
1310
+ const target = useRef(text.length);
1311
+ target.current = text.length;
1312
+ const animating = shown < text.length;
1313
+ useEffect(() => {
1314
+ if (!animating) return;
1315
+ if (reducedMotion()) {
1316
+ setShown(target.current);
1317
+ return;
1318
+ }
1319
+ let frame = requestAnimationFrame(function step() {
1320
+ setShown((current) => {
1321
+ const backlog = target.current - current;
1322
+ if (backlog <= 0) return current;
1323
+ return current + Math.max(MIN_PER_FRAME, Math.ceil(backlog / CATCH_UP_FRAMES));
1324
+ });
1325
+ frame = requestAnimationFrame(step);
1326
+ });
1327
+ return () => cancelAnimationFrame(frame);
1328
+ }, [animating]);
1329
+ const end = Math.min(shown, text.length);
1330
+ const code = text.charCodeAt(end - 1);
1331
+ return text.slice(0, code >= 55296 && code <= 56319 ? end - 1 : end);
1332
+ }
1333
+ /**
1334
+ * Hides a link, image or citation whose Markdown has not fully arrived (`[label](/pa`), so the
1335
+ * reader never sees raw brackets turn into a link.
1336
+ */
1337
+ function settlePartialMarkdown(text) {
1338
+ const open = text.lastIndexOf("[");
1339
+ if (open < 0) return text;
1340
+ const tail = text.slice(open);
1341
+ if (/^\[[^\]\n]*$/.test(tail) || /^\[[^\]\n]*\]\([^)\s]*$/.test(tail)) return text.slice(0, open > 0 && text[open - 1] === "!" ? open - 1 : open);
1342
+ return text;
1343
+ }
1344
+ /**
1345
+ * Splits Markdown into top-level blocks at blank lines outside code fences, so that while text
1346
+ * streams only the last block renders again. A blank line followed by an indented line continues
1347
+ * the block (a list item's next paragraph).
1348
+ */
1349
+ function markdownBlocks(text) {
1350
+ const blocks = [];
1351
+ let current = [];
1352
+ let blank = false;
1353
+ let fence = null;
1354
+ for (const line of text.split("\n")) {
1355
+ if (fence === null && line.trim() === "") {
1356
+ blank = current.length > 0;
1357
+ continue;
1358
+ }
1359
+ if (blank) {
1360
+ if (/^[ \t]/.test(line)) current.push("");
1361
+ else {
1362
+ blocks.push(current.join("\n"));
1363
+ current = [];
1364
+ }
1365
+ blank = false;
1366
+ }
1367
+ const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
1368
+ if (marker) {
1369
+ if (fence === null) fence = marker;
1370
+ else if (marker.startsWith(fence)) fence = null;
1371
+ }
1372
+ current.push(line);
1373
+ }
1374
+ if (current.length > 0) blocks.push(current.join("\n"));
1375
+ return blocks;
1376
+ }
1377
+ // src/markdown.tsx
1378
+ const CITE = "#rungent-cite-";
1379
+ /**
1380
+ * Turns `[n]` markers with a citation into links the renderer shows as citations; other markers
1381
+ * and code spans are left alone.
1382
+ */
1383
+ function linkCitations(text, cited) {
1384
+ return text.split(/(`+[^`]*`+)/).map((part, index) => index % 2 === 1 ? part : part.replace(/\[(\d{1,3})\](?!\()/g, (match, n, offset) => {
1385
+ return !((offset === 0 || part[offset - 1] === "\n") && part[offset + match.length] === ":") && cited.has(Number(n)) ? `[${n}](${CITE}${n})` : match;
1386
+ })).join("");
1387
+ }
1388
+ const Block = memo(function Block({ text, components }) {
1389
+ return /* @__PURE__ */ jsx(ReactMarkdown, {
1390
+ remarkPlugins: [remarkGfm],
1391
+ components,
1392
+ children: text
1393
+ });
1394
+ });
1395
+ /** Link and image renderers: citations, same-origin links through `navigate`, relative URLs. */
1396
+ function renderers(cited, navigate, baseUrl) {
1397
+ const resolve = (href) => baseUrl ? new URL(href, baseUrl).href : href;
1398
+ const follow = (event, href) => {
1399
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
1400
+ if (href.startsWith("#")) return;
1401
+ event.preventDefault();
1402
+ navigate(href);
1403
+ };
1404
+ return {
1405
+ a({ href = "", children }) {
1406
+ if (href.startsWith(CITE)) {
1407
+ const n = Number(href.slice(14));
1408
+ const hit = cited.get(n)?.hit;
1409
+ if (!hit) return /* @__PURE__ */ jsx(Fragment, { children });
1410
+ return /* @__PURE__ */ jsx("a", {
1411
+ className: "rungent-cite",
1412
+ href: hit.url,
1413
+ title: hit.title,
1414
+ "aria-label": `${n}: ${hit.title}`,
1415
+ onClick: (event) => follow(event, hit.url),
1416
+ children: n
1417
+ });
1418
+ }
1419
+ const target = resolve(href);
1420
+ const external = samePath(target) === null;
1421
+ return /* @__PURE__ */ jsx("a", {
1422
+ href: target,
1423
+ ...external ? {
1424
+ target: "_blank",
1425
+ rel: "noopener noreferrer"
1426
+ } : {},
1427
+ onClick: (event) => follow(event, target),
1428
+ children
1429
+ });
1430
+ },
1431
+ img({ src, alt }) {
1432
+ return typeof src === "string" ? /* @__PURE__ */ jsx("img", {
1433
+ src: resolve(src),
1434
+ alt: alt ?? ""
1435
+ }) : null;
1436
+ },
1437
+ pre({ children }) {
1438
+ return /* @__PURE__ */ jsx("pre", {
1439
+ className: SCROLL_CLASS,
1440
+ children
1441
+ });
1442
+ },
1443
+ table({ children }) {
1444
+ return /* @__PURE__ */ jsx("table", {
1445
+ className: SCROLL_CLASS,
1446
+ children
1447
+ });
1448
+ }
1449
+ };
1450
+ }
1451
+ const NONE = [];
1452
+ /** Safe Markdown: raw HTML is not rendered, and same-origin links route through `onOpen`. */
1453
+ function Markdown({ text, citations = NONE, baseUrl, streaming }) {
1454
+ const { navigate } = useRungent();
1455
+ const cited = useMemo(() => new Map(citations.map((citation) => [citation.n, citation])), [citations]);
1456
+ const components = useMemo(() => renderers(cited, navigate, baseUrl), [
1457
+ cited,
1458
+ navigate,
1459
+ baseUrl
1460
+ ]);
1461
+ return /* @__PURE__ */ jsx("div", {
1462
+ className: "rungent-markdown",
1463
+ "data-streaming": streaming || void 0,
1464
+ children: markdownBlocks(linkCitations(text, cited)).map((block, index) => /* @__PURE__ */ jsx(Block, {
1465
+ text: block,
1466
+ components
1467
+ }, index))
1468
+ });
1469
+ }
1470
+ // src/ring.tsx
1471
+ const SIZE = 18;
1472
+ const RADIUS = 15.5 / 2;
1473
+ const CIRCUMFERENCE = 2 * Math.PI * RADIUS;
1474
+ function compact(tokens, locale) {
1475
+ return new Intl.NumberFormat(locale, {
1476
+ notation: "compact",
1477
+ maximumFractionDigits: 1
1478
+ }).format(tokens);
1479
+ }
1480
+ /** How full the conversation's context is: a ring that turns amber at 70% and red at 90%. */
1481
+ function ContextRing({ usage }) {
1482
+ const { t, locale } = useRungent();
1483
+ const [open, setOpen] = useState(false);
1484
+ const tipId = useId();
1485
+ const percent = Math.round(usage.usedTokens / usage.budgetTokens * 100);
1486
+ const level = percent >= 90 ? "high" : percent >= 70 ? "medium" : "low";
1487
+ const filled = Math.min(percent, 100) / 100;
1488
+ return /* @__PURE__ */ jsxs("span", {
1489
+ className: "rungent-ring-wrap",
1490
+ onMouseEnter: () => setOpen(true),
1491
+ onMouseLeave: () => setOpen(false),
1492
+ children: [/* @__PURE__ */ jsx("button", {
1493
+ type: "button",
1494
+ className: "rungent-ring",
1495
+ "data-level": level,
1496
+ "aria-label": `${t("contextTitle")}: ${t("contextUsed", { percent })}`,
1497
+ "aria-describedby": open ? tipId : void 0,
1498
+ onFocus: () => setOpen(true),
1499
+ onBlur: () => setOpen(false),
1500
+ children: /* @__PURE__ */ jsxs("svg", {
1501
+ width: SIZE,
1502
+ height: SIZE,
1503
+ viewBox: `0 0 ${SIZE} ${SIZE}`,
1504
+ "aria-hidden": "true",
1505
+ children: [/* @__PURE__ */ jsx("circle", {
1506
+ className: "rungent-ring-track",
1507
+ cx: SIZE / 2,
1508
+ cy: SIZE / 2,
1509
+ r: RADIUS
1510
+ }), /* @__PURE__ */ jsx("circle", {
1511
+ className: "rungent-ring-value",
1512
+ cx: SIZE / 2,
1513
+ cy: SIZE / 2,
1514
+ r: RADIUS,
1515
+ strokeDasharray: CIRCUMFERENCE,
1516
+ strokeDashoffset: CIRCUMFERENCE * (1 - filled)
1517
+ })]
1518
+ })
1519
+ }), open ? /* @__PURE__ */ jsxs("span", {
1520
+ id: tipId,
1521
+ role: "tooltip",
1522
+ className: "rungent-ring-tip",
1523
+ children: [
1524
+ /* @__PURE__ */ jsx("strong", { children: percent > 100 ? t("contextOver", { percent: percent - 100 }) : t("contextUsed", { percent }) }),
1525
+ /* @__PURE__ */ jsx("span", { children: t("contextDetail", {
1526
+ used: compact(usage.usedTokens, locale),
1527
+ budget: compact(usage.budgetTokens, locale)
1528
+ }) }),
1529
+ usage.source === "estimated" ? /* @__PURE__ */ jsx("span", {
1530
+ className: "rungent-muted",
1531
+ children: t("contextEstimated")
1532
+ }) : null
1533
+ ]
1534
+ }) : null]
1535
+ });
1536
+ }
1537
+ // src/trace.ts
1538
+ const SEARCH_TOOL = "search";
1539
+ const INPUT_TOOL = "request_input";
1540
+ /**
1541
+ * Groups items into the user's messages, answers and traces: the steps between two of them.
1542
+ * While `running`, a run that has shown nothing yet (or ended a step with text and works on)
1543
+ * gets an empty trace at the end, under the key its first step keeps.
1544
+ */
1545
+ function threadBlocks(items, running) {
1546
+ const blocks = [];
1547
+ let turn = "start";
1548
+ let traces = 0;
1549
+ for (const item of items) {
1550
+ const last = blocks.at(-1);
1551
+ if (item.kind === "user") {
1552
+ turn = item.id;
1553
+ traces = 0;
1554
+ blocks.push({
1555
+ kind: "user",
1556
+ key: item.id,
1557
+ item
1558
+ });
1559
+ } else if (item.kind === "assistant") blocks.push({
1560
+ kind: "answer",
1561
+ key: item.id,
1562
+ item
1563
+ });
1564
+ else if (last?.kind === "trace") last.steps.push(item);
1565
+ else blocks.push({
1566
+ kind: "trace",
1567
+ key: `trace:${turn}:${traces++}`,
1568
+ steps: [item]
1569
+ });
1570
+ }
1571
+ const last = blocks.at(-1);
1572
+ if (running && last?.kind !== "trace" && !(last?.kind === "answer" && last.item.streaming)) blocks.push({
1573
+ kind: "trace",
1574
+ key: `trace:${turn}:${traces}`,
1575
+ steps: []
1576
+ });
1577
+ return blocks;
1578
+ }
1579
+ const isSearch = (tool) => (tool.meta?.op ?? tool.name) === SEARCH_TOOL;
1580
+ const isInput = (tool) => (tool.meta?.op ?? tool.name) === INPUT_TOOL;
1581
+ function parse(json) {
1582
+ if (json === null) return void 0;
1583
+ try {
1584
+ return JSON.parse(json);
1585
+ } catch {
1586
+ return;
1587
+ }
1588
+ }
1589
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1590
+ /** The hits a search step found, from its result. */
1591
+ function searchHits(tool) {
1592
+ const result = parse(tool.result);
1593
+ if (!isRecord(result) || !Array.isArray(result.hits)) return null;
1594
+ return result.hits.flatMap((hit) => isRecord(hit) && typeof hit.title === "string" ? [{
1595
+ title: hit.title,
1596
+ ...typeof hit.url === "string" ? { url: hit.url } : {}
1597
+ }] : []);
1598
+ }
1599
+ const LIST_KEYS = [
1600
+ "items",
1601
+ "data",
1602
+ "results",
1603
+ "records",
1604
+ "list",
1605
+ "hits"
1606
+ ];
1607
+ /** How many things an operation's result lists: an array, or the one list in an object. */
1608
+ function resultCount(json) {
1609
+ const result = parse(json);
1610
+ if (Array.isArray(result)) return result.length;
1611
+ if (!isRecord(result)) return null;
1612
+ for (const key of LIST_KEYS) {
1613
+ const value = result[key];
1614
+ if (Array.isArray(value)) return value.length;
1615
+ }
1616
+ const lists = Object.values(result).filter(Array.isArray);
1617
+ return lists.length === 1 ? lists[0].length : null;
1618
+ }
1619
+ const ARG_LIMIT = 3;
1620
+ const VALUE_LIMIT = 32;
1621
+ /** The call's plain arguments as `key=value`, the first few, long values cut. */
1622
+ function keyArguments(args) {
1623
+ if (!args) return [];
1624
+ return Object.entries(args).filter((entry) => [
1625
+ "string",
1626
+ "number",
1627
+ "boolean"
1628
+ ].includes(typeof entry[1]) && entry[1] !== "").slice(0, ARG_LIMIT).map(([key, value]) => {
1629
+ const text = String(value).replace(/\s+/g, " ");
1630
+ return `${key}=${text.length > VALUE_LIMIT ? `${text.slice(0, 31)}…` : text}`;
1631
+ });
1632
+ }
1633
+ /** The search text of a search step. */
1634
+ function searchQuery(tool) {
1635
+ const q = tool.arguments?.q;
1636
+ return typeof q === "string" ? q.trim() : "";
1637
+ }
1638
+ /** A tool's name for people: its operation's title, else its name made readable. */
1639
+ function toolTitle(tool) {
1640
+ if (tool.meta?.title) return tool.meta.title;
1641
+ const words = tool.name.replace(/[_-]+/g, " ").trim();
1642
+ return words ? words[0]?.toUpperCase() + words.slice(1) : tool.id;
1643
+ }
1644
+ /** What a step did, in a line: `Searched for "q"`, `List servers`, `Thinking…`. */
1645
+ function stepLabel(step, t) {
1646
+ if (step.kind === "progress") return step.message;
1647
+ if (step.kind === "reasoning") return step.streaming ? t("thinking") : t("traceThought");
1648
+ if (isSearch(step)) {
1649
+ const query = searchQuery(step);
1650
+ if (step.status === "running") return query ? t("traceSearching", { query }) : t("searching");
1651
+ return query ? t("traceSearched", { query }) : t("traceSearchedPlain");
1652
+ }
1653
+ if (isInput(step)) return t("traceAsked");
1654
+ return toolTitle(step);
1655
+ }
1656
+ /** What a step found, in short: `5 results`, `zone=bj-1`, `12 items`. */
1657
+ function stepFacts(step, t) {
1658
+ if (step.kind !== "tool" || isInput(step)) return [];
1659
+ if (isSearch(step)) {
1660
+ const hits = step.status === "succeeded" ? searchHits(step) : null;
1661
+ if (!hits) return [];
1662
+ return [hits.length === 1 ? t("traceResult") : t("traceResults", { count: hits.length })];
1663
+ }
1664
+ const facts = keyArguments(step.arguments);
1665
+ const count = step.status === "succeeded" ? resultCount(step.result) : null;
1666
+ if (count !== null) facts.push(count === 1 ? t("traceItem") : t("traceItems", { count }));
1667
+ if (step.deduplicated) facts.push(t("toolDeduplicated"));
1668
+ return facts;
1669
+ }
1670
+ const SUMMARY_LIMIT = 3;
1671
+ /**
1672
+ * What a finished trace did, in one line without its time: `Searched · List servers`. Repeats
1673
+ * fold together; past three it says how many more.
1674
+ */
1675
+ function summarize(steps, t) {
1676
+ const names = [];
1677
+ for (const step of steps) {
1678
+ if (step.kind === "progress") continue;
1679
+ const name = step.kind === "reasoning" ? t("traceThought") : isSearch(step) ? t("traceSearchedPlain") : isInput(step) ? t("traceAsked") : toolTitle(step);
1680
+ if (!names.includes(name)) names.push(name);
1681
+ }
1682
+ const acts = names.length > 1 ? names.filter((name) => name !== t("traceThought")) : names;
1683
+ if (acts.length === 0) return t("traceWorked");
1684
+ const shown = acts.slice(0, SUMMARY_LIMIT);
1685
+ const line = shown.join(t("traceSeparator"));
1686
+ const more = acts.length - shown.length;
1687
+ return more > 0 ? `${line} ${t("traceMore", { count: more })}` : line;
1688
+ }
1689
+ /** The span of a trace in milliseconds by the server's clock, until `endAt` when later. */
1690
+ function traceDuration(steps, endAt) {
1691
+ const starts = steps.map((step) => step.startedAt).filter((at) => at !== null);
1692
+ const ends = steps.map((step) => step.kind === "progress" ? step.startedAt : step.endedAt).concat(endAt).filter((at) => at !== null);
1693
+ if (starts.length === 0 || ends.length === 0) return null;
1694
+ const span = Math.max(...ends) - Math.min(...starts);
1695
+ return span >= 0 ? span : null;
1696
+ }
1697
+ /** A step's time in milliseconds by the server's clock, once it ended. */
1698
+ function stepDuration(step) {
1699
+ if (step.kind === "progress" || step.startedAt === null || step.endedAt === null) return null;
1700
+ return Math.max(0, step.endedAt - step.startedAt);
1701
+ }
1702
+ /** `0.4s`, `12s`, `1m 5s`, in the locale's units. */
1703
+ function formatDuration(ms, locale) {
1704
+ const unit = (value, name, digits = 0) => new Intl.NumberFormat(locale, {
1705
+ style: "unit",
1706
+ unit: name,
1707
+ unitDisplay: "narrow",
1708
+ maximumFractionDigits: digits
1709
+ }).format(value);
1710
+ if (ms < 1e4) return unit(Math.max(ms, 100) / 1e3, "second", 1);
1711
+ const seconds = Math.round(ms / 1e3);
1712
+ if (seconds < 60) return unit(seconds, "second");
1713
+ return `${unit(Math.floor(seconds / 60), "minute")} ${unit(seconds % 60, "second")}`;
1714
+ }
1715
+ // src/trace-view.tsx
1716
+ /** A run's steps, live while it works and folded into one line once it is done. */
1717
+ /**
1718
+ * When this page first saw each step or trace, by id: the server's timestamps say how long a
1719
+ * finished step took, but a live one counts on this clock, which may differ from the server's.
1720
+ * Kept outside React, so a dock that mounts again keeps counting.
1721
+ */
1722
+ const firstSeen = /* @__PURE__ */ new Map();
1723
+ const seen = (id) => {
1724
+ const at = firstSeen.get(id);
1725
+ if (at !== void 0) return at;
1726
+ const now = Date.now();
1727
+ firstSeen.set(id, now);
1728
+ return now;
1729
+ };
1730
+ /** The time now, again every second while `ticking`. */
1731
+ function useNow(ticking) {
1732
+ const [now, setNow] = useState(Date.now);
1733
+ useEffect(() => {
1734
+ if (!ticking) return;
1735
+ setNow(Date.now());
1736
+ const timer = setInterval(() => setNow(Date.now()), 1e3);
1737
+ return () => clearInterval(timer);
1738
+ }, [ticking]);
1739
+ return now;
1740
+ }
1741
+ function Chevron() {
1742
+ return /* @__PURE__ */ jsx("svg", {
1743
+ viewBox: "0 0 24 24",
1744
+ width: "14",
1745
+ height: "14",
1746
+ "aria-hidden": "true",
1747
+ className: "rungent-icon",
1748
+ children: /* @__PURE__ */ jsx("path", { d: "m9 6 6 6-6 6" })
1749
+ });
1750
+ }
1751
+ function StepMark({ mark }) {
1752
+ return mark === "running" ? /* @__PURE__ */ jsx("span", {
1753
+ className: "rungent-spinner rungent-step-mark",
1754
+ "aria-hidden": "true"
1755
+ }) : /* @__PURE__ */ jsx("span", {
1756
+ className: "rungent-step-mark rungent-status",
1757
+ "data-status": mark,
1758
+ "aria-hidden": "true"
1759
+ });
1760
+ }
1761
+ function Json({ label, value }) {
1762
+ const ref = useRef(null);
1763
+ useScrollbar(ref);
1764
+ let text;
1765
+ try {
1766
+ text = JSON.stringify(typeof value === "string" ? JSON.parse(value) : value, null, 2);
1767
+ } catch {
1768
+ text = String(value);
1769
+ }
1770
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
1771
+ className: "rungent-step-json-label",
1772
+ children: label
1773
+ }), /* @__PURE__ */ jsx("pre", {
1774
+ ref,
1775
+ className: `rungent-step-json ${SCROLL_CLASS}`,
1776
+ children: text
1777
+ })] });
1778
+ }
1779
+ /** Reasoning as it streams: a few lines high, following its end while it grows. */
1780
+ function Reasoning({ text, streaming }) {
1781
+ const ref = useRef(null);
1782
+ useScrollbar(ref);
1783
+ useLayoutEffect(() => {
1784
+ const element = ref.current;
1785
+ if (element && streaming && text) element.scrollTop = element.scrollHeight;
1786
+ }, [text, streaming]);
1787
+ return /* @__PURE__ */ jsx("div", {
1788
+ ref,
1789
+ className: `rungent-step-reasoning ${SCROLL_CLASS}`,
1790
+ children: text
1791
+ });
1792
+ }
1793
+ function Hits({ tool }) {
1794
+ const { navigate } = useRungent();
1795
+ const hits = searchHits(tool) ?? [];
1796
+ if (hits.length === 0) return null;
1797
+ const follow = (event, url) => {
1798
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
1799
+ event.preventDefault();
1800
+ navigate(url);
1801
+ };
1802
+ return /* @__PURE__ */ jsx("ol", {
1803
+ className: "rungent-step-hits",
1804
+ children: hits.map((hit, index) => /* @__PURE__ */ jsx("li", { children: hit.url ? /* @__PURE__ */ jsx("a", {
1805
+ href: hit.url,
1806
+ onClick: (event) => follow(event, hit.url),
1807
+ children: hit.title
1808
+ }) : hit.title }, index))
1809
+ });
1810
+ }
1811
+ /** What a step shows when opened: hits, reasoning, the error, and its JSON on request. */
1812
+ function stepBody(step, t) {
1813
+ if (step.kind === "reasoning") return step.text ? /* @__PURE__ */ jsx(Reasoning, {
1814
+ text: step.text,
1815
+ streaming: step.streaming
1816
+ }) : null;
1817
+ if (step.kind !== "tool") return null;
1818
+ const hits = isSearch(step) && step.status === "succeeded" ? /* @__PURE__ */ jsx(Hits, { tool: step }) : null;
1819
+ const json = step.arguments || step.result ? /* @__PURE__ */ jsxs("details", {
1820
+ className: "rungent-step-details",
1821
+ children: [
1822
+ /* @__PURE__ */ jsx("summary", { children: t("traceDetails") }),
1823
+ step.arguments ? /* @__PURE__ */ jsx(Json, {
1824
+ label: t("traceArguments"),
1825
+ value: step.arguments
1826
+ }) : null,
1827
+ step.result ? /* @__PURE__ */ jsx(Json, {
1828
+ label: t("traceResultJson"),
1829
+ value: step.result
1830
+ }) : null
1831
+ ]
1832
+ }) : null;
1833
+ return hits || json ? /* @__PURE__ */ jsxs(Fragment, { children: [hits, json] }) : null;
1834
+ }
1835
+ function Step({ step, active, live, awaiting, now }) {
1836
+ const { t, locale } = useRungent();
1837
+ const unfinished = step.kind === "tool" && step.status === "running" || step.kind === "reasoning" && step.streaming;
1838
+ const running = unfinished && active && awaiting === null;
1839
+ const [open, setOpen] = useState(null);
1840
+ const expanded = open ?? (step.kind === "reasoning" && step.streaming);
1841
+ const bodyId = useId();
1842
+ const startedHere = seen(step.id);
1843
+ const body = stepBody(step, t);
1844
+ const failed = step.kind === "tool" && step.status === "failed";
1845
+ const mark = running ? "running" : awaiting ? "waiting" : failed ? "failed" : step.kind === "progress" || unfinished ? "note" : "succeeded";
1846
+ const duration = running ? now - startedHere : stepDuration(step);
1847
+ const facts = stepFacts(step, t);
1848
+ if (awaiting) facts.push(awaiting === "approval" ? t("toolAwaitingApproval") : awaiting === "form" ? t("toolAwaitingInput") : t("traceAwaitingAnswer"));
1849
+ const row = /* @__PURE__ */ jsxs(Fragment, { children: [
1850
+ /* @__PURE__ */ jsx(StepMark, { mark }),
1851
+ /* @__PURE__ */ jsxs("span", {
1852
+ className: "rungent-step-text",
1853
+ children: [/* @__PURE__ */ jsx("span", {
1854
+ className: "rungent-step-label",
1855
+ children: stepLabel(step, t)
1856
+ }), facts.map((fact) => /* @__PURE__ */ jsx("span", {
1857
+ className: "rungent-step-fact",
1858
+ children: fact
1859
+ }, fact))]
1860
+ }),
1861
+ duration !== null && (running || duration >= 100) && step.kind !== "progress" ? /* @__PURE__ */ jsx("span", {
1862
+ className: "rungent-step-time",
1863
+ children: formatDuration(duration, locale)
1864
+ }) : null,
1865
+ body ? /* @__PURE__ */ jsx(Chevron, {}) : null
1866
+ ] });
1867
+ return /* @__PURE__ */ jsxs("li", {
1868
+ className: "rungent-step",
1869
+ "data-live": live || void 0,
1870
+ "data-open": body && expanded || void 0,
1871
+ children: [
1872
+ body ? /* @__PURE__ */ jsx("button", {
1873
+ type: "button",
1874
+ className: "rungent-step-row",
1875
+ "aria-expanded": expanded,
1876
+ "aria-controls": bodyId,
1877
+ onClick: () => setOpen(!expanded),
1878
+ children: row
1879
+ }) : /* @__PURE__ */ jsx("div", {
1880
+ className: "rungent-step-row",
1881
+ children: row
1882
+ }),
1883
+ failed && step.kind === "tool" ? /* @__PURE__ */ jsx("p", {
1884
+ className: "rungent-step-error",
1885
+ children: step.error?.code === "not_executed" ? t("toolNotExecuted") : step.error?.message || t("toolFailed")
1886
+ }) : null,
1887
+ body && expanded ? /* @__PURE__ */ jsx("div", {
1888
+ id: bodyId,
1889
+ className: "rungent-step-body",
1890
+ children: body
1891
+ }) : null
1892
+ ]
1893
+ });
1894
+ }
1895
+ /**
1896
+ * The steps of a run: each with what it did, its time, and what it found on request. Live, the
1897
+ * header says what the run does now and the steps are open; done, it folds into one line
1898
+ * (`Searched, list servers · 14s`) that opens again on a click.
1899
+ */
1900
+ function Trace({ traceKey, steps, live, writing, endAt, retry, awaiting }) {
1901
+ const { t, locale } = useRungent();
1902
+ const [open, setOpen] = useState(null);
1903
+ const waiting = steps.some((step) => step.kind === "tool" && awaiting(step.id) !== null);
1904
+ const expanded = open ?? (live && !writing || waiting);
1905
+ const startedHere = seen(traceKey);
1906
+ const now = useNow(live);
1907
+ const listId = useId();
1908
+ const last = steps.at(-1);
1909
+ const lastRunning = last && (last.kind === "tool" && last.status === "running" || last.kind === "reasoning" && last.streaming);
1910
+ const thinking = live && !writing && !lastRunning;
1911
+ const failed = steps.some((step) => step.kind === "tool" && step.status === "failed");
1912
+ let title;
1913
+ if (live) title = retry ? t("retrying", {
1914
+ attempt: retry.attempt,
1915
+ max: retry.maxAttempts
1916
+ }) : writing ? t("traceWriting") : expanded && steps.length > 0 ? t("traceWorking") : thinking || !last ? t("thinking") : stepLabel(last, t);
1917
+ else title = summarize(steps, t);
1918
+ const duration = live ? now - startedHere : traceDuration(steps, endAt);
1919
+ return /* @__PURE__ */ jsxs("section", {
1920
+ className: "rungent-trace",
1921
+ "data-live": live || void 0,
1922
+ "aria-label": title,
1923
+ children: [/* @__PURE__ */ jsxs("button", {
1924
+ type: "button",
1925
+ className: "rungent-trace-head",
1926
+ "aria-expanded": expanded,
1927
+ "aria-controls": listId,
1928
+ onClick: () => setOpen(!expanded),
1929
+ disabled: steps.length === 0,
1930
+ children: [
1931
+ /* @__PURE__ */ jsx(StepMark, { mark: live ? "running" : waiting ? "waiting" : failed ? "failed" : "succeeded" }),
1932
+ /* @__PURE__ */ jsx("span", {
1933
+ className: "rungent-trace-title",
1934
+ children: title
1935
+ }),
1936
+ duration !== null && (live ? duration >= 2e3 : true) ? /* @__PURE__ */ jsx("span", {
1937
+ className: "rungent-step-time",
1938
+ children: formatDuration(duration, locale)
1939
+ }) : null,
1940
+ steps.length > 0 ? /* @__PURE__ */ jsx(Chevron, {}) : null
1941
+ ]
1942
+ }), expanded && steps.length > 0 ? /* @__PURE__ */ jsxs("ol", {
1943
+ id: listId,
1944
+ className: "rungent-steps",
1945
+ children: [steps.map((step) => /* @__PURE__ */ jsx(Step, {
1946
+ step,
1947
+ active: live,
1948
+ live: live && step === last && !thinking,
1949
+ awaiting: step.kind === "tool" ? awaiting(step.id) : null,
1950
+ now
1951
+ }, step.id)), thinking ? /* @__PURE__ */ jsx("li", {
1952
+ className: "rungent-step",
1953
+ "data-live": "",
1954
+ children: /* @__PURE__ */ jsxs("div", {
1955
+ className: "rungent-step-row",
1956
+ children: [/* @__PURE__ */ jsx(StepMark, { mark: "running" }), /* @__PURE__ */ jsx("span", {
1957
+ className: "rungent-step-text",
1958
+ children: /* @__PURE__ */ jsx("span", {
1959
+ className: "rungent-step-label",
1960
+ children: t("thinking")
1961
+ })
1962
+ })]
1963
+ })
1964
+ }) : null]
1965
+ }) : null]
1966
+ });
1967
+ }
1968
+ // src/thread.tsx
1969
+ /**
1970
+ * An operation's form: the host's own component for the operation when it registered one, else
1971
+ * the generic form the host's `role: form` operation described. Both start from the arguments.
1972
+ */
1973
+ function HostForm({ open, submit, submitAnswers, cancel }) {
1974
+ const { forms, t } = useRungent();
1975
+ const root = useRoot("rungent-card rungent-host-form");
1976
+ const { op, form, arguments: args, issues = [] } = open.meta;
1977
+ const Own = forms[op];
1978
+ if (!Own) return /* @__PURE__ */ jsx(RungentForm, {
1979
+ form,
1980
+ values: args,
1981
+ issues,
1982
+ onSubmit: submitAnswers,
1983
+ onCancel: cancel
1984
+ });
1985
+ return /* @__PURE__ */ jsxs("section", {
1986
+ ...root,
1987
+ "aria-label": form.prompt,
1988
+ "data-op": op,
1989
+ children: [
1990
+ /* @__PURE__ */ jsx("h3", {
1991
+ className: "rungent-card-title",
1992
+ children: form.prompt
1993
+ }),
1994
+ issues.length > 0 ? /* @__PURE__ */ jsxs("div", {
1995
+ className: "rungent-issue",
1996
+ role: "alert",
1997
+ children: [t("formIssues"), /* @__PURE__ */ jsx("ul", { children: issues.map((issue) => /* @__PURE__ */ jsxs("li", { children: [issue.path ? `${issue.path}: ` : "", issue.message] }, `${issue.path}:${issue.message}`)) })]
1998
+ }) : null,
1999
+ /* @__PURE__ */ jsx(Own, {
2000
+ op,
2001
+ arguments: args,
2002
+ issues,
2003
+ submit,
2004
+ cancel
2005
+ })
2006
+ ]
2007
+ });
2008
+ }
2009
+ /** Answers an interrupt, then moves focus to the composer: the card it came from goes away. */
2010
+ function Interrupt({ open, thread, focusComposer }) {
2011
+ const answer = (entries) => {
2012
+ focusComposer();
2013
+ thread.resume(entries);
2014
+ };
2015
+ const { t } = useRungent();
2016
+ switch (open.kind) {
2017
+ case "approval": return /* @__PURE__ */ jsx(ApprovalCard, {
2018
+ interrupt: open,
2019
+ onAnswer: (approved) => answer([answerApproval(open, approved)])
2020
+ });
2021
+ case "input": return /* @__PURE__ */ jsx(RungentForm, {
2022
+ form: open.form,
2023
+ onSubmit: (answers) => answer([answerInput(open, answers)])
2024
+ });
2025
+ case "form": return /* @__PURE__ */ jsx(HostForm, {
2026
+ open,
2027
+ submit: (args) => answer([submitForm(open, args)]),
2028
+ submitAnswers: (answers) => answer([submitFormAnswers(open, answers)]),
2029
+ cancel: () => answer(cancelAll([open]))
2030
+ });
2031
+ case "task": return /* @__PURE__ */ jsxs("div", {
2032
+ className: "rungent-card rungent-task",
2033
+ role: "status",
2034
+ children: [
2035
+ /* @__PURE__ */ jsx("span", {
2036
+ className: "rungent-spinner",
2037
+ "aria-hidden": "true"
2038
+ }),
2039
+ /* @__PURE__ */ jsx("span", { children: open.progress?.message ?? t("taskRunning", { op: open.op }) }),
2040
+ /* @__PURE__ */ jsx("button", {
2041
+ type: "button",
2042
+ className: "rungent-button",
2043
+ onClick: () => answer(cancelAll([open])),
2044
+ children: t("cancelTask")
2045
+ })
2046
+ ]
2047
+ });
2048
+ default: return null;
2049
+ }
2050
+ }
2051
+ function errorKey(code) {
2052
+ switch (code) {
2053
+ case "model_unavailable":
2054
+ case "max_steps":
2055
+ case "open_interrupts":
2056
+ case "history_conflict":
2057
+ case "invalid_interaction": return `error.${code}`;
2058
+ default: return "error.internal";
2059
+ }
2060
+ }
2061
+ let nextAttachment = 0;
2062
+ function useAttachments() {
2063
+ const { upload } = useRungent();
2064
+ const [pending, setPending] = useState([]);
2065
+ const settle = (key, change) => setPending((current) => current.map((item) => item.key === key ? {
2066
+ ...item,
2067
+ ...change
2068
+ } : item));
2069
+ const add = (files) => {
2070
+ if (!upload) return;
2071
+ for (const file of files) {
2072
+ const key = nextAttachment++;
2073
+ setPending((current) => [...current, {
2074
+ key,
2075
+ name: file.name,
2076
+ image: file.type.startsWith("image/"),
2077
+ status: "uploading"
2078
+ }]);
2079
+ upload(file).then((uploaded) => settle(key, {
2080
+ status: "done",
2081
+ file: uploaded
2082
+ }), () => settle(key, { status: "failed" }));
2083
+ }
2084
+ };
2085
+ return {
2086
+ pending,
2087
+ add,
2088
+ remove: (key) => setPending((current) => current.filter((item) => item.key !== key)),
2089
+ clear: () => setPending([])
2090
+ };
2091
+ }
2092
+ function PaperclipIcon() {
2093
+ return /* @__PURE__ */ jsx("svg", {
2094
+ viewBox: "0 0 24 24",
2095
+ width: "18",
2096
+ height: "18",
2097
+ "aria-hidden": "true",
2098
+ className: "rungent-icon",
2099
+ children: /* @__PURE__ */ jsx("path", { d: "m21.4 11.1-8.6 8.6a5.7 5.7 0 0 1-8-8l8.5-8.6a3.8 3.8 0 0 1 5.4 5.4l-8.6 8.6a1.9 1.9 0 0 1-2.7-2.7l7.9-7.9" })
2100
+ });
2101
+ }
2102
+ function FileIcon() {
2103
+ return /* @__PURE__ */ jsxs("svg", {
2104
+ viewBox: "0 0 24 24",
2105
+ width: "16",
2106
+ height: "16",
2107
+ "aria-hidden": "true",
2108
+ className: "rungent-icon",
2109
+ children: [/* @__PURE__ */ jsx("path", { d: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" }), /* @__PURE__ */ jsx("path", { d: "M14 2v6h6" })]
2110
+ });
2111
+ }
2112
+ function ThumbIcon({ down }) {
2113
+ return /* @__PURE__ */ jsxs("svg", {
2114
+ viewBox: "0 0 24 24",
2115
+ width: "15",
2116
+ height: "15",
2117
+ "aria-hidden": "true",
2118
+ className: "rungent-icon",
2119
+ style: down ? { transform: "scaleY(-1)" } : void 0,
2120
+ children: [/* @__PURE__ */ jsx("path", { d: "M7 10v12" }), /* @__PURE__ */ jsx("path", { d: "M15 5.9 14 10h5.8a2 2 0 0 1 1.9 2.6l-2.3 8a2 2 0 0 1-1.9 1.4H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.8a2 2 0 0 0 1.8-1.1L12 2a3.1 3.1 0 0 1 3 3.9Z" })]
2121
+ });
2122
+ }
2123
+ function PendingList({ attachments }) {
2124
+ const { t } = useRungent();
2125
+ const { pending, remove } = attachments;
2126
+ if (pending.length === 0) return null;
2127
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("ul", {
2128
+ className: "rungent-attachments",
2129
+ "aria-label": t("attachments"),
2130
+ children: pending.map((item) => /* @__PURE__ */ jsxs("li", {
2131
+ className: item.image ? "rungent-attachment rungent-thumb" : "rungent-attachment rungent-chip",
2132
+ "data-status": item.status,
2133
+ "aria-busy": item.status === "uploading" || void 0,
2134
+ children: [
2135
+ item.status === "uploading" ? /* @__PURE__ */ jsx("span", {
2136
+ className: "rungent-spinner",
2137
+ role: "img",
2138
+ "aria-label": t("uploading", { file: item.name })
2139
+ }) : item.image && item.file ? /* @__PURE__ */ jsx("img", {
2140
+ className: "rungent-thumb-img",
2141
+ src: item.file.url,
2142
+ alt: item.name
2143
+ }) : /* @__PURE__ */ jsx(FileIcon, {}),
2144
+ item.image ? null : /* @__PURE__ */ jsx("span", {
2145
+ className: "rungent-attachment-name",
2146
+ children: item.name
2147
+ }),
2148
+ /* @__PURE__ */ jsx("button", {
2149
+ type: "button",
2150
+ className: "rungent-attachment-remove",
2151
+ "aria-label": t("removeAttachment", { file: item.name }),
2152
+ onClick: () => remove(item.key),
2153
+ children: "×"
2154
+ })
2155
+ ]
2156
+ }, item.key))
2157
+ }), pending.filter((item) => item.status === "failed").map((item) => /* @__PURE__ */ jsx("p", {
2158
+ className: "rungent-error rungent-small rungent-upload-error",
2159
+ role: "alert",
2160
+ children: t("uploadFailed", { file: item.name })
2161
+ }, item.key))] });
2162
+ }
2163
+ function SendIcon() {
2164
+ return /* @__PURE__ */ jsxs("svg", {
2165
+ viewBox: "0 0 24 24",
2166
+ width: "16",
2167
+ height: "16",
2168
+ "aria-hidden": "true",
2169
+ className: "rungent-icon",
2170
+ children: [/* @__PURE__ */ jsx("path", { d: "M12 19V5" }), /* @__PURE__ */ jsx("path", { d: "m5 12 7-7 7 7" })]
2171
+ });
2172
+ }
2173
+ function StopIcon() {
2174
+ return /* @__PURE__ */ jsx("svg", {
2175
+ viewBox: "0 0 24 24",
2176
+ width: "14",
2177
+ height: "14",
2178
+ "aria-hidden": "true",
2179
+ children: /* @__PURE__ */ jsx("rect", {
2180
+ x: "5",
2181
+ y: "5",
2182
+ width: "14",
2183
+ height: "14",
2184
+ rx: "2",
2185
+ fill: "currentColor"
2186
+ })
2187
+ });
2188
+ }
2189
+ /**
2190
+ * The message box: one card with the text, which grows with it and then scrolls, and a row
2191
+ * under it with attachments and the context ring on the left and send or stop on the right.
2192
+ */
2193
+ function Composer({ thread, attachments }) {
2194
+ const { t, upload } = useRungent();
2195
+ const [text, setText] = useState("");
2196
+ const input = useRef(null);
2197
+ const running = thread.state.status === "running";
2198
+ const ready = attachments.pending.flatMap((item) => item.status === "done" && item.file ? [item.file] : []);
2199
+ const uploading = attachments.pending.some((item) => item.status === "uploading");
2200
+ const canSend = !running && !uploading && (text.trim() !== "" || ready.length > 0);
2201
+ useAutosize(input, text, useCallback(() => input.current?.closest(".rungent-thread")?.clientHeight || window.innerHeight, []));
2202
+ useScrollbar(input);
2203
+ const wasRunning = useRef(running);
2204
+ useEffect(() => {
2205
+ if (wasRunning.current && !running) {
2206
+ const active = document.activeElement;
2207
+ const thread = input.current?.closest(".rungent-thread");
2208
+ if (!active || active === document.body || thread?.contains(active)) input.current?.focus();
2209
+ }
2210
+ wasRunning.current = running;
2211
+ }, [running]);
2212
+ const send = () => {
2213
+ if (!canSend) return;
2214
+ const message = text.trim();
2215
+ setText("");
2216
+ attachments.clear();
2217
+ thread.send(ready.length === 0 ? message : [...message ? [{
2218
+ type: "text",
2219
+ text: message
2220
+ }] : [], ...ready.map((file) => attachmentPart(file))]);
2221
+ };
2222
+ const onKeyDown = (event) => {
2223
+ const composing = event.nativeEvent.isComposing || event.keyCode === 229;
2224
+ if (event.key === "Enter" && !event.shiftKey && !composing) {
2225
+ event.preventDefault();
2226
+ send();
2227
+ }
2228
+ };
2229
+ const onPaste = (event) => {
2230
+ const files = [...event.clipboardData.files];
2231
+ if (!upload || files.length === 0) return;
2232
+ event.preventDefault();
2233
+ attachments.add(files);
2234
+ };
2235
+ const context = thread.state.context;
2236
+ const started = thread.state.items.length > 0 || running;
2237
+ return /* @__PURE__ */ jsx("form", {
2238
+ className: "rungent-composer",
2239
+ onSubmit: (event) => {
2240
+ event.preventDefault();
2241
+ send();
2242
+ },
2243
+ children: /* @__PURE__ */ jsxs("div", {
2244
+ className: "rungent-composer-box",
2245
+ children: [
2246
+ /* @__PURE__ */ jsx(PendingList, { attachments }),
2247
+ /* @__PURE__ */ jsx("textarea", {
2248
+ ref: input,
2249
+ className: `rungent-composer-input ${SCROLL_CLASS}`,
2250
+ rows: 1,
2251
+ "aria-label": t("composerLabel"),
2252
+ placeholder: t("composerPlaceholder"),
2253
+ value: text,
2254
+ onChange: (event) => setText(event.target.value),
2255
+ onKeyDown,
2256
+ onPaste,
2257
+ "data-rungent-autofocus": ""
2258
+ }),
2259
+ /* @__PURE__ */ jsxs("div", {
2260
+ className: "rungent-composer-bar",
2261
+ children: [
2262
+ upload ? /* @__PURE__ */ jsxs("label", {
2263
+ className: "rungent-icon-button rungent-attach",
2264
+ title: t("attach"),
2265
+ children: [
2266
+ /* @__PURE__ */ jsx("input", {
2267
+ type: "file",
2268
+ multiple: true,
2269
+ className: "rungent-visually-hidden",
2270
+ onChange: (event) => {
2271
+ attachments.add([...event.target.files ?? []]);
2272
+ event.target.value = "";
2273
+ }
2274
+ }),
2275
+ /* @__PURE__ */ jsx(PaperclipIcon, {}),
2276
+ /* @__PURE__ */ jsx("span", {
2277
+ className: "rungent-visually-hidden",
2278
+ children: t("attach")
2279
+ })
2280
+ ]
2281
+ }) : null,
2282
+ context && started ? /* @__PURE__ */ jsx(ContextRing, { usage: context }) : null,
2283
+ /* @__PURE__ */ jsx("span", { className: "rungent-composer-spacer" }),
2284
+ running ? /* @__PURE__ */ jsx("button", {
2285
+ type: "button",
2286
+ className: "rungent-send",
2287
+ "data-stop": "",
2288
+ "aria-label": t("stop"),
2289
+ title: t("stop"),
2290
+ onClick: () => void thread.cancel(),
2291
+ children: /* @__PURE__ */ jsx(StopIcon, {})
2292
+ }) : /* @__PURE__ */ jsx("button", {
2293
+ type: "submit",
2294
+ className: "rungent-send",
2295
+ "aria-label": t("send"),
2296
+ title: t("send"),
2297
+ disabled: !canSend,
2298
+ children: /* @__PURE__ */ jsx(SendIcon, {})
2299
+ })
2300
+ ]
2301
+ })
2302
+ ]
2303
+ })
2304
+ });
2305
+ }
2306
+ function UserMessage({ item }) {
2307
+ const { t } = useRungent();
2308
+ return /* @__PURE__ */ jsxs("div", {
2309
+ className: "rungent-user-turn",
2310
+ children: [item.attachments.length > 0 ? /* @__PURE__ */ jsx("ul", {
2311
+ className: "rungent-attachments rungent-sent",
2312
+ "aria-label": t("attachments"),
2313
+ children: item.attachments.map((attachment, index) => {
2314
+ const name = attachment.name ?? t(attachment.kind === "image" ? "image" : "file");
2315
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("a", {
2316
+ className: attachment.kind === "image" ? "rungent-attachment rungent-thumb" : "rungent-attachment rungent-chip",
2317
+ href: attachment.url,
2318
+ target: "_blank",
2319
+ rel: "noopener noreferrer",
2320
+ "aria-label": t("openAttachment", { file: name }),
2321
+ children: attachment.kind === "image" ? /* @__PURE__ */ jsx("img", {
2322
+ className: "rungent-thumb-img",
2323
+ src: attachment.url,
2324
+ alt: ""
2325
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(FileIcon, {}), /* @__PURE__ */ jsx("span", {
2326
+ className: "rungent-attachment-name",
2327
+ children: name
2328
+ })] })
2329
+ }) }, index);
2330
+ })
2331
+ }) : null, item.text ? /* @__PURE__ */ jsx("div", {
2332
+ className: "rungent-message rungent-user",
2333
+ children: item.text
2334
+ }) : null]
2335
+ });
2336
+ }
2337
+ function Rating({ threadId, messageId }) {
2338
+ const { client, t } = useRungent();
2339
+ const [rating, setRating] = useState(null);
2340
+ const [asking, setAsking] = useState(false);
2341
+ const [comment, setComment] = useState("");
2342
+ const [status, setStatus] = useState("idle");
2343
+ const send = (feedback) => client.setFeedback(threadId, messageId, feedback).then(() => setStatus("sent"), () => setStatus("failed"));
2344
+ const rate = (next) => {
2345
+ setRating(next);
2346
+ setAsking(next === "down");
2347
+ setComment("");
2348
+ setStatus("idle");
2349
+ send({ rating: next });
2350
+ };
2351
+ return /* @__PURE__ */ jsxs("div", {
2352
+ className: "rungent-feedback",
2353
+ children: [/* @__PURE__ */ jsxs("div", {
2354
+ className: "rungent-feedback-buttons",
2355
+ role: "group",
2356
+ "aria-label": t("rateAnswer"),
2357
+ children: [
2358
+ /* @__PURE__ */ jsx("button", {
2359
+ type: "button",
2360
+ className: "rungent-icon-button rungent-feedback-button",
2361
+ "aria-pressed": rating === "up",
2362
+ "aria-label": t("goodAnswer"),
2363
+ title: t("goodAnswer"),
2364
+ onClick: () => rate("up"),
2365
+ children: /* @__PURE__ */ jsx(ThumbIcon, {})
2366
+ }),
2367
+ /* @__PURE__ */ jsx("button", {
2368
+ type: "button",
2369
+ className: "rungent-icon-button rungent-feedback-button",
2370
+ "aria-pressed": rating === "down",
2371
+ "aria-label": t("badAnswer"),
2372
+ title: t("badAnswer"),
2373
+ onClick: () => rate("down"),
2374
+ children: /* @__PURE__ */ jsx(ThumbIcon, { down: true })
2375
+ }),
2376
+ /* @__PURE__ */ jsx("span", {
2377
+ className: "rungent-muted rungent-small",
2378
+ role: "status",
2379
+ children: status === "failed" ? t("feedbackFailed") : status === "sent" && !asking ? t("feedbackThanks") : null
2380
+ })
2381
+ ]
2382
+ }), asking ? /* @__PURE__ */ jsxs("form", {
2383
+ className: "rungent-feedback-form",
2384
+ onSubmit: (event) => {
2385
+ event.preventDefault();
2386
+ setAsking(false);
2387
+ const text = comment.trim();
2388
+ if (text) send({
2389
+ rating: "down",
2390
+ comment: text
2391
+ });
2392
+ },
2393
+ children: [
2394
+ /* @__PURE__ */ jsx("input", {
2395
+ className: "rungent-input",
2396
+ "aria-label": t("feedbackComment"),
2397
+ placeholder: t("feedbackComment"),
2398
+ value: comment,
2399
+ onChange: (event) => setComment(event.target.value)
2400
+ }),
2401
+ /* @__PURE__ */ jsx("button", {
2402
+ type: "button",
2403
+ className: "rungent-button rungent-ghost",
2404
+ onClick: () => setAsking(false),
2405
+ children: t("feedbackSkip")
2406
+ }),
2407
+ /* @__PURE__ */ jsx("button", {
2408
+ type: "submit",
2409
+ className: "rungent-button",
2410
+ disabled: !comment.trim(),
2411
+ children: t("feedbackSend")
2412
+ })
2413
+ ]
2414
+ }) : null]
2415
+ });
2416
+ }
2417
+ /** The last answer of each finished turn, which the user can rate. */
2418
+ function rateable(items, running) {
2419
+ const ids = /* @__PURE__ */ new Set();
2420
+ let last = null;
2421
+ for (const item of items) if (item.kind === "user") {
2422
+ if (last) ids.add(last);
2423
+ last = null;
2424
+ } else if (item.kind === "assistant" && !item.streaming && item.text.trim()) last = item.id;
2425
+ if (last && !running) ids.add(last);
2426
+ return ids;
2427
+ }
2428
+ function hasFiles(event) {
2429
+ return [...event.dataTransfer.types].includes("Files");
2430
+ }
2431
+ /** Within this many pixels of the end, the reader is "at the latest" and new content follows. */
2432
+ const PIN_SLACK = 48;
2433
+ /** Where the reader left each thread that is not at its end, so it shows there again. */
2434
+ const scrolled = /* @__PURE__ */ new Map();
2435
+ /**
2436
+ * Keeps a scroll container at its end while its content grows, unless the reader scrolled up to
2437
+ * read; `pin` brings it back to the end and keeps it there. A thread (`key`) shown again, say by
2438
+ * a dock mounted again, opens where the reader left it.
2439
+ */
2440
+ function useStickToBottom(scroller, key) {
2441
+ const pinned = useRef(true);
2442
+ const [atEnd, setAtEnd] = useState(true);
2443
+ const keyRef = useRef(key);
2444
+ keyRef.current = key;
2445
+ const toEnd = useCallback(() => {
2446
+ const element = scroller.current;
2447
+ if (element) element.scrollTop = element.scrollHeight;
2448
+ }, [scroller]);
2449
+ useLayoutEffect(() => {
2450
+ const element = scroller.current;
2451
+ const top = key === null ? void 0 : scrolled.get(key);
2452
+ if (!element || top === void 0) return;
2453
+ element.scrollTop = top;
2454
+ pinned.current = false;
2455
+ setAtEnd(false);
2456
+ }, [key]);
2457
+ useEffect(() => {
2458
+ const element = scroller.current;
2459
+ if (!element) return;
2460
+ const onScroll = () => {
2461
+ const near = element.scrollHeight - element.scrollTop - element.clientHeight <= PIN_SLACK;
2462
+ pinned.current = near;
2463
+ setAtEnd(near);
2464
+ const key = keyRef.current;
2465
+ if (key !== null) {
2466
+ if (near) scrolled.delete(key);
2467
+ else scrolled.set(key, element.scrollTop);
2468
+ }
2469
+ };
2470
+ element.addEventListener("scroll", onScroll, { passive: true });
2471
+ const observer = typeof ResizeObserver === "undefined" ? void 0 : new ResizeObserver(() => {
2472
+ if (pinned.current) toEnd();
2473
+ });
2474
+ observer?.observe(element);
2475
+ for (const child of element.children) observer?.observe(child);
2476
+ const children = new MutationObserver(() => {
2477
+ observer?.disconnect();
2478
+ observer?.observe(element);
2479
+ for (const child of element.children) observer?.observe(child);
2480
+ if (pinned.current) toEnd();
2481
+ });
2482
+ children.observe(element, {
2483
+ childList: true,
2484
+ subtree: true,
2485
+ characterData: true
2486
+ });
2487
+ return () => {
2488
+ element.removeEventListener("scroll", onScroll);
2489
+ observer?.disconnect();
2490
+ children.disconnect();
2491
+ };
2492
+ }, [scroller, toEnd]);
2493
+ return {
2494
+ atEnd,
2495
+ pin: useCallback(() => {
2496
+ pinned.current = true;
2497
+ setAtEnd(true);
2498
+ toEnd();
2499
+ }, [toEnd])
2500
+ };
2501
+ }
2502
+ /** An empty conversation: what rungent can do, and questions to start from. */
2503
+ function Welcome({ ask }) {
2504
+ const { t, suggestions } = useRungent();
2505
+ const questions = suggestions?.() ?? [];
2506
+ return /* @__PURE__ */ jsxs("div", {
2507
+ className: "rungent-welcome",
2508
+ children: [
2509
+ /* @__PURE__ */ jsx("span", {
2510
+ className: "rungent-welcome-mark",
2511
+ "aria-hidden": "true",
2512
+ children: "✦"
2513
+ }),
2514
+ /* @__PURE__ */ jsx("h3", {
2515
+ className: "rungent-welcome-title",
2516
+ children: t("welcomeTitle")
2517
+ }),
2518
+ /* @__PURE__ */ jsx("p", {
2519
+ className: "rungent-muted",
2520
+ children: t("welcome")
2521
+ }),
2522
+ questions.length > 0 ? /* @__PURE__ */ jsx("ul", {
2523
+ className: "rungent-suggestions",
2524
+ "aria-label": t("suggestions"),
2525
+ children: questions.map((question) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx("button", {
2526
+ type: "button",
2527
+ className: "rungent-suggestion",
2528
+ onClick: () => ask(question),
2529
+ children: question
2530
+ }) }, question))
2531
+ }) : null
2532
+ ]
2533
+ });
2534
+ }
2535
+ const NO_CITATIONS = [];
2536
+ /** An answer that started this long before it mounted is replayed history. */
2537
+ const HISTORY_MS = 5e3;
2538
+ /** An answer: text revealed at a steady pace while it streams, with a caret at its end. */
2539
+ function AssistantMessage({ item, citations, children }) {
2540
+ const [history] = useState(() => item.startedAt !== null && item.startedAt < Date.now() - HISTORY_MS);
2541
+ const smooth = useSmoothText(item.text, item.streaming && !history);
2542
+ const shown = history ? item.text : smooth;
2543
+ const typing = item.streaming || shown.length < item.text.length;
2544
+ return /* @__PURE__ */ jsxs("div", {
2545
+ className: "rungent-message rungent-assistant",
2546
+ "aria-busy": typing || void 0,
2547
+ children: [/* @__PURE__ */ jsx(Markdown, {
2548
+ text: typing ? settlePartialMarkdown(shown) : item.text,
2549
+ citations: citations ?? NO_CITATIONS,
2550
+ streaming: typing
2551
+ }), typing ? null : children]
2552
+ });
2553
+ }
2554
+ /** One conversation: messages, tool activity, open requests and the composer. */
2555
+ function RungentThread({ threadId, onThreadCreated, initialMessage }) {
2556
+ const { t, upload } = useRungent();
2557
+ const root = useRoot("rungent-thread");
2558
+ const thread = useThread(threadId);
2559
+ const { state } = thread;
2560
+ const attachments = useAttachments();
2561
+ const [dragging, setDragging] = useState(false);
2562
+ const scroller = useRef(null);
2563
+ const rootRef = useRef(null);
2564
+ const { atEnd, pin } = useStickToBottom(scroller, thread.threadId);
2565
+ useScrollbar(scroller);
2566
+ const focusComposer = () => rootRef.current?.querySelector("[data-rungent-autofocus]")?.focus();
2567
+ const sentInitial = useRef(false);
2568
+ useEffect(() => {
2569
+ if (initialMessage && !sentInitial.current) {
2570
+ sentInitial.current = true;
2571
+ thread.send(initialMessage);
2572
+ }
2573
+ }, [initialMessage, thread.send]);
2574
+ useEffect(() => {
2575
+ if (threadId === null && thread.threadId) onThreadCreated?.(thread.threadId);
2576
+ }, [
2577
+ thread.threadId,
2578
+ threadId,
2579
+ onThreadCreated
2580
+ ]);
2581
+ const userTurns = state.items.filter((item) => item.kind === "user").length;
2582
+ const turnsSeen = useRef(userTurns);
2583
+ useEffect(() => {
2584
+ if (userTurns > turnsSeen.current) pin();
2585
+ turnsSeen.current = userTurns;
2586
+ }, [userTurns, pin]);
2587
+ const running = state.status === "running";
2588
+ const rated = rateable(state.items, running);
2589
+ const blocks = threadBlocks(state.items, running);
2590
+ const lastTrace = blocks.findLastIndex((block) => block.kind === "trace");
2591
+ const liveTrace = lastTrace > blocks.findLastIndex((block) => block.kind === "user") ? lastTrace : -1;
2592
+ const awaiting = (toolCallId) => {
2593
+ const open = state.interrupts.find((open) => open.interrupt.toolCallId === toolCallId);
2594
+ return open?.kind === "approval" || open?.kind === "form" || open?.kind === "input" ? open.kind : null;
2595
+ };
2596
+ const drop = upload ? {
2597
+ onDragOver: (event) => {
2598
+ if (!hasFiles(event)) return;
2599
+ event.preventDefault();
2600
+ setDragging(true);
2601
+ },
2602
+ onDragLeave: (event) => {
2603
+ if (!event.currentTarget.contains(event.relatedTarget)) setDragging(false);
2604
+ },
2605
+ onDrop: (event) => {
2606
+ if (!hasFiles(event)) return;
2607
+ event.preventDefault();
2608
+ setDragging(false);
2609
+ attachments.add([...event.dataTransfer.files]);
2610
+ }
2611
+ } : {};
2612
+ const empty = state.items.length === 0 && !running;
2613
+ return /* @__PURE__ */ jsxs("div", {
2614
+ ...root,
2615
+ ref: rootRef,
2616
+ "data-dragging": dragging || void 0,
2617
+ ...drop,
2618
+ children: [
2619
+ dragging ? /* @__PURE__ */ jsx("div", {
2620
+ className: "rungent-drop",
2621
+ "aria-hidden": "true",
2622
+ children: t("dropFiles")
2623
+ }) : null,
2624
+ /* @__PURE__ */ jsxs("div", {
2625
+ className: `rungent-messages ${SCROLL_CLASS}`,
2626
+ "data-empty": empty || void 0,
2627
+ ref: scroller,
2628
+ role: "log",
2629
+ "aria-live": "polite",
2630
+ children: [
2631
+ empty ? /* @__PURE__ */ jsx(Welcome, { ask: (question) => void thread.send(question) }) : null,
2632
+ blocks.map((block, index) => {
2633
+ if (block.kind === "user") return /* @__PURE__ */ jsx(UserMessage, { item: block.item }, block.key);
2634
+ if (block.kind === "trace") {
2635
+ const live = running && index === liveTrace;
2636
+ const next = blocks[index + 1];
2637
+ const answer = next?.kind === "answer" ? next.item : null;
2638
+ return /* @__PURE__ */ jsx(Trace, {
2639
+ traceKey: block.key,
2640
+ steps: block.steps,
2641
+ live,
2642
+ writing: live && answer?.streaming === true,
2643
+ endAt: answer?.endedAt ?? null,
2644
+ retry: state.retry,
2645
+ awaiting
2646
+ }, block.key);
2647
+ }
2648
+ const { item } = block;
2649
+ return /* @__PURE__ */ jsx(AssistantMessage, {
2650
+ item,
2651
+ citations: state.citations[item.id],
2652
+ children: thread.threadId && rated.has(item.id) ? /* @__PURE__ */ jsx(Rating, {
2653
+ threadId: thread.threadId,
2654
+ messageId: item.id
2655
+ }) : null
2656
+ }, item.id);
2657
+ }),
2658
+ state.interrupts.map((open) => /* @__PURE__ */ jsx(Interrupt, {
2659
+ open,
2660
+ thread,
2661
+ focusComposer
2662
+ }, open.id)),
2663
+ state.status === "cancelled" ? /* @__PURE__ */ jsx("p", {
2664
+ className: "rungent-note",
2665
+ children: t("cancelled")
2666
+ }) : null,
2667
+ state.status === "failed" && state.error ? /* @__PURE__ */ jsx("p", {
2668
+ className: "rungent-error",
2669
+ role: "alert",
2670
+ children: t(errorKey(state.error.code))
2671
+ }) : null,
2672
+ thread.error ? /* @__PURE__ */ jsx("p", {
2673
+ className: "rungent-error",
2674
+ role: "alert",
2675
+ children: t("error.request")
2676
+ }) : null
2677
+ ]
2678
+ }),
2679
+ /* @__PURE__ */ jsxs("div", {
2680
+ className: "rungent-composer-wrap",
2681
+ children: [atEnd ? null : /* @__PURE__ */ jsx("button", {
2682
+ type: "button",
2683
+ className: "rungent-jump",
2684
+ onClick: pin,
2685
+ children: t("jumpToLatest")
2686
+ }), /* @__PURE__ */ jsx(Composer, {
2687
+ thread,
2688
+ attachments
2689
+ })]
2690
+ })
2691
+ ]
2692
+ });
2693
+ }
2694
+ // src/dock.tsx
2695
+ function History({ current, onPick }) {
2696
+ const { t, locale } = useRungent();
2697
+ const { threads, loading, hasMore, loadMore, remove } = useThreads();
2698
+ const list = useRef(null);
2699
+ useScrollbar(list);
2700
+ return /* @__PURE__ */ jsxs("nav", {
2701
+ ref: list,
2702
+ className: `rungent-history ${SCROLL_CLASS}`,
2703
+ "aria-label": t("history"),
2704
+ children: [
2705
+ threads.length === 0 && !loading ? /* @__PURE__ */ jsx("p", {
2706
+ className: "rungent-muted",
2707
+ children: t("noThreads")
2708
+ }) : null,
2709
+ /* @__PURE__ */ jsx("ul", {
2710
+ className: "rungent-history-list",
2711
+ children: threads.map((thread) => /* @__PURE__ */ jsxs("li", {
2712
+ className: "rungent-history-row",
2713
+ children: [/* @__PURE__ */ jsxs("button", {
2714
+ type: "button",
2715
+ className: "rungent-history-item",
2716
+ "aria-current": thread.id === current || void 0,
2717
+ onClick: () => onPick(thread.id),
2718
+ children: [/* @__PURE__ */ jsx("span", {
2719
+ className: "rungent-history-title",
2720
+ children: thread.title ?? t("untitled")
2721
+ }), /* @__PURE__ */ jsx("time", {
2722
+ className: "rungent-muted rungent-small",
2723
+ dateTime: thread.createdAt,
2724
+ children: new Date(thread.createdAt).toLocaleDateString(locale, {
2725
+ month: "short",
2726
+ day: "numeric"
2727
+ })
2728
+ })]
2729
+ }), /* @__PURE__ */ jsx("button", {
2730
+ type: "button",
2731
+ className: "rungent-icon-button",
2732
+ "aria-label": `${t("deleteThread")}: ${thread.title ?? t("untitled")}`,
2733
+ onClick: () => void remove(thread.id),
2734
+ children: "×"
2735
+ })]
2736
+ }, thread.id))
2737
+ }),
2738
+ loading ? /* @__PURE__ */ jsx("p", {
2739
+ className: "rungent-muted",
2740
+ children: t("loading")
2741
+ }) : null,
2742
+ hasMore && !loading ? /* @__PURE__ */ jsx("button", {
2743
+ type: "button",
2744
+ className: "rungent-button",
2745
+ onClick: loadMore,
2746
+ children: t("loadMore")
2747
+ }) : null
2748
+ ]
2749
+ });
2750
+ }
2751
+ /** The page keeps at least this much room beside the panel. */
2752
+ const PAGE_MIN = 320;
2753
+ /** Arrow keys move the panel's edge by this much. */
2754
+ const KEY_STEP = 16;
2755
+ function clampWidth(width, room) {
2756
+ const max = Math.max(DOCK_WIDTH.min, Math.min(DOCK_WIDTH.max, room - PAGE_MIN));
2757
+ return Math.round(Math.min(Math.max(width, DOCK_WIDTH.min), max));
2758
+ }
2759
+ function Icon({ path }) {
2760
+ return /* @__PURE__ */ jsx("svg", {
2761
+ viewBox: "0 0 24 24",
2762
+ width: "16",
2763
+ height: "16",
2764
+ "aria-hidden": "true",
2765
+ className: "rungent-icon",
2766
+ children: /* @__PURE__ */ jsx("path", { d: path })
2767
+ });
2768
+ }
2769
+ const ICONS = {
2770
+ history: "M3 12a9 9 0 1 0 3-6.7L3 8M3 3v5h5M12 7v5l3 2",
2771
+ newChat: "M12 5v14M5 12h14",
2772
+ expand: "M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7",
2773
+ collapse: "M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7",
2774
+ close: "M18 6 6 18M6 6l12 12"
2775
+ };
2776
+ /** The panel's left edge: drag, arrow keys, Home/End, or double-click to reset. */
2777
+ function ResizeHandle({ width, room, onResize, onCommit }) {
2778
+ const { t } = useRungent();
2779
+ const drag = useRef(null);
2780
+ const onPointerDown = (event) => {
2781
+ if (event.button !== 0) return;
2782
+ event.preventDefault();
2783
+ event.currentTarget.setPointerCapture(event.pointerId);
2784
+ drag.current = {
2785
+ x: event.clientX,
2786
+ width
2787
+ };
2788
+ };
2789
+ const onPointerMove = (event) => {
2790
+ if (!drag.current) return;
2791
+ onResize(clampWidth(drag.current.width + drag.current.x - event.clientX, room()));
2792
+ };
2793
+ const onPointerUp = (event) => {
2794
+ if (!drag.current) return;
2795
+ drag.current = null;
2796
+ onCommit(clampWidth(width, room()));
2797
+ event.currentTarget.releasePointerCapture(event.pointerId);
2798
+ };
2799
+ const onKeyDown = (event) => {
2800
+ const next = event.key === "ArrowLeft" ? width + KEY_STEP : event.key === "ArrowRight" ? width - KEY_STEP : event.key === "Home" ? DOCK_WIDTH.max : event.key === "End" ? DOCK_WIDTH.min : null;
2801
+ if (next === null) return;
2802
+ event.preventDefault();
2803
+ onCommit(clampWidth(next, room()));
2804
+ };
2805
+ return /* @__PURE__ */ jsx("div", {
2806
+ className: "rungent-resize",
2807
+ role: "separator",
2808
+ "aria-orientation": "vertical",
2809
+ "aria-label": t("resize"),
2810
+ "aria-valuemin": DOCK_WIDTH.min,
2811
+ "aria-valuemax": DOCK_WIDTH.max,
2812
+ "aria-valuenow": width,
2813
+ tabIndex: 0,
2814
+ onPointerDown,
2815
+ onPointerMove,
2816
+ onPointerUp,
2817
+ onPointerCancel: onPointerUp,
2818
+ onKeyDown,
2819
+ onDoubleClick: () => onCommit(clampWidth(DOCK_WIDTH.initial, room()))
2820
+ });
2821
+ }
2822
+ /**
2823
+ * The assistant beside the product's page. Open, the panel takes its room from the page instead
2824
+ * of covering it, so what rungent opens or changes stays in view; its width can be dragged and is
2825
+ * remembered. Expanded, the conversation fills the area with the history beside it. On narrow
2826
+ * screens it fills the screen. ⌘J / Ctrl+J toggles it, Escape closes it (or leaves expanded).
2827
+ *
2828
+ * Mount it once, with `RungentProvider`, in the app's root layout: outside per-route layouts
2829
+ * (Next.js `app/layout.tsx`, a React Router root route), so that navigating never mounts it
2830
+ * again. Whether it is open, its width, thread and view live in a store that outlives the dock
2831
+ * (and `localStorage`), and the first paint shows them, so even a dock mounted again stays put:
2832
+ * it animates only when the user opens it.
2833
+ */
2834
+ function RungentDock({ children, open: openProp, onOpenChange, threadId: threadProp, onThreadChange, onLayoutChange, launcher = true }) {
2835
+ const { t, dock, dockKey, ask, askTaken } = useRungent();
2836
+ const root = useRoot("rungent-dock");
2837
+ const launcherRoot = useRoot("rungent-launcher-root");
2838
+ const [dockOpen, setDockOpen] = useControlledOpen(dock, openProp, onOpenChange);
2839
+ const [saved, write] = useDockState(dockKey);
2840
+ const threadId = threadProp === void 0 ? saved.threadId : threadProp;
2841
+ const onThread = useRef(onThreadChange);
2842
+ onThread.current = onThreadChange;
2843
+ const setThreadId = useCallback((id) => {
2844
+ if (threadProp === void 0) write({ threadId: id });
2845
+ onThread.current?.(id);
2846
+ }, [threadProp, write]);
2847
+ const { view, expanded } = saved;
2848
+ const setView = (next) => write({ view: next });
2849
+ const setExpanded = (next) => write({ expanded: next });
2850
+ const [session, setSession] = useState(0);
2851
+ const [pendingAsk, setPendingAsk] = useState(null);
2852
+ const shell = useRef(null);
2853
+ const panel = useRef(null);
2854
+ const returnFocus = useRef(null);
2855
+ const titleId = useId();
2856
+ const wraps = children !== void 0;
2857
+ const [shellWidth, setShellWidth] = useState(() => typeof window === "undefined" ? DOCK_WIDTH.initial + PAGE_MIN : window.innerWidth);
2858
+ const room = useCallback(() => (wraps ? shell.current?.clientWidth : 0) || window.innerWidth, [wraps]);
2859
+ useLayoutEffect(() => {
2860
+ setShellWidth(room());
2861
+ const element = shell.current;
2862
+ if (!element || typeof ResizeObserver === "undefined") return;
2863
+ const observer = new ResizeObserver(() => setShellWidth(room()));
2864
+ observer.observe(element);
2865
+ return () => observer.disconnect();
2866
+ }, [room]);
2867
+ const [dragWidth, setDragWidth] = useState(null);
2868
+ const width = clampWidth(dragWidth ?? saved.width, shellWidth);
2869
+ const commitWidth = (next) => {
2870
+ setDragWidth(null);
2871
+ write({ width: next });
2872
+ };
2873
+ const layout = !dockOpen ? "closed" : expanded ? "expanded" : "panel";
2874
+ useLayoutEffect(() => {
2875
+ if (wraps || layout !== "panel" || window.innerWidth <= 640) return;
2876
+ const root = document.documentElement;
2877
+ const previous = root.style.paddingRight;
2878
+ root.style.paddingRight = `${width}px`;
2879
+ return () => {
2880
+ root.style.paddingRight = previous;
2881
+ };
2882
+ }, [
2883
+ wraps,
2884
+ layout,
2885
+ width
2886
+ ]);
2887
+ const onLayout = useRef(onLayoutChange);
2888
+ onLayout.current = onLayoutChange;
2889
+ useEffect(() => onLayout.current?.(layout), [layout]);
2890
+ const openRef = useRef(dockOpen);
2891
+ openRef.current = dockOpen;
2892
+ useEffect(() => {
2893
+ const onKey = (event) => {
2894
+ if (event.key.toLowerCase() === "j" && (event.metaKey || event.ctrlKey) && !event.altKey) {
2895
+ event.preventDefault();
2896
+ setDockOpen(!openRef.current);
2897
+ }
2898
+ };
2899
+ window.addEventListener("keydown", onKey);
2900
+ return () => window.removeEventListener("keydown", onKey);
2901
+ }, [setDockOpen]);
2902
+ useEffect(() => {
2903
+ if (!ask || ask.id <= askTaken.current) return;
2904
+ askTaken.current = ask.id;
2905
+ setPendingAsk(ask.query);
2906
+ setThreadId(null);
2907
+ setView("thread");
2908
+ setSession((n) => n + 1);
2909
+ }, [ask]);
2910
+ const [entering, setEntering] = useState(false);
2911
+ const openings = useRef(saved.openings);
2912
+ const wasOpen = useRef(dockOpen);
2913
+ useLayoutEffect(() => {
2914
+ const explicit = saved.openings !== openings.current || openProp !== void 0;
2915
+ openings.current = saved.openings;
2916
+ if (dockOpen && !wasOpen.current && explicit) {
2917
+ setEntering(true);
2918
+ if (document.activeElement instanceof HTMLElement && !panel.current?.contains(document.activeElement)) returnFocus.current = document.activeElement;
2919
+ panel.current?.querySelector("[data-rungent-autofocus]")?.focus();
2920
+ } else if (!dockOpen && wasOpen.current) {
2921
+ setEntering(false);
2922
+ if (returnFocus.current) {
2923
+ returnFocus.current.focus();
2924
+ returnFocus.current = null;
2925
+ }
2926
+ }
2927
+ wasOpen.current = dockOpen;
2928
+ }, [
2929
+ dockOpen,
2930
+ saved.openings,
2931
+ openProp
2932
+ ]);
2933
+ const newChat = () => {
2934
+ setPendingAsk(null);
2935
+ setThreadId(null);
2936
+ setView("thread");
2937
+ setSession((n) => n + 1);
2938
+ };
2939
+ const pick = (id) => {
2940
+ setPendingAsk(null);
2941
+ setThreadId(id);
2942
+ setView("thread");
2943
+ };
2944
+ const conversation = /* @__PURE__ */ jsx(RungentThread, {
2945
+ threadId,
2946
+ onThreadCreated: (id) => {
2947
+ setPendingAsk(null);
2948
+ setThreadId(id);
2949
+ },
2950
+ ...pendingAsk ? { initialMessage: pendingAsk } : {}
2951
+ }, session);
2952
+ return /* @__PURE__ */ jsxs("div", {
2953
+ ref: shell,
2954
+ className: "rungent-shell",
2955
+ "data-layout": layout,
2956
+ "data-fixed": wraps ? void 0 : "",
2957
+ children: [wraps ? /* @__PURE__ */ jsx("div", {
2958
+ className: "rungent-shell-page",
2959
+ inert: layout === "expanded",
2960
+ children
2961
+ }) : null, dockOpen ? /* @__PURE__ */ jsxs("aside", {
2962
+ ...root,
2963
+ ref: panel,
2964
+ "aria-labelledby": titleId,
2965
+ "data-entering": entering || void 0,
2966
+ onAnimationEnd: (event) => {
2967
+ if (event.target === event.currentTarget) setEntering(false);
2968
+ },
2969
+ style: { "--rungent-dock-width": `${width}px` },
2970
+ onKeyDown: (event) => {
2971
+ if (event.key !== "Escape" || event.defaultPrevented) return;
2972
+ event.preventDefault();
2973
+ if (expanded) setExpanded(false);
2974
+ else setDockOpen(false);
2975
+ },
2976
+ children: [
2977
+ expanded ? null : /* @__PURE__ */ jsx(ResizeHandle, {
2978
+ width,
2979
+ room,
2980
+ onResize: setDragWidth,
2981
+ onCommit: commitWidth
2982
+ }),
2983
+ /* @__PURE__ */ jsxs("header", {
2984
+ className: "rungent-dock-header",
2985
+ children: [
2986
+ /* @__PURE__ */ jsx("h2", {
2987
+ id: titleId,
2988
+ className: "rungent-dock-title",
2989
+ children: t("assistant")
2990
+ }),
2991
+ expanded ? null : /* @__PURE__ */ jsx("button", {
2992
+ type: "button",
2993
+ className: "rungent-icon-button",
2994
+ "aria-label": t("history"),
2995
+ title: t("history"),
2996
+ "aria-pressed": view === "history",
2997
+ onClick: () => setView(view === "history" ? "thread" : "history"),
2998
+ children: /* @__PURE__ */ jsx(Icon, { path: ICONS.history })
2999
+ }),
3000
+ /* @__PURE__ */ jsx("button", {
3001
+ type: "button",
3002
+ className: "rungent-icon-button",
3003
+ "aria-label": t("newChat"),
3004
+ title: t("newChat"),
3005
+ onClick: newChat,
3006
+ children: /* @__PURE__ */ jsx(Icon, { path: ICONS.newChat })
3007
+ }),
3008
+ /* @__PURE__ */ jsx("button", {
3009
+ type: "button",
3010
+ className: "rungent-icon-button rungent-expand",
3011
+ "aria-label": expanded ? t("collapse") : t("expand"),
3012
+ title: expanded ? t("collapse") : t("expand"),
3013
+ "aria-pressed": expanded,
3014
+ onClick: () => setExpanded(!expanded),
3015
+ children: /* @__PURE__ */ jsx(Icon, { path: expanded ? ICONS.collapse : ICONS.expand })
3016
+ }),
3017
+ /* @__PURE__ */ jsx("button", {
3018
+ type: "button",
3019
+ className: "rungent-icon-button",
3020
+ "aria-label": t("close"),
3021
+ title: t("close"),
3022
+ onClick: () => setDockOpen(false),
3023
+ children: /* @__PURE__ */ jsx(Icon, { path: ICONS.close })
3024
+ })
3025
+ ]
3026
+ }),
3027
+ /* @__PURE__ */ jsxs("div", {
3028
+ className: "rungent-dock-body",
3029
+ "data-expanded": expanded || void 0,
3030
+ children: [expanded || view === "history" ? /* @__PURE__ */ jsx(History, {
3031
+ current: threadId,
3032
+ onPick: pick
3033
+ }) : null, expanded || view === "thread" ? /* @__PURE__ */ jsx("div", {
3034
+ className: "rungent-dock-main",
3035
+ children: conversation
3036
+ }) : null]
3037
+ })
3038
+ ]
3039
+ }) : launcher ? /* @__PURE__ */ jsx("div", {
3040
+ ...launcherRoot,
3041
+ children: /* @__PURE__ */ jsx("button", {
3042
+ type: "button",
3043
+ className: "rungent-launcher",
3044
+ "aria-label": t("openAssistant"),
3045
+ "aria-keyshortcuts": "Meta+J Control+J",
3046
+ onClick: () => setDockOpen(true),
3047
+ children: /* @__PURE__ */ jsx("span", {
3048
+ "aria-hidden": "true",
3049
+ children: "✦"
3050
+ })
3051
+ })
3052
+ }) : null]
3053
+ });
3054
+ }
3055
+ // src/help.tsx
3056
+ /** Fetches and renders one Markdown help page. */
3057
+ function HelpViewer({ url }) {
3058
+ const { t } = useRungent();
3059
+ const root = useRoot("rungent-help");
3060
+ const [page, setPage] = useState();
3061
+ useEffect(() => {
3062
+ const controller = new AbortController();
3063
+ fetch(url, {
3064
+ signal: controller.signal,
3065
+ headers: { Accept: "text/markdown, text/plain" }
3066
+ }).then(async (response) => {
3067
+ if (!response.ok) throw new Error(String(response.status));
3068
+ setPage({
3069
+ url,
3070
+ text: await response.text()
3071
+ });
3072
+ }).catch(() => {
3073
+ if (!controller.signal.aborted) setPage({
3074
+ url,
3075
+ failed: true
3076
+ });
3077
+ });
3078
+ return () => controller.abort();
3079
+ }, [url]);
3080
+ const absolute = new URL(url, window.location.href).href;
3081
+ return /* @__PURE__ */ jsx("article", {
3082
+ ...root,
3083
+ "aria-busy": page?.url !== url || void 0,
3084
+ children: page?.url !== url ? /* @__PURE__ */ jsx("p", {
3085
+ className: "rungent-muted",
3086
+ children: t("loading")
3087
+ }) : "failed" in page ? /* @__PURE__ */ jsx("p", {
3088
+ className: "rungent-error",
3089
+ role: "alert",
3090
+ children: t("loadFailed")
3091
+ }) : /* @__PURE__ */ jsx(Markdown, {
3092
+ text: page.text,
3093
+ baseUrl: absolute
3094
+ })
3095
+ });
3096
+ }
3097
+ // src/palette.tsx
3098
+ /** Renders an excerpt with its `«…»` matches highlighted. */
3099
+ function Excerpt({ text }) {
3100
+ const parts = text.split(/«([^»]*)»/).map((part, index) => index % 2 === 1 ? /* @__PURE__ */ jsx("mark", { children: part }, index) : part);
3101
+ return /* @__PURE__ */ jsx("span", {
3102
+ className: "rungent-hit-excerpt",
3103
+ children: parts
3104
+ });
3105
+ }
3106
+ /** `work_item`, `workItem` or `work-item` as `Work item`. */
3107
+ function humanize(type) {
3108
+ const words = type.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_\-\s]+/g, " ").trim().toLowerCase();
3109
+ return words.charAt(0).toUpperCase() + words.slice(1);
3110
+ }
3111
+ function group(hits) {
3112
+ const groups = /* @__PURE__ */ new Map();
3113
+ for (const hit of hits) groups.set(hit.type, [...groups.get(hit.type) ?? [], hit]);
3114
+ return [...groups];
3115
+ }
3116
+ /**
3117
+ * ⌘K / Ctrl+K search over every source, grouped by type. Arrow keys move, Enter opens, and the
3118
+ * last row hands the query to the assistant.
3119
+ */
3120
+ function SearchPalette({ open: openProp, onOpenChange, onAsk } = {}) {
3121
+ const { t, navigate, askAssistant, palette, paletteSeed } = useRungent();
3122
+ const root = useRoot("rungent-palette-root");
3123
+ const [open, setOpen] = useControlledOpen(palette, openProp, onOpenChange);
3124
+ const openRef = useRef(open);
3125
+ openRef.current = open;
3126
+ const [query, setQuery] = useState("");
3127
+ const [active, setActive] = useState(0);
3128
+ const { result, loading } = useSearch(open ? query : "");
3129
+ const input = useRef(null);
3130
+ const options = useRef(null);
3131
+ useScrollbar(options);
3132
+ const returnFocus = useRef(null);
3133
+ const listId = useId();
3134
+ useEffect(() => {
3135
+ const onKey = (event) => {
3136
+ if (event.key.toLowerCase() === "k" && (event.metaKey || event.ctrlKey) && !event.altKey) {
3137
+ event.preventDefault();
3138
+ setOpen(!openRef.current);
3139
+ }
3140
+ };
3141
+ window.addEventListener("keydown", onKey);
3142
+ return () => window.removeEventListener("keydown", onKey);
3143
+ }, [setOpen]);
3144
+ useEffect(() => {
3145
+ if (open) {
3146
+ returnFocus.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
3147
+ setQuery(paletteSeed.current);
3148
+ paletteSeed.current = "";
3149
+ input.current?.focus();
3150
+ } else {
3151
+ setQuery("");
3152
+ returnFocus.current?.focus();
3153
+ returnFocus.current = null;
3154
+ }
3155
+ }, [open]);
3156
+ useEffect(() => setActive(0), [result]);
3157
+ if (!open) return null;
3158
+ const groups = group(result?.hits ?? []);
3159
+ const rows = [...groups.flatMap(([, hits]) => hits.map((hit) => ({
3160
+ kind: "hit",
3161
+ hit
3162
+ }))), ...query.trim() ? [{ kind: "ask" }] : []];
3163
+ const typeLabel = (type) => t.find(`type.${type}`) ?? humanize(type);
3164
+ const optionId = (index) => `${listId}-${index}`;
3165
+ const choose = (row) => {
3166
+ if (!row) return;
3167
+ setOpen(false);
3168
+ if (row.kind === "ask") (onAsk ?? askAssistant)(query.trim());
3169
+ else navigate(row.hit.url);
3170
+ };
3171
+ const onKeyDown = (event) => {
3172
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
3173
+ event.preventDefault();
3174
+ if (rows.length === 0) return;
3175
+ const step = event.key === "ArrowDown" ? 1 : -1;
3176
+ setActive((current) => (current + step + rows.length) % rows.length);
3177
+ } else if (event.key === "Enter" && !event.nativeEvent.isComposing) {
3178
+ event.preventDefault();
3179
+ choose(rows[active]);
3180
+ } else if (event.key === "Escape") {
3181
+ event.preventDefault();
3182
+ setOpen(false);
3183
+ }
3184
+ };
3185
+ let index = -1;
3186
+ const option = (row, content) => {
3187
+ index += 1;
3188
+ const at = index;
3189
+ return /* @__PURE__ */ jsx("div", {
3190
+ id: optionId(at),
3191
+ role: "option",
3192
+ tabIndex: -1,
3193
+ "aria-selected": at === active,
3194
+ className: "rungent-option",
3195
+ onMouseMove: () => setActive(at),
3196
+ onMouseDown: (event) => event.preventDefault(),
3197
+ onClick: () => choose(row),
3198
+ children: content
3199
+ }, row.kind === "ask" ? "ask" : `${row.hit.type}:${row.hit.id}`);
3200
+ };
3201
+ return /* @__PURE__ */ jsxs("div", {
3202
+ ...root,
3203
+ children: [/* @__PURE__ */ jsx("div", {
3204
+ className: "rungent-overlay",
3205
+ onMouseDown: () => setOpen(false)
3206
+ }), /* @__PURE__ */ jsxs("div", {
3207
+ className: "rungent-palette",
3208
+ role: "dialog",
3209
+ "aria-modal": "true",
3210
+ "aria-label": t("searchLabel"),
3211
+ children: [
3212
+ /* @__PURE__ */ jsx("input", {
3213
+ ref: input,
3214
+ className: "rungent-palette-input",
3215
+ role: "combobox",
3216
+ "aria-expanded": rows.length > 0,
3217
+ "aria-controls": listId,
3218
+ "aria-activedescendant": rows.length > 0 ? optionId(active) : void 0,
3219
+ "aria-autocomplete": "list",
3220
+ "aria-label": t("searchLabel"),
3221
+ placeholder: t("searchPlaceholder"),
3222
+ value: query,
3223
+ onChange: (event) => setQuery(event.target.value),
3224
+ onKeyDown
3225
+ }),
3226
+ /* @__PURE__ */ jsxs("div", {
3227
+ ref: options,
3228
+ id: listId,
3229
+ role: "listbox",
3230
+ className: `rungent-options ${SCROLL_CLASS}`,
3231
+ "aria-label": t("searchLabel"),
3232
+ children: [groups.map(([type, hits]) => /* @__PURE__ */ jsxs("div", {
3233
+ role: "group",
3234
+ "aria-label": typeLabel(type),
3235
+ children: [/* @__PURE__ */ jsx("p", {
3236
+ className: "rungent-group",
3237
+ "aria-hidden": "true",
3238
+ children: typeLabel(type)
3239
+ }), hits.map((hit) => option({
3240
+ kind: "hit",
3241
+ hit
3242
+ }, /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
3243
+ className: "rungent-hit-title",
3244
+ children: hit.title
3245
+ }), hit.excerpt ? /* @__PURE__ */ jsx(Excerpt, { text: hit.excerpt }) : null] })))]
3246
+ }, type)), query.trim() ? option({ kind: "ask" }, /* @__PURE__ */ jsxs("span", {
3247
+ className: "rungent-ask",
3248
+ children: [
3249
+ /* @__PURE__ */ jsx("span", {
3250
+ "aria-hidden": "true",
3251
+ children: "✦ "
3252
+ }),
3253
+ t("askAssistant"),
3254
+ ": ",
3255
+ /* @__PURE__ */ jsx("q", { children: query.trim() })
3256
+ ]
3257
+ })) : null]
3258
+ }),
3259
+ /* @__PURE__ */ jsxs("div", {
3260
+ className: "rungent-palette-status",
3261
+ role: "status",
3262
+ children: [
3263
+ loading ? t("searching") : null,
3264
+ !loading && result && result.hits.length === 0 ? t("noResults") : null,
3265
+ result && result.failed.length > 0 ? /* @__PURE__ */ jsxs("span", {
3266
+ className: "rungent-muted",
3267
+ children: [" ", t("failedSources", { sources: result.failed.map((failure) => failure.source).join(", ") })]
3268
+ }) : null
3269
+ ]
3270
+ })
3271
+ ]
3272
+ })]
3273
+ });
3274
+ }
3275
+ // src/settings.tsx
3276
+ const PROVIDERS = [
3277
+ "openai-compatible",
3278
+ "openai",
3279
+ "anthropic"
3280
+ ];
3281
+ let nextKey = 0;
3282
+ const row = (endpoint) => ({
3283
+ key: nextKey++,
3284
+ endpoint,
3285
+ apiKey: ""
3286
+ });
3287
+ /** The endpoint as PUT takes it; models configured in code (provider `custom`) stay out. */
3288
+ function update({ endpoint, apiKey }) {
3289
+ const { hasApiKey: _, provider, ...fields } = endpoint;
3290
+ if (provider === "custom") return [];
3291
+ return [apiKey ? {
3292
+ ...fields,
3293
+ provider,
3294
+ apiKey
3295
+ } : {
3296
+ ...fields,
3297
+ provider
3298
+ }];
3299
+ }
3300
+ /** An id no other row has, `model-N`. */
3301
+ function freshId(rows) {
3302
+ const taken = new Set(rows.map((item) => item.endpoint.id));
3303
+ let n = rows.length + 1;
3304
+ while (taken.has(`model-${n}`)) n += 1;
3305
+ return `model-${n}`;
3306
+ }
3307
+ /** Sets or, when empty, removes an optional numeric field. */
3308
+ function numberField(endpoint, key, value) {
3309
+ const { [key]: _, ...rest } = endpoint;
3310
+ const number = Number(value);
3311
+ return value === "" || Number.isNaN(number) ? rest : {
3312
+ ...rest,
3313
+ [key]: number
3314
+ };
3315
+ }
3316
+ /** The admin form for the model chain. Keys are write-only: it shows whether one is stored. */
3317
+ function ModelSettings() {
3318
+ const { client, t } = useRungent();
3319
+ const root = useRoot("rungent-settings");
3320
+ const baseId = useId();
3321
+ const [rows, setRows] = useState(null);
3322
+ const [status, setStatus] = useState("idle");
3323
+ const [confirming, setConfirming] = useState(false);
3324
+ useEffect(() => {
3325
+ let live = true;
3326
+ client.getSettings().then((settings) => live && setRows(settings.models.chain.map(row)), (error) => live && setStatus({ failed: error instanceof RungentRequestError ? String(error.status) : "—" }));
3327
+ return () => {
3328
+ live = false;
3329
+ };
3330
+ }, [client]);
3331
+ const edit = (index, change) => {
3332
+ setStatus("idle");
3333
+ setRows((current) => (current ?? []).map((item, at) => at === index ? change(item) : item));
3334
+ };
3335
+ const field = (index, fields) => edit(index, (item) => ({
3336
+ ...item,
3337
+ endpoint: {
3338
+ ...item.endpoint,
3339
+ ...fields
3340
+ }
3341
+ }));
3342
+ const move = (index, by) => {
3343
+ setStatus("idle");
3344
+ setRows((current) => {
3345
+ const next = [...current ?? []];
3346
+ const [item] = next.splice(index, 1);
3347
+ if (item) next.splice(index + by, 0, item);
3348
+ return next;
3349
+ });
3350
+ };
3351
+ const save = async (event) => {
3352
+ event.preventDefault();
3353
+ if (!rows) return;
3354
+ setStatus("saving");
3355
+ try {
3356
+ const saved = await client.putSettings({ models: { chain: rows.flatMap(update) } });
3357
+ setRows(saved.models.chain.map(row));
3358
+ setStatus("saved");
3359
+ } catch (error) {
3360
+ setStatus({ failed: error instanceof RungentRequestError ? String(error.status) : "—" });
3361
+ }
3362
+ };
3363
+ const reset = async () => {
3364
+ setConfirming(false);
3365
+ setStatus("saving");
3366
+ try {
3367
+ const defaults = await client.resetSettings();
3368
+ setRows(defaults.models.chain.map(row));
3369
+ setStatus("reset");
3370
+ } catch (error) {
3371
+ setStatus({ failed: error instanceof RungentRequestError ? String(error.status) : "—" });
3372
+ }
3373
+ };
3374
+ const fromCode = (rows ?? []).some((item) => item.endpoint.provider === "custom");
3375
+ return /* @__PURE__ */ jsxs("form", {
3376
+ ...root,
3377
+ onSubmit: save,
3378
+ "aria-labelledby": `${baseId}-title`,
3379
+ children: [
3380
+ /* @__PURE__ */ jsx("h2", {
3381
+ id: `${baseId}-title`,
3382
+ className: "rungent-settings-title",
3383
+ children: t("models")
3384
+ }),
3385
+ /* @__PURE__ */ jsx("p", {
3386
+ className: "rungent-muted rungent-settings-hint",
3387
+ children: t("modelsHint")
3388
+ }),
3389
+ rows === null && status === "idle" ? /* @__PURE__ */ jsx("p", {
3390
+ className: "rungent-muted",
3391
+ children: t("loading")
3392
+ }) : null,
3393
+ /* @__PURE__ */ jsx("ol", {
3394
+ className: "rungent-chain",
3395
+ children: (rows ?? []).map((item, index) => {
3396
+ const id = `${baseId}-${item.key}`;
3397
+ const { endpoint } = item;
3398
+ if (endpoint.provider === "custom") return /* @__PURE__ */ jsxs("li", {
3399
+ className: "rungent-card rungent-endpoint",
3400
+ "data-provider": "custom",
3401
+ children: [/* @__PURE__ */ jsxs("div", {
3402
+ className: "rungent-endpoint-head",
3403
+ children: [/* @__PURE__ */ jsx("span", {
3404
+ className: "rungent-endpoint-index",
3405
+ children: index + 1
3406
+ }), /* @__PURE__ */ jsx("span", {
3407
+ className: "rungent-endpoint-name",
3408
+ children: endpoint.model || endpoint.id
3409
+ })]
3410
+ }), /* @__PURE__ */ jsx("p", {
3411
+ className: "rungent-muted rungent-small rungent-settings-hint",
3412
+ children: t("configuredInCode")
3413
+ })]
3414
+ }, item.key);
3415
+ return /* @__PURE__ */ jsxs("li", {
3416
+ className: "rungent-card rungent-endpoint",
3417
+ children: [/* @__PURE__ */ jsxs("div", {
3418
+ className: "rungent-endpoint-head",
3419
+ children: [
3420
+ /* @__PURE__ */ jsx("span", {
3421
+ className: "rungent-endpoint-index",
3422
+ children: index + 1
3423
+ }),
3424
+ /* @__PURE__ */ jsx("span", {
3425
+ className: "rungent-endpoint-name",
3426
+ children: endpoint.model || "—"
3427
+ }),
3428
+ /* @__PURE__ */ jsx("button", {
3429
+ type: "button",
3430
+ className: "rungent-icon-button",
3431
+ "aria-label": `${t("moveUp")}: ${endpoint.model}`,
3432
+ disabled: index === 0,
3433
+ onClick: () => move(index, -1),
3434
+ children: "↑"
3435
+ }),
3436
+ /* @__PURE__ */ jsx("button", {
3437
+ type: "button",
3438
+ className: "rungent-icon-button",
3439
+ "aria-label": `${t("moveDown")}: ${endpoint.model}`,
3440
+ disabled: index === (rows?.length ?? 0) - 1,
3441
+ onClick: () => move(index, 1),
3442
+ children: "↓"
3443
+ }),
3444
+ /* @__PURE__ */ jsx("button", {
3445
+ type: "button",
3446
+ className: "rungent-icon-button",
3447
+ "aria-label": `${t("remove")}: ${endpoint.model}`,
3448
+ onClick: () => {
3449
+ setStatus("idle");
3450
+ setRows((current) => (current ?? []).filter((_, at) => at !== index));
3451
+ },
3452
+ children: "×"
3453
+ })
3454
+ ]
3455
+ }), /* @__PURE__ */ jsxs("div", {
3456
+ className: "rungent-fields",
3457
+ children: [
3458
+ /* @__PURE__ */ jsx("label", {
3459
+ htmlFor: `${id}-provider`,
3460
+ className: "rungent-label",
3461
+ children: t("provider")
3462
+ }),
3463
+ /* @__PURE__ */ jsx("select", {
3464
+ id: `${id}-provider`,
3465
+ className: "rungent-input",
3466
+ value: endpoint.provider,
3467
+ onChange: (event) => field(index, { provider: event.target.value }),
3468
+ children: PROVIDERS.map((provider) => /* @__PURE__ */ jsx("option", {
3469
+ value: provider,
3470
+ children: provider
3471
+ }, provider))
3472
+ }),
3473
+ /* @__PURE__ */ jsx("label", {
3474
+ htmlFor: `${id}-model`,
3475
+ className: "rungent-label",
3476
+ children: t("model")
3477
+ }),
3478
+ /* @__PURE__ */ jsx("input", {
3479
+ id: `${id}-model`,
3480
+ className: "rungent-input",
3481
+ required: true,
3482
+ value: endpoint.model,
3483
+ onChange: (event) => field(index, { model: event.target.value })
3484
+ }),
3485
+ /* @__PURE__ */ jsx("label", {
3486
+ htmlFor: `${id}-base`,
3487
+ className: "rungent-label",
3488
+ children: t("baseURL")
3489
+ }),
3490
+ /* @__PURE__ */ jsx("input", {
3491
+ id: `${id}-base`,
3492
+ className: "rungent-input",
3493
+ type: "url",
3494
+ value: endpoint.baseURL ?? "",
3495
+ onChange: (event) => {
3496
+ const value = event.target.value;
3497
+ edit(index, (other) => {
3498
+ const { baseURL: _, ...rest } = other.endpoint;
3499
+ return {
3500
+ ...other,
3501
+ endpoint: value ? {
3502
+ ...rest,
3503
+ baseURL: value
3504
+ } : rest
3505
+ };
3506
+ });
3507
+ }
3508
+ }),
3509
+ /* @__PURE__ */ jsx("label", {
3510
+ htmlFor: `${id}-key`,
3511
+ className: "rungent-label",
3512
+ children: t("apiKey")
3513
+ }),
3514
+ /* @__PURE__ */ jsx("input", {
3515
+ id: `${id}-key`,
3516
+ className: "rungent-input",
3517
+ type: "password",
3518
+ autoComplete: "off",
3519
+ placeholder: endpoint.hasApiKey ? t("apiKeySaved") : "",
3520
+ value: item.apiKey,
3521
+ onChange: (event) => edit(index, (other) => ({
3522
+ ...other,
3523
+ apiKey: event.target.value
3524
+ }))
3525
+ }),
3526
+ /* @__PURE__ */ jsx("label", {
3527
+ htmlFor: `${id}-temperature`,
3528
+ className: "rungent-label",
3529
+ children: t("temperature")
3530
+ }),
3531
+ /* @__PURE__ */ jsx("input", {
3532
+ id: `${id}-temperature`,
3533
+ className: "rungent-input",
3534
+ type: "number",
3535
+ min: 0,
3536
+ max: 2,
3537
+ step: .1,
3538
+ value: endpoint.temperature ?? "",
3539
+ onChange: (event) => {
3540
+ const value = event.target.value;
3541
+ edit(index, (other) => ({
3542
+ ...other,
3543
+ endpoint: numberField(other.endpoint, "temperature", value)
3544
+ }));
3545
+ }
3546
+ }),
3547
+ /* @__PURE__ */ jsx("label", {
3548
+ htmlFor: `${id}-max-tokens`,
3549
+ className: "rungent-label",
3550
+ children: t("maxOutputTokens")
3551
+ }),
3552
+ /* @__PURE__ */ jsx("input", {
3553
+ id: `${id}-max-tokens`,
3554
+ className: "rungent-input",
3555
+ type: "number",
3556
+ min: 1,
3557
+ step: 1,
3558
+ value: endpoint.maxOutputTokens ?? "",
3559
+ onChange: (event) => {
3560
+ const value = event.target.value;
3561
+ edit(index, (other) => ({
3562
+ ...other,
3563
+ endpoint: numberField(other.endpoint, "maxOutputTokens", value)
3564
+ }));
3565
+ }
3566
+ }),
3567
+ /* @__PURE__ */ jsx("span", {}),
3568
+ /* @__PURE__ */ jsxs("label", {
3569
+ className: "rungent-choice",
3570
+ children: [/* @__PURE__ */ jsx("input", {
3571
+ type: "checkbox",
3572
+ checked: endpoint.vision ?? false,
3573
+ onChange: (event) => field(index, { vision: event.target.checked })
3574
+ }), /* @__PURE__ */ jsx("span", { children: t("vision") })]
3575
+ })
3576
+ ]
3577
+ })]
3578
+ }, item.key);
3579
+ })
3580
+ }),
3581
+ fromCode ? /* @__PURE__ */ jsx("p", {
3582
+ className: "rungent-muted rungent-small rungent-settings-note",
3583
+ children: t("saveReplacesCode")
3584
+ }) : null,
3585
+ confirming ? /* @__PURE__ */ jsxs("div", {
3586
+ className: "rungent-card rungent-confirm",
3587
+ role: "alertdialog",
3588
+ "aria-label": t("resetDefaults"),
3589
+ children: [/* @__PURE__ */ jsx("p", { children: t("resetConfirm") }), /* @__PURE__ */ jsxs("div", {
3590
+ className: "rungent-actions",
3591
+ children: [/* @__PURE__ */ jsx("button", {
3592
+ type: "button",
3593
+ className: "rungent-button",
3594
+ onClick: () => setConfirming(false),
3595
+ children: t("cancel")
3596
+ }), /* @__PURE__ */ jsx("button", {
3597
+ type: "button",
3598
+ className: "rungent-button rungent-primary",
3599
+ "data-danger": "",
3600
+ onClick: () => void reset(),
3601
+ children: t("resetDefaults")
3602
+ })]
3603
+ })]
3604
+ }) : null,
3605
+ /* @__PURE__ */ jsxs("div", {
3606
+ className: "rungent-actions",
3607
+ children: [
3608
+ /* @__PURE__ */ jsx("span", {
3609
+ className: "rungent-small",
3610
+ role: "status",
3611
+ children: status === "saved" ? t("saved") : status === "reset" ? t("resetDone") : typeof status === "object" ? t("saveFailed", { status: status.failed }) : null
3612
+ }),
3613
+ /* @__PURE__ */ jsx("button", {
3614
+ type: "button",
3615
+ className: "rungent-button rungent-ghost",
3616
+ disabled: rows === null || status === "saving" || confirming,
3617
+ onClick: () => setConfirming(true),
3618
+ children: t("resetDefaults")
3619
+ }),
3620
+ /* @__PURE__ */ jsx("button", {
3621
+ type: "button",
3622
+ className: "rungent-button",
3623
+ disabled: rows === null,
3624
+ onClick: () => setRows((current) => [...current ?? [], row({
3625
+ id: freshId(current ?? []),
3626
+ provider: "openai-compatible",
3627
+ model: "",
3628
+ hasApiKey: false
3629
+ })]),
3630
+ children: t("addModel")
3631
+ }),
3632
+ /* @__PURE__ */ jsx("button", {
3633
+ type: "submit",
3634
+ className: "rungent-button rungent-primary",
3635
+ disabled: rows === null || status === "saving",
3636
+ children: t("save")
3637
+ })
3638
+ ]
3639
+ })
3640
+ ]
3641
+ });
3642
+ }
3643
+ export { ApprovalCard, DOCK_WIDTH, HelpViewer, Markdown, ModelSettings, RungentDock, RungentForm, RungentProvider, RungentThread, SCROLLING_ATTRIBUTE, SCROLL_CLASS, SearchPalette, locales, useCatalog, useDock, useScrollbar, useSearch, useSearchPalette, useThread, useThreads, watchScrollbar };