very-happy-cli 0.2.156 → 0.2.157
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/dist/{AcpBackend-BHe1_F1h.cjs → AcpBackend-BymWX-LI.cjs} +2 -2
- package/dist/{AcpBackend-C3nc1u-s.mjs → AcpBackend-Cy18U7yw.mjs} +2 -2
- package/dist/{AcpSessionManager-BVxkQnNf.cjs → AcpSessionManager-BF7zBGAi.cjs} +1 -1
- package/dist/{AcpSessionManager-dN3k1LbI.mjs → AcpSessionManager-Ds8rcp95.mjs} +1 -1
- package/dist/{agentGuidance-C604n0Zq.mjs → agentGuidance-CU6YD_Ms.mjs} +560 -29
- package/dist/{agentGuidance-C-CmV03f.cjs → agentGuidance-Db76O1kw.cjs} +579 -28
- package/dist/{agentHome-CmIJNV7f.cjs → agentHome-B0CLy0Qx.cjs} +2 -2
- package/dist/{agentHome-D2XGsoqs.mjs → agentHome-BaJ9xtxB.mjs} +2 -2
- package/dist/{auto-B1I6G_Nf.mjs → auto-B1YAwaeU.mjs} +6 -6
- package/dist/{auto-CMDq4oIu.cjs → auto-DqKGFq8U.cjs} +6 -6
- package/dist/codex/happyMcpStdioBridge.cjs +2 -2
- package/dist/codex/happyMcpStdioBridge.mjs +2 -2
- package/dist/{config-BYHSRY2E.cjs → config-CzkBjZnV.cjs} +4 -4
- package/dist/{config-BkTu25bH.mjs → config-aAbhJllb.mjs} +4 -4
- package/dist/{index-B5QbzEga.mjs → index-BVu8Cufk.mjs} +8 -8
- package/dist/{index-DAAreiRF.mjs → index-BYU1e81k.mjs} +288 -44
- package/dist/{index-BbtR-Qto.cjs → index-C9QzZsUQ.cjs} +291 -47
- package/dist/{index-B_-7NpGZ.cjs → index-CTbGqVFY.cjs} +7 -7
- package/dist/{index-CB8QnjvS.cjs → index-Cz-uqnJk.cjs} +4 -4
- package/dist/{index-PYO8Mdz4.mjs → index-DQcRkI9r.mjs} +4 -4
- package/dist/index.cjs +4 -4
- package/dist/index.mjs +4 -4
- package/dist/{install-CO1ps6Wt.cjs → install-BMlV0Tnr.cjs} +1 -1
- package/dist/{install-CNtXzwT_.mjs → install-BuYnqtVa.mjs} +1 -1
- package/dist/{installTerminalHooks-BOAnQ1Qe.cjs → installTerminalHooks-BVVOEGhG.cjs} +4 -4
- package/dist/{installTerminalHooks-CMpOV3RU.mjs → installTerminalHooks-ELDoqh0A.mjs} +4 -4
- package/dist/lib.cjs +2 -2
- package/dist/lib.d.cts +77 -1
- package/dist/lib.d.mts +77 -1
- package/dist/lib.mjs +2 -2
- package/dist/{limits-DmMdchTz.mjs → limits-A2c-3M-_.mjs} +162 -11
- package/dist/{limits-o29KXBgj.cjs → limits-CyuIt-Vl.cjs} +169 -10
- package/dist/{mcp-C_uejotl.mjs → mcp-Bo934Kpy.mjs} +4 -4
- package/dist/{mcp-CwK1nI7Y.cjs → mcp-CXkvnztT.cjs} +4 -4
- package/dist/{piRuntime-Dj5WnqzJ.cjs → piRuntime-CJjA26oD.cjs} +2 -2
- package/dist/{piRuntime-Cu2-8nOT.mjs → piRuntime-DdEY2mE9.mjs} +2 -2
- package/dist/{piTerminal-D-BIbov9.cjs → piTerminal-CpU3hzrX.cjs} +6 -6
- package/dist/{piTerminal-DanZeBrO.mjs → piTerminal-DwWmgumi.mjs} +6 -6
- package/dist/{runGemini-CZ_lhMWY.mjs → runGemini-Cj6oJQ-I.mjs} +6 -6
- package/dist/{runGemini--QqK-Ap5.cjs → runGemini-DS-0qm0L.cjs} +6 -6
- package/dist/{runOpenClaw-C0xLhTvk.cjs → runOpenClaw-CvSm8oTc.cjs} +5 -5
- package/dist/{runOpenClaw-CxgLpm38.mjs → runOpenClaw-DUCQxkI-.mjs} +5 -5
- package/dist/{send-CTcGMVuG.cjs → send-CHxobaoI.cjs} +43 -31
- package/dist/{send-BaOkDgH0.mjs → send-D5CyRyZ_.mjs} +43 -31
- package/dist/{sessions-OmvyJb0n.cjs → sessions-BFlIrKCY.cjs} +133 -49
- package/dist/{sessions-Bn304xF1.mjs → sessions-DsE01xKc.mjs} +133 -49
- package/dist/{spawn-BKNabutV.mjs → spawn-CdihhwHs.mjs} +4 -4
- package/dist/{spawn-CC6V2KiA.cjs → spawn-HV345RN-.cjs} +4 -4
- package/dist/{teams-CLbS2_4Q.mjs → teams-BE8nMB6O.mjs} +5 -5
- package/dist/{teams-XtrH3_h3.cjs → teams-BahinMnH.cjs} +5 -5
- package/dist/{todo-CEDvKNXK.cjs → todo-CMMQ6yhU.cjs} +2 -2
- package/dist/{todo-BcPbNKt2.mjs → todo-CuQAkSp2.mjs} +2 -2
- package/dist/{types-CphWjqHc.cjs → types-B0sSi6eM.cjs} +77 -4
- package/dist/{types-BEVzYSoV.mjs → types-BrGJ7PJz.mjs} +77 -4
- package/package.json +7 -7
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
var z = require('zod');
|
|
4
4
|
var node_crypto = require('node:crypto');
|
|
5
|
-
var persistence = require('./limits-
|
|
5
|
+
var persistence = require('./limits-CyuIt-Vl.cjs');
|
|
6
6
|
var promises = require('node:fs/promises');
|
|
7
7
|
var node_fs = require('node:fs');
|
|
8
8
|
var path = require('node:path');
|
|
@@ -884,7 +884,7 @@ async function resolvePermissionRequest(sessionId, requestId, verdict, deps = {}
|
|
|
884
884
|
`No local key for session ${sessionId} \u2014 approve/deny needs the session key from ~/.happy/sessions.json (the RPC payload is encrypted with it), so only sessions this machine's daemon spawned within 14 days can be answered from here.`
|
|
885
885
|
);
|
|
886
886
|
}
|
|
887
|
-
const token = await (deps.bearerToken ?? bearerToken$
|
|
887
|
+
const token = await (deps.bearerToken ?? bearerToken$2)();
|
|
888
888
|
const fetchState = deps.fetchAgentState ?? fetchDecryptedAgentState;
|
|
889
889
|
const before = pendingRequestsOf(await fetchState(sessionId, persisted, token), now());
|
|
890
890
|
if (!before.some((request) => request.id === requestId)) {
|
|
@@ -934,7 +934,7 @@ async function resolvePermissionRequest(sessionId, requestId, verdict, deps = {}
|
|
|
934
934
|
}
|
|
935
935
|
return { sessionId, requestId, payload, outcome, settled };
|
|
936
936
|
}
|
|
937
|
-
async function bearerToken$
|
|
937
|
+
async function bearerToken$2() {
|
|
938
938
|
const credentials = await persistence.readCredentialsForConfiguredRelay();
|
|
939
939
|
if (!credentials) throw new Error("CLI is not authenticated (no ~/.happy/access.key)");
|
|
940
940
|
return credentials.token;
|
|
@@ -963,6 +963,18 @@ async function fetchDecryptedAgentState(sessionId, persisted, token) {
|
|
|
963
963
|
const SESSION_OPS_CLIENT = "session-ops";
|
|
964
964
|
const DEFAULT_RECENT_LIMIT = 15;
|
|
965
965
|
const MAX_READ_LIMIT = 100;
|
|
966
|
+
function backgroundTasksOf(child) {
|
|
967
|
+
const raw = child.backgroundTasks;
|
|
968
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
969
|
+
const r = raw;
|
|
970
|
+
if (typeof r.count !== "number" || !Array.isArray(r.tasks)) return void 0;
|
|
971
|
+
return {
|
|
972
|
+
count: r.count,
|
|
973
|
+
tasks: r.tasks.filter((task) => !!task && typeof task === "object" && typeof task.id === "string"),
|
|
974
|
+
...typeof r.reportedAt === "number" ? { reportedAt: r.reportedAt } : {},
|
|
975
|
+
...r.stale === true ? { stale: true } : {}
|
|
976
|
+
};
|
|
977
|
+
}
|
|
966
978
|
function mergeSessionSummaries(live, persisted, options = {}) {
|
|
967
979
|
const recentLimit = Math.max(0, options.recentLimit ?? DEFAULT_RECENT_LIMIT);
|
|
968
980
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -982,7 +994,8 @@ function mergeSessionSummaries(live, persisted, options = {}) {
|
|
|
982
994
|
return summaries.filter((summary) => summary.tags?.includes(wanted) === true);
|
|
983
995
|
}
|
|
984
996
|
function livenessOf(child) {
|
|
985
|
-
|
|
997
|
+
const backgroundTasks = backgroundTasksOf(child);
|
|
998
|
+
return { live: true, pid: typeof child.pid === "number" ? child.pid : void 0, ...backgroundTasks ? { backgroundTasks } : {} };
|
|
986
999
|
}
|
|
987
1000
|
function sessionLiveness(live, sessionId) {
|
|
988
1001
|
const child = live.find((entry) => entry.happySessionId === sessionId);
|
|
@@ -994,6 +1007,7 @@ function toSummary(id, persisted, extra) {
|
|
|
994
1007
|
id,
|
|
995
1008
|
live: extra.live,
|
|
996
1009
|
...extra.pid !== void 0 ? { pid: extra.pid } : {},
|
|
1010
|
+
...extra.backgroundTasks ? { backgroundTasks: extra.backgroundTasks } : {},
|
|
997
1011
|
...meta?.summary?.text ? { title: meta.summary.text } : {},
|
|
998
1012
|
...meta?.path ? { cwd: meta.path } : {},
|
|
999
1013
|
...meta?.flavor ? { flavor: meta.flavor } : {},
|
|
@@ -1013,6 +1027,7 @@ function summarizeAccountSession(row, persisted, liveIds, now) {
|
|
|
1013
1027
|
live: liveIds.has(row.id),
|
|
1014
1028
|
url: sessionWebUrl(row.id),
|
|
1015
1029
|
decryptable: false,
|
|
1030
|
+
readable: false,
|
|
1016
1031
|
active: row.active === true,
|
|
1017
1032
|
archived: typeof row.archivedAt === "number",
|
|
1018
1033
|
...typeof row.activeAt === "number" ? { activeAt: row.activeAt } : {},
|
|
@@ -1032,9 +1047,12 @@ function summarizeAccountSession(row, persisted, liveIds, now) {
|
|
|
1032
1047
|
if (!metadata) return base;
|
|
1033
1048
|
const meta = metadata;
|
|
1034
1049
|
const pending = pendingRequestsOf(agentState, now);
|
|
1050
|
+
const backgroundTasks = persistence.backgroundTasksReport(agentState?.backgroundTasks, now, { active: row.active === true });
|
|
1035
1051
|
return {
|
|
1036
1052
|
...base,
|
|
1037
1053
|
decryptable: true,
|
|
1054
|
+
readable: true,
|
|
1055
|
+
backgroundTasks,
|
|
1038
1056
|
...meta.summary?.text ? { title: meta.summary.text } : {},
|
|
1039
1057
|
...meta.path ? { cwd: meta.path } : {},
|
|
1040
1058
|
...meta.flavor ? { flavor: meta.flavor } : {},
|
|
@@ -1064,7 +1082,7 @@ function orderAccountSessions(summaries, options = {}) {
|
|
|
1064
1082
|
return rows.filter((summary) => rank(summary) < 2 || idleKept++ < recentLimit);
|
|
1065
1083
|
}
|
|
1066
1084
|
async function listAccountSessions(options = {}) {
|
|
1067
|
-
const token = await bearerToken();
|
|
1085
|
+
const token = await bearerToken$1();
|
|
1068
1086
|
const response = await axios.get(`${persistence.configuration.serverUrl}/v1/sessions`, {
|
|
1069
1087
|
headers: {
|
|
1070
1088
|
"Authorization": `Bearer ${token}`,
|
|
@@ -1080,7 +1098,7 @@ async function listAccountSessions(options = {}) {
|
|
|
1080
1098
|
const summaries = rows.filter((row) => typeof row?.id === "string").map((row) => summarizeAccountSession(row, persisted[row.id], liveIds, now)).filter((summary) => options.includeArchived || !summary.archived);
|
|
1081
1099
|
return orderAccountSessions(summaries, options);
|
|
1082
1100
|
}
|
|
1083
|
-
async function bearerToken() {
|
|
1101
|
+
async function bearerToken$1() {
|
|
1084
1102
|
const credentials = await persistence.readCredentialsForConfiguredRelay();
|
|
1085
1103
|
if (!credentials) throw new Error("CLI is not authenticated (no ~/.happy/access.key)");
|
|
1086
1104
|
return credentials.token;
|
|
@@ -1095,7 +1113,7 @@ function requirePersisted(sessionId) {
|
|
|
1095
1113
|
return persisted;
|
|
1096
1114
|
}
|
|
1097
1115
|
async function readSessionLog(sessionId, persisted, limit) {
|
|
1098
|
-
const token = await bearerToken();
|
|
1116
|
+
const token = await bearerToken$1();
|
|
1099
1117
|
const response = await axios.get(
|
|
1100
1118
|
`${persistence.configuration.serverUrl}/v3/sessions/${encodeURIComponent(sessionId)}/messages`,
|
|
1101
1119
|
{
|
|
@@ -1134,7 +1152,7 @@ async function readSessionTranscript(sessionId, limit, options = {}) {
|
|
|
1134
1152
|
};
|
|
1135
1153
|
}
|
|
1136
1154
|
async function readSessionMetadata(sessionId, persisted) {
|
|
1137
|
-
const token = await bearerToken();
|
|
1155
|
+
const token = await bearerToken$1();
|
|
1138
1156
|
const response = await axios.get(`${persistence.configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}`, {
|
|
1139
1157
|
headers: {
|
|
1140
1158
|
"Authorization": `Bearer ${token}`,
|
|
@@ -1147,7 +1165,7 @@ async function readSessionMetadata(sessionId, persisted) {
|
|
|
1147
1165
|
return persistence.decrypt(persistence.decodeBase64(persisted.encryptionKey), persisted.encryptionVariant, persistence.decodeBase64(ciphertext));
|
|
1148
1166
|
}
|
|
1149
1167
|
async function readSessionState(sessionId, persisted) {
|
|
1150
|
-
const token = await bearerToken();
|
|
1168
|
+
const token = await bearerToken$1();
|
|
1151
1169
|
const response = await axios.get(`${persistence.configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}`, {
|
|
1152
1170
|
headers: {
|
|
1153
1171
|
"Authorization": `Bearer ${token}`,
|
|
@@ -1199,7 +1217,7 @@ async function stopSession(sessionId) {
|
|
|
1199
1217
|
return await persistence.stopDaemonSession(sessionId);
|
|
1200
1218
|
}
|
|
1201
1219
|
async function archiveSession(sessionId) {
|
|
1202
|
-
const token = await bearerToken();
|
|
1220
|
+
const token = await bearerToken$1();
|
|
1203
1221
|
await axios.post(
|
|
1204
1222
|
`${persistence.configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}/archive`,
|
|
1205
1223
|
{},
|
|
@@ -1213,7 +1231,7 @@ async function archiveSession(sessionId) {
|
|
|
1213
1231
|
);
|
|
1214
1232
|
}
|
|
1215
1233
|
async function unarchiveSession(sessionId) {
|
|
1216
|
-
const token = await bearerToken();
|
|
1234
|
+
const token = await bearerToken$1();
|
|
1217
1235
|
await axios.post(
|
|
1218
1236
|
`${persistence.configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}/unarchive`,
|
|
1219
1237
|
{},
|
|
@@ -1249,7 +1267,7 @@ function explainNotLive(sessionId, status, resumeHint) {
|
|
|
1249
1267
|
}
|
|
1250
1268
|
}
|
|
1251
1269
|
const CLI_RESUME_HINT = "Use --resume to bring it back on this machine, or spawn a new session.";
|
|
1252
|
-
const defaultDeps = {
|
|
1270
|
+
const defaultDeps$1 = {
|
|
1253
1271
|
listLive: () => persistence.listDaemonSessions(),
|
|
1254
1272
|
readState: (sessionId, persisted) => readSessionState(sessionId, persisted),
|
|
1255
1273
|
send: (sessionId, persisted, text, client, options) => sendUserMessage(sessionId, persisted, text, client, options),
|
|
@@ -1260,7 +1278,7 @@ const defaultDeps = {
|
|
|
1260
1278
|
now: () => Date.now()
|
|
1261
1279
|
};
|
|
1262
1280
|
async function deliverToSession(sessionId, persisted, text, client, options = {}, deps = {}) {
|
|
1263
|
-
const d = { ...defaultDeps, ...deps };
|
|
1281
|
+
const d = { ...defaultDeps$1, ...deps };
|
|
1264
1282
|
const resumeHint = options.resumeHint ?? CLI_RESUME_HINT;
|
|
1265
1283
|
const classify = async () => {
|
|
1266
1284
|
const [live, server] = await Promise.all([d.listLive(), d.readState(sessionId, persisted)]);
|
|
@@ -1351,6 +1369,10 @@ async function waitUntilLive(classify, d, options) {
|
|
|
1351
1369
|
const SESSION_PEER_SENT_FROM = "session-peer";
|
|
1352
1370
|
const CLI_PEER_SENDER_ID = "cli";
|
|
1353
1371
|
const MESSAGE_FOOTER = "This message comes from another agent session on this machine, not from the user.";
|
|
1372
|
+
const MESSAGE_FOOTER_PREFIX = "This message comes from another agent session";
|
|
1373
|
+
function messageFooterFor(sender) {
|
|
1374
|
+
return sender.machine ? `${MESSAGE_FOOTER_PREFIX} on machine ${sanitizeHeaderValue(sender.machine, 128)}, not from the user.` : MESSAGE_FOOTER;
|
|
1375
|
+
}
|
|
1354
1376
|
function sanitizeHeaderValue(value, max = 200) {
|
|
1355
1377
|
if (!value) return "";
|
|
1356
1378
|
const collapsed = value.replace(/\s+/g, " ").trim().slice(0, max);
|
|
@@ -1360,6 +1382,7 @@ function senderFields(sender) {
|
|
|
1360
1382
|
const parts = [];
|
|
1361
1383
|
if (sender.flavor) parts.push(`agent ${sanitizeHeaderValue(sender.flavor, 32)}`);
|
|
1362
1384
|
if (sender.cwd) parts.push(`cwd ${sanitizeHeaderValue(sender.cwd, 400)}`);
|
|
1385
|
+
if (sender.machine) parts.push(`machine ${sanitizeHeaderValue(sender.machine, 128)}`);
|
|
1363
1386
|
return parts.map((part) => `; ${part}`).join("");
|
|
1364
1387
|
}
|
|
1365
1388
|
function quotedTitle(sender) {
|
|
@@ -1367,7 +1390,9 @@ function quotedTitle(sender) {
|
|
|
1367
1390
|
}
|
|
1368
1391
|
function formatSessionPeerMessage(input) {
|
|
1369
1392
|
const header = `[Very Happy session message ${input.id} from ${quotedTitle(input.from)} ${input.from.sessionId}${senderFields(input.from)}${input.replyTo ? `; re ${sanitizeHeaderValue(input.replyTo, 64)}` : ""}]`;
|
|
1370
|
-
const
|
|
1393
|
+
const base = messageFooterFor(input.from);
|
|
1394
|
+
const routed = input.from.machine ? " (it is routed to that machine for you)" : "";
|
|
1395
|
+
const footer = input.from.sessionId === CLI_PEER_SENDER_ID ? `${base} It was sent from the command line (\`very-happy sessions message\`), so there is no session to reply to; act on it here.` : `${base} Reply with session_message(to: "${input.from.sessionId}")${routed} \u2014 or \`very-happy sessions message ${input.from.sessionId} "<text>"\` \u2014 only when you have something to add (a question, a decision, a heads-up). Do not reply just to acknowledge or thank; the exchange ends when nothing is left to coordinate.`;
|
|
1371
1396
|
return `${header}
|
|
1372
1397
|
${input.body.trim()}
|
|
1373
1398
|
|
|
@@ -1429,7 +1454,7 @@ function resolveRepoIdentity(cwd, fs = realFs) {
|
|
|
1429
1454
|
}
|
|
1430
1455
|
return { root: null, common: null };
|
|
1431
1456
|
}
|
|
1432
|
-
const PEER_SCOPES = ["repo", "cwd", "machine"];
|
|
1457
|
+
const PEER_SCOPES$1 = ["repo", "cwd", "machine"];
|
|
1433
1458
|
function isPeerInScope(scope, self, other) {
|
|
1434
1459
|
if (scope === "machine") return true;
|
|
1435
1460
|
if (scope === "cwd") return path.resolve(self.cwd) === path.resolve(other.cwd);
|
|
@@ -1437,24 +1462,508 @@ function isPeerInScope(scope, self, other) {
|
|
|
1437
1462
|
return path.resolve(self.cwd) === path.resolve(other.cwd);
|
|
1438
1463
|
}
|
|
1439
1464
|
|
|
1465
|
+
const REMOTE_SESSION_OPS_MIN_CLI_VERSION = "0.2.157";
|
|
1466
|
+
const REMOTE_OPS_PROTOCOL_VERSION = 1;
|
|
1467
|
+
const REMOTE_TEXT_MAX_BYTES = 64 * 1024;
|
|
1468
|
+
const REMOTE_TRANSCRIPT_MAX_BYTES = 200 * 1024;
|
|
1469
|
+
const REMOTE_CALLS_PER_MINUTE = 60;
|
|
1470
|
+
const REMOTE_WRITE_CALLS_PER_MINUTE = 30;
|
|
1471
|
+
const REMOTE_LOCATE_MAX_IDS = 200;
|
|
1472
|
+
const REMOTE_OP_DEADLINE_MS = 25e3;
|
|
1473
|
+
const REMOTE_SEND_COMMIT_DEADLINE_MS = 18e3;
|
|
1474
|
+
const REMOTE_RESUME_WAIT_MS = 1e4;
|
|
1475
|
+
const REMOTE_WAIT_POLL_MS = 5e3;
|
|
1476
|
+
const REMOTE_ANSWER_MAX_BYTES = 64 * 1024;
|
|
1477
|
+
const REMOTE_TITLE_MAX_BYTES = 1024;
|
|
1478
|
+
const REMOTE_SENT_FROM_ALLOWED = ["cli", "assistant", "automation"];
|
|
1479
|
+
const LOCAL_ID_RE = /^[a-zA-Z0-9_.:-]{1,128}$/;
|
|
1480
|
+
function remoteError(code, message) {
|
|
1481
|
+
return { ok: false, error: { code, message } };
|
|
1482
|
+
}
|
|
1483
|
+
const SESSION_ID_RE = /^[a-zA-Z0-9_-]{1,128}$/;
|
|
1484
|
+
const PEER_SCOPES = ["repo", "cwd", "machine"];
|
|
1485
|
+
function isSessionId(value) {
|
|
1486
|
+
return typeof value === "string" && SESSION_ID_RE.test(value);
|
|
1487
|
+
}
|
|
1488
|
+
function utf8Bytes(text) {
|
|
1489
|
+
return Buffer.byteLength(text, "utf8");
|
|
1490
|
+
}
|
|
1491
|
+
function sanitizeSender(raw) {
|
|
1492
|
+
if (!raw || typeof raw !== "object") return null;
|
|
1493
|
+
const r = raw;
|
|
1494
|
+
if (typeof r.sessionId !== "string" || r.sessionId.length === 0 || r.sessionId.length > 128) return null;
|
|
1495
|
+
const optional = (key, max) => typeof r[key] === "string" && r[key].length > 0 ? { [key]: r[key].slice(0, max) } : {};
|
|
1496
|
+
return {
|
|
1497
|
+
sessionId: r.sessionId,
|
|
1498
|
+
...optional("title", 200),
|
|
1499
|
+
...optional("flavor", 32),
|
|
1500
|
+
...optional("cwd", 1024),
|
|
1501
|
+
...optional("machine", 128)
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
function guardRemoteSessionOpsRequest(method, raw, options) {
|
|
1505
|
+
if (!options.enabled) {
|
|
1506
|
+
return remoteError("disabled", 'Remote session operations are turned off on this machine (settings.json remoteSessionOps = "off")');
|
|
1507
|
+
}
|
|
1508
|
+
if (!raw || typeof raw !== "object") return remoteError("bad_request", "Request must be an object");
|
|
1509
|
+
const r = raw;
|
|
1510
|
+
if (r.v !== REMOTE_OPS_PROTOCOL_VERSION) return remoteError("bad_request", `Unsupported protocol version ${String(r.v)} (this daemon speaks v${REMOTE_OPS_PROTOCOL_VERSION})`);
|
|
1511
|
+
const from = r.from;
|
|
1512
|
+
if (!from || typeof from !== "object" || typeof from.host !== "string" || from.host.length === 0 || typeof from.cli !== "string") {
|
|
1513
|
+
return remoteError("bad_request", "from.host and from.cli are required");
|
|
1514
|
+
}
|
|
1515
|
+
const caller = {
|
|
1516
|
+
host: from.host.slice(0, 128),
|
|
1517
|
+
cli: from.cli.slice(0, 32),
|
|
1518
|
+
...typeof from.machineId === "string" && from.machineId.length > 0 ? { machineId: from.machineId.slice(0, 128) } : {},
|
|
1519
|
+
...isSessionId(from.sessionId) ? { sessionId: from.sessionId } : {}
|
|
1520
|
+
};
|
|
1521
|
+
const args = r.args && typeof r.args === "object" ? r.args : {};
|
|
1522
|
+
const limit = typeof args.limit === "number" && Number.isFinite(args.limit) && args.limit >= 1 ? Math.floor(args.limit) : void 0;
|
|
1523
|
+
let clean;
|
|
1524
|
+
switch (method) {
|
|
1525
|
+
case "sessions.list": {
|
|
1526
|
+
if (args.ids !== void 0) {
|
|
1527
|
+
if (!Array.isArray(args.ids) || !args.ids.every(isSessionId)) return remoteError("bad_request", "ids must be an array of session ids");
|
|
1528
|
+
if (args.ids.length > REMOTE_LOCATE_MAX_IDS) return remoteError("too_large", `ids: at most ${REMOTE_LOCATE_MAX_IDS} per call`);
|
|
1529
|
+
}
|
|
1530
|
+
const out = {
|
|
1531
|
+
...args.ids !== void 0 ? { ids: args.ids } : {},
|
|
1532
|
+
...args.all === true ? { all: true } : {},
|
|
1533
|
+
...typeof args.tag === "string" && args.tag.length > 0 ? { tag: args.tag.slice(0, 128) } : {},
|
|
1534
|
+
...limit !== void 0 ? { limit } : {}
|
|
1535
|
+
};
|
|
1536
|
+
clean = out;
|
|
1537
|
+
break;
|
|
1538
|
+
}
|
|
1539
|
+
case "sessions.read": {
|
|
1540
|
+
if (!isSessionId(args.sessionId)) return remoteError("bad_request", "sessionId is required");
|
|
1541
|
+
const out = { sessionId: args.sessionId, ...limit !== void 0 ? { limit } : {}, ...args.full === true ? { full: true } : {} };
|
|
1542
|
+
clean = out;
|
|
1543
|
+
break;
|
|
1544
|
+
}
|
|
1545
|
+
case "sessions.send": {
|
|
1546
|
+
if (!isSessionId(args.sessionId)) return remoteError("bad_request", "sessionId is required");
|
|
1547
|
+
if (typeof args.text !== "string" || args.text.trim().length === 0) return remoteError("bad_request", "text must be non-empty");
|
|
1548
|
+
if (utf8Bytes(args.text) > REMOTE_TEXT_MAX_BYTES) return remoteError("too_large", `text exceeds ${REMOTE_TEXT_MAX_BYTES} bytes`);
|
|
1549
|
+
if (args.localId !== void 0 && (typeof args.localId !== "string" || !LOCAL_ID_RE.test(args.localId))) return remoteError("bad_request", "localId must be a short id");
|
|
1550
|
+
const out = {
|
|
1551
|
+
sessionId: args.sessionId,
|
|
1552
|
+
text: args.text,
|
|
1553
|
+
...args.resume === true ? { resume: true } : {},
|
|
1554
|
+
...args.model === null || typeof args.model === "string" && args.model.length <= 128 ? { model: args.model } : {},
|
|
1555
|
+
...REMOTE_SENT_FROM_ALLOWED.includes(args.sentFrom) ? { sentFrom: args.sentFrom } : {},
|
|
1556
|
+
...typeof args.localId === "string" ? { localId: args.localId } : {}
|
|
1557
|
+
};
|
|
1558
|
+
clean = out;
|
|
1559
|
+
break;
|
|
1560
|
+
}
|
|
1561
|
+
case "sessions.peers": {
|
|
1562
|
+
if (args.scope !== void 0 && !PEER_SCOPES.includes(args.scope)) return remoteError("bad_request", `scope must be one of ${PEER_SCOPES.join(", ")}`);
|
|
1563
|
+
const out = {
|
|
1564
|
+
...args.scope !== void 0 ? { scope: args.scope } : {},
|
|
1565
|
+
...typeof args.cwd === "string" && args.cwd.length > 0 ? { cwd: args.cwd.slice(0, 4096) } : {}
|
|
1566
|
+
};
|
|
1567
|
+
clean = out;
|
|
1568
|
+
break;
|
|
1569
|
+
}
|
|
1570
|
+
case "sessions.message": {
|
|
1571
|
+
if (!isSessionId(args.to)) return remoteError("bad_request", "to is required");
|
|
1572
|
+
if (typeof args.body !== "string" || args.body.trim().length === 0) return remoteError("bad_request", "body must be non-empty");
|
|
1573
|
+
if (utf8Bytes(args.body) > REMOTE_TEXT_MAX_BYTES) return remoteError("too_large", `body exceeds ${REMOTE_TEXT_MAX_BYTES} bytes`);
|
|
1574
|
+
const sender = sanitizeSender(args.from);
|
|
1575
|
+
if (!sender) return remoteError("bad_request", "from.sessionId (the sender) is required");
|
|
1576
|
+
const out = {
|
|
1577
|
+
to: args.to,
|
|
1578
|
+
body: args.body,
|
|
1579
|
+
...typeof args.replyTo === "string" && args.replyTo.length > 0 ? { replyTo: args.replyTo.slice(0, 64) } : {},
|
|
1580
|
+
// The recipient's header names the machine the call came
|
|
1581
|
+
// from, as the caller identified itself — never a value the
|
|
1582
|
+
// sender picked for someone else.
|
|
1583
|
+
from: { ...sender, machine: caller.host }
|
|
1584
|
+
};
|
|
1585
|
+
clean = out;
|
|
1586
|
+
break;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
return { ok: true, request: { v: REMOTE_OPS_PROTOCOL_VERSION, from: caller, args: clean } };
|
|
1590
|
+
}
|
|
1591
|
+
class RemoteCallBudget {
|
|
1592
|
+
constructor(perMinute = REMOTE_CALLS_PER_MINUTE, now = Date.now) {
|
|
1593
|
+
this.perMinute = perMinute;
|
|
1594
|
+
this.now = now;
|
|
1595
|
+
this.tokens = perMinute;
|
|
1596
|
+
this.lastRefill = now();
|
|
1597
|
+
}
|
|
1598
|
+
tokens;
|
|
1599
|
+
lastRefill;
|
|
1600
|
+
/** Take one token; false = over budget (with ms until the next token). */
|
|
1601
|
+
take() {
|
|
1602
|
+
if (this.perMinute <= 0) return { ok: true };
|
|
1603
|
+
const t = this.now();
|
|
1604
|
+
const refill = (t - this.lastRefill) / 6e4 * this.perMinute;
|
|
1605
|
+
if (refill > 0) {
|
|
1606
|
+
this.tokens = Math.min(this.perMinute, this.tokens + refill);
|
|
1607
|
+
this.lastRefill = t;
|
|
1608
|
+
}
|
|
1609
|
+
if (this.tokens >= 1) {
|
|
1610
|
+
this.tokens -= 1;
|
|
1611
|
+
return { ok: true };
|
|
1612
|
+
}
|
|
1613
|
+
return { ok: false, retryAfterMs: Math.ceil((1 - this.tokens) / this.perMinute * 6e4) };
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
function sanitizeAuditValue(value, max = 64) {
|
|
1617
|
+
if (typeof value !== "string" || value.length === 0) return "?";
|
|
1618
|
+
return value.slice(0, max).replace(/[^\x20-\x7e]/g, "?");
|
|
1619
|
+
}
|
|
1620
|
+
function formatRemoteAuditLine(input) {
|
|
1621
|
+
const from = input.from;
|
|
1622
|
+
const opt = (value) => value === void 0 ? "-" : sanitizeAuditValue(value);
|
|
1623
|
+
return `[REMOTE SESSION OPS] ${sanitizeAuditValue(input.method)} from machine=${sanitizeAuditValue(from?.machineId)} host=${sanitizeAuditValue(from?.host)} cli=${sanitizeAuditValue(from?.cli, 32)} session=${opt(from?.sessionId)} target=${opt(input.sessionId)} \u2192 ${input.outcome} (${Math.max(0, Math.round(input.durationMs))}ms)`;
|
|
1624
|
+
}
|
|
1625
|
+
function capRemoteText(text, maxBytes, keep = "head") {
|
|
1626
|
+
if (utf8Bytes(text) <= maxBytes) return text;
|
|
1627
|
+
const buffer = Buffer.from(text, "utf8");
|
|
1628
|
+
const marker = "\u2026";
|
|
1629
|
+
const room = Math.max(0, maxBytes - Buffer.byteLength(marker));
|
|
1630
|
+
const slice = keep === "head" ? buffer.subarray(0, room) : buffer.subarray(buffer.length - room);
|
|
1631
|
+
const clean = slice.toString("utf8").replace(/^�+|�+$/g, "");
|
|
1632
|
+
return keep === "head" ? clean + marker : marker + clean;
|
|
1633
|
+
}
|
|
1634
|
+
function capRemoteTranscript(transcript, maxBytes = REMOTE_TRANSCRIPT_MAX_BYTES) {
|
|
1635
|
+
if (utf8Bytes(transcript) <= maxBytes) return { transcript, truncated: false };
|
|
1636
|
+
const buffer = Buffer.from(transcript, "utf8");
|
|
1637
|
+
const marker = "\u2026 [truncated by the remote machine: transcript exceeded the RPC budget; use --limit] \u2026\n";
|
|
1638
|
+
const tail = buffer.subarray(buffer.length - (maxBytes - Buffer.byteLength(marker))).toString("utf8");
|
|
1639
|
+
return { transcript: marker + tail.replace(/^�+/, ""), truncated: true };
|
|
1640
|
+
}
|
|
1641
|
+
function parseHappyClientVersion(value) {
|
|
1642
|
+
if (typeof value !== "string") return null;
|
|
1643
|
+
const match = value.match(/(\d+)\.(\d+)\.(\d+)/);
|
|
1644
|
+
return match ? `${match[1]}.${match[2]}.${match[3]}` : null;
|
|
1645
|
+
}
|
|
1646
|
+
function compareVersions(a, b) {
|
|
1647
|
+
const pa = a.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
1648
|
+
const pb = b.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
1649
|
+
for (let i = 0; i < 3; i++) {
|
|
1650
|
+
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
1651
|
+
if (d !== 0) return d;
|
|
1652
|
+
}
|
|
1653
|
+
return 0;
|
|
1654
|
+
}
|
|
1655
|
+
function supportsRemoteSessionOps(cliVersion) {
|
|
1656
|
+
if (!cliVersion) return null;
|
|
1657
|
+
return compareVersions(cliVersion, REMOTE_SESSION_OPS_MIN_CLI_VERSION) >= 0;
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
const REMOTE_CLIENT_TAG = "session-ops";
|
|
1661
|
+
const REMOTE_RPC_TIMEOUT_MS = 3e4;
|
|
1662
|
+
const REMOTE_LOCATE_MAX_MACHINES = 8;
|
|
1663
|
+
class RemoteSessionOpsError extends Error {
|
|
1664
|
+
constructor(code, message, machineId, ambiguous = false) {
|
|
1665
|
+
super(message);
|
|
1666
|
+
this.code = code;
|
|
1667
|
+
this.machineId = machineId;
|
|
1668
|
+
this.ambiguous = ambiguous;
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
async function bearerToken() {
|
|
1672
|
+
const credentials = await persistence.readCredentialsForConfiguredRelay();
|
|
1673
|
+
if (!credentials) throw new Error("CLI is not authenticated (no ~/.happy/access.key)");
|
|
1674
|
+
return credentials.token;
|
|
1675
|
+
}
|
|
1676
|
+
async function listAccountMachines() {
|
|
1677
|
+
const token = await bearerToken();
|
|
1678
|
+
const response = await axios.get(`${persistence.configuration.serverUrl}/v1/machines`, {
|
|
1679
|
+
headers: { "Authorization": `Bearer ${token}`, "X-Happy-Client": `${REMOTE_CLIENT_TAG}/${persistence.configuration.currentCliVersion}` },
|
|
1680
|
+
timeout: 15e3
|
|
1681
|
+
});
|
|
1682
|
+
const rows = Array.isArray(response.data) ? response.data : [];
|
|
1683
|
+
return rows.filter((row) => !!row && typeof row === "object" && typeof row.id === "string").map((row) => ({
|
|
1684
|
+
id: row.id,
|
|
1685
|
+
active: row.active === true,
|
|
1686
|
+
...typeof row.activeAt === "number" ? { activeAt: row.activeAt } : {},
|
|
1687
|
+
cliVersion: parseHappyClientVersion(row.lastHappyClient)
|
|
1688
|
+
}));
|
|
1689
|
+
}
|
|
1690
|
+
async function callerIdentity(env = process.env) {
|
|
1691
|
+
const settings = await persistence.readSettings().catch(() => null);
|
|
1692
|
+
const sessionId = env.VH_PEER_SESSION_ID;
|
|
1693
|
+
return {
|
|
1694
|
+
...settings?.machineId ? { machineId: settings.machineId } : {},
|
|
1695
|
+
host: os.hostname(),
|
|
1696
|
+
cli: persistence.configuration.currentCliVersion,
|
|
1697
|
+
...sessionId && /^[a-zA-Z0-9_-]{1,128}$/.test(sessionId) ? { sessionId } : {}
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
const defaultDeps = {
|
|
1701
|
+
listMachines: listAccountMachines,
|
|
1702
|
+
selfMachineId: async () => (await persistence.readSettings().catch(() => null))?.machineId,
|
|
1703
|
+
openTransport: async () => {
|
|
1704
|
+
const socket = await openUserScopedSocket(await bearerToken());
|
|
1705
|
+
return {
|
|
1706
|
+
call: (method, paramsJson) => socket.rpcCall({ method, params: paramsJson }, REMOTE_RPC_TIMEOUT_MS),
|
|
1707
|
+
close: () => socket.close()
|
|
1708
|
+
};
|
|
1709
|
+
},
|
|
1710
|
+
caller: () => callerIdentity(),
|
|
1711
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
1712
|
+
now: () => Date.now()
|
|
1713
|
+
};
|
|
1714
|
+
function withDefaults(deps) {
|
|
1715
|
+
return { ...defaultDeps, ...deps };
|
|
1716
|
+
}
|
|
1717
|
+
function pickRemoteCandidates(machines, selfId) {
|
|
1718
|
+
const candidates = [];
|
|
1719
|
+
const skipped = [];
|
|
1720
|
+
for (const machine of machines) {
|
|
1721
|
+
if (selfId && machine.id === selfId) {
|
|
1722
|
+
skipped.push({ machine, reason: "self" });
|
|
1723
|
+
continue;
|
|
1724
|
+
}
|
|
1725
|
+
if (!machine.active) {
|
|
1726
|
+
skipped.push({ machine, reason: "offline" });
|
|
1727
|
+
continue;
|
|
1728
|
+
}
|
|
1729
|
+
if (supportsRemoteSessionOps(machine.cliVersion) === false) {
|
|
1730
|
+
skipped.push({ machine, reason: "too_old" });
|
|
1731
|
+
continue;
|
|
1732
|
+
}
|
|
1733
|
+
candidates.push(machine);
|
|
1734
|
+
}
|
|
1735
|
+
candidates.sort((a, b) => (b.activeAt ?? 0) - (a.activeAt ?? 0));
|
|
1736
|
+
return { candidates: candidates.slice(0, REMOTE_LOCATE_MAX_MACHINES), skipped };
|
|
1737
|
+
}
|
|
1738
|
+
function describeAge(activeAt, now) {
|
|
1739
|
+
if (activeAt === void 0) return "never seen";
|
|
1740
|
+
const minutes = Math.round((now - activeAt) / 6e4);
|
|
1741
|
+
if (minutes < 2) return "seen just now";
|
|
1742
|
+
if (minutes < 120) return `last seen ${minutes}m ago`;
|
|
1743
|
+
if (minutes < 48 * 60) return `last seen ${Math.round(minutes / 60)}h ago`;
|
|
1744
|
+
return `last seen ${Math.round(minutes / 1440)}d ago`;
|
|
1745
|
+
}
|
|
1746
|
+
async function resolveExplicitMachine(machineId, deps) {
|
|
1747
|
+
const machines = await deps.listMachines();
|
|
1748
|
+
const machine = machines.find((row) => row.id === machineId);
|
|
1749
|
+
if (!machine) throw new RemoteSessionOpsError("unknown_machine", `Machine ${machineId} is not on this account`, machineId);
|
|
1750
|
+
if (!machine.active) throw new RemoteSessionOpsError("offline", `Machine ${machineId} is offline (${describeAge(machine.activeAt, deps.now())}); its sessions cannot be reached until its daemon reconnects`, machineId);
|
|
1751
|
+
if (supportsRemoteSessionOps(machine.cliVersion) === false) {
|
|
1752
|
+
throw new RemoteSessionOpsError("too_old", `Machine ${machineId} runs CLI ${machine.cliVersion}; cross-machine session operations need \u2265 ${REMOTE_SESSION_OPS_MIN_CLI_VERSION} on the target`, machineId);
|
|
1753
|
+
}
|
|
1754
|
+
return machine;
|
|
1755
|
+
}
|
|
1756
|
+
async function callRemoteSessionOp(transport, machineId, method, args, from) {
|
|
1757
|
+
const params = JSON.stringify({ v: REMOTE_OPS_PROTOCOL_VERSION, from, args });
|
|
1758
|
+
let ack;
|
|
1759
|
+
try {
|
|
1760
|
+
ack = await transport.call(`${machineId}:${method}`, params);
|
|
1761
|
+
} catch (error) {
|
|
1762
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
1763
|
+
throw new RemoteSessionOpsError("unreachable", `Machine ${machineId} did not answer ${method} (${reason})`, machineId, true);
|
|
1764
|
+
}
|
|
1765
|
+
if (!ack?.ok) {
|
|
1766
|
+
const reason = ack?.error ?? "no ack";
|
|
1767
|
+
if (/not available/i.test(reason)) {
|
|
1768
|
+
throw new RemoteSessionOpsError("unreachable", `Machine ${machineId} did not answer ${method}: its daemon is offline, restarting, or runs a CLI older than ${REMOTE_SESSION_OPS_MIN_CLI_VERSION}`, machineId);
|
|
1769
|
+
}
|
|
1770
|
+
throw new RemoteSessionOpsError("unreachable", `Machine ${machineId}: ${reason}`, machineId, true);
|
|
1771
|
+
}
|
|
1772
|
+
let envelope;
|
|
1773
|
+
try {
|
|
1774
|
+
envelope = typeof ack.result === "string" ? JSON.parse(ack.result) : ack.result;
|
|
1775
|
+
} catch {
|
|
1776
|
+
throw new RemoteSessionOpsError("unreachable", `Machine ${machineId} returned an unreadable ${method} response`, machineId);
|
|
1777
|
+
}
|
|
1778
|
+
if (!envelope || typeof envelope !== "object") throw new RemoteSessionOpsError("unreachable", `Machine ${machineId} returned an empty ${method} response`, machineId);
|
|
1779
|
+
if ("ok" in envelope) {
|
|
1780
|
+
if (envelope.ok) return envelope.result;
|
|
1781
|
+
throw new RemoteSessionOpsError(envelope.error.code, `Machine ${machineId}: ${envelope.error.message}`, machineId);
|
|
1782
|
+
}
|
|
1783
|
+
throw new RemoteSessionOpsError("internal", `Machine ${machineId}: ${envelope.error ?? "remote handler failed"}`, machineId);
|
|
1784
|
+
}
|
|
1785
|
+
async function locateRemoteSession(transport, sessionId, options, deps) {
|
|
1786
|
+
const from = await deps.caller();
|
|
1787
|
+
if (options.machineId) {
|
|
1788
|
+
const machine = await resolveExplicitMachine(options.machineId, deps);
|
|
1789
|
+
const listing = await callRemoteSessionOp(transport, machine.id, "sessions.list", { ids: [sessionId] }, from);
|
|
1790
|
+
if (!listing.sessions.some((row) => row.id === sessionId)) {
|
|
1791
|
+
throw new RemoteSessionOpsError("no_local_key", `Machine ${machine.id} (${listing.host}) has no key for session ${sessionId}: it was not spawned there (or is older than 14 days)`, machine.id);
|
|
1792
|
+
}
|
|
1793
|
+
return { machine, host: listing.host };
|
|
1794
|
+
}
|
|
1795
|
+
const { candidates, skipped } = pickRemoteCandidates(await deps.listMachines(), await deps.selfMachineId());
|
|
1796
|
+
const failures = [];
|
|
1797
|
+
for (const machine of candidates) {
|
|
1798
|
+
try {
|
|
1799
|
+
const listing = await callRemoteSessionOp(transport, machine.id, "sessions.list", { ids: [sessionId] }, from);
|
|
1800
|
+
if (listing.sessions.some((row) => row.id === sessionId)) return { machine, host: listing.host };
|
|
1801
|
+
failures.push(`${listing.host || machine.id}: not there`);
|
|
1802
|
+
} catch (error) {
|
|
1803
|
+
failures.push(`${machine.id}: ${error instanceof RemoteSessionOpsError ? error.code : error instanceof Error ? error.message : String(error)}`);
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
const skippedText = skipped.filter((s) => s.reason !== "self").map((s) => `${s.machine.id}: ${s.reason}`);
|
|
1807
|
+
const detail = [...failures, ...skippedText];
|
|
1808
|
+
throw new RemoteSessionOpsError(
|
|
1809
|
+
"not_located",
|
|
1810
|
+
`Session ${sessionId} is not on this machine and no online machine of this account reports it${detail.length ? ` (${detail.join("; ")})` : " (no other machines are online)"}. Pass --machine <id> to name one, or bring its machine online.`
|
|
1811
|
+
);
|
|
1812
|
+
}
|
|
1813
|
+
async function withRemoteTransport(deps, fn) {
|
|
1814
|
+
const transport = await deps.openTransport();
|
|
1815
|
+
try {
|
|
1816
|
+
return await fn(transport);
|
|
1817
|
+
} finally {
|
|
1818
|
+
try {
|
|
1819
|
+
transport.close();
|
|
1820
|
+
} catch {
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
async function readRemoteTranscript(sessionId, options = {}, overrides = {}) {
|
|
1825
|
+
const deps = withDefaults(overrides);
|
|
1826
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1827
|
+
const located = await locateRemoteSession(transport, sessionId, { machineId: options.machineId }, deps);
|
|
1828
|
+
return callRemoteSessionOp(transport, located.machine.id, "sessions.read", {
|
|
1829
|
+
sessionId,
|
|
1830
|
+
...options.limit !== void 0 ? { limit: options.limit } : {},
|
|
1831
|
+
...options.full ? { full: true } : {}
|
|
1832
|
+
}, await deps.caller());
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
async function waitForRemoteTurnEnd(sessionId, options, overrides = {}) {
|
|
1836
|
+
const deps = withDefaults(overrides);
|
|
1837
|
+
const pollMs = options.pollMs ?? REMOTE_WAIT_POLL_MS;
|
|
1838
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1839
|
+
const located = await locateRemoteSession(transport, sessionId, { machineId: options.machineId }, deps);
|
|
1840
|
+
const from = await deps.caller();
|
|
1841
|
+
const deadline = deps.now() + options.timeoutMs;
|
|
1842
|
+
const args = { sessionId, ...options.limit !== void 0 ? { limit: options.limit } : {}, ...options.full ? { full: true } : {} };
|
|
1843
|
+
while (true) {
|
|
1844
|
+
const read = await callRemoteSessionOp(transport, located.machine.id, "sessions.read", args, from);
|
|
1845
|
+
if (read.turn.ended) return { read, timedOut: false };
|
|
1846
|
+
if (deps.now() + pollMs > deadline) return { read, timedOut: true };
|
|
1847
|
+
await deps.sleep(pollMs);
|
|
1848
|
+
}
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
async function sendRemoteMessage(sessionId, text, options = {}, overrides = {}) {
|
|
1852
|
+
const deps = withDefaults(overrides);
|
|
1853
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1854
|
+
const located = await locateRemoteSession(transport, sessionId, { machineId: options.machineId }, deps);
|
|
1855
|
+
const from = await deps.caller();
|
|
1856
|
+
const localId = options.localId ?? `remote-send-${node_crypto.randomUUID()}`;
|
|
1857
|
+
const args = {
|
|
1858
|
+
sessionId,
|
|
1859
|
+
text,
|
|
1860
|
+
localId,
|
|
1861
|
+
...options.resume ? { resume: true } : {},
|
|
1862
|
+
...options.model !== void 0 ? { model: options.model } : {},
|
|
1863
|
+
...options.sentFrom !== void 0 ? { sentFrom: options.sentFrom } : {}
|
|
1864
|
+
};
|
|
1865
|
+
const attempt = () => callRemoteSessionOp(transport, located.machine.id, "sessions.send", args, from);
|
|
1866
|
+
let result;
|
|
1867
|
+
try {
|
|
1868
|
+
result = await attempt();
|
|
1869
|
+
} catch (error) {
|
|
1870
|
+
const retryable = error instanceof RemoteSessionOpsError && (error.ambiguous || error.code === "timeout");
|
|
1871
|
+
if (!retryable) throw error;
|
|
1872
|
+
result = await attempt();
|
|
1873
|
+
}
|
|
1874
|
+
return { ...result, machine: { id: located.machine.id, host: located.host } };
|
|
1875
|
+
});
|
|
1876
|
+
}
|
|
1877
|
+
async function sendRemotePeerMessage(args, options = {}, overrides = {}) {
|
|
1878
|
+
const deps = withDefaults(overrides);
|
|
1879
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1880
|
+
const located = await locateRemoteSession(transport, args.to, { machineId: options.machineId }, deps);
|
|
1881
|
+
const caller = await deps.caller();
|
|
1882
|
+
const result = await callRemoteSessionOp(transport, located.machine.id, "sessions.message", {
|
|
1883
|
+
to: args.to,
|
|
1884
|
+
body: args.body,
|
|
1885
|
+
...args.replyTo ? { replyTo: args.replyTo } : {},
|
|
1886
|
+
from: { ...args.from, machine: args.from.machine ?? caller.host }
|
|
1887
|
+
}, caller);
|
|
1888
|
+
return { ...result, machine: { id: located.machine.id, host: located.host } };
|
|
1889
|
+
});
|
|
1890
|
+
}
|
|
1891
|
+
async function listRemotePeers(machineId, options = {}, overrides = {}) {
|
|
1892
|
+
const deps = withDefaults(overrides);
|
|
1893
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1894
|
+
const machine = await resolveExplicitMachine(machineId, deps);
|
|
1895
|
+
return callRemoteSessionOp(transport, machine.id, "sessions.peers", {
|
|
1896
|
+
...options.scope ? { scope: options.scope } : {},
|
|
1897
|
+
...options.cwd ? { cwd: options.cwd } : {}
|
|
1898
|
+
}, await deps.caller());
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1901
|
+
async function listRemoteSessions(machineId, options = {}, overrides = {}) {
|
|
1902
|
+
const deps = withDefaults(overrides);
|
|
1903
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1904
|
+
const machine = await resolveExplicitMachine(machineId, deps);
|
|
1905
|
+
return callRemoteSessionOp(transport, machine.id, "sessions.list", {
|
|
1906
|
+
...options.tag ? { tag: options.tag } : {},
|
|
1907
|
+
...options.limit !== void 0 ? { limit: options.limit } : {}
|
|
1908
|
+
}, await deps.caller());
|
|
1909
|
+
});
|
|
1910
|
+
}
|
|
1911
|
+
async function fillForeignAccountRows(rows, overrides = {}) {
|
|
1912
|
+
const deps = withDefaults(overrides);
|
|
1913
|
+
const pending = new Set(rows.filter((row) => !row.decryptable).map((row) => row.id));
|
|
1914
|
+
const asked = [];
|
|
1915
|
+
if (pending.size === 0) return { rows, asked, skipped: [] };
|
|
1916
|
+
const { candidates, skipped } = pickRemoteCandidates(await deps.listMachines(), await deps.selfMachineId());
|
|
1917
|
+
const filled = /* @__PURE__ */ new Map();
|
|
1918
|
+
if (candidates.length > 0) {
|
|
1919
|
+
await withRemoteTransport(deps, async (transport) => {
|
|
1920
|
+
const from = await deps.caller();
|
|
1921
|
+
for (const machine of candidates) {
|
|
1922
|
+
if (pending.size === 0) break;
|
|
1923
|
+
try {
|
|
1924
|
+
const listing = await callRemoteSessionOp(transport, machine.id, "sessions.list", { ids: [...pending], all: true }, from);
|
|
1925
|
+
let count = 0;
|
|
1926
|
+
for (const row of listing.sessions) {
|
|
1927
|
+
if (!pending.has(row.id)) continue;
|
|
1928
|
+
pending.delete(row.id);
|
|
1929
|
+
count++;
|
|
1930
|
+
filled.set(row.id, { ...row, decryptable: false, readable: true, via: machine.id, machine: { id: machine.id, host: listing.host } });
|
|
1931
|
+
}
|
|
1932
|
+
asked.push({ machineId: machine.id, host: listing.host, filled: count });
|
|
1933
|
+
} catch (error) {
|
|
1934
|
+
asked.push({ machineId: machine.id, filled: 0, error: error instanceof Error ? error.message : String(error) });
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
});
|
|
1938
|
+
}
|
|
1939
|
+
return {
|
|
1940
|
+
rows: rows.map((row) => filled.get(row.id) ?? row),
|
|
1941
|
+
asked,
|
|
1942
|
+
skipped: skipped.filter((s) => s.reason !== "self").map((s) => ({ machineId: s.machine.id, reason: s.reason }))
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1440
1946
|
const SESSION_PEER_TOOL_NAMES = ["session_message", "session_peers"];
|
|
1441
1947
|
const SESSION_PEER_TOOL_SCHEMAS = {
|
|
1442
1948
|
session_message: {
|
|
1443
1949
|
title: "Message Another Session",
|
|
1444
1950
|
readOnly: false,
|
|
1445
|
-
description: "Send a message to another agent session
|
|
1951
|
+
description: "Send a message to another agent session (find ids with session_peers). It lands in that session's chat with your title, session id and cwd, and tells the peer how to reply to you. Use it to coordinate when you both edit the same files: say what you are changing and ask what they are changing. Returns as soon as the message is queued; the reply arrives later as a message from that session. Sessions on this machine are reached directly; a session spawned by another machine of this account is routed to that machine's daemon (it must be online). Terminal-mirror sessions cannot receive messages.",
|
|
1446
1952
|
inputSchema: {
|
|
1447
1953
|
to: z.z.string().min(1).max(128).describe("Target session id (from session_peers, or a peer's message header)"),
|
|
1448
1954
|
body: z.z.string().min(1).max(16e3).describe("The message text"),
|
|
1449
|
-
replyTo: z.z.string().min(1).max(64).optional().describe("Id of the peer message you are answering (from its header), if any")
|
|
1955
|
+
replyTo: z.z.string().min(1).max(64).optional().describe("Id of the peer message you are answering (from its header), if any"),
|
|
1956
|
+
machineId: z.z.string().min(1).max(128).optional().describe("Machine id the target session runs on, when known (skips the lookup across the account's machines)")
|
|
1450
1957
|
}
|
|
1451
1958
|
},
|
|
1452
1959
|
session_peers: {
|
|
1453
1960
|
title: "List Peer Sessions",
|
|
1454
1961
|
readOnly: true,
|
|
1455
|
-
description: 'List the other agent sessions running on this machine and the files each edited in the last 30 minutes. Default scope "repo": sessions in the same git repository, including its other worktrees (sameWorktree says whether they share your checkout). "cwd": the same directory only. "machine": every live session here.',
|
|
1962
|
+
description: 'List the other agent sessions running on this machine and the files each edited in the last 30 minutes. Default scope "repo": sessions in the same git repository, including its other worktrees (sameWorktree says whether they share your checkout). "cwd": the same directory only. "machine": every live session here. With machineId, list the live sessions on that other machine of this account instead (scope "machine" unless you pass a cwd that exists there).',
|
|
1456
1963
|
inputSchema: {
|
|
1457
|
-
scope: z.z.enum(["repo", "cwd", "machine"]).optional().describe("repo (default) | cwd | machine")
|
|
1964
|
+
scope: z.z.enum(["repo", "cwd", "machine"]).optional().describe("repo (default) | cwd | machine"),
|
|
1965
|
+
machineId: z.z.string().min(1).max(128).optional().describe("Another machine of this account (from the web's machine list) to list instead of this one"),
|
|
1966
|
+
cwd: z.z.string().min(1).max(4096).optional().describe("With machineId: a directory on that machine to compute repo/cwd scope from")
|
|
1458
1967
|
}
|
|
1459
1968
|
}
|
|
1460
1969
|
};
|
|
@@ -1495,19 +2004,27 @@ async function sendPeerMessage(context, args) {
|
|
|
1495
2004
|
if (args.to === self.sessionId) throw new Error("That is this session; message a peer instead");
|
|
1496
2005
|
const body = typeof args.body === "string" ? args.body.trim() : "";
|
|
1497
2006
|
if (!body) throw new Error("body must be non-empty");
|
|
2007
|
+
const now = (context.now ?? Date.now)();
|
|
1498
2008
|
const persisted = (context.readPersisted ?? persistence.readPersistedSessions)()[args.to];
|
|
1499
|
-
if (!persisted) {
|
|
1500
|
-
|
|
2009
|
+
if (!persisted || args.machineId) {
|
|
2010
|
+
const remote = context.remoteMessage === void 0 ? sendRemotePeerMessage : context.remoteMessage;
|
|
2011
|
+
if (remote === null) {
|
|
2012
|
+
throw new Error(`Session ${args.to} is not on this machine (no local key)`);
|
|
2013
|
+
}
|
|
2014
|
+
if (context.sentTo) {
|
|
2015
|
+
const budget = checkPeerSendBudget(context.sentTo, args.to, now);
|
|
2016
|
+
if (!budget.ok) throw new Error(replyLoopRefusal(budget.count, args.to));
|
|
2017
|
+
}
|
|
2018
|
+
const result2 = await remote({ to: args.to, body, replyTo: args.replyTo, from: self, machineId: args.machineId });
|
|
2019
|
+
context.sentTo?.get(args.to)?.push(now);
|
|
2020
|
+
return result2;
|
|
1501
2021
|
}
|
|
1502
2022
|
const live = (await (context.listPeers ?? persistence.listDaemonPeers)()).find((session) => session.sessionId === args.to);
|
|
1503
2023
|
if (!live) throw new Error(`Session ${args.to} is not running on this machine; nothing would read the message`);
|
|
1504
2024
|
if (live.kind === "mirror") throw new Error(`Session ${args.to} is a terminal mirror (a person typing claude in a terminal); it cannot receive messages`);
|
|
1505
|
-
const now = (context.now ?? Date.now)();
|
|
1506
2025
|
if (context.sentTo) {
|
|
1507
2026
|
const budget = checkPeerSendBudget(context.sentTo, args.to, now);
|
|
1508
|
-
if (!budget.ok)
|
|
1509
|
-
throw new Error(`Refused: this session already sent ${budget.count} messages to ${args.to} in the last ${Math.round(PEER_MESSAGE_RATE_WINDOW_MS / 6e4)} minutes. That is a reply loop, not coordination \u2014 STOP replying to that session now; do not send acknowledgements or thanks. Continue your own work.`);
|
|
1510
|
-
}
|
|
2027
|
+
if (!budget.ok) throw new Error(replyLoopRefusal(budget.count, args.to));
|
|
1511
2028
|
}
|
|
1512
2029
|
const messageId = node_crypto.randomUUID().slice(0, 8);
|
|
1513
2030
|
const text = formatSessionPeerMessage({ id: messageId, from: self, body, replyTo: args.replyTo });
|
|
@@ -1523,13 +2040,27 @@ async function sendPeerMessage(context, args) {
|
|
|
1523
2040
|
...result.error ? { error: result.error } : {}
|
|
1524
2041
|
};
|
|
1525
2042
|
}
|
|
2043
|
+
function replyLoopRefusal(count, to) {
|
|
2044
|
+
return `Refused: this session already sent ${count} messages to ${to} in the last ${Math.round(PEER_MESSAGE_RATE_WINDOW_MS / 6e4)} minutes. That is a reply loop, not coordination \u2014 STOP replying to that session now; do not send acknowledgements or thanks. Continue your own work.`;
|
|
2045
|
+
}
|
|
1526
2046
|
async function executeSessionPeerTool(name, args, context) {
|
|
1527
2047
|
switch (name) {
|
|
1528
2048
|
case "session_message":
|
|
1529
|
-
return sendPeerMessage(context, {
|
|
2049
|
+
return sendPeerMessage(context, {
|
|
2050
|
+
to: String(args?.to ?? ""),
|
|
2051
|
+
body: String(args?.body ?? ""),
|
|
2052
|
+
...args?.replyTo ? { replyTo: String(args.replyTo) } : {},
|
|
2053
|
+
...args?.machineId ? { machineId: String(args.machineId) } : {}
|
|
2054
|
+
});
|
|
1530
2055
|
case "session_peers": {
|
|
1531
2056
|
const scope = args?.scope;
|
|
1532
|
-
if (scope !== void 0 && !PEER_SCOPES.includes(scope)) throw new Error(`scope must be one of ${PEER_SCOPES.join(", ")}`);
|
|
2057
|
+
if (scope !== void 0 && !PEER_SCOPES$1.includes(scope)) throw new Error(`scope must be one of ${PEER_SCOPES$1.join(", ")}`);
|
|
2058
|
+
if (args?.machineId) {
|
|
2059
|
+
return (context.remotePeers ?? listRemotePeers)(String(args.machineId), {
|
|
2060
|
+
...scope !== void 0 ? { scope } : {},
|
|
2061
|
+
...typeof args.cwd === "string" && args.cwd ? { cwd: args.cwd } : {}
|
|
2062
|
+
});
|
|
2063
|
+
}
|
|
1533
2064
|
return listPeerSessions(context, scope ?? "repo");
|
|
1534
2065
|
}
|
|
1535
2066
|
}
|
|
@@ -1616,15 +2147,24 @@ exports.AGENT_GUIDANCE = AGENT_GUIDANCE;
|
|
|
1616
2147
|
exports.AUTOMATIONS_UNAVAILABLE_MESSAGE = AUTOMATIONS_UNAVAILABLE_MESSAGE;
|
|
1617
2148
|
exports.AUTOMATION_TOOL_NAMES = AUTOMATION_TOOL_NAMES;
|
|
1618
2149
|
exports.AutomationsRequestError = AutomationsRequestError;
|
|
2150
|
+
exports.CLI_PEER_SENDER_ID = CLI_PEER_SENDER_ID;
|
|
1619
2151
|
exports.DEFAULT_RECENT_LIMIT = DEFAULT_RECENT_LIMIT;
|
|
1620
2152
|
exports.MAX_READ_LIMIT = MAX_READ_LIMIT;
|
|
1621
|
-
exports.PEER_SCOPES = PEER_SCOPES;
|
|
2153
|
+
exports.PEER_SCOPES = PEER_SCOPES$1;
|
|
1622
2154
|
exports.PREVIEW_TOOL_DESCRIPTION = PREVIEW_TOOL_DESCRIPTION;
|
|
1623
2155
|
exports.PREVIEW_TOOL_NAME = PREVIEW_TOOL_NAME;
|
|
1624
2156
|
exports.PREVIEW_TOOL_TITLE = PREVIEW_TOOL_TITLE;
|
|
2157
|
+
exports.REMOTE_ANSWER_MAX_BYTES = REMOTE_ANSWER_MAX_BYTES;
|
|
2158
|
+
exports.REMOTE_OP_DEADLINE_MS = REMOTE_OP_DEADLINE_MS;
|
|
2159
|
+
exports.REMOTE_RESUME_WAIT_MS = REMOTE_RESUME_WAIT_MS;
|
|
2160
|
+
exports.REMOTE_SEND_COMMIT_DEADLINE_MS = REMOTE_SEND_COMMIT_DEADLINE_MS;
|
|
2161
|
+
exports.REMOTE_TITLE_MAX_BYTES = REMOTE_TITLE_MAX_BYTES;
|
|
2162
|
+
exports.REMOTE_WRITE_CALLS_PER_MINUTE = REMOTE_WRITE_CALLS_PER_MINUTE;
|
|
1625
2163
|
exports.REPORT_PROGRESS_TOOL_DESCRIPTION = REPORT_PROGRESS_TOOL_DESCRIPTION;
|
|
1626
2164
|
exports.REPORT_PROGRESS_TOOL_NAME = REPORT_PROGRESS_TOOL_NAME;
|
|
1627
2165
|
exports.REPORT_PROGRESS_TOOL_TITLE = REPORT_PROGRESS_TOOL_TITLE;
|
|
2166
|
+
exports.RemoteCallBudget = RemoteCallBudget;
|
|
2167
|
+
exports.RemoteSessionOpsError = RemoteSessionOpsError;
|
|
1628
2168
|
exports.SESSION_PEER_SENT_FROM = SESSION_PEER_SENT_FROM;
|
|
1629
2169
|
exports.SESSION_PEER_TOOL_NAMES = SESSION_PEER_TOOL_NAMES;
|
|
1630
2170
|
exports.TEAM_TOOL_NAMES = TEAM_TOOL_NAMES;
|
|
@@ -1635,16 +2175,24 @@ exports.analyzeLatestTurn = analyzeLatestTurn;
|
|
|
1635
2175
|
exports.archiveSession = archiveSession;
|
|
1636
2176
|
exports.authenticatedAutomationsClient = authenticatedAutomationsClient;
|
|
1637
2177
|
exports.automationRunIdFromEnv = automationRunIdFromEnv;
|
|
2178
|
+
exports.capRemoteText = capRemoteText;
|
|
2179
|
+
exports.capRemoteTranscript = capRemoteTranscript;
|
|
1638
2180
|
exports.cliPeerSelf = cliPeerSelf;
|
|
1639
2181
|
exports.createAutomationsClient = createAutomationsClient;
|
|
1640
2182
|
exports.createSessionPeerToolExecutor = createSessionPeerToolExecutor;
|
|
1641
2183
|
exports.createTeamsClient = createTeamsClient;
|
|
1642
2184
|
exports.deliverToSession = deliverToSession;
|
|
2185
|
+
exports.fillForeignAccountRows = fillForeignAccountRows;
|
|
1643
2186
|
exports.formatEditConflictNotice = formatEditConflictNotice;
|
|
2187
|
+
exports.formatRemoteAuditLine = formatRemoteAuditLine;
|
|
2188
|
+
exports.guardRemoteSessionOpsRequest = guardRemoteSessionOpsRequest;
|
|
1644
2189
|
exports.isAutomationsUnavailable = isAutomationsUnavailable;
|
|
1645
2190
|
exports.listAccountSessions = listAccountSessions;
|
|
1646
2191
|
exports.listPeerSessions = listPeerSessions;
|
|
2192
|
+
exports.listRemotePeers = listRemotePeers;
|
|
2193
|
+
exports.listRemoteSessions = listRemoteSessions;
|
|
1647
2194
|
exports.listSessions = listSessions;
|
|
2195
|
+
exports.readRemoteTranscript = readRemoteTranscript;
|
|
1648
2196
|
exports.readSessionLog = readSessionLog;
|
|
1649
2197
|
exports.readSessionMetadata = readSessionMetadata;
|
|
1650
2198
|
exports.readSessionTranscript = readSessionTranscript;
|
|
@@ -1652,8 +2200,10 @@ exports.readTeamScope = readTeamScope;
|
|
|
1652
2200
|
exports.registerAutomationTools = registerAutomationTools;
|
|
1653
2201
|
exports.registerSessionPeerTools = registerSessionPeerTools;
|
|
1654
2202
|
exports.registerTeamsTools = registerTeamsTools;
|
|
2203
|
+
exports.remoteError = remoteError;
|
|
1655
2204
|
exports.resolvePermissionRequest = resolvePermissionRequest;
|
|
1656
2205
|
exports.sendPeerMessage = sendPeerMessage;
|
|
2206
|
+
exports.sendRemoteMessage = sendRemoteMessage;
|
|
1657
2207
|
exports.sendUserMessage = sendUserMessage;
|
|
1658
2208
|
exports.sessionWebUrl = sessionWebUrl;
|
|
1659
2209
|
exports.stopSession = stopSession;
|
|
@@ -1661,5 +2211,6 @@ exports.teamRequest = teamRequest;
|
|
|
1661
2211
|
exports.teamScopePath = teamScopePath;
|
|
1662
2212
|
exports.trimIdent = trimIdent;
|
|
1663
2213
|
exports.userPromptText = userPromptText;
|
|
2214
|
+
exports.waitForRemoteTurnEnd = waitForRemoteTurnEnd;
|
|
1664
2215
|
exports.waitForSessionKey = waitForSessionKey;
|
|
1665
2216
|
exports.waitForTurnEnd = waitForTurnEnd;
|