@conveno/cli 0.2.0-rc.1 → 0.2.0-rc.11
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/README.md +26 -29
- package/dist/acp-BOSDOzU7.js +82 -0
- package/dist/agy-relay-BUo9uRng.js +137 -0
- package/dist/args-C1eX8Ixk.js +361 -0
- package/dist/bin.js +4 -4
- package/dist/ctx-tYftvhz_.js +17 -0
- package/dist/daemon.js +490 -1153
- package/dist/daemonError-DraepwsB.js +66 -0
- package/dist/dist-BRjg9CLd.js +731 -0
- package/dist/dist-DEjU_KXC.js +969 -0
- package/dist/{dist-CWvQqhPj.js → dist-Dg2IY9OA.js} +1 -1
- package/dist/dist-KWlFKO7H.js +645 -0
- package/dist/{acp-BlKK0v-B.js → dist-Rdj5ogAX.js} +41 -288
- package/dist/dist-Y0JDSJP_.js +667 -0
- package/dist/{dist-DsRTUePN.js → dist-n6XMTlyN.js} +6 -14
- package/dist/{dist-_qrCNXUP.js → dist-qONHJRJk.js} +817 -1289
- package/dist/fmt-C2SsP5Y0.js +96 -0
- package/dist/{hook-bfp9_AVT.js → hook-CDF1A8AY.js} +31 -22
- package/dist/hook-entry-BYvXWDJv.js +1320 -0
- package/dist/hook-entry-D2CAJsq-.js +1 -0
- package/dist/main-EqfI0btx.js +650 -0
- package/dist/pick-B-axJvgf.js +9 -0
- package/dist/run-CtGfzzwB.js +5568 -0
- package/dist/runtime-BDNmkbsS.js +770 -0
- package/dist/{dist-D8gPpZKN.js → toml-patch-DGzVRdd1.js} +20 -1889
- package/dist/{main-sIWDc4jt.js → uninstall-Blt-KHI5.js} +628 -1495
- package/dist/watch-CuZ7jPVd.js +185 -0
- package/package.json +21 -16
- package/dist/args-DHkLY6_f.js +0 -513
- package/dist/dist-DcmKjrmu.js +0 -271
- package/dist/hook-entry-Daxws9EC.js +0 -1
- package/dist/hook-entry-RlH2cG3S.js +0 -1289
- package/dist/runtime-5nEur1P5.js +0 -1505
package/dist/daemon.js
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { homedir, hostname, userInfo } from "node:os";
|
|
3
|
-
import {
|
|
3
|
+
import { t as codexAdapter } from "./dist-DEjU_KXC.js";
|
|
4
|
+
import { An as parseIpcRequest, C as bindAccountDevice, Cn as isSocketPathTooLong, Ct as proofsMatch, D as clientProof, Dn as newDeviceId, E as clearOrchestrator, En as makeResult, Et as readAncestry, F as dataPaths, I as decideAutoContinue, J as formatHookContext, Jt as takeWithinBytes, Kt as statusAfterLiveness, L as defaultProcessIo, Lt as resolveRecipient, M as currentAccessToken, Mn as safeParse, N as daemonProof, Nn as sanitizeLine, On as newMessageId, Ot as readInbox, P as dataDir, Pn as socketPathTooLongMessage, Pt as requeueEntries, R as detectRepo, S as baseName, Tn as makeEventNotification, Tt as readAccountTokens, U as evaluateLiveness, V as effectiveHolder, X as generateSessionName, Xt as tooManyUnreadMessage, Yt as takeWithinChars, Z as holderAfterDeparture, Zt as turnHops, b as autoCandidates, bn as defaultSocketPath, ct as markDelivered, en as validateRename, fn as OWNER_SESSION_ID, gt as pendingForInjection, hn as RpcErrorCode, j as createWmiWalker, jn as parseRelayFrame, kn as newSessionId, kt as readSettings, l as RESPONSE_BUDGET_BYTES, mn as RelayPayload, n as AccountError, nt as jwtClaim, on as DeviceId, p as ackEntries, pn as PROTOCOL_VERSION, q as formatContinuation, r as ConvenoError, sn as EVENT_NAMES, tt as isOnline, un as Message, ut as newAuthNonce, vn as SessionId, w as claimOrchestrator, wn as makeError, x as autoLimitsFromEnv, xn as encodeFrame, xt as planSpawn, yn as createLineDecoder } from "./dist-qONHJRJk.js";
|
|
4
5
|
import { randomBytes } from "node:crypto";
|
|
5
6
|
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
7
|
import { connect, createServer } from "node:net";
|
|
7
8
|
import { dirname, join, posix, win32 } from "node:path";
|
|
8
|
-
import { n as
|
|
9
|
-
import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-CWvQqhPj.js";
|
|
9
|
+
import { _ as sasMatches, a as JoinerPairing, b as signRelayHello, c as decodePairMessage, d as forkPoint, f as generateIdentity, g as publicRecord, h as parseIdentity, i as InviterPairing, l as deviceFingerprint, m as openEnvelope, n as ENVELOPE_MAX_AGE_MS, o as appendRevoke, p as headMatches, r as ENVELOPE_MAX_FUTURE_MS, s as chainHead, t as CryptoError, u as encodePairMessage, v as sealEnvelope, x as verifyChain, y as serializeIdentity } from "./dist-Dg2IY9OA.js";
|
|
10
10
|
import { execFileSync } from "node:child_process";
|
|
11
11
|
import { DatabaseSync } from "node:sqlite";
|
|
12
|
-
import { c as claudeTranscript, i as codexTranscript, t as openCodeTranscript } from "./dist-D8gPpZKN.js";
|
|
13
|
-
import { readFile, readdir, stat } from "node:fs/promises";
|
|
14
12
|
// ../daemon/src/lifecycle.ts
|
|
15
13
|
/** Thrown when another Conveno daemon already owns the lock file or answers on the socket. */
|
|
16
14
|
var DaemonAlreadyRunningError = class extends Error {
|
|
@@ -160,75 +158,6 @@ function createDaemonLog(path, opts = {}) {
|
|
|
160
158
|
}
|
|
161
159
|
};
|
|
162
160
|
}
|
|
163
|
-
// ../daemon/src/peek.ts
|
|
164
|
-
/** Longest text of one turn that is returned. A tool output is cut to this. */
|
|
165
|
-
const PEEK_TURN_MAX_CHARS = 4e3;
|
|
166
|
-
/**
|
|
167
|
-
* Longest text of one turn that is redacted. A larger one is cut first, at a word boundary, so the
|
|
168
|
-
* redaction pass stays fast. The cut can only remove the end of a secret, never expose more.
|
|
169
|
-
*/
|
|
170
|
-
const PEEK_REDACT_INPUT_MAX = 2e5;
|
|
171
|
-
const CLIP = "\n[clipped]";
|
|
172
|
-
/** Cut `text` to at most `max` characters, at a word boundary when one is near. */
|
|
173
|
-
function clip$1(text, max, marker = CLIP) {
|
|
174
|
-
if (text.length <= max) return text;
|
|
175
|
-
const room = Math.max(0, max - marker.length);
|
|
176
|
-
let cut = text.slice(0, room);
|
|
177
|
-
const space = cut.search(/\s\S*$/);
|
|
178
|
-
if (space > room - 80 && space > 0) cut = cut.slice(0, space);
|
|
179
|
-
return cut + marker;
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* Drop control characters other than tab and newline, and invisible direction and zero-width
|
|
183
|
-
* characters: a transcript can carry terminal escapes, and the reader may show this text.
|
|
184
|
-
*/
|
|
185
|
-
function stripControl(text) {
|
|
186
|
-
let out = "";
|
|
187
|
-
for (const ch of text) {
|
|
188
|
-
const c = ch.codePointAt(0);
|
|
189
|
-
if (!(c < 32 && c !== 9 && c !== 10 || c >= 127 && c <= 159 || c >= 8203 && c <= 8207 || c >= 8232 && c <= 8238 || c >= 8294 && c <= 8297 || c === 65279)) out += ch;
|
|
190
|
-
}
|
|
191
|
-
return out;
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Turn what a reader returned into the wire result: redact every turn (always), clip each turn,
|
|
195
|
-
* then keep the newest turns that fit in `maxChars`. Redaction runs on the whole turn text before
|
|
196
|
-
* it is clipped, so a secret is never cut in the middle and left half visible.
|
|
197
|
-
*/
|
|
198
|
-
function preparePeek(entries, more, maxChars) {
|
|
199
|
-
let redactions = 0;
|
|
200
|
-
let truncated = more;
|
|
201
|
-
const perTurn = Math.min(PEEK_TURN_MAX_CHARS, maxChars);
|
|
202
|
-
const prepared = entries.map((e) => {
|
|
203
|
-
const raw = stripControl(e.text);
|
|
204
|
-
const input = clip$1(raw, PEEK_REDACT_INPUT_MAX, "");
|
|
205
|
-
const { text, findings } = redactWithReport(input);
|
|
206
|
-
for (const n of Object.values(findings)) redactions += n;
|
|
207
|
-
const clipped = clip$1(text, perTurn);
|
|
208
|
-
if (clipped !== text || input !== raw) truncated = true;
|
|
209
|
-
return {
|
|
210
|
-
role: e.role,
|
|
211
|
-
text: clipped,
|
|
212
|
-
...e.at ? { at: e.at } : {}
|
|
213
|
-
};
|
|
214
|
-
});
|
|
215
|
-
const kept = [];
|
|
216
|
-
let total = 0;
|
|
217
|
-
for (let i = prepared.length - 1; i >= 0; i--) {
|
|
218
|
-
const t = prepared[i];
|
|
219
|
-
if (total + t.text.length > maxChars) {
|
|
220
|
-
truncated = true;
|
|
221
|
-
break;
|
|
222
|
-
}
|
|
223
|
-
total += t.text.length;
|
|
224
|
-
kept.unshift(t);
|
|
225
|
-
}
|
|
226
|
-
return {
|
|
227
|
-
turns: kept,
|
|
228
|
-
truncated,
|
|
229
|
-
redactions
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
161
|
const HANDSHAKE_TIMEOUT_MS = 15e3;
|
|
233
162
|
/**
|
|
234
163
|
* One WebSocket to the relay: challenge, signed hello, then frames. It does not reconnect by
|
|
@@ -1155,8 +1084,9 @@ var RelayHub = class {
|
|
|
1155
1084
|
this.state.hold(id, from, p, since);
|
|
1156
1085
|
return;
|
|
1157
1086
|
}
|
|
1158
|
-
const
|
|
1159
|
-
|
|
1087
|
+
const isOwner = p.message.from === OWNER_SESSION_ID;
|
|
1088
|
+
const sender = isOwner ? void 0 : r.sessions.find((s) => s.id === p.message.from);
|
|
1089
|
+
if (!isOwner && !sender) {
|
|
1160
1090
|
this.bounce(from, p, "unknown_sender");
|
|
1161
1091
|
return;
|
|
1162
1092
|
}
|
|
@@ -1165,14 +1095,20 @@ var RelayHub = class {
|
|
|
1165
1095
|
return;
|
|
1166
1096
|
}
|
|
1167
1097
|
const device = this.chainState?.members.get(from)?.name ?? r.deviceName;
|
|
1168
|
-
const
|
|
1098
|
+
const { fromCli: _c, ...rest } = p.message;
|
|
1099
|
+
const message = sender ? {
|
|
1169
1100
|
...p.message,
|
|
1170
1101
|
from: this.state.alias(from, sender.id),
|
|
1171
1102
|
to: p.toSession,
|
|
1172
1103
|
fromName: remoteSessionName(sender.name, device),
|
|
1173
1104
|
fromCli: sender.cli
|
|
1105
|
+
} : {
|
|
1106
|
+
...rest,
|
|
1107
|
+
from: OWNER_SESSION_ID,
|
|
1108
|
+
to: p.toSession,
|
|
1109
|
+
fromName: "you"
|
|
1174
1110
|
};
|
|
1175
|
-
const reason = this.o.host.deliverLocal(message, p.toSession);
|
|
1111
|
+
const reason = this.o.host.deliverLocal(message, p.toSession, p.hops ?? 0);
|
|
1176
1112
|
if (reason !== void 0) this.bounce(from, p, reason);
|
|
1177
1113
|
}
|
|
1178
1114
|
bounce(to, p, reason) {
|
|
@@ -1258,14 +1194,15 @@ var RelayHub = class {
|
|
|
1258
1194
|
return all.find((s) => s.id === to) ?? all.find((s) => s.name === to);
|
|
1259
1195
|
}
|
|
1260
1196
|
/** Send a message to a session on another device. Throws when that cannot be done now. */
|
|
1261
|
-
sendRemote(target, message) {
|
|
1197
|
+
sendRemote(target, message, hops = 0) {
|
|
1262
1198
|
if (this.conflict) throw new ConvenoError(RpcErrorCode.Conflict, "The device list has a conflict, so nothing is sent to other devices. Run \"conveno devices\".");
|
|
1263
1199
|
const real = this.state.unalias(target.id);
|
|
1264
1200
|
if (!real) throw new ConvenoError(RpcErrorCode.NotFound, `No session "${target.name}".`);
|
|
1265
1201
|
if (!this.sendPayload(real.device, {
|
|
1266
1202
|
type: "message",
|
|
1267
1203
|
toSession: real.remote,
|
|
1268
|
-
message
|
|
1204
|
+
message,
|
|
1205
|
+
...hops > 0 ? { hops } : {}
|
|
1269
1206
|
})) throw new ConvenoError(RpcErrorCode.NotFound, `Session "${target.name}" is on ${target.deviceName ?? "another device"}, and the relay is not connected. Run "conveno relay status".`);
|
|
1270
1207
|
this.sent.set(message.id, {
|
|
1271
1208
|
fromSession: message.from,
|
|
@@ -1647,143 +1584,6 @@ var RelayHub = class {
|
|
|
1647
1584
|
return this.pairStatus(q);
|
|
1648
1585
|
}
|
|
1649
1586
|
};
|
|
1650
|
-
// ../daemon/src/tickets-store.ts
|
|
1651
|
-
/** Tickets, and the sessions whose permission relay is on. */
|
|
1652
|
-
const TICKET_MIGRATION = {
|
|
1653
|
-
name: "006_tickets",
|
|
1654
|
-
sql: `
|
|
1655
|
-
CREATE TABLE tickets (
|
|
1656
|
-
id TEXT PRIMARY KEY,
|
|
1657
|
-
from_session TEXT NOT NULL,
|
|
1658
|
-
to_session TEXT NOT NULL,
|
|
1659
|
-
-- 'orchestrator' when it was addressed to the role, else the session id.
|
|
1660
|
-
to_ref TEXT NOT NULL,
|
|
1661
|
-
kind TEXT NOT NULL,
|
|
1662
|
-
question TEXT NOT NULL,
|
|
1663
|
-
options TEXT,
|
|
1664
|
-
status TEXT NOT NULL,
|
|
1665
|
-
answer TEXT,
|
|
1666
|
-
answered_by TEXT,
|
|
1667
|
-
answer_message_id TEXT,
|
|
1668
|
-
created_at TEXT NOT NULL,
|
|
1669
|
-
answered_at TEXT,
|
|
1670
|
-
expires_at TEXT
|
|
1671
|
-
);
|
|
1672
|
-
CREATE INDEX tickets_status ON tickets (status, created_at);
|
|
1673
|
-
CREATE INDEX tickets_from ON tickets (from_session);
|
|
1674
|
-
CREATE INDEX tickets_to ON tickets (to_session);
|
|
1675
|
-
CREATE TABLE permission_relay (
|
|
1676
|
-
session_id TEXT PRIMARY KEY,
|
|
1677
|
-
-- The orchestrator when the person turned the relay on: the only one who may approve.
|
|
1678
|
-
approver TEXT NOT NULL,
|
|
1679
|
-
enabled_at TEXT NOT NULL
|
|
1680
|
-
);
|
|
1681
|
-
`
|
|
1682
|
-
};
|
|
1683
|
-
const str$1 = (v) => typeof v === "string" ? v : void 0;
|
|
1684
|
-
function toRow(r) {
|
|
1685
|
-
const options = str$1(r.options);
|
|
1686
|
-
return {
|
|
1687
|
-
ticket: Ticket.parse({
|
|
1688
|
-
id: r.id,
|
|
1689
|
-
fromSession: r.from_session,
|
|
1690
|
-
toSession: r.to_session,
|
|
1691
|
-
kind: r.kind,
|
|
1692
|
-
question: r.question,
|
|
1693
|
-
status: r.status,
|
|
1694
|
-
createdAt: r.created_at,
|
|
1695
|
-
...options ? { options: JSON.parse(options) } : {},
|
|
1696
|
-
...str$1(r.answer) !== void 0 ? { answer: r.answer } : {},
|
|
1697
|
-
...str$1(r.answered_by) !== void 0 ? { answeredBy: r.answered_by } : {},
|
|
1698
|
-
...str$1(r.answer_message_id) !== void 0 ? { answerMessageId: r.answer_message_id } : {},
|
|
1699
|
-
...str$1(r.answered_at) !== void 0 ? { answeredAt: r.answered_at } : {},
|
|
1700
|
-
...str$1(r.expires_at) !== void 0 ? { expiresAt: r.expires_at } : {}
|
|
1701
|
-
}),
|
|
1702
|
-
toRef: r.to_ref
|
|
1703
|
-
};
|
|
1704
|
-
}
|
|
1705
|
-
/** SQLite access for tickets. Methods are synchronous; callers group writes with `Store.tx`. */
|
|
1706
|
-
var TicketStore = class {
|
|
1707
|
-
db;
|
|
1708
|
-
constructor(db) {
|
|
1709
|
-
this.db = db;
|
|
1710
|
-
}
|
|
1711
|
-
all(sql, ...params) {
|
|
1712
|
-
return this.db.prepare(sql).all(...params);
|
|
1713
|
-
}
|
|
1714
|
-
run(sql, ...params) {
|
|
1715
|
-
this.db.prepare(sql).run(...params);
|
|
1716
|
-
}
|
|
1717
|
-
insert(t, toRef) {
|
|
1718
|
-
this.run(`INSERT INTO tickets (id, from_session, to_session, to_ref, kind, question, options, status,
|
|
1719
|
-
created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, t.id, t.fromSession, t.toSession, toRef, t.kind, t.question, t.options ? JSON.stringify(t.options) : null, t.status, t.createdAt, t.expiresAt ?? null);
|
|
1720
|
-
}
|
|
1721
|
-
get(id) {
|
|
1722
|
-
const r = this.all("SELECT * FROM tickets WHERE id = ?", id)[0];
|
|
1723
|
-
return r ? toRow(r) : void 0;
|
|
1724
|
-
}
|
|
1725
|
-
/**
|
|
1726
|
-
* Tickets newest first. With `session`, those it asked or that are addressed to it: by its id,
|
|
1727
|
-
* or to the orchestrator role when `holder` says it holds the role.
|
|
1728
|
-
*/
|
|
1729
|
-
list(filter) {
|
|
1730
|
-
const where = [];
|
|
1731
|
-
const params = [];
|
|
1732
|
-
if (filter.session !== void 0) {
|
|
1733
|
-
where.push(filter.holder ? "(from_session = ? OR to_session = ? OR to_ref = 'orchestrator')" : "(from_session = ? OR to_session = ?)");
|
|
1734
|
-
params.push(filter.session, filter.session);
|
|
1735
|
-
}
|
|
1736
|
-
if (filter.id !== void 0) {
|
|
1737
|
-
where.push("id = ?");
|
|
1738
|
-
params.push(filter.id);
|
|
1739
|
-
}
|
|
1740
|
-
const scope = where.length > 0 ? ` WHERE ${where.join(" AND ")}` : "";
|
|
1741
|
-
const open = this.all(`SELECT COUNT(*) AS n FROM tickets${scope}${scope ? " AND" : " WHERE"} status = 'open'`, ...params)[0];
|
|
1742
|
-
const withStatus = [...where];
|
|
1743
|
-
const listParams = [...params];
|
|
1744
|
-
if (filter.status !== void 0) {
|
|
1745
|
-
withStatus.push("status = ?");
|
|
1746
|
-
listParams.push(filter.status);
|
|
1747
|
-
}
|
|
1748
|
-
const sql = `SELECT * FROM tickets${withStatus.length > 0 ? ` WHERE ${withStatus.join(" AND ")}` : ""} ORDER BY id DESC LIMIT ?`;
|
|
1749
|
-
return {
|
|
1750
|
-
rows: this.all(sql, ...listParams, filter.limit).map(toRow),
|
|
1751
|
-
openCount: Number(open?.n ?? 0)
|
|
1752
|
-
};
|
|
1753
|
-
}
|
|
1754
|
-
answer(id, answer, by, at, messageId) {
|
|
1755
|
-
this.run(`UPDATE tickets SET status = 'answered', answer = ?, answered_by = ?, answered_at = ?,
|
|
1756
|
-
answer_message_id = ? WHERE id = ? AND status = 'open'`, answer, by, at, messageId ?? null, id);
|
|
1757
|
-
}
|
|
1758
|
-
setStatus(id, status) {
|
|
1759
|
-
this.run("UPDATE tickets SET status = ? WHERE id = ? AND status = 'open'", status, id);
|
|
1760
|
-
}
|
|
1761
|
-
/** Open tickets whose `expires_at` is at or before `now`. */
|
|
1762
|
-
dueToExpire(now) {
|
|
1763
|
-
return this.all("SELECT * FROM tickets WHERE status = 'open' AND expires_at IS NOT NULL AND expires_at <= ?", now).map(toRow);
|
|
1764
|
-
}
|
|
1765
|
-
/** A session is gone: drop what it asked, and close what was addressed to it. */
|
|
1766
|
-
forgetSession(id) {
|
|
1767
|
-
this.run("DELETE FROM tickets WHERE from_session = ?", id);
|
|
1768
|
-
this.run("UPDATE tickets SET status = 'cancelled' WHERE to_session = ? AND to_ref != 'orchestrator' AND status = 'open'", id);
|
|
1769
|
-
this.run("DELETE FROM permission_relay WHERE session_id = ?", id);
|
|
1770
|
-
}
|
|
1771
|
-
relays() {
|
|
1772
|
-
return this.all("SELECT session_id, approver FROM permission_relay ORDER BY enabled_at, session_id").map((r) => ({
|
|
1773
|
-
session: r.session_id,
|
|
1774
|
-
approver: r.approver
|
|
1775
|
-
}));
|
|
1776
|
-
}
|
|
1777
|
-
/** The session allowed to approve for `id`, or undefined while the relay is off. */
|
|
1778
|
-
approverOf(id) {
|
|
1779
|
-
const r = this.all("SELECT approver FROM permission_relay WHERE session_id = ?", id)[0];
|
|
1780
|
-
return r ? r.approver : void 0;
|
|
1781
|
-
}
|
|
1782
|
-
setRelay(id, approver, at) {
|
|
1783
|
-
if (approver) this.run("INSERT OR REPLACE INTO permission_relay (session_id, approver, enabled_at) VALUES (?, ?, ?)", id, approver, at);
|
|
1784
|
-
else this.run("DELETE FROM permission_relay WHERE session_id = ?", id);
|
|
1785
|
-
}
|
|
1786
|
-
};
|
|
1787
1587
|
// ../daemon/src/store.ts
|
|
1788
1588
|
const MIGRATIONS = [
|
|
1789
1589
|
{
|
|
@@ -1867,7 +1667,31 @@ const MIGRATIONS = [
|
|
|
1867
1667
|
ALTER TABLE sessions ADD COLUMN peekable INTEGER NOT NULL DEFAULT 1;
|
|
1868
1668
|
`
|
|
1869
1669
|
},
|
|
1870
|
-
|
|
1670
|
+
{
|
|
1671
|
+
name: "006_cleanup",
|
|
1672
|
+
sql: `
|
|
1673
|
+
DROP TABLE IF EXISTS tickets;
|
|
1674
|
+
DROP TABLE IF EXISTS permission_relay;
|
|
1675
|
+
DELETE FROM mailbox WHERE session_id = '${OWNER_SESSION_ID}';
|
|
1676
|
+
DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox);
|
|
1677
|
+
ALTER TABLE sessions DROP COLUMN auto;
|
|
1678
|
+
ALTER TABLE sessions DROP COLUMN auto_explicit;
|
|
1679
|
+
ALTER TABLE sessions DROP COLUMN auto_paused_at;
|
|
1680
|
+
ALTER TABLE sessions DROP COLUMN auto_paused_by;
|
|
1681
|
+
ALTER TABLE sessions DROP COLUMN auto_limit;
|
|
1682
|
+
ALTER TABLE sessions DROP COLUMN auto_orch_resumed_at;
|
|
1683
|
+
ALTER TABLE sessions DROP COLUMN peekable;
|
|
1684
|
+
ALTER TABLE sessions DROP COLUMN cli_session_id;
|
|
1685
|
+
ALTER TABLE sessions DROP COLUMN transcript_path;
|
|
1686
|
+
`
|
|
1687
|
+
},
|
|
1688
|
+
{
|
|
1689
|
+
name: "007_native_id",
|
|
1690
|
+
sql: `
|
|
1691
|
+
ALTER TABLE sessions ADD COLUMN native_id TEXT;
|
|
1692
|
+
CREATE INDEX sessions_native_id ON sessions (native_id);
|
|
1693
|
+
`
|
|
1694
|
+
}
|
|
1871
1695
|
];
|
|
1872
1696
|
const str = (v) => typeof v === "string" ? v : void 0;
|
|
1873
1697
|
const num = (v) => typeof v === "number" ? v : void 0;
|
|
@@ -1902,8 +1726,6 @@ function toSessionRow(r) {
|
|
|
1902
1726
|
deliveryTier: r.delivery_tier,
|
|
1903
1727
|
spawned: r.spawned === 1,
|
|
1904
1728
|
spawnDepth: r.spawn_depth,
|
|
1905
|
-
auto: r.auto === 1,
|
|
1906
|
-
autoExplicit: r.auto_explicit === 1,
|
|
1907
1729
|
autoRuns: isoList(r.auto_runs),
|
|
1908
1730
|
turnHops: num(r.turn_hops) ?? 0,
|
|
1909
1731
|
startedAt: r.started_at,
|
|
@@ -1921,23 +1743,12 @@ function toSessionRow(r) {
|
|
|
1921
1743
|
if (hostPid !== void 0) row.hostPid = hostPid;
|
|
1922
1744
|
const hostPids = pidList(r.host_pids);
|
|
1923
1745
|
if (hostPids !== void 0) row.hostPids = hostPids;
|
|
1924
|
-
const cliSessionId = str(r.cli_session_id);
|
|
1925
|
-
if (cliSessionId !== void 0) row.cliSessionId = cliSessionId;
|
|
1926
|
-
const transcriptPath = str(r.transcript_path);
|
|
1927
|
-
if (transcriptPath !== void 0) row.transcriptPath = transcriptPath;
|
|
1928
|
-
if (r.peekable === 0) row.peekable = false;
|
|
1929
1746
|
const statusText = str(r.status_text);
|
|
1930
1747
|
if (statusText !== void 0) row.statusText = statusText;
|
|
1931
1748
|
const spawnedBy = str(r.spawned_by);
|
|
1932
1749
|
if (spawnedBy !== void 0) row.spawnedBy = spawnedBy;
|
|
1933
|
-
const
|
|
1934
|
-
if (
|
|
1935
|
-
const pausedBy = str(r.auto_paused_by);
|
|
1936
|
-
if (pausedBy === "limit") row.autoPausedBy = pausedBy;
|
|
1937
|
-
const limit = num(r.auto_limit);
|
|
1938
|
-
if (limit !== void 0) row.autoLimit = limit;
|
|
1939
|
-
const orchResumedAt = str(r.auto_orch_resumed_at);
|
|
1940
|
-
if (orchResumedAt !== void 0) row.autoOrchResumedAt = orchResumedAt;
|
|
1750
|
+
const nativeId = str(r.native_id);
|
|
1751
|
+
if (nativeId !== void 0) row.nativeId = nativeId;
|
|
1941
1752
|
return row;
|
|
1942
1753
|
}
|
|
1943
1754
|
/** Wire-format session for a stored row. */
|
|
@@ -1953,13 +1764,9 @@ function toSession(row, isOrchestrator, unreadCount) {
|
|
|
1953
1764
|
deliveryTier: row.deliveryTier,
|
|
1954
1765
|
spawned: row.spawned,
|
|
1955
1766
|
spawnDepth: row.spawnDepth,
|
|
1956
|
-
auto: row.auto,
|
|
1957
1767
|
startedAt: row.startedAt,
|
|
1958
1768
|
lastSeenAt: row.lastSeenAt
|
|
1959
1769
|
};
|
|
1960
|
-
if (row.autoPausedAt !== void 0) s.autoPausedAt = row.autoPausedAt;
|
|
1961
|
-
if (row.autoPausedBy !== void 0) s.autoPausedBy = row.autoPausedBy;
|
|
1962
|
-
if (row.autoLimit !== void 0) s.autoLimit = row.autoLimit;
|
|
1963
1770
|
if (unreadCount !== void 0) s.unreadCount = unreadCount;
|
|
1964
1771
|
if (row.cliVersion !== void 0) s.cliVersion = row.cliVersion;
|
|
1965
1772
|
if (row.repoRoot !== void 0) s.repo = row.repoRemoteUrlHash !== void 0 ? {
|
|
@@ -1970,8 +1777,8 @@ function toSession(row, isOrchestrator, unreadCount) {
|
|
|
1970
1777
|
if (row.hostPid !== void 0) s.hostPid = row.hostPid;
|
|
1971
1778
|
if (row.hostPids !== void 0) s.hostPids = row.hostPids;
|
|
1972
1779
|
if (row.statusText !== void 0) s.statusText = row.statusText;
|
|
1973
|
-
if (row.peekable === false) s.peekable = false;
|
|
1974
1780
|
if (row.spawnedBy !== void 0) s.spawnedBy = row.spawnedBy;
|
|
1781
|
+
if (row.nativeId !== void 0) s.nativeId = row.nativeId;
|
|
1975
1782
|
return s;
|
|
1976
1783
|
}
|
|
1977
1784
|
function toEntry(r) {
|
|
@@ -1993,14 +1800,12 @@ function toEntry(r) {
|
|
|
1993
1800
|
/** SQLite persistence. All methods are synchronous; callers group writes with `tx`. */
|
|
1994
1801
|
var Store = class {
|
|
1995
1802
|
db;
|
|
1996
|
-
tickets;
|
|
1997
1803
|
constructor(path) {
|
|
1998
1804
|
this.db = new DatabaseSync(path);
|
|
1999
1805
|
this.db.exec("PRAGMA journal_mode = WAL");
|
|
2000
1806
|
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
2001
1807
|
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
2002
1808
|
this.migrate();
|
|
2003
|
-
this.tickets = new TicketStore(this.db);
|
|
2004
1809
|
}
|
|
2005
1810
|
all(sql, ...params) {
|
|
2006
1811
|
return this.db.prepare(sql).all(...params);
|
|
@@ -2047,9 +1852,8 @@ var Store = class {
|
|
|
2047
1852
|
insertSession(s) {
|
|
2048
1853
|
this.run(`INSERT INTO sessions (id, name, cli, cli_version, device_id, cwd, repo_root, repo_remote_hash,
|
|
2049
1854
|
pid, host_pid, host_pids, status, status_text, delivery_tier, spawned_by, spawned, spawn_depth,
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, s.id, s.name, s.cli, s.cliVersion ?? null, s.deviceId, s.cwd, s.repoRoot ?? null, s.repoRemoteUrlHash ?? null, s.pid ?? null, s.hostPid ?? null, s.hostPids ? JSON.stringify(s.hostPids) : null, s.status, s.statusText ?? null, s.deliveryTier, s.spawnedBy ?? null, s.spawned ? 1 : 0, s.spawnDepth, s.auto ? 1 : 0, s.autoExplicit ? 1 : 0, s.autoPausedAt ?? null, s.autoPausedBy ?? null, s.autoLimit ?? null, JSON.stringify(s.autoRuns), s.turnHops, s.startedAt, s.lastSeenAt);
|
|
1855
|
+
auto_runs, turn_hops, started_at, last_seen_at)
|
|
1856
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, s.id, s.name, s.cli, s.cliVersion ?? null, s.deviceId, s.cwd, s.repoRoot ?? null, s.repoRemoteUrlHash ?? null, s.pid ?? null, s.hostPid ?? null, s.hostPids ? JSON.stringify(s.hostPids) : null, s.status, s.statusText ?? null, s.deliveryTier, s.spawnedBy ?? null, s.spawned ? 1 : 0, s.spawnDepth, JSON.stringify(s.autoRuns), s.turnHops, s.startedAt, s.lastSeenAt);
|
|
2053
1857
|
}
|
|
2054
1858
|
getSession(id) {
|
|
2055
1859
|
const r = this.all("SELECT * FROM sessions WHERE id = ?", id)[0];
|
|
@@ -2062,29 +1866,9 @@ var Store = class {
|
|
|
2062
1866
|
updateSession(id, fields) {
|
|
2063
1867
|
const sets = [];
|
|
2064
1868
|
const vals = [];
|
|
2065
|
-
if (fields.
|
|
2066
|
-
sets.push("
|
|
2067
|
-
vals.push(fields.
|
|
2068
|
-
}
|
|
2069
|
-
if (fields.autoExplicit !== void 0) {
|
|
2070
|
-
sets.push("auto_explicit = ?");
|
|
2071
|
-
vals.push(fields.autoExplicit ? 1 : 0);
|
|
2072
|
-
}
|
|
2073
|
-
if (fields.autoPausedAt !== void 0) {
|
|
2074
|
-
sets.push("auto_paused_at = ?");
|
|
2075
|
-
vals.push(fields.autoPausedAt);
|
|
2076
|
-
}
|
|
2077
|
-
if (fields.autoPausedBy !== void 0) {
|
|
2078
|
-
sets.push("auto_paused_by = ?");
|
|
2079
|
-
vals.push(fields.autoPausedBy);
|
|
2080
|
-
}
|
|
2081
|
-
if (fields.autoLimit !== void 0) {
|
|
2082
|
-
sets.push("auto_limit = ?");
|
|
2083
|
-
vals.push(fields.autoLimit);
|
|
2084
|
-
}
|
|
2085
|
-
if (fields.autoOrchResumedAt !== void 0) {
|
|
2086
|
-
sets.push("auto_orch_resumed_at = ?");
|
|
2087
|
-
vals.push(fields.autoOrchResumedAt);
|
|
1869
|
+
if (fields.nativeId !== void 0) {
|
|
1870
|
+
sets.push("native_id = ?");
|
|
1871
|
+
vals.push(fields.nativeId);
|
|
2088
1872
|
}
|
|
2089
1873
|
if (fields.turnHops !== void 0) {
|
|
2090
1874
|
sets.push("turn_hops = ?");
|
|
@@ -2094,18 +1878,6 @@ var Store = class {
|
|
|
2094
1878
|
sets.push("auto_runs = ?");
|
|
2095
1879
|
vals.push(JSON.stringify(fields.autoRuns));
|
|
2096
1880
|
}
|
|
2097
|
-
if (fields.cliSessionId !== void 0) {
|
|
2098
|
-
sets.push("cli_session_id = ?");
|
|
2099
|
-
vals.push(fields.cliSessionId);
|
|
2100
|
-
}
|
|
2101
|
-
if (fields.transcriptPath !== void 0) {
|
|
2102
|
-
sets.push("transcript_path = ?");
|
|
2103
|
-
vals.push(fields.transcriptPath);
|
|
2104
|
-
}
|
|
2105
|
-
if (fields.peekable !== void 0) {
|
|
2106
|
-
sets.push("peekable = ?");
|
|
2107
|
-
vals.push(fields.peekable ? 1 : 0);
|
|
2108
|
-
}
|
|
2109
1881
|
if (fields.name !== void 0) {
|
|
2110
1882
|
sets.push("name = ?");
|
|
2111
1883
|
vals.push(fields.name);
|
|
@@ -2132,15 +1904,11 @@ var Store = class {
|
|
|
2132
1904
|
setHolder(id) {
|
|
2133
1905
|
this.run("UPDATE orchestrator SET session_id = ? WHERE slot = 1", id);
|
|
2134
1906
|
}
|
|
2135
|
-
/** `hops`: automatic turns behind the message (the
|
|
1907
|
+
/** `hops`: automatic turns behind the message (the wake limit counts them). */
|
|
2136
1908
|
insertMessage(message, recipient, at, hops = 0) {
|
|
2137
1909
|
this.run("INSERT INTO messages (id, json) VALUES (?, ?)", message.id, JSON.stringify(message));
|
|
2138
1910
|
this.run("INSERT INTO mailbox (session_id, message_id, state, queued_at, hops) VALUES (?, ?, 'queued', ?, ?)", recipient, message.id, at, hops);
|
|
2139
1911
|
}
|
|
2140
|
-
/** Start a new chain for the messages queued for a session: their hops go back to 0. */
|
|
2141
|
-
resetQueuedHops(sessionId) {
|
|
2142
|
-
this.run("UPDATE mailbox SET hops = 0 WHERE session_id = ? AND state = 'queued'", sessionId);
|
|
2143
|
-
}
|
|
2144
1912
|
/** Messages queued for a session that no one has been shown yet. */
|
|
2145
1913
|
unreadCount(sessionId) {
|
|
2146
1914
|
const r = this.all("SELECT COUNT(*) AS n FROM mailbox WHERE session_id = ? AND state = 'queued'", sessionId)[0];
|
|
@@ -2151,7 +1919,6 @@ var Store = class {
|
|
|
2151
1919
|
}
|
|
2152
1920
|
/** Remove a session, its mailbox, and any message no mailbox refers to any more. */
|
|
2153
1921
|
deleteSession(id) {
|
|
2154
|
-
this.tickets.forgetSession(id);
|
|
2155
1922
|
this.run("DELETE FROM mailbox WHERE session_id = ?", id);
|
|
2156
1923
|
this.run("DELETE FROM messages WHERE id NOT IN (SELECT message_id FROM mailbox)");
|
|
2157
1924
|
this.run("DELETE FROM sessions WHERE id = ?", id);
|
|
@@ -2176,303 +1943,34 @@ var Store = class {
|
|
|
2176
1943
|
WHERE session_id = ? AND message_id = ?`, e.state, e.deliveredAt ?? null, e.readAt ?? null, e.ackedAt ?? null, sessionId, e.message.id);
|
|
2177
1944
|
}
|
|
2178
1945
|
};
|
|
2179
|
-
// ../daemon/src/tickets.ts
|
|
2180
|
-
/** An open question expires after this long. The asker's own CLI prompt is unaffected. */
|
|
2181
|
-
const TICKET_TTL_MS = 864e5;
|
|
2182
|
-
/** A permission ticket outlives the hook that asked for it by little: the hook gives up in 90 s. */
|
|
2183
|
-
const PERMISSION_TICKET_TTL_MS = 3e5;
|
|
2184
|
-
const fail = (code, message) => {
|
|
2185
|
-
throw new ConvenoError(code, message);
|
|
2186
|
-
};
|
|
2187
|
-
const clip = (text, max) => {
|
|
2188
|
-
const flat = sanitizeLine(text);
|
|
2189
|
-
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
|
|
2190
|
-
};
|
|
2191
|
-
/** Questions to the orchestrator, answers back to the asker, and the permission relay. */
|
|
2192
|
-
var TicketService = class {
|
|
2193
|
-
host;
|
|
2194
|
-
constructor(host) {
|
|
2195
|
-
this.host = host;
|
|
2196
|
-
}
|
|
2197
|
-
get store() {
|
|
2198
|
-
return this.host.store.tickets;
|
|
2199
|
-
}
|
|
2200
|
-
create(p) {
|
|
2201
|
-
const asker = this.requireOnline(p.sessionId);
|
|
2202
|
-
const target = this.host.resolve(p.to ?? "orchestrator");
|
|
2203
|
-
if (target.id === asker.id) fail(RpcErrorCode.InvalidParams, p.to === void 0 || p.to === "orchestrator" ? "You are the orchestrator, so there is no one above you to ask. Ask the user directly." : "A session cannot ask itself. Name another session in `to`.");
|
|
2204
|
-
return this.open(asker, target, {
|
|
2205
|
-
kind: "question",
|
|
2206
|
-
question: p.question,
|
|
2207
|
-
options: p.options,
|
|
2208
|
-
toRef: p.to === void 0 || p.to === "orchestrator" ? ORCHESTRATOR_ALIAS : target.id,
|
|
2209
|
-
ttlMs: TICKET_TTL_MS
|
|
2210
|
-
});
|
|
2211
|
-
}
|
|
2212
|
-
open(asker, target, t) {
|
|
2213
|
-
const at = this.host.iso();
|
|
2214
|
-
if (this.store.list({
|
|
2215
|
-
session: asker.id,
|
|
2216
|
-
status: "open",
|
|
2217
|
-
limit: 200
|
|
2218
|
-
}).rows.filter((r) => r.ticket.fromSession === asker.id).length >= 50) fail(RpcErrorCode.LimitExceeded, `You already have 50 open tickets. Wait for answers or cancel some.`);
|
|
2219
|
-
const ticket = {
|
|
2220
|
-
id: newTicketId(),
|
|
2221
|
-
fromSession: asker.id,
|
|
2222
|
-
toSession: target.id,
|
|
2223
|
-
kind: t.kind,
|
|
2224
|
-
question: t.question,
|
|
2225
|
-
...t.options ? { options: t.options } : {},
|
|
2226
|
-
status: "open",
|
|
2227
|
-
createdAt: at,
|
|
2228
|
-
expiresAt: new Date(Date.parse(at) + t.ttlMs).toISOString()
|
|
2229
|
-
};
|
|
2230
|
-
const message = {
|
|
2231
|
-
id: newMessageId(),
|
|
2232
|
-
from: asker.id,
|
|
2233
|
-
to: target.id,
|
|
2234
|
-
kind: "question",
|
|
2235
|
-
body: {
|
|
2236
|
-
ticketId: ticket.id,
|
|
2237
|
-
question: t.question,
|
|
2238
|
-
...t.options ? { options: t.options } : {}
|
|
2239
|
-
},
|
|
2240
|
-
urgent: true,
|
|
2241
|
-
createdAt: at,
|
|
2242
|
-
fromName: asker.name,
|
|
2243
|
-
fromCli: asker.cli
|
|
2244
|
-
};
|
|
2245
|
-
this.host.store.tx(() => {
|
|
2246
|
-
this.store.insert(ticket, t.toRef);
|
|
2247
|
-
this.host.queue(message, target, true);
|
|
2248
|
-
});
|
|
2249
|
-
this.host.emit({
|
|
2250
|
-
event: "ticket.created",
|
|
2251
|
-
data: { ticket }
|
|
2252
|
-
}, target.id);
|
|
2253
|
-
return { ticket };
|
|
2254
|
-
}
|
|
2255
|
-
answer(p, client) {
|
|
2256
|
-
const row = this.store.get(p.ticketId);
|
|
2257
|
-
if (!row) fail(RpcErrorCode.NotFound, `No ticket ${p.ticketId}. Run tickets to see the open ones.`);
|
|
2258
|
-
const { ticket, toRef } = row;
|
|
2259
|
-
if (ticket.status !== "open") fail(RpcErrorCode.Conflict, `Ticket ${ticket.id} is already ${ticket.status}, so it cannot be answered.`);
|
|
2260
|
-
let by;
|
|
2261
|
-
let me;
|
|
2262
|
-
if (p.sessionId === void 0) {
|
|
2263
|
-
if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Only a session or the conveno command can answer a ticket. Pass sessionId.");
|
|
2264
|
-
by = HUMAN_ANSWERER;
|
|
2265
|
-
} else {
|
|
2266
|
-
me = this.host.requireSession(p.sessionId);
|
|
2267
|
-
by = me.id;
|
|
2268
|
-
if (me.id === ticket.fromSession) fail(RpcErrorCode.Unauthorized, "A session cannot answer its own ticket.");
|
|
2269
|
-
if (!(me.id === ticket.toSession || toRef === "orchestrator" && this.host.holder() === me.id)) fail(RpcErrorCode.Unauthorized, `Ticket ${ticket.id} is not addressed to you. Only the session it was sent to can answer it.`);
|
|
2270
|
-
}
|
|
2271
|
-
let response = p.response;
|
|
2272
|
-
if (ticket.kind === "permission") {
|
|
2273
|
-
response = p.response.trim().toLowerCase();
|
|
2274
|
-
if (!PERMISSION_ANSWERS.includes(response)) fail(RpcErrorCode.InvalidParams, `Ticket ${ticket.id} is a permission request. Answer "allow" or "deny" and nothing else.`);
|
|
2275
|
-
}
|
|
2276
|
-
const at = this.host.iso();
|
|
2277
|
-
const asker = this.host.store.getSession(ticket.fromSession);
|
|
2278
|
-
let messageId;
|
|
2279
|
-
this.host.store.tx(() => {
|
|
2280
|
-
let message;
|
|
2281
|
-
if (ticket.kind === "question" && asker) {
|
|
2282
|
-
message = {
|
|
2283
|
-
id: newMessageId(),
|
|
2284
|
-
from: me?.id ?? this.host.daemonSender,
|
|
2285
|
-
to: asker.id,
|
|
2286
|
-
kind: "answer",
|
|
2287
|
-
body: {
|
|
2288
|
-
ticketId: ticket.id,
|
|
2289
|
-
response
|
|
2290
|
-
},
|
|
2291
|
-
urgent: true,
|
|
2292
|
-
createdAt: at,
|
|
2293
|
-
...me ? {
|
|
2294
|
-
fromName: me.name,
|
|
2295
|
-
fromCli: me.cli
|
|
2296
|
-
} : {}
|
|
2297
|
-
};
|
|
2298
|
-
this.host.queue(message, asker, false);
|
|
2299
|
-
messageId = message.id;
|
|
2300
|
-
}
|
|
2301
|
-
this.store.answer(ticket.id, response, by, at, messageId);
|
|
2302
|
-
});
|
|
2303
|
-
const done = this.store.get(ticket.id).ticket;
|
|
2304
|
-
this.host.emit({
|
|
2305
|
-
event: "ticket.answered",
|
|
2306
|
-
data: { ticket: done }
|
|
2307
|
-
}, ticket.fromSession);
|
|
2308
|
-
if (ticket.toSession !== ticket.fromSession) this.host.emit({
|
|
2309
|
-
event: "ticket.answered",
|
|
2310
|
-
data: { ticket: done }
|
|
2311
|
-
}, ticket.toSession);
|
|
2312
|
-
return { ticket: done };
|
|
2313
|
-
}
|
|
2314
|
-
list(p, client) {
|
|
2315
|
-
if (p.sessionId === void 0 && client !== "cli") fail(RpcErrorCode.Unauthorized, "Pass sessionId to list your tickets.");
|
|
2316
|
-
if (p.sessionId !== void 0) this.host.requireSession(p.sessionId);
|
|
2317
|
-
const { rows, openCount } = this.store.list({
|
|
2318
|
-
...p.sessionId !== void 0 ? {
|
|
2319
|
-
session: p.sessionId,
|
|
2320
|
-
holder: this.host.holder() === p.sessionId
|
|
2321
|
-
} : {},
|
|
2322
|
-
...p.status !== void 0 ? { status: p.status } : {},
|
|
2323
|
-
...p.ticketId !== void 0 ? { id: p.ticketId } : {},
|
|
2324
|
-
limit: p.limit
|
|
2325
|
-
});
|
|
2326
|
-
return {
|
|
2327
|
-
tickets: rows.map((r) => r.ticket),
|
|
2328
|
-
openCount
|
|
2329
|
-
};
|
|
2330
|
-
}
|
|
2331
|
-
cancel(p, client) {
|
|
2332
|
-
const row = this.store.get(p.ticketId);
|
|
2333
|
-
if (!row) fail(RpcErrorCode.NotFound, `No ticket ${p.ticketId}. Run tickets to see the open ones.`);
|
|
2334
|
-
const { ticket } = row;
|
|
2335
|
-
if (p.sessionId === void 0) {
|
|
2336
|
-
if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Pass sessionId to cancel a ticket.");
|
|
2337
|
-
} else {
|
|
2338
|
-
this.host.requireSession(p.sessionId);
|
|
2339
|
-
if (p.sessionId !== ticket.fromSession) fail(RpcErrorCode.Unauthorized, "Only the session that asked can cancel a ticket.");
|
|
2340
|
-
}
|
|
2341
|
-
if (ticket.status !== "open") fail(RpcErrorCode.Conflict, `Ticket ${ticket.id} is already ${ticket.status}, so it cannot be cancelled.`);
|
|
2342
|
-
this.store.setStatus(ticket.id, "cancelled");
|
|
2343
|
-
return { ticket: this.store.get(ticket.id).ticket };
|
|
2344
|
-
}
|
|
2345
|
-
/** Expire open tickets past their time; tell the asker of a question that it went unanswered. */
|
|
2346
|
-
sweep() {
|
|
2347
|
-
const at = this.host.iso();
|
|
2348
|
-
for (const { ticket } of this.store.dueToExpire(at)) this.host.store.tx(() => {
|
|
2349
|
-
this.store.setStatus(ticket.id, "expired");
|
|
2350
|
-
const asker = this.host.store.getSession(ticket.fromSession);
|
|
2351
|
-
if (ticket.kind === "question" && asker) {
|
|
2352
|
-
const target = this.host.store.getSession(ticket.toSession);
|
|
2353
|
-
this.host.queue({
|
|
2354
|
-
id: newMessageId(),
|
|
2355
|
-
from: this.host.daemonSender,
|
|
2356
|
-
to: asker.id,
|
|
2357
|
-
kind: "system",
|
|
2358
|
-
body: {
|
|
2359
|
-
event: "ticket.expired",
|
|
2360
|
-
detail: `Your question to ${target?.name ?? "the orchestrator"} (ticket ${ticket.id}) got no answer and has expired. Ask again, or decide yourself.`
|
|
2361
|
-
},
|
|
2362
|
-
urgent: false,
|
|
2363
|
-
createdAt: at
|
|
2364
|
-
}, asker, false);
|
|
2365
|
-
}
|
|
2366
|
-
});
|
|
2367
|
-
}
|
|
2368
|
-
relay(p, client) {
|
|
2369
|
-
if (client !== "cli") fail(RpcErrorCode.Unauthorized, "Only the conveno command switches the permission relay. An agent cannot turn it on for itself or another agent.");
|
|
2370
|
-
if (p.enabled !== void 0) {
|
|
2371
|
-
if (p.target === void 0) fail(RpcErrorCode.InvalidParams, "Name the session to switch the relay for.");
|
|
2372
|
-
const target = this.host.requireSession(p.target);
|
|
2373
|
-
if (p.enabled && !target.spawned) fail(RpcErrorCode.InvalidParams, `${target.name} was not started by Conveno, so a person is driving it. The relay is only for sessions started with conveno spawn or spawn_session.`);
|
|
2374
|
-
let approver = null;
|
|
2375
|
-
if (p.enabled) {
|
|
2376
|
-
approver = this.host.holder();
|
|
2377
|
-
if (approver === null) fail(RpcErrorCode.NotFound, "No session holds the orchestrator role, so there is no one to approve. Run orchestrate in the session you want to use, then turn the relay on.");
|
|
2378
|
-
if (approver === target.id) fail(RpcErrorCode.InvalidParams, `${target.name} is the orchestrator, so it cannot relay to itself.`);
|
|
2379
|
-
}
|
|
2380
|
-
this.store.setRelay(target.id, approver, this.host.iso());
|
|
2381
|
-
}
|
|
2382
|
-
return { relays: this.store.relays() };
|
|
2383
|
-
}
|
|
2384
|
-
request(p) {
|
|
2385
|
-
const me = this.requireOnline(p.sessionId);
|
|
2386
|
-
const local = (reason) => ({
|
|
2387
|
-
relay: false,
|
|
2388
|
-
reason
|
|
2389
|
-
});
|
|
2390
|
-
const approverId = this.store.approverOf(me.id);
|
|
2391
|
-
if (approverId === void 0) return local("The permission relay is off for this session.");
|
|
2392
|
-
if (!me.spawned) return local("A person drives this session, so the relay does not apply.");
|
|
2393
|
-
const verdict = classifyPermission({
|
|
2394
|
-
tool: p.tool,
|
|
2395
|
-
command: p.command,
|
|
2396
|
-
paths: p.paths,
|
|
2397
|
-
cwd: p.cwd ?? me.cwd,
|
|
2398
|
-
repoRoot: me.repoRoot
|
|
2399
|
-
});
|
|
2400
|
-
if (!verdict.relay) return local(verdict.reason);
|
|
2401
|
-
const target = this.host.store.getSession(approverId);
|
|
2402
|
-
if (!target || target.status === "offline") return local("The orchestrator this relay was set up with is not online.");
|
|
2403
|
-
if (target.id === me.id) return local("This session is the orchestrator.");
|
|
2404
|
-
if (this.store.list({
|
|
2405
|
-
session: me.id,
|
|
2406
|
-
status: "open",
|
|
2407
|
-
limit: 200
|
|
2408
|
-
}).rows.filter((r) => r.ticket.fromSession === me.id && r.ticket.kind === "permission").length >= 5) return local("Too many permission requests are waiting already.");
|
|
2409
|
-
const lines = [
|
|
2410
|
-
`Permission request (EXPERIMENTAL relay) from ${me.name} (${me.cli}) in ${clip(me.repoRoot ?? me.cwd, 200)}.`,
|
|
2411
|
-
`Tool: ${clip(p.tool, 100)}`,
|
|
2412
|
-
...p.command ? [`Command: ${clip(p.command, 1e3)}`] : [],
|
|
2413
|
-
...p.paths?.length ? [`Files: ${clip(p.paths.join(", "), 1e3)}`] : [],
|
|
2414
|
-
...p.cwd ? [`Working folder: ${clip(p.cwd, 200)}`] : [],
|
|
2415
|
-
...p.description ? [`The CLI says: ${clip(p.description, 300)}`] : [],
|
|
2416
|
-
`Answer "allow" or "deny". The worker waits about 80 seconds, then its own prompt takes over. Allow only what you would run yourself in this repo.`
|
|
2417
|
-
];
|
|
2418
|
-
const { ticket } = this.open(me, target, {
|
|
2419
|
-
kind: "permission",
|
|
2420
|
-
question: lines.join("\n"),
|
|
2421
|
-
options: [...PERMISSION_ANSWERS],
|
|
2422
|
-
toRef: target.id,
|
|
2423
|
-
ttlMs: PERMISSION_TICKET_TTL_MS
|
|
2424
|
-
});
|
|
2425
|
-
return {
|
|
2426
|
-
relay: true,
|
|
2427
|
-
ticket
|
|
2428
|
-
};
|
|
2429
|
-
}
|
|
2430
|
-
requireOnline(id) {
|
|
2431
|
-
const row = this.host.requireSession(id);
|
|
2432
|
-
if (row.status === "offline") fail(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again before asking.`);
|
|
2433
|
-
return row;
|
|
2434
|
-
}
|
|
2435
|
-
};
|
|
2436
1946
|
// ../daemon/src/server.ts
|
|
2437
|
-
const DAEMON_VERSION = "0.2.0-rc.
|
|
1947
|
+
const DAEMON_VERSION = "0.2.0-rc.11";
|
|
2438
1948
|
/** A connection that has not finished the handshake by then is closed. */
|
|
2439
1949
|
const AUTH_TIMEOUT_MS = 5e3;
|
|
2440
1950
|
/** Unread messages one session may hold. */
|
|
2441
1951
|
const MAX_UNREAD_PER_SESSION = 1e3;
|
|
2442
1952
|
/**
|
|
2443
|
-
*
|
|
2444
|
-
*
|
|
2445
|
-
*
|
|
2446
|
-
* without piling up months of test sessions. It applies only when nothing is waiting for it.
|
|
1953
|
+
* An offline session is removed this long after it went offline. The grace lets a session whose
|
|
1954
|
+
* host process is still alive come back with a heartbeat. Sessions already offline when the daemon
|
|
1955
|
+
* starts are removed at once.
|
|
2447
1956
|
*/
|
|
2448
|
-
const
|
|
2449
|
-
/**
|
|
2450
|
-
* An offline session that a newer live session has replaced (same name, CLI and repo) is deleted
|
|
2451
|
-
* after this grace. It cannot come back: a heartbeat is refused while another live session holds
|
|
2452
|
-
* its name.
|
|
2453
|
-
*/
|
|
2454
|
-
const PRUNE_SUPERSEDED_AFTER_MS = 3e5;
|
|
2455
|
-
/**
|
|
2456
|
-
* An offline session with unread (queued) messages keeps them this long, whatever the other rules
|
|
2457
|
-
* say, so mail sent to a closed session survives a weekend. Then the session and its mailbox go.
|
|
2458
|
-
*/
|
|
2459
|
-
const PRUNE_UNREAD_AFTER_MS = 6048e5;
|
|
1957
|
+
const OFFLINE_GRACE_MS = 6e4;
|
|
2460
1958
|
/** Time the daemon spends reading the process table for one `session.hostOf`. */
|
|
2461
1959
|
const HOST_OF_TIMEOUT_MS = 1500;
|
|
1960
|
+
/** Message bytes one daemon wake hands over: the text goes on a command line (\`codex queue\`). */
|
|
1961
|
+
const DAEMON_WAKE_BYTES = 16e3;
|
|
1962
|
+
/** First wait before a daemon wake is tried again; doubles up to the max. */
|
|
1963
|
+
const WAKE_RETRY_MS = 15e3;
|
|
1964
|
+
/** A wake still not a turn after this long counts as unread in status (see `stalledWoken`). */
|
|
1965
|
+
const WOKEN_STALL_MS = 3e4;
|
|
1966
|
+
const WAKE_RETRY_MAX_MS = 3e5;
|
|
2462
1967
|
/** Sender id on `system` messages made by the daemon itself (no session sent them). */
|
|
2463
1968
|
const DAEMON_SENDER_ID = SessionId.parse("0".repeat(26));
|
|
2464
1969
|
const CLI_TIER = {
|
|
2465
1970
|
claude: "next_turn",
|
|
2466
1971
|
codex: "next_turn",
|
|
2467
|
-
cursor: "next_turn",
|
|
2468
|
-
copilot: "next_turn",
|
|
2469
1972
|
antigravity: "next_turn"
|
|
2470
1973
|
};
|
|
2471
|
-
/**
|
|
2472
|
-
* CLIs whose adapter can wake an idle session in auto mode (Claude Code's asyncRewake listener,
|
|
2473
|
-
* the OpenCode plugin). A message to such a session in auto mode is reported as `live`.
|
|
2474
|
-
*/
|
|
2475
|
-
const CLI_WAKE = /* @__PURE__ */ new Set(["claude", "opencode"]);
|
|
2476
1974
|
var Daemon = class {
|
|
2477
1975
|
store;
|
|
2478
1976
|
token;
|
|
@@ -2483,25 +1981,44 @@ var Daemon = class {
|
|
|
2483
1981
|
requestShutdown;
|
|
2484
1982
|
log;
|
|
2485
1983
|
authTimeoutMs;
|
|
2486
|
-
pathExists;
|
|
2487
1984
|
autoLimits;
|
|
2488
|
-
transcripts;
|
|
2489
|
-
transcriptEnv;
|
|
2490
1985
|
processIo;
|
|
1986
|
+
platform;
|
|
1987
|
+
wakers;
|
|
1988
|
+
settingsPath;
|
|
2491
1989
|
conns = /* @__PURE__ */ new Set();
|
|
2492
1990
|
/** Reaches the owner's other devices; set by startDaemon unless disabled. */
|
|
2493
1991
|
relay;
|
|
2494
1992
|
deviceId;
|
|
2495
|
-
/**
|
|
1993
|
+
/**
|
|
1994
|
+
* The newest idle-wake listener of each session, the ids it replaced, and the connection it
|
|
1995
|
+
* asked on. The session counts as wakeable while that connection is open. In memory only.
|
|
1996
|
+
*/
|
|
2496
1997
|
listeners = /* @__PURE__ */ new Map();
|
|
1998
|
+
/**
|
|
1999
|
+
* Messages the last wake handed each session, until its turn starts or ends. A requeue of
|
|
2000
|
+
* these makes the session idle again. In memory only.
|
|
2001
|
+
*/
|
|
2002
|
+
woken = /* @__PURE__ */ new Map();
|
|
2003
|
+
/** Sessions a daemon waker is working on, so one session gets one wake at a time. */
|
|
2004
|
+
daemonWaking = /* @__PURE__ */ new Set();
|
|
2005
|
+
/** Daemon wakes to try again (after \`failed\` or the wake limit), by session. In memory only. */
|
|
2006
|
+
wakeRetry = /* @__PURE__ */ new Map();
|
|
2007
|
+
/** Set when the daemon shuts down: closing connections must not touch the store any more. */
|
|
2008
|
+
stopping = false;
|
|
2009
|
+
/**
|
|
2010
|
+
* Sessions whose daemon waker answered \`unsupported\` (no \`queue\` in that binary, an ephemeral
|
|
2011
|
+
* thread): not asked again for them while the daemon runs, so a new daemon checks afresh. Other
|
|
2012
|
+
* sessions of the same CLI are still woken.
|
|
2013
|
+
*/
|
|
2014
|
+
wakersOff = /* @__PURE__ */ new Set();
|
|
2015
|
+
/** When each session's last daemon wake was handed over, to tell a wake that never became a turn. */
|
|
2016
|
+
wokenAt = /* @__PURE__ */ new Map();
|
|
2497
2017
|
idleSince;
|
|
2498
2018
|
startedMs;
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
platform: process.platform,
|
|
2503
|
-
env: process.env
|
|
2504
|
-
}, processIo = defaultProcessIo) {
|
|
2019
|
+
/** When each session went offline, for the removal grace. In memory only. */
|
|
2020
|
+
offlineSince = /* @__PURE__ */ new Map();
|
|
2021
|
+
constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath) {
|
|
2505
2022
|
this.store = store;
|
|
2506
2023
|
this.token = token;
|
|
2507
2024
|
this.now = now;
|
|
@@ -2511,24 +2028,14 @@ var Daemon = class {
|
|
|
2511
2028
|
this.requestShutdown = requestShutdown;
|
|
2512
2029
|
this.log = log;
|
|
2513
2030
|
this.authTimeoutMs = authTimeoutMs;
|
|
2514
|
-
this.pathExists = pathExists;
|
|
2515
2031
|
this.autoLimits = autoLimits;
|
|
2516
|
-
this.transcripts = transcripts;
|
|
2517
|
-
this.transcriptEnv = transcriptEnv;
|
|
2518
2032
|
this.processIo = processIo;
|
|
2033
|
+
this.platform = platform;
|
|
2034
|
+
this.wakers = wakers;
|
|
2035
|
+
this.settingsPath = settingsPath;
|
|
2519
2036
|
this.deviceId = store.deviceId();
|
|
2520
2037
|
this.startedMs = now().getTime();
|
|
2521
2038
|
this.idleSince = this.startedMs;
|
|
2522
|
-
this.tickets = new TicketService({
|
|
2523
|
-
store,
|
|
2524
|
-
iso: () => this.iso(),
|
|
2525
|
-
requireSession: (id) => this.requireSession(id),
|
|
2526
|
-
resolve: (to) => this.resolveOnline(to),
|
|
2527
|
-
holder: () => effectiveHolder(store.holder(), this.named(store.allSessions()))?.id ?? null,
|
|
2528
|
-
queue: (message, row, limit) => this.queueMessage(message, row, limit),
|
|
2529
|
-
emit: (payload, onlyTo) => this.emit(payload, onlyTo),
|
|
2530
|
-
daemonSender: DAEMON_SENDER_ID
|
|
2531
|
-
});
|
|
2532
2039
|
}
|
|
2533
2040
|
iso = () => this.now().toISOString();
|
|
2534
2041
|
attach(socket) {
|
|
@@ -2549,6 +2056,7 @@ var Daemon = class {
|
|
|
2549
2056
|
socket.on("close", () => {
|
|
2550
2057
|
clearTimeout(authTimer);
|
|
2551
2058
|
this.conns.delete(conn);
|
|
2059
|
+
this.listenerGone(conn);
|
|
2552
2060
|
});
|
|
2553
2061
|
socket.on("error", () => socket.destroy());
|
|
2554
2062
|
}
|
|
@@ -2610,29 +2118,22 @@ var Daemon = class {
|
|
|
2610
2118
|
case "session.rename": return this.rename(req.params);
|
|
2611
2119
|
case "session.setStatus": return this.setStatus(req.params);
|
|
2612
2120
|
case "session.list": return this.list(req.params);
|
|
2613
|
-
case "session.byHost": return this.byHost(req.params
|
|
2121
|
+
case "session.byHost": return this.byHost(req.params);
|
|
2614
2122
|
case "session.hostOf": return this.hostOf(req.params);
|
|
2615
|
-
case "session.
|
|
2616
|
-
case "session.setAuto": return this.setAuto(req.params);
|
|
2123
|
+
case "session.setNative": return this.setNative(req.params);
|
|
2617
2124
|
case "turn.start": return this.turnStart(req.params.sessionId);
|
|
2618
2125
|
case "turn.end": return this.turnEnd(req.params);
|
|
2619
|
-
case "turn.wake": return this.turnWake(req.params);
|
|
2620
|
-
case "session.setCliInfo": return this.setCliInfo(req.params);
|
|
2621
|
-
case "session.setPeekable": return this.setPeekable(req.params);
|
|
2622
|
-
case "session.peek": return this.peek(conn, req.params);
|
|
2126
|
+
case "turn.wake": return this.turnWake(conn, req.params);
|
|
2623
2127
|
case "daemon.shutdown": return { ok: true };
|
|
2624
2128
|
case "orchestrator.claim": return this.claim(req.params.sessionId);
|
|
2129
|
+
case "orchestrator.clear": return this.clearLead(conn);
|
|
2625
2130
|
case "message.send": return this.sendMessage(req.params);
|
|
2131
|
+
case "owner.send": return this.ownerSend(conn, req.params);
|
|
2626
2132
|
case "message.inbox": return this.inbox(req.params);
|
|
2627
2133
|
case "message.deliver": return this.deliver(req.params);
|
|
2628
2134
|
case "message.ack": return this.ack(req.params);
|
|
2135
|
+
case "message.requeue": return this.requeue(req.params);
|
|
2629
2136
|
case "events.subscribe": return this.subscribe(conn, req.params);
|
|
2630
|
-
case "ticket.create": return this.tickets.create(req.params);
|
|
2631
|
-
case "ticket.answer": return this.tickets.answer(req.params, conn.client);
|
|
2632
|
-
case "ticket.list": return this.tickets.list(req.params, conn.client);
|
|
2633
|
-
case "ticket.cancel": return this.tickets.cancel(req.params, conn.client);
|
|
2634
|
-
case "permission.relay": return this.tickets.relay(req.params, conn.client);
|
|
2635
|
-
case "permission.request": return this.tickets.request(req.params);
|
|
2636
2137
|
case "relay.status":
|
|
2637
2138
|
case "devices.list":
|
|
2638
2139
|
case "devices.pair":
|
|
@@ -2681,30 +2182,24 @@ var Daemon = class {
|
|
|
2681
2182
|
if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
|
|
2682
2183
|
return row;
|
|
2683
2184
|
}
|
|
2185
|
+
/** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
|
|
2684
2186
|
view(row) {
|
|
2685
|
-
|
|
2187
|
+
const holder = effectiveHolder(this.store.holder(), this.named([row]));
|
|
2188
|
+
return toSession({
|
|
2189
|
+
...row,
|
|
2190
|
+
deliveryTier: this.tierFor(row)
|
|
2191
|
+
}, holder?.id === row.id, this.store.unreadCount(row.id) + this.stalledWoken(row.id));
|
|
2686
2192
|
}
|
|
2687
2193
|
/** The orchestrator as routing sees it: the holder, if it is online. */
|
|
2688
2194
|
orchestratorNow() {
|
|
2689
2195
|
return effectiveHolder(this.store.holder(), this.named(this.store.allSessions()))?.id ?? null;
|
|
2690
2196
|
}
|
|
2691
|
-
/** The online session a recipient names (`orchestrator`, a name or an id). */
|
|
2692
|
-
resolveOnline(to) {
|
|
2693
|
-
const rows = this.store.allSessions();
|
|
2694
|
-
const found = resolveRecipient(to, this.named(rows), this.store.holder());
|
|
2695
|
-
return rows.find((r) => r.id === found.id);
|
|
2696
|
-
}
|
|
2697
|
-
/** Queue a message for a session and tell its subscriber. `limit` applies the unread cap. */
|
|
2698
|
-
queueMessage(message, row, limit) {
|
|
2699
|
-
if (limit && this.store.unreadCount(row.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(row.name, MAX_UNREAD_PER_SESSION));
|
|
2700
|
-
this.store.insertMessage(message, row.id, message.createdAt);
|
|
2701
|
-
this.emitMessage(message, row.id);
|
|
2702
|
-
}
|
|
2703
2197
|
emit(payload, onlyTo) {
|
|
2198
|
+
const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
|
|
2704
2199
|
for (const c of this.conns) {
|
|
2705
2200
|
const sub = c.sub;
|
|
2706
2201
|
if (!sub?.topics.has(payload.event)) continue;
|
|
2707
|
-
if (
|
|
2202
|
+
if (only !== void 0 && sub.sessionId !== void 0 && !only.includes(sub.sessionId)) continue;
|
|
2708
2203
|
this.send(c, makeEventNotification(payload));
|
|
2709
2204
|
}
|
|
2710
2205
|
}
|
|
@@ -2719,11 +2214,13 @@ var Daemon = class {
|
|
|
2719
2214
|
});
|
|
2720
2215
|
this.relay?.sessionsChanged();
|
|
2721
2216
|
}
|
|
2217
|
+
/** Every message that lands in a local mailbox goes through here. */
|
|
2722
2218
|
emitMessage(m, recipient) {
|
|
2723
2219
|
this.emit({
|
|
2724
2220
|
event: "message.received",
|
|
2725
2221
|
data: { message: m }
|
|
2726
2222
|
}, recipient);
|
|
2223
|
+
this.daemonWake(recipient);
|
|
2727
2224
|
}
|
|
2728
2225
|
async detect(p) {
|
|
2729
2226
|
if (p.repo) return p.repo;
|
|
@@ -2748,8 +2245,6 @@ var Daemon = class {
|
|
|
2748
2245
|
deliveryTier: p.acp ? "acp" : CLI_TIER[p.cli] ?? "inbox",
|
|
2749
2246
|
spawned: p.spawned,
|
|
2750
2247
|
spawnDepth: parent ? parent.spawnDepth + 1 : 0,
|
|
2751
|
-
auto: p.auto ?? (p.spawned || p.spawnedBy !== void 0),
|
|
2752
|
-
autoExplicit: false,
|
|
2753
2248
|
autoRuns: [],
|
|
2754
2249
|
turnHops: 0,
|
|
2755
2250
|
startedAt: at,
|
|
@@ -2768,7 +2263,18 @@ var Daemon = class {
|
|
|
2768
2263
|
return r;
|
|
2769
2264
|
});
|
|
2770
2265
|
this.emitSession(row.id, "registered");
|
|
2771
|
-
|
|
2266
|
+
this.claimPreferredLead(row);
|
|
2267
|
+
return { session: this.view(this.store.getSession(row.id) ?? row) };
|
|
2268
|
+
}
|
|
2269
|
+
/**
|
|
2270
|
+
* The saved preferred lead CLI takes the lead when it registers and nobody online leads. The
|
|
2271
|
+
* settings are read on each register, so a change needs no restart. It is the normal claim.
|
|
2272
|
+
*/
|
|
2273
|
+
claimPreferredLead(row) {
|
|
2274
|
+
if (this.settingsPath === void 0) return;
|
|
2275
|
+
if (readSettings(this.settingsPath).leadCli !== row.cli) return;
|
|
2276
|
+
if (this.orchestratorNow() !== null) return;
|
|
2277
|
+
this.claim(row.id);
|
|
2772
2278
|
}
|
|
2773
2279
|
async registerAsync(p) {
|
|
2774
2280
|
return this.register(p, await this.detect(p));
|
|
@@ -2786,6 +2292,7 @@ var Daemon = class {
|
|
|
2786
2292
|
status: "idle",
|
|
2787
2293
|
lastSeenAt: at
|
|
2788
2294
|
});
|
|
2295
|
+
this.offlineSince.delete(sessionId);
|
|
2789
2296
|
this.emitSession(sessionId, "updated");
|
|
2790
2297
|
return { lastSeenAt: at };
|
|
2791
2298
|
}
|
|
@@ -2797,6 +2304,8 @@ var Daemon = class {
|
|
|
2797
2304
|
if (after !== before) this.store.setHolder(after);
|
|
2798
2305
|
});
|
|
2799
2306
|
this.listeners.delete(sessionId);
|
|
2307
|
+
this.woken.delete(sessionId);
|
|
2308
|
+
this.offlineSince.set(sessionId, this.now().getTime());
|
|
2800
2309
|
this.emitSession(sessionId, change);
|
|
2801
2310
|
if (after !== before) this.emit({
|
|
2802
2311
|
event: "orchestrator.changed",
|
|
@@ -2835,7 +2344,7 @@ var Daemon = class {
|
|
|
2835
2344
|
}
|
|
2836
2345
|
list(p) {
|
|
2837
2346
|
const rows = this.store.allSessions().filter((r) => {
|
|
2838
|
-
if (
|
|
2347
|
+
if (r.status === "offline" && !p.includeOffline) return false;
|
|
2839
2348
|
if (p.cli && r.cli !== p.cli) return false;
|
|
2840
2349
|
if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
|
|
2841
2350
|
return true;
|
|
@@ -2851,15 +2360,33 @@ var Daemon = class {
|
|
|
2851
2360
|
* Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
|
|
2852
2361
|
* session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
|
|
2853
2362
|
* null; the daemon never guesses. With `cwd`, the sessions that share the pid are narrowed to
|
|
2854
|
-
* those registered in the same folder (
|
|
2363
|
+
* those registered in the same folder (separators, trailing slash, case
|
|
2855
2364
|
* on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
|
|
2856
2365
|
* folder still match nothing.
|
|
2857
2366
|
*/
|
|
2858
|
-
byHost(
|
|
2859
|
-
const
|
|
2367
|
+
byHost(p) {
|
|
2368
|
+
const { pid, cwd, nativeId } = p;
|
|
2369
|
+
const rows = this.store.allSessions().filter((r) => p.includeOffline || r.status !== "offline");
|
|
2370
|
+
const live = (list) => {
|
|
2371
|
+
const online = list.filter((r) => r.status !== "offline");
|
|
2372
|
+
return online.length > 0 ? online : list;
|
|
2373
|
+
};
|
|
2374
|
+
if (nativeId !== void 0) {
|
|
2375
|
+
const own = live(rows.filter((r) => r.nativeId === nativeId))[0];
|
|
2376
|
+
if (!own) return { session: null };
|
|
2377
|
+
const pids = [...own.hostPid === void 0 ? [] : [own.hostPid], ...own.hostPids ?? []];
|
|
2378
|
+
if (pids.length === 0 || pids.includes(pid)) return { session: this.view(own) };
|
|
2379
|
+
const mine = this.pidHolders(rows, pid, cwd, live);
|
|
2380
|
+
return { session: this.view(mine.length === 1 ? mine[0] : own) };
|
|
2381
|
+
}
|
|
2382
|
+
const holders = this.pidHolders(rows, pid, cwd, live);
|
|
2860
2383
|
const only = holders.length === 1 ? holders[0] : void 0;
|
|
2861
2384
|
return { session: only ? this.view(only) : null };
|
|
2862
2385
|
}
|
|
2386
|
+
/** Sessions whose host is `pid` (in `cwd`, when given), online ones first. */
|
|
2387
|
+
pidHolders(rows, pid, cwd, live) {
|
|
2388
|
+
return live(rows.filter((r) => r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, this.platform))));
|
|
2389
|
+
}
|
|
2863
2390
|
/**
|
|
2864
2391
|
* Walk up from a hook's parent pid to its host CLI, for a hook that would otherwise read the
|
|
2865
2392
|
* process table itself. With no online session of the hook's CLI there is nothing the hook could
|
|
@@ -2885,122 +2412,41 @@ var Daemon = class {
|
|
|
2885
2412
|
};
|
|
2886
2413
|
}
|
|
2887
2414
|
/**
|
|
2888
|
-
*
|
|
2889
|
-
*
|
|
2890
|
-
* keeps only sessions last seen at least that long ago. Online candidates are never removed:
|
|
2891
|
-
* those picked by `ids` or `names` come back in `skippedOnline`, and with `olderThanMs` alone
|
|
2892
|
-
* they are ignored, since the caller asked for offline sessions. A removed session takes its
|
|
2893
|
-
* mailbox with it, in one transaction.
|
|
2415
|
+
* A hook records the CLI's own id for its session. One online session holds an id at a time,
|
|
2416
|
+
* so a CLI that reuses an id for a new session (a resumed thread) moves it there.
|
|
2894
2417
|
*/
|
|
2895
|
-
|
|
2896
|
-
const
|
|
2897
|
-
|
|
2898
|
-
const
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
return p.olderThanMs === void 0 || nowMs - Date.parse(r.lastSeenAt) >= p.olderThanMs;
|
|
2903
|
-
});
|
|
2904
|
-
const brief = (r) => ({
|
|
2905
|
-
id: r.id,
|
|
2906
|
-
name: r.name
|
|
2418
|
+
setNative(p) {
|
|
2419
|
+
const row = this.requireOnline(p.sessionId);
|
|
2420
|
+
if (row.nativeId === p.nativeId) return { session: this.view(row) };
|
|
2421
|
+
const others = this.store.allSessions().filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
|
|
2422
|
+
this.store.tx(() => {
|
|
2423
|
+
for (const o of others) this.store.updateSession(o.id, { nativeId: null });
|
|
2424
|
+
this.store.updateSession(row.id, { nativeId: p.nativeId });
|
|
2907
2425
|
});
|
|
2908
|
-
const
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
return {
|
|
2912
|
-
forgotten: offline.map(brief),
|
|
2913
|
-
skippedOnline: skippedOnline.map(brief)
|
|
2914
|
-
};
|
|
2915
|
-
}
|
|
2916
|
-
/**
|
|
2917
|
-
* A hook reports the CLI's own session id and transcript file. The session is the one online
|
|
2918
|
-
* session whose `hostPid` equals `pid`, as in `byHost`; no unique match changes nothing. A new
|
|
2919
|
-
* CLI session id with no path drops the old path, which belonged to the previous conversation.
|
|
2920
|
-
*/
|
|
2921
|
-
setCliInfo(p) {
|
|
2922
|
-
const holders = this.store.allSessions().filter((r) => r.status !== "offline" && r.hostPid === p.pid);
|
|
2923
|
-
const row = holders.length === 1 ? holders[0] : void 0;
|
|
2924
|
-
if (!row) return { updated: false };
|
|
2925
|
-
const fields = {};
|
|
2926
|
-
if (p.cliSessionId !== void 0) fields.cliSessionId = p.cliSessionId;
|
|
2927
|
-
if (p.transcriptPath !== void 0) fields.transcriptPath = p.transcriptPath;
|
|
2928
|
-
else if (p.cliSessionId !== void 0 && p.cliSessionId !== row.cliSessionId) fields.transcriptPath = null;
|
|
2929
|
-
this.store.updateSession(row.id, fields);
|
|
2930
|
-
return { updated: true };
|
|
2931
|
-
}
|
|
2932
|
-
/** The owner's switch. With no `session`, every online session on this device. */
|
|
2933
|
-
setPeekable(p) {
|
|
2934
|
-
const rows = this.store.allSessions();
|
|
2935
|
-
const targets = p.session === void 0 ? rows.filter((r) => r.status !== "offline") : rows.filter((r) => r.id === p.session || r.name === p.session && r.status !== "offline");
|
|
2936
|
-
if (p.session !== void 0 && targets.length === 0) throw new ConvenoError(RpcErrorCode.NotFound, `No online session "${p.session}". Run "conveno status" to see the names.`);
|
|
2937
|
-
for (const r of targets) this.store.updateSession(r.id, { peekable: p.peekable });
|
|
2938
|
-
return { sessions: targets.map((r) => ({
|
|
2939
|
-
id: r.id,
|
|
2940
|
-
name: r.name,
|
|
2941
|
-
peekable: p.peekable
|
|
2942
|
-
})) };
|
|
2943
|
-
}
|
|
2944
|
-
/**
|
|
2945
|
-
* Read the recent turns of another session's transcript on this device. Redaction is always on.
|
|
2946
|
-
* The target's owner can see every peek in the daemon log (who looked at whom and how many
|
|
2947
|
-
* turns, never the content), and can turn peek off for a session.
|
|
2948
|
-
*/
|
|
2949
|
-
async peek(conn, p) {
|
|
2950
|
-
if (p.sessionId === void 0 && conn.kind !== "cli") throw new ConvenoError(RpcErrorCode.InvalidParams, "A session must give its own sessionId to peek. Only the conveno command may peek without one.");
|
|
2951
|
-
const caller = p.sessionId !== void 0 ? this.requireSession(p.sessionId) : void 0;
|
|
2952
|
-
const target = this.store.getSession(resolveRecipient(p.target, this.named(this.store.allSessions()), this.store.holder()).id);
|
|
2953
|
-
const who = `${caller ? `${caller.name} (${caller.id})` : "the conveno command"} -> ${target.name} (${target.id}, ${target.cli})`;
|
|
2954
|
-
if (target.peekable === false) {
|
|
2955
|
-
this.log.note(`peek refused, peek is off: ${who}`);
|
|
2956
|
-
throw new ConvenoError(RpcErrorCode.PermissionRequired, `Peek is turned off for ${target.name}. Its owner can run "conveno peek on ${target.name}" to allow it.`);
|
|
2957
|
-
}
|
|
2958
|
-
const reader = target.deliveryTier === "acp" ? acpTranscript : this.transcripts[target.cli];
|
|
2959
|
-
if (!reader) throw new ConvenoError(RpcErrorCode.InvalidParams, `peek not supported for ${target.cli} yet.`);
|
|
2960
|
-
const res = await reader.read({
|
|
2961
|
-
cwd: target.cwd,
|
|
2962
|
-
startedAt: target.startedAt,
|
|
2963
|
-
lastTurns: p.lastTurns,
|
|
2964
|
-
...target.cliSessionId !== void 0 ? { cliSessionId: target.cliSessionId } : {},
|
|
2965
|
-
...target.transcriptPath !== void 0 ? { transcriptPath: target.transcriptPath } : {},
|
|
2966
|
-
...target.hostPid !== void 0 ? { hostPid: target.hostPid } : {}
|
|
2967
|
-
}, this.transcriptEnv);
|
|
2968
|
-
if (!res.ok) {
|
|
2969
|
-
this.log.note(`peek found nothing (${res.reason}): ${who}`);
|
|
2970
|
-
throw new ConvenoError(res.reason === "unsupported" ? RpcErrorCode.InvalidParams : RpcErrorCode.NotFound, res.message);
|
|
2971
|
-
}
|
|
2972
|
-
const out = preparePeek(res.entries, res.more, p.maxChars);
|
|
2973
|
-
this.log.note(`peek: ${who}, ${out.turns.length} turns, ${out.redactions} redactions`);
|
|
2974
|
-
return {
|
|
2975
|
-
session: {
|
|
2976
|
-
id: target.id,
|
|
2977
|
-
name: target.name,
|
|
2978
|
-
cli: target.cli
|
|
2979
|
-
},
|
|
2980
|
-
turns: out.turns,
|
|
2981
|
-
truncated: out.truncated,
|
|
2982
|
-
redacted: true,
|
|
2983
|
-
redactions: out.redactions
|
|
2984
|
-
};
|
|
2426
|
+
for (const o of others) this.emitSession(o.id, "updated");
|
|
2427
|
+
this.emitSession(row.id, "updated");
|
|
2428
|
+
this.daemonWake(row.id);
|
|
2429
|
+
return { session: this.view(this.requireSession(row.id)) };
|
|
2985
2430
|
}
|
|
2986
|
-
|
|
2987
|
-
|
|
2431
|
+
/** Delete offline sessions and their mail. \`graceMs\` 0 removes every one at once. */
|
|
2432
|
+
removeOffline(graceMs) {
|
|
2433
|
+
const nowMs = this.now().getTime();
|
|
2434
|
+
const gone = this.store.allSessions().filter((r) => {
|
|
2435
|
+
if (r.status !== "offline") return false;
|
|
2436
|
+
const since = this.offlineSince.get(r.id) ?? Date.parse(r.lastSeenAt);
|
|
2437
|
+
return nowMs - since >= graceMs;
|
|
2438
|
+
});
|
|
2439
|
+
if (gone.length === 0) return;
|
|
2988
2440
|
this.store.tx(() => {
|
|
2989
|
-
for (const r of
|
|
2441
|
+
for (const r of gone) this.store.deleteSession(r.id);
|
|
2990
2442
|
});
|
|
2991
|
-
for (const r of
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
*/
|
|
2999
|
-
workspaceGone(row, nowMs) {
|
|
3000
|
-
if (nowMs - Date.parse(row.lastSeenAt) < 3e5) return false;
|
|
3001
|
-
if (this.store.unreadCount(row.id) > 0) return false;
|
|
3002
|
-
if (row.hostPid !== void 0 && this.isAlive(row.hostPid)) return false;
|
|
3003
|
-
return !this.pathExists(row.cwd) || row.repoRoot !== void 0 && !this.pathExists(row.repoRoot);
|
|
2443
|
+
for (const r of gone) {
|
|
2444
|
+
this.listeners.delete(r.id);
|
|
2445
|
+
this.woken.delete(r.id);
|
|
2446
|
+
this.wokenAt.delete(r.id);
|
|
2447
|
+
this.wakersOff.delete(r.id);
|
|
2448
|
+
this.offlineSince.delete(r.id);
|
|
2449
|
+
}
|
|
3004
2450
|
}
|
|
3005
2451
|
claim(sessionId) {
|
|
3006
2452
|
this.requireSession(sessionId);
|
|
@@ -3045,45 +2491,92 @@ var Daemon = class {
|
|
|
3045
2491
|
previous: res.previous
|
|
3046
2492
|
};
|
|
3047
2493
|
}
|
|
2494
|
+
clearLead(conn) {
|
|
2495
|
+
this.requireCli(conn, "clear the lead");
|
|
2496
|
+
const holder = this.store.holder();
|
|
2497
|
+
const res = clearOrchestrator(holder, this.named(this.store.allSessions()));
|
|
2498
|
+
const at = this.iso();
|
|
2499
|
+
const sent = [];
|
|
2500
|
+
this.store.tx(() => {
|
|
2501
|
+
this.store.setHolder(null);
|
|
2502
|
+
for (const n of res.notices) {
|
|
2503
|
+
const m = {
|
|
2504
|
+
id: newMessageId(),
|
|
2505
|
+
from: DAEMON_SENDER_ID,
|
|
2506
|
+
to: n.to,
|
|
2507
|
+
kind: "system",
|
|
2508
|
+
body: {
|
|
2509
|
+
event: n.event,
|
|
2510
|
+
detail: n.detail
|
|
2511
|
+
},
|
|
2512
|
+
urgent: false,
|
|
2513
|
+
createdAt: at
|
|
2514
|
+
};
|
|
2515
|
+
this.store.insertMessage(m, n.to, at);
|
|
2516
|
+
sent.push(m);
|
|
2517
|
+
}
|
|
2518
|
+
});
|
|
2519
|
+
if (holder !== null) {
|
|
2520
|
+
this.emit({
|
|
2521
|
+
event: "orchestrator.changed",
|
|
2522
|
+
data: {
|
|
2523
|
+
orchestrator: null,
|
|
2524
|
+
previous: holder
|
|
2525
|
+
}
|
|
2526
|
+
});
|
|
2527
|
+
if (res.previous) this.emitSession(res.previous, "updated");
|
|
2528
|
+
for (const m of sent) this.emitMessage(m, m.to);
|
|
2529
|
+
}
|
|
2530
|
+
return { previous: res.previous };
|
|
2531
|
+
}
|
|
3048
2532
|
sendMessage(p) {
|
|
3049
2533
|
const sender = this.requireSession(p.sessionId);
|
|
3050
2534
|
if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
|
|
3051
2535
|
if (p.kind === "system") throw new ConvenoError(RpcErrorCode.InvalidParams, "Messages of kind \"system\" are made by the Conveno daemon only. Send kind \"text\" instead.");
|
|
2536
|
+
return this.deliverFrom({
|
|
2537
|
+
id: sender.id,
|
|
2538
|
+
name: sender.name,
|
|
2539
|
+
cli: sender.cli,
|
|
2540
|
+
hops: sender.status === "busy" ? sender.turnHops : 0
|
|
2541
|
+
}, p);
|
|
2542
|
+
}
|
|
2543
|
+
/** The recipient names the owner: `you`, or the id of a message the owner sent. */
|
|
2544
|
+
isOwnerRecipient(to) {
|
|
2545
|
+
return to === "you" || to === OWNER_SESSION_ID;
|
|
2546
|
+
}
|
|
2547
|
+
/**
|
|
2548
|
+
* Route one message from \`sender\` (a session, or the owner) to a session, or to a session on
|
|
2549
|
+
* another device. The owner is not a session and has no inbox: a session cannot message \`you\`.
|
|
2550
|
+
*/
|
|
2551
|
+
deliverFrom(sender, p) {
|
|
3052
2552
|
if (p.replyTo !== void 0 && !this.store.hasMessage(p.replyTo)) throw new ConvenoError(RpcErrorCode.NotFound, `Message ${p.replyTo} does not exist, so it cannot be replied to. Check the message id.`);
|
|
3053
|
-
const rows = this.store.allSessions();
|
|
3054
|
-
let target;
|
|
3055
|
-
try {
|
|
3056
|
-
target = resolveRecipient(p.to, this.named(rows), this.store.holder());
|
|
3057
|
-
} catch (e) {
|
|
3058
|
-
const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
|
|
3059
|
-
if (!remote) throw e;
|
|
3060
|
-
return this.sendToRemote(sender, remote, p);
|
|
3061
|
-
}
|
|
3062
|
-
const targetRow = rows.find((r) => r.id === target.id);
|
|
3063
|
-
if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
|
|
3064
2553
|
const at = this.iso();
|
|
3065
|
-
const
|
|
2554
|
+
const rows = this.store.allSessions();
|
|
2555
|
+
const make = (to) => ({
|
|
3066
2556
|
id: newMessageId(),
|
|
3067
2557
|
from: sender.id,
|
|
3068
|
-
to
|
|
2558
|
+
to,
|
|
3069
2559
|
kind: p.kind,
|
|
3070
2560
|
body: p.body,
|
|
3071
2561
|
urgent: p.urgent,
|
|
3072
2562
|
createdAt: at,
|
|
3073
2563
|
fromName: sender.name,
|
|
3074
|
-
fromCli: sender.cli,
|
|
2564
|
+
...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
|
|
3075
2565
|
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
3076
|
-
};
|
|
3077
|
-
const enableAuto = sender.id !== targetRow.id && effectiveHolder(this.store.holder(), this.named(rows))?.id === sender.id && !targetRow.auto && !targetRow.autoExplicit;
|
|
3078
|
-
const hops = sender.status === "busy" ? sender.turnHops : 0;
|
|
3079
|
-
this.store.tx(() => {
|
|
3080
|
-
this.store.insertMessage(message, targetRow.id, at, hops);
|
|
3081
|
-
if (enableAuto) this.store.updateSession(targetRow.id, { auto: true });
|
|
3082
2566
|
});
|
|
3083
|
-
if (
|
|
3084
|
-
|
|
3085
|
-
|
|
2567
|
+
if (this.isOwnerRecipient(p.to)) throw new ConvenoError(RpcErrorCode.InvalidParams, sender.id === OWNER_SESSION_ID ? "You cannot send a message to yourself." : "The user reads your replies in this session. Answer there instead of sending a message.");
|
|
2568
|
+
let target;
|
|
2569
|
+
try {
|
|
2570
|
+
target = resolveRecipient(p.to, this.named(rows), this.store.holder());
|
|
2571
|
+
} catch (e) {
|
|
2572
|
+
const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
|
|
2573
|
+
if (!remote) throw e;
|
|
2574
|
+
return this.sendToRemote(make(p.to), remote, sender.hops);
|
|
3086
2575
|
}
|
|
2576
|
+
const targetRow = rows.find((r) => r.id === target.id);
|
|
2577
|
+
if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
|
|
2578
|
+
const message = make(p.to);
|
|
2579
|
+
this.store.insertMessage(message, targetRow.id, at, sender.hops);
|
|
3087
2580
|
this.emitMessage(message, targetRow.id);
|
|
3088
2581
|
return {
|
|
3089
2582
|
message,
|
|
@@ -3094,174 +2587,255 @@ var Daemon = class {
|
|
|
3094
2587
|
}
|
|
3095
2588
|
};
|
|
3096
2589
|
}
|
|
3097
|
-
|
|
2590
|
+
requireCli(conn, what) {
|
|
2591
|
+
if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, `Only the conveno command and app can ${what}. A session cannot act as the owner.`);
|
|
2592
|
+
}
|
|
2593
|
+
ownerSend(conn, p) {
|
|
2594
|
+
this.requireCli(conn, "send as the owner");
|
|
2595
|
+
return this.deliverFrom({
|
|
2596
|
+
id: OWNER_SESSION_ID,
|
|
2597
|
+
name: "you",
|
|
2598
|
+
hops: 0
|
|
2599
|
+
}, {
|
|
2600
|
+
to: p.to,
|
|
2601
|
+
kind: "text",
|
|
2602
|
+
body: { text: p.text },
|
|
2603
|
+
urgent: p.urgent,
|
|
2604
|
+
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
2605
|
+
});
|
|
2606
|
+
}
|
|
2607
|
+
/**
|
|
2608
|
+
* \`acp\` for an ACP host. \`live\` while something can wake the session: a listener's connection
|
|
2609
|
+
* is open, or the session is busy in a turn a listener's CLI ends with its own hook (it continues
|
|
2610
|
+
* with what waits, then arms a new listener), or a daemon waker can reach it. Otherwise the CLI's
|
|
2611
|
+
* own tier.
|
|
2612
|
+
*/
|
|
3098
2613
|
tierFor(row) {
|
|
3099
|
-
|
|
3100
|
-
if (row.
|
|
3101
|
-
if (
|
|
2614
|
+
if (row.deliveryTier === "acp") return "acp";
|
|
2615
|
+
if (this.listenerConnected(row.id)) return "live";
|
|
2616
|
+
if (row.status === "busy" && this.listeners.has(row.id)) return "live";
|
|
2617
|
+
if (this.daemonWakerFor(row)) return "live";
|
|
3102
2618
|
return row.deliveryTier;
|
|
3103
2619
|
}
|
|
2620
|
+
listenerConnected(id) {
|
|
2621
|
+
const conn = this.listeners.get(id)?.conn;
|
|
2622
|
+
return conn !== void 0 && this.conns.has(conn) && !conn.socket.destroyed;
|
|
2623
|
+
}
|
|
2624
|
+
/** A connection closed: a listener that asked on it no longer makes its session wakeable. */
|
|
2625
|
+
listenerGone(conn) {
|
|
2626
|
+
if (this.stopping) return;
|
|
2627
|
+
for (const [id, rec] of this.listeners) {
|
|
2628
|
+
if (rec.conn !== conn) continue;
|
|
2629
|
+
rec.conn = void 0;
|
|
2630
|
+
this.emitSession(id, "updated");
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
daemonWakerFor(row) {
|
|
2634
|
+
if (row.nativeId === void 0 || this.wakersOff.has(row.id)) return void 0;
|
|
2635
|
+
return this.wakers[row.cli];
|
|
2636
|
+
}
|
|
3104
2637
|
/**
|
|
3105
|
-
*
|
|
3106
|
-
* session
|
|
3107
|
-
*
|
|
2638
|
+
* A message landed for \`id\`. When its CLI has a daemon waker, no listener is connected and the
|
|
2639
|
+
* session is idle, hand the waiting messages to the waker (under the wake limit, like
|
|
2640
|
+
* \`turn.wake\`, and under \`DAEMON_WAKE_BYTES\`, since they go on a command line). \`queued\`
|
|
2641
|
+
* and \`unknown\` keep them delivered (a wake that timed out may have landed: a requeue could
|
|
2642
|
+
* deliver them twice). \`failed\` and \`unsupported\` put them back; after \`failed\` or the wake
|
|
2643
|
+
* limit, the sweep tries again with a growing delay. One wake per session at a time.
|
|
3108
2644
|
*/
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
const row =
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
const caller = this.requireOnline(p.sessionId);
|
|
3117
|
-
if (this.orchestratorNow() !== caller.id) throw new ConvenoError(RpcErrorCode.PermissionRequired, "Only the orchestrator can resume auto mode for another session. The owner can run: conveno auto resume <session>");
|
|
3118
|
-
if (p.auto !== void 0 || p.limit !== void 0) throw new ConvenoError(RpcErrorCode.PermissionRequired, "A session can only resume auto mode. Turning it on or off and changing the limit is up to the owner: conveno auto");
|
|
3119
|
-
if (row.autoPausedBy === void 0) throw new ConvenoError(RpcErrorCode.PermissionRequired, `Auto mode for "${row.name}" is not paused.`);
|
|
3120
|
-
const last = row.autoOrchResumedAt ? Date.parse(row.autoOrchResumedAt) : NaN;
|
|
3121
|
-
if (this.now().getTime() - last < this.autoLimits.windowMs) {
|
|
3122
|
-
const minutes = Math.round(this.autoLimits.windowMs / 6e4);
|
|
3123
|
-
throw new ConvenoError(RpcErrorCode.PermissionRequired, `The orchestrator already resumed auto mode for "${row.name}" within the last ${minutes} minutes. Only the owner can resume it now: conveno auto resume ${row.name}`);
|
|
3124
|
-
}
|
|
2645
|
+
daemonWake(id) {
|
|
2646
|
+
if (this.daemonWaking.has(id)) return;
|
|
2647
|
+
const row = this.store.getSession(id);
|
|
2648
|
+
const wake = row?.status === "idle" && !this.listenerConnected(id) && this.daemonWakerFor(row);
|
|
2649
|
+
if (!row || !wake) {
|
|
2650
|
+
this.wakeRetry.delete(id);
|
|
2651
|
+
return;
|
|
3125
2652
|
}
|
|
3126
|
-
const
|
|
3127
|
-
|
|
3128
|
-
this.store.
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
2653
|
+
const d = this.continueWith(row, true, false, DAEMON_WAKE_BYTES);
|
|
2654
|
+
if (d.messages.length === 0) {
|
|
2655
|
+
const queued = this.store.entries(id, { states: ["queued"] });
|
|
2656
|
+
if (autoCandidates(queued, id).length > 0) this.scheduleWakeRetry(id);
|
|
2657
|
+
else this.wakeRetry.delete(id);
|
|
2658
|
+
return;
|
|
2659
|
+
}
|
|
2660
|
+
this.markWoken(id, d.messages);
|
|
2661
|
+
this.daemonWaking.add(id);
|
|
2662
|
+
const text = formatContinuation(d.messages, d.orchestrator, d.remaining);
|
|
2663
|
+
const session = this.view(this.requireSession(id));
|
|
2664
|
+
(async () => {
|
|
2665
|
+
let outcome;
|
|
2666
|
+
try {
|
|
2667
|
+
outcome = await wake({
|
|
2668
|
+
session,
|
|
2669
|
+
text,
|
|
2670
|
+
messages: d.messages,
|
|
2671
|
+
...row.nativeId !== void 0 ? { nativeId: row.nativeId } : {}
|
|
2672
|
+
});
|
|
2673
|
+
} catch (e) {
|
|
2674
|
+
this.log.error(`${row.cli} waker failed`, e);
|
|
2675
|
+
outcome = "failed";
|
|
2676
|
+
}
|
|
2677
|
+
this.daemonWaking.delete(id);
|
|
2678
|
+
if (outcome === "queued" || outcome === "unknown" || this.stopping) {
|
|
2679
|
+
this.wakeRetry.delete(id);
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
if (outcome === "unsupported") {
|
|
2683
|
+
this.wakeRetry.delete(id);
|
|
2684
|
+
this.wakersOff.add(row.id);
|
|
2685
|
+
this.relay?.sessionsChanged();
|
|
2686
|
+
}
|
|
2687
|
+
if (this.store.getSession(id)?.status === "offline") {
|
|
2688
|
+
this.wakeRetry.delete(id);
|
|
2689
|
+
return;
|
|
2690
|
+
}
|
|
2691
|
+
this.requeueFor(id, d.messages.map((m) => m.id));
|
|
2692
|
+
if (outcome === "failed") this.scheduleWakeRetry(id);
|
|
2693
|
+
})();
|
|
2694
|
+
}
|
|
2695
|
+
/** Try a daemon wake of \`id\` again later, each time waiting twice as long, up to a cap. */
|
|
2696
|
+
scheduleWakeRetry(id) {
|
|
2697
|
+
const delayMs = Math.min((this.wakeRetry.get(id)?.delayMs ?? 0) * 2 || WAKE_RETRY_MS, WAKE_RETRY_MAX_MS);
|
|
2698
|
+
this.wakeRetry.set(id, {
|
|
2699
|
+
atMs: this.now().getTime() + delayMs,
|
|
2700
|
+
delayMs
|
|
2701
|
+
});
|
|
2702
|
+
}
|
|
2703
|
+
/** Run the daemon wakes whose retry is due. Called by the sweep. */
|
|
2704
|
+
retryDaemonWakes(nowMs) {
|
|
2705
|
+
for (const [id, r] of [...this.wakeRetry]) if (r.atMs <= nowMs) this.daemonWake(id);
|
|
2706
|
+
}
|
|
2707
|
+
markWoken(id, messages) {
|
|
2708
|
+
this.woken.set(id, new Set(messages.map((m) => m.id)));
|
|
2709
|
+
this.wokenAt.set(id, this.now().getTime());
|
|
2710
|
+
}
|
|
2711
|
+
/**
|
|
2712
|
+
* Messages a wake handed over that no turn took up: the CLI accepted them but the turn never
|
|
2713
|
+
* started (Codex keeps queued input while a turn is interrupted). Counted as unread so status
|
|
2714
|
+
* shows them. A turn start or end clears \`woken\`.
|
|
2715
|
+
*/
|
|
2716
|
+
stalledWoken(id) {
|
|
2717
|
+
const at = this.wokenAt.get(id);
|
|
2718
|
+
if (at === void 0 || this.now().getTime() - at < WOKEN_STALL_MS) return 0;
|
|
2719
|
+
return this.woken.get(id)?.size ?? 0;
|
|
2720
|
+
}
|
|
2721
|
+
/**
|
|
2722
|
+
* Delivered messages go back to queued. When they are from the last wake and that wake made the
|
|
2723
|
+
* session busy, the wake never became a turn: the session is idle again and the wake does not
|
|
2724
|
+
* count against the limit.
|
|
2725
|
+
*/
|
|
2726
|
+
requeue(p) {
|
|
2727
|
+
this.requireSession(p.sessionId);
|
|
2728
|
+
return this.requeueFor(p.sessionId, p.ids);
|
|
2729
|
+
}
|
|
2730
|
+
requeueFor(id, ids) {
|
|
2731
|
+
const woken = this.woken.get(id);
|
|
2732
|
+
const fromWake = woken !== void 0 && ids.some((m) => woken.has(m));
|
|
2733
|
+
const res = this.store.tx(() => {
|
|
2734
|
+
const r = requeueEntries(this.store.entries(id, { ids: [...ids] }), ids);
|
|
2735
|
+
for (const e of r.changed) this.store.saveEntry(id, e);
|
|
2736
|
+
const row = this.requireSession(id);
|
|
2737
|
+
const idle = fromWake && r.changed.length > 0 && row.status === "busy";
|
|
2738
|
+
if (idle) this.store.updateSession(id, {
|
|
2739
|
+
status: "idle",
|
|
2740
|
+
turnHops: 0,
|
|
2741
|
+
autoRuns: row.autoRuns.slice(0, -1)
|
|
3140
2742
|
});
|
|
3141
|
-
|
|
2743
|
+
return {
|
|
2744
|
+
requeued: r.changed.length,
|
|
2745
|
+
idle
|
|
2746
|
+
};
|
|
3142
2747
|
});
|
|
3143
|
-
this.
|
|
3144
|
-
|
|
2748
|
+
if (fromWake) this.woken.delete(id);
|
|
2749
|
+
if (res.idle) this.emitSession(id, "updated");
|
|
2750
|
+
return { requeued: res.requeued };
|
|
3145
2751
|
}
|
|
3146
2752
|
/**
|
|
3147
2753
|
* The user typed a prompt: the session is busy, and messages it sends start a new chain (0 hops).
|
|
3148
|
-
* A pause stays until the owner or the orchestrator resumes it.
|
|
3149
2754
|
*/
|
|
3150
2755
|
turnStart(sessionId) {
|
|
3151
|
-
this.requireOnline(sessionId);
|
|
3152
|
-
this.
|
|
2756
|
+
const row = this.requireOnline(sessionId);
|
|
2757
|
+
const fromWake = this.woken.has(sessionId) && row.status === "busy";
|
|
2758
|
+
this.woken.delete(sessionId);
|
|
2759
|
+
this.store.updateSession(sessionId, fromWake ? { status: "busy" } : {
|
|
3153
2760
|
status: "busy",
|
|
3154
2761
|
turnHops: 0
|
|
3155
2762
|
});
|
|
3156
2763
|
this.emitSession(sessionId, "updated");
|
|
3157
2764
|
return { session: this.view(this.requireSession(sessionId)) };
|
|
3158
2765
|
}
|
|
3159
|
-
/** The notice a session gets when its auto mode pauses. It waits for the next prompt. */
|
|
3160
|
-
pauseNotice(row, reason, at) {
|
|
3161
|
-
const minutes = Math.round(this.autoLimits.windowMs / 6e4);
|
|
3162
|
-
const limit = row.autoLimit ?? this.autoLimits.limit;
|
|
3163
|
-
const detail = `Conveno paused auto mode for this session (${pauseLabel(reason)}): ${limit} automatic turns within ${minutes} minutes, or a message that ${limit} automatic turns led to with no person in between (sessions answering each other). Messages still arrive at the next prompt. The owner can resume it with: conveno auto resume ${row.name}; the orchestrator can once per ${minutes} minutes.`;
|
|
3164
|
-
return {
|
|
3165
|
-
id: newMessageId(),
|
|
3166
|
-
from: DAEMON_SENDER_ID,
|
|
3167
|
-
to: row.id,
|
|
3168
|
-
kind: "system",
|
|
3169
|
-
body: {
|
|
3170
|
-
event: "auto.paused",
|
|
3171
|
-
detail
|
|
3172
|
-
},
|
|
3173
|
-
urgent: false,
|
|
3174
|
-
createdAt: at
|
|
3175
|
-
};
|
|
3176
|
-
}
|
|
3177
2766
|
/**
|
|
3178
|
-
* Hand the session its waiting messages to continue with, if
|
|
2767
|
+
* Hand the session its waiting messages to continue with, if the wake limit allows it.
|
|
3179
2768
|
* On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
|
|
3180
2769
|
* handed over means the session is now idle. One transaction.
|
|
3181
2770
|
*/
|
|
3182
|
-
continueWith(row, allow, endOfTurn) {
|
|
2771
|
+
continueWith(row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES, maxChars) {
|
|
3183
2772
|
const nowMs = this.now().getTime();
|
|
3184
2773
|
const at = this.iso();
|
|
3185
2774
|
const orchestrator = this.orchestratorNow();
|
|
3186
|
-
let pausedBy = row.autoPausedBy;
|
|
3187
|
-
let notice;
|
|
3188
2775
|
const res = this.store.tx(() => {
|
|
3189
2776
|
const queued = this.store.entries(row.id, { states: ["queued"] });
|
|
3190
2777
|
const candidates = allow ? autoCandidates(queued, row.id) : [];
|
|
3191
|
-
const decision = decideAutoContinue({
|
|
3192
|
-
auto: row.auto,
|
|
3193
|
-
...row.autoPausedBy !== void 0 ? { pausedBy: row.autoPausedBy } : {},
|
|
3194
|
-
...row.autoLimit !== void 0 ? { limit: row.autoLimit } : {},
|
|
3195
|
-
runs: row.autoRuns
|
|
3196
|
-
}, candidates, nowMs, this.autoLimits);
|
|
2778
|
+
const decision = decideAutoContinue({ runs: row.autoRuns }, candidates, nowMs, this.autoLimits);
|
|
3197
2779
|
if (decision.continue) {
|
|
3198
|
-
const
|
|
2780
|
+
const fit = takeWithinBytes(candidates.slice(0, 20), maxBytes);
|
|
2781
|
+
const { taken, preview } = maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, maxChars, (ms, cut) => formatContinuation(ms, orchestrator, queued.length - (cut ? 0 : ms.length)));
|
|
3199
2782
|
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
3200
2783
|
for (const e of updated) this.store.saveEntry(row.id, e);
|
|
3201
2784
|
this.store.updateSession(row.id, {
|
|
3202
2785
|
status: "busy",
|
|
3203
2786
|
autoRuns: decision.runs,
|
|
3204
|
-
turnHops: turnHops(taken)
|
|
2787
|
+
turnHops: turnHops(preview ? fit.slice(0, 1) : taken)
|
|
3205
2788
|
});
|
|
2789
|
+
if (preview) return {
|
|
2790
|
+
messages: [preview],
|
|
2791
|
+
remaining: queued.length
|
|
2792
|
+
};
|
|
3206
2793
|
return {
|
|
3207
2794
|
messages: updated.map((e) => e.message),
|
|
3208
2795
|
remaining: queued.length - taken.length
|
|
3209
2796
|
};
|
|
3210
2797
|
}
|
|
3211
|
-
if (decision.pause !== void 0) {
|
|
3212
|
-
pausedBy = decision.pause;
|
|
3213
|
-
notice = this.pauseNotice(row, decision.pause, at);
|
|
3214
|
-
this.store.insertMessage(notice, row.id, at);
|
|
3215
|
-
this.store.updateSession(row.id, {
|
|
3216
|
-
autoPausedAt: at,
|
|
3217
|
-
autoPausedBy: decision.pause
|
|
3218
|
-
});
|
|
3219
|
-
}
|
|
3220
2798
|
if (endOfTurn) this.store.updateSession(row.id, {
|
|
3221
2799
|
status: "idle",
|
|
3222
2800
|
turnHops: 0
|
|
3223
2801
|
});
|
|
3224
2802
|
return {
|
|
3225
2803
|
messages: [],
|
|
3226
|
-
remaining: queued.length
|
|
2804
|
+
remaining: queued.length
|
|
3227
2805
|
};
|
|
3228
2806
|
});
|
|
3229
|
-
if (
|
|
3230
|
-
if ((res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") || notice) this.emitSession(row.id, "updated");
|
|
2807
|
+
if (res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") this.emitSession(row.id, "updated");
|
|
3231
2808
|
return {
|
|
3232
2809
|
...res,
|
|
3233
|
-
auto: row.auto,
|
|
3234
|
-
paused: pausedBy !== void 0,
|
|
3235
|
-
...pausedBy !== void 0 ? { pausedBy } : {},
|
|
3236
2810
|
orchestrator
|
|
3237
2811
|
};
|
|
3238
2812
|
}
|
|
3239
2813
|
turnEnd(p) {
|
|
3240
2814
|
const row = this.requireOnline(p.sessionId);
|
|
2815
|
+
this.woken.delete(p.sessionId);
|
|
3241
2816
|
if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
|
|
3242
|
-
return this.continueWith(row, p.allowContinue, true);
|
|
2817
|
+
return this.continueWith(row, p.allowContinue, true, RESPONSE_BUDGET_BYTES, p.maxChars);
|
|
3243
2818
|
}
|
|
3244
2819
|
/**
|
|
3245
2820
|
* An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
|
|
3246
2821
|
* `superseded` and stops. A busy session is not woken; its messages wait for the end of the turn.
|
|
3247
2822
|
*/
|
|
3248
|
-
turnWake(p) {
|
|
2823
|
+
turnWake(conn, p) {
|
|
3249
2824
|
const row = this.requireOnline(p.sessionId);
|
|
3250
2825
|
const known = this.listeners.get(row.id);
|
|
3251
2826
|
if (known?.retired.includes(p.listenerId)) return {
|
|
3252
2827
|
messages: [],
|
|
3253
2828
|
remaining: this.store.unreadCount(row.id),
|
|
3254
|
-
auto: row.auto,
|
|
3255
|
-
paused: row.autoPausedBy !== void 0,
|
|
3256
|
-
...row.autoPausedBy !== void 0 ? { pausedBy: row.autoPausedBy } : {},
|
|
3257
2829
|
orchestrator: this.orchestratorNow(),
|
|
3258
2830
|
superseded: true
|
|
3259
2831
|
};
|
|
2832
|
+
const wasConnected = this.listenerConnected(row.id);
|
|
3260
2833
|
if (known?.current !== p.listenerId) {
|
|
3261
2834
|
const retired = known ? [...known.retired, known.current].slice(-64) : [];
|
|
3262
2835
|
this.listeners.set(row.id, {
|
|
3263
2836
|
current: p.listenerId,
|
|
3264
|
-
retired
|
|
2837
|
+
retired,
|
|
2838
|
+
conn
|
|
3265
2839
|
});
|
|
3266
2840
|
if (known) this.emit({
|
|
3267
2841
|
event: "session.updated",
|
|
@@ -3270,24 +2844,31 @@ var Daemon = class {
|
|
|
3270
2844
|
change: "updated"
|
|
3271
2845
|
}
|
|
3272
2846
|
}, row.id);
|
|
3273
|
-
}
|
|
2847
|
+
} else known.conn = conn;
|
|
2848
|
+
if (!wasConnected) this.relay?.sessionsChanged();
|
|
2849
|
+
const d = this.continueWith(row, row.status === "idle", false, RESPONSE_BUDGET_BYTES, p.maxChars);
|
|
2850
|
+
if (d.messages.length > 0) this.markWoken(row.id, d.messages);
|
|
3274
2851
|
return {
|
|
3275
|
-
...
|
|
2852
|
+
...d,
|
|
3276
2853
|
superseded: false
|
|
3277
2854
|
};
|
|
3278
2855
|
}
|
|
3279
2856
|
inbox(p) {
|
|
3280
2857
|
this.requireSession(p.sessionId);
|
|
2858
|
+
return this.readInboxOf(p.sessionId, p.unreadOnly, p.limit);
|
|
2859
|
+
}
|
|
2860
|
+
/** A mailbox's messages, oldest first, marked read. */
|
|
2861
|
+
readInboxOf(id, unreadOnly, limit) {
|
|
3281
2862
|
const at = this.iso();
|
|
3282
2863
|
return this.store.tx(() => {
|
|
3283
|
-
const entries = this.store.entries(
|
|
2864
|
+
const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
|
|
3284
2865
|
const res = readInbox(entries, {
|
|
3285
|
-
unreadOnly
|
|
3286
|
-
limit
|
|
2866
|
+
unreadOnly,
|
|
2867
|
+
limit,
|
|
3287
2868
|
maxBytes: RESPONSE_BUDGET_BYTES
|
|
3288
2869
|
}, at);
|
|
3289
2870
|
const changed = new Set(res.returned.map((e) => e.message.id));
|
|
3290
|
-
for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(
|
|
2871
|
+
for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
|
|
3291
2872
|
return {
|
|
3292
2873
|
messages: res.returned.map((e) => e.message),
|
|
3293
2874
|
unreadCount: res.unreadCount
|
|
@@ -3299,9 +2880,14 @@ var Daemon = class {
|
|
|
3299
2880
|
const at = this.iso();
|
|
3300
2881
|
return this.store.tx(() => {
|
|
3301
2882
|
const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
|
|
3302
|
-
const
|
|
2883
|
+
const fit = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
|
|
2884
|
+
const { taken, preview } = p.maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, p.maxChars, (ms) => formatHookContext(ms));
|
|
3303
2885
|
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
3304
2886
|
for (const e of updated) this.store.saveEntry(p.sessionId, e);
|
|
2887
|
+
if (preview) return {
|
|
2888
|
+
messages: [preview],
|
|
2889
|
+
remaining: pending.length
|
|
2890
|
+
};
|
|
3305
2891
|
return {
|
|
3306
2892
|
messages: updated.map((e) => e.message),
|
|
3307
2893
|
remaining: pending.length - taken.length
|
|
@@ -3310,19 +2896,24 @@ var Daemon = class {
|
|
|
3310
2896
|
}
|
|
3311
2897
|
ack(p) {
|
|
3312
2898
|
this.requireSession(p.sessionId);
|
|
2899
|
+
return this.ackFor(p.sessionId, p.ids);
|
|
2900
|
+
}
|
|
2901
|
+
ackFor(id, ids) {
|
|
3313
2902
|
const at = this.iso();
|
|
3314
2903
|
return this.store.tx(() => {
|
|
3315
|
-
const entries = this.store.entries(
|
|
3316
|
-
const res = ackEntries(entries,
|
|
3317
|
-
for (const e of res.entries) this.store.saveEntry(
|
|
2904
|
+
const entries = this.store.entries(id, { ids });
|
|
2905
|
+
const res = ackEntries(entries, ids, at);
|
|
2906
|
+
for (const e of res.entries) this.store.saveEntry(id, e);
|
|
3318
2907
|
return { acked: res.acked };
|
|
3319
2908
|
});
|
|
3320
2909
|
}
|
|
3321
2910
|
subscribe(conn, p) {
|
|
3322
|
-
|
|
2911
|
+
if (p.sessionId === void 0) {
|
|
2912
|
+
if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, "Pass sessionId to subscribe. Only the conveno command and app can subscribe to every event.");
|
|
2913
|
+
} else this.requireSession(p.sessionId);
|
|
3323
2914
|
const topics = p.topics ?? [...EVENT_NAMES];
|
|
3324
2915
|
conn.sub = {
|
|
3325
|
-
sessionId: p.sessionId,
|
|
2916
|
+
...p.sessionId !== void 0 ? { sessionId: p.sessionId } : {},
|
|
3326
2917
|
topics: new Set(topics)
|
|
3327
2918
|
};
|
|
3328
2919
|
return { subscribed: topics };
|
|
@@ -3343,20 +2934,8 @@ var Daemon = class {
|
|
|
3343
2934
|
default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
|
|
3344
2935
|
}
|
|
3345
2936
|
}
|
|
3346
|
-
sendToRemote(
|
|
3347
|
-
|
|
3348
|
-
id: newMessageId(),
|
|
3349
|
-
from: sender.id,
|
|
3350
|
-
to: p.to,
|
|
3351
|
-
kind: p.kind,
|
|
3352
|
-
body: p.body,
|
|
3353
|
-
urgent: p.urgent,
|
|
3354
|
-
createdAt: this.iso(),
|
|
3355
|
-
fromName: sender.name,
|
|
3356
|
-
fromCli: sender.cli,
|
|
3357
|
-
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
3358
|
-
};
|
|
3359
|
-
this.relay.sendRemote(target, message);
|
|
2937
|
+
sendToRemote(message, target, hops) {
|
|
2938
|
+
this.relay.sendRemote(target, message, hops);
|
|
3360
2939
|
return {
|
|
3361
2940
|
message,
|
|
3362
2941
|
delivery: target.deliveryTier,
|
|
@@ -3370,15 +2949,18 @@ var Daemon = class {
|
|
|
3370
2949
|
relayHost() {
|
|
3371
2950
|
return {
|
|
3372
2951
|
log: this.log,
|
|
3373
|
-
localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) =>
|
|
3374
|
-
|
|
2952
|
+
localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => {
|
|
2953
|
+
const { nativeId: _n, ...s } = this.view(r);
|
|
2954
|
+
return s;
|
|
2955
|
+
}),
|
|
2956
|
+
deliverLocal: (m, to, hops = 0) => {
|
|
3375
2957
|
if (m.kind === "system") return "not_allowed";
|
|
3376
2958
|
const row = this.store.getSession(to);
|
|
3377
2959
|
if (!row) return "session_gone";
|
|
3378
2960
|
if (row.status === "offline") return "session_offline";
|
|
3379
2961
|
if (this.store.hasMessage(m.id)) return void 0;
|
|
3380
2962
|
if (this.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
|
|
3381
|
-
this.store.insertMessage(m, row.id, this.iso());
|
|
2963
|
+
this.store.insertMessage(m, row.id, this.iso(), hops);
|
|
3382
2964
|
this.emitMessage(m, row.id);
|
|
3383
2965
|
},
|
|
3384
2966
|
notify: (to, event, detail) => {
|
|
@@ -3400,30 +2982,18 @@ var Daemon = class {
|
|
|
3400
2982
|
}
|
|
3401
2983
|
};
|
|
3402
2984
|
}
|
|
3403
|
-
/**
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
* 2. Replaced by a newer live session with the same name, CLI and repo: delete after
|
|
3407
|
-
* PRUNE_SUPERSEDED_AFTER_MS.
|
|
3408
|
-
* 3. Otherwise delete after PRUNE_OFFLINE_AFTER_MS.
|
|
3409
|
-
* Besides these rules, `workspaceGone` forgets an offline session whose folder has been gone a while.
|
|
3410
|
-
*/
|
|
3411
|
-
shouldPrune(row, all, nowMs) {
|
|
3412
|
-
const offlineMs = nowMs - Date.parse(row.lastSeenAt);
|
|
3413
|
-
if (this.store.unreadCount(row.id) > 0) return offlineMs >= PRUNE_UNREAD_AFTER_MS;
|
|
3414
|
-
const place = (r) => r.repoRoot ?? r.cwd;
|
|
3415
|
-
return offlineMs >= (all.some((o) => o.id !== row.id && o.status !== "offline" && o.name === row.name && o.cli === row.cli && place(o) === place(row) && Date.parse(o.startedAt) > Date.parse(row.startedAt)) ? PRUNE_SUPERSEDED_AFTER_MS : PRUNE_OFFLINE_AFTER_MS);
|
|
2985
|
+
/** Remove every offline session at once. The daemon does this when it starts. */
|
|
2986
|
+
removeAllOffline() {
|
|
2987
|
+
this.removeOffline(0);
|
|
3416
2988
|
}
|
|
3417
2989
|
sweep() {
|
|
3418
|
-
this.tickets.sweep();
|
|
3419
2990
|
const nowMs = this.now().getTime();
|
|
2991
|
+
this.removeOffline(OFFLINE_GRACE_MS);
|
|
2992
|
+
this.retryDaemonWakes(nowMs);
|
|
3420
2993
|
let online = 0;
|
|
3421
2994
|
const rows = this.store.allSessions();
|
|
3422
2995
|
for (const row of rows) {
|
|
3423
|
-
if (row.status === "offline")
|
|
3424
|
-
if (this.shouldPrune(row, rows, nowMs) || this.workspaceGone(row, nowMs)) this.forgetRows([row]);
|
|
3425
|
-
continue;
|
|
3426
|
-
}
|
|
2996
|
+
if (row.status === "offline") continue;
|
|
3427
2997
|
const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), this.startedMs);
|
|
3428
2998
|
const verdict = evaluateLiveness({
|
|
3429
2999
|
lastSeenMs,
|
|
@@ -3436,6 +3006,14 @@ var Daemon = class {
|
|
|
3436
3006
|
else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
|
|
3437
3007
|
}
|
|
3438
3008
|
};
|
|
3009
|
+
/** Do two directory paths name the same place, ignoring trailing separators (and case on Windows)? */
|
|
3010
|
+
function samePath(a, b, platform) {
|
|
3011
|
+
const norm = (p) => {
|
|
3012
|
+
const s = p.replace(/[\\/]+$/, "");
|
|
3013
|
+
return platform === "win32" ? s.replace(/\\/g, "/").toLowerCase() : s;
|
|
3014
|
+
};
|
|
3015
|
+
return norm(a) === norm(b);
|
|
3016
|
+
}
|
|
3439
3017
|
const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
|
|
3440
3018
|
/** Start the relay client. A broken relay state is logged and leaves the daemon local-only. */
|
|
3441
3019
|
function startRelay(daemon, opts, relayOpts) {
|
|
@@ -3475,11 +3053,13 @@ async function startDaemon(opts) {
|
|
|
3475
3053
|
await clearStaleSocket(socketPath);
|
|
3476
3054
|
let closing;
|
|
3477
3055
|
let timer;
|
|
3056
|
+
const daemonLog = createDaemonLog(paths.daemonLog, { now });
|
|
3478
3057
|
const daemon = new Daemon(store, token, now, isAlive, opts.idleExitMs ?? 6e5, () => {
|
|
3479
3058
|
close().then(() => opts.onIdleExit?.());
|
|
3480
3059
|
}, () => {
|
|
3481
3060
|
close().then(() => opts.onShutdown?.());
|
|
3482
|
-
},
|
|
3061
|
+
}, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings);
|
|
3062
|
+
daemon.removeAllOffline();
|
|
3483
3063
|
const srv = createServer((socket) => daemon.attach(socket));
|
|
3484
3064
|
server = srv;
|
|
3485
3065
|
await new Promise((resolve, reject) => {
|
|
@@ -3494,6 +3074,7 @@ async function startDaemon(opts) {
|
|
|
3494
3074
|
function close() {
|
|
3495
3075
|
closing ??= (async () => {
|
|
3496
3076
|
if (timer) clearInterval(timer);
|
|
3077
|
+
daemon.stopping = true;
|
|
3497
3078
|
walker?.close();
|
|
3498
3079
|
daemon.relay?.stop();
|
|
3499
3080
|
const stopped = new Promise((resolve) => srv.close(() => resolve()));
|
|
@@ -3508,7 +3089,16 @@ async function startDaemon(opts) {
|
|
|
3508
3089
|
return {
|
|
3509
3090
|
socketPath,
|
|
3510
3091
|
close,
|
|
3511
|
-
sweep: () => daemon.sweep()
|
|
3092
|
+
sweep: () => daemon.sweep(),
|
|
3093
|
+
testRelay: {
|
|
3094
|
+
host: () => daemon.relayHost(),
|
|
3095
|
+
set: (relay) => {
|
|
3096
|
+
daemon.relay = relay && {
|
|
3097
|
+
sessionsChanged: () => {},
|
|
3098
|
+
...relay
|
|
3099
|
+
};
|
|
3100
|
+
}
|
|
3101
|
+
}
|
|
3512
3102
|
};
|
|
3513
3103
|
} catch (e) {
|
|
3514
3104
|
server?.close();
|
|
@@ -3517,264 +3107,11 @@ async function startDaemon(opts) {
|
|
|
3517
3107
|
throw e;
|
|
3518
3108
|
}
|
|
3519
3109
|
}
|
|
3520
|
-
// ../adapters/copilot/dist/transcript.js
|
|
3521
|
-
/**
|
|
3522
|
-
* GitHub Copilot CLI keeps each session in `~/.copilot/session-state/<session-id>/` (COPILOT_HOME
|
|
3523
|
-
* replaces `~/.copilot`): `events.jsonl`, an append-only stream of `{ type, data, id, timestamp }`
|
|
3524
|
-
* records, and `workspace.yaml` with `id`, `cwd`, `created_at` and `updated_at`.
|
|
3525
|
-
*
|
|
3526
|
-
* GitHub does not document this layout. It is taken from community write-ups of Copilot CLI 1.0.11
|
|
3527
|
-
* and later (the events.jsonl reference gist
|
|
3528
|
-
* https://gist.github.com/RockNoggin/8cc87f640ce5e3d284298a6db21f7523 and
|
|
3529
|
-
* https://github.com/microsoft/What-I-Did-Copilot/blob/main/docs/architecture.md) and the open
|
|
3530
|
-
* request for documentation, github/copilot-cli#3551. The reference bundle in
|
|
3531
|
-
* reference/bundles/copilot-cli is a closed binary whose strings do not show the layout, so this
|
|
3532
|
-
* reader is not checked against a real install. It skips what it does not recognise.
|
|
3533
|
-
*/
|
|
3534
|
-
const copilotHome = (env) => env.env.COPILOT_HOME?.trim() || join(env.home, ".copilot");
|
|
3535
|
-
const unquote = (s) => s.trim().replace(/^(["'])(.*)\1$/, "$2");
|
|
3536
|
-
/** The `cwd:` value of a workspace.yaml, which is flat `key: value` lines. */
|
|
3537
|
-
function yamlCwd(yaml) {
|
|
3538
|
-
const m = /^cwd:[ \t]*(.+)$/m.exec(yaml);
|
|
3539
|
-
return m?.[1] ? unquote(m[1]) : void 0;
|
|
3540
|
-
}
|
|
3541
|
-
async function sessionCwd(dir) {
|
|
3542
|
-
try {
|
|
3543
|
-
const cwd = yamlCwd(await readFile(join(dir, "workspace.yaml"), "utf8"));
|
|
3544
|
-
if (cwd) return cwd;
|
|
3545
|
-
} catch {}
|
|
3546
|
-
try {
|
|
3547
|
-
const head = await readHeadLine(join(dir, "events.jsonl"), 262144);
|
|
3548
|
-
const ev = head ? JSON.parse(head) : null;
|
|
3549
|
-
const data = isRecord(ev) && ev.type === "session.start" ? ev.data : void 0;
|
|
3550
|
-
const context = isRecord(data) && isRecord(data.context) ? data.context : void 0;
|
|
3551
|
-
return asString(context?.cwd);
|
|
3552
|
-
} catch {
|
|
3553
|
-
return;
|
|
3554
|
-
}
|
|
3555
|
-
}
|
|
3556
|
-
const textOf = (v) => {
|
|
3557
|
-
if (typeof v === "string") return v;
|
|
3558
|
-
if (Array.isArray(v)) return v.map(textOf).filter(Boolean).join("\n");
|
|
3559
|
-
if (isRecord(v)) return asString(v.text) ?? asString(v.content) ?? "";
|
|
3560
|
-
return "";
|
|
3561
|
-
};
|
|
3562
|
-
/** Normalize one events.jsonl record. Exported for tests. */
|
|
3563
|
-
function parseCopilotEvent(obj) {
|
|
3564
|
-
const data = isRecord(obj.data) ? obj.data : {};
|
|
3565
|
-
if (data.agentId !== void 0) return [];
|
|
3566
|
-
const at = toIso(obj.timestamp);
|
|
3567
|
-
const stamp = at ? { at } : {};
|
|
3568
|
-
switch (obj.type) {
|
|
3569
|
-
case "user.message": {
|
|
3570
|
-
const text = asString(data.content) ?? "";
|
|
3571
|
-
return text === "" ? [] : [{
|
|
3572
|
-
role: "user",
|
|
3573
|
-
text,
|
|
3574
|
-
...stamp
|
|
3575
|
-
}];
|
|
3576
|
-
}
|
|
3577
|
-
case "assistant.message": {
|
|
3578
|
-
const out = [];
|
|
3579
|
-
const text = asString(data.content) ?? "";
|
|
3580
|
-
if (text !== "") out.push({
|
|
3581
|
-
role: "assistant",
|
|
3582
|
-
text,
|
|
3583
|
-
...stamp
|
|
3584
|
-
});
|
|
3585
|
-
if (Array.isArray(data.toolRequests)) for (const r of data.toolRequests) {
|
|
3586
|
-
if (!isRecord(r)) continue;
|
|
3587
|
-
out.push({
|
|
3588
|
-
role: "tool",
|
|
3589
|
-
text: describeToolCall(asString(r.name) ?? "tool", r.arguments ?? r.intentionSummary),
|
|
3590
|
-
...stamp
|
|
3591
|
-
});
|
|
3592
|
-
}
|
|
3593
|
-
return out;
|
|
3594
|
-
}
|
|
3595
|
-
case "tool.execution_complete": {
|
|
3596
|
-
const result = isRecord(data.result) ? data.result : {};
|
|
3597
|
-
const text = textOf(result.content) || textOf(result.detailedContent);
|
|
3598
|
-
return text === "" ? [] : [{
|
|
3599
|
-
role: "tool",
|
|
3600
|
-
text,
|
|
3601
|
-
...stamp
|
|
3602
|
-
}];
|
|
3603
|
-
}
|
|
3604
|
-
default: return [];
|
|
3605
|
-
}
|
|
3606
|
-
}
|
|
3607
|
-
/** Find the session directory, or the reason there is none. */
|
|
3608
|
-
async function locateCopilotSession(q, env) {
|
|
3609
|
-
const root = join(copilotHome(env), "session-state");
|
|
3610
|
-
if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
|
|
3611
|
-
const dir = join(root, q.cliSessionId);
|
|
3612
|
-
if (await stat(join(dir, "events.jsonl")).then(() => true, () => false)) return { dir };
|
|
3613
|
-
}
|
|
3614
|
-
const since = Date.parse(q.startedAt);
|
|
3615
|
-
const floor = Number.isFinite(since) ? since - 5e3 : 0;
|
|
3616
|
-
for (const e of await entriesNewestFirst(root)) {
|
|
3617
|
-
if (!e.dir || e.mtimeMs < floor) continue;
|
|
3618
|
-
if (!await stat(join(e.path, "events.jsonl")).then(() => true, () => false)) continue;
|
|
3619
|
-
const cwd = await sessionCwd(e.path);
|
|
3620
|
-
if (cwd !== void 0 && samePath(cwd, q.cwd, env.platform)) return { dir: e.path };
|
|
3621
|
-
}
|
|
3622
|
-
return { error: "no session in session-state for this working directory since it started" };
|
|
3623
|
-
}
|
|
3624
|
-
const copilotTranscript = { async read(q, env) {
|
|
3625
|
-
try {
|
|
3626
|
-
const found = await locateCopilotSession(q, env);
|
|
3627
|
-
if ("error" in found) return notFound("Copilot", found.error);
|
|
3628
|
-
const { entries, more } = await tailJsonl(join(found.dir, "events.jsonl"), q.lastTurns, parseCopilotEvent);
|
|
3629
|
-
return {
|
|
3630
|
-
ok: true,
|
|
3631
|
-
entries,
|
|
3632
|
-
more
|
|
3633
|
-
};
|
|
3634
|
-
} catch (e) {
|
|
3635
|
-
return notFound("Copilot", e instanceof Error ? e.message : "read failed");
|
|
3636
|
-
}
|
|
3637
|
-
} };
|
|
3638
|
-
// ../adapters/grok/dist/transcript.js
|
|
3639
|
-
/**
|
|
3640
|
-
* Grok Build (xAI) keeps a session at
|
|
3641
|
-
* `$GROK_HOME/sessions/<encoded cwd>/<session id>/chat_history.jsonl`, `$GROK_HOME` defaulting to
|
|
3642
|
-
* `~/.grok`. The cwd directory name is the URL-encoded working directory; one over 255 bytes is
|
|
3643
|
-
* `<slug>-<blake3 hex16>` and holds a `.cwd` file with the real path.
|
|
3644
|
-
* reference/src/grok-build/crates/codegen/xai-dirs/src/lib.rs (grok home),
|
|
3645
|
-
* xai-grok-config/src/paths.rs (`encode_cwd_dirname`, `sessions_cwd_dir_in`),
|
|
3646
|
-
* xai-grok-shell/src/session/persistence.rs (`session_dir_in`).
|
|
3647
|
-
*
|
|
3648
|
-
* Each line of chat_history.jsonl is a `ConversationItem` tagged by `type`: `user`, `assistant`,
|
|
3649
|
-
* `tool_result`, `system`, `reasoning`, `backend_tool_call`
|
|
3650
|
-
* (xai-grok-sampling-types/src/conversation.rs). Items carry no timestamp.
|
|
3651
|
-
*/
|
|
3652
|
-
const grokHome = (env) => env.env.GROK_HOME?.trim() || join(env.home, ".grok");
|
|
3653
|
-
/** `urlencoding::encode`: everything but the unreserved characters `A-Za-z0-9-_.~` is percent-encoded. */
|
|
3654
|
-
function encodeCwdDirname(cwd) {
|
|
3655
|
-
return encodeURIComponent(cwd).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
3656
|
-
}
|
|
3657
|
-
const readText = (p) => readFile(p, "utf8").then((t) => t, () => void 0);
|
|
3658
|
-
const textParts = (content) => {
|
|
3659
|
-
if (typeof content === "string") return content;
|
|
3660
|
-
if (!Array.isArray(content)) return "";
|
|
3661
|
-
return content.map((p) => isRecord(p) && p.type === "text" ? asString(p.text) ?? "" : "").filter(Boolean).join("\n");
|
|
3662
|
-
};
|
|
3663
|
-
/** The user's own words: the CLI wraps the typed text in `<user_query>`. */
|
|
3664
|
-
const unwrapQuery = (text) => {
|
|
3665
|
-
return (/<user_query>([\s\S]*?)(?:<\/user_query>|$)/.exec(text)?.[1] ?? text).trim();
|
|
3666
|
-
};
|
|
3667
|
-
/** Normalize one chat_history.jsonl line. Exported for tests. */
|
|
3668
|
-
function parseGrokItem(obj) {
|
|
3669
|
-
switch (obj.type) {
|
|
3670
|
-
case "user": {
|
|
3671
|
-
const reason = obj.synthetic_reason;
|
|
3672
|
-
if (reason !== void 0 && reason !== null && reason !== "human") return [];
|
|
3673
|
-
const text = unwrapQuery(textParts(obj.content));
|
|
3674
|
-
return text === "" ? [] : [{
|
|
3675
|
-
role: "user",
|
|
3676
|
-
text
|
|
3677
|
-
}];
|
|
3678
|
-
}
|
|
3679
|
-
case "assistant": {
|
|
3680
|
-
const out = [];
|
|
3681
|
-
const text = asString(obj.content) ?? "";
|
|
3682
|
-
if (text !== "") out.push({
|
|
3683
|
-
role: "assistant",
|
|
3684
|
-
text
|
|
3685
|
-
});
|
|
3686
|
-
if (Array.isArray(obj.tool_calls)) {
|
|
3687
|
-
for (const c of obj.tool_calls) if (isRecord(c)) out.push({
|
|
3688
|
-
role: "tool",
|
|
3689
|
-
text: describeToolCall(asString(c.name) ?? "tool", c.arguments)
|
|
3690
|
-
});
|
|
3691
|
-
}
|
|
3692
|
-
return out;
|
|
3693
|
-
}
|
|
3694
|
-
case "tool_result": {
|
|
3695
|
-
const text = asString(obj.content) ?? "";
|
|
3696
|
-
return text === "" ? [] : [{
|
|
3697
|
-
role: "tool",
|
|
3698
|
-
text
|
|
3699
|
-
}];
|
|
3700
|
-
}
|
|
3701
|
-
default: return [];
|
|
3702
|
-
}
|
|
3703
|
-
}
|
|
3704
|
-
/** The directory of sessions for a working directory, or undefined. */
|
|
3705
|
-
async function cwdDir(root, cwd) {
|
|
3706
|
-
const direct = join(root, encodeCwdDirname(cwd));
|
|
3707
|
-
if (await stat(direct).then((s) => s.isDirectory(), () => false)) return direct;
|
|
3708
|
-
let names;
|
|
3709
|
-
try {
|
|
3710
|
-
names = await readdir(root);
|
|
3711
|
-
} catch {
|
|
3712
|
-
return;
|
|
3713
|
-
}
|
|
3714
|
-
for (const name of names) {
|
|
3715
|
-
const dir = join(root, name);
|
|
3716
|
-
if ((await readText(join(dir, ".cwd")))?.trim() === cwd) return dir;
|
|
3717
|
-
}
|
|
3718
|
-
}
|
|
3719
|
-
/** Find the chat_history.jsonl for a session, or the reason there is none. */
|
|
3720
|
-
async function locateGrokHistory(q, env) {
|
|
3721
|
-
const dir = await cwdDir(join(grokHome(env), "sessions"), q.cwd);
|
|
3722
|
-
if (dir === void 0) return { error: "no Grok sessions for this working directory" };
|
|
3723
|
-
if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
|
|
3724
|
-
const path = join(dir, q.cliSessionId, "chat_history.jsonl");
|
|
3725
|
-
if (await stat(path).then(() => true, () => false)) return { path };
|
|
3726
|
-
}
|
|
3727
|
-
const since = Date.parse(q.startedAt);
|
|
3728
|
-
const floor = Number.isFinite(since) ? since - 5e3 : 0;
|
|
3729
|
-
let best;
|
|
3730
|
-
for (const e of await entriesNewestFirst(dir)) {
|
|
3731
|
-
if (!e.dir) continue;
|
|
3732
|
-
const path = join(e.path, "chat_history.jsonl");
|
|
3733
|
-
const s = await stat(path).catch(() => void 0);
|
|
3734
|
-
if (s && s.mtimeMs >= floor && (!best || s.mtimeMs > best.mtimeMs)) best = {
|
|
3735
|
-
path,
|
|
3736
|
-
mtimeMs: s.mtimeMs
|
|
3737
|
-
};
|
|
3738
|
-
}
|
|
3739
|
-
if (best) return { path: best.path };
|
|
3740
|
-
return { error: "no Grok session in this working directory since it started" };
|
|
3741
|
-
}
|
|
3742
|
-
const grokTranscript = { async read(q, env) {
|
|
3743
|
-
try {
|
|
3744
|
-
const found = await locateGrokHistory(q, env);
|
|
3745
|
-
if ("error" in found) return notFound("Grok", found.error);
|
|
3746
|
-
const { entries, more } = await tailJsonl(found.path, q.lastTurns, parseGrokItem);
|
|
3747
|
-
return {
|
|
3748
|
-
ok: true,
|
|
3749
|
-
entries,
|
|
3750
|
-
more
|
|
3751
|
-
};
|
|
3752
|
-
} catch (e) {
|
|
3753
|
-
return notFound("Grok", e instanceof Error ? e.message : "read failed");
|
|
3754
|
-
}
|
|
3755
|
-
} };
|
|
3756
|
-
// ../daemon/src/transcripts.ts
|
|
3757
|
-
/**
|
|
3758
|
-
* The transcript reader of each CLI the daemon can peek into. A CLI missing here answers
|
|
3759
|
-
* "peek not supported for <cli> yet". Cursor and Antigravity are listed with the reason, so the
|
|
3760
|
-
* message says why.
|
|
3761
|
-
*/
|
|
3762
|
-
function defaultTranscriptReaders() {
|
|
3763
|
-
return {
|
|
3764
|
-
claude: claudeTranscript,
|
|
3765
|
-
codex: codexTranscript,
|
|
3766
|
-
opencode: openCodeTranscript,
|
|
3767
|
-
copilot: copilotTranscript,
|
|
3768
|
-
grok: grokTranscript,
|
|
3769
|
-
cursor: unsupportedTranscript("cursor", "its chat storage is not documented"),
|
|
3770
|
-
antigravity: unsupportedTranscript("antigravity", "its conversation store is not documented")
|
|
3771
|
-
};
|
|
3772
|
-
}
|
|
3773
3110
|
// ../daemon/src/bin.ts
|
|
3774
3111
|
async function main() {
|
|
3775
3112
|
const handle = await startDaemon({
|
|
3776
3113
|
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
3777
|
-
|
|
3114
|
+
wakers: { codex: codexAdapter.daemonWake },
|
|
3778
3115
|
onIdleExit: () => {
|
|
3779
3116
|
process.stderr.write("convenod: no sessions for a while, exiting.\n");
|
|
3780
3117
|
process.exit(0);
|