@conveno/cli 0.2.0-rc.1 → 0.2.0-rc.10
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 +28 -29
- package/dist/acp-TSjX4JP9.js +82 -0
- package/dist/agy-relay-D-OWo85B.js +137 -0
- package/dist/args-B3Cj2Ie4.js +361 -0
- package/dist/bin.js +4 -4
- package/dist/ctx-tYftvhz_.js +17 -0
- package/dist/daemon.js +490 -1151
- package/dist/daemonError-C05GqdhQ.js +66 -0
- package/dist/{acp-BlKK0v-B.js → dist-BLfduOoT.js} +39 -286
- package/dist/dist-BRjg9CLd.js +731 -0
- package/dist/{dist-CWvQqhPj.js → dist-CVdpCNJo.js} +1 -1
- package/dist/{dist-DsRTUePN.js → dist-D_O_JLLq.js} +6 -14
- package/dist/dist-DaIpdMke.js +667 -0
- package/dist/dist-MK-cK1JY.js +969 -0
- package/dist/{dist-_qrCNXUP.js → dist-STNJjbNH.js} +840 -1253
- package/dist/dist-VOS92iqO.js +645 -0
- package/dist/fmt-C2SsP5Y0.js +96 -0
- package/dist/{hook-bfp9_AVT.js → hook-CDF1A8AY.js} +31 -22
- package/dist/hook-entry-C0bPssOy.js +1 -0
- package/dist/hook-entry-CQQU-e_t.js +2500 -0
- package/dist/main-BhKTG0AI.js +650 -0
- package/dist/pick-DLp6w_-z.js +9 -0
- package/dist/run-eCXO1SyO.js +5609 -0
- package/dist/runtime-BGPlr8CI.js +772 -0
- package/dist/{dist-D8gPpZKN.js → toml-patch-DGzVRdd1.js} +20 -1889
- package/dist/{main-sIWDc4jt.js → uninstall-DQlzpv5R.js} +629 -1494
- package/dist/watch-D0KIPowJ.js +185 -0
- package/package.json +23 -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-MK-cK1JY.js";
|
|
4
|
+
import { An as newSessionId, C as bindAccountDevice, Ct as proofsMatch, D as clientProof, Dn as makeResult, E as clearOrchestrator, En as makeEventNotification, Et as readAncestry, F as dataPaths, Fn as socketPathTooLongMessage, I as decideAutoContinue, J as formatHookContext, L as defaultProcessIo, M as currentAccessToken, Mn as parseRelayFrame, N as daemonProof, Nn as safeParse, On as newDeviceId, Ot as readInbox, P as dataDir, Pn as sanitizeLine, Pt as requeueEntries, Qt as turnHops, R as detectRepo, Rt as resolveRecipient, S as baseName, Sn as encodeFrame, Tn as makeError, Tt as readAccountTokens, U as evaluateLiveness, V as effectiveHolder, X as generateSessionName, Xt as takeWithinChars, Yt as takeWithinBytes, Z as holderAfterDeparture, Zt as tooManyUnreadMessage, b as autoCandidates, bn as createLineDecoder, cn as EVENT_NAMES, ct as markDelivered, dn as Message, gn as RpcErrorCode, gt as pendingForInjection, hn as RelayPayload, j as createWmiWalker, jn as parseIpcRequest, kn as newMessageId, kt as readSettings, l as RESPONSE_BUDGET_BYTES, mn as PROTOCOL_VERSION, n as AccountError, nt as jwtClaim, p as ackEntries, pn as OWNER_SESSION_ID, q as formatContinuation, qt as statusAfterLiveness, r as ConvenoError, sn as DeviceId, tn as validateRename, tt as isOnline, ut as newAuthNonce, w as claimOrchestrator, wn as isSocketPathTooLong, x as autoLimitsFromEnv, xn as defaultSocketPath, xt as planSpawn, yn as SessionId } from "./dist-STNJjbNH.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-CVdpCNJo.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,289 +1943,27 @@ 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.10";
|
|
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 = {
|
|
@@ -2468,11 +1973,6 @@ const CLI_TIER = {
|
|
|
2468
1973
|
copilot: "next_turn",
|
|
2469
1974
|
antigravity: "next_turn"
|
|
2470
1975
|
};
|
|
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
1976
|
var Daemon = class {
|
|
2477
1977
|
store;
|
|
2478
1978
|
token;
|
|
@@ -2483,25 +1983,44 @@ var Daemon = class {
|
|
|
2483
1983
|
requestShutdown;
|
|
2484
1984
|
log;
|
|
2485
1985
|
authTimeoutMs;
|
|
2486
|
-
pathExists;
|
|
2487
1986
|
autoLimits;
|
|
2488
|
-
transcripts;
|
|
2489
|
-
transcriptEnv;
|
|
2490
1987
|
processIo;
|
|
1988
|
+
platform;
|
|
1989
|
+
wakers;
|
|
1990
|
+
settingsPath;
|
|
2491
1991
|
conns = /* @__PURE__ */ new Set();
|
|
2492
1992
|
/** Reaches the owner's other devices; set by startDaemon unless disabled. */
|
|
2493
1993
|
relay;
|
|
2494
1994
|
deviceId;
|
|
2495
|
-
/**
|
|
1995
|
+
/**
|
|
1996
|
+
* The newest idle-wake listener of each session, the ids it replaced, and the connection it
|
|
1997
|
+
* asked on. The session counts as wakeable while that connection is open. In memory only.
|
|
1998
|
+
*/
|
|
2496
1999
|
listeners = /* @__PURE__ */ new Map();
|
|
2000
|
+
/**
|
|
2001
|
+
* Messages the last wake handed each session, until its turn starts or ends. A requeue of
|
|
2002
|
+
* these makes the session idle again. In memory only.
|
|
2003
|
+
*/
|
|
2004
|
+
woken = /* @__PURE__ */ new Map();
|
|
2005
|
+
/** Sessions a daemon waker is working on, so one session gets one wake at a time. */
|
|
2006
|
+
daemonWaking = /* @__PURE__ */ new Set();
|
|
2007
|
+
/** Daemon wakes to try again (after \`failed\` or the wake limit), by session. In memory only. */
|
|
2008
|
+
wakeRetry = /* @__PURE__ */ new Map();
|
|
2009
|
+
/** Set when the daemon shuts down: closing connections must not touch the store any more. */
|
|
2010
|
+
stopping = false;
|
|
2011
|
+
/**
|
|
2012
|
+
* Sessions whose daemon waker answered \`unsupported\` (no \`queue\` in that binary, an ephemeral
|
|
2013
|
+
* thread): not asked again for them while the daemon runs, so a new daemon checks afresh. Other
|
|
2014
|
+
* sessions of the same CLI are still woken.
|
|
2015
|
+
*/
|
|
2016
|
+
wakersOff = /* @__PURE__ */ new Set();
|
|
2017
|
+
/** When each session's last daemon wake was handed over, to tell a wake that never became a turn. */
|
|
2018
|
+
wokenAt = /* @__PURE__ */ new Map();
|
|
2497
2019
|
idleSince;
|
|
2498
2020
|
startedMs;
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
platform: process.platform,
|
|
2503
|
-
env: process.env
|
|
2504
|
-
}, processIo = defaultProcessIo) {
|
|
2021
|
+
/** When each session went offline, for the removal grace. In memory only. */
|
|
2022
|
+
offlineSince = /* @__PURE__ */ new Map();
|
|
2023
|
+
constructor(store, token, now, isAlive, idleExitMs, requestIdleExit, requestShutdown, log, authTimeoutMs = AUTH_TIMEOUT_MS, autoLimits = autoLimitsFromEnv({}), processIo = defaultProcessIo, platform = process.platform, wakers = {}, settingsPath) {
|
|
2505
2024
|
this.store = store;
|
|
2506
2025
|
this.token = token;
|
|
2507
2026
|
this.now = now;
|
|
@@ -2511,24 +2030,14 @@ var Daemon = class {
|
|
|
2511
2030
|
this.requestShutdown = requestShutdown;
|
|
2512
2031
|
this.log = log;
|
|
2513
2032
|
this.authTimeoutMs = authTimeoutMs;
|
|
2514
|
-
this.pathExists = pathExists;
|
|
2515
2033
|
this.autoLimits = autoLimits;
|
|
2516
|
-
this.transcripts = transcripts;
|
|
2517
|
-
this.transcriptEnv = transcriptEnv;
|
|
2518
2034
|
this.processIo = processIo;
|
|
2035
|
+
this.platform = platform;
|
|
2036
|
+
this.wakers = wakers;
|
|
2037
|
+
this.settingsPath = settingsPath;
|
|
2519
2038
|
this.deviceId = store.deviceId();
|
|
2520
2039
|
this.startedMs = now().getTime();
|
|
2521
2040
|
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
2041
|
}
|
|
2533
2042
|
iso = () => this.now().toISOString();
|
|
2534
2043
|
attach(socket) {
|
|
@@ -2549,6 +2058,7 @@ var Daemon = class {
|
|
|
2549
2058
|
socket.on("close", () => {
|
|
2550
2059
|
clearTimeout(authTimer);
|
|
2551
2060
|
this.conns.delete(conn);
|
|
2061
|
+
this.listenerGone(conn);
|
|
2552
2062
|
});
|
|
2553
2063
|
socket.on("error", () => socket.destroy());
|
|
2554
2064
|
}
|
|
@@ -2610,29 +2120,22 @@ var Daemon = class {
|
|
|
2610
2120
|
case "session.rename": return this.rename(req.params);
|
|
2611
2121
|
case "session.setStatus": return this.setStatus(req.params);
|
|
2612
2122
|
case "session.list": return this.list(req.params);
|
|
2613
|
-
case "session.byHost": return this.byHost(req.params
|
|
2123
|
+
case "session.byHost": return this.byHost(req.params);
|
|
2614
2124
|
case "session.hostOf": return this.hostOf(req.params);
|
|
2615
|
-
case "session.
|
|
2616
|
-
case "session.setAuto": return this.setAuto(req.params);
|
|
2125
|
+
case "session.setNative": return this.setNative(req.params);
|
|
2617
2126
|
case "turn.start": return this.turnStart(req.params.sessionId);
|
|
2618
2127
|
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);
|
|
2128
|
+
case "turn.wake": return this.turnWake(conn, req.params);
|
|
2623
2129
|
case "daemon.shutdown": return { ok: true };
|
|
2624
2130
|
case "orchestrator.claim": return this.claim(req.params.sessionId);
|
|
2131
|
+
case "orchestrator.clear": return this.clearLead(conn);
|
|
2625
2132
|
case "message.send": return this.sendMessage(req.params);
|
|
2133
|
+
case "owner.send": return this.ownerSend(conn, req.params);
|
|
2626
2134
|
case "message.inbox": return this.inbox(req.params);
|
|
2627
2135
|
case "message.deliver": return this.deliver(req.params);
|
|
2628
2136
|
case "message.ack": return this.ack(req.params);
|
|
2137
|
+
case "message.requeue": return this.requeue(req.params);
|
|
2629
2138
|
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
2139
|
case "relay.status":
|
|
2637
2140
|
case "devices.list":
|
|
2638
2141
|
case "devices.pair":
|
|
@@ -2681,30 +2184,24 @@ var Daemon = class {
|
|
|
2681
2184
|
if (row.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${row.name}" is offline. Register the session again.`);
|
|
2682
2185
|
return row;
|
|
2683
2186
|
}
|
|
2187
|
+
/** The wire view of a session. Its `deliveryTier` is the live one (`tierFor`). */
|
|
2684
2188
|
view(row) {
|
|
2685
|
-
|
|
2189
|
+
const holder = effectiveHolder(this.store.holder(), this.named([row]));
|
|
2190
|
+
return toSession({
|
|
2191
|
+
...row,
|
|
2192
|
+
deliveryTier: this.tierFor(row)
|
|
2193
|
+
}, holder?.id === row.id, this.store.unreadCount(row.id) + this.stalledWoken(row.id));
|
|
2686
2194
|
}
|
|
2687
2195
|
/** The orchestrator as routing sees it: the holder, if it is online. */
|
|
2688
2196
|
orchestratorNow() {
|
|
2689
2197
|
return effectiveHolder(this.store.holder(), this.named(this.store.allSessions()))?.id ?? null;
|
|
2690
2198
|
}
|
|
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
2199
|
emit(payload, onlyTo) {
|
|
2200
|
+
const only = onlyTo === void 0 || Array.isArray(onlyTo) ? onlyTo : [onlyTo];
|
|
2704
2201
|
for (const c of this.conns) {
|
|
2705
2202
|
const sub = c.sub;
|
|
2706
2203
|
if (!sub?.topics.has(payload.event)) continue;
|
|
2707
|
-
if (
|
|
2204
|
+
if (only !== void 0 && sub.sessionId !== void 0 && !only.includes(sub.sessionId)) continue;
|
|
2708
2205
|
this.send(c, makeEventNotification(payload));
|
|
2709
2206
|
}
|
|
2710
2207
|
}
|
|
@@ -2719,11 +2216,13 @@ var Daemon = class {
|
|
|
2719
2216
|
});
|
|
2720
2217
|
this.relay?.sessionsChanged();
|
|
2721
2218
|
}
|
|
2219
|
+
/** Every message that lands in a local mailbox goes through here. */
|
|
2722
2220
|
emitMessage(m, recipient) {
|
|
2723
2221
|
this.emit({
|
|
2724
2222
|
event: "message.received",
|
|
2725
2223
|
data: { message: m }
|
|
2726
2224
|
}, recipient);
|
|
2225
|
+
this.daemonWake(recipient);
|
|
2727
2226
|
}
|
|
2728
2227
|
async detect(p) {
|
|
2729
2228
|
if (p.repo) return p.repo;
|
|
@@ -2748,8 +2247,6 @@ var Daemon = class {
|
|
|
2748
2247
|
deliveryTier: p.acp ? "acp" : CLI_TIER[p.cli] ?? "inbox",
|
|
2749
2248
|
spawned: p.spawned,
|
|
2750
2249
|
spawnDepth: parent ? parent.spawnDepth + 1 : 0,
|
|
2751
|
-
auto: p.auto ?? (p.spawned || p.spawnedBy !== void 0),
|
|
2752
|
-
autoExplicit: false,
|
|
2753
2250
|
autoRuns: [],
|
|
2754
2251
|
turnHops: 0,
|
|
2755
2252
|
startedAt: at,
|
|
@@ -2768,7 +2265,18 @@ var Daemon = class {
|
|
|
2768
2265
|
return r;
|
|
2769
2266
|
});
|
|
2770
2267
|
this.emitSession(row.id, "registered");
|
|
2771
|
-
|
|
2268
|
+
this.claimPreferredLead(row);
|
|
2269
|
+
return { session: this.view(this.store.getSession(row.id) ?? row) };
|
|
2270
|
+
}
|
|
2271
|
+
/**
|
|
2272
|
+
* The saved preferred lead CLI takes the lead when it registers and nobody online leads. The
|
|
2273
|
+
* settings are read on each register, so a change needs no restart. It is the normal claim.
|
|
2274
|
+
*/
|
|
2275
|
+
claimPreferredLead(row) {
|
|
2276
|
+
if (this.settingsPath === void 0) return;
|
|
2277
|
+
if (readSettings(this.settingsPath).leadCli !== row.cli) return;
|
|
2278
|
+
if (this.orchestratorNow() !== null) return;
|
|
2279
|
+
this.claim(row.id);
|
|
2772
2280
|
}
|
|
2773
2281
|
async registerAsync(p) {
|
|
2774
2282
|
return this.register(p, await this.detect(p));
|
|
@@ -2786,6 +2294,7 @@ var Daemon = class {
|
|
|
2786
2294
|
status: "idle",
|
|
2787
2295
|
lastSeenAt: at
|
|
2788
2296
|
});
|
|
2297
|
+
this.offlineSince.delete(sessionId);
|
|
2789
2298
|
this.emitSession(sessionId, "updated");
|
|
2790
2299
|
return { lastSeenAt: at };
|
|
2791
2300
|
}
|
|
@@ -2797,6 +2306,8 @@ var Daemon = class {
|
|
|
2797
2306
|
if (after !== before) this.store.setHolder(after);
|
|
2798
2307
|
});
|
|
2799
2308
|
this.listeners.delete(sessionId);
|
|
2309
|
+
this.woken.delete(sessionId);
|
|
2310
|
+
this.offlineSince.set(sessionId, this.now().getTime());
|
|
2800
2311
|
this.emitSession(sessionId, change);
|
|
2801
2312
|
if (after !== before) this.emit({
|
|
2802
2313
|
event: "orchestrator.changed",
|
|
@@ -2835,7 +2346,7 @@ var Daemon = class {
|
|
|
2835
2346
|
}
|
|
2836
2347
|
list(p) {
|
|
2837
2348
|
const rows = this.store.allSessions().filter((r) => {
|
|
2838
|
-
if (
|
|
2349
|
+
if (r.status === "offline" && !p.includeOffline) return false;
|
|
2839
2350
|
if (p.cli && r.cli !== p.cli) return false;
|
|
2840
2351
|
if (p.repo && r.repoRoot !== p.repo && baseName(r.repoRoot ?? r.cwd) !== p.repo) return false;
|
|
2841
2352
|
return true;
|
|
@@ -2851,15 +2362,33 @@ var Daemon = class {
|
|
|
2851
2362
|
* Exact equality only, with no walk to farther ancestors, so a hook from a CLI that has no
|
|
2852
2363
|
* session matches nothing. Two sessions under one CLI process are ambiguous, so the result is
|
|
2853
2364
|
* null; the daemon never guesses. With `cwd`, the sessions that share the pid are narrowed to
|
|
2854
|
-
* those registered in the same folder (
|
|
2365
|
+
* those registered in the same folder (separators, trailing slash, case
|
|
2855
2366
|
* on Windows), so several folders on one OpenCode 2.x server stay apart. Two sessions in one
|
|
2856
2367
|
* folder still match nothing.
|
|
2857
2368
|
*/
|
|
2858
|
-
byHost(
|
|
2859
|
-
const
|
|
2369
|
+
byHost(p) {
|
|
2370
|
+
const { pid, cwd, nativeId } = p;
|
|
2371
|
+
const rows = this.store.allSessions().filter((r) => p.includeOffline || r.status !== "offline");
|
|
2372
|
+
const live = (list) => {
|
|
2373
|
+
const online = list.filter((r) => r.status !== "offline");
|
|
2374
|
+
return online.length > 0 ? online : list;
|
|
2375
|
+
};
|
|
2376
|
+
if (nativeId !== void 0) {
|
|
2377
|
+
const own = live(rows.filter((r) => r.nativeId === nativeId))[0];
|
|
2378
|
+
if (!own) return { session: null };
|
|
2379
|
+
const pids = [...own.hostPid === void 0 ? [] : [own.hostPid], ...own.hostPids ?? []];
|
|
2380
|
+
if (pids.length === 0 || pids.includes(pid)) return { session: this.view(own) };
|
|
2381
|
+
const mine = this.pidHolders(rows, pid, cwd, live);
|
|
2382
|
+
return { session: this.view(mine.length === 1 ? mine[0] : own) };
|
|
2383
|
+
}
|
|
2384
|
+
const holders = this.pidHolders(rows, pid, cwd, live);
|
|
2860
2385
|
const only = holders.length === 1 ? holders[0] : void 0;
|
|
2861
2386
|
return { session: only ? this.view(only) : null };
|
|
2862
2387
|
}
|
|
2388
|
+
/** Sessions whose host is `pid` (in `cwd`, when given), online ones first. */
|
|
2389
|
+
pidHolders(rows, pid, cwd, live) {
|
|
2390
|
+
return live(rows.filter((r) => r.hostPid === pid && (cwd === void 0 || samePath(r.cwd, cwd, this.platform))));
|
|
2391
|
+
}
|
|
2863
2392
|
/**
|
|
2864
2393
|
* Walk up from a hook's parent pid to its host CLI, for a hook that would otherwise read the
|
|
2865
2394
|
* process table itself. With no online session of the hook's CLI there is nothing the hook could
|
|
@@ -2885,122 +2414,41 @@ var Daemon = class {
|
|
|
2885
2414
|
};
|
|
2886
2415
|
}
|
|
2887
2416
|
/**
|
|
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.
|
|
2417
|
+
* A hook records the CLI's own id for its session. One online session holds an id at a time,
|
|
2418
|
+
* so a CLI that reuses an id for a new session (a resumed thread) moves it there.
|
|
2894
2419
|
*/
|
|
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
|
|
2420
|
+
setNative(p) {
|
|
2421
|
+
const row = this.requireOnline(p.sessionId);
|
|
2422
|
+
if (row.nativeId === p.nativeId) return { session: this.view(row) };
|
|
2423
|
+
const others = this.store.allSessions().filter((r) => r.id !== row.id && r.nativeId === p.nativeId);
|
|
2424
|
+
this.store.tx(() => {
|
|
2425
|
+
for (const o of others) this.store.updateSession(o.id, { nativeId: null });
|
|
2426
|
+
this.store.updateSession(row.id, { nativeId: p.nativeId });
|
|
2907
2427
|
});
|
|
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
|
-
};
|
|
2428
|
+
for (const o of others) this.emitSession(o.id, "updated");
|
|
2429
|
+
this.emitSession(row.id, "updated");
|
|
2430
|
+
this.daemonWake(row.id);
|
|
2431
|
+
return { session: this.view(this.requireSession(row.id)) };
|
|
2985
2432
|
}
|
|
2986
|
-
|
|
2987
|
-
|
|
2433
|
+
/** Delete offline sessions and their mail. \`graceMs\` 0 removes every one at once. */
|
|
2434
|
+
removeOffline(graceMs) {
|
|
2435
|
+
const nowMs = this.now().getTime();
|
|
2436
|
+
const gone = this.store.allSessions().filter((r) => {
|
|
2437
|
+
if (r.status !== "offline") return false;
|
|
2438
|
+
const since = this.offlineSince.get(r.id) ?? Date.parse(r.lastSeenAt);
|
|
2439
|
+
return nowMs - since >= graceMs;
|
|
2440
|
+
});
|
|
2441
|
+
if (gone.length === 0) return;
|
|
2988
2442
|
this.store.tx(() => {
|
|
2989
|
-
for (const r of
|
|
2443
|
+
for (const r of gone) this.store.deleteSession(r.id);
|
|
2990
2444
|
});
|
|
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);
|
|
2445
|
+
for (const r of gone) {
|
|
2446
|
+
this.listeners.delete(r.id);
|
|
2447
|
+
this.woken.delete(r.id);
|
|
2448
|
+
this.wokenAt.delete(r.id);
|
|
2449
|
+
this.wakersOff.delete(r.id);
|
|
2450
|
+
this.offlineSince.delete(r.id);
|
|
2451
|
+
}
|
|
3004
2452
|
}
|
|
3005
2453
|
claim(sessionId) {
|
|
3006
2454
|
this.requireSession(sessionId);
|
|
@@ -3045,45 +2493,92 @@ var Daemon = class {
|
|
|
3045
2493
|
previous: res.previous
|
|
3046
2494
|
};
|
|
3047
2495
|
}
|
|
2496
|
+
clearLead(conn) {
|
|
2497
|
+
this.requireCli(conn, "clear the lead");
|
|
2498
|
+
const holder = this.store.holder();
|
|
2499
|
+
const res = clearOrchestrator(holder, this.named(this.store.allSessions()));
|
|
2500
|
+
const at = this.iso();
|
|
2501
|
+
const sent = [];
|
|
2502
|
+
this.store.tx(() => {
|
|
2503
|
+
this.store.setHolder(null);
|
|
2504
|
+
for (const n of res.notices) {
|
|
2505
|
+
const m = {
|
|
2506
|
+
id: newMessageId(),
|
|
2507
|
+
from: DAEMON_SENDER_ID,
|
|
2508
|
+
to: n.to,
|
|
2509
|
+
kind: "system",
|
|
2510
|
+
body: {
|
|
2511
|
+
event: n.event,
|
|
2512
|
+
detail: n.detail
|
|
2513
|
+
},
|
|
2514
|
+
urgent: false,
|
|
2515
|
+
createdAt: at
|
|
2516
|
+
};
|
|
2517
|
+
this.store.insertMessage(m, n.to, at);
|
|
2518
|
+
sent.push(m);
|
|
2519
|
+
}
|
|
2520
|
+
});
|
|
2521
|
+
if (holder !== null) {
|
|
2522
|
+
this.emit({
|
|
2523
|
+
event: "orchestrator.changed",
|
|
2524
|
+
data: {
|
|
2525
|
+
orchestrator: null,
|
|
2526
|
+
previous: holder
|
|
2527
|
+
}
|
|
2528
|
+
});
|
|
2529
|
+
if (res.previous) this.emitSession(res.previous, "updated");
|
|
2530
|
+
for (const m of sent) this.emitMessage(m, m.to);
|
|
2531
|
+
}
|
|
2532
|
+
return { previous: res.previous };
|
|
2533
|
+
}
|
|
3048
2534
|
sendMessage(p) {
|
|
3049
2535
|
const sender = this.requireSession(p.sessionId);
|
|
3050
2536
|
if (sender.status === "offline") throw new ConvenoError(RpcErrorCode.NotFound, `Session "${sender.name}" is offline. Register the session again before sending.`);
|
|
3051
2537
|
if (p.kind === "system") throw new ConvenoError(RpcErrorCode.InvalidParams, "Messages of kind \"system\" are made by the Conveno daemon only. Send kind \"text\" instead.");
|
|
2538
|
+
return this.deliverFrom({
|
|
2539
|
+
id: sender.id,
|
|
2540
|
+
name: sender.name,
|
|
2541
|
+
cli: sender.cli,
|
|
2542
|
+
hops: sender.status === "busy" ? sender.turnHops : 0
|
|
2543
|
+
}, p);
|
|
2544
|
+
}
|
|
2545
|
+
/** The recipient names the owner: `you`, or the id of a message the owner sent. */
|
|
2546
|
+
isOwnerRecipient(to) {
|
|
2547
|
+
return to === "you" || to === OWNER_SESSION_ID;
|
|
2548
|
+
}
|
|
2549
|
+
/**
|
|
2550
|
+
* Route one message from \`sender\` (a session, or the owner) to a session, or to a session on
|
|
2551
|
+
* another device. The owner is not a session and has no inbox: a session cannot message \`you\`.
|
|
2552
|
+
*/
|
|
2553
|
+
deliverFrom(sender, p) {
|
|
3052
2554
|
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
2555
|
const at = this.iso();
|
|
3065
|
-
const
|
|
2556
|
+
const rows = this.store.allSessions();
|
|
2557
|
+
const make = (to) => ({
|
|
3066
2558
|
id: newMessageId(),
|
|
3067
2559
|
from: sender.id,
|
|
3068
|
-
to
|
|
2560
|
+
to,
|
|
3069
2561
|
kind: p.kind,
|
|
3070
2562
|
body: p.body,
|
|
3071
2563
|
urgent: p.urgent,
|
|
3072
2564
|
createdAt: at,
|
|
3073
2565
|
fromName: sender.name,
|
|
3074
|
-
fromCli: sender.cli,
|
|
2566
|
+
...sender.cli !== void 0 ? { fromCli: sender.cli } : {},
|
|
3075
2567
|
...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
2568
|
});
|
|
3083
|
-
if (
|
|
3084
|
-
|
|
3085
|
-
|
|
2569
|
+
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.");
|
|
2570
|
+
let target;
|
|
2571
|
+
try {
|
|
2572
|
+
target = resolveRecipient(p.to, this.named(rows), this.store.holder());
|
|
2573
|
+
} catch (e) {
|
|
2574
|
+
const remote = e instanceof ConvenoError && e.code === RpcErrorCode.NotFound ? this.relay?.resolveRemote(p.to) : void 0;
|
|
2575
|
+
if (!remote) throw e;
|
|
2576
|
+
return this.sendToRemote(make(p.to), remote, sender.hops);
|
|
3086
2577
|
}
|
|
2578
|
+
const targetRow = rows.find((r) => r.id === target.id);
|
|
2579
|
+
if (this.store.unreadCount(targetRow.id) >= 1e3) throw new ConvenoError(RpcErrorCode.LimitExceeded, tooManyUnreadMessage(targetRow.name, MAX_UNREAD_PER_SESSION));
|
|
2580
|
+
const message = make(p.to);
|
|
2581
|
+
this.store.insertMessage(message, targetRow.id, at, sender.hops);
|
|
3087
2582
|
this.emitMessage(message, targetRow.id);
|
|
3088
2583
|
return {
|
|
3089
2584
|
message,
|
|
@@ -3094,174 +2589,255 @@ var Daemon = class {
|
|
|
3094
2589
|
}
|
|
3095
2590
|
};
|
|
3096
2591
|
}
|
|
3097
|
-
|
|
2592
|
+
requireCli(conn, what) {
|
|
2593
|
+
if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, `Only the conveno command and app can ${what}. A session cannot act as the owner.`);
|
|
2594
|
+
}
|
|
2595
|
+
ownerSend(conn, p) {
|
|
2596
|
+
this.requireCli(conn, "send as the owner");
|
|
2597
|
+
return this.deliverFrom({
|
|
2598
|
+
id: OWNER_SESSION_ID,
|
|
2599
|
+
name: "you",
|
|
2600
|
+
hops: 0
|
|
2601
|
+
}, {
|
|
2602
|
+
to: p.to,
|
|
2603
|
+
kind: "text",
|
|
2604
|
+
body: { text: p.text },
|
|
2605
|
+
urgent: p.urgent,
|
|
2606
|
+
...p.replyTo !== void 0 ? { replyTo: p.replyTo } : {}
|
|
2607
|
+
});
|
|
2608
|
+
}
|
|
2609
|
+
/**
|
|
2610
|
+
* \`acp\` for an ACP host. \`live\` while something can wake the session: a listener's connection
|
|
2611
|
+
* is open, or the session is busy in a turn a listener's CLI ends with its own hook (it continues
|
|
2612
|
+
* with what waits, then arms a new listener), or a daemon waker can reach it. Otherwise the CLI's
|
|
2613
|
+
* own tier.
|
|
2614
|
+
*/
|
|
3098
2615
|
tierFor(row) {
|
|
3099
|
-
|
|
3100
|
-
if (row.
|
|
3101
|
-
if (
|
|
2616
|
+
if (row.deliveryTier === "acp") return "acp";
|
|
2617
|
+
if (this.listenerConnected(row.id)) return "live";
|
|
2618
|
+
if (row.status === "busy" && this.listeners.has(row.id)) return "live";
|
|
2619
|
+
if (this.daemonWakerFor(row)) return "live";
|
|
3102
2620
|
return row.deliveryTier;
|
|
3103
2621
|
}
|
|
2622
|
+
listenerConnected(id) {
|
|
2623
|
+
const conn = this.listeners.get(id)?.conn;
|
|
2624
|
+
return conn !== void 0 && this.conns.has(conn) && !conn.socket.destroyed;
|
|
2625
|
+
}
|
|
2626
|
+
/** A connection closed: a listener that asked on it no longer makes its session wakeable. */
|
|
2627
|
+
listenerGone(conn) {
|
|
2628
|
+
if (this.stopping) return;
|
|
2629
|
+
for (const [id, rec] of this.listeners) {
|
|
2630
|
+
if (rec.conn !== conn) continue;
|
|
2631
|
+
rec.conn = void 0;
|
|
2632
|
+
this.emitSession(id, "updated");
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
daemonWakerFor(row) {
|
|
2636
|
+
if (row.nativeId === void 0 || this.wakersOff.has(row.id)) return void 0;
|
|
2637
|
+
return this.wakers[row.cli];
|
|
2638
|
+
}
|
|
3104
2639
|
/**
|
|
3105
|
-
*
|
|
3106
|
-
* session
|
|
3107
|
-
*
|
|
2640
|
+
* A message landed for \`id\`. When its CLI has a daemon waker, no listener is connected and the
|
|
2641
|
+
* session is idle, hand the waiting messages to the waker (under the wake limit, like
|
|
2642
|
+
* \`turn.wake\`, and under \`DAEMON_WAKE_BYTES\`, since they go on a command line). \`queued\`
|
|
2643
|
+
* and \`unknown\` keep them delivered (a wake that timed out may have landed: a requeue could
|
|
2644
|
+
* deliver them twice). \`failed\` and \`unsupported\` put them back; after \`failed\` or the wake
|
|
2645
|
+
* limit, the sweep tries again with a growing delay. One wake per session at a time.
|
|
3108
2646
|
*/
|
|
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
|
-
}
|
|
2647
|
+
daemonWake(id) {
|
|
2648
|
+
if (this.daemonWaking.has(id)) return;
|
|
2649
|
+
const row = this.store.getSession(id);
|
|
2650
|
+
const wake = row?.status === "idle" && !this.listenerConnected(id) && this.daemonWakerFor(row);
|
|
2651
|
+
if (!row || !wake) {
|
|
2652
|
+
this.wakeRetry.delete(id);
|
|
2653
|
+
return;
|
|
3125
2654
|
}
|
|
3126
|
-
const
|
|
3127
|
-
|
|
3128
|
-
this.store.
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
|
|
2655
|
+
const d = this.continueWith(row, true, false, DAEMON_WAKE_BYTES);
|
|
2656
|
+
if (d.messages.length === 0) {
|
|
2657
|
+
const queued = this.store.entries(id, { states: ["queued"] });
|
|
2658
|
+
if (autoCandidates(queued, id).length > 0) this.scheduleWakeRetry(id);
|
|
2659
|
+
else this.wakeRetry.delete(id);
|
|
2660
|
+
return;
|
|
2661
|
+
}
|
|
2662
|
+
this.markWoken(id, d.messages);
|
|
2663
|
+
this.daemonWaking.add(id);
|
|
2664
|
+
const text = formatContinuation(d.messages, d.orchestrator, d.remaining);
|
|
2665
|
+
const session = this.view(this.requireSession(id));
|
|
2666
|
+
(async () => {
|
|
2667
|
+
let outcome;
|
|
2668
|
+
try {
|
|
2669
|
+
outcome = await wake({
|
|
2670
|
+
session,
|
|
2671
|
+
text,
|
|
2672
|
+
messages: d.messages,
|
|
2673
|
+
...row.nativeId !== void 0 ? { nativeId: row.nativeId } : {}
|
|
2674
|
+
});
|
|
2675
|
+
} catch (e) {
|
|
2676
|
+
this.log.error(`${row.cli} waker failed`, e);
|
|
2677
|
+
outcome = "failed";
|
|
2678
|
+
}
|
|
2679
|
+
this.daemonWaking.delete(id);
|
|
2680
|
+
if (outcome === "queued" || outcome === "unknown" || this.stopping) {
|
|
2681
|
+
this.wakeRetry.delete(id);
|
|
2682
|
+
return;
|
|
2683
|
+
}
|
|
2684
|
+
if (outcome === "unsupported") {
|
|
2685
|
+
this.wakeRetry.delete(id);
|
|
2686
|
+
this.wakersOff.add(row.id);
|
|
2687
|
+
this.relay?.sessionsChanged();
|
|
2688
|
+
}
|
|
2689
|
+
if (this.store.getSession(id)?.status === "offline") {
|
|
2690
|
+
this.wakeRetry.delete(id);
|
|
2691
|
+
return;
|
|
2692
|
+
}
|
|
2693
|
+
this.requeueFor(id, d.messages.map((m) => m.id));
|
|
2694
|
+
if (outcome === "failed") this.scheduleWakeRetry(id);
|
|
2695
|
+
})();
|
|
2696
|
+
}
|
|
2697
|
+
/** Try a daemon wake of \`id\` again later, each time waiting twice as long, up to a cap. */
|
|
2698
|
+
scheduleWakeRetry(id) {
|
|
2699
|
+
const delayMs = Math.min((this.wakeRetry.get(id)?.delayMs ?? 0) * 2 || WAKE_RETRY_MS, WAKE_RETRY_MAX_MS);
|
|
2700
|
+
this.wakeRetry.set(id, {
|
|
2701
|
+
atMs: this.now().getTime() + delayMs,
|
|
2702
|
+
delayMs
|
|
2703
|
+
});
|
|
2704
|
+
}
|
|
2705
|
+
/** Run the daemon wakes whose retry is due. Called by the sweep. */
|
|
2706
|
+
retryDaemonWakes(nowMs) {
|
|
2707
|
+
for (const [id, r] of [...this.wakeRetry]) if (r.atMs <= nowMs) this.daemonWake(id);
|
|
2708
|
+
}
|
|
2709
|
+
markWoken(id, messages) {
|
|
2710
|
+
this.woken.set(id, new Set(messages.map((m) => m.id)));
|
|
2711
|
+
this.wokenAt.set(id, this.now().getTime());
|
|
2712
|
+
}
|
|
2713
|
+
/**
|
|
2714
|
+
* Messages a wake handed over that no turn took up: the CLI accepted them but the turn never
|
|
2715
|
+
* started (Codex keeps queued input while a turn is interrupted). Counted as unread so status
|
|
2716
|
+
* shows them. A turn start or end clears \`woken\`.
|
|
2717
|
+
*/
|
|
2718
|
+
stalledWoken(id) {
|
|
2719
|
+
const at = this.wokenAt.get(id);
|
|
2720
|
+
if (at === void 0 || this.now().getTime() - at < WOKEN_STALL_MS) return 0;
|
|
2721
|
+
return this.woken.get(id)?.size ?? 0;
|
|
2722
|
+
}
|
|
2723
|
+
/**
|
|
2724
|
+
* Delivered messages go back to queued. When they are from the last wake and that wake made the
|
|
2725
|
+
* session busy, the wake never became a turn: the session is idle again and the wake does not
|
|
2726
|
+
* count against the limit.
|
|
2727
|
+
*/
|
|
2728
|
+
requeue(p) {
|
|
2729
|
+
this.requireSession(p.sessionId);
|
|
2730
|
+
return this.requeueFor(p.sessionId, p.ids);
|
|
2731
|
+
}
|
|
2732
|
+
requeueFor(id, ids) {
|
|
2733
|
+
const woken = this.woken.get(id);
|
|
2734
|
+
const fromWake = woken !== void 0 && ids.some((m) => woken.has(m));
|
|
2735
|
+
const res = this.store.tx(() => {
|
|
2736
|
+
const r = requeueEntries(this.store.entries(id, { ids: [...ids] }), ids);
|
|
2737
|
+
for (const e of r.changed) this.store.saveEntry(id, e);
|
|
2738
|
+
const row = this.requireSession(id);
|
|
2739
|
+
const idle = fromWake && r.changed.length > 0 && row.status === "busy";
|
|
2740
|
+
if (idle) this.store.updateSession(id, {
|
|
2741
|
+
status: "idle",
|
|
2742
|
+
turnHops: 0,
|
|
2743
|
+
autoRuns: row.autoRuns.slice(0, -1)
|
|
3140
2744
|
});
|
|
3141
|
-
|
|
2745
|
+
return {
|
|
2746
|
+
requeued: r.changed.length,
|
|
2747
|
+
idle
|
|
2748
|
+
};
|
|
3142
2749
|
});
|
|
3143
|
-
this.
|
|
3144
|
-
|
|
2750
|
+
if (fromWake) this.woken.delete(id);
|
|
2751
|
+
if (res.idle) this.emitSession(id, "updated");
|
|
2752
|
+
return { requeued: res.requeued };
|
|
3145
2753
|
}
|
|
3146
2754
|
/**
|
|
3147
2755
|
* 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
2756
|
*/
|
|
3150
2757
|
turnStart(sessionId) {
|
|
3151
|
-
this.requireOnline(sessionId);
|
|
3152
|
-
this.
|
|
2758
|
+
const row = this.requireOnline(sessionId);
|
|
2759
|
+
const fromWake = this.woken.has(sessionId) && row.status === "busy";
|
|
2760
|
+
this.woken.delete(sessionId);
|
|
2761
|
+
this.store.updateSession(sessionId, fromWake ? { status: "busy" } : {
|
|
3153
2762
|
status: "busy",
|
|
3154
2763
|
turnHops: 0
|
|
3155
2764
|
});
|
|
3156
2765
|
this.emitSession(sessionId, "updated");
|
|
3157
2766
|
return { session: this.view(this.requireSession(sessionId)) };
|
|
3158
2767
|
}
|
|
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
2768
|
/**
|
|
3178
|
-
* Hand the session its waiting messages to continue with, if
|
|
2769
|
+
* Hand the session its waiting messages to continue with, if the wake limit allows it.
|
|
3179
2770
|
* On a hand-over the session is busy and its turn carries the hops. With `endOfTurn`, nothing
|
|
3180
2771
|
* handed over means the session is now idle. One transaction.
|
|
3181
2772
|
*/
|
|
3182
|
-
continueWith(row, allow, endOfTurn) {
|
|
2773
|
+
continueWith(row, allow, endOfTurn, maxBytes = RESPONSE_BUDGET_BYTES, maxChars) {
|
|
3183
2774
|
const nowMs = this.now().getTime();
|
|
3184
2775
|
const at = this.iso();
|
|
3185
2776
|
const orchestrator = this.orchestratorNow();
|
|
3186
|
-
let pausedBy = row.autoPausedBy;
|
|
3187
|
-
let notice;
|
|
3188
2777
|
const res = this.store.tx(() => {
|
|
3189
2778
|
const queued = this.store.entries(row.id, { states: ["queued"] });
|
|
3190
2779
|
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);
|
|
2780
|
+
const decision = decideAutoContinue({ runs: row.autoRuns }, candidates, nowMs, this.autoLimits);
|
|
3197
2781
|
if (decision.continue) {
|
|
3198
|
-
const
|
|
2782
|
+
const fit = takeWithinBytes(candidates.slice(0, 20), maxBytes);
|
|
2783
|
+
const { taken, preview } = maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, maxChars, (ms, cut) => formatContinuation(ms, orchestrator, queued.length - (cut ? 0 : ms.length)));
|
|
3199
2784
|
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
3200
2785
|
for (const e of updated) this.store.saveEntry(row.id, e);
|
|
3201
2786
|
this.store.updateSession(row.id, {
|
|
3202
2787
|
status: "busy",
|
|
3203
2788
|
autoRuns: decision.runs,
|
|
3204
|
-
turnHops: turnHops(taken)
|
|
2789
|
+
turnHops: turnHops(preview ? fit.slice(0, 1) : taken)
|
|
3205
2790
|
});
|
|
2791
|
+
if (preview) return {
|
|
2792
|
+
messages: [preview],
|
|
2793
|
+
remaining: queued.length
|
|
2794
|
+
};
|
|
3206
2795
|
return {
|
|
3207
2796
|
messages: updated.map((e) => e.message),
|
|
3208
2797
|
remaining: queued.length - taken.length
|
|
3209
2798
|
};
|
|
3210
2799
|
}
|
|
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
2800
|
if (endOfTurn) this.store.updateSession(row.id, {
|
|
3221
2801
|
status: "idle",
|
|
3222
2802
|
turnHops: 0
|
|
3223
2803
|
});
|
|
3224
2804
|
return {
|
|
3225
2805
|
messages: [],
|
|
3226
|
-
remaining: queued.length
|
|
2806
|
+
remaining: queued.length
|
|
3227
2807
|
};
|
|
3228
2808
|
});
|
|
3229
|
-
if (
|
|
3230
|
-
if ((res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") || notice) this.emitSession(row.id, "updated");
|
|
2809
|
+
if (res.messages.length > 0 ? row.status !== "busy" : endOfTurn && row.status !== "idle") this.emitSession(row.id, "updated");
|
|
3231
2810
|
return {
|
|
3232
2811
|
...res,
|
|
3233
|
-
auto: row.auto,
|
|
3234
|
-
paused: pausedBy !== void 0,
|
|
3235
|
-
...pausedBy !== void 0 ? { pausedBy } : {},
|
|
3236
2812
|
orchestrator
|
|
3237
2813
|
};
|
|
3238
2814
|
}
|
|
3239
2815
|
turnEnd(p) {
|
|
3240
2816
|
const row = this.requireOnline(p.sessionId);
|
|
2817
|
+
this.woken.delete(p.sessionId);
|
|
3241
2818
|
if (row.status === "waiting_on_question") return this.continueWith(row, false, false);
|
|
3242
|
-
return this.continueWith(row, p.allowContinue, true);
|
|
2819
|
+
return this.continueWith(row, p.allowContinue, true, RESPONSE_BUDGET_BYTES, p.maxChars);
|
|
3243
2820
|
}
|
|
3244
2821
|
/**
|
|
3245
2822
|
* An idle-wake listener asks for work. The newest listener of a session wins: an older one gets
|
|
3246
2823
|
* `superseded` and stops. A busy session is not woken; its messages wait for the end of the turn.
|
|
3247
2824
|
*/
|
|
3248
|
-
turnWake(p) {
|
|
2825
|
+
turnWake(conn, p) {
|
|
3249
2826
|
const row = this.requireOnline(p.sessionId);
|
|
3250
2827
|
const known = this.listeners.get(row.id);
|
|
3251
2828
|
if (known?.retired.includes(p.listenerId)) return {
|
|
3252
2829
|
messages: [],
|
|
3253
2830
|
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
2831
|
orchestrator: this.orchestratorNow(),
|
|
3258
2832
|
superseded: true
|
|
3259
2833
|
};
|
|
2834
|
+
const wasConnected = this.listenerConnected(row.id);
|
|
3260
2835
|
if (known?.current !== p.listenerId) {
|
|
3261
2836
|
const retired = known ? [...known.retired, known.current].slice(-64) : [];
|
|
3262
2837
|
this.listeners.set(row.id, {
|
|
3263
2838
|
current: p.listenerId,
|
|
3264
|
-
retired
|
|
2839
|
+
retired,
|
|
2840
|
+
conn
|
|
3265
2841
|
});
|
|
3266
2842
|
if (known) this.emit({
|
|
3267
2843
|
event: "session.updated",
|
|
@@ -3270,24 +2846,31 @@ var Daemon = class {
|
|
|
3270
2846
|
change: "updated"
|
|
3271
2847
|
}
|
|
3272
2848
|
}, row.id);
|
|
3273
|
-
}
|
|
2849
|
+
} else known.conn = conn;
|
|
2850
|
+
if (!wasConnected) this.relay?.sessionsChanged();
|
|
2851
|
+
const d = this.continueWith(row, row.status === "idle", false, RESPONSE_BUDGET_BYTES, p.maxChars);
|
|
2852
|
+
if (d.messages.length > 0) this.markWoken(row.id, d.messages);
|
|
3274
2853
|
return {
|
|
3275
|
-
...
|
|
2854
|
+
...d,
|
|
3276
2855
|
superseded: false
|
|
3277
2856
|
};
|
|
3278
2857
|
}
|
|
3279
2858
|
inbox(p) {
|
|
3280
2859
|
this.requireSession(p.sessionId);
|
|
2860
|
+
return this.readInboxOf(p.sessionId, p.unreadOnly, p.limit);
|
|
2861
|
+
}
|
|
2862
|
+
/** A mailbox's messages, oldest first, marked read. */
|
|
2863
|
+
readInboxOf(id, unreadOnly, limit) {
|
|
3281
2864
|
const at = this.iso();
|
|
3282
2865
|
return this.store.tx(() => {
|
|
3283
|
-
const entries = this.store.entries(
|
|
2866
|
+
const entries = this.store.entries(id, unreadOnly ? { states: ["queued"] } : {});
|
|
3284
2867
|
const res = readInbox(entries, {
|
|
3285
|
-
unreadOnly
|
|
3286
|
-
limit
|
|
2868
|
+
unreadOnly,
|
|
2869
|
+
limit,
|
|
3287
2870
|
maxBytes: RESPONSE_BUDGET_BYTES
|
|
3288
2871
|
}, at);
|
|
3289
2872
|
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(
|
|
2873
|
+
for (const e of res.entries) if (changed.has(e.message.id)) this.store.saveEntry(id, e);
|
|
3291
2874
|
return {
|
|
3292
2875
|
messages: res.returned.map((e) => e.message),
|
|
3293
2876
|
unreadCount: res.unreadCount
|
|
@@ -3299,9 +2882,14 @@ var Daemon = class {
|
|
|
3299
2882
|
const at = this.iso();
|
|
3300
2883
|
return this.store.tx(() => {
|
|
3301
2884
|
const pending = pendingForInjection(this.store.entries(p.sessionId, { states: ["queued"] }));
|
|
3302
|
-
const
|
|
2885
|
+
const fit = takeWithinBytes(pending.slice(0, p.limit), RESPONSE_BUDGET_BYTES);
|
|
2886
|
+
const { taken, preview } = p.maxChars === void 0 ? { taken: fit } : takeWithinChars(fit, p.maxChars, (ms) => formatHookContext(ms));
|
|
3303
2887
|
const updated = markDelivered(taken, taken.map((e) => e.message.id), at);
|
|
3304
2888
|
for (const e of updated) this.store.saveEntry(p.sessionId, e);
|
|
2889
|
+
if (preview) return {
|
|
2890
|
+
messages: [preview],
|
|
2891
|
+
remaining: pending.length
|
|
2892
|
+
};
|
|
3305
2893
|
return {
|
|
3306
2894
|
messages: updated.map((e) => e.message),
|
|
3307
2895
|
remaining: pending.length - taken.length
|
|
@@ -3310,19 +2898,24 @@ var Daemon = class {
|
|
|
3310
2898
|
}
|
|
3311
2899
|
ack(p) {
|
|
3312
2900
|
this.requireSession(p.sessionId);
|
|
2901
|
+
return this.ackFor(p.sessionId, p.ids);
|
|
2902
|
+
}
|
|
2903
|
+
ackFor(id, ids) {
|
|
3313
2904
|
const at = this.iso();
|
|
3314
2905
|
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(
|
|
2906
|
+
const entries = this.store.entries(id, { ids });
|
|
2907
|
+
const res = ackEntries(entries, ids, at);
|
|
2908
|
+
for (const e of res.entries) this.store.saveEntry(id, e);
|
|
3318
2909
|
return { acked: res.acked };
|
|
3319
2910
|
});
|
|
3320
2911
|
}
|
|
3321
2912
|
subscribe(conn, p) {
|
|
3322
|
-
|
|
2913
|
+
if (p.sessionId === void 0) {
|
|
2914
|
+
if (conn.client !== "cli") throw new ConvenoError(RpcErrorCode.Unauthorized, "Pass sessionId to subscribe. Only the conveno command and app can subscribe to every event.");
|
|
2915
|
+
} else this.requireSession(p.sessionId);
|
|
3323
2916
|
const topics = p.topics ?? [...EVENT_NAMES];
|
|
3324
2917
|
conn.sub = {
|
|
3325
|
-
sessionId: p.sessionId,
|
|
2918
|
+
...p.sessionId !== void 0 ? { sessionId: p.sessionId } : {},
|
|
3326
2919
|
topics: new Set(topics)
|
|
3327
2920
|
};
|
|
3328
2921
|
return { subscribed: topics };
|
|
@@ -3343,20 +2936,8 @@ var Daemon = class {
|
|
|
3343
2936
|
default: throw new ConvenoError(RpcErrorCode.MethodNotFound, `Method not found: ${req.method}`);
|
|
3344
2937
|
}
|
|
3345
2938
|
}
|
|
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);
|
|
2939
|
+
sendToRemote(message, target, hops) {
|
|
2940
|
+
this.relay.sendRemote(target, message, hops);
|
|
3360
2941
|
return {
|
|
3361
2942
|
message,
|
|
3362
2943
|
delivery: target.deliveryTier,
|
|
@@ -3370,15 +2951,18 @@ var Daemon = class {
|
|
|
3370
2951
|
relayHost() {
|
|
3371
2952
|
return {
|
|
3372
2953
|
log: this.log,
|
|
3373
|
-
localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) =>
|
|
3374
|
-
|
|
2954
|
+
localSessions: () => this.store.allSessions().filter((r) => r.status !== "offline").map((r) => {
|
|
2955
|
+
const { nativeId: _n, ...s } = this.view(r);
|
|
2956
|
+
return s;
|
|
2957
|
+
}),
|
|
2958
|
+
deliverLocal: (m, to, hops = 0) => {
|
|
3375
2959
|
if (m.kind === "system") return "not_allowed";
|
|
3376
2960
|
const row = this.store.getSession(to);
|
|
3377
2961
|
if (!row) return "session_gone";
|
|
3378
2962
|
if (row.status === "offline") return "session_offline";
|
|
3379
2963
|
if (this.store.hasMessage(m.id)) return void 0;
|
|
3380
2964
|
if (this.store.unreadCount(row.id) >= 1e3) return "mailbox_full";
|
|
3381
|
-
this.store.insertMessage(m, row.id, this.iso());
|
|
2965
|
+
this.store.insertMessage(m, row.id, this.iso(), hops);
|
|
3382
2966
|
this.emitMessage(m, row.id);
|
|
3383
2967
|
},
|
|
3384
2968
|
notify: (to, event, detail) => {
|
|
@@ -3400,30 +2984,18 @@ var Daemon = class {
|
|
|
3400
2984
|
}
|
|
3401
2985
|
};
|
|
3402
2986
|
}
|
|
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);
|
|
2987
|
+
/** Remove every offline session at once. The daemon does this when it starts. */
|
|
2988
|
+
removeAllOffline() {
|
|
2989
|
+
this.removeOffline(0);
|
|
3416
2990
|
}
|
|
3417
2991
|
sweep() {
|
|
3418
|
-
this.tickets.sweep();
|
|
3419
2992
|
const nowMs = this.now().getTime();
|
|
2993
|
+
this.removeOffline(OFFLINE_GRACE_MS);
|
|
2994
|
+
this.retryDaemonWakes(nowMs);
|
|
3420
2995
|
let online = 0;
|
|
3421
2996
|
const rows = this.store.allSessions();
|
|
3422
2997
|
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
|
-
}
|
|
2998
|
+
if (row.status === "offline") continue;
|
|
3427
2999
|
const lastSeenMs = Math.max(Date.parse(row.lastSeenAt), this.startedMs);
|
|
3428
3000
|
const verdict = evaluateLiveness({
|
|
3429
3001
|
lastSeenMs,
|
|
@@ -3436,6 +3008,14 @@ var Daemon = class {
|
|
|
3436
3008
|
else if (nowMs - this.idleSince >= this.idleExitMs) this.requestIdleExit();
|
|
3437
3009
|
}
|
|
3438
3010
|
};
|
|
3011
|
+
/** Do two directory paths name the same place, ignoring trailing separators (and case on Windows)? */
|
|
3012
|
+
function samePath(a, b, platform) {
|
|
3013
|
+
const norm = (p) => {
|
|
3014
|
+
const s = p.replace(/[\\/]+$/, "");
|
|
3015
|
+
return platform === "win32" ? s.replace(/\\/g, "/").toLowerCase() : s;
|
|
3016
|
+
};
|
|
3017
|
+
return norm(a) === norm(b);
|
|
3018
|
+
}
|
|
3439
3019
|
const unauthorizedMessage = "Finish the handshake first: call hello, then auth. Both use the token in daemon.token in the Conveno data directory.";
|
|
3440
3020
|
/** Start the relay client. A broken relay state is logged and leaves the daemon local-only. */
|
|
3441
3021
|
function startRelay(daemon, opts, relayOpts) {
|
|
@@ -3475,11 +3055,13 @@ async function startDaemon(opts) {
|
|
|
3475
3055
|
await clearStaleSocket(socketPath);
|
|
3476
3056
|
let closing;
|
|
3477
3057
|
let timer;
|
|
3058
|
+
const daemonLog = createDaemonLog(paths.daemonLog, { now });
|
|
3478
3059
|
const daemon = new Daemon(store, token, now, isAlive, opts.idleExitMs ?? 6e5, () => {
|
|
3479
3060
|
close().then(() => opts.onIdleExit?.());
|
|
3480
3061
|
}, () => {
|
|
3481
3062
|
close().then(() => opts.onShutdown?.());
|
|
3482
|
-
},
|
|
3063
|
+
}, daemonLog, opts.authTimeoutMs ?? 5e3, opts.autoLimits ?? autoLimitsFromEnv(process.env), processIo, opts.platform, opts.wakers ?? {}, paths.settings);
|
|
3064
|
+
daemon.removeAllOffline();
|
|
3483
3065
|
const srv = createServer((socket) => daemon.attach(socket));
|
|
3484
3066
|
server = srv;
|
|
3485
3067
|
await new Promise((resolve, reject) => {
|
|
@@ -3494,6 +3076,7 @@ async function startDaemon(opts) {
|
|
|
3494
3076
|
function close() {
|
|
3495
3077
|
closing ??= (async () => {
|
|
3496
3078
|
if (timer) clearInterval(timer);
|
|
3079
|
+
daemon.stopping = true;
|
|
3497
3080
|
walker?.close();
|
|
3498
3081
|
daemon.relay?.stop();
|
|
3499
3082
|
const stopped = new Promise((resolve) => srv.close(() => resolve()));
|
|
@@ -3508,7 +3091,16 @@ async function startDaemon(opts) {
|
|
|
3508
3091
|
return {
|
|
3509
3092
|
socketPath,
|
|
3510
3093
|
close,
|
|
3511
|
-
sweep: () => daemon.sweep()
|
|
3094
|
+
sweep: () => daemon.sweep(),
|
|
3095
|
+
testRelay: {
|
|
3096
|
+
host: () => daemon.relayHost(),
|
|
3097
|
+
set: (relay) => {
|
|
3098
|
+
daemon.relay = relay && {
|
|
3099
|
+
sessionsChanged: () => {},
|
|
3100
|
+
...relay
|
|
3101
|
+
};
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
3512
3104
|
};
|
|
3513
3105
|
} catch (e) {
|
|
3514
3106
|
server?.close();
|
|
@@ -3517,264 +3109,11 @@ async function startDaemon(opts) {
|
|
|
3517
3109
|
throw e;
|
|
3518
3110
|
}
|
|
3519
3111
|
}
|
|
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
3112
|
// ../daemon/src/bin.ts
|
|
3774
3113
|
async function main() {
|
|
3775
3114
|
const handle = await startDaemon({
|
|
3776
3115
|
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
3777
|
-
|
|
3116
|
+
wakers: { codex: codexAdapter.daemonWake },
|
|
3778
3117
|
onIdleExit: () => {
|
|
3779
3118
|
process.stderr.write("convenod: no sessions for a while, exiting.\n");
|
|
3780
3119
|
process.exit(0);
|