@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.
Files changed (78) hide show
  1. package/README.md +14 -11
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/install.js +5 -0
  5. package/dist/install.js.map +1 -1
  6. package/package.json +6 -6
  7. package/plugins/approval/index.ts +129 -13
  8. package/plugins/approval/plugin.json +4 -1
  9. package/plugins/approval/policy.ts +127 -7
  10. package/plugins/approval/review.ts +188 -45
  11. package/plugins/ask/index.ts +29 -1
  12. package/plugins/budget/index.ts +44 -6
  13. package/plugins/budget/plugin.json +1 -2
  14. package/plugins/compact/compact.ts +153 -39
  15. package/plugins/compact/index.ts +39 -5
  16. package/plugins/compact/plugin.json +5 -2
  17. package/plugins/cost/cache.ts +114 -0
  18. package/plugins/cost/index.ts +109 -51
  19. package/plugins/cost/plugin.json +3 -2
  20. package/plugins/memory/memory.ts +51 -28
  21. package/plugins/models/configure.ts +344 -125
  22. package/plugins/models/index.ts +44 -9
  23. package/plugins/models/price.ts +291 -0
  24. package/plugins/models/provider.ts +40 -8
  25. package/plugins/models/saved.ts +20 -4
  26. package/plugins/modes/index.ts +3 -4
  27. package/plugins/prompts/prompts.ts +5 -1
  28. package/plugins/task/index.ts +31 -10
  29. package/plugins/task/plugin.json +5 -2
  30. package/plugins/task/subagent.ts +21 -4
  31. package/plugins/todo/index.ts +62 -1
  32. package/plugins/todo/plugin.json +1 -1
  33. package/plugins/tui/frontend.ts +31 -5
  34. package/plugins/tui/index.ts +2 -1
  35. package/plugins/tui/plugin.json +1 -1
  36. package/plugins/tui/screen.ts +17 -5
  37. package/plugins/tui/transcript.ts +518 -507
  38. package/plugins/tui/tui.ts +212 -54
  39. package/plugins/withdraw/index.ts +111 -0
  40. package/plugins/withdraw/plugin.json +8 -0
  41. package/plugins-dist/approval/index.js +103 -9
  42. package/plugins-dist/approval/plugin.json +4 -1
  43. package/plugins-dist/approval/policy.js +112 -9
  44. package/plugins-dist/approval/review.js +141 -34
  45. package/plugins-dist/ask/index.js +28 -2
  46. package/plugins-dist/budget/index.js +30 -7
  47. package/plugins-dist/budget/plugin.json +1 -2
  48. package/plugins-dist/compact/compact.js +106 -32
  49. package/plugins-dist/compact/index.js +27 -3
  50. package/plugins-dist/compact/plugin.json +6 -2
  51. package/plugins-dist/cost/cache.js +100 -0
  52. package/plugins-dist/cost/index.js +87 -38
  53. package/plugins-dist/cost/plugin.json +5 -2
  54. package/plugins-dist/memory/memory.js +51 -32
  55. package/plugins-dist/models/configure.js +285 -105
  56. package/plugins-dist/models/index.js +33 -2
  57. package/plugins-dist/models/price.js +244 -0
  58. package/plugins-dist/models/provider.js +22 -4
  59. package/plugins-dist/models/saved.js +13 -3
  60. package/plugins-dist/modes/index.js +2 -3
  61. package/plugins-dist/prompts/prompts.js +5 -1
  62. package/plugins-dist/task/index.js +25 -7
  63. package/plugins-dist/task/plugin.json +5 -2
  64. package/plugins-dist/task/subagent.js +15 -6
  65. package/plugins-dist/todo/index.js +50 -0
  66. package/plugins-dist/todo/plugin.json +1 -1
  67. package/plugins-dist/tui/frontend.js +26 -4
  68. package/plugins-dist/tui/index.js +2 -1
  69. package/plugins-dist/tui/plugin.json +2 -1
  70. package/plugins-dist/tui/screen.js +7 -3
  71. package/plugins-dist/tui/transcript.js +13 -5
  72. package/plugins-dist/tui/tui.js +197 -50
  73. package/plugins-dist/tui/vendor.js +1388 -1088
  74. package/plugins-dist/withdraw/index.js +88 -0
  75. package/plugins-dist/withdraw/plugin.json +12 -0
  76. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  77. package/src/api.ts +1 -1
  78. package/src/install.ts +5 -0
@@ -1,5 +1,7 @@
1
1
  import { definePlugin } from "@uncarved/jade-api";
2
- const KEY = "jade/cost/usage";
2
+ import { cacheReport, prefixWatcher } from "./cache.js";
3
+ const OLD_KEY = "jade/cost/usage";
4
+ const KEY = "jade/cost/spent";
3
5
  const UNKNOWN = "";
4
6
  export function parsePrices(value) {
5
7
  const out = {};
@@ -14,7 +16,8 @@ export function parsePrices(value) {
14
16
  continue;
15
17
  const cacheRead = num(p.cacheRead);
16
18
  const cacheWrite = num(p.cacheWrite);
17
- out[model] = { input, output, ...cacheRead !== undefined ? { cacheRead } : {}, ...cacheWrite !== undefined ? { cacheWrite } : {} };
19
+ const currency = typeof p.currency === "string" && p.currency.trim() ? p.currency.trim().toUpperCase() : undefined;
20
+ out[model] = { input, output, ...cacheRead !== undefined ? { cacheRead } : {}, ...cacheWrite !== undefined ? { cacheWrite } : {}, ...currency ? { currency } : {} };
18
21
  }
19
22
  return out;
20
23
  }
@@ -26,8 +29,11 @@ export function priceOf(prices, model) {
26
29
  return best === undefined ? undefined : prices[best];
27
30
  }
28
31
  export function costOf(u, p) {
29
- const plain = Math.max(0, u.inputTokens - u.cacheReadTokens - u.cacheWriteTokens);
30
- return (plain * p.input + u.cacheReadTokens * (p.cacheRead ?? p.input) + u.cacheWriteTokens * (p.cacheWrite ?? p.input) + u.outputTokens * p.output) / 1e6;
32
+ const n = (v) => typeof v === "number" && Number.isFinite(v) ? v : 0;
33
+ const read = n(u.cacheReadTokens);
34
+ const write = n(u.cacheWriteTokens);
35
+ const plain = Math.max(0, n(u.inputTokens) - read - write);
36
+ return (plain * p.input + read * (p.cacheRead ?? p.input) + write * (p.cacheWrite ?? p.input) + n(u.outputTokens) * p.output) / 1e6;
31
37
  }
32
38
  function usageIn(e) {
33
39
  const usage = e.data?.usage;
@@ -45,20 +51,31 @@ function add(totals, model, u) {
45
51
  t[k] += v;
46
52
  }
47
53
  }
48
- function total(totals, prices, current) {
49
- let sum;
50
- for (const [model, u] of Object.entries(totals)) {
51
- const p = priceOf(prices, model === UNKNOWN ? current ?? "" : model);
52
- if (p)
53
- sum = (sum ?? 0) + costOf(u, p);
54
- }
55
- return sum;
54
+ function addMoney(to, p, amount) {
55
+ const c = p.currency ?? "USD";
56
+ to[c] = (to[c] ?? 0) + amount;
56
57
  }
57
- const money = (n) => `$${n < 0.01 && n > 0 ? n.toFixed(4) : n.toFixed(2)}`;
58
+ const SYMBOLS = { USD: "$", CNY: "¥" };
59
+ const amount = (n) => n < 0.01 && n > 0 ? n.toFixed(4) : n.toFixed(2);
60
+ export const money = (m) => Object.entries(m).map(([c, n]) => SYMBOLS[c] ? `${SYMBOLS[c]}${amount(n)}` : `${amount(n)} ${c}`).join(" + ");
58
61
  const tokens = (n) => n >= 1e6 ? `${(n / 1e6).toFixed(2)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);
62
+ function pricer(config, models) {
63
+ const prices = parsePrices(config.prices);
64
+ const price = (model, at = new Date) => {
65
+ try {
66
+ const p = models()?.price?.(model, at);
67
+ if (p)
68
+ return p;
69
+ } catch {}
70
+ return priceOf(prices, model);
71
+ };
72
+ const forLogged = (model, at) => price(model === UNKNOWN ? models()?.current()?.model ?? "" : model, at);
73
+ return { price, forLogged };
74
+ }
59
75
  export default definePlugin({
60
76
  process(ctx) {
61
- const prices = parsePrices(ctx.config.prices);
77
+ const { price, forLogged } = pricer(ctx.config, () => ctx.service("models@1"));
78
+ ctx.provide("cost@1", { price });
62
79
  ctx.service("commands@1")?.register({
63
80
  name: "cost",
64
81
  description: "show this session's token usage per model, and what it cost at the configured prices",
@@ -68,49 +85,81 @@ export default definePlugin({
68
85
  if (!s)
69
86
  return "No session is open.";
70
87
  const totals = {};
71
- for (const e of await s.history()) {
88
+ const spent = {};
89
+ const history = await s.history();
90
+ for (const e of history) {
72
91
  const u = usageIn(e);
73
- if (u)
74
- add(totals, u.model, u.usage);
92
+ if (!u)
93
+ continue;
94
+ add(totals, u.model, u.usage);
95
+ const p = forLogged(u.model, new Date(e.at));
96
+ if (p)
97
+ addMoney(spent[u.model] ??= {}, p, costOf(u.usage, p));
75
98
  }
76
- const current = ctx.service("models@1")?.current()?.model;
77
99
  const rows = Object.entries(totals).map(([model, u]) => {
78
- const p = priceOf(prices, model === UNKNOWN ? current ?? "" : model);
79
100
  const cached = u.cacheReadTokens ? `, ${tokens(u.cacheReadTokens)} from cache` : "";
80
- return `${model === UNKNOWN ? "plugin requests (compaction, review, sub-agents)" : model}: ${tokens(u.inputTokens)} in${cached}, ${tokens(u.outputTokens)} out${p ? ` · ${money(costOf(u, p))}` : ""}`;
101
+ return `${model === UNKNOWN ? "plugin requests (compaction, review, sub-agents)" : model}: ${tokens(u.inputTokens)} in${cached}, ${tokens(u.outputTokens)} out${spent[model] ? ` · ${money(spent[model])}` : ""}`;
81
102
  });
82
103
  if (rows.length === 0)
83
104
  return "No model usage in this session yet.";
84
- const sum = total(totals, prices, current);
85
- const hint = `No price is configured for ${sum === undefined ? "these models" : "some of these models"}: add {"jade/cost": {"prices": {"<model name or prefix>": {"input": <$ per million tokens>, "output": <$>}}}} to ${ctx.home}/config.json`;
86
- const unpriced = Object.keys(totals).some((m) => !priceOf(prices, m === UNKNOWN ? current ?? "" : m));
87
- return [...rows, ...sum !== undefined ? [`Total: ${money(sum)}`] : [], ...unpriced ? [hint] : []].join(`
105
+ const sum = {};
106
+ for (const m of Object.values(spent))
107
+ for (const [c, n] of Object.entries(m))
108
+ sum[c] = (sum[c] ?? 0) + n;
109
+ const priced = Object.keys(sum).length > 0;
110
+ 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`;
111
+ const unpriced = Object.keys(totals).some((m) => !spent[m]);
112
+ return [...rows, ...priced ? [`Total: ${money(sum)}`] : [], ...cacheReport(history, `${ctx.plugin}/prefix`), ...unpriced ? [hint] : []].join(`
88
113
  `);
89
114
  }
90
115
  });
91
116
  },
92
117
  session(ctx) {
93
- const prices = parsePrices(ctx.config.prices);
94
- if (Object.keys(prices).length === 0 || !ctx.status)
118
+ const watch = prefixWatcher();
119
+ ctx.kernel.hook({
120
+ kind: "transform",
121
+ point: "model.before",
122
+ order: 1000,
123
+ optional: true,
124
+ fn: async (req, hook) => {
125
+ const change = watch(req);
126
+ if (change)
127
+ await hook.emit("prefix", change);
128
+ }
129
+ });
130
+ if (!ctx.status)
95
131
  return;
96
- const models = ctx.service("models@1");
97
- let totals;
98
- const show = () => {
99
- const sum = total(totals ?? {}, prices, models?.current()?.model);
100
- ctx.status?.(sum === undefined ? undefined : money(sum));
101
- };
132
+ const { forLogged } = pricer(ctx.config, () => ctx.service("models@1"));
133
+ let spent;
134
+ let dirty = false;
135
+ const show = () => ctx.status?.(spent && Object.keys(spent).length ? money(spent) : undefined);
102
136
  ctx.kernel.hook({
103
137
  kind: "observe",
104
138
  point: "event",
105
139
  fn: async (e, hook) => {
106
- totals ??= structuredClone(hook.derived[KEY] ?? {});
140
+ if (!spent) {
141
+ const saved = hook.derived[KEY];
142
+ spent = saved ? { ...saved } : {};
143
+ if (!saved) {
144
+ for (const [model, u] of Object.entries(hook.derived[OLD_KEY] ?? {})) {
145
+ const p = forLogged(model, new Date);
146
+ if (p)
147
+ addMoney(spent, p, costOf(u, p));
148
+ }
149
+ }
150
+ show();
151
+ }
107
152
  const u = usageIn(e);
108
153
  if (u) {
109
- add(totals, u.model, u.usage);
110
- show();
111
- } else if (e.type === "turn.ended") {
112
- show();
113
- await hook.record(KEY, totals);
154
+ const p = forLogged(u.model, new Date(e.at));
155
+ if (p) {
156
+ addMoney(spent, p, costOf(u.usage, p));
157
+ dirty = true;
158
+ show();
159
+ }
160
+ } else if (e.type === "turn.ended" && dirty) {
161
+ dirty = false;
162
+ await hook.record(KEY, spent);
114
163
  }
115
164
  }
116
165
  });
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "id": "jade/cost",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.js",
6
+ "provides": [
7
+ "cost@1"
8
+ ],
6
9
  "optional": [
7
10
  "commands@1",
8
11
  "models@1"
@@ -10,7 +13,7 @@
10
13
  "config": {
11
14
  "prices": {
12
15
  "default": {},
13
- "description": "prices in $ per million tokens, by model name or name prefix: { \"<model>\": { \"input\": 3, \"output\": 15, \"cacheRead\": 0.3, \"cacheWrite\": 3.75 } }; models without a price are counted in tokens only"
16
+ "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"
14
17
  }
15
18
  }
16
19
  }
@@ -1,6 +1,6 @@
1
- import { createHash } from "node:crypto";
1
+ import { createHash, randomBytes } from "node:crypto";
2
2
  import { existsSync, realpathSync } from "node:fs";
3
- import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  export const MEMORY_SCOPES = ["user", "project"];
6
6
  const MAX_SCOPE_CHARS = 4000;
@@ -12,6 +12,17 @@ const localDate = () => {
12
12
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
13
13
  };
14
14
  const size = (entries) => entries.reduce((n, e) => n + e.text.length, 0);
15
+ const pending = new Map;
16
+ function serialized(file, fn) {
17
+ const p = (pending.get(file) ?? Promise.resolve()).then(fn, fn);
18
+ const tail = p.catch(() => {});
19
+ pending.set(file, tail);
20
+ tail.then(() => {
21
+ if (pending.get(file) === tail)
22
+ pending.delete(file);
23
+ });
24
+ return p;
25
+ }
15
26
  const render = (entries) => entries.map((e) => e.date ? `- [${e.date}] ${e.text}` : `- ${e.text}`).join(`
16
27
  `);
17
28
 
@@ -37,37 +48,43 @@ export class Memory {
37
48
  return m ? { text: m[2], date: m[1] } : { text: l };
38
49
  });
39
50
  }
40
- async add(scope, text) {
41
- const entry = this.#check(text);
42
- const all = await this.entries(scope);
43
- if (all.some((e) => e.text === entry))
44
- return false;
45
- const after = [...all, { text: entry, date: this.#today() }];
46
- this.#fits(scope, all, after);
47
- await this.#write(scope, after);
48
- return true;
51
+ add(scope, text) {
52
+ return serialized(this.files[scope], async () => {
53
+ const entry = this.#check(text);
54
+ const all = await this.entries(scope);
55
+ if (all.some((e) => e.text === entry))
56
+ return false;
57
+ const after = [...all, { text: entry, date: this.#today() }];
58
+ this.#fits(scope, all, after);
59
+ await this.#write(scope, after);
60
+ return true;
61
+ });
49
62
  }
50
- async remove(scope, text) {
51
- const all = await this.entries(scope);
52
- const i = this.#find(scope, all, text);
53
- if (i < 0)
54
- return;
55
- const [removed] = all.splice(i, 1);
56
- await this.#write(scope, all);
57
- return removed.text;
63
+ remove(scope, text) {
64
+ return serialized(this.files[scope], async () => {
65
+ const all = await this.entries(scope);
66
+ const i = this.#find(scope, all, text);
67
+ if (i < 0)
68
+ return;
69
+ const [removed] = all.splice(i, 1);
70
+ await this.#write(scope, all);
71
+ return removed.text;
72
+ });
58
73
  }
59
- async replace(scope, old, text) {
60
- const entry = this.#check(text);
61
- const all = await this.entries(scope);
62
- const i = this.#find(scope, all, old);
63
- if (i < 0)
64
- return;
65
- if (all.some((e, j) => j !== i && e.text === entry))
66
- throw new Error(`the ${scope} memory already has "${entry}"; remove the old one instead`);
67
- const after = all.with(i, { text: entry, date: this.#today() });
68
- this.#fits(scope, all, after);
69
- await this.#write(scope, after);
70
- return all[i].text;
74
+ replace(scope, old, text) {
75
+ return serialized(this.files[scope], async () => {
76
+ const entry = this.#check(text);
77
+ const all = await this.entries(scope);
78
+ const i = this.#find(scope, all, old);
79
+ if (i < 0)
80
+ return;
81
+ if (all.some((e, j) => j !== i && e.text === entry))
82
+ throw new Error(`the ${scope} memory already has "${entry}"; remove the old one instead`);
83
+ const after = all.with(i, { text: entry, date: this.#today() });
84
+ this.#fits(scope, all, after);
85
+ await this.#write(scope, after);
86
+ return all[i].text;
87
+ });
71
88
  }
72
89
  async prompt() {
73
90
  const sections = [];
@@ -112,8 +129,10 @@ ${render(all)}`);
112
129
  async#write(scope, entries) {
113
130
  const file = this.files[scope];
114
131
  await mkdir(path.dirname(file), { recursive: true });
115
- await writeFile(file, entries.length ? render(entries) + `
132
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
133
+ await writeFile(tmp, entries.length ? render(entries) + `
116
134
  ` : "");
135
+ await rename(tmp, file);
117
136
  }
118
137
  }
119
138
  export function projectKey(root) {