@ouro.bot/cli 0.1.0-alpha.1160 → 0.1.0-alpha.1162

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.
Files changed (32) hide show
  1. package/changelog.json +12 -0
  2. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
  3. package/deploy/unraid/sanctuary.xml +1 -1
  4. package/dist/mailbox-ui/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  5. package/dist/mailbox-ui/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  6. package/dist/mailbox-ui/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  7. package/dist/mailbox-ui/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  8. package/dist/mailbox-ui/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  9. package/dist/mailbox-ui/assets/index-BI1pAais.css +1 -0
  10. package/dist/mailbox-ui/assets/index-DqdAt_p5.js +1 -0
  11. package/dist/mailbox-ui/assets/vendor-mqLhL5Io.js +65 -0
  12. package/dist/mailbox-ui/index.html +3 -3
  13. package/dist/mind/session-transaction.js +23 -0
  14. package/dist/repertoire/tools-app-sessions.js +1 -1
  15. package/dist/senses/app-sessions/app-interface.js +31 -12
  16. package/dist/senses/app-sessions/client.js +3 -0
  17. package/dist/senses/app-sessions/coordinator.js +78 -0
  18. package/dist/senses/app-sessions/digest-push.js +62 -59
  19. package/dist/senses/app-sessions/digest.js +11 -1
  20. package/dist/senses/app-sessions/handoff.js +130 -30
  21. package/dist/senses/app-sessions/retire.js +90 -0
  22. package/dist/senses/app-sessions/sense.js +15 -3
  23. package/dist/senses/app-sessions/size-watch.js +11 -7
  24. package/dist/senses/app-sessions/stuck-resume.js +50 -0
  25. package/dist/senses/app-sessions/waiting-prompts.js +1 -1
  26. package/dist/senses/shepherd/conversation-hold.js +78 -0
  27. package/dist/senses/shepherd/owner-notice.js +5 -1
  28. package/npm-shrinkwrap.json +8 -2
  29. package/package.json +1 -1
  30. package/dist/mailbox-ui/assets/index-Dbska1tZ.js +0 -1
  31. package/dist/mailbox-ui/assets/index-DsiKaPyH.css +0 -1
  32. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +0 -61
@@ -33,53 +33,153 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.readSuccessions = exports.FIRST_MESSAGE_SCAN_BYTES = exports.MESSAGE_HEAD_CHARS = exports.SUCCEEDS_LINE = void 0;
37
+ exports.namedPredecessor = namedPredecessor;
38
+ exports.refreshSuccessions = refreshSuccessions;
39
+ exports.successorOf = successorOf;
36
40
  exports.isHandedOff = isHandedOff;
37
41
  const fs = __importStar(require("node:fs"));
38
42
  const path = __importStar(require("node:path"));
39
43
  const runtime_1 = require("../../nerves/runtime");
40
44
  const client_1 = require("./client");
41
45
  const store_1 = require("./store");
42
- const HEAD_BYTES = 16384;
43
- const RECENT_MS = 7 * 86_400_000;
44
- const HANDOFF_WORDS = /successor|hand-?off|handed off|carry on from/i;
45
46
  /**
46
- * Whether an oversize session has been handed off: it is in the oversize list, and a session newer than it opens by
47
- * naming it in a hand-off. Only the first bytes of each recent log are read, so no large history is loaded.
47
+ * Who succeeds whom. A session that takes over another's job says so in its first message: the contract is a line of its
48
+ * own, `Succeeds: <predecessor session id>`, within the message's first 16 KB. Kickoffs written before that line existed
49
+ * are read too, when "successor to" or "successor of" opens the message and is followed closely by a session id, for
50
+ * example `the successor to "desk epoch 3" (cfb84353-…)` or `the fresh successor to session 2fa5297c`.
51
+ *
52
+ * The first message sits after the start-up hooks' events, tens of KB into the history, so each history is read forward
53
+ * at most 1 MB until its first message, once; after that only for the successor's first finished turn.
48
54
  */
49
- function isHandedOff(agentRoot, row, options = {}) {
50
- const flagged = (0, store_1.readJson)(path.join((0, store_1.appSessionsStateDir)(agentRoot), "oversize.json"), {}).sessions ?? {};
51
- if (!flagged[row.id])
52
- return false;
53
- const root = path.dirname(path.dirname((0, client_1.eventLogPath)(row.id, options)));
54
- const born = Date.parse(String(row.createdAt));
55
- let names;
55
+ exports.SUCCEEDS_LINE = "Succeeds:";
56
+ const STRUCTURED = /^[ \t>*_`]*Succeeds:[ \t*_`]*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/im;
57
+ const FREE_TEXT = /\bsuccessor (?:to|of)\b/gi;
58
+ const SESSION_ID = /\b[0-9a-f]{8}(?:-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})?\b/i;
59
+ /** How much of the first message is read for the line. */
60
+ exports.MESSAGE_HEAD_CHARS = 16_384;
61
+ /** The free-text wording counts only where the message opens, and the id only close after it. */
62
+ const FREE_TEXT_OPENING_CHARS = 2_000;
63
+ const FREE_TEXT_ID_WINDOW = 240;
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
+ 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
+ const stateFile = (agentRoot) => path.join((0, store_1.appSessionsStateDir)(agentRoot), "successions.json");
69
+ const readSuccessions = (agentRoot) => (0, store_1.readJson)(stateFile(agentRoot), { sessions: {} }).sessions;
70
+ exports.readSuccessions = readSuccessions;
71
+ /** The session a first message says it succeeds: the `Succeeds:` line, else the older wording. `known` resolves a short id. */
72
+ function namedPredecessor(message, self, known) {
73
+ const head = message.slice(0, exports.MESSAGE_HEAD_CHARS);
74
+ const line = STRUCTURED.exec(head)?.[1]?.toLowerCase();
75
+ if (line && line !== self)
76
+ return { predecessor: line, marker: "structured" };
77
+ const opening = head.slice(0, FREE_TEXT_OPENING_CHARS);
78
+ for (const phrase of opening.matchAll(FREE_TEXT)) {
79
+ const after = head.slice(phrase.index + phrase[0].length, phrase.index + phrase[0].length + FREE_TEXT_ID_WINDOW);
80
+ const id = SESSION_ID.exec(after)?.[0]?.toLowerCase();
81
+ const resolved = id ? known(id) : null;
82
+ if (resolved && resolved !== self)
83
+ return { predecessor: resolved, marker: "free-text" };
84
+ }
85
+ return null;
86
+ }
87
+ const sessionsRoot = (client) => path.dirname(path.dirname((0, client_1.eventLogPath)("x", client)));
88
+ function historyIds(client) {
56
89
  try {
57
- names = fs.readdirSync(root);
90
+ return fs.readdirSync(sessionsRoot(client)).filter(name => /^[0-9a-f-]{36}$/i.test(name));
58
91
  }
59
92
  catch {
60
- return false;
93
+ return [];
61
94
  }
62
- for (const name of names) {
63
- if (name === row.id)
95
+ }
96
+ /** Read what is new in each recent history, as far as succession needs, and remember it. Returns every succession known. */
97
+ function refreshSuccessions(agentRoot, client, now = Date.now()) {
98
+ const before = (0, exports.readSuccessions)(agentRoot);
99
+ const ids = historyIds(client);
100
+ const known = (value) => {
101
+ const matches = ids.filter(id => id.toLowerCase().startsWith(value));
102
+ return matches.length === 1 ? matches[0] : null;
103
+ };
104
+ const next = {};
105
+ for (const id of ids) {
106
+ const was = before[id];
107
+ if (was && !was.pending && (!was.predecessor || was.turned)) {
108
+ next[id] = was;
64
109
  continue;
110
+ }
111
+ let modified;
65
112
  try {
66
- const file = path.join(root, name, "events.jsonl");
67
- const stat = fs.statSync(file);
68
- if (Date.now() - stat.mtimeMs > RECENT_MS || stat.birthtimeMs <= born)
69
- continue;
70
- const fd = fs.openSync(file, "r");
71
- const buf = Buffer.alloc(HEAD_BYTES);
72
- const len = fs.readSync(fd, buf, 0, buf.length, 0);
73
- fs.closeSync(fd);
74
- const head = buf.toString("utf8", 0, len);
75
- if ((head.includes(row.id) || head.includes(row.id.slice(0, 8))) && HANDOFF_WORDS.test(head)) {
76
- (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: name } });
77
- return true;
78
- }
113
+ modified = fs.statSync((0, client_1.eventLogPath)(id, client)).mtimeMs;
79
114
  }
80
115
  catch {
81
116
  continue;
82
117
  }
118
+ if (!was && now - modified > RECENT_MS)
119
+ continue;
120
+ const entry = was ? { ...was } : { predecessor: null, offset: 0, pending: true };
121
+ let message = null;
122
+ let turned = false;
123
+ const read = (0, client_1.readNewAppEvents)(id, entry.offset, exports.FIRST_MESSAGE_SCAN_BYTES, event => {
124
+ if (event.agentId !== undefined)
125
+ return;
126
+ const data = event.data && typeof event.data === "object" ? event.data : {};
127
+ if (entry.pending && !message && event.type === "user.message" && typeof data.content === "string")
128
+ message = { text: data.content, ...(typeof event.timestamp === "string" ? { at: event.timestamp } : {}) };
129
+ else if ((message || !entry.pending) && event.type === "assistant.turn_end")
130
+ turned = true;
131
+ }, client);
132
+ entry.offset = read.offset;
133
+ if (entry.pending) {
134
+ const first = message;
135
+ if (first) {
136
+ delete entry.pending;
137
+ const named = namedPredecessor(first.text, id, known);
138
+ Object.assign(entry, named ?? {}, first.at ? { at: first.at } : {});
139
+ }
140
+ else if (entry.offset >= exports.FIRST_MESSAGE_SCAN_BYTES)
141
+ delete entry.pending;
142
+ }
143
+ if (entry.predecessor && turned)
144
+ entry.turned = true;
145
+ next[id] = entry;
83
146
  }
84
- return false;
147
+ (0, store_1.writeJson)(stateFile(agentRoot), { sessions: next });
148
+ return next;
149
+ }
150
+ /** The newest session that took over `id`'s job, following the chain of hand-offs to the live end; null when none did. */
151
+ function successorOf(id, successions) {
152
+ // The newest claim wins when two sessions name the same predecessor.
153
+ const direct = (of) => {
154
+ let newest = null;
155
+ for (const [claimant, entry] of Object.entries(successions)) {
156
+ const at = Date.parse(String(entry.at)) || 0;
157
+ if (entry.predecessor === of && (!newest || at > newest.at))
158
+ newest = { id: claimant, at };
159
+ }
160
+ return newest?.id ?? null;
161
+ };
162
+ let current = id;
163
+ const seen = new Set([id]);
164
+ for (let later = direct(current); later; later = direct(current)) {
165
+ // Sessions that claim to succeed each other own nothing for certain, so none of them is retired.
166
+ if (seen.has(later))
167
+ return null;
168
+ seen.add(later);
169
+ current = later;
170
+ }
171
+ return current === id ? null : current;
172
+ }
173
+ /**
174
+ * 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.
176
+ */
177
+ function isHandedOff(agentRoot, row, options = {}) {
178
+ const flagged = (0, store_1.readJson)(path.join((0, store_1.appSessionsStateDir)(agentRoot), "oversize.json"), {}).sessions ?? {};
179
+ if (!flagged[row.id])
180
+ return false;
181
+ const successor = successorOf(row.id, refreshSuccessions(agentRoot, options));
182
+ if (successor)
183
+ (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
+ return successor !== null;
85
185
  }
@@ -0,0 +1,90 @@
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, deps.now);
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
+ }
@@ -50,10 +50,12 @@ 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");
56
57
  const store_1 = require("./store");
58
+ const retire_1 = require("./retire");
57
59
  const size_watch_1 = require("./size-watch");
58
60
  const waiting_prompts_1 = require("./waiting-prompts");
59
61
  const wake_runner_1 = require("./wake-runner");
@@ -215,13 +217,16 @@ async function checkDigest(agentName, agentRoot, deps) {
215
217
  const config = (0, identity_1.loadAgentConfig)({ agentName, agentRoot }).senses?.["app-sessions"];
216
218
  if (!config?.enabled || !config.digest)
217
219
  return exports.DIGEST_IDLE_MS;
218
- const rows = await (0, client_1.listAppSessions)({ ...deps.client, now: () => deps.now });
220
+ const list = () => (0, client_1.listAppSessions)({ ...deps.client, now: () => deps.now });
221
+ const rows = await list();
219
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 } : {}) });
220
224
  const digest = await (0, digest_1.writeDigest)({
221
225
  agentRoot, config: config.digest, client: deps.client, run: deps.run, now: deps.now, home: deps.home, rows,
222
226
  appRunning: (0, client_1.appRunning)(deps.client), waitingPrompts: (0, waiting_prompts_1.waitingPromptsOf)(agentRoot, rows, deps.now), state,
223
227
  });
224
- await (0, digest_push_1.pushDue)(digest, state, deps.now, deps.notify);
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));
225
230
  (0, digest_1.writeDigestState)(agentRoot, state);
226
231
  return (config.digest.everySeconds ?? digest_1.DIGEST_DEFAULT_SECONDS) * 1000;
227
232
  }
@@ -254,7 +259,14 @@ function startAppSessionsSense(options) {
254
259
  waitingPoll = waitingPoll.then(() => recordSnapshot(agentRoot, client, now())).then(taken => (0, waiting_prompts_1.noticeWaitingPrompts)(agentRoot, taken, { notify: notifyOwner, now: now() })).catch((error) => {
255
260
  (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 } });
256
261
  });
257
- sizePoll = sizePoll.then(async () => (0, size_watch_1.noticeOversizedSessions)(agentRoot, await (0, client_1.listAppSessions)({ ...client, now: () => now() }), { notify: notifyOwner, now: now(), client, ...(options.memory ? { memory: options.memory } : {}) })).then(() => undefined).catch((error) => {
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) => {
258
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 } });
259
271
  });
260
272
  cancelSnapshot = schedule(snapshotTick, exports.SNAPSHOT_MS);
@@ -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
@@ -76,9 +77,9 @@ exports.readOversize = readOversize;
76
77
  const neverResume = (agentRoot) => Object.keys((0, exports.readOversize)(agentRoot));
77
78
  exports.neverResume = neverResume;
78
79
  const mb = (bytes) => bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
79
- function handoffNudge(name, bytes, asked = 0, askedAtBytes) {
80
+ function handoffNudge(name, bytes, asked = 0, askedAtBytes, id = "<its session id>") {
80
81
  const again = asked ? ` This is ask ${asked + 1}${askedAtBytes ? `: it was ${mb(askedAtBytes)} at the last one and is still growing` : ""}.` : "";
81
- 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, start a fresh successor session that reads that checkpoint plus the tail of the old log, then archive the old one. This goes to the session and to its coordinator; the coordinator starts the successor when there is one. Once it has been idle for ${exports.IDLE_ARCHIVE_MS / 60_000} minutes it is archived for you (reversibly) to free its memory. Keep images out of chat (save screenshots and art as files and link the path): inline images are nearly all of the size.`;
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.`;
82
83
  }
83
84
  function archivedNote(name, id, bytes, where) {
84
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).`;
@@ -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
- const reachable = (id) => {
188
- const row = id ? listed.get(id) : undefined;
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, client);
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.coordinatingCreatorSessionId);
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);
@@ -203,7 +207,7 @@ async function noticeOversizedSessions(agentRoot, rows, deps) {
203
207
  }
204
208
  // An entry from before asks were counted had one ask.
205
209
  const asked = entry.nudges ?? (entry.nudgedAt ? 1 : 0);
206
- const text = handoffNudge(row.name, entry.bytes, asked, entry.nudgedBytes);
210
+ const text = handoffNudge(row.name, entry.bytes, asked, entry.nudgedBytes, row.id);
207
211
  const reached = [];
208
212
  for (const id of to)
209
213
  if ((await send(id, text).catch(failed)).ok)
@@ -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.coordinatingCreatorSessionId);
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();
@@ -1,12 +1,15 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1160",
3
+ "version": "0.1.0-alpha.1162",
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.1160",
9
+ "version": "0.1.0-alpha.1162",
10
+ "bundleDependencies": [
11
+ "@ouro.bot/friends"
12
+ ],
10
13
  "dependencies": {
11
14
  "@anthropic-ai/sdk": "^0.78.0",
12
15
  "@ouro.bot/friends": "0.1.0-alpha.18",
@@ -1427,6 +1430,7 @@
1427
1430
  "version": "0.1.0-alpha.18",
1428
1431
  "resolved": "https://registry.npmjs.org/@ouro.bot/friends/-/friends-0.1.0-alpha.18.tgz",
1429
1432
  "integrity": "sha512-28DqPjiZ3kOVNBbFNGWqvfRO11xDn7V0ggaMUZvSx8pY9rHgnbMRzSc5NPtdjDTUpaYS28mRQCNqTgx+R5F8fQ==",
1433
+ "inBundle": true,
1430
1434
  "license": "Apache-2.0",
1431
1435
  "dependencies": {
1432
1436
  "libsodium-wrappers": "0.8.4"
@@ -5761,12 +5765,14 @@
5761
5765
  "version": "0.8.4",
5762
5766
  "resolved": "https://registry.npmjs.org/libsodium/-/libsodium-0.8.4.tgz",
5763
5767
  "integrity": "sha512-lMcYaRi0zcs7tarATsQUYC7rstliIXZuoq0c6zXSgNtSNtdvBgkSegjWhpMJAXzKX3SUSwIp7+zEsob+j3LuRw==",
5768
+ "inBundle": true,
5764
5769
  "license": "ISC"
5765
5770
  },
5766
5771
  "node_modules/libsodium-wrappers": {
5767
5772
  "version": "0.8.4",
5768
5773
  "resolved": "https://registry.npmjs.org/libsodium-wrappers/-/libsodium-wrappers-0.8.4.tgz",
5769
5774
  "integrity": "sha512-mu8aAWucZjTB5O/BtGXtW4e1agy7uHxNYG7zPthmmD1jU43LCDmSWZLN4JhflbdPXj3yDO4lxM1O9hLDgIOXDw==",
5775
+ "inBundle": true,
5770
5776
  "license": "ISC",
5771
5777
  "dependencies": {
5772
5778
  "libsodium": "^0.8.0"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1160",
3
+ "version": "0.1.0-alpha.1162",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },