@triflux/remote 10.0.1 → 10.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/hub/pipe.mjs +239 -121
  2. package/hub/public/dashboard.html +68 -7
  3. package/hub/server.mjs +2181 -701
  4. package/hub/store-adapter.mjs +101 -37
  5. package/hub/store.mjs +356 -153
  6. package/hub/team/agent-map.json +26 -7
  7. package/hub/team/ansi.mjs +245 -146
  8. package/hub/team/backend.mjs +84 -17
  9. package/hub/team/build-worker-prompt.mjs +42 -0
  10. package/hub/team/check-mcp-hub.mjs +49 -0
  11. package/hub/team/claude-daemon-control.mjs +219 -0
  12. package/hub/team/claude-native-bridge.mjs +784 -0
  13. package/hub/team/claude-session-projection.mjs +65 -0
  14. package/hub/team/cli/commands/attach.mjs +57 -37
  15. package/hub/team/cli/commands/control.mjs +29 -8
  16. package/hub/team/cli/commands/debug.mjs +95 -74
  17. package/hub/team/cli/commands/focus.mjs +80 -53
  18. package/hub/team/cli/commands/interrupt.mjs +18 -6
  19. package/hub/team/cli/commands/kill.mjs +16 -5
  20. package/hub/team/cli/commands/list.mjs +31 -24
  21. package/hub/team/cli/commands/send.mjs +19 -6
  22. package/hub/team/cli/commands/start/index.mjs +154 -33
  23. package/hub/team/cli/commands/start/parse-args.mjs +89 -12
  24. package/hub/team/cli/commands/start/start-headless.mjs +127 -37
  25. package/hub/team/cli/commands/start/start-in-process.mjs +50 -40
  26. package/hub/team/cli/commands/start/start-mux.mjs +122 -73
  27. package/hub/team/cli/commands/start/start-wt.mjs +86 -69
  28. package/hub/team/cli/commands/status.mjs +43 -14
  29. package/hub/team/cli/commands/stop.mjs +11 -4
  30. package/hub/team/cli/commands/task.mjs +8 -3
  31. package/hub/team/cli/commands/tasks.mjs +13 -13
  32. package/hub/team/cli/index.mjs +2 -2
  33. package/hub/team/cli/manifest.mjs +38 -8
  34. package/hub/team/cli/render.mjs +52 -30
  35. package/hub/team/cli/services/attach-fallback.mjs +74 -54
  36. package/hub/team/cli/services/hub-client.mjs +45 -17
  37. package/hub/team/cli/services/member-selector.mjs +37 -30
  38. package/hub/team/cli/services/native-control.mjs +144 -116
  39. package/hub/team/cli/services/runtime-mode.mjs +55 -1
  40. package/hub/team/cli/services/state-store.mjs +66 -9
  41. package/hub/team/cli/services/task-model.mjs +40 -30
  42. package/hub/team/codex-review.mjs +521 -0
  43. package/hub/team/conductor-mesh-bridge.mjs +25 -24
  44. package/hub/team/conductor-registry.mjs +121 -0
  45. package/hub/team/conductor.mjs +1379 -671
  46. package/hub/team/consensus-meta.mjs +176 -0
  47. package/hub/team/dashboard-anchor.mjs +4 -5
  48. package/hub/team/dashboard-layout.mjs +3 -1
  49. package/hub/team/dashboard-open.mjs +21 -119
  50. package/hub/team/dashboard.mjs +76 -28
  51. package/hub/team/event-log.mjs +18 -10
  52. package/hub/team/execution-mode.mjs +241 -0
  53. package/hub/team/extract-completion-payload.mjs +110 -0
  54. package/hub/team/git-preflight.mjs +286 -0
  55. package/hub/team/handoff.mjs +49 -18
  56. package/hub/team/headless-bridge-session.mjs +17 -0
  57. package/hub/team/headless.mjs +2065 -1156
  58. package/hub/team/health-probe.mjs +232 -69
  59. package/hub/team/launcher-template.mjs +23 -13
  60. package/hub/team/lead-control.mjs +91 -4
  61. package/hub/team/mcp-selector.mjs +145 -0
  62. package/hub/team/native-supervisor.mjs +90 -26
  63. package/hub/team/native.mjs +74 -35
  64. package/hub/team/nativeProxy.mjs +184 -113
  65. package/hub/team/notify.mjs +147 -78
  66. package/hub/team/orchestrator.mjs +173 -161
  67. package/hub/team/pane.mjs +43 -15
  68. package/hub/team/process-cleanup.mjs +69 -25
  69. package/hub/team/psmux.mjs +1067 -264
  70. package/hub/team/recovery-store.mjs +149 -0
  71. package/hub/team/remote-probe.mjs +69 -53
  72. package/hub/team/remote-session.mjs +131 -59
  73. package/hub/team/remote-watcher.mjs +62 -34
  74. package/hub/team/retry-state-machine.mjs +267 -0
  75. package/hub/team/routing.mjs +51 -25
  76. package/hub/team/runtime-strategy.mjs +200 -0
  77. package/hub/team/schemas/worker-completion.json +39 -0
  78. package/hub/team/sentinel-capture.mjs +127 -0
  79. package/hub/team/session-sync.mjs +153 -6
  80. package/hub/team/session.mjs +605 -611
  81. package/hub/team/shared.mjs +13 -13
  82. package/hub/team/staleState.mjs +72 -30
  83. package/hub/team/swarm-cli.mjs +390 -0
  84. package/hub/team/swarm-hypervisor.mjs +1526 -198
  85. package/hub/team/swarm-intent.mjs +216 -0
  86. package/hub/team/swarm-locks.mjs +140 -25
  87. package/hub/team/swarm-planner.mjs +121 -21
  88. package/hub/team/swarm-preflight.mjs +317 -0
  89. package/hub/team/swarm-reconciler.mjs +128 -23
  90. package/hub/team/synapse-cli.mjs +458 -0
  91. package/hub/team/synapse-http.mjs +60 -0
  92. package/hub/team/synapse-registry.mjs +329 -0
  93. package/hub/team/terminal-opener.mjs +216 -0
  94. package/hub/team/tui-core.mjs +288 -0
  95. package/hub/team/tui-lite.mjs +234 -146
  96. package/hub/team/tui-remote-adapter.mjs +21 -37
  97. package/hub/team/tui-synapse.mjs +223 -0
  98. package/hub/team/tui-viewer.mjs +104 -45
  99. package/hub/team/tui-widgets.mjs +262 -0
  100. package/hub/team/tui.mjs +936 -449
  101. package/hub/team/worker-completion-validator.mjs +84 -0
  102. package/hub/team/worker-sandbox.mjs +93 -0
  103. package/hub/team/worker-signal.mjs +263 -0
  104. package/hub/team/worker-signal.types.d.ts +52 -0
  105. package/hub/team/worktree-lifecycle.mjs +518 -64
  106. package/hub/team/wt-manager.mjs +297 -26
  107. package/hub/tools.mjs +474 -252
  108. package/hub/tray.mjs +411 -368
  109. package/hub/workers/claude-worker.mjs +162 -118
  110. package/hub/workers/codex-app-server-worker.mjs +1015 -0
  111. package/hub/workers/codex-mcp.mjs +724 -507
  112. package/hub/workers/delegator-mcp.mjs +663 -337
  113. package/hub/workers/factory.mjs +100 -21
  114. package/hub/workers/gemini-worker.mjs +179 -86
  115. package/hub/workers/interface.mjs +23 -2
  116. package/hub/workers/lib/jsonrpc-stdio.mjs +463 -0
  117. package/hub/workers/worker-utils.mjs +22 -16
  118. package/package.json +4 -3
  119. package/scripts/lib/agent-json.mjs +27 -0
  120. package/scripts/lib/async.mjs +174 -0
  121. package/scripts/lib/claudemd-scanner.mjs +223 -0
  122. package/scripts/lib/cli-agy.mjs +62 -0
  123. package/scripts/lib/cli-claude.mjs +78 -0
  124. package/scripts/lib/cli-codex.mjs +199 -0
  125. package/scripts/lib/cli-gemini.mjs +67 -0
  126. package/scripts/lib/codex-recovery.sh +50 -0
  127. package/scripts/lib/context.mjs +67 -0
  128. package/scripts/lib/cross-review-utils.mjs +59 -0
  129. package/scripts/lib/doctor-env-checks.mjs +121 -0
  130. package/scripts/lib/dynamic-route-cli.mjs +107 -0
  131. package/scripts/lib/env-probe.mjs +269 -0
  132. package/scripts/lib/env.mjs +14 -0
  133. package/scripts/lib/gemini-profiles.mjs +119 -0
  134. package/scripts/lib/handoff.mjs +187 -0
  135. package/scripts/lib/hook-utils.mjs +16 -0
  136. package/scripts/lib/hub.mjs +48 -0
  137. package/scripts/lib/keyword-rules.mjs +195 -0
  138. package/scripts/lib/logger.mjs +105 -0
  139. package/scripts/lib/mcp-filter.mjs +883 -0
  140. package/scripts/lib/mcp-gateway-servers.mjs +70 -0
  141. package/scripts/lib/mcp-guard-engine.mjs +2120 -0
  142. package/scripts/lib/mcp-health.mjs +773 -0
  143. package/scripts/lib/mcp-manifest.mjs +89 -0
  144. package/scripts/lib/mcp-server-catalog.mjs +355 -0
  145. package/scripts/lib/pid.mjs +63 -0
  146. package/scripts/lib/process-utils.mjs +26 -0
  147. package/scripts/lib/psmux-info.mjs +179 -0
  148. package/scripts/lib/quota.mjs +47 -0
  149. package/scripts/lib/remote-spawn-transfer.mjs +226 -0
  150. package/scripts/lib/skill-state.mjs +220 -0
  151. package/scripts/lib/skill-template.mjs +375 -0
  152. package/scripts/lib/team.mjs +75 -0
  153. package/scripts/lib/timeout.mjs +66 -0
  154. package/scripts/lib/tmp.mjs +26 -0
  155. package/scripts/lib/toml.mjs +113 -0
@@ -1,17 +1,49 @@
1
1
  // hub/team/backend.mjs — CLI 백엔드 추상화 레이어
2
- // 각 CLI(codex/gemini/claude)의 명령 빌드 로직을 클래스로 캡슐화한다.
2
+ // 각 CLI(codex/gemini/claude/antigravity)의 명령 빌드 로직을 클래스로 캡슐화한다.
3
3
  // v7.2.2
4
+ import { writeFileSync } from "node:fs";
4
5
  import { createRequire } from "node:module";
5
6
 
6
7
  import { buildExecArgs } from "@triflux/core/hub/codex-adapter.mjs";
8
+ import { IS_WINDOWS } from "@triflux/core/hub/platform.mjs";
9
+
10
+ // --yolo is required: without it gemini waits on stdin for tool-call approval
11
+ // even when stdin is redirected, producing a 0-byte 90s+ silent hang.
12
+ // execution-mode.mjs:buildSpawnSpecForMode enforces the same flag.
13
+ export function buildGeminiCommand(prompt, resultFile, { isWindows } = {}) {
14
+ if (isWindows) {
15
+ return `$null | gemini --yolo --prompt ${prompt} --output-format text > '${resultFile}' 2>'${resultFile}.err'`;
16
+ }
17
+ return `gemini --yolo --prompt ${prompt} --output-format text > '${resultFile}' 2>'${resultFile}.err' < /dev/null`;
18
+ }
19
+
20
+ export function buildAntigravityCommand(
21
+ prompt,
22
+ resultFile,
23
+ { isWindows } = {},
24
+ ) {
25
+ // Persist prompt to a sibling file so the shell never interpolates raw
26
+ // prompt content. Without this the Unix branch let `$()`, backticks, `\\`,
27
+ // and `"` reach the shell verbatim (P1: shell injection).
28
+ const promptFile = `${resultFile}.prompt`;
29
+ writeFileSync(promptFile, prompt);
30
+ if (isWindows) {
31
+ return `Get-Content -Raw '${promptFile}' | agy --print --dangerously-skip-permissions > '${resultFile}' 2>'${resultFile}.err'`;
32
+ }
33
+ return `agy --print --dangerously-skip-permissions < '${promptFile}' > '${resultFile}' 2>'${resultFile}.err'`;
34
+ }
7
35
 
8
36
  const _require = createRequire(import.meta.url);
9
37
 
10
38
  // ── 백엔드 클래스 ──────────────────────────────────────────────────────────
11
39
 
12
40
  export class CodexBackend {
13
- name() { return "codex"; }
14
- command() { return "codex"; }
41
+ name() {
42
+ return "codex";
43
+ }
44
+ command() {
45
+ return "codex";
46
+ }
15
47
 
16
48
  /**
17
49
  * @param {string} prompt — 프롬프트 (프롬프트 파일 경로가 아닌 PowerShell 표현식)
@@ -23,44 +55,79 @@ export class CodexBackend {
23
55
  return buildExecArgs({ prompt, resultFile, ...opts });
24
56
  }
25
57
 
26
- env() { return {}; }
58
+ env() {
59
+ return {};
60
+ }
27
61
  }
28
62
 
29
63
  export class GeminiBackend {
30
- name() { return "gemini"; }
31
- command() { return "gemini"; }
64
+ name() {
65
+ return "gemini";
66
+ }
67
+ command() {
68
+ return "gemini";
69
+ }
32
70
 
33
71
  buildArgs(prompt, resultFile, opts = {}) {
34
- return `gemini --prompt ${prompt} --output-format text > '${resultFile}' 2>'${resultFile}.err'`;
72
+ return buildGeminiCommand(prompt, resultFile, { isWindows: IS_WINDOWS });
35
73
  }
36
74
 
37
- env() { return {}; }
75
+ env() {
76
+ return {};
77
+ }
38
78
  }
39
79
 
40
80
  export class ClaudeBackend {
41
- name() { return "claude"; }
42
- command() { return "claude"; }
81
+ name() {
82
+ return "claude";
83
+ }
84
+ command() {
85
+ return "claude";
86
+ }
43
87
 
44
88
  buildArgs(prompt, resultFile, opts = {}) {
45
89
  return `claude --print ${prompt} --output-format text > '${resultFile}' 2>&1`;
46
90
  }
47
91
 
48
- env() { return {}; }
92
+ env() {
93
+ return {};
94
+ }
95
+ }
96
+
97
+ export class AntigravityBackend {
98
+ name() {
99
+ return "antigravity";
100
+ }
101
+ command() {
102
+ return "agy";
103
+ }
104
+
105
+ buildArgs(prompt, resultFile, opts = {}) {
106
+ return buildAntigravityCommand(prompt, resultFile, {
107
+ isWindows: IS_WINDOWS,
108
+ ...opts,
109
+ });
110
+ }
111
+
112
+ env() {
113
+ return {};
114
+ }
49
115
  }
50
116
 
51
117
  // ── 레지스트리 ─────────────────────────────────────────────────────────────
52
118
 
53
- /** @type {Map<string, CodexBackend|GeminiBackend|ClaudeBackend>} */
119
+ /** @type {Map<string, CodexBackend|GeminiBackend|ClaudeBackend|AntigravityBackend>} */
54
120
  const backends = new Map([
55
- ["codex", new CodexBackend()],
121
+ ["codex", new CodexBackend()],
56
122
  ["gemini", new GeminiBackend()],
57
123
  ["claude", new ClaudeBackend()],
124
+ ["antigravity", new AntigravityBackend()],
58
125
  ]);
59
126
 
60
127
  /**
61
128
  * 백엔드 이름으로 조회한다.
62
- * @param {string} name — "codex" | "gemini" | "claude"
63
- * @returns {CodexBackend|GeminiBackend|ClaudeBackend}
129
+ * @param {string} name — "codex" | "gemini" | "claude" | "antigravity"
130
+ * @returns {CodexBackend|GeminiBackend|ClaudeBackend|AntigravityBackend}
64
131
  * @throws {Error} 등록되지 않은 이름
65
132
  */
66
133
  export function getBackend(name) {
@@ -73,7 +140,7 @@ export function getBackend(name) {
73
140
  * 에이전트명 또는 CLI명을 Backend로 해석한다.
74
141
  * agent-map.json을 통해 에이전트명 → CLI명으로 변환 후 레지스트리에서 조회한다.
75
142
  * @param {string} agentOrCli — "executor", "codex", "designer" 등
76
- * @returns {CodexBackend|GeminiBackend|ClaudeBackend}
143
+ * @returns {CodexBackend|GeminiBackend|ClaudeBackend|AntigravityBackend}
77
144
  */
78
145
  export function getBackendForAgent(agentOrCli) {
79
146
  const agentMap = _require("./agent-map.json");
@@ -83,7 +150,7 @@ export function getBackendForAgent(agentOrCli) {
83
150
 
84
151
  /**
85
152
  * 등록된 모든 백엔드를 반환한다.
86
- * @returns {Array<CodexBackend|GeminiBackend|ClaudeBackend>}
153
+ * @returns {Array<CodexBackend|GeminiBackend|ClaudeBackend|AntigravityBackend>}
87
154
  */
88
155
  export function listBackends() {
89
156
  return Array.from(backends.values());
@@ -0,0 +1,42 @@
1
+ // hub/team/build-worker-prompt.mjs — append Completion Protocol to PRD prompt (#125)
2
+ //
3
+ // swarm-hypervisor injects a Completion Protocol appendix into every worker
4
+ // prompt so that workers emit a sentinel-framed JSON payload conductor.mjs can
5
+ // reliably capture (see sentinel-capture.mjs and extract-completion-payload.mjs).
6
+ //
7
+ // Pure module — no I/O — so the appendix and merge logic can be unit-tested
8
+ // without spawning conductors.
9
+
10
+ import { SENTINEL_BEGIN, SENTINEL_END } from "./sentinel-capture.mjs";
11
+
12
+ export const COMPLETION_PROTOCOL_APPENDIX = `
13
+
14
+ ## Completion Protocol (자동 삽입됨)
15
+ <!-- swarm hypervisor 가 이 섹션을 worker prompt 에 자동 주입합니다.
16
+ PRD 작성자는 이 섹션을 수정하지 마세요.
17
+ 상세: hub/team/build-worker-prompt.mjs / sentinel-capture.mjs (#125). -->
18
+
19
+ 작업의 마지막 단계로, stdout 에 다음 형식의 완료 payload 를 정확히 한 번 출력하라:
20
+
21
+ ${SENTINEL_BEGIN}
22
+ {"shard":"<shard name>","status":"ok","commits_made":[{"sha":"<40-char full sha>","message":"<commit msg>"}]}
23
+ ${SENTINEL_END}
24
+
25
+ 규약:
26
+ - 두 sentinel 마커는 각자 자기 줄에 단독으로 출력 (앞뒤 newline)
27
+ - 마커 사이 본문은 단일 JSON object (배열/primitive 금지)
28
+ - commits_made 가 비어 있어도 됨 (no-op shard)
29
+ - 마커 쌍은 stdout 에 정확히 한 번만 출력해야 함. 재emit 시 conductor 는 첫 BEGIN..END 한 쌍만 채택하며, 이후 stdout 은 무시한다.
30
+ - ${SENTINEL_BEGIN} 만 출력하고 ${SENTINEL_END} 누락 시 conductor 가 truncation 으로 명확히 reject
31
+ `;
32
+
33
+ /**
34
+ * Append the Completion Protocol section to a PRD prompt.
35
+ *
36
+ * @param {string|null|undefined} prdPrompt — original PRD body
37
+ * @returns {string} prompt with appendix
38
+ */
39
+ export function buildWorkerPrompt(prdPrompt) {
40
+ const body = typeof prdPrompt === "string" ? prdPrompt : "";
41
+ return body + COMPLETION_PROTOCOL_APPENDIX;
42
+ }
@@ -0,0 +1,49 @@
1
+ // hub/team/check-mcp-hub.mjs — health-probe L2 용 hub /health ping 체커.
2
+ // health-probe.mjs 의 checkMcp 로 주입되어 `mcp_initializing` state 판정에 사용.
3
+ // hub /health 가 200 이면 OK (MCP transport 인프라 살아있음), 그 외는 fail.
4
+
5
+ const DEFAULT_HUB_URL = "http://127.0.0.1:27888";
6
+ const DEFAULT_TIMEOUT_MS = 3000;
7
+
8
+ function resolveHubHealthUrl(hubUrl) {
9
+ const base = hubUrl || process.env.TFX_HUB_URL || DEFAULT_HUB_URL;
10
+ // `/mcp` suffix 제거 (triflux convention — bridge.mjs:54, hub-client.mjs,
11
+ // lead-control.mjs, session-sync.mjs 전부 TFX_HUB_URL 을 MCP transport URL
12
+ // 로 쓰고 base URL 이 필요할 때 `/mcp$` 를 strip 한다). 제거하지 않으면
13
+ // `.../mcp/health` 가 되어 hub 가 404 로 응답 → L2 영구 fail → heartbeat
14
+ // 이 지속적으로 `mcp_initializing` 로 grace — #173 Codex P2 review.
15
+ return base.replace(/\/mcp\/?$/, "").replace(/\/+$/, "") + "/health";
16
+ }
17
+
18
+ /**
19
+ * Hub /health 기반 L2 checker factory.
20
+ * @param {object} [opts]
21
+ * @param {string} [opts.hubUrl] — override. 미지정 시 TFX_HUB_URL env 또는 default.
22
+ * @param {number} [opts.timeoutMs=3000] — fetch timeout (ms).
23
+ * @param {typeof fetch} [opts.fetchFn] — fetch 오버라이드 (테스트용).
24
+ * @returns {() => Promise<boolean>} — true = hub healthy, false = degraded/down/timeout.
25
+ */
26
+ export function createHubHealthChecker(opts = {}) {
27
+ const url = resolveHubHealthUrl(opts.hubUrl);
28
+ const timeoutMs = Number.isFinite(opts.timeoutMs)
29
+ ? opts.timeoutMs
30
+ : DEFAULT_TIMEOUT_MS;
31
+ const fetchFn = opts.fetchFn || globalThis.fetch;
32
+
33
+ return async function checkMcpHubHealth() {
34
+ if (typeof fetchFn !== "function") return false;
35
+ const controller = new AbortController();
36
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
37
+ try {
38
+ const res = await fetchFn(url, {
39
+ method: "GET",
40
+ signal: controller.signal,
41
+ });
42
+ return res.ok === true;
43
+ } catch {
44
+ return false;
45
+ } finally {
46
+ clearTimeout(timer);
47
+ }
48
+ };
49
+ }
@@ -0,0 +1,219 @@
1
+ import crypto from "node:crypto";
2
+ import net from "node:net";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ export function resolveClaudeConfigDir(env = process.env) {
7
+ if (env.CLAUDE_CONFIG_DIR) return path.resolve(env.CLAUDE_CONFIG_DIR);
8
+ return path.join(os.homedir(), ".claude");
9
+ }
10
+
11
+ export function deriveClaudeDaemonPaths({
12
+ configDir = resolveClaudeConfigDir(),
13
+ uid = typeof process.getuid === "function" ? process.getuid() : 0,
14
+ tmpRoot = "/tmp",
15
+ } = {}) {
16
+ const resolvedConfigDir = path.resolve(configDir);
17
+ const hash = crypto
18
+ .createHash("sha256")
19
+ .update(resolvedConfigDir)
20
+ .digest("hex")
21
+ .slice(0, 8);
22
+ const daemonDir = path.join(tmpRoot, `cc-daemon-${uid}`, hash);
23
+ return {
24
+ configDir: resolvedConfigDir,
25
+ hash,
26
+ daemonDir,
27
+ controlSock: path.join(daemonDir, "control.sock"),
28
+ rosterPath: path.join(resolvedConfigDir, "daemon", "roster.json"),
29
+ sessionsDir: path.join(resolvedConfigDir, "sessions"),
30
+ };
31
+ }
32
+
33
+ export function readFirstJsonLine(text) {
34
+ const line = String(text)
35
+ .split("\n")
36
+ .find((entry) => entry.trim().length > 0);
37
+ if (!line) throw new Error("empty daemon response");
38
+ return JSON.parse(line);
39
+ }
40
+
41
+ export function sendClaudeControlRequest(
42
+ sockPath,
43
+ request,
44
+ { timeoutMs = 6000 } = {},
45
+ ) {
46
+ return new Promise((resolve, reject) => {
47
+ const socket = net.connect(sockPath);
48
+ let settled = false;
49
+ let data = "";
50
+ const finish = (error, value) => {
51
+ if (settled) return;
52
+ settled = true;
53
+ socket.destroy();
54
+ if (error) reject(error);
55
+ else resolve(value);
56
+ };
57
+
58
+ socket.setTimeout(timeoutMs, () => {
59
+ finish(
60
+ new Error(`Timed out waiting for Claude daemon response: ${sockPath}`),
61
+ );
62
+ });
63
+ socket.on("error", finish);
64
+ socket.on("connect", () => {
65
+ socket.write(`${JSON.stringify(request)}\n`);
66
+ });
67
+ socket.on("data", (chunk) => {
68
+ data += chunk.toString("utf8");
69
+ if (!data.includes("\n")) return;
70
+ try {
71
+ finish(null, readFirstJsonLine(data));
72
+ } catch (error) {
73
+ finish(error);
74
+ }
75
+ });
76
+ socket.on("close", () => {
77
+ if (settled) return;
78
+ if (data.length === 0) {
79
+ finish(
80
+ new Error("Claude daemon closed control socket without a response"),
81
+ );
82
+ return;
83
+ }
84
+ try {
85
+ finish(null, readFirstJsonLine(data));
86
+ } catch (error) {
87
+ finish(error);
88
+ }
89
+ });
90
+ });
91
+ }
92
+
93
+ export function buildDaemonExecDispatchPayload({
94
+ short = crypto.randomBytes(4).toString("hex"),
95
+ sessionId,
96
+ cwd = process.cwd(),
97
+ command,
98
+ name,
99
+ createdAt = Date.now(),
100
+ cols = 120,
101
+ rows = 40,
102
+ } = {}) {
103
+ if (!command) throw new Error("command is required");
104
+ if (!name) throw new Error("name is required");
105
+ const uuid = crypto.randomUUID();
106
+ const resolvedSessionId = sessionId || `${short}${uuid.slice(8)}`;
107
+ return {
108
+ proto: 1,
109
+ short,
110
+ sessionId: resolvedSessionId,
111
+ createdAt,
112
+ source: "shell",
113
+ cwd,
114
+ launch: {
115
+ mode: "exec",
116
+ cmd: "/bin/zsh",
117
+ args: ["-lc", command],
118
+ },
119
+ env: {},
120
+ isolation: "none",
121
+ respawnFlags: [],
122
+ seed: {
123
+ intent: name,
124
+ name,
125
+ },
126
+ cols,
127
+ rows,
128
+ };
129
+ }
130
+
131
+ export function findDaemonJobByShort(listResponse, short) {
132
+ if (!Array.isArray(listResponse?.jobs)) return null;
133
+ return listResponse.jobs.find((job) => job?.short === short) || null;
134
+ }
135
+
136
+ export function findDaemonJobBySessionId(listResponse, sessionId) {
137
+ if (!Array.isArray(listResponse?.jobs)) return null;
138
+ const expected = String(sessionId || "");
139
+ if (!expected) return null;
140
+ return (
141
+ listResponse.jobs.find((job) => {
142
+ const candidate =
143
+ job?.sessionId ??
144
+ job?.session_id ??
145
+ job?.dispatch?.sessionId ??
146
+ job?.d?.sessionId ??
147
+ "";
148
+ return String(candidate) === expected;
149
+ }) || null
150
+ );
151
+ }
152
+
153
+ export async function waitForDaemonJobPid(
154
+ controlSock,
155
+ short,
156
+ { timeoutMs = 5000 } = {},
157
+ ) {
158
+ const deadline = Date.now() + timeoutMs;
159
+ while (Date.now() < deadline) {
160
+ const list = await sendClaudeControlRequest(controlSock, {
161
+ proto: 1,
162
+ op: "list",
163
+ });
164
+ const job = findDaemonJobByShort(list, short);
165
+ if (Number.isInteger(job?.pid) && job.pid > 0) return job;
166
+ await new Promise((resolve) => setTimeout(resolve, 100));
167
+ }
168
+ throw new Error(`Claude daemon dispatch did not expose a pid for ${short}`);
169
+ }
170
+
171
+ export async function killDaemonJob(controlSock, short) {
172
+ return await sendClaudeControlRequest(controlSock, {
173
+ proto: 1,
174
+ op: "kill",
175
+ short,
176
+ });
177
+ }
178
+
179
+ export async function sendKillBySessionId({
180
+ daemonPaths,
181
+ sessionId,
182
+ timeoutMs = 6000,
183
+ } = {}) {
184
+ const controlSock = daemonPaths?.controlSock;
185
+ if (!controlSock || !sessionId) {
186
+ return { ok: true, killed: false, reason: "missing_target" };
187
+ }
188
+
189
+ try {
190
+ const list = await sendClaudeControlRequest(
191
+ controlSock,
192
+ {
193
+ proto: 1,
194
+ op: "list",
195
+ },
196
+ { timeoutMs },
197
+ );
198
+ const job = findDaemonJobBySessionId(list, sessionId);
199
+ if (!job?.short) {
200
+ return { ok: true, killed: false, reason: "not_found" };
201
+ }
202
+ return await sendClaudeControlRequest(
203
+ controlSock,
204
+ {
205
+ proto: 1,
206
+ op: "kill",
207
+ short: job.short,
208
+ },
209
+ { timeoutMs },
210
+ );
211
+ } catch (error) {
212
+ return {
213
+ ok: false,
214
+ killed: false,
215
+ reason: "control_unavailable",
216
+ error: error?.message || String(error),
217
+ };
218
+ }
219
+ }