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,150 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
|
|
4
|
+
const EXTRACTOR_VERSION = 3;
|
|
5
|
+
const hash = value => crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
6
|
+
|
|
7
|
+
// 规则 1:长代码块脱水(保留短示例命令,折叠冗长实现片段)
|
|
8
|
+
function dehydrateCodeBlocks(text) {
|
|
9
|
+
return text.replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g, (match, lang, code) => {
|
|
10
|
+
const lines = code.split('\n');
|
|
11
|
+
if (lines.length <= 5 && code.length <= 160) return match;
|
|
12
|
+
const header = lines.slice(0, 2).join('\n');
|
|
13
|
+
const footer = lines.slice(-1).join('\n');
|
|
14
|
+
return '```' + (lang || '') + '\n' + header + '\n// ... [代码块共 ' + lines.length + ' 行已折叠] ...\n' + footer + '\n```';
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// 规则 3:连续终端日志堆栈脱水(折叠连续多行时间戳日志行)
|
|
19
|
+
function dehydrateTerminalLogs(text) {
|
|
20
|
+
const logLineRegex = /^\[?\d{2,4}[-:\/]\d{2}[-:\/]\d{2,4}[ T]?\d{2}:\d{2}:\d{2}(?:\.\d+)?\]?/;
|
|
21
|
+
const lines = text.split('\n');
|
|
22
|
+
const compacted = [];
|
|
23
|
+
let logBuffer = [];
|
|
24
|
+
|
|
25
|
+
const flushLogs = () => {
|
|
26
|
+
if (logBuffer.length > 5) {
|
|
27
|
+
compacted.push(...logBuffer.slice(0, 2));
|
|
28
|
+
compacted.push('[... 中间 ' + (logBuffer.length - 4) + ' 行时间戳运行日志已折叠 ...]');
|
|
29
|
+
compacted.push(...logBuffer.slice(-2));
|
|
30
|
+
} else {
|
|
31
|
+
compacted.push(...logBuffer);
|
|
32
|
+
}
|
|
33
|
+
logBuffer = [];
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
for (let i = 0; i < lines.length; i++) {
|
|
37
|
+
const line = lines[i];
|
|
38
|
+
if (logLineRegex.test(line.trim())) {
|
|
39
|
+
logBuffer.push(line);
|
|
40
|
+
} else {
|
|
41
|
+
flushLogs();
|
|
42
|
+
compacted.push(line);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
flushLogs();
|
|
46
|
+
return compacted.join('\n');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Strip only recognized machine envelopes; quoted XML and ordinary human text remain data.
|
|
50
|
+
function cleanMessage(text) {
|
|
51
|
+
let value = text.trim();
|
|
52
|
+
const leading = /^<(heartbeat|in-app-browser-context|send_user_message_question_reply)\b[^>]*>([\s\S]*?)<\/\1>/;
|
|
53
|
+
let match;
|
|
54
|
+
while ((match = value.match(leading))) {
|
|
55
|
+
let replacement = '';
|
|
56
|
+
if (match[1] === 'send_user_message_question_reply') {
|
|
57
|
+
try {
|
|
58
|
+
const replies = JSON.parse(match[2]);
|
|
59
|
+
if (!Array.isArray(replies) || replies.some(reply => typeof reply.question !== 'string' || typeof reply.answer !== 'string')) return value;
|
|
60
|
+
replacement = replies.map(reply => `提问:${reply.question}\n用户回答:${reply.answer}`).join('\n');
|
|
61
|
+
} catch { return value; }
|
|
62
|
+
}
|
|
63
|
+
value = (replacement + '\n' + value.slice(match[0].length)).trim();
|
|
64
|
+
if (replacement) break;
|
|
65
|
+
}
|
|
66
|
+
// 仅应用规则 1 (代码块脱水) 与 规则 3 (终端日志脱水),智能体正文汇报完整保留
|
|
67
|
+
value = dehydrateCodeBlocks(value);
|
|
68
|
+
value = dehydrateTerminalLogs(value);
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Input is an ordered, complete list of app-server turns, not raw tool output.
|
|
73
|
+
function extractHistory({ hostId, threadId, turns, continuous = true }) {
|
|
74
|
+
if (typeof hostId !== 'string' || typeof threadId !== 'string' || !Array.isArray(turns)) throw new Error('会话来源无效');
|
|
75
|
+
const events = [], sources = {}, gaps = new Set();
|
|
76
|
+
let filtered = 0, bytes = 0;
|
|
77
|
+
const turnHashes = [];
|
|
78
|
+
const emit = (prefix, turn, item, data) => {
|
|
79
|
+
const ref = `${prefix}${events.length + 1}`;
|
|
80
|
+
const event = { ref, turnStartedAt: turn.startedAt ?? null, turnCompletedAt: turn.completedAt ?? null, ...data };
|
|
81
|
+
events.push(event);
|
|
82
|
+
const locator = typeof data.text === 'string' ? data.text.split('\n').map(line => line.trim()).find(line => line.length >= 10 && !/^[#<\-]/.test(line))?.slice(0, 24) : null;
|
|
83
|
+
sources[ref] = { hostId, threadId, turnId: turn.id, itemId: item.id, locator: locator || null, turnStartedAt: turn.startedAt ?? null, turnCompletedAt: turn.completedAt ?? null, hash: hash(data) };
|
|
84
|
+
};
|
|
85
|
+
const ids = new Set();
|
|
86
|
+
for (const turn of turns) {
|
|
87
|
+
if (!turn || typeof turn.id !== 'string' || !Array.isArray(turn.items) || ids.has(turn.id)) throw new Error('回合来源无效或重复');
|
|
88
|
+
ids.add(turn.id);
|
|
89
|
+
if (turn.itemsView && turn.itemsView !== 'full') gaps.add('回合条目未完整加载');
|
|
90
|
+
if (!['completed', 'failed', 'interrupted', 'inProgress'].includes(turn.status)) gaps.add('未知回合状态');
|
|
91
|
+
bytes += Buffer.byteLength(JSON.stringify(turn));
|
|
92
|
+
const lastUnknown = turn.status === 'completed' && !turn.items.some(item => item.type === 'agentMessage' && item.phase === 'final_answer')
|
|
93
|
+
? turn.items.findLast(item => item.type === 'agentMessage' && item.phase == null) : null;
|
|
94
|
+
const turnEvents = [];
|
|
95
|
+
const begin = events.length;
|
|
96
|
+
const itemIds = new Set();
|
|
97
|
+
for (const item of turn.items) {
|
|
98
|
+
if (!item || typeof item.id !== 'string' || itemIds.has(item.id)) throw new Error('条目来源无效或重复');
|
|
99
|
+
itemIds.add(item.id);
|
|
100
|
+
if (item.type === 'userMessage' && Array.isArray(item.content)) {
|
|
101
|
+
const text = cleanMessage(item.content.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n'));
|
|
102
|
+
if (text) emit('u', turn, item, { type: 'user', text }); else filtered++;
|
|
103
|
+
} else if (item.type === 'agentMessage' && typeof item.text === 'string' && (item.phase === 'final_answer' || item === lastUnknown)) {
|
|
104
|
+
const text = cleanMessage(item.text);
|
|
105
|
+
if (text) {
|
|
106
|
+
emit('a', turn, item, { type: 'answer', text, finality: item.phase === 'final_answer' ? 'confirmed' : 'unknown' });
|
|
107
|
+
if (item.phase == null) gaps.add('最终答复标记未知');
|
|
108
|
+
} else filtered++;
|
|
109
|
+
} else filtered++;
|
|
110
|
+
}
|
|
111
|
+
for (const event of events.slice(begin)) turnEvents.push({ ...event, ref: undefined, itemId: sources[event.ref].itemId });
|
|
112
|
+
turnHashes.push({ turnId: turn.id, status: turn.status, hash: hash({ status: turn.status, itemsView: turn.itemsView || 'full', events: turnEvents }) });
|
|
113
|
+
if (turnEvents.length && turn.status !== 'completed') gaps.add(`回合${turn.status}`);
|
|
114
|
+
if (turn.status === 'completed' && turnEvents.some(event => event.type === 'user') && !turnEvents.some(event => event.type === 'answer')) gaps.add('回合缺少最终答复');
|
|
115
|
+
}
|
|
116
|
+
if (!continuous) gaps.add('分页不连续');
|
|
117
|
+
const compactBytes = Buffer.byteLength(JSON.stringify(events));
|
|
118
|
+
return { hostId, threadId, events, sources, turnHashes, limitations: [], continuous: continuous && !gaps.has('回合条目未完整加载'), gaps: [...gaps],
|
|
119
|
+
stats: { rawBytes: bytes, compactBytes, retainedEvents: events.length, filteredItems: filtered, estimatedTokens: Math.ceil(compactBytes / 3) }, extractorVersion: EXTRACTOR_VERSION };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// A successful checkpoint binds the ledger to an immutable completed prefix.
|
|
123
|
+
function prepareIncremental(extracted, checkpoint, versions) {
|
|
124
|
+
if (!extracted.continuous) throw new Error('来源不连续,不能推进检查点');
|
|
125
|
+
if (checkpoint && (checkpoint.hostId !== extracted.hostId || checkpoint.threadId !== extracted.threadId)) throw new Error('检查点会话不匹配');
|
|
126
|
+
let start = 0, reason = 'initial', changedTurn;
|
|
127
|
+
const versionsMatch = !versions || ['prompt', 'schema', 'ledger'].every(key => checkpoint?.versions?.[key] === versions[key]);
|
|
128
|
+
if (checkpoint && checkpoint.extractorVersion === extracted.extractorVersion && versionsMatch) {
|
|
129
|
+
const prior = checkpoint.turnHashes;
|
|
130
|
+
while (start < prior.length && start < extracted.turnHashes.length && prior[start].turnId === extracted.turnHashes[start].turnId && prior[start].hash === extracted.turnHashes[start].hash) start++;
|
|
131
|
+
reason = start === prior.length ? 'incremental' : 'history_changed';
|
|
132
|
+
if (reason === 'history_changed') {
|
|
133
|
+
changedTurn = { index: start, previousTurnId: prior[start]?.turnId, currentTurnId: extracted.turnHashes[start]?.turnId };
|
|
134
|
+
start = 0;
|
|
135
|
+
}
|
|
136
|
+
} else if (checkpoint) reason = versionsMatch ? 'extractor_changed' : 'versions_changed';
|
|
137
|
+
const turnIds = new Set(extracted.turnHashes.slice(start).map(turn => turn.turnId));
|
|
138
|
+
return { reason, changedTurn, startTurn: start, events: extracted.events.filter(event => turnIds.has(extracted.sources[event.ref].turnId)),
|
|
139
|
+
ledger: checkpoint?.ledger || null };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function commitCheckpoint(extracted, ledger, versions) {
|
|
143
|
+
if (!extracted.continuous) throw new Error('来源不连续,不能推进检查点');
|
|
144
|
+
if (!ledger || typeof ledger !== 'object' || !versions?.prompt || !versions?.schema || !versions?.ledger) throw new Error('成功账本或版本缺失');
|
|
145
|
+
if (extracted.turnHashes.some(turn => !['completed', 'failed', 'interrupted'].includes(turn.status))) throw new Error('范围含未完成回合,不能推进检查点');
|
|
146
|
+
return { hostId: extracted.hostId, threadId: extracted.threadId, extractorVersion: extracted.extractorVersion,
|
|
147
|
+
versions: { prompt: versions.prompt, schema: versions.schema, ledger: versions.ledger },
|
|
148
|
+
turnHashes: extracted.turnHashes, ledger };
|
|
149
|
+
}
|
|
150
|
+
module.exports = { extractHistory, prepareIncremental, commitCheckpoint };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
const { readConfiguredLang, getUi } = require('./i18n.cjs');
|
|
4
|
+
|
|
5
|
+
const STATES = new Set(['todo', 'in_progress', 'blocked', 'needs_verification', 'done']);
|
|
6
|
+
const exactKeys = (value, keys) => value && typeof value === 'object' && !Array.isArray(value) &&
|
|
7
|
+
Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
|
|
8
|
+
|
|
9
|
+
function summarizeTasks(ledger, { lang = readConfiguredLang() } = {}) {
|
|
10
|
+
const totalTasks = ledger.tasks.length;
|
|
11
|
+
const completedTasks = ledger.tasks.filter(task => task.status === 'done').length;
|
|
12
|
+
const remainingTasks = totalTasks - completedTasks;
|
|
13
|
+
const known = totalTasks > 0;
|
|
14
|
+
const percent = known ? Math.round(completedTasks * 100 / totalTasks) : null;
|
|
15
|
+
const ui = getUi(lang);
|
|
16
|
+
return {
|
|
17
|
+
totalTasks,
|
|
18
|
+
completedTasks,
|
|
19
|
+
remainingTasks,
|
|
20
|
+
percent,
|
|
21
|
+
remainingPercent: percent === null ? null : 100 - percent,
|
|
22
|
+
basis: totalTasks
|
|
23
|
+
? ui.t('basisPattern', { done: completedTasks, total: totalTasks, remaining: remainingTasks, remainingPercent: 100 - percent })
|
|
24
|
+
: ui.strings.basisEmpty,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function mergeAnalysis(previous, output, allowedRefs, { lang = readConfiguredLang(), maxTaskSummaryLength } = {}) {
|
|
29
|
+
const en = lang === 'en';
|
|
30
|
+
const maxSummaryLen = Number.isInteger(maxTaskSummaryLength) ? maxTaskSummaryLength : (en ? 60 : 20);
|
|
31
|
+
const keys = ['summary', 'tasks', 'removedTaskIds', ...(Object.hasOwn(output || {}, 'gitPush') ? ['gitPush'] : [])];
|
|
32
|
+
if (!exactKeys(output, keys) || typeof output.summary !== 'string' || !Array.isArray(output.tasks) || !Array.isArray(output.removedTaskIds)) {
|
|
33
|
+
throw new Error(en ? 'Invalid analysis result format' : '分析结果格式无效');
|
|
34
|
+
}
|
|
35
|
+
const known = new Map((previous?.tasks || []).map(task => [task.id, task]));
|
|
36
|
+
const removed = new Set();
|
|
37
|
+
for (const id of output.removedTaskIds) {
|
|
38
|
+
if (typeof id !== 'string' || !known.has(id) || removed.has(id)) {
|
|
39
|
+
throw new Error(en ? 'Invalid removedTaskIds entry' : '移除任务标识无效');
|
|
40
|
+
}
|
|
41
|
+
removed.add(id);
|
|
42
|
+
}
|
|
43
|
+
const seen = new Set(), changes = [];
|
|
44
|
+
const refs = new Set(allowedRefs);
|
|
45
|
+
let gitPush = previous?.gitPush;
|
|
46
|
+
if (Object.hasOwn(output, 'gitPush')) {
|
|
47
|
+
const value = output.gitPush;
|
|
48
|
+
if (!exactKeys(value, ['status', 'evidenceRefs']) || !['unknown', 'not_pushed', 'pushed'].includes(value.status) ||
|
|
49
|
+
!Array.isArray(value.evidenceRefs) || value.evidenceRefs.some(ref => typeof ref !== 'string' || !refs.has(ref)) ||
|
|
50
|
+
(value.status === 'pushed' && !value.evidenceRefs.length)) {
|
|
51
|
+
throw new Error(en ? 'Invalid gitPush status or evidence' : '推送状态或证据无效');
|
|
52
|
+
}
|
|
53
|
+
gitPush = { status: value.status, evidenceRefs: [...new Set(value.evidenceRefs)] };
|
|
54
|
+
}
|
|
55
|
+
for (const [index, task] of output.tasks.entries()) {
|
|
56
|
+
if (!exactKeys(task, ['knownTaskId', 'title', 'status', 'evidenceRefs', ...(Object.hasOwn(task, 'summary') ? ['summary'] : [])]) ||
|
|
57
|
+
(task.knownTaskId !== null && typeof task.knownTaskId !== 'string') ||
|
|
58
|
+
typeof task.title !== 'string' || !task.title.trim() || !STATES.has(task.status) || !Array.isArray(task.evidenceRefs) ||
|
|
59
|
+
task.evidenceRefs.some(ref => typeof ref !== 'string' || !refs.has(ref))) {
|
|
60
|
+
throw new Error(en ? 'Invalid task entry or evidenceRefs' : '任务结果或证据无效');
|
|
61
|
+
}
|
|
62
|
+
if (Object.hasOwn(task, 'summary') && (typeof task.summary !== 'string' || !task.summary.trim() || [...task.summary].length > maxSummaryLen)) {
|
|
63
|
+
const length = typeof task.summary === 'string' ? [...task.summary].length : 0;
|
|
64
|
+
throw new Error(en
|
|
65
|
+
? `Invalid short summary for task #${index + 1} "${task.title}": got ${length} chars, expected 1 to ${maxSummaryLen} chars. Please shorten this task summary.`
|
|
66
|
+
: `第 ${index + 1} 项任务“${task.title}”的短总结无效:当前 ${length} 个字符,要求为1至${maxSummaryLen}个字符,请修改该项 summary`);
|
|
67
|
+
}
|
|
68
|
+
if (task.knownTaskId !== null && (!known.has(task.knownTaskId) || seen.has(task.knownTaskId) || removed.has(task.knownTaskId))) {
|
|
69
|
+
throw new Error(en ? 'Conflicting task identifier' : '任务标识冲突');
|
|
70
|
+
}
|
|
71
|
+
const id = task.knownTaskId ?? crypto.randomUUID();
|
|
72
|
+
seen.add(id);
|
|
73
|
+
const summary = task.summary ?? (known.get(id)?.title === task.title ? known.get(id).summary : undefined);
|
|
74
|
+
changes.push({ id, title: task.title, ...(summary ? { summary } : {}), status: task.status, evidenceRefs: [...new Set(task.evidenceRefs)] });
|
|
75
|
+
}
|
|
76
|
+
const result = new Map([...known].filter(([id]) => !removed.has(id)));
|
|
77
|
+
for (const task of changes) result.set(task.id, task);
|
|
78
|
+
const ledger = { summary: output.summary, tasks: [...result.values()], ...(gitPush ? { gitPush } : {}) };
|
|
79
|
+
return { ...ledger, ...summarizeTasks(ledger, { lang }) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = { mergeAnalysis, summarizeTasks };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
// Only diagnostic metadata can cross this boundary; arbitrary text is discarded.
|
|
6
|
+
const FIELDS = new Set(('runId threadId hostId actionSequence requestId requestType stage method model rpcId attempt batch batches ' +
|
|
7
|
+
'pid parentPid code signal elapsedMs wallElapsedMs jobElapsedMs jobWallElapsedMs idleMs timeoutMs overshootMs bytes inputBytes outputBytes promptBytes instructionBytes schemaBytes stdinBytes profile throughTurnId ' +
|
|
8
|
+
'estimatedTokens rawBytes compactBytes turnCount eventCount totalTasks completedTasks percent eventType itemType diagnostic component hasRemote ' +
|
|
9
|
+
'httpStatus systemCode ok sent revision resourceVersion catalogVersion cacheAgeMs inputTokens outputTokens cachedInputTokens promptVersion schemaVersion ledgerVersion reason').split(' '));
|
|
10
|
+
|
|
11
|
+
function diagnosticFields(value) {
|
|
12
|
+
const text = typeof value === 'string' ? value : String(value?.message || '');
|
|
13
|
+
const diagnostic = /已有分析|already.*(?:running|pending)/i.test(text) ? 'already_running'
|
|
14
|
+
: /unauthorized|authentication|not logged in|login|sign.in|\b401\b/i.test(text) ? 'authentication'
|
|
15
|
+
: /rate.limit|quota|usage.limit|\b429\b/i.test(text) ? 'rate_limit'
|
|
16
|
+
: /code.mode.*(disabled|unavailable)/i.test(text) ? 'code_mode_disabled'
|
|
17
|
+
: /model.*(not found|unavailable|not supported|access)|model_not_found/i.test(text) ? 'model_unavailable'
|
|
18
|
+
: /context.length|context.window|too many tokens/i.test(text) ? 'context_limit'
|
|
19
|
+
: /dns|ENOTFOUND|name resolution/i.test(text) ? 'dns'
|
|
20
|
+
: /certificate|\bTLS\b|\bSSL\b/i.test(text) ? 'tls'
|
|
21
|
+
: /timed?.?out|timeout|超时/i.test(text) ? 'timeout'
|
|
22
|
+
: /connection|disconnect|unexpected eof|ECONNRESET|EPIPE/i.test(text) ? 'connection'
|
|
23
|
+
: /中断|abort/i.test(text) ? 'cancelled' : 'other';
|
|
24
|
+
const result = { diagnostic };
|
|
25
|
+
const status = text.match(/\b(?:http(?: status)?|status(?: code)?)[:= ]+(\d{3})\b/i);
|
|
26
|
+
if (status) result.httpStatus = Number(status[1]);
|
|
27
|
+
if (/codex_models_manager|available models|list_models/i.test(text)) result.component = 'model_catalog';
|
|
28
|
+
else if (/codex_core_plugins|plugin catalog|featured plugin/i.test(text)) result.component = 'plugin_catalog';
|
|
29
|
+
if (/^(?:E[A-Z0-9_]+|APP_SERVER_TIMEOUT)$/.test(value?.code || '')) result.systemCode = value.code;
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function createAnalysisLog(file, { maxBytes = 2 * 1024 * 1024, backups = 3 } = {}) {
|
|
34
|
+
let warned = false;
|
|
35
|
+
return (event, fields = {}) => {
|
|
36
|
+
if (!/^[a-z][a-z0-9_.]{0,79}$/.test(event)) return;
|
|
37
|
+
const entry = { time: new Date().toISOString(), event, processId: process.pid };
|
|
38
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
39
|
+
if (!FIELDS.has(key)) continue;
|
|
40
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'number' && Number.isFinite(value)) entry[key] = value;
|
|
41
|
+
else if (typeof value === 'string' && /^[A-Za-z0-9_./:-]{1,120}$/.test(value)) entry[key] = value;
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
45
|
+
const line = JSON.stringify(entry) + '\n';
|
|
46
|
+
if (fs.existsSync(file) && fs.statSync(file).size + Buffer.byteLength(line) > maxBytes) {
|
|
47
|
+
for (let i = backups; i >= 1; i--) {
|
|
48
|
+
const from = i === 1 ? file : `${file}.${i - 1}`;
|
|
49
|
+
const to = `${file}.${i}`;
|
|
50
|
+
if (fs.existsSync(to)) fs.unlinkSync(to);
|
|
51
|
+
if (fs.existsSync(from)) fs.renameSync(from, to);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
fs.appendFileSync(file, line, { mode: 0o600 });
|
|
55
|
+
fs.chmodSync(file, 0o600);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (!warned) { warned = true; console.error(`分析诊断日志写入失败(${diagnosticFields(error).systemCode || 'UNKNOWN'})`); }
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = { createAnalysisLog, diagnosticFields };
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const os = require('node:os');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { spawn, execFileSync } = require('node:child_process');
|
|
6
|
+
const { resolveCodexBin } = require('./resolve.cjs');
|
|
7
|
+
const { diagnosticFields } = require('./analysis-log.cjs');
|
|
8
|
+
|
|
9
|
+
const disabled = ['shell_tool', 'unified_exec', 'apps', 'plugins', 'hooks', 'browser_use', 'computer_use', 'multi_agent', 'view_image', 'sleep_tool', 'code_mode_host',
|
|
10
|
+
'code_mode', 'code_mode_only', 'goals', 'current_time_reminder'];
|
|
11
|
+
const { getAnalysisInstructions, measureRequest } = require('./analysis-budget.cjs');
|
|
12
|
+
const { readConfiguredLang } = require('./i18n.cjs');
|
|
13
|
+
const { resolveLatestLuna, resolveLowCostModel } = require('./model-router.cjs');
|
|
14
|
+
const ALLOWED_ITEMS = new Set(['agent_message', 'reasoning', 'error']);
|
|
15
|
+
|
|
16
|
+
function prepareModelCatalog({ home, directory, binary, log = () => {},
|
|
17
|
+
readVersion = executable => execFileSync(executable, ['--version'], { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] }) }) {
|
|
18
|
+
const started = performance.now();
|
|
19
|
+
const fallback = reason => { log('catalog.fallback', { reason, elapsedMs: Math.round(performance.now() - started) }); return null; };
|
|
20
|
+
try {
|
|
21
|
+
const source = path.join(home, 'models_cache.json');
|
|
22
|
+
const cached = JSON.parse(fs.readFileSync(source, 'utf8'));
|
|
23
|
+
if (!Array.isArray(cached.models) || !cached.models.every(model => model && typeof model.slug === 'string')) return fallback('invalid_cache');
|
|
24
|
+
const lunaModel = resolveLatestLuna(cached.models);
|
|
25
|
+
if (!lunaModel) return fallback('model_missing');
|
|
26
|
+
// A credential-file update invalidates this shortcut without reading credentials.
|
|
27
|
+
if (fs.statSync(path.join(home, 'auth.json')).mtimeMs > fs.statSync(source).mtimeMs) return fallback('account_changed');
|
|
28
|
+
const version = String(readVersion(binary)).match(/\b(\d+\.\d+\.\d+)/)?.[1];
|
|
29
|
+
if (!version || cached.client_version !== version) return fallback('version_mismatch');
|
|
30
|
+
const fetchedAt = Date.parse(cached.fetched_at);
|
|
31
|
+
if (!Number.isFinite(fetchedAt)) return fallback('invalid_cache');
|
|
32
|
+
const file = path.join(directory, 'model-catalog.json');
|
|
33
|
+
// This temporary catalog describes a JSON-only analysis process. Model
|
|
34
|
+
// instructions, context limits and other capability metadata remain intact.
|
|
35
|
+
const contents = JSON.stringify({ models: cached.models.map(model => model.slug === lunaModel
|
|
36
|
+
? { ...model, tool_mode: 'direct', apply_patch_tool_type: null, experimental_supported_tools: [] } : model) });
|
|
37
|
+
fs.writeFileSync(file, contents, { mode: 0o600 });
|
|
38
|
+
log('catalog.ready', { model: lunaModel, catalogVersion: version, cacheAgeMs: Date.now() - fetchedAt,
|
|
39
|
+
bytes: Buffer.byteLength(contents), elapsedMs: Math.round(performance.now() - started) });
|
|
40
|
+
return file;
|
|
41
|
+
} catch { return fallback('unavailable'); }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Error text can contain request or session content. Report only recognized categories.
|
|
45
|
+
function diagnosticHint(text, lang = readConfiguredLang()) {
|
|
46
|
+
const en = lang === 'en';
|
|
47
|
+
if (/unauthorized|authentication|not logged in|login|sign.in|\b401\b/i.test(text)) return en ? 'Please check Codex login status' : '请检查 Codex 登录状态';
|
|
48
|
+
if (/model.*(not found|unavailable|not supported|access)|model_not_found/i.test(text)) return en ? 'Model unavailable or unauthorized for this account' : '模型不可用或账户无权使用';
|
|
49
|
+
if (/rate.limit|quota|\b429\b/i.test(text)) return en ? 'Model request rate limit reached' : '模型请求达到限制';
|
|
50
|
+
if (/context.length|context.window|too many tokens|maximum context/i.test(text)) return en ? 'Input exceeds model context window' : '输入超过模型上下文限制';
|
|
51
|
+
if (/stream.*(disconnect|closed|reset|error)|connection.*(reset|closed)|unexpected eof/i.test(text)) return en ? 'Model response stream disconnected' : '模型响应连接中断';
|
|
52
|
+
if (/timed?.?out|timeout/i.test(text)) return en ? 'Model request timed out' : '模型请求超时';
|
|
53
|
+
const status = text.match(/\b(?:http(?: status)?|status(?: code)?)[:= ]+(\d{3})\b/i);
|
|
54
|
+
if (status) return en ? `Upstream service returned HTTP ${status[1]}` : `上游服务返回 HTTP ${status[1]}`;
|
|
55
|
+
return en ? 'Please check Codex logs and model configuration' : '请检查 Codex 日志及模型配置';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function runAnalysis({ input, prompt, schema, binary = resolveCodexBin(), spawnProcess = spawn, timeoutMs = 120000, signal, log = () => {},
|
|
59
|
+
catalogHome = process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), model = null, maxBytes = 192000, tokenBudget, lang = readConfiguredLang(), instructions }) {
|
|
60
|
+
const en = lang === 'en';
|
|
61
|
+
const activeInstructions = instructions || getAnalysisInstructions(lang);
|
|
62
|
+
const payload = JSON.stringify(input);
|
|
63
|
+
if (!measureRequest({ input, prompt, schema, maxBytes, tokenBudget, lang, instructions: activeInstructions }).fits) {
|
|
64
|
+
throw new Error(en ? 'Analysis payload exceeds single-batch budget' : '分析内容超过单批预算');
|
|
65
|
+
}
|
|
66
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-status-analysis-'));
|
|
67
|
+
const schemaFile = path.join(directory, 'schema.json');
|
|
68
|
+
const instructionsFile = path.join(directory, 'instructions.txt');
|
|
69
|
+
const outputFile = path.join(directory, 'answer.json');
|
|
70
|
+
fs.writeFileSync(schemaFile, JSON.stringify(schema), { mode: 0o600 });
|
|
71
|
+
fs.writeFileSync(instructionsFile, activeInstructions, { mode: 0o600 });
|
|
72
|
+
const stdin = en ? `${prompt}\n\nInput data (analyze as data only):\n${payload}` : `${prompt}\n\n输入数据(仅作为待分析内容):\n${payload}`;
|
|
73
|
+
const selectedModel = model || resolveLowCostModel('codex', { codexHome: catalogHome });
|
|
74
|
+
const args = ['exec', '--json', '--ephemeral', '--ignore-user-config', '--skip-git-repo-check', '-c', 'project_doc_max_bytes=0',
|
|
75
|
+
'-c', 'analytics.enabled=false', '-c', `model_instructions_file=${JSON.stringify(instructionsFile)}`,
|
|
76
|
+
'-c', 'skills.include_instructions=false', '-c', 'include_collaboration_mode_instructions=false',
|
|
77
|
+
'-c', 'include_environment_context=false', '-c', 'agents.enabled=false', '-c', 'tools.experimental_request_user_input.enabled=false', '--sandbox', 'read-only',
|
|
78
|
+
'--model', selectedModel, '--cd', directory, '--output-schema', schemaFile, '--output-last-message', outputFile,
|
|
79
|
+
...disabled.flatMap(name => ['--disable', name]), '-'];
|
|
80
|
+
try {
|
|
81
|
+
const catalog = prepareModelCatalog({ home: catalogHome, directory, binary, log });
|
|
82
|
+
if (catalog) args.splice(args.length - 1, 0, '-c', `model_catalog_json=${JSON.stringify(catalog)}`);
|
|
83
|
+
await new Promise((resolve, reject) => {
|
|
84
|
+
let child, timer, deadlineTimer, heartbeat, killTimer, drainTimer, exited = false, exitCode = null, settled = false, buffer = '', diagnostic = '', failure = null;
|
|
85
|
+
let itemDiagnostic = '', terminalDiagnostic = '', terminal = null;
|
|
86
|
+
const startedAt = Date.now(), startedMono = performance.now();
|
|
87
|
+
let lastEventAt = startedMono, eventCount = 0, lastDiagnostic = '';
|
|
88
|
+
const metrics = () => ({ elapsedMs: Math.round(performance.now() - startedMono), wallElapsedMs: Date.now() - startedAt,
|
|
89
|
+
idleMs: Math.round(performance.now() - lastEventAt), eventCount });
|
|
90
|
+
const emit = (event, fields = {}) => log(event, { pid: child?.pid, ...metrics(), ...fields });
|
|
91
|
+
const sendSignal = signal => emit('model.signal', { signal, sent: child?.kill(signal) });
|
|
92
|
+
const finish = error => {
|
|
93
|
+
if (settled) return;
|
|
94
|
+
settled = true; clearTimeout(timer); clearInterval(deadlineTimer); clearInterval(heartbeat); clearTimeout(killTimer); clearTimeout(drainTimer); signal?.removeEventListener('abort', onAbort);
|
|
95
|
+
emit('model.settled', { ok: !error, ...(error ? diagnosticFields(error) : {}) });
|
|
96
|
+
if (error) reject(error); else resolve();
|
|
97
|
+
};
|
|
98
|
+
const abort = error => {
|
|
99
|
+
if (failure || settled) return;
|
|
100
|
+
failure = error;
|
|
101
|
+
emit('model.stop', { ...diagnosticFields(error), timeoutMs,
|
|
102
|
+
overshootMs: Math.max(0, Date.now() - startedAt - timeoutMs) });
|
|
103
|
+
if (!exited) {
|
|
104
|
+
sendSignal('SIGTERM');
|
|
105
|
+
killTimer = setTimeout(() => { if (!exited) sendSignal('SIGKILL'); }, 1500);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const onAbort = () => abort(new Error(en ? 'Analysis aborted' : '分析已中断'));
|
|
109
|
+
try { child = spawnProcess(binary, args, { cwd: directory, stdio: ['pipe', 'pipe', 'pipe'] }); }
|
|
110
|
+
catch (error) { finish(error); return; }
|
|
111
|
+
emit('model.spawn', { model: 'gpt-6-luna', parentPid: process.pid, timeoutMs, profile: 'task_analysis_v1', inputBytes: Buffer.byteLength(payload),
|
|
112
|
+
promptBytes: Buffer.byteLength(prompt), instructionBytes: Buffer.byteLength(activeInstructions),
|
|
113
|
+
schemaBytes: Buffer.byteLength(JSON.stringify(schema)), stdinBytes: Buffer.byteLength(stdin) });
|
|
114
|
+
heartbeat = setInterval(() => emit('model.wait', { reason: failure ? 'stopping' : terminal ? 'process_exit' : 'response' }), 15000);
|
|
115
|
+
if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });
|
|
116
|
+
const deadline = Date.now() + timeoutMs;
|
|
117
|
+
timer = setTimeout(() => abort(new Error(en ? 'Analysis timed out' : '分析超时')), timeoutMs);
|
|
118
|
+
deadlineTimer = setInterval(() => {
|
|
119
|
+
if (Date.now() >= deadline) abort(new Error(en ? 'Analysis timed out' : '分析超时'));
|
|
120
|
+
}, Math.min(timeoutMs, 1000));
|
|
121
|
+
child.on('error', error => {
|
|
122
|
+
emit('model.process.error', diagnosticFields(error));
|
|
123
|
+
failure ||= error;
|
|
124
|
+
if (!child.pid && !exited) finish(failure);
|
|
125
|
+
});
|
|
126
|
+
child.stderr.on('data', chunk => {
|
|
127
|
+
diagnostic = (diagnostic + chunk.toString()).slice(-4096);
|
|
128
|
+
const fields = diagnosticFields(diagnostic), signature = JSON.stringify(fields);
|
|
129
|
+
if (signature !== lastDiagnostic) { emit('model.diagnostic', fields); lastDiagnostic = signature; }
|
|
130
|
+
});
|
|
131
|
+
const parseLine = line => {
|
|
132
|
+
if (!line.trim()) return;
|
|
133
|
+
let event;
|
|
134
|
+
try { event = JSON.parse(line); } catch { emit('model.protocol.error', { bytes: Buffer.byteLength(line) }); return abort(new Error(en ? 'Invalid analysis event format' : '分析事件格式无效')); }
|
|
135
|
+
lastEventAt = performance.now(); eventCount++;
|
|
136
|
+
const eventType = ['thread.started', 'turn.started', 'turn.completed', 'turn.failed', 'item.started', 'item.updated', 'item.completed', 'error'].includes(event.type) ? event.type : 'unknown';
|
|
137
|
+
const itemType = ['agent_message', 'reasoning', 'error', 'command_execution', 'file_change', 'mcp_tool_call', 'web_search', 'todo_list'].includes(event.item?.type) ? event.item.type : undefined;
|
|
138
|
+
emit('model.event', { eventType, itemType, bytes: Buffer.byteLength(line),
|
|
139
|
+
inputTokens: event.usage?.input_tokens, outputTokens: event.usage?.output_tokens, cachedInputTokens: event.usage?.cached_input_tokens });
|
|
140
|
+
if (event.type === 'error' || event.type === 'turn.failed' || event.item?.type === 'error') {
|
|
141
|
+
emit('model.event.diagnostic', diagnosticFields(event.item?.message || event.error?.message || event.message || ''));
|
|
142
|
+
}
|
|
143
|
+
if (event.type?.startsWith('item.') && event.item) {
|
|
144
|
+
if (!ALLOWED_ITEMS.has(event.item.type)) {
|
|
145
|
+
const toolName = String(event.item.type).replace(/[^a-z0-9_]/gi, '').slice(0, 80);
|
|
146
|
+
return abort(new Error(en ? `Analysis requested disallowed tool: ${toolName}` : `分析请求了不允许的工具:${toolName}`));
|
|
147
|
+
}
|
|
148
|
+
if (event.item.type === 'error' && typeof event.item.message === 'string') itemDiagnostic = event.item.message.slice(0, 4096);
|
|
149
|
+
}
|
|
150
|
+
if (event.type === 'turn.completed') terminal = terminal === 'failed' || terminal === 'error' ? terminal : 'completed';
|
|
151
|
+
if (event.type === 'turn.failed') {
|
|
152
|
+
terminal = 'failed';
|
|
153
|
+
terminalDiagnostic = typeof event.error?.message === 'string' ? event.error.message.slice(0, 4096) : '';
|
|
154
|
+
}
|
|
155
|
+
if (event.type === 'error') {
|
|
156
|
+
terminal = 'error';
|
|
157
|
+
terminalDiagnostic = typeof event.message === 'string' ? event.message.slice(0, 4096) : '';
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
child.stdout.on('data', chunk => {
|
|
161
|
+
buffer += chunk.toString();
|
|
162
|
+
if (buffer.length > 1024 * 1024) return abort(new Error(en ? 'Analysis event payload too large' : '分析事件过大'));
|
|
163
|
+
let newline;
|
|
164
|
+
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
165
|
+
const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);
|
|
166
|
+
parseLine(line);
|
|
167
|
+
if (failure) return;
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
const complete = code => {
|
|
171
|
+
if (settled) return;
|
|
172
|
+
if (!failure && buffer.trim()) parseLine(buffer);
|
|
173
|
+
if (failure) return finish(failure);
|
|
174
|
+
if (code === 0 && terminal === 'completed') return finish();
|
|
175
|
+
const source = terminal === 'failed' ? 'turn.failed' : terminal === 'error' ? 'error'
|
|
176
|
+
: terminal !== 'completed' ? (en ? 'turn.completed not received' : '未收到 turn.completed') : (en ? `exit code ${code}` : `退出码 ${code}`);
|
|
177
|
+
const hint = diagnosticHint(`${terminalDiagnostic} ${itemDiagnostic} ${diagnostic}`, lang);
|
|
178
|
+
finish(new Error(en ? `Analysis process did not complete cleanly (${source}): ${hint}` : `分析进程未成功完成(${source}):${hint}`));
|
|
179
|
+
};
|
|
180
|
+
child.once('exit', (code, signal) => {
|
|
181
|
+
exited = true; exitCode = code;
|
|
182
|
+
emit('model.exit', { code, signal: signal ?? child.signalCode ?? null });
|
|
183
|
+
// Descendants can keep stdio open after the CLI exits. Allow buffered events to
|
|
184
|
+
// drain, then release inherited pipes so they cannot keep the job pending forever.
|
|
185
|
+
drainTimer = setTimeout(() => {
|
|
186
|
+
emit('model.output.drain_timeout');
|
|
187
|
+
child.stdout.destroy(); child.stderr.destroy(); child.stdin.destroy();
|
|
188
|
+
complete(exitCode);
|
|
189
|
+
}, 500);
|
|
190
|
+
});
|
|
191
|
+
child.once('close', (code, signal) => { emit('model.close', { code, signal }); complete(exited ? exitCode : code); });
|
|
192
|
+
child.stdin.on('error', error => { emit('model.stdin.error', diagnosticFields(error)); abort(error); });
|
|
193
|
+
child.stdin.end(stdin);
|
|
194
|
+
});
|
|
195
|
+
try {
|
|
196
|
+
const contents = fs.readFileSync(outputFile, 'utf8');
|
|
197
|
+
const result = JSON.parse(contents);
|
|
198
|
+
log('model.output.valid', { outputBytes: Buffer.byteLength(contents) });
|
|
199
|
+
return result;
|
|
200
|
+
} catch (error) { log('model.output.failed', diagnosticFields(error)); throw error; }
|
|
201
|
+
} finally { fs.rmSync(directory, { recursive: true, force: true }); log('model.cleanup.complete'); }
|
|
202
|
+
}
|
|
203
|
+
module.exports = { runAnalysis, prepareModelCatalog };
|