@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.
- package/changelog.json +12 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/heart/daemon/cli-exec.js +7 -0
- package/dist/heart/daemon/cli-gate.js +1 -1
- package/dist/heart/daemon/cli-help.js +7 -2
- package/dist/heart/daemon/cli-manifest.js +1 -0
- package/dist/heart/daemon/cli-parse.js +8 -1
- package/dist/mailbox-ui/assets/index-CcfmfCyO.js +1 -0
- package/dist/mailbox-ui/assets/index-JVa7jDQI.css +1 -0
- package/dist/mailbox-ui/assets/{vendor-mqLhL5Io.js → vendor-tRKTU6Ih.js} +10 -10
- package/dist/mailbox-ui/index.html +3 -3
- package/dist/mailroom/blob-store.js +1 -0
- package/dist/mailroom/sweep-orphans-cli.js +34 -0
- package/dist/repertoire/tools-app-sessions.js +63 -27
- package/dist/senses/app-sessions/client.js +4 -68
- package/dist/senses/app-sessions/digest-push.js +2 -2
- package/dist/senses/app-sessions/shepherd-cli.js +165 -0
- package/dist/senses/app-sessions/store.js +0 -17
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/mailbox-ui/assets/index-BI1pAais.css +0 -1
- package/dist/mailbox-ui/assets/index-DqdAt_p5.js +0 -1
- package/dist/senses/app-sessions/app-interface.js +0 -364
- package/dist/senses/app-sessions/coordinator.js +0 -78
- package/dist/senses/app-sessions/handoff.js +0 -177
|
@@ -1,364 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.appUrl = void 0;
|
|
37
|
-
exports.findSession = findSession;
|
|
38
|
-
exports.listSessionsAndChats = listSessionsAndChats;
|
|
39
|
-
exports.getSessionsStatus = getSessionsStatus;
|
|
40
|
-
exports.getSession = getSession;
|
|
41
|
-
exports.deliverMessage = deliverMessage;
|
|
42
|
-
exports.sendSessionMessage = sendSessionMessage;
|
|
43
|
-
exports.createSession = createSession;
|
|
44
|
-
exports.answerSessionInput = answerSessionInput;
|
|
45
|
-
exports.respondToSessionPlan = respondToSessionPlan;
|
|
46
|
-
exports.archiveSession = archiveSession;
|
|
47
|
-
exports.archiveRow = archiveRow;
|
|
48
|
-
exports.navigateTo = navigateTo;
|
|
49
|
-
exports.saveSessionAutomation = saveSessionAutomation;
|
|
50
|
-
exports.getSessionAutomation = getSessionAutomation;
|
|
51
|
-
exports.listWorkflows = listWorkflows;
|
|
52
|
-
exports.runWorkflow = runWorkflow;
|
|
53
|
-
const node_crypto_1 = require("node:crypto");
|
|
54
|
-
const os = __importStar(require("node:os"));
|
|
55
|
-
const runtime_1 = require("../../nerves/runtime");
|
|
56
|
-
const client_1 = require("./client");
|
|
57
|
-
const coordinator_1 = require("./coordinator");
|
|
58
|
-
const handoff_1 = require("./handoff");
|
|
59
|
-
const store_1 = require("./store");
|
|
60
|
-
/**
|
|
61
|
-
* The GitHub Copilot app's own interface, used the way a coordinating session uses its client tools: the same twelve
|
|
62
|
-
* operations, under the app's names, answering in the app's shapes. Each one is a request on the app's local WebSocket,
|
|
63
|
-
* the socket its own window speaks, and a reply read back from it. Nothing here reads the app's database or files.
|
|
64
|
-
*
|
|
65
|
-
* Three things a session gets from the app are not reachable from outside it. An outside client is anonymous: the app
|
|
66
|
-
* takes its messages for the person's, and ignores the creator and coordination fields on a create request, so a session
|
|
67
|
-
* made here has no coordinator and nothing reports back unless the sender watches it. A question or plan approval is
|
|
68
|
-
* announced once, to the clients connected then (see `prompts.ts`). `relay_session_input` and `publish_chat_update` act
|
|
69
|
-
* on the calling session's own conversation, which a client outside the app has none of.
|
|
70
|
-
*/
|
|
71
|
-
const REQUEST_WAIT_MS = 30_000;
|
|
72
|
-
const CREATE_WAIT_MS = 300_000;
|
|
73
|
-
const ARCHIVE_WAIT_MS = 60_000;
|
|
74
|
-
const ANSWER_WAIT_MS = 15_000;
|
|
75
|
-
const COORDINATION_NOTE = "an outside client cannot be a session's coordinator, so the app will not report back: replies come back to you through the app-sessions sense instead";
|
|
76
|
-
const isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
77
|
-
const str = (value) => (typeof value === "string" && value.length > 0 ? value : null);
|
|
78
|
-
const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== null && item !== undefined));
|
|
79
|
-
/** The link that opens a session in the app. */
|
|
80
|
-
const appUrl = (id) => `ghapp://sessions/${id}`;
|
|
81
|
-
exports.appUrl = appUrl;
|
|
82
|
-
const reasonOf = (frame) => str(frame.error) ?? str(frame.message) ?? str(frame.reason) ?? str(frame.detail) ?? String(frame.type);
|
|
83
|
-
/** Whether a sender wants a session's reply back, and for how long: once (the default), always, or never. */
|
|
84
|
-
const notifyMode = (value) => (value === "never" ? null : value === "always" ? "always" : "once");
|
|
85
|
-
/** One request and its answer: the frame `settle` calls "ok", or the reason it was refused, or that the app did not answer in time. */
|
|
86
|
-
async function ask(frame, settle, waitMs, options) {
|
|
87
|
-
// An answer carries the id of the request it answers; every other request gets its own.
|
|
88
|
-
const requestId = str(frame.request_id) ?? (0, node_crypto_1.randomUUID)();
|
|
89
|
-
const verdict = (reply) => (reply.type === "socket_error" || reply.type === "error" ? "fail" : settle(reply, requestId));
|
|
90
|
-
const got = await (0, client_1.exchange)([{ ...frame, request_id: requestId }], { keep: reply => verdict(reply) !== "ignore", done: reply => /^(ok|fail)$/.test(verdict(reply)), waitMs }, options);
|
|
91
|
-
const last = got.at(-1);
|
|
92
|
-
if (last && verdict(last) === "ok")
|
|
93
|
-
return { ok: true, frame: last, error: null };
|
|
94
|
-
return { ok: false, frame: last ?? null, error: last && verdict(last) === "fail" ? reasonOf(last) : "the app did not answer in time" };
|
|
95
|
-
}
|
|
96
|
-
/** A session by its id or its project-session (workspace) id, or a unique start of either; the first eight characters are enough. */
|
|
97
|
-
function findSession(rows, value) {
|
|
98
|
-
const wanted = str(value)?.trim() ?? "";
|
|
99
|
-
if (!wanted)
|
|
100
|
-
throw new Error("name a session: its id, or the start of it, from list_sessions_and_chats");
|
|
101
|
-
const exact = rows.find(row => row.id === wanted) ?? rows.find(row => row.workspaceId === wanted);
|
|
102
|
-
if (exact)
|
|
103
|
-
return exact;
|
|
104
|
-
const matches = rows.filter(row => row.id.startsWith(wanted) || row.workspaceId?.startsWith(wanted));
|
|
105
|
-
if (matches.length === 1)
|
|
106
|
-
return matches[0];
|
|
107
|
-
throw new Error(matches.length ? `'${wanted}' matches ${matches.length} sessions; give more of the id` : `no session '${wanted}' in the Copilot app (list_sessions_and_chats shows them)`);
|
|
108
|
-
}
|
|
109
|
-
const resolve = async (value, options) => findSession(await (0, client_1.listAppSessions)(options), value);
|
|
110
|
-
/**
|
|
111
|
-
* Who coordinates the session now, beside the app's own field, which keeps naming a coordinator that handed off and
|
|
112
|
-
* was archived (see `coordinator.ts`). Say a lane has no coordinator only when `coordinator_gone` is true.
|
|
113
|
-
*/
|
|
114
|
-
function coordination(row, rows, options, successors) {
|
|
115
|
-
const found = (0, coordinator_1.coordinatorOf)(row, rows, { client: options, ...(successors ? { successorOf: successors } : {}) });
|
|
116
|
-
if (!found)
|
|
117
|
-
return {};
|
|
118
|
-
if ("gone" in found)
|
|
119
|
-
return { coordinator_gone: true };
|
|
120
|
-
return { coordinator_session_id: found.id, coordinator_name: found.name, ...(found.via === "app" ? {} : { coordinator_found_by: found.via }) };
|
|
121
|
-
}
|
|
122
|
-
function item(row, rows, options, successors) {
|
|
123
|
-
return compact({
|
|
124
|
-
type: row.kind === "chat" ? "chat" : "session", id: row.id, app_url: (0, exports.appUrl)(row.id), name: row.name, project_id: row.projectId, project_name: row.project, project_repo: row.projectRepo,
|
|
125
|
-
branch: row.branch, path: row.path, created_at: row.createdAt, updated_at: row.updatedAt, creator_session_id: row.creatorSessionId,
|
|
126
|
-
coordinating_creator_session_id: row.coordinatingCreatorSessionId, ...coordination(row, rows, options, successors), parent_session_id: row.parentSessionId, is_running: row.isRunning, ...(row.remote ? { remote: true } : {}),
|
|
127
|
-
});
|
|
128
|
-
}
|
|
129
|
-
/** What an answer needs from a session blocked on something: the request's id and what it asks, or why the id is unknown. */
|
|
130
|
-
function awaitingInput(row, pending) {
|
|
131
|
-
const request = pending[row.id];
|
|
132
|
-
if (row.awaiting === "permission")
|
|
133
|
-
return { kind: "permission", request_id: row.prompt.requestId, what: row.prompt.what, note: "answer it in the app; the app's own tools do not answer permissions either" };
|
|
134
|
-
if (row.awaiting === "input" || row.awaiting === "plan") {
|
|
135
|
-
const kind = row.awaiting === "plan" ? "plan" : "user_input";
|
|
136
|
-
if (request && (request.kind === "plan") === (kind === "plan")) {
|
|
137
|
-
return compact({ kind, request_id: request.requestId, question: request.question, choices: request.choices, allow_freeform: request.allowFreeform, summary: request.summary, actions: request.actions });
|
|
138
|
-
}
|
|
139
|
-
return { kind, request_id: null, note: "it was asked while this agent was not connected to the app, which announces a question only once; the person can answer it in the app" };
|
|
140
|
-
}
|
|
141
|
-
return undefined;
|
|
142
|
-
}
|
|
143
|
-
function status(row, rows, pending, options, successors) {
|
|
144
|
-
const input = awaitingInput(row, pending);
|
|
145
|
-
return compact({
|
|
146
|
-
...item(row, rows, options, successors), was_interrupted: row.wasInterrupted || null,
|
|
147
|
-
activity: compact({ status: row.state === "working" ? "busy" : row.state, why: row.detail, last_activity: row.lastActivity }),
|
|
148
|
-
awaiting_user_input: row.awaiting === "input", awaiting_plan_approval: row.awaiting === "plan", awaiting_permission: row.awaiting === "permission",
|
|
149
|
-
awaiting_input: input,
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
// ---------- reading ----------
|
|
153
|
-
async function listSessionsAndChats(options = {}, agentRoot) {
|
|
154
|
-
const rows = await (0, client_1.listAppSessions)(options);
|
|
155
|
-
const successors = agentRoot ? (0, coordinator_1.handoffSuccessors)(agentRoot) : undefined;
|
|
156
|
-
return { total: rows.length, items: rows.map(row => item(row, rows, options, successors)) };
|
|
157
|
-
}
|
|
158
|
-
async function getSessionsStatus(agentRoot, state, options = {}) {
|
|
159
|
-
const rows = await (0, client_1.listAppSessions)(options);
|
|
160
|
-
const pending = (0, store_1.readPending)(agentRoot);
|
|
161
|
-
const successors = (0, coordinator_1.handoffSuccessors)(agentRoot);
|
|
162
|
-
const count = (keep) => rows.filter(keep).length;
|
|
163
|
-
return {
|
|
164
|
-
summary: {
|
|
165
|
-
total: rows.length, running: count(row => row.isRunning), busy: count(row => row.state === "working"), blocked: count(row => row.state === "waiting"), stuck: count(row => row.state === "stuck"),
|
|
166
|
-
awaiting_user_input: count(row => row.awaiting === "input"), awaiting_plan_approval: count(row => row.awaiting === "plan"),
|
|
167
|
-
},
|
|
168
|
-
sessions: rows.filter(row => !state || row.state === state || (state === "busy" && row.state === "working")).map(row => status(row, rows, pending, options, successors)),
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
async function getSession(agentRoot, id, options = {}) {
|
|
172
|
-
const rows = await (0, client_1.listAppSessions)(options);
|
|
173
|
-
return status(findSession(rows, id), rows, (0, store_1.readPending)(agentRoot), options, (0, coordinator_1.handoffSuccessors)(agentRoot));
|
|
174
|
-
}
|
|
175
|
-
// ---------- writing ----------
|
|
176
|
-
/** Put a message into a session, as its message box does, and wait for the app to accept it (a session that is not loaded loads first). */
|
|
177
|
-
async function deliverMessage(id, message, mode, options = {}) {
|
|
178
|
-
(0, client_1.assertSessionId)(id);
|
|
179
|
-
let interim = false;
|
|
180
|
-
const sent = await ask({ type: "send_message", session_id: id, prompt: message, delivery_mode: mode }, (reply, requestId) => {
|
|
181
|
-
if (/^session_message_(sent|queued)$/.test(String(reply.type)) && reply.request_id === requestId)
|
|
182
|
-
return "ok";
|
|
183
|
-
if (reply.type === "session_dispatch_state" && reply.request_id === requestId) {
|
|
184
|
-
interim ||= reply.dispatch_may_have_started === true;
|
|
185
|
-
return "wait";
|
|
186
|
-
}
|
|
187
|
-
return reply.request_id === requestId || (reply.session_id === id && /^session_(message_delivery_unknown|resume_failed)$/.test(String(reply.type))) ? "fail" : "ignore";
|
|
188
|
-
}, options.sendWaitMs ?? client_1.SEND_WAIT_MS, options);
|
|
189
|
-
const unconfirmed = !sent.ok && interim && sent.frame?.type === "session_dispatch_state";
|
|
190
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_sent", message: "sent a message into a Copilot app session", meta: { session: id, chars: message.length, ok: sent.ok } });
|
|
191
|
-
return unconfirmed ? { ...sent, error: "the app began delivering the message but had not confirmed it in time; read the session before sending it again" } : sent;
|
|
192
|
-
}
|
|
193
|
-
/** `send_session_message`. `notify_on_idle` brings the session's finished reply back to the sender. */
|
|
194
|
-
async function sendSessionMessage(agentRoot, args, options = {}) {
|
|
195
|
-
const message = typeof args.message === "string" ? args.message : "";
|
|
196
|
-
if (!message.trim())
|
|
197
|
-
throw new Error("say what to send");
|
|
198
|
-
const row = await resolve(args.session_id, options);
|
|
199
|
-
const offset = (0, client_1.eventLogSize)(row.id, options);
|
|
200
|
-
const sent = await deliverMessage(row.id, message, args.delivery_mode === "enqueue" ? "enqueue" : "immediate", options);
|
|
201
|
-
const notify = notifyMode(args.notify_on_idle);
|
|
202
|
-
const watching = sent.ok && notify !== null;
|
|
203
|
-
if (watching)
|
|
204
|
-
(0, store_1.watchSession)(agentRoot, row.id, row.name, offset, Date.now(), notify === "once");
|
|
205
|
-
return compact({ ok: sent.ok, status: sent.ok ? (sent.frame?.type === "session_message_queued" ? "queued" : "accepted") : "failed", session_id: row.id, name: row.name, message_id: str(sent.frame?.message_id), watching, error: sent.error });
|
|
206
|
-
}
|
|
207
|
-
/** The project a create request names: its id, or its name or repository as the app lists it. */
|
|
208
|
-
async function projectId(value, options) {
|
|
209
|
-
const listed = await ask({ type: "list_projects" }, reply => (reply.type === "project_list" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
|
|
210
|
-
const projects = Array.isArray(listed.frame?.projects) ? listed.frame.projects.filter(isRecord) : [];
|
|
211
|
-
const found = projects.find(project => project.id === value) ?? projects.find(project => project.name === value);
|
|
212
|
-
if (!found)
|
|
213
|
-
throw new Error(`no project '${value}' in the Copilot app${projects.length ? ` (it has: ${projects.map(project => str(project.name) ?? "?").join(", ")})` : ""}`);
|
|
214
|
-
return found.id;
|
|
215
|
-
}
|
|
216
|
-
/** Start a session: a project session in its own worktree (or on the project's checkout), or a standalone chat. */
|
|
217
|
-
async function createSession(agentRoot, args, options = {}) {
|
|
218
|
-
const kickoff = isRecord(args.kickoff) ? args.kickoff : {};
|
|
219
|
-
const prompt = str(kickoff.prompt);
|
|
220
|
-
const name = str(args.name);
|
|
221
|
-
const project = str(args.project_id);
|
|
222
|
-
const chat = args.session_kind === "chat" || (!project && args.session_kind !== "project");
|
|
223
|
-
if (!chat && !project)
|
|
224
|
-
throw new Error("a project session needs project_id (a project's id or name; list_sessions_and_chats shows project_id on its sessions)");
|
|
225
|
-
let created;
|
|
226
|
-
if (chat) {
|
|
227
|
-
created = await ask({ type: "create_session", cwd: os.homedir(), session_type: "general_chat", ...(str(kickoff.model) ? { model: str(kickoff.model) } : {}), ...(str(kickoff.agent) ? { agent: str(kickoff.agent) } : {}) }, (reply, id) => (reply.request_id === id ? (reply.type === "session_created" ? "ok" : "fail") : "ignore"), REQUEST_WAIT_MS, options);
|
|
228
|
-
}
|
|
229
|
-
else {
|
|
230
|
-
const worktree = args.workspace_type !== "branch";
|
|
231
|
-
created = await ask({
|
|
232
|
-
type: worktree ? "create_worktree_workspace" : "create_branch_workspace", project_id: await projectId(project, options),
|
|
233
|
-
...(worktree ? { branch_name: str(args.branch_name) ?? `ouro-${(0, node_crypto_1.randomUUID)().slice(0, 8)}`, checkout_existing_branch: false } : {}),
|
|
234
|
-
...(name ? { name } : {}), kickoff_permission_mode: str(kickoff.permission_mode) ?? "allow-all",
|
|
235
|
-
...(str(kickoff.model) ? { kickoff_model: str(kickoff.model) } : {}),
|
|
236
|
-
...(str(kickoff.agent) ? { kickoff_agent: str(kickoff.agent) } : {}), ...(str(kickoff.reasoning_effort) ? { kickoff_reasoning_effort: str(kickoff.reasoning_effort) } : {}),
|
|
237
|
-
}, (reply, id) => (reply.request_id === id ? (reply.type === "workspace_created" ? "ok" : reply.type === "workspace_changed" ? "wait" : "fail") : reply.type === "session_creation_failed" ? "fail" : "ignore"), CREATE_WAIT_MS, options);
|
|
238
|
-
// The app opens the workspace's session only for its own window, so an outside client opens it.
|
|
239
|
-
if (created.ok) {
|
|
240
|
-
const workspace = isRecord(created.frame.workspace) ? created.frame.workspace : {};
|
|
241
|
-
const workspaceId = str(workspace.id);
|
|
242
|
-
const cwd = str(workspace.displayPath);
|
|
243
|
-
if (workspaceId && cwd)
|
|
244
|
-
created = await ask({ type: "create_session", workspace_id: workspaceId, cwd }, (reply, id) => (reply.request_id === id ? (reply.type === "session_created" ? "ok" : "fail") : "ignore"), REQUEST_WAIT_MS, options);
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
const id = str(created.frame?.session_id);
|
|
248
|
-
if (!created.ok || !id)
|
|
249
|
-
return { ok: false, created: false, error: created.error ?? "the app did not name the session it made" };
|
|
250
|
-
(0, client_1.assertSessionId)(id);
|
|
251
|
-
(0, store_1.addProbe)(agentRoot, id, name, Date.now());
|
|
252
|
-
// The app does not run a kickoff for a client that is not its window ("ready for first message"), so the first message and mode are set here.
|
|
253
|
-
let sent = null;
|
|
254
|
-
if (chat && name)
|
|
255
|
-
await ask({ type: "rename_session", session_id: id, title: name }, reply => (reply.type === "session_title_updated" && reply.session_id === id ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
|
|
256
|
-
const mode = str(kickoff.mode);
|
|
257
|
-
if (mode && mode !== "interactive")
|
|
258
|
-
await ask({ type: "set_session_mode", session_id: id, mode }, reply => (reply.type === "session_mode_result" && reply.session_id === id ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
|
|
259
|
-
if (prompt)
|
|
260
|
-
sent = await sendSessionMessage(agentRoot, { session_id: id, message: prompt, notify_on_idle: args.notify_on_idle }, options);
|
|
261
|
-
const error = sent && !sent.ok ? `created, but the first message was not accepted: ${String(sent.error)}` : null;
|
|
262
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_created", message: "created a Copilot app session", meta: { session: id, chat, prompted: !!prompt } });
|
|
263
|
-
return compact({ ok: error === null, created: true, session_id: id, app_url: (0, exports.appUrl)(id), kind: chat ? "chat" : "session", workspace_id: str(created.frame?.workspace_id), watching: sent?.watching, coordination: COORDINATION_NOTE, error });
|
|
264
|
-
}
|
|
265
|
-
/** Answer a question a session asked with its ask_user tool. */
|
|
266
|
-
async function answerSessionInput(agentRoot, args, options = {}) {
|
|
267
|
-
const answer = typeof args.answer === "string" ? args.answer : "";
|
|
268
|
-
if (!answer)
|
|
269
|
-
throw new Error("give the answer");
|
|
270
|
-
const row = await resolve(args.session_id, options);
|
|
271
|
-
const request = (0, store_1.readPending)(agentRoot)[row.id];
|
|
272
|
-
if (row.awaiting !== "input" || request?.kind !== "input")
|
|
273
|
-
throw new Error(`session ${row.id} is not waiting on a question this agent heard asked (get_session shows what it waits on)`);
|
|
274
|
-
const answered = await ask({ type: "respond_to_user_input", session_id: row.id, request_id: request.requestId, answer, was_freeform: !(request.choices ?? []).includes(answer) }, reply => (reply.type === "user_input_resolved" && reply.request_id === request.requestId ? "ok" : "ignore"), ANSWER_WAIT_MS, options);
|
|
275
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_answered", message: "answered a Copilot app session's question", meta: { session: row.id, ok: answered.ok } });
|
|
276
|
-
return compact({ ok: answered.ok, session_id: row.id, error: answered.error });
|
|
277
|
-
}
|
|
278
|
-
/** Approve or reject a plan a session is paused on. */
|
|
279
|
-
async function respondToSessionPlan(agentRoot, args, options = {}) {
|
|
280
|
-
const row = await resolve(args.session_id, options);
|
|
281
|
-
const request = (0, store_1.readPending)(agentRoot)[row.id];
|
|
282
|
-
if (row.awaiting !== "plan" || request?.kind !== "plan")
|
|
283
|
-
throw new Error(`session ${row.id} is not waiting on a plan this agent heard presented (get_session shows what it waits on)`);
|
|
284
|
-
const approved = args.approved === true || args.approved === "true";
|
|
285
|
-
const responded = await ask({ type: "respond_to_exit_plan_mode", session_id: row.id, request_id: request.requestId, approved, ...(str(args.selected_action) ? { selected_action: str(args.selected_action) } : {}) }, reply => (reply.request_id === request.requestId ? (reply.type === "exit_plan_mode_resolved" ? "ok" : reply.type === "exit_plan_mode_response_failed" ? "fail" : "ignore") : "ignore"), ANSWER_WAIT_MS, options);
|
|
286
|
-
const feedback = str(args.feedback);
|
|
287
|
-
const told = responded.ok && feedback ? await sendSessionMessage(agentRoot, { session_id: row.id, message: feedback, notify_on_idle: "never" }, options) : null;
|
|
288
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_plan_answered", message: "answered a Copilot app session's plan", meta: { session: row.id, ok: responded.ok, approved } });
|
|
289
|
-
return compact({ ok: responded.ok, approved, session_id: row.id, feedback_sent: told ? told.ok : undefined, error: responded.error });
|
|
290
|
-
}
|
|
291
|
-
/** Archive a session this agent created: its workspace when it has one (and the worktree with it), else the chat. */
|
|
292
|
-
async function archiveSession(agentRoot, id, options = {}, ownerAsked = false) {
|
|
293
|
-
const row = await resolve(id, options);
|
|
294
|
-
const made = (0, store_1.readProbes)(agentRoot);
|
|
295
|
-
let reason = null;
|
|
296
|
-
if (!made[row.id]) {
|
|
297
|
-
reason = ownerAsked ? "owner-asked" : (0, handoff_1.isHandedOff)(agentRoot, row) ? "handed-off" : null;
|
|
298
|
-
if (!reason) {
|
|
299
|
-
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_archive_declined", message: "declined to archive a session this agent did not create", meta: { session: row.id } });
|
|
300
|
-
throw new Error(`session ${row.id} was not created by this agent, so it will not archive it unless the owner asked for it or a newer session names it as handed off (yours: ${Object.keys(made).join(", ") || "none"})`);
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
return archiveRow(agentRoot, row, reason, options);
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* Ask the app to archive a session the caller has already decided may go, and log it when `reason` is set. The worktree
|
|
307
|
-
* goes with it, so only call this for a session whose work is finished or was asked for in person.
|
|
308
|
-
*/
|
|
309
|
-
async function archiveRow(agentRoot, row, reason, options = {}) {
|
|
310
|
-
const archived = row.workspaceId
|
|
311
|
-
? await ask({ type: "archive_workspace", workspace_id: row.workspaceId, delete_worktree: row.workspaceType === "worktree" }, (reply, requestId) => (reply.request_id === requestId ? (reply.type === "workspace_archived" ? "ok" : "fail") : "ignore"), ARCHIVE_WAIT_MS, options)
|
|
312
|
-
: await ask({ type: "archive_session", session_id: row.id }, (reply, requestId) => (reply.type === "general_chat_sessions_changed" ? "ok" : reply.request_id === requestId ? "fail" : "ignore"), ARCHIVE_WAIT_MS, options);
|
|
313
|
-
if (archived.ok) {
|
|
314
|
-
(0, store_1.removeProbe)(agentRoot, row.id);
|
|
315
|
-
if (reason) {
|
|
316
|
-
(0, store_1.addArchiveLog)(agentRoot, { id: row.id, name: row.name, at: new Date(options.now?.() ?? Date.now()).toISOString(), reason });
|
|
317
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_archived_not_created", message: "archived a session this agent did not create", meta: { session: row.id, reason } });
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
else
|
|
321
|
-
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.app_sessions_archive_refused", message: "the Copilot app did not archive a session", meta: { session: row.id, error: archived.error } });
|
|
322
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_archived", message: "asked the Copilot app to archive a session", meta: { session: row.id, ok: archived.ok } });
|
|
323
|
-
return compact({ ok: archived.ok, session_id: row.id, error: archived.error });
|
|
324
|
-
}
|
|
325
|
-
/** Show a session in the app's window, as following its link does. */
|
|
326
|
-
async function navigateTo(id, options = {}) {
|
|
327
|
-
const row = await resolve(id, options);
|
|
328
|
-
const shown = await ask({ type: "handle_deep_link", url: (0, exports.appUrl)(row.id) }, reply => (reply.type === "deep_link_received" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
|
|
329
|
-
return compact({ ok: shown.ok, session_id: row.id, app_url: (0, exports.appUrl)(row.id), error: shown.error });
|
|
330
|
-
}
|
|
331
|
-
// ---------- automations and workflows ----------
|
|
332
|
-
/** Create or replace the automation that wakes a session, or clear it. */
|
|
333
|
-
async function saveSessionAutomation(args, options = {}) {
|
|
334
|
-
const row = await resolve(args.session_id, options);
|
|
335
|
-
const settle = (reply, id) => (reply.request_id === id && /^session_automation_mutation_result$/.test(String(reply.type)) ? (reply.error ? "fail" : "ok") : "ignore");
|
|
336
|
-
if (args.clear === true) {
|
|
337
|
-
const owned = await ownedAutomations(row.id, options);
|
|
338
|
-
const first = Array.isArray(owned.frame?.automations) ? owned.frame.automations.filter(isRecord)[0] : undefined;
|
|
339
|
-
if (!str(first?.id))
|
|
340
|
-
return { ok: false, error: owned.error ?? "that session has no automation to clear" };
|
|
341
|
-
const cleared = await ask({ type: "cancel_session_automation", session_id: row.id, automation_id: first.id }, settle, REQUEST_WAIT_MS, options);
|
|
342
|
-
return compact({ ok: cleared.ok, session_id: row.id, cleared: cleared.ok, error: cleared.error });
|
|
343
|
-
}
|
|
344
|
-
const keys = ["prompt", "interval", "run_at", "every_minutes", "schedule_hour", "schedule_day", "schedule_minute", "cron_expression", "name"];
|
|
345
|
-
const saved = await ask({ type: "save_session_automation", session_id: row.id, ...Object.fromEntries(keys.filter(key => args[key] !== undefined).map(key => [key, args[key]])) }, settle, REQUEST_WAIT_MS, options);
|
|
346
|
-
return compact({ ok: saved.ok, session_id: row.id, automation: saved.frame?.automation, error: saved.error });
|
|
347
|
-
}
|
|
348
|
-
const ownedAutomations = (session, options) => ask({ type: "list_owned_session_automations", session_id: session }, (reply, id) => (reply.request_id === id && reply.type === "owned_session_automations_result" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
|
|
349
|
-
async function getSessionAutomation(id, options = {}) {
|
|
350
|
-
const row = await resolve(id, options);
|
|
351
|
-
const owned = await ownedAutomations(row.id, options);
|
|
352
|
-
return compact({ ok: owned.ok, session_id: row.id, automations: owned.frame?.automations, schedules: owned.frame?.legacy_schedules, error: owned.error });
|
|
353
|
-
}
|
|
354
|
-
async function listWorkflows(options = {}) {
|
|
355
|
-
const listed = await ask({ type: "list_workflows" }, (reply, id) => (reply.request_id === id && reply.type === "workflow_list" ? "ok" : "ignore"), REQUEST_WAIT_MS, options);
|
|
356
|
-
return compact({ ok: listed.ok, workflows: listed.frame?.tasks, error: listed.error });
|
|
357
|
-
}
|
|
358
|
-
async function runWorkflow(id, options = {}) {
|
|
359
|
-
const workflow = str(id);
|
|
360
|
-
if (!workflow)
|
|
361
|
-
throw new Error("name the workflow: its id, from list_workflows");
|
|
362
|
-
const started = await ask({ type: "run_workflow_now", id: workflow }, reply => (reply.type === "workflow_run_started" ? "ok" : reply.type === "workflow_run_rejected" ? "fail" : "ignore"), REQUEST_WAIT_MS, options);
|
|
363
|
-
return compact({ ok: started.ok, run: started.frame?.run, error: started.error });
|
|
364
|
-
}
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.REPORT_SCAN_BYTES = void 0;
|
|
4
|
-
exports.handoffSuccessors = handoffSuccessors;
|
|
5
|
-
exports.reportTargets = reportTargets;
|
|
6
|
-
exports.coordinatorOf = coordinatorOf;
|
|
7
|
-
const runtime_1 = require("../../nerves/runtime");
|
|
8
|
-
const client_1 = require("./client");
|
|
9
|
-
const handoff_1 = require("./handoff");
|
|
10
|
-
/**
|
|
11
|
-
* Who coordinates a session now. The app records a coordinator once, when the session is made, and never lets another
|
|
12
|
-
* session take that field over: when the coordinator hands off to a fresh successor and is archived, the field still
|
|
13
|
-
* names the archived one, while the lanes have long been reporting to the successor. So the field alone is not the truth.
|
|
14
|
-
* In order:
|
|
15
|
-
*
|
|
16
|
-
* - `app`: the session the app names, when it is still in the sidebar (by session id or project-session id);
|
|
17
|
-
* - `hand-off`: that session's successor, when a hand-off names one that is listed (`successorOf`, owned by `handoff.ts`);
|
|
18
|
-
* - `reports`: the listed session this lane last sent a message to with `send_session_message`, in the end of its history.
|
|
19
|
-
*
|
|
20
|
-
* `gone` means none of these finds one: only then may anyone say the lane has no coordinator.
|
|
21
|
-
*/
|
|
22
|
-
exports.REPORT_SCAN_BYTES = 16 * 1024 * 1024;
|
|
23
|
-
const SEND_TOOL = /(?:^|-)send_session_message$/;
|
|
24
|
-
/** `successorOf` over the hand-offs the sense last recorded (`handoff.ts` refreshes them each minute), read once, when first needed. */
|
|
25
|
-
function handoffSuccessors(agentRoot) {
|
|
26
|
-
let successions = null;
|
|
27
|
-
return id => (0, handoff_1.successorOf)(id, (successions ??= (0, handoff_1.readSuccessions)(agentRoot)));
|
|
28
|
-
}
|
|
29
|
-
const listedAs = (rows, id) => id ? rows.find(row => row.id === id || row.workspaceId === id) : undefined;
|
|
30
|
-
/** The session ids this lane sent messages to, oldest first, from the end of its history. */
|
|
31
|
-
function reportTargets(id, client = {}, maxBytes = exports.REPORT_SCAN_BYTES) {
|
|
32
|
-
const targets = [];
|
|
33
|
-
for (const line of (0, client_1.readEventLog)(id, { ...client, maxBytes }).text.split("\n")) {
|
|
34
|
-
if (!line.includes("send_session_message"))
|
|
35
|
-
continue;
|
|
36
|
-
let event;
|
|
37
|
-
try {
|
|
38
|
-
event = JSON.parse(line);
|
|
39
|
-
}
|
|
40
|
-
catch {
|
|
41
|
-
continue;
|
|
42
|
-
}
|
|
43
|
-
for (const request of event.data?.toolRequests ?? []) {
|
|
44
|
-
if (typeof request?.name !== "string" || !SEND_TOOL.test(request.name))
|
|
45
|
-
continue;
|
|
46
|
-
let args = request.arguments;
|
|
47
|
-
if (typeof args === "string") {
|
|
48
|
-
try {
|
|
49
|
-
args = JSON.parse(args);
|
|
50
|
-
}
|
|
51
|
-
catch {
|
|
52
|
-
continue;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
const target = args?.session_id;
|
|
56
|
-
if (typeof target === "string" && target)
|
|
57
|
-
targets.push(target);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
return targets;
|
|
61
|
-
}
|
|
62
|
-
function coordinatorOf(row, rows, deps = {}) {
|
|
63
|
-
const recorded = row.coordinatingCreatorSessionId;
|
|
64
|
-
if (!recorded)
|
|
65
|
-
return null;
|
|
66
|
-
const named = listedAs(rows, recorded);
|
|
67
|
-
if (named && named.id !== row.id)
|
|
68
|
-
return { id: named.id, name: named.name, via: "app" };
|
|
69
|
-
const successor = listedAs(rows, deps.successorOf?.(recorded));
|
|
70
|
-
let found = successor && successor.id !== row.id ? { id: successor.id, name: successor.name, via: "hand-off" } : null;
|
|
71
|
-
if (!found) {
|
|
72
|
-
const latest = reportTargets(row.id, deps.client).reverse().map(id => listedAs(rows, id)).find(target => target && target.id !== row.id);
|
|
73
|
-
if (latest)
|
|
74
|
-
found = { id: latest.id, name: latest.name, via: "reports" };
|
|
75
|
-
}
|
|
76
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_coordinator_resolved", message: "worked out who coordinates a lane whose recorded coordinator is not listed", meta: { session: row.id, recorded, found: found && "id" in found ? found.id : null, via: found && "via" in found ? found.via : null } });
|
|
77
|
-
return found ?? { gone: true, recorded };
|
|
78
|
-
}
|
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.readSuccessions = exports.FIRST_MESSAGE_SCAN_BYTES = exports.MESSAGE_HEAD_CHARS = exports.SUCCEEDS_LINE = void 0;
|
|
37
|
-
exports.namedPredecessor = namedPredecessor;
|
|
38
|
-
exports.refreshSuccessions = refreshSuccessions;
|
|
39
|
-
exports.successorOf = successorOf;
|
|
40
|
-
exports.isHandedOff = isHandedOff;
|
|
41
|
-
const fs = __importStar(require("node:fs"));
|
|
42
|
-
const path = __importStar(require("node:path"));
|
|
43
|
-
const runtime_1 = require("../../nerves/runtime");
|
|
44
|
-
const client_1 = require("./client");
|
|
45
|
-
const store_1 = require("./store");
|
|
46
|
-
/**
|
|
47
|
-
* Who succeeds whom. A session that takes over another's job says so in its first message: the contract is a line of its
|
|
48
|
-
* own, `Succeeds: <predecessor session id>`, within the message's first 16 KB. Kickoffs written before that line existed
|
|
49
|
-
* are read too, when "successor to" or "successor of" opens the message and is followed closely by a session id, for
|
|
50
|
-
* example `the successor to "desk epoch 3" (cfb84353-…)` or `the fresh successor to session 2fa5297c`.
|
|
51
|
-
*
|
|
52
|
-
* The first message sits after the start-up hooks' events, tens of KB into the history, so each history is read forward
|
|
53
|
-
* at most 1 MB until its first message, once; after that only for the successor's first finished turn.
|
|
54
|
-
*/
|
|
55
|
-
exports.SUCCEEDS_LINE = "Succeeds:";
|
|
56
|
-
const STRUCTURED = /^[ \t>*_`]*Succeeds:[ \t*_`]*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b/im;
|
|
57
|
-
const FREE_TEXT = /\bsuccessor (?:to|of)\b/gi;
|
|
58
|
-
const SESSION_ID = /\b[0-9a-f]{8}(?:-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})?\b/i;
|
|
59
|
-
/** How much of the first message is read for the line. */
|
|
60
|
-
exports.MESSAGE_HEAD_CHARS = 16_384;
|
|
61
|
-
/** The free-text wording counts only where the message opens, and the id only close after it. */
|
|
62
|
-
const FREE_TEXT_OPENING_CHARS = 2_000;
|
|
63
|
-
const FREE_TEXT_ID_WINDOW = 240;
|
|
64
|
-
/** How far into a history the first message is looked for, and the most read per pass while waiting for the first turn. */
|
|
65
|
-
exports.FIRST_MESSAGE_SCAN_BYTES = 1024 * 1024;
|
|
66
|
-
const stateFile = (agentRoot) => path.join((0, store_1.appSessionsStateDir)(agentRoot), "successions.json");
|
|
67
|
-
const readSuccessions = (agentRoot) => (0, store_1.readJson)(stateFile(agentRoot), { sessions: {} }).sessions;
|
|
68
|
-
exports.readSuccessions = readSuccessions;
|
|
69
|
-
/** The session a first message says it succeeds: the `Succeeds:` line, else the older wording. `known` resolves a short id. */
|
|
70
|
-
function namedPredecessor(message, self, known) {
|
|
71
|
-
const head = message.slice(0, exports.MESSAGE_HEAD_CHARS);
|
|
72
|
-
const line = STRUCTURED.exec(head)?.[1]?.toLowerCase();
|
|
73
|
-
if (line && line !== self)
|
|
74
|
-
return { predecessor: line, marker: "structured" };
|
|
75
|
-
const opening = head.slice(0, FREE_TEXT_OPENING_CHARS);
|
|
76
|
-
for (const phrase of opening.matchAll(FREE_TEXT)) {
|
|
77
|
-
const after = head.slice(phrase.index + phrase[0].length, phrase.index + phrase[0].length + FREE_TEXT_ID_WINDOW);
|
|
78
|
-
const id = SESSION_ID.exec(after)?.[0]?.toLowerCase();
|
|
79
|
-
const resolved = id ? known(id) : null;
|
|
80
|
-
if (resolved && resolved !== self)
|
|
81
|
-
return { predecessor: resolved, marker: "free-text" };
|
|
82
|
-
}
|
|
83
|
-
return null;
|
|
84
|
-
}
|
|
85
|
-
const sessionsRoot = (client) => path.dirname(path.dirname((0, client_1.eventLogPath)("x", client)));
|
|
86
|
-
function historyIds(client) {
|
|
87
|
-
try {
|
|
88
|
-
return fs.readdirSync(sessionsRoot(client)).filter(name => /^[0-9a-f-]{36}$/i.test(name));
|
|
89
|
-
}
|
|
90
|
-
catch {
|
|
91
|
-
return [];
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Read what is new in the history of each session the app lists, as far as succession needs, and remember only those,
|
|
96
|
-
* plus each pending succession: one whose successor has left the sidebar while the session it succeeds is still listed,
|
|
97
|
-
* so that session can still be retired. Anything else the app no longer lists drops out, and the record stays the size
|
|
98
|
-
* of the sidebar.
|
|
99
|
-
*/
|
|
100
|
-
function refreshSuccessions(agentRoot, client, listed) {
|
|
101
|
-
const before = (0, exports.readSuccessions)(agentRoot);
|
|
102
|
-
const live = new Set(listed);
|
|
103
|
-
const ids = historyIds(client);
|
|
104
|
-
const known = (value) => {
|
|
105
|
-
const matches = ids.filter(id => id.toLowerCase().startsWith(value));
|
|
106
|
-
return matches.length === 1 ? matches[0] : null;
|
|
107
|
-
};
|
|
108
|
-
const next = {};
|
|
109
|
-
for (const [id, entry] of Object.entries(before))
|
|
110
|
-
if (!live.has(id) && entry.predecessor && live.has(entry.predecessor))
|
|
111
|
-
next[id] = entry;
|
|
112
|
-
for (const id of live) {
|
|
113
|
-
const was = before[id];
|
|
114
|
-
if (was && !was.pending && (!was.predecessor || was.turned)) {
|
|
115
|
-
next[id] = was;
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
const entry = was ? { ...was } : { predecessor: null, offset: 0, pending: true };
|
|
119
|
-
let message = null;
|
|
120
|
-
let turned = false;
|
|
121
|
-
const read = (0, client_1.readNewAppEvents)(id, entry.offset, exports.FIRST_MESSAGE_SCAN_BYTES, event => {
|
|
122
|
-
if (event.agentId !== undefined)
|
|
123
|
-
return;
|
|
124
|
-
const data = event.data && typeof event.data === "object" ? event.data : {};
|
|
125
|
-
if (entry.pending && !message && event.type === "user.message" && typeof data.content === "string")
|
|
126
|
-
message = { text: data.content, ...(typeof event.timestamp === "string" ? { at: event.timestamp } : {}) };
|
|
127
|
-
else if ((message || !entry.pending) && event.type === "assistant.turn_end")
|
|
128
|
-
turned = true;
|
|
129
|
-
}, client);
|
|
130
|
-
entry.offset = read.offset;
|
|
131
|
-
if (entry.pending) {
|
|
132
|
-
const first = message;
|
|
133
|
-
if (first) {
|
|
134
|
-
delete entry.pending;
|
|
135
|
-
const named = namedPredecessor(first.text, id, known);
|
|
136
|
-
Object.assign(entry, named ?? {}, first.at ? { at: first.at } : {});
|
|
137
|
-
}
|
|
138
|
-
else if (entry.offset >= exports.FIRST_MESSAGE_SCAN_BYTES)
|
|
139
|
-
delete entry.pending;
|
|
140
|
-
}
|
|
141
|
-
if (entry.predecessor && turned)
|
|
142
|
-
entry.turned = true;
|
|
143
|
-
next[id] = entry;
|
|
144
|
-
}
|
|
145
|
-
(0, store_1.writeJson)(stateFile(agentRoot), { sessions: next });
|
|
146
|
-
return next;
|
|
147
|
-
}
|
|
148
|
-
/** The newest session that took over `id`'s job, following the chain of hand-offs to the live end; null when none did. */
|
|
149
|
-
function successorOf(id, successions) {
|
|
150
|
-
// The newest claim wins when two sessions name the same predecessor.
|
|
151
|
-
const direct = (of) => {
|
|
152
|
-
let newest = null;
|
|
153
|
-
for (const [claimant, entry] of Object.entries(successions)) {
|
|
154
|
-
const at = Date.parse(String(entry.at)) || 0;
|
|
155
|
-
if (entry.predecessor === of && (!newest || at > newest.at))
|
|
156
|
-
newest = { id: claimant, at };
|
|
157
|
-
}
|
|
158
|
-
return newest?.id ?? null;
|
|
159
|
-
};
|
|
160
|
-
let current = id;
|
|
161
|
-
const seen = new Set([id]);
|
|
162
|
-
for (let later = direct(current); later; later = direct(current)) {
|
|
163
|
-
// Sessions that claim to succeed each other own nothing for certain, so none of them is retired.
|
|
164
|
-
if (seen.has(later))
|
|
165
|
-
return null;
|
|
166
|
-
seen.add(later);
|
|
167
|
-
current = later;
|
|
168
|
-
}
|
|
169
|
-
return current === id ? null : current;
|
|
170
|
-
}
|
|
171
|
-
/** Whether a newer session's first message names this one as the session it succeeds (the chain's live end, via `successorOf`). */
|
|
172
|
-
function isHandedOff(agentRoot, row) {
|
|
173
|
-
const successor = successorOf(row.id, (0, exports.readSuccessions)(agentRoot));
|
|
174
|
-
if (successor)
|
|
175
|
-
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.app_sessions_handoff_found", message: "found the successor that a session was handed off to", meta: { session: row.id, successor } });
|
|
176
|
-
return successor !== null;
|
|
177
|
-
}
|