very-happy-cli 0.2.151 → 0.2.153

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.
Files changed (65) hide show
  1. package/dist/{AcpBackend-blE9IEod.cjs → AcpBackend-DSt8nTYm.cjs} +2 -2
  2. package/dist/{AcpBackend-BjTA5gUB.mjs → AcpBackend-YDGv4E-g.mjs} +2 -2
  3. package/dist/{AcpSessionManager-D-9mrp40.mjs → AcpSessionManager-Cxf5HQX1.mjs} +1 -1
  4. package/dist/{AcpSessionManager-bF8PYu_B.cjs → AcpSessionManager-uov6I9C8.cjs} +9 -9
  5. package/dist/agentGuidance-BM4kMNyr.cjs +553 -0
  6. package/dist/agentGuidance-C8unGWp7.mjs +529 -0
  7. package/dist/{agentHome-D6MSfwnp.cjs → agentHome-BJ7bde35.cjs} +4 -4
  8. package/dist/{agentHome-CeFDNzvq.mjs → agentHome-D68Xh2ae.mjs} +4 -4
  9. package/dist/auto-C-90ojIH.cjs +472 -0
  10. package/dist/auto-CcXxfqkC.mjs +466 -0
  11. package/dist/codex/happyMcpStdioBridge.cjs +4 -2
  12. package/dist/codex/happyMcpStdioBridge.mjs +4 -2
  13. package/dist/{config-C-A1XF62.mjs → config-CHJ189UJ.mjs} +6 -6
  14. package/dist/{config-Cadw1sAk.cjs → config-D23kF0_u.cjs} +6 -6
  15. package/dist/{index-DYQgcgL2.mjs → index-BXA9fxbK.mjs} +6 -6
  16. package/dist/{index-CIyjJy8D.mjs → index-BacwoXzs.mjs} +748 -55
  17. package/dist/{index-DEp6CmmS.mjs → index-BgYZGODP.mjs} +20 -20
  18. package/dist/{index-vyRqLjDv.cjs → index-D49WvbDT.cjs} +6 -6
  19. package/dist/{index-BKGspSWk.cjs → index-DEOVn46R.cjs} +21 -21
  20. package/dist/{index-CqtfRzug.cjs → index-DHrwHxHf.cjs} +805 -105
  21. package/dist/index.cjs +5 -5
  22. package/dist/index.mjs +5 -5
  23. package/dist/install-BiOXBnnS.cjs +118 -0
  24. package/dist/install-Ca7_Z3bV.mjs +114 -0
  25. package/dist/{installPiTools-C-Lxv4Bt.mjs → installPiTools-Cj7yU9Fc.mjs} +2 -1
  26. package/dist/{installPiTools-BKnXjrVu.cjs → installPiTools-DuZ6jZvX.cjs} +3 -2
  27. package/dist/{installTerminalHooks-Bf_adbl3.cjs → installTerminalHooks-BF0kL0ae.cjs} +8 -8
  28. package/dist/{installTerminalHooks-Ch_yTtEA.mjs → installTerminalHooks-Bpl32K75.mjs} +7 -7
  29. package/dist/lib.cjs +4 -4
  30. package/dist/lib.mjs +4 -4
  31. package/dist/limits-BtAuKRl2.mjs +2080 -0
  32. package/dist/limits-DY_sFA3J.cjs +2175 -0
  33. package/dist/{mcp-zu8n8TkR.mjs → mcp-DQkmk4VV.mjs} +15 -8
  34. package/dist/{mcp-CMxEZ6-0.cjs → mcp-JpqI2POW.cjs} +15 -7
  35. package/dist/piExtension.d.mts +4 -1
  36. package/dist/piExtension.mjs +24 -1
  37. package/dist/{piRuntime-Cu6cXZ6N.mjs → piRuntime-DBpe12NN.mjs} +2 -2
  38. package/dist/{piRuntime-D3ny0mVg.cjs → piRuntime-DRbbeQ72.cjs} +2 -2
  39. package/dist/{piTerminal-M677UP7y.mjs → piTerminal-BoHvPEZ_.mjs} +8 -7
  40. package/dist/{piTerminal-kDSd_r9X.cjs → piTerminal-qdJ9KZVL.cjs} +8 -7
  41. package/dist/{runGemini-DuwdVV1O.cjs → runGemini-CtOEFvhf.cjs} +9 -9
  42. package/dist/{runGemini-DvJwQVGp.mjs → runGemini-YqH7a-7O.mjs} +8 -8
  43. package/dist/{runOpenClaw-BG82bF18.mjs → runOpenClaw-DSSyFQBb.mjs} +7 -7
  44. package/dist/{runOpenClaw-BsvtCE_H.cjs → runOpenClaw-DoqZXBvL.cjs} +7 -7
  45. package/dist/{send-aUkjhey7.cjs → send-9075kHZP.cjs} +6 -6
  46. package/dist/{send-o6WM-1G8.mjs → send-Cs-RwqNf.mjs} +6 -6
  47. package/dist/{sessions-DlU3foY_.mjs → sessions-iBnYzVUK.mjs} +6 -6
  48. package/dist/{sessions-B3vP18kz.cjs → sessions-qULzUzlI.cjs} +6 -6
  49. package/dist/{spawn-DxHIIqhi.mjs → spawn-C6fRkedx.mjs} +7 -32
  50. package/dist/{spawn-DH6_p4-f.cjs → spawn-od9V23cc.cjs} +8 -33
  51. package/dist/{teams-DoAA_CcN.mjs → teams-CkrWQ4uM.mjs} +16 -73
  52. package/dist/{teams-BW8D1n3o.cjs → teams-CrCzU-AV.cjs} +14 -71
  53. package/dist/terminalTitleSuggest-DKgX3osW.mjs +38 -0
  54. package/dist/terminalTitleSuggest-Dji8I0Jy.cjs +45 -0
  55. package/dist/{todo-Bcc2XxGh.cjs → todo-BCT_ZPuV.cjs} +4 -23
  56. package/dist/{todo-BhJbG5eq.mjs → todo-aCZmSt27.mjs} +2 -21
  57. package/dist/{types-BN3eiipi.mjs → types-BvqOVUOW.mjs} +214 -1022
  58. package/dist/{types-CPubg05Z.cjs → types-CUCU7Vw8.cjs} +43 -863
  59. package/package.json +7 -7
  60. package/dist/agentGuidance-BXa9ikrZ.cjs +0 -267
  61. package/dist/agentGuidance-Dvo3cZMW.mjs +0 -251
  62. package/dist/limits-DS-bnYYp.mjs +0 -1165
  63. package/dist/limits-DwcY3kyi.cjs +0 -1236
  64. package/dist/projectPath-CSpqWdxp.mjs +0 -10
  65. package/dist/projectPath-ChLhdOyt.cjs +0 -13
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "very-happy-cli",
3
- "version": "0.2.151",
3
+ "version": "0.2.153",
4
4
  "description": "Remote multi-agent workspace CLI with deep Claude integration, native terminal streaming, and self-hosting.",
5
5
  "author": "Kirill Dubovitskiy",
6
6
  "contributors": [
@@ -117,12 +117,12 @@
117
117
  "zod": "^4.0.0"
118
118
  },
119
119
  "optionalDependencies": {
120
- "very-happy-tools-arm64-darwin": "0.2.151",
121
- "very-happy-tools-x64-darwin": "0.2.151",
122
- "very-happy-tools-arm64-linux": "0.2.151",
123
- "very-happy-tools-x64-linux": "0.2.151",
124
- "very-happy-tools-arm64-win32": "0.2.151",
125
- "very-happy-tools-x64-win32": "0.2.151"
120
+ "very-happy-tools-arm64-darwin": "0.2.153",
121
+ "very-happy-tools-x64-darwin": "0.2.153",
122
+ "very-happy-tools-arm64-linux": "0.2.153",
123
+ "very-happy-tools-x64-linux": "0.2.153",
124
+ "very-happy-tools-arm64-win32": "0.2.153",
125
+ "very-happy-tools-x64-win32": "0.2.153"
126
126
  },
127
127
  "devDependencies": {
128
128
  "@slopus/happy-wire": "workspace:*",
@@ -1,267 +0,0 @@
1
- 'use strict';
2
-
3
- var z = require('zod');
4
- var node_crypto = require('node:crypto');
5
- var persistence = require('./limits-DwcY3kyi.cjs');
6
- var promises = require('node:fs/promises');
7
- var node_fs = require('node:fs');
8
- var path = require('node:path');
9
-
10
- const TeamScopeSchema = z.z.object({
11
- serverUrl: z.z.string(),
12
- scopeToken: z.z.string().min(1),
13
- teamId: z.z.string().min(1),
14
- botId: z.z.string().min(1),
15
- taskId: z.z.string().optional(),
16
- attemptId: z.z.string().optional()
17
- });
18
- function teamScopePath(sessionId) {
19
- const supplied = process.env.VH_TEAM_SCOPE_FILE;
20
- if (supplied) {
21
- if (!path.isAbsolute(supplied)) throw new Error("VH_TEAM_SCOPE_FILE must be absolute");
22
- return supplied;
23
- }
24
- if (!sessionId || !/^[a-zA-Z0-9_-]+$/.test(sessionId)) throw new Error("Teams requires a managed session or VH_TEAM_SCOPE_FILE");
25
- return path.join(persistence.configuration.happyHomeDir, "teams", "scopes", `${sessionId}.json`);
26
- }
27
- async function readTeamScope(path) {
28
- let file;
29
- try {
30
- file = await promises.open(path, node_fs.constants.O_RDONLY | (node_fs.constants.O_NOFOLLOW ?? 0));
31
- } catch (error) {
32
- if (error.code === "ENOENT") return null;
33
- throw new Error("Cannot open team scope");
34
- }
35
- try {
36
- const stat = await file.stat();
37
- if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("Team scope owner mismatch");
38
- if (!stat.isFile() || process.platform !== "win32" && (stat.mode & 63) !== 0) throw new Error("Team scope must be a private 0600 file");
39
- const scope = TeamScopeSchema.parse(JSON.parse(await file.readFile("utf8")));
40
- scope.serverUrl = persistence.normalizeHttpEndpoint(scope.serverUrl, "team scope");
41
- if (scope.serverUrl !== persistence.configuration.serverUrl) throw new Error("Team scope belongs to another server");
42
- return scope;
43
- } catch {
44
- throw new Error("Invalid or unsafe team scope file");
45
- } finally {
46
- await file.close();
47
- }
48
- }
49
- async function writeTeamScope(path$1, scope) {
50
- await promises.mkdir(path.dirname(path$1), { recursive: true, mode: 448 });
51
- const temporary = `${path$1}.${node_crypto.randomUUID()}.new`;
52
- const file = await promises.open(temporary, "wx", 384);
53
- try {
54
- await file.writeFile(JSON.stringify(TeamScopeSchema.parse(scope)));
55
- await file.sync();
56
- } finally {
57
- await file.close();
58
- }
59
- try {
60
- await promises.rename(temporary, path$1);
61
- } finally {
62
- await promises.unlink(temporary).catch(() => {
63
- });
64
- }
65
- }
66
-
67
- async function teamRequest(path, method, token, scoped, body) {
68
- const response = await fetch(`${persistence.configuration.serverUrl}${path}`, {
69
- method,
70
- redirect: "error",
71
- headers: { "content-type": "application/json", ...scoped ? { "x-happy-team-token": token } : { authorization: `Bearer ${token}` } },
72
- body: body === void 0 ? void 0 : JSON.stringify(body),
73
- signal: AbortSignal.timeout(25e3)
74
- }).catch(() => {
75
- throw new Error("Teams connection failed; outcome may be unknown. Reuse the request ID when retrying.");
76
- });
77
- if (!response.ok) throw new Error(`Teams request failed (HTTP ${response.status})`);
78
- try {
79
- return await response.json();
80
- } catch {
81
- throw new Error("Teams returned an invalid response");
82
- }
83
- }
84
- class TeamConnectionPreflightError extends Error {
85
- }
86
- const initializationLocks = /* @__PURE__ */ new Map();
87
- async function serializeInitialization(path, work) {
88
- const previous = initializationLocks.get(path) ?? Promise.resolve();
89
- const next = previous.catch(() => {
90
- }).then(work);
91
- initializationLocks.set(path, next);
92
- try {
93
- return await next;
94
- } finally {
95
- if (initializationLocks.get(path) === next) initializationLocks.delete(path);
96
- }
97
- }
98
- function createTeamsClient(sessionId) {
99
- const scopePath = () => teamScopePath(sessionId ?? process.env.HAPPY_SESSION_ID);
100
- return {
101
- async initialize(input, options) {
102
- const path = scopePath();
103
- return serializeInitialization(path, async () => {
104
- const priorScope = await readTeamScope(path);
105
- if (priorScope && !options?.resumeAdoption) throw new Error("This session already has a team scope; use scoped team tools");
106
- if (process.env.VH_TEAM_SCOPE_FILE) throw new Error("Assigned team scope is missing or already managed; ask the owner to restore it");
107
- const sid = sessionId ?? process.env.HAPPY_SESSION_ID;
108
- if (!sid) throw new Error("A managed session identity is required");
109
- const machineId = (await persistence.readSettings()).machineId;
110
- if (!machineId) throw new TeamConnectionPreflightError("Connect this machine to Very Happy before joining a team");
111
- if (input.machineId && input.machineId !== machineId) throw new TeamConnectionPreflightError("Teams must use this session\u2019s local machine");
112
- const persisted = persistence.readPersistedSessions()[sid];
113
- if (!persisted || persisted.metadata.machineId !== machineId) throw new TeamConnectionPreflightError("Team identity must be a persisted session on this machine");
114
- const credentials = await persistence.readCredentialsForConfiguredRelay();
115
- if (!credentials) throw new TeamConnectionPreflightError("Sign in to Very Happy before creating or joining a team");
116
- if (priorScope && !options?.expectedTeamId) throw new Error("This session already belongs to another team scope");
117
- let teamId = input.teamId ?? options?.expectedTeamId;
118
- if (!teamId) {
119
- const created = await teamRequest("/v1/teams", "POST", credentials.token, false, { name: input.name, machineId, requestId: input.requestId });
120
- teamId = created.team.id;
121
- } else {
122
- const existing = await teamRequest(`/v1/teams/${encodeURIComponent(teamId)}`, "GET", credentials.token, false);
123
- if (existing.team?.machineId !== machineId) throw new TeamConnectionPreflightError("Team belongs to another machine");
124
- }
125
- if (options?.onTeamResolved) await options.onTeamResolved(teamId);
126
- if (priorScope) {
127
- if (priorScope.teamId !== teamId || priorScope.taskId) throw new Error("This session already belongs to another team scope");
128
- const inspected = await teamRequest(`/v1/teams/${encodeURIComponent(teamId)}/agent`, "GET", priorScope.scopeToken, true);
129
- const bot = inspected.team?.bots?.find((candidate) => candidate.id === priorScope.botId);
130
- if (!bot?.root || bot.managed || bot.sessionId !== sid) throw new Error("Existing scope is not this session\u2019s root identity");
131
- return { team: inspected.team, botId: priorScope.botId };
132
- }
133
- const result = await teamRequest(
134
- `/v1/teams/${encodeURIComponent(teamId)}/actions`,
135
- "POST",
136
- credentials.token,
137
- false,
138
- { requestId: input.requestId, action: { type: "join", name: input.name, sessionId: sid, ...input.botId ? { botId: input.botId } : {} } }
139
- );
140
- if (!result.credential?.token || !result.credential?.botId) throw new Error("Team join did not issue a credential");
141
- await writeTeamScope(path, { serverUrl: persistence.configuration.serverUrl, teamId, botId: result.credential.botId, scopeToken: result.credential.token });
142
- return { team: result.team, botId: result.credential.botId };
143
- });
144
- },
145
- async inspect() {
146
- const scope = await readTeamScope(scopePath());
147
- if (!scope) throw new Error("Join or create a team first");
148
- const { credential: _credential, ...safe } = await teamRequest(`/v1/teams/${encodeURIComponent(scope.teamId)}/agent`, "GET", scope.scopeToken, true);
149
- return safe;
150
- },
151
- async action(action, requestId = node_crypto.randomUUID()) {
152
- const scope = await readTeamScope(scopePath());
153
- if (!scope) throw new Error("Join or create a team first");
154
- const result = await teamRequest(`/v1/teams/${encodeURIComponent(scope.teamId)}/agent`, "POST", scope.scopeToken, true, { requestId, action });
155
- const { credential: _credential, ...safe } = result;
156
- return safe;
157
- }
158
- };
159
- }
160
-
161
- 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"];
162
- const id = z.z.string().min(1).max(128);
163
- const text = z.z.string().min(1).max(32e3);
164
- const requestId = id.describe("Unique operation ID. Reuse the same ID and arguments after an uncertain response.");
165
- function registerTeamsTools(server, sessionId, client = createTeamsClient(sessionId)) {
166
- const register = (name, description, inputSchema, execute) => {
167
- 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) => {
168
- try {
169
- return { content: [{ type: "text", text: JSON.stringify(await execute(args)) }], isError: false };
170
- } catch (error) {
171
- return { content: [{ type: "text", text: error instanceof Error ? error.message : "Teams operation failed" }], isError: true };
172
- }
173
- });
174
- };
175
- register(
176
- "team_create",
177
- "Create an official Very Happy team and join this session as its root bot. Does not grant access outside this account.",
178
- { name: id, machineId: id.optional(), requestId },
179
- (args) => client.initialize(args)
180
- );
181
- register(
182
- "team_join",
183
- "Join an existing team as a root bot using this session owner\u2019s account. Scoped workers cannot elevate their role.",
184
- { teamId: id, name: id, botId: id.optional().describe("Existing root bot to reconnect; preserves its identity"), requestId },
185
- (args) => client.initialize(args)
186
- );
187
- register("team_inspect", "Read your visible team tasks, attempts and messages. Inspect before decisions; submission is not acceptance.", {}, () => client.inspect());
188
- const action = (name, description, fields) => register(
189
- `team_${name}`,
190
- description,
191
- { requestId, ...fields },
192
- ({ requestId: key, ...args }) => client.action({ type: name, ...args, ...name === "delegate" && args.directory === void 0 ? { directory: process.cwd() } : {} }, key)
193
- );
194
- action("delegate", "Delegate a goal with acceptance criteria. Use parentTaskId for subdelegation. Existing assigneeBotId or a managed worker may execute it.", {
195
- goal: text,
196
- acceptance: z.z.array(text).min(1).max(32),
197
- parentTaskId: id.optional(),
198
- assigneeBotId: id.optional(),
199
- botName: id.optional(),
200
- directory: z.z.string().min(1).optional(),
201
- assistant: z.z.enum(["claude", "codex", "pi-acp"]).optional(),
202
- model: z.z.string().trim().min(1).max(256).optional()
203
- });
204
- action("message", "Send a persistent task-related message. Delivery does not mean the model has read or acted on it.", { taskId: id, body: text, recipientBotId: id.optional() });
205
- action("submit", "Submit evidence for your current attempt and goal version. The owner still has to accept it.", { taskId: id, attemptId: id, goalVersion: z.z.number().int().positive(), result: text });
206
- const current = { attemptId: id, goalVersion: z.z.number().int().positive() };
207
- action("accept", "Accept a task you own after checking its evidence. Resource cleanup is tracked separately.", { taskId: id, ...current });
208
- action("return", "Return your task for further work with a concrete reason.", { taskId: id, reason: text, ...current });
209
- action("cancel", "Cancel an owned task and its dependent work. Cleanup may remain pending.", { taskId: id, reason: text, ...current });
210
- action("handoff", "Move an owned task to another bot; prior execution authority is superseded.", { taskId: id, assigneeBotId: id, ...current });
211
- 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, botId: id, body: text, runAt: z.z.number().int().nonnegative(), intervalMs: z.z.number().int().min(6e4).optional() }, ({ requestId: key, ...args }) => client.action({ type: "schedule-create", ...args }, key));
212
- for (const operation of ["pause", "resume", "cancel"]) {
213
- 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, version: z.z.number().int().positive() }, ({ requestId: key, ...args }) => client.action({ type: `schedule-${operation}`, ...args }, key));
214
- }
215
- }
216
-
217
- function trimIdent(text) {
218
- const lines = text.split("\n");
219
- while (lines.length > 0 && lines[0].trim() === "") {
220
- lines.shift();
221
- }
222
- while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
223
- lines.pop();
224
- }
225
- const minSpaces = lines.reduce((min, line) => {
226
- if (line.trim() === "") {
227
- return min;
228
- }
229
- const leadingSpaces = line.match(/^\s*/)[0].length;
230
- return Math.min(min, leadingSpaces);
231
- }, Infinity);
232
- const trimmedLines = lines.map((line) => line.slice(minSpaces));
233
- return trimmedLines.join("\n");
234
- }
235
-
236
- const AGENT_GUIDANCE = (() => trimIdent(`
237
- 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:
238
-
239
- - 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.
240
- - 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.
241
-
242
- 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.
243
-
244
- 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.
245
- `))();
246
- const PREVIEW_TOOL_NAME = "open_preview";
247
- const PREVIEW_TOOL_TITLE = "Open File Preview for the User";
248
- 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.';
249
- const REPORT_PROGRESS_TOOL_NAME = "report_progress";
250
- const REPORT_PROGRESS_TOOL_TITLE = "Report Progress to the Task Board";
251
- 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).`;
252
-
253
- exports.AGENT_GUIDANCE = AGENT_GUIDANCE;
254
- exports.PREVIEW_TOOL_DESCRIPTION = PREVIEW_TOOL_DESCRIPTION;
255
- exports.PREVIEW_TOOL_NAME = PREVIEW_TOOL_NAME;
256
- exports.PREVIEW_TOOL_TITLE = PREVIEW_TOOL_TITLE;
257
- exports.REPORT_PROGRESS_TOOL_DESCRIPTION = REPORT_PROGRESS_TOOL_DESCRIPTION;
258
- exports.REPORT_PROGRESS_TOOL_NAME = REPORT_PROGRESS_TOOL_NAME;
259
- exports.REPORT_PROGRESS_TOOL_TITLE = REPORT_PROGRESS_TOOL_TITLE;
260
- exports.TEAM_TOOL_NAMES = TEAM_TOOL_NAMES;
261
- exports.TeamConnectionPreflightError = TeamConnectionPreflightError;
262
- exports.createTeamsClient = createTeamsClient;
263
- exports.readTeamScope = readTeamScope;
264
- exports.registerTeamsTools = registerTeamsTools;
265
- exports.teamRequest = teamRequest;
266
- exports.teamScopePath = teamScopePath;
267
- exports.trimIdent = trimIdent;
@@ -1,251 +0,0 @@
1
- import { z } from 'zod';
2
- import { randomUUID } from 'node:crypto';
3
- import { n as normalizeHttpEndpoint, c as configuration, r as readSettings, d as readPersistedSessions, e as readCredentialsForConfiguredRelay } from './limits-DS-bnYYp.mjs';
4
- import { open, mkdir, rename, unlink } from 'node:fs/promises';
5
- import { constants } from 'node:fs';
6
- import { isAbsolute, join, dirname } from 'node:path';
7
-
8
- const TeamScopeSchema = z.object({
9
- serverUrl: z.string(),
10
- scopeToken: z.string().min(1),
11
- teamId: z.string().min(1),
12
- botId: z.string().min(1),
13
- taskId: z.string().optional(),
14
- attemptId: z.string().optional()
15
- });
16
- function teamScopePath(sessionId) {
17
- const supplied = process.env.VH_TEAM_SCOPE_FILE;
18
- if (supplied) {
19
- if (!isAbsolute(supplied)) throw new Error("VH_TEAM_SCOPE_FILE must be absolute");
20
- return supplied;
21
- }
22
- if (!sessionId || !/^[a-zA-Z0-9_-]+$/.test(sessionId)) throw new Error("Teams requires a managed session or VH_TEAM_SCOPE_FILE");
23
- return join(configuration.happyHomeDir, "teams", "scopes", `${sessionId}.json`);
24
- }
25
- async function readTeamScope(path) {
26
- let file;
27
- try {
28
- file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
29
- } catch (error) {
30
- if (error.code === "ENOENT") return null;
31
- throw new Error("Cannot open team scope");
32
- }
33
- try {
34
- const stat = await file.stat();
35
- if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("Team scope owner mismatch");
36
- if (!stat.isFile() || process.platform !== "win32" && (stat.mode & 63) !== 0) throw new Error("Team scope must be a private 0600 file");
37
- const scope = TeamScopeSchema.parse(JSON.parse(await file.readFile("utf8")));
38
- scope.serverUrl = normalizeHttpEndpoint(scope.serverUrl, "team scope");
39
- if (scope.serverUrl !== configuration.serverUrl) throw new Error("Team scope belongs to another server");
40
- return scope;
41
- } catch {
42
- throw new Error("Invalid or unsafe team scope file");
43
- } finally {
44
- await file.close();
45
- }
46
- }
47
- async function writeTeamScope(path, scope) {
48
- await mkdir(dirname(path), { recursive: true, mode: 448 });
49
- const temporary = `${path}.${randomUUID()}.new`;
50
- const file = await open(temporary, "wx", 384);
51
- try {
52
- await file.writeFile(JSON.stringify(TeamScopeSchema.parse(scope)));
53
- await file.sync();
54
- } finally {
55
- await file.close();
56
- }
57
- try {
58
- await rename(temporary, path);
59
- } finally {
60
- await unlink(temporary).catch(() => {
61
- });
62
- }
63
- }
64
-
65
- async function teamRequest(path, method, token, scoped, body) {
66
- const response = await fetch(`${configuration.serverUrl}${path}`, {
67
- method,
68
- redirect: "error",
69
- headers: { "content-type": "application/json", ...scoped ? { "x-happy-team-token": token } : { authorization: `Bearer ${token}` } },
70
- body: body === void 0 ? void 0 : JSON.stringify(body),
71
- signal: AbortSignal.timeout(25e3)
72
- }).catch(() => {
73
- throw new Error("Teams connection failed; outcome may be unknown. Reuse the request ID when retrying.");
74
- });
75
- if (!response.ok) throw new Error(`Teams request failed (HTTP ${response.status})`);
76
- try {
77
- return await response.json();
78
- } catch {
79
- throw new Error("Teams returned an invalid response");
80
- }
81
- }
82
- class TeamConnectionPreflightError extends Error {
83
- }
84
- const initializationLocks = /* @__PURE__ */ new Map();
85
- async function serializeInitialization(path, work) {
86
- const previous = initializationLocks.get(path) ?? Promise.resolve();
87
- const next = previous.catch(() => {
88
- }).then(work);
89
- initializationLocks.set(path, next);
90
- try {
91
- return await next;
92
- } finally {
93
- if (initializationLocks.get(path) === next) initializationLocks.delete(path);
94
- }
95
- }
96
- function createTeamsClient(sessionId) {
97
- const scopePath = () => teamScopePath(sessionId ?? process.env.HAPPY_SESSION_ID);
98
- return {
99
- async initialize(input, options) {
100
- const path = scopePath();
101
- return serializeInitialization(path, async () => {
102
- const priorScope = await readTeamScope(path);
103
- if (priorScope && !options?.resumeAdoption) throw new Error("This session already has a team scope; use scoped team tools");
104
- if (process.env.VH_TEAM_SCOPE_FILE) throw new Error("Assigned team scope is missing or already managed; ask the owner to restore it");
105
- const sid = sessionId ?? process.env.HAPPY_SESSION_ID;
106
- if (!sid) throw new Error("A managed session identity is required");
107
- const machineId = (await readSettings()).machineId;
108
- if (!machineId) throw new TeamConnectionPreflightError("Connect this machine to Very Happy before joining a team");
109
- if (input.machineId && input.machineId !== machineId) throw new TeamConnectionPreflightError("Teams must use this session\u2019s local machine");
110
- const persisted = readPersistedSessions()[sid];
111
- if (!persisted || persisted.metadata.machineId !== machineId) throw new TeamConnectionPreflightError("Team identity must be a persisted session on this machine");
112
- const credentials = await readCredentialsForConfiguredRelay();
113
- if (!credentials) throw new TeamConnectionPreflightError("Sign in to Very Happy before creating or joining a team");
114
- if (priorScope && !options?.expectedTeamId) throw new Error("This session already belongs to another team scope");
115
- let teamId = input.teamId ?? options?.expectedTeamId;
116
- if (!teamId) {
117
- const created = await teamRequest("/v1/teams", "POST", credentials.token, false, { name: input.name, machineId, requestId: input.requestId });
118
- teamId = created.team.id;
119
- } else {
120
- const existing = await teamRequest(`/v1/teams/${encodeURIComponent(teamId)}`, "GET", credentials.token, false);
121
- if (existing.team?.machineId !== machineId) throw new TeamConnectionPreflightError("Team belongs to another machine");
122
- }
123
- if (options?.onTeamResolved) await options.onTeamResolved(teamId);
124
- if (priorScope) {
125
- if (priorScope.teamId !== teamId || priorScope.taskId) throw new Error("This session already belongs to another team scope");
126
- const inspected = await teamRequest(`/v1/teams/${encodeURIComponent(teamId)}/agent`, "GET", priorScope.scopeToken, true);
127
- const bot = inspected.team?.bots?.find((candidate) => candidate.id === priorScope.botId);
128
- if (!bot?.root || bot.managed || bot.sessionId !== sid) throw new Error("Existing scope is not this session\u2019s root identity");
129
- return { team: inspected.team, botId: priorScope.botId };
130
- }
131
- const result = await teamRequest(
132
- `/v1/teams/${encodeURIComponent(teamId)}/actions`,
133
- "POST",
134
- credentials.token,
135
- false,
136
- { requestId: input.requestId, action: { type: "join", name: input.name, sessionId: sid, ...input.botId ? { botId: input.botId } : {} } }
137
- );
138
- if (!result.credential?.token || !result.credential?.botId) throw new Error("Team join did not issue a credential");
139
- await writeTeamScope(path, { serverUrl: configuration.serverUrl, teamId, botId: result.credential.botId, scopeToken: result.credential.token });
140
- return { team: result.team, botId: result.credential.botId };
141
- });
142
- },
143
- async inspect() {
144
- const scope = await readTeamScope(scopePath());
145
- if (!scope) throw new Error("Join or create a team first");
146
- const { credential: _credential, ...safe } = await teamRequest(`/v1/teams/${encodeURIComponent(scope.teamId)}/agent`, "GET", scope.scopeToken, true);
147
- return safe;
148
- },
149
- async action(action, requestId = randomUUID()) {
150
- const scope = await readTeamScope(scopePath());
151
- if (!scope) throw new Error("Join or create a team first");
152
- const result = await teamRequest(`/v1/teams/${encodeURIComponent(scope.teamId)}/agent`, "POST", scope.scopeToken, true, { requestId, action });
153
- const { credential: _credential, ...safe } = result;
154
- return safe;
155
- }
156
- };
157
- }
158
-
159
- 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"];
160
- const id = z.string().min(1).max(128);
161
- const text = z.string().min(1).max(32e3);
162
- const requestId = id.describe("Unique operation ID. Reuse the same ID and arguments after an uncertain response.");
163
- function registerTeamsTools(server, sessionId, client = createTeamsClient(sessionId)) {
164
- const register = (name, description, inputSchema, execute) => {
165
- 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) => {
166
- try {
167
- return { content: [{ type: "text", text: JSON.stringify(await execute(args)) }], isError: false };
168
- } catch (error) {
169
- return { content: [{ type: "text", text: error instanceof Error ? error.message : "Teams operation failed" }], isError: true };
170
- }
171
- });
172
- };
173
- register(
174
- "team_create",
175
- "Create an official Very Happy team and join this session as its root bot. Does not grant access outside this account.",
176
- { name: id, machineId: id.optional(), requestId },
177
- (args) => client.initialize(args)
178
- );
179
- register(
180
- "team_join",
181
- "Join an existing team as a root bot using this session owner\u2019s account. Scoped workers cannot elevate their role.",
182
- { teamId: id, name: id, botId: id.optional().describe("Existing root bot to reconnect; preserves its identity"), requestId },
183
- (args) => client.initialize(args)
184
- );
185
- register("team_inspect", "Read your visible team tasks, attempts and messages. Inspect before decisions; submission is not acceptance.", {}, () => client.inspect());
186
- const action = (name, description, fields) => register(
187
- `team_${name}`,
188
- description,
189
- { requestId, ...fields },
190
- ({ requestId: key, ...args }) => client.action({ type: name, ...args, ...name === "delegate" && args.directory === void 0 ? { directory: process.cwd() } : {} }, key)
191
- );
192
- action("delegate", "Delegate a goal with acceptance criteria. Use parentTaskId for subdelegation. Existing assigneeBotId or a managed worker may execute it.", {
193
- goal: text,
194
- acceptance: z.array(text).min(1).max(32),
195
- parentTaskId: id.optional(),
196
- assigneeBotId: id.optional(),
197
- botName: id.optional(),
198
- directory: z.string().min(1).optional(),
199
- assistant: z.enum(["claude", "codex", "pi-acp"]).optional(),
200
- model: z.string().trim().min(1).max(256).optional()
201
- });
202
- action("message", "Send a persistent task-related message. Delivery does not mean the model has read or acted on it.", { taskId: id, body: text, recipientBotId: id.optional() });
203
- action("submit", "Submit evidence for your current attempt and goal version. The owner still has to accept it.", { taskId: id, attemptId: id, goalVersion: z.number().int().positive(), result: text });
204
- const current = { attemptId: id, goalVersion: z.number().int().positive() };
205
- action("accept", "Accept a task you own after checking its evidence. Resource cleanup is tracked separately.", { taskId: id, ...current });
206
- action("return", "Return your task for further work with a concrete reason.", { taskId: id, reason: text, ...current });
207
- action("cancel", "Cancel an owned task and its dependent work. Cleanup may remain pending.", { taskId: id, reason: text, ...current });
208
- action("handoff", "Move an owned task to another bot; prior execution authority is superseded.", { taskId: id, assigneeBotId: id, ...current });
209
- 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, botId: id, body: text, runAt: z.number().int().nonnegative(), intervalMs: z.number().int().min(6e4).optional() }, ({ requestId: key, ...args }) => client.action({ type: "schedule-create", ...args }, key));
210
- for (const operation of ["pause", "resume", "cancel"]) {
211
- 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, version: z.number().int().positive() }, ({ requestId: key, ...args }) => client.action({ type: `schedule-${operation}`, ...args }, key));
212
- }
213
- }
214
-
215
- function trimIdent(text) {
216
- const lines = text.split("\n");
217
- while (lines.length > 0 && lines[0].trim() === "") {
218
- lines.shift();
219
- }
220
- while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
221
- lines.pop();
222
- }
223
- const minSpaces = lines.reduce((min, line) => {
224
- if (line.trim() === "") {
225
- return min;
226
- }
227
- const leadingSpaces = line.match(/^\s*/)[0].length;
228
- return Math.min(min, leadingSpaces);
229
- }, Infinity);
230
- const trimmedLines = lines.map((line) => line.slice(minSpaces));
231
- return trimmedLines.join("\n");
232
- }
233
-
234
- const AGENT_GUIDANCE = (() => trimIdent(`
235
- 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:
236
-
237
- - 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.
238
- - 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.
239
-
240
- 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.
241
-
242
- 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.
243
- `))();
244
- const PREVIEW_TOOL_NAME = "open_preview";
245
- const PREVIEW_TOOL_TITLE = "Open File Preview for the User";
246
- 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.';
247
- const REPORT_PROGRESS_TOOL_NAME = "report_progress";
248
- const REPORT_PROGRESS_TOOL_TITLE = "Report Progress to the Task Board";
249
- 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).`;
250
-
251
- export { AGENT_GUIDANCE as A, PREVIEW_TOOL_NAME as P, REPORT_PROGRESS_TOOL_NAME as R, TeamConnectionPreflightError as T, PREVIEW_TOOL_TITLE as a, PREVIEW_TOOL_DESCRIPTION as b, readTeamScope as c, teamRequest as d, createTeamsClient as e, trimIdent as f, TEAM_TOOL_NAMES as g, REPORT_PROGRESS_TOOL_TITLE as h, REPORT_PROGRESS_TOOL_DESCRIPTION as i, registerTeamsTools as r, teamScopePath as t };