@ouro.bot/cli 0.1.0-alpha.1115 → 0.1.0-alpha.1116

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.1116",
6
+ "changes": [
7
+ "The issue-drain poller moved to Desk, and the app-sessions sense now only runs commands and delivers their wakes. Add a `wakeRunners` entry to `senses.app-sessions` in agent.json (`name`, `command` as an argv array, optional `everySeconds` of 10 or more, default 300, and optional `session`): the sense runs the command on that cadence, sends each wake it prints to its session, and runs the wake's `done` command to report delivery. `ouro status` lists each runner and the command's own status lines, and the daemon still starts without loading the app client. `issueDrains` and `issuePollMinutes` are retired: a config that still has them shows a notice and is otherwise ignored, so move the drains to Desk's drain config (same fields, same state shape, so seen markers carry over) before updating. See docs/app-sessions-sense.md."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1115",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1115",
2
+ "runtimeVersion": "0.1.0-alpha.1116",
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.1115</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1116</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,7 @@ 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 issue_drain_state_1 = require("../../senses/app-sessions/issue-drain-state");
48
+ const wake_runner_state_1 = require("../../senses/app-sessions/wake-runner-state");
49
49
  const store_1 = require("../../senses/app-sessions/store");
50
50
  const waiting_status_1 = require("../../senses/app-sessions/waiting-status");
51
51
  const process_manager_1 = require("./process-manager");
@@ -111,10 +111,10 @@ function readAgentSenses(agentJsonPath) {
111
111
  if (sense === "bluebubbles" && typeof hostUsername === "string" && hostUsername.trim().length > 0) {
112
112
  defaults[sense] = { enabled, hostUsername: hostUsername.trim() };
113
113
  }
114
- // Issue drains the config rejects stay unset here; the sense itself reports the error when it polls.
114
+ // Wake runners the config rejects stay unset here; the sense itself reports the error when it runs them.
115
115
  if (sense === "app-sessions") {
116
116
  try {
117
- defaults[sense] = { enabled, ...(0, identity_1.normalizeIssueDrains)(rawSense, agentJsonPath) };
117
+ defaults[sense] = { enabled, ...(0, identity_1.normalizeWakeRunners)(rawSense, agentJsonPath) };
118
118
  }
119
119
  catch {
120
120
  defaults[sense] = { enabled };
@@ -127,9 +127,13 @@ function readAgentSenses(agentJsonPath) {
127
127
  }
128
128
  return { senses: defaults, workbenchHasStaleBundleEntry };
129
129
  }
130
- /** The app-sessions row's `ouro status` lines: sessions waiting on the owner, then each issue drain. */
131
- function appSessionsLines(agentRoot, drains, now) {
132
- const lines = [...(0, waiting_status_1.waitingStatusLines)((0, store_1.readSnapshot)(agentRoot), now), ...(drains?.length ? (0, issue_drain_state_1.drainStatusLines)(drains, (0, issue_drain_state_1.readDrainStates)(agentRoot), now) : [])];
130
+ /** The app-sessions row's `ouro status` lines: sessions waiting on the owner, then each wake runner. */
131
+ function appSessionsLines(agentRoot, config, now) {
132
+ const lines = [
133
+ ...(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) : []),
136
+ ];
133
137
  return lines.length ? { lines } : {};
134
138
  }
135
139
  function textField(record, key) {
@@ -1105,7 +1109,7 @@ class DaemonSenseManager {
1105
1109
  : entry.sense === "workbench"
1106
1110
  ? WORKBENCH_RUNTIME_INJECTION_DETAIL
1107
1111
  : "not enabled in agent.json",
1108
- ...(entry.enabled && entry.sense === "app-sessions" ? appSessionsLines(path.join(this.bundlesRoot, `${agent}.ouro`), context.senses["app-sessions"].issueDrains, Date.now()) : {}),
1112
+ ...(entry.enabled && entry.sense === "app-sessions" ? appSessionsLines(path.join(this.bundlesRoot, `${agent}.ouro`), context.senses["app-sessions"], Date.now()) : {}),
1109
1113
  ...(entry.sense === "bluebubbles" && blueBubblesConfigured ? {
1110
1114
  proofMethod: blueBubblesRuntimeFacts.proofMethod,
1111
1115
  lastProofAt: blueBubblesRuntimeFacts.lastProofAt,
@@ -40,7 +40,7 @@ exports.defaultStableVaultEmail = defaultStableVaultEmail;
40
40
  exports.resolveVaultConfig = resolveVaultConfig;
41
41
  exports.persistedSenses = persistedSenses;
42
42
  exports.hasStaleWorkbenchBundleEntry = hasStaleWorkbenchBundleEntry;
43
- exports.normalizeIssueDrains = normalizeIssueDrains;
43
+ exports.normalizeWakeRunners = normalizeWakeRunners;
44
44
  exports.normalizeSenses = normalizeSenses;
45
45
  exports.buildDefaultAgentTemplate = buildDefaultAgentTemplate;
46
46
  exports.getAgentName = getAgentName;
@@ -175,49 +175,42 @@ function hasStaleWorkbenchBundleEntry(rawSenses, rawMcpServers) {
175
175
  const rawWorkbench = rawSenses.workbench;
176
176
  return !(isPlainRecord(rawWorkbench) && rawWorkbench.enabled === false);
177
177
  }
178
- function normalizeIssueDrains(rawSense, configFile) {
178
+ function normalizeWakeRunners(rawSense, configFile) {
179
179
  function fail(what) {
180
- (0, runtime_1.emitNervesEvent)({ level: "error", event: "config_identity.error", component: "config/identity", message: "agent config has invalid issue drains", meta: { path: configFile } });
180
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "config_identity.error", component: "config/identity", message: "agent config has invalid wake runners", meta: { path: configFile } });
181
181
  throw new Error(`agent.json at ${configFile}: senses.app-sessions.${what}.`);
182
182
  }
183
- const { issueDrains, issuePollMinutes } = rawSense;
183
+ const { wakeRunners, issueDrains } = rawSense;
184
184
  const result = {};
185
- if (issueDrains !== undefined) {
186
- if (!Array.isArray(issueDrains))
187
- fail("issueDrains must be an array");
188
- const seen = new Set();
189
- result.issueDrains = issueDrains.map((entry, index) => {
185
+ if (issueDrains !== undefined)
186
+ result.retiredIssueDrains = true;
187
+ if (wakeRunners !== undefined) {
188
+ if (!Array.isArray(wakeRunners))
189
+ fail("wakeRunners must be an array");
190
+ const names = new Set();
191
+ result.wakeRunners = wakeRunners.map((entry, index) => {
190
192
  const item = (entry && typeof entry === "object" ? entry : {});
191
- const { repo, session, account, ignoredBodyTrailers, ignoredLabels } = item;
192
- if (typeof repo !== "string" || !/^[\w.-]+\/[\w.-]+$/.test(repo))
193
- fail(`issueDrains[${index}].repo must be "owner/name"`);
194
- if (typeof session !== "string" || !session.trim())
195
- fail(`issueDrains[${index}].session must be a Copilot app session id`);
196
- if (account !== undefined && (typeof account !== "string" || !account.trim()))
197
- fail(`issueDrains[${index}].account must be a GitHub login`);
198
- if (ignoredBodyTrailers !== undefined && (!Array.isArray(ignoredBodyTrailers) || ignoredBodyTrailers.some(key => typeof key !== "string" || !/^[\w][\w -]*$/.test(key.trim())))) {
199
- fail(`issueDrains[${index}].ignoredBodyTrailers must be an array of trailer keys such as "Active-at"`);
200
- }
201
- if (ignoredLabels !== undefined && (!Array.isArray(ignoredLabels) || ignoredLabels.some(name => typeof name !== "string" || !name.trim()))) {
202
- fail(`issueDrains[${index}].ignoredLabels must be an array of label names such as "agent:drain"`);
203
- }
204
- if (seen.has(repo))
205
- fail(`issueDrains[${index}].repo ${repo} is listed twice`);
206
- seen.add(repo);
193
+ const { name, command, everySeconds, session } = item;
194
+ if (typeof name !== "string" || !name.trim())
195
+ fail(`wakeRunners[${index}].name must be a non-empty name`);
196
+ if (!Array.isArray(command) || command.length === 0 || command.some(part => typeof part !== "string" || !part))
197
+ fail(`wakeRunners[${index}].command must be a non-empty array of strings`);
198
+ if (everySeconds !== undefined && (typeof everySeconds !== "number" || !Number.isInteger(everySeconds) || everySeconds < 10))
199
+ fail(`wakeRunners[${index}].everySeconds must be a whole number of seconds, 10 or more`);
200
+ if (session !== undefined && (typeof session !== "string" || !session.trim()))
201
+ fail(`wakeRunners[${index}].session must be a Copilot app session id`);
202
+ const key = name.trim();
203
+ if (names.has(key))
204
+ fail(`wakeRunners[${index}].name ${key} is listed twice`);
205
+ names.add(key);
207
206
  return {
208
- repo: repo,
209
- session: session.trim(),
210
- ...(account !== undefined ? { account: account.trim() } : {}),
211
- ...(ignoredBodyTrailers !== undefined ? { ignoredBodyTrailers: ignoredBodyTrailers.map(key => key.trim()) } : {}),
212
- ...(ignoredLabels !== undefined ? { ignoredLabels: ignoredLabels.map(name => name.trim()) } : {}),
207
+ name: key,
208
+ command: command,
209
+ ...(everySeconds !== undefined ? { everySeconds: everySeconds } : {}),
210
+ ...(session !== undefined ? { session: session.trim() } : {}),
213
211
  };
214
212
  });
215
213
  }
216
- if (issuePollMinutes !== undefined) {
217
- if (typeof issuePollMinutes !== "number" || !Number.isFinite(issuePollMinutes) || issuePollMinutes < 1)
218
- fail("issuePollMinutes must be a number of at least 1");
219
- result.issuePollMinutes = issuePollMinutes;
220
- }
221
214
  return result;
222
215
  }
223
216
  function normalizeSenses(value, configFile) {
@@ -311,7 +304,7 @@ function normalizeSenses(value, configFile) {
311
304
  continue;
312
305
  }
313
306
  if (senseName === "app-sessions") {
314
- defaults[senseName] = { enabled, ...normalizeIssueDrains(rawSense, configFile) };
307
+ defaults[senseName] = { enabled, ...normalizeWakeRunners(rawSense, configFile) };
315
308
  continue;
316
309
  }
317
310
  defaults[senseName] = { enabled };
@@ -103,9 +103,9 @@ 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
- // Issue-drain status reader: pure state-file read and line rendering for `ouro status`. The poller
107
- // (issue-drains.ts) owns observability via senses.issue_drain_poll and friends.
108
- "senses/app-sessions/issue-drain-state",
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",
109
109
  // Waiting-prompt status reader: pure line rendering for `ouro status`. The notifier
110
110
  // (waiting-prompts.ts) owns observability via senses.app_sessions_waiting_notice and friends.
111
111
  "senses/app-sessions/waiting-status",
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.APP_SESSIONS_WAKE_TRIGGER = exports.WATCH_POLL_MS = exports.SNAPSHOT_MS = void 0;
3
+ exports.WAKE_RUNNER_IDLE_MS = exports.APP_SESSIONS_WAKE_TRIGGER = exports.WATCH_POLL_MS = exports.SNAPSHOT_MS = void 0;
4
4
  exports.newReplies = newReplies;
5
5
  exports.replyContent = replyContent;
6
6
  exports.privateRuntimeDeliver = privateRuntimeDeliver;
7
7
  exports.checkWatches = checkWatches;
8
8
  exports.recordSnapshot = recordSnapshot;
9
- exports.checkIssueDrains = checkIssueDrains;
9
+ exports.checkWakeRunners = checkWakeRunners;
10
10
  exports.startAppSessionsSense = startAppSessionsSense;
11
11
  const node_crypto_1 = require("node:crypto");
12
12
  const socket_client_1 = require("../../heart/daemon/socket-client");
@@ -14,10 +14,10 @@ const identity_1 = require("../../heart/identity");
14
14
  const pending_1 = require("../../mind/pending");
15
15
  const runtime_1 = require("../../nerves/runtime");
16
16
  const cmux_1 = require("../shepherd/cmux");
17
- const issue_drains_1 = require("./issue-drains");
18
17
  const client_1 = require("./client");
19
18
  const store_1 = require("./store");
20
19
  const waiting_prompts_1 = require("./waiting-prompts");
20
+ const wake_runner_1 = require("./wake-runner");
21
21
  /**
22
22
  * The app-sessions perception loop. Every minute it snapshots the app's sessions (counts and stuck ids) into the
23
23
  * agent's state for its prompt and health. Every ten seconds it reads the new part of each watched session's log
@@ -137,17 +137,30 @@ function recordSnapshot(agentRoot, client, now) {
137
137
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_snapshot", message: "snapshotted the Copilot app's sessions", meta: { ...result.counts, appRunning: result.appRunning } });
138
138
  return result;
139
139
  }
140
- /** Poll the issue drains in `agent.json` once; returns the milliseconds until the next poll. A bad config is logged and retried then. */
141
- async function checkIssueDrains(agentName, agentRoot, deps) {
140
+ /** How long to wait before looking again when no wake runner is configured, so one added to `agent.json` starts within five minutes. */
141
+ exports.WAKE_RUNNER_IDLE_MS = 5 * 60_000;
142
+ /**
143
+ * Run the wake runners in `agent.json` that are due and return the milliseconds until the next one is. `due` remembers each
144
+ * runner's next run between calls. A bad config is logged and looked at again later.
145
+ */
146
+ async function checkWakeRunners(agentName, agentRoot, deps, due = new Map()) {
142
147
  try {
143
148
  const config = (0, identity_1.loadAgentConfig)({ agentName, agentRoot }).senses?.["app-sessions"];
144
- if (config?.enabled && config.issueDrains?.length)
145
- await (0, issue_drains_1.pollIssueDrains)(agentRoot, config.issueDrains, deps);
146
- return config?.issuePollMinutes ? config.issuePollMinutes * 60_000 : issue_drains_1.ISSUE_POLL_MS;
149
+ const runners = config?.enabled ? config.wakeRunners ?? [] : [];
150
+ const every = (name) => (runners.find(runner => runner.name === name)?.everySeconds ?? wake_runner_1.WAKE_RUNNER_DEFAULT_SECONDS) * 1000;
151
+ const ready = new Set(runners.filter(runner => (due.get(runner.name) ?? 0) <= deps.now).map(runner => runner.name));
152
+ if (runners.length && ready.size)
153
+ await (0, wake_runner_1.runWakeRunners)(agentRoot, runners, deps, ready);
154
+ for (const name of ready)
155
+ due.set(name, deps.now + every(name));
156
+ for (const name of [...due.keys()])
157
+ if (!runners.some(runner => runner.name === name))
158
+ due.delete(name);
159
+ return runners.length ? Math.max(1000, Math.min(...runners.map(runner => due.get(runner.name) - deps.now))) : exports.WAKE_RUNNER_IDLE_MS;
147
160
  }
148
161
  catch (error) {
149
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.issue_drain_error", message: "could not check the issue drains", meta: { error: error.message } });
150
- return issue_drains_1.ISSUE_POLL_MS;
162
+ (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 } });
163
+ return exports.WAKE_RUNNER_IDLE_MS;
151
164
  }
152
165
  }
153
166
  function startAppSessionsSense(options) {
@@ -160,8 +173,9 @@ function startAppSessionsSense(options) {
160
173
  let cancelSnapshot;
161
174
  let cancelWatch = null;
162
175
  let inFlight = Promise.resolve();
163
- let cancelIssues = null;
164
- let issuePoll = Promise.resolve();
176
+ let cancelRunners = null;
177
+ let runnerPoll = Promise.resolve();
178
+ const due = new Map();
165
179
  let waitingPoll = Promise.resolve();
166
180
  const notifyOwner = options.notifyOwner ?? (0, waiting_prompts_1.ownerNotifier)(options.agentName, agentRoot);
167
181
  const snapshotTick = () => {
@@ -183,26 +197,26 @@ function startAppSessionsSense(options) {
183
197
  cancelWatch = schedule(watchTick, exports.WATCH_POLL_MS);
184
198
  });
185
199
  };
186
- const issueTick = () => {
200
+ const runnerTick = () => {
187
201
  if (stopped)
188
202
  return;
189
- issuePoll = checkIssueDrains(options.agentName, agentRoot, { connect: options.connectGithub ?? issue_drains_1.connectGithub, send: options.sendWake ?? (0, issue_drains_1.sendWake)(client), now: now() }).then(ms => {
203
+ runnerPoll = checkWakeRunners(options.agentName, agentRoot, { run: options.runCommand ?? wake_runner_1.runCommand, send: options.sendWake ?? (0, wake_runner_1.sendWake)(client), now: now() }, due).then(ms => {
190
204
  if (!stopped)
191
- cancelIssues = schedule(issueTick, ms);
205
+ cancelRunners = schedule(runnerTick, ms);
192
206
  });
193
207
  };
194
208
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_start", message: "app-sessions sense started", meta: { agent: options.agentName } });
195
209
  snapshotTick();
196
210
  watchTick();
197
- issueTick();
211
+ runnerTick();
198
212
  return {
199
213
  stop: () => {
200
214
  stopped = true;
201
215
  cancelSnapshot();
202
216
  cancelWatch?.();
203
- cancelIssues?.();
217
+ cancelRunners?.();
204
218
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_end", message: "app-sessions sense stopped", meta: { agent: options.agentName } });
205
219
  },
206
- done: () => Promise.all([inFlight, issuePoll, waitingPoll]).then(() => undefined),
220
+ done: () => Promise.all([inFlight, runnerPoll, waitingPoll]).then(() => undefined),
207
221
  };
208
222
  }
@@ -33,30 +33,25 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.drainStateFile = exports.seenIssue = void 0;
37
- exports.readDrainStates = readDrainStates;
38
- exports.drainStatusLines = drainStatusLines;
36
+ exports.readWakeRunnerStates = exports.wakeRunnerStateFile = void 0;
37
+ exports.wakeRunnerStatusLines = wakeRunnerStatusLines;
39
38
  const path = __importStar(require("node:path"));
40
39
  const store_1 = require("./store");
41
- const seenIssue = (entry) => typeof entry === "string" ? { updatedAt: entry } : entry;
42
- exports.seenIssue = seenIssue;
43
- const drainStateFile = (agentRoot) => path.join((0, store_1.appSessionsStateDir)(agentRoot), "issue-drains.json");
44
- exports.drainStateFile = drainStateFile;
45
- function readDrainStates(agentRoot) {
46
- return (0, store_1.readJson)((0, exports.drainStateFile)(agentRoot), {});
47
- }
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;
48
44
  function ago(iso, now) {
49
45
  const minutes = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000));
50
46
  return minutes < 1 ? "just now" : minutes < 90 ? `${minutes}m ago` : `${Math.round(minutes / 60)}h ago`;
51
47
  }
52
- /** One `ouro status` line per drain: its last poll, open issues, events waiting, last wake and last error. */
53
- function drainStatusLines(drains, states, now) {
54
- return drains.map(drain => {
55
- const state = states[drain.repo];
56
- const head = `issue drain ${drain.repo} -> ${drain.session.slice(0, 8)}`;
57
- if (!state?.lastPollAt)
58
- return `${head}: not polled yet`;
59
- const wake = state.lastWakeAt ? `${ago(state.lastWakeAt, now)} (${state.lastWakeCount} issue${state.lastWakeCount === 1 ? "" : "s"})` : "never";
60
- return `${head}: polled ${ago(state.lastPollAt, now)}, ${state.openCount ?? "?"} open, ${state.pending.length} waiting, last wake ${wake}${state.lastError ? `, last error: ${state.lastError}` : ""}`;
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 ?? [])];
61
56
  });
62
57
  }
@@ -0,0 +1,155 @@
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.runCommand = 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 client_1 = require("./client");
44
+ const store_1 = require("./store");
45
+ const wake_runner_state_1 = require("./wake-runner-state");
46
+ /**
47
+ * Wake runners: a command the agent runs on a cadence and delivers the wakes of to Copilot app sessions. The agent knows
48
+ * nothing about what the command watches. Desk's `drains.js poll` is the one that watches GitHub issues; anything that
49
+ * prints the same JSON works.
50
+ *
51
+ * The command prints one JSON value: `{ "wakes": [{ "session", "message", "done" }], "status": ["…"] }`. Each wake's message
52
+ * is sent to its session (`session` is optional when the runner names one). `done` is the argv that reports the wake's
53
+ * delivery: it runs after a successful send, and with `--error <reason>` added after a failed one, so the command can keep
54
+ * the wake pending until it lands. `status` lines show under the app-sessions row of `ouro status`.
55
+ */
56
+ exports.WAKE_RUNNER_DEFAULT_SECONDS = 300;
57
+ exports.WAKE_RUNNER_TIMEOUT_MS = 2 * 60_000;
58
+ const MAX_STATUS_LINES = 20;
59
+ const MAX_LINE = 300;
60
+ const MAX_OUTPUT = 10 * 1024 * 1024;
61
+ /** The command's output as wakes and status lines, or the reason it is not one. */
62
+ function parseWakeOutput(stdout) {
63
+ let parsed;
64
+ try {
65
+ parsed = JSON.parse(stdout);
66
+ }
67
+ catch {
68
+ throw new Error("the command did not print JSON");
69
+ }
70
+ const record = (parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {});
71
+ if (!Array.isArray(record.wakes))
72
+ throw new Error('the command printed no "wakes" array');
73
+ const wakes = record.wakes.map((entry, index) => {
74
+ const wake = (entry && typeof entry === "object" ? entry : {});
75
+ if (typeof wake.message !== "string" || !wake.message.trim())
76
+ throw new Error(`wakes[${index}] has no message`);
77
+ if (wake.session !== undefined && (typeof wake.session !== "string" || !wake.session.trim()))
78
+ throw new Error(`wakes[${index}].session is not a session id`);
79
+ if (wake.done !== undefined && (!Array.isArray(wake.done) || wake.done.length === 0 || wake.done.some(part => typeof part !== "string")))
80
+ throw new Error(`wakes[${index}].done is not an argv`);
81
+ return { message: wake.message, ...(wake.session !== undefined ? { session: wake.session } : {}), ...(wake.done !== undefined ? { done: wake.done } : {}) };
82
+ });
83
+ // eslint-disable-next-line no-control-regex
84
+ const clean = (line) => line.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").trim().slice(0, MAX_LINE);
85
+ const status = Array.isArray(record.status) ? record.status.filter((line) => typeof line === "string").map(clean).filter(Boolean).slice(0, MAX_STATUS_LINES) : [];
86
+ return { wakes, status };
87
+ }
88
+ /** 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. */
89
+ const runCommand = (argv, timeoutMs) => new Promise(resolve => {
90
+ const [program, ...args] = argv;
91
+ (0, node_child_process_1.execFile)(program, args, { encoding: "utf8", timeout: timeoutMs, maxBuffer: MAX_OUTPUT, env: process.env }, (error, stdout, stderr) => {
92
+ if (!error)
93
+ return resolve({ ok: true, stdout, error: null });
94
+ const reason = String(stderr).trim().split("\n")[0] || error.message;
95
+ resolve({ ok: false, stdout, error: `${path.basename(program)} failed: ${reason}`.slice(0, MAX_LINE) });
96
+ });
97
+ });
98
+ exports.runCommand = runCommand;
99
+ const sendWake = (client) => async (session, message) => {
100
+ const result = await (0, client_1.sendToAppSession)(session, message, { ...client, delivery: "enqueue" });
101
+ return { ok: result.ok, error: result.error };
102
+ };
103
+ exports.sendWake = sendWake;
104
+ /** Run one runner's command, deliver its wakes and report each one back. Returns the runner's new state. */
105
+ async function runWakeRunner(runner, deps) {
106
+ const state = { lastRunAt: new Date(deps.now).toISOString() };
107
+ const ran = await deps.run(runner.command, exports.WAKE_RUNNER_TIMEOUT_MS);
108
+ if (!ran.ok)
109
+ return fail(runner, state, ran.error ?? "the command failed");
110
+ let output;
111
+ try {
112
+ output = parseWakeOutput(ran.stdout);
113
+ }
114
+ catch (error) {
115
+ return fail(runner, state, error.message);
116
+ }
117
+ state.status = output.status;
118
+ state.lastWakes = output.wakes.length;
119
+ state.lastDelivered = 0;
120
+ const problems = [];
121
+ for (const wake of output.wakes) {
122
+ const session = wake.session ?? runner.session;
123
+ const sent = session
124
+ ? await deps.send(session, wake.message).catch((error) => ({ ok: false, error: error.message }))
125
+ : { ok: false, error: "the wake names no session and the runner has none" };
126
+ const reason = sent.ok ? null : sent.error ?? "the app refused the message";
127
+ if (!reason)
128
+ state.lastDelivered += 1;
129
+ else
130
+ problems.push(`could not deliver a wake: ${reason}`);
131
+ if (wake.done) {
132
+ const reported = await deps.run(reason === null ? wake.done : [...wake.done, "--error", reason], exports.WAKE_RUNNER_TIMEOUT_MS);
133
+ if (!reported.ok)
134
+ problems.push(`could not report a wake's delivery: ${reported.error ?? "the command failed"}`);
135
+ }
136
+ }
137
+ if (problems.length)
138
+ state.lastError = problems[0];
139
+ (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 } });
140
+ return state;
141
+ }
142
+ function fail(runner, state, reason) {
143
+ state.lastError = reason;
144
+ (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 } });
145
+ return state;
146
+ }
147
+ /** Run the `only` runners of the configured list (all by default) and write the states. A runner dropped from the config loses its state. */
148
+ async function runWakeRunners(agentRoot, runners, deps, only) {
149
+ const stored = (0, wake_runner_state_1.readWakeRunnerStates)(agentRoot);
150
+ const states = Object.fromEntries(runners.map(runner => [runner.name, stored[runner.name] ?? {}]));
151
+ for (const runner of runners)
152
+ if (!only || only.has(runner.name))
153
+ states[runner.name] = await runWakeRunner(runner, deps);
154
+ (0, store_1.writeJson)((0, wake_runner_state_1.wakeRunnerStateFile)(agentRoot), states);
155
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1115",
3
+ "version": "0.1.0-alpha.1116",
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.1115",
9
+ "version": "0.1.0-alpha.1116",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sdk": "^0.78.0",
12
12
  "@ouro.bot/friends": "0.1.0-alpha.18",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1115",
3
+ "version": "0.1.0-alpha.1116",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },
@@ -1,182 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sendWake = exports.connectGithub = exports.DRAIN_LABEL_PREFIX = exports.DRAIN_STATUS_MARKER = exports.ISSUE_POLL_MS = void 0;
4
- exports.wakeMessage = wakeMessage;
5
- exports.pollDrain = pollDrain;
6
- exports.pollIssueDrains = pollIssueDrains;
7
- const node_crypto_1 = require("node:crypto");
8
- const node_child_process_1 = require("node:child_process");
9
- const account_pool_1 = require("../../heart/providers/account-pool");
10
- const runtime_1 = require("../../nerves/runtime");
11
- const client_1 = require("./client");
12
- const issue_drain_state_1 = require("./issue-drain-state");
13
- const store_1 = require("./store");
14
- /**
15
- * Issue drains: Copilot app sessions that work a GitHub repository's issues. A deterministic poll (no model turn)
16
- * lists each repository's open issues and messages the drain's session when one is new or changed since the last
17
- * poll. Events are written to disk before anyone is woken, so a crash or a refused message loses nothing; an
18
- * authentication or network failure is recorded for `ouro status` and leaves every marker where it was.
19
- *
20
- * `updated_at` alone is not a revision: the drain's own label edits and status comment move it too. An issue wakes the
21
- * drain only when something other than the drain changed it since the revision last recorded for that issue.
22
- */
23
- exports.ISSUE_POLL_MS = 5 * 60_000;
24
- /** A drain's own status comment carries this marker, so its creation and edits do not wake the drain again. */
25
- exports.DRAIN_STATUS_MARKER = "<!-- ouro-drain-status -->";
26
- /** The drain moves an issue through labels in this namespace (`drain: triaged`, `drain: in progress`); changing them is not news. */
27
- exports.DRAIN_LABEL_PREFIX = "drain:";
28
- /** A closed issue's record is kept this long, so one that comes back unchanged is not mistaken for a new issue. */
29
- const GONE_MS = 30 * 24 * 3_600_000;
30
- const MAX_TITLES = 20;
31
- const PAGE = 100;
32
- const blank = () => ({ seeded: false, seen: {}, pending: [] });
33
- function oneLine(text) {
34
- const flat = text.replace(/\s+/g, " ").trim();
35
- return flat.length > 120 ? `${flat.slice(0, 119)}…` : flat;
36
- }
37
- function wakeMessage(repo, events) {
38
- const shown = events.slice(0, MAX_TITLES).map(event => `#${event.number} ${oneLine(event.title)}`);
39
- const more = events.length > MAX_TITLES ? `, and ${events.length - MAX_TITLES} more` : "";
40
- return `New or changed issues in ${repo}: ${shown.join(", ")}${more}. Drain them.`;
41
- }
42
- const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
43
- /** The body without its ignored trailer lines (`Active-at: …`), so an edit that touches only those lines leaves the digest alone. */
44
- function bodyWithoutTrailers(body, keys) {
45
- if (keys.length === 0)
46
- return body;
47
- const trailer = new RegExp(`^[ \\t]*(?:${keys.map(escapeRegExp).join("|")})[ \\t]*:.*(?:\\r?\\n|$)`, "gim");
48
- return body.replace(trailer, "").trimEnd();
49
- }
50
- const digestOf = (issue, keys) => (0, node_crypto_1.createHash)("sha1").update(`${issue.title}\n${bodyWithoutTrailers(issue.body ?? "", keys)}`).digest("hex").slice(0, 16);
51
- /** The drain's own status comment: the marker, written by the polling account. Its creation and every edit are skipped. */
52
- const ownStatus = (comment, login) => comment.user?.login?.toLowerCase() === login.toLowerCase() && !!comment.body?.includes(exports.DRAIN_STATUS_MARKER);
53
- /** A reopen, or a change to a label that is neither in the drain's namespace nor on its ignored list. Closes, assignments and mentions are not news. */
54
- const newsEvent = (event, ignoredLabels) => {
55
- if (event.event === "reopened")
56
- return true;
57
- if (event.event !== "labeled" && event.event !== "unlabeled")
58
- return false;
59
- const name = (event.label?.name ?? "").toLowerCase();
60
- return !name.startsWith(exports.DRAIN_LABEL_PREFIX) && !ignoredLabels.includes(name);
61
- };
62
- /** Whether anyone but the drain changed the issue since `before`: a new issue, an edit, another comment, a reopen or a label outside the drain's own. */
63
- async function changedByOthers(api, repo, issue, before, digest, ignored, ignoredLabels) {
64
- if (!before)
65
- return true;
66
- if (before.digest && (before.ignored ?? "") === ignored && before.digest !== digest)
67
- return true;
68
- const since = before.updatedAt;
69
- const comments = (await api.comments(repo, issue.number, since)).filter(comment => comment.updated_at > since);
70
- if (comments.some(comment => !ownStatus(comment, api.login)))
71
- return true;
72
- const events = (await api.issueEvents(repo, issue.number)).filter(event => event.created_at > since);
73
- return events.some(event => newsEvent(event, ignoredLabels));
74
- }
75
- /** Poll one drain's repository, record what changed, then wake its session once with the whole batch. */
76
- async function pollDrain(drain, states, save, deps) {
77
- const state = states[drain.repo] ?? (states[drain.repo] = blank());
78
- const at = new Date(deps.now).toISOString();
79
- try {
80
- const api = await deps.connect(drain.account);
81
- const issues = await api.openIssues(drain.repo);
82
- const trailers = drain.ignoredBodyTrailers ?? [];
83
- const ignored = trailers.join(",");
84
- const labels = (drain.ignoredLabels ?? []).map(name => name.toLowerCase());
85
- const seen = {};
86
- const recorded = [];
87
- for (const issue of issues) {
88
- const key = String(issue.number);
89
- const before = (0, issue_drain_state_1.seenIssue)(state.seen[key]);
90
- const digest = digestOf(issue, trailers);
91
- seen[key] = { updatedAt: issue.updated_at, digest, ...(ignored ? { ignored } : {}) };
92
- if (!state.seeded || before?.updatedAt === issue.updated_at)
93
- continue;
94
- if (await changedByOthers(api, drain.repo, issue, before, digest, ignored, labels))
95
- recorded.push({ number: issue.number, title: issue.title, updatedAt: issue.updated_at });
96
- }
97
- for (const [key, entry] of Object.entries(state.seen)) {
98
- const gone = (0, issue_drain_state_1.seenIssue)(entry);
99
- const goneAt = gone.goneAt ?? deps.now;
100
- if (!(key in seen) && deps.now - goneAt < GONE_MS)
101
- seen[key] = { ...gone, goneAt };
102
- }
103
- const open = new Set(issues.map(issue => issue.number));
104
- const numbers = new Set(recorded.map(event => event.number));
105
- state.pending = [...state.pending.filter(event => open.has(event.number) && !numbers.has(event.number)), ...recorded];
106
- state.seen = seen;
107
- state.seeded = true;
108
- state.openCount = issues.length;
109
- delete state.lastError;
110
- }
111
- catch (error) {
112
- state.lastError = error.message;
113
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.issue_drain_poll_error", message: "could not poll a repository's issues; markers stay where they were", meta: { repo: drain.repo, error: state.lastError } });
114
- }
115
- state.lastPollAt = at;
116
- save();
117
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.issue_drain_poll", message: "polled a repository's issues for its drain", meta: { repo: drain.repo, open: state.openCount ?? null, waiting: state.pending.length, ok: !state.lastError } });
118
- if (state.pending.length === 0)
119
- return;
120
- const events = state.pending;
121
- const sent = await deps.send(drain.session, wakeMessage(drain.repo, events)).catch((error) => ({ ok: false, error: error.message }));
122
- if (sent.ok) {
123
- state.pending = [];
124
- state.lastWakeAt = new Date(deps.now).toISOString();
125
- state.lastWakeCount = events.length;
126
- }
127
- else {
128
- state.lastError = `could not wake the drain: ${sent.error ?? "the app refused the message"}`;
129
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.issue_drain_wake_error", message: "could not message an issue drain; its events wait on disk", meta: { repo: drain.repo, session: drain.session, error: state.lastError } });
130
- }
131
- save();
132
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.issue_drain_wake", message: "messaged an issue drain about new or changed issues", meta: { repo: drain.repo, session: drain.session, issues: events.length, ok: sent.ok } });
133
- }
134
- /** Poll every configured drain once. Repositories dropped from the config lose their state. */
135
- async function pollIssueDrains(agentRoot, drains, deps) {
136
- const stored = (0, issue_drain_state_1.readDrainStates)(agentRoot);
137
- const states = Object.fromEntries(drains.map(drain => [drain.repo, stored[drain.repo] ?? blank()]));
138
- const save = () => (0, store_1.writeJson)((0, issue_drain_state_1.drainStateFile)(agentRoot), states);
139
- for (const drain of drains)
140
- await pollDrain(drain, states, save, deps);
141
- save();
142
- }
143
- /** The drain's GitHub access: its account's token from the `gh` CLI, then the REST API. */
144
- const connectGithub = async (account) => {
145
- const tokenArgs = ["auth", "token", "--hostname", "github.com", ...(account ? ["--user", account] : [])];
146
- const result = (0, node_child_process_1.spawnSync)("gh", tokenArgs, { encoding: "utf8", timeout: 10_000, env: (0, account_pool_1.cleanGhEnv)() });
147
- const token = result.status === 0 ? String(result.stdout ?? "").trim() : "";
148
- if (!token)
149
- throw new Error(`the GitHub CLI has no token for ${account ?? "its active account"} (run \`gh auth login --hostname github.com\`)`);
150
- const get = async (route) => {
151
- const response = await fetch(`https://api.github.com${route}`, {
152
- headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "ouro-issue-drains" },
153
- signal: AbortSignal.timeout(30_000),
154
- });
155
- if (!response.ok)
156
- throw new Error(`GitHub answered HTTP ${response.status} for ${route.split("?")[0]}`);
157
- return { body: await response.json(), next: /rel="next"/.test(response.headers.get("link") ?? "") };
158
- };
159
- const all = async (route) => {
160
- const items = [];
161
- const join = route.includes("?") ? "&" : "?";
162
- for (let page = 1;; page++) {
163
- const { body, next } = await get(`${route}${join}per_page=${PAGE}&page=${page}`);
164
- items.push(...body);
165
- if (!next)
166
- return items;
167
- }
168
- };
169
- const login = account ?? String((await get("/user")).body.login ?? "");
170
- return {
171
- login,
172
- openIssues: async (repo) => (await all(`/repos/${repo}/issues?state=open&sort=updated&direction=desc`)).filter(issue => !issue.pull_request),
173
- comments: (repo, issue, since) => all(`/repos/${repo}/issues/${issue}/comments?since=${encodeURIComponent(since)}`),
174
- issueEvents: (repo, issue) => all(`/repos/${repo}/issues/${issue}/events`),
175
- };
176
- };
177
- exports.connectGithub = connectGithub;
178
- const sendWake = (client) => async (session, message) => {
179
- const result = await (0, client_1.sendToAppSession)(session, message, { ...client, delivery: "enqueue" });
180
- return { ok: result.ok, error: result.error };
181
- };
182
- exports.sendWake = sendWake;