@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
@@ -6,9 +6,9 @@
6
6
  <meta name="color-scheme" content="dark" />
7
7
  <title>Ouro Mailbox</title>
8
8
  <meta name="description" content="The daemon-hosted shared orientation surface for agents alive on this machine." />
9
- <script type="module" crossorigin src="/assets/index-Dbska1tZ.js"></script>
10
- <link rel="modulepreload" crossorigin href="/assets/vendor-CcN1XpQ9.js">
11
- <link rel="stylesheet" crossorigin href="/assets/index-DsiKaPyH.css">
9
+ <script type="module" crossorigin src="/assets/index-DqdAt_p5.js"></script>
10
+ <link rel="modulepreload" crossorigin href="/assets/vendor-mqLhL5Io.js">
11
+ <link rel="stylesheet" crossorigin href="/assets/index-BI1pAais.css">
12
12
  </head>
13
13
  <body>
14
14
  <div id="app"></div>
@@ -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
- function item(row) {
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
- return { total: rows.length, items: rows.map(item) };
155
+ const successors = agentRoot ? (0, coordinator_1.handoffSuccessors)(agentRoot, options) : 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, options);
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
- return status(await resolve(id, options), (0, store_1.readPending)(agentRoot));
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, options));
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 = {}) {
@@ -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. */
@@ -355,6 +355,7 @@ async function listAppSessions(options = {}) {
355
355
  continue;
356
356
  const session = isRecord(workspace.session) ? workspace.session : {};
357
357
  const binding = arr(workspace.checkoutBindings)[0];
358
+ const openPr = arr(workspace.repoContexts).map(context => isRecord(context.createdPullRequest) ? context.createdPullRequest : null).find(pr => pr && !/^(merged|closed)$/i.test(str(pr.state) ?? ""));
358
359
  add(str(session.sessionId) ?? str(workspace.activeSessionId), {
359
360
  name: str(workspace.name) ?? str(session.title) ?? "(unnamed)", kind: "workspace", workspaceId: str(workspace.id), workspaceType: str(workspace.workspaceType),
360
361
  project: str(workspace.projectName), projectId: str(workspace.projectId), projectRepo: str(binding?.repoFullName), branch: str(workspace.branch), path: str(workspace.displayPath),
@@ -362,6 +363,8 @@ async function listAppSessions(options = {}) {
362
363
  isRunning: session.isRunning === true, wasInterrupted: session.wasInterrupted === true,
363
364
  remote: (str(workspace.hostId) ?? "local") !== "local" || (str(session.executionLocation) ?? "local") !== "local",
364
365
  createdAt: str(workspace.createdAt), updatedAt: str(session.updatedAt) ?? str(workspace.updatedAt),
366
+ ...(openPr ? { openPullRequest: str(openPr.htmlUrl) ?? `#${String(openPr.number)}` } : {}),
367
+ ...(session.sessionAutomation || workspace.agentMergeEnabled === true ? { automation: true } : {}),
365
368
  }, session.isRunning === true);
366
369
  }
367
370
  for (const chat of chats) {
@@ -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 `handoff.ts` knows, read once, the first time a pass needs one. */
25
+ function handoffSuccessors(agentRoot, client) {
26
+ let successions = null;
27
+ return id => (0, handoff_1.successorOf)(id, (successions ??= (0, handoff_1.refreshSuccessions)(agentRoot, client)));
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. Four things only: work that is ready
11
- * for them, work that finished, something only they can unblock, and something that stays broken. A condition must last
12
- * before it counts, each is told once until it clears, and one message carries everything due, at most one per half hour.
13
- * Nothing is ever sent on a timer.
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, stuck: 20 * 60_000, machine: 10 * 60_000, drain: 5 * 60_000 };
19
- const HEADINGS = { ready: "Ready for you", done: "Done", "needs-you": "Waiting on you", broken: "Still broken" };
20
- const ORDER = ["needs-you", "ready", "broken", "done"];
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, cards) {
31
+ function conditions(digest) {
23
32
  const items = [];
24
33
  for (const item of digest.needsOwner) {
25
- if (item.kind === "ready")
26
- items.push({ key: item.key, kind: "ready", text: `${(0, owner_notice_1.plain)(item.name, 60)} — ${(0, owner_notice_1.plain)(item.text, 200)}`, holdMs: exports.HOLD_MS.card });
27
- if (item.kind === "waiting")
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 (session.state === "stuck")
36
- items.push({ key: `stuck:${session.id}`, kind: "broken", text: `${(0, owner_notice_1.plain)(session.name, 60)} is stuck: ${(0, owner_notice_1.plain)(session.detail, 100)}`, holdMs: exports.HOLD_MS.stuck });
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: the owner notice path sends plain text, so no markdown. */
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 or done, so a restart never announces old work. A condition that is no longer true is forgotten, so it is
61
- * told again if it comes back.
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, state.cards);
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" || item.kind === "done")
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
- const unsent = new Set(due.map(item => item.key));
82
- let sent = null;
83
- if (due.length && now - state.lastPushAt >= exports.PUSH_GAP_MS) {
84
- const shown = due.slice(0, exports.PUSH_LIST_MAX);
85
- const extra = due.length - shown.length;
86
- const text = `${pushMessage(shown)}${extra ? `\n\nand ${extra} more` : ""}`;
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
- return { sent, due: due.length };
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
  }
@@ -69,6 +69,7 @@ const NAME_MAX = 60;
69
69
  const ARCHIVE_REASONS = {
70
70
  "owner-asked": "you asked",
71
71
  "handed-off": "handed off to a successor",
72
+ finished: "finished: idle a day after its coordinator went",
72
73
  "oversize-idle": "over the size limit and idle 30 min after the hand-off ask",
73
74
  "memory-pressure": "over the size limit and idle while memory ran short",
74
75
  };
@@ -166,6 +167,10 @@ async function buildDigest(input) {
166
167
  const recentArchives = (0, store_1.readArchiveLog)(input.agentRoot)
167
168
  .filter(entry => input.now - Date.parse(entry.at) < exports.CARD_WINDOW_MS)
168
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 }));
169
174
  const digest = {
170
175
  at: new Date(input.now).toISOString(),
171
176
  appRunning: input.appRunning,
@@ -175,6 +180,7 @@ async function buildDigest(input) {
175
180
  machine: machine.installed || machine.error ? machine : null,
176
181
  drains,
177
182
  merged,
183
+ ...(fixed.length ? { fixed } : {}),
178
184
  ...(recentArchives.length ? { archived: recentArchives } : {}),
179
185
  unread,
180
186
  tokens: 0,
@@ -199,8 +205,10 @@ function renderDigest(digest, now, plain = false) {
199
205
  blocks.push(["**Needs you**", ...digest.needsOwner.map(item => `- ${item.name} — ${item.text}${item.since ? ` (${minutes(now - item.since)})` : ""}`)].join("\n"));
200
206
  }
201
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}`));
202
210
  for (const session of digest.sessions)
203
- if (session.state === "stuck")
211
+ if (session.state === "stuck" && !resumed.has(`${session.id}@${session.lastActivity}`))
204
212
  broken.push(`- ${session.name} — stuck (${session.detail})`);
205
213
  if (digest.machine?.heartbeat === "bad" || digest.machine?.heartbeat === "stale")
206
214
  broken.push(`- Mac watcher — heartbeat ${digest.machine.heartbeat}${digest.machine.bad ? `: ${digest.machine.bad}` : ""}`);
@@ -210,6 +218,8 @@ function renderDigest(digest, now, plain = false) {
210
218
  broken.push(`- drain ${stale} since its last good poll`);
211
219
  if (broken.length)
212
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"));
213
223
  const { counts } = digest;
214
224
  const working = digest.sessions.filter(session => session.state === "working");
215
225
  const list = working.slice(0, WORKING_LISTED).map(session => sessionLine(session, now));