@runappsai/agent 0.1.11 → 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/ui.cjs CHANGED
@@ -552,6 +552,10 @@ function h(tag, cls, text) {
552
552
  }
553
553
  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
554
  var I = {
555
+ 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"/>'),
556
+ play: (s = 13) => svg(s, '<polygon points="6 3 20 12 6 21 6 3"/>'),
557
+ 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"/>'),
558
+ 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
559
  tick: (s = 14) => svg(s, '<path d="M20 6 9 17l-5-5"/>'),
556
560
  enter: (s = 14) => svg(s, '<polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/>'),
557
561
  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 +662,36 @@ async function modalInput(root, title, opts) {
658
662
  const ok = await modal(root, { title, body: [field], ok: opts.ok, cancel: opts.cancel, focus: field, submitOnEnter: true });
659
663
  return ok ? field.value.trim() || null : null;
660
664
  }
665
+ var fileDialogOpt;
666
+ function setFileDialog(d) {
667
+ fileDialogOpt = d;
668
+ }
669
+ function fileDialog() {
670
+ if (fileDialogOpt === false) return void 0;
671
+ if (fileDialogOpt) return fileDialogOpt;
672
+ const ui = globalThis.puter?.ui;
673
+ return typeof ui?.openFiles === "function" && typeof ui?.saveFile === "function" ? ui : void 0;
674
+ }
675
+ function chooseFiles(input, onFiles) {
676
+ const d = fileDialog();
677
+ if (!d) {
678
+ input.click();
679
+ return;
680
+ }
681
+ d.openFiles({ accept: input.accept || void 0, multiple: input.multiple }).then((files) => {
682
+ if (files?.length) onFiles(files);
683
+ }, () => input.click());
684
+ }
661
685
  function downloadBlob(name, data, type) {
662
686
  const blob = new Blob([data], { type: type || "application/octet-stream" });
687
+ const d = fileDialog();
688
+ if (d) {
689
+ void d.saveFile(blob, name).catch(() => plainDownload(blob, name));
690
+ return;
691
+ }
692
+ plainDownload(blob, name);
693
+ }
694
+ function plainDownload(blob, name) {
663
695
  const url = URL.createObjectURL(blob);
664
696
  const a = h("a");
665
697
  a.href = url;
@@ -884,6 +916,460 @@ var SELECT_CSS = `
884
916
  :is(.ra-chat,.ra-ui) .ra-selnone{padding:8px;color:var(--ra-fg-muted)}
885
917
  `;
886
918
 
919
+ // src/tool.ts
920
+ var NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
921
+ function defineTool(def) {
922
+ if (!NAME_RE.test(def.name)) {
923
+ throw new Error(`tool name "${def.name}" must match ${NAME_RE}`);
924
+ }
925
+ if (!def.description || !def.description.trim()) {
926
+ throw new Error(`tool "${def.name}" needs a description`);
927
+ }
928
+ const parameters = def.parameters ?? { type: "object", properties: {}, additionalProperties: false };
929
+ return { ...def, parameters };
930
+ }
931
+
932
+ // src/schedule.ts
933
+ function localSchedules(key) {
934
+ const read = () => {
935
+ try {
936
+ const v = JSON.parse(localStorage.getItem(key) || "[]");
937
+ return Array.isArray(v) ? v : [];
938
+ } catch {
939
+ return [];
940
+ }
941
+ };
942
+ const write = (list) => {
943
+ try {
944
+ if (list.length) localStorage.setItem(key, JSON.stringify(list));
945
+ else localStorage.removeItem(key);
946
+ } catch {
947
+ }
948
+ };
949
+ const change = (fn) => lock(`${key}:write`, async () => {
950
+ write(fn(read()));
951
+ });
952
+ return {
953
+ list: async () => read(),
954
+ get: async (id) => read().find((t) => t.id === id),
955
+ put: (task) => change((list) => {
956
+ const i = list.findIndex((t) => t.id === task.id);
957
+ if (i >= 0) list[i] = task;
958
+ else list.push(task);
959
+ return list;
960
+ }),
961
+ delete: (id) => change((list) => list.filter((t) => t.id !== id)),
962
+ subscribe(fn) {
963
+ if (typeof window === "undefined") return () => {
964
+ };
965
+ const on = (e) => {
966
+ if (e.key === key) fn();
967
+ };
968
+ window.addEventListener("storage", on);
969
+ return () => window.removeEventListener("storage", on);
970
+ }
971
+ };
972
+ }
973
+ var locks = () => typeof navigator !== "undefined" ? navigator.locks : void 0;
974
+ function lock(name, fn) {
975
+ const l = locks();
976
+ return l ? l.request(name, {}, fn) : fn();
977
+ }
978
+ async function tryLock(name, fn) {
979
+ const l = locks();
980
+ if (!l) {
981
+ await fn();
982
+ return true;
983
+ }
984
+ let got = false;
985
+ await l.request(name, { ifAvailable: true }, async (held) => {
986
+ if (!held) return;
987
+ got = true;
988
+ await fn();
989
+ });
990
+ return got;
991
+ }
992
+ var HHMM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
993
+ function parseLocalTime(s) {
994
+ const m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(s.trim());
995
+ if (m) return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] ?? 0)).getTime();
996
+ return /[zZ]|[+-]\d{2}:?\d{2}$/.test(s) ? Date.parse(s) : NaN;
997
+ }
998
+ function formatLocalTime(ms) {
999
+ const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
1000
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
1001
+ }
1002
+ 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 };
1003
+ function parseCron(expr) {
1004
+ const f = expr.trim().split(/\s+/);
1005
+ if (f.length !== 5) throw new Error(`cron needs five fields (minute hour day month weekday), got "${expr}"`);
1006
+ const field = (s, lo, hi, what) => {
1007
+ const out = /* @__PURE__ */ new Set();
1008
+ for (const part of s.toLowerCase().split(",")) {
1009
+ const [range, stepS] = part.split("/");
1010
+ const step = stepS === void 0 ? 1 : Number(stepS);
1011
+ if (!Number.isInteger(step) || step < 1) throw new Error(`cron ${what}: bad step in "${part}"`);
1012
+ const num = (x) => {
1013
+ const n = CRON_NAMES[x] ?? Number(x);
1014
+ if (!Number.isInteger(n)) throw new Error(`cron ${what}: "${x}" is not a number`);
1015
+ return n;
1016
+ };
1017
+ let a, b;
1018
+ if (range === "*") {
1019
+ a = lo;
1020
+ b = hi;
1021
+ } else if (range.includes("-")) {
1022
+ const [x, y] = range.split("-");
1023
+ a = num(x);
1024
+ b = num(y);
1025
+ } else {
1026
+ a = num(range);
1027
+ b = stepS === void 0 ? a : hi;
1028
+ }
1029
+ if (what === "weekday") {
1030
+ if (a === 7) a = 0;
1031
+ if (b === 7 && a !== 0) b = 6, out.add(0);
1032
+ }
1033
+ if (a < lo || b > hi || a > b) throw new Error(`cron ${what}: "${part}" is outside ${lo}-${hi}`);
1034
+ for (let n = a; n <= b; n += step) out.add(n);
1035
+ }
1036
+ return out;
1037
+ };
1038
+ 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] === "*" };
1039
+ }
1040
+ function cronNext(c, after) {
1041
+ const start = new Date(after);
1042
+ start.setSeconds(0, 0);
1043
+ start.setMinutes(start.getMinutes() + 1);
1044
+ const hours = [...c.hour].sort((a, b) => a - b), mins = [...c.min].sort((a, b) => a - b);
1045
+ for (let day = 0; day < 366 * 5; day++) {
1046
+ const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + day);
1047
+ if (!c.mon.has(d.getMonth() + 1)) continue;
1048
+ const domOk = c.dom.has(d.getDate()), dowOk = c.dow.has(d.getDay());
1049
+ if (!(c.domAny && c.dowAny ? true : c.domAny ? dowOk : c.dowAny ? domOk : domOk || dowOk)) continue;
1050
+ for (const h2 of hours) for (const m of mins) {
1051
+ const t = new Date(d.getFullYear(), d.getMonth(), d.getDate(), h2, m).getTime();
1052
+ if (t >= start.getTime()) return t;
1053
+ }
1054
+ }
1055
+ return null;
1056
+ }
1057
+ function checkSchedule(s, minMinutes = 1) {
1058
+ switch (s?.type) {
1059
+ case "once":
1060
+ return Number.isFinite(parseLocalTime(s.at)) ? void 0 : `"at" must be a local time like 2026-11-28 09:00, got "${s.at}"`;
1061
+ case "every":
1062
+ return Number.isFinite(s.minutes) && s.minutes >= minMinutes ? void 0 : `"minutes" must be at least ${minMinutes}`;
1063
+ case "daily":
1064
+ if (!HHMM.test(s.time ?? "")) return `"time" must be HH:mm, got "${s.time}"`;
1065
+ 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`;
1066
+ return void 0;
1067
+ case "cron": {
1068
+ try {
1069
+ const c = parseCron(s.cron);
1070
+ if (cronNext(c, Date.now()) === null) return "this cron never runs";
1071
+ } catch (err) {
1072
+ return err.message;
1073
+ }
1074
+ if (minMinutes > 1) {
1075
+ const c = parseCron(s.cron);
1076
+ const a = cronNext(c, Date.now()), b = cronNext(c, a);
1077
+ if (b !== null && b - a < minMinutes * 6e4) return `runs more often than every ${minMinutes} minutes`;
1078
+ }
1079
+ return void 0;
1080
+ }
1081
+ default:
1082
+ return `"type" must be once, every, daily or cron`;
1083
+ }
1084
+ }
1085
+ function nextRun(s, after, from = after) {
1086
+ switch (s.type) {
1087
+ case "once": {
1088
+ const t = parseLocalTime(s.at);
1089
+ return Number.isFinite(t) && t > after ? t : null;
1090
+ }
1091
+ case "every": {
1092
+ const p = s.minutes * 6e4;
1093
+ let t = from + p;
1094
+ if (t <= after) t = after + p;
1095
+ return t;
1096
+ }
1097
+ case "daily": {
1098
+ const m = HHMM.exec(s.time);
1099
+ if (!m) return null;
1100
+ const base = new Date(after);
1101
+ for (let day = 0; day < 8; day++) {
1102
+ const d = new Date(base.getFullYear(), base.getMonth(), base.getDate() + day, +m[1], +m[2]);
1103
+ if (d.getTime() > after && (!s.days?.length || s.days.includes(d.getDay()))) return d.getTime();
1104
+ }
1105
+ return null;
1106
+ }
1107
+ case "cron":
1108
+ try {
1109
+ return cronNext(parseCron(s.cron), after);
1110
+ } catch {
1111
+ return null;
1112
+ }
1113
+ }
1114
+ }
1115
+ var DAY_EN = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
1116
+ var DAY_ZH = ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"];
1117
+ function describeSchedule(s, locale = "en") {
1118
+ const zh = locale === "zh";
1119
+ switch (s.type) {
1120
+ case "once": {
1121
+ const t = parseLocalTime(s.at);
1122
+ return (zh ? "\u4E00\u6B21 \xB7 " : "Once \xB7 ") + (Number.isFinite(t) ? formatLocalTime(t) : s.at);
1123
+ }
1124
+ case "every": {
1125
+ const m = s.minutes;
1126
+ 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`;
1127
+ return zh ? `\u6BCF ${v}` : `Every ${v}`;
1128
+ }
1129
+ case "daily": {
1130
+ const days = [...new Set(s.days ?? [])].sort((a, b) => a - b);
1131
+ if (!days.length || days.length === 7) return (zh ? "\u6BCF\u5929 " : "Daily ") + s.time;
1132
+ if (days.join() === "1,2,3,4,5") return (zh ? "\u5DE5\u4F5C\u65E5 " : "Weekdays ") + s.time;
1133
+ if (days.join() === "0,6") return (zh ? "\u5468\u672B " : "Weekends ") + s.time;
1134
+ return (zh ? "\u6BCF\u5468" + days.map((d) => DAY_ZH[d]).join("\u3001") + " " : days.map((d) => DAY_EN[d]).join(", ") + " ") + s.time;
1135
+ }
1136
+ case "cron":
1137
+ return `cron ${s.cron}`;
1138
+ }
1139
+ }
1140
+ var newTaskId = () => `t_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
1141
+ function makeTask(fields, limits = {}, now = Date.now()) {
1142
+ const name = fields.name?.trim(), prompt = fields.prompt?.trim();
1143
+ if (!name) throw new Error("a task needs a name");
1144
+ if (!prompt) throw new Error("a task needs a prompt");
1145
+ const problem = checkSchedule(fields.schedule, limits.minMinutes ?? 5);
1146
+ if (problem) throw new Error(problem);
1147
+ const enabled = fields.enabled ?? true;
1148
+ const next = enabled ? nextRun(fields.schedule, now) : null;
1149
+ if (enabled && next === null) throw new Error("that time has already passed");
1150
+ return { id: newTaskId(), name, prompt, schedule: fields.schedule, enabled, next, by: fields.by, created: now, updated: now, runs: 0 };
1151
+ }
1152
+ function changeTask(task, patch, limits = {}, now = Date.now()) {
1153
+ const out = { ...task, updated: now };
1154
+ if (patch.name !== void 0) {
1155
+ if (!patch.name.trim()) throw new Error("a task needs a name");
1156
+ out.name = patch.name.trim();
1157
+ }
1158
+ if (patch.prompt !== void 0) {
1159
+ if (!patch.prompt.trim()) throw new Error("a task needs a prompt");
1160
+ out.prompt = patch.prompt.trim();
1161
+ }
1162
+ if (patch.schedule) {
1163
+ const problem = checkSchedule(patch.schedule, limits.minMinutes ?? 5);
1164
+ if (problem) throw new Error(problem);
1165
+ out.schedule = patch.schedule;
1166
+ }
1167
+ if (patch.enabled !== void 0) out.enabled = patch.enabled;
1168
+ if (patch.schedule || patch.enabled !== void 0) {
1169
+ out.next = out.enabled ? nextRun(out.schedule, now) : null;
1170
+ if (out.enabled && out.next === null) throw new Error("that time has already passed");
1171
+ }
1172
+ return out;
1173
+ }
1174
+ var SCHEDULE_SCHEMA = {
1175
+ type: "object",
1176
+ 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).`,
1177
+ properties: {
1178
+ type: { type: "string", enum: ["once", "every", "daily", "cron"] },
1179
+ at: { type: "string" },
1180
+ in_minutes: { type: "number" },
1181
+ minutes: { type: "number" },
1182
+ time: { type: "string" },
1183
+ days: { type: "array", items: { type: "integer", minimum: 0, maximum: 6 } },
1184
+ cron: { type: "string" }
1185
+ },
1186
+ required: ["type"],
1187
+ additionalProperties: false
1188
+ };
1189
+ function toSchedule(a, now) {
1190
+ switch (a.type) {
1191
+ case "once":
1192
+ return { type: "once", at: a.at ?? (a.in_minutes !== void 0 ? formatLocalTime(now + Math.max(1, Math.round(a.in_minutes)) * 6e4) : "") };
1193
+ case "every":
1194
+ return { type: "every", minutes: Math.round(a.minutes ?? 0) };
1195
+ case "daily":
1196
+ return { type: "daily", time: a.time ?? "", ...a.days?.length ? { days: a.days } : {} };
1197
+ case "cron":
1198
+ return { type: "cron", cron: a.cron ?? "" };
1199
+ }
1200
+ }
1201
+ function taskLine(t, now = Date.now()) {
1202
+ return {
1203
+ id: t.id,
1204
+ name: t.name,
1205
+ prompt: t.prompt,
1206
+ schedule: describeSchedule(t.schedule),
1207
+ enabled: t.enabled,
1208
+ next: t.next ? formatLocalTime(t.next) : null,
1209
+ runs: t.runs,
1210
+ ...t.last ? { last_run: `${formatLocalTime(t.last.at)} ${t.last.status}${t.last.note ? ": " + t.last.note : ""}` } : {},
1211
+ ...t.next && t.next < now ? { overdue: true } : {}
1212
+ };
1213
+ }
1214
+ function scheduleTools(store, opts = {}) {
1215
+ const now = opts.now ?? Date.now;
1216
+ const tz = (() => {
1217
+ try {
1218
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
1219
+ } catch {
1220
+ return "local";
1221
+ }
1222
+ })();
1223
+ const changed = () => {
1224
+ try {
1225
+ opts.onChange?.();
1226
+ } catch {
1227
+ }
1228
+ };
1229
+ const header = () => `Now: ${formatLocalTime(now())} (${tz}).`;
1230
+ return [
1231
+ defineTool({
1232
+ name: "schedule_list",
1233
+ description: "Lists the scheduled tasks: prompts this app's agent runs on its own at set times (while the app is open).",
1234
+ readOnly: true,
1235
+ display: { label: () => "Scheduled tasks" },
1236
+ execute: async () => {
1237
+ const list = await store.list();
1238
+ return `${header()}
1239
+ ${list.length ? JSON.stringify(list.map((t) => taskLine(t, now())), null, 1) : "No scheduled tasks."}`;
1240
+ }
1241
+ }),
1242
+ defineTool({
1243
+ name: "schedule_add",
1244
+ 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.`,
1245
+ parameters: {
1246
+ type: "object",
1247
+ properties: {
1248
+ name: { type: "string", description: 'Short name the user sees, e.g. "Morning news digest".' },
1249
+ prompt: { type: "string", description: "The instruction for each run, complete on its own." },
1250
+ schedule: SCHEDULE_SCHEMA,
1251
+ enabled: { type: "boolean", description: "Default true." }
1252
+ },
1253
+ required: ["name", "prompt", "schedule"],
1254
+ additionalProperties: false
1255
+ },
1256
+ display: { label: (a) => `Schedule \u201C${a.name ?? ""}\u201D` },
1257
+ execute: async (a) => {
1258
+ const list = await store.list();
1259
+ if (list.length >= (opts.maxTasks ?? 20)) throw new Error(`there are already ${list.length} tasks, the most allowed; remove one first`);
1260
+ const task = makeTask({ name: a.name, prompt: a.prompt, schedule: toSchedule(a.schedule, now()), enabled: a.enabled, by: "agent" }, opts, now());
1261
+ await store.put(task);
1262
+ changed();
1263
+ return `${header()}
1264
+ Added: ${JSON.stringify(taskLine(task, now()))}`;
1265
+ }
1266
+ }),
1267
+ defineTool({
1268
+ name: "schedule_update",
1269
+ description: "Changes a scheduled task (by id, from schedule_list): its name, prompt, schedule, or enabled (false pauses it).",
1270
+ parameters: {
1271
+ type: "object",
1272
+ properties: { id: { type: "string" }, name: { type: "string" }, prompt: { type: "string" }, schedule: SCHEDULE_SCHEMA, enabled: { type: "boolean" } },
1273
+ required: ["id"],
1274
+ additionalProperties: false
1275
+ },
1276
+ display: { label: (a) => `Update scheduled task ${a.id ?? ""}` },
1277
+ execute: async (a) => {
1278
+ const task = await store.get(a.id);
1279
+ if (!task) throw new Error(`no task with id ${a.id}; schedule_list shows them`);
1280
+ const next = changeTask(task, { name: a.name, prompt: a.prompt, schedule: a.schedule ? toSchedule(a.schedule, now()) : void 0, enabled: a.enabled }, opts, now());
1281
+ await store.put(next);
1282
+ changed();
1283
+ return `${header()}
1284
+ Updated: ${JSON.stringify(taskLine(next, now()))}`;
1285
+ }
1286
+ }),
1287
+ defineTool({
1288
+ name: "schedule_remove",
1289
+ description: "Removes a scheduled task (by id). Its conversation stays.",
1290
+ parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"], additionalProperties: false },
1291
+ display: { label: (a) => `Remove scheduled task ${a.id ?? ""}` },
1292
+ execute: async (a) => {
1293
+ const task = await store.get(a.id);
1294
+ if (!task) throw new Error(`no task with id ${a.id}`);
1295
+ await store.delete(a.id);
1296
+ changed();
1297
+ return `Removed \u201C${task.name}\u201D.`;
1298
+ }
1299
+ })
1300
+ ];
1301
+ }
1302
+ var Scheduler = class {
1303
+ constructor(opts) {
1304
+ __publicField(this, "opts", opts);
1305
+ __publicField(this, "timer", null);
1306
+ __publicField(this, "busy", false);
1307
+ __publicField(this, "unsub", null);
1308
+ /** Ids of tasks this tab is running now. */
1309
+ __publicField(this, "running", /* @__PURE__ */ new Set());
1310
+ __publicField(this, "poke", () => void this.tick());
1311
+ }
1312
+ start() {
1313
+ if (this.timer) return;
1314
+ this.timer = setInterval(() => void this.tick(), this.opts.interval ?? 2e4);
1315
+ this.unsub = this.opts.store.subscribe?.(() => this.opts.onChange?.()) ?? null;
1316
+ if (typeof window !== "undefined") window.addEventListener("focus", this.poke);
1317
+ void this.tick();
1318
+ }
1319
+ stop() {
1320
+ if (this.timer) clearInterval(this.timer);
1321
+ this.timer = null;
1322
+ this.unsub?.();
1323
+ this.unsub = null;
1324
+ if (typeof window !== "undefined") window.removeEventListener("focus", this.poke);
1325
+ }
1326
+ /** Looks for a due task and runs it when idle. Resolves once that run is over. */
1327
+ async tick() {
1328
+ if (this.busy || !this.opts.idle()) return;
1329
+ const now = (this.opts.now ?? Date.now)();
1330
+ const due = (await this.opts.store.list()).filter((t) => t.enabled && t.next !== null && t.next <= now).sort((a, b) => a.next - b.next);
1331
+ for (const t of due) {
1332
+ if (this.busy || !this.opts.idle()) return;
1333
+ if (await this.fire(t.id, false)) return;
1334
+ }
1335
+ }
1336
+ /** Runs a task now (the user's "Run now"), whatever its time; false when it is already running somewhere. */
1337
+ runNow(id) {
1338
+ return this.fire(id, true);
1339
+ }
1340
+ async fire(id, force) {
1341
+ if (this.busy) return false;
1342
+ this.busy = true;
1343
+ let ran = false;
1344
+ try {
1345
+ await tryLock(`${this.opts.lockPrefix}:task:${id}`, async () => {
1346
+ const store = this.opts.store, clock2 = this.opts.now ?? Date.now;
1347
+ const task = await store.get(id);
1348
+ const now = clock2();
1349
+ if (!task || !force && (!task.enabled || task.next === null || task.next > now)) return;
1350
+ const next = task.enabled ? nextRun(task.schedule, now, now) : task.next;
1351
+ await store.put({ ...task, next: task.schedule.type === "once" && !force ? null : next, ...task.schedule.type === "once" && !force ? { enabled: false } : {} });
1352
+ ran = true;
1353
+ this.running.add(id);
1354
+ this.opts.onChange?.();
1355
+ let out;
1356
+ try {
1357
+ out = await this.opts.run(task);
1358
+ } catch (err) {
1359
+ out = { status: "error", note: err.message };
1360
+ }
1361
+ this.running.delete(id);
1362
+ const after = await store.get(id);
1363
+ if (after) await store.put({ ...after, runs: after.runs + 1, last: { at: now, ...out } });
1364
+ this.opts.onChange?.();
1365
+ });
1366
+ return ran;
1367
+ } finally {
1368
+ this.busy = false;
1369
+ }
1370
+ }
1371
+ };
1372
+
887
1373
  // src/compaction.ts
888
1374
  var DEFAULT_COMPACTION = { reserveTokens: 16384, keepRecentTokens: 2e4 };
889
1375
  function resolveSettings(window2, s = {}) {
@@ -970,7 +1456,7 @@ function filesPanel(opts) {
970
1456
  fileInput.type = "file";
971
1457
  fileInput.multiple = true;
972
1458
  fileInput.style.display = "none";
973
- const uploadBtn = ibtn(I.upload(), t.upload, () => fileInput.click());
1459
+ const uploadBtn = ibtn(I.upload(), t.upload, () => chooseFiles(fileInput, (picked) => void upload(picked)));
974
1460
  const zipBtn = ibtn(I.download(), t.downloadZip, () => void downloadFolder("/"));
975
1461
  const newBtn = ibtn(I.filePlus(14), t.newFile, () => void newFile());
976
1462
  const refreshBtn = ibtn(I.refresh(), t.refresh, () => void refresh());
@@ -2102,6 +2588,51 @@ var STRINGS = {
2102
2588
  webOn: "Web search: on",
2103
2589
  webOff: "Web search: off",
2104
2590
  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",
2591
+ permAlways: "Always allow (this app)",
2592
+ sched: "Scheduled",
2593
+ schedNew: "New task",
2594
+ schedNone: 'No scheduled tasks yet. Ask the AI ("every weekday at 9, summarise the news") or add one.',
2595
+ 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.",
2596
+ schedName: "Name",
2597
+ schedPrompt: "What to do",
2598
+ schedWhen: "When",
2599
+ schedOnce: "Once",
2600
+ schedEvery: "Every",
2601
+ schedDaily: "Daily / weekly",
2602
+ schedCron: "Cron",
2603
+ schedMin: "minutes",
2604
+ schedHour: "hours",
2605
+ schedDay: "days",
2606
+ schedCronHint: "minute hour day month weekday, e.g. 0 9 * * 1-5",
2607
+ schedNext: "Next {time}",
2608
+ schedNoNext: "Will not run again",
2609
+ schedPaused: "Paused",
2610
+ schedRunning: "Running",
2611
+ schedLast: "Last {time} \xB7 {status}",
2612
+ schedOk: "done",
2613
+ schedErr: "failed",
2614
+ schedStopped: "stopped",
2615
+ schedRunNow: "Run now",
2616
+ schedPause: "Pause",
2617
+ schedResume: "Resume",
2618
+ schedEdit: "Edit",
2619
+ schedOpen: "Open its conversation",
2620
+ schedDel: "Delete task",
2621
+ schedDelMsg: 'Delete "{name}"? Its conversation stays.',
2622
+ schedSave: "Save",
2623
+ schedBusy: "Another scheduled task is running; try again when it ends.",
2624
+ schedByAI: "by AI",
2625
+ schedRunHead: '\u23F0 Scheduled task "{name}" \xB7 {time}\n(Running unattended: the user may not be watching.)',
2626
+ schedStarted: 'Scheduled task "{name}" started',
2627
+ schedFailed: 'Scheduled task "{name}" failed: {error}',
2628
+ schedNamePh: "e.g. Morning news digest",
2629
+ schedPromptPh: "What the AI should do each time. Write it to stand alone: the run does not see this conversation.",
2630
+ schedDayNames: "Sun,Mon,Tue,Wed,Thu,Fri,Sat",
2631
+ tSchedList: "Scheduled tasks",
2632
+ tSchedAdd: 'Schedule "{name}"',
2633
+ tSchedUpdate: "Change scheduled task",
2634
+ tSchedRemove: "Remove scheduled task",
2635
+ 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
2636
  runCode: "Run code",
2106
2637
  ingRead: "Reading",
2107
2638
  ingList: "Listing",
@@ -2370,6 +2901,51 @@ var STRINGS = {
2370
2901
  webOn: "\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5F00\u542F",
2371
2902
  webOff: "\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5173\u95ED",
2372
2903
  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",
2904
+ permAlways: "\u4EE5\u540E\u90FD\u5141\u8BB8\uFF08\u672C\u5E94\u7528\uFF09",
2905
+ sched: "\u5B9A\u65F6\u4EFB\u52A1",
2906
+ schedNew: "\u65B0\u5EFA",
2907
+ 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",
2908
+ 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",
2909
+ schedName: "\u540D\u79F0",
2910
+ schedPrompt: "\u8981\u505A\u4EC0\u4E48",
2911
+ schedWhen: "\u65F6\u95F4",
2912
+ schedOnce: "\u4E00\u6B21",
2913
+ schedEvery: "\u6BCF\u9694",
2914
+ schedDaily: "\u6BCF\u5929 / \u6BCF\u5468",
2915
+ schedCron: "Cron",
2916
+ schedMin: "\u5206\u949F",
2917
+ schedHour: "\u5C0F\u65F6",
2918
+ schedDay: "\u5929",
2919
+ schedCronHint: "\u5206 \u65F6 \u65E5 \u6708 \u5468\uFF0C\u5982 0 9 * * 1-5",
2920
+ schedNext: "\u4E0B\u6B21 {time}",
2921
+ schedNoNext: "\u4E0D\u4F1A\u518D\u8FD0\u884C",
2922
+ schedPaused: "\u5DF2\u6682\u505C",
2923
+ schedRunning: "\u8FD0\u884C\u4E2D",
2924
+ schedLast: "\u4E0A\u6B21 {time} \xB7 {status}",
2925
+ schedOk: "\u5B8C\u6210",
2926
+ schedErr: "\u5931\u8D25",
2927
+ schedStopped: "\u5DF2\u505C\u6B62",
2928
+ schedRunNow: "\u7ACB\u5373\u8FD0\u884C",
2929
+ schedPause: "\u6682\u505C",
2930
+ schedResume: "\u6062\u590D",
2931
+ schedEdit: "\u7F16\u8F91",
2932
+ schedOpen: "\u6253\u5F00\u5B83\u7684\u5BF9\u8BDD",
2933
+ schedDel: "\u5220\u9664\u4EFB\u52A1",
2934
+ schedDelMsg: "\u5220\u9664\u300C{name}\u300D\uFF1F\u5B83\u7684\u5BF9\u8BDD\u4F1A\u4FDD\u7559\u3002",
2935
+ schedSave: "\u4FDD\u5B58",
2936
+ schedBusy: "\u53E6\u4E00\u4E2A\u5B9A\u65F6\u4EFB\u52A1\u6B63\u5728\u8FD0\u884C\uFF0C\u7ED3\u675F\u540E\u518D\u8BD5\u3002",
2937
+ schedByAI: "AI \u521B\u5EFA",
2938
+ 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",
2939
+ schedStarted: "\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D\u5F00\u59CB\u8FD0\u884C",
2940
+ schedFailed: "\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D\u5931\u8D25\uFF1A{error}",
2941
+ schedNamePh: "\u5982\uFF1A\u65E9\u95F4\u65B0\u95FB\u6458\u8981",
2942
+ 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",
2943
+ schedDayNames: "\u65E5,\u4E00,\u4E8C,\u4E09,\u56DB,\u4E94,\u516D",
2944
+ tSchedList: "\u67E5\u770B\u5B9A\u65F6\u4EFB\u52A1",
2945
+ tSchedAdd: "\u5B89\u6392\u5B9A\u65F6\u4EFB\u52A1\u300C{name}\u300D",
2946
+ tSchedUpdate: "\u4FEE\u6539\u5B9A\u65F6\u4EFB\u52A1",
2947
+ tSchedRemove: "\u5220\u9664\u5B9A\u65F6\u4EFB\u52A1",
2948
+ 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
2949
  runCode: "\u8FD0\u884C\u4EE3\u7801",
2374
2950
  ingRead: "\u6B63\u5728\u8BFB\u53D6",
2375
2951
  ingList: "\u6B63\u5728\u67E5\u770B",
@@ -2592,6 +3168,25 @@ var CSS = tokenCSS() + `
2592
3168
  .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
3169
  .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
3170
  .ra-skm.drop{outline:2px dashed var(--ra-accent);outline-offset:-4px}
3171
+ .ra-schm .ra-skb.on{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
3172
+ .ra-schm .ra-mi.ra-off .ra-mtt{color:var(--ra-fg-muted)}
3173
+ .ra-schm .ra-mi small.ra-bad{color:var(--ra-red)}
3174
+ .ra-schm .ra-mi small{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp:none}
3175
+ .ra-schf{display:flex;flex-direction:column;gap:10px;padding:6px 8px 6px}
3176
+ .ra-schf .ra-schh{font-size:13px;font-weight:600}
3177
+ .ra-schf .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
3178
+ .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}
3179
+ .ra-chat .ra-schf textarea{min-height:88px;resize:vertical;line-height:1.5}
3180
+ .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)}
3181
+ .ra-schf .ra-row{display:flex;gap:8px;align-items:center}
3182
+ .ra-schf .ra-row>*{flex:1;min-width:0}
3183
+ .ra-schf .ra-row.ra-col2{flex-direction:column;align-items:stretch}
3184
+ .ra-schf .ra-days{display:flex;gap:4px}
3185
+ .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)}
3186
+ .ra-chat .ra-schf .ra-days button.on{background:var(--ra-accent-subtle);border-color:transparent;color:var(--ra-accent-fg);font-weight:600}
3187
+ .ra-schf .ra-note{font-size:11.5px;color:var(--ra-fg-muted)}
3188
+ .ra-schf .ra-note.err{color:var(--ra-red)}
3189
+ .ra-schf .ra-btns{display:flex;justify-content:flex-end;gap:6px}
2595
3190
  .ra-set{padding:10px 12px;display:flex;flex-direction:column;gap:10px;width:min(360px,calc(100% - 24px))}
2596
3191
  /* The settings panel takes the chat's height under the header (a host may add fields of its own). */
2597
3192
  .ra-chat .ra-set{max-height:calc(100% - 72px)}
@@ -3389,8 +3984,9 @@ function renderChat(target, opts) {
3389
3984
  injectStyles();
3390
3985
  const lang = pickLocale(opts.locale);
3391
3986
  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;
3987
+ 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, ...agentOpts } = opts;
3393
3988
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
3989
+ setFileDialog(fileDialogOpt2);
3394
3990
  const provider = providerOpt ? (0, import_index2.toProvider)(providerOpt) : clientOpt ? (0, import_index2.toProvider)(clientOpt) : givenAgent?.provider ?? null;
3395
3991
  const project = provider?.name ?? agentOpts.appName ?? "app";
3396
3992
  const root = h("div", "ra-chat");
@@ -3448,6 +4044,10 @@ function renderChat(target, opts) {
3448
4044
  };
3449
4045
  };
3450
4046
  const setSkillCount = countBadge(skillsBtn, t.skills);
4047
+ const schedBtn = h("button", "ra-btn ghost");
4048
+ schedBtn.type = "button";
4049
+ schedBtn.innerHTML = I.clock() + `<span>${escapeHTML(t.sched)}</span>`;
4050
+ const setSchedCount = countBadge(schedBtn, t.sched);
3451
4051
  const histBtn = h("button", "ra-btn ghost");
3452
4052
  histBtn.type = "button";
3453
4053
  histBtn.innerHTML = I.hist() + `<span>${escapeHTML(t.history)}</span>`;
@@ -3471,12 +4071,12 @@ function renderChat(target, opts) {
3471
4071
  setBtn.innerHTML = I.gear();
3472
4072
  setBtn.title = t.settings;
3473
4073
  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]]) {
4074
+ 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
4075
  btn.setAttribute("aria-label", label);
3476
4076
  if (!btn.title) btn.title = label;
3477
4077
  }
3478
4078
  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 ?? []);
4079
+ head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, schedBtn, histBtn, newBtn, clearBtn, ...headerActions ?? [], setBtn, ...headerEnd ?? []);
3480
4080
  if (title === false) head.style.display = "none";
3481
4081
  const log = h("div", "ra-log");
3482
4082
  const inner = h("div", "ra-col");
@@ -3596,6 +4196,32 @@ ${t.webHint}`;
3596
4196
  drawWeb();
3597
4197
  for (const a of live.values()) applyWeb(a);
3598
4198
  });
4199
+ const PERM_KEY = `__runapps_agent_chat:${project}:perm`;
4200
+ const permOwn = !givenAgent && typeof agentOpts.permissions !== "function";
4201
+ const permShown = permOwn && permissionsSetting !== false;
4202
+ let permChoice = (() => {
4203
+ if (!permShown) return null;
4204
+ try {
4205
+ const v = localStorage.getItem(PERM_KEY);
4206
+ if (v === "ask" || v === "auto") return v;
4207
+ } catch {
4208
+ }
4209
+ return null;
4210
+ })();
4211
+ const permAuto = () => (permChoice ?? agentOpts.permissions ?? "ask") === "auto";
4212
+ const setPerm = (p, quiet = false) => {
4213
+ const was = permAuto();
4214
+ permChoice = p;
4215
+ if (permShown) {
4216
+ try {
4217
+ if (p) localStorage.setItem(PERM_KEY, p);
4218
+ else localStorage.removeItem(PERM_KEY);
4219
+ } catch {
4220
+ }
4221
+ }
4222
+ for (const a of live.values()) a.configure({ permissions: p ?? agentOpts.permissions ?? "ask" });
4223
+ if (!quiet && !was && permAuto()) ui.notify(t.permAutoNote);
4224
+ };
3599
4225
  left.append(attachBtn, webBtn, ...hostActions, hint);
3600
4226
  bar.append(left, acts);
3601
4227
  box.append(cmds, files, ta, bar, fileInput);
@@ -3644,6 +4270,7 @@ ${t.webHint}`;
3644
4270
  let cmdIndex = 0;
3645
4271
  let cmdFrame = null;
3646
4272
  let unsub = [];
4273
+ const unmountHooks = [];
3647
4274
  let menu = null;
3648
4275
  let mounted = true;
3649
4276
  const rootSize = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
@@ -3704,7 +4331,8 @@ ${t.webHint}`;
3704
4331
  w?.forEach((f) => f(shown));
3705
4332
  };
3706
4333
  const uiFor = (id) => ({
3707
- confirm: async (title2, message, o) => await whenCurrent(id, o?.signal) ? ui.confirm(title2, message, o) : false,
4334
+ // A permission question gets "Always allow (this app)", which turns auto-run on (a tool's own `always` keeps its place).
4335
+ 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
4336
  select: async (title2, options, o) => await whenCurrent(id, o?.signal) ? ui.select(title2, options, o) : null,
3709
4337
  input: async (title2, o) => await whenCurrent(id, o?.signal) ? ui.input(title2, o) : null,
3710
4338
  notify: (m, l) => ui.notify(m, l)
@@ -3712,7 +4340,7 @@ ${t.webHint}`;
3712
4340
  const restorable = (a) => !!a.workspace && typeof wsOpt === "function" && !a.workspace.root;
3713
4341
  const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || a.queued.length > 0 || waiting.has(a.id)));
3714
4342
  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 });
4343
+ const text = a.title ?? (0, import_index2.titleOf)({ v: 2, id: a.id, messages: a.messages, usage: a.usage, droppedTurns: 0, savedAt: 0 });
3716
4344
  return text === import_index2.UNTITLED ? t.untitled : text.length > 40 ? text.slice(0, 37) + "\u2026" : text;
3717
4345
  };
3718
4346
  const markBackground = () => histBtn.classList.toggle("ra-bg", background().length > 0);
@@ -4727,7 +5355,11 @@ ${t.webHint}`;
4727
5355
  return "Shown to the user.";
4728
5356
  }
4729
5357
  };
4730
- const chatTools = [...agentOpts.tools ?? [], ...nextPrompt ? [nextPromptTool] : []];
5358
+ const schedCfg = scheduleOpt ? scheduleOpt === true ? {} : scheduleOpt : null;
5359
+ const schedStore = schedCfg ? schedCfg.store ?? localSchedules(`__runapps_agent_chat:${project}:schedules`) : null;
5360
+ const schedLabels = { schedule_list: () => t.tSchedList, schedule_add: (a) => t.tSchedAdd.replace("{name}", a.name ?? ""), schedule_update: () => t.tSchedUpdate, schedule_remove: () => t.tSchedRemove };
5361
+ const schedTools = schedStore && schedCfg.tools !== false ? scheduleTools(schedStore, { ...schedCfg, onChange: () => refreshSched() }).map((x) => ({ ...x, display: { ...x.display, icon: I.clock(), label: schedLabels[x.name] } })) : [];
5362
+ const chatTools = [...agentOpts.tools ?? [], ...nextPrompt ? [nextPromptTool] : [], ...schedTools];
4731
5363
  const hiddenTools = new Set(chatTools.filter((x) => x.display?.hidden).map((x) => x.name));
4732
5364
  const syncSend = () => {
4733
5365
  const busy = root.dataset.busy === "1", any = !!(ta.value.trim() || pendingFiles.length || pendingContext.length);
@@ -4947,7 +5579,7 @@ ${ta.value}` : textOf(item.message);
4947
5579
  renderFiles();
4948
5580
  ta.focus();
4949
5581
  };
4950
- attachBtn.addEventListener("click", () => fileInput.click());
5582
+ attachBtn.addEventListener("click", () => chooseFiles(fileInput, (picked) => void addFiles(picked)));
4951
5583
  fileInput.addEventListener("change", () => {
4952
5584
  void addFiles(fileInput.files);
4953
5585
  fileInput.value = "";
@@ -5217,7 +5849,6 @@ ${c.text}` })));
5217
5849
  }
5218
5850
  };
5219
5851
  let userSettings = givenAgent ? {} : readSettings();
5220
- let permChoice = null;
5221
5852
  const hasSettings = opts.settings ?? !givenAgent;
5222
5853
  let settingsTab = 0;
5223
5854
  if (!hasSettings) setBtn.style.display = "none";
@@ -5462,7 +6093,7 @@ ${c.text}` })));
5462
6093
  }
5463
6094
  userSettings = {};
5464
6095
  writeSettings({});
5465
- permChoice = null;
6096
+ setPerm(null, true);
5466
6097
  for (const ag of live.values()) applyTo(ag, {}, null);
5467
6098
  closeMenu();
5468
6099
  ui.notify(t.applied);
@@ -5478,7 +6109,7 @@ ${c.text}` })));
5478
6109
  if (Number.isFinite(k) && k > 0) next.maxTokens = k;
5479
6110
  }
5480
6111
  if (effortSel.value && !effortSel.disabled) next.reasoningEffort = effortSel.value;
5481
- if (perm.value === "ask" || perm.value === "auto") permChoice = perm.value;
6112
+ if ((perm.value === "ask" || perm.value === "auto") && perm.value !== (permAuto() ? "auto" : "ask")) setPerm(perm.value);
5482
6113
  const summarize = sumSel.value === "summary";
5483
6114
  if (summarize !== hostCompaction.summarize) next.summarize = summarize;
5484
6115
  const at = atPick.read();
@@ -5591,7 +6222,7 @@ ${c.text}` })));
5591
6222
  document.addEventListener("click", onDocClick, true);
5592
6223
  function onDocClick(e) {
5593
6224
  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();
6225
+ 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
6226
  }
5596
6227
  const skillInput = h("input");
5597
6228
  skillInput.type = "file";
@@ -5647,7 +6278,7 @@ ${c.text}` })));
5647
6278
  const up = h("button", "ra-btn xs solid");
5648
6279
  up.type = "button";
5649
6280
  up.innerHTML = I.upload(13) + `<span>${escapeHTML(t.uploadZip)}</span>`;
5650
- up.addEventListener("click", () => skillInput.click());
6281
+ up.addEventListener("click", () => chooseFiles(skillInput, (picked) => void installZips(picked)));
5651
6282
  if (!ws.userSkillsDir) up.style.display = "none";
5652
6283
  head2.append(h("span", "", skills.length ? `${t.skills} \xB7 ${skills.length}` : t.skills), up);
5653
6284
  mine.append(head2);
@@ -5722,6 +6353,285 @@ ${c.text}` })));
5722
6353
  });
5723
6354
  };
5724
6355
  skillsBtn.addEventListener("click", () => void openSkills());
6356
+ if (!schedStore) schedBtn.style.display = "none";
6357
+ const schedLimits = { minMinutes: schedCfg?.minMinutes, maxTasks: schedCfg?.maxTasks };
6358
+ const dayNames = t.schedDayNames.split(",");
6359
+ const zhWords = /[\u4e00-\u9fff]/.test(t.sched);
6360
+ const fmtShort = (ms) => {
6361
+ const s = formatLocalTime(ms);
6362
+ return s.slice(0, 4) === String((/* @__PURE__ */ new Date()).getFullYear()) ? s.slice(5) : s;
6363
+ };
6364
+ const runScheduled = async (task) => {
6365
+ await ready;
6366
+ const text = `${t.schedRunHead.replace("{name}", task.name).replace("{time}", formatLocalTime(Date.now()))}
6367
+
6368
+ ${task.prompt}`;
6369
+ let a;
6370
+ if (givenAgent || oneChat) a = agent ?? givenAgent;
6371
+ else {
6372
+ const sid = task.session ?? `sched_${task.id}`;
6373
+ if (!task.session) {
6374
+ const cur = await schedStore.get(task.id);
6375
+ if (cur) await schedStore.put({ ...cur, session: sid });
6376
+ }
6377
+ a = agent?.id === sid ? agent : live.get(sid) ?? await makeAgent(sid);
6378
+ if (a !== agent) {
6379
+ await a.ready();
6380
+ live.set(sid, a);
6381
+ watchBackground(a);
6382
+ }
6383
+ }
6384
+ if (!givenAgent && !oneChat) a.setTitle(`\u23F0 ${task.name}`);
6385
+ ui.notify(t.schedStarted.replace("{name}", task.name));
6386
+ const r = a === agent ? await promptFromHost(text) : await a.prompt(text);
6387
+ refreshHistCount();
6388
+ if (r.reason === "error" || r.reason === "max_turns") ui.notify(t.schedFailed.replace("{name}", task.name).replace("{error}", r.error?.message ?? r.reason), "warning");
6389
+ 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 } : {} };
6390
+ };
6391
+ const schedIdle = () => mounted && !switching && !!agent && asked === 0 && waiting.size === 0 && ![...live.values()].some((a) => a.busy || a.queued.length > 0) && !(document.activeElement === ta && ta.value.trim());
6392
+ const scheduler = schedStore ? new Scheduler({ store: schedStore, run: runScheduled, idle: schedIdle, lockPrefix: `__runapps_agent_chat:${project}:schedules`, onChange: () => refreshSched() }) : null;
6393
+ if (scheduler) {
6394
+ const again = () => setTimeout(() => void scheduler.tick(), 1500);
6395
+ let lastBusy = false;
6396
+ const poll = setInterval(() => {
6397
+ const b = !schedIdle();
6398
+ if (lastBusy && !b) again();
6399
+ lastBusy = b;
6400
+ }, 3e3);
6401
+ unmountHooks.push(() => {
6402
+ clearInterval(poll);
6403
+ scheduler.stop();
6404
+ });
6405
+ }
6406
+ let schedView = "list";
6407
+ const refreshSched = () => {
6408
+ if (!schedStore) return;
6409
+ void schedStore.list().then((all) => {
6410
+ setSchedCount(all.filter((x) => x.enabled).length);
6411
+ if (menu?.classList.contains("ra-schm") && schedView === "list") drawSchedList(menu);
6412
+ }).catch(() => void 0);
6413
+ };
6414
+ const openSched = () => {
6415
+ if (menu) {
6416
+ const was = menu.classList.contains("ra-schm");
6417
+ closeMenu();
6418
+ if (was) return;
6419
+ }
6420
+ if (!schedStore) return;
6421
+ const mine = h("div", "ra-menu ra-skm ra-schm");
6422
+ menu = mine;
6423
+ placeMenu(mine);
6424
+ void drawSchedList(mine);
6425
+ };
6426
+ const drawSchedList = async (mine) => {
6427
+ schedView = "list";
6428
+ let all = [];
6429
+ try {
6430
+ all = await schedStore.list();
6431
+ } catch (err) {
6432
+ ui.notify(err.message, "error");
6433
+ }
6434
+ if (menu !== mine) return;
6435
+ all.sort((a, b) => a.enabled === b.enabled ? (a.next ?? Infinity) - (b.next ?? Infinity) : a.enabled ? -1 : 1);
6436
+ mine.replaceChildren();
6437
+ const head2 = h("div", "ra-skh");
6438
+ const add = h("button", "ra-btn xs solid");
6439
+ add.type = "button";
6440
+ add.innerHTML = I.plus(13) + `<span>${escapeHTML(t.schedNew)}</span>`;
6441
+ add.addEventListener("click", () => drawSchedForm(mine, null));
6442
+ head2.append(h("span", "", all.length ? `${t.sched} \xB7 ${all.length}` : t.sched), add);
6443
+ mine.append(head2);
6444
+ if (!all.length) mine.append(h("div", "ra-none", t.schedNone));
6445
+ const statusWord = { ok: t.schedOk, error: t.schedErr, stopped: t.schedStopped };
6446
+ for (const task of all) {
6447
+ const row = h("div", "ra-mi" + (task.enabled ? "" : " ra-off"));
6448
+ const b = h("button");
6449
+ b.type = "button";
6450
+ b.title = t.schedEdit;
6451
+ const name = h("span", "ra-mt");
6452
+ const running = scheduler?.running.has(task.id);
6453
+ if (running) name.append(h("span", "ra-spin"));
6454
+ name.append(h("span", "ra-mtt", task.name));
6455
+ if (running) name.append(h("span", "ra-skb on", t.schedRunning));
6456
+ else if (!task.enabled) name.append(h("span", "ra-skb", t.schedPaused));
6457
+ if (task.by === "agent") name.append(h("span", "ra-skb", t.schedByAI));
6458
+ 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}`;
6459
+ b.append(name, h("small", "", when));
6460
+ 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})` : ""))));
6461
+ b.addEventListener("click", () => drawSchedForm(mine, task));
6462
+ const act = (icon, title2, fn, cls = "ra-x ra-ia") => {
6463
+ const x = h("button", cls);
6464
+ x.type = "button";
6465
+ x.innerHTML = icon;
6466
+ x.title = title2;
6467
+ x.setAttribute("aria-label", title2);
6468
+ x.addEventListener("click", (e) => {
6469
+ e.stopPropagation();
6470
+ fn();
6471
+ });
6472
+ return x;
6473
+ };
6474
+ const runB = act(I.play(), t.schedRunNow, () => {
6475
+ void scheduler.runNow(task.id).then((ok) => {
6476
+ if (!ok) ui.notify(t.schedBusy, "warning");
6477
+ });
6478
+ setTimeout(refreshSched, 100);
6479
+ });
6480
+ const pauseB = act(task.enabled ? I.pause() : I.clock(13), task.enabled ? t.schedPause : t.schedResume, async () => {
6481
+ try {
6482
+ const cur = await schedStore.get(task.id);
6483
+ if (cur) await schedStore.put(changeTask(cur, { enabled: !cur.enabled }, schedLimits));
6484
+ } catch (err) {
6485
+ ui.notify(err.message, "error");
6486
+ }
6487
+ refreshSched();
6488
+ });
6489
+ const openB = act(I.message(), t.schedOpen, () => {
6490
+ closeMenu();
6491
+ if (task.session) void resume(task.session).catch((err) => ui.notify(err.message, "error"));
6492
+ });
6493
+ if (!task.session || givenAgent || oneChat) openB.style.display = "none";
6494
+ const del = act(I.trash(), t.schedDel, async () => {
6495
+ closeMenu();
6496
+ if (!await modalConfirm(root, t.schedDel, t.schedDelMsg.replace("{name}", task.name), { danger: true, ok: t.delete, cancel: t.cancel })) return;
6497
+ try {
6498
+ await schedStore.delete(task.id);
6499
+ } catch (err) {
6500
+ ui.notify(err.message, "error");
6501
+ }
6502
+ refreshSched();
6503
+ }, "ra-x");
6504
+ row.append(b, runB, pauseB, openB, del);
6505
+ mine.append(row);
6506
+ }
6507
+ mine.append(h("div", "ra-skf", t.schedHint));
6508
+ };
6509
+ const drawSchedForm = (mine, task) => {
6510
+ schedView = "form";
6511
+ for (const b of menuSelects.splice(0)) b.close();
6512
+ mine.replaceChildren();
6513
+ const form = h("div", "ra-schf");
6514
+ const field = (label, ...els) => {
6515
+ const l = h("div", "ra-fld");
6516
+ l.append(h("span", "", label), ...els);
6517
+ return l;
6518
+ };
6519
+ const nameIn = h("input");
6520
+ nameIn.type = "text";
6521
+ nameIn.placeholder = t.schedNamePh;
6522
+ nameIn.value = task?.name ?? "";
6523
+ const promptIn = h("textarea");
6524
+ promptIn.placeholder = t.schedPromptPh;
6525
+ promptIn.value = task?.prompt ?? "";
6526
+ const s0 = task?.schedule ?? { type: "daily", time: "09:00" };
6527
+ 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 });
6528
+ menuSelects.push(typeSel);
6529
+ const atIn = h("input");
6530
+ atIn.type = "datetime-local";
6531
+ const at0 = s0.type === "once" ? parseLocalTime(s0.at) : Date.now() + 36e5;
6532
+ atIn.value = formatLocalTime(Number.isFinite(at0) ? at0 : Date.now() + 36e5).replace(" ", "T");
6533
+ const everyN = h("input");
6534
+ everyN.type = "number";
6535
+ everyN.min = "1";
6536
+ everyN.step = "1";
6537
+ const m0 = s0.type === "every" ? s0.minutes : 60;
6538
+ const unit0 = m0 % 1440 === 0 ? "1440" : m0 % 60 === 0 ? "60" : "1";
6539
+ everyN.value = String(m0 / Number(unit0));
6540
+ const unitSel = selectBox(root, { options: [{ value: "1", label: t.schedMin }, { value: "60", label: t.schedHour }, { value: "1440", label: t.schedDay }], value: unit0 });
6541
+ menuSelects.push(unitSel);
6542
+ const everyRow = h("div", "ra-row");
6543
+ everyRow.append(everyN, unitSel.el);
6544
+ const timeIn = h("input");
6545
+ timeIn.type = "time";
6546
+ timeIn.value = s0.type === "daily" ? s0.time : "09:00";
6547
+ const days = new Set(s0.type === "daily" && s0.days?.length ? s0.days : [0, 1, 2, 3, 4, 5, 6]);
6548
+ const dayRow = h("div", "ra-days");
6549
+ for (const d of [1, 2, 3, 4, 5, 6, 0]) {
6550
+ const db = h("button", days.has(d) ? "on" : "", dayNames[d]);
6551
+ db.type = "button";
6552
+ db.addEventListener("click", () => {
6553
+ if (days.has(d)) {
6554
+ if (days.size > 1) days.delete(d);
6555
+ } else days.add(d);
6556
+ db.classList.toggle("on", days.has(d));
6557
+ preview();
6558
+ });
6559
+ dayRow.append(db);
6560
+ }
6561
+ const dailyBox = h("div", "ra-row ra-col2");
6562
+ dailyBox.append(timeIn, dayRow);
6563
+ const cronIn = h("input");
6564
+ cronIn.type = "text";
6565
+ cronIn.placeholder = "0 9 * * 1-5";
6566
+ cronIn.value = s0.type === "cron" ? s0.cron : "";
6567
+ const cronBox = h("div", "ra-fld");
6568
+ cronBox.append(cronIn, h("span", "ra-note", t.schedCronHint));
6569
+ const whenBox = h("div", "ra-fld");
6570
+ const note = h("div", "ra-note");
6571
+ const build = () => {
6572
+ switch (typeSel.value) {
6573
+ case "once":
6574
+ return { type: "once", at: atIn.value.replace("T", " ") };
6575
+ case "every":
6576
+ return { type: "every", minutes: Math.round(Number(everyN.value) * Number(unitSel.value)) };
6577
+ case "cron":
6578
+ return { type: "cron", cron: cronIn.value.trim() };
6579
+ default:
6580
+ return { type: "daily", time: timeIn.value, ...days.size < 7 ? { days: [...days].sort((a, b) => a - b) } : {} };
6581
+ }
6582
+ };
6583
+ const preview = () => {
6584
+ const sc = build();
6585
+ const problem = checkSchedule(sc, schedLimits.minMinutes ?? 5);
6586
+ const nx = problem ? null : nextRun(sc, Date.now());
6587
+ note.textContent = problem ?? (nx ? t.schedNext.replace("{time}", formatLocalTime(nx)) : t.schedNoNext);
6588
+ note.classList.toggle("err", !!problem || !nx);
6589
+ save.disabled = !!problem || !nx || !nameIn.value.trim() || !promptIn.value.trim();
6590
+ };
6591
+ const showType = () => {
6592
+ const v = typeSel.value;
6593
+ whenBox.replaceChildren(typeSel.el, ...v === "once" ? [atIn] : v === "every" ? [everyRow] : v === "cron" ? [cronBox] : [dailyBox]);
6594
+ preview();
6595
+ };
6596
+ typeSel.el.addEventListener("change", showType);
6597
+ unitSel.el.addEventListener("change", preview);
6598
+ for (const el of [nameIn, promptIn, atIn, everyN, timeIn, cronIn]) el.addEventListener("input", preview);
6599
+ const btns = h("div", "ra-btns");
6600
+ const cancel = h("button", "ra-btn xs ghost", t.cancel);
6601
+ cancel.type = "button";
6602
+ const save = h("button", "ra-btn xs solid", t.schedSave);
6603
+ save.type = "button";
6604
+ cancel.addEventListener("click", () => {
6605
+ for (const b of menuSelects.splice(0)) b.close();
6606
+ void drawSchedList(mine);
6607
+ });
6608
+ save.addEventListener("click", async () => {
6609
+ try {
6610
+ const fields = { name: nameIn.value, prompt: promptIn.value, schedule: build() };
6611
+ if (task) {
6612
+ const cur = await schedStore.get(task.id);
6613
+ if (!cur) throw new Error("gone");
6614
+ await schedStore.put(changeTask(cur, { ...fields, enabled: true }, schedLimits));
6615
+ } else {
6616
+ if ((await schedStore.list()).length >= (schedLimits.maxTasks ?? 20)) throw new Error(`${schedLimits.maxTasks ?? 20} tasks at most`);
6617
+ await schedStore.put(makeTask({ ...fields, by: "user" }, schedLimits));
6618
+ }
6619
+ for (const b of menuSelects.splice(0)) b.close();
6620
+ await drawSchedList(mine);
6621
+ refreshSched();
6622
+ } catch (err) {
6623
+ note.textContent = err.message;
6624
+ note.classList.add("err");
6625
+ }
6626
+ });
6627
+ btns.append(cancel, save);
6628
+ 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);
6629
+ mine.append(form);
6630
+ showType();
6631
+ queueMicrotask(() => (task ? promptIn : nameIn).focus());
6632
+ };
6633
+ schedBtn.addEventListener("click", () => openSched());
6634
+ refreshSched();
5725
6635
  const fail = (err) => ui.notify(err.message, "error");
5726
6636
  let compacting = false;
5727
6637
  const transcriptMarkdown = (a) => {
@@ -6429,6 +7339,9 @@ ${c.text}` })));
6429
7339
  const firstId = agentOpts.id ?? (typeof resumeOpt === "string" ? resumeOpt : resumeOpt === false ? void 0 : readLast(project) ?? void 0);
6430
7340
  const starting = givenAgent ? Promise.resolve(givenAgent) : makeAgent(firstId);
6431
7341
  const ready = starting.then((a) => attach(a));
7342
+ if (scheduler) void ready.then(() => {
7343
+ if (mounted) scheduler.start();
7344
+ }).catch(() => void 0);
6432
7345
  ready.catch((err) => {
6433
7346
  addError(`${err.message}`);
6434
7347
  setBusy(false);
@@ -6489,6 +7402,12 @@ ${c.text}` })));
6489
7402
  mounted = false;
6490
7403
  if (histTimer) clearTimeout(histTimer);
6491
7404
  for (const u of unsub) u();
7405
+ for (const u of unmountHooks.splice(0)) {
7406
+ try {
7407
+ u();
7408
+ } catch {
7409
+ }
7410
+ }
6492
7411
  ui.cancelAll(true);
6493
7412
  closeMenu();
6494
7413
  document.removeEventListener("click", onDocClick, true);