@njuptlzf/agent-chat-server 0.4.1 → 0.5.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.
@@ -0,0 +1,176 @@
1
+ /**
2
+ * 记忆提供方注册表。
3
+ *
4
+ * 服务器只认 id,不认实现:换记忆引擎 = 换 manifest 里的 `agent.memory.provider`,
5
+ * 本文件之外的服务器代码一行不动。
6
+ *
7
+ * 注册有两条路:
8
+ * 1. **内置**:`scoped-memory` 是平台自带的最小实现,作为默认值存在——没有它,
9
+ * 一个没声明 provider 的产品就会没有记忆,那是最糟的默认。
10
+ * 2. **外部**:产品在 manifest 里声明 `agent.memoryProviders: [...]`,条目可以是
11
+ * 产品目录内的相对路径,也可以是包名(走 Node 解析)。外部模块与 `agent.extensions`
12
+ * 同一信任模型:仓库内代码、过准入扫描、进程内运行。
13
+ *
14
+ * 两条刻意选择:
15
+ * - **不可用即报错,不静默降级**。选了没装的 provider 就抛,并列出已注册 id。
16
+ * 静默回落默认实现,会让"我换了引擎"和"我忘了装"看起来一模一样。
17
+ * - **模块用动态 import**。静态导入会把提供方(可能是第三方包)的整棵源码拉进
18
+ * 本仓的 tsc program,跨仓源码进他人编译单元是最难收拾的一类耦合。
19
+ */
20
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
21
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
22
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
23
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
24
+ });
25
+ }
26
+ return path;
27
+ };
28
+ import { existsSync, readFileSync } from "node:fs";
29
+ import { createRequire } from "node:module";
30
+ import * as path from "node:path";
31
+ import { pathToFileURL } from "node:url";
32
+ import { scopedMemory } from "pi-scoped-memory";
33
+ import { auditExtensionSource } from "./extension-admission.js";
34
+ /** 不指定时的实现。与 protocol 的 `agent.memory === true` 对齐。 */
35
+ export const DEFAULT_MEMORY_PROVIDER_ID = "scoped-memory";
36
+ const requireFromRoot = createRequire(import.meta.url);
37
+ function installedVersion(pkg) {
38
+ try {
39
+ const parsed = requireFromRoot(`${pkg}/package.json`);
40
+ return typeof parsed.version === "string" ? parsed.version : "unknown";
41
+ }
42
+ catch {
43
+ // Version is for logs, not behaviour: a missing package.json must not break open().
44
+ return "unknown";
45
+ }
46
+ }
47
+ const scopedMemoryProvider = {
48
+ id: DEFAULT_MEMORY_PROVIDER_ID,
49
+ version: installedVersion("pi-scoped-memory"),
50
+ async open(ctx) {
51
+ const dir = ctx.storageRoot;
52
+ const { rm } = await import("node:fs/promises");
53
+ return {
54
+ providerId: DEFAULT_MEMORY_PROVIDER_ID,
55
+ // scopedMemory appends its own snapshot in before_agent_start.
56
+ selfInjects: true,
57
+ factory: scopedMemory({ dir, autoCapture: true }),
58
+ async promptSection() {
59
+ return "";
60
+ },
61
+ async erase() {
62
+ // Its own file is <dir>/entries.jsonl; the directory is host-allocated,
63
+ // so removing it is exactly one tenant's worth of data.
64
+ await rm(dir, { recursive: true, force: true });
65
+ },
66
+ async dispose() { },
67
+ };
68
+ },
69
+ };
70
+ const registry = new Map([
71
+ [scopedMemoryProvider.id, scopedMemoryProvider],
72
+ ]);
73
+ /** 已加载的外部模块,按解析后的绝对路径去重:同一文件 import 两次不该注册两次。 */
74
+ const loadedModules = new Map();
75
+ function assertProviderShape(candidate, source) {
76
+ const provider = candidate;
77
+ if (!provider || typeof provider !== "object") {
78
+ throw new Error(`${source}: default export must be a memory provider object`);
79
+ }
80
+ if (typeof provider.id !== "string" || provider.id.trim() === "") {
81
+ throw new Error(`${source}: provider.id must be a non-empty string`);
82
+ }
83
+ if (typeof provider.version !== "string") {
84
+ throw new Error(`${source}: provider.version must be a string`);
85
+ }
86
+ if (typeof provider.open !== "function") {
87
+ throw new Error(`${source}: provider.open must be a function`);
88
+ }
89
+ return provider;
90
+ }
91
+ /**
92
+ * 注册一个提供方。
93
+ *
94
+ * 同 id 重复注册直接抛:静默覆盖会让"哪个实现真的生效"变成必须读启动日志才能回答的
95
+ * 问题,而启动日志往往在出事后已经滚没了。
96
+ */
97
+ export function registerMemoryProvider(provider) {
98
+ const existing = registry.get(provider.id);
99
+ if (existing && existing !== provider) {
100
+ throw new Error(`memory provider "${provider.id}" is already registered (${existing.version})`);
101
+ }
102
+ registry.set(provider.id, provider);
103
+ }
104
+ /**
105
+ * 解析 manifest 里的一条外部模块声明。
106
+ *
107
+ * 相对路径(`./x.ts`)必须落在产品目录内——与 `server.routes` 同一条纪律:写 `../`
108
+ * 等于让 manifest 加载任意文件。裸说明符(包名)交给 Node 解析,装在哪由依赖树决定。
109
+ */
110
+ export function resolveProviderModuleEntry(entry, productDir) {
111
+ const trimmed = entry.trim();
112
+ if (trimmed === "")
113
+ throw new Error("memory provider module path must not be empty");
114
+ if (trimmed.startsWith(".")) {
115
+ const resolved = path.resolve(productDir, trimmed);
116
+ const inside = path.resolve(productDir) + path.sep;
117
+ if (!resolved.startsWith(inside)) {
118
+ throw new Error(`memory provider module "${trimmed}" must stay inside the product directory`);
119
+ }
120
+ return resolved;
121
+ }
122
+ try {
123
+ return requireFromRoot.resolve(trimmed, { paths: [productDir] });
124
+ }
125
+ catch (error) {
126
+ throw new Error(`memory provider module "${trimmed}" is not resolvable from ${productDir}: ${error.message}`);
127
+ }
128
+ }
129
+ /**
130
+ * 从文件加载外部提供方。准入扫描与扩展同一套判据:提供方也在服务进程内运行,
131
+ * 读 env / 拉子进程在这里同样是跨层能力。
132
+ */
133
+ export async function loadMemoryProviderModule(entry, productDir) {
134
+ const resolved = resolveProviderModuleEntry(entry, productDir);
135
+ const cached = loadedModules.get(resolved);
136
+ if (cached)
137
+ return cached;
138
+ const loading = (async () => {
139
+ if (!existsSync(resolved)) {
140
+ throw new Error(`memory provider module "${entry}" does not exist (resolved: ${resolved})`);
141
+ }
142
+ const violations = auditExtensionSource(readFileSync(resolved, "utf8"), `memory provider "${entry}"`);
143
+ if (violations.length > 0) {
144
+ throw new Error(violations.map((v) => `criterion ${v.criterion}: ${v.reason}`).join("; "));
145
+ }
146
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(resolved).href)));
147
+ const provider = assertProviderShape(mod.default, `memory provider "${entry}"`);
148
+ registerMemoryProvider(provider);
149
+ return provider;
150
+ })();
151
+ loadedModules.set(resolved, loading);
152
+ try {
153
+ return await loading;
154
+ }
155
+ catch (error) {
156
+ // A failed load must not poison the cache: fixing the file and retrying is
157
+ // the normal path during development.
158
+ loadedModules.delete(resolved);
159
+ throw error;
160
+ }
161
+ }
162
+ export function listMemoryProviders() {
163
+ return [...registry.values()].map((provider) => ({
164
+ id: provider.id,
165
+ version: provider.version,
166
+ default: provider.id === DEFAULT_MEMORY_PROVIDER_ID,
167
+ }));
168
+ }
169
+ export function resolveMemoryProvider(id) {
170
+ const wanted = id ?? DEFAULT_MEMORY_PROVIDER_ID;
171
+ const provider = registry.get(wanted);
172
+ if (!provider) {
173
+ throw new Error(`unknown memory provider "${wanted}" — available: ${[...registry.keys()].join(", ")}`);
174
+ }
175
+ return provider;
176
+ }
package/dist/server.d.ts CHANGED
@@ -9,6 +9,7 @@ import { type SuggestionsRunner } from "./suggestions.ts";
9
9
  import { type CooldownRegistry } from "./model-failover.ts";
10
10
  import { type ModelConfigStore } from "./model-config.ts";
11
11
  import { type McpConfigStore } from "./mcp-config.ts";
12
+ import type { CostTable } from "./cost-model.ts";
12
13
  import type { AccountStateStore, AuditEvent, AuditStore, Authenticator, BillingStore, HistoryStore, MembershipStore, MemberPoolStore, RunLogStore } from "./stores.ts";
13
14
  import type { Ledger } from "./ledger.ts";
14
15
  import type { Engine } from "./orchestrator/engine.ts";
@@ -74,6 +75,11 @@ export interface ServerDeps {
74
75
  * 先占位再开跑,并发下不会超发(旧模型实测超发 140%)。
75
76
  */
76
77
  ledger: Ledger;
78
+ /**
79
+ * 成本表(统一成本模型)。omitted ⇒ settle 的 cu=0(CU 闸不启用,零行为变化);
80
+ * 主链 main.ts 由 loadCostTable 装配。按 run 起始 tier 模型折算,见 CostTable 注释。
81
+ */
82
+ costTable?: CostTable;
77
83
  /**
78
84
  * 编排引擎。omitted ⇒ 默认 `taskflow` 适配器(W1:单 phase 通路)。
79
85
  * 测试注入 `createFakeEngine()`,**不建 pi 会话、不调模型**——
package/dist/server.js CHANGED
@@ -1495,7 +1495,9 @@ export function createChatServer(deps) {
1495
1495
  res.write(": ping\n\n");
1496
1496
  }, 15000);
1497
1497
  let session;
1498
- const mapper = createEventMapper();
1498
+ // costUsd 统一口径:装了 costTable 就按 run 起始 tier 模型折算 CU 写进 TokenUsage.costUsd;
1499
+ // 没装则传 undefined 让 mapper 回退 pi 的 cost.total(老部署零行为变化)。
1500
+ const mapper = createEventMapper(deps.costTable ? (u) => deps.costTable.cuFor(tier.provider, tier.model, u) : undefined);
1499
1501
  const accounting = createRunAccounting(limits.maxToolRounds);
1500
1502
  const toolCalls = {};
1501
1503
  let doneSent = false;
@@ -1948,7 +1950,9 @@ export function createChatServer(deps) {
1948
1950
  const durationMs = Date.now() - startedAt.getTime();
1949
1951
  try {
1950
1952
  // 结算(I4):把占位换成实际消耗,多退少补。条件更新保证幂等(I6)。
1951
- await deps.ledger.settle({ operationId, userId, persona, tokens: usage.total });
1953
+ // CU 闸:按本次 run 的起始 tier 模型把 usage 折算成 CU(failover/多 phase 见 CostTable 边界)。
1954
+ const cu = deps.costTable?.cuFor(tier.provider, tier.model, usage) ?? 0;
1955
+ await deps.ledger.settle({ operationId, userId, persona, tokens: usage.total, cu });
1952
1956
  // Charge after the fact: the run already spent the tokens; the balance gate stops the next one.
1953
1957
  if (billingActive) {
1954
1958
  // 池优先拆账(结算=发放检查点之二):结算时**重读**池——
package/dist/session.js CHANGED
@@ -4,17 +4,23 @@ import * as path from "node:path";
4
4
  import { Type } from "typebox";
5
5
  import { createAgentSession, createMcpExtension, DefaultResourceLoader, defineTool, initTheme, loadSkillsFromDir, stripFrontmatter, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
6
6
  import { toProxySpawn } from "./mcp-config.js";
7
- import { scopedMemory } from "pi-scoped-memory";
7
+ import { loadMemoryProviderModule, resolveMemoryProvider } from "./memory-providers.js";
8
8
  import { agentFor, resolveTier } from "./manifest.js";
9
9
  import { applyPersonaOverride } from "./persona-config.js";
10
+ import { validateModelsCost } from "./cost-model.js";
10
11
  /**
11
12
  * One shared ModelRuntime per process. Credentials live on the server only and
12
13
  * are injected from environment variables, never read from a user's home dir.
13
14
  */
14
15
  export async function createModelRuntime(dataDir, provider) {
16
+ // 成本模型校验:缺 costModel 声明放行(走全局倍率兜底),但声明了却非法的模型 fail fast。
17
+ // 2026-11-18 口径修订:ModelScope 这类按次计费模型不可能逐模型声明,统一 token×倍率兜底。
18
+ const modelsPath = `${dataDir}/models.json`;
19
+ const rawModels = JSON.parse(readFileSync(modelsPath, "utf8"));
20
+ validateModelsCost(rawModels);
15
21
  const runtime = await ModelRuntime.create({
16
22
  authPath: `${dataDir}/auth.json`,
17
- modelsPath: `${dataDir}/models.json`,
23
+ modelsPath,
18
24
  });
19
25
  const envName = `${provider.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_API_KEY`;
20
26
  const key = process.env[envName];
@@ -344,6 +350,14 @@ export function compileSystemPrompt(product, qual, persona, override) {
344
350
  disabledTools: effective.disabledTools,
345
351
  };
346
352
  }
353
+ /**
354
+ * Provider handle per live session.
355
+ *
356
+ * A WeakMap rather than a field on the session: the handle is host bookkeeping
357
+ * (store connection, lock file), and the session object belongs to pi. Keying by
358
+ * session also means a crashed session cannot leak a handle into the next one.
359
+ */
360
+ const memorySessionsByAgent = new WeakMap();
347
361
  /**
348
362
  * Build a pi session locked down for multi-user serving:
349
363
  * - no built-in tools (no bash / read / write / edit), verified by test
@@ -445,17 +459,32 @@ export async function createProductSession(opts) {
445
459
  },
446
460
  ]
447
461
  : [];
448
- // scopedMemory (plan B; npm 版本消费,正本在 github.com/njuptlzf/pi-scoped-memory):
449
- // one factory per session,
450
- // pointed at the tenant/scope directory the host computes. The plugin itself only
451
- // knows a directory — no userId/scope inside it, so it stays open-sourceable
452
- // without business knowledge. `qual || "default"` keeps single-track products
453
- // whole. `autoCapture` is host policy: every 10 turns one cheap completion
454
- // distils the tail of the transcript into a remembered point (secret-filtered,
455
- // silent on failure; the same opt-in stays false in the standalone CLI).
456
- const memoryExtensions = product.memoryEnabled
457
- ? [scopedMemory({ dir: path.join(opts.dataDir, "memory", opts.userId, opts.qual || "default"), autoCapture: true })]
458
- : [];
462
+ // Memory comes from the provider registry, not from a hardcoded plugin:
463
+ // one open() per session, pointed at the tenant/scope directory the host
464
+ // computes. The provider never learns userId/scope semantics beyond that root,
465
+ // so an implementation can stay generic (and open-sourceable). Swapping the
466
+ // engine is a manifest edit — `agent.memory.provider`.
467
+ //
468
+ // External modules load here, before resolution: the platform does not know
469
+ // `hermes-scoped` exists until the product declares the module that provides
470
+ // it. Loading is per-file memoised, so this is one dynamic import per process.
471
+ if (product.memoryEnabled) {
472
+ for (const entry of product.memoryProviderModules) {
473
+ await loadMemoryProviderModule(entry, product.dir);
474
+ }
475
+ }
476
+ // Two disjoint roots per session: the scope (user × product × qual) and the
477
+ // user's cross-scope profile. Siblings, not nested — erasing one qualification
478
+ // must not delete the user's identity, and the provider enforces that too.
479
+ const memorySession = product.memoryEnabled
480
+ ? await resolveMemoryProvider(product.memoryProviderId).open({
481
+ storageRoot: path.join(opts.dataDir, "memory", opts.userId, opts.qual || "default"),
482
+ sharedRoot: path.join(opts.dataDir, "memory", opts.userId, "profile"),
483
+ agentDir: opts.dataDir,
484
+ scope: { userId: opts.userId, productId: product.manifest.id, qual: opts.qual || "" },
485
+ })
486
+ : null;
487
+ const memoryExtensions = memorySession ? [memorySession.factory] : [];
459
488
  // pi prints the working directory into the system prompt, so use the per-product
460
489
  // data dir (empty of source code) rather than the product's source directory.
461
490
  const cwd = opts.dataDir;
@@ -472,13 +501,19 @@ export async function createProductSession(opts) {
472
501
  // browser never has to remember to repeat it. `label` is display text the
473
502
  // operator wrote; ids alone would be meaningless to the model.
474
503
  const qualSection = qualSectionOf(product, opts.qual);
504
+ // A provider that does not inject on its own hands us the text; the host puts
505
+ // it where prompt sections belong. Asking for it here — before the session
506
+ // exists — is why `open()` and `mount()` are separate in the port.
507
+ const memorySection = memorySession && !memorySession.selfInjects
508
+ ? await memorySession.promptSection()
509
+ : "";
475
510
  const resourceLoader = new DefaultResourceLoader({
476
511
  cwd,
477
512
  agentDir: opts.dataDir,
478
513
  settingsManager,
479
514
  systemPrompt: effective.prompt,
480
515
  ...(() => {
481
- const extra = [qualSection, skillSupport.promptSection].filter((s) => s !== "");
516
+ const extra = [qualSection, memorySection, skillSupport.promptSection].filter((s) => s !== "");
482
517
  return extra.length > 0 ? { appendSystemPrompt: extra } : {};
483
518
  })(),
484
519
  // Manifest-declared extensions (operator-reviewed repo code). They load even
@@ -509,14 +544,19 @@ export async function createProductSession(opts) {
509
544
  sessionManager: SessionManager.inMemory(cwd, undefined, opts.history),
510
545
  settingsManager,
511
546
  });
512
- if (mcpExtensions.length > 0 || product.extensionPaths.length > 0) {
547
+ if (mcpExtensions.length > 0 || product.extensionPaths.length > 0 || memorySession) {
513
548
  // Emits session_start, which is when the MCP extension connects its servers
514
549
  // (in the background; the first prompt waits for "direct" servers) and when
515
550
  // manifest-declared extensions run their own startup handlers.
551
+ // A self-injecting memory provider needs this too: without the bind its
552
+ // before_agent_start hook never runs, and the failure mode is silence (tools
553
+ // work, the policy prompt never appears).
516
554
  // mode "rpc" is pi's own non-terminal contract: dialogs are data, not TUI
517
555
  // components — exactly what our SSE bridge below implements.
518
556
  await session.bindExtensions({ uiContext: createExtensionUIContext(opts), mode: "rpc" });
519
557
  }
558
+ if (memorySession)
559
+ memorySessionsByAgent.set(session, memorySession);
520
560
  return session;
521
561
  }
522
562
  /**
@@ -535,6 +575,12 @@ export async function disposeProductSession(session) {
535
575
  }
536
576
  finally {
537
577
  session.dispose();
578
+ // Provider handles go last and separately: the extension's shutdown handlers
579
+ // run inside a live session, while dispose() closes store/lock connections.
580
+ const memory = memorySessionsByAgent.get(session);
581
+ memorySessionsByAgent.delete(session);
582
+ if (memory)
583
+ await memory.dispose();
538
584
  }
539
585
  }
540
586
  /** Snapshot a session's history so it can be saved and restored later. */
@@ -83,6 +83,8 @@ export declare class SqliteLedger implements Ledger {
83
83
  private countForCap;
84
84
  private countSettled;
85
85
  private tokensUsed;
86
+ /** 今日已结算的 CU(成本模型独立闸)——结算后的预留仍留在表里,按 state='settled' 求和。 */
87
+ private cuUsed;
86
88
  reserve(input: ReserveInput): Promise<ReserveOutcome>;
87
89
  settle(input: SettleInput): Promise<SettleOutcome>;
88
90
  release(operationId: string): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { DatabaseSync } from "node:sqlite";
3
3
  import { DEFAULT_PERSONA_ID } from "@njuptlzf/agent-chat-protocol";
4
- import { assertMembershipWrite, assertProductId, summarizeHistory, quotaBlockedReason } from "./stores.js";
4
+ import { assertMembershipWrite, assertProductId, summarizeHistory, quotaBlockedCostReason, quotaBlockedReason } from "./stores.js";
5
5
  import { RESERVATION_TTL_MS } from "./ledger.js";
6
6
  import { auditPageWindow } from "./stores.js";
7
7
  import { GENESIS_HASH, assertNoSensitiveKeys, canonicalize, rowHash, segmentsFrom, verifyChain } from "./audit.js";
@@ -57,6 +57,8 @@ export function openDatabase(file, defaultScope = "", defaultPersona = DEFAULT_P
57
57
  persona TEXT NOT NULL,
58
58
  day TEXT NOT NULL,
59
59
  tokens INTEGER NOT NULL DEFAULT 0,
60
+ -- 成本模型(CU 维度):独立额度闸,与 token 维度并列(用户拍板:不并入 T3)。
61
+ cost_units INTEGER NOT NULL DEFAULT 0,
60
62
  state TEXT NOT NULL,
61
63
  created_at INTEGER NOT NULL,
62
64
  expires_at INTEGER NOT NULL
@@ -303,6 +305,10 @@ function migrateScope(db, defaultScope, defaultPersona) {
303
305
  }
304
306
  if (!columns("feedback").includes("content"))
305
307
  db.exec("ALTER TABLE feedback ADD COLUMN content TEXT");
308
+ // 成本模型:预留账本加 CU 维度(独立额度闸)。老行 0 = 迁移前无成本计量,不回填。
309
+ if (!columns("quota_reservations").includes("cost_units")) {
310
+ db.exec("ALTER TABLE quota_reservations ADD COLUMN cost_units INTEGER NOT NULL DEFAULT 0");
311
+ }
306
312
  if (!columns("feedback").includes("status")) {
307
313
  db.exec("ALTER TABLE feedback ADD COLUMN status TEXT NOT NULL DEFAULT 'new'");
308
314
  }
@@ -505,6 +511,13 @@ export class SqliteLedger {
505
511
  .get(userId, persona, day);
506
512
  return row?.tokens ?? 0;
507
513
  }
514
+ /** 今日已结算的 CU(成本模型独立闸)——结算后的预留仍留在表里,按 state='settled' 求和。 */
515
+ cuUsed(userId, persona, day) {
516
+ const row = this.db
517
+ .prepare("SELECT COALESCE(SUM(cost_units), 0) AS n FROM quota_reservations WHERE user_id = ? AND persona = ? AND day = ? AND state = 'settled'")
518
+ .get(userId, persona, day);
519
+ return row.n;
520
+ }
508
521
  async reserve(input) {
509
522
  const nowMs = this.now().getTime();
510
523
  const day = this.day();
@@ -550,11 +563,28 @@ export class SqliteLedger {
550
563
  if (cap !== undefined && cap > 0)
551
564
  reserveTokens = Math.min(cap, tokenCap - used - reserved.n);
552
565
  }
566
+ // 成本模型 CU 闸(独立于 token):同一 BEGIN IMMEDIATE 事务内判定,任一维触顶即拒。
567
+ let reserveCu = 0;
568
+ const dailyCostCap = input.caps?.dailyCostCap;
569
+ if (dailyCostCap !== undefined && dailyCostCap > 0) {
570
+ const usedCu = this.cuUsed(input.userId, input.persona, day);
571
+ const reservedCu = this.db
572
+ .prepare(`SELECT COALESCE(SUM(cost_units), 0) AS n FROM quota_reservations
573
+ WHERE user_id = ? AND persona = ? AND day = ? AND state = 'reserved' AND expires_at > ?`)
574
+ .get(input.userId, input.persona, day, nowMs).n;
575
+ if (usedCu + reservedCu >= dailyCostCap) {
576
+ this.db.exec("ROLLBACK");
577
+ return { ok: false, reason: quotaBlockedCostReason(input.caps ?? {}) };
578
+ }
579
+ const cap = input.caps?.perRunCostCap;
580
+ if (cap !== undefined && cap > 0)
581
+ reserveCu = Math.min(cap, dailyCostCap - usedCu - reservedCu);
582
+ }
553
583
  const expiresAt = nowMs + (input.ttlMs ?? RESERVATION_TTL_MS);
554
584
  this.db
555
- .prepare(`INSERT INTO quota_reservations (operation_id, user_id, persona, day, tokens, state, created_at, expires_at)
556
- VALUES (?, ?, ?, ?, ?, 'reserved', ?, ?)`)
557
- .run(input.operationId, input.userId, input.persona, day, reserveTokens, nowMs, expiresAt);
585
+ .prepare(`INSERT INTO quota_reservations (operation_id, user_id, persona, day, tokens, cost_units, state, created_at, expires_at)
586
+ VALUES (?, ?, ?, ?, ?, ?, 'reserved', ?, ?)`)
587
+ .run(input.operationId, input.userId, input.persona, day, reserveTokens, reserveCu, nowMs, expiresAt);
558
588
  this.db.exec("COMMIT");
559
589
  return { ok: true, reservation: { operationId: input.operationId, expiresAt } };
560
590
  }
@@ -570,9 +600,9 @@ export class SqliteLedger {
570
600
  // 条件更新 = 幂等闸:只有 `reserved → settled` 的那一次会写 quota,
571
601
  // 重复 settle 直接返回 already(不重复扣费)。
572
602
  const res = this.db
573
- .prepare(`UPDATE quota_reservations SET state = 'settled', tokens = ?
603
+ .prepare(`UPDATE quota_reservations SET state = 'settled', tokens = ?, cost_units = ?
574
604
  WHERE operation_id = ? AND state = 'reserved'`)
575
- .run(input.tokens, input.operationId);
605
+ .run(input.tokens, input.cu ?? 0, input.operationId);
576
606
  if (res.changes === 0) {
577
607
  this.db.exec("COMMIT");
578
608
  return "already";
package/dist/stores.d.ts CHANGED
@@ -58,7 +58,17 @@ export interface QuotaCaps {
58
58
  * 当日总量判定。<=0/缺省 = 不启用(预留写 0,W3 现状)。
59
59
  */
60
60
  perRunTokenCap?: number;
61
+ /**
62
+ * 成本模型(CU 维度,独立于 token 的第三闸):每 run 的 CU 上界与每日 CU 总量。
63
+ * 独立于 T3 的 tokenCap 体系——按次计费换算不成 token,并入会编造假 token 值导致失真。
64
+ */
65
+ perRunCostCap?: number;
66
+ dailyCostCap?: number;
61
67
  }
68
+ /** 成本额度(CU)撞闸文案——与 token/run 并列,明示这是成本维度而非 token 维度。 */
69
+ export declare function quotaBlockedCostReason(caps: {
70
+ dailyCostCap?: number;
71
+ }): string;
62
72
  /** 万位读法:5000000 → 「500 万」(撞闸文案与权益卡共用,别在 UI 里二次造轮子)。 */
63
73
  export declare function fmtTokensWan(n: number): string;
64
74
  /**
package/dist/stores.js CHANGED
@@ -147,6 +147,11 @@ export class MemoryHistoryStore {
147
147
  return rows.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
148
148
  }
149
149
  }
150
+ /** 成本额度(CU)撞闸文案——与 token/run 并列,明示这是成本维度而非 token 维度。 */
151
+ export function quotaBlockedCostReason(caps) {
152
+ const cap = caps.dailyCostCap;
153
+ return `今日成本额度已用完${cap !== undefined && cap > 0 ? `(上限 ${cap} CU)` : ""},次日重置;如需提额请联系管理员`;
154
+ }
150
155
  /** 万位读法:5000000 → 「500 万」(撞闸文案与权益卡共用,别在 UI 里二次造轮子)。 */
151
156
  export function fmtTokensWan(n) {
152
157
  return n >= 10000 ? `${(n / 10000).toLocaleString("zh-CN")} 万` : String(n);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@njuptlzf/agent-chat-server",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "agentChat platform kernel: sessions, authz, billing, audit, model/MCP/persona config planes, and the product-directory loader.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -55,7 +55,8 @@
55
55
  },
56
56
  "dependencies": {
57
57
  "@earendil-works/pi-coding-agent": "1.5.2",
58
- "@njuptlzf/agent-chat-protocol": "^0.4.0",
58
+ "@njuptlzf/agent-chat-protocol": "^0.5.0",
59
+ "@njuptlzf/pi-hermes-memory": "0.11.0-scoped.1",
59
60
  "casbin": "^5.51.1",
60
61
  "pi-scoped-memory": "^0.3.0",
61
62
  "taskflow-core": "1.0.0",
@@ -20,7 +20,7 @@ import { createRequire } from "node:module";
20
20
  import { spawnSync } from "node:child_process";
21
21
  import process from "node:process";
22
22
 
23
- const CLI_VERSION = "0.4.1";
23
+ const CLI_VERSION = "0.5.1";
24
24
  const MIN_SERVER = "0.2.0";
25
25
  const PKG = {
26
26
  protocol: "@njuptlzf/agent-chat-protocol",
@@ -215,9 +215,9 @@ function packageTemplate(o) {
215
215
  private: true,
216
216
  type: "module",
217
217
  dependencies: {
218
- [PKG.protocol]: "^0.4.0",
219
- [PKG.server]: "^0.4.0",
220
- [PKG.web]: "^0.4.0",
218
+ [PKG.protocol]: "^0.5.0",
219
+ [PKG.server]: "^0.5.0",
220
+ [PKG.web]: "^0.5.0",
221
221
  },
222
222
  devDependencies: {
223
223
  tsx: "^4.20.0",
@@ -408,7 +408,7 @@ function checkDeps(add, dir) {
408
408
  const all = { ...(pj.dependencies ?? {}), ...(pj.devDependencies ?? {}) };
409
409
  const missing = Object.values(PKG).filter((n) => !(n in all));
410
410
  if (missing.length) add("FAIL", "deps", `未声明平台依赖:${missing.join("、")}`,
411
- `npm i ${PKG.protocol}@^0.4.0 ${PKG.server}@^0.4.0 ${PKG.web}@^0.4.0`);
411
+ `npm i ${PKG.protocol}@^0.5.0 ${PKG.server}@^0.5.0 ${PKG.web}@^0.5.0`);
412
412
  else add("OK", "deps", "三个平台包依赖已声明");
413
413
 
414
414
  try {
@@ -712,6 +712,45 @@ function checkTestScripts(add, dir, opts) {
712
712
  return runs;
713
713
  }
714
714
 
715
+ /**
716
+ * 工具 schema 的 TypeBox 越界构造子(启发式,只给 WARN)。
717
+ *
718
+ * pi 按 JSON Schema 校验工具参数(`@earendil-works/pi-schema`):`Refine` 静默不跑、
719
+ * `BigInt`/`Undefined`/`Void` 拒绝**每一个**参数(工具永远调不通)、`Codec` 不解码、
720
+ * `Format.Set` 不检查。四者都不报编译错,只在运行期让约束或工具本身失效——没有别的
721
+ * 门禁能抓到,所以在这里给一条建议。只 WARN:同一构造子也可能用在非工具 schema 上。
722
+ */
723
+ const TOOL_SCHEMA_TRAPS = [
724
+ [/Type\.Refine\s*\(/, "Type.Refine() 不跑,约束需挪进 execute() 自己校验"],
725
+ [/Type\.(?:BigInt|Undefined|Void)\s*\(/, "BigInt()/Undefined()/Void() 会拒绝每一个参数(工具永远调不通)"],
726
+ [/Type\.Codec\s*\(/, "Type.Codec() 不解码,execute() 收到的是 JSON 值"],
727
+ [/Format\.Set\s*\(/, "Format.Set() 注册的格式不检查"],
728
+ ];
729
+
730
+ function checkToolSchemas(add, dir) {
731
+ const hits = [];
732
+ for (const f of walkFiles(dir).filter((f) => /\.(ts|tsx)$/.test(f))) {
733
+ if (/[\\/](test|tests|e2e)[\\/]/.test(f)) continue; // 测试里造反例不算产品用法
734
+ const text = stripComments(readText(path.dirname(f), path.basename(f)));
735
+ if (!text) continue;
736
+ const rel = path.relative(dir, f).replace(/\\/g, "/");
737
+ for (const [re, why] of TOOL_SCHEMA_TRAPS) {
738
+ if (re.test(text)) hits.push(`${rel}:${why}`);
739
+ }
740
+ }
741
+ if (hits.length === 0) {
742
+ add("OK", "tool-schema", "未检出 pi 不支持的 TypeBox 构造子");
743
+ return;
744
+ }
745
+ add(
746
+ "WARN",
747
+ "tool-schema",
748
+ `检出 ${hits.length} 处 pi 工具参数校验不生效的 TypeBox 构造子`,
749
+ `${hits.join(";")}。工具 schema 改用 JSON Schema 子集(Object/String/Number/Boolean/Array/Optional/Union/Literal),` +
750
+ "表达不了的约束挪进 execute() 自己校验;若不是工具 schema 可忽略本条",
751
+ );
752
+ }
753
+
715
754
  function checkTooling(add, dir) {
716
755
  const wf = path.join(dir, ".github", "workflows");
717
756
  const wfFiles = fs.existsSync(wf) ? fs.readdirSync(wf).filter((f) => /\.ya?ml$/.test(f)) : [];
@@ -765,6 +804,7 @@ function check(opts, dir) {
765
804
  const caps = checkCapabilities(add, dir);
766
805
  const runs = checkTestScripts(add, dir, opts);
767
806
  checkTooling(add, dir);
807
+ checkToolSchemas(add, dir);
768
808
  if (opts.deep) checkDeep(add, dir);
769
809
 
770
810
  const failures = results.filter((r) => r.level === "FAIL");
package/src/authz.ts CHANGED
@@ -139,6 +139,9 @@ export interface LimitsConfig {
139
139
  * 产品级可按 `limits.personas.<id>` 逐人格覆盖。
140
140
  */
141
141
  perRunTokenCap?: number;
142
+ /** 成本模型(CU 维度)额度:每 run 上界 / 每日总量,独立于 token 体系。 */
143
+ perRunCostCap?: number;
144
+ dailyCostCap?: number;
142
145
  /** 按人格(账本产品)覆盖;缺省继承产品级。 */
143
146
  personas?: Record<string, LimitsConfig>;
144
147
  }
@@ -152,6 +155,9 @@ export function capsForRoles(roles: string[], limits: LimitsConfig): QuotaCaps {
152
155
  tokenCap,
153
156
  // T3:单次 run 上界随人格生效;<=0 视为不启用(ledger 侧钳制)。
154
157
  ...(limits.perRunTokenCap !== undefined && limits.perRunTokenCap > 0 ? { perRunTokenCap: limits.perRunTokenCap } : {}),
158
+ // 成本模型 CU 闸(独立于 token);<=0 视为不启用。
159
+ ...(limits.perRunCostCap !== undefined && limits.perRunCostCap > 0 ? { perRunCostCap: limits.perRunCostCap } : {}),
160
+ ...(limits.dailyCostCap !== undefined && limits.dailyCostCap > 0 ? { dailyCostCap: limits.dailyCostCap } : {}),
155
161
  };
156
162
  }
157
163