ai-agentmanager 1.57.3 → 1.59.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 +21 -0
- package/README.md +53 -4
- package/docs/architecture.md +4 -1
- package/package.json +1 -1
- package/public/announce.js +134 -0
- package/public/app.js +98 -11
- package/public/files.js +105 -0
- package/public/index.html +45 -3
- package/public/keys.js +1 -0
- package/public/palette.js +122 -0
- package/public/screen.js +231 -13
- package/public/setup.js +1 -1
- package/public/style.css +42 -0
- package/src/announce.js +140 -0
- package/src/awake.js +75 -0
- package/src/cli.js +77 -2
- package/src/files.js +80 -0
- package/src/manager.js +72 -0
- package/src/notify.js +90 -8
- package/src/screen.js +60 -3
- package/src/server.js +101 -12
package/public/screen.js
CHANGED
|
@@ -122,8 +122,13 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
122
122
|
const view = $('#screen-view');
|
|
123
123
|
const state = $('#screen-state');
|
|
124
124
|
let status = null;
|
|
125
|
+
let awake = null; // whether the computer is kept from sleeping (src/awake.js)
|
|
125
126
|
let rfb = null;
|
|
126
127
|
let ended = null; // why the last connection ended
|
|
128
|
+
// While a mouse button is down noVNC lays a sheet over the page to follow the mouse, and takes
|
|
129
|
+
// it away when the button comes up on that sheet. Under this dialog the sheet never gets that,
|
|
130
|
+
// and would stay over the page after the dialog closes, taking the next click. Taken away here.
|
|
131
|
+
let release = () => {};
|
|
127
132
|
|
|
128
133
|
const remote = () => document.body.classList.contains('remote');
|
|
129
134
|
|
|
@@ -137,7 +142,7 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
137
142
|
if (!stage) return;
|
|
138
143
|
const cx = keep && view.scrollWidth ? (view.scrollLeft + view.clientWidth / 2) / view.scrollWidth : 0.5;
|
|
139
144
|
const cy = keep && view.scrollHeight ? (view.scrollTop + view.clientHeight / 2) / view.scrollHeight : 0.5;
|
|
140
|
-
if (zoom === 1) moving = false;
|
|
145
|
+
if (zoom === 1 || pad) moving = false;
|
|
141
146
|
view.classList.toggle('zoomed', zoom > 1);
|
|
142
147
|
// The outer size: scrollbars that take room must not make the screen smaller than the zoom says.
|
|
143
148
|
const w = view.offsetWidth;
|
|
@@ -149,9 +154,16 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
149
154
|
stage.querySelector('.screen-pan').hidden = !moving;
|
|
150
155
|
$('#screen-zoom-now').textContent = zoom === 1 ? 'Fit' : `${Math.round(zoom * 100)}%`;
|
|
151
156
|
const move = $('#screen-move');
|
|
152
|
-
move.hidden = zoom === 1;
|
|
157
|
+
move.hidden = zoom === 1 || pad; // as a trackpad the screen follows the pointer
|
|
153
158
|
move.setAttribute('aria-pressed', String(moving));
|
|
154
159
|
move.classList.toggle('on', moving);
|
|
160
|
+
const sheet = stage.querySelector('.screen-pad');
|
|
161
|
+
sheet.hidden = !pad;
|
|
162
|
+
stage.querySelector('.screen-pointer').hidden = !pad;
|
|
163
|
+
const padBtn = $('#screen-pad');
|
|
164
|
+
padBtn.setAttribute('aria-pressed', String(pad));
|
|
165
|
+
padBtn.classList.toggle('on', pad);
|
|
166
|
+
if (pad) point(false);
|
|
155
167
|
}
|
|
156
168
|
function setZoom(step) {
|
|
157
169
|
const at = ZOOMS.indexOf(zoom);
|
|
@@ -159,6 +171,156 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
159
171
|
layout();
|
|
160
172
|
}
|
|
161
173
|
new ResizeObserver(() => layout()).observe(view);
|
|
174
|
+
|
|
175
|
+
// Trackpad: a fingertip covers the button it aims at, so the screen can be a trackpad instead.
|
|
176
|
+
// A drag anywhere moves a pointer drawn here (slowly for a slow finger), a tap clicks where it
|
|
177
|
+
// is, two fingers scroll or, tapped, right-click, and a finger held down first drags.
|
|
178
|
+
let pad = false;
|
|
179
|
+
try {
|
|
180
|
+
pad = localStorage.getItem('screen-pad') === '1';
|
|
181
|
+
} catch {}
|
|
182
|
+
let at = null; // the pointer, in the computer's screen pixels
|
|
183
|
+
/** Where the pointer is: in the drawn screen (what noVNC counts in), in the stage and in the page. */
|
|
184
|
+
function spot() {
|
|
185
|
+
const c = stage?.querySelector('canvas');
|
|
186
|
+
if (!c?.width || !rfb?._handleMouseMove) return null;
|
|
187
|
+
at ??= { x: c.width / 2, y: c.height / 2 };
|
|
188
|
+
at.x = Math.max(0, Math.min(c.width - 1, at.x));
|
|
189
|
+
at.y = Math.max(0, Math.min(c.height - 1, at.y));
|
|
190
|
+
const r = c.getBoundingClientRect();
|
|
191
|
+
const s = stage.getBoundingClientRect();
|
|
192
|
+
// The middle of the pixel, so that it is the same pixel again when noVNC counts back.
|
|
193
|
+
const x = ((Math.floor(at.x) + 0.5) / c.width) * r.width;
|
|
194
|
+
const y = ((Math.floor(at.y) + 0.5) / c.height) * r.height;
|
|
195
|
+
return { x, y, left: r.left - s.left + x, top: r.top - s.top + y, pageX: r.left + x, pageY: r.top + y, per: c.width / (r.width || 1) };
|
|
196
|
+
}
|
|
197
|
+
/** Draw the pointer where it is, keep it in view when zoomed in, and tell the computer. */
|
|
198
|
+
function point(send = true) {
|
|
199
|
+
const p = spot();
|
|
200
|
+
if (!p) return null;
|
|
201
|
+
const arrow = stage.querySelector('.screen-pointer');
|
|
202
|
+
arrow.style.left = `${p.left}px`;
|
|
203
|
+
arrow.style.top = `${p.top}px`;
|
|
204
|
+
const edge = 36;
|
|
205
|
+
if (p.left < view.scrollLeft + edge) view.scrollLeft = p.left - edge;
|
|
206
|
+
else if (p.left > view.scrollLeft + view.clientWidth - edge) view.scrollLeft = p.left - view.clientWidth + edge;
|
|
207
|
+
if (p.top < view.scrollTop + edge) view.scrollTop = p.top - edge;
|
|
208
|
+
else if (p.top > view.scrollTop + view.clientHeight - edge) view.scrollTop = p.top - view.clientHeight + edge;
|
|
209
|
+
if (send) rfb._handleMouseMove(p.x, p.y);
|
|
210
|
+
return p;
|
|
211
|
+
}
|
|
212
|
+
/** The ring that shows the page took a tap. */
|
|
213
|
+
function ring(x, y) {
|
|
214
|
+
const el = document.createElement('div');
|
|
215
|
+
el.className = 'screen-tap';
|
|
216
|
+
el.style.left = `${x}px`;
|
|
217
|
+
el.style.top = `${y}px`;
|
|
218
|
+
dialog.append(el);
|
|
219
|
+
setTimeout(() => el.remove(), 450);
|
|
220
|
+
}
|
|
221
|
+
/** The trackpad's gestures, on the sheet that covers the screen while it is on. */
|
|
222
|
+
function trackpad(sheet, mine) {
|
|
223
|
+
const HOLD = 450; // ms a finger rests before it holds the button down
|
|
224
|
+
const STEP = 28; // px two fingers move for one notch of the wheel
|
|
225
|
+
let g = null; // the gesture under way
|
|
226
|
+
const mid = (ts) => ({ x: [...ts].reduce((n, t) => n + t.clientX, 0) / ts.length, y: [...ts].reduce((n, t) => n + t.clientY, 0) / ts.length });
|
|
227
|
+
const button = (mask) => {
|
|
228
|
+
const p = rfb === mine && spot();
|
|
229
|
+
if (p) mine._handleMouseButton(p.x, p.y, mask);
|
|
230
|
+
return p;
|
|
231
|
+
};
|
|
232
|
+
const down = () => (g?.held ? 0x1 : 0);
|
|
233
|
+
const arrow = () => stage?.querySelector('.screen-pointer');
|
|
234
|
+
sheet.addEventListener('touchstart', (e) => {
|
|
235
|
+
e.preventDefault(); // no focus change (the phone's keyboard stays open) and no made-up mouse
|
|
236
|
+
const m = mid(e.touches);
|
|
237
|
+
if (!g) {
|
|
238
|
+
g = { fingers: 0, moved: false, held: false, far: 0, sx: 0, sy: 0, since: e.timeStamp, timer: null };
|
|
239
|
+
g.timer = setTimeout(() => {
|
|
240
|
+
if (!g || g.moved || g.fingers !== 1 || !button(0x1)) return;
|
|
241
|
+
g.held = true;
|
|
242
|
+
arrow()?.classList.add('held');
|
|
243
|
+
}, HOLD);
|
|
244
|
+
}
|
|
245
|
+
g.fingers = Math.max(g.fingers, e.touches.length);
|
|
246
|
+
if (e.touches.length > 1) clearTimeout(g.timer);
|
|
247
|
+
Object.assign(g, { x: m.x, y: m.y, last: e.timeStamp });
|
|
248
|
+
}, { passive: false });
|
|
249
|
+
sheet.addEventListener('touchmove', (e) => {
|
|
250
|
+
e.preventDefault();
|
|
251
|
+
if (!g) return;
|
|
252
|
+
const m = mid(e.touches);
|
|
253
|
+
const dx = m.x - g.x;
|
|
254
|
+
const dy = m.y - g.y;
|
|
255
|
+
const ms = Math.max(1, e.timeStamp - g.last);
|
|
256
|
+
Object.assign(g, { x: m.x, y: m.y, last: e.timeStamp });
|
|
257
|
+
g.far += Math.hypot(dx, dy);
|
|
258
|
+
// A finger is never quite still: only past this is it a move, not a tap.
|
|
259
|
+
if (!g.moved && g.far < 8 && !g.held) return;
|
|
260
|
+
g.moved = true;
|
|
261
|
+
if (!g.held) clearTimeout(g.timer);
|
|
262
|
+
if (e.touches.length > 1) {
|
|
263
|
+
// As on the phone itself: what is under the fingers goes where they go.
|
|
264
|
+
g.sx += dx;
|
|
265
|
+
g.sy += dy;
|
|
266
|
+
for (const [axis, back, on] of [['sy', 0x8, 0x10], ['sx', 0x20, 0x40]]) {
|
|
267
|
+
while (Math.abs(g[axis]) >= STEP) {
|
|
268
|
+
const notch = g[axis] > 0 ? back : on;
|
|
269
|
+
g[axis] -= Math.sign(g[axis]) * STEP;
|
|
270
|
+
button(down() | notch);
|
|
271
|
+
button(down());
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const p = spot();
|
|
277
|
+
if (!p) return;
|
|
278
|
+
// A slow finger moves the pointer less than its own way, for small targets; a quick one crosses the screen.
|
|
279
|
+
const gain = p.per * Math.max(0.35, Math.min(2.5, 0.35 + 1.5 * (Math.hypot(dx, dy) / ms)));
|
|
280
|
+
at.x += dx * gain;
|
|
281
|
+
at.y += dy * gain;
|
|
282
|
+
point();
|
|
283
|
+
}, { passive: false });
|
|
284
|
+
const end = (e) => {
|
|
285
|
+
e.preventDefault();
|
|
286
|
+
if (!g) return;
|
|
287
|
+
if (e.touches.length) {
|
|
288
|
+
// One finger of several lifted: the rest carry on from where they are.
|
|
289
|
+
const m = mid(e.touches);
|
|
290
|
+
Object.assign(g, { x: m.x, y: m.y, last: e.timeStamp });
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const was = g;
|
|
294
|
+
g = null;
|
|
295
|
+
clearTimeout(was.timer);
|
|
296
|
+
if (was.held) {
|
|
297
|
+
button(0);
|
|
298
|
+
arrow()?.classList.remove('held');
|
|
299
|
+
} else if (!was.moved && e.type === 'touchend' && e.timeStamp - was.since < HOLD) {
|
|
300
|
+
// Press and release apart, as a hand on a mouse: a Mac does not take them in one instant.
|
|
301
|
+
const p = button(was.fingers > 1 ? 0x4 : 0x1);
|
|
302
|
+
if (p) ring(p.pageX, p.pageY);
|
|
303
|
+
setTimeout(() => button(0), 100);
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
sheet.addEventListener('touchend', end, { passive: false });
|
|
307
|
+
sheet.addEventListener('touchcancel', end, { passive: false });
|
|
308
|
+
}
|
|
309
|
+
function setPad(on) {
|
|
310
|
+
pad = on;
|
|
311
|
+
try {
|
|
312
|
+
localStorage.setItem('screen-pad', on ? '1' : '0');
|
|
313
|
+
} catch {}
|
|
314
|
+
layout();
|
|
315
|
+
if (on) {
|
|
316
|
+
point();
|
|
317
|
+
toast('Trackpad: drag to move the pointer, tap to click. Two fingers scroll, or tapped, right-click. Hold, then drag, to drag.', 7000);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
// The button is for fingers: it shows once the page has been touched.
|
|
321
|
+
const showPad = () => ($('#screen-pad').hidden = false);
|
|
322
|
+
if (navigator.maxTouchPoints > 0 || pad) showPad(); // on already: there must be a way to turn it off
|
|
323
|
+
else dialog.addEventListener('touchstart', showPad, { once: true, passive: true, capture: true });
|
|
162
324
|
const others = (v = status?.viewers ?? []) => v.filter((x) => x.who !== 'this computer');
|
|
163
325
|
|
|
164
326
|
/** The dot on the button: someone on another device is looking at this computer's screen. */
|
|
@@ -179,12 +341,21 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
179
341
|
<p><code>${esc(m.fix)}</code></p></div>`;
|
|
180
342
|
}
|
|
181
343
|
|
|
344
|
+
/** A sleeping computer shows nothing and runs nothing: it can be kept awake, from here too. */
|
|
345
|
+
function keepAwake() {
|
|
346
|
+
if (!awake?.supported) return '';
|
|
347
|
+
const opt = (v, label) => `<option value="${v}"${awake.mode === v ? ' selected' : ''}>${label}</option>`;
|
|
348
|
+
return `<p class="screen-awake"><label>Keep this computer awake <select data-screen-awake>${opt('off', 'No')}${opt('working', 'While an agent works')}${opt('always', 'Always')}</select></label>
|
|
349
|
+
<span class="hint">${awake.mode === 'off' ? 'Asleep, it cannot be reached from here and its agents stop.' : 'It will not go to sleep by itself. The display may still sleep and lock; a closed lid still puts a laptop to sleep.'}</span></p>`;
|
|
350
|
+
}
|
|
351
|
+
|
|
182
352
|
function render() {
|
|
183
353
|
const s = status;
|
|
184
354
|
const connected = Boolean(rfb);
|
|
185
355
|
view.hidden = !connected;
|
|
186
356
|
body.hidden = connected;
|
|
187
357
|
$('#screen-keys').hidden = !connected;
|
|
358
|
+
if (!connected) showClip(false);
|
|
188
359
|
$('#screen-off').hidden = remote() || !s?.enabled;
|
|
189
360
|
if (connected || !s) return;
|
|
190
361
|
const far = others();
|
|
@@ -194,7 +365,7 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
194
365
|
body.innerHTML = `<h3>This computer's screen, here and on your phone</h3>
|
|
195
366
|
<p>See the whole screen and click or type in it: a pop-up that needs an answer, another program you want to watch.</p>
|
|
196
367
|
<p class="hint">Whoever uses this controls the whole computer, not only the agents. It is off until you turn it on, and it can only be turned on here, on the computer itself. The computer's own screen sharing still asks for its sign-in every time.</p>
|
|
197
|
-
${remote() ? '<p><b>Off.</b> Turn it on on the computer: the Screen button, or <code>agentmgr screen --on</code>.</p>' : '<p><button class="primary" data-screen="on">Turn on</button></p>'}`;
|
|
368
|
+
${remote() ? '<p><b>Off.</b> Turn it on on the computer: the Screen button, or <code>agentmgr screen --on</code>.</p>' : '<p><button class="primary" data-screen="on">Turn on</button></p>'}${keepAwake()}`;
|
|
198
369
|
return;
|
|
199
370
|
}
|
|
200
371
|
if (!s.listening) {
|
|
@@ -208,10 +379,11 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
208
379
|
state.textContent = ended ? 'Ended' : 'Ready';
|
|
209
380
|
body.innerHTML = `${ended ? `<p><b>Ended:</b> ${esc(ended)}</p>` : '<h3>Ready</h3>'}${notListed()}
|
|
210
381
|
<p class="hint">${s.platform === 'darwin' ? 'The Mac asks for your Mac user name and password next. They go to the Mac and are not kept.' : 'The computer asks for its screen sharing password next. It is not kept.'}</p>
|
|
211
|
-
<p><button class="primary" data-screen="connect">${ended ? 'Connect again' : 'Connect'}</button></p>${viewed}`;
|
|
382
|
+
<p><button class="primary" data-screen="connect">${ended ? 'Connect again' : 'Connect'}</button></p>${viewed}${keepAwake()}`;
|
|
212
383
|
}
|
|
213
384
|
|
|
214
385
|
async function refresh() {
|
|
386
|
+
awake = await api('GET', '/awake').catch(() => null);
|
|
215
387
|
try {
|
|
216
388
|
status = await api('GET', '/screen');
|
|
217
389
|
} catch (err) {
|
|
@@ -227,6 +399,7 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
227
399
|
const was = rfb;
|
|
228
400
|
rfb = null;
|
|
229
401
|
ended = reason;
|
|
402
|
+
release();
|
|
230
403
|
try {
|
|
231
404
|
was?.disconnect();
|
|
232
405
|
} catch {}
|
|
@@ -257,14 +430,16 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
257
430
|
let RFB;
|
|
258
431
|
try {
|
|
259
432
|
({ default: RFB } = await import('/vendor/novnc/core/rfb.js'));
|
|
433
|
+
({ releaseCapture: release } = await import('/vendor/novnc/core/util/events.js'));
|
|
260
434
|
} catch (err) {
|
|
261
435
|
return drop(`The viewer could not be loaded (${err.message})`);
|
|
262
436
|
}
|
|
263
437
|
stage = document.createElement('div');
|
|
264
438
|
stage.className = 'screen-stage';
|
|
265
|
-
stage.innerHTML = '<div class="screen-pan" hidden></div>';
|
|
439
|
+
stage.innerHTML = '<div class="screen-pan" hidden></div><div class="screen-pad" hidden></div><div class="screen-pointer" hidden></div>';
|
|
266
440
|
view.replaceChildren(stage);
|
|
267
441
|
zoom = 1;
|
|
442
|
+
at = null;
|
|
268
443
|
const mine = new RFB(stage, REMOTE ? new StreamChannel() : `ws://${location.host}/ws/screen`);
|
|
269
444
|
rfb = mine;
|
|
270
445
|
mine.scaleViewport = true;
|
|
@@ -285,14 +460,11 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
285
460
|
mine._handleMouseButton = button;
|
|
286
461
|
}
|
|
287
462
|
calls.forEach((args, i) => setTimeout(() => rfb === mine && button.apply(mine, args), 50 + i * 100));
|
|
288
|
-
|
|
289
|
-
ring.className = 'screen-tap';
|
|
290
|
-
ring.style.left = `${ev.detail.clientX}px`;
|
|
291
|
-
ring.style.top = `${ev.detail.clientY}px`;
|
|
292
|
-
dialog.append(ring);
|
|
293
|
-
setTimeout(() => ring.remove(), 450);
|
|
463
|
+
ring(ev.detail.clientX, ev.detail.clientY);
|
|
294
464
|
};
|
|
295
465
|
}
|
|
466
|
+
trackpad(stage.querySelector('.screen-pad'), mine);
|
|
467
|
+
stage.addEventListener('mouseup', () => setTimeout(release), true); // after noVNC has had it
|
|
296
468
|
// A mouse still gives the screen the focus, for the computer's own keyboard.
|
|
297
469
|
let touched = 0;
|
|
298
470
|
stage.addEventListener('touchstart', () => {
|
|
@@ -335,10 +507,53 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
335
507
|
});
|
|
336
508
|
|
|
337
509
|
// Typed blind on a phone, a password goes wrong easily: let it be seen.
|
|
338
|
-
dialog.addEventListener('change', (e) => {
|
|
510
|
+
dialog.addEventListener('change', async (e) => {
|
|
339
511
|
if (e.target.matches('[data-screen-show]')) e.target.form.password.type = e.target.checked ? 'text' : 'password';
|
|
512
|
+
if (e.target.matches('[data-screen-awake]')) {
|
|
513
|
+
try {
|
|
514
|
+
awake = await api('PUT', '/awake', { mode: e.target.value });
|
|
515
|
+
toast(awake.mode === 'off' ? 'This computer may go to sleep by itself again' : awake.mode === 'always' ? 'This computer is kept awake' : 'This computer is kept awake while an agent works');
|
|
516
|
+
} catch (err) {
|
|
517
|
+
toast(`Error: ${err.message}`, 6000);
|
|
518
|
+
}
|
|
519
|
+
if (!rfb) render();
|
|
520
|
+
}
|
|
340
521
|
});
|
|
341
522
|
|
|
523
|
+
// The computer's clipboard. Its screen sharing does not share it with a browser (a Mac's only
|
|
524
|
+
// with Apple's own viewer), so the daemon reads and sets it: text typed or pasted here goes
|
|
525
|
+
// there, and what was copied there comes here.
|
|
526
|
+
const clipText = $('#screen-clip-text');
|
|
527
|
+
function showClip(on) {
|
|
528
|
+
$('#screen-clip').hidden = !on;
|
|
529
|
+
$('#screen-clip-btn').setAttribute('aria-pressed', String(on));
|
|
530
|
+
$('#screen-clip-btn').classList.toggle('on', on);
|
|
531
|
+
if (on) clipText.focus();
|
|
532
|
+
}
|
|
533
|
+
async function clip(what) {
|
|
534
|
+
if (what === 'clip-get') {
|
|
535
|
+
const got = await api('GET', '/screen/clipboard');
|
|
536
|
+
clipText.value = got.text;
|
|
537
|
+
clipText.select();
|
|
538
|
+
if (!got.text) return toast("The computer's clipboard has no text");
|
|
539
|
+
// The page may put it on this device's clipboard only where the browser lets it.
|
|
540
|
+
const here = await navigator.clipboard?.writeText(got.text).then(() => true, () => false);
|
|
541
|
+
return toast(`${got.cut ? 'The first part of what' : 'What'} was copied on the computer${here ? ' is on this device\'s clipboard now' : ': copy it from the box'}`);
|
|
542
|
+
}
|
|
543
|
+
const text = clipText.value;
|
|
544
|
+
if (!text) return toast('Type or paste the text first');
|
|
545
|
+
await api('PUT', '/screen/clipboard', { text });
|
|
546
|
+
if (what === 'clip-paste' && rfb) {
|
|
547
|
+
const mod = MOD[status?.platform === 'darwin' ? 'cmd' : 'ctrl'];
|
|
548
|
+
rfb.sendKey(mod, null, true);
|
|
549
|
+
rfb.sendKey(key('v'), null);
|
|
550
|
+
rfb.sendKey(mod, null, false);
|
|
551
|
+
clipText.value = '';
|
|
552
|
+
return toast('Pasted on the computer');
|
|
553
|
+
}
|
|
554
|
+
toast("On the computer's clipboard");
|
|
555
|
+
}
|
|
556
|
+
|
|
342
557
|
dialog.addEventListener('click', async (e) => {
|
|
343
558
|
const key = e.target.closest('[data-screen-key]');
|
|
344
559
|
if (key && rfb) return rfb.sendKey(KEYS[key.dataset.screenKey], null);
|
|
@@ -359,7 +574,9 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
359
574
|
else if (what === 'move') {
|
|
360
575
|
moving = !moving;
|
|
361
576
|
layout();
|
|
362
|
-
} else if (what === '
|
|
577
|
+
} else if (what === 'pad') setPad(!pad);
|
|
578
|
+
else if (what === 'clip') showClip($('#screen-clip').hidden);
|
|
579
|
+
else if (what.startsWith('clip-')) await clip(what); else if (what === 'cancel') drop('You cancelled the sign-in');
|
|
363
580
|
else if (what === 'close') dialog.close();
|
|
364
581
|
} catch (err) {
|
|
365
582
|
toast(`Error: ${err.message}`, 6000);
|
|
@@ -421,6 +638,7 @@ export function initScreen({ api, esc, toast, $ }) {
|
|
|
421
638
|
const was = rfb;
|
|
422
639
|
rfb = null;
|
|
423
640
|
ended = null;
|
|
641
|
+
release();
|
|
424
642
|
try {
|
|
425
643
|
was?.disconnect();
|
|
426
644
|
} catch {}
|
package/public/setup.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
const STEPS = [
|
|
5
5
|
['agent', 'Start your first agent', 'Give it a request and a repo or folder; it works in its own branch.', '#new-btn', 'New agents'],
|
|
6
6
|
['service', 'Start at login', 'So AI Agent Manager and your agents come back by themselves after a restart.', '#settings-btn', 'Settings'],
|
|
7
|
-
['alerts', 'Get
|
|
7
|
+
['alerts', 'Get alerts', 'Hear in Slack or on your phone when an agent needs you, is stuck or finished.', '#alerts-btn', 'Alerts'],
|
|
8
8
|
['assistant', 'Let work come to you', 'The assistant, or triggers (a GitHub label, a webhook), start agents for new work.', '#assistant-btn', 'Assistant'],
|
|
9
9
|
['remote', 'Use it from your phone', 'Answer agents from anywhere on your network.', '#remote-btn', 'Remote access'],
|
|
10
10
|
['budget', 'Set a budget', 'An alert at 80% of an agent budget, and a daily limit.', '#spend-btn', 'Results'],
|
package/public/style.css
CHANGED
|
@@ -572,6 +572,14 @@ dialog::backdrop { background: rgba(0, 0, 0, .45); }
|
|
|
572
572
|
|
|
573
573
|
.needs { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; }
|
|
574
574
|
.needs.inbox { margin: 8px 10px 16px; }
|
|
575
|
+
.needs.inbox.one > .need:not(.now) { display: none; }
|
|
576
|
+
/* A sideways swipe on the card is ours (the next card): not the browser's, which on Android goes back a page. */
|
|
577
|
+
.needs.inbox.one { touch-action: pan-y; }
|
|
578
|
+
.needs.inbox.one > .need.now { min-height: 40vh; }
|
|
579
|
+
.inbox-counts { align-items: center; }
|
|
580
|
+
.inbox-counts .spacer { flex: 1; }
|
|
581
|
+
.inbox-step { display: inline-flex; gap: 6px; align-items: center; }
|
|
582
|
+
.inbox-step button { min-width: 34px; font-size: 16px; }
|
|
575
583
|
.need { border: 1px solid var(--border); border-left-width: 3px; border-radius: 6px; padding: 9px 11px; background: var(--panel); font-size: 13px; }
|
|
576
584
|
.need.prompt { border-left-color: var(--red); }
|
|
577
585
|
.need.question { border-left-color: var(--accent); }
|
|
@@ -645,6 +653,11 @@ pre.diff .meta { color: var(--muted); font-weight: 600; }
|
|
|
645
653
|
|
|
646
654
|
/* ---------- Human vs AI, plan review */
|
|
647
655
|
.ha-card { border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; margin: 10px 0; }
|
|
656
|
+
.upd-card h3 { margin: 0 0 6px; }
|
|
657
|
+
.upd-card textarea, .upd-card input { width: 100%; font: inherit; font-size: 16px; }
|
|
658
|
+
.upd-card label { display: block; margin: 6px 0; color: var(--muted); font-size: 12px; }
|
|
659
|
+
.upd-card textarea { resize: vertical; }
|
|
660
|
+
.upd-details { margin-top: 10px; border-top: 1px solid var(--border); padding-top: 6px; }
|
|
648
661
|
.ha-card.human { border-left: 3px solid var(--accent); }
|
|
649
662
|
.ha-card h4 { margin: 0 0 6px; }
|
|
650
663
|
.ha-card p { margin: 4px 0; }
|
|
@@ -968,6 +981,15 @@ input.inline { display: inline-block; width: 80px; padding: 1px 4px; }
|
|
|
968
981
|
.screen-view.zoomed { overflow: auto; }
|
|
969
982
|
.screen-stage { position: relative; width: 100%; height: 100%; }
|
|
970
983
|
.screen-stage > div:not(.screen-pan) { touch-action: none; }
|
|
984
|
+
.screen-clip { display: flex; gap: 6px; align-items: flex-start; padding: 6px 8px; border-bottom: 1px solid #30363d; }
|
|
985
|
+
.screen-clip[hidden] { display: none; }
|
|
986
|
+
.screen-clip textarea { flex: 1; min-width: 0; font-size: 16px; background: #161a22; color: #c9d1d9; border: 1px solid #30363d; border-radius: 6px; padding: 4px 6px; resize: vertical; }
|
|
987
|
+
.screen-clip-acts { display: flex; flex-wrap: wrap; gap: 4px; max-width: 45%; }
|
|
988
|
+
.screen-awake select { margin-left: 6px; }
|
|
989
|
+
.screen-pad { position: absolute; inset: 0; z-index: 2; }
|
|
990
|
+
.screen-pointer { position: absolute; z-index: 3; width: 0; height: 0; pointer-events: none; }
|
|
991
|
+
.screen-pointer::after { content: ''; position: absolute; left: -2px; top: -1px; width: 15px; height: 22px; background: no-repeat url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 15 22'%3E%3Cpath d='M2 1v17l4.2-4 2.9 6.6 2.6-1.1-2.9-6.5H14z' fill='%23000' stroke='%23fff' stroke-width='1.4' stroke-linejoin='round'/%3E%3C/svg%3E"); filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.6)); }
|
|
992
|
+
.screen-pointer.held::after { filter: drop-shadow(0 0 4px #4c8dff) drop-shadow(0 0 2px #4c8dff); }
|
|
971
993
|
.screen-pan { position: absolute; inset: 0; z-index: 2; cursor: grab; touch-action: pan-x pan-y; }
|
|
972
994
|
.screen-dialog .term-bar { flex-wrap: wrap; row-gap: 4px; }
|
|
973
995
|
.screen-keys button.on { background: var(--accent, #4c8dff); color: #fff; }
|
|
@@ -1209,6 +1231,25 @@ body.watching .layout { display: none; }
|
|
|
1209
1231
|
}
|
|
1210
1232
|
/* ---------- keyboard shortcuts */
|
|
1211
1233
|
kbd { display: inline-block; min-width: 1.6em; padding: 1px 5px; border: 1px solid var(--border); border-bottom-width: 2px; border-radius: 4px; background: var(--bg); font: 11.5px var(--mono); text-align: center; line-height: 1.4; }
|
|
1234
|
+
.files-dialog { width: min(680px, calc(100vw - 16px)); height: min(720px, calc(100dvh - 16px)); max-width: none; padding: 10px; }
|
|
1235
|
+
.files-dialog[open] { display: flex; flex-direction: column; gap: 6px; }
|
|
1236
|
+
.files-head, .files-bar { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
|
|
1237
|
+
.files-bar input:not([type]) { flex: 1; min-width: 120px; font-size: 16px; font-family: var(--mono); }
|
|
1238
|
+
.files-list { list-style: none; margin: 0; padding: 0; flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; border: 1px solid var(--border); border-radius: var(--radius); }
|
|
1239
|
+
.files-row { display: flex; gap: 8px; align-items: baseline; width: 100%; padding: 9px 10px; border: 0; border-bottom: 1px solid var(--border); border-radius: 0; background: none; color: var(--text); text-align: left; text-decoration: none; font: inherit; cursor: pointer; }
|
|
1240
|
+
.files-row:hover { background: var(--panel-2); }
|
|
1241
|
+
.files-name { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
|
1242
|
+
.files-row .hint { flex: none; font-size: 12px; }
|
|
1243
|
+
.files-empty { padding: 12px; }
|
|
1244
|
+
.files-foot { margin: 0; }
|
|
1245
|
+
.go-dialog { width: min(600px, calc(100vw - 16px)); max-width: none; margin-top: 8vh; padding: 8px; }
|
|
1246
|
+
.go-dialog input { width: 100%; font-size: 16px; padding: 8px 10px; }
|
|
1247
|
+
.go-list { list-style: none; margin: 6px 0 0; padding: 0; max-height: min(60vh, 520px); overflow-y: auto; overscroll-behavior: contain; }
|
|
1248
|
+
.go-list li { display: flex; gap: 8px; align-items: baseline; padding: 7px 8px; border-radius: 6px; cursor: pointer; }
|
|
1249
|
+
.go-list li.sel, .go-list li:hover { background: var(--panel-2); }
|
|
1250
|
+
.go-name { flex: none; font-weight: 600; max-width: 55%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1251
|
+
.go-hint { flex: 1; min-width: 0; color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1252
|
+
.go-kind { flex: none; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
|
|
1212
1253
|
.keys-dialog { max-width: 520px; width: calc(100% - 32px); }
|
|
1213
1254
|
.keys-dialog h4 { margin: 14px 0 4px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); }
|
|
1214
1255
|
.keys-dialog table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
|
@@ -1822,3 +1863,4 @@ table.eval-items tr.eval-na td { color: var(--muted); }
|
|
|
1822
1863
|
.screen-combo { width: 74px; padding: 2px 4px; font-size: 13px; background: #161a22; color: #c9d1d9; border: 1px solid #30363d; border-radius: 6px; }
|
|
1823
1864
|
.screen-tap { position: fixed; width: 28px; height: 28px; margin: -14px 0 0 -14px; border: 2px solid #4c8dff; border-radius: 50%; pointer-events: none; z-index: 5; animation: screen-tap 0.45s ease-out forwards; }
|
|
1824
1865
|
@keyframes screen-tap { from { transform: scale(0.4); opacity: 1; } to { transform: scale(1.4); opacity: 0; } }
|
|
1866
|
+
@media (max-width: 800px) { .needs.inbox.one .need-actions button { padding: 10px 14px; font-size: 15px; } }
|
package/src/announce.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Announce: what to tell the people who asked for the work, once an agent has something to show
|
|
2
|
+
// (a pull request opened) or is finished. One tool-less model call writes three things from the
|
|
3
|
+
// agent's live context: a short Slack message, a short email, and the details as a document both
|
|
4
|
+
// point to. They are drafts: you read them, change them and send them. Nothing here writes to a
|
|
5
|
+
// person by itself.
|
|
6
|
+
|
|
7
|
+
/** The parts of the document, in order, as the model is told to write them and as they are read back. */
|
|
8
|
+
const PARTS = ['Slack', 'Email', 'Details'];
|
|
9
|
+
|
|
10
|
+
export const announceSettings = (config = {}) => ({ auto: config.announce?.auto !== false });
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* What stage the work is at, for the wording: finished, something to show, or under way. From
|
|
14
|
+
* what is tracked, not from what the agent says about itself in passing.
|
|
15
|
+
*/
|
|
16
|
+
/** Finished: its brief says so, in its status or in its results. */
|
|
17
|
+
const done = (v) => v.brief?.status === 'done' || v.results?.outcome === 'done';
|
|
18
|
+
|
|
19
|
+
export function stageOf(v) {
|
|
20
|
+
const prs = (v.prs ?? []).filter((p) => p.source !== 'mentioned');
|
|
21
|
+
if (done(v) || (prs.length && prs.every((p) => p.state === 'MERGED'))) return 'finished';
|
|
22
|
+
if (prs.some((p) => p.state === 'OPEN' || p.state === 'MERGED')) return 'ready for review';
|
|
23
|
+
return 'in progress';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The moments an update is prepared for by itself: finished, and each pull request it opens. */
|
|
27
|
+
export function milestonesOf(v) {
|
|
28
|
+
const out = [];
|
|
29
|
+
for (const p of v.prs ?? []) if (p.source !== 'mentioned' && p.url && ['OPEN', 'MERGED'].includes(p.state)) out.push(`pr:${p.url}`);
|
|
30
|
+
if (done(v)) out.push('done');
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function updatePrompt({ intent, status, digest, repo, briefMarkdown, stage = 'in progress' }) {
|
|
35
|
+
return [
|
|
36
|
+
'Write an update for the people who asked for a piece of software work: the requester and other stakeholders. They did not follow the work and may not read code.',
|
|
37
|
+
`The work is ${stage}. Base everything only on the context below: the original ask, the conversation and actions, the repository changes and the brief.`,
|
|
38
|
+
'Write as the person responsible for the work, in the first person plural or neutral ("This is done", "We changed…"). No mention of an AI agent, its tools or this prompt.',
|
|
39
|
+
'',
|
|
40
|
+
'Output Markdown with exactly these three level-2 sections, in this order, and nothing before the first:',
|
|
41
|
+
'',
|
|
42
|
+
'## Slack',
|
|
43
|
+
'A message to paste into Slack: at most 5 lines of under 100 characters each, plain text. First line: what this is about and where it stands (finished, ready for review, in progress), in a few words. Then what was done, what is left or needed from the reader (a review, a decision, nothing), each in one line. No headings, no tables, no greeting, no sign-off, no links.',
|
|
44
|
+
'',
|
|
45
|
+
'## Email',
|
|
46
|
+
'First line exactly "To: <the name of whoever asked, if the context says; otherwise leave empty>". Second line "Subject: <under 70 characters, saying what and where it stands>". Then an empty line and the body in plain text: a one-line greeting ("Hi <first name>," or "Hi,"), then 3 to 6 short sentences or bullets ("- ") covering what was asked, what was done, the status, and what is needed from the reader with any date the context gives. No signature, no links.',
|
|
47
|
+
'',
|
|
48
|
+
'## Details',
|
|
49
|
+
'The full write-up the two messages point to, in Markdown, with these level-3 headings: "### What was asked", "### What was done" (specific: components, behaviour, pull requests by number and tickets by key), "### Status" (what is finished, tested, merged or released, and what is not), "### What is left" (or "Nothing."), "### Decisions and risks" (what needs a decision or could go wrong; or "None."), "### Links" (the pull requests, tickets and documents in the context, as a list).',
|
|
50
|
+
'',
|
|
51
|
+
'Rules:',
|
|
52
|
+
'- Say only what the context supports. Where it does not say, write "To be confirmed" in Details and leave it out of the two messages.',
|
|
53
|
+
'- Plain words for a reader outside the team: what changes for users or the business before how it was built. No file paths in the two messages.',
|
|
54
|
+
'- Do not claim more than was checked: "tests pass" only if the context shows them passing, "released" only if it was.',
|
|
55
|
+
'- The two messages stand on their own and do not repeat each other word for word; Details is 150 to 500 words.',
|
|
56
|
+
'',
|
|
57
|
+
'<agent_status>',
|
|
58
|
+
status,
|
|
59
|
+
'</agent_status>',
|
|
60
|
+
'<intent>',
|
|
61
|
+
intent || '(none)',
|
|
62
|
+
'</intent>',
|
|
63
|
+
'<conversation>',
|
|
64
|
+
digest || '(no conversation recorded yet)',
|
|
65
|
+
'</conversation>',
|
|
66
|
+
'<repository>',
|
|
67
|
+
repo || '(no repository changes recorded)',
|
|
68
|
+
'</repository>',
|
|
69
|
+
'<brief>',
|
|
70
|
+
briefMarkdown || '(no brief yet)',
|
|
71
|
+
'</brief>',
|
|
72
|
+
].join('\n');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The written update taken apart: { slack, to, subject, email, details }. A part the model left
|
|
77
|
+
* out is an empty string; a reply with none of them is all Details, so nothing written is lost.
|
|
78
|
+
*/
|
|
79
|
+
export function parseUpdate(markdown) {
|
|
80
|
+
const text = String(markdown ?? '').replace(/\r\n/g, '\n');
|
|
81
|
+
const parts = {};
|
|
82
|
+
const heads = [...text.matchAll(/^##[ \t]+(Slack|Email|Details)\b[^\n]*\n/gim)];
|
|
83
|
+
heads.forEach((m, i) => {
|
|
84
|
+
const name = PARTS.find((p) => p.toLowerCase() === m[1].toLowerCase());
|
|
85
|
+
parts[name] ??= text.slice(m.index + m[0].length, heads[i + 1]?.index ?? text.length).trim();
|
|
86
|
+
});
|
|
87
|
+
if (!heads.length) return { slack: '', to: '', subject: '', email: '', details: text.trim() };
|
|
88
|
+
let email = parts.Email ?? '';
|
|
89
|
+
const line = (label) => {
|
|
90
|
+
const m = new RegExp(`^\\**${label}:\\**[ \\t]*(.*)$`, 'im').exec(email);
|
|
91
|
+
if (!m) return '';
|
|
92
|
+
email = (email.slice(0, m.index) + email.slice(m.index + m[0].length)).trim();
|
|
93
|
+
return m[1].replace(/^[<(\[]|[>)\]]$/g, '').trim();
|
|
94
|
+
};
|
|
95
|
+
const to = line('To');
|
|
96
|
+
const subject = line('Subject');
|
|
97
|
+
// A fenced block around a message is the model being careful, not part of the message.
|
|
98
|
+
const bare = (s) => s.replace(/^```\w*\n([\s\S]*?)\n```$/m, '$1').trim();
|
|
99
|
+
return { slack: bare(parts.Slack ?? ''), to: /^(to be confirmed|unknown|none|n\/a|-)?$/i.test(to) ? '' : to, subject, email: bare(email), details: parts.Details ?? '' };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A message with the link to the details under it, when there is one. */
|
|
103
|
+
export const withLink = (text, link) => (link ? `${text.trim()}\n\nDetails: ${link}` : text.trim());
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Prepares an update by itself when an agent reaches a moment worth telling: it finished, or it
|
|
107
|
+
* opened a pull request. Only moments seen to happen while this runs count: what was already so
|
|
108
|
+
* when the daemon started (or when updates were turned on) is not announced after the fact.
|
|
109
|
+
*/
|
|
110
|
+
export class Announcer {
|
|
111
|
+
/** `prepare(agentId, milestone)` writes the update and resolves when it is there. */
|
|
112
|
+
constructor({ manager, config = {}, prepare, log = () => {} }) {
|
|
113
|
+
Object.assign(this, { manager, config, prepare, log });
|
|
114
|
+
this.seen = new Map(); // agent id -> the milestones it had already reached
|
|
115
|
+
manager.on('change', (a) => this.observe(a));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
get settings() {
|
|
119
|
+
return announceSettings(this.config);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
change(b = {}) {
|
|
123
|
+
if (typeof b.auto !== 'boolean') throw Object.assign(new Error('auto is true or false'), { status: 400 });
|
|
124
|
+
this.config.announce = { ...this.config.announce, auto: b.auto };
|
|
125
|
+
return this.config.announce;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
observe(a) {
|
|
129
|
+
if (!a?.id || ['general', 'assistant'].includes(a.kind) || a.hunting || a.reviewing) return;
|
|
130
|
+
const now = milestonesOf(a);
|
|
131
|
+
const before = this.seen.get(a.id);
|
|
132
|
+
this.seen.set(a.id, new Set([...(before ?? []), ...now]));
|
|
133
|
+
if (!before || !this.settings.auto) return;
|
|
134
|
+
const fresh = now.filter((m) => !before.has(m));
|
|
135
|
+
if (!fresh.length) return;
|
|
136
|
+
// Finished says more than the pull request that came with it: one update for both.
|
|
137
|
+
const milestone = fresh.includes('done') ? 'done' : fresh.at(-1);
|
|
138
|
+
this.prepare(a.id, milestone).catch((e) => this.log(`update for ${a.name}: ${e.message.slice(0, 160)}`));
|
|
139
|
+
}
|
|
140
|
+
}
|
package/src/awake.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Awake: a sleeping computer runs no agents and cannot be reached from the phone. While this is
|
|
2
|
+
// on, the computer is kept from going to sleep by itself: always, or only while an agent works.
|
|
3
|
+
// The display may still sleep and lock, and closing a laptop's lid still puts it to sleep.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
|
|
7
|
+
export const AWAKE_MODES = ['off', 'working', 'always'];
|
|
8
|
+
const GRACE_MS = 5 * 60_000; // after the last agent stops working: its next turn is often minutes away
|
|
9
|
+
|
|
10
|
+
const fail = (status, message) => Object.assign(new Error(message), { status });
|
|
11
|
+
|
|
12
|
+
export const awakeSettings = (config) => ({ mode: AWAKE_MODES.includes(config.awake?.mode) ? config.awake.mode : 'off' });
|
|
13
|
+
|
|
14
|
+
/** What keeps this computer awake for as long as it runs, and ends with this process: [command, args], or null. */
|
|
15
|
+
export function keeper(platform = process.platform, exists = fs.existsSync) {
|
|
16
|
+
// -i: no idle sleep. -w: until this process is gone, so nothing is left behind.
|
|
17
|
+
if (platform === 'darwin' && exists('/usr/bin/caffeinate')) return ['/usr/bin/caffeinate', ['-i', '-w', String(process.pid)]];
|
|
18
|
+
const inhibit = ['/usr/bin/systemd-inhibit', '/bin/systemd-inhibit'].find((p) => exists(p));
|
|
19
|
+
if (platform === 'linux' && inhibit) return [inhibit, ['--what=idle:sleep', '--who=AI Agent Manager', '--why=Agents are working, or the computer is reached from a phone', 'tail', '--pid', String(process.pid), '-f', '/dev/null']];
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class Awake {
|
|
24
|
+
/** `working()` says whether an agent is working now. `run` and `how` stand in for the system's in tests. */
|
|
25
|
+
constructor({ config, working = () => false, how = keeper(), run = (cmd, args) => spawn(cmd, args, { stdio: 'ignore' }), now = () => Date.now(), log = () => {}, timer = true }) {
|
|
26
|
+
Object.assign(this, { config, working, how, run, now, log });
|
|
27
|
+
this.child = null;
|
|
28
|
+
this.workedAt = 0;
|
|
29
|
+
if (timer) {
|
|
30
|
+
this.timer = setInterval(() => this.tick(), 20_000);
|
|
31
|
+
this.timer.unref();
|
|
32
|
+
}
|
|
33
|
+
this.tick();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get settings() {
|
|
37
|
+
return awakeSettings(this.config);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
status() {
|
|
41
|
+
return { ...this.settings, supported: Boolean(this.how), holding: Boolean(this.child) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
change(b = {}) {
|
|
45
|
+
if (!AWAKE_MODES.includes(b.mode)) throw fail(400, `mode is one of: ${AWAKE_MODES.join(', ')}`);
|
|
46
|
+
if (b.mode !== 'off' && !this.how) throw fail(400, 'This computer has nothing here to keep it awake with (macOS: caffeinate; Linux: systemd-inhibit)');
|
|
47
|
+
this.config.awake = { mode: b.mode };
|
|
48
|
+
this.tick();
|
|
49
|
+
return this.config.awake;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Hold the computer awake, or let go, as the mode and the agents say. */
|
|
53
|
+
tick() {
|
|
54
|
+
const { mode } = this.settings;
|
|
55
|
+
if (mode === 'working' && this.working()) this.workedAt = this.now();
|
|
56
|
+
const want = Boolean(this.how) && (mode === 'always' || (mode === 'working' && this.workedAt > 0 && this.now() - this.workedAt < GRACE_MS));
|
|
57
|
+
if (want && !this.child) {
|
|
58
|
+
const child = this.run(...this.how);
|
|
59
|
+
this.child = child;
|
|
60
|
+
child.on?.('error', () => this.child === child && (this.child = null));
|
|
61
|
+
child.on?.('exit', () => this.child === child && (this.child = null));
|
|
62
|
+
this.log('awake: keeping this computer from sleeping');
|
|
63
|
+
} else if (!want && this.child) this.stop();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
stop() {
|
|
67
|
+
const child = this.child;
|
|
68
|
+
this.child = null;
|
|
69
|
+
if (!child) return;
|
|
70
|
+
try {
|
|
71
|
+
child.kill();
|
|
72
|
+
} catch {}
|
|
73
|
+
this.log('awake: the computer may sleep again');
|
|
74
|
+
}
|
|
75
|
+
}
|