@runappsai/agent 0.1.11 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ui.cjs CHANGED
@@ -398,6 +398,20 @@ var VirtualList = class {
398
398
  this.win.replaceChildren();
399
399
  this.top.style.height = this.bottom.style.height = "0px";
400
400
  }
401
+ /**
402
+ * Puts row `i` at the top of the view and stops following the bottom. The
403
+ * rows above it are measured as they come into the window; the row stays
404
+ * where it is while they are (the layout anchors on the row at the top).
405
+ */
406
+ scrollToIndex(i) {
407
+ if (this.disposed || i < 0 || i >= this.rows.length) return;
408
+ this.pinned = null;
409
+ this.follow = false;
410
+ const total = this.computeOffsets();
411
+ this.bottom.style.height = `${total}px`;
412
+ this.setTop(this.offsets[i]);
413
+ this.layout();
414
+ }
401
415
  /** Jumps to the end and follows new output. */
402
416
  scrollToBottom() {
403
417
  this.pinned = null;
@@ -552,6 +566,10 @@ function h(tag, cls, text) {
552
566
  }
553
567
  var svg = (size, body, stroke = 2) => `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${stroke}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
554
568
  var I = {
569
+ clock: (s = 14) => svg(s, '<circle cx="12" cy="13" r="8"/><path d="M12 9v4l2 2"/><path d="M5 3 2 6"/><path d="m22 6-3-3"/>'),
570
+ play: (s = 13) => svg(s, '<polygon points="6 3 20 12 6 21 6 3"/>'),
571
+ pause: (s = 13) => svg(s, '<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>'),
572
+ pencil: (s = 13) => svg(s, '<path d="M21.17 6.81a1 1 0 0 0-3.99-3.99L3.84 16.17a2 2 0 0 0-.5.83l-1.32 4.35a.5.5 0 0 0 .62.62l4.35-1.32a2 2 0 0 0 .83-.5z"/>'),
555
573
  tick: (s = 14) => svg(s, '<path d="M20 6 9 17l-5-5"/>'),
556
574
  enter: (s = 14) => svg(s, '<polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/>'),
557
575
  lock: (s = 12) => svg(s, '<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>'),
@@ -658,8 +676,36 @@ async function modalInput(root, title, opts) {
658
676
  const ok = await modal(root, { title, body: [field], ok: opts.ok, cancel: opts.cancel, focus: field, submitOnEnter: true });
659
677
  return ok ? field.value.trim() || null : null;
660
678
  }
679
+ var fileDialogOpt;
680
+ function setFileDialog(d) {
681
+ fileDialogOpt = d;
682
+ }
683
+ function fileDialog() {
684
+ if (fileDialogOpt === false) return void 0;
685
+ if (fileDialogOpt) return fileDialogOpt;
686
+ const ui = globalThis.puter?.ui;
687
+ return typeof ui?.openFiles === "function" && typeof ui?.saveFile === "function" ? ui : void 0;
688
+ }
689
+ function chooseFiles(input, onFiles) {
690
+ const d = fileDialog();
691
+ if (!d) {
692
+ input.click();
693
+ return;
694
+ }
695
+ d.openFiles({ accept: input.accept || void 0, multiple: input.multiple }).then((files) => {
696
+ if (files?.length) onFiles(files);
697
+ }, () => input.click());
698
+ }
661
699
  function downloadBlob(name, data, type) {
662
700
  const blob = new Blob([data], { type: type || "application/octet-stream" });
701
+ const d = fileDialog();
702
+ if (d) {
703
+ void d.saveFile(blob, name).catch(() => plainDownload(blob, name));
704
+ return;
705
+ }
706
+ plainDownload(blob, name);
707
+ }
708
+ function plainDownload(blob, name) {
663
709
  const url = URL.createObjectURL(blob);
664
710
  const a = h("a");
665
711
  a.href = url;
@@ -884,6 +930,460 @@ var SELECT_CSS = `
884
930
  :is(.ra-chat,.ra-ui) .ra-selnone{padding:8px;color:var(--ra-fg-muted)}
885
931
  `;
886
932
 
933
+ // src/tool.ts
934
+ var NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
935
+ function defineTool(def) {
936
+ if (!NAME_RE.test(def.name)) {
937
+ throw new Error(`tool name "${def.name}" must match ${NAME_RE}`);
938
+ }
939
+ if (!def.description || !def.description.trim()) {
940
+ throw new Error(`tool "${def.name}" needs a description`);
941
+ }
942
+ const parameters = def.parameters ?? { type: "object", properties: {}, additionalProperties: false };
943
+ return { ...def, parameters };
944
+ }
945
+
946
+ // src/schedule.ts
947
+ function localSchedules(key) {
948
+ const read = () => {
949
+ try {
950
+ const v = JSON.parse(localStorage.getItem(key) || "[]");
951
+ return Array.isArray(v) ? v : [];
952
+ } catch {
953
+ return [];
954
+ }
955
+ };
956
+ const write = (list) => {
957
+ try {
958
+ if (list.length) localStorage.setItem(key, JSON.stringify(list));
959
+ else localStorage.removeItem(key);
960
+ } catch {
961
+ }
962
+ };
963
+ const change = (fn) => lock(`${key}:write`, async () => {
964
+ write(fn(read()));
965
+ });
966
+ return {
967
+ list: async () => read(),
968
+ get: async (id) => read().find((t) => t.id === id),
969
+ put: (task) => change((list) => {
970
+ const i = list.findIndex((t) => t.id === task.id);
971
+ if (i >= 0) list[i] = task;
972
+ else list.push(task);
973
+ return list;
974
+ }),
975
+ delete: (id) => change((list) => list.filter((t) => t.id !== id)),
976
+ subscribe(fn) {
977
+ if (typeof window === "undefined") return () => {
978
+ };
979
+ const on = (e) => {
980
+ if (e.key === key) fn();
981
+ };
982
+ window.addEventListener("storage", on);
983
+ return () => window.removeEventListener("storage", on);
984
+ }
985
+ };
986
+ }
987
+ var locks = () => typeof navigator !== "undefined" ? navigator.locks : void 0;
988
+ function lock(name, fn) {
989
+ const l = locks();
990
+ return l ? l.request(name, {}, fn) : fn();
991
+ }
992
+ async function tryLock(name, fn) {
993
+ const l = locks();
994
+ if (!l) {
995
+ await fn();
996
+ return true;
997
+ }
998
+ let got = false;
999
+ await l.request(name, { ifAvailable: true }, async (held) => {
1000
+ if (!held) return;
1001
+ got = true;
1002
+ await fn();
1003
+ });
1004
+ return got;
1005
+ }
1006
+ var HHMM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
1007
+ function parseLocalTime(s) {
1008
+ const m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(s.trim());
1009
+ if (m) return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] ?? 0)).getTime();
1010
+ return /[zZ]|[+-]\d{2}:?\d{2}$/.test(s) ? Date.parse(s) : NaN;
1011
+ }
1012
+ function formatLocalTime(ms) {
1013
+ const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
1014
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
1015
+ }
1016
+ var CRON_NAMES = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6, jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
1017
+ function parseCron(expr) {
1018
+ const f = expr.trim().split(/\s+/);
1019
+ if (f.length !== 5) throw new Error(`cron needs five fields (minute hour day month weekday), got "${expr}"`);
1020
+ const field = (s, lo, hi, what) => {
1021
+ const out = /* @__PURE__ */ new Set();
1022
+ for (const part of s.toLowerCase().split(",")) {
1023
+ const [range, stepS] = part.split("/");
1024
+ const step = stepS === void 0 ? 1 : Number(stepS);
1025
+ if (!Number.isInteger(step) || step < 1) throw new Error(`cron ${what}: bad step in "${part}"`);
1026
+ const num = (x) => {
1027
+ const n = CRON_NAMES[x] ?? Number(x);
1028
+ if (!Number.isInteger(n)) throw new Error(`cron ${what}: "${x}" is not a number`);
1029
+ return n;
1030
+ };
1031
+ let a, b;
1032
+ if (range === "*") {
1033
+ a = lo;
1034
+ b = hi;
1035
+ } else if (range.includes("-")) {
1036
+ const [x, y] = range.split("-");
1037
+ a = num(x);
1038
+ b = num(y);
1039
+ } else {
1040
+ a = num(range);
1041
+ b = stepS === void 0 ? a : hi;
1042
+ }
1043
+ if (what === "weekday") {
1044
+ if (a === 7) a = 0;
1045
+ if (b === 7 && a !== 0) b = 6, out.add(0);
1046
+ }
1047
+ if (a < lo || b > hi || a > b) throw new Error(`cron ${what}: "${part}" is outside ${lo}-${hi}`);
1048
+ for (let n = a; n <= b; n += step) out.add(n);
1049
+ }
1050
+ return out;
1051
+ };
1052
+ return { min: field(f[0], 0, 59, "minute"), hour: field(f[1], 0, 23, "hour"), dom: field(f[2], 1, 31, "day"), mon: field(f[3], 1, 12, "month"), dow: field(f[4], 0, 7, "weekday"), domAny: f[2] === "*", dowAny: f[4] === "*" };
1053
+ }
1054
+ function cronNext(c, after) {
1055
+ const start = new Date(after);
1056
+ start.setSeconds(0, 0);
1057
+ start.setMinutes(start.getMinutes() + 1);
1058
+ const hours = [...c.hour].sort((a, b) => a - b), mins = [...c.min].sort((a, b) => a - b);
1059
+ for (let day = 0; day < 366 * 5; day++) {
1060
+ const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + day);
1061
+ if (!c.mon.has(d.getMonth() + 1)) continue;
1062
+ const domOk = c.dom.has(d.getDate()), dowOk = c.dow.has(d.getDay());
1063
+ if (!(c.domAny && c.dowAny ? true : c.domAny ? dowOk : c.dowAny ? domOk : domOk || dowOk)) continue;
1064
+ for (const h2 of hours) for (const m of mins) {
1065
+ const t = new Date(d.getFullYear(), d.getMonth(), d.getDate(), h2, m).getTime();
1066
+ if (t >= start.getTime()) return t;
1067
+ }
1068
+ }
1069
+ return null;
1070
+ }
1071
+ function checkSchedule(s, minMinutes = 1) {
1072
+ switch (s?.type) {
1073
+ case "once":
1074
+ return Number.isFinite(parseLocalTime(s.at)) ? void 0 : `"at" must be a local time like 2026-11-28 09:00, got "${s.at}"`;
1075
+ case "every":
1076
+ return Number.isFinite(s.minutes) && s.minutes >= minMinutes ? void 0 : `"minutes" must be at least ${minMinutes}`;
1077
+ case "daily":
1078
+ if (!HHMM.test(s.time ?? "")) return `"time" must be HH:mm, got "${s.time}"`;
1079
+ if (s.days && (!s.days.length || s.days.some((d) => !Number.isInteger(d) || d < 0 || d > 6))) return `"days" must be weekday numbers 0 (Sunday) to 6`;
1080
+ return void 0;
1081
+ case "cron": {
1082
+ try {
1083
+ const c = parseCron(s.cron);
1084
+ if (cronNext(c, Date.now()) === null) return "this cron never runs";
1085
+ } catch (err) {
1086
+ return err.message;
1087
+ }
1088
+ if (minMinutes > 1) {
1089
+ const c = parseCron(s.cron);
1090
+ const a = cronNext(c, Date.now()), b = cronNext(c, a);
1091
+ if (b !== null && b - a < minMinutes * 6e4) return `runs more often than every ${minMinutes} minutes`;
1092
+ }
1093
+ return void 0;
1094
+ }
1095
+ default:
1096
+ return `"type" must be once, every, daily or cron`;
1097
+ }
1098
+ }
1099
+ function nextRun(s, after, from = after) {
1100
+ switch (s.type) {
1101
+ case "once": {
1102
+ const t = parseLocalTime(s.at);
1103
+ return Number.isFinite(t) && t > after ? t : null;
1104
+ }
1105
+ case "every": {
1106
+ const p = s.minutes * 6e4;
1107
+ let t = from + p;
1108
+ if (t <= after) t = after + p;
1109
+ return t;
1110
+ }
1111
+ case "daily": {
1112
+ const m = HHMM.exec(s.time);
1113
+ if (!m) return null;
1114
+ const base = new Date(after);
1115
+ for (let day = 0; day < 8; day++) {
1116
+ const d = new Date(base.getFullYear(), base.getMonth(), base.getDate() + day, +m[1], +m[2]);
1117
+ if (d.getTime() > after && (!s.days?.length || s.days.includes(d.getDay()))) return d.getTime();
1118
+ }
1119
+ return null;
1120
+ }
1121
+ case "cron":
1122
+ try {
1123
+ return cronNext(parseCron(s.cron), after);
1124
+ } catch {
1125
+ return null;
1126
+ }
1127
+ }
1128
+ }
1129
+ var DAY_EN = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
1130
+ var DAY_ZH = ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"];
1131
+ function describeSchedule(s, locale = "en") {
1132
+ const zh = locale === "zh";
1133
+ switch (s.type) {
1134
+ case "once": {
1135
+ const t = parseLocalTime(s.at);
1136
+ return (zh ? "\u4E00\u6B21 \xB7 " : "Once \xB7 ") + (Number.isFinite(t) ? formatLocalTime(t) : s.at);
1137
+ }
1138
+ case "every": {
1139
+ const m = s.minutes;
1140
+ const v = m % 1440 === 0 ? zh ? `${m / 1440} \u5929` : `${m / 1440} d` : m % 60 === 0 ? zh ? `${m / 60} \u5C0F\u65F6` : `${m / 60} h` : zh ? `${m} \u5206\u949F` : `${m} min`;
1141
+ return zh ? `\u6BCF ${v}` : `Every ${v}`;
1142
+ }
1143
+ case "daily": {
1144
+ const days = [...new Set(s.days ?? [])].sort((a, b) => a - b);
1145
+ if (!days.length || days.length === 7) return (zh ? "\u6BCF\u5929 " : "Daily ") + s.time;
1146
+ if (days.join() === "1,2,3,4,5") return (zh ? "\u5DE5\u4F5C\u65E5 " : "Weekdays ") + s.time;
1147
+ if (days.join() === "0,6") return (zh ? "\u5468\u672B " : "Weekends ") + s.time;
1148
+ return (zh ? "\u6BCF\u5468" + days.map((d) => DAY_ZH[d]).join("\u3001") + " " : days.map((d) => DAY_EN[d]).join(", ") + " ") + s.time;
1149
+ }
1150
+ case "cron":
1151
+ return `cron ${s.cron}`;
1152
+ }
1153
+ }
1154
+ var newTaskId = () => `t_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
1155
+ function makeTask(fields, limits = {}, now = Date.now()) {
1156
+ const name = fields.name?.trim(), prompt = fields.prompt?.trim();
1157
+ if (!name) throw new Error("a task needs a name");
1158
+ if (!prompt) throw new Error("a task needs a prompt");
1159
+ const problem = checkSchedule(fields.schedule, limits.minMinutes ?? 5);
1160
+ if (problem) throw new Error(problem);
1161
+ const enabled = fields.enabled ?? true;
1162
+ const next = enabled ? nextRun(fields.schedule, now) : null;
1163
+ if (enabled && next === null) throw new Error("that time has already passed");
1164
+ return { id: newTaskId(), name, prompt, schedule: fields.schedule, enabled, next, by: fields.by, created: now, updated: now, runs: 0 };
1165
+ }
1166
+ function changeTask(task, patch, limits = {}, now = Date.now()) {
1167
+ const out = { ...task, updated: now };
1168
+ if (patch.name !== void 0) {
1169
+ if (!patch.name.trim()) throw new Error("a task needs a name");
1170
+ out.name = patch.name.trim();
1171
+ }
1172
+ if (patch.prompt !== void 0) {
1173
+ if (!patch.prompt.trim()) throw new Error("a task needs a prompt");
1174
+ out.prompt = patch.prompt.trim();
1175
+ }
1176
+ if (patch.schedule) {
1177
+ const problem = checkSchedule(patch.schedule, limits.minMinutes ?? 5);
1178
+ if (problem) throw new Error(problem);
1179
+ out.schedule = patch.schedule;
1180
+ }
1181
+ if (patch.enabled !== void 0) out.enabled = patch.enabled;
1182
+ if (patch.schedule || patch.enabled !== void 0) {
1183
+ out.next = out.enabled ? nextRun(out.schedule, now) : null;
1184
+ if (out.enabled && out.next === null) throw new Error("that time has already passed");
1185
+ }
1186
+ return out;
1187
+ }
1188
+ var SCHEDULE_SCHEMA = {
1189
+ type: "object",
1190
+ description: `When it runs, in the user's local time. type "once": at ("YYYY-MM-DD HH:mm") or in_minutes (from now). type "every": minutes. type "daily": time ("HH:mm") and optional days (0 = Sunday \u2026 6 = Saturday; [1,2,3,4,5] for weekdays). type "cron": cron (five fields, local time).`,
1191
+ properties: {
1192
+ type: { type: "string", enum: ["once", "every", "daily", "cron"] },
1193
+ at: { type: "string" },
1194
+ in_minutes: { type: "number" },
1195
+ minutes: { type: "number" },
1196
+ time: { type: "string" },
1197
+ days: { type: "array", items: { type: "integer", minimum: 0, maximum: 6 } },
1198
+ cron: { type: "string" }
1199
+ },
1200
+ required: ["type"],
1201
+ additionalProperties: false
1202
+ };
1203
+ function toSchedule(a, now) {
1204
+ switch (a.type) {
1205
+ case "once":
1206
+ return { type: "once", at: a.at ?? (a.in_minutes !== void 0 ? formatLocalTime(now + Math.max(1, Math.round(a.in_minutes)) * 6e4) : "") };
1207
+ case "every":
1208
+ return { type: "every", minutes: Math.round(a.minutes ?? 0) };
1209
+ case "daily":
1210
+ return { type: "daily", time: a.time ?? "", ...a.days?.length ? { days: a.days } : {} };
1211
+ case "cron":
1212
+ return { type: "cron", cron: a.cron ?? "" };
1213
+ }
1214
+ }
1215
+ function taskLine(t, now = Date.now()) {
1216
+ return {
1217
+ id: t.id,
1218
+ name: t.name,
1219
+ prompt: t.prompt,
1220
+ schedule: describeSchedule(t.schedule),
1221
+ enabled: t.enabled,
1222
+ next: t.next ? formatLocalTime(t.next) : null,
1223
+ runs: t.runs,
1224
+ ...t.last ? { last_run: `${formatLocalTime(t.last.at)} ${t.last.status}${t.last.note ? ": " + t.last.note : ""}` } : {},
1225
+ ...t.next && t.next < now ? { overdue: true } : {}
1226
+ };
1227
+ }
1228
+ function scheduleTools(store, opts = {}) {
1229
+ const now = opts.now ?? Date.now;
1230
+ const tz = (() => {
1231
+ try {
1232
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
1233
+ } catch {
1234
+ return "local";
1235
+ }
1236
+ })();
1237
+ const changed = () => {
1238
+ try {
1239
+ opts.onChange?.();
1240
+ } catch {
1241
+ }
1242
+ };
1243
+ const header = () => `Now: ${formatLocalTime(now())} (${tz}).`;
1244
+ return [
1245
+ defineTool({
1246
+ name: "schedule_list",
1247
+ description: "Lists the scheduled tasks: prompts this app's agent runs on its own at set times (while the app is open).",
1248
+ readOnly: true,
1249
+ display: { label: () => "Scheduled tasks" },
1250
+ execute: async () => {
1251
+ const list = await store.list();
1252
+ return `${header()}
1253
+ ${list.length ? JSON.stringify(list.map((t) => taskLine(t, now())), null, 1) : "No scheduled tasks."}`;
1254
+ }
1255
+ }),
1256
+ defineTool({
1257
+ name: "schedule_add",
1258
+ description: `Adds a scheduled task: at the set times the agent is given \`prompt\` in a conversation of the task's own and works on it unattended (the user may not be watching; questions wait for them). Runs only while the app is open in a browser; a run missed while it was closed happens once when it is next opened. Repeats at most every ${opts.minMinutes ?? 5} minutes. Write the prompt so it stands alone: the run does not see this conversation.`,
1259
+ parameters: {
1260
+ type: "object",
1261
+ properties: {
1262
+ name: { type: "string", description: 'Short name the user sees, e.g. "Morning news digest".' },
1263
+ prompt: { type: "string", description: "The instruction for each run, complete on its own." },
1264
+ schedule: SCHEDULE_SCHEMA,
1265
+ enabled: { type: "boolean", description: "Default true." }
1266
+ },
1267
+ required: ["name", "prompt", "schedule"],
1268
+ additionalProperties: false
1269
+ },
1270
+ display: { label: (a) => `Schedule \u201C${a.name ?? ""}\u201D` },
1271
+ execute: async (a) => {
1272
+ const list = await store.list();
1273
+ if (list.length >= (opts.maxTasks ?? 20)) throw new Error(`there are already ${list.length} tasks, the most allowed; remove one first`);
1274
+ const task = makeTask({ name: a.name, prompt: a.prompt, schedule: toSchedule(a.schedule, now()), enabled: a.enabled, by: "agent" }, opts, now());
1275
+ await store.put(task);
1276
+ changed();
1277
+ return `${header()}
1278
+ Added: ${JSON.stringify(taskLine(task, now()))}`;
1279
+ }
1280
+ }),
1281
+ defineTool({
1282
+ name: "schedule_update",
1283
+ description: "Changes a scheduled task (by id, from schedule_list): its name, prompt, schedule, or enabled (false pauses it).",
1284
+ parameters: {
1285
+ type: "object",
1286
+ properties: { id: { type: "string" }, name: { type: "string" }, prompt: { type: "string" }, schedule: SCHEDULE_SCHEMA, enabled: { type: "boolean" } },
1287
+ required: ["id"],
1288
+ additionalProperties: false
1289
+ },
1290
+ display: { label: (a) => `Update scheduled task ${a.id ?? ""}` },
1291
+ execute: async (a) => {
1292
+ const task = await store.get(a.id);
1293
+ if (!task) throw new Error(`no task with id ${a.id}; schedule_list shows them`);
1294
+ const next = changeTask(task, { name: a.name, prompt: a.prompt, schedule: a.schedule ? toSchedule(a.schedule, now()) : void 0, enabled: a.enabled }, opts, now());
1295
+ await store.put(next);
1296
+ changed();
1297
+ return `${header()}
1298
+ Updated: ${JSON.stringify(taskLine(next, now()))}`;
1299
+ }
1300
+ }),
1301
+ defineTool({
1302
+ name: "schedule_remove",
1303
+ description: "Removes a scheduled task (by id). Its conversation stays.",
1304
+ parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"], additionalProperties: false },
1305
+ display: { label: (a) => `Remove scheduled task ${a.id ?? ""}` },
1306
+ execute: async (a) => {
1307
+ const task = await store.get(a.id);
1308
+ if (!task) throw new Error(`no task with id ${a.id}`);
1309
+ await store.delete(a.id);
1310
+ changed();
1311
+ return `Removed \u201C${task.name}\u201D.`;
1312
+ }
1313
+ })
1314
+ ];
1315
+ }
1316
+ var Scheduler = class {
1317
+ constructor(opts) {
1318
+ __publicField(this, "opts", opts);
1319
+ __publicField(this, "timer", null);
1320
+ __publicField(this, "busy", false);
1321
+ __publicField(this, "unsub", null);
1322
+ /** Ids of tasks this tab is running now. */
1323
+ __publicField(this, "running", /* @__PURE__ */ new Set());
1324
+ __publicField(this, "poke", () => void this.tick());
1325
+ }
1326
+ start() {
1327
+ if (this.timer) return;
1328
+ this.timer = setInterval(() => void this.tick(), this.opts.interval ?? 2e4);
1329
+ this.unsub = this.opts.store.subscribe?.(() => this.opts.onChange?.()) ?? null;
1330
+ if (typeof window !== "undefined") window.addEventListener("focus", this.poke);
1331
+ void this.tick();
1332
+ }
1333
+ stop() {
1334
+ if (this.timer) clearInterval(this.timer);
1335
+ this.timer = null;
1336
+ this.unsub?.();
1337
+ this.unsub = null;
1338
+ if (typeof window !== "undefined") window.removeEventListener("focus", this.poke);
1339
+ }
1340
+ /** Looks for a due task and runs it when idle. Resolves once that run is over. */
1341
+ async tick() {
1342
+ if (this.busy || !this.opts.idle()) return;
1343
+ const now = (this.opts.now ?? Date.now)();
1344
+ const due = (await this.opts.store.list()).filter((t) => t.enabled && t.next !== null && t.next <= now).sort((a, b) => a.next - b.next);
1345
+ for (const t of due) {
1346
+ if (this.busy || !this.opts.idle()) return;
1347
+ if (await this.fire(t.id, false)) return;
1348
+ }
1349
+ }
1350
+ /** Runs a task now (the user's "Run now"), whatever its time; false when it is already running somewhere. */
1351
+ runNow(id) {
1352
+ return this.fire(id, true);
1353
+ }
1354
+ async fire(id, force) {
1355
+ if (this.busy) return false;
1356
+ this.busy = true;
1357
+ let ran = false;
1358
+ try {
1359
+ await tryLock(`${this.opts.lockPrefix}:task:${id}`, async () => {
1360
+ const store = this.opts.store, clock2 = this.opts.now ?? Date.now;
1361
+ const task = await store.get(id);
1362
+ const now = clock2();
1363
+ if (!task || !force && (!task.enabled || task.next === null || task.next > now)) return;
1364
+ const next = task.enabled ? nextRun(task.schedule, now, now) : task.next;
1365
+ await store.put({ ...task, next: task.schedule.type === "once" && !force ? null : next, ...task.schedule.type === "once" && !force ? { enabled: false } : {} });
1366
+ ran = true;
1367
+ this.running.add(id);
1368
+ this.opts.onChange?.();
1369
+ let out;
1370
+ try {
1371
+ out = await this.opts.run(task);
1372
+ } catch (err) {
1373
+ out = { status: "error", note: err.message };
1374
+ }
1375
+ this.running.delete(id);
1376
+ const after = await store.get(id);
1377
+ if (after) await store.put({ ...after, runs: after.runs + 1, last: { at: now, ...out } });
1378
+ this.opts.onChange?.();
1379
+ });
1380
+ return ran;
1381
+ } finally {
1382
+ this.busy = false;
1383
+ }
1384
+ }
1385
+ };
1386
+
887
1387
  // src/compaction.ts
888
1388
  var DEFAULT_COMPACTION = { reserveTokens: 16384, keepRecentTokens: 2e4 };
889
1389
  function resolveSettings(window2, s = {}) {
@@ -970,7 +1470,7 @@ function filesPanel(opts) {
970
1470
  fileInput.type = "file";
971
1471
  fileInput.multiple = true;
972
1472
  fileInput.style.display = "none";
973
- const uploadBtn = ibtn(I.upload(), t.upload, () => fileInput.click());
1473
+ const uploadBtn = ibtn(I.upload(), t.upload, () => chooseFiles(fileInput, (picked) => void upload(picked)));
974
1474
  const zipBtn = ibtn(I.download(), t.downloadZip, () => void downloadFolder("/"));
975
1475
  const newBtn = ibtn(I.filePlus(14), t.newFile, () => void newFile());
976
1476
  const refreshBtn = ibtn(I.refresh(), t.refresh, () => void refresh());
@@ -1662,7 +2162,7 @@ function debugPanel(opts) {
1662
2162
  ctx.textContent = "\u2014";
1663
2163
  });
1664
2164
  const sys = pre("\u2026", "tall");
1665
- void a.systemPrompt().then((p) => {
2165
+ void (a.systemPrompt?.() ?? Promise.resolve("(this agent does not expose its system prompt)")).then((p) => {
1666
2166
  sys.textContent = p;
1667
2167
  }).catch((err) => {
1668
2168
  sys.textContent = String(err);
@@ -2102,6 +2602,51 @@ var STRINGS = {
2102
2602
  webOn: "Web search: on",
2103
2603
  webOff: "Web search: off",
2104
2604
  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",
2605
+ permAlways: "Always allow (this app)",
2606
+ sched: "Scheduled",
2607
+ schedNew: "New task",
2608
+ schedNone: 'No scheduled tasks yet. Ask the AI ("every weekday at 9, summarise the news") or add one.',
2609
+ 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.",
2610
+ schedName: "Name",
2611
+ schedPrompt: "What to do",
2612
+ schedWhen: "When",
2613
+ schedOnce: "Once",
2614
+ schedEvery: "Every",
2615
+ schedDaily: "Daily / weekly",
2616
+ schedCron: "Cron",
2617
+ schedMin: "minutes",
2618
+ schedHour: "hours",
2619
+ schedDay: "days",
2620
+ schedCronHint: "minute hour day month weekday, e.g. 0 9 * * 1-5",
2621
+ schedNext: "Next {time}",
2622
+ schedNoNext: "Will not run again",
2623
+ schedPaused: "Paused",
2624
+ schedRunning: "Running",
2625
+ schedLast: "Last {time} \xB7 {status}",
2626
+ schedOk: "done",
2627
+ schedErr: "failed",
2628
+ schedStopped: "stopped",
2629
+ schedRunNow: "Run now",
2630
+ schedPause: "Pause",
2631
+ schedResume: "Resume",
2632
+ schedEdit: "Edit",
2633
+ schedOpen: "Open its conversation",
2634
+ schedDel: "Delete task",
2635
+ schedDelMsg: 'Delete "{name}"? Its conversation stays.',
2636
+ schedSave: "Save",
2637
+ schedBusy: "Another scheduled task is running; try again when it ends.",
2638
+ schedByAI: "by AI",
2639
+ schedRunHead: '\u23F0 Scheduled task "{name}" \xB7 {time}\n(Running unattended: the user may not be watching.)',
2640
+ schedStarted: 'Scheduled task "{name}" started',
2641
+ schedFailed: 'Scheduled task "{name}" failed: {error}',
2642
+ schedNamePh: "e.g. Morning news digest",
2643
+ schedPromptPh: "What the AI should do each time. Write it to stand alone: the run does not see this conversation.",
2644
+ schedDayNames: "Sun,Mon,Tue,Wed,Thu,Fri,Sat",
2645
+ tSchedList: "Scheduled tasks",
2646
+ tSchedAdd: 'Schedule "{name}"',
2647
+ tSchedUpdate: "Change scheduled task",
2648
+ tSchedRemove: "Remove scheduled task",
2649
+ permAutoNote: "Auto-run is on: the AI will no longer ask before deleting, overwriting or publishing. Turn it off in Settings \u2192 Tool permissions.",
2105
2650
  runCode: "Run code",
2106
2651
  ingRead: "Reading",
2107
2652
  ingList: "Listing",
@@ -2159,6 +2704,8 @@ var STRINGS = {
2159
2704
  delTurnMsg: "They are removed from the conversation; files stay as they are.",
2160
2705
  replyCost: "Cost: {cost}",
2161
2706
  replyUsage: "{in} in \xB7 {out} out \xB7 {calls} calls",
2707
+ older: "Load earlier messages",
2708
+ olderBusy: "Wait for the reply to finish, then load earlier messages.",
2162
2709
  rewindMsg: "The conversation after it is dropped and the message goes back into the composer.",
2163
2710
  rewindFiles: "Also restore the directory's files to that moment",
2164
2711
  rewindGone: "This message is no longer in the conversation.",
@@ -2259,6 +2806,7 @@ var STRINGS = {
2259
2806
  cmdsMore: "Templates (/name) and skills (/skill:name) are listed as you type.",
2260
2807
  autoCompact: "Auto-compaction",
2261
2808
  autoCompactAt: "when less than {n} tokens are left",
2809
+ autoCompactFull: "when the context is full",
2262
2810
  directory: "Directory",
2263
2811
  messagesLabel: "Messages",
2264
2812
  cmdArgs: { compact: "[focus]", model: "[name]", effort: "[level]" },
@@ -2370,6 +2918,51 @@ var STRINGS = {
2370
2918
  webOn: "\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5F00\u542F",
2371
2919
  webOff: "\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5173\u95ED",
2372
2920
  webHint: "\u5F00\u542F\u540E AI \u53EF\u4EE5\u641C\u7D22\u548C\u9605\u8BFB\u7F51\u9875\uFF0C\u67E5\u8D44\u6599\u548C\u6700\u65B0\u4FE1\u606F\uFF1B\u6BCF\u6B21\u641C\u7D22\u3001\u6BCF\u8BFB\u4E00\u4E2A\u7F51\u9875\u6309\u6B21\u8BA1\u8D39",
2921
+ permAlways: "\u4EE5\u540E\u90FD\u5141\u8BB8\uFF08\u672C\u5E94\u7528\uFF09",
2922
+ sched: "\u5B9A\u65F6\u4EFB\u52A1",
2923
+ schedNew: "\u65B0\u5EFA",
2924
+ schedNone: "\u8FD8\u6CA1\u6709\u5B9A\u65F6\u4EFB\u52A1\u3002\u53EF\u4EE5\u76F4\u63A5\u8BA9 AI \u5B89\u6392\uFF08\u6BD4\u5982\u300C\u6BCF\u4E2A\u5DE5\u4F5C\u65E5\u65E9\u4E0A 9 \u70B9\u6574\u7406\u65B0\u95FB\u300D\uFF09\uFF0C\u6216\u70B9\u65B0\u5EFA\u3002",
2925
+ schedHint: "\u5B9A\u65F6\u4EFB\u52A1\u53EA\u5728\u672C\u5E94\u7528\u9875\u9762\u6253\u5F00\u65F6\u8FD0\u884C\uFF0C\u5E76\u7B49\u5BF9\u8BDD\u7A7A\u95F2\u65F6\u624D\u5F00\u59CB\uFF1B\u9875\u9762\u5173\u95ED\u671F\u95F4\u9519\u8FC7\u7684\uFF0C\u4E0B\u6B21\u6253\u5F00\u65F6\u8865\u8DD1\u4E00\u6B21\u3002",
2926
+ schedName: "\u540D\u79F0",
2927
+ schedPrompt: "\u8981\u505A\u4EC0\u4E48",
2928
+ schedWhen: "\u65F6\u95F4",
2929
+ schedOnce: "\u4E00\u6B21",
2930
+ schedEvery: "\u6BCF\u9694",
2931
+ schedDaily: "\u6BCF\u5929 / \u6BCF\u5468",
2932
+ schedCron: "Cron",
2933
+ schedMin: "\u5206\u949F",
2934
+ schedHour: "\u5C0F\u65F6",
2935
+ schedDay: "\u5929",
2936
+ schedCronHint: "\u5206 \u65F6 \u65E5 \u6708 \u5468\uFF0C\u5982 0 9 * * 1-5",
2937
+ schedNext: "\u4E0B\u6B21 {time}",
2938
+ schedNoNext: "\u4E0D\u4F1A\u518D\u8FD0\u884C",
2939
+ schedPaused: "\u5DF2\u6682\u505C",
2940
+ schedRunning: "\u8FD0\u884C\u4E2D",
2941
+ schedLast: "\u4E0A\u6B21 {time} \xB7 {status}",
2942
+ schedOk: "\u5B8C\u6210",
2943
+ schedErr: "\u5931\u8D25",
2944
+ schedStopped: "\u5DF2\u505C\u6B62",
2945
+ schedRunNow: "\u7ACB\u5373\u8FD0\u884C",
2946
+ schedPause: "\u6682\u505C",
2947
+ schedResume: "\u6062\u590D",
2948
+ schedEdit: "\u7F16\u8F91",
2949
+ schedOpen: "\u6253\u5F00\u5B83\u7684\u5BF9\u8BDD",
2950
+ schedDel: "\u5220\u9664\u4EFB\u52A1",
2951
+ schedDelMsg: "\u5220\u9664\u300C{name}\u300D\uFF1F\u5B83\u7684\u5BF9\u8BDD\u4F1A\u4FDD\u7559\u3002",
2952
+ schedSave: "\u4FDD\u5B58",
2953
+ schedBusy: "\u53E6\u4E00\u4E2A\u5B9A\u65F6\u4EFB\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u7ED3\u675F\u540E\u518D\u8BD5\u3002",
2954
+ schedByAI: "AI \u521B\u5EFA",
2955
+ schedRunHead: "\u23F0 \u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D \xB7 {time}\n\uFF08\u65E0\u4EBA\u503C\u5B88\u8FD0\u884C\uFF1A\u7528\u6237\u53EF\u80FD\u4E0D\u5728\u65C1\u8FB9\u3002\uFF09",
2956
+ schedStarted: "\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D\u5F00\u59CB\u8FD0\u884C",
2957
+ schedFailed: "\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D\u5931\u8D25\uFF1A{error}",
2958
+ schedNamePh: "\u5982\uFF1A\u65E9\u95F4\u65B0\u95FB\u6458\u8981",
2959
+ schedPromptPh: "\u6BCF\u6B21\u8FD0\u884C\u65F6 AI \u8981\u505A\u7684\u4E8B\u3002\u5199\u5B8C\u6574\uFF1A\u8FD0\u884C\u65F6\u770B\u4E0D\u5230\u8FD9\u6BB5\u5BF9\u8BDD\u3002",
2960
+ schedDayNames: "\u65E5,\u4E00,\u4E8C,\u4E09,\u56DB,\u4E94,\u516D",
2961
+ tSchedList: "\u67E5\u770B\u5B9A\u65F6\u4EFB\u52A1",
2962
+ tSchedAdd: "\u5B89\u6392\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D",
2963
+ tSchedUpdate: "\u4FEE\u6539\u5B9A\u65F6\u4EFB\u52A1",
2964
+ tSchedRemove: "\u5220\u9664\u5B9A\u65F6\u4EFB\u52A1",
2965
+ permAutoNote: "\u5DF2\u5F00\u542F\u81EA\u52A8\u6267\u884C\uFF1A\u5220\u9664\u3001\u8986\u76D6\u3001\u53D1\u5E03\u7B49\u64CD\u4F5C\u4E5F\u4E0D\u518D\u8BE2\u95EE\u3002\u53EF\u5728\u8BBE\u7F6E \u2192 \u5DE5\u5177\u6743\u9650\u91CC\u5173\u95ED\u3002",
2373
2966
  runCode: "\u8FD0\u884C\u4EE3\u7801",
2374
2967
  ingRead: "\u6B63\u5728\u8BFB\u53D6",
2375
2968
  ingList: "\u6B63\u5728\u67E5\u770B",
@@ -2427,6 +3020,8 @@ var STRINGS = {
2427
3020
  delTurnMsg: "\u8FD9\u6761\u63D0\u95EE\u548C\u5B83\u7684\u56DE\u7B54\u4F1A\u4ECE\u5BF9\u8BDD\u4E2D\u5220\u9664\uFF0C\u6587\u4EF6\u4E0D\u53D7\u5F71\u54CD\u3002",
2428
3021
  replyCost: "\u8D39\u7528\uFF1A{cost}",
2429
3022
  replyUsage: "\u8F93\u5165 {in} \xB7 \u8F93\u51FA {out} \xB7 {calls} \u6B21\u8C03\u7528",
3023
+ older: "\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F",
3024
+ olderBusy: "\u7B49\u8FD9\u6B21\u56DE\u590D\u7ED3\u675F\u540E\u518D\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F\u3002",
2430
3025
  rewindMsg: "\u5B83\u4E4B\u540E\u7684\u5BF9\u8BDD\u4F1A\u88AB\u5220\u9664\uFF0C\u6D88\u606F\u5185\u5BB9\u653E\u56DE\u8F93\u5165\u6846\u3002",
2431
3026
  rewindFiles: "\u540C\u65F6\u628A\u76EE\u5F55\u91CC\u7684\u6587\u4EF6\u6062\u590D\u5230\u90A3\u4E00\u523B",
2432
3027
  rewindGone: "\u8FD9\u6761\u6D88\u606F\u5DF2\u4E0D\u5728\u5BF9\u8BDD\u91CC\uFF08\u53EF\u80FD\u5DF2\u88AB\u538B\u7F29\uFF09\u3002",
@@ -2527,6 +3122,7 @@ var STRINGS = {
2527
3122
  cmdsMore: "\u6A21\u677F\uFF08/\u540D\u79F0\uFF09\u548C Skill\uFF08/skill:\u540D\u79F0\uFF09\u5728\u8F93\u5165\u65F6\u5217\u51FA\u3002",
2528
3123
  autoCompact: "\u81EA\u52A8\u538B\u7F29",
2529
3124
  autoCompactAt: "\u5269\u4F59\u4E0D\u8DB3 {n} tokens \u65F6",
3125
+ autoCompactFull: "\u4E0A\u4E0B\u6587\u7528\u6EE1\u65F6",
2530
3126
  directory: "\u76EE\u5F55",
2531
3127
  messagesLabel: "\u6D88\u606F",
2532
3128
  cmdArgs: { compact: "[\u91CD\u70B9]", model: "[\u540D\u79F0]", effort: "[\u6863\u4F4D]" },
@@ -2592,6 +3188,25 @@ var CSS = tokenCSS() + `
2592
3188
  .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}
2593
3189
  .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}
2594
3190
  .ra-skm.drop{outline:2px dashed var(--ra-accent);outline-offset:-4px}
3191
+ .ra-schm .ra-skb.on{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
3192
+ .ra-schm .ra-mi.ra-off .ra-mtt{color:var(--ra-fg-muted)}
3193
+ .ra-schm .ra-mi small.ra-bad{color:var(--ra-red)}
3194
+ .ra-schm .ra-mi small{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp:none}
3195
+ .ra-schf{display:flex;flex-direction:column;gap:10px;padding:6px 8px 6px}
3196
+ .ra-schf .ra-schh{font-size:13px;font-weight:600}
3197
+ .ra-schf .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
3198
+ .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}
3199
+ .ra-chat .ra-schf textarea{min-height:88px;resize:vertical;line-height:1.5}
3200
+ .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)}
3201
+ .ra-schf .ra-row{display:flex;gap:8px;align-items:center}
3202
+ .ra-schf .ra-row>*{flex:1;min-width:0}
3203
+ .ra-schf .ra-row.ra-col2{flex-direction:column;align-items:stretch}
3204
+ .ra-schf .ra-days{display:flex;gap:4px}
3205
+ .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)}
3206
+ .ra-chat .ra-schf .ra-days button.on{background:var(--ra-accent-subtle);border-color:transparent;color:var(--ra-accent-fg);font-weight:600}
3207
+ .ra-schf .ra-note{font-size:11.5px;color:var(--ra-fg-muted)}
3208
+ .ra-schf .ra-note.err{color:var(--ra-red)}
3209
+ .ra-schf .ra-btns{display:flex;justify-content:flex-end;gap:6px}
2595
3210
  .ra-set{padding:10px 12px;display:flex;flex-direction:column;gap:10px;width:min(360px,calc(100% - 24px))}
2596
3211
  /* The settings panel takes the chat's height under the header (a host may add fields of its own). */
2597
3212
  .ra-chat .ra-set{max-height:calc(100% - 72px)}
@@ -2746,6 +3361,8 @@ var CSS = tokenCSS() + `
2746
3361
  @keyframes ra-shimmer{from{background-position:100% 0}to{background-position:0 0}}
2747
3362
  @media (prefers-reduced-motion:reduce){.ra-pending>span{animation:none;color:var(--ra-fg-muted);background:none}}
2748
3363
  .ra-time{text-align:center;font-size:12px;color:var(--ra-fg-muted);padding:14px 0 2px}
3364
+ .ra-olderrow{display:flex;justify-content:center;padding:6px 0 2px}
3365
+ .ra-chat .ra-older{font-size:12px;color:var(--ra-fg-muted)}
2749
3366
  .ra-work{border-bottom:1px solid var(--ra-border);padding-bottom:6px;margin-bottom:4px}
2750
3367
  .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}
2751
3368
  .ra-work>summary::-webkit-details-marker{display:none}
@@ -2798,6 +3415,8 @@ var CSS = tokenCSS() + `
2798
3415
  .ra-tool>summary .ra-chev{color:var(--ra-fg-muted);transition:transform .15s}
2799
3416
  .ra-tool[open]>summary .ra-chev{transform:rotate(90deg)}
2800
3417
  .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}
3418
+ .ra-tool .ra-ticon[data-tone="warning"]{background:var(--ra-warn-bg);color:var(--ra-warn-fg)}
3419
+ .ra-tool .ra-ticon[data-tone="danger"]{background:var(--ra-red-subtle);color:var(--ra-red)}
2801
3420
  .ra-tool.fail .ra-ticon{background:var(--ra-red-subtle);color:var(--ra-red)}
2802
3421
  .ra-tool .ra-tname{font-weight:600;white-space:nowrap}
2803
3422
  .ra-tool .ra-tname.own{font-weight:500;min-width:0;overflow:hidden;text-overflow:ellipsis}
@@ -2849,6 +3468,9 @@ var CSS = tokenCSS() + `
2849
3468
  .ra-q .ra-opt small{display:block;color:var(--ra-fg-muted);font-size:12px}
2850
3469
  .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}
2851
3470
  .ra-q .ra-field:focus{border-color:var(--ra-accent)}
3471
+ .ra-q .ra-field.bad{border-color:var(--ra-red)}
3472
+ .ra-q .ra-form{display:flex;flex-direction:column;gap:8px;margin:2px 0 4px}
3473
+ .ra-q .ra-ff{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--ra-fg-muted)}
2852
3474
  .ra-q textarea.ra-field{min-height:96px;max-height:200px;resize:vertical}
2853
3475
  .ra-btns{display:flex;justify-content:flex-end;gap:8px}
2854
3476
  .ra-cbody{margin:2px 0 10px;max-height:min(60vh,560px);overflow:auto;min-width:0}
@@ -3311,10 +3933,64 @@ function inlineUI(askArea, toasts, t, onChange) {
3311
3933
  }
3312
3934
  card.append(list);
3313
3935
  const row = h("div", "ra-btns");
3314
- row.append(btn(t.cancel, "ghost", () => done(null)), btn(t.ok, "solid", () => {
3315
- const picked = inputs.filter((i) => i.checked).map((i) => i.value === "__other__" ? other?.value.trim() ?? "" : i.value).filter(Boolean);
3316
- if (picked.length) done(picked);
3317
- }));
3936
+ const pickedNow = () => inputs.filter((i) => i.checked).map((i) => i.value === "__other__" ? other?.value.trim() ?? "" : i.value).filter(Boolean);
3937
+ const min = opts.multi ? opts.min ?? 1 : 1, max = opts.multi ? opts.max : void 0;
3938
+ const fits = (n) => n >= min && (max === void 0 || n <= max);
3939
+ const okBtn = btn(t.ok, "solid", () => {
3940
+ const picked = pickedNow();
3941
+ if (fits(picked.length)) done(picked);
3942
+ });
3943
+ if (opts.multi && (opts.min !== void 0 || opts.max !== void 0)) {
3944
+ const sync = () => {
3945
+ okBtn.disabled = !fits(pickedNow().length);
3946
+ };
3947
+ list.addEventListener("change", sync);
3948
+ list.addEventListener("input", sync);
3949
+ sync();
3950
+ }
3951
+ row.append(btn(t.cancel, "ghost", () => done(null)), okBtn);
3952
+ card.append(row);
3953
+ }, null, opts.signal),
3954
+ form: (title, fields, opts = {}) => open((card, done) => {
3955
+ head(card, title, opts.message);
3956
+ const box = h("div", "ra-form");
3957
+ const inputs = fields.map((f) => {
3958
+ const label = h("label", "ra-ff");
3959
+ label.append(h("span", "", (f.label ?? f.name) + (f.required ? " *" : "")));
3960
+ const input = h("input", "ra-field");
3961
+ input.type = f.type === "number" ? "number" : "text";
3962
+ input.name = f.name;
3963
+ if (f.type === "number") input.step = "any";
3964
+ if (f.placeholder) input.placeholder = f.placeholder;
3965
+ if (f.initial !== void 0) input.value = String(f.initial);
3966
+ label.append(input);
3967
+ box.append(label);
3968
+ return { f, input };
3969
+ });
3970
+ const submit = () => {
3971
+ const out = {};
3972
+ for (const { f, input } of inputs) {
3973
+ const raw = input.value.trim();
3974
+ const bad = !raw && f.required || !!raw && f.type === "number" && !Number.isFinite(Number(raw));
3975
+ input.classList.toggle("bad", bad);
3976
+ if (bad) {
3977
+ input.focus();
3978
+ return;
3979
+ }
3980
+ if (raw) out[f.name] = f.type === "number" ? Number(raw) : raw;
3981
+ }
3982
+ done(out);
3983
+ };
3984
+ box.addEventListener("keydown", (ev) => {
3985
+ const e = ev;
3986
+ if (e.key === "Enter" && !e.isComposing) {
3987
+ e.preventDefault();
3988
+ submit();
3989
+ }
3990
+ });
3991
+ card.append(box);
3992
+ const row = h("div", "ra-btns");
3993
+ row.append(btn(t.cancel, "ghost", () => done(null)), btn(opts.ok ?? t.submit, "solid", submit));
3318
3994
  card.append(row);
3319
3995
  }, null, opts.signal),
3320
3996
  input: (title, opts = {}) => open((card, done) => {
@@ -3389,8 +4065,10 @@ function renderChat(target, opts) {
3389
4065
  injectStyles();
3390
4066
  const lang = pickLocale(opts.locale);
3391
4067
  const t = STRINGS[lang];
3392
- 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;
4068
+ 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: fileDialogOpt2, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, webSearch: webSearchOpt, schedule: scheduleOpt, queue: queueOpt, replyActions, clearButton, commands: commandsOpt, uploadImage, headerStart, ...agentOpts } = opts;
4069
+ const canQueue = queueOpt !== false;
3393
4070
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
4071
+ setFileDialog(fileDialogOpt2);
3394
4072
  const provider = providerOpt ? (0, import_index2.toProvider)(providerOpt) : clientOpt ? (0, import_index2.toProvider)(clientOpt) : givenAgent?.provider ?? null;
3395
4073
  const project = provider?.name ?? agentOpts.appName ?? "app";
3396
4074
  const root = h("div", "ra-chat");
@@ -3448,6 +4126,10 @@ function renderChat(target, opts) {
3448
4126
  };
3449
4127
  };
3450
4128
  const setSkillCount = countBadge(skillsBtn, t.skills);
4129
+ const schedBtn = h("button", "ra-btn ghost");
4130
+ schedBtn.type = "button";
4131
+ schedBtn.innerHTML = I.clock() + `<span>${escapeHTML(t.sched)}</span>`;
4132
+ const setSchedCount = countBadge(schedBtn, t.sched);
3451
4133
  const histBtn = h("button", "ra-btn ghost");
3452
4134
  histBtn.type = "button";
3453
4135
  histBtn.innerHTML = I.hist() + `<span>${escapeHTML(t.history)}</span>`;
@@ -3461,7 +4143,7 @@ function renderChat(target, opts) {
3461
4143
  clearBtn.style.display = "none";
3462
4144
  let oneChat = false;
3463
4145
  const syncClear = () => {
3464
- clearBtn.style.display = oneChat && agent?.messages.length ? "" : "none";
4146
+ clearBtn.style.display = clearButton !== false && oneChat && agent?.messages.length ? "" : "none";
3465
4147
  };
3466
4148
  const useBtn = h("button", "ra-btn ghost ra-usebtn");
3467
4149
  useBtn.type = "button";
@@ -3471,12 +4153,12 @@ function renderChat(target, opts) {
3471
4153
  setBtn.innerHTML = I.gear();
3472
4154
  setBtn.title = t.settings;
3473
4155
  setBtn.setAttribute("aria-label", t.settings);
3474
- for (const [btn, label] of [[debugBtn, t.debug], [filesBtn, t.files], [skillsBtn, t.skills], [histBtn, t.history], [newBtn, t.newChat], [clearBtn, t.clearChat]]) {
4156
+ 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]]) {
3475
4157
  btn.setAttribute("aria-label", label);
3476
4158
  if (!btn.title) btn.title = label;
3477
4159
  }
3478
- for (const el of [...headerActions ?? [], ...headerEnd ?? [], ...composerTop ? [composerTop] : [], ...emptyState instanceof HTMLElement ? [emptyState] : []]) el.classList.add("ra-host");
3479
- head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, histBtn, newBtn, clearBtn, ...headerActions ?? [], setBtn, ...headerEnd ?? []);
4160
+ for (const el of [...headerStart ?? [], ...headerActions ?? [], ...headerEnd ?? [], ...composerTop ? [composerTop] : [], ...emptyState instanceof HTMLElement ? [emptyState] : []]) el.classList.add("ra-host");
4161
+ head.append(...headerStart ?? [], titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, schedBtn, histBtn, newBtn, clearBtn, ...headerActions ?? [], setBtn, ...headerEnd ?? []);
3480
4162
  if (title === false) head.style.display = "none";
3481
4163
  const log = h("div", "ra-log");
3482
4164
  const inner = h("div", "ra-col");
@@ -3596,6 +4278,32 @@ ${t.webHint}`;
3596
4278
  drawWeb();
3597
4279
  for (const a of live.values()) applyWeb(a);
3598
4280
  });
4281
+ const PERM_KEY = `__runapps_agent_chat:${project}:perm`;
4282
+ const permOwn = !givenAgent && typeof agentOpts.permissions !== "function";
4283
+ const permShown = permOwn && permissionsSetting !== false;
4284
+ let permChoice = (() => {
4285
+ if (!permShown) return null;
4286
+ try {
4287
+ const v = localStorage.getItem(PERM_KEY);
4288
+ if (v === "ask" || v === "auto") return v;
4289
+ } catch {
4290
+ }
4291
+ return null;
4292
+ })();
4293
+ const permAuto = () => (permChoice ?? agentOpts.permissions ?? "ask") === "auto";
4294
+ const setPerm = (p, quiet = false) => {
4295
+ const was = permAuto();
4296
+ permChoice = p;
4297
+ if (permShown) {
4298
+ try {
4299
+ if (p) localStorage.setItem(PERM_KEY, p);
4300
+ else localStorage.removeItem(PERM_KEY);
4301
+ } catch {
4302
+ }
4303
+ }
4304
+ for (const a of live.values()) a.configure({ permissions: p ?? agentOpts.permissions ?? "ask" });
4305
+ if (!quiet && !was && permAuto()) ui.notify(t.permAutoNote);
4306
+ };
3599
4307
  left.append(attachBtn, webBtn, ...hostActions, hint);
3600
4308
  bar.append(left, acts);
3601
4309
  box.append(cmds, files, ta, bar, fileInput);
@@ -3644,6 +4352,7 @@ ${t.webHint}`;
3644
4352
  let cmdIndex = 0;
3645
4353
  let cmdFrame = null;
3646
4354
  let unsub = [];
4355
+ const unmountHooks = [];
3647
4356
  let menu = null;
3648
4357
  let mounted = true;
3649
4358
  const rootSize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
@@ -3704,15 +4413,16 @@ ${t.webHint}`;
3704
4413
  w?.forEach((f) => f(shown));
3705
4414
  };
3706
4415
  const uiFor = (id) => ({
3707
- confirm: async (title2, message, o) => await whenCurrent(id, o?.signal) ? ui.confirm(title2, message, o) : false,
4416
+ // A permission question gets "Always allow (this app)", which turns auto-run on (a tool's own `always` keeps its place).
4417
+ confirm: async (title2, message, o) => await whenCurrent(id, o?.signal) ? ui.confirm(title2, message, o?.permission && permShown && !o.always ? { ...o, always: { label: t.permAlways, onChoose: () => setPerm("auto") } } : o) : false,
3708
4418
  select: async (title2, options, o) => await whenCurrent(id, o?.signal) ? ui.select(title2, options, o) : null,
3709
4419
  input: async (title2, o) => await whenCurrent(id, o?.signal) ? ui.input(title2, o) : null,
3710
4420
  notify: (m, l) => ui.notify(m, l)
3711
4421
  });
3712
4422
  const restorable = (a) => !!a.workspace && typeof wsOpt === "function" && !a.workspace.root;
3713
- const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || a.queued.length > 0 || waiting.has(a.id)));
4423
+ const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || (a.queued?.length ?? 0) > 0 || waiting.has(a.id)));
3714
4424
  const titleOfAgent = (a) => {
3715
- const text = (0, import_index2.titleOf)({ v: 2, id: a.id, messages: a.messages, usage: a.usage, droppedTurns: 0, savedAt: 0 });
4425
+ const text = a.title ?? (0, import_index2.titleOf)({ v: 2, id: a.id, messages: a.messages, usage: a.usage, droppedTurns: 0, savedAt: 0 });
3716
4426
  return text === import_index2.UNTITLED ? t.untitled : text.length > 40 ? text.slice(0, 37) + "\u2026" : text;
3717
4427
  };
3718
4428
  const markBackground = () => histBtn.classList.toggle("ra-bg", background().length > 0);
@@ -3759,7 +4469,7 @@ ${t.webHint}`;
3759
4469
  ui.notify(`${titleOfAgent(a)} \xB7 ${t.finished}`);
3760
4470
  setTimeout(() => {
3761
4471
  if (!mounted) return;
3762
- if (agent !== a && !a.busy && !a.queued.length && !waiting.has(a.id)) {
4472
+ if (agent !== a && !a.busy && !a.queued?.length && !waiting.has(a.id)) {
3763
4473
  live.delete(a.id);
3764
4474
  unwatchBackground(a);
3765
4475
  release(a);
@@ -3945,7 +4655,7 @@ ${t.webHint}`;
3945
4655
  back.title = t.rewind;
3946
4656
  back.setAttribute("aria-label", t.rewind);
3947
4657
  back.addEventListener("click", () => void rewindTo(row));
3948
- foot.append(time, copy, back);
4658
+ foot.append(time, copy, ...replyActions?.rewind === false ? [] : [back]);
3949
4659
  el.addEventListener("mouseenter", () => row.update());
3950
4660
  row.update = () => {
3951
4661
  const ts = tsOf(row.msg);
@@ -4101,12 +4811,12 @@ ${t.webHint}`;
4101
4811
  ui.cancelAll();
4102
4812
  await a.abort();
4103
4813
  }
4104
- await a.remove(turn.start, turn.end);
4814
+ await a.remove?.(turn.start, turn.end);
4105
4815
  } catch (err) {
4106
4816
  ui.notify(err.message, "error");
4107
4817
  }
4108
4818
  })());
4109
- foot.append(copy, again, del);
4819
+ foot.append(copy, ...replyActions?.retry === false ? [] : [again], ...replyActions?.delete === false ? [] : [del]);
4110
4820
  const u = last.runUsage;
4111
4821
  if (u && u.calls) {
4112
4822
  const show = (currency) => {
@@ -4135,7 +4845,7 @@ ${t.webHint}`;
4135
4845
  const m = /^<file name="([^"]*)">\n([\s\S]*)\n<\/file>$/.exec(p.text);
4136
4846
  if (m) inline.set(m[1], m[2]);
4137
4847
  }
4138
- const images = parts.flatMap((p) => p.type === "image_url" && p.image_url.url.startsWith("data:") ? [p.image_url.url] : []);
4848
+ const images = imagesOf(parts);
4139
4849
  const files2 = [], paths = [], missing = [];
4140
4850
  for (const line of block.text.split("\n").slice(1)) {
4141
4851
  const a = parseAttachLine(line);
@@ -4365,6 +5075,7 @@ ${t.webHint}`;
4365
5075
  const d = displayOf(name), label = labelOf(name, args);
4366
5076
  const icon = h("span", "ra-ticon");
4367
5077
  icon.innerHTML = d?.icon ?? (TOOL_ICON[name] ?? I.wrench)();
5078
+ if (d?.tone) icon.dataset.tone = d.tone;
4368
5079
  const end = h("span", "ra-tend");
4369
5080
  end.innerHTML = '<span class="ra-spin"></span>';
4370
5081
  sum.innerHTML = `<span class="ra-chev">${I.chev()}</span>`;
@@ -4479,7 +5190,7 @@ ${t.webHint}`;
4479
5190
  list.schedule();
4480
5191
  return card;
4481
5192
  };
4482
- 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] : []) : [];
5193
+ 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] : []) : [];
4483
5194
  const offerFile = async (card) => {
4484
5195
  const ws = agent?.workspace;
4485
5196
  const d = displayOf(card.name), a = card.args;
@@ -4617,6 +5328,26 @@ ${t.webHint}`;
4617
5328
  active = null;
4618
5329
  let last = null;
4619
5330
  let lastUserTs;
5331
+ const src = agent;
5332
+ if (src?.hasOlder && src.loadOlder) {
5333
+ const b = h("button", "ra-btn ghost ra-older");
5334
+ b.type = "button";
5335
+ b.textContent = t.older;
5336
+ b.addEventListener("click", () => {
5337
+ if (src.busy) {
5338
+ ui.notify(t.olderBusy, "warning");
5339
+ return;
5340
+ }
5341
+ b.disabled = true;
5342
+ void src.loadOlder().catch((err) => {
5343
+ b.disabled = false;
5344
+ ui.notify(err.message, "error");
5345
+ });
5346
+ });
5347
+ const el = h("div", "ra-olderrow");
5348
+ el.append(b);
5349
+ addRow({ render: () => el, el });
5350
+ }
4620
5351
  const flush = (atEnd = false) => {
4621
5352
  if (!last) return;
4622
5353
  const m = last;
@@ -4727,17 +5458,24 @@ ${t.webHint}`;
4727
5458
  return "Shown to the user.";
4728
5459
  }
4729
5460
  };
4730
- const chatTools = [...agentOpts.tools ?? [], ...nextPrompt ? [nextPromptTool] : []];
5461
+ const schedCfg = scheduleOpt ? scheduleOpt === true ? {} : scheduleOpt : null;
5462
+ const schedStore = schedCfg ? schedCfg.store ?? localSchedules(`__runapps_agent_chat:${project}:schedules`) : null;
5463
+ const schedLabels = { schedule_list: () => t.tSchedList, schedule_add: (a) => t.tSchedAdd.replace("{name}", a.name ?? ""), schedule_update: () => t.tSchedUpdate, schedule_remove: () => t.tSchedRemove };
5464
+ const schedTools = schedStore && schedCfg.tools !== false ? scheduleTools(schedStore, { ...schedCfg, onChange: () => refreshSched() }).map((x) => ({ ...x, display: { ...x.display, icon: I.clock(), label: schedLabels[x.name] } })) : [];
5465
+ const chatTools = [...agentOpts.tools ?? [], ...nextPrompt ? [nextPromptTool] : [], ...schedTools];
4731
5466
  const hiddenTools = new Set(chatTools.filter((x) => x.display?.hidden).map((x) => x.name));
5467
+ const hideToolsOf = (a) => {
5468
+ for (const x of a.tools ?? []) if (x.display?.hidden) hiddenTools.add(x.name);
5469
+ };
4732
5470
  const syncSend = () => {
4733
5471
  const busy = root.dataset.busy === "1", any = !!(ta.value.trim() || pendingFiles.length || pendingContext.length);
4734
5472
  sendBtn.style.display = !busy && any ? "" : "none";
4735
- steerBtn.style.display = fuBtn.style.display = busy && any ? "" : "none";
5473
+ steerBtn.style.display = fuBtn.style.display = canQueue && busy && any ? "" : "none";
4736
5474
  };
4737
5475
  const setBusy = (busy) => {
4738
5476
  root.dataset.busy = busy ? "1" : "";
4739
- ta.placeholder = busy ? fill(t.placeholderBusy) : nextSuggestion ?? placeholder ?? t.placeholder;
4740
- hint.textContent = fill(busy ? t.hintBusy : nextSuggestion ? t.hintNext : t.hintIdle);
5477
+ ta.placeholder = busy && canQueue ? fill(t.placeholderBusy) : nextSuggestion ?? placeholder ?? t.placeholder;
5478
+ hint.textContent = fill(busy && canQueue ? t.hintBusy : nextSuggestion ? t.hintNext : t.hintIdle);
4741
5479
  syncSend();
4742
5480
  stopBtn.style.display = busy ? "" : "none";
4743
5481
  renderQueue();
@@ -4768,18 +5506,18 @@ ${t.webHint}`;
4768
5506
  const actions = (item) => {
4769
5507
  const box2 = h("span", "ra-qa");
4770
5508
  if (item.kind !== "steer") box2.append(btn(I.enter(), t.sendNow, () => {
4771
- if (a.dequeue(item.message)) a.steer(item.message.content);
5509
+ if (a.dequeue?.(item.message)) a.steer?.(item.message.content);
4772
5510
  renderQueue();
4773
5511
  }));
4774
5512
  box2.append(btn(I.pen(), t.editQueued, () => {
4775
- if (!a.dequeue(item.message)) return;
5513
+ if (!a.dequeue?.(item.message)) return;
4776
5514
  ta.value = ta.value.trim() ? `${textOf(item.message)}
4777
5515
  ${ta.value}` : textOf(item.message);
4778
5516
  ta.focus();
4779
5517
  renderQueue();
4780
5518
  }));
4781
5519
  box2.append(btn(I.x(14), t.remove, () => {
4782
- a.dequeue(item.message);
5520
+ a.dequeue?.(item.message);
4783
5521
  renderQueue();
4784
5522
  }));
4785
5523
  return box2;
@@ -4947,7 +5685,7 @@ ${ta.value}` : textOf(item.message);
4947
5685
  renderFiles();
4948
5686
  ta.focus();
4949
5687
  };
4950
- attachBtn.addEventListener("click", () => fileInput.click());
5688
+ attachBtn.addEventListener("click", () => chooseFiles(fileInput, (picked) => void addFiles(picked)));
4951
5689
  fileInput.addEventListener("change", () => {
4952
5690
  void addFiles(fileInput.files);
4953
5691
  fileInput.value = "";
@@ -5027,6 +5765,14 @@ ${a.text}
5027
5765
  parts.push({ type: "video_url", video_url: { url: b64 } });
5028
5766
  }
5029
5767
  if (a.image && !blind && a.file.size <= MAX_IMAGE_PART) {
5768
+ if (uploadImage) {
5769
+ try {
5770
+ parts.push({ type: "image_url", image_url: { url: await uploadImage(a.file) } });
5771
+ } catch (err) {
5772
+ ui.notify(`${a.name}: ${err?.message || String(err)}`, "error");
5773
+ }
5774
+ continue;
5775
+ }
5030
5776
  const b64 = await new Promise((res) => {
5031
5777
  const r = new FileReader();
5032
5778
  r.onload = () => res(String(r.result));
@@ -5050,6 +5796,7 @@ ${lines.join("\n")}` });
5050
5796
  if (!text && !pendingFiles.length && !pendingContext.length || !agent || sending) return;
5051
5797
  clearNext();
5052
5798
  if (runBuiltin(text)) return;
5799
+ if (!canQueue && (agent.busy || compacting)) return;
5053
5800
  if (compacting) mode = "followUp";
5054
5801
  const a = agent;
5055
5802
  const taken = pendingFiles.splice(0);
@@ -5091,8 +5838,8 @@ ${c.text}` })));
5091
5838
  await a.prompt(content);
5092
5839
  return;
5093
5840
  }
5094
- if (mode === "steer") a.steer(content);
5095
- else void a.followUp(content).catch(() => void 0);
5841
+ if (mode === "steer") a.steer?.(content);
5842
+ else void a.followUp?.(content).catch(() => void 0);
5096
5843
  renderQueue();
5097
5844
  } catch (err) {
5098
5845
  awaitingRow = null;
@@ -5217,7 +5964,6 @@ ${c.text}` })));
5217
5964
  }
5218
5965
  };
5219
5966
  let userSettings = givenAgent ? {} : readSettings();
5220
- let permChoice = null;
5221
5967
  const hasSettings = opts.settings ?? !givenAgent;
5222
5968
  let settingsTab = 0;
5223
5969
  if (!hasSettings) setBtn.style.display = "none";
@@ -5462,7 +6208,7 @@ ${c.text}` })));
5462
6208
  }
5463
6209
  userSettings = {};
5464
6210
  writeSettings({});
5465
- permChoice = null;
6211
+ setPerm(null, true);
5466
6212
  for (const ag of live.values()) applyTo(ag, {}, null);
5467
6213
  closeMenu();
5468
6214
  ui.notify(t.applied);
@@ -5478,7 +6224,7 @@ ${c.text}` })));
5478
6224
  if (Number.isFinite(k) && k > 0) next.maxTokens = k;
5479
6225
  }
5480
6226
  if (effortSel.value && !effortSel.disabled) next.reasoningEffort = effortSel.value;
5481
- if (perm.value === "ask" || perm.value === "auto") permChoice = perm.value;
6227
+ if ((perm.value === "ask" || perm.value === "auto") && perm.value !== (permAuto() ? "auto" : "ask")) setPerm(perm.value);
5482
6228
  const summarize = sumSel.value === "summary";
5483
6229
  if (summarize !== hostCompaction.summarize) next.summarize = summarize;
5484
6230
  const at = atPick.read();
@@ -5527,7 +6273,7 @@ ${c.text}` })));
5527
6273
  const b = h("button");
5528
6274
  b.type = "button";
5529
6275
  const bg = s ? live.get(s.id) : void 0;
5530
- const state = s && bg && bg !== cur ? waiting.has(s.id) ? ` \xB7 ${t.waitingAnswer}` : bg.busy || bg.queued.length ? ` \xB7 ${t.running}` : "" : "";
6276
+ const state = s && bg && bg !== cur ? waiting.has(s.id) ? ` \xB7 ${t.waitingAnswer}` : bg.busy || bg.queued?.length ? ` \xB7 ${t.running}` : "" : "";
5531
6277
  const name = h("span", "ra-mt");
5532
6278
  if (state && !waiting.has(s.id)) name.append(h("span", "ra-spin"));
5533
6279
  name.append(h("span", "ra-mtt", (s ? s.title : titleOfAgent(cur)) || t.untitled));
@@ -5591,7 +6337,7 @@ ${c.text}` })));
5591
6337
  document.addEventListener("click", onDocClick, true);
5592
6338
  function onDocClick(e) {
5593
6339
  if (e.target?.closest?.(".ra-selp")) return;
5594
- if (menu && !menu.contains(e.target) && !histBtn.contains(e.target) && !setBtn.contains(e.target) && !skillsBtn.contains(e.target) && !useBtn.contains(e.target)) closeMenu();
6340
+ 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)) closeMenu();
5595
6341
  }
5596
6342
  const skillInput = h("input");
5597
6343
  skillInput.type = "file";
@@ -5647,7 +6393,7 @@ ${c.text}` })));
5647
6393
  const up = h("button", "ra-btn xs solid");
5648
6394
  up.type = "button";
5649
6395
  up.innerHTML = I.upload(13) + `<span>${escapeHTML(t.uploadZip)}</span>`;
5650
- up.addEventListener("click", () => skillInput.click());
6396
+ up.addEventListener("click", () => chooseFiles(skillInput, (picked) => void installZips(picked)));
5651
6397
  if (!ws.userSkillsDir) up.style.display = "none";
5652
6398
  head2.append(h("span", "", skills.length ? `${t.skills} \xB7 ${skills.length}` : t.skills), up);
5653
6399
  mine.append(head2);
@@ -5722,6 +6468,285 @@ ${c.text}` })));
5722
6468
  });
5723
6469
  };
5724
6470
  skillsBtn.addEventListener("click", () => void openSkills());
6471
+ if (!schedStore) schedBtn.style.display = "none";
6472
+ const schedLimits = { minMinutes: schedCfg?.minMinutes, maxTasks: schedCfg?.maxTasks };
6473
+ const dayNames = t.schedDayNames.split(",");
6474
+ const zhWords = /[\u4e00-\u9fff]/.test(t.sched);
6475
+ const fmtShort = (ms) => {
6476
+ const s = formatLocalTime(ms);
6477
+ return s.slice(0, 4) === String((/* @__PURE__ */ new Date()).getFullYear()) ? s.slice(5) : s;
6478
+ };
6479
+ const runScheduled = async (task) => {
6480
+ await ready;
6481
+ const text = `${t.schedRunHead.replace("{name}", task.name).replace("{time}", formatLocalTime(Date.now()))}
6482
+
6483
+ ${task.prompt}`;
6484
+ let a;
6485
+ if (givenAgent || oneChat) a = agent ?? givenAgent;
6486
+ else {
6487
+ const sid = task.session ?? `sched_${task.id}`;
6488
+ if (!task.session) {
6489
+ const cur = await schedStore.get(task.id);
6490
+ if (cur) await schedStore.put({ ...cur, session: sid });
6491
+ }
6492
+ a = agent?.id === sid ? agent : live.get(sid) ?? await makeAgent(sid);
6493
+ if (a !== agent) {
6494
+ await a.ready();
6495
+ live.set(sid, a);
6496
+ watchBackground(a);
6497
+ }
6498
+ }
6499
+ if (!givenAgent && !oneChat) a.setTitle?.(`\u23F0 ${task.name}`);
6500
+ ui.notify(t.schedStarted.replace("{name}", task.name));
6501
+ const r = a === agent ? await promptFromHost(text) : await a.prompt(text);
6502
+ refreshHistCount();
6503
+ if (r.reason === "error" || r.reason === "max_turns") ui.notify(t.schedFailed.replace("{name}", task.name).replace("{error}", r.error?.message ?? r.reason), "warning");
6504
+ 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 } : {} };
6505
+ };
6506
+ const schedIdle = () => mounted && !switching && !!agent && asked === 0 && waiting.size === 0 && ![...live.values()].some((a) => a.busy || (a.queued?.length ?? 0) > 0) && !(document.activeElement === ta && ta.value.trim());
6507
+ const scheduler = schedStore ? new Scheduler({ store: schedStore, run: runScheduled, idle: schedIdle, lockPrefix: `__runapps_agent_chat:${project}:schedules`, onChange: () => refreshSched() }) : null;
6508
+ if (scheduler) {
6509
+ const again = () => setTimeout(() => void scheduler.tick(), 1500);
6510
+ let lastBusy = false;
6511
+ const poll = setInterval(() => {
6512
+ const b = !schedIdle();
6513
+ if (lastBusy && !b) again();
6514
+ lastBusy = b;
6515
+ }, 3e3);
6516
+ unmountHooks.push(() => {
6517
+ clearInterval(poll);
6518
+ scheduler.stop();
6519
+ });
6520
+ }
6521
+ let schedView = "list";
6522
+ const refreshSched = () => {
6523
+ if (!schedStore) return;
6524
+ void schedStore.list().then((all) => {
6525
+ setSchedCount(all.filter((x) => x.enabled).length);
6526
+ if (menu?.classList.contains("ra-schm") && schedView === "list") drawSchedList(menu);
6527
+ }).catch(() => void 0);
6528
+ };
6529
+ const openSched = () => {
6530
+ if (menu) {
6531
+ const was = menu.classList.contains("ra-schm");
6532
+ closeMenu();
6533
+ if (was) return;
6534
+ }
6535
+ if (!schedStore) return;
6536
+ const mine = h("div", "ra-menu ra-skm ra-schm");
6537
+ menu = mine;
6538
+ placeMenu(mine);
6539
+ void drawSchedList(mine);
6540
+ };
6541
+ const drawSchedList = async (mine) => {
6542
+ schedView = "list";
6543
+ let all = [];
6544
+ try {
6545
+ all = await schedStore.list();
6546
+ } catch (err) {
6547
+ ui.notify(err.message, "error");
6548
+ }
6549
+ if (menu !== mine) return;
6550
+ all.sort((a, b) => a.enabled === b.enabled ? (a.next ?? Infinity) - (b.next ?? Infinity) : a.enabled ? -1 : 1);
6551
+ mine.replaceChildren();
6552
+ const head2 = h("div", "ra-skh");
6553
+ const add = h("button", "ra-btn xs solid");
6554
+ add.type = "button";
6555
+ add.innerHTML = I.plus(13) + `<span>${escapeHTML(t.schedNew)}</span>`;
6556
+ add.addEventListener("click", () => drawSchedForm(mine, null));
6557
+ head2.append(h("span", "", all.length ? `${t.sched} \xB7 ${all.length}` : t.sched), add);
6558
+ mine.append(head2);
6559
+ if (!all.length) mine.append(h("div", "ra-none", t.schedNone));
6560
+ const statusWord = { ok: t.schedOk, error: t.schedErr, stopped: t.schedStopped };
6561
+ for (const task of all) {
6562
+ const row = h("div", "ra-mi" + (task.enabled ? "" : " ra-off"));
6563
+ const b = h("button");
6564
+ b.type = "button";
6565
+ b.title = t.schedEdit;
6566
+ const name = h("span", "ra-mt");
6567
+ const running = scheduler?.running.has(task.id);
6568
+ if (running) name.append(h("span", "ra-spin"));
6569
+ name.append(h("span", "ra-mtt", task.name));
6570
+ if (running) name.append(h("span", "ra-skb on", t.schedRunning));
6571
+ else if (!task.enabled) name.append(h("span", "ra-skb", t.schedPaused));
6572
+ if (task.by === "agent") name.append(h("span", "ra-skb", t.schedByAI));
6573
+ const when = `${describeSchedule(task.schedule, zhWords ? "zh" : "en")} \xB7 ${task.enabled && task.next ? t.schedNext.replace("{time}", fmtShort(task.next)) : task.enabled ? t.schedNoNext : t.schedPaused}`;
6574
+ b.append(name, h("small", "", when));
6575
+ if (task.last) 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})` : ""))));
6576
+ b.addEventListener("click", () => drawSchedForm(mine, task));
6577
+ const act = (icon, title2, fn, cls = "ra-x ra-ia") => {
6578
+ const x = h("button", cls);
6579
+ x.type = "button";
6580
+ x.innerHTML = icon;
6581
+ x.title = title2;
6582
+ x.setAttribute("aria-label", title2);
6583
+ x.addEventListener("click", (e) => {
6584
+ e.stopPropagation();
6585
+ fn();
6586
+ });
6587
+ return x;
6588
+ };
6589
+ const runB = act(I.play(), t.schedRunNow, () => {
6590
+ void scheduler.runNow(task.id).then((ok) => {
6591
+ if (!ok) ui.notify(t.schedBusy, "warning");
6592
+ });
6593
+ setTimeout(refreshSched, 100);
6594
+ });
6595
+ const pauseB = act(task.enabled ? I.pause() : I.clock(13), task.enabled ? t.schedPause : t.schedResume, async () => {
6596
+ try {
6597
+ const cur = await schedStore.get(task.id);
6598
+ if (cur) await schedStore.put(changeTask(cur, { enabled: !cur.enabled }, schedLimits));
6599
+ } catch (err) {
6600
+ ui.notify(err.message, "error");
6601
+ }
6602
+ refreshSched();
6603
+ });
6604
+ const openB = act(I.message(), t.schedOpen, () => {
6605
+ closeMenu();
6606
+ if (task.session) void resume(task.session).catch((err) => ui.notify(err.message, "error"));
6607
+ });
6608
+ if (!task.session || givenAgent || oneChat) openB.style.display = "none";
6609
+ const del = act(I.trash(), t.schedDel, async () => {
6610
+ closeMenu();
6611
+ if (!await modalConfirm(root, t.schedDel, t.schedDelMsg.replace("{name}", task.name), { danger: true, ok: t.delete, cancel: t.cancel })) return;
6612
+ try {
6613
+ await schedStore.delete(task.id);
6614
+ } catch (err) {
6615
+ ui.notify(err.message, "error");
6616
+ }
6617
+ refreshSched();
6618
+ }, "ra-x");
6619
+ row.append(b, runB, pauseB, openB, del);
6620
+ mine.append(row);
6621
+ }
6622
+ mine.append(h("div", "ra-skf", t.schedHint));
6623
+ };
6624
+ const drawSchedForm = (mine, task) => {
6625
+ schedView = "form";
6626
+ for (const b of menuSelects.splice(0)) b.close();
6627
+ mine.replaceChildren();
6628
+ const form = h("div", "ra-schf");
6629
+ const field = (label, ...els) => {
6630
+ const l = h("div", "ra-fld");
6631
+ l.append(h("span", "", label), ...els);
6632
+ return l;
6633
+ };
6634
+ const nameIn = h("input");
6635
+ nameIn.type = "text";
6636
+ nameIn.placeholder = t.schedNamePh;
6637
+ nameIn.value = task?.name ?? "";
6638
+ const promptIn = h("textarea");
6639
+ promptIn.placeholder = t.schedPromptPh;
6640
+ promptIn.value = task?.prompt ?? "";
6641
+ const s0 = task?.schedule ?? { type: "daily", time: "09:00" };
6642
+ 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 });
6643
+ menuSelects.push(typeSel);
6644
+ const atIn = h("input");
6645
+ atIn.type = "datetime-local";
6646
+ const at0 = s0.type === "once" ? parseLocalTime(s0.at) : Date.now() + 36e5;
6647
+ atIn.value = formatLocalTime(Number.isFinite(at0) ? at0 : Date.now() + 36e5).replace(" ", "T");
6648
+ const everyN = h("input");
6649
+ everyN.type = "number";
6650
+ everyN.min = "1";
6651
+ everyN.step = "1";
6652
+ const m0 = s0.type === "every" ? s0.minutes : 60;
6653
+ const unit0 = m0 % 1440 === 0 ? "1440" : m0 % 60 === 0 ? "60" : "1";
6654
+ everyN.value = String(m0 / Number(unit0));
6655
+ const unitSel = selectBox(root, { options: [{ value: "1", label: t.schedMin }, { value: "60", label: t.schedHour }, { value: "1440", label: t.schedDay }], value: unit0 });
6656
+ menuSelects.push(unitSel);
6657
+ const everyRow = h("div", "ra-row");
6658
+ everyRow.append(everyN, unitSel.el);
6659
+ const timeIn = h("input");
6660
+ timeIn.type = "time";
6661
+ timeIn.value = s0.type === "daily" ? s0.time : "09:00";
6662
+ const days = new Set(s0.type === "daily" && s0.days?.length ? s0.days : [0, 1, 2, 3, 4, 5, 6]);
6663
+ const dayRow = h("div", "ra-days");
6664
+ for (const d of [1, 2, 3, 4, 5, 6, 0]) {
6665
+ const db = h("button", days.has(d) ? "on" : "", dayNames[d]);
6666
+ db.type = "button";
6667
+ db.addEventListener("click", () => {
6668
+ if (days.has(d)) {
6669
+ if (days.size > 1) days.delete(d);
6670
+ } else days.add(d);
6671
+ db.classList.toggle("on", days.has(d));
6672
+ preview();
6673
+ });
6674
+ dayRow.append(db);
6675
+ }
6676
+ const dailyBox = h("div", "ra-row ra-col2");
6677
+ dailyBox.append(timeIn, dayRow);
6678
+ const cronIn = h("input");
6679
+ cronIn.type = "text";
6680
+ cronIn.placeholder = "0 9 * * 1-5";
6681
+ cronIn.value = s0.type === "cron" ? s0.cron : "";
6682
+ const cronBox = h("div", "ra-fld");
6683
+ cronBox.append(cronIn, h("span", "ra-note", t.schedCronHint));
6684
+ const whenBox = h("div", "ra-fld");
6685
+ const note = h("div", "ra-note");
6686
+ const build = () => {
6687
+ switch (typeSel.value) {
6688
+ case "once":
6689
+ return { type: "once", at: atIn.value.replace("T", " ") };
6690
+ case "every":
6691
+ return { type: "every", minutes: Math.round(Number(everyN.value) * Number(unitSel.value)) };
6692
+ case "cron":
6693
+ return { type: "cron", cron: cronIn.value.trim() };
6694
+ default:
6695
+ return { type: "daily", time: timeIn.value, ...days.size < 7 ? { days: [...days].sort((a, b) => a - b) } : {} };
6696
+ }
6697
+ };
6698
+ const preview = () => {
6699
+ const sc = build();
6700
+ const problem = checkSchedule(sc, schedLimits.minMinutes ?? 5);
6701
+ const nx = problem ? null : nextRun(sc, Date.now());
6702
+ note.textContent = problem ?? (nx ? t.schedNext.replace("{time}", formatLocalTime(nx)) : t.schedNoNext);
6703
+ note.classList.toggle("err", !!problem || !nx);
6704
+ save.disabled = !!problem || !nx || !nameIn.value.trim() || !promptIn.value.trim();
6705
+ };
6706
+ const showType = () => {
6707
+ const v = typeSel.value;
6708
+ whenBox.replaceChildren(typeSel.el, ...v === "once" ? [atIn] : v === "every" ? [everyRow] : v === "cron" ? [cronBox] : [dailyBox]);
6709
+ preview();
6710
+ };
6711
+ typeSel.el.addEventListener("change", showType);
6712
+ unitSel.el.addEventListener("change", preview);
6713
+ for (const el of [nameIn, promptIn, atIn, everyN, timeIn, cronIn]) el.addEventListener("input", preview);
6714
+ const btns = h("div", "ra-btns");
6715
+ const cancel = h("button", "ra-btn xs ghost", t.cancel);
6716
+ cancel.type = "button";
6717
+ const save = h("button", "ra-btn xs solid", t.schedSave);
6718
+ save.type = "button";
6719
+ cancel.addEventListener("click", () => {
6720
+ for (const b of menuSelects.splice(0)) b.close();
6721
+ void drawSchedList(mine);
6722
+ });
6723
+ save.addEventListener("click", async () => {
6724
+ try {
6725
+ const fields = { name: nameIn.value, prompt: promptIn.value, schedule: build() };
6726
+ if (task) {
6727
+ const cur = await schedStore.get(task.id);
6728
+ if (!cur) throw new Error("gone");
6729
+ await schedStore.put(changeTask(cur, { ...fields, enabled: true }, schedLimits));
6730
+ } else {
6731
+ if ((await schedStore.list()).length >= (schedLimits.maxTasks ?? 20)) throw new Error(`${schedLimits.maxTasks ?? 20} tasks at most`);
6732
+ await schedStore.put(makeTask({ ...fields, by: "user" }, schedLimits));
6733
+ }
6734
+ for (const b of menuSelects.splice(0)) b.close();
6735
+ await drawSchedList(mine);
6736
+ refreshSched();
6737
+ } catch (err) {
6738
+ note.textContent = err.message;
6739
+ note.classList.add("err");
6740
+ }
6741
+ });
6742
+ btns.append(cancel, save);
6743
+ 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);
6744
+ mine.append(form);
6745
+ showType();
6746
+ queueMicrotask(() => (task ? promptIn : nameIn).focus());
6747
+ };
6748
+ schedBtn.addEventListener("click", () => openSched());
6749
+ refreshSched();
5725
6750
  const fail = (err) => ui.notify(err.message, "error");
5726
6751
  let compacting = false;
5727
6752
  const transcriptMarkdown = (a) => {
@@ -5821,7 +6846,7 @@ ${c.text}` })));
5821
6846
  compacting = true;
5822
6847
  let summary = null;
5823
6848
  try {
5824
- summary = await a.summarize(asked2?.msg);
6849
+ summary = await a.summarize?.(asked2?.msg) ?? null;
5825
6850
  } finally {
5826
6851
  compacting = false;
5827
6852
  closeActive();
@@ -5830,7 +6855,7 @@ ${c.text}` })));
5830
6855
  await (oneChat ? clearConversation() : newSession().then(() => void 0));
5831
6856
  const b = agent;
5832
6857
  if (summary) {
5833
- await b.seed(summary);
6858
+ await b.seed?.(summary);
5834
6859
  renderHistory(b.messages);
5835
6860
  showUsage_(b);
5836
6861
  } else if (a.messages.length > 1) ui.notify(t.ovNoSummary, "warning");
@@ -6017,7 +7042,7 @@ ${c.text}` })));
6017
7042
  else ui.notify(t.debugOff);
6018
7043
  } }
6019
7044
  ];
6020
- const builtinCommands = () => builtins.filter((b) => (b.name !== "files" || !!agent?.workspace && filesOpt !== false) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || !givenAgent && !!agent?.workspace && !oneChat)).map((b) => ({ name: b.name, description: b.name === "new" && oneChat ? t.confirmClear.split(/[??]/)[0] : t.cmd[b.name] ?? "", kind: t.command, args: b.args, builtin: true }));
7045
+ const builtinCommands = () => builtins.filter((b) => (!commandsOpt || commandsOpt.includes(b.name)) && (b.name !== "files" || !!agent?.workspace && filesOpt !== false) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || !givenAgent && !!agent?.workspace && !oneChat)).map((b) => ({ name: b.name, description: b.name === "new" && oneChat ? t.confirmClear.split(/[??]/)[0] : t.cmd[b.name] ?? "", kind: t.command, args: b.args, builtin: true }));
6021
7046
  const runBuiltin = (text) => {
6022
7047
  const m = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text);
6023
7048
  if (!m) return false;
@@ -6066,7 +7091,7 @@ ${c.text}` })));
6066
7091
  const cap2 = (x) => x.charAt(0).toUpperCase() + x.slice(1);
6067
7092
  const compactLine = (a, window2) => {
6068
7093
  const c = a.compactionFor(window2);
6069
- return `${c.summarize ? t.autoCompact : t.autoTrim}: ${t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens))}`;
7094
+ return `${c.summarize ? t.autoCompact : t.autoTrim}: ${c.reserveTokens > 0 ? t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens)) : t.autoCompactFull}`;
6070
7095
  };
6071
7096
  const pctOf = (used, window2) => {
6072
7097
  const p = used / window2;
@@ -6135,6 +7160,7 @@ ${c.text}` })));
6135
7160
  const attach = async (a) => {
6136
7161
  for (const u of unsub) u();
6137
7162
  unsub = [];
7163
+ hideToolsOf(a);
6138
7164
  if (a.workspace) {
6139
7165
  const ws = a.workspace;
6140
7166
  unsub.push(ws.onChange((c) => {
@@ -6212,6 +7238,19 @@ ${c.text}` })));
6212
7238
  showUsage_(a);
6213
7239
  }
6214
7240
  });
7241
+ on("history", (ev) => {
7242
+ if (agent !== a) return;
7243
+ const before = list.length, hadOlder = before > 0 && list.rows[0]?.el?.classList.contains("ra-olderrow") === true;
7244
+ const following = list.follow, top = log.scrollTop;
7245
+ renderHistory(a.messages);
7246
+ if (ev.reason === "older") list.scrollToIndex(Math.max(0, list.length - (before - (hadOlder ? 1 : 0))));
7247
+ else if (ev.reason === "newer" && !following) {
7248
+ list.follow = false;
7249
+ log.scrollTop = top;
7250
+ list.layout();
7251
+ }
7252
+ showUsage_(a);
7253
+ });
6215
7254
  on("text_delta", (ev) => {
6216
7255
  const act = ensureActive();
6217
7256
  clearPending(act);
@@ -6301,7 +7340,7 @@ ${c.text}` })));
6301
7340
  if (!ev.summary && ev.runId && trimNoted === ev.runId) return;
6302
7341
  if (!ev.summary) trimNoted = ev.runId ?? null;
6303
7342
  const first = a.messages[0];
6304
- const s = first && typeof first.content === "string" ? (0, import_index2.summaryOf)(first) : null;
7343
+ const s = ev.summaryText ?? (first && typeof first.content === "string" ? (0, import_index2.summaryOf)(first) : null);
6305
7344
  addNote(ev.summary ? t.compacted : t.trimmed, ev.summary && s ? s : void 0);
6306
7345
  });
6307
7346
  on("run_end", (r) => {
@@ -6364,7 +7403,7 @@ ${c.text}` })));
6364
7403
  if (id && id === agent?.id) return agent;
6365
7404
  const prev = agent;
6366
7405
  if (prev) {
6367
- if (prev.busy || prev.queued.length > 0) {
7406
+ if (prev.busy || (prev.queued?.length ?? 0) > 0) {
6368
7407
  if (background().length >= MAX_BACKGROUND) {
6369
7408
  ui.notify(t.bgLimit.replace("{n}", String(background().length)), "warning");
6370
7409
  return prev;
@@ -6390,7 +7429,7 @@ ${c.text}` })));
6390
7429
  await ready;
6391
7430
  const a = agent ?? givenAgent;
6392
7431
  ui.cancelAll();
6393
- await a.clear();
7432
+ await a.clear?.();
6394
7433
  if (agent === a || givenAgent === a) {
6395
7434
  renderHistory(a.messages);
6396
7435
  showUsage_(a);
@@ -6429,6 +7468,9 @@ ${c.text}` })));
6429
7468
  const firstId = agentOpts.id ?? (typeof resumeOpt === "string" ? resumeOpt : resumeOpt === false ? void 0 : readLast(project) ?? void 0);
6430
7469
  const starting = givenAgent ? Promise.resolve(givenAgent) : makeAgent(firstId);
6431
7470
  const ready = starting.then((a) => attach(a));
7471
+ if (scheduler) void ready.then(() => {
7472
+ if (mounted) scheduler.start();
7473
+ }).catch(() => void 0);
6432
7474
  ready.catch((err) => {
6433
7475
  addError(`${err.message}`);
6434
7476
  setBusy(false);
@@ -6471,6 +7513,9 @@ ${c.text}` })));
6471
7513
  debugOn = on;
6472
7514
  applyDebug();
6473
7515
  },
7516
+ setTitle(text) {
7517
+ titleEl.textContent = text;
7518
+ },
6474
7519
  updateComposerAction(id, patch) {
6475
7520
  const e = actionBtns.get(id);
6476
7521
  if (!e) return;
@@ -6489,6 +7534,12 @@ ${c.text}` })));
6489
7534
  mounted = false;
6490
7535
  if (histTimer) clearTimeout(histTimer);
6491
7536
  for (const u of unsub) u();
7537
+ for (const u of unmountHooks.splice(0)) {
7538
+ try {
7539
+ u();
7540
+ } catch {
7541
+ }
7542
+ }
6492
7543
  ui.cancelAll(true);
6493
7544
  closeMenu();
6494
7545
  document.removeEventListener("click", onDocClick, true);