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.
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Agent 自主跨环境协作原语(基于 pi-durable 的 section + defineTool + ToolPark)。
3
+ *
4
+ * 包含:
5
+ * 1. section("foreman-topology") —— 动态注入已配置环境清单,Agent 天然知晓宿主机与容器同伴。
6
+ * 2. list_envs 工具 —— 随时查询最新环境与会话 ID。
7
+ * 3. ask_peer 工具(parked tool)—— Agent 自主向另一个环境(可精确到某个会话)提问并挂起等待答案:
8
+ * - maxDepth(默认 2)与 visited 环路检测,彻底杜绝 A→B→A 死锁;
9
+ * - 进行中的提问同步记入 AsksDoc,供后续调用做防环检查。
10
+ */
11
+ import { randomUUID } from "node:crypto";
12
+ import {
13
+ SubmissionSettled, defineExtension, defineTool, section,
14
+ } from "@earendil-works/pi-durable";
15
+ import { int, obj, opt, str } from "@earendil-works/pi-schema";
16
+ import { AsksDoc, upsertAskRecord } from "../docs.mjs";
17
+ import { entryToText, projectSubmission, signalValue, truncate } from "../projection.mjs";
18
+
19
+ export function createPeerToolsExtension({ cfg, getHarness, getIndex, getModels }) {
20
+ const topologySection = section("foreman-topology", async (input) => {
21
+ const envs = cfg.environments ?? {};
22
+ const names = Object.keys(envs);
23
+ if (names.length === 0) return undefined;
24
+
25
+ const index = getIndex?.();
26
+ const myEnv = index?.get(Number(input.conversationId))?.env;
27
+ const lines = [
28
+ "You are running inside pi-foreman, a multi-environment coding console.",
29
+ myEnv ? `Your current environment name is "${myEnv}".` : "",
30
+ "Available environments you can collaborate with via `ask_peer` (when enabled).",
31
+ "Pass targetConversationId to address one specific session (e.g. when the user writes @name); otherwise the newest session of that environment answers.",
32
+ ...names.map((n) => {
33
+ const e = envs[n];
34
+ const h = cfg.hosts?.[e.host];
35
+ const kind = `${h?.type ?? "ssh"}-${e.runtime ?? (e.container ? "docker" : "host")}`;
36
+ const desc = e.description ? ` — ${e.description}` : "";
37
+ const sessions = index?.forEnv(n) ?? [];
38
+ const roster = sessions.length ? `\n sessions: ${sessions.map((c) => `#${c.conversationId} "${c.title}"`).join(", ")}` : "";
39
+ return `- ${n} (${kind}${e.container ? `, container=${e.container}` : ""}, cwd=${e.cwd ?? "/"})${desc}${roster}`;
40
+ }),
41
+ ].filter(Boolean);
42
+ return lines.join("\n");
43
+ });
44
+
45
+ const listEnvsTool = defineTool({
46
+ name: "list_envs",
47
+ description: "List all configured host and Docker container environments and their active sessions.",
48
+ parameters: obj({}),
49
+ execute: async (_args, api) => {
50
+ const index = getIndex?.();
51
+ const myRec = index?.get(Number(api.conversationId));
52
+ const items = Object.entries(cfg.environments ?? {}).map(([name, e]) => {
53
+ const h = cfg.hosts?.[e.host];
54
+ const convs = index ? index.forEnv(name) : [];
55
+ return {
56
+ name,
57
+ isSelf: myRec?.env === name,
58
+ host: e.host,
59
+ hostType: h?.type ?? "ssh",
60
+ runtime: e.runtime ?? (e.container ? "docker" : "host"),
61
+ container: e.container ?? null,
62
+ cwd: e.cwd ?? null,
63
+ description: e.description ?? null,
64
+ activeConversations: convs.map((c) => ({ conversationId: c.conversationId, title: c.title, cwd: c.cwd })),
65
+ };
66
+ });
67
+ return { output: [{ type: "text", text: JSON.stringify(items, null, 2) }] };
68
+ },
69
+ });
70
+
71
+ const askPeerTool = defineTool({
72
+ name: "ask_peer",
73
+ description:
74
+ "Ask another environment's agent a question (e.g., compare environment versions, inspect container files/logs, verify builds) and wait for its reply.",
75
+ parameters: obj({
76
+ targetEnv: opt(str({ description: "Target environment name (see list_envs). Optional when targetConversationId is given." })),
77
+ targetConversationId: opt(int({ description: "Exact target session id, e.g. the conversationId behind an @name the user mentioned" })),
78
+ question: str({ description: "Clear self-contained question for the target agent" }),
79
+ timeoutSec: opt(int({ minimum: 10, maximum: 900, description: "Timeout in seconds (default 300)" })),
80
+ }),
81
+ replay: "safe",
82
+ execute: async (args, api, context) => {
83
+ const targetLabel = args.targetEnv ?? `会话 #${args.targetConversationId}`;
84
+ // 1. 已经被信号唤醒:读取对端答复
85
+ const wokeSignal = signalValue(await api.readSignal(SubmissionSettled, "answered", context));
86
+ const cp = api.checkpoint;
87
+ if (wokeSignal !== undefined) {
88
+ const view = projectSubmission(wokeSignal);
89
+ const elapsedMs = cp?.askedAt ? api.now() - cp.askedAt : undefined;
90
+ if (!view.ok || view.type !== "input") {
91
+ const err = `对端 ${targetLabel} 未能作答: ${view.error ?? view.status}`;
92
+ if (cp?.askId) {
93
+ await upsertAskRecord(getHarness(), context, {
94
+ id: cp.askId, status: "failed", error: err, elapsedMs, updatedAt: api.now(),
95
+ }).catch(() => {});
96
+ }
97
+ return { output: [{ type: "text", text: err }], isError: true };
98
+ }
99
+ const entry = await api.commit((tx) => tx.entry(view.answerEntryId), context);
100
+ const answer = entryToText(entry) || "(对端无文本输出)";
101
+ if (cp?.askId) {
102
+ await upsertAskRecord(getHarness(), context, {
103
+ id: cp.askId, status: "answered", answer, answerEntryId: view.answerEntryId, elapsedMs, updatedAt: api.now(),
104
+ }).catch(() => {});
105
+ }
106
+ return {
107
+ output: [{ type: "text", text: `[Reply from ${targetLabel}]\n${answer}` }],
108
+ details: { targetEnv: targetLabel, targetConversationId: cp?.targetConversationId, elapsedMs },
109
+ };
110
+ }
111
+
112
+ if (api.wake?.reason === "expired" || api.wake?.reason === "time") {
113
+ if (cp?.askId) {
114
+ await upsertAskRecord(getHarness(), context, {
115
+ id: cp.askId, status: "failed", error: `等待 ${targetLabel} 超时`, updatedAt: api.now(),
116
+ }).catch(() => {});
117
+ }
118
+ return { output: [{ type: "text", text: `等待 ${targetLabel} 回答超时` }], isError: true };
119
+ }
120
+
121
+ // 2. 首次执行:权限、拓扑、深度与环路检查
122
+ if (cfg.peer?.allowAgentTool === false) {
123
+ return { output: [{ type: "text", text: "当前配置已禁用 Agent 自主跨环境提问(peer.allowAgentTool=false)" }], isError: true };
124
+ }
125
+
126
+ const index = getIndex?.();
127
+ // 目标:优先按会话 id 精确投递,否则按环境挑最新会话(必要时新建)
128
+ let targetEnv = args.targetEnv;
129
+ let target;
130
+ if (args.targetConversationId !== undefined) {
131
+ const rec = index?.get(Number(args.targetConversationId));
132
+ if (!rec) {
133
+ return { output: [{ type: "text", text: `找不到会话 #${args.targetConversationId}` }], isError: true };
134
+ }
135
+ if (targetEnv && rec.env !== targetEnv) {
136
+ return { output: [{ type: "text", text: `会话 #${args.targetConversationId} 属于环境 ${rec.env},不是 ${targetEnv}` }], isError: true };
137
+ }
138
+ targetEnv = rec.env;
139
+ target = { conversationId: Number(args.targetConversationId), rec };
140
+ } else {
141
+ if (!targetEnv) {
142
+ return { output: [{ type: "text", text: "需要提供 targetEnv 或 targetConversationId 之一" }], isError: true };
143
+ }
144
+ if (!cfg.environments?.[targetEnv]) {
145
+ return {
146
+ output: [{ type: "text", text: `未知目标环境 "${targetEnv}"。可用环境: ${Object.keys(cfg.environments ?? {}).join(", ")}` }],
147
+ isError: true,
148
+ };
149
+ }
150
+ const { resolveOrCreateEnvConversation } = await import("./ask-peer.mjs");
151
+ target = await resolveOrCreateEnvConversation(
152
+ { harness: getHarness(), index, cfg, models: getModels?.(), ctx: context },
153
+ targetEnv,
154
+ undefined,
155
+ );
156
+ if (!target) {
157
+ return { output: [{ type: "text", text: `无法为环境 ${targetEnv} 创建会话(请先登录并设置默认模型)` }], isError: true };
158
+ }
159
+ }
160
+
161
+ const myRec = index?.get(Number(api.conversationId));
162
+ const fromEnv = myRec?.env ?? "unknown";
163
+ if (fromEnv === targetEnv) {
164
+ return { output: [{ type: "text", text: `不能向当前所在环境 "${targetEnv}" 发起跨环境提问` }], isError: true };
165
+ }
166
+
167
+ // 防环 + 限深:扫描当前是否已有向我们发起并正在等待的 ask,避免 A->B->A 死锁
168
+ const maxDepth = cfg.peer?.maxDepth ?? 2;
169
+ const asksSnap = await api.snapshot(AsksDoc, context);
170
+ const activeAsks = Object.values(asksSnap?.items ?? {}).filter((a) => a.status === "waiting");
171
+ const chainDepth = computeChainDepth(activeAsks, Number(api.conversationId));
172
+ if (chainDepth >= maxDepth) {
173
+ return { output: [{ type: "text", text: `已达到跨环境嵌套调用深度上限 (${maxDepth}),请直接汇总已知信息或请用户介入` }], isError: true };
174
+ }
175
+ if (wouldCycle(activeAsks, Number(api.conversationId), targetEnv)) {
176
+ return { output: [{ type: "text", text: `检测到跨环境调用环路(${targetEnv} 正在等待当前会话的答复),已拒绝` }], isError: true };
177
+ }
178
+
179
+ const askId = await api.memo("ask.id", randomUUID(), context);
180
+ const askedAt = await api.memo("ask.at", api.now(), context);
181
+ const timeoutMs = (args.timeoutSec ?? 300) * 1000;
182
+
183
+ const handle = await api.conversation(target.conversationId, context);
184
+ if (!handle) {
185
+ return { output: [{ type: "text", text: `找不到目标会话 ${target.conversationId}` }], isError: true };
186
+ }
187
+
188
+ await api.commit(async (tx) => {
189
+ await handle.admit(tx, {
190
+ type: "input",
191
+ content: `[来自环境 ${fromEnv} 的 Agent 提问]\n\n${args.question}`,
192
+ requestId: `foreman.ask_peer_tool:${api.taskId}`,
193
+ notify: { taskId: api.taskId, key: "answered" },
194
+ });
195
+ const doc = await tx.doc(AsksDoc);
196
+ doc.items[askId] = {
197
+ id: askId,
198
+ kind: "ask",
199
+ source: "agent-tool",
200
+ status: "waiting",
201
+ fromEnv,
202
+ toEnv: targetEnv,
203
+ fromConversationId: Number(api.conversationId),
204
+ toConversationId: target.conversationId,
205
+ taskId: Number(api.taskId),
206
+ question: truncate(args.question, 2000),
207
+ createdAt: askedAt,
208
+ updatedAt: askedAt,
209
+ };
210
+ if (!doc.order.includes(askId)) doc.order.push(askId);
211
+ }, context);
212
+
213
+ return {
214
+ kind: "sleep",
215
+ signals: [SubmissionSettled.key("answered")],
216
+ until: askedAt + timeoutMs,
217
+ checkpoint: { askId, askedAt, targetConversationId: target.conversationId },
218
+ };
219
+ },
220
+ });
221
+
222
+ return defineExtension({
223
+ name: "foreman-peer-tools",
224
+ sections: [topologySection],
225
+ tools: [listEnvsTool, askPeerTool],
226
+ });
227
+ }
228
+
229
+ function computeChainDepth(activeAsks, currentConvId) {
230
+ let depth = 0;
231
+ let cursor = currentConvId;
232
+ const seen = new Set();
233
+ while (cursor && !seen.has(cursor)) {
234
+ seen.add(cursor);
235
+ const parent = activeAsks.find((a) => a.toConversationId === cursor);
236
+ if (!parent?.fromConversationId) break;
237
+ depth++;
238
+ cursor = parent.fromConversationId;
239
+ }
240
+ return depth;
241
+ }
242
+
243
+ function wouldCycle(activeAsks, currentConvId, targetEnv) {
244
+ let cursor = currentConvId;
245
+ const seen = new Set();
246
+ while (cursor && !seen.has(cursor)) {
247
+ seen.add(cursor);
248
+ const parent = activeAsks.find((a) => a.toConversationId === cursor);
249
+ if (!parent) break;
250
+ if (parent.fromEnv === targetEnv) return true;
251
+ cursor = parent.fromConversationId;
252
+ }
253
+ return false;
254
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * 目录级上下文扩展(workspace-context + read_skill):
3
+ * 1. 动态读取当前会话所在目录的远端 `AGENTS.md` + `.agents/skills` + `.pi/skills`;
4
+ * 2. 合并目录配置里勾选的本地个人 Skills;
5
+ * 3. 仅注入简短摘要索引(保持 Prompt Cache 稳定性),需要详情时 Agent 调用 `read` 或 `read_skill`。
6
+ */
7
+ import { defineExtension, defineTool, section } from "@earendil-works/pi-durable";
8
+ import { obj, str } from "@earendil-works/pi-schema";
9
+ import { resolveWorkspaceFor } from "../config.mjs";
10
+ import {
11
+ discoverRemoteWorkspaceContext,
12
+ listLocalSkills,
13
+ readLocalSkill,
14
+ } from "../skills.mjs";
15
+
16
+ export function createWorkspaceExtension({ cfg, getIndex }) {
17
+ const workspaceSection = section("workspace-context", async (input, context) => {
18
+ const index = getIndex?.();
19
+ const rec = index?.get(Number(input.conversationId));
20
+ const envName = rec?.env;
21
+ const cwd = input.agent?.cwd ?? rec?.cwd ?? (envName ? cfg.environments?.[envName]?.cwd : undefined);
22
+ const ws = envName ? resolveWorkspaceFor(cfg, envName, cwd) : null;
23
+
24
+ let remote = { agentsMd: null, skills: [] };
25
+ if (input.env && cwd) {
26
+ try {
27
+ remote = await discoverRemoteWorkspaceContext(input.env, cwd, context);
28
+ } catch { /* 目录不可达时不阻断模型对话 */ }
29
+ }
30
+
31
+ const disabled = new Set(ws?.disabledSkills ?? []);
32
+ const remoteSkills = remote.skills.filter((s) => !disabled.has(s.name));
33
+ const remoteNames = new Set(remoteSkills.map((s) => s.name));
34
+
35
+ const enabledLocalNames = new Set(ws?.skills ?? []);
36
+ const localSkills = enabledLocalNames.size > 0
37
+ ? listLocalSkills().filter((s) => enabledLocalNames.has(s.name) && !remoteNames.has(s.name))
38
+ : [];
39
+
40
+ const chunks = [];
41
+ if (ws?.instructions) {
42
+ chunks.push(`<workspace-instructions>\n${ws.instructions}\n</workspace-instructions>`);
43
+ }
44
+ if (remote.agentsMd) {
45
+ chunks.push(`<project-agents-md path="${cwd}/AGENTS.md">\n${remote.agentsMd}\n</project-agents-md>`);
46
+ }
47
+
48
+ if (remoteSkills.length > 0 || localSkills.length > 0) {
49
+ const lines = [
50
+ "The following directory skills are available for this workspace. When a task matches one, read its full SKILL.md before acting:",
51
+ ...remoteSkills.map((s) =>
52
+ `- **${s.name}** (workspace \`${s.path}\`): ${s.description || "Use `read` on this file for instructions."}`,
53
+ ),
54
+ ...localSkills.map((s) =>
55
+ `- **${s.name}** (local skill): ${s.description || "Call `read_skill` to load instructions."}`,
56
+ ),
57
+ ];
58
+ chunks.push(`<available-skills>\n${lines.join("\n")}\n</available-skills>`);
59
+ }
60
+
61
+ return chunks.length > 0 ? chunks.join("\n\n") : undefined;
62
+ }, { tag: false });
63
+
64
+ const readSkillTool = defineTool({
65
+ name: "read_skill",
66
+ description: "Read full instructions (SKILL.md) of a skill enabled for this workspace.",
67
+ parameters: obj({
68
+ name: str({ description: "Skill name from <available-skills>" }),
69
+ }),
70
+ execute: async (args, api, context) => {
71
+ const cleanName = String(args.name ?? "").trim();
72
+ const index = getIndex?.();
73
+ const rec = index?.get(Number(api.conversationId));
74
+ const envName = rec?.env;
75
+ const cwd = rec?.cwd ?? api.env?.cwd ?? (envName ? cfg.environments?.[envName]?.cwd : undefined);
76
+
77
+ // 先尝试从远端工作目录查找
78
+ if (api.env && cwd) {
79
+ try {
80
+ const remote = await discoverRemoteWorkspaceContext(api.env, cwd, context);
81
+ const hit = remote.skills.find((s) => s.name === cleanName || s.dirName === cleanName);
82
+ if (hit) {
83
+ const res = await api.env.readTextFile(hit.path, context);
84
+ if (res.ok) {
85
+ return { output: [{ type: "text", text: `# Skill: ${hit.name} (${hit.path})\n\n${res.value}` }] };
86
+ }
87
+ }
88
+ } catch { /* fallback local */ }
89
+ }
90
+
91
+ const local = readLocalSkill(cleanName);
92
+ if (local) {
93
+ return { output: [{ type: "text", text: `# Skill: ${local.name} (local)\n\n${local.content}` }] };
94
+ }
95
+
96
+ return {
97
+ output: [{ type: "text", text: `未找到名为 "${cleanName}" 的 Skill。` }],
98
+ isError: true,
99
+ };
100
+ },
101
+ });
102
+
103
+ return defineExtension({
104
+ name: "foreman-workspace",
105
+ sections: [workspaceSection],
106
+ tools: [readSkillTool],
107
+ });
108
+ }
@@ -0,0 +1 @@
1
+ @keyframes aui-pulse{50%{opacity:.5}}:where(.aui-md[data-status=running]):empty:after,:where(.aui-md[data-status=running])>:where(:not(ol):not(ul):not(pre)):last-child:after,:where(.aui-md[data-status=running])>pre:last-child code:after,:where(.aui-md[data-status=running])>:where(:is(ol,ul):last-child)>:where(li:last-child:not(:has(*>li))):after,:where(.aui-md[data-status=running])>:where(:is(ol,ul):last-child)>:where(li:last-child)>:where(:is(ol,ul):last-child)>:where(li:last-child:not(:has(*>li))):after,:where(.aui-md[data-status=running])>:where(:is(ol,ul):last-child)>:where(li:last-child)>:where(:is(ol,ul):last-child)>:where(li:last-child)>:where(:is(ol,ul):last-child)>:where(li:last-child):after{animation:aui-pulse 2s cubic-bezier(.4,0,.6,1) infinite;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";--aui-content: "●";content:var(--aui-content);margin-left:.25rem;margin-right:.25rem}