@eum-agent/automation-schedule 0.0.0-stage → 1.0.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.
Files changed (4) hide show
  1. package/dist/index.js +730 -0
  2. package/package.json +49 -3
  3. package/ui/ui.js +2654 -0
  4. package/README.md +0 -3
package/ui/ui.js ADDED
@@ -0,0 +1,2654 @@
1
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ /** Browser translations keyed by the product's supported language-region IDs. */
4
+ var CATALOGUES$1 = {
5
+ "zh-CN": {
6
+ locale: "zh-CN",
7
+ nav: "计划",
8
+ heading: "计划任务",
9
+ creation: "智能体创建",
10
+ agentLimit: "创建上限",
11
+ agentLimitHelp: "每个智能体在单个工作空间内可创建的计划任务数量上限。设为 0 表示不限制。手动创建的任务不计入此上限,降低上限不会删除已有任务。",
12
+ invalidLimit: "须为 0 到 1000 之间的整数。",
13
+ retry: "重试",
14
+ increase: "增加",
15
+ decrease: "减少",
16
+ add: "添加",
17
+ remove: "移除",
18
+ close: "关闭",
19
+ untitled: "未命名会话",
20
+ noWorkspace: "先选择或创建一个工作空间。",
21
+ loadFailed: "计划任务读取失败。",
22
+ offline: "未连接到网关服务",
23
+ authenticationRequired: "认证不可用,请重新打开页面",
24
+ create: "新建计划任务",
25
+ createTitle: "新建计划任务",
26
+ editTitle: "编辑计划任务",
27
+ edit: "编辑",
28
+ delete: "删除",
29
+ confirmDelete: "确认删除",
30
+ pause: "暂停",
31
+ resume: "恢复",
32
+ save: "保存",
33
+ createAction: "创建",
34
+ cancel: "取消",
35
+ loading: "加载中…",
36
+ saving: "保存中…",
37
+ empty: "暂无计划任务",
38
+ emptyHint: "让智能体按时间自动执行工作,例如每天早上汇总变更。",
39
+ list: "计划任务列表",
40
+ backToList: "返回计划任务列表",
41
+ overview: "概览",
42
+ nextRun: "下次执行",
43
+ lastRun: "最近一次",
44
+ runs: "运行记录",
45
+ creator: "创建者",
46
+ on: "开启",
47
+ off: "关闭",
48
+ scopeNone: "无",
49
+ noRuns: "暂无运行记录",
50
+ openSession: "打开会话",
51
+ paused: "已暂停",
52
+ sectionBasics: "基本信息",
53
+ sectionTiming: "执行计划",
54
+ required: "此项为必填项。",
55
+ scopeUnavailable: "使用已有会话时,任务在该会话里执行并沿用它已有的授权,不设预授权。",
56
+ sectionScope: "预授权",
57
+ name: "任务名称",
58
+ namePlaceholder: "例如:每日构建检查",
59
+ agent: "执行智能体",
60
+ mode: "执行方式",
61
+ modeOnce: "单次",
62
+ modeRepeat: "重复",
63
+ modeCron: "Cron",
64
+ runAt: "执行时间",
65
+ frequency: "重复频率",
66
+ frequencyInterval: "按间隔",
67
+ frequencyDaily: "每天",
68
+ frequencyWeekly: "每周",
69
+ frequencyMonthly: "每月",
70
+ interval: "间隔",
71
+ every: "每",
72
+ unit: "单位",
73
+ unitMinute: "分钟",
74
+ unitHour: "小时",
75
+ weekdays: "星期",
76
+ listSeparator: "、",
77
+ monthDay: "日期",
78
+ monthDaySuffix: "日",
79
+ monthDayHelp: "当月没有该日期时不执行。",
80
+ timeOfDay: "时间",
81
+ expression: "表达式",
82
+ expressionHelp: "五段式:分 时 日 月 周。例如 0 9 * * 1-5 表示工作日 9:00。",
83
+ timezone: "时区",
84
+ timezoneEmpty: "没有匹配的时区",
85
+ upcoming: "近期执行",
86
+ inTimezone: "时区:{{zone}}",
87
+ "invalid.amount": "请输入有效的间隔。",
88
+ "invalid.tooOften": "间隔不能少于 5 分钟。",
89
+ "invalid.weekdays": "请至少选择一天。",
90
+ "invalid.monthDay": "请输入 1 到 31 之间的日期。",
91
+ "invalid.expression": "请输入 Cron 表达式。",
92
+ "invalid.past": "执行时间已过,请选择之后的时间。",
93
+ "invalid.neverRuns": "这个表达式永远不会执行。",
94
+ "invalid.timezone": "无法识别这个时区。",
95
+ "invalid.syntax": "Cron 表达式格式不正确。",
96
+ catchUp: "错过执行",
97
+ catchUpRun: "恢复后补执行一次",
98
+ catchUpSkip: "跳过",
99
+ catchUpHelp: "网关停止或设备休眠期间错过的执行,恢复后补执行一次。",
100
+ instruction: "执行指令",
101
+ instructionPlaceholder: "描述每次执行时智能体要完成的工作",
102
+ target: "运行会话",
103
+ targetNew: "每次新建会话",
104
+ targetSession: "使用已有会话",
105
+ session: "会话",
106
+ sessionPlaceholder: "选择会话",
107
+ scopeHelp: "任务执行时可直接使用以下权限,无需等待审批。仅对每次新建的会话生效。",
108
+ scopePaths: "路径",
109
+ scopePathAdd: "添加路径",
110
+ scopePathsEmpty: "未添加路径。",
111
+ scopePathTitle: "添加预授权路径",
112
+ scopeAccess: "访问权限",
113
+ scopeRead: "只读",
114
+ scopeWrite: "读写",
115
+ scopeReadWarning: "允许任务免审批读取此路径及其子路径。",
116
+ scopeWriteWarning: "允许任务免审批读取和修改此路径及其子路径。",
117
+ scopeNetwork: "命令联网",
118
+ scopeNetworkPolicy: "遵循审批策略",
119
+ scopeNetworkAuthorized: "预先授权",
120
+ scopeNetworkHelp: "预先授权后,任务执行的命令无需审批即可访问任意外部地址。",
121
+ scopeHosts: "网站",
122
+ scopeHost: "主机名",
123
+ scopeHostAdd: "添加网站",
124
+ scopeHostsEmpty: "未添加网站。",
125
+ scopeHostTitle: "添加预授权网站",
126
+ scopeHostHelp: "只填主机名,不含协议和路径。",
127
+ ruleNone: "未设置执行计划",
128
+ ruleOnce: "{{at}} 执行一次",
129
+ ruleEveryMinutes: "每 {{amount}} 分钟",
130
+ ruleEveryHours: "每 {{amount}} 小时",
131
+ ruleDaily: "每天 {{time}}",
132
+ ruleWeekly: "每{{days}} {{time}}",
133
+ ruleMonthly: "每月 {{day}} 日 {{time}}",
134
+ ruleCron: "Cron {{expression}}({{timezone}})",
135
+ next: "下次执行 {{at}}",
136
+ noNext: "不再执行",
137
+ byYou: "由你创建",
138
+ byAgent: "由 {{name}} 创建",
139
+ "runKind.scheduled": "按计划",
140
+ "runKind.catch-up": "补执行",
141
+ "runKind.fired": "外部触发",
142
+ "state.running": "运行中",
143
+ "state.waiting": "等待处理",
144
+ "state.completed": "已完成",
145
+ "state.failed": "失败",
146
+ "state.skipped": "已跳过",
147
+ "reason.previous-running": "上次执行尚未结束",
148
+ "reason.target-busy": "目标会话繁忙",
149
+ "reason.missed": "已错过",
150
+ "reason.agent-removed": "智能体已删除",
151
+ "reason.workspace-removed": "工作空间已删除",
152
+ "reason.session-missing": "目标会话不存在",
153
+ "reason.no-model": "没有可用模型",
154
+ "reason.turn-failed": "执行失败",
155
+ "reason.turn-interrupted": "执行中断",
156
+ "reason.gateway-stopped": "网关已停止",
157
+ "problem.agent-removed": "异常:智能体已删除",
158
+ "problem.workspace-removed": "异常:工作空间已删除",
159
+ "problem.session-missing": "异常:目标会话不存在",
160
+ "problem.no-model": "异常:没有可用模型",
161
+ "problem.source-unavailable": "异常:触发源不可用"
162
+ },
163
+ "en-US": {
164
+ locale: "en-US",
165
+ nav: "Schedules",
166
+ heading: "Scheduled tasks",
167
+ creation: "Agent-created tasks",
168
+ agentLimit: "Limit",
169
+ agentLimitHelp: "Maximum number of scheduled tasks each agent can create per workspace. Set to 0 for no limit. Manually created tasks do not count toward this limit. Lowering the limit does not delete existing tasks.",
170
+ invalidLimit: "Must be a whole number from 0 to 1000.",
171
+ retry: "Retry",
172
+ increase: "Increase",
173
+ decrease: "Decrease",
174
+ add: "Add",
175
+ remove: "Remove",
176
+ close: "Close",
177
+ untitled: "Untitled session",
178
+ noWorkspace: "Choose or create a workspace first.",
179
+ loadFailed: "The scheduled tasks could not be read.",
180
+ offline: "Not connected to the gateway",
181
+ authenticationRequired: "Authentication is unavailable; reopen the page",
182
+ create: "New scheduled task",
183
+ createTitle: "New scheduled task",
184
+ editTitle: "Edit scheduled task",
185
+ edit: "Edit",
186
+ delete: "Delete",
187
+ confirmDelete: "Confirm delete",
188
+ pause: "Pause",
189
+ resume: "Resume",
190
+ save: "Save",
191
+ createAction: "Create",
192
+ cancel: "Cancel",
193
+ loading: "Loading…",
194
+ saving: "Saving…",
195
+ empty: "No scheduled tasks",
196
+ emptyHint: "Have an agent do work on a schedule, such as summarizing changes every morning.",
197
+ list: "Scheduled tasks",
198
+ backToList: "Back to scheduled tasks",
199
+ overview: "Overview",
200
+ nextRun: "Next run",
201
+ lastRun: "Last run",
202
+ runs: "Run history",
203
+ creator: "Created by",
204
+ on: "On",
205
+ off: "Off",
206
+ scopeNone: "None",
207
+ noRuns: "No runs yet",
208
+ openSession: "Open session",
209
+ paused: "Paused",
210
+ sectionBasics: "Basics",
211
+ sectionTiming: "Schedule",
212
+ required: "This field is required.",
213
+ scopeUnavailable: "Runs delivered into an existing session use the permissions that session already holds; no pre-authorization applies.",
214
+ sectionScope: "Pre-authorization",
215
+ name: "Task name",
216
+ namePlaceholder: "e.g. Daily build check",
217
+ agent: "Agent",
218
+ mode: "Runs",
219
+ modeOnce: "Once",
220
+ modeRepeat: "Repeating",
221
+ modeCron: "Cron",
222
+ runAt: "Date and time",
223
+ frequency: "Frequency",
224
+ frequencyInterval: "At an interval",
225
+ frequencyDaily: "Daily",
226
+ frequencyWeekly: "Weekly",
227
+ frequencyMonthly: "Monthly",
228
+ interval: "Interval",
229
+ every: "Every",
230
+ unit: "Unit",
231
+ unitMinute: "minutes",
232
+ unitHour: "hours",
233
+ weekdays: "Days",
234
+ listSeparator: ", ",
235
+ monthDay: "Day",
236
+ monthDaySuffix: "of the month",
237
+ monthDayHelp: "Months without this day are skipped.",
238
+ timeOfDay: "Time",
239
+ expression: "Expression",
240
+ expressionHelp: "Five fields: minute hour day month weekday. 0 9 * * 1-5 is weekdays at 9:00.",
241
+ timezone: "Time zone",
242
+ timezoneEmpty: "No matching time zone",
243
+ upcoming: "Upcoming",
244
+ inTimezone: "Time zone: {{zone}}",
245
+ "invalid.amount": "Enter a valid interval.",
246
+ "invalid.tooOften": "The interval must be at least 5 minutes.",
247
+ "invalid.weekdays": "Choose at least one day.",
248
+ "invalid.monthDay": "Enter a day from 1 to 31.",
249
+ "invalid.expression": "Enter a cron expression.",
250
+ "invalid.past": "That time has passed; choose a later one.",
251
+ "invalid.neverRuns": "This expression never runs.",
252
+ "invalid.timezone": "This time zone is not recognized.",
253
+ "invalid.syntax": "The cron expression is not valid.",
254
+ catchUp: "Missed runs",
255
+ catchUpRun: "Run once on resume",
256
+ catchUpSkip: "Skip",
257
+ catchUpHelp: "A run missed while the gateway was stopped or the device asleep runs once on resume.",
258
+ instruction: "Instruction",
259
+ instructionPlaceholder: "Describe what the agent should do on each run",
260
+ target: "Session",
261
+ targetNew: "New session each run",
262
+ targetSession: "Existing session",
263
+ session: "Target session",
264
+ sessionPlaceholder: "Choose a session",
265
+ scopeHelp: "Runs use these permissions without waiting for approval. Applies to runs that open a new session.",
266
+ scopePaths: "Paths",
267
+ scopePathAdd: "Add path",
268
+ scopePathsEmpty: "No paths added.",
269
+ scopePathTitle: "Add pre-authorized path",
270
+ scopeAccess: "Access",
271
+ scopeRead: "Read",
272
+ scopeWrite: "Read & write",
273
+ scopeReadWarning: "Runs may read this path and everything under it without asking.",
274
+ scopeWriteWarning: "Runs may read and change this path and everything under it without asking.",
275
+ scopeNetwork: "Command network",
276
+ scopeNetworkPolicy: "Follow approval policy",
277
+ scopeNetworkAuthorized: "Pre-authorize",
278
+ scopeNetworkHelp: "Pre-authorized commands may reach any outside address without approval.",
279
+ scopeHosts: "Websites",
280
+ scopeHost: "Host",
281
+ scopeHostAdd: "Add website",
282
+ scopeHostsEmpty: "No websites added.",
283
+ scopeHostTitle: "Add pre-authorized website",
284
+ scopeHostHelp: "A host name alone, without scheme or path.",
285
+ ruleNone: "No schedule",
286
+ ruleOnce: "Once at {{at}}",
287
+ ruleEveryMinutes: "Every {{amount}} min",
288
+ ruleEveryHours: "Every {{amount}} h",
289
+ ruleDaily: "Daily at {{time}}",
290
+ ruleWeekly: "Every {{days}} at {{time}}",
291
+ ruleMonthly: "Monthly on day {{day}} at {{time}}",
292
+ ruleCron: "Cron {{expression}} ({{timezone}})",
293
+ next: "Next run {{at}}",
294
+ noNext: "No further runs",
295
+ byYou: "Created by you",
296
+ byAgent: "Created by {{name}}",
297
+ "runKind.scheduled": "Scheduled",
298
+ "runKind.catch-up": "Catch-up",
299
+ "runKind.fired": "Triggered",
300
+ "state.running": "Running",
301
+ "state.waiting": "Needs attention",
302
+ "state.completed": "Completed",
303
+ "state.failed": "Failed",
304
+ "state.skipped": "Skipped",
305
+ "reason.previous-running": "previous run still in progress",
306
+ "reason.target-busy": "target session busy",
307
+ "reason.missed": "missed",
308
+ "reason.agent-removed": "agent deleted",
309
+ "reason.workspace-removed": "workspace deleted",
310
+ "reason.session-missing": "target session not found",
311
+ "reason.no-model": "no model available",
312
+ "reason.turn-failed": "run failed",
313
+ "reason.turn-interrupted": "run interrupted",
314
+ "reason.gateway-stopped": "gateway stopped",
315
+ "problem.agent-removed": "Error: agent deleted",
316
+ "problem.workspace-removed": "Error: workspace deleted",
317
+ "problem.session-missing": "Error: target session not found",
318
+ "problem.no-model": "Error: no model available",
319
+ "problem.source-unavailable": "Error: trigger source unavailable"
320
+ }
321
+ };
322
+ /** `{{name}}` placeholders filled from `values`. */
323
+ function fill(text, values) {
324
+ return text.replace(/\{\{(\w+)\}\}/g, (whole, key) => key in values ? String(values[key]) : whole);
325
+ }
326
+ function localTimezone() {
327
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
328
+ }
329
+ function dateOf(at) {
330
+ const date = new Date(at);
331
+ return {
332
+ year: date.getFullYear(),
333
+ month: date.getMonth() + 1,
334
+ day: date.getDate()
335
+ };
336
+ }
337
+ function timeOf(at) {
338
+ const date = new Date(at);
339
+ return {
340
+ hour: date.getHours(),
341
+ minute: date.getMinutes()
342
+ };
343
+ }
344
+ /** The local instant a date and time name. */
345
+ function instantOf(date, time) {
346
+ return new Date(date.year, date.month - 1, date.day, time.hour, time.minute).getTime();
347
+ }
348
+ /** Where a new task starts: once, an hour from now on the hour, and every
349
+ * repeating field filled with something a person would plausibly want. */
350
+ function defaultCadence(now) {
351
+ const soon = new Date(now + 36e5);
352
+ soon.setMinutes(0, 0, 0);
353
+ return {
354
+ mode: "once",
355
+ date: dateOf(soon.getTime()),
356
+ time: timeOf(soon.getTime()),
357
+ frequency: "daily",
358
+ amount: 1,
359
+ unit: "hour",
360
+ weekdays: [
361
+ 1,
362
+ 2,
363
+ 3,
364
+ 4,
365
+ 5
366
+ ],
367
+ monthDay: 1,
368
+ expression: "0 9 * * 1-5",
369
+ timezone: localTimezone()
370
+ };
371
+ }
372
+ var NUMBER = "(\\d{1,2})";
373
+ var DAILY = new RegExp(`^${NUMBER} ${NUMBER} \\* \\* \\*$`);
374
+ var DAYS = "[0-6](?:-[0-6])?";
375
+ var WEEKLY = new RegExp(`^${NUMBER} ${NUMBER} \\* \\* (${DAYS}(?:,${DAYS})*)$`);
376
+ var MONTHLY = new RegExp(`^${NUMBER} ${NUMBER} ${NUMBER} \\* \\*$`);
377
+ function clock(minute, hour) {
378
+ const m = Number(minute);
379
+ const h = Number(hour);
380
+ return m <= 59 && h <= 23 ? {
381
+ hour: h,
382
+ minute: m
383
+ } : null;
384
+ }
385
+ /** The frequency a cron expression was written from, when it is one. */
386
+ function frequencyOf(expression) {
387
+ const daily = DAILY.exec(expression);
388
+ if (daily !== null) {
389
+ const time = clock(daily[1], daily[2]);
390
+ return time && {
391
+ frequency: "daily",
392
+ time,
393
+ weekdays: [
394
+ 1,
395
+ 2,
396
+ 3,
397
+ 4,
398
+ 5
399
+ ],
400
+ monthDay: 1
401
+ };
402
+ }
403
+ const weekly = WEEKLY.exec(expression);
404
+ if (weekly !== null) {
405
+ const time = clock(weekly[1], weekly[2]);
406
+ const days = /* @__PURE__ */ new Set();
407
+ for (const part of weekly[3].split(",")) {
408
+ const [from, to = from] = part.split("-").map(Number);
409
+ if (to < from) return null;
410
+ for (let day = from; day <= to; day++) days.add(day);
411
+ }
412
+ const weekdays = [...days].sort();
413
+ return time && {
414
+ frequency: "weekly",
415
+ time,
416
+ weekdays,
417
+ monthDay: 1
418
+ };
419
+ }
420
+ const monthly = MONTHLY.exec(expression);
421
+ if (monthly !== null) {
422
+ const time = clock(monthly[1], monthly[2]);
423
+ const day = Number(monthly[3]);
424
+ if (day < 1 || day > 31) return null;
425
+ return time && {
426
+ frequency: "monthly",
427
+ time,
428
+ weekdays: [
429
+ 1,
430
+ 2,
431
+ 3,
432
+ 4,
433
+ 5
434
+ ],
435
+ monthDay: day
436
+ };
437
+ }
438
+ return null;
439
+ }
440
+ function cadenceOf(rule, now) {
441
+ const base = defaultCadence(now);
442
+ if (rule === null) return base;
443
+ switch (rule.kind) {
444
+ case "once": return {
445
+ ...base,
446
+ mode: "once",
447
+ date: dateOf(rule.at),
448
+ time: timeOf(rule.at)
449
+ };
450
+ case "interval": {
451
+ const hours = rule.everyMinutes % 60 === 0;
452
+ return {
453
+ ...base,
454
+ mode: "repeat",
455
+ frequency: "interval",
456
+ amount: hours ? rule.everyMinutes / 60 : rule.everyMinutes,
457
+ unit: hours ? "hour" : "minute"
458
+ };
459
+ }
460
+ case "cron": {
461
+ const written = {
462
+ ...base,
463
+ expression: rule.expression,
464
+ timezone: rule.timezone
465
+ };
466
+ const frequency = rule.timezone === localTimezone() ? frequencyOf(rule.expression) : null;
467
+ return frequency === null ? {
468
+ ...written,
469
+ mode: "cron"
470
+ } : {
471
+ ...written,
472
+ mode: "repeat",
473
+ ...frequency
474
+ };
475
+ }
476
+ }
477
+ }
478
+ /** What is wrong with a cadence before the gateway is asked, as a catalogue
479
+ * key under `invalid.`; null when there is nothing. */
480
+ function problemOf(cadence, now = Date.now()) {
481
+ switch (cadence.mode) {
482
+ case "once": return instantOf(cadence.date, cadence.time) <= now ? "past" : null;
483
+ case "repeat":
484
+ switch (cadence.frequency) {
485
+ case "interval": {
486
+ const minutes = intervalMinutes(cadence);
487
+ if (minutes === null) return "amount";
488
+ return minutes < 5 ? "tooOften" : null;
489
+ }
490
+ case "weekly": return cadence.weekdays.length === 0 ? "weekdays" : null;
491
+ case "monthly": return cadence.monthDay === null ? "monthDay" : null;
492
+ case "daily": return null;
493
+ }
494
+ break;
495
+ case "cron": return cadence.expression.trim() === "" ? "expression" : null;
496
+ }
497
+ return null;
498
+ }
499
+ function intervalMinutes(cadence) {
500
+ if (cadence.amount === null || !Number.isInteger(cadence.amount) || cadence.amount < 1) return null;
501
+ return cadence.unit === "hour" ? cadence.amount * 60 : cadence.amount;
502
+ }
503
+ /** Collapses consecutive days into ranges, the way cron is usually written
504
+ * by hand: Monday to Friday reads `1-5`. */
505
+ function weekdayField(days) {
506
+ const sorted = [...new Set(days)].sort();
507
+ const parts = [];
508
+ let start = sorted[0];
509
+ let previous = start;
510
+ for (const day of [...sorted.slice(1), NaN]) {
511
+ if (day === previous + 1) {
512
+ previous = day;
513
+ continue;
514
+ }
515
+ parts.push(previous - start >= 2 ? `${start}-${previous}` : previous === start ? `${start}` : `${start},${previous}`);
516
+ start = day;
517
+ previous = day;
518
+ }
519
+ return parts.join(",");
520
+ }
521
+ /** The rule a valid cadence stands for; null while `problemOf` names one. */
522
+ function ruleOf(cadence, anchor, now = Date.now()) {
523
+ if (problemOf(cadence, now) !== null) return null;
524
+ const { hour, minute } = cadence.time;
525
+ const timezone = localTimezone();
526
+ switch (cadence.mode) {
527
+ case "once": return {
528
+ kind: "once",
529
+ at: instantOf(cadence.date, cadence.time)
530
+ };
531
+ case "cron": return {
532
+ kind: "cron",
533
+ expression: cadence.expression.trim(),
534
+ timezone: cadence.timezone
535
+ };
536
+ case "repeat": switch (cadence.frequency) {
537
+ case "interval": return {
538
+ kind: "interval",
539
+ everyMinutes: intervalMinutes(cadence),
540
+ anchor
541
+ };
542
+ case "daily": return {
543
+ kind: "cron",
544
+ expression: `${minute} ${hour} * * *`,
545
+ timezone
546
+ };
547
+ case "weekly": return {
548
+ kind: "cron",
549
+ expression: `${minute} ${hour} * * ${weekdayField(cadence.weekdays)}`,
550
+ timezone
551
+ };
552
+ case "monthly": return {
553
+ kind: "cron",
554
+ expression: `${minute} ${hour} ${cadence.monthDay} * *`,
555
+ timezone
556
+ };
557
+ }
558
+ }
559
+ }
560
+ /**
561
+ * The problem a gateway refusal of a rule names, so the page says it in its
562
+ * own words. Every rule refusal starts `invalid rule:` (`src/source/rules.ts`);
563
+ * one this page does not recognise is the expression's syntax,
564
+ * the only refusal whose words come from the cron parser. Null for a refusal
565
+ * that is not about the rule.
566
+ */
567
+ function problemOfRefusal(reason) {
568
+ const match = /invalid rule: (.*)$/.exec(reason);
569
+ if (match === null) return null;
570
+ const detail = match[1];
571
+ if (detail === "the time has passed") return "past";
572
+ if (detail === "runs less than 5 minutes apart") return "tooOften";
573
+ if (detail === "the expression never runs") return "neverRuns";
574
+ if (detail.startsWith("unknown time zone")) return "timezone";
575
+ return "syntax";
576
+ }
577
+ //#endregion
578
+ //#region src/ui/describe.ts
579
+ function wordsOf(ctx) {
580
+ return {
581
+ t: (key, values) => values === void 0 ? ctx.i18n.t(key) : fill(ctx.i18n.t(key), values),
582
+ get locale() {
583
+ return ctx.i18n.t("locale");
584
+ }
585
+ };
586
+ }
587
+ function when(at, locale) {
588
+ return new Intl.DateTimeFormat(locale, {
589
+ dateStyle: "medium",
590
+ timeStyle: "short"
591
+ }).format(at);
592
+ }
593
+ function pad(value) {
594
+ return String(value).padStart(2, "0");
595
+ }
596
+ function timeText(time) {
597
+ return `${pad(time.hour)}:${pad(time.minute)}`;
598
+ }
599
+ /** A Sunday, from which a weekday's date is counted to name it. */
600
+ var SUNDAY = new Date(2026, 8, 27);
601
+ /** Days of the week in the order the page's language reads a week. */
602
+ function weekdayOrder(locale) {
603
+ return locale.startsWith("en") ? [
604
+ 0,
605
+ 1,
606
+ 2,
607
+ 3,
608
+ 4,
609
+ 5,
610
+ 6
611
+ ] : [
612
+ 1,
613
+ 2,
614
+ 3,
615
+ 4,
616
+ 5,
617
+ 6,
618
+ 0
619
+ ];
620
+ }
621
+ function weekdayName(day, locale) {
622
+ const date = new Date(SUNDAY.getFullYear(), SUNDAY.getMonth(), SUNDAY.getDate() + day);
623
+ return new Intl.DateTimeFormat(locale, { weekday: "short" }).format(date);
624
+ }
625
+ function ruleText(rule, words) {
626
+ const { t, locale } = words;
627
+ if (rule === null) return t("ruleNone");
628
+ const cadence = cadenceOf(rule, Date.now());
629
+ const time = timeText(cadence.time);
630
+ switch (cadence.mode) {
631
+ case "once": return t("ruleOnce", { at: when(instantOf(cadence.date, cadence.time), locale) });
632
+ case "cron": return t("ruleCron", {
633
+ expression: cadence.expression,
634
+ timezone: cadence.timezone
635
+ });
636
+ case "repeat": switch (cadence.frequency) {
637
+ case "interval": return t(cadence.unit === "hour" ? "ruleEveryHours" : "ruleEveryMinutes", { amount: cadence.amount ?? "" });
638
+ case "daily": return t("ruleDaily", { time });
639
+ case "weekly": return t("ruleWeekly", {
640
+ days: weekdayOrder(locale).filter((day) => cadence.weekdays.includes(day)).map((day) => weekdayName(day, locale)).join(t("listSeparator")),
641
+ time
642
+ });
643
+ case "monthly": return t("ruleMonthly", {
644
+ day: cadence.monthDay ?? "",
645
+ time
646
+ });
647
+ }
648
+ }
649
+ }
650
+ function runStateText(run, words) {
651
+ const state = words.t(`state.${run.state}`);
652
+ return run.reason === null ? state : `${state} · ${words.t(`reason.${run.reason}`)}`;
653
+ }
654
+ /** A task's state as its row and its detail name it; null while it simply runs. */
655
+ function stateOf(trigger, next, words) {
656
+ if (trigger.problem !== null) return {
657
+ text: words.t(`problem.${trigger.problem}`),
658
+ tone: "destructive"
659
+ };
660
+ if (!trigger.enabled) return {
661
+ text: words.t("paused"),
662
+ tone: "muted"
663
+ };
664
+ if (next === null) return {
665
+ text: words.t("noNext"),
666
+ tone: "muted"
667
+ };
668
+ return null;
669
+ }
670
+ //#endregion
671
+ //#region src/ui/env.tsx
672
+ var EnvContext = createContext(null);
673
+ var EnvProvider = EnvContext.Provider;
674
+ function envOf(ctx, store) {
675
+ return {
676
+ ctx,
677
+ store,
678
+ words: wordsOf(ctx)
679
+ };
680
+ }
681
+ function useEnv() {
682
+ const env = useContext(EnvContext);
683
+ if (env === null) throw new Error("scheduled tasks page rendered outside its provider");
684
+ return env;
685
+ }
686
+ function useSchedule(pick) {
687
+ const { store } = useEnv();
688
+ return useSyncExternalStore(store.subscribe, () => pick(store.get()));
689
+ }
690
+ /** The workspace the page is in, or `null` while there is none. */
691
+ function useWorkspaceId() {
692
+ const { ctx } = useEnv();
693
+ return useSyncExternalStore(ctx.host.subscribe, () => ctx.host.get().workspaceId ?? null);
694
+ }
695
+ /** Returns feature failures; the global dialog owns gateway connectivity and authentication. */
696
+ function failureText$1(_ctx, error) {
697
+ const failure = error?.failure;
698
+ if (failure === "offline" || failure === "authentication") return null;
699
+ return (error instanceof Error ? error.message : String(error)).replace(/^plugin "[^"]+" failed in \w+: /, "");
700
+ }
701
+ /** Shows a failure outside a form as a toast; offline says nothing, because
702
+ * the host's connection dialog owns the outage. */
703
+ function useFailureToast() {
704
+ const { ctx } = useEnv();
705
+ const toast = ctx.ui.useToast();
706
+ return useCallback((error) => {
707
+ const text = failureText$1(ctx, error);
708
+ if (text === null) return;
709
+ toast.add({
710
+ id: `failure::${text}`,
711
+ tone: "destructive",
712
+ title: text
713
+ });
714
+ }, [ctx, toast]);
715
+ }
716
+ /** What a session is called: the person's name, else the topic title, else
717
+ * the name of the task that opened it, else the untitled wording. */
718
+ function sessionTitle(session, tasks, untitled) {
719
+ if (session === void 0) return untitled;
720
+ if (session.name !== null) return session.name;
721
+ const ref = session.origin?.ref ?? null;
722
+ const origin = ref === null ? void 0 : tasks.find((one) => one.id === ref)?.name;
723
+ return session.title ?? origin ?? untitled;
724
+ }
725
+ /** An agent's face: its uploaded picture, else initials over a colour seeded
726
+ * by its id, the way the host draws one. */
727
+ function AgentFace({ agentId, size = "md", className }) {
728
+ const { ctx, store } = useEnv();
729
+ const agent = useSchedule((state) => state.agents.find((one) => one.agentId === agentId));
730
+ const rev = agent?.avatar ?? null;
731
+ const src = useSchedule((state) => rev === null ? null : state.pictures[rev] ?? null);
732
+ useEffect(() => {
733
+ if (rev !== null) store.requestPicture(agentId, rev);
734
+ }, [
735
+ store,
736
+ agentId,
737
+ rev
738
+ ]);
739
+ const name = agent?.name ?? agentId;
740
+ return /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
741
+ content: name,
742
+ children: /* @__PURE__ */ jsx(ctx.ui.Avatar, {
743
+ alt: name,
744
+ name,
745
+ seed: agentId,
746
+ algorithm: "initials",
747
+ size,
748
+ shape: "circle",
749
+ ...src === null ? {} : { src },
750
+ className
751
+ })
752
+ });
753
+ }
754
+ //#endregion
755
+ //#region src/tool-names.ts
756
+ /** Canonical names shared by tool registration and browser presentation. */
757
+ var TOOL_NAMES = [
758
+ "schedule_create",
759
+ "schedule_list",
760
+ "schedule_update",
761
+ "schedule_delete"
762
+ ];
763
+ //#endregion
764
+ //#region src/ui/metadata.ts
765
+ var CATALOGUES = {
766
+ "en-US": {
767
+ section: "Built-in plugins",
768
+ group: "Schedules",
769
+ schedule_create: "Create scheduled task",
770
+ schedule_list: "List scheduled tasks",
771
+ schedule_update: "Edit scheduled task",
772
+ schedule_delete: "Delete scheduled task"
773
+ },
774
+ "zh-CN": {
775
+ section: "内置插件",
776
+ group: "计划任务",
777
+ schedule_create: "新建计划任务",
778
+ schedule_list: "查看计划任务",
779
+ schedule_update: "修改计划任务",
780
+ schedule_delete: "删除计划任务"
781
+ }
782
+ };
783
+ var names = new Set(TOOL_NAMES);
784
+ /** Registers presentation facets with the same activation lifetime as the tools. */
785
+ function registerMetadata(ctx) {
786
+ ctx.i18n.register(CATALOGUES, "en-US");
787
+ ctx.i18n.contribute(Object.fromEntries(Object.entries(CATALOGUES).map(([language, catalogue]) => [language, Object.fromEntries([...names].map((tool) => [`transcript.actions.${tool}`, catalogue[tool] ?? tool]))])), "en-US");
788
+ ctx.slots.register("chat.tool.presentation", {
789
+ id: "tool-metadata",
790
+ describe: ({ call }) => {
791
+ if (!names.has(call.name)) return void 0;
792
+ const input = call.input !== null && typeof call.input === "object" ? call.input : {};
793
+ const summary = [
794
+ "path",
795
+ "url",
796
+ "query",
797
+ "command",
798
+ "skill",
799
+ "id",
800
+ "name",
801
+ "task",
802
+ "prompt"
803
+ ].flatMap((key) => typeof input[key] === "string" ? [input[key]] : []).slice(0, 2).join(" · ").replace(/\s+/g, " ").slice(0, 240);
804
+ return {
805
+ label: names.has(call.name) ? ctx.i18n.t(call.name) : call.name,
806
+ icon: "hammer",
807
+ summary
808
+ };
809
+ }
810
+ });
811
+ ctx.slots.register("shell.tools.group", {
812
+ id: "tool-groups",
813
+ describe: (tool) => {
814
+ if (tool.plugin !== ctx.plugin) return void 0;
815
+ return {
816
+ key: `plugin:${ctx.plugin}`,
817
+ label: ctx.i18n.t("group"),
818
+ source: ctx.plugin,
819
+ sectionLabel: ctx.i18n.t("section"),
820
+ sectionOrder: 1,
821
+ order: 6
822
+ };
823
+ }
824
+ });
825
+ }
826
+ //#endregion
827
+ //#region src/ui/scope.tsx
828
+ function RemoveButton({ label, onClick }) {
829
+ const { ctx } = useEnv();
830
+ return /* @__PURE__ */ jsx(ctx.ui.Button, {
831
+ variant: "ghost",
832
+ size: "sm",
833
+ type: "button",
834
+ icon: "trash",
835
+ "aria-label": label,
836
+ title: label,
837
+ onClick,
838
+ className: "sch-row-action"
839
+ });
840
+ }
841
+ function AddPathDialog({ open, onOpenChange, onAdd }) {
842
+ const { ctx, words } = useEnv();
843
+ const { t } = words;
844
+ const ui = ctx.ui;
845
+ const [path, setPath] = useState("");
846
+ const [access, setAccess] = useState("read");
847
+ useEffect(() => {
848
+ if (!open) {
849
+ setPath("");
850
+ setAccess("read");
851
+ }
852
+ }, [open]);
853
+ return /* @__PURE__ */ jsx(ui.Dialog, {
854
+ size: "sm",
855
+ open,
856
+ onOpenChange,
857
+ title: t("scopePathTitle"),
858
+ closeLabel: t("close"),
859
+ children: /* @__PURE__ */ jsxs("form", {
860
+ onSubmit: (event) => {
861
+ event.preventDefault();
862
+ event.stopPropagation();
863
+ if (path === "") return;
864
+ onAdd({
865
+ kind: access,
866
+ target: path
867
+ });
868
+ onOpenChange(false);
869
+ },
870
+ className: "sch-stack sch-path-form",
871
+ children: [
872
+ /* @__PURE__ */ jsx(ui.Field, {
873
+ label: t("scopePaths"),
874
+ inline: true,
875
+ children: (binding) => /* @__PURE__ */ jsx(ui.PathInput, {
876
+ ...binding,
877
+ value: path,
878
+ onValueChange: setPath,
879
+ placeholder: "/"
880
+ })
881
+ }),
882
+ /* @__PURE__ */ jsx(ui.Field, {
883
+ label: t("scopeAccess"),
884
+ inline: true,
885
+ children: () => /* @__PURE__ */ jsx(ui.Segmented, {
886
+ fullWidth: true,
887
+ label: t("scopeAccess"),
888
+ value: access,
889
+ onSelect: (value) => setAccess(value),
890
+ options: [{
891
+ value: "read",
892
+ label: t("scopeRead")
893
+ }, {
894
+ value: "write",
895
+ label: t("scopeWrite")
896
+ }]
897
+ })
898
+ }),
899
+ /* @__PURE__ */ jsx(ui.Alert, {
900
+ tone: "warning",
901
+ children: t(access === "read" ? "scopeReadWarning" : "scopeWriteWarning")
902
+ }),
903
+ /* @__PURE__ */ jsx("div", {
904
+ className: "sch-foot",
905
+ children: /* @__PURE__ */ jsx(ui.Button, {
906
+ type: "submit",
907
+ variant: "primary",
908
+ disabled: path === "",
909
+ children: t("add")
910
+ })
911
+ })
912
+ ]
913
+ })
914
+ });
915
+ }
916
+ function AddHostDialog({ open, onOpenChange, onAdd }) {
917
+ const { ctx, words } = useEnv();
918
+ const { t } = words;
919
+ const ui = ctx.ui;
920
+ const [host, setHost] = useState("");
921
+ useEffect(() => {
922
+ if (!open) setHost("");
923
+ }, [open]);
924
+ return /* @__PURE__ */ jsx(ui.Dialog, {
925
+ size: "sm",
926
+ open,
927
+ onOpenChange,
928
+ title: t("scopeHostTitle"),
929
+ closeLabel: t("close"),
930
+ children: /* @__PURE__ */ jsxs("form", {
931
+ onSubmit: (event) => {
932
+ event.preventDefault();
933
+ event.stopPropagation();
934
+ const wanted = host.trim().toLowerCase();
935
+ if (wanted === "") return;
936
+ onAdd(wanted);
937
+ onOpenChange(false);
938
+ },
939
+ className: "sch-stack",
940
+ children: [/* @__PURE__ */ jsx(ui.Field, {
941
+ label: t("scopeHost"),
942
+ help: t("scopeHostHelp"),
943
+ inline: true,
944
+ children: (binding) => /* @__PURE__ */ jsx(ui.Input, {
945
+ ...binding,
946
+ value: host,
947
+ spellCheck: false,
948
+ autoComplete: "off",
949
+ placeholder: "example.com",
950
+ className: "sch-mono",
951
+ onChange: (event) => setHost(event.target.value)
952
+ })
953
+ }), /* @__PURE__ */ jsx("div", {
954
+ className: "sch-foot",
955
+ children: /* @__PURE__ */ jsx(ui.Button, {
956
+ type: "submit",
957
+ variant: "primary",
958
+ disabled: host.trim() === "",
959
+ children: t("add")
960
+ })
961
+ })]
962
+ })
963
+ });
964
+ }
965
+ /** One kind of scope as a list: its name and add action, then a row per item. */
966
+ function ScopeList({ title, addLabel, emptyLabel, onAdd, children }) {
967
+ const { ctx } = useEnv();
968
+ return /* @__PURE__ */ jsxs("div", {
969
+ className: "sch-scope-list",
970
+ children: [/* @__PURE__ */ jsxs("div", {
971
+ className: "sch-scope-head",
972
+ children: [/* @__PURE__ */ jsx("span", { children: title }), /* @__PURE__ */ jsx(ctx.ui.Button, {
973
+ variant: "outline",
974
+ size: "sm",
975
+ icon: "plus",
976
+ type: "button",
977
+ onClick: onAdd,
978
+ children: addLabel
979
+ })]
980
+ }), children.length === 0 ? /* @__PURE__ */ jsx("p", {
981
+ className: "sch-muted-text",
982
+ children: emptyLabel
983
+ }) : /* @__PURE__ */ jsx("ul", {
984
+ className: "sch-rows",
985
+ children
986
+ })]
987
+ });
988
+ }
989
+ function Row$1({ icon, target, badge, onRemove }) {
990
+ const { ctx, words } = useEnv();
991
+ return /* @__PURE__ */ jsxs("li", {
992
+ className: "sch-row",
993
+ children: [
994
+ /* @__PURE__ */ jsx(ctx.ui.Icon, {
995
+ name: icon,
996
+ className: "sch-row-icon"
997
+ }),
998
+ /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
999
+ content: target,
1000
+ children: /* @__PURE__ */ jsx("span", {
1001
+ className: "sch-row-target sch-mono",
1002
+ children: target
1003
+ })
1004
+ }),
1005
+ badge,
1006
+ /* @__PURE__ */ jsx(RemoveButton, {
1007
+ label: `${words.t("remove")} ${target}`,
1008
+ onClick: onRemove
1009
+ })
1010
+ ]
1011
+ });
1012
+ }
1013
+ /** Edits exact path targets, web hosts, and network pre-authorization for scheduled runs. */
1014
+ function Scope({ value, onChange }) {
1015
+ const { ctx, words } = useEnv();
1016
+ const { t } = words;
1017
+ const ui = ctx.ui;
1018
+ const [adding, setAdding] = useState(null);
1019
+ const paths = value.filter((item) => item.kind === "read" || item.kind === "write");
1020
+ const hosts = value.filter((item) => item.kind === "web-host");
1021
+ const network = value.some((item) => item.kind === "network");
1022
+ const without = (gone) => value.filter((item) => item.kind !== gone.kind || item.target !== gone.target);
1023
+ const addPath = (item) => onChange([...value.filter((one) => !((one.kind === "read" || one.kind === "write") && one.target === item.target)), item]);
1024
+ const addHost = (host) => {
1025
+ if (!hosts.some((one) => one.target === host)) onChange([...value, {
1026
+ kind: "web-host",
1027
+ target: host
1028
+ }]);
1029
+ };
1030
+ return /* @__PURE__ */ jsxs("div", {
1031
+ "data-slot": "schedule-scope",
1032
+ className: "sch-stack",
1033
+ children: [
1034
+ /* @__PURE__ */ jsx(ScopeList, {
1035
+ title: t("scopePaths"),
1036
+ addLabel: t("scopePathAdd"),
1037
+ emptyLabel: t("scopePathsEmpty"),
1038
+ onAdd: () => setAdding("path"),
1039
+ children: paths.map((item) => /* @__PURE__ */ jsx(Row$1, {
1040
+ icon: "folder",
1041
+ target: item.target,
1042
+ badge: /* @__PURE__ */ jsx(ui.Badge, {
1043
+ size: "sm",
1044
+ tone: item.kind === "write" ? "warning" : "neutral",
1045
+ children: t(item.kind === "write" ? "scopeWrite" : "scopeRead")
1046
+ }),
1047
+ onRemove: () => onChange(without(item))
1048
+ }, `${item.kind}:${item.target}`))
1049
+ }),
1050
+ /* @__PURE__ */ jsx(ScopeList, {
1051
+ title: t("scopeHosts"),
1052
+ addLabel: t("scopeHostAdd"),
1053
+ emptyLabel: t("scopeHostsEmpty"),
1054
+ onAdd: () => setAdding("host"),
1055
+ children: hosts.map((item) => /* @__PURE__ */ jsx(Row$1, {
1056
+ icon: "globe",
1057
+ target: item.target,
1058
+ onRemove: () => onChange(without(item))
1059
+ }, item.target))
1060
+ }),
1061
+ /* @__PURE__ */ jsx(ui.Field, {
1062
+ label: t("scopeNetwork"),
1063
+ help: t("scopeNetworkHelp"),
1064
+ inline: true,
1065
+ children: () => /* @__PURE__ */ jsx(ui.Segmented, {
1066
+ fullWidth: true,
1067
+ label: t("scopeNetwork"),
1068
+ value: network ? "authorized" : "policy",
1069
+ onSelect: (choice) => onChange(choice === "authorized" ? [...value.filter((item) => item.kind !== "network"), {
1070
+ kind: "network",
1071
+ target: "*"
1072
+ }] : value.filter((item) => item.kind !== "network")),
1073
+ options: [{
1074
+ value: "policy",
1075
+ label: t("scopeNetworkPolicy")
1076
+ }, {
1077
+ value: "authorized",
1078
+ label: t("scopeNetworkAuthorized")
1079
+ }]
1080
+ })
1081
+ }),
1082
+ /* @__PURE__ */ jsx(AddPathDialog, {
1083
+ open: adding === "path",
1084
+ onOpenChange: (open) => setAdding(open ? "path" : null),
1085
+ onAdd: addPath
1086
+ }),
1087
+ /* @__PURE__ */ jsx(AddHostDialog, {
1088
+ open: adding === "host",
1089
+ onOpenChange: (open) => setAdding(open ? "host" : null),
1090
+ onAdd: addHost
1091
+ })
1092
+ ]
1093
+ });
1094
+ }
1095
+ //#endregion
1096
+ //#region src/ui/timing.tsx
1097
+ /**
1098
+ * The 执行计划 tab of the schedule editor: how a task is timed, as a mode
1099
+ * (单次 / 重复 / Cron) and the fields that mode needs, then the next runs this
1100
+ * plugin's `preview` computes for it and whether a missed run is caught up.
1101
+ *
1102
+ * The rows are inline fields, label beside control, so the tab reads as a
1103
+ * form of one rhythm whatever the mode. The preview is asked for every valid
1104
+ * rule; a rule the page already knows is incomplete says why instead, and a
1105
+ * rule the gateway refuses shows the gateway's sentence.
1106
+ */
1107
+ /** Every IANA zone the browser knows, the local one first. */
1108
+ function timezones() {
1109
+ const local = localTimezone();
1110
+ return [local, ...(typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []).filter((zone) => zone !== local)];
1111
+ }
1112
+ function isToday(date) {
1113
+ const today = dateOf(Date.now());
1114
+ return today.year === date.year && today.month === date.month && today.day === date.day;
1115
+ }
1116
+ /** The earliest time a one-off run can still take today: the next minute. */
1117
+ function nowTime() {
1118
+ const next = new Date(Date.now() + 6e4);
1119
+ return {
1120
+ hour: next.getHours(),
1121
+ minute: next.getMinutes()
1122
+ };
1123
+ }
1124
+ function usePreview(rule) {
1125
+ const { ctx } = useEnv();
1126
+ const [preview, setPreview] = useState(null);
1127
+ const key = rule === null ? null : JSON.stringify(rule);
1128
+ useEffect(() => {
1129
+ if (key === null) {
1130
+ setPreview(null);
1131
+ return;
1132
+ }
1133
+ let live = true;
1134
+ ctx.invoke("preview", { rule: JSON.parse(key) }).then((result) => live && setPreview({ next: result.times })).catch((error) => {
1135
+ const failure = error?.failure;
1136
+ if (live) setPreview({ error: failure === void 0 ? failureText$1(ctx, error) ?? "" : "" });
1137
+ });
1138
+ return () => {
1139
+ live = false;
1140
+ };
1141
+ }, [ctx, key]);
1142
+ return preview;
1143
+ }
1144
+ function Timing({ cadence, anchor, catchUp, onCadence, onCatchUp }) {
1145
+ const { ctx, words } = useEnv();
1146
+ const { t, locale } = words;
1147
+ const ui = ctx.ui;
1148
+ const zones = useMemo(() => timezones().map((zone) => ({
1149
+ value: zone,
1150
+ label: zone
1151
+ })), []);
1152
+ const problem = problemOf(cadence);
1153
+ const rule = ruleOf(cadence, anchor);
1154
+ const preview = usePreview(rule);
1155
+ const zone = rule?.kind === "cron" ? rule.timezone : null;
1156
+ const at = useMemo(() => {
1157
+ try {
1158
+ return new Intl.DateTimeFormat(locale, {
1159
+ ...zone === null ? {} : { timeZone: zone },
1160
+ month: "short",
1161
+ day: "numeric",
1162
+ weekday: "short",
1163
+ hour: "2-digit",
1164
+ minute: "2-digit"
1165
+ });
1166
+ } catch (error) {
1167
+ if (zone === null) throw error;
1168
+ return null;
1169
+ }
1170
+ }, [locale, zone]);
1171
+ return /* @__PURE__ */ jsxs("div", {
1172
+ "data-slot": "schedule-timing",
1173
+ className: "sch-stack",
1174
+ children: [
1175
+ /* @__PURE__ */ jsx(ui.Field, {
1176
+ label: t("mode"),
1177
+ inline: true,
1178
+ children: () => /* @__PURE__ */ jsx(ui.Segmented, {
1179
+ fullWidth: true,
1180
+ label: t("mode"),
1181
+ value: cadence.mode,
1182
+ onSelect: (mode) => onCadence({ mode }),
1183
+ options: [
1184
+ {
1185
+ value: "once",
1186
+ label: t("modeOnce")
1187
+ },
1188
+ {
1189
+ value: "repeat",
1190
+ label: t("modeRepeat")
1191
+ },
1192
+ {
1193
+ value: "cron",
1194
+ label: t("modeCron")
1195
+ }
1196
+ ]
1197
+ })
1198
+ }),
1199
+ cadence.mode === "once" && /* @__PURE__ */ jsx(ui.Field, {
1200
+ label: t("runAt"),
1201
+ inline: true,
1202
+ children: (binding) => /* @__PURE__ */ jsxs("div", {
1203
+ className: "sch-date-time",
1204
+ children: [/* @__PURE__ */ jsx(ui.DatePicker, {
1205
+ id: binding.id,
1206
+ labelledBy: binding["aria-labelledby"],
1207
+ value: cadence.date,
1208
+ min: dateOf(Date.now()),
1209
+ onChange: (date) => {
1210
+ const earliest = nowTime();
1211
+ onCadence(isToday(date) && (cadence.time.hour < earliest.hour || cadence.time.hour === earliest.hour && cadence.time.minute < earliest.minute) ? {
1212
+ date,
1213
+ time: earliest
1214
+ } : { date });
1215
+ }
1216
+ }), /* @__PURE__ */ jsx(ui.TimePicker, {
1217
+ labelledBy: binding["aria-labelledby"],
1218
+ value: cadence.time,
1219
+ ...isToday(cadence.date) ? { min: nowTime() } : {},
1220
+ onChange: (time) => onCadence({ time })
1221
+ })]
1222
+ })
1223
+ }),
1224
+ cadence.mode === "repeat" && /* @__PURE__ */ jsxs(Fragment, { children: [
1225
+ /* @__PURE__ */ jsx(ui.Field, {
1226
+ label: t("frequency"),
1227
+ inline: true,
1228
+ children: (binding) => /* @__PURE__ */ jsx("div", {
1229
+ className: "sch-select",
1230
+ children: /* @__PURE__ */ jsxs(ui.Select, {
1231
+ className: "sch-full-width",
1232
+ ...binding,
1233
+ value: cadence.frequency,
1234
+ onValueChange: (frequency) => onCadence({ frequency }),
1235
+ children: [
1236
+ /* @__PURE__ */ jsx("option", {
1237
+ value: "interval",
1238
+ children: t("frequencyInterval")
1239
+ }),
1240
+ /* @__PURE__ */ jsx("option", {
1241
+ value: "daily",
1242
+ children: t("frequencyDaily")
1243
+ }),
1244
+ /* @__PURE__ */ jsx("option", {
1245
+ value: "weekly",
1246
+ children: t("frequencyWeekly")
1247
+ }),
1248
+ /* @__PURE__ */ jsx("option", {
1249
+ value: "monthly",
1250
+ children: t("frequencyMonthly")
1251
+ })
1252
+ ]
1253
+ })
1254
+ })
1255
+ }),
1256
+ cadence.frequency === "interval" && /* @__PURE__ */ jsx(ui.Field, {
1257
+ label: t("interval"),
1258
+ inline: true,
1259
+ children: (binding) => /* @__PURE__ */ jsxs("div", {
1260
+ className: "sch-inline",
1261
+ children: [
1262
+ /* @__PURE__ */ jsx("span", {
1263
+ className: "sch-muted-text",
1264
+ children: t("every")
1265
+ }),
1266
+ /* @__PURE__ */ jsx("div", {
1267
+ className: "sch-number",
1268
+ children: /* @__PURE__ */ jsx(ui.InputNumber, {
1269
+ id: binding.id,
1270
+ label: t("interval"),
1271
+ incrementLabel: t("increase"),
1272
+ decrementLabel: t("decrease"),
1273
+ min: 1,
1274
+ step: 1,
1275
+ value: cadence.amount,
1276
+ onValueChange: (amount) => onCadence({ amount })
1277
+ })
1278
+ }),
1279
+ /* @__PURE__ */ jsx("div", {
1280
+ className: "sch-unit",
1281
+ children: /* @__PURE__ */ jsxs(ui.Select, {
1282
+ className: "sch-full-width",
1283
+ "aria-label": t("unit"),
1284
+ value: cadence.unit,
1285
+ onValueChange: (unit) => onCadence({ unit }),
1286
+ children: [/* @__PURE__ */ jsx("option", {
1287
+ value: "minute",
1288
+ children: t("unitMinute")
1289
+ }), /* @__PURE__ */ jsx("option", {
1290
+ value: "hour",
1291
+ children: t("unitHour")
1292
+ })]
1293
+ })
1294
+ })
1295
+ ]
1296
+ })
1297
+ }),
1298
+ cadence.frequency === "weekly" && /* @__PURE__ */ jsx(ui.Field, {
1299
+ label: t("weekdays"),
1300
+ inline: true,
1301
+ children: (binding) => /* @__PURE__ */ jsx(ui.WeekdayPicker, {
1302
+ labelledBy: binding["aria-labelledby"],
1303
+ value: cadence.weekdays,
1304
+ onChange: (weekdays) => onCadence({ weekdays })
1305
+ })
1306
+ }),
1307
+ cadence.frequency === "monthly" && /* @__PURE__ */ jsx(ui.Field, {
1308
+ label: t("monthDay"),
1309
+ help: t("monthDayHelp"),
1310
+ inline: true,
1311
+ children: (binding) => /* @__PURE__ */ jsxs("div", {
1312
+ className: "sch-inline",
1313
+ children: [/* @__PURE__ */ jsx("div", {
1314
+ className: "sch-number",
1315
+ children: /* @__PURE__ */ jsx(ui.InputNumber, {
1316
+ id: binding.id,
1317
+ label: t("monthDay"),
1318
+ incrementLabel: t("increase"),
1319
+ decrementLabel: t("decrease"),
1320
+ min: 1,
1321
+ max: 31,
1322
+ step: 1,
1323
+ value: cadence.monthDay,
1324
+ onValueChange: (monthDay) => onCadence({ monthDay })
1325
+ })
1326
+ }), /* @__PURE__ */ jsx("span", {
1327
+ className: "sch-muted-text",
1328
+ children: t("monthDaySuffix")
1329
+ })]
1330
+ })
1331
+ }),
1332
+ cadence.frequency !== "interval" && /* @__PURE__ */ jsx(ui.Field, {
1333
+ label: t("timeOfDay"),
1334
+ inline: true,
1335
+ children: (binding) => /* @__PURE__ */ jsx(ui.TimePicker, {
1336
+ id: binding.id,
1337
+ labelledBy: binding["aria-labelledby"],
1338
+ value: cadence.time,
1339
+ onChange: (time) => onCadence({ time })
1340
+ })
1341
+ })
1342
+ ] }),
1343
+ cadence.mode === "cron" && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ui.Field, {
1344
+ label: t("expression"),
1345
+ help: t("expressionHelp"),
1346
+ inline: true,
1347
+ children: (binding) => /* @__PURE__ */ jsx(ui.Input, {
1348
+ ...binding,
1349
+ value: cadence.expression,
1350
+ spellCheck: false,
1351
+ autoComplete: "off",
1352
+ placeholder: "0 9 * * 1-5",
1353
+ className: "sch-mono",
1354
+ onChange: (event) => onCadence({ expression: event.target.value })
1355
+ })
1356
+ }), /* @__PURE__ */ jsx(ui.Field, {
1357
+ label: t("timezone"),
1358
+ inline: true,
1359
+ children: (binding) => /* @__PURE__ */ jsx(ui.Combobox, {
1360
+ id: binding.id,
1361
+ "aria-labelledby": binding["aria-labelledby"],
1362
+ label: t("timezone"),
1363
+ options: zones,
1364
+ value: cadence.timezone,
1365
+ onValueChange: (timezone) => timezone !== null && onCadence({ timezone }),
1366
+ emptyLabel: t("timezoneEmpty"),
1367
+ toggleLabel: t("timezone")
1368
+ })
1369
+ })] }),
1370
+ /* @__PURE__ */ jsxs("div", {
1371
+ "data-slot": "schedule-preview",
1372
+ className: "sch-preview",
1373
+ children: [/* @__PURE__ */ jsx("span", {
1374
+ className: "sch-muted-text sch-preview-term",
1375
+ children: t("upcoming")
1376
+ }), problem !== null ? /* @__PURE__ */ jsx("span", {
1377
+ className: "sch-danger",
1378
+ children: t(`invalid.${problem}`)
1379
+ }) : preview === null ? /* @__PURE__ */ jsx("span", {
1380
+ className: "sch-muted-text",
1381
+ children: "—"
1382
+ }) : "error" in preview ? /* @__PURE__ */ jsx("span", {
1383
+ className: "sch-danger",
1384
+ children: (() => {
1385
+ const named = problemOfRefusal(preview.error);
1386
+ return named === null ? preview.error : t(`invalid.${named}`);
1387
+ })()
1388
+ }) : at === null ? /* @__PURE__ */ jsx("span", {
1389
+ className: "sch-danger",
1390
+ children: t("invalid.timezone")
1391
+ }) : /* @__PURE__ */ jsxs("ul", {
1392
+ className: "sch-preview-list",
1393
+ children: [preview.next.map((next) => /* @__PURE__ */ jsx("li", {
1394
+ className: "sch-tabular",
1395
+ children: at.format(next)
1396
+ }, next)), zone !== null && /* @__PURE__ */ jsx("li", {
1397
+ className: "sch-muted-text",
1398
+ children: t("inTimezone", { zone })
1399
+ })]
1400
+ })]
1401
+ }),
1402
+ /* @__PURE__ */ jsx(ui.Field, {
1403
+ label: t("catchUp"),
1404
+ help: t("catchUpHelp"),
1405
+ inline: true,
1406
+ children: () => /* @__PURE__ */ jsx(ui.Segmented, {
1407
+ fullWidth: true,
1408
+ label: t("catchUp"),
1409
+ value: catchUp ? "catch-up" : "skip",
1410
+ onSelect: (value) => onCatchUp(value === "catch-up"),
1411
+ options: [{
1412
+ value: "catch-up",
1413
+ label: t("catchUpRun")
1414
+ }, {
1415
+ value: "skip",
1416
+ label: t("catchUpSkip")
1417
+ }]
1418
+ })
1419
+ })
1420
+ ]
1421
+ });
1422
+ }
1423
+ //#endregion
1424
+ //#region src/ui/wire.ts
1425
+ /** The minted source this plugin's definitions carry. */
1426
+ var SOURCE = "plugin:@eum-agent/automation-schedule:schedule";
1427
+ /** A definition's config read back; `null` for one that is not a rule. */
1428
+ function configOf(raw) {
1429
+ if (typeof raw !== "object" || raw === null) return null;
1430
+ const { rule, catchUp } = raw;
1431
+ if (typeof rule !== "object" || rule === null) return null;
1432
+ const kind = rule.kind;
1433
+ if (kind !== "once" && kind !== "interval" && kind !== "cron") return null;
1434
+ return {
1435
+ rule,
1436
+ catchUp: catchUp !== false
1437
+ };
1438
+ }
1439
+ //#endregion
1440
+ //#region src/ui/editor.tsx
1441
+ /**
1442
+ * The dialog that creates or changes a scheduled task.
1443
+ *
1444
+ * Three tabs: 基本信息 (name, agent, instruction, where it runs), 执行计划
1445
+ * (`timing.tsx`) and 预授权 (`scope.tsx`), which says why it is empty while
1446
+ * runs go into an existing session — such a run carries no scope. Saving with
1447
+ * something missing marks each tab that still needs attention and opens the
1448
+ * first of them; a refusal stays in the footer beside the action that caused
1449
+ * it.
1450
+ *
1451
+ * It writes through the core's `trigger.create` / `trigger.update`, the
1452
+ * definition's `config` being this plugin's `{ rule, catchUp }`.
1453
+ */
1454
+ var TABS = [
1455
+ "basics",
1456
+ "timing",
1457
+ "scope"
1458
+ ];
1459
+ function draftOf(trigger, agentId) {
1460
+ const now = Date.now();
1461
+ const config = trigger === null ? null : configOf(trigger.config);
1462
+ const rule = config?.rule ?? null;
1463
+ return {
1464
+ name: trigger?.name ?? "",
1465
+ agentId: trigger?.agentId ?? agentId,
1466
+ cadence: cadenceOf(rule, now),
1467
+ anchor: rule?.kind === "interval" ? rule.anchor : now,
1468
+ instruction: trigger?.instruction ?? "",
1469
+ targetKind: trigger?.target.kind ?? "new-session",
1470
+ sessionId: trigger?.target.kind === "session" ? trigger.target.sessionId : "",
1471
+ catchUp: config?.catchUp ?? true,
1472
+ scope: [...trigger?.scope ?? []]
1473
+ };
1474
+ }
1475
+ /** The input a complete draft stands for; null while something is missing. */
1476
+ function inputOf(draft, workspaceId) {
1477
+ const rule = ruleOf(draft.cadence, draft.anchor);
1478
+ if (rule === null || draft.name.trim() === "" || draft.instruction.trim() === "" || draft.targetKind === "session" && draft.sessionId === "") return null;
1479
+ return {
1480
+ name: draft.name.trim(),
1481
+ agentId: draft.agentId,
1482
+ workspaceId,
1483
+ config: {
1484
+ rule,
1485
+ catchUp: draft.catchUp
1486
+ },
1487
+ instruction: draft.instruction.trim(),
1488
+ target: draft.targetKind === "session" ? {
1489
+ kind: "session",
1490
+ sessionId: draft.sessionId
1491
+ } : { kind: "new-session" },
1492
+ scope: draft.targetKind === "session" ? [] : [...draft.scope]
1493
+ };
1494
+ }
1495
+ function EditorBody({ trigger, workspaceId, onClose }) {
1496
+ const { ctx, words } = useEnv();
1497
+ const { t } = words;
1498
+ const ui = ctx.ui;
1499
+ const agents = useSchedule((state) => state.agents);
1500
+ const sessions = useSchedule((state) => state.sessions);
1501
+ const tasks = useSchedule((state) => state.tasks) ?? [];
1502
+ const [draft, setDraft] = useState(() => draftOf(trigger, agents.find((one) => one.startsSessions)?.agentId ?? agents[0]?.agentId ?? ""));
1503
+ const [pending, setPending] = useState(false);
1504
+ const saving = useRef(false);
1505
+ const [failure, setFailure] = useState(null);
1506
+ const [tab, setTab] = useState("basics");
1507
+ const [attempted, setAttempted] = useState(false);
1508
+ const set = (patch) => setDraft((current) => ({
1509
+ ...current,
1510
+ ...patch
1511
+ }));
1512
+ const input = inputOf(draft, trigger?.workspaceId ?? workspaceId);
1513
+ const optionLabel = (one) => {
1514
+ const title = sessionTitle(one, tasks, t("untitled"));
1515
+ return one.name !== null && one.title !== null ? `${title} · ${one.title}` : title;
1516
+ };
1517
+ const workspaceSessions = sessions.filter((one) => one.workspaceId === (trigger?.workspaceId ?? workspaceId) && one.parentSessionId === void 0);
1518
+ async function save(ready) {
1519
+ if (saving.current) return;
1520
+ saving.current = true;
1521
+ setPending(true);
1522
+ setFailure(null);
1523
+ try {
1524
+ if (trigger === null) await ctx.call("trigger.create", {
1525
+ ...ready,
1526
+ source: SOURCE
1527
+ });
1528
+ else await ctx.call("trigger.update", {
1529
+ ...ready,
1530
+ id: trigger.id
1531
+ });
1532
+ onClose();
1533
+ } catch (error) {
1534
+ const text = failureText$1(ctx, error);
1535
+ const named = text === null ? null : problemOfRefusal(text);
1536
+ setFailure(named === null ? text : t(`invalid.${named}`));
1537
+ } finally {
1538
+ saving.current = false;
1539
+ setPending(false);
1540
+ }
1541
+ }
1542
+ const missing = {
1543
+ name: draft.name.trim() === "",
1544
+ instruction: draft.instruction.trim() === "",
1545
+ session: draft.targetKind === "session" && draft.sessionId === ""
1546
+ };
1547
+ const incomplete = {
1548
+ basics: missing.name || missing.instruction || missing.session,
1549
+ timing: problemOf(draft.cadence) !== null,
1550
+ scope: false
1551
+ };
1552
+ const required = (gap) => attempted && gap ? t("required") : void 0;
1553
+ const tabLabel = (key, label) => /* @__PURE__ */ jsxs(Fragment, { children: [label, attempted && incomplete[key] && /* @__PURE__ */ jsx("span", {
1554
+ "aria-hidden": "true",
1555
+ className: "sch-tab-mark"
1556
+ })] });
1557
+ return /* @__PURE__ */ jsxs("form", {
1558
+ "data-slot": "schedule-editor",
1559
+ className: "sch-editor",
1560
+ noValidate: true,
1561
+ onSubmit: (event) => {
1562
+ event.preventDefault();
1563
+ if (input === null) {
1564
+ setAttempted(true);
1565
+ setTab(TABS.find((key) => incomplete[key]) ?? tab);
1566
+ return;
1567
+ }
1568
+ save(input);
1569
+ },
1570
+ children: [/* @__PURE__ */ jsxs(ui.Tabs, {
1571
+ value: tab,
1572
+ onValueChange: (next) => setTab(next),
1573
+ children: [
1574
+ /* @__PURE__ */ jsxs(ui.TabsList, {
1575
+ "aria-label": trigger === null ? t("createTitle") : t("editTitle"),
1576
+ children: [
1577
+ /* @__PURE__ */ jsx(ui.TabsTrigger, {
1578
+ value: "basics",
1579
+ children: tabLabel("basics", t("sectionBasics"))
1580
+ }),
1581
+ /* @__PURE__ */ jsx(ui.TabsTrigger, {
1582
+ value: "timing",
1583
+ children: tabLabel("timing", t("sectionTiming"))
1584
+ }),
1585
+ /* @__PURE__ */ jsx(ui.TabsTrigger, {
1586
+ value: "scope",
1587
+ children: tabLabel("scope", t("sectionScope"))
1588
+ })
1589
+ ]
1590
+ }),
1591
+ /* @__PURE__ */ jsx(ui.TabsContent, {
1592
+ value: "basics",
1593
+ children: /* @__PURE__ */ jsxs("div", {
1594
+ className: "sch-panel",
1595
+ children: [
1596
+ /* @__PURE__ */ jsx(ui.Field, {
1597
+ label: t("name"),
1598
+ required: true,
1599
+ inline: true,
1600
+ error: required(missing.name),
1601
+ children: (binding) => /* @__PURE__ */ jsx(ui.Input, {
1602
+ ...binding,
1603
+ value: draft.name,
1604
+ maxLength: 80,
1605
+ placeholder: t("namePlaceholder"),
1606
+ onChange: (event) => set({ name: event.target.value })
1607
+ })
1608
+ }),
1609
+ /* @__PURE__ */ jsx(ui.Field, {
1610
+ label: t("agent"),
1611
+ required: true,
1612
+ inline: true,
1613
+ children: (binding) => /* @__PURE__ */ jsx(ui.Select, {
1614
+ className: "sch-full-width",
1615
+ ...binding,
1616
+ value: draft.agentId,
1617
+ onValueChange: (agentId) => set({ agentId }),
1618
+ children: agents.map((agent) => /* @__PURE__ */ jsx("option", {
1619
+ value: agent.agentId,
1620
+ children: /* @__PURE__ */ jsxs("span", {
1621
+ className: "sch-agent-option",
1622
+ children: [/* @__PURE__ */ jsx(AgentFace, {
1623
+ agentId: agent.agentId,
1624
+ size: "sm"
1625
+ }), /* @__PURE__ */ jsx("span", {
1626
+ className: "sch-agent-name",
1627
+ children: agent.name
1628
+ })]
1629
+ })
1630
+ }, agent.agentId))
1631
+ })
1632
+ }),
1633
+ /* @__PURE__ */ jsx(ui.Field, {
1634
+ label: t("instruction"),
1635
+ required: true,
1636
+ inline: true,
1637
+ error: required(missing.instruction),
1638
+ children: (binding) => /* @__PURE__ */ jsx(ui.Textarea, {
1639
+ ...binding,
1640
+ rows: 6,
1641
+ maxLength: 8e3,
1642
+ value: draft.instruction,
1643
+ placeholder: t("instructionPlaceholder"),
1644
+ onChange: (event) => set({ instruction: event.target.value })
1645
+ })
1646
+ }),
1647
+ /* @__PURE__ */ jsx(ui.Field, {
1648
+ label: t("target"),
1649
+ inline: true,
1650
+ children: () => /* @__PURE__ */ jsx(ui.Segmented, {
1651
+ fullWidth: true,
1652
+ label: t("target"),
1653
+ value: draft.targetKind,
1654
+ onSelect: (targetKind) => set({ targetKind }),
1655
+ options: [{
1656
+ value: "new-session",
1657
+ label: t("targetNew")
1658
+ }, {
1659
+ value: "session",
1660
+ label: t("targetSession")
1661
+ }]
1662
+ })
1663
+ }),
1664
+ draft.targetKind === "session" && /* @__PURE__ */ jsx(ui.Field, {
1665
+ label: t("session"),
1666
+ required: true,
1667
+ inline: true,
1668
+ error: required(missing.session),
1669
+ children: (binding) => /* @__PURE__ */ jsxs(ui.Select, {
1670
+ className: "sch-full-width",
1671
+ ...binding,
1672
+ value: draft.sessionId,
1673
+ onValueChange: (sessionId) => set({ sessionId }),
1674
+ children: [/* @__PURE__ */ jsx("option", {
1675
+ value: "",
1676
+ disabled: true,
1677
+ children: t("sessionPlaceholder")
1678
+ }), workspaceSessions.map((one) => /* @__PURE__ */ jsx("option", {
1679
+ value: one.sessionId,
1680
+ children: optionLabel(one)
1681
+ }, one.sessionId))]
1682
+ })
1683
+ })
1684
+ ]
1685
+ })
1686
+ }),
1687
+ /* @__PURE__ */ jsx(ui.TabsContent, {
1688
+ value: "timing",
1689
+ children: /* @__PURE__ */ jsx("div", {
1690
+ className: "sch-panel",
1691
+ children: /* @__PURE__ */ jsx(Timing, {
1692
+ cadence: draft.cadence,
1693
+ anchor: draft.anchor,
1694
+ catchUp: draft.catchUp,
1695
+ onCadence: (patch) => setDraft((current) => ({
1696
+ ...current,
1697
+ cadence: {
1698
+ ...current.cadence,
1699
+ ...patch
1700
+ }
1701
+ })),
1702
+ onCatchUp: (catchUp) => set({ catchUp })
1703
+ })
1704
+ })
1705
+ }),
1706
+ /* @__PURE__ */ jsx(ui.TabsContent, {
1707
+ value: "scope",
1708
+ children: /* @__PURE__ */ jsxs("div", {
1709
+ className: "sch-panel",
1710
+ children: [/* @__PURE__ */ jsx("p", {
1711
+ className: "sch-muted-text",
1712
+ children: t(draft.targetKind === "session" ? "scopeUnavailable" : "scopeHelp")
1713
+ }), draft.targetKind === "new-session" && /* @__PURE__ */ jsx(Scope, {
1714
+ value: draft.scope,
1715
+ onChange: (scope) => set({ scope })
1716
+ })]
1717
+ })
1718
+ })
1719
+ ]
1720
+ }), /* @__PURE__ */ jsxs("div", {
1721
+ className: "sch-editor-foot",
1722
+ children: [failure !== null && /* @__PURE__ */ jsx("p", {
1723
+ role: "alert",
1724
+ className: "sch-danger sch-grow",
1725
+ children: failure
1726
+ }), /* @__PURE__ */ jsxs("div", {
1727
+ className: "sch-foot-actions",
1728
+ children: [/* @__PURE__ */ jsx(ui.Button, {
1729
+ type: "button",
1730
+ variant: "ghost",
1731
+ onClick: onClose,
1732
+ children: t("cancel")
1733
+ }), /* @__PURE__ */ jsx(ui.Button, {
1734
+ type: "submit",
1735
+ variant: "primary",
1736
+ disabled: pending,
1737
+ loading: pending,
1738
+ children: t(trigger === null ? "createAction" : "save")
1739
+ })]
1740
+ })]
1741
+ })]
1742
+ });
1743
+ }
1744
+ /** `editing` is the task being changed, `'new'` for a new one, null for closed. */
1745
+ function ScheduleEditor({ editing, workspaceId, onClose }) {
1746
+ const { ctx, words } = useEnv();
1747
+ return /* @__PURE__ */ jsx(ctx.ui.Dialog, {
1748
+ open: editing !== null,
1749
+ onOpenChange: (open) => !open && onClose(),
1750
+ title: editing === "new" ? words.t("createTitle") : words.t("editTitle"),
1751
+ closeLabel: words.t("close"),
1752
+ children: editing !== null && /* @__PURE__ */ jsx(EditorBody, {
1753
+ trigger: editing === "new" ? null : editing,
1754
+ workspaceId,
1755
+ onClose
1756
+ })
1757
+ });
1758
+ }
1759
+ //#endregion
1760
+ //#region src/ui/page.tsx
1761
+ /** Pause or resume, and delete: from the list and from the detail alike. */
1762
+ function useTaskActions(trigger) {
1763
+ const { ctx, store } = useEnv();
1764
+ const pending = useSchedule((state) => !!state.pendingActions[trigger.id]);
1765
+ const fail = useFailureToast();
1766
+ const run = (call) => {
1767
+ store.runTaskAction(trigger.id, call).catch((error) => fail(error));
1768
+ };
1769
+ return {
1770
+ pending,
1771
+ toggle: () => run(() => ctx.call("trigger.setEnabled", {
1772
+ id: trigger.id,
1773
+ enabled: !trigger.enabled
1774
+ })),
1775
+ remove: () => run(() => ctx.call("trigger.remove", { id: trigger.id }))
1776
+ };
1777
+ }
1778
+ function IconAction({ label, icon, onClick, onBlur, className, pending = false }) {
1779
+ const { ctx } = useEnv();
1780
+ return /* @__PURE__ */ jsx(ctx.ui.Tooltip, {
1781
+ content: label,
1782
+ children: /* @__PURE__ */ jsx(ctx.ui.Button, {
1783
+ variant: "ghost",
1784
+ size: "sm",
1785
+ type: "button",
1786
+ "aria-label": label,
1787
+ disabled: pending,
1788
+ loading: pending,
1789
+ "aria-busy": pending,
1790
+ onClick,
1791
+ ...onBlur === void 0 ? {} : { onBlur },
1792
+ className: `sch-icon-action${className === void 0 ? "" : ` ${className}`}`,
1793
+ children: /* @__PURE__ */ jsx(ctx.ui.Icon, { name: icon })
1794
+ })
1795
+ });
1796
+ }
1797
+ function Row({ trigger, selected, onSelect }) {
1798
+ const { ctx, words } = useEnv();
1799
+ const { t, locale } = words;
1800
+ const next = useSchedule((state) => state.next[trigger.id]);
1801
+ const state = stateOf(trigger, next, words);
1802
+ const actions = useTaskActions(trigger);
1803
+ const rule = configOf(trigger.config)?.rule ?? null;
1804
+ const [confirming, setConfirming] = useState(false);
1805
+ return /* @__PURE__ */ jsxs("li", {
1806
+ "data-trigger": trigger.id,
1807
+ "data-selected": selected || void 0,
1808
+ "data-confirming": confirming || void 0,
1809
+ className: "sch-task",
1810
+ children: [
1811
+ /* @__PURE__ */ jsx(AgentFace, {
1812
+ agentId: trigger.agentId,
1813
+ size: "lg"
1814
+ }),
1815
+ /* @__PURE__ */ jsxs(ctx.ui.Button, {
1816
+ variant: "plain",
1817
+ type: "button",
1818
+ "aria-current": selected || void 0,
1819
+ onClick: onSelect,
1820
+ className: "sch-task-main",
1821
+ children: [/* @__PURE__ */ jsxs("span", {
1822
+ className: "sch-task-line",
1823
+ children: [/* @__PURE__ */ jsx("span", {
1824
+ className: "sch-task-name",
1825
+ "data-paused": !trigger.enabled || void 0,
1826
+ children: trigger.name
1827
+ }), state !== null && /* @__PURE__ */ jsx("span", {
1828
+ className: "sch-task-state",
1829
+ "data-tone": state.tone,
1830
+ children: state.text
1831
+ })]
1832
+ }), /* @__PURE__ */ jsx("span", {
1833
+ className: "sch-task-rule",
1834
+ children: [ruleText(rule, words), trigger.enabled && typeof next === "number" && rule?.kind !== "once" ? t("next", { at: when(next, locale) }) : null].filter((part) => part !== null).join(" · ")
1835
+ })]
1836
+ }),
1837
+ /* @__PURE__ */ jsxs("div", {
1838
+ "data-slot": "schedule-actions",
1839
+ className: "sch-task-actions",
1840
+ children: [/* @__PURE__ */ jsx(IconAction, {
1841
+ label: trigger.enabled ? t("pause") : t("resume"),
1842
+ icon: trigger.enabled ? "pause" : "play",
1843
+ pending: actions.pending,
1844
+ onClick: actions.toggle
1845
+ }), /* @__PURE__ */ jsx(IconAction, {
1846
+ label: confirming ? t("confirmDelete") : t("delete"),
1847
+ icon: "trash",
1848
+ pending: actions.pending,
1849
+ onClick: () => confirming ? actions.remove() : setConfirming(true),
1850
+ onBlur: () => setConfirming(false),
1851
+ className: confirming ? "sch-danger-action sch-armed" : "sch-danger-action"
1852
+ })]
1853
+ })
1854
+ ]
1855
+ });
1856
+ }
1857
+ function TaskList({ tasks, selectedId, onSelect, onCreate, hidden }) {
1858
+ const { words } = useEnv();
1859
+ const { t } = words;
1860
+ return /* @__PURE__ */ jsxs("aside", {
1861
+ "data-slot": "schedule-list",
1862
+ "aria-label": t("list"),
1863
+ className: "sch-list",
1864
+ "data-narrow-hidden": hidden || void 0,
1865
+ children: [/* @__PURE__ */ jsxs("div", {
1866
+ className: "sch-list-head",
1867
+ children: [/* @__PURE__ */ jsx("h2", { children: t("nav") }), /* @__PURE__ */ jsx(IconAction, {
1868
+ label: t("create"),
1869
+ icon: "plus",
1870
+ onClick: onCreate
1871
+ })]
1872
+ }), /* @__PURE__ */ jsx("div", {
1873
+ className: "sch-list-body",
1874
+ children: tasks.length > 0 && /* @__PURE__ */ jsx("ul", {
1875
+ className: "sch-tasks",
1876
+ children: tasks.map((trigger) => /* @__PURE__ */ jsx(Row, {
1877
+ trigger,
1878
+ selected: trigger.id === selectedId,
1879
+ onSelect: () => onSelect(trigger.id)
1880
+ }, trigger.id))
1881
+ })
1882
+ })]
1883
+ });
1884
+ }
1885
+ /** A term and what it is, as one row of the overview. */
1886
+ function Fact({ term, children }) {
1887
+ return /* @__PURE__ */ jsxs("div", {
1888
+ className: "sch-fact",
1889
+ children: [/* @__PURE__ */ jsx("dt", { children: term }), /* @__PURE__ */ jsx("dd", { children })]
1890
+ });
1891
+ }
1892
+ function ScopeLine({ item }) {
1893
+ const { ctx, words } = useEnv();
1894
+ const { t } = words;
1895
+ const icon = item.kind === "network" ? "network" : item.kind === "web-host" ? "globe" : "folder";
1896
+ return /* @__PURE__ */ jsxs("li", {
1897
+ className: "sch-scope-line",
1898
+ children: [
1899
+ /* @__PURE__ */ jsx(ctx.ui.Icon, {
1900
+ name: icon,
1901
+ className: "sch-row-icon"
1902
+ }),
1903
+ item.kind === "network" ? /* @__PURE__ */ jsx("span", {
1904
+ className: "sch-row-target",
1905
+ children: t("scopeNetwork")
1906
+ }) : /* @__PURE__ */ jsx("span", {
1907
+ className: "sch-row-target sch-mono",
1908
+ children: item.target
1909
+ }),
1910
+ (item.kind === "read" || item.kind === "write") && /* @__PURE__ */ jsx(ctx.ui.Badge, {
1911
+ size: "sm",
1912
+ tone: item.kind === "write" ? "warning" : "neutral",
1913
+ children: t(item.kind === "write" ? "scopeWrite" : "scopeRead")
1914
+ })
1915
+ ]
1916
+ });
1917
+ }
1918
+ function Runs({ trigger }) {
1919
+ const { ctx, words } = useEnv();
1920
+ const { t, locale } = words;
1921
+ const fail = useFailureToast();
1922
+ const [runs, setRuns] = useState(null);
1923
+ const [failed, setFailed] = useState(false);
1924
+ useEffect(() => {
1925
+ let live = true;
1926
+ setRuns(null);
1927
+ setFailed(false);
1928
+ const read = (first) => ctx.call("trigger.runs", { id: trigger.id }).then((answer) => live && setRuns(answer.runs)).catch((error) => {
1929
+ if (!live || !first) return;
1930
+ setFailed(true);
1931
+ fail(error);
1932
+ });
1933
+ read(true);
1934
+ const off = ctx.onCore("trigger.runChanged", () => void read(false));
1935
+ return () => {
1936
+ live = false;
1937
+ off();
1938
+ };
1939
+ }, [
1940
+ ctx,
1941
+ trigger.id,
1942
+ fail
1943
+ ]);
1944
+ if (runs === null) return failed ? null : /* @__PURE__ */ jsx("p", {
1945
+ className: "sch-muted-text",
1946
+ children: t("loading")
1947
+ });
1948
+ if (runs.length === 0) return /* @__PURE__ */ jsx("p", {
1949
+ className: "sch-muted-text",
1950
+ children: t("noRuns")
1951
+ });
1952
+ return /* @__PURE__ */ jsx("ul", {
1953
+ "data-slot": "schedule-runs",
1954
+ className: "sch-runs",
1955
+ children: runs.map((run) => /* @__PURE__ */ jsxs("li", {
1956
+ "data-run": run.id,
1957
+ className: "sch-run",
1958
+ children: [
1959
+ /* @__PURE__ */ jsx("span", {
1960
+ className: "sch-run-at sch-tabular",
1961
+ children: when(run.startedAt, locale)
1962
+ }),
1963
+ /* @__PURE__ */ jsx("span", {
1964
+ className: "sch-run-kind",
1965
+ children: t(`runKind.${run.kind}`)
1966
+ }),
1967
+ /* @__PURE__ */ jsx("span", {
1968
+ className: "sch-run-state",
1969
+ "data-state": run.state,
1970
+ children: runStateText(run, words)
1971
+ }),
1972
+ run.sessionId !== null && /* @__PURE__ */ jsx(ctx.ui.Button, {
1973
+ size: "sm",
1974
+ variant: "ghost",
1975
+ type: "button",
1976
+ onClick: () => ctx.navigation.openSession(run.sessionId),
1977
+ children: t("openSession")
1978
+ })
1979
+ ]
1980
+ }, run.id))
1981
+ });
1982
+ }
1983
+ function TaskDetail({ trigger, onEdit, onBack }) {
1984
+ const { ctx, words } = useEnv();
1985
+ const { t, locale } = words;
1986
+ const ui = ctx.ui;
1987
+ const agents = useSchedule((state) => state.agents);
1988
+ const sessions = useSchedule((state) => state.sessions);
1989
+ const tasks = useSchedule((state) => state.tasks);
1990
+ const next = useSchedule((state) => state.next[trigger.id]);
1991
+ const [confirming, setConfirming] = useState(false);
1992
+ const [tab, setTab] = useState("overview");
1993
+ const agentName = (id) => agents.find((one) => one.agentId === id)?.name ?? id;
1994
+ const state = stateOf(trigger, next, words);
1995
+ const config = configOf(trigger.config);
1996
+ const actions = useTaskActions(trigger);
1997
+ useEffect(() => setConfirming(false), [trigger.id]);
1998
+ const target = trigger.target.kind === "new-session" ? t("targetNew") : (() => {
1999
+ const { sessionId } = trigger.target;
2000
+ const session = sessions.find((one) => one.sessionId === sessionId);
2001
+ return session === void 0 ? t("targetSession") : sessionTitle(session, tasks ?? [], t("untitled"));
2002
+ })();
2003
+ const nextText = trigger.enabled && typeof next === "number" ? when(next, locale) : null;
2004
+ return /* @__PURE__ */ jsxs("div", {
2005
+ "data-slot": "schedule-detail",
2006
+ className: "sch-detail",
2007
+ children: [/* @__PURE__ */ jsx("header", {
2008
+ className: "sch-detail-head",
2009
+ children: /* @__PURE__ */ jsxs("div", {
2010
+ className: "sch-detail-title",
2011
+ children: [
2012
+ /* @__PURE__ */ jsx("span", {
2013
+ className: "sch-narrow-only",
2014
+ children: /* @__PURE__ */ jsx(ui.BackButton, {
2015
+ "aria-label": t("backToList"),
2016
+ onClick: onBack
2017
+ })
2018
+ }),
2019
+ /* @__PURE__ */ jsx(AgentFace, {
2020
+ agentId: trigger.agentId,
2021
+ size: "md"
2022
+ }),
2023
+ /* @__PURE__ */ jsxs("div", {
2024
+ className: "sch-grow",
2025
+ children: [/* @__PURE__ */ jsx("h1", { children: trigger.name }), /* @__PURE__ */ jsx("p", {
2026
+ "data-tone": state?.tone,
2027
+ children: state?.text ?? (nextText === null ? "—" : t("next", { at: nextText }))
2028
+ })]
2029
+ }),
2030
+ /* @__PURE__ */ jsxs("div", {
2031
+ className: "sch-detail-actions",
2032
+ children: [
2033
+ /* @__PURE__ */ jsx(IconAction, {
2034
+ label: trigger.enabled ? t("pause") : t("resume"),
2035
+ icon: trigger.enabled ? "pause" : "play",
2036
+ pending: actions.pending,
2037
+ onClick: actions.toggle
2038
+ }),
2039
+ /* @__PURE__ */ jsx(IconAction, {
2040
+ label: t("edit"),
2041
+ icon: "pencil",
2042
+ pending: actions.pending,
2043
+ onClick: onEdit
2044
+ }),
2045
+ confirming ? /* @__PURE__ */ jsx(ui.Button, {
2046
+ type: "button",
2047
+ variant: "ghost",
2048
+ size: "sm",
2049
+ className: "sch-danger-action sch-armed",
2050
+ onBlur: () => setConfirming(false),
2051
+ disabled: actions.pending,
2052
+ loading: actions.pending,
2053
+ "aria-busy": actions.pending,
2054
+ onClick: actions.remove,
2055
+ children: t("confirmDelete")
2056
+ }) : /* @__PURE__ */ jsx(IconAction, {
2057
+ label: t("delete"),
2058
+ icon: "trash",
2059
+ pending: actions.pending,
2060
+ onClick: () => setConfirming(true),
2061
+ className: "sch-danger-action"
2062
+ })
2063
+ ]
2064
+ })
2065
+ ]
2066
+ })
2067
+ }), /* @__PURE__ */ jsx("div", {
2068
+ className: "sch-detail-body",
2069
+ children: /* @__PURE__ */ jsxs(ui.Tabs, {
2070
+ value: tab,
2071
+ onValueChange: (value) => setTab(value),
2072
+ children: [
2073
+ /* @__PURE__ */ jsxs(ui.TabsList, {
2074
+ "aria-label": trigger.name,
2075
+ children: [/* @__PURE__ */ jsx(ui.TabsTrigger, {
2076
+ value: "overview",
2077
+ children: t("overview")
2078
+ }), /* @__PURE__ */ jsx(ui.TabsTrigger, {
2079
+ value: "runs",
2080
+ children: t("runs")
2081
+ })]
2082
+ }),
2083
+ /* @__PURE__ */ jsx(ui.TabsContent, {
2084
+ value: "overview",
2085
+ children: /* @__PURE__ */ jsxs("div", {
2086
+ className: "sch-page",
2087
+ children: [/* @__PURE__ */ jsxs("dl", {
2088
+ className: "sch-facts",
2089
+ children: [
2090
+ /* @__PURE__ */ jsx(Fact, {
2091
+ term: t("sectionTiming"),
2092
+ children: ruleText(config?.rule ?? null, words)
2093
+ }),
2094
+ /* @__PURE__ */ jsx(Fact, {
2095
+ term: t("nextRun"),
2096
+ children: nextText ?? t("noNext")
2097
+ }),
2098
+ /* @__PURE__ */ jsx(Fact, {
2099
+ term: t("lastRun"),
2100
+ children: trigger.lastRun === null ? "—" : `${when(trigger.lastRun.startedAt, locale)} · ${runStateText(trigger.lastRun, words)}`
2101
+ }),
2102
+ /* @__PURE__ */ jsx(Fact, {
2103
+ term: t("agent"),
2104
+ children: agentName(trigger.agentId)
2105
+ }),
2106
+ /* @__PURE__ */ jsx(Fact, {
2107
+ term: t("target"),
2108
+ children: target
2109
+ }),
2110
+ /* @__PURE__ */ jsx(Fact, {
2111
+ term: t("catchUp"),
2112
+ children: t(config?.catchUp === false ? "off" : "on")
2113
+ }),
2114
+ trigger.target.kind === "new-session" && /* @__PURE__ */ jsx(Fact, {
2115
+ term: t("sectionScope"),
2116
+ children: trigger.scope.length === 0 ? t("scopeNone") : /* @__PURE__ */ jsx("ul", {
2117
+ className: "sch-scope-lines",
2118
+ children: trigger.scope.map((item) => /* @__PURE__ */ jsx(ScopeLine, { item }, `${item.kind}:${item.target}`))
2119
+ })
2120
+ }),
2121
+ /* @__PURE__ */ jsx(Fact, {
2122
+ term: t("creator"),
2123
+ children: trigger.createdBy.kind === "user" ? t("byYou") : t("byAgent", { name: agentName(trigger.createdBy.agentId) })
2124
+ })
2125
+ ]
2126
+ }), /* @__PURE__ */ jsxs("section", {
2127
+ className: "sch-section",
2128
+ children: [/* @__PURE__ */ jsx("h3", { children: t("instruction") }), /* @__PURE__ */ jsx("p", {
2129
+ className: "sch-instruction",
2130
+ children: trigger.instruction
2131
+ })]
2132
+ })]
2133
+ })
2134
+ }),
2135
+ /* @__PURE__ */ jsx(ui.TabsContent, {
2136
+ value: "runs",
2137
+ children: /* @__PURE__ */ jsx("div", {
2138
+ className: "sch-page",
2139
+ children: /* @__PURE__ */ jsx(Runs, { trigger })
2140
+ })
2141
+ })
2142
+ ]
2143
+ })
2144
+ })]
2145
+ });
2146
+ }
2147
+ /** Lists the selected workspace's tasks and offers the first-task action in its full-page empty state. */
2148
+ function SchedulesPage() {
2149
+ const { ctx, store, words } = useEnv();
2150
+ const { t } = words;
2151
+ const ui = ctx.ui;
2152
+ const workspaceId = useWorkspaceId();
2153
+ const tasks = useSchedule((state) => state.tasks);
2154
+ const failed = useSchedule((state) => state.tasksFailed);
2155
+ const [editing, setEditing] = useState(null);
2156
+ const [picked, setPicked] = useState(null);
2157
+ const [backed, setBacked] = useState(false);
2158
+ useEffect(() => store.retain(), [store]);
2159
+ if (workspaceId === null) return /* @__PURE__ */ jsx("div", {
2160
+ "data-slot": "schedules-page",
2161
+ className: "sch-page-root sch-centre",
2162
+ children: /* @__PURE__ */ jsx(ui.EmptyState, {
2163
+ title: t("empty"),
2164
+ description: t("noWorkspace")
2165
+ })
2166
+ });
2167
+ const shown = (tasks ?? []).filter((one) => one.workspaceId === workspaceId);
2168
+ const current = shown.find((one) => one.id === picked) ?? (backed ? null : shown[0] ?? null);
2169
+ return /* @__PURE__ */ jsxs("div", {
2170
+ "data-slot": "schedules-page",
2171
+ className: "sch-page-root",
2172
+ children: [
2173
+ /* @__PURE__ */ jsx(TaskList, {
2174
+ tasks: shown,
2175
+ selectedId: current?.id ?? null,
2176
+ onSelect: (id) => {
2177
+ setPicked(id);
2178
+ setBacked(false);
2179
+ },
2180
+ onCreate: () => setEditing("new"),
2181
+ hidden: current !== null || shown.length === 0
2182
+ }),
2183
+ /* @__PURE__ */ jsx("div", {
2184
+ className: "sch-main",
2185
+ "data-narrow-hidden": current === null && shown.length > 0 || void 0,
2186
+ children: current !== null ? /* @__PURE__ */ jsx(TaskDetail, {
2187
+ trigger: current,
2188
+ onEdit: () => setEditing(current),
2189
+ onBack: () => {
2190
+ setPicked(null);
2191
+ setBacked(true);
2192
+ }
2193
+ }) : failed ? /* @__PURE__ */ jsx("div", {
2194
+ className: "sch-centre",
2195
+ children: /* @__PURE__ */ jsx(ui.Alert, {
2196
+ tone: "destructive",
2197
+ role: "alert",
2198
+ children: /* @__PURE__ */ jsxs("div", {
2199
+ className: "sch-failure",
2200
+ children: [/* @__PURE__ */ jsx("p", { children: t("loadFailed") }), /* @__PURE__ */ jsx(ui.Button, {
2201
+ variant: "ghost",
2202
+ type: "button",
2203
+ onClick: store.reloadTasks,
2204
+ children: t("retry")
2205
+ })]
2206
+ })
2207
+ })
2208
+ }) : /* @__PURE__ */ jsx("div", {
2209
+ className: `sch-centre${shown.length === 0 ? " sch-page-empty" : ""}`,
2210
+ children: /* @__PURE__ */ jsx(ui.EmptyState, {
2211
+ title: t("empty"),
2212
+ description: t("emptyHint"),
2213
+ variant: shown.length === 0 ? "page" : "default",
2214
+ icon: shown.length === 0 ? "calendar-clock" : void 0,
2215
+ children: /* @__PURE__ */ jsx(ui.Button, {
2216
+ variant: "primary",
2217
+ icon: "plus",
2218
+ type: "button",
2219
+ onClick: () => setEditing("new"),
2220
+ children: t("create")
2221
+ })
2222
+ })
2223
+ })
2224
+ }),
2225
+ /* @__PURE__ */ jsx(ui.StatusBarArea, { className: "sch-status-area" }),
2226
+ /* @__PURE__ */ jsx(ScheduleEditor, {
2227
+ editing,
2228
+ workspaceId,
2229
+ onClose: () => setEditing(null)
2230
+ })
2231
+ ]
2232
+ });
2233
+ }
2234
+ //#endregion
2235
+ //#region src/ui/settings.tsx
2236
+ /** The bound `src/schedule/settings.ts` holds, restated for the page because
2237
+ * the browser module imports nothing from the Node half. */
2238
+ var AGENT_LIMIT_CEILING = 1e3;
2239
+ /** How long the field stays still before a value is written. */
2240
+ var SAVE_DELAY_MS = 500;
2241
+ function failureText(_ctx, error) {
2242
+ const failure = error?.failure;
2243
+ if (failure === "offline" || failure === "authentication") return null;
2244
+ return error instanceof Error ? error.message : String(error);
2245
+ }
2246
+ function valid(limit) {
2247
+ return limit !== null && Number.isInteger(limit) && limit >= 0 && limit <= AGENT_LIMIT_CEILING;
2248
+ }
2249
+ function settingsFor(ctx) {
2250
+ return function ScheduleSettingsPanel() {
2251
+ const connection = useSyncExternalStore(ctx.host.subscribe, () => ctx.host.get().connection);
2252
+ const t = ctx.i18n.t;
2253
+ const toast = ctx.ui.useToast();
2254
+ const [draft, setDraft] = useState(void 0);
2255
+ const [readFailure, setReadFailure] = useState(null);
2256
+ const [attempt, setAttempt] = useState(0);
2257
+ const [saving, setSaving] = useState(false);
2258
+ const writes = useRef(Promise.resolve());
2259
+ const sequence = useRef(0);
2260
+ const alive = useRef(true);
2261
+ const submitted = useRef(void 0);
2262
+ const stored = useRef(void 0);
2263
+ const waiting = useRef(null);
2264
+ useEffect(() => {
2265
+ let live = true;
2266
+ setReadFailure(null);
2267
+ if (connection !== "online") return;
2268
+ ctx.invoke("getScheduleSettings", {}).then((settings) => {
2269
+ if (!live) return;
2270
+ stored.current = settings.agentLimit;
2271
+ setDraft(settings.agentLimit);
2272
+ }, (error) => {
2273
+ if (live) setReadFailure(failureText(ctx, error));
2274
+ });
2275
+ return () => {
2276
+ live = false;
2277
+ };
2278
+ }, [attempt, connection]);
2279
+ const write = (value, mounted) => {
2280
+ if (value === submitted.current || submitted.current === void 0 && value === stored.current) return;
2281
+ submitted.current = value;
2282
+ const request = ++sequence.current;
2283
+ if (mounted) setSaving(true);
2284
+ writes.current = writes.current.then(async () => {
2285
+ try {
2286
+ const settings = await ctx.invoke("setScheduleSettings", { agentLimit: value });
2287
+ stored.current = settings.agentLimit;
2288
+ } catch (error) {
2289
+ if (request === sequence.current) {
2290
+ submitted.current = void 0;
2291
+ if (mounted && alive.current && waiting.current === null && stored.current !== void 0) setDraft(stored.current);
2292
+ }
2293
+ const text = failureText(ctx, error);
2294
+ if (text !== null) toast.add({
2295
+ tone: "destructive",
2296
+ title: text
2297
+ });
2298
+ } finally {
2299
+ if (request === sequence.current && mounted && alive.current) setSaving(false);
2300
+ }
2301
+ });
2302
+ };
2303
+ useEffect(() => {
2304
+ alive.current = true;
2305
+ return () => {
2306
+ alive.current = false;
2307
+ const pending = waiting.current;
2308
+ if (pending === null) return;
2309
+ clearTimeout(pending.timer);
2310
+ waiting.current = null;
2311
+ write(pending.value, false);
2312
+ };
2313
+ }, []);
2314
+ const edit = (value) => {
2315
+ setDraft(value);
2316
+ if (waiting.current !== null) clearTimeout(waiting.current.timer);
2317
+ waiting.current = null;
2318
+ if (!valid(value)) return;
2319
+ const timer = setTimeout(() => {
2320
+ waiting.current = null;
2321
+ write(value, true);
2322
+ }, 500);
2323
+ waiting.current = {
2324
+ timer,
2325
+ value
2326
+ };
2327
+ };
2328
+ return /* @__PURE__ */ jsxs(ctx.ui.SettingsPanel, {
2329
+ title: t("creation"),
2330
+ children: [
2331
+ draft === void 0 && readFailure === null && /* @__PURE__ */ jsx("p", {
2332
+ role: "status",
2333
+ className: "sch-muted-text",
2334
+ children: t("loading")
2335
+ }),
2336
+ readFailure !== null && /* @__PURE__ */ jsx(ctx.ui.Alert, {
2337
+ tone: "destructive",
2338
+ role: "alert",
2339
+ children: /* @__PURE__ */ jsxs("div", {
2340
+ className: "schedule-error",
2341
+ children: [/* @__PURE__ */ jsx("p", { children: readFailure }), /* @__PURE__ */ jsx(ctx.ui.Button, {
2342
+ variant: "ghost",
2343
+ type: "button",
2344
+ onClick: () => setAttempt((n) => n + 1),
2345
+ children: t("retry")
2346
+ })]
2347
+ })
2348
+ }),
2349
+ draft !== void 0 && /* @__PURE__ */ jsx(ctx.ui.SettingsPanel, {
2350
+ title: t("agentLimit"),
2351
+ hint: t("agentLimitHelp"),
2352
+ level: "field",
2353
+ inline: true,
2354
+ children: /* @__PURE__ */ jsxs("div", {
2355
+ className: "schedule-control",
2356
+ children: [/* @__PURE__ */ jsxs("div", {
2357
+ className: "schedule-input-row",
2358
+ children: [/* @__PURE__ */ jsx(ctx.ui.InputNumber, {
2359
+ label: t("agentLimit"),
2360
+ incrementLabel: t("increase"),
2361
+ decrementLabel: t("decrease"),
2362
+ min: 0,
2363
+ max: AGENT_LIMIT_CEILING,
2364
+ step: 1,
2365
+ value: draft,
2366
+ onValueChange: edit
2367
+ }), /* @__PURE__ */ jsx("span", {
2368
+ className: "schedule-save-indicator",
2369
+ children: saving && /* @__PURE__ */ jsx(ctx.ui.Spinner, {
2370
+ size: "sm",
2371
+ label: t("saving")
2372
+ })
2373
+ })]
2374
+ }), !valid(draft) && /* @__PURE__ */ jsx("p", {
2375
+ className: "schedule-invalid",
2376
+ children: t("invalidLimit")
2377
+ })]
2378
+ })
2379
+ })
2380
+ ]
2381
+ });
2382
+ };
2383
+ }
2384
+ //#endregion
2385
+ //#region src/ui/store.ts
2386
+ var EMPTY = {
2387
+ tasks: null,
2388
+ tasksFailed: false,
2389
+ pendingActions: {},
2390
+ agents: [],
2391
+ sessions: [],
2392
+ next: {},
2393
+ pictures: {}
2394
+ };
2395
+ /** One list's reader: at most one read in flight and one queued behind it. */
2396
+ function reader(read) {
2397
+ let running = false;
2398
+ let again = false;
2399
+ const run = () => {
2400
+ if (running) {
2401
+ again = true;
2402
+ return;
2403
+ }
2404
+ running = true;
2405
+ read().finally(() => {
2406
+ running = false;
2407
+ if (again) {
2408
+ again = false;
2409
+ run();
2410
+ }
2411
+ });
2412
+ };
2413
+ return run;
2414
+ }
2415
+ function createScheduleStore(ctx) {
2416
+ let state = EMPTY;
2417
+ const listeners = /* @__PURE__ */ new Set();
2418
+ const inflight = /* @__PURE__ */ new Set();
2419
+ let holders = 0;
2420
+ let stop = null;
2421
+ const set = (patch) => {
2422
+ state = {
2423
+ ...state,
2424
+ ...patch
2425
+ };
2426
+ for (const listener of [...listeners]) listener();
2427
+ };
2428
+ const loadTasks = reader(() => ctx.call("trigger.list", {}).then(({ triggers }) => set({
2429
+ tasks: triggers.filter((one) => one.source === SOURCE),
2430
+ tasksFailed: false
2431
+ })).catch((error) => set({ tasksFailed: state.tasks === null && failureText$1(ctx, error) !== null })).then(() => void 0));
2432
+ const loadAgents = reader(() => ctx.call("config.agent.list", {}).then((agents) => set({ agents })).catch(() => void 0));
2433
+ const loadSessions = reader(() => ctx.call("session.list", {}).then((sessions) => set({ sessions })).catch(() => void 0));
2434
+ const loadNext = reader(() => ctx.invoke("nextRuns", {}).then(({ next }) => set({ next })).catch(() => void 0));
2435
+ const loadAll = () => {
2436
+ loadTasks();
2437
+ loadAgents();
2438
+ loadSessions();
2439
+ loadNext();
2440
+ };
2441
+ function start() {
2442
+ let connection = ctx.host.get().connection;
2443
+ const offs = [
2444
+ ctx.onCore("trigger.changed", loadTasks),
2445
+ ctx.onCore("config.agentChanged", loadAgents),
2446
+ ctx.onCore("config.agentRemoved", loadAgents),
2447
+ ctx.onCore("session.created", loadSessions),
2448
+ ctx.onCore("session.updated", loadSessions),
2449
+ ctx.on("nextRunsChanged", (event) => set({ next: event.payload.next })),
2450
+ ctx.host.subscribe(() => {
2451
+ const now = ctx.host.get().connection;
2452
+ if (now === "online" && connection !== "online") loadAll();
2453
+ connection = now;
2454
+ })
2455
+ ];
2456
+ loadAll();
2457
+ return () => {
2458
+ for (const off of offs) off();
2459
+ };
2460
+ }
2461
+ return {
2462
+ get: () => state,
2463
+ subscribe(listener) {
2464
+ listeners.add(listener);
2465
+ return () => {
2466
+ listeners.delete(listener);
2467
+ };
2468
+ },
2469
+ retain() {
2470
+ holders += 1;
2471
+ if (holders === 1) stop = start();
2472
+ let released = false;
2473
+ return () => {
2474
+ if (released) return;
2475
+ released = true;
2476
+ holders -= 1;
2477
+ if (holders === 0) {
2478
+ stop?.();
2479
+ stop = null;
2480
+ }
2481
+ };
2482
+ },
2483
+ reloadTasks: loadTasks,
2484
+ async runTaskAction(id, action) {
2485
+ if (state.pendingActions[id]) return;
2486
+ set({ pendingActions: {
2487
+ ...state.pendingActions,
2488
+ [id]: true
2489
+ } });
2490
+ try {
2491
+ await action();
2492
+ } finally {
2493
+ const pendingActions = { ...state.pendingActions };
2494
+ delete pendingActions[id];
2495
+ set({ pendingActions });
2496
+ }
2497
+ },
2498
+ requestPicture(agentId, rev) {
2499
+ if (rev in state.pictures || inflight.has(rev)) return;
2500
+ inflight.add(rev);
2501
+ ctx.call("config.agent.avatar", { agentId }).then((answer) => set({ pictures: {
2502
+ ...state.pictures,
2503
+ [rev]: answer === null ? null : `data:${answer.mediaType};base64,${answer.data}`
2504
+ } })).catch(() => set({ pictures: {
2505
+ ...state.pictures,
2506
+ [rev]: null
2507
+ } })).finally(() => inflight.delete(rev));
2508
+ }
2509
+ };
2510
+ }
2511
+ //#endregion
2512
+ //#region src/ui/index.tsx
2513
+ /** The host compares this against its own before calling `register`. */
2514
+ var runtimeVersion = 5;
2515
+ var STYLES = `
2516
+ .schedule-control { display: flex; min-width: 0; flex-direction: column; align-items: flex-end; gap: .25rem; }
2517
+ .schedule-control > * { width: 10.25rem; }
2518
+ .schedule-input-row { display: flex; align-items: center; gap: .5rem; }
2519
+ .schedule-input-row > :first-child { min-width: 0; width: 9rem; }
2520
+ .schedule-save-indicator { display: inline-flex; width: .75rem; flex: none; }
2521
+ .schedule-invalid { font-size: .75rem; color: var(--destructive); text-align: end; }
2522
+ .schedule-error, .sch-failure { display: flex; min-width: 0; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: .5rem; }
2523
+
2524
+ .sch-page-root { display: grid; grid-template-columns: 18rem minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) auto; height: 100%; min-height: 0; width: 100%; font-size: .875rem; }
2525
+ .sch-centre { display: flex; min-height: 0; flex: 1; align-items: center; justify-content: center; padding: 0 2rem; }
2526
+ .sch-page-empty { padding: 0; }
2527
+ .sch-list { grid-column: 1; grid-row: 1 / span 2; z-index: 10; display: flex; height: 100%; width: 18rem; flex-shrink: 0; flex-direction: column; border-inline-end: 1px solid var(--border); background: var(--background); }
2528
+ .sch-list-head { display: flex; height: 3.5rem; flex-shrink: 0; align-items: center; justify-content: space-between; gap: .75rem; padding: 0 .75rem; }
2529
+ .sch-list-head h2 { margin: 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .875rem; font-weight: 600; line-height: 1.25rem; }
2530
+ .sch-list-body { min-height: 0; flex: 1; overflow-y: auto; padding: 0 .75rem .5rem; }
2531
+ .sch-tasks { display: flex; flex-direction: column; gap: .25rem; margin: 0; padding: 0; list-style: none; }
2532
+ .sch-task { --row-fill: var(--background); position: relative; display: flex; align-items: center; gap: .625rem; overflow: hidden; padding: .5rem; border-radius: var(--radius-control); transition: background-color 150ms ease; }
2533
+ .sch-task:hover { --row-fill: var(--muted); background: var(--muted); }
2534
+ .sch-task[data-selected] { --row-fill: var(--accent); background: var(--accent); }
2535
+ .sch-task-main { display: flex; min-width: 0; flex: 1; flex-direction: column; align-items: stretch; text-align: start; outline: none; }
2536
+ .sch-task-line { display: flex; min-width: 0; align-items: baseline; gap: .5rem; }
2537
+ .sch-task-name { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1.25rem; color: var(--foreground); }
2538
+ .sch-task-name[data-paused] { color: var(--muted-foreground); }
2539
+ .sch-task-state { flex-shrink: 0; font-size: .75rem; color: var(--muted-foreground); }
2540
+ .sch-task-state[data-tone=destructive] { color: var(--destructive); }
2541
+ .sch-task-rule { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .75rem; line-height: 1.25rem; color: var(--muted-foreground); }
2542
+ .sch-task-actions { pointer-events: none; position: absolute; inset-block: 0; inset-inline-end: 0; display: flex; align-items: center; padding-inline: 4rem .5rem; background: linear-gradient(to right, transparent, var(--row-fill) 1.75rem); opacity: 0; transition: opacity 150ms ease; }
2543
+ .sch-task-actions > * { pointer-events: auto; }
2544
+ .sch-task:is(:hover, :focus-within, [data-confirming]) .sch-task-actions { opacity: 1; }
2545
+ @media (hover: none) { .sch-task-actions { opacity: 1; } }
2546
+ .sch-icon-action { aspect-ratio: 1; padding: 0; color: var(--muted-foreground); }
2547
+ .sch-icon-action:hover { color: var(--foreground); }
2548
+ .sch-danger-action:hover, .sch-armed { color: var(--destructive); }
2549
+
2550
+ .sch-main { grid-column: 2; grid-row: 1; position: relative; display: flex; height: 100%; min-height: 0; min-width: 0; flex: 1; flex-direction: column; }
2551
+ .sch-status-area { grid-column: 2; grid-row: 2; }
2552
+ .sch-detail { display: flex; min-height: 0; min-width: 0; flex: 1; flex-direction: column; }
2553
+ .sch-detail-head { flex-shrink: 0; padding: 0 1rem; border-bottom: 1px solid var(--border); background: var(--background); }
2554
+ .sch-detail-title { display: flex; height: 4rem; align-items: center; gap: .75rem; }
2555
+ .sch-detail-title h1 { margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 1rem; font-weight: 500; }
2556
+ .sch-detail-title p { margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .75rem; color: var(--muted-foreground); }
2557
+ .sch-detail-title p[data-tone=destructive] { color: var(--destructive); }
2558
+ .sch-detail-actions { display: flex; flex-shrink: 0; align-items: center; gap: .25rem; }
2559
+ .sch-detail-body { min-height: 0; flex: 1; overflow-y: auto; padding: .75rem 1rem 0; }
2560
+ .sch-page { margin: 0 auto; display: flex; width: 100%; max-width: 48rem; flex-direction: column; gap: 2rem; padding: 1.5rem .5rem; }
2561
+ .sch-facts { display: flex; flex-direction: column; margin: 0; }
2562
+ .sch-fact { display: grid; gap: .25rem 1rem; padding: .5rem 0; border-bottom: 1px solid var(--border); }
2563
+ .sch-fact:last-child { border-bottom: 0; }
2564
+ .sch-fact dt { color: var(--muted-foreground); }
2565
+ .sch-fact dd { min-width: 0; margin: 0; color: var(--foreground); }
2566
+ @media (min-width: 640px) { .sch-fact { grid-template-columns: 7rem minmax(0, 1fr); } }
2567
+ .sch-section { display: flex; min-width: 0; flex-direction: column; gap: .5rem; }
2568
+ .sch-section h3 { margin: 0; font-size: .875rem; font-weight: 600; }
2569
+ .sch-instruction { margin: 0; white-space: pre-wrap; padding: .5rem .75rem; border-radius: var(--radius-control); background: var(--muted); line-height: 1.5rem; }
2570
+ .sch-scope-lines { display: flex; flex-direction: column; gap: .375rem; margin: 0; padding: 0; list-style: none; }
2571
+ .sch-scope-line { display: flex; min-width: 0; align-items: center; gap: .5rem; }
2572
+ .sch-runs { display: flex; flex-direction: column; margin: 0; padding: 0; list-style: none; }
2573
+ .sch-run { display: flex; align-items: center; gap: .75rem; padding: .5rem 0; border-bottom: 1px solid var(--border); }
2574
+ .sch-run:last-child { border-bottom: 0; }
2575
+ .sch-run-at { width: 11rem; flex-shrink: 0; color: var(--muted-foreground); }
2576
+ .sch-run-kind { width: 4rem; flex-shrink: 0; color: var(--muted-foreground); }
2577
+ .sch-run-state { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2578
+ .sch-run-state[data-state=failed] { color: var(--destructive); }
2579
+ .sch-narrow-only { display: none; }
2580
+ @media (max-width: 767px) {
2581
+ .sch-page-root { grid-template-columns: minmax(0, 1fr); }
2582
+ .sch-list { grid-column: 1; grid-row: 1; width: 100%; }
2583
+ .sch-main { grid-column: 1; }
2584
+ .sch-status-area { grid-column: 1; }
2585
+ .sch-list[data-narrow-hidden], .sch-main[data-narrow-hidden] { display: none; }
2586
+ .sch-narrow-only { display: contents; }
2587
+ }
2588
+
2589
+ :scope[data-slot="dialog-content"]:has(.sch-path-form) { width: 32rem; }
2590
+ .sch-editor { display: flex; min-width: 0; flex-direction: column; gap: 1rem; }
2591
+ .sch-panel, .sch-stack { display: flex; min-width: 0; flex-direction: column; gap: 1rem; padding-top: .75rem; }
2592
+ .sch-stack { padding-top: 0; }
2593
+ .sch-tab-mark { display: inline-block; width: .375rem; height: .375rem; margin-inline-start: .375rem; border-radius: 999px; background: var(--destructive); vertical-align: middle; }
2594
+ .sch-editor-foot { display: flex; align-items: center; gap: .75rem; padding-top: 1rem; border-top: 1px solid var(--border); }
2595
+ .sch-foot-actions, .sch-foot { display: flex; flex-shrink: 0; justify-content: flex-end; gap: .5rem; margin-inline-start: auto; }
2596
+ .sch-grow { min-width: 0; flex: 1; }
2597
+ .sch-inline { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
2598
+ .sch-select, .sch-full-width { width: 100%; }
2599
+ .sch-agent-option { display: inline-flex; min-width: 0; max-width: 100%; align-items: center; gap: .5rem; vertical-align: middle; }
2600
+ .sch-agent-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2601
+ .sch-date-time { display: flex; flex-wrap: wrap; gap: .5rem; }
2602
+ .sch-date-time > button { flex: 1 1 10rem; }
2603
+ .sch-number { width: 8rem; }
2604
+ .sch-unit { width: 6rem; }
2605
+ .sch-preview { display: grid; gap: 0 1rem; font-size: .75rem; line-height: 1.25rem; }
2606
+ @media (min-width: 640px) { .sch-preview { grid-template-columns: 7rem minmax(0, 1fr); } }
2607
+ @media (max-width: 639px) { .sch-preview-term { display: none; } }
2608
+ .sch-preview-list { display: flex; flex-direction: column; margin: 0; padding: 0; list-style: none; color: var(--foreground); }
2609
+ .sch-scope-list { display: flex; min-width: 0; flex-direction: column; gap: .5rem; }
2610
+ .sch-scope-head { display: flex; align-items: center; justify-content: space-between; gap: .5rem; }
2611
+ .sch-rows { display: flex; flex-direction: column; gap: .125rem; margin: 0 -.75rem; padding: 0; list-style: none; }
2612
+ .sch-row { display: flex; min-width: 0; align-items: center; gap: .75rem; padding: .375rem .75rem; border-radius: var(--radius-control); }
2613
+ .sch-row:hover { background: var(--muted); }
2614
+ .sch-row-icon { width: 1rem; height: 1rem; flex-shrink: 0; color: var(--muted-foreground); }
2615
+ .sch-row-target { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2616
+ .sch-row-action { aspect-ratio: 1; padding: 0; color: var(--muted-foreground); opacity: 0; transition: opacity 150ms ease; }
2617
+ .sch-row:is(:hover, :focus-within) .sch-row-action { opacity: 1; }
2618
+ .sch-row-action:hover { color: var(--destructive); }
2619
+ @media (hover: none) { .sch-row-action { opacity: 1; } }
2620
+
2621
+ .sch-mono { font-family: var(--font-mono, ui-monospace, monospace); font-size: .75rem; }
2622
+ .sch-muted-text { margin: 0; font-size: .75rem; line-height: 1.6; color: var(--muted-foreground); }
2623
+ .sch-danger { margin: 0; font-size: .75rem; color: var(--destructive); }
2624
+ .sch-tabular { font-variant-numeric: tabular-nums; }
2625
+ `;
2626
+ /** Registers the page, the settings category and their scoped presentation. */
2627
+ var register = (ctx) => {
2628
+ registerMetadata(ctx);
2629
+ ctx.i18n.register(CATALOGUES$1, "en-US");
2630
+ ctx.styles.add(STYLES);
2631
+ const env = envOf(ctx, createScheduleStore(ctx));
2632
+ ctx.slots.register("shell.nav.page", {
2633
+ id: "schedules",
2634
+ order: 10,
2635
+ label: () => ctx.i18n.t("nav"),
2636
+ icon: "calendar-clock",
2637
+ component: function SchedulesNavPage() {
2638
+ return /* @__PURE__ */ jsx(EnvProvider, {
2639
+ value: env,
2640
+ children: /* @__PURE__ */ jsx(SchedulesPage, {})
2641
+ });
2642
+ }
2643
+ });
2644
+ ctx.slots.register("shell.settings.category", {
2645
+ id: "schedule",
2646
+ label: () => ctx.i18n.t("heading"),
2647
+ region: "preset",
2648
+ order: 65,
2649
+ icon: "clock",
2650
+ component: settingsFor(ctx)
2651
+ });
2652
+ };
2653
+ //#endregion
2654
+ export { SAVE_DELAY_MS, register, runtimeVersion };