ai-agentmanager 1.46.0 → 1.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +79 -0
- package/package.json +1 -1
- package/public/app.js +51 -4
- package/public/index.html +9 -0
- package/public/keys.js +4 -2
- package/public/plan.js +323 -0
- package/public/style.css +87 -2
- package/public/system.js +151 -0
- package/public/today.js +102 -2
- package/src/calendar.js +385 -0
- package/src/cli.js +113 -0
- package/src/config.js +4 -0
- package/src/debt.js +276 -0
- package/src/decisions.js +188 -0
- package/src/milestones.js +282 -0
- package/src/notify.js +1 -0
- package/src/server.js +107 -3
- package/src/system.js +239 -0
- package/src/today.js +3 -1
package/public/today.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// Today: what needs you, from every list, most pressing first: agents stopped at a prompt or
|
|
2
2
|
// waiting for an answer, issues and pull requests ready for your review, what's asked of you
|
|
3
3
|
// (by due date), new Jira issues, and the rest. Each says why it's here, and the common
|
|
4
|
-
// decisions are a click (or a key) away. Listen reads the top of it aloud.
|
|
4
|
+
// decisions are a click (or a key) away. Listen reads the top of it aloud. With your calendar
|
|
5
|
+
// connected, the day is laid out on top: meetings, the free time between them with what needs you
|
|
6
|
+
// placed in it, and what each meeting is about.
|
|
5
7
|
|
|
6
8
|
import { listenHtml } from './speak.js';
|
|
7
9
|
import { holdWhilePicking, rowKeys } from './rowkeys.js';
|
|
@@ -10,7 +12,7 @@ import { expandButton, expandable } from './expand.js';
|
|
|
10
12
|
// Up to this score an item is pressing: it counts on the button.
|
|
11
13
|
const PRESSING = 32;
|
|
12
14
|
|
|
13
|
-
export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions, openIssues, openReviews, openBugs, openChanges, openEval, toast }) {
|
|
15
|
+
export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions, openIssues, openReviews, openBugs, openChanges, openEval, openPlan, toast }) {
|
|
14
16
|
const dialog = $('#today-dialog');
|
|
15
17
|
const body = $('#today-body');
|
|
16
18
|
let data = null;
|
|
@@ -22,6 +24,8 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
|
|
|
22
24
|
let editing = null; // the question whose draft answer is being edited
|
|
23
25
|
let replying = null; // the item a reply or send-back box is open on
|
|
24
26
|
const drafts = new Map(); // typed text per item, kept across redraws
|
|
27
|
+
let calOpen = false; // the calendar's settings are showing
|
|
28
|
+
let calDraft = {}; // what's typed in them, kept across redraws
|
|
25
29
|
|
|
26
30
|
async function load({ quiet = false, fresh = false } = {}) {
|
|
27
31
|
if (loading) return;
|
|
@@ -61,6 +65,7 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
|
|
|
61
65
|
if (it.kind === 'pr-requested') return [btn('review', 'Review it', 'A reviewer agent reads it and finds what blocks approval (a)', true), link(it.url, 'PR')].join(' ');
|
|
62
66
|
if (it.kind === 'pr-ready') return [btn('open-reviews', 'Open review', 'Pick what to post (Enter)', true), link(it.url, 'PR')].join(' ');
|
|
63
67
|
if (it.kind === 'rule') return btn('inbox', 'Inbox', 'Decide in the inbox (Enter)', true);
|
|
68
|
+
if (it.kind === 'milestone') return btn('plan', 'Checklist', 'What is open for this date, and its reminders (Enter)', true);
|
|
64
69
|
if (it.kind === 'eval') return [btn('gaps', 'Close the gaps', 'Send what is pending to the agent, to bring it to 100% (a)', true), btn('eval', 'Eval', 'What was run and verified, and what is pending (Enter)'), btn('done', 'Seen', 'Off the list until its confidence changes (d)'), btn('open', 'Open', "Open the agent's session")].join(' ');
|
|
65
70
|
if (it.kind === 'bench') return [btn('fix', 'Ask to fix', 'Ask the agent to make it as fast as before, or say why it can\'t be (a)', true), btn('done', "It's fine", 'The slowdown is expected: off the list (d)'), btn('open', 'Open', "Open the agent's session (Enter)")].join(' ');
|
|
66
71
|
if (it.kind === 'bug-pr') return [link(it.url, 'Open PR'), btn('done', 'Done', 'You looked at it: off the list (d)'), btn('bugs', 'Details', 'The bug and how the fix was checked (Enter)')].join(' ');
|
|
@@ -93,12 +98,62 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
|
|
|
93
98
|
</tr>`;
|
|
94
99
|
}
|
|
95
100
|
|
|
101
|
+
const hm = (ms) => new Date(ms).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
|
|
102
|
+
const dur = (m) => (m >= 60 ? `${Math.floor(m / 60)}h${m % 60 ? ` ${m % 60}m` : ''}` : `${m}m`);
|
|
103
|
+
|
|
104
|
+
/** The calendar's settings: its private iCal address (never shown back) and the working day. */
|
|
105
|
+
function calForm(d) {
|
|
106
|
+
if (!calOpen) return '';
|
|
107
|
+
return `<form class="today-cal" data-day-form autocomplete="off">
|
|
108
|
+
<input name="ics" value="${esc(calDraft.ics ?? '')}" placeholder="${d.connected ? 'Add another calendar: its private iCal address' : "Your calendar's private iCal address (https://… .ics)"}" aria-label="The calendar's private iCal address" />
|
|
109
|
+
<label class="hint">Working day <input type="time" name="workStart" value="${esc(calDraft.workStart ?? d.workStart ?? '09:00')}" /> to <input type="time" name="workEnd" value="${esc(calDraft.workEnd ?? d.workEnd ?? '18:00')}" /></label>
|
|
110
|
+
<button class="small primary">Save</button>
|
|
111
|
+
${d.connected ? '<button type="button" class="small" data-day="disconnect" title="Forget the calendar addresses">Disconnect</button>' : ''}
|
|
112
|
+
<button type="button" class="small" data-day="settings">Cancel</button>
|
|
113
|
+
<p class="hint">Google Calendar: Settings → your calendar → Integrate calendar → <b>Secret address in iCal format</b>. Outlook: Settings → Calendar → Shared calendars → Publish a calendar → <b>ICS</b>. It gives read access only, is kept in config.json on this computer, and isn't shown here again.</p>
|
|
114
|
+
</form>`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The day on top of the list: meetings, and the free time with what needs you placed in it. */
|
|
118
|
+
function dayHtml() {
|
|
119
|
+
const d = data.day;
|
|
120
|
+
if (!d) return '';
|
|
121
|
+
if (!d.connected) return `<div class="today-day"><div class="today-day-head"><span class="hint">Plan the day around your meetings: connect your calendar, and what needs you is fitted into the free time between them.</span><span class="spacer"></span><button class="small" data-day="settings">Connect calendar</button></div>${calForm(d)}</div>`;
|
|
122
|
+
const gear = '<button class="small" data-day="settings" title="Calendar addresses and working hours">Calendar…</button>';
|
|
123
|
+
if (d.error || !d.meetings) return `<div class="today-day"><div class="today-day-head"><span class="hint">Couldn't plan the day: ${esc(d.error ?? 'the calendar could not be read')}</span><span class="spacer"></span>${gear}</div>${calForm(d)}</div>`;
|
|
124
|
+
const bad = (d.sources ?? []).filter((s) => s.error);
|
|
125
|
+
const rel = (r) => (r.kind === 'agent' ? `<button class="link" data-day-agent="${esc(r.agentId)}" title="${esc(r.why)}: open its session">${esc(r.title)}</button>` : `<button class="link" data-day-item="${esc(r.id)}" title="${esc(r.why)}: show it in the list">${esc(r.title)}</button>`);
|
|
126
|
+
const rows = [
|
|
127
|
+
...d.meetings.filter((m) => !m.past).map((m) => ({ at: m.start, html: `<li class="day-meeting${m.now ? ' now' : ''}${m.free ? ' free' : ''}"><span class="day-time">${esc(hm(m.start))} – ${esc(hm(m.end))}</span><span class="day-what"><b>${esc(m.title)}</b>${m.now ? ' <span class="tag">now</span>' : ''}${m.location ? ` <span class="hint">· ${esc(m.location)}</span>` : ''}${m.related.length ? `<div class="hint">About: ${m.related.map(rel).join(' · ')}</div>` : ''}</span></li>` })),
|
|
128
|
+
...d.blocks.map((b) => ({ at: b.start, html: `<li class="day-free"><span class="day-time">${esc(hm(b.start))} – ${esc(hm(b.end))}</span><span class="day-what"><span class="day-free-label">Free ${esc(dur(b.minutes))}</span>${b.items.length ? `<ol>${b.items.map((i) => `<li><button class="link" data-day-item="${esc(i.id)}" title="Show it in the list">${esc(i.label)}: ${esc(i.title)}</button> <span class="hint">${i.minutes}m</span></li>`).join('')}</ol>` : ' <span class="hint">nothing waiting for it</span>'}</span></li>` })),
|
|
129
|
+
].sort((x, y) => x.at - y.at);
|
|
130
|
+
const busy = d.meetings.filter((m) => !m.free).length;
|
|
131
|
+
const summary = [
|
|
132
|
+
busy ? `${busy} meeting${busy === 1 ? '' : 's'} today (${dur(d.meetingMinutes)})` : 'No meetings today',
|
|
133
|
+
d.freeMinutes ? `${dur(d.freeMinutes)} free until ${esc(d.workEnd)}` : 'no free time left today',
|
|
134
|
+
d.needMinutes ? `what needs you: about ${dur(d.needMinutes)}` : null,
|
|
135
|
+
d.unplaced ? `<b>${d.unplaced} won't fit today</b>` : null,
|
|
136
|
+
].filter(Boolean).join(' · ');
|
|
137
|
+
const next = d.current ? `In <b>${esc(d.current)}</b> now` : d.next ? `Next: <b>${esc(d.next.title)}</b> ${d.next.inMinutes <= 90 ? `in ${d.next.inMinutes} min` : `at ${esc(hm(d.next.start))}`}` : '';
|
|
138
|
+
return `<div class="today-day">
|
|
139
|
+
<div class="today-day-head"><b>Your day</b><span class="hint">${summary}${next ? ` · ${next}` : ''}</span><span class="spacer"></span>${gear}</div>
|
|
140
|
+
${d.allDay?.length ? `<div class="hint">All day: ${esc(d.allDay.join(', '))}</div>` : ''}
|
|
141
|
+
${bad.length ? `<div class="hint">Couldn't read ${esc(bad.map((s) => `${s.name} (${s.error})`).join(', '))}: showing what was read last.</div>` : ''}
|
|
142
|
+
${rows.length ? `<ul class="day-rows">${rows.map((r) => r.html).join('')}</ul>` : ''}
|
|
143
|
+
${calForm(d)}
|
|
144
|
+
</div>`;
|
|
145
|
+
}
|
|
146
|
+
|
|
96
147
|
function draw() {
|
|
97
148
|
if (!dialog.open) return;
|
|
98
149
|
if (!data) {
|
|
99
150
|
body.innerHTML = '<p class="hint">Loading…</p>';
|
|
100
151
|
return;
|
|
101
152
|
}
|
|
153
|
+
// What's typed in the calendar's settings survives the list being drawn again.
|
|
154
|
+
const cf = body.querySelector('[data-day-form]');
|
|
155
|
+
const calFocus = cf && document.activeElement?.form === cf ? document.activeElement.name : null;
|
|
156
|
+
if (cf) calDraft = Object.fromEntries(new FormData(cf));
|
|
102
157
|
const items = data.items;
|
|
103
158
|
const pressing = items.filter((i) => i.score <= PRESSING).length;
|
|
104
159
|
const off = [!data.features?.jira && 'Jira', !data.features?.slack && !data.features?.gemini && 'Actions'].filter(Boolean);
|
|
@@ -112,15 +167,31 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
|
|
|
112
167
|
${expandButton(dialog)}
|
|
113
168
|
<button class="small" data-today="close" title="Close (Esc)">Close</button>
|
|
114
169
|
</div>
|
|
170
|
+
${dayHtml()}
|
|
115
171
|
${items.length
|
|
116
172
|
? `<div class="issues-scroll"><table class="issues today-table"><tbody>${items.map(row).join('')}</tbody></table></div>`
|
|
117
173
|
: '<p class="hint issues-empty">Nothing needs you right now: no agent is waiting on you, nothing is due, and no review is waiting.</p>'}
|
|
118
174
|
${asideHtml()}
|
|
119
175
|
<p class="hint">Keys: j/k move (or click a row), Enter opens, 1–6 pick an answer, a assign or review, d done, s skip, z snooze, c discuss, u undo, r look again, f bigger.${off.length ? ` Not included (off in Settings → What you use): ${esc(off.join(', '))}.` : ''}${data.errors?.length ? ` Couldn't get: ${esc(data.errors.map((e) => `${e.source === 'jira' ? 'Jira' : e.source} (${e.error})`).join('; '))}.` : ''}</p>`;
|
|
176
|
+
if (calFocus) body.querySelector(`[data-day-form] [name="${calFocus}"]`)?.focus();
|
|
120
177
|
keys.redraw();
|
|
121
178
|
}
|
|
122
179
|
const render = holdWhilePicking(body, draw);
|
|
123
180
|
|
|
181
|
+
/** Save the calendar's settings: a new address is checked by the daemon before it is kept. */
|
|
182
|
+
async function saveCalendar(form) {
|
|
183
|
+
const f = Object.fromEntries(new FormData(form));
|
|
184
|
+
try {
|
|
185
|
+
await api('PUT', '/calendar', { ...(f.ics?.trim() ? { add: f.ics.trim() } : {}), workStart: f.workStart, workEnd: f.workEnd });
|
|
186
|
+
calOpen = false;
|
|
187
|
+
calDraft = {};
|
|
188
|
+
toast?.(f.ics?.trim() ? 'Calendar connected' : 'Working hours saved', 2500);
|
|
189
|
+
} catch (err) {
|
|
190
|
+
return toast?.(err.message, 7000);
|
|
191
|
+
}
|
|
192
|
+
load();
|
|
193
|
+
}
|
|
194
|
+
|
|
124
195
|
/** What you skipped, marked done or removed: each can be brought back, or all of them. */
|
|
125
196
|
function asideHtml() {
|
|
126
197
|
const aside = data?.aside ?? [];
|
|
@@ -207,6 +278,10 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
|
|
|
207
278
|
dialog.close();
|
|
208
279
|
return openAgent(it.agentId);
|
|
209
280
|
}
|
|
281
|
+
if (what === 'plan' || (what === 'enter' && it.kind === 'milestone')) {
|
|
282
|
+
dialog.close();
|
|
283
|
+
return openPlan?.('dates');
|
|
284
|
+
}
|
|
210
285
|
if (what === 'inbox' || (what === 'enter' && it.kind === 'rule')) {
|
|
211
286
|
dialog.close();
|
|
212
287
|
return showInbox();
|
|
@@ -350,6 +425,8 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
|
|
|
350
425
|
e.preventDefault();
|
|
351
426
|
// Done typing: the list may be drawn again.
|
|
352
427
|
document.activeElement?.blur?.();
|
|
428
|
+
const cal = e.target.closest('[data-day-form]');
|
|
429
|
+
if (cal) return saveCalendar(cal);
|
|
353
430
|
const f = e.target.closest('[data-today-form]');
|
|
354
431
|
const ed = e.target.closest('[data-today-edit]');
|
|
355
432
|
try {
|
|
@@ -391,6 +468,29 @@ export function initToday({ api, $, esc, ago, openAgent, showInbox, openActions,
|
|
|
391
468
|
}
|
|
392
469
|
return load();
|
|
393
470
|
}
|
|
471
|
+
const day = e.target.closest('[data-day]')?.dataset.day;
|
|
472
|
+
if (day === 'settings') {
|
|
473
|
+
calOpen = !calOpen;
|
|
474
|
+
calDraft = {};
|
|
475
|
+
return draw();
|
|
476
|
+
}
|
|
477
|
+
if (day === 'disconnect') {
|
|
478
|
+
await api('PUT', '/calendar', { ics: [] }).catch((err) => toast?.(err.message, 6000));
|
|
479
|
+
calOpen = false;
|
|
480
|
+
return load();
|
|
481
|
+
}
|
|
482
|
+
const dayAgent = e.target.closest('[data-day-agent]')?.dataset.dayAgent;
|
|
483
|
+
if (dayAgent) {
|
|
484
|
+
dialog.close();
|
|
485
|
+
return openAgent(dayAgent);
|
|
486
|
+
}
|
|
487
|
+
const dayItem = e.target.closest('[data-day-item]')?.dataset.dayItem;
|
|
488
|
+
if (dayItem) {
|
|
489
|
+
const tr = [...body.querySelectorAll('tr[data-row-id]')].find((r) => r.dataset.rowId === dayItem);
|
|
490
|
+
tr?.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
|
491
|
+
tr?.classList.add('day-flash');
|
|
492
|
+
return setTimeout(() => tr?.classList.remove('day-flash'), 1600);
|
|
493
|
+
}
|
|
394
494
|
const pick = e.target.closest('[data-today-pick]');
|
|
395
495
|
if (pick) return pickAt(itemOf(e.target.closest('tr[data-row-id]')?.dataset.rowId), Number(pick.dataset.todayPick));
|
|
396
496
|
const b = e.target.closest('[data-today]')?.dataset.today;
|
package/src/calendar.js
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// Calendar-aware day: your meetings today, the free time between them, and what needs you fitted
|
|
2
|
+
// into that time, most pressing first; and for each meeting, the agents, pull requests and issues
|
|
3
|
+
// it is about. The calendar is read from its private iCal address (Google, Outlook and Apple
|
|
4
|
+
// calendars all have one), which only gives read access. Nothing is written to it, and nothing
|
|
5
|
+
// about it leaves this computer.
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
|
|
9
|
+
const MIN = 60_000;
|
|
10
|
+
const DAY = 86_400_000;
|
|
11
|
+
const CACHE_MS = 10 * MIN;
|
|
12
|
+
export const CALENDAR_DEFAULTS = { ics: [], workStart: '09:00', workEnd: '18:00' };
|
|
13
|
+
const WEEKDAYS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
|
|
14
|
+
/** Minutes a thing that needs you usually takes, by its kind in Today. */
|
|
15
|
+
const MINUTES = { prompt: 3, waiting: 5, question: 5, ask: 10, rule: 2, reminder: 10, stuck: 10, conflict: 10, review: 15, issue: 10, 'issue-review': 20, 'issue-new': 10, action: 20, 'pr-review': 25, 'pr-requested': 25, 'pr-ready': 5, bug: 15, 'bug-pr': 15, eval: 10, bench: 10, milestone: 10 };
|
|
16
|
+
const err = (status, message) => Object.assign(new Error(message), { status });
|
|
17
|
+
const clip = (s, n) => {
|
|
18
|
+
const t = String(s ?? '').replace(/\s+/g, ' ').trim();
|
|
19
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
20
|
+
};
|
|
21
|
+
const dayNum = (y, m, d) => Math.round(Date.UTC(y, m - 1, d) / DAY);
|
|
22
|
+
const fromDayNum = (n) => {
|
|
23
|
+
const d = new Date(n * DAY);
|
|
24
|
+
return { y: d.getUTCFullYear(), m: d.getUTCMonth() + 1, d: d.getUTCDate() };
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** How far a time zone is ahead of UTC at an instant, in ms. */
|
|
28
|
+
function tzOffset(utcMs, tz) {
|
|
29
|
+
const p = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: tz, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).formatToParts(new Date(utcMs)).map((x) => [x.type, Number(x.value)]));
|
|
30
|
+
return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - Math.floor(utcMs / 1000) * 1000;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A wall-clock time ({ y, m, d, h, mi, s }) in a zone ("utc", an IANA name, or null for this computer's) as ms. */
|
|
34
|
+
export function wallToMs(w, tz) {
|
|
35
|
+
const guess = Date.UTC(w.y, w.m - 1, w.d, w.h ?? 0, w.mi ?? 0, w.s ?? 0);
|
|
36
|
+
if (tz === 'utc') return guess;
|
|
37
|
+
if (tz) {
|
|
38
|
+
try {
|
|
39
|
+
const t = guess - tzOffset(guess, tz);
|
|
40
|
+
return guess - tzOffset(t, tz);
|
|
41
|
+
} catch {
|
|
42
|
+
// A zone name this runtime doesn't know (some calendars use their own): this computer's time.
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return new Date(w.y, w.m - 1, w.d, w.h ?? 0, w.mi ?? 0, w.s ?? 0).getTime();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** "20261113T170000Z", "20261113T090000" or "20261113": { w, tz, allDay }. */
|
|
49
|
+
function parseTime(value, params = {}) {
|
|
50
|
+
const m = String(value).trim().match(/^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})?(Z)?)?$/);
|
|
51
|
+
if (!m) return null;
|
|
52
|
+
const allDay = !m[4];
|
|
53
|
+
return { w: { y: Number(m[1]), m: Number(m[2]), d: Number(m[3]), h: Number(m[4] ?? 0), mi: Number(m[5] ?? 0), s: Number(m[6] ?? 0) }, tz: m[7] ? 'utc' : params.TZID ?? null, allDay };
|
|
54
|
+
}
|
|
55
|
+
const wallKey = (w, allDay) => `${w.y}${String(w.m).padStart(2, '0')}${String(w.d).padStart(2, '0')}${allDay ? '' : `T${String(w.h).padStart(2, '0')}${String(w.mi).padStart(2, '0')}`}`;
|
|
56
|
+
|
|
57
|
+
/** "PT1H30M", "P1D": ms. */
|
|
58
|
+
function durationMs(v) {
|
|
59
|
+
const m = String(v).match(/^([+-])?P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/);
|
|
60
|
+
if (!m) return 0;
|
|
61
|
+
return (m[1] === '-' ? -1 : 1) * ((Number(m[2] ?? 0) * 7 + Number(m[3] ?? 0)) * DAY + Number(m[4] ?? 0) * 60 * MIN + Number(m[5] ?? 0) * MIN + Number(m[6] ?? 0) * 1000);
|
|
62
|
+
}
|
|
63
|
+
const unescapeText = (s) => String(s ?? '').replace(/\\n/gi, '\n').replace(/\\([,;\\])/g, '$1');
|
|
64
|
+
|
|
65
|
+
/** The events of an iCalendar file, as written (recurring ones not yet spread over their dates). */
|
|
66
|
+
export function parseIcs(text) {
|
|
67
|
+
// A line that starts with a space or tab continues the one before.
|
|
68
|
+
const lines = String(text ?? '').replace(/\r\n/g, '\n').replace(/\n[ \t]/g, '').split('\n');
|
|
69
|
+
const events = [];
|
|
70
|
+
let cur = null;
|
|
71
|
+
let depth = 0; // inside VALARM and the like: not the event's own lines
|
|
72
|
+
for (const line of lines) {
|
|
73
|
+
if (line === 'BEGIN:VEVENT') {
|
|
74
|
+
cur = { exdates: [] };
|
|
75
|
+
depth = 0;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (!cur) continue;
|
|
79
|
+
if (line.startsWith('BEGIN:')) {
|
|
80
|
+
depth++;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (line.startsWith('END:') && line !== 'END:VEVENT') {
|
|
84
|
+
depth--;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (line === 'END:VEVENT') {
|
|
88
|
+
if (cur.start) events.push(cur);
|
|
89
|
+
cur = null;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (depth) continue;
|
|
93
|
+
const at = line.indexOf(':');
|
|
94
|
+
if (at < 0) continue;
|
|
95
|
+
const [name, ...ps] = line.slice(0, at).split(';');
|
|
96
|
+
const params = Object.fromEntries(ps.map((p) => [p.split('=')[0].toUpperCase(), p.split('=').slice(1).join('=').replace(/^"|"$/g, '')]));
|
|
97
|
+
const value = line.slice(at + 1);
|
|
98
|
+
switch (name.toUpperCase()) {
|
|
99
|
+
case 'UID': cur.uid = value; break;
|
|
100
|
+
case 'SUMMARY': cur.summary = unescapeText(value); break;
|
|
101
|
+
case 'DESCRIPTION': cur.description = unescapeText(value); break;
|
|
102
|
+
case 'LOCATION': cur.location = unescapeText(value); break;
|
|
103
|
+
case 'URL': cur.url = value; break;
|
|
104
|
+
case 'STATUS': cur.status = value.toUpperCase(); break;
|
|
105
|
+
case 'TRANSP': cur.transparent = value.toUpperCase() === 'TRANSPARENT'; break;
|
|
106
|
+
case 'DTSTART': cur.start = parseTime(value, params); break;
|
|
107
|
+
case 'DTEND': cur.end = parseTime(value, params); break;
|
|
108
|
+
case 'DURATION': cur.duration = durationMs(value); break;
|
|
109
|
+
case 'RECURRENCE-ID': cur.recurrenceId = parseTime(value, params); break;
|
|
110
|
+
case 'EXDATE': for (const v of value.split(',')) { const t = parseTime(v, params); if (t) cur.exdates.push(t); } break;
|
|
111
|
+
case 'RRULE': cur.rrule = Object.fromEntries(value.split(';').map((p) => [p.split('=')[0].toUpperCase(), p.split('=')[1] ?? ''])); break;
|
|
112
|
+
default:
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return events;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Whether a recurring event falls on a day (day number `n`), by its rule. */
|
|
119
|
+
function onDay(ev, n, s0) {
|
|
120
|
+
const r = ev.rrule;
|
|
121
|
+
const interval = Math.max(1, Number(r.INTERVAL) || 1);
|
|
122
|
+
const c = fromDayNum(n);
|
|
123
|
+
const wd = WEEKDAYS[new Date(n * DAY).getUTCDay()];
|
|
124
|
+
const byday = (r.BYDAY ?? '').split(',').filter(Boolean);
|
|
125
|
+
const s = ev.start.w;
|
|
126
|
+
switch (r.FREQ) {
|
|
127
|
+
case 'DAILY':
|
|
128
|
+
return (n - s0) % interval === 0 && (!byday.length || byday.includes(wd));
|
|
129
|
+
case 'WEEKLY': {
|
|
130
|
+
const wkst = WEEKDAYS.indexOf(r.WKST ?? 'MO');
|
|
131
|
+
const week = (x) => Math.floor((x - ((new Date(x * DAY).getUTCDay() - wkst + 7) % 7)) / 7);
|
|
132
|
+
return (week(n) - week(s0)) % interval === 0 && (byday.length ? byday.includes(wd) : wd === WEEKDAYS[new Date(s0 * DAY).getUTCDay()]);
|
|
133
|
+
}
|
|
134
|
+
case 'MONTHLY': {
|
|
135
|
+
if (((c.y - s.y) * 12 + (c.m - s.m)) % interval !== 0) return false;
|
|
136
|
+
if (byday.length) {
|
|
137
|
+
const nth = Math.ceil(c.d / 7);
|
|
138
|
+
const last = new Date(Date.UTC(c.y, c.m, 0)).getUTCDate();
|
|
139
|
+
const fromEnd = -Math.ceil((last - c.d + 1) / 7);
|
|
140
|
+
return byday.some((b) => {
|
|
141
|
+
const m = b.match(/^([+-]?\d+)?([A-Z]{2})$/);
|
|
142
|
+
return m && m[2] === wd && (!m[1] || Number(m[1]) === nth || Number(m[1]) === fromEnd);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
if (r.BYMONTHDAY) {
|
|
146
|
+
const last = new Date(Date.UTC(c.y, c.m, 0)).getUTCDate();
|
|
147
|
+
return r.BYMONTHDAY.split(',').map(Number).some((d) => d === c.d || (d < 0 && last + d + 1 === c.d));
|
|
148
|
+
}
|
|
149
|
+
return c.d === s.d;
|
|
150
|
+
}
|
|
151
|
+
case 'YEARLY':
|
|
152
|
+
return (c.y - s.y) % interval === 0 && c.m === s.m && c.d === s.d;
|
|
153
|
+
default:
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The events between two instants, recurring ones spread over their dates:
|
|
160
|
+
* [{ uid, title, description, location, url, start, end (ms), allDay, free }], by start.
|
|
161
|
+
*/
|
|
162
|
+
export function eventsBetween(events, from, to) {
|
|
163
|
+
const out = [];
|
|
164
|
+
// An occurrence changed on its own (moved, renamed) replaces the one its series would give.
|
|
165
|
+
const moved = new Map();
|
|
166
|
+
for (const e of events) if (e.recurrenceId && e.uid) moved.set(`${e.uid}|${wallKey(e.recurrenceId.w, e.recurrenceId.allDay)}`, true);
|
|
167
|
+
const lengthOf = (e) => {
|
|
168
|
+
if (e.end) return wallToMs(e.end.w, e.end.tz) - wallToMs(e.start.w, e.start.tz);
|
|
169
|
+
if (e.duration) return e.duration;
|
|
170
|
+
return e.start.allDay ? DAY : 0;
|
|
171
|
+
};
|
|
172
|
+
const push = (e, w) => {
|
|
173
|
+
const start = wallToMs(w, e.start.allDay ? null : e.start.tz);
|
|
174
|
+
const end = start + Math.max(0, lengthOf(e));
|
|
175
|
+
if (end <= from || start >= to) return;
|
|
176
|
+
out.push({ uid: e.uid ?? null, title: clip(e.summary || '(no title)', 200), description: clip(e.description, 2000), location: clip(e.location, 200) || null, url: e.url ?? null, start, end, allDay: e.start.allDay, free: Boolean(e.transparent) });
|
|
177
|
+
};
|
|
178
|
+
for (const e of events) {
|
|
179
|
+
if (e.status === 'CANCELLED') continue;
|
|
180
|
+
if (!e.rrule || e.recurrenceId) {
|
|
181
|
+
push(e, e.start.w);
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
const s0 = dayNum(e.start.w.y, e.start.w.m, e.start.w.d);
|
|
185
|
+
const until = e.rrule.UNTIL ? parseTime(e.rrule.UNTIL) : null;
|
|
186
|
+
const untilMs = until ? wallToMs(until.allDay ? { ...until.w, h: 23, mi: 59, s: 59 } : until.w, until.tz ?? e.start.tz) : Infinity;
|
|
187
|
+
const count = Number(e.rrule.COUNT) || Infinity;
|
|
188
|
+
const skip = new Set(e.exdates.map((x) => wallKey(x.w, x.allDay || e.start.allDay)));
|
|
189
|
+
const lastDay = Math.floor(to / DAY) + 2;
|
|
190
|
+
// Without a count, nothing before the window matters: start near it (a week early, for long events).
|
|
191
|
+
let n = count === Infinity ? Math.max(s0, Math.floor(from / DAY) - 7) : s0;
|
|
192
|
+
let made = 0;
|
|
193
|
+
for (let guard = 0; n <= lastDay && made < count && guard < 20_000; n++, guard++) {
|
|
194
|
+
if (!onDay(e, n, s0)) continue;
|
|
195
|
+
const w = { ...fromDayNum(n), h: e.start.w.h, mi: e.start.w.mi, s: e.start.w.s };
|
|
196
|
+
if (wallToMs(w, e.start.allDay ? null : e.start.tz) > untilMs) break;
|
|
197
|
+
made++;
|
|
198
|
+
const key = wallKey(w, e.start.allDay);
|
|
199
|
+
if (skip.has(key) || moved.has(`${e.uid}|${key}`)) continue;
|
|
200
|
+
push(e, w);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return out.sort((a, b) => a.start - b.start || a.end - b.end);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** What a meeting is about, from its title and description: the agents and Today items it names. */
|
|
207
|
+
export function relatedTo(meeting, { agents = [], items = [] } = {}) {
|
|
208
|
+
const text = `${meeting.title} ${meeting.description ?? ''}`;
|
|
209
|
+
const lower = text.toLowerCase().replace(/[-_]+/g, ' ');
|
|
210
|
+
const keys = new Set([...text.matchAll(/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g)].map((m) => m[0]));
|
|
211
|
+
const prs = new Set([...text.matchAll(/#(\d{1,6})\b/g)].map((m) => m[1]));
|
|
212
|
+
const out = [];
|
|
213
|
+
const seen = new Set();
|
|
214
|
+
const add = (x) => {
|
|
215
|
+
if (seen.has(x.key) || out.length >= 6) return;
|
|
216
|
+
seen.add(x.key);
|
|
217
|
+
out.push(x);
|
|
218
|
+
};
|
|
219
|
+
for (const a of agents) {
|
|
220
|
+
const name = String(a.name ?? '').toLowerCase().replace(/[-_]+/g, ' ').trim();
|
|
221
|
+
const issue = a.issue && keys.has(a.issue);
|
|
222
|
+
const pr = (a.prs ?? []).find((p) => prs.has(String(p.number)));
|
|
223
|
+
const named = name.length >= 5 && lower.includes(name);
|
|
224
|
+
const project = a.project && a.project.length >= 4 && new RegExp(`\\b${a.project.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim().replace(/ /g, '[ -]')}\\b`).test(lower);
|
|
225
|
+
if (issue || pr || named) add({ key: `agent:${a.id}`, kind: 'agent', agentId: a.id, title: a.name, why: issue ? `works on ${a.issue}` : pr ? `opened #${pr.number}` : 'named in the invite', status: a.status ?? null });
|
|
226
|
+
else if (project) add({ key: `agent:${a.id}`, kind: 'agent', agentId: a.id, title: a.name, why: `in ${a.project}`, status: a.status ?? null });
|
|
227
|
+
}
|
|
228
|
+
for (const i of items) {
|
|
229
|
+
const t = `${i.title} ${i.issueKey ?? ''}`;
|
|
230
|
+
if ([...keys].some((k) => t.includes(k)) || [...prs].some((n) => new RegExp(`#${n}\\b`).test(t))) add({ key: `item:${i.id}`, kind: 'item', id: i.id, title: clip(i.title, 120), why: i.label, url: i.url ?? null, agentId: i.agentId ?? null });
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const atTime = (now, hhmm) => {
|
|
236
|
+
const [h, m] = String(hhmm).split(':').map(Number);
|
|
237
|
+
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), h || 0, m || 0).getTime();
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The day: meetings, free blocks from now to the end of the working day, and Today's items placed
|
|
242
|
+
* in them in order (most pressing first), each with the minutes it usually takes.
|
|
243
|
+
*/
|
|
244
|
+
export function dayPlan({ events = [], items = [], agents = [], now = new Date(), workStart = '09:00', workEnd = '18:00' } = {}) {
|
|
245
|
+
const t = now.getTime();
|
|
246
|
+
const dayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
|
247
|
+
const today = events.filter((e) => e.end > dayStart && e.start < dayStart + DAY);
|
|
248
|
+
const meetings = today.filter((e) => !e.allDay).map((e) => ({ title: e.title, start: e.start, end: e.end, location: e.location, url: e.url, free: e.free, now: e.start <= t && e.end > t, past: e.end <= t, related: e.end > t ? relatedTo(e, { agents, items }) : [] }));
|
|
249
|
+
const busy = meetings.filter((m) => !m.free);
|
|
250
|
+
const from = Math.max(t, atTime(now, workStart));
|
|
251
|
+
const to = atTime(now, workEnd);
|
|
252
|
+
// Free time: the working day from now on, less the meetings.
|
|
253
|
+
const gaps = [];
|
|
254
|
+
let at = from;
|
|
255
|
+
for (const m of busy.filter((x) => x.end > from && x.start < to).sort((a, b) => a.start - b.start)) {
|
|
256
|
+
if (m.start - at >= 15 * MIN) gaps.push([at, m.start]);
|
|
257
|
+
at = Math.max(at, m.end);
|
|
258
|
+
}
|
|
259
|
+
if (to - at >= 15 * MIN) gaps.push([at, to]);
|
|
260
|
+
// A date coming up is something to know, not something to sit down and do.
|
|
261
|
+
const todo = items.filter((i) => i.kind !== 'milestone');
|
|
262
|
+
const left = todo.map((i) => ({ id: i.id, kind: i.kind, label: i.label, title: clip(i.title, 140), minutes: MINUTES[i.kind] ?? 10, agentId: i.agentId ?? null, url: i.url ?? null }));
|
|
263
|
+
const blocks = gaps.map(([start, end]) => {
|
|
264
|
+
let room = Math.floor((end - start) / MIN);
|
|
265
|
+
const placed = [];
|
|
266
|
+
for (let k = 0; k < left.length; ) {
|
|
267
|
+
if (left[k].minutes <= room) {
|
|
268
|
+
room -= left[k].minutes;
|
|
269
|
+
placed.push(...left.splice(k, 1));
|
|
270
|
+
} else k++;
|
|
271
|
+
}
|
|
272
|
+
return { start, end, minutes: Math.floor((end - start) / MIN), items: placed, spare: room };
|
|
273
|
+
});
|
|
274
|
+
const next = busy.find((m) => m.start > t) ?? null;
|
|
275
|
+
return {
|
|
276
|
+
date: new Date(dayStart).toISOString(),
|
|
277
|
+
allDay: today.filter((e) => e.allDay).map((e) => e.title),
|
|
278
|
+
meetings,
|
|
279
|
+
blocks,
|
|
280
|
+
current: busy.find((m) => m.now)?.title ?? null,
|
|
281
|
+
next: next ? { title: next.title, start: next.start, inMinutes: Math.round((next.start - t) / MIN), related: next.related } : null,
|
|
282
|
+
meetingMinutes: Math.round(busy.reduce((s, m) => s + (m.end - m.start), 0) / MIN),
|
|
283
|
+
freeMinutes: blocks.reduce((s, b) => s + b.minutes, 0),
|
|
284
|
+
needMinutes: todo.reduce((s, i) => s + (MINUTES[i.kind] ?? 10), 0),
|
|
285
|
+
unplaced: left.length,
|
|
286
|
+
workStart,
|
|
287
|
+
workEnd,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Settings from config.json's "calendar". */
|
|
292
|
+
export function calendarSettings(config = {}) {
|
|
293
|
+
const s = { ...CALENDAR_DEFAULTS, ...config.calendar };
|
|
294
|
+
const time = (v, d) => (/^([01]\d|2[0-3]):[0-5]\d$/.test(String(v)) ? String(v) : d);
|
|
295
|
+
const ics = (Array.isArray(s.ics) ? s.ics : s.ics ? [s.ics] : []).map((u) => String(u).trim().replace(/^webcal:\/\//i, 'https://')).filter((u) => /^https?:\/\//i.test(u) || u.startsWith('/'));
|
|
296
|
+
const workStart = time(s.workStart, CALENDAR_DEFAULTS.workStart);
|
|
297
|
+
const workEnd = time(s.workEnd, CALENDAR_DEFAULTS.workEnd);
|
|
298
|
+
return { ics: [...new Set(ics)].slice(0, 8), workStart, workEnd: workEnd > workStart ? workEnd : CALENDAR_DEFAULTS.workEnd };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function defaultFetch(source) {
|
|
302
|
+
if (source.startsWith('/')) return fs.readFileSync(source, 'utf8');
|
|
303
|
+
const res = await fetch(source, { headers: { accept: 'text/calendar, text/plain;q=0.9, */*;q=0.5' }, signal: AbortSignal.timeout(20_000), redirect: 'follow' });
|
|
304
|
+
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
|
|
305
|
+
return res.text();
|
|
306
|
+
}
|
|
307
|
+
/** Where a calendar comes from, without its secret address: the host, or the file's name. */
|
|
308
|
+
const sourceName = (u) => {
|
|
309
|
+
if (u.startsWith('/')) return u.split('/').pop();
|
|
310
|
+
try {
|
|
311
|
+
return new URL(u).host;
|
|
312
|
+
} catch {
|
|
313
|
+
return 'calendar';
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
export class Calendar {
|
|
318
|
+
constructor({ config = {}, fetchText = defaultFetch, now = () => new Date(), log = (m) => console.log(`[agentmgr] ${m}`) }) {
|
|
319
|
+
Object.assign(this, { config, fetchText, now, log });
|
|
320
|
+
this.cache = new Map(); // address -> { at, events, error }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
get settings() {
|
|
324
|
+
return calendarSettings(this.config);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Check the addresses can be read as calendars, then keep them; `save(patch)` writes config.json. */
|
|
328
|
+
async set({ ics, add, workStart, workEnd } = {}, save) {
|
|
329
|
+
// `add`: one more address next to the ones already kept (they are never sent to the page).
|
|
330
|
+
if (add !== undefined && String(add).trim()) ics = [...this.settings.ics, String(add).trim()];
|
|
331
|
+
const next = calendarSettings({ calendar: { ...this.config.calendar, ...(ics !== undefined ? { ics } : {}), ...(workStart ? { workStart } : {}), ...(workEnd ? { workEnd } : {}) } });
|
|
332
|
+
if (ics !== undefined) {
|
|
333
|
+
const asked = (Array.isArray(ics) ? ics : [ics]).filter((u) => String(u ?? '').trim());
|
|
334
|
+
if (asked.length !== next.ics.length) throw err(400, "A calendar address starts with https:// (or webcal://): the calendar's private iCal address");
|
|
335
|
+
for (const u of next.ics) {
|
|
336
|
+
if (this.config.calendar?.ics?.includes(u)) continue;
|
|
337
|
+
let text;
|
|
338
|
+
try {
|
|
339
|
+
text = await this.fetchText(u);
|
|
340
|
+
} catch (e) {
|
|
341
|
+
throw err(400, `Couldn't read the calendar at ${sourceName(u)}: ${e.message}`);
|
|
342
|
+
}
|
|
343
|
+
if (!/BEGIN:VCALENDAR/.test(text)) throw err(400, `${sourceName(u)} didn't return a calendar: use the calendar's private iCal address (it ends in .ics)`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
this.config.calendar = next;
|
|
347
|
+
this.cache.clear();
|
|
348
|
+
save?.({ calendar: next });
|
|
349
|
+
return this.status();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async load(source) {
|
|
353
|
+
const hit = this.cache.get(source);
|
|
354
|
+
if (hit && this.now().getTime() - hit.at < CACHE_MS) return hit;
|
|
355
|
+
let rec;
|
|
356
|
+
try {
|
|
357
|
+
rec = { at: this.now().getTime(), events: parseIcs(await this.fetchText(source)), error: null };
|
|
358
|
+
} catch (e) {
|
|
359
|
+
// A calendar that can't be read right now: what was read last, with why.
|
|
360
|
+
rec = { at: this.now().getTime(), events: hit?.events ?? [], error: String(e.message).slice(0, 200) };
|
|
361
|
+
this.log(`calendar: ${sourceName(source)}: ${e.message}`);
|
|
362
|
+
}
|
|
363
|
+
this.cache.set(source, rec);
|
|
364
|
+
return rec;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
status() {
|
|
368
|
+
const s = this.settings;
|
|
369
|
+
return { connected: s.ics.length > 0, sources: s.ics.map((u) => ({ name: sourceName(u), error: this.cache.get(u)?.error ?? null, events: this.cache.get(u)?.events.length ?? null })), workStart: s.workStart, workEnd: s.workEnd };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Today planned around the meetings; { connected: false } when no calendar is set. */
|
|
373
|
+
async day({ items = [], agents = [] } = {}) {
|
|
374
|
+
const s = this.settings;
|
|
375
|
+
if (!s.ics.length) return { connected: false, workStart: s.workStart, workEnd: s.workEnd };
|
|
376
|
+
const now = this.now();
|
|
377
|
+
const dayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
|
378
|
+
const loaded = await Promise.all(s.ics.map((u) => this.load(u)));
|
|
379
|
+
const events = eventsBetween(loaded.flatMap((l) => l.events), dayStart, dayStart + DAY);
|
|
380
|
+
// The same meeting on two calendars is one meeting.
|
|
381
|
+
const seen = new Set();
|
|
382
|
+
const unique = events.filter((e) => !seen.has(`${e.title}|${e.start}|${e.end}`) && seen.add(`${e.title}|${e.start}|${e.end}`));
|
|
383
|
+
return { ...this.status(), ...dayPlan({ events: unique, items, agents, now, workStart: s.workStart, workEnd: s.workEnd }) };
|
|
384
|
+
}
|
|
385
|
+
}
|