@ouro.bot/cli 0.1.0-alpha.1172 → 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.
@@ -6,9 +6,9 @@
6
6
  <meta name="color-scheme" content="dark" />
7
7
  <title>Ouro Mailbox</title>
8
8
  <meta name="description" content="The daemon-hosted shared orientation surface for agents alive on this machine." />
9
- <script type="module" crossorigin src="/assets/index-DqdAt_p5.js"></script>
10
- <link rel="modulepreload" crossorigin href="/assets/vendor-mqLhL5Io.js">
11
- <link rel="stylesheet" crossorigin href="/assets/index-BI1pAais.css">
9
+ <script type="module" crossorigin src="/assets/index-CcfmfCyO.js"></script>
10
+ <link rel="modulepreload" crossorigin href="/assets/vendor-tRKTU6Ih.js">
11
+ <link rel="stylesheet" crossorigin href="/assets/index-JVa7jDQI.css">
12
12
  </head>
13
13
  <body>
14
14
  <div id="app"></div>
@@ -607,6 +607,7 @@ class AzureBlobMailroomStore {
607
607
  scanned,
608
608
  referenced: scanned - candidates.length,
609
609
  orphaned: candidates.length,
610
+ deletable: deleted,
610
611
  deleted: dryRun ? 0 : deleted,
611
612
  skippedYoung,
612
613
  dryRun,
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runHostedRawSweep = runHostedRawSweep;
4
+ const runtime_credentials_1 = require("../heart/runtime-credentials");
5
+ const runtime_1 = require("../nerves/runtime");
6
+ const reader_1 = require("./reader");
7
+ async function runHostedRawSweep(agentName, live) {
8
+ const freshRuntime = await (0, runtime_credentials_1.refreshRuntimeCredentialConfig)(agentName, { preserveCachedOnFailure: false });
9
+ if (!freshRuntime.ok) {
10
+ throw new Error(`mail raw sweep for ${agentName} requires fresh ${freshRuntime.itemPath}: ${freshRuntime.error}`);
11
+ }
12
+ const reader = (0, reader_1.resolveMailroomReader)(agentName);
13
+ if (!reader.ok)
14
+ throw new Error(reader.error);
15
+ const store = reader.store;
16
+ if (reader.storeKind !== "azure-blob" || typeof store.sweepOrphanedEncryptedRaw !== "function") {
17
+ throw new Error(`mail raw sweep for ${agentName} requires hosted Azure Mailroom; resolved ${reader.storeKind}`);
18
+ }
19
+ const result = await store.sweepOrphanedEncryptedRaw({ dryRun: !live });
20
+ (0, runtime_1.emitNervesEvent)({
21
+ component: "senses",
22
+ event: "senses.mail_raw_sweep_cli_completed",
23
+ message: "hosted mail raw orphan sweep completed",
24
+ meta: { agentName, ...result },
25
+ });
26
+ return [
27
+ `${live ? "swept" : "dry run (nothing deleted; rerun with --live to delete)"}: encrypted raw mail for ${agentName}`,
28
+ `encrypted raw objects scanned: ${result.scanned}`,
29
+ `kept, still referenced: ${result.referenced}`,
30
+ `orphans found: ${result.orphaned}`,
31
+ `kept, younger than the 24h grace: ${result.skippedYoung}`,
32
+ `${live ? "deleted" : "would delete"}: ${live ? result.deleted : result.deletable}`,
33
+ ].join("\n");
34
+ }
@@ -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.1172",
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.1172",
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.1172",
3
+ "version": "0.1.0-alpha.1174",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },