@kmmao/happy-agent 0.3.11 → 0.4.1

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 CHANGED
@@ -18,7 +18,7 @@ var path = require('path');
18
18
  var fs = require('fs');
19
19
  var os = require('os');
20
20
 
21
- var version = "0.3.11";
21
+ var version = "0.4.1";
22
22
 
23
23
  function loadConfig() {
24
24
  const serverUrl = (process.env.HAPPY_SERVER_URL ?? "https://happyserve.xycloud.info").replace(/\/+$/, "");
@@ -789,6 +789,7 @@ function createRpcHandlerManager(config) {
789
789
  }
790
790
 
791
791
  const execAsync = util.promisify(child_process.exec);
792
+ const execFileAsync$1 = util.promisify(child_process.execFile);
792
793
  const UPLOAD_TEMP_DIR = path.join(os.tmpdir(), "happy", "uploads");
793
794
  const MAX_WRITE_SIZE = 10 * 1024 * 1024;
794
795
  function validatePath(targetPath, workingDirectory, additionalAllowedDirs) {
@@ -1048,6 +1049,367 @@ function registerAgentHandlers(rpcHandlerManager, workingDirectory, sessionId) {
1048
1049
  await promises.mkdir(uploadDir, { recursive: true });
1049
1050
  return { success: true, path: uploadDir };
1050
1051
  });
1052
+ rpcHandlerManager.registerHandler("getDirectoryTree", async (data) => {
1053
+ logger.debug("Get directory tree request:", data.path, "maxDepth:", data.maxDepth);
1054
+ const validation = validatePath(data.path, workingDirectory);
1055
+ if (!validation.valid) {
1056
+ return { success: false, error: validation.error };
1057
+ }
1058
+ async function buildTree(dirPath, name, currentDepth) {
1059
+ try {
1060
+ const stats = await promises.stat(dirPath);
1061
+ const node = {
1062
+ name,
1063
+ path: dirPath,
1064
+ type: stats.isDirectory() ? "directory" : "file",
1065
+ size: stats.size,
1066
+ modified: stats.mtime.getTime()
1067
+ };
1068
+ if (stats.isDirectory() && currentDepth < data.maxDepth) {
1069
+ const entries = await promises.readdir(dirPath, { withFileTypes: true });
1070
+ const children = [];
1071
+ await Promise.all(
1072
+ entries.map(async (entry) => {
1073
+ if (entry.isSymbolicLink()) return;
1074
+ const childPath = path.join(dirPath, entry.name);
1075
+ const childNode = await buildTree(childPath, entry.name, currentDepth + 1);
1076
+ if (childNode) children.push(childNode);
1077
+ })
1078
+ );
1079
+ children.sort((a, b) => {
1080
+ if (a.type === "directory" && b.type !== "directory") return -1;
1081
+ if (a.type !== "directory" && b.type === "directory") return 1;
1082
+ return a.name.localeCompare(b.name);
1083
+ });
1084
+ node.children = children;
1085
+ }
1086
+ return node;
1087
+ } catch (error) {
1088
+ logger.debug(`Failed to process ${dirPath}:`, error instanceof Error ? error.message : String(error));
1089
+ return null;
1090
+ }
1091
+ }
1092
+ try {
1093
+ if (data.maxDepth < 0) {
1094
+ return { success: false, error: "maxDepth must be non-negative" };
1095
+ }
1096
+ const baseName = data.path === "/" ? "/" : data.path.split("/").pop() || data.path;
1097
+ const tree = await buildTree(data.path, baseName, 0);
1098
+ if (!tree) {
1099
+ return { success: false, error: "Failed to access the specified path" };
1100
+ }
1101
+ return { success: true, tree };
1102
+ } catch (error) {
1103
+ logger.debug("Failed to get directory tree:", error);
1104
+ return {
1105
+ success: false,
1106
+ error: error instanceof Error ? error.message : "Failed to get directory tree"
1107
+ };
1108
+ }
1109
+ });
1110
+ rpcHandlerManager.registerHandler(
1111
+ "ripgrep",
1112
+ async (data) => {
1113
+ const cwd = data.cwd || workingDirectory;
1114
+ if (data.cwd) {
1115
+ const validation = validatePath(data.cwd, workingDirectory);
1116
+ if (!validation.valid) {
1117
+ return { success: false, error: validation.error };
1118
+ }
1119
+ }
1120
+ try {
1121
+ const { stdout, stderr } = await execFileAsync$1("rg", data.args, {
1122
+ cwd,
1123
+ timeout: 3e4,
1124
+ maxBuffer: 10 * 1024 * 1024
1125
+ });
1126
+ return { success: true, stdout: stdout?.toString() ?? "", stderr: stderr?.toString() ?? "", exitCode: 0 };
1127
+ } catch (error) {
1128
+ const e = error;
1129
+ if (e.code === "ENOENT") {
1130
+ return { success: false, error: "ripgrep (rg) is not installed on this machine" };
1131
+ }
1132
+ if (e.code === "1" || e.status === 1) {
1133
+ return { success: true, stdout: e.stdout?.toString() ?? "", stderr: e.stderr?.toString() ?? "", exitCode: 1 };
1134
+ }
1135
+ return {
1136
+ success: false,
1137
+ stdout: e.stdout?.toString() ?? "",
1138
+ stderr: e.stderr?.toString() ?? "",
1139
+ exitCode: typeof e.code === "number" ? e.code : 1,
1140
+ error: e.message ?? "ripgrep failed"
1141
+ };
1142
+ }
1143
+ }
1144
+ );
1145
+ rpcHandlerManager.registerHandler(
1146
+ "difftastic",
1147
+ async (data) => {
1148
+ const cwd = data.cwd || workingDirectory;
1149
+ if (data.cwd) {
1150
+ const validation = validatePath(data.cwd, workingDirectory);
1151
+ if (!validation.valid) {
1152
+ return { success: false, error: validation.error };
1153
+ }
1154
+ }
1155
+ try {
1156
+ const { stdout, stderr } = await execFileAsync$1("difft", data.args, {
1157
+ cwd,
1158
+ timeout: 3e4,
1159
+ maxBuffer: 10 * 1024 * 1024
1160
+ });
1161
+ return { success: true, stdout: stdout?.toString() ?? "", stderr: stderr?.toString() ?? "", exitCode: 0 };
1162
+ } catch (error) {
1163
+ const e = error;
1164
+ if (e.code === "ENOENT") {
1165
+ return { success: false, error: "difftastic (difft) is not installed on this machine" };
1166
+ }
1167
+ return {
1168
+ success: false,
1169
+ stdout: e.stdout?.toString() ?? "",
1170
+ stderr: e.stderr?.toString() ?? "",
1171
+ exitCode: typeof e.code === "number" ? e.code : 1,
1172
+ error: e.message ?? "difftastic failed"
1173
+ };
1174
+ }
1175
+ }
1176
+ );
1177
+ rpcHandlerManager.registerHandler("listRemoteGitRepos", async (data) => {
1178
+ const page = data.page ?? 1;
1179
+ const perPage = data.perPage ?? 30;
1180
+ const query = data.query?.trim() || "";
1181
+ logger.debug("listRemoteGitRepos request:", { provider: data.provider, host: data.host, page, perPage, query });
1182
+ if (!data.apiToken) return { success: false, error: "API token is required" };
1183
+ if (!data.host?.trim()) return { success: false, error: "Host is required" };
1184
+ try {
1185
+ const baseUrl = buildGitApiBase(data.provider, data.host);
1186
+ const headers = buildGitApiHeaders(data.apiToken);
1187
+ let repos;
1188
+ let hasMore;
1189
+ if (data.provider === "github") {
1190
+ const listUrl = `${baseUrl}/user/repos?per_page=${perPage}&page=${page}&sort=updated&affiliation=owner,collaborator,organization_member`;
1191
+ const response = await fetch(listUrl, { headers });
1192
+ if (!response.ok) {
1193
+ const errorText = await response.text().catch(() => "");
1194
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
1195
+ }
1196
+ const items = await response.json();
1197
+ repos = normalizeRemoteRepoEntries(items);
1198
+ hasMore = items.length >= perPage;
1199
+ } else {
1200
+ const searchParams = new URLSearchParams({ sort: "updated", order: "desc", limit: String(perPage), page: String(page) });
1201
+ if (query) searchParams.set("q", query);
1202
+ const searchUrl = `${baseUrl}/repos/search?${searchParams.toString()}`;
1203
+ const response = await fetch(searchUrl, { headers });
1204
+ if (!response.ok) {
1205
+ const errorText = await response.text().catch(() => "");
1206
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
1207
+ }
1208
+ const body = await response.json();
1209
+ const items = Array.isArray(body) ? body : body.data || [];
1210
+ repos = normalizeRemoteRepoEntries(items);
1211
+ hasMore = items.length >= perPage;
1212
+ }
1213
+ return { success: true, repos, hasMore };
1214
+ } catch (error) {
1215
+ logger.debug("listRemoteGitRepos failed:", error);
1216
+ return { success: false, error: error instanceof Error ? error.message : "Failed to load remote repositories" };
1217
+ }
1218
+ });
1219
+ rpcHandlerManager.registerHandler(
1220
+ "cloneGitRepo",
1221
+ async (data) => {
1222
+ logger.debug("cloneGitRepo request:", { repoUrl: data.repoUrl, targetDirectory: data.targetDirectory });
1223
+ if (!data.repoUrl?.trim()) return { success: false, error: "Repository URL is required" };
1224
+ if (!data.targetDirectory?.trim()) return { success: false, error: "Target directory is required" };
1225
+ if (!data.targetDirectory.startsWith("/")) return { success: false, error: "Target directory must be an absolute path" };
1226
+ const coords = parseCloneCoordinates(data.repoUrl);
1227
+ if (!coords) return { success: false, error: "Invalid repository URL" };
1228
+ const repoPath = path.join(path.resolve(data.targetDirectory), coords.repo);
1229
+ try {
1230
+ await promises.mkdir(path.resolve(data.targetDirectory), { recursive: true });
1231
+ try {
1232
+ const existing = await promises.stat(repoPath);
1233
+ if (existing.isDirectory()) {
1234
+ return { success: false, error: `Destination already exists: ${repoPath}` };
1235
+ }
1236
+ } catch {
1237
+ }
1238
+ const cloneUrl = resolveCloneUrl(data.repoUrl, data.host);
1239
+ const options = {
1240
+ cwd: path.resolve(data.targetDirectory),
1241
+ timeout: 3e5,
1242
+ maxBuffer: 4 * 1024 * 1024,
1243
+ env: buildCloneAuthEnv(data.provider, data.apiToken)
1244
+ };
1245
+ const { stdout, stderr } = await execFileAsync$1("git", ["clone", cloneUrl, repoPath], options);
1246
+ return { success: true, repoPath, stdout: stdout?.toString() ?? "", stderr: stderr?.toString() ?? "" };
1247
+ } catch (error) {
1248
+ const e = error;
1249
+ logger.debug("cloneGitRepo failed:", { message: e.message, stderr: e.stderr });
1250
+ return { success: false, repoPath, stdout: e.stdout || "", stderr: e.stderr || "", error: e.message || "Failed to clone repository" };
1251
+ }
1252
+ }
1253
+ );
1254
+ rpcHandlerManager.registerHandler("createRemoteWebhook", async (data) => {
1255
+ logger.debug("createRemoteWebhook request:", { provider: data.provider, repoUrl: data.repoUrl });
1256
+ try {
1257
+ const parsed = parseRepoOwnerFromUrl(data.repoUrl);
1258
+ if (!parsed) return { success: false, error: "Invalid repo URL" };
1259
+ const { origin, owner, repo } = parsed;
1260
+ const isGitHubCom = origin === "https://github.com" || origin === "http://github.com";
1261
+ const baseUrl = data.provider === "github" && isGitHubCom ? "https://api.github.com" : data.provider === "github" ? `${origin}/api/v3` : `${origin}/api/v1`;
1262
+ const headers = {
1263
+ Authorization: `token ${data.apiToken}`,
1264
+ "Content-Type": "application/json",
1265
+ Accept: "application/json"
1266
+ };
1267
+ const hooksEndpoint = `${baseUrl}/repos/${owner}/${repo}/hooks`;
1268
+ const giteaEvents = [
1269
+ "issues",
1270
+ "issue_assign",
1271
+ "issue_label",
1272
+ "issue_milestone",
1273
+ "issue_comment",
1274
+ "pull_request",
1275
+ "pull_request_assign",
1276
+ "pull_request_label",
1277
+ "pull_request_milestone",
1278
+ "pull_request_comment",
1279
+ "pull_request_review",
1280
+ "pull_request_sync"
1281
+ ];
1282
+ const events = data.provider === "gitea" ? giteaEvents : data.events;
1283
+ const listRes = await fetch(hooksEndpoint, { headers });
1284
+ if (listRes.ok) {
1285
+ const hooks = await listRes.json();
1286
+ const existing = hooks.find((h) => h.config.url === data.webhookUrl);
1287
+ if (existing) {
1288
+ const patchRes = await fetch(`${hooksEndpoint}/${existing.id}`, {
1289
+ method: "PATCH",
1290
+ headers,
1291
+ body: JSON.stringify({ config: { url: data.webhookUrl, content_type: "json", secret: data.webhookSecret }, events, active: true })
1292
+ });
1293
+ if (!patchRes.ok) {
1294
+ const errText = await patchRes.text().catch(() => "");
1295
+ return { success: false, error: `PATCH ${patchRes.status}: ${errText}` };
1296
+ }
1297
+ return { success: true, created: false, webhookId: existing.id };
1298
+ }
1299
+ }
1300
+ const createBody = {
1301
+ name: "web",
1302
+ config: { url: data.webhookUrl, content_type: "json", secret: data.webhookSecret },
1303
+ events,
1304
+ active: true
1305
+ };
1306
+ if (data.provider === "gitea") createBody.type = "gitea";
1307
+ const createRes = await fetch(hooksEndpoint, { method: "POST", headers, body: JSON.stringify(createBody) });
1308
+ if (createRes.ok || createRes.status === 201) {
1309
+ const body = await createRes.json().catch(() => ({}));
1310
+ return { success: true, created: true, webhookId: body.id };
1311
+ }
1312
+ const errBody = await createRes.text().catch(() => "");
1313
+ return { success: false, error: `HTTP ${createRes.status}: ${errBody}` };
1314
+ } catch (error) {
1315
+ logger.debug("createRemoteWebhook failed:", error);
1316
+ return { success: false, error: error instanceof Error ? error.message : "Failed to create webhook" };
1317
+ }
1318
+ });
1319
+ rpcHandlerManager.registerHandler("deleteRemoteWebhook", async (data) => {
1320
+ logger.debug("deleteRemoteWebhook request:", { provider: data.provider, repoUrl: data.repoUrl });
1321
+ try {
1322
+ const parsed = parseRepoOwnerFromUrl(data.repoUrl);
1323
+ if (!parsed) return { success: false, error: "Invalid repo URL" };
1324
+ const { origin, owner, repo } = parsed;
1325
+ const isGitHubCom = origin === "https://github.com" || origin === "http://github.com";
1326
+ const baseUrl = data.provider === "github" && isGitHubCom ? "https://api.github.com" : data.provider === "github" ? `${origin}/api/v3` : `${origin}/api/v1`;
1327
+ const headers = { Authorization: `token ${data.apiToken}`, Accept: "application/json" };
1328
+ const hooksEndpoint = `${baseUrl}/repos/${owner}/${repo}/hooks`;
1329
+ const listRes = await fetch(hooksEndpoint, { headers });
1330
+ if (!listRes.ok) return { success: false, error: `List hooks failed: HTTP ${listRes.status}` };
1331
+ const hooks = await listRes.json();
1332
+ const existing = hooks.find((h) => h.config.url === data.webhookUrl);
1333
+ if (!existing) return { success: true, deleted: false };
1334
+ const deleteRes = await fetch(`${hooksEndpoint}/${existing.id}`, { method: "DELETE", headers });
1335
+ if (deleteRes.ok || deleteRes.status === 204) return { success: true, deleted: true };
1336
+ const errBody = await deleteRes.text().catch(() => "");
1337
+ return { success: false, error: `DELETE ${deleteRes.status}: ${errBody}` };
1338
+ } catch (error) {
1339
+ logger.debug("deleteRemoteWebhook failed:", error);
1340
+ return { success: false, error: error instanceof Error ? error.message : "Failed to delete webhook" };
1341
+ }
1342
+ });
1343
+ }
1344
+ function parseHostEntry(host) {
1345
+ const match = host.match(/^(https?):\/\/(.+)/);
1346
+ if (match) return { bare: match[2].replace(/\/$/, ""), protocol: match[1] };
1347
+ return { bare: host.replace(/\/$/, ""), protocol: null };
1348
+ }
1349
+ function buildGitApiBase(provider, host) {
1350
+ const { bare, protocol } = parseHostEntry(host);
1351
+ const normalizedProtocol = protocol ?? "https";
1352
+ const origin = `${normalizedProtocol}://${bare}`;
1353
+ const isGitHubCom = bare === "github.com" || bare === "www.github.com";
1354
+ if (provider === "github") {
1355
+ return isGitHubCom ? "https://api.github.com" : `${origin}/api/v3`;
1356
+ }
1357
+ return `${origin}/api/v1`;
1358
+ }
1359
+ function buildGitApiHeaders(apiToken) {
1360
+ return {
1361
+ Authorization: `token ${apiToken}`,
1362
+ Accept: "application/json",
1363
+ "Content-Type": "application/json"
1364
+ };
1365
+ }
1366
+ function normalizeRemoteRepoEntries(pageRepos) {
1367
+ return pageRepos.filter((repo) => !!repo.name).map((repo) => {
1368
+ const owner = repo.owner?.login || repo.owner?.username || "";
1369
+ const fullName = repo.full_name || (owner ? `${owner}/${repo.name}` : repo.name || "");
1370
+ const htmlUrl = repo.html_url || "";
1371
+ const cloneUrl = repo.clone_url || (htmlUrl ? `${htmlUrl}.git` : "");
1372
+ return { name: repo.name || fullName, fullName, cloneUrl, htmlUrl, private: !!repo.private, updatedAt: repo.updated_at ? Date.parse(repo.updated_at) : null };
1373
+ }).filter((repo) => !!repo.cloneUrl);
1374
+ }
1375
+ function parseCloneCoordinates(repoUrl) {
1376
+ const trimmed = repoUrl.trim();
1377
+ const sshMatch = trimmed.match(/^git@([^:]+):([^/]+)\/([^/.]+?)(?:\.git)?$/);
1378
+ if (sshMatch) return { host: sshMatch[1], owner: sshMatch[2], repo: sshMatch[3] };
1379
+ const sshUrlMatch = trimmed.match(/^ssh:\/\/[^@]+@([^/]+)\/([^/]+)\/([^/.]+?)(?:\.git)?$/);
1380
+ if (sshUrlMatch) return { host: sshUrlMatch[1], owner: sshUrlMatch[2], repo: sshUrlMatch[3] };
1381
+ const httpsMatch = trimmed.match(/^https?:\/\/([^/]+)\/([^/]+)\/([^/.]+?)(?:\.git)?$/);
1382
+ if (httpsMatch) return { host: httpsMatch[1], owner: httpsMatch[2], repo: httpsMatch[3] };
1383
+ return null;
1384
+ }
1385
+ function resolveCloneUrl(repoUrl, configuredHost) {
1386
+ if (/^https?:\/\//.test(repoUrl)) return repoUrl;
1387
+ const coords = parseCloneCoordinates(repoUrl);
1388
+ if (!coords) return repoUrl;
1389
+ const hostEntry = configuredHost ? parseHostEntry(configuredHost) : null;
1390
+ const protocol = hostEntry?.protocol ?? "https";
1391
+ const bareHost = hostEntry?.bare ?? coords.host;
1392
+ return `${protocol}://${bareHost}/${coords.owner}/${coords.repo}.git`;
1393
+ }
1394
+ function buildCloneAuthEnv(provider, apiToken) {
1395
+ if (!apiToken) return void 0;
1396
+ const username = provider === "github" ? "x-access-token" : "oauth2";
1397
+ const authValue = Buffer.from(`${username}:${apiToken}`).toString("base64");
1398
+ return {
1399
+ ...process.env,
1400
+ GIT_CONFIG_COUNT: "1",
1401
+ GIT_CONFIG_KEY_0: "http.extraHeader",
1402
+ GIT_CONFIG_VALUE_0: `Authorization: Basic ${authValue}`
1403
+ };
1404
+ }
1405
+ function parseRepoOwnerFromUrl(repoUrl) {
1406
+ try {
1407
+ const url = new URL(repoUrl);
1408
+ const parts = url.pathname.replace(/^\//, "").replace(/\.git$/, "").split("/");
1409
+ if (parts.length >= 2) return { origin: url.origin, owner: parts[0], repo: parts[1] };
1410
+ } catch {
1411
+ }
1412
+ return null;
1051
1413
  }
1052
1414
 
1053
1415
  class SessionClient extends node_events.EventEmitter {
@@ -1475,6 +1837,364 @@ function isNotFound(err) {
1475
1837
  return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
1476
1838
  }
1477
1839
 
1840
+ const pidToSession = /* @__PURE__ */ new Map();
1841
+ function trackSession(session) {
1842
+ pidToSession.set(session.pid, session);
1843
+ }
1844
+ function untrackSession(pid) {
1845
+ const session = pidToSession.get(pid);
1846
+ pidToSession.delete(pid);
1847
+ return session;
1848
+ }
1849
+ function getTrackedSession(pid) {
1850
+ return pidToSession.get(pid);
1851
+ }
1852
+ function getAllTrackedSessions() {
1853
+ return [...pidToSession.values()];
1854
+ }
1855
+ function getTrackedSessionCount() {
1856
+ return pidToSession.size;
1857
+ }
1858
+
1859
+ var trackedSessions = /*#__PURE__*/Object.freeze({
1860
+ __proto__: null,
1861
+ getAllTrackedSessions: getAllTrackedSessions,
1862
+ getTrackedSession: getTrackedSession,
1863
+ getTrackedSessionCount: getTrackedSessionCount,
1864
+ trackSession: trackSession,
1865
+ untrackSession: untrackSession
1866
+ });
1867
+
1868
+ const execFileAsync = util.promisify(child_process.execFile);
1869
+ const SERVER_INTERNAL_SECRETS = /* @__PURE__ */ new Set([
1870
+ "DATABASE_URL",
1871
+ "REDIS_URL",
1872
+ "JWT_SECRET",
1873
+ "ENCRYPTION_KEY",
1874
+ "GITHUB_CLIENT_SECRET",
1875
+ "AWS_SECRET_ACCESS_KEY",
1876
+ "AWS_ACCESS_KEY_ID",
1877
+ "AWS_SESSION_TOKEN",
1878
+ "STRIPE_SECRET_KEY",
1879
+ "SENDGRID_API_KEY",
1880
+ "S3_ACCESS_KEY",
1881
+ "S3_SECRET_KEY"
1882
+ ]);
1883
+ function buildSpawnEnv(extra) {
1884
+ const base = {};
1885
+ for (const [key, value] of Object.entries(process.env)) {
1886
+ if (!SERVER_INTERNAL_SECRETS.has(key) && key !== "CLAUDECODE") {
1887
+ base[key] = value;
1888
+ }
1889
+ }
1890
+ if (extra) {
1891
+ for (const [key, value] of Object.entries(extra)) {
1892
+ if (value !== void 0) {
1893
+ base[key] = value;
1894
+ }
1895
+ }
1896
+ }
1897
+ return base;
1898
+ }
1899
+ let happyBinaryPath;
1900
+ async function findHappyBinary() {
1901
+ if (happyBinaryPath !== void 0) return happyBinaryPath;
1902
+ try {
1903
+ const { stdout } = await execFileAsync("which", ["happy"]);
1904
+ happyBinaryPath = stdout.trim() || null;
1905
+ } catch {
1906
+ happyBinaryPath = null;
1907
+ }
1908
+ return happyBinaryPath;
1909
+ }
1910
+ async function spawnSession(options) {
1911
+ const {
1912
+ directory,
1913
+ agent = "claude",
1914
+ approvedNewDirectoryCreation = false,
1915
+ happySessionId,
1916
+ automationContext,
1917
+ environmentVariables
1918
+ } = options;
1919
+ const happyPath = await findHappyBinary();
1920
+ if (!happyPath) {
1921
+ return {
1922
+ type: "error",
1923
+ errorMessage: "happy CLI not found. Install with: npm install -g @kmmao/happy-coder"
1924
+ };
1925
+ }
1926
+ try {
1927
+ const dirStat = await promises.stat(directory);
1928
+ if (!dirStat.isDirectory()) {
1929
+ return { type: "error", errorMessage: `Path exists but is not a directory: ${directory}` };
1930
+ }
1931
+ } catch {
1932
+ if (!approvedNewDirectoryCreation) {
1933
+ return { type: "requestToApproveDirectoryCreation", directory };
1934
+ }
1935
+ try {
1936
+ await promises.mkdir(directory, { recursive: true });
1937
+ logger.debug(`[SPAWN] Created directory: ${directory}`);
1938
+ } catch (mkdirError) {
1939
+ return {
1940
+ type: "error",
1941
+ errorMessage: `Failed to create directory: ${mkdirError instanceof Error ? mkdirError.message : String(mkdirError)}`
1942
+ };
1943
+ }
1944
+ }
1945
+ const args = [
1946
+ agent,
1947
+ "--happy-starting-mode",
1948
+ "remote",
1949
+ "--started-by",
1950
+ "daemon"
1951
+ ];
1952
+ if (happySessionId) {
1953
+ args.push("--happy-session-id", happySessionId);
1954
+ }
1955
+ const spawnEnv = buildSpawnEnv(environmentVariables);
1956
+ logger.debug(`[SPAWN] ${happyPath} ${args.join(" ")} in ${directory}`);
1957
+ let happyProcess;
1958
+ try {
1959
+ happyProcess = child_process.spawn(happyPath, args, {
1960
+ cwd: directory,
1961
+ detached: true,
1962
+ stdio: ["ignore", "pipe", "pipe"],
1963
+ env: spawnEnv
1964
+ });
1965
+ } catch (spawnError) {
1966
+ return {
1967
+ type: "error",
1968
+ errorMessage: `Failed to spawn: ${spawnError instanceof Error ? spawnError.message : String(spawnError)}`
1969
+ };
1970
+ }
1971
+ const pid = happyProcess.pid;
1972
+ if (!pid) {
1973
+ return { type: "error", errorMessage: "Spawned process has no PID" };
1974
+ }
1975
+ const tracked = {
1976
+ pid,
1977
+ directory,
1978
+ startedAt: Date.now(),
1979
+ childProcess: happyProcess,
1980
+ lastActivityAt: Date.now(),
1981
+ automationContext
1982
+ };
1983
+ trackSession(tracked);
1984
+ happyProcess.stdout?.on("data", () => {
1985
+ tracked.lastActivityAt = Date.now();
1986
+ });
1987
+ happyProcess.stderr?.on("data", () => {
1988
+ tracked.lastActivityAt = Date.now();
1989
+ });
1990
+ happyProcess.on("exit", (code, signal) => {
1991
+ logger.debug(`[SPAWN] Process ${pid} exited: code=${code} signal=${signal}`);
1992
+ const session = untrackSession(pid);
1993
+ if (session) {
1994
+ session.terminationReason = signal ? `signal:${signal}` : code !== 0 ? `exit:${code}` : "completed";
1995
+ }
1996
+ });
1997
+ happyProcess.unref();
1998
+ logger.debug(`[SPAWN] Spawned PID ${pid} in ${directory}`);
1999
+ return { type: "success", pid, directory };
2000
+ }
2001
+ function stopSession(pid) {
2002
+ const tracked = untrackSession(pid);
2003
+ if (!tracked) {
2004
+ try {
2005
+ process.kill(pid, "SIGTERM");
2006
+ return { stopped: true };
2007
+ } catch {
2008
+ return { stopped: false, error: `No tracked session with PID ${pid}` };
2009
+ }
2010
+ }
2011
+ try {
2012
+ if (tracked.childProcess && !tracked.childProcess.killed) {
2013
+ tracked.childProcess.kill("SIGTERM");
2014
+ } else {
2015
+ process.kill(pid, "SIGTERM");
2016
+ }
2017
+ tracked.terminationReason = "user_stop";
2018
+ logger.debug(`[SPAWN] Stopped session PID ${pid}`);
2019
+ return { stopped: true };
2020
+ } catch (error) {
2021
+ return {
2022
+ stopped: false,
2023
+ error: error instanceof Error ? error.message : "Failed to stop session"
2024
+ };
2025
+ }
2026
+ }
2027
+
2028
+ const PROMPT_DIR = path.join(os.tmpdir(), "happy", "agent-prompts");
2029
+ async function writePromptFile(prefix, content) {
2030
+ await promises.mkdir(PROMPT_DIR, { recursive: true });
2031
+ const filename = `${prefix}-${Date.now()}.md`;
2032
+ const filepath = path.join(PROMPT_DIR, filename);
2033
+ await promises.writeFile(filepath, content, "utf-8");
2034
+ return filepath;
2035
+ }
2036
+ function buildWebhookPrompt(data) {
2037
+ return [
2038
+ `# Issue #${data.issueNumber}: ${data.issueTitle}`,
2039
+ "",
2040
+ `Author: ${data.issueAuthor}`,
2041
+ `Labels: ${data.issueLabels.join(", ") || "none"}`,
2042
+ `URL: ${data.issueUrl}`,
2043
+ "",
2044
+ data.issueBody
2045
+ ].join("\n");
2046
+ }
2047
+ function buildSupervisorPrompt(data) {
2048
+ const parts = [
2049
+ `# Supervisor Run: ${data.runId}`,
2050
+ "",
2051
+ `Trigger: ${data.trigger}`,
2052
+ `Project: ${data.projectId}`
2053
+ ];
2054
+ if (data.mode) parts.push(`Mode: ${data.mode}`);
2055
+ if (data.dimensions?.length) parts.push(`Dimensions: ${data.dimensions.join(", ")}`);
2056
+ if (data.changedFiles?.length) {
2057
+ parts.push("", "## Changed Files", ...data.changedFiles.map((f) => `- ${f}`));
2058
+ }
2059
+ if (data.customRules) parts.push("", "## Custom Rules", data.customRules);
2060
+ return parts.join("\n");
2061
+ }
2062
+ function mapTaskPriority(priority) {
2063
+ if (priority === "urgent" || priority === "high") return "urgent";
2064
+ if (priority === "background" || priority === "low") return "background";
2065
+ return "user";
2066
+ }
2067
+ function handleWebhookTrigger(data, client, serverUrl, authToken, scheduler) {
2068
+ logger.debug(`[TRIGGER] Webhook: issue #${data.issueNumber} in ${data.repoPath}`);
2069
+ const { deduped } = scheduler.enqueue({
2070
+ kind: "webhook",
2071
+ dedupeKey: `webhook:${data.webhookEventId}`,
2072
+ priority: "background",
2073
+ run: async (jobId) => {
2074
+ client.emitWebhookStatus({ webhookEventId: data.webhookEventId, status: "dispatched" });
2075
+ const promptFile = await writePromptFile("webhook", buildWebhookPrompt(data));
2076
+ const result = await spawnSession({
2077
+ directory: data.repoPath,
2078
+ approvedNewDirectoryCreation: false,
2079
+ automationContext: { kind: "webhook", trigger: `issue#${data.issueNumber}` },
2080
+ environmentVariables: {
2081
+ HAPPY_INITIAL_PROMPT_FILE: promptFile,
2082
+ HAPPY_WEBHOOK_EVENT_ID: data.webhookEventId,
2083
+ HAPPY_WEBHOOK_ISSUE_URL: data.issueUrl,
2084
+ HAPPY_SERVER_URL: serverUrl,
2085
+ HAPPY_AUTH_TOKEN: authToken
2086
+ }
2087
+ });
2088
+ if (result.type !== "success") {
2089
+ const msg = result.type === "error" ? result.errorMessage : "Directory creation not approved";
2090
+ client.emitWebhookStatus({ webhookEventId: data.webhookEventId, status: "failed", errorMessage: msg });
2091
+ throw new Error(msg);
2092
+ }
2093
+ const tracked = (await Promise.resolve().then(function () { return trackedSessions; })).getTrackedSession(result.pid);
2094
+ if (tracked?.childProcess) {
2095
+ tracked.childProcess.on("exit", (code) => {
2096
+ if (code === 0) scheduler.markCompleted(jobId);
2097
+ else scheduler.markFailed(jobId, `exit code ${code}`);
2098
+ client.emitWebhookStatus({ webhookEventId: data.webhookEventId, status: code === 0 ? "completed" : "failed" });
2099
+ });
2100
+ }
2101
+ return { pid: result.pid };
2102
+ }
2103
+ });
2104
+ if (deduped) {
2105
+ logger.debug(`[TRIGGER] Webhook deduped: ${data.webhookEventId}`);
2106
+ }
2107
+ }
2108
+ function handleSupervisorTrigger(data, client, serverUrl, authToken, scheduler) {
2109
+ logger.debug(`[TRIGGER] Supervisor: run ${data.runId} in ${data.repoPath}`);
2110
+ const { deduped } = scheduler.enqueue({
2111
+ kind: "supervisor",
2112
+ dedupeKey: `supervisor:${data.runId}`,
2113
+ priority: "background",
2114
+ run: async (jobId) => {
2115
+ client.emitSupervisorRunStatus({ runId: data.runId, projectId: data.projectId, status: "running" });
2116
+ const promptFile = await writePromptFile("supervisor", buildSupervisorPrompt(data));
2117
+ const result = await spawnSession({
2118
+ directory: data.repoPath,
2119
+ approvedNewDirectoryCreation: false,
2120
+ automationContext: { kind: "supervisor", trigger: data.trigger, projectId: data.projectId, runId: data.runId },
2121
+ environmentVariables: {
2122
+ HAPPY_INITIAL_PROMPT_FILE: promptFile,
2123
+ HAPPY_SUPERVISOR_RUN_ID: data.runId,
2124
+ HAPPY_SUPERVISOR_PROJECT_ID: data.projectId,
2125
+ HAPPY_SUPERVISOR_SERVER_URL: serverUrl,
2126
+ HAPPY_SUPERVISOR_AUTH_TOKEN: authToken
2127
+ }
2128
+ });
2129
+ if (result.type !== "success") {
2130
+ const msg = result.type === "error" ? result.errorMessage : "Directory creation not approved";
2131
+ client.emitSupervisorRunStatus({ runId: data.runId, projectId: data.projectId, status: "failed", errorMessage: msg });
2132
+ throw new Error(msg);
2133
+ }
2134
+ const tracked = (await Promise.resolve().then(function () { return trackedSessions; })).getTrackedSession(result.pid);
2135
+ if (tracked?.childProcess) {
2136
+ tracked.childProcess.on("exit", (code) => {
2137
+ const status = code === 0 ? "completed" : "failed";
2138
+ if (code === 0) scheduler.markCompleted(jobId);
2139
+ else scheduler.markFailed(jobId, `exit code ${code}`);
2140
+ client.emitSupervisorRunStatus({ runId: data.runId, projectId: data.projectId, status });
2141
+ });
2142
+ }
2143
+ return { pid: result.pid };
2144
+ }
2145
+ });
2146
+ if (deduped) {
2147
+ logger.debug(`[TRIGGER] Supervisor deduped: ${data.runId}`);
2148
+ }
2149
+ }
2150
+ function handleTaskTrigger(data, serverUrl, _authToken, scheduler) {
2151
+ logger.debug(`[TRIGGER] Task: ${data.taskId} in ${data.directory}`);
2152
+ const { deduped } = scheduler.enqueue({
2153
+ kind: "task",
2154
+ dedupeKey: `task:${data.taskId}`,
2155
+ priority: mapTaskPriority(data.priority),
2156
+ run: async (jobId) => {
2157
+ const promptFile = await writePromptFile("task", data.prompt);
2158
+ const skillEnv = {};
2159
+ if (data.skillContents?.length) {
2160
+ skillEnv.HAPPY_TASK_SKILL_COUNT = String(data.skillContents.length);
2161
+ for (let i = 0; i < data.skillContents.length; i++) {
2162
+ skillEnv[`HAPPY_TASK_SKILL_${i}_NAME`] = data.skillContents[i].name;
2163
+ skillEnv[`HAPPY_TASK_SKILL_${i}_CONTENT`] = data.skillContents[i].content;
2164
+ }
2165
+ }
2166
+ const result = await spawnSession({
2167
+ directory: data.directory,
2168
+ approvedNewDirectoryCreation: true,
2169
+ automationContext: { kind: "task", trigger: "task-dispatch", projectId: data.projectId },
2170
+ environmentVariables: {
2171
+ HAPPY_INITIAL_PROMPT_FILE: promptFile,
2172
+ HAPPY_TASK_ID: data.taskId,
2173
+ HAPPY_TASK_PRIORITY: data.priority,
2174
+ HAPPY_TASK_SERVER_URL: serverUrl,
2175
+ HAPPY_TASK_RESULT_TOKEN: data.resultToken ?? "",
2176
+ HAPPY_TASK_REPORT_URL: `${serverUrl}/v1/tasks/${data.taskId}/result`,
2177
+ ...skillEnv
2178
+ }
2179
+ });
2180
+ if (result.type !== "success") {
2181
+ throw new Error(result.type === "error" ? result.errorMessage : "Directory creation not approved");
2182
+ }
2183
+ const tracked = (await Promise.resolve().then(function () { return trackedSessions; })).getTrackedSession(result.pid);
2184
+ if (tracked?.childProcess) {
2185
+ tracked.childProcess.on("exit", (code) => {
2186
+ if (code === 0) scheduler.markCompleted(jobId);
2187
+ else scheduler.markFailed(jobId, `exit code ${code}`);
2188
+ });
2189
+ }
2190
+ return { pid: result.pid };
2191
+ }
2192
+ });
2193
+ if (deduped) {
2194
+ logger.debug(`[TRIGGER] Task deduped: ${data.taskId}`);
2195
+ }
2196
+ }
2197
+
1478
2198
  const TAILSCALE_REFRESH_MS = 5 * 60 * 1e3;
1479
2199
  class MachineClient {
1480
2200
  machine;
@@ -1486,11 +2206,18 @@ class MachineClient {
1486
2206
  tunnelManager = null;
1487
2207
  token;
1488
2208
  serverUrl;
2209
+ agentVersion;
2210
+ startTime = Date.now();
1489
2211
  onEphemeral;
2212
+ automationEnabled = false;
2213
+ automationServerUrl = "";
2214
+ automationAuthToken = "";
2215
+ scheduler = null;
1490
2216
  constructor(opts) {
1491
2217
  this.token = opts.token;
1492
2218
  this.machine = opts.machine;
1493
2219
  this.serverUrl = opts.serverUrl;
2220
+ this.agentVersion = opts.agentVersion ?? "unknown";
1494
2221
  this.onEphemeral = opts.onEphemeral;
1495
2222
  this.rpcHandlerManager = new RpcHandlerManager({
1496
2223
  scopePrefix: opts.machine.id,
@@ -1500,6 +2227,32 @@ class MachineClient {
1500
2227
  });
1501
2228
  const workDir = opts.workingDirectory ?? process.cwd();
1502
2229
  registerAgentHandlers(this.rpcHandlerManager, workDir, opts.machine.id);
2230
+ this.registerMachineHandlers();
2231
+ }
2232
+ // -----------------------------------------------------------------------
2233
+ // Machine-scoped RPC handlers
2234
+ // -----------------------------------------------------------------------
2235
+ registerMachineHandlers() {
2236
+ this.rpcHandlerManager.registerHandler(
2237
+ "spawn-happy-session",
2238
+ async (data) => {
2239
+ logger.debug("[MACHINE] spawn-happy-session request:", data.directory);
2240
+ return spawnSession(data);
2241
+ }
2242
+ );
2243
+ this.rpcHandlerManager.registerHandler("stop-session", async (data) => {
2244
+ logger.debug("[MACHINE] stop-session request:", data.pid);
2245
+ return stopSession(data.pid);
2246
+ });
2247
+ this.rpcHandlerManager.registerHandler("list-tracked-sessions", async () => {
2248
+ const sessions = getAllTrackedSessions().map((s) => ({
2249
+ pid: s.pid,
2250
+ directory: s.directory,
2251
+ startedAt: s.startedAt,
2252
+ happySessionId: s.happySessionId
2253
+ }));
2254
+ return { sessions };
2255
+ });
1503
2256
  }
1504
2257
  // -----------------------------------------------------------------------
1505
2258
  // Connection
@@ -1526,6 +2279,8 @@ class MachineClient {
1526
2279
  status: "running",
1527
2280
  pid: process.pid,
1528
2281
  startedAt: Date.now(),
2282
+ startTime: this.startTime,
2283
+ startedWithCliVersion: this.agentVersion,
1529
2284
  tailscale: this.lastTailscaleInfo ?? state?.tailscale
1530
2285
  }));
1531
2286
  this.startKeepAlive();
@@ -1565,12 +2320,12 @@ class MachineClient {
1565
2320
  }
1566
2321
  }
1567
2322
  });
1568
- if (this.onEphemeral) {
1569
- this.socket.on("ephemeral", (data) => {
1570
- logger.debug("[MACHINE] Received ephemeral event:", data.type);
1571
- this.onEphemeral?.(data);
1572
- });
1573
- }
2323
+ this.socket.on("ephemeral", (data) => {
2324
+ const event = data;
2325
+ logger.debug("[MACHINE] Received ephemeral event:", event.type);
2326
+ this.onEphemeral?.(event);
2327
+ this.handleAutomationEvent(event);
2328
+ });
1574
2329
  this.socket.on("connect_error", (error) => {
1575
2330
  logger.debug(`[MACHINE] Connection error: ${error.message}`);
1576
2331
  });
@@ -1647,6 +2402,79 @@ class MachineClient {
1647
2402
  }, { maxRetries: 3, label: "updateDaemonState" });
1648
2403
  }
1649
2404
  // -----------------------------------------------------------------------
2405
+ // Socket event emitters
2406
+ // -----------------------------------------------------------------------
2407
+ /** Emit a session lifecycle event. */
2408
+ emitSessionEvent(sessionId, eventType, summary, detail) {
2409
+ this.socket?.emit("session-event", { sessionId, eventType, summary, detail });
2410
+ }
2411
+ /** Report webhook processing status. */
2412
+ emitWebhookStatus(data) {
2413
+ this.socket?.emit("webhook-status", data);
2414
+ }
2415
+ /** Report supervisor run status. */
2416
+ emitSupervisorRunStatus(data) {
2417
+ this.socket?.emit("supervisor-run-status", data);
2418
+ }
2419
+ /** Submit a knowledge entry from a session. */
2420
+ emitSubmitKnowledge(sid, entry) {
2421
+ this.socket?.emit("submit-knowledge", { sid, entry });
2422
+ }
2423
+ /** Fetch knowledge for a session. */
2424
+ emitFetchKnowledge(sid, mode, contextHints, callback) {
2425
+ this.socket?.emit("fetch-knowledge", { sid, mode, contextHints }, callback);
2426
+ }
2427
+ /** Stream task log chunk. */
2428
+ emitTaskLog(sid, taskId, outputFile, chunk, offset) {
2429
+ this.socket?.emit("task-log", { sid, taskId, outputFile, chunk, offset });
2430
+ }
2431
+ // -----------------------------------------------------------------------
2432
+ // Automation triggers
2433
+ // -----------------------------------------------------------------------
2434
+ /**
2435
+ * Enable automation handling — agent will process webhook, supervisor,
2436
+ * and task triggers from the server by spawning Happy CLI sessions.
2437
+ */
2438
+ enableAutomation(serverUrl, authToken, scheduler) {
2439
+ this.automationEnabled = true;
2440
+ this.automationServerUrl = serverUrl;
2441
+ this.automationAuthToken = authToken;
2442
+ this.scheduler = scheduler;
2443
+ logger.debug("[MACHINE] Automation enabled");
2444
+ }
2445
+ /** Internal dispatch for ephemeral events that need automation handling. */
2446
+ handleAutomationEvent(event) {
2447
+ if (!this.automationEnabled || !this.scheduler) return;
2448
+ switch (event.type) {
2449
+ case "webhook-trigger":
2450
+ handleWebhookTrigger(
2451
+ event,
2452
+ this,
2453
+ this.automationServerUrl,
2454
+ this.automationAuthToken,
2455
+ this.scheduler
2456
+ );
2457
+ break;
2458
+ case "supervisor-trigger":
2459
+ handleSupervisorTrigger(
2460
+ event,
2461
+ this,
2462
+ this.automationServerUrl,
2463
+ this.automationAuthToken,
2464
+ this.scheduler
2465
+ );
2466
+ break;
2467
+ case "task-trigger":
2468
+ handleTaskTrigger(
2469
+ event,
2470
+ this.automationServerUrl,
2471
+ this.automationAuthToken,
2472
+ this.scheduler
2473
+ );
2474
+ break;
2475
+ }
2476
+ }
2477
+ // -----------------------------------------------------------------------
1650
2478
  // Lifecycle
1651
2479
  // -----------------------------------------------------------------------
1652
2480
  /** Seed initial Tailscale info detected before connect. */
@@ -1721,6 +2549,306 @@ function tailscaleChanged(prev, next) {
1721
2549
  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);
1722
2550
  }
1723
2551
 
2552
+ const PRIORITY_ORDER = {
2553
+ urgent: 0,
2554
+ user: 1,
2555
+ background: 2
2556
+ };
2557
+ const ACTIVE_STATUSES = /* @__PURE__ */ new Set(["queued", "dispatching", "running"]);
2558
+ class AutomationScheduler {
2559
+ maxConcurrentJobs;
2560
+ retryDelayMs;
2561
+ defaultMaxAttempts;
2562
+ maxRecentCompletions;
2563
+ /** Active jobs indexed by id. */
2564
+ jobs = /* @__PURE__ */ new Map();
2565
+ /** dedupeKey → jobId for fast dedup lookups. */
2566
+ dedupeIndex = /* @__PURE__ */ new Map();
2567
+ /** Ring buffer for completed/failed jobs. */
2568
+ recentCompletions = [];
2569
+ pumpTimer = null;
2570
+ pumping = false;
2571
+ constructor(options) {
2572
+ this.maxConcurrentJobs = options?.maxConcurrentJobs ?? 2;
2573
+ this.retryDelayMs = options?.retryDelayMs ?? 5e3;
2574
+ this.defaultMaxAttempts = options?.maxAttempts ?? 3;
2575
+ this.maxRecentCompletions = options?.maxRecentCompletions ?? 50;
2576
+ this.pumpTimer = setInterval(() => this.pump(), 1e3);
2577
+ }
2578
+ // -----------------------------------------------------------------------
2579
+ // Public API
2580
+ // -----------------------------------------------------------------------
2581
+ enqueue(opts) {
2582
+ const existingId = this.dedupeIndex.get(opts.dedupeKey);
2583
+ if (existingId) {
2584
+ const existing = this.jobs.get(existingId);
2585
+ if (existing && ACTIVE_STATUSES.has(existing.status)) {
2586
+ logger.debug(`[SCHEDULER] Deduped: ${opts.dedupeKey} (job ${existingId} is ${existing.status})`);
2587
+ return { job: existing, deduped: true };
2588
+ }
2589
+ }
2590
+ const job = {
2591
+ id: crypto.randomUUID(),
2592
+ kind: opts.kind,
2593
+ dedupeKey: opts.dedupeKey,
2594
+ priority: opts.priority,
2595
+ status: "queued",
2596
+ attempt: 0,
2597
+ maxAttempts: this.defaultMaxAttempts,
2598
+ createdAt: Date.now(),
2599
+ updatedAt: Date.now(),
2600
+ nextRunAt: Date.now(),
2601
+ run: opts.run
2602
+ };
2603
+ this.jobs.set(job.id, job);
2604
+ this.dedupeIndex.set(job.dedupeKey, job.id);
2605
+ logger.debug(`[SCHEDULER] Enqueued: ${job.kind} ${job.dedupeKey} (${job.priority}) id=${job.id}`);
2606
+ this.pump();
2607
+ return { job, deduped: false };
2608
+ }
2609
+ markCompleted(jobId) {
2610
+ const job = this.jobs.get(jobId);
2611
+ if (!job || job.status === "completed" || job.status === "failed") return;
2612
+ job.status = "completed";
2613
+ job.updatedAt = Date.now();
2614
+ logger.debug(`[SCHEDULER] Completed: ${job.kind} ${job.dedupeKey} id=${jobId}`);
2615
+ this.finalize(job);
2616
+ }
2617
+ markFailed(jobId, error) {
2618
+ const job = this.jobs.get(jobId);
2619
+ if (!job || job.status === "completed" || job.status === "failed") return;
2620
+ job.errorMessage = error;
2621
+ job.updatedAt = Date.now();
2622
+ if (job.attempt < job.maxAttempts) {
2623
+ job.status = "queued";
2624
+ job.nextRunAt = Date.now() + job.attempt * this.retryDelayMs;
2625
+ logger.debug(`[SCHEDULER] Retry queued: ${job.dedupeKey} attempt=${job.attempt}/${job.maxAttempts} nextRunAt=+${job.attempt * this.retryDelayMs}ms`);
2626
+ this.pump();
2627
+ return;
2628
+ }
2629
+ job.status = "failed";
2630
+ logger.debug(`[SCHEDULER] Failed (exhausted): ${job.kind} ${job.dedupeKey} id=${jobId}: ${error}`);
2631
+ this.finalize(job);
2632
+ }
2633
+ getStatus() {
2634
+ let queueLength = 0;
2635
+ let runningCount = 0;
2636
+ for (const job of this.jobs.values()) {
2637
+ if (job.status === "queued") queueLength++;
2638
+ else if (job.status === "dispatching" || job.status === "running") runningCount++;
2639
+ }
2640
+ return {
2641
+ queueLength,
2642
+ runningCount,
2643
+ recentCompletions: [...this.recentCompletions]
2644
+ };
2645
+ }
2646
+ shutdown() {
2647
+ if (this.pumpTimer) {
2648
+ clearInterval(this.pumpTimer);
2649
+ this.pumpTimer = null;
2650
+ }
2651
+ }
2652
+ // -----------------------------------------------------------------------
2653
+ // Internal
2654
+ // -----------------------------------------------------------------------
2655
+ pump() {
2656
+ if (this.pumping) return;
2657
+ this.pumping = true;
2658
+ try {
2659
+ const now = Date.now();
2660
+ let runningCount = 0;
2661
+ for (const job of this.jobs.values()) {
2662
+ if (job.status === "dispatching" || job.status === "running") runningCount++;
2663
+ }
2664
+ if (runningCount >= this.maxConcurrentJobs) return;
2665
+ const ready = [];
2666
+ for (const job of this.jobs.values()) {
2667
+ if (job.status === "queued" && job.nextRunAt <= now) {
2668
+ ready.push(job);
2669
+ }
2670
+ }
2671
+ ready.sort((a, b) => {
2672
+ const pDiff = PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority];
2673
+ if (pDiff !== 0) return pDiff;
2674
+ return a.createdAt - b.createdAt;
2675
+ });
2676
+ const slotsAvailable = this.maxConcurrentJobs - runningCount;
2677
+ const toDispatch = ready.slice(0, slotsAvailable);
2678
+ for (const job of toDispatch) {
2679
+ this.dispatch(job);
2680
+ }
2681
+ } finally {
2682
+ this.pumping = false;
2683
+ }
2684
+ }
2685
+ dispatch(job) {
2686
+ job.status = "dispatching";
2687
+ job.attempt++;
2688
+ job.updatedAt = Date.now();
2689
+ logger.debug(`[SCHEDULER] Dispatching: ${job.kind} ${job.dedupeKey} attempt=${job.attempt}`);
2690
+ job.run(job.id).then(({ pid }) => {
2691
+ if (job.status === "dispatching") {
2692
+ job.status = "running";
2693
+ job.pid = pid;
2694
+ job.updatedAt = Date.now();
2695
+ logger.debug(`[SCHEDULER] Running: ${job.dedupeKey} pid=${pid}`);
2696
+ }
2697
+ }).catch((error) => {
2698
+ const msg = error instanceof Error ? error.message : String(error);
2699
+ logger.debug(`[SCHEDULER] Dispatch failed: ${job.dedupeKey}: ${msg}`);
2700
+ if (job.status === "dispatching") {
2701
+ this.markFailed(job.id, msg);
2702
+ }
2703
+ });
2704
+ }
2705
+ finalize(job) {
2706
+ this.jobs.delete(job.id);
2707
+ if (this.dedupeIndex.get(job.dedupeKey) === job.id) {
2708
+ this.dedupeIndex.delete(job.dedupeKey);
2709
+ }
2710
+ this.recentCompletions.push({
2711
+ id: job.id,
2712
+ kind: job.kind,
2713
+ dedupeKey: job.dedupeKey,
2714
+ status: job.status,
2715
+ completedAt: job.updatedAt,
2716
+ errorMessage: job.errorMessage
2717
+ });
2718
+ while (this.recentCompletions.length > this.maxRecentCompletions) {
2719
+ this.recentCompletions.shift();
2720
+ }
2721
+ this.pump();
2722
+ }
2723
+ }
2724
+
2725
+ function pidFilePath(homeDir) {
2726
+ return node_path.join(homeDir, "agent-daemon.pid");
2727
+ }
2728
+ function writePidFile(homeDir, pid) {
2729
+ node_fs.mkdirSync(homeDir, { recursive: true });
2730
+ node_fs.writeFileSync(pidFilePath(homeDir), String(pid), "utf-8");
2731
+ }
2732
+ function readPidFile(homeDir) {
2733
+ try {
2734
+ const raw = node_fs.readFileSync(pidFilePath(homeDir), "utf-8").trim();
2735
+ const pid = parseInt(raw, 10);
2736
+ return isNaN(pid) ? null : pid;
2737
+ } catch {
2738
+ return null;
2739
+ }
2740
+ }
2741
+ function removePidFile(homeDir) {
2742
+ try {
2743
+ node_fs.unlinkSync(pidFilePath(homeDir));
2744
+ } catch {
2745
+ }
2746
+ }
2747
+ function isProcessRunning(pid) {
2748
+ try {
2749
+ process.kill(pid, 0);
2750
+ return true;
2751
+ } catch {
2752
+ return false;
2753
+ }
2754
+ }
2755
+ async function startDaemon(options) {
2756
+ const config = loadConfig();
2757
+ const creds = requireCredentials(config);
2758
+ const existingPid = readPidFile(config.homeDir);
2759
+ if (existingPid && isProcessRunning(existingPid)) {
2760
+ console.log(`Daemon already running (PID ${existingPid})`);
2761
+ process.exitCode = 1;
2762
+ return;
2763
+ }
2764
+ if (existingPid) {
2765
+ removePidFile(config.homeDir);
2766
+ }
2767
+ const workDir = options.directory ?? process.cwd();
2768
+ console.log(`Starting agent daemon in ${workDir}...`);
2769
+ const metadata = {
2770
+ host: node_os.hostname(),
2771
+ platform: process.platform,
2772
+ happyCliVersion: version,
2773
+ homeDir: config.homeDir,
2774
+ happyHomeDir: config.homeDir,
2775
+ happyLibDir: config.homeDir
2776
+ };
2777
+ const machine = await getOrCreateMachine(config, creds, metadata);
2778
+ console.log(`Machine: ${machine.id} (${machine.metadata.host})`);
2779
+ const tailscaleInfo = await detectTailscale();
2780
+ const serves = tailscaleInfo.status === "connected" ? await detectTailscaleServe() : [];
2781
+ const fullTailscale = { ...tailscaleInfo, serves };
2782
+ if (tailscaleInfo.status === "connected") {
2783
+ console.log(`Tailscale: ${tailscaleInfo.hostname} (${tailscaleInfo.ipv4})`);
2784
+ }
2785
+ const client = new MachineClient({
2786
+ token: creds.token,
2787
+ machine,
2788
+ serverUrl: config.serverUrl,
2789
+ agentVersion: version,
2790
+ workingDirectory: workDir
2791
+ });
2792
+ const scheduler = new AutomationScheduler({ maxConcurrentJobs: 2 });
2793
+ client.setTailscaleInfo(fullTailscale);
2794
+ client.enableAutomation(config.serverUrl, creds.token, scheduler);
2795
+ client.connect();
2796
+ writePidFile(config.homeDir, process.pid);
2797
+ console.log(`Daemon started (PID ${process.pid})`);
2798
+ let shuttingDown = false;
2799
+ const shutdown = (signal) => {
2800
+ if (shuttingDown) return;
2801
+ shuttingDown = true;
2802
+ logger.debug(`[DAEMON] Received ${signal}, shutting down...`);
2803
+ console.log(`
2804
+ Received ${signal}, shutting down...`);
2805
+ scheduler.shutdown();
2806
+ client.shutdown();
2807
+ removePidFile(config.homeDir);
2808
+ process.exit(0);
2809
+ };
2810
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
2811
+ process.on("SIGINT", () => shutdown("SIGINT"));
2812
+ await new Promise(() => {
2813
+ });
2814
+ }
2815
+ function stopDaemon() {
2816
+ const config = loadConfig();
2817
+ const pid = readPidFile(config.homeDir);
2818
+ if (!pid) {
2819
+ console.log("No daemon PID file found.");
2820
+ return;
2821
+ }
2822
+ if (!isProcessRunning(pid)) {
2823
+ console.log(`Daemon PID ${pid} is not running (stale PID file). Cleaning up.`);
2824
+ removePidFile(config.homeDir);
2825
+ return;
2826
+ }
2827
+ try {
2828
+ process.kill(pid, "SIGTERM");
2829
+ console.log(`Sent SIGTERM to daemon (PID ${pid})`);
2830
+ removePidFile(config.homeDir);
2831
+ } catch (error) {
2832
+ console.error(`Failed to stop daemon: ${error instanceof Error ? error.message : String(error)}`);
2833
+ process.exitCode = 1;
2834
+ }
2835
+ }
2836
+ function daemonStatus() {
2837
+ const config = loadConfig();
2838
+ const pid = readPidFile(config.homeDir);
2839
+ if (!pid) {
2840
+ console.log("Daemon is not running (no PID file).");
2841
+ return;
2842
+ }
2843
+ if (isProcessRunning(pid)) {
2844
+ console.log(`Daemon is running (PID ${pid})`);
2845
+ console.log(`PID file: ${pidFilePath(config.homeDir)}`);
2846
+ } else {
2847
+ console.log(`Daemon PID ${pid} is not running (stale PID file).`);
2848
+ console.log(`Run \`happy-agent daemon stop\` to clean up.`);
2849
+ }
2850
+ }
2851
+
1724
2852
  function formatTime(ts) {
1725
2853
  if (!ts) return "-";
1726
2854
  const date = new Date(ts);
@@ -2156,6 +3284,19 @@ program.command("machine").description("Manage machine identity").addCommand(
2156
3284
  }
2157
3285
  })
2158
3286
  );
3287
+ program.command("daemon").description("Run as a persistent background daemon").addCommand(
3288
+ new commander.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) => {
3289
+ await startDaemon(opts);
3290
+ })
3291
+ ).addCommand(
3292
+ new commander.Command("stop").description("Stop the running daemon").action(() => {
3293
+ stopDaemon();
3294
+ })
3295
+ ).addCommand(
3296
+ new commander.Command("status").description("Check daemon status").action(() => {
3297
+ daemonStatus();
3298
+ })
3299
+ );
2159
3300
  program.parseAsync(process.argv).catch((err) => {
2160
3301
  console.error(err instanceof Error ? err.message : String(err));
2161
3302
  process.exitCode = 1;
@@ -2169,6 +3310,7 @@ exports.authLogout = authLogout;
2169
3310
  exports.authStatus = authStatus;
2170
3311
  exports.createRpcHandlerManager = createRpcHandlerManager;
2171
3312
  exports.createSession = createSession;
3313
+ exports.daemonStatus = daemonStatus;
2172
3314
  exports.deleteSession = deleteSession;
2173
3315
  exports.fetchMessagesAfterSeq = fetchMessagesAfterSeq;
2174
3316
  exports.getOrCreateMachine = getOrCreateMachine;
@@ -2181,3 +3323,5 @@ exports.readCredentials = readCredentials;
2181
3323
  exports.requireCredentials = requireCredentials;
2182
3324
  exports.resolveSessionEncryption = resolveSessionEncryption;
2183
3325
  exports.sendMessagesBatch = sendMessagesBatch;
3326
+ exports.startDaemon = startDaemon;
3327
+ exports.stopDaemon = stopDaemon;