very-happy-cli 0.2.138 → 0.2.140

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 (45) hide show
  1. package/dist/{AcpBackend-BUoDXZnv.cjs → AcpBackend-C0Lq4uoA.cjs} +2 -2
  2. package/dist/{AcpBackend-bqVGMkPh.mjs → AcpBackend-DsSYq8T-.mjs} +2 -2
  3. package/dist/{AcpSessionManager-BBAQ8EQf.mjs → AcpSessionManager-BAErE9s0.mjs} +1 -1
  4. package/dist/{AcpSessionManager-DmmA52Ep.cjs → AcpSessionManager-DIqByTH7.cjs} +1 -1
  5. package/dist/{agentGuidance-4HV-BOge.cjs → agentGuidance-Dl3apItH.cjs} +1 -1
  6. package/dist/{agentGuidance-WHZsBKpm.mjs → agentGuidance-xk3v4_7E.mjs} +1 -1
  7. package/dist/codex/happyMcpStdioBridge.cjs +2 -2
  8. package/dist/codex/happyMcpStdioBridge.mjs +2 -2
  9. package/dist/{config-BRXqgJJj.mjs → config-BVoHul9V.mjs} +4 -4
  10. package/dist/{config-DpuZN2Rs.cjs → config-D0-jnCOC.cjs} +4 -4
  11. package/dist/{index-DQe7ljLR.mjs → index-BNydKYvS.mjs} +7 -7
  12. package/dist/{index-D8Q3OhdR.mjs → index-BPnAbcz_.mjs} +4 -4
  13. package/dist/{index-CHP265gs.cjs → index-BuQn9kUK.cjs} +4 -4
  14. package/dist/{index-Dbl5U_N0.mjs → index-D0IP7gXG.mjs} +116 -232
  15. package/dist/{index-3N-qu-RG.cjs → index-DJvzGXVN.cjs} +7 -7
  16. package/dist/{index-CRRK5P1r.cjs → index-__h-pCTK.cjs} +147 -268
  17. package/dist/index.cjs +4 -4
  18. package/dist/index.mjs +4 -4
  19. package/dist/{installTerminalHooks-DfUGgeyb.mjs → installTerminalHooks-D2ice1a-.mjs} +4 -4
  20. package/dist/{installTerminalHooks-CWGkoWDD.cjs → installTerminalHooks-D3jfvbyY.cjs} +4 -4
  21. package/dist/lib.cjs +2 -2
  22. package/dist/lib.d.cts +21 -0
  23. package/dist/lib.d.mts +21 -0
  24. package/dist/lib.mjs +2 -2
  25. package/dist/{limits-CfzVummd.cjs → limits-Dbip6eVO.cjs} +26 -7
  26. package/dist/{limits-DEsg_gHi.mjs → limits-nhD0Wran.mjs} +26 -8
  27. package/dist/{mcp-CN2UVfut.cjs → mcp-DeapmTWN.cjs} +21 -21
  28. package/dist/{mcp-UnjB3I8_.mjs → mcp-V26C05fN.mjs} +19 -19
  29. package/dist/{runGemini-BUVjTJKn.cjs → runGemini-D34eCFpz.cjs} +7 -7
  30. package/dist/{runGemini-BZ0xXRj-.mjs → runGemini-sa5kAgPe.mjs} +6 -6
  31. package/dist/{runOpenClaw-Bj2EgRHB.cjs → runOpenClaw-B8F8D--R.cjs} +6 -6
  32. package/dist/{runOpenClaw-BcUmnBpW.mjs → runOpenClaw-Bdsq8KBa.mjs} +5 -5
  33. package/dist/{send-BkypdBpK.cjs → send-DP_S3wn0.cjs} +4 -4
  34. package/dist/{send-snK_NGAA.mjs → send-KICC_ACz.mjs} +4 -4
  35. package/dist/{sessions-DxlC4C4g.mjs → sessions-C6EvnC4B.mjs} +4 -4
  36. package/dist/{sessions-9A-uoJL_.cjs → sessions-CGBBgVZn.cjs} +4 -4
  37. package/dist/{spawn-BORLpj60.cjs → spawn-BhUK0Vt2.cjs} +8 -8
  38. package/dist/{spawn-DFfHCafP.mjs → spawn-C1OqXJNb.mjs} +6 -6
  39. package/dist/{teams-9x2FO9RW.cjs → teams-C29nEHFD.cjs} +4 -4
  40. package/dist/{teams-Cfr-2Yd-.mjs → teams-Dm5HGpNz.mjs} +4 -4
  41. package/dist/{todo-CU5cjQZU.mjs → todo-C-vovA0N.mjs} +3 -3
  42. package/dist/{todo-DydKcknX.cjs → todo-CeJX0z_2.cjs} +3 -3
  43. package/dist/{types-CRxf_3n8.cjs → types-DCVS050m.cjs} +571 -13
  44. package/dist/{types-D5EsIAOe.mjs → types-thyvQB2a.mjs} +558 -13
  45. package/package.json +7 -7
@@ -1,13 +1,13 @@
1
1
  import{createRequire as _pkgrollCR}from"node:module";const require=_pkgrollCR(import.meta.url);import chalk from 'chalk';
2
2
  import os, { homedir, userInfo, tmpdir } from 'node:os';
3
3
  import { randomUUID, randomInt, randomBytes, createHash as createHash$1, timingSafeEqual } from 'node:crypto';
4
- import { j as getProjectPath, g as BUILTIN_TODO_DISCOVERY, p as projectPath, k as initializeSandbox, w as wrapCommand, d as contentLogMetadata, I as InvalidateSync, R as RawJSONLinesSchema, h as delay, l as AsyncLock, S as STREAM_DELTA_MAX_CHARS, M as MAX_CHAT_ATTACHMENT_SOURCE_BYTES, m as commandOnPath, n as deriveLocalCliUpdateSummary, o as AGENT_VERSION_SOURCES, q as isClaudeSessionId, r as getLocalHappyAgentCredentialPath, t as readLocalHappyAgentCredentials, u as parseExactVersion, v as compareExactVersions, x as extractCompleteLines, y as decideBackfill, z as parseTerminalHookPayload, C as tmuxArgs, D as scrubTmuxClientEnv, E as decideMirrorBinding, F as MIRROR_BACKFILL_LINES_DEFAULT, G as mirrorLineKey, H as mirrorLocalId, J as detectCLIAvailability, K as detectResumeSupport, L as summarizeSpawnSessionForLog, N as shellescape, A as ApiClient, O as fetchCliUpdateState, P as resolveCliUpdateCheckInterval, Q as DEFAULT_CLI_UPDATE_CHECK_INTERVAL_MS, i as isValidSessionId, T as listVhTerminals, U as isValidTerminalId, V as readVhTerminal, W as sendToVhTerminal, X as ContextUsageSchema, Y as TITLE_PROMPT_PREFIX, Z as BOARD_ANALYZER_PROMPT_PREFIX, f as connectionState, _ as startOfflineReconnection, c as createEnvelope, $ as CodexAppServerClient } from './types-D5EsIAOe.mjs';
5
- import { z as readDaemonState, l as logger, c as configuration, A as clearDaemonState, B as ensurePrivateDirectory, D as hardenPrivateFile, p as packageJson, g as readSettings, E as readCredentials, s as credentialRelayProblem, i as encodeBase64, F as readSettingsOutcome, G as updateSettings, H as encodeBase64Url, m as decodeBase64, I as writeCredentialsLegacy, J as writeCredentialsDataKey, d as readCredentialsForConfiguredRelay, j as encrypt, r as readPersistedSessions, w as writePrivateFileSync, K as decryptWithDataKey, L as decryptLegacy, M as persistSession, k as decrypt, f as ensurePrivateDirectorySync, N as acquireDaemonLock, O as deletePersistedSessions, P as writeDaemonState, Q as writeSettings, R as releaseDaemonLock, C as CLIPBOARD_TOOL_NAME, a as CLIPBOARD_TOOL_TITLE, b as CLIPBOARD_TOOL_DESCRIPTION, e as CLIPBOARD_MAX_BYTES, S as clearCredentials, T as clearMachineId, U as SandboxConfigSchema, V as getLatestDaemonLog } from './limits-DEsg_gHi.mjs';
4
+ import { o as notifyDaemonSessionEvent, q as getProjectPath, l as BUILTIN_TODO_DISCOVERY, p as projectPath, r as initializeSandbox, w as wrapCommand, j as contentLogMetadata, I as InvalidateSync, R as RawJSONLinesSchema, m as delay, t as AsyncLock, S as STREAM_DELTA_MAX_CHARS, M as MAX_CHAT_ATTACHMENT_SOURCE_BYTES, u as notifyDaemonClaudeAuthFailed, v as commandOnPath, c as checkIfDaemonRunningAndCleanupStaleState, x as deriveLocalCliUpdateSummary, y as AGENT_VERSION_SOURCES, z as isClaudeSessionId, C as getLocalHappyAgentCredentialPath, D as readLocalHappyAgentCredentials, E as parseExactVersion, F as compareExactVersions, G as extractCompleteLines, H as decideBackfill, J as parseTerminalHookPayload, K as tmuxArgs, L as scrubTmuxClientEnv, N as decideMirrorBinding, O as MIRROR_BACKFILL_LINES_DEFAULT, P as mirrorLineKey, Q as mirrorLocalId, T as listDaemonSessions, U as stopDaemonSession, V as detectCLIAvailability, W as detectResumeSupport, X as isDaemonRunningCurrentlyInstalledHappyVersion, Y as stopDaemon, Z as TurnActivityTracker, _ as summarizeSpawnSessionForLog, $ as shellescape, A as ApiClient, a0 as fetchCliUpdateState, a1 as resolveCliUpdateCheckInterval, a2 as DEFAULT_CLI_UPDATE_CHECK_INTERVAL_MS, a3 as cleanupDaemonState, i as isValidSessionId, s as spawnDaemonSession, a4 as listVhTerminals, a5 as isValidTerminalId, a6 as readVhTerminal, a7 as sendToVhTerminal, a8 as ContextUsageSchema, a9 as TITLE_PROMPT_PREFIX, aa as BOARD_ANALYZER_PROMPT_PREFIX, k as connectionState, ab as startOfflineReconnection, n as notifyDaemonSessionStarted, d as createEnvelope, ac as CodexAppServerClient } from './types-thyvQB2a.mjs';
5
+ import { l as logger, D as ensurePrivateDirectory, E as hardenPrivateFile, c as configuration, p as packageJson, g as readSettings, F as readCredentials, u as credentialRelayProblem, o as readDaemonState, i as encodeBase64, G as readSettingsOutcome, H as updateSettings, I as encodeBase64Url, m as decodeBase64, J as writeCredentialsLegacy, K as writeCredentialsDataKey, d as readCredentialsForConfiguredRelay, j as encrypt, r as readPersistedSessions, w as writePrivateFileSync, L as decryptWithDataKey, M as decryptLegacy, N as persistSession, k as decrypt, f as ensurePrivateDirectorySync, O as acquireDaemonLock, P as deletePersistedSessions, Q as writeDaemonState, R as writeSettings, S as releaseDaemonLock, C as CLIPBOARD_TOOL_NAME, a as CLIPBOARD_TOOL_TITLE, b as CLIPBOARD_TOOL_DESCRIPTION, e as CLIPBOARD_MAX_BYTES, T as clearCredentials, U as clearMachineId, V as SandboxConfigSchema, W as getLatestDaemonLog } from './limits-nhD0Wran.mjs';
6
6
  import spawn$1, { spawn } from 'cross-spawn';
7
7
  import path, { join, resolve, basename, isAbsolute, dirname, sep, delimiter, normalize } from 'node:path';
8
8
  import { createInterface } from 'node:readline';
9
9
  import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, unlinkSync, renameSync, writeFileSync, accessSync, constants, openSync, fsyncSync, closeSync, rmSync as rmSync$1, chmodSync as chmodSync$1 } from 'node:fs';
10
- import { f as trimIdent, A as AGENT_GUIDANCE, t as teamScopePath, T as TeamConnectionPreflightError, e as createTeamsClient, P as PREVIEW_TOOL_NAME, R as REPORT_PROGRESS_TOOL_NAME, g as TEAM_TOOL_NAMES, r as registerTeamsTools, a as PREVIEW_TOOL_TITLE, b as PREVIEW_TOOL_DESCRIPTION, h as REPORT_PROGRESS_TOOL_TITLE, i as REPORT_PROGRESS_TOOL_DESCRIPTION } from './agentGuidance-WHZsBKpm.mjs';
10
+ import { f as trimIdent, A as AGENT_GUIDANCE, t as teamScopePath, T as TeamConnectionPreflightError, e as createTeamsClient, P as PREVIEW_TOOL_NAME, R as REPORT_PROGRESS_TOOL_NAME, g as TEAM_TOOL_NAMES, r as registerTeamsTools, a as PREVIEW_TOOL_TITLE, b as PREVIEW_TOOL_DESCRIPTION, h as REPORT_PROGRESS_TOOL_TITLE, i as REPORT_PROGRESS_TOOL_DESCRIPTION } from './agentGuidance-xk3v4_7E.mjs';
11
11
  import { readFile, writeFile, rename, unlink, mkdir, symlink, rm, readlink, lstat, stat, open as open$1, appendFile } from 'node:fs/promises';
12
12
  import fs, { watch, access } from 'fs/promises';
13
13
  import { useStdout, useInput, Box, Text, render } from 'ink';
@@ -93,212 +93,6 @@ function withoutServerSnapshot(response) {
93
93
  return { ...response, metadataVersion: 0, agentStateVersion: 0 };
94
94
  }
95
95
 
96
- function daemonControlHeaders(controlToken) {
97
- return {
98
- "Content-Type": "application/json",
99
- ...controlToken ? { Authorization: `Bearer ${controlToken}` } : {}
100
- };
101
- }
102
- async function daemonPost(path, body) {
103
- const state = await readDaemonState();
104
- if (!state?.httpPort) {
105
- const errorMessage = "No daemon running, no state file found";
106
- logger.debug(`[CONTROL CLIENT] ${errorMessage}`);
107
- return {
108
- error: errorMessage
109
- };
110
- }
111
- try {
112
- process.kill(state.pid, 0);
113
- } catch (error) {
114
- const errorMessage = "Daemon is not running, file is stale";
115
- logger.debug(`[CONTROL CLIENT] ${errorMessage}`);
116
- return {
117
- error: errorMessage
118
- };
119
- }
120
- try {
121
- const timeout = process.env.HAPPY_DAEMON_HTTP_TIMEOUT ? parseInt(process.env.HAPPY_DAEMON_HTTP_TIMEOUT) : 1e4;
122
- const response = await fetch(`http://127.0.0.1:${state.httpPort}${path}`, {
123
- method: "POST",
124
- // A state written by an old daemon has no token and must remain callable;
125
- // a new daemon always writes one and rejects requests without it.
126
- headers: daemonControlHeaders(state.controlToken),
127
- body: JSON.stringify(body || {}),
128
- // Mostly increased for stress test
129
- signal: AbortSignal.timeout(timeout)
130
- });
131
- if (!response.ok) {
132
- const failure = await response.json().catch(() => null);
133
- const reason = typeof failure?.error === "string" && failure.error ? failure.error : `HTTP ${response.status}`;
134
- const errorMessage = `Request failed: ${path}, ${reason}`;
135
- logger.debug(`[CONTROL CLIENT] ${errorMessage}`);
136
- return {
137
- error: errorMessage
138
- };
139
- }
140
- return await response.json();
141
- } catch (error) {
142
- const errorMessage = `Request failed: ${path}, ${error instanceof Error ? error.message : "Unknown error"}`;
143
- logger.debug(`[CONTROL CLIENT] ${errorMessage}`);
144
- return {
145
- error: errorMessage
146
- };
147
- }
148
- }
149
- const SESSION_STARTED_RETRY_TIMEOUT_MS = 3e3;
150
- const SESSION_STARTED_RETRY_INTERVAL_MS = 100;
151
- async function notifyDaemonSessionStarted(sessionId, metadata, encryption) {
152
- const payload = { sessionId, metadata, encryption };
153
- const deadline = Date.now() + SESSION_STARTED_RETRY_TIMEOUT_MS;
154
- let result;
155
- while (true) {
156
- result = await daemonPost("/session-started", payload);
157
- if (!result?.error) {
158
- return result;
159
- }
160
- if (Date.now() >= deadline) {
161
- return result;
162
- }
163
- await new Promise((resolve) => setTimeout(resolve, SESSION_STARTED_RETRY_INTERVAL_MS));
164
- }
165
- }
166
- async function listDaemonSessions() {
167
- const result = await daemonPost("/list");
168
- return result.children || [];
169
- }
170
- async function stopDaemonSession(sessionId) {
171
- const result = await daemonPost("/stop-session", { sessionId });
172
- return result.success || false;
173
- }
174
- async function spawnDaemonSession(directory, sessionId, opts) {
175
- const result = await daemonPost("/spawn-session", {
176
- directory,
177
- sessionId,
178
- spawnedBy: opts?.spawnedBy,
179
- permissionMode: opts?.permissionMode,
180
- agent: opts?.agent,
181
- environmentVariables: opts?.environmentVariables
182
- });
183
- return result;
184
- }
185
- async function notifyDaemonSessionEvent(sessionId, event, spawnedBy) {
186
- return daemonPost("/session-event", { sessionId, event, spawnedBy });
187
- }
188
- async function notifyDaemonClaudeAuthFailed(sessionId) {
189
- return daemonPost("/session-event", { sessionId, event: "auth_failed" });
190
- }
191
- async function stopDaemonHttp() {
192
- await daemonPost("/stop");
193
- }
194
- async function pushClipboardViaDaemon(text) {
195
- const result = await daemonPost("/clipboard", { text });
196
- if (result?.error && result.delivered === void 0) {
197
- return { delivered: false, error: result.error };
198
- }
199
- return result;
200
- }
201
- async function setTerminalTitleViaDaemon(terminalId, title, ifAbsent = false) {
202
- const result = await daemonPost("/terminal-title", { terminalId, title, ifAbsent });
203
- if (result?.error) {
204
- return { ok: false, error: result.error };
205
- }
206
- return { ok: result?.status === "ok", error: result?.status === "ok" ? void 0 : "unexpected daemon response" };
207
- }
208
- async function checkIfDaemonRunningAndCleanupStaleState() {
209
- const state = await readDaemonState();
210
- if (!state) {
211
- return false;
212
- }
213
- try {
214
- process.kill(state.pid, 0);
215
- } catch {
216
- logger.debug("[DAEMON RUN] Daemon PID not running, cleaning up state");
217
- await cleanupDaemonState();
218
- return false;
219
- }
220
- if (state.httpPort) {
221
- try {
222
- const response = await fetch(`http://127.0.0.1:${state.httpPort}/list`, {
223
- method: "POST",
224
- headers: daemonControlHeaders(state.controlToken),
225
- body: "{}",
226
- signal: AbortSignal.timeout(2e3)
227
- });
228
- if (response.ok) {
229
- return true;
230
- }
231
- } catch {
232
- logger.debug(`[DAEMON RUN] PID ${state.pid} is alive but HTTP health check failed on port ${state.httpPort}, cleaning up stale state`);
233
- await cleanupDaemonState();
234
- return false;
235
- }
236
- }
237
- return true;
238
- }
239
- async function isDaemonRunningCurrentlyInstalledHappyVersion() {
240
- logger.debug("[DAEMON CONTROL] Checking if daemon is running same version");
241
- const runningDaemon = await checkIfDaemonRunningAndCleanupStaleState();
242
- if (!runningDaemon) {
243
- logger.debug("[DAEMON CONTROL] No daemon running, returning false");
244
- return false;
245
- }
246
- const state = await readDaemonState();
247
- if (!state) {
248
- logger.debug("[DAEMON CONTROL] No daemon state found, returning false");
249
- return false;
250
- }
251
- const currentCliVersion = configuration.currentCliVersion;
252
- logger.debug(`[DAEMON CONTROL] Current CLI version: ${currentCliVersion}, Daemon started with version: ${state.startedWithCliVersion}`);
253
- return currentCliVersion === state.startedWithCliVersion;
254
- }
255
- async function cleanupDaemonState() {
256
- try {
257
- await clearDaemonState();
258
- logger.debug("[DAEMON RUN] Daemon state file removed");
259
- } catch (error) {
260
- logger.debug("[DAEMON RUN] Error cleaning up daemon metadata", error);
261
- }
262
- }
263
- async function stopDaemon() {
264
- try {
265
- const state = await readDaemonState();
266
- if (!state) {
267
- logger.debug("No daemon state found");
268
- return;
269
- }
270
- logger.debug(`Stopping daemon with PID ${state.pid}`);
271
- try {
272
- await stopDaemonHttp();
273
- await waitForProcessDeath(state.pid, 2e3);
274
- logger.debug("Daemon stopped gracefully via HTTP");
275
- return;
276
- } catch (error) {
277
- logger.debug("HTTP stop failed, will force kill", error);
278
- }
279
- try {
280
- process.kill(state.pid, "SIGKILL");
281
- logger.debug("Force killed daemon");
282
- } catch (error) {
283
- logger.debug("Daemon already dead");
284
- }
285
- } catch (error) {
286
- logger.debug("Error stopping daemon", error);
287
- }
288
- }
289
- async function waitForProcessDeath(pid, timeout) {
290
- const start = Date.now();
291
- while (Date.now() - start < timeout) {
292
- try {
293
- process.kill(pid, 0);
294
- await new Promise((resolve) => setTimeout(resolve, 100));
295
- } catch {
296
- return;
297
- }
298
- }
299
- throw new Error("Process did not die within timeout");
300
- }
301
-
302
96
  class Session {
303
97
  path;
304
98
  logPath;
@@ -3902,6 +3696,7 @@ function applyClaudeSdkMetadata(current, update) {
3902
3696
  function createTurnSteeringController() {
3903
3697
  let interrupt = null;
3904
3698
  let steering = false;
3699
+ let interrupting = false;
3905
3700
  return {
3906
3701
  setInterrupt(next) {
3907
3702
  interrupt = next;
@@ -3926,17 +3721,31 @@ function createTurnSteeringController() {
3926
3721
  */
3927
3722
  async interruptTurn() {
3928
3723
  if (!interrupt) return false;
3929
- await interrupt();
3930
- return true;
3724
+ interrupting = true;
3725
+ try {
3726
+ await interrupt();
3727
+ return true;
3728
+ } catch (error) {
3729
+ interrupting = false;
3730
+ throw error;
3731
+ }
3931
3732
  },
3932
3733
  consumeReady() {
3933
3734
  if (!steering) return false;
3934
3735
  steering = false;
3935
3736
  return true;
3936
3737
  },
3738
+ /** The next `result` belongs to a stop-button interrupt: close the
3739
+ * turn as cancelled and say "Aborted by user", not "failed". */
3740
+ consumeInterrupted() {
3741
+ if (!interrupting) return false;
3742
+ interrupting = false;
3743
+ return true;
3744
+ },
3937
3745
  reset() {
3938
3746
  interrupt = null;
3939
3747
  steering = false;
3748
+ interrupting = false;
3940
3749
  }
3941
3750
  };
3942
3751
  }
@@ -4098,6 +3907,7 @@ async function claudeRemoteLauncher(session, onPermissionModeChange, onEffective
4098
3907
  return;
4099
3908
  }
4100
3909
  logger.debug("[remote]: interrupt did not stop the turn in time; escalating to hard abort");
3910
+ turnSteering.consumeInterrupted();
4101
3911
  }
4102
3912
  await abort();
4103
3913
  }
@@ -4431,6 +4241,11 @@ async function claudeRemoteLauncher(session, onPermissionModeChange, onEffective
4431
4241
  session.client.closeClaudeSessionTurn("cancelled");
4432
4242
  return;
4433
4243
  }
4244
+ if (turnSteering.consumeInterrupted()) {
4245
+ session.client.closeClaudeSessionTurn("cancelled");
4246
+ session.client.sendSessionEvent({ type: "message", message: "Aborted by user" });
4247
+ return;
4248
+ }
4434
4249
  applyClaudeResultLifecycle(result, {
4435
4250
  closeCompleted: () => session.client.closeClaudeSessionTurn("completed"),
4436
4251
  closeFailed: (error) => session.client.closeClaudeSessionTurn("failed", { error }),
@@ -6259,6 +6074,7 @@ function startDaemonControlServer({
6259
6074
  onHappySessionWebhook,
6260
6075
  onSessionStateEvent,
6261
6076
  onClaudeAuthFailed,
6077
+ onSessionTurnEvent,
6262
6078
  pushClipboard,
6263
6079
  onTerminalHook,
6264
6080
  setTerminalTitle
@@ -6315,7 +6131,7 @@ function startDaemonControlServer({
6315
6131
  schema: {
6316
6132
  body: z.object({
6317
6133
  sessionId: z.string(),
6318
- event: z.enum(["completed", "needs_input", "auth_failed"]),
6134
+ event: z.enum(["completed", "needs_input", "auth_failed", "turn_started", "turn_ended"]),
6319
6135
  spawnedBy: z.string().optional()
6320
6136
  }),
6321
6137
  response: {
@@ -6331,6 +6147,10 @@ function startDaemonControlServer({
6331
6147
  onClaudeAuthFailed?.(sessionId);
6332
6148
  return { status: "ok" };
6333
6149
  }
6150
+ if (event === "turn_started" || event === "turn_ended") {
6151
+ onSessionTurnEvent?.(sessionId, event);
6152
+ return { status: "ok" };
6153
+ }
6334
6154
  onSessionStateEvent?.(sessionId, event, spawnedBy);
6335
6155
  return { status: "ok" };
6336
6156
  });
@@ -10225,6 +10045,7 @@ async function startDaemon() {
10225
10045
  const { credentials, machineId } = await authAndSetupMachineIfNeeded();
10226
10046
  logger.debug("[DAEMON RUN] Auth and machine setup complete");
10227
10047
  const pidToTrackedSession = /* @__PURE__ */ new Map();
10048
+ const turnActivity = new TurnActivityTracker();
10228
10049
  const sessionIdToFinishedSession = /* @__PURE__ */ new Map();
10229
10050
  let teamWorker;
10230
10051
  const persisted = readPersistedSessions();
@@ -10496,6 +10317,9 @@ async function startDaemon() {
10496
10317
  if (options.resumeCodexThreadId) {
10497
10318
  extraEnv.HAPPY_FORK_CODEX_THREAD_ID = options.resumeCodexThreadId;
10498
10319
  }
10320
+ if (options.importCodexThreadId && UUID_RE.test(options.importCodexThreadId)) {
10321
+ extraEnv.HAPPY_IMPORT_CODEX_THREAD_ID = options.importCodexThreadId;
10322
+ }
10499
10323
  if (options.variant === "assistant") {
10500
10324
  extraEnv.HAPPY_SESSION_VARIANT = "assistant";
10501
10325
  }
@@ -11060,6 +10884,7 @@ async function startDaemon() {
11060
10884
  const onChildExited = (pid) => {
11061
10885
  const session = pidToTrackedSession.get(pid);
11062
10886
  if (session?.happySessionId && (session.spawnedBy === "teams" || teamWorker?.hasSession(session.happySessionId))) teamWorker?.report(session.happySessionId, "exited");
10887
+ if (session?.happySessionId) turnActivity.forget(session.happySessionId);
11063
10888
  if (session?.happySessionId && session.encryption) {
11064
10889
  sessionIdToFinishedSession.set(session.happySessionId, session);
11065
10890
  logger.debug(`[DAEMON RUN] Process PID ${pid} exited, preserved session ${session.happySessionId} for resume`);
@@ -11141,6 +10966,7 @@ async function startDaemon() {
11141
10966
  onHappySessionWebhook,
11142
10967
  onSessionStateEvent,
11143
10968
  onClaudeAuthFailed: (sessionId) => claudeAuthServiceRef?.signalAuthFailed(sessionId),
10969
+ onSessionTurnEvent: (sessionId, event) => turnActivity.apply(sessionId, event),
11144
10970
  pushClipboard: (text) => {
11145
10971
  if (!apiMachineRef) {
11146
10972
  return { delivered: false, truncated: false, totalBytes: 0, error: "daemon is still starting up" };
@@ -11253,7 +11079,10 @@ async function startDaemon() {
11253
11079
  const updateController = createUpdateController({
11254
11080
  policy: () => fetchCliUpdateState(configuration.serverUrl, packageJson.version),
11255
11081
  enabled: async () => ((await readSettings()).cliAutoUpdate ?? "idle") !== "off",
11256
- idle: () => pidToTrackedSession.size === 0 && !apiMachine.hasLiveTerminals(),
11082
+ // B-466: "idle" = no agent turn in flight. Idle wrappers survive a
11083
+ // handover (they talk to the server themselves) and web terminals live
11084
+ // in tmux, so neither is a reason to hold an update.
11085
+ idle: () => !turnActivity.hasActiveTurn(),
11257
11086
  install: installCliSafely,
11258
11087
  publish: (state) => {
11259
11088
  cliUpdateStateRef = state;
@@ -11308,7 +11137,7 @@ async function startDaemon() {
11308
11137
  } catch {
11309
11138
  }
11310
11139
  }
11311
- if (bundleReplaced && !teamWorker?.busy && !updateController.isRunning() && pidToTrackedSession.size === 0 && !apiMachine.hasLiveTerminals()) {
11140
+ if (bundleReplaced && !teamWorker?.busy && !updateController.isRunning() && !turnActivity.hasActiveTurn()) {
11312
11141
  const preflight = await preflightNewBundle(bundlePath);
11313
11142
  if (preflight.action === "hold") {
11314
11143
  if (lastHandoverHold !== preflight.reason) {
@@ -11318,7 +11147,7 @@ async function startDaemon() {
11318
11147
  updateController.holdHandover(preflight.reason);
11319
11148
  return;
11320
11149
  }
11321
- if (teamWorker?.busy || updateController.isRunning() || pidToTrackedSession.size > 0 || apiMachine.hasLiveTerminals()) return;
11150
+ if (teamWorker?.busy || updateController.isRunning() || turnActivity.hasActiveTurn()) return;
11322
11151
  lastHandoverHold = null;
11323
11152
  logger.debug("[DAEMON RUN] Daemon bundle replaced on disk and verified, handing off to new daemon");
11324
11153
  teamWorker?.stop();
@@ -12476,7 +12305,7 @@ function registerSideQuestionHandler(rpc, deps) {
12476
12305
  const retainMs = deps.retainMs ?? SIDE_QUESTION_RETAIN_MS;
12477
12306
  const maxRunMs = deps.maxRunMs ?? SIDE_QUESTION_MAX_RUN_MS;
12478
12307
  const run = deps.run ?? (async (input) => {
12479
- const { query } = await import('./index-D8Q3OhdR.mjs');
12308
+ const { query } = await import('./index-BPnAbcz_.mjs');
12480
12309
  return runSideQuestion(query, input);
12481
12310
  });
12482
12311
  const slots = /* @__PURE__ */ new Map();
@@ -16572,6 +16401,43 @@ async function resumeExistingThread(opts) {
16572
16401
  }
16573
16402
  }
16574
16403
 
16404
+ const IMPORT_CODEX_THREAD_ENV = "HAPPY_IMPORT_CODEX_THREAD_ID";
16405
+ async function importCodexThread(opts) {
16406
+ let forked;
16407
+ try {
16408
+ forked = await opts.client.forkThread({
16409
+ threadId: opts.threadId,
16410
+ cwd: opts.cwd,
16411
+ mcpServers: opts.mcpServers
16412
+ });
16413
+ } catch (error) {
16414
+ const reason = error instanceof Error ? error.message : String(error);
16415
+ throw new Error(`Failed to import Codex thread ${opts.threadId}: ${reason}`);
16416
+ }
16417
+ if (!forked.threadId || forked.threadId === opts.threadId) {
16418
+ throw new Error(`Failed to import Codex thread ${opts.threadId}: Codex did not create an independent copy`);
16419
+ }
16420
+ opts.session.updateMetadata((currentMetadata) => ({
16421
+ ...currentMetadata,
16422
+ codexThreadId: forked.threadId,
16423
+ importedFromCodexThreadId: opts.threadId
16424
+ }));
16425
+ let thread = forked.thread;
16426
+ if (!Array.isArray(thread?.turns)) {
16427
+ thread = (await opts.client.readThread({ threadId: forked.threadId, includeTurns: true })).thread;
16428
+ }
16429
+ const envelopes = mapCodexThreadToSessionEnvelopes(thread);
16430
+ for (const envelope of envelopes) {
16431
+ opts.session.sendSessionProtocolMessage(envelope);
16432
+ }
16433
+ opts.messageBuffer.addMessage(`Imported thread ${trimIdent(opts.threadId)} as ${trimIdent(forked.threadId)}`, "status");
16434
+ opts.session.sendSessionEvent({
16435
+ type: "message",
16436
+ message: `Imported Codex thread ${opts.threadId} (continuing as ${forked.threadId})`
16437
+ });
16438
+ return { threadId: forked.threadId, model: forked.model, replayed: envelopes.length };
16439
+ }
16440
+
16575
16441
  function emitReadyIfIdle({ pending, queueSize, shouldExit, sendReady, notify }) {
16576
16442
  if (shouldExit) {
16577
16443
  return false;
@@ -16786,6 +16652,12 @@ async function runCodex(opts) {
16786
16652
  ...forkedFromMessageId ? { forkedFromMessageId } : {}
16787
16653
  });
16788
16654
  metadata.attachmentKinds = [...CLAUDE_ATTACHMENT_KINDS];
16655
+ const importCodexThreadId = process.env[IMPORT_CODEX_THREAD_ENV];
16656
+ if (importCodexThreadId) {
16657
+ metadata.importedFromCodexThreadId = importCodexThreadId;
16658
+ const importTitle = process.env.HAPPY_IMPORT_TITLE;
16659
+ if (importTitle) metadata.summary = { text: importTitle, updatedAt: Date.now() };
16660
+ }
16789
16661
  const reconnectSessionId = process.env.HAPPY_RECONNECT_SESSION_ID;
16790
16662
  const reconnectKeyBase64 = process.env.HAPPY_RECONNECT_ENCRYPTION_KEY;
16791
16663
  const reconnectVariant = process.env.HAPPY_RECONNECT_ENCRYPTION_VARIANT;
@@ -17304,6 +17176,18 @@ async function runCodex(opts) {
17304
17176
  first = false;
17305
17177
  appendSystemPromptInjected = true;
17306
17178
  }
17179
+ if (!reconnectSessionId && !opts.resumeThreadId && importCodexThreadId) {
17180
+ await importCodexThread({
17181
+ client,
17182
+ session,
17183
+ messageBuffer,
17184
+ threadId: importCodexThreadId,
17185
+ cwd: process.cwd(),
17186
+ mcpServers
17187
+ });
17188
+ first = false;
17189
+ appendSystemPromptInjected = true;
17190
+ }
17307
17191
  const forkCodexThreadId = process.env.HAPPY_FORK_CODEX_THREAD_ID;
17308
17192
  if (!reconnectSessionId && forkCodexThreadId) {
17309
17193
  try {
@@ -17657,7 +17541,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17657
17541
  process.exit(0);
17658
17542
  } else if (subcommand === "install-terminal-hooks") {
17659
17543
  try {
17660
- const { installTerminalHooks, parseTerminalHooksArgs, TERMINAL_HOOKS_HELP } = await import('./installTerminalHooks-DfUGgeyb.mjs');
17544
+ const { installTerminalHooks, parseTerminalHooksArgs, TERMINAL_HOOKS_HELP } = await import('./installTerminalHooks-D2ice1a-.mjs');
17661
17545
  const command = parseTerminalHooksArgs(args.slice(1));
17662
17546
  if (command.action === "help") {
17663
17547
  console.log(TERMINAL_HOOKS_HELP);
@@ -17674,7 +17558,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17674
17558
  }
17675
17559
  } else if (subcommand === "spawn") {
17676
17560
  try {
17677
- const { handleSpawnCommand } = await import('./spawn-DFfHCafP.mjs');
17561
+ const { handleSpawnCommand } = await import('./spawn-C1OqXJNb.mjs');
17678
17562
  await handleSpawnCommand(args.slice(1));
17679
17563
  } catch (error) {
17680
17564
  console.error(chalk.red("Error:"), error instanceof Error ? error.message : "Unknown error");
@@ -17686,7 +17570,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17686
17570
  return;
17687
17571
  } else if (subcommand === "sessions") {
17688
17572
  try {
17689
- const { handleSessionsCommand } = await import('./sessions-DxlC4C4g.mjs');
17573
+ const { handleSessionsCommand } = await import('./sessions-C6EvnC4B.mjs');
17690
17574
  await handleSessionsCommand(args.slice(1));
17691
17575
  } catch (error) {
17692
17576
  console.error(chalk.red("Error:"), error instanceof Error ? error.message : "Unknown error");
@@ -17698,7 +17582,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17698
17582
  return;
17699
17583
  } else if (subcommand === "send") {
17700
17584
  try {
17701
- const { handleSendCommand } = await import('./send-snK_NGAA.mjs');
17585
+ const { handleSendCommand } = await import('./send-KICC_ACz.mjs');
17702
17586
  await handleSendCommand(args.slice(1));
17703
17587
  } catch (error) {
17704
17588
  console.error(chalk.red("Error:"), error instanceof Error ? error.message : "Unknown error");
@@ -17804,9 +17688,9 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17804
17688
  if (geminiSubcommand === "project" && args[2] === "set" && args[3]) {
17805
17689
  const projectId = args[3];
17806
17690
  try {
17807
- const { saveGoogleCloudProjectToConfig } = await import('./config-BRXqgJJj.mjs');
17808
- const { readCredentialsForConfiguredRelay: readCredentialsForConfiguredRelay2 } = await import('./limits-DEsg_gHi.mjs').then(function (n) { return n.W; });
17809
- const { ApiClient: ApiClient2 } = await import('./types-D5EsIAOe.mjs').then(function (n) { return n.a0; });
17691
+ const { saveGoogleCloudProjectToConfig } = await import('./config-BVoHul9V.mjs');
17692
+ const { readCredentialsForConfiguredRelay: readCredentialsForConfiguredRelay2 } = await import('./limits-nhD0Wran.mjs').then(function (n) { return n.X; });
17693
+ const { ApiClient: ApiClient2 } = await import('./types-thyvQB2a.mjs').then(function (n) { return n.ad; });
17810
17694
  let userEmail = void 0;
17811
17695
  try {
17812
17696
  const credentials = await readCredentialsForConfiguredRelay2();
@@ -17837,7 +17721,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17837
17721
  }
17838
17722
  if (geminiSubcommand === "project" && args[2] === "get") {
17839
17723
  try {
17840
- const { readGeminiLocalConfig } = await import('./config-BRXqgJJj.mjs');
17724
+ const { readGeminiLocalConfig } = await import('./config-BVoHul9V.mjs');
17841
17725
  const config = readGeminiLocalConfig();
17842
17726
  if (config.googleCloudProject) {
17843
17727
  console.log(`Current Google Cloud Project: ${config.googleCloudProject}`);
@@ -17877,7 +17761,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17877
17761
  process.exit(0);
17878
17762
  }
17879
17763
  try {
17880
- const { runGemini } = await import('./runGemini-BZ0xXRj-.mjs');
17764
+ const { runGemini } = await import('./runGemini-sa5kAgPe.mjs');
17881
17765
  let startedBy = void 0;
17882
17766
  for (let i = 1; i < args.length; i++) {
17883
17767
  if (args[i] === "--started-by") {
@@ -17907,7 +17791,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17907
17791
  }
17908
17792
  };
17909
17793
  try {
17910
- const { runAcp, resolveAcpAgentConfig } = await import('./index-DQe7ljLR.mjs');
17794
+ const { runAcp, resolveAcpAgentConfig } = await import('./index-BNydKYvS.mjs');
17911
17795
  const parsed = parsePiRunnerArgs(args.slice(1));
17912
17796
  const resolved = resolveAcpAgentConfig(["pi", ...parsed.passthrough]);
17913
17797
  const { credentials } = await authAndSetupMachineIfNeeded();
@@ -17935,7 +17819,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17935
17819
  return;
17936
17820
  } else if (subcommand === "acp") {
17937
17821
  try {
17938
- const { runAcp, resolveAcpAgentConfig } = await import('./index-DQe7ljLR.mjs');
17822
+ const { runAcp, resolveAcpAgentConfig } = await import('./index-BNydKYvS.mjs');
17939
17823
  let startedBy = void 0;
17940
17824
  let verbose = false;
17941
17825
  const acpArgs = [];
@@ -17975,7 +17859,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
17975
17859
  return;
17976
17860
  } else if (subcommand === "openclaw") {
17977
17861
  try {
17978
- const { runOpenClaw } = await import('./runOpenClaw-BcUmnBpW.mjs');
17862
+ const { runOpenClaw } = await import('./runOpenClaw-Bdsq8KBa.mjs');
17979
17863
  let startedBy = void 0;
17980
17864
  let verbose = false;
17981
17865
  let gatewayUrl;
@@ -18026,7 +17910,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
18026
17910
  return;
18027
17911
  } else if (subcommand === "todo") {
18028
17912
  try {
18029
- const { handleTodoCommand } = await import('./todo-CU5cjQZU.mjs');
17913
+ const { handleTodoCommand } = await import('./todo-C-vovA0N.mjs');
18030
17914
  await handleTodoCommand(args.slice(1));
18031
17915
  } catch (error) {
18032
17916
  console.error(JSON.stringify({ error: error instanceof Error ? error.message : "Todo command failed" }));
@@ -18035,7 +17919,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
18035
17919
  return;
18036
17920
  } else if (subcommand === "teams") {
18037
17921
  try {
18038
- const { handleTeamsCommand } = await import('./teams-Cfr-2Yd-.mjs');
17922
+ const { handleTeamsCommand } = await import('./teams-Dm5HGpNz.mjs');
18039
17923
  await handleTeamsCommand(args.slice(1));
18040
17924
  } catch (error) {
18041
17925
  console.error(error instanceof Error ? error.message : "Teams command failed");
@@ -18044,7 +17928,7 @@ Conversation history is preserved on the server, but in-flight tool calls are in
18044
17928
  return;
18045
17929
  } else if (subcommand === "mcp" && args.length === 1) {
18046
17930
  try {
18047
- const { handleMcpCommand } = await import('./mcp-UnjB3I8_.mjs');
17931
+ const { handleMcpCommand } = await import('./mcp-V26C05fN.mjs');
18048
17932
  await handleMcpCommand();
18049
17933
  } catch (error) {
18050
17934
  process.stderr.write(`[very-happy mcp] Fatal: ${error instanceof Error ? error.message : String(error)}
@@ -18406,4 +18290,4 @@ ${chalk.bold("Examples:")}
18406
18290
  }
18407
18291
  }
18408
18292
 
18409
- export { ALLOWED_SPAWN_PERMISSION_MODES as A, hashObject as B, startHappyServer as C, DEFAULT_RECENT_LIMIT as D, registerAgentAttachmentDownloads as E, TitleGenerator as F, GEMINI_MODEL_ENV as G, CLAUDE_ATTACHMENT_KINDS as H, stageClaudeAttachments as I, appendStagedAttachmentsToPrompt as J, BasePermissionHandler as K, writeSessionModeFile as L, MAX_READ_LIMIT as M, normalizeAcpPermissionMode as N, removeSessionModeFile as O, PI_TEAMS_EXTENSION as P, GEMINI_API_KEY_ENV as Q, GOOGLE_API_KEY_ENV as R, SPAWN_AGENTS as S, TEAM_SKILL as T, BaseReasoningProcessor as U, MessageBuffer as V, CHANGE_TITLE_INSTRUCTION as W, sessionWebUrl as a, sanitizeSpawnPermissionMode as b, checkIfDaemonRunningAndCleanupStaleState as c, sendUserMessage as d, listSessions as e, stopSession as f, resolvePermissionRequest as g, archiveSession as h, isValidSpawnOrigin as i, DEFAULT_GEMINI_MODEL as j, setTerminalTitleViaDaemon as k, listAccountSessions as l, registerAssistantSessionTools as m, initialMachineMetadata as n, createSessionMetadata as o, pushClipboardViaDaemon as p, query as q, readSessionTranscript as r, spawnDaemonSession as s, tmuxSupportsSessionEnv as t, setupOfflineReconnection as u, notifyDaemonSessionStarted as v, waitForSessionKey as w, MessageQueue2 as x, registerKillSessionHandler as y, StreamRelay as z };
18293
+ export { ALLOWED_SPAWN_PERMISSION_MODES as A, appendStagedAttachmentsToPrompt as B, CLAUDE_ATTACHMENT_KINDS as C, DEFAULT_RECENT_LIMIT as D, BasePermissionHandler as E, writeSessionModeFile as F, GEMINI_MODEL_ENV as G, normalizeAcpPermissionMode as H, removeSessionModeFile as I, GEMINI_API_KEY_ENV as J, GOOGLE_API_KEY_ENV as K, BaseReasoningProcessor as L, MAX_READ_LIMIT as M, MessageBuffer as N, CHANGE_TITLE_INSTRUCTION as O, PI_TEAMS_EXTENSION as P, SPAWN_AGENTS as S, TEAM_SKILL as T, sanitizeSpawnPermissionMode as a, sendUserMessage as b, listSessions as c, stopSession as d, resolvePermissionRequest as e, archiveSession as f, DEFAULT_GEMINI_MODEL as g, registerAssistantSessionTools as h, isValidSpawnOrigin as i, initialMachineMetadata as j, createSessionMetadata as k, listAccountSessions as l, setupOfflineReconnection as m, MessageQueue2 as n, registerKillSessionHandler as o, StreamRelay as p, query as q, readSessionTranscript as r, sessionWebUrl as s, tmuxSupportsSessionEnv as t, hashObject as u, startHappyServer as v, waitForSessionKey as w, registerAgentAttachmentDownloads as x, TitleGenerator as y, stageClaudeAttachments as z };
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var AcpBackend = require('./AcpBackend-BUoDXZnv.cjs');
4
- var persistence = require('./limits-CfzVummd.cjs');
5
- var AcpSessionManager = require('./AcpSessionManager-DmmA52Ep.cjs');
6
- var api = require('./types-CRxf_3n8.cjs');
7
- var index = require('./index-CRRK5P1r.cjs');
3
+ var AcpBackend = require('./AcpBackend-C0Lq4uoA.cjs');
4
+ var persistence = require('./limits-Dbip6eVO.cjs');
5
+ var AcpSessionManager = require('./AcpSessionManager-DIqByTH7.cjs');
6
+ var api = require('./types-DCVS050m.cjs');
7
+ var index = require('./index-__h-pCTK.cjs');
8
8
  var promises = require('node:fs/promises');
9
9
  var node_crypto = require('node:crypto');
10
10
  var path = require('node:path');
@@ -33,7 +33,7 @@ require('fs');
33
33
  require('node:readline');
34
34
  require('@anthropic-ai/sandbox-runtime');
35
35
  require('expo-server-sdk');
36
- require('./agentGuidance-4HV-BOge.cjs');
36
+ require('./agentGuidance-Dl3apItH.cjs');
37
37
  require('ink');
38
38
  require('react');
39
39
  require('@anthropic-ai/claude-agent-sdk');
@@ -657,7 +657,7 @@ async function runAcp(opts) {
657
657
  session = initialSession;
658
658
  if (response) {
659
659
  try {
660
- await index.notifyDaemonSessionStarted(response.id, metadata, {
660
+ await api.notifyDaemonSessionStarted(response.id, metadata, {
661
661
  encryptionKey: persistence.encodeBase64(response.encryptionKey),
662
662
  encryptionVariant: response.encryptionVariant,
663
663
  seq: response.seq,