@ouro.bot/cli 0.1.0-alpha.1143 → 0.1.0-alpha.1145
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/heart/identity.js +37 -0
- package/dist/repertoire/guardrails.js +1 -1
- package/dist/repertoire/tools-app-sessions.js +21 -2
- package/dist/senses/app-sessions/digest-cards.js +187 -0
- package/dist/senses/app-sessions/digest-push.js +105 -0
- package/dist/senses/app-sessions/digest-sources.js +204 -0
- package/dist/senses/app-sessions/digest.js +271 -0
- package/dist/senses/app-sessions/sense.js +82 -2
- package/dist/senses/app-sessions/size-watch.js +108 -0
- package/dist/senses/teams.js +9 -0
- 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.1145",
|
|
6
|
+
"changes": [
|
|
7
|
+
"The app-sessions sense now flags any Copilot app session whose history passes 500 MB, because the app loads a whole history into memory whenever it resumes that session, and several multi-GB ones froze a Mac. It asks the session's coordinator (or the session itself) once, with no model turn, to hand off to a fresh successor and to keep images out of chat, and records the session as never-resume."
|
|
8
|
+
]
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"version": "0.1.0-alpha.1144",
|
|
12
|
+
"changes": [
|
|
13
|
+
"Away from your Mac, you can now see how things are going. The app-sessions sense builds a status digest with no model turn (sessions and their task cards' next steps, the Mac's health, the drains, what merged today), answers /status or \"how's it going?\" in Teams from it at no token cost, and tells you, in plain text, only what is ready for you, done, waiting on you, or still broken."
|
|
14
|
+
]
|
|
15
|
+
},
|
|
4
16
|
{
|
|
5
17
|
"version": "0.1.0-alpha.1143",
|
|
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.1145</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
package/dist/heart/identity.js
CHANGED
|
@@ -175,6 +175,41 @@ function hasStaleWorkbenchBundleEntry(rawSenses, rawMcpServers) {
|
|
|
175
175
|
const rawWorkbench = rawSenses.workbench;
|
|
176
176
|
return !(isPlainRecord(rawWorkbench) && rawWorkbench.enabled === false);
|
|
177
177
|
}
|
|
178
|
+
function normalizeDigest(raw, fail) {
|
|
179
|
+
if (!isPlainRecord(raw))
|
|
180
|
+
fail("digest must be an object");
|
|
181
|
+
const { everySeconds, drains, deskRoots, mergedToday } = raw;
|
|
182
|
+
const argv = (value) => Array.isArray(value) && value.length > 0 && value.every(part => typeof part === "string" && part.length > 0);
|
|
183
|
+
const result = {};
|
|
184
|
+
if (everySeconds !== undefined) {
|
|
185
|
+
if (typeof everySeconds !== "number" || !Number.isInteger(everySeconds) || everySeconds < 60)
|
|
186
|
+
fail("digest.everySeconds must be a whole number of seconds, 60 or more");
|
|
187
|
+
result.everySeconds = everySeconds;
|
|
188
|
+
}
|
|
189
|
+
if (drains !== undefined) {
|
|
190
|
+
if (!argv(drains))
|
|
191
|
+
fail("digest.drains must be a non-empty array of strings");
|
|
192
|
+
result.drains = drains;
|
|
193
|
+
}
|
|
194
|
+
if (deskRoots !== undefined) {
|
|
195
|
+
if (!argv(deskRoots))
|
|
196
|
+
fail("digest.deskRoots must be a non-empty array of folders");
|
|
197
|
+
result.deskRoots = deskRoots;
|
|
198
|
+
}
|
|
199
|
+
if (mergedToday !== undefined) {
|
|
200
|
+
if (!Array.isArray(mergedToday))
|
|
201
|
+
fail("digest.mergedToday must be an array");
|
|
202
|
+
result.mergedToday = mergedToday.map((entry, index) => {
|
|
203
|
+
const item = isPlainRecord(entry) ? entry : {};
|
|
204
|
+
if (typeof item.label !== "string" || !item.label.trim())
|
|
205
|
+
fail(`digest.mergedToday[${index}].label must be a non-empty name`);
|
|
206
|
+
if (!argv(item.command))
|
|
207
|
+
fail(`digest.mergedToday[${index}].command must be a non-empty array of strings`);
|
|
208
|
+
return { label: item.label.trim(), command: item.command };
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
return result;
|
|
212
|
+
}
|
|
178
213
|
function normalizeWakeRunners(rawSense, configFile) {
|
|
179
214
|
function fail(what) {
|
|
180
215
|
(0, runtime_1.emitNervesEvent)({ level: "error", event: "config_identity.error", component: "config/identity", message: "agent config has invalid wake runners", meta: { path: configFile } });
|
|
@@ -184,6 +219,8 @@ function normalizeWakeRunners(rawSense, configFile) {
|
|
|
184
219
|
const result = {};
|
|
185
220
|
if (issueDrains !== undefined)
|
|
186
221
|
result.retiredIssueDrains = true;
|
|
222
|
+
if (rawSense.digest !== undefined)
|
|
223
|
+
result.digest = normalizeDigest(rawSense.digest, fail);
|
|
187
224
|
if (wakeRunners !== undefined) {
|
|
188
225
|
if (!Array.isArray(wakeRunners))
|
|
189
226
|
fail("wakeRunners must be an array");
|
|
@@ -424,7 +424,7 @@ const COMMERCE_AUTHORITY_TOOLS = new Set(["stripe_create_card", "flight_hold", "
|
|
|
424
424
|
// A call with no known trust level fails closed.
|
|
425
425
|
const SHEPHERD_FAMILY_TOOLS = new Set(["shepherd_overview", "shepherd_read", "shepherd_signal", "shepherd_send"]);
|
|
426
426
|
// The app-sessions tools read and write the owner's Copilot app sessions on this machine: family only, as Shepherd's.
|
|
427
|
-
const APP_SESSIONS_FAMILY_TOOLS = new Set(["app_sessions_list", "app_sessions_tail", "app_sessions_send", "app_sessions_resume", "app_sessions_new", "app_sessions_archive", "app_sessions_restart", "app_sessions_watch"]);
|
|
427
|
+
const APP_SESSIONS_FAMILY_TOOLS = new Set(["app_sessions_list", "app_sessions_tail", "app_sessions_send", "app_sessions_resume", "app_sessions_new", "app_sessions_archive", "app_sessions_restart", "app_sessions_watch", "app_sessions_digest"]);
|
|
428
428
|
const MAIL_FAMILY_TOOLS = new Set(["mail_screener", "mail_decide", "mail_access_log", "mail_send", "mail_index_refresh"]);
|
|
429
429
|
const MAIL_DELEGATED_READ_TOOLS = new Set(["mail_recent", "mail_search"]);
|
|
430
430
|
function opaqueAnsiShellAtoms(command) {
|
|
@@ -33,12 +33,13 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.appSessionsToolDefinitions = exports.appSessionsWatchTool = exports.appSessionsRestartTool = exports.appSessionsArchiveTool = exports.appSessionsNewTool = exports.appSessionsResumeTool = exports.appSessionsSendTool = exports.appSessionsTailTool = exports.appSessionsListTool = void 0;
|
|
36
|
+
exports.appSessionsToolDefinitions = exports.appSessionsWatchTool = exports.appSessionsDigestTool = exports.appSessionsRestartTool = exports.appSessionsArchiveTool = exports.appSessionsNewTool = exports.appSessionsResumeTool = exports.appSessionsSendTool = exports.appSessionsTailTool = exports.appSessionsListTool = void 0;
|
|
37
37
|
exports.appSessionsToolsEnabled = appSessionsToolsEnabled;
|
|
38
38
|
const fs = __importStar(require("node:fs"));
|
|
39
39
|
const path = __importStar(require("node:path"));
|
|
40
40
|
const runtime_1 = require("../nerves/runtime");
|
|
41
41
|
const client_1 = require("../senses/app-sessions/client");
|
|
42
|
+
const digest_1 = require("../senses/app-sessions/digest");
|
|
42
43
|
const store_1 = require("../senses/app-sessions/store");
|
|
43
44
|
/**
|
|
44
45
|
* The app-sessions tools: read and write this machine's GitHub Copilot app sessions. Every write is logged as a
|
|
@@ -328,6 +329,24 @@ exports.appSessionsRestartTool = {
|
|
|
328
329
|
? { mutates: "external_side_effect", risk: "high", reason: "restarts the owner's Copilot app" }
|
|
329
330
|
: { mutates: "none", risk: "low" },
|
|
330
331
|
};
|
|
332
|
+
exports.appSessionsDigestTool = {
|
|
333
|
+
tool: {
|
|
334
|
+
type: "function",
|
|
335
|
+
function: {
|
|
336
|
+
name: "app_sessions_digest",
|
|
337
|
+
description: "How everything is going, already worked out with no model: what needs the owner, what is broken, each working session with its card's next step, the Mac's health, the drains and what merged today. Answer \"how's it going?\" from it in a few lines of your own, leading with what needs the owner; never add facts it does not carry. It is at most a few minutes old and says so when older.",
|
|
338
|
+
parameters: { type: "object", properties: {}, additionalProperties: false },
|
|
339
|
+
},
|
|
340
|
+
},
|
|
341
|
+
handler: (_args, ctx) => run("app_sessions_digest", ctx, (agentRoot) => {
|
|
342
|
+
const digest = (0, digest_1.readDigestText)(agentRoot, Date.now());
|
|
343
|
+
if (!digest)
|
|
344
|
+
throw new Error("no status digest yet: it is built when agent.json gives the app-sessions sense a digest block");
|
|
345
|
+
return { digest };
|
|
346
|
+
}),
|
|
347
|
+
summaryKeys: [],
|
|
348
|
+
riskProfile: () => ({ mutates: "none", risk: "low" }),
|
|
349
|
+
};
|
|
331
350
|
exports.appSessionsWatchTool = {
|
|
332
351
|
tool: {
|
|
333
352
|
type: "function",
|
|
@@ -353,5 +372,5 @@ exports.appSessionsWatchTool = {
|
|
|
353
372
|
riskProfile: { mutates: "durable_state_write", risk: "high", reason: "changes which app sessions' replies wake the agent" },
|
|
354
373
|
};
|
|
355
374
|
exports.appSessionsToolDefinitions = [
|
|
356
|
-
exports.appSessionsListTool, exports.appSessionsTailTool, exports.appSessionsSendTool, exports.appSessionsResumeTool, exports.appSessionsNewTool, exports.appSessionsArchiveTool, exports.appSessionsRestartTool, exports.appSessionsWatchTool,
|
|
375
|
+
exports.appSessionsListTool, exports.appSessionsTailTool, exports.appSessionsSendTool, exports.appSessionsResumeTool, exports.appSessionsNewTool, exports.appSessionsArchiveTool, exports.appSessionsRestartTool, exports.appSessionsWatchTool, exports.appSessionsDigestTool,
|
|
357
376
|
];
|
|
@@ -0,0 +1,187 @@
|
|
|
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.FIRST_SCAN_BYTES = void 0;
|
|
37
|
+
exports.scanFocus = scanFocus;
|
|
38
|
+
exports.readCard = readCard;
|
|
39
|
+
const fs = __importStar(require("node:fs"));
|
|
40
|
+
const path = __importStar(require("node:path"));
|
|
41
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
42
|
+
const client_1 = require("./client");
|
|
43
|
+
const CHUNK_BYTES = 256 * 1024;
|
|
44
|
+
/** The most of one session's history the first scan reads, newest first; a declaration older than this is not found. */
|
|
45
|
+
exports.FIRST_SCAN_BYTES = 512 * 1024 * 1024;
|
|
46
|
+
const NEXT_MAX_CHARS = 120;
|
|
47
|
+
const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
48
|
+
function declaration(line) {
|
|
49
|
+
let event;
|
|
50
|
+
try {
|
|
51
|
+
event = JSON.parse(line);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
if (event.type !== "assistant.message" || !Array.isArray(event.data?.toolRequests))
|
|
57
|
+
return null;
|
|
58
|
+
let found = null;
|
|
59
|
+
for (const request of event.data.toolRequests) {
|
|
60
|
+
if (typeof request.name !== "string" || !request.name.endsWith("task_focus"))
|
|
61
|
+
continue;
|
|
62
|
+
const args = (request.arguments && typeof request.arguments === "object" ? request.arguments : {});
|
|
63
|
+
if (args.clear === true)
|
|
64
|
+
found = "clear";
|
|
65
|
+
else if (typeof args.track === "string" && typeof args.slug === "string" && SLUG.test(args.track) && SLUG.test(args.slug))
|
|
66
|
+
found = { track: args.track, slug: args.slug };
|
|
67
|
+
}
|
|
68
|
+
return found;
|
|
69
|
+
}
|
|
70
|
+
function applyDeclaration(next, found) {
|
|
71
|
+
if (found === "clear") {
|
|
72
|
+
delete next.track;
|
|
73
|
+
delete next.slug;
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
next.track = found.track;
|
|
77
|
+
next.slug = found.slug;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** The newest declaration in the log, found by reading backwards from the end, as the entry that continues from the end. */
|
|
81
|
+
function scanBackwards(fd, size, maxBytes) {
|
|
82
|
+
const entry = { offset: size };
|
|
83
|
+
let position = size;
|
|
84
|
+
let carry = Buffer.alloc(0);
|
|
85
|
+
while (position > 0 && size - position < maxBytes) {
|
|
86
|
+
const start = Math.max(0, position - CHUNK_BYTES);
|
|
87
|
+
const chunk = Buffer.alloc(position - start);
|
|
88
|
+
fs.readSync(fd, chunk, 0, chunk.length, start);
|
|
89
|
+
const buffer = Buffer.concat([chunk, carry]);
|
|
90
|
+
const first = start > 0 ? buffer.indexOf(10) : -1;
|
|
91
|
+
position = start;
|
|
92
|
+
if (start > 0 && first < 0) {
|
|
93
|
+
carry = buffer;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
carry = start > 0 ? buffer.subarray(0, first + 1) : Buffer.alloc(0);
|
|
97
|
+
const lines = buffer.subarray(first + 1).toString("utf-8").split("\n");
|
|
98
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
99
|
+
if (!lines[index].includes("task_focus"))
|
|
100
|
+
continue;
|
|
101
|
+
const found = declaration(lines[index]);
|
|
102
|
+
if (!found)
|
|
103
|
+
continue;
|
|
104
|
+
applyDeclaration(entry, found);
|
|
105
|
+
return { entry, bytes: size - position };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return { entry, bytes: size - position };
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Finds the task the session declared. A session not seen before is read backwards from its end until its newest
|
|
112
|
+
* declaration; after that only what was added since is read, forwards, up to `maxBytes`.
|
|
113
|
+
*/
|
|
114
|
+
function scan(id, entry, maxBytes, options = {}) {
|
|
115
|
+
let fd;
|
|
116
|
+
try {
|
|
117
|
+
fd = fs.openSync((0, client_1.eventLogPath)(id, options), "r");
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return { entry: entry ?? { offset: 0 }, bytes: 0 };
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const size = fs.fstatSync(fd).size;
|
|
124
|
+
if (entry === undefined)
|
|
125
|
+
return scanBackwards(fd, size, Math.min(maxBytes, exports.FIRST_SCAN_BYTES));
|
|
126
|
+
let offset = Math.min(entry.offset, size);
|
|
127
|
+
const next = { offset, ...(entry.track ? { track: entry.track, slug: entry.slug } : {}) };
|
|
128
|
+
const begin = offset;
|
|
129
|
+
let carry = Buffer.alloc(0);
|
|
130
|
+
while (offset < size && offset - begin < maxBytes) {
|
|
131
|
+
const chunk = Buffer.alloc(Math.min(CHUNK_BYTES, size - offset));
|
|
132
|
+
fs.readSync(fd, chunk, 0, chunk.length, offset);
|
|
133
|
+
offset += chunk.length;
|
|
134
|
+
const buffer = Buffer.concat([carry, chunk]);
|
|
135
|
+
const end = buffer.lastIndexOf(10);
|
|
136
|
+
carry = buffer.subarray(end + 1);
|
|
137
|
+
const lines = end < 0 ? [] : buffer.subarray(0, end).toString("utf-8").split("\n");
|
|
138
|
+
for (const line of lines) {
|
|
139
|
+
if (!line.includes("task_focus"))
|
|
140
|
+
continue;
|
|
141
|
+
const found = declaration(line);
|
|
142
|
+
if (found)
|
|
143
|
+
applyDeclaration(next, found);
|
|
144
|
+
}
|
|
145
|
+
next.offset = offset - carry.length;
|
|
146
|
+
}
|
|
147
|
+
return { entry: next, bytes: offset - begin };
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
fs.closeSync(fd);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** `scan` with a record of how much history was read and whether a task was found, so the digest's cost is visible. */
|
|
154
|
+
function scanFocus(id, entry, maxBytes, options = {}) {
|
|
155
|
+
const scanned = scan(id, entry, maxBytes, options);
|
|
156
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_focus_scanned", message: "scanned a session's history for its declared task", meta: { bytes: scanned.bytes, first: entry === undefined, found: !!scanned.entry.track } });
|
|
157
|
+
return scanned;
|
|
158
|
+
}
|
|
159
|
+
/** The card at `<root>/<track>/<slug>/task.md`, or archived beside it, in the first desk root that has it: its title, status and next step. */
|
|
160
|
+
function readCard(roots, track, slug) {
|
|
161
|
+
for (const root of roots) {
|
|
162
|
+
const body = [path.join(root, track, slug, "task.md"), path.join(root, track, "_archive", slug, "task.md")].map(file => {
|
|
163
|
+
try {
|
|
164
|
+
return fs.readFileSync(file, "utf-8");
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
}).find(content => content !== null);
|
|
170
|
+
if (body === undefined)
|
|
171
|
+
continue;
|
|
172
|
+
const front = /^---\n([\s\S]*?)\n---/.exec(body)?.[1] ?? "";
|
|
173
|
+
const field = (name) => {
|
|
174
|
+
const value = new RegExp(`^${name}:\\s*(.+)$`, "m").exec(front)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
|
|
175
|
+
return value || null;
|
|
176
|
+
};
|
|
177
|
+
const next = /^\*\*Next step:\*\*\s*(.+)$/m.exec(body)?.[1]?.trim().replace(/[*_`]/g, "");
|
|
178
|
+
return {
|
|
179
|
+
track,
|
|
180
|
+
slug,
|
|
181
|
+
title: field("title") ?? slug,
|
|
182
|
+
status: field("status") ?? "unknown",
|
|
183
|
+
next: next ? (next.length > NEXT_MAX_CHARS ? `${next.slice(0, NEXT_MAX_CHARS - 1)}…` : next) : null,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.HOLD_MS = exports.PUSH_LIST_MAX = exports.PUSH_GAP_MS = void 0;
|
|
4
|
+
exports.conditions = conditions;
|
|
5
|
+
exports.pushMessage = pushMessage;
|
|
6
|
+
exports.pushDue = pushDue;
|
|
7
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
8
|
+
const owner_notice_1 = require("../shepherd/owner-notice");
|
|
9
|
+
/**
|
|
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.
|
|
14
|
+
*/
|
|
15
|
+
exports.PUSH_GAP_MS = 30 * 60_000;
|
|
16
|
+
exports.PUSH_LIST_MAX = 8;
|
|
17
|
+
/** 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"];
|
|
21
|
+
/** Every condition that holds in this digest. Prompts are left out: the waiting-prompt notice already tells those. */
|
|
22
|
+
function conditions(digest, cards) {
|
|
23
|
+
const items = [];
|
|
24
|
+
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
|
+
}
|
|
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 });
|
|
41
|
+
}
|
|
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
|
+
return items;
|
|
49
|
+
}
|
|
50
|
+
/** One plain-text message with everything due, grouped by kind: the owner notice path sends plain text, so no markdown. */
|
|
51
|
+
function pushMessage(items) {
|
|
52
|
+
const blocks = ORDER.map(kind => {
|
|
53
|
+
const own = items.filter(item => item.kind === kind);
|
|
54
|
+
return own.length ? [`${HEADINGS[kind]}:`, ...own.map(item => `- ${item.text}`)].join("\n") : "";
|
|
55
|
+
}).filter(Boolean);
|
|
56
|
+
return blocks.join("\n\n");
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* 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.
|
|
62
|
+
*/
|
|
63
|
+
async function pushDue(digest, state, now, notify) {
|
|
64
|
+
const present = conditions(digest, state.cards);
|
|
65
|
+
const keys = new Set(present.map(item => item.key));
|
|
66
|
+
for (const key of Object.keys(state.firstSeen))
|
|
67
|
+
if (!keys.has(key))
|
|
68
|
+
delete state.firstSeen[key];
|
|
69
|
+
for (const key of Object.keys(state.pushed))
|
|
70
|
+
if (!keys.has(key))
|
|
71
|
+
delete state.pushed[key];
|
|
72
|
+
for (const item of present)
|
|
73
|
+
state.firstSeen[item.key] ??= now;
|
|
74
|
+
if (!state.seeded) {
|
|
75
|
+
for (const item of present)
|
|
76
|
+
if (item.kind === "ready" || item.kind === "done")
|
|
77
|
+
state.pushed[item.key] = new Date(now).toISOString();
|
|
78
|
+
state.seeded = true;
|
|
79
|
+
}
|
|
80
|
+
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;
|
|
103
|
+
}
|
|
104
|
+
return { sent, due: due.length };
|
|
105
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
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.MERGED_TTL_MS = exports.DRAIN_STALE_MS = exports.HEARTBEAT_STALE_S = void 0;
|
|
37
|
+
exports.readMachine = readMachine;
|
|
38
|
+
exports.parseDrains = parseDrains;
|
|
39
|
+
exports.readDrains = readDrains;
|
|
40
|
+
exports.parseHttp = parseHttp;
|
|
41
|
+
exports.startOfToday = startOfToday;
|
|
42
|
+
exports.readMergedToday = readMergedToday;
|
|
43
|
+
exports.sourceFailed = sourceFailed;
|
|
44
|
+
exports.mergedCacheFile = mergedCacheFile;
|
|
45
|
+
exports.isFolder = isFolder;
|
|
46
|
+
const fs = __importStar(require("node:fs"));
|
|
47
|
+
const path = __importStar(require("node:path"));
|
|
48
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
49
|
+
const client_1 = require("./client");
|
|
50
|
+
const store_1 = require("./store");
|
|
51
|
+
/** A heartbeat older than this is the watcher itself gone quiet. */
|
|
52
|
+
exports.HEARTBEAT_STALE_S = 180;
|
|
53
|
+
/** A drain whose last good poll is older than this is not polling. */
|
|
54
|
+
exports.DRAIN_STALE_MS = 15 * 60_000;
|
|
55
|
+
const MAX_MERGED_LISTED = 8;
|
|
56
|
+
function record(value) {
|
|
57
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
58
|
+
}
|
|
59
|
+
function text(value) {
|
|
60
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
61
|
+
}
|
|
62
|
+
/** The machine's health, from `housesitter restart-copilot --status --json`. */
|
|
63
|
+
async function readMachine(options) {
|
|
64
|
+
const empty = { installed: false, heartbeat: "unknown", beatAgeS: null, bad: null, restartedAt: null, resumedAt: null, watched: 0, watchBad: [] };
|
|
65
|
+
let result;
|
|
66
|
+
try {
|
|
67
|
+
result = await (0, client_1.restartStatus)(options);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
return { ...empty, error: error.message };
|
|
71
|
+
}
|
|
72
|
+
if (!result.installed)
|
|
73
|
+
return empty;
|
|
74
|
+
const status = record(result.status);
|
|
75
|
+
const recovery = record(status.recovery);
|
|
76
|
+
const watch = record(record(recovery.watch).sessions);
|
|
77
|
+
const beatAge = typeof recovery.beat_age_s === "number" ? recovery.beat_age_s : null;
|
|
78
|
+
const bad = text(recovery.bad);
|
|
79
|
+
const watchBad = Object.entries(watch)
|
|
80
|
+
.map(([id, entry]) => ({ id, title: text(record(entry).title) ?? id.slice(0, 8), status: text(record(entry).status) ?? "ok" }))
|
|
81
|
+
.filter(entry => entry.status !== "ok");
|
|
82
|
+
return {
|
|
83
|
+
installed: true,
|
|
84
|
+
heartbeat: bad ? "bad" : beatAge === null ? "unknown" : beatAge > exports.HEARTBEAT_STALE_S ? "stale" : "ok",
|
|
85
|
+
beatAgeS: beatAge,
|
|
86
|
+
bad,
|
|
87
|
+
restartedAt: text(record(status.result).restarted_at),
|
|
88
|
+
resumedAt: text(record(status.resumer).at),
|
|
89
|
+
watched: Object.keys(watch).length,
|
|
90
|
+
watchBad,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/** The drains' status lines as counts and the ones that are not polling. A line this does not know is left out. */
|
|
94
|
+
function parseDrains(lines, now) {
|
|
95
|
+
const facts = { polling: 0, waiting: 0, relays: 0, stale: [], quota: [] };
|
|
96
|
+
for (const line of lines) {
|
|
97
|
+
const drain = /^issue drain (\S+) -> \S+: last ok poll (\S+) .*?, (\d+) open, (\d+) waiting/.exec(line);
|
|
98
|
+
if (drain) {
|
|
99
|
+
const at = Date.parse(drain[2]);
|
|
100
|
+
const age = Number.isNaN(at) ? Infinity : now - at;
|
|
101
|
+
if (age > exports.DRAIN_STALE_MS)
|
|
102
|
+
facts.stale.push(`${drain[1]}: ${Number.isFinite(age) ? `${Math.round(age / 60_000)} min` : "never polled"}`);
|
|
103
|
+
else
|
|
104
|
+
facts.polling += 1;
|
|
105
|
+
facts.waiting += Number(drain[4]);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (line.startsWith("relay ")) {
|
|
109
|
+
facts.relays += 1;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const quota = /^quota (\S+): (\d+)\/(\d+) calls left/.exec(line);
|
|
113
|
+
if (quota)
|
|
114
|
+
facts.quota.push(`${quota[1]} ${quota[2]}/${quota[3]}`);
|
|
115
|
+
}
|
|
116
|
+
return facts;
|
|
117
|
+
}
|
|
118
|
+
/** The drains' status from the configured command, which prints `{ "status": ["…"] }`. */
|
|
119
|
+
async function readDrains(command, run, now) {
|
|
120
|
+
if (!command)
|
|
121
|
+
return null;
|
|
122
|
+
const result = await run(command, 60_000);
|
|
123
|
+
if (!result.ok)
|
|
124
|
+
return { polling: 0, waiting: 0, relays: 0, stale: [], quota: [], error: result.error ?? "the drains command failed" };
|
|
125
|
+
try {
|
|
126
|
+
const status = record(JSON.parse(result.stdout)).status;
|
|
127
|
+
return parseDrains(Array.isArray(status) ? status.filter((line) => typeof line === "string") : [], now);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return { polling: 0, waiting: 0, relays: 0, stale: [], quota: [], error: "the drains command did not print JSON" };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** The headers and body of `gh api -i` output. A 304 has no body. */
|
|
134
|
+
function parseHttp(stdout) {
|
|
135
|
+
const split = stdout.search(/\r?\n\r?\n/);
|
|
136
|
+
const head = split < 0 ? stdout : stdout.slice(0, split);
|
|
137
|
+
const body = split < 0 ? "" : stdout.slice(split).trim();
|
|
138
|
+
const lines = head.split(/\r?\n/);
|
|
139
|
+
const status = Number(/^HTTP\/\S+ (\d{3})/.exec(lines[0])?.[1] ?? 0);
|
|
140
|
+
const etag = lines.map(line => /^etag:\s*(.+)$/i.exec(line)?.[1]?.trim()).find(Boolean) ?? null;
|
|
141
|
+
return { status, etag, body };
|
|
142
|
+
}
|
|
143
|
+
/** A search answered this recently is reused: GitHub's search has its own small quota, and asking more often tells nothing new. */
|
|
144
|
+
exports.MERGED_TTL_MS = 4 * 60_000;
|
|
145
|
+
/** Midnight today in this machine's time zone, as an instant GitHub's search takes. */
|
|
146
|
+
function startOfToday(now) {
|
|
147
|
+
const day = new Date(now);
|
|
148
|
+
day.setHours(0, 0, 0, 0);
|
|
149
|
+
return day.toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Pull requests the account merged today. An answer under four minutes old is reused, and the search is conditional when
|
|
153
|
+
* GitHub gave an ETag (a 304 costs nothing). Search draws on its own quota, never the one the drains use.
|
|
154
|
+
*/
|
|
155
|
+
async function readMergedToday(account, run, cacheFile, now) {
|
|
156
|
+
const since = startOfToday(now);
|
|
157
|
+
const caches = (0, store_1.readJson)(cacheFile, {});
|
|
158
|
+
const cached = caches[account.label]?.since === since ? caches[account.label] : undefined;
|
|
159
|
+
if (cached && now - cached.at < exports.MERGED_TTL_MS)
|
|
160
|
+
return { label: account.label, count: cached.count, prs: cached.prs };
|
|
161
|
+
const query = `search/issues?q=${encodeURIComponent(`is:pr is:merged author:@me merged:>=${since}`)}&per_page=100`;
|
|
162
|
+
const result = await run([...account.command, "api", "-i", ...(cached?.etag ? ["-H", `If-None-Match: ${cached.etag}`] : []), query], 60_000);
|
|
163
|
+
const http = parseHttp(result.stdout);
|
|
164
|
+
if (http.status === 304 && cached) {
|
|
165
|
+
caches[account.label] = { ...cached, at: now };
|
|
166
|
+
(0, store_1.writeJson)(cacheFile, caches);
|
|
167
|
+
return { label: account.label, count: cached.count, prs: cached.prs };
|
|
168
|
+
}
|
|
169
|
+
if (http.status !== 200)
|
|
170
|
+
return { label: account.label, count: cached?.count ?? 0, prs: cached?.prs ?? [], error: result.error ?? `GitHub answered ${http.status || "nothing"}` };
|
|
171
|
+
try {
|
|
172
|
+
const body = record(JSON.parse(http.body));
|
|
173
|
+
const items = (Array.isArray(body.items) ? body.items : []).map(record);
|
|
174
|
+
const prs = items.map(item => ({
|
|
175
|
+
repo: (text(item.repository_url) ?? "").replace(/^.*\/repos\//, ""),
|
|
176
|
+
number: typeof item.number === "number" ? item.number : 0,
|
|
177
|
+
title: text(item.title) ?? "",
|
|
178
|
+
})).slice(0, MAX_MERGED_LISTED);
|
|
179
|
+
const count = typeof body.total_count === "number" ? body.total_count : items.length;
|
|
180
|
+
caches[account.label] = { since, at: now, etag: http.etag, count, prs };
|
|
181
|
+
(0, store_1.writeJson)(cacheFile, caches);
|
|
182
|
+
return { label: account.label, count, prs };
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return { label: account.label, count: 0, prs: [], error: "GitHub's answer was not JSON" };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** One source's failure, kept short, as a nerves event and a line the digest shows. */
|
|
189
|
+
function sourceFailed(source, error) {
|
|
190
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_digest_source_error", message: "a status digest source could not be read", meta: { source, error } });
|
|
191
|
+
return `${source}: ${error}`.slice(0, 200);
|
|
192
|
+
}
|
|
193
|
+
function mergedCacheFile(stateDir) {
|
|
194
|
+
return path.join(stateDir, "digest-merged.json");
|
|
195
|
+
}
|
|
196
|
+
/** Whether a folder exists: a desk root that is not there is skipped, not an error. */
|
|
197
|
+
function isFolder(folder) {
|
|
198
|
+
try {
|
|
199
|
+
return fs.statSync(folder).isDirectory();
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
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.EMPTY_DIGEST_STATE = exports.SCAN_BUDGET_BYTES = exports.CARD_WINDOW_MS = exports.DIGEST_STALE_MS = exports.DIGEST_DEFAULT_SECONDS = void 0;
|
|
37
|
+
exports.digestFiles = digestFiles;
|
|
38
|
+
exports.readDigestState = readDigestState;
|
|
39
|
+
exports.expandHome = expandHome;
|
|
40
|
+
exports.minutes = minutes;
|
|
41
|
+
exports.buildDigest = buildDigest;
|
|
42
|
+
exports.renderDigest = renderDigest;
|
|
43
|
+
exports.writeDigest = writeDigest;
|
|
44
|
+
exports.writeDigestState = writeDigestState;
|
|
45
|
+
exports.readDigestText = readDigestText;
|
|
46
|
+
exports.isStatusAsk = isStatusAsk;
|
|
47
|
+
exports.statusAnswer = statusAnswer;
|
|
48
|
+
const path = __importStar(require("node:path"));
|
|
49
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
50
|
+
const digest_cards_1 = require("./digest-cards");
|
|
51
|
+
const digest_sources_1 = require("./digest-sources");
|
|
52
|
+
const store_1 = require("./store");
|
|
53
|
+
/**
|
|
54
|
+
* The status digest: one deterministic picture of how everything is going, built with no model turn from the app's
|
|
55
|
+
* sessions, their task cards, the machine's health, the drains and what merged today. It is written beside the sense's
|
|
56
|
+
* snapshot; the Teams `/status` command and the `app_sessions_digest` tool read it, and `digest-push.ts` decides what is
|
|
57
|
+
* worth telling the owner unasked.
|
|
58
|
+
*/
|
|
59
|
+
exports.DIGEST_DEFAULT_SECONDS = 300;
|
|
60
|
+
/** A digest older than this is shown as stale: the sense that writes it may be down. */
|
|
61
|
+
exports.DIGEST_STALE_MS = 15 * 60_000;
|
|
62
|
+
/** Only sessions active in this window have their card looked up. */
|
|
63
|
+
exports.CARD_WINDOW_MS = 24 * 3_600_000;
|
|
64
|
+
/** The most history one digest reads to find declared tasks, so the first one after a start stays light. */
|
|
65
|
+
exports.SCAN_BUDGET_BYTES = 1024 * 1024 * 1024;
|
|
66
|
+
const INCREMENTAL_SCAN_BYTES = 4 * 1024 * 1024;
|
|
67
|
+
const WORKING_LISTED = 8;
|
|
68
|
+
const NAME_MAX = 60;
|
|
69
|
+
exports.EMPTY_DIGEST_STATE = { focus: {}, cards: {}, firstSeen: {}, pushed: {}, lastPushAt: 0, seeded: false };
|
|
70
|
+
function digestFiles(agentRoot) {
|
|
71
|
+
const dir = (0, store_1.appSessionsStateDir)(agentRoot);
|
|
72
|
+
return { json: path.join(dir, "digest.json"), state: path.join(dir, "digest-state.json") };
|
|
73
|
+
}
|
|
74
|
+
function readDigestState(agentRoot) {
|
|
75
|
+
return { ...exports.EMPTY_DIGEST_STATE, ...(0, store_1.readJson)(digestFiles(agentRoot).state, {}) };
|
|
76
|
+
}
|
|
77
|
+
function expandHome(folder, home) {
|
|
78
|
+
return folder === "~" ? home : folder.startsWith("~/") ? path.join(home, folder.slice(2)) : folder;
|
|
79
|
+
}
|
|
80
|
+
function cut(value, max) {
|
|
81
|
+
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
|
|
82
|
+
}
|
|
83
|
+
function minutes(ms) {
|
|
84
|
+
const min = Math.max(0, Math.round(ms / 60_000));
|
|
85
|
+
return min < 90 ? `${min} min` : min < 60 * 36 ? `${Math.round(min / 60)} h` : `${Math.round(min / 1440)} d`;
|
|
86
|
+
}
|
|
87
|
+
/** Looks up every recently active session's declared task and card; reads at most the scan budget of history. */
|
|
88
|
+
function attachCards(input) {
|
|
89
|
+
const roots = (input.config.deskRoots ?? []).map(folder => expandHome(folder, input.home)).filter(digest_sources_1.isFolder);
|
|
90
|
+
const cards = new Map();
|
|
91
|
+
if (!roots.length)
|
|
92
|
+
return cards;
|
|
93
|
+
let budget = input.scanBudgetBytes ?? exports.SCAN_BUDGET_BYTES;
|
|
94
|
+
const known = new Set(input.rows.map(row => row.id));
|
|
95
|
+
for (const id of Object.keys(input.state.focus))
|
|
96
|
+
if (!known.has(id))
|
|
97
|
+
delete input.state.focus[id];
|
|
98
|
+
const busyFirst = [...input.rows].sort((a, b) => Number(a.state === "idle") - Number(b.state === "idle"));
|
|
99
|
+
for (const row of busyFirst) {
|
|
100
|
+
const active = row.state !== "idle" || (row.lastActivity !== null && input.now - Date.parse(row.lastActivity) < exports.CARD_WINDOW_MS);
|
|
101
|
+
if (!active || row.remote)
|
|
102
|
+
continue;
|
|
103
|
+
if (budget > 0) {
|
|
104
|
+
const scanned = (0, digest_cards_1.scanFocus)(row.id, input.state.focus[row.id], Math.min(budget, input.state.focus[row.id] ? INCREMENTAL_SCAN_BYTES : digest_cards_1.FIRST_SCAN_BYTES), input.client);
|
|
105
|
+
input.state.focus[row.id] = scanned.entry;
|
|
106
|
+
budget -= scanned.bytes;
|
|
107
|
+
}
|
|
108
|
+
const focus = input.state.focus[row.id];
|
|
109
|
+
const card = focus?.track && focus.slug ? (0, digest_cards_1.readCard)(roots, focus.track, focus.slug) : null;
|
|
110
|
+
if (card)
|
|
111
|
+
cards.set(row.id, card);
|
|
112
|
+
}
|
|
113
|
+
return cards;
|
|
114
|
+
}
|
|
115
|
+
/** What only the owner can do next: an open prompt, an answer to give, or finished work to look at. */
|
|
116
|
+
function needsOwner(sessions, prompts, now) {
|
|
117
|
+
const items = prompts.map(prompt => ({ kind: "prompt", key: `prompt:${prompt.session}:${prompt.requestId}`, session: prompt.session, name: prompt.name, text: prompt.what, since: prompt.since }));
|
|
118
|
+
const prompted = new Set(prompts.map(prompt => prompt.session));
|
|
119
|
+
for (const session of sessions) {
|
|
120
|
+
if (session.state === "waiting" && !prompted.has(session.id)) {
|
|
121
|
+
const since = session.lastActivity ? Date.parse(session.lastActivity) : NaN;
|
|
122
|
+
items.push({ kind: "waiting", key: `waiting:${session.id}`, session: session.id, name: session.name, text: session.detail, since: Number.isNaN(since) ? now : since });
|
|
123
|
+
}
|
|
124
|
+
if (session.card?.status === "collaborating") {
|
|
125
|
+
items.push({ kind: "ready", key: `ready:${session.card.track}/${session.card.slug}`, session: session.id, name: session.name, text: `ready for you: ${session.card.title}${session.card.next ? `. Next: ${session.card.next}` : ""}`, since: null });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return items;
|
|
129
|
+
}
|
|
130
|
+
/** Builds the digest from the app's rows and every source the config names. A source that fails is named in `unread`. */
|
|
131
|
+
async function buildDigest(input) {
|
|
132
|
+
const cards = attachCards(input);
|
|
133
|
+
const unread = [];
|
|
134
|
+
const sessions = input.rows
|
|
135
|
+
.filter(row => row.state !== "idle" || cards.has(row.id))
|
|
136
|
+
.map(row => ({
|
|
137
|
+
id: row.id,
|
|
138
|
+
name: cut(row.name, NAME_MAX),
|
|
139
|
+
state: row.state,
|
|
140
|
+
detail: row.detail,
|
|
141
|
+
lastActivity: row.lastActivity,
|
|
142
|
+
...(cards.has(row.id) ? { card: cards.get(row.id) } : {}),
|
|
143
|
+
}));
|
|
144
|
+
const counts = { working: 0, idle: 0, waiting: 0, stuck: 0 };
|
|
145
|
+
for (const row of input.rows)
|
|
146
|
+
counts[row.state] += 1;
|
|
147
|
+
const machine = await (0, digest_sources_1.readMachine)(input.client).catch(/* v8 ignore next -- readMachine never throws @preserve */ (error) => ({ error: error.message }));
|
|
148
|
+
if (machine.error)
|
|
149
|
+
unread.push((0, digest_sources_1.sourceFailed)("machine health", machine.error));
|
|
150
|
+
const drains = await (0, digest_sources_1.readDrains)(input.config.drains, input.run, input.now);
|
|
151
|
+
if (drains?.error)
|
|
152
|
+
unread.push((0, digest_sources_1.sourceFailed)("drains", drains.error));
|
|
153
|
+
const merged = [];
|
|
154
|
+
for (const account of input.config.mergedToday ?? []) {
|
|
155
|
+
const facts = await (0, digest_sources_1.readMergedToday)(account, input.run, (0, digest_sources_1.mergedCacheFile)((0, store_1.appSessionsStateDir)(input.agentRoot)), input.now);
|
|
156
|
+
if (facts.error)
|
|
157
|
+
unread.push((0, digest_sources_1.sourceFailed)(`merged today (${account.label})`, facts.error));
|
|
158
|
+
merged.push(facts);
|
|
159
|
+
}
|
|
160
|
+
const digest = {
|
|
161
|
+
at: new Date(input.now).toISOString(),
|
|
162
|
+
appRunning: input.appRunning,
|
|
163
|
+
counts,
|
|
164
|
+
sessions,
|
|
165
|
+
needsOwner: needsOwner(sessions, input.waitingPrompts, input.now),
|
|
166
|
+
machine: machine.installed || machine.error ? machine : null,
|
|
167
|
+
drains,
|
|
168
|
+
merged,
|
|
169
|
+
unread,
|
|
170
|
+
tokens: 0,
|
|
171
|
+
};
|
|
172
|
+
digest.tokens = Math.ceil(renderDigest(digest, input.now).length / 4);
|
|
173
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_digest_built", message: "built the status digest", meta: { sessions: sessions.length, needsOwner: digest.needsOwner.length, unread: unread.length, tokens: digest.tokens } });
|
|
174
|
+
return digest;
|
|
175
|
+
}
|
|
176
|
+
function clock(ms) {
|
|
177
|
+
return new Date(ms).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", timeZoneName: "short" });
|
|
178
|
+
}
|
|
179
|
+
function sessionLine(session, now) {
|
|
180
|
+
const last = session.lastActivity ? Date.parse(session.lastActivity) : NaN;
|
|
181
|
+
const bits = [session.card?.next ?? (session.card ? session.card.title : null), Number.isNaN(last) ? null : `last turn ${minutes(now - last)} ago`].filter(Boolean);
|
|
182
|
+
return `- ${session.name}${bits.length ? ` — ${bits.join("; ")}` : ""}`;
|
|
183
|
+
}
|
|
184
|
+
/** The digest as the short Teams message: a blank line between paragraphs, bullets where there are several. `plain` leaves out the bold marks, for a send that is plain text. */
|
|
185
|
+
function renderDigest(digest, now, plain = false) {
|
|
186
|
+
const at = Date.parse(digest.at);
|
|
187
|
+
const blocks = [`**Ouroboros status** · ${clock(at)}`];
|
|
188
|
+
if (digest.needsOwner.length) {
|
|
189
|
+
blocks.push(["**Needs you**", ...digest.needsOwner.map(item => `- ${item.name} — ${item.text}${item.since ? ` (${minutes(now - item.since)})` : ""}`)].join("\n"));
|
|
190
|
+
}
|
|
191
|
+
const broken = [];
|
|
192
|
+
for (const session of digest.sessions)
|
|
193
|
+
if (session.state === "stuck")
|
|
194
|
+
broken.push(`- ${session.name} — stuck (${session.detail})`);
|
|
195
|
+
if (digest.machine?.heartbeat === "bad" || digest.machine?.heartbeat === "stale")
|
|
196
|
+
broken.push(`- Mac watcher — heartbeat ${digest.machine.heartbeat}${digest.machine.bad ? `: ${digest.machine.bad}` : ""}`);
|
|
197
|
+
for (const session of digest.machine?.watchBad ?? [])
|
|
198
|
+
broken.push(`- ${cut(session.title, NAME_MAX)} — health watch: ${session.status}`);
|
|
199
|
+
for (const stale of digest.drains?.stale ?? [])
|
|
200
|
+
broken.push(`- drain ${stale} since its last good poll`);
|
|
201
|
+
if (broken.length)
|
|
202
|
+
blocks.push(["**Broken**", ...broken].join("\n"));
|
|
203
|
+
const { counts } = digest;
|
|
204
|
+
const working = digest.sessions.filter(session => session.state === "working");
|
|
205
|
+
const list = working.slice(0, WORKING_LISTED).map(session => sessionLine(session, now));
|
|
206
|
+
if (working.length > WORKING_LISTED)
|
|
207
|
+
list.push(`- and ${working.length - WORKING_LISTED} more`);
|
|
208
|
+
blocks.push([`**Sessions** ${counts.working} working · ${counts.waiting} waiting · ${counts.stuck} stuck · ${counts.idle} idle${digest.appRunning ? "" : " · the app is not running"}`, ...list].join("\n"));
|
|
209
|
+
if (digest.machine) {
|
|
210
|
+
const machine = digest.machine;
|
|
211
|
+
const parts = [
|
|
212
|
+
machine.installed ? `heartbeat ${machine.heartbeat}${machine.beatAgeS === null ? "" : ` (${machine.beatAgeS} s)`}` : "status unreadable",
|
|
213
|
+
machine.restartedAt ? `app restarted ${minutes(now - Date.parse(machine.restartedAt))} ago` : null,
|
|
214
|
+
machine.resumedAt ? `last resume ${minutes(now - Date.parse(machine.resumedAt))} ago` : null,
|
|
215
|
+
machine.installed ? `health watch: ${machine.watched} sessions, ${machine.watchBad.length} not ok` : null,
|
|
216
|
+
].filter(Boolean);
|
|
217
|
+
blocks.push(`**Machine** ${parts.join(" · ")}`);
|
|
218
|
+
}
|
|
219
|
+
if (digest.drains) {
|
|
220
|
+
const drains = digest.drains;
|
|
221
|
+
blocks.push(`**Drains** ${drains.polling} polling, ${drains.stale.length} stale · ${drains.relays} relays · ${drains.waiting} issues waiting${drains.quota.length ? ` · quota ${drains.quota.join(", ")}` : ""}`);
|
|
222
|
+
}
|
|
223
|
+
if (digest.merged.length) {
|
|
224
|
+
const total = digest.merged.reduce((sum, account) => sum + account.count, 0);
|
|
225
|
+
const prs = digest.merged.flatMap(account => account.prs).slice(0, 4).map(pr => `- ${pr.repo}#${pr.number} ${cut(pr.title, 70)}`);
|
|
226
|
+
blocks.push([`**Merged today** ${total}${digest.merged.length > 1 ? ` (${digest.merged.map(account => `${account.label} ${account.count}`).join(", ")})` : ""}`, ...prs].join("\n"));
|
|
227
|
+
}
|
|
228
|
+
if (digest.unread.length)
|
|
229
|
+
blocks.push(`Not read: ${digest.unread.join("; ")}`);
|
|
230
|
+
const text = blocks.join("\n\n");
|
|
231
|
+
return plain ? text.replace(/\*\*/g, "") : text;
|
|
232
|
+
}
|
|
233
|
+
/** Builds the digest and writes it and the state beside the sense's snapshot; the sense calls this on its cadence. */
|
|
234
|
+
async function writeDigest(input) {
|
|
235
|
+
const digest = await buildDigest(input);
|
|
236
|
+
const files = digestFiles(input.agentRoot);
|
|
237
|
+
(0, store_1.writeJson)(files.json, digest);
|
|
238
|
+
writeDigestState(input.agentRoot, input.state);
|
|
239
|
+
return digest;
|
|
240
|
+
}
|
|
241
|
+
function writeDigestState(agentRoot, state) {
|
|
242
|
+
(0, store_1.writeJson)(digestFiles(agentRoot).state, state);
|
|
243
|
+
}
|
|
244
|
+
/** The last digest as the Teams message, with its age when it is old; null when no digest was ever written. */
|
|
245
|
+
function readDigestText(agentRoot, now) {
|
|
246
|
+
const digest = (0, store_1.readJson)(digestFiles(agentRoot).json, null);
|
|
247
|
+
if (!digest)
|
|
248
|
+
return null;
|
|
249
|
+
const age = now - Date.parse(digest.at);
|
|
250
|
+
const stale = age > exports.DIGEST_STALE_MS ? `The digest is ${minutes(age)} old; the sense that writes it may be down.\n\n` : "";
|
|
251
|
+
return `${stale}${renderDigest(digest, now)}`;
|
|
252
|
+
}
|
|
253
|
+
/** The ask that means "how is everything going": the whole message, nothing else. */
|
|
254
|
+
const STATUS_ASK = /^(?:hey |hi |ouro(?:boros)?,? )?(?:how(?:'?s| is| are) (?:it|things|everything|we|the work) (?:going|doing)|how(?:'?s| are) (?:things|everything)|what'?s (?:the )?status|what'?s (?:up|going on)|status(?: report| update)?|sitrep|any news|update me)[?!. ]*$/i;
|
|
255
|
+
function isStatusAsk(message) {
|
|
256
|
+
return STATUS_ASK.test(message.trim().replace(/[’]/g, "'"));
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* The answer to "how's it going?" with no model turn: `/status`, or the plain question with nothing else in the message.
|
|
260
|
+
* Null means the message is something else and goes to the agent as usual.
|
|
261
|
+
*/
|
|
262
|
+
function statusAnswer(message, agentRoot, now) {
|
|
263
|
+
const slash = /^\/status\s*$/i.test(message.trim());
|
|
264
|
+
if (!slash && !isStatusAsk(message))
|
|
265
|
+
return null;
|
|
266
|
+
const text = readDigestText(agentRoot, now);
|
|
267
|
+
if (!text && !slash)
|
|
268
|
+
return null;
|
|
269
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_status_answered", message: "answered a status ask from the digest with no model turn", meta: { via: slash ? "command" : "question", tokens: Math.ceil((text?.length ?? 0) / 4) } });
|
|
270
|
+
return text ?? "No status digest yet. Add a digest block to the app-sessions sense in agent.json and it is built within minutes.";
|
|
271
|
+
}
|
|
@@ -1,12 +1,46 @@
|
|
|
1
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
|
+
})();
|
|
2
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WAKE_RUNNER_IDLE_MS = exports.APP_SESSIONS_WAKE_TRIGGER = exports.WATCH_POLL_MS = exports.SNAPSHOT_MS = void 0;
|
|
36
|
+
exports.DIGEST_IDLE_MS = exports.WAKE_RUNNER_IDLE_MS = exports.APP_SESSIONS_WAKE_TRIGGER = exports.WATCH_POLL_MS = exports.SNAPSHOT_MS = void 0;
|
|
4
37
|
exports.newReplies = newReplies;
|
|
5
38
|
exports.replyContent = replyContent;
|
|
6
39
|
exports.privateRuntimeDeliver = privateRuntimeDeliver;
|
|
7
40
|
exports.checkWatches = checkWatches;
|
|
8
41
|
exports.recordSnapshot = recordSnapshot;
|
|
9
42
|
exports.checkWakeRunners = checkWakeRunners;
|
|
43
|
+
exports.checkDigest = checkDigest;
|
|
10
44
|
exports.startAppSessionsSense = startAppSessionsSense;
|
|
11
45
|
const node_crypto_1 = require("node:crypto");
|
|
12
46
|
const socket_client_1 = require("../../heart/daemon/socket-client");
|
|
@@ -14,8 +48,12 @@ const identity_1 = require("../../heart/identity");
|
|
|
14
48
|
const pending_1 = require("../../mind/pending");
|
|
15
49
|
const runtime_1 = require("../../nerves/runtime");
|
|
16
50
|
const cmux_1 = require("../shepherd/cmux");
|
|
51
|
+
const os = __importStar(require("node:os"));
|
|
52
|
+
const digest_1 = require("./digest");
|
|
53
|
+
const digest_push_1 = require("./digest-push");
|
|
17
54
|
const client_1 = require("./client");
|
|
18
55
|
const store_1 = require("./store");
|
|
56
|
+
const size_watch_1 = require("./size-watch");
|
|
19
57
|
const waiting_prompts_1 = require("./waiting-prompts");
|
|
20
58
|
const wake_runner_1 = require("./wake-runner");
|
|
21
59
|
/**
|
|
@@ -163,6 +201,32 @@ async function checkWakeRunners(agentName, agentRoot, deps, due = new Map()) {
|
|
|
163
201
|
return exports.WAKE_RUNNER_IDLE_MS;
|
|
164
202
|
}
|
|
165
203
|
}
|
|
204
|
+
/** How long to wait before looking again when no digest is configured, so one added to `agent.json` starts within two minutes. */
|
|
205
|
+
exports.DIGEST_IDLE_MS = 2 * 60_000;
|
|
206
|
+
/**
|
|
207
|
+
* Build the status digest if `agent.json` asks for one, and tell the owner what it judges worth telling. Returns the
|
|
208
|
+
* milliseconds until the next one is due. A failure is logged and tried again next time.
|
|
209
|
+
*/
|
|
210
|
+
async function checkDigest(agentName, agentRoot, deps) {
|
|
211
|
+
try {
|
|
212
|
+
const config = (0, identity_1.loadAgentConfig)({ agentName, agentRoot }).senses?.["app-sessions"];
|
|
213
|
+
if (!config?.enabled || !config.digest)
|
|
214
|
+
return exports.DIGEST_IDLE_MS;
|
|
215
|
+
const rows = (0, client_1.listAppSessions)({ ...deps.client, now: () => deps.now });
|
|
216
|
+
const state = (0, digest_1.readDigestState)(agentRoot);
|
|
217
|
+
const digest = await (0, digest_1.writeDigest)({
|
|
218
|
+
agentRoot, config: config.digest, client: deps.client, run: deps.run, now: deps.now, home: deps.home, rows,
|
|
219
|
+
appRunning: (0, client_1.appRunning)(deps.client), waitingPrompts: (0, waiting_prompts_1.waitingPromptsOf)(agentRoot, rows, deps.now), state,
|
|
220
|
+
});
|
|
221
|
+
await (0, digest_push_1.pushDue)(digest, state, deps.now, deps.notify);
|
|
222
|
+
(0, digest_1.writeDigestState)(agentRoot, state);
|
|
223
|
+
return (config.digest.everySeconds ?? digest_1.DIGEST_DEFAULT_SECONDS) * 1000;
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_digest_error", message: "could not build the status digest", meta: { error: error.message } });
|
|
227
|
+
return exports.DIGEST_IDLE_MS;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
166
230
|
function startAppSessionsSense(options) {
|
|
167
231
|
const agentRoot = options.agentRoot ?? (0, identity_1.getAgentRoot)(options.agentName);
|
|
168
232
|
const now = options.now ?? Date.now;
|
|
@@ -177,7 +241,10 @@ function startAppSessionsSense(options) {
|
|
|
177
241
|
let runnerPoll = Promise.resolve();
|
|
178
242
|
const due = new Map();
|
|
179
243
|
let waitingPoll = Promise.resolve();
|
|
244
|
+
let sizePoll = Promise.resolve();
|
|
180
245
|
const notifyOwner = options.notifyOwner ?? (0, waiting_prompts_1.ownerNotifier)(options.agentName, agentRoot);
|
|
246
|
+
let cancelDigest = null;
|
|
247
|
+
let digestPoll = Promise.resolve();
|
|
181
248
|
const snapshotTick = () => {
|
|
182
249
|
if (stopped)
|
|
183
250
|
return;
|
|
@@ -185,6 +252,9 @@ function startAppSessionsSense(options) {
|
|
|
185
252
|
waitingPoll = waitingPoll.then(() => (0, waiting_prompts_1.noticeWaitingPrompts)(agentRoot, taken, { notify: notifyOwner, now: now() })).catch((error) => {
|
|
186
253
|
(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 } });
|
|
187
254
|
});
|
|
255
|
+
sizePoll = sizePoll.then(() => (0, size_watch_1.noticeOversizedSessions)(agentRoot, (0, client_1.listAppSessions)({ ...client, now: () => now() }), { notify: notifyOwner, now: now(), client })).then(() => undefined).catch((error) => {
|
|
256
|
+
(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 } });
|
|
257
|
+
});
|
|
188
258
|
cancelSnapshot = schedule(snapshotTick, exports.SNAPSHOT_MS);
|
|
189
259
|
};
|
|
190
260
|
const watchTick = () => {
|
|
@@ -205,18 +275,28 @@ function startAppSessionsSense(options) {
|
|
|
205
275
|
cancelRunners = schedule(runnerTick, ms);
|
|
206
276
|
});
|
|
207
277
|
};
|
|
278
|
+
const digestTick = () => {
|
|
279
|
+
if (stopped)
|
|
280
|
+
return;
|
|
281
|
+
digestPoll = checkDigest(options.agentName, agentRoot, { client, run: options.runCommand ?? wake_runner_1.runCommand, notify: notifyOwner, now: now(), home: os.homedir() }).then(ms => {
|
|
282
|
+
if (!stopped)
|
|
283
|
+
cancelDigest = schedule(digestTick, ms);
|
|
284
|
+
});
|
|
285
|
+
};
|
|
208
286
|
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_start", message: "app-sessions sense started", meta: { agent: options.agentName } });
|
|
209
287
|
snapshotTick();
|
|
210
288
|
watchTick();
|
|
211
289
|
runnerTick();
|
|
290
|
+
digestTick();
|
|
212
291
|
return {
|
|
213
292
|
stop: () => {
|
|
214
293
|
stopped = true;
|
|
215
294
|
cancelSnapshot();
|
|
216
295
|
cancelWatch?.();
|
|
217
296
|
cancelRunners?.();
|
|
297
|
+
cancelDigest?.();
|
|
218
298
|
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_end", message: "app-sessions sense stopped", meta: { agent: options.agentName } });
|
|
219
299
|
},
|
|
220
|
-
done: () => Promise.all([inFlight, runnerPoll, waitingPoll]).then(() => undefined),
|
|
300
|
+
done: () => Promise.all([inFlight, runnerPoll, waitingPoll, sizePoll, digestPoll]).then(() => undefined),
|
|
221
301
|
};
|
|
222
302
|
}
|
|
@@ -0,0 +1,108 @@
|
|
|
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.neverResume = exports.readOversize = exports.OVERSIZE_BYTES = void 0;
|
|
37
|
+
exports.handoffNudge = handoffNudge;
|
|
38
|
+
exports.noticeOversizedSessions = noticeOversizedSessions;
|
|
39
|
+
const path = __importStar(require("node:path"));
|
|
40
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
41
|
+
const owner_notice_1 = require("../shepherd/owner-notice");
|
|
42
|
+
const client_1 = require("./client");
|
|
43
|
+
const store_1 = require("./store");
|
|
44
|
+
/**
|
|
45
|
+
* 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
|
|
46
|
+
* inline images) has frozen the machine. The snapshot already lists every session each minute, so this is deterministic
|
|
47
|
+
* and costs no model turn: a session whose `events.jsonl` passes the limit is flagged never-resume, and its coordinator
|
|
48
|
+
* (or the session itself when it has none) is asked once to hand it off to a fresh successor. A session that is not running
|
|
49
|
+
* and has no smaller coordinator is not messaged, because the message would reload it; the owner is told instead.
|
|
50
|
+
*/
|
|
51
|
+
exports.OVERSIZE_BYTES = 500 * 1024 * 1024;
|
|
52
|
+
const stateFile = (agentRoot) => path.join((0, store_1.appSessionsStateDir)(agentRoot), "oversize.json");
|
|
53
|
+
const readOversize = (agentRoot) => (0, store_1.readJson)(stateFile(agentRoot), { sessions: {} }).sessions;
|
|
54
|
+
exports.readOversize = readOversize;
|
|
55
|
+
/** The ids of sessions flagged never-resume: a resume path asks this before it wakes one. */
|
|
56
|
+
const neverResume = (agentRoot) => Object.keys((0, exports.readOversize)(agentRoot));
|
|
57
|
+
exports.neverResume = neverResume;
|
|
58
|
+
const mb = (bytes) => bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
|
|
59
|
+
function handoffNudge(name, bytes) {
|
|
60
|
+
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. Please hand it off before it grows: 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. Keep images out of chat (save screenshots and art as files and link the path): inline images are nearly all of the size.`;
|
|
61
|
+
}
|
|
62
|
+
/** Flag every over-limit session and nudge each once. Returns the number nudged (or owner-told) this run. */
|
|
63
|
+
async function noticeOversizedSessions(agentRoot, rows, deps) {
|
|
64
|
+
const size = deps.size ?? ((id) => (0, client_1.eventLogSize)(id, deps.client));
|
|
65
|
+
const send = deps.send ?? ((id, text) => (0, client_1.sendToAppSession)(id, text, { ...deps.client, delivery: "enqueue" }));
|
|
66
|
+
const before = (0, exports.readOversize)(agentRoot);
|
|
67
|
+
const sizes = new Map(rows.filter(row => !row.remote).map(row => [row.id, size(row.id)]));
|
|
68
|
+
const big = rows.filter(row => (sizes.get(row.id) ?? 0) > exports.OVERSIZE_BYTES);
|
|
69
|
+
const bigIds = new Set(big.map(row => row.id));
|
|
70
|
+
const next = {};
|
|
71
|
+
let nudged = 0;
|
|
72
|
+
const ownerLines = [];
|
|
73
|
+
for (const row of big) {
|
|
74
|
+
const bytes = sizes.get(row.id);
|
|
75
|
+
const entry = { ...before[row.id], bytes, name: row.name };
|
|
76
|
+
next[row.id] = entry;
|
|
77
|
+
if (entry.nudgedAt)
|
|
78
|
+
continue;
|
|
79
|
+
const parent = rows.find(other => other.id === row.coordinatingCreatorSessionId);
|
|
80
|
+
const recipient = parent && !bigIds.has(parent.id) ? parent.id : row.isRunning ? row.id : null;
|
|
81
|
+
if (recipient) {
|
|
82
|
+
const sent = await send(recipient, handoffNudge(row.name, bytes)).catch((error) => ({ ok: false, reply: "", messageId: null, error: error.message }));
|
|
83
|
+
if (!sent.ok)
|
|
84
|
+
continue;
|
|
85
|
+
entry.nudgedAt = new Date(deps.now).toISOString();
|
|
86
|
+
entry.to = recipient;
|
|
87
|
+
nudged += 1;
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
// Not in memory and no smaller coordinator: any message would reload gigabytes, so the owner is told instead.
|
|
91
|
+
ownerLines.push(`- "${(0, owner_notice_1.plain)(row.name, 60)}" (${mb(bytes)})`);
|
|
92
|
+
entry.to = "owner";
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (ownerLines.length) {
|
|
96
|
+
const outcome = await deps.notify(`These sessions have histories over ${mb(exports.OVERSIZE_BYTES)} and cannot be nudged without reloading them. They need a hand-off to a fresh successor session (checkpoint, tail, archive); keep images out of chat:\n${ownerLines.join("\n")}`, big.filter(row => next[row.id].to === "owner").map(row => `oversize:${row.id}`));
|
|
97
|
+
if (outcome !== "pending")
|
|
98
|
+
for (const row of big)
|
|
99
|
+
if (next[row.id].to === "owner") {
|
|
100
|
+
next[row.id].nudgedAt = new Date(deps.now).toISOString();
|
|
101
|
+
nudged += 1;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
(0, store_1.writeJson)(stateFile(agentRoot), { sessions: next });
|
|
105
|
+
if (nudged)
|
|
106
|
+
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_oversize_nudge", message: "asked for a hand-off of Copilot app sessions whose history is over the limit", meta: { sessions: nudged } });
|
|
107
|
+
return nudged;
|
|
108
|
+
}
|
package/dist/senses/teams.js
CHANGED
|
@@ -68,6 +68,7 @@ const phrases_1 = require("../mind/phrases");
|
|
|
68
68
|
const format_1 = require("../mind/format");
|
|
69
69
|
const config_2 = require("../heart/config");
|
|
70
70
|
const context_1 = require("../mind/context");
|
|
71
|
+
const digest_1 = require("./app-sessions/digest");
|
|
71
72
|
const commands_1 = require("./commands");
|
|
72
73
|
const nerves_1 = require("../nerves");
|
|
73
74
|
const runtime_1 = require("../nerves/runtime");
|
|
@@ -935,6 +936,14 @@ async function handleTeamsMessage(text, stream, conversationId, teamsContext, se
|
|
|
935
936
|
// Pre-resolve friend for session path + slash commands (pipeline will re-use the cached result)
|
|
936
937
|
const resolvedContext = await resolver.resolve();
|
|
937
938
|
const friendId = resolvedContext.friend.id;
|
|
939
|
+
// The owner's "how's it going?" is answered from the status digest with no model turn.
|
|
940
|
+
if (resolvedContext.friend.trustLevel === "family") {
|
|
941
|
+
const status = (0, digest_1.statusAnswer)(text, owner.agentRoot, Date.now());
|
|
942
|
+
if (status !== null) {
|
|
943
|
+
await stream.emit(status);
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
938
947
|
// ── Teams adapter concerns: controller, callbacks, session path ──────────
|
|
939
948
|
const controller = new AbortController();
|
|
940
949
|
const channelConfig = (0, config_2.getTeamsChannelConfig)();
|
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.1145",
|
|
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.1145",
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@anthropic-ai/sdk": "^0.78.0",
|
|
12
12
|
"@ouro.bot/friends": "0.1.0-alpha.18",
|