agent-things 0.0.0-stage → 1.2.2
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/LICENSE +21 -0
- package/NOTICE +5 -0
- package/README.md +221 -2
- package/bin/agent-things.cjs +8 -0
- package/bin/antigravity-session-status.cjs +96 -0
- package/bin/claude-session-status.cjs +55 -0
- package/bin/codex-session-status.cjs +287 -0
- package/mods/agent-things-ui/.claude-plugin/plugin.json +12 -0
- package/mods/agent-things-ui/SKILL.md +10 -0
- package/mods/agent-things-ui/hooks/controls.js +112 -0
- package/mods/agent-things-ui/hooks/foundation.js +431 -0
- package/mods/agent-things-ui/hooks/hooks.json +1 -0
- package/mods/agent-things-ui/hooks/presentation.js +223 -0
- package/mods/agent-things-ui/hooks/progress.js +1 -0
- package/mods/agent-things-ui/hooks/register.js +382 -0
- package/native/bin/bridge +0 -0
- package/native/bin/bridge.json +20 -0
- package/native/session-status-bridge.swift +280 -0
- package/outputs/antigravity-session-status.js +2476 -0
- package/outputs/codex-session-status.js +1761 -0
- package/package.json +75 -4
- package/scripts/build-antigravity-bundle.cjs +35 -0
- package/scripts/build-codex-bundle.cjs +31 -0
- package/scripts/build-native-bridge.cjs +55 -0
- package/scripts/build-shared-ui.cjs +16 -0
- package/scripts/setup-antigravity-service.cjs +71 -0
- package/scripts/setup-claude-service.cjs +21 -0
- package/skills/agent-things/SKILL.en.md +95 -0
- package/skills/agent-things/SKILL.md +99 -0
- package/skills/codex/things/SKILL.en.md +10 -0
- package/skills/codex/things/SKILL.md +10 -0
- package/skills/things/SKILL.en.md +10 -0
- package/skills/things/SKILL.md +10 -0
- package/skills/things/checklist.en.md +91 -0
- package/skills/things/checklist.md +95 -0
- package/src/analysis-app-server.cjs +74 -0
- package/src/analysis-assets/output.en.schema.json +93 -0
- package/src/analysis-assets/output.schema.json +93 -0
- package/src/analysis-assets/prompt.en.txt +17 -0
- package/src/analysis-assets/prompt.zh-CN.txt +18 -0
- package/src/analysis-budget.cjs +105 -0
- package/src/analysis-git.cjs +38 -0
- package/src/analysis-history.cjs +150 -0
- package/src/analysis-ledger.cjs +82 -0
- package/src/analysis-log.cjs +62 -0
- package/src/analysis-runner.cjs +203 -0
- package/src/analysis-service.cjs +197 -0
- package/src/analysis-source.cjs +72 -0
- package/src/antigravity-card.cjs +2063 -0
- package/src/antigravity-hook.cjs +138 -0
- package/src/antigravity-mcp-config.cjs +36 -0
- package/src/app-server.cjs +96 -0
- package/src/cdp.cjs +115 -0
- package/src/claude-inline-install.cjs +38 -0
- package/src/claude-mcp-config.cjs +29 -0
- package/src/cli/arguments.cjs +30 -0
- package/src/cli/environment-probe.cjs +130 -0
- package/src/cli/integration-state.cjs +15 -0
- package/src/cli/interactive-cli.cjs +236 -0
- package/src/cli/prompt-tui.cjs +420 -0
- package/src/cli/setup-orchestrator.cjs +449 -0
- package/src/codex-mcp-config.cjs +67 -0
- package/src/harnesses/antigravity/analysis-profile.cjs +41 -0
- package/src/harnesses/antigravity/antigravity-git.cjs +89 -0
- package/src/harnesses/antigravity/antigravity-harness.js +1477 -0
- package/src/harnesses/antigravity/antigravity-injector.cjs +104 -0
- package/src/harnesses/antigravity/antigravity-migration.cjs +235 -0
- package/src/harnesses/antigravity/antigravity-service.cjs +357 -0
- package/src/harnesses/antigravity/antigravity-title.cjs +155 -0
- package/src/harnesses/antigravity/gemini-runner.cjs +304 -0
- package/src/harnesses/antigravity/transcript-cleaner.cjs +129 -0
- package/src/harnesses/antigravity/transcript-source.cjs +100 -0
- package/src/harnesses/claude/claude-harness.js +93 -0
- package/src/harnesses/claude/claude-host-helper.cjs +176 -0
- package/src/harnesses/claude/claude-injector.cjs +95 -0
- package/src/harnesses/claude/claude-local-source.cjs +106 -0
- package/src/harnesses/claude/claude-navigation.cjs +99 -0
- package/src/harnesses/claude/claude-runner.cjs +74 -0
- package/src/harnesses/claude/claude-service.cjs +313 -0
- package/src/harnesses/claude/claude-source.cjs +70 -0
- package/src/harnesses/codex/codex-analysis.cjs +10 -0
- package/src/harnesses/codex/codex-card-bridge.js +123 -0
- package/src/harnesses/codex/codex-card-events.cjs +76 -0
- package/src/harnesses/codex/codex-card.cjs +169 -0
- package/src/harnesses/codex/codex-git.cjs +24 -0
- package/src/harnesses/codex/codex-harness.js +229 -0
- package/src/harnesses/codex/codex-local-card.js +97 -0
- package/src/harnesses/codex/codex-progress-context.cjs +84 -0
- package/src/harnesses/codex/codex-service.cjs +502 -0
- package/src/i18n.cjs +174 -0
- package/src/launchd.cjs +105 -0
- package/src/lifecycle-lock.cjs +13 -0
- package/src/local-progress-http.cjs +267 -0
- package/src/manual-status-agent.cjs +12 -0
- package/src/manual-status-startup.cjs +66 -0
- package/src/manual-status-store.cjs +466 -0
- package/src/mcp-stdio.cjs +67 -0
- package/src/model-router.cjs +63 -0
- package/src/native-bridge.cjs +17 -0
- package/src/npm-updates.cjs +228 -0
- package/src/plugins/things/assets/logo.svg +13 -0
- package/src/plugins/things/plugin.json +6 -0
- package/src/plugins/things/sidecars/things_board/app.js +447 -0
- package/src/plugins/things/sidecars/things_board/index.html +2141 -0
- package/src/plugins/things/sidecars/things_board/main.mjs +652 -0
- package/src/plugins/things/sidecars/things_board/package.json +6 -0
- package/src/plugins/things/sidecars/things_board/sidecar.json +21 -0
- package/src/plugins/things/sidecars/things_board/styles.css +560 -0
- package/src/plugins/things/sidecars/things_board/ui-i18n.mjs +434 -0
- package/src/progress-error.cjs +54 -0
- package/src/progress-tools.cjs +145 -0
- package/src/project-path.cjs +15 -0
- package/src/renderer-resource.cjs +17 -0
- package/src/request-budget.cjs +24 -0
- package/src/resolve.cjs +51 -0
- package/src/runtime-install.cjs +635 -0
- package/src/session-status-filter.cjs +136 -0
- package/src/session-status.js +992 -0
- package/src/session-view.cjs +34 -0
- package/src/startup/controller.cjs +354 -0
- package/src/startup/watch.cjs +126 -0
- package/src/state-file-lock.cjs +31 -0
- package/src/task-provenance.cjs +42 -0
- package/src/ui-foundation.cjs +435 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const os = require('node:os');
|
|
4
|
+
const crypto = require('node:crypto');
|
|
5
|
+
const { ManualStatusStore } = require('../../manual-status-store.cjs');
|
|
6
|
+
const { startProgressHttp } = require('../../local-progress-http.cjs');
|
|
7
|
+
const { callProgressTool } = require('../../progress-tools.cjs');
|
|
8
|
+
const { AnalysisService } = require('../../analysis-service.cjs');
|
|
9
|
+
const { inspectGit, requireGitRemote } = require('../../analysis-git.cjs');
|
|
10
|
+
const { createAnalysisLog } = require('../../analysis-log.cjs');
|
|
11
|
+
const { resolveTaskSources } = require('../../task-provenance.cjs');
|
|
12
|
+
const updates = require('../../npm-updates.cjs');
|
|
13
|
+
const { ClaudeTranscriptServer } = require('./claude-source.cjs');
|
|
14
|
+
const { runClaudeAnalysis } = require('./claude-runner.cjs');
|
|
15
|
+
const { navigationResult } = require('./claude-navigation.cjs');
|
|
16
|
+
const { ClaudeLocalSource } = require('./claude-local-source.cjs');
|
|
17
|
+
|
|
18
|
+
const { sessionView, PROTOCOL_VERSION } = require('../../session-view.cjs');
|
|
19
|
+
const { errorDetails } = require('../../progress-error.cjs');
|
|
20
|
+
const { readConfiguredLang, getUi } = require('../../i18n.cjs');
|
|
21
|
+
|
|
22
|
+
const DEFAULT_PORT = 29889;
|
|
23
|
+
const DEFAULT_STATE_FILE = path.join(os.homedir(), 'Library/Application Support/AgentThings/claude/manual-state.json');
|
|
24
|
+
|
|
25
|
+
class ClaudeStatusStore extends ManualStatusStore {
|
|
26
|
+
resolveKey(id) {
|
|
27
|
+
const en = this.lang() === 'en';
|
|
28
|
+
if (this.validKey(id)) {
|
|
29
|
+
if (JSON.parse(id)[0] !== 'local') throw new Error(en ? 'Only local Claude Code sessions are supported right now' : '当前只支持本地 Claude Code 会话');
|
|
30
|
+
return id;
|
|
31
|
+
}
|
|
32
|
+
if (typeof id !== 'string' || !id.trim() || id.length > 256) throw new Error(en ? 'Please provide a Claude Desktop session identifier' : '请提供 Claude Desktop 会话标识');
|
|
33
|
+
return JSON.stringify(['local', id.trim()]);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
class ClaudeService {
|
|
38
|
+
constructor({ stateFile = DEFAULT_STATE_FILE, port = DEFAULT_PORT, run = runClaudeAnalysis, host = null, localSource = new ClaudeLocalSource() } = {}) {
|
|
39
|
+
this.stateFile = stateFile; this.port = port;
|
|
40
|
+
this.store = new ClaudeStatusStore(stateFile);
|
|
41
|
+
this.log = createAnalysisLog(path.join(path.dirname(stateFile), 'analysis.jsonl'));
|
|
42
|
+
this.jobs = new Map();
|
|
43
|
+
// 侧栏弹窗请求在右侧侧栏打开卡片:按会话键暂存,由该会话的 mod 下次轮询取走。
|
|
44
|
+
this.paneRequests = new Map();
|
|
45
|
+
// mod 的长轮询:按会话键挂起,弹窗请求一到立即回复,免去轮询间隔。
|
|
46
|
+
this.paneWaiters = new Map();
|
|
47
|
+
// 同会话多入口同步:每个会话记录最后一次变化时的账本修订号,按会话唤醒长等待(不同会话互不唤醒)。
|
|
48
|
+
this.keyChanges = new Map(); this.keySignatures = new Map(); this.watchers = new Map(); this.loggedReads = new Map();
|
|
49
|
+
this.watchStartRevision = 0;
|
|
50
|
+
this.lastLang = this.currentLang();
|
|
51
|
+
// 所有写入都经最外层 transaction(write 自身也会进入 transaction):在其结束后比对各会话的变化。
|
|
52
|
+
const transaction = this.store.transaction.bind(this.store);
|
|
53
|
+
this.store.transaction = operation => {
|
|
54
|
+
const outermost = !this.store.writing;
|
|
55
|
+
try { return transaction(operation); } finally { if (outermost) this.detectChanges(); }
|
|
56
|
+
};
|
|
57
|
+
this.localSource = localSource;
|
|
58
|
+
this.host = host || ((method, threadId, options) => {
|
|
59
|
+
if (['session', 'identity'].includes(method)) {
|
|
60
|
+
const session = this.localSource.resolve(threadId);
|
|
61
|
+
if (session) return Promise.resolve({ id: session.sessionId, cwd: session.cwd });
|
|
62
|
+
}
|
|
63
|
+
return this.requestHost(method, threadId, options);
|
|
64
|
+
});
|
|
65
|
+
this.makeServer = () => host ? new ClaudeTranscriptServer(this.host) : this.localSource.server(new ClaudeTranscriptServer(this.host));
|
|
66
|
+
this.analysis = new AnalysisService({ store: this.store, logFile: path.join(path.dirname(stateFile), 'analysis.jsonl'), makeServer: this.makeServer, run });
|
|
67
|
+
}
|
|
68
|
+
currentLang() {
|
|
69
|
+
if (typeof this.store?.lang === 'function') return this.store.lang();
|
|
70
|
+
return readConfiguredLang({ dataDir: path.dirname(this.stateFile) });
|
|
71
|
+
}
|
|
72
|
+
requestHost(method, threadId, options) {
|
|
73
|
+
const id = crypto.randomUUID();
|
|
74
|
+
const en = this.currentLang() === 'en';
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
const timer = setTimeout(() => { this.jobs.delete(id); reject(new Error(en ? 'Claude UI connection unavailable; check plugin status' : 'Claude 界面连接不可用,请检查插件挂载状态')); }, 20000);
|
|
77
|
+
this.jobs.set(id, { id, method, threadId, options, resolve, reject, timer });
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
async projectGit(key) {
|
|
81
|
+
const en = this.currentLang() === 'en';
|
|
82
|
+
if (!this.store.validKey(key)) throw new Error(en ? 'Invalid session identifier' : '无效会话标识');
|
|
83
|
+
const session = await this.host('session', JSON.parse(key)[1]);
|
|
84
|
+
if (!session?.cwd) return { status: 'checked', hasRepository: false, hasRemote: false, projectKnown: true, projectPath: null };
|
|
85
|
+
return { ...await inspectGit(session.cwd), projectKnown: true, projectPath: session.cwd };
|
|
86
|
+
}
|
|
87
|
+
async tools(name, args) {
|
|
88
|
+
const lang = this.currentLang();
|
|
89
|
+
const en = lang === 'en';
|
|
90
|
+
if (args?.conversation_id && !this.store.validKey(args.conversation_id)) {
|
|
91
|
+
const identity = await this.host('identity', args.conversation_id);
|
|
92
|
+
if (!identity?.id) throw new Error(en ? 'Unable to match Claude Desktop session identity; use the host session ID' : '无法匹配 Claude Desktop 会话身份,请使用宿主的会话标识');
|
|
93
|
+
args = { ...args, conversation_id: JSON.stringify(['local', identity.id]) };
|
|
94
|
+
}
|
|
95
|
+
return callProgressTool(this.store, name, args, { projectGit: key => this.projectGit(key), resolveProjects: async keys => {
|
|
96
|
+
const result = {};
|
|
97
|
+
for (const key of keys) { const session = await this.host('session', JSON.parse(key)[1]); if (session) result[key] = session.cwd || null; }
|
|
98
|
+
return result;
|
|
99
|
+
}, resolveSources: async (key, tasks) => {
|
|
100
|
+
const server = this.makeServer();
|
|
101
|
+
try { return await resolveTaskSources(server.request.bind(server), key, tasks); }
|
|
102
|
+
finally { await server.close(); }
|
|
103
|
+
}, lang });
|
|
104
|
+
}
|
|
105
|
+
async locateSource(session, itemId) {
|
|
106
|
+
const lang = this.currentLang();
|
|
107
|
+
const en = lang === 'en';
|
|
108
|
+
if (!session || typeof itemId !== 'string' || !/^[\w-]{1,256}$/.test(itemId) || !await this.localSource.message(session, itemId)) {
|
|
109
|
+
throw new Error(en ? 'Source message not found' : '未找到来源消息');
|
|
110
|
+
}
|
|
111
|
+
return navigationResult(await this.requestHost('locate', session.sessionId, { itemId }), lang);
|
|
112
|
+
}
|
|
113
|
+
async rpc(message) {
|
|
114
|
+
const lang = this.currentLang();
|
|
115
|
+
const en = lang === 'en';
|
|
116
|
+
if (!message || typeof message.requestId !== 'string') throw new Error(en ? 'Invalid request' : '无效请求');
|
|
117
|
+
let errorInfo = null, error = null, projectGit = null, analysisState = null, updateInfo = null, pane = null;
|
|
118
|
+
try {
|
|
119
|
+
if (message.type === 'list') { /* Return the current snapshot. */ }
|
|
120
|
+
else if (message.type === 'panel-event') this.log(`panel.${message.action}`, { key: message.key });
|
|
121
|
+
else if (message.type === 'open-pane') {
|
|
122
|
+
if (!this.store.validKey(message.key) || JSON.parse(message.key)[0] !== 'local') throw new Error(en ? 'Invalid Claude session identifier' : '无效 Claude 会话标识');
|
|
123
|
+
pane = { delivered: await this.deliverPane(message.key, 4000) };
|
|
124
|
+
}
|
|
125
|
+
else if (message.type === 'app-update-info') updateInfo = await updates.getUpdateInfo({ force: message.force === true });
|
|
126
|
+
else if (message.type === 'app-update-start') { await updates.startUpdate(); updateInfo = await updates.getUpdateInfo(); }
|
|
127
|
+
else {
|
|
128
|
+
if (!this.store.validKey(message.key) || JSON.parse(message.key)[0] !== 'local') throw new Error(en ? 'Invalid Claude session identifier' : '无效 Claude 会话标识');
|
|
129
|
+
if (message.type === 'update') {
|
|
130
|
+
if (message.record?.state === 'pushed') requireGitRemote(await this.projectGit(message.key), lang);
|
|
131
|
+
this.store.update(message);
|
|
132
|
+
} else if (message.type === 'project-git') projectGit = await this.projectGit(message.key);
|
|
133
|
+
else if (message.type === 'locate-source') {
|
|
134
|
+
const session = this.localSource.resolve(JSON.parse(message.key)[1]);
|
|
135
|
+
const result = await this.locateSource(session, message.source?.itemId);
|
|
136
|
+
return { requestId: message.requestId, navigation: result };
|
|
137
|
+
}
|
|
138
|
+
else if (message.type === 'analysis-state') { analysisState = this.store.analysisState(message.key); this.log('sync.panel_read', { key: message.key, revision: analysisState.revision }); }
|
|
139
|
+
else if (message.type === 'analyze') {
|
|
140
|
+
const job = this.analysis.start(message.key, { requestId: message.requestId });
|
|
141
|
+
job.promise.catch(failure => this.log('analysis.error', { error: failure.message }));
|
|
142
|
+
analysisState = this.store.analysisState(message.key);
|
|
143
|
+
} else throw new Error(en ? 'Unknown action' : '未知操作');
|
|
144
|
+
}
|
|
145
|
+
} catch (failure) { errorInfo = errorDetails(failure, undefined, lang); error = failure.message; }
|
|
146
|
+
return { protocolVersion: PROTOCOL_VERSION, requestId: message.requestId, error, errorInfo,
|
|
147
|
+
...(this.store.validKey(message.key) && JSON.parse(message.key)[0] === 'local' ? { session: sessionView(this.store, message.key, { projectGit, capabilities: { locate: true }, lang }) } : {}), snapshot: this.syncSnapshot(), projectGit, analysisState, updateInfo, ...(pane ? { pane } : {}) };
|
|
148
|
+
}
|
|
149
|
+
async inline(message) {
|
|
150
|
+
const lang = this.currentLang();
|
|
151
|
+
const en = lang === 'en';
|
|
152
|
+
const { t } = getUi(lang);
|
|
153
|
+
const session = this.localSource.resolve(message.sessionId, message.cwd);
|
|
154
|
+
if (!session) throw new Error(en ? 'Local identity for the current Claude Code session was not found' : '未找到当前 Claude Code 会话的本地身份');
|
|
155
|
+
const key = JSON.stringify(['local', session.sessionId]);
|
|
156
|
+
if (message.action === 'pane-poll') return { paneRequested: this.takePaneRequest(key), lang };
|
|
157
|
+
if (message.action === 'pane-wait') return { paneRequested: await this.waitPaneRequest(key, message.waitMs), lang };
|
|
158
|
+
if (message.action === 'watch') {
|
|
159
|
+
const started = Date.now(), result = await this.watch(key, message.since, message.waitMs);
|
|
160
|
+
if (result.changed || result.paneRequested) this.log('watch.wake', { revision: this.store.data.revision, elapsedMs: Date.now() - started, ok: result.changed });
|
|
161
|
+
return { ...result, revision: this.store.data.revision };
|
|
162
|
+
}
|
|
163
|
+
let source = null;
|
|
164
|
+
if (message.action === 'source' || message.action === 'locate') {
|
|
165
|
+
const task = this.store.getProgress(key)?.tasks.find(task => task.id === message.taskId);
|
|
166
|
+
if (!task?.source) throw new Error(en ? 'No source record for this task' : '此任务没有来源记录');
|
|
167
|
+
source = { ...task.source, title: task.title };
|
|
168
|
+
if (message.action === 'locate') return { navigation: await this.locateSource(session, source.itemId), lang };
|
|
169
|
+
const original = await this.localSource.message(session, source.itemId);
|
|
170
|
+
source.text = original?.text || source.locator || '';
|
|
171
|
+
source.occurredAt = original?.occurredAt || null;
|
|
172
|
+
} else if (message.action === 'save' || message.action === 'clear') {
|
|
173
|
+
const reply = await this.rpc({ type: 'update', key, requestId: message.requestId,
|
|
174
|
+
expectedRevision: message.expectedRevision, record: message.action === 'clear' ? null : message.record });
|
|
175
|
+
if (reply.error) throw Object.assign(new Error(reply.error), reply.errorInfo || {});
|
|
176
|
+
} else if (message.action === 'analyze') {
|
|
177
|
+
const reply = await this.rpc({ type: 'analyze', key, requestId: message.requestId });
|
|
178
|
+
if (reply.error) throw Object.assign(new Error(reply.error), reply.errorInfo || {});
|
|
179
|
+
} else if (message.action === 'update-info' || message.action === 'upgrade') {
|
|
180
|
+
const reply = await this.rpc({ type: message.action === 'upgrade' ? 'app-update-start' : 'app-update-info', requestId: message.requestId });
|
|
181
|
+
if (reply.error) throw Object.assign(new Error(reply.error), reply.errorInfo || {});
|
|
182
|
+
return { updateInfo: reply.updateInfo, lang };
|
|
183
|
+
} else if (message.action !== 'read') throw new Error(en ? 'Unknown card action' : '未知卡片操作');
|
|
184
|
+
const projection = this.store.readSessionProjection(key);
|
|
185
|
+
// 只记每个会话读到新修订号的那一次:旧版插件每 2 秒轮询,逐次记录会刷满日志并冲掉验收记录。
|
|
186
|
+
if (message.action === 'read' && this.loggedReads.get(key) !== projection.revision) { this.loggedReads.set(key, projection.revision); this.log('sync.inline_read', { revision: projection.revision }); }
|
|
187
|
+
return { session: sessionView(this.store, key, { capabilities: { locate: true }, projection, lang }), key, title: session.title || t('fallbackShortTitle'), record: projection.record, lang,
|
|
188
|
+
revision: projection.revision, paneRequested: this.takePaneRequest(key), analysis: projection.analysis ? { ledger: { ...projection.analysis.ledger, tasks: projection.activeTasks } } : null, timeline: projection.timelineSummary, source,
|
|
189
|
+
...(message.action === 'read' && message.includeGit ? { projectGit: await this.projectGit(key) } : {}) };
|
|
190
|
+
}
|
|
191
|
+
waitPaneRequest(key, waitMs) {
|
|
192
|
+
if (this.takePaneRequest(key)) return Promise.resolve(true);
|
|
193
|
+
const limit = Math.min(Math.max(Number(waitMs) || 20000, 0), 25000);
|
|
194
|
+
return new Promise(resolve => {
|
|
195
|
+
const waiters = this.paneWaiters.get(key) || new Set();
|
|
196
|
+
const wake = value => { clearTimeout(timer); waiters.delete(wake); if (!waiters.size && this.paneWaiters.get(key) === waiters) this.paneWaiters.delete(key); resolve(value); };
|
|
197
|
+
const timer = setTimeout(() => wake(false), limit);
|
|
198
|
+
waiters.add(wake); this.paneWaiters.set(key, waiters);
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
keySignature(data, key) {
|
|
202
|
+
const timeline = (data.timeline || []).filter(item => item.key === key)
|
|
203
|
+
.map(item => [item.actionSequence, item.status, item.stage, item.error || null, item.finishedAt || null]);
|
|
204
|
+
return crypto.createHash('sha1').update(JSON.stringify([data.records?.[key] || null, data.analysis?.[key] || null, timeline])).digest('base64');
|
|
205
|
+
}
|
|
206
|
+
detectChanges() {
|
|
207
|
+
const data = this.store.data, keys = new Set([...Object.keys(data.records || {}), ...Object.keys(data.analysis || {}),
|
|
208
|
+
...(data.timeline || []).map(item => item.key), ...this.keySignatures.keys()]);
|
|
209
|
+
for (const key of keys) {
|
|
210
|
+
const signature = this.keySignature(data, key);
|
|
211
|
+
if (this.keySignatures.get(key) === signature) continue;
|
|
212
|
+
const known = this.keySignatures.has(key);
|
|
213
|
+
this.keySignatures.set(key, signature);
|
|
214
|
+
if (!known && !this.watchStarted) continue;
|
|
215
|
+
this.keyChanges.set(key, data.revision);
|
|
216
|
+
this.log('sync.change', { revision: data.revision, sent: this.watchers.get(key)?.size || 0 });
|
|
217
|
+
this.wakeWatchers(key, { changed: true });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
// 快照附带单会话数据版本:弹窗据此补读任务列表(任务来源等记录之外的变化也算)。未变过的会话取启动时修订号。
|
|
221
|
+
syncSnapshot() {
|
|
222
|
+
return { ...this.store.snapshot(), lang: this.currentLang(), keyVersionBase: this.watchStartRevision, keyVersions: Object.fromEntries(this.keyChanges) };
|
|
223
|
+
}
|
|
224
|
+
// 某会话自 since 之后是否变过:启动前的变化以启动时修订号计,令重连的客户端补读一次。
|
|
225
|
+
changedSince(key, since) {
|
|
226
|
+
const at = this.keyChanges.get(key) ?? this.watchStartRevision;
|
|
227
|
+
return Number.isInteger(since) ? at > since : true;
|
|
228
|
+
}
|
|
229
|
+
wakeWatchers(key, result) {
|
|
230
|
+
const set = this.watchers.get(key);
|
|
231
|
+
if (!set?.size) return false;
|
|
232
|
+
this.watchers.delete(key);
|
|
233
|
+
for (const wake of [...set]) wake(result);
|
|
234
|
+
return true;
|
|
235
|
+
}
|
|
236
|
+
watch(key, since, waitMs) {
|
|
237
|
+
if (this.takePaneRequest(key)) return Promise.resolve({ changed: this.changedSince(key, since), paneRequested: true });
|
|
238
|
+
if (this.changedSince(key, since)) return Promise.resolve({ changed: true, paneRequested: false });
|
|
239
|
+
const limit = Math.min(Math.max(Number(waitMs) || 20000, 0), 25000);
|
|
240
|
+
return new Promise(resolve => {
|
|
241
|
+
const set = this.watchers.get(key) || new Set();
|
|
242
|
+
const wake = (result = {}) => { clearTimeout(timer); set.delete(wake); if (!set.size && this.watchers.get(key) === set) this.watchers.delete(key);
|
|
243
|
+
resolve({ changed: Boolean(result.changed), paneRequested: Boolean(result.paneRequested) }); };
|
|
244
|
+
const timer = setTimeout(() => wake({}), limit);
|
|
245
|
+
set.add(wake); this.watchers.set(key, set);
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
// 交给该会话的 mod:有长轮询在等就立即送达;否则暂存 60 秒,并最多等 graceMs 看 mod 是否上线取走。
|
|
249
|
+
deliverPane(key, graceMs) {
|
|
250
|
+
if (this.wakeWatchers(key, { paneRequested: true })) return Promise.resolve(true);
|
|
251
|
+
const waiters = this.paneWaiters.get(key);
|
|
252
|
+
if (waiters?.size) { this.paneWaiters.delete(key); for (const wake of [...waiters]) wake(true); return Promise.resolve(true); }
|
|
253
|
+
this.paneRequests.get(key)?.settle(false);
|
|
254
|
+
return new Promise(resolve => {
|
|
255
|
+
const entry = { at: Date.now(), settle: value => { clearTimeout(timer); entry.settle = () => {}; resolve(value); } };
|
|
256
|
+
const timer = setTimeout(() => entry.settle(false), graceMs);
|
|
257
|
+
this.paneRequests.set(key, entry);
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
takePaneRequest(key) {
|
|
261
|
+
const entry = this.paneRequests.get(key);
|
|
262
|
+
if (!entry) return false;
|
|
263
|
+
this.paneRequests.delete(key);
|
|
264
|
+
const fresh = Date.now() - entry.at < 60000;
|
|
265
|
+
entry.settle(fresh);
|
|
266
|
+
return fresh;
|
|
267
|
+
}
|
|
268
|
+
startWatching() {
|
|
269
|
+
this.detectChanges();
|
|
270
|
+
this.watchStarted = true; this.watchStartRevision = this.store.data.revision;
|
|
271
|
+
// 兜底:其他进程直接写账本文件时也能发现(仅 stat,未变化时不读文件)。
|
|
272
|
+
this.changeTimer = setInterval(() => {
|
|
273
|
+
try {
|
|
274
|
+
if (this.store.reloadIfModified()) this.detectChanges();
|
|
275
|
+
const nextLang = this.currentLang();
|
|
276
|
+
if (nextLang !== this.lastLang) {
|
|
277
|
+
this.lastLang = nextLang;
|
|
278
|
+
for (const key of [...this.watchers.keys()]) this.wakeWatchers(key, { changed: true });
|
|
279
|
+
}
|
|
280
|
+
} catch { /* Next tick retries. */ }
|
|
281
|
+
}, 300);
|
|
282
|
+
this.changeTimer.unref?.();
|
|
283
|
+
}
|
|
284
|
+
async start() {
|
|
285
|
+
this.http = await startProgressHttp({ port: this.port, stateFile: this.stateFile, handle: async (method, route, body) => {
|
|
286
|
+
const en = this.currentLang() === 'en';
|
|
287
|
+
if (method === 'GET' && route === '/snapshot') return { snapshot: this.syncSnapshot() };
|
|
288
|
+
if (method === 'GET' && route === '/host-jobs') return [...this.jobs.values()].map(({ id, method, threadId, options }) => ({ id, method, threadId, options }));
|
|
289
|
+
if (method === 'POST' && route === '/host-reply') {
|
|
290
|
+
const job = this.jobs.get(body.id);
|
|
291
|
+
if (job) { this.jobs.delete(body.id); clearTimeout(job.timer); body.error ? job.reject(new Error(body.error)) : job.resolve(body.result); }
|
|
292
|
+
return { ok: true };
|
|
293
|
+
}
|
|
294
|
+
if (method === 'POST' && route === '/rpc') return this.rpc(body);
|
|
295
|
+
if (method === 'POST' && route === '/inline') return this.inline(body);
|
|
296
|
+
if (method === 'POST' && route === '/tools') return { result: await this.tools(body.name, body.args) };
|
|
297
|
+
throw new Error(en ? 'Unknown service route' : '未知服务路径');
|
|
298
|
+
} });
|
|
299
|
+
this.store.recoverPending();
|
|
300
|
+
this.startWatching();
|
|
301
|
+
return this.http.credentials.port;
|
|
302
|
+
}
|
|
303
|
+
async stop() {
|
|
304
|
+
const stopMsg = this.currentLang() === 'en' ? 'Claude background service stopped' : 'Claude 后台服务已停止';
|
|
305
|
+
for (const job of this.jobs.values()) { clearTimeout(job.timer); job.reject(new Error(stopMsg)); }
|
|
306
|
+
for (const waiters of [...this.paneWaiters.values()]) for (const wake of [...waiters]) wake(false);
|
|
307
|
+
for (const entry of this.paneRequests.values()) entry.settle(false);
|
|
308
|
+
clearInterval(this.changeTimer);
|
|
309
|
+
for (const set of [...this.watchers.values()]) for (const wake of [...set]) wake({});
|
|
310
|
+
this.jobs.clear(); await this.analysis.stop(); await this.http?.close();
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
module.exports = { ClaudeService, ClaudeStatusStore, DEFAULT_PORT, DEFAULT_STATE_FILE };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
|
|
4
|
+
function textContent(content) {
|
|
5
|
+
if (typeof content === 'string') return content;
|
|
6
|
+
return Array.isArray(content) ? content.filter(part => part.type === 'text').map(part => part.text || '').join('\n') : '';
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function transcriptTurns(result) {
|
|
10
|
+
const messages = Array.isArray(result) ? result : result?.messages;
|
|
11
|
+
if (!Array.isArray(messages)) throw new Error('Claude 会话文本格式不受支持');
|
|
12
|
+
const turns = [];
|
|
13
|
+
for (const entry of messages) appendTranscriptEntry(turns, entry);
|
|
14
|
+
return turns;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function appendTranscriptEntry(turns, entry) {
|
|
18
|
+
const clean = cleanTranscriptMessage(entry);
|
|
19
|
+
if (clean) appendCleanMessage(turns, clean);
|
|
20
|
+
}
|
|
21
|
+
function cleanTranscriptMessage(entry) {
|
|
22
|
+
const message = entry.message || entry;
|
|
23
|
+
const role = message.role || entry.type;
|
|
24
|
+
if (!['user', 'assistant'].includes(role) || entry.isSidechain) return null;
|
|
25
|
+
if (role === 'assistant' && message.stop_reason && message.stop_reason !== 'end_turn') return null;
|
|
26
|
+
const original = textContent(message.content);
|
|
27
|
+
const text = original.length > 24000 ? `${original.slice(0, 12000)}\n[内容已精简]\n${original.slice(-12000)}` : original;
|
|
28
|
+
if (!text.trim()) return null;
|
|
29
|
+
const id = entry.uuid || entry.id;
|
|
30
|
+
if (typeof id !== 'string' || !id) throw new Error('Claude 消息缺少稳定身份');
|
|
31
|
+
return { id, role, text, occurredAt: entry.timestamp || null };
|
|
32
|
+
}
|
|
33
|
+
function appendCleanMessage(turns, { id, role, text, occurredAt }) {
|
|
34
|
+
if (role === 'user') turns.push({ id, status: 'completed', startedAt: occurredAt, completedAt: occurredAt, items: [{ id, type: 'userMessage', content: [{ type: 'text', text }] }] });
|
|
35
|
+
else {
|
|
36
|
+
const turn = turns.at(-1);
|
|
37
|
+
if (turn) { turn.items.push({ id, type: 'agentMessage', text, phase: 'final_answer' }); turn.completedAt = occurredAt || turn.completedAt; }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
class ClaudeTranscriptServer {
|
|
42
|
+
constructor(host) { this.host = host; this.snapshotId = crypto.randomUUID(); }
|
|
43
|
+
async initialize() {}
|
|
44
|
+
async close() {}
|
|
45
|
+
async request(method, params) {
|
|
46
|
+
if (method === 'thread/read') {
|
|
47
|
+
const session = await this.host('session', params.threadId);
|
|
48
|
+
return { thread: { id: params.threadId, cwd: session?.cwd || null } };
|
|
49
|
+
}
|
|
50
|
+
if (method !== 'thread/turns/list') throw new Error('Claude 数据源不支持此方法');
|
|
51
|
+
return this.host('turns', params.threadId, { snapshotId: this.snapshotId, sortDirection: params.sortDirection || 'asc', cursor: params.cursor || null, limit: params.limit || 100 });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function pageClaudeTurns(turns, { sortDirection = 'asc', cursor = null, limit = 100 } = {}) {
|
|
56
|
+
const ordered = sortDirection === 'desc' ? [...turns].reverse() : turns;
|
|
57
|
+
const start = cursor ? ordered.findIndex(turn => turn.id === cursor) + 1 : 0;
|
|
58
|
+
if (cursor && start === 0) throw new Error('Claude 会话分页位置已变化,请重新分析');
|
|
59
|
+
const data = [];
|
|
60
|
+
let bytes = 0;
|
|
61
|
+
for (const turn of ordered.slice(start, start + Math.min(100, limit))) {
|
|
62
|
+
const size = Buffer.byteLength(JSON.stringify(turn));
|
|
63
|
+
if (size > 480000) throw new Error('Claude 单轮文本过大,请先精简该轮内容');
|
|
64
|
+
if (bytes + size > 480000 && data.length) break;
|
|
65
|
+
data.push(turn); bytes += size;
|
|
66
|
+
}
|
|
67
|
+
return { data, nextCursor: start + data.length < ordered.length ? data.at(-1).id : null };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
module.exports = { transcriptTurns, cleanTranscriptMessage, appendCleanMessage, pageClaudeTurns, ClaudeTranscriptServer };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { AnalysisService } = require('../../analysis-service.cjs');
|
|
3
|
+
const { AnalysisAppServer } = require('../../analysis-app-server.cjs');
|
|
4
|
+
const { runAnalysis } = require('../../analysis-runner.cjs');
|
|
5
|
+
|
|
6
|
+
function createCodexAnalysis(options) {
|
|
7
|
+
return new AnalysisService({ ...options, makeServer: settings => new AnalysisAppServer(settings), run: runAnalysis });
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
module.exports = { createCodexAnalysis };
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
(() => {
|
|
3
|
+
const container = document.getElementById('progress-card');
|
|
4
|
+
const pending = new Map();
|
|
5
|
+
const readActions = new Set(['analysis-state', 'project-git', 'app-update-info']);
|
|
6
|
+
let nextId = 0, ready = false, theme, initial, watchGeneration = 0;
|
|
7
|
+
|
|
8
|
+
const uiText = (key, fallback) => {
|
|
9
|
+
const p = window.__agentThingsPresentation;
|
|
10
|
+
const lang = initial?.lang || initial?.snapshot?.lang || window.__agentThingsLang || p?.lang || 'zh';
|
|
11
|
+
const ui = p?.forLang ? p.forLang(lang) : null;
|
|
12
|
+
return ui?.strings?.[key] ?? p?.strings?.[key] ?? fallback;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function notify(method, params, id) {
|
|
16
|
+
window.parent.postMessage({ jsonrpc: '2.0', method, params, ...(id == null ? {} : { id }) }, '*');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function request(method, params, timeout = 15000, uiRequestId) {
|
|
20
|
+
const id = ++nextId;
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const timer = setTimeout(() => { pending.delete(id); reject(new Error(uiText('cardTimeout', '卡片连接超时'))); }, timeout);
|
|
23
|
+
pending.set(id, { resolve, reject, timer, uiRequestId });
|
|
24
|
+
notify(method, params, id);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function watchChanges(conversationId, cardToken) {
|
|
29
|
+
const generation = ++watchGeneration;
|
|
30
|
+
let cursor, retryMs = 500;
|
|
31
|
+
while (generation === watchGeneration) {
|
|
32
|
+
try {
|
|
33
|
+
const result = await request('tools/call', { name: 'read_session_card', arguments: {
|
|
34
|
+
conversation_id: conversationId, card_token: cardToken, action: 'watch-state', ...(cursor ? { cursor } : {}),
|
|
35
|
+
} });
|
|
36
|
+
if (generation !== watchGeneration) return;
|
|
37
|
+
const state = result.structuredContent;
|
|
38
|
+
if (result.isError || !state?.cursor) throw new Error(result.content?.[0]?.text || uiText('cardSyncUnavailable', '卡片同步暂不可用'));
|
|
39
|
+
cursor = state.cursor;
|
|
40
|
+
retryMs = 500;
|
|
41
|
+
window.__codexSessionStatus?.receiveCardEvent(state);
|
|
42
|
+
} catch {
|
|
43
|
+
if (generation !== watchGeneration) return;
|
|
44
|
+
window.__codexSessionStatus?.disconnectCardEvents();
|
|
45
|
+
await new Promise(resolve => setTimeout(resolve, retryMs));
|
|
46
|
+
retryMs = Math.min(retryMs * 2, 8000);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
window.addEventListener('pagehide', () => {
|
|
52
|
+
watchGeneration++;
|
|
53
|
+
for (const [id, entry] of pending) {
|
|
54
|
+
clearTimeout(entry.timer);
|
|
55
|
+
notify('notifications/cancelled', { requestId: id });
|
|
56
|
+
entry.reject(new Error(uiText('cardClosed', '卡片已关闭')));
|
|
57
|
+
}
|
|
58
|
+
pending.clear();
|
|
59
|
+
});
|
|
60
|
+
window.addEventListener('pageshow', event => {
|
|
61
|
+
if (event.persisted && initial?.conversationId && initial.cardToken) void watchChanges(initial.conversationId, initial.cardToken);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
function mount() {
|
|
65
|
+
if (!ready || !initial || window.__codexSessionStatus) return;
|
|
66
|
+
const { conversationId, cardToken, key, title, snapshot, analysisState, session } = initial;
|
|
67
|
+
if (!conversationId || !key || !snapshot) { container.textContent = uiText('cardMissingSession', '卡片缺少当前会话信息'); return; }
|
|
68
|
+
if (!cardToken) { container.textContent = uiText('cardAuthUnavailable', '卡片授权不可用,请重新打开会话进度卡片'); return; }
|
|
69
|
+
container.replaceChildren();
|
|
70
|
+
installCodexSessionStatus('codex-mcp-app', null, {
|
|
71
|
+
container, key, title, snapshot, analysisState, session, theme, lang: initial.lang || snapshot?.lang,
|
|
72
|
+
async send(payload) {
|
|
73
|
+
const { type, requestId, expectedRevision, record, source, cancelRequestId } = JSON.parse(payload);
|
|
74
|
+
if (type === 'panel-event') return;
|
|
75
|
+
if (type === 'cancel-request') {
|
|
76
|
+
for (const [id, entry] of pending) if (entry.uiRequestId === cancelRequestId) {
|
|
77
|
+
notify('notifications/cancelled', { requestId: id }); clearTimeout(entry.timer); pending.delete(id);
|
|
78
|
+
entry.reject(Object.assign(new Error(uiText('cardRequestCancelled', '请求已取消')), { code: 'REQUEST_CANCELLED' }));
|
|
79
|
+
}
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const name = readActions.has(type) ? 'read_session_card' : 'change_session_card';
|
|
83
|
+
try {
|
|
84
|
+
const result = await request('tools/call', { name, arguments: { conversation_id: conversationId, card_token: cardToken, action: type,
|
|
85
|
+
...(expectedRevision == null ? {} : { expectedRevision }), ...(record === undefined ? {} : { record }), ...(source ? { source } : {}) } }, 18000, requestId);
|
|
86
|
+
const errorInfo = result.structuredContent?.errorInfo;
|
|
87
|
+
const error = result.isError || !result.structuredContent ? result.content?.[0]?.text || uiText('cardOpFailed', '卡片操作失败') : undefined;
|
|
88
|
+
window.__codexSessionStatus?.reply({ requestId, ...result.structuredContent, error, errorInfo });
|
|
89
|
+
} catch (error) { window.__codexSessionStatus?.reply({ requestId, error: error.message, errorInfo: { code: error.code || 'HOST_UNAVAILABLE', message: error.message, retryable: true } }); }
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
new ResizeObserver(() => {
|
|
93
|
+
const height = Math.ceil(container.getBoundingClientRect().height);
|
|
94
|
+
notify('ui/notifications/size-changed', { height });
|
|
95
|
+
}).observe(container);
|
|
96
|
+
void watchChanges(conversationId, cardToken);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
window.addEventListener('message', ({ source, data }) => {
|
|
100
|
+
if (source !== window.parent || data?.jsonrpc !== '2.0') return;
|
|
101
|
+
const entry = pending.get(data.id);
|
|
102
|
+
if (entry) {
|
|
103
|
+
clearTimeout(entry.timer); pending.delete(data.id);
|
|
104
|
+
if (data.error) entry.reject(new Error(data.error.message)); else entry.resolve(data.result);
|
|
105
|
+
}
|
|
106
|
+
if (data.method === 'ui/notifications/tool-result') {
|
|
107
|
+
initial = { ...data.params?.structuredContent, cardToken: data.params?._meta?.cardToken };
|
|
108
|
+
mount();
|
|
109
|
+
} else if (data.method === 'ui/notifications/host-context-changed') {
|
|
110
|
+
theme = data.params?.theme;
|
|
111
|
+
window.__codexSessionStatus?.setTheme(theme);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
request('ui/initialize', { appInfo: { name: 'agent-things', version: window.__agentThingsVersion || '1.1.1' }, appCapabilities: {}, protocolVersion: '2026-01-26' }, 5000)
|
|
116
|
+
.then(result => {
|
|
117
|
+
theme = result?.hostContext?.theme;
|
|
118
|
+
ready = true;
|
|
119
|
+
notify('ui/notifications/initialized', {});
|
|
120
|
+
mount();
|
|
121
|
+
})
|
|
122
|
+
.catch(error => { container.textContent = error.message; });
|
|
123
|
+
})();
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
|
|
6
|
+
const { progressError } = require('../../progress-error.cjs');
|
|
7
|
+
|
|
8
|
+
const WAIT_MS = 10000;
|
|
9
|
+
|
|
10
|
+
function cardCursor({ snapshot, analysisState }) {
|
|
11
|
+
// The ledger's global revision also changes when another chat is written.
|
|
12
|
+
return crypto.createHash('sha256').update(JSON.stringify([
|
|
13
|
+
snapshot.records, analysisState.analysis, analysisState.timeline,
|
|
14
|
+
])).digest('hex');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function createCardEvents({ store, read, waitMs = WAIT_MS }) {
|
|
18
|
+
const waiting = new Map();
|
|
19
|
+
const fileName = path.basename(store.file);
|
|
20
|
+
let watcher, closed = false;
|
|
21
|
+
|
|
22
|
+
function stopWatching(error) {
|
|
23
|
+
watcher?.close();
|
|
24
|
+
watcher = null;
|
|
25
|
+
for (const waiters of waiting.values()) {
|
|
26
|
+
for (const waiter of waiters) waiter.finish(null, error);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function publish(_event, file) {
|
|
31
|
+
if (!waiting.size || (file && file !== fileName)) return;
|
|
32
|
+
try {
|
|
33
|
+
store.reloadIfModified(true);
|
|
34
|
+
for (const [key, waiters] of waiting) {
|
|
35
|
+
const state = read(key);
|
|
36
|
+
const cursor = cardCursor(state);
|
|
37
|
+
for (const waiter of waiters) {
|
|
38
|
+
if (waiter.cursor !== cursor) waiter.finish({ ...state, cursor });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
} catch (error) { stopWatching(error); }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
async wait(key, previousCursor, signal) {
|
|
46
|
+
signal?.throwIfAborted();
|
|
47
|
+
if (closed) throw new Error('卡片同步已关闭');
|
|
48
|
+
if (!watcher) {
|
|
49
|
+
watcher = fs.watch(path.dirname(store.file), { persistent: false }, publish);
|
|
50
|
+
watcher.on('error', stopWatching);
|
|
51
|
+
}
|
|
52
|
+
const state = read(key);
|
|
53
|
+
const cursor = cardCursor(state);
|
|
54
|
+
if (cursor !== previousCursor) return { ...state, cursor };
|
|
55
|
+
const waiters = waiting.get(key) || new Set();
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
const waiter = { cursor, finish(result, error) {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
signal?.removeEventListener('abort', abort);
|
|
60
|
+
waiters.delete(waiter);
|
|
61
|
+
if (!waiters.size) waiting.delete(key);
|
|
62
|
+
if (error) reject(error); else resolve(result || { cursor });
|
|
63
|
+
} };
|
|
64
|
+
const abort = () => waiter.finish(null, progressError('REQUEST_CANCELLED'));
|
|
65
|
+
const timer = setTimeout(() => waiter.finish(), waitMs);
|
|
66
|
+
waiters.add(waiter);
|
|
67
|
+
waiting.set(key, waiters);
|
|
68
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
69
|
+
if (signal?.aborted) abort();
|
|
70
|
+
});
|
|
71
|
+
},
|
|
72
|
+
close() { closed = true; stopWatching(); },
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
module.exports = { createCardEvents };
|