@ouro.bot/cli 0.1.0-alpha.1170 → 0.1.0-alpha.1171

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 CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1171",
6
+ "changes": [
7
+ "The app-sessions sense no longer runs wake delivery or stuck resume: Shepherd owns them now (`shepherd wakes status`, `shepherd stuck plan`). A `wakeRunners` block in agent.json is ignored, and a hand-off is read from the successor's `Succeeds:` line alone."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1170",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1170",
2
+ "runtimeVersion": "0.1.0-alpha.1171",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -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.1170</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1171</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -45,7 +45,6 @@ const provider_credentials_1 = require("../provider-credentials");
45
45
  const sense_truth_1 = require("../sense-truth");
46
46
  const machine_identity_1 = require("../machine-identity");
47
47
  const shepherd_config_1 = require("../shepherd-config");
48
- const wake_runner_state_1 = require("../../senses/app-sessions/wake-runner-state");
49
48
  const store_1 = require("../../senses/app-sessions/store");
50
49
  const waiting_status_1 = require("../../senses/app-sessions/waiting-status");
51
50
  const process_manager_1 = require("./process-manager");
@@ -111,10 +110,10 @@ function readAgentSenses(agentJsonPath) {
111
110
  if (sense === "bluebubbles" && typeof hostUsername === "string" && hostUsername.trim().length > 0) {
112
111
  defaults[sense] = { enabled, hostUsername: hostUsername.trim() };
113
112
  }
114
- // Wake runners the config rejects stay unset here; the sense itself reports the error when it runs them.
113
+ // Config the app-sessions block rejects stays unset here; the sense itself reports the error when it runs.
115
114
  if (sense === "app-sessions") {
116
115
  try {
117
- defaults[sense] = { enabled, ...(0, identity_1.normalizeWakeRunners)(rawSense, agentJsonPath) };
116
+ defaults[sense] = { enabled, ...(0, identity_1.normalizeAppSessionsConfig)(rawSense, agentJsonPath) };
118
117
  }
119
118
  catch {
120
119
  defaults[sense] = { enabled };
@@ -127,12 +126,11 @@ function readAgentSenses(agentJsonPath) {
127
126
  }
128
127
  return { senses: defaults, workbenchHasStaleBundleEntry };
129
128
  }
130
- /** The app-sessions row's `ouro status` lines: sessions waiting on the owner, then each wake runner. */
129
+ /** The app-sessions row's `ouro status` lines: sessions waiting on the owner, and a retired `issueDrains` notice. */
131
130
  function appSessionsLines(agentRoot, config, now) {
132
131
  const lines = [
133
132
  ...(0, waiting_status_1.waitingStatusLines)((0, store_1.readSnapshot)(agentRoot), now),
134
- ...(config.retiredIssueDrains ? ["issueDrains in agent.json is retired and no longer polled: Desk polls drains now, so move them to Desk's drain config and add a wakeRunners entry (docs/app-sessions-sense.md)"] : []),
135
- ...(config.wakeRunners?.length ? (0, wake_runner_state_1.wakeRunnerStatusLines)(config.wakeRunners, (0, wake_runner_state_1.readWakeRunnerStates)(agentRoot), now) : []),
133
+ ...(config.retiredIssueDrains ? ["issueDrains in agent.json is retired and no longer polled: Desk polls drains now, so move them to Desk's drain config, and wake delivery is Shepherd's (~/.config/shepherd/wakes.json; docs/app-sessions-sense.md)"] : []),
136
134
  ];
137
135
  return lines.length ? { lines } : {};
138
136
  }
@@ -40,7 +40,7 @@ exports.defaultStableVaultEmail = defaultStableVaultEmail;
40
40
  exports.resolveVaultConfig = resolveVaultConfig;
41
41
  exports.persistedSenses = persistedSenses;
42
42
  exports.hasStaleWorkbenchBundleEntry = hasStaleWorkbenchBundleEntry;
43
- exports.normalizeWakeRunners = normalizeWakeRunners;
43
+ exports.normalizeAppSessionsConfig = normalizeAppSessionsConfig;
44
44
  exports.normalizeSenses = normalizeSenses;
45
45
  exports.buildDefaultAgentTemplate = buildDefaultAgentTemplate;
46
46
  exports.getAgentName = getAgentName;
@@ -211,47 +211,17 @@ function normalizeDigest(raw, fail) {
211
211
  }
212
212
  return result;
213
213
  }
214
- function normalizeWakeRunners(rawSense, configFile) {
214
+ function normalizeAppSessionsConfig(rawSense, configFile) {
215
215
  function fail(what) {
216
- (0, runtime_1.emitNervesEvent)({ level: "error", event: "config_identity.error", component: "config/identity", message: "agent config has invalid wake runners", meta: { path: configFile } });
216
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "config_identity.error", component: "config/identity", message: "agent config has invalid app-sessions settings", meta: { path: configFile } });
217
217
  throw new Error(`agent.json at ${configFile}: senses.app-sessions.${what}.`);
218
218
  }
219
- const { wakeRunners, issueDrains } = rawSense;
219
+ // `wakeRunners` is ignored: Shepherd delivers wakes now. `issueDrains` is noted, since Desk polls drains now.
220
220
  const result = {};
221
- if (issueDrains !== undefined)
221
+ if (rawSense.issueDrains !== undefined)
222
222
  result.retiredIssueDrains = true;
223
223
  if (rawSense.digest !== undefined)
224
224
  result.digest = normalizeDigest(rawSense.digest, fail);
225
- if (wakeRunners !== undefined) {
226
- if (!Array.isArray(wakeRunners))
227
- fail("wakeRunners must be an array");
228
- const names = new Set();
229
- result.wakeRunners = wakeRunners.map((entry, index) => {
230
- const item = (entry && typeof entry === "object" ? entry : {});
231
- const { name, command, everySeconds, session, delivery } = item;
232
- if (typeof name !== "string" || !name.trim())
233
- fail(`wakeRunners[${index}].name must be a non-empty name`);
234
- if (!Array.isArray(command) || command.length === 0 || command.some(part => typeof part !== "string" || !part))
235
- fail(`wakeRunners[${index}].command must be a non-empty array of strings`);
236
- if (everySeconds !== undefined && (typeof everySeconds !== "number" || !Number.isInteger(everySeconds) || everySeconds < 10))
237
- fail(`wakeRunners[${index}].everySeconds must be a whole number of seconds, 10 or more`);
238
- if (session !== undefined && (typeof session !== "string" || !session.trim()))
239
- fail(`wakeRunners[${index}].session must be a Copilot app session id`);
240
- if (delivery !== undefined && delivery !== "immediate" && delivery !== "enqueue")
241
- fail(`wakeRunners[${index}].delivery must be "immediate" or "enqueue"`);
242
- const key = name.trim();
243
- if (names.has(key))
244
- fail(`wakeRunners[${index}].name ${key} is listed twice`);
245
- names.add(key);
246
- return {
247
- name: key,
248
- command: command,
249
- ...(everySeconds !== undefined ? { everySeconds: everySeconds } : {}),
250
- ...(session !== undefined ? { session: session.trim() } : {}),
251
- ...(delivery !== undefined ? { delivery: delivery } : {}),
252
- };
253
- });
254
- }
255
225
  return result;
256
226
  }
257
227
  function normalizeSenses(value, configFile) {
@@ -345,7 +315,7 @@ function normalizeSenses(value, configFile) {
345
315
  continue;
346
316
  }
347
317
  if (senseName === "app-sessions") {
348
- defaults[senseName] = { enabled, ...normalizeWakeRunners(rawSense, configFile) };
318
+ defaults[senseName] = { enabled, ...normalizeAppSessionsConfig(rawSense, configFile) };
349
319
  continue;
350
320
  }
351
321
  defaults[senseName] = { enabled };
@@ -103,9 +103,8 @@ const DISPATCH_EXEMPT_PATTERNS = [
103
103
  // consumed by server readers and the UI. Mailbox read/render modules own
104
104
  // the observability for these projections.
105
105
  "heart/mailbox/mailbox-types",
106
- // Wake-runner status reader: pure state-file read and line rendering for `ouro status`. The runner
107
- // (wake-runner.ts) owns observability via senses.wake_runner_run and friends.
108
- "senses/app-sessions/wake-runner-state",
106
+ // Argv runner: no events of its own; the digest's sources report a run that failed, with its reason.
107
+ "senses/app-sessions/run-command",
109
108
  // Waiting-prompt status reader: pure line rendering for `ouro status`. The notifier
110
109
  // (waiting-prompts.ts) owns observability via senses.app_sessions_waiting_notice and friends.
111
110
  "senses/app-sessions/waiting-status",
@@ -297,7 +297,7 @@ async function archiveSession(agentRoot, id, options = {}, ownerAsked = false) {
297
297
  reason = ownerAsked ? "owner-asked" : (0, handoff_1.isHandedOff)(agentRoot, row) ? "handed-off" : null;
298
298
  if (!reason) {
299
299
  (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_archive_declined", message: "declined to archive a session this agent did not create", meta: { session: row.id } });
300
- throw new Error(`session ${row.id} was not created by this agent, so it will not archive it unless the owner asked for it or it is oversize and a newer session names it as handed off (yours: ${Object.keys(made).join(", ") || "none"})`);
300
+ throw new Error(`session ${row.id} was not created by this agent, so it will not archive it unless the owner asked for it or a newer session names it as handed off (yours: ${Object.keys(made).join(", ") || "none"})`);
301
301
  }
302
302
  }
303
303
  return archiveRow(agentRoot, row, reason, options);
@@ -43,7 +43,6 @@ exports.assertSessionId = assertSessionId;
43
43
  exports.eventLogPath = eventLogPath;
44
44
  exports.readEventLog = readEventLog;
45
45
  exports.parseEventLines = parseEventLines;
46
- exports.messageDelivered = messageDelivered;
47
46
  exports.describePermission = describePermission;
48
47
  exports.tailFacts = tailFacts;
49
48
  exports.classify = classify;
@@ -55,8 +54,6 @@ exports.readNewAppEvents = readNewAppEvents;
55
54
  exports.messagesIn = messagesIn;
56
55
  exports.eventLogSize = eventLogSize;
57
56
  exports.exchange = exchange;
58
- exports.listSessionQueue = listSessionQueue;
59
- exports.withdrawQueuedMessages = withdrawQueuedMessages;
60
57
  exports.appRunning = appRunning;
61
58
  exports.findHousesitter = findHousesitter;
62
59
  exports.restartEnqueue = restartEnqueue;
@@ -65,7 +62,6 @@ const fs = __importStar(require("node:fs"));
65
62
  const os = __importStar(require("node:os"));
66
63
  const path = __importStar(require("node:path"));
67
64
  const node_child_process_1 = require("node:child_process");
68
- const node_crypto_1 = require("node:crypto");
69
65
  const ws_1 = __importDefault(require("ws"));
70
66
  const runtime_1 = require("../../nerves/runtime");
71
67
  /** The most a send waits: a session whose runtime is not in memory loads first, often for more than 20 s. */
@@ -183,20 +179,6 @@ function parseEventLines(text) {
183
179
  function tailEvents(stateDir, id, bytes) {
184
180
  return parseEventLines(readEventLog(id, { stateDir, maxBytes: bytes }).text);
185
181
  }
186
- const DELIVERY_TAIL_BYTES = 4 * 1024 * 1024;
187
- const DELIVERY_CLOCK_SLACK_MS = 60_000;
188
- const squash = (text) => text.replace(/\s+/g, " ").trim();
189
- /**
190
- * Whether a message sent at `sinceMs` has reached the session: its log holds a user message that starts with the same
191
- * text. A message the app accepted but still holds in its own queue is not in the log yet.
192
- */
193
- function messageDelivered(id, text, sinceMs, options = {}) {
194
- const probe = squash(text).slice(0, 160);
195
- return parseEventLines(readEventLog(id, { ...options, maxBytes: DELIVERY_TAIL_BYTES }).text).some(event => {
196
- const data = isRecord(event.data) ? event.data : {};
197
- return event.type === "user.message" && Date.parse(str(event.timestamp) ?? "") >= sinceMs - DELIVERY_CLOCK_SLACK_MS && squash(str(data.content) ?? "").includes(probe);
198
- });
199
- }
200
182
  const PERMISSION_WHAT = {
201
183
  shell: "run a shell command",
202
184
  write: "change a file",
@@ -582,31 +564,6 @@ function exchange(frames, exchangeOptions, options = {}) {
582
564
  socket.on("close", finish);
583
565
  });
584
566
  }
585
- /** The session's queued messages, oldest first. An empty list when the session has none or the app cannot say. */
586
- async function listSessionQueue(id, options = {}) {
587
- assertSessionId(id);
588
- const requestId = (0, node_crypto_1.randomUUID)();
589
- const got = await exchange([{ type: "get_session_queue", session_id: id, request_id: requestId }], { keep: (frame) => frame.request_id === requestId || frame.type === "socket_error", done: (frame) => frame.request_id === requestId || frame.type === "socket_error", waitMs: options.sendWaitMs ?? exports.SEND_WAIT_MS }, options);
590
- const data = isRecord(got.at(-1)?.data) ? got.at(-1).data : {};
591
- const items = Array.isArray(data.items) ? data.items : [];
592
- return items.filter(isRecord).flatMap(item => (str(item.id) && item.kind === "message" ? [{ id: str(item.id), source: str(item.source) ?? "", text: str(item.display_text) ?? "" }] : []));
593
- }
594
- /**
595
- * Take back the messages of `source: "user"` (what the app's own box and Ouroboros send) that a session still holds in its
596
- * queue and that start with `prefix`. Only those: another session's or an agent's messages stay. Returns how many it removed.
597
- */
598
- async function withdrawQueuedMessages(id, prefix, options = {}) {
599
- const mine = (await listSessionQueue(id, options)).filter(item => item.source === "user" && item.text.startsWith(prefix));
600
- let removed = 0;
601
- for (const item of mine) {
602
- const requestId = (0, node_crypto_1.randomUUID)();
603
- const got = await exchange([{ type: "remove_session_queue_item", session_id: id, id: item.id, request_id: requestId }], { keep: (frame) => frame.request_id === requestId || frame.type === "socket_error", done: (frame) => frame.request_id === requestId || frame.type === "socket_error", waitMs: options.sendWaitMs ?? exports.SEND_WAIT_MS }, options);
604
- if (got.at(-1)?.request_id === requestId && !got.at(-1)?.error)
605
- removed += 1;
606
- }
607
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_queue_withdrawn", message: "took back queued messages a newer one replaces", meta: { session: id, found: mine.length, removed } });
608
- return removed;
609
- }
610
567
  /** Whether the app is up: its server files name a live process. */
611
568
  function appRunning(options = {}) {
612
569
  try {
@@ -12,8 +12,8 @@ const digest_cards_1 = require("./digest-cards");
12
12
  /**
13
13
  * What is worth telling the owner unasked, judged with no model turn from the digest: only what only they can act on.
14
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.
15
+ * broken go in the digest (`/status`), not in a push: a stuck session is shown under Broken there (`shepherd stuck plan` is
16
+ * where it gets fixed), and the machine, the drains and the health watch have owners of their own.
17
17
  *
18
18
  * A condition must last before it counts, is told once and then not again until it clears and comes back, and is
19
19
  * checked live again just before the message goes out. One message carries everything due, at most one per half hour,
@@ -167,10 +167,6 @@ async function buildDigest(input) {
167
167
  const recentArchives = (0, store_1.readArchiveLog)(input.agentRoot)
168
168
  .filter(entry => input.now - Date.parse(entry.at) < exports.CARD_WINDOW_MS)
169
169
  .map(entry => ({ name: cut(entry.name, NAME_MAX), reason: `${ARCHIVE_REASONS[entry.reason]}${entry.note ? ` (${entry.note})` : ""}` }));
170
- const fixed = Object.entries(input.state.resumed ?? {})
171
- .filter(([, entry]) => entry.ok && input.now - Date.parse(entry.at) < exports.CARD_WINDOW_MS)
172
- .sort(([, a], [, b]) => b.at.localeCompare(a.at))
173
- .map(([session, entry]) => ({ session, name: cut(entry.name, NAME_MAX), what: "resumed it: its loop had stopped", at: entry.at, stop: entry.lastActivity }));
174
170
  const digest = {
175
171
  at: new Date(input.now).toISOString(),
176
172
  appRunning: input.appRunning,
@@ -180,7 +176,6 @@ async function buildDigest(input) {
180
176
  machine: machine.installed || machine.error ? machine : null,
181
177
  drains,
182
178
  merged,
183
- ...(fixed.length ? { fixed } : {}),
184
179
  ...(recentArchives.length ? { archived: recentArchives } : {}),
185
180
  unread,
186
181
  tokens: 0,
@@ -205,10 +200,8 @@ function renderDigest(digest, now, plain = false) {
205
200
  blocks.push(["**Needs you**", ...digest.needsOwner.map(item => `- ${item.name} — ${item.text}${item.since ? ` (${minutes(now - item.since)})` : ""}`)].join("\n"));
206
201
  }
207
202
  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}`));
210
203
  for (const session of digest.sessions)
211
- if (session.state === "stuck" && !resumed.has(`${session.id}@${session.lastActivity}`))
204
+ if (session.state === "stuck")
212
205
  broken.push(`- ${session.name} — stuck (${session.detail})`);
213
206
  if (digest.machine?.heartbeat === "bad" || digest.machine?.heartbeat === "stale")
214
207
  broken.push(`- Mac watcher — heartbeat ${digest.machine.heartbeat}${digest.machine.bad ? `: ${digest.machine.bad}` : ""}`);
@@ -218,8 +211,6 @@ function renderDigest(digest, now, plain = false) {
218
211
  broken.push(`- drain ${stale} since its last good poll`);
219
212
  if (broken.length)
220
213
  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"));
223
214
  const { counts } = digest;
224
215
  const working = digest.sessions.filter(session => session.state === "working");
225
216
  const list = working.slice(0, WORKING_LISTED).map(session => sessionLine(session, now));
@@ -168,14 +168,8 @@ function successorOf(id, successions) {
168
168
  }
169
169
  return current === id ? null : current;
170
170
  }
171
- /**
172
- * Whether an oversize session has been handed off: it is in the oversize list, and a newer session's first message
173
- * names it as the session it succeeds, as the sense last recorded.
174
- */
171
+ /** Whether a newer session's first message names this one as the session it succeeds (the chain's live end, via `successorOf`). */
175
172
  function isHandedOff(agentRoot, row) {
176
- const flagged = (0, store_1.readJson)(path.join((0, store_1.appSessionsStateDir)(agentRoot), "oversize.json"), {}).sessions ?? {};
177
- if (!flagged[row.id])
178
- return false;
179
173
  const successor = successorOf(row.id, (0, exports.readSuccessions)(agentRoot));
180
174
  if (successor)
181
175
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_handoff_found", message: "found the successor that a session was handed off to", meta: { session: row.id, successor } });
@@ -33,25 +33,19 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.readWakeRunnerStates = exports.wakeRunnerStateFile = void 0;
37
- exports.wakeRunnerStatusLines = wakeRunnerStatusLines;
36
+ exports.runCommand = void 0;
37
+ const node_child_process_1 = require("node:child_process");
38
38
  const path = __importStar(require("node:path"));
39
- const store_1 = require("./store");
40
- const wakeRunnerStateFile = (agentRoot) => path.join((0, store_1.appSessionsStateDir)(agentRoot), "wake-runners.json");
41
- exports.wakeRunnerStateFile = wakeRunnerStateFile;
42
- const readWakeRunnerStates = (agentRoot) => (0, store_1.readJson)((0, exports.wakeRunnerStateFile)(agentRoot), {});
43
- exports.readWakeRunnerStates = readWakeRunnerStates;
44
- function ago(iso, now) {
45
- const minutes = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000));
46
- return minutes < 1 ? "just now" : minutes < 90 ? `${minutes}m ago` : `${Math.round(minutes / 60)}h ago`;
47
- }
48
- /** One `ouro status` line per runner (last run, wakes delivered, last error), then the lines its command reported. */
49
- function wakeRunnerStatusLines(runners, states, now) {
50
- return runners.flatMap(runner => {
51
- const state = states[runner.name];
52
- if (!state?.lastRunAt)
53
- return [`wake runner ${runner.name}: not run yet`];
54
- const delivered = state.lastWakes === undefined ? "" : `, ${state.lastDelivered}/${state.lastWakes} wake${state.lastWakes === 1 ? "" : "s"} delivered`;
55
- return [`wake runner ${runner.name}: ran ${ago(state.lastRunAt, now)}${delivered}${state.lastError ? `, last error: ${state.lastError}` : ""}`, ...(state.status ?? [])];
39
+ const MAX_LINE = 300;
40
+ const MAX_OUTPUT = 10 * 1024 * 1024;
41
+ /** Runs an argv with no shell, returning what it printed. A non-zero exit, a timeout or a missing program is a failure with its reason. */
42
+ const runCommand = (argv, timeoutMs) => new Promise(resolve => {
43
+ const [program, ...args] = argv;
44
+ (0, node_child_process_1.execFile)(program, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: MAX_OUTPUT, env: process.env }, (error, stdout, stderr) => {
45
+ if (!error)
46
+ return resolve({ ok: true, stdout, error: null });
47
+ const reason = String(stderr).trim().split("\n")[0] || error.message;
48
+ resolve({ ok: false, stdout, error: `${path.basename(program)} failed: ${reason}`.slice(0, MAX_LINE) });
56
49
  });
57
- }
50
+ });
51
+ exports.runCommand = runCommand;
@@ -33,13 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.DIGEST_IDLE_MS = 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.APP_SESSIONS_WAKE_TRIGGER = exports.WATCH_POLL_MS = exports.SNAPSHOT_MS = void 0;
37
37
  exports.newReplies = newReplies;
38
38
  exports.replyContent = replyContent;
39
39
  exports.privateRuntimeDeliver = privateRuntimeDeliver;
40
40
  exports.checkWatches = checkWatches;
41
41
  exports.recordSnapshot = recordSnapshot;
42
- exports.checkWakeRunners = checkWakeRunners;
43
42
  exports.checkDigest = checkDigest;
44
43
  exports.startAppSessionsSense = startAppSessionsSense;
45
44
  const node_crypto_1 = require("node:crypto");
@@ -50,13 +49,12 @@ const runtime_1 = require("../../nerves/runtime");
50
49
  const cmux_1 = require("../shepherd/cmux");
51
50
  const os = __importStar(require("node:os"));
52
51
  const digest_1 = require("./digest");
53
- const stuck_resume_1 = require("./stuck-resume");
54
52
  const digest_push_1 = require("./digest-push");
55
53
  const client_1 = require("./client");
56
54
  const prompts_1 = require("./prompts");
57
55
  const store_1 = require("./store");
58
56
  const waiting_prompts_1 = require("./waiting-prompts");
59
- const wake_runner_1 = require("./wake-runner");
57
+ const run_command_1 = require("./run-command");
60
58
  /**
61
59
  * The app-sessions perception loop. Every minute it snapshots the app's sessions (counts and stuck ids) into the
62
60
  * agent's state for its prompt and health. Every ten seconds it reads the new part of each watched session's log
@@ -178,32 +176,6 @@ async function recordSnapshot(agentRoot, client, now) {
178
176
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_snapshot", message: "snapshotted the Copilot app's sessions", meta: { ...result.counts, appRunning: result.appRunning } });
179
177
  return result;
180
178
  }
181
- /** How long to wait before looking again when no wake runner is configured, so one added to `agent.json` starts within five minutes. */
182
- exports.WAKE_RUNNER_IDLE_MS = 5 * 60_000;
183
- /**
184
- * Run the wake runners in `agent.json` that are due and return the milliseconds until the next one is. `due` remembers each
185
- * runner's next run between calls. A bad config is logged and looked at again later.
186
- */
187
- async function checkWakeRunners(agentName, agentRoot, deps, due = new Map()) {
188
- try {
189
- const config = (0, identity_1.loadAgentConfig)({ agentName, agentRoot }).senses?.["app-sessions"];
190
- const runners = config?.enabled ? config.wakeRunners ?? [] : [];
191
- const every = (name) => (runners.find(runner => runner.name === name)?.everySeconds ?? wake_runner_1.WAKE_RUNNER_DEFAULT_SECONDS) * 1000;
192
- const ready = new Set(runners.filter(runner => (due.get(runner.name) ?? 0) <= deps.now).map(runner => runner.name));
193
- if (runners.length && ready.size)
194
- await (0, wake_runner_1.runWakeRunners)(agentRoot, runners, deps, ready);
195
- for (const name of ready)
196
- due.set(name, deps.now + every(name));
197
- for (const name of [...due.keys()])
198
- if (!runners.some(runner => runner.name === name))
199
- due.delete(name);
200
- return runners.length ? Math.max(1000, Math.min(...runners.map(runner => due.get(runner.name) - deps.now))) : exports.WAKE_RUNNER_IDLE_MS;
201
- }
202
- catch (error) {
203
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.wake_runner_config_error", message: "could not check the wake runners", meta: { error: error.message } });
204
- return exports.WAKE_RUNNER_IDLE_MS;
205
- }
206
- }
207
179
  /** How long to wait before looking again when no digest is configured, so one added to `agent.json` starts within two minutes. */
208
180
  exports.DIGEST_IDLE_MS = 2 * 60_000;
209
181
  /**
@@ -218,7 +190,6 @@ async function checkDigest(agentName, agentRoot, deps) {
218
190
  const list = () => (0, client_1.listAppSessions)({ ...deps.client, now: () => deps.now });
219
191
  const rows = await list();
220
192
  const state = (0, digest_1.readDigestState)(agentRoot);
221
- await (0, stuck_resume_1.resumeStuck)(rows, state, deps.now, { client: deps.client, ...(deps.resume ? { send: deps.resume } : {}) });
222
193
  const digest = await (0, digest_1.writeDigest)({
223
194
  agentRoot, config: config.digest, client: deps.client, run: deps.run, now: deps.now, home: deps.home, rows,
224
195
  appRunning: (0, client_1.appRunning)(deps.client), waitingPrompts: (0, waiting_prompts_1.waitingPromptsOf)(agentRoot, rows, deps.now), state,
@@ -243,9 +214,6 @@ function startAppSessionsSense(options) {
243
214
  let cancelSnapshot;
244
215
  let cancelWatch = null;
245
216
  let inFlight = Promise.resolve();
246
- let cancelRunners = null;
247
- let runnerPoll = Promise.resolve();
248
- const due = new Map();
249
217
  let waitingPoll = Promise.resolve();
250
218
  const notifyOwner = options.notifyOwner ?? (0, waiting_prompts_1.ownerNotifier)(options.agentName, agentRoot);
251
219
  let cancelDigest = null;
@@ -268,18 +236,10 @@ function startAppSessionsSense(options) {
268
236
  cancelWatch = schedule(watchTick, exports.WATCH_POLL_MS);
269
237
  });
270
238
  };
271
- const runnerTick = () => {
272
- if (stopped)
273
- return;
274
- runnerPoll = checkWakeRunners(options.agentName, agentRoot, { run: options.runCommand ?? wake_runner_1.runCommand, send: options.sendWake ?? (0, wake_runner_1.sendWake)(client), delivered: options.wasDelivered ?? (0, wake_runner_1.wasDelivered)(client), now: now() }, due).then(ms => {
275
- if (!stopped)
276
- cancelRunners = schedule(runnerTick, ms);
277
- });
278
- };
279
239
  const digestTick = () => {
280
240
  if (stopped)
281
241
  return;
282
- digestPoll = checkDigest(options.agentName, agentRoot, { client, run: options.runCommand ?? wake_runner_1.runCommand, notify: notifyOwner, now: now(), home: os.homedir() }).then(ms => {
242
+ digestPoll = checkDigest(options.agentName, agentRoot, { client, run: options.runCommand ?? run_command_1.runCommand, notify: notifyOwner, now: now(), home: os.homedir() }).then(ms => {
283
243
  if (!stopped)
284
244
  cancelDigest = schedule(digestTick, ms);
285
245
  });
@@ -288,18 +248,16 @@ function startAppSessionsSense(options) {
288
248
  const prompts = (0, prompts_1.startPromptTracker)({ agentRoot, ...(client.stateDir ? { stateDir: client.stateDir } : {}), ...(client.openSocket ? { openSocket: client.openSocket } : {}), schedule, now });
289
249
  snapshotTick();
290
250
  watchTick();
291
- runnerTick();
292
251
  digestTick();
293
252
  return {
294
253
  stop: () => {
295
254
  stopped = true;
296
255
  cancelSnapshot();
297
256
  cancelWatch?.();
298
- cancelRunners?.();
299
257
  prompts.stop();
300
258
  cancelDigest?.();
301
259
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_end", message: "app-sessions sense stopped", meta: { agent: options.agentName } });
302
260
  },
303
- done: () => Promise.all([inFlight, runnerPoll, waitingPoll, digestPoll]).then(() => undefined),
261
+ done: () => Promise.all([inFlight, waitingPoll, digestPoll]).then(() => undefined),
304
262
  };
305
263
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1170",
3
+ "version": "0.1.0-alpha.1171",
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.1170",
9
+ "version": "0.1.0-alpha.1171",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1170",
3
+ "version": "0.1.0-alpha.1171",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },
@@ -1,52 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RESUME_TEXT = exports.RESUMES_PER_DAY = exports.RESUME_MAX_LOG_BYTES = exports.RESUME_MAX_IDLE_MS = void 0;
4
- exports.resumeStuck = resumeStuck;
5
- const runtime_1 = require("../../nerves/runtime");
6
- const app_interface_1 = require("./app-interface");
7
- const client_1 = require("./client");
8
- /**
9
- * A session whose loop stopped (not running, its last turn called tools and no next turn started) is something an
10
- * agent can fix, so the sense fixes it rather than asking the owner: it sends the session one message to carry on, once
11
- * per stop, and the digest shows it under what was fixed. A session asleep for over a day, one whose history is over
12
- * 500 MB (the app loads all of it on resume) or a remote one is left alone, and a session that keeps stopping is resumed
13
- * at most three times a day; past that it stays under "Broken" in the digest.
14
- */
15
- exports.RESUME_MAX_IDLE_MS = 24 * 3_600_000;
16
- exports.RESUME_MAX_LOG_BYTES = 500 * 1024 * 1024;
17
- exports.RESUMES_PER_DAY = 3;
18
- exports.RESUME_TEXT = "Your loop stopped: your last turn ended without finishing and no next turn started. Carry on where you left off. Re-check anything that was in flight (a shell command, a subagent, a send or a push) before relying on it.";
19
- /** Whether the app lists this session as stopped mid-loop, rather than hung while running. */
20
- const loopStopped = (row) => row.state === "stuck" && !row.isRunning && !row.remote && !row.awaiting;
21
- /** Resumes every session whose loop stopped since it was last resumed. Returns how many it resumed. */
22
- async function resumeStuck(rows, state, now, deps = {}) {
23
- const send = deps.send ?? ((id, text) => (0, app_interface_1.deliverMessage)(id, text, "immediate", deps.client));
24
- const resumed = (state.resumed ??= {});
25
- for (const [id, entry] of Object.entries(resumed)) {
26
- entry.times = entry.times.filter(at => now - Date.parse(at) < 24 * 3_600_000);
27
- if (!entry.times.length)
28
- delete resumed[id];
29
- }
30
- let count = 0;
31
- for (const row of rows) {
32
- if (!loopStopped(row))
33
- continue;
34
- const last = Date.parse(row.lastActivity ?? "");
35
- if (Number.isNaN(last) || now - last > exports.RESUME_MAX_IDLE_MS)
36
- continue;
37
- if ((0, client_1.eventLogSize)(row.id, deps.client) > exports.RESUME_MAX_LOG_BYTES)
38
- continue;
39
- const before = resumed[row.id];
40
- if (before?.lastActivity === row.lastActivity)
41
- continue;
42
- if ((before?.times.length ?? 0) >= exports.RESUMES_PER_DAY)
43
- continue;
44
- const asked = await send(row.id, exports.RESUME_TEXT).catch((error) => ({ ok: false, frame: null, error: error.message }));
45
- const at = new Date(now).toISOString();
46
- resumed[row.id] = { name: row.name, lastActivity: row.lastActivity, at, ok: asked.ok, times: [...(before?.times ?? []), at] };
47
- if (asked.ok)
48
- count += 1;
49
- (0, runtime_1.emitNervesEvent)({ level: asked.ok ? "info" : "warn", component: "senses", event: "senses.app_sessions_stuck_resumed", message: asked.ok ? "resumed a session whose loop had stopped" : "could not resume a session whose loop had stopped", meta: { session: row.id, ok: asked.ok, ...(asked.error ? { error: asked.error } : {}) } });
50
- }
51
- return count;
52
- }
@@ -1,194 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.sendWake = exports.wasDelivered = exports.runCommand = exports.WAKE_HOLD_MS = exports.WAKE_RUNNER_TIMEOUT_MS = exports.WAKE_RUNNER_DEFAULT_SECONDS = void 0;
37
- exports.parseWakeOutput = parseWakeOutput;
38
- exports.runWakeRunner = runWakeRunner;
39
- exports.runWakeRunners = runWakeRunners;
40
- const node_child_process_1 = require("node:child_process");
41
- const path = __importStar(require("node:path"));
42
- const runtime_1 = require("../../nerves/runtime");
43
- const app_interface_1 = require("./app-interface");
44
- const client_1 = require("./client");
45
- const store_1 = require("./store");
46
- const wake_runner_state_1 = require("./wake-runner-state");
47
- /**
48
- * Wake runners: a command the agent runs on a cadence and delivers the wakes of to Copilot app sessions. The agent knows
49
- * nothing about what the command watches. Desk's `drains.js poll` is the one that watches GitHub issues; anything that
50
- * prints the same JSON works.
51
- *
52
- * The command prints one JSON value: `{ "wakes": [{ "session", "message", "done" }], "status": ["…"] }`. Each wake's message
53
- * is sent to its session (`session` is optional when the runner names one). `done` is the argv that reports the wake's
54
- * delivery: it runs after a successful send, and with `--error <reason>` added after a failed one, so the command can keep
55
- * the wake pending until it lands. `status` lines show under the app-sessions row of `ouro status`.
56
- *
57
- * A wake is delivered "immediate" by default: the app admits it at the session's next turn boundary. A session that works for
58
- * hours in one run never goes idle, so a message queued behind that run ("enqueue") waits until the run ends, however old the
59
- * news in it. A runner can ask for "enqueue" when a wake should never interrupt.
60
- *
61
- * The app holds an accepted message in its own queue until the session reaches a turn boundary, and it cannot be taken back.
62
- * So a session gets one wake at a time: while the last wake sent to it has not shown up in its log, the next wake is held
63
- * and reported undelivered, and the command, which re-derives its state every run, offers it again. A wake still missing
64
- * after `WAKE_HOLD_MS` is taken as lost. Held wakes never pile up in the app as hours-old news.
65
- *
66
- * A wake may name `replaces`, a message prefix. Before it is sent, the messages the session still holds in the app's queue
67
- * that start with it (and come from the user side, never another session's or an agent's) are taken back, so a newer wake
68
- * replaces older undelivered ones instead of queueing behind them.
69
- */
70
- exports.WAKE_RUNNER_DEFAULT_SECONDS = 300;
71
- exports.WAKE_RUNNER_TIMEOUT_MS = 2 * 60_000;
72
- exports.WAKE_HOLD_MS = 30 * 60_000;
73
- const MAX_STATUS_LINES = 20;
74
- const MAX_LINE = 300;
75
- const MAX_OUTPUT = 10 * 1024 * 1024;
76
- /** The command's output as wakes and status lines, or the reason it is not one. */
77
- function parseWakeOutput(stdout) {
78
- let parsed;
79
- try {
80
- parsed = JSON.parse(stdout);
81
- }
82
- catch {
83
- throw new Error("the command did not print JSON");
84
- }
85
- const record = (parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {});
86
- if (!Array.isArray(record.wakes))
87
- throw new Error('the command printed no "wakes" array');
88
- const wakes = record.wakes.map((entry, index) => {
89
- const wake = (entry && typeof entry === "object" ? entry : {});
90
- if (typeof wake.message !== "string" || !wake.message.trim())
91
- throw new Error(`wakes[${index}] has no message`);
92
- if (wake.session !== undefined && (typeof wake.session !== "string" || !wake.session.trim()))
93
- throw new Error(`wakes[${index}].session is not a session id`);
94
- if (wake.done !== undefined && (!Array.isArray(wake.done) || wake.done.length === 0 || wake.done.some(part => typeof part !== "string")))
95
- throw new Error(`wakes[${index}].done is not an argv`);
96
- if (wake.replaces !== undefined && (typeof wake.replaces !== "string" || !wake.replaces.trim()))
97
- throw new Error(`wakes[${index}].replaces is not a message prefix`);
98
- return { message: wake.message, ...(wake.session !== undefined ? { session: wake.session } : {}), ...(wake.done !== undefined ? { done: wake.done } : {}), ...(wake.replaces !== undefined ? { replaces: wake.replaces } : {}) };
99
- });
100
- // eslint-disable-next-line no-control-regex
101
- const clean = (line) => line.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim().slice(0, MAX_LINE);
102
- const status = Array.isArray(record.status) ? record.status.filter((line) => typeof line === "string").map(clean).filter(Boolean).slice(0, MAX_STATUS_LINES) : [];
103
- return { wakes, status };
104
- }
105
- /** Runs an argv with no shell, returning what it printed. A non-zero exit, a timeout or a missing program is a failure with its reason. */
106
- const runCommand = (argv, timeoutMs) => new Promise(resolve => {
107
- const [program, ...args] = argv;
108
- (0, node_child_process_1.execFile)(program, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: MAX_OUTPUT, env: process.env }, (error, stdout, stderr) => {
109
- if (!error)
110
- return resolve({ ok: true, stdout, error: null });
111
- const reason = String(stderr).trim().split("\n")[0] || error.message;
112
- resolve({ ok: false, stdout, error: `${path.basename(program)} failed: ${reason}`.slice(0, MAX_LINE) });
113
- });
114
- });
115
- exports.runCommand = runCommand;
116
- const wasDelivered = (client) => (session, message, sinceMs) => (0, client_1.messageDelivered)(session, message, sinceMs, client);
117
- exports.wasDelivered = wasDelivered;
118
- const sendWake = (client) => async (session, message, delivery, replaces) => {
119
- // The command re-derives its whole state each run, so a wake still queued in the session is stale news: take it back first.
120
- if (replaces)
121
- await (0, client_1.withdrawQueuedMessages)(session, replaces, client).catch(() => 0);
122
- const result = await (0, app_interface_1.deliverMessage)(session, message, delivery, client);
123
- return { ok: result.ok, error: result.error };
124
- };
125
- exports.sendWake = sendWake;
126
- /** Run one runner's command, deliver its wakes and report each one back. Returns the runner's new state. */
127
- async function runWakeRunner(runner, deps, previous = {}) {
128
- const state = { lastRunAt: new Date(deps.now).toISOString() };
129
- const open = openWakes(previous, deps);
130
- if (Object.keys(open).length)
131
- state.open = open;
132
- const ran = await deps.run(runner.command, exports.WAKE_RUNNER_TIMEOUT_MS);
133
- if (!ran.ok)
134
- return fail(runner, state, ran.error ?? "the command failed");
135
- let output;
136
- try {
137
- output = parseWakeOutput(ran.stdout);
138
- }
139
- catch (error) {
140
- return fail(runner, state, error.message);
141
- }
142
- state.status = output.status;
143
- state.lastWakes = output.wakes.length;
144
- state.lastDelivered = 0;
145
- const problems = [];
146
- for (const wake of output.wakes) {
147
- const session = wake.session ?? runner.session;
148
- // A wake that replaces older ones takes them back from the app's queue and goes out; only a wake that cannot is held behind the last one.
149
- const holding = session && !wake.replaces ? state.open?.[session] : undefined;
150
- const sent = !session
151
- ? { ok: false, error: "the wake names no session and the runner has none" }
152
- : holding
153
- ? { ok: false, error: `held: the wake sent ${ageLabel(deps.now - Date.parse(holding.at))} ago has not reached the session yet` }
154
- : await deps.send(session, wake.message, runner.delivery ?? "immediate", wake.replaces).catch((error) => ({ ok: false, error: error.message }));
155
- if (session && sent.ok)
156
- (state.open ??= {})[session] = { at: new Date(deps.now).toISOString(), message: wake.message };
157
- const reason = sent.ok ? null : sent.error ?? "the app refused the message";
158
- if (!reason)
159
- state.lastDelivered += 1;
160
- else
161
- problems.push(`could not deliver a wake: ${reason}`);
162
- if (wake.done) {
163
- const reported = await deps.run(reason === null ? wake.done : [...wake.done, "--error", reason], exports.WAKE_RUNNER_TIMEOUT_MS);
164
- if (!reported.ok)
165
- problems.push(`could not report a wake's delivery: ${reported.error ?? "the command failed"}`);
166
- }
167
- }
168
- if (problems.length)
169
- state.lastError = problems[0];
170
- (0, runtime_1.emitNervesEvent)({ level: problems.length ? "warn" : "info", component: "senses", event: "senses.wake_runner_run", message: "ran a wake runner and delivered its wakes", meta: { runner: runner.name, wakes: state.lastWakes, delivered: state.lastDelivered, problems: problems.length } });
171
- return state;
172
- }
173
- const ageLabel = (ms) => `${Math.max(1, Math.round(ms / 60_000))} min`;
174
- /** The wakes sent earlier that are still in the app's queue, by session: the ones the session's log does not show and that are younger than the hold. */
175
- function openWakes(previous, deps) {
176
- return Object.fromEntries(Object.entries(previous.open ?? {}).filter(([session, wake]) => {
177
- const sentAt = Date.parse(wake.at);
178
- return deps.now - sentAt < exports.WAKE_HOLD_MS && !deps.delivered(session, wake.message, sentAt);
179
- }));
180
- }
181
- function fail(runner, state, reason) {
182
- state.lastError = reason;
183
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.wake_runner_error", message: "a wake runner's command did not give wakes; nothing was delivered", meta: { runner: runner.name, error: reason } });
184
- return state;
185
- }
186
- /** Run the `only` runners of the configured list (all by default) and write the states. A runner dropped from the config loses its state. */
187
- async function runWakeRunners(agentRoot, runners, deps, only) {
188
- const stored = (0, wake_runner_state_1.readWakeRunnerStates)(agentRoot);
189
- const states = Object.fromEntries(runners.map(runner => [runner.name, stored[runner.name] ?? {}]));
190
- for (const runner of runners)
191
- if (!only || only.has(runner.name))
192
- states[runner.name] = await runWakeRunner(runner, deps, stored[runner.name]);
193
- (0, store_1.writeJson)((0, wake_runner_state_1.wakeRunnerStateFile)(agentRoot), states);
194
- }