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

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,18 @@
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.1175",
6
+ "changes": [
7
+ "The daemon survives a vault outage at startup instead of crash-looping. When the vault does not answer (timeout, refused or reset connection, DNS failure), provider readiness no longer aborts startup: the agent is marked degraded as `vault:<agent>` in daemon health and the vault is retried with capped backoff until it answers. Rejections from a reachable vault (locked, wrong password, missing credential) still fail startup, and `ouro mail sweep-orphans` still requires a fresh vault read. No credentials are cached on disk. The Unraid template follows the release version."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1174",
12
+ "changes": [
13
+ "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."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1173",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1173",
2
+ "runtimeVersion": "0.1.0-alpha.1175",
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.1175</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.isTransientVaultError = isTransientVaultError;
36
37
  exports.vaultUnlockOrRecoverFix = vaultUnlockOrRecoverFix;
37
38
  exports.checkAgentConfig = checkAgentConfig;
38
39
  exports.checkAgentConfigWithProviderHealth = checkAgentConfigWithProviderHealth;
@@ -209,6 +210,10 @@ function isTransientVaultError(error) {
209
210
  const normalized = error.toLowerCase();
210
211
  return (normalized.includes("timed out") ||
211
212
  normalized.includes("econnrefused") ||
213
+ normalized.includes("econnreset") ||
214
+ normalized.includes("enotfound") ||
215
+ normalized.includes("eai_again") ||
216
+ normalized.includes("ehostunreach") ||
212
217
  normalized.includes("socket hang up") ||
213
218
  normalized.includes("etimedout"));
214
219
  }
@@ -241,6 +246,7 @@ function invalidPoolResult(agentName, lane, provider, model, pool) {
241
246
  ok: false,
242
247
  error: `${lane} provider ${provider} model ${model} cannot read provider credentials from ${agentName}'s vault: ${pool.error}`,
243
248
  fix: `Vault read timed out -- this usually resolves on retry. Run 'ouro up' again.`,
249
+ vaultUnreachable: true,
244
250
  };
245
251
  }
246
252
  if (pool.reason === "unavailable" && isVaultLockedError(pool.error)) {
@@ -79,6 +79,7 @@ const context_loss_sentinel_1 = require("../context-loss-sentinel");
79
79
  const provider_credentials_1 = require("../provider-credentials");
80
80
  const runtime_credentials_1 = require("../runtime-credentials");
81
81
  const machine_identity_1 = require("../machine-identity");
82
+ const vault_outage_1 = require("./vault-outage");
82
83
  const container_credential_bootstrap_1 = require("./container-credential-bootstrap");
83
84
  const daemon_bootstrap_startup_1 = require("./daemon-bootstrap-startup");
84
85
  const sanctuary_package_management_1 = require("./sanctuary-package-management");
@@ -713,42 +714,48 @@ function writeStopCommandHealthState() {
713
714
  // Health writes are best-effort during shutdown.
714
715
  }
715
716
  }
717
+ /* v8 ignore start -- degraded-component bookkeeping wiring; retry/backoff logic is tested in vault-outage.test.ts @preserve */
718
+ function setVaultDegraded(agent, reason) {
719
+ const component = `vault:${agent}`;
720
+ const fullReason = `${reason}. Fix: the agent's vault is unreachable; the daemon stays up and retries. Run 'ouro doctor' if this persists.`;
721
+ const existing = degradedComponents.find((entry) => entry.component === component);
722
+ if (existing)
723
+ existing.reason = fullReason;
724
+ else
725
+ degradedComponents.push({ component, reason: fullReason, since: new Date().toISOString() });
726
+ }
727
+ function clearVaultDegraded(agent) {
728
+ const index = degradedComponents.findIndex((entry) => entry.component === `vault:${agent}`);
729
+ if (index >= 0)
730
+ degradedComponents.splice(index, 1);
731
+ }
732
+ /* v8 ignore stop */
733
+ async function checkProviderRuntime(agent) {
734
+ try {
735
+ await (0, runtime_credentials_1.refreshRuntimeCredentialConfig)(agent, { preserveCachedOnFailure: true });
736
+ // Read from the same vault listing: whether this machine has config or not, the
737
+ // daemon then knows, and its bootstrap spares each worker and sense a vault CLI run.
738
+ await (0, runtime_credentials_1.refreshMachineRuntimeCredentialConfig)(agent, daemonMachineId, { preserveCachedOnFailure: true });
739
+ // The ping runs in a child process, so the provider SDK it loads doesn't stay in the daemon.
740
+ return await (0, agent_config_check_1.checkAgentConfigWithProviderHealth)(agent, (0, identity_1.getAgentBundlesRoot)(), { pingProvider: provider_ping_child_1.pingProviderInChild });
741
+ }
742
+ catch {
743
+ (0, runtime_1.emitNervesEvent)({
744
+ level: "warn",
745
+ component: "daemon",
746
+ event: "daemon.provider_readiness_unavailable",
747
+ message: "fresh provider readiness check failed before daemon startup",
748
+ meta: { agent },
749
+ });
750
+ throw new Error("provider runtime preparation failed");
751
+ }
752
+ }
716
753
  async function prepareProviderRuntime() {
717
- const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
718
- const readiness = await Promise.all(readinessAgents.map(async (agent) => {
719
- try {
720
- await (0, runtime_credentials_1.refreshRuntimeCredentialConfig)(agent, { preserveCachedOnFailure: true });
721
- // Read from the same vault listing: whether this machine has config or not, the
722
- // daemon then knows, and its bootstrap spares each worker and sense a vault CLI run.
723
- await (0, runtime_credentials_1.refreshMachineRuntimeCredentialConfig)(agent, daemonMachineId, { preserveCachedOnFailure: true });
724
- // The ping runs in a child process, so the provider SDK it loads doesn't stay in the daemon.
725
- const result = await (0, agent_config_check_1.checkAgentConfigWithProviderHealth)(agent, bundlesRoot, { pingProvider: provider_ping_child_1.pingProviderInChild });
726
- if (result.ok)
727
- return null;
728
- (0, runtime_1.emitNervesEvent)({
729
- level: "warn",
730
- component: "daemon",
731
- event: "daemon.provider_readiness_unavailable",
732
- message: "fresh provider readiness was unavailable before daemon startup",
733
- meta: { agent },
734
- });
735
- return result.issue ?? {
736
- summary: `${agent}: provider runtime unavailable`,
737
- actions: [{ actor: "agent-runnable", command: "ouro doctor" }],
738
- };
739
- }
740
- catch {
741
- (0, runtime_1.emitNervesEvent)({
742
- level: "warn",
743
- component: "daemon",
744
- event: "daemon.provider_readiness_unavailable",
745
- message: "fresh provider readiness check failed before daemon startup",
746
- meta: { agent },
747
- });
748
- throw new Error("provider runtime preparation failed");
749
- }
750
- }));
751
- const failures = readiness.filter((entry) => entry !== null);
754
+ const failures = await (0, vault_outage_1.prepareProviderRuntimeTolerantOfVaultOutage)(readinessAgents, {
755
+ check: checkProviderRuntime,
756
+ onDegraded: setVaultDegraded,
757
+ onRecovered: clearVaultDegraded,
758
+ });
752
759
  if (failures.length > 0) {
753
760
  throw (0, daemon_bootstrap_startup_1.createProviderReadinessPreparationFailure)(failures);
754
761
  }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareProviderRuntimeTolerantOfVaultOutage = prepareProviderRuntimeTolerantOfVaultOutage;
4
+ const runtime_1 = require("../../nerves/runtime");
5
+ const DEFAULT_INITIAL_DELAY_MS = 5_000;
6
+ const DEFAULT_MAX_DELAY_MS = 5 * 60_000;
7
+ /**
8
+ * Boot-time provider readiness that tolerates an unreachable vault. A vault that
9
+ * answers with a rejection (locked, missing, wrong credentials) is still a failure;
10
+ * one that doesn't answer degrades that agent and retries with backoff instead of
11
+ * taking the whole daemon down.
12
+ */
13
+ async function prepareProviderRuntimeTolerantOfVaultOutage(agents, deps) {
14
+ const results = await Promise.all(agents.map(async (agent) => {
15
+ const result = await deps.check(agent);
16
+ if (result.ok)
17
+ return null;
18
+ if (result.vaultUnreachable) {
19
+ beginVaultOutageRecovery(agent, result.error ?? "vault unreachable", deps);
20
+ return null;
21
+ }
22
+ (0, runtime_1.emitNervesEvent)({
23
+ level: "warn",
24
+ component: "daemon",
25
+ event: "daemon.provider_readiness_unavailable",
26
+ message: "fresh provider readiness was unavailable before daemon startup",
27
+ meta: { agent },
28
+ });
29
+ return result.issue ?? {
30
+ summary: `${agent}: provider runtime unavailable`,
31
+ actions: [{ actor: "agent-runnable", command: "ouro doctor" }],
32
+ };
33
+ }));
34
+ return results.filter((entry) => entry !== null);
35
+ }
36
+ function beginVaultOutageRecovery(agent, reason, deps) {
37
+ const schedule = deps.schedule ?? ((run, delayMs) => setTimeout(run, delayMs));
38
+ const maxDelayMs = deps.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
39
+ let delayMs = deps.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
40
+ deps.onDegraded(agent, reason);
41
+ (0, runtime_1.emitNervesEvent)({
42
+ level: "warn",
43
+ component: "daemon",
44
+ event: "daemon.vault_unreachable_degraded",
45
+ message: "vault unreachable at startup; daemon stays up in degraded mode and retries with backoff",
46
+ meta: { agent, reason },
47
+ });
48
+ const attempt = () => {
49
+ void deps.check(agent).then((result) => {
50
+ if (result.ok) {
51
+ deps.onRecovered(agent);
52
+ (0, runtime_1.emitNervesEvent)({
53
+ component: "daemon",
54
+ event: "daemon.vault_recovered",
55
+ message: "vault reachable again; agent left degraded mode",
56
+ meta: { agent },
57
+ });
58
+ return;
59
+ }
60
+ // A rejection (not just silence) needs a human; it stays degraded and visible while we keep retrying slowly.
61
+ deps.onDegraded(agent, result.error ?? reason);
62
+ scheduleNext();
63
+ }).catch((error) => {
64
+ deps.onDegraded(agent, error instanceof Error ? error.message : String(error));
65
+ scheduleNext();
66
+ });
67
+ };
68
+ const scheduleNext = () => {
69
+ const handle = schedule(attempt, delayMs);
70
+ handle?.unref?.();
71
+ delayMs = Math.min(delayMs * 2, maxDelayMs);
72
+ };
73
+ scheduleNext();
74
+ }
@@ -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
  }