@uncarved/jade 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -11
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/install.js +5 -0
- package/dist/install.js.map +1 -1
- package/package.json +6 -6
- package/plugins/approval/index.ts +129 -13
- package/plugins/approval/plugin.json +4 -1
- package/plugins/approval/policy.ts +127 -7
- package/plugins/approval/review.ts +188 -45
- package/plugins/ask/index.ts +29 -1
- package/plugins/budget/index.ts +44 -6
- package/plugins/budget/plugin.json +1 -2
- package/plugins/compact/compact.ts +153 -39
- package/plugins/compact/index.ts +39 -5
- package/plugins/compact/plugin.json +5 -2
- package/plugins/cost/cache.ts +114 -0
- package/plugins/cost/index.ts +109 -51
- package/plugins/cost/plugin.json +3 -2
- package/plugins/memory/memory.ts +51 -28
- package/plugins/models/configure.ts +344 -125
- package/plugins/models/index.ts +44 -9
- package/plugins/models/price.ts +291 -0
- package/plugins/models/provider.ts +40 -8
- package/plugins/models/saved.ts +20 -4
- package/plugins/modes/index.ts +3 -4
- package/plugins/prompts/prompts.ts +5 -1
- package/plugins/task/index.ts +31 -10
- package/plugins/task/plugin.json +5 -2
- package/plugins/task/subagent.ts +21 -4
- package/plugins/todo/index.ts +62 -1
- package/plugins/todo/plugin.json +1 -1
- package/plugins/tui/frontend.ts +31 -5
- package/plugins/tui/index.ts +2 -1
- package/plugins/tui/plugin.json +1 -1
- package/plugins/tui/screen.ts +17 -5
- package/plugins/tui/transcript.ts +518 -507
- package/plugins/tui/tui.ts +212 -54
- package/plugins/withdraw/index.ts +111 -0
- package/plugins/withdraw/plugin.json +8 -0
- package/plugins-dist/approval/index.js +103 -9
- package/plugins-dist/approval/plugin.json +4 -1
- package/plugins-dist/approval/policy.js +112 -9
- package/plugins-dist/approval/review.js +141 -34
- package/plugins-dist/ask/index.js +28 -2
- package/plugins-dist/budget/index.js +30 -7
- package/plugins-dist/budget/plugin.json +1 -2
- package/plugins-dist/compact/compact.js +106 -32
- package/plugins-dist/compact/index.js +27 -3
- package/plugins-dist/compact/plugin.json +6 -2
- package/plugins-dist/cost/cache.js +100 -0
- package/plugins-dist/cost/index.js +87 -38
- package/plugins-dist/cost/plugin.json +5 -2
- package/plugins-dist/memory/memory.js +51 -32
- package/plugins-dist/models/configure.js +285 -105
- package/plugins-dist/models/index.js +33 -2
- package/plugins-dist/models/price.js +244 -0
- package/plugins-dist/models/provider.js +22 -4
- package/plugins-dist/models/saved.js +13 -3
- package/plugins-dist/modes/index.js +2 -3
- package/plugins-dist/prompts/prompts.js +5 -1
- package/plugins-dist/task/index.js +25 -7
- package/plugins-dist/task/plugin.json +5 -2
- package/plugins-dist/task/subagent.js +15 -6
- package/plugins-dist/todo/index.js +50 -0
- package/plugins-dist/todo/plugin.json +1 -1
- package/plugins-dist/tui/frontend.js +26 -4
- package/plugins-dist/tui/index.js +2 -1
- package/plugins-dist/tui/plugin.json +2 -1
- package/plugins-dist/tui/screen.js +7 -3
- package/plugins-dist/tui/transcript.js +13 -5
- package/plugins-dist/tui/tui.js +197 -50
- package/plugins-dist/tui/vendor.js +1388 -1088
- package/plugins-dist/withdraw/index.js +88 -0
- package/plugins-dist/withdraw/plugin.json +12 -0
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/src/api.ts +1 -1
- package/src/install.ts +5 -0
package/plugins/cost/index.ts
CHANGED
|
@@ -1,26 +1,31 @@
|
|
|
1
|
-
// jade/cost
|
|
1
|
+
// jade/cost:按单价把会话的 token 用量换算成钱,显示在状态栏上;/cost 列出每个模型用了多少。
|
|
2
2
|
//
|
|
3
|
-
//
|
|
3
|
+
// 单价不内置(价格会变,兼容服务上的模型名也各不相同)。两个来源,前一个优先:
|
|
4
|
+
// - /model 里给模型填的(存在 models.json,可以分时段、用美元或人民币),经 models@1.price 取;
|
|
5
|
+
// - $JADE_HOME/config.json,单位是每百万 token(下面的数字只是示例),currency 不写时是美元:
|
|
4
6
|
//
|
|
5
7
|
// { "jade/cost": { "prices": { "claude-opus": { "input": 15, "output": 75, "cacheRead": 1.5, "cacheWrite": 18.75 } } } }
|
|
6
8
|
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
9
|
+
// 键是模型名或它的前缀(最长的前缀算数);cacheRead、cacheWrite 不写时按 input 算。
|
|
10
|
+
//
|
|
11
|
+
// 每个回复按它的时间(事件的 at)取单价,所以峰谷价按请求发生的时段算。不同货币分开合计,不换算。
|
|
12
|
+
// 没有单价的模型只计 token,不计钱。用量来自日志:模型的每次回复,以及插件自己发的请求(压缩的总结、auto 模式的审查、子 Agent),
|
|
13
|
+
// 后者不知道用的是哪个模型,按会话当前的模型算。状态栏的合计每轮结束时记进 derived,恢复会话后接着算;/cost 每次从整份日志重算。
|
|
10
14
|
|
|
11
15
|
import type { LogEvent, Usage } from "uncarved";
|
|
12
16
|
import { definePlugin } from "@uncarved/jade-api";
|
|
13
|
-
import type { Commands, Models } from "@uncarved/jade-api/services";
|
|
17
|
+
import type { Commands, Cost, Models, Price } from "@uncarved/jade-api/services";
|
|
18
|
+
import { cacheReport, prefixWatcher } from "./cache.ts";
|
|
14
19
|
|
|
15
|
-
export
|
|
16
|
-
input: number;
|
|
17
|
-
output: number;
|
|
18
|
-
cacheRead?: number;
|
|
19
|
-
cacheWrite?: number;
|
|
20
|
-
}
|
|
20
|
+
export type { Price };
|
|
21
21
|
type Totals = Record<string, Required<Usage>>;
|
|
22
|
+
/** 货币 → 金额 */
|
|
23
|
+
type Money = Record<string, number>;
|
|
22
24
|
|
|
23
|
-
|
|
25
|
+
/** 以前的版本在 derived 里记的是 token 合计(Totals),恢复这样的会话时按现在的单价折算 */
|
|
26
|
+
const OLD_KEY = "jade/cost/usage";
|
|
27
|
+
/** 状态栏的合计:货币 → 金额 */
|
|
28
|
+
const KEY = "jade/cost/spent";
|
|
24
29
|
/** 插件自己发的请求没有记模型名时记在这个名字下,算钱时按当前模型 */
|
|
25
30
|
const UNKNOWN = "";
|
|
26
31
|
|
|
@@ -36,7 +41,8 @@ export function parsePrices(value: unknown): Record<string, Price> {
|
|
|
36
41
|
if (input === undefined || output === undefined) continue;
|
|
37
42
|
const cacheRead = num(p.cacheRead);
|
|
38
43
|
const cacheWrite = num(p.cacheWrite);
|
|
39
|
-
|
|
44
|
+
const currency = typeof p.currency === "string" && p.currency.trim() ? p.currency.trim().toUpperCase() : undefined;
|
|
45
|
+
out[model] = { input, output, ...(cacheRead !== undefined ? { cacheRead } : {}), ...(cacheWrite !== undefined ? { cacheWrite } : {}), ...(currency ? { currency } : {}) };
|
|
40
46
|
}
|
|
41
47
|
return out;
|
|
42
48
|
}
|
|
@@ -49,9 +55,12 @@ export function priceOf(prices: Record<string, Price>, model: string): Price | u
|
|
|
49
55
|
}
|
|
50
56
|
|
|
51
57
|
/** 一份用量按单价是多少钱。inputTokens 含缓存命中和写入的部分(Usage 的约定) */
|
|
52
|
-
export function costOf(u:
|
|
53
|
-
const
|
|
54
|
-
|
|
58
|
+
export function costOf(u: Usage, p: Price): number {
|
|
59
|
+
const n = (v: number | undefined) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
60
|
+
const read = n(u.cacheReadTokens);
|
|
61
|
+
const write = n(u.cacheWriteTokens);
|
|
62
|
+
const plain = Math.max(0, n(u.inputTokens) - read - write);
|
|
63
|
+
return (plain * p.input + read * (p.cacheRead ?? p.input) + write * (p.cacheWrite ?? p.input) + n(u.outputTokens) * p.output) / 1_000_000;
|
|
55
64
|
}
|
|
56
65
|
|
|
57
66
|
/** 一个事件带来的用量和它的模型;不带用量的事件 undefined */
|
|
@@ -70,22 +79,42 @@ function add(totals: Totals, model: string, u: Usage): void {
|
|
|
70
79
|
}
|
|
71
80
|
}
|
|
72
81
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
for (const [model, u] of Object.entries(totals)) {
|
|
77
|
-
const p = priceOf(prices, model === UNKNOWN ? (current ?? "") : model);
|
|
78
|
-
if (p) sum = (sum ?? 0) + costOf(u, p);
|
|
79
|
-
}
|
|
80
|
-
return sum;
|
|
82
|
+
function addMoney(to: Money, p: Price, amount: number): void {
|
|
83
|
+
const c = p.currency ?? "USD";
|
|
84
|
+
to[c] = (to[c] ?? 0) + amount;
|
|
81
85
|
}
|
|
82
86
|
|
|
83
|
-
const
|
|
87
|
+
const SYMBOLS: Record<string, string> = { USD: "$", CNY: "¥" };
|
|
88
|
+
const amount = (n: number) => (n < 0.01 && n > 0 ? n.toFixed(4) : n.toFixed(2));
|
|
89
|
+
/** "$0.12 + ¥0.80";没有符号的货币写成 "0.12 EUR" */
|
|
90
|
+
export const money = (m: Money) =>
|
|
91
|
+
Object.entries(m)
|
|
92
|
+
.map(([c, n]) => (SYMBOLS[c] ? `${SYMBOLS[c]}${amount(n)}` : `${amount(n)} ${c}`))
|
|
93
|
+
.join(" + ");
|
|
84
94
|
const tokens = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(2)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
|
|
85
95
|
|
|
96
|
+
/** 取单价:先 models@1.price(/model 里填的),再配置里的。可选服务用的时候再取(设计 3.3) */
|
|
97
|
+
function pricer(config: Record<string, unknown>, models: () => Models | undefined) {
|
|
98
|
+
const prices = parsePrices(config.prices);
|
|
99
|
+
const price = (model: string, at: Date = new Date()): Price | undefined => {
|
|
100
|
+
try {
|
|
101
|
+
const p = models()?.price?.(model, at);
|
|
102
|
+
if (p) return p;
|
|
103
|
+
} catch {
|
|
104
|
+
// 模型插件出错时退回配置里的
|
|
105
|
+
}
|
|
106
|
+
return priceOf(prices, model);
|
|
107
|
+
};
|
|
108
|
+
/** 日志里的模型名;插件自己发的请求按当前模型 */
|
|
109
|
+
const forLogged = (model: string, at: Date) => price(model === UNKNOWN ? (models()?.current()?.model ?? "") : model, at);
|
|
110
|
+
return { price, forLogged };
|
|
111
|
+
}
|
|
112
|
+
|
|
86
113
|
export default definePlugin({
|
|
87
114
|
process(ctx) {
|
|
88
|
-
const
|
|
115
|
+
const { price, forLogged } = pricer(ctx.config, () => ctx.service<Models>("models@1"));
|
|
116
|
+
// jade/compact 按缓存价和原价的比例判断提前清理划不划算
|
|
117
|
+
ctx.provide("cost@1", { price } satisfies Cost);
|
|
89
118
|
ctx.service<Commands>("commands@1")?.register({
|
|
90
119
|
name: "cost",
|
|
91
120
|
description: "show this session's token usage per model, and what it cost at the configured prices",
|
|
@@ -94,48 +123,77 @@ export default definePlugin({
|
|
|
94
123
|
const s = sessions.current;
|
|
95
124
|
if (!s) return "No session is open.";
|
|
96
125
|
const totals: Totals = {};
|
|
97
|
-
|
|
126
|
+
const spent: Record<string, Money> = {};
|
|
127
|
+
const history = await s.history();
|
|
128
|
+
for (const e of history) {
|
|
98
129
|
const u = usageIn(e);
|
|
99
|
-
if (u)
|
|
130
|
+
if (!u) continue;
|
|
131
|
+
add(totals, u.model, u.usage);
|
|
132
|
+
const p = forLogged(u.model, new Date(e.at));
|
|
133
|
+
if (p) addMoney((spent[u.model] ??= {}), p, costOf(u.usage, p));
|
|
100
134
|
}
|
|
101
|
-
const current = ctx.service<Models>("models@1")?.current()?.model;
|
|
102
135
|
const rows = Object.entries(totals).map(([model, u]) => {
|
|
103
|
-
const p = priceOf(prices, model === UNKNOWN ? (current ?? "") : model);
|
|
104
136
|
const cached = u.cacheReadTokens ? `, ${tokens(u.cacheReadTokens)} from cache` : "";
|
|
105
|
-
return `${model === UNKNOWN ? "plugin requests (compaction, review, sub-agents)" : model}: ${tokens(u.inputTokens)} in${cached}, ${tokens(u.outputTokens)} out${
|
|
137
|
+
return `${model === UNKNOWN ? "plugin requests (compaction, review, sub-agents)" : model}: ${tokens(u.inputTokens)} in${cached}, ${tokens(u.outputTokens)} out${spent[model] ? ` · ${money(spent[model])}` : ""}`;
|
|
106
138
|
});
|
|
107
139
|
if (rows.length === 0) return "No model usage in this session yet.";
|
|
108
|
-
const sum =
|
|
109
|
-
const
|
|
110
|
-
const
|
|
111
|
-
|
|
140
|
+
const sum: Money = {};
|
|
141
|
+
for (const m of Object.values(spent)) for (const [c, n] of Object.entries(m)) sum[c] = (sum[c] ?? 0) + n;
|
|
142
|
+
const priced = Object.keys(sum).length > 0;
|
|
143
|
+
const hint = `No price is set for ${priced ? "some of these models" : "these models"}: set one in /model (Manage models… → the model → Settings… → Price), or add {"jade/cost": {"prices": {"<model name or prefix>": {"input": <per million tokens>, "output": <…>, "currency": "USD"}}}} to ${ctx.home}/config.json`;
|
|
144
|
+
const unpriced = Object.keys(totals).some((m) => !spent[m]);
|
|
145
|
+
return [...rows, ...(priced ? [`Total: ${money(sum)}`] : []), ...cacheReport(history, `${ctx.plugin}/prefix`), ...(unpriced ? [hint] : [])].join("\n");
|
|
112
146
|
},
|
|
113
147
|
});
|
|
114
148
|
},
|
|
115
149
|
|
|
116
150
|
session(ctx) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
151
|
+
// 最后一个改请求的 hook 之后看前缀有没有沿用上一次的(见 cache.ts);子 Agent 也记,事后查日志用
|
|
152
|
+
const watch = prefixWatcher();
|
|
153
|
+
ctx.kernel.hook({
|
|
154
|
+
kind: "transform",
|
|
155
|
+
point: "model.before",
|
|
156
|
+
order: 1000,
|
|
157
|
+
optional: true,
|
|
158
|
+
fn: async (req, hook) => {
|
|
159
|
+
const change = watch(req);
|
|
160
|
+
if (change) await hook.emit("prefix", change);
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
// 前端没有状态栏:不用算
|
|
164
|
+
if (!ctx.status) return;
|
|
165
|
+
const { forLogged } = pricer(ctx.config, () => ctx.service<Models>("models@1"));
|
|
166
|
+
let spent: Money | undefined;
|
|
167
|
+
/** 上次记进 derived 之后又算了钱:没有单价时不往日志里写空的合计 */
|
|
168
|
+
let dirty = false;
|
|
169
|
+
const show = () => ctx.status?.(spent && Object.keys(spent).length ? money(spent) : undefined);
|
|
126
170
|
ctx.kernel.hook({
|
|
127
171
|
kind: "observe",
|
|
128
172
|
point: "event",
|
|
129
173
|
fn: async (e, hook) => {
|
|
130
174
|
// 恢复的会话:从上次记下的合计接着算
|
|
131
|
-
|
|
175
|
+
if (!spent) {
|
|
176
|
+
const saved = hook.derived[KEY] as Money | undefined;
|
|
177
|
+
spent = saved ? { ...saved } : {};
|
|
178
|
+
if (!saved) {
|
|
179
|
+
for (const [model, u] of Object.entries((hook.derived[OLD_KEY] as Totals | undefined) ?? {})) {
|
|
180
|
+
const p = forLogged(model, new Date());
|
|
181
|
+
if (p) addMoney(spent, p, costOf(u, p));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
show();
|
|
185
|
+
}
|
|
132
186
|
const u = usageIn(e);
|
|
133
187
|
if (u) {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
188
|
+
const p = forLogged(u.model, new Date(e.at));
|
|
189
|
+
if (p) {
|
|
190
|
+
addMoney(spent, p, costOf(u.usage, p));
|
|
191
|
+
dirty = true;
|
|
192
|
+
show();
|
|
193
|
+
}
|
|
194
|
+
} else if (e.type === "turn.ended" && dirty) {
|
|
195
|
+
dirty = false;
|
|
196
|
+
await hook.record(KEY, spent);
|
|
139
197
|
}
|
|
140
198
|
},
|
|
141
199
|
});
|
package/plugins/cost/plugin.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "jade/cost",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"api": "^1",
|
|
5
5
|
"entry": "./index.ts",
|
|
6
|
+
"provides": ["cost@1"],
|
|
6
7
|
"optional": ["commands@1", "models@1"],
|
|
7
8
|
"config": {
|
|
8
9
|
"prices": {
|
|
9
10
|
"default": {},
|
|
10
|
-
"description": "prices
|
|
11
|
+
"description": "prices per million tokens, by model name or name prefix: { \"<model>\": { \"input\": 3, \"output\": 15, \"cacheRead\": 0.3, \"cacheWrite\": 3.75, \"currency\": \"USD\" } } (currency defaults to USD). A price set for a model in /model (which can change by time of day) takes precedence; models without a price are counted in tokens only"
|
|
11
12
|
}
|
|
12
13
|
}
|
|
13
14
|
}
|
package/plugins/memory/memory.ts
CHANGED
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
// 模型用 memory 工具增删改,用户用 /memory 查看和管理。从旧 jade 的 memory.ts 移植,文件位置不变。
|
|
7
7
|
// 每条前面是保存它的日期("- [2026-11-25] 内容"),由代码写,模型据此判断旧不旧;没有日期的旧条目照常读。
|
|
8
8
|
|
|
9
|
-
import { createHash } from "node:crypto";
|
|
9
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
10
10
|
import { existsSync, realpathSync } from "node:fs";
|
|
11
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
11
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
12
12
|
import path from "node:path";
|
|
13
13
|
import type { Tool } from "uncarved";
|
|
14
14
|
|
|
@@ -33,6 +33,20 @@ const localDate = () => {
|
|
|
33
33
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
|
34
34
|
};
|
|
35
35
|
const size = (entries: MemoryEntry[]) => entries.reduce((n, e) => n + e.text.length, 0);
|
|
36
|
+
/**
|
|
37
|
+
* 每个记忆文件上正在进行的改动。同一进程里的几个会话(各有一个 Memory)同时改同一个文件时依次进行,
|
|
38
|
+
* 否则后读的会覆盖先写的
|
|
39
|
+
*/
|
|
40
|
+
const pending = new Map<string, Promise<unknown>>();
|
|
41
|
+
function serialized<T>(file: string, fn: () => Promise<T>): Promise<T> {
|
|
42
|
+
const p = (pending.get(file) ?? Promise.resolve()).then(fn, fn);
|
|
43
|
+
const tail = p.catch(() => {});
|
|
44
|
+
pending.set(file, tail);
|
|
45
|
+
void tail.then(() => {
|
|
46
|
+
if (pending.get(file) === tail) pending.delete(file);
|
|
47
|
+
});
|
|
48
|
+
return p;
|
|
49
|
+
}
|
|
36
50
|
const render = (entries: MemoryEntry[]) => entries.map((e) => (e.date ? `- [${e.date}] ${e.text}` : `- ${e.text}`)).join("\n");
|
|
37
51
|
|
|
38
52
|
export class Memory {
|
|
@@ -68,37 +82,43 @@ export class Memory {
|
|
|
68
82
|
}
|
|
69
83
|
|
|
70
84
|
/** 加一条;已经有同样的一条时不重复。返回是否加入 */
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
85
|
+
add(scope: MemoryScope, text: string): Promise<boolean> {
|
|
86
|
+
return serialized(this.files[scope], async () => {
|
|
87
|
+
const entry = this.#check(text);
|
|
88
|
+
const all = await this.entries(scope);
|
|
89
|
+
if (all.some((e) => e.text === entry)) return false;
|
|
90
|
+
const after = [...all, { text: entry, date: this.#today() }];
|
|
91
|
+
this.#fits(scope, all, after);
|
|
92
|
+
await this.#write(scope, after);
|
|
93
|
+
return true;
|
|
94
|
+
});
|
|
79
95
|
}
|
|
80
96
|
|
|
81
97
|
/** 删掉内容完全相同的一条,或者唯一包含 text 的那一条。返回删掉的那条 */
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
98
|
+
remove(scope: MemoryScope, text: string): Promise<string | undefined> {
|
|
99
|
+
return serialized(this.files[scope], async () => {
|
|
100
|
+
const all = await this.entries(scope);
|
|
101
|
+
const i = this.#find(scope, all, text);
|
|
102
|
+
if (i < 0) return undefined;
|
|
103
|
+
const [removed] = all.splice(i, 1);
|
|
104
|
+
await this.#write(scope, all);
|
|
105
|
+
return removed!.text;
|
|
106
|
+
});
|
|
89
107
|
}
|
|
90
108
|
|
|
91
109
|
/** 把 old 指的那条(找法同 remove)原地换成 text,日期更新。返回被换掉的那条;找不到时返回 undefined */
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
110
|
+
replace(scope: MemoryScope, old: string, text: string): Promise<string | undefined> {
|
|
111
|
+
return serialized(this.files[scope], async () => {
|
|
112
|
+
const entry = this.#check(text);
|
|
113
|
+
const all = await this.entries(scope);
|
|
114
|
+
const i = this.#find(scope, all, old);
|
|
115
|
+
if (i < 0) return undefined;
|
|
116
|
+
if (all.some((e, j) => j !== i && e.text === entry)) throw new Error(`the ${scope} memory already has "${entry}"; remove the old one instead`);
|
|
117
|
+
const after = all.with(i, { text: entry, date: this.#today() });
|
|
118
|
+
this.#fits(scope, all, after);
|
|
119
|
+
await this.#write(scope, after);
|
|
120
|
+
return all[i]!.text;
|
|
121
|
+
});
|
|
102
122
|
}
|
|
103
123
|
|
|
104
124
|
/** 系统提示词里的一段;没有记忆时返回 undefined */
|
|
@@ -147,7 +167,10 @@ export class Memory {
|
|
|
147
167
|
async #write(scope: MemoryScope, entries: MemoryEntry[]) {
|
|
148
168
|
const file = this.files[scope];
|
|
149
169
|
await mkdir(path.dirname(file), { recursive: true });
|
|
150
|
-
|
|
170
|
+
// 先写临时文件再改名:别的进程(另一个 jade)读到的不会是写了一半的文件
|
|
171
|
+
const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
172
|
+
await writeFile(tmp, entries.length ? render(entries) + "\n" : "");
|
|
173
|
+
await rename(tmp, file);
|
|
151
174
|
}
|
|
152
175
|
}
|
|
153
176
|
|