@runappsai/agent 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +162 -2
- package/dist/agent-core.umd.js +266 -0
- package/dist/agent.d.ts +222 -0
- package/dist/agent.js +1331 -0
- package/dist/agent.umd.js +732 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +4 -0
- package/dist/chat-theme.d.ts +24 -0
- package/dist/chat-theme.js +101 -0
- package/dist/chat.d.ts +271 -0
- package/dist/chat.js +4097 -0
- package/dist/compaction.d.ts +48 -0
- package/dist/compaction.js +208 -0
- package/dist/completion.d.ts +29 -0
- package/dist/completion.js +88 -0
- package/dist/context.d.ts +44 -0
- package/dist/context.js +177 -0
- package/dist/debug-panel.d.ts +40 -0
- package/dist/debug-panel.js +262 -0
- package/dist/dialogs.d.ts +7 -0
- package/dist/dialogs.js +231 -0
- package/dist/directory-fs.d.ts +5 -0
- package/dist/directory-fs.js +118 -0
- package/dist/dom.d.ts +83 -0
- package/dist/dom.js +163 -0
- package/dist/edit.d.ts +22 -0
- package/dist/edit.js +133 -0
- package/dist/file-guard.d.ts +46 -0
- package/dist/file-guard.js +153 -0
- package/dist/file-tools.d.ts +16 -0
- package/dist/file-tools.js +339 -0
- package/dist/files-panel.d.ts +60 -0
- package/dist/files-panel.js +613 -0
- package/dist/index.cjs +4848 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +44 -0
- package/dist/json-schema.d.ts +3 -0
- package/dist/json-schema.js +141 -0
- package/dist/llm.d.ts +95 -0
- package/dist/llm.js +5 -0
- package/dist/markdown.d.ts +4 -0
- package/dist/markdown.js +265 -0
- package/dist/mcp.d.ts +82 -0
- package/dist/mcp.js +325 -0
- package/dist/node.cjs +402 -0
- package/dist/node.d.ts +78 -0
- package/dist/node.js +432 -0
- package/dist/pdf.d.ts +52 -0
- package/dist/pdf.js +77 -0
- package/dist/provider.d.ts +135 -0
- package/dist/provider.js +181 -0
- package/dist/sandbox.d.ts +33 -0
- package/dist/sandbox.js +219 -0
- package/dist/select.d.ts +30 -0
- package/dist/select.js +185 -0
- package/dist/skill-zips.d.ts +28 -0
- package/dist/skill-zips.js +123 -0
- package/dist/skills.d.ts +20 -0
- package/dist/skills.js +111 -0
- package/dist/templates.d.ts +24 -0
- package/dist/templates.js +136 -0
- package/dist/tool.d.ts +28 -0
- package/dist/tool.js +102 -0
- package/dist/types.d.ts +571 -0
- package/dist/types.js +7 -0
- package/dist/ui.cjs +6246 -0
- package/dist/ui.d.ts +6 -0
- package/dist/ui.js +11 -0
- package/dist/vlist.d.ts +80 -0
- package/dist/vlist.js +277 -0
- package/dist/workspace.d.ts +343 -0
- package/dist/workspace.js +1203 -0
- package/dist/zip.d.ts +26 -0
- package/dist/zip.js +204 -0
- package/docs/agent.md +228 -0
- package/docs/chat-ui.md +307 -0
- package/docs/node.md +135 -0
- package/docs/providers.md +176 -0
- package/docs/reference.md +143 -0
- package/docs/skills.md +131 -0
- package/docs/tools.md +254 -0
- package/docs/workspace.md +198 -0
- package/package.json +59 -4
package/dist/chat.js
ADDED
|
@@ -0,0 +1,4097 @@
|
|
|
1
|
+
// `renderChat(target, opts)`: the element becomes a chat with an agent —
|
|
2
|
+
// transcript (Markdown replies, thinking, tool cards, compaction notes),
|
|
3
|
+
// composer (Enter sends, steer / follow-up while running, slash
|
|
4
|
+
// commands for skills and templates), questions the agent asks rendered
|
|
5
|
+
// inline, a session menu when there is a workspace. Plain DOM, no
|
|
6
|
+
// framework, styles injected once; the host gives the element a height.
|
|
7
|
+
//
|
|
8
|
+
// Look and behaviour follow the harness app's chat (React/Chakra, purple
|
|
9
|
+
// palette): a right-aligned user bubble, replies full width with their work folded,
|
|
10
|
+
// collapsible tool cards with an icon, duration and status, a fixed-
|
|
11
|
+
// height composer that never resizes while typing, and a virtual
|
|
12
|
+
// transcript (`VirtualList`) that keeps only the rows near the viewport
|
|
13
|
+
// in the DOM, so a long history costs nothing to open.
|
|
14
|
+
import { escapeHTML } from "./markdown.js";
|
|
15
|
+
import { VirtualList } from "./vlist.js";
|
|
16
|
+
import { downloadBlob, h, I, modal, modalConfirm, renderMD } from "./dom.js";
|
|
17
|
+
import { selectBox, SELECT_CSS } from "./select.js";
|
|
18
|
+
import { filesPanel, freePath } from "./files-panel.js";
|
|
19
|
+
import { debugPanel } from "./debug-panel.js";
|
|
20
|
+
import { tokenCSS, tokenProp } from "./chat-theme.js";
|
|
21
|
+
// The core comes in through its entry, so a CommonJS build of the UI requires the core package instead of bundling a copy.
|
|
22
|
+
import { Agent, toProvider, titleOf, UNTITLED, summaryOf, listTemplates, extractPdfText, formatPdfText, isPdf, modelAccepts } from "./index.js";
|
|
23
|
+
/* ------------------------------------------------------------------ */
|
|
24
|
+
/* Text */
|
|
25
|
+
/* ------------------------------------------------------------------ */
|
|
26
|
+
const STRINGS = {
|
|
27
|
+
en: {
|
|
28
|
+
assistant: "Assistant", placeholder: "Ask the agent to do something… type / for commands", placeholderBusy: "↵ to steer the current task, {mod}↵ to queue for later",
|
|
29
|
+
send: "Send", stop: "Stop", steer: "Steer", followUp: "Follow-up", steerTip: "Insert into the current task", followUpTip: "Queue after the current task",
|
|
30
|
+
usageLine: "{cost} · {tokens} tokens · {calls} calls", uCost: "Cost", uIn: "Input", uOut: "Output", uCalls: "Calls", uOf: "{used} of {window} tokens", compactNow: "Compact now", emptyResult: "(empty)",
|
|
31
|
+
queued: "Queued messages", queuedN: "{n} message queued", queuedNs: "{n} messages queued", queueNext: "Next:", sendNow: "Send now (insert into the current task)", editQueued: "Edit", expand: "Show all", collapse: "Collapse", clear: "Clear queue", thinking: "Thinking…", thought: "Thought process",
|
|
32
|
+
enter: "to send", newline: "new line", hintIdle: "↵ {enter} · ⇧↵ {newline}", hintNext: "Tab to use the suggestion · ↵ {enter}", hintBusy: "↵ steer · {mod}↵ follow-up · ⇧↵ {newline}", empty: "Start a conversation", history: "Chats", newChat: "New chat", clearChat: "Clear", confirmClear: "Clear this conversation? Its messages are removed; the files stay.", noSessions: "No other conversations yet", notSaved: "not saved yet",
|
|
33
|
+
compacted: "Context compacted", trimmed: "Earlier conversation trimmed to fit the context", allow: "Allow", decline: "Decline", cancel: "Cancel", submit: "Submit", ok: "OK",
|
|
34
|
+
other: "Other…", typeAnswer: "Type your answer", args: "Arguments", result: "Result", error: "Error", declined: "declined", blocked: "blocked", skipped: "skipped",
|
|
35
|
+
open: "Open in editor", stopped: "Stopped.", maxTurns: "Paused at the turn limit ({n})", retry: "Retry", messages: "messages", skill: "Skill", template: "Template",
|
|
36
|
+
delete: "Delete", deleteAll: "Delete all", confirmDelete: "Delete this conversation and its files?", confirmDeleteAll: "Delete every conversation, this one included, and their files?", untitled: "New conversation",
|
|
37
|
+
attach: "Attach files", drop: "Drop files to attach", tooLarge: "is too large (max 20 MB)", remove: "Remove",
|
|
38
|
+
toolsRunning: "Running", toolsDone: "Ran {n} tool calls", toolsDone1: "Ran 1 tool call", toolsFailed: "{n} failed",
|
|
39
|
+
actRead: "read {n} file(s)", actList: "listed {n} folder(s)", actSearch: "searched {n} time(s)", actWrite: "wrote {n} file(s)", actEdit: "edited {n} file(s)", actDelete: "deleted {n} file(s)", actRun: "ran {n} snippet(s)", actAsk: "asked you {n} time(s)", actOther: "used {name}",
|
|
40
|
+
ingRead: "Reading", ingList: "Listing", ingSearch: "Searching", ingWrite: "Writing", ingEdit: "Editing", ingDelete: "Deleting", ingRun: "Running code", ingAsk: "Asking you", ingOther: "Running", current: "Current", jumpEnd: "Jump to the latest",
|
|
41
|
+
sTabModel: "Model", debug: "Debug", dCalls: "Calls", dRequests: "Requests", dEvents: "Events", dContext: "Context", dTools: "Tools", dClear: "Clear the record", dFilter: "Filter by type",
|
|
42
|
+
dNoCalls: "No tool calls yet.", dNoRequests: "No model requests yet. Each call to the model is listed here with what was sent and what came back.", dNoEvents: "No events yet.",
|
|
43
|
+
dSystem: "System prompt", dMessages: "Messages sent to the model", dPayload: "Request", dResponse: "Response", dRun: "Run", dTurn: "Turn {n}", sent: "sent", justNow: "Just now", minutesAgo: "{n} min ago", hoursAgo: "{n} h ago", context: "context", copy: "Copy", copied: "Copied", rewind: "Rewind to here", rewindTitle: "Rewind to this message", regen: "Answer again", regenTitle: "Answer this question again", regenMsg: "This answer and what follows are dropped and the question is sent again.", delTurn: "Delete", delTurnTitle: "Delete this question and its answer?", delTurnMsg: "They are removed from the conversation; files stay as they are.", replyCost: "Cost: {cost}", replyUsage: "{in} in · {out} out · {calls} calls",
|
|
44
|
+
rewindMsg: "The conversation after it is dropped and the message goes back into the composer.", rewindFiles: "Also restore the directory's files to that moment", rewindGone: "This message is no longer in the conversation.", rewindSnapshot: "{n} files ({size}) as they were at {time}", rewindPartial: "Files over 2 MB were not in the snapshot and stay as they are.", rewindGoneFile: "{path} is no longer in the directory.",
|
|
45
|
+
running: "running", waitingAnswer: "waiting for your answer", finished: "finished", bgLimit: "{n} conversations are already running in the background; stop one before switching away from this one.",
|
|
46
|
+
settings: "Settings", sVision: "sees pictures", sVisionYes: "sees pictures", sVisionNo: "text only", noVision: "{model} cannot see pictures: they are saved as files, but the model will not see what is in them.", sEffort: "Thinking", sEffortDefault: "Model default", sEffortNone: "this model does not expose a thinking level", sModel: "Model", sDefault: "Platform default", sMaxTurns: "Max turns per run", sMaxTokens: "Max output per reply", sPrice: "Price", sPriceLine: "input {in} · output {out} per M tokens", sPerCall: "{amount} per call", sAuto: "Model's maximum", sCustomN: "Set a number", filter: "Filter…", sPerms: "Tool permissions", sAsk: "Ask before destructive tools", sAutoPerm: "Allow everything", sCustom: "Decided by the app",
|
|
47
|
+
apply: "Apply", reset: "Reset to the app's defaults", applied: "Settings applied", continueRun: "Continue", maxTurnsHint: "Raise the limit in Settings, or continue from here.",
|
|
48
|
+
files: "Files", downloadZip: "Download as zip", zipping: "Zipping", wrap: "Word wrap", preview: "Preview Markdown", edit: "Edit", tooBig: "Too large to edit here; download it.", conflict: "The file changed since you opened it. Overwrite it?", readOnly: "Read-only", autoSaved: "Unsaved edits saved", upload: "Upload", newFile: "New file", refresh: "Refresh", close: "Close", save: "Save", download: "Download", confirmDeleteFile: "Delete {path}?", newFilePath: "Path of the new file",
|
|
49
|
+
noPreview: "No preview for this file; download it.", changedByAgent: "changed by the agent", noFiles: "The directory is empty.", discard: "Discard unsaved changes?", saved: "Saved",
|
|
50
|
+
skills: "Skills", uploadZip: "Upload zip", noSkills: "No skills yet. Upload a zip: SKILL.md at its root, or one folder per skill.", useSkill: "Use it: puts /skill:name in the composer", skillFolder: "folder", manualOnly: "manual only",
|
|
51
|
+
skillsInstalled: "Installed: {names}", skillRemoved: "Removed {name}", notZip: "not a zip file",
|
|
52
|
+
confirmDeleteZip: "Delete {zip}? All of its skills go: {names}. No conversation will have them any more.", confirmDeleteSkill: "Delete the skill {name} ({path})? No conversation will have it any more.",
|
|
53
|
+
skillsHint: "Built-in skills come with the app and cannot be removed. Your skills — zips you upload and skills the agent writes — are kept in {user} and shared by every conversation. {dir} is generated from both when the agent loads, read-only. Drop a zip here to install it.",
|
|
54
|
+
skillsHintNoUser: "These skills come with the app. {dir} is generated from them when the agent loads, read-only.",
|
|
55
|
+
waiting: "Thinking", compactingNow: "Compacting the context", builtinSkill: "built-in",
|
|
56
|
+
today: "Today", yesterday: "Yesterday",
|
|
57
|
+
worked: "Worked for {t}", workedNoTime: "Work", sec: "{s}s", minSec: "{m}m {s}s", hourMin: "{h}h {m}m",
|
|
58
|
+
command: "Command", user: "User", compacting: "Compacting the context…", nothingToCompact: "Nothing to compact yet", busyCmd: "Wait for the current task to finish, or stop it, first", nothingToExport: "Nothing to export yet", nothingToContinue: "Nothing to continue",
|
|
59
|
+
unknownModel: "No model named \"{name}\"", modelSet: "Model: {name}", effortSet: "Thinking: {name}", effortLevels: "Thinking levels of {model}: {levels}", unknownEffort: "\"{name}\" is not a thinking level of {model} ({levels})", debugOff: "Debug mode is off",
|
|
60
|
+
cmdsTitle: "Commands", cmdsMore: "Templates (/name) and skills (/skill:name) are listed as you type.", autoCompact: "Auto-compaction", autoCompactAt: "when less than {n} tokens are left", directory: "Directory", messagesLabel: "Messages",
|
|
61
|
+
cmdArgs: { compact: "[focus]", model: "[name]", effort: "[level]" },
|
|
62
|
+
cmd: { help: "Show these commands", new: "Start a new conversation", resume: "Open a saved conversation", compact: "Summarise older turns now; add what the summary must keep", continue: "Continue the last run", model: "Switch model; no name opens the settings", effort: "Set the thinking level", context: "Context use, model and spending", export: "Download the conversation as Markdown", files: "Open the file manager", settings: "Open the settings", debug: "Show or hide the debug panel" },
|
|
63
|
+
},
|
|
64
|
+
zh: {
|
|
65
|
+
assistant: "助手", placeholder: "让 agent 做点什么… 输入 / 查看命令", placeholderBusy: "↵ 插入当前任务,{mod}↵ 排队到之后",
|
|
66
|
+
send: "发送", stop: "停止", steer: "插入", followUp: "排队", steerTip: "插入到当前任务,下一步就会看到", followUpTip: "排到当前任务结束之后",
|
|
67
|
+
usageLine: "{cost} · {tokens} tokens · {calls} 次调用", uCost: "花费", uIn: "输入", uOut: "输出", uCalls: "调用", uOf: "{used} / {window} tokens", compactNow: "立即压缩", emptyResult: "(空)",
|
|
68
|
+
queued: "排队中的消息", queuedN: "{n} 条消息排队中", queuedNs: "{n} 条消息排队中", queueNext: "下一条:", sendNow: "立即发送(插入当前任务)", editQueued: "编辑", expand: "展开", collapse: "收起", clear: "清空队列", thinking: "思考中…", thought: "思考过程",
|
|
69
|
+
enter: "发送", newline: "换行", hintIdle: "↵ {enter} · ⇧↵ {newline}", hintNext: "Tab 使用建议 · ↵ {enter}", hintBusy: "↵ 插入 · {mod}↵ 排队 · ⇧↵ {newline}", empty: "开始对话", history: "会话", newChat: "新对话", clearChat: "清除", confirmClear: "清除这次对话?消息会被删除,文件保留。", noSessions: "还没有其它对话", notSaved: "尚未保存",
|
|
70
|
+
compacted: "上下文已压缩", trimmed: "较早的对话已裁剪以适应上下文", allow: "允许", decline: "拒绝", cancel: "取消", submit: "提交", ok: "确定",
|
|
71
|
+
other: "其他…", typeAnswer: "请输入", args: "参数", result: "结果", error: "错误", declined: "已拒绝", blocked: "已拦截", skipped: "已跳过",
|
|
72
|
+
open: "在编辑器中打开", stopped: "已停止。", maxTurns: "已达最大轮数 {n},暂停", retry: "重试", messages: "条消息", skill: "Skill", template: "模板",
|
|
73
|
+
delete: "删除", deleteAll: "全部删除", confirmDelete: "删除这个对话和它的文件?", confirmDeleteAll: "删除所有对话(包括当前这个)和它们的文件?", untitled: "新对话",
|
|
74
|
+
attach: "添加附件", drop: "松开即可添加附件", tooLarge: "太大了(最大 20 MB)", remove: "移除",
|
|
75
|
+
toolsRunning: "正在执行", toolsDone: "执行了 {n} 个工具调用", toolsDone1: "执行了 1 个工具调用", toolsFailed: "{n} 个失败",
|
|
76
|
+
actRead: "读取了 {n} 个文件", actList: "查看了 {n} 个目录", actSearch: "搜索了 {n} 次", actWrite: "写入了 {n} 个文件", actEdit: "修改了 {n} 个文件", actDelete: "删除了 {n} 个文件", actRun: "运行了 {n} 段代码", actAsk: "询问了你 {n} 次", actOther: "调用了 {name}",
|
|
77
|
+
ingRead: "正在读取", ingList: "正在查看", ingSearch: "正在搜索", ingWrite: "正在写入", ingEdit: "正在修改", ingDelete: "正在删除", ingRun: "正在运行代码", ingAsk: "正在询问你", ingOther: "正在执行", current: "当前", jumpEnd: "回到最新",
|
|
78
|
+
sTabModel: "模型", debug: "调试", dCalls: "调用", dRequests: "请求", dEvents: "事件", dContext: "上下文", dTools: "工具", dClear: "清空记录", dFilter: "按类型过滤",
|
|
79
|
+
dNoCalls: "还没有工具调用。", dNoRequests: "还没有模型请求。每次调用模型都会记在这里,包括发了什么、收到什么。", dNoEvents: "还没有事件。",
|
|
80
|
+
dSystem: "系统提示词", dMessages: "发给模型的消息", dPayload: "请求内容", dResponse: "响应", dRun: "运行", dTurn: "第 {n} 轮", sent: "已发送", justNow: "刚刚", minutesAgo: "{n} 分钟前", hoursAgo: "{n} 小时前", context: "上下文", copy: "复制", copied: "已复制", rewind: "回退到这里", rewindTitle: "回退到这条消息", regen: "重新回答", regenTitle: "重新回答这个问题", regenMsg: "这个回答及之后的对话会被删除,问题重新发送。", delTurn: "删除", delTurnTitle: "删除这一轮问答?", delTurnMsg: "这条提问和它的回答会从对话中删除,文件不受影响。", replyCost: "费用:{cost}", replyUsage: "输入 {in} · 输出 {out} · {calls} 次调用",
|
|
81
|
+
rewindMsg: "它之后的对话会被删除,消息内容放回输入框。", rewindFiles: "同时把目录里的文件恢复到那一刻", rewindGone: "这条消息已不在对话里(可能已被压缩)。", rewindSnapshot: "{time} 时的 {n} 个文件({size})", rewindPartial: "超过 2 MB 的文件没进快照,会保持原样。", rewindGoneFile: "{path} 已不在目录里。",
|
|
82
|
+
running: "运行中", waitingAnswer: "等待你回答", finished: "已完成", bgLimit: "后台已有 {n} 个会话在运行,先停掉一个再切换。",
|
|
83
|
+
settings: "设置", sVision: "可看图", sVisionYes: "可看图", sVisionNo: "仅文字", noVision: "{model} 不能看图:图片已保存为文件,但模型看不到图里的内容。", sEffort: "思考强度", sEffortDefault: "模型默认", sEffortNone: "这个模型没有思考强度可调", sModel: "模型", sDefault: "平台默认", sMaxTurns: "每次运行最大轮数", sMaxTokens: "单次回复最大输出", sPrice: "单价", sPriceLine: "每百万 tokens 输入 {in} · 输出 {out}", sPerCall: "每次调用 {amount}", sAuto: "模型上限", sCustomN: "自定义", filter: "搜索…", sPerms: "工具权限", sAsk: "破坏性操作先询问", sAutoPerm: "全部自动允许", sCustom: "由应用决定",
|
|
84
|
+
apply: "应用", reset: "恢复应用默认", applied: "设置已应用", continueRun: "继续", maxTurnsHint: "可在设置里调高上限,或点继续从这里接着跑",
|
|
85
|
+
files: "文件", downloadZip: "打包下载 (zip)", zipping: "正在打包", wrap: "自动换行", preview: "预览 Markdown", edit: "编辑", tooBig: "文件太大,无法在这里编辑,可以下载。", conflict: "文件在你打开后被改过,要覆盖吗?", readOnly: "只读", autoSaved: "未保存的修改已自动保存", upload: "上传", newFile: "新建文件", refresh: "刷新", close: "关闭", save: "保存", download: "下载", confirmDeleteFile: "删除 {path}?", newFilePath: "新文件的路径",
|
|
86
|
+
noPreview: "这个文件无法预览,可以下载。", changedByAgent: "agent 改过", noFiles: "目录是空的。", discard: "放弃未保存的修改?", saved: "已保存",
|
|
87
|
+
skills: "技能", uploadZip: "上传 zip", noSkills: "还没有技能。上传一个 zip:根目录有 SKILL.md,或每个技能一个文件夹。", useSkill: "使用:在输入框填入 /skill:名称", skillFolder: "文件夹", manualOnly: "仅手动",
|
|
88
|
+
skillsInstalled: "已安装:{names}", skillRemoved: "已删除 {name}", notZip: "不是 zip 文件",
|
|
89
|
+
confirmDeleteZip: "删除 {zip}?里面的技能会一起删除:{names}。所有对话都不能再用。", confirmDeleteSkill: "删除技能 {name}({path})?所有对话都不能再用。",
|
|
90
|
+
skillsHint: "应用自带的技能不能删除。你上传的 zip 和智能体写的技能保存在 {user},所有对话共用。{dir} 是加载时由这两部分生成的只读目录。把 zip 拖到这里也能安装。",
|
|
91
|
+
skillsHintNoUser: "这些技能是应用自带的。{dir} 是加载时由它们生成的只读目录。",
|
|
92
|
+
waiting: "思考中", compactingNow: "正在压缩上下文", builtinSkill: "应用自带",
|
|
93
|
+
today: "今天", yesterday: "昨天",
|
|
94
|
+
worked: "已工作 {t}", workedNoTime: "工作过程", sec: "{s}秒", minSec: "{m}分{s}秒", hourMin: "{h}小时{m}分",
|
|
95
|
+
command: "命令", user: "用户", compacting: "正在压缩上下文…", nothingToCompact: "暂时没有可压缩的内容", busyCmd: "请等当前任务结束(或先停止)", nothingToExport: "还没有可导出的内容", nothingToContinue: "没有可继续的内容",
|
|
96
|
+
unknownModel: "没有名为“{name}”的模型", modelSet: "模型:{name}", effortSet: "思考强度:{name}", effortLevels: "{model} 的思考强度:{levels}", unknownEffort: "“{name}”不是 {model} 的思考强度({levels})", debugOff: "调试模式未开启",
|
|
97
|
+
cmdsTitle: "命令", cmdsMore: "模板(/名称)和 Skill(/skill:名称)在输入时列出。", autoCompact: "自动压缩", autoCompactAt: "剩余不足 {n} tokens 时", directory: "目录", messagesLabel: "消息",
|
|
98
|
+
cmdArgs: { compact: "[重点]", model: "[名称]", effort: "[档位]" },
|
|
99
|
+
cmd: { help: "显示这些命令", new: "开始新对话", resume: "打开保存的对话", compact: "立即压缩较早的对话,可附上要保留的重点", continue: "继续上一次运行", model: "切换模型,不带名称则打开设置", effort: "设置思考强度", context: "上下文占用、模型和花费", export: "把对话下载为 Markdown", files: "打开文件管理", settings: "打开设置", debug: "显示或隐藏调试面板" },
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
function pickLocale(opt) {
|
|
103
|
+
if (opt)
|
|
104
|
+
return opt;
|
|
105
|
+
const lang = (typeof document !== "undefined" && document.documentElement.lang) || (typeof navigator !== "undefined" ? navigator.language : "") || "";
|
|
106
|
+
return /^zh/i.test(lang) ? "zh" : "en";
|
|
107
|
+
}
|
|
108
|
+
/* ------------------------------------------------------------------ */
|
|
109
|
+
/* Styles — every colour and font is a --ra-* variable (chat-theme.ts) */
|
|
110
|
+
/* ------------------------------------------------------------------ */
|
|
111
|
+
const STYLE_ID = "runapps-agent-chat-style";
|
|
112
|
+
const CSS = tokenCSS() + `
|
|
113
|
+
.ra-chat{display:flex;flex-direction:column;height:100%;min-height:0;box-sizing:border-box;background:var(--ra-bg);color:var(--ra-fg);font:14px/1.5 var(--ra-font);position:relative;overflow:hidden;-webkit-font-smoothing:antialiased}
|
|
114
|
+
.ra-chat *,.ra-chat *::before,.ra-chat *::after{box-sizing:border-box}
|
|
115
|
+
/* The chat's own controls start bare; what the host puts in (.ra-host: header actions, the empty state, composerTop, a tool's own content) keeps the host's styles. */
|
|
116
|
+
.ra-chat button:where(:not(.ra-host,.ra-host *)){font:inherit;color:inherit;background:none;border:0;cursor:pointer;padding:0;margin:0;line-height:inherit}
|
|
117
|
+
/* Debug mode: a dashed frame around the chat shows where on the page it is mounted. */
|
|
118
|
+
.ra-chat button:disabled{opacity:.5;cursor:default}
|
|
119
|
+
.ra-chat textarea:where(:not(.ra-host *)),.ra-chat input[type=text]:where(:not(.ra-host *)){font:inherit;color:inherit;background:transparent;border:0;outline:0;width:100%;margin:0}
|
|
120
|
+
.ra-chat svg{flex-shrink:0}
|
|
121
|
+
.ra-col{max-width:820px;margin:0 auto;padding:0 20px;width:100%}
|
|
122
|
+
.ra-chat .ra-btn{display:inline-flex;align-items:center;gap:5px;height:28px;padding:0 10px;border-radius:6px;font-size:12px;font-weight:500;border:1px solid var(--ra-border);background:var(--ra-bg);white-space:nowrap}
|
|
123
|
+
.ra-chat .ra-btn:hover{background:var(--ra-muted)}
|
|
124
|
+
.ra-chat .ra-btn.xs{height:24px;padding:0 8px;font-size:12px}
|
|
125
|
+
.ra-chat .ra-btn.ghost{border-color:transparent;background:transparent}
|
|
126
|
+
.ra-chat .ra-btn.ghost:hover{background:var(--ra-muted)}
|
|
127
|
+
.ra-chat .ra-btn.subtle{border-color:transparent;background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
|
|
128
|
+
.ra-chat .ra-btn.subtle:hover{background:var(--ra-accent-muted)}
|
|
129
|
+
.ra-chat .ra-btn.solid{border-color:var(--ra-accent);background:var(--ra-accent);color:#fff}
|
|
130
|
+
.ra-chat .ra-btn.solid:hover{filter:brightness(1.08)}
|
|
131
|
+
.ra-chat .ra-btn.red{border-color:#dc2626;background:#dc2626;color:#fff}
|
|
132
|
+
.ra-chat .ra-btn.red:hover{filter:brightness(1.08)}
|
|
133
|
+
.ra-chat .ra-btn.red-subtle{border-color:transparent;background:var(--ra-red-subtle);color:var(--ra-red)}
|
|
134
|
+
.ra-head{display:flex;align-items:center;gap:8px;padding:8px 16px;border-bottom:1px solid var(--ra-border);flex-shrink:0;min-height:44px}
|
|
135
|
+
.ra-head .ra-title{font-weight:600;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
136
|
+
.ra-badge{display:inline-flex;align-items:center;font-size:11px;font-weight:500;color:var(--ra-fg-muted);border:1px solid var(--ra-border);border-radius:4px;padding:0 6px;line-height:18px;white-space:nowrap}
|
|
137
|
+
.ra-badge.p{background:var(--ra-accent-subtle);color:var(--ra-accent-fg);border-color:transparent}
|
|
138
|
+
.ra-head .ra-sp{flex:1}
|
|
139
|
+
.ra-menu{position:absolute;right:12px;top:42px;z-index:6;width:min(360px,calc(100% - 24px));max-height:60%;overflow:auto;background:var(--ra-panel);border:1px solid var(--ra-border);border-radius:8px;box-shadow:var(--ra-shadow-md);padding:4px}
|
|
140
|
+
.ra-menu .ra-mi{display:flex;align-items:center;gap:6px;border-radius:6px}
|
|
141
|
+
.ra-menu .ra-mi:hover{background:var(--ra-muted)}
|
|
142
|
+
.ra-menu .ra-mi.ra-cur{background:var(--ra-muted);box-shadow:inset 3px 0 0 var(--ra-accent)}
|
|
143
|
+
.ra-menu .ra-mi .ra-now{flex:none;display:inline-block;font-size:10.5px;font-weight:600;line-height:16px;padding:0 6px;border-radius:999px;background:var(--ra-accent-subtle);color:var(--ra-accent-fg);vertical-align:1px}
|
|
144
|
+
.ra-menu .ra-sep{border-top:1px solid var(--ra-border);margin:4px 6px}
|
|
145
|
+
.ra-menu .ra-mi>button:first-child>span.ra-mt{display:flex;align-items:center;gap:6px;min-width:0;overflow:visible}
|
|
146
|
+
.ra-menu .ra-mi .ra-mtt{min-width:0;flex:0 1 auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
147
|
+
.ra-menu .ra-mi .ra-mt .ra-spin{flex:none}
|
|
148
|
+
.ra-menu .ra-mi>button:first-child{flex:1;min-width:0;text-align:left;padding:6px 8px;font-size:13px}
|
|
149
|
+
.ra-menu .ra-mi>button:first-child>span{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
150
|
+
.ra-menu .ra-mi small{display:block;color:var(--ra-fg-muted);font-size:11px}
|
|
151
|
+
.ra-menu .ra-mi .ra-x{width:24px;height:24px;margin-right:4px;border-radius:4px;display:inline-flex;align-items:center;justify-content:center;color:var(--ra-fg-muted);opacity:0}
|
|
152
|
+
.ra-menu .ra-mi:hover .ra-x{opacity:1}
|
|
153
|
+
.ra-menu .ra-x:hover{background:var(--ra-red-subtle);color:var(--ra-red)}
|
|
154
|
+
.ra-menu .ra-none{padding:8px 10px;color:var(--ra-fg-muted);font-size:13px}
|
|
155
|
+
.ra-head .ra-cnt{font-size:11px;font-weight:600;line-height:16px;min-width:16px;height:16px;padding:0 5px;border-radius:999px;background:var(--ra-muted);color:var(--ra-fg-muted);text-align:center;box-sizing:border-box;margin-left:-1px}
|
|
156
|
+
.ra-skm .ra-skh{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:6px 8px 8px;font-size:13px;font-weight:600}
|
|
157
|
+
.ra-skm .ra-skh .ra-btn{gap:4px}
|
|
158
|
+
.ra-skm .ra-skb{flex:none;font-size:10.5px;font-weight:500;line-height:16px;padding:0 6px;border-radius:999px;background:var(--ra-muted);color:var(--ra-fg-muted)}
|
|
159
|
+
.ra-skm .ra-mi:hover .ra-skb{background:var(--ra-panel)}
|
|
160
|
+
.ra-skm .ra-mi .ra-ia{margin-right:0}
|
|
161
|
+
.ra-skm .ra-mi .ra-ia:hover{background:var(--ra-panel);color:var(--ra-fg)}
|
|
162
|
+
.ra-skm .ra-mi small{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;white-space:normal;line-height:1.45;margin-top:1px}
|
|
163
|
+
.ra-skm .ra-skf{padding:8px 8px 4px;margin-top:4px;border-top:1px solid var(--ra-border);font-size:11.5px;color:var(--ra-fg-muted);line-height:1.5}
|
|
164
|
+
.ra-skm.drop{outline:2px dashed var(--ra-accent);outline-offset:-4px}
|
|
165
|
+
.ra-set{padding:10px 12px;display:flex;flex-direction:column;gap:10px;width:min(360px,calc(100% - 24px))}
|
|
166
|
+
/* The settings panel takes the chat's height under the header (a host may add fields of its own). */
|
|
167
|
+
.ra-chat .ra-set{max-height:calc(100% - 72px)}
|
|
168
|
+
.ra-set .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
|
|
169
|
+
.ra-set input[type=number]{font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;padding:6px 12px;min-height:34px;box-sizing:border-box;outline:0;width:100%;margin:0}
|
|
170
|
+
.ra-set input:focus{border-color:var(--ra-accent);box-shadow:0 0 0 3px var(--ra-accent-subtle)}
|
|
171
|
+
.ra-set .ra-row{display:flex;gap:8px;align-items:center}
|
|
172
|
+
.ra-set .ra-row>*{flex:1;min-width:0}
|
|
173
|
+
.ra-set .ra-lim{font-size:11px;color:var(--ra-fg-muted);margin-top:-4px}
|
|
174
|
+
.ra-set .ra-btns{justify-content:space-between}
|
|
175
|
+
.ra-set .ra-pane{display:flex;flex-direction:column;gap:10px}
|
|
176
|
+
.ra-set .ra-pane[hidden]{display:none}
|
|
177
|
+
.ra-set .ra-tabs{display:flex;gap:2px;border-bottom:1px solid var(--ra-border);margin:-2px -4px 0}
|
|
178
|
+
.ra-set .ra-tab{padding:4px 10px 7px;font-size:13px;color:var(--ra-fg-muted);border-bottom:2px solid transparent;margin-bottom:-1px}
|
|
179
|
+
.ra-set .ra-tab:hover{color:var(--ra-fg)}
|
|
180
|
+
.ra-set .ra-tab.on{color:var(--ra-fg);border-bottom-color:var(--ra-accent);font-weight:500}
|
|
181
|
+
.ra-set .ra-tgl{display:flex;gap:8px;align-items:flex-start;font-size:13px;color:var(--ra-fg);cursor:pointer}
|
|
182
|
+
.ra-set .ra-tgl input{margin:3px 0 0;accent-color:var(--ra-accent);flex:none}
|
|
183
|
+
.ra-set .ra-tgl small,.ra-set .ra-fld small{display:block;font-size:11.5px;color:var(--ra-fg-muted);margin-top:1px}
|
|
184
|
+
.ra-card .ra-btn{margin-top:8px}
|
|
185
|
+
.ra-menu .ra-mi .ra-spin{margin-right:6px}
|
|
186
|
+
.ra-chat .ra-btn.ra-bg{position:relative}
|
|
187
|
+
.ra-chat .ra-btn.ra-bg::after{content:"";position:absolute;top:4px;right:4px;width:7px;height:7px;border-radius:50%;background:var(--ra-accent)}
|
|
188
|
+
.ra-menu .ra-mf{border-top:1px solid var(--ra-border);margin-top:4px;padding-top:4px;display:flex;justify-content:flex-end}
|
|
189
|
+
.ra-main{flex:1;min-height:0;display:flex;position:relative;overflow:hidden}
|
|
190
|
+
.ra-chat{container-type:inline-size}
|
|
191
|
+
.ra-chatcol{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative}
|
|
192
|
+
/* An overlay: the tint is laid over the page colour, so a palette whose subtle is translucent (a host's fill colour) still hides the chat behind. */
|
|
193
|
+
.ra-fp{position:absolute;top:0;right:0;bottom:0;width:380px;max-width:100%;z-index:4;border-left:1px solid var(--ra-border);background:linear-gradient(var(--ra-subtle),var(--ra-subtle)) var(--ra-bg);display:flex;flex-direction:column;box-shadow:-8px 0 24px rgba(0,0,0,.08)}
|
|
194
|
+
.ra-chat.ra-files-open .ra-ed{right:380px}
|
|
195
|
+
@container (max-width:760px){.ra-fp{left:0;width:auto;border-left:0;box-shadow:none}.ra-chat.ra-files-open .ra-ed{right:0}.ra-chat.ra-editing .ra-fp{display:none}}
|
|
196
|
+
@container (max-width:560px){.ra-head .ra-btn span{display:none}.ra-head .ra-btn{padding:0 7px}.ra-head{padding:8px 10px}.ra-badge{display:none}.ra-col{padding:0 12px}}
|
|
197
|
+
@container (min-width:761px){.ra-dp{width:460px}}
|
|
198
|
+
/* Selected (its panel is open) reads differently from hover, so a button just clicked shut does not look still on. */
|
|
199
|
+
.ra-chat .ra-btn.on,.ra-chat .ra-btn.on:hover{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
|
|
200
|
+
.ra-chat button:focus{outline:none}
|
|
201
|
+
.ra-chat button:focus-visible{outline:2px solid var(--ra-accent-muted);outline-offset:1px}
|
|
202
|
+
.ra-dtabs{display:flex;gap:2px;min-width:0;overflow-x:auto}
|
|
203
|
+
.ra-chat .ra-dtab{display:inline-flex;align-items:center;gap:5px;height:28px;padding:0 9px;border-radius:6px;font-size:12.5px;color:var(--ra-fg-muted);white-space:nowrap}
|
|
204
|
+
.ra-chat .ra-dtab:hover{background:var(--ra-muted);color:var(--ra-fg)}
|
|
205
|
+
.ra-chat .ra-dtab.on{background:var(--ra-muted);color:var(--ra-fg);font-weight:600}
|
|
206
|
+
.ra-dcount{font-size:10.5px;font-weight:600;line-height:15px;padding:0 5px;border-radius:999px;background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
|
|
207
|
+
.ra-dbody{flex:1;min-height:0;overflow:auto;padding:8px 10px 14px;display:flex;flex-direction:column;gap:4px;font-size:13px}
|
|
208
|
+
.ra-dfold{border:1px solid var(--ra-border);border-radius:6px;background:var(--ra-bg)}
|
|
209
|
+
.ra-dfold>summary{display:flex;align-items:center;gap:6px;padding:5px 8px;cursor:pointer;list-style:none;min-width:0}
|
|
210
|
+
.ra-dfold>summary::-webkit-details-marker{display:none}
|
|
211
|
+
.ra-dfold>summary:hover{background:var(--ra-muted)}
|
|
212
|
+
.ra-dfold>summary .ra-chev{display:inline-flex;color:var(--ra-fg-muted);transition:transform .15s;flex:none}
|
|
213
|
+
.ra-dfold[open]>summary .ra-chev{transform:rotate(90deg)}
|
|
214
|
+
.ra-dfold>summary>.ra-dmuted:last-child{margin-left:auto;flex:none}
|
|
215
|
+
.ra-dfb{border-top:1px solid var(--ra-border);padding:6px 8px 8px;display:flex;flex-direction:column;gap:4px}
|
|
216
|
+
.ra-dpre{margin:0;max-height:220px;overflow:auto;background:var(--ra-muted);border-radius:4px;padding:6px 8px;font:11.5px/1.5 var(--ra-mono);white-space:pre-wrap;word-break:break-word}
|
|
217
|
+
.ra-dpre.tall{max-height:380px}
|
|
218
|
+
.ra-dlabel{font-size:11.5px;color:var(--ra-fg-muted);margin-top:4px}
|
|
219
|
+
.ra-dmuted{color:var(--ra-fg-muted);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
|
|
220
|
+
.ra-dmono{font:600 12.5px var(--ra-mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
|
|
221
|
+
.ra-dst{display:inline-flex;flex:none;font-size:12px}
|
|
222
|
+
.ra-dst.ok{color:var(--ra-ok)}.ra-dst.fail{color:var(--ra-red)}
|
|
223
|
+
.ra-drun{display:flex;flex-direction:column;gap:4px;padding:6px 0 10px;border-bottom:1px dashed var(--ra-border)}
|
|
224
|
+
.ra-drh{font-size:11.5px;font-weight:600;color:var(--ra-fg-muted);text-transform:uppercase;letter-spacing:.04em}
|
|
225
|
+
.ra-dturn{display:flex;align-items:center;gap:2px;min-width:0;padding:2px 0 0 2px}
|
|
226
|
+
.ra-dbadge{flex:none;font-size:10.5px;font-weight:600;line-height:16px;padding:0 6px;border-radius:4px;background:var(--ra-muted);color:var(--ra-fg-muted)}
|
|
227
|
+
.ra-dbadge.ok{background:color-mix(in srgb,var(--ra-ok) 15%,transparent);color:var(--ra-ok)}
|
|
228
|
+
.ra-dbadge.fail{background:var(--ra-red-subtle);color:var(--ra-red)}
|
|
229
|
+
.ra-dbar{display:flex;gap:6px;align-items:center;margin-bottom:4px}
|
|
230
|
+
.ra-dbar .ra-field{flex:1;border:1px solid var(--ra-border);border-radius:6px;padding:4px 8px;background:var(--ra-bg);font-size:12.5px}
|
|
231
|
+
.ra-dkv{display:grid;grid-template-columns:76px 1fr;gap:3px 8px;align-items:baseline}
|
|
232
|
+
.ra-dkv .ra-dmono{font-weight:500;white-space:normal;word-break:break-all}
|
|
233
|
+
.ra-ddesc{font-size:12.5px;color:var(--ra-fg);white-space:pre-wrap}
|
|
234
|
+
.ra-fph{display:flex;align-items:center;gap:2px;height:40px;padding:0 8px 0 12px;border-bottom:1px solid var(--ra-border);flex-shrink:0}
|
|
235
|
+
.ra-fph .ra-fpt{font-size:12px;font-weight:600;color:var(--ra-fg-muted);text-transform:uppercase;letter-spacing:.04em}
|
|
236
|
+
.ra-fph .ra-sp{flex:1}
|
|
237
|
+
.ra-chat .ra-ib{width:26px;height:26px;border-radius:4px;display:inline-flex;align-items:center;justify-content:center;color:var(--ra-fg-muted)}
|
|
238
|
+
.ra-chat .ra-ib:hover{background:var(--ra-muted);color:var(--ra-fg)}
|
|
239
|
+
.ra-tree{flex:1;min-height:0;overflow:auto;padding:4px}
|
|
240
|
+
.ra-fr{display:flex;align-items:center;gap:6px;padding:3px 6px;border-radius:4px;cursor:pointer;font-size:13px;min-height:26px}
|
|
241
|
+
.ra-fr:hover{background:var(--ra-panel)}
|
|
242
|
+
.ra-fr.ra-cur{background:var(--ra-accent-subtle)}
|
|
243
|
+
.ra-fr .ra-frc{width:12px;display:inline-flex;color:var(--ra-fg-muted);flex-shrink:0}
|
|
244
|
+
.ra-fr .ra-fri{display:inline-flex;color:var(--ra-fg-muted);flex-shrink:0}
|
|
245
|
+
.ra-fr .ra-frn{min-width:0;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
246
|
+
.ra-dot{width:6px;height:6px;border-radius:50%;background:#f97316;flex-shrink:0}
|
|
247
|
+
.ra-fr .ra-fra{display:none;gap:0;flex-shrink:0}
|
|
248
|
+
.ra-fr.ra-ro .ra-frn{color:var(--ra-fg-muted)}
|
|
249
|
+
.ra-fr .ra-frl{display:inline-flex;flex-shrink:0;color:var(--ra-fg-muted);opacity:.7;padding:0 4px}
|
|
250
|
+
.ra-edh .ra-edro{display:inline-flex;align-items:center;gap:4px;flex-shrink:0;font-size:11px;color:var(--ra-fg-muted);background:var(--ra-muted);border-radius:999px;padding:1px 8px;margin-right:4px}
|
|
251
|
+
.ra-fr:hover .ra-fra{display:inline-flex}
|
|
252
|
+
.ra-fr .ra-fra .ra-ib{width:22px;height:22px}
|
|
253
|
+
.ra-fpe{padding:8px 10px;font-size:12px;color:var(--ra-fg-muted)}
|
|
254
|
+
.ra-ed{position:absolute;inset:0;z-index:3;display:flex;flex-direction:column;background:var(--ra-bg)}
|
|
255
|
+
.ra-edh{display:flex;align-items:center;gap:6px;height:40px;padding:0 8px 0 16px;border-bottom:1px solid var(--ra-border);flex-shrink:0;background:var(--ra-subtle)}
|
|
256
|
+
.ra-edh .ra-edp{flex:1;min-width:0;font:12px var(--ra-mono);color:var(--ra-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
257
|
+
.ra-edh .ra-eda{display:inline-flex;align-items:center;gap:2px}
|
|
258
|
+
.ra-edb{flex:1;min-height:0;display:flex;flex-direction:column}
|
|
259
|
+
.ra-edta{flex:1;min-height:0;resize:none;padding:14px 20px;font:13.5px/1.6 var(--ra-mono);tab-size:2;white-space:pre;overflow:auto}
|
|
260
|
+
.ra-edta.ra-wrap{white-space:pre-wrap;word-break:break-word}
|
|
261
|
+
.ra-edmd{flex:1;min-height:0;overflow:auto;padding:16px 24px;max-width:860px}
|
|
262
|
+
.ra-chat .ra-ib.on{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
|
|
263
|
+
.ra-edpv{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:12px}
|
|
264
|
+
.ra-edpv img{max-width:100%;max-height:100%;border-radius:4px}
|
|
265
|
+
.ra-edpv:has(.ra-edpdf){padding:0}
|
|
266
|
+
.ra-edpdf{width:100%;height:100%;border:0;background:var(--ra-bg)}
|
|
267
|
+
.ra-fpdrop{position:absolute;inset:0;z-index:5;display:none;align-items:center;justify-content:center;background:color-mix(in srgb,var(--ra-accent) 8%,transparent);border:2px dashed var(--ra-accent);color:var(--ra-accent-fg);font-weight:600;pointer-events:none}
|
|
268
|
+
.ra-fp[data-drop="1"] .ra-fpdrop{display:flex}
|
|
269
|
+
.ra-md .ra-path{display:inline-flex;align-items:center;gap:3px;cursor:pointer;color:var(--ra-link);text-decoration:underline;text-decoration-color:color-mix(in srgb,var(--ra-link) 45%,transparent);text-underline-offset:3px}
|
|
270
|
+
.ra-md .ra-path:hover{text-decoration-color:var(--ra-link)}
|
|
271
|
+
.ra-md .ra-path:hover{background:var(--ra-accent-muted)}
|
|
272
|
+
.ra-tool .ra-tacts{display:flex;gap:10px}
|
|
273
|
+
.ra-log{flex:1;min-height:0;overflow-y:auto;overscroll-behavior:contain}
|
|
274
|
+
.ra-jumpwrap{position:relative;height:0;flex-shrink:0;z-index:2}
|
|
275
|
+
.ra-chat .ra-jump{position:absolute;left:50%;bottom:10px;width:30px;height:30px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;
|
|
276
|
+
background:color-mix(in srgb,var(--ra-panel) 82%,transparent);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);border:1px solid var(--ra-border);color:var(--ra-fg-muted);box-shadow:var(--ra-shadow);
|
|
277
|
+
opacity:0;transform:translate(-50%,6px);pointer-events:none;transition:opacity .18s,transform .18s,color .15s,border-color .15s}
|
|
278
|
+
.ra-chat .ra-jump.show{opacity:.7;transform:translate(-50%,0);pointer-events:auto}
|
|
279
|
+
.ra-chat .ra-jump:hover,.ra-chat .ra-jump:focus-visible{opacity:1;color:var(--ra-fg);border-color:var(--ra-accent-muted)}
|
|
280
|
+
.ra-log .ra-col{padding-top:6px;padding-bottom:6px}
|
|
281
|
+
.ra-row{padding:10px 0}
|
|
282
|
+
.ra-empty{padding:48px 0 24px;text-align:center;color:var(--ra-fg-muted)}
|
|
283
|
+
.ra-empty.start{text-align:left;padding:56px 8px 24px}
|
|
284
|
+
.ra-empty-icon{color:var(--ra-accent-fg);display:inline-flex;margin-bottom:14px}
|
|
285
|
+
.ra-empty-icon svg{width:44px;height:44px}
|
|
286
|
+
.ra-empty-title{margin:0 0 10px;font-size:20px;font-weight:600;color:var(--ra-fg);line-height:1.4}
|
|
287
|
+
.ra-empty-text{margin:0;font-size:14px;line-height:1.7}
|
|
288
|
+
.ra-empty.start .ra-sugs{justify-content:flex-start}
|
|
289
|
+
.ra-sugs{display:flex;flex-wrap:wrap;gap:8px;justify-content:center;margin-top:16px}
|
|
290
|
+
.ra-sugs button{border:1px solid var(--ra-border);border-radius:999px;padding:5px 12px;font-size:13px;color:var(--ra-fg)}
|
|
291
|
+
.ra-sugs button:hover{background:var(--ra-muted)}
|
|
292
|
+
.ra-user{display:flex;justify-content:flex-end}
|
|
293
|
+
.ra-user .ra-bubble{max-width:85%;background:var(--ra-user-bg);border-radius:16px;padding:8px 14px;white-space:pre-wrap;word-break:break-word;font-size:14px}
|
|
294
|
+
.ra-user img{display:block;max-width:240px;border-radius:4px;margin-top:6px}
|
|
295
|
+
.ra-user{flex-direction:column;align-items:flex-end}
|
|
296
|
+
.ra-uf{display:flex;align-items:center;gap:2px;font-size:12px;color:var(--ra-fg-muted);margin-top:4px;height:22px;padding-right:2px;opacity:0;transition:opacity .15s}
|
|
297
|
+
.ra-user:hover .ra-uf,.ra-uf:focus-within{opacity:1}
|
|
298
|
+
.ra-af{display:flex;align-items:center;gap:2px;font-size:12px;color:var(--ra-fg-muted);margin-top:2px;height:22px;opacity:0;transition:opacity .15s}
|
|
299
|
+
.ra-af .ra-ib{width:22px;height:22px}
|
|
300
|
+
.ra-af .ra-cost{margin-left:auto;font-variant-numeric:tabular-nums;cursor:default}
|
|
301
|
+
.ra-asst:hover .ra-af,.ra-af:focus-within{opacity:1}
|
|
302
|
+
.ra-uf .ra-ut{display:inline-flex;align-items:center;gap:5px;margin-right:4px}
|
|
303
|
+
.ra-uf .ra-ut::after{content:"·";margin-left:4px}
|
|
304
|
+
.ra-uf .ra-ib{width:22px;height:22px}
|
|
305
|
+
.ra-modal label.ra-ck{display:flex;align-items:center;gap:8px;font-size:14px;cursor:pointer}
|
|
306
|
+
.ra-modal label.ra-ck input{width:auto;accent-color:var(--ra-accent)}
|
|
307
|
+
.ra-modal .ra-dn{font-size:12px;color:var(--ra-fg-muted);margin:-4px 0 0 24px}
|
|
308
|
+
.ra-asst{min-width:0}
|
|
309
|
+
.ra-body{min-width:0;display:flex;flex-direction:column;gap:8px}
|
|
310
|
+
.ra-pending{font-size:13px;padding:2px 0;color:var(--ra-fg-muted)}
|
|
311
|
+
.ra-pending .ra-lpv{font-size:12px;line-height:1.55;color:var(--ra-fg-muted);max-height:4.65em;overflow:hidden;display:flex;flex-direction:column;justify-content:flex-end;margin-top:3px;padding-left:10px;border-left:2px solid var(--ra-border);-webkit-mask-image:linear-gradient(to bottom,transparent 0,#000 1.6em);mask-image:linear-gradient(to bottom,transparent 0,#000 1.6em)}
|
|
312
|
+
.ra-pending .ra-lpv.head{justify-content:flex-start;-webkit-mask-image:linear-gradient(to top,transparent 0,#000 1.6em);mask-image:linear-gradient(to top,transparent 0,#000 1.6em)}
|
|
313
|
+
.ra-pending .ra-lpv>div{white-space:pre-wrap;word-break:break-word;flex-shrink:0}
|
|
314
|
+
.ra-pending .ra-lpv.code>div{font:11.5px/1.55 var(--ra-mono)}
|
|
315
|
+
.ra-pending>span{background:linear-gradient(90deg,var(--ra-fg-muted) 0%,var(--ra-fg-muted) 35%,var(--ra-fg) 50%,var(--ra-fg-muted) 65%,var(--ra-fg-muted) 100%);background-size:250% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:ra-shimmer 1.8s linear infinite}
|
|
316
|
+
@keyframes ra-shimmer{from{background-position:100% 0}to{background-position:0 0}}
|
|
317
|
+
@media (prefers-reduced-motion:reduce){.ra-pending>span{animation:none;color:var(--ra-fg-muted);background:none}}
|
|
318
|
+
.ra-time{text-align:center;font-size:12px;color:var(--ra-fg-muted);padding:14px 0 2px}
|
|
319
|
+
.ra-work{border-bottom:1px solid var(--ra-border);padding-bottom:6px;margin-bottom:4px}
|
|
320
|
+
.ra-work>summary{display:inline-flex;align-items:center;gap:4px;font-size:13px;color:var(--ra-fg-muted);cursor:pointer;list-style:none;user-select:none;padding:2px 0}
|
|
321
|
+
.ra-work>summary::-webkit-details-marker{display:none}
|
|
322
|
+
.ra-work>summary:hover{color:var(--ra-fg)}
|
|
323
|
+
.ra-work>summary .ra-chev{display:inline-flex;transition:transform .15s}
|
|
324
|
+
.ra-work[open]>summary .ra-chev{transform:rotate(90deg)}
|
|
325
|
+
.ra-work .ra-wb{display:flex;flex-direction:column;gap:8px;margin:8px 0 4px}
|
|
326
|
+
.ra-md{font-size:14px;line-height:1.65;word-break:break-word;overflow-wrap:anywhere}
|
|
327
|
+
.ra-md>:first-child{margin-top:0}.ra-md>:last-child{margin-bottom:0}
|
|
328
|
+
.ra-md p{margin:.5em 0}.ra-md h1,.ra-md h2,.ra-md h3,.ra-md h4{margin:1em 0 .4em;line-height:1.3;font-weight:650}.ra-md h1{font-size:1.35em}.ra-md h2{font-size:1.2em}.ra-md h3{font-size:1.05em}
|
|
329
|
+
.ra-md strong{font-weight:650}
|
|
330
|
+
.ra-md ul,.ra-md ol{margin:.4em 0;padding-left:1.4em}.ra-md li{margin:.15em 0}
|
|
331
|
+
.ra-md code{font:.88em/1.5 var(--ra-mono);background:var(--ra-muted);padding:.1em .35em;border-radius:4px}
|
|
332
|
+
.ra-md .ra-cb{margin:.7em 0;border:1px solid var(--ra-border);border-radius:6px;overflow:hidden}
|
|
333
|
+
.ra-md .ra-cbh{display:flex;align-items:center;justify-content:space-between;padding:4px 10px;border-bottom:1px solid var(--ra-border);background:var(--ra-muted);color:var(--ra-fg-muted);font:12px var(--ra-mono)}
|
|
334
|
+
.ra-md .ra-cbh button{display:inline-flex;padding:3px;border-radius:4px;color:inherit}
|
|
335
|
+
.ra-md .ra-cbh button:hover{background:var(--ra-panel)}
|
|
336
|
+
.ra-md pre{margin:0;padding:10px 12px;overflow:auto;font:12.5px/1.55 var(--ra-mono)}
|
|
337
|
+
.ra-md pre code{background:none;padding:0;font:inherit}
|
|
338
|
+
.ra-md blockquote{margin:.6em 0;padding:.2em .9em;border-left:3px solid var(--ra-accent);color:var(--ra-fg-muted)}
|
|
339
|
+
.ra-md .ra-tw{margin:.7em 0;overflow:auto;border:1px solid var(--ra-border);border-radius:6px}
|
|
340
|
+
.ra-md table{border-collapse:collapse;width:100%;font-size:.95em}
|
|
341
|
+
.ra-md th,.ra-md td{padding:6px 10px;border-bottom:1px solid var(--ra-border);text-align:left}.ra-md thead{background:var(--ra-muted)}.ra-md th{font-weight:600}.ra-md tr:last-child td{border-bottom:0}
|
|
342
|
+
.ra-md hr{border:0;border-top:1px solid var(--ra-border);margin:1em 0}
|
|
343
|
+
.ra-md a{color:var(--ra-link);text-decoration:underline;text-decoration-color:color-mix(in srgb,var(--ra-link) 45%,transparent);text-underline-offset:3px}
|
|
344
|
+
.ra-md a:hover{text-decoration-color:var(--ra-link)}
|
|
345
|
+
.ra-md img{max-width:100%;border-radius:4px}
|
|
346
|
+
.ra-cursor>:last-child::after{content:"";display:inline-block;width:7px;height:14px;background:var(--ra-fg-muted);margin-left:2px;vertical-align:-2px;animation:ra-blink 1s steps(2) infinite;border-radius:1px}
|
|
347
|
+
@keyframes ra-blink{50%{opacity:0}}
|
|
348
|
+
.ra-think summary{cursor:pointer;color:var(--ra-fg-muted);font-size:12px;list-style:none;display:inline-flex;align-items:center;gap:6px;user-select:none;padding:2px 0}
|
|
349
|
+
.ra-think summary::-webkit-details-marker{display:none}
|
|
350
|
+
.ra-think summary .ra-chev{transition:transform .15s}
|
|
351
|
+
.ra-think[open] summary .ra-chev{transform:rotate(90deg)}
|
|
352
|
+
.ra-think .ra-think-body{font-size:12px;color:var(--ra-fg-muted);white-space:pre-wrap;border-left:2px solid var(--ra-border);padding-left:12px;margin:4px 0 0 4px;max-height:280px;overflow:auto}
|
|
353
|
+
.ra-tg>summary{display:inline-flex;align-items:center;gap:6px;max-width:100%;font-size:13px;color:var(--ra-fg-muted);cursor:pointer;list-style:none;user-select:none;padding:2px 0}
|
|
354
|
+
.ra-tg>summary::-webkit-details-marker{display:none}
|
|
355
|
+
.ra-tg>summary:hover{color:var(--ra-fg)}
|
|
356
|
+
.ra-tg>summary .ra-tgt{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
357
|
+
.ra-tg>summary .ra-tgt code{font:12px var(--ra-mono);background:none;padding:0;color:inherit}
|
|
358
|
+
.ra-tg>summary .ra-tgf{color:var(--ra-red);flex-shrink:0}
|
|
359
|
+
.ra-tg>summary .ra-chev{display:inline-flex;transition:transform .15s;flex-shrink:0}
|
|
360
|
+
.ra-tg[open]>summary .ra-chev{transform:rotate(90deg)}
|
|
361
|
+
.ra-tg .ra-tgb{display:flex;flex-direction:column;gap:8px;margin-top:6px}
|
|
362
|
+
.ra-tool{border:1px solid var(--ra-border);border-radius:6px;overflow:hidden;font-size:14px}
|
|
363
|
+
.ra-tool.fail{border-color:var(--ra-red)}
|
|
364
|
+
.ra-tool>summary{display:flex;align-items:center;gap:8px;padding:7px 10px;cursor:pointer;list-style:none;user-select:none}
|
|
365
|
+
.ra-tool>summary::-webkit-details-marker{display:none}
|
|
366
|
+
.ra-tool>summary:hover{background:var(--ra-muted)}
|
|
367
|
+
.ra-tool>summary .ra-chev{color:var(--ra-fg-muted);transition:transform .15s}
|
|
368
|
+
.ra-tool[open]>summary .ra-chev{transform:rotate(90deg)}
|
|
369
|
+
.ra-tool .ra-ticon{width:20px;height:20px;border-radius:4px;background:var(--ra-accent-subtle);color:var(--ra-accent-fg);display:inline-flex;align-items:center;justify-content:center}
|
|
370
|
+
.ra-tool.fail .ra-ticon{background:var(--ra-red-subtle);color:var(--ra-red)}
|
|
371
|
+
.ra-tool .ra-tname{font-weight:600;white-space:nowrap}
|
|
372
|
+
.ra-tool .ra-tname.own{font-weight:500;min-width:0;overflow:hidden;text-overflow:ellipsis}
|
|
373
|
+
.ra-tool>summary:has(.ra-tx){flex-wrap:wrap}
|
|
374
|
+
.ra-tool .ra-tx{flex-basis:100%;min-width:0;padding-left:26px;cursor:default}
|
|
375
|
+
.ra-tool .ra-tout{font-variant-numeric:tabular-nums}
|
|
376
|
+
.ra-tool .ra-tsum{flex:1;min-width:0;color:var(--ra-fg-muted);font:13px var(--ra-mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
377
|
+
.ra-tool .ra-tend{display:inline-flex;align-items:center;gap:6px;margin-left:auto;font-size:12px;color:var(--ra-fg-muted);white-space:nowrap}
|
|
378
|
+
.ra-tool .ra-tend .ok{color:var(--ra-ok);display:inline-flex}.ra-tool .ra-tend .fail{color:var(--ra-red);display:inline-flex}
|
|
379
|
+
.ra-spin{width:12px;height:12px;border:2px solid var(--ra-border);border-top-color:var(--ra-accent);border-radius:50%;animation:ra-spin .8s linear infinite;flex-shrink:0}
|
|
380
|
+
@keyframes ra-spin{to{transform:rotate(360deg)}}
|
|
381
|
+
.ra-tool .ra-tbody{border-top:1px solid var(--ra-border);padding:4px 10px 10px;display:flex;flex-direction:column;gap:8px}
|
|
382
|
+
.ra-tool .ra-tlabel{font-size:12px;color:var(--ra-fg-muted);margin:4px 0}
|
|
383
|
+
.ra-tool pre{margin:0;background:var(--ra-muted);border-radius:4px;padding:8px;max-height:280px;overflow:auto;font:12px/1.5 var(--ra-mono);white-space:pre-wrap;word-break:break-word}
|
|
384
|
+
.ra-tool .ra-tupd{font-size:12px;color:var(--ra-fg-muted);padding:0 10px 8px;white-space:pre-wrap}
|
|
385
|
+
.ra-tool .ra-open{font-size:12px;color:var(--ra-accent-fg);align-self:flex-start;text-decoration:underline;text-underline-offset:2px}
|
|
386
|
+
.ra-card{border:1px solid var(--ra-border);background:var(--ra-muted);border-radius:6px;padding:12px}
|
|
387
|
+
.ra-card .ra-ct{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;margin-bottom:6px}
|
|
388
|
+
.ra-card .ra-ct.only{margin-bottom:0;font-weight:500;color:var(--ra-fg-muted)}
|
|
389
|
+
.ra-card .ra-md{font-size:13px}
|
|
390
|
+
.ra-err{border:1px solid var(--ra-red);background:var(--ra-red-subtle);border-radius:6px;padding:8px;font-size:14px;color:var(--ra-red);white-space:pre-wrap;word-break:break-word}
|
|
391
|
+
.ra-err .ra-btn{margin-top:6px}
|
|
392
|
+
.ra-ask{flex-shrink:0;max-height:45%;overflow-y:auto}
|
|
393
|
+
.ra-ask .ra-col{display:flex;flex-direction:column;gap:8px;padding-top:8px;padding-bottom:8px}
|
|
394
|
+
.ra-q{border:1px solid var(--ra-accent-muted);border-radius:8px;padding:12px;background:var(--ra-subtle);display:flex;flex-direction:column;gap:10px}
|
|
395
|
+
.ra-q .ra-qt{font-weight:600;font-size:14px}
|
|
396
|
+
.ra-q .ra-qm{font-size:14px;white-space:pre-wrap}
|
|
397
|
+
.ra-q .ra-opts{display:flex;flex-direction:column;gap:4px}
|
|
398
|
+
.ra-q .ra-opt{display:flex;gap:8px;align-items:flex-start;border:1px solid var(--ra-border);border-radius:6px;padding:6px 12px;text-align:left;width:100%;background:var(--ra-bg);font-size:14px;min-height:32px}
|
|
399
|
+
.ra-q .ra-opt:hover{background:var(--ra-muted)}
|
|
400
|
+
.ra-q .ra-opt input[type=radio],.ra-q .ra-opt input[type=checkbox]{width:auto;flex:none;margin:4px 0 0;accent-color:var(--ra-accent)}
|
|
401
|
+
/* A host's form styles (antd's .ant-form input[type=radio]:focus) put a square focus shadow on our radios and checkboxes: none here (more specific than theirs on purpose). Keyboard focus shows on the option's row for a radio, as a ring for a checkbox. */
|
|
402
|
+
.ra-chat input:is([type=radio],[type=checkbox]):focus:not(.ra-x){box-shadow:none;outline:0}
|
|
403
|
+
.ra-chat input[type=checkbox]:focus-visible:not(.ra-x){outline:2px solid var(--ra-accent);outline-offset:1px}
|
|
404
|
+
.ra-opt:has(input:focus-visible){border-color:var(--ra-accent)}
|
|
405
|
+
.ra-q .ra-opt>div,.ra-q .ra-opt>span{flex:1;min-width:0}
|
|
406
|
+
.ra-q .ra-opt small{display:block;color:var(--ra-fg-muted);font-size:12px}
|
|
407
|
+
.ra-q .ra-field{border:1px solid var(--ra-border);border-radius:6px;padding:6px 10px;background:var(--ra-bg);width:100%;font-size:14px}
|
|
408
|
+
.ra-q .ra-field:focus{border-color:var(--ra-accent)}
|
|
409
|
+
.ra-q textarea.ra-field{min-height:96px;max-height:200px;resize:vertical}
|
|
410
|
+
.ra-btns{display:flex;justify-content:flex-end;gap:8px}
|
|
411
|
+
.ra-cbody{margin:2px 0 10px;max-height:min(60vh,560px);overflow:auto;min-width:0}
|
|
412
|
+
.ra-status{font-size:14px;color:var(--ra-fg-muted);padding:4px 0}
|
|
413
|
+
.ra-comp{flex-shrink:0;padding:8px 0 14px}
|
|
414
|
+
.ra-alert{font-size:14px;color:var(--ra-red);margin-bottom:8px;white-space:pre-wrap}
|
|
415
|
+
.ra-queue{background:var(--ra-muted);border-radius:12px;margin:0 6px 8px;font-size:13px;overflow:hidden}
|
|
416
|
+
.ra-queue .ra-qr{display:flex;align-items:center;gap:8px;padding:8px 8px 8px 14px;min-height:36px;box-sizing:border-box}
|
|
417
|
+
.ra-queue .ra-qr+.ra-qr{border-top:1px solid color-mix(in srgb,var(--ra-border) 70%,transparent)}
|
|
418
|
+
.ra-queue .ra-qn{flex:none;color:var(--ra-fg);font-weight:500}
|
|
419
|
+
.ra-queue .ra-qt{flex:1;min-width:0;color:var(--ra-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
420
|
+
.ra-queue .ra-qt b{font-weight:500;color:var(--ra-fg-muted);margin-right:4px}
|
|
421
|
+
.ra-queue .ra-qk{flex:none;font-size:10.5px;line-height:16px;padding:0 6px;border-radius:999px;background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
|
|
422
|
+
.ra-queue .ra-qa{flex:none;display:inline-flex;gap:2px}
|
|
423
|
+
.ra-queue .ra-qa button,.ra-queue .ra-qtog{width:28px;height:28px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;color:var(--ra-fg-muted)}
|
|
424
|
+
.ra-queue .ra-qa button:hover,.ra-queue .ra-qtog:hover{background:var(--ra-panel);color:var(--ra-fg)}
|
|
425
|
+
.ra-queue .ra-qhd{cursor:pointer}
|
|
426
|
+
.ra-queue .ra-qtog svg{transition:transform .15s}
|
|
427
|
+
.ra-queue.open .ra-qtog svg{transform:rotate(180deg)}
|
|
428
|
+
.ra-queue .ra-qlist .ra-qr{padding-left:14px}
|
|
429
|
+
.ra-box{position:relative;border:1px solid var(--ra-border);border-radius:12px;padding:8px 10px 6px;background:var(--ra-panel);box-shadow:var(--ra-shadow)}
|
|
430
|
+
.ra-box:focus-within{border-color:color-mix(in srgb,var(--ra-fg) 28%,transparent)}
|
|
431
|
+
.ra-box textarea{resize:none;height:64px;overflow-y:auto;padding:2px 4px;line-height:1.5;display:block}
|
|
432
|
+
/* A host's generic focus rule (textarea:focus-visible{outline…}) must not draw a square inside the rounded box: the box shows focus. */
|
|
433
|
+
.ra-chat .ra-box textarea:focus,.ra-chat .ra-box textarea:focus-visible{outline:none;box-shadow:none;background:transparent}
|
|
434
|
+
.ra-chat[data-asking="1"] .ra-box textarea,.ra-chat[data-short="1"] .ra-box textarea{height:1.6em}
|
|
435
|
+
.ra-chat[data-short="1"] .ra-bar .ra-hint{display:none}
|
|
436
|
+
.ra-chat[data-asking="1"] .ra-ask{max-height:70%}
|
|
437
|
+
.ra-timgs{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}
|
|
438
|
+
.ra-timgs img{max-width:100%;max-height:180px;border-radius:6px;border:1px solid var(--ra-border);display:block}
|
|
439
|
+
.ra-bar{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:4px;min-height:32px}
|
|
440
|
+
.ra-bar .ra-hint{font-size:12px;color:var(--ra-fg-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;letter-spacing:.01em}
|
|
441
|
+
.ra-kbd{display:inline-block;font:11px/1.4 var(--ra-mono);border:1px solid var(--ra-border);border-bottom-width:2px;border-radius:4px;padding:0 4px;background:var(--ra-muted);color:var(--ra-fg)}
|
|
442
|
+
/* The action area keeps the send/stop button's height while it is hidden, so the composer does not grow when one appears. */
|
|
443
|
+
.ra-bar .ra-acts{display:flex;gap:6px;align-items:center;min-height:30px}
|
|
444
|
+
/* Send: a quiet ↵ in the toolbar, there only while something can be sent. */
|
|
445
|
+
.ra-chat .ra-send{width:30px;height:30px;border-radius:8px;color:var(--ra-fg);display:inline-flex;align-items:center;justify-content:center}
|
|
446
|
+
.ra-chat .ra-send:hover{background:var(--ra-muted)}
|
|
447
|
+
.ra-chat .ra-stop{width:30px;height:30px;border-radius:8px;color:var(--ra-fg);display:inline-flex;align-items:center;justify-content:center}
|
|
448
|
+
.ra-chat .ra-stop:hover{background:var(--ra-muted)}
|
|
449
|
+
.ra-cmds{position:absolute;left:0;right:0;bottom:calc(100% + 6px);z-index:5;background:var(--ra-panel);border:1px solid var(--ra-border);border-radius:6px;box-shadow:var(--ra-shadow-md);padding:4px;max-height:260px;overflow:auto}
|
|
450
|
+
.ra-cmds button{display:flex;gap:8px;align-items:center;width:100%;text-align:left;padding:6px 8px;border-radius:4px;font-size:13px}
|
|
451
|
+
.ra-cmds button:hover,.ra-cmds button.ra-cur{background:var(--ra-muted)}
|
|
452
|
+
.ra-cmds .ra-cn{font:600 14px var(--ra-mono)}
|
|
453
|
+
.ra-cmds .ra-ca{font:12px var(--ra-mono);color:var(--ra-fg-muted);margin-left:-4px}
|
|
454
|
+
.ra-cmds .ra-cd{font-size:12px;color:var(--ra-fg-muted);flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
455
|
+
.ra-chat .ra-attach{width:28px;height:28px;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;color:var(--ra-fg-muted);margin-right:4px}
|
|
456
|
+
.ra-chat .ra-attach:hover{background:var(--ra-muted);color:var(--ra-fg)}
|
|
457
|
+
.ra-bar .ra-left{display:flex;align-items:center;min-width:0}
|
|
458
|
+
.ra-bar .ra-left>.ra-host{flex:none;margin-right:6px}
|
|
459
|
+
.ra-chat .ra-cbtn{flex:none;height:28px;border-radius:6px;display:inline-flex;align-items:center;gap:5px;padding:0 8px;margin-right:6px;font-size:12px;color:var(--ra-fg-muted);white-space:nowrap}
|
|
460
|
+
.ra-chat .ra-cbtn.icon{width:28px;padding:0;justify-content:center}
|
|
461
|
+
.ra-chat .ra-cbtn:hover:not(:disabled){background:var(--ra-muted);color:var(--ra-fg)}
|
|
462
|
+
.ra-chat .ra-cbtn svg{width:15px;height:15px}
|
|
463
|
+
.ra-files{display:flex;flex-wrap:wrap;gap:6px;padding:0 0 6px}
|
|
464
|
+
.ra-chip{display:inline-flex;align-items:center;gap:10px;max-width:min(100%,340px);height:44px;border:1px solid var(--ra-border);border-radius:12px;padding:0 12px 0 10px;font-size:14px;background:var(--ra-panel);white-space:nowrap}
|
|
465
|
+
.ra-chip img{width:30px;height:30px;object-fit:cover;border-radius:6px;flex:none}
|
|
466
|
+
.ra-chip .ra-ext{flex:none;font:600 11px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;letter-spacing:.02em;color:var(--ra-fg-muted);border:1px solid var(--ra-border);border-radius:7px;padding:5px 6px;text-transform:uppercase;min-width:34px;text-align:center}
|
|
467
|
+
.ra-chip .ra-cn{display:inline-flex;min-width:0;flex:0 1 auto;color:var(--ra-fg)}
|
|
468
|
+
.ra-chip .ra-cn .st{min-width:0;overflow:hidden;text-overflow:ellipsis}
|
|
469
|
+
.ra-chip .ra-cn .ex{flex:none}
|
|
470
|
+
.ra-chip small{flex:none;color:var(--ra-fg-muted);font-size:13px}
|
|
471
|
+
.ra-chip button{flex:none;width:20px;height:20px;border-radius:6px;color:var(--ra-fg-muted);display:inline-flex;align-items:center;justify-content:center}
|
|
472
|
+
.ra-chip button:hover{background:var(--ra-muted);color:var(--ra-fg)}
|
|
473
|
+
.ra-user .ra-files{justify-content:flex-end;padding:0;margin-top:8px}
|
|
474
|
+
.ra-chip-link{cursor:pointer}
|
|
475
|
+
.ra-ctx{height:36px;gap:8px;padding:0 8px 0 10px;font-size:13px}
|
|
476
|
+
.ra-ctxi{display:inline-flex;color:var(--ra-accent-fg);flex:none}
|
|
477
|
+
.ra-chip-link:hover{border-color:color-mix(in srgb,var(--ra-fg) 25%,transparent);background:var(--ra-subtle)}
|
|
478
|
+
.ra-drop{position:absolute;inset:0;z-index:8;display:none;align-items:center;justify-content:center;background:color-mix(in srgb,var(--ra-accent) 8%,transparent);border:2px dashed var(--ra-accent);border-radius:8px;color:var(--ra-accent-fg);font-weight:600;pointer-events:none}
|
|
479
|
+
.ra-chat[data-drop="1"] .ra-drop{display:flex}
|
|
480
|
+
/* How full the context is: a ring in the header; its panel has the numbers and the spending. */
|
|
481
|
+
.ra-head .ra-usebtn{padding:0 8px}
|
|
482
|
+
.ra-ring{width:18px;height:18px;display:block}
|
|
483
|
+
.ra-ring circle{fill:none;stroke-width:4}
|
|
484
|
+
.ra-use{padding:14px 16px 12px;width:min(320px,calc(100% - 24px))}
|
|
485
|
+
.ra-use .ra-uh{display:flex;align-items:baseline;justify-content:space-between;gap:8px}
|
|
486
|
+
.ra-use .ra-uh span{font-size:13px;font-weight:600}
|
|
487
|
+
.ra-use .ra-uh b{font-size:22px;font-weight:600;letter-spacing:-.02em;font-variant-numeric:tabular-nums}
|
|
488
|
+
.ra-use .ra-ubar{height:6px;border-radius:999px;background:var(--ra-muted);overflow:hidden;margin:8px 0 6px}
|
|
489
|
+
.ra-use .ra-ubar i{display:block;height:100%;border-radius:inherit;background:var(--ra-accent);transition:width .3s}
|
|
490
|
+
.ra-use.mid .ra-ubar i{background:var(--ra-warn-fg)}
|
|
491
|
+
.ra-use.hi .ra-ubar i{background:var(--ra-red)}
|
|
492
|
+
.ra-use .ra-usub{display:flex;justify-content:space-between;gap:8px;font-size:12px;color:var(--ra-fg-muted);font-variant-numeric:tabular-nums}
|
|
493
|
+
.ra-use .ra-usub span:last-child{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
494
|
+
.ra-use .ra-ugrid{display:grid;grid-template-columns:repeat(4,1fr);gap:4px;margin:14px 0 4px;padding-top:12px;border-top:1px solid var(--ra-border)}
|
|
495
|
+
.ra-use .ra-ugrid div{display:flex;flex-direction:column;gap:2px;min-width:0}
|
|
496
|
+
.ra-use .ra-ugrid small{font-size:11px;color:var(--ra-fg-muted)}
|
|
497
|
+
.ra-use .ra-ugrid b{font-size:14px;font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
498
|
+
.ra-use .ra-unote{font-size:11.5px;color:var(--ra-fg-muted);line-height:1.5;margin-top:10px}
|
|
499
|
+
.ra-use .ra-mf{margin-top:10px;padding-top:8px}
|
|
500
|
+
.ra-ring .tr{stroke:var(--ra-border)}
|
|
501
|
+
.ra-ring .pr{stroke:var(--ra-accent);stroke-linecap:round;transition:stroke-dashoffset .3s}
|
|
502
|
+
.ra-ring.mid .pr{stroke:var(--ra-warn-fg)}
|
|
503
|
+
.ra-ring.hi .pr{stroke:var(--ra-red)}
|
|
504
|
+
.ra-warn{display:inline-flex;align-items:center;gap:8px;max-width:100%;padding:5px 6px 5px 10px;border:1px solid var(--ra-warn-border);background:var(--ra-warn-bg);color:var(--ra-warn-fg);border-radius:8px;font-size:12.5px;font-weight:500;line-height:1.4}
|
|
505
|
+
.ra-warn>span{min-width:0}
|
|
506
|
+
.ra-chat .ra-warn .ra-btn{height:22px;padding:0 8px;font-size:12px;border-color:var(--ra-warn-border);background:transparent;color:inherit}
|
|
507
|
+
.ra-chat .ra-warn .ra-btn:hover{background:var(--ra-warn-border)}
|
|
508
|
+
.ra-modal{position:absolute;inset:0;z-index:9;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.4);padding:16px}
|
|
509
|
+
.ra-modal .ra-dlg{width:min(420px,100%);background:var(--ra-panel);border:1px solid var(--ra-border);border-radius:10px;box-shadow:var(--ra-shadow-md);padding:16px;display:flex;flex-direction:column;gap:10px}
|
|
510
|
+
.ra-modal .ra-dt{font-size:15px;font-weight:600}
|
|
511
|
+
.ra-modal .ra-dm{font-size:14px;color:var(--ra-fg-muted);white-space:pre-wrap}
|
|
512
|
+
.ra-modal .ra-btns{margin-top:4px}
|
|
513
|
+
.ra-toasts{position:absolute;top:10px;left:50%;transform:translateX(-50%);z-index:7;display:flex;flex-direction:column;gap:6px;pointer-events:none;max-width:calc(100% - 32px)}
|
|
514
|
+
.ra-toast{background:#18181b;color:#fff;font-size:13px;padding:8px 14px;border-radius:8px;box-shadow:var(--ra-shadow-md);white-space:pre-wrap;word-break:break-word}
|
|
515
|
+
.ra-toast.warning{background:#d97706}.ra-toast.error{background:#dc2626}
|
|
516
|
+
` + SELECT_CSS;
|
|
517
|
+
/**
|
|
518
|
+
* Gives a page's own `<select>` the chat's dropdown: the select stays (hidden) and in step — its
|
|
519
|
+
* `value` and `change` work as before — and a selectBox shows in its place. `host` positions the
|
|
520
|
+
* list (a positioned element with the class `ra-ui`, or the chat's root).
|
|
521
|
+
*/
|
|
522
|
+
export function enhanceSelect(select, host, opts = {}) {
|
|
523
|
+
injectStyles();
|
|
524
|
+
const read = () => Array.from(select.options).map((o) => ({ value: o.value, label: o.textContent ?? o.value }));
|
|
525
|
+
const box = selectBox(host, { options: read(), value: select.value, ...opts });
|
|
526
|
+
const display = select.style.display;
|
|
527
|
+
select.style.display = "none";
|
|
528
|
+
select.after(box.el);
|
|
529
|
+
box.el.addEventListener("change", () => {
|
|
530
|
+
if (select.value === box.value)
|
|
531
|
+
return;
|
|
532
|
+
select.value = box.value;
|
|
533
|
+
select.dispatchEvent(new Event("change", { bubbles: true }));
|
|
534
|
+
});
|
|
535
|
+
// Code that sets the select (or its options) is followed.
|
|
536
|
+
const watcher = new MutationObserver(() => { box.setOptions(read()); box.value = select.value; });
|
|
537
|
+
watcher.observe(select, { childList: true, subtree: true, characterData: true });
|
|
538
|
+
const desc = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value");
|
|
539
|
+
if (desc?.set && desc.get) {
|
|
540
|
+
Object.defineProperty(select, "value", { configurable: true, get() { return desc.get.call(this); }, set(v) { desc.set.call(this, v); box.value = desc.get.call(this); } });
|
|
541
|
+
}
|
|
542
|
+
return Object.assign(box, {
|
|
543
|
+
/** Puts the select back as it was: the dropdown goes, nothing watches the select any more. */
|
|
544
|
+
destroy() {
|
|
545
|
+
box.close();
|
|
546
|
+
watcher.disconnect();
|
|
547
|
+
delete select.value; // the prototype's accessor again
|
|
548
|
+
select.style.display = display;
|
|
549
|
+
box.el.remove();
|
|
550
|
+
},
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
function injectStyles() {
|
|
554
|
+
if (typeof document === "undefined" || document.getElementById(STYLE_ID))
|
|
555
|
+
return;
|
|
556
|
+
const s = document.createElement("style");
|
|
557
|
+
s.id = STYLE_ID;
|
|
558
|
+
s.textContent = CSS;
|
|
559
|
+
// First in <head>, so a host stylesheet's rules of equal weight come later and win.
|
|
560
|
+
document.head.prepend(s);
|
|
561
|
+
}
|
|
562
|
+
/* ------------------------------------------------------------------ */
|
|
563
|
+
/* DOM helpers and icons (lucide outlines, inline) */
|
|
564
|
+
/* ------------------------------------------------------------------ */
|
|
565
|
+
const TOOL_ICON = {
|
|
566
|
+
read_file: I.fileText, write_file: I.filePlus, edit_file: I.filePen, delete_file: I.fileX, list_files: I.folderOpen,
|
|
567
|
+
search_files: I.search, run_js: I.braces, ask_user: I.message,
|
|
568
|
+
};
|
|
569
|
+
/** Text of a message's content; images are listed as `<img>` elements by the caller. */
|
|
570
|
+
function textOfContent(content) {
|
|
571
|
+
if (typeof content === "string")
|
|
572
|
+
return content;
|
|
573
|
+
if (!Array.isArray(content))
|
|
574
|
+
return "";
|
|
575
|
+
return content.filter((p) => p.type === "text").map((p) => p.text).join("\n");
|
|
576
|
+
}
|
|
577
|
+
function imagesOf(content) {
|
|
578
|
+
if (!Array.isArray(content))
|
|
579
|
+
return [];
|
|
580
|
+
return content.flatMap((p) => (p.type === "image_url" ? [p.image_url.url] : []));
|
|
581
|
+
}
|
|
582
|
+
/** One-line summary of a call's arguments: the path, the pattern, the question, else the first value. */
|
|
583
|
+
function summarizeArgs(name, args) {
|
|
584
|
+
if (!args || typeof args !== "object")
|
|
585
|
+
return typeof args === "string" ? args.slice(0, 80) : "";
|
|
586
|
+
const a = args;
|
|
587
|
+
const path = typeof a.path === "string" ? a.path : undefined;
|
|
588
|
+
if (name === "search_files")
|
|
589
|
+
return `${String(a.pattern ?? "")}${path ? ` in ${path}` : ""}`;
|
|
590
|
+
if (name === "run_js")
|
|
591
|
+
return String(a.code ?? "").split("\n").find((l) => l.trim() && !l.trim().startsWith("//"))?.trim().slice(0, 80) ?? "";
|
|
592
|
+
if (name === "ask_user") {
|
|
593
|
+
const q = a.questions;
|
|
594
|
+
return Array.isArray(q) && q[0] && typeof q[0] === "object" ? String(q[0].question ?? "") : "";
|
|
595
|
+
}
|
|
596
|
+
if (path)
|
|
597
|
+
return path;
|
|
598
|
+
const first = Object.values(a)[0];
|
|
599
|
+
return first === undefined ? "" : (typeof first === "string" ? first : JSON.stringify(first)).slice(0, 80);
|
|
600
|
+
}
|
|
601
|
+
const TOOL_KIND = {
|
|
602
|
+
read_file: "Read", list_files: "List", search_files: "Search", write_file: "Write", edit_file: "Edit", delete_file: "Delete", run_js: "Run", ask_user: "Ask",
|
|
603
|
+
};
|
|
604
|
+
const pathArg = (args) => (args && typeof args === "object" && typeof args.path === "string" ? args.path : undefined);
|
|
605
|
+
/** The status a saved tool result stands for, as the live card showed it. */
|
|
606
|
+
function statusOfResult(text) {
|
|
607
|
+
if (text.startsWith("Skipped"))
|
|
608
|
+
return "skipped";
|
|
609
|
+
if (text.startsWith("The user declined"))
|
|
610
|
+
return "declined";
|
|
611
|
+
if (text.includes("Do not retry it another way"))
|
|
612
|
+
return "blocked";
|
|
613
|
+
if (/^Error|^Tool call "[^"]*" was not executed/.test(text))
|
|
614
|
+
return "error";
|
|
615
|
+
return "ok";
|
|
616
|
+
}
|
|
617
|
+
/** An amount of money in `currency` (the model's price currency; USD when unknown). */
|
|
618
|
+
function fmtCost(amount, currency) {
|
|
619
|
+
const sym = currencySymbol(currency);
|
|
620
|
+
if (amount === 0)
|
|
621
|
+
return `${sym}0`;
|
|
622
|
+
if (amount < 0.001)
|
|
623
|
+
return `${sym}${amount.toFixed(5)}`;
|
|
624
|
+
if (amount < 0.1)
|
|
625
|
+
return `${sym}${amount.toFixed(4)}`;
|
|
626
|
+
return `${sym}${amount.toFixed(3)}`;
|
|
627
|
+
}
|
|
628
|
+
function currencySymbol(currency) {
|
|
629
|
+
const c = (currency || "USD").toUpperCase();
|
|
630
|
+
return c === "USD" ? "$" : c === "CNY" || c === "JPY" ? "¥" : c === "EUR" ? "€" : c === "GBP" ? "£" : `${c} `;
|
|
631
|
+
}
|
|
632
|
+
/** A unit price: up to four significant digits, no trailing zeros. */
|
|
633
|
+
function fmtPrice(amount, currency) {
|
|
634
|
+
return `${currencySymbol(currency)}${Number(amount.toPrecision(4))}`;
|
|
635
|
+
}
|
|
636
|
+
function fmtTokens(n) {
|
|
637
|
+
if (n >= 1_000_000)
|
|
638
|
+
return `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 1 : 2)}M`;
|
|
639
|
+
return n >= 10_000 ? `${(n / 1000).toFixed(1)}k` : String(n);
|
|
640
|
+
}
|
|
641
|
+
function fmtSize(n) {
|
|
642
|
+
return n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 / 1024).toFixed(1)} MB`;
|
|
643
|
+
}
|
|
644
|
+
function relTime(ts, t) {
|
|
645
|
+
const s = Math.round((Date.now() - ts) / 1000);
|
|
646
|
+
if (s < 60)
|
|
647
|
+
return t.justNow;
|
|
648
|
+
if (s < 3600)
|
|
649
|
+
return t.minutesAgo.replace("{n}", String(Math.floor(s / 60)));
|
|
650
|
+
if (s < 86400)
|
|
651
|
+
return t.hoursAgo.replace("{n}", String(Math.floor(s / 3600)));
|
|
652
|
+
return clockTime(ts);
|
|
653
|
+
}
|
|
654
|
+
/** "18:00" today, "10/31 18:00" earlier this year, else with the year. */
|
|
655
|
+
function clockTime(ts) {
|
|
656
|
+
const d = new Date(ts), now = new Date();
|
|
657
|
+
const hm = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
|
658
|
+
if (d.toDateString() === now.toDateString())
|
|
659
|
+
return hm;
|
|
660
|
+
const md = `${d.getMonth() + 1}/${d.getDate()}`;
|
|
661
|
+
return d.getFullYear() === now.getFullYear() ? `${md} ${hm}` : `${d.getFullYear()}/${md} ${hm}`;
|
|
662
|
+
}
|
|
663
|
+
const tsOf = (m) => m?.ts;
|
|
664
|
+
const CKPT_FILE_MAX = 2 * 1024 * 1024;
|
|
665
|
+
const CKPT_TOTAL_MAX = 32 * 1024 * 1024;
|
|
666
|
+
/** Snapshots kept per directory (the newest user messages); older ones are deleted. */
|
|
667
|
+
const CKPT_KEEP = 30;
|
|
668
|
+
const ckptKey = (ts) => `ckpt:${ts}`;
|
|
669
|
+
const CKPT_INDEX = "ckpt:index";
|
|
670
|
+
async function takeCheckpoint(ws, ts) {
|
|
671
|
+
const files = [];
|
|
672
|
+
const skipped = [];
|
|
673
|
+
let total = 0;
|
|
674
|
+
for (const f of await ws.list("/")) {
|
|
675
|
+
if (ws.isSkillPath(f.path) || ws.mountOf(f.path))
|
|
676
|
+
continue;
|
|
677
|
+
if (f.size > CKPT_FILE_MAX || total + f.size > CKPT_TOTAL_MAX) {
|
|
678
|
+
skipped.push(f.path);
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
const r = await ws.read(f.path);
|
|
682
|
+
files.push({ path: f.path, contentType: r.contentType, data: r.data });
|
|
683
|
+
total += f.size;
|
|
684
|
+
}
|
|
685
|
+
await ws.putData(ckptKey(ts), { at: ts, files, partial: skipped.length > 0, skipped });
|
|
686
|
+
const index = [...((await ws.getData(CKPT_INDEX)) ?? []).filter((t) => t !== ts), ts].sort((a, b) => a - b);
|
|
687
|
+
for (const old of index.splice(0, Math.max(0, index.length - CKPT_KEEP)))
|
|
688
|
+
await ws.deleteData(ckptKey(old));
|
|
689
|
+
await ws.putData(CKPT_INDEX, index);
|
|
690
|
+
}
|
|
691
|
+
/** Drops the snapshots of messages sent after `ts` (they were rewound away). */
|
|
692
|
+
async function dropCheckpointsAfter(ws, ts) {
|
|
693
|
+
const index = (await ws.getData(CKPT_INDEX)) ?? [];
|
|
694
|
+
for (const t of index.filter((t) => t > ts))
|
|
695
|
+
await ws.deleteData(ckptKey(t));
|
|
696
|
+
await ws.putData(CKPT_INDEX, index.filter((t) => t <= ts));
|
|
697
|
+
}
|
|
698
|
+
const hostKey = (ts) => `hoststate:${ts}`;
|
|
699
|
+
const HOST_INDEX = "hoststate:index";
|
|
700
|
+
async function takeHostState(ws, ts, value) {
|
|
701
|
+
await ws.putData(hostKey(ts), { at: ts, value });
|
|
702
|
+
const index = [...((await ws.getData(HOST_INDEX)) ?? []).filter((t) => t !== ts), ts].sort((a, b) => a - b);
|
|
703
|
+
for (const old of index.splice(0, Math.max(0, index.length - CKPT_KEEP)))
|
|
704
|
+
await ws.deleteData(hostKey(old));
|
|
705
|
+
await ws.putData(HOST_INDEX, index);
|
|
706
|
+
}
|
|
707
|
+
async function dropHostStatesAfter(ws, ts) {
|
|
708
|
+
const index = (await ws.getData(HOST_INDEX)) ?? [];
|
|
709
|
+
for (const t of index.filter((t) => t > ts))
|
|
710
|
+
await ws.deleteData(hostKey(t));
|
|
711
|
+
await ws.putData(HOST_INDEX, index.filter((t) => t <= ts));
|
|
712
|
+
}
|
|
713
|
+
async function restoreCheckpoint(ws, c) {
|
|
714
|
+
const keep = new Set([...c.files.map((f) => f.path), ...(c.skipped ?? [])]);
|
|
715
|
+
for (const f of await ws.list("/")) {
|
|
716
|
+
if (ws.isSkillPath(f.path) || ws.mountOf(f.path) || keep.has(f.path))
|
|
717
|
+
continue;
|
|
718
|
+
// Snapshots from before `skipped` was recorded: a big file may not have been in it; leave it.
|
|
719
|
+
if (!c.skipped && c.partial && f.size > CKPT_FILE_MAX)
|
|
720
|
+
continue;
|
|
721
|
+
await ws.delete(f.path);
|
|
722
|
+
}
|
|
723
|
+
for (const f of c.files)
|
|
724
|
+
await ws.write(f.path, f.data, f.contentType);
|
|
725
|
+
}
|
|
726
|
+
const MAX_ATTACHMENT = 20 * 1024 * 1024;
|
|
727
|
+
const MAX_IMAGE_PART = 8 * 1024 * 1024;
|
|
728
|
+
/** A video sent inline (as a data URL) at most this big. */
|
|
729
|
+
const MAX_VIDEO_PART = 25 * 1024 * 1024;
|
|
730
|
+
const MAX_INLINE_TEXT = 64 * 1024;
|
|
731
|
+
const TEXT_EXT = /\.(txt|md|markdown|csv|tsv|json|jsonl|ya?ml|toml|xml|html?|css|js|mjs|cjs|ts|tsx|jsx|py|rb|go|rs|java|kt|c|h|cpp|hpp|cs|sh|bash|zsh|sql|ini|cfg|conf|log|env|svg|tex|rst)$/i;
|
|
732
|
+
const ATTACH_MARK = "[attachments]";
|
|
733
|
+
/** A text part of a message that came from the host (`addContext`): its first line names it, the rest is what the model reads. */
|
|
734
|
+
const CONTEXT_MARK = "[context] ";
|
|
735
|
+
/**
|
|
736
|
+
* A user message's text parts. A message kept as one string (a host that
|
|
737
|
+
* saves conversations as text joins the parts with newlines) is split back
|
|
738
|
+
* where the chat's own parts begin: context items, the attachment list,
|
|
739
|
+
* inlined files.
|
|
740
|
+
*/
|
|
741
|
+
function textPartsOf(content) {
|
|
742
|
+
if (Array.isArray(content))
|
|
743
|
+
return content.filter((p) => p.type === "text").map((p) => p.text);
|
|
744
|
+
if (typeof content !== "string")
|
|
745
|
+
return [];
|
|
746
|
+
if (!content.includes(CONTEXT_MARK) && !content.includes(ATTACH_MARK) && !content.includes("<file name="))
|
|
747
|
+
return [content];
|
|
748
|
+
const parts = [];
|
|
749
|
+
let cur = [], inFile = false;
|
|
750
|
+
for (const line of content.split("\n")) {
|
|
751
|
+
if (!inFile && (line.startsWith(CONTEXT_MARK) || line.startsWith(ATTACH_MARK) || line.startsWith("<file name=")) && cur.length) {
|
|
752
|
+
parts.push(cur.join("\n"));
|
|
753
|
+
cur = [];
|
|
754
|
+
}
|
|
755
|
+
cur.push(line);
|
|
756
|
+
// An inlined file's own lines never start a part.
|
|
757
|
+
if (!inFile && line.startsWith("<file name="))
|
|
758
|
+
inFile = !line.endsWith("</file>");
|
|
759
|
+
else if (inFile && line === "</file>")
|
|
760
|
+
inFile = false;
|
|
761
|
+
}
|
|
762
|
+
if (cur.length)
|
|
763
|
+
parts.push(cur.join("\n"));
|
|
764
|
+
return parts;
|
|
765
|
+
}
|
|
766
|
+
/** One line of the attachment list: `- <path or name> (<type>, <size>)[ — note]`; the name may hold parentheses. */
|
|
767
|
+
function parseAttachLine(line) {
|
|
768
|
+
const m = /^- (.+) \(([^()]*)\)(?: — .*)?$/.exec(line);
|
|
769
|
+
if (!m)
|
|
770
|
+
return null;
|
|
771
|
+
const [type = "", size = ""] = m[2].split(/,\s*/);
|
|
772
|
+
return { ref: m[1], type, size };
|
|
773
|
+
}
|
|
774
|
+
/** What the user typed for a message: the slash command as written, not its expansion. */
|
|
775
|
+
const typedOf = (m) => m?.typed;
|
|
776
|
+
/** Added to the agent's instructions when it has a directory: how to hand a file to the user. */
|
|
777
|
+
const linksHint = (uploads) => `When you create or change a file for the user, name its absolute path in backticks (for example \`/index.html\`); in the chat that path becomes a link that opens the file. Files the user attaches arrive under ${uploads}.`;
|
|
778
|
+
const filesHint = (uploads) => `The user can browse, edit and download every file of the directory from the chat's Files panel. When you create or change a file for the user, name its absolute path in backticks (for example \`${uploads}/report.csv\`); in the chat that path becomes a link that opens the file, with a download button. Files the user attaches arrive under ${uploads}.`;
|
|
779
|
+
/** Text when the type or extension says so, or when the first 8 KB hold no NUL byte and decode as UTF-8. */
|
|
780
|
+
function decodeText(file, bytes) {
|
|
781
|
+
const typed = /^text\//.test(file.type) || /json|xml|javascript|yaml|csv|svg/.test(file.type) || TEXT_EXT.test(file.name);
|
|
782
|
+
if (!typed) {
|
|
783
|
+
const head = bytes.subarray(0, 8192);
|
|
784
|
+
for (const b of head)
|
|
785
|
+
if (b === 0)
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
try {
|
|
789
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
790
|
+
}
|
|
791
|
+
catch {
|
|
792
|
+
return null;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
function safeName(name) {
|
|
796
|
+
const base = name.replace(/^.*[\\/]/, "").replace(/[\u0000-\u001f]/g, "").trim() || "file";
|
|
797
|
+
return base.length > 120 ? base.slice(-120) : base;
|
|
798
|
+
}
|
|
799
|
+
/** `AgentUI` whose questions are cards above the composer and whose notices are toasts in the chat. */
|
|
800
|
+
function inlineUI(askArea, toasts, t, onChange) {
|
|
801
|
+
const pending = new Set();
|
|
802
|
+
const open = (build, cancelValue, signal) => new Promise((resolve) => {
|
|
803
|
+
if (signal?.aborted) {
|
|
804
|
+
resolve(cancelValue);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
const card = h("section", "ra-q");
|
|
808
|
+
let entry;
|
|
809
|
+
// A stopped run takes its question away as if dismissed.
|
|
810
|
+
const onAbort = () => entry.cancel();
|
|
811
|
+
const done = (v) => { signal?.removeEventListener("abort", onAbort); pending.delete(entry); card.remove(); onChange(); resolve(v); };
|
|
812
|
+
entry = { card, cancel: () => done(cancelValue) };
|
|
813
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
814
|
+
card.addEventListener("keydown", (e) => { if (e.key === "Escape" && !e.isComposing) {
|
|
815
|
+
e.preventDefault();
|
|
816
|
+
e.stopPropagation();
|
|
817
|
+
entry.cancel();
|
|
818
|
+
} });
|
|
819
|
+
build(card, done);
|
|
820
|
+
pending.add(entry);
|
|
821
|
+
askArea.append(card);
|
|
822
|
+
onChange();
|
|
823
|
+
const focus = card.querySelector("input,textarea,button.solid,button");
|
|
824
|
+
queueMicrotask(() => focus?.focus());
|
|
825
|
+
});
|
|
826
|
+
const head = (card, title, message) => {
|
|
827
|
+
card.append(h("div", "ra-qt", title));
|
|
828
|
+
if (message)
|
|
829
|
+
card.append(h("div", "ra-qm", message));
|
|
830
|
+
};
|
|
831
|
+
const btn = (label, cls, onClick) => { const b = h("button", "ra-btn xs " + cls, label); b.type = "button"; b.addEventListener("click", onClick); return b; };
|
|
832
|
+
return {
|
|
833
|
+
confirm: (title, message, opts = {}) => open((card, done) => {
|
|
834
|
+
head(card, title, message);
|
|
835
|
+
// The tool's own content (a diff to pick changes in), between the question and its buttons.
|
|
836
|
+
if (opts.body) {
|
|
837
|
+
try {
|
|
838
|
+
const b = opts.body();
|
|
839
|
+
b.classList.add("ra-cbody");
|
|
840
|
+
card.append(b);
|
|
841
|
+
}
|
|
842
|
+
catch (err) {
|
|
843
|
+
console.warn("agent: confirm body failed", err);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
const row = h("div", "ra-btns");
|
|
847
|
+
row.append(btn(opts.cancel ?? t.decline, "ghost", () => done(false)));
|
|
848
|
+
const always = opts.always;
|
|
849
|
+
if (always)
|
|
850
|
+
row.append(btn(always.label, "subtle", () => { try {
|
|
851
|
+
always.onChoose();
|
|
852
|
+
}
|
|
853
|
+
catch (err) {
|
|
854
|
+
console.warn("agent: always.onChoose failed", err);
|
|
855
|
+
} done(true); }));
|
|
856
|
+
row.append(btn(opts.ok ?? t.allow, opts.danger ? "red" : "solid", () => done(true)));
|
|
857
|
+
card.append(row);
|
|
858
|
+
}, false, opts.signal),
|
|
859
|
+
select: (title, options, opts = {}) => open((card, done) => {
|
|
860
|
+
head(card, title, opts.message);
|
|
861
|
+
const list = h("div", "ra-opts");
|
|
862
|
+
if (!opts.multi && !opts.allowOther) {
|
|
863
|
+
// Single choice: a click answers.
|
|
864
|
+
for (const o of options) {
|
|
865
|
+
const b = h("button", "ra-opt");
|
|
866
|
+
b.type = "button";
|
|
867
|
+
const text = h("div");
|
|
868
|
+
text.append(h("span", "", o.label ?? o.value));
|
|
869
|
+
if (o.description)
|
|
870
|
+
text.append(h("small", "", o.description));
|
|
871
|
+
b.append(text);
|
|
872
|
+
b.addEventListener("click", () => done([o.value]));
|
|
873
|
+
list.append(b);
|
|
874
|
+
}
|
|
875
|
+
card.append(list, (() => { const r = h("div", "ra-btns"); r.append(btn(t.cancel, "ghost", () => done(null))); return r; })());
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
const name = "ra_" + Math.random().toString(36).slice(2, 8);
|
|
879
|
+
const inputs = [];
|
|
880
|
+
const add = (o) => {
|
|
881
|
+
const label = h("label", "ra-opt");
|
|
882
|
+
const input = h("input");
|
|
883
|
+
input.type = opts.multi ? "checkbox" : "radio";
|
|
884
|
+
input.name = name;
|
|
885
|
+
input.value = o.value;
|
|
886
|
+
inputs.push(input);
|
|
887
|
+
const text = h("div");
|
|
888
|
+
text.append(h("span", "", o.label ?? o.value));
|
|
889
|
+
if (o.description)
|
|
890
|
+
text.append(h("small", "", o.description));
|
|
891
|
+
label.append(input, text);
|
|
892
|
+
list.append(label);
|
|
893
|
+
};
|
|
894
|
+
options.forEach(add);
|
|
895
|
+
let other = null;
|
|
896
|
+
if (opts.allowOther) {
|
|
897
|
+
add({ value: "__other__", label: t.other });
|
|
898
|
+
other = h("input", "ra-field");
|
|
899
|
+
other.type = "text";
|
|
900
|
+
other.placeholder = t.typeAnswer;
|
|
901
|
+
other.addEventListener("focus", () => { const o = inputs.find((i) => i.value === "__other__"); if (o)
|
|
902
|
+
o.checked = true; });
|
|
903
|
+
list.append(other);
|
|
904
|
+
}
|
|
905
|
+
card.append(list);
|
|
906
|
+
const row = h("div", "ra-btns");
|
|
907
|
+
row.append(btn(t.cancel, "ghost", () => done(null)), btn(t.ok, "solid", () => {
|
|
908
|
+
const picked = inputs.filter((i) => i.checked).map((i) => (i.value === "__other__" ? (other?.value.trim() ?? "") : i.value)).filter(Boolean);
|
|
909
|
+
if (picked.length)
|
|
910
|
+
done(picked);
|
|
911
|
+
}));
|
|
912
|
+
card.append(row);
|
|
913
|
+
}, null, opts.signal),
|
|
914
|
+
input: (title, opts = {}) => open((card, done) => {
|
|
915
|
+
head(card, title, opts.message);
|
|
916
|
+
const field = opts.multiline ? h("textarea", "ra-field") : h("input", "ra-field");
|
|
917
|
+
if (!opts.multiline)
|
|
918
|
+
field.type = "text";
|
|
919
|
+
if (opts.placeholder)
|
|
920
|
+
field.placeholder = opts.placeholder;
|
|
921
|
+
if (opts.initial)
|
|
922
|
+
field.value = opts.initial;
|
|
923
|
+
field.addEventListener("keydown", (ev) => {
|
|
924
|
+
const e = ev;
|
|
925
|
+
if (e.key === "Enter" && !e.isComposing && (!opts.multiline || e.metaKey || e.ctrlKey)) {
|
|
926
|
+
e.preventDefault();
|
|
927
|
+
done(field.value);
|
|
928
|
+
}
|
|
929
|
+
});
|
|
930
|
+
card.append(field);
|
|
931
|
+
const row = h("div", "ra-btns");
|
|
932
|
+
row.append(btn(t.cancel, "ghost", () => done(null)), btn(t.submit, "solid", () => done(field.value)));
|
|
933
|
+
card.append(row);
|
|
934
|
+
}, null, opts.signal),
|
|
935
|
+
notify(message, level = "info") {
|
|
936
|
+
const el = h("div", "ra-toast " + level, message);
|
|
937
|
+
toasts.append(el);
|
|
938
|
+
setTimeout(() => el.remove(), level === "error" ? 8000 : 4000);
|
|
939
|
+
},
|
|
940
|
+
/** Declines the questions on screen (`all`: the parked ones of other sessions too). */
|
|
941
|
+
cancelAll(all = false) {
|
|
942
|
+
for (const p of [...pending])
|
|
943
|
+
if (all || p.card.isConnected)
|
|
944
|
+
p.cancel();
|
|
945
|
+
},
|
|
946
|
+
/** Takes the cards on screen out of the DOM, still pending, for the session being left. */
|
|
947
|
+
park() {
|
|
948
|
+
const out = [];
|
|
949
|
+
for (const p of pending)
|
|
950
|
+
if (p.card.isConnected) {
|
|
951
|
+
p.card.remove();
|
|
952
|
+
out.push(p.card);
|
|
953
|
+
}
|
|
954
|
+
onChange();
|
|
955
|
+
return out;
|
|
956
|
+
},
|
|
957
|
+
restore(cards) {
|
|
958
|
+
for (const c of cards)
|
|
959
|
+
askArea.append(c);
|
|
960
|
+
if (cards.length)
|
|
961
|
+
onChange();
|
|
962
|
+
},
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
const LAST_KEY = (project) => `__runapps_agent_chat:${project}:last`;
|
|
966
|
+
function readLast(project) {
|
|
967
|
+
try {
|
|
968
|
+
return localStorage.getItem(LAST_KEY(project));
|
|
969
|
+
}
|
|
970
|
+
catch {
|
|
971
|
+
return null;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
function writeLast(project, id) {
|
|
975
|
+
try {
|
|
976
|
+
if (id)
|
|
977
|
+
localStorage.setItem(LAST_KEY(project), id);
|
|
978
|
+
else
|
|
979
|
+
localStorage.removeItem(LAST_KEY(project));
|
|
980
|
+
}
|
|
981
|
+
catch { /* private mode */ }
|
|
982
|
+
}
|
|
983
|
+
export function renderChat(target, opts) {
|
|
984
|
+
if (typeof document === "undefined")
|
|
985
|
+
throw new Error("renderChat needs a document");
|
|
986
|
+
if (!opts.agent && !opts.provider && !opts.client)
|
|
987
|
+
throw new Error("renderChat needs a provider (or a RunApps client, or an agent)");
|
|
988
|
+
injectStyles();
|
|
989
|
+
const lang = pickLocale(opts.locale);
|
|
990
|
+
const t = STRINGS[lang];
|
|
991
|
+
const { client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, ...agentOpts } = opts;
|
|
992
|
+
const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
|
|
993
|
+
const provider = providerOpt ? toProvider(providerOpt) : clientOpt ? toProvider(clientOpt) : givenAgent?.provider ?? null;
|
|
994
|
+
const project = provider?.name ?? agentOpts.appName ?? "app";
|
|
995
|
+
// Shell.
|
|
996
|
+
const root = h("div", "ra-chat");
|
|
997
|
+
if (className)
|
|
998
|
+
root.classList.add(...className.split(/\s+/).filter(Boolean));
|
|
999
|
+
// Appearance: data-theme is what was asked (auto/light/dark), data-scheme what applies; the palette and
|
|
1000
|
+
// overrides are applied for the scheme in effect (a custom palette inline, since it has no CSS of its own).
|
|
1001
|
+
let themeNow = theme ?? "auto";
|
|
1002
|
+
let paletteNow = paletteOpt ?? "claude";
|
|
1003
|
+
let varsNow = varsOpt;
|
|
1004
|
+
const media = typeof matchMedia === "function" ? matchMedia("(prefers-color-scheme: dark)") : null;
|
|
1005
|
+
let inlineProps = [];
|
|
1006
|
+
const applyAppearance = () => {
|
|
1007
|
+
const scheme = themeNow === "auto" ? (media?.matches ? "dark" : "light") : themeNow;
|
|
1008
|
+
root.dataset.theme = themeNow;
|
|
1009
|
+
root.dataset.scheme = scheme;
|
|
1010
|
+
if (typeof paletteNow === "string")
|
|
1011
|
+
root.dataset.palette = paletteNow;
|
|
1012
|
+
else
|
|
1013
|
+
delete root.dataset.palette;
|
|
1014
|
+
for (const prop of inlineProps)
|
|
1015
|
+
root.style.removeProperty(prop);
|
|
1016
|
+
inlineProps = [];
|
|
1017
|
+
const set = (vals) => {
|
|
1018
|
+
for (const [k, v] of Object.entries(vals ?? {}))
|
|
1019
|
+
if (v !== undefined) {
|
|
1020
|
+
const prop = tokenProp(k);
|
|
1021
|
+
root.style.setProperty(prop, v);
|
|
1022
|
+
inlineProps.push(prop);
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
if (typeof paletteNow !== "string")
|
|
1026
|
+
set(paletteNow[scheme]);
|
|
1027
|
+
const v = varsNow;
|
|
1028
|
+
if (v && ("light" in v || "dark" in v))
|
|
1029
|
+
set(v[scheme]);
|
|
1030
|
+
else
|
|
1031
|
+
set(v);
|
|
1032
|
+
};
|
|
1033
|
+
applyAppearance();
|
|
1034
|
+
const onScheme = () => { if (themeNow === "auto")
|
|
1035
|
+
applyAppearance(); };
|
|
1036
|
+
media?.addEventListener?.("change", onScheme);
|
|
1037
|
+
const head = h("div", "ra-head");
|
|
1038
|
+
const titleEl = h("div", "ra-title", title === false ? "" : title || agentOpts.appName || t.assistant);
|
|
1039
|
+
const modelEl = h("span", "ra-badge");
|
|
1040
|
+
const debugBtn = h("button", "ra-btn ghost");
|
|
1041
|
+
debugBtn.type = "button";
|
|
1042
|
+
debugBtn.innerHTML = I.bug() + `<span>${escapeHTML(t.debug)}</span>`;
|
|
1043
|
+
const filesBtn = h("button", "ra-btn ghost");
|
|
1044
|
+
filesBtn.type = "button";
|
|
1045
|
+
filesBtn.innerHTML = I.folder() + `<span>${escapeHTML(t.files)}</span>`;
|
|
1046
|
+
const skillsBtn = h("button", "ra-btn ghost");
|
|
1047
|
+
skillsBtn.type = "button";
|
|
1048
|
+
skillsBtn.innerHTML = I.puzzle() + `<span>${escapeHTML(t.skills)}</span>`;
|
|
1049
|
+
/** A number beside a header button's label (also on narrow screens, where the label hides); 0: no number. */
|
|
1050
|
+
const countBadge = (btn, label) => {
|
|
1051
|
+
const b = h("b", "ra-cnt");
|
|
1052
|
+
b.style.display = "none";
|
|
1053
|
+
btn.append(b);
|
|
1054
|
+
return (n) => { b.textContent = String(n); b.style.display = n ? "" : "none"; btn.title = n ? `${label} · ${n}` : label; };
|
|
1055
|
+
};
|
|
1056
|
+
const setSkillCount = countBadge(skillsBtn, t.skills);
|
|
1057
|
+
const histBtn = h("button", "ra-btn ghost");
|
|
1058
|
+
histBtn.type = "button";
|
|
1059
|
+
histBtn.innerHTML = I.hist() + `<span>${escapeHTML(t.history)}</span>`;
|
|
1060
|
+
// How many conversations there are (none shown while the open one is the only one).
|
|
1061
|
+
const setHistCount = countBadge(histBtn, t.history);
|
|
1062
|
+
const newBtn = h("button", "ra-btn ghost");
|
|
1063
|
+
newBtn.type = "button";
|
|
1064
|
+
newBtn.innerHTML = I.plus() + `<span>${escapeHTML(t.newChat)}</span>`;
|
|
1065
|
+
// Without a conversation list: one conversation, which this starts over.
|
|
1066
|
+
const clearBtn = h("button", "ra-btn ghost");
|
|
1067
|
+
clearBtn.type = "button";
|
|
1068
|
+
clearBtn.innerHTML = I.eraser() + `<span>${escapeHTML(t.clearChat)}</span>`;
|
|
1069
|
+
clearBtn.style.display = "none";
|
|
1070
|
+
// How full the context is, as a ring; a click opens the numbers and the spending.
|
|
1071
|
+
const useBtn = h("button", "ra-btn ghost ra-usebtn");
|
|
1072
|
+
useBtn.type = "button";
|
|
1073
|
+
useBtn.style.display = "none";
|
|
1074
|
+
const setBtn = h("button", "ra-btn ghost");
|
|
1075
|
+
setBtn.type = "button";
|
|
1076
|
+
setBtn.innerHTML = I.gear();
|
|
1077
|
+
setBtn.title = t.settings;
|
|
1078
|
+
setBtn.setAttribute("aria-label", t.settings);
|
|
1079
|
+
// In a narrow chat the labels fold away and only the icons show: each button keeps its name.
|
|
1080
|
+
for (const [btn, label] of [[debugBtn, t.debug], [filesBtn, t.files], [skillsBtn, t.skills], [histBtn, t.history], [newBtn, t.newChat], [clearBtn, t.clearChat]]) {
|
|
1081
|
+
btn.setAttribute("aria-label", label);
|
|
1082
|
+
if (!btn.title)
|
|
1083
|
+
btn.title = label;
|
|
1084
|
+
}
|
|
1085
|
+
for (const el of [...(headerActions ?? []), ...(headerEnd ?? []), ...(composerTop ? [composerTop] : []), ...(emptyState instanceof HTMLElement ? [emptyState] : [])])
|
|
1086
|
+
el.classList.add("ra-host");
|
|
1087
|
+
head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, histBtn, newBtn, clearBtn, ...(headerActions ?? []), setBtn, ...(headerEnd ?? []));
|
|
1088
|
+
if (title === false)
|
|
1089
|
+
head.style.display = "none";
|
|
1090
|
+
const log = h("div", "ra-log");
|
|
1091
|
+
const inner = h("div", "ra-col");
|
|
1092
|
+
log.append(inner);
|
|
1093
|
+
const askArea = h("div", "ra-ask");
|
|
1094
|
+
const askCol = h("div", "ra-col");
|
|
1095
|
+
askArea.append(askCol);
|
|
1096
|
+
const statusEl = h("div", "ra-status");
|
|
1097
|
+
statusEl.style.display = "none";
|
|
1098
|
+
const comp = h("div", "ra-comp");
|
|
1099
|
+
const compCol = h("div", "ra-col");
|
|
1100
|
+
const alertEl = h("div", "ra-alert");
|
|
1101
|
+
alertEl.style.display = "none";
|
|
1102
|
+
alertEl.setAttribute("role", "alert");
|
|
1103
|
+
const queueEl = h("div", "ra-queue");
|
|
1104
|
+
queueEl.style.display = "none";
|
|
1105
|
+
const box = h("div", "ra-box");
|
|
1106
|
+
const cmds = h("div", "ra-cmds");
|
|
1107
|
+
cmds.style.display = "none";
|
|
1108
|
+
const ta = h("textarea");
|
|
1109
|
+
ta.rows = 2;
|
|
1110
|
+
ta.setAttribute("aria-label", "Message");
|
|
1111
|
+
const files = h("div", "ra-files");
|
|
1112
|
+
files.style.display = "none";
|
|
1113
|
+
const bar = h("div", "ra-bar");
|
|
1114
|
+
const left = h("div", "ra-left");
|
|
1115
|
+
const attachBtn = h("button", "ra-attach");
|
|
1116
|
+
attachBtn.type = "button";
|
|
1117
|
+
attachBtn.innerHTML = I.clip();
|
|
1118
|
+
attachBtn.title = t.attach;
|
|
1119
|
+
attachBtn.setAttribute("aria-label", t.attach);
|
|
1120
|
+
const fileInput = h("input");
|
|
1121
|
+
fileInput.type = "file";
|
|
1122
|
+
fileInput.multiple = true;
|
|
1123
|
+
fileInput.style.display = "none";
|
|
1124
|
+
if (attachOpt === false)
|
|
1125
|
+
attachBtn.style.display = "none";
|
|
1126
|
+
const hint = h("span", "ra-hint");
|
|
1127
|
+
// ⌘ on a Mac, Ctrl elsewhere (the symbols read like the app's own placeholder: "↵ to send, ⌘↵ to queue").
|
|
1128
|
+
// Chrome's userAgentData says "macOS", navigator.platform says "MacIntel": match either, any case.
|
|
1129
|
+
const isMac = typeof navigator !== "undefined" && /mac|iphone|ipad|ipod/i.test(`${navigator.userAgentData?.platform ?? ""} ${navigator.platform ?? ""}`);
|
|
1130
|
+
const MOD = isMac ? "⌘" : "Ctrl+";
|
|
1131
|
+
const fill = (x) => x.replace("{mod}", MOD).replace("{enter}", t.enter).replace("{newline}", t.newline);
|
|
1132
|
+
hint.textContent = fill(t.hintIdle);
|
|
1133
|
+
const acts = h("div", "ra-acts");
|
|
1134
|
+
const sendBtn = h("button", "ra-send");
|
|
1135
|
+
sendBtn.type = "button";
|
|
1136
|
+
sendBtn.innerHTML = I.corner(18);
|
|
1137
|
+
sendBtn.title = t.send;
|
|
1138
|
+
sendBtn.setAttribute("aria-label", t.send);
|
|
1139
|
+
const steerBtn = h("button", "ra-btn xs subtle");
|
|
1140
|
+
steerBtn.type = "button";
|
|
1141
|
+
steerBtn.innerHTML = I.corner() + escapeHTML(t.steer);
|
|
1142
|
+
steerBtn.title = t.steerTip;
|
|
1143
|
+
const fuBtn = h("button", "ra-btn xs subtle", t.followUp);
|
|
1144
|
+
fuBtn.type = "button";
|
|
1145
|
+
fuBtn.title = t.followUpTip;
|
|
1146
|
+
// While it works, the send button's place holds a stop square.
|
|
1147
|
+
const stopBtn = h("button", "ra-stop");
|
|
1148
|
+
stopBtn.type = "button";
|
|
1149
|
+
stopBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><rect x="2" y="2" width="12" height="12" rx="3" fill="currentColor"/></svg>';
|
|
1150
|
+
stopBtn.title = t.stop;
|
|
1151
|
+
stopBtn.setAttribute("aria-label", t.stop);
|
|
1152
|
+
acts.append(steerBtn, fuBtn, stopBtn, sendBtn);
|
|
1153
|
+
// The host's toolbar buttons: an element as it is, a ComposerAction drawn as ours.
|
|
1154
|
+
const actionBtns = new Map();
|
|
1155
|
+
const drawAction = (btn, a) => {
|
|
1156
|
+
const icon = a.icon && a.iconOnly ? a.icon : a.icon ? a.icon + `<span>${escapeHTML(a.label)}</span>` : `<span>${escapeHTML(a.label)}</span>`;
|
|
1157
|
+
btn.innerHTML = icon;
|
|
1158
|
+
btn.classList.toggle("icon", !!(a.icon && a.iconOnly));
|
|
1159
|
+
btn.title = a.title ?? a.label;
|
|
1160
|
+
btn.setAttribute("aria-label", a.label);
|
|
1161
|
+
btn.style.display = a.hidden ? "none" : "";
|
|
1162
|
+
btn.disabled = !!a.disabled;
|
|
1163
|
+
};
|
|
1164
|
+
const hostActions = (composerActions ?? []).map((x) => {
|
|
1165
|
+
if (x instanceof HTMLElement) {
|
|
1166
|
+
x.classList.add("ra-host");
|
|
1167
|
+
return x;
|
|
1168
|
+
}
|
|
1169
|
+
const a = { ...x };
|
|
1170
|
+
const btn = h("button", "ra-cbtn");
|
|
1171
|
+
btn.type = "button";
|
|
1172
|
+
btn.addEventListener("click", () => a.onClick());
|
|
1173
|
+
drawAction(btn, a);
|
|
1174
|
+
if (a.id)
|
|
1175
|
+
actionBtns.set(a.id, { btn, a });
|
|
1176
|
+
return btn;
|
|
1177
|
+
});
|
|
1178
|
+
left.append(attachBtn, ...hostActions, hint);
|
|
1179
|
+
bar.append(left, acts);
|
|
1180
|
+
box.append(cmds, files, ta, bar, fileInput);
|
|
1181
|
+
const drop = h("div", "ra-drop", t.drop);
|
|
1182
|
+
compCol.append(alertEl, queueEl, ...(composerTop ? [composerTop] : []), box);
|
|
1183
|
+
comp.append(compCol);
|
|
1184
|
+
const toasts = h("div", "ra-toasts");
|
|
1185
|
+
const statusCol = h("div", "ra-col");
|
|
1186
|
+
statusCol.append(statusEl);
|
|
1187
|
+
const main = h("div", "ra-main");
|
|
1188
|
+
const chatCol = h("div", "ra-chatcol");
|
|
1189
|
+
// Back to the end: shown while the transcript is scrolled away from it.
|
|
1190
|
+
const jumpWrap = h("div", "ra-jumpwrap");
|
|
1191
|
+
const jumpBtn = h("button", "ra-jump");
|
|
1192
|
+
jumpBtn.type = "button";
|
|
1193
|
+
jumpBtn.innerHTML = I.arrowDown();
|
|
1194
|
+
jumpBtn.title = t.jumpEnd;
|
|
1195
|
+
jumpBtn.setAttribute("aria-label", t.jumpEnd);
|
|
1196
|
+
jumpBtn.tabIndex = -1;
|
|
1197
|
+
jumpWrap.append(jumpBtn);
|
|
1198
|
+
chatCol.append(log, jumpWrap, askArea, statusCol, comp);
|
|
1199
|
+
main.append(chatCol);
|
|
1200
|
+
root.append(head, main, toasts, drop);
|
|
1201
|
+
target.replaceChildren(root);
|
|
1202
|
+
// State.
|
|
1203
|
+
let agent;
|
|
1204
|
+
const list = new VirtualList(log, inner, {
|
|
1205
|
+
estimate: 96, overscan: 400, rowClass: "ra-row",
|
|
1206
|
+
onFollow: (following) => {
|
|
1207
|
+
const show = !following && log.scrollHeight - log.clientHeight > 40;
|
|
1208
|
+
jumpBtn.classList.toggle("show", show);
|
|
1209
|
+
jumpBtn.tabIndex = show ? 0 : -1;
|
|
1210
|
+
},
|
|
1211
|
+
});
|
|
1212
|
+
jumpBtn.addEventListener("click", () => list.scrollToBottom());
|
|
1213
|
+
// Opening or closing something in the transcript (tool calls, a card, the thinking) keeps the clicked line where it is.
|
|
1214
|
+
log.addEventListener("click", (e) => {
|
|
1215
|
+
const sum = e.target.closest("summary");
|
|
1216
|
+
if (sum && log.contains(sum))
|
|
1217
|
+
list.pin(sum);
|
|
1218
|
+
}, true);
|
|
1219
|
+
let active = null;
|
|
1220
|
+
let renderTimer = null;
|
|
1221
|
+
const cards = new Map();
|
|
1222
|
+
/** The call behind each tool card element, for the group line that sums them up. */
|
|
1223
|
+
const cardCall = new WeakMap();
|
|
1224
|
+
/** Calls of the drawn history still waiting for a result (a resumed run): tool_end fills them in before their row is built. */
|
|
1225
|
+
const histCalls = new Map();
|
|
1226
|
+
let commands = [];
|
|
1227
|
+
let cmdIndex = 0;
|
|
1228
|
+
let cmdFrame = null;
|
|
1229
|
+
let unsub = [];
|
|
1230
|
+
let menu = null;
|
|
1231
|
+
let mounted = true;
|
|
1232
|
+
// A short chat (a phone held sideways, a small panel) keeps the transcript readable: the composer is compact.
|
|
1233
|
+
const rootSize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => { root.dataset.short = root.clientHeight && root.clientHeight < 420 ? "1" : ""; });
|
|
1234
|
+
rootSize?.observe(root);
|
|
1235
|
+
// While a question waits, the composer folds to one line so the question has the room (short screens).
|
|
1236
|
+
// An answered question sends the view back to the latest output (where the reply to it appears).
|
|
1237
|
+
let asked = 0;
|
|
1238
|
+
const ui = inlineUI(askCol, toasts, t, () => {
|
|
1239
|
+
const n = askCol.childElementCount;
|
|
1240
|
+
root.dataset.asking = n ? "1" : "";
|
|
1241
|
+
if (n < asked)
|
|
1242
|
+
list.scrollToBottom();
|
|
1243
|
+
else
|
|
1244
|
+
list.schedule();
|
|
1245
|
+
asked = n;
|
|
1246
|
+
});
|
|
1247
|
+
const MAX_BACKGROUND = 3;
|
|
1248
|
+
/** Sessions the chat made that are still running after the user switched away (and the current one). */
|
|
1249
|
+
const live = new Map();
|
|
1250
|
+
const bgSubs = new Map();
|
|
1251
|
+
const parked = new Map();
|
|
1252
|
+
/** Background sessions whose question waits for the user to come back. */
|
|
1253
|
+
const waiting = new Set();
|
|
1254
|
+
const waiters = new Map();
|
|
1255
|
+
/** Resolves true once session `id` is on screen; false when its run stops (or the session goes away) first. */
|
|
1256
|
+
const whenCurrent = (id, signal) => new Promise((res) => {
|
|
1257
|
+
if (agent?.id === id) {
|
|
1258
|
+
res(true);
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
if (signal?.aborted) {
|
|
1262
|
+
res(false);
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
waiting.add(id);
|
|
1266
|
+
const w = waiters.get(id) ?? [];
|
|
1267
|
+
const settle = (shown) => { signal?.removeEventListener("abort", onAbort); res(shown); };
|
|
1268
|
+
const onAbort = () => { const list = waiters.get(id); if (list) {
|
|
1269
|
+
const k = list.indexOf(settle);
|
|
1270
|
+
if (k >= 0)
|
|
1271
|
+
list.splice(k, 1);
|
|
1272
|
+
if (!list.length) {
|
|
1273
|
+
waiters.delete(id);
|
|
1274
|
+
waiting.delete(id);
|
|
1275
|
+
}
|
|
1276
|
+
} settle(false); markBackground(); };
|
|
1277
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1278
|
+
w.push(settle);
|
|
1279
|
+
waiters.set(id, w);
|
|
1280
|
+
markBackground();
|
|
1281
|
+
});
|
|
1282
|
+
const wake = (id, shown = true) => { const w = waiters.get(id); waiters.delete(id); waiting.delete(id); w?.forEach((f) => f(shown)); };
|
|
1283
|
+
/** The chat's dialogs for one session: a question from a session that is not on screen waits until it is (or its run stops). */
|
|
1284
|
+
const uiFor = (id) => ({
|
|
1285
|
+
confirm: async (title, message, o) => ((await whenCurrent(id, o?.signal)) ? ui.confirm(title, message, o) : false),
|
|
1286
|
+
select: async (title, options, o) => ((await whenCurrent(id, o?.signal)) ? ui.select(title, options, o) : null),
|
|
1287
|
+
input: async (title, o) => ((await whenCurrent(id, o?.signal)) ? ui.input(title, o) : null),
|
|
1288
|
+
notify: (m, l) => ui.notify(m, l),
|
|
1289
|
+
});
|
|
1290
|
+
/** Whether rewinding may restore files: only a directory of the session's own, kept in IndexedDB (not a folder on disk, not shared). */
|
|
1291
|
+
const restorable = (a) => !!a.workspace && typeof wsOpt === "function" && !a.workspace.root;
|
|
1292
|
+
const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || a.queued.length > 0 || waiting.has(a.id)));
|
|
1293
|
+
const titleOfAgent = (a) => { const text = titleOf({ v: 2, id: a.id, messages: a.messages, usage: a.usage, droppedTurns: 0, savedAt: 0 }); return text === UNTITLED ? t.untitled : text.length > 40 ? text.slice(0, 37) + "…" : text; };
|
|
1294
|
+
const markBackground = () => histBtn.classList.toggle("ra-bg", background().length > 0);
|
|
1295
|
+
/** The Chats count: the conversations, open one included, shown once there is another (redrawn after a run, a switch, a delete). */
|
|
1296
|
+
let histTimer = null;
|
|
1297
|
+
const refreshHistCount = () => {
|
|
1298
|
+
if (histTimer)
|
|
1299
|
+
clearTimeout(histTimer);
|
|
1300
|
+
histTimer = setTimeout(async () => {
|
|
1301
|
+
histTimer = null;
|
|
1302
|
+
const ws = agent?.workspace;
|
|
1303
|
+
if (!ws || givenAgent) {
|
|
1304
|
+
setHistCount(0);
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
try {
|
|
1308
|
+
const all = await ws.sessions.list();
|
|
1309
|
+
// Every conversation, the open one included; nothing while the open one is the only one.
|
|
1310
|
+
const others = all.filter((x) => x.id !== agent.id).length;
|
|
1311
|
+
if (agent?.workspace === ws)
|
|
1312
|
+
setHistCount(others ? others + 1 : 0);
|
|
1313
|
+
}
|
|
1314
|
+
catch { /* leave it */ }
|
|
1315
|
+
}, 50);
|
|
1316
|
+
};
|
|
1317
|
+
/** The work files as they are when a message is sent, so a rewind to it can put them back. */
|
|
1318
|
+
const checkpoint = async (a, msg) => {
|
|
1319
|
+
const ts = tsOf(msg);
|
|
1320
|
+
if (!a.workspace || !ts)
|
|
1321
|
+
return;
|
|
1322
|
+
// The app's own state (rewindState), kept beside the conversation.
|
|
1323
|
+
if (rewindState) {
|
|
1324
|
+
try {
|
|
1325
|
+
await takeHostState(a.workspace, ts, await rewindState.take());
|
|
1326
|
+
}
|
|
1327
|
+
catch (err) {
|
|
1328
|
+
console.warn("agent: rewindState.take failed", err);
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
if (!restorable(a))
|
|
1332
|
+
return;
|
|
1333
|
+
try {
|
|
1334
|
+
await takeCheckpoint(a.workspace, ts);
|
|
1335
|
+
}
|
|
1336
|
+
catch (err) {
|
|
1337
|
+
console.warn("agent: checkpoint failed", err);
|
|
1338
|
+
}
|
|
1339
|
+
};
|
|
1340
|
+
/** Keeps an eye on a session running in the background: a notice when it ends, dropped once idle. */
|
|
1341
|
+
const watchBackground = (a) => {
|
|
1342
|
+
if (bgSubs.has(a.id))
|
|
1343
|
+
return;
|
|
1344
|
+
const subs = [];
|
|
1345
|
+
subs.push(a.on("run_end", () => {
|
|
1346
|
+
if (agent === a)
|
|
1347
|
+
return;
|
|
1348
|
+
ui.notify(`${titleOfAgent(a)} · ${t.finished}`);
|
|
1349
|
+
// `busy` flips after the run's promise settles, a tick after this event.
|
|
1350
|
+
setTimeout(() => { if (!mounted)
|
|
1351
|
+
return; if (agent !== a && !a.busy && !a.queued.length && !waiting.has(a.id)) {
|
|
1352
|
+
live.delete(a.id);
|
|
1353
|
+
unwatchBackground(a);
|
|
1354
|
+
release(a);
|
|
1355
|
+
} markBackground(); }, 50);
|
|
1356
|
+
}));
|
|
1357
|
+
subs.push(a.on("run_start", (ev) => { markBackground(); if (ev.message)
|
|
1358
|
+
void checkpoint(a, ev.message); }));
|
|
1359
|
+
bgSubs.set(a.id, subs);
|
|
1360
|
+
markBackground();
|
|
1361
|
+
};
|
|
1362
|
+
const unwatchBackground = (a) => { bgSubs.get(a.id)?.forEach((u) => u()); bgSubs.delete(a.id); };
|
|
1363
|
+
// The header buttons of the two side panels show which one is open, however it was opened or closed.
|
|
1364
|
+
const panel = filesPanel({ t, root, editorHost: chatCol, notify: (m, l) => ui.notify(m, l), onChange: () => void refreshCommands(), onShow: (v) => filesBtn.classList.toggle("on", v) });
|
|
1365
|
+
main.append(panel.el);
|
|
1366
|
+
const dpanel = debugPanel({ t, root, onShow: (v) => debugBtn.classList.toggle("on", v) });
|
|
1367
|
+
main.append(dpanel.el);
|
|
1368
|
+
let debugOn = !!debugOpt;
|
|
1369
|
+
const applyDebug = () => {
|
|
1370
|
+
debugBtn.style.display = debugOn ? "" : "none";
|
|
1371
|
+
root.dataset.debug = debugOn ? "1" : "";
|
|
1372
|
+
// Sessions are recorded only while debug mode is on (a trace holds on to its agent).
|
|
1373
|
+
if (debugOn) {
|
|
1374
|
+
for (const a of live.values())
|
|
1375
|
+
if (a !== agent)
|
|
1376
|
+
dpanel.setAgent(a);
|
|
1377
|
+
if (agent)
|
|
1378
|
+
dpanel.setAgent(agent);
|
|
1379
|
+
}
|
|
1380
|
+
else {
|
|
1381
|
+
dpanel.close();
|
|
1382
|
+
for (const a of live.values())
|
|
1383
|
+
dpanel.forget(a);
|
|
1384
|
+
}
|
|
1385
|
+
};
|
|
1386
|
+
applyDebug();
|
|
1387
|
+
filesBtn.addEventListener("click", () => { if (dpanel.visible) {
|
|
1388
|
+
dpanel.close();
|
|
1389
|
+
applyDebug();
|
|
1390
|
+
} void panel.toggle(); });
|
|
1391
|
+
debugBtn.addEventListener("click", async () => {
|
|
1392
|
+
if (panel.visible)
|
|
1393
|
+
await panel.close();
|
|
1394
|
+
if (panel.visible)
|
|
1395
|
+
return; // closing was declined (unsaved edits)
|
|
1396
|
+
dpanel.toggle();
|
|
1397
|
+
applyDebug();
|
|
1398
|
+
});
|
|
1399
|
+
/** Opens a path: the host's editor when it has one, else the files panel. */
|
|
1400
|
+
const openPath = (path) => { if (onOpenFile)
|
|
1401
|
+
onOpenFile(path);
|
|
1402
|
+
else
|
|
1403
|
+
void panel.open(path); };
|
|
1404
|
+
const openIfExists = async (path) => {
|
|
1405
|
+
const ws = agent?.workspace;
|
|
1406
|
+
if (ws && !(await ws.exists(path))) {
|
|
1407
|
+
ui.notify(`${t.rewindGoneFile.replace("{path}", path)}`, "warning");
|
|
1408
|
+
return;
|
|
1409
|
+
}
|
|
1410
|
+
openPath(path);
|
|
1411
|
+
};
|
|
1412
|
+
const emptyEl = h("div", "ra-empty");
|
|
1413
|
+
const emptyRow = { render: () => emptyEl };
|
|
1414
|
+
const showEmpty = () => {
|
|
1415
|
+
if (emptyState === null)
|
|
1416
|
+
return;
|
|
1417
|
+
emptyEl.replaceChildren();
|
|
1418
|
+
emptyEl.classList.toggle("start", typeof emptyState === "object" && !(emptyState instanceof HTMLElement) && emptyState?.align === "start");
|
|
1419
|
+
if (emptyState instanceof HTMLElement)
|
|
1420
|
+
emptyEl.append(emptyState);
|
|
1421
|
+
else if (emptyState && typeof emptyState === "object") {
|
|
1422
|
+
if (emptyState.icon) {
|
|
1423
|
+
const icon = h("div", "ra-empty-icon");
|
|
1424
|
+
if (typeof emptyState.icon === "string")
|
|
1425
|
+
icon.innerHTML = emptyState.icon;
|
|
1426
|
+
else
|
|
1427
|
+
icon.append(emptyState.icon);
|
|
1428
|
+
emptyEl.append(icon);
|
|
1429
|
+
}
|
|
1430
|
+
if (emptyState.title)
|
|
1431
|
+
emptyEl.append(h("h3", "ra-empty-title", emptyState.title));
|
|
1432
|
+
if (emptyState.text)
|
|
1433
|
+
emptyEl.append(h("p", "ra-empty-text", emptyState.text));
|
|
1434
|
+
}
|
|
1435
|
+
else
|
|
1436
|
+
emptyEl.append(h("div", "", typeof emptyState === "string" ? emptyState : t.empty));
|
|
1437
|
+
if (suggestions?.length) {
|
|
1438
|
+
const row = h("div", "ra-sugs");
|
|
1439
|
+
for (const s of suggestions) {
|
|
1440
|
+
const label = typeof s === "string" ? s : s.label, prompt = typeof s === "string" ? s : s.prompt;
|
|
1441
|
+
const b = h("button", "", label);
|
|
1442
|
+
b.type = "button";
|
|
1443
|
+
if (prompt !== label)
|
|
1444
|
+
b.title = prompt;
|
|
1445
|
+
b.addEventListener("click", () => { ta.value = prompt; ta.focus(); renderCmds(); });
|
|
1446
|
+
row.append(b);
|
|
1447
|
+
}
|
|
1448
|
+
emptyEl.append(row);
|
|
1449
|
+
}
|
|
1450
|
+
if (!list.rows.includes(emptyRow))
|
|
1451
|
+
list.push(emptyRow);
|
|
1452
|
+
};
|
|
1453
|
+
const hideEmpty = () => list.remove(emptyRow);
|
|
1454
|
+
/* --- rows --- */
|
|
1455
|
+
const addRow = (row) => { hideEmpty(); list.push(row); };
|
|
1456
|
+
/** An attachment card: the file type as a small badge (or the picture), the name ellipsised in the middle so the extension stays, the size. */
|
|
1457
|
+
const chipEl = (name, size, preview) => {
|
|
1458
|
+
const chip = h("span", "ra-chip");
|
|
1459
|
+
const dot = name.lastIndexOf(".");
|
|
1460
|
+
const ext = dot > 0 && name.length - dot <= 6 ? name.slice(dot) : "";
|
|
1461
|
+
if (preview) {
|
|
1462
|
+
const img = h("img");
|
|
1463
|
+
img.src = preview;
|
|
1464
|
+
img.alt = "";
|
|
1465
|
+
chip.append(img);
|
|
1466
|
+
}
|
|
1467
|
+
else
|
|
1468
|
+
chip.append(h("span", "ra-ext", (ext.slice(1) || "file").slice(0, 4)));
|
|
1469
|
+
const n = h("span", "ra-cn");
|
|
1470
|
+
n.title = name;
|
|
1471
|
+
n.append(h("span", "st", ext ? name.slice(0, dot) : name));
|
|
1472
|
+
if (ext)
|
|
1473
|
+
n.append(h("span", "ex", ext));
|
|
1474
|
+
chip.append(n);
|
|
1475
|
+
if (size)
|
|
1476
|
+
chip.append(h("small", "", size.replace(/\s+(?=[KMG]?B$)/, "")));
|
|
1477
|
+
return chip;
|
|
1478
|
+
};
|
|
1479
|
+
const contextChip = (label, title, icon) => {
|
|
1480
|
+
const chip = h("span", "ra-chip ra-ctx");
|
|
1481
|
+
const ico = h("span", "ra-ctxi");
|
|
1482
|
+
ico.innerHTML = icon ?? I.pointer(15);
|
|
1483
|
+
const n = h("span", "ra-cn");
|
|
1484
|
+
n.title = title ?? label;
|
|
1485
|
+
n.append(h("span", "st", label));
|
|
1486
|
+
chip.append(ico, n);
|
|
1487
|
+
return chip;
|
|
1488
|
+
};
|
|
1489
|
+
/** The context parts of a message: its label (first line) and what the model read. */
|
|
1490
|
+
const contextsOf = (content) => textPartsOf(content).flatMap((p) => (p.startsWith(CONTEXT_MARK) ? [{ label: p.slice(CONTEXT_MARK.length).split("\n")[0], text: p.includes("\n") ? p.slice(p.indexOf("\n") + 1) : "" }] : []));
|
|
1491
|
+
const userEl = (content, row) => {
|
|
1492
|
+
const el = h("div", "ra-user");
|
|
1493
|
+
const b = h("div", "ra-bubble");
|
|
1494
|
+
// The attachment list (a text part of its own) is shown as chips, not as text.
|
|
1495
|
+
const parts = textPartsOf(content);
|
|
1496
|
+
const text = row.text;
|
|
1497
|
+
b.textContent = text.length > 4000 ? text.slice(0, 4000) + "…" : text;
|
|
1498
|
+
const attached = parts.find((p) => p.startsWith(ATTACH_MARK));
|
|
1499
|
+
if (attached) {
|
|
1500
|
+
const chips = h("div", "ra-files");
|
|
1501
|
+
for (const line of attached.split("\n").slice(1)) {
|
|
1502
|
+
const a = parseAttachLine(line);
|
|
1503
|
+
if (!a)
|
|
1504
|
+
continue;
|
|
1505
|
+
const chip = chipEl(a.ref.replace(/^.*\//, ""), a.size, null);
|
|
1506
|
+
// A file saved in the directory: click to find it in the files panel.
|
|
1507
|
+
if (a.ref.startsWith("/")) {
|
|
1508
|
+
const path = a.ref;
|
|
1509
|
+
chip.classList.add("ra-chip-link");
|
|
1510
|
+
chip.title = `${t.open} ${path}`;
|
|
1511
|
+
chip.setAttribute("role", "button");
|
|
1512
|
+
chip.tabIndex = 0;
|
|
1513
|
+
chip.addEventListener("click", () => void openIfExists(path));
|
|
1514
|
+
chip.addEventListener("keydown", (e) => { if (e.key === "Enter")
|
|
1515
|
+
void openIfExists(path); });
|
|
1516
|
+
}
|
|
1517
|
+
chips.append(chip);
|
|
1518
|
+
}
|
|
1519
|
+
if (chips.childElementCount)
|
|
1520
|
+
b.append(chips);
|
|
1521
|
+
}
|
|
1522
|
+
const ctx = contextsOf(content);
|
|
1523
|
+
if (ctx.length) {
|
|
1524
|
+
const chips = h("div", "ra-files");
|
|
1525
|
+
for (const c of ctx)
|
|
1526
|
+
chips.append(contextChip(c.label));
|
|
1527
|
+
b.append(chips);
|
|
1528
|
+
}
|
|
1529
|
+
for (const url of imagesOf(content)) {
|
|
1530
|
+
const img = h("img");
|
|
1531
|
+
img.src = url;
|
|
1532
|
+
img.alt = "";
|
|
1533
|
+
b.append(img);
|
|
1534
|
+
}
|
|
1535
|
+
// Footer, shown on hover: sent + when, copy, rewind.
|
|
1536
|
+
const foot = h("div", "ra-uf");
|
|
1537
|
+
const time = h("span", "ra-ut");
|
|
1538
|
+
const copy = h("button", "ra-ib");
|
|
1539
|
+
copy.type = "button";
|
|
1540
|
+
copy.innerHTML = I.copy(13);
|
|
1541
|
+
copy.title = t.copy;
|
|
1542
|
+
copy.setAttribute("aria-label", t.copy);
|
|
1543
|
+
copy.addEventListener("click", () => { void navigator.clipboard?.writeText(row.text).then(() => ui.notify(t.copied)); });
|
|
1544
|
+
const back = h("button", "ra-ib");
|
|
1545
|
+
back.type = "button";
|
|
1546
|
+
back.innerHTML = I.undo();
|
|
1547
|
+
back.title = t.rewind;
|
|
1548
|
+
back.setAttribute("aria-label", t.rewind);
|
|
1549
|
+
back.addEventListener("click", () => void rewindTo(row));
|
|
1550
|
+
foot.append(time, copy, back);
|
|
1551
|
+
el.addEventListener("mouseenter", () => row.update());
|
|
1552
|
+
row.update = () => {
|
|
1553
|
+
const ts = tsOf(row.msg);
|
|
1554
|
+
time.innerHTML = I.checks() + `<span>${escapeHTML(ts ? relTime(ts, t) : t.sent)}</span>`;
|
|
1555
|
+
back.disabled = !row.msg;
|
|
1556
|
+
};
|
|
1557
|
+
row.update();
|
|
1558
|
+
el.append(b, foot);
|
|
1559
|
+
return el;
|
|
1560
|
+
};
|
|
1561
|
+
const userRow = (content, msg) => {
|
|
1562
|
+
const parts = textPartsOf(content);
|
|
1563
|
+
// Expanded slash commands show what was typed; the expansion is for the model.
|
|
1564
|
+
const own = parts.filter((p) => !p.startsWith(ATTACH_MARK) && !p.startsWith(CONTEXT_MARK) && !p.startsWith("<file name="));
|
|
1565
|
+
const typed = typedOf(msg);
|
|
1566
|
+
const row = { msg, text: typed ?? own.join("\n"), update: () => undefined, render: () => userEl(content, row) };
|
|
1567
|
+
return row;
|
|
1568
|
+
};
|
|
1569
|
+
/** The row drawn for a message this chat sent, until the agent's run_start hands over the message object. */
|
|
1570
|
+
let awaitingRow = null;
|
|
1571
|
+
const addUser = (content, msg) => { stampBefore(tsOf(msg) ?? Date.now()); const row = userRow(content, msg); addRow(row); list.scrollToBottom(); return row; };
|
|
1572
|
+
/** A dialog for rewinding: drop what follows the message, optionally put the files back as they were. */
|
|
1573
|
+
/** Asks before rewinding; the file option shows only when there is a snapshot to restore (and says what it holds). */
|
|
1574
|
+
const rewindDialog = async (ckpt, host, texts = { title: t.rewindTitle, message: t.rewindMsg, ok: t.rewind }) => {
|
|
1575
|
+
const ck = h("input");
|
|
1576
|
+
ck.type = "checkbox";
|
|
1577
|
+
ck.checked = !!ckpt;
|
|
1578
|
+
const hostCk = h("input");
|
|
1579
|
+
hostCk.type = "checkbox";
|
|
1580
|
+
hostCk.checked = true;
|
|
1581
|
+
const body = [];
|
|
1582
|
+
if (host && rewindState) {
|
|
1583
|
+
const lab = h("label", "ra-ck");
|
|
1584
|
+
lab.append(hostCk, h("span", "", rewindState.label));
|
|
1585
|
+
body.push(lab);
|
|
1586
|
+
}
|
|
1587
|
+
if (ckpt) {
|
|
1588
|
+
const lab = h("label", "ra-ck");
|
|
1589
|
+
lab.append(ck, h("span", "", t.rewindFiles));
|
|
1590
|
+
const size = ckpt.files.reduce((n, f) => n + (typeof f.data === "string" ? new TextEncoder().encode(f.data).length : f.data.byteLength), 0);
|
|
1591
|
+
body.push(lab, h("div", "ra-dn", t.rewindSnapshot.replace("{n}", String(ckpt.files.length)).replace("{size}", fmtSize(size)).replace("{time}", clockTime(ckpt.at)) + (ckpt.partial ? ` ${t.rewindPartial}` : "")));
|
|
1592
|
+
}
|
|
1593
|
+
const ok = await modal(root, { title: texts.title, message: texts.message, body, ok: texts.ok, cancel: t.cancel, focus: "ok" });
|
|
1594
|
+
return ok ? { files: !!ckpt && ck.checked, host: !!host && hostCk.checked } : null;
|
|
1595
|
+
};
|
|
1596
|
+
const rewindTo = (row) => (row.msg ? rewindToMessage(row.msg, row.text) : Promise.resolve());
|
|
1597
|
+
/** Rewinds to a user message: its text and attachments go back into the composer; `resend` sends it again at once (Answer again). */
|
|
1598
|
+
const rewindToMessage = async (msg, text, resend = false) => {
|
|
1599
|
+
if (!agent)
|
|
1600
|
+
return;
|
|
1601
|
+
const a = agent;
|
|
1602
|
+
const row = { msg, text };
|
|
1603
|
+
const index = a.messages.indexOf(row.msg);
|
|
1604
|
+
if (index < 0) {
|
|
1605
|
+
ui.notify(t.rewindGone, "warning");
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1608
|
+
const ws = a.workspace;
|
|
1609
|
+
const ts = tsOf(row.msg);
|
|
1610
|
+
const ckpt = ws && ts && restorable(a) ? await ws.getData(ckptKey(ts)) : undefined;
|
|
1611
|
+
const hostState = ws && ts && rewindState ? await ws.getData(hostKey(ts)) : undefined;
|
|
1612
|
+
const choice = await rewindDialog(ckpt, hostState, resend ? { title: t.regenTitle, message: t.regenMsg, ok: t.regen } : undefined);
|
|
1613
|
+
if (!choice || agent !== a)
|
|
1614
|
+
return;
|
|
1615
|
+
let rewound = false;
|
|
1616
|
+
try {
|
|
1617
|
+
if (a.busy) {
|
|
1618
|
+
ui.cancelAll();
|
|
1619
|
+
await a.abort();
|
|
1620
|
+
}
|
|
1621
|
+
await a.rewind(index);
|
|
1622
|
+
rewound = true;
|
|
1623
|
+
if (choice.files && ws && ckpt) {
|
|
1624
|
+
try {
|
|
1625
|
+
await restoreCheckpoint(ws, ckpt);
|
|
1626
|
+
}
|
|
1627
|
+
catch (err) {
|
|
1628
|
+
ui.notify(err.message, "error");
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
if (choice.host && hostState && rewindState) {
|
|
1632
|
+
try {
|
|
1633
|
+
await rewindState.restore(hostState.value);
|
|
1634
|
+
}
|
|
1635
|
+
catch (err) {
|
|
1636
|
+
ui.notify(err.message, "error");
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
if (ws && ts) {
|
|
1640
|
+
void dropCheckpointsAfter(ws, ts).catch(() => undefined);
|
|
1641
|
+
void dropHostStatesAfter(ws, ts).catch(() => undefined);
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
catch (err) {
|
|
1645
|
+
ui.notify(err.message, "error");
|
|
1646
|
+
}
|
|
1647
|
+
finally {
|
|
1648
|
+
// Whatever happened, the transcript shows what the agent has.
|
|
1649
|
+
if (agent === a) {
|
|
1650
|
+
renderHistory(a.messages);
|
|
1651
|
+
showUsage_(a);
|
|
1652
|
+
void panel.refresh();
|
|
1653
|
+
void refreshCommands();
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
if (!rewound || agent !== a)
|
|
1657
|
+
return;
|
|
1658
|
+
ta.value = row.text;
|
|
1659
|
+
ta.focus();
|
|
1660
|
+
renderCmds();
|
|
1661
|
+
await reattach(row.msg);
|
|
1662
|
+
if (resend)
|
|
1663
|
+
await send("prompt");
|
|
1664
|
+
};
|
|
1665
|
+
/* --- a reply's footer, shown on hover: copy, answer again, delete; what the reply cost --- */
|
|
1666
|
+
/** A message the user wrote (not a compaction summary or the agent's own note). */
|
|
1667
|
+
const isUserTurn = (m) => m.role === "user" && !(typeof m.content === "string" && (summaryOf(m) !== null || m.content.startsWith("[environment]")));
|
|
1668
|
+
/** The question-and-answer a reply belongs to: from its user message up to the next one. */
|
|
1669
|
+
const turnOf = (a, last) => {
|
|
1670
|
+
const msgs = a.messages, i = msgs.indexOf(last);
|
|
1671
|
+
if (i < 0)
|
|
1672
|
+
return null;
|
|
1673
|
+
let start = i;
|
|
1674
|
+
while (start >= 0 && !isUserTurn(msgs[start]))
|
|
1675
|
+
start--;
|
|
1676
|
+
let end = i + 1;
|
|
1677
|
+
while (end < msgs.length && !isUserTurn(msgs[end]))
|
|
1678
|
+
end++;
|
|
1679
|
+
return start < 0 ? null : { start, end };
|
|
1680
|
+
};
|
|
1681
|
+
const replyFoot = (last) => {
|
|
1682
|
+
const foot = h("div", "ra-af");
|
|
1683
|
+
const btn = (icon, label, onClick) => { const b = h("button", "ra-ib"); b.type = "button"; b.innerHTML = icon; b.title = label; b.setAttribute("aria-label", label); b.addEventListener("click", onClick); return b; };
|
|
1684
|
+
const copy = btn(I.copy(13), t.copy, () => {
|
|
1685
|
+
const a = agent, turn = a && turnOf(a, last);
|
|
1686
|
+
// The answer: the reply's last text (what came before it is the work behind it).
|
|
1687
|
+
const texts = turn ? a.messages.slice(turn.start + 1, turn.end).filter((m) => m.role === "assistant").map((m) => textOfContent(m.content).trim()).filter(Boolean) : [textOfContent(last.content).trim()];
|
|
1688
|
+
void navigator.clipboard?.writeText(texts.at(-1) ?? "").then(() => ui.notify(t.copied));
|
|
1689
|
+
});
|
|
1690
|
+
const again = btn(I.refresh(13), t.regen, () => {
|
|
1691
|
+
const a = agent, turn = a && turnOf(a, last);
|
|
1692
|
+
if (!a || !turn) {
|
|
1693
|
+
ui.notify(t.rewindGone, "warning");
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
const user = a.messages[turn.start];
|
|
1697
|
+
void rewindToMessage(user, userRow(user.content, user).text, true);
|
|
1698
|
+
});
|
|
1699
|
+
const del = btn(I.trash(13), t.delTurn, () => void (async () => {
|
|
1700
|
+
const a = agent;
|
|
1701
|
+
if (!a || !turnOf(a, last)) {
|
|
1702
|
+
ui.notify(t.rewindGone, "warning");
|
|
1703
|
+
return;
|
|
1704
|
+
}
|
|
1705
|
+
if (!(await modalConfirm(root, t.delTurnTitle, t.delTurnMsg, { danger: true, ok: t.delTurn, cancel: t.cancel })))
|
|
1706
|
+
return;
|
|
1707
|
+
const turn = agent === a ? turnOf(a, last) : null;
|
|
1708
|
+
if (!turn)
|
|
1709
|
+
return;
|
|
1710
|
+
try {
|
|
1711
|
+
if (a.busy) {
|
|
1712
|
+
ui.cancelAll();
|
|
1713
|
+
await a.abort();
|
|
1714
|
+
}
|
|
1715
|
+
await a.remove(turn.start, turn.end);
|
|
1716
|
+
}
|
|
1717
|
+
catch (err) {
|
|
1718
|
+
ui.notify(err.message, "error");
|
|
1719
|
+
}
|
|
1720
|
+
})());
|
|
1721
|
+
foot.append(copy, again, del);
|
|
1722
|
+
const u = last.runUsage;
|
|
1723
|
+
if (u && u.calls) {
|
|
1724
|
+
const show = (currency) => { cost.textContent = t.replyCost.replace("{cost}", fmtCost(u.total_cost, currency)); };
|
|
1725
|
+
const cost = h("span", "ra-cost");
|
|
1726
|
+
show(costCurrency);
|
|
1727
|
+
// In the model's currency: asked of its catalogue entry when not known yet.
|
|
1728
|
+
const a = agent;
|
|
1729
|
+
if (costCurrency === undefined && a)
|
|
1730
|
+
void a.modelInfo().then((info) => { if (info?.price?.currency)
|
|
1731
|
+
show(info.price.currency); }).catch(() => undefined);
|
|
1732
|
+
cost.title = t.replyUsage.replace("{in}", fmtTokens(u.prompt_tokens)).replace("{out}", fmtTokens(u.completion_tokens)).replace("{calls}", String(u.calls));
|
|
1733
|
+
foot.append(cost);
|
|
1734
|
+
}
|
|
1735
|
+
return foot;
|
|
1736
|
+
};
|
|
1737
|
+
/** Puts a rewound message's context and attachments back into the composer: files from the directory, or from what the message carried inline. */
|
|
1738
|
+
const reattach = async (msg) => {
|
|
1739
|
+
if (typeof msg.content !== "string" && !Array.isArray(msg.content))
|
|
1740
|
+
return;
|
|
1741
|
+
// A message kept as one string: its parts, split back.
|
|
1742
|
+
const parts = Array.isArray(msg.content) ? msg.content : textPartsOf(msg.content).map((text) => ({ type: "text", text }));
|
|
1743
|
+
for (const c of contextsOf(parts).reverse())
|
|
1744
|
+
addContext({ label: c.label, text: c.text });
|
|
1745
|
+
const block = parts.find((p) => p.type === "text" && p.text.startsWith(ATTACH_MARK));
|
|
1746
|
+
if (!block)
|
|
1747
|
+
return;
|
|
1748
|
+
const ws = agent?.workspace;
|
|
1749
|
+
const inline = new Map();
|
|
1750
|
+
for (const p of parts)
|
|
1751
|
+
if (p.type === "text") {
|
|
1752
|
+
const m = /^<file name="([^"]*)">\n([\s\S]*)\n<\/file>$/.exec(p.text);
|
|
1753
|
+
if (m)
|
|
1754
|
+
inline.set(m[1], m[2]);
|
|
1755
|
+
}
|
|
1756
|
+
const images = parts.flatMap((p) => (p.type === "image_url" && p.image_url.url.startsWith("data:") ? [p.image_url.url] : []));
|
|
1757
|
+
const files = [], paths = [], missing = [];
|
|
1758
|
+
for (const line of block.text.split("\n").slice(1)) {
|
|
1759
|
+
const a = parseAttachLine(line);
|
|
1760
|
+
if (!a)
|
|
1761
|
+
continue;
|
|
1762
|
+
const { ref, type } = a;
|
|
1763
|
+
const name = ref.replace(/^.*\//, "");
|
|
1764
|
+
if (ref.startsWith("/") && ws) {
|
|
1765
|
+
try {
|
|
1766
|
+
const r = await ws.read(ref);
|
|
1767
|
+
files.push(new File([r.data], name, { type: r.contentType || type }));
|
|
1768
|
+
paths.push(ref);
|
|
1769
|
+
}
|
|
1770
|
+
catch {
|
|
1771
|
+
missing.push(ref);
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
else if (inline.has(name)) {
|
|
1775
|
+
files.push(new File([inline.get(name)], name, { type }));
|
|
1776
|
+
paths.push(undefined);
|
|
1777
|
+
}
|
|
1778
|
+
else if (/^image\//.test(type) && images.length) {
|
|
1779
|
+
const blob = await (await fetch(images.shift())).blob();
|
|
1780
|
+
files.push(new File([blob], name, { type }));
|
|
1781
|
+
paths.push(undefined);
|
|
1782
|
+
}
|
|
1783
|
+
else
|
|
1784
|
+
missing.push(name);
|
|
1785
|
+
}
|
|
1786
|
+
if (files.length)
|
|
1787
|
+
await addFiles(files, paths);
|
|
1788
|
+
if (missing.length)
|
|
1789
|
+
ui.notify(t.rewindGoneFile.replace("{path}", missing.join(", ")), "warning");
|
|
1790
|
+
};
|
|
1791
|
+
const asstRow = () => {
|
|
1792
|
+
const el = h("div", "ra-asst");
|
|
1793
|
+
const body = h("div", "ra-body");
|
|
1794
|
+
el.append(body);
|
|
1795
|
+
return { render: () => el, el, body, text: null, think: null, thinkBody: null, md: "", reasoning: "" };
|
|
1796
|
+
};
|
|
1797
|
+
const fmtDuration = (ms) => {
|
|
1798
|
+
const s = Math.max(1, Math.round(ms / 1000));
|
|
1799
|
+
if (s < 60)
|
|
1800
|
+
return t.sec.replace("{s}", String(s));
|
|
1801
|
+
if (s < 3600)
|
|
1802
|
+
return t.minSec.replace("{m}", String(Math.floor(s / 60))).replace("{s}", String(s % 60));
|
|
1803
|
+
return t.hourMin.replace("{h}", String(Math.floor(s / 3600))).replace("{m}", String(Math.floor((s % 3600) / 60)));
|
|
1804
|
+
};
|
|
1805
|
+
/**
|
|
1806
|
+
* A finished reply: everything before its answer (thinking, tool calls, text written along the way)
|
|
1807
|
+
* folds into one "Worked for 6m 38s" line, the answer stays below it. A reply that is only an answer
|
|
1808
|
+
* has nothing to fold; one that ended without an answer (stopped, turn limit) folds whole.
|
|
1809
|
+
*/
|
|
1810
|
+
const foldReply = (body, ms) => {
|
|
1811
|
+
if (body.querySelector(":scope>.ra-work"))
|
|
1812
|
+
return;
|
|
1813
|
+
const kids = Array.from(body.children);
|
|
1814
|
+
const last = kids.at(-1);
|
|
1815
|
+
const process = last?.classList.contains("ra-md") ? kids.slice(0, -1) : kids;
|
|
1816
|
+
if (!process.length)
|
|
1817
|
+
return;
|
|
1818
|
+
const d = h("details", "ra-work");
|
|
1819
|
+
const sum = h("summary");
|
|
1820
|
+
sum.append(h("span", "", ms !== undefined && ms > 0 ? t.worked.replace("{t}", fmtDuration(ms)) : t.workedNoTime));
|
|
1821
|
+
const chev = h("span", "ra-chev");
|
|
1822
|
+
chev.innerHTML = I.chev(13);
|
|
1823
|
+
sum.append(chev);
|
|
1824
|
+
// Opening it keeps the line where it is; the steps open below.
|
|
1825
|
+
sum.addEventListener("click", () => list.pin(sum));
|
|
1826
|
+
const inner = h("div", "ra-wb");
|
|
1827
|
+
inner.append(...process);
|
|
1828
|
+
d.append(sum, inner);
|
|
1829
|
+
body.prepend(d);
|
|
1830
|
+
};
|
|
1831
|
+
/** When the reply being drawn began (the run, or the steer it follows): its "worked for" time counts from here. */
|
|
1832
|
+
let replyStart = 0;
|
|
1833
|
+
const closeActive = () => {
|
|
1834
|
+
if (!active)
|
|
1835
|
+
return;
|
|
1836
|
+
clearPending(active);
|
|
1837
|
+
// A reply that never got any output (stopped at once) leaves no empty row behind.
|
|
1838
|
+
if (!active.body.childElementCount) {
|
|
1839
|
+
list.remove(active);
|
|
1840
|
+
active = null;
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
flushActive(true);
|
|
1844
|
+
foldReply(active.body, replyStart ? Date.now() - replyStart : undefined);
|
|
1845
|
+
active = null;
|
|
1846
|
+
list.schedule();
|
|
1847
|
+
};
|
|
1848
|
+
const ensureActive = () => {
|
|
1849
|
+
if (!active) {
|
|
1850
|
+
active = asstRow();
|
|
1851
|
+
addRow(active);
|
|
1852
|
+
}
|
|
1853
|
+
return active;
|
|
1854
|
+
};
|
|
1855
|
+
/** Shows "Thinking" at the end of the reply until the model's first output arrives. */
|
|
1856
|
+
/**
|
|
1857
|
+
* What the agent is doing right now, at the end of the reply: a shimmering label ("Thinking", "Running
|
|
1858
|
+
* code", …) and under it a few lines that scroll as they grow — the latest thinking, the code being run,
|
|
1859
|
+
* a tool's progress. Text the model writes replaces it (that is visible by itself).
|
|
1860
|
+
*/
|
|
1861
|
+
const showPending = (label = t.waiting, preview) => {
|
|
1862
|
+
const act = ensureActive();
|
|
1863
|
+
if (!act.pending) {
|
|
1864
|
+
act.pending = h("div", "ra-pending");
|
|
1865
|
+
act.pending.append(h("span", "", label));
|
|
1866
|
+
}
|
|
1867
|
+
const el = act.pending;
|
|
1868
|
+
el.firstElementChild.textContent = label;
|
|
1869
|
+
let pv = el.querySelector(".ra-lpv");
|
|
1870
|
+
const text = preview?.text.trim() ?? "";
|
|
1871
|
+
if (text) {
|
|
1872
|
+
if (!pv) {
|
|
1873
|
+
pv = h("div", "ra-lpv");
|
|
1874
|
+
pv.append(h("div"));
|
|
1875
|
+
el.append(pv);
|
|
1876
|
+
}
|
|
1877
|
+
pv.className = "ra-lpv" + (preview.code ? " code" : "") + (preview.head ? " head" : "");
|
|
1878
|
+
// Only the end matters for a stream (the box shows its last lines); the start for code.
|
|
1879
|
+
pv.firstElementChild.textContent = preview.head ? text.slice(0, 600) : text.slice(-600);
|
|
1880
|
+
}
|
|
1881
|
+
else
|
|
1882
|
+
pv?.remove();
|
|
1883
|
+
// Always the last thing in the reply.
|
|
1884
|
+
if (act.body.lastElementChild !== el)
|
|
1885
|
+
act.body.append(el);
|
|
1886
|
+
list.schedule();
|
|
1887
|
+
};
|
|
1888
|
+
/** The reply's last piece of content: the live status at the end does not count. */
|
|
1889
|
+
const lastContent = (body) => {
|
|
1890
|
+
const last = body.lastElementChild;
|
|
1891
|
+
return last?.classList.contains("ra-pending") ? last.previousElementSibling : last;
|
|
1892
|
+
};
|
|
1893
|
+
/** Adds content to a reply, before the live status (which stays last). */
|
|
1894
|
+
const putContent = (body, el) => {
|
|
1895
|
+
const p = body.lastElementChild;
|
|
1896
|
+
if (p?.classList.contains("ra-pending"))
|
|
1897
|
+
body.insertBefore(el, p);
|
|
1898
|
+
else
|
|
1899
|
+
body.append(el);
|
|
1900
|
+
};
|
|
1901
|
+
/** The preview of a tool call: the code it runs, the text it writes, else its arguments in short. */
|
|
1902
|
+
const toolPreview = (name, args) => {
|
|
1903
|
+
const a = (args && typeof args === "object" ? args : {});
|
|
1904
|
+
if (name === "run_js" && typeof a.code === "string")
|
|
1905
|
+
return { text: a.code, code: true, head: true };
|
|
1906
|
+
if (name === "write_file" && typeof a.content === "string")
|
|
1907
|
+
return { text: a.content, head: true };
|
|
1908
|
+
if (name === "edit_file" && Array.isArray(a.edits))
|
|
1909
|
+
return { text: a.edits.map((e) => (e && typeof e === "object" ? String(e.newText ?? "") : "")).join("\n…\n"), head: true };
|
|
1910
|
+
if (name === "edit_file" && typeof a.newText === "string")
|
|
1911
|
+
return { text: a.newText, head: true };
|
|
1912
|
+
return { text: summarizeArgs(name, args), head: true };
|
|
1913
|
+
};
|
|
1914
|
+
const clearPending = (act = active) => { if (act?.pending) {
|
|
1915
|
+
act.pending.remove();
|
|
1916
|
+
act.pending = null;
|
|
1917
|
+
} };
|
|
1918
|
+
/* --- time dividers: "Today 22:15" above a message that starts a conversation or follows a long pause --- */
|
|
1919
|
+
const GAP_MS = 15 * 60_000;
|
|
1920
|
+
let lastStamp = 0;
|
|
1921
|
+
const timeLabel = (ts) => {
|
|
1922
|
+
const d = new Date(ts), now = new Date();
|
|
1923
|
+
const hm = d.toLocaleTimeString(lang === "zh" ? "zh-CN" : undefined, { hour: "2-digit", minute: "2-digit", hour12: false });
|
|
1924
|
+
const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
|
|
1925
|
+
const diff = Math.round((day(now) - day(d)) / 86_400_000);
|
|
1926
|
+
if (diff === 0)
|
|
1927
|
+
return `${t.today} ${hm}`;
|
|
1928
|
+
if (diff === 1)
|
|
1929
|
+
return `${t.yesterday} ${hm}`;
|
|
1930
|
+
const date = d.toLocaleDateString(lang === "zh" ? "zh-CN" : undefined, d.getFullYear() === now.getFullYear() ? { month: "short", day: "numeric" } : { year: "numeric", month: "short", day: "numeric" });
|
|
1931
|
+
return `${date} ${hm}`;
|
|
1932
|
+
};
|
|
1933
|
+
/** A divider before a message sent at `ts`, when it opens the conversation or comes after a long pause. */
|
|
1934
|
+
const stampBefore = (ts) => {
|
|
1935
|
+
if (!ts)
|
|
1936
|
+
return;
|
|
1937
|
+
if (!lastStamp || ts - lastStamp >= GAP_MS) {
|
|
1938
|
+
const el = h("div", "ra-time", timeLabel(ts));
|
|
1939
|
+
addRow({ render: () => el, el });
|
|
1940
|
+
}
|
|
1941
|
+
lastStamp = ts;
|
|
1942
|
+
};
|
|
1943
|
+
const thinkEl = (reasoning, done) => {
|
|
1944
|
+
const d = h("details", "ra-think");
|
|
1945
|
+
const s = h("summary");
|
|
1946
|
+
s.innerHTML = `<span class="ra-chev">${I.chev(13)}</span>${I.brain()}<span>${escapeHTML(done ? t.thought : t.thinking)}</span>`;
|
|
1947
|
+
const body = h("div", "ra-think-body", reasoning);
|
|
1948
|
+
d.append(s, body);
|
|
1949
|
+
return [d, body];
|
|
1950
|
+
};
|
|
1951
|
+
/** `code` spans naming a file of the directory become links that open it (checked against the directory, so prose paths stay plain). */
|
|
1952
|
+
const linkPaths = (el) => {
|
|
1953
|
+
const ws = agent?.workspace;
|
|
1954
|
+
if (!ws)
|
|
1955
|
+
return;
|
|
1956
|
+
for (const code of Array.from(el.querySelectorAll("code"))) {
|
|
1957
|
+
if (code.closest("pre") || code.classList.contains("ra-path"))
|
|
1958
|
+
continue;
|
|
1959
|
+
const text = code.textContent?.trim() ?? "";
|
|
1960
|
+
if (!/^\/[^\s`'"<>]+$/.test(text) || text.length > 200)
|
|
1961
|
+
continue;
|
|
1962
|
+
void ws.exists(text).then((ok) => { if (ok && !code.classList.contains("ra-path")) {
|
|
1963
|
+
code.classList.add("ra-path");
|
|
1964
|
+
code.dataset.path = text;
|
|
1965
|
+
code.title = t.open;
|
|
1966
|
+
code.insertAdjacentHTML("beforeend", I.download(11));
|
|
1967
|
+
} });
|
|
1968
|
+
}
|
|
1969
|
+
};
|
|
1970
|
+
const renderFinal = (el, md) => { renderMD(el, md, false); linkPaths(el); };
|
|
1971
|
+
const flushActive = (final) => {
|
|
1972
|
+
if (renderTimer !== null) {
|
|
1973
|
+
clearTimeout(renderTimer);
|
|
1974
|
+
renderTimer = null;
|
|
1975
|
+
}
|
|
1976
|
+
if (!active)
|
|
1977
|
+
return;
|
|
1978
|
+
if (active.text && (active.drawn !== active.md || active.drawnFinal !== final)) {
|
|
1979
|
+
renderMD(active.text, active.md, !final);
|
|
1980
|
+
active.drawn = active.md;
|
|
1981
|
+
active.drawnFinal = final;
|
|
1982
|
+
if (final)
|
|
1983
|
+
linkPaths(active.text);
|
|
1984
|
+
}
|
|
1985
|
+
if (active.thinkBody)
|
|
1986
|
+
active.thinkBody.textContent = active.reasoning;
|
|
1987
|
+
if (active.think && final) {
|
|
1988
|
+
active.think.querySelector("summary span:last-child").textContent = t.thought;
|
|
1989
|
+
active.think.style.display = "";
|
|
1990
|
+
}
|
|
1991
|
+
// Thinking streams into the live preview; its own folded block shows once the thought is complete.
|
|
1992
|
+
else if (active.pending && active.reasoning && !active.text)
|
|
1993
|
+
showPending(t.thinking.replace(/…$/, ""), { text: active.reasoning });
|
|
1994
|
+
list.schedule();
|
|
1995
|
+
};
|
|
1996
|
+
const scheduleRender = () => { if (renderTimer === null)
|
|
1997
|
+
renderTimer = window.setTimeout(() => { renderTimer = null; flushActive(false); }, 100); };
|
|
1998
|
+
/** A tool's own display (ToolDefinition.display): any of its functions failing falls back to the default. */
|
|
1999
|
+
const displayOf = (name) => agent?.tools?.find((x) => x.name === name)?.display;
|
|
2000
|
+
const tryDisplay = (fn) => { if (!fn)
|
|
2001
|
+
return undefined; try {
|
|
2002
|
+
return fn();
|
|
2003
|
+
}
|
|
2004
|
+
catch {
|
|
2005
|
+
return undefined;
|
|
2006
|
+
} };
|
|
2007
|
+
const labelOf = (name, args) => { const d = displayOf(name); const l = tryDisplay(d?.label && (() => d.label(args))); return typeof l === "string" && l.trim() ? l : undefined; };
|
|
2008
|
+
/** The app's own content on a card: replaced on every call of `render`. */
|
|
2009
|
+
const renderCustom = (card, call) => {
|
|
2010
|
+
const d = displayOf(card.name);
|
|
2011
|
+
if (!d?.render)
|
|
2012
|
+
return;
|
|
2013
|
+
const el = tryDisplay(() => d.render({ args: card.args, ...call }));
|
|
2014
|
+
const sum = card.el.querySelector("summary");
|
|
2015
|
+
sum.querySelector(".ra-tx")?.remove();
|
|
2016
|
+
if (!(el instanceof HTMLElement))
|
|
2017
|
+
return;
|
|
2018
|
+
const box = h("div", "ra-tx ra-host");
|
|
2019
|
+
// Clicks on the app's content (a chip, a link) are its own: they do not fold the card.
|
|
2020
|
+
box.addEventListener("click", (e) => e.preventDefault());
|
|
2021
|
+
box.append(el);
|
|
2022
|
+
sum.append(box);
|
|
2023
|
+
};
|
|
2024
|
+
const makeCard = (name, args) => {
|
|
2025
|
+
const el = h("details", "ra-tool");
|
|
2026
|
+
cardCall.set(el, { name, args });
|
|
2027
|
+
const sum = h("summary");
|
|
2028
|
+
const d = displayOf(name), label = labelOf(name, args);
|
|
2029
|
+
const icon = h("span", "ra-ticon");
|
|
2030
|
+
icon.innerHTML = d?.icon ?? (TOOL_ICON[name] ?? I.wrench)();
|
|
2031
|
+
const end = h("span", "ra-tend");
|
|
2032
|
+
end.innerHTML = '<span class="ra-spin"></span>';
|
|
2033
|
+
sum.innerHTML = `<span class="ra-chev">${I.chev()}</span>`;
|
|
2034
|
+
const title = h("span", "ra-tname", label ?? name);
|
|
2035
|
+
if (label) {
|
|
2036
|
+
title.title = name;
|
|
2037
|
+
title.classList.add("own");
|
|
2038
|
+
}
|
|
2039
|
+
sum.append(icon, title, h("span", "ra-tsum", label ? "" : summarizeArgs(name, args)), end);
|
|
2040
|
+
const tb = h("div", "ra-tbody");
|
|
2041
|
+
const argsPre = h("pre", "", name === "run_js" && args && typeof args === "object" && typeof args.code === "string" ? args.code : typeof args === "string" ? args : JSON.stringify(args, null, 2));
|
|
2042
|
+
tb.append(h("div", "ra-tlabel", t.args), argsPre);
|
|
2043
|
+
const path = args && typeof args === "object" && typeof args.path === "string" ? args.path : null;
|
|
2044
|
+
if (path && name !== "delete_file" && name !== "list_files" && name !== "search_files") {
|
|
2045
|
+
const acts = h("div", "ra-tacts");
|
|
2046
|
+
const o = h("button", "ra-open", `${t.open} ${path}`);
|
|
2047
|
+
o.type = "button";
|
|
2048
|
+
o.addEventListener("click", () => openPath(path));
|
|
2049
|
+
const d = h("button", "ra-open", t.download);
|
|
2050
|
+
d.type = "button";
|
|
2051
|
+
d.addEventListener("click", () => void panel.download(path));
|
|
2052
|
+
acts.append(o, d);
|
|
2053
|
+
tb.append(acts);
|
|
2054
|
+
}
|
|
2055
|
+
el.append(sum, tb);
|
|
2056
|
+
const card = { el, name, args, end, body: tb, update: null, result: null };
|
|
2057
|
+
renderCustom(card, { status: "running" });
|
|
2058
|
+
return card;
|
|
2059
|
+
};
|
|
2060
|
+
/**
|
|
2061
|
+
* Consecutive tool calls of a reply share one collapsed line — "Running read_file /x" while one runs,
|
|
2062
|
+
* "Ran 3 tool calls" when done, failures counted — and their cards only show when it is opened.
|
|
2063
|
+
*/
|
|
2064
|
+
const groupIn = (body) => {
|
|
2065
|
+
const last = lastContent(body);
|
|
2066
|
+
if (last instanceof HTMLDetailsElement && last.classList.contains("ra-tg"))
|
|
2067
|
+
return last.querySelector(".ra-tgb");
|
|
2068
|
+
const g = h("details", "ra-tg");
|
|
2069
|
+
const sum = h("summary");
|
|
2070
|
+
const inner = h("div", "ra-tgb");
|
|
2071
|
+
g.append(sum, inner);
|
|
2072
|
+
putContent(body, g);
|
|
2073
|
+
return inner;
|
|
2074
|
+
};
|
|
2075
|
+
/** "读取了 3 个文件,修改了 1 个文件" — counted by kind, distinct paths for file tools, in the order they first ran. */
|
|
2076
|
+
const describeCalls = (calls) => {
|
|
2077
|
+
const order = [];
|
|
2078
|
+
const seen = new Map();
|
|
2079
|
+
for (const c of calls) {
|
|
2080
|
+
// A tool with its own words: those, counted when the same.
|
|
2081
|
+
const own = labelOf(c.name, c.args);
|
|
2082
|
+
if (own !== undefined) {
|
|
2083
|
+
const key = `Own:${own}`;
|
|
2084
|
+
if (!seen.has(key)) {
|
|
2085
|
+
order.push(key);
|
|
2086
|
+
seen.set(key, 0);
|
|
2087
|
+
}
|
|
2088
|
+
seen.set(key, seen.get(key) + 1);
|
|
2089
|
+
continue;
|
|
2090
|
+
}
|
|
2091
|
+
const kind = TOOL_KIND[c.name] ?? "Other";
|
|
2092
|
+
const key = kind === "Other" ? `Other:${c.name}` : kind;
|
|
2093
|
+
if (!seen.has(key)) {
|
|
2094
|
+
order.push(key);
|
|
2095
|
+
seen.set(key, kind === "Read" || kind === "Write" || kind === "Edit" || kind === "Delete" ? new Set() : 0);
|
|
2096
|
+
}
|
|
2097
|
+
const v = seen.get(key);
|
|
2098
|
+
if (v instanceof Set)
|
|
2099
|
+
v.add(pathArg(c.args) ?? String(v.size));
|
|
2100
|
+
else
|
|
2101
|
+
seen.set(key, v + 1);
|
|
2102
|
+
}
|
|
2103
|
+
return order.map((key) => {
|
|
2104
|
+
const v = seen.get(key);
|
|
2105
|
+
const n = String(v instanceof Set ? v.size : v);
|
|
2106
|
+
if (key.startsWith("Own:"))
|
|
2107
|
+
return v === 1 ? key.slice(4) : `${key.slice(4)} ×${n}`;
|
|
2108
|
+
if (key.startsWith("Other:"))
|
|
2109
|
+
return t.actOther.replace("{name}", key.slice(6));
|
|
2110
|
+
return t[`act${key}`].replace("{n}", n);
|
|
2111
|
+
}).join(lang === "zh" ? "," : ", ");
|
|
2112
|
+
};
|
|
2113
|
+
/** "正在修改 第一章.md" — the call in progress, by kind, with its file name or argument summary. */
|
|
2114
|
+
const describeRunning = (c, el) => {
|
|
2115
|
+
const own = labelOf(c.name, c.args);
|
|
2116
|
+
if (own !== undefined)
|
|
2117
|
+
return { verb: own, what: "" };
|
|
2118
|
+
const kind = TOOL_KIND[c.name] ?? "Other";
|
|
2119
|
+
const path = pathArg(c.args);
|
|
2120
|
+
const verb = t[`ing${kind}`];
|
|
2121
|
+
if (kind === "Other")
|
|
2122
|
+
return { verb: `${verb} ${c.name}`, what: el.querySelector(".ra-tsum")?.textContent ?? "" };
|
|
2123
|
+
if (kind === "Ask")
|
|
2124
|
+
return { verb, what: "" };
|
|
2125
|
+
if (path && kind !== "Search")
|
|
2126
|
+
return { verb, what: path.slice(path.lastIndexOf("/") + 1) || path, title: path };
|
|
2127
|
+
return { verb, what: el.querySelector(".ra-tsum")?.textContent ?? "" };
|
|
2128
|
+
};
|
|
2129
|
+
const refreshGroup = (cardEl) => {
|
|
2130
|
+
const g = cardEl.closest(".ra-tg");
|
|
2131
|
+
if (!g)
|
|
2132
|
+
return;
|
|
2133
|
+
const all = Array.from(g.querySelectorAll(".ra-tgb > .ra-tool"));
|
|
2134
|
+
const running = all.filter((c) => c.querySelector(".ra-tend .ra-spin"));
|
|
2135
|
+
const failed = all.filter((c) => c.classList.contains("fail")).length;
|
|
2136
|
+
const sum = g.querySelector("summary");
|
|
2137
|
+
sum.replaceChildren();
|
|
2138
|
+
if (running.length) {
|
|
2139
|
+
const el = running[running.length - 1];
|
|
2140
|
+
const r = describeRunning(cardCall.get(el) ?? { name: el.querySelector(".ra-tname")?.textContent ?? "", args: undefined }, el);
|
|
2141
|
+
sum.append(h("span", "ra-spin"));
|
|
2142
|
+
const txt = h("span", "ra-tgt");
|
|
2143
|
+
txt.append(`${r.verb} `);
|
|
2144
|
+
if (r.what)
|
|
2145
|
+
txt.append(h("code", "", r.what));
|
|
2146
|
+
if (r.title)
|
|
2147
|
+
txt.title = r.title;
|
|
2148
|
+
sum.append(txt);
|
|
2149
|
+
}
|
|
2150
|
+
else {
|
|
2151
|
+
const calls = all.map((el) => cardCall.get(el)).filter((c) => !!c);
|
|
2152
|
+
const label = calls.length ? describeCalls(calls) : (all.length === 1 ? t.toolsDone1 : t.toolsDone.replace("{n}", String(all.length)));
|
|
2153
|
+
const txt = h("span", "ra-tgt", label);
|
|
2154
|
+
txt.title = all.length === 1 ? t.toolsDone1 : t.toolsDone.replace("{n}", String(all.length));
|
|
2155
|
+
sum.append(txt);
|
|
2156
|
+
}
|
|
2157
|
+
if (failed)
|
|
2158
|
+
sum.append(h("span", "ra-tgf", t.toolsFailed.replace("{n}", String(failed))));
|
|
2159
|
+
const chev = h("span", "ra-chev");
|
|
2160
|
+
chev.innerHTML = I.chev(12);
|
|
2161
|
+
sum.append(chev);
|
|
2162
|
+
};
|
|
2163
|
+
const addCard = (id, name, args, body) => {
|
|
2164
|
+
const card = makeCard(name, args);
|
|
2165
|
+
groupIn(body).append(card.el);
|
|
2166
|
+
cards.set(id, card);
|
|
2167
|
+
refreshGroup(card.el);
|
|
2168
|
+
list.schedule();
|
|
2169
|
+
return card;
|
|
2170
|
+
};
|
|
2171
|
+
/** Pictures a tool returned, shown under its result (a screenshot, a chart). */
|
|
2172
|
+
const imagesOf = (content) => Array.isArray(content) ? content.flatMap((p) => (p.type === "image_url" && /^(data:image\/|https?:)/.test(p.image_url.url) ? [p.image_url.url] : [])) : [];
|
|
2173
|
+
const finishCard = (card, status, result, durationMs, images = [], details) => {
|
|
2174
|
+
const ok = status === "ok";
|
|
2175
|
+
const fail = status === "error" || status === "blocked";
|
|
2176
|
+
card.end.replaceChildren();
|
|
2177
|
+
const d = displayOf(card.name);
|
|
2178
|
+
const outcome = tryDisplay(d?.outcome && (() => d.outcome({ args: card.args, status, result, details })));
|
|
2179
|
+
if (typeof outcome === "string" && outcome)
|
|
2180
|
+
card.end.append(h("span", "ra-tout", outcome));
|
|
2181
|
+
else if (durationMs !== undefined)
|
|
2182
|
+
card.end.append(h("span", "", `${Math.round(durationMs)}ms`));
|
|
2183
|
+
const mark = h("span", ok ? "ok" : fail ? "fail" : "");
|
|
2184
|
+
if (ok)
|
|
2185
|
+
mark.innerHTML = I.check();
|
|
2186
|
+
else if (status === "error")
|
|
2187
|
+
mark.innerHTML = I.xcircle();
|
|
2188
|
+
else if (status === "blocked") {
|
|
2189
|
+
mark.innerHTML = I.ban();
|
|
2190
|
+
mark.title = t.blocked;
|
|
2191
|
+
}
|
|
2192
|
+
else
|
|
2193
|
+
mark.textContent = t[status] ?? status;
|
|
2194
|
+
card.end.append(mark);
|
|
2195
|
+
card.el.classList.toggle("fail", fail);
|
|
2196
|
+
renderCustom(card, { status, result, details });
|
|
2197
|
+
card.update?.remove();
|
|
2198
|
+
if (!card.result) {
|
|
2199
|
+
card.result = h("pre", "");
|
|
2200
|
+
card.body.append(h("div", "ra-tlabel", status === "error" ? t.error : t.result), card.result);
|
|
2201
|
+
}
|
|
2202
|
+
card.result.textContent = result.length > 20_000 ? result.slice(0, 20_000) + "…" : result || t.emptyResult;
|
|
2203
|
+
if (images.length && !card.body.querySelector(".ra-timgs")) {
|
|
2204
|
+
const row = h("div", "ra-timgs");
|
|
2205
|
+
for (const src of images.slice(0, 4)) {
|
|
2206
|
+
const img = h("img");
|
|
2207
|
+
img.src = src;
|
|
2208
|
+
img.alt = t.result;
|
|
2209
|
+
img.addEventListener("load", () => list.schedule());
|
|
2210
|
+
row.append(img);
|
|
2211
|
+
}
|
|
2212
|
+
card.body.append(row);
|
|
2213
|
+
}
|
|
2214
|
+
refreshGroup(card.el);
|
|
2215
|
+
list.schedule();
|
|
2216
|
+
};
|
|
2217
|
+
const noteEl = (text, summary, action) => {
|
|
2218
|
+
const card = h("div", "ra-card");
|
|
2219
|
+
const head = h("div", "ra-ct" + (summary ? "" : " only"));
|
|
2220
|
+
head.innerHTML = I.layers() + `<span>${escapeHTML(text)}</span>`;
|
|
2221
|
+
card.append(head);
|
|
2222
|
+
if (summary) {
|
|
2223
|
+
const md = h("div", "ra-md");
|
|
2224
|
+
renderMD(md, summary, false);
|
|
2225
|
+
card.append(md);
|
|
2226
|
+
}
|
|
2227
|
+
if (action) {
|
|
2228
|
+
const b = h("button", "ra-btn xs subtle", action.label);
|
|
2229
|
+
b.type = "button";
|
|
2230
|
+
b.addEventListener("click", () => { b.disabled = true; action.onClick(); });
|
|
2231
|
+
card.append(b);
|
|
2232
|
+
}
|
|
2233
|
+
return card;
|
|
2234
|
+
};
|
|
2235
|
+
const addNote = (text, summary, action) => { addRow({ render: () => noteEl(text, summary, action) }); list.schedule(); };
|
|
2236
|
+
/** A short notice sized to its text (a run that stopped at the turn limit); its button runs the action and removes the notice. */
|
|
2237
|
+
const addWarn = (text, action, hint) => {
|
|
2238
|
+
const row = {
|
|
2239
|
+
render: () => {
|
|
2240
|
+
const el = h("div", "ra-warn");
|
|
2241
|
+
el.setAttribute("role", "status");
|
|
2242
|
+
if (hint)
|
|
2243
|
+
el.title = hint;
|
|
2244
|
+
el.innerHTML = I.alert(14);
|
|
2245
|
+
el.append(h("span", "", text));
|
|
2246
|
+
if (action) {
|
|
2247
|
+
const b = h("button", "ra-btn xs", action.label);
|
|
2248
|
+
b.type = "button";
|
|
2249
|
+
b.addEventListener("click", () => { list.remove(row); action.onClick(); });
|
|
2250
|
+
el.append(b);
|
|
2251
|
+
}
|
|
2252
|
+
return el;
|
|
2253
|
+
},
|
|
2254
|
+
};
|
|
2255
|
+
addRow(row);
|
|
2256
|
+
list.schedule();
|
|
2257
|
+
};
|
|
2258
|
+
const addError = (message, retry) => {
|
|
2259
|
+
const row = {
|
|
2260
|
+
render: () => {
|
|
2261
|
+
const card = h("div", "ra-err", message);
|
|
2262
|
+
if (retry) {
|
|
2263
|
+
const b = h("button", "ra-btn xs red-subtle", t.retry);
|
|
2264
|
+
b.type = "button";
|
|
2265
|
+
b.addEventListener("click", () => { list.remove(row); retry(); });
|
|
2266
|
+
card.append(b);
|
|
2267
|
+
}
|
|
2268
|
+
return card;
|
|
2269
|
+
},
|
|
2270
|
+
};
|
|
2271
|
+
addRow(row);
|
|
2272
|
+
list.schedule();
|
|
2273
|
+
};
|
|
2274
|
+
/** Rows for a saved transcript; each reply is built only when scrolled into view. */
|
|
2275
|
+
const renderHistory = (messages) => {
|
|
2276
|
+
list.clear();
|
|
2277
|
+
lastStamp = 0;
|
|
2278
|
+
cards.clear();
|
|
2279
|
+
histCalls.clear();
|
|
2280
|
+
active = null;
|
|
2281
|
+
// One row per reply, as live: every turn between two user messages; text-less turns (thinking + tool calls) share a group.
|
|
2282
|
+
let last = null;
|
|
2283
|
+
let lastUserTs;
|
|
2284
|
+
const flush = (atEnd = false) => {
|
|
2285
|
+
if (!last)
|
|
2286
|
+
return;
|
|
2287
|
+
const m = last;
|
|
2288
|
+
last = null;
|
|
2289
|
+
// A reply still being written (the session is running) is not folded yet.
|
|
2290
|
+
const fold = !(atEnd && agent?.busy);
|
|
2291
|
+
addRow({
|
|
2292
|
+
render: () => {
|
|
2293
|
+
const r = asstRow();
|
|
2294
|
+
for (const it of m.items) {
|
|
2295
|
+
if (it.kind === "think") {
|
|
2296
|
+
// Thinking during a chain of calls sits in the group, before the calls it led to.
|
|
2297
|
+
const [d] = thinkEl(it.text, true);
|
|
2298
|
+
const lastEl = r.body.lastElementChild;
|
|
2299
|
+
if (lastEl instanceof HTMLDetailsElement && lastEl.classList.contains("ra-tg"))
|
|
2300
|
+
lastEl.querySelector(".ra-tgb").append(d);
|
|
2301
|
+
else
|
|
2302
|
+
r.body.append(d);
|
|
2303
|
+
}
|
|
2304
|
+
else if (it.kind === "text") {
|
|
2305
|
+
const el = h("div", "ra-md");
|
|
2306
|
+
renderFinal(el, it.text);
|
|
2307
|
+
r.body.append(el);
|
|
2308
|
+
}
|
|
2309
|
+
else {
|
|
2310
|
+
const c = it.call;
|
|
2311
|
+
const card = makeCard(c.name, c.args);
|
|
2312
|
+
groupIn(r.body).append(card.el);
|
|
2313
|
+
// A call still running (the session is mid-run) gets its card registered, so its tool_end lands.
|
|
2314
|
+
if (c.status)
|
|
2315
|
+
finishCard(card, c.status, c.result ?? "", undefined, c.images);
|
|
2316
|
+
else {
|
|
2317
|
+
if (c.id)
|
|
2318
|
+
cards.set(c.id, card);
|
|
2319
|
+
refreshGroup(card.el);
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
if (fold)
|
|
2324
|
+
foldReply(r.body, m.start !== undefined && m.end !== undefined ? m.end - m.start : undefined);
|
|
2325
|
+
if (fold && m.msg)
|
|
2326
|
+
r.el.append(replyFoot(m.msg));
|
|
2327
|
+
return r.el;
|
|
2328
|
+
},
|
|
2329
|
+
});
|
|
2330
|
+
};
|
|
2331
|
+
for (const m of messages) {
|
|
2332
|
+
if (m.role === "user") {
|
|
2333
|
+
flush();
|
|
2334
|
+
const s = typeof m.content === "string" ? summaryOf(m) : null;
|
|
2335
|
+
if (s !== null) {
|
|
2336
|
+
addNote(t.compacted, s);
|
|
2337
|
+
continue;
|
|
2338
|
+
}
|
|
2339
|
+
// The agent's own notes to the model (a loop warning) are not the user's messages.
|
|
2340
|
+
if (typeof m.content === "string" && m.content.startsWith("[environment]"))
|
|
2341
|
+
continue;
|
|
2342
|
+
lastUserTs = tsOf(m);
|
|
2343
|
+
stampBefore(lastUserTs);
|
|
2344
|
+
addRow(userRow(m.content, m));
|
|
2345
|
+
}
|
|
2346
|
+
else if (m.role === "assistant") {
|
|
2347
|
+
const text = textOfContent(m.content);
|
|
2348
|
+
const rs = m.reasoning_content;
|
|
2349
|
+
const reasoning = typeof rs === "string" ? rs : "";
|
|
2350
|
+
if (!last)
|
|
2351
|
+
last = { items: [], calls: [], start: lastUserTs };
|
|
2352
|
+
last.msg = m;
|
|
2353
|
+
last.end = tsOf(m) ?? last.end;
|
|
2354
|
+
if (last.end)
|
|
2355
|
+
lastStamp = last.end;
|
|
2356
|
+
if (reasoning)
|
|
2357
|
+
last.items.push({ kind: "think", text: reasoning });
|
|
2358
|
+
if (text)
|
|
2359
|
+
last.items.push({ kind: "text", text });
|
|
2360
|
+
for (const c of m.tool_calls ?? []) {
|
|
2361
|
+
if (hiddenTools.has(c.function.name))
|
|
2362
|
+
continue;
|
|
2363
|
+
let args = c.function.arguments;
|
|
2364
|
+
try {
|
|
2365
|
+
args = JSON.parse(c.function.arguments);
|
|
2366
|
+
}
|
|
2367
|
+
catch { /* keep the string */ }
|
|
2368
|
+
const call = { id: c.id ?? "", name: c.function.name, args };
|
|
2369
|
+
last.items.push({ kind: "call", call });
|
|
2370
|
+
last.calls.push(call);
|
|
2371
|
+
if (call.id)
|
|
2372
|
+
histCalls.set(call.id, call);
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
else if (m.role === "tool") {
|
|
2376
|
+
const text = textOfContent(m.content);
|
|
2377
|
+
const call = last?.calls.find((c) => c.id === (m.tool_call_id ?? ""));
|
|
2378
|
+
if (call) {
|
|
2379
|
+
call.result = text;
|
|
2380
|
+
call.status = statusOfResult(text);
|
|
2381
|
+
call.images = imagesOf(m.content);
|
|
2382
|
+
histCalls.delete(call.id);
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
}
|
|
2386
|
+
flush(true);
|
|
2387
|
+
if (!messages.length)
|
|
2388
|
+
showEmpty();
|
|
2389
|
+
list.scrollToBottom();
|
|
2390
|
+
};
|
|
2391
|
+
/* --- composer --- */
|
|
2392
|
+
/* --- the next-message suggestion (nextPrompt) --- */
|
|
2393
|
+
/** Shown greyed in the empty input; Tab takes it. */
|
|
2394
|
+
let nextSuggestion = null;
|
|
2395
|
+
/** What the model suggested during the run in progress; shown when it ends. */
|
|
2396
|
+
let pendingNext = null;
|
|
2397
|
+
const clearNext = () => {
|
|
2398
|
+
pendingNext = null;
|
|
2399
|
+
if (nextSuggestion === null)
|
|
2400
|
+
return;
|
|
2401
|
+
nextSuggestion = null;
|
|
2402
|
+
setBusy(root.dataset.busy === "1");
|
|
2403
|
+
};
|
|
2404
|
+
const nextPromptTool = {
|
|
2405
|
+
name: "suggest_next_prompt",
|
|
2406
|
+
description: "Offer the user their likely next message: it appears greyed in their input box and Tab sends it there. Call it only in the same reply as your final answer, after writing the answer, and only when an obvious next request follows (after writing a strategy: \"Backtest it over the last year\"). Write it as the user would type it — in the user's language, one short sentence, a request to you, nothing you already did. When no next step is clear, do not call it.",
|
|
2407
|
+
parameters: {
|
|
2408
|
+
type: "object",
|
|
2409
|
+
properties: { text: { type: "string", description: "The suggested message, as the user would type it" } },
|
|
2410
|
+
required: ["text"],
|
|
2411
|
+
additionalProperties: false,
|
|
2412
|
+
},
|
|
2413
|
+
readOnly: true,
|
|
2414
|
+
endsRun: true,
|
|
2415
|
+
display: { hidden: true },
|
|
2416
|
+
execute: ({ text }) => {
|
|
2417
|
+
pendingNext = String(text ?? "").replace(/\s+/g, " ").trim().slice(0, 200) || null;
|
|
2418
|
+
return "Shown to the user.";
|
|
2419
|
+
},
|
|
2420
|
+
};
|
|
2421
|
+
/** Every tool the chat's agents get: the host's, plus the built-in suggestion tool. */
|
|
2422
|
+
const chatTools = [...(agentOpts.tools ?? []), ...(nextPrompt ? [nextPromptTool] : [])];
|
|
2423
|
+
const hiddenTools = new Set(chatTools.filter((x) => x.display?.hidden).map((x) => x.name));
|
|
2424
|
+
/** Send is there only while idle with something to send (text, a file, context); steer and follow-up only while busy with something to send. */
|
|
2425
|
+
const syncSend = () => {
|
|
2426
|
+
const busy = root.dataset.busy === "1", any = !!(ta.value.trim() || pendingFiles.length || pendingContext.length);
|
|
2427
|
+
sendBtn.style.display = !busy && any ? "" : "none";
|
|
2428
|
+
steerBtn.style.display = fuBtn.style.display = busy && any ? "" : "none";
|
|
2429
|
+
};
|
|
2430
|
+
const setBusy = (busy) => {
|
|
2431
|
+
root.dataset.busy = busy ? "1" : "";
|
|
2432
|
+
ta.placeholder = busy ? fill(t.placeholderBusy) : (nextSuggestion ?? placeholder ?? t.placeholder);
|
|
2433
|
+
hint.textContent = fill(busy ? t.hintBusy : nextSuggestion ? t.hintNext : t.hintIdle);
|
|
2434
|
+
syncSend();
|
|
2435
|
+
stopBtn.style.display = busy ? "" : "none";
|
|
2436
|
+
renderQueue();
|
|
2437
|
+
};
|
|
2438
|
+
/** The queue above the composer: one message shows whole with its actions; several fold into "N queued · Next: …" (a click opens the list). */
|
|
2439
|
+
let queueOpen = false;
|
|
2440
|
+
const renderQueue = () => {
|
|
2441
|
+
const q = agent?.queued ?? [];
|
|
2442
|
+
queueEl.style.display = q.length ? "" : "none";
|
|
2443
|
+
queueEl.replaceChildren();
|
|
2444
|
+
if (!q.length) {
|
|
2445
|
+
queueOpen = false;
|
|
2446
|
+
return;
|
|
2447
|
+
}
|
|
2448
|
+
const a = agent;
|
|
2449
|
+
const textOf = (m) => textOfContent(m.content).replace(/\s*\[attachments\][\s\S]*$/, "").replace(/(^|\n)\[context\] [\s\S]*$/, "").replace(/\s+/g, " ").trim();
|
|
2450
|
+
const btn = (icon, title, fn) => { const b = h("button"); b.type = "button"; b.innerHTML = icon; b.title = title; b.setAttribute("aria-label", title); b.addEventListener("click", (e) => { e.stopPropagation(); fn(); }); return b; };
|
|
2451
|
+
const actions = (item) => {
|
|
2452
|
+
const box = h("span", "ra-qa");
|
|
2453
|
+
// Send now: a queued follow-up becomes a steer, inserted at the next step of the running task.
|
|
2454
|
+
if (item.kind !== "steer")
|
|
2455
|
+
box.append(btn(I.enter(), t.sendNow, () => { if (a.dequeue(item.message))
|
|
2456
|
+
a.steer(item.message.content); renderQueue(); }));
|
|
2457
|
+
box.append(btn(I.pen(), t.editQueued, () => {
|
|
2458
|
+
if (!a.dequeue(item.message))
|
|
2459
|
+
return;
|
|
2460
|
+
ta.value = ta.value.trim() ? `${textOf(item.message)}\n${ta.value}` : textOf(item.message);
|
|
2461
|
+
ta.focus();
|
|
2462
|
+
renderQueue();
|
|
2463
|
+
}));
|
|
2464
|
+
box.append(btn(I.x(14), t.remove, () => { a.dequeue(item.message); renderQueue(); }));
|
|
2465
|
+
return box;
|
|
2466
|
+
};
|
|
2467
|
+
const kindTag = (item) => (item.kind === "steer" ? h("span", "ra-qk", t.steer) : null);
|
|
2468
|
+
queueEl.classList.toggle("open", queueOpen && q.length > 1);
|
|
2469
|
+
if (q.length === 1) {
|
|
2470
|
+
const item = q[0];
|
|
2471
|
+
const row = h("div", "ra-qr");
|
|
2472
|
+
const tag = kindTag(item);
|
|
2473
|
+
row.append(h("span", "ra-qn", t.queuedN.replace("{n}", "1")));
|
|
2474
|
+
if (tag)
|
|
2475
|
+
row.append(tag);
|
|
2476
|
+
row.append(h("span", "ra-qt", textOf(item.message)), actions(item));
|
|
2477
|
+
queueEl.append(row);
|
|
2478
|
+
return;
|
|
2479
|
+
}
|
|
2480
|
+
const head = h("div", "ra-qr ra-qhd");
|
|
2481
|
+
const next = h("span", "ra-qt");
|
|
2482
|
+
if (!queueOpen) {
|
|
2483
|
+
next.append(h("b", "", t.queueNext));
|
|
2484
|
+
next.append(textOf(q[0].message));
|
|
2485
|
+
}
|
|
2486
|
+
const tog = h("span", "ra-qtog");
|
|
2487
|
+
tog.innerHTML = I.chevDown(14);
|
|
2488
|
+
tog.title = queueOpen ? t.collapse : t.expand;
|
|
2489
|
+
head.append(h("span", "ra-qn", t.queuedNs.replace("{n}", String(q.length))), next, tog);
|
|
2490
|
+
head.addEventListener("click", () => { queueOpen = !queueOpen; renderQueue(); });
|
|
2491
|
+
queueEl.append(head);
|
|
2492
|
+
if (queueOpen) {
|
|
2493
|
+
for (const item of q) {
|
|
2494
|
+
const row = h("div", "ra-qr");
|
|
2495
|
+
const tag = kindTag(item);
|
|
2496
|
+
if (tag)
|
|
2497
|
+
row.append(tag);
|
|
2498
|
+
row.append(h("span", "ra-qt", textOf(item.message)), actions(item));
|
|
2499
|
+
queueEl.append(row);
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
};
|
|
2503
|
+
const setAlert = (message) => { alertEl.style.display = message ? "" : "none"; alertEl.textContent = message ?? ""; };
|
|
2504
|
+
const refreshCommands = async () => {
|
|
2505
|
+
const ws = agent?.workspace;
|
|
2506
|
+
if (!ws) {
|
|
2507
|
+
commands = [];
|
|
2508
|
+
setSkillCount(0);
|
|
2509
|
+
return;
|
|
2510
|
+
}
|
|
2511
|
+
try {
|
|
2512
|
+
const [skills, templates] = await Promise.all([ws.skills(), listTemplates(ws)]);
|
|
2513
|
+
if (agent?.workspace === ws)
|
|
2514
|
+
setSkillCount(skills.length);
|
|
2515
|
+
commands = [
|
|
2516
|
+
...templates.map((p) => ({ name: p.name, description: p.description, kind: t.template })),
|
|
2517
|
+
...skills.map((s) => ({ name: `skill:${s.name}`, description: s.description, kind: t.skill })),
|
|
2518
|
+
];
|
|
2519
|
+
}
|
|
2520
|
+
catch {
|
|
2521
|
+
commands = [];
|
|
2522
|
+
setSkillCount(0);
|
|
2523
|
+
}
|
|
2524
|
+
};
|
|
2525
|
+
let cmdsDismissed = false;
|
|
2526
|
+
const currentSuggestions = () => {
|
|
2527
|
+
const v = ta.value;
|
|
2528
|
+
if (cmdsDismissed || !v.startsWith("/") || /\s/.test(v))
|
|
2529
|
+
return [];
|
|
2530
|
+
return [...builtinCommands(), ...commands].filter((c) => `/${c.name}`.startsWith(v)).slice(0, 40);
|
|
2531
|
+
};
|
|
2532
|
+
const renderCmds = () => {
|
|
2533
|
+
syncSend();
|
|
2534
|
+
const found = currentSuggestions();
|
|
2535
|
+
cmds.style.display = found.length ? "" : "none";
|
|
2536
|
+
cmds.replaceChildren();
|
|
2537
|
+
if (cmdIndex >= found.length)
|
|
2538
|
+
cmdIndex = 0;
|
|
2539
|
+
found.forEach((c, i) => {
|
|
2540
|
+
const b = h("button", i === cmdIndex ? "ra-cur" : "");
|
|
2541
|
+
b.type = "button";
|
|
2542
|
+
b.append(h("span", "ra-cn", `/${c.name}`));
|
|
2543
|
+
if (c.args)
|
|
2544
|
+
b.append(h("span", "ra-ca", c.args));
|
|
2545
|
+
b.append(h("span", "ra-badge", c.kind), h("span", "ra-cd", c.description));
|
|
2546
|
+
b.addEventListener("mousedown", (e) => { e.preventDefault(); pickCommand(c); ta.focus(); });
|
|
2547
|
+
cmds.append(b);
|
|
2548
|
+
if (i === cmdIndex)
|
|
2549
|
+
b.scrollIntoView?.({ block: "nearest" });
|
|
2550
|
+
});
|
|
2551
|
+
};
|
|
2552
|
+
// Typing only touches the popover, once per frame; the transcript and the box never change size.
|
|
2553
|
+
const scheduleCmds = () => { if (cmdFrame === null)
|
|
2554
|
+
cmdFrame = requestAnimationFrame(() => { cmdFrame = null; renderCmds(); }); };
|
|
2555
|
+
/* --- attachments --- */
|
|
2556
|
+
const pendingFiles = [];
|
|
2557
|
+
/** What the host put into the next message (addContext). */
|
|
2558
|
+
const pendingContext = [];
|
|
2559
|
+
const renderFiles = () => { files.style.display = pendingFiles.length || pendingContext.length ? "" : "none"; syncSend(); };
|
|
2560
|
+
const removeContext = (id) => {
|
|
2561
|
+
const i = pendingContext.findIndex((c) => c.id === id);
|
|
2562
|
+
if (i < 0)
|
|
2563
|
+
return;
|
|
2564
|
+
pendingContext[i].chip.remove();
|
|
2565
|
+
pendingContext.splice(i, 1);
|
|
2566
|
+
renderFiles();
|
|
2567
|
+
};
|
|
2568
|
+
const addContext = (item) => {
|
|
2569
|
+
const id = item.id ?? `ctx_${Math.random().toString(36).slice(2, 8)}`;
|
|
2570
|
+
removeContext(id);
|
|
2571
|
+
// One line: the sent message names the item by its first line.
|
|
2572
|
+
item = { ...item, label: item.label.replace(/\s+/g, " ").trim() || "context" };
|
|
2573
|
+
const chip = contextChip(item.label, item.title, item.icon);
|
|
2574
|
+
const x = h("button");
|
|
2575
|
+
x.type = "button";
|
|
2576
|
+
x.innerHTML = I.x();
|
|
2577
|
+
x.title = t.remove;
|
|
2578
|
+
x.setAttribute("aria-label", t.remove);
|
|
2579
|
+
x.addEventListener("click", () => removeContext(id));
|
|
2580
|
+
chip.append(x);
|
|
2581
|
+
pendingContext.push({ id, label: item.label, text: item.text, chip });
|
|
2582
|
+
files.prepend(chip);
|
|
2583
|
+
renderFiles();
|
|
2584
|
+
return () => removeContext(id);
|
|
2585
|
+
};
|
|
2586
|
+
const removeFile = (a) => { const i = pendingFiles.indexOf(a); if (i >= 0)
|
|
2587
|
+
pendingFiles.splice(i, 1); if (a.preview)
|
|
2588
|
+
URL.revokeObjectURL(a.preview); a.chip.remove(); renderFiles(); };
|
|
2589
|
+
// Files are read before they join the message: a send waits for the ones still being read (attach, then Enter at once).
|
|
2590
|
+
let reading = Promise.resolve();
|
|
2591
|
+
const addFiles = (list, paths = []) => {
|
|
2592
|
+
// Copied now: the picker's list is emptied as soon as this returns.
|
|
2593
|
+
const files = list ? Array.from(list) : [];
|
|
2594
|
+
const run = reading.then(() => readFiles(files, paths));
|
|
2595
|
+
reading = run.catch(() => undefined);
|
|
2596
|
+
return run;
|
|
2597
|
+
};
|
|
2598
|
+
const readFiles = async (list, paths) => {
|
|
2599
|
+
if (attachOpt === false || !list?.length)
|
|
2600
|
+
return;
|
|
2601
|
+
for (const [i, file] of Array.from(list).entries()) {
|
|
2602
|
+
if (file.size > MAX_ATTACHMENT) {
|
|
2603
|
+
ui.notify(`${file.name} ${t.tooLarge}`, "warning");
|
|
2604
|
+
continue;
|
|
2605
|
+
}
|
|
2606
|
+
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
2607
|
+
const image = /^image\/(png|jpe?g|gif|webp)$/.test(file.type);
|
|
2608
|
+
const text = image ? null : decodeText(file, bytes);
|
|
2609
|
+
const preview = image ? URL.createObjectURL(file) : null;
|
|
2610
|
+
const chip = chipEl(safeName(file.name), fmtSize(file.size), preview);
|
|
2611
|
+
const x = h("button");
|
|
2612
|
+
x.type = "button";
|
|
2613
|
+
x.innerHTML = I.x();
|
|
2614
|
+
x.title = t.remove;
|
|
2615
|
+
x.setAttribute("aria-label", t.remove);
|
|
2616
|
+
chip.append(x);
|
|
2617
|
+
const a = { file, name: safeName(file.name), bytes, text, image, preview, chip, path: paths[i] };
|
|
2618
|
+
x.addEventListener("click", () => removeFile(a));
|
|
2619
|
+
pendingFiles.push(a);
|
|
2620
|
+
files.append(chip);
|
|
2621
|
+
}
|
|
2622
|
+
renderFiles();
|
|
2623
|
+
ta.focus();
|
|
2624
|
+
};
|
|
2625
|
+
attachBtn.addEventListener("click", () => fileInput.click());
|
|
2626
|
+
fileInput.addEventListener("change", () => { void addFiles(fileInput.files); fileInput.value = ""; });
|
|
2627
|
+
ta.addEventListener("paste", (e) => {
|
|
2628
|
+
const items = Array.from(e.clipboardData?.files ?? []);
|
|
2629
|
+
// Office apps put a picture of the selection next to its text: the text is what was meant.
|
|
2630
|
+
if (!items.length || e.clipboardData?.getData("text/plain"))
|
|
2631
|
+
return;
|
|
2632
|
+
e.preventDefault();
|
|
2633
|
+
void addFiles(items);
|
|
2634
|
+
});
|
|
2635
|
+
let dragDepth = 0;
|
|
2636
|
+
root.addEventListener("dragenter", (e) => { if (attachOpt === false || !e.dataTransfer?.types.includes("Files"))
|
|
2637
|
+
return; e.preventDefault(); dragDepth++; root.dataset.drop = "1"; });
|
|
2638
|
+
root.addEventListener("dragover", (e) => { if (root.dataset.drop) {
|
|
2639
|
+
e.preventDefault();
|
|
2640
|
+
e.dataTransfer.dropEffect = "copy";
|
|
2641
|
+
} });
|
|
2642
|
+
root.addEventListener("dragleave", () => { if (root.dataset.drop && --dragDepth <= 0) {
|
|
2643
|
+
dragDepth = 0;
|
|
2644
|
+
delete root.dataset.drop;
|
|
2645
|
+
} });
|
|
2646
|
+
root.addEventListener("drop", (e) => { if (!root.dataset.drop)
|
|
2647
|
+
return; e.preventDefault(); dragDepth = 0; delete root.dataset.drop; void addFiles(e.dataTransfer?.files); });
|
|
2648
|
+
/** The message to send: the text, the attachment list (saved to the directory, or inlined), and pictures for the model. */
|
|
2649
|
+
const buildContent = async (text, taken, target) => {
|
|
2650
|
+
if (!taken.length)
|
|
2651
|
+
return text;
|
|
2652
|
+
// Saved as files only when the model has file tools to read them; otherwise they go into the message.
|
|
2653
|
+
const ws = agentOpts.fileTools === false ? null : target.workspace;
|
|
2654
|
+
const lines = [];
|
|
2655
|
+
const parts = [];
|
|
2656
|
+
// A model known not to see pictures gets none: they are kept as files, and the user is told.
|
|
2657
|
+
const blind = taken.some((a) => a.image) && (await target.accepts("image")) === false;
|
|
2658
|
+
// A video goes to a model that takes video (or may: the catalogue does not say), inline like a picture.
|
|
2659
|
+
const isVideo = (a) => /^video\//.test(a.file.type) && a.file.size <= MAX_VIDEO_PART;
|
|
2660
|
+
const seesVideo = taken.some(isVideo) && (await target.accepts("video")) !== false;
|
|
2661
|
+
if (blind)
|
|
2662
|
+
ui.notify(t.noVision.replace("{model}", target.model || (await target.modelInfo())?.id || t.sDefault), "warning");
|
|
2663
|
+
for (const a of taken) {
|
|
2664
|
+
const type = a.file.type || (a.text !== null ? "text/plain" : "application/octet-stream");
|
|
2665
|
+
if (ws) {
|
|
2666
|
+
const path = a.path && (await ws.exists(a.path)) ? a.path : await freePath(ws, uploadsDir, a.name);
|
|
2667
|
+
if (path !== a.path)
|
|
2668
|
+
await ws.write(path, a.text ?? a.bytes, type);
|
|
2669
|
+
lines.push(`- ${path} (${type}, ${fmtSize(a.file.size)})`);
|
|
2670
|
+
void panel.refresh();
|
|
2671
|
+
}
|
|
2672
|
+
else if (isPdf(a.name, a.file.type, a.bytes)) {
|
|
2673
|
+
// No directory to save it in: its text goes in the message (pdf.js, loaded now).
|
|
2674
|
+
let text = "";
|
|
2675
|
+
try {
|
|
2676
|
+
text = formatPdfText(a.name, await extractPdfText(a.bytes));
|
|
2677
|
+
}
|
|
2678
|
+
catch (err) {
|
|
2679
|
+
text = `Could not read the PDF: ${err.message}`;
|
|
2680
|
+
}
|
|
2681
|
+
if (text.length > MAX_INLINE_TEXT)
|
|
2682
|
+
text = text.slice(0, MAX_INLINE_TEXT) + "\n[… truncated]";
|
|
2683
|
+
lines.push(`- ${a.name} (${type}, ${fmtSize(a.file.size)}) — its text below`);
|
|
2684
|
+
parts.push({ type: "text", text: `<file name="${a.name}">\n${text}\n</file>` });
|
|
2685
|
+
}
|
|
2686
|
+
else if (a.text !== null && a.text.length <= MAX_INLINE_TEXT) {
|
|
2687
|
+
lines.push(`- ${a.name} (${type}, ${fmtSize(a.file.size)}) — contents below`);
|
|
2688
|
+
parts.push({ type: "text", text: `<file name="${a.name}">\n${a.text}\n</file>` });
|
|
2689
|
+
}
|
|
2690
|
+
else
|
|
2691
|
+
lines.push(`- ${a.name} (${type}, ${fmtSize(a.file.size)}) — ${a.image && !blind ? "the picture below" : isVideo(a) && seesVideo ? "the video below" : "not readable here"}`);
|
|
2692
|
+
if (isVideo(a) && seesVideo) {
|
|
2693
|
+
const b64 = await new Promise((res) => { const r = new FileReader(); r.onload = () => res(String(r.result)); r.readAsDataURL(a.file); });
|
|
2694
|
+
parts.push({ type: "video_url", video_url: { url: b64 } });
|
|
2695
|
+
}
|
|
2696
|
+
if (a.image && !blind && a.file.size <= MAX_IMAGE_PART) {
|
|
2697
|
+
const b64 = await new Promise((res) => { const r = new FileReader(); r.onload = () => res(String(r.result)); r.readAsDataURL(a.file); });
|
|
2698
|
+
parts.push({ type: "image_url", image_url: { url: b64 } });
|
|
2699
|
+
}
|
|
2700
|
+
}
|
|
2701
|
+
const note = ws ? `${ATTACH_MARK} files the user attached, saved in the directory (read them with read_file):` : `${ATTACH_MARK} files the user attached:`;
|
|
2702
|
+
const content = [];
|
|
2703
|
+
if (text)
|
|
2704
|
+
content.push({ type: "text", text });
|
|
2705
|
+
content.push({ type: "text", text: `${note}\n${lines.join("\n")}` });
|
|
2706
|
+
content.push(...parts);
|
|
2707
|
+
return content;
|
|
2708
|
+
};
|
|
2709
|
+
let sending = false;
|
|
2710
|
+
const send = async (mode) => {
|
|
2711
|
+
await reading;
|
|
2712
|
+
const text = ta.value.trim();
|
|
2713
|
+
if ((!text && !pendingFiles.length && !pendingContext.length) || !agent || sending)
|
|
2714
|
+
return;
|
|
2715
|
+
clearNext();
|
|
2716
|
+
if (runBuiltin(text))
|
|
2717
|
+
return;
|
|
2718
|
+
// While compacting, a message waits for it and then runs (Enter, Steer and Follow-up alike).
|
|
2719
|
+
if (compacting)
|
|
2720
|
+
mode = "followUp";
|
|
2721
|
+
const a = agent;
|
|
2722
|
+
// The files are taken now, so a second Enter while they are being written cannot send them again.
|
|
2723
|
+
const taken = pendingFiles.splice(0);
|
|
2724
|
+
for (const f of taken)
|
|
2725
|
+
f.chip.remove();
|
|
2726
|
+
const takenCtx = pendingContext.splice(0);
|
|
2727
|
+
for (const c of takenCtx)
|
|
2728
|
+
c.chip.remove();
|
|
2729
|
+
renderFiles();
|
|
2730
|
+
ta.value = "";
|
|
2731
|
+
renderCmds();
|
|
2732
|
+
setAlert();
|
|
2733
|
+
sending = true;
|
|
2734
|
+
let content;
|
|
2735
|
+
try {
|
|
2736
|
+
content = await buildContent(text, taken, a);
|
|
2737
|
+
// The host's context goes right after the typed text, one part each.
|
|
2738
|
+
if (takenCtx.length) {
|
|
2739
|
+
const parts = typeof content === "string" ? (content ? [{ type: "text", text: content }] : []) : content;
|
|
2740
|
+
const at = parts.length && parts[0].type === "text" && !parts[0].text.startsWith(ATTACH_MARK) ? 1 : 0;
|
|
2741
|
+
parts.splice(at, 0, ...takenCtx.map((c) => ({ type: "text", text: `${CONTEXT_MARK}${c.label}\n${c.text}` })));
|
|
2742
|
+
content = parts;
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
catch (err) {
|
|
2746
|
+
// Nothing was sent: the text, the files and the context go back where they were.
|
|
2747
|
+
ta.value = text;
|
|
2748
|
+
pendingFiles.unshift(...taken);
|
|
2749
|
+
for (const f of taken.slice().reverse())
|
|
2750
|
+
files.prepend(f.chip);
|
|
2751
|
+
pendingContext.unshift(...takenCtx);
|
|
2752
|
+
for (const c of takenCtx.slice().reverse())
|
|
2753
|
+
files.prepend(c.chip);
|
|
2754
|
+
renderFiles();
|
|
2755
|
+
setAlert(err.message);
|
|
2756
|
+
return;
|
|
2757
|
+
}
|
|
2758
|
+
finally {
|
|
2759
|
+
sending = false;
|
|
2760
|
+
}
|
|
2761
|
+
for (const f of taken)
|
|
2762
|
+
if (f.preview)
|
|
2763
|
+
URL.revokeObjectURL(f.preview);
|
|
2764
|
+
if (!a.busy)
|
|
2765
|
+
mode = "prompt";
|
|
2766
|
+
try {
|
|
2767
|
+
if (mode === "prompt") {
|
|
2768
|
+
// Drawn now; the agent's run_start hands this row its message.
|
|
2769
|
+
if (agent === a && !a.busy)
|
|
2770
|
+
awaitingRow = addUser(content);
|
|
2771
|
+
await a.prompt(content);
|
|
2772
|
+
return;
|
|
2773
|
+
}
|
|
2774
|
+
if (mode === "steer")
|
|
2775
|
+
a.steer(content);
|
|
2776
|
+
else
|
|
2777
|
+
void a.followUp(content).catch(() => undefined);
|
|
2778
|
+
renderQueue();
|
|
2779
|
+
}
|
|
2780
|
+
catch (err) {
|
|
2781
|
+
awaitingRow = null;
|
|
2782
|
+
setAlert(err.message);
|
|
2783
|
+
}
|
|
2784
|
+
};
|
|
2785
|
+
ta.addEventListener("input", () => { cmdsDismissed = false; if (ta.value)
|
|
2786
|
+
clearNext(); syncSend(); scheduleCmds(); });
|
|
2787
|
+
ta.addEventListener("keydown", (e) => {
|
|
2788
|
+
// Confirming a word in an input method is not sending (Safari reports it with keyCode 229).
|
|
2789
|
+
if (e.isComposing || e.keyCode === 229)
|
|
2790
|
+
return;
|
|
2791
|
+
const found = currentSuggestions();
|
|
2792
|
+
if (found.length) {
|
|
2793
|
+
if (e.key === "ArrowDown") {
|
|
2794
|
+
e.preventDefault();
|
|
2795
|
+
cmdIndex = (cmdIndex + 1) % found.length;
|
|
2796
|
+
renderCmds();
|
|
2797
|
+
return;
|
|
2798
|
+
}
|
|
2799
|
+
if (e.key === "ArrowUp") {
|
|
2800
|
+
e.preventDefault();
|
|
2801
|
+
cmdIndex = (cmdIndex - 1 + found.length) % found.length;
|
|
2802
|
+
renderCmds();
|
|
2803
|
+
return;
|
|
2804
|
+
}
|
|
2805
|
+
if (e.key === "Tab") {
|
|
2806
|
+
e.preventDefault();
|
|
2807
|
+
ta.value = `/${found[cmdIndex].name} `;
|
|
2808
|
+
renderCmds();
|
|
2809
|
+
return;
|
|
2810
|
+
}
|
|
2811
|
+
if (e.key === "Enter" && !e.shiftKey) {
|
|
2812
|
+
e.preventDefault();
|
|
2813
|
+
pickCommand(found[cmdIndex]);
|
|
2814
|
+
return;
|
|
2815
|
+
}
|
|
2816
|
+
if (e.key === "Escape") {
|
|
2817
|
+
cmdsDismissed = true;
|
|
2818
|
+
cmds.style.display = "none";
|
|
2819
|
+
return;
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
// The suggested next message: Tab puts it in the empty input, Esc drops it.
|
|
2823
|
+
if (nextSuggestion && !ta.value && e.key === "Tab" && !e.shiftKey) {
|
|
2824
|
+
e.preventDefault();
|
|
2825
|
+
ta.value = nextSuggestion;
|
|
2826
|
+
clearNext();
|
|
2827
|
+
syncSend();
|
|
2828
|
+
return;
|
|
2829
|
+
}
|
|
2830
|
+
if (nextSuggestion && !ta.value && e.key === "Escape") {
|
|
2831
|
+
clearNext();
|
|
2832
|
+
return;
|
|
2833
|
+
}
|
|
2834
|
+
if (e.key !== "Enter" || e.shiftKey)
|
|
2835
|
+
return;
|
|
2836
|
+
e.preventDefault();
|
|
2837
|
+
// ⌘↵ on a Mac, Ctrl+↵ elsewhere queues a follow-up while the agent runs. Both modifiers are accepted
|
|
2838
|
+
// everywhere (⊞↵ too, when Windows lets the browser see it — the OS binds Win+Enter to Narrator); Alt+↵ still works.
|
|
2839
|
+
const queueKey = e.metaKey || e.ctrlKey || e.altKey;
|
|
2840
|
+
void send(agent?.busy ? (queueKey ? "followUp" : "steer") : "prompt");
|
|
2841
|
+
});
|
|
2842
|
+
ta.addEventListener("blur", () => { cmds.style.display = "none"; });
|
|
2843
|
+
ta.addEventListener("focus", () => renderCmds());
|
|
2844
|
+
sendBtn.addEventListener("click", () => void send("prompt"));
|
|
2845
|
+
steerBtn.addEventListener("click", () => void send("steer"));
|
|
2846
|
+
fuBtn.addEventListener("click", () => void send("followUp"));
|
|
2847
|
+
stopBtn.addEventListener("click", () => { ui.cancelAll(); void agent?.abort(); });
|
|
2848
|
+
log.addEventListener("click", (e) => {
|
|
2849
|
+
const target = e.target;
|
|
2850
|
+
// The app's own links first (onLink).
|
|
2851
|
+
const link = onLink ? target.closest("a[href]") : null;
|
|
2852
|
+
if (link && onLink) {
|
|
2853
|
+
let handled = false;
|
|
2854
|
+
try {
|
|
2855
|
+
handled = onLink(link.getAttribute("href") ?? "", link.textContent ?? "") === true;
|
|
2856
|
+
}
|
|
2857
|
+
catch (err) {
|
|
2858
|
+
console.warn("agent: onLink failed", err);
|
|
2859
|
+
}
|
|
2860
|
+
if (handled) {
|
|
2861
|
+
e.preventDefault();
|
|
2862
|
+
return;
|
|
2863
|
+
}
|
|
2864
|
+
}
|
|
2865
|
+
const pathEl = target.closest(".ra-path");
|
|
2866
|
+
if (pathEl?.dataset.path) {
|
|
2867
|
+
e.preventDefault();
|
|
2868
|
+
openPath(pathEl.dataset.path);
|
|
2869
|
+
return;
|
|
2870
|
+
}
|
|
2871
|
+
const a = target.closest(".ra-md a[href]");
|
|
2872
|
+
if (a && agent?.workspace) {
|
|
2873
|
+
const href = a.getAttribute("href") ?? "";
|
|
2874
|
+
if (href.startsWith("/") && !href.startsWith("//")) {
|
|
2875
|
+
e.preventDefault();
|
|
2876
|
+
const ws = agent.workspace;
|
|
2877
|
+
void ws.exists(href).then((ok) => { if (ok)
|
|
2878
|
+
openPath(href);
|
|
2879
|
+
else
|
|
2880
|
+
window.open(a.href, "_blank", "noopener"); });
|
|
2881
|
+
return;
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
});
|
|
2885
|
+
const SET_KEY = `__runapps_agent_chat:${project}:settings`;
|
|
2886
|
+
const readSettings = () => { try {
|
|
2887
|
+
return JSON.parse(localStorage.getItem(SET_KEY) || "{}");
|
|
2888
|
+
}
|
|
2889
|
+
catch {
|
|
2890
|
+
return {};
|
|
2891
|
+
} };
|
|
2892
|
+
const writeSettings = (v) => { try {
|
|
2893
|
+
if (Object.keys(v).length)
|
|
2894
|
+
localStorage.setItem(SET_KEY, JSON.stringify(v));
|
|
2895
|
+
else
|
|
2896
|
+
localStorage.removeItem(SET_KEY);
|
|
2897
|
+
}
|
|
2898
|
+
catch { /* private mode */ } };
|
|
2899
|
+
let userSettings = givenAgent ? {} : readSettings();
|
|
2900
|
+
let permChoice = null; // not persisted: allowing everything is a per-page decision
|
|
2901
|
+
const hasSettings = opts.settings ?? !givenAgent;
|
|
2902
|
+
let settingsTab = 0;
|
|
2903
|
+
if (!hasSettings)
|
|
2904
|
+
setBtn.style.display = "none";
|
|
2905
|
+
let modelsCache = null;
|
|
2906
|
+
/** The thinking levels a model offers (`options.inputs.reasoning_effort`), or null when it has none. */
|
|
2907
|
+
const effortOf = (m) => {
|
|
2908
|
+
const f = m?.options?.inputs?.reasoning_effort;
|
|
2909
|
+
if (!f)
|
|
2910
|
+
return null;
|
|
2911
|
+
const levels = (f.enum ?? []).filter((v) => typeof v === "string");
|
|
2912
|
+
return levels.length ? { levels, def: typeof f.default === "string" ? f.default : undefined } : null;
|
|
2913
|
+
};
|
|
2914
|
+
/** Puts the user's settings on an agent (every open session gets the same ones). */
|
|
2915
|
+
const applyTo = (ag, s, p) => {
|
|
2916
|
+
const hostEffort = agentOpts.extra?.reasoning_effort;
|
|
2917
|
+
ag.configure({ model: s.model ?? agentOpts.model, maxTurns: s.maxTurns ?? agentOpts.maxTurns ?? 100, maxTokens: s.maxTokens ?? (typeof agentOpts.maxTokens === "number" ? agentOpts.maxTokens : "auto"), permissions: p ?? agentOpts.permissions ?? "ask", reasoningEffort: s.reasoningEffort ?? (typeof hostEffort === "string" ? hostEffort : null) });
|
|
2918
|
+
modelEl.textContent = ag.model ?? "";
|
|
2919
|
+
modelEl.style.display = ag.model ? "" : "none";
|
|
2920
|
+
};
|
|
2921
|
+
const saveSettings = (next) => { userSettings = next; writeSettings(next); for (const ag of live.values())
|
|
2922
|
+
applyTo(ag, next, permChoice); showUsage_(agent); };
|
|
2923
|
+
const loadModels = async () => {
|
|
2924
|
+
if (provider?.models) {
|
|
2925
|
+
try {
|
|
2926
|
+
modelsCache ??= (await provider.models()).filter((m) => !m.capability || m.capability === "text" || m.capability === "vision");
|
|
2927
|
+
}
|
|
2928
|
+
catch { /* no catalogue */ }
|
|
2929
|
+
}
|
|
2930
|
+
return modelsCache ?? [];
|
|
2931
|
+
};
|
|
2932
|
+
// A model chosen earlier that the catalogue no longer lists (the host removed it) is forgotten: the default applies again.
|
|
2933
|
+
if (userSettings.model && provider?.models) {
|
|
2934
|
+
void loadModels().then((list) => {
|
|
2935
|
+
if (!list.length || !userSettings.model || list.some((m) => m.id === userSettings.model))
|
|
2936
|
+
return;
|
|
2937
|
+
const { model: _gone, ...rest } = userSettings;
|
|
2938
|
+
saveSettings(rest);
|
|
2939
|
+
});
|
|
2940
|
+
}
|
|
2941
|
+
const kTok = (n) => (typeof n === "number" ? (n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)) : "?");
|
|
2942
|
+
/** The model's price as one line ("" when the catalogue gives none). */
|
|
2943
|
+
const priceOf = (m) => {
|
|
2944
|
+
const p = m?.price;
|
|
2945
|
+
if (!p || (p.input === undefined && p.output === undefined))
|
|
2946
|
+
return "";
|
|
2947
|
+
const line = t.sPriceLine.replace("{in}", fmtPrice(p.input ?? 0, p.currency)).replace("{out}", fmtPrice(p.output ?? 0, p.currency));
|
|
2948
|
+
return p.per_call ? `${line} · ${t.sPerCall.replace("{amount}", fmtPrice(p.per_call, p.currency))}` : line;
|
|
2949
|
+
};
|
|
2950
|
+
const openSettings = async () => {
|
|
2951
|
+
if (menu) {
|
|
2952
|
+
closeMenu();
|
|
2953
|
+
return;
|
|
2954
|
+
}
|
|
2955
|
+
if (!agent)
|
|
2956
|
+
return;
|
|
2957
|
+
const a = agent;
|
|
2958
|
+
// This menu's own reference: another menu opened while the catalogue loads replaces it.
|
|
2959
|
+
const mine = h("div", "ra-menu ra-set");
|
|
2960
|
+
menu = mine;
|
|
2961
|
+
placeMenu(mine);
|
|
2962
|
+
const cur = a.settings;
|
|
2963
|
+
const sel = (options, value) => { const b = selectBox(root, { options, value, filterLabel: t.filter }); menuSelects.push(b); return b; };
|
|
2964
|
+
const modelSel = sel([{ value: "", label: t.sDefault }], "");
|
|
2965
|
+
const lim = h("div", "ra-lim");
|
|
2966
|
+
const effortSel = sel([], "");
|
|
2967
|
+
const effortNote = h("div", "ra-lim");
|
|
2968
|
+
const chosenModel = () => { const id = modelSel.value || modelsCache?.find((m) => m.is_default)?.id; return modelsCache?.find((x) => x.id === id); };
|
|
2969
|
+
const showLim = () => {
|
|
2970
|
+
const m = chosenModel();
|
|
2971
|
+
const sees = modelAccepts(m, "image");
|
|
2972
|
+
const price = priceOf(m);
|
|
2973
|
+
lim.textContent = m ? `${t.context} ${kTok(m.max_input_tokens)} · ${t.sMaxTokens} ${kTok(m.max_tokens)}${sees === undefined ? "" : ` · ${sees ? t.sVisionYes : t.sVisionNo}`}${price ? ` · ${t.sPrice}: ${price}` : ""}` : "";
|
|
2974
|
+
// Thinking levels follow the model: the list is the catalogue's, the first entry its default.
|
|
2975
|
+
const eff = effortOf(m);
|
|
2976
|
+
const keep = effortSel.value;
|
|
2977
|
+
effortSel.setOptions([{ value: "", label: t.sEffortDefault, note: eff?.def }, ...(eff?.levels ?? []).map((l) => ({ value: l, label: l }))]);
|
|
2978
|
+
effortSel.disabled = !eff;
|
|
2979
|
+
effortSel.value = eff && eff.levels.includes(keep) ? keep : "";
|
|
2980
|
+
effortNote.textContent = eff ? "" : t.sEffortNone;
|
|
2981
|
+
effortNote.style.display = eff ? "none" : "";
|
|
2982
|
+
};
|
|
2983
|
+
modelSel.el.addEventListener("change", showLim);
|
|
2984
|
+
const modelOpts = [];
|
|
2985
|
+
if (provider?.models) {
|
|
2986
|
+
await loadModels();
|
|
2987
|
+
if (menu !== mine)
|
|
2988
|
+
return;
|
|
2989
|
+
const def = modelsCache?.find((m) => m.is_default);
|
|
2990
|
+
// The platform default names the model it is; each model shows its context / output limits.
|
|
2991
|
+
modelOpts.push({ value: "", label: t.sDefault, note: def?.id });
|
|
2992
|
+
// A model that sees pictures says so next to its limits.
|
|
2993
|
+
// Each model: whether it sees pictures, its context / output limits and its price (input / output per M tokens).
|
|
2994
|
+
for (const m of modelsCache ?? []) {
|
|
2995
|
+
const p = m.price, price = p && (p.input !== undefined || p.output !== undefined) ? ` · ${fmtPrice(p.input ?? 0, p.currency)} / ${fmtPrice(p.output ?? 0, p.currency)}` : "";
|
|
2996
|
+
modelOpts.push({ value: m.id, label: m.id, note: `${modelAccepts(m, "image") ? `${t.sVision} · ` : ""}${kTok(m.max_input_tokens)} / ${kTok(m.max_tokens)}${price}` });
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
else
|
|
3000
|
+
modelOpts.push({ value: "", label: t.sDefault });
|
|
3001
|
+
if (cur.model && !modelOpts.some((o) => o.value === cur.model))
|
|
3002
|
+
modelOpts.push({ value: cur.model, label: cur.model });
|
|
3003
|
+
modelSel.setOptions(modelOpts);
|
|
3004
|
+
modelSel.value = cur.model ?? "";
|
|
3005
|
+
showLim();
|
|
3006
|
+
if (cur.reasoningEffort && effortSel.options.some((o) => o.value === cur.reasoningEffort))
|
|
3007
|
+
effortSel.value = cur.reasoningEffort;
|
|
3008
|
+
const turns = h("input");
|
|
3009
|
+
turns.type = "number";
|
|
3010
|
+
turns.min = "1";
|
|
3011
|
+
turns.max = "1000";
|
|
3012
|
+
turns.step = "1";
|
|
3013
|
+
turns.value = String(cur.maxTurns);
|
|
3014
|
+
const tokMode = sel([{ value: "auto", label: t.sAuto }, { value: "n", label: t.sCustomN }], "auto");
|
|
3015
|
+
const tokN = h("input");
|
|
3016
|
+
tokN.type = "number";
|
|
3017
|
+
tokN.min = "256";
|
|
3018
|
+
tokN.step = "256";
|
|
3019
|
+
tokN.value = String(typeof cur.maxTokens === "number" ? cur.maxTokens : 8192);
|
|
3020
|
+
tokMode.value = typeof cur.maxTokens === "number" ? "n" : "auto";
|
|
3021
|
+
tokN.style.display = tokMode.value === "n" ? "" : "none";
|
|
3022
|
+
tokMode.el.addEventListener("change", () => { tokN.style.display = tokMode.value === "n" ? "" : "none"; });
|
|
3023
|
+
const perm = sel([{ value: "ask", label: t.sAsk }, { value: "auto", label: t.sAutoPerm }, ...(cur.permissions === "custom" ? [{ value: "custom", label: t.sCustom }] : [])], cur.permissions);
|
|
3024
|
+
const field = (label, ...els) => { const l = h("div", "ra-fld"); l.append(h("span", "", label), ...els); return l; };
|
|
3025
|
+
const tokRow = h("div", "ra-row");
|
|
3026
|
+
tokRow.append(tokMode.el, tokN);
|
|
3027
|
+
const own = h("div", "ra-pane");
|
|
3028
|
+
own.append(field(t.sModel, modelSel.el), lim, field(t.sEffort, effortSel.el), effortNote, field(t.sMaxTurns, turns), field(t.sMaxTokens, tokRow));
|
|
3029
|
+
if (permissionsSetting !== false)
|
|
3030
|
+
own.append(field(t.sPerms, perm.el));
|
|
3031
|
+
// The host's own settings, each tab a pane: drawn here, read back on Apply.
|
|
3032
|
+
const hostReads = [];
|
|
3033
|
+
const hostPane = (tab) => {
|
|
3034
|
+
const pane = h("div", "ra-pane");
|
|
3035
|
+
for (const f of tab.fields) {
|
|
3036
|
+
if (f instanceof HTMLElement) {
|
|
3037
|
+
f.classList.add("ra-host");
|
|
3038
|
+
pane.append(f);
|
|
3039
|
+
continue;
|
|
3040
|
+
}
|
|
3041
|
+
if (f.type === "toggle") {
|
|
3042
|
+
const row = h("label", "ra-tgl");
|
|
3043
|
+
const box = h("input");
|
|
3044
|
+
box.type = "checkbox";
|
|
3045
|
+
box.checked = f.value();
|
|
3046
|
+
const text = h("span", "", f.label);
|
|
3047
|
+
if (f.hint)
|
|
3048
|
+
text.append(h("small", "", f.hint));
|
|
3049
|
+
row.append(box, text);
|
|
3050
|
+
pane.append(row);
|
|
3051
|
+
hostReads.push(() => { if (box.checked !== f.value())
|
|
3052
|
+
f.onChange(box.checked); });
|
|
3053
|
+
}
|
|
3054
|
+
else {
|
|
3055
|
+
const b = sel(f.options, f.value());
|
|
3056
|
+
const fl = field(f.label, b.el);
|
|
3057
|
+
if (f.hint)
|
|
3058
|
+
fl.append(h("small", "", f.hint));
|
|
3059
|
+
pane.append(fl);
|
|
3060
|
+
hostReads.push(() => { if (b.value !== f.value())
|
|
3061
|
+
f.onChange(b.value); });
|
|
3062
|
+
}
|
|
3063
|
+
}
|
|
3064
|
+
return pane;
|
|
3065
|
+
};
|
|
3066
|
+
const panes = [own, ...(settingsTabs ?? []).map(hostPane)];
|
|
3067
|
+
if (panes.length > 1) {
|
|
3068
|
+
// Tabs: the chat's own first, then the host's; the panel reopens on the tab last shown.
|
|
3069
|
+
const bar = h("div", "ra-tabs");
|
|
3070
|
+
bar.setAttribute("role", "tablist");
|
|
3071
|
+
const tabs = [t.sTabModel, ...(settingsTabs ?? []).map((x) => x.label)].map((label, i) => {
|
|
3072
|
+
const b = h("button", "ra-tab", label);
|
|
3073
|
+
b.type = "button";
|
|
3074
|
+
b.setAttribute("role", "tab");
|
|
3075
|
+
b.addEventListener("click", () => show(i));
|
|
3076
|
+
return b;
|
|
3077
|
+
});
|
|
3078
|
+
const show = (i) => {
|
|
3079
|
+
settingsTab = i;
|
|
3080
|
+
panes.forEach((p, j) => { p.hidden = j !== i; });
|
|
3081
|
+
tabs.forEach((b, j) => { b.classList.toggle("on", j === i); b.setAttribute("aria-selected", String(j === i)); });
|
|
3082
|
+
};
|
|
3083
|
+
bar.append(...tabs);
|
|
3084
|
+
menu.append(bar, ...panes);
|
|
3085
|
+
show(Math.min(settingsTab, panes.length - 1));
|
|
3086
|
+
}
|
|
3087
|
+
else
|
|
3088
|
+
menu.append(own);
|
|
3089
|
+
const btns = h("div", "ra-btns");
|
|
3090
|
+
const resetB = h("button", "ra-btn xs ghost", t.reset);
|
|
3091
|
+
resetB.type = "button";
|
|
3092
|
+
const applyB = h("button", "ra-btn xs solid", t.apply);
|
|
3093
|
+
applyB.type = "button";
|
|
3094
|
+
btns.append(resetB, applyB);
|
|
3095
|
+
menu.append(btns);
|
|
3096
|
+
resetB.addEventListener("click", () => {
|
|
3097
|
+
for (const f of (settingsTabs ?? []).flatMap((x) => x.fields)) {
|
|
3098
|
+
if (f instanceof HTMLElement || f.default === undefined)
|
|
3099
|
+
continue;
|
|
3100
|
+
if (f.type === "toggle") {
|
|
3101
|
+
if (f.value() !== f.default)
|
|
3102
|
+
f.onChange(f.default);
|
|
3103
|
+
}
|
|
3104
|
+
else if (f.value() !== f.default)
|
|
3105
|
+
f.onChange(f.default);
|
|
3106
|
+
}
|
|
3107
|
+
userSettings = {};
|
|
3108
|
+
writeSettings({});
|
|
3109
|
+
permChoice = null;
|
|
3110
|
+
for (const ag of live.values())
|
|
3111
|
+
applyTo(ag, {}, null);
|
|
3112
|
+
closeMenu();
|
|
3113
|
+
ui.notify(t.applied);
|
|
3114
|
+
showUsage_(agent);
|
|
3115
|
+
});
|
|
3116
|
+
applyB.addEventListener("click", () => {
|
|
3117
|
+
const next = {};
|
|
3118
|
+
if (modelSel.value)
|
|
3119
|
+
next.model = modelSel.value;
|
|
3120
|
+
// Saved only when it differs from the app's default, so a later change of that default still reaches this user.
|
|
3121
|
+
const n = parseInt(turns.value, 10);
|
|
3122
|
+
if (Number.isFinite(n) && n > 0 && Math.min(1000, n) !== (agentOpts.maxTurns ?? 100))
|
|
3123
|
+
next.maxTurns = Math.min(1000, n);
|
|
3124
|
+
if (tokMode.value === "n") {
|
|
3125
|
+
const k = parseInt(tokN.value, 10);
|
|
3126
|
+
if (Number.isFinite(k) && k > 0)
|
|
3127
|
+
next.maxTokens = k;
|
|
3128
|
+
}
|
|
3129
|
+
if (effortSel.value && !effortSel.disabled)
|
|
3130
|
+
next.reasoningEffort = effortSel.value;
|
|
3131
|
+
if (perm.value === "ask" || perm.value === "auto")
|
|
3132
|
+
permChoice = perm.value;
|
|
3133
|
+
for (const read of hostReads)
|
|
3134
|
+
read();
|
|
3135
|
+
saveSettings(next);
|
|
3136
|
+
closeMenu();
|
|
3137
|
+
ui.notify(t.applied);
|
|
3138
|
+
});
|
|
3139
|
+
};
|
|
3140
|
+
setBtn.addEventListener("click", () => void openSettings());
|
|
3141
|
+
/* --- sessions menu --- */
|
|
3142
|
+
// The settings menu's dropdowns: closed with it, so none keeps a document listener.
|
|
3143
|
+
const menuSelects = [];
|
|
3144
|
+
const closeMenu = () => { menu?.remove(); menu = null; for (const b of menuSelects.splice(0))
|
|
3145
|
+
b.close(); };
|
|
3146
|
+
/** A header menu opens right under the header, however tall the host made it. */
|
|
3147
|
+
const placeMenu = (el) => { root.append(el); el.style.top = `${head.offsetTop + head.offsetHeight + 4}px`; };
|
|
3148
|
+
const openMenu = async () => {
|
|
3149
|
+
if (menu) {
|
|
3150
|
+
closeMenu();
|
|
3151
|
+
return;
|
|
3152
|
+
}
|
|
3153
|
+
if (!agent?.workspace)
|
|
3154
|
+
return;
|
|
3155
|
+
const ws = agent.workspace;
|
|
3156
|
+
const mine = h("div", "ra-menu");
|
|
3157
|
+
menu = mine;
|
|
3158
|
+
placeMenu(mine);
|
|
3159
|
+
let all = [];
|
|
3160
|
+
try {
|
|
3161
|
+
all = await ws.sessions.list();
|
|
3162
|
+
}
|
|
3163
|
+
catch { /* none */ }
|
|
3164
|
+
if (menu !== mine)
|
|
3165
|
+
return;
|
|
3166
|
+
// The conversations: the open one first, marked (also before it is saved), then the others, newest first.
|
|
3167
|
+
const cur = agent;
|
|
3168
|
+
const others = all.filter((x) => x.id !== cur.id);
|
|
3169
|
+
const saved = all.find((x) => x.id === cur.id);
|
|
3170
|
+
const sessionRow = (s) => {
|
|
3171
|
+
const isCur = !s || s.id === cur.id;
|
|
3172
|
+
const row = h("div", "ra-mi" + (isCur ? " ra-cur" : ""));
|
|
3173
|
+
const b = h("button");
|
|
3174
|
+
b.type = "button";
|
|
3175
|
+
const bg = s ? live.get(s.id) : undefined;
|
|
3176
|
+
const state = s && bg && bg !== cur ? (waiting.has(s.id) ? ` · ${t.waitingAnswer}` : bg.busy || bg.queued.length ? ` · ${t.running}` : "") : "";
|
|
3177
|
+
// The title line: the title shortens, the "Current" tag (and a spinner for a running session) always shows.
|
|
3178
|
+
const name = h("span", "ra-mt");
|
|
3179
|
+
if (state && !waiting.has(s.id))
|
|
3180
|
+
name.append(h("span", "ra-spin"));
|
|
3181
|
+
name.append(h("span", "ra-mtt", (s ? s.title : titleOfAgent(cur)) || t.untitled));
|
|
3182
|
+
if (isCur) {
|
|
3183
|
+
name.append(h("span", "ra-now", t.current));
|
|
3184
|
+
row.setAttribute("aria-current", "true");
|
|
3185
|
+
}
|
|
3186
|
+
b.append(name, h("small", "", s ? `${s.messages} ${t.messages} · ${new Date(s.savedAt).toLocaleString()}${state}` : t.notSaved));
|
|
3187
|
+
b.addEventListener("click", () => { closeMenu(); if (s && !isCur)
|
|
3188
|
+
void resume(s.id).catch((err) => ui.notify(err.message, "error")); });
|
|
3189
|
+
row.append(b);
|
|
3190
|
+
if (s) {
|
|
3191
|
+
const x = h("button", "ra-x");
|
|
3192
|
+
x.type = "button";
|
|
3193
|
+
x.innerHTML = I.trash();
|
|
3194
|
+
x.title = t.delete;
|
|
3195
|
+
x.setAttribute("aria-label", t.delete);
|
|
3196
|
+
x.addEventListener("click", async (e) => {
|
|
3197
|
+
e.stopPropagation();
|
|
3198
|
+
closeMenu();
|
|
3199
|
+
if (await modalConfirm(root, t.delete, t.confirmDelete, { danger: true, ok: t.delete, cancel: t.cancel }))
|
|
3200
|
+
await deleteSession(s.id, false, s.workspace).catch((err) => ui.notify(err.message, "error"));
|
|
3201
|
+
});
|
|
3202
|
+
row.append(x);
|
|
3203
|
+
}
|
|
3204
|
+
return row;
|
|
3205
|
+
};
|
|
3206
|
+
mine.append(sessionRow(saved ?? null));
|
|
3207
|
+
if (!others.length)
|
|
3208
|
+
mine.append(h("div", "ra-none", t.noSessions));
|
|
3209
|
+
else
|
|
3210
|
+
mine.append(h("div", "ra-sep"));
|
|
3211
|
+
for (const s of others)
|
|
3212
|
+
mine.append(sessionRow(s));
|
|
3213
|
+
if (others.length) {
|
|
3214
|
+
const foot = h("div", "ra-mf");
|
|
3215
|
+
const del = h("button", "ra-btn xs ghost");
|
|
3216
|
+
del.type = "button";
|
|
3217
|
+
del.innerHTML = I.trash() + escapeHTML(t.deleteAll);
|
|
3218
|
+
del.addEventListener("click", async () => {
|
|
3219
|
+
closeMenu();
|
|
3220
|
+
if (!(await modalConfirm(root, t.deleteAll, t.confirmDeleteAll, { danger: true, ok: t.deleteAll, cancel: t.cancel })))
|
|
3221
|
+
return;
|
|
3222
|
+
try {
|
|
3223
|
+
for (const s of all)
|
|
3224
|
+
await deleteSession(s.id, true, s.workspace);
|
|
3225
|
+
await newSession();
|
|
3226
|
+
}
|
|
3227
|
+
catch (err) {
|
|
3228
|
+
ui.notify(err.message, "error");
|
|
3229
|
+
}
|
|
3230
|
+
});
|
|
3231
|
+
foot.append(del);
|
|
3232
|
+
mine.append(foot);
|
|
3233
|
+
}
|
|
3234
|
+
};
|
|
3235
|
+
histBtn.addEventListener("click", () => void openMenu());
|
|
3236
|
+
newBtn.addEventListener("click", () => { closeMenu(); void newSession().catch((err) => ui.notify(err.message, "error")); });
|
|
3237
|
+
clearBtn.addEventListener("click", async () => {
|
|
3238
|
+
closeMenu();
|
|
3239
|
+
if (await modalConfirm(root, t.clearChat, t.confirmClear, { danger: true, ok: t.clearChat, cancel: t.cancel }))
|
|
3240
|
+
await clearConversation().catch((err) => ui.notify(err.message, "error"));
|
|
3241
|
+
});
|
|
3242
|
+
document.addEventListener("click", onDocClick, true);
|
|
3243
|
+
function onDocClick(e) { if (e.target?.closest?.(".ra-selp"))
|
|
3244
|
+
return; if (menu && !menu.contains(e.target) && !histBtn.contains(e.target) && !setBtn.contains(e.target) && !skillsBtn.contains(e.target) && !useBtn.contains(e.target))
|
|
3245
|
+
closeMenu(); }
|
|
3246
|
+
/* --- skills menu --- */
|
|
3247
|
+
const skillInput = h("input");
|
|
3248
|
+
skillInput.type = "file";
|
|
3249
|
+
skillInput.accept = ".zip,application/zip";
|
|
3250
|
+
skillInput.multiple = true;
|
|
3251
|
+
skillInput.style.display = "none";
|
|
3252
|
+
root.append(skillInput);
|
|
3253
|
+
const installZips = async (files) => {
|
|
3254
|
+
const ws = agent?.workspace;
|
|
3255
|
+
if (!ws || !files?.length)
|
|
3256
|
+
return;
|
|
3257
|
+
const names = [];
|
|
3258
|
+
for (const f of Array.from(files)) {
|
|
3259
|
+
if (!/\.zip$/i.test(f.name) && f.type !== "application/zip" && f.type !== "application/x-zip-compressed") {
|
|
3260
|
+
ui.notify(`${f.name}: ${t.notZip}`, "warning");
|
|
3261
|
+
continue;
|
|
3262
|
+
}
|
|
3263
|
+
try {
|
|
3264
|
+
names.push(...(await ws.installSkill(f)).map((s) => s.name));
|
|
3265
|
+
}
|
|
3266
|
+
catch (err) {
|
|
3267
|
+
ui.notify(`${f.name}: ${err.message}`, "error");
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
if (names.length)
|
|
3271
|
+
ui.notify(t.skillsInstalled.replace("{names}", names.join(", ")));
|
|
3272
|
+
await refreshCommands();
|
|
3273
|
+
if (menu?.classList.contains("ra-skm")) {
|
|
3274
|
+
closeMenu();
|
|
3275
|
+
void openSkills();
|
|
3276
|
+
}
|
|
3277
|
+
};
|
|
3278
|
+
skillInput.addEventListener("change", () => { void installZips(skillInput.files); skillInput.value = ""; });
|
|
3279
|
+
const openSkills = async () => {
|
|
3280
|
+
if (menu) {
|
|
3281
|
+
const was = menu.classList.contains("ra-skm");
|
|
3282
|
+
closeMenu();
|
|
3283
|
+
if (was)
|
|
3284
|
+
return;
|
|
3285
|
+
}
|
|
3286
|
+
const ws = agent?.workspace;
|
|
3287
|
+
if (!ws)
|
|
3288
|
+
return;
|
|
3289
|
+
const mine = h("div", "ra-menu ra-skm");
|
|
3290
|
+
menu = mine;
|
|
3291
|
+
placeMenu(mine);
|
|
3292
|
+
let skills = [];
|
|
3293
|
+
try {
|
|
3294
|
+
skills = await ws.skills();
|
|
3295
|
+
}
|
|
3296
|
+
catch (err) {
|
|
3297
|
+
ui.notify(err.message, "error");
|
|
3298
|
+
}
|
|
3299
|
+
if (menu !== mine)
|
|
3300
|
+
return;
|
|
3301
|
+
const head = h("div", "ra-skh");
|
|
3302
|
+
const up = h("button", "ra-btn xs solid");
|
|
3303
|
+
up.type = "button";
|
|
3304
|
+
up.innerHTML = I.upload(13) + `<span>${escapeHTML(t.uploadZip)}</span>`;
|
|
3305
|
+
up.addEventListener("click", () => skillInput.click());
|
|
3306
|
+
if (!ws.userSkillsDir)
|
|
3307
|
+
up.style.display = "none";
|
|
3308
|
+
head.append(h("span", "", skills.length ? `${t.skills} · ${skills.length}` : t.skills), up);
|
|
3309
|
+
mine.append(head);
|
|
3310
|
+
if (!skills.length)
|
|
3311
|
+
mine.append(h("div", "ra-none", t.noSkills));
|
|
3312
|
+
for (const s of skills) {
|
|
3313
|
+
const row = h("div", "ra-mi");
|
|
3314
|
+
const b = h("button");
|
|
3315
|
+
b.type = "button";
|
|
3316
|
+
b.title = t.useSkill;
|
|
3317
|
+
const name = h("span", "ra-mt");
|
|
3318
|
+
const isZip = !!s.from && /\.zip$/i.test(s.from);
|
|
3319
|
+
name.append(h("span", "ra-mtt", s.name), h("span", "ra-skb", s.builtin ? t.builtinSkill : isZip ? "zip" : t.skillFolder));
|
|
3320
|
+
if (s.disableModelInvocation)
|
|
3321
|
+
name.append(h("span", "ra-skb", t.manualOnly));
|
|
3322
|
+
b.append(name, h("small", "", s.description));
|
|
3323
|
+
// Using a skill: it goes into the composer as /skill:name.
|
|
3324
|
+
b.addEventListener("click", () => { closeMenu(); ta.value = `/skill:${s.name} `; ta.focus(); renderCmds(); });
|
|
3325
|
+
const act = (icon, title, fn, cls = "ra-x ra-ia") => { const x = h("button", cls); x.type = "button"; x.innerHTML = icon; x.title = title; x.setAttribute("aria-label", title); x.addEventListener("click", (e) => { e.stopPropagation(); fn(); }); return x; };
|
|
3326
|
+
// A folder of the user's opens where it can be edited; anything else opens read-only in the generated folder.
|
|
3327
|
+
const view = act(I.eye(), t.open, () => { closeMenu(); openPath(s.from && !isZip ? `${s.from}/SKILL.md` : s.path); });
|
|
3328
|
+
const dl = act(I.download(), t.download, () => { if (isZip)
|
|
3329
|
+
void panel.download(s.from);
|
|
3330
|
+
else
|
|
3331
|
+
void panel.downloadFolder(s.from ?? s.dir); });
|
|
3332
|
+
const del = act(I.trash(), t.delete, async () => {
|
|
3333
|
+
closeMenu();
|
|
3334
|
+
// A zip of several skills goes as a whole: say which go with it.
|
|
3335
|
+
const packed = isZip ? skills.filter((x) => x.from === s.from).map((x) => x.name) : [s.name];
|
|
3336
|
+
const msg = packed.length > 1 ? t.confirmDeleteZip.replace("{zip}", s.from.replace(/^.*\//, "")).replace("{names}", packed.join("、")) : t.confirmDeleteSkill.replace("{name}", s.name).replace("{path}", s.from ?? "");
|
|
3337
|
+
if (!(await modalConfirm(root, t.delete, msg, { danger: true, ok: t.delete, cancel: t.cancel })))
|
|
3338
|
+
return;
|
|
3339
|
+
try {
|
|
3340
|
+
await ws.removeSkill(s.name);
|
|
3341
|
+
await refreshCommands();
|
|
3342
|
+
ui.notify(t.skillRemoved.replace("{name}", packed.join(", ")));
|
|
3343
|
+
}
|
|
3344
|
+
catch (err) {
|
|
3345
|
+
ui.notify(err.message, "error");
|
|
3346
|
+
}
|
|
3347
|
+
}, "ra-x");
|
|
3348
|
+
if (s.builtin || !s.from?.startsWith((ws.userSkillsDir ?? "\u0000") + "/"))
|
|
3349
|
+
del.style.display = "none";
|
|
3350
|
+
row.append(b, view, dl, del);
|
|
3351
|
+
mine.append(row);
|
|
3352
|
+
}
|
|
3353
|
+
mine.append(h("div", "ra-skf", (ws.userSkillsDir ? t.skillsHint.replace("{user}", ws.userSkillsDir) : t.skillsHintNoUser).replace("{dir}", ws.skillsDir)));
|
|
3354
|
+
// A zip dropped on the menu installs like the upload button.
|
|
3355
|
+
// Without user skills (the app's only), a dropped zip is no install: the menu takes no drops.
|
|
3356
|
+
if (ws.userSkillsDir)
|
|
3357
|
+
mine.addEventListener("dragover", (e) => { if (e.dataTransfer?.types.includes("Files")) {
|
|
3358
|
+
e.preventDefault();
|
|
3359
|
+
e.stopPropagation();
|
|
3360
|
+
mine.classList.add("drop");
|
|
3361
|
+
} });
|
|
3362
|
+
mine.addEventListener("dragleave", () => mine.classList.remove("drop"));
|
|
3363
|
+
if (ws.userSkillsDir)
|
|
3364
|
+
mine.addEventListener("drop", (e) => { e.preventDefault(); e.stopPropagation(); mine.classList.remove("drop"); void installZips(e.dataTransfer?.files); });
|
|
3365
|
+
};
|
|
3366
|
+
skillsBtn.addEventListener("click", () => void openSkills());
|
|
3367
|
+
const fail = (err) => ui.notify(err.message, "error");
|
|
3368
|
+
let compacting = false;
|
|
3369
|
+
/** The conversation as Markdown: what was said, and the tools each turn called. */
|
|
3370
|
+
const transcriptMarkdown = (a) => {
|
|
3371
|
+
const out = [`# ${titleOfAgent(a)}`, ""];
|
|
3372
|
+
for (const m of a.messages) {
|
|
3373
|
+
if (m.role === "tool" || m.role === "system")
|
|
3374
|
+
continue;
|
|
3375
|
+
const text = textOfContent(m.content).trim();
|
|
3376
|
+
const s = m.role === "user" && typeof m.content === "string" ? summaryOf(m) : null;
|
|
3377
|
+
if (s !== null) {
|
|
3378
|
+
out.push(`> **${t.compacted}**`, ">", ...s.split("\n").map((l) => `> ${l}`), "");
|
|
3379
|
+
continue;
|
|
3380
|
+
}
|
|
3381
|
+
const calls = m.role === "assistant" ? (m.tool_calls ?? []).filter((c) => !hiddenTools.has(c.function.name)) : [];
|
|
3382
|
+
if (!text && !calls.length)
|
|
3383
|
+
continue;
|
|
3384
|
+
out.push(`## ${m.role === "user" ? t.user : t.assistant}`, "");
|
|
3385
|
+
if (text)
|
|
3386
|
+
out.push(text, "");
|
|
3387
|
+
for (const c of calls) {
|
|
3388
|
+
let args = c.function.arguments;
|
|
3389
|
+
try {
|
|
3390
|
+
args = JSON.parse(c.function.arguments);
|
|
3391
|
+
}
|
|
3392
|
+
catch { /* as sent */ }
|
|
3393
|
+
const what = summarizeArgs(c.function.name, args);
|
|
3394
|
+
out.push(`- \`${c.function.name}\`${what ? ` ${what}` : ""}`);
|
|
3395
|
+
}
|
|
3396
|
+
if (calls.length)
|
|
3397
|
+
out.push("");
|
|
3398
|
+
}
|
|
3399
|
+
return out.join("\n");
|
|
3400
|
+
};
|
|
3401
|
+
const pickModel = (models, q) => {
|
|
3402
|
+
const l = q.toLowerCase();
|
|
3403
|
+
const exact = models.find((m) => m.id.toLowerCase() === l);
|
|
3404
|
+
if (exact)
|
|
3405
|
+
return exact;
|
|
3406
|
+
const part = models.filter((m) => m.id.toLowerCase().includes(l));
|
|
3407
|
+
return part.length === 1 ? part[0] : part.find((m) => m.id.toLowerCase().startsWith(l));
|
|
3408
|
+
};
|
|
3409
|
+
const builtins = [
|
|
3410
|
+
{ name: "help", run: () => {
|
|
3411
|
+
const lines = builtinCommands().map((c) => `- \`/${c.name}${c.args ? ` ${c.args}` : ""}\` — ${c.description}`);
|
|
3412
|
+
addNote(t.cmdsTitle, [...lines, "", t.cmdsMore].join("\n"));
|
|
3413
|
+
} },
|
|
3414
|
+
{ name: "new", aliases: ["clear"], run: () => { closeMenu(); return clearBtn.style.display === "none" ? newSession().then(() => undefined) : clearConversation(); } },
|
|
3415
|
+
{ name: "resume", run: () => openMenu() },
|
|
3416
|
+
{ name: "compact", args: t.cmdArgs.compact, run: async (focus) => {
|
|
3417
|
+
const a = agent;
|
|
3418
|
+
if (a.busy) {
|
|
3419
|
+
ui.notify(t.busyCmd, "warning");
|
|
3420
|
+
return;
|
|
3421
|
+
}
|
|
3422
|
+
compacting = true;
|
|
3423
|
+
try {
|
|
3424
|
+
// The compaction events show it running and draw the summary; Stop aborts it.
|
|
3425
|
+
if (!(await a.compact(focus)))
|
|
3426
|
+
ui.notify(t.nothingToCompact);
|
|
3427
|
+
}
|
|
3428
|
+
catch (err) {
|
|
3429
|
+
if (!/abort/i.test(err.message ?? "") && err.name !== "AbortError")
|
|
3430
|
+
throw err;
|
|
3431
|
+
ui.notify(t.stopped);
|
|
3432
|
+
}
|
|
3433
|
+
finally {
|
|
3434
|
+
compacting = false;
|
|
3435
|
+
// The agent lets go of the compaction a tick after it resolves (and then starts any message queued meanwhile).
|
|
3436
|
+
if (agent === a) {
|
|
3437
|
+
closeActive();
|
|
3438
|
+
showUsage_(a);
|
|
3439
|
+
setTimeout(() => { if (agent === a && !a.busy)
|
|
3440
|
+
setBusy(false); }, 0);
|
|
3441
|
+
}
|
|
3442
|
+
}
|
|
3443
|
+
} },
|
|
3444
|
+
{ name: "continue", run: async () => {
|
|
3445
|
+
if (agent.busy) {
|
|
3446
|
+
ui.notify(t.busyCmd, "warning");
|
|
3447
|
+
return;
|
|
3448
|
+
}
|
|
3449
|
+
if (!agent.messages.length) {
|
|
3450
|
+
ui.notify(t.nothingToContinue);
|
|
3451
|
+
return;
|
|
3452
|
+
}
|
|
3453
|
+
await agent.continue();
|
|
3454
|
+
} },
|
|
3455
|
+
{ name: "model", args: t.cmdArgs.model, run: async (q) => {
|
|
3456
|
+
if (!q)
|
|
3457
|
+
return openSettings();
|
|
3458
|
+
const m = pickModel(await loadModels(), q);
|
|
3459
|
+
if (!m) {
|
|
3460
|
+
ui.notify(t.unknownModel.replace("{name}", q), "warning");
|
|
3461
|
+
return;
|
|
3462
|
+
}
|
|
3463
|
+
const next = { ...userSettings };
|
|
3464
|
+
if (m.is_default && !agentOpts.model)
|
|
3465
|
+
delete next.model;
|
|
3466
|
+
else
|
|
3467
|
+
next.model = m.id;
|
|
3468
|
+
// A thinking level the new model does not have would be refused.
|
|
3469
|
+
const eff = effortOf(m);
|
|
3470
|
+
if (next.reasoningEffort && !eff?.levels.includes(next.reasoningEffort))
|
|
3471
|
+
delete next.reasoningEffort;
|
|
3472
|
+
saveSettings(next);
|
|
3473
|
+
ui.notify(t.modelSet.replace("{name}", m.id));
|
|
3474
|
+
} },
|
|
3475
|
+
{ name: "effort", args: t.cmdArgs.effort, run: async (q) => {
|
|
3476
|
+
const models = await loadModels();
|
|
3477
|
+
const id = agent.model || models.find((x) => x.is_default)?.id;
|
|
3478
|
+
const m = models.find((x) => x.id === id);
|
|
3479
|
+
const eff = effortOf(m);
|
|
3480
|
+
const name = m?.id ?? id ?? "?";
|
|
3481
|
+
if (!eff) {
|
|
3482
|
+
ui.notify(`${name}: ${t.sEffortNone}`, "warning");
|
|
3483
|
+
return;
|
|
3484
|
+
}
|
|
3485
|
+
const levels = eff.levels.join(" / ");
|
|
3486
|
+
if (!q) {
|
|
3487
|
+
ui.notify(t.effortLevels.replace("{model}", name).replace("{levels}", levels));
|
|
3488
|
+
return;
|
|
3489
|
+
}
|
|
3490
|
+
const next = { ...userSettings };
|
|
3491
|
+
if (/^(default|auto|默认)$/i.test(q))
|
|
3492
|
+
delete next.reasoningEffort;
|
|
3493
|
+
else if (eff.levels.includes(q.toLowerCase()))
|
|
3494
|
+
next.reasoningEffort = q.toLowerCase();
|
|
3495
|
+
else {
|
|
3496
|
+
ui.notify(t.unknownEffort.replace("{name}", q).replace("{model}", name).replace("{levels}", levels), "warning");
|
|
3497
|
+
return;
|
|
3498
|
+
}
|
|
3499
|
+
saveSettings(next);
|
|
3500
|
+
ui.notify(t.effortSet.replace("{name}", next.reasoningEffort ?? (eff.def ? `${t.sEffortDefault} · ${eff.def}` : t.sEffortDefault)));
|
|
3501
|
+
} },
|
|
3502
|
+
{ name: "context", run: async () => {
|
|
3503
|
+
const a = agent;
|
|
3504
|
+
const [c, lim, info] = await Promise.all([a.context(), a.limits(), a.modelInfo()]);
|
|
3505
|
+
const price = priceOf(info);
|
|
3506
|
+
const pct = Math.round((c.used / c.window) * 100);
|
|
3507
|
+
const u = a.usage;
|
|
3508
|
+
const comp = agentOpts.compaction;
|
|
3509
|
+
const lines = [
|
|
3510
|
+
`- ${t.sModel}: ${a.model || (await loadModels()).find((m) => m.is_default)?.id || t.sDefault}`,
|
|
3511
|
+
`- ${t.context}: ${pct < 1 && c.used ? "<1" : pct}% · ${fmtTokens(c.used)} / ${fmtTokens(c.window)} tokens · ${t.sMaxTokens} ${fmtTokens(lim.output)}`,
|
|
3512
|
+
price ? `- ${t.sPrice}: ${price}` : "",
|
|
3513
|
+
`- ${t.messagesLabel}: ${a.messages.length}`,
|
|
3514
|
+
u.calls ? `- ${fill(t.usageLine.replace("{cost}", fmtCost(u.total_cost, info?.price?.currency)).replace("{tokens}", fmtTokens(u.prompt_tokens + u.completion_tokens)).replace("{calls}", String(u.calls)))}` : "",
|
|
3515
|
+
comp === false ? "" : `- ${t.autoCompact}: ${t.autoCompactAt.replace("{n}", fmtTokens(Math.min(16_384, Math.floor(c.window * 0.2))))}`,
|
|
3516
|
+
a.workspace ? `- ${t.directory}: \`${a.workspace.id}\`` : "",
|
|
3517
|
+
].filter(Boolean);
|
|
3518
|
+
addNote(t.context, lines.join("\n"));
|
|
3519
|
+
} },
|
|
3520
|
+
{ name: "export", run: () => {
|
|
3521
|
+
if (!agent.messages.length) {
|
|
3522
|
+
ui.notify(t.nothingToExport);
|
|
3523
|
+
return;
|
|
3524
|
+
}
|
|
3525
|
+
const name = titleOfAgent(agent).replace(/[\\/:*?"<>|\s]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "conversation";
|
|
3526
|
+
downloadBlob(`${name}.md`, transcriptMarkdown(agent), "text/markdown;charset=utf-8");
|
|
3527
|
+
} },
|
|
3528
|
+
{ name: "files", run: () => (filesOpt === false ? undefined : filesBtn.click()) },
|
|
3529
|
+
{ name: "settings", run: () => openSettings() },
|
|
3530
|
+
{ name: "debug", run: () => { if (debugOn)
|
|
3531
|
+
debugBtn.click();
|
|
3532
|
+
else
|
|
3533
|
+
ui.notify(t.debugOff); } },
|
|
3534
|
+
];
|
|
3535
|
+
/** The built-ins this chat offers now (the files, settings and debug ones only where their button shows). */
|
|
3536
|
+
const builtinCommands = () => builtins
|
|
3537
|
+
.filter((b) => (b.name !== "files" || (!!agent?.workspace && filesOpt !== false)) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || (!givenAgent && !!agent?.workspace && clearBtn.style.display === "none")))
|
|
3538
|
+
.map((b) => ({ name: b.name, description: b.name === "new" && clearBtn.style.display !== "none" ? t.confirmClear.split(/[??]/)[0] : t.cmd[b.name] ?? "", kind: t.command, args: b.args, builtin: true }));
|
|
3539
|
+
/** `/name [arg]` naming a built-in: run it here (nothing goes to the model). */
|
|
3540
|
+
const runBuiltin = (text) => {
|
|
3541
|
+
const m = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text);
|
|
3542
|
+
if (!m)
|
|
3543
|
+
return false;
|
|
3544
|
+
const key = m[1].toLowerCase();
|
|
3545
|
+
const b = builtins.find((x) => x.name === key || x.aliases?.includes(key));
|
|
3546
|
+
if (!b || !builtinCommands().some((c) => c.name === b.name))
|
|
3547
|
+
return false;
|
|
3548
|
+
ta.value = "";
|
|
3549
|
+
renderCmds();
|
|
3550
|
+
try {
|
|
3551
|
+
void Promise.resolve(b.run((m[2] ?? "").trim())).catch(fail);
|
|
3552
|
+
}
|
|
3553
|
+
catch (err) {
|
|
3554
|
+
fail(err);
|
|
3555
|
+
}
|
|
3556
|
+
return true;
|
|
3557
|
+
};
|
|
3558
|
+
/** A suggestion picked: a built-in runs at once when it needs no argument or its name is typed out; anything else is filled in for its arguments. */
|
|
3559
|
+
const pickCommand = (c) => {
|
|
3560
|
+
if (c.builtin && (!c.args || ta.value.trim() === `/${c.name}`)) {
|
|
3561
|
+
ta.value = `/${c.name}`;
|
|
3562
|
+
void send("prompt");
|
|
3563
|
+
return;
|
|
3564
|
+
}
|
|
3565
|
+
ta.value = `/${c.name} `;
|
|
3566
|
+
renderCmds();
|
|
3567
|
+
};
|
|
3568
|
+
/* --- wiring an agent --- */
|
|
3569
|
+
/** The currency the model's costs are in (its catalogue price), for the usage panel. */
|
|
3570
|
+
let costCurrency;
|
|
3571
|
+
/** The header's ring (how full the context is) and, while it is open, the usage panel. */
|
|
3572
|
+
const showUsage_ = (a) => {
|
|
3573
|
+
if (showUsage === false || agent !== a)
|
|
3574
|
+
return;
|
|
3575
|
+
if (!a.messages.length) {
|
|
3576
|
+
useBtn.style.display = "none";
|
|
3577
|
+
if (menu?.classList.contains("ra-use"))
|
|
3578
|
+
closeMenu();
|
|
3579
|
+
return;
|
|
3580
|
+
}
|
|
3581
|
+
void Promise.all([a.context(), a.modelInfo()]).then(([c, info]) => {
|
|
3582
|
+
if (agent !== a)
|
|
3583
|
+
return;
|
|
3584
|
+
costCurrency = info?.price?.currency;
|
|
3585
|
+
const ratio = Math.min(1, c.used / c.window);
|
|
3586
|
+
const r = 8, len = 2 * Math.PI * r;
|
|
3587
|
+
useBtn.innerHTML = `<svg class="ra-ring${ratio >= 0.9 ? " hi" : ratio >= 0.7 ? " mid" : ""}" viewBox="0 0 20 20" aria-hidden="true"><circle class="tr" cx="10" cy="10" r="${r}"/><circle class="pr" cx="10" cy="10" r="${r}" stroke-dasharray="${len.toFixed(2)}" stroke-dashoffset="${(len * (1 - Math.max(ratio, 0.03))).toFixed(2)}" transform="rotate(-90 10 10)"/></svg>`;
|
|
3588
|
+
const label = `${cap(t.context)} ${pctOf(c.used, c.window)}`;
|
|
3589
|
+
useBtn.title = label;
|
|
3590
|
+
useBtn.setAttribute("aria-label", label);
|
|
3591
|
+
useBtn.style.display = "";
|
|
3592
|
+
if (menu?.classList.contains("ra-use"))
|
|
3593
|
+
fillUsage(menu, a, c);
|
|
3594
|
+
});
|
|
3595
|
+
};
|
|
3596
|
+
const cap = (x) => x.charAt(0).toUpperCase() + x.slice(1);
|
|
3597
|
+
const pctOf = (used, window) => { const p = used / window; return used && p < 0.01 ? "<1%" : `${Math.round(Math.min(1, p) * 100)}%`; };
|
|
3598
|
+
/** The usage panel: how full the context is, what the conversation has cost, and Compact now. */
|
|
3599
|
+
const fillUsage = (panel, a, c) => {
|
|
3600
|
+
const ratio = Math.min(1, c.used / c.window), u = a.usage;
|
|
3601
|
+
panel.className = "ra-menu ra-use" + (ratio >= 0.9 ? " hi" : ratio >= 0.7 ? " mid" : "");
|
|
3602
|
+
const head = h("div", "ra-uh");
|
|
3603
|
+
head.append(h("span", "", cap(t.context)), h("b", "", pctOf(c.used, c.window)));
|
|
3604
|
+
const bar = h("div", "ra-ubar");
|
|
3605
|
+
const fillEl = h("i");
|
|
3606
|
+
fillEl.style.width = `${Math.max(ratio, c.used ? 0.01 : 0) * 100}%`;
|
|
3607
|
+
bar.append(fillEl);
|
|
3608
|
+
const sub = h("div", "ra-usub");
|
|
3609
|
+
sub.append(h("span", "", t.uOf.replace("{used}", fmtTokens(c.used)).replace("{window}", fmtTokens(c.window))), h("span", "", a.model || modelsCache?.find((m) => m.is_default)?.id || ""));
|
|
3610
|
+
const grid = h("div", "ra-ugrid");
|
|
3611
|
+
for (const [k, v] of [[t.uCost, fmtCost(u.total_cost, costCurrency)], [t.uIn, fmtTokens(u.prompt_tokens)], [t.uOut, fmtTokens(u.completion_tokens)], [t.uCalls, String(u.calls)]]) {
|
|
3612
|
+
const cell = h("div");
|
|
3613
|
+
cell.append(h("small", "", k), h("b", "", v));
|
|
3614
|
+
grid.append(cell);
|
|
3615
|
+
}
|
|
3616
|
+
panel.replaceChildren(head, bar, sub, grid);
|
|
3617
|
+
if (agentOpts.compaction !== false)
|
|
3618
|
+
panel.append(h("div", "ra-unote", `${t.autoCompact}: ${t.autoCompactAt.replace("{n}", fmtTokens(Math.min(16_384, Math.floor(c.window * 0.2))))}`));
|
|
3619
|
+
const foot = h("div", "ra-mf");
|
|
3620
|
+
const compactBtn = h("button", "ra-btn xs ghost");
|
|
3621
|
+
compactBtn.type = "button";
|
|
3622
|
+
compactBtn.textContent = t.compactNow;
|
|
3623
|
+
compactBtn.disabled = a.busy || compacting;
|
|
3624
|
+
compactBtn.addEventListener("click", () => {
|
|
3625
|
+
closeMenu();
|
|
3626
|
+
void Promise.resolve(builtins.find((b) => b.name === "compact").run("")).catch((err) => ui.notify(err.message, "error"));
|
|
3627
|
+
});
|
|
3628
|
+
foot.append(compactBtn);
|
|
3629
|
+
panel.append(foot);
|
|
3630
|
+
};
|
|
3631
|
+
const openUsage = async () => {
|
|
3632
|
+
if (menu?.classList.contains("ra-use")) {
|
|
3633
|
+
closeMenu();
|
|
3634
|
+
return;
|
|
3635
|
+
}
|
|
3636
|
+
closeMenu();
|
|
3637
|
+
if (!agent)
|
|
3638
|
+
return;
|
|
3639
|
+
const a = agent;
|
|
3640
|
+
const mine = h("div", "ra-menu ra-use");
|
|
3641
|
+
menu = mine;
|
|
3642
|
+
placeMenu(mine);
|
|
3643
|
+
const c = await a.context();
|
|
3644
|
+
if (menu === mine && agent === a)
|
|
3645
|
+
fillUsage(mine, a, c);
|
|
3646
|
+
};
|
|
3647
|
+
useBtn.addEventListener("click", () => void openUsage());
|
|
3648
|
+
/** How a run ended when it did not finish — stopped, turn limit (with Continue), error (with Retry); also drawn for a reopened session until its next run. */
|
|
3649
|
+
const addEnd = (a, end) => {
|
|
3650
|
+
if (!end)
|
|
3651
|
+
return;
|
|
3652
|
+
const go = () => { try {
|
|
3653
|
+
void a.continue().catch((e) => ui.notify(e.message, "error"));
|
|
3654
|
+
}
|
|
3655
|
+
catch (e) {
|
|
3656
|
+
ui.notify(e.message, "error");
|
|
3657
|
+
} };
|
|
3658
|
+
if (end.reason === "error")
|
|
3659
|
+
addError(end.error ?? t.error, a.messages.length ? go : undefined);
|
|
3660
|
+
else if (end.reason === "max_turns")
|
|
3661
|
+
addWarn(t.maxTurns.replace("{n}", String(a.settings.maxTurns)), { label: t.continueRun, onClick: go }, t.maxTurnsHint);
|
|
3662
|
+
else
|
|
3663
|
+
addNote(t.stopped);
|
|
3664
|
+
};
|
|
3665
|
+
const attach = async (a) => {
|
|
3666
|
+
for (const u of unsub)
|
|
3667
|
+
u();
|
|
3668
|
+
unsub = [];
|
|
3669
|
+
// Skills added or removed anywhere (the menu, the agent, another tab): the count and the / list follow.
|
|
3670
|
+
if (a.workspace) {
|
|
3671
|
+
const ws = a.workspace;
|
|
3672
|
+
unsub.push(ws.onChange((c) => { if (ws.isSkillPath(c.path))
|
|
3673
|
+
void refreshCommands(); }));
|
|
3674
|
+
}
|
|
3675
|
+
if (agent && agent !== a)
|
|
3676
|
+
parked.set(agent.id, ui.park());
|
|
3677
|
+
if (agent !== a)
|
|
3678
|
+
clearNext();
|
|
3679
|
+
agent = a;
|
|
3680
|
+
live.set(a.id, a);
|
|
3681
|
+
unwatchBackground(a);
|
|
3682
|
+
ui.restore(parked.get(a.id) ?? []);
|
|
3683
|
+
parked.delete(a.id);
|
|
3684
|
+
wake(a.id);
|
|
3685
|
+
markBackground();
|
|
3686
|
+
cards.clear();
|
|
3687
|
+
active = null;
|
|
3688
|
+
awaitingRow = null;
|
|
3689
|
+
modelEl.textContent = a.model ?? "";
|
|
3690
|
+
modelEl.style.display = a.model ? "" : "none";
|
|
3691
|
+
// A host's own agent has no sessions to switch between: the chat cannot make a new one.
|
|
3692
|
+
const hasSessions = !givenAgent && (sessions ?? !!a.workspace);
|
|
3693
|
+
histBtn.style.display = newBtn.style.display = hasSessions && a.workspace ? "" : "none";
|
|
3694
|
+
clearBtn.style.display = hasSessions && a.workspace ? "none" : "";
|
|
3695
|
+
filesBtn.style.display = a.workspace && filesOpt !== false ? "" : "none";
|
|
3696
|
+
skillsBtn.style.display = a.workspace && skillsMenu !== false ? "" : "none";
|
|
3697
|
+
panel.setWorkspace(a.workspace);
|
|
3698
|
+
if (debugOn)
|
|
3699
|
+
dpanel.setAgent(a);
|
|
3700
|
+
list.clear();
|
|
3701
|
+
showEmpty();
|
|
3702
|
+
setBusy(a.busy);
|
|
3703
|
+
setAlert();
|
|
3704
|
+
if (!givenAgent)
|
|
3705
|
+
writeLast(project, a.id);
|
|
3706
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3707
|
+
const on = (name, fn) => unsub.push(a.on(name, fn));
|
|
3708
|
+
on("run_start", (ev) => {
|
|
3709
|
+
// A prompt sent from here was drawn then (awaitingRow); one from a queued follow-up or the host is drawn now; continue() has none.
|
|
3710
|
+
if (ev.message) {
|
|
3711
|
+
if (awaitingRow && !awaitingRow.msg) {
|
|
3712
|
+
awaitingRow.msg = ev.message;
|
|
3713
|
+
awaitingRow.update();
|
|
3714
|
+
}
|
|
3715
|
+
else
|
|
3716
|
+
addUser(ev.message.content, ev.message);
|
|
3717
|
+
void checkpoint(a, ev.message);
|
|
3718
|
+
}
|
|
3719
|
+
awaitingRow = null;
|
|
3720
|
+
active = null;
|
|
3721
|
+
replyStart = Date.now();
|
|
3722
|
+
setBusy(true);
|
|
3723
|
+
showPending();
|
|
3724
|
+
});
|
|
3725
|
+
on("turn_start", () => {
|
|
3726
|
+
flushActive(true);
|
|
3727
|
+
// A run's turns share one row (folded into "Worked for …" at the end); a turn starts its own text and thinking,
|
|
3728
|
+
// and consecutive text-less turns (thinking and tool calls) share one group, so a chain of calls reads as one step.
|
|
3729
|
+
if (active) {
|
|
3730
|
+
active.text = null;
|
|
3731
|
+
active.md = "";
|
|
3732
|
+
active.drawn = undefined;
|
|
3733
|
+
active.drawnFinal = undefined;
|
|
3734
|
+
active.think = null;
|
|
3735
|
+
active.thinkBody = null;
|
|
3736
|
+
active.reasoning = "";
|
|
3737
|
+
}
|
|
3738
|
+
// Waiting for the model again (after tool results, or after a steer): say so until it answers.
|
|
3739
|
+
showPending();
|
|
3740
|
+
queueMicrotask(renderQueue);
|
|
3741
|
+
});
|
|
3742
|
+
// Steering is drawn when it lands in the history (at a turn, or before the next prompt), once.
|
|
3743
|
+
on("steered", (ev) => {
|
|
3744
|
+
// The row in progress ends here: what the agent does after the steer is drawn below the user's message, not above it.
|
|
3745
|
+
closeActive();
|
|
3746
|
+
replyStart = Date.now();
|
|
3747
|
+
for (const m of ev.messages)
|
|
3748
|
+
addUser(m.content, m);
|
|
3749
|
+
renderQueue();
|
|
3750
|
+
});
|
|
3751
|
+
on("queued", () => renderQueue());
|
|
3752
|
+
// The host rewound the agent itself: show what it has now.
|
|
3753
|
+
on("rewind", () => { if (agent === a) {
|
|
3754
|
+
renderHistory(a.messages);
|
|
3755
|
+
showUsage_(a);
|
|
3756
|
+
} });
|
|
3757
|
+
on("text_delta", (ev) => {
|
|
3758
|
+
const act = ensureActive();
|
|
3759
|
+
clearPending(act);
|
|
3760
|
+
if (!act.text) {
|
|
3761
|
+
act.text = h("div", "ra-md");
|
|
3762
|
+
putContent(act.body, act.text);
|
|
3763
|
+
}
|
|
3764
|
+
act.md = ev.text;
|
|
3765
|
+
scheduleRender();
|
|
3766
|
+
});
|
|
3767
|
+
on("reasoning_delta", (ev) => {
|
|
3768
|
+
const act = ensureActive();
|
|
3769
|
+
if (!act.pending && !act.text)
|
|
3770
|
+
showPending();
|
|
3771
|
+
if (!act.think) {
|
|
3772
|
+
[act.think, act.thinkBody] = thinkEl("", false);
|
|
3773
|
+
act.think.style.display = "none";
|
|
3774
|
+
// Inside the running group when the chain has started; otherwise before this turn's text.
|
|
3775
|
+
const last = lastContent(act.body);
|
|
3776
|
+
if (last instanceof HTMLDetailsElement && last.classList.contains("ra-tg") && !act.text)
|
|
3777
|
+
last.querySelector(".ra-tgb").append(act.think);
|
|
3778
|
+
else if (act.text)
|
|
3779
|
+
act.body.insertBefore(act.think, act.text);
|
|
3780
|
+
else
|
|
3781
|
+
putContent(act.body, act.think);
|
|
3782
|
+
}
|
|
3783
|
+
act.reasoning = ev.text;
|
|
3784
|
+
scheduleRender();
|
|
3785
|
+
});
|
|
3786
|
+
on("message_reset", () => { if (active) {
|
|
3787
|
+
active.md = "";
|
|
3788
|
+
active.reasoning = "";
|
|
3789
|
+
active.text?.remove();
|
|
3790
|
+
active.text = null;
|
|
3791
|
+
active.think?.remove();
|
|
3792
|
+
active.think = null;
|
|
3793
|
+
active.thinkBody = null;
|
|
3794
|
+
showPending();
|
|
3795
|
+
} });
|
|
3796
|
+
on("message_end", () => { clearPending(); flushActive(true); lastStamp = Date.now(); });
|
|
3797
|
+
on("tool_start", (ev) => {
|
|
3798
|
+
if (hiddenTools.has(ev.name))
|
|
3799
|
+
return;
|
|
3800
|
+
flushActive(true);
|
|
3801
|
+
const card = addCard(ev.id, ev.name, ev.args, ensureActive().body);
|
|
3802
|
+
// The folded group says which tool; the preview shows what it is doing.
|
|
3803
|
+
const r = describeRunning({ name: ev.name, args: ev.args }, card.el);
|
|
3804
|
+
// A file's name goes in the label; anything longer (code, a query) is the preview's.
|
|
3805
|
+
showPending(r.title ? `${r.verb} ${r.what}` : r.verb, toolPreview(ev.name, ev.args));
|
|
3806
|
+
});
|
|
3807
|
+
on("tool_update", (ev) => {
|
|
3808
|
+
const c = cards.get(ev.id);
|
|
3809
|
+
if (!c)
|
|
3810
|
+
return;
|
|
3811
|
+
if (!c.update) {
|
|
3812
|
+
c.update = h("div", "ra-tupd");
|
|
3813
|
+
c.el.append(c.update);
|
|
3814
|
+
}
|
|
3815
|
+
c.update.textContent = ev.content;
|
|
3816
|
+
if (active?.pending)
|
|
3817
|
+
showPending(active.pending.firstElementChild.textContent ?? t.waiting, { text: ev.content });
|
|
3818
|
+
list.schedule();
|
|
3819
|
+
});
|
|
3820
|
+
on("tool_end", (ev) => {
|
|
3821
|
+
const c = cards.get(ev.id);
|
|
3822
|
+
if (c)
|
|
3823
|
+
finishCard(c, ev.status, ev.result, ev.durationMs, imagesOf(ev.content), ev.details);
|
|
3824
|
+
else {
|
|
3825
|
+
const hc = histCalls.get(ev.id);
|
|
3826
|
+
if (hc) {
|
|
3827
|
+
hc.status = ev.status;
|
|
3828
|
+
hc.result = ev.result;
|
|
3829
|
+
histCalls.delete(ev.id);
|
|
3830
|
+
}
|
|
3831
|
+
}
|
|
3832
|
+
// tool_end carries no arguments: the card has them.
|
|
3833
|
+
const path = c?.args && typeof c.args === "object" ? c.args.path : undefined;
|
|
3834
|
+
if (ev.status === "ok" && typeof path === "string" && /^(write_file|edit_file|delete_file)$/.test(ev.name))
|
|
3835
|
+
panel.changed(path);
|
|
3836
|
+
// The last call of the batch is done: the model is asked next.
|
|
3837
|
+
if (active?.pending && !active.body.querySelector(".ra-tend .ra-spin"))
|
|
3838
|
+
showPending();
|
|
3839
|
+
});
|
|
3840
|
+
// A summary being written: in a run the placeholder says so; compact() on its own also puts the chat in its busy state.
|
|
3841
|
+
let trimNoted = null;
|
|
3842
|
+
on("compaction_start", (ev) => {
|
|
3843
|
+
if (!ev.runId) {
|
|
3844
|
+
setBusy(true);
|
|
3845
|
+
replyStart = Date.now();
|
|
3846
|
+
}
|
|
3847
|
+
showPending(t.compactingNow);
|
|
3848
|
+
});
|
|
3849
|
+
on("compaction", (ev) => {
|
|
3850
|
+
// In a run the model is asked next ("Thinking" again); compact() on its own is done.
|
|
3851
|
+
if (ev.runId) {
|
|
3852
|
+
if (active?.pending)
|
|
3853
|
+
showPending();
|
|
3854
|
+
}
|
|
3855
|
+
else
|
|
3856
|
+
closeActive();
|
|
3857
|
+
// Trimming may happen at every turn of a long run: one note per run says so.
|
|
3858
|
+
if (!ev.summary && ev.runId && trimNoted === ev.runId)
|
|
3859
|
+
return;
|
|
3860
|
+
if (!ev.summary)
|
|
3861
|
+
trimNoted = ev.runId ?? null;
|
|
3862
|
+
const first = a.messages[0];
|
|
3863
|
+
const s = first && typeof first.content === "string" ? summaryOf(first) : null;
|
|
3864
|
+
addNote(ev.summary ? t.compacted : t.trimmed, ev.summary && s ? s : undefined);
|
|
3865
|
+
});
|
|
3866
|
+
on("run_end", (r) => {
|
|
3867
|
+
// A finished run's suggestion goes into the input (setBusy below shows it); a stopped or failed one's is dropped.
|
|
3868
|
+
nextSuggestion = r.reason === "done" && !ta.value.trim() ? pendingNext : null;
|
|
3869
|
+
pendingNext = null;
|
|
3870
|
+
const row = active;
|
|
3871
|
+
closeActive();
|
|
3872
|
+
// The finished reply gets its footer: actions and what the run cost (on its last assistant message).
|
|
3873
|
+
const lastMsg = [...a.messages].reverse().find((m) => m.role === "assistant");
|
|
3874
|
+
if (row && row.body.childElementCount && lastMsg && !row.el.querySelector(":scope>.ra-af")) {
|
|
3875
|
+
row.el.append(replyFoot(lastMsg));
|
|
3876
|
+
list.schedule();
|
|
3877
|
+
}
|
|
3878
|
+
ui.cancelAll();
|
|
3879
|
+
addEnd(a, r.reason === "done" ? null : { reason: r.reason, error: r.error?.message, at: Date.now() });
|
|
3880
|
+
setBusy(false);
|
|
3881
|
+
showUsage_(a);
|
|
3882
|
+
void refreshCommands();
|
|
3883
|
+
void panel.refresh();
|
|
3884
|
+
refreshHistCount();
|
|
3885
|
+
});
|
|
3886
|
+
try {
|
|
3887
|
+
await a.ready();
|
|
3888
|
+
}
|
|
3889
|
+
catch (err) {
|
|
3890
|
+
addError(err.message);
|
|
3891
|
+
}
|
|
3892
|
+
if (agent !== a || !mounted)
|
|
3893
|
+
return;
|
|
3894
|
+
onSession?.(a);
|
|
3895
|
+
renderHistory(a.messages);
|
|
3896
|
+
if (!a.busy)
|
|
3897
|
+
addEnd(a, a.lastEnd);
|
|
3898
|
+
showUsage_(a);
|
|
3899
|
+
refreshHistCount();
|
|
3900
|
+
await refreshCommands();
|
|
3901
|
+
};
|
|
3902
|
+
const newId = () => `agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
3903
|
+
/** An agent for session `id`; with a workspace factory, the session's own directory (opened under the same id). */
|
|
3904
|
+
const makeAgent = async (id) => {
|
|
3905
|
+
const sid = id ?? newId();
|
|
3906
|
+
const workspace = typeof wsOpt === "function" ? await wsOpt(sid) : wsOpt ?? null;
|
|
3907
|
+
// The host's instructions may be a function (re-read every turn): the hint joins whatever it returns.
|
|
3908
|
+
const base = agentOpts.instructions;
|
|
3909
|
+
const hint = filesOpt === false ? linksHint(uploadsDir) : filesHint(uploadsDir);
|
|
3910
|
+
const instructions = !workspace ? base : typeof base === "function" ? () => [base(), hint].filter(Boolean).join("\n\n") : [base, hint].filter(Boolean).join("\n\n");
|
|
3911
|
+
const over = {};
|
|
3912
|
+
if (userSettings.model)
|
|
3913
|
+
over.model = userSettings.model;
|
|
3914
|
+
if (userSettings.maxTurns)
|
|
3915
|
+
over.maxTurns = userSettings.maxTurns;
|
|
3916
|
+
if (userSettings.maxTokens)
|
|
3917
|
+
over.maxTokens = userSettings.maxTokens;
|
|
3918
|
+
if (userSettings.reasoningEffort)
|
|
3919
|
+
over.extra = { ...(agentOpts.extra ?? {}), reasoning_effort: userSettings.reasoningEffort };
|
|
3920
|
+
if (permChoice)
|
|
3921
|
+
over.permissions = permChoice;
|
|
3922
|
+
return new Agent(provider, { ...agentOpts, ...over, tools: chatTools, instructions, id: sid, workspace, ui: agentOpts.ui ?? uiFor(sid) });
|
|
3923
|
+
};
|
|
3924
|
+
/** Closes the workspace the chat opened for a session it no longer holds (it reopens on resume). */
|
|
3925
|
+
const release = (a) => { dpanel.forget(a); if (typeof wsOpt === "function")
|
|
3926
|
+
a.workspace?.close(); };
|
|
3927
|
+
let switching = null;
|
|
3928
|
+
const switchTo = (id) => {
|
|
3929
|
+
if (givenAgent)
|
|
3930
|
+
return Promise.reject(new Error("newSession/resume need the chat to own its agent (pass a provider, not an agent)"));
|
|
3931
|
+
// One switch at a time: a double click on New chat makes one new session, not two.
|
|
3932
|
+
if (switching)
|
|
3933
|
+
return switching;
|
|
3934
|
+
const run = (async () => {
|
|
3935
|
+
if (id && id === agent?.id)
|
|
3936
|
+
return agent;
|
|
3937
|
+
const prev = agent;
|
|
3938
|
+
if (prev) {
|
|
3939
|
+
if (prev.busy || prev.queued.length > 0) {
|
|
3940
|
+
if (background().length >= MAX_BACKGROUND) {
|
|
3941
|
+
ui.notify(t.bgLimit.replace("{n}", String(background().length)), "warning");
|
|
3942
|
+
return prev;
|
|
3943
|
+
}
|
|
3944
|
+
watchBackground(prev); // keeps running; its questions wait for the user to come back
|
|
3945
|
+
}
|
|
3946
|
+
else {
|
|
3947
|
+
live.delete(prev.id);
|
|
3948
|
+
release(prev);
|
|
3949
|
+
} // idle and saved: rebuilt from storage when resumed
|
|
3950
|
+
}
|
|
3951
|
+
const a = (id && live.get(id)) || await makeAgent(id);
|
|
3952
|
+
await attach(a);
|
|
3953
|
+
return a;
|
|
3954
|
+
})();
|
|
3955
|
+
switching = run;
|
|
3956
|
+
void run.finally(() => { if (switching === run)
|
|
3957
|
+
switching = null; }).catch(() => undefined);
|
|
3958
|
+
return run;
|
|
3959
|
+
};
|
|
3960
|
+
const newSession = () => switchTo();
|
|
3961
|
+
const clearConversation = async () => {
|
|
3962
|
+
await ready;
|
|
3963
|
+
const a = agent ?? givenAgent;
|
|
3964
|
+
ui.cancelAll();
|
|
3965
|
+
await a.clear();
|
|
3966
|
+
if (agent === a || givenAgent === a) {
|
|
3967
|
+
renderHistory(a.messages);
|
|
3968
|
+
showUsage_(a);
|
|
3969
|
+
renderQueue();
|
|
3970
|
+
setAlert();
|
|
3971
|
+
}
|
|
3972
|
+
};
|
|
3973
|
+
const resume = (id) => switchTo(id);
|
|
3974
|
+
const deleteSession = async (id, keepOpen = false, space) => {
|
|
3975
|
+
await ready;
|
|
3976
|
+
if (givenAgent)
|
|
3977
|
+
throw new Error("deleteSession needs the chat to own its agent (pass a provider, not an agent)");
|
|
3978
|
+
const ws = agent.workspace;
|
|
3979
|
+
if (!ws)
|
|
3980
|
+
return;
|
|
3981
|
+
if (id !== agent.id) {
|
|
3982
|
+
const bg = live.get(id);
|
|
3983
|
+
if (bg) {
|
|
3984
|
+
// Its questions are answered "no" first, so the abort does not wait on a dialog nobody will see.
|
|
3985
|
+
wake(id, false);
|
|
3986
|
+
parked.delete(id);
|
|
3987
|
+
await bg.abort();
|
|
3988
|
+
live.delete(id);
|
|
3989
|
+
unwatchBackground(bg);
|
|
3990
|
+
release(bg);
|
|
3991
|
+
markBackground();
|
|
3992
|
+
}
|
|
3993
|
+
await ws.sessions.delete(id, space);
|
|
3994
|
+
refreshHistCount();
|
|
3995
|
+
return;
|
|
3996
|
+
}
|
|
3997
|
+
// The open session: stop it, drop its directory (files, skills, the saved session) and start afresh.
|
|
3998
|
+
ui.cancelAll();
|
|
3999
|
+
await agent.abort();
|
|
4000
|
+
if (typeof wsOpt === "function")
|
|
4001
|
+
await ws.destroy();
|
|
4002
|
+
else
|
|
4003
|
+
await ws.sessions.delete(id, ws.id);
|
|
4004
|
+
writeLast(project, null);
|
|
4005
|
+
if (!keepOpen)
|
|
4006
|
+
await newSession();
|
|
4007
|
+
};
|
|
4008
|
+
// Which session opens first: an explicit id, else the one last open here, else a new one.
|
|
4009
|
+
const firstId = agentOpts.id ?? (typeof resumeOpt === "string" ? resumeOpt : resumeOpt === false ? undefined : readLast(project) ?? undefined);
|
|
4010
|
+
const starting = givenAgent ? Promise.resolve(givenAgent) : makeAgent(firstId);
|
|
4011
|
+
const ready = starting.then((a) => attach(a));
|
|
4012
|
+
ready.catch((err) => {
|
|
4013
|
+
// No session could be opened (the workspace factory or the agent threw): say so instead of a dead chat.
|
|
4014
|
+
addError(`${err.message}`);
|
|
4015
|
+
setBusy(false);
|
|
4016
|
+
});
|
|
4017
|
+
// `prompt()` from the host: draw the message here, not from run_start.
|
|
4018
|
+
const promptFromHost = async (text) => {
|
|
4019
|
+
await ready;
|
|
4020
|
+
if (!agent.busy)
|
|
4021
|
+
awaitingRow = addUser(text);
|
|
4022
|
+
return agent.prompt(text);
|
|
4023
|
+
};
|
|
4024
|
+
return {
|
|
4025
|
+
get agent() { return agent ?? givenAgent; },
|
|
4026
|
+
get ready() { return ready; },
|
|
4027
|
+
element: root,
|
|
4028
|
+
ui,
|
|
4029
|
+
prompt: promptFromHost,
|
|
4030
|
+
setInput(text) { ta.value = text; ta.focus(); renderCmds(); },
|
|
4031
|
+
insertText(text) {
|
|
4032
|
+
const at = document.activeElement === ta ? ta.selectionStart : ta.value.length, end = document.activeElement === ta ? ta.selectionEnd : at;
|
|
4033
|
+
const before = ta.value.slice(0, at), after = ta.value.slice(end);
|
|
4034
|
+
const piece = (before && !/\s$/.test(before) ? " " : "") + text + (after && /^\S/.test(after) ? " " : after ? "" : " ");
|
|
4035
|
+
ta.value = before + piece + after;
|
|
4036
|
+
ta.focus();
|
|
4037
|
+
ta.setSelectionRange(before.length + piece.length, before.length + piece.length);
|
|
4038
|
+
renderCmds();
|
|
4039
|
+
},
|
|
4040
|
+
newSession,
|
|
4041
|
+
resume,
|
|
4042
|
+
deleteSession: (id) => deleteSession(id),
|
|
4043
|
+
clear: clearConversation,
|
|
4044
|
+
addContext,
|
|
4045
|
+
setDebug(on) { debugOn = on; applyDebug(); },
|
|
4046
|
+
updateComposerAction(id, patch) { const e = actionBtns.get(id); if (!e)
|
|
4047
|
+
return; Object.assign(e.a, patch); drawAction(e.btn, e.a); },
|
|
4048
|
+
setAppearance(o) {
|
|
4049
|
+
if (o.theme)
|
|
4050
|
+
themeNow = o.theme;
|
|
4051
|
+
if (o.palette)
|
|
4052
|
+
paletteNow = o.palette;
|
|
4053
|
+
if (o.vars !== undefined)
|
|
4054
|
+
varsNow = o.vars;
|
|
4055
|
+
applyAppearance();
|
|
4056
|
+
},
|
|
4057
|
+
refresh: refreshCommands,
|
|
4058
|
+
unmount() {
|
|
4059
|
+
if (!mounted)
|
|
4060
|
+
return;
|
|
4061
|
+
mounted = false;
|
|
4062
|
+
if (histTimer)
|
|
4063
|
+
clearTimeout(histTimer);
|
|
4064
|
+
for (const u of unsub)
|
|
4065
|
+
u();
|
|
4066
|
+
ui.cancelAll(true);
|
|
4067
|
+
closeMenu();
|
|
4068
|
+
document.removeEventListener("click", onDocClick, true);
|
|
4069
|
+
media?.removeEventListener?.("change", onScheme);
|
|
4070
|
+
if (renderTimer !== null)
|
|
4071
|
+
clearTimeout(renderTimer);
|
|
4072
|
+
if (cmdFrame !== null)
|
|
4073
|
+
cancelAnimationFrame(cmdFrame);
|
|
4074
|
+
list.dispose();
|
|
4075
|
+
rootSize?.disconnect();
|
|
4076
|
+
panel.dispose();
|
|
4077
|
+
dpanel.dispose();
|
|
4078
|
+
for (const f of pendingFiles)
|
|
4079
|
+
if (f.preview)
|
|
4080
|
+
URL.revokeObjectURL(f.preview);
|
|
4081
|
+
for (const id of [...waiters.keys()])
|
|
4082
|
+
wake(id, false);
|
|
4083
|
+
if (!givenAgent)
|
|
4084
|
+
for (const a of live.values()) {
|
|
4085
|
+
unwatchBackground(a);
|
|
4086
|
+
void a.abort().finally(() => release(a));
|
|
4087
|
+
}
|
|
4088
|
+
// A host that keeps the handle does not keep the sessions, their messages or their dialogs.
|
|
4089
|
+
live.clear();
|
|
4090
|
+
parked.clear();
|
|
4091
|
+
waiters.clear();
|
|
4092
|
+
pendingFiles.length = 0;
|
|
4093
|
+
pendingContext.length = 0;
|
|
4094
|
+
root.remove();
|
|
4095
|
+
},
|
|
4096
|
+
};
|
|
4097
|
+
}
|