aegiscode 7.0.26 → 7.0.28
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/SOURCE-OFFER.txt +9 -0
- package/package.json +4 -7
- package/scripts/check.mjs +1 -52
- package/scripts/demo.mjs +1 -94
- package/scripts/predist.mjs +1 -75
- package/scripts/runtests.mjs +1 -56
- package/scripts/seal-gate.mjs +1 -74
- package/src/agents.js +1 -139
- package/src/app.js +1 -2957
- package/src/art.js +1 -289
- package/src/chatflow.js +1 -3023
- package/src/checkpoint.js +1 -90
- package/src/clipboard.js +1 -424
- package/src/cloudsync.js +1 -528
- package/src/commands.js +1 -4089
- package/src/config.js +1 -581
- package/src/connect.js +1 -349
- package/src/credentials.js +1 -33
- package/src/deps.js +1 -232
- package/src/devrun.js +1 -187
- package/src/diff.js +1 -333
- package/src/diffview.js +1 -296
- package/src/engine.js +1 -297
- package/src/entitlement.js +1 -355
- package/src/events.js +1 -707
- package/src/export.js +1 -67
- package/src/filepreview.js +1 -153
- package/src/fingerprint.js +1 -592
- package/src/format.js +1 -259
- package/src/fuzzy.js +1 -119
- package/src/history.js +1 -423
- package/src/init.js +1 -175
- package/src/input.js +1 -139
- package/src/keys.js +1 -183
- package/src/markdown.js +1 -306
- package/src/models.js +1 -507
- package/src/naming.js +1 -57
- package/src/overlays.js +1 -462
- package/src/panels.js +1 -1418
- package/src/ping.js +1 -226
- package/src/presence.js +1 -238
- package/src/render.js +1 -516
- package/src/screen.js +1 -518
- package/src/screens.js +1 -896
- package/src/secret.js +1 -59
- package/src/securefs.js +1 -359
- package/src/settings.js +1 -155
- package/src/shared.js +1 -52
- package/src/sharedpaths.js +1 -53
- package/src/signup.js +1 -156
- package/src/summarize.js +1 -95
- package/src/sysdiag.js +1 -585
- package/src/system.js +1 -40
- package/src/theme.js +1 -570
- package/src/title.js +1 -220
- package/src/todos.js +1 -115
- package/src/tokens.js +1 -263
- package/src/topup.js +1 -210
- package/src/update.js +1 -191
- package/vendor/client/aegis.js +1 -2441
- package/vendor/client/attest.js +1 -518
- package/vendor/client/authorship-key.js +1 -410
- package/vendor/client/auto-provision.js +1 -134
- package/vendor/client/brain-catalog.js +1 -268
- package/vendor/client/byok-catalog.js +1 -199
- package/vendor/client/catalog-client.js +1 -487
- package/vendor/client/conversation-export.js +1 -177
- package/vendor/client/credentials.js +1 -494
- package/vendor/client/device-fingerprint.js +1 -141
- package/vendor/client/drive-connect.js +1 -110
- package/vendor/client/drive-upload.js +1 -234
- package/vendor/client/env-file.js +1 -1273
- package/vendor/client/fingerprint.js +1 -1064
- package/vendor/client/foreign-memory.js +1 -669
- package/vendor/client/google-signin.js +1 -133
- package/vendor/client/hooks.js +1 -430
- package/vendor/client/model-discovery.js +1 -373
- package/vendor/client/naming.js +1 -283
- package/vendor/client/platform.js +1 -937
- package/vendor/client/prefs.js +1 -351
- package/vendor/client/presence-constants.js +1 -107
- package/vendor/client/presence.js +1 -438
- package/vendor/client/record-vault.js +3 -1055
- package/vendor/client/session-store.js +1 -575
- package/vendor/client/topup.js +1 -297
- package/vendor/client/touch.js +1 -458
- package/vendor/client/update.js +1 -763
- package/vendor/client/user-models.js +1 -381
- package/vendor/desktop/lib/local/agents.js +1 -105
- package/vendor/desktop/lib/local/attachments.js +1 -276
- package/vendor/desktop/lib/local/autonomous.js +1 -1045
- package/vendor/desktop/lib/local/claude-pro.js +1 -1028
- package/vendor/desktop/lib/local/context.js +1 -125
- package/vendor/desktop/lib/local/engine.js +1 -3666
- package/vendor/desktop/lib/local/entitlement.js +1 -660
- package/vendor/desktop/lib/local/exec-plan.js +1 -269
- package/vendor/desktop/lib/local/git-scope.js +1 -228
- package/vendor/desktop/lib/local/integrity.js +1 -163
- package/vendor/desktop/lib/local/local.js +1 -2145
- package/vendor/desktop/lib/local/prompt.js +1 -280
- package/vendor/desktop/lib/local/queue.js +1 -560
- package/vendor/desktop/lib/local/session-rounds.js +1 -238
- package/vendor/desktop/lib/local/shell.js +1 -712
- package/vendor/desktop/lib/local/spill.js +1 -75
- package/vendor/desktop/lib/local/tools.js +1 -1328
- package/vendor/desktop/lib/local/turn-guard.js +1 -300
- package/vendor/desktop/lib/local/worktree-lock.js +1 -235
- package/vendor/desktop/lib/settings.js +1 -890
- package/vendor/desktop/main.js +1 -4890
- package/vendor/desktop/renderer/usage.js +1 -1239
- package/vendor/hosts/install.js +1 -638
- package/vendor/hosts/openai-shim.js +1 -515
- package/vendor/hosts/spec.js +1 -164
- package/vendor/hosts/targets.js +1 -346
- package/vendor/mcp/server.js +1 -221
- package/vendor/mcp/tools.js +1 -408
- package/vendor/one/src/child.js +1 -285
- package/vendor/one/src/permissions.js +1 -383
package/src/title.js
CHANGED
|
@@ -1,222 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
|
|
4
|
-
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
-
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* The terminal title bar — the session's *topic*.
|
|
10
|
-
*
|
|
11
|
-
* Claude Code keeps the window/tab title pointed at what the session is about
|
|
12
|
-
* ("✳ Fixing the nexus hang") rather than at a static product string, so a row
|
|
13
|
-
* of terminal tabs is readable at a glance. This host shipped the static half
|
|
14
|
-
* only: `chatflow.js`'s `setTitle()` wrote "AEGIS Code" forever, spinning a
|
|
15
|
-
* braille frame while a turn ran and never naming the work. Every tab of every
|
|
16
|
-
* session read the same, which is exactly the problem the topic solves.
|
|
17
|
-
*
|
|
18
|
-
* The topic is derived from the user's own prompt, locally — no model call, so
|
|
19
|
-
* it costs nothing, adds no latency to the first frame, and cannot invent a
|
|
20
|
-
* task the user never asked for. It is re-derived per prompt and adopted only
|
|
21
|
-
* when the ask is about something new (`adoptTopic`), so a follow-up like
|
|
22
|
-
* "now add a test for that" keeps the title it inherited.
|
|
23
|
-
*
|
|
24
|
-
* Everything here is pure and returns strings, so the whole surface is
|
|
25
|
-
* assertable without a TTY; `writeTitle` is the one function that touches a
|
|
26
|
-
* stream, and it swallows a non-writable one.
|
|
27
|
-
*/
|
|
28
|
-
|
|
29
|
-
/** The title the app wears before a topic exists (and after one is cleared). */
|
|
30
|
-
const DEFAULT_TITLE = 'AEGIS Code';
|
|
31
|
-
|
|
32
|
-
/** The braille frames the title spins while a turn runs (the reference's). */
|
|
33
|
-
const TITLE_SPIN = ['⠐', '⠂', '⠄', '⠆', '⠈', '⠠', '⠰', '⠁'];
|
|
34
|
-
|
|
35
|
-
/** Longest topic, in cells, before it is clipped on a word boundary. */
|
|
36
|
-
const TOPIC_MAX = 48;
|
|
37
|
-
|
|
38
|
-
/** Longest string that ever reaches the terminal (topic + " · AEGIS Code"). */
|
|
39
|
-
const TITLE_MAX = 96;
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Politeness and throat-clearing, stripped from the front of a prompt so the
|
|
43
|
-
* title says "Add a retry to the fetcher" instead of "Please can you add a
|
|
44
|
-
* retry to the fetcher". Applied repeatedly — "ok so please can you…" is one
|
|
45
|
-
* habit, not four.
|
|
46
|
-
*/
|
|
47
|
-
const FILLER =
|
|
48
|
-
/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and|i'?m trying to|i am trying to|i'?m working on|i am working on)\b[\s,:;-]*/i;
|
|
49
|
-
|
|
50
|
-
/** Leading markdown/list/quote noise: `> `, `- `, `1. `, `## `. */
|
|
51
|
-
const LEADING_NOISE = /^(?:[>#*•·\-–—]+|\d+[.)])\s*/;
|
|
52
|
-
|
|
53
|
-
/** Words that carry no topic signal when comparing two asks. */
|
|
54
|
-
const STOPWORDS = new Set([
|
|
55
|
-
'the', 'and', 'for', 'with', 'that', 'this', 'these', 'those', 'you', 'your', 'yours',
|
|
56
|
-
'can', 'could', 'would', 'should', 'will', 'please', 'pls', 'hey', 'now', 'then',
|
|
57
|
-
'from', 'into', 'onto', 'over', 'under', 'about', 'also', 'just', 'like', 'want',
|
|
58
|
-
'need', 'make', 'made', 'use', 'using', 'get', 'got', 'let', 'lets', 'its', 'it',
|
|
59
|
-
'are', 'was', 'were', 'been', 'has', 'have', 'had', 'but', 'not', 'all', 'any',
|
|
60
|
-
'how', 'what', 'when', 'where', 'which', 'who', 'why', 'there', 'here', 'some',
|
|
61
|
-
'one', 'two', 'add', 'new', 'fix', 'fixing', 'help', 'doing', 'does', 'did', 'me',
|
|
62
|
-
'my', 'our', 'we', 'i', 'a', 'an', 'to', 'of', 'in', 'on', 'at', 'is', 'be', 'do',
|
|
63
|
-
]);
|
|
64
|
-
|
|
65
|
-
/** Strip anything that could break out of the OSC title sequence. */
|
|
66
|
-
function sanitize(text, max = TITLE_MAX) {
|
|
67
|
-
const flat = String(text == null ? '' : text)
|
|
68
|
-
// Control chars (including ESC, BEL, CR, LF, TAB) become a space, so a
|
|
69
|
-
// prompt can never inject an escape sequence into the title bar — the one
|
|
70
|
-
// place in this UI where user text reaches the terminal unsanitized.
|
|
71
|
-
.replace(/[\u0000-\u001f\u007f]/g, ' ')
|
|
72
|
-
.replace(/\s+/g, ' ')
|
|
73
|
-
.trim();
|
|
74
|
-
if (flat.length <= max) return flat;
|
|
75
|
-
return `${flat.slice(0, Math.max(0, max - 1)).trimEnd()}…`;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* A short, single-line topic for a user prompt.
|
|
80
|
-
*
|
|
81
|
-
* Uses the first line that has anything on it (a pasted block's first line is
|
|
82
|
-
* its subject), drops politeness and list noise, collapses whitespace, and
|
|
83
|
-
* clips on a word boundary with an ellipsis. Returns '' when there is nothing
|
|
84
|
-
* to say — the caller then keeps the title it already had.
|
|
85
|
-
*/
|
|
86
|
-
function topicFrom(text, { max = TOPIC_MAX } = {}) {
|
|
87
|
-
if (text == null) return '';
|
|
88
|
-
const lines = String(text).split(/[\r\n]+/);
|
|
89
|
-
let line = '';
|
|
90
|
-
for (const raw of lines) {
|
|
91
|
-
const cleaned = sanitize(raw, 4_000).replace(LEADING_NOISE, '').trim();
|
|
92
|
-
// A pasted block's fence marker is not the topic; the code under it is.
|
|
93
|
-
if (!cleaned || /^```/.test(cleaned)) continue;
|
|
94
|
-
line = cleaned;
|
|
95
|
-
break;
|
|
96
|
-
}
|
|
97
|
-
if (!line) return '';
|
|
98
|
-
let body = line;
|
|
99
|
-
for (let i = 0; i < 6; i++) {
|
|
100
|
-
const next = body.replace(FILLER, '');
|
|
101
|
-
if (next === body) break;
|
|
102
|
-
body = next.replace(LEADING_NOISE, '').trim();
|
|
103
|
-
}
|
|
104
|
-
body = body.replace(/[.!?]+$/, '').trim();
|
|
105
|
-
if (!body) body = line;
|
|
106
|
-
if (/^[a-z]/.test(body)) body = body[0].toUpperCase() + body.slice(1);
|
|
107
|
-
return sanitize(body, max);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/** Topic-defining words of a phrase: lowercase, deduped, stopwords dropped. */
|
|
111
|
-
function keywords(phrase) {
|
|
112
|
-
const out = new Set();
|
|
113
|
-
for (const word of String(phrase || '').toLowerCase().match(/[\p{L}\p{N}_]+/gu) || []) {
|
|
114
|
-
if (word.length < 3 || STOPWORDS.has(word)) continue;
|
|
115
|
-
out.add(word);
|
|
116
|
-
}
|
|
117
|
-
return [...out];
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* Does `next` read as a *different* task from `prev`?
|
|
122
|
-
*
|
|
123
|
-
* The overlap is measured against the shorter keyword set, so a long follow-up
|
|
124
|
-
* that repeats the subject ("also add a test for the config loader") is not
|
|
125
|
-
* mistaken for a new task, while a genuinely unrelated ask ("now write the
|
|
126
|
-
* changelog") is. An empty `next` is never a shift — it means "no topic", and
|
|
127
|
-
* the caller keeps what it had.
|
|
128
|
-
*/
|
|
129
|
-
function titleShift(prev, next, { threshold = 0.34 } = {}) {
|
|
130
|
-
if (!next) return false;
|
|
131
|
-
if (!prev) return true;
|
|
132
|
-
const a = keywords(prev);
|
|
133
|
-
const b = keywords(next);
|
|
134
|
-
if (!a.length || !b.length) return true;
|
|
135
|
-
const set = new Set(a);
|
|
136
|
-
let hits = 0;
|
|
137
|
-
for (const word of b) if (set.has(word)) hits++;
|
|
138
|
-
return hits / Math.min(a.length, b.length) < threshold;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/** The topic after this prompt: the new one only when it is a new task. */
|
|
142
|
-
function adoptTopic(prev, prompt, opts) {
|
|
143
|
-
const next = topicFrom(prompt);
|
|
144
|
-
if (!next) return prev || '';
|
|
145
|
-
return titleShift(prev, next, opts) ? next : prev || '';
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* The composed title.
|
|
150
|
-
*
|
|
151
|
-
* working, with topic `⠂ Fixing the config loader`
|
|
152
|
-
* idle, with topic `Fixing the config loader · AEGIS Code`
|
|
153
|
-
* no topic `AEGIS Code`
|
|
154
|
-
*
|
|
155
|
-
* The idle form keeps the product name so a tab is still identifiable as this
|
|
156
|
-
* CLI; the working form is the topic alone, which is what Claude Code shows
|
|
157
|
-
* while a turn runs.
|
|
158
|
-
*/
|
|
159
|
-
function titleText({ topic = '', frame = null, app = DEFAULT_TITLE } = {}) {
|
|
160
|
-
const clean = sanitize(topic, TOPIC_MAX);
|
|
161
|
-
if (!clean) return sanitize(app, TITLE_MAX) || DEFAULT_TITLE;
|
|
162
|
-
const head = frame ? `${frame} ` : '';
|
|
163
|
-
return sanitize(frame ? `${head}${clean}` : `${clean} · ${app}`, TITLE_MAX);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/** Truthiness for the env flags: `1`, `true`, `yes`, `on` (any case). */
|
|
167
|
-
function flagOn(value) {
|
|
168
|
-
if (value === true) return true;
|
|
169
|
-
if (value == null || value === false) return false;
|
|
170
|
-
return /^(?:1|true|yes|on)$/i.test(String(value).trim());
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Is the title bar ours to write?
|
|
175
|
-
*
|
|
176
|
-
* On by default — a title that follows the work is the feature. Off via
|
|
177
|
-
* `AEGIS_DISABLE_TERMINAL_TITLE=1` (and Claude Code's own
|
|
178
|
-
* `CLAUDE_CODE_DISABLE_TERMINAL_TITLE`, so a shell configured for the
|
|
179
|
-
* reference behaves the same here), or `terminalTitle: false` in config.json.
|
|
180
|
-
* `AEGIS_TERMINAL_TITLE=1` wins over the config, for a one-off run.
|
|
181
|
-
*/
|
|
182
|
-
function titleEnabled(env = {}, config = {}) {
|
|
183
|
-
const e = env || {};
|
|
184
|
-
if (flagOn(e.AEGIS_TERMINAL_TITLE)) return true;
|
|
185
|
-
if (flagOn(e.AEGIS_DISABLE_TERMINAL_TITLE)) return false;
|
|
186
|
-
if (flagOn(e.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)) return false;
|
|
187
|
-
const cfg = config || {};
|
|
188
|
-
if (cfg.terminalTitle === false || cfg.terminalTitleBar === false) return false;
|
|
189
|
-
return true;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/**
|
|
193
|
-
* Write one title to a stream as an OSC 0 sequence. `''` clears it (what the
|
|
194
|
-
* teardown wants, so the shell that gets the terminal back is not left wearing
|
|
195
|
-
* this app's title). Never throws: a stubbed, closed or non-TTY stream is a
|
|
196
|
-
* missing nicety, not a reason to lose a turn.
|
|
197
|
-
*/
|
|
198
|
-
function writeTitle(text, out) {
|
|
199
|
-
const stream = out || process.stdout;
|
|
200
|
-
if (!stream || typeof stream.write !== 'function') return false;
|
|
201
|
-
try {
|
|
202
|
-
stream.write(`\x1b]0;${sanitize(text, TITLE_MAX)}\x07`);
|
|
203
|
-
return true;
|
|
204
|
-
} catch {
|
|
205
|
-
return false;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
module.exports = {
|
|
210
|
-
DEFAULT_TITLE,
|
|
211
|
-
TITLE_SPIN,
|
|
212
|
-
TOPIC_MAX,
|
|
213
|
-
TITLE_MAX,
|
|
214
|
-
sanitize,
|
|
215
|
-
topicFrom,
|
|
216
|
-
keywords,
|
|
217
|
-
titleShift,
|
|
218
|
-
adoptTopic,
|
|
219
|
-
titleText,
|
|
220
|
-
titleEnabled,
|
|
221
|
-
writeTitle,
|
|
222
|
-
};
|
|
3
|
+
"use strict";const DEFAULT_TITLE="AEGIS Code",TITLE_SPIN=["⠐","⠂","⠄","⠆","⠈","⠠","⠰","⠁"],TOPIC_MAX=48,TITLE_MAX=96,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and|i'?m trying to|i am trying to|i'?m working on|i am working on)\b[\s,:;-]*/i,LEADING_NOISE=/^(?:[>#*•·\-–—]+|\d+[.)])\s*/,STOPWORDS=new Set(["the","and","for","with","that","this","these","those","you","your","yours","can","could","would","should","will","please","pls","hey","now","then","from","into","onto","over","under","about","also","just","like","want","need","make","made","use","using","get","got","let","lets","its","it","are","was","were","been","has","have","had","but","not","all","any","how","what","when","where","which","who","why","there","here","some","one","two","add","new","fix","fixing","help","doing","does","did","me","my","our","we","i","a","an","to","of","in","on","at","is","be","do"]);function sanitize(t,e=TITLE_MAX){const n=String(null==t?"":t).replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1)).trimEnd()}…`}function topicFrom(t,{max:e=TOPIC_MAX}={}){if(null==t)return"";const n=String(t).split(/[\r\n]+/);let i="";for(const t of n){const e=sanitize(t,4e3).replace(LEADING_NOISE,"").trim();if(e&&!/^```/.test(e)){i=e;break}}if(!i)return"";let o=i;for(let t=0;t<6;t++){const t=o.replace(FILLER,"");if(t===o)break;o=t.replace(LEADING_NOISE,"").trim()}return o=o.replace(/[.!?]+$/,"").trim(),o||(o=i),/^[a-z]/.test(o)&&(o=o[0].toUpperCase()+o.slice(1)),sanitize(o,e)}function keywords(t){const e=new Set;for(const n of String(t||"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)||[])n.length<3||STOPWORDS.has(n)||e.add(n);return[...e]}function titleShift(t,e,{threshold:n=.34}={}){if(!e)return!1;if(!t)return!0;const i=keywords(t),o=keywords(e);if(!i.length||!o.length)return!0;const r=new Set(i);let l=0;for(const t of o)r.has(t)&&l++;return l/Math.min(i.length,o.length)<n}function adoptTopic(t,e,n){const i=topicFrom(e);return i&&titleShift(t,i,n)?i:t||""}function titleText({topic:t="",frame:e=null,app:n="AEGIS Code"}={}){const i=sanitize(t,TOPIC_MAX);return i?sanitize(e?`${e?`${e} `:""}${i}`:`${i} · ${n}`,TITLE_MAX):sanitize(n,TITLE_MAX)||"AEGIS Code"}function flagOn(t){return!0===t||null!=t&&!1!==t&&/^(?:1|true|yes|on)$/i.test(String(t).trim())}function titleEnabled(t={},e={}){const n=t||{};if(flagOn(n.AEGIS_TERMINAL_TITLE))return!0;if(flagOn(n.AEGIS_DISABLE_TERMINAL_TITLE))return!1;if(flagOn(n.CLAUDE_CODE_DISABLE_TERMINAL_TITLE))return!1;const i=e||{};return!1!==i.terminalTitle&&!1!==i.terminalTitleBar}function writeTitle(t,e){const n=e||process.stdout;if(!n||"function"!=typeof n.write)return!1;try{return n.write(`]0;${sanitize(t,TITLE_MAX)}`),!0}catch{return!1}}module.exports={DEFAULT_TITLE:"AEGIS Code",TITLE_SPIN:TITLE_SPIN,TOPIC_MAX:TOPIC_MAX,TITLE_MAX:TITLE_MAX,sanitize:sanitize,topicFrom:topicFrom,keywords:keywords,titleShift:titleShift,adoptTopic:adoptTopic,titleText:titleText,titleEnabled:titleEnabled,writeTitle:writeTitle};
|
package/src/todos.js
CHANGED
|
@@ -1,117 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
|
|
4
|
-
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
-
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* /todos — a session todo list the user owns, and the agent can read.
|
|
10
|
-
*
|
|
11
|
-
* Ported from the upstream engine's `src/session.js` (todosFile/readTodos/
|
|
12
|
-
* writeTodos/addTodo/completeTodo/clearTodos/formatTodos). The upstream writes
|
|
13
|
-
* to `$AEGISCODEX_HOME/todos.json`; here the dir comes from this host's own
|
|
14
|
-
* `aegisDir()`, so the list lands in `$AEGISCODE_HOME/todos.json` beside
|
|
15
|
-
* credentials.json and permissions.json.
|
|
16
|
-
*
|
|
17
|
-
* Three properties carried over deliberately, because each is a failure a todo
|
|
18
|
-
* list is uniquely good at:
|
|
19
|
-
*
|
|
20
|
-
* 1. It cannot throw. A corrupt or hand-edited file reads as `[]` rather than
|
|
21
|
-
* taking the prompt down — the list is a convenience, not a dependency.
|
|
22
|
-
* 2. It cannot half-write. `writeTodos` writes a temp file and renames it, so
|
|
23
|
-
* a crash during the write leaves the previous list intact rather than a
|
|
24
|
-
* truncated JSON blob that the next read has to guess at.
|
|
25
|
-
* 3. It cannot accept an empty item. A blank todo is a rendering artifact, so
|
|
26
|
-
* blank text is filtered on write and refused on add.
|
|
27
|
-
*
|
|
28
|
-
* `completeTodo` takes either the 1-based number from `/todos` or a unique text
|
|
29
|
-
* prefix. Ambiguity is reported, never guessed: matching two todos and picking
|
|
30
|
-
* the first is how the wrong item gets closed silently.
|
|
31
|
-
*/
|
|
32
|
-
|
|
33
|
-
const fs = require('node:fs');
|
|
34
|
-
const path = require('node:path');
|
|
35
|
-
|
|
36
|
-
const { aegisDir } = require('./config.js');
|
|
37
|
-
const { writePrivateFile } = require('./securefs.js');
|
|
38
|
-
|
|
39
|
-
function todosFile() {
|
|
40
|
-
return path.join(aegisDir(), 'todos.json');
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** The session todo list (never throws; a corrupt file reads as empty). */
|
|
44
|
-
function readTodos() {
|
|
45
|
-
try {
|
|
46
|
-
const parsed = JSON.parse(fs.readFileSync(todosFile(), 'utf8'));
|
|
47
|
-
if (!Array.isArray(parsed)) return [];
|
|
48
|
-
return parsed
|
|
49
|
-
.filter((t) => t && typeof t.text === 'string')
|
|
50
|
-
.map((t) => ({ text: t.text, done: t.done === true, at: t.at || null }));
|
|
51
|
-
} catch {
|
|
52
|
-
return [];
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** Persist the list and return the cleaned copy that was written. */
|
|
57
|
-
function writeTodos(list) {
|
|
58
|
-
const clean = (Array.isArray(list) ? list : [])
|
|
59
|
-
.filter((t) => t && typeof t.text === 'string' && t.text.trim())
|
|
60
|
-
.map((t) => ({ text: t.text.trim(), done: t.done === true, at: t.at || new Date().toISOString() }));
|
|
61
|
-
try {
|
|
62
|
-
// Through securefs, not `fs.writeFileSync`: todos.json lives in the data
|
|
63
|
-
// dir, so the raw write gave it umask mode (0664 — world-readable in a
|
|
64
|
-
// 0775 dir) and followed a symlink planted there. The temp-file + rename
|
|
65
|
-
// shape the old code spelled out by hand is what `writePrivateFile` does,
|
|
66
|
-
// plus 0600/0700 and O_NOFOLLOW.
|
|
67
|
-
writePrivateFile(todosFile(), `${JSON.stringify(clean, null, 2)}\n`);
|
|
68
|
-
} catch {
|
|
69
|
-
/* best-effort, like every other store in this host */
|
|
70
|
-
}
|
|
71
|
-
return clean;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function addTodo(text) {
|
|
75
|
-
const t = String(text || '').trim();
|
|
76
|
-
if (!t) return { error: 'usage: /todos add <text>' };
|
|
77
|
-
const list = readTodos();
|
|
78
|
-
list.push({ text: t, done: false, at: new Date().toISOString() });
|
|
79
|
-
return { list: writeTodos(list), added: t };
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Toggle done by 1-based index or by unique text prefix. Returns
|
|
84
|
-
* `{ list, item }` or `{ error }` — an ambiguous prefix is an error naming how
|
|
85
|
-
* many matched, not a silent first-match.
|
|
86
|
-
*/
|
|
87
|
-
function completeTodo(token) {
|
|
88
|
-
const list = readTodos();
|
|
89
|
-
const key = String(token || '').trim();
|
|
90
|
-
if (!key) return { error: 'usage: /todos done <n|text>' };
|
|
91
|
-
let idx = -1;
|
|
92
|
-
const n = Number.parseInt(key, 10);
|
|
93
|
-
if (Number.isFinite(n) && String(n) === key) idx = n - 1;
|
|
94
|
-
else {
|
|
95
|
-
const matches = list.map((t, i) => (t.text.startsWith(key) ? i : -1)).filter((i) => i >= 0);
|
|
96
|
-
if (matches.length === 1) idx = matches[0];
|
|
97
|
-
else if (matches.length > 1) return { error: `"${key}" matches ${matches.length} todos — use the number from /todos` };
|
|
98
|
-
}
|
|
99
|
-
if (idx < 0 || idx >= list.length) return { error: `no todo #${key} — run /todos to list them` };
|
|
100
|
-
list[idx].done = !list[idx].done;
|
|
101
|
-
return { list: writeTodos(list), item: list[idx] };
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function clearTodos() {
|
|
105
|
-
writeTodos([]);
|
|
106
|
-
return { list: [] };
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/** Panel lines for the list. */
|
|
110
|
-
function formatTodos(list = readTodos()) {
|
|
111
|
-
if (!list.length) return [' No todos yet — /todos add <text>'];
|
|
112
|
-
return list.map((t, i) => ` ${String(i + 1).padStart(2)}. ${t.done ? '✔' : '○'} ${t.text}`);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
module.exports = {
|
|
116
|
-
todosFile, readTodos, writeTodos, addTodo, completeTodo, clearTodos, formatTodos,
|
|
117
|
-
};
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{writePrivateFile:writePrivateFile}=require("./securefs.js");function todosFile(){return path.join(aegisDir(),"todos.json")}function readTodos(){try{const t=JSON.parse(fs.readFileSync(todosFile(),"utf8"));return Array.isArray(t)?t.filter((t=>t&&"string"==typeof t.text)).map((t=>({text:t.text,done:!0===t.done,at:t.at||null}))):[]}catch{return[]}}function writeTodos(t){const e=(Array.isArray(t)?t:[]).filter((t=>t&&"string"==typeof t.text&&t.text.trim())).map((t=>({text:t.text.trim(),done:!0===t.done,at:t.at||(new Date).toISOString()})));try{writePrivateFile(todosFile(),`${JSON.stringify(e,null,2)}\n`)}catch{}return e}function addTodo(t){const e=String(t||"").trim();if(!e)return{error:"usage: /todos add <text>"};const o=readTodos();return o.push({text:e,done:!1,at:(new Date).toISOString()}),{list:writeTodos(o),added:e}}function completeTodo(t){const e=readTodos(),o=String(t||"").trim();if(!o)return{error:"usage: /todos done <n|text>"};let r=-1;const i=Number.parseInt(o,10);if(Number.isFinite(i)&&String(i)===o)r=i-1;else{const t=e.map(((t,e)=>t.text.startsWith(o)?e:-1)).filter((t=>t>=0));if(1===t.length)r=t[0];else if(t.length>1)return{error:`"${o}" matches ${t.length} todos — use the number from /todos`}}return r<0||r>=e.length?{error:`no todo #${o} — run /todos to list them`}:(e[r].done=!e[r].done,{list:writeTodos(e),item:e[r]})}function clearTodos(){return writeTodos([]),{list:[]}}function formatTodos(t=readTodos()){return t.length?t.map(((t,e)=>` ${String(e+1).padStart(2)}. ${t.done?"✔":"○"} ${t.text}`)):[" No todos yet — /todos add <text>"]}module.exports={todosFile:todosFile,readTodos:readTodos,writeTodos:writeTodos,addTodo:addTodo,completeTodo:completeTodo,clearTodos:clearTodos,formatTodos:formatTodos};
|
package/src/tokens.js
CHANGED
|
@@ -1,265 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
|
|
4
|
-
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
-
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Token + cost estimation. Tokens are estimated from text length (~4
|
|
10
|
-
* chars/token, the usual rule of thumb) and priced against the per-model rates
|
|
11
|
-
* in the SHARED table. Everything is labeled approximate in the UI.
|
|
12
|
-
*
|
|
13
|
-
* The rate table itself is not here — see the block below.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
// ── The rate table is NOT defined here ─────────────────────────────────────
|
|
17
|
-
//
|
|
18
|
-
// This file used to carry its own copy of `RATES`, and that copy is how the
|
|
19
|
-
// DeepSeek row came to be wrong in one host and right in the other: the table
|
|
20
|
-
// existed twice (here and desktop/renderer/usage.js), so a rate read off the
|
|
21
|
-
// vendor's pricing page reached whichever copy someone happened to edit. The
|
|
22
|
-
// CLI's copy still said $0.14/$0.28 — the retired V4-Flash tier — while the
|
|
23
|
-
// desktop's had been corrected, and `/cost` would have disagreed with the GUI
|
|
24
|
-
// about the same turn on the same engine.
|
|
25
|
-
//
|
|
26
|
-
// So the table lives in exactly one place. `desktop/renderer/usage.js` is
|
|
27
|
-
// already the declared single source of truth for turning a provider's usage
|
|
28
|
-
// object into a display number (cli/src/deps.js resolves it, and
|
|
29
|
-
// test/cli-tools.test.mjs asserts the function identity), so the rates belong
|
|
30
|
-
// there too rather than in a second table that can only drift.
|
|
31
|
-
//
|
|
32
|
-
// `sharedpaths.js` is used rather than `deps.js` because deps.js eagerly
|
|
33
|
-
// requires the engine, the client and the tool registry — pulling all of that
|
|
34
|
-
// in to read a number would be a require cycle for anything in that graph.
|
|
35
|
-
const path = require('node:path');
|
|
36
|
-
|
|
37
|
-
const { resolveShared } = require('./sharedpaths.js');
|
|
38
|
-
const shared = require(resolveShared(path.join('desktop', 'renderer', 'usage.js')));
|
|
39
|
-
|
|
40
|
-
const { RATES, RATE_BASIS, UNPRICED_BY_DESIGN, isPeak, ratesFor, costBreakdown, cacheHitRate, usageBuckets } = shared;
|
|
41
|
-
|
|
42
|
-
// System prompt + tool definitions overhead, roughly, in tokens.
|
|
43
|
-
const SYSTEM_TOKENS = 18000;
|
|
44
|
-
const TOOL_TOKENS = 12000;
|
|
45
|
-
// Default context window we budget against (Sonnet 5 class).
|
|
46
|
-
const CONTEXT_WINDOW = 200000;
|
|
47
|
-
|
|
48
|
-
// Real per-provider context budgets for the /context meter. The default above
|
|
49
|
-
// is the Claude-class window the UI was built around; providers with a
|
|
50
|
-
// different window map here so the meter shows the truth instead of a
|
|
51
|
-
// Sonnet-flavored estimate.
|
|
52
|
-
//
|
|
53
|
-
// DeepSeek V4 — verified live 2026-09-11 against api.deepseek.com:
|
|
54
|
-
// - a 942,031-token prompt was ACCEPTED (HTTP 200)
|
|
55
|
-
// - a 1,122,032-token prompt was REJECTED, verbatim: "This model's maximum
|
|
56
|
-
// context length is 1048576 tokens."
|
|
57
|
-
// so the window is 1M. The old 256k figure here understated it 4x and made the
|
|
58
|
-
// /context meter lie. Max output is 393216 — the API rejects anything larger
|
|
59
|
-
// with "the valid range of max_tokens is [1, 393216]".
|
|
60
|
-
// Keyed by provider name or model-id prefix (longest prefix wins via the
|
|
61
|
-
// iteration order below — exact id matches take priority).
|
|
62
|
-
const CONTEXT_WINDOWS = {
|
|
63
|
-
deepseek: 1_048_576,
|
|
64
|
-
openrouter: 256_000,
|
|
65
|
-
together: 256_000,
|
|
66
|
-
xai: 256_000,
|
|
67
|
-
groq: 128_000,
|
|
68
|
-
ollama: 128_000,
|
|
69
|
-
openai: 200_000,
|
|
70
|
-
anthropic: 200_000,
|
|
71
|
-
google: 1_000_000,
|
|
72
|
-
gemini: 1_000_000,
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
/** The context budget to show/guard against for a model id, provider, or raw model string. */
|
|
76
|
-
function contextWindowFor(model) {
|
|
77
|
-
const raw = String(model || '').toLowerCase();
|
|
78
|
-
if (!raw) return CONTEXT_WINDOW;
|
|
79
|
-
// Same two-candidate lookup as ratesFor in the shared table, for the same
|
|
80
|
-
// reason: a byok id ("deepseek:deepseek-v4-flash") carries a routing label in
|
|
81
|
-
// front of the model, and matching it as written left the 1M-token DeepSeek
|
|
82
|
-
// window reading as the 200k default — a meter that would have told a user
|
|
83
|
-
// they were at 20% of a context that was 4% full.
|
|
84
|
-
const ids = [raw];
|
|
85
|
-
const tail = raw.slice(raw.lastIndexOf(':') + 1);
|
|
86
|
-
if (tail && tail !== raw) ids.push(tail);
|
|
87
|
-
for (const id of ids) {
|
|
88
|
-
if (CONTEXT_WINDOWS[id]) return CONTEXT_WINDOWS[id];
|
|
89
|
-
for (const [prefix, win] of Object.entries(CONTEXT_WINDOWS)) {
|
|
90
|
-
if (id.startsWith(prefix)) return win;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return CONTEXT_WINDOW;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/** Rough token estimate: ~4 chars per token (heuristic, labeled approximate). */
|
|
97
|
-
function estimateTokens(text) {
|
|
98
|
-
if (!text) return 0;
|
|
99
|
-
return Math.max(1, Math.ceil([...String(text)].length / 4));
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* The same 4:1 rule, from a streamed LENGTH rather than from the text.
|
|
104
|
-
*
|
|
105
|
-
* The live tails count what has arrived as a display width, because they are
|
|
106
|
-
* painted from a counter on a timer rather than from a string — see app.js
|
|
107
|
-
* (`chars += w(chunk.delta)`) and chatflow.js (`streamedChars += w(delta)`).
|
|
108
|
-
* Both sites then label that number `tokens`, so the count form of the
|
|
109
|
-
* heuristic has to live beside the text form. Without it the two producers fed
|
|
110
|
-
* their raw cell count straight into `fmtTokens(...) tokens`, which printed the
|
|
111
|
-
* character count as a token count — the live spinner read ~4x high, and high
|
|
112
|
-
* against every settled figure for the same turn (the desktop meter included),
|
|
113
|
-
* which is exactly the "tokens spent" gap against the reference engine.
|
|
114
|
-
*
|
|
115
|
-
* Returns 0 for an empty stream so a caller can tell "nothing yet" from "some",
|
|
116
|
-
* rather than `estimateTokens`'s floor of 1.
|
|
117
|
-
*/
|
|
118
|
-
function estimateTokensFromCells(cells) {
|
|
119
|
-
const n = Number(cells);
|
|
120
|
-
if (!(n > 0)) return 0;
|
|
121
|
-
return Math.ceil(n / 4);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Bucket the transcript's token usage.
|
|
126
|
-
* input — user prompts + system + tools (per exchange)
|
|
127
|
-
* output — assistant replies
|
|
128
|
-
* cacheRead — what a resumed session reads back (prior context, approximated
|
|
129
|
-
* as all prior user+assistant text)
|
|
130
|
-
* cacheWrite — the newest user+assistant chunk written to cache
|
|
131
|
-
*/
|
|
132
|
-
function transcriptUsage(transcript, model = 'sonnet') {
|
|
133
|
-
const userMsgs = transcript.filter((m) => m.role === 'user');
|
|
134
|
-
const asstMsgs = transcript.filter((m) => m.role === 'assistant');
|
|
135
|
-
const input = userMsgs.reduce((a, m) => a + estimateTokens(m.text || ''), 0);
|
|
136
|
-
const output = asstMsgs.reduce((a, m) => a + estimateTokens(m.text || ''), 0);
|
|
137
|
-
const cacheRead = Math.max(0, input - (userMsgs.length ? estimateTokens(userMsgs[userMsgs.length - 1].text || '') : 0));
|
|
138
|
-
const cacheWrite = userMsgs.length ? estimateTokens(userMsgs[userMsgs.length - 1].text || '') : 0;
|
|
139
|
-
return { input, output, cacheRead, cacheWrite };
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Dollar cost of a usage record at the given model's rates.
|
|
144
|
-
*
|
|
145
|
-
* Returns a number for backward compatibility, but the basis is not lost: use
|
|
146
|
-
* `costBreakdown` when the caller needs to know whether the figure is real.
|
|
147
|
-
* (`usageCost` in the shared module, which also folds the record through
|
|
148
|
-
* `usageBuckets` first — so a wire usage object is normalized identically in
|
|
149
|
-
* both hosts, where this file's old copy read `usage.input` directly.)
|
|
150
|
-
*
|
|
151
|
-
* `model` has no `= 'sonnet'` default here either, and that matters for more
|
|
152
|
-
* than tidiness: a default parameter in THIS file would re-introduce exactly
|
|
153
|
-
* the split the shared module just removed, and only on the CLI side — so
|
|
154
|
-
* `usageCost(u)` would report `basis: 'exact'` in the terminal and
|
|
155
|
-
* `basis: 'default'` in the GUI for the same turn on the same engine. The
|
|
156
|
-
* whole point of delegating is that both hosts answer identically.
|
|
157
|
-
*/
|
|
158
|
-
function usageCost(usage, model, opts = {}) {
|
|
159
|
-
return shared.usageCost(usage, model, opts);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/** Full session accounting: per-bucket tokens, cost, and context used %. */
|
|
163
|
-
function sessionAccounting(transcript, model = 'sonnet') {
|
|
164
|
-
const usage = transcriptUsage(transcript, model);
|
|
165
|
-
const system = SYSTEM_TOKENS;
|
|
166
|
-
const tools = TOOL_TOKENS;
|
|
167
|
-
const history = usage.input + usage.output;
|
|
168
|
-
const used = system + tools + history;
|
|
169
|
-
const contextWindow = contextWindowFor(model);
|
|
170
|
-
// ONE breakdown, not a cost call plus a separate basis call: ratesFor reads
|
|
171
|
-
// the wall clock for peak/off-peak, so two evaluations straddling a peak
|
|
172
|
-
// boundary would report a peak cost with an off-peak basis (or vice versa) —
|
|
173
|
-
// two different claims about the same number, which is the thing this return
|
|
174
|
-
// shape exists to prevent. The upstream engine's sessionAccounting is written the
|
|
175
|
-
// same way; if one host folds this into two calls again the two will disagree
|
|
176
|
-
// about the same turn, which is how the rate table split in the first place.
|
|
177
|
-
const breakdown = costBreakdown(usage, model);
|
|
178
|
-
return {
|
|
179
|
-
usage,
|
|
180
|
-
system,
|
|
181
|
-
tools,
|
|
182
|
-
history,
|
|
183
|
-
used,
|
|
184
|
-
contextWindow,
|
|
185
|
-
pct: Math.min(100, Math.round((used / contextWindow) * 100)),
|
|
186
|
-
cost: breakdown.cost,
|
|
187
|
-
// Which rate row priced this. 'default' means the model is unpriced and
|
|
188
|
-
// `cost` is a Sonnet-class placeholder — surfaced rather than swallowed so
|
|
189
|
-
// /cost can label it instead of printing a fabricated figure.
|
|
190
|
-
costBasis: breakdown.basis,
|
|
191
|
-
costPriced: breakdown.priced,
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* Build the same accounting shape from summed history.jsonl token
|
|
197
|
-
* records (live usage numbers when `real`, estimated otherwise). Real usage
|
|
198
|
-
* already includes system prompt + tools in cacheRead, so `used` counts
|
|
199
|
-
* input + output + cache instead of re-adding the constants.
|
|
200
|
-
*/
|
|
201
|
-
function accountingFromUsage(usage, model = 'sonnet', { exchanges = 0, real = false, costUsd, at } = {}) {
|
|
202
|
-
const breakdown = costBreakdown(usage, model, { at });
|
|
203
|
-
const cost = typeof costUsd === 'number' ? costUsd : breakdown.cost;
|
|
204
|
-
const used = real
|
|
205
|
-
? usage.input + usage.output + usage.cacheRead + usage.cacheWrite
|
|
206
|
-
: SYSTEM_TOKENS + TOOL_TOKENS + usage.input + usage.output;
|
|
207
|
-
const contextWindow = contextWindowFor(model);
|
|
208
|
-
return {
|
|
209
|
-
usage,
|
|
210
|
-
system: SYSTEM_TOKENS,
|
|
211
|
-
tools: TOOL_TOKENS,
|
|
212
|
-
history: usage.input + usage.output,
|
|
213
|
-
used,
|
|
214
|
-
contextWindow,
|
|
215
|
-
pct: Math.min(100, Math.round((used / contextWindow) * 100)),
|
|
216
|
-
cost,
|
|
217
|
-
// A settled charge (costUsd) is the ledger's own truth, so it is 'settled'
|
|
218
|
-
// rather than a table match — the pool's bill carries a margin and a
|
|
219
|
-
// prompt-cache discount the table cannot see, so the two must never be
|
|
220
|
-
// conflated.
|
|
221
|
-
costBasis: typeof costUsd === 'number' ? 'settled' : breakdown.basis,
|
|
222
|
-
costPriced: typeof costUsd === 'number' ? true : breakdown.priced,
|
|
223
|
-
exchanges,
|
|
224
|
-
real,
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
function fmtTokens(n) {
|
|
229
|
-
if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
|
|
230
|
-
return String(n);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
function fmtCost(d) {
|
|
234
|
-
return `$${d.toFixed(4)}`;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
module.exports = {
|
|
238
|
-
RATES,
|
|
239
|
-
RATE_BASIS,
|
|
240
|
-
UNPRICED_BY_DESIGN,
|
|
241
|
-
isPeak,
|
|
242
|
-
SYSTEM_TOKENS,
|
|
243
|
-
TOOL_TOKENS,
|
|
244
|
-
CONTEXT_WINDOW,
|
|
245
|
-
CONTEXT_WINDOWS,
|
|
246
|
-
contextWindowFor,
|
|
247
|
-
ratesFor,
|
|
248
|
-
costBreakdown,
|
|
249
|
-
cacheHitRate,
|
|
250
|
-
// Re-exported so a caller that only needs the bucket shape (the per-turn
|
|
251
|
-
// in/out readout in chatflow.js and app.js) does not have to reach past this
|
|
252
|
-
// module into the desktop bundle itself — and, more importantly, so it has
|
|
253
|
-
// exactly ONE way to read a usage object rather than a hand-rolled
|
|
254
|
-
// `input_tokens ?? prompt_tokens`, which is how the two hosts came to
|
|
255
|
-
// disagree about the same turn's prompt size in the first place.
|
|
256
|
-
usageBuckets,
|
|
257
|
-
estimateTokens,
|
|
258
|
-
estimateTokensFromCells,
|
|
259
|
-
transcriptUsage,
|
|
260
|
-
usageCost,
|
|
261
|
-
sessionAccounting,
|
|
262
|
-
accountingFromUsage,
|
|
263
|
-
fmtTokens,
|
|
264
|
-
fmtCost,
|
|
265
|
-
};
|
|
3
|
+
"use strict";const path=require("node:path"),{resolveShared:resolveShared}=require("./sharedpaths.js"),shared=require(resolveShared(path.join("desktop","renderer","usage.js"))),{RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,ratesFor:ratesFor,costBreakdown:costBreakdown,cacheHitRate:cacheHitRate,usageBuckets:usageBuckets}=shared,SYSTEM_TOKENS=18e3,TOOL_TOKENS=12e3,CONTEXT_WINDOW=2e5,CONTEXT_WINDOWS={deepseek:1048576,openrouter:256e3,together:256e3,xai:256e3,groq:128e3,ollama:128e3,openai:2e5,anthropic:2e5,google:1e6,gemini:1e6};function contextWindowFor(e){const t=String(e||"").toLowerCase();if(!t)return CONTEXT_WINDOW;const s=[t],o=t.slice(t.lastIndexOf(":")+1);o&&o!==t&&s.push(o);for(const e of s){if(CONTEXT_WINDOWS[e])return CONTEXT_WINDOWS[e];for(const[t,s]of Object.entries(CONTEXT_WINDOWS))if(e.startsWith(t))return s}return CONTEXT_WINDOW}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimateTokensFromCells(e){const t=Number(e);return t>0?Math.ceil(t/4):0}function transcriptUsage(e,t="sonnet"){const s=e.filter((e=>"user"===e.role)),o=e.filter((e=>"assistant"===e.role)),n=s.reduce(((e,t)=>e+estimateTokens(t.text||"")),0);return{input:n,output:o.reduce(((e,t)=>e+estimateTokens(t.text||"")),0),cacheRead:Math.max(0,n-(s.length?estimateTokens(s[s.length-1].text||""):0)),cacheWrite:s.length?estimateTokens(s[s.length-1].text||""):0}}function usageCost(e,t,s={}){return shared.usageCost(e,t,s)}function sessionAccounting(e,t="sonnet"){const s=transcriptUsage(e,t),o=s.input+s.output,n=3e4+o,r=contextWindowFor(t),a=costBreakdown(s,t);return{usage:s,system:18e3,tools:12e3,history:o,used:n,contextWindow:r,pct:Math.min(100,Math.round(n/r*100)),cost:a.cost,costBasis:a.basis,costPriced:a.priced}}function accountingFromUsage(e,t="sonnet",{exchanges:s=0,real:o=!1,costUsd:n,at:r}={}){const a=costBreakdown(e,t,{at:r}),c="number"==typeof n?n:a.cost,i=o?e.input+e.output+e.cacheRead+e.cacheWrite:3e4+e.input+e.output,u=contextWindowFor(t);return{usage:e,system:18e3,tools:12e3,history:e.input+e.output,used:i,contextWindow:u,pct:Math.min(100,Math.round(i/u*100)),cost:c,costBasis:"number"==typeof n?"settled":a.basis,costPriced:"number"==typeof n||a.priced,exchanges:s,real:o}}function fmtTokens(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function fmtCost(e){return`$${e.toFixed(4)}`}module.exports={RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,SYSTEM_TOKENS:18e3,TOOL_TOKENS:12e3,CONTEXT_WINDOW:CONTEXT_WINDOW,CONTEXT_WINDOWS:CONTEXT_WINDOWS,contextWindowFor:contextWindowFor,ratesFor:ratesFor,costBreakdown:costBreakdown,cacheHitRate:cacheHitRate,usageBuckets:usageBuckets,estimateTokens:estimateTokens,estimateTokensFromCells:estimateTokensFromCells,transcriptUsage:transcriptUsage,usageCost:usageCost,sessionAccounting:sessionAccounting,accountingFromUsage:accountingFromUsage,fmtTokens:fmtTokens,fmtCost:fmtCost};
|