@ouro.bot/cli 0.1.0-alpha.1169 → 0.1.0-alpha.1170
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.json +6 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/senses/app-sessions/app-interface.js +5 -5
- package/dist/senses/app-sessions/sense.js +2 -15
- package/dist/senses/app-sessions/stuck-resume.js +10 -8
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/senses/app-sessions/retire.js +0 -90
- package/dist/senses/app-sessions/size-watch.js +0 -259
package/changelog.json
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
|
|
3
3
|
"versions": [
|
|
4
|
+
{
|
|
5
|
+
"version": "0.1.0-alpha.1170",
|
|
6
|
+
"changes": [
|
|
7
|
+
"The app-sessions sense no longer runs the size watch or hand-off retirement: Shepherd's `shepherd watch` and `shepherd retire plan` do, ported rule for rule. The resume rule skips a session whose history is over 500 MB directly."
|
|
8
|
+
]
|
|
9
|
+
},
|
|
4
10
|
{
|
|
5
11
|
"version": "0.1.0-alpha.1169",
|
|
6
12
|
"changes": [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<?xml version="1.0"?>
|
|
2
2
|
<Container version="2">
|
|
3
3
|
<Name>ouro-butler</Name>
|
|
4
|
-
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.
|
|
4
|
+
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1170</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
|
@@ -303,17 +303,17 @@ async function archiveSession(agentRoot, id, options = {}, ownerAsked = false) {
|
|
|
303
303
|
return archiveRow(agentRoot, row, reason, options);
|
|
304
304
|
}
|
|
305
305
|
/**
|
|
306
|
-
* Ask the app to archive a session the caller has already decided may go, and log it when `reason` is set.
|
|
307
|
-
*
|
|
306
|
+
* Ask the app to archive a session the caller has already decided may go, and log it when `reason` is set. The worktree
|
|
307
|
+
* goes with it, so only call this for a session whose work is finished or was asked for in person.
|
|
308
308
|
*/
|
|
309
|
-
async function archiveRow(agentRoot, row, reason, options = {}
|
|
309
|
+
async function archiveRow(agentRoot, row, reason, options = {}) {
|
|
310
310
|
const archived = row.workspaceId
|
|
311
|
-
? await ask({ type: "archive_workspace", workspace_id: row.workspaceId, delete_worktree: row.workspaceType === "worktree"
|
|
311
|
+
? await ask({ type: "archive_workspace", workspace_id: row.workspaceId, delete_worktree: row.workspaceType === "worktree" }, (reply, requestId) => (reply.request_id === requestId ? (reply.type === "workspace_archived" ? "ok" : "fail") : "ignore"), ARCHIVE_WAIT_MS, options)
|
|
312
312
|
: await ask({ type: "archive_session", session_id: row.id }, (reply, requestId) => (reply.type === "general_chat_sessions_changed" ? "ok" : reply.request_id === requestId ? "fail" : "ignore"), ARCHIVE_WAIT_MS, options);
|
|
313
313
|
if (archived.ok) {
|
|
314
314
|
(0, store_1.removeProbe)(agentRoot, row.id);
|
|
315
315
|
if (reason) {
|
|
316
|
-
(0, store_1.addArchiveLog)(agentRoot, { id: row.id, name: row.name, at: new Date(options.now?.() ?? Date.now()).toISOString(), reason
|
|
316
|
+
(0, store_1.addArchiveLog)(agentRoot, { id: row.id, name: row.name, at: new Date(options.now?.() ?? Date.now()).toISOString(), reason });
|
|
317
317
|
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_archived_not_created", message: "archived a session this agent did not create", meta: { session: row.id, reason } });
|
|
318
318
|
}
|
|
319
319
|
}
|
|
@@ -55,8 +55,6 @@ const digest_push_1 = require("./digest-push");
|
|
|
55
55
|
const client_1 = require("./client");
|
|
56
56
|
const prompts_1 = require("./prompts");
|
|
57
57
|
const store_1 = require("./store");
|
|
58
|
-
const retire_1 = require("./retire");
|
|
59
|
-
const size_watch_1 = require("./size-watch");
|
|
60
58
|
const waiting_prompts_1 = require("./waiting-prompts");
|
|
61
59
|
const wake_runner_1 = require("./wake-runner");
|
|
62
60
|
/**
|
|
@@ -220,7 +218,7 @@ async function checkDigest(agentName, agentRoot, deps) {
|
|
|
220
218
|
const list = () => (0, client_1.listAppSessions)({ ...deps.client, now: () => deps.now });
|
|
221
219
|
const rows = await list();
|
|
222
220
|
const state = (0, digest_1.readDigestState)(agentRoot);
|
|
223
|
-
await (0, stuck_resume_1.resumeStuck)(
|
|
221
|
+
await (0, stuck_resume_1.resumeStuck)(rows, state, deps.now, { client: deps.client, ...(deps.resume ? { send: deps.resume } : {}) });
|
|
224
222
|
const digest = await (0, digest_1.writeDigest)({
|
|
225
223
|
agentRoot, config: config.digest, client: deps.client, run: deps.run, now: deps.now, home: deps.home, rows,
|
|
226
224
|
appRunning: (0, client_1.appRunning)(deps.client), waitingPrompts: (0, waiting_prompts_1.waitingPromptsOf)(agentRoot, rows, deps.now), state,
|
|
@@ -249,7 +247,6 @@ function startAppSessionsSense(options) {
|
|
|
249
247
|
let runnerPoll = Promise.resolve();
|
|
250
248
|
const due = new Map();
|
|
251
249
|
let waitingPoll = Promise.resolve();
|
|
252
|
-
let sizePoll = Promise.resolve();
|
|
253
250
|
const notifyOwner = options.notifyOwner ?? (0, waiting_prompts_1.ownerNotifier)(options.agentName, agentRoot);
|
|
254
251
|
let cancelDigest = null;
|
|
255
252
|
let digestPoll = Promise.resolve();
|
|
@@ -259,16 +256,6 @@ function startAppSessionsSense(options) {
|
|
|
259
256
|
waitingPoll = waitingPoll.then(() => recordSnapshot(agentRoot, client, now())).then(taken => (0, waiting_prompts_1.noticeWaitingPrompts)(agentRoot, taken, { notify: notifyOwner, now: now() })).catch((error) => {
|
|
260
257
|
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_waiting_error", message: "could not check the sessions waiting on a prompt", meta: { error: error.message } });
|
|
261
258
|
});
|
|
262
|
-
sizePoll = sizePoll.then(async () => {
|
|
263
|
-
const rows = await (0, client_1.listAppSessions)({ ...client, now: () => now() });
|
|
264
|
-
const retired = await (0, retire_1.retireSessions)(agentRoot, rows, { now: now(), client }).catch((error) => {
|
|
265
|
-
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_retire_error", message: "could not retire handed-off or finished sessions", meta: { error: error.message } });
|
|
266
|
-
return [];
|
|
267
|
-
});
|
|
268
|
-
await (0, size_watch_1.noticeOversizedSessions)(agentRoot, rows.filter(row => !retired.includes(row.id)), { notify: notifyOwner, now: now(), client, ...(options.memory ? { memory: options.memory } : {}) });
|
|
269
|
-
}).catch((error) => {
|
|
270
|
-
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_oversize_error", message: "could not check the sessions' history sizes", meta: { error: error.message } });
|
|
271
|
-
});
|
|
272
259
|
cancelSnapshot = schedule(snapshotTick, exports.SNAPSHOT_MS);
|
|
273
260
|
};
|
|
274
261
|
const watchTick = () => {
|
|
@@ -313,6 +300,6 @@ function startAppSessionsSense(options) {
|
|
|
313
300
|
cancelDigest?.();
|
|
314
301
|
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_end", message: "app-sessions sense stopped", meta: { agent: options.agentName } });
|
|
315
302
|
},
|
|
316
|
-
done: () => Promise.all([inFlight, runnerPoll, waitingPoll,
|
|
303
|
+
done: () => Promise.all([inFlight, runnerPoll, waitingPoll, digestPoll]).then(() => undefined),
|
|
317
304
|
};
|
|
318
305
|
}
|
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.RESUME_TEXT = exports.RESUMES_PER_DAY = exports.RESUME_MAX_IDLE_MS = void 0;
|
|
3
|
+
exports.RESUME_TEXT = exports.RESUMES_PER_DAY = exports.RESUME_MAX_LOG_BYTES = exports.RESUME_MAX_IDLE_MS = void 0;
|
|
4
4
|
exports.resumeStuck = resumeStuck;
|
|
5
5
|
const runtime_1 = require("../../nerves/runtime");
|
|
6
6
|
const app_interface_1 = require("./app-interface");
|
|
7
|
-
const
|
|
7
|
+
const client_1 = require("./client");
|
|
8
8
|
/**
|
|
9
9
|
* A session whose loop stopped (not running, its last turn called tools and no next turn started) is something an
|
|
10
10
|
* agent can fix, so the sense fixes it rather than asking the owner: it sends the session one message to carry on, once
|
|
11
|
-
* per stop, and the digest shows it under what was fixed. A session asleep for over a day, one
|
|
12
|
-
*
|
|
13
|
-
* three times a day; past that it stays under "Broken" in the digest.
|
|
11
|
+
* per stop, and the digest shows it under what was fixed. A session asleep for over a day, one whose history is over
|
|
12
|
+
* 500 MB (the app loads all of it on resume) or a remote one is left alone, and a session that keeps stopping is resumed
|
|
13
|
+
* at most three times a day; past that it stays under "Broken" in the digest.
|
|
14
14
|
*/
|
|
15
15
|
exports.RESUME_MAX_IDLE_MS = 24 * 3_600_000;
|
|
16
|
+
exports.RESUME_MAX_LOG_BYTES = 500 * 1024 * 1024;
|
|
16
17
|
exports.RESUMES_PER_DAY = 3;
|
|
17
18
|
exports.RESUME_TEXT = "Your loop stopped: your last turn ended without finishing and no next turn started. Carry on where you left off. Re-check anything that was in flight (a shell command, a subagent, a send or a push) before relying on it.";
|
|
18
19
|
/** Whether the app lists this session as stopped mid-loop, rather than hung while running. */
|
|
19
20
|
const loopStopped = (row) => row.state === "stuck" && !row.isRunning && !row.remote && !row.awaiting;
|
|
20
21
|
/** Resumes every session whose loop stopped since it was last resumed. Returns how many it resumed. */
|
|
21
|
-
async function resumeStuck(
|
|
22
|
+
async function resumeStuck(rows, state, now, deps = {}) {
|
|
22
23
|
const send = deps.send ?? ((id, text) => (0, app_interface_1.deliverMessage)(id, text, "immediate", deps.client));
|
|
23
24
|
const resumed = (state.resumed ??= {});
|
|
24
25
|
for (const [id, entry] of Object.entries(resumed)) {
|
|
@@ -26,14 +27,15 @@ async function resumeStuck(agentRoot, rows, state, now, deps = {}) {
|
|
|
26
27
|
if (!entry.times.length)
|
|
27
28
|
delete resumed[id];
|
|
28
29
|
}
|
|
29
|
-
const giants = new Set((0, size_watch_1.neverResume)(agentRoot));
|
|
30
30
|
let count = 0;
|
|
31
31
|
for (const row of rows) {
|
|
32
|
-
if (!loopStopped(row)
|
|
32
|
+
if (!loopStopped(row))
|
|
33
33
|
continue;
|
|
34
34
|
const last = Date.parse(row.lastActivity ?? "");
|
|
35
35
|
if (Number.isNaN(last) || now - last > exports.RESUME_MAX_IDLE_MS)
|
|
36
36
|
continue;
|
|
37
|
+
if ((0, client_1.eventLogSize)(row.id, deps.client) > exports.RESUME_MAX_LOG_BYTES)
|
|
38
|
+
continue;
|
|
37
39
|
const before = resumed[row.id];
|
|
38
40
|
if (before?.lastActivity === row.lastActivity)
|
|
39
41
|
continue;
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1170",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@ouro.bot/cli",
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.1170",
|
|
10
10
|
"bundleDependencies": [
|
|
11
11
|
"@ouro.bot/friends"
|
|
12
12
|
],
|
package/package.json
CHANGED
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.FINISHED_IDLE_MS = exports.HANDOFF_QUIET_MS = void 0;
|
|
4
|
-
exports.childrenNote = childrenNote;
|
|
5
|
-
exports.retireSessions = retireSessions;
|
|
6
|
-
const runtime_1 = require("../../nerves/runtime");
|
|
7
|
-
const owner_notice_1 = require("../shepherd/owner-notice");
|
|
8
|
-
const app_interface_1 = require("./app-interface");
|
|
9
|
-
const coordinator_1 = require("./coordinator");
|
|
10
|
-
const handoff_1 = require("./handoff");
|
|
11
|
-
const size_watch_1 = require("./size-watch");
|
|
12
|
-
/**
|
|
13
|
-
* The sidebar shows live jobs only. Each minute, with no model turn, two kinds of session leave it, through the app's
|
|
14
|
-
* archive (reversible, worktree kept), logged and listed in the status digest:
|
|
15
|
-
*
|
|
16
|
-
* - **Handed off.** A session whose job has a newer owner: a later session's first message says `Succeeds: <its id>`
|
|
17
|
-
* (see `handoff.ts`). It goes once that successor has finished its first turn and it has itself been idle for
|
|
18
|
-
* `HANDOFF_QUIET_MS`, whatever its size.
|
|
19
|
-
* - **Finished.** An idle session whose coordinator is archived or gone, with no open pull request and no automation,
|
|
20
|
-
* and no turn for `FINISHED_IDLE_MS`.
|
|
21
|
-
*
|
|
22
|
-
* Neither ever goes while it runs, waits on a person (a question, plan or permission) or is stuck, or while a session it
|
|
23
|
-
* coordinates still does: the app archives a session without its children, which keep running but can no longer report
|
|
24
|
-
* to it, so a predecessor stays until its children are idle, and its successor is then told which children it had.
|
|
25
|
-
*/
|
|
26
|
-
exports.HANDOFF_QUIET_MS = 5 * 60_000;
|
|
27
|
-
/** A day: an orphan quiet this long has had a full day for its coordinator's successor to pick it up. */
|
|
28
|
-
exports.FINISHED_IDLE_MS = 24 * 3_600_000;
|
|
29
|
-
const quietSince = (row) => Math.max(Date.parse(row.lastActivity ?? "") || 0, Date.parse(row.updatedAt ?? "") || 0);
|
|
30
|
-
const settled = (row) => !row.isRunning && row.state === "idle" && !row.awaiting && !row.remote;
|
|
31
|
-
const recordedCoordinator = (row) => row.coordinatingCreatorSessionId ?? row.parentSessionId;
|
|
32
|
-
const short = (id) => id.slice(0, 8);
|
|
33
|
-
function childrenNote(predecessor, children) {
|
|
34
|
-
const list = children.map(child => `"${(0, owner_notice_1.plain)(child.name, 60)}" (${child.id})`).join(", ");
|
|
35
|
-
return `I archived "${(0, owner_notice_1.plain)(predecessor.name, 60)}" (${predecessor.id}), the session you succeed, now that you have taken over and it is idle. It coordinated ${list}. They are idle and can no longer report to it; message them by id if their work continues. The archive is reversible from the app.`;
|
|
36
|
-
}
|
|
37
|
-
/** Archive the handed-off and the finished sessions among `rows`. Returns the ids archived. */
|
|
38
|
-
async function retireSessions(agentRoot, rows, deps) {
|
|
39
|
-
const send = deps.send ?? ((id, text) => (0, app_interface_1.deliverMessage)(id, text, "immediate", deps.client));
|
|
40
|
-
const archive = deps.archive ?? (async (row, reason, note) => (await (0, app_interface_1.archiveRow)(agentRoot, row, reason, deps.client, { note, keepWorktree: true })).ok === true);
|
|
41
|
-
const successions = (0, handoff_1.refreshSuccessions)(agentRoot, deps.client, rows.map(row => row.id));
|
|
42
|
-
const listed = new Map(rows.map(row => [row.id, row]));
|
|
43
|
-
const childrenOf = (id) => rows.filter(row => recordedCoordinator(row) === id);
|
|
44
|
-
const busyChildren = (id, except) => childrenOf(id).filter(child => child.id !== except && !(settled(child) || (child.remote && !child.isRunning)));
|
|
45
|
-
const archived = [];
|
|
46
|
-
for (const row of rows) {
|
|
47
|
-
if (!settled(row) || deps.now - quietSince(row) < exports.HANDOFF_QUIET_MS)
|
|
48
|
-
continue;
|
|
49
|
-
const direct = Object.entries(successions).find(([, entry]) => entry.predecessor === row.id && entry.turned)?.[0];
|
|
50
|
-
if (!direct)
|
|
51
|
-
continue;
|
|
52
|
-
const successor = (0, handoff_1.successorOf)(row.id, successions);
|
|
53
|
-
if (!successor)
|
|
54
|
-
continue;
|
|
55
|
-
const busy = busyChildren(row.id, direct);
|
|
56
|
-
if (busy.length) {
|
|
57
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_handoff_held", message: "held a handed-off session while sessions it coordinates still work", meta: { session: row.id, successor, children: busy.map(child => child.id) } });
|
|
58
|
-
continue;
|
|
59
|
-
}
|
|
60
|
-
const heir = listed.get(successor);
|
|
61
|
-
// The app deletes an archived session's automation, and restoring it does not bring it back.
|
|
62
|
-
const note = `succeeded by ${heir ? `"${(0, owner_notice_1.plain)(heir.name, 60)}" ` : ""}(${short(successor)}); ${(0, size_watch_1.whereItLeftOff)(row, deps.client)}${row.automation ? "; its automation was removed with it" : ""}`;
|
|
63
|
-
if (!(await archive(row, "handed-off", note).catch(() => false)))
|
|
64
|
-
continue;
|
|
65
|
-
archived.push(row.id);
|
|
66
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_handoff_archived", message: "archived a session whose successor took over", meta: { session: row.id, successor } });
|
|
67
|
-
const orphans = childrenOf(row.id).filter(child => child.id !== direct && child.id !== successor);
|
|
68
|
-
if (orphans.length && heir)
|
|
69
|
-
await send(successor, childrenNote(row, orphans)).catch(() => undefined);
|
|
70
|
-
}
|
|
71
|
-
for (const row of rows) {
|
|
72
|
-
if (archived.includes(row.id) || !settled(row) || row.openPullRequest || row.automation)
|
|
73
|
-
continue;
|
|
74
|
-
const coordinator = recordedCoordinator(row);
|
|
75
|
-
if (!coordinator || (listed.has(coordinator) && !archived.includes(coordinator)))
|
|
76
|
-
continue;
|
|
77
|
-
// The recorded coordinator may have handed off: a lane that a live successor or the session it reports to still coordinates is not finished.
|
|
78
|
-
const live = (0, coordinator_1.coordinatorOf)(row, rows, { client: deps.client, successorOf: id => (0, handoff_1.successorOf)(id, successions) });
|
|
79
|
-
if (live && "id" in live && !archived.includes(live.id))
|
|
80
|
-
continue;
|
|
81
|
-
if (deps.now - quietSince(row) < exports.FINISHED_IDLE_MS || busyChildren(row.id, null).length)
|
|
82
|
-
continue;
|
|
83
|
-
const note = `${row.detail || "idle"}; ${(0, size_watch_1.whereItLeftOff)(row, deps.client)}`;
|
|
84
|
-
if (!(await archive(row, "finished", note).catch(() => false)))
|
|
85
|
-
continue;
|
|
86
|
-
archived.push(row.id);
|
|
87
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_finished_archived", message: "archived an idle session whose coordinator is gone", meta: { session: row.id, coordinator } });
|
|
88
|
-
}
|
|
89
|
-
return archived;
|
|
90
|
-
}
|
|
@@ -1,259 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.shortOfMemory = exports.neverResume = exports.readOversize = exports.PRESSURE_FREE_BYTES = exports.PRESSURE_SWAP_BYTES = exports.IDLE_ARCHIVE_MS = exports.RENUDGE_GROWTH = exports.OVERSIZE_BYTES = void 0;
|
|
37
|
-
exports.handoffNudge = handoffNudge;
|
|
38
|
-
exports.archivedNote = archivedNote;
|
|
39
|
-
exports.readMemory = readMemory;
|
|
40
|
-
exports.whereItLeftOff = whereItLeftOff;
|
|
41
|
-
exports.noticeOversizedSessions = noticeOversizedSessions;
|
|
42
|
-
const node_child_process_1 = require("node:child_process");
|
|
43
|
-
const fs = __importStar(require("node:fs"));
|
|
44
|
-
const os = __importStar(require("node:os"));
|
|
45
|
-
const path = __importStar(require("node:path"));
|
|
46
|
-
const runtime_1 = require("../../nerves/runtime");
|
|
47
|
-
const owner_notice_1 = require("../shepherd/owner-notice");
|
|
48
|
-
const app_interface_1 = require("./app-interface");
|
|
49
|
-
const client_1 = require("./client");
|
|
50
|
-
const coordinator_1 = require("./coordinator");
|
|
51
|
-
const store_1 = require("./store");
|
|
52
|
-
/**
|
|
53
|
-
* A session's event log is loaded whole into memory when the app resumes it, and a log of several GB (almost all of it
|
|
54
|
-
* inline images) has frozen the machine. Each minute, with no model turn, every local session's `events.jsonl` is
|
|
55
|
-
* measured, listed in the sidebar or not, and one over the limit is flagged never-resume. A listed one is asked to hand
|
|
56
|
-
* off to a fresh successor: its coordinator, and the session itself while it runs, are asked again each time its history
|
|
57
|
-
* grows by half, because one ask is easily ignored. A flagged session that then sits idle for 30 minutes (or at once,
|
|
58
|
-
* when memory runs short) is archived through the app, reversibly and keeping its worktree, to free its runtime, and its
|
|
59
|
-
* coordinator is told where it left off. A session that is not running and has no smaller coordinator is never messaged,
|
|
60
|
-
* because the message would reload it; the owner is told instead.
|
|
61
|
-
*/
|
|
62
|
-
exports.OVERSIZE_BYTES = 500 * 1024 * 1024;
|
|
63
|
-
/** A flagged session that keeps running is asked again each time its history reaches this multiple of its size at the last ask. */
|
|
64
|
-
exports.RENUDGE_GROWTH = 1.5;
|
|
65
|
-
/** A flagged session idle this long after its last ask is archived. */
|
|
66
|
-
exports.IDLE_ARCHIVE_MS = 30 * 60_000;
|
|
67
|
-
/** Swap use above this, or free memory below the next, means the machine is short of memory: idle giants go at once. */
|
|
68
|
-
exports.PRESSURE_SWAP_BYTES = 8 * 1024 ** 3;
|
|
69
|
-
exports.PRESSURE_FREE_BYTES = 1024 ** 3;
|
|
70
|
-
/** How far back from the end of a log to look for where the session last pushed, in chunks. */
|
|
71
|
-
const PUSH_SCAN_BYTES = 64 * 1024 * 1024;
|
|
72
|
-
const PUSH_CHUNK_BYTES = 4 * 1024 * 1024;
|
|
73
|
-
const stateFile = (agentRoot) => path.join((0, store_1.appSessionsStateDir)(agentRoot), "oversize.json");
|
|
74
|
-
const readOversize = (agentRoot) => (0, store_1.readJson)(stateFile(agentRoot), { sessions: {} }).sessions;
|
|
75
|
-
exports.readOversize = readOversize;
|
|
76
|
-
/** The ids of sessions flagged never-resume: a resume path asks this before it wakes one. */
|
|
77
|
-
const neverResume = (agentRoot) => Object.keys((0, exports.readOversize)(agentRoot));
|
|
78
|
-
exports.neverResume = neverResume;
|
|
79
|
-
const mb = (bytes) => bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
|
|
80
|
-
function handoffNudge(name, bytes, asked = 0, askedAtBytes, id = "<its session id>") {
|
|
81
|
-
const again = asked ? ` This is ask ${asked + 1}${askedAtBytes ? `: it was ${mb(askedAtBytes)} at the last one and is still growing` : ""}.` : "";
|
|
82
|
-
return `The session "${(0, owner_notice_1.plain)(name, 60)}" has a ${mb(bytes)} history, over the ${mb(exports.OVERSIZE_BYTES)} limit: the app loads all of it into memory every time that session resumes, and a few like it froze this Mac.${again} Please hand it off now: write a checkpoint of its purpose and open work, then start a fresh successor session whose first message begins with the line \`Succeeds: ${id}\` and has it read that checkpoint plus the tail of the old log. That line is how the old session is retired: it is archived for you (reversibly) once the successor has taken its first turn and the old one is idle, or in any case once it has been idle ${exports.IDLE_ARCHIVE_MS / 60_000} minutes after this ask. This goes to the session and to its coordinator; the coordinator starts the successor when there is one. Keep images out of chat (save screenshots and art as files and link the path): inline images are nearly all of the size.`;
|
|
83
|
-
}
|
|
84
|
-
function archivedNote(name, id, bytes, where) {
|
|
85
|
-
return `I archived the session "${(0, owner_notice_1.plain)(name, 60)}" (${id}) to free memory: its ${mb(bytes)} history is over the ${mb(exports.OVERSIZE_BYTES)} limit and it sat idle after the hand-off ask. The archive is reversible from the app, and its worktree was kept. Where it left off: ${where}. If its work is not finished, start a fresh successor session from there and the tail of its log (~/.copilot/session-state/${id}/events.jsonl).`;
|
|
86
|
-
}
|
|
87
|
-
/** Swap in use and free memory: `sysctl vm.swapusage` on macOS, `/proc/meminfo` elsewhere. An unreadable swap counts as none. */
|
|
88
|
-
function readMemory(platform = process.platform, read = what => what === "swapusage"
|
|
89
|
-
? (0, node_child_process_1.execFileSync)("sysctl", ["-n", "vm.swapusage"], { encoding: "utf8", timeout: 5_000 })
|
|
90
|
-
: fs.readFileSync("/proc/meminfo", "utf8")) {
|
|
91
|
-
let swapUsedBytes = 0;
|
|
92
|
-
try {
|
|
93
|
-
if (platform === "darwin")
|
|
94
|
-
swapUsedBytes = Number(/used = ([\d.]+)M/.exec(read("swapusage"))?.[1] ?? 0) * 1024 ** 2;
|
|
95
|
-
else {
|
|
96
|
-
const info = read("meminfo");
|
|
97
|
-
const kb = (key) => Number(new RegExp(`^${key}:\\s+(\\d+)`, "m").exec(info)?.[1] ?? 0) * 1024;
|
|
98
|
-
swapUsedBytes = kb("SwapTotal") - kb("SwapFree");
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
catch {
|
|
102
|
-
swapUsedBytes = 0;
|
|
103
|
-
}
|
|
104
|
-
return { swapUsedBytes, freeBytes: os.freemem() };
|
|
105
|
-
}
|
|
106
|
-
const shortOfMemory = (memory) => memory.swapUsedBytes > exports.PRESSURE_SWAP_BYTES || memory.freeBytes < exports.PRESSURE_FREE_BYTES;
|
|
107
|
-
exports.shortOfMemory = shortOfMemory;
|
|
108
|
-
const sessionsRoot = (client) => path.dirname(path.dirname((0, client_1.eventLogPath)("x", client)));
|
|
109
|
-
/** Every local session's history size, whether or not the sidebar lists it. */
|
|
110
|
-
function localLogSizes(client) {
|
|
111
|
-
const sizes = new Map();
|
|
112
|
-
let names;
|
|
113
|
-
try {
|
|
114
|
-
names = fs.readdirSync(sessionsRoot(client));
|
|
115
|
-
}
|
|
116
|
-
catch {
|
|
117
|
-
return sizes;
|
|
118
|
-
}
|
|
119
|
-
for (const name of names)
|
|
120
|
-
sizes.set(name, (0, client_1.eventLogSize)(name, client));
|
|
121
|
-
return sizes;
|
|
122
|
-
}
|
|
123
|
-
/** The name the session saved for itself, for one the sidebar no longer lists. */
|
|
124
|
-
function savedName(id, client) {
|
|
125
|
-
try {
|
|
126
|
-
const head = fs.readFileSync(path.join(sessionsRoot(client), id, "workspace.yaml"), "utf8").slice(0, 4096);
|
|
127
|
-
return /^name: ['"]?(.*?)['"]?$/m.exec(head)?.[1] || null;
|
|
128
|
-
}
|
|
129
|
-
catch {
|
|
130
|
-
return null;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
const last = (text, pattern) => text.match(pattern)?.at(-1);
|
|
134
|
-
/**
|
|
135
|
-
* Where a session left off, for its coordinator: its workspace branch, and the last `git push` and pull request in the
|
|
136
|
-
* end of its history (credentials in a push URL are cut). Only the last 64 MB is read, a chunk at a time.
|
|
137
|
-
*/
|
|
138
|
-
function whereItLeftOff(row, client = {}) {
|
|
139
|
-
let push;
|
|
140
|
-
let pr;
|
|
141
|
-
let fd = null;
|
|
142
|
-
try {
|
|
143
|
-
fd = fs.openSync((0, client_1.eventLogPath)(row.id, client), "r");
|
|
144
|
-
const size = fs.fstatSync(fd).size;
|
|
145
|
-
for (let end = size; end > 0 && size - end < PUSH_SCAN_BYTES && !(push && pr); end -= PUSH_CHUNK_BYTES) {
|
|
146
|
-
const start = Math.max(0, end - PUSH_CHUNK_BYTES - 512);
|
|
147
|
-
const buffer = Buffer.alloc(end - start);
|
|
148
|
-
fs.readSync(fd, buffer, 0, buffer.length, start);
|
|
149
|
-
const text = buffer.toString("utf8");
|
|
150
|
-
push ??= last(text, /git push\b[^"\\\n]{0,200}/g);
|
|
151
|
-
pr ??= last(text, /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
catch {
|
|
155
|
-
// No log: say what the sidebar knows.
|
|
156
|
-
}
|
|
157
|
-
finally {
|
|
158
|
-
if (fd !== null)
|
|
159
|
-
fs.closeSync(fd);
|
|
160
|
-
}
|
|
161
|
-
const parts = [
|
|
162
|
-
...(row.branch ? [`branch ${row.branch}${row.projectRepo ? ` in ${row.projectRepo}` : ""}`] : []),
|
|
163
|
-
...(push ? [`last push \`${push.split(/\s(?:2>|\||;|&&)/)[0].replace(/\/\/[^/@\s]*@/, "//").trim()}\``] : []),
|
|
164
|
-
...(pr ? [`last pull request ${pr}`] : []),
|
|
165
|
-
];
|
|
166
|
-
return parts.length ? parts.join("; ") : "no push or pull request in the end of its history";
|
|
167
|
-
}
|
|
168
|
-
const failed = (error) => ({ ok: false, frame: null, error: error.message });
|
|
169
|
-
/** Flag every over-limit session, ask again as one grows, and archive the idle ones. Returns what this pass did. */
|
|
170
|
-
async function noticeOversizedSessions(agentRoot, rows, deps) {
|
|
171
|
-
const client = deps.client;
|
|
172
|
-
const send = deps.send ?? ((id, text) => (0, app_interface_1.deliverMessage)(id, text, "immediate", deps.client));
|
|
173
|
-
const archive = deps.archive ?? (async (row, reason, note) => (await (0, app_interface_1.archiveRow)(agentRoot, row, reason, client, { note, keepWorktree: true })).ok === true);
|
|
174
|
-
const at = new Date(deps.now).toISOString();
|
|
175
|
-
const before = (0, exports.readOversize)(agentRoot);
|
|
176
|
-
const sizes = localLogSizes(client);
|
|
177
|
-
const listed = new Map(rows.filter(row => !row.remote).map(row => [row.id, row]));
|
|
178
|
-
const next = {};
|
|
179
|
-
for (const [id, bytes] of sizes) {
|
|
180
|
-
if (bytes <= exports.OVERSIZE_BYTES)
|
|
181
|
-
continue;
|
|
182
|
-
const { unlisted: _unlisted, ...kept } = before[id] ?? {};
|
|
183
|
-
const row = listed.get(id);
|
|
184
|
-
next[id] = { ...kept, bytes, name: row?.name ?? kept.name ?? savedName(id, client) ?? id, ...(row ? {} : { unlisted: true }) };
|
|
185
|
-
}
|
|
186
|
-
const big = [...listed.values()].filter(row => next[row.id]);
|
|
187
|
-
// A coordinator that is itself a giant is only messaged while it runs, since a message would reload it.
|
|
188
|
-
// The coordinator now, not the one the app recorded: that one may have handed off and been archived.
|
|
189
|
-
const successors = (0, coordinator_1.handoffSuccessors)(agentRoot);
|
|
190
|
-
const reachable = (lane) => {
|
|
191
|
-
const found = (0, coordinator_1.coordinatorOf)(lane, rows.filter(row => !row.remote), { client, successorOf: successors });
|
|
192
|
-
const row = found && "id" in found ? listed.get(found.id) : undefined;
|
|
193
|
-
return row && (row.isRunning || !next[row.id]) ? row : undefined;
|
|
194
|
-
};
|
|
195
|
-
let nudged = 0;
|
|
196
|
-
const ownerRows = [];
|
|
197
|
-
for (const row of big) {
|
|
198
|
-
const entry = next[row.id];
|
|
199
|
-
const due = row.isRunning ? entry.nudgedBytes === undefined || entry.bytes >= entry.nudgedBytes * exports.RENUDGE_GROWTH : !entry.nudgedAt;
|
|
200
|
-
if (!due)
|
|
201
|
-
continue;
|
|
202
|
-
const boss = reachable(row);
|
|
203
|
-
const to = [...(boss && boss.id !== row.id ? [boss.id] : []), ...(row.isRunning ? [row.id] : [])];
|
|
204
|
-
if (!to.length) {
|
|
205
|
-
ownerRows.push(row);
|
|
206
|
-
continue;
|
|
207
|
-
}
|
|
208
|
-
// An entry from before asks were counted had one ask.
|
|
209
|
-
const asked = entry.nudges ?? (entry.nudgedAt ? 1 : 0);
|
|
210
|
-
const text = handoffNudge(row.name, entry.bytes, asked, entry.nudgedBytes, row.id);
|
|
211
|
-
const reached = [];
|
|
212
|
-
for (const id of to)
|
|
213
|
-
if ((await send(id, text).catch(failed)).ok)
|
|
214
|
-
reached.push(id);
|
|
215
|
-
if (!reached.length)
|
|
216
|
-
continue;
|
|
217
|
-
Object.assign(entry, { nudgedAt: at, nudgedBytes: entry.bytes, nudges: asked + 1, to: reached.join(",") });
|
|
218
|
-
nudged += 1;
|
|
219
|
-
}
|
|
220
|
-
if (ownerRows.length) {
|
|
221
|
-
const lines = ownerRows.map(row => `- "${(0, owner_notice_1.plain)(row.name, 60)}" (${mb(next[row.id].bytes)})`);
|
|
222
|
-
const outcome = await deps.notify(`These sessions have histories over ${mb(exports.OVERSIZE_BYTES)} and cannot be nudged without reloading them. They need a hand-off to a fresh successor session (checkpoint, tail, archive); keep images out of chat:\n${lines.join("\n")}`, ownerRows.map(row => `oversize:${row.id}`));
|
|
223
|
-
for (const row of ownerRows) {
|
|
224
|
-
next[row.id].to = "owner";
|
|
225
|
-
if (outcome !== "pending") {
|
|
226
|
-
Object.assign(next[row.id], { nudgedAt: at, nudgedBytes: next[row.id].bytes, nudges: (next[row.id].nudges ?? 0) + 1 });
|
|
227
|
-
nudged += 1;
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
const quiet = big.filter(row => !row.isRunning && row.state !== "waiting");
|
|
232
|
-
const pressed = quiet.length > 0 && (0, exports.shortOfMemory)((deps.memory ?? readMemory)());
|
|
233
|
-
const idle = quiet.filter(row => {
|
|
234
|
-
const entry = next[row.id];
|
|
235
|
-
if (pressed)
|
|
236
|
-
return true;
|
|
237
|
-
if (!entry.nudgedAt)
|
|
238
|
-
return false;
|
|
239
|
-
return deps.now - Math.max(Date.parse(entry.nudgedAt), Date.parse(row.lastActivity ?? "") || 0) >= exports.IDLE_ARCHIVE_MS;
|
|
240
|
-
}).sort((a, b) => next[b.id].bytes - next[a.id].bytes);
|
|
241
|
-
let archived = 0;
|
|
242
|
-
for (const row of idle) {
|
|
243
|
-
const entry = next[row.id];
|
|
244
|
-
const where = whereItLeftOff(row, client);
|
|
245
|
-
const reason = pressed ? "memory-pressure" : "oversize-idle";
|
|
246
|
-
if (!(await archive(row, reason, `${mb(entry.bytes)}; ${where}`).catch(() => false)))
|
|
247
|
-
continue;
|
|
248
|
-
entry.archivedAt = at;
|
|
249
|
-
archived += 1;
|
|
250
|
-
const boss = reachable(row);
|
|
251
|
-
if (boss && boss.id !== row.id)
|
|
252
|
-
await send(boss.id, archivedNote(row.name, row.id, entry.bytes, where)).catch(failed);
|
|
253
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_oversize_archived", message: "archived an idle Copilot app session whose history is over the limit", meta: { session: row.id, bytes: entry.bytes, reason } });
|
|
254
|
-
}
|
|
255
|
-
(0, store_1.writeJson)(stateFile(agentRoot), { sessions: next });
|
|
256
|
-
if (nudged)
|
|
257
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_oversize_nudge", message: "asked for a hand-off of Copilot app sessions whose history is over the limit", meta: { sessions: nudged } });
|
|
258
|
-
return { nudged, archived };
|
|
259
|
-
}
|