@chosengeneration/light-code 0.33.0 → 0.35.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/server.js CHANGED
@@ -24131,7 +24131,7 @@ var require_cross_spawn = __commonJS({
24131
24131
  var cp = __require("child_process");
24132
24132
  var parse3 = require_parse2();
24133
24133
  var enoent = require_enoent();
24134
- function spawn6(command, args, options) {
24134
+ function spawn7(command, args, options) {
24135
24135
  const parsed = parse3(command, args, options);
24136
24136
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
24137
24137
  enoent.hookChildProcess(spawned, parsed);
@@ -24143,8 +24143,8 @@ var require_cross_spawn = __commonJS({
24143
24143
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
24144
24144
  return result;
24145
24145
  }
24146
- module.exports = spawn6;
24147
- module.exports.spawn = spawn6;
24146
+ module.exports = spawn7;
24147
+ module.exports.spawn = spawn7;
24148
24148
  module.exports.sync = spawnSync;
24149
24149
  module.exports._parse = parse3;
24150
24150
  module.exports._enoent = enoent;
@@ -39191,9 +39191,28 @@ var apigeeMtlsSettingsSchema = external_exports.object({
39191
39191
  refreshSkewSeconds: external_exports.number().int().nonnegative().optional(),
39192
39192
  extraHeaders: external_exports.record(external_exports.string(), external_exports.string()).optional()
39193
39193
  });
39194
+ var tokenCommandSchema = external_exports.object({
39195
+ command: external_exports.array(external_exports.string().min(1)).min(1, "Give the program and its arguments").describe("argv. Spawned directly \u2014 nothing is parsed by a shell."),
39196
+ cwd: external_exports.string().optional(),
39197
+ tokenPath: external_exports.string().optional(),
39198
+ expiresInPath: external_exports.string().optional(),
39199
+ fallbackExpirySeconds: external_exports.number().int().positive().optional(),
39200
+ refreshSkewSeconds: external_exports.number().int().nonnegative().optional(),
39201
+ timeoutSeconds: external_exports.number().int().positive().optional(),
39202
+ headerName: external_exports.string().optional(),
39203
+ headerPrefix: external_exports.string().optional(),
39204
+ env: external_exports.record(external_exports.string(), external_exports.string()).optional()
39205
+ });
39194
39206
  var authSchema = external_exports.discriminatedUnion("type", [
39195
39207
  external_exports.object({ type: external_exports.literal("none") }),
39208
+ /**
39209
+ * `apiKeyRef` may name the environment as well as the secret store.
39210
+ *
39211
+ * `env:API_TOKEN` reads it from the process environment — see `auth/secretRef.ts`. Anything
39212
+ * else is a key into `SecretStore`, which is what the UI writes.
39213
+ */
39196
39214
  external_exports.object({ type: external_exports.literal("apiKey"), apiKeyRef: external_exports.string().min(1) }),
39215
+ external_exports.object({ type: external_exports.literal("tokenCommand"), tokenCommand: tokenCommandSchema }),
39197
39216
  external_exports.object({
39198
39217
  type: external_exports.literal("apigeeMtls"),
39199
39218
  certs: certConfigSchema,
@@ -39256,6 +39275,17 @@ var pythonConfigSchema = external_exports.object({
39256
39275
  * user storage is the fallback.
39257
39276
  */
39258
39277
  venvPath: external_exports.string(),
39278
+ /**
39279
+ * A Python interpreter to use directly, with no virtualenv and no uv.
39280
+ *
39281
+ * For an environment somebody else already built — a Streamlit app, a container, a conda env
39282
+ * — where the interpreter has the internal libraries the tools need and installing a package
39283
+ * manager to reach it makes no sense. Left unset, uv is preferred and this is the fallback:
39284
+ * `python3`, then `python`, from PATH.
39285
+ *
39286
+ * User-scope only for the same reason as `uvPath`: it names a program that gets run.
39287
+ */
39288
+ interpreterPath: external_exports.string(),
39259
39289
  /**
39260
39290
  * Package index for tool dependencies. §3 treats `uv` resolving PyPI as *our* egress
39261
39291
  * rather than the user's, so pointing it at an internal mirror is the expected
@@ -40780,6 +40810,30 @@ function resolveActiveProfile(config2) {
40780
40810
  return found;
40781
40811
  }
40782
40812
 
40813
+ // ../../packages/core/dist/providers/auth/secretRef.js
40814
+ var ENV_REF_PREFIX = "env:";
40815
+ function describeSecretRef(ref) {
40816
+ if (!ref.startsWith(ENV_REF_PREFIX))
40817
+ return { kind: "store" };
40818
+ const envVar = ref.slice(ENV_REF_PREFIX.length).trim();
40819
+ return envVar.length === 0 ? { kind: "store" } : { kind: "env", envVar };
40820
+ }
40821
+ async function resolveSecretRef(ref, options) {
40822
+ const described = describeSecretRef(ref);
40823
+ if (described.kind === "env") {
40824
+ const value = (options.env ?? process.env)[described.envVar];
40825
+ return value === void 0 || value.trim().length === 0 ? void 0 : value;
40826
+ }
40827
+ return options.secrets.get(ref);
40828
+ }
40829
+ function describeMissingSecret(ref, what = "API key") {
40830
+ const described = describeSecretRef(ref);
40831
+ if (described.kind === "env") {
40832
+ return `The ${what} is configured to come from the environment variable ${String(described.envVar)}, which is not set in this process. Set it before starting Light Code \u2014 a variable exported after the process began is not visible to it. If a launcher sets it, check that it is exported rather than assigned only in its own shell.`;
40833
+ }
40834
+ return `${what.charAt(0).toUpperCase()}${what.slice(1)} missing for this provider profile. Open Settings (the icon in the Light Code header), edit the active profile, and enter it again.`;
40835
+ }
40836
+
40783
40837
  // ../../packages/core/dist/providers/auth/apiKey.js
40784
40838
  function defaultApiKeyHeader(wireFormat) {
40785
40839
  switch (wireFormat) {
@@ -40801,9 +40855,9 @@ var ApiKeyAuthStrategy = class {
40801
40855
  this.header = header;
40802
40856
  }
40803
40857
  async resolveHeaders() {
40804
- const key = await this.secrets.get(this.apiKeyRef);
40858
+ const key = await resolveSecretRef(this.apiKeyRef, { secrets: this.secrets });
40805
40859
  if (key === void 0) {
40806
- throw new Error("API key missing for this provider profile. Open Settings (the icon in the Light Code header), edit the active profile, and enter the API key again.");
40860
+ throw new Error(describeMissingSecret(this.apiKeyRef));
40807
40861
  }
40808
40862
  return { [this.header.name]: `${this.header.prefix}${key}` };
40809
40863
  }
@@ -40814,6 +40868,141 @@ var NoAuthStrategy = class {
40814
40868
  }
40815
40869
  };
40816
40870
 
40871
+ // ../../packages/core/dist/providers/auth/tokenCommand.js
40872
+ import { spawn } from "node:child_process";
40873
+ function readPath(source, dotted) {
40874
+ let current = source;
40875
+ for (const part of dotted.split(".")) {
40876
+ if (current === null || typeof current !== "object")
40877
+ return void 0;
40878
+ current = current[part];
40879
+ }
40880
+ return current;
40881
+ }
40882
+ var TokenCommandAuthStrategy = class {
40883
+ settings;
40884
+ held;
40885
+ inFlight;
40886
+ constructor(settings) {
40887
+ this.settings = settings;
40888
+ if (settings.command.length === 0) {
40889
+ throw new Error("The token command is empty. Give the program and its arguments.");
40890
+ }
40891
+ }
40892
+ async resolveHeaders() {
40893
+ const token = await this.token();
40894
+ const name = this.settings.headerName ?? "Authorization";
40895
+ const prefix = this.settings.headerPrefix ?? "Bearer ";
40896
+ return { [name]: `${prefix}${token.value}` };
40897
+ }
40898
+ /**
40899
+ * Checked before a stream opens, with margin for a long generation.
40900
+ *
40901
+ * The same reasoning as the Apigee strategy: a token that expires halfway through a response
40902
+ * cannot be recovered from without discarding what has already been written.
40903
+ */
40904
+ async ensureTokenForStream(marginSeconds = 120) {
40905
+ const deadline = Date.now() + marginSeconds * 1e3;
40906
+ if (this.held === void 0 || this.held.expiresAt <= deadline) {
40907
+ this.held = void 0;
40908
+ await this.token();
40909
+ }
40910
+ }
40911
+ /** Drops the held token, so the next request fetches a new one. For a 401 retry. */
40912
+ invalidate() {
40913
+ this.held = void 0;
40914
+ }
40915
+ async token() {
40916
+ const skew = (this.settings.refreshSkewSeconds ?? 60) * 1e3;
40917
+ if (this.held !== void 0 && this.held.expiresAt - skew > Date.now())
40918
+ return this.held;
40919
+ this.inFlight ??= this.fetch().then((token) => {
40920
+ this.held = token;
40921
+ return token;
40922
+ }).finally(() => {
40923
+ this.inFlight = void 0;
40924
+ });
40925
+ return this.inFlight;
40926
+ }
40927
+ async fetch() {
40928
+ const [program, ...args] = this.settings.command;
40929
+ const timeout = (this.settings.timeoutSeconds ?? 30) * 1e3;
40930
+ const output = await new Promise((resolve, reject2) => {
40931
+ const child = spawn(program, args, {
40932
+ // Never `shell: true`. See the note at the top of this file.
40933
+ shell: false,
40934
+ ...this.settings.cwd === void 0 ? {} : { cwd: this.settings.cwd },
40935
+ env: { ...process.env, ...this.settings.env ?? {} }
40936
+ });
40937
+ let stdout = "";
40938
+ let stderr = "";
40939
+ let settled = false;
40940
+ const timer = setTimeout(() => {
40941
+ if (settled)
40942
+ return;
40943
+ settled = true;
40944
+ child.kill();
40945
+ reject2(new Error(`The token command did not finish within ${String(timeout / 1e3)}s: ${program}. Raise its timeout, or check whether it is waiting for input \u2014 a command that prompts will never return here, because nothing is attached to answer.`));
40946
+ }, timeout);
40947
+ child.stdout.on("data", (chunk) => stdout += chunk.toString());
40948
+ child.stderr.on("data", (chunk) => stderr += chunk.toString());
40949
+ child.on("error", (error51) => {
40950
+ if (settled)
40951
+ return;
40952
+ settled = true;
40953
+ clearTimeout(timer);
40954
+ reject2(new Error(error51.code === "ENOENT" ? `The token command's program was not found: ${program}. Give an absolute path, or make sure it is on the PATH of the process that started Light Code.` : `The token command could not be started: ${error51.message}`));
40955
+ });
40956
+ child.on("close", (code) => {
40957
+ if (settled)
40958
+ return;
40959
+ settled = true;
40960
+ clearTimeout(timer);
40961
+ if (code === 0) {
40962
+ resolve(stdout);
40963
+ return;
40964
+ }
40965
+ const detail = stderr.trim().length > 0 ? stderr.trim() : stdout.trim();
40966
+ reject2(new Error(`The token command exited with code ${String(code ?? -1)}.` + (detail.length > 0 ? `
40967
+ ${detail.slice(0, 2e3)}` : " It printed nothing.")));
40968
+ });
40969
+ });
40970
+ return this.parse(output);
40971
+ }
40972
+ parse(stdout) {
40973
+ const fallback = (this.settings.fallbackExpirySeconds ?? 3600) * 1e3;
40974
+ if (this.settings.tokenPath === void 0) {
40975
+ const value2 = stdout.trim();
40976
+ if (value2.length === 0) {
40977
+ throw new Error("The token command succeeded but printed nothing. It must write the token to stdout, or name `tokenPath` if it prints JSON.");
40978
+ }
40979
+ if (/\s/.test(value2)) {
40980
+ throw new Error("The token command printed more than one line, so it is not clear which part is the token. Print only the token, or have it print JSON and set `tokenPath`.");
40981
+ }
40982
+ return { value: value2, expiresAt: Date.now() + fallback };
40983
+ }
40984
+ let parsed;
40985
+ try {
40986
+ parsed = JSON.parse(stdout);
40987
+ } catch {
40988
+ throw new Error(`\`tokenPath\` is set, so the token command's output is read as JSON \u2014 and it did not parse. It printed: ${stdout.trim().slice(0, 200)}`);
40989
+ }
40990
+ const value = readPath(parsed, this.settings.tokenPath);
40991
+ if (typeof value !== "string" || value.trim().length === 0) {
40992
+ throw new Error(`The token command's JSON has nothing usable at "${this.settings.tokenPath}". It printed: ${stdout.trim().slice(0, 200)}`);
40993
+ }
40994
+ let lifetime = fallback;
40995
+ if (this.settings.expiresInPath !== void 0) {
40996
+ const reported = readPath(parsed, this.settings.expiresInPath);
40997
+ const seconds = typeof reported === "string" ? Number(reported) : reported;
40998
+ if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0) {
40999
+ lifetime = seconds * 1e3;
41000
+ }
41001
+ }
41002
+ return { value: value.trim(), expiresAt: Date.now() + lifetime };
41003
+ }
41004
+ };
41005
+
40817
41006
  // ../../packages/core/dist/providers/auth/apigeeMtls.js
40818
41007
  var DEFAULTS = {
40819
41008
  grantType: "client_credentials",
@@ -40832,7 +41021,7 @@ function defaultTokenUrl(baseUrl) {
40832
41021
  return "";
40833
41022
  }
40834
41023
  }
40835
- function readPath(source, dottedPath) {
41024
+ function readPath2(source, dottedPath) {
40836
41025
  return dottedPath.split(".").reduce((current, segment) => {
40837
41026
  if (typeof current !== "object" || current === null)
40838
41027
  return void 0;
@@ -40951,11 +41140,11 @@ var ApigeeMtlsAuthStrategy = class {
40951
41140
  throw new ApigeeAuthError(`The token endpoint at ${tokenUrl} did not return JSON.`);
40952
41141
  }
40953
41142
  const tokenPath = this.settings.tokenPath ?? DEFAULTS.tokenPath;
40954
- const value = readPath(payload, tokenPath);
41143
+ const value = readPath2(payload, tokenPath);
40955
41144
  if (typeof value !== "string" || value.length === 0) {
40956
41145
  throw new ApigeeAuthError(`The token endpoint response has no token at "${tokenPath}". Set tokenPath if your gateway nests it elsewhere.`);
40957
41146
  }
40958
- const rawExpiry = readPath(payload, this.settings.expiresInPath ?? DEFAULTS.expiresInPath);
41147
+ const rawExpiry = readPath2(payload, this.settings.expiresInPath ?? DEFAULTS.expiresInPath);
40959
41148
  const expiresInSeconds = typeof rawExpiry === "number" && rawExpiry > 0 ? rawExpiry : typeof rawExpiry === "string" && Number.parseInt(rawExpiry, 10) > 0 ? Number.parseInt(rawExpiry, 10) : this.settings.fallbackExpirySeconds ?? DEFAULTS.fallbackExpirySeconds;
40960
41149
  const skew = this.settings.refreshSkewSeconds ?? DEFAULTS.refreshSkewSeconds;
40961
41150
  const issuedAt = this.now();
@@ -41216,6 +41405,14 @@ function createBaseAuthStrategy(auth2, context) {
41216
41405
  prefix: context.apiKeyHeaderPrefix ?? derived.prefix
41217
41406
  });
41218
41407
  }
41408
+ case "tokenCommand": {
41409
+ const derived = defaultApiKeyHeader(context.wireFormat ?? "openai");
41410
+ return new TokenCommandAuthStrategy({
41411
+ ...auth2.tokenCommand,
41412
+ headerName: auth2.tokenCommand.headerName ?? context.apiKeyHeaderName ?? derived.name,
41413
+ headerPrefix: auth2.tokenCommand.headerPrefix ?? context.apiKeyHeaderPrefix ?? derived.prefix
41414
+ });
41415
+ }
41219
41416
  case "none":
41220
41417
  return new NoAuthStrategy();
41221
41418
  case "apigeeMtls": {
@@ -41407,7 +41604,11 @@ async function testConnection(profile, context, http, signal) {
41407
41604
  } else {
41408
41605
  try {
41409
41606
  await auth2.resolveHeaders();
41410
- steps.push({ step: "token", status: "ok", detail: "Credential resolved from secure storage." });
41607
+ steps.push({
41608
+ step: "token",
41609
+ status: "ok",
41610
+ detail: profile.auth.type === "tokenCommand" ? "The token command ran and returned a token." : profile.auth.type === "apiKey" && profile.auth.apiKeyRef.startsWith("env:") ? `Key read from ${profile.auth.apiKeyRef.slice("env:".length)}.` : "Credential resolved from secure storage."
41611
+ });
41411
41612
  } catch (error51) {
41412
41613
  steps.push({ step: "token", status: "failed", detail: messageOf(error51) });
41413
41614
  steps.push({ step: "models", status: "skipped", detail: "Not attempted \u2014 no credential." });
@@ -42639,8 +42840,9 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
42639
42840
  if (options.canWriteSkills === true) {
42640
42841
  lines.push("", "Recording what you learn:", "- When the user explains something durable about their environment \u2014 an internal", " library and how to use it, a house convention, the shape of an in-house API, a", " gotcha specific to this codebase \u2014 offer to record it with write_skill. Ask first;", " do not write one unprompted.", '- "Durable" means it would be true again next week and useful to a future', " conversation. A one-off instruction for the current task is not a skill.", options.skillsSearchable === true ? "- Before writing a new skill, search for one with search_docs: if a note already covers the subject, read it and update that instead of creating a near-duplicate." : "- Before writing a new skill, check the list above: if one already covers the subject, read it and update that instead of creating a near-duplicate.", "- When you learn something *corrects* an existing skill, say so and offer to update", " it. A stale skill is worse than a missing one, because it is trusted.", "- Write for a reader who has none of this conversation: name the package, the import", ' path, the function, and show a short example. Avoid "as discussed" and "the usual".', options.skillsSearchable === true ? "- The description line is what search matches on, so make it say what subject the skill covers in the words someone would search for \u2014 it is a trigger, not a summary." : "- The description line is the only part always in context, so make it say what subject the skill covers \u2014 it is a trigger for reading, not a summary.");
42641
42842
  }
42843
+ lines.push("", "Charts:", "- **Draw one whenever numbers are easier seen than read** \u2014 a count per folder or per day, a", " value trending over time, a breakdown of a total. Use show_chart; do not print a table of", " figures where a chart would answer the question faster.", "- **Always fill in `detail`** when the numbers count things that can be named \u2014 the subjects,", ' the files, the ids. A bar reading 14 is only useful if "which fourteen?" has an answer, and', " the detail is what lets the user open the bar instead of asking you to search again.", "- Say in `note` where the numbers came from and what they exclude. A chart is believed", " without being checked, so its limits have to travel with it.", "- Series must have exactly one value per category. A mismatch is refused rather than padded,", " because a chart drawn from misaligned data looks correct and is not.", "- After drawing, describe what it shows. Do not recite the numbers again \u2014 they are on screen.", "- **A Python tool can produce the data.** Have it return JSON shaped", ' `{"categories": [...], "series": [{"name": ..., "values": [...], "detail": [[...], ...]}]}`', " and pass that straight to show_chart. That is the intended way to chart anything you have", " analysed in Python \u2014 the tool does the arithmetic, show_chart draws it, and the numbers are", " never retyped by you in between.");
42642
42844
  if (options.mailIndexed === true) {
42643
- lines.push("", "Email:", "- **Always answer questions about email from the index, using search_mail and", " mail_patterns.** That is what it is for. It is fast, it answers questions about time", " and recurrence that a live search cannot, and it does not disturb the running Outlook.", '- **Only search Outlook itself when the user asks you to.** "Check Outlook", "look at my', ' actual mailbox", "is it there now" and anything similar are the instruction to use', " outlook_search. Do not reach for it on your own initiative.", "- If the index has nothing, say so plainly and say when it was last synced. Do not", " quietly fall back to scanning Outlook - a slow live scan that nobody asked for reads", " as the assistant having hung.", "- One exception worth naming: if the user is asking about something that arrived in the", " last few minutes, the index may not have it yet. Say that, and offer to check Outlook", " rather than doing it unasked.", "- **The index holds plain text.** Colours, highlighting and images are not in it. When", " those could carry meaning \u2014 a red line marking a failure, a highlighted cell \u2014 use", " outlook_read_email on the id, which reads the live message and reports the colours.", " Never conclude a message looks fine from indexed text alone.", "- mail_coverage says which folders are indexed and how far back. Check it before saying", " something is not in the mail: an empty search over an unindexed folder looks exactly", " like an empty search over an indexed one.");
42845
+ lines.push("", "Email:", "- **Always answer questions about email from the index, using search_mail and", " mail_patterns.** That is what it is for. It is fast, it answers questions about time", " and recurrence that a live search cannot, and it does not disturb the running Outlook.", '- **Only search Outlook itself when the user asks you to.** "Check Outlook", "look at my', ' actual mailbox", "is it there now" and anything similar are the instruction to use', " outlook_search. Do not reach for it on your own initiative.", "- If the index has nothing, say so plainly and say when it was last synced. Do not", " quietly fall back to scanning Outlook - a slow live scan that nobody asked for reads", " as the assistant having hung.", "- One exception worth naming: if the user is asking about something that arrived in the", " last few minutes, the index may not have it yet. Say that, and offer to check Outlook", " rather than doing it unasked.", "- **The index holds plain text.** Colours, highlighting and images are not in it. When", " those could carry meaning \u2014 a red line marking a failure, a highlighted cell \u2014 use", " outlook_read_email on the id, which reads the live message and reports the colours.", " Never conclude a message looks fine from indexed text alone.", "- mail_coverage says which folders are indexed and how far back. Check it before saying", " something is not in the mail: an empty search over an unindexed folder looks exactly", " like an empty search over an indexed one.", "- **Use mail_stats for any question with a number in the answer** \u2014 how many alerts per", " folder, per day, per hour, which senders, whether a figure inside the alerts is climbing.", " It counts everything the filters matched. Never count search results by eye: search", " returns a page, so counting what you were shown reports a sample as if it were the total.", "- mail_stats already returns categories, values and detail in the shape show_chart wants.", " Pass it through rather than retyping the numbers, and keep the detail.");
42644
42846
  }
42645
42847
  if (options.expertAvailable === true) {
42646
42848
  lines.push("", "Expert consultation:", "- A stronger model, Claude, is available through the ask_expert tool. You CAN talk to", " it. Never tell the user you have no way to reach another model \u2014 you do.", '- **If the user asks you to consult it, do so.** "Ask Claude", "check with the', ' expert", "what does Claude think" and anything similar are direct instructions.', " It is their money and their decision; do not talk them out of it or decide the", " question is too simple to be worth asking.", "- Otherwise, judge it yourself. It costs real money per call, so on your own", " initiative use it for: planning a change spanning several files, diagnosing a bug", " you have already failed to fix once, choosing between designs with long-lived", " consequences, or reviewing something subtle before committing to it.", "- On your own initiative, do not use it for anything you could answer by reading a", " file, for routine edits, or for restating something already established here.", "- If you decide against consulting it, say that you chose not to and why. Do not say", " you are unable to.", "- The expert can read and search this workspace but cannot edit or run anything. It", " cannot see this conversation, so put the context it needs in your question.", "- You remain responsible for the work. Treat its answer as advice from a colleague:", " verify it against the actual code, and say so if you disagree.");
@@ -42687,7 +42889,7 @@ function fallbackLocations(name) {
42687
42889
  if (path8.isAbsolute(name))
42688
42890
  return [];
42689
42891
  const candidates = [];
42690
- const push = (dir) => {
42892
+ const push2 = (dir) => {
42691
42893
  if (dir === void 0 || dir.length === 0)
42692
42894
  return;
42693
42895
  if (process.platform === "win32")
@@ -42695,12 +42897,12 @@ function fallbackLocations(name) {
42695
42897
  candidates.push(path8.join(dir, name));
42696
42898
  };
42697
42899
  if (process.platform === "win32") {
42698
- push(process.env.APPDATA !== void 0 ? path8.join(process.env.APPDATA, "npm") : void 0);
42900
+ push2(process.env.APPDATA !== void 0 ? path8.join(process.env.APPDATA, "npm") : void 0);
42699
42901
  } else {
42700
- push("/usr/local/bin");
42701
- push("/opt/homebrew/bin");
42702
- push(process.env.HOME !== void 0 ? path8.join(process.env.HOME, ".npm-global", "bin") : void 0);
42703
- push(process.env.HOME !== void 0 ? path8.join(process.env.HOME, ".local", "bin") : void 0);
42902
+ push2("/usr/local/bin");
42903
+ push2("/opt/homebrew/bin");
42904
+ push2(process.env.HOME !== void 0 ? path8.join(process.env.HOME, ".npm-global", "bin") : void 0);
42905
+ push2(process.env.HOME !== void 0 ? path8.join(process.env.HOME, ".local", "bin") : void 0);
42704
42906
  }
42705
42907
  return candidates;
42706
42908
  }
@@ -45669,6 +45871,125 @@ function message(error51) {
45669
45871
  return error51 instanceof Error ? error51.message : String(error51);
45670
45872
  }
45671
45873
 
45874
+ // ../../packages/core/dist/office/mailStats.js
45875
+ var DETAIL_CAP = 50;
45876
+ function push(buckets, label, record2) {
45877
+ const existing = buckets.get(label);
45878
+ const line = `${new Date(record2.receivedAt).toLocaleString()} \u2014 ${record2.subject}`;
45879
+ if (existing === void 0) {
45880
+ buckets.set(label, { label, count: 1, detail: [line] });
45881
+ return;
45882
+ }
45883
+ existing.count += 1;
45884
+ if (existing.detail.length < DETAIL_CAP)
45885
+ existing.detail.push(line);
45886
+ }
45887
+ function dayKey(at) {
45888
+ const date5 = new Date(at);
45889
+ const month = String(date5.getMonth() + 1).padStart(2, "0");
45890
+ const day = String(date5.getDate()).padStart(2, "0");
45891
+ return `${String(date5.getFullYear())}-${month}-${day}`;
45892
+ }
45893
+ function hourKey(at) {
45894
+ return String(new Date(at).getHours()).padStart(2, "0");
45895
+ }
45896
+ function groupKey(record2, by) {
45897
+ switch (by) {
45898
+ case "folder":
45899
+ return record2.folder;
45900
+ case "day":
45901
+ return dayKey(record2.receivedAt);
45902
+ case "hour":
45903
+ return hourKey(record2.receivedAt);
45904
+ case "sender":
45905
+ return record2.sender;
45906
+ case "status":
45907
+ return record2.status ?? "none";
45908
+ }
45909
+ }
45910
+ function countBy(records, by, options = {}) {
45911
+ const buckets = /* @__PURE__ */ new Map();
45912
+ for (const record2 of records)
45913
+ push(buckets, groupKey(record2, by), record2);
45914
+ if (by === "day" && options.fillDays === true && records.length > 0) {
45915
+ const times = records.map((record2) => record2.receivedAt);
45916
+ const from = new Date(Math.min(...times));
45917
+ const to = new Date(Math.max(...times));
45918
+ from.setHours(0, 0, 0, 0);
45919
+ for (let day = from; day <= to; day = new Date(day.getTime() + 864e5)) {
45920
+ const key = dayKey(day.getTime());
45921
+ if (!buckets.has(key))
45922
+ buckets.set(key, { label: key, count: 0, detail: [] });
45923
+ }
45924
+ }
45925
+ if (by === "hour") {
45926
+ for (let hour = 0; hour < 24; hour++) {
45927
+ const key = String(hour).padStart(2, "0");
45928
+ if (!buckets.has(key))
45929
+ buckets.set(key, { label: key, count: 0, detail: [] });
45930
+ }
45931
+ }
45932
+ const rows = [...buckets.values()];
45933
+ return by === "day" || by === "hour" ? rows.sort((a, b) => a.label.localeCompare(b.label)) : rows.sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
45934
+ }
45935
+ function crossTab(records, by, splitBy) {
45936
+ const categories = countBy(records, by, { fillDays: true }).map((bucket) => bucket.label);
45937
+ const splits = [...new Set(records.map((record2) => groupKey(record2, splitBy)))].sort();
45938
+ const index = /* @__PURE__ */ new Map();
45939
+ for (const record2 of records) {
45940
+ const key = `${groupKey(record2, by)}\0${groupKey(record2, splitBy)}`;
45941
+ push(index, key, record2);
45942
+ }
45943
+ return {
45944
+ categories,
45945
+ series: splits.map((split) => ({
45946
+ name: split,
45947
+ values: categories.map((category) => index.get(`${category}\0${split}`)?.count ?? 0),
45948
+ detail: categories.map((category) => index.get(`${category}\0${split}`)?.detail ?? null)
45949
+ }))
45950
+ };
45951
+ }
45952
+ function extractNumber(record2, label) {
45953
+ const haystack = `${record2.subject}
45954
+ ${record2.preview}`;
45955
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
45956
+ const pattern = new RegExp(`${escaped}[^0-9+-]{0,12}([+-]?[0-9][0-9,]*(?:\\.[0-9]+)?)`, "i");
45957
+ const match = pattern.exec(haystack);
45958
+ if (match?.[1] === void 0)
45959
+ return void 0;
45960
+ const value = Number(match[1].replace(/,/g, ""));
45961
+ return Number.isFinite(value) ? value : void 0;
45962
+ }
45963
+ function numberOverTime(records, label, how = "last") {
45964
+ const byDay = /* @__PURE__ */ new Map();
45965
+ let matched = 0;
45966
+ for (const record2 of [...records].sort((a, b) => a.receivedAt - b.receivedAt)) {
45967
+ const value = extractNumber(record2, label);
45968
+ if (value === void 0)
45969
+ continue;
45970
+ matched += 1;
45971
+ const key = dayKey(record2.receivedAt);
45972
+ const entry = byDay.get(key) ?? { values: [], detail: [] };
45973
+ entry.values.push(value);
45974
+ if (entry.detail.length < DETAIL_CAP) {
45975
+ entry.detail.push(`${new Date(record2.receivedAt).toLocaleTimeString()} \u2014 ${String(value)} \u2014 ${record2.subject}`);
45976
+ }
45977
+ byDay.set(key, entry);
45978
+ }
45979
+ const points = [...byDay.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([day, entry]) => ({
45980
+ label: day,
45981
+ value: how === "sum" ? entry.values.reduce((sum, value) => sum + value, 0) : how === "max" ? Math.max(...entry.values) : how === "average" ? entry.values.reduce((sum, value) => sum + value, 0) / entry.values.length : entry.values[entry.values.length - 1],
45982
+ detail: entry.detail
45983
+ }));
45984
+ return { points, matched, skipped: records.length - matched };
45985
+ }
45986
+ function dailyChange(points) {
45987
+ return points.map((point, index) => ({
45988
+ label: point.label,
45989
+ change: index === 0 ? void 0 : point.value - points[index - 1].value
45990
+ }));
45991
+ }
45992
+
45672
45993
  // ../../packages/core/dist/office/mailIndex.js
45673
45994
  function parseStatusTag(subject) {
45674
45995
  if (/\[\s*alert\s*\]/i.test(subject))
@@ -46143,6 +46464,115 @@ function haystackOf(record2) {
46143
46464
  ${record2.sender}
46144
46465
  ${record2.preview}`.toLowerCase();
46145
46466
  }
46467
+ var statsSchema = external_exports.object({
46468
+ by: external_exports.enum(["folder", "day", "hour", "sender", "status"]).describe("What each bar or point represents. `day` and `hour` are in local time."),
46469
+ splitBy: external_exports.enum(["folder", "day", "hour", "sender", "status"]).optional().describe("Optional second dimension, giving one series per value \u2014 for a stacked or grouped bar."),
46470
+ withinHours: external_exports.number().min(0.1).max(24 * 365).optional().describe("Only mail received in this many hours."),
46471
+ status: external_exports.enum(["alert", "ok"]).optional().describe("Narrow to [ALERT] or [OK] messages first."),
46472
+ folder: external_exports.string().optional().describe("Narrow to a folder path first."),
46473
+ within: external_exports.array(external_exports.string().min(1)).max(500).optional().describe("Count only these message ids, from an earlier search_mail result."),
46474
+ numberLabel: external_exports.string().optional().describe('Instead of counting, read a labelled number out of each message and track it over time. Give the text that precedes it, e.g. "queue depth" or "rows". A message with no such label is left out rather than counted as zero.'),
46475
+ combine: external_exports.enum(["last", "max", "sum", "average"]).optional().describe("With numberLabel: what several messages in one day mean. Default last."),
46476
+ change: external_exports.boolean().optional().describe("With numberLabel: report the day-on-day movement rather than the value itself.")
46477
+ });
46478
+ function createMailStatsTool(options) {
46479
+ return {
46480
+ name: "mail_stats",
46481
+ group: "read",
46482
+ description: 'Counts indexed mail into buckets, ready to draw with show_chart. `by` picks the buckets (folder, day, hour, sender, status) and `splitBy` adds a second dimension for a stacked or grouped bar - "alerts per folder per day" is by=day, splitBy=folder. Every bucket comes back with the messages it counted, so pass those straight to show_chart as `detail` and the user can open a bar to see what is in it. With `numberLabel` it instead reads a labelled figure out of each message and tracks it over days - for an alert that carries a count or a percentage - and `change: true` reports the day-on-day movement instead of the value. These are exact counts over the index, not a sample and not a semantic guess.',
46483
+ parametersSchema: statsSchema,
46484
+ execute: async (params) => {
46485
+ try {
46486
+ const all = await options.loadRecords();
46487
+ if (all.length === 0) {
46488
+ return {
46489
+ content: "Nothing is indexed, so there is nothing to count. Say so rather than reporting zero of anything - zero is a finding and this is not one."
46490
+ };
46491
+ }
46492
+ let records = params.withinHours === void 0 ? [...all] : since(all, params.withinHours);
46493
+ if (params.status !== void 0)
46494
+ records = records.filter((r) => r.status === params.status);
46495
+ if (params.folder !== void 0) {
46496
+ const wanted = normaliseFolder(params.folder);
46497
+ records = records.filter((r) => normaliseFolder(r.folder).startsWith(wanted));
46498
+ }
46499
+ if (params.within !== void 0 && params.within.length > 0) {
46500
+ const keep = new Set(params.within);
46501
+ records = records.filter((r) => keep.has(r.id));
46502
+ }
46503
+ if (records.length === 0) {
46504
+ return { content: "No indexed messages match those filters, so there is nothing to count." };
46505
+ }
46506
+ if (params.numberLabel !== void 0) {
46507
+ const { points, matched, skipped } = numberOverTime(records, params.numberLabel, params.combine ?? "last");
46508
+ if (points.length === 0) {
46509
+ return {
46510
+ content: `No message contains a number labelled "${params.numberLabel}". Check the wording against an actual subject - the label is matched literally, on purpose, so that a number belonging to something else is never charted as this one.`
46511
+ };
46512
+ }
46513
+ const rows = params.change === true ? dailyChange(points).map((entry) => ({
46514
+ label: entry.label,
46515
+ value: entry.change,
46516
+ detail: null
46517
+ })) : points.map((point) => ({ label: point.label, value: point.value, detail: point.detail }));
46518
+ const usable = rows.filter((row) => row.value !== void 0);
46519
+ return {
46520
+ content: [
46521
+ `${String(matched)} message(s) carried a number labelled "${params.numberLabel}"${skipped > 0 ? `, ${String(skipped)} did not and were left out` : ""}.`,
46522
+ params.change === true ? "Day-on-day movement. The first day has no predecessor and is omitted rather than shown as no change." : `One point per day, taking the ${params.combine ?? "last"} value where a day had several.`,
46523
+ "",
46524
+ JSON.stringify({
46525
+ categories: usable.map((row) => row.label),
46526
+ series: [
46527
+ {
46528
+ name: params.change === true ? `${params.numberLabel} change` : params.numberLabel,
46529
+ values: usable.map((row) => row.value),
46530
+ ...params.change === true ? {} : { detail: usable.map((row) => row.detail) }
46531
+ }
46532
+ ]
46533
+ }),
46534
+ "",
46535
+ "Pass this to show_chart as a line chart. Keep `detail` on the series so the user can open a point."
46536
+ ].join("\n")
46537
+ };
46538
+ }
46539
+ if (params.splitBy !== void 0) {
46540
+ const table = crossTab(records, params.by, params.splitBy);
46541
+ return {
46542
+ content: [
46543
+ `${String(records.length)} message(s), by ${params.by} and ${params.splitBy}.`,
46544
+ "",
46545
+ JSON.stringify(table),
46546
+ "",
46547
+ "Pass this to show_chart as stackedBar or groupedBar. `detail` is already aligned."
46548
+ ].join("\n")
46549
+ };
46550
+ }
46551
+ const buckets = countBy(records, params.by, { fillDays: true });
46552
+ return {
46553
+ content: [
46554
+ `${String(records.length)} message(s) in ${String(buckets.length)} bucket(s), by ${params.by}.` + (params.by === "day" ? " Days with none are included as zero \u2014 a missing day and a day with nothing are different claims, and only one of them is true." : ""),
46555
+ "",
46556
+ JSON.stringify({
46557
+ categories: buckets.map((bucket) => bucket.label),
46558
+ series: [
46559
+ {
46560
+ name: params.status === void 0 ? "Messages" : params.status.toUpperCase(),
46561
+ values: buckets.map((bucket) => bucket.count),
46562
+ detail: buckets.map((bucket) => bucket.detail.length === 0 ? null : bucket.detail)
46563
+ }
46564
+ ]
46565
+ }),
46566
+ "",
46567
+ "Pass this to show_chart. Keep `detail` so the user can open a bar and see what is in it."
46568
+ ].join("\n")
46569
+ };
46570
+ } catch (error51) {
46571
+ return { content: error51 instanceof Error ? error51.message : String(error51), isError: true };
46572
+ }
46573
+ }
46574
+ };
46575
+ }
46146
46576
 
46147
46577
  // ../../packages/core/dist/office/mailStore.js
46148
46578
  import fs5 from "node:fs/promises";
@@ -53562,25 +53992,64 @@ async function discoverWorkspaceVenv(workspaceRoot) {
53562
53992
  continue;
53563
53993
  }
53564
53994
  let uvManaged = false;
53565
- let pythonVersion;
53995
+ let pythonVersion2;
53566
53996
  try {
53567
53997
  const config2 = await fs8.readFile(path14.join(candidate, "pyvenv.cfg"), "utf8");
53568
53998
  uvManaged = /^\s*uv\s*=/m.test(config2);
53569
- pythonVersion = /^\s*version(?:_info)?\s*=\s*(.+)$/m.exec(config2)?.[1]?.trim();
53999
+ pythonVersion2 = /^\s*version(?:_info)?\s*=\s*(.+)$/m.exec(config2)?.[1]?.trim();
53570
54000
  } catch {
53571
54001
  }
53572
54002
  return {
53573
54003
  path: candidate,
53574
54004
  interpreter,
53575
54005
  uvManaged,
53576
- ...pythonVersion !== void 0 ? { pythonVersion } : {}
54006
+ ...pythonVersion2 !== void 0 ? { pythonVersion: pythonVersion2 } : {}
53577
54007
  };
53578
54008
  }
53579
54009
  return void 0;
53580
54010
  }
54011
+ var BARE_PYTHON_CANDIDATES = ["python3", "python"];
54012
+ async function detectBareInterpreter(configuredPath) {
54013
+ const candidates = configuredPath !== void 0 && configuredPath.trim().length > 0 ? [configuredPath.trim()] : [...BARE_PYTHON_CANDIDATES];
54014
+ for (const candidate of candidates) {
54015
+ try {
54016
+ const version2 = await pythonVersion(candidate);
54017
+ if (version2 !== void 0)
54018
+ return { path: candidate, version: version2 };
54019
+ } catch {
54020
+ }
54021
+ }
54022
+ return void 0;
54023
+ }
54024
+ async function pythonVersion(program) {
54025
+ const { spawn: spawn7 } = await import("node:child_process");
54026
+ return new Promise((resolve) => {
54027
+ const child = spawn7(program, ["-c", 'import sys; print("%d.%d.%d" % sys.version_info[:3])'], {
54028
+ shell: false,
54029
+ env: minimalPythonEnv()
54030
+ });
54031
+ let out = "";
54032
+ child.stdout.on("data", (chunk) => out += chunk.toString());
54033
+ child.on("error", () => resolve(void 0));
54034
+ const timer = setTimeout(() => {
54035
+ child.kill();
54036
+ resolve(void 0);
54037
+ }, 1e4);
54038
+ child.on("close", (code) => {
54039
+ clearTimeout(timer);
54040
+ const version2 = out.trim();
54041
+ if (code !== 0 || !/^\d+\.\d+\.\d+$/.test(version2)) {
54042
+ resolve(void 0);
54043
+ return;
54044
+ }
54045
+ const major = Number(version2.split(".")[0]);
54046
+ resolve(major >= 3 ? version2 : void 0);
54047
+ });
54048
+ });
54049
+ }
53581
54050
 
53582
54051
  // ../../packages/core/dist/python/worker.js
53583
- import { execFile as execFile4, spawn as spawn2 } from "node:child_process";
54052
+ import { execFile as execFile4, spawn as spawn3 } from "node:child_process";
53584
54053
  import { createInterface } from "node:readline";
53585
54054
  var PythonWorkerError = class extends Error {
53586
54055
  traceback;
@@ -53604,7 +54073,7 @@ var PythonWorker = class {
53604
54073
  start() {
53605
54074
  if (this.child !== void 0 && this.child.exitCode === null && !this.child.killed)
53606
54075
  return this.child;
53607
- const child = spawn2(this.options.pythonPath, [this.options.workerScript], {
54076
+ const child = spawn3(this.options.pythonPath, [this.options.workerScript], {
53608
54077
  cwd: this.options.cwd,
53609
54078
  env: this.options.env,
53610
54079
  windowsHide: true,
@@ -54245,7 +54714,7 @@ function makeWriteTool(context, options) {
54245
54714
  if (context.installDeps === void 0) {
54246
54715
  await restore();
54247
54716
  return {
54248
- content: `This tool declares dependencies (${declared.join(", ")}) but dependency installation is not available \u2014 uv could not be found. Rewrite it using only the standard library, or ask the user to configure uv in Settings \u2192 Python.`,
54717
+ content: `This tool declares dependencies (${declared.join(", ")}) but they cannot be installed. ` + (context.installUnavailableReason ?? "uv could not be found. Ask the user to configure uv in Settings \u2192 Python.") + " Rewrite the tool using only the standard library and whatever is already importable, or ask the user to install the package themselves.",
54249
54718
  isError: true
54250
54719
  };
54251
54720
  }
@@ -54427,8 +54896,7 @@ var PythonManager = class {
54427
54896
  if (this.uv === void 0)
54428
54897
  this.uv = await detectUv(config2.uvPath);
54429
54898
  if (this.uv === void 0) {
54430
- this.ready = false;
54431
- this.detail = "uv was not found. Install it and set the path in Settings \u2192 Python, or add it to PATH.";
54899
+ await this.startWithoutUv(config2, this.options.workspaceRoot);
54432
54900
  return;
54433
54901
  }
54434
54902
  try {
@@ -54576,6 +55044,16 @@ var PythonManager = class {
54576
55044
  ...generated !== void 0 ? { generateSource: generated } : {},
54577
55045
  worker,
54578
55046
  onChanged: () => this.refresh(),
55047
+ /*
55048
+ * No installing against an interpreter we do not own.
55049
+ *
55050
+ * Absent rather than failing, so the refusal happens before a file is written and names the
55051
+ * package. The reason travels with it because the advice differs: install uv, versus
55052
+ * install the package into the environment you already have.
55053
+ */
55054
+ ...this.venvSource === "interpreter" ? {
55055
+ installUnavailableReason: `Light Code is using the Python interpreter at ${this.interpreter} directly, with no virtualenv, so it does not install or remove packages there \u2014 that environment belongs to whatever started it.`
55056
+ } : {},
54579
55057
  ...uv !== void 0 ? {
54580
55058
  installDeps: (packages) => installDependencies({
54581
55059
  uv,
@@ -54589,6 +55067,44 @@ var PythonManager = class {
54589
55067
  } : {}
54590
55068
  };
54591
55069
  }
55070
+ /**
55071
+ * Starts against an interpreter we did not create and do not own.
55072
+ *
55073
+ * Deliberately parallel to the uv path rather than folded into it: the two differ on the one
55074
+ * decision that matters — whether installing a package is allowed — and a single path with a
55075
+ * flag threaded through it is how that decision ends up being made in the wrong place.
55076
+ */
55077
+ async startWithoutUv(config2, workspaceRoot) {
55078
+ const bare = await detectBareInterpreter(config2.interpreterPath);
55079
+ if (bare === void 0) {
55080
+ this.ready = false;
55081
+ this.detail = config2.interpreterPath !== void 0 && config2.interpreterPath.trim().length > 0 ? `The configured interpreter could not be run: ${config2.interpreterPath}. Give the full path to a Python 3 executable, or clear the field to search the PATH.` : "No Python was found. Either install uv (Settings \u2192 Python) so Light Code can manage an environment for you, or make a Python 3 interpreter available on PATH \u2014 if one is already installed, give its full path in Settings \u2192 Python.";
55082
+ return;
55083
+ }
55084
+ try {
55085
+ const env2 = minimalPythonEnv(this.options.sessionEnv?.() ?? {});
55086
+ this.interpreter = bare.path;
55087
+ this.venvPath = "";
55088
+ this.venvSource = "interpreter";
55089
+ this.venvIsUvManaged = false;
55090
+ const workerScript = await this.writeWorkerScript();
55091
+ this.worker ??= new PythonWorker({
55092
+ pythonPath: bare.path,
55093
+ workerScript,
55094
+ cwd: workspaceRoot,
55095
+ env: env2,
55096
+ logger: this.options.logger,
55097
+ timeoutMs: this.timeoutMs
55098
+ });
55099
+ await this.refresh();
55100
+ this.ready = true;
55101
+ this.detail = `Ready \u2014 using Python ${bare.version} at ${bare.path}, with no virtualenv. Tools run against whatever that interpreter can already import; declared dependencies are NOT installed. Install uv if you want Light Code to manage an environment.`;
55102
+ } catch (error51) {
55103
+ this.ready = false;
55104
+ this.detail = error51 instanceof Error ? error51.message : String(error51);
55105
+ this.options.logger.warn("python environment failed to start", this.detail);
55106
+ }
55107
+ }
54592
55108
  status() {
54593
55109
  return {
54594
55110
  enabled: this.enabled,
@@ -55390,13 +55906,13 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
55390
55906
  // ../../packages/core/dist/host/bridge.js
55391
55907
  import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
55392
55908
  import { watch as watchPath } from "node:fs";
55393
- import { spawn as spawn5 } from "node:child_process";
55909
+ import { spawn as spawn6 } from "node:child_process";
55394
55910
  import fs18 from "node:fs/promises";
55395
55911
  import os2 from "node:os";
55396
55912
  import path23 from "node:path";
55397
55913
 
55398
55914
  // ../../packages/core/dist/office/bridge.js
55399
- import { spawn as spawn3 } from "node:child_process";
55915
+ import { spawn as spawn4 } from "node:child_process";
55400
55916
  import fs15 from "node:fs/promises";
55401
55917
  import path21 from "node:path";
55402
55918
 
@@ -57379,7 +57895,7 @@ var OfficeBridge = class {
57379
57895
  const BOM = "\uFEFF";
57380
57896
  await fs15.writeFile(target, `${BOM}${OFFICE_WORKER_SOURCE}`, "utf8");
57381
57897
  this.scriptPath = target;
57382
- const child = spawn3("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", target], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
57898
+ const child = spawn4("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", target], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
57383
57899
  this.child = child;
57384
57900
  this.buffer = "";
57385
57901
  child.stdout?.setEncoding("utf8");
@@ -58027,7 +58543,7 @@ var NodeFileSystem = class {
58027
58543
  };
58028
58544
 
58029
58545
  // ../../packages/core/dist/platform/node/terminal.js
58030
- import { execFile as execFile6, spawn as spawn4 } from "node:child_process";
58546
+ import { execFile as execFile6, spawn as spawn5 } from "node:child_process";
58031
58547
  var NodeTerminalProcess = class {
58032
58548
  child;
58033
58549
  dataListeners = [];
@@ -58078,7 +58594,7 @@ var NodeTerminalProcess = class {
58078
58594
  };
58079
58595
  var NodeTerminal = class {
58080
58596
  run(command, options = {}) {
58081
- const child = spawn4(command, {
58597
+ const child = spawn5(command, {
58082
58598
  cwd: options.cwd,
58083
58599
  env: options.env ? { ...process.env, ...options.env } : process.env,
58084
58600
  shell: true,
@@ -58256,7 +58772,31 @@ async function toSummary(profile, secrets) {
58256
58772
  baseUrl: profile.baseUrl,
58257
58773
  model: profile.model,
58258
58774
  authType: profile.auth.type,
58259
- hasApiKey: profile.auth.type === "apiKey" && await secrets.get(profile.auth.apiKeyRef) !== void 0,
58775
+ hasApiKey: profile.auth.type === "apiKey" && await resolveSecretRef(profile.auth.apiKeyRef, { secrets }) !== void 0,
58776
+ /*
58777
+ * The reference itself, when it names the environment.
58778
+ *
58779
+ * Sending it is not a secret leak (invariant 7) — a variable *name* is not its value, and the
58780
+ * user typed it. It is what lets the panel show "from $API_TOKEN" instead of an empty box that
58781
+ * reads as an unconfigured profile.
58782
+ */
58783
+ ...profile.auth.type === "apiKey" && describeSecretRef(profile.auth.apiKeyRef).kind === "env" ? { apiKeyEnvVar: describeSecretRef(profile.auth.apiKeyRef).envVar } : {},
58784
+ // Not a secret: a command describes how to *get* a credential. The token it produces never
58785
+ // crosses the bridge, and a form cannot edit what it is never shown.
58786
+ ...profile.auth.type === "tokenCommand" ? {
58787
+ /*
58788
+ * `env` is dropped on the way out, deliberately.
58789
+ *
58790
+ * It is the one field here somebody might have put a credential in, and the panel has no
58791
+ * business rendering it. Dropping it from the summary rather than from the schema means a
58792
+ * hand-written one keeps working; the form simply never sees it, and never sends it back.
58793
+ */
58794
+ tokenCommand: ((whole) => {
58795
+ const { env: env2, ...rest } = whole;
58796
+ void env2;
58797
+ return rest;
58798
+ })(profile.auth.tokenCommand)
58799
+ } : {},
58260
58800
  hasClientSecret: false,
58261
58801
  hasCertPassphrase: false
58262
58802
  };
@@ -59016,6 +59556,7 @@ function wireChatBridge(services) {
59016
59556
  combined.register(createSearchMailTool(mailToolOptions));
59017
59557
  combined.register(createMailPatternsTool(mailToolOptions));
59018
59558
  combined.register(createMailCoverageTool(mailToolOptions));
59559
+ combined.register(createMailStatsTool(mailToolOptions));
59019
59560
  combined.register(createOpenEmailTool({
59020
59561
  display: async (id) => office().request({ op: "outlook.display", id })
59021
59562
  }));
@@ -59138,7 +59679,8 @@ function wireChatBridge(services) {
59138
59679
  try {
59139
59680
  const { config: config2 } = await configManager.load();
59140
59681
  const refs = (config2.profiles ?? []).flatMap((profile) => SECRET_REFS_PER_PROFILE.map((refFor) => refFor(profile.id)));
59141
- const values = await Promise.all(refs.map((ref) => secrets.get(ref)));
59682
+ const named = (config2.profiles ?? []).map((profile) => profile.auth.type === "apiKey" ? profile.auth.apiKeyRef : void 0).filter((ref) => ref !== void 0);
59683
+ const values = await Promise.all([.../* @__PURE__ */ new Set([...refs, ...named])].map((ref) => resolveSecretRef(ref, { secrets })));
59142
59684
  cachedSecretValues = values.filter((value) => value !== void 0 && value.length > 0);
59143
59685
  return [...cachedSecretValues];
59144
59686
  } catch (error51) {
@@ -59448,6 +59990,8 @@ function wireChatBridge(services) {
59448
59990
  expertInformed = true;
59449
59991
  if (CONTROL_TOOLS.has(toolCall.name))
59450
59992
  return;
59993
+ if (chartFromToolCall(toolCall.name, toolCall.arguments) !== void 0)
59994
+ return;
59451
59995
  const summary = {
59452
59996
  id: toolCall.id,
59453
59997
  name: toolCall.name,
@@ -59461,6 +60005,11 @@ function wireChatBridge(services) {
59461
60005
  post({ type: "textChunk", text: result.content });
59462
60006
  return;
59463
60007
  }
60008
+ const chart = chartFromToolCall(toolCall.name, toolCall.arguments);
60009
+ if (chart !== void 0) {
60010
+ post(chart.kind === "chart" ? { type: "chart", chart: chart.chart, ...expertInformed ? { expertInformed } : {} } : { type: "chartError", message: chart.message });
60011
+ return;
60012
+ }
59464
60013
  const summary = {
59465
60014
  id: toolCall.id,
59466
60015
  name: toolCall.name,
@@ -59500,8 +60049,8 @@ function wireChatBridge(services) {
59500
60049
  }
59501
60050
  }
59502
60051
  async function buildAuthFromInput(input, id) {
59503
- async function persistSecret(ref, typed) {
59504
- const value = typed?.trim() ?? "";
60052
+ async function persistSecret(ref, typed2) {
60053
+ const value = typed2?.trim() ?? "";
59505
60054
  if (value.length > 0) {
59506
60055
  await secrets.set(ref, value);
59507
60056
  return true;
@@ -59525,8 +60074,32 @@ function wireChatBridge(services) {
59525
60074
  }
59526
60075
  };
59527
60076
  }
60077
+ if (input.authType === "tokenCommand") {
60078
+ if (services.executableAuthRefusal !== void 0)
60079
+ throw new Error(services.executableAuthRefusal);
60080
+ const existing2 = (await configManager.load()).config.profiles?.find((profile) => profile.id === id);
60081
+ if (input.tokenCommand === void 0 || input.tokenCommand.command.length === 0) {
60082
+ return existing2?.auth.type === "tokenCommand" ? existing2.auth : { type: "none" };
60083
+ }
60084
+ return {
60085
+ type: "tokenCommand",
60086
+ tokenCommand: {
60087
+ ...input.tokenCommand,
60088
+ command: input.tokenCommand.command.filter((part) => part.trim().length > 0)
60089
+ }
60090
+ };
60091
+ }
59528
60092
  if (input.authType === "none")
59529
60093
  return { type: "none" };
60094
+ const typed = input.apiKey.trim();
60095
+ if (describeSecretRef(typed).kind === "env") {
60096
+ await secrets.delete(apiKeyRefFor(id));
60097
+ return { type: "apiKey", apiKeyRef: typed };
60098
+ }
60099
+ const existing = (await configManager.load()).config.profiles?.find((profile) => profile.id === id);
60100
+ if (typed.length === 0 && existing?.auth.type === "apiKey" && describeSecretRef(existing.auth.apiKeyRef).kind === "env") {
60101
+ return existing.auth;
60102
+ }
59530
60103
  const apiKeyRef = apiKeyRefFor(id);
59531
60104
  if (await persistSecret(apiKeyRef, input.apiKey)) {
59532
60105
  return { type: "apiKey", apiKeyRef };
@@ -60591,7 +61164,7 @@ function wireChatBridge(services) {
60591
61164
  return void 0;
60592
61165
  try {
60593
61166
  const listed = await new Promise((resolve, reject2) => {
60594
- const child = spawn5(ripgrepPath, ["--files", "--hidden", "--glob", "!.git"], { cwd: workspaceRoot });
61167
+ const child = spawn6(ripgrepPath, ["--files", "--hidden", "--glob", "!.git"], { cwd: workspaceRoot });
60595
61168
  let out = "";
60596
61169
  child.stdout.on("data", (chunk) => out += chunk.toString("utf8"));
60597
61170
  child.on("error", reject2);
@@ -62090,6 +62663,21 @@ ${entry.content}`);
62090
62663
  lines.push(`## Thinking
62091
62664
 
62092
62665
  ${entry.content}`);
62666
+ } else if (entry.kind === "chart") {
62667
+ const chart = entry.chart;
62668
+ const header = ["", ...chart.series.map((series) => series.name)];
62669
+ lines.push([
62670
+ `## ${chart.title ?? "Chart"}`,
62671
+ "",
62672
+ `| ${header.join(" | ")} |`,
62673
+ `| ${header.map(() => "---").join(" | ")} |`,
62674
+ ...chart.categories.map((category, index) => `| ${category} | ${chart.series.map((series) => String(series.values[index] ?? "")).join(" | ")} |`),
62675
+ ...chart.note === void 0 ? [] : ["", chart.note]
62676
+ ].join("\n"));
62677
+ } else if (entry.kind === "chartError") {
62678
+ lines.push(`## Chart
62679
+
62680
+ Could not be drawn: ${entry.message}`);
62093
62681
  } else {
62094
62682
  const call = entry.toolCall;
62095
62683
  lines.push([
@@ -62590,6 +63178,89 @@ function deriveTitle(messages) {
62590
63178
  return `${cut.trimEnd()}\u2026`;
62591
63179
  }
62592
63180
 
63181
+ // ../../packages/core/dist/charts/types.js
63182
+ var CHART_TYPES = ["bar", "stackedBar", "groupedBar", "line", "multiLine", "pie"];
63183
+ var MAX_CATEGORIES = 200;
63184
+ var MAX_SERIES = 12;
63185
+ var finiteNumber = external_exports.number().refine((value) => Number.isFinite(value), { message: "must be a finite number" });
63186
+ var chartSeriesSchema = external_exports.object({
63187
+ name: external_exports.string().min(1).describe('What this series is, e.g. "Alerts" or "Inbox". Shown in the legend.'),
63188
+ values: external_exports.array(finiteNumber).min(1).max(MAX_CATEGORIES).describe("One number per category, in the same order as `categories`."),
63189
+ /**
63190
+ * What each number is made of, for the reader who asks "which ones?".
63191
+ *
63192
+ * Aligned with `values` by index, and any entry may be omitted. This is the drill-down: a bar
63193
+ * showing 14 alerts can list the fourteen subjects, so the chart is a way *into* the data rather
63194
+ * than a summary that replaces it.
63195
+ */
63196
+ detail: external_exports.array(external_exports.union([external_exports.array(external_exports.string()), external_exports.null()])).max(MAX_CATEGORIES).optional().describe("Optional. For each value, the rows behind it \u2014 subjects, ids, filenames, whatever the number counted. Same order as `values`; use null where there is nothing to show.")
63197
+ });
63198
+ var chartSpecSchema = external_exports.object({
63199
+ type: external_exports.enum(CHART_TYPES).describe("bar, stackedBar, groupedBar, line, multiLine or pie."),
63200
+ title: external_exports.string().max(200).optional(),
63201
+ categories: external_exports.array(external_exports.string()).min(1).max(MAX_CATEGORIES).describe("The x axis, or the pie slice labels. One per value in every series."),
63202
+ series: external_exports.array(chartSeriesSchema).min(1).max(MAX_SERIES),
63203
+ xLabel: external_exports.string().max(80).optional(),
63204
+ yLabel: external_exports.string().max(80).optional(),
63205
+ note: external_exports.string().max(500).optional().describe("A line under the chart. Say where the numbers came from, and what they exclude.")
63206
+ }).superRefine((spec, context) => {
63207
+ for (const [index, series] of spec.series.entries()) {
63208
+ if (series.values.length !== spec.categories.length) {
63209
+ context.addIssue({
63210
+ code: "custom",
63211
+ path: ["series", index, "values"],
63212
+ /*
63213
+ * Refused rather than padded, and the message says the counts.
63214
+ *
63215
+ * A silently padded series draws a chart that is the right shape and the wrong answer,
63216
+ * and nobody checks a chart against its data — that is what a chart is for. Being told
63217
+ * the two numbers is also what lets the model fix it in one turn.
63218
+ */
63219
+ message: `series "${series.name}" has ${String(series.values.length)} value(s) but there are ${String(spec.categories.length)} categories. They must match exactly \u2014 a chart drawn from misaligned data looks correct and is not.`
63220
+ });
63221
+ }
63222
+ if (series.detail !== void 0 && series.detail.length > series.values.length) {
63223
+ context.addIssue({
63224
+ code: "custom",
63225
+ path: ["series", index, "detail"],
63226
+ message: `series "${series.name}" has more detail entries than values.`
63227
+ });
63228
+ }
63229
+ }
63230
+ if (spec.type === "pie") {
63231
+ if (spec.series.length !== 1) {
63232
+ context.addIssue({
63233
+ code: "custom",
63234
+ path: ["series"],
63235
+ message: "a pie chart takes exactly one series \u2014 use stackedBar or groupedBar for several."
63236
+ });
63237
+ }
63238
+ if (spec.series.some((series) => series.values.some((value) => value < 0))) {
63239
+ context.addIssue({
63240
+ code: "custom",
63241
+ path: ["series"],
63242
+ // A negative slice has no meaning: it cannot be drawn, and drawing its absolute value
63243
+ // would misreport the total every other slice is measured against.
63244
+ message: "a pie chart cannot show negative values."
63245
+ });
63246
+ }
63247
+ }
63248
+ if (spec.type === "stackedBar" && spec.series.some((series) => series.values.some((value) => value < 0))) {
63249
+ context.addIssue({
63250
+ code: "custom",
63251
+ path: ["series"],
63252
+ message: "a stacked bar cannot show negative values \u2014 the segments would overlap rather than stack."
63253
+ });
63254
+ }
63255
+ });
63256
+ function chartTotals(spec) {
63257
+ const series = spec.series.map((entry) => ({
63258
+ name: entry.name,
63259
+ total: entry.values.reduce((sum, value) => sum + value, 0)
63260
+ }));
63261
+ return { series, grand: series.reduce((sum, entry) => sum + entry.total, 0) };
63262
+ }
63263
+
62593
63264
  // ../../packages/core/dist/history/transcript.js
62594
63265
  var CONTROL_TOOLS = /* @__PURE__ */ new Set(["attempt_completion", "ask_followup_question"]);
62595
63266
  function formatToolArguments(raw) {
@@ -62636,6 +63307,11 @@ function toTranscript(messages) {
62636
63307
  }
62637
63308
  for (const toolCall of message3.toolCalls ?? []) {
62638
63309
  const result = resultsByCallId.get(toolCall.id);
63310
+ const asChart = chartFromToolCall(toolCall.name, toolCall.arguments);
63311
+ if (asChart !== void 0) {
63312
+ entries.push(asChart.kind === "chart" ? { kind: "chart", chart: asChart.chart, ...expertInformed ? { expertInformed: true } : {} } : asChart);
63313
+ continue;
63314
+ }
62639
63315
  if (CONTROL_TOOLS.has(toolCall.name)) {
62640
63316
  if (result !== void 0)
62641
63317
  entries.push({ kind: "text", role: "assistant", content: result });
@@ -62661,6 +63337,19 @@ function toTranscript(messages) {
62661
63337
  }
62662
63338
  return entries;
62663
63339
  }
63340
+ function chartFromToolCall(name, rawArguments) {
63341
+ if (name !== "show_chart")
63342
+ return void 0;
63343
+ const parsed = chartSpecSchema.safeParse(decodeArguments(rawArguments));
63344
+ return parsed.success ? { kind: "chart", chart: parsed.data } : { kind: "chartError", message: parsed.error.issues.map((issue2) => issue2.message).join("; ") };
63345
+ }
63346
+ function decodeArguments(raw) {
63347
+ try {
63348
+ return JSON.parse(raw.length > 0 ? raw : "{}");
63349
+ } catch {
63350
+ return raw;
63351
+ }
63352
+ }
62664
63353
 
62665
63354
  // ../../packages/core/dist/history/redactTask.js
62666
63355
  function redactMessage(message3, knownSecrets) {
@@ -62688,6 +63377,29 @@ function redactTask(task, knownSecrets) {
62688
63377
  };
62689
63378
  }
62690
63379
 
63380
+ // ../../packages/core/dist/tools/showChart.js
63381
+ function createShowChartTool() {
63382
+ return {
63383
+ name: "show_chart",
63384
+ // A control tool: it presents, it does not act. Never filtered out by a mode, never gated.
63385
+ group: "always",
63386
+ description: "Draw a chart for the user: bar, stackedBar, groupedBar, line, multiLine or pie. Give `categories` (the x axis, or the pie slice labels) and one or more named `series`, each with one number per category. Use it whenever a set of numbers is easier seen than read \u2014 counts per folder or per day, a value trending over time, a breakdown of a total. Series lengths must match the categories exactly; a mismatch is refused rather than padded, because a chart drawn from misaligned data looks correct and is not. Add `detail` to a series to record what each number is made of (the subjects counted, the files measured) \u2014 the user can then open any point and see what went into it, which is what makes a chart worth drawing rather than a summary that hides the evidence. Say in `note` where the numbers came from and what they leave out.",
63387
+ parametersSchema: chartSpecSchema,
63388
+ async execute(params) {
63389
+ const totals = chartTotals(params);
63390
+ const detailed = params.series.filter((series) => series.detail !== void 0).length;
63391
+ return {
63392
+ content: [
63393
+ `Drew a ${params.type} chart${params.title === void 0 ? "" : ` titled "${params.title}"`} with ${String(params.categories.length)} categor(ies) and ${String(params.series.length)} series.`,
63394
+ ...totals.series.map((entry) => ` ${entry.name}: total ${String(entry.total)}`),
63395
+ detailed === 0 ? "No per-point detail was given, so the user cannot open a point to see what is behind it. Add `detail` when the numbers count things worth naming." : `${String(detailed)} series carr(ies) per-point detail, so the user can open a point and see what went into it.`,
63396
+ "The chart is now in the conversation. Describe what it shows rather than reciting the numbers again \u2014 they are on screen."
63397
+ ].join("\n")
63398
+ };
63399
+ }
63400
+ };
63401
+ }
63402
+
62691
63403
  // ../../packages/core/dist/tools/applyDiff/eol.js
62692
63404
  function detectEol(text) {
62693
63405
  const crlfCount = (text.match(/\r\n/g) ?? []).length;
@@ -63396,6 +64108,7 @@ function createDefaultToolRegistry() {
63396
64108
  registry2.register(executeCommandTool);
63397
64109
  registry2.register(askFollowupQuestionTool);
63398
64110
  registry2.register(createAskUserFormTool());
64111
+ registry2.register(createShowChartTool());
63399
64112
  registry2.register(attemptCompletionTool);
63400
64113
  return registry2;
63401
64114
  }
@@ -64245,6 +64958,15 @@ async function startServer(options) {
64245
64958
  * absent for them rather than a queue they would have to visit to approve themselves.
64246
64959
  */
64247
64960
  ...roles.shared && !isAdminSession(principal) ? {
64961
+ /*
64962
+ * A personal profile may not run a program to fetch its token.
64963
+ *
64964
+ * That would be arbitrary execution as the service account, which §14 says plainly is
64965
+ * the thing locking down configuration does *not* buy you. An administrator can still
64966
+ * set one up as a shared profile, which is where a credential belonging to the server
64967
+ * belongs anyway.
64968
+ */
64969
+ executableAuthRefusal: "A profile that runs a program to fetch its token can only be set up by an administrator on a shared server \u2014 it would run as the account this server runs as. Ask an administrator to add it as a shared profile, or use an API key.",
64248
64970
  submitForReview: async (request) => {
64249
64971
  const queued = await reviews.submit({ ...request, authorId: principal.id, authorName: principal.displayName });
64250
64972
  log(`${principal.displayName} submitted ${request.kind} "${request.name}" for review`);