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,197 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const crypto = require('node:crypto');
5
+ const { createAnalysisLog, diagnosticFields } = require('./analysis-log.cjs');
6
+ const { captureExtracted } = require('./analysis-source.cjs');
7
+ const { prepareIncremental, commitCheckpoint } = require('./analysis-history.cjs');
8
+ const { mergeAnalysis } = require('./analysis-ledger.cjs');
9
+ const { readProjectGit } = require('./analysis-git.cjs');
10
+ const { assertUpdateIdle } = require('./npm-updates.cjs');
11
+
12
+ const { nextBatch, measureRequest, splitAdaptiveBatches, FULL_PASS_MAX_BYTES, FULL_PASS_TOKEN_BUDGET, getAnalysisInstructions } = require('./analysis-budget.cjs');
13
+ const { errorDetails, progressError } = require('./progress-error.cjs');
14
+ const { readConfiguredLang } = require('./i18n.cjs');
15
+ const versions = { prompt: '4', schema: '4', ledger: '3' };
16
+ class AnalysisService {
17
+ constructor({ store, onChange = () => {}, makeServer, run,
18
+ resources = path.join(__dirname, 'analysis-assets'), logFile = path.join(path.dirname(store.file), 'analysis.jsonl'),
19
+ maxBytes = FULL_PASS_MAX_BYTES, tokenBudget = FULL_PASS_TOKEN_BUDGET, lang = null }) {
20
+ if (typeof makeServer !== 'function' || typeof run !== 'function') throw new TypeError('分析服务需要会话源和模型执行器');
21
+ Object.assign(this, { store, onChange, makeServer, run, resources, maxBytes, tokenBudget, lang });
22
+ this.log = createAnalysisLog(logFile);
23
+ this.active = new Map();
24
+ this.stopped = false;
25
+ }
26
+ activeLang() {
27
+ return this.lang || readConfiguredLang({ dataDir: path.dirname(this.store.file) });
28
+ }
29
+ analyze(key) { return this.start(key).promise; }
30
+
31
+ start(key, { requestId } = {}) {
32
+ if (this.stopped) throw progressError('SERVICE_STOPPING');
33
+ const existing = [...this.active.values()].find(job => job.key === key);
34
+ if (existing && this.store.analysisState(key).timeline.some(event => event.actionSequence === existing.sequence && event.status === 'pending')) return { promise: existing.promise, runId: existing.runId, actionSequence: existing.sequence };
35
+ assertUpdateIdle();
36
+ const [hostId, sidebarId] = JSON.parse(key);
37
+ const threadId = sidebarId.startsWith('local:') ? sidebarId.slice(6) : sidebarId;
38
+ if (hostId !== 'local') throw new Error('当前仅支持本机会话');
39
+ const runId = crypto.randomUUID();
40
+ let sequence;
41
+ try { sequence = this.store.beginAnalysis(key, null); }
42
+ catch (error) { this.log('analysis.rejected', { runId, requestId, threadId, ...diagnosticFields(error) }); throw error; }
43
+ this.onChange(key, { status: 'pending', stage: 'starting' });
44
+ const controller = new AbortController();
45
+ const startedAt = Date.now(), startedMono = performance.now();
46
+ const log = (event, fields = {}) => this.log(event, { runId, requestId, threadId, hostId, actionSequence: sequence,
47
+ jobElapsedMs: Math.round(performance.now() - startedMono), jobWallElapsedMs: Date.now() - startedAt, ...fields });
48
+ const job = { key, runId, sequence, controller, server: null, promise: null, log };
49
+ log('analysis.start', { promptVersion: versions.prompt, schemaVersion: versions.schema, ledgerVersion: versions.ledger });
50
+ this.active.set(sequence, job);
51
+ job.promise = this.runAnalysis(key, sequence, hostId, threadId, job).finally(() => this.active.delete(sequence));
52
+ return { promise: job.promise, runId, actionSequence: sequence };
53
+ }
54
+
55
+ async runAnalysis(key, sequence, hostId, threadId, job) {
56
+ let server;
57
+ try {
58
+ server = job.server = this.makeServer({ log: job.log }); await server.initialize();
59
+ job.controller.signal.throwIfAborted();
60
+ let attempt = 1;
61
+ const capture = () => captureExtracted(server.request.bind(server), hostId, threadId, info => {
62
+ this.store.updateAnalysis(key, sequence, { boundary: info.boundary, boundaryAttempt: attempt, stats: { turnCount: info.turnCount, rawBytes: info.rawBytes, compactBytes: info.compactBytes } });
63
+ job.log('source.page', { attempt, turnCount: info.turnCount, rawBytes: info.rawBytes, compactBytes: info.compactBytes,
64
+ throughTurnId: info.boundary?.turnId });
65
+ this.onChange(key, { status: 'pending', stage: 'reading' });
66
+ });
67
+ this.store.updateAnalysis(key, sequence, { stage: 'reading' }); this.onChange(key, { status: 'pending', stage: 'reading' });
68
+ job.log('analysis.stage', { stage: 'reading', attempt });
69
+ let captured;
70
+ try { captured = await capture(); }
71
+ catch (error) {
72
+ if (error.code !== 'APP_SERVER_TIMEOUT' || job.controller.signal.aborted) throw error;
73
+ job.log('source.retry', { attempt: 2, ...diagnosticFields(error) });
74
+ this.store.updateAnalysis(key, sequence, { stage: 'retrying' }); this.onChange(key, { status: 'pending', stage: 'retrying' });
75
+ await server.close();
76
+ job.controller.signal.throwIfAborted();
77
+ server = job.server = this.makeServer({ log: job.log });
78
+ await server.initialize();
79
+ job.controller.signal.throwIfAborted();
80
+ attempt = 2;
81
+ this.store.updateAnalysis(key, sequence, { stage: 'reading', stats: { turnCount: 0, rawBytes: 0, compactBytes: 0 }, attempt: 2 }); this.onChange(key, { status: 'pending', stage: 'reading' });
82
+ captured = await capture();
83
+ }
84
+ this.store.updateAnalysis(key, sequence, { boundary: captured.boundary, boundaryAttempt: attempt, stats: { turnCount: captured.boundary?.turnCount ?? 0, rawBytes: captured.extracted.stats.rawBytes, compactBytes: captured.extracted.stats.compactBytes } }); this.onChange(key, { status: 'pending', stage: 'reading' });
85
+ const extracted = captured.extracted;
86
+ const projectGit = await readProjectGit(server.request.bind(server), threadId);
87
+ job.log('project.git', { reason: projectGit.status, hasRemote: projectGit.hasRemote });
88
+ const lang = this.activeLang();
89
+ const activeVersions = lang === 'en'
90
+ ? { ...versions, prompt: `${versions.prompt}-en`, schema: `${versions.schema}-en` }
91
+ : versions;
92
+ const instructions = getAnalysisInstructions(lang);
93
+ const previous = this.store.analysisState(key).analysis;
94
+ const delta = prepareIncremental(extracted, previous?.checkpoint, activeVersions);
95
+ job.log('source.complete', { reason: delta.reason, turnCount: extracted.turnHashes.length,
96
+ rawBytes: extracted.stats.rawBytes, compactBytes: extracted.stats.compactBytes, eventCount: delta.events.length,
97
+ changedTurn: delta.changedTurn, previousTaskCount: previous?.ledger?.tasks?.length || 0, lang });
98
+ let ledger = previous?.ledger || delta.ledger;
99
+ const allSources = { ...extracted.sources };
100
+ if (ledger) {
101
+ ledger = structuredClone(ledger);
102
+ // Replayed history may assign an old short ref to a different message.
103
+ const sourceRefs = new Map();
104
+ const retainedRefs = new Set(ledger.tasks.flatMap(task => task.evidenceRefs || []));
105
+ for (const ref of ledger.gitPush?.evidenceRefs || []) retainedRefs.add(ref);
106
+ for (const [ref, source] of Object.entries(previous?.sources || {})) {
107
+ if (!retainedRefs.has(ref)) continue;
108
+ const nextRef = delta.reason === 'incremental' ? ref : `p${sequence}_${ref}`;
109
+ sourceRefs.set(ref, nextRef);
110
+ allSources[nextRef] = source;
111
+ }
112
+ const remap = refs => (refs || []).map(ref => sourceRefs.get(ref) || ref);
113
+ for (const task of ledger.tasks) task.evidenceRefs = remap(task.evidenceRefs);
114
+ if (ledger.gitPush) ledger.gitPush.evidenceRefs = remap(ledger.gitPush.evidenceRefs);
115
+ }
116
+ const manualEvents = this.store.analysisState(key).timeline.filter(item => item.source === 'manual' && item.actionSequence < sequence &&
117
+ item.actionSequence > (delta.reason === 'incremental' ? previous?.checkpoint?.actionSequence || 0 : 0)).map(item => {
118
+ const ref = `m${item.actionSequence}`;
119
+ allSources[ref] = { hostId, threadId, actionSequence: item.actionSequence, requestedAt: item.requestedAt };
120
+ return { ref, type: 'manual', effectiveAtMs: item.requestedAt, state: item.record.state, progress: item.record.progress ?? null, note: item.record.note ?? '' };
121
+ });
122
+ const promptFile = lang === 'en' && fs.existsSync(path.join(this.resources, 'prompt.en.txt')) ? 'prompt.en.txt' : 'prompt.zh-CN.txt';
123
+ const schemaFile = lang === 'en' && fs.existsSync(path.join(this.resources, 'output.en.schema.json')) ? 'output.en.schema.json' : 'output.schema.json';
124
+ const prompt = fs.readFileSync(path.join(this.resources, promptFile), 'utf8');
125
+ const schema = JSON.parse(fs.readFileSync(path.join(this.resources, schemaFile), 'utf8'));
126
+ if (manualEvents.length && delta.events.some(event => event.turnStartedAt == null)) {
127
+ extracted.gaps.push(lang === 'en' ? 'Some turn timestamps are unknown; ordering with manual records could not be verified' : '部分对话时间未知,无法确定与手动记录的先后');
128
+ }
129
+ this.store.updateAnalysis(key, sequence, { stage: 'analyzing', batch: { current: 1, total: 1 } }); this.onChange(key, { status: 'pending', stage: 'analyzing' });
130
+ job.log('analysis.stage', { stage: 'analyzing' });
131
+ const allowedRefs = new Set((ledger?.tasks || []).flatMap(task => task.evidenceRefs));
132
+ for (const ref of ledger?.gitPush?.evidenceRefs || []) allowedRefs.add(ref);
133
+
134
+ // 优先单次全量打完;若超出预算则自适应 1/2 对半折叠(Binary Split)拆分成批次
135
+ const manualContext = manualEvents;
136
+ const batches = splitAdaptiveBatches({
137
+ events: delta.events,
138
+ baseInput: { manualContext, gaps: extracted.gaps, projectGit },
139
+ prompt,
140
+ schema,
141
+ maxBytes: this.maxBytes,
142
+ tokenBudget: this.tokenBudget,
143
+ sources: allSources,
144
+ lang,
145
+ instructions,
146
+ });
147
+ const totalBatches = batches.length;
148
+ if (totalBatches > 1) {
149
+ job.log('model.batch.split', { totalBatches, totalEvents: delta.events.length, reason: 'budget_exceeded_adaptive_split' });
150
+ }
151
+
152
+ for (let b = 0; b < totalBatches; b++) {
153
+ const currentBatch = b + 1;
154
+ const events = batches[b];
155
+ const input = { previousLedger: ledger, events, manualContext, gaps: extracted.gaps, projectGit };
156
+ for (const event of events) allowedRefs.add(event.ref);
157
+ for (const event of manualContext) allowedRefs.add(event.ref);
158
+
159
+ this.store.updateAnalysis(key, sequence, { stage: 'analyzing', batch: { current: currentBatch, total: totalBatches } });
160
+ this.onChange(key, { status: 'pending', stage: 'analyzing', batch: { current: currentBatch, total: totalBatches } });
161
+
162
+ const log = (event, fields) => job.log(event, { batch: currentBatch, totalBatches, ...fields });
163
+ const budget = measureRequest({ input, prompt, schema, maxBytes: this.maxBytes, tokenBudget: this.tokenBudget, lang, instructions });
164
+ log('model.batch.start', { eventCount: events.length, inputBytes: budget.inputBytes, bytes: budget.bytes, estimatedTokens: budget.estimatedTokens });
165
+ const result = await this.run({ prompt, schema, log, signal: job.controller.signal, input, maxBytes: this.maxBytes, tokenBudget: this.tokenBudget, lang, instructions });
166
+ job.controller.signal.throwIfAborted();
167
+ ledger = mergeAnalysis(ledger, result, allowedRefs, { lang });
168
+ log('model.batch.complete', { totalTasks: ledger.totalTasks, completedTasks: ledger.completedTasks, percent: ledger.percent });
169
+ }
170
+ job.controller.signal.throwIfAborted();
171
+ const checkpoint = commitCheckpoint(extracted, ledger, activeVersions);
172
+ checkpoint.actionSequence = sequence;
173
+ this.store.finishAnalysis(key, sequence, { ledger, checkpoint, sources: allSources, boundary: captured.boundary, projectGit });
174
+ job.log('analysis.complete', { totalTasks: ledger.totalTasks, completedTasks: ledger.completedTasks, percent: ledger.percent });
175
+ this.onChange(key, { status: 'completed' });
176
+ return this.store.analysisState(key);
177
+ } catch (error) {
178
+ if (job.controller.signal.aborted) error = job.controller.signal.reason;
179
+ job.log('analysis.failed', diagnosticFields(error));
180
+ this.store.finishAnalysis(key, sequence, { error: error.message, errorCode: errorDetails(error, 'ANALYSIS_FAILED').code });
181
+ this.onChange(key, { status: 'failed', error: error.message });
182
+ throw error;
183
+ } finally {
184
+ job.log('analysis.cleanup.start');
185
+ await server?.close();
186
+ job.log('analysis.cleanup.complete');
187
+ }
188
+ }
189
+
190
+ async stop() {
191
+ this.stopped = true;
192
+ const jobs = [...this.active.values()];
193
+ for (const job of jobs) { job.log('analysis.cancel'); job.controller.abort(progressError('SERVICE_STOPPING')); job.server?.close(); }
194
+ await Promise.allSettled(jobs.map(job => job.promise));
195
+ }
196
+ }
197
+ module.exports = { AnalysisService };
@@ -0,0 +1,72 @@
1
+ 'use strict';
2
+
3
+ // The caller owns app-server transport and invokes this only for an explicit analysis action.
4
+ async function readTurns(request, threadId, boundary, onTurn, onPage) {
5
+ if (typeof request !== 'function' || typeof threadId !== 'string' || !threadId) throw new Error('会话来源无效');
6
+ const turns = [], cursors = new Set(), turnIds = new Set();
7
+ let cursor = null;
8
+ do {
9
+ const page = await request('thread/turns/list', { threadId, sortDirection: 'asc', itemsView: 'full', cursor, limit: 100 });
10
+ if (!page || !Array.isArray(page.data) || (page.nextCursor != null && typeof page.nextCursor !== 'string')) throw new Error('回合分页响应无效');
11
+ for (const turn of page.data) {
12
+ if (!turn || typeof turn.id !== 'string' || turnIds.has(turn.id)) throw new Error('回合分页重复或缺少标识');
13
+ turnIds.add(turn.id);
14
+ if (boundary && turn.id === boundary.id) { if (onTurn) await onTurn(boundary); else turns.push(boundary); if (onPage) await onPage(); return turns; }
15
+ if (onTurn) await onTurn(turn); else turns.push(turn);
16
+ }
17
+ if (onPage) await onPage();
18
+ cursor = page.nextCursor ?? null;
19
+ if (cursor !== null) {
20
+ if (!cursor || cursors.has(cursor) || page.data.length === 0) throw new Error('回合分页未连续前进');
21
+ cursors.add(cursor);
22
+ }
23
+ } while (cursor !== null);
24
+ if (boundary) throw new Error('分析边界已不存在,请重试');
25
+ return turns;
26
+ }
27
+
28
+ async function captureTurns(request, threadId) {
29
+ const page = await request('thread/turns/list', { threadId, sortDirection: 'desc', itemsView: 'full', cursor: null, limit: 1 });
30
+ if (!page || !Array.isArray(page.data) || page.data.length > 1) throw new Error('无法读取分析边界');
31
+ const boundary = page.data[0] ?? null;
32
+ if (!boundary) return { turns: [], boundary: null };
33
+ if (typeof boundary.id !== 'string' || !Array.isArray(boundary.items)) throw new Error('分析边界无效');
34
+ const turns = await readTurns(request, threadId, structuredClone(boundary));
35
+ return { turns, boundary: { turnId: boundary.id, itemId: boundary.items.at(-1)?.id ?? null, turnCount: turns.length, occurredAt: boundary.completedAt ?? boundary.startedAt ?? null } };
36
+ }
37
+ async function captureExtracted(request, hostId, threadId, onProgress = () => {}) {
38
+ const { extractHistory } = require('./analysis-history.cjs');
39
+ const page = await request('thread/turns/list', { threadId, sortDirection: 'desc', itemsView: 'full', cursor: null, limit: 1 });
40
+ if (!page || !Array.isArray(page.data) || page.data.length > 1) throw new Error('无法读取分析边界');
41
+ const boundary = page.data[0] ?? null;
42
+ const combined = extractHistory({ hostId, threadId, turns: [] });
43
+ const gaps = new Set(); let turnCount = 0, compactBytes = 2;
44
+ let capturedBoundary = null;
45
+ if (boundary) {
46
+ if (typeof boundary.id !== 'string' || !Array.isArray(boundary.items)) throw new Error('分析边界无效');
47
+ capturedBoundary = { turnId: boundary.id, itemId: boundary.items.at(-1)?.id ?? null, occurredAt: boundary.completedAt ?? boundary.startedAt ?? null };
48
+ await onProgress({ boundary: capturedBoundary, turnCount: 0, rawBytes: 0, compactBytes });
49
+ await readTurns(request, threadId, boundary, turn => {
50
+ const part = extractHistory({ hostId, threadId, turns: [turn] });
51
+ turnCount++;
52
+ for (const event of part.events) {
53
+ const old = event.ref;
54
+ const ref = old[0] + String(combined.events.length + 1);
55
+ const cleanEvent = { ...event, ref };
56
+ compactBytes += Buffer.byteLength(JSON.stringify(cleanEvent)) + (combined.events.length ? 1 : 0);
57
+ combined.events.push(cleanEvent); combined.sources[ref] = part.sources[old];
58
+ }
59
+ combined.turnHashes.push(...part.turnHashes);
60
+ combined.continuous &&= part.continuous;
61
+ for (const gap of part.gaps) gaps.add(gap);
62
+ combined.stats.rawBytes += part.stats.rawBytes;
63
+ combined.stats.filteredItems += part.stats.filteredItems;
64
+ }, () => onProgress({ boundary: capturedBoundary, turnCount, rawBytes: combined.stats.rawBytes, compactBytes }));
65
+ }
66
+ combined.gaps = [...gaps];
67
+ combined.stats.retainedEvents = combined.events.length;
68
+ combined.stats.compactBytes = Buffer.byteLength(JSON.stringify(combined.events));
69
+ combined.stats.estimatedTokens = Math.ceil(combined.stats.compactBytes / 3);
70
+ return { extracted: combined, boundary: capturedBoundary ? { ...capturedBoundary, turnCount } : null };
71
+ }
72
+ module.exports = { readTurns, captureTurns, captureExtracted };