@triflux/core 10.50.2 → 10.52.0
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/hooks/agy-session-hook.mjs +11 -56
- package/hooks/codex-session-hook.mjs +11 -101
- package/hub/bridge.mjs +65 -1250
- package/hub/cli-adapter-base.mjs +12 -90
- package/hub/codex-adapter.mjs +0 -1
- package/hub/codex-preflight.mjs +5 -28
- package/hub/index.mjs +3 -19
- package/hub/lib/process-utils.mjs +1 -156
- package/hub/lib/spawn-trace.mjs +3 -2
- package/hub/lib/timeout-defaults.mjs +0 -1
- package/hub/team/claude-daemon-control.mjs +1 -2
- package/hub/team/claude-session-projection.mjs +5 -73
- package/hub/team/nativeProxy.mjs +759 -0
- package/hub/team/session-context.mjs +1 -1
- package/hud/cli-policy.mjs +0 -22
- package/hud/constants.mjs +13 -26
- package/hud/hud-qos-status.mjs +42 -54
- package/hud/providers/gemini.mjs +125 -20
- package/hud/renderers.mjs +101 -122
- package/hud/utils.mjs +10 -6
- package/package.json +2 -6
- package/scripts/lib/agent-route-policy.mjs +143 -62
- package/scripts/lib/cli-claude.mjs +0 -14
- package/scripts/lib/env-probe.mjs +2 -131
- package/scripts/lib/gemini-profiles.mjs +2 -69
- package/scripts/lib/legacy-mcp-cleanup.mjs +283 -0
- package/scripts/lib/machine-profile.mjs +3 -17
- package/scripts/lib/mcp-filter.mjs +109 -53
- package/scripts/lib/mcp-guard-engine.mjs +40 -98
- package/scripts/lib/mcp-health.mjs +2 -2
- package/scripts/lib/mcp-server-catalog.mjs +2 -2
- package/scripts/lib/psmux-info.mjs +11 -59
- package/scripts/lib/session-presence.mjs +2 -100
- package/scripts/lib/skill-template.mjs +0 -245
- package/hub/adaptive-diagnostic.mjs +0 -350
- package/hub/adaptive-inject.mjs +0 -224
- package/hub/adaptive-memory.mjs +0 -277
- package/hub/adaptive.mjs +0 -172
- package/hub/assign-callbacks.mjs +0 -170
- package/hub/delegator/contracts.mjs +0 -38
- package/hub/delegator/index.mjs +0 -14
- package/hub/delegator/schema/delegator-tools.schema.json +0 -250
- package/hub/delegator/service.mjs +0 -336
- package/hub/delegator/tool-definitions.mjs +0 -35
- package/hub/dynamic-routing-engine.mjs +0 -511
- package/hub/hitl.mjs +0 -202
- package/hub/lib/known-errors.json +0 -72
- package/hub/lib/memory-store.mjs +0 -1001
- package/hub/lib/phase-manager.mjs +0 -493
- package/hub/lib/risk-tier.mjs +0 -53
- package/hub/lib/ssh-command.mjs +0 -231
- package/hub/lib/staged-file-detect.mjs +0 -43
- package/hub/lib/state-snapshot.mjs +0 -293
- package/hub/lib/tfx-route-args.mjs +0 -353
- package/hub/lib/trace-recorder.mjs +0 -153
- package/hub/lib/uuidv7.mjs +0 -45
- package/hub/memory-doctor.mjs +0 -640
- package/hub/middleware/quota-middleware.mjs +0 -70
- package/hub/middleware/request-logger.mjs +0 -191
- package/hub/paths.mjs +0 -24
- package/hub/pipeline/index.mjs +0 -163
- package/hub/pipeline/state.mjs +0 -191
- package/hub/pipeline/transitions.mjs +0 -131
- package/hub/reflexion.mjs +0 -290
- package/hub/role-contract.mjs +0 -314
- package/hub/router.mjs +0 -2026
- package/hub/routing-snapshot.mjs +0 -261
- package/hub/session-fingerprint.mjs +0 -418
- package/hub/state.mjs +0 -300
- package/hub/team/synapse-http.mjs +0 -311
- package/hub/team-bridge.mjs +0 -27
- package/mesh/index.mjs +0 -69
- package/mesh/mesh-budget.mjs +0 -137
- package/mesh/mesh-heartbeat.mjs +0 -100
- package/mesh/mesh-protocol.mjs +0 -96
- package/mesh/mesh-queue.mjs +0 -163
- package/mesh/mesh-registry.mjs +0 -78
- package/mesh/mesh-router.mjs +0 -77
- package/scripts/lib/claudemd-scanner.mjs +0 -223
- package/scripts/lib/context.mjs +0 -67
- package/scripts/lib/dynamic-route-cli.mjs +0 -107
- package/scripts/lib/handoff.mjs +0 -187
- package/scripts/lib/logger.mjs +0 -122
- package/scripts/lib/stealth-fetch.mjs +0 -176
package/hub/state.mjs
DELETED
|
@@ -1,300 +0,0 @@
|
|
|
1
|
-
import { execSync } from "node:child_process";
|
|
2
|
-
import {
|
|
3
|
-
closeSync,
|
|
4
|
-
existsSync,
|
|
5
|
-
mkdirSync,
|
|
6
|
-
openSync,
|
|
7
|
-
readFileSync,
|
|
8
|
-
renameSync,
|
|
9
|
-
statSync,
|
|
10
|
-
unlinkSync,
|
|
11
|
-
writeFileSync,
|
|
12
|
-
} from "node:fs";
|
|
13
|
-
import { homedir } from "node:os";
|
|
14
|
-
import { dirname, join } from "node:path";
|
|
15
|
-
import { fileURLToPath } from "node:url";
|
|
16
|
-
|
|
17
|
-
const PROJECT_ROOT = fileURLToPath(new URL("..", import.meta.url));
|
|
18
|
-
const PID_FILE_NAME = "hub.pid";
|
|
19
|
-
const LEGACY_STATE_FILE_NAME = "hub-state.json";
|
|
20
|
-
const LOCK_FILE_NAME = "hub-start.lock";
|
|
21
|
-
|
|
22
|
-
let heldLockPath = null;
|
|
23
|
-
let heldLockFd = null;
|
|
24
|
-
let cachedVersionHash = null;
|
|
25
|
-
|
|
26
|
-
function getStateDir(options = {}) {
|
|
27
|
-
return (
|
|
28
|
-
options.stateDir ||
|
|
29
|
-
process.env.TFX_HUB_STATE_DIR?.trim() ||
|
|
30
|
-
join(homedir(), ".claude", "cache", "tfx-hub")
|
|
31
|
-
);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function getStatePath(options = {}) {
|
|
35
|
-
return options.statePath || join(getStateDir(options), PID_FILE_NAME);
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function getLegacyStatePath(options = {}) {
|
|
39
|
-
return join(getStateDir(options), LEGACY_STATE_FILE_NAME);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function getLockPath(options = {}) {
|
|
43
|
-
return options.lockPath || join(getStateDir(options), LOCK_FILE_NAME);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function sleep(ms) {
|
|
47
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function isPidAlive(pid) {
|
|
51
|
-
if (!Number.isFinite(Number(pid)) || Number(pid) <= 0) return false;
|
|
52
|
-
try {
|
|
53
|
-
process.kill(Number(pid), 0);
|
|
54
|
-
return true;
|
|
55
|
-
} catch {
|
|
56
|
-
return false;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function parseJson(text, fallback = null) {
|
|
61
|
-
try {
|
|
62
|
-
return JSON.parse(text);
|
|
63
|
-
} catch {
|
|
64
|
-
return fallback;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
function safeReplaceFile(tempPath, targetPath) {
|
|
69
|
-
try {
|
|
70
|
-
renameSync(tempPath, targetPath);
|
|
71
|
-
} catch (error) {
|
|
72
|
-
if (!["EEXIST", "EPERM", "EACCES"].includes(error?.code)) {
|
|
73
|
-
try {
|
|
74
|
-
unlinkSync(tempPath);
|
|
75
|
-
} catch {}
|
|
76
|
-
throw error;
|
|
77
|
-
}
|
|
78
|
-
try {
|
|
79
|
-
unlinkSync(targetPath);
|
|
80
|
-
} catch {}
|
|
81
|
-
renameSync(tempPath, targetPath);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function writeJsonFile(targetPath, payload) {
|
|
86
|
-
const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`;
|
|
87
|
-
writeFileSync(tempPath, `${JSON.stringify(payload, null, 2)}\n`, {
|
|
88
|
-
encoding: "utf8",
|
|
89
|
-
mode: 0o600,
|
|
90
|
-
});
|
|
91
|
-
safeReplaceFile(tempPath, targetPath);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function readJsonFile(filePath) {
|
|
95
|
-
try {
|
|
96
|
-
if (!existsSync(filePath)) return null;
|
|
97
|
-
return parseJson(readFileSync(filePath, "utf8"), null);
|
|
98
|
-
} catch {
|
|
99
|
-
return null;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* 허브의 현재 상태(PID, 포트, 버전 등)를 파일에 기록합니다.
|
|
105
|
-
* 원자적(atomic) 쓰기를 위해 임시 파일을 생성한 후 교체하는 방식을 사용합니다.
|
|
106
|
-
*
|
|
107
|
-
* @param {object} payload - 상태 데이터
|
|
108
|
-
* @param {number} payload.pid - 허브 프로세스 ID
|
|
109
|
-
* @param {number} payload.port - 허브 서버 포트
|
|
110
|
-
* @param {string} payload.version - 허브 버전
|
|
111
|
-
* @param {string} payload.sessionId - 현재 세션 ID
|
|
112
|
-
* @param {string} payload.startedAt - 시작 시각 (ISO 8601)
|
|
113
|
-
* @param {object} [options] - 옵션
|
|
114
|
-
* @param {string} [options.stateDir] - 상태 파일이 저장될 디렉토리
|
|
115
|
-
* @returns {object} 기록된 상태 데이터
|
|
116
|
-
*/
|
|
117
|
-
export function writeState(
|
|
118
|
-
{ pid, port, version, sessionId, startedAt, ...rest },
|
|
119
|
-
options = {},
|
|
120
|
-
) {
|
|
121
|
-
const stateDir = getStateDir(options);
|
|
122
|
-
const statePath = getStatePath(options);
|
|
123
|
-
const payload = { pid, port, version, sessionId, startedAt, ...rest };
|
|
124
|
-
|
|
125
|
-
mkdirSync(stateDir, { recursive: true });
|
|
126
|
-
writeJsonFile(statePath, payload);
|
|
127
|
-
try {
|
|
128
|
-
unlinkSync(getLegacyStatePath(options));
|
|
129
|
-
} catch {}
|
|
130
|
-
return payload;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* 파일로부터 허브의 현재 상태를 읽어옵니다.
|
|
135
|
-
*
|
|
136
|
-
* @param {object} [options] - 옵션
|
|
137
|
-
* @param {string} [options.stateDir] - 상태 파일이 저장된 디렉토리
|
|
138
|
-
* @returns {object|null} 읽어온 상태 데이터 또는 실패 시 null
|
|
139
|
-
*/
|
|
140
|
-
export function readState(options = {}) {
|
|
141
|
-
return (
|
|
142
|
-
readJsonFile(getStatePath(options)) ??
|
|
143
|
-
readJsonFile(getLegacyStatePath(options))
|
|
144
|
-
);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* 지정된 포트에서 실행 중인 허브 서버의 헬스 체크를 수행합니다.
|
|
149
|
-
*
|
|
150
|
-
* @param {number|string} port - 서버 포트
|
|
151
|
-
* @param {object} [options] - 옵션
|
|
152
|
-
* @param {number} [options.timeoutMs=1000] - 요청 타임아웃
|
|
153
|
-
* @param {string} [options.baseUrl] - 서버 베이스 URL
|
|
154
|
-
* @returns {Promise<boolean>} 서버 정상 작동 여부
|
|
155
|
-
*/
|
|
156
|
-
export async function isServerHealthy(port, options = {}) {
|
|
157
|
-
const resolvedPort = Number(port);
|
|
158
|
-
if (!Number.isFinite(resolvedPort) || resolvedPort <= 0) return false;
|
|
159
|
-
|
|
160
|
-
const timeoutMs = Math.max(100, Number(options.timeoutMs) || 1000);
|
|
161
|
-
const baseUrl = options.baseUrl || `http://127.0.0.1:${resolvedPort}`;
|
|
162
|
-
|
|
163
|
-
try {
|
|
164
|
-
const response = await fetch(`${baseUrl}/health`, {
|
|
165
|
-
method: "GET",
|
|
166
|
-
signal: AbortSignal.timeout(timeoutMs),
|
|
167
|
-
});
|
|
168
|
-
if (!response.ok) return false;
|
|
169
|
-
const body = await response.json().catch(() => null);
|
|
170
|
-
return body?.ok === true;
|
|
171
|
-
} catch {
|
|
172
|
-
return false;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* 현재 프로젝트의 버전 해시를 생성합니다.
|
|
178
|
-
* package.json의 버전과 Git commit SHA를 조합합니다.
|
|
179
|
-
*
|
|
180
|
-
* @param {object} [options] - 옵션
|
|
181
|
-
* @param {boolean} [options.force=false] - 캐시를 무시하고 새로 생성할지 여부
|
|
182
|
-
* @returns {string} 버전 해시 문자열
|
|
183
|
-
*/
|
|
184
|
-
export function getVersionHash(options = {}) {
|
|
185
|
-
if (cachedVersionHash && !options.force) return cachedVersionHash;
|
|
186
|
-
|
|
187
|
-
const packageJsonPath = join(PROJECT_ROOT, "package.json");
|
|
188
|
-
const pkg = parseJson(readFileSync(packageJsonPath, "utf8"), {});
|
|
189
|
-
const version = String(pkg?.version || "0.0.0").trim();
|
|
190
|
-
|
|
191
|
-
let sha = String(process.env.TFX_HUB_GIT_SHA || "").trim();
|
|
192
|
-
if (!sha) {
|
|
193
|
-
try {
|
|
194
|
-
sha = execSync("git rev-parse --short HEAD", {
|
|
195
|
-
cwd: PROJECT_ROOT,
|
|
196
|
-
encoding: "utf8",
|
|
197
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
198
|
-
windowsHide: true,
|
|
199
|
-
}).trim();
|
|
200
|
-
} catch {
|
|
201
|
-
sha = "";
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
cachedVersionHash = sha ? `${version}-${sha}` : version;
|
|
206
|
-
return cachedVersionHash;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/**
|
|
210
|
-
* 허브 시작 시 중복 실행을 방지하기 위한 잠금(lock)을 획득합니다.
|
|
211
|
-
* 이미 실행 중인 다른 프로세스가 있는지 확인하고 유효한 잠금을 획득할 때까지 재시도합니다.
|
|
212
|
-
*
|
|
213
|
-
* @param {object} [options] - 옵션
|
|
214
|
-
* @param {number} [options.timeoutMs=3000] - 최대 대기 시간
|
|
215
|
-
* @param {number} [options.pollMs=50] - 재시도 간격
|
|
216
|
-
* @param {string} [options.lockPath] - 잠금 파일 경로
|
|
217
|
-
* @returns {Promise<{path: string}>} 잠금 파일 경로
|
|
218
|
-
* @throws {Error} 타임아웃 내에 잠금을 획득하지 못한 경우
|
|
219
|
-
*/
|
|
220
|
-
export async function acquireLock(options = {}) {
|
|
221
|
-
if (heldLockFd !== null && heldLockPath) {
|
|
222
|
-
return { path: heldLockPath };
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
const lockPath = getLockPath(options);
|
|
226
|
-
const timeoutMs = Math.max(100, Number(options.timeoutMs) || 3000);
|
|
227
|
-
const pollMs = Math.max(10, Number(options.pollMs) || 50);
|
|
228
|
-
const deadline = Date.now() + timeoutMs;
|
|
229
|
-
|
|
230
|
-
mkdirSync(dirname(lockPath), { recursive: true });
|
|
231
|
-
|
|
232
|
-
while (Date.now() <= deadline) {
|
|
233
|
-
try {
|
|
234
|
-
const fd = openSync(lockPath, "wx", 0o600);
|
|
235
|
-
writeFileSync(
|
|
236
|
-
fd,
|
|
237
|
-
`${JSON.stringify(
|
|
238
|
-
{
|
|
239
|
-
pid: process.pid,
|
|
240
|
-
createdAt: new Date().toISOString(),
|
|
241
|
-
},
|
|
242
|
-
null,
|
|
243
|
-
2,
|
|
244
|
-
)}\n`,
|
|
245
|
-
"utf8",
|
|
246
|
-
);
|
|
247
|
-
heldLockFd = fd;
|
|
248
|
-
heldLockPath = lockPath;
|
|
249
|
-
return { path: lockPath };
|
|
250
|
-
} catch (error) {
|
|
251
|
-
if (error?.code !== "EEXIST") {
|
|
252
|
-
throw error;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
try {
|
|
256
|
-
const raw = readFileSync(lockPath, "utf8");
|
|
257
|
-
const data = parseJson(raw, {});
|
|
258
|
-
const stats = statSync(lockPath);
|
|
259
|
-
const STALE_LOCK_AGE_MS = 60_000;
|
|
260
|
-
const staleByPid = !isPidAlive(data?.pid);
|
|
261
|
-
const staleByAge = Date.now() - stats.mtimeMs > STALE_LOCK_AGE_MS;
|
|
262
|
-
if (staleByPid || staleByAge) {
|
|
263
|
-
try {
|
|
264
|
-
unlinkSync(lockPath);
|
|
265
|
-
} catch {}
|
|
266
|
-
continue;
|
|
267
|
-
}
|
|
268
|
-
} catch {}
|
|
269
|
-
|
|
270
|
-
await sleep(pollMs);
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
throw new Error(`hub start lock busy: ${lockPath}`);
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
/**
|
|
278
|
-
* 획득했던 잠금을 해제합니다. 잠금 파일을 삭제하고 관련 리소스를 정리합니다.
|
|
279
|
-
*
|
|
280
|
-
* @param {object} [options] - 옵션
|
|
281
|
-
* @param {string} [options.lockPath] - 명시적인 잠금 파일 경로
|
|
282
|
-
*/
|
|
283
|
-
export function releaseLock(options = {}) {
|
|
284
|
-
const lockPath = options.lockPath || heldLockPath || getLockPath(options);
|
|
285
|
-
|
|
286
|
-
if (heldLockFd !== null) {
|
|
287
|
-
try {
|
|
288
|
-
closeSync(heldLockFd);
|
|
289
|
-
} catch {}
|
|
290
|
-
heldLockFd = null;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
try {
|
|
294
|
-
if (existsSync(lockPath)) unlinkSync(lockPath);
|
|
295
|
-
} catch {}
|
|
296
|
-
|
|
297
|
-
if (!options.lockPath || options.lockPath === heldLockPath) {
|
|
298
|
-
heldLockPath = null;
|
|
299
|
-
}
|
|
300
|
-
}
|
|
@@ -1,311 +0,0 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
2
|
-
import { createHash } from "node:crypto";
|
|
3
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
-
import { homedir, hostname } from "node:os";
|
|
5
|
-
import { dirname, join } from "node:path";
|
|
6
|
-
import { normalizeRoleKey } from "../role-contract.mjs";
|
|
7
|
-
|
|
8
|
-
const HUB_DEFAULT_PORT = 27888;
|
|
9
|
-
// Same token file as hub/bridge.mjs (HUB_TOKEN_FILE). Kept inline rather than
|
|
10
|
-
// imported so this helper stays dependency-free and byte-identical across the
|
|
11
|
-
// packages/core mirror (which cannot carry relative cross-package imports).
|
|
12
|
-
const HUB_TOKEN_FILE = join(homedir(), ".claude", ".tfx-hub-token");
|
|
13
|
-
|
|
14
|
-
// In-flight fire-and-forget POSTs. A short-lived caller (the SessionStart hook,
|
|
15
|
-
// which process.exit(0)s immediately after firing register) must be able to
|
|
16
|
-
// flush these before the process dies: Node's process.exit() abandons pending
|
|
17
|
-
// socket I/O, so an un-awaited loopback POST is created but never written.
|
|
18
|
-
// Callers on an exit budget drain this set via drainPendingSynapse() first.
|
|
19
|
-
const inFlightSynapse = new Set();
|
|
20
|
-
|
|
21
|
-
function normalizeToken(raw) {
|
|
22
|
-
if (raw == null) return null;
|
|
23
|
-
const token = String(raw).trim();
|
|
24
|
-
return token || null;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function opaqueId(prefix, value) {
|
|
28
|
-
return `${prefix}_${createHash("sha256")
|
|
29
|
-
.update(String(value || ""))
|
|
30
|
-
.digest("base64url")
|
|
31
|
-
.slice(0, 22)}`;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function normalizedProjectId(value) {
|
|
35
|
-
try {
|
|
36
|
-
return normalizeRoleKey({ project_id: value, role_kind: "cto" }).project_id;
|
|
37
|
-
} catch {
|
|
38
|
-
return "";
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function resolveProjectId(cwd, meta, opts = {}) {
|
|
43
|
-
const explicit = meta?.project_id || process.env.TFX_PROJECT_ID;
|
|
44
|
-
if (explicit) return normalizedProjectId(explicit);
|
|
45
|
-
if (typeof opts.resolveProjectId === "function") {
|
|
46
|
-
return normalizedProjectId(opts.resolveProjectId(cwd));
|
|
47
|
-
}
|
|
48
|
-
let current = cwd;
|
|
49
|
-
while (current) {
|
|
50
|
-
const manifest = join(current, ".triflux", "project.json");
|
|
51
|
-
if (existsSync(manifest)) {
|
|
52
|
-
try {
|
|
53
|
-
const parsed = JSON.parse(readFileSync(manifest, "utf8"));
|
|
54
|
-
if (parsed?.schema_version !== "tfx.project.v1") return "";
|
|
55
|
-
return normalizedProjectId(parsed.project_id);
|
|
56
|
-
} catch {
|
|
57
|
-
return "";
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
const parent = dirname(current);
|
|
61
|
-
if (parent === current) break;
|
|
62
|
-
current = parent;
|
|
63
|
-
}
|
|
64
|
-
return "";
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function inferSessionCli(meta, opts = {}) {
|
|
68
|
-
const explicit = String(meta?.cli || meta?.actor_cli || "")
|
|
69
|
-
.trim()
|
|
70
|
-
.toLowerCase();
|
|
71
|
-
if (explicit === "codex" || explicit === "claude") return explicit;
|
|
72
|
-
const entrypoint = String(opts.entrypoint ?? process.argv[1] ?? "");
|
|
73
|
-
if (entrypoint.includes("codex-session-hook")) return "codex";
|
|
74
|
-
if (entrypoint.includes("agy-session-hook")) return "other";
|
|
75
|
-
return "claude";
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function resolveTmuxSession(meta, opts = {}) {
|
|
79
|
-
const explicit =
|
|
80
|
-
meta?.tmux_session || meta?.session_name || process.env.TFX_TMUX_SESSION;
|
|
81
|
-
if (explicit) return String(explicit).trim();
|
|
82
|
-
if (!process.env.TMUX) return "";
|
|
83
|
-
try {
|
|
84
|
-
const run =
|
|
85
|
-
opts.tmuxSessionName ||
|
|
86
|
-
(() =>
|
|
87
|
-
execFileSync("tmux", ["display-message", "-p", "#{session_name}"], {
|
|
88
|
-
encoding: "utf8",
|
|
89
|
-
timeout: 200,
|
|
90
|
-
windowsHide: true,
|
|
91
|
-
}));
|
|
92
|
-
return String(run() || "").trim();
|
|
93
|
-
} catch {
|
|
94
|
-
return "";
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export function buildSynapseRegistrationMeta(meta, opts = {}) {
|
|
99
|
-
if (!meta || meta.sessionKind !== "interactive") return meta;
|
|
100
|
-
const sessionId = String(meta.sessionId || "").trim();
|
|
101
|
-
if (!sessionId) return meta;
|
|
102
|
-
const cwd = typeof meta.cwd === "string" ? meta.cwd : process.cwd();
|
|
103
|
-
const cli = inferSessionCli(meta, opts);
|
|
104
|
-
const hostId = String(
|
|
105
|
-
meta.host_id ||
|
|
106
|
-
process.env.TFX_HOST_ID ||
|
|
107
|
-
opaqueId("hst", opts.hostname?.() || hostname()),
|
|
108
|
-
).trim();
|
|
109
|
-
const expiresAtMs = Number(opts.nowMs?.() ?? Date.now()) + 299000;
|
|
110
|
-
const transportLocators = [];
|
|
111
|
-
if (cli === "claude") {
|
|
112
|
-
transportLocators.push({
|
|
113
|
-
schema_version: "tfx.transport-locator.v1",
|
|
114
|
-
transport_id: opaqueId("trn", `claude-uds:${hostId}:${sessionId}`),
|
|
115
|
-
kind: "claude-uds",
|
|
116
|
-
host_id: hostId,
|
|
117
|
-
capabilities: ["probe", "wake", "activate", "interrupt"],
|
|
118
|
-
priority: 100,
|
|
119
|
-
expires_at_ms: expiresAtMs,
|
|
120
|
-
locator: {
|
|
121
|
-
session_id: sessionId,
|
|
122
|
-
bridge_id: String(
|
|
123
|
-
meta.bridge_id || process.env.TFX_BRIDGE_ID || "local-hub",
|
|
124
|
-
),
|
|
125
|
-
},
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
const tmuxSession = resolveTmuxSession(meta, opts);
|
|
129
|
-
if (tmuxSession) {
|
|
130
|
-
const muxServerSource =
|
|
131
|
-
meta.mux_server_id ||
|
|
132
|
-
process.env.TFX_MUX_SERVER_ID ||
|
|
133
|
-
String(process.env.TMUX || "default").split(",", 1)[0];
|
|
134
|
-
transportLocators.push({
|
|
135
|
-
schema_version: "tfx.transport-locator.v1",
|
|
136
|
-
transport_id: opaqueId("trn", `tmux:${hostId}:${tmuxSession}`),
|
|
137
|
-
kind: "tmux",
|
|
138
|
-
host_id: hostId,
|
|
139
|
-
capabilities: ["probe", "wake", "activate", "interrupt"],
|
|
140
|
-
priority: cli === "codex" ? 100 : 50,
|
|
141
|
-
expires_at_ms: expiresAtMs,
|
|
142
|
-
locator: {
|
|
143
|
-
session_name: tmuxSession,
|
|
144
|
-
mux_server_id: opaqueId("mux", muxServerSource),
|
|
145
|
-
},
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
const directAgentId = `session:${sessionId}`;
|
|
149
|
-
return {
|
|
150
|
-
...meta,
|
|
151
|
-
agent_id:
|
|
152
|
-
meta.agent_id ||
|
|
153
|
-
(directAgentId.length <= 64 && /^[a-zA-Z0-9._:-]+$/u.test(directAgentId)
|
|
154
|
-
? directAgentId
|
|
155
|
-
: opaqueId("session", sessionId)),
|
|
156
|
-
cli,
|
|
157
|
-
project_id: resolveProjectId(cwd, meta, opts) || undefined,
|
|
158
|
-
session_id: meta.session_id || sessionId,
|
|
159
|
-
host_id: hostId,
|
|
160
|
-
transport_locators_json:
|
|
161
|
-
meta.transport_locators_json ?? JSON.stringify(transportLocators),
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// Mirrors hub/bridge.mjs:readHubToken — env override first, then the token file.
|
|
166
|
-
// Missing token → null (backward-compatible with token-less hubs).
|
|
167
|
-
function readHubToken() {
|
|
168
|
-
const envToken = normalizeToken(process.env.TFX_HUB_TOKEN);
|
|
169
|
-
if (envToken) return envToken;
|
|
170
|
-
try {
|
|
171
|
-
return normalizeToken(readFileSync(HUB_TOKEN_FILE, "utf8"));
|
|
172
|
-
} catch {
|
|
173
|
-
return null;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// Wrap IPv6 hosts in [...] so they form a valid URL authority (cf. bridge.mjs).
|
|
178
|
-
function formatHostForUrl(host) {
|
|
179
|
-
return String(host).includes(":") ? `[${host}]` : host;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// Resolve the hub base URL from env (TFX_HUB_URL / TFX_HUB_PORT) before falling
|
|
183
|
-
// back to the loopback default, so a cascaded / non-default hub port is hit
|
|
184
|
-
// instead of silently posting to 127.0.0.1:27888 and missing the live hub.
|
|
185
|
-
function resolveSynapseBaseUrl() {
|
|
186
|
-
const envUrl = normalizeToken(process.env.TFX_HUB_URL);
|
|
187
|
-
if (envUrl) return envUrl.replace(/\/mcp$/, "");
|
|
188
|
-
|
|
189
|
-
const envPort = Number.parseInt(String(process.env.TFX_HUB_PORT ?? ""), 10);
|
|
190
|
-
if (Number.isFinite(envPort) && envPort > 0) {
|
|
191
|
-
return `http://${formatHostForUrl("127.0.0.1")}:${envPort}`;
|
|
192
|
-
}
|
|
193
|
-
return `http://${formatHostForUrl("127.0.0.1")}:${HUB_DEFAULT_PORT}`;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
function resolveSynapseFetch(fetchImpl) {
|
|
197
|
-
if (fetchImpl === null) return null;
|
|
198
|
-
if (typeof fetchImpl === "function") return fetchImpl;
|
|
199
|
-
if (typeof globalThis.fetch === "function") {
|
|
200
|
-
return globalThis.fetch.bind(globalThis);
|
|
201
|
-
}
|
|
202
|
-
return null;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
export function buildSynapseTaskSummary(prompt, maxLength = 100) {
|
|
206
|
-
if (maxLength <= 0) return "";
|
|
207
|
-
return String(prompt ?? "").slice(0, maxLength);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
export function fireAndForgetSynapse(path, payload, opts = {}) {
|
|
211
|
-
const fetchImpl = resolveSynapseFetch(opts.fetchImpl);
|
|
212
|
-
if (!fetchImpl) return false;
|
|
213
|
-
|
|
214
|
-
try {
|
|
215
|
-
const baseUrl = opts.baseUrl || resolveSynapseBaseUrl();
|
|
216
|
-
const url = new URL(path, baseUrl).toString();
|
|
217
|
-
const headers = { "content-type": "application/json" };
|
|
218
|
-
// token: false explicitly skips auth; otherwise reuse the hub token so a
|
|
219
|
-
// token-required hub does not 401 (the failure would be swallowed silently).
|
|
220
|
-
if (opts.token !== false) {
|
|
221
|
-
const token =
|
|
222
|
-
typeof opts.token === "string" && opts.token.trim()
|
|
223
|
-
? opts.token.trim()
|
|
224
|
-
: readHubToken();
|
|
225
|
-
if (token) headers.Authorization = `Bearer ${token}`;
|
|
226
|
-
}
|
|
227
|
-
const init = {
|
|
228
|
-
method: "POST",
|
|
229
|
-
headers,
|
|
230
|
-
body: JSON.stringify(payload),
|
|
231
|
-
};
|
|
232
|
-
// Optional bounded timeout so callers on a teardown budget (e.g. SessionEnd)
|
|
233
|
-
// cannot hang the host process if the hub stalls. The timer is unref'd so it
|
|
234
|
-
// never keeps the event loop (and thus the hook process) alive on its own.
|
|
235
|
-
let timer = null;
|
|
236
|
-
const timeoutMs = Number(opts.timeoutMs);
|
|
237
|
-
if (
|
|
238
|
-
Number.isFinite(timeoutMs) &&
|
|
239
|
-
timeoutMs > 0 &&
|
|
240
|
-
typeof AbortController === "function"
|
|
241
|
-
) {
|
|
242
|
-
const controller = new AbortController();
|
|
243
|
-
init.signal = controller.signal;
|
|
244
|
-
timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
245
|
-
if (typeof timer.unref === "function") timer.unref();
|
|
246
|
-
}
|
|
247
|
-
const tracked = Promise.resolve(fetchImpl(url, init))
|
|
248
|
-
.catch(() => {})
|
|
249
|
-
.finally(() => {
|
|
250
|
-
if (timer) clearTimeout(timer);
|
|
251
|
-
inFlightSynapse.delete(tracked);
|
|
252
|
-
});
|
|
253
|
-
inFlightSynapse.add(tracked);
|
|
254
|
-
return true;
|
|
255
|
-
} catch {
|
|
256
|
-
return false;
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// Await any in-flight fire-and-forget Synapse POSTs, bounded by timeoutMs so a
|
|
261
|
-
// stalled hub can never hang the caller. The SessionStart hook calls this right
|
|
262
|
-
// before process.exit(0) so the register POST actually flushes to the socket.
|
|
263
|
-
export function drainPendingSynapse(timeoutMs = 1000) {
|
|
264
|
-
if (inFlightSynapse.size === 0) return Promise.resolve();
|
|
265
|
-
const settled = Promise.allSettled([...inFlightSynapse]);
|
|
266
|
-
const ms = Number(timeoutMs);
|
|
267
|
-
if (!Number.isFinite(ms) || ms <= 0) return settled;
|
|
268
|
-
let timeout = null;
|
|
269
|
-
const timeoutPromise = new Promise((resolve) => {
|
|
270
|
-
// Keep this timer ref'ed: drainPendingSynapse() is awaited specifically
|
|
271
|
-
// to hold the process open until either in-flight POSTs settle or the
|
|
272
|
-
// bounded drain budget expires. An unref'ed timer can let Node's test
|
|
273
|
-
// runner/process exit before the Promise resolves when no other handles
|
|
274
|
-
// remain.
|
|
275
|
-
timeout = setTimeout(resolve, ms);
|
|
276
|
-
});
|
|
277
|
-
return Promise.race([settled, timeoutPromise]).finally(() => {
|
|
278
|
-
if (timeout) clearTimeout(timeout);
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
export function registerSynapseSession(meta, opts = {}) {
|
|
283
|
-
return fireAndForgetSynapse(
|
|
284
|
-
"/synapse/register",
|
|
285
|
-
buildSynapseRegistrationMeta(meta, opts),
|
|
286
|
-
opts,
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
export function heartbeatSynapseSession(
|
|
291
|
-
sessionId,
|
|
292
|
-
partialMeta = {},
|
|
293
|
-
opts = {},
|
|
294
|
-
) {
|
|
295
|
-
// The live route reads `{ sessionId, partial }` (hub/server.mjs
|
|
296
|
-
// /synapse/heartbeat → synapseRegistry.heartbeat(sessionId, partial)), so the
|
|
297
|
-
// helper must nest the meta under `partial` rather than spreading it top-level.
|
|
298
|
-
return fireAndForgetSynapse(
|
|
299
|
-
"/synapse/heartbeat",
|
|
300
|
-
{
|
|
301
|
-
sessionId,
|
|
302
|
-
partial:
|
|
303
|
-
partialMeta && typeof partialMeta === "object" ? partialMeta : {},
|
|
304
|
-
},
|
|
305
|
-
opts,
|
|
306
|
-
);
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
export function unregisterSynapseSession(sessionId, opts = {}) {
|
|
310
|
-
return fireAndForgetSynapse("/synapse/unregister", { sessionId }, opts);
|
|
311
|
-
}
|
package/hub/team-bridge.mjs
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
// @triflux/core — team-bridge 인터페이스
|
|
2
|
-
// remote 패키지가 런타임에 구현을 주입한다.
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* @typedef {object} TeamBridge
|
|
6
|
-
* @property {(args?: object) => Promise<object>} teamInfo
|
|
7
|
-
* @property {(args?: object) => Promise<object>} teamTaskList
|
|
8
|
-
* @property {(args?: object) => Promise<object>} teamTaskUpdate
|
|
9
|
-
* @property {(args?: object) => Promise<object>} teamSendMessage
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
/** @type {TeamBridge | null} */
|
|
13
|
-
let _bridge = null;
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* @param {TeamBridge | null} impl
|
|
17
|
-
*/
|
|
18
|
-
export function registerTeamBridge(impl) {
|
|
19
|
-
_bridge = impl;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* @returns {TeamBridge | null}
|
|
24
|
-
*/
|
|
25
|
-
export function getTeamBridge() {
|
|
26
|
-
return _bridge;
|
|
27
|
-
}
|
package/mesh/index.mjs
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import { readdirSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
|
|
4
|
-
export { createMeshBudget } from "./mesh-budget.mjs";
|
|
5
|
-
export { createHeartbeatMonitor } from "./mesh-heartbeat.mjs";
|
|
6
|
-
export {
|
|
7
|
-
createMessage,
|
|
8
|
-
deserialize,
|
|
9
|
-
MSG_TYPES,
|
|
10
|
-
serialize,
|
|
11
|
-
validate,
|
|
12
|
-
} from "./mesh-protocol.mjs";
|
|
13
|
-
export { createMessageQueue } from "./mesh-queue.mjs";
|
|
14
|
-
export { createRegistry } from "./mesh-registry.mjs";
|
|
15
|
-
export { routeMessage, routeOrDeadLetter } from "./mesh-router.mjs";
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Loads skills assigned to a specific agent from a skills directory.
|
|
19
|
-
* Reuses the same directory-scan approach as generateSkillDocs().
|
|
20
|
-
*
|
|
21
|
-
* @param {string} agentId - The agent identifier
|
|
22
|
-
* @param {string} skillsDir - Path to the skills directory
|
|
23
|
-
* @returns {Promise<string[]>} Array of skill names available to this agent
|
|
24
|
-
*/
|
|
25
|
-
export async function loadSkillsForAgent(agentId, skillsDir) {
|
|
26
|
-
if (!agentId || typeof agentId !== "string") {
|
|
27
|
-
throw new TypeError("agentId must be a non-empty string");
|
|
28
|
-
}
|
|
29
|
-
if (!skillsDir || typeof skillsDir !== "string") {
|
|
30
|
-
throw new TypeError("skillsDir must be a non-empty string");
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
let entries;
|
|
34
|
-
try {
|
|
35
|
-
entries = readdirSync(skillsDir, { withFileTypes: true });
|
|
36
|
-
} catch {
|
|
37
|
-
return [];
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
const skills = [];
|
|
41
|
-
for (const entry of entries) {
|
|
42
|
-
if (!entry.isDirectory()) continue;
|
|
43
|
-
const skillName = entry.name;
|
|
44
|
-
const skillPath = join(skillsDir, skillName, "SKILL.md");
|
|
45
|
-
let skillContent = null;
|
|
46
|
-
try {
|
|
47
|
-
const { readFileSync } = await import("node:fs");
|
|
48
|
-
skillContent = readFileSync(skillPath, "utf8");
|
|
49
|
-
} catch {
|
|
50
|
-
// Skill has no SKILL.md — include it anyway
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// If SKILL.md mentions the agentId or no agent restriction, include it
|
|
54
|
-
const isRestricted = skillContent
|
|
55
|
-
? /^agents?\s*:/im.test(skillContent)
|
|
56
|
-
: false;
|
|
57
|
-
|
|
58
|
-
if (!isRestricted) {
|
|
59
|
-
skills.push(skillName);
|
|
60
|
-
continue;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
if (skillContent?.includes(agentId)) {
|
|
64
|
-
skills.push(skillName);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
return skills;
|
|
69
|
-
}
|