@ouro.bot/cli 0.1.0-alpha.1175 → 0.1.0-alpha.1176

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,13 @@
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.1176",
6
+ "changes": [
7
+ "The app-sessions sense reads the app through Shepherd's `shepherd` CLI: the sidebar from `shepherd sessions --json` and a watched session's replies from `shepherd messages --json`. It no longer opens the app's socket, reads its database or its event logs for the sidebar, watches or questions. A watch's cursor is the time it was sent to; a reply is an assistant message after it. Shepherd's messages carry no tool requests, so a message that narrates before a tool call counts as a reply. The prompt listener (prompts.ts) and its pending-request store are removed: Shepherd's resident watch hears questions and plans. The digest's task cards still read the session's event log, until Shepherd exposes tool calls.",
8
+ "Each read of the app's sessions through Shepherd emits a nerves event (`senses.app_sessions_rows`) with its row count."
9
+ ]
10
+ },
4
11
  {
5
12
  "version": "0.1.0-alpha.1175",
6
13
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1175",
2
+ "runtimeVersion": "0.1.0-alpha.1176",
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.1175</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1176</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -103,14 +103,14 @@ exports.listSessionsAndChatsTool = define("list_sessions_and_chats", "Every open
103
103
  exports.getSessionsStatusTool = define("get_sessions_status", "What every session is doing now, with counts: busy, idle, stuck, blocked, and what each blocked one waits on. awaiting_input carries the request_id and the question that answer_session_input or respond_to_session_plan_v2 needs. Read-only.", { state: { type: "string", enum: ["busy", "idle", "waiting", "stuck"], description: "Only sessions in this state." } }, [], READ, args => (0, shepherd_cli_1.shepherd)(["sessions", ...(typeof args.state === "string" ? ["--state", args.state] : [])]), ["state"]);
104
104
  exports.getSessionTool = define("get_session", "One session's details and what it is doing now, including what it waits on (awaiting_input). Read-only.", { session_id: session }, ["session_id"], READ, args => (0, shepherd_cli_1.shepherd)(["session", sessionId(args)]), ["session_id"]);
105
105
  exports.sendSessionMessageTool = define("send_session_message", "Send a message into a session, as its message box does; waits up to 2 minutes for the app to accept it (a session that is not loaded loads first). The app takes it for the person's, so say who you are in it. immediate (default) is admitted at the session's next turn boundary; enqueue waits behind its work.", { session_id: session, message: { type: "string", description: "What to send." }, delivery_mode: { type: "string", enum: ["immediate", "enqueue"] }, notify_on_idle: notifyOnIdle }, ["session_id", "message"], write("sends a message into another agent session in the owner's Copilot app"), async (args, agentRoot) => {
106
- // The session is resolved and its log measured before the send, so the watch starts where the reply will follow.
106
+ // The session is resolved and the send time taken before the send, so the watch's cursor sits before any reply to it.
107
107
  const row = await (0, shepherd_cli_1.shepherd)(["session", sessionId(args)]);
108
108
  const id = String(row.id);
109
109
  const mode = watchMode(args.notify_on_idle);
110
- const offset = (0, client_1.eventLogSize)(id);
110
+ const sentAt = new Date().toISOString();
111
111
  const sent = await (0, shepherd_cli_1.shepherd)(["send", id], bodyOf(args, "session_id", "notify_on_idle"));
112
112
  if (mode !== null)
113
- (0, store_1.watchSession)(agentRoot, id, String(row.name), offset, Date.now(), mode === "once");
113
+ (0, store_1.watchSession)(agentRoot, id, String(row.name), sentAt, Date.now(), mode === "once");
114
114
  return { ...sent, watching: mode !== null };
115
115
  }, ["session_id"]);
116
116
  exports.createSessionTool = define("create_session", "Start a session. With project_id (a project's id or name): a project session in its own worktree (workspace_type branch uses the project's checkout instead), kicked off with kickoff.prompt and allow-all permissions unless kickoff.permission_mode says otherwise. Without it: a standalone chat. Waits for the session to exist (a worktree takes about two minutes). It has no coordinator: the app does not let an outside client be one. You may archive what you create.", {
@@ -129,9 +129,9 @@ exports.createSessionTool = define("create_session", "Start a session. With proj
129
129
  const mode = watchMode(args.notify_on_idle);
130
130
  const kickoff = (args.kickoff && typeof args.kickoff === "object" ? args.kickoff : {});
131
131
  const prompted = Boolean(kickoff.prompt);
132
- // A new session's log starts empty, so its first reply is read from offset 0.
132
+ // A new session has no replies before this, so its first one is read from the time it was made.
133
133
  if (prompted && mode !== null)
134
- (0, store_1.watchSession)(agentRoot, String(created.session_id), typeof args.name === "string" ? args.name : null, 0, Date.now(), mode === "once");
134
+ (0, store_1.watchSession)(agentRoot, String(created.session_id), typeof args.name === "string" ? args.name : null, new Date().toISOString(), Date.now(), mode === "once");
135
135
  return prompted ? { ...created, watching: mode !== null } : created;
136
136
  }, ["name"]);
137
137
  exports.answerSessionInputTool = define("answer_session_input", "Answer the question a session asked with ask_user and is blocked on. get_session shows it (awaiting_input.question, choices). A choice or free text. A question asked while this agent was not connected has no request id and cannot be answered here.", { session_id: session, answer: { type: "string" } }, ["session_id", "answer"], write("answers a question for the person in another agent session"), args => (0, shepherd_cli_1.shepherd)(["answer", sessionId(args)], bodyOf(args, "session_id")), ["session_id"]);
@@ -32,27 +32,11 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
35
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.realRunFile = exports.appUrl = exports.HUNG_MS = exports.HOUSESITTER_ENV = exports.SEND_WAIT_MS = void 0;
40
- exports.defaultStateDir = defaultStateDir;
41
- exports.copilotAppUrl = copilotAppUrl;
36
+ exports.realRunFile = exports.appUrl = exports.HOUSESITTER_ENV = void 0;
37
+ exports.snapshot = snapshot;
42
38
  exports.assertSessionId = assertSessionId;
43
39
  exports.eventLogPath = eventLogPath;
44
- exports.readEventLog = readEventLog;
45
- exports.parseEventLines = parseEventLines;
46
- exports.describePermission = describePermission;
47
- exports.tailFacts = tailFacts;
48
- exports.classify = classify;
49
- exports.listAppSessions = listAppSessions;
50
- exports.snapshot = snapshot;
51
- exports.readNewAppEvents = readNewAppEvents;
52
- exports.messagesIn = messagesIn;
53
- exports.eventLogSize = eventLogSize;
54
- exports.exchange = exchange;
55
- exports.appRunning = appRunning;
56
40
  exports.findHousesitter = findHousesitter;
57
41
  exports.restartEnqueue = restartEnqueue;
58
42
  exports.restartStatus = restartStatus;
@@ -60,455 +44,34 @@ const fs = __importStar(require("node:fs"));
60
44
  const os = __importStar(require("node:os"));
61
45
  const path = __importStar(require("node:path"));
62
46
  const node_child_process_1 = require("node:child_process");
63
- const ws_1 = __importDefault(require("ws"));
64
47
  const runtime_1 = require("../../nerves/runtime");
65
- /** The most a send waits: a session whose runtime is not in memory loads first, often for more than 20 s. */
66
- exports.SEND_WAIT_MS = 120_000;
67
48
  /** Names the Housesitter command to run: the path of its `bin/housesitter.mjs`, or of an executable. */
68
49
  exports.HOUSESITTER_ENV = "HOUSESITTER_BIN";
69
- const REQUEST_WAIT_MS = 30_000;
70
50
  const HOUSESITTER_WAIT_MS = 30_000;
71
- const STATUS_TAIL_BYTES = 512 * 1024;
72
- const EVENT_CHUNK_BYTES = 256 * 1024;
73
- const MAX_EVENT_BYTES = 8 * 1024 * 1024;
74
- const MESSAGE_MAX_CHARS = 4_000;
75
- /** A cut loop this fresh may just be a turn the database has not marked running yet. */
76
- const STUCK_GRACE_MS = 120_000;
77
- /** A session the app says is running whose history, sub-agents included, has not grown for this long is hung. */
78
- exports.HUNG_MS = 30 * 60_000;
79
51
  const SESSION_ID = /^[A-Za-z0-9-]+$/;
80
- const ASK_TOOLS = new Set(["ask_user", "ask_followup_question", "request_user_input"]);
81
- const PLAN_TOOLS = new Set(["exit_plan_mode"]);
82
- const LOOP = new Set([
83
- "user.message", "assistant.turn_start", "assistant.message", "assistant.turn_end", "abort", "session.task_complete",
84
- "tool.execution_start", "tool.execution_complete", "subagent.started", "subagent.completed",
85
- ]);
86
- function defaultStateDir() {
87
- return path.join(os.homedir(), ".copilot");
88
- }
89
- function processAlive(pid) {
90
- try {
91
- process.kill(pid, 0);
92
- return true;
93
- }
94
- catch (error) {
95
- return error.code === "EPERM";
96
- }
97
- }
98
- /**
99
- * The app's current server address. Every app build (release, dev, PR) writes `ws.port` and
100
- * `ws.token`; the release app also writes `ws.release.*`, so those win. The port file holds
101
- * `<port>\n<pid>`, and a file whose app has exited is skipped.
102
- */
103
- function copilotAppUrl(stateDir, alive = processAlive) {
104
- const run = path.join(stateDir, "run");
105
- for (const prefix of ["ws.release", "ws"]) {
106
- let port, pid, token;
107
- try {
108
- ;
109
- [port, pid] = fs.readFileSync(path.join(run, `${prefix}.port`), "utf-8").split(/\r?\n/).map(line => line.trim());
110
- token = fs.readFileSync(path.join(run, `${prefix}.token`), "utf-8").split(/\r?\n/)[0].trim();
111
- }
112
- catch {
113
- continue;
114
- }
115
- if (!/^\d+$/.test(port) || !token)
116
- continue;
117
- if (pid && /^\d+$/.test(pid) && !alive(Number(pid)))
118
- continue;
119
- return `ws://127.0.0.1:${port}?token=${encodeURIComponent(token)}&observer=1`;
120
- }
121
- throw new Error(`the GitHub Copilot app is not running (no live server files in ${run})`);
122
- }
123
- function stateDirOf(options) {
124
- return options.stateDir ?? defaultStateDir();
125
- }
126
- function isRecord(value) {
127
- return !!value && typeof value === "object" && !Array.isArray(value);
128
- }
129
- function str(value) {
130
- return typeof value === "string" && value.length > 0 ? value : null;
131
- }
132
- function assertSessionId(id) {
133
- if (!SESSION_ID.test(id))
134
- throw new Error(`'${id}' is not a Copilot app session id`);
135
- return id;
136
- }
137
- // ---------- the session's event log ----------
138
- function eventLogPath(id, options = {}) {
139
- return path.join(stateDirOf(options), "session-state", assertSessionId(id), "events.jsonl");
140
- }
141
- /** `length` bytes of the session's event log ending at `end` (default: its end), as text. */
142
- function readEventLog(id, options) {
143
- let fd;
144
- try {
145
- fd = fs.openSync(eventLogPath(id, options), "r");
146
- }
147
- catch {
148
- return { text: "", start: 0, end: 0 };
149
- }
150
- try {
151
- const size = fs.fstatSync(fd).size;
152
- const start = Math.max(options.from ?? 0, size - options.maxBytes, 0);
153
- const buffer = Buffer.alloc(Math.max(0, size - start));
154
- fs.readSync(fd, buffer, 0, buffer.length, start);
155
- return { text: buffer.toString("utf-8"), start, end: size };
156
- }
157
- finally {
158
- fs.closeSync(fd);
159
- }
160
- }
161
- function parseEventLines(text) {
162
- const events = [];
163
- for (const line of text.split("\n")) {
164
- if (!line.startsWith("{"))
165
- continue;
166
- try {
167
- const event = JSON.parse(line);
168
- if (isRecord(event))
169
- events.push(event);
170
- }
171
- catch {
172
- // A line cut by the tail window is not an event.
173
- }
174
- }
175
- return events;
176
- }
177
- function tailEvents(stateDir, id, bytes) {
178
- return parseEventLines(readEventLog(id, { stateDir, maxBytes: bytes }).text);
179
- }
180
- const PERMISSION_WHAT = {
181
- shell: "run a shell command",
182
- write: "change a file",
183
- read: "read a file",
184
- url: "open a web address",
185
- mcp: "use a connected tool",
186
- "custom-tool": "use a custom tool",
187
- "extension-management": "change an extension",
188
- };
189
- /** The request in a few plain words. A command's text stays out: it can carry secrets. */
190
- function describePermission(request) {
191
- const record = isRecord(request) ? request : {};
192
- const kind = str(record.kind);
193
- if (kind === "extension-permission-access") {
194
- const capabilities = Array.isArray(record.capabilities) ? record.capabilities.filter((item) => typeof item === "string").join(", ") : "";
195
- return `let the extension ${str(record.extensionName) ?? "(unnamed)"} ${capabilities || "ask for access"}`;
196
- }
197
- const what = (kind && PERMISSION_WHAT[kind]) || (kind ? `a ${kind} permission` : "a permission");
198
- const intention = str(record.intention);
199
- return intention ? `${what} (${intention})` : what;
200
- }
201
- /** What the session's own history says about its agent loop. Sub-agent events are their parent's business. */
202
- function tailFacts(events) {
203
- const tools = new Map();
204
- const permissions = new Map();
205
- let last = null;
206
- let lastActivity = null;
207
- let askedTools = false;
208
- let finished = false;
209
- for (const event of events) {
210
- if (event.agentId !== undefined)
211
- continue;
212
- const type = str(event.type) ?? "";
213
- const data = isRecord(event.data) ? event.data : {};
214
- if (type === "session.shutdown" || type === "session.resume" || type === "session.start") {
215
- tools.clear();
216
- permissions.clear();
217
- }
218
- if (type === "tool.execution_start" && str(data.toolCallId))
219
- tools.set(data.toolCallId, str(data.toolName) ?? "");
220
- if (type === "tool.execution_complete" && str(data.toolCallId))
221
- tools.delete(data.toolCallId);
222
- if (type === "permission.requested" && str(data.requestId) && data.resolvedByHook !== true)
223
- permissions.set(data.requestId, { requestId: data.requestId, what: describePermission(data.permissionRequest), at: str(event.timestamp) });
224
- if (type === "permission.completed" && str(data.requestId))
225
- permissions.delete(data.requestId);
226
- if (!LOOP.has(type))
227
- continue;
228
- // Only a person's stop counts; a runtime shutdown cancels sub-agents with other reasons.
229
- if (type === "abort" && str(data.reason) && data.reason !== "user_initiated")
230
- continue;
231
- if (type === "assistant.message") {
232
- askedTools = Array.isArray(data.toolRequests) && data.toolRequests.length > 0;
233
- finished = false;
234
- }
235
- if (type === "session.task_complete")
236
- finished = true;
237
- if (type === "user.message") {
238
- askedTools = false;
239
- finished = false;
240
- }
241
- last = type;
242
- lastActivity = str(event.timestamp) ?? lastActivity;
243
- }
244
- const pending = [...tools.values()].map(name => name.replace(/^[\w-]+?-(?=ask_|exit_)/, ""));
245
- const awaiting = pending.some(name => ASK_TOOLS.has(name)) ? "input" : pending.some(name => PLAN_TOOLS.has(name)) ? "plan" : permissions.size > 0 ? "permission" : null;
246
- let loopCut = false;
247
- let detail = "no agent activity";
248
- if (last === "abort")
249
- detail = "stopped by the person";
250
- else if (last === "session.task_complete" || (last === "assistant.turn_end" && finished))
251
- detail = "task complete";
252
- else if (last === "assistant.turn_end") {
253
- loopCut = askedTools;
254
- detail = askedTools ? "between turns (its last turn called tools and no next turn started)" : "its turn ended";
255
- }
256
- else if (last) {
257
- loopCut = true;
258
- detail = `mid-turn (last ${last})`;
259
- }
260
- const prompt = permissions.values().next().value;
261
- return { awaiting, loopCut, detail, lastActivity, ...(prompt ? { prompt } : {}) };
262
- }
263
- const factsCache = new Map();
264
- /** The tail facts and when the log was last written, re-read only when the log changed, so a periodic snapshot stays cheap. */
265
- function cachedTailFacts(stateDir, id) {
266
- const file = eventLogPath(id, { stateDir });
267
- let key = "missing";
268
- let writtenAtMs = null;
269
- try {
270
- const stat = fs.statSync(file);
271
- key = `${stat.size}:${stat.mtimeMs}`;
272
- writtenAtMs = stat.mtimeMs;
273
- }
274
- catch {
275
- // No log yet: the facts of an empty history.
276
- }
277
- const cached = factsCache.get(file);
278
- if (cached?.key === key)
279
- return cached;
280
- const entry = { key, facts: tailFacts(tailEvents(stateDir, id, STATUS_TAIL_BYTES)), writtenAtMs };
281
- factsCache.set(file, entry);
282
- return entry;
283
- }
284
- function classify(isRunning, facts, nowMs, writtenAtMs = null) {
285
- if (facts.awaiting === "permission")
286
- return { state: "waiting", detail: "waiting for a permission answer" };
287
- if (facts.awaiting)
288
- return { state: "waiting", detail: `waiting for the person's ${facts.awaiting === "plan" ? "plan approval" : "answer"}` };
289
- if (isRunning) {
290
- if (writtenAtMs !== null && nowMs - writtenAtMs >= exports.HUNG_MS)
291
- return { state: "stuck", detail: `the app says it is running, but its history has not grown for ${Math.round((nowMs - writtenAtMs) / 60_000)} min` };
292
- return { state: "working", detail: "the app says it is running" };
293
- }
294
- if (facts.loopCut) {
295
- const at = Date.parse(facts.lastActivity ?? "");
296
- if (!Number.isNaN(at) && nowMs - at < STUCK_GRACE_MS)
297
- return { state: "working", detail: `starting up (${facts.detail})` };
298
- return { state: "stuck", detail: `not running, but its loop stopped ${facts.detail}` };
299
- }
300
- return { state: "idle", detail: facts.detail };
301
- }
302
- const arr = (value) => (Array.isArray(value) ? value.filter(isRecord) : []);
303
- /** The sidebar as the app itself lists it: its workspace sessions and its chats, in one exchange. */
304
- async function sidebarItems(options) {
305
- const got = await exchange([{ type: "list_workspaces" }, { type: "list_general_chat_sessions" }], {
306
- keep: (frame) => /^(workspace_list|general_chat_sessions_list|socket_error)$/.test(String(frame.type)),
307
- done: (_frame, all) => all.some(frame => frame.type === "workspace_list") && all.some(frame => frame.type === "general_chat_sessions_list") || all.some(frame => frame.type === "socket_error"),
308
- waitMs: REQUEST_WAIT_MS,
309
- }, options);
310
- const workspaces = got.find(frame => frame.type === "workspace_list");
311
- const chats = got.find(frame => frame.type === "general_chat_sessions_list");
312
- if (!workspaces || !chats)
313
- throw new Error(str(got.find(frame => frame.type === "socket_error")?.message) ?? "the Copilot app did not list its sessions in time");
314
- return { workspaces: arr(workspaces.workspaces), chats: arr(chats.sessions) };
315
- }
316
- /** Every session in this Mac's Copilot app sidebar, with what it is doing now. */
317
- async function listAppSessions(options = {}) {
318
- const stateDir = stateDirOf(options);
319
- const now = (options.now ?? Date.now)();
320
- const { workspaces, chats } = await sidebarItems(options);
321
- const rows = [];
322
- const add = (id, row, isRunning) => {
323
- if (!id || !SESSION_ID.test(id) || rows.some(known => known.id === id))
324
- return;
325
- const { facts, writtenAtMs } = cachedTailFacts(stateDir, id);
326
- const { state, detail } = classify(isRunning, facts, now, writtenAtMs);
327
- rows.push({
328
- id, ...row, state, detail, lastActivity: facts.lastActivity ?? row.updatedAt,
329
- ...(facts.awaiting ? { awaiting: facts.awaiting } : {}),
330
- ...(facts.prompt ? { prompt: facts.prompt } : {}),
331
- });
332
- };
333
- for (const workspace of workspaces) {
334
- if (workspace.archivedAt)
335
- continue;
336
- const session = isRecord(workspace.session) ? workspace.session : {};
337
- const binding = arr(workspace.checkoutBindings)[0];
338
- const openPr = arr(workspace.repoContexts).map(context => isRecord(context.createdPullRequest) ? context.createdPullRequest : null).find(pr => pr && !/^(merged|closed)$/i.test(str(pr.state) ?? ""));
339
- add(str(session.sessionId) ?? str(workspace.activeSessionId), {
340
- name: str(workspace.name) ?? str(session.title) ?? "(unnamed)", kind: "workspace", workspaceId: str(workspace.id), workspaceType: str(workspace.workspaceType),
341
- project: str(workspace.projectName), projectId: str(workspace.projectId), projectRepo: str(binding?.repoFullName), branch: str(workspace.branch), path: str(workspace.displayPath),
342
- creatorSessionId: str(workspace.creatorSessionId), coordinatingCreatorSessionId: str(workspace.coordinatingCreatorSessionId), parentSessionId: null,
343
- isRunning: session.isRunning === true, wasInterrupted: session.wasInterrupted === true,
344
- remote: (str(workspace.hostId) ?? "local") !== "local" || (str(session.executionLocation) ?? "local") !== "local",
345
- createdAt: str(workspace.createdAt), updatedAt: str(session.updatedAt) ?? str(workspace.updatedAt),
346
- ...(openPr ? { openPullRequest: str(openPr.htmlUrl) ?? `#${String(openPr.number)}` } : {}),
347
- ...(session.sessionAutomation || workspace.agentMergeEnabled === true ? { automation: true } : {}),
348
- }, session.isRunning === true);
349
- }
350
- for (const chat of chats) {
351
- if (chat.archivedAt)
352
- continue;
353
- add(str(chat.id), {
354
- name: str(chat.title) ?? "(unnamed chat)", kind: "chat", workspaceId: null, workspaceType: null, project: null, projectId: null, projectRepo: null, branch: null, path: null,
355
- creatorSessionId: null, coordinatingCreatorSessionId: str(chat.coordinatingCreatorSessionId), parentSessionId: str(chat.parentSessionId),
356
- isRunning: chat.isRunning === true, wasInterrupted: chat.wasInterrupted === true, remote: (str(chat.executionLocation) ?? "local") !== "local",
357
- createdAt: str(chat.createdAt), updatedAt: str(chat.updatedAt),
358
- }, chat.isRunning === true);
359
- }
360
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_listed", message: "listed the Copilot app's sessions", meta: { sessions: rows.length } });
361
- return rows;
362
- }
363
- /** Counts by state and every session's id, name and state: the cheap picture a sense or a fleet view carries. */
364
- function snapshot(options, rows) {
52
+ /** The app's sessions as the sidebar lists them, counted by state, with each one's id, name and state. */
53
+ function snapshot(rows, now) {
365
54
  const counts = { working: 0, idle: 0, waiting: 0, stuck: 0 };
366
55
  for (const row of rows)
367
56
  counts[row.state] += 1;
368
57
  return {
369
- at: new Date((options.now ?? Date.now)()).toISOString(),
370
- appRunning: appRunning(options),
58
+ at: new Date(now).toISOString(),
59
+ appRunning: true,
371
60
  counts,
372
61
  sessions: rows.map(row => ({ id: row.id, name: row.name, state: row.state })),
373
62
  };
374
63
  }
375
- function openEventLog(id, options) {
376
- try {
377
- return fs.openSync(eventLogPath(id, options), "r");
378
- }
379
- catch (error) {
380
- if (error.code === "ENOENT")
381
- return null;
382
- throw error;
383
- }
384
- }
385
64
  /** The link that opens a session in the app. */
386
65
  const appUrl = (id) => `ghapp://sessions/${id}`;
387
66
  exports.appUrl = appUrl;
388
- /** Read forward from a watch cursor; stop at a complete event after the budget, never jump to the newest tail. */
389
- function readNewAppEvents(id, from, maxBytes, visit, options = {}) {
390
- const fd = openEventLog(id, options);
391
- if (fd === null)
392
- return { offset: 0, logBytes: 0, skippedEvents: 0 };
393
- try {
394
- const logBytes = fs.fstatSync(fd).size;
395
- const result = { offset: Math.min(from, logBytes), logBytes, skippedEvents: 0 };
396
- let position = result.offset;
397
- let carry = Buffer.alloc(0);
398
- let dropping = false;
399
- while (position < logBytes) {
400
- const chunk = Buffer.alloc(Math.min(EVENT_CHUNK_BYTES, logBytes - position));
401
- fs.readSync(fd, chunk, 0, chunk.length, position);
402
- const buffer = Buffer.concat([carry, chunk]);
403
- const start = position - carry.length;
404
- position += chunk.length;
405
- let lineStart = 0;
406
- for (let at = buffer.indexOf(10); at >= 0; at = buffer.indexOf(10, lineStart)) {
407
- const line = buffer.subarray(lineStart, at);
408
- if (dropping || line.length > MAX_EVENT_BYTES)
409
- result.skippedEvents += 1;
410
- else if (line.length) {
411
- const events = parseEventLines(line.toString("utf-8"));
412
- if (!events.length)
413
- result.skippedEvents += 1;
414
- for (const event of events)
415
- visit(event);
416
- }
417
- dropping = false;
418
- result.offset = start + at + 1;
419
- lineStart = at + 1;
420
- if (result.offset - from >= maxBytes)
421
- return result;
422
- }
423
- carry = buffer.subarray(lineStart);
424
- if (dropping || carry.length > MAX_EVENT_BYTES) {
425
- dropping = true;
426
- carry = Buffer.alloc(0);
427
- }
428
- }
429
- return result;
430
- }
431
- finally {
432
- fs.closeSync(fd);
433
- }
434
- }
435
- /** The top-level user and assistant messages among `events`. */
436
- function messagesIn(events) {
437
- const messages = [];
438
- for (const event of events) {
439
- if (event.agentId !== undefined)
440
- continue;
441
- const data = isRecord(event.data) ? event.data : {};
442
- const text = typeof data.content === "string" ? data.content : "";
443
- if ((event.type === "user.message" || event.type === "assistant.message") && text.trim()) {
444
- messages.push({ at: str(event.timestamp), role: event.type === "user.message" ? "user" : "assistant", text: text.slice(0, MESSAGE_MAX_CHARS), ...(text.length > MESSAGE_MAX_CHARS ? { truncated: true } : {}) });
445
- }
446
- }
447
- return messages;
448
- }
449
- /** The size of the session's event log now: where a reply to a message sent now will start. */
450
- function eventLogSize(id, options = {}) {
451
- try {
452
- return fs.statSync(eventLogPath(id, options)).size;
453
- }
454
- catch {
455
- return 0;
456
- }
457
- }
458
- /**
459
- * Send requests on one connection and collect the replies `keep` accepts until `done` says so or the wait runs out.
460
- * A socket error ends the exchange with a `socket_error` frame; the app not running throws.
461
- */
462
- function exchange(frames, exchangeOptions, options = {}) {
463
- const url = copilotAppUrl(stateDirOf(options));
464
- const openSocket = options.openSocket ?? ((target) => new ws_1.default(target));
465
- const keep = exchangeOptions.keep ?? (() => true);
466
- const done = exchangeOptions.done ?? (() => false);
467
- return new Promise((resolve) => {
468
- const got = [];
469
- let finished = false;
470
- const socket = openSocket(url);
471
- const finish = () => {
472
- if (finished)
473
- return;
474
- finished = true;
475
- clearTimeout(timer);
476
- socket.close();
477
- resolve(got);
478
- };
479
- const timer = setTimeout(finish, exchangeOptions.waitMs);
480
- socket.on("open", () => { for (const frame of frames)
481
- socket.send(JSON.stringify(frame)); });
482
- socket.on("message", (data) => {
483
- let frame;
484
- try {
485
- frame = JSON.parse(String(data));
486
- }
487
- catch {
488
- return;
489
- }
490
- if (!isRecord(frame) || !keep(frame))
491
- return;
492
- got.push(frame);
493
- if (done(frame, got))
494
- finish();
495
- });
496
- socket.on("error", (error) => {
497
- got.push({ type: "socket_error", message: error.message });
498
- finish();
499
- });
500
- socket.on("close", finish);
501
- });
67
+ function assertSessionId(id) {
68
+ if (!SESSION_ID.test(id))
69
+ throw new Error(`'${id}' is not a Copilot app session id`);
70
+ return id;
502
71
  }
503
- /** Whether the app is up: its server files name a live process. */
504
- function appRunning(options = {}) {
505
- try {
506
- copilotAppUrl(stateDirOf(options));
507
- return true;
508
- }
509
- catch {
510
- return false;
511
- }
72
+ /** A session's event log in the app's state folder; the digest reads a task declaration from it (see `digest-cards.ts`). */
73
+ function eventLogPath(id, options = {}) {
74
+ return path.join(options.stateDir ?? path.join(os.homedir(), ".copilot"), "session-state", assertSessionId(id), "events.jsonl");
512
75
  }
513
76
  // ---------- restarting the app (Housesitter) ----------
514
77
  const realRunFile = (file, args, timeoutMs) => new Promise((resolve) => {
@@ -51,36 +51,29 @@ const os = __importStar(require("node:os"));
51
51
  const digest_1 = require("./digest");
52
52
  const digest_push_1 = require("./digest-push");
53
53
  const client_1 = require("./client");
54
- const prompts_1 = require("./prompts");
54
+ const shepherd_rows_1 = require("./shepherd-rows");
55
55
  const store_1 = require("./store");
56
56
  const waiting_prompts_1 = require("./waiting-prompts");
57
57
  const run_command_1 = require("./run-command");
58
58
  /**
59
- * The app-sessions perception loop. Every minute it snapshots the app's sessions (counts and stuck ids) into the
60
- * agent's state for its prompt and health. Every ten seconds it reads the new part of each watched session's log
61
- * (a session the agent wrote to), and a finished reply there comes to the agent as an inbound message on its
62
- * private runtime, the way Shepherd's returns do, so a conversation with another session works both ways.
59
+ * The app-sessions perception loop. Shepherd reads the app: every minute the sense takes the app's sessions from
60
+ * `shepherd sessions` into the agent's state for its prompt and health. Every ten seconds it reads the recent messages of
61
+ * each session the agent watches (`shepherd messages`), and a finished reply there comes to the agent as an inbound
62
+ * message on its private runtime, the way Shepherd's returns do, so a conversation with another session works both ways.
63
63
  */
64
64
  exports.SNAPSHOT_MS = 60_000;
65
65
  exports.WATCH_POLL_MS = 10_000;
66
66
  exports.APP_SESSIONS_WAKE_TRIGGER = "app-sessions";
67
- const REPLY_SCAN_BYTES = 4 * 1024 * 1024;
67
+ /** The messages a watch pass reads: a session's replies between two passes, ten seconds apart, are far fewer. */
68
+ const REPLY_COUNT = 50;
68
69
  const INBOUND_TTL_MS = 24 * 3_600_000;
69
- /** The replies the session finished since `entry.offset`, and the offset to continue from. */
70
- function newReplies(id, entry, client = {}) {
71
- const replies = [];
72
- const read = (0, client_1.readNewAppEvents)(id, entry.offset, REPLY_SCAN_BYTES, event => {
73
- if (event.type !== "assistant.message")
74
- return;
75
- const data = event.data;
76
- if (Array.isArray(data?.toolRequests) && data.toolRequests.length)
77
- return;
78
- replies.push(...(0, client_1.messagesIn)([event]));
79
- }, client);
80
- const gap = read.logBytes < entry.offset
81
- ? "Observation gap: the session log shrank or is missing. Re-read the conversation before relying on prior progress."
82
- : read.skippedEvents ? `Observation gap: ${read.skippedEvents} malformed or oversized events skipped. Re-read app_sessions_tail; do not assume this is complete history.` : null;
83
- return { offset: read.offset, replies, ...(gap ? { gap } : {}), ...(read.offset < read.logBytes ? { backlog: true } : {}) };
70
+ /** A message's time in ms; a message with no time is never after a cursor. */
71
+ const timeOf = (at) => Date.parse(at ?? "");
72
+ /** The assistant messages a watched session wrote after the watch's cursor, and the cursor to continue from. */
73
+ async function newReplies(id, entry) {
74
+ const replies = (await (0, shepherd_rows_1.sessionMessages)(id, REPLY_COUNT)).filter(message => message.role === "assistant" && timeOf(message.at) > Date.parse(entry.after));
75
+ const after = replies.reduce((latest, reply) => (timeOf(reply.at) > Date.parse(latest) ? reply.at : latest), entry.after);
76
+ return { after, replies };
84
77
  }
85
78
  function replyContent(id, name, replies) {
86
79
  return [
@@ -116,13 +109,13 @@ function privateRuntimeDeliver(agent, now) {
116
109
  }
117
110
  };
118
111
  }
119
- /** Read every watched session once; deliver what they finished saying. Returns how many replies went to the agent. */
120
- async function checkWatches(agentRoot, deliver, client, now) {
121
- const offsets = {};
112
+ /** Read every watched session once; deliver what they finished saying. Returns how many passes delivered to the agent. */
113
+ async function checkWatches(agentRoot, deliver, now) {
114
+ const afters = {};
122
115
  const observations = {};
123
116
  let sidebar = null;
124
117
  try {
125
- sidebar = new Map((await (0, client_1.listAppSessions)({ ...client, now: () => now })).map(row => [row.id, row]));
118
+ sidebar = new Map((await (0, shepherd_rows_1.sessionRows)()).map(row => [row.id, row]));
126
119
  }
127
120
  catch (error) {
128
121
  (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_watch_error", message: "current sidebar identity unavailable; replies are historical only", meta: { error: error.message } });
@@ -132,39 +125,38 @@ async function checkWatches(agentRoot, deliver, client, now) {
132
125
  if (entry.until <= now)
133
126
  continue;
134
127
  try {
135
- const { offset, replies, gap, backlog } = newReplies(id, entry, client);
128
+ const { after, replies } = await newReplies(id, entry);
136
129
  const current = sidebar?.get(id);
137
130
  const renamed = current && entry.name && current.name !== entry.name;
138
- if (replies.length > 0 || renamed || gap) {
131
+ if (replies.length > 0 || renamed) {
139
132
  const identity = current
140
133
  ? `Observed at ${new Date(now).toISOString()}: current name ${JSON.stringify(current.name)}, state ${current.state}.${renamed ? ` Renamed from ${JSON.stringify(entry.name)}; prior work attribution may be stale, re-read the conversation.` : ""}`
141
134
  : `Observed at ${new Date(now).toISOString()}: current sidebar identity unavailable; re-read before attributing these replies to current work.`;
142
- await deliver(`${identity}${gap ? `\n${gap}` : ""}${backlog ? "\nMore local events remain unread; this burst is not the latest complete conversation." : ""}${replies.length ? `\n${replyContent(id, current?.name ?? entry.name, replies)}` : "\n[Copilot app session observation; no new reply] Re-read app_sessions_tail and get_sessions_status before reporting current progress."}`, [`${id}:${offset}:${current?.name ?? ""}`]);
135
+ await deliver(`${identity}${replies.length ? `\n${replyContent(id, current?.name ?? entry.name, replies)}` : "\n[Copilot app session observation; no new reply] Re-read app_sessions_tail and get_sessions_status before reporting current progress."}`, [`${id}:${after}:${current?.name ?? ""}`]);
143
136
  delivered += 1;
144
137
  if (entry.once && replies.length > 0)
145
138
  (0, store_1.unwatchSession)(agentRoot, id);
146
139
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_reply_delivered", message: "delivered a watched Copilot app session's reply to the agent", meta: { session: id, messages: replies.length } });
147
140
  }
148
- offsets[id] = offset;
149
- observations[id] = { previousOffset: entry.offset, ...(current ? { name: current.name } : {}) };
141
+ afters[id] = after;
142
+ observations[id] = { name: current?.name };
150
143
  }
151
144
  catch (error) {
152
145
  (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_watch_error", message: "could not read a watched Copilot app session", meta: { session: id, error: error.message } });
153
146
  }
154
147
  }
155
- (0, store_1.updateWatches)(agentRoot, offsets, now, observations);
148
+ (0, store_1.updateWatches)(agentRoot, afters, now, observations);
156
149
  return delivered;
157
150
  }
158
151
  /** Snapshot the app's sessions into the agent's state. A failure is recorded in the snapshot, not thrown. */
159
- async function recordSnapshot(agentRoot, client, now) {
152
+ async function recordSnapshot(agentRoot, now) {
160
153
  let result;
161
154
  try {
162
- const rows = await (0, client_1.listAppSessions)({ ...client, now: () => now });
163
- const picture = (0, client_1.snapshot)({ ...client, now: () => now }, rows);
164
- const names = new Map(picture.sessions.map(row => [row.id, row.name]));
155
+ const rows = await (0, shepherd_rows_1.sessionRows)();
156
+ const picture = (0, client_1.snapshot)(rows, now);
165
157
  result = {
166
158
  ...picture,
167
- stuck: picture.sessions.filter(row => row.state === "stuck").map(row => ({ id: row.id, name: names.get(row.id) })),
159
+ stuck: picture.sessions.filter(row => row.state === "stuck").map(row => ({ id: row.id, name: row.name })),
168
160
  waitingPrompts: (0, waiting_prompts_1.waitingPromptsOf)(agentRoot, rows, now),
169
161
  };
170
162
  }
@@ -187,15 +179,14 @@ async function checkDigest(agentName, agentRoot, deps) {
187
179
  const config = (0, identity_1.loadAgentConfig)({ agentName, agentRoot }).senses?.["app-sessions"];
188
180
  if (!config?.enabled || !config.digest)
189
181
  return exports.DIGEST_IDLE_MS;
190
- const list = () => (0, client_1.listAppSessions)({ ...deps.client, now: () => deps.now });
191
- const rows = await list();
182
+ const rows = await (0, shepherd_rows_1.sessionRows)();
192
183
  const state = (0, digest_1.readDigestState)(agentRoot);
193
184
  const digest = await (0, digest_1.writeDigest)({
194
185
  agentRoot, config: config.digest, client: deps.client, run: deps.run, now: deps.now, home: deps.home, rows,
195
- appRunning: (0, client_1.appRunning)(deps.client), waitingPrompts: (0, waiting_prompts_1.waitingPromptsOf)(agentRoot, rows, deps.now), state,
186
+ appRunning: true, waitingPrompts: (0, waiting_prompts_1.waitingPromptsOf)(agentRoot, rows, deps.now), state,
196
187
  });
197
188
  const roots = (config.digest.deskRoots ?? []).map(folder => (0, digest_1.expandHome)(folder, deps.home));
198
- await (0, digest_push_1.pushDue)(digest, state, deps.now, deps.notify, async (items) => (0, digest_push_1.stillDue)(items, await list(), roots));
189
+ await (0, digest_push_1.pushDue)(digest, state, deps.now, deps.notify, async (items) => (0, digest_push_1.stillDue)(items, await (0, shepherd_rows_1.sessionRows)(), roots));
199
190
  (0, digest_1.writeDigestState)(agentRoot, state);
200
191
  return (config.digest.everySeconds ?? digest_1.DIGEST_DEFAULT_SECONDS) * 1000;
201
192
  }
@@ -221,7 +212,7 @@ function startAppSessionsSense(options) {
221
212
  const snapshotTick = () => {
222
213
  if (stopped)
223
214
  return;
224
- waitingPoll = waitingPoll.then(() => recordSnapshot(agentRoot, client, now())).then(taken => (0, waiting_prompts_1.noticeWaitingPrompts)(agentRoot, taken, { notify: notifyOwner, now: now() })).catch((error) => {
215
+ waitingPoll = waitingPoll.then(() => recordSnapshot(agentRoot, now())).then(taken => (0, waiting_prompts_1.noticeWaitingPrompts)(agentRoot, taken, { notify: notifyOwner, now: now() })).catch((error) => {
225
216
  (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 } });
226
217
  });
227
218
  cancelSnapshot = schedule(snapshotTick, exports.SNAPSHOT_MS);
@@ -229,7 +220,7 @@ function startAppSessionsSense(options) {
229
220
  const watchTick = () => {
230
221
  if (stopped)
231
222
  return;
232
- inFlight = checkWatches(agentRoot, deliver, client, now()).catch((error) => {
223
+ inFlight = checkWatches(agentRoot, deliver, now()).catch((error) => {
233
224
  (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_watch_error", message: "could not check the watched Copilot app sessions", meta: { error: error.message } });
234
225
  }).finally(() => {
235
226
  if (!stopped)
@@ -245,7 +236,6 @@ function startAppSessionsSense(options) {
245
236
  });
246
237
  };
247
238
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_start", message: "app-sessions sense started", meta: { agent: options.agentName } });
248
- const prompts = (0, prompts_1.startPromptTracker)({ agentRoot, ...(client.stateDir ? { stateDir: client.stateDir } : {}), ...(client.openSocket ? { openSocket: client.openSocket } : {}), schedule, now });
249
239
  snapshotTick();
250
240
  watchTick();
251
241
  digestTick();
@@ -254,7 +244,6 @@ function startAppSessionsSense(options) {
254
244
  stopped = true;
255
245
  cancelSnapshot();
256
246
  cancelWatch?.();
257
- prompts.stop();
258
247
  cancelDigest?.();
259
248
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_end", message: "app-sessions sense stopped", meta: { agent: options.agentName } });
260
249
  },
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.rowOf = rowOf;
4
+ exports.sessionRows = sessionRows;
5
+ exports.sessionMessages = sessionMessages;
6
+ const runtime_1 = require("../../nerves/runtime");
7
+ const shepherd_cli_1 = require("./shepherd-cli");
8
+ /**
9
+ * The app's sessions as Shepherd lists them (`shepherd sessions --json`, `shepherd messages --json`), in the shapes the
10
+ * sense and its digest work from. Shepherd reads the app's socket and database; this maps its JSON and adds nothing.
11
+ */
12
+ const STATE = { busy: "working", waiting: "waiting", stuck: "stuck", idle: "idle" };
13
+ const str = (value) => (typeof value === "string" && value.length > 0 ? value : null);
14
+ const object = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : {});
15
+ /** One session row from Shepherd's JSON. A permission request the person must answer carries its id as the prompt. */
16
+ function rowOf(item) {
17
+ const activity = object(item.activity);
18
+ const input = object(item.awaiting_input);
19
+ const kind = str(input.kind);
20
+ const requestId = str(input.request_id);
21
+ const awaiting = kind === "plan" ? "plan" : kind === "user_input" ? "input" : kind === "permission" ? "permission" : undefined;
22
+ return {
23
+ id: String(item.id),
24
+ name: str(item.name) ?? "(unnamed)",
25
+ kind: item.type === "chat" ? "chat" : "workspace",
26
+ workspaceId: null,
27
+ workspaceType: null,
28
+ project: str(item.project_name),
29
+ projectId: str(item.project_id),
30
+ projectRepo: str(item.project_repo),
31
+ branch: str(item.branch),
32
+ path: str(item.path),
33
+ parentSessionId: str(item.parent_session_id),
34
+ creatorSessionId: str(item.creator_session_id),
35
+ coordinatingCreatorSessionId: str(item.coordinating_creator_session_id),
36
+ state: STATE[String(activity.status)] ?? "idle",
37
+ detail: str(activity.why) ?? "",
38
+ isRunning: item.is_running === true,
39
+ wasInterrupted: item.was_interrupted === true,
40
+ remote: item.remote === true,
41
+ createdAt: str(item.created_at),
42
+ updatedAt: str(item.updated_at),
43
+ lastActivity: str(activity.last_activity) ?? str(item.updated_at),
44
+ ...(awaiting ? { awaiting } : {}),
45
+ ...(kind === "permission" && requestId ? { prompt: { requestId, what: str(input.what) ?? "a permission", at: null } } : {}),
46
+ };
47
+ }
48
+ /** Every session in the app's sidebar. Throws when Shepherd cannot read the app. */
49
+ async function sessionRows() {
50
+ const picture = await (0, shepherd_cli_1.shepherd)(["sessions"]);
51
+ const rows = (Array.isArray(picture.sessions) ? picture.sessions : []).map(item => rowOf(object(item)));
52
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_rows", message: "read the app's session rows through Shepherd", meta: { rows: rows.length } });
53
+ return rows;
54
+ }
55
+ /** The last `count` visible messages of a session, oldest first, as Shepherd reads them. */
56
+ async function sessionMessages(id, count) {
57
+ const history = await (0, shepherd_cli_1.shepherd)(["messages", id], { count });
58
+ return (Array.isArray(history.messages) ? history.messages : []).map(item => {
59
+ const message = object(item);
60
+ return {
61
+ at: str(message.at),
62
+ role: message.role === "user" ? "user" : "assistant",
63
+ text: String(message.text ?? ""),
64
+ ...(message.truncated === true ? { truncated: true } : {}),
65
+ };
66
+ });
67
+ }
@@ -41,8 +41,6 @@ exports.readWatches = readWatches;
41
41
  exports.watchSession = watchSession;
42
42
  exports.unwatchSession = unwatchSession;
43
43
  exports.updateWatches = updateWatches;
44
- exports.readPending = readPending;
45
- exports.writePending = writePending;
46
44
  exports.writeSnapshot = writeSnapshot;
47
45
  exports.readSnapshot = readSnapshot;
48
46
  exports.snapshotSummary = snapshotSummary;
@@ -74,16 +72,15 @@ function writeJson(file, value) {
74
72
  fs.renameSync(next, file);
75
73
  }
76
74
  const watchFile = (agentRoot) => path.join(appSessionsStateDir(agentRoot), "watch.json");
77
- const pendingFile = (agentRoot) => path.join(appSessionsStateDir(agentRoot), "pending.json");
78
75
  const snapshotFile = (agentRoot) => path.join(appSessionsStateDir(agentRoot), "snapshot.json");
79
76
  function readWatches(agentRoot) {
80
77
  return readJson(watchFile(agentRoot), {});
81
78
  }
82
- /** Start (or extend) watching a session from `offset` in its event log. */
83
- function watchSession(agentRoot, id, name, offset, now, once = false) {
79
+ /** Start (or extend) watching a session for assistant messages after `after` (ISO); the earlier cursor is kept. */
80
+ function watchSession(agentRoot, id, name, after, now, once = false) {
84
81
  const watches = readWatches(agentRoot);
85
82
  const current = watches[id];
86
- const entry = { name: name ?? current?.name ?? null, offset: current ? Math.min(current.offset, offset) : offset, until: now + exports.WATCH_MS, ...(once && (current?.once ?? true) ? { once: true } : {}) };
83
+ const entry = { name: name ?? current?.name ?? null, after: current && Date.parse(current.after) < Date.parse(after) ? current.after : after, until: now + exports.WATCH_MS, ...(once && (current?.once ?? true) ? { once: true } : {}) };
87
84
  watches[id] = entry;
88
85
  writeJson(watchFile(agentRoot), watches);
89
86
  (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_watch", message: "watching a Copilot app session for replies", meta: { session: id } });
@@ -99,32 +96,25 @@ function unwatchSession(agentRoot, id) {
99
96
  return true;
100
97
  }
101
98
  /**
102
- * Apply the loop's progress to the watch file as it is now, so a watch a tool added meanwhile survives: offsets
103
- * only move forward, and expired watches go.
99
+ * Apply the loop's progress to the watch file as it is now, so a watch a tool added meanwhile survives: cursors only move
100
+ * forward, and expired watches go.
104
101
  */
105
- function updateWatches(agentRoot, offsets, now, observations = {}) {
102
+ function updateWatches(agentRoot, afters, now, observations = {}) {
106
103
  const watches = readWatches(agentRoot);
107
104
  for (const [id, entry] of Object.entries(watches)) {
108
105
  if (entry.until <= now) {
109
106
  delete watches[id];
110
107
  continue;
111
108
  }
112
- const offset = offsets[id];
109
+ const after = afters[id];
110
+ if (after !== undefined && Date.parse(after) > Date.parse(entry.after))
111
+ entry.after = after;
113
112
  const observation = observations[id];
114
- if (offset !== undefined && (offset > entry.offset || observation?.previousOffset === entry.offset))
115
- entry.offset = offset;
116
113
  if (observation?.name !== undefined)
117
114
  entry.name = observation.name;
118
115
  }
119
116
  writeJson(watchFile(agentRoot), watches);
120
117
  }
121
- /** The open requests by session id. */
122
- function readPending(agentRoot) {
123
- return readJson(pendingFile(agentRoot), {});
124
- }
125
- function writePending(agentRoot, pending) {
126
- writeJson(pendingFile(agentRoot), pending);
127
- }
128
118
  function writeSnapshot(agentRoot, snapshot) {
129
119
  writeJson(snapshotFile(agentRoot), snapshot);
130
120
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1175",
3
+ "version": "0.1.0-alpha.1176",
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.1175",
9
+ "version": "0.1.0-alpha.1176",
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.1175",
3
+ "version": "0.1.0-alpha.1176",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },
@@ -1,101 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.applyFrame = applyFrame;
7
- exports.startPromptTracker = startPromptTracker;
8
- const ws_1 = __importDefault(require("ws"));
9
- const runtime_1 = require("../../nerves/runtime");
10
- const cmux_1 = require("../shepherd/cmux");
11
- const client_1 = require("./client");
12
- const client_2 = require("./client");
13
- const store_1 = require("./store");
14
- /**
15
- * The questions and plan approvals the app's sessions are blocked on. The app announces each one once, as a frame to
16
- * the clients connected at that moment, and never repeats it to a client that connects later, so a client that wants
17
- * to answer one has to be listening when it is asked. This keeps one observer connection open and records what it
18
- * hears under the sense's state, where the tools read it.
19
- */
20
- const RECONNECT_MS = [1_000, 2_000, 5_000, 10_000, 30_000];
21
- const KEEP_MS = 24 * 3_600_000;
22
- const text = (value) => (typeof value === "string" && value ? value : undefined);
23
- /** Apply one frame to the open requests. True when they changed. */
24
- function applyFrame(pending, frame, at) {
25
- const session = text(frame.session_id);
26
- const requestId = text(frame.request_id);
27
- if (!session || !requestId)
28
- return false;
29
- if (frame.type === "user_input_request") {
30
- pending[session] = {
31
- kind: "input", requestId, at, ...(text(frame.question) ? { question: text(frame.question) } : {}),
32
- ...(Array.isArray(frame.choices) ? { choices: frame.choices.filter((choice) => typeof choice === "string") } : {}),
33
- ...(typeof frame.allow_freeform === "boolean" ? { allowFreeform: frame.allow_freeform } : {}),
34
- };
35
- return true;
36
- }
37
- if (frame.type === "exit_plan_mode_request") {
38
- pending[session] = {
39
- kind: "plan", requestId, at, ...(text(frame.summary) ? { summary: text(frame.summary) } : {}),
40
- ...(Array.isArray(frame.actions) ? { actions: frame.actions.filter((action) => typeof action === "string") } : {}),
41
- };
42
- return true;
43
- }
44
- if ((frame.type === "user_input_resolved" || frame.type === "exit_plan_mode_resolved") && pending[session]?.requestId === requestId) {
45
- delete pending[session];
46
- return true;
47
- }
48
- return false;
49
- }
50
- function startPromptTracker(options) {
51
- const stateDir = options.stateDir ?? (0, client_2.defaultStateDir)();
52
- const openSocket = options.openSocket ?? ((url) => new ws_1.default(url));
53
- const schedule = options.schedule ?? cmux_1.realSchedule;
54
- const now = options.now ?? Date.now;
55
- const pending = Object.fromEntries(Object.entries((0, store_1.readPending)(options.agentRoot)).filter(([, request]) => now() - Date.parse(request.at) < KEEP_MS));
56
- let stopped = false;
57
- let attempt = 0;
58
- let socket = null;
59
- let cancelRetry = null;
60
- const retry = () => {
61
- if (stopped || cancelRetry)
62
- return;
63
- cancelRetry = schedule(() => { cancelRetry = null; connect(); }, RECONNECT_MS[Math.min(attempt, RECONNECT_MS.length - 1)]);
64
- attempt += 1;
65
- };
66
- const connect = () => {
67
- try {
68
- socket = openSocket((0, client_1.copilotAppUrl)(stateDir));
69
- }
70
- catch (error) {
71
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_prompts_unavailable", message: "the Copilot app is not reachable; open questions are not tracked until it is", meta: { error: error.message } });
72
- return retry();
73
- }
74
- socket.on("open", () => { attempt = 0; });
75
- socket.on("message", (data) => {
76
- const raw = String(data);
77
- if (!/^\{"type":"(user_input_re|exit_plan_mode_re)/.test(raw))
78
- return;
79
- let frame;
80
- try {
81
- frame = JSON.parse(raw);
82
- }
83
- catch {
84
- return;
85
- }
86
- if (applyFrame(pending, frame, new Date(now()).toISOString()))
87
- (0, store_1.writePending)(options.agentRoot, pending);
88
- });
89
- socket.on("error", () => undefined);
90
- socket.on("close", retry);
91
- };
92
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_prompts_start", message: "tracking the Copilot app's open questions" });
93
- connect();
94
- return {
95
- stop: () => {
96
- stopped = true;
97
- cancelRetry?.();
98
- socket?.close();
99
- },
100
- };
101
- }