@1agents/acp-service 0.10.11 → 0.10.12

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.
@@ -1,175 +0,0 @@
1
- /**
2
- * Optional automatic archiving of silent DSH sessions.
3
- *
4
- * DSH already owns the durable archive set through `ctx.workspaceRegistry`:
5
- * archiving a session hides it from the workspace grouping, clears its pin and
6
- * gates every model step for it and its subagent descendants. This module only
7
- * decides *when* to call that API. It never deletes sessions or changes their
8
- * history, and it never archives a session that DSH currently reports as
9
- * pinned, so a pinned session is always archived manually by the user.
10
- */
11
- import { stat } from 'node:fs/promises';
12
- /** One day in milliseconds. */
13
- const DAY_MS = 24 * 60 * 60 * 1000;
14
- /** Default policy: idle for seven days, check once a day, first check a minute after startup. */
15
- export const DEFAULT_AUTO_ARCHIVE = Object.freeze({
16
- enabled: false,
17
- inactivityMs: 7 * DAY_MS,
18
- scanIntervalMs: DAY_MS,
19
- initialDelayMs: 60 * 1000,
20
- });
21
- /** Normalize user config while preserving the shipped defaults for absent fields. */
22
- export function resolveAutoArchiveConfig(input) {
23
- if (input === undefined || input === null || typeof input !== 'object')
24
- return { ...DEFAULT_AUTO_ARCHIVE };
25
- const result = { ...DEFAULT_AUTO_ARCHIVE };
26
- if ('enabled' in input) {
27
- if (typeof input.enabled !== 'boolean')
28
- throw new Error('autoArchive.enabled must be a boolean');
29
- result.enabled = input.enabled;
30
- }
31
- for (const key of ['inactivityMs', 'scanIntervalMs', 'initialDelayMs']) {
32
- if (!(key in input))
33
- continue;
34
- const value = input[key];
35
- if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
36
- throw new Error(`autoArchive.${key} must be a positive integer`);
37
- }
38
- result[key] = value;
39
- }
40
- return result;
41
- }
42
- /**
43
- * Build the list of sessions that have been silent long enough to archive.
44
- *
45
- * Last activity is the later of DSH's own recency (`updatedAt`, which is the
46
- * session creation time or its last real user message) and the modification
47
- * time of the durable session file. This matches both interpretations of
48
- * "last activity" — the last message block and the backing file's mtime — and
49
- * treats a session with a newer file as active. Pinned and already-archived
50
- * sessions are excluded; pinned sessions stay a manual archive decision.
51
- *
52
- * @param host - minimal DSH service surface.
53
- * @param now - current epoch milliseconds.
54
- * @param inactivityMs - silence threshold in milliseconds.
55
- * @returns sessions to archive, newest activity first.
56
- */
57
- export async function findSilentSessions(host, now, inactivityMs) {
58
- if (!Number.isSafeInteger(now) || now < 0)
59
- throw new Error('now must be a non-negative safe integer');
60
- if (!Number.isSafeInteger(inactivityMs) || inactivityMs < 1)
61
- throw new Error('inactivityMs must be a positive integer');
62
- const pinned = new Set(host.pinnedSessionIds());
63
- const archived = new Set(host.archivedSessionIds());
64
- const cutoff = now - inactivityMs;
65
- const byId = new Map();
66
- // Collect every observed activity time before applying the threshold: a
67
- // durable file written after the last user message must be able to lift a
68
- // session from the candidate set even if its summary was read first.
69
- const record = (sessionId, lastActiveAt) => {
70
- if (pinned.has(sessionId) || archived.has(sessionId))
71
- return;
72
- if (!Number.isFinite(lastActiveAt) || lastActiveAt < 0)
73
- return;
74
- byId.set(sessionId, Math.max(byId.get(sessionId) ?? 0, lastActiveAt));
75
- };
76
- for (const summary of await host.listSummaries())
77
- record(summary.sessionId, summary.updatedAt);
78
- // A durable file written after the last user message (a tool result, a
79
- // title/compaction update, an imported history) still counts as activity.
80
- await Promise.all((await host.listStored()).map(async (snapshot) => {
81
- const { id, createdAt } = snapshot.header;
82
- let lastActiveAt = createdAt;
83
- const path = snapshot.location?.path;
84
- if (path !== undefined) {
85
- try {
86
- lastActiveAt = Math.max(lastActiveAt, (await stat(path)).mtimeMs);
87
- }
88
- catch (error) {
89
- // A missing or unreadable artifact must not make the session look
90
- // newer than the header alone says; keep the header timestamp.
91
- host.log?.(`auto-archive: cannot stat ${path}: ${String(error)}`);
92
- }
93
- }
94
- record(id, lastActiveAt);
95
- }));
96
- return [...byId.entries()]
97
- .filter(([, lastActiveAt]) => lastActiveAt < cutoff)
98
- .map(([sessionId, lastActiveAt]) => ({ sessionId, lastActiveAt }))
99
- .sort((a, b) => b.lastActiveAt - a.lastActiveAt);
100
- }
101
- /** Run one sweep: find silent sessions and archive them one by one. */
102
- export async function sweepAutoArchive(host, now, inactivityMs) {
103
- const candidates = await findSilentSessions(host, now, inactivityMs);
104
- const archived = [];
105
- const failed = [];
106
- for (const { sessionId } of candidates) {
107
- // A live session whose turn started after the scan began has become
108
- // active again; leave it to the next sweep instead of stopping its work.
109
- if (host.isActive?.(sessionId))
110
- continue;
111
- try {
112
- await host.archive(sessionId);
113
- archived.push(sessionId);
114
- }
115
- catch (error) {
116
- failed.push(sessionId);
117
- host.log?.(`auto-archive: failed to archive ${sessionId}: ${String(error)}`);
118
- }
119
- }
120
- return { candidates: candidates.length, archived, failed };
121
- }
122
- /**
123
- * Install the periodic sweep on a Cordis context.
124
- *
125
- * Uses the host's disposal-aware `ctx.interval()` when the timer plugin is
126
- * composed and falls back to a plain interval otherwise; either way the timer
127
- * is cleared when the owning plugin fiber is disposed. The first sweep is
128
- * delayed so a freshly started DSH does not archive sessions before its
129
- * workspace registry and persistence listings have settled.
130
- *
131
- * @param ctx - plugin context.
132
- * @param config - normalized auto-archive config.
133
- * @param run - one sweep; called with no arguments.
134
- * @returns a disposer for the installed timer(s).
135
- */
136
- export function installAutoArchiveTimer(ctx, config, run) {
137
- const disposers = [];
138
- const own = (dispose) => { disposers.push(dispose); };
139
- const disposeAll = () => {
140
- for (const dispose of disposers.splice(0)) {
141
- try {
142
- dispose();
143
- }
144
- catch (error) {
145
- ctx.logger?.warn?.('auto-archive: timer disposal failed: %s', error);
146
- }
147
- }
148
- };
149
- if (!config.enabled)
150
- return disposeAll;
151
- let intervalDispose;
152
- const startInterval = () => {
153
- if (typeof ctx.interval === 'function') {
154
- intervalDispose = ctx.interval(() => { void run(); }, config.scanIntervalMs);
155
- }
156
- else {
157
- const timer = setInterval(() => { void run(); }, config.scanIntervalMs);
158
- // Node's timer object is disposable through its own clear method.
159
- intervalDispose = () => clearInterval(timer);
160
- }
161
- own(intervalDispose);
162
- };
163
- if (typeof ctx.timeout === 'function') {
164
- own(ctx.timeout(() => { startInterval(); void run(); }, config.initialDelayMs));
165
- }
166
- else {
167
- const startTimer = setTimeout(() => { startInterval(); void run(); }, config.initialDelayMs);
168
- own(() => clearTimeout(startTimer));
169
- }
170
- // Cordis invokes an effect body immediately and treats its *return value* as
171
- // the cleanup. Returning `() => disposeAll` (not `disposeAll` itself) keeps
172
- // the timers alive until the owning fiber is actually disposed.
173
- ctx.effect?.(() => () => disposeAll);
174
- return disposeAll;
175
- }