@ouro.bot/cli 0.1.0-alpha.1173 → 0.1.0-alpha.1174

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.1174",
6
+ "changes": [
7
+ "The app-sessions tools run Shepherd's `shepherd` CLI with `--json` for every verb (sessions, session, messages, send, create, answer, plan, archive, automation, workflows, run-workflow, open) instead of the app's socket. Shepherd is found by `SHEPHERD_BIN`, then `shepherd` on PATH, then Housesitter's copy; without it the tools say how to install it (`npx github:ourostack/shepherd#v0.8.1`). The app-interface socket requests, the handoff and coordinator readers, the probe list and the event-log history reader are removed. A notify_on_idle watch still reads the event log until the sense moves to Shepherd too."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1173",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1173",
2
+ "runtimeVersion": "0.1.0-alpha.1174",
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.1173</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1174</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -38,19 +38,21 @@ exports.appSessionsToolsEnabled = appSessionsToolsEnabled;
38
38
  const fs = __importStar(require("node:fs"));
39
39
  const path = __importStar(require("node:path"));
40
40
  const runtime_1 = require("../nerves/runtime");
41
- const app_interface_1 = require("../senses/app-sessions/app-interface");
42
41
  const digest_1 = require("../senses/app-sessions/digest");
43
42
  const client_1 = require("../senses/app-sessions/client");
43
+ const shepherd_cli_1 = require("../senses/app-sessions/shepherd-cli");
44
44
  const store_1 = require("../senses/app-sessions/store");
45
45
  /**
46
46
  * The app-sessions tools: what a coordinating session of the GitHub Copilot app can do with its client tools, under the
47
- * app's own names and in its shapes (see `senses/app-sessions/app-interface.ts` for how each reaches the app, and which
48
- * parts of the app are not reachable from outside it). Beside them, `app_sessions_tail` reads a session's transcript and
49
- * `app_sessions_restart` restarts the app through Housesitter, which the app's own tools do not do. Every write is
50
- * logged as a nerves event; none is gated beyond the harness's trust rule (family only).
47
+ * app's own names and in its shapes. Each one runs the matching verb of Shepherd's `shepherd` CLI with `--json`
48
+ * (see `senses/app-sessions/shepherd-cli.ts`), which owns the app's socket and database. Beside them, `app_sessions_tail`
49
+ * reads a session's last messages and `app_sessions_restart` restarts the app through Housesitter, which the app's own
50
+ * tools do not do. Every write is logged as a nerves event; none is gated beyond the harness's trust rule (family only).
51
51
  */
52
- /** This Mac's app, in `~/.copilot`. */
52
+ /** This Mac's app, in `~/.copilot`; the restart goes through Housesitter. */
53
53
  const clientOptions = {};
54
+ /** The status fields a session row carries beyond its identity; `list_sessions_and_chats` leaves them out, as it always has. */
55
+ const STATUS_KEYS = ["activity", "awaiting_user_input", "awaiting_plan_approval", "awaiting_permission", "awaiting_input", "was_interrupted"];
54
56
  function appSessionsToolsEnabled(agentRoot) {
55
57
  if (!agentRoot)
56
58
  return false;
@@ -64,6 +66,14 @@ function appSessionsToolsEnabled(agentRoot) {
64
66
  }
65
67
  const READ = { mutates: "none", risk: "low" };
66
68
  const write = (reason) => ({ mutates: "external_side_effect", risk: "high", reason });
69
+ const sessionId = (args) => String(args.session_id);
70
+ /** The arguments without `skip`, as the verb's JSON input; undefined when nothing is left, so the verb reads instead. */
71
+ function bodyOf(args, ...skip) {
72
+ const body = Object.fromEntries(Object.entries(args).filter(([key]) => !skip.includes(key)));
73
+ return Object.keys(body).length ? body : undefined;
74
+ }
75
+ /** Whether a watch answers the session's replies: `never` does not, `always` keeps watching for a day, `once` (the default) stops at the first reply. */
76
+ const watchMode = (value) => (value === "never" ? null : value === "always" ? "always" : "once");
67
77
  function define(name, description, properties, required, risk, body, summaryKeys = []) {
68
78
  return {
69
79
  tool: { type: "function", function: { name, description, parameters: { type: "object", properties, ...(required.length ? { required } : {}), additionalProperties: false } } },
@@ -77,7 +87,7 @@ function define(name, description, properties, required, risk, body, summaryKeys
77
87
  }
78
88
  catch (error) {
79
89
  (0, runtime_1.emitNervesEvent)({ level: "warn", component: "repertoire", event: "repertoire.app_sessions_tool_error", message: "app-sessions tool call failed", meta: { tool: name, error: error.message } });
80
- return JSON.stringify({ error: error.message });
90
+ return JSON.stringify({ error: error.message, ...(error instanceof shepherd_cli_1.ShepherdFailure ? { code: error.code } : {}) });
81
91
  }
82
92
  },
83
93
  summaryKeys,
@@ -86,10 +96,23 @@ function define(name, description, properties, required, risk, body, summaryKeys
86
96
  }
87
97
  const session = { type: "string", description: "A session's id from list_sessions_and_chats; a unique start of it (the first 8 characters) works." };
88
98
  const notifyOnIdle = { type: "string", enum: ["once", "always", "never"], description: "Whether the session's finished replies come back to you as inbound messages: once (default, the next one), always (for a day), or never. The app does not report back to an outside client, so this is how replies reach you." };
89
- exports.listSessionsAndChatsTool = define("list_sessions_and_chats", "Every open coding session and chat in this Mac's GitHub Copilot app: id, app_url, name, project, branch, who created and coordinates it. Read-only.", {}, [], READ, (_args, agentRoot) => (0, app_interface_1.listSessionsAndChats)(clientOptions, agentRoot));
90
- exports.getSessionsStatusTool = define("get_sessions_status", "What every session is doing now, with counts: busy, idle, stuck, blocked, and what each blocked one waits on. awaiting_input carries the request_id and the question that answer_session_input or respond_to_session_plan_v2 needs. Read-only.", { state: { type: "string", enum: ["busy", "idle", "waiting", "stuck"], description: "Only sessions in this state." } }, [], READ, (args, agentRoot) => (0, app_interface_1.getSessionsStatus)(agentRoot, typeof args.state === "string" ? args.state : undefined, clientOptions), ["state"]);
91
- exports.getSessionTool = define("get_session", "One session's details and what it is doing now, including what it waits on (awaiting_input). Read-only.", { session_id: session }, ["session_id"], READ, (args, agentRoot) => (0, app_interface_1.getSession)(agentRoot, args.session_id, clientOptions), ["session_id"]);
92
- exports.sendSessionMessageTool = define("send_session_message", "Send a message into a session, as its message box does; waits up to 2 minutes for the app to accept it (a session that is not loaded loads first). The app takes it for the person's, so say who you are in it. immediate (default) is admitted at the session's next turn boundary; enqueue waits behind its work.", { session_id: session, message: { type: "string", description: "What to send." }, delivery_mode: { type: "string", enum: ["immediate", "enqueue"] }, notify_on_idle: notifyOnIdle }, ["session_id", "message"], write("sends a message into another agent session in the owner's Copilot app"), (args, agentRoot) => (0, app_interface_1.sendSessionMessage)(agentRoot, args, clientOptions), ["session_id"]);
99
+ exports.listSessionsAndChatsTool = define("list_sessions_and_chats", "Every open coding session and chat in this Mac's GitHub Copilot app: id, app_url, name, project, branch, who created and coordinates it. Read-only.", {}, [], READ, async () => {
100
+ const picture = await (0, shepherd_cli_1.shepherd)(["sessions"]);
101
+ return { total: picture.summary.total, items: picture.sessions.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => !STATUS_KEYS.includes(key)))) };
102
+ });
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
+ 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
+ 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.
107
+ const row = await (0, shepherd_cli_1.shepherd)(["session", sessionId(args)]);
108
+ const id = String(row.id);
109
+ const mode = watchMode(args.notify_on_idle);
110
+ const offset = (0, client_1.eventLogSize)(id);
111
+ const sent = await (0, shepherd_cli_1.shepherd)(["send", id], bodyOf(args, "session_id", "notify_on_idle"));
112
+ if (mode !== null)
113
+ (0, store_1.watchSession)(agentRoot, id, String(row.name), offset, Date.now(), mode === "once");
114
+ return { ...sent, watching: mode !== null };
115
+ }, ["session_id"]);
93
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.", {
94
117
  name: { type: "string", description: "Sidebar title." }, project_id: { type: "string", description: "The project's id or name." }, session_kind: { type: "string", enum: ["chat", "project"] },
95
118
  workspace_type: { type: "string", enum: ["worktree", "branch"] }, branch_name: { type: "string", description: "Branch for a worktree; a fresh ouro-… name by default." },
@@ -101,27 +124,40 @@ exports.createSessionTool = define("create_session", "Start a session. With proj
101
124
  },
102
125
  },
103
126
  notify_on_idle: notifyOnIdle,
104
- }, [], write("opens a new agent session in the owner's Copilot app"), (args, agentRoot) => (0, app_interface_1.createSession)(agentRoot, args, clientOptions), ["name"]);
105
- 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, agentRoot) => (0, app_interface_1.answerSessionInput)(agentRoot, args, clientOptions), ["session_id"]);
106
- exports.respondToSessionPlanTool = define("respond_to_session_plan_v2", "Approve or reject the plan a session paused on (awaiting_plan_approval). feedback is sent to the session as a message after the decision.", { session_id: session, approved: { type: "boolean" }, selected_action: { type: "string", description: "One of awaiting_input.actions; the recommended one by default." }, feedback: { type: "string" } }, ["session_id", "approved"], write("approves or rejects another agent session's plan for the person"), (args, agentRoot) => (0, app_interface_1.respondToSessionPlan)(agentRoot, args, clientOptions), ["session_id"]);
107
- exports.archiveSessionTool = define("archive_session", "Archive a session you created with create_session (a project session's worktree goes with it). A session you did not create is archived only when the owner asked for that session in this conversation (owner_asked: true) or when it is over the size limit and a newer session names it as handed off. Archiving can be undone, and each such archive is logged and shown in the next digest.", { session_id: session, owner_asked: { type: "boolean", description: "True only when the owner asked in this conversation for this session to be archived." } }, ["session_id"], write("archives a session in the owner's Copilot app"), (args, agentRoot) => (0, app_interface_1.archiveSession)(agentRoot, args.session_id, clientOptions, args.owner_asked === true), ["session_id"]);
108
- exports.navigateToTool = define("navigate_to", "Show a session in the app's window, as following its app_url does.", { id: session }, ["id"], write("changes what the owner's Copilot app shows"), args => (0, app_interface_1.navigateTo)(args.id, clientOptions), ["id"]);
127
+ }, [], write("opens a new agent session in the owner's Copilot app"), async (args, agentRoot) => {
128
+ const created = await (0, shepherd_cli_1.shepherd)(["create"], bodyOf(args, "notify_on_idle"));
129
+ const mode = watchMode(args.notify_on_idle);
130
+ const kickoff = (args.kickoff && typeof args.kickoff === "object" ? args.kickoff : {});
131
+ const prompted = Boolean(kickoff.prompt);
132
+ // A new session's log starts empty, so its first reply is read from offset 0.
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");
135
+ return prompted ? { ...created, watching: mode !== null } : created;
136
+ }, ["name"]);
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"]);
138
+ exports.respondToSessionPlanTool = define("respond_to_session_plan_v2", "Approve or reject the plan a session paused on (awaiting_plan_approval). feedback is sent to the session as a message after the decision.", { session_id: session, approved: { type: "boolean" }, selected_action: { type: "string", description: "One of awaiting_input.actions; the recommended one by default." }, feedback: { type: "string" } }, ["session_id", "approved"], write("approves or rejects another agent session's plan for the person"), args => (0, shepherd_cli_1.shepherd)(["plan", sessionId(args)], bodyOf(args, "session_id")), ["session_id"]);
139
+ exports.archiveSessionTool = define("archive_session", "Archive a session you created with create_session (a project session's worktree goes with it). A session you did not create is archived only when the owner asked for that session in this conversation (owner_asked: true) or when it is over the size limit and a newer session names it as handed off. Archiving can be undone, and each such archive is logged and shown in the next digest.", { session_id: session, owner_asked: { type: "boolean", description: "True only when the owner asked in this conversation for this session to be archived." } }, ["session_id"], write("archives a session in the owner's Copilot app"), async (args, agentRoot) => {
140
+ const ownerAsked = args.owner_asked === true;
141
+ const row = await (0, shepherd_cli_1.shepherd)(["session", sessionId(args)]);
142
+ const archived = await (0, shepherd_cli_1.shepherd)(["archive", String(row.id)], ownerAsked ? { owner_asked: true } : undefined);
143
+ // Shepherd logs the archives it makes itself; the owner-asked ones are logged here for the digest.
144
+ if (ownerAsked)
145
+ (0, store_1.addArchiveLog)(agentRoot, { id: String(row.id), name: String(row.name), at: new Date().toISOString(), reason: "owner-asked" });
146
+ return archived;
147
+ }, ["session_id"]);
148
+ exports.navigateToTool = define("navigate_to", "Show a session in the app's window, as following its app_url does.", { id: session }, ["id"], write("changes what the owner's Copilot app shows"), args => (0, shepherd_cli_1.shepherd)(["open", String(args.id)]), ["id"]);
109
149
  exports.saveSessionAutomationTool = define("save_session_automation", "Create or replace the automation that wakes a session on a schedule, or clear it. interval is once (run_at), minutes (every_minutes), daily or weekly (schedule_hour, schedule_minute, schedule_day), or cron (cron_expression, five fields, local time).", {
110
150
  session_id: session, prompt: { type: "string" }, interval: { type: "string", enum: ["once", "minutes", "daily", "weekly", "cron"] }, run_at: { type: "string" }, every_minutes: { type: "number" },
111
151
  schedule_hour: { type: "number" }, schedule_minute: { type: "number" }, schedule_day: { type: "number" }, cron_expression: { type: "string" }, name: { type: "string" },
112
152
  clear: { type: "boolean", description: "Remove the session's automation instead." },
113
- }, ["session_id"], write("schedules wake-ups for an agent session in the owner's Copilot app"), args => (0, app_interface_1.saveSessionAutomation)(args, clientOptions), ["session_id"]);
114
- exports.getSessionAutomationTool = define("get_session_automation", "The automation attached to a session. Read-only.", { session_id: session }, ["session_id"], READ, args => (0, app_interface_1.getSessionAutomation)(args.session_id, clientOptions), ["session_id"]);
115
- exports.listWorkflowsTool = define("list_workflows", "The app's automations (workflows), with their ids and schedules. Read-only.", {}, [], READ, () => (0, app_interface_1.listWorkflows)(clientOptions));
116
- exports.runWorkflowTool = define("run_workflow", "Run one of the app's automations now, in a new session.", { id: { type: "string", description: "From list_workflows." } }, ["id"], write("starts a session in the owner's Copilot app"), args => (0, app_interface_1.runWorkflow)(args.id, clientOptions), ["id"]);
153
+ }, ["session_id"], write("schedules wake-ups for an agent session in the owner's Copilot app"), args => (0, shepherd_cli_1.shepherd)(["automation", sessionId(args)], bodyOf(args, "session_id")), ["session_id"]);
154
+ exports.getSessionAutomationTool = define("get_session_automation", "The automation attached to a session. Read-only.", { session_id: session }, ["session_id"], READ, args => (0, shepherd_cli_1.shepherd)(["automation", sessionId(args)]), ["session_id"]);
155
+ exports.listWorkflowsTool = define("list_workflows", "The app's automations (workflows), with their ids and schedules. Read-only.", {}, [], READ, () => (0, shepherd_cli_1.shepherd)(["workflows"]));
156
+ exports.runWorkflowTool = define("run_workflow", "Run one of the app's automations now, in a new session.", { id: { type: "string", description: "From list_workflows." } }, ["id"], write("starts a session in the owner's Copilot app"), args => (0, shepherd_cli_1.shepherd)(["run-workflow", String(args.id)]), ["id"]);
117
157
  exports.appSessionsTailTool = define("app_sessions_tail", "A session's last visible prompts and replies, oldest first, with its current name and state and how much of the local log was read. Re-read before reporting current progress: older messages are not live status. Read-only.", { session_id: session, count: { type: "number", description: "How many messages, 1-50. Default 6." } }, ["session_id"], READ, async (args, agentRoot) => {
118
- const row = (0, app_interface_1.findSession)(await (0, client_1.listAppSessions)(clientOptions), args.session_id);
119
- const history = (0, client_1.readAppSessionHistory)(row.id, Math.min(50, Math.max(1, Math.trunc(Number(args.count) || 6))), clientOptions);
120
- const watchedName = (0, store_1.readWatches)(agentRoot)[row.id]?.name;
121
- return {
122
- session_id: row.id, name: row.name, state: row.state, last_activity: row.lastActivity, ...history, ...(watchedName && watchedName !== row.name ? { renamed_from: watchedName } : {}),
123
- coverage: history.missing ? "missing" : history.skippedEvents ? "incomplete" : row.remote ? "local-only" : "local", freshness: "point-in-time; re-read before reporting current progress",
124
- };
158
+ const history = await (0, shepherd_cli_1.shepherd)(["messages", sessionId(args)], { count: Math.min(50, Math.max(1, Math.trunc(Number(args.count) || 6))) });
159
+ const watchedName = (0, store_1.readWatches)(agentRoot)[String(history.session_id)]?.name;
160
+ return { ...history, ...(watchedName && watchedName !== history.name ? { renamed_from: watchedName } : {}) };
125
161
  }, ["session_id"]);
126
162
  exports.appSessionsRestartTool = define("app_sessions_restart", "Restart the Copilot app and lose no session's work, through Housesitter on this Mac (it restarts the app from outside, as a launchd job). status: the restart in progress or the last one: state, step, start time, result, log. enqueue: start one now; every working session is asked to reach a safe point, the app is quit through its Quit menu (it waits while a person is using the Mac), relaunched, and every session that was working gets a resume message and is checked to have taken a turn. Starting one while another runs is refused. Says so plainly when Housesitter is not on this Mac.", { action: { type: "string", enum: ["status", "enqueue"], description: "Default status." }, why: { type: "string", description: "enqueue: the reason; it completes \"restarted at 11:40 for …\" in the resume message each session gets." } }, [], { mutates: "external_side_effect", risk: "high", reason: "restarts the owner's Copilot app" }, async (args, _agentRoot, ctx) => {
127
163
  if (args.action !== "enqueue")
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.realRunFile = exports.HUNG_MS = exports.HOUSESITTER_ENV = exports.SEND_WAIT_MS = void 0;
39
+ exports.realRunFile = exports.appUrl = exports.HUNG_MS = exports.HOUSESITTER_ENV = exports.SEND_WAIT_MS = void 0;
40
40
  exports.defaultStateDir = defaultStateDir;
41
41
  exports.copilotAppUrl = copilotAppUrl;
42
42
  exports.assertSessionId = assertSessionId;
@@ -48,8 +48,6 @@ exports.tailFacts = tailFacts;
48
48
  exports.classify = classify;
49
49
  exports.listAppSessions = listAppSessions;
50
50
  exports.snapshot = snapshot;
51
- exports.readAppSessionHistory = readAppSessionHistory;
52
- exports.tailAppSession = tailAppSession;
53
51
  exports.readNewAppEvents = readNewAppEvents;
54
52
  exports.messagesIn = messagesIn;
55
53
  exports.eventLogSize = eventLogSize;
@@ -384,71 +382,9 @@ function openEventLog(id, options) {
384
382
  throw error;
385
383
  }
386
384
  }
387
- /** Scan backwards until enough visible messages or the beginning, with bounded memory, not a fixed byte tail. */
388
- function readAppSessionHistory(id, count, options = {}) {
389
- const requestedCount = Math.min(50, Math.max(1, Math.trunc(count) || 1));
390
- const result = {
391
- messages: [], observedAt: new Date((options.now ?? Date.now)()).toISOString(), source: "local_event_log",
392
- requestedCount, returnedCount: 0, logBytes: 0, scannedBytes: 0, beginningReached: false, skippedEvents: 0, missing: false,
393
- };
394
- const fd = openEventLog(id, options);
395
- if (fd === null)
396
- return { ...result, missing: true };
397
- try {
398
- let position = fs.fstatSync(fd).size;
399
- result.logBytes = position;
400
- let carry = Buffer.alloc(0);
401
- let dropping = false;
402
- const keep = (line) => {
403
- if (dropping || line.length > MAX_EVENT_BYTES) {
404
- result.skippedEvents += 1;
405
- dropping = false;
406
- return;
407
- }
408
- if (!line.length)
409
- return;
410
- const events = parseEventLines(line.toString("utf-8"));
411
- if (!events.length)
412
- result.skippedEvents += 1;
413
- result.messages.push(...messagesIn(events));
414
- };
415
- while (position > 0 && result.messages.length < requestedCount) {
416
- const length = Math.min(EVENT_CHUNK_BYTES, position);
417
- position -= length;
418
- const chunk = Buffer.alloc(length);
419
- fs.readSync(fd, chunk, 0, length, position);
420
- result.scannedBytes += length;
421
- const buffer = Buffer.concat([chunk, carry]);
422
- let end = buffer.length;
423
- for (let at = buffer.lastIndexOf(10, end - 1); at >= 0; at = end > 0 ? buffer.lastIndexOf(10, end - 1) : -1) {
424
- keep(buffer.subarray(at + 1, end));
425
- end = at;
426
- if (result.messages.length >= requestedCount)
427
- break;
428
- }
429
- carry = buffer.subarray(0, end);
430
- if (dropping || carry.length > MAX_EVENT_BYTES) {
431
- dropping = true;
432
- carry = Buffer.alloc(0);
433
- }
434
- }
435
- if (position === 0 && result.messages.length < requestedCount) {
436
- keep(carry);
437
- result.beginningReached = true;
438
- }
439
- result.messages.reverse();
440
- result.returnedCount = result.messages.length;
441
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_history_read", message: "read bounded conversation history", meta: { session: id, returned: result.returnedCount, scannedBytes: result.scannedBytes, skippedEvents: result.skippedEvents } });
442
- return result;
443
- }
444
- finally {
445
- fs.closeSync(fd);
446
- }
447
- }
448
- /** Compatibility array view; tools also expose the read's coverage and observation time. */
449
- function tailAppSession(id, count, options = {}) {
450
- return readAppSessionHistory(id, count, options).messages;
451
- }
385
+ /** The link that opens a session in the app. */
386
+ const appUrl = (id) => `ghapp://sessions/${id}`;
387
+ exports.appUrl = appUrl;
452
388
  /** Read forward from a watch cursor; stop at a complete event after the budget, never jump to the newest tail. */
453
389
  function readNewAppEvents(id, from, maxBytes, visit, options = {}) {
454
390
  const fd = openEventLog(id, options);
@@ -7,7 +7,7 @@ exports.stillDue = stillDue;
7
7
  exports.pushDue = pushDue;
8
8
  const runtime_1 = require("../../nerves/runtime");
9
9
  const owner_notice_1 = require("../shepherd/owner-notice");
10
- const app_interface_1 = require("./app-interface");
10
+ const client_1 = require("./client");
11
11
  const digest_cards_1 = require("./digest-cards");
12
12
  /**
13
13
  * What is worth telling the owner unasked, judged with no model turn from the digest: only what only they can act on.
@@ -44,7 +44,7 @@ function conditions(digest) {
44
44
  function pushMessage(items) {
45
45
  const blocks = ORDER.map(kind => {
46
46
  const own = items.filter(item => item.kind === kind);
47
- return own.length ? [`${HEADINGS[kind]}:`, ...own.map(item => `- ${item.text} ${(0, app_interface_1.appUrl)(item.session)}`)].join("\n") : "";
47
+ return own.length ? [`${HEADINGS[kind]}:`, ...own.map(item => `- ${item.text} ${(0, client_1.appUrl)(item.session)}`)].join("\n") : "";
48
48
  }).filter(Boolean);
49
49
  return blocks.join("\n\n");
50
50
  }
@@ -0,0 +1,165 @@
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.ShepherdFailure = exports.ShepherdUnavailableError = exports.SHEPHERD_INSTALL = exports.SHEPHERD_BIN_ENV = exports.SHEPHERD_VERSION = void 0;
37
+ exports.resolveShepherd = resolveShepherd;
38
+ exports.shepherd = shepherd;
39
+ const node_child_process_1 = require("node:child_process");
40
+ const fs = __importStar(require("node:fs"));
41
+ const os = __importStar(require("node:os"));
42
+ const path = __importStar(require("node:path"));
43
+ const runtime_1 = require("../../nerves/runtime");
44
+ /**
45
+ * The GitHub Copilot app's sessions, read and acted on through Shepherd's `shepherd` CLI (github.com/ourostack/shepherd),
46
+ * which owns the app's socket and database. Each verb takes `--json`, prints one JSON result, and a failure exits non-zero
47
+ * with `{ ok: false, code, error }`, where `error` says the problem and the fix. A verb that takes arguments reads one JSON
48
+ * object on stdin with `--input -`.
49
+ *
50
+ * Shepherd is found as Housesitter's restart is: `SHEPHERD_BIN` if set, else `shepherd` on PATH, else the copy Housesitter
51
+ * installs under its releases folder, run with this Node.
52
+ */
53
+ exports.SHEPHERD_VERSION = "0.8.1";
54
+ exports.SHEPHERD_BIN_ENV = "SHEPHERD_BIN";
55
+ exports.SHEPHERD_INSTALL = `npx github:ourostack/shepherd#v${exports.SHEPHERD_VERSION}`;
56
+ /** Longer than a send's two-minute wait, so a slow send is answered rather than cut off here. */
57
+ const SHEPHERD_TIMEOUT_MS = 150_000;
58
+ const BUNDLED_PATH = ["Library", "Application Support", "housesitter", "releases", "shepherd", "current", "bin", "shepherd.mjs"];
59
+ class ShepherdUnavailableError extends Error {
60
+ constructor(problem) {
61
+ super(`${problem}. Fix: install Shepherd with ${exports.SHEPHERD_INSTALL}, or set ${exports.SHEPHERD_BIN_ENV} to its CLI`);
62
+ this.name = "ShepherdUnavailableError";
63
+ }
64
+ }
65
+ exports.ShepherdUnavailableError = ShepherdUnavailableError;
66
+ /** A verb that failed, with Shepherd's code; the message is its problem and fix. */
67
+ class ShepherdFailure extends Error {
68
+ code;
69
+ constructor(code, message) {
70
+ super(message);
71
+ this.name = "ShepherdFailure";
72
+ this.code = code;
73
+ }
74
+ }
75
+ exports.ShepherdFailure = ShepherdFailure;
76
+ const isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
77
+ /** A `.js` or `.mjs` file runs under this Node; anything else is an executable. */
78
+ const commandFor = (file) => (/\.m?js$/.test(file) ? { file: process.execPath, prefix: [file] } : { file, prefix: [] });
79
+ function onPath(name, pathValue) {
80
+ for (const dir of pathValue.split(path.delimiter)) {
81
+ if (!dir)
82
+ continue;
83
+ const candidate = path.join(dir, name);
84
+ try {
85
+ if (fs.statSync(candidate).isFile()) {
86
+ fs.accessSync(candidate, fs.constants.X_OK);
87
+ return candidate;
88
+ }
89
+ }
90
+ catch {
91
+ // not an executable here; keep looking
92
+ }
93
+ }
94
+ return null;
95
+ }
96
+ /** The Shepherd CLI to run, or null when none is installed. */
97
+ function resolveShepherd(env = process.env, home = os.homedir()) {
98
+ const explicit = env[exports.SHEPHERD_BIN_ENV];
99
+ if (explicit) {
100
+ if (!fs.existsSync(explicit))
101
+ throw new ShepherdUnavailableError(`${exports.SHEPHERD_BIN_ENV} points at ${explicit}, which does not exist`);
102
+ return commandFor(explicit);
103
+ }
104
+ const found = onPath("shepherd", env.PATH ?? "");
105
+ if (found)
106
+ return { file: found, prefix: [] };
107
+ const bundled = path.join(home, ...BUNDLED_PATH);
108
+ return fs.existsSync(bundled) ? commandFor(bundled) : null;
109
+ }
110
+ function runCommand(command, args, stdin, timeoutMs) {
111
+ return new Promise((resolve, reject) => {
112
+ const child = (0, node_child_process_1.spawn)(command.file, [...command.prefix, ...args], { stdio: ["pipe", "pipe", "pipe"] });
113
+ let stdout = "";
114
+ let stderr = "";
115
+ const timer = setTimeout(() => {
116
+ child.kill();
117
+ reject(new ShepherdFailure("timeout", `shepherd did not answer within ${Math.round(timeoutMs / 1000)} s. Fix: check the GitHub Copilot app is running, then try again`));
118
+ }, timeoutMs);
119
+ child.stdout.on("data", chunk => { stdout += String(chunk); });
120
+ child.stderr.on("data", chunk => { stderr += String(chunk); });
121
+ child.stdin.on("error", () => undefined);
122
+ child.on("error", error => {
123
+ clearTimeout(timer);
124
+ reject(new ShepherdUnavailableError(`could not start shepherd at ${command.file} (${error.message})`));
125
+ });
126
+ child.on("close", code => {
127
+ clearTimeout(timer);
128
+ resolve({ code, stdout, stderr });
129
+ });
130
+ child.stdin.end(stdin ?? "");
131
+ });
132
+ }
133
+ /** The last line of stdout as a JSON object, or null when there is none. */
134
+ function jsonResult(stdout) {
135
+ const line = stdout.trim().split("\n").slice(-1).join("");
136
+ try {
137
+ const parsed = JSON.parse(line);
138
+ return isRecord(parsed) ? parsed : null;
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ }
144
+ /**
145
+ * Runs one Shepherd verb with `--json` and returns its JSON result. `input` is sent as the verb's one JSON object on
146
+ * stdin. Throws ShepherdUnavailableError when no Shepherd is installed, and ShepherdFailure when the verb fails.
147
+ */
148
+ async function shepherd(verb, input, options = {}) {
149
+ const command = resolveShepherd(options.env, options.home);
150
+ if (!command)
151
+ throw new ShepherdUnavailableError("Shepherd is not installed, so the GitHub Copilot app's sessions cannot be reached");
152
+ const args = [...verb, "--json", ...(input === undefined ? [] : ["--input", "-"])];
153
+ const { code, stdout, stderr } = await runCommand(command, args, input === undefined ? null : JSON.stringify(input), options.timeoutMs ?? SHEPHERD_TIMEOUT_MS);
154
+ const parsed = jsonResult(stdout);
155
+ if (code !== 0 || parsed?.ok === false) {
156
+ const failure = parsed && typeof parsed.error === "string" ? parsed.error : `shepherd ${verb.join(" ")} failed (exit ${code})${stderr.trim() ? `: ${stderr.trim()}` : ""}`;
157
+ const reason = parsed && typeof parsed.code === "string" ? parsed.code : `exit-${code}`;
158
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.shepherd_error", message: "a Shepherd verb failed", meta: { verb: verb[0], code: reason } });
159
+ throw new ShepherdFailure(reason, failure);
160
+ }
161
+ if (!parsed)
162
+ throw new ShepherdFailure("no-json", `shepherd ${verb[0]} printed no JSON. Fix: run it by hand with --json to see its output`);
163
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.shepherd_call", message: "ran a Shepherd verb", meta: { verb: verb[0] } });
164
+ return parsed;
165
+ }
@@ -41,9 +41,6 @@ exports.readWatches = readWatches;
41
41
  exports.watchSession = watchSession;
42
42
  exports.unwatchSession = unwatchSession;
43
43
  exports.updateWatches = updateWatches;
44
- exports.readProbes = readProbes;
45
- exports.addProbe = addProbe;
46
- exports.removeProbe = removeProbe;
47
44
  exports.readPending = readPending;
48
45
  exports.writePending = writePending;
49
46
  exports.writeSnapshot = writeSnapshot;
@@ -77,7 +74,6 @@ function writeJson(file, value) {
77
74
  fs.renameSync(next, file);
78
75
  }
79
76
  const watchFile = (agentRoot) => path.join(appSessionsStateDir(agentRoot), "watch.json");
80
- const probesFile = (agentRoot) => path.join(appSessionsStateDir(agentRoot), "probes.json");
81
77
  const pendingFile = (agentRoot) => path.join(appSessionsStateDir(agentRoot), "pending.json");
82
78
  const snapshotFile = (agentRoot) => path.join(appSessionsStateDir(agentRoot), "snapshot.json");
83
79
  function readWatches(agentRoot) {
@@ -122,19 +118,6 @@ function updateWatches(agentRoot, offsets, now, observations = {}) {
122
118
  }
123
119
  writeJson(watchFile(agentRoot), watches);
124
120
  }
125
- function readProbes(agentRoot) {
126
- return readJson(probesFile(agentRoot), {});
127
- }
128
- function addProbe(agentRoot, id, name, now) {
129
- const probes = readProbes(agentRoot);
130
- probes[id] = { name, at: new Date(now).toISOString() };
131
- writeJson(probesFile(agentRoot), probes);
132
- }
133
- function removeProbe(agentRoot, id) {
134
- const probes = readProbes(agentRoot);
135
- delete probes[id];
136
- writeJson(probesFile(agentRoot), probes);
137
- }
138
121
  /** The open requests by session id. */
139
122
  function readPending(agentRoot) {
140
123
  return readJson(pendingFile(agentRoot), {});
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1173",
3
+ "version": "0.1.0-alpha.1174",
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.1173",
9
+ "version": "0.1.0-alpha.1174",
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.1173",
3
+ "version": "0.1.0-alpha.1174",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },
@@ -1,364 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.appUrl = void 0;
37
- exports.findSession = findSession;
38
- exports.listSessionsAndChats = listSessionsAndChats;
39
- exports.getSessionsStatus = getSessionsStatus;
40
- exports.getSession = getSession;
41
- exports.deliverMessage = deliverMessage;
42
- exports.sendSessionMessage = sendSessionMessage;
43
- exports.createSession = createSession;
44
- exports.answerSessionInput = answerSessionInput;
45
- exports.respondToSessionPlan = respondToSessionPlan;
46
- exports.archiveSession = archiveSession;
47
- exports.archiveRow = archiveRow;
48
- exports.navigateTo = navigateTo;
49
- exports.saveSessionAutomation = saveSessionAutomation;
50
- exports.getSessionAutomation = getSessionAutomation;
51
- exports.listWorkflows = listWorkflows;
52
- exports.runWorkflow = runWorkflow;
53
- const node_crypto_1 = require("node:crypto");
54
- const os = __importStar(require("node:os"));
55
- const runtime_1 = require("../../nerves/runtime");
56
- const client_1 = require("./client");
57
- const coordinator_1 = require("./coordinator");
58
- const handoff_1 = require("./handoff");
59
- const store_1 = require("./store");
60
- /**
61
- * The GitHub Copilot app's own interface, used the way a coordinating session uses its client tools: the same twelve
62
- * operations, under the app's names, answering in the app's shapes. Each one is a request on the app's local WebSocket,
63
- * the socket its own window speaks, and a reply read back from it. Nothing here reads the app's database or files.
64
- *
65
- * Three things a session gets from the app are not reachable from outside it. An outside client is anonymous: the app
66
- * takes its messages for the person's, and ignores the creator and coordination fields on a create request, so a session
67
- * made here has no coordinator and nothing reports back unless the sender watches it. A question or plan approval is
68
- * announced once, to the clients connected then (see `prompts.ts`). `relay_session_input` and `publish_chat_update` act
69
- * on the calling session's own conversation, which a client outside the app has none of.
70
- */
71
- const REQUEST_WAIT_MS = 30_000;
72
- const CREATE_WAIT_MS = 300_000;
73
- const ARCHIVE_WAIT_MS = 60_000;
74
- const ANSWER_WAIT_MS = 15_000;
75
- const COORDINATION_NOTE = "an outside client cannot be a session's coordinator, so the app will not report back: replies come back to you through the app-sessions sense instead";
76
- const isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
77
- const str = (value) => (typeof value === "string" && value.length > 0 ? value : null);
78
- const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== null && item !== undefined));
79
- /** The link that opens a session in the app. */
80
- const appUrl = (id) => `ghapp://sessions/${id}`;
81
- exports.appUrl = appUrl;
82
- const reasonOf = (frame) => str(frame.error) ?? str(frame.message) ?? str(frame.reason) ?? str(frame.detail) ?? String(frame.type);
83
- /** Whether a sender wants a session's reply back, and for how long: once (the default), always, or never. */
84
- const notifyMode = (value) => (value === "never" ? null : value === "always" ? "always" : "once");
85
- /** One request and its answer: the frame `settle` calls "ok", or the reason it was refused, or that the app did not answer in time. */
86
- async function ask(frame, settle, waitMs, options) {
87
- // An answer carries the id of the request it answers; every other request gets its own.
88
- const requestId = str(frame.request_id) ?? (0, node_crypto_1.randomUUID)();
89
- const verdict = (reply) => (reply.type === "socket_error" || reply.type === "error" ? "fail" : settle(reply, requestId));
90
- const got = await (0, client_1.exchange)([{ ...frame, request_id: requestId }], { keep: reply => verdict(reply) !== "ignore", done: reply => /^(ok|fail)$/.test(verdict(reply)), waitMs }, options);
91
- const last = got.at(-1);
92
- if (last && verdict(last) === "ok")
93
- return { ok: true, frame: last, error: null };
94
- return { ok: false, frame: last ?? null, error: last && verdict(last) === "fail" ? reasonOf(last) : "the app did not answer in time" };
95
- }
96
- /** A session by its id or its project-session (workspace) id, or a unique start of either; the first eight characters are enough. */
97
- function findSession(rows, value) {
98
- const wanted = str(value)?.trim() ?? "";
99
- if (!wanted)
100
- throw new Error("name a session: its id, or the start of it, from list_sessions_and_chats");
101
- const exact = rows.find(row => row.id === wanted) ?? rows.find(row => row.workspaceId === wanted);
102
- if (exact)
103
- return exact;
104
- const matches = rows.filter(row => row.id.startsWith(wanted) || row.workspaceId?.startsWith(wanted));
105
- if (matches.length === 1)
106
- return matches[0];
107
- throw new Error(matches.length ? `'${wanted}' matches ${matches.length} sessions; give more of the id` : `no session '${wanted}' in the Copilot app (list_sessions_and_chats shows them)`);
108
- }
109
- const resolve = async (value, options) => findSession(await (0, client_1.listAppSessions)(options), value);
110
- /**
111
- * Who coordinates the session now, beside the app's own field, which keeps naming a coordinator that handed off and
112
- * was archived (see `coordinator.ts`). Say a lane has no coordinator only when `coordinator_gone` is true.
113
- */
114
- function coordination(row, rows, options, successors) {
115
- const found = (0, coordinator_1.coordinatorOf)(row, rows, { client: options, ...(successors ? { successorOf: successors } : {}) });
116
- if (!found)
117
- return {};
118
- if ("gone" in found)
119
- return { coordinator_gone: true };
120
- return { coordinator_session_id: found.id, coordinator_name: found.name, ...(found.via === "app" ? {} : { coordinator_found_by: found.via }) };
121
- }
122
- function item(row, rows, options, successors) {
123
- return compact({
124
- type: row.kind === "chat" ? "chat" : "session", id: row.id, app_url: (0, exports.appUrl)(row.id), name: row.name, project_id: row.projectId, project_name: row.project, project_repo: row.projectRepo,
125
- branch: row.branch, path: row.path, created_at: row.createdAt, updated_at: row.updatedAt, creator_session_id: row.creatorSessionId,
126
- coordinating_creator_session_id: row.coordinatingCreatorSessionId, ...coordination(row, rows, options, successors), parent_session_id: row.parentSessionId, is_running: row.isRunning, ...(row.remote ? { remote: true } : {}),
127
- });
128
- }
129
- /** What an answer needs from a session blocked on something: the request's id and what it asks, or why the id is unknown. */
130
- function awaitingInput(row, pending) {
131
- const request = pending[row.id];
132
- if (row.awaiting === "permission")
133
- return { kind: "permission", request_id: row.prompt.requestId, what: row.prompt.what, note: "answer it in the app; the app's own tools do not answer permissions either" };
134
- if (row.awaiting === "input" || row.awaiting === "plan") {
135
- const kind = row.awaiting === "plan" ? "plan" : "user_input";
136
- if (request && (request.kind === "plan") === (kind === "plan")) {
137
- return compact({ kind, request_id: request.requestId, question: request.question, choices: request.choices, allow_freeform: request.allowFreeform, summary: request.summary, actions: request.actions });
138
- }
139
- return { kind, request_id: null, note: "it was asked while this agent was not connected to the app, which announces a question only once; the person can answer it in the app" };
140
- }
141
- return undefined;
142
- }
143
- function status(row, rows, pending, options, successors) {
144
- const input = awaitingInput(row, pending);
145
- return compact({
146
- ...item(row, rows, options, successors), was_interrupted: row.wasInterrupted || null,
147
- activity: compact({ status: row.state === "working" ? "busy" : row.state, why: row.detail, last_activity: row.lastActivity }),
148
- awaiting_user_input: row.awaiting === "input", awaiting_plan_approval: row.awaiting === "plan", awaiting_permission: row.awaiting === "permission",
149
- awaiting_input: input,
150
- });
151
- }
152
- // ---------- reading ----------
153
- async function listSessionsAndChats(options = {}, agentRoot) {
154
- const rows = await (0, client_1.listAppSessions)(options);
155
- const successors = agentRoot ? (0, coordinator_1.handoffSuccessors)(agentRoot) : undefined;
156
- return { total: rows.length, items: rows.map(row => item(row, rows, options, successors)) };
157
- }
158
- async function getSessionsStatus(agentRoot, state, options = {}) {
159
- const rows = await (0, client_1.listAppSessions)(options);
160
- const pending = (0, store_1.readPending)(agentRoot);
161
- const successors = (0, coordinator_1.handoffSuccessors)(agentRoot);
162
- const count = (keep) => rows.filter(keep).length;
163
- return {
164
- summary: {
165
- total: rows.length, running: count(row => row.isRunning), busy: count(row => row.state === "working"), blocked: count(row => row.state === "waiting"), stuck: count(row => row.state === "stuck"),
166
- awaiting_user_input: count(row => row.awaiting === "input"), awaiting_plan_approval: count(row => row.awaiting === "plan"),
167
- },
168
- sessions: rows.filter(row => !state || row.state === state || (state === "busy" && row.state === "working")).map(row => status(row, rows, pending, options, successors)),
169
- };
170
- }
171
- async function getSession(agentRoot, id, options = {}) {
172
- const rows = await (0, client_1.listAppSessions)(options);
173
- return status(findSession(rows, id), rows, (0, store_1.readPending)(agentRoot), options, (0, coordinator_1.handoffSuccessors)(agentRoot));
174
- }
175
- // ---------- writing ----------
176
- /** Put a message into a session, as its message box does, and wait for the app to accept it (a session that is not loaded loads first). */
177
- async function deliverMessage(id, message, mode, options = {}) {
178
- (0, client_1.assertSessionId)(id);
179
- let interim = false;
180
- const sent = await ask({ type: "send_message", session_id: id, prompt: message, delivery_mode: mode }, (reply, requestId) => {
181
- if (/^session_message_(sent|queued)$/.test(String(reply.type)) && reply.request_id === requestId)
182
- return "ok";
183
- if (reply.type === "session_dispatch_state" && reply.request_id === requestId) {
184
- interim ||= reply.dispatch_may_have_started === true;
185
- return "wait";
186
- }
187
- return reply.request_id === requestId || (reply.session_id === id && /^session_(message_delivery_unknown|resume_failed)$/.test(String(reply.type))) ? "fail" : "ignore";
188
- }, options.sendWaitMs ?? client_1.SEND_WAIT_MS, options);
189
- const unconfirmed = !sent.ok && interim && sent.frame?.type === "session_dispatch_state";
190
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_sent", message: "sent a message into a Copilot app session", meta: { session: id, chars: message.length, ok: sent.ok } });
191
- return unconfirmed ? { ...sent, error: "the app began delivering the message but had not confirmed it in time; read the session before sending it again" } : sent;
192
- }
193
- /** `send_session_message`. `notify_on_idle` brings the session's finished reply back to the sender. */
194
- async function sendSessionMessage(agentRoot, args, options = {}) {
195
- const message = typeof args.message === "string" ? args.message : "";
196
- if (!message.trim())
197
- throw new Error("say what to send");
198
- const row = await resolve(args.session_id, options);
199
- const offset = (0, client_1.eventLogSize)(row.id, options);
200
- const sent = await deliverMessage(row.id, message, args.delivery_mode === "enqueue" ? "enqueue" : "immediate", options);
201
- const notify = notifyMode(args.notify_on_idle);
202
- const watching = sent.ok && notify !== null;
203
- if (watching)
204
- (0, store_1.watchSession)(agentRoot, row.id, row.name, offset, Date.now(), notify === "once");
205
- return compact({ ok: sent.ok, status: sent.ok ? (sent.frame?.type === "session_message_queued" ? "queued" : "accepted") : "failed", session_id: row.id, name: row.name, message_id: str(sent.frame?.message_id), watching, error: sent.error });
206
- }
207
- /** The project a create request names: its id, or its name or repository as the app lists it. */
208
- async function projectId(value, options) {
209
- const listed = await ask({ type: "list_projects" }, reply => (reply.type === "project_list" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
210
- const projects = Array.isArray(listed.frame?.projects) ? listed.frame.projects.filter(isRecord) : [];
211
- const found = projects.find(project => project.id === value) ?? projects.find(project => project.name === value);
212
- if (!found)
213
- throw new Error(`no project '${value}' in the Copilot app${projects.length ? ` (it has: ${projects.map(project => str(project.name) ?? "?").join(", ")})` : ""}`);
214
- return found.id;
215
- }
216
- /** Start a session: a project session in its own worktree (or on the project's checkout), or a standalone chat. */
217
- async function createSession(agentRoot, args, options = {}) {
218
- const kickoff = isRecord(args.kickoff) ? args.kickoff : {};
219
- const prompt = str(kickoff.prompt);
220
- const name = str(args.name);
221
- const project = str(args.project_id);
222
- const chat = args.session_kind === "chat" || (!project && args.session_kind !== "project");
223
- if (!chat && !project)
224
- throw new Error("a project session needs project_id (a project's id or name; list_sessions_and_chats shows project_id on its sessions)");
225
- let created;
226
- if (chat) {
227
- created = await ask({ type: "create_session", cwd: os.homedir(), session_type: "general_chat", ...(str(kickoff.model) ? { model: str(kickoff.model) } : {}), ...(str(kickoff.agent) ? { agent: str(kickoff.agent) } : {}) }, (reply, id) => (reply.request_id === id ? (reply.type === "session_created" ? "ok" : "fail") : "ignore"), REQUEST_WAIT_MS, options);
228
- }
229
- else {
230
- const worktree = args.workspace_type !== "branch";
231
- created = await ask({
232
- type: worktree ? "create_worktree_workspace" : "create_branch_workspace", project_id: await projectId(project, options),
233
- ...(worktree ? { branch_name: str(args.branch_name) ?? `ouro-${(0, node_crypto_1.randomUUID)().slice(0, 8)}`, checkout_existing_branch: false } : {}),
234
- ...(name ? { name } : {}), kickoff_permission_mode: str(kickoff.permission_mode) ?? "allow-all",
235
- ...(str(kickoff.model) ? { kickoff_model: str(kickoff.model) } : {}),
236
- ...(str(kickoff.agent) ? { kickoff_agent: str(kickoff.agent) } : {}), ...(str(kickoff.reasoning_effort) ? { kickoff_reasoning_effort: str(kickoff.reasoning_effort) } : {}),
237
- }, (reply, id) => (reply.request_id === id ? (reply.type === "workspace_created" ? "ok" : reply.type === "workspace_changed" ? "wait" : "fail") : reply.type === "session_creation_failed" ? "fail" : "ignore"), CREATE_WAIT_MS, options);
238
- // The app opens the workspace's session only for its own window, so an outside client opens it.
239
- if (created.ok) {
240
- const workspace = isRecord(created.frame.workspace) ? created.frame.workspace : {};
241
- const workspaceId = str(workspace.id);
242
- const cwd = str(workspace.displayPath);
243
- if (workspaceId && cwd)
244
- created = await ask({ type: "create_session", workspace_id: workspaceId, cwd }, (reply, id) => (reply.request_id === id ? (reply.type === "session_created" ? "ok" : "fail") : "ignore"), REQUEST_WAIT_MS, options);
245
- }
246
- }
247
- const id = str(created.frame?.session_id);
248
- if (!created.ok || !id)
249
- return { ok: false, created: false, error: created.error ?? "the app did not name the session it made" };
250
- (0, client_1.assertSessionId)(id);
251
- (0, store_1.addProbe)(agentRoot, id, name, Date.now());
252
- // The app does not run a kickoff for a client that is not its window ("ready for first message"), so the first message and mode are set here.
253
- let sent = null;
254
- if (chat && name)
255
- await ask({ type: "rename_session", session_id: id, title: name }, reply => (reply.type === "session_title_updated" && reply.session_id === id ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
256
- const mode = str(kickoff.mode);
257
- if (mode && mode !== "interactive")
258
- await ask({ type: "set_session_mode", session_id: id, mode }, reply => (reply.type === "session_mode_result" && reply.session_id === id ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
259
- if (prompt)
260
- sent = await sendSessionMessage(agentRoot, { session_id: id, message: prompt, notify_on_idle: args.notify_on_idle }, options);
261
- const error = sent && !sent.ok ? `created, but the first message was not accepted: ${String(sent.error)}` : null;
262
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_created", message: "created a Copilot app session", meta: { session: id, chat, prompted: !!prompt } });
263
- return compact({ ok: error === null, created: true, session_id: id, app_url: (0, exports.appUrl)(id), kind: chat ? "chat" : "session", workspace_id: str(created.frame?.workspace_id), watching: sent?.watching, coordination: COORDINATION_NOTE, error });
264
- }
265
- /** Answer a question a session asked with its ask_user tool. */
266
- async function answerSessionInput(agentRoot, args, options = {}) {
267
- const answer = typeof args.answer === "string" ? args.answer : "";
268
- if (!answer)
269
- throw new Error("give the answer");
270
- const row = await resolve(args.session_id, options);
271
- const request = (0, store_1.readPending)(agentRoot)[row.id];
272
- if (row.awaiting !== "input" || request?.kind !== "input")
273
- throw new Error(`session ${row.id} is not waiting on a question this agent heard asked (get_session shows what it waits on)`);
274
- const answered = await ask({ type: "respond_to_user_input", session_id: row.id, request_id: request.requestId, answer, was_freeform: !(request.choices ?? []).includes(answer) }, reply => (reply.type === "user_input_resolved" && reply.request_id === request.requestId ? "ok" : "ignore"), ANSWER_WAIT_MS, options);
275
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_answered", message: "answered a Copilot app session's question", meta: { session: row.id, ok: answered.ok } });
276
- return compact({ ok: answered.ok, session_id: row.id, error: answered.error });
277
- }
278
- /** Approve or reject a plan a session is paused on. */
279
- async function respondToSessionPlan(agentRoot, args, options = {}) {
280
- const row = await resolve(args.session_id, options);
281
- const request = (0, store_1.readPending)(agentRoot)[row.id];
282
- if (row.awaiting !== "plan" || request?.kind !== "plan")
283
- throw new Error(`session ${row.id} is not waiting on a plan this agent heard presented (get_session shows what it waits on)`);
284
- const approved = args.approved === true || args.approved === "true";
285
- const responded = await ask({ type: "respond_to_exit_plan_mode", session_id: row.id, request_id: request.requestId, approved, ...(str(args.selected_action) ? { selected_action: str(args.selected_action) } : {}) }, reply => (reply.request_id === request.requestId ? (reply.type === "exit_plan_mode_resolved" ? "ok" : reply.type === "exit_plan_mode_response_failed" ? "fail" : "ignore") : "ignore"), ANSWER_WAIT_MS, options);
286
- const feedback = str(args.feedback);
287
- const told = responded.ok && feedback ? await sendSessionMessage(agentRoot, { session_id: row.id, message: feedback, notify_on_idle: "never" }, options) : null;
288
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_plan_answered", message: "answered a Copilot app session's plan", meta: { session: row.id, ok: responded.ok, approved } });
289
- return compact({ ok: responded.ok, approved, session_id: row.id, feedback_sent: told ? told.ok : undefined, error: responded.error });
290
- }
291
- /** Archive a session this agent created: its workspace when it has one (and the worktree with it), else the chat. */
292
- async function archiveSession(agentRoot, id, options = {}, ownerAsked = false) {
293
- const row = await resolve(id, options);
294
- const made = (0, store_1.readProbes)(agentRoot);
295
- let reason = null;
296
- if (!made[row.id]) {
297
- reason = ownerAsked ? "owner-asked" : (0, handoff_1.isHandedOff)(agentRoot, row) ? "handed-off" : null;
298
- if (!reason) {
299
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_archive_declined", message: "declined to archive a session this agent did not create", meta: { session: row.id } });
300
- throw new Error(`session ${row.id} was not created by this agent, so it will not archive it unless the owner asked for it or a newer session names it as handed off (yours: ${Object.keys(made).join(", ") || "none"})`);
301
- }
302
- }
303
- return archiveRow(agentRoot, row, reason, options);
304
- }
305
- /**
306
- * Ask the app to archive a session the caller has already decided may go, and log it when `reason` is set. The worktree
307
- * goes with it, so only call this for a session whose work is finished or was asked for in person.
308
- */
309
- async function archiveRow(agentRoot, row, reason, options = {}) {
310
- const archived = row.workspaceId
311
- ? await ask({ type: "archive_workspace", workspace_id: row.workspaceId, delete_worktree: row.workspaceType === "worktree" }, (reply, requestId) => (reply.request_id === requestId ? (reply.type === "workspace_archived" ? "ok" : "fail") : "ignore"), ARCHIVE_WAIT_MS, options)
312
- : await ask({ type: "archive_session", session_id: row.id }, (reply, requestId) => (reply.type === "general_chat_sessions_changed" ? "ok" : reply.request_id === requestId ? "fail" : "ignore"), ARCHIVE_WAIT_MS, options);
313
- if (archived.ok) {
314
- (0, store_1.removeProbe)(agentRoot, row.id);
315
- if (reason) {
316
- (0, store_1.addArchiveLog)(agentRoot, { id: row.id, name: row.name, at: new Date(options.now?.() ?? Date.now()).toISOString(), reason });
317
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_archived_not_created", message: "archived a session this agent did not create", meta: { session: row.id, reason } });
318
- }
319
- }
320
- else
321
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_archive_refused", message: "the Copilot app did not archive a session", meta: { session: row.id, error: archived.error } });
322
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_archived", message: "asked the Copilot app to archive a session", meta: { session: row.id, ok: archived.ok } });
323
- return compact({ ok: archived.ok, session_id: row.id, error: archived.error });
324
- }
325
- /** Show a session in the app's window, as following its link does. */
326
- async function navigateTo(id, options = {}) {
327
- const row = await resolve(id, options);
328
- const shown = await ask({ type: "handle_deep_link", url: (0, exports.appUrl)(row.id) }, reply => (reply.type === "deep_link_received" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
329
- return compact({ ok: shown.ok, session_id: row.id, app_url: (0, exports.appUrl)(row.id), error: shown.error });
330
- }
331
- // ---------- automations and workflows ----------
332
- /** Create or replace the automation that wakes a session, or clear it. */
333
- async function saveSessionAutomation(args, options = {}) {
334
- const row = await resolve(args.session_id, options);
335
- const settle = (reply, id) => (reply.request_id === id && /^session_automation_mutation_result$/.test(String(reply.type)) ? (reply.error ? "fail" : "ok") : "ignore");
336
- if (args.clear === true) {
337
- const owned = await ownedAutomations(row.id, options);
338
- const first = Array.isArray(owned.frame?.automations) ? owned.frame.automations.filter(isRecord)[0] : undefined;
339
- if (!str(first?.id))
340
- return { ok: false, error: owned.error ?? "that session has no automation to clear" };
341
- const cleared = await ask({ type: "cancel_session_automation", session_id: row.id, automation_id: first.id }, settle, REQUEST_WAIT_MS, options);
342
- return compact({ ok: cleared.ok, session_id: row.id, cleared: cleared.ok, error: cleared.error });
343
- }
344
- const keys = ["prompt", "interval", "run_at", "every_minutes", "schedule_hour", "schedule_day", "schedule_minute", "cron_expression", "name"];
345
- const saved = await ask({ type: "save_session_automation", session_id: row.id, ...Object.fromEntries(keys.filter(key => args[key] !== undefined).map(key => [key, args[key]])) }, settle, REQUEST_WAIT_MS, options);
346
- return compact({ ok: saved.ok, session_id: row.id, automation: saved.frame?.automation, error: saved.error });
347
- }
348
- const ownedAutomations = (session, options) => ask({ type: "list_owned_session_automations", session_id: session }, (reply, id) => (reply.request_id === id && reply.type === "owned_session_automations_result" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
349
- async function getSessionAutomation(id, options = {}) {
350
- const row = await resolve(id, options);
351
- const owned = await ownedAutomations(row.id, options);
352
- return compact({ ok: owned.ok, session_id: row.id, automations: owned.frame?.automations, schedules: owned.frame?.legacy_schedules, error: owned.error });
353
- }
354
- async function listWorkflows(options = {}) {
355
- const listed = await ask({ type: "list_workflows" }, (reply, id) => (reply.request_id === id && reply.type === "workflow_list" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
356
- return compact({ ok: listed.ok, workflows: listed.frame?.tasks, error: listed.error });
357
- }
358
- async function runWorkflow(id, options = {}) {
359
- const workflow = str(id);
360
- if (!workflow)
361
- throw new Error("name the workflow: its id, from list_workflows");
362
- const started = await ask({ type: "run_workflow_now", id: workflow }, reply => (reply.type === "workflow_run_started" ? "ok" : reply.type === "workflow_run_rejected" ? "fail" : "ignore"), REQUEST_WAIT_MS, options);
363
- return compact({ ok: started.ok, run: started.frame?.run, error: started.error });
364
- }
@@ -1,78 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.REPORT_SCAN_BYTES = void 0;
4
- exports.handoffSuccessors = handoffSuccessors;
5
- exports.reportTargets = reportTargets;
6
- exports.coordinatorOf = coordinatorOf;
7
- const runtime_1 = require("../../nerves/runtime");
8
- const client_1 = require("./client");
9
- const handoff_1 = require("./handoff");
10
- /**
11
- * Who coordinates a session now. The app records a coordinator once, when the session is made, and never lets another
12
- * session take that field over: when the coordinator hands off to a fresh successor and is archived, the field still
13
- * names the archived one, while the lanes have long been reporting to the successor. So the field alone is not the truth.
14
- * In order:
15
- *
16
- * - `app`: the session the app names, when it is still in the sidebar (by session id or project-session id);
17
- * - `hand-off`: that session's successor, when a hand-off names one that is listed (`successorOf`, owned by `handoff.ts`);
18
- * - `reports`: the listed session this lane last sent a message to with `send_session_message`, in the end of its history.
19
- *
20
- * `gone` means none of these finds one: only then may anyone say the lane has no coordinator.
21
- */
22
- exports.REPORT_SCAN_BYTES = 16 * 1024 * 1024;
23
- const SEND_TOOL = /(?:^|-)send_session_message$/;
24
- /** `successorOf` over the hand-offs the sense last recorded (`handoff.ts` refreshes them each minute), read once, when first needed. */
25
- function handoffSuccessors(agentRoot) {
26
- let successions = null;
27
- return id => (0, handoff_1.successorOf)(id, (successions ??= (0, handoff_1.readSuccessions)(agentRoot)));
28
- }
29
- const listedAs = (rows, id) => id ? rows.find(row => row.id === id || row.workspaceId === id) : undefined;
30
- /** The session ids this lane sent messages to, oldest first, from the end of its history. */
31
- function reportTargets(id, client = {}, maxBytes = exports.REPORT_SCAN_BYTES) {
32
- const targets = [];
33
- for (const line of (0, client_1.readEventLog)(id, { ...client, maxBytes }).text.split("\n")) {
34
- if (!line.includes("send_session_message"))
35
- continue;
36
- let event;
37
- try {
38
- event = JSON.parse(line);
39
- }
40
- catch {
41
- continue;
42
- }
43
- for (const request of event.data?.toolRequests ?? []) {
44
- if (typeof request?.name !== "string" || !SEND_TOOL.test(request.name))
45
- continue;
46
- let args = request.arguments;
47
- if (typeof args === "string") {
48
- try {
49
- args = JSON.parse(args);
50
- }
51
- catch {
52
- continue;
53
- }
54
- }
55
- const target = args?.session_id;
56
- if (typeof target === "string" && target)
57
- targets.push(target);
58
- }
59
- }
60
- return targets;
61
- }
62
- function coordinatorOf(row, rows, deps = {}) {
63
- const recorded = row.coordinatingCreatorSessionId;
64
- if (!recorded)
65
- return null;
66
- const named = listedAs(rows, recorded);
67
- if (named && named.id !== row.id)
68
- return { id: named.id, name: named.name, via: "app" };
69
- const successor = listedAs(rows, deps.successorOf?.(recorded));
70
- let found = successor && successor.id !== row.id ? { id: successor.id, name: successor.name, via: "hand-off" } : null;
71
- if (!found) {
72
- const latest = reportTargets(row.id, deps.client).reverse().map(id => listedAs(rows, id)).find(target => target && target.id !== row.id);
73
- if (latest)
74
- found = { id: latest.id, name: latest.name, via: "reports" };
75
- }
76
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_coordinator_resolved", message: "worked out who coordinates a lane whose recorded coordinator is not listed", meta: { session: row.id, recorded, found: found && "id" in found ? found.id : null, via: found && "via" in found ? found.via : null } });
77
- return found ?? { gone: true, recorded };
78
- }
@@ -1,177 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.readSuccessions = exports.FIRST_MESSAGE_SCAN_BYTES = exports.MESSAGE_HEAD_CHARS = exports.SUCCEEDS_LINE = void 0;
37
- exports.namedPredecessor = namedPredecessor;
38
- exports.refreshSuccessions = refreshSuccessions;
39
- exports.successorOf = successorOf;
40
- exports.isHandedOff = isHandedOff;
41
- const fs = __importStar(require("node:fs"));
42
- const path = __importStar(require("node:path"));
43
- const runtime_1 = require("../../nerves/runtime");
44
- const client_1 = require("./client");
45
- const store_1 = require("./store");
46
- /**
47
- * Who succeeds whom. A session that takes over another's job says so in its first message: the contract is a line of its
48
- * own, `Succeeds: <predecessor session id>`, within the message's first 16 KB. Kickoffs written before that line existed
49
- * are read too, when "successor to" or "successor of" opens the message and is followed closely by a session id, for
50
- * example `the successor to "desk epoch 3" (cfb84353-…)` or `the fresh successor to session 2fa5297c`.
51
- *
52
- * The first message sits after the start-up hooks' events, tens of KB into the history, so each history is read forward
53
- * at most 1 MB until its first message, once; after that only for the successor's first finished turn.
54
- */
55
- exports.SUCCEEDS_LINE = "Succeeds:";
56
- const STRUCTURED = /^[ \t>*_`]*Succeeds:[ \t*_`]*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/im;
57
- const FREE_TEXT = /\bsuccessor (?:to|of)\b/gi;
58
- const SESSION_ID = /\b[0-9a-f]{8}(?:-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})?\b/i;
59
- /** How much of the first message is read for the line. */
60
- exports.MESSAGE_HEAD_CHARS = 16_384;
61
- /** The free-text wording counts only where the message opens, and the id only close after it. */
62
- const FREE_TEXT_OPENING_CHARS = 2_000;
63
- const FREE_TEXT_ID_WINDOW = 240;
64
- /** How far into a history the first message is looked for, and the most read per pass while waiting for the first turn. */
65
- exports.FIRST_MESSAGE_SCAN_BYTES = 1024 * 1024;
66
- const stateFile = (agentRoot) => path.join((0, store_1.appSessionsStateDir)(agentRoot), "successions.json");
67
- const readSuccessions = (agentRoot) => (0, store_1.readJson)(stateFile(agentRoot), { sessions: {} }).sessions;
68
- exports.readSuccessions = readSuccessions;
69
- /** The session a first message says it succeeds: the `Succeeds:` line, else the older wording. `known` resolves a short id. */
70
- function namedPredecessor(message, self, known) {
71
- const head = message.slice(0, exports.MESSAGE_HEAD_CHARS);
72
- const line = STRUCTURED.exec(head)?.[1]?.toLowerCase();
73
- if (line && line !== self)
74
- return { predecessor: line, marker: "structured" };
75
- const opening = head.slice(0, FREE_TEXT_OPENING_CHARS);
76
- for (const phrase of opening.matchAll(FREE_TEXT)) {
77
- const after = head.slice(phrase.index + phrase[0].length, phrase.index + phrase[0].length + FREE_TEXT_ID_WINDOW);
78
- const id = SESSION_ID.exec(after)?.[0]?.toLowerCase();
79
- const resolved = id ? known(id) : null;
80
- if (resolved && resolved !== self)
81
- return { predecessor: resolved, marker: "free-text" };
82
- }
83
- return null;
84
- }
85
- const sessionsRoot = (client) => path.dirname(path.dirname((0, client_1.eventLogPath)("x", client)));
86
- function historyIds(client) {
87
- try {
88
- return fs.readdirSync(sessionsRoot(client)).filter(name => /^[0-9a-f-]{36}$/i.test(name));
89
- }
90
- catch {
91
- return [];
92
- }
93
- }
94
- /**
95
- * Read what is new in the history of each session the app lists, as far as succession needs, and remember only those,
96
- * plus each pending succession: one whose successor has left the sidebar while the session it succeeds is still listed,
97
- * so that session can still be retired. Anything else the app no longer lists drops out, and the record stays the size
98
- * of the sidebar.
99
- */
100
- function refreshSuccessions(agentRoot, client, listed) {
101
- const before = (0, exports.readSuccessions)(agentRoot);
102
- const live = new Set(listed);
103
- const ids = historyIds(client);
104
- const known = (value) => {
105
- const matches = ids.filter(id => id.toLowerCase().startsWith(value));
106
- return matches.length === 1 ? matches[0] : null;
107
- };
108
- const next = {};
109
- for (const [id, entry] of Object.entries(before))
110
- if (!live.has(id) && entry.predecessor && live.has(entry.predecessor))
111
- next[id] = entry;
112
- for (const id of live) {
113
- const was = before[id];
114
- if (was && !was.pending && (!was.predecessor || was.turned)) {
115
- next[id] = was;
116
- continue;
117
- }
118
- const entry = was ? { ...was } : { predecessor: null, offset: 0, pending: true };
119
- let message = null;
120
- let turned = false;
121
- const read = (0, client_1.readNewAppEvents)(id, entry.offset, exports.FIRST_MESSAGE_SCAN_BYTES, event => {
122
- if (event.agentId !== undefined)
123
- return;
124
- const data = event.data && typeof event.data === "object" ? event.data : {};
125
- if (entry.pending && !message && event.type === "user.message" && typeof data.content === "string")
126
- message = { text: data.content, ...(typeof event.timestamp === "string" ? { at: event.timestamp } : {}) };
127
- else if ((message || !entry.pending) && event.type === "assistant.turn_end")
128
- turned = true;
129
- }, client);
130
- entry.offset = read.offset;
131
- if (entry.pending) {
132
- const first = message;
133
- if (first) {
134
- delete entry.pending;
135
- const named = namedPredecessor(first.text, id, known);
136
- Object.assign(entry, named ?? {}, first.at ? { at: first.at } : {});
137
- }
138
- else if (entry.offset >= exports.FIRST_MESSAGE_SCAN_BYTES)
139
- delete entry.pending;
140
- }
141
- if (entry.predecessor && turned)
142
- entry.turned = true;
143
- next[id] = entry;
144
- }
145
- (0, store_1.writeJson)(stateFile(agentRoot), { sessions: next });
146
- return next;
147
- }
148
- /** The newest session that took over `id`'s job, following the chain of hand-offs to the live end; null when none did. */
149
- function successorOf(id, successions) {
150
- // The newest claim wins when two sessions name the same predecessor.
151
- const direct = (of) => {
152
- let newest = null;
153
- for (const [claimant, entry] of Object.entries(successions)) {
154
- const at = Date.parse(String(entry.at)) || 0;
155
- if (entry.predecessor === of && (!newest || at > newest.at))
156
- newest = { id: claimant, at };
157
- }
158
- return newest?.id ?? null;
159
- };
160
- let current = id;
161
- const seen = new Set([id]);
162
- for (let later = direct(current); later; later = direct(current)) {
163
- // Sessions that claim to succeed each other own nothing for certain, so none of them is retired.
164
- if (seen.has(later))
165
- return null;
166
- seen.add(later);
167
- current = later;
168
- }
169
- return current === id ? null : current;
170
- }
171
- /** Whether a newer session's first message names this one as the session it succeeds (the chain's live end, via `successorOf`). */
172
- function isHandedOff(agentRoot, row) {
173
- const successor = successorOf(row.id, (0, exports.readSuccessions)(agentRoot));
174
- if (successor)
175
- (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_handoff_found", message: "found the successor that a session was handed off to", meta: { session: row.id, successor } });
176
- return successor !== null;
177
- }