@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.
@@ -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.1175",
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.1175",
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.1175",
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
- }