@runappsai/agent 0.1.10 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chat.js CHANGED
@@ -13,8 +13,10 @@
13
13
  // in the DOM, so a long history costs nothing to open.
14
14
  import { escapeHTML } from "./markdown.js";
15
15
  import { VirtualList } from "./vlist.js";
16
- import { downloadBlob, h, I, modal, modalConfirm, renderMD } from "./dom.js";
16
+ import { chooseFiles, downloadBlob, h, I, modal, modalConfirm, renderMD, setFileDialog } from "./dom.js";
17
17
  import { selectBox, SELECT_CSS } from "./select.js";
18
+ import { Scheduler, scheduleTools, localSchedules, makeTask, changeTask, describeSchedule, formatLocalTime, nextRun, checkSchedule, parseLocalTime } from "./schedule.js";
19
+ import { DEFAULT_COMPACTION, resolveSettings } from "./compaction.js";
18
20
  import { filesPanel, freePath } from "./files-panel.js";
19
21
  import { debugPanel } from "./debug-panel.js";
20
22
  import { tokenCSS, tokenProp } from "./chat-theme.js";
@@ -39,9 +41,9 @@ const STRINGS = {
39
41
  attach: "Attach files", drop: "Drop files to attach", tooLarge: "is too large (max 20 MB)", remove: "Remove",
40
42
  toolsRunning: "Running", toolsDone: "Ran {n} tool calls", toolsDone1: "Ran 1 tool call", toolsFailed: "{n} failed",
41
43
  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}", actWeb: "searched the web {n} time(s)", actBrowse: "read {n} web page(s)", ingWeb: "Searching the web", ingBrowse: "Reading",
42
- web: "Web", webOn: "Web search: on", webOff: "Web search: off", webHint: "When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed",
44
+ web: "Web", webOn: "Web search: on", webOff: "Web search: off", webHint: "When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed", permAlways: "Always allow (this app)", sched: "Scheduled", schedNew: "New task", schedNone: "No scheduled tasks yet. Ask the AI (\"every weekday at 9, summarise the news\") or add one.", schedHint: "Tasks run only while this app is open, and wait until the chat is idle. A run missed while it was closed happens once when you next open it.", schedName: "Name", schedPrompt: "What to do", schedWhen: "When", schedOnce: "Once", schedEvery: "Every", schedDaily: "Daily / weekly", schedCron: "Cron", schedMin: "minutes", schedHour: "hours", schedDay: "days", schedCronHint: "minute hour day month weekday, e.g. 0 9 * * 1-5", schedNext: "Next {time}", schedNoNext: "Will not run again", schedPaused: "Paused", schedRunning: "Running", schedLast: "Last {time} · {status}", schedOk: "done", schedErr: "failed", schedStopped: "stopped", schedRunNow: "Run now", schedPause: "Pause", schedResume: "Resume", schedEdit: "Edit", schedOpen: "Open its conversation", schedDel: "Delete task", schedDelMsg: "Delete \"{name}\"? Its conversation stays.", schedSave: "Save", schedBusy: "Another scheduled task is running; try again when it ends.", schedByAI: "by AI", schedRunHead: "⏰ Scheduled task \"{name}\" · {time}\n(Running unattended: the user may not be watching.)", schedStarted: "Scheduled task \"{name}\" started", schedFailed: "Scheduled task \"{name}\" failed: {error}", schedNamePh: "e.g. Morning news digest", schedPromptPh: "What the AI should do each time. Write it to stand alone: the run does not see this conversation.", schedDayNames: "Sun,Mon,Tue,Wed,Thu,Fri,Sat", tSchedList: "Scheduled tasks", tSchedAdd: "Schedule \"{name}\"", tSchedUpdate: "Change scheduled task", tSchedRemove: "Remove scheduled task", permAutoNote: "Auto-run is on: the AI will no longer ask before deleting, overwriting or publishing. Turn it off in Settings → Tool permissions.",
43
45
  runCode: "Run code", 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",
44
- sTabModel: "Model", debug: "Debug", dCalls: "Calls", dRequests: "Requests", dEvents: "Events", dContext: "Context", dTools: "Tools", dClear: "Clear the record", dFilter: "Filter by type",
46
+ sTabModel: "Model", sTabContext: "Context", sCompact: "When the context is nearly full", sCompactSummary: "Summarise older turns (one extra model call)", sCompactTrim: "Only trim: drop old tool results, then the oldest turns", sCompactAt: "Start when fewer tokens than this are left", sKeepRecent: "Keep this many of the newest tokens word for word", sDefaultN: "Default ({n})", sCompactNote: "{model}: starts with {at} tokens left and keeps about {keep} word for word (capped at 20% / 40% of its {window} window)", sCompactNoteTrim: "{model}: trims with fewer than {at} tokens left (capped at 20% of its {window} window)", autoTrim: "Auto-trim", debug: "Debug", dCalls: "Calls", dRequests: "Requests", dEvents: "Events", dContext: "Context", dTools: "Tools", dClear: "Clear the record", dFilter: "Filter by type",
45
47
  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.",
46
48
  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",
47
49
  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.",
@@ -79,9 +81,9 @@ const STRINGS = {
79
81
  attach: "添加附件", drop: "松开即可添加附件", tooLarge: "太大了(最大 20 MB)", remove: "移除",
80
82
  toolsRunning: "正在执行", toolsDone: "执行了 {n} 个工具调用", toolsDone1: "执行了 1 个工具调用", toolsFailed: "{n} 个失败",
81
83
  actRead: "读取了 {n} 个文件", actList: "查看了 {n} 个目录", actSearch: "搜索了 {n} 次", actWrite: "写入了 {n} 个文件", actEdit: "修改了 {n} 个文件", actDelete: "删除了 {n} 个文件", actRun: "运行了 {n} 段代码", actAsk: "询问了你 {n} 次", actOther: "调用了 {name}", actWeb: "联网搜索了 {n} 次", actBrowse: "阅读了 {n} 个网页", ingWeb: "正在联网搜索", ingBrowse: "正在阅读",
82
- web: "联网", webOn: "联网搜索:已开启", webOff: "联网搜索:已关闭", webHint: "开启后 AI 可以搜索和阅读网页,查资料和最新信息;每次搜索、每读一个网页按次计费",
84
+ web: "联网", webOn: "联网搜索:已开启", webOff: "联网搜索:已关闭", webHint: "开启后 AI 可以搜索和阅读网页,查资料和最新信息;每次搜索、每读一个网页按次计费", permAlways: "以后都允许(本应用)", sched: "定时任务", schedNew: "新建", schedNone: "还没有定时任务。可以直接让 AI 安排(比如「每个工作日早上 9 点整理新闻」),或点新建。", schedHint: "定时任务只在本应用页面打开时运行,并等对话空闲时才开始;页面关闭期间错过的,下次打开时补跑一次。", schedName: "名称", schedPrompt: "要做什么", schedWhen: "时间", schedOnce: "一次", schedEvery: "每隔", schedDaily: "每天 / 每周", schedCron: "Cron", schedMin: "分钟", schedHour: "小时", schedDay: "天", schedCronHint: "分 时 日 月 周,如 0 9 * * 1-5", schedNext: "下次 {time}", schedNoNext: "不会再运行", schedPaused: "已暂停", schedRunning: "运行中", schedLast: "上次 {time} · {status}", schedOk: "完成", schedErr: "失败", schedStopped: "已停止", schedRunNow: "立即运行", schedPause: "暂停", schedResume: "恢复", schedEdit: "编辑", schedOpen: "打开它的对话", schedDel: "删除任务", schedDelMsg: "删除「{name}」?它的对话会保留。", schedSave: "保存", schedBusy: "另一个定时任务正在运行,结束后再试。", schedByAI: "AI 创建", schedRunHead: "⏰ 定时任务「{name}」 · {time}\n(无人值守运行:用户可能不在旁边。)", schedStarted: "定时任务「{name}」开始运行", schedFailed: "定时任务「{name}」失败:{error}", schedNamePh: "如:早间新闻摘要", schedPromptPh: "每次运行时 AI 要做的事。写完整:运行时看不到这段对话。", schedDayNames: "日,一,二,三,四,五,六", tSchedList: "查看定时任务", tSchedAdd: "安排定时任务「{name}」", tSchedUpdate: "修改定时任务", tSchedRemove: "删除定时任务", permAutoNote: "已开启自动执行:删除、覆盖、发布等操作也不再询问。可在设置 → 工具权限里关闭。",
83
85
  runCode: "运行代码", ingRead: "正在读取", ingList: "正在查看", ingSearch: "正在搜索", ingWrite: "正在写入", ingEdit: "正在修改", ingDelete: "正在删除", ingRun: "正在运行代码", ingAsk: "正在询问你", ingOther: "正在执行", current: "当前", jumpEnd: "回到最新",
84
- sTabModel: "模型", debug: "调试", dCalls: "调用", dRequests: "请求", dEvents: "事件", dContext: "上下文", dTools: "工具", dClear: "清空记录", dFilter: "按类型过滤",
86
+ sTabModel: "模型", sTabContext: "上下文", sCompact: "上下文快满时", sCompactSummary: "把较早的对话写成摘要(多一次模型调用)", sCompactTrim: "只裁剪:先删旧的工具结果,再删最早的对话", sCompactAt: "剩余少于多少 tokens 时开始", sKeepRecent: "原样保留最近多少 tokens", sDefaultN: "默认({n})", sCompactNote: "{model}:剩余 {at} tokens 时开始,原样保留约 {keep} tokens(最多为上下文 {window} 的 20% / 40%)", sCompactNoteTrim: "{model}:剩余少于 {at} tokens 时裁剪(最多为上下文 {window} 的 20%)", autoTrim: "自动裁剪", debug: "调试", dCalls: "调用", dRequests: "请求", dEvents: "事件", dContext: "上下文", dTools: "工具", dClear: "清空记录", dFilter: "按类型过滤",
85
87
  dNoCalls: "还没有工具调用。", dNoRequests: "还没有模型请求。每次调用模型都会记在这里,包括发了什么、收到什么。", dNoEvents: "还没有事件。",
86
88
  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} 次调用",
87
89
  rewindMsg: "它之后的对话会被删除,消息内容放回输入框。", rewindFiles: "同时把目录里的文件恢复到那一刻", rewindGone: "这条消息已不在对话里(可能已被压缩)。", rewindSnapshot: "{time} 时的 {n} 个文件({size})", rewindPartial: "超过 2 MB 的文件没进快照,会保持原样。", rewindGoneFile: "{path} 已不在目录里。",
@@ -168,13 +170,32 @@ const CSS = tokenCSS() + `
168
170
  .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}
169
171
  .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}
170
172
  .ra-skm.drop{outline:2px dashed var(--ra-accent);outline-offset:-4px}
173
+ .ra-schm .ra-skb.on{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
174
+ .ra-schm .ra-mi.ra-off .ra-mtt{color:var(--ra-fg-muted)}
175
+ .ra-schm .ra-mi small.ra-bad{color:var(--ra-red)}
176
+ .ra-schm .ra-mi small{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp:none}
177
+ .ra-schf{display:flex;flex-direction:column;gap:10px;padding:6px 8px 6px}
178
+ .ra-schf .ra-schh{font-size:13px;font-weight:600}
179
+ .ra-schf .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
180
+ .ra-chat .ra-schf input:not([type=checkbox]),.ra-chat .ra-schf textarea{font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;padding:6px 10px;min-height:34px;box-sizing:border-box;outline:0;width:100%;margin:0}
181
+ .ra-chat .ra-schf textarea{min-height:88px;resize:vertical;line-height:1.5}
182
+ .ra-chat .ra-schf input:focus,.ra-chat .ra-schf textarea:focus{border-color:var(--ra-accent);box-shadow:0 0 0 3px var(--ra-accent-subtle)}
183
+ .ra-schf .ra-row{display:flex;gap:8px;align-items:center}
184
+ .ra-schf .ra-row>*{flex:1;min-width:0}
185
+ .ra-schf .ra-row.ra-col2{flex-direction:column;align-items:stretch}
186
+ .ra-schf .ra-days{display:flex;gap:4px}
187
+ .ra-chat .ra-schf .ra-days button{flex:1;height:28px;border-radius:6px;border:1px solid var(--ra-border);font-size:12px;color:var(--ra-fg-muted)}
188
+ .ra-chat .ra-schf .ra-days button.on{background:var(--ra-accent-subtle);border-color:transparent;color:var(--ra-accent-fg);font-weight:600}
189
+ .ra-schf .ra-note{font-size:11.5px;color:var(--ra-fg-muted)}
190
+ .ra-schf .ra-note.err{color:var(--ra-red)}
191
+ .ra-schf .ra-btns{display:flex;justify-content:flex-end;gap:6px}
171
192
  .ra-set{padding:10px 12px;display:flex;flex-direction:column;gap:10px;width:min(360px,calc(100% - 24px))}
172
193
  /* The settings panel takes the chat's height under the header (a host may add fields of its own). */
173
194
  .ra-chat .ra-set{max-height:calc(100% - 72px)}
174
195
  .ra-set .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
175
196
  .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}
176
197
  .ra-set input:focus{border-color:var(--ra-accent);box-shadow:0 0 0 3px var(--ra-accent-subtle)}
177
- .ra-set .ra-row{display:flex;gap:8px;align-items:center}
198
+ .ra-set .ra-row{display:flex;gap:8px;align-items:center;padding:0}
178
199
  .ra-set .ra-row>*{flex:1;min-width:0}
179
200
  .ra-set .ra-lim{font-size:11px;color:var(--ra-fg-muted);margin-top:-4px}
180
201
  .ra-set .ra-btns{justify-content:space-between}
@@ -1019,8 +1040,9 @@ export function renderChat(target, opts) {
1019
1040
  injectStyles();
1020
1041
  const lang = pickLocale(opts.locale);
1021
1042
  const t = STRINGS[lang];
1022
- const { toolSettings, 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, webSearch: webSearchOpt, ...agentOpts } = opts;
1043
+ const { toolSettings, 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, fileDialog: fileDialogOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, webSearch: webSearchOpt, schedule: scheduleOpt, ...agentOpts } = opts;
1023
1044
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
1045
+ setFileDialog(fileDialogOpt);
1024
1046
  const provider = providerOpt ? toProvider(providerOpt) : clientOpt ? toProvider(clientOpt) : givenAgent?.provider ?? null;
1025
1047
  const project = provider?.name ?? agentOpts.appName ?? "app";
1026
1048
  // Shell.
@@ -1085,6 +1107,10 @@ export function renderChat(target, opts) {
1085
1107
  return (n) => { b.textContent = String(n); b.style.display = n ? "" : "none"; btn.title = n ? `${label} · ${n}` : label; };
1086
1108
  };
1087
1109
  const setSkillCount = countBadge(skillsBtn, t.skills);
1110
+ const schedBtn = h("button", "ra-btn ghost");
1111
+ schedBtn.type = "button";
1112
+ schedBtn.innerHTML = I.clock() + `<span>${escapeHTML(t.sched)}</span>`;
1113
+ const setSchedCount = countBadge(schedBtn, t.sched);
1088
1114
  const histBtn = h("button", "ra-btn ghost");
1089
1115
  histBtn.type = "button";
1090
1116
  histBtn.innerHTML = I.hist() + `<span>${escapeHTML(t.history)}</span>`;
@@ -1111,14 +1137,14 @@ export function renderChat(target, opts) {
1111
1137
  setBtn.title = t.settings;
1112
1138
  setBtn.setAttribute("aria-label", t.settings);
1113
1139
  // In a narrow chat the labels fold away and only the icons show: each button keeps its name.
1114
- for (const [btn, label] of [[debugBtn, t.debug], [filesBtn, t.files], [skillsBtn, t.skills], [histBtn, t.history], [newBtn, t.newChat], [clearBtn, t.clearChat]]) {
1140
+ for (const [btn, label] of [[debugBtn, t.debug], [filesBtn, t.files], [skillsBtn, t.skills], [schedBtn, t.sched], [histBtn, t.history], [newBtn, t.newChat], [clearBtn, t.clearChat]]) {
1115
1141
  btn.setAttribute("aria-label", label);
1116
1142
  if (!btn.title)
1117
1143
  btn.title = label;
1118
1144
  }
1119
1145
  for (const el of [...(headerActions ?? []), ...(headerEnd ?? []), ...(composerTop ? [composerTop] : []), ...(emptyState instanceof HTMLElement ? [emptyState] : [])])
1120
1146
  el.classList.add("ra-host");
1121
- head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, histBtn, newBtn, clearBtn, ...(headerActions ?? []), setBtn, ...(headerEnd ?? []));
1147
+ head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, schedBtn, histBtn, newBtn, clearBtn, ...(headerActions ?? []), setBtn, ...(headerEnd ?? []));
1122
1148
  if (title === false)
1123
1149
  head.style.display = "none";
1124
1150
  const log = h("div", "ra-log");
@@ -1244,6 +1270,36 @@ export function renderChat(target, opts) {
1244
1270
  for (const a of live.values())
1245
1271
  applyWeb(a);
1246
1272
  });
1273
+ // 自动执行: every tool runs without asking, turned on from a permission question or the settings; kept per app (the app's `permissions` until the user chooses).
1274
+ const PERM_KEY = `__runapps_agent_chat:${project}:perm`;
1275
+ const permOwn = !givenAgent && typeof agentOpts.permissions !== "function";
1276
+ const permShown = permOwn && permissionsSetting !== false;
1277
+ let permChoice = (() => { if (!permShown)
1278
+ return null; try {
1279
+ const v = localStorage.getItem(PERM_KEY);
1280
+ if (v === "ask" || v === "auto")
1281
+ return v;
1282
+ }
1283
+ catch { /* private mode */ } return null; })();
1284
+ const permAuto = () => (permChoice ?? agentOpts.permissions ?? "ask") === "auto";
1285
+ /** Sets the user's choice (null: back to the app's) on every open session, kept per app. */
1286
+ const setPerm = (p, quiet = false) => {
1287
+ const was = permAuto();
1288
+ permChoice = p;
1289
+ if (permShown) {
1290
+ try {
1291
+ if (p)
1292
+ localStorage.setItem(PERM_KEY, p);
1293
+ else
1294
+ localStorage.removeItem(PERM_KEY);
1295
+ }
1296
+ catch { /* private mode */ }
1297
+ }
1298
+ for (const a of live.values())
1299
+ a.configure({ permissions: p ?? agentOpts.permissions ?? "ask" });
1300
+ if (!quiet && !was && permAuto())
1301
+ ui.notify(t.permAutoNote);
1302
+ };
1247
1303
  left.append(attachBtn, webBtn, ...hostActions, hint);
1248
1304
  bar.append(left, acts);
1249
1305
  box.append(cmds, files, ta, bar, fileInput);
@@ -1296,6 +1352,8 @@ export function renderChat(target, opts) {
1296
1352
  let cmdIndex = 0;
1297
1353
  let cmdFrame = null;
1298
1354
  let unsub = [];
1355
+ /** Run once when the chat is unmounted. */
1356
+ const unmountHooks = [];
1299
1357
  let menu = null;
1300
1358
  let mounted = true;
1301
1359
  // A short chat (a phone held sideways, a small panel) keeps the transcript readable: the composer is compact.
@@ -1351,7 +1409,8 @@ export function renderChat(target, opts) {
1351
1409
  const wake = (id, shown = true) => { const w = waiters.get(id); waiters.delete(id); waiting.delete(id); w?.forEach((f) => f(shown)); };
1352
1410
  /** 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). */
1353
1411
  const uiFor = (id) => ({
1354
- confirm: async (title, message, o) => ((await whenCurrent(id, o?.signal)) ? ui.confirm(title, message, o) : false),
1412
+ // A permission question gets "Always allow (this app)", which turns auto-run on (a tool's own `always` keeps its place).
1413
+ confirm: async (title, message, o) => ((await whenCurrent(id, o?.signal)) ? ui.confirm(title, message, o?.permission && permShown && !o.always ? { ...o, always: { label: t.permAlways, onChoose: () => setPerm("auto") } } : o) : false),
1355
1414
  select: async (title, options, o) => ((await whenCurrent(id, o?.signal)) ? ui.select(title, options, o) : null),
1356
1415
  input: async (title, o) => ((await whenCurrent(id, o?.signal)) ? ui.input(title, o) : null),
1357
1416
  notify: (m, l) => ui.notify(m, l),
@@ -1359,7 +1418,7 @@ export function renderChat(target, opts) {
1359
1418
  /** Whether rewinding may restore files: only a directory of the session's own, kept in IndexedDB (not a folder on disk, not shared). */
1360
1419
  const restorable = (a) => !!a.workspace && typeof wsOpt === "function" && !a.workspace.root;
1361
1420
  const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || a.queued.length > 0 || waiting.has(a.id)));
1362
- 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; };
1421
+ const titleOfAgent = (a) => { const text = a.title ?? 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; };
1363
1422
  const markBackground = () => histBtn.classList.toggle("ra-bg", background().length > 0);
1364
1423
  /** The Chats count: the conversations, open one included, shown once there is another (redrawn after a run, a switch, a delete). */
1365
1424
  let histTimer = null;
@@ -2518,7 +2577,14 @@ export function renderChat(target, opts) {
2518
2577
  },
2519
2578
  };
2520
2579
  /** Every tool the chat's agents get: the host's, plus the built-in suggestion tool. */
2521
- const chatTools = [...(agentOpts.tools ?? []), ...(nextPrompt ? [nextPromptTool] : [])];
2580
+ // Scheduled tasks: the store, and the agent's tools over it (their cards in the chat's language).
2581
+ const schedCfg = scheduleOpt ? (scheduleOpt === true ? {} : scheduleOpt) : null;
2582
+ const schedStore = schedCfg ? schedCfg.store ?? localSchedules(`__runapps_agent_chat:${project}:schedules`) : null;
2583
+ const schedLabels = { schedule_list: () => t.tSchedList, schedule_add: (a) => t.tSchedAdd.replace("{name}", a.name ?? ""), schedule_update: () => t.tSchedUpdate, schedule_remove: () => t.tSchedRemove };
2584
+ const schedTools = schedStore && schedCfg.tools !== false
2585
+ ? scheduleTools(schedStore, { ...schedCfg, onChange: () => refreshSched() }).map((x) => ({ ...x, display: { ...x.display, icon: I.clock(), label: schedLabels[x.name] } }))
2586
+ : [];
2587
+ const chatTools = [...(agentOpts.tools ?? []), ...(nextPrompt ? [nextPromptTool] : []), ...schedTools];
2522
2588
  const hiddenTools = new Set(chatTools.filter((x) => x.display?.hidden).map((x) => x.name));
2523
2589
  /** 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. */
2524
2590
  const syncSend = () => {
@@ -2721,7 +2787,7 @@ export function renderChat(target, opts) {
2721
2787
  renderFiles();
2722
2788
  ta.focus();
2723
2789
  };
2724
- attachBtn.addEventListener("click", () => fileInput.click());
2790
+ attachBtn.addEventListener("click", () => chooseFiles(fileInput, (picked) => void addFiles(picked)));
2725
2791
  fileInput.addEventListener("change", () => { void addFiles(fileInput.files); fileInput.value = ""; });
2726
2792
  ta.addEventListener("paste", (e) => {
2727
2793
  const items = Array.from(e.clipboardData?.files ?? []);
@@ -2981,6 +3047,8 @@ export function renderChat(target, opts) {
2981
3047
  }
2982
3048
  }
2983
3049
  });
3050
+ // The app's own compaction: what "default" means in the settings.
3051
+ const hostCompaction = { summarize: agentOpts.compaction !== false, ...(typeof agentOpts.compaction === "object" ? agentOpts.compaction : {}) };
2984
3052
  const SET_KEY = `__runapps_agent_chat:${project}:settings`;
2985
3053
  const readSettings = () => { try {
2986
3054
  return JSON.parse(localStorage.getItem(SET_KEY) || "{}");
@@ -2996,7 +3064,6 @@ export function renderChat(target, opts) {
2996
3064
  }
2997
3065
  catch { /* private mode */ } };
2998
3066
  let userSettings = givenAgent ? {} : readSettings();
2999
- let permChoice = null; // not persisted: allowing everything is a per-page decision
3000
3067
  const hasSettings = opts.settings ?? !givenAgent;
3001
3068
  let settingsTab = 0;
3002
3069
  if (!hasSettings)
@@ -3013,7 +3080,7 @@ export function renderChat(target, opts) {
3013
3080
  /** Puts the user's settings on an agent (every open session gets the same ones). */
3014
3081
  const applyTo = (ag, s, p) => {
3015
3082
  const hostEffort = agentOpts.extra?.reasoning_effort;
3016
- 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) });
3083
+ 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), compaction: { summarize: s.summarize ?? hostCompaction.summarize, reserveTokens: s.reserveTokens ?? hostCompaction.reserveTokens, keepRecentTokens: s.keepRecentTokens ?? hostCompaction.keepRecentTokens } });
3017
3084
  modelEl.textContent = ag.model ?? "";
3018
3085
  modelEl.style.display = ag.model ? "" : "none";
3019
3086
  };
@@ -3127,6 +3194,50 @@ export function renderChat(target, opts) {
3127
3194
  own.append(field(t.sModel, modelSel.el), lim, field(t.sEffort, effortSel.el), effortNote, field(t.sMaxTurns, turns), field(t.sMaxTokens, tokRow));
3128
3195
  if (permissionsSetting !== false)
3129
3196
  own.append(field(t.sPerms, perm.el));
3197
+ // Context: how the conversation is kept within the model's window.
3198
+ const cc = cur.compaction;
3199
+ const sumSel = sel([{ value: "summary", label: t.sCompactSummary }, { value: "trim", label: t.sCompactTrim }], cc.summarize === false ? "trim" : "summary");
3200
+ const numPick = (value, def) => {
3201
+ const mode = sel([{ value: "auto", label: t.sDefaultN.replace("{n}", fmtTokens(def)) }, { value: "n", label: t.sCustomN }], value !== undefined && value !== def ? "n" : "auto");
3202
+ const input = h("input");
3203
+ input.type = "number";
3204
+ input.min = "1024";
3205
+ input.step = "1024";
3206
+ input.value = String(value ?? def);
3207
+ const row = h("div", "ra-row");
3208
+ row.append(mode.el, input);
3209
+ const sync = () => { input.style.display = mode.value === "n" ? "" : "none"; };
3210
+ mode.el.addEventListener("change", sync);
3211
+ sync();
3212
+ /** The number chosen, or undefined for the default. */
3213
+ const read = () => { if (mode.value !== "n")
3214
+ return undefined; const v = parseInt(input.value, 10); return Number.isFinite(v) && v >= 1024 ? v : undefined; };
3215
+ return { row, read, mode, input };
3216
+ };
3217
+ const atPick = numPick(cc.reserveTokens, hostCompaction.reserveTokens ?? DEFAULT_COMPACTION.reserveTokens);
3218
+ const keepPick = numPick(cc.keepRecentTokens, hostCompaction.keepRecentTokens ?? DEFAULT_COMPACTION.keepRecentTokens);
3219
+ const keepField = field(t.sKeepRecent, keepPick.row);
3220
+ const compactNote = h("div", "ra-lim");
3221
+ const showCompact = () => {
3222
+ const summary = sumSel.value === "summary";
3223
+ keepField.style.display = summary ? "" : "none";
3224
+ // What the choice comes to with the model picked above: the thresholds are capped by its window.
3225
+ const m = chosenModel();
3226
+ const inCap = agentOpts.maxInputTokens;
3227
+ const known = typeof m?.max_input_tokens === "number" && m.max_input_tokens > 0 ? m.max_input_tokens : 128_000;
3228
+ const window = typeof inCap === "number" ? Math.min(inCap, known) : known;
3229
+ const r = resolveSettings(window, { reserveTokens: atPick.read() ?? hostCompaction.reserveTokens, keepRecentTokens: keepPick.read() ?? hostCompaction.keepRecentTokens });
3230
+ const name = m?.id ?? (modelSel.value || t.sDefault);
3231
+ compactNote.textContent = (summary ? t.sCompactNote.replace("{keep}", fmtTokens(r.keepRecentTokens)) : t.sCompactNoteTrim)
3232
+ .replace("{model}", name).replace("{at}", fmtTokens(r.reserveTokens)).replace("{window}", fmtTokens(window));
3233
+ };
3234
+ for (const el of [sumSel.el, modelSel.el, atPick.mode.el, keepPick.mode.el])
3235
+ el.addEventListener("change", showCompact);
3236
+ for (const el of [atPick.input, keepPick.input])
3237
+ el.addEventListener("input", showCompact);
3238
+ showCompact();
3239
+ const ctxPane = h("div", "ra-pane");
3240
+ ctxPane.append(field(t.sCompact, sumSel.el), field(t.sCompactAt, atPick.row), keepField, compactNote);
3130
3241
  // The host's own settings, each tab a pane: drawn here, read back on Apply.
3131
3242
  const hostReads = [];
3132
3243
  const hostPane = (tab) => {
@@ -3162,12 +3273,12 @@ export function renderChat(target, opts) {
3162
3273
  }
3163
3274
  return pane;
3164
3275
  };
3165
- const panes = [own, ...(settingsTabs ?? []).map(hostPane)];
3276
+ const panes = [own, ctxPane, ...(settingsTabs ?? []).map(hostPane)];
3166
3277
  if (panes.length > 1) {
3167
3278
  // Tabs: the chat's own first, then the host's; the panel reopens on the tab last shown.
3168
3279
  const bar = h("div", "ra-tabs");
3169
3280
  bar.setAttribute("role", "tablist");
3170
- const tabs = [t.sTabModel, ...(settingsTabs ?? []).map((x) => x.label)].map((label, i) => {
3281
+ const tabs = [t.sTabModel, t.sTabContext, ...(settingsTabs ?? []).map((x) => x.label)].map((label, i) => {
3171
3282
  const b = h("button", "ra-tab", label);
3172
3283
  b.type = "button";
3173
3284
  b.setAttribute("role", "tab");
@@ -3205,7 +3316,7 @@ export function renderChat(target, opts) {
3205
3316
  }
3206
3317
  userSettings = {};
3207
3318
  writeSettings({});
3208
- permChoice = null;
3319
+ setPerm(null, true);
3209
3320
  for (const ag of live.values())
3210
3321
  applyTo(ag, {}, null);
3211
3322
  closeMenu();
@@ -3227,8 +3338,17 @@ export function renderChat(target, opts) {
3227
3338
  }
3228
3339
  if (effortSel.value && !effortSel.disabled)
3229
3340
  next.reasoningEffort = effortSel.value;
3230
- if (perm.value === "ask" || perm.value === "auto")
3231
- permChoice = perm.value;
3341
+ if ((perm.value === "ask" || perm.value === "auto") && perm.value !== (permAuto() ? "auto" : "ask"))
3342
+ setPerm(perm.value);
3343
+ const summarize = sumSel.value === "summary";
3344
+ if (summarize !== hostCompaction.summarize)
3345
+ next.summarize = summarize;
3346
+ const at = atPick.read();
3347
+ if (at !== undefined)
3348
+ next.reserveTokens = at;
3349
+ const keep = keepPick.read();
3350
+ if (keep !== undefined)
3351
+ next.keepRecentTokens = keep;
3232
3352
  for (const read of hostReads)
3233
3353
  read();
3234
3354
  saveSettings(next);
@@ -3340,7 +3460,7 @@ export function renderChat(target, opts) {
3340
3460
  });
3341
3461
  document.addEventListener("click", onDocClick, true);
3342
3462
  function onDocClick(e) { if (e.target?.closest?.(".ra-selp"))
3343
- return; if (menu && !menu.contains(e.target) && !histBtn.contains(e.target) && !setBtn.contains(e.target) && !skillsBtn.contains(e.target) && !useBtn.contains(e.target))
3463
+ return; if (menu && !menu.contains(e.target) && !histBtn.contains(e.target) && !setBtn.contains(e.target) && !skillsBtn.contains(e.target) && !schedBtn.contains(e.target) && !useBtn.contains(e.target))
3344
3464
  closeMenu(); }
3345
3465
  /* --- skills menu --- */
3346
3466
  const skillInput = h("input");
@@ -3401,7 +3521,7 @@ export function renderChat(target, opts) {
3401
3521
  const up = h("button", "ra-btn xs solid");
3402
3522
  up.type = "button";
3403
3523
  up.innerHTML = I.upload(13) + `<span>${escapeHTML(t.uploadZip)}</span>`;
3404
- up.addEventListener("click", () => skillInput.click());
3524
+ up.addEventListener("click", () => chooseFiles(skillInput, (picked) => void installZips(picked)));
3405
3525
  if (!ws.userSkillsDir)
3406
3526
  up.style.display = "none";
3407
3527
  head.append(h("span", "", skills.length ? `${t.skills} · ${skills.length}` : t.skills), up);
@@ -3463,6 +3583,291 @@ export function renderChat(target, opts) {
3463
3583
  mine.addEventListener("drop", (e) => { e.preventDefault(); e.stopPropagation(); mine.classList.remove("drop"); void installZips(e.dataTransfer?.files); });
3464
3584
  };
3465
3585
  skillsBtn.addEventListener("click", () => void openSkills());
3586
+ /* --- scheduled tasks --- */
3587
+ if (!schedStore)
3588
+ schedBtn.style.display = "none";
3589
+ const schedLimits = { minMinutes: schedCfg?.minMinutes, maxTasks: schedCfg?.maxTasks };
3590
+ const dayNames = t.schedDayNames.split(",");
3591
+ const zhWords = /[\u4e00-\u9fff]/.test(t.sched);
3592
+ const fmtShort = (ms) => { const s = formatLocalTime(ms); return s.slice(0, 4) === String(new Date().getFullYear()) ? s.slice(5) : s; };
3593
+ /** Runs one task: in its own conversation (made on its first run), or the one conversation when the chat keeps only one. */
3594
+ const runScheduled = async (task) => {
3595
+ await ready;
3596
+ const text = `${t.schedRunHead.replace("{name}", task.name).replace("{time}", formatLocalTime(Date.now()))}\n\n${task.prompt}`;
3597
+ let a;
3598
+ if (givenAgent || oneChat)
3599
+ a = agent ?? givenAgent;
3600
+ else {
3601
+ const sid = task.session ?? `sched_${task.id}`;
3602
+ if (!task.session) {
3603
+ const cur = await schedStore.get(task.id);
3604
+ if (cur)
3605
+ await schedStore.put({ ...cur, session: sid });
3606
+ }
3607
+ a = agent?.id === sid ? agent : live.get(sid) ?? await makeAgent(sid);
3608
+ if (a !== agent) {
3609
+ await a.ready();
3610
+ live.set(sid, a);
3611
+ watchBackground(a);
3612
+ }
3613
+ }
3614
+ // Its own conversation is named after it (the first message would be the run's header).
3615
+ if (!givenAgent && !oneChat)
3616
+ a.setTitle(`⏰ ${task.name}`);
3617
+ ui.notify(t.schedStarted.replace("{name}", task.name));
3618
+ const r = a === agent ? await promptFromHost(text) : await a.prompt(text);
3619
+ refreshHistCount();
3620
+ if (r.reason === "error" || r.reason === "max_turns")
3621
+ ui.notify(t.schedFailed.replace("{name}", task.name).replace("{error}", r.error?.message ?? r.reason), "warning");
3622
+ return { status: r.reason === "done" ? "ok" : r.reason === "aborted" ? "stopped" : "error", ...(r.error ? { note: r.error.message } : r.reason === "max_turns" ? { note: "turn limit" } : {}), ...(r.usage?.total_cost ? { cost: r.usage.total_cost } : {}) };
3623
+ };
3624
+ /** Idle: nothing running in any conversation, no question open, not switching, the user not typing. */
3625
+ const schedIdle = () => mounted && !switching && !!agent && asked === 0 && waiting.size === 0
3626
+ && ![...live.values()].some((a) => a.busy || a.queued.length > 0)
3627
+ && !(document.activeElement === ta && ta.value.trim());
3628
+ const scheduler = schedStore ? new Scheduler({ store: schedStore, run: runScheduled, idle: schedIdle, lockPrefix: `__runapps_agent_chat:${project}:schedules`, onChange: () => refreshSched() }) : null;
3629
+ if (scheduler) {
3630
+ // Each run that ends is a moment the chat may have become idle: look again.
3631
+ const again = () => setTimeout(() => void scheduler.tick(), 1500);
3632
+ let lastBusy = false;
3633
+ const poll = setInterval(() => { const b = !schedIdle(); if (lastBusy && !b)
3634
+ again(); lastBusy = b; }, 3000);
3635
+ unmountHooks.push(() => { clearInterval(poll); scheduler.stop(); });
3636
+ }
3637
+ let schedView = "list";
3638
+ const refreshSched = () => {
3639
+ if (!schedStore)
3640
+ return;
3641
+ void schedStore.list().then((all) => {
3642
+ setSchedCount(all.filter((x) => x.enabled).length);
3643
+ if (menu?.classList.contains("ra-schm") && schedView === "list")
3644
+ drawSchedList(menu);
3645
+ }).catch(() => undefined);
3646
+ };
3647
+ const openSched = () => {
3648
+ if (menu) {
3649
+ const was = menu.classList.contains("ra-schm");
3650
+ closeMenu();
3651
+ if (was)
3652
+ return;
3653
+ }
3654
+ if (!schedStore)
3655
+ return;
3656
+ const mine = h("div", "ra-menu ra-skm ra-schm");
3657
+ menu = mine;
3658
+ placeMenu(mine);
3659
+ void drawSchedList(mine);
3660
+ };
3661
+ const drawSchedList = async (mine) => {
3662
+ schedView = "list";
3663
+ let all = [];
3664
+ try {
3665
+ all = await schedStore.list();
3666
+ }
3667
+ catch (err) {
3668
+ ui.notify(err.message, "error");
3669
+ }
3670
+ if (menu !== mine)
3671
+ return;
3672
+ all.sort((a, b) => (a.enabled === b.enabled ? (a.next ?? Infinity) - (b.next ?? Infinity) : a.enabled ? -1 : 1));
3673
+ mine.replaceChildren();
3674
+ const head = h("div", "ra-skh");
3675
+ const add = h("button", "ra-btn xs solid");
3676
+ add.type = "button";
3677
+ add.innerHTML = I.plus(13) + `<span>${escapeHTML(t.schedNew)}</span>`;
3678
+ add.addEventListener("click", () => drawSchedForm(mine, null));
3679
+ head.append(h("span", "", all.length ? `${t.sched} · ${all.length}` : t.sched), add);
3680
+ mine.append(head);
3681
+ if (!all.length)
3682
+ mine.append(h("div", "ra-none", t.schedNone));
3683
+ const statusWord = { ok: t.schedOk, error: t.schedErr, stopped: t.schedStopped };
3684
+ for (const task of all) {
3685
+ const row = h("div", "ra-mi" + (task.enabled ? "" : " ra-off"));
3686
+ const b = h("button");
3687
+ b.type = "button";
3688
+ b.title = t.schedEdit;
3689
+ const name = h("span", "ra-mt");
3690
+ const running = scheduler?.running.has(task.id);
3691
+ if (running)
3692
+ name.append(h("span", "ra-spin"));
3693
+ name.append(h("span", "ra-mtt", task.name));
3694
+ if (running)
3695
+ name.append(h("span", "ra-skb on", t.schedRunning));
3696
+ else if (!task.enabled)
3697
+ name.append(h("span", "ra-skb", t.schedPaused));
3698
+ if (task.by === "agent")
3699
+ name.append(h("span", "ra-skb", t.schedByAI));
3700
+ const when = `${describeSchedule(task.schedule, zhWords ? "zh" : "en")} · ${task.enabled && task.next ? t.schedNext.replace("{time}", fmtShort(task.next)) : task.enabled ? t.schedNoNext : t.schedPaused}`;
3701
+ b.append(name, h("small", "", when));
3702
+ if (task.last)
3703
+ b.append(h("small", task.last.status === "ok" ? "" : "ra-bad", t.schedLast.replace("{time}", fmtShort(task.last.at)).replace("{status}", statusWord[task.last.status] + (task.last.note ? ` (${task.last.note})` : ""))));
3704
+ b.addEventListener("click", () => drawSchedForm(mine, task));
3705
+ 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; };
3706
+ const runB = act(I.play(), t.schedRunNow, () => {
3707
+ void scheduler.runNow(task.id).then((ok) => { if (!ok)
3708
+ ui.notify(t.schedBusy, "warning"); });
3709
+ setTimeout(refreshSched, 100);
3710
+ });
3711
+ const pauseB = act(task.enabled ? I.pause() : I.clock(13), task.enabled ? t.schedPause : t.schedResume, async () => {
3712
+ try {
3713
+ const cur = await schedStore.get(task.id);
3714
+ if (cur)
3715
+ await schedStore.put(changeTask(cur, { enabled: !cur.enabled }, schedLimits));
3716
+ }
3717
+ catch (err) {
3718
+ ui.notify(err.message, "error");
3719
+ }
3720
+ refreshSched();
3721
+ });
3722
+ const openB = act(I.message(), t.schedOpen, () => { closeMenu(); if (task.session)
3723
+ void resume(task.session).catch((err) => ui.notify(err.message, "error")); });
3724
+ if (!task.session || givenAgent || oneChat)
3725
+ openB.style.display = "none";
3726
+ const del = act(I.trash(), t.schedDel, async () => {
3727
+ closeMenu();
3728
+ if (!(await modalConfirm(root, t.schedDel, t.schedDelMsg.replace("{name}", task.name), { danger: true, ok: t.delete, cancel: t.cancel })))
3729
+ return;
3730
+ try {
3731
+ await schedStore.delete(task.id);
3732
+ }
3733
+ catch (err) {
3734
+ ui.notify(err.message, "error");
3735
+ }
3736
+ refreshSched();
3737
+ }, "ra-x");
3738
+ row.append(b, runB, pauseB, openB, del);
3739
+ mine.append(row);
3740
+ }
3741
+ mine.append(h("div", "ra-skf", t.schedHint));
3742
+ };
3743
+ /** The add / edit form, in the same menu. */
3744
+ const drawSchedForm = (mine, task) => {
3745
+ schedView = "form";
3746
+ for (const b of menuSelects.splice(0))
3747
+ b.close();
3748
+ mine.replaceChildren();
3749
+ const form = h("div", "ra-schf");
3750
+ const field = (label, ...els) => { const l = h("div", "ra-fld"); l.append(h("span", "", label), ...els); return l; };
3751
+ const nameIn = h("input");
3752
+ nameIn.type = "text";
3753
+ nameIn.placeholder = t.schedNamePh;
3754
+ nameIn.value = task?.name ?? "";
3755
+ const promptIn = h("textarea");
3756
+ promptIn.placeholder = t.schedPromptPh;
3757
+ promptIn.value = task?.prompt ?? "";
3758
+ const s0 = task?.schedule ?? { type: "daily", time: "09:00" };
3759
+ const typeSel = selectBox(root, { options: [{ value: "once", label: t.schedOnce }, { value: "every", label: t.schedEvery }, { value: "daily", label: t.schedDaily }, { value: "cron", label: t.schedCron }], value: s0.type });
3760
+ menuSelects.push(typeSel);
3761
+ // once
3762
+ const atIn = h("input");
3763
+ atIn.type = "datetime-local";
3764
+ const at0 = s0.type === "once" ? parseLocalTime(s0.at) : Date.now() + 3600_000;
3765
+ atIn.value = formatLocalTime(Number.isFinite(at0) ? at0 : Date.now() + 3600_000).replace(" ", "T");
3766
+ // every
3767
+ const everyN = h("input");
3768
+ everyN.type = "number";
3769
+ everyN.min = "1";
3770
+ everyN.step = "1";
3771
+ const m0 = s0.type === "every" ? s0.minutes : 60;
3772
+ const unit0 = m0 % 1440 === 0 ? "1440" : m0 % 60 === 0 ? "60" : "1";
3773
+ everyN.value = String(m0 / Number(unit0));
3774
+ const unitSel = selectBox(root, { options: [{ value: "1", label: t.schedMin }, { value: "60", label: t.schedHour }, { value: "1440", label: t.schedDay }], value: unit0 });
3775
+ menuSelects.push(unitSel);
3776
+ const everyRow = h("div", "ra-row");
3777
+ everyRow.append(everyN, unitSel.el);
3778
+ // daily
3779
+ const timeIn = h("input");
3780
+ timeIn.type = "time";
3781
+ timeIn.value = s0.type === "daily" ? s0.time : "09:00";
3782
+ const days = new Set(s0.type === "daily" && s0.days?.length ? s0.days : [0, 1, 2, 3, 4, 5, 6]);
3783
+ const dayRow = h("div", "ra-days");
3784
+ // Monday first.
3785
+ for (const d of [1, 2, 3, 4, 5, 6, 0]) {
3786
+ const db = h("button", days.has(d) ? "on" : "", dayNames[d]);
3787
+ db.type = "button";
3788
+ db.addEventListener("click", () => { if (days.has(d)) {
3789
+ if (days.size > 1)
3790
+ days.delete(d);
3791
+ }
3792
+ else
3793
+ days.add(d); db.classList.toggle("on", days.has(d)); preview(); });
3794
+ dayRow.append(db);
3795
+ }
3796
+ const dailyBox = h("div", "ra-row ra-col2");
3797
+ dailyBox.append(timeIn, dayRow);
3798
+ // cron
3799
+ const cronIn = h("input");
3800
+ cronIn.type = "text";
3801
+ cronIn.placeholder = "0 9 * * 1-5";
3802
+ cronIn.value = s0.type === "cron" ? s0.cron : "";
3803
+ const cronBox = h("div", "ra-fld");
3804
+ cronBox.append(cronIn, h("span", "ra-note", t.schedCronHint));
3805
+ const whenBox = h("div", "ra-fld");
3806
+ const note = h("div", "ra-note");
3807
+ const build = () => {
3808
+ switch (typeSel.value) {
3809
+ case "once": return { type: "once", at: atIn.value.replace("T", " ") };
3810
+ case "every": return { type: "every", minutes: Math.round(Number(everyN.value) * Number(unitSel.value)) };
3811
+ case "cron": return { type: "cron", cron: cronIn.value.trim() };
3812
+ default: return { type: "daily", time: timeIn.value, ...(days.size < 7 ? { days: [...days].sort((a, b) => a - b) } : {}) };
3813
+ }
3814
+ };
3815
+ const preview = () => {
3816
+ const sc = build();
3817
+ const problem = checkSchedule(sc, schedLimits.minMinutes ?? 5);
3818
+ const nx = problem ? null : nextRun(sc, Date.now());
3819
+ note.textContent = problem ?? (nx ? t.schedNext.replace("{time}", formatLocalTime(nx)) : t.schedNoNext);
3820
+ note.classList.toggle("err", !!problem || !nx);
3821
+ save.disabled = !!problem || !nx || !nameIn.value.trim() || !promptIn.value.trim();
3822
+ };
3823
+ const showType = () => {
3824
+ const v = typeSel.value;
3825
+ whenBox.replaceChildren(typeSel.el, ...(v === "once" ? [atIn] : v === "every" ? [everyRow] : v === "cron" ? [cronBox] : [dailyBox]));
3826
+ preview();
3827
+ };
3828
+ typeSel.el.addEventListener("change", showType);
3829
+ unitSel.el.addEventListener("change", preview);
3830
+ for (const el of [nameIn, promptIn, atIn, everyN, timeIn, cronIn])
3831
+ el.addEventListener("input", preview);
3832
+ const btns = h("div", "ra-btns");
3833
+ const cancel = h("button", "ra-btn xs ghost", t.cancel);
3834
+ cancel.type = "button";
3835
+ const save = h("button", "ra-btn xs solid", t.schedSave);
3836
+ save.type = "button";
3837
+ cancel.addEventListener("click", () => { for (const b of menuSelects.splice(0))
3838
+ b.close(); void drawSchedList(mine); });
3839
+ save.addEventListener("click", async () => {
3840
+ try {
3841
+ const fields = { name: nameIn.value, prompt: promptIn.value, schedule: build() };
3842
+ if (task) {
3843
+ const cur = await schedStore.get(task.id);
3844
+ if (!cur)
3845
+ throw new Error("gone");
3846
+ await schedStore.put(changeTask(cur, { ...fields, enabled: true }, schedLimits));
3847
+ }
3848
+ else {
3849
+ if ((await schedStore.list()).length >= (schedLimits.maxTasks ?? 20))
3850
+ throw new Error(`${schedLimits.maxTasks ?? 20} tasks at most`);
3851
+ await schedStore.put(makeTask({ ...fields, by: "user" }, schedLimits));
3852
+ }
3853
+ for (const b of menuSelects.splice(0))
3854
+ b.close();
3855
+ await drawSchedList(mine);
3856
+ refreshSched();
3857
+ }
3858
+ catch (err) {
3859
+ note.textContent = err.message;
3860
+ note.classList.add("err");
3861
+ }
3862
+ });
3863
+ btns.append(cancel, save);
3864
+ form.append(h("div", "ra-schh", task ? t.schedEdit : t.schedNew), field(t.schedName, nameIn), field(t.schedPrompt, promptIn), field(t.schedWhen, whenBox), note, btns);
3865
+ mine.append(form);
3866
+ showType();
3867
+ queueMicrotask(() => (task ? promptIn : nameIn).focus());
3868
+ };
3869
+ schedBtn.addEventListener("click", () => openSched());
3870
+ refreshSched();
3466
3871
  const fail = (err) => ui.notify(err.message, "error");
3467
3872
  let compacting = false;
3468
3873
  /** The conversation as Markdown: what was said, and the tools each turn called. */
@@ -3763,14 +4168,13 @@ export function renderChat(target, opts) {
3763
4168
  const price = priceOf(info);
3764
4169
  const pct = Math.round((c.used / c.window) * 100);
3765
4170
  const u = a.usage;
3766
- const comp = agentOpts.compaction;
3767
4171
  const lines = [
3768
4172
  `- ${t.sModel}: ${a.model || (await loadModels()).find((m) => m.is_default)?.id || t.sDefault}`,
3769
4173
  `- ${t.context}: ${pct < 1 && c.used ? "<1" : pct}% · ${fmtTokens(c.used)} / ${fmtTokens(c.window)} tokens · ${t.sMaxTokens} ${fmtTokens(lim.output)}`,
3770
4174
  price ? `- ${t.sPrice}: ${price}` : "",
3771
4175
  `- ${t.messagesLabel}: ${a.messages.length}`,
3772
4176
  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)))}` : "",
3773
- comp === false ? "" : `- ${t.autoCompact}: ${t.autoCompactAt.replace("{n}", fmtTokens(Math.min(16_384, Math.floor(c.window * 0.2))))}`,
4177
+ `- ${compactLine(a, c.window)}`,
3774
4178
  a.workspace ? `- ${t.directory}: \`${a.workspace.id}\`` : "",
3775
4179
  ].filter(Boolean);
3776
4180
  addNote(t.context, lines.join("\n"));
@@ -3852,6 +4256,8 @@ export function renderChat(target, opts) {
3852
4256
  });
3853
4257
  };
3854
4258
  const cap = (x) => x.charAt(0).toUpperCase() + x.slice(1);
4259
+ /** "Auto-compaction: when less than 16k tokens are left" (or Auto-trim), as the agent will do it now. */
4260
+ const compactLine = (a, window) => { const c = a.compactionFor(window); return `${c.summarize ? t.autoCompact : t.autoTrim}: ${t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens))}`; };
3855
4261
  const pctOf = (used, window) => { const p = used / window; return used && p < 0.01 ? "<1%" : `${Math.round(Math.min(1, p) * 100)}%`; };
3856
4262
  /** The usage panel: how full the context is, what the conversation has cost, and Compact now. */
3857
4263
  const fillUsage = (panel, a, c) => {
@@ -3872,8 +4278,7 @@ export function renderChat(target, opts) {
3872
4278
  grid.append(cell);
3873
4279
  }
3874
4280
  panel.replaceChildren(head, bar, sub, grid);
3875
- if (agentOpts.compaction !== false)
3876
- panel.append(h("div", "ra-unote", `${t.autoCompact}: ${t.autoCompactAt.replace("{n}", fmtTokens(Math.min(16_384, Math.floor(c.window * 0.2))))}`));
4281
+ panel.append(h("div", "ra-unote", compactLine(a, c.window)));
3877
4282
  const foot = h("div", "ra-mf");
3878
4283
  const compactBtn = h("button", "ra-btn xs ghost");
3879
4284
  compactBtn.type = "button";
@@ -4275,6 +4680,10 @@ export function renderChat(target, opts) {
4275
4680
  const firstId = agentOpts.id ?? (typeof resumeOpt === "string" ? resumeOpt : resumeOpt === false ? undefined : readLast(project) ?? undefined);
4276
4681
  const starting = givenAgent ? Promise.resolve(givenAgent) : makeAgent(firstId);
4277
4682
  const ready = starting.then((a) => attach(a));
4683
+ // Scheduled tasks start once the first conversation is open.
4684
+ if (scheduler)
4685
+ void ready.then(() => { if (mounted)
4686
+ scheduler.start(); }).catch(() => undefined);
4278
4687
  ready.catch((err) => {
4279
4688
  // No session could be opened (the workspace factory or the agent threw): say so instead of a dead chat.
4280
4689
  addError(`${err.message}`);
@@ -4329,6 +4738,12 @@ export function renderChat(target, opts) {
4329
4738
  clearTimeout(histTimer);
4330
4739
  for (const u of unsub)
4331
4740
  u();
4741
+ for (const u of unmountHooks.splice(0)) {
4742
+ try {
4743
+ u();
4744
+ }
4745
+ catch { /* keep going */ }
4746
+ }
4332
4747
  ui.cancelAll(true);
4333
4748
  closeMenu();
4334
4749
  document.removeEventListener("click", onDocClick, true);