@cocorograph/hub-agent 0.5.3 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/main.mjs +76 -1
- package/src/tmux.mjs +89 -4
- package/src/ws-client.mjs +4 -1
package/package.json
CHANGED
package/src/main.mjs
CHANGED
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
*
|
|
11
11
|
* 仕様書: ナレッジ/インフラ/cockpit-hub-hosted-integration-spec (id=6080)
|
|
12
12
|
*/
|
|
13
|
+
import { readFile } from "node:fs/promises"
|
|
14
|
+
import os from "node:os"
|
|
15
|
+
import path from "node:path"
|
|
16
|
+
|
|
13
17
|
import pino from "pino"
|
|
14
18
|
|
|
15
19
|
import { readConfig } from "./config.mjs"
|
|
@@ -20,6 +24,7 @@ import { listSkills } from "./skills.mjs"
|
|
|
20
24
|
import { listSessionStates } from "./state.mjs"
|
|
21
25
|
import {
|
|
22
26
|
createSession as createTmuxSession,
|
|
27
|
+
createWorktreeDir,
|
|
23
28
|
execTmux,
|
|
24
29
|
killManySessions,
|
|
25
30
|
killSession as killTmuxSession,
|
|
@@ -29,6 +34,24 @@ import { getSessionUsages, getUsage } from "./usage.mjs"
|
|
|
29
34
|
|
|
30
35
|
const logger = pino({ name: "hub-agent" })
|
|
31
36
|
|
|
37
|
+
const BUNDLE_MANIFEST_PATH =
|
|
38
|
+
process.env.HUB_BUNDLE_MANIFEST ||
|
|
39
|
+
path.join(os.homedir(), ".claude", "scripts", "manifest.json")
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* `~/.claude/scripts/manifest.json` から Hub AI bundle の version を読む。
|
|
43
|
+
* 未セットアップなら null を返す。
|
|
44
|
+
*/
|
|
45
|
+
async function readBundleVersion() {
|
|
46
|
+
try {
|
|
47
|
+
const text = await readFile(BUNDLE_MANIFEST_PATH, "utf-8")
|
|
48
|
+
const data = JSON.parse(text)
|
|
49
|
+
return typeof data?.version === "string" ? data.version : null
|
|
50
|
+
} catch {
|
|
51
|
+
return null
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
32
55
|
export async function startDaemon({ version, ptyModule } = {}) {
|
|
33
56
|
const config = await readConfig()
|
|
34
57
|
if (!config) {
|
|
@@ -45,7 +68,12 @@ export async function startDaemon({ version, ptyModule } = {}) {
|
|
|
45
68
|
const resolvedPty = ptyModule || (await import("node-pty"))
|
|
46
69
|
const ptyBridge = new PtyBridge({ ptyModule: resolvedPty, logger, plugins })
|
|
47
70
|
|
|
48
|
-
const
|
|
71
|
+
const bundleVersion = await readBundleVersion()
|
|
72
|
+
if (bundleVersion) {
|
|
73
|
+
logger.info({ bundleVersion }, "hub bundle version detected")
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const client = new WsClient(config, { logger, version, bundleVersion })
|
|
49
77
|
|
|
50
78
|
// EventEmitter の 'error' は listener が無いと process が落ちる。
|
|
51
79
|
// ws-client は close 側で reconnect を予約しているので、ここでは log だけ。
|
|
@@ -286,6 +314,53 @@ async function dispatch(msg, ctx) {
|
|
|
286
314
|
}
|
|
287
315
|
return
|
|
288
316
|
}
|
|
317
|
+
case "worktree.create": {
|
|
318
|
+
// body: { request_id, dir, branch, claude_cmd? }
|
|
319
|
+
const dir = (msg.dir || "").trim()
|
|
320
|
+
const branch = (msg.branch || "").trim()
|
|
321
|
+
if (!dir || !branch) {
|
|
322
|
+
ctx.client.send({
|
|
323
|
+
type: "worktree.create.result",
|
|
324
|
+
request_id: msg.request_id,
|
|
325
|
+
ok: false,
|
|
326
|
+
error: "dir and branch required",
|
|
327
|
+
})
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
if (!/^[A-Za-z0-9._\-/]+$/.test(branch) || branch.startsWith("-")) {
|
|
331
|
+
ctx.client.send({
|
|
332
|
+
type: "worktree.create.result",
|
|
333
|
+
request_id: msg.request_id,
|
|
334
|
+
ok: false,
|
|
335
|
+
error: "invalid branch name",
|
|
336
|
+
})
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
try {
|
|
340
|
+
const { wtName, wtPath, createdBranch } = await createWorktreeDir(dir, branch)
|
|
341
|
+
// worktree dir で tmux session を作成 (claude_cmd は createSession の default)
|
|
342
|
+
await createTmuxSession(wtName, wtPath, {
|
|
343
|
+
claudeCmd: typeof msg.claude_cmd === "string" ? msg.claude_cmd : undefined,
|
|
344
|
+
})
|
|
345
|
+
ctx.client.send({
|
|
346
|
+
type: "worktree.create.result",
|
|
347
|
+
request_id: msg.request_id,
|
|
348
|
+
ok: true,
|
|
349
|
+
wt_name: wtName,
|
|
350
|
+
wt_path: wtPath,
|
|
351
|
+
branch,
|
|
352
|
+
created_branch: createdBranch,
|
|
353
|
+
})
|
|
354
|
+
} catch (err) {
|
|
355
|
+
ctx.client.send({
|
|
356
|
+
type: "worktree.create.result",
|
|
357
|
+
request_id: msg.request_id,
|
|
358
|
+
ok: false,
|
|
359
|
+
error: err.message,
|
|
360
|
+
})
|
|
361
|
+
}
|
|
362
|
+
return
|
|
363
|
+
}
|
|
289
364
|
case "tmux.kill_session": {
|
|
290
365
|
const names = Array.isArray(msg.session_names)
|
|
291
366
|
? msg.session_names
|
package/src/tmux.mjs
CHANGED
|
@@ -20,6 +20,7 @@ import path from "node:path"
|
|
|
20
20
|
import { promisify } from "node:util"
|
|
21
21
|
|
|
22
22
|
import { detectSessionState } from "./state.mjs"
|
|
23
|
+
import { getSessionUsages } from "./usage.mjs"
|
|
23
24
|
|
|
24
25
|
const execFileP = promisify(execFile)
|
|
25
26
|
|
|
@@ -32,6 +33,72 @@ function sanitizeTmuxName(s) {
|
|
|
32
33
|
return s.replace(/[.:]/g, "-")
|
|
33
34
|
}
|
|
34
35
|
|
|
36
|
+
/**
|
|
37
|
+
* git branch 名から worktree dir 名 (= tmux session 名) を導出する。
|
|
38
|
+
* 例: "feature/multi-area" -> "feature-multi-area"
|
|
39
|
+
* "fix.typo:v2" -> "fix-typo-v2"
|
|
40
|
+
*
|
|
41
|
+
* 移植元: D00000_cockpit/webapp/lib/worktrees.ts (sanitizeBranchToWtName)
|
|
42
|
+
*/
|
|
43
|
+
export function sanitizeBranchToWtName(branch) {
|
|
44
|
+
return branch
|
|
45
|
+
.replace(/[\s/:.]+/g, "-")
|
|
46
|
+
.replace(/[^A-Za-z0-9_-]/g, "")
|
|
47
|
+
.replace(/^-+|-+$/g, "")
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function branchExists(repoDir, branch) {
|
|
51
|
+
try {
|
|
52
|
+
await execFileP("git", [
|
|
53
|
+
"-C",
|
|
54
|
+
repoDir,
|
|
55
|
+
"show-ref",
|
|
56
|
+
"--verify",
|
|
57
|
+
"--quiet",
|
|
58
|
+
`refs/heads/${branch}`,
|
|
59
|
+
])
|
|
60
|
+
return true
|
|
61
|
+
} catch {
|
|
62
|
+
return false
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* `<repoDir>/.claude/worktrees/<wtName>` に worktree を作成する。
|
|
68
|
+
* branch が既存ならそれを checkout、無ければ `-b` で新規作成。
|
|
69
|
+
*
|
|
70
|
+
* 移植元: D00000_cockpit/webapp/lib/worktrees.ts (createWorktree)
|
|
71
|
+
*/
|
|
72
|
+
export async function createWorktreeDir(parentDir, branch) {
|
|
73
|
+
const repoDir = path.resolve(HUB_PROJECTS_BASE, parentDir)
|
|
74
|
+
if (repoDir !== HUB_PROJECTS_BASE && !repoDir.startsWith(HUB_PROJECTS_BASE + path.sep)) {
|
|
75
|
+
throw new Error("dir outside projects base")
|
|
76
|
+
}
|
|
77
|
+
// .git の存在チェック (file or dir)
|
|
78
|
+
try {
|
|
79
|
+
await fs.stat(path.join(repoDir, ".git"))
|
|
80
|
+
} catch {
|
|
81
|
+
throw new Error("not a git repository")
|
|
82
|
+
}
|
|
83
|
+
const wtName = sanitizeBranchToWtName(branch)
|
|
84
|
+
if (!wtName) throw new Error("invalid branch name")
|
|
85
|
+
const wtPath = path.join(repoDir, ".claude", "worktrees", wtName)
|
|
86
|
+
try {
|
|
87
|
+
await fs.stat(wtPath)
|
|
88
|
+
throw new Error("worktree already exists")
|
|
89
|
+
} catch (err) {
|
|
90
|
+
if (err.message === "worktree already exists") throw err
|
|
91
|
+
// ENOENT は期待動作
|
|
92
|
+
}
|
|
93
|
+
const exists = await branchExists(repoDir, branch)
|
|
94
|
+
if (exists) {
|
|
95
|
+
await execFileP("git", ["-C", repoDir, "worktree", "add", wtPath, branch])
|
|
96
|
+
} else {
|
|
97
|
+
await execFileP("git", ["-C", repoDir, "worktree", "add", "-b", branch, wtPath])
|
|
98
|
+
}
|
|
99
|
+
return { wtName, wtPath, createdBranch: !exists }
|
|
100
|
+
}
|
|
101
|
+
|
|
35
102
|
/**
|
|
36
103
|
* `~/hub/projects/<project>/.claude/worktrees/<wt>` を走査し、
|
|
37
104
|
* worktree_session_name → parent_session_name の Map を返す。
|
|
@@ -159,20 +226,38 @@ export async function listSessions(opts = {}) {
|
|
|
159
226
|
}
|
|
160
227
|
})
|
|
161
228
|
|
|
162
|
-
// state + cwd + worktree
|
|
163
|
-
|
|
229
|
+
// state + cwd + worktree 親判定 + statusLine 由来 context% を並列付与
|
|
230
|
+
// statusLine の `used_percentage` を context_pct (USED %) として使う。
|
|
231
|
+
// pane 解析 (state.detectSessionState) はフォーマット変動に脆いので、
|
|
232
|
+
// statusLine cache がある cwd では優先採用する。
|
|
233
|
+
const [wtParentMap, sessionUsages] = await Promise.all([
|
|
234
|
+
buildWorktreeParentMap(),
|
|
235
|
+
getSessionUsages().catch(() => []),
|
|
236
|
+
])
|
|
237
|
+
// cwd → context_pct の lookup (同一 cwd で複数 session_id ある場合は最新 mtime 優先)
|
|
238
|
+
const ctxByCwd = new Map()
|
|
239
|
+
for (const u of sessionUsages) {
|
|
240
|
+
const prev = ctxByCwd.get(u.cwd)
|
|
241
|
+
if (!prev || u.updatedAtMs > prev.updatedAtMs) {
|
|
242
|
+
ctxByCwd.set(u.cwd, { contextPercent: u.contextPercent, updatedAtMs: u.updatedAtMs })
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
164
246
|
return Promise.all(
|
|
165
247
|
base.map(async (s) => {
|
|
166
248
|
const [state, cwd] = await Promise.all([
|
|
167
249
|
detectSessionState(s.name, opts),
|
|
168
250
|
getSessionCwd(s.name, opts),
|
|
169
251
|
])
|
|
252
|
+
// statusLine 由来 context% を最優先 (USED %), なければ pane 解析の fallback
|
|
253
|
+
const fromStatusLine = cwd ? ctxByCwd.get(cwd)?.contextPercent : null
|
|
254
|
+
const context_pct =
|
|
255
|
+
typeof fromStatusLine === "number" ? fromStatusLine : state.context_pct
|
|
170
256
|
return {
|
|
171
257
|
...s,
|
|
172
258
|
status: state.status,
|
|
173
|
-
context_pct
|
|
259
|
+
context_pct,
|
|
174
260
|
cwd,
|
|
175
|
-
// worktree session の場合は親 workspace の session 名を入れる (旧 cockpit webapp 互換)
|
|
176
261
|
parent_session_name: wtParentMap.get(s.name) || null,
|
|
177
262
|
}
|
|
178
263
|
}),
|
package/src/ws-client.mjs
CHANGED
|
@@ -20,13 +20,14 @@ const MAX_BACKOFF_MS = 30_000
|
|
|
20
20
|
export class WsClient extends EventEmitter {
|
|
21
21
|
/**
|
|
22
22
|
* @param {{ hub_url: string, agent_id: string, agent_token: string }} config
|
|
23
|
-
* @param {{ logger?: import('pino').Logger, version?: string }} opts
|
|
23
|
+
* @param {{ logger?: import('pino').Logger, version?: string, bundleVersion?: string|null, hostname?: string }} opts
|
|
24
24
|
*/
|
|
25
25
|
constructor(config, opts = {}) {
|
|
26
26
|
super()
|
|
27
27
|
this.config = config
|
|
28
28
|
this.logger = opts.logger
|
|
29
29
|
this.version = opts.version || "0.1.0"
|
|
30
|
+
this.bundleVersion = opts.bundleVersion || null
|
|
30
31
|
this.hostname = opts.hostname || os.hostname()
|
|
31
32
|
this.ws = null
|
|
32
33
|
this.heartbeatTimer = null
|
|
@@ -56,6 +57,7 @@ export class WsClient extends EventEmitter {
|
|
|
56
57
|
agent_id: this.config.agent_id,
|
|
57
58
|
hostname: this.hostname,
|
|
58
59
|
version: this.version,
|
|
60
|
+
bundle_version: this.bundleVersion,
|
|
59
61
|
})
|
|
60
62
|
this._startHeartbeat()
|
|
61
63
|
this.emit("open")
|
|
@@ -142,6 +144,7 @@ export class WsClient extends EventEmitter {
|
|
|
142
144
|
const ok = this._sendJson({
|
|
143
145
|
type: "heartbeat",
|
|
144
146
|
uptime_sec: Math.floor((Date.now() - this.startedAt) / 1000),
|
|
147
|
+
bundle_version: this.bundleVersion,
|
|
145
148
|
})
|
|
146
149
|
if (!ok) {
|
|
147
150
|
this.logger?.warn("heartbeat send failed, forcing reconnect")
|