@njuptlzf/agent-chat-server 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/session.ts CHANGED
@@ -1,688 +1,689 @@
1
- import { randomUUID } from "node:crypto";
2
- import { readFileSync } from "node:fs";
3
- import * as path from "node:path";
4
- import { Type } from "typebox";
5
- import {
6
- createAgentSession,
7
- createMcpExtension,
8
- DefaultResourceLoader,
9
- defineTool,
10
- initTheme,
11
- loadSkillsFromDir,
12
- stripFrontmatter,
13
- ModelRuntime,
14
- SessionManager,
15
- SettingsManager,
16
- type AgentSession,
17
- type ExtensionAPI,
18
- type ExtensionUIContext,
19
- type ExtensionUIDialogOptions,
20
- type FileEntry,
21
- type McpServerConfig,
22
- type Skill,
23
- type Theme,
24
- type ToolDefinition,
25
- } from "@earendil-works/pi-coding-agent";
26
- import type { McpServerDecl } from "@njuptlzf/agent-chat-protocol";
27
- import { toProxySpawn, type McpConfigStore } from "./mcp-config.ts";
28
- import { scopedMemory } from "pi-scoped-memory";
29
- import type { LoadedProduct, ResolvedTier, ToolContext } from "./manifest.ts";
30
- import { agentFor, resolveTier } from "./manifest.ts";
31
- import { applyPersonaOverride, type PersonaConfigStore, type PersonaOverride } from "./persona-config.ts";
32
-
33
- /**
34
- * One shared ModelRuntime per process. Credentials live on the server only and
35
- * are injected from environment variables, never read from a user's home dir.
36
- */
37
- export async function createModelRuntime(dataDir: string, provider: string): Promise<ModelRuntime> {
38
- const runtime = await ModelRuntime.create({
39
- authPath: `${dataDir}/auth.json`,
40
- modelsPath: `${dataDir}/models.json`,
41
- });
42
- const envName = `${provider.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_API_KEY`;
43
- const key = process.env[envName];
44
- if (key) await runtime.setRuntimeApiKey(provider, key);
45
- else console.warn(`[agent-chat] ${envName} is not set; model calls will fail until it is.`);
46
- return runtime;
47
- }
48
-
49
- /**
50
- * Every skill available to one qualification, in declaration order (S1: a qual
51
- * may replace the product's skill dirs, so the slash surface is per-scope).
52
- * Skills are the only source of slash commands, so both the session builder and
53
- * the command list use this.
54
- */
55
- export function loadProductSkills(product: LoadedProduct, qual?: string, persona?: string): Skill[] {
56
- const skills: Skill[] = [];
57
- for (const dir of agentFor(product, qual, persona).skillDirs) {
58
- skills.push(...loadSkillsFromDir({ dir, source: `product:${product.manifest.id}` }).skills);
59
- }
60
- return skills;
61
- }
62
-
63
- /**
64
- * 人格工具白名单:**收窄**,不是替换。
65
- *
66
- * - 未声明 `allowTools` ⇒ 原样返回(老行为零影响);
67
- * - 声明了 ⇒ 只留白名单里的内联工具。**空数组 = 一个都不给**(不是「全给」)。
68
- *
69
- * 这是声明人格与默认助手真正的分界线:prompt 里写「不要答业务问题」说得再好,不如
70
- * `pick_practice` 根本不在工具列表里来得硬。
71
- */
72
- export function filterToolsForPersona<T>(tools: T[], allow: string[] | undefined, disabled?: string[]): T[] {
73
- // 未声明 allowTools 且没有停用项 ⇒ 原样返回(老行为零影响)
74
- if (allow === undefined && (disabled === undefined || disabled.length === 0)) return tools;
75
- if (allow === undefined) {
76
- // 「不限白名单,但停用几个」:按名字减,不认名字的工具保留
77
- const deny = new Set(disabled);
78
- return tools.filter((t) => !deny.has((t as { name?: string }).name ?? ""));
79
- }
80
- const set = new Set(allow);
81
- const deny = new Set(disabled ?? []);
82
- return tools.filter((t) => {
83
- const name = (t as { name?: string }).name ?? "";
84
- return set.has(name) && !deny.has(name);
85
- });
86
- }
87
-
88
- /**
89
- * MCP 侧的同一道闸:把 `allowTools` 翻成 pi 的 per-tool `toolExposure`。
90
- *
91
- * 与已有 exposure **取交集**——管理员在管理页显式关掉的工具,人格白名单也打不开。
92
- * 反过来(人格没写 ⇒ 不动)保证老配置零影响。
93
- */
94
- export function narrowMcpExposure(decl: McpServerDecl, allow: string[] | undefined, disabled?: string[]): McpServerDecl {
95
- const deny = disabled ?? [];
96
- if (allow === undefined && deny.length === 0) return decl;
97
- const prev = decl.toolExposure ?? {};
98
- const out: Record<string, "direct" | "hidden"> = allow === undefined
99
- // 「不限白名单,但停用几个」:默认全开,逐个隐藏(管理员已隐藏的保持隐藏)
100
- ? { "*": "direct", ...prev }
101
- : { "*": "hidden" };
102
- if (allow !== undefined) {
103
- // 默认全隐,再把允许的打开;原本 hidden 的保持 hidden(交集)。
104
- for (const [name, ex] of Object.entries(prev)) if (ex === "hidden") out[name] = "hidden";
105
- for (const name of allow) if (out[name] !== "hidden") out[name] = "direct";
106
- }
107
- // 人格配置的停用项:只能关,不能开(覆盖管理员已打开的那些)。
108
- for (const name of deny) out[name] = "hidden";
109
- return { ...decl, toolExposure: out };
110
- }
111
-
112
- /**
113
- * A slash command as the UI offers it. Bare names, not pi's `/skill:<name>`:
114
- * the picker is ours and the user should not have to know pi's spelling.
115
- */
116
- export interface ProductCommand {
117
- name: string;
118
- description: string;
119
- }
120
-
121
- /**
122
- * Skills that can be typed explicitly. Unlike the system-prompt advertising
123
- * (`createSkillSupport`), this includes `disable-model-invocation` skills: those
124
- * are exactly the ones meant to be invoked by hand.
125
- */
126
- export function buildCommands(skills: Skill[]): ProductCommand[] {
127
- return skills.map((s) => ({ name: s.name, description: s.description }));
128
- }
129
-
130
- /**
131
- * Expand a typed "/name args" into the skill body, so the "/" never reaches the
132
- * model. Anything not starting with "/" passes through untouched; an unknown
133
- * command is an error rather than a silent pass-through, because the UI offers a
134
- * picker and a stray "/" would otherwise be sent to the model as prose.
135
- *
136
- * The skill's own path is deliberately not included (no server filesystem paths
137
- * in prompts), and only the body is sent — the frontmatter is metadata.
138
- */
139
- export function expandCommand(message: string, commands: ProductCommand[], skills: Skill[]): { error: string } | { message: string } {
140
- if (!message.startsWith("/")) return { message };
141
- const match = /^\/([a-z0-9][a-z0-9-]{0,63})(?:\s+([\s\S]*))?$/.exec(message);
142
- const name = match?.[1];
143
- if (!name || !commands.some((c) => c.name === name)) {
144
- return { error: `unknown command "${message.split(/\s/)[0]}"; see GET /api/commands` };
145
- }
146
- const skill = skills.find((s) => s.name === name)!;
147
- const body = stripFrontmatter(readFileSync(skill.filePath, "utf8")).trim();
148
- const args = match![2]?.trim();
149
- return { message: `<skill name="${skill.name}">\n${body}\n</skill>${args ? `\n\n${args}` : ""}` };
150
- }
151
-
152
- /** One extension dialog to forward to the browser (batch 3-4b). Mirrors the `ui_prompt` ChatEvent. */
153
- export interface UIPromptRequest {
154
- id: string;
155
- kind: "select" | "confirm" | "input";
156
- title: string;
157
- message?: string;
158
- options?: string[];
159
- placeholder?: string;
160
- /** pi's dialog `timeout` option, when set: close with defaults after this long. */
161
- timeoutMs?: number;
162
- }
163
-
164
- /** The browser's answer to a `UIPromptRequest` (mirrors POST /api/ui-response). */
165
- export interface UIPromptAnswer {
166
- value?: string;
167
- confirmed?: boolean;
168
- cancelled?: boolean;
169
- }
170
-
171
- export interface CreateProductSessionOptions {
172
- product: LoadedProduct;
173
- modelRuntime: ModelRuntime;
174
- tools: unknown[];
175
- userId: string;
176
- dataDir: string;
177
- /**
178
- * Which tier this run uses (batch 3-1), already resolved against the manifest
179
- * by `resolveTier`. Omit to run the manifest's `agent.model` as-is.
180
- */
181
- tier?: ResolvedTier;
182
- /**
183
- * Qualification this run studies for (id from the manifest's `quals`). It only
184
- * scopes the system prompt — the default persona must not answer for another exam's
185
- * syllabus. Omit or "" for products without qualifications.
186
- */
187
- qual?: string;
188
- /**
189
- * Which assistant persona this session is (). Omit for the product
190
- * product default. It only swaps prompt/skills here; the tool whitelist is
191
- * decided by the caller (the endpoint builds `tools`), because that is where
192
- * the real boundary is.
193
- */
194
- persona?: string;
195
- /**
196
- * 运行时人格配置。**每次建会话读一次**:写完 `invalidate()` 即生效,
197
- * 不用重启;已建好的会话不受影响(prompt 在创建时定死)。
198
- */
199
- personaConfig?: PersonaConfigStore;
200
- /**
201
- * 直接指定覆盖值(试跑):**优先于** `personaConfig` 里的已保存值,
202
- * 让「未保存的草稿」也能真跑一次。传 `{}` = 明确用 manifest 原样(不是"回落")。
203
- */
204
- personaOverride?: PersonaOverride;
205
- /** Restored history entries (header + entries), from the HistoryStore. */
206
- history?: FileEntry[];
207
- /**
208
- * Optional tuning of pi's automatic context compaction, which is enabled by
209
- * default (reserveTokens 16384 / keepRecentTokens 20000). Tests and ops may
210
- * pass smaller thresholds here; omit to keep pi's defaults.
211
- */
212
- compaction?: { reserveTokens?: number; keepRecentTokens?: number };
213
- /**
214
- * Asked before running a tool listed in the manifest's `confirmTools`.
215
- * Resolve true to allow, false to block (the model sees an error result).
216
- */
217
- requestConfirm?: (info: { toolCallId: string; name: string; args: Record<string, unknown> }) => Promise<boolean>;
218
- /**
219
- * An extension called `ctx.ui.select/confirm/input`; forward it to the UI and
220
- * await the answer. Without this the dialogs fail closed immediately
221
- * (confirm -> false, the rest -> undefined), matching pi's own no-UI behavior.
222
- */
223
- requestUI?: (req: UIPromptRequest, signal?: AbortSignal) => Promise<UIPromptAnswer>;
224
- /** An extension called `ctx.ui.notify`; fire-and-forget to the UI. */
225
- onUINotify?: (message: string, level: "info" | "warning" | "error") => void;
226
- /**
227
- * 业务接入配置:data/mcp-config.json 为准,缺省回落 manifest 的 `mcp:` 种子。
228
- */
229
- mcpConfig?: McpConfigStore;
230
- }
231
-
232
- /**
233
- * Skills without a filesystem tool.
234
- *
235
- * pi only advertises skills when `read` or `bash` is enabled, because the model
236
- * normally loads SKILL.md by reading the file. Serving many users we do not want
237
- * any file tool, so we advertise the skills ourselves (name + description, no
238
- * server paths) and expose a `load_skill` tool that resolves a skill by *name*
239
- * from the product's own registry. There is no path argument to abuse.
240
- */
241
- function createSkillSupport(skills: Skill[]): { promptSection: string; tool?: ToolDefinition } {
242
- const visible = skills.filter((s) => !s.disableModelInvocation);
243
- if (visible.length === 0) return { promptSection: "" };
244
-
245
- const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
246
- const promptSection = [
247
- "以下技能提供特定任务的详细做法。任务与某个技能的描述匹配时,先调用 load_skill 工具加载它,再按其中的步骤执行。",
248
- "<available_skills>",
249
- ...visible.map((s) => ` <skill><name>${esc(s.name)}</name><description>${esc(s.description)}</description></skill>`),
250
- "</available_skills>",
251
- ].join("\n");
252
-
253
- const byName = new Map(visible.map((s) => [s.name, s]));
254
- const names = visible.map((s) => s.name);
255
- const tool = defineTool({
256
- name: "load_skill",
257
- label: "加载技能",
258
- description: `按名称加载一个技能的完整说明。可用技能:${names.join("、")}`,
259
- promptSnippet: "load_skill: 按名称加载技能说明",
260
- parameters: Type.Object({
261
- name: Type.String({ description: "技能名称", enum: names } as never),
262
- }),
263
- async execute(_id, params) {
264
- const skill = byName.get(params.name);
265
- if (!skill) {
266
- return { content: [{ type: "text", text: `没有名为 ${params.name} 的技能。可用:${names.join("、")}` }], details: { found: false, name: params.name }, isError: true };
267
- }
268
- const text = stripFrontmatter(readFileSync(skill.filePath, "utf8")).trim();
269
- return { content: [{ type: "text", text }], details: { found: true, name: skill.name } };
270
- },
271
- });
272
- return { promptSection, tool: tool as ToolDefinition };
273
- }
274
-
275
- /**
276
- * Match a tool name against the manifest's `confirmTools` patterns:
277
- * exact name, or a `prefix*` entry matching by prefix.
278
- */
279
- export function needsConfirmation(patterns: string[], toolName: string): boolean {
280
- return patterns.some(
281
- (p) => (p.endsWith("*") ? toolName.startsWith(p.slice(0, -1)) : p === toolName),
282
- );
283
- }
284
-
285
- /**
286
- * Manifest MCP declaration -> pi server config. pi types stay in this file.
287
- * Paths were already resolved against the product dir by loadProduct.
288
- * Exposure defaults to "direct" so tools are declared to the model like the
289
- * product's own tools; "codemode" is rejected at manifest load because this
290
- * session does not load the codemode extension.
291
- *
292
- * identity injection: every stdio server child is spawned per session,
293
- * so the run's (userId, scope) rides in as env the manifest cannot override
294
- * (AC_* keys are applied last). A business MCP server like the product's must know
295
- * whose wrong-book to read — tool arguments come from the model and are not
296
- * an identity; the environment is. AC_DATA_DIR/AC_PRODUCT_DIR give the child
297
- * the repo facts it cannot re-derive (its cwd is the data dir; manifest
298
- * `${VAR}` templates resolve against the HOST process env, so the server must
299
- * never read DATA_DIR itself — the host passes the resolved absolute path).
300
- * HTTP servers get no identity header yet
301
- * (ponytail: no consumer; upgrade path = signed header or per-user URL).
302
- * openapi entries are translated here into a stdio spawn of mcp-openapi-proxy
303
- * (); the AC_* identity env rides along harmlessly (the proxy ignores it).
304
- * Exported for tests.
305
- */
306
- export function toMcpConfig(
307
- id: string,
308
- decl: McpServerDecl,
309
- identity: { userId: string; scope: string; dataDir: string; productDir: string; persona: string },
310
- ): McpServerConfig {
311
- const common = {
312
- exposure: decl.exposure ?? ("direct" as const),
313
- ...(decl.description ? { description: decl.description } : {}),
314
- ...(decl.enabled !== undefined ? { enabled: decl.enabled } : {}),
315
- ...(decl.timeout ? { timeout: decl.timeout } : {}),
316
- // 白名单单层(2A):pi 原生 per-tool exposure,三种接入统一这一层。
317
- ...(decl.toolExposure ? { toolExposure: decl.toolExposure } : {}),
318
- };
319
- const identityEnv = {
320
- AC_USER_ID: identity.userId,
321
- AC_SCOPE: identity.scope,
322
- AC_DATA_DIR: identity.dataDir,
323
- AC_PRODUCT_DIR: identity.productDir,
324
- // 账本按产品(人格)分,MCP 工具要知道"这次会话是哪本账"。
325
- AC_PERSONA: identity.persona,
326
- };
327
- if (decl.type === "openapi" || (decl.type === undefined && decl.openapi && !decl.command && !decl.url)) {
328
- const spawn = toProxySpawn(decl, id);
329
- return {
330
- type: "stdio",
331
- command: spawn.command,
332
- args: spawn.args,
333
- env: { ...spawn.env, ...decl.env, ...identityEnv },
334
- ...common,
335
- };
336
- }
337
- return decl.command
338
- ? {
339
- type: "stdio",
340
- command: decl.command,
341
- args: decl.args,
342
- env: { ...decl.env, ...identityEnv },
343
- cwd: decl.cwd,
344
- ...common,
345
- }
346
- : { type: "http", url: decl.url ?? "", headers: decl.headers, ...common };
347
- }
348
-
349
- /**
350
- * pi's `theme` singleton is terminal-only and not exported from the package root.
351
- * `initTheme()` (idempotent, verified safe without a TTY) installs the default
352
- * theme on this global symbol; read it back. ponytail: the symbol key is pi
353
- * internals — if it ever disappears, the Proxy fallback keeps `theme.fg/bg`
354
- * calls returning plain text, which is all a web client could want anyway.
355
- */
356
- let cachedTheme: Theme | undefined;
357
- function webTheme(): Theme {
358
- if (!cachedTheme) {
359
- initTheme();
360
- const installed = (globalThis as Record<symbol, Theme | undefined>)[
361
- Symbol.for("@earendil-works/pi-coding-agent:theme")
362
- ];
363
- cachedTheme =
364
- installed ??
365
- (new Proxy({} as Record<string, unknown>, {
366
- get: () => (...args: unknown[]) => (typeof args.at(-1) === "string" ? args.at(-1) : ""),
367
- }) as unknown as Theme);
368
- }
369
- return cachedTheme;
370
- }
371
-
372
- /**
373
- * Bridge pi's `ctx.ui.*` to our web UI: the three dialogs are forwarded through
374
- * the SSE stream and resolved by POST /api/ui-response (the server side of
375
- * `requestUI` decides timeouts), everything terminal-only is a no-op. This is
376
- * the same split pi's own RPC mode makes (see dist/modes/rpc/rpc-mode.js).
377
- */
378
- function createExtensionUIContext(opts: CreateProductSessionOptions): ExtensionUIContext {
379
- const ask = async (
380
- kind: UIPromptRequest["kind"],
381
- fields: Omit<UIPromptRequest, "id" | "kind">,
382
- dialog?: ExtensionUIDialogOptions,
383
- ): Promise<UIPromptAnswer> => {
384
- if (!opts.requestUI) return { cancelled: true };
385
- try {
386
- return await opts.requestUI(
387
- { id: randomUUID(), kind, timeoutMs: dialog?.timeout, ...fields },
388
- dialog?.signal,
389
- );
390
- } catch {
391
- return { cancelled: true };
392
- }
393
- };
394
- const noop = () => {};
395
- return {
396
- async select(title, options, dialog) {
397
- const a = await ask("select", { title, options }, dialog);
398
- return a.cancelled ? undefined : a.value;
399
- },
400
- async confirm(title, message, dialog) {
401
- const a = await ask("confirm", { title, message }, dialog);
402
- return !a.cancelled && a.confirmed === true;
403
- },
404
- async input(title, placeholder, dialog) {
405
- const a = await ask("input", { title, placeholder }, dialog);
406
- return a.cancelled ? undefined : a.value;
407
- },
408
- notify: (message, type) => opts.onUINotify?.(message, type ?? "info"),
409
- // Terminal-only affordances: accepted and dropped (no web equivalent yet).
410
- onTerminalInput: () => noop,
411
- setStatus: noop,
412
- setWorkingMessage: noop,
413
- setWorkingVisible: noop,
414
- setWorkingIndicator: noop,
415
- setHiddenThinkingLabel: noop,
416
- setWidget: noop,
417
- setFooter: noop,
418
- setHeader: noop,
419
- setTitle: noop,
420
- pasteToEditor: noop,
421
- setEditorText: noop,
422
- getEditorText: () => "",
423
- editor: async () => undefined,
424
- custom: async () => undefined as never,
425
- addAutocompleteProvider: noop,
426
- setEditorComponent: noop,
427
- getEditorComponent: () => undefined,
428
- get theme() {
429
- return webTheme();
430
- },
431
- getAllThemes: () => [],
432
- getTheme: () => undefined,
433
- setTheme: () => ({ success: false, error: "theme switching is not supported in web mode" }),
434
- getToolsExpanded: () => false,
435
- setToolsExpanded: noop,
436
- };
437
- }
438
-
439
- /**
440
- * 选项那一行(进 system prompt,不进用户消息)。真实会话与「编译预览」共用这一份,
441
- * 否则预览看到的 prompt 会和实际跑的不是同一段。
442
- */
443
- export function qualSectionOf(product: LoadedProduct, qual: string | undefined): string {
444
- const entry = qual ? product.manifest.quals?.find((q) => q.id === qual) : undefined;
445
- if (!entry) return "";
446
- const level = entry.level === "junior" ? "初级" : entry.level === "middle" ? "中级" : "高级";
447
- const tpl = product.manifest.scopePromptTemplate;
448
- if (!tpl) return "";
449
- return tpl
450
- .replaceAll("{label}", String(entry.label ?? ""))
451
- .replaceAll("{level}", level)
452
- .replaceAll("{direction}", typeof entry.direction === "string" && entry.direction ? `,${entry.direction}` : "");
453
- }
454
-
455
- /**
456
- * 编译预览:**不建会话、不连 MCP、不调模型**,只把
457
- * 「这个人格现在会拼成什么」算出来。与 `createProductSession` 共用
458
- * `agentFor` / `applyPersonaOverride` / `loadProductSkills` / `qualSectionOf`,
459
- * 所以它显示的就是真实会话会拿到的 prompt 与技能。
460
- */
461
- export function compileSystemPrompt(
462
- product: LoadedProduct,
463
- qual: string | undefined,
464
- persona: string | undefined,
465
- override?: PersonaOverride,
466
- ): { systemPrompt: string; skills: { name: string; description: string }[]; allowTools?: string[]; disabledTools: string[] } {
467
- const agent = agentFor(product, qual, persona);
468
- const skills = loadProductSkills(product, qual, persona);
469
- const effective = applyPersonaOverride(agent, override);
470
- const extra = [qualSectionOf(product, qual), createSkillSupport(skills).promptSection].filter((s) => s !== "");
471
- return {
472
- systemPrompt: [effective.prompt, ...extra].join("\n\n"),
473
- skills: skills.map((s) => ({ name: s.name, description: s.description })),
474
- allowTools: effective.allowTools,
475
- disabledTools: effective.disabledTools,
476
- };
477
- }
478
-
479
- /**
480
- * Build a pi session locked down for multi-user serving:
481
- * - no built-in tools (no bash / read / write / edit), verified by test
482
- * - only the product's own tools plus manifest-declared MCP tools
483
- * - in-memory settings and history (the host owns persistence)
484
- * - no filesystem discovery of extensions, prompts, themes or context files
485
- */
486
- export async function createProductSession(opts: CreateProductSessionOptions): Promise<AgentSession> {
487
- const { product, modelRuntime } = opts;
488
- // The tier names the provider, model and thinking level; none of the physical ids
489
- // leave the server. :provider 取自解析结果而不是 `agent.model`——一旦
490
- // model-config.json 把某个候选绑到另一个 provider,这里再读 manifest 就会拿错端点。
491
- const resolved = opts.tier ?? resolveTier(product)!;
492
- const provider = resolved.provider;
493
- const modelId = resolved.model;
494
- const thinking = resolved.thinking;
495
-
496
- // Resolved through the runtime so providers declared in models.json work;
497
- // pi-ai's static catalog only knows built-in providers.
498
- const model = modelRuntime.getModel(provider, modelId);
499
- if (!model) throw new Error(`Unknown model ${provider}/${modelId} (is it configured in models.json?)`);
500
-
501
- // 人格/选项解析一次,prompt、技能、工具白名单都用它——三处各算一遍迟早分叉。
502
- const agent = agentFor(product, opts.qual, opts.persona);
503
- const skills = loadProductSkills(product, opts.qual, opts.persona);
504
- // 运行时覆盖:manifest 编译结果之上,只换 prompt、只减工具。
505
- // 读的是**建会话这一刻**的配置——所以改完不重启即生效,老会话不受影响。
506
- const personaId = opts.persona ?? product.defaultPersona;
507
- const override =
508
- opts.personaOverride !== undefined ? opts.personaOverride : opts.personaConfig?.get().personas[personaId];
509
- const effective = applyPersonaOverride(agent, override);
510
- // 工具白名单:声明人格只拿得到 allowTools 里的那几个。
511
- const tools = filterToolsForPersona(opts.tools, effective.allowTools, effective.disabledTools);
512
- const skillSupport = createSkillSupport(skills);
513
-
514
- /**
515
- * 能力面硬边界(补):`allowTools` 不只管内联工具,也要管住**扩展工具**——
516
- * pi 在**注册期**按 `tools` 过滤 extension/custom/builtin(`_refreshToolRegistry`
517
- * → `_isAllowedTool`),比事后 `setActiveTools` 硬:换会话、重连 MCP、重新注册都绕不过。
518
- *
519
- * 两个必须记住的点:
520
- * 1. **`mcp__*` 要显式写进白名单**。不写的话 pi 认为"白名单不含 MCP",MCP 工具只留给
521
- * tool_search(本仓库没装)⇒ 声明人格的账本工具 连声明都没有。
522
- * 真正的 MCP 可见性仍由 `narrowMcpExposure` 按 `toolExposure` 逐个收窄。
523
- * 2. `load_skill` 是"读自己声明的技能"的加载器;有技能却不在白名单里,等于技能废了。
524
- * 只在该人格**真的有技能**时放行。
525
- *
526
- * `disabledTools` 走 `excludeTools`:它在 pi 里是"白名单之后再生效"的 denylist,
527
- * 所以能补上以前"没有白名单的人格停不掉扩展工具"的半边洞。只减,不能加。
528
- */
529
- const toolAllowlist =
530
- effective.allowTools === undefined
531
- ? undefined
532
- : [...effective.allowTools, "mcp__*", ...(skillSupport.tool ? ["load_skill"] : [])];
533
- const toolDenylist = effective.disabledTools.length > 0 ? [...effective.disabledTools] : undefined;
534
-
535
- // MCP servers come from the mcp-config store (data/mcp-config.json, seeded by
536
- // the manifest's `mcp:` block) — operator-controlled, same trust level as the
537
- // inline tools module, never from user input.
538
- const mcpCfg = opts.mcpConfig?.get();
539
- const mcpDecl = mcpCfg?.servers ?? product.manifest.mcp;
540
- const mcpNames = mcpDecl ? Object.keys(mcpDecl) : [];
541
- const mcpExtensions = mcpNames.length > 0
542
- ? [
543
- createMcpExtension({
544
- loadConfig: () => ({
545
- servers: mcpNames.map((name) => ({
546
- name,
547
- config: toMcpConfig(name, narrowMcpExposure(mcpDecl![name]!, effective.allowTools, effective.disabledTools), {
548
- userId: opts.userId,
549
- scope: opts.qual ?? "",
550
- dataDir: opts.dataDir,
551
- productDir: product.dir,
552
- persona: personaId,
553
- }),
554
- source: opts.mcpConfig?.path ?? product.manifestFile,
555
- scope: "project" as const,
556
- })),
557
- autoEnableCodemode: false,
558
- errors: [],
559
- }),
560
- // The server is not interactive: never write config back to disk.
561
- updateConfig: () => {},
562
- logPath: `${opts.dataDir}/mcp.log`,
563
- }),
564
- ]
565
- : [];
566
-
567
- // User confirmation gate: pause before tools the manifest lists in
568
- // `confirmTools` and ask the UI (via opts.requestConfirm) to decide.
569
- const confirmPatterns = product.manifest.confirmTools ?? [];
570
- const confirmExtensions = confirmPatterns.length > 0 && opts.requestConfirm
571
- ? [
572
- (pi: ExtensionAPI) => {
573
- pi.on("tool_call", async (event) => {
574
- if (!needsConfirmation(confirmPatterns, event.toolName)) return undefined;
575
- const allow = await opts.requestConfirm!({
576
- toolCallId: event.toolCallId,
577
- name: event.toolName,
578
- args: event.input,
579
- });
580
- return allow ? undefined : { block: true, reason: "用户拒绝了该操作" };
581
- });
582
- },
583
- ]
584
- : [];
585
-
586
- // scopedMemory (, plan B; vendored copy at 0.2.0): one factory per session,
587
- // pointed at the tenant/scope directory the host computes. The plugin itself only
588
- // knows a directory — no userId/scope inside it, so it stays open-sourceable
589
- // without business knowledge. `qual || "default"` keeps single-track products
590
- // whole. `autoCapture` is host policy: every 10 turns one cheap completion
591
- // distils the tail of the transcript into a remembered point (secret-filtered,
592
- // silent on failure; the same opt-in stays false in the standalone CLI).
593
- const memoryExtensions = product.memoryEnabled
594
- ? [scopedMemory({ dir: path.join(opts.dataDir, "memory", opts.userId, opts.qual || "default"), autoCapture: true })]
595
- : [];
596
-
597
- // pi prints the working directory into the system prompt, so use the per-product
598
- // data dir (empty of source code) rather than the product's source directory.
599
- const cwd = opts.dataDir;
600
- // DefaultResourceLoader with every filesystem discovery channel off: the only
601
- // extension is the manifest-driven MCP factory above, and the system prompt is
602
- // exactly the product's (plus the skill advertising section), never discovered.
603
- // (createAgentSession does not call reload() for a caller-provided loader.)
604
- const settingsManager = SettingsManager.inMemory({
605
- retry: { enabled: true, maxRetries: 2 },
606
- ...(opts.compaction ? { compaction: { enabled: true, ...opts.compaction } } : {}),
607
- });
608
- // The qualification line goes into the system prompt, not the user message, so
609
- // switching qualifications mid-thread still scopes the next answer and the
610
- // browser never has to remember to repeat it. `label` is display text the
611
- // operator wrote; ids alone would be meaningless to the model.
612
- const qualSection = qualSectionOf(product, opts.qual);
613
- const resourceLoader = new DefaultResourceLoader({
614
- cwd,
615
- agentDir: opts.dataDir,
616
- settingsManager,
617
- systemPrompt: effective.prompt,
618
- ...(() => {
619
- const extra = [qualSection, skillSupport.promptSection].filter((s) => s !== "");
620
- return extra.length > 0 ? { appendSystemPrompt: extra } : {};
621
- })(),
622
- // Manifest-declared extensions (operator-reviewed repo code). They load even
623
- // with `noExtensions: true`, which only gates pi's own discovery channels.
624
- ...(product.extensionPaths.length > 0 ? { additionalExtensionPaths: product.extensionPaths } : {}),
625
- extensionFactories: [...mcpExtensions, ...confirmExtensions, ...memoryExtensions],
626
- noExtensions: true,
627
- noSkills: true,
628
- noPromptTemplates: true,
629
- noThemes: true,
630
- noContextFiles: true,
631
- });
632
- await resourceLoader.reload();
633
-
634
- const { session } = await createAgentSession({
635
- cwd,
636
- agentDir: opts.dataDir,
637
- model,
638
- thinkingLevel: thinking,
639
- modelRuntime,
640
- resourceLoader,
641
- // "builtin" drops read/bash/edit/write but keeps customTools; "all" would drop ours too.
642
- noTools: "builtin",
643
- // 能力面白名单/停用(见上面 toolAllowlist 的注释):注册期过滤,扩展工具也管。
644
- ...(toolAllowlist !== undefined ? { tools: toolAllowlist } : {}),
645
- ...(toolDenylist !== undefined ? { excludeTools: toolDenylist } : {}),
646
- // 用过滤后的 `tools`(人格白名单),不是 opts.tools——写错了不会报错,只是白名单静默失效。
647
- customTools: [...(tools as ToolDefinition[]), ...(skillSupport.tool ? [skillSupport.tool] : [])],
648
- sessionManager: SessionManager.inMemory(cwd, undefined, opts.history),
649
- settingsManager,
650
- });
651
- if (mcpExtensions.length > 0 || product.extensionPaths.length > 0) {
652
- // Emits session_start, which is when the MCP extension connects its servers
653
- // (in the background; the first prompt waits for "direct" servers) and when
654
- // manifest-declared extensions run their own startup handlers.
655
- // mode "rpc" is pi's own non-terminal contract: dialogs are data, not TUI
656
- // components — exactly what our SSE bridge below implements.
657
- await session.bindExtensions({ uiContext: createExtensionUIContext(opts), mode: "rpc" });
658
- }
659
- return session;
660
- }
661
-
662
- /**
663
- * Tear down a session created by createProductSession.
664
- *
665
- * AgentSession.dispose() alone never emits "session_shutdown", so extensions —
666
- * notably the MCP extension's stdio child processes — would keep their handles
667
- * open and the process alive. Emit the shutdown event first, then dispose.
668
- */
669
- export async function disposeProductSession(session: AgentSession): Promise<void> {
670
- try {
671
- const runner = session.extensionRunner;
672
- if (runner.hasHandlers("session_shutdown")) {
673
- await runner.emit({ type: "session_shutdown", reason: "quit" });
674
- }
675
- } finally {
676
- session.dispose();
677
- }
678
- }
679
-
680
- /** Snapshot a session's history so it can be saved and restored later. */
681
- export function exportHistory(session: AgentSession): FileEntry[] {
682
- const sm = session.sessionManager;
683
- const header = sm.getHeader();
684
- const entries = sm.getEntries();
685
- return header ? [header, ...entries] : entries;
686
- }
687
-
688
- export type { ToolContext };
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import * as path from "node:path";
4
+ import { Type } from "typebox";
5
+ import {
6
+ createAgentSession,
7
+ createMcpExtension,
8
+ DefaultResourceLoader,
9
+ defineTool,
10
+ initTheme,
11
+ loadSkillsFromDir,
12
+ stripFrontmatter,
13
+ ModelRuntime,
14
+ SessionManager,
15
+ SettingsManager,
16
+ type AgentSession,
17
+ type ExtensionAPI,
18
+ type ExtensionUIContext,
19
+ type ExtensionUIDialogOptions,
20
+ type FileEntry,
21
+ type McpServerConfig,
22
+ type Skill,
23
+ type Theme,
24
+ type ToolDefinition,
25
+ } from "@earendil-works/pi-coding-agent";
26
+ import type { McpServerDecl } from "@njuptlzf/agent-chat-protocol";
27
+ import { toProxySpawn, type McpConfigStore } from "./mcp-config.ts";
28
+ import { scopedMemory } from "pi-scoped-memory";
29
+ import type { LoadedProduct, ResolvedTier, ToolContext } from "./manifest.ts";
30
+ import { agentFor, resolveTier } from "./manifest.ts";
31
+ import { applyPersonaOverride, type PersonaConfigStore, type PersonaOverride } from "./persona-config.ts";
32
+
33
+ /**
34
+ * One shared ModelRuntime per process. Credentials live on the server only and
35
+ * are injected from environment variables, never read from a user's home dir.
36
+ */
37
+ export async function createModelRuntime(dataDir: string, provider: string): Promise<ModelRuntime> {
38
+ const runtime = await ModelRuntime.create({
39
+ authPath: `${dataDir}/auth.json`,
40
+ modelsPath: `${dataDir}/models.json`,
41
+ });
42
+ const envName = `${provider.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_API_KEY`;
43
+ const key = process.env[envName];
44
+ if (key) await runtime.setRuntimeApiKey(provider, key);
45
+ else console.warn(`[agent-chat] ${envName} is not set; model calls will fail until it is.`);
46
+ return runtime;
47
+ }
48
+
49
+ /**
50
+ * Every skill available to one qualification, in declaration order (S1: a qual
51
+ * may replace the product's skill dirs, so the slash surface is per-scope).
52
+ * Skills are the only source of slash commands, so both the session builder and
53
+ * the command list use this.
54
+ */
55
+ export function loadProductSkills(product: LoadedProduct, qual?: string, persona?: string): Skill[] {
56
+ const skills: Skill[] = [];
57
+ for (const dir of agentFor(product, qual, persona).skillDirs) {
58
+ skills.push(...loadSkillsFromDir({ dir, source: `product:${product.manifest.id}` }).skills);
59
+ }
60
+ return skills;
61
+ }
62
+
63
+ /**
64
+ * 人格工具白名单:**收窄**,不是替换。
65
+ *
66
+ * - 未声明 `allowTools` ⇒ 原样返回(老行为零影响);
67
+ * - 声明了 ⇒ 只留白名单里的内联工具。**空数组 = 一个都不给**(不是「全给」)。
68
+ *
69
+ * 这是声明人格与默认助手真正的分界线:prompt 里写「不要答业务问题」说得再好,不如
70
+ * `pick_practice` 根本不在工具列表里来得硬。
71
+ */
72
+ export function filterToolsForPersona<T>(tools: T[], allow: string[] | undefined, disabled?: string[]): T[] {
73
+ // 未声明 allowTools 且没有停用项 ⇒ 原样返回(老行为零影响)
74
+ if (allow === undefined && (disabled === undefined || disabled.length === 0)) return tools;
75
+ if (allow === undefined) {
76
+ // 「不限白名单,但停用几个」:按名字减,不认名字的工具保留
77
+ const deny = new Set(disabled);
78
+ return tools.filter((t) => !deny.has((t as { name?: string }).name ?? ""));
79
+ }
80
+ const set = new Set(allow);
81
+ const deny = new Set(disabled ?? []);
82
+ return tools.filter((t) => {
83
+ const name = (t as { name?: string }).name ?? "";
84
+ return set.has(name) && !deny.has(name);
85
+ });
86
+ }
87
+
88
+ /**
89
+ * MCP 侧的同一道闸:把 `allowTools` 翻成 pi 的 per-tool `toolExposure`。
90
+ *
91
+ * 与已有 exposure **取交集**——管理员在管理页显式关掉的工具,人格白名单也打不开。
92
+ * 反过来(人格没写 ⇒ 不动)保证老配置零影响。
93
+ */
94
+ export function narrowMcpExposure(decl: McpServerDecl, allow: string[] | undefined, disabled?: string[]): McpServerDecl {
95
+ const deny = disabled ?? [];
96
+ if (allow === undefined && deny.length === 0) return decl;
97
+ const prev = decl.toolExposure ?? {};
98
+ const out: Record<string, "direct" | "hidden"> = allow === undefined
99
+ // 「不限白名单,但停用几个」:默认全开,逐个隐藏(管理员已隐藏的保持隐藏)
100
+ ? { "*": "direct", ...prev }
101
+ : { "*": "hidden" };
102
+ if (allow !== undefined) {
103
+ // 默认全隐,再把允许的打开;原本 hidden 的保持 hidden(交集)。
104
+ for (const [name, ex] of Object.entries(prev)) if (ex === "hidden") out[name] = "hidden";
105
+ for (const name of allow) if (out[name] !== "hidden") out[name] = "direct";
106
+ }
107
+ // 人格配置的停用项:只能关,不能开(覆盖管理员已打开的那些)。
108
+ for (const name of deny) out[name] = "hidden";
109
+ return { ...decl, toolExposure: out };
110
+ }
111
+
112
+ /**
113
+ * A slash command as the UI offers it. Bare names, not pi's `/skill:<name>`:
114
+ * the picker is ours and the user should not have to know pi's spelling.
115
+ */
116
+ export interface ProductCommand {
117
+ name: string;
118
+ description: string;
119
+ }
120
+
121
+ /**
122
+ * Skills that can be typed explicitly. Unlike the system-prompt advertising
123
+ * (`createSkillSupport`), this includes `disable-model-invocation` skills: those
124
+ * are exactly the ones meant to be invoked by hand.
125
+ */
126
+ export function buildCommands(skills: Skill[]): ProductCommand[] {
127
+ return skills.map((s) => ({ name: s.name, description: s.description }));
128
+ }
129
+
130
+ /**
131
+ * Expand a typed "/name args" into the skill body, so the "/" never reaches the
132
+ * model. Anything not starting with "/" passes through untouched; an unknown
133
+ * command is an error rather than a silent pass-through, because the UI offers a
134
+ * picker and a stray "/" would otherwise be sent to the model as prose.
135
+ *
136
+ * The skill's own path is deliberately not included (no server filesystem paths
137
+ * in prompts), and only the body is sent — the frontmatter is metadata.
138
+ */
139
+ export function expandCommand(message: string, commands: ProductCommand[], skills: Skill[]): { error: string } | { message: string } {
140
+ if (!message.startsWith("/")) return { message };
141
+ const match = /^\/([a-z0-9][a-z0-9-]{0,63})(?:\s+([\s\S]*))?$/.exec(message);
142
+ const name = match?.[1];
143
+ if (!name || !commands.some((c) => c.name === name)) {
144
+ return { error: `unknown command "${message.split(/\s/)[0]}"; see GET /api/commands` };
145
+ }
146
+ const skill = skills.find((s) => s.name === name)!;
147
+ const body = stripFrontmatter(readFileSync(skill.filePath, "utf8")).trim();
148
+ const args = match![2]?.trim();
149
+ return { message: `<skill name="${skill.name}">\n${body}\n</skill>${args ? `\n\n${args}` : ""}` };
150
+ }
151
+
152
+ /** One extension dialog to forward to the browser (batch 3-4b). Mirrors the `ui_prompt` ChatEvent. */
153
+ export interface UIPromptRequest {
154
+ id: string;
155
+ kind: "select" | "confirm" | "input";
156
+ title: string;
157
+ message?: string;
158
+ options?: string[];
159
+ placeholder?: string;
160
+ /** pi's dialog `timeout` option, when set: close with defaults after this long. */
161
+ timeoutMs?: number;
162
+ }
163
+
164
+ /** The browser's answer to a `UIPromptRequest` (mirrors POST /api/ui-response). */
165
+ export interface UIPromptAnswer {
166
+ value?: string;
167
+ confirmed?: boolean;
168
+ cancelled?: boolean;
169
+ }
170
+
171
+ export interface CreateProductSessionOptions {
172
+ product: LoadedProduct;
173
+ modelRuntime: ModelRuntime;
174
+ tools: unknown[];
175
+ userId: string;
176
+ dataDir: string;
177
+ /**
178
+ * Which tier this run uses (batch 3-1), already resolved against the manifest
179
+ * by `resolveTier`. Omit to run the manifest's `agent.model` as-is.
180
+ */
181
+ tier?: ResolvedTier;
182
+ /**
183
+ * Qualification this run studies for (id from the manifest's `quals`). It only
184
+ * scopes the system prompt — the default persona must not answer for another exam's
185
+ * syllabus. Omit or "" for products without qualifications.
186
+ */
187
+ qual?: string;
188
+ /**
189
+ * Which assistant persona this session is (). Omit for the product
190
+ * product default. It only swaps prompt/skills here; the tool whitelist is
191
+ * decided by the caller (the endpoint builds `tools`), because that is where
192
+ * the real boundary is.
193
+ */
194
+ persona?: string;
195
+ /**
196
+ * 运行时人格配置。**每次建会话读一次**:写完 `invalidate()` 即生效,
197
+ * 不用重启;已建好的会话不受影响(prompt 在创建时定死)。
198
+ */
199
+ personaConfig?: PersonaConfigStore;
200
+ /**
201
+ * 直接指定覆盖值(试跑):**优先于** `personaConfig` 里的已保存值,
202
+ * 让「未保存的草稿」也能真跑一次。传 `{}` = 明确用 manifest 原样(不是"回落")。
203
+ */
204
+ personaOverride?: PersonaOverride;
205
+ /** Restored history entries (header + entries), from the HistoryStore. */
206
+ history?: FileEntry[];
207
+ /**
208
+ * Optional tuning of pi's automatic context compaction, which is enabled by
209
+ * default (reserveTokens 16384 / keepRecentTokens 20000). Tests and ops may
210
+ * pass smaller thresholds here; omit to keep pi's defaults.
211
+ */
212
+ compaction?: { reserveTokens?: number; keepRecentTokens?: number };
213
+ /**
214
+ * Asked before running a tool listed in the manifest's `confirmTools`.
215
+ * Resolve true to allow, false to block (the model sees an error result).
216
+ */
217
+ requestConfirm?: (info: { toolCallId: string; name: string; args: Record<string, unknown> }) => Promise<boolean>;
218
+ /**
219
+ * An extension called `ctx.ui.select/confirm/input`; forward it to the UI and
220
+ * await the answer. Without this the dialogs fail closed immediately
221
+ * (confirm -> false, the rest -> undefined), matching pi's own no-UI behavior.
222
+ */
223
+ requestUI?: (req: UIPromptRequest, signal?: AbortSignal) => Promise<UIPromptAnswer>;
224
+ /** An extension called `ctx.ui.notify`; fire-and-forget to the UI. */
225
+ onUINotify?: (message: string, level: "info" | "warning" | "error") => void;
226
+ /**
227
+ * 业务接入配置:data/mcp-config.json 为准,缺省回落 manifest 的 `mcp:` 种子。
228
+ */
229
+ mcpConfig?: McpConfigStore;
230
+ }
231
+
232
+ /**
233
+ * Skills without a filesystem tool.
234
+ *
235
+ * pi only advertises skills when `read` or `bash` is enabled, because the model
236
+ * normally loads SKILL.md by reading the file. Serving many users we do not want
237
+ * any file tool, so we advertise the skills ourselves (name + description, no
238
+ * server paths) and expose a `load_skill` tool that resolves a skill by *name*
239
+ * from the product's own registry. There is no path argument to abuse.
240
+ */
241
+ function createSkillSupport(skills: Skill[]): { promptSection: string; tool?: ToolDefinition } {
242
+ const visible = skills.filter((s) => !s.disableModelInvocation);
243
+ if (visible.length === 0) return { promptSection: "" };
244
+
245
+ const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
246
+ const promptSection = [
247
+ "以下技能提供特定任务的详细做法。任务与某个技能的描述匹配时,先调用 load_skill 工具加载它,再按其中的步骤执行。",
248
+ "<available_skills>",
249
+ ...visible.map((s) => ` <skill><name>${esc(s.name)}</name><description>${esc(s.description)}</description></skill>`),
250
+ "</available_skills>",
251
+ ].join("\n");
252
+
253
+ const byName = new Map(visible.map((s) => [s.name, s]));
254
+ const names = visible.map((s) => s.name);
255
+ const tool = defineTool({
256
+ name: "load_skill",
257
+ label: "加载技能",
258
+ description: `按名称加载一个技能的完整说明。可用技能:${names.join("、")}`,
259
+ promptSnippet: "load_skill: 按名称加载技能说明",
260
+ parameters: Type.Object({
261
+ name: Type.String({ description: "技能名称", enum: names } as never),
262
+ }),
263
+ async execute(_id, params) {
264
+ const skill = byName.get(params.name);
265
+ if (!skill) {
266
+ return { content: [{ type: "text", text: `没有名为 ${params.name} 的技能。可用:${names.join("、")}` }], details: { found: false, name: params.name }, isError: true };
267
+ }
268
+ const text = stripFrontmatter(readFileSync(skill.filePath, "utf8")).trim();
269
+ return { content: [{ type: "text", text }], details: { found: true, name: skill.name } };
270
+ },
271
+ });
272
+ return { promptSection, tool: tool as ToolDefinition };
273
+ }
274
+
275
+ /**
276
+ * Match a tool name against the manifest's `confirmTools` patterns:
277
+ * exact name, or a `prefix*` entry matching by prefix.
278
+ */
279
+ export function needsConfirmation(patterns: string[], toolName: string): boolean {
280
+ return patterns.some(
281
+ (p) => (p.endsWith("*") ? toolName.startsWith(p.slice(0, -1)) : p === toolName),
282
+ );
283
+ }
284
+
285
+ /**
286
+ * Manifest MCP declaration -> pi server config. pi types stay in this file.
287
+ * Paths were already resolved against the product dir by loadProduct.
288
+ * Exposure defaults to "direct" so tools are declared to the model like the
289
+ * product's own tools; "codemode" is rejected at manifest load because this
290
+ * session does not load the codemode extension.
291
+ *
292
+ * identity injection: every stdio server child is spawned per session,
293
+ * so the run's (userId, scope) rides in as env the manifest cannot override
294
+ * (AC_* keys are applied last). A business MCP server like the product's must know
295
+ * whose wrong-book to read — tool arguments come from the model and are not
296
+ * an identity; the environment is. AC_DATA_DIR/AC_PRODUCT_DIR give the child
297
+ * the repo facts it cannot re-derive (its cwd is the data dir; manifest
298
+ * `${VAR}` templates resolve against the HOST process env, so the server must
299
+ * never read DATA_DIR itself — the host passes the resolved absolute path).
300
+ * HTTP servers get no identity header yet
301
+ * (ponytail: no consumer; upgrade path = signed header or per-user URL).
302
+ * openapi entries are translated here into a stdio spawn of mcp-openapi-proxy
303
+ * (); the AC_* identity env rides along harmlessly (the proxy ignores it).
304
+ * Exported for tests.
305
+ */
306
+ export function toMcpConfig(
307
+ id: string,
308
+ decl: McpServerDecl,
309
+ identity: { userId: string; scope: string; dataDir: string; productDir: string; persona: string },
310
+ ): McpServerConfig {
311
+ const common = {
312
+ exposure: decl.exposure ?? ("direct" as const),
313
+ ...(decl.description ? { description: decl.description } : {}),
314
+ ...(decl.enabled !== undefined ? { enabled: decl.enabled } : {}),
315
+ ...(decl.timeout ? { timeout: decl.timeout } : {}),
316
+ // 白名单单层(2A):pi 原生 per-tool exposure,三种接入统一这一层。
317
+ ...(decl.toolExposure ? { toolExposure: decl.toolExposure } : {}),
318
+ };
319
+ const identityEnv = {
320
+ AC_USER_ID: identity.userId,
321
+ AC_SCOPE: identity.scope,
322
+ AC_DATA_DIR: identity.dataDir,
323
+ AC_PRODUCT_DIR: identity.productDir,
324
+ // 账本按产品(人格)分,MCP 工具要知道"这次会话是哪本账"。
325
+ AC_PERSONA: identity.persona,
326
+ };
327
+ if (decl.type === "openapi" || (decl.type === undefined && decl.openapi && !decl.command && !decl.url)) {
328
+ const spawn = toProxySpawn(decl, id);
329
+ return {
330
+ type: "stdio",
331
+ command: spawn.command,
332
+ args: spawn.args,
333
+ env: { ...spawn.env, ...decl.env, ...identityEnv },
334
+ ...common,
335
+ };
336
+ }
337
+ return decl.command
338
+ ? {
339
+ type: "stdio",
340
+ command: decl.command,
341
+ args: decl.args,
342
+ env: { ...decl.env, ...identityEnv },
343
+ cwd: decl.cwd,
344
+ ...common,
345
+ }
346
+ : { type: "http", url: decl.url ?? "", headers: decl.headers, ...common };
347
+ }
348
+
349
+ /**
350
+ * pi's `theme` singleton is terminal-only and not exported from the package root.
351
+ * `initTheme()` (idempotent, verified safe without a TTY) installs the default
352
+ * theme on this global symbol; read it back. ponytail: the symbol key is pi
353
+ * internals — if it ever disappears, the Proxy fallback keeps `theme.fg/bg`
354
+ * calls returning plain text, which is all a web client could want anyway.
355
+ */
356
+ let cachedTheme: Theme | undefined;
357
+ function webTheme(): Theme {
358
+ if (!cachedTheme) {
359
+ initTheme();
360
+ const installed = (globalThis as Record<symbol, Theme | undefined>)[
361
+ Symbol.for("@earendil-works/pi-coding-agent:theme")
362
+ ];
363
+ cachedTheme =
364
+ installed ??
365
+ (new Proxy({} as Record<string, unknown>, {
366
+ get: () => (...args: unknown[]) => (typeof args.at(-1) === "string" ? args.at(-1) : ""),
367
+ }) as unknown as Theme);
368
+ }
369
+ return cachedTheme;
370
+ }
371
+
372
+ /**
373
+ * Bridge pi's `ctx.ui.*` to our web UI: the three dialogs are forwarded through
374
+ * the SSE stream and resolved by POST /api/ui-response (the server side of
375
+ * `requestUI` decides timeouts), everything terminal-only is a no-op. This is
376
+ * the same split pi's own RPC mode makes (see dist/modes/rpc/rpc-mode.js).
377
+ */
378
+ function createExtensionUIContext(opts: CreateProductSessionOptions): ExtensionUIContext {
379
+ const ask = async (
380
+ kind: UIPromptRequest["kind"],
381
+ fields: Omit<UIPromptRequest, "id" | "kind">,
382
+ dialog?: ExtensionUIDialogOptions,
383
+ ): Promise<UIPromptAnswer> => {
384
+ if (!opts.requestUI) return { cancelled: true };
385
+ try {
386
+ return await opts.requestUI(
387
+ { id: randomUUID(), kind, timeoutMs: dialog?.timeout, ...fields },
388
+ dialog?.signal,
389
+ );
390
+ } catch {
391
+ return { cancelled: true };
392
+ }
393
+ };
394
+ const noop = () => {};
395
+ return {
396
+ async select(title, options, dialog) {
397
+ const a = await ask("select", { title, options }, dialog);
398
+ return a.cancelled ? undefined : a.value;
399
+ },
400
+ async confirm(title, message, dialog) {
401
+ const a = await ask("confirm", { title, message }, dialog);
402
+ return !a.cancelled && a.confirmed === true;
403
+ },
404
+ async input(title, placeholder, dialog) {
405
+ const a = await ask("input", { title, placeholder }, dialog);
406
+ return a.cancelled ? undefined : a.value;
407
+ },
408
+ notify: (message, type) => opts.onUINotify?.(message, type ?? "info"),
409
+ // Terminal-only affordances: accepted and dropped (no web equivalent yet).
410
+ onTerminalInput: () => noop,
411
+ setStatus: noop,
412
+ setWorkingMessage: noop,
413
+ setWorkingVisible: noop,
414
+ setWorkingIndicator: noop,
415
+ setHiddenThinkingLabel: noop,
416
+ setWidget: noop,
417
+ setFooter: noop,
418
+ setHeader: noop,
419
+ setTitle: noop,
420
+ pasteToEditor: noop,
421
+ setEditorText: noop,
422
+ getEditorText: () => "",
423
+ editor: async () => undefined,
424
+ custom: async () => undefined as never,
425
+ addAutocompleteProvider: noop,
426
+ setEditorComponent: noop,
427
+ getEditorComponent: () => undefined,
428
+ get theme() {
429
+ return webTheme();
430
+ },
431
+ getAllThemes: () => [],
432
+ getTheme: () => undefined,
433
+ setTheme: () => ({ success: false, error: "theme switching is not supported in web mode" }),
434
+ getToolsExpanded: () => false,
435
+ setToolsExpanded: noop,
436
+ };
437
+ }
438
+
439
+ /**
440
+ * 选项那一行(进 system prompt,不进用户消息)。真实会话与「编译预览」共用这一份,
441
+ * 否则预览看到的 prompt 会和实际跑的不是同一段。
442
+ */
443
+ export function qualSectionOf(product: LoadedProduct, qual: string | undefined): string {
444
+ const entry = qual ? product.manifest.quals?.find((q) => q.id === qual) : undefined;
445
+ if (!entry) return "";
446
+ const level = entry.level === "junior" ? "初级" : entry.level === "middle" ? "中级" : "高级";
447
+ const tpl = product.manifest.scopePromptTemplate;
448
+ if (!tpl) return "";
449
+ return tpl
450
+ .replaceAll("{label}", String(entry.label ?? ""))
451
+ .replaceAll("{level}", level)
452
+ .replaceAll("{direction}", typeof entry.direction === "string" && entry.direction ? `,${entry.direction}` : "");
453
+ }
454
+
455
+ /**
456
+ * 编译预览:**不建会话、不连 MCP、不调模型**,只把
457
+ * 「这个人格现在会拼成什么」算出来。与 `createProductSession` 共用
458
+ * `agentFor` / `applyPersonaOverride` / `loadProductSkills` / `qualSectionOf`,
459
+ * 所以它显示的就是真实会话会拿到的 prompt 与技能。
460
+ */
461
+ export function compileSystemPrompt(
462
+ product: LoadedProduct,
463
+ qual: string | undefined,
464
+ persona: string | undefined,
465
+ override?: PersonaOverride,
466
+ ): { systemPrompt: string; skills: { name: string; description: string }[]; allowTools?: string[]; disabledTools: string[] } {
467
+ const agent = agentFor(product, qual, persona);
468
+ const skills = loadProductSkills(product, qual, persona);
469
+ const effective = applyPersonaOverride(agent, override);
470
+ const extra = [qualSectionOf(product, qual), createSkillSupport(skills).promptSection].filter((s) => s !== "");
471
+ return {
472
+ systemPrompt: [effective.prompt, ...extra].join("\n\n"),
473
+ skills: skills.map((s) => ({ name: s.name, description: s.description })),
474
+ allowTools: effective.allowTools,
475
+ disabledTools: effective.disabledTools,
476
+ };
477
+ }
478
+
479
+ /**
480
+ * Build a pi session locked down for multi-user serving:
481
+ * - no built-in tools (no bash / read / write / edit), verified by test
482
+ * - only the product's own tools plus manifest-declared MCP tools
483
+ * - in-memory settings and history (the host owns persistence)
484
+ * - no filesystem discovery of extensions, prompts, themes or context files
485
+ */
486
+ export async function createProductSession(opts: CreateProductSessionOptions): Promise<AgentSession> {
487
+ const { product, modelRuntime } = opts;
488
+ // The tier names the provider, model and thinking level; none of the physical ids
489
+ // leave the server. :provider 取自解析结果而不是 `agent.model`——一旦
490
+ // model-config.json 把某个候选绑到另一个 provider,这里再读 manifest 就会拿错端点。
491
+ const resolved = opts.tier ?? resolveTier(product)!;
492
+ const provider = resolved.provider;
493
+ const modelId = resolved.model;
494
+ const thinking = resolved.thinking;
495
+
496
+ // Resolved through the runtime so providers declared in models.json work;
497
+ // pi-ai's static catalog only knows built-in providers.
498
+ const model = modelRuntime.getModel(provider, modelId);
499
+ if (!model) throw new Error(`Unknown model ${provider}/${modelId} (is it configured in models.json?)`);
500
+
501
+ // 人格/选项解析一次,prompt、技能、工具白名单都用它——三处各算一遍迟早分叉。
502
+ const agent = agentFor(product, opts.qual, opts.persona);
503
+ const skills = loadProductSkills(product, opts.qual, opts.persona);
504
+ // 运行时覆盖:manifest 编译结果之上,只换 prompt、只减工具。
505
+ // 读的是**建会话这一刻**的配置——所以改完不重启即生效,老会话不受影响。
506
+ const personaId = opts.persona ?? product.defaultPersona;
507
+ const override =
508
+ opts.personaOverride !== undefined ? opts.personaOverride : opts.personaConfig?.get().personas[personaId];
509
+ const effective = applyPersonaOverride(agent, override);
510
+ // 工具白名单:声明人格只拿得到 allowTools 里的那几个。
511
+ const tools = filterToolsForPersona(opts.tools, effective.allowTools, effective.disabledTools);
512
+ const skillSupport = createSkillSupport(skills);
513
+
514
+ /**
515
+ * 能力面硬边界(补):`allowTools` 不只管内联工具,也要管住**扩展工具**——
516
+ * pi 在**注册期**按 `tools` 过滤 extension/custom/builtin(`_refreshToolRegistry`
517
+ * → `_isAllowedTool`),比事后 `setActiveTools` 硬:换会话、重连 MCP、重新注册都绕不过。
518
+ *
519
+ * 两个必须记住的点:
520
+ * 1. **`mcp__*` 要显式写进白名单**。不写的话 pi 认为"白名单不含 MCP",MCP 工具只留给
521
+ * tool_search(本仓库没装)⇒ 声明人格的账本工具 连声明都没有。
522
+ * 真正的 MCP 可见性仍由 `narrowMcpExposure` 按 `toolExposure` 逐个收窄。
523
+ * 2. `load_skill` 是"读自己声明的技能"的加载器;有技能却不在白名单里,等于技能废了。
524
+ * 只在该人格**真的有技能**时放行。
525
+ *
526
+ * `disabledTools` 走 `excludeTools`:它在 pi 里是"白名单之后再生效"的 denylist,
527
+ * 所以能补上以前"没有白名单的人格停不掉扩展工具"的半边洞。只减,不能加。
528
+ */
529
+ const toolAllowlist =
530
+ effective.allowTools === undefined
531
+ ? undefined
532
+ : [...effective.allowTools, "mcp__*", ...(skillSupport.tool ? ["load_skill"] : [])];
533
+ const toolDenylist = effective.disabledTools.length > 0 ? [...effective.disabledTools] : undefined;
534
+
535
+ // MCP servers come from the mcp-config store (data/mcp-config.json, seeded by
536
+ // the manifest's `mcp:` block) — operator-controlled, same trust level as the
537
+ // inline tools module, never from user input.
538
+ const mcpCfg = opts.mcpConfig?.get();
539
+ const mcpDecl = mcpCfg?.servers ?? product.manifest.mcp;
540
+ const mcpNames = mcpDecl ? Object.keys(mcpDecl) : [];
541
+ const mcpExtensions = mcpNames.length > 0
542
+ ? [
543
+ createMcpExtension({
544
+ loadConfig: () => ({
545
+ servers: mcpNames.map((name) => ({
546
+ name,
547
+ config: toMcpConfig(name, narrowMcpExposure(mcpDecl![name]!, effective.allowTools, effective.disabledTools), {
548
+ userId: opts.userId,
549
+ scope: opts.qual ?? "",
550
+ dataDir: opts.dataDir,
551
+ productDir: product.dir,
552
+ persona: personaId,
553
+ }),
554
+ source: opts.mcpConfig?.path ?? product.manifestFile,
555
+ scope: "project" as const,
556
+ })),
557
+ autoEnableCodemode: false,
558
+ errors: [],
559
+ }),
560
+ // The server is not interactive: never write config back to disk.
561
+ updateConfig: () => {},
562
+ logPath: `${opts.dataDir}/mcp.log`,
563
+ }),
564
+ ]
565
+ : [];
566
+
567
+ // User confirmation gate: pause before tools the manifest lists in
568
+ // `confirmTools` and ask the UI (via opts.requestConfirm) to decide.
569
+ const confirmPatterns = product.manifest.confirmTools ?? [];
570
+ const confirmExtensions = confirmPatterns.length > 0 && opts.requestConfirm
571
+ ? [
572
+ (pi: ExtensionAPI) => {
573
+ pi.on("tool_call", async (event) => {
574
+ if (!needsConfirmation(confirmPatterns, event.toolName)) return undefined;
575
+ const allow = await opts.requestConfirm!({
576
+ toolCallId: event.toolCallId,
577
+ name: event.toolName,
578
+ args: event.input,
579
+ });
580
+ return allow ? undefined : { block: true, reason: "用户拒绝了该操作" };
581
+ });
582
+ },
583
+ ]
584
+ : [];
585
+
586
+ // scopedMemory (plan B; npm 版本消费,正本在 github.com/njuptlzf/pi-scoped-memory):
587
+ // one factory per session,
588
+ // pointed at the tenant/scope directory the host computes. The plugin itself only
589
+ // knows a directory — no userId/scope inside it, so it stays open-sourceable
590
+ // without business knowledge. `qual || "default"` keeps single-track products
591
+ // whole. `autoCapture` is host policy: every 10 turns one cheap completion
592
+ // distils the tail of the transcript into a remembered point (secret-filtered,
593
+ // silent on failure; the same opt-in stays false in the standalone CLI).
594
+ const memoryExtensions = product.memoryEnabled
595
+ ? [scopedMemory({ dir: path.join(opts.dataDir, "memory", opts.userId, opts.qual || "default"), autoCapture: true })]
596
+ : [];
597
+
598
+ // pi prints the working directory into the system prompt, so use the per-product
599
+ // data dir (empty of source code) rather than the product's source directory.
600
+ const cwd = opts.dataDir;
601
+ // DefaultResourceLoader with every filesystem discovery channel off: the only
602
+ // extension is the manifest-driven MCP factory above, and the system prompt is
603
+ // exactly the product's (plus the skill advertising section), never discovered.
604
+ // (createAgentSession does not call reload() for a caller-provided loader.)
605
+ const settingsManager = SettingsManager.inMemory({
606
+ retry: { enabled: true, maxRetries: 2 },
607
+ ...(opts.compaction ? { compaction: { enabled: true, ...opts.compaction } } : {}),
608
+ });
609
+ // The qualification line goes into the system prompt, not the user message, so
610
+ // switching qualifications mid-thread still scopes the next answer and the
611
+ // browser never has to remember to repeat it. `label` is display text the
612
+ // operator wrote; ids alone would be meaningless to the model.
613
+ const qualSection = qualSectionOf(product, opts.qual);
614
+ const resourceLoader = new DefaultResourceLoader({
615
+ cwd,
616
+ agentDir: opts.dataDir,
617
+ settingsManager,
618
+ systemPrompt: effective.prompt,
619
+ ...(() => {
620
+ const extra = [qualSection, skillSupport.promptSection].filter((s) => s !== "");
621
+ return extra.length > 0 ? { appendSystemPrompt: extra } : {};
622
+ })(),
623
+ // Manifest-declared extensions (operator-reviewed repo code). They load even
624
+ // with `noExtensions: true`, which only gates pi's own discovery channels.
625
+ ...(product.extensionPaths.length > 0 ? { additionalExtensionPaths: product.extensionPaths } : {}),
626
+ extensionFactories: [...mcpExtensions, ...confirmExtensions, ...memoryExtensions],
627
+ noExtensions: true,
628
+ noSkills: true,
629
+ noPromptTemplates: true,
630
+ noThemes: true,
631
+ noContextFiles: true,
632
+ });
633
+ await resourceLoader.reload();
634
+
635
+ const { session } = await createAgentSession({
636
+ cwd,
637
+ agentDir: opts.dataDir,
638
+ model,
639
+ thinkingLevel: thinking,
640
+ modelRuntime,
641
+ resourceLoader,
642
+ // "builtin" drops read/bash/edit/write but keeps customTools; "all" would drop ours too.
643
+ noTools: "builtin",
644
+ // 能力面白名单/停用(见上面 toolAllowlist 的注释):注册期过滤,扩展工具也管。
645
+ ...(toolAllowlist !== undefined ? { tools: toolAllowlist } : {}),
646
+ ...(toolDenylist !== undefined ? { excludeTools: toolDenylist } : {}),
647
+ // 用过滤后的 `tools`(人格白名单),不是 opts.tools——写错了不会报错,只是白名单静默失效。
648
+ customTools: [...(tools as ToolDefinition[]), ...(skillSupport.tool ? [skillSupport.tool] : [])],
649
+ sessionManager: SessionManager.inMemory(cwd, undefined, opts.history),
650
+ settingsManager,
651
+ });
652
+ if (mcpExtensions.length > 0 || product.extensionPaths.length > 0) {
653
+ // Emits session_start, which is when the MCP extension connects its servers
654
+ // (in the background; the first prompt waits for "direct" servers) and when
655
+ // manifest-declared extensions run their own startup handlers.
656
+ // mode "rpc" is pi's own non-terminal contract: dialogs are data, not TUI
657
+ // components — exactly what our SSE bridge below implements.
658
+ await session.bindExtensions({ uiContext: createExtensionUIContext(opts), mode: "rpc" });
659
+ }
660
+ return session;
661
+ }
662
+
663
+ /**
664
+ * Tear down a session created by createProductSession.
665
+ *
666
+ * AgentSession.dispose() alone never emits "session_shutdown", so extensions —
667
+ * notably the MCP extension's stdio child processes — would keep their handles
668
+ * open and the process alive. Emit the shutdown event first, then dispose.
669
+ */
670
+ export async function disposeProductSession(session: AgentSession): Promise<void> {
671
+ try {
672
+ const runner = session.extensionRunner;
673
+ if (runner.hasHandlers("session_shutdown")) {
674
+ await runner.emit({ type: "session_shutdown", reason: "quit" });
675
+ }
676
+ } finally {
677
+ session.dispose();
678
+ }
679
+ }
680
+
681
+ /** Snapshot a session's history so it can be saved and restored later. */
682
+ export function exportHistory(session: AgentSession): FileEntry[] {
683
+ const sm = session.sessionManager;
684
+ const header = sm.getHeader();
685
+ const entries = sm.getEntries();
686
+ return header ? [header, ...entries] : entries;
687
+ }
688
+
689
+ export type { ToolContext };