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/LICENSE +21 -0
- package/README.md +179 -2
- package/package.json +58 -4
- package/src/bootstrap.mjs +107 -0
- package/src/cli.mjs +504 -0
- package/src/config.mjs +819 -0
- package/src/docs.mjs +148 -0
- package/src/envs.mjs +621 -0
- package/src/harness.mjs +96 -0
- package/src/hub.mjs +117 -0
- package/src/projection.mjs +455 -0
- package/src/providers.mjs +622 -0
- package/src/server.mjs +1350 -0
- package/src/skills.mjs +340 -0
- package/src/stores.mjs +117 -0
- package/src/tasks/ask-peer.mjs +201 -0
- package/src/tasks/peer-tools.mjs +254 -0
- package/src/tasks/workspace-extension.mjs +108 -0
- package/web/dist/assets/chat-vendor-CpKl2eGN.css +1 -0
- package/web/dist/assets/chat-vendor-PY5rkhAV.js +43 -0
- package/web/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/web/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/web/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/web/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/web/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/web/dist/assets/icons-BRdrcGH3.js +2 -0
- package/web/dist/assets/index-C32JOM8D.js +35 -0
- package/web/dist/assets/index-D_7gqB73.css +1 -0
- package/web/dist/assets/react-vendor-DEAzPTfA.js +10 -0
- package/web/dist/index.html +17 -0
package/src/harness.mjs
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Harness 装配 + SQLite 会话元数据索引 + 协作扩展注册。
|
|
3
|
+
*/
|
|
4
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
5
|
+
import { createRegistry, Harness } from "@earendil-works/pi-durable";
|
|
6
|
+
import { CodingTools } from "@earendil-works/pi-durable/tools";
|
|
7
|
+
import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
|
|
8
|
+
import { paths } from "./config.mjs";
|
|
9
|
+
import { DurableConvIndex } from "./docs.mjs";
|
|
10
|
+
import { PeerExtension } from "./tasks/ask-peer.mjs";
|
|
11
|
+
import { createPeerToolsExtension } from "./tasks/peer-tools.mjs";
|
|
12
|
+
import { createWorkspaceExtension } from "./tasks/workspace-extension.mjs";
|
|
13
|
+
|
|
14
|
+
export const CONTEXT = BACKGROUND_CONTEXT;
|
|
15
|
+
|
|
16
|
+
export function createFleetRegistry({ cfg, getHarness, getIndex, getModels } = {}) {
|
|
17
|
+
const registry = createRegistry();
|
|
18
|
+
registry.install(CodingTools);
|
|
19
|
+
registry.install(PeerExtension);
|
|
20
|
+
if (cfg && getIndex) {
|
|
21
|
+
registry.install(createWorkspaceExtension({ cfg, getIndex }));
|
|
22
|
+
}
|
|
23
|
+
if (cfg && getHarness && getIndex) {
|
|
24
|
+
registry.install(createPeerToolsExtension({ cfg, getHarness, getIndex, getModels }));
|
|
25
|
+
}
|
|
26
|
+
return registry;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 打开 Fleet:一个 Harness 承载所有环境的所有会话。
|
|
31
|
+
* models 参数支持传函数 `() => models`,方便 `/reload` 热替换。
|
|
32
|
+
*/
|
|
33
|
+
export async function openFleet({ cfg, dir, envs, models, registry, onWake, settings }) {
|
|
34
|
+
const p = paths(dir);
|
|
35
|
+
const storage = await openNodeSqliteStorage(p.sessionDb);
|
|
36
|
+
|
|
37
|
+
let harnessRef = null;
|
|
38
|
+
let indexRef = null;
|
|
39
|
+
const modelsGetter = typeof models === "function" ? models : () => models;
|
|
40
|
+
|
|
41
|
+
const reg = registry ?? createFleetRegistry({
|
|
42
|
+
cfg,
|
|
43
|
+
getHarness: () => harnessRef,
|
|
44
|
+
getIndex: () => indexRef,
|
|
45
|
+
getModels: modelsGetter,
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const harness = await Harness.open(storage, {
|
|
49
|
+
models,
|
|
50
|
+
registry: reg,
|
|
51
|
+
env: async (target) => {
|
|
52
|
+
const rec = indexRef?.get(target.conversationId);
|
|
53
|
+
if (!rec) return undefined;
|
|
54
|
+
const fallbackCwd = cfg.environments?.[rec.env]?.cwd ?? ".";
|
|
55
|
+
// target.cwd 来自 pi.agent.cwd(/cd 修改后即时生效)
|
|
56
|
+
return envs.envAsync(rec.env, target.cwd ?? rec.cwd ?? fallbackCwd);
|
|
57
|
+
},
|
|
58
|
+
onWake: onWake ?? (() => {}),
|
|
59
|
+
...(mergedSettings(cfg, settings) ? { settings: mergedSettings(cfg, settings) } : {}),
|
|
60
|
+
}, CONTEXT);
|
|
61
|
+
|
|
62
|
+
harnessRef = harness;
|
|
63
|
+
indexRef = new DurableConvIndex(harness, dir, CONTEXT);
|
|
64
|
+
await indexRef.load();
|
|
65
|
+
|
|
66
|
+
return { harness, index: indexRef, storage, registry: reg };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function mergedSettings(cfg, override) {
|
|
70
|
+
const fromCfg = cfg?.harness?.settings;
|
|
71
|
+
const merged = { ...(fromCfg ?? {}), ...(override ?? {}) };
|
|
72
|
+
return Object.keys(merged).length ? merged : undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 建一个绑定到指定环境的会话(创建会话与元数据落盘尽可能同步) */
|
|
76
|
+
export async function createEnvConversation(harness, index, { env, cwd, model, thinkingLevel, title }) {
|
|
77
|
+
const { configure } = await import("@earendil-works/pi-durable");
|
|
78
|
+
const createdAt = Date.now();
|
|
79
|
+
const meta = { env, cwd, title: title ?? `${env}${cwd ? `:${cwd}` : ""}`, createdAt };
|
|
80
|
+
const id = await harness.commit(async (tx) => {
|
|
81
|
+
const created = await tx.createConversation({ ownership: { kind: "ownerless" } });
|
|
82
|
+
const change = {
|
|
83
|
+
...(model?.provider && model?.modelId ? { model } : {}),
|
|
84
|
+
...(cwd ? { cwd } : {}),
|
|
85
|
+
...(thinkingLevel ? { thinkingLevel } : {}),
|
|
86
|
+
};
|
|
87
|
+
if (Object.keys(change).length > 0) {
|
|
88
|
+
await configure(tx, created.id, change);
|
|
89
|
+
}
|
|
90
|
+
await index.setInTx(tx, created.id, meta);
|
|
91
|
+
return created.id;
|
|
92
|
+
}, CONTEXT);
|
|
93
|
+
return harness.conversation(id, CONTEXT);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export { createRegistry };
|
package/src/hub.mjs
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Watch 扇出层。
|
|
3
|
+
*
|
|
4
|
+
* pi 的 WatchHandle.start() 只能装【一个】异步监听器;这里做引用计数扇出,
|
|
5
|
+
* 并显式提供 close() 确保关服时能真正调用上游 handle.stop()。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export class Channel {
|
|
9
|
+
#key;
|
|
10
|
+
#acquire;
|
|
11
|
+
#project;
|
|
12
|
+
#handle = null;
|
|
13
|
+
#snapshot = undefined;
|
|
14
|
+
#subs = new Set();
|
|
15
|
+
#starting = null;
|
|
16
|
+
#error = null;
|
|
17
|
+
|
|
18
|
+
constructor(key, acquire, project) {
|
|
19
|
+
this.#key = key;
|
|
20
|
+
this.#acquire = acquire;
|
|
21
|
+
this.#project = project;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
get key() { return this.#key; }
|
|
25
|
+
get subscriberCount() { return this.#subs.size; }
|
|
26
|
+
get snapshot() { return this.#snapshot; }
|
|
27
|
+
|
|
28
|
+
subscribe(emit) {
|
|
29
|
+
this.#subs.add(emit);
|
|
30
|
+
if (this.#snapshot !== undefined || this.#error) this.#push(emit);
|
|
31
|
+
if (!this.#handle && !this.#starting) this.#start();
|
|
32
|
+
return () => this.unsubscribe(emit);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
unsubscribe(emit) {
|
|
36
|
+
this.#subs.delete(emit);
|
|
37
|
+
if (this.#subs.size === 0) void this.#stop();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
refresh() {
|
|
41
|
+
if (this.#handle) this.#broadcast();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async close() {
|
|
45
|
+
this.#subs.clear();
|
|
46
|
+
await this.#stop();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async #start() {
|
|
50
|
+
this.#starting = (async () => {
|
|
51
|
+
try {
|
|
52
|
+
const handle = await this.#acquire();
|
|
53
|
+
if (this.#subs.size === 0) {
|
|
54
|
+
try { await handle.stop(); } catch { /* already stopped */ }
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
this.#handle = handle;
|
|
58
|
+
this.#snapshot = this.#project(handle.value);
|
|
59
|
+
this.#error = null;
|
|
60
|
+
handle.start(async (call) => {
|
|
61
|
+
if (call.kind !== "value") return;
|
|
62
|
+
this.#snapshot = this.#project(call.value);
|
|
63
|
+
this.#broadcast();
|
|
64
|
+
});
|
|
65
|
+
this.#broadcast();
|
|
66
|
+
} catch (error) {
|
|
67
|
+
this.#error = String(error?.message ?? error);
|
|
68
|
+
this.#handle = null;
|
|
69
|
+
this.#broadcast();
|
|
70
|
+
} finally {
|
|
71
|
+
this.#starting = null;
|
|
72
|
+
}
|
|
73
|
+
})();
|
|
74
|
+
return this.#starting;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async #stop() {
|
|
78
|
+
const handle = this.#handle;
|
|
79
|
+
this.#handle = null;
|
|
80
|
+
this.#snapshot = undefined;
|
|
81
|
+
if (handle) {
|
|
82
|
+
try { await handle.stop(); } catch { /* 已经停了 */ }
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
#broadcast() {
|
|
87
|
+
for (const emit of [...this.#subs]) this.#push(emit);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#push(emit) {
|
|
91
|
+
try {
|
|
92
|
+
emit(this.#snapshot, { key: this.#key, ...(this.#error ? { error: this.#error } : {}) });
|
|
93
|
+
} catch { /* 订阅者已断开 */ }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export class Hub {
|
|
98
|
+
#channels = new Map();
|
|
99
|
+
|
|
100
|
+
channel(key, acquire, project) {
|
|
101
|
+
let c = this.#channels.get(key);
|
|
102
|
+
if (!c) {
|
|
103
|
+
c = new Channel(key, acquire, project);
|
|
104
|
+
this.#channels.set(key, c);
|
|
105
|
+
}
|
|
106
|
+
return c;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
stats() {
|
|
110
|
+
return [...this.#channels.values()].map((c) => ({ key: c.key, subscribers: c.subscriberCount }));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async closeAll() {
|
|
114
|
+
await Promise.all([...this.#channels.values()].map((c) => c.close()));
|
|
115
|
+
this.#channels.clear();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ═══════════════════════════════════════════════════════════════════════════
|
|
3
|
+
* 防腐层(Anti-Corruption Layer)
|
|
4
|
+
*
|
|
5
|
+
* 🔴 全项目【唯一】允许解构 pi-durable / pi-ai 原始记录形状的文件。
|
|
6
|
+
* CLI、WebSocket/HTTP 服务、GUI 一律只消费这里导出的 DTO。
|
|
7
|
+
* ═══════════════════════════════════════════════════════════════════════════
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const KIND_MAP = {
|
|
11
|
+
"pi.user": "user",
|
|
12
|
+
"pi.assistant": "assistant",
|
|
13
|
+
"pi.tool-result": "toolResult",
|
|
14
|
+
"pi.system": "system",
|
|
15
|
+
"pi.reset": "reset",
|
|
16
|
+
"pi.compaction": "compaction",
|
|
17
|
+
"foreman.exec": "exec",
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export function entryKind(rawKind) {
|
|
21
|
+
return KIND_MAP[rawKind] ?? "other";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function contentText(content) {
|
|
25
|
+
if (typeof content === "string") return content;
|
|
26
|
+
if (!Array.isArray(content)) return "";
|
|
27
|
+
return content
|
|
28
|
+
.filter((p) => p && p.type === "text" && typeof p.text === "string")
|
|
29
|
+
.map((p) => p.text)
|
|
30
|
+
.join("");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function messageTime(msg) {
|
|
34
|
+
return typeof msg?.timestamp === "number" ? msg.timestamp : undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function extractDiff(details) {
|
|
38
|
+
if (!details || typeof details !== "object") return undefined;
|
|
39
|
+
const { diff, patch, firstChangedLine } = details;
|
|
40
|
+
if (typeof diff !== "string" && typeof patch !== "string") return undefined;
|
|
41
|
+
return {
|
|
42
|
+
text: typeof diff === "string" ? diff : "",
|
|
43
|
+
patch: typeof patch === "string" ? patch : "",
|
|
44
|
+
firstChangedLine: typeof firstChangedLine === "number" ? firstChangedLine : undefined,
|
|
45
|
+
lineCount: typeof diff === "string" ? diff.split("\n").length : 0,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function projectEntry(entry) {
|
|
50
|
+
if (!entry || typeof entry !== "object") return undefined;
|
|
51
|
+
const kind = entryKind(entry.kind);
|
|
52
|
+
const messages = Array.isArray(entry.model) ? entry.model : [];
|
|
53
|
+
const first = messages[0];
|
|
54
|
+
|
|
55
|
+
const view = {
|
|
56
|
+
id: id(entry.id),
|
|
57
|
+
kind,
|
|
58
|
+
rawKind: entry.kind,
|
|
59
|
+
conversationId: id(entry.conversationId),
|
|
60
|
+
at: messageTime(first),
|
|
61
|
+
taskId: id(entry.byTaskId),
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
if (kind === "user") {
|
|
65
|
+
view.text = contentText(first?.content);
|
|
66
|
+
return view;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (kind === "assistant") {
|
|
70
|
+
const parts = Array.isArray(first?.content) ? first.content : [];
|
|
71
|
+
view.text = parts.filter((p) => p?.type === "text").map((p) => p.text).join("");
|
|
72
|
+
const thinking = parts.filter((p) => p?.type === "thinking").map((p) => p.thinking ?? "").join("");
|
|
73
|
+
if (thinking) view.thinking = thinking;
|
|
74
|
+
const calls = parts.filter((p) => p?.type === "toolCall");
|
|
75
|
+
if (calls.length) view.toolCalls = calls.map(projectToolCall);
|
|
76
|
+
if (first) {
|
|
77
|
+
view.stopReason = first.stopReason;
|
|
78
|
+
view.errorMessage = first.errorMessage;
|
|
79
|
+
view.durationMs = first.durationMs;
|
|
80
|
+
view.model = first.model;
|
|
81
|
+
view.provider = first.provider;
|
|
82
|
+
if (first.usage) view.usage = projectUsage(first.usage);
|
|
83
|
+
}
|
|
84
|
+
return view;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (kind === "toolResult") {
|
|
88
|
+
view.toolResult = projectToolResult(first);
|
|
89
|
+
return view;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (kind === "compaction" || kind === "reset" || kind === "system") {
|
|
93
|
+
view.text = contentText(first?.content) || (entry.data && typeof entry.data === "object"
|
|
94
|
+
? String(entry.data.reason ?? entry.data.summary ?? "")
|
|
95
|
+
: "");
|
|
96
|
+
view.data = entry.data;
|
|
97
|
+
return view;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (kind === "exec") {
|
|
101
|
+
view.at = typeof entry.data?.at === "number" ? entry.data.at : messageTime(first);
|
|
102
|
+
view.data = entry.data;
|
|
103
|
+
view.text = contentText(first?.content);
|
|
104
|
+
return view;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
view.data = entry.data;
|
|
108
|
+
view.text = contentText(first?.content);
|
|
109
|
+
return view;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function projectToolCall(call) {
|
|
113
|
+
if (!call) return undefined;
|
|
114
|
+
return {
|
|
115
|
+
id: call.id,
|
|
116
|
+
name: call.name,
|
|
117
|
+
args: call.arguments ?? {},
|
|
118
|
+
...(call.argumentsError ? { argsError: call.argumentsError } : {}),
|
|
119
|
+
...(call.namespace ? { namespace: call.namespace } : {}),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function projectToolResult(msg) {
|
|
124
|
+
if (!msg || msg.role !== "toolResult") return undefined;
|
|
125
|
+
return {
|
|
126
|
+
callId: msg.toolCallId,
|
|
127
|
+
name: msg.toolName,
|
|
128
|
+
isError: Boolean(msg.isError),
|
|
129
|
+
text: contentText(msg.content),
|
|
130
|
+
durationMs: msg.durationMs,
|
|
131
|
+
diff: extractDiff(msg.details),
|
|
132
|
+
details: msg.details,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function entryToText(entry) {
|
|
137
|
+
const msgs = Array.isArray(entry?.model) ? entry.model : [];
|
|
138
|
+
return msgs.map((m) => contentText(m?.content)).filter(Boolean).join("\n").trim();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function projectWake(wake) {
|
|
142
|
+
if (!wake || typeof wake !== "object") return undefined;
|
|
143
|
+
switch (wake.reason) {
|
|
144
|
+
case "signal": return { reason: "signal", signal: wake.signal, key: wake.key };
|
|
145
|
+
case "tasks": return { reason: "tasks", ended: (wake.ended ?? []).map(id) };
|
|
146
|
+
case "time": return { reason: "time" };
|
|
147
|
+
case "expired": return { reason: "expired" };
|
|
148
|
+
default: return { reason: String(wake.reason) };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function isWakeExpired(wake) {
|
|
153
|
+
const w = projectWake(wake);
|
|
154
|
+
return w?.reason === "expired" || w?.reason === "time";
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function projectEntries(entries) {
|
|
158
|
+
if (!Array.isArray(entries)) return [];
|
|
159
|
+
return entries.map(projectEntry).filter(Boolean).sort((a, b) => a.id - b.id);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function projectLive(live) {
|
|
163
|
+
if (!live || typeof live !== "object") return { running: false, tools: [], nestedTools: [], compactions: [] };
|
|
164
|
+
|
|
165
|
+
const tools = Array.isArray(live.tools) ? live.tools.map(projectToolSlot) : [];
|
|
166
|
+
const generation = live.generation
|
|
167
|
+
? {
|
|
168
|
+
attempt: live.generation.attempt,
|
|
169
|
+
text: contentText(live.generation.message?.content),
|
|
170
|
+
thinking: (Array.isArray(live.generation.message?.content)
|
|
171
|
+
? live.generation.message.content.filter((p) => p?.type === "thinking").map((p) => p.thinking).join("")
|
|
172
|
+
: "") || undefined,
|
|
173
|
+
retryAt: live.generation.retry?.at,
|
|
174
|
+
retryError: live.generation.retry?.error,
|
|
175
|
+
pollAt: live.generation.deferred?.pollAt,
|
|
176
|
+
}
|
|
177
|
+
: undefined;
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
running: Boolean(live.run) || tools.some((t) => t.status === "running" || t.status === "pending"),
|
|
181
|
+
turns: live.run?.turns,
|
|
182
|
+
runTaskId: id(live.run?.taskId),
|
|
183
|
+
generation,
|
|
184
|
+
tools,
|
|
185
|
+
nestedTools: Array.isArray(live.nestedTools) ? live.nestedTools.map(projectToolSlot) : [],
|
|
186
|
+
compactions: Array.isArray(live.compactions)
|
|
187
|
+
? live.compactions.map((c) => ({
|
|
188
|
+
taskId: id(c.taskId), trigger: c.trigger, blocking: c.blocking,
|
|
189
|
+
attempt: c.attempt, retryAt: c.retry?.at, retryError: c.retry?.error,
|
|
190
|
+
}))
|
|
191
|
+
: [],
|
|
192
|
+
compactionFailure: live.compactionFailure
|
|
193
|
+
? { taskId: id(live.compactionFailure.taskId), trigger: live.compactionFailure.trigger, error: live.compactionFailure.error }
|
|
194
|
+
: undefined,
|
|
195
|
+
failure: live.runFailure
|
|
196
|
+
? { taskId: id(live.runFailure.taskId), reason: live.runFailure.reason, detail: live.runFailure.detail }
|
|
197
|
+
: undefined,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function projectToolSlot(slot) {
|
|
202
|
+
if (!slot) return undefined;
|
|
203
|
+
return {
|
|
204
|
+
callId: slot.callId,
|
|
205
|
+
name: slot.name,
|
|
206
|
+
status: slot.status,
|
|
207
|
+
output: slot.output,
|
|
208
|
+
droppedBytes: slot.droppedBytes,
|
|
209
|
+
droppedLines: slot.droppedLines,
|
|
210
|
+
details: slot.details,
|
|
211
|
+
diff: extractDiff(slot.details),
|
|
212
|
+
taskId: id(slot.taskId),
|
|
213
|
+
entryId: id(slot.entry),
|
|
214
|
+
unoffered: slot.unoffered === true,
|
|
215
|
+
diagnostics: slot.diagnostics,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function projectUsage(usage) {
|
|
220
|
+
if (!usage) return undefined;
|
|
221
|
+
return {
|
|
222
|
+
input: usage.input ?? 0,
|
|
223
|
+
output: usage.output ?? 0,
|
|
224
|
+
cacheRead: usage.cacheRead ?? 0,
|
|
225
|
+
cacheWrite: usage.cacheWrite ?? 0,
|
|
226
|
+
reasoning: usage.reasoning ?? 0,
|
|
227
|
+
totalTokens: usage.totalTokens ?? 0,
|
|
228
|
+
cost: usage.cost?.total ?? 0,
|
|
229
|
+
costFromProvider: usage.cost?.totalFromProvider === true,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function projectUsageState(state) {
|
|
234
|
+
if (!state || typeof state !== "object") return { models: [], tools: [], totals: emptyTotals() };
|
|
235
|
+
const models = Object.entries(state.models ?? {}).map(([key, u]) => ({ key, ...projectUsage(u) }));
|
|
236
|
+
const tools = Object.entries(state.tools ?? {}).map(([key, u]) => ({ key, ...projectUsage(u) }));
|
|
237
|
+
const totals = models.reduce(
|
|
238
|
+
(acc, m) => ({
|
|
239
|
+
input: acc.input + m.input, output: acc.output + m.output,
|
|
240
|
+
cacheRead: acc.cacheRead + m.cacheRead, cacheWrite: acc.cacheWrite + m.cacheWrite,
|
|
241
|
+
reasoning: acc.reasoning + m.reasoning, totalTokens: acc.totalTokens + m.totalTokens,
|
|
242
|
+
cost: acc.cost + m.cost,
|
|
243
|
+
}),
|
|
244
|
+
emptyTotals(),
|
|
245
|
+
);
|
|
246
|
+
return { models, tools, totals };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function emptyTotals() {
|
|
250
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, totalTokens: 0, cost: 0 };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export const ASK_PEER_TASK_KIND = "foreman.ask-peer";
|
|
254
|
+
|
|
255
|
+
export function projectTaskGraph(graph) {
|
|
256
|
+
const tasks = graph?.tasks;
|
|
257
|
+
if (!tasks || typeof tasks !== "object") return [];
|
|
258
|
+
return Object.values(tasks).map(projectTaskNode).filter(Boolean).sort((a, b) => a.id - b.id);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function projectTaskNode(node) {
|
|
262
|
+
if (!node) return undefined;
|
|
263
|
+
const st = node.state ?? {};
|
|
264
|
+
const view = {
|
|
265
|
+
id: id(node.id),
|
|
266
|
+
kind: node.kind,
|
|
267
|
+
conversationId: id(node.conversationId),
|
|
268
|
+
ownerId: id(node.owner),
|
|
269
|
+
background: Boolean(node.background),
|
|
270
|
+
abortRequested: Boolean(node.abortRequested),
|
|
271
|
+
status: st.status,
|
|
272
|
+
phase: st.phase,
|
|
273
|
+
blocked: node.blocked,
|
|
274
|
+
ownedConversations: (node.conversations ?? []).map(id),
|
|
275
|
+
isAskPeer: node.kind === ASK_PEER_TASK_KIND || node.kind === "pi.tool",
|
|
276
|
+
};
|
|
277
|
+
if (st.status === "waiting") {
|
|
278
|
+
view.waitingOn = (st.on ?? []).map(id);
|
|
279
|
+
view.joinPolicy = st.policy;
|
|
280
|
+
}
|
|
281
|
+
if (st.status === "sleeping") {
|
|
282
|
+
view.until = st.until;
|
|
283
|
+
view.signals = (st.signals ?? []).map((s) => ({ signal: s.signal, key: s.key }));
|
|
284
|
+
view.awaitingPeer = view.signals.some((s) => s.signal === "pi.submission-settled");
|
|
285
|
+
view.awaitingApproval = view.signals.some((s) => s.signal === "foreman.peer-approval");
|
|
286
|
+
}
|
|
287
|
+
if (st.status === "completing") view.outcomeStatus = st.outcome;
|
|
288
|
+
view.label = taskLabel(view);
|
|
289
|
+
return view;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function taskLabel(node) {
|
|
293
|
+
const base = node.kind === ASK_PEER_TASK_KIND ? "跨环境提问" : node.kind.replace(/^pi\./, "");
|
|
294
|
+
switch (node.status) {
|
|
295
|
+
case "waiting": return `${base} · 等待 ${node.waitingOn?.length ?? 0} 个子任务(${node.joinPolicy})`;
|
|
296
|
+
case "sleeping":
|
|
297
|
+
if (node.awaitingApproval) return `${base} · 等待人工放行跨环境提问`;
|
|
298
|
+
if (node.awaitingPeer) return `${base} · 等待对端回答${node.until ? `(截止 ${new Date(node.until).toLocaleTimeString()})` : ""}`;
|
|
299
|
+
return `${base} · 休眠${node.until ? `至 ${new Date(node.until).toLocaleTimeString()}` : ""}`;
|
|
300
|
+
case "completing": return `${base} · 收尾(${node.outcomeStatus})`;
|
|
301
|
+
default: return `${base} · ${node.status}`;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export function projectSubmission(settled) {
|
|
306
|
+
if (!settled) return { ok: false, status: "unknown", error: "submission 未返回结果" };
|
|
307
|
+
if (settled.status === "done") {
|
|
308
|
+
return {
|
|
309
|
+
ok: true, status: "done",
|
|
310
|
+
type: settled.type,
|
|
311
|
+
entryId: id(settled.entry),
|
|
312
|
+
answerEntryId: id(settled.answer),
|
|
313
|
+
conversationId: id(settled.conversationId),
|
|
314
|
+
submissionId: id(settled.id),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
ok: false,
|
|
319
|
+
status: settled.status ?? "unanswered",
|
|
320
|
+
type: settled.type,
|
|
321
|
+
reason: settled.reason,
|
|
322
|
+
error: settled.reason ? `${settled.reason}${settled.detail ? `: ${truncate(String(settled.detail), 300)}` : ""}` : "未作答",
|
|
323
|
+
conversationId: id(settled.conversationId),
|
|
324
|
+
submissionId: id(settled.id),
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export function projectTaskOutcome(outcome) {
|
|
329
|
+
if (!outcome) return { ok: false, status: "unknown", error: "任务无 outcome" };
|
|
330
|
+
if (outcome.status === "completed") return { ok: true, status: "completed", result: outcome.result };
|
|
331
|
+
return {
|
|
332
|
+
ok: false,
|
|
333
|
+
status: outcome.status,
|
|
334
|
+
error: outcome.error?.message ?? outcome.reason ?? `任务以 ${outcome.status} 结束`,
|
|
335
|
+
result: outcome.result,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function signalValue(state) {
|
|
340
|
+
if (!state) return undefined;
|
|
341
|
+
if (state.kind === "value") return state.value;
|
|
342
|
+
if (state.kind) return undefined;
|
|
343
|
+
return state;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function projectModel(model, supportedThinkingLevels) {
|
|
347
|
+
if (!model || typeof model !== "object") return undefined;
|
|
348
|
+
return {
|
|
349
|
+
provider: model.provider,
|
|
350
|
+
id: model.id,
|
|
351
|
+
name: model.name ?? model.id,
|
|
352
|
+
api: model.api,
|
|
353
|
+
contextWindow: model.contextWindow ?? 0,
|
|
354
|
+
maxTokens: model.maxTokens ?? 0,
|
|
355
|
+
vision: Array.isArray(model.input) && model.input.includes("image"),
|
|
356
|
+
reasoning: model.reasoning === true,
|
|
357
|
+
...(Array.isArray(supportedThinkingLevels) ? { supportedThinkingLevels } : {}),
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export function projectEnvStatus(name, probe) {
|
|
362
|
+
if (!probe?.ok) {
|
|
363
|
+
return { name, ok: false, error: probe?.error ?? "未知错误", ms: probe?.ms, mode: probe?.mode };
|
|
364
|
+
}
|
|
365
|
+
const i = probe.info ?? {};
|
|
366
|
+
return {
|
|
367
|
+
name, ok: true, mode: probe.mode,
|
|
368
|
+
os: i.os, arch: i.arch, home: i.home, tmpdir: i.tmpdir,
|
|
369
|
+
pid: i.pid, protocol: i.protocol, version: i.version,
|
|
370
|
+
separator: i.separator, features: i.features ?? [],
|
|
371
|
+
connectMs: probe.connectMs, opMs: probe.opMs,
|
|
372
|
+
latencyGrade: gradeLatency(probe.opMs),
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export function gradeLatency(ms) {
|
|
377
|
+
if (ms === undefined || ms === null) return undefined;
|
|
378
|
+
if (ms < 20) return "优秀";
|
|
379
|
+
if (ms < 80) return "良好";
|
|
380
|
+
if (ms < 250) return "可用";
|
|
381
|
+
return "偏慢";
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
export function projectFileInfo(info) {
|
|
385
|
+
if (!info) return undefined;
|
|
386
|
+
return {
|
|
387
|
+
name: info.name,
|
|
388
|
+
path: info.path,
|
|
389
|
+
kind: info.kind,
|
|
390
|
+
isDir: info.kind === "directory",
|
|
391
|
+
size: info.size ?? 0,
|
|
392
|
+
mtimeMs: info.mtimeMs ?? 0,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export function projectFileListing(listing) {
|
|
397
|
+
return {
|
|
398
|
+
entries: (listing?.entries ?? []).map((e) => ({ path: e.path, kind: e.kind, isDir: e.kind === "directory" })),
|
|
399
|
+
truncated: Boolean(listing?.truncated),
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export function projectExec(result, accumulated, command) {
|
|
404
|
+
const ok = result?.ok === true;
|
|
405
|
+
return {
|
|
406
|
+
ok,
|
|
407
|
+
command: Array.isArray(command) ? command.join(" ") : String(command ?? ""),
|
|
408
|
+
exitCode: ok ? result.value.exitCode : undefined,
|
|
409
|
+
spillPath: ok ? result.value.spillPath : undefined,
|
|
410
|
+
output: accumulated ?? "",
|
|
411
|
+
error: ok ? undefined : describeUpstreamError(result?.error),
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export function describeUpstreamError(error) {
|
|
416
|
+
if (!error) return undefined;
|
|
417
|
+
const code = error.code ? `[${error.code}] ` : "";
|
|
418
|
+
const name = error.constructor?.name && error.constructor.name !== "Error" ? `${error.constructor.name}: ` : "";
|
|
419
|
+
return `${code}${name}${truncate(String(error.message ?? error), 300)}`;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
export function truncate(s, n) {
|
|
423
|
+
const str = String(s ?? "");
|
|
424
|
+
return str.length > n ? `${str.slice(0, n)}…` : str;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
export function id(n) {
|
|
428
|
+
return n === undefined || n === null ? undefined : Number(n);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
export function projectConversationView(view) {
|
|
432
|
+
if (!view) return undefined;
|
|
433
|
+
const docs = view.docs ?? {};
|
|
434
|
+
return {
|
|
435
|
+
conversation: view.conversation
|
|
436
|
+
? {
|
|
437
|
+
id: id(view.conversation.id),
|
|
438
|
+
owner: view.conversation.owner
|
|
439
|
+
? {
|
|
440
|
+
kind: view.conversation.owner.kind,
|
|
441
|
+
taskId: id(view.conversation.owner.taskId),
|
|
442
|
+
conversationId: id(view.conversation.owner.conversationId),
|
|
443
|
+
}
|
|
444
|
+
: undefined,
|
|
445
|
+
}
|
|
446
|
+
: undefined,
|
|
447
|
+
entries: projectEntries(view.entries),
|
|
448
|
+
before: id(view.before),
|
|
449
|
+
run: projectLive(docs["pi.live"]),
|
|
450
|
+
usage: projectUsageState(docs["pi.usage"]),
|
|
451
|
+
agent: docs["pi.agent"],
|
|
452
|
+
provider: docs["pi.provider"],
|
|
453
|
+
inbox: docs["pi.inbox"],
|
|
454
|
+
};
|
|
455
|
+
}
|