very-happy-cli 0.2.155 → 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-DmFcRh54.cjs → AcpBackend-BymWX-LI.cjs} +2 -2
- package/dist/{AcpBackend-DVB0nzgR.mjs → AcpBackend-Cy18U7yw.mjs} +2 -2
- package/dist/{AcpSessionManager-CWaSYTnT.cjs → AcpSessionManager-BF7zBGAi.cjs} +1 -1
- package/dist/{AcpSessionManager-dGDgNb-p.mjs → AcpSessionManager-Ds8rcp95.mjs} +1 -1
- package/dist/{agentGuidance-BWxFC6UL.mjs → agentGuidance-CU6YD_Ms.mjs} +560 -29
- package/dist/{agentGuidance-un7YPryB.cjs → agentGuidance-Db76O1kw.cjs} +579 -28
- package/dist/{agentHome-aucT8BHw.cjs → agentHome-B0CLy0Qx.cjs} +2 -2
- package/dist/{agentHome-ByLb2HFg.mjs → agentHome-BaJ9xtxB.mjs} +2 -2
- package/dist/{auto-BQnD6gVx.mjs → auto-B1YAwaeU.mjs} +6 -6
- package/dist/{auto-P9RoJaY0.cjs → auto-DqKGFq8U.cjs} +6 -6
- package/dist/codex/happyMcpStdioBridge.cjs +2 -2
- package/dist/codex/happyMcpStdioBridge.mjs +2 -2
- package/dist/{config-BoePh9PX.cjs → config-CzkBjZnV.cjs} +4 -4
- package/dist/{config-BPZ2Y6o8.mjs → config-aAbhJllb.mjs} +4 -4
- package/dist/{index-BjzdXb9x.mjs → index-BVu8Cufk.mjs} +8 -8
- package/dist/{index-B4oXnbYw.mjs → index-BYU1e81k.mjs} +372 -65
- package/dist/{index-D_fYUxVg.cjs → index-C9QzZsUQ.cjs} +375 -68
- package/dist/{index-DRrLaljt.cjs → index-CTbGqVFY.cjs} +7 -7
- package/dist/{index--KCpVs1c.cjs → index-Cz-uqnJk.cjs} +4 -4
- package/dist/{index-DVVRqaVG.mjs → index-DQcRkI9r.mjs} +4 -4
- package/dist/index.cjs +4 -4
- package/dist/index.mjs +4 -4
- package/dist/{install-CGigiocs.cjs → install-BMlV0Tnr.cjs} +1 -1
- package/dist/{install-DP5aPNEX.mjs → install-BuYnqtVa.mjs} +1 -1
- package/dist/{installTerminalHooks-XrcPvfBs.cjs → installTerminalHooks-BVVOEGhG.cjs} +4 -4
- package/dist/{installTerminalHooks-tIg7mANc.mjs → installTerminalHooks-ELDoqh0A.mjs} +4 -4
- package/dist/lib.cjs +2 -2
- package/dist/lib.d.cts +101 -9
- package/dist/lib.d.mts +101 -9
- package/dist/lib.mjs +2 -2
- package/dist/{limits-C_DW0M0q.mjs → limits-A2c-3M-_.mjs} +162 -11
- package/dist/{limits-DkfHJ3nS.cjs → limits-CyuIt-Vl.cjs} +169 -10
- package/dist/{mcp-o7QglAQM.mjs → mcp-Bo934Kpy.mjs} +4 -4
- package/dist/{mcp-BqlXl10F.cjs → mcp-CXkvnztT.cjs} +4 -4
- package/dist/{piRuntime-BxP4B_zY.cjs → piRuntime-CJjA26oD.cjs} +2 -2
- package/dist/{piRuntime-MjiJI-nV.mjs → piRuntime-DdEY2mE9.mjs} +2 -2
- package/dist/{piTerminal-DYzRcwgb.cjs → piTerminal-CpU3hzrX.cjs} +6 -6
- package/dist/{piTerminal-Dpq6yqKU.mjs → piTerminal-DwWmgumi.mjs} +6 -6
- package/dist/{runGemini-CDlcQ-OA.mjs → runGemini-Cj6oJQ-I.mjs} +6 -6
- package/dist/{runGemini-8Pxh94Fm.cjs → runGemini-DS-0qm0L.cjs} +6 -6
- package/dist/{runOpenClaw-B5FSZIbK.cjs → runOpenClaw-CvSm8oTc.cjs} +5 -5
- package/dist/{runOpenClaw-YkhsgPs0.mjs → runOpenClaw-DUCQxkI-.mjs} +5 -5
- package/dist/{send-CwrYXTPr.cjs → send-CHxobaoI.cjs} +43 -31
- package/dist/{send-DJStmLBv.mjs → send-D5CyRyZ_.mjs} +43 -31
- package/dist/{sessions-MX21NJXd.cjs → sessions-BFlIrKCY.cjs} +133 -49
- package/dist/{sessions-JaVXlSqj.mjs → sessions-DsE01xKc.mjs} +133 -49
- package/dist/{spawn-BaPnjClT.mjs → spawn-CdihhwHs.mjs} +4 -4
- package/dist/{spawn-cIoglKVf.cjs → spawn-HV345RN-.cjs} +4 -4
- package/dist/{teams-DXV5Pwwt.mjs → teams-BE8nMB6O.mjs} +5 -5
- package/dist/{teams-Dqk7F3D-.cjs → teams-BahinMnH.cjs} +5 -5
- package/dist/{todo-Buuqn9gm.cjs → todo-CMMQ6yhU.cjs} +2 -2
- package/dist/{todo-2Z1REhfx.mjs → todo-CuQAkSp2.mjs} +2 -2
- package/dist/{types-a2xsH2UI.cjs → types-B0sSi6eM.cjs} +125 -13
- package/dist/{types-CkbfdRzq.mjs → types-BrGJ7PJz.mjs} +125 -13
- package/package.json +7 -7
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { G as normalizeHttpEndpoint, c as configuration, r as readSettings, d as readPersistedSessions, h as readCredentialsForConfiguredRelay, H as AutomationNameSchema, I as AutomationConcurrencySchema, J as AutomationActionSchema, K as AutomationTriggerSchema, w as encodeBase64, L as encrypt, M as decodeBase64, g as delay, N as decrypt, O as listDaemonSessions, n as stopDaemonSession, P as resumeDaemonSession, i as isValidSessionId,
|
|
3
|
+
import { G as normalizeHttpEndpoint, c as configuration, r as readSettings, d as readPersistedSessions, h as readCredentialsForConfiguredRelay, H as AutomationNameSchema, I as AutomationConcurrencySchema, J as AutomationActionSchema, K as AutomationTriggerSchema, w as encodeBase64, L as encrypt, M as decodeBase64, g as delay, N as decrypt, O as listDaemonSessions, n as stopDaemonSession, P as backgroundTasksReport, Q as resumeDaemonSession, i as isValidSessionId, R as listDaemonPeers } from './limits-A2c-3M-_.mjs';
|
|
4
4
|
import { open, mkdir, rename, unlink } from 'node:fs/promises';
|
|
5
5
|
import { constants, existsSync, readFileSync, statSync } from 'node:fs';
|
|
6
6
|
import { isAbsolute, join, dirname, resolve as resolve$1 } from 'node:path';
|
|
7
|
-
import {
|
|
7
|
+
import { hostname, userInfo } from 'node:os';
|
|
8
8
|
import axios from 'axios';
|
|
9
9
|
import { io } from 'socket.io-client';
|
|
10
10
|
|
|
@@ -882,7 +882,7 @@ async function resolvePermissionRequest(sessionId, requestId, verdict, deps = {}
|
|
|
882
882
|
`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.`
|
|
883
883
|
);
|
|
884
884
|
}
|
|
885
|
-
const token = await (deps.bearerToken ?? bearerToken$
|
|
885
|
+
const token = await (deps.bearerToken ?? bearerToken$2)();
|
|
886
886
|
const fetchState = deps.fetchAgentState ?? fetchDecryptedAgentState;
|
|
887
887
|
const before = pendingRequestsOf(await fetchState(sessionId, persisted, token), now());
|
|
888
888
|
if (!before.some((request) => request.id === requestId)) {
|
|
@@ -932,7 +932,7 @@ async function resolvePermissionRequest(sessionId, requestId, verdict, deps = {}
|
|
|
932
932
|
}
|
|
933
933
|
return { sessionId, requestId, payload, outcome, settled };
|
|
934
934
|
}
|
|
935
|
-
async function bearerToken$
|
|
935
|
+
async function bearerToken$2() {
|
|
936
936
|
const credentials = await readCredentialsForConfiguredRelay();
|
|
937
937
|
if (!credentials) throw new Error("CLI is not authenticated (no ~/.happy/access.key)");
|
|
938
938
|
return credentials.token;
|
|
@@ -961,6 +961,18 @@ async function fetchDecryptedAgentState(sessionId, persisted, token) {
|
|
|
961
961
|
const SESSION_OPS_CLIENT = "session-ops";
|
|
962
962
|
const DEFAULT_RECENT_LIMIT = 15;
|
|
963
963
|
const MAX_READ_LIMIT = 100;
|
|
964
|
+
function backgroundTasksOf(child) {
|
|
965
|
+
const raw = child.backgroundTasks;
|
|
966
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
967
|
+
const r = raw;
|
|
968
|
+
if (typeof r.count !== "number" || !Array.isArray(r.tasks)) return void 0;
|
|
969
|
+
return {
|
|
970
|
+
count: r.count,
|
|
971
|
+
tasks: r.tasks.filter((task) => !!task && typeof task === "object" && typeof task.id === "string"),
|
|
972
|
+
...typeof r.reportedAt === "number" ? { reportedAt: r.reportedAt } : {},
|
|
973
|
+
...r.stale === true ? { stale: true } : {}
|
|
974
|
+
};
|
|
975
|
+
}
|
|
964
976
|
function mergeSessionSummaries(live, persisted, options = {}) {
|
|
965
977
|
const recentLimit = Math.max(0, options.recentLimit ?? DEFAULT_RECENT_LIMIT);
|
|
966
978
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -980,7 +992,8 @@ function mergeSessionSummaries(live, persisted, options = {}) {
|
|
|
980
992
|
return summaries.filter((summary) => summary.tags?.includes(wanted) === true);
|
|
981
993
|
}
|
|
982
994
|
function livenessOf(child) {
|
|
983
|
-
|
|
995
|
+
const backgroundTasks = backgroundTasksOf(child);
|
|
996
|
+
return { live: true, pid: typeof child.pid === "number" ? child.pid : void 0, ...backgroundTasks ? { backgroundTasks } : {} };
|
|
984
997
|
}
|
|
985
998
|
function sessionLiveness(live, sessionId) {
|
|
986
999
|
const child = live.find((entry) => entry.happySessionId === sessionId);
|
|
@@ -992,6 +1005,7 @@ function toSummary(id, persisted, extra) {
|
|
|
992
1005
|
id,
|
|
993
1006
|
live: extra.live,
|
|
994
1007
|
...extra.pid !== void 0 ? { pid: extra.pid } : {},
|
|
1008
|
+
...extra.backgroundTasks ? { backgroundTasks: extra.backgroundTasks } : {},
|
|
995
1009
|
...meta?.summary?.text ? { title: meta.summary.text } : {},
|
|
996
1010
|
...meta?.path ? { cwd: meta.path } : {},
|
|
997
1011
|
...meta?.flavor ? { flavor: meta.flavor } : {},
|
|
@@ -1011,6 +1025,7 @@ function summarizeAccountSession(row, persisted, liveIds, now) {
|
|
|
1011
1025
|
live: liveIds.has(row.id),
|
|
1012
1026
|
url: sessionWebUrl(row.id),
|
|
1013
1027
|
decryptable: false,
|
|
1028
|
+
readable: false,
|
|
1014
1029
|
active: row.active === true,
|
|
1015
1030
|
archived: typeof row.archivedAt === "number",
|
|
1016
1031
|
...typeof row.activeAt === "number" ? { activeAt: row.activeAt } : {},
|
|
@@ -1030,9 +1045,12 @@ function summarizeAccountSession(row, persisted, liveIds, now) {
|
|
|
1030
1045
|
if (!metadata) return base;
|
|
1031
1046
|
const meta = metadata;
|
|
1032
1047
|
const pending = pendingRequestsOf(agentState, now);
|
|
1048
|
+
const backgroundTasks = backgroundTasksReport(agentState?.backgroundTasks, now, { active: row.active === true });
|
|
1033
1049
|
return {
|
|
1034
1050
|
...base,
|
|
1035
1051
|
decryptable: true,
|
|
1052
|
+
readable: true,
|
|
1053
|
+
backgroundTasks,
|
|
1036
1054
|
...meta.summary?.text ? { title: meta.summary.text } : {},
|
|
1037
1055
|
...meta.path ? { cwd: meta.path } : {},
|
|
1038
1056
|
...meta.flavor ? { flavor: meta.flavor } : {},
|
|
@@ -1062,7 +1080,7 @@ function orderAccountSessions(summaries, options = {}) {
|
|
|
1062
1080
|
return rows.filter((summary) => rank(summary) < 2 || idleKept++ < recentLimit);
|
|
1063
1081
|
}
|
|
1064
1082
|
async function listAccountSessions(options = {}) {
|
|
1065
|
-
const token = await bearerToken();
|
|
1083
|
+
const token = await bearerToken$1();
|
|
1066
1084
|
const response = await axios.get(`${configuration.serverUrl}/v1/sessions`, {
|
|
1067
1085
|
headers: {
|
|
1068
1086
|
"Authorization": `Bearer ${token}`,
|
|
@@ -1078,7 +1096,7 @@ async function listAccountSessions(options = {}) {
|
|
|
1078
1096
|
const summaries = rows.filter((row) => typeof row?.id === "string").map((row) => summarizeAccountSession(row, persisted[row.id], liveIds, now)).filter((summary) => options.includeArchived || !summary.archived);
|
|
1079
1097
|
return orderAccountSessions(summaries, options);
|
|
1080
1098
|
}
|
|
1081
|
-
async function bearerToken() {
|
|
1099
|
+
async function bearerToken$1() {
|
|
1082
1100
|
const credentials = await readCredentialsForConfiguredRelay();
|
|
1083
1101
|
if (!credentials) throw new Error("CLI is not authenticated (no ~/.happy/access.key)");
|
|
1084
1102
|
return credentials.token;
|
|
@@ -1093,7 +1111,7 @@ function requirePersisted(sessionId) {
|
|
|
1093
1111
|
return persisted;
|
|
1094
1112
|
}
|
|
1095
1113
|
async function readSessionLog(sessionId, persisted, limit) {
|
|
1096
|
-
const token = await bearerToken();
|
|
1114
|
+
const token = await bearerToken$1();
|
|
1097
1115
|
const response = await axios.get(
|
|
1098
1116
|
`${configuration.serverUrl}/v3/sessions/${encodeURIComponent(sessionId)}/messages`,
|
|
1099
1117
|
{
|
|
@@ -1132,7 +1150,7 @@ async function readSessionTranscript(sessionId, limit, options = {}) {
|
|
|
1132
1150
|
};
|
|
1133
1151
|
}
|
|
1134
1152
|
async function readSessionMetadata(sessionId, persisted) {
|
|
1135
|
-
const token = await bearerToken();
|
|
1153
|
+
const token = await bearerToken$1();
|
|
1136
1154
|
const response = await axios.get(`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}`, {
|
|
1137
1155
|
headers: {
|
|
1138
1156
|
"Authorization": `Bearer ${token}`,
|
|
@@ -1145,7 +1163,7 @@ async function readSessionMetadata(sessionId, persisted) {
|
|
|
1145
1163
|
return decrypt(decodeBase64(persisted.encryptionKey), persisted.encryptionVariant, decodeBase64(ciphertext));
|
|
1146
1164
|
}
|
|
1147
1165
|
async function readSessionState(sessionId, persisted) {
|
|
1148
|
-
const token = await bearerToken();
|
|
1166
|
+
const token = await bearerToken$1();
|
|
1149
1167
|
const response = await axios.get(`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}`, {
|
|
1150
1168
|
headers: {
|
|
1151
1169
|
"Authorization": `Bearer ${token}`,
|
|
@@ -1197,7 +1215,7 @@ async function stopSession(sessionId) {
|
|
|
1197
1215
|
return await stopDaemonSession(sessionId);
|
|
1198
1216
|
}
|
|
1199
1217
|
async function archiveSession(sessionId) {
|
|
1200
|
-
const token = await bearerToken();
|
|
1218
|
+
const token = await bearerToken$1();
|
|
1201
1219
|
await axios.post(
|
|
1202
1220
|
`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}/archive`,
|
|
1203
1221
|
{},
|
|
@@ -1211,7 +1229,7 @@ async function archiveSession(sessionId) {
|
|
|
1211
1229
|
);
|
|
1212
1230
|
}
|
|
1213
1231
|
async function unarchiveSession(sessionId) {
|
|
1214
|
-
const token = await bearerToken();
|
|
1232
|
+
const token = await bearerToken$1();
|
|
1215
1233
|
await axios.post(
|
|
1216
1234
|
`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}/unarchive`,
|
|
1217
1235
|
{},
|
|
@@ -1247,7 +1265,7 @@ function explainNotLive(sessionId, status, resumeHint) {
|
|
|
1247
1265
|
}
|
|
1248
1266
|
}
|
|
1249
1267
|
const CLI_RESUME_HINT = "Use --resume to bring it back on this machine, or spawn a new session.";
|
|
1250
|
-
const defaultDeps = {
|
|
1268
|
+
const defaultDeps$1 = {
|
|
1251
1269
|
listLive: () => listDaemonSessions(),
|
|
1252
1270
|
readState: (sessionId, persisted) => readSessionState(sessionId, persisted),
|
|
1253
1271
|
send: (sessionId, persisted, text, client, options) => sendUserMessage(sessionId, persisted, text, client, options),
|
|
@@ -1258,7 +1276,7 @@ const defaultDeps = {
|
|
|
1258
1276
|
now: () => Date.now()
|
|
1259
1277
|
};
|
|
1260
1278
|
async function deliverToSession(sessionId, persisted, text, client, options = {}, deps = {}) {
|
|
1261
|
-
const d = { ...defaultDeps, ...deps };
|
|
1279
|
+
const d = { ...defaultDeps$1, ...deps };
|
|
1262
1280
|
const resumeHint = options.resumeHint ?? CLI_RESUME_HINT;
|
|
1263
1281
|
const classify = async () => {
|
|
1264
1282
|
const [live, server] = await Promise.all([d.listLive(), d.readState(sessionId, persisted)]);
|
|
@@ -1349,6 +1367,10 @@ async function waitUntilLive(classify, d, options) {
|
|
|
1349
1367
|
const SESSION_PEER_SENT_FROM = "session-peer";
|
|
1350
1368
|
const CLI_PEER_SENDER_ID = "cli";
|
|
1351
1369
|
const MESSAGE_FOOTER = "This message comes from another agent session on this machine, not from the user.";
|
|
1370
|
+
const MESSAGE_FOOTER_PREFIX = "This message comes from another agent session";
|
|
1371
|
+
function messageFooterFor(sender) {
|
|
1372
|
+
return sender.machine ? `${MESSAGE_FOOTER_PREFIX} on machine ${sanitizeHeaderValue(sender.machine, 128)}, not from the user.` : MESSAGE_FOOTER;
|
|
1373
|
+
}
|
|
1352
1374
|
function sanitizeHeaderValue(value, max = 200) {
|
|
1353
1375
|
if (!value) return "";
|
|
1354
1376
|
const collapsed = value.replace(/\s+/g, " ").trim().slice(0, max);
|
|
@@ -1358,6 +1380,7 @@ function senderFields(sender) {
|
|
|
1358
1380
|
const parts = [];
|
|
1359
1381
|
if (sender.flavor) parts.push(`agent ${sanitizeHeaderValue(sender.flavor, 32)}`);
|
|
1360
1382
|
if (sender.cwd) parts.push(`cwd ${sanitizeHeaderValue(sender.cwd, 400)}`);
|
|
1383
|
+
if (sender.machine) parts.push(`machine ${sanitizeHeaderValue(sender.machine, 128)}`);
|
|
1361
1384
|
return parts.map((part) => `; ${part}`).join("");
|
|
1362
1385
|
}
|
|
1363
1386
|
function quotedTitle(sender) {
|
|
@@ -1365,7 +1388,9 @@ function quotedTitle(sender) {
|
|
|
1365
1388
|
}
|
|
1366
1389
|
function formatSessionPeerMessage(input) {
|
|
1367
1390
|
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)}` : ""}]`;
|
|
1368
|
-
const
|
|
1391
|
+
const base = messageFooterFor(input.from);
|
|
1392
|
+
const routed = input.from.machine ? " (it is routed to that machine for you)" : "";
|
|
1393
|
+
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.`;
|
|
1369
1394
|
return `${header}
|
|
1370
1395
|
${input.body.trim()}
|
|
1371
1396
|
|
|
@@ -1427,7 +1452,7 @@ function resolveRepoIdentity(cwd, fs = realFs) {
|
|
|
1427
1452
|
}
|
|
1428
1453
|
return { root: null, common: null };
|
|
1429
1454
|
}
|
|
1430
|
-
const PEER_SCOPES = ["repo", "cwd", "machine"];
|
|
1455
|
+
const PEER_SCOPES$1 = ["repo", "cwd", "machine"];
|
|
1431
1456
|
function isPeerInScope(scope, self, other) {
|
|
1432
1457
|
if (scope === "machine") return true;
|
|
1433
1458
|
if (scope === "cwd") return resolve$1(self.cwd) === resolve$1(other.cwd);
|
|
@@ -1435,24 +1460,508 @@ function isPeerInScope(scope, self, other) {
|
|
|
1435
1460
|
return resolve$1(self.cwd) === resolve$1(other.cwd);
|
|
1436
1461
|
}
|
|
1437
1462
|
|
|
1463
|
+
const REMOTE_SESSION_OPS_MIN_CLI_VERSION = "0.2.157";
|
|
1464
|
+
const REMOTE_OPS_PROTOCOL_VERSION = 1;
|
|
1465
|
+
const REMOTE_TEXT_MAX_BYTES = 64 * 1024;
|
|
1466
|
+
const REMOTE_TRANSCRIPT_MAX_BYTES = 200 * 1024;
|
|
1467
|
+
const REMOTE_CALLS_PER_MINUTE = 60;
|
|
1468
|
+
const REMOTE_WRITE_CALLS_PER_MINUTE = 30;
|
|
1469
|
+
const REMOTE_LOCATE_MAX_IDS = 200;
|
|
1470
|
+
const REMOTE_OP_DEADLINE_MS = 25e3;
|
|
1471
|
+
const REMOTE_SEND_COMMIT_DEADLINE_MS = 18e3;
|
|
1472
|
+
const REMOTE_RESUME_WAIT_MS = 1e4;
|
|
1473
|
+
const REMOTE_WAIT_POLL_MS = 5e3;
|
|
1474
|
+
const REMOTE_ANSWER_MAX_BYTES = 64 * 1024;
|
|
1475
|
+
const REMOTE_TITLE_MAX_BYTES = 1024;
|
|
1476
|
+
const REMOTE_SENT_FROM_ALLOWED = ["cli", "assistant", "automation"];
|
|
1477
|
+
const LOCAL_ID_RE = /^[a-zA-Z0-9_.:-]{1,128}$/;
|
|
1478
|
+
function remoteError(code, message) {
|
|
1479
|
+
return { ok: false, error: { code, message } };
|
|
1480
|
+
}
|
|
1481
|
+
const SESSION_ID_RE = /^[a-zA-Z0-9_-]{1,128}$/;
|
|
1482
|
+
const PEER_SCOPES = ["repo", "cwd", "machine"];
|
|
1483
|
+
function isSessionId(value) {
|
|
1484
|
+
return typeof value === "string" && SESSION_ID_RE.test(value);
|
|
1485
|
+
}
|
|
1486
|
+
function utf8Bytes(text) {
|
|
1487
|
+
return Buffer.byteLength(text, "utf8");
|
|
1488
|
+
}
|
|
1489
|
+
function sanitizeSender(raw) {
|
|
1490
|
+
if (!raw || typeof raw !== "object") return null;
|
|
1491
|
+
const r = raw;
|
|
1492
|
+
if (typeof r.sessionId !== "string" || r.sessionId.length === 0 || r.sessionId.length > 128) return null;
|
|
1493
|
+
const optional = (key, max) => typeof r[key] === "string" && r[key].length > 0 ? { [key]: r[key].slice(0, max) } : {};
|
|
1494
|
+
return {
|
|
1495
|
+
sessionId: r.sessionId,
|
|
1496
|
+
...optional("title", 200),
|
|
1497
|
+
...optional("flavor", 32),
|
|
1498
|
+
...optional("cwd", 1024),
|
|
1499
|
+
...optional("machine", 128)
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
function guardRemoteSessionOpsRequest(method, raw, options) {
|
|
1503
|
+
if (!options.enabled) {
|
|
1504
|
+
return remoteError("disabled", 'Remote session operations are turned off on this machine (settings.json remoteSessionOps = "off")');
|
|
1505
|
+
}
|
|
1506
|
+
if (!raw || typeof raw !== "object") return remoteError("bad_request", "Request must be an object");
|
|
1507
|
+
const r = raw;
|
|
1508
|
+
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})`);
|
|
1509
|
+
const from = r.from;
|
|
1510
|
+
if (!from || typeof from !== "object" || typeof from.host !== "string" || from.host.length === 0 || typeof from.cli !== "string") {
|
|
1511
|
+
return remoteError("bad_request", "from.host and from.cli are required");
|
|
1512
|
+
}
|
|
1513
|
+
const caller = {
|
|
1514
|
+
host: from.host.slice(0, 128),
|
|
1515
|
+
cli: from.cli.slice(0, 32),
|
|
1516
|
+
...typeof from.machineId === "string" && from.machineId.length > 0 ? { machineId: from.machineId.slice(0, 128) } : {},
|
|
1517
|
+
...isSessionId(from.sessionId) ? { sessionId: from.sessionId } : {}
|
|
1518
|
+
};
|
|
1519
|
+
const args = r.args && typeof r.args === "object" ? r.args : {};
|
|
1520
|
+
const limit = typeof args.limit === "number" && Number.isFinite(args.limit) && args.limit >= 1 ? Math.floor(args.limit) : void 0;
|
|
1521
|
+
let clean;
|
|
1522
|
+
switch (method) {
|
|
1523
|
+
case "sessions.list": {
|
|
1524
|
+
if (args.ids !== void 0) {
|
|
1525
|
+
if (!Array.isArray(args.ids) || !args.ids.every(isSessionId)) return remoteError("bad_request", "ids must be an array of session ids");
|
|
1526
|
+
if (args.ids.length > REMOTE_LOCATE_MAX_IDS) return remoteError("too_large", `ids: at most ${REMOTE_LOCATE_MAX_IDS} per call`);
|
|
1527
|
+
}
|
|
1528
|
+
const out = {
|
|
1529
|
+
...args.ids !== void 0 ? { ids: args.ids } : {},
|
|
1530
|
+
...args.all === true ? { all: true } : {},
|
|
1531
|
+
...typeof args.tag === "string" && args.tag.length > 0 ? { tag: args.tag.slice(0, 128) } : {},
|
|
1532
|
+
...limit !== void 0 ? { limit } : {}
|
|
1533
|
+
};
|
|
1534
|
+
clean = out;
|
|
1535
|
+
break;
|
|
1536
|
+
}
|
|
1537
|
+
case "sessions.read": {
|
|
1538
|
+
if (!isSessionId(args.sessionId)) return remoteError("bad_request", "sessionId is required");
|
|
1539
|
+
const out = { sessionId: args.sessionId, ...limit !== void 0 ? { limit } : {}, ...args.full === true ? { full: true } : {} };
|
|
1540
|
+
clean = out;
|
|
1541
|
+
break;
|
|
1542
|
+
}
|
|
1543
|
+
case "sessions.send": {
|
|
1544
|
+
if (!isSessionId(args.sessionId)) return remoteError("bad_request", "sessionId is required");
|
|
1545
|
+
if (typeof args.text !== "string" || args.text.trim().length === 0) return remoteError("bad_request", "text must be non-empty");
|
|
1546
|
+
if (utf8Bytes(args.text) > REMOTE_TEXT_MAX_BYTES) return remoteError("too_large", `text exceeds ${REMOTE_TEXT_MAX_BYTES} bytes`);
|
|
1547
|
+
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");
|
|
1548
|
+
const out = {
|
|
1549
|
+
sessionId: args.sessionId,
|
|
1550
|
+
text: args.text,
|
|
1551
|
+
...args.resume === true ? { resume: true } : {},
|
|
1552
|
+
...args.model === null || typeof args.model === "string" && args.model.length <= 128 ? { model: args.model } : {},
|
|
1553
|
+
...REMOTE_SENT_FROM_ALLOWED.includes(args.sentFrom) ? { sentFrom: args.sentFrom } : {},
|
|
1554
|
+
...typeof args.localId === "string" ? { localId: args.localId } : {}
|
|
1555
|
+
};
|
|
1556
|
+
clean = out;
|
|
1557
|
+
break;
|
|
1558
|
+
}
|
|
1559
|
+
case "sessions.peers": {
|
|
1560
|
+
if (args.scope !== void 0 && !PEER_SCOPES.includes(args.scope)) return remoteError("bad_request", `scope must be one of ${PEER_SCOPES.join(", ")}`);
|
|
1561
|
+
const out = {
|
|
1562
|
+
...args.scope !== void 0 ? { scope: args.scope } : {},
|
|
1563
|
+
...typeof args.cwd === "string" && args.cwd.length > 0 ? { cwd: args.cwd.slice(0, 4096) } : {}
|
|
1564
|
+
};
|
|
1565
|
+
clean = out;
|
|
1566
|
+
break;
|
|
1567
|
+
}
|
|
1568
|
+
case "sessions.message": {
|
|
1569
|
+
if (!isSessionId(args.to)) return remoteError("bad_request", "to is required");
|
|
1570
|
+
if (typeof args.body !== "string" || args.body.trim().length === 0) return remoteError("bad_request", "body must be non-empty");
|
|
1571
|
+
if (utf8Bytes(args.body) > REMOTE_TEXT_MAX_BYTES) return remoteError("too_large", `body exceeds ${REMOTE_TEXT_MAX_BYTES} bytes`);
|
|
1572
|
+
const sender = sanitizeSender(args.from);
|
|
1573
|
+
if (!sender) return remoteError("bad_request", "from.sessionId (the sender) is required");
|
|
1574
|
+
const out = {
|
|
1575
|
+
to: args.to,
|
|
1576
|
+
body: args.body,
|
|
1577
|
+
...typeof args.replyTo === "string" && args.replyTo.length > 0 ? { replyTo: args.replyTo.slice(0, 64) } : {},
|
|
1578
|
+
// The recipient's header names the machine the call came
|
|
1579
|
+
// from, as the caller identified itself — never a value the
|
|
1580
|
+
// sender picked for someone else.
|
|
1581
|
+
from: { ...sender, machine: caller.host }
|
|
1582
|
+
};
|
|
1583
|
+
clean = out;
|
|
1584
|
+
break;
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
return { ok: true, request: { v: REMOTE_OPS_PROTOCOL_VERSION, from: caller, args: clean } };
|
|
1588
|
+
}
|
|
1589
|
+
class RemoteCallBudget {
|
|
1590
|
+
constructor(perMinute = REMOTE_CALLS_PER_MINUTE, now = Date.now) {
|
|
1591
|
+
this.perMinute = perMinute;
|
|
1592
|
+
this.now = now;
|
|
1593
|
+
this.tokens = perMinute;
|
|
1594
|
+
this.lastRefill = now();
|
|
1595
|
+
}
|
|
1596
|
+
tokens;
|
|
1597
|
+
lastRefill;
|
|
1598
|
+
/** Take one token; false = over budget (with ms until the next token). */
|
|
1599
|
+
take() {
|
|
1600
|
+
if (this.perMinute <= 0) return { ok: true };
|
|
1601
|
+
const t = this.now();
|
|
1602
|
+
const refill = (t - this.lastRefill) / 6e4 * this.perMinute;
|
|
1603
|
+
if (refill > 0) {
|
|
1604
|
+
this.tokens = Math.min(this.perMinute, this.tokens + refill);
|
|
1605
|
+
this.lastRefill = t;
|
|
1606
|
+
}
|
|
1607
|
+
if (this.tokens >= 1) {
|
|
1608
|
+
this.tokens -= 1;
|
|
1609
|
+
return { ok: true };
|
|
1610
|
+
}
|
|
1611
|
+
return { ok: false, retryAfterMs: Math.ceil((1 - this.tokens) / this.perMinute * 6e4) };
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
function sanitizeAuditValue(value, max = 64) {
|
|
1615
|
+
if (typeof value !== "string" || value.length === 0) return "?";
|
|
1616
|
+
return value.slice(0, max).replace(/[^\x20-\x7e]/g, "?");
|
|
1617
|
+
}
|
|
1618
|
+
function formatRemoteAuditLine(input) {
|
|
1619
|
+
const from = input.from;
|
|
1620
|
+
const opt = (value) => value === void 0 ? "-" : sanitizeAuditValue(value);
|
|
1621
|
+
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)`;
|
|
1622
|
+
}
|
|
1623
|
+
function capRemoteText(text, maxBytes, keep = "head") {
|
|
1624
|
+
if (utf8Bytes(text) <= maxBytes) return text;
|
|
1625
|
+
const buffer = Buffer.from(text, "utf8");
|
|
1626
|
+
const marker = "\u2026";
|
|
1627
|
+
const room = Math.max(0, maxBytes - Buffer.byteLength(marker));
|
|
1628
|
+
const slice = keep === "head" ? buffer.subarray(0, room) : buffer.subarray(buffer.length - room);
|
|
1629
|
+
const clean = slice.toString("utf8").replace(/^�+|�+$/g, "");
|
|
1630
|
+
return keep === "head" ? clean + marker : marker + clean;
|
|
1631
|
+
}
|
|
1632
|
+
function capRemoteTranscript(transcript, maxBytes = REMOTE_TRANSCRIPT_MAX_BYTES) {
|
|
1633
|
+
if (utf8Bytes(transcript) <= maxBytes) return { transcript, truncated: false };
|
|
1634
|
+
const buffer = Buffer.from(transcript, "utf8");
|
|
1635
|
+
const marker = "\u2026 [truncated by the remote machine: transcript exceeded the RPC budget; use --limit] \u2026\n";
|
|
1636
|
+
const tail = buffer.subarray(buffer.length - (maxBytes - Buffer.byteLength(marker))).toString("utf8");
|
|
1637
|
+
return { transcript: marker + tail.replace(/^�+/, ""), truncated: true };
|
|
1638
|
+
}
|
|
1639
|
+
function parseHappyClientVersion(value) {
|
|
1640
|
+
if (typeof value !== "string") return null;
|
|
1641
|
+
const match = value.match(/(\d+)\.(\d+)\.(\d+)/);
|
|
1642
|
+
return match ? `${match[1]}.${match[2]}.${match[3]}` : null;
|
|
1643
|
+
}
|
|
1644
|
+
function compareVersions(a, b) {
|
|
1645
|
+
const pa = a.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
1646
|
+
const pb = b.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
1647
|
+
for (let i = 0; i < 3; i++) {
|
|
1648
|
+
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
1649
|
+
if (d !== 0) return d;
|
|
1650
|
+
}
|
|
1651
|
+
return 0;
|
|
1652
|
+
}
|
|
1653
|
+
function supportsRemoteSessionOps(cliVersion) {
|
|
1654
|
+
if (!cliVersion) return null;
|
|
1655
|
+
return compareVersions(cliVersion, REMOTE_SESSION_OPS_MIN_CLI_VERSION) >= 0;
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
const REMOTE_CLIENT_TAG = "session-ops";
|
|
1659
|
+
const REMOTE_RPC_TIMEOUT_MS = 3e4;
|
|
1660
|
+
const REMOTE_LOCATE_MAX_MACHINES = 8;
|
|
1661
|
+
class RemoteSessionOpsError extends Error {
|
|
1662
|
+
constructor(code, message, machineId, ambiguous = false) {
|
|
1663
|
+
super(message);
|
|
1664
|
+
this.code = code;
|
|
1665
|
+
this.machineId = machineId;
|
|
1666
|
+
this.ambiguous = ambiguous;
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
async function bearerToken() {
|
|
1670
|
+
const credentials = await readCredentialsForConfiguredRelay();
|
|
1671
|
+
if (!credentials) throw new Error("CLI is not authenticated (no ~/.happy/access.key)");
|
|
1672
|
+
return credentials.token;
|
|
1673
|
+
}
|
|
1674
|
+
async function listAccountMachines() {
|
|
1675
|
+
const token = await bearerToken();
|
|
1676
|
+
const response = await axios.get(`${configuration.serverUrl}/v1/machines`, {
|
|
1677
|
+
headers: { "Authorization": `Bearer ${token}`, "X-Happy-Client": `${REMOTE_CLIENT_TAG}/${configuration.currentCliVersion}` },
|
|
1678
|
+
timeout: 15e3
|
|
1679
|
+
});
|
|
1680
|
+
const rows = Array.isArray(response.data) ? response.data : [];
|
|
1681
|
+
return rows.filter((row) => !!row && typeof row === "object" && typeof row.id === "string").map((row) => ({
|
|
1682
|
+
id: row.id,
|
|
1683
|
+
active: row.active === true,
|
|
1684
|
+
...typeof row.activeAt === "number" ? { activeAt: row.activeAt } : {},
|
|
1685
|
+
cliVersion: parseHappyClientVersion(row.lastHappyClient)
|
|
1686
|
+
}));
|
|
1687
|
+
}
|
|
1688
|
+
async function callerIdentity(env = process.env) {
|
|
1689
|
+
const settings = await readSettings().catch(() => null);
|
|
1690
|
+
const sessionId = env.VH_PEER_SESSION_ID;
|
|
1691
|
+
return {
|
|
1692
|
+
...settings?.machineId ? { machineId: settings.machineId } : {},
|
|
1693
|
+
host: hostname(),
|
|
1694
|
+
cli: configuration.currentCliVersion,
|
|
1695
|
+
...sessionId && /^[a-zA-Z0-9_-]{1,128}$/.test(sessionId) ? { sessionId } : {}
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
const defaultDeps = {
|
|
1699
|
+
listMachines: listAccountMachines,
|
|
1700
|
+
selfMachineId: async () => (await readSettings().catch(() => null))?.machineId,
|
|
1701
|
+
openTransport: async () => {
|
|
1702
|
+
const socket = await openUserScopedSocket(await bearerToken());
|
|
1703
|
+
return {
|
|
1704
|
+
call: (method, paramsJson) => socket.rpcCall({ method, params: paramsJson }, REMOTE_RPC_TIMEOUT_MS),
|
|
1705
|
+
close: () => socket.close()
|
|
1706
|
+
};
|
|
1707
|
+
},
|
|
1708
|
+
caller: () => callerIdentity(),
|
|
1709
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
1710
|
+
now: () => Date.now()
|
|
1711
|
+
};
|
|
1712
|
+
function withDefaults(deps) {
|
|
1713
|
+
return { ...defaultDeps, ...deps };
|
|
1714
|
+
}
|
|
1715
|
+
function pickRemoteCandidates(machines, selfId) {
|
|
1716
|
+
const candidates = [];
|
|
1717
|
+
const skipped = [];
|
|
1718
|
+
for (const machine of machines) {
|
|
1719
|
+
if (selfId && machine.id === selfId) {
|
|
1720
|
+
skipped.push({ machine, reason: "self" });
|
|
1721
|
+
continue;
|
|
1722
|
+
}
|
|
1723
|
+
if (!machine.active) {
|
|
1724
|
+
skipped.push({ machine, reason: "offline" });
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
if (supportsRemoteSessionOps(machine.cliVersion) === false) {
|
|
1728
|
+
skipped.push({ machine, reason: "too_old" });
|
|
1729
|
+
continue;
|
|
1730
|
+
}
|
|
1731
|
+
candidates.push(machine);
|
|
1732
|
+
}
|
|
1733
|
+
candidates.sort((a, b) => (b.activeAt ?? 0) - (a.activeAt ?? 0));
|
|
1734
|
+
return { candidates: candidates.slice(0, REMOTE_LOCATE_MAX_MACHINES), skipped };
|
|
1735
|
+
}
|
|
1736
|
+
function describeAge(activeAt, now) {
|
|
1737
|
+
if (activeAt === void 0) return "never seen";
|
|
1738
|
+
const minutes = Math.round((now - activeAt) / 6e4);
|
|
1739
|
+
if (minutes < 2) return "seen just now";
|
|
1740
|
+
if (minutes < 120) return `last seen ${minutes}m ago`;
|
|
1741
|
+
if (minutes < 48 * 60) return `last seen ${Math.round(minutes / 60)}h ago`;
|
|
1742
|
+
return `last seen ${Math.round(minutes / 1440)}d ago`;
|
|
1743
|
+
}
|
|
1744
|
+
async function resolveExplicitMachine(machineId, deps) {
|
|
1745
|
+
const machines = await deps.listMachines();
|
|
1746
|
+
const machine = machines.find((row) => row.id === machineId);
|
|
1747
|
+
if (!machine) throw new RemoteSessionOpsError("unknown_machine", `Machine ${machineId} is not on this account`, machineId);
|
|
1748
|
+
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);
|
|
1749
|
+
if (supportsRemoteSessionOps(machine.cliVersion) === false) {
|
|
1750
|
+
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);
|
|
1751
|
+
}
|
|
1752
|
+
return machine;
|
|
1753
|
+
}
|
|
1754
|
+
async function callRemoteSessionOp(transport, machineId, method, args, from) {
|
|
1755
|
+
const params = JSON.stringify({ v: REMOTE_OPS_PROTOCOL_VERSION, from, args });
|
|
1756
|
+
let ack;
|
|
1757
|
+
try {
|
|
1758
|
+
ack = await transport.call(`${machineId}:${method}`, params);
|
|
1759
|
+
} catch (error) {
|
|
1760
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
1761
|
+
throw new RemoteSessionOpsError("unreachable", `Machine ${machineId} did not answer ${method} (${reason})`, machineId, true);
|
|
1762
|
+
}
|
|
1763
|
+
if (!ack?.ok) {
|
|
1764
|
+
const reason = ack?.error ?? "no ack";
|
|
1765
|
+
if (/not available/i.test(reason)) {
|
|
1766
|
+
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);
|
|
1767
|
+
}
|
|
1768
|
+
throw new RemoteSessionOpsError("unreachable", `Machine ${machineId}: ${reason}`, machineId, true);
|
|
1769
|
+
}
|
|
1770
|
+
let envelope;
|
|
1771
|
+
try {
|
|
1772
|
+
envelope = typeof ack.result === "string" ? JSON.parse(ack.result) : ack.result;
|
|
1773
|
+
} catch {
|
|
1774
|
+
throw new RemoteSessionOpsError("unreachable", `Machine ${machineId} returned an unreadable ${method} response`, machineId);
|
|
1775
|
+
}
|
|
1776
|
+
if (!envelope || typeof envelope !== "object") throw new RemoteSessionOpsError("unreachable", `Machine ${machineId} returned an empty ${method} response`, machineId);
|
|
1777
|
+
if ("ok" in envelope) {
|
|
1778
|
+
if (envelope.ok) return envelope.result;
|
|
1779
|
+
throw new RemoteSessionOpsError(envelope.error.code, `Machine ${machineId}: ${envelope.error.message}`, machineId);
|
|
1780
|
+
}
|
|
1781
|
+
throw new RemoteSessionOpsError("internal", `Machine ${machineId}: ${envelope.error ?? "remote handler failed"}`, machineId);
|
|
1782
|
+
}
|
|
1783
|
+
async function locateRemoteSession(transport, sessionId, options, deps) {
|
|
1784
|
+
const from = await deps.caller();
|
|
1785
|
+
if (options.machineId) {
|
|
1786
|
+
const machine = await resolveExplicitMachine(options.machineId, deps);
|
|
1787
|
+
const listing = await callRemoteSessionOp(transport, machine.id, "sessions.list", { ids: [sessionId] }, from);
|
|
1788
|
+
if (!listing.sessions.some((row) => row.id === sessionId)) {
|
|
1789
|
+
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);
|
|
1790
|
+
}
|
|
1791
|
+
return { machine, host: listing.host };
|
|
1792
|
+
}
|
|
1793
|
+
const { candidates, skipped } = pickRemoteCandidates(await deps.listMachines(), await deps.selfMachineId());
|
|
1794
|
+
const failures = [];
|
|
1795
|
+
for (const machine of candidates) {
|
|
1796
|
+
try {
|
|
1797
|
+
const listing = await callRemoteSessionOp(transport, machine.id, "sessions.list", { ids: [sessionId] }, from);
|
|
1798
|
+
if (listing.sessions.some((row) => row.id === sessionId)) return { machine, host: listing.host };
|
|
1799
|
+
failures.push(`${listing.host || machine.id}: not there`);
|
|
1800
|
+
} catch (error) {
|
|
1801
|
+
failures.push(`${machine.id}: ${error instanceof RemoteSessionOpsError ? error.code : error instanceof Error ? error.message : String(error)}`);
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
const skippedText = skipped.filter((s) => s.reason !== "self").map((s) => `${s.machine.id}: ${s.reason}`);
|
|
1805
|
+
const detail = [...failures, ...skippedText];
|
|
1806
|
+
throw new RemoteSessionOpsError(
|
|
1807
|
+
"not_located",
|
|
1808
|
+
`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.`
|
|
1809
|
+
);
|
|
1810
|
+
}
|
|
1811
|
+
async function withRemoteTransport(deps, fn) {
|
|
1812
|
+
const transport = await deps.openTransport();
|
|
1813
|
+
try {
|
|
1814
|
+
return await fn(transport);
|
|
1815
|
+
} finally {
|
|
1816
|
+
try {
|
|
1817
|
+
transport.close();
|
|
1818
|
+
} catch {
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
async function readRemoteTranscript(sessionId, options = {}, overrides = {}) {
|
|
1823
|
+
const deps = withDefaults(overrides);
|
|
1824
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1825
|
+
const located = await locateRemoteSession(transport, sessionId, { machineId: options.machineId }, deps);
|
|
1826
|
+
return callRemoteSessionOp(transport, located.machine.id, "sessions.read", {
|
|
1827
|
+
sessionId,
|
|
1828
|
+
...options.limit !== void 0 ? { limit: options.limit } : {},
|
|
1829
|
+
...options.full ? { full: true } : {}
|
|
1830
|
+
}, await deps.caller());
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
async function waitForRemoteTurnEnd(sessionId, options, overrides = {}) {
|
|
1834
|
+
const deps = withDefaults(overrides);
|
|
1835
|
+
const pollMs = options.pollMs ?? REMOTE_WAIT_POLL_MS;
|
|
1836
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1837
|
+
const located = await locateRemoteSession(transport, sessionId, { machineId: options.machineId }, deps);
|
|
1838
|
+
const from = await deps.caller();
|
|
1839
|
+
const deadline = deps.now() + options.timeoutMs;
|
|
1840
|
+
const args = { sessionId, ...options.limit !== void 0 ? { limit: options.limit } : {}, ...options.full ? { full: true } : {} };
|
|
1841
|
+
while (true) {
|
|
1842
|
+
const read = await callRemoteSessionOp(transport, located.machine.id, "sessions.read", args, from);
|
|
1843
|
+
if (read.turn.ended) return { read, timedOut: false };
|
|
1844
|
+
if (deps.now() + pollMs > deadline) return { read, timedOut: true };
|
|
1845
|
+
await deps.sleep(pollMs);
|
|
1846
|
+
}
|
|
1847
|
+
});
|
|
1848
|
+
}
|
|
1849
|
+
async function sendRemoteMessage(sessionId, text, options = {}, overrides = {}) {
|
|
1850
|
+
const deps = withDefaults(overrides);
|
|
1851
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1852
|
+
const located = await locateRemoteSession(transport, sessionId, { machineId: options.machineId }, deps);
|
|
1853
|
+
const from = await deps.caller();
|
|
1854
|
+
const localId = options.localId ?? `remote-send-${randomUUID()}`;
|
|
1855
|
+
const args = {
|
|
1856
|
+
sessionId,
|
|
1857
|
+
text,
|
|
1858
|
+
localId,
|
|
1859
|
+
...options.resume ? { resume: true } : {},
|
|
1860
|
+
...options.model !== void 0 ? { model: options.model } : {},
|
|
1861
|
+
...options.sentFrom !== void 0 ? { sentFrom: options.sentFrom } : {}
|
|
1862
|
+
};
|
|
1863
|
+
const attempt = () => callRemoteSessionOp(transport, located.machine.id, "sessions.send", args, from);
|
|
1864
|
+
let result;
|
|
1865
|
+
try {
|
|
1866
|
+
result = await attempt();
|
|
1867
|
+
} catch (error) {
|
|
1868
|
+
const retryable = error instanceof RemoteSessionOpsError && (error.ambiguous || error.code === "timeout");
|
|
1869
|
+
if (!retryable) throw error;
|
|
1870
|
+
result = await attempt();
|
|
1871
|
+
}
|
|
1872
|
+
return { ...result, machine: { id: located.machine.id, host: located.host } };
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
async function sendRemotePeerMessage(args, options = {}, overrides = {}) {
|
|
1876
|
+
const deps = withDefaults(overrides);
|
|
1877
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1878
|
+
const located = await locateRemoteSession(transport, args.to, { machineId: options.machineId }, deps);
|
|
1879
|
+
const caller = await deps.caller();
|
|
1880
|
+
const result = await callRemoteSessionOp(transport, located.machine.id, "sessions.message", {
|
|
1881
|
+
to: args.to,
|
|
1882
|
+
body: args.body,
|
|
1883
|
+
...args.replyTo ? { replyTo: args.replyTo } : {},
|
|
1884
|
+
from: { ...args.from, machine: args.from.machine ?? caller.host }
|
|
1885
|
+
}, caller);
|
|
1886
|
+
return { ...result, machine: { id: located.machine.id, host: located.host } };
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
async function listRemotePeers(machineId, options = {}, overrides = {}) {
|
|
1890
|
+
const deps = withDefaults(overrides);
|
|
1891
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1892
|
+
const machine = await resolveExplicitMachine(machineId, deps);
|
|
1893
|
+
return callRemoteSessionOp(transport, machine.id, "sessions.peers", {
|
|
1894
|
+
...options.scope ? { scope: options.scope } : {},
|
|
1895
|
+
...options.cwd ? { cwd: options.cwd } : {}
|
|
1896
|
+
}, await deps.caller());
|
|
1897
|
+
});
|
|
1898
|
+
}
|
|
1899
|
+
async function listRemoteSessions(machineId, options = {}, overrides = {}) {
|
|
1900
|
+
const deps = withDefaults(overrides);
|
|
1901
|
+
return withRemoteTransport(deps, async (transport) => {
|
|
1902
|
+
const machine = await resolveExplicitMachine(machineId, deps);
|
|
1903
|
+
return callRemoteSessionOp(transport, machine.id, "sessions.list", {
|
|
1904
|
+
...options.tag ? { tag: options.tag } : {},
|
|
1905
|
+
...options.limit !== void 0 ? { limit: options.limit } : {}
|
|
1906
|
+
}, await deps.caller());
|
|
1907
|
+
});
|
|
1908
|
+
}
|
|
1909
|
+
async function fillForeignAccountRows(rows, overrides = {}) {
|
|
1910
|
+
const deps = withDefaults(overrides);
|
|
1911
|
+
const pending = new Set(rows.filter((row) => !row.decryptable).map((row) => row.id));
|
|
1912
|
+
const asked = [];
|
|
1913
|
+
if (pending.size === 0) return { rows, asked, skipped: [] };
|
|
1914
|
+
const { candidates, skipped } = pickRemoteCandidates(await deps.listMachines(), await deps.selfMachineId());
|
|
1915
|
+
const filled = /* @__PURE__ */ new Map();
|
|
1916
|
+
if (candidates.length > 0) {
|
|
1917
|
+
await withRemoteTransport(deps, async (transport) => {
|
|
1918
|
+
const from = await deps.caller();
|
|
1919
|
+
for (const machine of candidates) {
|
|
1920
|
+
if (pending.size === 0) break;
|
|
1921
|
+
try {
|
|
1922
|
+
const listing = await callRemoteSessionOp(transport, machine.id, "sessions.list", { ids: [...pending], all: true }, from);
|
|
1923
|
+
let count = 0;
|
|
1924
|
+
for (const row of listing.sessions) {
|
|
1925
|
+
if (!pending.has(row.id)) continue;
|
|
1926
|
+
pending.delete(row.id);
|
|
1927
|
+
count++;
|
|
1928
|
+
filled.set(row.id, { ...row, decryptable: false, readable: true, via: machine.id, machine: { id: machine.id, host: listing.host } });
|
|
1929
|
+
}
|
|
1930
|
+
asked.push({ machineId: machine.id, host: listing.host, filled: count });
|
|
1931
|
+
} catch (error) {
|
|
1932
|
+
asked.push({ machineId: machine.id, filled: 0, error: error instanceof Error ? error.message : String(error) });
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
});
|
|
1936
|
+
}
|
|
1937
|
+
return {
|
|
1938
|
+
rows: rows.map((row) => filled.get(row.id) ?? row),
|
|
1939
|
+
asked,
|
|
1940
|
+
skipped: skipped.filter((s) => s.reason !== "self").map((s) => ({ machineId: s.machine.id, reason: s.reason }))
|
|
1941
|
+
};
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1438
1944
|
const SESSION_PEER_TOOL_NAMES = ["session_message", "session_peers"];
|
|
1439
1945
|
const SESSION_PEER_TOOL_SCHEMAS = {
|
|
1440
1946
|
session_message: {
|
|
1441
1947
|
title: "Message Another Session",
|
|
1442
1948
|
readOnly: false,
|
|
1443
|
-
description: "Send a message to another agent session
|
|
1949
|
+
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.",
|
|
1444
1950
|
inputSchema: {
|
|
1445
1951
|
to: z.string().min(1).max(128).describe("Target session id (from session_peers, or a peer's message header)"),
|
|
1446
1952
|
body: z.string().min(1).max(16e3).describe("The message text"),
|
|
1447
|
-
replyTo: z.string().min(1).max(64).optional().describe("Id of the peer message you are answering (from its header), if any")
|
|
1953
|
+
replyTo: z.string().min(1).max(64).optional().describe("Id of the peer message you are answering (from its header), if any"),
|
|
1954
|
+
machineId: 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)")
|
|
1448
1955
|
}
|
|
1449
1956
|
},
|
|
1450
1957
|
session_peers: {
|
|
1451
1958
|
title: "List Peer Sessions",
|
|
1452
1959
|
readOnly: true,
|
|
1453
|
-
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.',
|
|
1960
|
+
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).',
|
|
1454
1961
|
inputSchema: {
|
|
1455
|
-
scope: z.enum(["repo", "cwd", "machine"]).optional().describe("repo (default) | cwd | machine")
|
|
1962
|
+
scope: z.enum(["repo", "cwd", "machine"]).optional().describe("repo (default) | cwd | machine"),
|
|
1963
|
+
machineId: 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"),
|
|
1964
|
+
cwd: z.string().min(1).max(4096).optional().describe("With machineId: a directory on that machine to compute repo/cwd scope from")
|
|
1456
1965
|
}
|
|
1457
1966
|
}
|
|
1458
1967
|
};
|
|
@@ -1493,19 +2002,27 @@ async function sendPeerMessage(context, args) {
|
|
|
1493
2002
|
if (args.to === self.sessionId) throw new Error("That is this session; message a peer instead");
|
|
1494
2003
|
const body = typeof args.body === "string" ? args.body.trim() : "";
|
|
1495
2004
|
if (!body) throw new Error("body must be non-empty");
|
|
2005
|
+
const now = (context.now ?? Date.now)();
|
|
1496
2006
|
const persisted = (context.readPersisted ?? readPersistedSessions)()[args.to];
|
|
1497
|
-
if (!persisted) {
|
|
1498
|
-
|
|
2007
|
+
if (!persisted || args.machineId) {
|
|
2008
|
+
const remote = context.remoteMessage === void 0 ? sendRemotePeerMessage : context.remoteMessage;
|
|
2009
|
+
if (remote === null) {
|
|
2010
|
+
throw new Error(`Session ${args.to} is not on this machine (no local key)`);
|
|
2011
|
+
}
|
|
2012
|
+
if (context.sentTo) {
|
|
2013
|
+
const budget = checkPeerSendBudget(context.sentTo, args.to, now);
|
|
2014
|
+
if (!budget.ok) throw new Error(replyLoopRefusal(budget.count, args.to));
|
|
2015
|
+
}
|
|
2016
|
+
const result2 = await remote({ to: args.to, body, replyTo: args.replyTo, from: self, machineId: args.machineId });
|
|
2017
|
+
context.sentTo?.get(args.to)?.push(now);
|
|
2018
|
+
return result2;
|
|
1499
2019
|
}
|
|
1500
2020
|
const live = (await (context.listPeers ?? listDaemonPeers)()).find((session) => session.sessionId === args.to);
|
|
1501
2021
|
if (!live) throw new Error(`Session ${args.to} is not running on this machine; nothing would read the message`);
|
|
1502
2022
|
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`);
|
|
1503
|
-
const now = (context.now ?? Date.now)();
|
|
1504
2023
|
if (context.sentTo) {
|
|
1505
2024
|
const budget = checkPeerSendBudget(context.sentTo, args.to, now);
|
|
1506
|
-
if (!budget.ok)
|
|
1507
|
-
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.`);
|
|
1508
|
-
}
|
|
2025
|
+
if (!budget.ok) throw new Error(replyLoopRefusal(budget.count, args.to));
|
|
1509
2026
|
}
|
|
1510
2027
|
const messageId = randomUUID().slice(0, 8);
|
|
1511
2028
|
const text = formatSessionPeerMessage({ id: messageId, from: self, body, replyTo: args.replyTo });
|
|
@@ -1521,13 +2038,27 @@ async function sendPeerMessage(context, args) {
|
|
|
1521
2038
|
...result.error ? { error: result.error } : {}
|
|
1522
2039
|
};
|
|
1523
2040
|
}
|
|
2041
|
+
function replyLoopRefusal(count, to) {
|
|
2042
|
+
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.`;
|
|
2043
|
+
}
|
|
1524
2044
|
async function executeSessionPeerTool(name, args, context) {
|
|
1525
2045
|
switch (name) {
|
|
1526
2046
|
case "session_message":
|
|
1527
|
-
return sendPeerMessage(context, {
|
|
2047
|
+
return sendPeerMessage(context, {
|
|
2048
|
+
to: String(args?.to ?? ""),
|
|
2049
|
+
body: String(args?.body ?? ""),
|
|
2050
|
+
...args?.replyTo ? { replyTo: String(args.replyTo) } : {},
|
|
2051
|
+
...args?.machineId ? { machineId: String(args.machineId) } : {}
|
|
2052
|
+
});
|
|
1528
2053
|
case "session_peers": {
|
|
1529
2054
|
const scope = args?.scope;
|
|
1530
|
-
if (scope !== void 0 && !PEER_SCOPES.includes(scope)) throw new Error(`scope must be one of ${PEER_SCOPES.join(", ")}`);
|
|
2055
|
+
if (scope !== void 0 && !PEER_SCOPES$1.includes(scope)) throw new Error(`scope must be one of ${PEER_SCOPES$1.join(", ")}`);
|
|
2056
|
+
if (args?.machineId) {
|
|
2057
|
+
return (context.remotePeers ?? listRemotePeers)(String(args.machineId), {
|
|
2058
|
+
...scope !== void 0 ? { scope } : {},
|
|
2059
|
+
...typeof args.cwd === "string" && args.cwd ? { cwd: args.cwd } : {}
|
|
2060
|
+
});
|
|
2061
|
+
}
|
|
1531
2062
|
return listPeerSessions(context, scope ?? "repo");
|
|
1532
2063
|
}
|
|
1533
2064
|
}
|
|
@@ -1610,4 +2141,4 @@ const REPORT_PROGRESS_TOOL_NAME = "report_progress";
|
|
|
1610
2141
|
const REPORT_PROGRESS_TOOL_TITLE = "Report Progress to the Task Board";
|
|
1611
2142
|
const REPORT_PROGRESS_TOOL_DESCRIPTION = `Report what you are doing to the user's task board, so they can see the state of this session at a glance without reading the transcript. Call it at meaningful milestones only: when you start substantive work, when you get blocked and need the user, when something is ready for their review, and when you are done. Do NOT call it after every tool call or every file edit \u2014 it is a status line, not a log. Set attention to "blocked" when you cannot proceed without the user, "review" when you want them to look at something, and "none" for ordinary progress. Keep progress to one short line describing the current state (the user reads it on a card).`;
|
|
1612
2143
|
|
|
1613
|
-
export {
|
|
2144
|
+
export { capRemoteText as $, isAutomationsUnavailable as A, AUTOMATIONS_UNAVAILABLE_MESSAGE as B, readTeamScope as C, DEFAULT_RECENT_LIMIT as D, teamScopePath as E, readSessionMetadata as F, waitForSessionKey as G, sendUserMessage as H, teamRequest as I, createTeamsClient as J, trimIdent as K, AGENT_GUIDANCE as L, MAX_READ_LIMIT as M, formatEditConflictNotice as N, REMOTE_WRITE_CALLS_PER_MINUTE as O, PREVIEW_TOOL_NAME as P, guardRemoteSessionOpsRequest as Q, RemoteCallBudget as R, SESSION_PEER_SENT_FROM as S, TurnWaitTimeoutError as T, remoteError as U, REMOTE_OP_DEADLINE_MS as V, formatRemoteAuditLine as W, REMOTE_SEND_COMMIT_DEADLINE_MS as X, REMOTE_RESUME_WAIT_MS as Y, CLI_PEER_SENDER_ID as Z, capRemoteTranscript as _, PREVIEW_TOOL_TITLE as a, REMOTE_ANSWER_MAX_BYTES as a0, REMOTE_TITLE_MAX_BYTES as a1, createAutomationsClient as a2, AutomationsRequestError as a3, analyzeLatestTurn as a4, readSessionLog as a5, TURN_WINDOW as a6, userPromptText as a7, TeamConnectionPreflightError as a8, RemoteSessionOpsError as a9, REPORT_PROGRESS_TOOL_NAME as aa, TEAM_TOOL_NAMES as ab, AUTOMATION_TOOL_NAMES as ac, SESSION_PEER_TOOL_NAMES as ad, createSessionPeerToolExecutor as ae, REPORT_PROGRESS_TOOL_TITLE as af, REPORT_PROGRESS_TOOL_DESCRIPTION as ag, PREVIEW_TOOL_DESCRIPTION as b, registerAutomationTools as c, registerSessionPeerTools as d, listRemoteSessions as e, fillForeignAccountRows as f, listSessions as g, cliPeerSelf as h, listRemotePeers as i, listPeerSessions as j, readSessionTranscript as k, listAccountSessions as l, waitForRemoteTurnEnd as m, readRemoteTranscript as n, stopSession as o, resolvePermissionRequest as p, archiveSession as q, registerTeamsTools as r, sendPeerMessage as s, PEER_SCOPES$1 as t, deliverToSession as u, sendRemoteMessage as v, waitForTurnEnd as w, sessionWebUrl as x, authenticatedAutomationsClient as y, automationRunIdFromEnv as z };
|