@chosengeneration/light-code 0.172.0 → 0.174.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.
- package/dist/cli.cjs +421 -34
- package/dist/server.cjs +410 -31
- package/package.json +1 -1
package/dist/server.cjs
CHANGED
|
@@ -43203,6 +43203,9 @@ var OpenAIProvider = class {
|
|
|
43203
43203
|
body.tools = toOpenAITools(options.tools);
|
|
43204
43204
|
body.tool_choice = "auto";
|
|
43205
43205
|
}
|
|
43206
|
+
const usageKey = this.profile.baseUrl.replace(/\/+$/, "");
|
|
43207
|
+
if (!NO_STREAM_USAGE.has(usageKey))
|
|
43208
|
+
body.stream_options = { include_usage: true };
|
|
43206
43209
|
if (this.profile.temperature !== void 0)
|
|
43207
43210
|
body.temperature = this.profile.temperature;
|
|
43208
43211
|
if (this.profile.topP !== void 0)
|
|
@@ -43212,6 +43215,17 @@ var OpenAIProvider = class {
|
|
|
43212
43215
|
try {
|
|
43213
43216
|
await this.auth.ensureTokenForStream?.();
|
|
43214
43217
|
response = await this.send(url2, body, options.signal);
|
|
43218
|
+
if (response.status >= 400 && response.status < 500 && response.status !== 401 && body.stream_options !== void 0) {
|
|
43219
|
+
const text2 = await response.text().catch(() => "");
|
|
43220
|
+
if (/stream_options|include_usage/i.test(text2)) {
|
|
43221
|
+
NO_STREAM_USAGE.add(usageKey);
|
|
43222
|
+
delete body.stream_options;
|
|
43223
|
+
response = await this.send(url2, body, options.signal);
|
|
43224
|
+
} else {
|
|
43225
|
+
yield { type: "error", error: `Request to ${url2} failed with HTTP ${response.status}${text2 ? `: ${text2.slice(0, 500)}` : ""}` };
|
|
43226
|
+
return;
|
|
43227
|
+
}
|
|
43228
|
+
}
|
|
43215
43229
|
if (response.status === 401 && this.auth.onUnauthorized !== void 0) {
|
|
43216
43230
|
this.logger?.debug("401 received; asking the auth strategy to refresh once");
|
|
43217
43231
|
if (await this.auth.onUnauthorized()) {
|
|
@@ -43252,6 +43266,20 @@ var OpenAIProvider = class {
|
|
|
43252
43266
|
return this.http.request(url2, request);
|
|
43253
43267
|
}
|
|
43254
43268
|
};
|
|
43269
|
+
var NO_STREAM_USAGE = /* @__PURE__ */ new Set();
|
|
43270
|
+
function usageFrom(parsed) {
|
|
43271
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
43272
|
+
return void 0;
|
|
43273
|
+
const usage = parsed.usage;
|
|
43274
|
+
if (usage === void 0 || usage === null || typeof usage.prompt_tokens !== "number")
|
|
43275
|
+
return void 0;
|
|
43276
|
+
return {
|
|
43277
|
+
type: "usage",
|
|
43278
|
+
inputTokens: usage.prompt_tokens,
|
|
43279
|
+
...typeof usage.completion_tokens === "number" ? { outputTokens: usage.completion_tokens } : {},
|
|
43280
|
+
...typeof usage.prompt_tokens_details?.cached_tokens === "number" ? { cachedTokens: usage.prompt_tokens_details.cached_tokens } : {}
|
|
43281
|
+
};
|
|
43282
|
+
}
|
|
43255
43283
|
function extractChoice(parsed) {
|
|
43256
43284
|
if (typeof parsed !== "object" || parsed === null || !("choices" in parsed))
|
|
43257
43285
|
return void 0;
|
|
@@ -43294,9 +43322,30 @@ async function* parseSseStream(body, url2, signal, logger) {
|
|
|
43294
43322
|
let buffer = "";
|
|
43295
43323
|
const thinking = new ThinkTagSplitter();
|
|
43296
43324
|
const toolCallAccumulators = /* @__PURE__ */ new Map();
|
|
43325
|
+
let finishedAt;
|
|
43326
|
+
const AFTER_FINISH_MS = 5e3;
|
|
43297
43327
|
try {
|
|
43298
43328
|
while (true) {
|
|
43299
|
-
|
|
43329
|
+
let next;
|
|
43330
|
+
if (finishedAt === void 0)
|
|
43331
|
+
next = await reader.read();
|
|
43332
|
+
else {
|
|
43333
|
+
const left = Math.max(0, AFTER_FINISH_MS - (Date.now() - finishedAt));
|
|
43334
|
+
let timer;
|
|
43335
|
+
next = await Promise.race([
|
|
43336
|
+
reader.read(),
|
|
43337
|
+
new Promise((resolve) => {
|
|
43338
|
+
timer = setTimeout(() => resolve("late"), left);
|
|
43339
|
+
})
|
|
43340
|
+
]);
|
|
43341
|
+
clearTimeout(timer);
|
|
43342
|
+
}
|
|
43343
|
+
if (next === "late") {
|
|
43344
|
+
void reader.cancel().catch(() => void 0);
|
|
43345
|
+
yield { type: "done" };
|
|
43346
|
+
return;
|
|
43347
|
+
}
|
|
43348
|
+
const { done, value } = next;
|
|
43300
43349
|
if (done)
|
|
43301
43350
|
break;
|
|
43302
43351
|
buffer += decoder2.decode(value, { stream: true });
|
|
@@ -43315,6 +43364,9 @@ async function* parseSseStream(body, url2, signal, logger) {
|
|
|
43315
43364
|
}
|
|
43316
43365
|
try {
|
|
43317
43366
|
const parsed = JSON.parse(data);
|
|
43367
|
+
const usage = usageFrom(parsed);
|
|
43368
|
+
if (usage !== void 0)
|
|
43369
|
+
yield usage;
|
|
43318
43370
|
const choice = extractChoice(parsed);
|
|
43319
43371
|
if (choice === void 0)
|
|
43320
43372
|
continue;
|
|
@@ -43330,12 +43382,11 @@ async function* parseSseStream(body, url2, signal, logger) {
|
|
|
43330
43382
|
yield { type: "text", text: split.text };
|
|
43331
43383
|
}
|
|
43332
43384
|
accumulateToolCallDeltas(toolCallAccumulators, choice.delta.tool_calls);
|
|
43333
|
-
if (choice.finishReason === "tool_calls") {
|
|
43385
|
+
if (choice.finishReason === "tool_calls" && finishedAt === void 0) {
|
|
43334
43386
|
for (const toolCall of completedToolCalls(toolCallAccumulators)) {
|
|
43335
43387
|
yield { type: "toolCall", toolCall };
|
|
43336
43388
|
}
|
|
43337
|
-
|
|
43338
|
-
return;
|
|
43389
|
+
finishedAt = Date.now();
|
|
43339
43390
|
}
|
|
43340
43391
|
} catch {
|
|
43341
43392
|
}
|
|
@@ -43524,6 +43575,14 @@ async function* parseAnthropicStream(body, url2, signal, logger) {
|
|
|
43524
43575
|
continue;
|
|
43525
43576
|
}
|
|
43526
43577
|
const eventType = parsed.type;
|
|
43578
|
+
if (eventType === "message_start") {
|
|
43579
|
+
const usage = parsed.message?.usage;
|
|
43580
|
+
if (typeof usage?.input_tokens === "number") {
|
|
43581
|
+
const cached2 = typeof usage.cache_read_input_tokens === "number" ? usage.cache_read_input_tokens : 0;
|
|
43582
|
+
const created = typeof usage.cache_creation_input_tokens === "number" ? usage.cache_creation_input_tokens : 0;
|
|
43583
|
+
yield { type: "usage", inputTokens: usage.input_tokens + cached2 + created, cachedTokens: cached2 };
|
|
43584
|
+
}
|
|
43585
|
+
}
|
|
43527
43586
|
if (eventType === "content_block_start") {
|
|
43528
43587
|
const index = typeof parsed.index === "number" ? parsed.index : 0;
|
|
43529
43588
|
const block2 = parsed.content_block;
|
|
@@ -43761,6 +43820,15 @@ async function* parseGeminiStream(body, url2, signal) {
|
|
|
43761
43820
|
} catch {
|
|
43762
43821
|
continue;
|
|
43763
43822
|
}
|
|
43823
|
+
const usage = parsed.usageMetadata;
|
|
43824
|
+
if (typeof usage?.promptTokenCount === "number") {
|
|
43825
|
+
yield {
|
|
43826
|
+
type: "usage",
|
|
43827
|
+
inputTokens: usage.promptTokenCount,
|
|
43828
|
+
...typeof usage.candidatesTokenCount === "number" ? { outputTokens: usage.candidatesTokenCount } : {},
|
|
43829
|
+
...typeof usage.cachedContentTokenCount === "number" ? { cachedTokens: usage.cachedContentTokenCount } : {}
|
|
43830
|
+
};
|
|
43831
|
+
}
|
|
43764
43832
|
const candidates = parsed.candidates;
|
|
43765
43833
|
if (!Array.isArray(candidates) || candidates.length === 0)
|
|
43766
43834
|
continue;
|
|
@@ -44060,6 +44128,40 @@ function estimateTokens(text2) {
|
|
|
44060
44128
|
return 0;
|
|
44061
44129
|
return Math.ceil(text2.length / 4);
|
|
44062
44130
|
}
|
|
44131
|
+
var calibrations = /* @__PURE__ */ new Map();
|
|
44132
|
+
function calibrate(key3, estimated, reported) {
|
|
44133
|
+
if (!(estimated > 0) || !(reported > 0))
|
|
44134
|
+
return;
|
|
44135
|
+
const ratio = reported / estimated;
|
|
44136
|
+
if (ratio < 0.5 || ratio > 4)
|
|
44137
|
+
return;
|
|
44138
|
+
const previous = calibrations.get(key3);
|
|
44139
|
+
calibrations.set(key3, previous === void 0 ? ratio : previous * 0.3 + ratio * 0.7);
|
|
44140
|
+
}
|
|
44141
|
+
function calibrationFor(key3) {
|
|
44142
|
+
return calibrations.get(key3);
|
|
44143
|
+
}
|
|
44144
|
+
function scaleBreakdown(breakdown, ratio) {
|
|
44145
|
+
if (ratio === void 0 || ratio === 1)
|
|
44146
|
+
return breakdown;
|
|
44147
|
+
const s = (n) => Math.round(n * ratio);
|
|
44148
|
+
return { ...breakdown, system: s(breakdown.system), toolDefinitions: s(breakdown.toolDefinitions), history: s(breakdown.history), results: s(breakdown.results), total: s(breakdown.total) };
|
|
44149
|
+
}
|
|
44150
|
+
function promptTokensFromError(error51) {
|
|
44151
|
+
const patterns = [
|
|
44152
|
+
/prompt contains (?:at least )?([\d,]+) (?:input )?tokens/i,
|
|
44153
|
+
/prompt is too long:?\s*([\d,]+)\s*tokens/i,
|
|
44154
|
+
/(?:requested|resulted in|have)\s+([\d,]+)\s+tokens?\b[^.]*(?:messages|prompt|input)/i,
|
|
44155
|
+
/input (?:length|tokens?)[^\d]{0,20}([\d,]+)/i
|
|
44156
|
+
];
|
|
44157
|
+
for (const pattern of patterns) {
|
|
44158
|
+
const m = pattern.exec(error51);
|
|
44159
|
+
const n = m?.[1] !== void 0 ? Number(m[1].replace(/,/g, "")) : NaN;
|
|
44160
|
+
if (Number.isFinite(n) && n > 0)
|
|
44161
|
+
return n;
|
|
44162
|
+
}
|
|
44163
|
+
return void 0;
|
|
44164
|
+
}
|
|
44063
44165
|
function computeBreakdown(messages, tools, contextWindow) {
|
|
44064
44166
|
let system = 0;
|
|
44065
44167
|
let history = 0;
|
|
@@ -44094,6 +44196,25 @@ function computeBreakdown(messages, tools, contextWindow) {
|
|
|
44094
44196
|
estimated: true
|
|
44095
44197
|
};
|
|
44096
44198
|
}
|
|
44199
|
+
function applyReportedUsage(breakdown, usage) {
|
|
44200
|
+
const reportedInput = usage?.inputTokens;
|
|
44201
|
+
if (reportedInput === void 0)
|
|
44202
|
+
return breakdown;
|
|
44203
|
+
const estimatedTotal = breakdown.total;
|
|
44204
|
+
const trueTotal = reportedInput + (usage?.cacheReadTokens ?? 0);
|
|
44205
|
+
if (estimatedTotal === 0)
|
|
44206
|
+
return { ...breakdown, total: trueTotal, estimated: false };
|
|
44207
|
+
const scale = trueTotal / estimatedTotal;
|
|
44208
|
+
return {
|
|
44209
|
+
system: Math.round(breakdown.system * scale),
|
|
44210
|
+
toolDefinitions: Math.round(breakdown.toolDefinitions * scale),
|
|
44211
|
+
history: Math.round(breakdown.history * scale),
|
|
44212
|
+
results: Math.round(breakdown.results * scale),
|
|
44213
|
+
total: trueTotal,
|
|
44214
|
+
contextWindow: breakdown.contextWindow,
|
|
44215
|
+
estimated: false
|
|
44216
|
+
};
|
|
44217
|
+
}
|
|
44097
44218
|
|
|
44098
44219
|
// ../../packages/core/dist/context/supersede.js
|
|
44099
44220
|
var SUPERSEDED_MARKER = "[Superseded: this file was read again later in the conversation. See the most recent read for current contents.]";
|
|
@@ -59549,6 +59670,29 @@ async function pythonVersion(program) {
|
|
|
59549
59670
|
// ../../packages/core/dist/python/worker.js
|
|
59550
59671
|
var import_node_child_process5 = require("node:child_process");
|
|
59551
59672
|
var import_node_readline = require("node:readline");
|
|
59673
|
+
function describeWorkerExit(code, signal) {
|
|
59674
|
+
if (signal !== null)
|
|
59675
|
+
return `The Python worker was stopped (${signal}).`;
|
|
59676
|
+
if (code === null)
|
|
59677
|
+
return "The Python worker exited.";
|
|
59678
|
+
const unsigned = code < 0 ? code + 4294967296 : code;
|
|
59679
|
+
const hex3 = `0x${unsigned.toString(16).toUpperCase().padStart(8, "0")}`;
|
|
59680
|
+
const known = {
|
|
59681
|
+
"0xC0000005": "an access violation inside Python or a library it loaded (a native extension, or a DLL it found on PATH)",
|
|
59682
|
+
"0xC00000FD": "a stack overflow - usually deep recursion in a tool",
|
|
59683
|
+
"0xC0000409": "a security check failure in native code",
|
|
59684
|
+
"0xC0000374": "heap corruption in native code",
|
|
59685
|
+
"0xC000001D": "an illegal instruction - a library built for a newer CPU",
|
|
59686
|
+
"0xC0000135": "a DLL it needs could not be found",
|
|
59687
|
+
"0xC0000017": "it ran out of memory",
|
|
59688
|
+
"0xC000013A": "it was interrupted (Ctrl+C)"
|
|
59689
|
+
};
|
|
59690
|
+
if (known[hex3] !== void 0)
|
|
59691
|
+
return `The Python worker crashed (${hex3}: ${known[hex3]}).`;
|
|
59692
|
+
if (unsigned >= 3221225472)
|
|
59693
|
+
return `The Python worker crashed (Windows code ${hex3}).`;
|
|
59694
|
+
return `The Python worker exited with code ${String(code)}.`;
|
|
59695
|
+
}
|
|
59552
59696
|
var PythonWorkerError = class extends Error {
|
|
59553
59697
|
traceback;
|
|
59554
59698
|
constructor(message5, traceback) {
|
|
@@ -59568,6 +59712,8 @@ var PythonWorker = class {
|
|
|
59568
59712
|
constructor(options) {
|
|
59569
59713
|
this.options = options;
|
|
59570
59714
|
}
|
|
59715
|
+
/** The worker's last stderr, for saying why it crashed. */
|
|
59716
|
+
stderrTail = "";
|
|
59571
59717
|
start() {
|
|
59572
59718
|
if (this.child !== void 0 && this.child.exitCode === null && !this.child.killed)
|
|
59573
59719
|
return this.child;
|
|
@@ -59582,10 +59728,20 @@ var PythonWorker = class {
|
|
|
59582
59728
|
this.reader = (0, import_node_readline.createInterface)({ input: child.stdout });
|
|
59583
59729
|
this.reader.on("line", (line) => this.onLine(line));
|
|
59584
59730
|
child.stderr.on("data", (chunk) => {
|
|
59585
|
-
|
|
59731
|
+
const text2 = chunk.toString("utf8").trimEnd();
|
|
59732
|
+
this.options.logger.warn("python worker stderr", text2);
|
|
59733
|
+
this.stderrTail = `${this.stderrTail}
|
|
59734
|
+
${text2}`.slice(-4e3);
|
|
59586
59735
|
});
|
|
59736
|
+
child.stdin.on("error", (error51) => this.options.logger.warn("python worker input closed", String(error51)));
|
|
59587
59737
|
child.on("exit", (code, signal) => {
|
|
59588
|
-
const reason = new PythonWorkerError(
|
|
59738
|
+
const reason = new PythonWorkerError(`${describeWorkerExit(code, signal)} It will restart on the next call.${this.stderrTail.trim() ? `
|
|
59739
|
+
|
|
59740
|
+
Its last output:
|
|
59741
|
+
${this.stderrTail.trim().split("\n").slice(-15).join("\n")}` : ""}`);
|
|
59742
|
+
if (code !== 0 && code !== null)
|
|
59743
|
+
this.options.logger.warn("python worker crashed", describeWorkerExit(code, signal));
|
|
59744
|
+
this.stderrTail = "";
|
|
59589
59745
|
for (const [, entry] of this.pending) {
|
|
59590
59746
|
clearTimeout(entry.timer);
|
|
59591
59747
|
entry.reject(reason);
|
|
@@ -60608,11 +60764,21 @@ var SHARE_SECTIONS = [
|
|
|
60608
60764
|
{
|
|
60609
60765
|
id: "atlassian",
|
|
60610
60766
|
label: "DevOps",
|
|
60611
|
-
description: "The Confluence, Jira, Bitbucket
|
|
60612
|
-
keys: ["confluence", "jira", "bitbucket", "jenkins", "
|
|
60767
|
+
description: "The Confluence, Jira, Bitbucket and Jenkins sites, their defaults and read-only settings, and the team repository for skills and tools. Tokens and passwords are not included. AutoSys is its own section, below.",
|
|
60768
|
+
keys: ["confluence", "jira", "bitbucket", "jenkins", "teamRepo"],
|
|
60613
60769
|
// A user id names one person: kept out of the file, and the importer's own is kept.
|
|
60614
|
-
strip: ["jenkins.username"
|
|
60615
|
-
stripNote: "Your Jenkins
|
|
60770
|
+
strip: ["jenkins.username"],
|
|
60771
|
+
stripNote: "Your Jenkins user name is left out; each person uses their own."
|
|
60772
|
+
},
|
|
60773
|
+
{
|
|
60774
|
+
// Asked for: "export only the AutoSys config and import only that". Its own section, so a file can carry
|
|
60775
|
+
// AutoSys alone, and importing it replaces the AutoSys settings and nothing else.
|
|
60776
|
+
id: "autosys",
|
|
60777
|
+
label: "AutoSys",
|
|
60778
|
+
description: "The AutoSys site, its addresses, the API gateway (token address, client id, headers), the test job and read-only setting. Passwords, secrets and certificate passphrases are not included. Alone, an import changes only AutoSys.",
|
|
60779
|
+
keys: ["autosys"],
|
|
60780
|
+
strip: ["autosys.username"],
|
|
60781
|
+
stripNote: "Your AutoSys user name is left out; each person uses their own."
|
|
60616
60782
|
},
|
|
60617
60783
|
{
|
|
60618
60784
|
id: "autosysAddresses",
|
|
@@ -60717,6 +60883,8 @@ function detailFor(section, config2) {
|
|
|
60717
60883
|
const sites = [config2.confluence?.baseUrl, config2.jira?.baseUrl, config2.bitbucket?.baseUrl].filter((site) => site !== void 0);
|
|
60718
60884
|
return sites.length > 0 ? sites.join(", ") : "not set up";
|
|
60719
60885
|
}
|
|
60886
|
+
case "autosys":
|
|
60887
|
+
return config2.autosys?.baseUrl ?? "not set up";
|
|
60720
60888
|
case "autosysAddresses":
|
|
60721
60889
|
return count(Object.keys(config2.autosys?.paths ?? {}).length, "address", "addresses");
|
|
60722
60890
|
case "datasets":
|
|
@@ -60766,6 +60934,8 @@ function secretRefsFor(section, config2) {
|
|
|
60766
60934
|
refs.push("Bitbucket: personal access token");
|
|
60767
60935
|
if (config2.jenkins?.tokenRef !== void 0)
|
|
60768
60936
|
refs.push("Jenkins: API token and user id");
|
|
60937
|
+
break;
|
|
60938
|
+
case "autosys":
|
|
60769
60939
|
if (config2.autosys?.auth?.type === "apigee") {
|
|
60770
60940
|
refs.push("AutoSys: gateway client secret");
|
|
60771
60941
|
if (config2.autosys.auth.passphraseRef !== void 0)
|
|
@@ -62373,6 +62543,11 @@ var PythonManager = class {
|
|
|
62373
62543
|
* declaration would be the setting not working.
|
|
62374
62544
|
*/
|
|
62375
62545
|
...this.jupyterConnectionFile !== void 0 ? { [JUPYTER_CONNECTION_ENV]: this.jupyterConnectionFile } : {},
|
|
62546
|
+
/*
|
|
62547
|
+
* A native crash - "python.exe has stopped working" - prints the Python stack it happened in to stderr, which
|
|
62548
|
+
* the worker keeps and reports. Without it the only trace was Windows' dialog. A user setting wins.
|
|
62549
|
+
*/
|
|
62550
|
+
PYTHONFAULTHANDLER: "1",
|
|
62376
62551
|
...resolved.env,
|
|
62377
62552
|
// Last, so nothing declared in python.env can replace the list the worker enforces.
|
|
62378
62553
|
LIGHT_CODE_BANNED_CALLS: JSON.stringify(this.bannedCalls)
|
|
@@ -62964,6 +63139,8 @@ async function consumeStream(provider, messages, streamOptions, stallSeconds, ev
|
|
|
62964
63139
|
} else if (chunk.type === "toolCall") {
|
|
62965
63140
|
if (outcome.toolCall === void 0)
|
|
62966
63141
|
outcome.toolCall = chunk.toolCall;
|
|
63142
|
+
} else if (chunk.type === "usage") {
|
|
63143
|
+
outcome.usage = { inputTokens: chunk.inputTokens, ...chunk.outputTokens !== void 0 ? { outputTokens: chunk.outputTokens } : {}, ...chunk.cachedTokens !== void 0 ? { cachedTokens: chunk.cachedTokens } : {} };
|
|
62967
63144
|
} else if (chunk.type === "error") {
|
|
62968
63145
|
outcome.error = chunk.error;
|
|
62969
63146
|
} else if (chunk.type === "done") {
|
|
@@ -62982,11 +63159,12 @@ var MAX_REFUNDED_STEPS = 20;
|
|
|
62982
63159
|
var FORM_DISMISSED = "The user dismissed the form without answering.";
|
|
62983
63160
|
var MAX_FORM_RESETS = 5;
|
|
62984
63161
|
var MAX_CONSECUTIVE_MISTAKES = 3;
|
|
62985
|
-
async function prepareModelMessages(conversation, provider, tools, options, events) {
|
|
63162
|
+
async function prepareModelMessages(conversation, provider, tools, options, events, meter) {
|
|
62986
63163
|
const contextWindow = options.contextWindow ?? 0;
|
|
63164
|
+
const ratio = calibrationFor(options.usageKey ?? "");
|
|
62987
63165
|
let messages = repairUnansweredToolCalls(conversation.toModelMessages());
|
|
62988
63166
|
if (options.compactionEnabled !== false && options.autoCompact !== false && contextWindow > 0 && options.contextWindowKnown !== false) {
|
|
62989
|
-
const estimated = computeBreakdown(messages, tools, contextWindow).total;
|
|
63167
|
+
const estimated = scaleBreakdown(computeBreakdown(messages, tools, contextWindow), ratio).total;
|
|
62990
63168
|
if (shouldCompact(messages, estimated, contextWindow, options.compaction ?? {})) {
|
|
62991
63169
|
const result = await compactHistory(messages, provider, {
|
|
62992
63170
|
// Keep recent history by size as well as by count, so a long window keeps a long tail.
|
|
@@ -63005,8 +63183,13 @@ async function prepareModelMessages(conversation, provider, tools, options, even
|
|
|
63005
63183
|
}
|
|
63006
63184
|
const superseded = dropSupersededReads(messages);
|
|
63007
63185
|
const evicted = dropEvictedDocs(superseded.messages);
|
|
63008
|
-
const
|
|
63009
|
-
|
|
63186
|
+
const raw = computeBreakdown(evicted.messages, tools, contextWindow);
|
|
63187
|
+
if (meter !== void 0) {
|
|
63188
|
+
meter.estimated = raw.total;
|
|
63189
|
+
meter.breakdown = raw;
|
|
63190
|
+
meter.dropped = superseded.supersededCount + evicted.evictedCount;
|
|
63191
|
+
}
|
|
63192
|
+
events.onContextUpdate?.(scaleBreakdown(raw, ratio), superseded.supersededCount + evicted.evictedCount, conversation.compactedCount());
|
|
63010
63193
|
return evicted.messages;
|
|
63011
63194
|
}
|
|
63012
63195
|
function unwrapDispatch(toolCall) {
|
|
@@ -63181,7 +63364,8 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
|
|
|
63181
63364
|
const streamOptions = { tools };
|
|
63182
63365
|
if (options.signal !== void 0)
|
|
63183
63366
|
streamOptions.signal = options.signal;
|
|
63184
|
-
const
|
|
63367
|
+
const meter = { estimated: 0, dropped: 0 };
|
|
63368
|
+
const modelMessages = await prepareModelMessages(conversation, provider, tools, options, events, meter);
|
|
63185
63369
|
const stallSeconds = options.stallSeconds ?? DEFAULT_STALL_SECONDS;
|
|
63186
63370
|
const maxRetries = Math.max(0, options.retries ?? DEFAULT_RETRIES);
|
|
63187
63371
|
const cancelled = () => options.signal?.aborted === true;
|
|
@@ -63202,6 +63386,17 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
|
|
|
63202
63386
|
const assistantText = outcome.text;
|
|
63203
63387
|
const toolCall = outcome.toolCall;
|
|
63204
63388
|
let streamError = outcome.error;
|
|
63389
|
+
const reportedInput = outcome.usage?.inputTokens ?? (streamError !== void 0 && isContextOverflow(streamError) ? promptTokensFromError(streamError) : void 0);
|
|
63390
|
+
if (reportedInput !== void 0 && meter.breakdown !== void 0) {
|
|
63391
|
+
calibrate(options.usageKey ?? "", meter.estimated, reportedInput);
|
|
63392
|
+
events.onContextUpdate?.(applyReportedUsage(meter.breakdown, { inputTokens: reportedInput }), meter.dropped, conversation.compactedCount());
|
|
63393
|
+
}
|
|
63394
|
+
if (outcome.usage !== void 0) {
|
|
63395
|
+
events.onUsage?.({ inputTokens: outcome.usage.inputTokens, outputTokens: outcome.usage.outputTokens ?? estimateTokens(assistantText), ...outcome.usage.cachedTokens !== void 0 ? { cachedTokens: outcome.usage.cachedTokens } : {}, estimated: outcome.usage.outputTokens === void 0 });
|
|
63396
|
+
} else if (streamError === void 0 && meter.breakdown !== void 0) {
|
|
63397
|
+
const output = estimateTokens(assistantText) + (toolCall !== void 0 ? estimateTokens(toolCall.name + toolCall.arguments) : 0);
|
|
63398
|
+
events.onUsage?.({ inputTokens: scaleBreakdown(meter.breakdown, calibrationFor(options.usageKey ?? "")).total, outputTokens: output, estimated: true });
|
|
63399
|
+
}
|
|
63205
63400
|
if (outcome.stalled && !cancelled()) {
|
|
63206
63401
|
streamError = `${stallDescription(stallSeconds)}, so the request was stopped` + (maxRetries > 0 ? ` (tried ${String(maxRetries + 1)} times)` : "") + '. The gateway may be overloaded, or the connection dropped without saying so. Send your message again to retry. If this model genuinely thinks for longer than that without streaming anything, raise "Give up on a silent reply after" in Settings \u2192 Approvals.';
|
|
63207
63402
|
}
|
|
@@ -65021,11 +65216,12 @@ var import_node_crypto12 = require("node:crypto");
|
|
|
65021
65216
|
var import_node_fs5 = require("node:fs");
|
|
65022
65217
|
var import_node_os5 = __toESM(require("node:os"), 1);
|
|
65023
65218
|
var import_node_path34 = __toESM(require("node:path"), 1);
|
|
65219
|
+
var isTokenEvent = (event) => event.k === "tokens";
|
|
65024
65220
|
function isUsageEvent(value) {
|
|
65025
65221
|
if (value === null || typeof value !== "object")
|
|
65026
65222
|
return false;
|
|
65027
65223
|
const event = value;
|
|
65028
|
-
return typeof event["t"] === "number" && typeof event["u"] === "string" && (event["k"] === "skill" || event["k"] === "tool") && typeof event["n"] === "string";
|
|
65224
|
+
return typeof event["t"] === "number" && typeof event["u"] === "string" && (event["k"] === "skill" || event["k"] === "tool" || event["k"] === "tokens") && typeof event["n"] === "string";
|
|
65029
65225
|
}
|
|
65030
65226
|
function parseUsageLines(text2) {
|
|
65031
65227
|
const events = [];
|
|
@@ -66351,6 +66547,7 @@ function fastFsCapabilities(exe, timeoutMs = 5e3) {
|
|
|
66351
66547
|
done(void 0);
|
|
66352
66548
|
}
|
|
66353
66549
|
});
|
|
66550
|
+
child.stdin.on("error", () => void 0);
|
|
66354
66551
|
child.stdin.end(JSON.stringify({ op: "capabilities" }));
|
|
66355
66552
|
});
|
|
66356
66553
|
}
|
|
@@ -66448,6 +66645,7 @@ function runHelper(exe, request, signal) {
|
|
|
66448
66645
|
reject2(new Error(`The file helper gave no answer${err.length > 0 ? `: ${err.slice(0, 300)}` : "."}`));
|
|
66449
66646
|
}
|
|
66450
66647
|
});
|
|
66648
|
+
child.stdin.on("error", () => void 0);
|
|
66451
66649
|
child.stdin.end(JSON.stringify(request));
|
|
66452
66650
|
});
|
|
66453
66651
|
}
|
|
@@ -67789,6 +67987,7 @@ function negotiateRequest(request, signal) {
|
|
|
67789
67987
|
}
|
|
67790
67988
|
resolve({ status: answer.status ?? 0, headers: answer.headers ?? {}, body: Buffer.from(answer.body ?? "", "base64") });
|
|
67791
67989
|
});
|
|
67990
|
+
child.stdin.on("error", () => void 0);
|
|
67792
67991
|
child.stdin.end(JSON.stringify(request));
|
|
67793
67992
|
});
|
|
67794
67993
|
}
|
|
@@ -70728,6 +70927,7 @@ var OfficeBridge = class {
|
|
|
70728
70927
|
child.stderr?.on("data", (chunk) => {
|
|
70729
70928
|
this.options.logger.warn(`office worker: ${String(chunk).trim().slice(0, 500)}`);
|
|
70730
70929
|
});
|
|
70930
|
+
child.stdin?.on("error", () => void 0);
|
|
70731
70931
|
child.on("exit", (code) => {
|
|
70732
70932
|
if (this.child !== child)
|
|
70733
70933
|
return;
|
|
@@ -74142,7 +74342,8 @@ function isAutosysName(name, pattern = false) {
|
|
|
74142
74342
|
function fill(template, values) {
|
|
74143
74343
|
return template.replace(/\{(filter:)?(\w+)\}/g, (_, filter, key3) => {
|
|
74144
74344
|
if (filter !== void 0) {
|
|
74145
|
-
|
|
74345
|
+
const value = values["pattern"] ?? values[key3] ?? values["job"] ?? "";
|
|
74346
|
+
return encodeURIComponent(`${key3}${value.includes("*") ? "=@" : "=="}${value}`);
|
|
74146
74347
|
}
|
|
74147
74348
|
return encodeURIComponent(values[key3] ?? "");
|
|
74148
74349
|
});
|
|
@@ -79643,6 +79844,8 @@ var NodeTerminalProcess = class {
|
|
|
79643
79844
|
this.exitListeners.push(listener);
|
|
79644
79845
|
}
|
|
79645
79846
|
write(data) {
|
|
79847
|
+
if (this.child.stdin !== null && this.child.stdin.listenerCount("error") === 0)
|
|
79848
|
+
this.child.stdin.on("error", () => void 0);
|
|
79646
79849
|
this.child.stdin?.write(data);
|
|
79647
79850
|
}
|
|
79648
79851
|
/** `child.kill()` alone leaves grandchildren running — see CLAUDE.md §16. */
|
|
@@ -80351,6 +80554,69 @@ async function rollUpMonths(options) {
|
|
|
80351
80554
|
// ../../packages/core/dist/usage/dashboard.js
|
|
80352
80555
|
var HOUR = 36e5;
|
|
80353
80556
|
var DAY = 24 * HOUR;
|
|
80557
|
+
var zeroTokens = () => ({ input: 0, output: 0, cached: 0, requests: 0 });
|
|
80558
|
+
function addTokens(into, event) {
|
|
80559
|
+
into.input += event.i ?? 0;
|
|
80560
|
+
into.output += event.o ?? 0;
|
|
80561
|
+
into.cached += event.c ?? 0;
|
|
80562
|
+
into.requests += 1;
|
|
80563
|
+
}
|
|
80564
|
+
function tokenStats(events, o) {
|
|
80565
|
+
const inScope = (event) => o.scope === "team" || event.u === o.me;
|
|
80566
|
+
const current = events.filter((event) => event.t >= o.from && event.t <= o.to && inScope(event));
|
|
80567
|
+
const total = zeroTokens();
|
|
80568
|
+
const previous = zeroTokens();
|
|
80569
|
+
for (const event of events)
|
|
80570
|
+
if (event.t >= o.previousFrom && event.t < o.from && inScope(event))
|
|
80571
|
+
addTokens(previous, event);
|
|
80572
|
+
const people = /* @__PURE__ */ new Map();
|
|
80573
|
+
const models = /* @__PURE__ */ new Map();
|
|
80574
|
+
const timeline = o.starts.map((start) => ({ start, input: 0, output: 0 }));
|
|
80575
|
+
let estimated = 0;
|
|
80576
|
+
for (const event of current) {
|
|
80577
|
+
addTokens(total, event);
|
|
80578
|
+
if (event.e === 1)
|
|
80579
|
+
estimated += 1;
|
|
80580
|
+
let person = people.get(event.u);
|
|
80581
|
+
if (person === void 0) {
|
|
80582
|
+
person = { ...zeroTokens(), lastActive: 0, spark: new Array(o.starts.length).fill(0), models: /* @__PURE__ */ new Set() };
|
|
80583
|
+
people.set(event.u, person);
|
|
80584
|
+
}
|
|
80585
|
+
addTokens(person, event);
|
|
80586
|
+
person.lastActive = Math.max(person.lastActive, event.t);
|
|
80587
|
+
person.models.add(event.n);
|
|
80588
|
+
const at = bucketIndex(o.starts, event.t);
|
|
80589
|
+
person.spark[at] = (person.spark[at] ?? 0) + (event.i ?? 0) + (event.o ?? 0);
|
|
80590
|
+
const bucket = timeline[at];
|
|
80591
|
+
if (bucket !== void 0) {
|
|
80592
|
+
bucket.input += event.i ?? 0;
|
|
80593
|
+
bucket.output += event.o ?? 0;
|
|
80594
|
+
}
|
|
80595
|
+
const model = models.get(event.n) ?? zeroTokens();
|
|
80596
|
+
addTokens(model, event);
|
|
80597
|
+
models.set(event.n, model);
|
|
80598
|
+
}
|
|
80599
|
+
const grand = total.input + total.output;
|
|
80600
|
+
return {
|
|
80601
|
+
total,
|
|
80602
|
+
previous,
|
|
80603
|
+
estimatedShare: current.length === 0 ? 0 : estimated / current.length,
|
|
80604
|
+
people: [...people.entries()].map(([user, p]) => ({
|
|
80605
|
+
user,
|
|
80606
|
+
...o.who(user),
|
|
80607
|
+
input: p.input,
|
|
80608
|
+
output: p.output,
|
|
80609
|
+
cached: p.cached,
|
|
80610
|
+
requests: p.requests,
|
|
80611
|
+
share: grand === 0 ? 0 : (p.input + p.output) / grand,
|
|
80612
|
+
lastActive: p.lastActive,
|
|
80613
|
+
spark: p.spark,
|
|
80614
|
+
models: [...p.models].sort()
|
|
80615
|
+
})).sort((a, b) => b.input + b.output - (a.input + a.output)),
|
|
80616
|
+
models: [...models.entries()].map(([model, m]) => ({ model, ...m })).sort((a, b) => b.input + b.output - (a.input + a.output)),
|
|
80617
|
+
timeline
|
|
80618
|
+
};
|
|
80619
|
+
}
|
|
80354
80620
|
var toolLabel = (name) => name.startsWith("py__") ? name.slice(4) : name;
|
|
80355
80621
|
function bucketUnit(span) {
|
|
80356
80622
|
if (span <= 2 * DAY)
|
|
@@ -80429,7 +80695,9 @@ function count2(events) {
|
|
|
80429
80695
|
}
|
|
80430
80696
|
return { uses: events.length, skillUses, toolUses, failures, people: people.size, skillsUsed: skills.size, toolsUsed: tools.size };
|
|
80431
80697
|
}
|
|
80432
|
-
function computeDashboard(
|
|
80698
|
+
function computeDashboard(given) {
|
|
80699
|
+
const tokenEvents = given.events.filter(isTokenEvent);
|
|
80700
|
+
const input = { ...given, events: given.events.filter((event) => !isTokenEvent(event)) };
|
|
80433
80701
|
const { from, to, scope, me } = input;
|
|
80434
80702
|
const profileOf = (user) => input.profiles?.[shardSegment(user)] ?? input.profiles?.[shardSegment(user).toLowerCase()];
|
|
80435
80703
|
const who = (user) => {
|
|
@@ -80478,7 +80746,7 @@ function computeDashboard(input) {
|
|
|
80478
80746
|
const item = installed.get(inventoryKey(event));
|
|
80479
80747
|
const author = event.a ?? item?.author;
|
|
80480
80748
|
entry = {
|
|
80481
|
-
kind: event.k,
|
|
80749
|
+
kind: event.k === "skill" ? "skill" : "tool",
|
|
80482
80750
|
name: event.n,
|
|
80483
80751
|
label: event.k === "tool" ? toolLabel(event.n) : event.n,
|
|
80484
80752
|
uses: 0,
|
|
@@ -80642,6 +80910,7 @@ function computeDashboard(input) {
|
|
|
80642
80910
|
const topSkill = [...entry.skills.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
|
|
80643
80911
|
return { team, people: entry.people.size, uses: entry.uses, skillUses: entry.skillUses, ...topSkill !== void 0 ? { topSkill } : {} };
|
|
80644
80912
|
}).sort((a, b) => b.uses - a.uses);
|
|
80913
|
+
const tokens = tokenStats(tokenEvents, { from, to, previousFrom, scope, me, starts, who });
|
|
80645
80914
|
return {
|
|
80646
80915
|
scope,
|
|
80647
80916
|
me,
|
|
@@ -80673,7 +80942,8 @@ function computeDashboard(input) {
|
|
|
80673
80942
|
tools: input.inventory.filter((item) => item.kind === "tool").length,
|
|
80674
80943
|
authors: new Set(input.inventory.map((item) => item.author).filter((author) => author !== void 0)).size
|
|
80675
80944
|
},
|
|
80676
|
-
eventsInStore: allInRange.length
|
|
80945
|
+
eventsInStore: allInRange.length,
|
|
80946
|
+
tokens
|
|
80677
80947
|
};
|
|
80678
80948
|
}
|
|
80679
80949
|
function asProblemItem(item, note) {
|
|
@@ -80964,7 +81234,7 @@ var params = external_exports.object({
|
|
|
80964
81234
|
to: external_exports.string().optional().describe("End date, YYYY-MM-DD (inclusive; default today)."),
|
|
80965
81235
|
scope: external_exports.enum(["me", "team"]).optional().describe("me: only the current user's use. Default team."),
|
|
80966
81236
|
user: external_exports.string().optional().describe("events: only this user (login or display name, any case)."),
|
|
80967
|
-
kind: external_exports.enum(["skill", "tool"]).optional().describe("events: only skill uses or only
|
|
81237
|
+
kind: external_exports.enum(["skill", "tool", "tokens"]).optional().describe("events: only skill uses, only tool calls, or only token counts (one row per model request: model, inputTokens, outputTokens, cachedTokens, estimated)."),
|
|
80968
81238
|
name: external_exports.string().optional().describe("events: only skills or tools whose name contains this (any case)."),
|
|
80969
81239
|
team: external_exports.string().optional().describe("events: only people in this team or department (any case)."),
|
|
80970
81240
|
limit: external_exports.number().int().min(1).max(2e5).optional().describe("events: at most this many rows, newest first (default 20000).")
|
|
@@ -81003,6 +81273,7 @@ function renderSummary(d, storeLabel) {
|
|
|
81003
81273
|
`- Skill uses: ${String(d.totals.skillUses.value)}${pct(d.totals.skillUses.value, d.totals.skillUses.previous)}; skills in use ${String(d.totals.skillsUsed.value)} of ${String(d.inventory.skills)} installed`,
|
|
81004
81274
|
`- Tool calls: ${String(d.totals.toolUses.value)}${pct(d.totals.toolUses.value, d.totals.toolUses.previous)}; failed ${String(d.totals.failures.value)}`,
|
|
81005
81275
|
`- Active people: ${String(d.totals.people.value)}${pct(d.totals.people.value, d.totals.people.previous)}`,
|
|
81276
|
+
`- Tokens: ${(d.tokens.total.input + d.tokens.total.output).toLocaleString("en")} (${d.tokens.total.input.toLocaleString("en")} in, ${d.tokens.total.output.toLocaleString("en")} out, ${d.tokens.total.cached.toLocaleString("en")} of the input cached) over ${String(d.tokens.total.requests)} requests${pct(d.tokens.total.input + d.tokens.total.output, d.tokens.previous.input + d.tokens.previous.output)}${d.tokens.estimatedShare > 0 ? `; ${String(Math.round(d.tokens.estimatedShare * 100))}% of requests estimated` : ""}`,
|
|
81006
81277
|
`- Your contribution: ${String(d.myImpact.skills)} skills and ${String(d.myImpact.tools)} tools, used ${String(d.myImpact.uses)} times by ${String(d.myImpact.reached)} people`
|
|
81007
81278
|
];
|
|
81008
81279
|
const table = (title, header2, rows) => {
|
|
@@ -81017,6 +81288,9 @@ function renderSummary(d, storeLabel) {
|
|
|
81017
81288
|
table("People", "| Person | Team | Uses | Skills | Favourite skill |", d.people.slice(0, 20).map((p) => `| ${name(p.user, p.displayName)} | ${p.team ?? ""} | ${String(p.uses)} | ${String(p.skills)} | ${p.favourite ?? ""} |`));
|
|
81018
81289
|
table("Teams", "| Team | People | Uses | Skill uses | Top skill |", d.teams.map((t) => `| ${t.team} | ${String(t.people)} | ${String(t.uses)} | ${String(t.skillUses)} | ${t.topSkill ?? ""} |`));
|
|
81019
81290
|
}
|
|
81291
|
+
const n = (v) => v.toLocaleString("en");
|
|
81292
|
+
table("Tokens by person", "| Person | Team | Total | Input | Output | Cached | Requests | Share | Models |", d.tokens.people.slice(0, 30).map((p) => `| ${name(p.user, p.displayName)} | ${p.team ?? ""} | ${n(p.input + p.output)} | ${n(p.input)} | ${n(p.output)} | ${n(p.cached)} | ${n(p.requests)} | ${String(Math.round(p.share * 100))}% | ${p.models.join(", ")} |`));
|
|
81293
|
+
table("Tokens by model", "| Model | Total | Input | Output | Requests |", d.tokens.models.slice(0, 15).map((m) => `| ${m.model} | ${n(m.input + m.output)} | ${n(m.input)} | ${n(m.output)} | ${n(m.requests)} |`));
|
|
81020
81294
|
if (d.problems.length > 0) {
|
|
81021
81295
|
lines2.push("", "## Needs attention");
|
|
81022
81296
|
for (const problem of d.problems)
|
|
@@ -81103,7 +81377,8 @@ Note: ${data.storeProblem}` : "";
|
|
|
81103
81377
|
author: event.a ?? null,
|
|
81104
81378
|
project: event.p ?? null,
|
|
81105
81379
|
failed: event.ok === false,
|
|
81106
|
-
ms: event.d ?? null
|
|
81380
|
+
ms: event.d ?? null,
|
|
81381
|
+
...event.k === "tokens" ? { model: event.n, inputTokens: event.i ?? 0, outputTokens: event.o ?? 0, cachedTokens: event.c ?? 0, estimated: event.e === 1 } : {}
|
|
81107
81382
|
}));
|
|
81108
81383
|
if (rows.length === 0)
|
|
81109
81384
|
return { content: `No usage matched in ${new Date(range.from).toISOString().slice(0, 10)} to ${new Date(range.to).toISOString().slice(0, 10)}.${note}` };
|
|
@@ -83766,6 +84041,31 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
|
|
|
83766
84041
|
return [];
|
|
83767
84042
|
}
|
|
83768
84043
|
}
|
|
84044
|
+
let persistTimer;
|
|
84045
|
+
let persisting = Promise.resolve();
|
|
84046
|
+
function persistSoon() {
|
|
84047
|
+
if (persistTimer !== void 0)
|
|
84048
|
+
return;
|
|
84049
|
+
persistTimer = setTimeout(() => {
|
|
84050
|
+
persistTimer = void 0;
|
|
84051
|
+
persisting = persisting.then(() => persistActiveTask()).catch(() => void 0);
|
|
84052
|
+
}, 3e3);
|
|
84053
|
+
persistTimer.unref?.();
|
|
84054
|
+
}
|
|
84055
|
+
function composerDraftFile() {
|
|
84056
|
+
const id = (0, import_node_crypto17.createHash)("sha256").update((workspaceRoot ?? "").toLowerCase()).digest("hex").slice(0, 16);
|
|
84057
|
+
return import_node_path53.default.join(storageDir, "drafts", `${id}.txt`);
|
|
84058
|
+
}
|
|
84059
|
+
let draftWrites = Promise.resolve();
|
|
84060
|
+
function saveComposerDraft(text2) {
|
|
84061
|
+
const kept = text2.slice(0, 2e5);
|
|
84062
|
+
draftWrites = draftWrites.then(() => kept.length === 0 ? import_promises29.default.rm(composerDraftFile(), { force: true }) : writeFileAtomically(composerDraftFile(), kept)).catch((error51) => logger.warn("could not keep the draft", String(error51)));
|
|
84063
|
+
return draftWrites;
|
|
84064
|
+
}
|
|
84065
|
+
async function readComposerDraft() {
|
|
84066
|
+
await draftWrites;
|
|
84067
|
+
return import_promises29.default.readFile(composerDraftFile(), "utf8").catch(() => "");
|
|
84068
|
+
}
|
|
83769
84069
|
async function persistActiveTask() {
|
|
83770
84070
|
if (workspaceRoot === void 0 || conversation.isEmpty())
|
|
83771
84071
|
return;
|
|
@@ -84197,6 +84497,8 @@ ${direction}` : attachMentions(text2, mentions);
|
|
|
84197
84497
|
contextWindow: capabilities.contextWindow,
|
|
84198
84498
|
// A guessed window must not drive compaction - see `contextWindowKnown`.
|
|
84199
84499
|
contextWindowKnown: capabilities.contextWindowKnown !== false,
|
|
84500
|
+
// The provider's real token counts correct the estimate for this model (`context/budget.ts`).
|
|
84501
|
+
usageKey: `${profile.baseUrl}|${profile.model}`,
|
|
84200
84502
|
// So images a tool returns (a Confluence page's pictures) reach a model that can see them.
|
|
84201
84503
|
supportsVision: capabilities.supportsVision,
|
|
84202
84504
|
// CLAUDE.md §5 has called this configurable since Phase 0; until now it was not.
|
|
@@ -84324,8 +84626,10 @@ ${direction}` : attachMentions(text2, mentions);
|
|
|
84324
84626
|
await runAgentTurn(provider, conversation, messageText, turnRegistry, toolContext, {
|
|
84325
84627
|
onContextUpdate: (breakdown, supersededCount, compactedCount) => {
|
|
84326
84628
|
post({ type: "contextUsage", usage: { ...breakdown, supersededCount, compactedCount } });
|
|
84629
|
+
persistSoon();
|
|
84327
84630
|
},
|
|
84328
84631
|
onCompacted: (summarisedCount) => post({ type: "compacted", summarisedCount }),
|
|
84632
|
+
onUsage: (counted) => recordTokens(profile.model, counted),
|
|
84329
84633
|
onContextWindowLearned: (tokens) => {
|
|
84330
84634
|
if (profile.modelCapabilities?.contextWindow !== void 0)
|
|
84331
84635
|
return;
|
|
@@ -84393,6 +84697,7 @@ ${direction}` : attachMentions(text2, mentions);
|
|
|
84393
84697
|
},
|
|
84394
84698
|
onToolResult: (toolCall, result) => {
|
|
84395
84699
|
recordUsage(toolCall, result);
|
|
84700
|
+
persistSoon();
|
|
84396
84701
|
if (CONTROL_TOOLS.has(toolCall.name)) {
|
|
84397
84702
|
const streamed = textBeforeControlTool;
|
|
84398
84703
|
textBeforeControlTool = "";
|
|
@@ -88861,6 +89166,23 @@ ${last}` : ""}`);
|
|
|
88861
89166
|
}
|
|
88862
89167
|
void Promise.all(events.map((event) => usageLog.append(event))).then(() => scheduleUsagePush()).catch((error51) => logger.warn(`usage: could not record: ${String(error51)}`));
|
|
88863
89168
|
}
|
|
89169
|
+
function recordTokens(model, counted) {
|
|
89170
|
+
if (!usageCollecting())
|
|
89171
|
+
return;
|
|
89172
|
+
const project = cachedAttribution.project;
|
|
89173
|
+
const event = {
|
|
89174
|
+
t: Date.now(),
|
|
89175
|
+
u: cachedAttribution.author ?? "unknown",
|
|
89176
|
+
...project !== void 0 ? { p: project } : {},
|
|
89177
|
+
k: "tokens",
|
|
89178
|
+
n: model,
|
|
89179
|
+
i: Math.max(0, Math.round(counted.inputTokens)),
|
|
89180
|
+
o: Math.max(0, Math.round(counted.outputTokens)),
|
|
89181
|
+
...counted.cachedTokens !== void 0 && counted.cachedTokens > 0 ? { c: Math.round(counted.cachedTokens) } : {},
|
|
89182
|
+
...counted.estimated ? { e: 1 } : {}
|
|
89183
|
+
};
|
|
89184
|
+
void usageLog.append(event).then(() => scheduleUsagePush()).catch((error51) => logger.warn(`usage: could not record tokens: ${String(error51)}`));
|
|
89185
|
+
}
|
|
88864
89186
|
function scheduleUsagePush() {
|
|
88865
89187
|
if (usagePushTimer !== void 0)
|
|
88866
89188
|
clearTimeout(usagePushTimer);
|
|
@@ -90605,6 +90927,10 @@ ${last}` : ""}`);
|
|
|
90605
90927
|
userTurnWindingDown = false;
|
|
90606
90928
|
}
|
|
90607
90929
|
})();
|
|
90930
|
+
} else if (message5.type === "saveComposerDraft") {
|
|
90931
|
+
void saveComposerDraft(message5.text);
|
|
90932
|
+
} else if (message5.type === "requestComposerDraft") {
|
|
90933
|
+
void readComposerDraft().then((text2) => post({ type: "composerDraft", text: text2 }));
|
|
90608
90934
|
} else if (message5.type === "compactConversation") {
|
|
90609
90935
|
reportFailure("handleCompactConversation", handleCompactConversation());
|
|
90610
90936
|
} else if (message5.type === "pickContextFiles") {
|
|
@@ -92335,6 +92661,7 @@ var LspClient = class {
|
|
|
92335
92661
|
p.reject(error51);
|
|
92336
92662
|
this.pending.clear();
|
|
92337
92663
|
});
|
|
92664
|
+
this.child.stdin?.on("error", () => void 0);
|
|
92338
92665
|
this.child.on("exit", (code) => {
|
|
92339
92666
|
this.exited = true;
|
|
92340
92667
|
this.lastError ??= `exited with code ${String(code)}`;
|
|
@@ -94016,11 +94343,15 @@ what the page names, since a wiki page can be out of date and the server cannot.
|
|
|
94016
94343
|
then saves the ones that answered: it asks **every time**, the prompt shows the addresses before and after
|
|
94017
94344
|
with each changed one tried live, and it is never available to a schedule or with read-only access.
|
|
94018
94345
|
Addresses must be paths on your site (\`/v1/job/{job}\`) - never another host - and the ones that send
|
|
94019
|
-
(events, JIL) are never tried. Placeholders: {job}, {pattern}, {filter:name} (\`name==PAY_*\`), {runNum},
|
|
94346
|
+
(events, JIL) are never tried. Placeholders: {job}, {pattern}, {filter:name} (\`name==PAY_LOAD\` for one job, \`name=@PAY_*\` for a pattern - \`=@\` is how AutoSys matches a wildcard), {runNum},
|
|
94020
94347
|
{type}, {machine}, {calendar}. Even without any of this, a **pattern** works on a server with no pattern
|
|
94021
94348
|
status address: the jobs are listed and each one's status read in turn.
|
|
94022
94349
|
|
|
94023
|
-
**Share
|
|
94350
|
+
**Share all of AutoSys**: Settings \u2192 Export, tick only **AutoSys** - the site, addresses, gateway (token address, client
|
|
94351
|
+
id, headers), test job and read-only setting, without your user name or any password or secret; importing it with only
|
|
94352
|
+
**AutoSys** ticked replaces the importer's AutoSys settings and nothing else, keeping their own user name.
|
|
94353
|
+
|
|
94354
|
+
**Share only the addresses**: Settings \u2192 Export, tick only **AutoSys addresses**; colleagues import the
|
|
94024
94355
|
file with that section ticked. It carries config:autosys (paths) alone, so their own site, sign-in and
|
|
94025
94356
|
other DevOps settings are not touched. The assistant can write the same file (\`light_code_export_config\`
|
|
94026
94357
|
with the section \`autosysAddresses\`), for example next to an onboarding page.
|
|
@@ -94567,13 +94898,25 @@ data is empty, not 0. Needs Fire Code's helper (Fire Code, or VS Code with Fire
|
|
|
94567
94898
|
"most contributions",
|
|
94568
94899
|
"usage_stats",
|
|
94569
94900
|
"custom metrics",
|
|
94570
|
-
"usage data"
|
|
94901
|
+
"usage data",
|
|
94902
|
+
"tokens burned",
|
|
94903
|
+
"token usage",
|
|
94904
|
+
"tokens by person",
|
|
94905
|
+
"tokens per user",
|
|
94906
|
+
"token spend",
|
|
94907
|
+
"who uses the most tokens"
|
|
94571
94908
|
],
|
|
94572
94909
|
body: `
|
|
94573
94910
|
**Settings \u2192 Usage** shows which skills and tools are used, by whom, who writes them, and what needs
|
|
94574
94911
|
attention - for **Me** or the whole **Team**, over the last 24 hours, 7 days, 30 days, 90 days, a year,
|
|
94575
94912
|
or a **custom** date range. Every figure is compared with the previous period of the same length.
|
|
94576
94913
|
|
|
94914
|
+
**Tokens burned**: every model request's tokens - input (cached included), output, and how much of the input the
|
|
94915
|
+
provider served from its cache - by person (with each person's share of the team's tokens, a trend line and the
|
|
94916
|
+
models they used) and by model. The counts are the providers' own; a request whose provider gave no count is
|
|
94917
|
+
estimated, and the section says what share was. Counts and the model only, never the prompt or the reply. The
|
|
94918
|
+
\`usage_stats\` tool's \`events\` with kind \`tokens\` gives one row per request for your own sums.
|
|
94919
|
+
|
|
94577
94920
|
**Collection is automatic** wherever the team already shares a store: an **OpenSearch** connection
|
|
94578
94921
|
first, then **any other vector store** (Qdrant, Chroma - from Settings \u2192 Search, in a collection named
|
|
94579
94922
|
\`light-code-usage\`), then a **team S3 bucket** (one a skills or tools folder syncs or publishes to,
|
|
@@ -94815,7 +95158,7 @@ one with an \`ac:image\` element naming the attachment.
|
|
|
94815
95158
|
body: `
|
|
94816
95159
|
**Export once, import on each machine.** Settings \u2192 Providers \u2192 Share settings with your team \u2192
|
|
94817
95160
|
**Export** writes a JSON file of the sections you tick \u2014 providers, MCP servers, search, skills,
|
|
94818
|
-
Python, buckets, Confluence and more. The assistant can write the same file with
|
|
95161
|
+
Python, buckets, DevOps (Confluence, Jira, Bitbucket, Jenkins), AutoSys on its own, and more. The assistant can write the same file with
|
|
94819
95162
|
\`light_code_export_config\` for a guide or a page.
|
|
94820
95163
|
|
|
94821
95164
|
**Never in the file**: any secret (API keys, passwords, tokens), approvals, other per-project settings,
|
|
@@ -95060,7 +95403,14 @@ edits made outside the agent (in VS Code, say) are saved with \`hub_sync\` "push
|
|
|
95060
95403
|
"copy from the grid",
|
|
95061
95404
|
"copy cell",
|
|
95062
95405
|
"copy the grid",
|
|
95063
|
-
"copy rows"
|
|
95406
|
+
"copy rows",
|
|
95407
|
+
"filter the grid",
|
|
95408
|
+
"column filter",
|
|
95409
|
+
"filter by value",
|
|
95410
|
+
"column chooser",
|
|
95411
|
+
"hide columns",
|
|
95412
|
+
"greater than",
|
|
95413
|
+
"between"
|
|
95064
95414
|
],
|
|
95065
95415
|
body: `
|
|
95066
95416
|
**Fire Code only.** Settings \u2192 Monitoring switches it on; a Monitoring button then appears at the top of the
|
|
@@ -95184,6 +95534,14 @@ monitor as it was - and the file's commits, with who, when and the commit messag
|
|
|
95184
95534
|
index, so every member sees the same list however long their Fire Code was closed. Cleaning up history keeps them;
|
|
95185
95535
|
deleting the monitor removes your own record of it. The grid window's buttons are icons - hover one to see what it does.
|
|
95186
95536
|
|
|
95537
|
+
**Filtering the grid**: every column has a filter box under its name - text to find, or a condition: \`>50\`, \`>=50\`,
|
|
95538
|
+
\`<50\`, \`10..50\` (between), \`=x\`, \`!=x\`, \`!text\` (does not contain), \`"exact"\`, \`=\` (empty), \`!=\` (not empty);
|
|
95539
|
+
\`a, b\` for either and \`>10 & <50\` for both. A time column compares times. The funnel beside a column's name lists its
|
|
95540
|
+
values with how many rows have each - search them, tick the ones to show, **Only these** for what the search found.
|
|
95541
|
+
**Columns** in the toolbar chooses the columns shown, remembered for that monitor. Only the rows in view are drawn, so
|
|
95542
|
+
a grid of 100,000 rows filters, sorts and scrolls quickly; the count says how many rows the filters leave, with
|
|
95543
|
+
**Clear filters**.
|
|
95544
|
+
|
|
95187
95545
|
**Copying from the grid**: click a cell to select it, Shift+click another for the block between, Ctrl+C to copy;
|
|
95188
95546
|
right-click a cell for Copy cell / row / column / whole grid; the grid window's copy button takes every row the filters
|
|
95189
95547
|
show, with headers. It pastes into Excel as cells and into Word or Outlook as a table, in the text the grid shows.
|
|
@@ -95871,9 +96229,13 @@ called at all.
|
|
|
95871
96229
|
],
|
|
95872
96230
|
body: `
|
|
95873
96231
|
The token bar under the composer shows where the window is going \u2014 system prompt, tool
|
|
95874
|
-
definitions, history, results \u2014 plus the cache hit rate.
|
|
95875
|
-
|
|
95876
|
-
|
|
96232
|
+
definitions, history, results \u2014 plus the cache hit rate. Before a reply the numbers are **estimates**: a real tokeniser would be a large download and
|
|
96233
|
+
would still be wrong for a gateway that rewrites the prompt. **After each reply the total is the
|
|
96234
|
+
provider's own count** (OpenAI-compatible gateways and vLLM are asked for it; Anthropic and Gemini
|
|
96235
|
+
send it), and that count corrects the estimate for the same model from then on - so the bar, and
|
|
96236
|
+
the point where compaction starts, follow what the model really holds. Code, JSON, paths and logs
|
|
96237
|
+
take more tokens per character than prose, which is why an estimate alone read 175k while the
|
|
96238
|
+
gateway already counted over 262k. A refusal for length that states the prompt's size corrects it too.
|
|
95877
96239
|
|
|
95878
96240
|
**Results dominate**, not the prompt. So an oversized tool result is capped, the full output is
|
|
95879
96241
|
written to disk, and a handle is returned that the model can re-read with an offset. Nothing is
|
|
@@ -96262,9 +96624,26 @@ walkthrough, whose steps link straight into the tab each one is about. On the No
|
|
|
96262
96624
|
"grayed out",
|
|
96263
96625
|
"disabled",
|
|
96264
96626
|
"cannot click",
|
|
96265
|
-
"not clickable"
|
|
96627
|
+
"not clickable",
|
|
96628
|
+
"python.exe crashed",
|
|
96629
|
+
"python crashed",
|
|
96630
|
+
"stopped working",
|
|
96631
|
+
"agent crashed",
|
|
96632
|
+
"conversation lost",
|
|
96633
|
+
"draft lost",
|
|
96634
|
+
"typed message gone",
|
|
96635
|
+
"host.log"
|
|
96266
96636
|
],
|
|
96267
96637
|
body: `
|
|
96638
|
+
**The agent crashed, or python.exe "stopped working".** A Python tool's worker that crashes is restarted on the
|
|
96639
|
+
next call, and the call that hit it says why - the Windows crash code in words (an access violation in a native
|
|
96640
|
+
library, a stack overflow, a missing DLL) and Python's own last lines, which it now prints on a native crash. It no
|
|
96641
|
+
longer takes the agent down with it (it used to, through the worker's closed input). Fire Code also stops Windows
|
|
96642
|
+
showing its "stopped working" box for the programs it starts, which kept a crashed worker alive until dismissed. The
|
|
96643
|
+
conversation is saved as the turn goes - after your message and after each tool result - and what you were typing is
|
|
96644
|
+
kept by the agent as well, so a restart loses neither. Each chat's log is \`host.log\` in its data folder, with the
|
|
96645
|
+
run before as \`host.previous.log\`: an error the agent survived is written there as "kept running".
|
|
96646
|
+
|
|
96268
96647
|
**A button is greyed out.** Hover over it: every control that can be disabled says why in its
|
|
96269
96648
|
tooltip - nothing changed since the last save, a field still empty, a reply still running, a
|
|
96270
96649
|
feature switched off elsewhere - and usually what to do about it.
|