agent-things 0.0.0-stage → 1.2.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 (125) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +5 -0
  3. package/README.md +221 -2
  4. package/README.zh-CN.md +222 -0
  5. package/bin/agent-things.cjs +8 -0
  6. package/bin/antigravity-session-status.cjs +96 -0
  7. package/bin/claude-session-status.cjs +55 -0
  8. package/bin/codex-session-status.cjs +287 -0
  9. package/mods/agent-things-ui/.claude-plugin/plugin.json +12 -0
  10. package/mods/agent-things-ui/SKILL.md +10 -0
  11. package/mods/agent-things-ui/hooks/controls.js +112 -0
  12. package/mods/agent-things-ui/hooks/foundation.js +431 -0
  13. package/mods/agent-things-ui/hooks/hooks.json +1 -0
  14. package/mods/agent-things-ui/hooks/presentation.js +223 -0
  15. package/mods/agent-things-ui/hooks/progress.js +1 -0
  16. package/mods/agent-things-ui/hooks/register.js +382 -0
  17. package/native/bin/bridge +0 -0
  18. package/native/bin/bridge.json +20 -0
  19. package/native/session-status-bridge.swift +280 -0
  20. package/outputs/antigravity-session-status.js +2476 -0
  21. package/outputs/codex-session-status.js +1761 -0
  22. package/package.json +75 -4
  23. package/scripts/build-antigravity-bundle.cjs +35 -0
  24. package/scripts/build-codex-bundle.cjs +31 -0
  25. package/scripts/build-native-bridge.cjs +55 -0
  26. package/scripts/build-shared-ui.cjs +16 -0
  27. package/scripts/setup-antigravity-service.cjs +71 -0
  28. package/scripts/setup-claude-service.cjs +21 -0
  29. package/skills/agent-things/SKILL.en.md +95 -0
  30. package/skills/agent-things/SKILL.md +99 -0
  31. package/skills/codex/things/SKILL.en.md +10 -0
  32. package/skills/codex/things/SKILL.md +10 -0
  33. package/skills/things/SKILL.en.md +10 -0
  34. package/skills/things/SKILL.md +10 -0
  35. package/skills/things/checklist.en.md +91 -0
  36. package/skills/things/checklist.md +95 -0
  37. package/src/analysis-app-server.cjs +74 -0
  38. package/src/analysis-assets/output.en.schema.json +93 -0
  39. package/src/analysis-assets/output.schema.json +93 -0
  40. package/src/analysis-assets/prompt.en.txt +17 -0
  41. package/src/analysis-assets/prompt.zh-CN.txt +18 -0
  42. package/src/analysis-budget.cjs +105 -0
  43. package/src/analysis-git.cjs +38 -0
  44. package/src/analysis-history.cjs +150 -0
  45. package/src/analysis-ledger.cjs +82 -0
  46. package/src/analysis-log.cjs +62 -0
  47. package/src/analysis-runner.cjs +203 -0
  48. package/src/analysis-service.cjs +197 -0
  49. package/src/analysis-source.cjs +72 -0
  50. package/src/antigravity-card.cjs +2063 -0
  51. package/src/antigravity-hook.cjs +138 -0
  52. package/src/antigravity-mcp-config.cjs +36 -0
  53. package/src/app-server.cjs +96 -0
  54. package/src/cdp.cjs +115 -0
  55. package/src/claude-inline-install.cjs +38 -0
  56. package/src/claude-mcp-config.cjs +29 -0
  57. package/src/cli/arguments.cjs +30 -0
  58. package/src/cli/environment-probe.cjs +130 -0
  59. package/src/cli/integration-state.cjs +15 -0
  60. package/src/cli/interactive-cli.cjs +236 -0
  61. package/src/cli/prompt-tui.cjs +420 -0
  62. package/src/cli/setup-orchestrator.cjs +449 -0
  63. package/src/codex-mcp-config.cjs +67 -0
  64. package/src/harnesses/antigravity/analysis-profile.cjs +41 -0
  65. package/src/harnesses/antigravity/antigravity-git.cjs +89 -0
  66. package/src/harnesses/antigravity/antigravity-harness.js +1477 -0
  67. package/src/harnesses/antigravity/antigravity-injector.cjs +104 -0
  68. package/src/harnesses/antigravity/antigravity-migration.cjs +235 -0
  69. package/src/harnesses/antigravity/antigravity-service.cjs +357 -0
  70. package/src/harnesses/antigravity/antigravity-title.cjs +155 -0
  71. package/src/harnesses/antigravity/gemini-runner.cjs +304 -0
  72. package/src/harnesses/antigravity/transcript-cleaner.cjs +129 -0
  73. package/src/harnesses/antigravity/transcript-source.cjs +100 -0
  74. package/src/harnesses/claude/claude-harness.js +93 -0
  75. package/src/harnesses/claude/claude-host-helper.cjs +176 -0
  76. package/src/harnesses/claude/claude-injector.cjs +95 -0
  77. package/src/harnesses/claude/claude-local-source.cjs +106 -0
  78. package/src/harnesses/claude/claude-navigation.cjs +99 -0
  79. package/src/harnesses/claude/claude-runner.cjs +74 -0
  80. package/src/harnesses/claude/claude-service.cjs +313 -0
  81. package/src/harnesses/claude/claude-source.cjs +70 -0
  82. package/src/harnesses/codex/codex-analysis.cjs +10 -0
  83. package/src/harnesses/codex/codex-card-bridge.js +123 -0
  84. package/src/harnesses/codex/codex-card-events.cjs +76 -0
  85. package/src/harnesses/codex/codex-card.cjs +169 -0
  86. package/src/harnesses/codex/codex-git.cjs +24 -0
  87. package/src/harnesses/codex/codex-harness.js +229 -0
  88. package/src/harnesses/codex/codex-local-card.js +97 -0
  89. package/src/harnesses/codex/codex-progress-context.cjs +84 -0
  90. package/src/harnesses/codex/codex-service.cjs +502 -0
  91. package/src/i18n.cjs +174 -0
  92. package/src/launchd.cjs +105 -0
  93. package/src/lifecycle-lock.cjs +13 -0
  94. package/src/local-progress-http.cjs +267 -0
  95. package/src/manual-status-agent.cjs +12 -0
  96. package/src/manual-status-startup.cjs +66 -0
  97. package/src/manual-status-store.cjs +466 -0
  98. package/src/mcp-stdio.cjs +67 -0
  99. package/src/model-router.cjs +63 -0
  100. package/src/native-bridge.cjs +17 -0
  101. package/src/npm-updates.cjs +228 -0
  102. package/src/plugins/things/assets/logo.svg +13 -0
  103. package/src/plugins/things/plugin.json +6 -0
  104. package/src/plugins/things/sidecars/things_board/app.js +447 -0
  105. package/src/plugins/things/sidecars/things_board/index.html +2141 -0
  106. package/src/plugins/things/sidecars/things_board/main.mjs +652 -0
  107. package/src/plugins/things/sidecars/things_board/package.json +6 -0
  108. package/src/plugins/things/sidecars/things_board/sidecar.json +21 -0
  109. package/src/plugins/things/sidecars/things_board/styles.css +560 -0
  110. package/src/plugins/things/sidecars/things_board/ui-i18n.mjs +434 -0
  111. package/src/progress-error.cjs +54 -0
  112. package/src/progress-tools.cjs +145 -0
  113. package/src/project-path.cjs +15 -0
  114. package/src/renderer-resource.cjs +17 -0
  115. package/src/request-budget.cjs +24 -0
  116. package/src/resolve.cjs +51 -0
  117. package/src/runtime-install.cjs +635 -0
  118. package/src/session-status-filter.cjs +136 -0
  119. package/src/session-status.js +992 -0
  120. package/src/session-view.cjs +34 -0
  121. package/src/startup/controller.cjs +354 -0
  122. package/src/startup/watch.cjs +126 -0
  123. package/src/state-file-lock.cjs +31 -0
  124. package/src/task-provenance.cjs +42 -0
  125. package/src/ui-foundation.cjs +435 -0
@@ -0,0 +1,176 @@
1
+ 'use strict';
2
+
3
+ // Serialized into the verified Claude main process. Dependencies are explicit.
4
+ function installClaudeHost({ root, credentialFile }) {
5
+ const req = process.getBuiltinModule('module').createRequire(process.execPath);
6
+ const fs = req('node:fs'), path = req('node:path'), crypto = req('node:crypto');
7
+ const { webContents, app } = req('electron');
8
+ const { transcriptTurns, pageClaudeTurns } = req(path.join(root, 'src/harnesses/claude/claude-source.cjs'));
9
+ const { locateClaudeMessage } = req(path.join(root, 'src/harnesses/claude/claude-navigation.cjs'));
10
+ const snapshots = new Map();
11
+ const globalName = '__agentThingsClaudeHost';
12
+ if (globalThis[globalName]) {
13
+ if (globalThis[globalName].credentialFile !== credentialFile) throw new Error('当前 Claude 已连接其他账本实例,请先停止该实例');
14
+ return { installed: true, pid: process.pid, reused: true };
15
+ }
16
+ const pages = new Map();
17
+ let stopped = false, refreshing = false, lastVersion = null, source = '', resourceStamp = '';
18
+ const handledJobs = new Set();
19
+ const heartbeat = path.join(path.dirname(credentialFile), 'attachment-host.json');
20
+ const binding = '__agentThingsClaudeSend';
21
+ const eligible = w => { try { return !w.isDestroyed() && new URL(w.getURL()).origin === 'https://claude.ai'; } catch { return false; } };
22
+ const request = async (route, body) => {
23
+ const auth = JSON.parse(fs.readFileSync(credentialFile, 'utf8'));
24
+ if (auth.service !== 'agent-things' || !Number.isInteger(auth.port) || auth.port < 1 || auth.port > 65535 || typeof auth.token !== 'string') throw new Error('Claude 插件服务凭据无效');
25
+ const response = await fetch(`http://127.0.0.1:${auth.port}${route}`, { method: body === undefined ? 'GET' : 'POST',
26
+ headers: { Authorization: `Bearer ${auth.token}`, 'Content-Type': 'application/json' },
27
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(15000) });
28
+ const value = await response.json(); if (!response.ok) throw new Error(value.error || '后台服务不可用'); return value;
29
+ };
30
+ const evaluate = (entry, expression) => entry.w.debugger.sendCommand('Runtime.evaluate', { expression, contextId: entry.contextId, returnByValue: true, awaitPromise: true });
31
+ const unwatch = async entry => {
32
+ if (entry.w.isDestroyed()) return;
33
+ if (entry.contextId && entry.w.debugger.isAttached()) {
34
+ try { await evaluate(entry, 'window.__codexSessionStatus?.destroy()'); } catch { /* A navigated document has no old world. */ }
35
+ }
36
+ entry.w.debugger.removeListener('message', entry.onMessage);
37
+ entry.w.debugger.removeListener('detach', entry.onDetach);
38
+ entry.w.removeListener('did-finish-load', entry.onLoad);
39
+ entry.w.removeListener('destroyed', entry.onGone);
40
+ if (entry.ownsDebugger && entry.w.debugger.isAttached()) entry.w.debugger.detach();
41
+ };
42
+ const install = async entry => {
43
+ if (entry.installing || !eligible(entry.w) || entry.w.isDevToolsOpened()) return;
44
+ entry.installing = true;
45
+ try {
46
+ if (!entry.w.debugger.isAttached()) { entry.w.debugger.attach('1.3'); entry.ownsDebugger = true; }
47
+ else if (!entry.ownsDebugger) throw new Error('Claude 页面正在被其他调试器使用');
48
+ await entry.w.debugger.sendCommand('Runtime.enable');
49
+ const { frameTree } = await entry.w.debugger.sendCommand('Page.getFrameTree');
50
+ const { executionContextId } = await entry.w.debugger.sendCommand('Page.createIsolatedWorld', { frameId: frameTree.frame.id, worldName: 'agent-things-claude' });
51
+ entry.contextId = executionContextId;
52
+ await entry.w.debugger.sendCommand('Runtime.addBinding', { name: binding, executionContextId });
53
+ const expression = `(() => {
54
+ const old=window.__codexSessionStatus;
55
+ if(old?.status().version===${JSON.stringify(lastVersion)})return true;
56
+ const saved=old?.exportForReload?.();if(saved?.busy)return false;
57
+ const install=new Function(${JSON.stringify(source)}+'\\nreturn installCodexSessionStatus;');
58
+ old?.destroy();install()(${JSON.stringify(lastVersion)},saved);return true;
59
+ })()`;
60
+ const result = await evaluate(entry, expression);
61
+ if (result.exceptionDetails) throw new Error('Claude 界面加载失败');
62
+ if (result.result.value) entry.version = lastVersion;
63
+ } finally { entry.installing = false; }
64
+ };
65
+ const watch = w => {
66
+ if (pages.has(w.id)) return;
67
+ const entry = { w, contextId: null, ownsDebugger: false, installing: false };
68
+ entry.onMessage = async (_event, method, params) => {
69
+ if (method !== 'Runtime.bindingCalled' || params.name !== binding || params.executionContextId !== entry.contextId || !eligible(w)) return;
70
+ if (typeof params.payload !== 'string' || Buffer.byteLength(params.payload) > 1024 * 1024) return;
71
+ let message;
72
+ try {
73
+ message = JSON.parse(params.payload);
74
+ const reply = await request('/rpc', message);
75
+ if (!w.isDestroyed()) await evaluate(entry, `window.__codexSessionStatus?.reply(${JSON.stringify(reply)})`);
76
+ } catch (error) {
77
+ if (message?.requestId && !w.isDestroyed()) await evaluate(entry, `window.__codexSessionStatus?.reply(${JSON.stringify({ requestId: message.requestId, error: error.message })})`).catch(() => {});
78
+ }
79
+ };
80
+ entry.onDetach = () => { entry.contextId = null; entry.version = null; entry.ownsDebugger = false; };
81
+ entry.onLoad = () => { entry.version = null; };
82
+ entry.onGone = () => { pages.delete(w.id); };
83
+ w.debugger.on('message', entry.onMessage); w.debugger.on('detach', entry.onDetach);
84
+ w.on('did-finish-load', entry.onLoad); w.once('destroyed', entry.onGone);
85
+ pages.set(w.id, entry);
86
+ };
87
+ const serveJob = async job => {
88
+ if (handledJobs.has(job.id)) return;
89
+ handledJobs.add(job.id);
90
+ try {
91
+ if (job.method === 'detach') { await status.stop(); await request('/host-reply', { id: job.id, result: { detached: true } }); return; }
92
+ if (!['session', 'turns', 'identity', 'locate'].includes(job.method) || typeof job.threadId !== 'string' || job.threadId.length > 256) throw new Error('无效宿主查询');
93
+ const target = [...pages.values()].find(entry => eligible(entry.w));
94
+ if (!target) throw new Error('Claude 页面尚未就绪');
95
+ if (job.method === 'turns') {
96
+ const options = job.options || {};
97
+ if (typeof options.snapshotId !== 'string' || !/^[a-z0-9-]{1,80}$/i.test(options.snapshotId)) throw new Error('Claude 分析快照身份无效');
98
+ for (const [key, value] of snapshots) if (Date.now() - value.at > 120000) snapshots.delete(key);
99
+ let snapshot = snapshots.get(options.snapshotId);
100
+ if (snapshot && snapshot.threadId !== job.threadId) throw new Error('Claude 分析快照会话不匹配');
101
+ if (!snapshot) {
102
+ if (snapshots.size >= 8) throw new Error('同时读取的 Claude 会话过多,请稍后重试');
103
+ const raw = await target.w.executeJavaScript(`window['claude.web'].LocalSessions.getTranscript(${JSON.stringify(job.threadId)})`);
104
+ snapshot = { threadId: job.threadId, turns: transcriptTurns(raw), at: Date.now() };
105
+ snapshots.set(options.snapshotId, snapshot);
106
+ }
107
+ snapshot.at = Date.now();
108
+ await request('/host-reply', { id: job.id, result: pageClaudeTurns(snapshot.turns, options) });
109
+ return;
110
+ }
111
+ if (job.method === 'locate') {
112
+ if (typeof job.options?.itemId !== 'string' || !/^[\w-]{1,256}$/.test(job.options.itemId)) throw new Error('无效来源消息标识');
113
+ const result = await target.w.executeJavaScript(`(${locateClaudeMessage.toString()})(${JSON.stringify({ threadId: job.threadId, itemId: job.options.itemId })})`);
114
+ await request('/host-reply', { id: job.id, result });
115
+ return;
116
+ }
117
+ const result = await target.w.executeJavaScript(`(async () => {
118
+ const api=window['claude.web']?.LocalSessions;
119
+ if(!api)throw new Error('当前 Claude 未提供会话读取接口');
120
+ const id=${JSON.stringify(job.threadId)};
121
+ const listed=await api.getSessionList();
122
+ const session=(Array.isArray(listed)?listed:listed.sessions)?.find(item=>item.sessionId===id||item.id===id||item.cliSessionId===id||item.priorCliSessionIds?.includes(id));
123
+ return session?{id:session.sessionId||session.id,cwd:session.cwd||null}:null;
124
+ })()`);
125
+ await request('/host-reply', { id: job.id, result });
126
+ } catch (error) { await request('/host-reply', { id: job.id, error: error.message }).catch(() => {}); }
127
+ finally { handledJobs.delete(job.id); }
128
+ };
129
+ const refresh = async () => {
130
+ if (refreshing || stopped) return;
131
+ refreshing = true;
132
+ try {
133
+ const resources = [path.join(root, 'src/harnesses/claude/claude-harness.js'), path.join(root, 'src/session-status.js')];
134
+ const stamp = resources.map(file => { const stat = fs.statSync(file); return `${stat.mtimeMs}:${stat.size}`; }).join('|');
135
+ if (stamp !== resourceStamp) {
136
+ source = resources.map(file => fs.readFileSync(file, 'utf8')).join('\n');
137
+ lastVersion = crypto.createHash('sha256').update(source).digest('hex'); resourceStamp = stamp;
138
+ }
139
+ for (const w of webContents.getAllWebContents()) if (eligible(w)) watch(w);
140
+ for (const entry of pages.values()) {
141
+ if (!eligible(entry.w)) continue;
142
+ if (entry.version !== lastVersion) await install(entry);
143
+ }
144
+ const snapshot = await request('/snapshot');
145
+ const serialized = JSON.stringify(snapshot.snapshot);
146
+ const views = [];
147
+ for (const entry of pages.values()) if (entry.contextId) {
148
+ const response = await evaluate(entry, `(() => {window.__codexSessionStatus?.receive(${serialized});return window.__codexSessionStatus?.status()})()`);
149
+ if (response.exceptionDetails) throw new Error('Claude 界面状态同步失败');
150
+ views.push({ id: entry.w.id, ...response.result.value });
151
+ }
152
+ status.views = views; status.lastError = null;
153
+ const jobs = await request('/host-jobs');
154
+ for (const job of jobs) void serveJob(job);
155
+ } catch (error) { status.lastError = error.message; }
156
+ finally {
157
+ refreshing = false;
158
+ try {
159
+ const temporary = `${heartbeat}.${process.pid}.tmp`;
160
+ fs.writeFileSync(temporary, JSON.stringify({ pid: process.pid, checkedAt: Date.now(), stopped, views: status.views || [], error: status.lastError }), { mode: 0o600 });
161
+ fs.renameSync(temporary, heartbeat);
162
+ } catch (error) { status.lastError = error.message; }
163
+ }
164
+ };
165
+ const status = { pid: process.pid, credentialFile, lastError: null, stop: async () => {
166
+ stopped = true; clearInterval(timer); app.removeListener('web-contents-created', onCreated);
167
+ await Promise.all([...pages.values()].map(unwatch)); pages.clear(); delete globalThis[globalName];
168
+ } };
169
+ const onCreated = (_event, w) => { if (eligible(w)) watch(w); };
170
+ app.on('web-contents-created', onCreated);
171
+ const timer = setInterval(refresh, 1000);
172
+ globalThis[globalName] = status;
173
+ void refresh();
174
+ return { installed: true, pid: process.pid };
175
+ }
176
+ module.exports = { installClaudeHost };
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { execFile } = require('node:child_process');
5
+ const { promisify } = require('node:util');
6
+ const { CdpSession, listTargets } = require('../../cdp.cjs');
7
+ const { installClaudeHost } = require('./claude-host-helper.cjs');
8
+ const execute = promisify(execFile);
9
+ const APP = '/Applications/Claude.app';
10
+ const REQUIREMENT = 'identifier "com.anthropic.claudefordesktop" and anchor apple generic and certificate leaf[subject.OU] = "Q6L2SF6YDW"';
11
+
12
+ async function verifyClaudeProcess(pid, run) {
13
+ const { stdout } = await run('/bin/ps', ['-p', String(pid), '-o', 'uid=,comm='], { timeout: 2000 });
14
+ const match = stdout.trim().match(/^(\d+)\s+(.+)$/);
15
+ if (!match || Number(match[1]) !== process.getuid() || match[2] !== `${APP}/Contents/MacOS/Claude`) throw new Error('连接目标属于其他进程,未确认 Claude 身份');
16
+ await run('/usr/bin/codesign', ['--verify', '--strict', `-R=${REQUIREMENT}`, APP], { timeout: 5000 });
17
+ }
18
+
19
+ async function inspectorOwner({ execute: run = execute } = {}) {
20
+ let output;
21
+ try { output = (await run('/usr/sbin/lsof', ['-t', '-nP', '-iTCP:9229', '-sTCP:LISTEN'], { timeout: 2000 })).stdout; }
22
+ catch (error) { if (error.code === 1) return null; throw error; }
23
+ const pids = [...new Set(output.trim().split(/\s+/))];
24
+ if (pids.length !== 1 || !/^\d+$/.test(pids[0])) throw new Error('调试端口归属不明确');
25
+ const pid = Number(pids[0]);
26
+ await verifyClaudeProcess(pid, run);
27
+ return pid;
28
+ }
29
+
30
+ class ClaudeInjector {
31
+ constructor({ stateFile, root = path.resolve(__dirname, '../../..'), run = execute } = {}) {
32
+ this.stateFile = stateFile; this.root = root; this.run = run;
33
+ this.attachedPid = null; this.busy = false; this.status = { state: 'waiting' };
34
+ }
35
+ async scan() {
36
+ if (this.busy) return this.status;
37
+ this.busy = true;
38
+ try {
39
+ const heartbeatFile = path.join(path.dirname(this.stateFile), 'attachment-host.json');
40
+ if (!this.attachedPid && fs.existsSync(heartbeatFile)) {
41
+ const heartbeat = JSON.parse(fs.readFileSync(heartbeatFile, 'utf8'));
42
+ if (Number.isInteger(heartbeat.pid) && !heartbeat.stopped && Date.now() - heartbeat.checkedAt < 5000) {
43
+ try { await verifyClaudeProcess(heartbeat.pid, this.run); this.attachedPid = heartbeat.pid; }
44
+ catch { /* The old host may have exited during a client update. */ }
45
+ }
46
+ }
47
+ if (this.attachedPid) {
48
+ if (fs.existsSync(heartbeatFile)) {
49
+ const heartbeat = JSON.parse(fs.readFileSync(heartbeatFile, 'utf8'));
50
+ if (heartbeat.pid === this.attachedPid && !heartbeat.stopped && Date.now() - heartbeat.checkedAt < 5000) {
51
+ return this.status = { state: heartbeat.error ? 'error' : 'attached', pid: this.attachedPid,
52
+ mounted: (heartbeat.views || []).reduce((count, view) => count + (view.mounted || 0), 0), ...(heartbeat.error ? { error: heartbeat.error } : {}) };
53
+ }
54
+ }
55
+ try {
56
+ const { stdout } = await this.run('/bin/ps', ['-p', String(this.attachedPid), '-o', 'comm='], { timeout: 2000 });
57
+ if (stdout.trim() === `${APP}/Contents/MacOS/Claude`) return this.status;
58
+ } catch { /* The previously attached app exited. */ }
59
+ this.attachedPid = null;
60
+ }
61
+ const pid = await inspectorOwner({ execute: this.run });
62
+ if (!pid) return this.status = { state: 'manual-debugger-required' };
63
+ const targets = await listTargets(9229, 2000);
64
+ if (targets.length !== 1 || targets[0].type !== 'node' || await inspectorOwner({ execute: this.run }) !== pid) throw new Error('Claude 调试目标已变化');
65
+ const session = new CdpSession(targets[0], 9229);
66
+ try {
67
+ await session.connect();
68
+ const response = await session.evaluate(`(() => {
69
+ if(process.pid!==${pid})throw new Error('Claude 进程身份已变化');
70
+ return (${installClaudeHost.toString()})(${JSON.stringify({ root: this.root, credentialFile: `${this.stateFile}.http.json` })});
71
+ })()`);
72
+ if (!response.result?.value?.installed) throw new Error('Claude 插件加载失败');
73
+ this.attachedPid = pid;
74
+ this.status = { state: 'attached', pid };
75
+ } finally {
76
+ try {
77
+ if (session.socket?.readyState === WebSocket.OPEN) await session.evaluate(`(() => {
78
+ const {Menu}=process.getBuiltinModule('module').createRequire(process.execPath)('electron');
79
+ const clear=menu=>{for(const item of menu?.items??[]){if(item.label==='Enable Main Process Debugger')item.checked=false;if(item.submenu)clear(item.submenu);}};
80
+ clear(Menu.getApplicationMenu());setTimeout(()=>process.getBuiltinModule('inspector').close(),150);return true;
81
+ })()`);
82
+ } finally { session.close(); }
83
+ }
84
+ return this.status;
85
+ } catch (error) { this.status = { state: 'error', error: error.message }; return this.status; }
86
+ finally {
87
+ this.busy = false;
88
+ const file = path.join(path.dirname(this.stateFile), 'attachment.json');
89
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
90
+ const temporary = `${file}.${process.pid}.tmp`;
91
+ fs.writeFileSync(temporary, JSON.stringify({ ...this.status, checkedAt: new Date().toISOString() }), { mode: 0o600 }); fs.renameSync(temporary, file);
92
+ }
93
+ }
94
+ }
95
+ module.exports = { ClaudeInjector, inspectorOwner, APP };
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const os = require('node:os');
5
+ const { cleanTranscriptMessage, appendCleanMessage, pageClaudeTurns } = require('./claude-source.cjs');
6
+
7
+ async function* entries(file) {
8
+ const size = fs.statSync(file).size;
9
+ if (!size) return;
10
+ let pending = '';
11
+ for await (const chunk of fs.createReadStream(file, { encoding: 'utf8', end: size - 1 })) {
12
+ pending += chunk;
13
+ let end;
14
+ while ((end = pending.indexOf('\n')) >= 0) {
15
+ const line = pending.slice(0, end); pending = pending.slice(end + 1);
16
+ if (line.trim()) yield JSON.parse(line);
17
+ }
18
+ }
19
+ if (pending.trim()) {
20
+ let entry;
21
+ try { entry = JSON.parse(pending); } catch { return; } // Incomplete trailing write lies outside this snapshot.
22
+ yield entry;
23
+ }
24
+ }
25
+
26
+ class ClaudeLocalSource {
27
+ constructor({ home = os.homedir() } = {}) { this.home = home; this.loadedAt = 0; this.sessions = []; this.fileCache = new Map(); }
28
+ loadSessions() {
29
+ if (Date.now() - this.loadedAt < 2000) return this.sessions;
30
+ const root = path.join(this.home, 'Library/Application Support/Claude/claude-code-sessions');
31
+ const sessions = [], seen = new Set();
32
+ if (fs.existsSync(root)) for (const account of fs.readdirSync(root, { withFileTypes: true }).filter(item => item.isDirectory())) {
33
+ const accountDir = path.join(root, account.name);
34
+ for (const org of fs.readdirSync(accountDir, { withFileTypes: true }).filter(item => item.isDirectory())) {
35
+ const directory = path.join(accountDir, org.name);
36
+ for (const file of fs.readdirSync(directory)) {
37
+ if (!/^local_[\w-]+\.json$/.test(file)) continue;
38
+ const filePath = path.join(directory, file);
39
+ seen.add(filePath);
40
+ const stat = fs.statSync(filePath);
41
+ const cached = this.fileCache.get(filePath);
42
+ let session;
43
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
44
+ session = cached.session;
45
+ } else {
46
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
47
+ session = data.sessionId && data.cliSessionId ? data : null;
48
+ this.fileCache.set(filePath, { mtimeMs: stat.mtimeMs, size: stat.size, session });
49
+ }
50
+ if (session) sessions.push(session);
51
+ }
52
+ }
53
+ }
54
+ for (const filePath of this.fileCache.keys()) {
55
+ if (!seen.has(filePath)) this.fileCache.delete(filePath);
56
+ }
57
+ this.sessions = sessions; this.loadedAt = Date.now(); return sessions;
58
+ }
59
+ resolve(id, cwd) {
60
+ if (typeof id !== 'string' || !/^[\w-]{1,256}$/.test(id)) throw new Error('Claude 会话身份无效');
61
+ const matches = this.loadSessions().filter(item => item.sessionId === id || item.cliSessionId === id || item.priorCliSessionIds?.includes(id));
62
+ const exact = matches.length > 1 && cwd ? matches.filter(item => item.cwd === cwd || item.originCwd === cwd) : matches;
63
+ if (exact.length > 1) throw new Error('Claude 会话身份匹配不唯一');
64
+ return exact[0] || null;
65
+ }
66
+ transcriptFile(session) {
67
+ const projects = path.join(this.home, '.claude/projects');
68
+ if (!fs.existsSync(projects)) throw new Error('Claude 本地会话目录不存在');
69
+ const names = fs.readdirSync(projects, { withFileTypes: true }).filter(item => item.isDirectory());
70
+ const files = names.map(item => path.join(projects, item.name, `${session.cliSessionId}.jsonl`)).filter(file => fs.existsSync(file));
71
+ if (files.length !== 1) throw new Error(files.length ? 'Claude 会话文件匹配不唯一' : '未找到此会话的本地历史文件');
72
+ return files[0];
73
+ }
74
+ async message(session, itemId) {
75
+ for await (const entry of entries(this.transcriptFile(session))) if (entry.uuid === itemId) return cleanTranscriptMessage(entry);
76
+ return null;
77
+ }
78
+ async turns(session) {
79
+ const messages = new Map();
80
+ for await (const entry of entries(this.transcriptFile(session))) {
81
+ if (!['user', 'assistant'].includes(entry.type) || !entry.uuid) continue;
82
+ const clean = cleanTranscriptMessage(entry);
83
+ if (clean) messages.set(clean.id, clean);
84
+ }
85
+ const turns = [];
86
+ for (const message of messages.values()) appendCleanMessage(turns, message);
87
+ return turns;
88
+ }
89
+ server(fallback) {
90
+ const source = this;
91
+ let session = null, turns = null;
92
+ return {
93
+ async initialize() {}, async close() { turns = null; await fallback?.close(); },
94
+ async request(method, params) {
95
+ session ||= source.resolve(params.threadId);
96
+ if (!session && fallback) return fallback.request(method, params);
97
+ if (!session) throw new Error('未找到 Claude 本地会话身份');
98
+ if (method === 'thread/read') return { thread: { id: params.threadId, cwd: session.cwd } };
99
+ if (method !== 'thread/turns/list') throw new Error('Claude 数据源不支持此方法');
100
+ turns ||= await source.turns(session);
101
+ return pageClaudeTurns(turns, params);
102
+ },
103
+ };
104
+ }
105
+ }
106
+ module.exports = { ClaudeLocalSource };
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+
3
+ // Runs in Claude's main renderer world, using its own transcript ref and pager.
4
+ async function locateClaudeMessage({ threadId, itemId, timeoutMs = 15000 }) {
5
+ const deadline = Date.now() + timeoutMs;
6
+ const wait = () => new Promise(resolve => setTimeout(resolve, 50));
7
+ const scope = () => {
8
+ const composer = document.querySelector(`[data-session-id="${CSS.escape(threadId)}"]`);
9
+ return composer?.closest('.epitaxy-chat-panel') || composer;
10
+ };
11
+ if (!scope()) {
12
+ const row = document.querySelector(`[data-row-key="${CSS.escape('code:' + threadId)}"]`);
13
+ const button = row?.querySelector('[data-row-main-button]');
14
+ if (!button) return { located: false, reason: 'session_not_visible' };
15
+ button.click();
16
+ while (!scope() && Date.now() < deadline) await wait();
17
+ }
18
+ const find = (root, id) => root?.querySelector(['data-epitaxy-entry', 'data-entry-key', 'data-turn-key', 'data-message-uuid']
19
+ .map(attribute => `[${attribute}="${CSS.escape(id)}"]`).join(','));
20
+ const reveal = element => {
21
+ element.scrollIntoView({ block: 'center', behavior: 'instant' });
22
+ element.animate?.([{ outline: '2px solid #0169cc' }, { outline: '2px solid transparent' }], { duration: 1400 });
23
+ return { located: true };
24
+ };
25
+ function transcript(root) {
26
+ const scroller = root?.querySelector('[data-autoscroll-container]');
27
+ if (!scroller) return {};
28
+ const key = Object.keys(scroller).find(key => key.startsWith('__reactFiber$'));
29
+ let first = key && scroller[key], top = first;
30
+ while (top?.return) top = top.return;
31
+ if (top?.stateNode?.current && top.stateNode.current !== top) first = first.alternate || first;
32
+ let api, pager, entries;
33
+ // Follow this transcript's ancestors only; never search other sessions' trees.
34
+ for (let fiber = first, depth = 0; fiber && depth < 100; fiber = fiber.return, depth++) {
35
+ const props = fiber.memoizedProps || {};
36
+ if (props.sessionId && props.sessionId !== threadId) break;
37
+ const candidate = props.messagesRef?.current || fiber.ref?.current;
38
+ if (!api && typeof candidate?.scrollToEntry === 'function') api = candidate;
39
+ if (props.historyPager) pager = props.historyPager;
40
+ const older = props.value?.olderSource;
41
+ if (!pager && older) pager = { hasEarlier: older.hasOlder, isLoadingEarlier: older.isLoadingOlder, earlierError: older.olderLoadFailed, loadEarlier: () => older.loadOlder({ trigger: 'anchor-restore', chain: () => Date.now() < deadline && !!scope() && !transcript(scope()).entries?.some(entry => entry.id === itemId || entry.sourceUuid === itemId || entry.lastAssistantUuid === itemId) }) };
42
+ if (Array.isArray(props.entries)) entries = props.entries;
43
+ if (api && pager && entries) break;
44
+ }
45
+ return { api, pager, entries };
46
+ }
47
+ while (Date.now() < deadline) {
48
+ const root = scope();
49
+ if (!root) return { located: false, reason: 'session_changed' };
50
+ const mounted = find(root, itemId);
51
+ if (mounted) return reveal(mounted);
52
+ const { api, pager, entries } = transcript(root);
53
+ if (!api || !entries) return { located: false, reason: 'transcript_api_unavailable' };
54
+ const entry = entries.find(entry => entry.id === itemId || entry.sourceUuid === itemId || entry.lastAssistantUuid === itemId);
55
+ if (entry) {
56
+ let report;
57
+ api.scrollToEntry(entry.id, 'instant', { flash: true, report: value => { report = value; } });
58
+ const until = Math.min(deadline, Date.now() + 5000);
59
+ while (Date.now() < until) {
60
+ if (scope() !== root) return { located: false, reason: 'session_changed' };
61
+ const target = find(root, entry.id) || find(root, itemId);
62
+ if (target) return reveal(target);
63
+ await wait();
64
+ }
65
+ return { located: false, reason: 'message_not_rendered', stage: report };
66
+ }
67
+ if (pager?.earlierError) return { located: false, reason: 'history_load_failed' };
68
+ if (!pager?.hasEarlier) return { located: false, reason: 'message_not_in_history' };
69
+ if (!pager.isLoadingEarlier) await pager.loadEarlier();
70
+ // Wait for the host to publish the next page before requesting another.
71
+ while (Date.now() < deadline) {
72
+ await wait();
73
+ const next = transcript(scope());
74
+ if (next.entries !== entries || next.pager?.earlierError || !next.pager?.hasEarlier) break;
75
+ }
76
+ }
77
+ return { located: false, reason: 'history_load_timeout' };
78
+ }
79
+ const { readConfiguredLang } = require('../../i18n.cjs');
80
+
81
+ function navigationResult(result, lang = readConfiguredLang()) {
82
+ const en = lang === 'en';
83
+ const messages = en ? {
84
+ session_not_visible: 'Please expand the corresponding session in the Claude sidebar first',
85
+ session_changed: 'Session changed; locating stopped',
86
+ transcript_api_unavailable: 'Message locating interface is unavailable in the current client',
87
+ message_not_rendered: 'Message loaded, but its display position could not be located yet',
88
+ history_load_failed: 'Claude failed to load earlier messages; please retry shortly',
89
+ message_not_in_history: 'This source message was not found in the current session history',
90
+ history_load_timeout: 'Claude is still loading earlier history; please retry shortly',
91
+ } : {
92
+ session_not_visible: '请先在 Claude 侧栏展开对应会话', session_changed: '会话已切换,定位已停止',
93
+ transcript_api_unavailable: '当前客户端的消息定位接口暂不可用', message_not_rendered: '消息已加载,但暂未能定位显示位置',
94
+ history_load_failed: 'Claude 加载历史消息失败,请稍后重试', message_not_in_history: '当前会话历史中没有找到这条来源消息',
95
+ history_load_timeout: 'Claude 仍在加载更早的历史,请稍后重试',
96
+ };
97
+ return { ...result, message: result?.located ? (en ? 'Located source' : '已定位来源') : messages[result?.reason] || (en ? 'Unable to locate source message right now' : '暂时无法定位来源消息') };
98
+ }
99
+ module.exports = { locateClaudeMessage, navigationResult };
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+ const { spawn } = require('node:child_process');
6
+ const { getAnalysisInstructions } = require('../../analysis-budget.cjs');
7
+ const { readConfiguredLang } = require('../../i18n.cjs');
8
+
9
+ function resolveClaudeBin() {
10
+ const root = path.join(os.homedir(), 'Library/Application Support/Claude/claude-code');
11
+ if (fs.existsSync(root)) {
12
+ const versions = fs.readdirSync(root).filter(name => /^\d+\.\d+\.\d+$/.test(name)).sort((a, b) => {
13
+ const x = a.split('.').map(Number), y = b.split('.').map(Number);
14
+ return y[0] - x[0] || y[1] - x[1] || y[2] - x[2];
15
+ });
16
+ for (const version of versions) for (const build of fs.readdirSync(path.join(root, version))) {
17
+ const file = path.join(root, version, build, 'claude.app/Contents/MacOS/claude');
18
+ if (fs.existsSync(file)) return file;
19
+ }
20
+ }
21
+ for (const file of [path.join(os.homedir(), '.local/bin/claude'), '/opt/homebrew/bin/claude', '/usr/local/bin/claude']) if (fs.existsSync(file)) return file;
22
+ throw new Error('未找到 Claude Code 运行时,请先在 Claude 中启动一次 Code 会话');
23
+ }
24
+
25
+ async function runClaudeAnalysis({ input, prompt, schema, signal, log = () => {}, binary = resolveClaudeBin(), model = 'haiku', timeoutMs = 120000, lang = readConfiguredLang(), instructions }) {
26
+ const en = lang === 'en';
27
+ const activeInstructions = instructions || getAnalysisInstructions(lang);
28
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-things-claude-'));
29
+ const settings = { disableAllHooks: true, enabledPlugins: {} };
30
+ const args = ['--print', '--model', model, '--output-format', 'json', '--json-schema', JSON.stringify(schema),
31
+ '--tools', '', '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', '--no-session-persistence',
32
+ '--disable-slash-commands', '--setting-sources', '', '--settings', JSON.stringify(settings), '--system-prompt', `${prompt}\n${activeInstructions}`];
33
+ const started = performance.now();
34
+ log('model.spawn', { model, profile: 'claude_cli_no_tools_v1', inputBytes: Buffer.byteLength(JSON.stringify(input)), lang });
35
+ try {
36
+ return await new Promise((resolve, reject) => {
37
+ if (signal?.aborted) { reject(new Error(en ? 'Analysis aborted' : '分析已中断')); return; }
38
+ const child = spawn(binary, args, { cwd: directory, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, CLAUDECODE: '', CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1' } });
39
+ let stdout = '', stderr = '', failure = null, forceStop;
40
+ const stop = error => {
41
+ failure ||= error; child.kill('SIGTERM');
42
+ if (!forceStop) forceStop = setTimeout(() => { if (child.exitCode === null) child.kill('SIGKILL'); }, 1500);
43
+ };
44
+ const abort = () => stop(new Error(en ? 'Analysis aborted' : '分析已中断'));
45
+ const timer = setTimeout(() => stop(new Error(en ? 'Claude analysis request timed out' : 'Claude 分析请求超时')), timeoutMs);
46
+ signal?.addEventListener('abort', abort, { once: true });
47
+ child.stdout.on('data', chunk => { stdout += chunk; if (Buffer.byteLength(stdout) > 4 * 1024 * 1024) stop(new Error(en ? 'Claude analysis output too large' : 'Claude 分析输出过大')); });
48
+ child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); });
49
+ child.stdin.on('error', error => { if (error.code !== 'EPIPE') stop(error); });
50
+ child.stdin.end(JSON.stringify(input));
51
+ child.once('error', error => { failure ||= error; });
52
+ child.once('close', code => {
53
+ clearTimeout(timer); clearTimeout(forceStop); signal?.removeEventListener('abort', abort);
54
+ log('model.settled', { model, elapsedMs: Math.round(performance.now() - started), ok: !failure && code === 0 });
55
+ if (failure) { reject(failure); return; }
56
+ if (code !== 0) {
57
+ reject(new Error(/auth|login|credential|401/i.test(stderr)
58
+ ? (en ? 'Claude analysis runtime not logged in; sign in to Claude Code first' : 'Claude 分析运行时未登录,请先完成 Claude Code 登录')
59
+ : (en ? 'Claude analysis runtime failed; check login and model access' : 'Claude 分析运行时返回错误,请检查登录与模型权限')));
60
+ return;
61
+ }
62
+ try {
63
+ const result = JSON.parse(stdout);
64
+ if (result.is_error) throw new Error(en ? 'Claude failed to complete structured analysis; check model access and quota' : 'Claude 未完成结构化分析,请检查模型权限与额度');
65
+ const value = result.structured_output || (typeof result.result === 'string' ? JSON.parse(result.result) : null);
66
+ if (!value || typeof value !== 'object') throw new Error(en ? 'Claude did not return structured analysis output' : 'Claude 未返回结构化分析结果');
67
+ resolve(value);
68
+ } catch (error) { reject(error); }
69
+ });
70
+ });
71
+ } finally { fs.rmSync(directory, { recursive: true, force: true }); }
72
+ }
73
+
74
+ module.exports = { runClaudeAnalysis, resolveClaudeBin };