@liang-hz/agent-in-chrome 0.55.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/.ext-id.txt +4 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/PRIVACY.md +86 -0
- package/README.en.md +419 -0
- package/README.md +406 -0
- package/bin/agent-in-chrome.mjs +97 -0
- package/commands/agent-in-chrome.md +18 -0
- package/commands/install-agent-in-chrome.md +22 -0
- package/docs/AGENTS.md +94 -0
- package/docs/CLI.md +297 -0
- package/docs/client-compat.json +23 -0
- package/extension/about-toc.js +25 -0
- package/extension/about.html +240 -0
- package/extension/about.js +44 -0
- package/extension/agent-window.html +100 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-24.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/icons/icon-64.png +0 -0
- package/extension/icons/icon-attention-128.png +0 -0
- package/extension/icons/icon-attention-16.png +0 -0
- package/extension/icons/icon-attention-24.png +0 -0
- package/extension/icons/icon-attention-32.png +0 -0
- package/extension/icons/icon-attention-48.png +0 -0
- package/extension/icons/icon-attention-64.png +0 -0
- package/extension/icons/icon-attention.svg +18 -0
- package/extension/icons/icon-failed-128.png +0 -0
- package/extension/icons/icon-failed-16.png +0 -0
- package/extension/icons/icon-failed-24.png +0 -0
- package/extension/icons/icon-failed-32.png +0 -0
- package/extension/icons/icon-failed-48.png +0 -0
- package/extension/icons/icon-failed-64.png +0 -0
- package/extension/icons/icon-failed.svg +18 -0
- package/extension/icons/icon-idle-128.png +0 -0
- package/extension/icons/icon-idle-16.png +0 -0
- package/extension/icons/icon-idle-24.png +0 -0
- package/extension/icons/icon-idle-32.png +0 -0
- package/extension/icons/icon-idle-48.png +0 -0
- package/extension/icons/icon-idle-64.png +0 -0
- package/extension/icons/icon-idle.svg +18 -0
- package/extension/icons/icon-mark.svg +10 -0
- package/extension/icons/icon-running-128.png +0 -0
- package/extension/icons/icon-running-16.png +0 -0
- package/extension/icons/icon-running-24.png +0 -0
- package/extension/icons/icon-running-32.png +0 -0
- package/extension/icons/icon-running-48.png +0 -0
- package/extension/icons/icon-running-64.png +0 -0
- package/extension/icons/icon-running.svg +18 -0
- package/extension/icons/icon.svg +18 -0
- package/extension/manifest.json +44 -0
- package/extension/popup-ui.js +38 -0
- package/extension/popup.html +350 -0
- package/extension/popup.js +741 -0
- package/extension/sw.js +11127 -0
- package/extension/update-check.js +66 -0
- package/extension/welcome.html +110 -0
- package/extension/welcome.js +18 -0
- package/mcp/agent-identity.mjs +1007 -0
- package/mcp/cdp/bridge.mjs +239 -0
- package/mcp/cdp/browser-launch.mjs +1127 -0
- package/mcp/cdp/chrome-shim.mjs +1124 -0
- package/mcp/cdp/client.mjs +443 -0
- package/mcp/cli-invocation.mjs +67 -0
- package/mcp/config.mjs +191 -0
- package/mcp/foreground-guard.mjs +295 -0
- package/mcp/proc-win.mjs +112 -0
- package/mcp/secret-shape.mjs +155 -0
- package/mcp/server.mjs +3437 -0
- package/mcp/session-id.mjs +281 -0
- package/mcp/token.mjs +260 -0
- package/mcp/tool-tiers.mjs +84 -0
- package/mcp/trace.mjs +528 -0
- package/mcp/update-cli.mjs +163 -0
- package/mcp/update-notice.mjs +194 -0
- package/native-host/host.mjs +356 -0
- package/native-host/mac-foreground/aic-fg.swift +114 -0
- package/native-host/mac-foreground/build.mjs +43 -0
- package/package.json +46 -0
- package/scripts/agents.mjs +921 -0
- package/scripts/borrow-login.mjs +935 -0
- package/scripts/cli-browser.mjs +148 -0
- package/scripts/e2e-sweep.mjs +192 -0
- package/scripts/e2e.mjs +3911 -0
- package/scripts/fixture-server.mjs +1419 -0
- package/scripts/guard-publish.mjs +175 -0
- package/scripts/install.mjs +1383 -0
- package/scripts/launcher-provenance.mjs +74 -0
- package/scripts/pack-crx.mjs +82 -0
- package/scripts/pick.mjs +114 -0
- package/scripts/test-agents.mjs +968 -0
- package/scripts/test-borrow.mjs +289 -0
- package/scripts/test-config.mjs +618 -0
- package/scripts/test-e2e-sweep.mjs +251 -0
- package/scripts/test-foreground-guard.mjs +383 -0
- package/scripts/test-identity.mjs +1141 -0
- package/scripts/test-install-skill.mjs +378 -0
- package/scripts/test-protocol.mjs +712 -0
- package/scripts/test-security.mjs +1360 -0
- package/scripts/test-sw.mjs +14526 -0
- package/scripts/test-update.mjs +301 -0
- package/skills/agent-in-chrome/SKILL.md +60 -0
- package/skills/agent-in-chrome/references/actions-and-waits.md +136 -0
- package/skills/agent-in-chrome/references/amap-dir-dropdown.md +66 -0
- package/skills/agent-in-chrome/references/geetest-click-captcha.md +55 -0
- package/skills/agent-in-chrome/references/network-debugging.md +20 -0
- package/skills/agent-in-chrome/references/reading-pages.md +30 -0
- package/skills/agent-in-chrome/references/recovery.md +25 -0
- package/skills/agent-in-chrome/references/tabs-and-sessions.md +34 -0
- package/skills/install-agent-in-chrome/SKILL.md +252 -0
|
@@ -0,0 +1,1007 @@
|
|
|
1
|
+
// 这一组标签页背后是「谁、在哪、在做哪一段对话」——四段身份(品牌 / 形态 / 工作区 /
|
|
2
|
+
// 会话名)的本机取证。MCP 握手里的 clientInfo 不够用:name 常常是**发协议帧的那层
|
|
3
|
+
// 中间件**在自报,而且它答不出形态、工作区和这一段对话叫什么。证据全在本机——父进程链、
|
|
4
|
+
// 自己的 cwd、客户端写在磁盘上的会话记录。**一条映射表都不写**:没有「进程名 → 品牌」
|
|
5
|
+
// 的白名单,那些是猜;这一整块东西唯一的用处就是认出是谁,**显示错了比不显示更坏**,
|
|
6
|
+
// 所以每一段都有「没证据就是 null」这条出口——宁可少显示一段,不许编。
|
|
7
|
+
|
|
8
|
+
import fsMod from "node:fs";
|
|
9
|
+
import osMod from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import zlibMod from "node:zlib";
|
|
12
|
+
import { execFileSync } from "node:child_process";
|
|
13
|
+
|
|
14
|
+
import { clientPid } from "./session-id.mjs";
|
|
15
|
+
import { isWinRoot, isWinTerminal, winProc } from "./proc-win.mjs";
|
|
16
|
+
|
|
17
|
+
/* 字段一律截断后再往外发:这些值都来自别人(客户端字符串、目录名、会话标题) */
|
|
18
|
+
export function clip(v, max) {
|
|
19
|
+
if (typeof v !== "string") return null;
|
|
20
|
+
const s = v.trim();
|
|
21
|
+
if (!s) return null;
|
|
22
|
+
return s.length > max ? s.slice(0, max) : s;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function procSource(exec = execFileSync, { platform = process.platform } = {}) {
|
|
26
|
+
if (platform === "win32") return winProc(exec);
|
|
27
|
+
const memo = new Map();
|
|
28
|
+
return {
|
|
29
|
+
get(pid) {
|
|
30
|
+
if (!Number.isInteger(pid) || pid <= 1) return null;
|
|
31
|
+
if (memo.has(pid)) return memo.get(pid);
|
|
32
|
+
let v = null;
|
|
33
|
+
try {
|
|
34
|
+
const out = exec("/bin/ps", ["-o", "ppid=,tty=,command=", "-p", String(pid)], {
|
|
35
|
+
encoding: "utf8",
|
|
36
|
+
timeout: 2000,
|
|
37
|
+
});
|
|
38
|
+
const m = /^\s*(\d+)\s+(\S+)\s+([\s\S]*)$/.exec(String(out || "").trim());
|
|
39
|
+
if (m) v = { ppid: Number(m[1]), tty: m[2], command: m[3].trim() };
|
|
40
|
+
} catch {
|
|
41
|
+
}
|
|
42
|
+
memo.set(pid, v);
|
|
43
|
+
return v;
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function hasTty(tty) {
|
|
49
|
+
return !!tty && tty !== "??" && tty !== "?" && tty !== "-";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/*
|
|
53
|
+
* 从命令行里认出 macOS 的 .app 包名:`/Applications/Qoder CN.app/Contents/MacOS/Electron`
|
|
54
|
+
* → `Qoder CN`。认包名而不是可执行文件名,因为后者常常是 `Electron` / `claude` 这种
|
|
55
|
+
* 答不出品牌的东西。
|
|
56
|
+
*/
|
|
57
|
+
export function bundleName(command) {
|
|
58
|
+
return bundleMatch(command)?.name || null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function bundleMatch(command) {
|
|
62
|
+
const s = String(command || "");
|
|
63
|
+
const marker = ".app/Contents/MacOS/";
|
|
64
|
+
const i = s.indexOf(marker);
|
|
65
|
+
if (i < 0) return null;
|
|
66
|
+
const head = s.slice(0, i);
|
|
67
|
+
if (!head.startsWith("/") || / -/.test(head)) return null;
|
|
68
|
+
const outerHead = s.slice(0, s.indexOf(".app/"));
|
|
69
|
+
const name = clip(outerHead.slice(outerHead.lastIndexOf("/") + 1), 40);
|
|
70
|
+
return name ? { name, appDir: `${outerHead}.app` } : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const bundleVersionMemo = new Map();
|
|
74
|
+
export function readBundleVersion(appDir, { exec = execFileSync } = {}) {
|
|
75
|
+
if (!appDir || typeof appDir !== "string") return null;
|
|
76
|
+
if (bundleVersionMemo.has(appDir)) return bundleVersionMemo.get(appDir);
|
|
77
|
+
let v = null;
|
|
78
|
+
try {
|
|
79
|
+
const out = /\.exe$/i.test(appDir)
|
|
80
|
+
? exec(
|
|
81
|
+
"powershell.exe",
|
|
82
|
+
["-NoProfile", "-NonInteractive", "-Command", "(Get-Item -LiteralPath $env:AIC_EXE).VersionInfo.ProductVersion"],
|
|
83
|
+
{
|
|
84
|
+
encoding: "utf8",
|
|
85
|
+
timeout: 4000,
|
|
86
|
+
windowsHide: true,
|
|
87
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
88
|
+
env: { ...process.env, AIC_EXE: appDir },
|
|
89
|
+
}
|
|
90
|
+
)
|
|
91
|
+
: exec(
|
|
92
|
+
"/usr/bin/plutil",
|
|
93
|
+
["-extract", "CFBundleShortVersionString", "raw", "-o", "-", path.join(appDir, "Contents", "Info.plist")],
|
|
94
|
+
{ encoding: "utf8", timeout: 2000 }
|
|
95
|
+
);
|
|
96
|
+
v = clip(String(out || "").trim(), 20);
|
|
97
|
+
} catch {
|
|
98
|
+
}
|
|
99
|
+
bundleVersionMemo.set(appDir, v);
|
|
100
|
+
return v;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const NOT_A_BRAND = new Set([
|
|
104
|
+
"node", "node.js", "deno", "bun", "python", "python3", "java", "ruby", "perl",
|
|
105
|
+
"electron", "sh", "bash", "zsh", "fish", "dash", "login", "tmux", "screen",
|
|
106
|
+
"ssh", "sshd", "code", "cli", "main", "app", "helper", "launchd",
|
|
107
|
+
]);
|
|
108
|
+
|
|
109
|
+
export function binShimName(command) {
|
|
110
|
+
const m = /[\\/]node_modules[\\/]\.bin[\\/]([\w.\-+]{2,40})(?:[\s]|$)/.exec(String(command || ""));
|
|
111
|
+
if (!m) return null;
|
|
112
|
+
const base = m[1].replace(/\.(cmd|exe|bat|ps1)$/i, "");
|
|
113
|
+
if (!base || NOT_A_BRAND.has(base.toLowerCase())) return null;
|
|
114
|
+
return clip(base, 40);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function plainName(command) {
|
|
118
|
+
const s = String(command || "").trim();
|
|
119
|
+
if (!s || s.startsWith("-")) return null;
|
|
120
|
+
const m = /^"([^"]+)"/.exec(s);
|
|
121
|
+
const argv0 = m ? m[1] : s.split(/\s/)[0];
|
|
122
|
+
const cut = Math.max(argv0.lastIndexOf("/"), argv0.lastIndexOf("\\"));
|
|
123
|
+
const base = argv0.slice(cut + 1).replace(/\.(exe|cmd|bat|com)$/i, "");
|
|
124
|
+
if (!base || NOT_A_BRAND.has(base.toLowerCase())) return null;
|
|
125
|
+
if (!/^[\w.\-+]{2,40}$/.test(base)) return null;
|
|
126
|
+
return clip(base, 40);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function exePathOf(command) {
|
|
130
|
+
const s = String(command || "").trim();
|
|
131
|
+
const m = /^"([^"]+)"/.exec(s);
|
|
132
|
+
const argv0 = m ? m[1] : s.split(/\s/)[0];
|
|
133
|
+
return /\.exe$/i.test(argv0) && /[\\/]/.test(argv0) ? argv0 : null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/*
|
|
137
|
+
* 沿父进程链找形态与品牌的证据,先撞见哪个算哪个:
|
|
138
|
+
*
|
|
139
|
+
* 撞见有终端的进程 → CLI(从命令行起来的)
|
|
140
|
+
* 撞见 .app 包 → 桌面端,顺带拿到包名当品牌候选
|
|
141
|
+
* 一路走到 launchd 都没终端 → 桌面端(GUI 进程的典型形状,如 ZCode)
|
|
142
|
+
*
|
|
143
|
+
* Windows 上三条证据各有对应物,判据不同、结论一模一样:
|
|
144
|
+
*
|
|
145
|
+
* 撞见终端宿主进程 → CLI(那边没有 tty 这一列,认进程名,
|
|
146
|
+
* 见 proc-win.mjs 的 TERMINALS)
|
|
147
|
+
* 撞见 explorer.exe 这类桌面根 → 桌面端,**上一跳**就是那个 GUI 进程
|
|
148
|
+
* (对应 macOS 的「launchd 直属」)
|
|
149
|
+
* 链在半路断了(父进程已退出,很常见) → 同上,按最后见到的那一跳算桌面端
|
|
150
|
+
*
|
|
151
|
+
* 最后两条要拿 `prev` 兜:Windows 的桌面根(explorer.exe)自己也是个普通进程,
|
|
152
|
+
* 不像 launchd 那样能靠 `ppid <= 1` 认出来,撞见时当前这一跳已经不是客户端了。
|
|
153
|
+
*
|
|
154
|
+
* 走不到任何一条(ps / PowerShell 不可用、链断在第一跳)就返回 null——不显示形态,也不猜。
|
|
155
|
+
*/
|
|
156
|
+
export function walkSurface(startPid, snap, { maxHops = 6, platform = process.platform } = {}) {
|
|
157
|
+
const win = platform === "win32";
|
|
158
|
+
const none = { surface: null, brand: null, appDir: null, why: "无证据" };
|
|
159
|
+
let pid = Number(startPid);
|
|
160
|
+
let prev = null;
|
|
161
|
+
for (let hop = 0; hop < maxHops; hop++) {
|
|
162
|
+
if (!Number.isInteger(pid) || pid <= 1) break;
|
|
163
|
+
const p = snap.get(pid);
|
|
164
|
+
if (!p) return win && prev ? guiSurface(prev, `父进程已退出@${pid}`) : none;
|
|
165
|
+
if (hasTty(p.tty)) return { surface: "cli", brand: binShimName(p.command), appDir: null, why: `${p.tty}@${pid}` };
|
|
166
|
+
if (win && isWinTerminal(p.name)) return { surface: "cli", brand: binShimName(p.command), appDir: null, why: `${p.name}@${pid}` };
|
|
167
|
+
if (win && isWinRoot(p.name)) return prev ? guiSurface(prev, `${p.name} 直属@${pid}`) : none;
|
|
168
|
+
const b = bundleMatch(p.command);
|
|
169
|
+
if (b) return { surface: "app", brand: b.name, appDir: b.appDir, why: `${b.name}.app@${pid}` };
|
|
170
|
+
if (!Number.isInteger(p.ppid) || p.ppid <= 1) {
|
|
171
|
+
return { surface: "app", brand: plainName(p.command) || binShimName(p.command), appDir: null, why: `launchd 直属、无终端@${pid}` };
|
|
172
|
+
}
|
|
173
|
+
prev = { ...p, pid };
|
|
174
|
+
pid = p.ppid;
|
|
175
|
+
}
|
|
176
|
+
return none;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function guiSurface(p, why) {
|
|
180
|
+
return {
|
|
181
|
+
surface: "app",
|
|
182
|
+
brand: plainName(p.command) || binShimName(p.command),
|
|
183
|
+
appDir: exePathOf(p.command),
|
|
184
|
+
why: `${why},取 ${p.pid}`,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function userDataDirFrom(startPid, snap, { fs = fsMod, maxHops = 6 } = {}) {
|
|
189
|
+
let pid = Number(startPid);
|
|
190
|
+
for (let hop = 0; hop < maxHops; hop++) {
|
|
191
|
+
if (!Number.isInteger(pid) || pid <= 1) break;
|
|
192
|
+
const p = snap.get(pid);
|
|
193
|
+
if (!p) break;
|
|
194
|
+
const i = String(p.command || "").indexOf("--user-data-dir=");
|
|
195
|
+
if (i >= 0) {
|
|
196
|
+
const rest = p.command.slice(i + "--user-data-dir=".length);
|
|
197
|
+
const cut = rest.search(/ --[A-Za-z]/);
|
|
198
|
+
for (const cand of [cut >= 0 ? rest.slice(0, cut) : rest, rest]) {
|
|
199
|
+
const v = cand.trim();
|
|
200
|
+
if (!path.isAbsolute(v)) continue;
|
|
201
|
+
try {
|
|
202
|
+
if (fs.statSync(v).isDirectory()) return v;
|
|
203
|
+
} catch {}
|
|
204
|
+
}
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
pid = p.ppid;
|
|
208
|
+
}
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/*
|
|
213
|
+
* 真正的客户端进程:跳过那些「只为拉起我们而存在」的一次性启动器。
|
|
214
|
+
*
|
|
215
|
+
* 走链这件事**只有一份实现**(session-id.mjs 的 clientPid)——sid 那边和身份这边必须
|
|
216
|
+
* 认到同一个进程,否则会话归属和卡片上的身份会对不上。这里只负责换个取数口:ps 快照
|
|
217
|
+
* 已经在手上了(同一张,一跳都不额外花进程),快照里没有的进程按「读不到」处理。
|
|
218
|
+
*/
|
|
219
|
+
export function resolveClientPid(ppid, snap, self, { maxHops = 3 } = {}) {
|
|
220
|
+
return clientPid({
|
|
221
|
+
ppid: Number(ppid),
|
|
222
|
+
self,
|
|
223
|
+
maxHops,
|
|
224
|
+
info: (pid) => snap.get(pid) || { ppid: null, command: "" },
|
|
225
|
+
}).pid;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/*
|
|
229
|
+
* 这一段对话开在哪。cwd 往上找 `.git`(worktree 里它是个文件,一样算),找到就报
|
|
230
|
+
* 仓库/工作树的目录名;没有 git 就报 cwd 的目录名。
|
|
231
|
+
*
|
|
232
|
+
* 四种情况报 null:cwd 是 `/`(桌面端 chat 模式就是这样拉起 server 的,它本来就没有
|
|
233
|
+
* 工作区);cwd 就是家目录(那不是「哪个项目」,报出来是噪音);cwd 在临时目录里;
|
|
234
|
+
* cwd 路径上有隐藏目录段、且一路上没找到 git。后两条是同一类:客户端把我们 spawn 在
|
|
235
|
+
* 它自己的内部目录里,那是它的管道工程,不是用户开着的项目。
|
|
236
|
+
*
|
|
237
|
+
* 隐藏目录那条只否得掉目录名兜底,否不掉已经找到的 git 检出——`.claude/worktrees/<名>`
|
|
238
|
+
* 底下的 worktree、`~/.config/nvim` 这类点目录里的真项目都要认出来。
|
|
239
|
+
*/
|
|
240
|
+
export function readWorkspace(cwd, { fs = fsMod, home = osMod.homedir(), tmp } = {}) {
|
|
241
|
+
const start = typeof cwd === "string" && cwd ? path.resolve(cwd) : null;
|
|
242
|
+
if (!start || start === "/" || start === path.parse(start).root) return null;
|
|
243
|
+
const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
|
244
|
+
const sameAs = (a, b) => fold(a) === fold(b);
|
|
245
|
+
const under = (p, base) => fold(p).startsWith(fold(base) + path.sep);
|
|
246
|
+
const tmps = tmp !== undefined ? [tmp] : [osMod.tmpdir(), "/tmp", "/private/tmp"];
|
|
247
|
+
for (const t of tmps) {
|
|
248
|
+
const r = t && path.resolve(t);
|
|
249
|
+
if (r && (sameAs(start, r) || under(start, r))) return null;
|
|
250
|
+
}
|
|
251
|
+
const hiddenSeg = start.split(path.sep).some((seg) => seg.length > 1 && seg.startsWith("."));
|
|
252
|
+
const homeAbs = home ? path.resolve(home) : null;
|
|
253
|
+
let dir = start;
|
|
254
|
+
for (let i = 0; i < 64; i++) {
|
|
255
|
+
if (homeAbs && sameAs(dir, homeAbs)) break;
|
|
256
|
+
try {
|
|
257
|
+
if (fs.existsSync(path.join(dir, ".git"))) return { name: clip(path.basename(dir), 40), kind: "git" };
|
|
258
|
+
} catch {}
|
|
259
|
+
const up = path.dirname(dir);
|
|
260
|
+
if (!up || up === dir) break;
|
|
261
|
+
dir = up;
|
|
262
|
+
}
|
|
263
|
+
if (hiddenSeg) return null;
|
|
264
|
+
if (homeAbs && sameAs(start, homeAbs)) return null;
|
|
265
|
+
return { name: clip(path.basename(start), 40), kind: "dir" };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function readClientSessionFile(pid, { fs = fsMod, home = osMod.homedir() } = {}) {
|
|
269
|
+
if (!Number.isInteger(pid) || pid <= 1 || !home) return null;
|
|
270
|
+
try {
|
|
271
|
+
const d = JSON.parse(fs.readFileSync(path.join(home, ".claude", "sessions", `${pid}.json`), "utf8"));
|
|
272
|
+
if (!d || typeof d !== "object" || Number(d.pid) !== pid) return null;
|
|
273
|
+
return d;
|
|
274
|
+
} catch {
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export function readHostSessionTitle(hostSessionId, { fs = fsMod, home = osMod.homedir(), env = process.env } = {}) {
|
|
280
|
+
const id = clip(hostSessionId, 100);
|
|
281
|
+
if (!id || !/^[\w.-]+$/.test(id) || !home) return null;
|
|
282
|
+
const roaming = path.join(home, "AppData", "Roaming");
|
|
283
|
+
const appdata = env?.APPDATA && (env.APPDATA === roaming || env.APPDATA.startsWith(home + path.sep)) ? env.APPDATA : roaming;
|
|
284
|
+
const roots = [
|
|
285
|
+
path.join(home, "Library", "Application Support", "Claude", "claude-code-sessions"),
|
|
286
|
+
path.join(appdata, "Claude", "claude-code-sessions"),
|
|
287
|
+
];
|
|
288
|
+
const dirs = (p) => {
|
|
289
|
+
try {
|
|
290
|
+
return fs.readdirSync(p, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
291
|
+
} catch {
|
|
292
|
+
return [];
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
for (const root of roots) {
|
|
296
|
+
for (const a of dirs(root)) {
|
|
297
|
+
for (const b of dirs(path.join(root, a))) {
|
|
298
|
+
try {
|
|
299
|
+
const d = JSON.parse(fs.readFileSync(path.join(root, a, b, `${id}.json`), "utf8"));
|
|
300
|
+
const t = clip(d?.title, 60);
|
|
301
|
+
if (t) return t;
|
|
302
|
+
} catch {}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/*
|
|
310
|
+
* 这一次调用是主会话发的,还是它派出去的某个 subagent 发的——以及那个子任务叫什么。
|
|
311
|
+
*
|
|
312
|
+
* 归属证据在客户端自己写的记录里,一条都不用猜:`~/.claude/sessions/<客户端 pid>.json`
|
|
313
|
+
* 给出会话 id,`~/.claude/projects/<cwd 转写>/<会话 id>/subagents/agent-<id>.meta.json`
|
|
314
|
+
* 给出这个子任务的 `description`(派它出去时写的那句任务名),`agent-<id>.jsonl` 里
|
|
315
|
+
* 是它自己发起的每一次工具调用。
|
|
316
|
+
*
|
|
317
|
+
* 「这一帧是谁发的」靠 toolUseId **精确匹配**,不靠时间窗口猜;抢在落盘前(毫秒级竞态)
|
|
318
|
+
* 就返回 null,下一帧补上。**绝不退而猜「最近活跃的那个子任务」**:并行子任务下猜错,
|
|
319
|
+
* 就是把 A 开的页记到 B 名下,那比不显示坏得多。
|
|
320
|
+
*/
|
|
321
|
+
const SUBAGENT_MEMO_MAX = 200;
|
|
322
|
+
const SUBAGENT_FRESH_MS = 15 * 60_000;
|
|
323
|
+
const SUBAGENT_DIR_MISS_MS = 30_000;
|
|
324
|
+
const subagentMemo = new Map();
|
|
325
|
+
const subagentDirMemo = new Map();
|
|
326
|
+
let lastSubagentFile = null;
|
|
327
|
+
|
|
328
|
+
export function resetSubagentMemo() {
|
|
329
|
+
subagentMemo.clear();
|
|
330
|
+
subagentDirMemo.clear();
|
|
331
|
+
lastSubagentFile = null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function subagentDir(local, { fs = fsMod, home = osMod.homedir() } = {}) {
|
|
335
|
+
const file = readClientSessionFile(local?.clientPid, { fs, home });
|
|
336
|
+
const id = clip(file?.sessionId, 100);
|
|
337
|
+
if (!id || !/^[A-Za-z0-9_-]+$/.test(id) || !home) return null;
|
|
338
|
+
const memo = subagentDirMemo.get(id);
|
|
339
|
+
if (memo && (memo.dir || Date.now() - memo.at < SUBAGENT_DIR_MISS_MS)) return memo.dir;
|
|
340
|
+
const root = path.join(home, ".claude", "projects");
|
|
341
|
+
const cands = [];
|
|
342
|
+
if (typeof file.cwd === "string" && file.cwd) cands.push(file.cwd.replace(/[^A-Za-z0-9]/g, "-"));
|
|
343
|
+
try {
|
|
344
|
+
for (const e of fs.readdirSync(root, { withFileTypes: true })) {
|
|
345
|
+
if (e.isDirectory() && !cands.includes(e.name)) cands.push(e.name);
|
|
346
|
+
}
|
|
347
|
+
} catch {}
|
|
348
|
+
let dir = null;
|
|
349
|
+
for (const c of cands) {
|
|
350
|
+
const d = path.join(root, c, id, "subagents");
|
|
351
|
+
try {
|
|
352
|
+
if (fs.existsSync(d)) {
|
|
353
|
+
dir = d;
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
} catch {}
|
|
357
|
+
}
|
|
358
|
+
if (subagentDirMemo.size >= SUBAGENT_MEMO_MAX) subagentDirMemo.clear();
|
|
359
|
+
subagentDirMemo.set(id, { dir, at: Date.now() });
|
|
360
|
+
return dir;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function tailIncludes(file, needle, fs) {
|
|
364
|
+
const MAX = 512 * 1024;
|
|
365
|
+
try {
|
|
366
|
+
let size = 0;
|
|
367
|
+
try {
|
|
368
|
+
size = fs.statSync(file).size;
|
|
369
|
+
} catch {}
|
|
370
|
+
if (size > MAX && fs.openSync && fs.readSync) {
|
|
371
|
+
const fd = fs.openSync(file, "r");
|
|
372
|
+
try {
|
|
373
|
+
const buf = Buffer.alloc(MAX);
|
|
374
|
+
const n = fs.readSync(fd, buf, 0, MAX, size - MAX);
|
|
375
|
+
return buf.toString("utf8", 0, n).includes(needle);
|
|
376
|
+
} finally {
|
|
377
|
+
try {
|
|
378
|
+
fs.closeSync(fd);
|
|
379
|
+
} catch {}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return fs.readFileSync(file, "utf8").includes(needle);
|
|
383
|
+
} catch {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
export function readClaudeSubagent(meta, local, { fs = fsMod, home = osMod.homedir() } = {}) {
|
|
389
|
+
const id = meta && typeof meta === "object" ? String(meta["claudecode/toolUseId"] || "") : "";
|
|
390
|
+
if (!/^toolu_[A-Za-z0-9_-]{1,64}$/.test(id) || !local) return null;
|
|
391
|
+
const hit = subagentMemo.get(id);
|
|
392
|
+
if (hit) return hit;
|
|
393
|
+
const dir = subagentDir(local, { fs, home });
|
|
394
|
+
if (!dir) return null;
|
|
395
|
+
let names = [];
|
|
396
|
+
try {
|
|
397
|
+
names = fs.readdirSync(dir).filter((f) => /^agent-.+\.jsonl$/.test(f));
|
|
398
|
+
} catch {
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
const now = Date.now();
|
|
402
|
+
const fresh = [];
|
|
403
|
+
for (const f of names) {
|
|
404
|
+
const p = path.join(dir, f);
|
|
405
|
+
let mt = 0;
|
|
406
|
+
try {
|
|
407
|
+
mt = fs.statSync(p).mtimeMs;
|
|
408
|
+
} catch {
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
if (now - mt > SUBAGENT_FRESH_MS) continue;
|
|
412
|
+
fresh.push({ p, mt });
|
|
413
|
+
}
|
|
414
|
+
fresh.sort((a, b) => b.mt - a.mt);
|
|
415
|
+
const i = lastSubagentFile ? fresh.findIndex((x) => x.p === lastSubagentFile) : -1;
|
|
416
|
+
if (i > 0) fresh.unshift(...fresh.splice(i, 1));
|
|
417
|
+
for (const { p } of fresh.slice(0, 8)) {
|
|
418
|
+
if (!tailIncludes(p, id, fs)) continue;
|
|
419
|
+
lastSubagentFile = p;
|
|
420
|
+
let info = null;
|
|
421
|
+
try {
|
|
422
|
+
const d = JSON.parse(fs.readFileSync(p.replace(/\.jsonl$/, ".meta.json"), "utf8"));
|
|
423
|
+
const label = clip(d?.description, 60);
|
|
424
|
+
const type = clip(d?.agentType, 40);
|
|
425
|
+
if (label || type) info = { label: label || null, type: type || null };
|
|
426
|
+
} catch {}
|
|
427
|
+
if (!info) return null;
|
|
428
|
+
if (subagentMemo.size >= SUBAGENT_MEMO_MAX) subagentMemo.clear();
|
|
429
|
+
subagentMemo.set(id, info);
|
|
430
|
+
return info;
|
|
431
|
+
}
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
export function readWorkbuddySessionTitle({ env = process.env, fs = fsMod, exec = execFileSync, alive = pidAlive } = {}) {
|
|
436
|
+
const dir = typeof env.WORKBUDDY_CONFIG_DIR === "string" ? env.WORKBUDDY_CONFIG_DIR : "";
|
|
437
|
+
if (!path.isAbsolute(dir)) return null;
|
|
438
|
+
const live = [];
|
|
439
|
+
try {
|
|
440
|
+
for (const f of fs.readdirSync(path.join(dir, "sessions")).slice(0, 100)) {
|
|
441
|
+
if (!f.endsWith(".json")) continue;
|
|
442
|
+
try {
|
|
443
|
+
const d = JSON.parse(fs.readFileSync(path.join(dir, "sessions", f), "utf8"));
|
|
444
|
+
if (d?.kind !== "interactive") continue;
|
|
445
|
+
const sid = String(d.sessionId || "");
|
|
446
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid)) continue;
|
|
447
|
+
if (!Number.isInteger(d.pid) || d.pid <= 1 || !alive(d.pid)) continue;
|
|
448
|
+
live.push(sid);
|
|
449
|
+
} catch {}
|
|
450
|
+
}
|
|
451
|
+
} catch {
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
if (live.length !== 1) return null;
|
|
455
|
+
try {
|
|
456
|
+
const out = exec(
|
|
457
|
+
process.platform === "win32" ? "sqlite3" : "/usr/bin/sqlite3",
|
|
458
|
+
["-readonly", path.join(dir, "workbuddy.db"), `select coalesce(custom_title, title) from sessions where id='${live[0]}' and deleted_at is null`],
|
|
459
|
+
{ encoding: "utf8", timeout: 2000 }
|
|
460
|
+
);
|
|
461
|
+
return clip(String(out || "").trim(), 60);
|
|
462
|
+
} catch {
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export function pidAlive(pid) {
|
|
468
|
+
try {
|
|
469
|
+
process.kill(pid, 0);
|
|
470
|
+
return true;
|
|
471
|
+
} catch {
|
|
472
|
+
return false;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
export function informativeName(name) {
|
|
477
|
+
const s = clip(name, 40);
|
|
478
|
+
if (!s) return null;
|
|
479
|
+
if (/^local-agent-mode-/i.test(s)) return null;
|
|
480
|
+
if (s.includes(":")) return null;
|
|
481
|
+
return s;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/*
|
|
485
|
+
* 本机取证的那几段(品牌兜底、形态、工作区、会话记录位置)。跟 clientInfo 无关的
|
|
486
|
+
* 部分在一个进程里是不变的,所以调用方算一次就够;会话标题另算(见上)。
|
|
487
|
+
*/
|
|
488
|
+
export function probeLocal({
|
|
489
|
+
env = process.env,
|
|
490
|
+
cwd = process.cwd(),
|
|
491
|
+
ppid = process.ppid,
|
|
492
|
+
self = process.argv[1],
|
|
493
|
+
snap = null,
|
|
494
|
+
fs = fsMod,
|
|
495
|
+
home = osMod.homedir(),
|
|
496
|
+
tmp,
|
|
497
|
+
exec = execFileSync,
|
|
498
|
+
platform = process.platform,
|
|
499
|
+
} = {}) {
|
|
500
|
+
const s = snap || procSource(exec, { platform });
|
|
501
|
+
const clientPid = resolveClientPid(ppid, s, self);
|
|
502
|
+
const walked = walkSurface(clientPid, s, { platform });
|
|
503
|
+
const clientCommand = s.get(clientPid)?.command || null;
|
|
504
|
+
const file = readClientSessionFile(clientPid, { fs, home });
|
|
505
|
+
|
|
506
|
+
const entrypoint = clip(file?.entrypoint || env.CLAUDE_CODE_ENTRYPOINT, 30);
|
|
507
|
+
const surface = entrypoint === "cli" ? "cli" : walked.surface;
|
|
508
|
+
|
|
509
|
+
const ws = readWorkspace(file?.cwd || cwd, tmp !== undefined ? { fs, home, tmp } : { fs, home });
|
|
510
|
+
|
|
511
|
+
return {
|
|
512
|
+
brandFallback: walked.brand,
|
|
513
|
+
brandAppDir: walked.appDir || null,
|
|
514
|
+
surface,
|
|
515
|
+
workspace: ws?.name || null,
|
|
516
|
+
workspaceKind: ws?.kind || null,
|
|
517
|
+
userDataDir: userDataDirFrom(ppid, s, { fs }),
|
|
518
|
+
hostSessionId: clip(env.CLAUDE_CODE_HOST_SESSION_ID, 100),
|
|
519
|
+
clientPid,
|
|
520
|
+
clientCommand,
|
|
521
|
+
sessionName: file && file.nameSource !== "derived" ? clip(file.name, 60) : null,
|
|
522
|
+
why: walked.why,
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const titleMemo = new Map();
|
|
527
|
+
const TITLE_MISS_BACKOFF_MS = 20_000;
|
|
528
|
+
const TITLE_MISS_BACKOFF_MAX_MS = 300_000;
|
|
529
|
+
const TITLE_MEMO_MAX = 200;
|
|
530
|
+
function missBackoff(misses) {
|
|
531
|
+
return Math.min(TITLE_MISS_BACKOFF_MS * 2 ** Math.max(0, misses - 1), TITLE_MISS_BACKOFF_MAX_MS);
|
|
532
|
+
}
|
|
533
|
+
function memoTitle(key, lookup, now = Date.now()) {
|
|
534
|
+
const hit = titleMemo.get(key);
|
|
535
|
+
if (hit && (hit.title || now < hit.nextTryAt)) return hit.title;
|
|
536
|
+
let title = null;
|
|
537
|
+
try {
|
|
538
|
+
title = lookup();
|
|
539
|
+
} catch {
|
|
540
|
+
title = null;
|
|
541
|
+
}
|
|
542
|
+
if (titleMemo.size >= TITLE_MEMO_MAX) titleMemo.clear();
|
|
543
|
+
const misses = title ? 0 : (hit?.misses || 0) + 1;
|
|
544
|
+
titleMemo.set(key, { title, misses, nextTryAt: now + missBackoff(misses) });
|
|
545
|
+
return title;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export function resetTitleMemo() {
|
|
549
|
+
titleMemo.clear();
|
|
550
|
+
dshCwdMemo.clear();
|
|
551
|
+
agWsMemo.clear();
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
export function zcodeDataDir({ env = process.env, home = osMod.homedir() } = {}) {
|
|
555
|
+
const base = typeof env.ZCODE_DATA_BASE_DIR === "string" ? env.ZCODE_DATA_BASE_DIR.trim() : "";
|
|
556
|
+
return path.join(base || home, ".zcode");
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
export function readZcodeSessionTitle(meta, { env = process.env, home = osMod.homedir(), fs = fsMod, exec = execFileSync } = {}) {
|
|
560
|
+
const id = meta && typeof meta === "object" ? String(meta.session_id || "") : "";
|
|
561
|
+
const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
562
|
+
const isMain = new RegExp(`^sess_${UUID}$`, "i").test(id);
|
|
563
|
+
const isSub = new RegExp(`^sess_subagent_agent_${UUID}$`, "i").test(id);
|
|
564
|
+
if (!isMain && !isSub) return null;
|
|
565
|
+
const db = path.join(zcodeDataDir({ env, home }), "cli", "db", "db.sqlite");
|
|
566
|
+
if (!fs.existsSync(db)) return null;
|
|
567
|
+
const sql = isSub
|
|
568
|
+
? `select title from session where id=(select parent_id from session where id='${id}') and title_source in ('generated','custom')`
|
|
569
|
+
: `select title from session where id='${id}' and title_source in ('generated','custom')`;
|
|
570
|
+
return memoTitle(`zcode:${db}:${id}`, () => {
|
|
571
|
+
const out = exec("/usr/bin/sqlite3", ["-readonly", db, sql], { encoding: "utf8", timeout: 2000 });
|
|
572
|
+
return clip(String(out || "").trim(), 60);
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const TRAE_WINDOW_MS = 15 * 60_000;
|
|
577
|
+
const TRAE_MAX_SCAN = 64 << 20;
|
|
578
|
+
const LINE_TS = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+[+-]\d{2}:\d{2})/;
|
|
579
|
+
|
|
580
|
+
export function traeDataDir({ userDataDir = null, appDir = null, env = process.env, fs = fsMod, home = osMod.homedir() } = {}) {
|
|
581
|
+
if (typeof userDataDir === "string" && path.isAbsolute(userDataDir) && fs.existsSync(path.join(userDataDir, "logs"))) {
|
|
582
|
+
return userDataDir;
|
|
583
|
+
}
|
|
584
|
+
const rg = /^((?:\/|[A-Za-z]:[\\/]).+?\.app)[\\/]/.exec(String(env.RG_PATH || ""));
|
|
585
|
+
const bundles = [typeof appDir === "string" && appDir.endsWith(".app") ? appDir : null, rg ? rg[1] : null];
|
|
586
|
+
for (const bundle of bundles) {
|
|
587
|
+
if (!bundle) continue;
|
|
588
|
+
let product;
|
|
589
|
+
try {
|
|
590
|
+
product = JSON.parse(fs.readFileSync(path.join(bundle, "Contents", "Resources", "app", "product.json"), "utf8"));
|
|
591
|
+
} catch {
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
if (!/^trae(-|$)/.test(String(product?.applicationName || ""))) continue;
|
|
595
|
+
const name = clip(product?.nameLong, 40);
|
|
596
|
+
if (!name || name.includes("/")) continue;
|
|
597
|
+
const dir = path.join(home, "Library", "Application Support", name);
|
|
598
|
+
if (fs.existsSync(path.join(dir, "logs"))) return dir;
|
|
599
|
+
}
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function traeLogFiles(dataDir, fs) {
|
|
604
|
+
const out = [];
|
|
605
|
+
const root = path.join(dataDir, "logs");
|
|
606
|
+
let dirs;
|
|
607
|
+
try {
|
|
608
|
+
dirs = fs.readdirSync(root).filter((d) => /^\d{8}T\d{6}$/.test(d));
|
|
609
|
+
} catch {
|
|
610
|
+
return out;
|
|
611
|
+
}
|
|
612
|
+
for (const d of dirs) {
|
|
613
|
+
const dir = path.join(root, d, "Modular");
|
|
614
|
+
let names;
|
|
615
|
+
try {
|
|
616
|
+
names = fs.readdirSync(dir);
|
|
617
|
+
} catch {
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
for (const f of names) {
|
|
621
|
+
const m = /^ai-agent_\d+_(\d{10,16})_stdout\.log$/.exec(f);
|
|
622
|
+
if (m) out.push({ file: path.join(dir, f), at: Number(m[1]) });
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
return out.sort((a, b) => a.at - b.at);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function lineTimeAt(fs, fd, off, size) {
|
|
629
|
+
const len = Math.min(4096, size - off);
|
|
630
|
+
if (len <= 0) return null;
|
|
631
|
+
const b = Buffer.allocUnsafe(len);
|
|
632
|
+
fs.readSync(fd, b, 0, len, off);
|
|
633
|
+
const s = b.toString("utf8");
|
|
634
|
+
const nl = off === 0 ? -1 : s.indexOf("\n");
|
|
635
|
+
const m = LINE_TS.exec(s.slice(nl + 1));
|
|
636
|
+
return m ? { t: Date.parse(m[1]), at: off + nl + 1 } : null;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function seekToTime(fs, fd, size, target) {
|
|
640
|
+
let lo = 0;
|
|
641
|
+
let hi = size;
|
|
642
|
+
let best = 0;
|
|
643
|
+
for (let i = 0; i < 40 && lo < hi; i++) {
|
|
644
|
+
const mid = (lo + hi) >> 1;
|
|
645
|
+
const p = lineTimeAt(fs, fd, mid, size);
|
|
646
|
+
if (!p) {
|
|
647
|
+
hi = mid;
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
if (p.t < target) {
|
|
651
|
+
best = p.at;
|
|
652
|
+
lo = p.at + 1;
|
|
653
|
+
} else hi = mid;
|
|
654
|
+
}
|
|
655
|
+
return best;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function traeScanFile(fs, file, id, fromMs, budget) {
|
|
659
|
+
const needle = `session_id: "${id}", title: "`;
|
|
660
|
+
let fd;
|
|
661
|
+
try {
|
|
662
|
+
fd = fs.openSync(file, "r");
|
|
663
|
+
} catch {
|
|
664
|
+
return { title: null, read: 0 };
|
|
665
|
+
}
|
|
666
|
+
try {
|
|
667
|
+
const size = fs.fstatSync(fd).size;
|
|
668
|
+
let off = fromMs === null ? 0 : seekToTime(fs, fd, size, fromMs);
|
|
669
|
+
const buf = Buffer.allocUnsafe(1 << 22);
|
|
670
|
+
let carry = "";
|
|
671
|
+
let read = 0;
|
|
672
|
+
let title = null;
|
|
673
|
+
while (off < size && read < budget) {
|
|
674
|
+
const n = fs.readSync(fd, buf, 0, buf.length, off);
|
|
675
|
+
if (n <= 0) break;
|
|
676
|
+
off += n;
|
|
677
|
+
read += n;
|
|
678
|
+
const chunk = carry + buf.toString("utf8", 0, n);
|
|
679
|
+
const nl = chunk.lastIndexOf("\n");
|
|
680
|
+
carry = nl < 0 ? chunk : chunk.slice(nl + 1);
|
|
681
|
+
const body = nl < 0 ? "" : chunk.slice(0, nl);
|
|
682
|
+
let i = -1;
|
|
683
|
+
while ((i = body.indexOf(needle, i + 1)) >= 0) {
|
|
684
|
+
const e = body.indexOf('"', i + needle.length);
|
|
685
|
+
if (e > 0) title = body.slice(i + needle.length, e);
|
|
686
|
+
}
|
|
687
|
+
if (title) break;
|
|
688
|
+
if (fromMs !== null) {
|
|
689
|
+
const last = body.slice(body.lastIndexOf("\n") + 1);
|
|
690
|
+
const m = LINE_TS.exec(last);
|
|
691
|
+
if (m && Date.parse(m[1]) > fromMs + TRAE_WINDOW_MS) break;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
return { title: clip(title, 60), read };
|
|
695
|
+
} catch {
|
|
696
|
+
return { title: null, read: 0 };
|
|
697
|
+
} finally {
|
|
698
|
+
try {
|
|
699
|
+
fs.closeSync(fd);
|
|
700
|
+
} catch {}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
export function readTraeSessionTitle(meta, { dataDir = null, fs = fsMod } = {}) {
|
|
705
|
+
const id = meta && typeof meta === "object" ? String(meta.chatSessionId || "") : "";
|
|
706
|
+
if (!/^[0-9a-f]{24}$/i.test(id)) return null;
|
|
707
|
+
if (meta.isCurrentSession === false) return null;
|
|
708
|
+
if (!dataDir) return null;
|
|
709
|
+
const createdMs = parseInt(id.slice(0, 8), 16) * 1000;
|
|
710
|
+
if (!Number.isFinite(createdMs) || createdMs <= 0) return null;
|
|
711
|
+
|
|
712
|
+
return memoTitle(`trae:${dataDir}:${id}`, () => {
|
|
713
|
+
const files = traeLogFiles(dataDir, fs);
|
|
714
|
+
let i = -1;
|
|
715
|
+
for (let k = 0; k < files.length; k++) if (files[k].at <= createdMs) i = k;
|
|
716
|
+
if (i < 0) return null;
|
|
717
|
+
let budget = TRAE_MAX_SCAN;
|
|
718
|
+
for (const c of [files[i], files[i + 1]]) {
|
|
719
|
+
if (!c || budget <= 0) break;
|
|
720
|
+
const r = traeScanFile(fs, c.file, id, c === files[i] ? createdMs : null, budget);
|
|
721
|
+
if (r.title) return r.title;
|
|
722
|
+
budget -= r.read;
|
|
723
|
+
}
|
|
724
|
+
return null;
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
const DSH_LIVE_WINDOW_MS = 10 * 60_000;
|
|
729
|
+
const DSH_MAX_LOG_BYTES = 32 << 20;
|
|
730
|
+
const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
731
|
+
|
|
732
|
+
export function dshHome({ env = process.env, home = osMod.homedir() } = {}) {
|
|
733
|
+
const d = typeof env.DSH_HOME === "string" ? env.DSH_HOME.trim() : "";
|
|
734
|
+
return path.isAbsolute(d) ? d : path.join(home, ".dsh");
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
export function isDshClient(clientCommand) {
|
|
738
|
+
const s = String(clientCommand || "");
|
|
739
|
+
return /@deepseek-ai[\\/]dsh[\\/]/.test(s) || /[\\/]\.bin[\\/]dsh(\.cmd|\.exe|\.bat)?(\s|$)/.test(s);
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
export function decodeZstdFrames(buf, { zlib = zlibMod } = {}) {
|
|
743
|
+
if (typeof zlib.zstdDecompressSync !== "function") return null;
|
|
744
|
+
if (!Buffer.isBuffer(buf) || buf.length > DSH_MAX_LOG_BYTES) return null;
|
|
745
|
+
const parts = [];
|
|
746
|
+
let i = buf.indexOf(ZSTD_MAGIC);
|
|
747
|
+
while (i >= 0) {
|
|
748
|
+
try {
|
|
749
|
+
parts.push(zlib.zstdDecompressSync(buf.subarray(i)));
|
|
750
|
+
} catch {
|
|
751
|
+
}
|
|
752
|
+
i = buf.indexOf(ZSTD_MAGIC, i + 4);
|
|
753
|
+
}
|
|
754
|
+
return parts.length ? Buffer.concat(parts).toString("utf8") : null;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
const dshCwdMemo = new Map();
|
|
758
|
+
|
|
759
|
+
/*
|
|
760
|
+
* 恰好一个活跃会话时返回 { id, title, cwd };分不出(0 个或多个活跃)就 null。
|
|
761
|
+
* title 可能暂缺(LLM 标题是首轮之后才生成的)——cwd 先到先用,两者不互相拖累。
|
|
762
|
+
*/
|
|
763
|
+
export function readDshSession(local, { env = process.env, home = osMod.homedir(), fs = fsMod, now = Date.now() } = {}) {
|
|
764
|
+
if (!local || !isDshClient(local.clientCommand)) return null;
|
|
765
|
+
const root = path.join(dshHome({ env, home }), "sessions");
|
|
766
|
+
const live = [];
|
|
767
|
+
let dirs;
|
|
768
|
+
try {
|
|
769
|
+
dirs = fs.readdirSync(root);
|
|
770
|
+
} catch {
|
|
771
|
+
return null;
|
|
772
|
+
}
|
|
773
|
+
for (const d of dirs.slice(0, 500)) {
|
|
774
|
+
let subs;
|
|
775
|
+
try {
|
|
776
|
+
subs = fs.readdirSync(path.join(root, d));
|
|
777
|
+
} catch {
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
for (const s of subs) {
|
|
781
|
+
if (!s.startsWith("session-")) continue;
|
|
782
|
+
const file = path.join(root, d, s, "session.jsonl.zstd");
|
|
783
|
+
try {
|
|
784
|
+
const st = fs.statSync(file);
|
|
785
|
+
if (now - st.mtimeMs <= DSH_LIVE_WINDOW_MS) live.push({ id: s, file });
|
|
786
|
+
} catch {}
|
|
787
|
+
if (live.length > 1) return null;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
if (live.length !== 1) return null;
|
|
791
|
+
const { id, file } = live[0];
|
|
792
|
+
|
|
793
|
+
let cwd = dshCwdMemo.get(id);
|
|
794
|
+
const title = memoTitle(`dsh:${file}`, () => {
|
|
795
|
+
let text;
|
|
796
|
+
try {
|
|
797
|
+
text = decodeZstdFrames(fs.readFileSync(file));
|
|
798
|
+
} catch {
|
|
799
|
+
return null;
|
|
800
|
+
}
|
|
801
|
+
if (!text) return null;
|
|
802
|
+
let found = null;
|
|
803
|
+
for (const line of text.split("\n")) {
|
|
804
|
+
if (cwd === undefined && line.includes('"type":"session"')) {
|
|
805
|
+
try {
|
|
806
|
+
const h = JSON.parse(line);
|
|
807
|
+
if (h?.type === "session" && typeof h.cwd === "string") {
|
|
808
|
+
cwd = h.cwd;
|
|
809
|
+
if (dshCwdMemo.size >= TITLE_MEMO_MAX) dshCwdMemo.clear();
|
|
810
|
+
dshCwdMemo.set(id, cwd);
|
|
811
|
+
}
|
|
812
|
+
} catch {}
|
|
813
|
+
}
|
|
814
|
+
if (!line.includes('"session/title"')) continue;
|
|
815
|
+
try {
|
|
816
|
+
const ev = JSON.parse(line);
|
|
817
|
+
const kind = ev?.data?.source?.kind;
|
|
818
|
+
if (ev?.type === "session/title" && (kind === "provider" || kind === "user")) {
|
|
819
|
+
const t = clip(ev.data.title, 60);
|
|
820
|
+
if (t) found = t;
|
|
821
|
+
}
|
|
822
|
+
} catch {}
|
|
823
|
+
}
|
|
824
|
+
return found;
|
|
825
|
+
});
|
|
826
|
+
if (cwd === undefined) {
|
|
827
|
+
try {
|
|
828
|
+
const first = zlibMod.zstdDecompressSync ? zlibMod.zstdDecompressSync(fs.readFileSync(file)) : null;
|
|
829
|
+
const h = first ? JSON.parse(first.toString("utf8").split("\n")[0]) : null;
|
|
830
|
+
cwd = h?.type === "session" && typeof h.cwd === "string" ? h.cwd : null;
|
|
831
|
+
} catch {
|
|
832
|
+
cwd = null;
|
|
833
|
+
}
|
|
834
|
+
if (dshCwdMemo.size >= TITLE_MEMO_MAX) dshCwdMemo.clear();
|
|
835
|
+
dshCwdMemo.set(id, cwd);
|
|
836
|
+
}
|
|
837
|
+
return { id, title: title || null, cwd: cwd || null };
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/* 会话 id 进路径与提取流程前的锚(安全边界,勿放宽):只放行 UUID 形状,`..`、`/`、
|
|
841
|
+
* 引号一概进不来——id 来自 MCP 调用方给的 _meta,是外部输入 */
|
|
842
|
+
const AG_CONV_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
843
|
+
|
|
844
|
+
export function antigravityDataDir(clientCommand, { home = osMod.homedir() } = {}) {
|
|
845
|
+
const m = /--app_data_dir[ =]([\w.-]+)/.exec(String(clientCommand || ""));
|
|
846
|
+
const name = m && m[1] !== "." && !m[1].includes("..") ? m[1] : "antigravity-ide";
|
|
847
|
+
return path.join(home, ".gemini", name);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
const agWsMemo = new Map();
|
|
851
|
+
const AG_WS_MISS_MS = 30_000;
|
|
852
|
+
const AG_DB_MAX = 256 << 20;
|
|
853
|
+
|
|
854
|
+
export function antigravityConversationId(meta) {
|
|
855
|
+
const id = meta && typeof meta === "object" ? String(meta["antigravity.google/conversation_id"] || "").trim() : "";
|
|
856
|
+
return AG_CONV_RE.test(id) ? id : null;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
function readVarint(buf, i) {
|
|
860
|
+
let value = 0;
|
|
861
|
+
for (let n = 0; n < 5; n++, i++) {
|
|
862
|
+
if (i >= buf.length) return null;
|
|
863
|
+
const b = buf[i];
|
|
864
|
+
value += (b & 0x7f) * 2 ** (7 * n);
|
|
865
|
+
if (b < 0x80) return { value, next: i + 1 };
|
|
866
|
+
}
|
|
867
|
+
return null;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
const AG_URI_MAX = 4096;
|
|
871
|
+
|
|
872
|
+
function agUriByLength(buf, idBuf) {
|
|
873
|
+
const idLen = idBuf.length;
|
|
874
|
+
for (let at = buf.indexOf(idBuf); at >= 0; at = buf.indexOf(idBuf, at + 1)) {
|
|
875
|
+
if (at < 1 || buf[at - 1] !== idLen) continue;
|
|
876
|
+
const tag = readVarint(buf, at + idLen);
|
|
877
|
+
if (!tag || (tag.value & 7) !== 2) continue;
|
|
878
|
+
const len = readVarint(buf, tag.next);
|
|
879
|
+
if (!len) continue;
|
|
880
|
+
if (len.value < 8 || len.value > AG_URI_MAX || len.next + len.value > buf.length) continue;
|
|
881
|
+
const val = buf.toString("utf8", len.next, len.next + len.value);
|
|
882
|
+
if (!val.startsWith("file://")) continue;
|
|
883
|
+
return val.slice("file://".length);
|
|
884
|
+
}
|
|
885
|
+
return null;
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function agUriToPath(raw) {
|
|
889
|
+
let p;
|
|
890
|
+
try {
|
|
891
|
+
p = decodeURIComponent(raw);
|
|
892
|
+
} catch {
|
|
893
|
+
p = raw;
|
|
894
|
+
}
|
|
895
|
+
return p.replace(/^\/([A-Za-z]:)/, "$1");
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
export function readAntigravityWorkspace(meta, local, { fs = fsMod, home = osMod.homedir() } = {}) {
|
|
899
|
+
const id = antigravityConversationId(meta);
|
|
900
|
+
if (!id) return null;
|
|
901
|
+
const hit = agWsMemo.get(id);
|
|
902
|
+
if (hit && (hit.dir || Date.now() - hit.at < AG_WS_MISS_MS)) return hit.dir;
|
|
903
|
+
let dir = null;
|
|
904
|
+
const db = path.join(antigravityDataDir(local?.clientCommand, { home }), "conversations", `${id}.db`);
|
|
905
|
+
const idBuf = Buffer.from(id);
|
|
906
|
+
for (const file of [db, `${db}-wal`]) {
|
|
907
|
+
let buf;
|
|
908
|
+
try {
|
|
909
|
+
if (fs.statSync(file).size > AG_DB_MAX) continue;
|
|
910
|
+
buf = fs.readFileSync(file);
|
|
911
|
+
} catch {
|
|
912
|
+
continue;
|
|
913
|
+
}
|
|
914
|
+
if (!buf.length || buf.length > AG_DB_MAX) continue;
|
|
915
|
+
const uri = agUriByLength(buf, idBuf);
|
|
916
|
+
if (uri === null) continue;
|
|
917
|
+
const p = agUriToPath(uri);
|
|
918
|
+
if (!path.isAbsolute(p)) continue;
|
|
919
|
+
dir = p;
|
|
920
|
+
break;
|
|
921
|
+
}
|
|
922
|
+
if (agWsMemo.size >= TITLE_MEMO_MAX) agWsMemo.clear();
|
|
923
|
+
agWsMemo.set(id, { dir, at: Date.now() });
|
|
924
|
+
return dir;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
/*
|
|
928
|
+
* 现在这一刻的会话标题。
|
|
929
|
+
*
|
|
930
|
+
* 顺序是**先协议级、后本机取证**,这一条不能反:`params._meta` 里带过来的会话 id 是
|
|
931
|
+
* 调用方自己说的「这一次调用属于哪段对话」,是唯一不含推断成分的证据;本机取证那几条
|
|
932
|
+
* (宿主文件、会话记录、活会话计数)多少都带假设。没有 meta 的客户端走本机取证那几条。
|
|
933
|
+
*
|
|
934
|
+
* 分不出是哪段对话时(整个 app 共用一个 MCP 进程、帧里又没有会话身份)一律返回 null,
|
|
935
|
+
* 不拿时间窗口去猜。
|
|
936
|
+
*/
|
|
937
|
+
export function readSessionTitle(local, { fs = fsMod, home = osMod.homedir(), env = process.env, exec = execFileSync, alive = pidAlive, meta = null, dsh } = {}) {
|
|
938
|
+
if (!local) return null;
|
|
939
|
+
const zc = readZcodeSessionTitle(meta, { env, home, fs, exec });
|
|
940
|
+
if (zc) return zc;
|
|
941
|
+
const tr = readTraeSessionTitle(meta, { fs, dataDir: traeDataDir({ userDataDir: local.userDataDir, appDir: local.brandAppDir, env, fs, home }) });
|
|
942
|
+
if (tr) return tr;
|
|
943
|
+
const ds = dsh !== undefined ? dsh : readDshSession(local, { env, home, fs });
|
|
944
|
+
if (ds?.title) return ds.title;
|
|
945
|
+
const t = readHostSessionTitle(local.hostSessionId, { fs, home, env });
|
|
946
|
+
if (t) return t;
|
|
947
|
+
const file = readClientSessionFile(local.clientPid, { fs, home });
|
|
948
|
+
if (file && file.nameSource !== "derived") return clip(file.name, 60);
|
|
949
|
+
const wb = readWorkbuddySessionTitle({ env, fs, exec, alive });
|
|
950
|
+
if (wb) return wb;
|
|
951
|
+
return local.sessionName || null;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/*
|
|
955
|
+
* 标题 + 会话级工作区,一次归属两样都拿。
|
|
956
|
+
*
|
|
957
|
+
* 工作区也要有会话级的一条:常驻进程型的客户端 spawn 我们时给的 cwd 是它自己启动时所在
|
|
958
|
+
* 的目录,跟「这段对话开在哪个项目」无关,真正的项目写在会话自己的记录里。probeLocal
|
|
959
|
+
* 那份工作区是进程级的、算一次就定死,所以这里另给一条会话级的出口;没有会话级证据的
|
|
960
|
+
* 客户端返回 null,调用方照用进程级的那份。
|
|
961
|
+
*/
|
|
962
|
+
export function readSessionIdentity(local, { fs = fsMod, home = osMod.homedir(), env = process.env, exec = execFileSync, alive = pidAlive, meta = null, tmp } = {}) {
|
|
963
|
+
if (!local) return { title: null, workspace: null, workspaceKind: null };
|
|
964
|
+
const ds = readDshSession(local, { env, home, fs });
|
|
965
|
+
const title = readSessionTitle(local, { fs, home, env, exec, alive, meta, dsh: ds });
|
|
966
|
+
const agDir = readAntigravityWorkspace(meta, local, { fs, home });
|
|
967
|
+
const wsDir = ds?.cwd || agDir;
|
|
968
|
+
const ws = wsDir ? readWorkspace(wsDir, tmp !== undefined ? { fs, home, tmp } : { fs, home }) : null;
|
|
969
|
+
return { title, workspace: ws?.name || null, workspaceKind: ws?.kind || null };
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
/*
|
|
973
|
+
* 拼出发给扩展的那个 agent 对象。`name/title` 是客户端自报的原文(照旧原样带上),
|
|
974
|
+
* `brand/version/surface/workspace/session` 是给人看的那几段。一段证据都没有就返回
|
|
975
|
+
* null——帧里连 agent 键都不加。
|
|
976
|
+
*
|
|
977
|
+
* 品牌的优先级是 **title > 父进程链 > name**:title 是协议里专门留给「人看的名字」的
|
|
978
|
+
* 字段,客户端报了它就是郑重报过家门;没报 title 的,父进程链认到的 .app 包名 / 裸进程名
|
|
979
|
+
* 比 name 可信——name 常常是发协议帧的那层中间件在自报,显示出来就是冒名顶替;链上一点
|
|
980
|
+
* 证据都没有(ps 不可用、真的是裸 CLI)才轮到 name。
|
|
981
|
+
*
|
|
982
|
+
* 版本号必须跟品牌**同源**:品牌来自 clientInfo 就用 clientInfo.version,来自 .app 包就读
|
|
983
|
+
* 包的 Info.plist,来自裸进程名就没有版本。两头各取一段拼出来的版本比不显示还糟。
|
|
984
|
+
*/
|
|
985
|
+
export function composeAgent(clientInfo, local, sessionTitle, { exec = execFileSync } = {}) {
|
|
986
|
+
const name = clip(clientInfo?.name, 40);
|
|
987
|
+
const title = clip(clientInfo?.title, 40);
|
|
988
|
+
const chainBrand = local?.brandFallback || null;
|
|
989
|
+
const brand = title || chainBrand || informativeName(name) || null;
|
|
990
|
+
let version = null;
|
|
991
|
+
if (brand) {
|
|
992
|
+
if (brand === title || !chainBrand) version = clip(clientInfo?.version, 20);
|
|
993
|
+
else version = local?.brandAppDir ? readBundleVersion(local.brandAppDir, { exec }) : null;
|
|
994
|
+
}
|
|
995
|
+
const a = {
|
|
996
|
+
name,
|
|
997
|
+
title,
|
|
998
|
+
version,
|
|
999
|
+
brand,
|
|
1000
|
+
surface: local?.surface || null,
|
|
1001
|
+
workspace: local?.workspace || null,
|
|
1002
|
+
workspaceKind: local?.workspaceKind || null,
|
|
1003
|
+
session: clip(sessionTitle, 60),
|
|
1004
|
+
};
|
|
1005
|
+
if (!a.brand && !a.name && !a.title && !a.workspace && !a.session) return null;
|
|
1006
|
+
return a;
|
|
1007
|
+
}
|