@njuptlzf/agent-chat-server 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/audit.d.ts +54 -0
  2. package/dist/audit.js +133 -0
  3. package/dist/authz.d.ts +134 -0
  4. package/dist/authz.js +238 -0
  5. package/dist/events.d.ts +33 -0
  6. package/dist/events.js +169 -0
  7. package/dist/index.d.ts +16 -0
  8. package/dist/index.js +4 -0
  9. package/dist/main.d.ts +1 -0
  10. package/dist/main.js +126 -0
  11. package/dist/manifest.d.ts +147 -0
  12. package/dist/manifest.js +491 -0
  13. package/dist/mcp-config.d.ts +87 -0
  14. package/dist/mcp-config.js +353 -0
  15. package/dist/model-config.d.ts +123 -0
  16. package/dist/model-config.js +371 -0
  17. package/dist/model-failover.d.ts +42 -0
  18. package/dist/model-failover.js +82 -0
  19. package/dist/models-api.d.ts +98 -0
  20. package/dist/models-api.js +326 -0
  21. package/dist/persona-config.d.ts +112 -0
  22. package/dist/persona-config.js +368 -0
  23. package/dist/persona-trial.d.ts +50 -0
  24. package/dist/persona-trial.js +77 -0
  25. package/dist/product-routes.d.ts +35 -0
  26. package/dist/product-routes.js +92 -0
  27. package/dist/server.d.ts +162 -0
  28. package/dist/server.js +2572 -0
  29. package/dist/session.d.ts +218 -0
  30. package/dist/session.js +545 -0
  31. package/dist/sqlite-stores.d.ts +173 -0
  32. package/dist/sqlite-stores.js +921 -0
  33. package/dist/stores.d.ts +506 -0
  34. package/dist/stores.js +614 -0
  35. package/dist/testing.d.ts +42 -0
  36. package/dist/testing.js +47 -0
  37. package/dist/trial-grant.d.ts +40 -0
  38. package/dist/trial-grant.js +24 -0
  39. package/dist/usage-report.d.ts +23 -0
  40. package/dist/usage-report.js +68 -0
  41. package/dist/util.d.ts +3 -0
  42. package/dist/util.js +5 -0
  43. package/package.json +16 -10
  44. package/scripts/agentchat-integrate.mjs +852 -607
@@ -0,0 +1,218 @@
1
+ import { ModelRuntime, type AgentSession, type FileEntry, type McpServerConfig, type Skill } from "@earendil-works/pi-coding-agent";
2
+ import type { McpServerDecl } from "@njuptlzf/agent-chat-protocol";
3
+ import { type McpConfigStore } from "./mcp-config.ts";
4
+ import type { LoadedProduct, ResolvedTier, ToolContext } from "./manifest.ts";
5
+ import { type PersonaConfigStore, type PersonaOverride } from "./persona-config.ts";
6
+ /**
7
+ * One shared ModelRuntime per process. Credentials live on the server only and
8
+ * are injected from environment variables, never read from a user's home dir.
9
+ */
10
+ export declare function createModelRuntime(dataDir: string, provider: string): Promise<ModelRuntime>;
11
+ /**
12
+ * Every skill available to one qualification, in declaration order (S1: a qual
13
+ * may replace the product's skill dirs, so the slash surface is per-scope).
14
+ * Skills are the only source of slash commands, so both the session builder and
15
+ * the command list use this.
16
+ */
17
+ export declare function loadProductSkills(product: LoadedProduct, qual?: string, persona?: string): Skill[];
18
+ /**
19
+ * 人格工具白名单:**收窄**,不是替换。
20
+ *
21
+ * - 未声明 `allowTools` ⇒ 原样返回(老行为零影响);
22
+ * - 声明了 ⇒ 只留白名单里的内联工具。**空数组 = 一个都不给**(不是「全给」)。
23
+ *
24
+ * 这是声明人格与默认助手真正的分界线:prompt 里写「不要答业务问题」说得再好,不如
25
+ * `pick_practice` 根本不在工具列表里来得硬。
26
+ */
27
+ export declare function filterToolsForPersona<T>(tools: T[], allow: string[] | undefined, disabled?: string[]): T[];
28
+ /**
29
+ * MCP 侧的同一道闸:把 `allowTools` 翻成 pi 的 per-tool `toolExposure`。
30
+ *
31
+ * 与已有 exposure **取交集**——管理员在管理页显式关掉的工具,人格白名单也打不开。
32
+ * 反过来(人格没写 ⇒ 不动)保证老配置零影响。
33
+ */
34
+ export declare function narrowMcpExposure(decl: McpServerDecl, allow: string[] | undefined, disabled?: string[]): McpServerDecl;
35
+ /**
36
+ * A slash command as the UI offers it. Bare names, not pi's `/skill:<name>`:
37
+ * the picker is ours and the user should not have to know pi's spelling.
38
+ */
39
+ export interface ProductCommand {
40
+ name: string;
41
+ description: string;
42
+ }
43
+ /**
44
+ * Skills that can be typed explicitly. Unlike the system-prompt advertising
45
+ * (`createSkillSupport`), this includes `disable-model-invocation` skills: those
46
+ * are exactly the ones meant to be invoked by hand.
47
+ */
48
+ export declare function buildCommands(skills: Skill[]): ProductCommand[];
49
+ /**
50
+ * Expand a typed "/name args" into the skill body, so the "/" never reaches the
51
+ * model. Anything not starting with "/" passes through untouched; an unknown
52
+ * command is an error rather than a silent pass-through, because the UI offers a
53
+ * picker and a stray "/" would otherwise be sent to the model as prose.
54
+ *
55
+ * The skill's own path is deliberately not included (no server filesystem paths
56
+ * in prompts), and only the body is sent — the frontmatter is metadata.
57
+ */
58
+ export declare function expandCommand(message: string, commands: ProductCommand[], skills: Skill[]): {
59
+ error: string;
60
+ } | {
61
+ message: string;
62
+ };
63
+ /** One extension dialog to forward to the browser (batch 3-4b). Mirrors the `ui_prompt` ChatEvent. */
64
+ export interface UIPromptRequest {
65
+ id: string;
66
+ kind: "select" | "confirm" | "input";
67
+ title: string;
68
+ message?: string;
69
+ options?: string[];
70
+ placeholder?: string;
71
+ /** pi's dialog `timeout` option, when set: close with defaults after this long. */
72
+ timeoutMs?: number;
73
+ }
74
+ /** The browser's answer to a `UIPromptRequest` (mirrors POST /api/ui-response). */
75
+ export interface UIPromptAnswer {
76
+ value?: string;
77
+ confirmed?: boolean;
78
+ cancelled?: boolean;
79
+ }
80
+ export interface CreateProductSessionOptions {
81
+ product: LoadedProduct;
82
+ modelRuntime: ModelRuntime;
83
+ tools: unknown[];
84
+ userId: string;
85
+ dataDir: string;
86
+ /**
87
+ * Which tier this run uses (batch 3-1), already resolved against the manifest
88
+ * by `resolveTier`. Omit to run the manifest's `agent.model` as-is.
89
+ */
90
+ tier?: ResolvedTier;
91
+ /**
92
+ * Qualification this run studies for (id from the manifest's `quals`). It only
93
+ * scopes the system prompt — the default persona must not answer for another exam's
94
+ * syllabus. Omit or "" for products without qualifications.
95
+ */
96
+ qual?: string;
97
+ /**
98
+ * Which assistant persona this session is (). Omit for the product
99
+ * product default. It only swaps prompt/skills here; the tool whitelist is
100
+ * decided by the caller (the endpoint builds `tools`), because that is where
101
+ * the real boundary is.
102
+ */
103
+ persona?: string;
104
+ /**
105
+ * 运行时人格配置。**每次建会话读一次**:写完 `invalidate()` 即生效,
106
+ * 不用重启;已建好的会话不受影响(prompt 在创建时定死)。
107
+ */
108
+ personaConfig?: PersonaConfigStore;
109
+ /**
110
+ * 直接指定覆盖值(试跑):**优先于** `personaConfig` 里的已保存值,
111
+ * 让「未保存的草稿」也能真跑一次。传 `{}` = 明确用 manifest 原样(不是"回落")。
112
+ */
113
+ personaOverride?: PersonaOverride;
114
+ /** Restored history entries (header + entries), from the HistoryStore. */
115
+ history?: FileEntry[];
116
+ /**
117
+ * Optional tuning of pi's automatic context compaction, which is enabled by
118
+ * default (reserveTokens 16384 / keepRecentTokens 20000). Tests and ops may
119
+ * pass smaller thresholds here; omit to keep pi's defaults.
120
+ */
121
+ compaction?: {
122
+ reserveTokens?: number;
123
+ keepRecentTokens?: number;
124
+ };
125
+ /**
126
+ * Asked before running a tool listed in the manifest's `confirmTools`.
127
+ * Resolve true to allow, false to block (the model sees an error result).
128
+ */
129
+ requestConfirm?: (info: {
130
+ toolCallId: string;
131
+ name: string;
132
+ args: Record<string, unknown>;
133
+ }) => Promise<boolean>;
134
+ /**
135
+ * An extension called `ctx.ui.select/confirm/input`; forward it to the UI and
136
+ * await the answer. Without this the dialogs fail closed immediately
137
+ * (confirm -> false, the rest -> undefined), matching pi's own no-UI behavior.
138
+ */
139
+ requestUI?: (req: UIPromptRequest, signal?: AbortSignal) => Promise<UIPromptAnswer>;
140
+ /** An extension called `ctx.ui.notify`; fire-and-forget to the UI. */
141
+ onUINotify?: (message: string, level: "info" | "warning" | "error") => void;
142
+ /**
143
+ * 业务接入配置:data/mcp-config.json 为准,缺省回落 manifest 的 `mcp:` 种子。
144
+ */
145
+ mcpConfig?: McpConfigStore;
146
+ }
147
+ /**
148
+ * Match a tool name against the manifest's `confirmTools` patterns:
149
+ * exact name, or a `prefix*` entry matching by prefix.
150
+ */
151
+ export declare function needsConfirmation(patterns: string[], toolName: string): boolean;
152
+ /**
153
+ * Manifest MCP declaration -> pi server config. pi types stay in this file.
154
+ * Paths were already resolved against the product dir by loadProduct.
155
+ * Exposure defaults to "direct" so tools are declared to the model like the
156
+ * product's own tools; "codemode" is rejected at manifest load because this
157
+ * session does not load the codemode extension.
158
+ *
159
+ * identity injection: every stdio server child is spawned per session,
160
+ * so the run's (userId, scope) rides in as env the manifest cannot override
161
+ * (AC_* keys are applied last). A business MCP server like the product's must know
162
+ * whose wrong-book to read — tool arguments come from the model and are not
163
+ * an identity; the environment is. AC_DATA_DIR/AC_PRODUCT_DIR give the child
164
+ * the repo facts it cannot re-derive (its cwd is the data dir; manifest
165
+ * `${VAR}` templates resolve against the HOST process env, so the server must
166
+ * never read DATA_DIR itself — the host passes the resolved absolute path).
167
+ * HTTP servers get no identity header yet
168
+ * (ponytail: no consumer; upgrade path = signed header or per-user URL).
169
+ * openapi entries are translated here into a stdio spawn of mcp-openapi-proxy
170
+ * (); the AC_* identity env rides along harmlessly (the proxy ignores it).
171
+ * Exported for tests.
172
+ */
173
+ export declare function toMcpConfig(id: string, decl: McpServerDecl, identity: {
174
+ userId: string;
175
+ scope: string;
176
+ dataDir: string;
177
+ productDir: string;
178
+ persona: string;
179
+ }): McpServerConfig;
180
+ /**
181
+ * 选项那一行(进 system prompt,不进用户消息)。真实会话与「编译预览」共用这一份,
182
+ * 否则预览看到的 prompt 会和实际跑的不是同一段。
183
+ */
184
+ export declare function qualSectionOf(product: LoadedProduct, qual: string | undefined): string;
185
+ /**
186
+ * 编译预览:**不建会话、不连 MCP、不调模型**,只把
187
+ * 「这个人格现在会拼成什么」算出来。与 `createProductSession` 共用
188
+ * `agentFor` / `applyPersonaOverride` / `loadProductSkills` / `qualSectionOf`,
189
+ * 所以它显示的就是真实会话会拿到的 prompt 与技能。
190
+ */
191
+ export declare function compileSystemPrompt(product: LoadedProduct, qual: string | undefined, persona: string | undefined, override?: PersonaOverride): {
192
+ systemPrompt: string;
193
+ skills: {
194
+ name: string;
195
+ description: string;
196
+ }[];
197
+ allowTools?: string[];
198
+ disabledTools: string[];
199
+ };
200
+ /**
201
+ * Build a pi session locked down for multi-user serving:
202
+ * - no built-in tools (no bash / read / write / edit), verified by test
203
+ * - only the product's own tools plus manifest-declared MCP tools
204
+ * - in-memory settings and history (the host owns persistence)
205
+ * - no filesystem discovery of extensions, prompts, themes or context files
206
+ */
207
+ export declare function createProductSession(opts: CreateProductSessionOptions): Promise<AgentSession>;
208
+ /**
209
+ * Tear down a session created by createProductSession.
210
+ *
211
+ * AgentSession.dispose() alone never emits "session_shutdown", so extensions —
212
+ * notably the MCP extension's stdio child processes — would keep their handles
213
+ * open and the process alive. Emit the shutdown event first, then dispose.
214
+ */
215
+ export declare function disposeProductSession(session: AgentSession): Promise<void>;
216
+ /** Snapshot a session's history so it can be saved and restored later. */
217
+ export declare function exportHistory(session: AgentSession): FileEntry[];
218
+ export type { ToolContext };