@zonease/happy 0.6.40 → 0.6.42

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 (87) hide show
  1. package/dist/{api-C7FyJfZ1.cjs → api-CIE4_cWd.cjs} +4 -4
  2. package/dist/{api-D6WL40-U.mjs → api-Ew6xr81i.mjs} +4 -4
  3. package/dist/{auth-DO9GexAR.mjs → auth-BzYevJo2.mjs} +4 -4
  4. package/dist/{auth-DCsIoZLT.cjs → auth-Dor79zTL.cjs} +4 -4
  5. package/dist/{auth-C7ZScWEw.cjs → auth-G9fZpVJ2.cjs} +2 -2
  6. package/dist/{auth-DxJ3VvrX.mjs → auth-Q2STUNI-.mjs} +2 -2
  7. package/dist/{browser-AoVGRX7y.mjs → browser-BI7s-V8E.mjs} +1 -1
  8. package/dist/{browser-DzgO4oaD.cjs → browser-qDIIAL7S.cjs} +1 -1
  9. package/dist/{claudeLocal-CWNGpJ0-.mjs → claudeLocal-Db2tDC4X.mjs} +1 -1
  10. package/dist/{claudeLocal-C6BdzhDx.cjs → claudeLocal-f4uBLJaM.cjs} +1 -1
  11. package/dist/{config-DZk-mJ0K.mjs → config-CHjDs8AS.mjs} +1 -1
  12. package/dist/{config-CclB3QW9.cjs → config-CSBlEik9.cjs} +1 -1
  13. package/dist/{connect-k9CqDJ-T.cjs → connect-CJoTliii.cjs} +5 -5
  14. package/dist/{connect-BXLUKJ5P.mjs → connect-O_nA5BOC.mjs} +5 -5
  15. package/dist/{controlClient-B23M-WPp.cjs → controlClient-CEz_p1zc.cjs} +1 -1
  16. package/dist/{controlClient-DB5tDU7V.mjs → controlClient-DoS9JqQC.mjs} +1 -1
  17. package/dist/cursorApprovalHook-B0v1kGa7.mjs +95 -0
  18. package/dist/cursorApprovalHook-DRAHfTXU.cjs +97 -0
  19. package/dist/cursorApprovalServer-DzY8yJlI.cjs +167 -0
  20. package/dist/cursorApprovalServer-JjPkdjGR.mjs +164 -0
  21. package/dist/{deviceKeys-BTdo34Uz.mjs → deviceKeys-B4aqjnE6.mjs} +2 -2
  22. package/dist/{deviceKeys-C540DcXl.cjs → deviceKeys-DyUn0bEx.cjs} +2 -2
  23. package/dist/{doctor-BQGLhrcI.cjs → doctor-BJSuVRUZ.cjs} +3 -3
  24. package/dist/{doctor-CU4JLGQ1.mjs → doctor-DRnft_5-.mjs} +3 -3
  25. package/dist/{downloadImage-DZXI3mXL.mjs → downloadImage-BpVF7A79.mjs} +7 -40
  26. package/dist/{downloadImage-cQ1Z7hkC.cjs → downloadImage-Cijmufpr.cjs} +5 -39
  27. package/dist/{enroll-Bo-CNio1.cjs → enroll-C2gunHdt.cjs} +3 -3
  28. package/dist/{enroll-B55BQR56.mjs → enroll-CysDL6ee.mjs} +3 -3
  29. package/dist/{evidence-DTYRAaOZ.mjs → evidence-DPutCuUr.mjs} +1 -1
  30. package/dist/{evidence-DQp8QWcv.cjs → evidence-DsQ-h-_W.cjs} +1 -1
  31. package/dist/{formatImageMessage-DbKSSjMx.mjs → formatImageMessage-6aV9YFWr.mjs} +1 -1
  32. package/dist/{formatImageMessage-CixDYY6G.cjs → formatImageMessage-BPK_Ivfe.cjs} +1 -1
  33. package/dist/gitWorktree-C6jLoaMw.cjs +39 -0
  34. package/dist/gitWorktree-CzJDU2BV.mjs +37 -0
  35. package/dist/{index-CDTNgfUf.cjs → index-BeKrqPYR.cjs} +25 -1
  36. package/dist/{index-CPKdvi7J.mjs → index-DTV7drqs.mjs} +25 -1
  37. package/dist/index.cjs +106 -41
  38. package/dist/index.mjs +106 -41
  39. package/dist/{install-B1e6rdy7.mjs → install-BsTA2tZn.mjs} +2 -2
  40. package/dist/{install-CgUPGIoF.mjs → install-DBg0xQ3g.mjs} +1 -1
  41. package/dist/{install-D7Ir7ciZ.cjs → install-DlOppA-e.cjs} +2 -2
  42. package/dist/{install-DSDufaPd.cjs → install-Tyhs6rUp.cjs} +1 -1
  43. package/dist/lib.cjs +4 -4
  44. package/dist/lib.d.cts +3 -2
  45. package/dist/lib.d.mts +3 -2
  46. package/dist/lib.mjs +4 -4
  47. package/dist/{loadableToolOutput-Bfei9wPq.mjs → loadableToolOutput-2dMPAp4N.mjs} +3 -456
  48. package/dist/{loadableToolOutput-CbLGtvST.cjs → loadableToolOutput-DPGTtKJM.cjs} +2 -458
  49. package/dist/{persistence-CBTtC_dm.cjs → persistence-BcQmjobZ.cjs} +7 -4
  50. package/dist/{persistence-DKfF81pd.mjs → persistence-D9tMm6bj.mjs} +8 -5
  51. package/dist/push-Cnm6JQMD.cjs +80 -0
  52. package/dist/push-Dxsugkes.mjs +78 -0
  53. package/dist/{run-BVZsMNwN.mjs → run-BEflQaQ2.mjs} +12 -9
  54. package/dist/{run-CURx7LhK.cjs → run-CiPWWhXt.cjs} +12 -9
  55. package/dist/{runClaude-CL3Kt5ex.cjs → runClaude-BVXsyCHb.cjs} +19 -18
  56. package/dist/{runClaude-6Gi0sYQy.mjs → runClaude-sPkSqHWY.mjs} +16 -15
  57. package/dist/{runCodex-YKyVBkJ3.cjs → runCodex-BAwhdmSA.cjs} +19 -17
  58. package/dist/{runCodex-ClwEgJ7M.mjs → runCodex-C4rHkIyw.mjs} +16 -14
  59. package/dist/runCursor-CD5wC3gA.cjs +578 -0
  60. package/dist/runCursor-DiHLWMs8.mjs +576 -0
  61. package/dist/{runGemini-BPWxVr60.mjs → runGemini-B-93gOqB.mjs} +18 -16
  62. package/dist/{runGemini-Xz2W1spn.cjs → runGemini-Cto-adir.cjs} +21 -19
  63. package/dist/{runOneShot-DjZyCvDI.cjs → runOneShot-BfIzE9W4.cjs} +3 -3
  64. package/dist/{runOneShot-CdCWiiLr.mjs → runOneShot-DGjlYVhR.mjs} +3 -3
  65. package/dist/{serve-B8vaWQA0.cjs → serve-CqL6NWDr.cjs} +7 -7
  66. package/dist/{serve-B48JttQ3.mjs → serve-ttlqF5jn.mjs} +7 -7
  67. package/dist/{session-BZO25zxp.cjs → session-BZhGpQUJ.cjs} +5 -5
  68. package/dist/{session-BXboDn2V.mjs → session-Co0REU9e.mjs} +5 -5
  69. package/dist/{sessionKeyCache-CDmexJ9p.cjs → sessionKeyCache-BwFUGgMs.cjs} +1 -1
  70. package/dist/{sessionKeyCache-B6cGadYL.mjs → sessionKeyCache-pXTjpETo.mjs} +1 -1
  71. package/dist/{sessionList-CgAYZpNj.mjs → sessionList-DaufR-sA.mjs} +2 -2
  72. package/dist/{sessionList-lQ-nqEhc.cjs → sessionList-fG5uAPzU.cjs} +2 -2
  73. package/dist/{sessionSummary-CcORiQSq.cjs → sessionSummary-CjZPt6nr.cjs} +3 -3
  74. package/dist/{sessionSummary-DCWQoaDP.mjs → sessionSummary-Dv6dPABg.mjs} +3 -3
  75. package/dist/setupOfflineReconnection-B6coH9QN.cjs +461 -0
  76. package/dist/setupOfflineReconnection-DW5il97B.mjs +457 -0
  77. package/dist/{spawnHappyCLI-KiazE3kL.cjs → spawnHappyCLI-Cfu7C1uM.cjs} +1 -1
  78. package/dist/{spawnHappyCLI-yBIP_Oqi.mjs → spawnHappyCLI-DhUeycct.mjs} +1 -1
  79. package/dist/{ssh-q5uZhqBf.mjs → ssh-8tPIKk-i.mjs} +9 -6
  80. package/dist/{ssh-yMllSHu5.cjs → ssh-C4YTSHXL.cjs} +9 -5
  81. package/dist/{task-wNX1N2i4.mjs → task-CH-oidFy.mjs} +6 -6
  82. package/dist/{task-_nr7J19j.cjs → task-DFW-PecP.cjs} +6 -6
  83. package/dist/{uninstall-Dxf6_4mQ.mjs → uninstall-CeioRZNI.mjs} +2 -2
  84. package/dist/{uninstall-Buaz7d-X.cjs → uninstall-yTSL3X6Y.cjs} +2 -2
  85. package/dist/{update-CGlIfa8e.cjs → update-Bju28vNP.cjs} +3 -3
  86. package/dist/{update-CnnoX2cV.mjs → update-Derd2hoX.mjs} +3 -3
  87. package/package.json +1 -1
@@ -0,0 +1,461 @@
1
+ 'use strict';
2
+
3
+ var logger = require('./persistence-BcQmjobZ.cjs');
4
+ var fs = require('node:fs');
5
+ var os = require('node:os');
6
+ var path = require('node:path');
7
+ var projectPath = require('./projectPath-ChLhdOyt.cjs');
8
+ var api = require('./api-CIE4_cWd.cjs');
9
+ var gitWorktree = require('./gitWorktree-C6jLoaMw.cjs');
10
+
11
+ class BasePermissionHandler {
12
+ pendingRequests = /* @__PURE__ */ new Map();
13
+ session;
14
+ pushClient;
15
+ isResetting = false;
16
+ isUserInteractionTool(toolName) {
17
+ return ["AskUserQuestion", "ExitPlanMode", "exit_plan_mode"].includes(toolName);
18
+ }
19
+ constructor(session, pushClient) {
20
+ this.session = session;
21
+ this.pushClient = pushClient;
22
+ this.setupRpcHandler();
23
+ }
24
+ /**
25
+ * Update the session reference (used after offline reconnection swaps sessions).
26
+ * This is critical for avoiding stale session references after onSessionSwap.
27
+ */
28
+ updateSession(newSession) {
29
+ logger.logger.debug(`${this.getLogPrefix()} Session reference updated`);
30
+ this.session = newSession;
31
+ this.setupRpcHandler();
32
+ }
33
+ /**
34
+ * Setup RPC handler for permission responses.
35
+ */
36
+ setupRpcHandler() {
37
+ this.session.rpcHandlerManager.registerHandler(
38
+ "permission",
39
+ async (response) => {
40
+ const pending = this.pendingRequests.get(response.id);
41
+ if (!pending) {
42
+ logger.logger.debug(`${this.getLogPrefix()} Permission request not found or already resolved`);
43
+ return;
44
+ }
45
+ this.pendingRequests.delete(response.id);
46
+ const result = response.approved ? { decision: response.decision === "approved_for_session" ? "approved_for_session" : "approved" } : { decision: response.decision === "denied" ? "denied" : "abort" };
47
+ pending.resolve(result);
48
+ if (response.approved && (response.mode === "bypassPermissions" || response.decision === "approved_for_session")) {
49
+ this.approvePendingRequestsForSession(response);
50
+ }
51
+ this.session.updateAgentState((currentState) => {
52
+ const request = currentState.requests?.[response.id];
53
+ if (!request) return currentState;
54
+ const { [response.id]: _, ...remainingRequests } = currentState.requests || {};
55
+ let res = {
56
+ ...currentState,
57
+ requests: remainingRequests,
58
+ completedRequests: {
59
+ ...currentState.completedRequests,
60
+ [response.id]: {
61
+ ...request,
62
+ completedAt: Date.now(),
63
+ status: response.approved ? "approved" : "denied",
64
+ decision: result.decision,
65
+ mode: response.mode,
66
+ allowedTools: response.allowTools
67
+ }
68
+ }
69
+ };
70
+ return res;
71
+ });
72
+ logger.logger.debug(`${this.getLogPrefix()} Permission ${response.approved ? "approved" : "denied"} for ${pending.toolName}`);
73
+ }
74
+ );
75
+ }
76
+ approvePendingRequestsForSession(response) {
77
+ const pendingSnapshot = Array.from(this.pendingRequests.entries());
78
+ const completedAt = Date.now();
79
+ for (const [id, pending] of pendingSnapshot) {
80
+ if (this.isUserInteractionTool(pending.toolName)) {
81
+ continue;
82
+ }
83
+ this.pendingRequests.delete(id);
84
+ pending.resolve({ decision: "approved_for_session" });
85
+ }
86
+ if (pendingSnapshot.length === 0) {
87
+ return;
88
+ }
89
+ this.session.updateAgentState((currentState) => {
90
+ const requests = { ...currentState.requests || {} };
91
+ const completedRequests = { ...currentState.completedRequests };
92
+ let changed = false;
93
+ for (const [id, pending] of pendingSnapshot) {
94
+ if (this.isUserInteractionTool(pending.toolName)) {
95
+ continue;
96
+ }
97
+ const request = requests[id];
98
+ if (!request) {
99
+ continue;
100
+ }
101
+ delete requests[id];
102
+ completedRequests[id] = {
103
+ ...request,
104
+ completedAt,
105
+ status: "approved",
106
+ decision: "approved_for_session",
107
+ mode: response.mode,
108
+ allowedTools: response.allowTools
109
+ };
110
+ changed = true;
111
+ }
112
+ if (!changed) {
113
+ return currentState;
114
+ }
115
+ return {
116
+ ...currentState,
117
+ requests,
118
+ completedRequests
119
+ };
120
+ });
121
+ }
122
+ /**
123
+ * Add a pending request to the agent state and send a push notification.
124
+ */
125
+ addPendingRequestToState(toolCallId, toolName, input) {
126
+ this.pushClient.sendToAllDevices(
127
+ "Permission Request",
128
+ `${this.getAgentName()} wants to ${toolName}`,
129
+ {
130
+ sessionId: this.session.sessionId,
131
+ requestId: toolCallId,
132
+ tool: toolName,
133
+ type: "permission_request"
134
+ }
135
+ );
136
+ this.session.updateAgentState((currentState) => ({
137
+ ...currentState,
138
+ requests: {
139
+ ...currentState.requests,
140
+ [toolCallId]: {
141
+ tool: toolName,
142
+ arguments: input,
143
+ createdAt: Date.now()
144
+ }
145
+ }
146
+ }));
147
+ }
148
+ /**
149
+ * Reset state for new sessions.
150
+ * This method is idempotent - safe to call multiple times.
151
+ */
152
+ reset() {
153
+ if (this.isResetting) {
154
+ logger.logger.debug(`${this.getLogPrefix()} Reset already in progress, skipping`);
155
+ return;
156
+ }
157
+ this.isResetting = true;
158
+ try {
159
+ const pendingSnapshot = Array.from(this.pendingRequests.entries());
160
+ this.pendingRequests.clear();
161
+ for (const [id, pending] of pendingSnapshot) {
162
+ try {
163
+ pending.reject(new Error("Session reset"));
164
+ } catch (err) {
165
+ logger.logger.debug(`${this.getLogPrefix()} Error rejecting pending request ${id}:`, err);
166
+ }
167
+ }
168
+ this.session.updateAgentState((currentState) => {
169
+ const pendingRequests = currentState.requests || {};
170
+ const completedRequests = { ...currentState.completedRequests };
171
+ for (const [id, request] of Object.entries(pendingRequests)) {
172
+ completedRequests[id] = {
173
+ ...request,
174
+ completedAt: Date.now(),
175
+ status: "canceled",
176
+ reason: "Session reset"
177
+ };
178
+ }
179
+ return {
180
+ ...currentState,
181
+ requests: {},
182
+ completedRequests
183
+ };
184
+ });
185
+ logger.logger.debug(`${this.getLogPrefix()} Permission handler reset`);
186
+ } finally {
187
+ this.isResetting = false;
188
+ }
189
+ }
190
+ }
191
+
192
+ const DEFAULT_MAX_SKILLS = 400;
193
+ const DEFAULT_MAX_DEPTH = 10;
194
+ const SKILL_FILE = "SKILL.md";
195
+ const IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
196
+ ".git",
197
+ "node_modules",
198
+ "dist",
199
+ "build",
200
+ "references",
201
+ "assets",
202
+ "templates"
203
+ ]);
204
+ function parseFrontMatter(content) {
205
+ if (!content.startsWith("---")) return {};
206
+ const end = content.indexOf("\n---", 3);
207
+ if (end < 0) return {};
208
+ const block = content.slice(3, end).split(/\r?\n/);
209
+ const result = {};
210
+ for (let i = 0; i < block.length; i++) {
211
+ const line = block[i];
212
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line.trim());
213
+ if (!match) continue;
214
+ const [, key, rawValue] = match;
215
+ let value = rawValue.trim().replace(/^['"]|['"]$/g, "");
216
+ if ((rawValue.trim() === ">-" || rawValue.trim() === ">" || rawValue.trim() === "|-" || rawValue.trim() === "|") && key === "description") {
217
+ const continuation = [];
218
+ while (i + 1 < block.length && /^\s+/.test(block[i + 1])) {
219
+ i++;
220
+ continuation.push(block[i].trim());
221
+ }
222
+ value = continuation.join(rawValue.trim().startsWith("|") ? "\n" : " ").trim();
223
+ }
224
+ if (key === "name" && value) result.name = value;
225
+ if (key === "description" && value) result.description = value;
226
+ }
227
+ return result;
228
+ }
229
+ function deriveSkillName(skillFilePath) {
230
+ return path.basename(path.dirname(skillFilePath));
231
+ }
232
+ function collectSkillFiles(root, maxDepth, maxFiles) {
233
+ const files = [];
234
+ function walk(dir, depth) {
235
+ if (files.length >= maxFiles || depth > maxDepth) return;
236
+ let entries;
237
+ try {
238
+ entries = fs.readdirSync(dir, { withFileTypes: true });
239
+ } catch {
240
+ return;
241
+ }
242
+ for (const entry of entries) {
243
+ if (files.length >= maxFiles) return;
244
+ const fullPath = path.join(dir, entry.name);
245
+ if (entry.isFile() && entry.name === SKILL_FILE) {
246
+ files.push(fullPath);
247
+ continue;
248
+ }
249
+ if (!entry.isDirectory()) continue;
250
+ if (IGNORED_DIRECTORIES.has(entry.name)) continue;
251
+ walk(fullPath, depth + 1);
252
+ }
253
+ }
254
+ if (fs.existsSync(root)) {
255
+ walk(root, 0);
256
+ }
257
+ return files;
258
+ }
259
+ function skillRoots(homeDir, includePluginCache) {
260
+ const roots = [
261
+ { path: path.join(homeDir, ".agents", "skills"), source: "agents" },
262
+ { path: path.join(homeDir, ".codex", "skills"), source: "codex" },
263
+ { path: path.join(homeDir, ".claude", "skills"), source: "claude" }
264
+ ];
265
+ if (includePluginCache) {
266
+ roots.push(
267
+ { path: path.join(homeDir, ".codex", "plugins", "cache"), source: "codex-plugin-cache" },
268
+ { path: path.join(homeDir, ".codex", ".tmp", "plugins", "plugins"), source: "codex-plugin-marketplace" }
269
+ );
270
+ }
271
+ return roots;
272
+ }
273
+ function discoverCodexSkills(options = {}) {
274
+ const homeDir = options.homeDir ?? os.homedir();
275
+ const maxSkills = options.maxSkills ?? DEFAULT_MAX_SKILLS;
276
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
277
+ const includePluginCache = options.includePluginCache ?? true;
278
+ const result = [];
279
+ const seen = /* @__PURE__ */ new Set();
280
+ for (const root of skillRoots(homeDir, includePluginCache)) {
281
+ if (result.length >= maxSkills) break;
282
+ const skillFiles = collectSkillFiles(root.path, maxDepth, maxSkills - result.length);
283
+ for (const skillFile of skillFiles) {
284
+ if (result.length >= maxSkills) break;
285
+ let content = "";
286
+ try {
287
+ content = fs.readFileSync(skillFile, "utf8");
288
+ } catch {
289
+ continue;
290
+ }
291
+ const frontMatter = parseFrontMatter(content);
292
+ const name = (frontMatter.name || deriveSkillName(skillFile)).trim();
293
+ if (!name) continue;
294
+ const key = name.toLowerCase();
295
+ if (seen.has(key)) continue;
296
+ seen.add(key);
297
+ result.push({
298
+ name,
299
+ description: frontMatter.description,
300
+ source: root.source
301
+ });
302
+ }
303
+ }
304
+ return result;
305
+ }
306
+
307
+ function detectWorkspaceSubdirectories(cwd) {
308
+ try {
309
+ const entries = fs.readdirSync(cwd, { withFileTypes: true });
310
+ const repos = [];
311
+ for (const entry of entries) {
312
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
313
+ const subDir = path.join(cwd, entry.name);
314
+ const info = gitWorktree.detectGitWorktree(subDir);
315
+ if (info.isWorktree && info.worktreeBasePath && info.worktreeBranchName) {
316
+ repos.push({
317
+ path: subDir,
318
+ basePath: info.worktreeBasePath,
319
+ branchName: info.worktreeBranchName,
320
+ displayName: entry.name
321
+ });
322
+ }
323
+ }
324
+ if (repos.length > 0) {
325
+ return {
326
+ isWorktree: true,
327
+ workspaceRepos: repos,
328
+ workspacePath: cwd
329
+ };
330
+ }
331
+ } catch {
332
+ }
333
+ return {};
334
+ }
335
+ function detectWorktreeMetadata() {
336
+ if (process.env.HAPPY_WORKSPACE_REPOS) {
337
+ try {
338
+ const repos = JSON.parse(process.env.HAPPY_WORKSPACE_REPOS);
339
+ return {
340
+ isWorktree: true,
341
+ workspaceRepos: repos,
342
+ workspacePath: process.env.HAPPY_WORKSPACE_PATH
343
+ };
344
+ } catch {
345
+ }
346
+ }
347
+ if (process.env.HAPPY_WORKTREE_BASE_PATH) {
348
+ return {
349
+ isWorktree: true,
350
+ worktreeBasePath: process.env.HAPPY_WORKTREE_BASE_PATH,
351
+ worktreeBranchName: process.env.HAPPY_WORKTREE_BRANCH_NAME
352
+ };
353
+ }
354
+ const info = gitWorktree.detectGitWorktree(process.cwd());
355
+ if (info.isWorktree) {
356
+ return {
357
+ isWorktree: true,
358
+ worktreeBasePath: info.worktreeBasePath,
359
+ worktreeBranchName: info.worktreeBranchName
360
+ };
361
+ }
362
+ const workspaceResult = detectWorkspaceSubdirectories(process.cwd());
363
+ if (workspaceResult.isWorktree) {
364
+ return workspaceResult;
365
+ }
366
+ return {};
367
+ }
368
+ function createSessionMetadata(opts) {
369
+ const state = {
370
+ controlledByUser: false
371
+ };
372
+ const metadata = {
373
+ path: process.cwd(),
374
+ host: os.hostname(),
375
+ version: logger.packageJson.version,
376
+ os: os.platform(),
377
+ machineId: opts.machineId,
378
+ homeDir: os.homedir(),
379
+ happyHomeDir: logger.configuration.happyHomeDir,
380
+ happyLibDir: projectPath.projectPath(),
381
+ happyToolsDir: api.resolveToolsDir(),
382
+ startedFromDaemon: opts.startedBy === "daemon",
383
+ hostPid: process.pid,
384
+ startedBy: opts.startedBy || "terminal",
385
+ lifecycleState: "running",
386
+ lifecycleStateSince: Date.now(),
387
+ flavor: opts.flavor,
388
+ // Worktree metadata: env vars from daemon take priority, otherwise detect via git
389
+ ...detectWorktreeMetadata()
390
+ };
391
+ if (opts.flavor === "codex") {
392
+ metadata.skills = discoverCodexSkills();
393
+ }
394
+ return { state, metadata };
395
+ }
396
+
397
+ function createOfflineSessionStub(sessionTag) {
398
+ return {
399
+ sessionId: `offline-${sessionTag}`,
400
+ sendCodexMessage: () => {
401
+ },
402
+ sendAgentMessage: () => {
403
+ },
404
+ sendClaudeSessionMessage: () => {
405
+ },
406
+ keepAlive: () => {
407
+ },
408
+ sendSessionEvent: () => {
409
+ },
410
+ sendSessionDeath: () => {
411
+ },
412
+ updateLifecycleState: () => {
413
+ },
414
+ requestControlTransfer: async () => {
415
+ },
416
+ flush: async () => {
417
+ },
418
+ close: async () => {
419
+ },
420
+ updateMetadata: () => {
421
+ },
422
+ updateAgentState: () => {
423
+ },
424
+ onUserMessage: () => {
425
+ },
426
+ rpcHandlerManager: {
427
+ registerHandler: () => {
428
+ }
429
+ }
430
+ };
431
+ }
432
+
433
+ function setupOfflineReconnection(opts) {
434
+ const { api: api$1, sessionTag, metadata, state, response, onSessionSwap } = opts;
435
+ let session;
436
+ let reconnectionHandle = null;
437
+ if (!response) {
438
+ session = createOfflineSessionStub(sessionTag);
439
+ reconnectionHandle = api.startOfflineReconnection({
440
+ serverUrl: logger.configuration.serverUrl,
441
+ onReconnected: async () => {
442
+ const resp = await api$1.getOrCreateSession({ tag: sessionTag, metadata, state });
443
+ if (!resp) throw new Error("Server unavailable");
444
+ const realSession = api$1.sessionSyncClient(resp);
445
+ onSessionSwap(realSession);
446
+ return realSession;
447
+ },
448
+ onNotify: (msg) => {
449
+ console.log(msg);
450
+ }
451
+ });
452
+ return { session, reconnectionHandle, isOffline: true };
453
+ } else {
454
+ session = api$1.sessionSyncClient(response);
455
+ return { session, reconnectionHandle: null, isOffline: false };
456
+ }
457
+ }
458
+
459
+ exports.BasePermissionHandler = BasePermissionHandler;
460
+ exports.createSessionMetadata = createSessionMetadata;
461
+ exports.setupOfflineReconnection = setupOfflineReconnection;