very-happy-cli 0.2.153 → 0.2.155
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AcpBackend-YDGv4E-g.mjs → AcpBackend-DVB0nzgR.mjs} +2 -2
- package/dist/{AcpBackend-DSt8nTYm.cjs → AcpBackend-DmFcRh54.cjs} +3 -3
- package/dist/{AcpSessionManager-uov6I9C8.cjs → AcpSessionManager-CWaSYTnT.cjs} +1 -1
- package/dist/{AcpSessionManager-Cxf5HQX1.mjs → AcpSessionManager-dGDgNb-p.mjs} +1 -1
- package/dist/agentGuidance-BWxFC6UL.mjs +1613 -0
- package/dist/agentGuidance-un7YPryB.cjs +1665 -0
- package/dist/{agentHome-D68Xh2ae.mjs → agentHome-ByLb2HFg.mjs} +5 -5
- package/dist/{agentHome-BJ7bde35.cjs → agentHome-aucT8BHw.cjs} +5 -5
- package/dist/{auto-CcXxfqkC.mjs → auto-BQnD6gVx.mjs} +21 -21
- package/dist/{auto-C-90ojIH.cjs → auto-P9RoJaY0.cjs} +24 -24
- package/dist/codex/happyMcpStdioBridge.cjs +6 -3
- package/dist/codex/happyMcpStdioBridge.mjs +6 -3
- package/dist/{config-CHJ189UJ.mjs → config-BPZ2Y6o8.mjs} +8 -8
- package/dist/{config-D23kF0_u.cjs → config-BoePh9PX.cjs} +8 -8
- package/dist/{index-D49WvbDT.cjs → index--KCpVs1c.cjs} +7 -7
- package/dist/{index-BacwoXzs.mjs → index-B4oXnbYw.mjs} +522 -729
- package/dist/{index-BgYZGODP.mjs → index-BjzdXb9x.mjs} +21 -13
- package/dist/{index-DEOVn46R.cjs → index-DRrLaljt.cjs} +21 -13
- package/dist/{index-BXA9fxbK.mjs → index-DVVRqaVG.mjs} +7 -7
- package/dist/{index-DHrwHxHf.cjs → index-D_fYUxVg.cjs} +579 -798
- package/dist/index.cjs +6 -6
- package/dist/index.mjs +6 -6
- package/dist/{install-BiOXBnnS.cjs → install-CGigiocs.cjs} +1 -1
- package/dist/{install-Ca7_Z3bV.mjs → install-DP5aPNEX.mjs} +1 -1
- package/dist/{installTerminalHooks-BF0kL0ae.cjs → installTerminalHooks-XrcPvfBs.cjs} +5 -5
- package/dist/{installTerminalHooks-Bpl32K75.mjs → installTerminalHooks-tIg7mANc.mjs} +5 -5
- package/dist/lib.cjs +2 -2
- package/dist/lib.mjs +2 -2
- package/dist/{limits-BtAuKRl2.mjs → limits-C_DW0M0q.mjs} +309 -13
- package/dist/{limits-DY_sFA3J.cjs → limits-DkfHJ3nS.cjs} +329 -12
- package/dist/{mcp-JpqI2POW.cjs → mcp-BqlXl10F.cjs} +23 -23
- package/dist/{mcp-DQkmk4VV.mjs → mcp-o7QglAQM.mjs} +17 -17
- package/dist/{piRuntime-DRbbeQ72.cjs → piRuntime-BxP4B_zY.cjs} +2 -2
- package/dist/{piRuntime-DBpe12NN.mjs → piRuntime-MjiJI-nV.mjs} +2 -2
- package/dist/{piTerminal-qdJ9KZVL.cjs → piTerminal-DYzRcwgb.cjs} +6 -6
- package/dist/{piTerminal-BoHvPEZ_.mjs → piTerminal-Dpq6yqKU.mjs} +6 -6
- package/dist/{runGemini-CtOEFvhf.cjs → runGemini-8Pxh94Fm.cjs} +7 -7
- package/dist/{runGemini-YqH7a-7O.mjs → runGemini-CDlcQ-OA.mjs} +6 -6
- package/dist/{runOpenClaw-DoqZXBvL.cjs → runOpenClaw-B5FSZIbK.cjs} +6 -6
- package/dist/{runOpenClaw-DSSyFQBb.mjs → runOpenClaw-YkhsgPs0.mjs} +5 -5
- package/dist/{send-9075kHZP.cjs → send-CwrYXTPr.cjs} +58 -54
- package/dist/{send-Cs-RwqNf.mjs → send-DJStmLBv.mjs} +56 -53
- package/dist/{sessions-iBnYzVUK.mjs → sessions-JaVXlSqj.mjs} +88 -45
- package/dist/{sessions-qULzUzlI.cjs → sessions-MX21NJXd.cjs} +99 -56
- package/dist/{spawn-C6fRkedx.mjs → spawn-BaPnjClT.mjs} +22 -22
- package/dist/{spawn-od9V23cc.cjs → spawn-cIoglKVf.cjs} +30 -30
- package/dist/{teams-CkrWQ4uM.mjs → teams-DXV5Pwwt.mjs} +8 -8
- package/dist/{teams-CrCzU-AV.cjs → teams-Dqk7F3D-.cjs} +8 -8
- package/dist/{todo-aCZmSt27.mjs → todo-2Z1REhfx.mjs} +8 -6
- package/dist/{todo-BCT_ZPuV.cjs → todo-Buuqn9gm.cjs} +8 -6
- package/dist/{types-BvqOVUOW.mjs → types-CkbfdRzq.mjs} +7 -267
- package/dist/{types-CUCU7Vw8.cjs → types-a2xsH2UI.cjs} +19 -295
- package/package.json +7 -7
- package/dist/agentGuidance-BM4kMNyr.cjs +0 -553
- package/dist/agentGuidance-C8unGWp7.mjs +0 -529
|
@@ -0,0 +1,1613 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { G as normalizeHttpEndpoint, c as configuration, r as readSettings, d as readPersistedSessions, h as readCredentialsForConfiguredRelay, H as AutomationNameSchema, I as AutomationConcurrencySchema, J as AutomationActionSchema, K as AutomationTriggerSchema, w as encodeBase64, L as encrypt, M as decodeBase64, g as delay, N as decrypt, O as listDaemonSessions, n as stopDaemonSession, P as resumeDaemonSession, i as isValidSessionId, Q as listDaemonPeers } from './limits-C_DW0M0q.mjs';
|
|
4
|
+
import { open, mkdir, rename, unlink } from 'node:fs/promises';
|
|
5
|
+
import { constants, existsSync, readFileSync, statSync } from 'node:fs';
|
|
6
|
+
import { isAbsolute, join, dirname, resolve as resolve$1 } from 'node:path';
|
|
7
|
+
import { userInfo, hostname } from 'node:os';
|
|
8
|
+
import axios from 'axios';
|
|
9
|
+
import { io } from 'socket.io-client';
|
|
10
|
+
|
|
11
|
+
const TeamScopeSchema = z.object({
|
|
12
|
+
serverUrl: z.string(),
|
|
13
|
+
scopeToken: z.string().min(1),
|
|
14
|
+
teamId: z.string().min(1),
|
|
15
|
+
botId: z.string().min(1),
|
|
16
|
+
taskId: z.string().optional(),
|
|
17
|
+
attemptId: z.string().optional()
|
|
18
|
+
});
|
|
19
|
+
function teamScopePath(sessionId) {
|
|
20
|
+
const supplied = process.env.VH_TEAM_SCOPE_FILE;
|
|
21
|
+
if (supplied) {
|
|
22
|
+
if (!isAbsolute(supplied)) throw new Error("VH_TEAM_SCOPE_FILE must be absolute");
|
|
23
|
+
return supplied;
|
|
24
|
+
}
|
|
25
|
+
if (!sessionId || !/^[a-zA-Z0-9_-]+$/.test(sessionId)) throw new Error("Teams requires a managed session or VH_TEAM_SCOPE_FILE");
|
|
26
|
+
return join(configuration.happyHomeDir, "teams", "scopes", `${sessionId}.json`);
|
|
27
|
+
}
|
|
28
|
+
async function readTeamScope(path) {
|
|
29
|
+
let file;
|
|
30
|
+
try {
|
|
31
|
+
file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (error.code === "ENOENT") return null;
|
|
34
|
+
throw new Error("Cannot open team scope");
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
const stat = await file.stat();
|
|
38
|
+
if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("Team scope owner mismatch");
|
|
39
|
+
if (!stat.isFile() || process.platform !== "win32" && (stat.mode & 63) !== 0) throw new Error("Team scope must be a private 0600 file");
|
|
40
|
+
const scope = TeamScopeSchema.parse(JSON.parse(await file.readFile("utf8")));
|
|
41
|
+
scope.serverUrl = normalizeHttpEndpoint(scope.serverUrl, "team scope");
|
|
42
|
+
if (scope.serverUrl !== configuration.serverUrl) throw new Error("Team scope belongs to another server");
|
|
43
|
+
return scope;
|
|
44
|
+
} catch {
|
|
45
|
+
throw new Error("Invalid or unsafe team scope file");
|
|
46
|
+
} finally {
|
|
47
|
+
await file.close();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function writeTeamScope(path, scope) {
|
|
51
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
52
|
+
const temporary = `${path}.${randomUUID()}.new`;
|
|
53
|
+
const file = await open(temporary, "wx", 384);
|
|
54
|
+
try {
|
|
55
|
+
await file.writeFile(JSON.stringify(TeamScopeSchema.parse(scope)));
|
|
56
|
+
await file.sync();
|
|
57
|
+
} finally {
|
|
58
|
+
await file.close();
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
await rename(temporary, path);
|
|
62
|
+
} finally {
|
|
63
|
+
await unlink(temporary).catch(() => {
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function teamRequest(path, method, token, scoped, body) {
|
|
69
|
+
const response = await fetch(`${configuration.serverUrl}${path}`, {
|
|
70
|
+
method,
|
|
71
|
+
redirect: "error",
|
|
72
|
+
headers: { "content-type": "application/json", ...scoped ? { "x-happy-team-token": token } : { authorization: `Bearer ${token}` } },
|
|
73
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
74
|
+
signal: AbortSignal.timeout(25e3)
|
|
75
|
+
}).catch(() => {
|
|
76
|
+
throw new Error("Teams connection failed; outcome may be unknown. Reuse the request ID when retrying.");
|
|
77
|
+
});
|
|
78
|
+
if (!response.ok) throw new Error(`Teams request failed (HTTP ${response.status})`);
|
|
79
|
+
try {
|
|
80
|
+
return await response.json();
|
|
81
|
+
} catch {
|
|
82
|
+
throw new Error("Teams returned an invalid response");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
class TeamConnectionPreflightError extends Error {
|
|
86
|
+
}
|
|
87
|
+
const initializationLocks = /* @__PURE__ */ new Map();
|
|
88
|
+
async function serializeInitialization(path, work) {
|
|
89
|
+
const previous = initializationLocks.get(path) ?? Promise.resolve();
|
|
90
|
+
const next = previous.catch(() => {
|
|
91
|
+
}).then(work);
|
|
92
|
+
initializationLocks.set(path, next);
|
|
93
|
+
try {
|
|
94
|
+
return await next;
|
|
95
|
+
} finally {
|
|
96
|
+
if (initializationLocks.get(path) === next) initializationLocks.delete(path);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function createTeamsClient(sessionId) {
|
|
100
|
+
const scopePath = () => teamScopePath(sessionId ?? process.env.HAPPY_SESSION_ID);
|
|
101
|
+
return {
|
|
102
|
+
async initialize(input, options) {
|
|
103
|
+
const path = scopePath();
|
|
104
|
+
return serializeInitialization(path, async () => {
|
|
105
|
+
const priorScope = await readTeamScope(path);
|
|
106
|
+
if (priorScope && !options?.resumeAdoption) throw new Error("This session already has a team scope; use scoped team tools");
|
|
107
|
+
if (process.env.VH_TEAM_SCOPE_FILE) throw new Error("Assigned team scope is missing or already managed; ask the owner to restore it");
|
|
108
|
+
const sid = sessionId ?? process.env.HAPPY_SESSION_ID;
|
|
109
|
+
if (!sid) throw new Error("A managed session identity is required");
|
|
110
|
+
const machineId = (await readSettings()).machineId;
|
|
111
|
+
if (!machineId) throw new TeamConnectionPreflightError("Connect this machine to Very Happy before joining a team");
|
|
112
|
+
if (input.machineId && input.machineId !== machineId) throw new TeamConnectionPreflightError("Teams must use this session\u2019s local machine");
|
|
113
|
+
const persisted = readPersistedSessions()[sid];
|
|
114
|
+
if (!persisted || persisted.metadata.machineId !== machineId) throw new TeamConnectionPreflightError("Team identity must be a persisted session on this machine");
|
|
115
|
+
const credentials = await readCredentialsForConfiguredRelay();
|
|
116
|
+
if (!credentials) throw new TeamConnectionPreflightError("Sign in to Very Happy before creating or joining a team");
|
|
117
|
+
if (priorScope && !options?.expectedTeamId) throw new Error("This session already belongs to another team scope");
|
|
118
|
+
let teamId = input.teamId ?? options?.expectedTeamId;
|
|
119
|
+
if (!teamId) {
|
|
120
|
+
const created = await teamRequest("/v1/teams", "POST", credentials.token, false, { name: input.name, machineId, requestId: input.requestId });
|
|
121
|
+
teamId = created.team.id;
|
|
122
|
+
} else {
|
|
123
|
+
const existing = await teamRequest(`/v1/teams/${encodeURIComponent(teamId)}`, "GET", credentials.token, false);
|
|
124
|
+
if (existing.team?.machineId !== machineId) throw new TeamConnectionPreflightError("Team belongs to another machine");
|
|
125
|
+
}
|
|
126
|
+
if (options?.onTeamResolved) await options.onTeamResolved(teamId);
|
|
127
|
+
if (priorScope) {
|
|
128
|
+
if (priorScope.teamId !== teamId || priorScope.taskId) throw new Error("This session already belongs to another team scope");
|
|
129
|
+
const inspected = await teamRequest(`/v1/teams/${encodeURIComponent(teamId)}/agent`, "GET", priorScope.scopeToken, true);
|
|
130
|
+
const bot = inspected.team?.bots?.find((candidate) => candidate.id === priorScope.botId);
|
|
131
|
+
if (!bot?.root || bot.managed || bot.sessionId !== sid) throw new Error("Existing scope is not this session\u2019s root identity");
|
|
132
|
+
return { team: inspected.team, botId: priorScope.botId };
|
|
133
|
+
}
|
|
134
|
+
const result = await teamRequest(
|
|
135
|
+
`/v1/teams/${encodeURIComponent(teamId)}/actions`,
|
|
136
|
+
"POST",
|
|
137
|
+
credentials.token,
|
|
138
|
+
false,
|
|
139
|
+
{ requestId: input.requestId, action: { type: "join", name: input.name, sessionId: sid, ...input.botId ? { botId: input.botId } : {} } }
|
|
140
|
+
);
|
|
141
|
+
if (!result.credential?.token || !result.credential?.botId) throw new Error("Team join did not issue a credential");
|
|
142
|
+
await writeTeamScope(path, { serverUrl: configuration.serverUrl, teamId, botId: result.credential.botId, scopeToken: result.credential.token });
|
|
143
|
+
return { team: result.team, botId: result.credential.botId };
|
|
144
|
+
});
|
|
145
|
+
},
|
|
146
|
+
async inspect() {
|
|
147
|
+
const scope = await readTeamScope(scopePath());
|
|
148
|
+
if (!scope) throw new Error("Join or create a team first");
|
|
149
|
+
const { credential: _credential, ...safe } = await teamRequest(`/v1/teams/${encodeURIComponent(scope.teamId)}/agent`, "GET", scope.scopeToken, true);
|
|
150
|
+
return safe;
|
|
151
|
+
},
|
|
152
|
+
async action(action, requestId = randomUUID()) {
|
|
153
|
+
const scope = await readTeamScope(scopePath());
|
|
154
|
+
if (!scope) throw new Error("Join or create a team first");
|
|
155
|
+
const result = await teamRequest(`/v1/teams/${encodeURIComponent(scope.teamId)}/agent`, "POST", scope.scopeToken, true, { requestId, action });
|
|
156
|
+
const { credential: _credential, ...safe } = result;
|
|
157
|
+
return safe;
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const TEAM_TOOL_NAMES = ["team_create", "team_join", "team_inspect", "team_delegate", "team_message", "team_submit", "team_accept", "team_return", "team_cancel", "team_handoff", "team_schedule_create", "team_schedule_pause", "team_schedule_resume", "team_schedule_cancel"];
|
|
163
|
+
const id$1 = z.string().min(1).max(128);
|
|
164
|
+
const text = z.string().min(1).max(32e3);
|
|
165
|
+
const requestId = id$1.describe("Unique operation ID. Reuse the same ID and arguments after an uncertain response.");
|
|
166
|
+
function registerTeamsTools(server, sessionId, client = createTeamsClient(sessionId)) {
|
|
167
|
+
const register = (name, description, inputSchema, execute) => {
|
|
168
|
+
server.registerTool(name, { description, inputSchema, annotations: { readOnlyHint: name === "team_inspect", idempotentHint: true, openWorldHint: false, destructiveHint: ["team_cancel", "team_handoff", "team_return", "team_schedule_cancel"].includes(name) } }, async (args) => {
|
|
169
|
+
try {
|
|
170
|
+
return { content: [{ type: "text", text: JSON.stringify(await execute(args)) }], isError: false };
|
|
171
|
+
} catch (error) {
|
|
172
|
+
return { content: [{ type: "text", text: error instanceof Error ? error.message : "Teams operation failed" }], isError: true };
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
};
|
|
176
|
+
register(
|
|
177
|
+
"team_create",
|
|
178
|
+
"Create an official Very Happy team and join this session as its root bot. Does not grant access outside this account.",
|
|
179
|
+
{ name: id$1, machineId: id$1.optional(), requestId },
|
|
180
|
+
(args) => client.initialize(args)
|
|
181
|
+
);
|
|
182
|
+
register(
|
|
183
|
+
"team_join",
|
|
184
|
+
"Join an existing team as a root bot using this session owner\u2019s account. Scoped workers cannot elevate their role.",
|
|
185
|
+
{ teamId: id$1, name: id$1, botId: id$1.optional().describe("Existing root bot to reconnect; preserves its identity"), requestId },
|
|
186
|
+
(args) => client.initialize(args)
|
|
187
|
+
);
|
|
188
|
+
register("team_inspect", "Read your visible team tasks, attempts and messages. Inspect before decisions; submission is not acceptance.", {}, () => client.inspect());
|
|
189
|
+
const action = (name, description, fields) => register(
|
|
190
|
+
`team_${name}`,
|
|
191
|
+
description,
|
|
192
|
+
{ requestId, ...fields },
|
|
193
|
+
({ requestId: key, ...args }) => client.action({ type: name, ...args, ...name === "delegate" && args.directory === void 0 ? { directory: process.cwd() } : {} }, key)
|
|
194
|
+
);
|
|
195
|
+
action("delegate", "Delegate a goal with acceptance criteria. Use parentTaskId for subdelegation. Existing assigneeBotId or a managed worker may execute it.", {
|
|
196
|
+
goal: text,
|
|
197
|
+
acceptance: z.array(text).min(1).max(32),
|
|
198
|
+
parentTaskId: id$1.optional(),
|
|
199
|
+
assigneeBotId: id$1.optional(),
|
|
200
|
+
botName: id$1.optional(),
|
|
201
|
+
directory: z.string().min(1).optional(),
|
|
202
|
+
assistant: z.enum(["claude", "codex", "pi-acp"]).optional(),
|
|
203
|
+
model: z.string().trim().min(1).max(256).optional()
|
|
204
|
+
});
|
|
205
|
+
action("message", "Send a persistent task-related message. Delivery does not mean the model has read or acted on it.", { taskId: id$1, body: text, recipientBotId: id$1.optional() });
|
|
206
|
+
action("submit", "Submit evidence for your current attempt and goal version. The owner still has to accept it.", { taskId: id$1, attemptId: id$1, goalVersion: z.number().int().positive(), result: text });
|
|
207
|
+
const current = { attemptId: id$1, goalVersion: z.number().int().positive() };
|
|
208
|
+
action("accept", "Accept a task you own after checking its evidence. Resource cleanup is tracked separately.", { taskId: id$1, ...current });
|
|
209
|
+
action("return", "Return your task for further work with a concrete reason.", { taskId: id$1, reason: text, ...current });
|
|
210
|
+
action("cancel", "Cancel an owned task and its dependent work. Cleanup may remain pending.", { taskId: id$1, reason: text, ...current });
|
|
211
|
+
action("handoff", "Move an owned task to another bot; prior execution authority is superseded.", { taskId: id$1, assigneeBotId: id$1, ...current });
|
|
212
|
+
register("team_schedule_create", "Create a persistent one-time or fixed-interval reminder for your own root bot. Delivery wakes the bound session; it does not prove task completion. Use epoch milliseconds, and inspect before retrying.", { requestId, name: id$1, botId: id$1, body: text, runAt: z.number().int().nonnegative(), intervalMs: z.number().int().min(6e4).optional() }, ({ requestId: key, ...args }) => client.action({ type: "schedule-create", ...args }, key));
|
|
213
|
+
for (const operation of ["pause", "resume", "cancel"]) {
|
|
214
|
+
register(`team_schedule_${operation}`, `${operation} your root bot\u2019s schedule using its current version from team_inspect. An already in-flight message may still arrive.`, { requestId, scheduleId: id$1, version: z.number().int().positive() }, ({ requestId: key, ...args }) => client.action({ type: `schedule-${operation}`, ...args }, key));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
class AutomationsRequestError extends Error {
|
|
219
|
+
constructor(status, code, runStatus) {
|
|
220
|
+
super(describeAutomationError(status, code, runStatus));
|
|
221
|
+
this.status = status;
|
|
222
|
+
this.code = code;
|
|
223
|
+
this.runStatus = runStatus;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function isAutomationsUnavailable(error) {
|
|
227
|
+
return error instanceof AutomationsRequestError && error.status === 404 && !error.code.endsWith("_not_found");
|
|
228
|
+
}
|
|
229
|
+
const AUTOMATIONS_UNAVAILABLE_MESSAGE = "Automations are not enabled on this server (set VH_AUTOMATIONS_ENABLED=true on the server, or upgrade it).";
|
|
230
|
+
function describeAutomationError(status, code, runStatus) {
|
|
231
|
+
if (status === 404 && !code.endsWith("_not_found")) return AUTOMATIONS_UNAVAILABLE_MESSAGE;
|
|
232
|
+
const known = {
|
|
233
|
+
automation_not_found: "No automation with that name or id.",
|
|
234
|
+
run_not_found: "No automation run with that id.",
|
|
235
|
+
machine_not_found: "That machine is not registered on this account.",
|
|
236
|
+
session_not_found: "That session does not belong to this account.",
|
|
237
|
+
automation_name_taken: "An automation with that name already exists.",
|
|
238
|
+
automation_count_quota_exceeded: "This account already holds the maximum number of automations (active + paused). Delete one you no longer need (`very-happy auto delete <name>`) before creating another.",
|
|
239
|
+
automation_paused: "That automation is paused; resume it before firing.",
|
|
240
|
+
stale_automation: "The automation changed since you read it; read it again and retry with the new version.",
|
|
241
|
+
run_finished: `The run already reached a terminal state${runStatus ? ` (${runStatus})` : ""}. In a continued (sticky) session, pass the runId named in the latest prompt header \u2014 the environment default is the run that started the session.`,
|
|
242
|
+
claim_mismatch: "Another daemon holds the claim for that run.",
|
|
243
|
+
run_not_claimed: "The run has not been claimed by its machine yet; cancel it instead of reporting.",
|
|
244
|
+
status_required: "An explicit report needs status done or failed.",
|
|
245
|
+
claim_required: "Lease, session and sticky fields are daemon-only; report just the outcome.",
|
|
246
|
+
sticky_requires_session: "A sticky key needs a session id.",
|
|
247
|
+
transaction_conflict: "The server was busy; retry the same request.",
|
|
248
|
+
invalid_cron: "The cron expression is invalid.",
|
|
249
|
+
invalid_timezone: "The time zone is not a valid IANA zone."
|
|
250
|
+
};
|
|
251
|
+
if (known[code]) return known[code];
|
|
252
|
+
if (status === 400) return "The server rejected the request (HTTP 400): check the arguments, or the server may expect a newer request shape.";
|
|
253
|
+
return `Automations request failed (HTTP ${status}${code ? `, ${code}` : ""}).`;
|
|
254
|
+
}
|
|
255
|
+
function createAutomationsClient(options) {
|
|
256
|
+
const doFetch = options.fetch ?? fetch;
|
|
257
|
+
const base = options.serverUrl.replace(/\/+$/, "");
|
|
258
|
+
async function request(method, path, body, query) {
|
|
259
|
+
const url = new URL(`${base}${path}`);
|
|
260
|
+
for (const [key, value] of Object.entries(query ?? {})) if (value !== void 0) url.searchParams.set(key, value);
|
|
261
|
+
let response;
|
|
262
|
+
try {
|
|
263
|
+
response = await doFetch(url.toString(), {
|
|
264
|
+
method,
|
|
265
|
+
redirect: "error",
|
|
266
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${options.token}`, "x-happy-client": `${options.client ?? "cli-auto"}/${configuration.currentCliVersion}` },
|
|
267
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
268
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 25e3)
|
|
269
|
+
});
|
|
270
|
+
} catch {
|
|
271
|
+
throw new Error("Automations connection failed; the outcome may be unknown. Read the current state before retrying.");
|
|
272
|
+
}
|
|
273
|
+
let parsed = null;
|
|
274
|
+
try {
|
|
275
|
+
parsed = await response.json();
|
|
276
|
+
} catch {
|
|
277
|
+
parsed = null;
|
|
278
|
+
}
|
|
279
|
+
if (!response.ok) {
|
|
280
|
+
const code = typeof parsed?.error === "string" ? parsed.error : "";
|
|
281
|
+
throw new AutomationsRequestError(response.status, code, typeof parsed?.status === "string" ? parsed.status : void 0);
|
|
282
|
+
}
|
|
283
|
+
return parsed;
|
|
284
|
+
}
|
|
285
|
+
const enc = encodeURIComponent;
|
|
286
|
+
return {
|
|
287
|
+
list: (machineId) => request("GET", "/v1/automations", void 0, { machineId }).then((r) => r.automations),
|
|
288
|
+
get: (id) => request("GET", `/v1/automations/${enc(id)}`).then((r) => r.automation),
|
|
289
|
+
getByName: (name) => request("GET", `/v1/automations/by-name/${enc(name)}`).then((r) => r.automation),
|
|
290
|
+
create: (input) => request("POST", "/v1/automations", input).then((r) => r.automation),
|
|
291
|
+
update: (id, input) => request("PATCH", `/v1/automations/${enc(id)}`, input).then((r) => r.automation),
|
|
292
|
+
remove: (id) => request("DELETE", `/v1/automations/${enc(id)}`),
|
|
293
|
+
pause: (id) => request("POST", `/v1/automations/${enc(id)}/pause`).then((r) => r.automation),
|
|
294
|
+
resume: (id) => request("POST", `/v1/automations/${enc(id)}/resume`).then((r) => r.automation),
|
|
295
|
+
run: (id, input = {}) => request("POST", `/v1/automations/${enc(id)}/run`, input).then((r) => r.run),
|
|
296
|
+
fire: (name, input = {}) => request("POST", `/v1/automations/by-name/${enc(name)}/fire`, input),
|
|
297
|
+
runs: (query = {}) => request("GET", "/v1/automations/runs", void 0, {
|
|
298
|
+
automationId: query.automationId,
|
|
299
|
+
name: query.name,
|
|
300
|
+
status: query.status,
|
|
301
|
+
attention: query.attention ? "1" : void 0,
|
|
302
|
+
limit: query.limit === void 0 ? void 0 : String(query.limit)
|
|
303
|
+
}).then((r) => r.runs),
|
|
304
|
+
getRun: (id) => request("GET", `/v1/automations/runs/${enc(id)}`).then((r) => r.run),
|
|
305
|
+
cancel: (id) => request("POST", `/v1/automations/runs/${enc(id)}/cancel`).then((r) => r.run),
|
|
306
|
+
ack: (id) => request("POST", `/v1/automations/runs/${enc(id)}/ack`).then((r) => r.run),
|
|
307
|
+
report: (id, input) => request("POST", `/v1/automations/runs/${enc(id)}/report`, input).then((r) => r.run),
|
|
308
|
+
claim: (input) => request("POST", "/v1/automations/claim", input),
|
|
309
|
+
stickies: (id, key) => request("GET", `/v1/automations/${enc(id)}/stickies`, void 0, { key }).then((r) => r.stickies),
|
|
310
|
+
putSticky: (id, key, sessionId) => request("PUT", `/v1/automations/${enc(id)}/stickies`, { key, sessionId }).then((r) => r.sticky),
|
|
311
|
+
deleteSticky: (id, key) => request("DELETE", `/v1/automations/${enc(id)}/stickies`, { key }).then((r) => r.removed)
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
async function authenticatedAutomationsClient(client = "cli-auto") {
|
|
315
|
+
const credentials = await readCredentialsForConfiguredRelay();
|
|
316
|
+
if (!credentials) throw new Error("Not authenticated. Run `very-happy auth login` first.");
|
|
317
|
+
const settings = await readSettings();
|
|
318
|
+
return { client: createAutomationsClient({ serverUrl: configuration.serverUrl, token: credentials.token, client }), machineId: settings.machineId };
|
|
319
|
+
}
|
|
320
|
+
function automationRunIdFromEnv(env = process.env) {
|
|
321
|
+
const value = env.VH_AUTOMATION_RUN_ID;
|
|
322
|
+
return value && /^[a-zA-Z0-9_-]{1,128}$/.test(value) ? value : void 0;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const AUTOMATION_TOOL_NAMES = [
|
|
326
|
+
"automation_list",
|
|
327
|
+
"automation_get",
|
|
328
|
+
"automation_create",
|
|
329
|
+
"automation_update",
|
|
330
|
+
"automation_pause",
|
|
331
|
+
"automation_resume",
|
|
332
|
+
"automation_delete",
|
|
333
|
+
"automation_run",
|
|
334
|
+
"automation_fire",
|
|
335
|
+
"automation_runs",
|
|
336
|
+
"automation_report",
|
|
337
|
+
"automation_ack"
|
|
338
|
+
];
|
|
339
|
+
const id = z.string().min(1).max(128);
|
|
340
|
+
const ref = { name: AutomationNameSchema.optional().describe("Automation name"), id: id.optional().describe("Automation id (alternative to name)") };
|
|
341
|
+
const payload = z.string().max(65536).optional().describe("Payload text; JSON lets prompts use {{payload.field}}");
|
|
342
|
+
const maxRuntimeMs = z.number().int().min(6e4).max(7 * 864e5).optional();
|
|
343
|
+
const AUTOMATION_TOOL_SCHEMAS = {
|
|
344
|
+
automation_list: { description: "List this account\u2019s automations (name, trigger, action, machine, status, next run). Defaults to every machine.", readOnly: true, inputSchema: { machineId: id.optional().describe("Only this machine id, or 'this' for the current machine") } },
|
|
345
|
+
automation_get: { description: "Read one automation by name or id, including its version (needed for automation_update).", readOnly: true, inputSchema: ref },
|
|
346
|
+
automation_create: {
|
|
347
|
+
description: "Create an automation: a trigger (cron+tz / interval / once / manual) and an action (spawn a session, send into a session, or run a script argv) on one machine. Defaults to the current machine. Prompts and argv may use {{payload}}, {{payload.path}}, {{run.id}}, {{automation.name}}, {{now}}.",
|
|
348
|
+
inputSchema: {
|
|
349
|
+
name: AutomationNameSchema,
|
|
350
|
+
description: z.string().max(4e3).optional(),
|
|
351
|
+
machineId: id.optional().describe("Target machine id; omit or 'this' for the current machine"),
|
|
352
|
+
trigger: AutomationTriggerSchema,
|
|
353
|
+
action: AutomationActionSchema,
|
|
354
|
+
concurrency: AutomationConcurrencySchema.optional().describe("skip (default): a run while another is active is recorded as skipped; queue: it waits"),
|
|
355
|
+
maxRuntimeMs,
|
|
356
|
+
paused: z.boolean().optional().describe("Create paused")
|
|
357
|
+
}
|
|
358
|
+
},
|
|
359
|
+
automation_update: {
|
|
360
|
+
description: "Change an automation (name / description / machine / trigger / action / concurrency / maxRuntimeMs). Requires the current version from automation_get; a stale version is rejected.",
|
|
361
|
+
inputSchema: {
|
|
362
|
+
...ref,
|
|
363
|
+
version: z.number().int().positive(),
|
|
364
|
+
newName: AutomationNameSchema.optional(),
|
|
365
|
+
description: z.string().max(4e3).nullable().optional(),
|
|
366
|
+
machineId: id.optional(),
|
|
367
|
+
trigger: AutomationTriggerSchema.optional(),
|
|
368
|
+
action: AutomationActionSchema.optional(),
|
|
369
|
+
concurrency: AutomationConcurrencySchema.optional(),
|
|
370
|
+
maxRuntimeMs
|
|
371
|
+
}
|
|
372
|
+
},
|
|
373
|
+
automation_pause: { description: "Pause an automation: no new scheduled runs and fire is refused until resumed.", inputSchema: ref },
|
|
374
|
+
automation_resume: { description: "Resume a paused automation; the next run is computed from now.", inputSchema: ref },
|
|
375
|
+
automation_delete: { description: "Delete an automation and its run history. Irreversible.", destructive: true, inputSchema: ref },
|
|
376
|
+
automation_run: { description: "Queue one run of an automation now (source: manual), optionally with a payload.", inputSchema: { ...ref, payload } },
|
|
377
|
+
automation_fire: { description: "Trigger an automation by name as an external event, with an optional payload and dedupe key (the same key within 24h returns the original run).", inputSchema: { name: AutomationNameSchema, payload, dedupeKey: z.string().min(1).max(256).optional() } },
|
|
378
|
+
automation_runs: { description: "List runs, newest first: status, session, summary, error, attention. Filter by automation, status or attention.", readOnly: true, inputSchema: { ...ref, status: z.string().min(1).max(64).optional(), attention: z.boolean().optional().describe("Only runs flagged for a human"), limit: z.number().int().min(1).max(200).optional() } },
|
|
379
|
+
automation_report: {
|
|
380
|
+
description: 'Report the result of an automation run. Without runId it targets the run that STARTED this session (VH_AUTOMATION_RUN_ID); in a continued sticky session always pass the runId named in the latest "[Very Happy automation \u2026 run <id>; \u2026]" prompt header. Use status done with a short summary, or failed with the error; set needsAttention when a human must look.',
|
|
381
|
+
inputSchema: { runId: id.optional(), status: z.enum(["done", "failed"]), summary: z.string().max(4096).optional(), error: z.string().max(4096).optional(), needsAttention: z.boolean().optional(), attentionReason: z.string().max(512).optional() }
|
|
382
|
+
},
|
|
383
|
+
automation_ack: { description: "Clear the attention flag of a run after a human handled it.", inputSchema: { runId: id } }
|
|
384
|
+
};
|
|
385
|
+
async function resolve(context, args) {
|
|
386
|
+
if (args.id) return context.client.get(args.id);
|
|
387
|
+
if (args.name) return context.client.getByName(args.name);
|
|
388
|
+
throw new Error("Give the automation name or id");
|
|
389
|
+
}
|
|
390
|
+
function machineFor(context, requested) {
|
|
391
|
+
if (requested && requested !== "this") return requested;
|
|
392
|
+
return context.machineId;
|
|
393
|
+
}
|
|
394
|
+
function requireMachine(context, requested) {
|
|
395
|
+
const machine = machineFor(context, requested);
|
|
396
|
+
if (!machine) throw new Error("This machine is not registered with Very Happy; pass machineId explicitly");
|
|
397
|
+
return machine;
|
|
398
|
+
}
|
|
399
|
+
async function executeAutomationTool(name, args, context) {
|
|
400
|
+
const { client } = context;
|
|
401
|
+
switch (name) {
|
|
402
|
+
case "automation_list":
|
|
403
|
+
return { automations: await client.list(machineFor(context, args.machineId)) };
|
|
404
|
+
case "automation_get":
|
|
405
|
+
return { automation: await resolve(context, args) };
|
|
406
|
+
case "automation_create": {
|
|
407
|
+
const input = {
|
|
408
|
+
name: args.name,
|
|
409
|
+
machineId: requireMachine(context, args.machineId),
|
|
410
|
+
trigger: args.trigger,
|
|
411
|
+
action: args.action,
|
|
412
|
+
...args.description !== void 0 ? { description: args.description } : {},
|
|
413
|
+
...args.concurrency !== void 0 ? { concurrency: args.concurrency } : {},
|
|
414
|
+
...args.maxRuntimeMs !== void 0 ? { maxRuntimeMs: args.maxRuntimeMs } : {},
|
|
415
|
+
...args.paused ? { status: "paused" } : {}
|
|
416
|
+
};
|
|
417
|
+
return { automation: await client.create(input) };
|
|
418
|
+
}
|
|
419
|
+
case "automation_update": {
|
|
420
|
+
const current = await resolve(context, args);
|
|
421
|
+
const input = {
|
|
422
|
+
version: args.version,
|
|
423
|
+
...args.newName !== void 0 ? { name: args.newName } : {},
|
|
424
|
+
...args.description !== void 0 ? { description: args.description } : {},
|
|
425
|
+
...args.machineId !== void 0 ? { machineId: machineFor(context, args.machineId) } : {},
|
|
426
|
+
...args.trigger !== void 0 ? { trigger: args.trigger } : {},
|
|
427
|
+
...args.action !== void 0 ? { action: args.action } : {},
|
|
428
|
+
...args.concurrency !== void 0 ? { concurrency: args.concurrency } : {},
|
|
429
|
+
...args.maxRuntimeMs !== void 0 ? { maxRuntimeMs: args.maxRuntimeMs } : {}
|
|
430
|
+
};
|
|
431
|
+
return { automation: await client.update(current.id, input) };
|
|
432
|
+
}
|
|
433
|
+
case "automation_pause":
|
|
434
|
+
return { automation: await client.pause((await resolve(context, args)).id) };
|
|
435
|
+
case "automation_resume":
|
|
436
|
+
return { automation: await client.resume((await resolve(context, args)).id) };
|
|
437
|
+
case "automation_delete": {
|
|
438
|
+
const target = await resolve(context, args);
|
|
439
|
+
await client.remove(target.id);
|
|
440
|
+
return { deleted: true, id: target.id, name: target.name };
|
|
441
|
+
}
|
|
442
|
+
case "automation_run":
|
|
443
|
+
return { run: await client.run((await resolve(context, args)).id, args.payload !== void 0 ? { payload: args.payload } : {}) };
|
|
444
|
+
case "automation_fire":
|
|
445
|
+
return client.fire(args.name, { ...args.payload !== void 0 ? { payload: args.payload } : {}, ...args.dedupeKey !== void 0 ? { dedupeKey: args.dedupeKey } : {} });
|
|
446
|
+
case "automation_runs": {
|
|
447
|
+
const automationId = args.id ?? (args.name ? (await client.getByName(args.name)).id : void 0);
|
|
448
|
+
return { runs: await client.runs({ automationId, status: args.status, attention: args.attention === true, limit: args.limit }) };
|
|
449
|
+
}
|
|
450
|
+
case "automation_report": {
|
|
451
|
+
const runId = args.runId ?? automationRunIdFromEnv(context.env ?? process.env);
|
|
452
|
+
if (!runId) throw new Error("No run id: pass runId (this session was not started by an automation)");
|
|
453
|
+
const report = {
|
|
454
|
+
status: args.status,
|
|
455
|
+
...args.summary !== void 0 ? { summary: args.summary } : {},
|
|
456
|
+
...args.error !== void 0 ? { error: args.error } : {},
|
|
457
|
+
...args.needsAttention !== void 0 ? { needsAttention: args.needsAttention } : {},
|
|
458
|
+
...args.attentionReason !== void 0 ? { attentionReason: args.attentionReason } : {}
|
|
459
|
+
};
|
|
460
|
+
return { run: await client.report(runId, report) };
|
|
461
|
+
}
|
|
462
|
+
case "automation_ack":
|
|
463
|
+
return { run: await client.ack(args.runId) };
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
function createAutomationToolExecutor() {
|
|
467
|
+
let context = null;
|
|
468
|
+
return async (name, args) => {
|
|
469
|
+
context ??= authenticatedAutomationsClient("mcp-auto").then(({ client, machineId }) => ({ client, machineId }));
|
|
470
|
+
let resolved;
|
|
471
|
+
try {
|
|
472
|
+
resolved = await context;
|
|
473
|
+
} catch (error) {
|
|
474
|
+
context = null;
|
|
475
|
+
throw error;
|
|
476
|
+
}
|
|
477
|
+
return executeAutomationTool(name, args, resolved);
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
function registerAutomationTools(server, execute = createAutomationToolExecutor()) {
|
|
481
|
+
for (const name of AUTOMATION_TOOL_NAMES) {
|
|
482
|
+
const spec = AUTOMATION_TOOL_SCHEMAS[name];
|
|
483
|
+
server.registerTool(name, {
|
|
484
|
+
description: spec.description,
|
|
485
|
+
inputSchema: spec.inputSchema,
|
|
486
|
+
annotations: { readOnlyHint: spec.readOnly === true, idempotentHint: name !== "automation_run" && name !== "automation_create", openWorldHint: false, destructiveHint: spec.destructive === true }
|
|
487
|
+
}, async (args) => {
|
|
488
|
+
try {
|
|
489
|
+
return { content: [{ type: "text", text: JSON.stringify(await execute(name, args ?? {})) }], isError: false };
|
|
490
|
+
} catch (error) {
|
|
491
|
+
return { content: [{ type: "text", text: error instanceof Error ? error.message : "Automation operation failed" }], isError: true };
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function sessionWebUrl(sessionId) {
|
|
498
|
+
return `${configuration.webappUrl.replace(/\/+$/, "")}/session/${sessionId}`;
|
|
499
|
+
}
|
|
500
|
+
async function waitForSessionKey(sessionId, timeoutMs) {
|
|
501
|
+
const deadline = Date.now() + timeoutMs;
|
|
502
|
+
while (true) {
|
|
503
|
+
const entry = readPersistedSessions()[sessionId];
|
|
504
|
+
if (entry) return entry;
|
|
505
|
+
if (Date.now() >= deadline) {
|
|
506
|
+
throw new Error(
|
|
507
|
+
`Session ${sessionId} has no encryption key in ${configuration.sessionsFile}. Either it was not spawned by this machine's daemon, or the daemon is too old to persist session keys.`
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
await delay(200);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
async function sendUserMessage(sessionId, persisted, text, client, options = {}) {
|
|
514
|
+
const credentials = await readCredentialsForConfiguredRelay();
|
|
515
|
+
if (!credentials) {
|
|
516
|
+
throw new Error("Not authenticated. Run `very-happy auth login` first.");
|
|
517
|
+
}
|
|
518
|
+
const envelope = {
|
|
519
|
+
role: "user",
|
|
520
|
+
content: {
|
|
521
|
+
type: "text",
|
|
522
|
+
text
|
|
523
|
+
},
|
|
524
|
+
meta: {
|
|
525
|
+
sentFrom: options.sentFrom ?? "cli",
|
|
526
|
+
...options.model !== void 0 ? { model: options.model } : {},
|
|
527
|
+
...options.permissionMode !== void 0 ? { permissionMode: options.permissionMode } : {},
|
|
528
|
+
...options.effort !== void 0 ? { effort: options.effort } : {},
|
|
529
|
+
...options.delivery !== void 0 ? { delivery: options.delivery } : {}
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
const encrypted = encodeBase64(encrypt(
|
|
533
|
+
decodeBase64(persisted.encryptionKey),
|
|
534
|
+
persisted.encryptionVariant,
|
|
535
|
+
envelope
|
|
536
|
+
));
|
|
537
|
+
await axios.post(
|
|
538
|
+
`${configuration.serverUrl}/v3/sessions/${encodeURIComponent(sessionId)}/messages`,
|
|
539
|
+
{ messages: [{ content: encrypted, localId: options.localId ?? randomUUID() }] },
|
|
540
|
+
{
|
|
541
|
+
headers: {
|
|
542
|
+
"Authorization": `Bearer ${credentials.token}`,
|
|
543
|
+
"Content-Type": "application/json",
|
|
544
|
+
"X-Happy-Client": `${client}/${configuration.currentCliVersion}`
|
|
545
|
+
},
|
|
546
|
+
timeout: 3e4
|
|
547
|
+
}
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const MAX_LINE_CHARS = 500;
|
|
552
|
+
const MAX_ARGS_CHARS = 160;
|
|
553
|
+
const DEFAULT_LIMITS = { line: MAX_LINE_CHARS, args: MAX_ARGS_CHARS };
|
|
554
|
+
const NO_LIMITS = { line: Number.POSITIVE_INFINITY, args: Number.POSITIVE_INFINITY };
|
|
555
|
+
function truncateText(text, max = MAX_LINE_CHARS) {
|
|
556
|
+
const chars = Array.from(text);
|
|
557
|
+
if (chars.length <= max) return text;
|
|
558
|
+
return chars.slice(0, max).join("") + ` \u2026[+${chars.length - max} chars]`;
|
|
559
|
+
}
|
|
560
|
+
function squash(text) {
|
|
561
|
+
return text.replace(/\s+/g, " ").trim();
|
|
562
|
+
}
|
|
563
|
+
function safeJson(value, max) {
|
|
564
|
+
try {
|
|
565
|
+
return truncateText(JSON.stringify(value) ?? "", max);
|
|
566
|
+
} catch {
|
|
567
|
+
return "[unserializable]";
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function formatMessageBody(body, limits = DEFAULT_LIMITS) {
|
|
571
|
+
if (!body || typeof body !== "object") return null;
|
|
572
|
+
const b = body;
|
|
573
|
+
if (b.role === "user" && b.content?.type === "text" && typeof b.content.text === "string") {
|
|
574
|
+
const text = squash(b.content.text);
|
|
575
|
+
return text.length > 0 ? `user: ${truncateText(text, limits.line)}` : null;
|
|
576
|
+
}
|
|
577
|
+
if (b.role === "session" && b.content && typeof b.content === "object") {
|
|
578
|
+
const env = b.content;
|
|
579
|
+
const ev = env.ev;
|
|
580
|
+
if (!ev || typeof ev.t !== "string") return null;
|
|
581
|
+
switch (ev.t) {
|
|
582
|
+
case "text": {
|
|
583
|
+
if (ev.thinking) return null;
|
|
584
|
+
const text = squash(String(ev.text ?? ""));
|
|
585
|
+
if (text.length === 0) return null;
|
|
586
|
+
const role = env.role === "user" ? "user" : "assistant";
|
|
587
|
+
return `${role}: ${truncateText(text, limits.line)}`;
|
|
588
|
+
}
|
|
589
|
+
case "tool-call-start": {
|
|
590
|
+
const name = String(ev.name ?? "tool");
|
|
591
|
+
const title = squash(String(ev.title ?? ""));
|
|
592
|
+
const args = ev.args ? safeJson(ev.args, limits.args) : "";
|
|
593
|
+
const detail = title || args;
|
|
594
|
+
return `[tool] ${name}${detail ? `: ${truncateText(detail, limits.args)}` : ""}`;
|
|
595
|
+
}
|
|
596
|
+
case "service": {
|
|
597
|
+
const text = squash(String(ev.text ?? ""));
|
|
598
|
+
return text.length > 0 ? `[service] ${truncateText(text, limits.args)}` : null;
|
|
599
|
+
}
|
|
600
|
+
case "turn-end": {
|
|
601
|
+
if (ev.status && ev.status !== "completed") return `[turn ${ev.status}]`;
|
|
602
|
+
return null;
|
|
603
|
+
}
|
|
604
|
+
default:
|
|
605
|
+
return null;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
if (b.role === "agent" && b.content?.type === "acp" && b.content.data && typeof b.content.data === "object") {
|
|
609
|
+
const d = b.content.data;
|
|
610
|
+
switch (d.type) {
|
|
611
|
+
case "message": {
|
|
612
|
+
const text = squash(String(d.message ?? ""));
|
|
613
|
+
return text.length > 0 ? `assistant: ${truncateText(text, limits.line)}` : null;
|
|
614
|
+
}
|
|
615
|
+
case "tool-call":
|
|
616
|
+
return `[tool] ${String(d.name ?? "tool")}: ${safeJson(d.input, limits.args)}`;
|
|
617
|
+
case "permission-request":
|
|
618
|
+
return `[permission] ${String(d.toolName ?? "")}: ${truncateText(squash(String(d.description ?? "")), limits.args)}`;
|
|
619
|
+
default:
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
if (b.role === "agent" && b.content?.type === "output") {
|
|
624
|
+
const msg = b.content.data?.message;
|
|
625
|
+
if (msg && Array.isArray(msg.content)) {
|
|
626
|
+
const texts = msg.content.filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => squash(c.text)).filter((t) => t.length > 0);
|
|
627
|
+
if (texts.length > 0) {
|
|
628
|
+
const role = msg.role === "user" ? "user" : "assistant";
|
|
629
|
+
return `${role}: ${truncateText(texts.join(" "), limits.line)}`;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
return null;
|
|
633
|
+
}
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
function formatTranscript(bodies, options = {}) {
|
|
637
|
+
const limits = options.full ? NO_LIMITS : DEFAULT_LIMITS;
|
|
638
|
+
const lines = [];
|
|
639
|
+
for (const body of bodies) {
|
|
640
|
+
const line = formatMessageBody(body, limits);
|
|
641
|
+
if (line !== null) lines.push(line);
|
|
642
|
+
}
|
|
643
|
+
return lines.join("\n");
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function asRecord(value) {
|
|
647
|
+
return value && typeof value === "object" ? value : null;
|
|
648
|
+
}
|
|
649
|
+
function sessionEnvelope(body) {
|
|
650
|
+
const b = asRecord(body);
|
|
651
|
+
if (!b || b.role !== "session") return null;
|
|
652
|
+
const env = asRecord(b.content);
|
|
653
|
+
if (!env) return null;
|
|
654
|
+
const ev = asRecord(env.ev);
|
|
655
|
+
return ev && typeof ev.t === "string" ? { role: env.role, ev } : null;
|
|
656
|
+
}
|
|
657
|
+
function isUserPrompt(body) {
|
|
658
|
+
const b = asRecord(body);
|
|
659
|
+
return !!b && b.role === "user" && b.content?.type === "text" && typeof b.content.text === "string";
|
|
660
|
+
}
|
|
661
|
+
function agentPiece(body) {
|
|
662
|
+
const env = sessionEnvelope(body);
|
|
663
|
+
if (env && env.role !== "user") {
|
|
664
|
+
if (env.ev.t === "text" && !env.ev.thinking) {
|
|
665
|
+
const text = String(env.ev.text ?? "");
|
|
666
|
+
return text.trim().length > 0 ? { kind: "text", text } : null;
|
|
667
|
+
}
|
|
668
|
+
if (env.ev.t === "tool-call-start") return { kind: "tool" };
|
|
669
|
+
return null;
|
|
670
|
+
}
|
|
671
|
+
const b = asRecord(body);
|
|
672
|
+
if (b?.role === "agent" && b.content?.type === "acp") {
|
|
673
|
+
const d = asRecord(b.content.data);
|
|
674
|
+
if (d?.type === "message") {
|
|
675
|
+
const text = String(d.message ?? "");
|
|
676
|
+
return text.trim().length > 0 ? { kind: "text", text } : null;
|
|
677
|
+
}
|
|
678
|
+
if (d?.type === "tool-call") return { kind: "tool" };
|
|
679
|
+
}
|
|
680
|
+
return null;
|
|
681
|
+
}
|
|
682
|
+
function userPromptText(body) {
|
|
683
|
+
return isUserPrompt(body) ? body.content.text : null;
|
|
684
|
+
}
|
|
685
|
+
function analyzeLatestTurn(entries, options = {}) {
|
|
686
|
+
const lastSeq = entries.length > 0 ? entries[entries.length - 1].seq : 0;
|
|
687
|
+
let userIndex = -1;
|
|
688
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
689
|
+
if (isUserPrompt(entries[i].body) && (!options.anchor || options.anchor(entries[i].body))) {
|
|
690
|
+
userIndex = i;
|
|
691
|
+
break;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
let ended = false;
|
|
695
|
+
let status = null;
|
|
696
|
+
let error = null;
|
|
697
|
+
let texts = [];
|
|
698
|
+
let lastMarker = null;
|
|
699
|
+
let startedAfterPrompt = false;
|
|
700
|
+
const emitsStarts = entries.some((entry) => sessionEnvelope(entry.body)?.ev?.t === "turn-start");
|
|
701
|
+
for (let i = userIndex + 1; i < entries.length; i++) {
|
|
702
|
+
const body = entries[i].body;
|
|
703
|
+
if (options.anchor && isUserPrompt(body)) {
|
|
704
|
+
if (ended) break;
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
const env = sessionEnvelope(body);
|
|
708
|
+
if (env?.ev?.t === "turn-start") {
|
|
709
|
+
lastMarker = "start";
|
|
710
|
+
startedAfterPrompt = true;
|
|
711
|
+
ended = false;
|
|
712
|
+
status = null;
|
|
713
|
+
error = null;
|
|
714
|
+
texts = [];
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
if (env?.ev?.t === "turn-end") {
|
|
718
|
+
lastMarker = "end";
|
|
719
|
+
if (userIndex >= 0 && emitsStarts && !startedAfterPrompt) continue;
|
|
720
|
+
ended = true;
|
|
721
|
+
status = typeof env.ev.status === "string" ? env.ev.status : null;
|
|
722
|
+
error = typeof env.ev.error === "string" ? env.ev.error : null;
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
const piece = agentPiece(body);
|
|
726
|
+
if (!piece) continue;
|
|
727
|
+
if (piece.kind === "tool") texts = [];
|
|
728
|
+
else texts.push(piece.text);
|
|
729
|
+
}
|
|
730
|
+
if (userIndex < 0) ended = lastMarker === "end";
|
|
731
|
+
return {
|
|
732
|
+
userSeq: userIndex >= 0 ? entries[userIndex].seq : null,
|
|
733
|
+
ended,
|
|
734
|
+
status: ended ? status : null,
|
|
735
|
+
error: ended ? error : null,
|
|
736
|
+
answer: texts.join("\n\n").trim(),
|
|
737
|
+
lastSeq
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
const USER_SOCKET_CONNECT_TIMEOUT_MS = 15e3;
|
|
742
|
+
async function openUserScopedSocket(token, options = {}) {
|
|
743
|
+
const socket = io(configuration.serverUrl, {
|
|
744
|
+
auth: {
|
|
745
|
+
token,
|
|
746
|
+
clientType: "user-scoped",
|
|
747
|
+
happyClient: `cli-session-ops/${configuration.currentCliVersion}`
|
|
748
|
+
},
|
|
749
|
+
path: "/v1/updates",
|
|
750
|
+
transports: ["websocket"],
|
|
751
|
+
reconnection: false,
|
|
752
|
+
autoConnect: false
|
|
753
|
+
});
|
|
754
|
+
await new Promise((resolve, reject) => {
|
|
755
|
+
const timer = setTimeout(() => {
|
|
756
|
+
socket.close();
|
|
757
|
+
reject(new Error(`Timed out connecting to ${configuration.serverUrl}`));
|
|
758
|
+
}, options.connectTimeoutMs ?? USER_SOCKET_CONNECT_TIMEOUT_MS);
|
|
759
|
+
socket.once("connect", () => {
|
|
760
|
+
clearTimeout(timer);
|
|
761
|
+
resolve();
|
|
762
|
+
});
|
|
763
|
+
socket.once("connect_error", (error) => {
|
|
764
|
+
clearTimeout(timer);
|
|
765
|
+
socket.close();
|
|
766
|
+
reject(new Error(`Could not connect to ${configuration.serverUrl}: ${error.message}`));
|
|
767
|
+
});
|
|
768
|
+
socket.connect();
|
|
769
|
+
});
|
|
770
|
+
return {
|
|
771
|
+
async rpcCall(payload, timeoutMs) {
|
|
772
|
+
const ack = await socket.timeout(timeoutMs).emitWithAck("rpc-call", payload);
|
|
773
|
+
return ack;
|
|
774
|
+
},
|
|
775
|
+
close() {
|
|
776
|
+
socket.close();
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
const RPC_RATE_LIMIT_ERROR = "RPC rate limit reached";
|
|
782
|
+
const RPC_ACCOUNT_RATE_LIMIT_ERROR = "RPC account rate limit reached";
|
|
783
|
+
const RPC_RATE_RETRY_MIN_DELAY_MS = 2e3;
|
|
784
|
+
const RPC_RATE_RETRY_MAX_DELAY_MS = 6e4;
|
|
785
|
+
const RPC_RATE_MAX_RETRIES = 2;
|
|
786
|
+
function isRpcRateLimitAck(ack) {
|
|
787
|
+
if (!ack || typeof ack !== "object") return false;
|
|
788
|
+
const a = ack;
|
|
789
|
+
if (a.ok !== false) return false;
|
|
790
|
+
if (a.code === "rpc_rate_limited" || a.code === "rpc_account_rate_limited") return true;
|
|
791
|
+
return a.error === RPC_RATE_LIMIT_ERROR || a.error === RPC_ACCOUNT_RATE_LIMIT_ERROR;
|
|
792
|
+
}
|
|
793
|
+
function rpcRateRetryDelayMs(attempt, retryAfterMs, random = Math.random()) {
|
|
794
|
+
if (typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
|
|
795
|
+
return Math.min(RPC_RATE_RETRY_MAX_DELAY_MS, Math.round(retryAfterMs * (1 + random * 0.5)));
|
|
796
|
+
}
|
|
797
|
+
const exponent = Math.max(0, Math.min(attempt, 32) - 1);
|
|
798
|
+
const ceiling = Math.min(RPC_RATE_RETRY_MIN_DELAY_MS * 2 ** exponent, RPC_RATE_RETRY_MAX_DELAY_MS);
|
|
799
|
+
return Math.round(RPC_RATE_RETRY_MIN_DELAY_MS + random * (ceiling - RPC_RATE_RETRY_MIN_DELAY_MS));
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const PERMISSION_OPS_CLIENT = "session-ops";
|
|
803
|
+
const PERMISSION_RPC_TIMEOUT_MS = 3e4;
|
|
804
|
+
const SETTLE_TIMEOUT_MS = 5e3;
|
|
805
|
+
const SETTLE_POLL_MS = 500;
|
|
806
|
+
function buildPermissionRpcPayload(requestId, verdict) {
|
|
807
|
+
if (verdict.kind === "approve") {
|
|
808
|
+
return {
|
|
809
|
+
id: requestId,
|
|
810
|
+
approved: true,
|
|
811
|
+
decision: verdict.forSession ? "approved_for_session" : "approved"
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
return {
|
|
815
|
+
id: requestId,
|
|
816
|
+
approved: false,
|
|
817
|
+
decision: "denied",
|
|
818
|
+
...verdict.reason ? { reason: verdict.reason } : {}
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
function interpretPermissionAck(ack, decryptResult) {
|
|
822
|
+
if (!ack.ok) {
|
|
823
|
+
const message = ack.error ?? "RPC call failed";
|
|
824
|
+
if (message === "RPC method not available") {
|
|
825
|
+
return { status: "offline", message: "no running wrapper has registered the permission RPC for this session" };
|
|
826
|
+
}
|
|
827
|
+
if (message === "RPC target disconnected") {
|
|
828
|
+
return { status: "offline", message: "the wrapper disconnected while the permission RPC was in flight" };
|
|
829
|
+
}
|
|
830
|
+
if (/timed? ?out/i.test(message)) {
|
|
831
|
+
return { status: "timeout", message };
|
|
832
|
+
}
|
|
833
|
+
if (isRpcRateLimitAck(ack)) {
|
|
834
|
+
return { status: "rate-limited", message, retryAfterMs: rpcRateRetryDelayMs(1, ack.retryAfterMs, 0) };
|
|
835
|
+
}
|
|
836
|
+
return { status: "rejected", message };
|
|
837
|
+
}
|
|
838
|
+
let body = null;
|
|
839
|
+
if (typeof ack.result === "string" && ack.result.length > 0) {
|
|
840
|
+
try {
|
|
841
|
+
body = decryptResult(ack.result);
|
|
842
|
+
} catch {
|
|
843
|
+
body = null;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
if (body && typeof body === "object" && typeof body.error === "string") {
|
|
847
|
+
return { status: "handler-error", message: body.error };
|
|
848
|
+
}
|
|
849
|
+
return { status: "acknowledged" };
|
|
850
|
+
}
|
|
851
|
+
function pendingRequestsOf(agentState, now) {
|
|
852
|
+
const requests = agentState?.requests;
|
|
853
|
+
if (!requests || typeof requests !== "object") return [];
|
|
854
|
+
return Object.entries(requests).map(([id, request]) => ({
|
|
855
|
+
id,
|
|
856
|
+
tool: typeof request?.tool === "string" ? request.tool : "unknown",
|
|
857
|
+
...request?.kind ? { kind: request.kind } : {},
|
|
858
|
+
...typeof request?.createdAt === "number" ? { createdAt: request.createdAt, waitingMs: Math.max(0, now - request.createdAt) } : {}
|
|
859
|
+
})).sort((a, b) => (a.createdAt ?? Number.MAX_SAFE_INTEGER) - (b.createdAt ?? Number.MAX_SAFE_INTEGER));
|
|
860
|
+
}
|
|
861
|
+
const RPC_DEADLINE_GRACE_MS = 2e3;
|
|
862
|
+
function withDeadline(promise, ms, message) {
|
|
863
|
+
return new Promise((resolve, reject) => {
|
|
864
|
+
const timer = setTimeout(() => reject(new Error(`${message} (timed out)`)), ms);
|
|
865
|
+
promise.then(
|
|
866
|
+
(value) => {
|
|
867
|
+
clearTimeout(timer);
|
|
868
|
+
resolve(value);
|
|
869
|
+
},
|
|
870
|
+
(error) => {
|
|
871
|
+
clearTimeout(timer);
|
|
872
|
+
reject(error);
|
|
873
|
+
}
|
|
874
|
+
);
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
async function resolvePermissionRequest(sessionId, requestId, verdict, deps = {}) {
|
|
878
|
+
const now = deps.now ?? Date.now;
|
|
879
|
+
const persisted = (deps.readPersisted ?? readPersistedSessions)()[sessionId];
|
|
880
|
+
if (!persisted) {
|
|
881
|
+
throw new Error(
|
|
882
|
+
`No local key for session ${sessionId} \u2014 approve/deny needs the session key from ~/.happy/sessions.json (the RPC payload is encrypted with it), so only sessions this machine's daemon spawned within 14 days can be answered from here.`
|
|
883
|
+
);
|
|
884
|
+
}
|
|
885
|
+
const token = await (deps.bearerToken ?? bearerToken$1)();
|
|
886
|
+
const fetchState = deps.fetchAgentState ?? fetchDecryptedAgentState;
|
|
887
|
+
const before = pendingRequestsOf(await fetchState(sessionId, persisted, token), now());
|
|
888
|
+
if (!before.some((request) => request.id === requestId)) {
|
|
889
|
+
const hint = before.length > 0 ? `Pending request ids: ${before.map((request) => `${request.id} (${request.tool})`).join(", ")}` : "The session has no pending requests.";
|
|
890
|
+
throw new Error(`Request ${requestId} is not pending on session ${sessionId}. ${hint}`);
|
|
891
|
+
}
|
|
892
|
+
const payload = buildPermissionRpcPayload(requestId, verdict);
|
|
893
|
+
const key = decodeBase64(persisted.encryptionKey);
|
|
894
|
+
const params = encodeBase64(encrypt(key, persisted.encryptionVariant, payload));
|
|
895
|
+
const transport = await (deps.openTransport ?? openUserScopedSocket)(token);
|
|
896
|
+
const rpcTimeoutMs = deps.rpcTimeoutMs ?? PERMISSION_RPC_TIMEOUT_MS;
|
|
897
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
898
|
+
let ack;
|
|
899
|
+
try {
|
|
900
|
+
for (let attempt = 1; ; attempt++) {
|
|
901
|
+
try {
|
|
902
|
+
ack = await withDeadline(
|
|
903
|
+
transport.rpcCall({ method: `${sessionId}:permission`, params }, rpcTimeoutMs),
|
|
904
|
+
rpcTimeoutMs + RPC_DEADLINE_GRACE_MS,
|
|
905
|
+
`permission RPC did not settle within ${rpcTimeoutMs}ms`
|
|
906
|
+
);
|
|
907
|
+
} catch (error) {
|
|
908
|
+
ack = { ok: false, error: error instanceof Error ? error.message : "RPC call failed" };
|
|
909
|
+
}
|
|
910
|
+
if (!isRpcRateLimitAck(ack) || attempt > RPC_RATE_MAX_RETRIES) break;
|
|
911
|
+
const waitMs = rpcRateRetryDelayMs(attempt, ack.retryAfterMs, (deps.random ?? Math.random)());
|
|
912
|
+
deps.onRateLimited?.({ attempt, waitMs, serverError: ack.error ?? "RPC rate limit reached" });
|
|
913
|
+
await sleep(waitMs);
|
|
914
|
+
}
|
|
915
|
+
} finally {
|
|
916
|
+
transport.close();
|
|
917
|
+
}
|
|
918
|
+
const outcome = interpretPermissionAck(ack, (encrypted) => decrypt(key, persisted.encryptionVariant, decodeBase64(encrypted)));
|
|
919
|
+
if (outcome.status !== "acknowledged") {
|
|
920
|
+
return { sessionId, requestId, payload, outcome };
|
|
921
|
+
}
|
|
922
|
+
const deadline = now() + (deps.settleTimeoutMs ?? SETTLE_TIMEOUT_MS);
|
|
923
|
+
let settled = false;
|
|
924
|
+
for (; ; ) {
|
|
925
|
+
const pending = pendingRequestsOf(await fetchState(sessionId, persisted, token), now());
|
|
926
|
+
if (!pending.some((request) => request.id === requestId)) {
|
|
927
|
+
settled = true;
|
|
928
|
+
break;
|
|
929
|
+
}
|
|
930
|
+
if (now() >= deadline) break;
|
|
931
|
+
await sleep(SETTLE_POLL_MS);
|
|
932
|
+
}
|
|
933
|
+
return { sessionId, requestId, payload, outcome, settled };
|
|
934
|
+
}
|
|
935
|
+
async function bearerToken$1() {
|
|
936
|
+
const credentials = await readCredentialsForConfiguredRelay();
|
|
937
|
+
if (!credentials) throw new Error("CLI is not authenticated (no ~/.happy/access.key)");
|
|
938
|
+
return credentials.token;
|
|
939
|
+
}
|
|
940
|
+
async function fetchDecryptedAgentState(sessionId, persisted, token) {
|
|
941
|
+
const response = await axios.get(
|
|
942
|
+
`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}`,
|
|
943
|
+
{
|
|
944
|
+
headers: {
|
|
945
|
+
"Authorization": `Bearer ${token}`,
|
|
946
|
+
"X-Happy-Client": `${PERMISSION_OPS_CLIENT}/${configuration.currentCliVersion}`
|
|
947
|
+
},
|
|
948
|
+
timeout: 15e3,
|
|
949
|
+
// 404 is a real answer ("not yours / gone"), not a transport fault.
|
|
950
|
+
validateStatus: (status) => status >= 200 && status < 300 || status === 404
|
|
951
|
+
}
|
|
952
|
+
);
|
|
953
|
+
if (response.status === 404) {
|
|
954
|
+
throw new Error(`Session ${sessionId} was not found on this account (it may have been deleted, or the local key belongs to a session on another relay).`);
|
|
955
|
+
}
|
|
956
|
+
const raw = response.data?.session?.agentState;
|
|
957
|
+
if (typeof raw !== "string" || raw.length === 0) return null;
|
|
958
|
+
return decrypt(decodeBase64(persisted.encryptionKey), persisted.encryptionVariant, decodeBase64(raw));
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
const SESSION_OPS_CLIENT = "session-ops";
|
|
962
|
+
const DEFAULT_RECENT_LIMIT = 15;
|
|
963
|
+
const MAX_READ_LIMIT = 100;
|
|
964
|
+
function mergeSessionSummaries(live, persisted, options = {}) {
|
|
965
|
+
const recentLimit = Math.max(0, options.recentLimit ?? DEFAULT_RECENT_LIMIT);
|
|
966
|
+
const seen = /* @__PURE__ */ new Set();
|
|
967
|
+
const summaries = [];
|
|
968
|
+
for (const child of live) {
|
|
969
|
+
const id = typeof child.happySessionId === "string" ? child.happySessionId : void 0;
|
|
970
|
+
if (!id || seen.has(id)) continue;
|
|
971
|
+
seen.add(id);
|
|
972
|
+
summaries.push(toSummary(id, persisted[id], livenessOf(child)));
|
|
973
|
+
}
|
|
974
|
+
const rest = Object.entries(persisted).filter(([id]) => !seen.has(id)).filter(([, entry]) => entry.metadata?.flavor !== "terminal-mirror").sort((a, b) => b[1].savedAt - a[1].savedAt).slice(0, recentLimit);
|
|
975
|
+
for (const [id, entry] of rest) {
|
|
976
|
+
summaries.push(toSummary(id, entry, { live: false }));
|
|
977
|
+
}
|
|
978
|
+
if (!options.tag) return summaries;
|
|
979
|
+
const wanted = options.tag;
|
|
980
|
+
return summaries.filter((summary) => summary.tags?.includes(wanted) === true);
|
|
981
|
+
}
|
|
982
|
+
function livenessOf(child) {
|
|
983
|
+
return { live: true, pid: typeof child.pid === "number" ? child.pid : void 0 };
|
|
984
|
+
}
|
|
985
|
+
function sessionLiveness(live, sessionId) {
|
|
986
|
+
const child = live.find((entry) => entry.happySessionId === sessionId);
|
|
987
|
+
return child ? livenessOf(child) : { live: false };
|
|
988
|
+
}
|
|
989
|
+
function toSummary(id, persisted, extra) {
|
|
990
|
+
const meta = persisted?.metadata;
|
|
991
|
+
return {
|
|
992
|
+
id,
|
|
993
|
+
live: extra.live,
|
|
994
|
+
...extra.pid !== void 0 ? { pid: extra.pid } : {},
|
|
995
|
+
...meta?.summary?.text ? { title: meta.summary.text } : {},
|
|
996
|
+
...meta?.path ? { cwd: meta.path } : {},
|
|
997
|
+
...meta?.flavor ? { flavor: meta.flavor } : {},
|
|
998
|
+
...meta?.tags?.length ? { tags: [...meta.tags] } : {},
|
|
999
|
+
...meta?.variant ? { variant: meta.variant } : {},
|
|
1000
|
+
url: sessionWebUrl(id),
|
|
1001
|
+
...persisted?.savedAt !== void 0 ? { savedAt: persisted.savedAt } : {}
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
async function listSessions(options = {}) {
|
|
1005
|
+
const live = await listDaemonSessions();
|
|
1006
|
+
return mergeSessionSummaries(live, readPersistedSessions(), options);
|
|
1007
|
+
}
|
|
1008
|
+
function summarizeAccountSession(row, persisted, liveIds, now) {
|
|
1009
|
+
const base = {
|
|
1010
|
+
id: row.id,
|
|
1011
|
+
live: liveIds.has(row.id),
|
|
1012
|
+
url: sessionWebUrl(row.id),
|
|
1013
|
+
decryptable: false,
|
|
1014
|
+
active: row.active === true,
|
|
1015
|
+
archived: typeof row.archivedAt === "number",
|
|
1016
|
+
...typeof row.activeAt === "number" ? { activeAt: row.activeAt } : {},
|
|
1017
|
+
...typeof row.updatedAt === "number" ? { updatedAt: row.updatedAt } : {},
|
|
1018
|
+
attention: false
|
|
1019
|
+
};
|
|
1020
|
+
if (!persisted) return base;
|
|
1021
|
+
const key = decodeBase64(persisted.encryptionKey);
|
|
1022
|
+
let metadata = null;
|
|
1023
|
+
let agentState = null;
|
|
1024
|
+
try {
|
|
1025
|
+
metadata = row.metadata ? decrypt(key, persisted.encryptionVariant, decodeBase64(row.metadata)) : null;
|
|
1026
|
+
agentState = row.agentState ? decrypt(key, persisted.encryptionVariant, decodeBase64(row.agentState)) : null;
|
|
1027
|
+
} catch {
|
|
1028
|
+
return base;
|
|
1029
|
+
}
|
|
1030
|
+
if (!metadata) return base;
|
|
1031
|
+
const meta = metadata;
|
|
1032
|
+
const pending = pendingRequestsOf(agentState, now);
|
|
1033
|
+
return {
|
|
1034
|
+
...base,
|
|
1035
|
+
decryptable: true,
|
|
1036
|
+
...meta.summary?.text ? { title: meta.summary.text } : {},
|
|
1037
|
+
...meta.path ? { cwd: meta.path } : {},
|
|
1038
|
+
...meta.flavor ? { flavor: meta.flavor } : {},
|
|
1039
|
+
...meta.tags?.length ? { tags: [...meta.tags] } : {},
|
|
1040
|
+
...meta.variant ? { variant: meta.variant } : {},
|
|
1041
|
+
...meta.machineId ? { machineId: meta.machineId } : {},
|
|
1042
|
+
...persisted.savedAt !== void 0 ? { savedAt: persisted.savedAt } : {},
|
|
1043
|
+
pending,
|
|
1044
|
+
attention: pending.length > 0
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
function orderAccountSessions(summaries, options = {}) {
|
|
1048
|
+
const oldestWait = (summary) => Math.max(0, ...(summary.pending ?? []).map((request) => request.waitingMs ?? 0));
|
|
1049
|
+
const rank = (summary) => summary.attention ? 0 : summary.live ? 1 : 2;
|
|
1050
|
+
let rows = summaries.filter((summary) => summary.flavor !== "terminal-mirror").slice().sort((a, b) => {
|
|
1051
|
+
const byRank = rank(a) - rank(b);
|
|
1052
|
+
if (byRank !== 0) return byRank;
|
|
1053
|
+
if (a.attention && b.attention) return oldestWait(b) - oldestWait(a);
|
|
1054
|
+
return (b.updatedAt ?? 0) - (a.updatedAt ?? 0);
|
|
1055
|
+
});
|
|
1056
|
+
if (options.tag) {
|
|
1057
|
+
const wanted = options.tag;
|
|
1058
|
+
rows = rows.filter((summary) => summary.tags?.includes(wanted) === true);
|
|
1059
|
+
}
|
|
1060
|
+
const recentLimit = Math.max(0, options.recentLimit ?? DEFAULT_RECENT_LIMIT);
|
|
1061
|
+
let idleKept = 0;
|
|
1062
|
+
return rows.filter((summary) => rank(summary) < 2 || idleKept++ < recentLimit);
|
|
1063
|
+
}
|
|
1064
|
+
async function listAccountSessions(options = {}) {
|
|
1065
|
+
const token = await bearerToken();
|
|
1066
|
+
const response = await axios.get(`${configuration.serverUrl}/v1/sessions`, {
|
|
1067
|
+
headers: {
|
|
1068
|
+
"Authorization": `Bearer ${token}`,
|
|
1069
|
+
"X-Happy-Client": `${SESSION_OPS_CLIENT}/${configuration.currentCliVersion}`
|
|
1070
|
+
},
|
|
1071
|
+
timeout: 15e3
|
|
1072
|
+
});
|
|
1073
|
+
const rows = Array.isArray(response.data?.sessions) ? response.data.sessions : [];
|
|
1074
|
+
const persisted = readPersistedSessions();
|
|
1075
|
+
const live = await listDaemonSessions();
|
|
1076
|
+
const liveIds = new Set(live.map((child) => child.happySessionId).filter((id) => typeof id === "string"));
|
|
1077
|
+
const now = Date.now();
|
|
1078
|
+
const summaries = rows.filter((row) => typeof row?.id === "string").map((row) => summarizeAccountSession(row, persisted[row.id], liveIds, now)).filter((summary) => options.includeArchived || !summary.archived);
|
|
1079
|
+
return orderAccountSessions(summaries, options);
|
|
1080
|
+
}
|
|
1081
|
+
async function bearerToken() {
|
|
1082
|
+
const credentials = await readCredentialsForConfiguredRelay();
|
|
1083
|
+
if (!credentials) throw new Error("CLI is not authenticated (no ~/.happy/access.key)");
|
|
1084
|
+
return credentials.token;
|
|
1085
|
+
}
|
|
1086
|
+
function requirePersisted(sessionId) {
|
|
1087
|
+
const persisted = readPersistedSessions()[sessionId];
|
|
1088
|
+
if (!persisted) {
|
|
1089
|
+
throw new Error(
|
|
1090
|
+
`No local key for session ${sessionId} \u2014 it was not spawned by this machine's daemon (or is older than 14 days).`
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
return persisted;
|
|
1094
|
+
}
|
|
1095
|
+
async function readSessionLog(sessionId, persisted, limit) {
|
|
1096
|
+
const token = await bearerToken();
|
|
1097
|
+
const response = await axios.get(
|
|
1098
|
+
`${configuration.serverUrl}/v3/sessions/${encodeURIComponent(sessionId)}/messages`,
|
|
1099
|
+
{
|
|
1100
|
+
params: { before_seq: 2147483647, limit },
|
|
1101
|
+
headers: {
|
|
1102
|
+
"Authorization": `Bearer ${token}`,
|
|
1103
|
+
"X-Happy-Client": `${SESSION_OPS_CLIENT}/${configuration.currentCliVersion}`
|
|
1104
|
+
},
|
|
1105
|
+
timeout: 15e3
|
|
1106
|
+
}
|
|
1107
|
+
);
|
|
1108
|
+
const messages = Array.isArray(response.data?.messages) ? response.data.messages : [];
|
|
1109
|
+
messages.reverse();
|
|
1110
|
+
const key = decodeBase64(persisted.encryptionKey);
|
|
1111
|
+
return messages.map((message) => {
|
|
1112
|
+
if (message.content?.t !== "encrypted") return { seq: message.seq, body: null };
|
|
1113
|
+
try {
|
|
1114
|
+
return { seq: message.seq, body: decrypt(key, persisted.encryptionVariant, decodeBase64(message.content.c)) };
|
|
1115
|
+
} catch {
|
|
1116
|
+
return { seq: message.seq, body: null };
|
|
1117
|
+
}
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1120
|
+
const TURN_WINDOW = 500;
|
|
1121
|
+
async function readSessionTranscript(sessionId, limit, options = {}) {
|
|
1122
|
+
const persisted = requirePersisted(sessionId);
|
|
1123
|
+
const bounded = Math.max(1, Math.min(MAX_READ_LIMIT, Math.floor(limit)));
|
|
1124
|
+
const entries = await readSessionLog(sessionId, persisted, Math.max(bounded, TURN_WINDOW));
|
|
1125
|
+
const shown = entries.slice(-bounded);
|
|
1126
|
+
const live = await listDaemonSessions();
|
|
1127
|
+
return {
|
|
1128
|
+
summary: toSummary(sessionId, persisted, sessionLiveness(live, sessionId)),
|
|
1129
|
+
messageCount: shown.length,
|
|
1130
|
+
transcript: formatTranscript(shown.map((entry) => entry.body), { full: options.full }),
|
|
1131
|
+
turn: analyzeLatestTurn(entries)
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
async function readSessionMetadata(sessionId, persisted) {
|
|
1135
|
+
const token = await bearerToken();
|
|
1136
|
+
const response = await axios.get(`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}`, {
|
|
1137
|
+
headers: {
|
|
1138
|
+
"Authorization": `Bearer ${token}`,
|
|
1139
|
+
"X-Happy-Client": `${SESSION_OPS_CLIENT}/${configuration.currentCliVersion}`
|
|
1140
|
+
},
|
|
1141
|
+
timeout: 15e3
|
|
1142
|
+
});
|
|
1143
|
+
const ciphertext = response.data?.session?.metadata;
|
|
1144
|
+
if (typeof ciphertext !== "string" || ciphertext.length === 0) return null;
|
|
1145
|
+
return decrypt(decodeBase64(persisted.encryptionKey), persisted.encryptionVariant, decodeBase64(ciphertext));
|
|
1146
|
+
}
|
|
1147
|
+
async function readSessionState(sessionId, persisted) {
|
|
1148
|
+
const token = await bearerToken();
|
|
1149
|
+
const response = await axios.get(`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}`, {
|
|
1150
|
+
headers: {
|
|
1151
|
+
"Authorization": `Bearer ${token}`,
|
|
1152
|
+
"X-Happy-Client": `${SESSION_OPS_CLIENT}/${configuration.currentCliVersion}`
|
|
1153
|
+
},
|
|
1154
|
+
timeout: 15e3,
|
|
1155
|
+
validateStatus: (status) => status >= 200 && status < 300 || status === 404
|
|
1156
|
+
});
|
|
1157
|
+
if (response.status === 404) return { found: false, active: false };
|
|
1158
|
+
const row = response.data?.session;
|
|
1159
|
+
if (!row || typeof row.id !== "string") throw new Error(`Server returned no session row for ${sessionId}`);
|
|
1160
|
+
const state = {
|
|
1161
|
+
found: true,
|
|
1162
|
+
active: row.active === true,
|
|
1163
|
+
...typeof row.activeAt === "number" ? { activeAt: row.activeAt } : {},
|
|
1164
|
+
archivedAt: typeof row.archivedAt === "number" ? row.archivedAt : null,
|
|
1165
|
+
...typeof row.updatedAt === "number" ? { updatedAt: row.updatedAt } : {}
|
|
1166
|
+
};
|
|
1167
|
+
if (persisted && typeof row.metadata === "string" && row.metadata.length > 0) {
|
|
1168
|
+
try {
|
|
1169
|
+
const metadata = decrypt(decodeBase64(persisted.encryptionKey), persisted.encryptionVariant, decodeBase64(row.metadata));
|
|
1170
|
+
if (metadata?.machineId) state.machineId = metadata.machineId;
|
|
1171
|
+
} catch {
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
return state;
|
|
1175
|
+
}
|
|
1176
|
+
class TurnWaitTimeoutError extends Error {
|
|
1177
|
+
constructor(sessionId, timeoutMs, turn) {
|
|
1178
|
+
super(`Session ${sessionId}: the latest turn did not end within ${Math.round(timeoutMs / 1e3)}s`);
|
|
1179
|
+
this.sessionId = sessionId;
|
|
1180
|
+
this.timeoutMs = timeoutMs;
|
|
1181
|
+
this.turn = turn;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
async function waitForTurnEnd(sessionId, options) {
|
|
1185
|
+
const persisted = requirePersisted(sessionId);
|
|
1186
|
+
const pollMs = options.pollMs ?? 3e3;
|
|
1187
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1188
|
+
const deadline = Date.now() + options.timeoutMs;
|
|
1189
|
+
while (true) {
|
|
1190
|
+
const turn = analyzeLatestTurn(await readSessionLog(sessionId, persisted, TURN_WINDOW));
|
|
1191
|
+
if (turn.ended) return turn;
|
|
1192
|
+
if (Date.now() + pollMs > deadline) throw new TurnWaitTimeoutError(sessionId, options.timeoutMs, turn);
|
|
1193
|
+
await sleep(pollMs);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
async function stopSession(sessionId) {
|
|
1197
|
+
return await stopDaemonSession(sessionId);
|
|
1198
|
+
}
|
|
1199
|
+
async function archiveSession(sessionId) {
|
|
1200
|
+
const token = await bearerToken();
|
|
1201
|
+
await axios.post(
|
|
1202
|
+
`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}/archive`,
|
|
1203
|
+
{},
|
|
1204
|
+
{
|
|
1205
|
+
headers: {
|
|
1206
|
+
"Authorization": `Bearer ${token}`,
|
|
1207
|
+
"X-Happy-Client": `${SESSION_OPS_CLIENT}/${configuration.currentCliVersion}`
|
|
1208
|
+
},
|
|
1209
|
+
timeout: 1e4
|
|
1210
|
+
}
|
|
1211
|
+
);
|
|
1212
|
+
}
|
|
1213
|
+
async function unarchiveSession(sessionId) {
|
|
1214
|
+
const token = await bearerToken();
|
|
1215
|
+
await axios.post(
|
|
1216
|
+
`${configuration.serverUrl}/v1/sessions/${encodeURIComponent(sessionId)}/unarchive`,
|
|
1217
|
+
{},
|
|
1218
|
+
{
|
|
1219
|
+
headers: {
|
|
1220
|
+
"Authorization": `Bearer ${token}`,
|
|
1221
|
+
"X-Happy-Client": `${SESSION_OPS_CLIENT}/${configuration.currentCliVersion}`
|
|
1222
|
+
},
|
|
1223
|
+
timeout: 1e4
|
|
1224
|
+
}
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
const ACTIVE_FRESH_WINDOW_MS = 15 * 60 * 1e3;
|
|
1229
|
+
const DEFAULT_RESUME_WAIT_MS = 3e4;
|
|
1230
|
+
const DEFAULT_RESUME_POLL_MS = 1e3;
|
|
1231
|
+
function classifySessionState(input) {
|
|
1232
|
+
const { liveHere, server, now } = input;
|
|
1233
|
+
if (!server.found) return "not_found";
|
|
1234
|
+
if (typeof server.archivedAt === "number") return "archived";
|
|
1235
|
+
if (liveHere) return "live";
|
|
1236
|
+
if (server.active && typeof server.activeAt === "number" && now - server.activeAt <= ACTIVE_FRESH_WINDOW_MS) return "live";
|
|
1237
|
+
return "offline";
|
|
1238
|
+
}
|
|
1239
|
+
function explainNotLive(sessionId, status, resumeHint) {
|
|
1240
|
+
switch (status) {
|
|
1241
|
+
case "archived":
|
|
1242
|
+
return `Session ${sessionId} is archived \u2014 no live wrapper will receive this message. ${resumeHint}`;
|
|
1243
|
+
case "offline":
|
|
1244
|
+
return `Session ${sessionId} is offline (its wrapper exited or timed out) \u2014 no live wrapper will receive this message. ${resumeHint}`;
|
|
1245
|
+
case "not_found":
|
|
1246
|
+
return `Session ${sessionId} was not found on this account \u2014 it cannot be messaged or resumed. Spawn a new session instead.`;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
const CLI_RESUME_HINT = "Use --resume to bring it back on this machine, or spawn a new session.";
|
|
1250
|
+
const defaultDeps = {
|
|
1251
|
+
listLive: () => listDaemonSessions(),
|
|
1252
|
+
readState: (sessionId, persisted) => readSessionState(sessionId, persisted),
|
|
1253
|
+
send: (sessionId, persisted, text, client, options) => sendUserMessage(sessionId, persisted, text, client, options),
|
|
1254
|
+
unarchive: unarchiveSession,
|
|
1255
|
+
archive: archiveSession,
|
|
1256
|
+
resume: resumeDaemonSession,
|
|
1257
|
+
sleep: (ms) => delay(ms).then(() => void 0),
|
|
1258
|
+
now: () => Date.now()
|
|
1259
|
+
};
|
|
1260
|
+
async function deliverToSession(sessionId, persisted, text, client, options = {}, deps = {}) {
|
|
1261
|
+
const d = { ...defaultDeps, ...deps };
|
|
1262
|
+
const resumeHint = options.resumeHint ?? CLI_RESUME_HINT;
|
|
1263
|
+
const classify = async () => {
|
|
1264
|
+
const [live, server] = await Promise.all([d.listLive(), d.readState(sessionId, persisted)]);
|
|
1265
|
+
return classifySessionState({ liveHere: sessionLiveness(live, sessionId).live, server, now: d.now() });
|
|
1266
|
+
};
|
|
1267
|
+
let status = await classify();
|
|
1268
|
+
let resumed = false;
|
|
1269
|
+
let resumeOutcome;
|
|
1270
|
+
if (status !== "live") {
|
|
1271
|
+
if (!options.resume || status === "not_found") {
|
|
1272
|
+
return { sessionId, status, delivered: false, resumed: false, stored: false, error: explainNotLive(sessionId, status, resumeHint) };
|
|
1273
|
+
}
|
|
1274
|
+
const wasArchived = status === "archived";
|
|
1275
|
+
if (wasArchived) {
|
|
1276
|
+
try {
|
|
1277
|
+
await d.unarchive(sessionId);
|
|
1278
|
+
} catch (error) {
|
|
1279
|
+
const message = `unarchive failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
1280
|
+
return { sessionId, status, delivered: false, resumed: false, stored: false, error: message, resume: { ok: false, error: message } };
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
const outcome = await d.resume(sessionId, {
|
|
1284
|
+
...typeof options.model === "string" ? { model: options.model } : {},
|
|
1285
|
+
...options.permissionMode !== void 0 ? { permissionMode: options.permissionMode } : {}
|
|
1286
|
+
});
|
|
1287
|
+
if (!outcome.success) {
|
|
1288
|
+
let message = outcome.error ?? "resume failed";
|
|
1289
|
+
if (wasArchived) {
|
|
1290
|
+
try {
|
|
1291
|
+
await d.archive(sessionId);
|
|
1292
|
+
} catch (error) {
|
|
1293
|
+
message += `; failed to restore archive state: ${error instanceof Error ? error.message : String(error)}`;
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
return { sessionId, status, delivered: false, resumed: false, stored: false, error: message, resume: { ok: false, error: message } };
|
|
1297
|
+
}
|
|
1298
|
+
resumed = true;
|
|
1299
|
+
resumeOutcome = { ok: true };
|
|
1300
|
+
status = await waitUntilLive(classify, d, options);
|
|
1301
|
+
if (status !== "live") {
|
|
1302
|
+
const waited = Math.round((options.waitMs ?? DEFAULT_RESUME_WAIT_MS) / 1e3);
|
|
1303
|
+
return {
|
|
1304
|
+
sessionId,
|
|
1305
|
+
status,
|
|
1306
|
+
delivered: false,
|
|
1307
|
+
resumed,
|
|
1308
|
+
stored: false,
|
|
1309
|
+
resume: resumeOutcome,
|
|
1310
|
+
error: `Session ${sessionId} was resumed but no live wrapper showed up within ${waited}s (state: ${status}); message not sent`
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
await d.send(sessionId, persisted, text, client, {
|
|
1315
|
+
...options.model !== void 0 ? { model: options.model } : {},
|
|
1316
|
+
...options.sentFrom !== void 0 ? { sentFrom: options.sentFrom } : {}
|
|
1317
|
+
});
|
|
1318
|
+
let after = "live";
|
|
1319
|
+
try {
|
|
1320
|
+
after = await classify();
|
|
1321
|
+
} catch {
|
|
1322
|
+
after = "live";
|
|
1323
|
+
}
|
|
1324
|
+
if (after !== "live") {
|
|
1325
|
+
return {
|
|
1326
|
+
sessionId,
|
|
1327
|
+
status: after,
|
|
1328
|
+
delivered: false,
|
|
1329
|
+
resumed,
|
|
1330
|
+
stored: true,
|
|
1331
|
+
...resumeOutcome ? { resume: resumeOutcome } : {},
|
|
1332
|
+
error: `Session ${sessionId} went ${after} while sending: the message is stored server-side but no wrapper is attached to read it. ${after === "not_found" ? "Spawn a new session." : resumeHint}`
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
return { sessionId, status: "live", delivered: true, resumed, stored: true, ...resumeOutcome ? { resume: resumeOutcome } : {} };
|
|
1336
|
+
}
|
|
1337
|
+
async function waitUntilLive(classify, d, options) {
|
|
1338
|
+
const waitMs = options.waitMs ?? DEFAULT_RESUME_WAIT_MS;
|
|
1339
|
+
const pollMs = options.pollMs ?? DEFAULT_RESUME_POLL_MS;
|
|
1340
|
+
const deadline = d.now() + waitMs;
|
|
1341
|
+
let status = await classify();
|
|
1342
|
+
while (status !== "live" && d.now() < deadline) {
|
|
1343
|
+
await d.sleep(pollMs);
|
|
1344
|
+
status = await classify();
|
|
1345
|
+
}
|
|
1346
|
+
return status;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
const SESSION_PEER_SENT_FROM = "session-peer";
|
|
1350
|
+
const CLI_PEER_SENDER_ID = "cli";
|
|
1351
|
+
const MESSAGE_FOOTER = "This message comes from another agent session on this machine, not from the user.";
|
|
1352
|
+
function sanitizeHeaderValue(value, max = 200) {
|
|
1353
|
+
if (!value) return "";
|
|
1354
|
+
const collapsed = value.replace(/\s+/g, " ").trim().slice(0, max);
|
|
1355
|
+
return collapsed.replace(/[%"\];]/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
|
|
1356
|
+
}
|
|
1357
|
+
function senderFields(sender) {
|
|
1358
|
+
const parts = [];
|
|
1359
|
+
if (sender.flavor) parts.push(`agent ${sanitizeHeaderValue(sender.flavor, 32)}`);
|
|
1360
|
+
if (sender.cwd) parts.push(`cwd ${sanitizeHeaderValue(sender.cwd, 400)}`);
|
|
1361
|
+
return parts.map((part) => `; ${part}`).join("");
|
|
1362
|
+
}
|
|
1363
|
+
function quotedTitle(sender) {
|
|
1364
|
+
return `"${sanitizeHeaderValue(sender.title, 120)}"`;
|
|
1365
|
+
}
|
|
1366
|
+
function formatSessionPeerMessage(input) {
|
|
1367
|
+
const header = `[Very Happy session message ${input.id} from ${quotedTitle(input.from)} ${input.from.sessionId}${senderFields(input.from)}${input.replyTo ? `; re ${sanitizeHeaderValue(input.replyTo, 64)}` : ""}]`;
|
|
1368
|
+
const footer = input.from.sessionId === CLI_PEER_SENDER_ID ? `${MESSAGE_FOOTER} It was sent from the command line (\`very-happy sessions message\`), so there is no session to reply to; act on it here.` : `${MESSAGE_FOOTER} Reply with session_message(to: "${input.from.sessionId}") \u2014 or \`very-happy sessions message ${input.from.sessionId} "<text>"\` \u2014 only when you have something to add (a question, a decision, a heads-up). Do not reply just to acknowledge or thank; the exchange ends when nothing is left to coordinate.`;
|
|
1369
|
+
return `${header}
|
|
1370
|
+
${input.body.trim()}
|
|
1371
|
+
|
|
1372
|
+
${footer}`;
|
|
1373
|
+
}
|
|
1374
|
+
function formatDuration(ms) {
|
|
1375
|
+
const seconds = Math.max(0, Math.round(ms / 1e3));
|
|
1376
|
+
if (seconds < 90) return `${seconds}s`;
|
|
1377
|
+
const minutes = Math.round(seconds / 60);
|
|
1378
|
+
if (minutes < 90) return `${minutes}m`;
|
|
1379
|
+
return `${Math.round(minutes / 60)}h`;
|
|
1380
|
+
}
|
|
1381
|
+
function formatEditConflictNotice(input) {
|
|
1382
|
+
const paths = input.paths && input.paths.length > 0 ? input.paths : [input.path];
|
|
1383
|
+
const more = paths.length - 1;
|
|
1384
|
+
const header = `[Very Happy edit conflict ${input.id}; file ${sanitizeHeaderValue(paths[0], 600)}${more > 0 ? `; more ${more}` : ""}; peer ${quotedTitle(input.peer)} ${input.peer.sessionId}${senderFields(input.peer)}; peer edited ${formatDuration(input.peerEditedAgoMs)} ago]`;
|
|
1385
|
+
const window = formatDuration(input.windowMs);
|
|
1386
|
+
const mirror = input.peer.flavor === "terminal-mirror";
|
|
1387
|
+
const what = more > 0 ? `the same ${paths.length} files` : "the same file";
|
|
1388
|
+
const advice = mirror ? `The peer is a terminal session (agent terminal-mirror): it cannot be messaged, and the person at that terminal owns those edits \u2014 re-read the file before changing it further and keep your change minimal.` : `No lock is held \u2014 coordinate before continuing: session_message(to: "${input.peer.sessionId}", body: "\u2026") saying what you are changing in ${more > 0 ? "these files" : "that file"} and asking what they are changing. One message that covers everything; do not send one per file.`;
|
|
1389
|
+
const list = more > 0 ? `
|
|
1390
|
+
Files:
|
|
1391
|
+
${paths.map((p) => `- ${p}`).join("\n")}` : "";
|
|
1392
|
+
return `${header}
|
|
1393
|
+
Another session on this machine edited ${what} within the last ${window}. Both sessions received this notice. ${advice}${list}`;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
const realFs = {
|
|
1397
|
+
existsSync,
|
|
1398
|
+
isDirectory: (path) => {
|
|
1399
|
+
try {
|
|
1400
|
+
return statSync(path).isDirectory();
|
|
1401
|
+
} catch {
|
|
1402
|
+
return false;
|
|
1403
|
+
}
|
|
1404
|
+
},
|
|
1405
|
+
readFileSync: (path) => readFileSync(path, "utf8")
|
|
1406
|
+
};
|
|
1407
|
+
function resolveRepoIdentity(cwd, fs = realFs) {
|
|
1408
|
+
let dir = resolve$1(cwd);
|
|
1409
|
+
for (let depth = 0; depth < 64; depth++) {
|
|
1410
|
+
const dotGit = resolve$1(dir, ".git");
|
|
1411
|
+
try {
|
|
1412
|
+
if (fs.existsSync(dotGit)) {
|
|
1413
|
+
if (fs.isDirectory(dotGit)) return { root: dir, common: dotGit };
|
|
1414
|
+
const gitdir = fs.readFileSync(dotGit).match(/^gitdir:\s*(.+?)\s*$/m)?.[1];
|
|
1415
|
+
if (gitdir) {
|
|
1416
|
+
const absolute = isAbsolute(gitdir) ? gitdir : resolve$1(dir, gitdir);
|
|
1417
|
+
const worktree = absolute.match(/^(.*[\\/]\.git)[\\/]worktrees[\\/][^\\/]+[\\/]?$/);
|
|
1418
|
+
return { root: dir, common: worktree ? worktree[1] : absolute };
|
|
1419
|
+
}
|
|
1420
|
+
return { root: dir, common: dotGit };
|
|
1421
|
+
}
|
|
1422
|
+
} catch {
|
|
1423
|
+
}
|
|
1424
|
+
const parent = dirname(dir);
|
|
1425
|
+
if (parent === dir) break;
|
|
1426
|
+
dir = parent;
|
|
1427
|
+
}
|
|
1428
|
+
return { root: null, common: null };
|
|
1429
|
+
}
|
|
1430
|
+
const PEER_SCOPES = ["repo", "cwd", "machine"];
|
|
1431
|
+
function isPeerInScope(scope, self, other) {
|
|
1432
|
+
if (scope === "machine") return true;
|
|
1433
|
+
if (scope === "cwd") return resolve$1(self.cwd) === resolve$1(other.cwd);
|
|
1434
|
+
if (self.repo.common && other.repo.common) return self.repo.common === other.repo.common;
|
|
1435
|
+
return resolve$1(self.cwd) === resolve$1(other.cwd);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
const SESSION_PEER_TOOL_NAMES = ["session_message", "session_peers"];
|
|
1439
|
+
const SESSION_PEER_TOOL_SCHEMAS = {
|
|
1440
|
+
session_message: {
|
|
1441
|
+
title: "Message Another Session",
|
|
1442
|
+
readOnly: false,
|
|
1443
|
+
description: "Send a message to another agent session running on this machine (find ids with session_peers). It lands in that session's chat with your title, session id and cwd, and tells the peer how to reply to you. Use it to coordinate when you both edit the same files: say what you are changing and ask what they are changing. Returns as soon as the message is queued; the reply arrives later as a message from that session. Only sessions this machine's daemon runs can be reached; terminal-mirror sessions cannot receive messages.",
|
|
1444
|
+
inputSchema: {
|
|
1445
|
+
to: z.string().min(1).max(128).describe("Target session id (from session_peers, or a peer's message header)"),
|
|
1446
|
+
body: z.string().min(1).max(16e3).describe("The message text"),
|
|
1447
|
+
replyTo: z.string().min(1).max(64).optional().describe("Id of the peer message you are answering (from its header), if any")
|
|
1448
|
+
}
|
|
1449
|
+
},
|
|
1450
|
+
session_peers: {
|
|
1451
|
+
title: "List Peer Sessions",
|
|
1452
|
+
readOnly: true,
|
|
1453
|
+
description: 'List the other agent sessions running on this machine and the files each edited in the last 30 minutes. Default scope "repo": sessions in the same git repository, including its other worktrees (sameWorktree says whether they share your checkout). "cwd": the same directory only. "machine": every live session here.',
|
|
1454
|
+
inputSchema: {
|
|
1455
|
+
scope: z.enum(["repo", "cwd", "machine"]).optional().describe("repo (default) | cwd | machine")
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
};
|
|
1459
|
+
const PEER_MESSAGE_RATE_LIMIT = 8;
|
|
1460
|
+
const PEER_MESSAGE_RATE_WINDOW_MS = 10 * 6e4;
|
|
1461
|
+
async function listPeerSessions(context, scope = "repo") {
|
|
1462
|
+
const self = context.self();
|
|
1463
|
+
const repoOf = context.repoOf ?? resolveRepoIdentity;
|
|
1464
|
+
const selfRepo = repoOf(self.cwd);
|
|
1465
|
+
const sessions = await (context.listPeers ?? listDaemonPeers)();
|
|
1466
|
+
const peers = sessions.filter((session) => session.sessionId !== self.sessionId).filter((session) => {
|
|
1467
|
+
const cwd = session.cwd ?? "";
|
|
1468
|
+
if (!cwd) return scope === "machine";
|
|
1469
|
+
return isPeerInScope(scope, { cwd: self.cwd, repo: selfRepo }, { cwd, repo: repoOf(cwd) });
|
|
1470
|
+
}).map((session) => ({
|
|
1471
|
+
...session,
|
|
1472
|
+
url: sessionWebUrl(session.sessionId),
|
|
1473
|
+
sameWorktree: !!session.cwd && !!selfRepo.root && repoOf(session.cwd).root === selfRepo.root
|
|
1474
|
+
}));
|
|
1475
|
+
return { self: { sessionId: self.sessionId, cwd: self.cwd, repoRoot: selfRepo.root, scope }, scope, peers };
|
|
1476
|
+
}
|
|
1477
|
+
function defaultDeliver(to, persisted, text, localId) {
|
|
1478
|
+
return deliverToSession(to, persisted, text, "session-message", {
|
|
1479
|
+
sentFrom: SESSION_PEER_SENT_FROM,
|
|
1480
|
+
resumeHint: "It has to be running to read a peer message; spawn a new session or ask the person."
|
|
1481
|
+
}, {
|
|
1482
|
+
send: (sessionId, key, body, client, options) => sendUserMessage(sessionId, key, body, client, { ...options, localId })
|
|
1483
|
+
});
|
|
1484
|
+
}
|
|
1485
|
+
function checkPeerSendBudget(sentTo, to, now, limit = PEER_MESSAGE_RATE_LIMIT, windowMs = PEER_MESSAGE_RATE_WINDOW_MS) {
|
|
1486
|
+
const recent = (sentTo.get(to) ?? []).filter((t) => now - t <= windowMs);
|
|
1487
|
+
sentTo.set(to, recent);
|
|
1488
|
+
return { ok: recent.length < limit, count: recent.length };
|
|
1489
|
+
}
|
|
1490
|
+
async function sendPeerMessage(context, args) {
|
|
1491
|
+
const self = context.self();
|
|
1492
|
+
if (!isValidSessionId(args.to)) throw new Error("Invalid session id");
|
|
1493
|
+
if (args.to === self.sessionId) throw new Error("That is this session; message a peer instead");
|
|
1494
|
+
const body = typeof args.body === "string" ? args.body.trim() : "";
|
|
1495
|
+
if (!body) throw new Error("body must be non-empty");
|
|
1496
|
+
const persisted = (context.readPersisted ?? readPersistedSessions)()[args.to];
|
|
1497
|
+
if (!persisted) {
|
|
1498
|
+
throw new Error(`Session ${args.to} is not on this machine (no local key); messaging sessions on other machines is not supported yet`);
|
|
1499
|
+
}
|
|
1500
|
+
const live = (await (context.listPeers ?? listDaemonPeers)()).find((session) => session.sessionId === args.to);
|
|
1501
|
+
if (!live) throw new Error(`Session ${args.to} is not running on this machine; nothing would read the message`);
|
|
1502
|
+
if (live.kind === "mirror") throw new Error(`Session ${args.to} is a terminal mirror (a person typing claude in a terminal); it cannot receive messages`);
|
|
1503
|
+
const now = (context.now ?? Date.now)();
|
|
1504
|
+
if (context.sentTo) {
|
|
1505
|
+
const budget = checkPeerSendBudget(context.sentTo, args.to, now);
|
|
1506
|
+
if (!budget.ok) {
|
|
1507
|
+
throw new Error(`Refused: this session already sent ${budget.count} messages to ${args.to} in the last ${Math.round(PEER_MESSAGE_RATE_WINDOW_MS / 6e4)} minutes. That is a reply loop, not coordination \u2014 STOP replying to that session now; do not send acknowledgements or thanks. Continue your own work.`);
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
const messageId = randomUUID().slice(0, 8);
|
|
1511
|
+
const text = formatSessionPeerMessage({ id: messageId, from: self, body, replyTo: args.replyTo });
|
|
1512
|
+
const result = await (context.deliver ?? defaultDeliver)(args.to, persisted, text, `session-message-${messageId}`);
|
|
1513
|
+
context.sentTo?.get(args.to)?.push(now);
|
|
1514
|
+
return {
|
|
1515
|
+
delivered: result.delivered,
|
|
1516
|
+
stored: result.stored,
|
|
1517
|
+
status: result.status,
|
|
1518
|
+
messageId,
|
|
1519
|
+
to: args.to,
|
|
1520
|
+
url: sessionWebUrl(args.to),
|
|
1521
|
+
...result.error ? { error: result.error } : {}
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
async function executeSessionPeerTool(name, args, context) {
|
|
1525
|
+
switch (name) {
|
|
1526
|
+
case "session_message":
|
|
1527
|
+
return sendPeerMessage(context, { to: String(args?.to ?? ""), body: String(args?.body ?? ""), ...args?.replyTo ? { replyTo: String(args.replyTo) } : {} });
|
|
1528
|
+
case "session_peers": {
|
|
1529
|
+
const scope = args?.scope;
|
|
1530
|
+
if (scope !== void 0 && !PEER_SCOPES.includes(scope)) throw new Error(`scope must be one of ${PEER_SCOPES.join(", ")}`);
|
|
1531
|
+
return listPeerSessions(context, scope ?? "repo");
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
function cliPeerSelf(env, cwd, persisted) {
|
|
1536
|
+
const sessionId = env.VH_PEER_SESSION_ID;
|
|
1537
|
+
if (sessionId && isValidSessionId(sessionId)) {
|
|
1538
|
+
const meta = persisted[sessionId]?.metadata;
|
|
1539
|
+
return { sessionId, title: meta?.summary?.text, flavor: meta?.flavor, cwd: meta?.path ?? cwd };
|
|
1540
|
+
}
|
|
1541
|
+
let user = "user";
|
|
1542
|
+
try {
|
|
1543
|
+
user = userInfo().username;
|
|
1544
|
+
} catch {
|
|
1545
|
+
}
|
|
1546
|
+
return { sessionId: CLI_PEER_SENDER_ID, title: `cli ${user}@${hostname()}`, flavor: "cli", cwd };
|
|
1547
|
+
}
|
|
1548
|
+
function createSessionPeerToolExecutor(client) {
|
|
1549
|
+
const context = {
|
|
1550
|
+
self: () => {
|
|
1551
|
+
const meta = client.getMetadata();
|
|
1552
|
+
return { sessionId: client.sessionId, title: meta?.summary?.text, flavor: meta?.flavor, cwd: meta?.path ?? process.cwd() };
|
|
1553
|
+
},
|
|
1554
|
+
// One budget per session process: the reply-loop guard.
|
|
1555
|
+
sentTo: /* @__PURE__ */ new Map()
|
|
1556
|
+
};
|
|
1557
|
+
return (name, args) => executeSessionPeerTool(name, args, context);
|
|
1558
|
+
}
|
|
1559
|
+
function registerSessionPeerTools(server, execute) {
|
|
1560
|
+
for (const name of SESSION_PEER_TOOL_NAMES) {
|
|
1561
|
+
const spec = SESSION_PEER_TOOL_SCHEMAS[name];
|
|
1562
|
+
server.registerTool(name, {
|
|
1563
|
+
description: spec.description,
|
|
1564
|
+
title: spec.title,
|
|
1565
|
+
inputSchema: spec.inputSchema,
|
|
1566
|
+
annotations: { readOnlyHint: spec.readOnly, idempotentHint: spec.readOnly, openWorldHint: false, destructiveHint: false }
|
|
1567
|
+
}, async (args) => {
|
|
1568
|
+
try {
|
|
1569
|
+
return { content: [{ type: "text", text: JSON.stringify(await execute(name, args ?? {})) }], isError: false };
|
|
1570
|
+
} catch (error) {
|
|
1571
|
+
return { content: [{ type: "text", text: error instanceof Error ? error.message : "Session peer operation failed" }], isError: true };
|
|
1572
|
+
}
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
function trimIdent(text) {
|
|
1578
|
+
const lines = text.split("\n");
|
|
1579
|
+
while (lines.length > 0 && lines[0].trim() === "") {
|
|
1580
|
+
lines.shift();
|
|
1581
|
+
}
|
|
1582
|
+
while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
|
|
1583
|
+
lines.pop();
|
|
1584
|
+
}
|
|
1585
|
+
const minSpaces = lines.reduce((min, line) => {
|
|
1586
|
+
if (line.trim() === "") {
|
|
1587
|
+
return min;
|
|
1588
|
+
}
|
|
1589
|
+
const leadingSpaces = line.match(/^\s*/)[0].length;
|
|
1590
|
+
return Math.min(min, leadingSpaces);
|
|
1591
|
+
}, Infinity);
|
|
1592
|
+
const trimmedLines = lines.map((line) => line.slice(minSpaces));
|
|
1593
|
+
return trimmedLines.join("\n");
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
const AGENT_GUIDANCE = (() => trimIdent(`
|
|
1597
|
+
You are running inside Happy: the user is reading this session in a web client (often a phone), NOT in the terminal where you run. Two consequences:
|
|
1598
|
+
|
|
1599
|
+
- Terminal output is not a good delivery channel. When the user asks for a piece of text ("copy that", "give me X", "\u590D\u5236\u7ED9\u6211", "\u53D1\u6211"), hand it over with mcp__happy__copy_to_clipboard instead of printing it for them to select by hand.
|
|
1600
|
+
- When you produce or want to show a FILE (a document you wrote, a report, an image, a PDF, a diff), call mcp__happy__open_preview with its path instead of cat-ing it. Their client opens the rendered file.
|
|
1601
|
+
|
|
1602
|
+
Judgement, not reflex: use these when the user's goal is to RECEIVE something. If they are asking a question you can just answer, answer it. Do not preview a file you only read for your own reasoning, and do not preview the same file repeatedly within a turn.
|
|
1603
|
+
|
|
1604
|
+
If you are working on a task the user is tracking, call mcp__happy__report_progress at meaningful milestones (started / blocked / needs review / done) so their board reflects reality. Do not report every tool call.
|
|
1605
|
+
`))();
|
|
1606
|
+
const PREVIEW_TOOL_NAME = "open_preview";
|
|
1607
|
+
const PREVIEW_TOOL_TITLE = "Open File Preview for the User";
|
|
1608
|
+
const PREVIEW_TOOL_DESCRIPTION = 'Open a file in the preview panel of every web client the user currently has open. Use this whenever you produce or want to show the user a file: a document or report you just wrote, a generated image or diagram, a PDF, a data file, or a source file you want them to look at. Trigger phrases include: "write me a doc", "show me that file", "let me see it", "\u5199\u4E2A\u6587\u6863", "\u7ED9\u6211\u770B\u770B\u8FD9\u4E2A\u6587\u4EF6", "\u6253\u5F00\u770B\u4E0B". Pass an absolute path (or one starting with ~). The file is read on this machine and rendered in their browser \u2014 markdown is rendered, images and PDFs are displayed, other text is syntax-highlighted. Prefer this over printing file contents to the terminal, which the user is probably not looking at. NOTE: this only requests that their client open the file; it cannot confirm the user actually looked at it, so do not assume they have seen it.';
|
|
1609
|
+
const REPORT_PROGRESS_TOOL_NAME = "report_progress";
|
|
1610
|
+
const REPORT_PROGRESS_TOOL_TITLE = "Report Progress to the Task Board";
|
|
1611
|
+
const REPORT_PROGRESS_TOOL_DESCRIPTION = `Report what you are doing to the user's task board, so they can see the state of this session at a glance without reading the transcript. Call it at meaningful milestones only: when you start substantive work, when you get blocked and need the user, when something is ready for their review, and when you are done. Do NOT call it after every tool call or every file edit \u2014 it is a status line, not a log. Set attention to "blocked" when you cannot proceed without the user, "review" when you want them to look at something, and "none" for ordinary progress. Keep progress to one short line describing the current state (the user reads it on a card).`;
|
|
1612
|
+
|
|
1613
|
+
export { AUTOMATIONS_UNAVAILABLE_MESSAGE as A, teamRequest as B, createTeamsClient as C, DEFAULT_RECENT_LIMIT as D, trimIdent as E, AGENT_GUIDANCE as F, formatEditConflictNotice as G, createAutomationsClient as H, AutomationsRequestError as I, analyzeLatestTurn as J, readSessionLog as K, TURN_WINDOW as L, MAX_READ_LIMIT as M, userPromptText as N, TeamConnectionPreflightError as O, PREVIEW_TOOL_NAME as P, TEAM_TOOL_NAMES as Q, REPORT_PROGRESS_TOOL_NAME as R, SESSION_PEER_SENT_FROM as S, TurnWaitTimeoutError as T, AUTOMATION_TOOL_NAMES as U, SESSION_PEER_TOOL_NAMES as V, createSessionPeerToolExecutor as W, REPORT_PROGRESS_TOOL_TITLE as X, REPORT_PROGRESS_TOOL_DESCRIPTION as Y, PREVIEW_TOOL_TITLE as a, PREVIEW_TOOL_DESCRIPTION as b, registerAutomationTools as c, registerSessionPeerTools as d, listSessions as e, cliPeerSelf as f, listPeerSessions as g, readSessionTranscript as h, stopSession as i, resolvePermissionRequest as j, archiveSession as k, listAccountSessions as l, PEER_SCOPES as m, deliverToSession as n, sessionWebUrl as o, authenticatedAutomationsClient as p, automationRunIdFromEnv as q, registerTeamsTools as r, sendPeerMessage as s, isAutomationsUnavailable as t, readTeamScope as u, teamScopePath as v, waitForTurnEnd as w, readSessionMetadata as x, waitForSessionKey as y, sendUserMessage as z };
|