pi-foreman 0.0.0-stage → 0.1.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/src/skills.mjs ADDED
@@ -0,0 +1,340 @@
1
+ /**
2
+ * 目录级 Skills 与项目规范发现、读取与安装引擎。
3
+ *
4
+ * 社区标准双层模型(Agent 在本地,执行在远端):
5
+ * 1. 目标环境目录(随 <cwd> 走):自动扫描 `<cwd>/AGENTS.md`、`<cwd>/.agents/skills/`、`<cwd>/.pi/skills/`;
6
+ * Agent 用原生的 `read` / `bash` 直接阅读和运行其中脚本。
7
+ * 2. 控制端本地个人 Skill 库:`~/.agents/skills/`、`~/.pi/agent/skills/`(及 `PI_FOREMAN_SKILLS_DIR`);
8
+ * 可在目录配置中勾选(零侵入,Agent 通过 `read_skill` 读取正文),也可一键推送安装到目标 `<cwd>/.agents/skills/`。
9
+ */
10
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join, posix, resolve } from "node:path";
13
+ import { normalizeWorkspaceCwd } from "./config.mjs";
14
+ import { piAgentDir } from "./stores.mjs";
15
+
16
+ export const SKILL_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
17
+ const MAX_AGENTS_MD_BYTES = 48 * 1024;
18
+ const MAX_SKILL_FILES = 50;
19
+ const MAX_SKILL_FILE_BYTES = 2 * 1024 * 1024;
20
+ const SKIP_COPY_NAMES = new Set([".git", "node_modules", ".DS_Store"]);
21
+
22
+ /** 解析 SKILL.md 的 YAML frontmatter(提取 name / description 与正文) */
23
+ export function parseSkillMarkdown(raw, fallbackName = "skill") {
24
+ const text = String(raw ?? "");
25
+ const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
26
+ if (!m) {
27
+ const firstLine = text.split(/\r?\n/).find((l) => l.trim() && !l.startsWith("#")) ?? "";
28
+ return { name: fallbackName, description: firstLine.trim().slice(0, 160), body: text };
29
+ }
30
+ const fm = m[1];
31
+ const body = m[2] ?? "";
32
+ let name = fallbackName;
33
+ let description = "";
34
+
35
+ const lines = fm.split(/\r?\n/);
36
+ for (let i = 0; i < lines.length; i++) {
37
+ const line = lines[i];
38
+ const kv = line.match(/^([a-zA-Z0-9_-]+):\s*(.*)$/);
39
+ if (!kv) continue;
40
+ const key = kv[1];
41
+ let val = kv[2].trim();
42
+ // 支持简单多行 folded/literal YAML (`>` / `|`)
43
+ if (val === "|" || val === ">" || val === "|-" || val === ">-") {
44
+ const multi = [];
45
+ while (i + 1 < lines.length && /^\s+/.test(lines[i + 1])) {
46
+ i++;
47
+ multi.push(lines[i].trim());
48
+ }
49
+ val = multi.join(" ");
50
+ } else {
51
+ val = val.replace(/^["']|["']$/g, "").trim();
52
+ }
53
+ if (key === "name" && val) name = val;
54
+ if (key === "description" && val) description = val;
55
+ }
56
+
57
+ return { name, description, body };
58
+ }
59
+
60
+ /** 列出控制端本地个人 Skill 目录下的全部 Skill */
61
+ export function listLocalSkills() {
62
+ const roots = [
63
+ join(homedir(), ".agents", "skills"),
64
+ join(piAgentDir(), "skills"),
65
+ ];
66
+ const extra = process.env.PI_FOREMAN_SKILLS_DIR;
67
+ if (extra) {
68
+ for (const part of extra.split(/[:;,]/).map((s) => s.trim()).filter(Boolean)) {
69
+ roots.unshift(resolve(part));
70
+ }
71
+ }
72
+
73
+ const byName = new Map();
74
+ for (const root of roots) {
75
+ if (!existsSync(root)) continue;
76
+ let entries;
77
+ try {
78
+ entries = readdirSync(root, { withFileTypes: true });
79
+ } catch {
80
+ continue;
81
+ }
82
+ for (const ent of entries) {
83
+ if (ent.name.startsWith(".")) continue;
84
+ if (ent.isDirectory() || ent.isSymbolicLink()) {
85
+ const dirPath = join(root, ent.name);
86
+ const skillFile = join(dirPath, "SKILL.md");
87
+ if (!existsSync(skillFile)) continue;
88
+ try {
89
+ const parsed = parseSkillMarkdown(readFileSync(skillFile, "utf8"), ent.name);
90
+ if (!byName.has(parsed.name)) {
91
+ byName.set(parsed.name, {
92
+ name: parsed.name,
93
+ description: parsed.description,
94
+ source: "local",
95
+ dir: dirPath,
96
+ file: skillFile,
97
+ hasScripts: existsSync(join(dirPath, "scripts")),
98
+ });
99
+ }
100
+ } catch { /* 跳过不可读 SKILL.md */ }
101
+ } else if (ent.isFile() && ent.name.endsWith(".md")) {
102
+ const filePath = join(root, ent.name);
103
+ const base = ent.name.slice(0, -3);
104
+ try {
105
+ const parsed = parseSkillMarkdown(readFileSync(filePath, "utf8"), base);
106
+ if (!byName.has(parsed.name)) {
107
+ byName.set(parsed.name, {
108
+ name: parsed.name,
109
+ description: parsed.description,
110
+ source: "local",
111
+ dir: null,
112
+ file: filePath,
113
+ hasScripts: false,
114
+ });
115
+ }
116
+ } catch { /* ignore */ }
117
+ }
118
+ }
119
+ }
120
+
121
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
122
+ }
123
+
124
+ export function readLocalSkill(name) {
125
+ const hit = listLocalSkills().find((s) => s.name === name);
126
+ if (!hit) return null;
127
+ try {
128
+ return {
129
+ name: hit.name,
130
+ file: hit.file,
131
+ content: readFileSync(hit.file, "utf8"),
132
+ };
133
+ } catch {
134
+ return null;
135
+ }
136
+ }
137
+
138
+ // ── 远端工作区上下文扫描与 TTL 缓存 ──────────────────────────────────────────
139
+
140
+ const remoteCache = new Map(); // `${envId}\0${normCwd}` -> { expiresAt, value }
141
+
142
+ export function invalidateWorkspaceCache(envId, cwd) {
143
+ if (!envId) return;
144
+ if (cwd) {
145
+ remoteCache.delete(`${envId}\u0000${normalizeWorkspaceCwd(cwd)}`);
146
+ return;
147
+ }
148
+ const prefix = `${envId}\u0000`;
149
+ for (const k of remoteCache.keys()) {
150
+ if (k.startsWith(prefix)) remoteCache.delete(k);
151
+ }
152
+ }
153
+
154
+ export function invalidateAllWorkspaceCaches() {
155
+ remoteCache.clear();
156
+ }
157
+
158
+ function joinTargetPath(base, ...parts) {
159
+ if (base === ".") return parts.join("/");
160
+ return posix.join(base.replace(/\\/g, "/"), ...parts);
161
+ }
162
+
163
+ /**
164
+ * 扫描远端(或本机)工作目录里的 AGENTS.md 与 `.agents/skills` + `.pi/skills`。
165
+ */
166
+ export async function discoverRemoteWorkspaceContext(execEnv, cwd, ctx, { ttlMs = 30_000, force = false } = {}) {
167
+ if (!execEnv || !cwd) {
168
+ return { cwd: cwd ?? ".", agentsMd: null, skills: [], scannedAt: Date.now() };
169
+ }
170
+ const normCwd = normalizeWorkspaceCwd(cwd);
171
+ const cacheKey = `${execEnv.id ?? "env"}\u0000${normCwd}`;
172
+ const now = Date.now();
173
+ if (!force) {
174
+ const hit = remoteCache.get(cacheKey);
175
+ if (hit && hit.expiresAt > now) return hit.value;
176
+ }
177
+
178
+ let agentsMd = null;
179
+ const agentsPath = joinTargetPath(normCwd, "AGENTS.md");
180
+ const hasAgents = await execEnv.exists(agentsPath, ctx);
181
+ if (hasAgents.ok && hasAgents.value) {
182
+ const readRes = await execEnv.readTextFile(agentsPath, ctx);
183
+ if (readRes.ok && typeof readRes.value === "string") {
184
+ const txt = readRes.value.trim();
185
+ if (txt) {
186
+ agentsMd = Buffer.byteLength(txt, "utf8") > MAX_AGENTS_MD_BYTES
187
+ ? `${txt.slice(0, MAX_AGENTS_MD_BYTES)}\n\n... (AGENTS.md truncated)`
188
+ : txt;
189
+ }
190
+ }
191
+ }
192
+
193
+ const skillsMap = new Map();
194
+ for (const relDir of [".agents/skills", ".pi/skills"]) {
195
+ const dirPath = joinTargetPath(normCwd, relDir);
196
+ const ex = await execEnv.exists(dirPath, ctx);
197
+ if (!ex.ok || !ex.value) continue;
198
+ const listed = await execEnv.listDir(dirPath, ctx);
199
+ if (!listed.ok || !Array.isArray(listed.value)) continue;
200
+
201
+ for (const entry of listed.value) {
202
+ if (!entry?.name || entry.name.startsWith(".")) continue;
203
+ if (entry.kind === "directory") {
204
+ const skillMdPath = joinTargetPath(dirPath, entry.name, "SKILL.md");
205
+ const existsSkill = await execEnv.exists(skillMdPath, ctx);
206
+ if (!existsSkill.ok || !existsSkill.value) continue;
207
+ const textRes = await execEnv.readTextFile(skillMdPath, ctx);
208
+ if (!textRes.ok) continue;
209
+ const parsed = parseSkillMarkdown(textRes.value, entry.name);
210
+ if (!skillsMap.has(parsed.name)) {
211
+ skillsMap.set(parsed.name, {
212
+ name: parsed.name,
213
+ dirName: entry.name,
214
+ description: parsed.description,
215
+ path: skillMdPath,
216
+ source: "remote",
217
+ });
218
+ }
219
+ } else if (entry.kind === "file" && entry.name.endsWith(".md")) {
220
+ const filePath = joinTargetPath(dirPath, entry.name);
221
+ const textRes = await execEnv.readTextFile(filePath, ctx);
222
+ if (!textRes.ok) continue;
223
+ const parsed = parseSkillMarkdown(textRes.value, entry.name.slice(0, -3));
224
+ if (!skillsMap.has(parsed.name)) {
225
+ skillsMap.set(parsed.name, {
226
+ name: parsed.name,
227
+ dirName: entry.name,
228
+ description: parsed.description,
229
+ path: filePath,
230
+ source: "remote",
231
+ });
232
+ }
233
+ }
234
+ }
235
+ }
236
+
237
+ const value = {
238
+ cwd: normCwd,
239
+ agentsMd,
240
+ skills: [...skillsMap.values()].sort((a, b) => a.name.localeCompare(b.name)),
241
+ scannedAt: Date.now(),
242
+ };
243
+ remoteCache.set(cacheKey, { expiresAt: Date.now() + ttlMs, value });
244
+ return value;
245
+ }
246
+
247
+ function walkLocalSkillFiles(rootDir, relPrefix = "", out = []) {
248
+ for (const ent of readdirSync(rootDir, { withFileTypes: true })) {
249
+ if (SKIP_COPY_NAMES.has(ent.name)) continue;
250
+ const abs = join(rootDir, ent.name);
251
+ const rel = relPrefix ? `${relPrefix}/${ent.name}` : ent.name;
252
+ if (ent.isDirectory()) {
253
+ walkLocalSkillFiles(abs, rel, out);
254
+ } else if (ent.isFile()) {
255
+ const st = statSync(abs);
256
+ if (st.size > MAX_SKILL_FILE_BYTES) {
257
+ throw new Error(`文件过大,超过 2MB 上限: ${rel}`);
258
+ }
259
+ out.push({ abs, rel });
260
+ if (out.length > MAX_SKILL_FILES) {
261
+ throw new Error(`Skill 文件数量超过上限 (${MAX_SKILL_FILES})`);
262
+ }
263
+ }
264
+ }
265
+ return out;
266
+ }
267
+
268
+ /**
269
+ * 安装 Skill 到目标环境的 `<cwd>/.agents/skills/<name>/`。
270
+ * 支持从本机个人 Skill 完整推送(包含 scripts/ 等),也支持新建文本 SKILL.md。
271
+ */
272
+ export async function installSkillToWorkspace(execEnv, cwd, { name, fromLocal, content }, ctx) {
273
+ if (!execEnv || !cwd) throw new Error("缺少执行环境或目录路径");
274
+ const cleanName = String(name ?? "").trim();
275
+ if (!SKILL_NAME_PATTERN.test(cleanName)) {
276
+ throw new Error(`Skill 名称非法: "${cleanName}"`);
277
+ }
278
+ const normCwd = normalizeWorkspaceCwd(cwd);
279
+ const destRoot = joinTargetPath(normCwd, ".agents", "skills", cleanName);
280
+
281
+ const mk = await execEnv.createDir(destRoot, { recursive: true }, ctx);
282
+ if (!mk.ok) throw new Error(`创建远端 Skill 目录失败: ${mk.error?.message ?? mk.error?.code}`);
283
+
284
+ if (fromLocal) {
285
+ const localSkill = listLocalSkills().find((s) => s.name === cleanName || s.name === String(fromLocal));
286
+ if (!localSkill) throw new Error(`找不到本机 Skill: ${fromLocal}`);
287
+ if (localSkill.dir) {
288
+ const files = walkLocalSkillFiles(localSkill.dir);
289
+ const madeDirs = new Set([destRoot]);
290
+ for (const f of files) {
291
+ const destFile = joinTargetPath(destRoot, f.rel);
292
+ const parentDir = posix.dirname(destFile);
293
+ if (!madeDirs.has(parentDir)) {
294
+ const rDir = await execEnv.createDir(parentDir, { recursive: true }, ctx);
295
+ if (!rDir.ok) throw new Error(`创建子目录失败 ${parentDir}: ${rDir.error?.message ?? ""}`);
296
+ madeDirs.add(parentDir);
297
+ }
298
+ const wr = await execEnv.writeFile(destFile, readFileSync(f.abs), ctx);
299
+ if (!wr.ok) throw new Error(`写入文件失败 ${destFile}: ${wr.error?.message ?? ""}`);
300
+ }
301
+ } else {
302
+ const wr = await execEnv.writeFile(joinTargetPath(destRoot, "SKILL.md"), readFileSync(localSkill.file), ctx);
303
+ if (!wr.ok) throw new Error(`写入 SKILL.md 失败: ${wr.error?.message ?? ""}`);
304
+ }
305
+ } else {
306
+ const body = String(content ?? "").trim();
307
+ if (!body) throw new Error("SKILL.md 内容不能为空");
308
+ const wr = await execEnv.writeFile(joinTargetPath(destRoot, "SKILL.md"), `${body}\n`, ctx);
309
+ if (!wr.ok) throw new Error(`写入 SKILL.md 失败: ${wr.error?.message ?? ""}`);
310
+ }
311
+
312
+ invalidateWorkspaceCache(execEnv.id, normCwd);
313
+ return { ok: true, name: cleanName, path: joinTargetPath(destRoot, "SKILL.md") };
314
+ }
315
+
316
+ export async function removeRemoteSkill(execEnv, cwd, skillName, ctx) {
317
+ if (!execEnv || !cwd) throw new Error("缺少执行环境或目录路径");
318
+ const cleanName = String(skillName ?? "").trim();
319
+ if (!SKILL_NAME_PATTERN.test(cleanName)) throw new Error(`Skill 名称非法: "${cleanName}"`);
320
+ const normCwd = normalizeWorkspaceCwd(cwd);
321
+
322
+ const candidates = [
323
+ joinTargetPath(normCwd, ".agents", "skills", cleanName),
324
+ joinTargetPath(normCwd, ".pi", "skills", cleanName),
325
+ joinTargetPath(normCwd, ".agents", "skills", `${cleanName}.md`),
326
+ joinTargetPath(normCwd, ".pi", "skills", `${cleanName}.md`),
327
+ ];
328
+
329
+ let removed = false;
330
+ for (const p of candidates) {
331
+ const ex = await execEnv.exists(p, ctx);
332
+ if (ex.ok && ex.value) {
333
+ const rm = await execEnv.remove(p, { recursive: true, force: true }, ctx);
334
+ if (rm.ok) removed = true;
335
+ }
336
+ }
337
+
338
+ invalidateWorkspaceCache(execEnv.id, normCwd);
339
+ return { ok: true, removed };
340
+ }
package/src/stores.mjs ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * 复用 pi coding-agent 已有的凭据与模型目录文件。
3
+ *
4
+ * 关键事实(来自 pi-ai 的类型定义):
5
+ * - `~/.pi/agent/auth.json` 的形状就是 pi-ai 的 `Credential`
6
+ * ("One type-tagged credential per provider — the shape of today's auth.json")
7
+ * - `~/.pi/agent/models-store.json` 的值就是 `ModelsStoreEntry`
8
+ * 所以不需要重新登录,直接适配即可。
9
+ *
10
+ * ⚠️ CredentialStore.modify 要求「按 provider id 互斥,若底层支持则跨进程互斥」。
11
+ * 这里用进程内的 promise 链做串行化 + 原子写。跨进程互斥没做(pi 自己也是
12
+ * best-effort:文档明说 "Best-effort stores ... are valid implementations")。
13
+ * 如果 pi 和 foreman 同时刷新同一个 provider 的 token,理论上会互相覆盖。
14
+ */
15
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { dirname, join } from "node:path";
18
+
19
+ /** pi coding-agent 的数据目录(与 pi 自己用的环境变量同名,保持一致) */
20
+ export function piAgentDir() {
21
+ return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
22
+ }
23
+
24
+ function readJson(file) {
25
+ if (!existsSync(file)) return {};
26
+ try {
27
+ return JSON.parse(readFileSync(file, "utf8"));
28
+ } catch {
29
+ return {};
30
+ }
31
+ }
32
+
33
+ function writeJsonAtomic(file, value) {
34
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
35
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
36
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
37
+ renameSync(tmp, file);
38
+ }
39
+
40
+ /** 按 key 串行化 read-modify-write */
41
+ class KeyMutex {
42
+ #chains = new Map();
43
+ run(key, fn) {
44
+ const prev = this.#chains.get(key) ?? Promise.resolve();
45
+ const next = prev.then(fn, fn);
46
+ // 链尾清理,避免 Map 无限增长
47
+ this.#chains.set(key, next.catch(() => {}));
48
+ return next;
49
+ }
50
+ }
51
+
52
+ export class FileCredentialStore {
53
+ #file;
54
+ #mutex = new KeyMutex();
55
+
56
+ constructor(file = join(piAgentDir(), "auth.json")) {
57
+ this.#file = file;
58
+ }
59
+
60
+ get file() {
61
+ return this.#file;
62
+ }
63
+
64
+ async read(providerId) {
65
+ return readJson(this.#file)[providerId];
66
+ }
67
+
68
+ async list() {
69
+ const all = readJson(this.#file);
70
+ return Object.entries(all)
71
+ .filter(([, c]) => c && typeof c.type === "string")
72
+ .map(([providerId, c]) => ({ providerId, type: c.type }));
73
+ }
74
+
75
+ async modify(providerId, fn) {
76
+ return this.#mutex.run(providerId, async () => {
77
+ const all = readJson(this.#file);
78
+ const current = all[providerId];
79
+ const next = await fn(current);
80
+ if (next === undefined) return current;
81
+ all[providerId] = next;
82
+ writeJsonAtomic(this.#file, all);
83
+ return next;
84
+ });
85
+ }
86
+
87
+ async delete(providerId) {
88
+ await this.#mutex.run(providerId, async () => {
89
+ const all = readJson(this.#file);
90
+ if (!(providerId in all)) return;
91
+ delete all[providerId];
92
+ writeJsonAtomic(this.#file, all);
93
+ });
94
+ }
95
+ }
96
+
97
+ export class FileModelsStore {
98
+ #file;
99
+
100
+ constructor(file = join(piAgentDir(), "models-store.json")) {
101
+ this.#file = file;
102
+ }
103
+
104
+ get file() {
105
+ return this.#file;
106
+ }
107
+
108
+ async read(providerId) {
109
+ return readJson(this.#file)[providerId];
110
+ }
111
+
112
+ async write(providerId, entry) {
113
+ const all = readJson(this.#file);
114
+ all[providerId] = entry;
115
+ writeJsonAtomic(this.#file, all);
116
+ }
117
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * 跨环境问答(CLI / 测试使用的同步版 durable Task)。
3
+ *
4
+ * - Task `foreman.ask-peer`:投递问题给对端会话并在同一 commit 里 park 等 SubmissionSettled。
5
+ * - GUI 里的协作走 `peer-tools.mjs` 的 `ask_peer` 工具,不经过本文件。
6
+ */
7
+ import { SubmissionSettled, defineExtension, defineTask } from "@earendil-works/pi-durable";
8
+ import {
9
+ entryToText, isWakeExpired, projectSubmission, projectTaskOutcome, signalValue,
10
+ } from "../projection.mjs";
11
+
12
+ export const TASK_NAME = "foreman.ask-peer";
13
+ export const EXTENSION_NAME = "foreman-peer";
14
+ const SIGNAL_KEY = "answered";
15
+
16
+ export const AskPeer = defineTask({
17
+ name: TASK_NAME,
18
+ version: 1,
19
+ initial: () => ({ phase: "deliver" }),
20
+
21
+ phases: {
22
+ deliver: async (task, rt, ctx) => {
23
+ const early = signalValue(await rt.readSignal(SubmissionSettled, SIGNAL_KEY, ctx));
24
+ if (early !== undefined) return collect(task, rt, ctx, early);
25
+
26
+ const handle = await rt.conversation(task.input.peerConversationId, ctx);
27
+ if (!handle) {
28
+ await fail(rt, ctx, `找不到对端会话 ${task.input.peerConversationId}(环境 ${task.input.peerEnv})`);
29
+ return;
30
+ }
31
+ if (task.input.deadline <= rt.now()) {
32
+ await fail(rt, ctx, "截止时间已过,未投递");
33
+ return;
34
+ }
35
+
36
+ // 🔴 admit + sleep 必须在同一个 commit 里(I-04)
37
+ await rt.commit(async (tx) => {
38
+ await handle.admit(tx, {
39
+ type: "input",
40
+ content: task.input.question,
41
+ requestId: `${TASK_NAME}:${rt.taskId}`,
42
+ notify: { taskId: rt.taskId, key: SIGNAL_KEY },
43
+ });
44
+ return {
45
+ status: "sleeping",
46
+ checkpoint: { phase: "collect" },
47
+ signals: [SubmissionSettled.key(SIGNAL_KEY)],
48
+ until: task.input.deadline,
49
+ };
50
+ }, ctx);
51
+ },
52
+
53
+ collect: async (task, rt, ctx) => {
54
+ if (isWakeExpired(task.state.wake)) {
55
+ await fail(rt, ctx, `等待 ${task.input.peerEnv} 回答超时(${Math.round((rt.now() - task.input.askedAt) / 1000)}s)`);
56
+ return;
57
+ }
58
+ const signaled = signalValue(await rt.readSignal(SubmissionSettled, SIGNAL_KEY, ctx));
59
+ if (signaled === undefined) {
60
+ await rt.commit(() => ({
61
+ status: "sleeping",
62
+ checkpoint: { phase: "collect" },
63
+ signals: [SubmissionSettled.key(SIGNAL_KEY)],
64
+ until: task.input.deadline,
65
+ }), ctx);
66
+ return;
67
+ }
68
+ await collect(task, rt, ctx, signaled);
69
+ },
70
+ },
71
+
72
+ abort: async (task, rt, ctx) => {
73
+ await rt.commit(() => ({
74
+ status: "terminal",
75
+ outcome: { status: "aborted", reason: `用户取消了对 ${task.input.peerEnv} 的提问` },
76
+ }), ctx);
77
+ },
78
+ });
79
+
80
+ async function collect(task, rt, ctx, settled) {
81
+ const view = projectSubmission(settled);
82
+ if (!view.ok || view.type !== "input") {
83
+ await fail(rt, ctx, `${task.input.peerEnv} 未能作答: ${view.error ?? view.status}`);
84
+ return;
85
+ }
86
+ await rt.commit(() => ({
87
+ status: "terminal",
88
+ outcome: {
89
+ status: "completed",
90
+ result: {
91
+ peerEnv: task.input.peerEnv,
92
+ peerConversationId: task.input.peerConversationId,
93
+ answerEntryId: view.answerEntryId,
94
+ askedAt: task.input.askedAt,
95
+ answeredAt: rt.now(),
96
+ ...(task.input.note ? { note: task.input.note } : {}),
97
+ },
98
+ },
99
+ }), ctx);
100
+ }
101
+
102
+ async function fail(rt, ctx, message) {
103
+ await rt.commit(() => ({ status: "terminal", outcome: { status: "failed", error: { message } } }), ctx);
104
+ }
105
+
106
+ export const PeerExtension = defineExtension({ name: EXTENSION_NAME, tasks: [AskPeer] });
107
+
108
+ export const entryText = entryToText;
109
+
110
+ /** 解析或按需创建环境会话 */
111
+ export async function resolveOrCreateEnvConversation({ harness, index, cfg, models, ctx }, envName, explicitConvId) {
112
+ if (explicitConvId !== undefined && explicitConvId !== null) {
113
+ const rec = index.get(Number(explicitConvId));
114
+ if (rec && rec.env === envName) {
115
+ const conv = await harness.conversation(Number(explicitConvId), ctx);
116
+ if (conv) return { conversationId: Number(conv.id), rec };
117
+ }
118
+ }
119
+ const existing = pickConversation(index, envName);
120
+ if (existing) {
121
+ const conv = await harness.conversation(existing.conversationId, ctx);
122
+ if (conv) return { conversationId: Number(conv.id), rec: existing };
123
+ }
124
+ if (!cfg?.environments?.[envName]) return null;
125
+ const { createEnvConversation } = await import("../harness.mjs");
126
+ const { resolveDefaultModel } = await import("../providers.mjs");
127
+ const model = models ? await resolveDefaultModel(models, cfg) : cfg.defaultModel;
128
+ if (!model?.provider || !model?.modelId) return null;
129
+ const conv = await createEnvConversation(harness, index, {
130
+ env: envName,
131
+ cwd: cfg.environments[envName].cwd,
132
+ model,
133
+ title: `${envName}`,
134
+ });
135
+ return { conversationId: Number(conv.id), rec: index.get(Number(conv.id)) };
136
+ }
137
+
138
+ /** 同步等待版(CLI / 测试复用) */
139
+ export async function askPeer({ harness, index, cfg, models, ctx }, {
140
+ fromEnv, toEnv, fromConversationId, toConversationId, question, timeoutMs = 600_000, note, onPhase, autoCreate = false,
141
+ }) {
142
+ const t0 = Date.now();
143
+ if (fromEnv === toEnv) return { ok: false, taskId: 0, peerEnv: toEnv, error: "不能问自己所在的环境", elapsedMs: 0 };
144
+
145
+ const from = autoCreate
146
+ ? await resolveOrCreateEnvConversation({ harness, index, cfg, models, ctx }, fromEnv, fromConversationId)
147
+ : (fromConversationId ? { conversationId: Number(fromConversationId), rec: index.get(fromConversationId) } : pickConversation(index, fromEnv));
148
+ const to = autoCreate
149
+ ? await resolveOrCreateEnvConversation({ harness, index, cfg, models, ctx }, toEnv, toConversationId)
150
+ : (toConversationId ? { conversationId: Number(toConversationId), rec: index.get(toConversationId) } : pickConversation(index, toEnv));
151
+
152
+ if (!from) return { ok: false, taskId: 0, peerEnv: toEnv, error: `环境 ${fromEnv} 没有可用会话`, elapsedMs: 0 };
153
+ if (!to) return { ok: false, taskId: 0, peerEnv: toEnv, error: `环境 ${toEnv} 没有可用会话`, elapsedMs: 0 };
154
+
155
+ const input = {
156
+ peerEnv: toEnv,
157
+ peerConversationId: to.conversationId,
158
+ question,
159
+ deadline: Date.now() + timeoutMs,
160
+ askedAt: Date.now(),
161
+ ...(note ? { note } : {}),
162
+ };
163
+
164
+ onPhase?.({ phase: "create" });
165
+ const taskId = await harness.commit(
166
+ (tx) => tx.createTask(AskPeer, input, { ownership: { kind: "conversation" }, conversationId: from.conversationId }),
167
+ ctx,
168
+ );
169
+ onPhase?.({ phase: "waiting", taskId });
170
+
171
+ const settled = await harness.waitForTask(taskId, ctx);
172
+ const outcome = projectTaskOutcome(settled.state?.outcome);
173
+ const elapsedMs = Date.now() - t0;
174
+
175
+ if (!outcome.ok) {
176
+ return { ok: false, taskId, peerEnv: toEnv, elapsedMs, error: outcome.error };
177
+ }
178
+
179
+ const result = outcome.result;
180
+ onPhase?.({ phase: "reading", taskId });
181
+ const entry = await harness.commit((tx) => tx.entry(result.answerEntryId), ctx);
182
+ const answer = entryText(entry);
183
+ onPhase?.({ phase: "done", taskId });
184
+
185
+ return {
186
+ ok: true,
187
+ taskId,
188
+ peerEnv: toEnv,
189
+ answer,
190
+ answerEntryId: result.answerEntryId,
191
+ elapsedMs,
192
+ fromConversationId: from.conversationId,
193
+ toConversationId: to.conversationId,
194
+ };
195
+ }
196
+
197
+ function pickConversation(index, envName) {
198
+ const all = index.forEnv(envName);
199
+ if (all.length === 0) return undefined;
200
+ return all.reduce((a, b) => ((b.createdAt ?? 0) > (a.createdAt ?? 0) ? b : a));
201
+ }