@ouro.bot/cli 0.1.0-alpha.1161 → 0.1.0-alpha.1163
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 +12 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/mind/session-transaction.js +23 -0
- package/dist/repertoire/tools-app-sessions.js +1 -1
- package/dist/senses/app-sessions/app-interface.js +32 -13
- package/dist/senses/app-sessions/coordinator.js +78 -0
- package/dist/senses/app-sessions/digest-push.js +62 -59
- package/dist/senses/app-sessions/digest.js +10 -1
- package/dist/senses/app-sessions/handoff.js +15 -17
- package/dist/senses/app-sessions/retire.js +9 -4
- package/dist/senses/app-sessions/sense.js +6 -2
- package/dist/senses/app-sessions/size-watch.js +8 -4
- package/dist/senses/app-sessions/stuck-resume.js +50 -0
- package/dist/senses/app-sessions/waiting-prompts.js +1 -1
- package/dist/senses/shepherd/conversation-hold.js +78 -0
- package/dist/senses/shepherd/owner-notice.js +5 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/changelog.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
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.1163",
|
|
6
|
+
"changes": [
|
|
7
|
+
"The Copilot app sense's succession record (successions.json) keeps only the sessions the sidebar lists, plus a successor that has left it while the session it succeeds is still listed, instead of every session ever seen (8,269 entries on the Mac mini), and reads no history of a session the app no longer lists. isHandedOff and handoffSuccessors read the record the sense refreshes each minute."
|
|
8
|
+
]
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"version": "0.1.0-alpha.1162",
|
|
12
|
+
"changes": [
|
|
13
|
+
"Notices the owner did not ask for never talk over a conversation: the app-sessions pushes, the waiting-prompt notice and Shepherd's owner notices are held while a turn is running in one of the owner's sessions, while either side wrote in the last 10 minutes, or while their message has no answer (up to 30 minutes), and go out once it is quiet. The digest push now carries only what only the owner can act on (ready work, a session waiting on their answer), rechecked live before sending, in whole sentences with the session's link and no cut-off names; finished and broken things stay in /status. A session whose loop stopped is resumed by the sense itself (once per stop, three a day at most) and listed under Fixed by me. get_session and the session lists name who coordinates a lane now, following a hand-off's Succeeds: line or the lane's own reports when its recorded coordinator was archived; the size watch asks that coordinator, and a lane it still finds is never retired as finished."
|
|
14
|
+
]
|
|
15
|
+
},
|
|
4
16
|
{
|
|
5
17
|
"version": "0.1.0-alpha.1161",
|
|
6
18
|
"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.1163</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
|
@@ -38,6 +38,7 @@ exports.admitSessionActivity = admitSessionActivity;
|
|
|
38
38
|
exports.acquireSessionTurnLease = acquireSessionTurnLease;
|
|
39
39
|
exports.withSessionTurnLease = withSessionTurnLease;
|
|
40
40
|
exports.withImmediateSessionTurnLease = withImmediateSessionTurnLease;
|
|
41
|
+
exports.sessionTurnInFlight = sessionTurnInFlight;
|
|
41
42
|
exports.currentSessionTurnLease = currentSessionTurnLease;
|
|
42
43
|
exports.assertSessionTurnLease = assertSessionTurnLease;
|
|
43
44
|
exports.readSessionTransaction = readSessionTransaction;
|
|
@@ -512,6 +513,28 @@ function withImmediateSessionTurnLease(sessionPath, work, options = {}) {
|
|
|
512
513
|
}
|
|
513
514
|
}
|
|
514
515
|
}
|
|
516
|
+
/**
|
|
517
|
+
* Whether a turn is running in this session right now, in any process: its lease row is held by a live process. Read
|
|
518
|
+
* only, so a caller outside the turn (a proactive notice) can wait for the answer instead of talking over it.
|
|
519
|
+
*/
|
|
520
|
+
function sessionTurnInFlight(sessionPath, isProcessAlive = processAlive) {
|
|
521
|
+
const lockPath = `${canonicalSessionPath(sessionPath)}.turn.lock`;
|
|
522
|
+
if (!fs.existsSync(lockPath))
|
|
523
|
+
return false;
|
|
524
|
+
let database = null;
|
|
525
|
+
try {
|
|
526
|
+
database = (0, sqlite_1.openDatabase)(lockPath, { readonly: true, fileMustExist: true });
|
|
527
|
+
const row = database.prepare("SELECT pid FROM session_turn_lease WHERE singleton = 1").get();
|
|
528
|
+
return typeof row?.pid === "number" && isProcessAlive(row.pid);
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
// No lease table yet, or the file is busy being created: nobody holds a turn we can see.
|
|
532
|
+
return false;
|
|
533
|
+
}
|
|
534
|
+
finally {
|
|
535
|
+
database?.close();
|
|
536
|
+
}
|
|
537
|
+
}
|
|
515
538
|
function currentSessionTurnLease(sessionPath) {
|
|
516
539
|
const lease = leaseContext.getStore();
|
|
517
540
|
return lease && lease.sessionPath === canonicalSessionPath(sessionPath) ? lease : null;
|
|
@@ -86,7 +86,7 @@ function define(name, description, properties, required, risk, body, summaryKeys
|
|
|
86
86
|
}
|
|
87
87
|
const session = { type: "string", description: "A session's id from list_sessions_and_chats; a unique start of it (the first 8 characters) works." };
|
|
88
88
|
const notifyOnIdle = { type: "string", enum: ["once", "always", "never"], description: "Whether the session's finished replies come back to you as inbound messages: once (default, the next one), always (for a day), or never. The app does not report back to an outside client, so this is how replies reach you." };
|
|
89
|
-
exports.listSessionsAndChatsTool = define("list_sessions_and_chats", "Every open coding session and chat in this Mac's GitHub Copilot app: id, app_url, name, project, branch, who created and coordinates it. Read-only.", {}, [], READ, () => (0, app_interface_1.listSessionsAndChats)(clientOptions));
|
|
89
|
+
exports.listSessionsAndChatsTool = define("list_sessions_and_chats", "Every open coding session and chat in this Mac's GitHub Copilot app: id, app_url, name, project, branch, who created and coordinates it. Read-only.", {}, [], READ, (_args, agentRoot) => (0, app_interface_1.listSessionsAndChats)(clientOptions, agentRoot));
|
|
90
90
|
exports.getSessionsStatusTool = define("get_sessions_status", "What every session is doing now, with counts: busy, idle, stuck, blocked, and what each blocked one waits on. awaiting_input carries the request_id and the question that answer_session_input or respond_to_session_plan_v2 needs. Read-only.", { state: { type: "string", enum: ["busy", "idle", "waiting", "stuck"], description: "Only sessions in this state." } }, [], READ, (args, agentRoot) => (0, app_interface_1.getSessionsStatus)(agentRoot, typeof args.state === "string" ? args.state : undefined, clientOptions), ["state"]);
|
|
91
91
|
exports.getSessionTool = define("get_session", "One session's details and what it is doing now, including what it waits on (awaiting_input). Read-only.", { session_id: session }, ["session_id"], READ, (args, agentRoot) => (0, app_interface_1.getSession)(agentRoot, args.session_id, clientOptions), ["session_id"]);
|
|
92
92
|
exports.sendSessionMessageTool = define("send_session_message", "Send a message into a session, as its message box does; waits up to 2 minutes for the app to accept it (a session that is not loaded loads first). The app takes it for the person's, so say who you are in it. immediate (default) is admitted at the session's next turn boundary; enqueue waits behind its work.", { session_id: session, message: { type: "string", description: "What to send." }, delivery_mode: { type: "string", enum: ["immediate", "enqueue"] }, notify_on_idle: notifyOnIdle }, ["session_id", "message"], write("sends a message into another agent session in the owner's Copilot app"), (args, agentRoot) => (0, app_interface_1.sendSessionMessage)(agentRoot, args, clientOptions), ["session_id"]);
|
|
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.appUrl = void 0;
|
|
36
37
|
exports.findSession = findSession;
|
|
37
38
|
exports.listSessionsAndChats = listSessionsAndChats;
|
|
38
39
|
exports.getSessionsStatus = getSessionsStatus;
|
|
@@ -53,6 +54,7 @@ const node_crypto_1 = require("node:crypto");
|
|
|
53
54
|
const os = __importStar(require("node:os"));
|
|
54
55
|
const runtime_1 = require("../../nerves/runtime");
|
|
55
56
|
const client_1 = require("./client");
|
|
57
|
+
const coordinator_1 = require("./coordinator");
|
|
56
58
|
const handoff_1 = require("./handoff");
|
|
57
59
|
const store_1 = require("./store");
|
|
58
60
|
/**
|
|
@@ -74,7 +76,9 @@ const COORDINATION_NOTE = "an outside client cannot be a session's coordinator,
|
|
|
74
76
|
const isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
75
77
|
const str = (value) => (typeof value === "string" && value.length > 0 ? value : null);
|
|
76
78
|
const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== null && item !== undefined));
|
|
79
|
+
/** The link that opens a session in the app. */
|
|
77
80
|
const appUrl = (id) => `ghapp://sessions/${id}`;
|
|
81
|
+
exports.appUrl = appUrl;
|
|
78
82
|
const reasonOf = (frame) => str(frame.error) ?? str(frame.message) ?? str(frame.reason) ?? str(frame.detail) ?? String(frame.type);
|
|
79
83
|
/** Whether a sender wants a session's reply back, and for how long: once (the default), always, or never. */
|
|
80
84
|
const notifyMode = (value) => (value === "never" ? null : value === "always" ? "always" : "once");
|
|
@@ -103,11 +107,23 @@ function findSession(rows, value) {
|
|
|
103
107
|
throw new Error(matches.length ? `'${wanted}' matches ${matches.length} sessions; give more of the id` : `no session '${wanted}' in the Copilot app (list_sessions_and_chats shows them)`);
|
|
104
108
|
}
|
|
105
109
|
const resolve = async (value, options) => findSession(await (0, client_1.listAppSessions)(options), value);
|
|
106
|
-
|
|
110
|
+
/**
|
|
111
|
+
* Who coordinates the session now, beside the app's own field, which keeps naming a coordinator that handed off and
|
|
112
|
+
* was archived (see `coordinator.ts`). Say a lane has no coordinator only when `coordinator_gone` is true.
|
|
113
|
+
*/
|
|
114
|
+
function coordination(row, rows, options, successors) {
|
|
115
|
+
const found = (0, coordinator_1.coordinatorOf)(row, rows, { client: options, ...(successors ? { successorOf: successors } : {}) });
|
|
116
|
+
if (!found)
|
|
117
|
+
return {};
|
|
118
|
+
if ("gone" in found)
|
|
119
|
+
return { coordinator_gone: true };
|
|
120
|
+
return { coordinator_session_id: found.id, coordinator_name: found.name, ...(found.via === "app" ? {} : { coordinator_found_by: found.via }) };
|
|
121
|
+
}
|
|
122
|
+
function item(row, rows, options, successors) {
|
|
107
123
|
return compact({
|
|
108
|
-
type: row.kind === "chat" ? "chat" : "session", id: row.id, app_url: appUrl(row.id), name: row.name, project_id: row.projectId, project_name: row.project, project_repo: row.projectRepo,
|
|
124
|
+
type: row.kind === "chat" ? "chat" : "session", id: row.id, app_url: (0, exports.appUrl)(row.id), name: row.name, project_id: row.projectId, project_name: row.project, project_repo: row.projectRepo,
|
|
109
125
|
branch: row.branch, path: row.path, created_at: row.createdAt, updated_at: row.updatedAt, creator_session_id: row.creatorSessionId,
|
|
110
|
-
coordinating_creator_session_id: row.coordinatingCreatorSessionId, parent_session_id: row.parentSessionId, is_running: row.isRunning, ...(row.remote ? { remote: true } : {}),
|
|
126
|
+
coordinating_creator_session_id: row.coordinatingCreatorSessionId, ...coordination(row, rows, options, successors), parent_session_id: row.parentSessionId, is_running: row.isRunning, ...(row.remote ? { remote: true } : {}),
|
|
111
127
|
});
|
|
112
128
|
}
|
|
113
129
|
/** What an answer needs from a session blocked on something: the request's id and what it asks, or why the id is unknown. */
|
|
@@ -124,34 +140,37 @@ function awaitingInput(row, pending) {
|
|
|
124
140
|
}
|
|
125
141
|
return undefined;
|
|
126
142
|
}
|
|
127
|
-
function status(row, pending) {
|
|
143
|
+
function status(row, rows, pending, options, successors) {
|
|
128
144
|
const input = awaitingInput(row, pending);
|
|
129
145
|
return compact({
|
|
130
|
-
...item(row), was_interrupted: row.wasInterrupted || null,
|
|
146
|
+
...item(row, rows, options, successors), was_interrupted: row.wasInterrupted || null,
|
|
131
147
|
activity: compact({ status: row.state === "working" ? "busy" : row.state, why: row.detail, last_activity: row.lastActivity }),
|
|
132
148
|
awaiting_user_input: row.awaiting === "input", awaiting_plan_approval: row.awaiting === "plan", awaiting_permission: row.awaiting === "permission",
|
|
133
149
|
awaiting_input: input,
|
|
134
150
|
});
|
|
135
151
|
}
|
|
136
152
|
// ---------- reading ----------
|
|
137
|
-
async function listSessionsAndChats(options = {}) {
|
|
153
|
+
async function listSessionsAndChats(options = {}, agentRoot) {
|
|
138
154
|
const rows = await (0, client_1.listAppSessions)(options);
|
|
139
|
-
|
|
155
|
+
const successors = agentRoot ? (0, coordinator_1.handoffSuccessors)(agentRoot) : undefined;
|
|
156
|
+
return { total: rows.length, items: rows.map(row => item(row, rows, options, successors)) };
|
|
140
157
|
}
|
|
141
158
|
async function getSessionsStatus(agentRoot, state, options = {}) {
|
|
142
159
|
const rows = await (0, client_1.listAppSessions)(options);
|
|
143
160
|
const pending = (0, store_1.readPending)(agentRoot);
|
|
161
|
+
const successors = (0, coordinator_1.handoffSuccessors)(agentRoot);
|
|
144
162
|
const count = (keep) => rows.filter(keep).length;
|
|
145
163
|
return {
|
|
146
164
|
summary: {
|
|
147
165
|
total: rows.length, running: count(row => row.isRunning), busy: count(row => row.state === "working"), blocked: count(row => row.state === "waiting"), stuck: count(row => row.state === "stuck"),
|
|
148
166
|
awaiting_user_input: count(row => row.awaiting === "input"), awaiting_plan_approval: count(row => row.awaiting === "plan"),
|
|
149
167
|
},
|
|
150
|
-
sessions: rows.filter(row => !state || row.state === state || (state === "busy" && row.state === "working")).map(row => status(row, pending)),
|
|
168
|
+
sessions: rows.filter(row => !state || row.state === state || (state === "busy" && row.state === "working")).map(row => status(row, rows, pending, options, successors)),
|
|
151
169
|
};
|
|
152
170
|
}
|
|
153
171
|
async function getSession(agentRoot, id, options = {}) {
|
|
154
|
-
|
|
172
|
+
const rows = await (0, client_1.listAppSessions)(options);
|
|
173
|
+
return status(findSession(rows, id), rows, (0, store_1.readPending)(agentRoot), options, (0, coordinator_1.handoffSuccessors)(agentRoot));
|
|
155
174
|
}
|
|
156
175
|
// ---------- writing ----------
|
|
157
176
|
/** Put a message into a session, as its message box does, and wait for the app to accept it (a session that is not loaded loads first). */
|
|
@@ -241,7 +260,7 @@ async function createSession(agentRoot, args, options = {}) {
|
|
|
241
260
|
sent = await sendSessionMessage(agentRoot, { session_id: id, message: prompt, notify_on_idle: args.notify_on_idle }, options);
|
|
242
261
|
const error = sent && !sent.ok ? `created, but the first message was not accepted: ${String(sent.error)}` : null;
|
|
243
262
|
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_created", message: "created a Copilot app session", meta: { session: id, chat, prompted: !!prompt } });
|
|
244
|
-
return compact({ ok: error === null, created: true, session_id: id, app_url: appUrl(id), kind: chat ? "chat" : "session", workspace_id: str(created.frame?.workspace_id), watching: sent?.watching, coordination: COORDINATION_NOTE, error });
|
|
263
|
+
return compact({ ok: error === null, created: true, session_id: id, app_url: (0, exports.appUrl)(id), kind: chat ? "chat" : "session", workspace_id: str(created.frame?.workspace_id), watching: sent?.watching, coordination: COORDINATION_NOTE, error });
|
|
245
264
|
}
|
|
246
265
|
/** Answer a question a session asked with its ask_user tool. */
|
|
247
266
|
async function answerSessionInput(agentRoot, args, options = {}) {
|
|
@@ -275,7 +294,7 @@ async function archiveSession(agentRoot, id, options = {}, ownerAsked = false) {
|
|
|
275
294
|
const made = (0, store_1.readProbes)(agentRoot);
|
|
276
295
|
let reason = null;
|
|
277
296
|
if (!made[row.id]) {
|
|
278
|
-
reason = ownerAsked ? "owner-asked" : (0, handoff_1.isHandedOff)(agentRoot, row
|
|
297
|
+
reason = ownerAsked ? "owner-asked" : (0, handoff_1.isHandedOff)(agentRoot, row) ? "handed-off" : null;
|
|
279
298
|
if (!reason) {
|
|
280
299
|
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_archive_declined", message: "declined to archive a session this agent did not create", meta: { session: row.id } });
|
|
281
300
|
throw new Error(`session ${row.id} was not created by this agent, so it will not archive it unless the owner asked for it or it is oversize and a newer session names it as handed off (yours: ${Object.keys(made).join(", ") || "none"})`);
|
|
@@ -306,8 +325,8 @@ async function archiveRow(agentRoot, row, reason, options = {}, extra = {}) {
|
|
|
306
325
|
/** Show a session in the app's window, as following its link does. */
|
|
307
326
|
async function navigateTo(id, options = {}) {
|
|
308
327
|
const row = await resolve(id, options);
|
|
309
|
-
const shown = await ask({ type: "handle_deep_link", url: appUrl(row.id) }, reply => (reply.type === "deep_link_received" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
|
|
310
|
-
return compact({ ok: shown.ok, session_id: row.id, app_url: appUrl(row.id), error: shown.error });
|
|
328
|
+
const shown = await ask({ type: "handle_deep_link", url: (0, exports.appUrl)(row.id) }, reply => (reply.type === "deep_link_received" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
|
|
329
|
+
return compact({ ok: shown.ok, session_id: row.id, app_url: (0, exports.appUrl)(row.id), error: shown.error });
|
|
311
330
|
}
|
|
312
331
|
// ---------- automations and workflows ----------
|
|
313
332
|
/** Create or replace the automation that wakes a session, or clear it. */
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.REPORT_SCAN_BYTES = void 0;
|
|
4
|
+
exports.handoffSuccessors = handoffSuccessors;
|
|
5
|
+
exports.reportTargets = reportTargets;
|
|
6
|
+
exports.coordinatorOf = coordinatorOf;
|
|
7
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
8
|
+
const client_1 = require("./client");
|
|
9
|
+
const handoff_1 = require("./handoff");
|
|
10
|
+
/**
|
|
11
|
+
* Who coordinates a session now. The app records a coordinator once, when the session is made, and never lets another
|
|
12
|
+
* session take that field over: when the coordinator hands off to a fresh successor and is archived, the field still
|
|
13
|
+
* names the archived one, while the lanes have long been reporting to the successor. So the field alone is not the truth.
|
|
14
|
+
* In order:
|
|
15
|
+
*
|
|
16
|
+
* - `app`: the session the app names, when it is still in the sidebar (by session id or project-session id);
|
|
17
|
+
* - `hand-off`: that session's successor, when a hand-off names one that is listed (`successorOf`, owned by `handoff.ts`);
|
|
18
|
+
* - `reports`: the listed session this lane last sent a message to with `send_session_message`, in the end of its history.
|
|
19
|
+
*
|
|
20
|
+
* `gone` means none of these finds one: only then may anyone say the lane has no coordinator.
|
|
21
|
+
*/
|
|
22
|
+
exports.REPORT_SCAN_BYTES = 16 * 1024 * 1024;
|
|
23
|
+
const SEND_TOOL = /(?:^|-)send_session_message$/;
|
|
24
|
+
/** `successorOf` over the hand-offs the sense last recorded (`handoff.ts` refreshes them each minute), read once, when first needed. */
|
|
25
|
+
function handoffSuccessors(agentRoot) {
|
|
26
|
+
let successions = null;
|
|
27
|
+
return id => (0, handoff_1.successorOf)(id, (successions ??= (0, handoff_1.readSuccessions)(agentRoot)));
|
|
28
|
+
}
|
|
29
|
+
const listedAs = (rows, id) => id ? rows.find(row => row.id === id || row.workspaceId === id) : undefined;
|
|
30
|
+
/** The session ids this lane sent messages to, oldest first, from the end of its history. */
|
|
31
|
+
function reportTargets(id, client = {}, maxBytes = exports.REPORT_SCAN_BYTES) {
|
|
32
|
+
const targets = [];
|
|
33
|
+
for (const line of (0, client_1.readEventLog)(id, { ...client, maxBytes }).text.split("\n")) {
|
|
34
|
+
if (!line.includes("send_session_message"))
|
|
35
|
+
continue;
|
|
36
|
+
let event;
|
|
37
|
+
try {
|
|
38
|
+
event = JSON.parse(line);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
for (const request of event.data?.toolRequests ?? []) {
|
|
44
|
+
if (typeof request?.name !== "string" || !SEND_TOOL.test(request.name))
|
|
45
|
+
continue;
|
|
46
|
+
let args = request.arguments;
|
|
47
|
+
if (typeof args === "string") {
|
|
48
|
+
try {
|
|
49
|
+
args = JSON.parse(args);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const target = args?.session_id;
|
|
56
|
+
if (typeof target === "string" && target)
|
|
57
|
+
targets.push(target);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return targets;
|
|
61
|
+
}
|
|
62
|
+
function coordinatorOf(row, rows, deps = {}) {
|
|
63
|
+
const recorded = row.coordinatingCreatorSessionId;
|
|
64
|
+
if (!recorded)
|
|
65
|
+
return null;
|
|
66
|
+
const named = listedAs(rows, recorded);
|
|
67
|
+
if (named && named.id !== row.id)
|
|
68
|
+
return { id: named.id, name: named.name, via: "app" };
|
|
69
|
+
const successor = listedAs(rows, deps.successorOf?.(recorded));
|
|
70
|
+
let found = successor && successor.id !== row.id ? { id: successor.id, name: successor.name, via: "hand-off" } : null;
|
|
71
|
+
if (!found) {
|
|
72
|
+
const latest = reportTargets(row.id, deps.client).reverse().map(id => listedAs(rows, id)).find(target => target && target.id !== row.id);
|
|
73
|
+
if (latest)
|
|
74
|
+
found = { id: latest.id, name: latest.name, via: "reports" };
|
|
75
|
+
}
|
|
76
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_coordinator_resolved", message: "worked out who coordinates a lane whose recorded coordinator is not listed", meta: { session: row.id, recorded, found: found && "id" in found ? found.id : null, via: found && "via" in found ? found.via : null } });
|
|
77
|
+
return found ?? { gone: true, recorded };
|
|
78
|
+
}
|
|
@@ -3,65 +3,74 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.HOLD_MS = exports.PUSH_LIST_MAX = exports.PUSH_GAP_MS = void 0;
|
|
4
4
|
exports.conditions = conditions;
|
|
5
5
|
exports.pushMessage = pushMessage;
|
|
6
|
+
exports.stillDue = stillDue;
|
|
6
7
|
exports.pushDue = pushDue;
|
|
7
8
|
const runtime_1 = require("../../nerves/runtime");
|
|
8
9
|
const owner_notice_1 = require("../shepherd/owner-notice");
|
|
10
|
+
const app_interface_1 = require("./app-interface");
|
|
11
|
+
const digest_cards_1 = require("./digest-cards");
|
|
9
12
|
/**
|
|
10
|
-
* What is worth telling the owner unasked, judged with no model turn from the digest
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
13
|
+
* What is worth telling the owner unasked, judged with no model turn from the digest: only what only they can act on.
|
|
14
|
+
* That is work ready for them to look at, and a session waiting on their answer. Finished work and things that are
|
|
15
|
+
* broken go in the digest (`/status`), not in a push: a stuck session is resumed by the sense itself (`stuck-resume.ts`)
|
|
16
|
+
* and shown there as fixed, and the machine, the drains and the health watch have owners of their own.
|
|
17
|
+
*
|
|
18
|
+
* A condition must last before it counts, is told once and then not again until it clears and comes back, and is
|
|
19
|
+
* checked live again just before the message goes out. One message carries everything due, at most one per half hour,
|
|
20
|
+
* and the sender holds it while the owner is mid-conversation (`conversation-hold.ts`). Nothing is sent on a timer.
|
|
14
21
|
*/
|
|
15
22
|
exports.PUSH_GAP_MS = 30 * 60_000;
|
|
16
23
|
exports.PUSH_LIST_MAX = 8;
|
|
17
24
|
/** How long a condition must hold before it is told. A card's state is a fact the moment it is seen. */
|
|
18
|
-
exports.HOLD_MS = { card: 0, waiting: 10 * 60_000
|
|
19
|
-
|
|
20
|
-
const
|
|
25
|
+
exports.HOLD_MS = { card: 0, waiting: 10 * 60_000 };
|
|
26
|
+
/** Names are never cut short in a push: a cut name ends in an ellipsis, and a push is whole sentences. */
|
|
27
|
+
const WHOLE = Number.MAX_SAFE_INTEGER;
|
|
28
|
+
const HEADINGS = { "needs-you": "Waiting on you", ready: "Ready for you" };
|
|
29
|
+
const ORDER = ["needs-you", "ready"];
|
|
21
30
|
/** Every condition that holds in this digest. Prompts are left out: the waiting-prompt notice already tells those. */
|
|
22
|
-
function conditions(digest
|
|
31
|
+
function conditions(digest) {
|
|
23
32
|
const items = [];
|
|
24
33
|
for (const item of digest.needsOwner) {
|
|
25
|
-
if (item.kind === "ready")
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
items.push({ key: item.key, kind: "needs-you", text: `${(0, owner_notice_1.plain)(item.name, 60)} — ${(0, owner_notice_1.plain)(item.text, 120)}`, holdMs: exports.HOLD_MS.waiting });
|
|
29
|
-
}
|
|
30
|
-
for (const session of digest.sessions) {
|
|
31
|
-
const card = session.card;
|
|
32
|
-
if (card?.status === "done" && cards[`${card.track}/${card.slug}`] !== undefined && cards[`${card.track}/${card.slug}`] !== "done") {
|
|
33
|
-
items.push({ key: `done:${card.track}/${card.slug}`, kind: "done", text: (0, owner_notice_1.plain)(card.title, 100), holdMs: exports.HOLD_MS.card });
|
|
34
|
+
if (item.kind === "ready") {
|
|
35
|
+
const title = digest.sessions.find(session => session.id === item.session)?.card?.title;
|
|
36
|
+
items.push({ key: item.key, kind: "ready", session: item.session, text: `"${(0, owner_notice_1.plain)(item.name, WHOLE)}" has ${title ? `"${(0, owner_notice_1.plain)(title, WHOLE)}"` : "its work"} ready for you to look at.`, holdMs: exports.HOLD_MS.card });
|
|
34
37
|
}
|
|
35
|
-
if (
|
|
36
|
-
items.push({ key:
|
|
37
|
-
}
|
|
38
|
-
const machine = digest.machine;
|
|
39
|
-
if (machine && (machine.heartbeat === "bad" || machine.heartbeat === "stale")) {
|
|
40
|
-
items.push({ key: "machine:heartbeat", kind: "broken", text: `the Mac watcher's heartbeat is ${machine.heartbeat}${machine.bad ? `: ${(0, owner_notice_1.plain)(machine.bad, 100)}` : ""}`, holdMs: exports.HOLD_MS.machine });
|
|
38
|
+
if (item.kind === "waiting")
|
|
39
|
+
items.push({ key: item.key, kind: "needs-you", session: item.session, text: `"${(0, owner_notice_1.plain)(item.name, WHOLE)}" is waiting for your answer.`, holdMs: exports.HOLD_MS.waiting });
|
|
41
40
|
}
|
|
42
|
-
for (const session of machine?.watchBad ?? [])
|
|
43
|
-
items.push({ key: `watch:${session.id}`, kind: "broken", text: `${(0, owner_notice_1.plain)(session.title, 60)} failed the health watch: ${(0, owner_notice_1.plain)(session.status, 60)}`, holdMs: exports.HOLD_MS.machine });
|
|
44
|
-
for (const stale of digest.drains?.stale ?? [])
|
|
45
|
-
items.push({ key: `drain:${stale.split(":")[0]}`, kind: "broken", text: `drain ${(0, owner_notice_1.plain)(stale, 80)} since its last good poll`, holdMs: exports.HOLD_MS.drain });
|
|
46
|
-
if (!digest.appRunning)
|
|
47
|
-
items.push({ key: "app:down", kind: "broken", text: "the Copilot app is not running", holdMs: exports.HOLD_MS.machine });
|
|
48
41
|
return items;
|
|
49
42
|
}
|
|
50
|
-
/** One plain-text message with everything due, grouped by kind
|
|
43
|
+
/** One plain-text message with everything due, grouped by kind, each a whole sentence and the link that opens it. */
|
|
51
44
|
function pushMessage(items) {
|
|
52
45
|
const blocks = ORDER.map(kind => {
|
|
53
46
|
const own = items.filter(item => item.kind === kind);
|
|
54
|
-
return own.length ? [`${HEADINGS[kind]}:`, ...own.map(item => `- ${item.text}`)].join("\n") : "";
|
|
47
|
+
return own.length ? [`${HEADINGS[kind]}:`, ...own.map(item => `- ${item.text} ${(0, app_interface_1.appUrl)(item.session)}`)].join("\n") : "";
|
|
55
48
|
}).filter(Boolean);
|
|
56
49
|
return blocks.join("\n\n");
|
|
57
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* The items that still hold against a fresh listing of the app's sessions and a fresh read of the cards: the session is
|
|
53
|
+
* still listed, a waiting one still waits on an answer (a prompt has its own notice), a ready card is still ready.
|
|
54
|
+
*/
|
|
55
|
+
function stillDue(items, rows, deskRoots) {
|
|
56
|
+
const fresh = new Map(rows.map(row => [row.id, row]));
|
|
57
|
+
return items.filter(item => {
|
|
58
|
+
const row = fresh.get(item.session);
|
|
59
|
+
if (!row)
|
|
60
|
+
return false;
|
|
61
|
+
if (item.kind === "needs-you")
|
|
62
|
+
return row.state === "waiting" && !row.prompt;
|
|
63
|
+
const [track = "", slug = ""] = item.key.slice("ready:".length).split("/");
|
|
64
|
+
return (0, digest_cards_1.readCard)(deskRoots, track, slug)?.status === "collaborating";
|
|
65
|
+
});
|
|
66
|
+
}
|
|
58
67
|
/**
|
|
59
68
|
* Updates the state for this digest and tells the owner what is due. The first digest after a start only records which
|
|
60
|
-
* cards are ready
|
|
61
|
-
*
|
|
69
|
+
* cards are ready, so a restart never announces old work. A condition that is no longer true is forgotten, so it is told
|
|
70
|
+
* again if it comes back. One that a live recheck no longer finds is dropped from this message, untold.
|
|
62
71
|
*/
|
|
63
|
-
async function pushDue(digest, state, now, notify) {
|
|
64
|
-
const present = conditions(digest
|
|
72
|
+
async function pushDue(digest, state, now, notify, recheck = async (items) => items) {
|
|
73
|
+
const present = conditions(digest);
|
|
65
74
|
const keys = new Set(present.map(item => item.key));
|
|
66
75
|
for (const key of Object.keys(state.firstSeen))
|
|
67
76
|
if (!keys.has(key))
|
|
@@ -73,33 +82,27 @@ async function pushDue(digest, state, now, notify) {
|
|
|
73
82
|
state.firstSeen[item.key] ??= now;
|
|
74
83
|
if (!state.seeded) {
|
|
75
84
|
for (const item of present)
|
|
76
|
-
if (item.kind === "ready"
|
|
85
|
+
if (item.kind === "ready")
|
|
77
86
|
state.pushed[item.key] = new Date(now).toISOString();
|
|
78
87
|
state.seeded = true;
|
|
79
88
|
}
|
|
80
89
|
const due = present.filter(item => !state.pushed[item.key] && now - state.firstSeen[item.key] >= item.holdMs);
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const outcome = await notify(text, shown.map(item => item.key));
|
|
88
|
-
if (outcome !== "pending") {
|
|
89
|
-
for (const item of shown) {
|
|
90
|
-
state.pushed[item.key] = new Date(now).toISOString();
|
|
91
|
-
unsent.delete(item.key);
|
|
92
|
-
}
|
|
93
|
-
state.lastPushAt = now;
|
|
94
|
-
sent = text;
|
|
95
|
-
}
|
|
96
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_digest_push", message: "judged what to tell the owner from the digest", meta: { due: due.length, outcome, tokens: Math.ceil(text.length / 4) } });
|
|
97
|
-
}
|
|
98
|
-
for (const session of digest.sessions) {
|
|
99
|
-
const card = session.card;
|
|
100
|
-
const key = card ? `${card.track}/${card.slug}` : "";
|
|
101
|
-
if (card && !unsent.has(`done:${key}`))
|
|
102
|
-
state.cards[key] = card.status;
|
|
90
|
+
if (!due.length || now - state.lastPushAt < exports.PUSH_GAP_MS)
|
|
91
|
+
return { sent: null, due: due.length };
|
|
92
|
+
const live = await recheck(due);
|
|
93
|
+
if (!live.length) {
|
|
94
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_digest_push_stale", message: "dropped what was due because a live recheck no longer found it", meta: { due: due.length } });
|
|
95
|
+
return { sent: null, due: 0 };
|
|
103
96
|
}
|
|
104
|
-
|
|
97
|
+
const shown = live.slice(0, exports.PUSH_LIST_MAX);
|
|
98
|
+
const extra = live.length - shown.length;
|
|
99
|
+
const text = `${pushMessage(shown)}${extra ? `\n\nand ${extra} more in /status` : ""}`;
|
|
100
|
+
const outcome = await notify(text, shown.map(item => item.key));
|
|
101
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_digest_push", message: "judged what to tell the owner from the digest", meta: { due: live.length, outcome, tokens: Math.ceil(text.length / 4) } });
|
|
102
|
+
if (outcome === "pending")
|
|
103
|
+
return { sent: null, due: live.length };
|
|
104
|
+
for (const item of shown)
|
|
105
|
+
state.pushed[item.key] = new Date(now).toISOString();
|
|
106
|
+
state.lastPushAt = now;
|
|
107
|
+
return { sent: text, due: live.length };
|
|
105
108
|
}
|
|
@@ -167,6 +167,10 @@ async function buildDigest(input) {
|
|
|
167
167
|
const recentArchives = (0, store_1.readArchiveLog)(input.agentRoot)
|
|
168
168
|
.filter(entry => input.now - Date.parse(entry.at) < exports.CARD_WINDOW_MS)
|
|
169
169
|
.map(entry => ({ name: cut(entry.name, NAME_MAX), reason: `${ARCHIVE_REASONS[entry.reason]}${entry.note ? ` (${entry.note})` : ""}` }));
|
|
170
|
+
const fixed = Object.entries(input.state.resumed ?? {})
|
|
171
|
+
.filter(([, entry]) => entry.ok && input.now - Date.parse(entry.at) < exports.CARD_WINDOW_MS)
|
|
172
|
+
.sort(([, a], [, b]) => b.at.localeCompare(a.at))
|
|
173
|
+
.map(([session, entry]) => ({ session, name: cut(entry.name, NAME_MAX), what: "resumed it: its loop had stopped", at: entry.at, stop: entry.lastActivity }));
|
|
170
174
|
const digest = {
|
|
171
175
|
at: new Date(input.now).toISOString(),
|
|
172
176
|
appRunning: input.appRunning,
|
|
@@ -176,6 +180,7 @@ async function buildDigest(input) {
|
|
|
176
180
|
machine: machine.installed || machine.error ? machine : null,
|
|
177
181
|
drains,
|
|
178
182
|
merged,
|
|
183
|
+
...(fixed.length ? { fixed } : {}),
|
|
179
184
|
...(recentArchives.length ? { archived: recentArchives } : {}),
|
|
180
185
|
unread,
|
|
181
186
|
tokens: 0,
|
|
@@ -200,8 +205,10 @@ function renderDigest(digest, now, plain = false) {
|
|
|
200
205
|
blocks.push(["**Needs you**", ...digest.needsOwner.map(item => `- ${item.name} — ${item.text}${item.since ? ` (${minutes(now - item.since)})` : ""}`)].join("\n"));
|
|
201
206
|
}
|
|
202
207
|
const broken = [];
|
|
208
|
+
// A stopped session the sense resumed from this very stop is under "Fixed", not here; one that stopped again is.
|
|
209
|
+
const resumed = new Set((digest.fixed ?? []).map(item => `${item.session}@${item.stop}`));
|
|
203
210
|
for (const session of digest.sessions)
|
|
204
|
-
if (session.state === "stuck")
|
|
211
|
+
if (session.state === "stuck" && !resumed.has(`${session.id}@${session.lastActivity}`))
|
|
205
212
|
broken.push(`- ${session.name} — stuck (${session.detail})`);
|
|
206
213
|
if (digest.machine?.heartbeat === "bad" || digest.machine?.heartbeat === "stale")
|
|
207
214
|
broken.push(`- Mac watcher — heartbeat ${digest.machine.heartbeat}${digest.machine.bad ? `: ${digest.machine.bad}` : ""}`);
|
|
@@ -211,6 +218,8 @@ function renderDigest(digest, now, plain = false) {
|
|
|
211
218
|
broken.push(`- drain ${stale} since its last good poll`);
|
|
212
219
|
if (broken.length)
|
|
213
220
|
blocks.push(["**Broken**", ...broken].join("\n"));
|
|
221
|
+
if (digest.fixed?.length)
|
|
222
|
+
blocks.push(["**Fixed by me**", ...digest.fixed.map(item => `- ${item.name} — ${item.what} (${minutes(now - Date.parse(item.at))} ago)`)].join("\n"));
|
|
214
223
|
const { counts } = digest;
|
|
215
224
|
const working = digest.sessions.filter(session => session.state === "working");
|
|
216
225
|
const list = working.slice(0, WORKING_LISTED).map(session => sessionLine(session, now));
|
|
@@ -63,8 +63,6 @@ const FREE_TEXT_OPENING_CHARS = 2_000;
|
|
|
63
63
|
const FREE_TEXT_ID_WINDOW = 240;
|
|
64
64
|
/** How far into a history the first message is looked for, and the most read per pass while waiting for the first turn. */
|
|
65
65
|
exports.FIRST_MESSAGE_SCAN_BYTES = 1024 * 1024;
|
|
66
|
-
/** Histories untouched this long are not read for a first message (an old one cannot hand off a live session). */
|
|
67
|
-
const RECENT_MS = 7 * 86_400_000;
|
|
68
66
|
const stateFile = (agentRoot) => path.join((0, store_1.appSessionsStateDir)(agentRoot), "successions.json");
|
|
69
67
|
const readSuccessions = (agentRoot) => (0, store_1.readJson)(stateFile(agentRoot), { sessions: {} }).sessions;
|
|
70
68
|
exports.readSuccessions = readSuccessions;
|
|
@@ -93,30 +91,30 @@ function historyIds(client) {
|
|
|
93
91
|
return [];
|
|
94
92
|
}
|
|
95
93
|
}
|
|
96
|
-
/**
|
|
97
|
-
|
|
94
|
+
/**
|
|
95
|
+
* Read what is new in the history of each session the app lists, as far as succession needs, and remember only those,
|
|
96
|
+
* plus each pending succession: one whose successor has left the sidebar while the session it succeeds is still listed,
|
|
97
|
+
* so that session can still be retired. Anything else the app no longer lists drops out, and the record stays the size
|
|
98
|
+
* of the sidebar.
|
|
99
|
+
*/
|
|
100
|
+
function refreshSuccessions(agentRoot, client, listed) {
|
|
98
101
|
const before = (0, exports.readSuccessions)(agentRoot);
|
|
102
|
+
const live = new Set(listed);
|
|
99
103
|
const ids = historyIds(client);
|
|
100
104
|
const known = (value) => {
|
|
101
105
|
const matches = ids.filter(id => id.toLowerCase().startsWith(value));
|
|
102
106
|
return matches.length === 1 ? matches[0] : null;
|
|
103
107
|
};
|
|
104
108
|
const next = {};
|
|
105
|
-
for (const id of
|
|
109
|
+
for (const [id, entry] of Object.entries(before))
|
|
110
|
+
if (!live.has(id) && entry.predecessor && live.has(entry.predecessor))
|
|
111
|
+
next[id] = entry;
|
|
112
|
+
for (const id of live) {
|
|
106
113
|
const was = before[id];
|
|
107
114
|
if (was && !was.pending && (!was.predecessor || was.turned)) {
|
|
108
115
|
next[id] = was;
|
|
109
116
|
continue;
|
|
110
117
|
}
|
|
111
|
-
let modified;
|
|
112
|
-
try {
|
|
113
|
-
modified = fs.statSync((0, client_1.eventLogPath)(id, client)).mtimeMs;
|
|
114
|
-
}
|
|
115
|
-
catch {
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
if (!was && now - modified > RECENT_MS)
|
|
119
|
-
continue;
|
|
120
118
|
const entry = was ? { ...was } : { predecessor: null, offset: 0, pending: true };
|
|
121
119
|
let message = null;
|
|
122
120
|
let turned = false;
|
|
@@ -172,13 +170,13 @@ function successorOf(id, successions) {
|
|
|
172
170
|
}
|
|
173
171
|
/**
|
|
174
172
|
* Whether an oversize session has been handed off: it is in the oversize list, and a newer session's first message
|
|
175
|
-
* names it as the session it succeeds.
|
|
173
|
+
* names it as the session it succeeds, as the sense last recorded.
|
|
176
174
|
*/
|
|
177
|
-
function isHandedOff(agentRoot, row
|
|
175
|
+
function isHandedOff(agentRoot, row) {
|
|
178
176
|
const flagged = (0, store_1.readJson)(path.join((0, store_1.appSessionsStateDir)(agentRoot), "oversize.json"), {}).sessions ?? {};
|
|
179
177
|
if (!flagged[row.id])
|
|
180
178
|
return false;
|
|
181
|
-
const successor = successorOf(row.id,
|
|
179
|
+
const successor = successorOf(row.id, (0, exports.readSuccessions)(agentRoot));
|
|
182
180
|
if (successor)
|
|
183
181
|
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_handoff_found", message: "found the successor that a session was handed off to", meta: { session: row.id, successor } });
|
|
184
182
|
return successor !== null;
|
|
@@ -6,6 +6,7 @@ exports.retireSessions = retireSessions;
|
|
|
6
6
|
const runtime_1 = require("../../nerves/runtime");
|
|
7
7
|
const owner_notice_1 = require("../shepherd/owner-notice");
|
|
8
8
|
const app_interface_1 = require("./app-interface");
|
|
9
|
+
const coordinator_1 = require("./coordinator");
|
|
9
10
|
const handoff_1 = require("./handoff");
|
|
10
11
|
const size_watch_1 = require("./size-watch");
|
|
11
12
|
/**
|
|
@@ -27,7 +28,7 @@ exports.HANDOFF_QUIET_MS = 5 * 60_000;
|
|
|
27
28
|
exports.FINISHED_IDLE_MS = 24 * 3_600_000;
|
|
28
29
|
const quietSince = (row) => Math.max(Date.parse(row.lastActivity ?? "") || 0, Date.parse(row.updatedAt ?? "") || 0);
|
|
29
30
|
const settled = (row) => !row.isRunning && row.state === "idle" && !row.awaiting && !row.remote;
|
|
30
|
-
const
|
|
31
|
+
const recordedCoordinator = (row) => row.coordinatingCreatorSessionId ?? row.parentSessionId;
|
|
31
32
|
const short = (id) => id.slice(0, 8);
|
|
32
33
|
function childrenNote(predecessor, children) {
|
|
33
34
|
const list = children.map(child => `"${(0, owner_notice_1.plain)(child.name, 60)}" (${child.id})`).join(", ");
|
|
@@ -37,9 +38,9 @@ function childrenNote(predecessor, children) {
|
|
|
37
38
|
async function retireSessions(agentRoot, rows, deps) {
|
|
38
39
|
const send = deps.send ?? ((id, text) => (0, app_interface_1.deliverMessage)(id, text, "immediate", deps.client));
|
|
39
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);
|
|
40
|
-
const successions = (0, handoff_1.refreshSuccessions)(agentRoot, deps.client,
|
|
41
|
+
const successions = (0, handoff_1.refreshSuccessions)(agentRoot, deps.client, rows.map(row => row.id));
|
|
41
42
|
const listed = new Map(rows.map(row => [row.id, row]));
|
|
42
|
-
const childrenOf = (id) => rows.filter(row =>
|
|
43
|
+
const childrenOf = (id) => rows.filter(row => recordedCoordinator(row) === id);
|
|
43
44
|
const busyChildren = (id, except) => childrenOf(id).filter(child => child.id !== except && !(settled(child) || (child.remote && !child.isRunning)));
|
|
44
45
|
const archived = [];
|
|
45
46
|
for (const row of rows) {
|
|
@@ -70,9 +71,13 @@ async function retireSessions(agentRoot, rows, deps) {
|
|
|
70
71
|
for (const row of rows) {
|
|
71
72
|
if (archived.includes(row.id) || !settled(row) || row.openPullRequest || row.automation)
|
|
72
73
|
continue;
|
|
73
|
-
const coordinator =
|
|
74
|
+
const coordinator = recordedCoordinator(row);
|
|
74
75
|
if (!coordinator || (listed.has(coordinator) && !archived.includes(coordinator)))
|
|
75
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;
|
|
76
81
|
if (deps.now - quietSince(row) < exports.FINISHED_IDLE_MS || busyChildren(row.id, null).length)
|
|
77
82
|
continue;
|
|
78
83
|
const note = `${row.detail || "idle"}; ${(0, size_watch_1.whereItLeftOff)(row, deps.client)}`;
|
|
@@ -50,6 +50,7 @@ const runtime_1 = require("../../nerves/runtime");
|
|
|
50
50
|
const cmux_1 = require("../shepherd/cmux");
|
|
51
51
|
const os = __importStar(require("node:os"));
|
|
52
52
|
const digest_1 = require("./digest");
|
|
53
|
+
const stuck_resume_1 = require("./stuck-resume");
|
|
53
54
|
const digest_push_1 = require("./digest-push");
|
|
54
55
|
const client_1 = require("./client");
|
|
55
56
|
const prompts_1 = require("./prompts");
|
|
@@ -216,13 +217,16 @@ async function checkDigest(agentName, agentRoot, deps) {
|
|
|
216
217
|
const config = (0, identity_1.loadAgentConfig)({ agentName, agentRoot }).senses?.["app-sessions"];
|
|
217
218
|
if (!config?.enabled || !config.digest)
|
|
218
219
|
return exports.DIGEST_IDLE_MS;
|
|
219
|
-
const
|
|
220
|
+
const list = () => (0, client_1.listAppSessions)({ ...deps.client, now: () => deps.now });
|
|
221
|
+
const rows = await list();
|
|
220
222
|
const state = (0, digest_1.readDigestState)(agentRoot);
|
|
223
|
+
await (0, stuck_resume_1.resumeStuck)(agentRoot, rows, state, deps.now, { client: deps.client, ...(deps.resume ? { send: deps.resume } : {}) });
|
|
221
224
|
const digest = await (0, digest_1.writeDigest)({
|
|
222
225
|
agentRoot, config: config.digest, client: deps.client, run: deps.run, now: deps.now, home: deps.home, rows,
|
|
223
226
|
appRunning: (0, client_1.appRunning)(deps.client), waitingPrompts: (0, waiting_prompts_1.waitingPromptsOf)(agentRoot, rows, deps.now), state,
|
|
224
227
|
});
|
|
225
|
-
|
|
228
|
+
const roots = (config.digest.deskRoots ?? []).map(folder => (0, digest_1.expandHome)(folder, deps.home));
|
|
229
|
+
await (0, digest_push_1.pushDue)(digest, state, deps.now, deps.notify, async (items) => (0, digest_push_1.stillDue)(items, await list(), roots));
|
|
226
230
|
(0, digest_1.writeDigestState)(agentRoot, state);
|
|
227
231
|
return (config.digest.everySeconds ?? digest_1.DIGEST_DEFAULT_SECONDS) * 1000;
|
|
228
232
|
}
|
|
@@ -47,6 +47,7 @@ const runtime_1 = require("../../nerves/runtime");
|
|
|
47
47
|
const owner_notice_1 = require("../shepherd/owner-notice");
|
|
48
48
|
const app_interface_1 = require("./app-interface");
|
|
49
49
|
const client_1 = require("./client");
|
|
50
|
+
const coordinator_1 = require("./coordinator");
|
|
50
51
|
const store_1 = require("./store");
|
|
51
52
|
/**
|
|
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
|
|
@@ -184,8 +185,11 @@ async function noticeOversizedSessions(agentRoot, rows, deps) {
|
|
|
184
185
|
}
|
|
185
186
|
const big = [...listed.values()].filter(row => next[row.id]);
|
|
186
187
|
// A coordinator that is itself a giant is only messaged while it runs, since a message would reload it.
|
|
187
|
-
|
|
188
|
-
|
|
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;
|
|
189
193
|
return row && (row.isRunning || !next[row.id]) ? row : undefined;
|
|
190
194
|
};
|
|
191
195
|
let nudged = 0;
|
|
@@ -195,7 +199,7 @@ async function noticeOversizedSessions(agentRoot, rows, deps) {
|
|
|
195
199
|
const due = row.isRunning ? entry.nudgedBytes === undefined || entry.bytes >= entry.nudgedBytes * exports.RENUDGE_GROWTH : !entry.nudgedAt;
|
|
196
200
|
if (!due)
|
|
197
201
|
continue;
|
|
198
|
-
const boss = reachable(row
|
|
202
|
+
const boss = reachable(row);
|
|
199
203
|
const to = [...(boss && boss.id !== row.id ? [boss.id] : []), ...(row.isRunning ? [row.id] : [])];
|
|
200
204
|
if (!to.length) {
|
|
201
205
|
ownerRows.push(row);
|
|
@@ -243,7 +247,7 @@ async function noticeOversizedSessions(agentRoot, rows, deps) {
|
|
|
243
247
|
continue;
|
|
244
248
|
entry.archivedAt = at;
|
|
245
249
|
archived += 1;
|
|
246
|
-
const boss = reachable(row
|
|
250
|
+
const boss = reachable(row);
|
|
247
251
|
if (boss && boss.id !== row.id)
|
|
248
252
|
await send(boss.id, archivedNote(row.name, row.id, entry.bytes, where)).catch(failed);
|
|
249
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 } });
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RESUME_TEXT = exports.RESUMES_PER_DAY = exports.RESUME_MAX_IDLE_MS = void 0;
|
|
4
|
+
exports.resumeStuck = resumeStuck;
|
|
5
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
6
|
+
const app_interface_1 = require("./app-interface");
|
|
7
|
+
const size_watch_1 = require("./size-watch");
|
|
8
|
+
/**
|
|
9
|
+
* A session whose loop stopped (not running, its last turn called tools and no next turn started) is something an
|
|
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 too big to resume (the
|
|
12
|
+
* size watch's never-resume list) or a remote one is left alone, and a session that keeps stopping is resumed at most
|
|
13
|
+
* three times a day; past that it stays under "Broken" in the digest.
|
|
14
|
+
*/
|
|
15
|
+
exports.RESUME_MAX_IDLE_MS = 24 * 3_600_000;
|
|
16
|
+
exports.RESUMES_PER_DAY = 3;
|
|
17
|
+
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
|
+
/** Whether the app lists this session as stopped mid-loop, rather than hung while running. */
|
|
19
|
+
const loopStopped = (row) => row.state === "stuck" && !row.isRunning && !row.remote && !row.awaiting;
|
|
20
|
+
/** Resumes every session whose loop stopped since it was last resumed. Returns how many it resumed. */
|
|
21
|
+
async function resumeStuck(agentRoot, rows, state, now, deps = {}) {
|
|
22
|
+
const send = deps.send ?? ((id, text) => (0, app_interface_1.deliverMessage)(id, text, "immediate", deps.client));
|
|
23
|
+
const resumed = (state.resumed ??= {});
|
|
24
|
+
for (const [id, entry] of Object.entries(resumed)) {
|
|
25
|
+
entry.times = entry.times.filter(at => now - Date.parse(at) < 24 * 3_600_000);
|
|
26
|
+
if (!entry.times.length)
|
|
27
|
+
delete resumed[id];
|
|
28
|
+
}
|
|
29
|
+
const giants = new Set((0, size_watch_1.neverResume)(agentRoot));
|
|
30
|
+
let count = 0;
|
|
31
|
+
for (const row of rows) {
|
|
32
|
+
if (!loopStopped(row) || giants.has(row.id))
|
|
33
|
+
continue;
|
|
34
|
+
const last = Date.parse(row.lastActivity ?? "");
|
|
35
|
+
if (Number.isNaN(last) || now - last > exports.RESUME_MAX_IDLE_MS)
|
|
36
|
+
continue;
|
|
37
|
+
const before = resumed[row.id];
|
|
38
|
+
if (before?.lastActivity === row.lastActivity)
|
|
39
|
+
continue;
|
|
40
|
+
if ((before?.times.length ?? 0) >= exports.RESUMES_PER_DAY)
|
|
41
|
+
continue;
|
|
42
|
+
const asked = await send(row.id, exports.RESUME_TEXT).catch((error) => ({ ok: false, frame: null, error: error.message }));
|
|
43
|
+
const at = new Date(now).toISOString();
|
|
44
|
+
resumed[row.id] = { name: row.name, lastActivity: row.lastActivity, at, ok: asked.ok, times: [...(before?.times ?? []), at] };
|
|
45
|
+
if (asked.ok)
|
|
46
|
+
count += 1;
|
|
47
|
+
(0, runtime_1.emitNervesEvent)({ level: asked.ok ? "info" : "warn", component: "senses", event: "senses.app_sessions_stuck_resumed", message: asked.ok ? "resumed a session whose loop had stopped" : "could not resume a session whose loop had stopped", meta: { session: row.id, ok: asked.ok, ...(asked.error ? { error: asked.error } : {}) } });
|
|
48
|
+
}
|
|
49
|
+
return count;
|
|
50
|
+
}
|
|
@@ -112,7 +112,7 @@ async function noticeWaitingPrompts(agentRoot, snapshot, deps) {
|
|
|
112
112
|
/** Sends the notice to the owner on the channel Shepherd's notices use. An outcome the transport could not confirm is `unknown`, never retried, so the owner is not told twice. */
|
|
113
113
|
function ownerNotifier(agent, agentRoot, deps = {}) {
|
|
114
114
|
const resolveTargets = deps.resolveTargets ?? (() => (0, owner_notice_1.resolveNoticeTargets)(agentRoot, undefined, (0, owner_notice_1.readEnabledReachChannels)(agent, agentRoot)));
|
|
115
|
-
const send = deps.send ?? (0, owner_notice_1.createNoticeSender)(agentRoot, { origin: "proactive" });
|
|
115
|
+
const send = deps.send ?? (0, owner_notice_1.createNoticeSender)(agentRoot, { origin: "proactive", holdWhileTalking: true });
|
|
116
116
|
return async (text, keys) => {
|
|
117
117
|
const targets = await resolveTargets();
|
|
118
118
|
if (targets.length === 0) {
|
|
@@ -0,0 +1,78 @@
|
|
|
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.UNANSWERED_HOLD_MS = exports.CONVERSATION_QUIET_MS = void 0;
|
|
37
|
+
exports.ownerConversationHold = ownerConversationHold;
|
|
38
|
+
const path = __importStar(require("node:path"));
|
|
39
|
+
const session_activity_1 = require("../../heart/session-activity");
|
|
40
|
+
const session_transaction_1 = require("../../mind/session-transaction");
|
|
41
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
42
|
+
/**
|
|
43
|
+
* A notice sent unasked never talks over a conversation. While the owner is mid-exchange with the agent, on any
|
|
44
|
+
* channel, a proactive notice waits and goes with the next one after the conversation goes quiet:
|
|
45
|
+
*
|
|
46
|
+
* - a turn is running in one of their sessions (the agent is answering them now);
|
|
47
|
+
* - they wrote in the last ten minutes, or the agent did (a reply, or a message it sent them unasked, invites an answer);
|
|
48
|
+
* - something they wrote has no answer yet, for up to half an hour, so a turn that died does not hold notices forever.
|
|
49
|
+
*
|
|
50
|
+
* Teams hands the agent a message some seconds after it is sent, so a question in flight is invisible here; the
|
|
51
|
+
* ten-minute window after the agent's own last message is what keeps a notice from landing between that question and
|
|
52
|
+
* its answer.
|
|
53
|
+
*/
|
|
54
|
+
exports.CONVERSATION_QUIET_MS = 10 * 60_000;
|
|
55
|
+
exports.UNANSWERED_HOLD_MS = 30 * 60_000;
|
|
56
|
+
function ownerConversationHold(agentRoot, friendId, now, deps = {}) {
|
|
57
|
+
const inFlight = deps.inFlight ?? session_transaction_1.sessionTurnInFlight;
|
|
58
|
+
const records = (0, session_activity_1.listSessionActivity)({
|
|
59
|
+
sessionsDir: path.join(agentRoot, "state", "sessions"), friendsDir: path.join(agentRoot, "friends"), agentName: path.basename(agentRoot, ".ouro"),
|
|
60
|
+
activeThresholdMs: Number.POSITIVE_INFINITY, nowMs: now, friendId,
|
|
61
|
+
});
|
|
62
|
+
let hold = null;
|
|
63
|
+
for (const record of records) {
|
|
64
|
+
const inbound = record.lastInboundAt ? Date.parse(record.lastInboundAt) : NaN;
|
|
65
|
+
const outbound = record.lastOutboundAt ? Date.parse(record.lastOutboundAt) : NaN;
|
|
66
|
+
if (inFlight(record.sessionPath))
|
|
67
|
+
hold = "turn-running";
|
|
68
|
+
else if (now - inbound < exports.CONVERSATION_QUIET_MS || now - outbound < exports.CONVERSATION_QUIET_MS)
|
|
69
|
+
hold ??= "recent-message";
|
|
70
|
+
else if (record.unansweredInboundCount > 0 && now - inbound < exports.UNANSWERED_HOLD_MS)
|
|
71
|
+
hold ??= "unanswered";
|
|
72
|
+
if (hold === "turn-running")
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
if (hold)
|
|
76
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.owner_notice_held", message: "held a notice the owner did not ask for while they are mid-conversation", meta: { friendId, hold } });
|
|
77
|
+
return hold;
|
|
78
|
+
}
|
|
@@ -55,6 +55,7 @@ const reach_channel_1 = require("../../heart/reach-channel");
|
|
|
55
55
|
const runtime_1 = require("../../nerves/runtime");
|
|
56
56
|
const notice_outbox_1 = require("./notice-outbox");
|
|
57
57
|
const optional_packages_1 = require("../../heart/optional-packages");
|
|
58
|
+
const conversation_hold_1 = require("./conversation-hold");
|
|
58
59
|
/**
|
|
59
60
|
* The owner notice: after a judged return, the agent's owner hears what happened in one short plain message on their
|
|
60
61
|
* own channel. It is deterministic, written here and sent with no model turn, so the owner hears about every return the
|
|
@@ -301,7 +302,10 @@ async function liveBotApi(config) {
|
|
|
301
302
|
*/
|
|
302
303
|
function createNoticeSender(agentRoot, deps = {}) {
|
|
303
304
|
const bots = new Map();
|
|
305
|
+
const hold = deps.holdWhileTalking === true ? (friendId) => (0, conversation_hold_1.ownerConversationHold)(agentRoot, friendId, Date.now()) : deps.holdWhileTalking || null;
|
|
304
306
|
return async (target, text, noticeIds) => {
|
|
307
|
+
if (hold?.(target.friendId))
|
|
308
|
+
return { delivered: false, reason: "owner_in_conversation" };
|
|
305
309
|
const deliveryId = noticeDeliveryId(target.friendId, noticeIds);
|
|
306
310
|
if (target.channel === "bluebubbles") {
|
|
307
311
|
let client;
|
|
@@ -338,7 +342,7 @@ function createOwnerNotifier(options) {
|
|
|
338
342
|
const { agent, policy } = options;
|
|
339
343
|
const enabledChannels = options.enabledChannels ?? (() => readEnabledReachChannels(agent, options.agentRoot));
|
|
340
344
|
const resolveTargets = options.resolveTargets ?? (() => resolveNoticeTargets(options.agentRoot, undefined, enabledChannels()));
|
|
341
|
-
const send = options.send ?? createNoticeSender(options.agentRoot);
|
|
345
|
+
const send = options.send ?? createNoticeSender(options.agentRoot, { holdWhileTalking: true });
|
|
342
346
|
const retryWrites = new Map();
|
|
343
347
|
const recoveredNoticeIds = new Set();
|
|
344
348
|
const writes = new Set();
|
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.1163",
|
|
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.1163",
|
|
10
10
|
"bundleDependencies": [
|
|
11
11
|
"@ouro.bot/friends"
|
|
12
12
|
],
|