@kmmao/happy-agent 0.3.11 → 0.4.0
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/index.cjs +947 -7
- package/dist/index.d.cts +136 -6
- package/dist/index.d.mts +136 -6
- package/dist/index.mjs +946 -9
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import axios, { AxiosError } from 'axios';
|
|
|
8
8
|
import qrcode from 'qrcode-terminal';
|
|
9
9
|
import { EventEmitter } from 'node:events';
|
|
10
10
|
import { io } from 'socket.io-client';
|
|
11
|
-
import { exec, execFile } from 'child_process';
|
|
11
|
+
import { exec, execFile, spawn } from 'child_process';
|
|
12
12
|
import { promisify } from 'util';
|
|
13
13
|
import { readFile, mkdir, writeFile, readdir, stat } from 'fs/promises';
|
|
14
14
|
import { createHash as createHash$1 } from 'crypto';
|
|
@@ -16,7 +16,7 @@ import { join as join$1, resolve } from 'path';
|
|
|
16
16
|
import { realpathSync } from 'fs';
|
|
17
17
|
import { tmpdir } from 'os';
|
|
18
18
|
|
|
19
|
-
var version = "0.
|
|
19
|
+
var version = "0.4.0";
|
|
20
20
|
|
|
21
21
|
function loadConfig() {
|
|
22
22
|
const serverUrl = (process.env.HAPPY_SERVER_URL ?? "https://happyserve.xycloud.info").replace(/\/+$/, "");
|
|
@@ -787,6 +787,7 @@ function createRpcHandlerManager(config) {
|
|
|
787
787
|
}
|
|
788
788
|
|
|
789
789
|
const execAsync = promisify(exec);
|
|
790
|
+
const execFileAsync$1 = promisify(execFile);
|
|
790
791
|
const UPLOAD_TEMP_DIR = join$1(tmpdir(), "happy", "uploads");
|
|
791
792
|
const MAX_WRITE_SIZE = 10 * 1024 * 1024;
|
|
792
793
|
function validatePath(targetPath, workingDirectory, additionalAllowedDirs) {
|
|
@@ -1046,6 +1047,367 @@ function registerAgentHandlers(rpcHandlerManager, workingDirectory, sessionId) {
|
|
|
1046
1047
|
await mkdir(uploadDir, { recursive: true });
|
|
1047
1048
|
return { success: true, path: uploadDir };
|
|
1048
1049
|
});
|
|
1050
|
+
rpcHandlerManager.registerHandler("getDirectoryTree", async (data) => {
|
|
1051
|
+
logger.debug("Get directory tree request:", data.path, "maxDepth:", data.maxDepth);
|
|
1052
|
+
const validation = validatePath(data.path, workingDirectory);
|
|
1053
|
+
if (!validation.valid) {
|
|
1054
|
+
return { success: false, error: validation.error };
|
|
1055
|
+
}
|
|
1056
|
+
async function buildTree(dirPath, name, currentDepth) {
|
|
1057
|
+
try {
|
|
1058
|
+
const stats = await stat(dirPath);
|
|
1059
|
+
const node = {
|
|
1060
|
+
name,
|
|
1061
|
+
path: dirPath,
|
|
1062
|
+
type: stats.isDirectory() ? "directory" : "file",
|
|
1063
|
+
size: stats.size,
|
|
1064
|
+
modified: stats.mtime.getTime()
|
|
1065
|
+
};
|
|
1066
|
+
if (stats.isDirectory() && currentDepth < data.maxDepth) {
|
|
1067
|
+
const entries = await readdir(dirPath, { withFileTypes: true });
|
|
1068
|
+
const children = [];
|
|
1069
|
+
await Promise.all(
|
|
1070
|
+
entries.map(async (entry) => {
|
|
1071
|
+
if (entry.isSymbolicLink()) return;
|
|
1072
|
+
const childPath = join$1(dirPath, entry.name);
|
|
1073
|
+
const childNode = await buildTree(childPath, entry.name, currentDepth + 1);
|
|
1074
|
+
if (childNode) children.push(childNode);
|
|
1075
|
+
})
|
|
1076
|
+
);
|
|
1077
|
+
children.sort((a, b) => {
|
|
1078
|
+
if (a.type === "directory" && b.type !== "directory") return -1;
|
|
1079
|
+
if (a.type !== "directory" && b.type === "directory") return 1;
|
|
1080
|
+
return a.name.localeCompare(b.name);
|
|
1081
|
+
});
|
|
1082
|
+
node.children = children;
|
|
1083
|
+
}
|
|
1084
|
+
return node;
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
logger.debug(`Failed to process ${dirPath}:`, error instanceof Error ? error.message : String(error));
|
|
1087
|
+
return null;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
try {
|
|
1091
|
+
if (data.maxDepth < 0) {
|
|
1092
|
+
return { success: false, error: "maxDepth must be non-negative" };
|
|
1093
|
+
}
|
|
1094
|
+
const baseName = data.path === "/" ? "/" : data.path.split("/").pop() || data.path;
|
|
1095
|
+
const tree = await buildTree(data.path, baseName, 0);
|
|
1096
|
+
if (!tree) {
|
|
1097
|
+
return { success: false, error: "Failed to access the specified path" };
|
|
1098
|
+
}
|
|
1099
|
+
return { success: true, tree };
|
|
1100
|
+
} catch (error) {
|
|
1101
|
+
logger.debug("Failed to get directory tree:", error);
|
|
1102
|
+
return {
|
|
1103
|
+
success: false,
|
|
1104
|
+
error: error instanceof Error ? error.message : "Failed to get directory tree"
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
});
|
|
1108
|
+
rpcHandlerManager.registerHandler(
|
|
1109
|
+
"ripgrep",
|
|
1110
|
+
async (data) => {
|
|
1111
|
+
const cwd = data.cwd || workingDirectory;
|
|
1112
|
+
if (data.cwd) {
|
|
1113
|
+
const validation = validatePath(data.cwd, workingDirectory);
|
|
1114
|
+
if (!validation.valid) {
|
|
1115
|
+
return { success: false, error: validation.error };
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
try {
|
|
1119
|
+
const { stdout, stderr } = await execFileAsync$1("rg", data.args, {
|
|
1120
|
+
cwd,
|
|
1121
|
+
timeout: 3e4,
|
|
1122
|
+
maxBuffer: 10 * 1024 * 1024
|
|
1123
|
+
});
|
|
1124
|
+
return { success: true, stdout: stdout?.toString() ?? "", stderr: stderr?.toString() ?? "", exitCode: 0 };
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
const e = error;
|
|
1127
|
+
if (e.code === "ENOENT") {
|
|
1128
|
+
return { success: false, error: "ripgrep (rg) is not installed on this machine" };
|
|
1129
|
+
}
|
|
1130
|
+
if (e.code === "1" || e.status === 1) {
|
|
1131
|
+
return { success: true, stdout: e.stdout?.toString() ?? "", stderr: e.stderr?.toString() ?? "", exitCode: 1 };
|
|
1132
|
+
}
|
|
1133
|
+
return {
|
|
1134
|
+
success: false,
|
|
1135
|
+
stdout: e.stdout?.toString() ?? "",
|
|
1136
|
+
stderr: e.stderr?.toString() ?? "",
|
|
1137
|
+
exitCode: typeof e.code === "number" ? e.code : 1,
|
|
1138
|
+
error: e.message ?? "ripgrep failed"
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
);
|
|
1143
|
+
rpcHandlerManager.registerHandler(
|
|
1144
|
+
"difftastic",
|
|
1145
|
+
async (data) => {
|
|
1146
|
+
const cwd = data.cwd || workingDirectory;
|
|
1147
|
+
if (data.cwd) {
|
|
1148
|
+
const validation = validatePath(data.cwd, workingDirectory);
|
|
1149
|
+
if (!validation.valid) {
|
|
1150
|
+
return { success: false, error: validation.error };
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
try {
|
|
1154
|
+
const { stdout, stderr } = await execFileAsync$1("difft", data.args, {
|
|
1155
|
+
cwd,
|
|
1156
|
+
timeout: 3e4,
|
|
1157
|
+
maxBuffer: 10 * 1024 * 1024
|
|
1158
|
+
});
|
|
1159
|
+
return { success: true, stdout: stdout?.toString() ?? "", stderr: stderr?.toString() ?? "", exitCode: 0 };
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
const e = error;
|
|
1162
|
+
if (e.code === "ENOENT") {
|
|
1163
|
+
return { success: false, error: "difftastic (difft) is not installed on this machine" };
|
|
1164
|
+
}
|
|
1165
|
+
return {
|
|
1166
|
+
success: false,
|
|
1167
|
+
stdout: e.stdout?.toString() ?? "",
|
|
1168
|
+
stderr: e.stderr?.toString() ?? "",
|
|
1169
|
+
exitCode: typeof e.code === "number" ? e.code : 1,
|
|
1170
|
+
error: e.message ?? "difftastic failed"
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
);
|
|
1175
|
+
rpcHandlerManager.registerHandler("listRemoteGitRepos", async (data) => {
|
|
1176
|
+
const page = data.page ?? 1;
|
|
1177
|
+
const perPage = data.perPage ?? 30;
|
|
1178
|
+
const query = data.query?.trim() || "";
|
|
1179
|
+
logger.debug("listRemoteGitRepos request:", { provider: data.provider, host: data.host, page, perPage, query });
|
|
1180
|
+
if (!data.apiToken) return { success: false, error: "API token is required" };
|
|
1181
|
+
if (!data.host?.trim()) return { success: false, error: "Host is required" };
|
|
1182
|
+
try {
|
|
1183
|
+
const baseUrl = buildGitApiBase(data.provider, data.host);
|
|
1184
|
+
const headers = buildGitApiHeaders(data.apiToken);
|
|
1185
|
+
let repos;
|
|
1186
|
+
let hasMore;
|
|
1187
|
+
if (data.provider === "github") {
|
|
1188
|
+
const listUrl = `${baseUrl}/user/repos?per_page=${perPage}&page=${page}&sort=updated&affiliation=owner,collaborator,organization_member`;
|
|
1189
|
+
const response = await fetch(listUrl, { headers });
|
|
1190
|
+
if (!response.ok) {
|
|
1191
|
+
const errorText = await response.text().catch(() => "");
|
|
1192
|
+
throw new Error(`HTTP ${response.status}: ${errorText}`);
|
|
1193
|
+
}
|
|
1194
|
+
const items = await response.json();
|
|
1195
|
+
repos = normalizeRemoteRepoEntries(items);
|
|
1196
|
+
hasMore = items.length >= perPage;
|
|
1197
|
+
} else {
|
|
1198
|
+
const searchParams = new URLSearchParams({ sort: "updated", order: "desc", limit: String(perPage), page: String(page) });
|
|
1199
|
+
if (query) searchParams.set("q", query);
|
|
1200
|
+
const searchUrl = `${baseUrl}/repos/search?${searchParams.toString()}`;
|
|
1201
|
+
const response = await fetch(searchUrl, { headers });
|
|
1202
|
+
if (!response.ok) {
|
|
1203
|
+
const errorText = await response.text().catch(() => "");
|
|
1204
|
+
throw new Error(`HTTP ${response.status}: ${errorText}`);
|
|
1205
|
+
}
|
|
1206
|
+
const body = await response.json();
|
|
1207
|
+
const items = Array.isArray(body) ? body : body.data || [];
|
|
1208
|
+
repos = normalizeRemoteRepoEntries(items);
|
|
1209
|
+
hasMore = items.length >= perPage;
|
|
1210
|
+
}
|
|
1211
|
+
return { success: true, repos, hasMore };
|
|
1212
|
+
} catch (error) {
|
|
1213
|
+
logger.debug("listRemoteGitRepos failed:", error);
|
|
1214
|
+
return { success: false, error: error instanceof Error ? error.message : "Failed to load remote repositories" };
|
|
1215
|
+
}
|
|
1216
|
+
});
|
|
1217
|
+
rpcHandlerManager.registerHandler(
|
|
1218
|
+
"cloneGitRepo",
|
|
1219
|
+
async (data) => {
|
|
1220
|
+
logger.debug("cloneGitRepo request:", { repoUrl: data.repoUrl, targetDirectory: data.targetDirectory });
|
|
1221
|
+
if (!data.repoUrl?.trim()) return { success: false, error: "Repository URL is required" };
|
|
1222
|
+
if (!data.targetDirectory?.trim()) return { success: false, error: "Target directory is required" };
|
|
1223
|
+
if (!data.targetDirectory.startsWith("/")) return { success: false, error: "Target directory must be an absolute path" };
|
|
1224
|
+
const coords = parseCloneCoordinates(data.repoUrl);
|
|
1225
|
+
if (!coords) return { success: false, error: "Invalid repository URL" };
|
|
1226
|
+
const repoPath = join$1(resolve(data.targetDirectory), coords.repo);
|
|
1227
|
+
try {
|
|
1228
|
+
await mkdir(resolve(data.targetDirectory), { recursive: true });
|
|
1229
|
+
try {
|
|
1230
|
+
const existing = await stat(repoPath);
|
|
1231
|
+
if (existing.isDirectory()) {
|
|
1232
|
+
return { success: false, error: `Destination already exists: ${repoPath}` };
|
|
1233
|
+
}
|
|
1234
|
+
} catch {
|
|
1235
|
+
}
|
|
1236
|
+
const cloneUrl = resolveCloneUrl(data.repoUrl, data.host);
|
|
1237
|
+
const options = {
|
|
1238
|
+
cwd: resolve(data.targetDirectory),
|
|
1239
|
+
timeout: 3e5,
|
|
1240
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
1241
|
+
env: buildCloneAuthEnv(data.provider, data.apiToken)
|
|
1242
|
+
};
|
|
1243
|
+
const { stdout, stderr } = await execFileAsync$1("git", ["clone", cloneUrl, repoPath], options);
|
|
1244
|
+
return { success: true, repoPath, stdout: stdout?.toString() ?? "", stderr: stderr?.toString() ?? "" };
|
|
1245
|
+
} catch (error) {
|
|
1246
|
+
const e = error;
|
|
1247
|
+
logger.debug("cloneGitRepo failed:", { message: e.message, stderr: e.stderr });
|
|
1248
|
+
return { success: false, repoPath, stdout: e.stdout || "", stderr: e.stderr || "", error: e.message || "Failed to clone repository" };
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
);
|
|
1252
|
+
rpcHandlerManager.registerHandler("createRemoteWebhook", async (data) => {
|
|
1253
|
+
logger.debug("createRemoteWebhook request:", { provider: data.provider, repoUrl: data.repoUrl });
|
|
1254
|
+
try {
|
|
1255
|
+
const parsed = parseRepoOwnerFromUrl(data.repoUrl);
|
|
1256
|
+
if (!parsed) return { success: false, error: "Invalid repo URL" };
|
|
1257
|
+
const { origin, owner, repo } = parsed;
|
|
1258
|
+
const isGitHubCom = origin === "https://github.com" || origin === "http://github.com";
|
|
1259
|
+
const baseUrl = data.provider === "github" && isGitHubCom ? "https://api.github.com" : data.provider === "github" ? `${origin}/api/v3` : `${origin}/api/v1`;
|
|
1260
|
+
const headers = {
|
|
1261
|
+
Authorization: `token ${data.apiToken}`,
|
|
1262
|
+
"Content-Type": "application/json",
|
|
1263
|
+
Accept: "application/json"
|
|
1264
|
+
};
|
|
1265
|
+
const hooksEndpoint = `${baseUrl}/repos/${owner}/${repo}/hooks`;
|
|
1266
|
+
const giteaEvents = [
|
|
1267
|
+
"issues",
|
|
1268
|
+
"issue_assign",
|
|
1269
|
+
"issue_label",
|
|
1270
|
+
"issue_milestone",
|
|
1271
|
+
"issue_comment",
|
|
1272
|
+
"pull_request",
|
|
1273
|
+
"pull_request_assign",
|
|
1274
|
+
"pull_request_label",
|
|
1275
|
+
"pull_request_milestone",
|
|
1276
|
+
"pull_request_comment",
|
|
1277
|
+
"pull_request_review",
|
|
1278
|
+
"pull_request_sync"
|
|
1279
|
+
];
|
|
1280
|
+
const events = data.provider === "gitea" ? giteaEvents : data.events;
|
|
1281
|
+
const listRes = await fetch(hooksEndpoint, { headers });
|
|
1282
|
+
if (listRes.ok) {
|
|
1283
|
+
const hooks = await listRes.json();
|
|
1284
|
+
const existing = hooks.find((h) => h.config.url === data.webhookUrl);
|
|
1285
|
+
if (existing) {
|
|
1286
|
+
const patchRes = await fetch(`${hooksEndpoint}/${existing.id}`, {
|
|
1287
|
+
method: "PATCH",
|
|
1288
|
+
headers,
|
|
1289
|
+
body: JSON.stringify({ config: { url: data.webhookUrl, content_type: "json", secret: data.webhookSecret }, events, active: true })
|
|
1290
|
+
});
|
|
1291
|
+
if (!patchRes.ok) {
|
|
1292
|
+
const errText = await patchRes.text().catch(() => "");
|
|
1293
|
+
return { success: false, error: `PATCH ${patchRes.status}: ${errText}` };
|
|
1294
|
+
}
|
|
1295
|
+
return { success: true, created: false, webhookId: existing.id };
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
const createBody = {
|
|
1299
|
+
name: "web",
|
|
1300
|
+
config: { url: data.webhookUrl, content_type: "json", secret: data.webhookSecret },
|
|
1301
|
+
events,
|
|
1302
|
+
active: true
|
|
1303
|
+
};
|
|
1304
|
+
if (data.provider === "gitea") createBody.type = "gitea";
|
|
1305
|
+
const createRes = await fetch(hooksEndpoint, { method: "POST", headers, body: JSON.stringify(createBody) });
|
|
1306
|
+
if (createRes.ok || createRes.status === 201) {
|
|
1307
|
+
const body = await createRes.json().catch(() => ({}));
|
|
1308
|
+
return { success: true, created: true, webhookId: body.id };
|
|
1309
|
+
}
|
|
1310
|
+
const errBody = await createRes.text().catch(() => "");
|
|
1311
|
+
return { success: false, error: `HTTP ${createRes.status}: ${errBody}` };
|
|
1312
|
+
} catch (error) {
|
|
1313
|
+
logger.debug("createRemoteWebhook failed:", error);
|
|
1314
|
+
return { success: false, error: error instanceof Error ? error.message : "Failed to create webhook" };
|
|
1315
|
+
}
|
|
1316
|
+
});
|
|
1317
|
+
rpcHandlerManager.registerHandler("deleteRemoteWebhook", async (data) => {
|
|
1318
|
+
logger.debug("deleteRemoteWebhook request:", { provider: data.provider, repoUrl: data.repoUrl });
|
|
1319
|
+
try {
|
|
1320
|
+
const parsed = parseRepoOwnerFromUrl(data.repoUrl);
|
|
1321
|
+
if (!parsed) return { success: false, error: "Invalid repo URL" };
|
|
1322
|
+
const { origin, owner, repo } = parsed;
|
|
1323
|
+
const isGitHubCom = origin === "https://github.com" || origin === "http://github.com";
|
|
1324
|
+
const baseUrl = data.provider === "github" && isGitHubCom ? "https://api.github.com" : data.provider === "github" ? `${origin}/api/v3` : `${origin}/api/v1`;
|
|
1325
|
+
const headers = { Authorization: `token ${data.apiToken}`, Accept: "application/json" };
|
|
1326
|
+
const hooksEndpoint = `${baseUrl}/repos/${owner}/${repo}/hooks`;
|
|
1327
|
+
const listRes = await fetch(hooksEndpoint, { headers });
|
|
1328
|
+
if (!listRes.ok) return { success: false, error: `List hooks failed: HTTP ${listRes.status}` };
|
|
1329
|
+
const hooks = await listRes.json();
|
|
1330
|
+
const existing = hooks.find((h) => h.config.url === data.webhookUrl);
|
|
1331
|
+
if (!existing) return { success: true, deleted: false };
|
|
1332
|
+
const deleteRes = await fetch(`${hooksEndpoint}/${existing.id}`, { method: "DELETE", headers });
|
|
1333
|
+
if (deleteRes.ok || deleteRes.status === 204) return { success: true, deleted: true };
|
|
1334
|
+
const errBody = await deleteRes.text().catch(() => "");
|
|
1335
|
+
return { success: false, error: `DELETE ${deleteRes.status}: ${errBody}` };
|
|
1336
|
+
} catch (error) {
|
|
1337
|
+
logger.debug("deleteRemoteWebhook failed:", error);
|
|
1338
|
+
return { success: false, error: error instanceof Error ? error.message : "Failed to delete webhook" };
|
|
1339
|
+
}
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
function parseHostEntry(host) {
|
|
1343
|
+
const match = host.match(/^(https?):\/\/(.+)/);
|
|
1344
|
+
if (match) return { bare: match[2].replace(/\/$/, ""), protocol: match[1] };
|
|
1345
|
+
return { bare: host.replace(/\/$/, ""), protocol: null };
|
|
1346
|
+
}
|
|
1347
|
+
function buildGitApiBase(provider, host) {
|
|
1348
|
+
const { bare, protocol } = parseHostEntry(host);
|
|
1349
|
+
const normalizedProtocol = protocol ?? "https";
|
|
1350
|
+
const origin = `${normalizedProtocol}://${bare}`;
|
|
1351
|
+
const isGitHubCom = bare === "github.com" || bare === "www.github.com";
|
|
1352
|
+
if (provider === "github") {
|
|
1353
|
+
return isGitHubCom ? "https://api.github.com" : `${origin}/api/v3`;
|
|
1354
|
+
}
|
|
1355
|
+
return `${origin}/api/v1`;
|
|
1356
|
+
}
|
|
1357
|
+
function buildGitApiHeaders(apiToken) {
|
|
1358
|
+
return {
|
|
1359
|
+
Authorization: `token ${apiToken}`,
|
|
1360
|
+
Accept: "application/json",
|
|
1361
|
+
"Content-Type": "application/json"
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
function normalizeRemoteRepoEntries(pageRepos) {
|
|
1365
|
+
return pageRepos.filter((repo) => !!repo.name).map((repo) => {
|
|
1366
|
+
const owner = repo.owner?.login || repo.owner?.username || "";
|
|
1367
|
+
const fullName = repo.full_name || (owner ? `${owner}/${repo.name}` : repo.name || "");
|
|
1368
|
+
const htmlUrl = repo.html_url || "";
|
|
1369
|
+
const cloneUrl = repo.clone_url || (htmlUrl ? `${htmlUrl}.git` : "");
|
|
1370
|
+
return { name: repo.name || fullName, fullName, cloneUrl, htmlUrl, private: !!repo.private, updatedAt: repo.updated_at ? Date.parse(repo.updated_at) : null };
|
|
1371
|
+
}).filter((repo) => !!repo.cloneUrl);
|
|
1372
|
+
}
|
|
1373
|
+
function parseCloneCoordinates(repoUrl) {
|
|
1374
|
+
const trimmed = repoUrl.trim();
|
|
1375
|
+
const sshMatch = trimmed.match(/^git@([^:]+):([^/]+)\/([^/.]+?)(?:\.git)?$/);
|
|
1376
|
+
if (sshMatch) return { host: sshMatch[1], owner: sshMatch[2], repo: sshMatch[3] };
|
|
1377
|
+
const sshUrlMatch = trimmed.match(/^ssh:\/\/[^@]+@([^/]+)\/([^/]+)\/([^/.]+?)(?:\.git)?$/);
|
|
1378
|
+
if (sshUrlMatch) return { host: sshUrlMatch[1], owner: sshUrlMatch[2], repo: sshUrlMatch[3] };
|
|
1379
|
+
const httpsMatch = trimmed.match(/^https?:\/\/([^/]+)\/([^/]+)\/([^/.]+?)(?:\.git)?$/);
|
|
1380
|
+
if (httpsMatch) return { host: httpsMatch[1], owner: httpsMatch[2], repo: httpsMatch[3] };
|
|
1381
|
+
return null;
|
|
1382
|
+
}
|
|
1383
|
+
function resolveCloneUrl(repoUrl, configuredHost) {
|
|
1384
|
+
if (/^https?:\/\//.test(repoUrl)) return repoUrl;
|
|
1385
|
+
const coords = parseCloneCoordinates(repoUrl);
|
|
1386
|
+
if (!coords) return repoUrl;
|
|
1387
|
+
const hostEntry = configuredHost ? parseHostEntry(configuredHost) : null;
|
|
1388
|
+
const protocol = hostEntry?.protocol ?? "https";
|
|
1389
|
+
const bareHost = hostEntry?.bare ?? coords.host;
|
|
1390
|
+
return `${protocol}://${bareHost}/${coords.owner}/${coords.repo}.git`;
|
|
1391
|
+
}
|
|
1392
|
+
function buildCloneAuthEnv(provider, apiToken) {
|
|
1393
|
+
if (!apiToken) return void 0;
|
|
1394
|
+
const username = provider === "github" ? "x-access-token" : "oauth2";
|
|
1395
|
+
const authValue = Buffer.from(`${username}:${apiToken}`).toString("base64");
|
|
1396
|
+
return {
|
|
1397
|
+
...process.env,
|
|
1398
|
+
GIT_CONFIG_COUNT: "1",
|
|
1399
|
+
GIT_CONFIG_KEY_0: "http.extraHeader",
|
|
1400
|
+
GIT_CONFIG_VALUE_0: `Authorization: Basic ${authValue}`
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
function parseRepoOwnerFromUrl(repoUrl) {
|
|
1404
|
+
try {
|
|
1405
|
+
const url = new URL(repoUrl);
|
|
1406
|
+
const parts = url.pathname.replace(/^\//, "").replace(/\.git$/, "").split("/");
|
|
1407
|
+
if (parts.length >= 2) return { origin: url.origin, owner: parts[0], repo: parts[1] };
|
|
1408
|
+
} catch {
|
|
1409
|
+
}
|
|
1410
|
+
return null;
|
|
1049
1411
|
}
|
|
1050
1412
|
|
|
1051
1413
|
class SessionClient extends EventEmitter {
|
|
@@ -1473,6 +1835,340 @@ function isNotFound(err) {
|
|
|
1473
1835
|
return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
|
|
1474
1836
|
}
|
|
1475
1837
|
|
|
1838
|
+
const pidToSession = /* @__PURE__ */ new Map();
|
|
1839
|
+
function trackSession(session) {
|
|
1840
|
+
pidToSession.set(session.pid, session);
|
|
1841
|
+
}
|
|
1842
|
+
function untrackSession(pid) {
|
|
1843
|
+
const session = pidToSession.get(pid);
|
|
1844
|
+
pidToSession.delete(pid);
|
|
1845
|
+
return session;
|
|
1846
|
+
}
|
|
1847
|
+
function getAllTrackedSessions() {
|
|
1848
|
+
return [...pidToSession.values()];
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
const execFileAsync = promisify(execFile);
|
|
1852
|
+
const SERVER_INTERNAL_SECRETS = /* @__PURE__ */ new Set([
|
|
1853
|
+
"DATABASE_URL",
|
|
1854
|
+
"REDIS_URL",
|
|
1855
|
+
"JWT_SECRET",
|
|
1856
|
+
"ENCRYPTION_KEY",
|
|
1857
|
+
"GITHUB_CLIENT_SECRET",
|
|
1858
|
+
"AWS_SECRET_ACCESS_KEY",
|
|
1859
|
+
"AWS_ACCESS_KEY_ID",
|
|
1860
|
+
"AWS_SESSION_TOKEN",
|
|
1861
|
+
"STRIPE_SECRET_KEY",
|
|
1862
|
+
"SENDGRID_API_KEY",
|
|
1863
|
+
"S3_ACCESS_KEY",
|
|
1864
|
+
"S3_SECRET_KEY"
|
|
1865
|
+
]);
|
|
1866
|
+
function buildSpawnEnv(extra) {
|
|
1867
|
+
const base = {};
|
|
1868
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
1869
|
+
if (!SERVER_INTERNAL_SECRETS.has(key) && key !== "CLAUDECODE") {
|
|
1870
|
+
base[key] = value;
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
if (extra) {
|
|
1874
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
1875
|
+
if (value !== void 0) {
|
|
1876
|
+
base[key] = value;
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
return base;
|
|
1881
|
+
}
|
|
1882
|
+
let happyBinaryPath;
|
|
1883
|
+
async function findHappyBinary() {
|
|
1884
|
+
if (happyBinaryPath !== void 0) return happyBinaryPath;
|
|
1885
|
+
try {
|
|
1886
|
+
const { stdout } = await execFileAsync("which", ["happy"]);
|
|
1887
|
+
happyBinaryPath = stdout.trim() || null;
|
|
1888
|
+
} catch {
|
|
1889
|
+
happyBinaryPath = null;
|
|
1890
|
+
}
|
|
1891
|
+
return happyBinaryPath;
|
|
1892
|
+
}
|
|
1893
|
+
async function spawnSession(options) {
|
|
1894
|
+
const {
|
|
1895
|
+
directory,
|
|
1896
|
+
agent = "claude",
|
|
1897
|
+
approvedNewDirectoryCreation = false,
|
|
1898
|
+
happySessionId,
|
|
1899
|
+
automationContext,
|
|
1900
|
+
environmentVariables
|
|
1901
|
+
} = options;
|
|
1902
|
+
const happyPath = await findHappyBinary();
|
|
1903
|
+
if (!happyPath) {
|
|
1904
|
+
return {
|
|
1905
|
+
type: "error",
|
|
1906
|
+
errorMessage: "happy CLI not found. Install with: npm install -g @kmmao/happy-coder"
|
|
1907
|
+
};
|
|
1908
|
+
}
|
|
1909
|
+
try {
|
|
1910
|
+
const dirStat = await stat(directory);
|
|
1911
|
+
if (!dirStat.isDirectory()) {
|
|
1912
|
+
return { type: "error", errorMessage: `Path exists but is not a directory: ${directory}` };
|
|
1913
|
+
}
|
|
1914
|
+
} catch {
|
|
1915
|
+
if (!approvedNewDirectoryCreation) {
|
|
1916
|
+
return { type: "requestToApproveDirectoryCreation", directory };
|
|
1917
|
+
}
|
|
1918
|
+
try {
|
|
1919
|
+
await mkdir(directory, { recursive: true });
|
|
1920
|
+
logger.debug(`[SPAWN] Created directory: ${directory}`);
|
|
1921
|
+
} catch (mkdirError) {
|
|
1922
|
+
return {
|
|
1923
|
+
type: "error",
|
|
1924
|
+
errorMessage: `Failed to create directory: ${mkdirError instanceof Error ? mkdirError.message : String(mkdirError)}`
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
const args = [
|
|
1929
|
+
agent,
|
|
1930
|
+
"--happy-starting-mode",
|
|
1931
|
+
"remote",
|
|
1932
|
+
"--started-by",
|
|
1933
|
+
"daemon"
|
|
1934
|
+
];
|
|
1935
|
+
if (happySessionId) {
|
|
1936
|
+
args.push("--happy-session-id", happySessionId);
|
|
1937
|
+
}
|
|
1938
|
+
const spawnEnv = buildSpawnEnv(environmentVariables);
|
|
1939
|
+
logger.debug(`[SPAWN] ${happyPath} ${args.join(" ")} in ${directory}`);
|
|
1940
|
+
let happyProcess;
|
|
1941
|
+
try {
|
|
1942
|
+
happyProcess = spawn(happyPath, args, {
|
|
1943
|
+
cwd: directory,
|
|
1944
|
+
detached: true,
|
|
1945
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1946
|
+
env: spawnEnv
|
|
1947
|
+
});
|
|
1948
|
+
} catch (spawnError) {
|
|
1949
|
+
return {
|
|
1950
|
+
type: "error",
|
|
1951
|
+
errorMessage: `Failed to spawn: ${spawnError instanceof Error ? spawnError.message : String(spawnError)}`
|
|
1952
|
+
};
|
|
1953
|
+
}
|
|
1954
|
+
const pid = happyProcess.pid;
|
|
1955
|
+
if (!pid) {
|
|
1956
|
+
return { type: "error", errorMessage: "Spawned process has no PID" };
|
|
1957
|
+
}
|
|
1958
|
+
const tracked = {
|
|
1959
|
+
pid,
|
|
1960
|
+
directory,
|
|
1961
|
+
startedAt: Date.now(),
|
|
1962
|
+
childProcess: happyProcess,
|
|
1963
|
+
lastActivityAt: Date.now(),
|
|
1964
|
+
automationContext
|
|
1965
|
+
};
|
|
1966
|
+
trackSession(tracked);
|
|
1967
|
+
happyProcess.stdout?.on("data", () => {
|
|
1968
|
+
tracked.lastActivityAt = Date.now();
|
|
1969
|
+
});
|
|
1970
|
+
happyProcess.stderr?.on("data", () => {
|
|
1971
|
+
tracked.lastActivityAt = Date.now();
|
|
1972
|
+
});
|
|
1973
|
+
happyProcess.on("exit", (code, signal) => {
|
|
1974
|
+
logger.debug(`[SPAWN] Process ${pid} exited: code=${code} signal=${signal}`);
|
|
1975
|
+
const session = untrackSession(pid);
|
|
1976
|
+
if (session) {
|
|
1977
|
+
session.terminationReason = signal ? `signal:${signal}` : code !== 0 ? `exit:${code}` : "completed";
|
|
1978
|
+
}
|
|
1979
|
+
});
|
|
1980
|
+
happyProcess.unref();
|
|
1981
|
+
logger.debug(`[SPAWN] Spawned PID ${pid} in ${directory}`);
|
|
1982
|
+
return { type: "success", pid, directory };
|
|
1983
|
+
}
|
|
1984
|
+
function stopSession(pid) {
|
|
1985
|
+
const tracked = untrackSession(pid);
|
|
1986
|
+
if (!tracked) {
|
|
1987
|
+
try {
|
|
1988
|
+
process.kill(pid, "SIGTERM");
|
|
1989
|
+
return { stopped: true };
|
|
1990
|
+
} catch {
|
|
1991
|
+
return { stopped: false, error: `No tracked session with PID ${pid}` };
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
try {
|
|
1995
|
+
if (tracked.childProcess && !tracked.childProcess.killed) {
|
|
1996
|
+
tracked.childProcess.kill("SIGTERM");
|
|
1997
|
+
} else {
|
|
1998
|
+
process.kill(pid, "SIGTERM");
|
|
1999
|
+
}
|
|
2000
|
+
tracked.terminationReason = "user_stop";
|
|
2001
|
+
logger.debug(`[SPAWN] Stopped session PID ${pid}`);
|
|
2002
|
+
return { stopped: true };
|
|
2003
|
+
} catch (error) {
|
|
2004
|
+
return {
|
|
2005
|
+
stopped: false,
|
|
2006
|
+
error: error instanceof Error ? error.message : "Failed to stop session"
|
|
2007
|
+
};
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
const PROMPT_DIR = join$1(tmpdir(), "happy", "agent-prompts");
|
|
2012
|
+
async function writePromptFile(prefix, content) {
|
|
2013
|
+
await mkdir(PROMPT_DIR, { recursive: true });
|
|
2014
|
+
const filename = `${prefix}-${Date.now()}.md`;
|
|
2015
|
+
const filepath = join$1(PROMPT_DIR, filename);
|
|
2016
|
+
await writeFile(filepath, content, "utf-8");
|
|
2017
|
+
return filepath;
|
|
2018
|
+
}
|
|
2019
|
+
function buildWebhookPrompt(data) {
|
|
2020
|
+
return [
|
|
2021
|
+
`# Issue #${data.issueNumber}: ${data.issueTitle}`,
|
|
2022
|
+
"",
|
|
2023
|
+
`Author: ${data.issueAuthor}`,
|
|
2024
|
+
`Labels: ${data.issueLabels.join(", ") || "none"}`,
|
|
2025
|
+
`URL: ${data.issueUrl}`,
|
|
2026
|
+
"",
|
|
2027
|
+
data.issueBody
|
|
2028
|
+
].join("\n");
|
|
2029
|
+
}
|
|
2030
|
+
function buildSupervisorPrompt(data) {
|
|
2031
|
+
const parts = [
|
|
2032
|
+
`# Supervisor Run: ${data.runId}`,
|
|
2033
|
+
"",
|
|
2034
|
+
`Trigger: ${data.trigger}`,
|
|
2035
|
+
`Project: ${data.projectId}`
|
|
2036
|
+
];
|
|
2037
|
+
if (data.mode) parts.push(`Mode: ${data.mode}`);
|
|
2038
|
+
if (data.dimensions?.length) parts.push(`Dimensions: ${data.dimensions.join(", ")}`);
|
|
2039
|
+
if (data.changedFiles?.length) {
|
|
2040
|
+
parts.push("", "## Changed Files", ...data.changedFiles.map((f) => `- ${f}`));
|
|
2041
|
+
}
|
|
2042
|
+
if (data.customRules) parts.push("", "## Custom Rules", data.customRules);
|
|
2043
|
+
return parts.join("\n");
|
|
2044
|
+
}
|
|
2045
|
+
async function handleWebhookTrigger(data, client, serverUrl, authToken) {
|
|
2046
|
+
logger.debug(`[TRIGGER] Webhook: issue #${data.issueNumber} in ${data.repoPath}`);
|
|
2047
|
+
client.emitWebhookStatus({
|
|
2048
|
+
webhookEventId: data.webhookEventId,
|
|
2049
|
+
status: "dispatched"
|
|
2050
|
+
});
|
|
2051
|
+
try {
|
|
2052
|
+
const promptFile = await writePromptFile("webhook", buildWebhookPrompt(data));
|
|
2053
|
+
const result = await spawnSession({
|
|
2054
|
+
directory: data.repoPath,
|
|
2055
|
+
approvedNewDirectoryCreation: false,
|
|
2056
|
+
automationContext: {
|
|
2057
|
+
kind: "webhook",
|
|
2058
|
+
trigger: `issue#${data.issueNumber}`
|
|
2059
|
+
},
|
|
2060
|
+
environmentVariables: {
|
|
2061
|
+
HAPPY_INITIAL_PROMPT_FILE: promptFile,
|
|
2062
|
+
HAPPY_WEBHOOK_EVENT_ID: data.webhookEventId,
|
|
2063
|
+
HAPPY_WEBHOOK_ISSUE_URL: data.issueUrl,
|
|
2064
|
+
HAPPY_SERVER_URL: serverUrl,
|
|
2065
|
+
HAPPY_AUTH_TOKEN: authToken
|
|
2066
|
+
}
|
|
2067
|
+
});
|
|
2068
|
+
if (result.type === "success") {
|
|
2069
|
+
logger.debug(`[TRIGGER] Webhook session spawned: PID ${result.pid}`);
|
|
2070
|
+
} else {
|
|
2071
|
+
logger.debug(`[TRIGGER] Webhook spawn failed: ${result.type === "error" ? result.errorMessage : "needs approval"}`);
|
|
2072
|
+
client.emitWebhookStatus({
|
|
2073
|
+
webhookEventId: data.webhookEventId,
|
|
2074
|
+
status: "failed",
|
|
2075
|
+
errorMessage: result.type === "error" ? result.errorMessage : "Directory creation not approved"
|
|
2076
|
+
});
|
|
2077
|
+
}
|
|
2078
|
+
} catch (error) {
|
|
2079
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2080
|
+
logger.debug(`[TRIGGER] Webhook error: ${msg}`);
|
|
2081
|
+
client.emitWebhookStatus({
|
|
2082
|
+
webhookEventId: data.webhookEventId,
|
|
2083
|
+
status: "failed",
|
|
2084
|
+
errorMessage: msg
|
|
2085
|
+
});
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
async function handleSupervisorTrigger(data, client, serverUrl, authToken) {
|
|
2089
|
+
logger.debug(`[TRIGGER] Supervisor: run ${data.runId} in ${data.repoPath}`);
|
|
2090
|
+
client.emitSupervisorRunStatus({
|
|
2091
|
+
runId: data.runId,
|
|
2092
|
+
projectId: data.projectId,
|
|
2093
|
+
status: "running"
|
|
2094
|
+
});
|
|
2095
|
+
try {
|
|
2096
|
+
const promptFile = await writePromptFile("supervisor", buildSupervisorPrompt(data));
|
|
2097
|
+
const result = await spawnSession({
|
|
2098
|
+
directory: data.repoPath,
|
|
2099
|
+
approvedNewDirectoryCreation: false,
|
|
2100
|
+
automationContext: {
|
|
2101
|
+
kind: "supervisor",
|
|
2102
|
+
trigger: data.trigger,
|
|
2103
|
+
projectId: data.projectId,
|
|
2104
|
+
runId: data.runId
|
|
2105
|
+
},
|
|
2106
|
+
environmentVariables: {
|
|
2107
|
+
HAPPY_INITIAL_PROMPT_FILE: promptFile,
|
|
2108
|
+
HAPPY_SUPERVISOR_RUN_ID: data.runId,
|
|
2109
|
+
HAPPY_SUPERVISOR_PROJECT_ID: data.projectId,
|
|
2110
|
+
HAPPY_SUPERVISOR_SERVER_URL: serverUrl,
|
|
2111
|
+
HAPPY_SUPERVISOR_AUTH_TOKEN: authToken
|
|
2112
|
+
}
|
|
2113
|
+
});
|
|
2114
|
+
if (result.type !== "success") {
|
|
2115
|
+
client.emitSupervisorRunStatus({
|
|
2116
|
+
runId: data.runId,
|
|
2117
|
+
projectId: data.projectId,
|
|
2118
|
+
status: "failed",
|
|
2119
|
+
errorMessage: result.type === "error" ? result.errorMessage : "Directory creation not approved"
|
|
2120
|
+
});
|
|
2121
|
+
}
|
|
2122
|
+
} catch (error) {
|
|
2123
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2124
|
+
logger.debug(`[TRIGGER] Supervisor error: ${msg}`);
|
|
2125
|
+
client.emitSupervisorRunStatus({
|
|
2126
|
+
runId: data.runId,
|
|
2127
|
+
projectId: data.projectId,
|
|
2128
|
+
status: "failed",
|
|
2129
|
+
errorMessage: msg
|
|
2130
|
+
});
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
async function handleTaskTrigger(data, serverUrl, _authToken) {
|
|
2134
|
+
logger.debug(`[TRIGGER] Task: ${data.taskId} in ${data.directory}`);
|
|
2135
|
+
try {
|
|
2136
|
+
const promptFile = await writePromptFile("task", data.prompt);
|
|
2137
|
+
const skillEnv = {};
|
|
2138
|
+
if (data.skillContents?.length) {
|
|
2139
|
+
skillEnv.HAPPY_TASK_SKILL_COUNT = String(data.skillContents.length);
|
|
2140
|
+
for (let i = 0; i < data.skillContents.length; i++) {
|
|
2141
|
+
skillEnv[`HAPPY_TASK_SKILL_${i}_NAME`] = data.skillContents[i].name;
|
|
2142
|
+
skillEnv[`HAPPY_TASK_SKILL_${i}_CONTENT`] = data.skillContents[i].content;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
const result = await spawnSession({
|
|
2146
|
+
directory: data.directory,
|
|
2147
|
+
approvedNewDirectoryCreation: true,
|
|
2148
|
+
// Tasks always auto-approve directory
|
|
2149
|
+
automationContext: {
|
|
2150
|
+
kind: "task",
|
|
2151
|
+
trigger: "task-dispatch",
|
|
2152
|
+
projectId: data.projectId
|
|
2153
|
+
},
|
|
2154
|
+
environmentVariables: {
|
|
2155
|
+
HAPPY_INITIAL_PROMPT_FILE: promptFile,
|
|
2156
|
+
HAPPY_TASK_ID: data.taskId,
|
|
2157
|
+
HAPPY_TASK_PRIORITY: data.priority,
|
|
2158
|
+
HAPPY_TASK_SERVER_URL: serverUrl,
|
|
2159
|
+
HAPPY_TASK_RESULT_TOKEN: data.resultToken ?? "",
|
|
2160
|
+
HAPPY_TASK_REPORT_URL: `${serverUrl}/v1/tasks/${data.taskId}/result`,
|
|
2161
|
+
...skillEnv
|
|
2162
|
+
}
|
|
2163
|
+
});
|
|
2164
|
+
if (result.type !== "success") {
|
|
2165
|
+
logger.debug(`[TRIGGER] Task spawn failed: ${result.type === "error" ? result.errorMessage : "needs approval"}`);
|
|
2166
|
+
}
|
|
2167
|
+
} catch (error) {
|
|
2168
|
+
logger.debug(`[TRIGGER] Task error: ${error instanceof Error ? error.message : String(error)}`);
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
|
|
1476
2172
|
const TAILSCALE_REFRESH_MS = 5 * 60 * 1e3;
|
|
1477
2173
|
class MachineClient {
|
|
1478
2174
|
machine;
|
|
@@ -1484,11 +2180,17 @@ class MachineClient {
|
|
|
1484
2180
|
tunnelManager = null;
|
|
1485
2181
|
token;
|
|
1486
2182
|
serverUrl;
|
|
2183
|
+
agentVersion;
|
|
2184
|
+
startTime = Date.now();
|
|
1487
2185
|
onEphemeral;
|
|
2186
|
+
automationEnabled = false;
|
|
2187
|
+
automationServerUrl = "";
|
|
2188
|
+
automationAuthToken = "";
|
|
1488
2189
|
constructor(opts) {
|
|
1489
2190
|
this.token = opts.token;
|
|
1490
2191
|
this.machine = opts.machine;
|
|
1491
2192
|
this.serverUrl = opts.serverUrl;
|
|
2193
|
+
this.agentVersion = opts.agentVersion ?? "unknown";
|
|
1492
2194
|
this.onEphemeral = opts.onEphemeral;
|
|
1493
2195
|
this.rpcHandlerManager = new RpcHandlerManager({
|
|
1494
2196
|
scopePrefix: opts.machine.id,
|
|
@@ -1498,6 +2200,32 @@ class MachineClient {
|
|
|
1498
2200
|
});
|
|
1499
2201
|
const workDir = opts.workingDirectory ?? process.cwd();
|
|
1500
2202
|
registerAgentHandlers(this.rpcHandlerManager, workDir, opts.machine.id);
|
|
2203
|
+
this.registerMachineHandlers();
|
|
2204
|
+
}
|
|
2205
|
+
// -----------------------------------------------------------------------
|
|
2206
|
+
// Machine-scoped RPC handlers
|
|
2207
|
+
// -----------------------------------------------------------------------
|
|
2208
|
+
registerMachineHandlers() {
|
|
2209
|
+
this.rpcHandlerManager.registerHandler(
|
|
2210
|
+
"spawn-happy-session",
|
|
2211
|
+
async (data) => {
|
|
2212
|
+
logger.debug("[MACHINE] spawn-happy-session request:", data.directory);
|
|
2213
|
+
return spawnSession(data);
|
|
2214
|
+
}
|
|
2215
|
+
);
|
|
2216
|
+
this.rpcHandlerManager.registerHandler("stop-session", async (data) => {
|
|
2217
|
+
logger.debug("[MACHINE] stop-session request:", data.pid);
|
|
2218
|
+
return stopSession(data.pid);
|
|
2219
|
+
});
|
|
2220
|
+
this.rpcHandlerManager.registerHandler("list-tracked-sessions", async () => {
|
|
2221
|
+
const sessions = getAllTrackedSessions().map((s) => ({
|
|
2222
|
+
pid: s.pid,
|
|
2223
|
+
directory: s.directory,
|
|
2224
|
+
startedAt: s.startedAt,
|
|
2225
|
+
happySessionId: s.happySessionId
|
|
2226
|
+
}));
|
|
2227
|
+
return { sessions };
|
|
2228
|
+
});
|
|
1501
2229
|
}
|
|
1502
2230
|
// -----------------------------------------------------------------------
|
|
1503
2231
|
// Connection
|
|
@@ -1524,6 +2252,8 @@ class MachineClient {
|
|
|
1524
2252
|
status: "running",
|
|
1525
2253
|
pid: process.pid,
|
|
1526
2254
|
startedAt: Date.now(),
|
|
2255
|
+
startTime: this.startTime,
|
|
2256
|
+
startedWithCliVersion: this.agentVersion,
|
|
1527
2257
|
tailscale: this.lastTailscaleInfo ?? state?.tailscale
|
|
1528
2258
|
}));
|
|
1529
2259
|
this.startKeepAlive();
|
|
@@ -1563,12 +2293,12 @@ class MachineClient {
|
|
|
1563
2293
|
}
|
|
1564
2294
|
}
|
|
1565
2295
|
});
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
}
|
|
2296
|
+
this.socket.on("ephemeral", (data) => {
|
|
2297
|
+
const event = data;
|
|
2298
|
+
logger.debug("[MACHINE] Received ephemeral event:", event.type);
|
|
2299
|
+
this.onEphemeral?.(event);
|
|
2300
|
+
this.handleAutomationEvent(event);
|
|
2301
|
+
});
|
|
1572
2302
|
this.socket.on("connect_error", (error) => {
|
|
1573
2303
|
logger.debug(`[MACHINE] Connection error: ${error.message}`);
|
|
1574
2304
|
});
|
|
@@ -1645,6 +2375,75 @@ class MachineClient {
|
|
|
1645
2375
|
}, { maxRetries: 3, label: "updateDaemonState" });
|
|
1646
2376
|
}
|
|
1647
2377
|
// -----------------------------------------------------------------------
|
|
2378
|
+
// Socket event emitters
|
|
2379
|
+
// -----------------------------------------------------------------------
|
|
2380
|
+
/** Emit a session lifecycle event. */
|
|
2381
|
+
emitSessionEvent(sessionId, eventType, summary, detail) {
|
|
2382
|
+
this.socket?.emit("session-event", { sessionId, eventType, summary, detail });
|
|
2383
|
+
}
|
|
2384
|
+
/** Report webhook processing status. */
|
|
2385
|
+
emitWebhookStatus(data) {
|
|
2386
|
+
this.socket?.emit("webhook-status", data);
|
|
2387
|
+
}
|
|
2388
|
+
/** Report supervisor run status. */
|
|
2389
|
+
emitSupervisorRunStatus(data) {
|
|
2390
|
+
this.socket?.emit("supervisor-run-status", data);
|
|
2391
|
+
}
|
|
2392
|
+
/** Submit a knowledge entry from a session. */
|
|
2393
|
+
emitSubmitKnowledge(sid, entry) {
|
|
2394
|
+
this.socket?.emit("submit-knowledge", { sid, entry });
|
|
2395
|
+
}
|
|
2396
|
+
/** Fetch knowledge for a session. */
|
|
2397
|
+
emitFetchKnowledge(sid, mode, contextHints, callback) {
|
|
2398
|
+
this.socket?.emit("fetch-knowledge", { sid, mode, contextHints }, callback);
|
|
2399
|
+
}
|
|
2400
|
+
/** Stream task log chunk. */
|
|
2401
|
+
emitTaskLog(sid, taskId, outputFile, chunk, offset) {
|
|
2402
|
+
this.socket?.emit("task-log", { sid, taskId, outputFile, chunk, offset });
|
|
2403
|
+
}
|
|
2404
|
+
// -----------------------------------------------------------------------
|
|
2405
|
+
// Automation triggers
|
|
2406
|
+
// -----------------------------------------------------------------------
|
|
2407
|
+
/**
|
|
2408
|
+
* Enable automation handling — agent will process webhook, supervisor,
|
|
2409
|
+
* and task triggers from the server by spawning Happy CLI sessions.
|
|
2410
|
+
*/
|
|
2411
|
+
enableAutomation(serverUrl, authToken) {
|
|
2412
|
+
this.automationEnabled = true;
|
|
2413
|
+
this.automationServerUrl = serverUrl;
|
|
2414
|
+
this.automationAuthToken = authToken;
|
|
2415
|
+
logger.debug("[MACHINE] Automation enabled");
|
|
2416
|
+
}
|
|
2417
|
+
/** Internal dispatch for ephemeral events that need automation handling. */
|
|
2418
|
+
handleAutomationEvent(event) {
|
|
2419
|
+
if (!this.automationEnabled) return;
|
|
2420
|
+
switch (event.type) {
|
|
2421
|
+
case "webhook-trigger":
|
|
2422
|
+
void handleWebhookTrigger(
|
|
2423
|
+
event,
|
|
2424
|
+
this,
|
|
2425
|
+
this.automationServerUrl,
|
|
2426
|
+
this.automationAuthToken
|
|
2427
|
+
);
|
|
2428
|
+
break;
|
|
2429
|
+
case "supervisor-trigger":
|
|
2430
|
+
void handleSupervisorTrigger(
|
|
2431
|
+
event,
|
|
2432
|
+
this,
|
|
2433
|
+
this.automationServerUrl,
|
|
2434
|
+
this.automationAuthToken
|
|
2435
|
+
);
|
|
2436
|
+
break;
|
|
2437
|
+
case "task-trigger":
|
|
2438
|
+
void handleTaskTrigger(
|
|
2439
|
+
event,
|
|
2440
|
+
this.automationServerUrl,
|
|
2441
|
+
this.automationAuthToken
|
|
2442
|
+
);
|
|
2443
|
+
break;
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
// -----------------------------------------------------------------------
|
|
1648
2447
|
// Lifecycle
|
|
1649
2448
|
// -----------------------------------------------------------------------
|
|
1650
2449
|
/** Seed initial Tailscale info detected before connect. */
|
|
@@ -1719,6 +2518,131 @@ function tailscaleChanged(prev, next) {
|
|
|
1719
2518
|
return prev.status !== next.status || prev.ipv4 !== next.ipv4 || prev.ipv6 !== next.ipv6 || prev.hostname !== next.hostname || JSON.stringify(prev.serves) !== JSON.stringify(next.serves);
|
|
1720
2519
|
}
|
|
1721
2520
|
|
|
2521
|
+
function pidFilePath(homeDir) {
|
|
2522
|
+
return join(homeDir, "agent-daemon.pid");
|
|
2523
|
+
}
|
|
2524
|
+
function writePidFile(homeDir, pid) {
|
|
2525
|
+
mkdirSync(homeDir, { recursive: true });
|
|
2526
|
+
writeFileSync(pidFilePath(homeDir), String(pid), "utf-8");
|
|
2527
|
+
}
|
|
2528
|
+
function readPidFile(homeDir) {
|
|
2529
|
+
try {
|
|
2530
|
+
const raw = readFileSync(pidFilePath(homeDir), "utf-8").trim();
|
|
2531
|
+
const pid = parseInt(raw, 10);
|
|
2532
|
+
return isNaN(pid) ? null : pid;
|
|
2533
|
+
} catch {
|
|
2534
|
+
return null;
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
function removePidFile(homeDir) {
|
|
2538
|
+
try {
|
|
2539
|
+
unlinkSync(pidFilePath(homeDir));
|
|
2540
|
+
} catch {
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
function isProcessRunning(pid) {
|
|
2544
|
+
try {
|
|
2545
|
+
process.kill(pid, 0);
|
|
2546
|
+
return true;
|
|
2547
|
+
} catch {
|
|
2548
|
+
return false;
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
async function startDaemon(options) {
|
|
2552
|
+
const config = loadConfig();
|
|
2553
|
+
const creds = requireCredentials(config);
|
|
2554
|
+
const existingPid = readPidFile(config.homeDir);
|
|
2555
|
+
if (existingPid && isProcessRunning(existingPid)) {
|
|
2556
|
+
console.log(`Daemon already running (PID ${existingPid})`);
|
|
2557
|
+
process.exitCode = 1;
|
|
2558
|
+
return;
|
|
2559
|
+
}
|
|
2560
|
+
if (existingPid) {
|
|
2561
|
+
removePidFile(config.homeDir);
|
|
2562
|
+
}
|
|
2563
|
+
const workDir = options.directory ?? process.cwd();
|
|
2564
|
+
console.log(`Starting agent daemon in ${workDir}...`);
|
|
2565
|
+
const metadata = {
|
|
2566
|
+
host: hostname(),
|
|
2567
|
+
platform: process.platform,
|
|
2568
|
+
happyCliVersion: version,
|
|
2569
|
+
homeDir: config.homeDir,
|
|
2570
|
+
happyHomeDir: config.homeDir,
|
|
2571
|
+
happyLibDir: config.homeDir
|
|
2572
|
+
};
|
|
2573
|
+
const machine = await getOrCreateMachine(config, creds, metadata);
|
|
2574
|
+
console.log(`Machine: ${machine.id} (${machine.metadata.host})`);
|
|
2575
|
+
const tailscaleInfo = await detectTailscale();
|
|
2576
|
+
const serves = tailscaleInfo.status === "connected" ? await detectTailscaleServe() : [];
|
|
2577
|
+
const fullTailscale = { ...tailscaleInfo, serves };
|
|
2578
|
+
if (tailscaleInfo.status === "connected") {
|
|
2579
|
+
console.log(`Tailscale: ${tailscaleInfo.hostname} (${tailscaleInfo.ipv4})`);
|
|
2580
|
+
}
|
|
2581
|
+
const client = new MachineClient({
|
|
2582
|
+
token: creds.token,
|
|
2583
|
+
machine,
|
|
2584
|
+
serverUrl: config.serverUrl,
|
|
2585
|
+
agentVersion: version,
|
|
2586
|
+
workingDirectory: workDir
|
|
2587
|
+
});
|
|
2588
|
+
client.setTailscaleInfo(fullTailscale);
|
|
2589
|
+
client.enableAutomation(config.serverUrl, creds.token);
|
|
2590
|
+
client.connect();
|
|
2591
|
+
writePidFile(config.homeDir, process.pid);
|
|
2592
|
+
console.log(`Daemon started (PID ${process.pid})`);
|
|
2593
|
+
let shuttingDown = false;
|
|
2594
|
+
const shutdown = (signal) => {
|
|
2595
|
+
if (shuttingDown) return;
|
|
2596
|
+
shuttingDown = true;
|
|
2597
|
+
logger.debug(`[DAEMON] Received ${signal}, shutting down...`);
|
|
2598
|
+
console.log(`
|
|
2599
|
+
Received ${signal}, shutting down...`);
|
|
2600
|
+
client.shutdown();
|
|
2601
|
+
removePidFile(config.homeDir);
|
|
2602
|
+
process.exit(0);
|
|
2603
|
+
};
|
|
2604
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
2605
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
2606
|
+
await new Promise(() => {
|
|
2607
|
+
});
|
|
2608
|
+
}
|
|
2609
|
+
function stopDaemon() {
|
|
2610
|
+
const config = loadConfig();
|
|
2611
|
+
const pid = readPidFile(config.homeDir);
|
|
2612
|
+
if (!pid) {
|
|
2613
|
+
console.log("No daemon PID file found.");
|
|
2614
|
+
return;
|
|
2615
|
+
}
|
|
2616
|
+
if (!isProcessRunning(pid)) {
|
|
2617
|
+
console.log(`Daemon PID ${pid} is not running (stale PID file). Cleaning up.`);
|
|
2618
|
+
removePidFile(config.homeDir);
|
|
2619
|
+
return;
|
|
2620
|
+
}
|
|
2621
|
+
try {
|
|
2622
|
+
process.kill(pid, "SIGTERM");
|
|
2623
|
+
console.log(`Sent SIGTERM to daemon (PID ${pid})`);
|
|
2624
|
+
removePidFile(config.homeDir);
|
|
2625
|
+
} catch (error) {
|
|
2626
|
+
console.error(`Failed to stop daemon: ${error instanceof Error ? error.message : String(error)}`);
|
|
2627
|
+
process.exitCode = 1;
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
function daemonStatus() {
|
|
2631
|
+
const config = loadConfig();
|
|
2632
|
+
const pid = readPidFile(config.homeDir);
|
|
2633
|
+
if (!pid) {
|
|
2634
|
+
console.log("Daemon is not running (no PID file).");
|
|
2635
|
+
return;
|
|
2636
|
+
}
|
|
2637
|
+
if (isProcessRunning(pid)) {
|
|
2638
|
+
console.log(`Daemon is running (PID ${pid})`);
|
|
2639
|
+
console.log(`PID file: ${pidFilePath(config.homeDir)}`);
|
|
2640
|
+
} else {
|
|
2641
|
+
console.log(`Daemon PID ${pid} is not running (stale PID file).`);
|
|
2642
|
+
console.log(`Run \`happy-agent daemon stop\` to clean up.`);
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
|
|
1722
2646
|
function formatTime(ts) {
|
|
1723
2647
|
if (!ts) return "-";
|
|
1724
2648
|
const date = new Date(ts);
|
|
@@ -2154,9 +3078,22 @@ program.command("machine").description("Manage machine identity").addCommand(
|
|
|
2154
3078
|
}
|
|
2155
3079
|
})
|
|
2156
3080
|
);
|
|
3081
|
+
program.command("daemon").description("Run as a persistent background daemon").addCommand(
|
|
3082
|
+
new Command("start").description("Start the agent daemon (connects to server, handles triggers)").option("--directory <dir>", "Working directory for spawned sessions").option("--foreground", "Run in foreground (do not detach)").action(async (opts) => {
|
|
3083
|
+
await startDaemon(opts);
|
|
3084
|
+
})
|
|
3085
|
+
).addCommand(
|
|
3086
|
+
new Command("stop").description("Stop the running daemon").action(() => {
|
|
3087
|
+
stopDaemon();
|
|
3088
|
+
})
|
|
3089
|
+
).addCommand(
|
|
3090
|
+
new Command("status").description("Check daemon status").action(() => {
|
|
3091
|
+
daemonStatus();
|
|
3092
|
+
})
|
|
3093
|
+
);
|
|
2157
3094
|
program.parseAsync(process.argv).catch((err) => {
|
|
2158
3095
|
console.error(err instanceof Error ? err.message : String(err));
|
|
2159
3096
|
process.exitCode = 1;
|
|
2160
3097
|
});
|
|
2161
3098
|
|
|
2162
|
-
export { MachineClient, RpcHandlerManager, SessionClient, authLogin, authLogout, authStatus, createRpcHandlerManager, createSession, deleteSession, fetchMessagesAfterSeq, getOrCreateMachine, getSessionMessages, listActiveSessions, listMachines, listSessions, loadConfig, readCredentials, requireCredentials, resolveSessionEncryption, sendMessagesBatch };
|
|
3099
|
+
export { MachineClient, RpcHandlerManager, SessionClient, authLogin, authLogout, authStatus, createRpcHandlerManager, createSession, daemonStatus, deleteSession, fetchMessagesAfterSeq, getOrCreateMachine, getSessionMessages, listActiveSessions, listMachines, listSessions, loadConfig, readCredentials, requireCredentials, resolveSessionEncryption, sendMessagesBatch, startDaemon, stopDaemon };
|