lemma-agent 0.0.0-stage → 1.0.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.
- package/README.md +140 -2
- package/bin/lemma.mjs +60 -0
- package/dist/acceptance.js +63 -0
- package/dist/admin.js +1482 -0
- package/dist/agents.js +245 -0
- package/dist/api-member.js +537 -0
- package/dist/app.js +161 -0
- package/dist/board.js +185 -0
- package/dist/business-tools.js +153 -0
- package/dist/change-ops.js +91 -0
- package/dist/changes.js +46 -0
- package/dist/cli-runner.js +106 -0
- package/dist/code-tools.js +396 -0
- package/dist/coding-benchmark-fixtures.js +1049 -0
- package/dist/coding-benchmark-suite.js +1252 -0
- package/dist/collaboration-benchmark.js +349 -0
- package/dist/config.js +392 -0
- package/dist/context-benchmark.js +91 -0
- package/dist/conventions.js +282 -0
- package/dist/conversation.js +39 -0
- package/dist/credentials.js +44 -0
- package/dist/deliverables.js +43 -0
- package/dist/digest.js +129 -0
- package/dist/dispatch.js +801 -0
- package/dist/execution-settings.js +24 -0
- package/dist/git-workbench.js +800 -0
- package/dist/git.js +149 -0
- package/dist/integration-git.js +108 -0
- package/dist/integrations.js +557 -0
- package/dist/jobs.js +100 -0
- package/dist/lead.js +263 -0
- package/dist/learning.js +36 -0
- package/dist/main.js +1459 -0
- package/dist/mcp-settings.js +45 -0
- package/dist/mcp-tools.js +102 -0
- package/dist/member-settings.js +245 -0
- package/dist/model-selection.js +48 -0
- package/dist/models.js +145 -0
- package/dist/native-selectors.js +45 -0
- package/dist/native-terminal-components.js +100 -0
- package/dist/ood-benchmark.js +660 -0
- package/dist/operations.js +21 -0
- package/dist/printer.js +113 -0
- package/dist/projects.js +282 -0
- package/dist/repair.js +102 -0
- package/dist/resources.js +31 -0
- package/dist/result-summary.js +8 -0
- package/dist/results.js +41 -0
- package/dist/scope.js +114 -0
- package/dist/sessions.js +95 -0
- package/dist/settings.js +32 -0
- package/dist/task-commands.js +37 -0
- package/dist/task-lifecycle.js +49 -0
- package/dist/task-readiness.js +22 -0
- package/dist/task-recovery.js +116 -0
- package/dist/task-review.js +70 -0
- package/dist/task-workflow.js +424 -0
- package/dist/terminal-layout.js +27 -0
- package/dist/terminal-state.js +145 -0
- package/dist/terminal.js +800 -0
- package/dist/tool-settings.js +111 -0
- package/dist/tools.js +1043 -0
- package/dist/ux-telemetry.js +127 -0
- package/dist/view.js +114 -0
- package/package.json +80 -6
- package/web/index.html +136 -0
- package/web/js/conversations.js +312 -0
- package/web/js/dag.js +495 -0
- package/web/js/drawer.js +139 -0
- package/web/js/editors.js +424 -0
- package/web/js/gitlens.js +844 -0
- package/web/js/main.js +152 -0
- package/web/js/sankey.js +476 -0
- package/web/js/store.js +291 -0
- package/web/js/ticket.js +151 -0
- package/web/js/timeline.js +183 -0
- package/web/js/topology.js +454 -0
- package/web/js/util.js +232 -0
- package/web/js/views.js +1496 -0
- package/web/style.css +5299 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { defineDoc } from "@earendil-works/pi-durable";
|
|
2
|
+
/** Intent and reconciliation are Durable documents, shared by members in this work session. */
|
|
3
|
+
export const Operations = defineDoc({
|
|
4
|
+
kind: "lemma.business-operations", version: 1, scope: "session", initial: () => ({ operations: {} }), checkpointWhen: () => false,
|
|
5
|
+
});
|
|
6
|
+
export const operationList = (state) => Object.values(state?.operations ?? {}).sort((a, b) => b.updatedAt - a.updatedAt);
|
|
7
|
+
export const unresolved = (operation) => operation.status === "pending" || operation.status === "unknown";
|
|
8
|
+
export async function resolveOperation(tx, id, outcome, evidence, at) {
|
|
9
|
+
const operation = (await tx.doc(Operations)).operations[id];
|
|
10
|
+
if (!operation || !unresolved(operation))
|
|
11
|
+
throw new Error("操作不存在或已完成核对。");
|
|
12
|
+
if (!evidence.trim())
|
|
13
|
+
throw new Error("需要填写人工查询远端状态的依据。");
|
|
14
|
+
const task = await tx.task(Number(operation.taskId));
|
|
15
|
+
if (task && !["terminal", "completing"].includes(task.state.status))
|
|
16
|
+
throw new Error("操作任务仍在运行,请先等待结束或取消后再核对。");
|
|
17
|
+
operation.status = "resolved";
|
|
18
|
+
operation.updatedAt = at;
|
|
19
|
+
operation.resolution = { outcome, evidence: evidence.trim().slice(0, 3000), at };
|
|
20
|
+
return outcome === "succeeded" ? "已记录远端成功,原失败交付仍保留;请基于远端凭证继续核对,勿重复提交。" : "已记录远端未执行,可在明确原因后重新派工。";
|
|
21
|
+
}
|
package/dist/printer.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { JOB_REPORT_ENTRY } from "./jobs.js";
|
|
2
|
+
const c = {
|
|
3
|
+
dim: (s) => `\x1b[2m${s}\x1b[0m`,
|
|
4
|
+
cyan: (s) => `\x1b[36m${s}\x1b[0m`,
|
|
5
|
+
yellow: (s) => `\x1b[33m${s}\x1b[0m`,
|
|
6
|
+
green: (s) => `\x1b[32m${s}\x1b[0m`,
|
|
7
|
+
red: (s) => `\x1b[31m${s}\x1b[0m`,
|
|
8
|
+
};
|
|
9
|
+
export const colors = c;
|
|
10
|
+
let sink;
|
|
11
|
+
export function setOutputSink(next) { sink = next; }
|
|
12
|
+
export function writeLine(text = "") {
|
|
13
|
+
if (sink)
|
|
14
|
+
sink(text);
|
|
15
|
+
else
|
|
16
|
+
console.log(text);
|
|
17
|
+
}
|
|
18
|
+
function textOf(content) {
|
|
19
|
+
if (typeof content === "string")
|
|
20
|
+
return content;
|
|
21
|
+
if (!Array.isArray(content))
|
|
22
|
+
return "";
|
|
23
|
+
return content
|
|
24
|
+
.filter((b) => b?.type === "text")
|
|
25
|
+
.map((b) => b.text)
|
|
26
|
+
.join("");
|
|
27
|
+
}
|
|
28
|
+
function clip(text, max) {
|
|
29
|
+
const t = text.trim();
|
|
30
|
+
return t.length > max ? `${t.slice(0, max)}…` : t;
|
|
31
|
+
}
|
|
32
|
+
export function printEntry(entry) {
|
|
33
|
+
const message = entry.model?.[0];
|
|
34
|
+
if (!message)
|
|
35
|
+
return;
|
|
36
|
+
if (entry.kind === JOB_REPORT_ENTRY) {
|
|
37
|
+
// 后台派工的结果发回总调度:标题行醒目,正文截一段
|
|
38
|
+
const [head = "", ...body] = textOf(message.content).split("\n");
|
|
39
|
+
const failed = /· (失败|已取消)】/.test(head);
|
|
40
|
+
writeLine(`\n${failed ? c.red(`◆ ${head}`) : c.yellow(`◆ ${head}`)}\n${c.dim(clip(body.join("\n").replace(/\n*(这是后台派工的结果[\s\S]*$/, ""), 800))}`);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (entry.kind === "pi.assistant") {
|
|
44
|
+
for (const block of message.content ?? []) {
|
|
45
|
+
if (block.type === "text" && block.text?.trim())
|
|
46
|
+
writeLine(`\n${c.green("总调度 ›")} ${block.text.trim()}`);
|
|
47
|
+
if (block.type === "toolCall") {
|
|
48
|
+
const args = block.arguments ?? {};
|
|
49
|
+
const extra = c.dim(`${args.background ? " (后台)" : ""}${args.session_id ? ` (续接 ${args.session_id})` : ""}`);
|
|
50
|
+
writeLine(`\n${c.cyan(`→ ${block.name}`)}${extra}\n${c.dim(clip(String(args.task ?? JSON.stringify(args)), 400))}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (message.stopReason === "error" && message.errorMessage)
|
|
54
|
+
writeLine(c.red(`\n模型出错:${message.errorMessage}`));
|
|
55
|
+
}
|
|
56
|
+
else if (entry.kind === "pi.tool-result") {
|
|
57
|
+
const text = textOf(message.content);
|
|
58
|
+
const label = message.isError ? c.red(`✗ ${message.toolName} 失败`) : c.yellow(`✓ ${message.toolName} 完成`);
|
|
59
|
+
writeLine(`\n${label}\n${c.dim(clip(text, 1200))}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** 订阅会话:打印新条目和工具的实时输出。返回停止函数。 */
|
|
63
|
+
export async function follow(root, context, options = {}) {
|
|
64
|
+
const watch = await root.watch(context);
|
|
65
|
+
const seen = new Set(watch.value.entries.map((e) => e.id));
|
|
66
|
+
const printedOutput = new Map();
|
|
67
|
+
if (options.replay) {
|
|
68
|
+
// 只回放最近一次重置(/new)之后的内容:重置前的记录模型已经看不到了,也不该再刷到屏幕上
|
|
69
|
+
const entries = watch.value.entries;
|
|
70
|
+
const lastReset = entries.findLastIndex((e) => e.kind === "pi.reset");
|
|
71
|
+
if (lastReset >= 0)
|
|
72
|
+
writeLine(c.dim("(更早的对话已重置:模型不再看到它们,记录仍在存储里,网页「运行记录」可查看)"));
|
|
73
|
+
for (const entry of entries.slice(lastReset + 1)) {
|
|
74
|
+
if (entry.kind === "pi.user")
|
|
75
|
+
writeLine(`你 › ${textOf(entry.model?.[0]?.content)}`);
|
|
76
|
+
else
|
|
77
|
+
printEntry(entry);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
options.onLive?.(watch.value.docs["pi.live"]);
|
|
81
|
+
watch.start(async (call) => {
|
|
82
|
+
if (call.kind !== "value")
|
|
83
|
+
return;
|
|
84
|
+
const { value } = call;
|
|
85
|
+
for (const entry of value.entries) {
|
|
86
|
+
if (seen.has(entry.id))
|
|
87
|
+
continue;
|
|
88
|
+
seen.add(entry.id);
|
|
89
|
+
printEntry(entry);
|
|
90
|
+
}
|
|
91
|
+
const live = value.docs["pi.live"];
|
|
92
|
+
options.onLive?.(live);
|
|
93
|
+
for (const slot of [...(live?.tools ?? []), ...(live?.nestedTools ?? [])]) {
|
|
94
|
+
const output = slot.output;
|
|
95
|
+
if (!output)
|
|
96
|
+
continue;
|
|
97
|
+
const done = printedOutput.get(slot.callId) ?? 0;
|
|
98
|
+
if (output.length > done) {
|
|
99
|
+
const fresh = output.slice(done);
|
|
100
|
+
printedOutput.set(slot.callId, output.length);
|
|
101
|
+
for (const line of fresh.split("\n"))
|
|
102
|
+
if (line.trim())
|
|
103
|
+
writeLine(c.dim(` [${slot.name}] ${line}`));
|
|
104
|
+
}
|
|
105
|
+
else if (output.length < done) {
|
|
106
|
+
printedOutput.set(slot.callId, output.length); // 输出窗口滚动了
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
return async () => {
|
|
111
|
+
await watch.stop();
|
|
112
|
+
};
|
|
113
|
+
}
|
package/dist/projects.js
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// 全局项目管理与零污染工作区解析(~/.lemma/projects.json & ~/.lemma/config.json):
|
|
2
|
+
// 1. 当在任意项目目录启动 lemma 且未显式指定局部 storage 时,将 session.sqlite、worktrees 与 ASSIGN.md
|
|
3
|
+
// 集中存放到 ~/.lemma/projects/<slug>-<hash>/,避免污染目标 Git 仓库工作区;
|
|
4
|
+
// 2. 全局配置 ~/.lemma/config.json 与凭据 ~/.lemma/credentials.json 在全部项目间共享;
|
|
5
|
+
// 3. 记录最近打开的项目清单,支持 /projects、/project use|init|remove 及 lemma --project / lemma projects。
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
10
|
+
import { loadConfig, normalizeConfig } from "./config.js";
|
|
11
|
+
export function lemmaHomeDir() {
|
|
12
|
+
return process.env.LEMMA_HOME?.trim() ? resolve(process.env.LEMMA_HOME.trim()) : join(homedir(), ".lemma");
|
|
13
|
+
}
|
|
14
|
+
export function globalConfigPath() {
|
|
15
|
+
return join(lemmaHomeDir(), "config.json");
|
|
16
|
+
}
|
|
17
|
+
export function projectsCatalogPath() {
|
|
18
|
+
return join(lemmaHomeDir(), "projects.json");
|
|
19
|
+
}
|
|
20
|
+
/** 向上查找 Git 仓库根目录;若当前不在 Git 仓库中则返回解析后的原目录。 */
|
|
21
|
+
export function findRepoRoot(cwd) {
|
|
22
|
+
let cur = resolve(cwd);
|
|
23
|
+
while (true) {
|
|
24
|
+
if (existsSync(join(cur, ".git")))
|
|
25
|
+
return cur;
|
|
26
|
+
const parent = dirname(cur);
|
|
27
|
+
if (parent === cur)
|
|
28
|
+
return resolve(cwd);
|
|
29
|
+
cur = parent;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function normalizedKeyPath(dir) {
|
|
33
|
+
const r = resolve(dir);
|
|
34
|
+
return process.platform === "win32" ? r.toLowerCase() : r;
|
|
35
|
+
}
|
|
36
|
+
export function projectIdForPath(projectRoot) {
|
|
37
|
+
const resolved = resolve(projectRoot);
|
|
38
|
+
const rawName = basename(resolved) || "workspace";
|
|
39
|
+
const slug = rawName
|
|
40
|
+
.replace(/[^\p{L}\p{N}_-]+/gu, "-")
|
|
41
|
+
.replace(/^-+|-+$/g, "")
|
|
42
|
+
.slice(0, 32) || "workspace";
|
|
43
|
+
const hash = createHash("sha256").update(normalizedKeyPath(resolved)).digest("hex").slice(0, 8);
|
|
44
|
+
return `${slug}-${hash}`;
|
|
45
|
+
}
|
|
46
|
+
export function projectStateDirFor(projectRoot) {
|
|
47
|
+
return join(lemmaHomeDir(), "projects", projectIdForPath(projectRoot));
|
|
48
|
+
}
|
|
49
|
+
export class ProjectCatalog {
|
|
50
|
+
filePath;
|
|
51
|
+
constructor(filePath = projectsCatalogPath()) {
|
|
52
|
+
this.filePath = resolve(filePath);
|
|
53
|
+
}
|
|
54
|
+
readRaw() {
|
|
55
|
+
if (!existsSync(this.filePath))
|
|
56
|
+
return [];
|
|
57
|
+
try {
|
|
58
|
+
const parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
|
|
59
|
+
if (!Array.isArray(parsed))
|
|
60
|
+
return [];
|
|
61
|
+
return parsed.filter((x) => Boolean(x && typeof x === "object" && typeof x.id === "string" && typeof x.path === "string"));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
writeRaw(entries) {
|
|
68
|
+
mkdirSync(dirname(this.filePath), { recursive: true });
|
|
69
|
+
const tmp = `${this.filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
70
|
+
try {
|
|
71
|
+
writeFileSync(tmp, `${JSON.stringify(entries, null, 2)}\n`, "utf8");
|
|
72
|
+
renameSync(tmp, this.filePath);
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
rmSync(tmp, { force: true });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
list() {
|
|
79
|
+
return this.readRaw().sort((a, b) => b.lastOpenedAt - a.lastOpenedAt || a.name.localeCompare(b.name));
|
|
80
|
+
}
|
|
81
|
+
touch(projectRoot, opts) {
|
|
82
|
+
const resolved = resolve(projectRoot);
|
|
83
|
+
const id = projectIdForPath(resolved);
|
|
84
|
+
const stateDir = opts?.stateDir ? resolve(opts.stateDir) : projectStateDirFor(resolved);
|
|
85
|
+
const storage = opts?.storage ? resolve(opts.storage) : join(stateDir, "session.sqlite");
|
|
86
|
+
const now = opts?.now ?? Date.now();
|
|
87
|
+
const entries = this.readRaw();
|
|
88
|
+
const key = normalizedKeyPath(resolved);
|
|
89
|
+
const idx = entries.findIndex((e) => normalizedKeyPath(e.path) === key || e.id === id);
|
|
90
|
+
const existing = idx >= 0 ? entries[idx] : undefined;
|
|
91
|
+
const next = {
|
|
92
|
+
id,
|
|
93
|
+
name: basename(resolved) || id,
|
|
94
|
+
path: resolved,
|
|
95
|
+
storage,
|
|
96
|
+
stateDir,
|
|
97
|
+
createdAt: existing?.createdAt ?? now,
|
|
98
|
+
lastOpenedAt: now,
|
|
99
|
+
};
|
|
100
|
+
if (idx >= 0)
|
|
101
|
+
entries[idx] = next;
|
|
102
|
+
else
|
|
103
|
+
entries.push(next);
|
|
104
|
+
this.writeRaw(entries);
|
|
105
|
+
return next;
|
|
106
|
+
}
|
|
107
|
+
resolve(query) {
|
|
108
|
+
const trimmed = query.trim().replace(/^["']|["']$/g, "");
|
|
109
|
+
if (!trimmed)
|
|
110
|
+
return undefined;
|
|
111
|
+
const all = this.list();
|
|
112
|
+
if (/^\d+$/.test(trimmed)) {
|
|
113
|
+
const idx = Number.parseInt(trimmed, 10) - 1;
|
|
114
|
+
return idx >= 0 && idx < all.length ? all[idx] : undefined;
|
|
115
|
+
}
|
|
116
|
+
const lower = trimmed.toLowerCase();
|
|
117
|
+
return (all.find((e) => e.id.toLowerCase() === lower) ??
|
|
118
|
+
all.find((e) => e.name.toLowerCase() === lower) ??
|
|
119
|
+
all.find((e) => normalizedKeyPath(e.path) === normalizedKeyPath(trimmed)));
|
|
120
|
+
}
|
|
121
|
+
remove(query) {
|
|
122
|
+
const found = this.resolve(query);
|
|
123
|
+
if (!found)
|
|
124
|
+
return undefined;
|
|
125
|
+
const next = this.readRaw().filter((e) => e.id !== found.id);
|
|
126
|
+
this.writeRaw(next);
|
|
127
|
+
return found;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* 解析启动工作区与配置:
|
|
132
|
+
* - 若显式指定 PI_AGENT_CONFIG,则完全沿用原路径解析,不触碰全局注册表;
|
|
133
|
+
* - 若当前仓库(或其 Git 根目录)无 pi-agent.config.json,则加载共享的 ~/.lemma/config.json,
|
|
134
|
+
* 并将 session.sqlite / worktrees / ASSIGN.md 集中隔离到 ~/.lemma/projects/<slug>-<hash>/;
|
|
135
|
+
* - 若仓库存在局部 pi-agent.config.json 但未显式指定 storage,同样使用 ~/.lemma/projects/ 集中存储。
|
|
136
|
+
*/
|
|
137
|
+
export function resolveStartupWorkspace(options) {
|
|
138
|
+
const catalog = options.catalog ?? new ProjectCatalog();
|
|
139
|
+
if (options.envConfigPath?.trim()) {
|
|
140
|
+
const configPath = resolve(options.cwd ?? process.cwd(), options.envConfigPath.trim());
|
|
141
|
+
const baseConfig = loadConfig(configPath);
|
|
142
|
+
return {
|
|
143
|
+
configPath,
|
|
144
|
+
baseConfig,
|
|
145
|
+
projectRoot: resolve(baseConfig.workdir),
|
|
146
|
+
isolatedExternally: false,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
let startDir = resolve(options.cwd ?? process.cwd());
|
|
150
|
+
if (options.projectArg?.trim()) {
|
|
151
|
+
const q = options.projectArg.trim().replace(/^["']|["']$/g, "");
|
|
152
|
+
const hit = catalog.resolve(q);
|
|
153
|
+
if (hit) {
|
|
154
|
+
if (!existsSync(hit.path) || !statSync(hit.path).isDirectory()) {
|
|
155
|
+
throw new Error(`项目目录不存在:${hit.path}`);
|
|
156
|
+
}
|
|
157
|
+
startDir = hit.path;
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
const candidate = resolve(startDir, q);
|
|
161
|
+
if (!existsSync(candidate) || !statSync(candidate).isDirectory()) {
|
|
162
|
+
throw new Error(`找不到项目“${q}”(可用 lemma projects 查看已记录项目或传入有效路径)。`);
|
|
163
|
+
}
|
|
164
|
+
startDir = candidate;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const projectRoot = findRepoRoot(startDir);
|
|
168
|
+
const cwdConfig = join(startDir, "pi-agent.config.json");
|
|
169
|
+
const rootConfig = join(projectRoot, "pi-agent.config.json");
|
|
170
|
+
const localConfigPath = existsSync(cwdConfig) ? cwdConfig : (existsSync(rootConfig) ? rootConfig : undefined);
|
|
171
|
+
const stateDir = projectStateDirFor(projectRoot);
|
|
172
|
+
const managedStorage = join(stateDir, "session.sqlite");
|
|
173
|
+
const managedProjectDir = join(stateDir, "project");
|
|
174
|
+
const sharedConfigPath = globalConfigPath();
|
|
175
|
+
const rawGlobal = existsSync(sharedConfigPath) ? JSON.parse(readFileSync(sharedConfigPath, "utf8")) : {};
|
|
176
|
+
const { workdir: _gw, storage: _gs, projectStateDir: _gp, ...sharedLayer } = rawGlobal;
|
|
177
|
+
if (localConfigPath) {
|
|
178
|
+
const rawLocal = JSON.parse(readFileSync(localConfigPath, "utf8"));
|
|
179
|
+
const mergedRaw = localConfigPath === sharedConfigPath
|
|
180
|
+
? rawLocal
|
|
181
|
+
: {
|
|
182
|
+
...sharedLayer,
|
|
183
|
+
...rawLocal,
|
|
184
|
+
...(rawLocal.orchestrator || rawGlobal.orchestrator ? { orchestrator: { ...sharedLayer.orchestrator, ...rawLocal.orchestrator } } : {}),
|
|
185
|
+
...(rawLocal.agents || rawGlobal.agents ? { agents: { ...sharedLayer.agents, ...rawLocal.agents } } : {}),
|
|
186
|
+
...(rawLocal.isolation || rawGlobal.isolation ? { isolation: { ...sharedLayer.isolation, ...rawLocal.isolation } } : {}),
|
|
187
|
+
...(rawLocal.budget || rawGlobal.budget ? { budget: { ...sharedLayer.budget, ...rawLocal.budget } } : {}),
|
|
188
|
+
...(rawLocal.autonomy || rawGlobal.autonomy ? { autonomy: { ...sharedLayer.autonomy, ...rawLocal.autonomy } } : {}),
|
|
189
|
+
};
|
|
190
|
+
const config = normalizeConfig(mergedRaw, localConfigPath);
|
|
191
|
+
const explicitStorage = typeof rawLocal.storage === "string" && rawLocal.storage.trim().length > 0;
|
|
192
|
+
const baseConfig = explicitStorage
|
|
193
|
+
? config
|
|
194
|
+
: { ...config, storage: managedStorage, projectStateDir: managedProjectDir };
|
|
195
|
+
const project = catalog.touch(resolve(baseConfig.workdir), {
|
|
196
|
+
storage: baseConfig.storage,
|
|
197
|
+
stateDir: explicitStorage ? dirname(baseConfig.storage) : stateDir,
|
|
198
|
+
});
|
|
199
|
+
return {
|
|
200
|
+
configPath: localConfigPath,
|
|
201
|
+
baseConfig,
|
|
202
|
+
projectRoot: resolve(baseConfig.workdir),
|
|
203
|
+
isolatedExternally: !explicitStorage,
|
|
204
|
+
project,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
const normalizedGlobal = normalizeConfig(sharedLayer, existsSync(sharedConfigPath) ? sharedConfigPath : join(projectRoot, "pi-agent.config.json"));
|
|
208
|
+
const baseConfig = {
|
|
209
|
+
...normalizedGlobal,
|
|
210
|
+
workdir: projectRoot,
|
|
211
|
+
storage: managedStorage,
|
|
212
|
+
projectStateDir: managedProjectDir,
|
|
213
|
+
};
|
|
214
|
+
const project = catalog.touch(projectRoot, { storage: managedStorage, stateDir });
|
|
215
|
+
return {
|
|
216
|
+
configPath: sharedConfigPath,
|
|
217
|
+
baseConfig,
|
|
218
|
+
projectRoot,
|
|
219
|
+
isolatedExternally: true,
|
|
220
|
+
project,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/** 基于当前仓库技术栈探测,生成极简不污染仓库存储的项目级 pi-agent.config.json(仅写 checks 与 linkDirs)。 */
|
|
224
|
+
export function initProjectConfig(projectRoot, opts) {
|
|
225
|
+
const root = findRepoRoot(projectRoot);
|
|
226
|
+
const targetPath = join(root, "pi-agent.config.json");
|
|
227
|
+
if (existsSync(targetPath) && !opts?.force) {
|
|
228
|
+
throw new Error(`${targetPath} 已存在;若需覆盖请传入 --force(注意:无 storage 字段时仍会将运行库存于 ~/.lemma/projects/)。`);
|
|
229
|
+
}
|
|
230
|
+
const checks = [];
|
|
231
|
+
const linkDirs = new Set();
|
|
232
|
+
const hasRootPkg = existsSync(join(root, "package.json"));
|
|
233
|
+
const hasFrontendPkg = existsSync(join(root, "frontend", "package.json"));
|
|
234
|
+
const hasRootPom = existsSync(join(root, "pom.xml"));
|
|
235
|
+
const hasBackendPom = existsSync(join(root, "backend", "pom.xml"));
|
|
236
|
+
const hasPyproject = existsSync(join(root, "pyproject.toml")) || existsSync(join(root, "requirements.txt"));
|
|
237
|
+
const hasGoMod = existsSync(join(root, "go.mod"));
|
|
238
|
+
if (hasRootPkg) {
|
|
239
|
+
linkDirs.add("node_modules");
|
|
240
|
+
try {
|
|
241
|
+
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
242
|
+
if (pkg.scripts?.typecheck)
|
|
243
|
+
checks.push({ name: "typecheck", command: "npm", args: ["run", "typecheck"], timeoutSeconds: 120 });
|
|
244
|
+
if (pkg.scripts?.test)
|
|
245
|
+
checks.push({ name: "npm-test", command: "npm", args: ["test"], timeoutSeconds: 180 });
|
|
246
|
+
}
|
|
247
|
+
catch { }
|
|
248
|
+
}
|
|
249
|
+
if (hasFrontendPkg) {
|
|
250
|
+
linkDirs.add("frontend/node_modules");
|
|
251
|
+
checks.push({ name: "frontend-build", command: "npm", args: ["--prefix", "frontend", "run", "build"], timeoutSeconds: 180 });
|
|
252
|
+
}
|
|
253
|
+
if (hasRootPom) {
|
|
254
|
+
checks.push({ name: "maven-compile", command: "mvn", args: ["test-compile"], timeoutSeconds: 240 });
|
|
255
|
+
}
|
|
256
|
+
else if (hasBackendPom) {
|
|
257
|
+
checks.push({ name: "backend-compile", command: "mvn", args: ["-f", "backend/pom.xml", "test-compile"], timeoutSeconds: 240 });
|
|
258
|
+
}
|
|
259
|
+
if (hasPyproject) {
|
|
260
|
+
linkDirs.add(".venv");
|
|
261
|
+
linkDirs.add("venv");
|
|
262
|
+
checks.push({ name: "pytest", command: "pytest", args: [], timeoutSeconds: 180 });
|
|
263
|
+
}
|
|
264
|
+
if (hasGoMod) {
|
|
265
|
+
checks.push({ name: "go-test", command: "go", args: ["test", "./..."], timeoutSeconds: 180 });
|
|
266
|
+
}
|
|
267
|
+
const payload = {
|
|
268
|
+
isolation: {
|
|
269
|
+
enabled: true,
|
|
270
|
+
linkDirs: linkDirs.size ? [...linkDirs] : ["node_modules", ".venv", "venv"],
|
|
271
|
+
},
|
|
272
|
+
autonomy: {
|
|
273
|
+
enabled: checks.length > 0,
|
|
274
|
+
maxRepairAttempts: 2,
|
|
275
|
+
resultMaxChars: 4000,
|
|
276
|
+
checks,
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
normalizeConfig(payload, targetPath);
|
|
280
|
+
writeFileSync(targetPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
|
|
281
|
+
return { path: targetPath, checks: checks.length, linkDirs: payload.isolation.linkDirs };
|
|
282
|
+
}
|
package/dist/repair.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { checkBudget, RunBudget, runDispatch } from "./dispatch.js";
|
|
3
|
+
import { Learning } from "./learning.js";
|
|
4
|
+
import { Results } from "./results.js";
|
|
5
|
+
export async function managedDispatch(kind, command, deps, args, io, label) {
|
|
6
|
+
const policy = deps.config.autonomy;
|
|
7
|
+
if (!policy.enabled || deps.config.agents[kind].workspace === "none" || deps.config.agents[kind].api?.httpTools?.some((tool) => tool.method === "POST"))
|
|
8
|
+
return runDispatch(kind, command, deps, args, io, label);
|
|
9
|
+
const completed = await io.memo("managed-result");
|
|
10
|
+
if (completed)
|
|
11
|
+
return completed;
|
|
12
|
+
const runKey = await io.commit(async (tx) => (await tx.doc(RunBudget)).runKey);
|
|
13
|
+
const fingerprint = createHash("sha256").update(args.task_id ?? args.task.replace(/\s+/g, " ").trim()).digest("hex").slice(0, 20);
|
|
14
|
+
let key = `${runKey}:${kind}:${fingerprint}`;
|
|
15
|
+
const previous = await io.commit(async (tx) => JSON.parse(JSON.stringify((await tx.doc(Learning)).events.filter((e) => e.key === key))));
|
|
16
|
+
// Freeze this call's starting attempt; replay must revisit an interrupted repair,
|
|
17
|
+
// while a separate repeated call still observes the shared task repair limit.
|
|
18
|
+
const checkpoint = await io.memo("repair-start", { used: previous.reduce((max, event) => Math.max(max, event.attempt), 0), key });
|
|
19
|
+
const used = checkpoint.used;
|
|
20
|
+
key = checkpoint.key;
|
|
21
|
+
if (used >= policy.maxRepairAttempts && previous.some((e) => e.attempt === used && e.status === "failed")) {
|
|
22
|
+
return { text: "这项任务已耗尽本轮自动修复次数,停止重复派工。请汇报失败证据;用户明确调整任务后再继续。", isError: true };
|
|
23
|
+
}
|
|
24
|
+
let result = await runDispatch(kind, command, deps, args, io, label);
|
|
25
|
+
const firstFailure = result.text.slice(-1200);
|
|
26
|
+
let totalCost = result.summary?.costUsd ?? 0;
|
|
27
|
+
let completeCost = result.summary?.costUsd !== undefined;
|
|
28
|
+
let totalTime = result.summary?.durationMs ?? 0;
|
|
29
|
+
let attempts = 0;
|
|
30
|
+
for (let attempt = used + 1; result.isError && !result.aborted && attempt <= policy.maxRepairAttempts; attempt++) {
|
|
31
|
+
if (io.signal.aborted || deps.hub.closing)
|
|
32
|
+
break;
|
|
33
|
+
const summary = result.summary;
|
|
34
|
+
// 没有可续接的执行上下文、权限/认证错误等,交回调度,不盲目重复付费。
|
|
35
|
+
if (!summary?.sessionId && !summary?.changeId)
|
|
36
|
+
break;
|
|
37
|
+
if (/超时|timed? ?out|permission denied|权限拒绝|被权限拒绝|unauthorized|authentication|api.?key|insufficient|余额|没有就绪|不可用|已达上限/i.test(result.text))
|
|
38
|
+
break;
|
|
39
|
+
const repairReceipt = await io.commit(async (tx) => !!(await tx.doc(Results, io.conversationId, `dispatch:${io.taskId}:repair:${attempt}`, null)).result?.dispatch);
|
|
40
|
+
const over = repairReceipt ? undefined : await checkBudget(io, deps.config, false);
|
|
41
|
+
if (over) {
|
|
42
|
+
result.text += `\n\n${over}`;
|
|
43
|
+
if (result.summary)
|
|
44
|
+
result.summary.body += `\n\n${over}`;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
attempts = attempt;
|
|
48
|
+
await io.commit(async (tx) => {
|
|
49
|
+
const state = await tx.doc(Learning);
|
|
50
|
+
if (!state.events.some((e) => e.key === key && e.attempt === attempt)) {
|
|
51
|
+
state.events.push({ key, task: args.task.slice(0, 200), agent: kind, attempt, status: "repairing", at: io.now() });
|
|
52
|
+
state.events = state.events.slice(-100);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
io.output(`自动修复 ${attempt}/${policy.maxRepairAttempts}:续接 ${kind},只传本次失败摘要\n`);
|
|
56
|
+
const repairIO = {
|
|
57
|
+
...io, attemptOf: io.callId, callId: `${io.callId}:repair:${attempt}`, taskId: `${io.taskId}:repair:${attempt}`,
|
|
58
|
+
memo: (name, candidate) => io.memo(`repair.${attempt}.${name}`, candidate),
|
|
59
|
+
};
|
|
60
|
+
const next = {
|
|
61
|
+
task: `原任务:${args.task.slice(0, 2500)}\n\n自动修复 ${attempt}/${policy.maxRepairAttempts}。当前代码未通过验收,检查根因并最小修改,保留原有验收标准,不要跳过或弱化检查。\n失败证据(节选):\n${result.text.slice(-3000)}`,
|
|
62
|
+
...(args.task_id ? { task_id: args.task_id } : {}),
|
|
63
|
+
...(args.model ? { model: args.model } : {}),
|
|
64
|
+
...(args.structured ? { structured: true } : {}),
|
|
65
|
+
...(summary.sessionId ? { session_id: summary.sessionId } : { based_on: summary.changeId }),
|
|
66
|
+
};
|
|
67
|
+
result = await runDispatch(kind, command, deps, next, repairIO, label);
|
|
68
|
+
totalCost += result.summary?.costUsd ?? 0;
|
|
69
|
+
completeCost &&= result.summary?.costUsd !== undefined;
|
|
70
|
+
totalTime += result.summary?.durationMs ?? 0;
|
|
71
|
+
await io.commit(async (tx) => {
|
|
72
|
+
const event = (await tx.doc(Learning)).events.find((e) => e.key === key && e.attempt === attempt);
|
|
73
|
+
if (event)
|
|
74
|
+
event.status = result.aborted ? "cancelled" : result.isError ? "failed" : "completed";
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (attempts) {
|
|
78
|
+
const change = result.summary?.changeId ? deps.changes.get(result.summary.changeId) : undefined;
|
|
79
|
+
if (!result.isError && change?.verification?.passed && change.verification.head === change.head) {
|
|
80
|
+
await io.commit(async (tx) => {
|
|
81
|
+
const state = await tx.doc(Learning);
|
|
82
|
+
if (!state.lessons.some((l) => l.key === key))
|
|
83
|
+
state.lessons.push({ key, kind: "repair", task: args.task.slice(0, 200), files: change.files.map((f) => f.path).slice(0, 20), checks: change.verification.checks, repairs: attempts, at: io.now(), failure: firstFailure, resolution: result.summary?.body.slice(0, 800) ?? "", changeId: change.id, head: change.head });
|
|
84
|
+
state.lessons = state.lessons.slice(-50);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const note = `\n\n[自动修复 ${attempts}/${policy.maxRepairAttempts};${result.isError ? "尚未通过,停止重试并交回调度" : "派工完成,仍需对照任务验收"};本次派工已知累计 $${totalCost.toFixed(4)}${completeCost ? "" : ",含费用未知的执行"}]`;
|
|
88
|
+
result.text += note;
|
|
89
|
+
if (result.summary) {
|
|
90
|
+
result.summary.costUsd = completeCost ? totalCost : undefined;
|
|
91
|
+
result.summary.durationMs = totalTime;
|
|
92
|
+
result.summary.body += note;
|
|
93
|
+
}
|
|
94
|
+
if (result.details) {
|
|
95
|
+
result.details.costUsd = completeCost ? totalCost : null;
|
|
96
|
+
result.details.durationMs = totalTime;
|
|
97
|
+
result.details.repairs = attempts;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
await io.memo("managed-result", JSON.parse(JSON.stringify(result)));
|
|
101
|
+
return result;
|
|
102
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { defineDoc } from "@earendil-works/pi-durable";
|
|
2
|
+
export const Resources = defineDoc({ kind: "lemma.resources", version: 1, scope: "session", initial: () => ({ claims: {} }), checkpointWhen: () => false });
|
|
3
|
+
export const CostLedger = defineDoc({ kind: "lemma.cost-ledger", version: 1, scope: "session", initial: () => ({ entries: {} }), checkpointWhen: () => false });
|
|
4
|
+
export const resourceService = (config, member) => config.agents[member]?.api ? new URL(config.agents[member].api.baseUrl).origin : `cli:${member}`;
|
|
5
|
+
/** Admission runs in a Durable transaction; sleeping callers retain only queue metadata. */
|
|
6
|
+
export async function admit(tx, config, input) {
|
|
7
|
+
const claims = (await tx.doc(Resources)).claims;
|
|
8
|
+
if (claims[input.id]?.status === "running")
|
|
9
|
+
return { state: "ready" };
|
|
10
|
+
const service = resourceService(config, input.member), reserve = config.budget.reservePerDispatchUsd ?? 0;
|
|
11
|
+
const policy = config.execution ?? {}, live = Object.values(claims).filter((claim) => claim.status === "running");
|
|
12
|
+
const queue = Object.values(claims).filter((claim) => claim.status === "queued").sort((a, b) => a.at - b.at || a.id.localeCompare(b.id));
|
|
13
|
+
const reason = live.length >= (policy.maxConcurrent ?? 8) ? "等待团队并发名额" : live.filter((claim) => claim.member === input.member).length >= (policy.perMember ?? 4) ? "等待成员并发名额" : live.filter((claim) => claim.service === service).length >= (policy.perService ?? 8) ? "等待服务并发名额" : undefined;
|
|
14
|
+
const existing = claims[input.id];
|
|
15
|
+
const reserved = live.filter((claim) => claim.runKey === input.runKey).reduce((sum, claim) => sum + claim.reservedUsd, 0);
|
|
16
|
+
if (config.budget.perRunUsd !== null && (input.spent >= config.budget.perRunUsd || input.spent + reserved + reserve > config.budget.perRunUsd)) {
|
|
17
|
+
claims[input.id] = { id: input.id, member: input.member, service, runKey: input.runKey, status: "released", reservedUsd: 0, at: existing?.at ?? input.at, reason: "预算不足(含并行预留)" };
|
|
18
|
+
return { state: "budget", reason: "已花费与并行预留达到预算,未启动新派工。预留为用户估计,不是实际账单上限。" };
|
|
19
|
+
}
|
|
20
|
+
// FIFO for callers competing for the same member/service; unrelated queues may proceed.
|
|
21
|
+
const ahead = queue.some((claim) => claim.id !== input.id && (claim.at < (existing?.at ?? input.at) || (claim.at === (existing?.at ?? input.at) && claim.id.localeCompare(input.id) < 0)) && (claim.member === input.member || claim.service === service));
|
|
22
|
+
const waiting = reason ?? (ahead ? "等待同服务先到任务" : undefined);
|
|
23
|
+
claims[input.id] = { id: input.id, member: input.member, service, runKey: input.runKey, status: waiting ? "queued" : "running", reservedUsd: waiting ? 0 : reserve, at: existing?.at ?? input.at, ...(waiting ? { reason: waiting } : {}) };
|
|
24
|
+
return waiting ? { state: "queued", reason: waiting } : { state: "ready" };
|
|
25
|
+
}
|
|
26
|
+
export async function releaseClaim(tx, id) { const claim = (await tx.doc(Resources)).claims[id]; if (claim) {
|
|
27
|
+
claim.status = "released";
|
|
28
|
+
claim.reservedUsd = 0;
|
|
29
|
+
delete claim.reason;
|
|
30
|
+
} }
|
|
31
|
+
export const resourceSnapshot = (state) => { const claims = Object.values(state?.claims ?? {}); return { running: claims.filter((claim) => claim.status === "running"), queued: claims.filter((claim) => claim.status === "queued"), reservedUsd: claims.reduce((sum, claim) => sum + claim.reservedUsd, 0) }; };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Shared by production dispatch and the context-cost ablation benchmark. */
|
|
2
|
+
export function summarizeResult(text, limit) {
|
|
3
|
+
if (!Number.isSafeInteger(limit) || limit < 1)
|
|
4
|
+
throw new Error("摘要长度需要为正整数。");
|
|
5
|
+
if (text.length <= limit)
|
|
6
|
+
return text;
|
|
7
|
+
return `${text.slice(0, Math.floor(limit * 0.6))}\n…(中间已省略,原文 ${text.length} 字符)\n${text.slice(-Math.floor(limit * 0.4))}`;
|
|
8
|
+
}
|
package/dist/results.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { defineDocFamily, defineTool } from "@earendil-works/pi-durable";
|
|
2
|
+
import { int, obj, opt, str } from "@earendil-works/pi-schema";
|
|
3
|
+
import { parseDeliverable, resultExcerpt } from "./deliverables.js";
|
|
4
|
+
export const Results = defineDocFamily({
|
|
5
|
+
kind: "lemma.result", version: 1, scope: "conversation", history: "latest", fork: "initial", family: true,
|
|
6
|
+
initial: () => ({ result: null }), checkpointWhen: () => false,
|
|
7
|
+
});
|
|
8
|
+
export function resultPage(result, offset = 0, limit = 8000) {
|
|
9
|
+
if (!Number.isSafeInteger(offset) || offset < 0)
|
|
10
|
+
throw new RangeError("offset must be a nonnegative integer.");
|
|
11
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 8000)
|
|
12
|
+
throw new RangeError("limit must be between 1 and 8000.");
|
|
13
|
+
const end = Math.min(result.text.length, offset + limit);
|
|
14
|
+
return { id: result.id, member: result.member, conversationId: result.conversationId, status: result.status,
|
|
15
|
+
text: result.text.slice(offset, end), offset, nextOffset: end < result.text.length ? end : null, totalChars: result.text.length };
|
|
16
|
+
}
|
|
17
|
+
export async function storeResult(tx, controllerId, result) {
|
|
18
|
+
const delivery = parseDeliverable(result.text);
|
|
19
|
+
if (delivery)
|
|
20
|
+
result = { ...result, deliverable: delivery };
|
|
21
|
+
const doc = await tx.doc(Results, controllerId, result.id, null);
|
|
22
|
+
doc.result = result;
|
|
23
|
+
}
|
|
24
|
+
/** Retrieve full reports within the calling controller's scope. */
|
|
25
|
+
export function createReadResultTool() {
|
|
26
|
+
return defineTool({
|
|
27
|
+
name: "read_result", description: "Read a stored member result by result_id. Paginate with nextOffset; at most 8000 characters per call. Only results from this controller are accessible.",
|
|
28
|
+
parameters: obj({ result_id: str(), field: opt(str({ description: "可选结构化字段,如 conclusion、data.total、evidence、artifacts、incomplete" })), offset: opt(int({ minimum: 0 })), limit: opt(int({ minimum: 1, maximum: 8000 })) }),
|
|
29
|
+
replay: "safe",
|
|
30
|
+
execute: async (args, api, context) => {
|
|
31
|
+
const result = (await api.snapshot(Results, api.conversationId, args.result_id, context))?.result;
|
|
32
|
+
if (!result)
|
|
33
|
+
return { output: [{ type: "text", text: "Result not found in this controller." }], isError: true };
|
|
34
|
+
const delivery = result.deliverable ?? parseDeliverable(result.text);
|
|
35
|
+
const payload = delivery && args.field
|
|
36
|
+
? { ...resultPage(result, args.offset, args.limit), field: args.field, ...resultExcerpt({ ...result, deliverable: delivery }, args), availableFields: Object.keys(delivery) }
|
|
37
|
+
: { ...resultPage(result, args.offset, args.limit), availableFields: delivery ? Object.keys(delivery) : [], ...(args.field ? { note: "该结果未启用结构化交付,已直接返回正文原文片段。" } : {}) };
|
|
38
|
+
return { output: [{ type: "text", text: JSON.stringify(payload) }], isError: false };
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
}
|