sideby 0.28.3 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +12 -0
- package/dist/src/cli/commands.js +337 -13
- package/dist/src/cli/json-schemas.js +87 -1
- package/dist/src/cli/main.js +65 -4
- package/dist/src/core/config.d.ts +25 -0
- package/dist/src/core/config.js +34 -0
- package/dist/src/core/fs-safe.d.ts +22 -1
- package/dist/src/core/fs-safe.js +68 -1
- package/dist/src/core/handoff-run.d.ts +2 -0
- package/dist/src/core/handoff-run.js +12 -6
- package/dist/src/core/launch.d.ts +6 -1
- package/dist/src/core/live-sessions.d.ts +2 -0
- package/dist/src/core/messages.d.ts +2 -0
- package/dist/src/core/messages.js +12 -34
- package/dist/src/core/network.d.ts +5 -2
- package/dist/src/core/network.js +15 -45
- package/dist/src/core/run-link.d.ts +6 -1
- package/dist/src/core/run-link.js +62 -22
- package/dist/src/core/search-catalog.d.ts +1 -1
- package/dist/src/core/search-catalog.js +37 -0
- package/dist/src/core/session-handoffs.d.ts +22 -0
- package/dist/src/core/session-handoffs.js +110 -0
- package/dist/src/core/session-hooks.d.ts +33 -0
- package/dist/src/core/session-hooks.js +92 -0
- package/dist/src/core/session-select.d.ts +18 -3
- package/dist/src/core/session-select.js +82 -8
- package/dist/src/core/unattended-ended.d.ts +62 -0
- package/dist/src/core/unattended-ended.js +275 -0
- package/dist/src/core/unattended-pending.d.ts +56 -0
- package/dist/src/core/unattended-pending.js +182 -0
- package/dist/src/core/unattended-state.d.ts +129 -0
- package/dist/src/core/unattended-state.js +373 -0
- package/dist/src/core/unattended.d.ts +142 -0
- package/dist/src/core/unattended.js +349 -0
- package/dist/src/panel/background.js +8 -0
- package/dist/src/panel/handler.d.ts +37 -0
- package/dist/src/panel/handler.js +156 -2
- package/dist/src/panel/i18n.d.ts +97 -0
- package/dist/src/panel/i18n.js +194 -0
- package/dist/src/panel/page-logic.d.ts +129 -0
- package/dist/src/panel/page-logic.js +166 -0
- package/dist/src/panel/page-script.js +638 -7
- package/dist/src/panel/page-styles.js +69 -0
- package/dist/src/panel/page.js +2 -0
- package/dist/src/plugins/bus.js +1 -0
- package/dist/src/runtime.d.ts +17 -1
- package/dist/src/runtime.js +78 -15
- package/dist/src/types.d.ts +48 -0
- package/dist/src/unattended/hook.d.ts +46 -0
- package/dist/src/unattended/hook.js +288 -0
- package/package.json +1 -1
- package/schemas/config.json +76 -0
- package/schemas/messages.json +4 -0
- package/schemas/send.json +4 -0
- package/schemas/sessions-copy.json +4 -0
- package/schemas/sessions-open-run.json +4 -0
- package/schemas/sessions.json +7 -0
- package/schemas/unattended-defer.json +143 -0
- package/schemas/unattended-pending.json +154 -0
- package/schemas/unattended.json +291 -0
- package/skills/sideby/SKILL.md +3 -2
- package/skills/sideby/references/sessions.md +1 -1
- package/skills/sideby/references/unattended.md +58 -0
|
@@ -1,20 +1,56 @@
|
|
|
1
1
|
import { UserError } from './errors.js';
|
|
2
|
-
import { listLiveSessions, shortId } from './live-sessions.js';
|
|
2
|
+
import { accountLabels, listLiveSessions, shortId, } from './live-sessions.js';
|
|
3
|
+
import { chainIdsMatching, laterHops, readHandoffChains, withHandoffs, } from './session-handoffs.js';
|
|
3
4
|
const COPY = { verb: 'copy', command: (id) => `sideby sessions copy ${id}` };
|
|
5
|
+
/** The one session id of a Handoff chain `target` names, when it names exactly one and a later hop exists. */
|
|
6
|
+
function handedOverId(target, chains, next) {
|
|
7
|
+
const ids = chainIdsMatching(chains, target);
|
|
8
|
+
if (ids.length > 1) {
|
|
9
|
+
const rows = ids.map((id) => ` ${next.command(id)}`).join('\n');
|
|
10
|
+
throw new UserError(`${target} matches ${ids.length} sessions that were handed over; ${next.verb} one by its full id:\n${rows}`, { code: 'several-sessions' });
|
|
11
|
+
}
|
|
12
|
+
const id = ids[0];
|
|
13
|
+
return id && laterHops(chains, id).length ? id : undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Follows a session id an Auto Handoff chain passed on: the newest later hop that is a Live Session. Undefined when
|
|
17
|
+
* the id is in no chain or is its last hop; a UserError naming the last hop when no later hop still runs.
|
|
18
|
+
*/
|
|
19
|
+
function followHandoff(target, sessions, next, handoffs) {
|
|
20
|
+
const from = handedOverId(target, handoffs.chains, next);
|
|
21
|
+
if (!from)
|
|
22
|
+
return undefined;
|
|
23
|
+
const later = laterHops(handoffs.chains, from);
|
|
24
|
+
for (const id of later) {
|
|
25
|
+
const live = sessions.find((s) => s.sessionId === id);
|
|
26
|
+
if (live)
|
|
27
|
+
return { session: live, handedOverFrom: from };
|
|
28
|
+
}
|
|
29
|
+
const last = later[0];
|
|
30
|
+
const account = handoffs.accountOf?.(last);
|
|
31
|
+
throw new UserError(`${shortId(from)} was handed over to session ${last}${account ? ` of ${account}` : ''}, which is not running now; run \`sideby sessions\` to see the running sessions`, { code: 'no-session' });
|
|
32
|
+
}
|
|
4
33
|
/**
|
|
5
34
|
* The one Session `target` names: a session id (or its first 8 or more characters), else an Account whose single
|
|
6
35
|
* Live Session it is. Several Sessions, or none, are a UserError that says what to run next.
|
|
7
36
|
*/
|
|
8
37
|
export function pickSession(target, sessions, account,
|
|
9
38
|
/** How the candidates are offered; `sessions copy` when left out. */
|
|
10
|
-
next = COPY
|
|
39
|
+
next = COPY,
|
|
40
|
+
/** The Handoff chains, and the Account label of a session id whose record the Host still has. */
|
|
41
|
+
handoffs = { chains: [] }) {
|
|
11
42
|
const byId = sessions.filter((s) => s.sessionId === target || (target.length >= 8 && s.sessionId.startsWith(target)));
|
|
12
43
|
if (byId.length === 1)
|
|
13
|
-
return byId[0];
|
|
44
|
+
return { session: byId[0] };
|
|
14
45
|
const list = byId.length ? byId : account ? sessions.filter((s) => s.account === account.ref) : [];
|
|
15
46
|
if (list.length === 1)
|
|
16
|
-
return list[0];
|
|
47
|
+
return { session: list[0] };
|
|
17
48
|
if (!list.length) {
|
|
49
|
+
if (!account) {
|
|
50
|
+
const followed = followHandoff(target, sessions, next, handoffs);
|
|
51
|
+
if (followed)
|
|
52
|
+
return followed;
|
|
53
|
+
}
|
|
18
54
|
if (account)
|
|
19
55
|
throw new UserError(`${account.label} has no running session now; start one with \`sideby run ${account.label}\`, or run \`sideby sessions\` to see the others`, { code: 'no-session' });
|
|
20
56
|
throw new UserError(`no running session or account named ${target}; run \`sideby sessions\` to see the running sessions`, { code: 'no-session' });
|
|
@@ -27,11 +63,14 @@ next = COPY) {
|
|
|
27
63
|
}
|
|
28
64
|
/**
|
|
29
65
|
* Lists the Live Sessions and picks the one `target` names, reading `target` as an Account (ref or alias) when it is
|
|
30
|
-
* one
|
|
31
|
-
* listing
|
|
66
|
+
* one, and following a Handoff chain when it is a session id that no longer runs (ADR-0057). `onListed` sees the
|
|
67
|
+
* listing before the pick, so its problems can be shown also when the pick fails; the listing is returned too, for
|
|
68
|
+
* callers that look for the sending Session in it. Its Sessions carry `handedOverFrom` where a chain led to them.
|
|
32
69
|
*/
|
|
33
70
|
export async function selectSession(rt, target, opts = {}) {
|
|
34
|
-
const
|
|
71
|
+
const raw = await listLiveSessions(rt, {}, opts.deps);
|
|
72
|
+
const chains = await readHandoffChains(rt.paths.stateDir);
|
|
73
|
+
const listed = { ...raw, sessions: withHandoffs(chains, raw.sessions) };
|
|
35
74
|
opts.onListed?.(listed);
|
|
36
75
|
let account;
|
|
37
76
|
try {
|
|
@@ -40,5 +79,40 @@ export async function selectSession(rt, target, opts = {}) {
|
|
|
40
79
|
catch {
|
|
41
80
|
// not an Account: a session id
|
|
42
81
|
}
|
|
43
|
-
|
|
82
|
+
const handoffs = { chains };
|
|
83
|
+
if (!account) {
|
|
84
|
+
// Only when the pick would end at a chain whose later hops all ended: which Account still has the last one.
|
|
85
|
+
const last = endedLastHop(target, listed.sessions, chains);
|
|
86
|
+
if (last) {
|
|
87
|
+
const label = await recordAccount(rt, last);
|
|
88
|
+
handoffs.accountOf = (id) => (id === last ? label : undefined);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const picked = pickSession(target, listed.sessions, account, opts.next, handoffs);
|
|
92
|
+
return { ...picked, listed };
|
|
93
|
+
}
|
|
94
|
+
/** The last hop of the chain `target` names, when neither `target` nor any later hop is a Live Session. */
|
|
95
|
+
function endedLastHop(target, sessions, chains) {
|
|
96
|
+
if (sessions.some((s) => s.sessionId === target || (target.length >= 8 && s.sessionId.startsWith(target))))
|
|
97
|
+
return undefined;
|
|
98
|
+
const ids = chainIdsMatching(chains, target);
|
|
99
|
+
if (ids.length !== 1)
|
|
100
|
+
return undefined;
|
|
101
|
+
const later = laterHops(chains, ids[0]);
|
|
102
|
+
if (!later.length || later.some((id) => sessions.some((s) => s.sessionId === id)))
|
|
103
|
+
return undefined;
|
|
104
|
+
return later[0];
|
|
105
|
+
}
|
|
106
|
+
/** The label of the Account whose Host last wrote (else last started) session `id`; undefined when none did. */
|
|
107
|
+
async function recordAccount(rt, id) {
|
|
108
|
+
const accounts = await rt.accounts();
|
|
109
|
+
let best;
|
|
110
|
+
for (const a of accounts) {
|
|
111
|
+
const family = rt.families.get(a.family);
|
|
112
|
+
const at = (await family?.sessionWrittenAt?.(a, id).catch(() => undefined)) ??
|
|
113
|
+
(await family?.sessionStartedAt?.(a, id).catch(() => undefined));
|
|
114
|
+
if (at !== undefined && (!best || at > best.at))
|
|
115
|
+
best = { ref: a.ref, at };
|
|
116
|
+
}
|
|
117
|
+
return best && (accountLabels(rt, accounts).get(best.ref) ?? best.ref);
|
|
44
118
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Env, UnattendedEndedContext } from '../types.ts';
|
|
2
|
+
import { type Paths } from './paths.ts';
|
|
3
|
+
export type UnattendedEndedEmit = (ctx: UnattendedEndedContext) => Promise<void> | void;
|
|
4
|
+
interface Seen {
|
|
5
|
+
startedAt: string;
|
|
6
|
+
reason: 'slot' | 'manual';
|
|
7
|
+
}
|
|
8
|
+
/** An event found and not yet delivered. */
|
|
9
|
+
interface Notice {
|
|
10
|
+
id: string;
|
|
11
|
+
startedAt: string;
|
|
12
|
+
endedAt: string;
|
|
13
|
+
reason: 'slot' | 'manual';
|
|
14
|
+
late?: true;
|
|
15
|
+
/** When a process took it to deliver; another takes it again once this is older than the lease. */
|
|
16
|
+
claimedAt?: string;
|
|
17
|
+
}
|
|
18
|
+
interface Checkpoint {
|
|
19
|
+
/** When a process last looked: stretches that ended after this are still to be found. */
|
|
20
|
+
checkedAt: string;
|
|
21
|
+
/** The stretch running then, as that process saw it start. */
|
|
22
|
+
current?: Seen;
|
|
23
|
+
/** Ids of the events delivered, newest last. */
|
|
24
|
+
emitted: string[];
|
|
25
|
+
/** Events found and not yet delivered, oldest first. */
|
|
26
|
+
outbox: Notice[];
|
|
27
|
+
}
|
|
28
|
+
/** At most this many events wait in the outbox; a look that finds more takes the oldest and leaves the rest. */
|
|
29
|
+
export declare const MAX_OUTBOX = 50;
|
|
30
|
+
/**
|
|
31
|
+
* Under the lock: finds the stretches that ended since the last look (oldest first, up to the outbox's room), adds
|
|
32
|
+
* them to the outbox, and claims every event in it that no other process holds. Returns the claimed events, oldest
|
|
33
|
+
* first; never throws.
|
|
34
|
+
*/
|
|
35
|
+
export declare function claimUnattendedEnded(paths: Paths, now?: Date): Promise<Notice[]>;
|
|
36
|
+
/**
|
|
37
|
+
* Runs `emit` for each claimed event, with the Pending Decisions kept during it that are still open, then marks the
|
|
38
|
+
* ones whose `emit` returned as delivered. One whose `emit` threw stays in the outbox and is tried again after the
|
|
39
|
+
* lease. Never throws.
|
|
40
|
+
*/
|
|
41
|
+
export declare function deliverUnattendedEnded(paths: Paths, notices: readonly Notice[], emit: UnattendedEndedEmit, now?: Date): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* Looks once: claims what ended since the last look and what still waits to be delivered, then delivers it. Cheap
|
|
44
|
+
* when the feature was never used (one read of the config). Never throws.
|
|
45
|
+
*/
|
|
46
|
+
export declare function checkUnattendedEnded(paths: Paths, emit: UnattendedEndedEmit, now?: Date): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* The background Panel's watch (spec §3.37): looks now and every 30 seconds until the returned function stops it.
|
|
49
|
+
* Only a standalone Panel server starts one; a Panel embedded in a Portal through `createPanelHandler` does not.
|
|
50
|
+
*/
|
|
51
|
+
export declare function watchUnattendedEnded(paths: Paths, emit: UnattendedEndedEmit, everyMs?: number): () => void;
|
|
52
|
+
/**
|
|
53
|
+
* A command's look when it starts: waits only for the look itself (two small file reads when nothing ended), and
|
|
54
|
+
* returns the delivery of what it found as `emitted`, which runs alongside the command. Plugins are loaded only when
|
|
55
|
+
* there is something to deliver; an event whose delivery does not finish is delivered by a later look.
|
|
56
|
+
*/
|
|
57
|
+
export declare function noticeUnattendedEnded(env: Env): Promise<{
|
|
58
|
+
emitted: Promise<void>;
|
|
59
|
+
}>;
|
|
60
|
+
/** Reads the checkpoint, for tests and diagnostics. */
|
|
61
|
+
export declare function readEndedCheckpoint(stateDir: string): Promise<Checkpoint | undefined>;
|
|
62
|
+
export {};
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// The end of a stretch of Unattended Mode (spec §3.37, ADR-0058): the first sideby process that notices it emits the
|
|
2
|
+
// plugin event `unattended.ended`. The background Panel looks every 30 seconds and other commands look when they
|
|
3
|
+
// start; none of the session hooks does. `<state>/unattended/ended.json` keeps when it last looked, the stretch it saw
|
|
4
|
+
// running then, the events found but not yet delivered (the outbox) and the ids of those delivered.
|
|
5
|
+
//
|
|
6
|
+
// Delivery is at least once: an event stays in the outbox until the plugin hooks have run for it, and one a process
|
|
7
|
+
// claimed but did not finish (it crashed, or was ended) is tried again after a lease. Each event has a stable `id`, so
|
|
8
|
+
// a plugin can skip one it has seen. Stretches that ended while no sideby process ran are found from the last look
|
|
9
|
+
// onward, oldest first, at most 50 a look; the rest wait for the next look.
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { writeFileAtomic } from './fs-safe.js';
|
|
12
|
+
import { takeFileLock } from './lock.js';
|
|
13
|
+
import { resolvePaths } from './paths.js';
|
|
14
|
+
import { listPendingDecisions } from './unattended-pending.js';
|
|
15
|
+
import { ensureUnattendedDir, readSmallJson, readUnattendedConfig, readUnattendedOverride, unattendedDir, unattendedTimeline, } from './unattended-state.js';
|
|
16
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
17
|
+
/** Noticed this long after its end, the event says `late`. */
|
|
18
|
+
const LATE_MS = 12 * 60 * 60 * 1000;
|
|
19
|
+
/** A look that changes nothing is written down at most this often. */
|
|
20
|
+
const REWRITE_MS = 60 * 1000;
|
|
21
|
+
const KEEP_EMITTED = 100;
|
|
22
|
+
/** At most this many events wait in the outbox; a look that finds more takes the oldest and leaves the rest. */
|
|
23
|
+
export const MAX_OUTBOX = 50;
|
|
24
|
+
/** A claimed event not delivered after this long is taken again (its process is gone or stuck). */
|
|
25
|
+
const LEASE_MS = 2 * 60 * 1000;
|
|
26
|
+
const file = (stateDir) => join(unattendedDir(stateDir), 'ended.json');
|
|
27
|
+
const lockFile = (dir) => join(dir, 'ended.lock');
|
|
28
|
+
const LOCK = { staleMs: 30_000, beatMs: 10_000 };
|
|
29
|
+
const isTime = (v) => typeof v === 'string' && Number.isFinite(Date.parse(v));
|
|
30
|
+
const isReason = (v) => v === 'slot' || v === 'manual';
|
|
31
|
+
function parseNotice(value) {
|
|
32
|
+
if (!value || typeof value !== 'object')
|
|
33
|
+
return undefined;
|
|
34
|
+
const v = value;
|
|
35
|
+
if (typeof v.id !== 'string' || !isTime(v.startedAt) || !isTime(v.endedAt) || !isReason(v.reason))
|
|
36
|
+
return undefined;
|
|
37
|
+
return {
|
|
38
|
+
id: v.id,
|
|
39
|
+
startedAt: v.startedAt,
|
|
40
|
+
endedAt: v.endedAt,
|
|
41
|
+
reason: v.reason,
|
|
42
|
+
...(v.late === true ? { late: true } : {}),
|
|
43
|
+
...(isTime(v.claimedAt) ? { claimedAt: v.claimedAt } : {}),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function parseCheckpoint(value) {
|
|
47
|
+
if (!value || typeof value !== 'object')
|
|
48
|
+
return undefined;
|
|
49
|
+
const v = value;
|
|
50
|
+
if (!isTime(v.checkedAt))
|
|
51
|
+
return undefined;
|
|
52
|
+
const c = v.current;
|
|
53
|
+
const current = c && isTime(c.startedAt) && isReason(c.reason) ? { startedAt: c.startedAt, reason: c.reason } : undefined;
|
|
54
|
+
const emitted = Array.isArray(v.emitted) ? v.emitted.filter((e) => typeof e === 'string') : [];
|
|
55
|
+
const outbox = (Array.isArray(v.outbox) ? v.outbox : [])
|
|
56
|
+
.map(parseNotice)
|
|
57
|
+
.filter((n) => n !== undefined);
|
|
58
|
+
return {
|
|
59
|
+
checkedAt: v.checkedAt,
|
|
60
|
+
...(current ? { current } : {}),
|
|
61
|
+
emitted: emitted.slice(-KEEP_EMITTED),
|
|
62
|
+
outbox: outbox.slice(0, MAX_OUTBOX),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
66
|
+
/** The event's id: its start and end, which do not change once it is found. */
|
|
67
|
+
const eventId = (startedAt, endedAt) => `${iso(startedAt)}/${iso(endedAt)}`;
|
|
68
|
+
async function writeCheckpoint(stateDir, c) {
|
|
69
|
+
await writeFileAtomic(file(stateDir), `${JSON.stringify(c)}\n`, 0o600);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Under the lock: finds the stretches that ended since the last look (oldest first, up to the outbox's room), adds
|
|
73
|
+
* them to the outbox, and claims every event in it that no other process holds. Returns the claimed events, oldest
|
|
74
|
+
* first; never throws.
|
|
75
|
+
*/
|
|
76
|
+
export async function claimUnattendedEnded(paths, now = new Date()) {
|
|
77
|
+
try {
|
|
78
|
+
const { configured, schedule } = await readUnattendedConfig(paths.configFile);
|
|
79
|
+
if (!configured && (await readSmallJson(file(paths.stateDir), 256 * 1024)) === undefined)
|
|
80
|
+
return [];
|
|
81
|
+
const dir = await ensureUnattendedDir(paths.stateDir);
|
|
82
|
+
const release = await takeFileLock(lockFile(dir), LOCK);
|
|
83
|
+
// Another process is looking right now and will report what there is.
|
|
84
|
+
if (!release)
|
|
85
|
+
return [];
|
|
86
|
+
try {
|
|
87
|
+
const before = parseCheckpoint(await readSmallJson(file(paths.stateDir), 256 * 1024));
|
|
88
|
+
const t = now.getTime();
|
|
89
|
+
// A clock that went back: look again once it has caught up.
|
|
90
|
+
if (before && Date.parse(before.checkedAt) > t)
|
|
91
|
+
return [];
|
|
92
|
+
const override = await readUnattendedOverride(paths.stateDir);
|
|
93
|
+
const last = before ? Date.parse(before.checkedAt) : t;
|
|
94
|
+
const from = Math.min(last, before?.current ? Date.parse(before.current.startedAt) : last) - 9 * DAY_MS;
|
|
95
|
+
const timeline = unattendedTimeline(schedule, override, from, t + DAY_MS);
|
|
96
|
+
const ended = [];
|
|
97
|
+
let current;
|
|
98
|
+
if (before) {
|
|
99
|
+
// The stretch seen running at the last look: it went on as long as the Schedule and the manual state now say;
|
|
100
|
+
// when they no longer cover that moment (the user turned it off), it ended now.
|
|
101
|
+
const seen = before.current;
|
|
102
|
+
const cont = seen ? timeline.find((s) => s.start <= last && last < s.end) : undefined;
|
|
103
|
+
if (seen) {
|
|
104
|
+
const end = cont ? cont.end : t;
|
|
105
|
+
if (end <= t)
|
|
106
|
+
ended.push({ startedAt: Date.parse(seen.startedAt), endedAt: end, reason: seen.reason });
|
|
107
|
+
else
|
|
108
|
+
current = seen;
|
|
109
|
+
}
|
|
110
|
+
for (const s of timeline) {
|
|
111
|
+
if (s === cont || s.end <= last || s.start > t)
|
|
112
|
+
continue;
|
|
113
|
+
// A stretch the last look did not see running counts from that look, at the earliest.
|
|
114
|
+
const start = Math.max(s.start, last);
|
|
115
|
+
if (s.end <= t) {
|
|
116
|
+
if (start < s.end)
|
|
117
|
+
ended.push({ startedAt: start, endedAt: s.end, reason: s.reason });
|
|
118
|
+
}
|
|
119
|
+
else if (!current)
|
|
120
|
+
current = { startedAt: iso(start), reason: s.reason };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
const running = timeline.find((s) => s.start <= t && t < s.end);
|
|
125
|
+
if (running)
|
|
126
|
+
current = { startedAt: iso(running.start), reason: running.reason };
|
|
127
|
+
}
|
|
128
|
+
ended.sort((a, b) => a.endedAt - b.endedAt);
|
|
129
|
+
const outbox = [...(before?.outbox ?? [])];
|
|
130
|
+
const emitted = [...(before?.emitted ?? [])];
|
|
131
|
+
const known = new Set([...emitted, ...outbox.map((n) => n.id)]);
|
|
132
|
+
const fresh = ended.filter((e) => !known.has(eventId(e.startedAt, e.endedAt)));
|
|
133
|
+
const room = MAX_OUTBOX - outbox.length;
|
|
134
|
+
let checkedAt = t;
|
|
135
|
+
if (fresh.length > room) {
|
|
136
|
+
// More than fit: take the oldest and look again from the end of the last one taken, so none is lost.
|
|
137
|
+
fresh.length = Math.max(0, room);
|
|
138
|
+
const lastTaken = fresh.at(-1);
|
|
139
|
+
checkedAt = lastTaken ? lastTaken.endedAt : last;
|
|
140
|
+
current = lastTaken ? undefined : before?.current;
|
|
141
|
+
}
|
|
142
|
+
for (const e of fresh)
|
|
143
|
+
outbox.push({
|
|
144
|
+
id: eventId(e.startedAt, e.endedAt),
|
|
145
|
+
startedAt: iso(e.startedAt),
|
|
146
|
+
endedAt: iso(e.endedAt),
|
|
147
|
+
reason: e.reason,
|
|
148
|
+
...(t - e.endedAt > LATE_MS ? { late: true } : {}),
|
|
149
|
+
});
|
|
150
|
+
const claimed = [];
|
|
151
|
+
for (const n of outbox)
|
|
152
|
+
if (!n.claimedAt || t - Date.parse(n.claimedAt) > LEASE_MS || Date.parse(n.claimedAt) > t) {
|
|
153
|
+
n.claimedAt = iso(t);
|
|
154
|
+
claimed.push(n);
|
|
155
|
+
}
|
|
156
|
+
const next = { checkedAt: iso(checkedAt), ...(current ? { current } : {}), emitted, outbox };
|
|
157
|
+
const same = before &&
|
|
158
|
+
!fresh.length &&
|
|
159
|
+
!claimed.length &&
|
|
160
|
+
JSON.stringify(before.current ?? null) === JSON.stringify(current ?? null) &&
|
|
161
|
+
t - last < REWRITE_MS;
|
|
162
|
+
// Claimed before any plugin runs: another process does not take the same events while the lease holds.
|
|
163
|
+
if (!same)
|
|
164
|
+
await writeCheckpoint(paths.stateDir, next);
|
|
165
|
+
return claimed.map(({ claimedAt: _, ...n }) => n);
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
await release();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return [];
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Runs `emit` for each claimed event, with the Pending Decisions kept during it that are still open, then marks the
|
|
177
|
+
* ones whose `emit` returned as delivered. One whose `emit` threw stays in the outbox and is tried again after the
|
|
178
|
+
* lease. Never throws.
|
|
179
|
+
*/
|
|
180
|
+
export async function deliverUnattendedEnded(paths, notices, emit, now = new Date()) {
|
|
181
|
+
if (!notices.length)
|
|
182
|
+
return;
|
|
183
|
+
const pending = await listPendingDecisions(paths.stateDir, { now }).catch(() => []);
|
|
184
|
+
const done = [];
|
|
185
|
+
for (const n of notices) {
|
|
186
|
+
const [start, end] = [Date.parse(n.startedAt), Date.parse(n.endedAt)];
|
|
187
|
+
try {
|
|
188
|
+
await emit({
|
|
189
|
+
id: n.id,
|
|
190
|
+
startedAt: n.startedAt,
|
|
191
|
+
endedAt: n.endedAt,
|
|
192
|
+
reason: n.reason,
|
|
193
|
+
...(n.late ? { late: true } : {}),
|
|
194
|
+
pending: pending.filter((p) => {
|
|
195
|
+
const at = Date.parse(p.at);
|
|
196
|
+
return at >= start && at <= end;
|
|
197
|
+
}),
|
|
198
|
+
});
|
|
199
|
+
done.push(n.id);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
// Not delivered: it stays in the outbox and is tried again.
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (!done.length)
|
|
206
|
+
return;
|
|
207
|
+
try {
|
|
208
|
+
const dir = await ensureUnattendedDir(paths.stateDir);
|
|
209
|
+
const release = await takeFileLock(lockFile(dir), { ...LOCK, wait: { timeoutMs: 5_000, pollMs: 50 } });
|
|
210
|
+
// Not marked: the lease runs out and they are delivered again, which `id` lets a plugin notice.
|
|
211
|
+
if (!release)
|
|
212
|
+
return;
|
|
213
|
+
try {
|
|
214
|
+
const c = parseCheckpoint(await readSmallJson(file(paths.stateDir), 256 * 1024));
|
|
215
|
+
if (!c)
|
|
216
|
+
return;
|
|
217
|
+
const ids = new Set(done);
|
|
218
|
+
c.outbox = c.outbox.filter((n) => !ids.has(n.id));
|
|
219
|
+
c.emitted = [...c.emitted.filter((id) => !ids.has(id)), ...done].slice(-KEEP_EMITTED);
|
|
220
|
+
await writeCheckpoint(paths.stateDir, c);
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
await release();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
// as above
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Looks once: claims what ended since the last look and what still waits to be delivered, then delivers it. Cheap
|
|
232
|
+
* when the feature was never used (one read of the config). Never throws.
|
|
233
|
+
*/
|
|
234
|
+
export async function checkUnattendedEnded(paths, emit, now = new Date()) {
|
|
235
|
+
await deliverUnattendedEnded(paths, await claimUnattendedEnded(paths, now), emit, now);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The background Panel's watch (spec §3.37): looks now and every 30 seconds until the returned function stops it.
|
|
239
|
+
* Only a standalone Panel server starts one; a Panel embedded in a Portal through `createPanelHandler` does not.
|
|
240
|
+
*/
|
|
241
|
+
export function watchUnattendedEnded(paths, emit, everyMs = 30_000) {
|
|
242
|
+
let running = false;
|
|
243
|
+
const look = () => {
|
|
244
|
+
if (running)
|
|
245
|
+
return;
|
|
246
|
+
running = true;
|
|
247
|
+
void checkUnattendedEnded(paths, emit).finally(() => {
|
|
248
|
+
running = false;
|
|
249
|
+
});
|
|
250
|
+
};
|
|
251
|
+
const timer = setInterval(look, everyMs);
|
|
252
|
+
timer.unref();
|
|
253
|
+
look();
|
|
254
|
+
return () => clearInterval(timer);
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* A command's look when it starts: waits only for the look itself (two small file reads when nothing ended), and
|
|
258
|
+
* returns the delivery of what it found as `emitted`, which runs alongside the command. Plugins are loaded only when
|
|
259
|
+
* there is something to deliver; an event whose delivery does not finish is delivered by a later look.
|
|
260
|
+
*/
|
|
261
|
+
export async function noticeUnattendedEnded(env) {
|
|
262
|
+
const paths = resolvePaths(env);
|
|
263
|
+
const notices = await claimUnattendedEnded(paths);
|
|
264
|
+
let rt;
|
|
265
|
+
const emitted = deliverUnattendedEnded(paths, notices, async (ctx) => {
|
|
266
|
+
rt ??= import('../runtime.js').then((m) => m.createRuntime({ env }));
|
|
267
|
+
for (const f of await (await rt).unattendedEnded(ctx))
|
|
268
|
+
console.error(`sideby: [${f.plugin}] unattended.ended failed: ${f.error}`);
|
|
269
|
+
});
|
|
270
|
+
return { emitted };
|
|
271
|
+
}
|
|
272
|
+
/** Reads the checkpoint, for tests and diagnostics. */
|
|
273
|
+
export async function readEndedCheckpoint(stateDir) {
|
|
274
|
+
return parseCheckpoint(await readSmallJson(file(stateDir), 256 * 1024));
|
|
275
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export interface PendingDecision {
|
|
2
|
+
id: string;
|
|
3
|
+
/** When it was kept (ISO). */
|
|
4
|
+
at: string;
|
|
5
|
+
/**
|
|
6
|
+
* question: a question the Host's ask tool was not allowed to show; permission: a permission request Claude Code
|
|
7
|
+
* would have shown, refused; deferred: `sideby unattended defer`.
|
|
8
|
+
*/
|
|
9
|
+
kind: PendingKind;
|
|
10
|
+
family: string;
|
|
11
|
+
/** The Account the session ran as (`SIDEBY_ACCOUNT`). */
|
|
12
|
+
account?: string;
|
|
13
|
+
sessionId?: string;
|
|
14
|
+
cwd?: string;
|
|
15
|
+
/** The subagent that made the request, when a subagent did (Claude's `agent_id` and `agent_type`). */
|
|
16
|
+
agentId?: string;
|
|
17
|
+
agentType?: string;
|
|
18
|
+
/** The question and its options, the tool and what it was to do, or the deferred text; at most 4000 characters. */
|
|
19
|
+
text: string;
|
|
20
|
+
/** When the user marked it done (ISO). */
|
|
21
|
+
doneAt?: string;
|
|
22
|
+
}
|
|
23
|
+
export type PendingKind = 'question' | 'permission' | 'deferred';
|
|
24
|
+
export declare const PENDING_KINDS: readonly PendingKind[];
|
|
25
|
+
export type PendingInput = Omit<PendingDecision, 'id' | 'at' | 'doneAt'>;
|
|
26
|
+
export declare const PENDING_TEXT_MAX = 4000;
|
|
27
|
+
export declare const pendingDir: (stateDir: string) => string;
|
|
28
|
+
/** At most `PENDING_TEXT_MAX` characters (whole characters, never half of one), ending in `…` when cut. */
|
|
29
|
+
export declare function clipPendingText(text: string): string;
|
|
30
|
+
/**
|
|
31
|
+
* Keeps one Pending Decision and returns it. With `dedupe`, an open one of the same kind, session and text is
|
|
32
|
+
* returned instead of a second copy (a model that asks the same question twice leaves one).
|
|
33
|
+
*/
|
|
34
|
+
export declare function addPendingDecision(stateDir: string, input: PendingInput, at?: Date, opts?: {
|
|
35
|
+
dedupe?: boolean;
|
|
36
|
+
}): Promise<PendingDecision>;
|
|
37
|
+
/**
|
|
38
|
+
* The Pending Decisions, oldest first: open ones, or with `all` the done ones too. Deletes the files of those done
|
|
39
|
+
* more than 30 days ago.
|
|
40
|
+
*/
|
|
41
|
+
export declare function listPendingDecisions(stateDir: string,
|
|
42
|
+
/** `prune: false` only reads (a read-only Panel): old done ones are left out but not deleted. */
|
|
43
|
+
opts?: {
|
|
44
|
+
all?: boolean;
|
|
45
|
+
now?: Date;
|
|
46
|
+
prune?: boolean;
|
|
47
|
+
}): Promise<PendingDecision[]>;
|
|
48
|
+
/** Opens a Pending Decision marked done again (the Panel's Undo after "Done"); throws when there is no such id. */
|
|
49
|
+
export declare function reopenPendingDecision(stateDir: string, id: string): Promise<PendingDecision>;
|
|
50
|
+
/** The open Pending Decision an id names: the whole id, or a start of it that only one has. */
|
|
51
|
+
export declare function findPendingDecision(stateDir: string, id: string): Promise<PendingDecision | undefined>;
|
|
52
|
+
/**
|
|
53
|
+
* Marks Pending Decisions done: one by id (or a unique start of it), or every open one with `'all'`. Returns the ones
|
|
54
|
+
* it marked; an id no Pending Decision has throws an Error whose message says how to list them.
|
|
55
|
+
*/
|
|
56
|
+
export declare function markPendingDone(stateDir: string, id: string | 'all', at?: Date): Promise<PendingDecision[]>;
|