agiledev-cli 0.1.5 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +300 -185
- package/SKILL.md +114 -98
- package/adev.js +1319 -1285
- package/autofix/agents/antigravity.js +379 -0
- package/autofix/agents/claude.js +147 -0
- package/autofix/agents/codex.js +179 -0
- package/autofix/agents/exec.js +230 -0
- package/autofix/agents/index.js +400 -0
- package/autofix/agents/opencode.js +233 -0
- package/autofix/agents/pi.js +247 -0
- package/autofix/agiledev.js +98 -0
- package/autofix/bridge.js +371 -0
- package/autofix/cli.js +712 -0
- package/autofix/context.js +152 -0
- package/autofix/conversation.js +302 -0
- package/autofix/coordinator.js +2892 -0
- package/autofix/git.js +459 -0
- package/autofix/policy.js +230 -0
- package/autofix/profile.js +578 -0
- package/autofix/public/app.js +3668 -0
- package/autofix/public/i18n-id.js +282 -0
- package/autofix/public/index.html +32 -0
- package/autofix/public/style.css +2463 -0
- package/autofix/queue.js +146 -0
- package/autofix/scheduler.js +994 -0
- package/autofix/scope.js +32 -0
- package/autofix/service.js +1940 -0
- package/autofix/store.js +375 -0
- package/autofix/workspace.js +298 -0
- package/autofix/worktree.js +379 -0
- package/docs/autofix-design.md +801 -0
- package/docs/autofix-profiles.example.json +65 -0
- package/imgs/Bug/350/247/243/345/206/263/345/244/207/346/263/250.png +0 -0
- package/imgs/logo.png +0 -0
- package/imgs//344/277/256/346/224/271Bug/347/212/266/346/200/201.png +0 -0
- package/imgs//345/270/256/346/210/221/344/277/256/345/244/215Bug-20260922-010.png +0 -0
- package/imgs//346/237/245/347/234/213/345/271/266/345/210/206/346/236/220/351/234/200/346/261/202/346/226/207/346/241/243.png +0 -0
- package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/347/216/260/345/234/250/346/234/211/345/223/252/344/272/233/345/274/200/345/217/221/344/273/273/345/212/241.png +0 -0
- package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/350/277/230/346/234/211/345/223/252/344/272/233Bug/346/234/252/350/247/243/345/206/263.png +0 -0
- package/package.json +39 -36
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 缺陷上下文装载:把敏捷系统上的缺陷详情、复现步骤、预期/实际行为、截图与评论
|
|
3
|
+
* 整理成修复 Agent 能直接消费的共享上下文。
|
|
4
|
+
*
|
|
5
|
+
* 为什么必须单独做:
|
|
6
|
+
* 主 Agent 转述缺陷时一定会丢信息——复现步骤被压缩、截图路径丢失、评论里的补充被忽略。
|
|
7
|
+
* 修复 Agent 拿到残缺的上下文就会"猜",猜出来的改动往往修的不是同一个问题。
|
|
8
|
+
* 所以上下文由调度器确定性装载,Agent 只读不改。
|
|
9
|
+
*/
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
import { htmlToText, downloadImages } from "../adev.js";
|
|
14
|
+
import { homeDir } from "./store.js";
|
|
15
|
+
|
|
16
|
+
/** 截图落盘目录:~/.agiledev-autofix/images/bug-<id>/ */
|
|
17
|
+
export function bugImageDir(bugId) {
|
|
18
|
+
return path.join(homeDir(), "images", `bug-${String(bugId ?? "unknown").replace(/[^\w.-]/g, "_")}`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 去掉 HTML 标签并压缩空白,保留换行结构(步骤通常是 <p>/<br>)。
|
|
23
|
+
*
|
|
24
|
+
* 空内容一律返回空串:上层要能区分「缺陷里没写」和「我没拿到」,
|
|
25
|
+
* 不能拿 "(空)" 这种占位文案冒充真实内容。
|
|
26
|
+
*/
|
|
27
|
+
export function plainText(raw) {
|
|
28
|
+
const input = String(raw ?? "");
|
|
29
|
+
if (!input.trim()) return "";
|
|
30
|
+
const text = htmlToText(input);
|
|
31
|
+
if (!text || text === "(空)") return "";
|
|
32
|
+
return text.replace(/\n{3,}/g, "\n\n").trim();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 归一化缺陷详情为共享上下文。
|
|
37
|
+
*
|
|
38
|
+
* 字段缺失时留 null/空数组,绝不用空字符串冒充"缺陷里没写"——
|
|
39
|
+
* 修复 Agent 需要区分"没写"和"我没拿到"。
|
|
40
|
+
*/
|
|
41
|
+
export function buildBugContext({ bug = {}, comments = [], images = [] } = {}) {
|
|
42
|
+
return {
|
|
43
|
+
code: bug.code || null,
|
|
44
|
+
title: bug.title || null,
|
|
45
|
+
severity: bug.severity || null,
|
|
46
|
+
status: bug.status || null,
|
|
47
|
+
description: plainText(bug.description) || null,
|
|
48
|
+
stepsToReproduce: plainText(bug.steps_to_reproduce) || null,
|
|
49
|
+
expectedBehavior: plainText(bug.expected_behavior) || null,
|
|
50
|
+
actualBehavior: plainText(bug.actual_behavior) || null,
|
|
51
|
+
reporter: bug.reporter_name || null,
|
|
52
|
+
assignee: bug.assignee_name || null,
|
|
53
|
+
iteration: bug.version_iteration_name || null,
|
|
54
|
+
createdAt: bug.created_at || null,
|
|
55
|
+
updatedAt: bug.updated_at || null,
|
|
56
|
+
screenshots: images.map(i => ({
|
|
57
|
+
file: i.file,
|
|
58
|
+
src: i.src || null,
|
|
59
|
+
// 告诉 Agent 这是本地文件路径,要直接读图而不是猜
|
|
60
|
+
hint: "本地已下载的缺陷截图,直接读取该文件查看界面表现",
|
|
61
|
+
})),
|
|
62
|
+
comments: (comments || []).map(c => ({
|
|
63
|
+
author: c.user_name || c.author_name || null,
|
|
64
|
+
at: c.created_at || null,
|
|
65
|
+
content: plainText(c.content),
|
|
66
|
+
})).filter(c => c.content),
|
|
67
|
+
loadedAt: new Date().toISOString(),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 从敏捷系统拉取缺陷详情 + 评论,并把截图下载到本地。
|
|
73
|
+
*
|
|
74
|
+
* 返回 { context, images };拉取失败时抛错,由调用方决定是重试还是转人工。
|
|
75
|
+
*/
|
|
76
|
+
export async function loadBugContext({ api, bugId, imageDir = null }) {
|
|
77
|
+
const [bug, comments] = await Promise.all([
|
|
78
|
+
api.getBug(bugId),
|
|
79
|
+
api.listComments(bugId).catch(() => []),
|
|
80
|
+
]);
|
|
81
|
+
|
|
82
|
+
const dir = imageDir || bugImageDir(bugId);
|
|
83
|
+
let images = [];
|
|
84
|
+
try {
|
|
85
|
+
// 截图藏在描述/步骤/预期/实际的富文本里,四处都要扫
|
|
86
|
+
images = await downloadImages(
|
|
87
|
+
api.config,
|
|
88
|
+
[bug.description, bug.steps_to_reproduce, bug.expected_behavior, bug.actual_behavior],
|
|
89
|
+
dir,
|
|
90
|
+
);
|
|
91
|
+
} catch {
|
|
92
|
+
// 截图下载失败不影响主流程:缺陷文字信息仍然可用
|
|
93
|
+
images = [];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { context: buildBugContext({ bug, comments, images }), images, raw: bug };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 上下文是否已经装载(避免重复拉取)。装载失败的不算成功,下次派工时再试。 */
|
|
100
|
+
export function hasContext(task) {
|
|
101
|
+
const c = task?.context;
|
|
102
|
+
if (!c || typeof c !== "object") return false;
|
|
103
|
+
return !!c.loadedAt && !c.loadError;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 把上下文渲染成给 Agent 看的纯文本。
|
|
108
|
+
*
|
|
109
|
+
* 结构固定,Agent 不需要猜字段在哪一段;截图单独成段并强调"必须打开看"。
|
|
110
|
+
*/
|
|
111
|
+
export function renderContextForAgent(context = {}) {
|
|
112
|
+
const lines = [];
|
|
113
|
+
const push = (label, value) => {
|
|
114
|
+
if (value == null || value === "") return;
|
|
115
|
+
lines.push(`【${label}】`, String(value), "");
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
lines.push(`缺陷编号:${context.code || "未知"}`, `标题:${context.title || "未知"}`);
|
|
119
|
+
if (context.severity) lines.push(`级别:${context.severity}`);
|
|
120
|
+
if (context.iteration) lines.push(`所属迭代:${context.iteration}`);
|
|
121
|
+
if (context.reporter) lines.push(`报告人:${context.reporter}`);
|
|
122
|
+
lines.push("");
|
|
123
|
+
|
|
124
|
+
push("复现步骤", context.stepsToReproduce);
|
|
125
|
+
push("预期行为", context.expectedBehavior);
|
|
126
|
+
push("实际行为", context.actualBehavior);
|
|
127
|
+
push("缺陷描述", context.description);
|
|
128
|
+
|
|
129
|
+
if (Array.isArray(context.screenshots) && context.screenshots.length) {
|
|
130
|
+
lines.push("【截图】");
|
|
131
|
+
context.screenshots.forEach((s, i) => {
|
|
132
|
+
lines.push(` ${i + 1}. ${s.file}`);
|
|
133
|
+
});
|
|
134
|
+
lines.push(" 以上是缺陷截图的本地路径,必须先打开查看界面表现再动手定位。", "");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (Array.isArray(context.comments) && context.comments.length) {
|
|
138
|
+
lines.push("【历史评论】");
|
|
139
|
+
for (const c of context.comments) {
|
|
140
|
+
lines.push(` - ${c.author || "?"}:${c.content}`);
|
|
141
|
+
}
|
|
142
|
+
lines.push("");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return lines.join("\n").trim();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 确保目录存在(截图下载前调用)。 */
|
|
149
|
+
export function ensureImageDir(dir) {
|
|
150
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
151
|
+
return dir;
|
|
152
|
+
}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent 实时会话:把 Agent CLI 的原生输出流解析成可在控制台阅读的消息。
|
|
3
|
+
*
|
|
4
|
+
* 存两份:
|
|
5
|
+
* - 内存/磁盘:按 scope(main 或任务编号)追加 JSONL,页面刷新后仍能看到最近过程;
|
|
6
|
+
* - 回调:Service 通过 onMessage 用 SSE 实时推给浏览器。
|
|
7
|
+
*
|
|
8
|
+
* Claude Code 的 stream-json、OpenCode 的 JSON 输出都尽量解析成文本 / 工具调用;
|
|
9
|
+
* 无法识别的行只保留成日志行,不把整段原始 JSON 灌进界面。
|
|
10
|
+
*/
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { statePath, enqueueWrite } from "./store.js";
|
|
14
|
+
|
|
15
|
+
const MAX_TEXT = 20000;
|
|
16
|
+
const MAX_LINES = 4000;
|
|
17
|
+
const KEEP_LINES = 2000;
|
|
18
|
+
const MAX_BUFFER = 1024 * 1024;
|
|
19
|
+
|
|
20
|
+
let seq = 0;
|
|
21
|
+
|
|
22
|
+
function safeName(scope) {
|
|
23
|
+
return String(scope || "main").replace(/[^a-zA-Z0-9._-]/g, "_") || "main";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function truncate(text) {
|
|
27
|
+
const s = String(text ?? "");
|
|
28
|
+
return s.length > MAX_TEXT ? `${s.slice(0, MAX_TEXT)}\n…(已截断)` : s;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 把 Claude 的 content 数组转成消息。 */
|
|
32
|
+
function contentToMessages(content, role) {
|
|
33
|
+
const out = [];
|
|
34
|
+
for (const c of Array.isArray(content) ? content : []) {
|
|
35
|
+
if (!c || typeof c !== "object") continue;
|
|
36
|
+
if (c.type === "text" && c.text) {
|
|
37
|
+
out.push({ role, kind: "text", text: truncate(c.text) });
|
|
38
|
+
} else if (c.type === "tool_use") {
|
|
39
|
+
out.push({
|
|
40
|
+
role: "agent",
|
|
41
|
+
kind: "tool",
|
|
42
|
+
text: String(c.name || "tool"),
|
|
43
|
+
name: String(c.name || "tool"),
|
|
44
|
+
input: c.input ?? null,
|
|
45
|
+
});
|
|
46
|
+
} else if (c.type === "thinking" && c.thinking) {
|
|
47
|
+
// 思考块默认折叠展示:保留完整决策过程,但不挤占正文
|
|
48
|
+
out.push({ role: "agent", kind: "thinking", text: truncate(c.thinking) });
|
|
49
|
+
} else if (c.type === "tool_result") {
|
|
50
|
+
out.push({
|
|
51
|
+
role: "tool",
|
|
52
|
+
kind: "tool_result",
|
|
53
|
+
text: truncate(toolResultText(c)),
|
|
54
|
+
...(c.is_error ? { error: true } : {}),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
// redacted_thinking 等加密块不展示:没有可读内容
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function toolResultText(c) {
|
|
63
|
+
if (typeof c.content === "string") return c.content;
|
|
64
|
+
if (Array.isArray(c.content)) {
|
|
65
|
+
return c.content
|
|
66
|
+
.map(x => (typeof x === "string" ? x : x?.text || ""))
|
|
67
|
+
.filter(Boolean)
|
|
68
|
+
.join("\n");
|
|
69
|
+
}
|
|
70
|
+
if (typeof c.result === "string") return c.result;
|
|
71
|
+
return "";
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 解析单个 JSON 对象,返回零到多条消息。 */
|
|
75
|
+
export function parseMessageObject(obj) {
|
|
76
|
+
if (Array.isArray(obj)) return obj.flatMap(parseMessageObject);
|
|
77
|
+
if (!obj || typeof obj !== "object") return [];
|
|
78
|
+
|
|
79
|
+
// Claude Code stream-json
|
|
80
|
+
if (obj.type === "assistant" && obj.message?.content) {
|
|
81
|
+
return contentToMessages(obj.message.content, "agent");
|
|
82
|
+
}
|
|
83
|
+
if (obj.type === "user" && obj.message?.content) {
|
|
84
|
+
return contentToMessages(obj.message.content, "tool");
|
|
85
|
+
}
|
|
86
|
+
if (obj.type === "system") {
|
|
87
|
+
if (obj.subtype === "init") {
|
|
88
|
+
const model = obj.model ? ` · ${obj.model}` : "";
|
|
89
|
+
return [{ role: "system", kind: "log", text: `会话已建立${model}` }];
|
|
90
|
+
}
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
if (obj.type === "result") {
|
|
94
|
+
const text = typeof obj.result === "string"
|
|
95
|
+
? obj.result
|
|
96
|
+
: (obj.result ? JSON.stringify(obj.result) : "");
|
|
97
|
+
return [{
|
|
98
|
+
role: "system",
|
|
99
|
+
kind: "result",
|
|
100
|
+
text: truncate(text || "(本轮结束,无文本输出)"),
|
|
101
|
+
...(obj.is_error === true ? { error: true } : {}),
|
|
102
|
+
}];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Antigravity stream-json(agy --output-format stream-json)
|
|
106
|
+
if (obj.event === "init") {
|
|
107
|
+
const model = obj.init?.model ? ` · ${obj.init.model}` : "";
|
|
108
|
+
return [{ role: "system", kind: "log", text: `Antigravity 会话已建立${model}` }];
|
|
109
|
+
}
|
|
110
|
+
if (obj.event === "step_update") {
|
|
111
|
+
const payload = obj.step_update || {};
|
|
112
|
+
const step = payload.step || payload;
|
|
113
|
+
const kind = String(step.step_type || step.type || "");
|
|
114
|
+
const info = step.tool_info || step.toolInfo || step.tool_call || step.toolCall || null;
|
|
115
|
+
const name = info?.name || info?.tool_name || step.tool_name || step.tool || null;
|
|
116
|
+
if (info || /tool/i.test(kind) || /tool/i.test(String(name || ""))) {
|
|
117
|
+
const toolName = String(name || "tool");
|
|
118
|
+
return [{ role: "agent", kind: "tool", text: toolName, name: toolName, input: info?.input ?? step.input ?? null }];
|
|
119
|
+
}
|
|
120
|
+
const text = [step.text, step.delta, step.content].find(v => typeof v === "string" && v.trim());
|
|
121
|
+
return text ? [{ role: "agent", kind: "text", text: truncate(text) }] : [];
|
|
122
|
+
}
|
|
123
|
+
if (obj.event === "result") {
|
|
124
|
+
const r = obj.result || {};
|
|
125
|
+
const text = typeof r.response === "string" && r.response
|
|
126
|
+
? r.response
|
|
127
|
+
: (typeof r.result === "string" ? r.result : "");
|
|
128
|
+
return [{
|
|
129
|
+
role: "system",
|
|
130
|
+
kind: "result",
|
|
131
|
+
text: truncate(text || (r.error ? String(r.error) : "(本轮结束,无文本输出)")),
|
|
132
|
+
...(r.error ? { error: true } : {}),
|
|
133
|
+
}];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// OpenCode / 通用 JSON
|
|
137
|
+
if (obj.type === "text" && typeof obj.part?.text === "string") {
|
|
138
|
+
return [{ role: "agent", kind: "text", text: truncate(obj.part.text) }];
|
|
139
|
+
}
|
|
140
|
+
if (obj.type === "text" && typeof obj.text === "string") {
|
|
141
|
+
return [{ role: "agent", kind: "text", text: truncate(obj.text) }];
|
|
142
|
+
}
|
|
143
|
+
// reasoning(思考)块折叠展示,便于回看主 Agent 的判断依据
|
|
144
|
+
if (obj.part?.type === "reasoning" && typeof obj.part.text === "string") {
|
|
145
|
+
return [{ role: "agent", kind: "thinking", text: truncate(obj.part.text) }];
|
|
146
|
+
}
|
|
147
|
+
if (obj.type === "thinking" && typeof obj.thinking === "string") {
|
|
148
|
+
return [{ role: "agent", kind: "thinking", text: truncate(obj.thinking) }];
|
|
149
|
+
}
|
|
150
|
+
if (typeof obj.part?.text === "string") {
|
|
151
|
+
return [{ role: "agent", kind: "text", text: truncate(obj.part.text) }];
|
|
152
|
+
}
|
|
153
|
+
if (typeof obj.content === "string") {
|
|
154
|
+
return [{ role: "agent", kind: "text", text: truncate(obj.content) }];
|
|
155
|
+
}
|
|
156
|
+
if (obj.error && typeof obj.error !== "object") {
|
|
157
|
+
return [{ role: "system", kind: "error", text: String(obj.error), error: true }];
|
|
158
|
+
}
|
|
159
|
+
if (obj.error?.message || obj.type === "error") {
|
|
160
|
+
return [{ role: "system", kind: "error", text: String(obj.error?.message || obj.message || "未知错误"), error: true }];
|
|
161
|
+
}
|
|
162
|
+
if (obj.type === "tool" || obj.type === "tool_use") {
|
|
163
|
+
return [{
|
|
164
|
+
role: "agent",
|
|
165
|
+
kind: "tool",
|
|
166
|
+
text: String(obj.name || obj.part?.tool || "tool"),
|
|
167
|
+
name: String(obj.name || obj.part?.tool || "tool"),
|
|
168
|
+
input: obj.input ?? obj.part?.state?.input ?? null,
|
|
169
|
+
}];
|
|
170
|
+
}
|
|
171
|
+
return [];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 解析一行原始输出。非 JSON 行按日志保留。 */
|
|
175
|
+
export function parseMessageLine(line) {
|
|
176
|
+
const t = String(line ?? "").trim();
|
|
177
|
+
if (!t) return [];
|
|
178
|
+
if (!t.startsWith("{") && !t.startsWith("[")) {
|
|
179
|
+
return [{ role: "agent", kind: "log", text: truncate(t) }];
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
return parseMessageObject(JSON.parse(t));
|
|
183
|
+
} catch {
|
|
184
|
+
return [{ role: "agent", kind: "log", text: truncate(t) }];
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export class ConversationHub {
|
|
189
|
+
constructor({ onMessage } = {}) {
|
|
190
|
+
this.onMessage = onMessage;
|
|
191
|
+
this.buffers = new Map();
|
|
192
|
+
this.counts = new Map();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
file(scope) {
|
|
196
|
+
return statePath("conversations", `${safeName(scope)}.jsonl`);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** 喂入一段原始 stdout;按行缓冲,避免半行 JSON 被解析坏。 */
|
|
200
|
+
feed(scope, chunk) {
|
|
201
|
+
if (chunk == null || chunk === "") return;
|
|
202
|
+
const key = scope || "main";
|
|
203
|
+
const buffer = (this.buffers.get(key) || "") + String(chunk);
|
|
204
|
+
if (buffer.length > MAX_BUFFER) {
|
|
205
|
+
// 防御:Agent 输出了超长无换行内容,丢弃旧缓冲而不是无限增长
|
|
206
|
+
this.buffers.set(key, buffer.slice(-MAX_BUFFER));
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const lines = buffer.split(/\r?\n/);
|
|
210
|
+
this.buffers.set(key, lines.pop() || "");
|
|
211
|
+
for (const line of lines) {
|
|
212
|
+
for (const msg of parseMessageLine(line)) this.append(key, msg);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
append(scope, msg) {
|
|
217
|
+
const key = scope || "main";
|
|
218
|
+
const entry = {
|
|
219
|
+
id: `${Date.now().toString(36)}-${(seq++).toString(36)}`,
|
|
220
|
+
at: new Date().toISOString(),
|
|
221
|
+
role: msg.role || "agent",
|
|
222
|
+
kind: msg.kind || "text",
|
|
223
|
+
text: truncate(msg.text),
|
|
224
|
+
...(msg.name ? { name: String(msg.name) } : {}),
|
|
225
|
+
...(msg.input !== undefined && msg.input !== null ? { input: msg.input } : {}),
|
|
226
|
+
...(msg.trigger ? { trigger: String(msg.trigger) } : {}),
|
|
227
|
+
...(msg.newSession ? { newSession: true } : {}),
|
|
228
|
+
...(msg.error ? { error: true } : {}),
|
|
229
|
+
};
|
|
230
|
+
enqueueWrite(() => {
|
|
231
|
+
this._append(key, entry);
|
|
232
|
+
});
|
|
233
|
+
this.onMessage?.(key, entry);
|
|
234
|
+
return entry;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
read(scope, limit = 500) {
|
|
238
|
+
const file = this.file(scope);
|
|
239
|
+
let text = "";
|
|
240
|
+
try { text = fs.readFileSync(file, "utf8"); } catch { return []; }
|
|
241
|
+
const lines = text.split("\n").filter(Boolean);
|
|
242
|
+
return lines.slice(-Math.max(1, limit)).map((line) => {
|
|
243
|
+
try { return JSON.parse(line); } catch { return null; }
|
|
244
|
+
}).filter(Boolean);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
clear(scope) {
|
|
248
|
+
const key = scope || "main";
|
|
249
|
+
try { fs.unlinkSync(this.file(key)); } catch { /* 不存在 */ }
|
|
250
|
+
this.counts.delete(safeName(key));
|
|
251
|
+
// 半行缓冲也要清掉,否则下一次输出接在旧内容后面会解析出脏消息
|
|
252
|
+
this.buffers.delete(key);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** 清空所有会话(服务启动时用):内存缓冲、计数与磁盘 JSONL 一起重置。 */
|
|
256
|
+
clearAll() {
|
|
257
|
+
this.buffers.clear();
|
|
258
|
+
this.counts.clear();
|
|
259
|
+
const dir = statePath("conversations");
|
|
260
|
+
let names = [];
|
|
261
|
+
try { names = fs.readdirSync(dir); } catch { return; }
|
|
262
|
+
for (const name of names) {
|
|
263
|
+
if (!name.endsWith(".jsonl")) continue;
|
|
264
|
+
try { fs.unlinkSync(path.join(dir, name)); } catch { /* 单个文件失败不影响其余 */ }
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/* ---------- 内部 ---------- */
|
|
269
|
+
|
|
270
|
+
_count(key) {
|
|
271
|
+
const name = safeName(key);
|
|
272
|
+
if (this.counts.has(name)) return this.counts.get(name);
|
|
273
|
+
let count = 0;
|
|
274
|
+
try {
|
|
275
|
+
const text = fs.readFileSync(this.file(key), "utf8");
|
|
276
|
+
count = text.split("\n").filter(Boolean).length;
|
|
277
|
+
} catch { /* 新会话 */ }
|
|
278
|
+
this.counts.set(name, count);
|
|
279
|
+
return count;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
_append(key, entry) {
|
|
283
|
+
const file = this.file(key);
|
|
284
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
285
|
+
fs.appendFileSync(file, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
|
|
286
|
+
const count = this._count(key) + 1;
|
|
287
|
+
this.counts.set(safeName(key), count);
|
|
288
|
+
if (count > MAX_LINES) this._trim(key);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** 超过上限时只保留最近 KEEP_LINES 条,避免会话文件无限增长。 */
|
|
292
|
+
_trim(key) {
|
|
293
|
+
const file = this.file(key);
|
|
294
|
+
try {
|
|
295
|
+
const lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean).slice(-KEEP_LINES);
|
|
296
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
297
|
+
fs.writeFileSync(tmp, lines.length ? `${lines.join("\n")}\n` : "", { mode: 0o600 });
|
|
298
|
+
fs.renameSync(tmp, file);
|
|
299
|
+
this.counts.set(safeName(key), lines.length);
|
|
300
|
+
} catch { /* 裁剪失败不影响新消息写入 */ }
|
|
301
|
+
}
|
|
302
|
+
}
|