dsh-go-codearts 0.0.0-stage → 1.0.0

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,360 @@
1
+ #!/usr/bin/env node
2
+ import { i as codeartsAccountsPath, t as CodeArtsAccountStore } from "./auth-T5qnGSPp.mjs";
3
+ import { J as isBenefitModel, l as fetchCallerIdentity } from "./upstream-Cr5tUI75.mjs";
4
+ import { i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-Bienp51v.mjs";
5
+ import { existsSync, statSync } from "node:fs";
6
+ //#region src/bin.ts
7
+ /**
8
+ * dsh-codearts CLI: sign-in state, diagnostics and sign-out.
9
+ *
10
+ * dsh plugin --profile web exec dsh-codearts status # sign-in state + seed models
11
+ * dsh plugin --profile web exec dsh-codearts status --json # machine-readable
12
+ * dsh plugin --profile web exec dsh-codearts models # discover the account's real models
13
+ * dsh plugin --profile web exec dsh-codearts models --json # machine-readable
14
+ * dsh plugin --profile web exec dsh-codearts usage # local token accounting
15
+ * dsh plugin --profile web exec dsh-codearts usage --json # machine-readable
16
+ * dsh plugin --profile web exec dsh-codearts identity # stable upstream user ids per account
17
+ * dsh plugin --profile web exec dsh-codearts identity --fix # merge duplicate entries onto them
18
+ * dsh plugin --profile web exec dsh-codearts doctor # secret-free diagnostics
19
+ * dsh plugin --profile web exec dsh-codearts logout # drop the plugin's credential
20
+ *
21
+ * `models` asks the upstream for the account's real catalog (built-in, limited-time
22
+ * benefit and agent-center sources) instead of printing the hand-maintained seed —
23
+ * that is the first thing to run when a model is missing from the picker.
24
+ *
25
+ * `usage` reads the plugin's own ledger of requests this machine sent — not an
26
+ * account balance (account credits live in the card / `credits` route).
27
+ *
28
+ * `identity` asks the gateway which account each stored credential belongs to. The
29
+ * login response carries no user id, so credentials used to be keyed by their DPoP
30
+ * key — which made a re-login of the same account look like a new one. This is the
31
+ * command that reports and (with --fix) merges those duplicates.
32
+ *
33
+ * `doctor` never prints token material — only paths, booleans and versions —
34
+ * so its output is safe to paste into a bug report. `logout` removes only this
35
+ * plugin's own credential copy; nothing outside the plugin is touched.
36
+ *
37
+ * @module dsh-codearts/bin
38
+ */
39
+ /** Bumped when a `--json` document changes shape (5: identity backfill). */
40
+ const JSON_SCHEMA_VERSION = 6;
41
+ /**
42
+ * 一句话描述一个账号,供人类可读输出用。
43
+ *
44
+ * 注意空串也要当「没有」:`credentialFromOAuth` 会把上游返回的空 `user_name` /
45
+ * `user_id` 原样写进 label,用 `??` 兜底会得到一个空名字,于是 `status` 打印出
46
+ * `- (expires …)` 这种认不出是哪个账号的行。
47
+ */
48
+ function describeAccount(account) {
49
+ const name = firstNonEmpty(account.label, account.userName, `${account.id.slice(0, 12)}…`);
50
+ const notes = [];
51
+ if (account.stale) notes.push("needs sign-in");
52
+ else if (typeof account.expiration === "string") notes.push(`expires ${account.expiration}`);
53
+ if (!account.signable) notes.push("no AK/SK");
54
+ return notes.length === 0 ? name : `${name} (${notes.join(", ")})`;
55
+ }
56
+ /** 第一个非空(去空白后)的字符串。 */
57
+ function firstNonEmpty(...values) {
58
+ for (const value of values) if (typeof value === "string" && value.trim() !== "") return value.trim();
59
+ return "";
60
+ }
61
+ function store() {
62
+ return new CodeArtsAccountStore(codeartsAccountsPath());
63
+ }
64
+ async function status(jsonOutput) {
65
+ const accounts = await store().list();
66
+ const cred = await store().current();
67
+ const out = {
68
+ schemaVersion: JSON_SCHEMA_VERSION,
69
+ version: CODEARTS_VERSION,
70
+ signedIn: accounts.length > 0,
71
+ signable: accounts.some((account) => account.signable),
72
+ accounts
73
+ };
74
+ if (cred !== void 0) {
75
+ if (cred.label !== void 0) out.label = cred.label;
76
+ if (cred.storedAt !== void 0) out.storedAt = cred.storedAt;
77
+ if (cred.expiration !== void 0) out.expiration = cred.expiration;
78
+ if (cred.stale === true) out.stale = true;
79
+ }
80
+ if (jsonOutput) {
81
+ process.stdout.write(JSON.stringify(out, null, 2) + "\n");
82
+ return out.signedIn ? 0 : 1;
83
+ }
84
+ if (out.signedIn) {
85
+ process.stdout.write(`signed in — ${accounts.length} account${accounts.length === 1 ? "" : "s"}:\n`);
86
+ for (const account of accounts) process.stdout.write(` - ${describeAccount(account)}\n`);
87
+ if (!out.signable) process.stdout.write("warning: no account carries AK/SK, so requests cannot be signed and chats will be rejected\n");
88
+ } else process.stdout.write("not signed in (no account stored; sign in from the CodeArts settings card)\n");
89
+ process.stdout.write("models: CLI 不缓存目录,跑 `dsh-codearts models` 现问上游\n");
90
+ return out.signedIn ? 0 : 1;
91
+ }
92
+ /**
93
+ * 动态发现当前可用模型(三路:内置 / 限时福利 / agent-center)。
94
+ *
95
+ * 这是排查「模型选择器里没有某个模型」的第一手段:它打印的是上游真实返回。
96
+ * 未登录时就是没有目录,直接说明原因 —— 不打印手维护的种子清单冒充上游结果。
97
+ */
98
+ async function models(jsonOutput) {
99
+ if ((await store().list()).length === 0) {
100
+ if (jsonOutput) process.stdout.write(JSON.stringify({
101
+ schemaVersion: JSON_SCHEMA_VERSION,
102
+ version: CODEARTS_VERSION,
103
+ discovered: false,
104
+ reason: "not signed in",
105
+ models: []
106
+ }, null, 2) + "\n");
107
+ else process.stdout.write("not signed in — 没有目录可展示(不会用种子清单冒充上游返回)\n");
108
+ return 1;
109
+ }
110
+ const outcome = await discoverModels(store());
111
+ if (jsonOutput) {
112
+ process.stdout.write(JSON.stringify({
113
+ schemaVersion: JSON_SCHEMA_VERSION,
114
+ version: CODEARTS_VERSION,
115
+ discovered: outcome.anySucceeded,
116
+ accounts: outcome.accounts.map((account) => ({
117
+ accountId: account.accountId,
118
+ label: account.label,
119
+ ok: account.ok,
120
+ sources: account.sources,
121
+ modelCount: account.models.length,
122
+ errors: account.errors
123
+ })),
124
+ models: outcome.models.map((m) => ({
125
+ id: m.id,
126
+ name: m.name,
127
+ contextWindow: m.contextWindow,
128
+ maxTokens: m.maxTokens,
129
+ supportsImages: m.supportsImages,
130
+ benefit: m.benefit === true || isBenefitModel(m.id)
131
+ }))
132
+ }, null, 2) + "\n");
133
+ return outcome.anySucceeded ? 0 : 1;
134
+ }
135
+ for (const account of outcome.accounts) {
136
+ const name = account.label ?? account.accountId;
137
+ process.stdout.write(account.ok ? `discovered ${account.models.length} model(s) for ${name} via ${account.sources.join(", ")}\n` : `discovery failed for ${name}: ${account.errors.map((e) => `${e.source}: ${e.message}`).join("; ")}\n`);
138
+ for (const error of account.ok ? account.errors : []) process.stdout.write(` warning: ${error.source} source failed (${error.message})\n`);
139
+ }
140
+ if (!outcome.anySucceeded) {
141
+ process.stdout.write("no account could be queried; nothing to list\n");
142
+ return 1;
143
+ }
144
+ process.stdout.write(`models (${outcome.models.length}):\n`);
145
+ for (const m of outcome.models) {
146
+ const flags = [
147
+ m.benefit === true || isBenefitModel(m.id) ? "benefit" : "",
148
+ m.supportsImages ? "images" : "",
149
+ `max ${m.maxTokens}`,
150
+ `ctx ${m.contextWindow}`
151
+ ].filter(Boolean).join(", ");
152
+ process.stdout.write(` - ${m.id} ${m.name} (${flags})\n`);
153
+ }
154
+ return 0;
155
+ }
156
+ /**
157
+ * 本机用量账本(插件自己记的,不是账号额度)。
158
+ *
159
+ * 为什么要用 CLI 暴露它:账本是插件进程边跑边写的,GUI 卡片能看,但这个命令让
160
+ * 「今天到底花了多少 token」在无图形界面时也能查,且输出可以直接贴进问题反馈。
161
+ */
162
+ async function usage(jsonOutput) {
163
+ const tracker = new CodeArtsUsageTracker({ path: codeartsUsagePath() });
164
+ await tracker.load();
165
+ const snapshot = tracker.snapshot();
166
+ if (jsonOutput) {
167
+ process.stdout.write(JSON.stringify({
168
+ schemaVersion: JSON_SCHEMA_VERSION,
169
+ version: CODEARTS_VERSION,
170
+ today: snapshot.today,
171
+ allTime: snapshot.allTime,
172
+ byModelToday: snapshot.byModelToday,
173
+ byAccountToday: snapshot.byAccountToday,
174
+ days: snapshot.days,
175
+ lastAt: snapshot.lastAt
176
+ }, null, 2) + "\n");
177
+ return 0;
178
+ }
179
+ if (snapshot.allTime.requests === 0) {
180
+ process.stdout.write("no usage recorded yet (nothing this plugin has sent)\n");
181
+ return 0;
182
+ }
183
+ process.stdout.write(`today ${snapshot.today.requests} request(s), in ${snapshot.today.promptTokens} / out ${snapshot.today.completionTokens} tokens\n`);
184
+ process.stdout.write(`all time ${snapshot.allTime.requests} request(s), in ${snapshot.allTime.promptTokens} / out ${snapshot.allTime.completionTokens} tokens (${snapshot.days} day(s) kept)\n`);
185
+ if (snapshot.byModelToday.length > 0) {
186
+ process.stdout.write("today by model:\n");
187
+ for (const entry of snapshot.byModelToday) process.stdout.write(` - ${entry.id} ${entry.totals.requests} req in ${entry.totals.promptTokens} / out ${entry.totals.completionTokens}\n`);
188
+ }
189
+ const accounts = Object.entries(snapshot.byAccountToday);
190
+ if (accounts.length > 0) {
191
+ process.stdout.write("today by account:\n");
192
+ for (const [id, totals] of accounts) process.stdout.write(` - ${id.slice(0, 12)}… ${totals.requests} req in ${totals.promptTokens} / out ${totals.completionTokens}\n`);
193
+ }
194
+ process.stdout.write("note: this counts requests this machine sent through the plugin; account credits are in the card\n");
195
+ return 0;
196
+ }
197
+ /**
198
+ * 身份回填与重复账号清理。
199
+ *
200
+ * 背景:上游登录响应里的 `user_id` 是空串,插件原先只能拿 DPoP 公钥当账号键,
201
+ * 于是「对同一个账号重新登录」会多出一条记录(旧的那条之后因凭据失效而停用)。
202
+ * `/snap-manager/v1/current/user` 能给出稳定 user_id,所以:
203
+ * - 新登录会自动带上身份(见 web-status 的登录流程);
204
+ * - 历史遗留的条目用 `identity --fix` 合并到稳定键上。
205
+ */
206
+ async function identity(jsonOutput, fix) {
207
+ const accounts = await store();
208
+ const ids = await accounts.ids();
209
+ if (ids.length === 0) {
210
+ if (jsonOutput) process.stdout.write(JSON.stringify({
211
+ schemaVersion: JSON_SCHEMA_VERSION,
212
+ fixed: fix,
213
+ duplicateIdentities: 0,
214
+ accounts: []
215
+ }, null, 2) + "\n");
216
+ else process.stdout.write("not signed in — nothing to inspect\n");
217
+ return 1;
218
+ }
219
+ const rows = [];
220
+ for (const id of ids) {
221
+ const resolved = await accounts.resolve(id);
222
+ if (resolved === void 0) {
223
+ rows.push({
224
+ id,
225
+ ok: false,
226
+ error: "credential unavailable (sign in again)"
227
+ });
228
+ continue;
229
+ }
230
+ try {
231
+ const found = await fetchCallerIdentity(resolved);
232
+ const action = fix ? await accounts.adoptIdentity(id, found) : void 0;
233
+ rows.push({
234
+ id,
235
+ userId: found.userId,
236
+ ...found.userName === "" ? {} : { userName: found.userName },
237
+ ok: true,
238
+ ...action === void 0 ? {} : { action }
239
+ });
240
+ } catch (error) {
241
+ rows.push({
242
+ id,
243
+ ok: false,
244
+ error: error instanceof Error ? error.message : String(error)
245
+ });
246
+ }
247
+ }
248
+ const byUser = /* @__PURE__ */ new Map();
249
+ for (const row of rows) if (row.userId !== void 0) byUser.set(row.userId, (byUser.get(row.userId) ?? 0) + 1);
250
+ const duplicates = [...byUser.entries()].filter(([, count]) => count > 1).length;
251
+ if (jsonOutput) {
252
+ process.stdout.write(JSON.stringify({
253
+ schemaVersion: JSON_SCHEMA_VERSION,
254
+ fixed: fix,
255
+ duplicateIdentities: duplicates,
256
+ accounts: rows
257
+ }, null, 2) + "\n");
258
+ return 0;
259
+ }
260
+ for (const row of rows) {
261
+ if (!row.ok) {
262
+ process.stdout.write(` - ${row.id.slice(0, 12)}… identity probe failed: ${row.error}\n`);
263
+ continue;
264
+ }
265
+ const label = row.userName === void 0 ? "" : ` (${row.userName})`;
266
+ const acted = row.action === void 0 ? "" : ` [${row.action}]`;
267
+ process.stdout.write(` - ${row.id.slice(0, 12)}… -> ${row.userId}${label}${acted}\n`);
268
+ }
269
+ if (fix) process.stdout.write("identity backfilled; duplicate entries were merged into the stable user id\n");
270
+ else if (duplicates > 0) process.stdout.write(`found ${duplicates} user id(s) stored more than once; re-run with --fix to merge them\n`);
271
+ else process.stdout.write("no duplicate accounts found\n");
272
+ return 0;
273
+ }
274
+ async function doctor(jsonOutput) {
275
+ const accountsPath = codeartsAccountsPath();
276
+ const exists = existsSync(accountsPath);
277
+ const accounts = await store().list();
278
+ const signable = accounts.some((account) => account.signable);
279
+ const hints = [];
280
+ if (accounts.length === 0) hints.push("No account stored yet: sign in from the CodeArts settings card.");
281
+ else {
282
+ const stale = accounts.filter((account) => account.stale);
283
+ if (stale.length > 0) hints.push(`${stale.length} of ${accounts.length} account(s) were marked stale after a failed refresh; sign in again.`);
284
+ if (!signable) hints.push("No account carries AK/SK. CodeArts rejects unsigned chat requests — sign in with the OAuth flow rather than pasting a bare token.");
285
+ }
286
+ if (!process.env.DSH_HOME) hints.push("DSH_HOME is unset; the credential path fell back to ~/.dsh — set DSH_HOME if your harness lives elsewhere.");
287
+ const out = {
288
+ schemaVersion: JSON_SCHEMA_VERSION,
289
+ version: CODEARTS_VERSION,
290
+ node: process.version,
291
+ platform: `${process.platform} ${process.arch}`,
292
+ authPath: accountsPath,
293
+ authFileExists: exists,
294
+ signedIn: accounts.length > 0,
295
+ signable,
296
+ accounts,
297
+ hints
298
+ };
299
+ if (jsonOutput) {
300
+ process.stdout.write(JSON.stringify(out, null, 2) + "\n");
301
+ return hints.length === 0 ? 0 : 1;
302
+ }
303
+ process.stdout.write(`dsh-codearts ${out.version} (node ${out.node}, ${out.platform})\n`);
304
+ process.stdout.write(`accounts: ${out.authPath}\n`);
305
+ process.stdout.write(` file exists : ${out.authFileExists ? "yes" : "no"}${exists ? ` (${statSync(accountsPath).size} bytes)` : ""}\n`);
306
+ process.stdout.write(` accounts : ${accounts.length}\n`);
307
+ for (const account of accounts) process.stdout.write(` - ${describeAccount(account)}\n`);
308
+ process.stdout.write(` signable : ${out.signable ? "yes (AK/SK present)" : "no (no AK/SK)"}\n`);
309
+ if (hints.length === 0) process.stdout.write("no issues found\n");
310
+ else {
311
+ process.stdout.write("hints:\n");
312
+ for (const hint of hints) process.stdout.write(` - ${hint}\n`);
313
+ }
314
+ return hints.length === 0 ? 0 : 1;
315
+ }
316
+ async function logout(jsonOutput) {
317
+ const accountsPath = codeartsAccountsPath();
318
+ const removed = (await store().list()).length;
319
+ await store().clear();
320
+ if (jsonOutput) process.stdout.write(JSON.stringify({
321
+ schemaVersion: JSON_SCHEMA_VERSION,
322
+ signedOut: true,
323
+ removed,
324
+ authPath: accountsPath
325
+ }, null, 2) + "\n");
326
+ else process.stdout.write(`signed out; removed ${removed} account${removed === 1 ? "" : "s"}\n`);
327
+ return 0;
328
+ }
329
+ async function main() {
330
+ const args = process.argv.slice(2);
331
+ const jsonOutput = args.includes("--json");
332
+ const fix = args.includes("--fix");
333
+ const positional = args.filter((arg) => !arg.startsWith("--"));
334
+ const unknown = args.filter((arg) => arg.startsWith("--") && arg !== "--json" && arg !== "--fix");
335
+ const raw = positional[0] ?? "status";
336
+ if (![
337
+ "doctor",
338
+ "identity",
339
+ "logout",
340
+ "models",
341
+ "status",
342
+ "usage"
343
+ ].includes(raw)) {
344
+ process.stderr.write(`dsh-codearts: expected doctor, identity, logout, models, status, or usage; got ${JSON.stringify(raw)}\n`);
345
+ process.exit(2);
346
+ }
347
+ if (unknown.length > 0) {
348
+ process.stderr.write(`dsh-codearts: unknown flag ${JSON.stringify(unknown[0])} (only --json and --fix are supported)\n`);
349
+ process.exit(2);
350
+ }
351
+ const action = raw;
352
+ const code = action === "doctor" ? await doctor(jsonOutput) : action === "identity" ? await identity(jsonOutput, fix) : action === "logout" ? await logout(jsonOutput) : action === "models" ? await models(jsonOutput) : action === "usage" ? await usage(jsonOutput) : await status(jsonOutput);
353
+ process.exit(code);
354
+ }
355
+ main().catch((error) => {
356
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
357
+ process.exit(1);
358
+ });
359
+ //#endregion
360
+ export {};
@@ -0,0 +1,113 @@
1
+ import { n as __exportAll } from "./rolldown-runtime-B4iAMlE-.mjs";
2
+ //#region node_modules/.pnpm/@earendil-works+pi-ai@1.3.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+signature-v4@5.7.4_ws@8.22.0_zod@4.6.5/node_modules/@earendil-works/pi-ai/dist/utils/text.js
3
+ /** Extract and join text from message content. */
4
+ function contentText(content, separator = "\n") {
5
+ if (typeof content === "string") return content;
6
+ return content.filter((block) => block.type === "text").map((block) => block.text).join(separator);
7
+ }
8
+ /** Render a system message as a complete prompt: its content followed by its sections. */
9
+ function getSystemMessageText(message) {
10
+ const parts = [contentText(message.content)];
11
+ for (const text of Object.values(message.sections ?? {})) if (text !== null) parts.push(text);
12
+ return parts.filter((part) => part.length > 0).join("\n\n");
13
+ }
14
+ /**
15
+ * Render a later system message for APIs that accept system messages mid-conversation.
16
+ * Section changes are framed by name so the model can relate them to the leading prompt.
17
+ * This framing is request-time only and may change between versions.
18
+ */
19
+ function renderSystemMessageUpdate(message) {
20
+ const parts = [];
21
+ const text = contentText(message.content);
22
+ if (text.length > 0) parts.push(text);
23
+ for (const [name, value] of Object.entries(message.sections ?? {})) parts.push(value === null ? `Removed system prompt section "${name}".` : `Updated system prompt section "${name}":\n\n${value}`);
24
+ return parts.join("\n\n");
25
+ }
26
+ //#endregion
27
+ //#region node_modules/.pnpm/@earendil-works+pi-ai@1.3.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+signature-v4@5.7.4_ws@8.22.0_zod@4.6.5/node_modules/@earendil-works/pi-ai/dist/utils/estimate.js
28
+ var estimate_exports = /* @__PURE__ */ __exportAll({
29
+ calculateContextTokens: () => calculateContextTokens,
30
+ estimateContextTokens: () => estimateContextTokens,
31
+ estimateMessageTokens: () => estimateMessageTokens,
32
+ estimateTextAndImageContentTokens: () => estimateTextAndImageContentTokens,
33
+ estimateTextTokens: () => estimateTextTokens
34
+ });
35
+ const CHARS_PER_TOKEN = 3.5;
36
+ const ESTIMATED_IMAGE_CHARS = 4800;
37
+ function calculateContextTokens(usage) {
38
+ return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
39
+ }
40
+ function safeJsonStringify(value) {
41
+ try {
42
+ return JSON.stringify(value) ?? "undefined";
43
+ } catch {
44
+ return "[unserializable]";
45
+ }
46
+ }
47
+ function estimateTextAndImageContentChars(content) {
48
+ if (typeof content === "string") return content.length;
49
+ let chars = 0;
50
+ for (const block of content) chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;
51
+ return chars;
52
+ }
53
+ function estimateTextTokens(text) {
54
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
55
+ }
56
+ function estimateTextAndImageContentTokens(content) {
57
+ return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
58
+ }
59
+ function estimateMessageTokens(message) {
60
+ let chars = 0;
61
+ if (message.role === "system") return estimateTextTokens(getSystemMessageText(message)) + estimateToolsTokens(message.toolsAdded) + estimateToolsTokens(message.toolsRemoved);
62
+ if (message.role === "user") return estimateTextAndImageContentTokens(message.content);
63
+ if (message.role === "toolResult") return estimateTextAndImageContentTokens(message.content);
64
+ for (const block of message.content) if (block.type === "text") chars += block.text.length;
65
+ else if (block.type === "thinking") chars += block.thinking.length;
66
+ else chars += block.name.length + safeJsonStringify(block.arguments).length;
67
+ return Math.ceil(chars / CHARS_PER_TOKEN);
68
+ }
69
+ function getLastAssistantUsageInfo(messages) {
70
+ let latestPrefixTimestamp = Number.NEGATIVE_INFINITY;
71
+ let usageInfo;
72
+ for (let i = 0; i < messages.length; i++) {
73
+ const message = messages[i];
74
+ if (message.role === "assistant") {
75
+ const assistant = message;
76
+ if (assistant.timestamp >= latestPrefixTimestamp && assistant.stopReason !== "aborted" && assistant.stopReason !== "error" && calculateContextTokens(assistant.usage) > 0) usageInfo = {
77
+ usage: assistant.usage,
78
+ index: i
79
+ };
80
+ }
81
+ latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);
82
+ }
83
+ return usageInfo;
84
+ }
85
+ function estimateContextTokens(context) {
86
+ const messages = "messages" in context ? context.messages : context;
87
+ const usageInfo = getLastAssistantUsageInfo(messages);
88
+ if (usageInfo) {
89
+ const usageTokens = calculateContextTokens(usageInfo.usage);
90
+ let trailingTokens = 0;
91
+ for (let i = usageInfo.index + 1; i < messages.length; i++) trailingTokens += estimateMessageTokens(messages[i]);
92
+ return {
93
+ tokens: usageTokens + trailingTokens,
94
+ usageTokens,
95
+ trailingTokens,
96
+ lastUsageIndex: usageInfo.index
97
+ };
98
+ }
99
+ let tokens = 0;
100
+ for (const message of messages) tokens += estimateMessageTokens(message);
101
+ return {
102
+ tokens,
103
+ usageTokens: 0,
104
+ trailingTokens: tokens,
105
+ lastUsageIndex: null
106
+ };
107
+ }
108
+ function estimateToolsTokens(tools) {
109
+ if (!tools || tools.length === 0) return 0;
110
+ return estimateTextTokens(safeJsonStringify(tools));
111
+ }
112
+ //#endregion
113
+ export { renderSystemMessageUpdate as a, getSystemMessageText as i, estimate_exports as n, contentText as r, estimateContextTokens as t };