diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..45a8238 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +# EditorConfig (https://editorconfig.org) +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space + +[*.ps1] +indent_size = 4 + +[*.{toml,sh}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..4150ac5 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,29 @@ +# The full check on all three systems runcoder supports. GitHub-hosted runners: this repository +# is public, and the Mac and Windows runs are the point. No secrets, no deploy, no publish. +name: check +on: + pull_request: + push: + branches: [main] +permissions: + contents: read +jobs: + check: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # no cache, so nothing a PR names is restored or saved + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + package-manager-cache: false + - run: npm install --global pnpm@12.25.1 + - run: pnpm install --frozen-lockfile + - run: pnpm check diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a934414 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +*.log +node_modules/ +tests/tmp/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5ebc40a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,48 @@ +# AGENTS.md + +Operating contract for anyone (human or coding agent) working in this repository. +`runcoder` is a Node.js command-line tool, published to npm as `@setkernel/runcoder`, that runs a +coding model on a Cloud Run GPU in the user's own Google Cloud project and deletes it afterwards. +It runs on other people's machines (macOS, Linux, Windows) against their billing accounts. +Licence: PolyForm Shield 1.0.0 (source-available, `LICENSE.md`). + +## Working agreement + +- Keep going on steps that don't need the owner; put status notes alongside the next action. +- Stop and ask before publishing to npm, pushing to `main`, or running runcoder against a real + Google Cloud project (that deploys a GPU and bills). +- Done means `pnpm check` passes; CI runs it on all three systems. A behaviour change that the + fakes cannot show (a real deploy, a real terminal window on Linux or Windows) also needs a run + on that system; say so when it has not happened. +- End a run with three headings: **Blocked on owner**, **Changed**, **Found**. + +## Commands + +```sh +pnpm install +pnpm check # node --check on every module, then the tests (about 5 minutes, one at a time) +pnpm test # the tests only +``` + +## Layout + +- `bin/runcoder.mjs`: commands and signal handling; every exit path ends in `cleanup()`. +- `src/session.mjs`: the session (lock, deploy, keep-alive loop, cleanup that deletes the service). +- `src/cloud.mjs`: every gcloud call. `src/tunnel.mjs`: the proxy, model download and warm-up. +- `src/cost.mjs`: billed time from Cloud Monitoring and prices from the Cloud Billing catalog. +- `src/qwen.mjs`, `src/qwen-window.mjs`: Qwen Code's settings and its terminal window. +- `src/setup.mjs`, `src/config.mjs`, `src/ui.mjs`, `src/proc.mjs`. +- `tests/`: runcoder run as a child process against `tests/fake/` (a Node gcloud with sh and + `.cmd` shims, fake Google APIs, a fake Ollama). + +## Rules + +- Nothing that bills may outlive the session: every new exit path must reach `cleanup()`, and a + change to start-up or shutdown needs a test that shows the fake service deleted (`noService`). +- Sign-in stays gcloud's own. No keys, tokens or account names in the repository, the config + file or the logs. +- The config file is data: never `eval`, `source` or `import` it. +- Run external programs through `src/proc.mjs` (cross-spawn), never a shell string, so Windows + `.cmd` files and paths with spaces work. Any call only one system has needs the others' branch. +- Costs come from Google's billed time and price list, never from a local estimate. +- Tests never reach Google and never notify the desktop: keep them on the fakes. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4c6caf3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,6 @@ +# CLAUDE.md + +Agent instructions for this repository live in [AGENTS.md](AGENTS.md), the +tool-neutral standard. Edit that file, not this one. + +@AGENTS.md diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..7beac78 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,91 @@ +Required Notice: Copyright 2026 SetKernel Digital Inc. + +# PolyForm Shield License 1.0.0 + + + +## Acceptance + +In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses. + +## Copyright License + +The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license). + +## Distribution License + +The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license). + +## Notices + +You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example: + +> Required Notice: Copyright Yoyodyne, Inc. (http://example.com) + +## Changes and New Works License + +The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose. + +## Patent License + +The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software. + +## Noncompete + +Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software. + +## Competition + +Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes. + +## New Products + +If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions. + +## Discontinued Products + +You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example: + +> Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms) + +## Sales of Business + +If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product. + +## Fair Use + +You may have "fair use" rights for the software under the law. These terms do not limit them. + +## No Other Rights + +These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses. + +## Patent Defense + +If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company. + +## Violations + +The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately. + +## No Liability + +***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*** + +## Definitions + +The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms. + +A **product** can be a good or service, or a combination of them. + +**You** refers to the individual or entity agreeing to these terms. + +**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates. + +**Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with. + +**Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the software under these terms. + +**Use** means anything you do with the software requiring one of your licenses. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fd8acd9 --- /dev/null +++ b/README.md @@ -0,0 +1,172 @@ +# runcoder + +A private open coding model on a Google Cloud Run GPU, from start to delete in one command. + +`runcoder` starts a GPU server in your own Google Cloud project, downloads an open model +([Qwen 3.8 27B](https://ollama.com/library/qwen3.8) by default) onto it, opens +[Qwen Code](https://github.com/QwenLM/qwen-code) in your project folder, and deletes the server +when you are done. You pay Google only for the minutes the server exists, and runcoder shows what +each session cost from Google's own billing data. + +It works on macOS, Linux and Windows. Sign-in is gcloud's own: runcoder has no account, no key +and no server of its own. + +## What you need + +- [Node.js](https://nodejs.org) 22 or later. +- The [Google Cloud CLI](https://cloud.google.com/sdk/docs/install) (`gcloud`), logged in with + `gcloud auth login`. +- A Google Cloud project with billing turned on. Google AI Pro and Ultra plans include a monthly + Google Cloud credit that covers a few hours a month (see [Cost](#cost)). + +## Install and set up + +```sh +npm install --global @setkernel/runcoder +runcoder setup +``` + +(`pnpm add --global @setkernel/runcoder` works the same.) npm and pnpm may say they skipped an +install script for `@qwen-code/audio-capture`, Qwen Code's voice input; runcoder does not use it. + +`runcoder setup` checks Node.js and gcloud, offers `gcloud auth login` if you are not logged in, +lists your projects to pick one, checks that billing is on and reads its currency, and asks +before turning on the two APIs it uses (Cloud Run and Cloud Monitoring; turning them on costs +nothing). It then asks for your monthly credit, if you have one, and prints the hourly rate. +Without a keyboard: `runcoder setup --project my-project --credit 14.25 --yes`. + +## Use + +```sh +runcoder ~/code/my-project +``` + +1. It deploys the server (Cloud Run, one GPU, `us-central1`, then `europe-west4` if that region + has no GPU free) and opens a private tunnel to it on `localhost:11435`. +2. It downloads the model to the server (about 10 minutes for 30 GB), loads it onto the GPU and + times a test answer. +3. It opens Qwen Code in a new terminal window, in your folder, pointed at the server. +4. The first window stays as the control panel: every 10 minutes it prints the time and cost so + far. **Press q there (or Ctrl+C, or close the window) and it deletes the server**, then prints + what the session cost. + +If the folder has earlier Qwen Code sessions, runcoder asks whether to continue the latest +(c), pick one (r), or start fresh. `-c`, `-p` and `-n` answer that in advance. + +Other commands: + +| Command | What it does | +| --- | --- | +| `runcoder status` | Whether a runcoder server exists (so whether anything can bill), and the credit left. | +| `runcoder credit` | This billing month's sessions with Google's billed minutes and cost. | +| `runcoder down` | Delete the server without starting anything. Use it if a run was killed. | +| `runcoder help` | All commands and options. | + +## Safety + +Something that bills by the second must never be left running. runcoder deletes the server when: + +- you press q, press Ctrl+C, or close its window; +- Qwen Code has been closed for 15 minutes (`RUNCODER_QWEN_IDLE_MINUTES`); +- the session reaches 150 minutes (`RUNCODER_MAX_MINUTES`); +- the model is lost and does not come back after three tries; +- anything goes wrong during start-up. + +The delete is retried five times. If it still cannot confirm the server is gone, it says so in +capitals and tells you to run `runcoder down`. The server has `--max-instances=1` and +`--min-instances=0`, so even a server that was somehow left behind scales to zero (and stops +billing) once nothing has used it for about 15 minutes. Only one runcoder session runs at a time +per computer, and your computer is kept awake while it runs. + +## Cost + +runcoder reads two things from Google, so its numbers match your bill rather than a guess: + +- **billed time**: Cloud Monitoring's `billable_instance_time` for the service, per session; +- **prices**: the Cloud Billing price list, in your billing account's currency. + +The default server (an NVIDIA RTX PRO 6000 GPU with 20 vCPU and 80 GiB) is billed for the GPU, +the CPU and the memory. Cloud Run's free tier (240,000 vCPU-seconds and 450,000 GiB-seconds a +month, per billing account) pays for the CPU and memory of roughly the first 2.8 hours each +month, so the rate goes up once it is used. In December 2026 in Canadian dollars that was +**CA$1.87 an hour, then CA$4.54**; `runcoder setup` prints yours. + +A monthly credit of CA$14.25 (Google AI Pro, in Canada) therefore buys about 4¾ billed hours a +month, about 4 hours of coding once the download is counted. Google publishes no API for credit +balances, so runcoder tracks the credit from the amount you give it and its own billed sessions; +other spending on the same billing account uses the credit too. When the credit looks used up, +runcoder asks before starting (and refuses without a keyboard unless `RUNCODER_ALLOW_PAID=1`). +Set `RUNCODER_FREE_TIER=0` if other Cloud Run services on the billing account use the free tier. + +For a smaller, slower and cheaper server: `RUNCODER_GPU=nvidia-l4 RUNCODER_CPU=8 +RUNCODER_MEMORY=32Gi RUNCODER_MODEL=`. + +## Privacy + +Your code and prompts go from Qwen Code through the tunnel (`gcloud run services proxy`, which +signs each request with your gcloud login) to the model on your own Cloud Run service. The +service refuses requests without your login (`--no-allow-unauthenticated`). Cloud Run's request +log records each request's time, path and size, not its contents. Nothing goes to setkernel or +any other third party, and the server, the downloaded model and its memory are deleted at the end +of each session. Qwen Code's own usage statistics are off. + +## Settings + +`runcoder setup` writes the config file. Any of these can go there as `KEY=value`, or be set in +the environment for one run (`RUNCODER_MAX_MINUTES=60 runcoder .`). + +| Setting | Default | | +| --- | --- | --- | +| `RUNCODER_PROJECT` | (setup asks) | Google Cloud project | +| `RUNCODER_MONTHLY_CREDIT` | `0` | Monthly credit to track; 0 turns tracking off | +| `RUNCODER_CURRENCY` | (setup reads it) | The billing account's currency | +| `RUNCODER_REGIONS` | `us-central1 europe-west4` | Regions to try, in order | +| `RUNCODER_MODEL` | `qwen3.8:27b-q8_0` | Any [Ollama](https://ollama.com/library) model that fits the GPU | +| `RUNCODER_CONTEXT` | `131072` | Context window, in tokens | +| `RUNCODER_GPU` | `nvidia-rtx-pro-6000` | Cloud Run GPU type (`nvidia-l4` is the other) | +| `RUNCODER_CPU`, `RUNCODER_MEMORY` | `20`, `80Gi` | Must suit the GPU (Cloud Run's rules) | +| `RUNCODER_MAX_MINUTES` | `150` | Hard limit for one session | +| `RUNCODER_QWEN_IDLE_MINUTES` | `15` | Shut down this long after Qwen Code closes | +| `RUNCODER_PORT` | `11435` | Local end of the tunnel | +| `RUNCODER_OPEN` | `auto` | `none` prints the Qwen Code command instead of opening a window | +| `RUNCODER_FREE_TIER` | `1` | `0` if the Cloud Run free tier is used elsewhere | +| `RUNCODER_ALLOW_PAID` | `0` | `1` lets a run without a keyboard go past the credit | +| `RUNCODER_SERVICE` | `runcoder` | Cloud Run service name | +| `RUNCODER_IMAGE` | `ollama/ollama:0.40.19` | Server image | + +Where things are: + +| | macOS and Linux | Windows | +| --- | --- | --- | +| Config | `~/.config/runcoder/config` | `%APPDATA%\runcoder\config` | +| Logs, lock, price cache | `~/.local/state/runcoder` | `%LOCALAPPDATA%\runcoder\state` | +| Qwen Code settings and sessions | `~/.local/share/runcoder/qwen-home` | `%LOCALAPPDATA%\runcoder\data\qwen-home` | + +The `XDG_*` variables move them on any system. Each run writes a full log, kept 60 days; the +path is printed on any error. + +## Uninstall + +```sh +runcoder down +npm uninstall --global @setkernel/runcoder +``` + +Then delete the three folders above, and turn off the Cloud Run and Cloud Monitoring APIs in your +project if nothing else uses them. + +## Development + +```sh +pnpm install +pnpm check # syntax pass, then the tests +``` + +The tests run runcoder for real against a fake `gcloud`, fake Google APIs and a fake model server, +so nothing reaches Google and nothing bills; one test starts the installed Qwen Code. CI runs them +on Linux, macOS and Windows. + +## Licence + +[PolyForm Shield 1.0.0](LICENSE.md): free to use, change and share, except to build a product +that competes with it. diff --git a/bin/runcoder.mjs b/bin/runcoder.mjs new file mode 100644 index 0000000..94d2446 --- /dev/null +++ b/bin/runcoder.mjs @@ -0,0 +1,71 @@ +#!/usr/bin/env node +// runcoder: a private open coding model on a Google Cloud Run GPU, from start to delete in one command. + +import { readFileSync } from "node:fs"; +import { loadSettings } from "../src/config.mjs"; + +const HELP = `runcoder: a private open coding model on a Google Cloud Run GPU, from start to delete in one command. + + runcoder setup Check this computer and your Google Cloud project, and save the settings. + Options: --project ID, --credit AMOUNT, --yes (no questions). + runcoder [-c|-p|-n] [DIR] + Start the GPU server, download the model, open Qwen Code in DIR (default: the + current folder) in a new terminal window, keep it alive, and delete everything + when you press q here (or Ctrl+C, or close this window). + If DIR has earlier Qwen Code sessions you are asked which to open; + -c continues the last one, -p shows the session picker, -n starts fresh. + runcoder status Whether a runcoder service exists (so whether anything can bill), and the credit left. + runcoder credit This billing month's runs with Google's billed minutes and cost, and the credit left. + runcoder down Delete the service without starting anything (recovery). + runcoder version Print the version. + runcoder help Show this help. + +Sign-in is gcloud's own (gcloud auth login). Settings: runcoder setup writes them; any RUNCODER_* +environment variable overrides them for one run. https://github.com/setkernel/runcoder`; + +const [cmd, ...rest] = process.argv.slice(2); +if (["help", "-h", "--help"].includes(cmd)) { + console.log(HELP); + process.exit(0); +} +if (["version", "--version", "-v"].includes(cmd)) { + const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); + console.log(`runcoder ${pkg.version}`); + process.exit(0); +} + +const { say, Stop, logFile, log } = await import("../src/ui.mjs"); +const { cleanup, cmdUp, cmdStatus, cmdCredit, cmdDown } = await import("../src/session.mjs"); +const { cmdSetup } = await import("../src/setup.mjs"); + +let exiting = false; +async function finish(rc) { + if (exiting) return; + exiting = true; + process.exit(await cleanup(rc)); +} +// Ctrl+C, a closed window (SIGHUP, also on Windows) or a kill all end in the same cleanup. +for (const [sig, rc] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]) process.on(sig, () => finish(rc)); +// Any error nothing else caught still ends in cleanup, so the server is deleted; during cleanup it is +// logged and cleanup carries on. +for (const ev of ["uncaughtException", "unhandledRejection"]) { + process.on(ev, (e) => { + log(`${ev}: ${e?.stack || e}`); + finish(1); + }); +} + +try { + const s = loadSettings(); + if (cmd === "setup") await cmdSetup(s, rest); + else if (cmd === "status") await cmdStatus(s); + else if (cmd === "credit") await cmdCredit(s); + else if (cmd === "down") cmdDown(s); + else await cmdUp(s, cmd === undefined ? [] : [cmd, ...rest]); + await finish(0); +} catch (e) { + if (e instanceof Stop) say(`ERROR: ${e.message}`); + else say(`ERROR: ${e.stack || e}`); + say(`Full log: ${logFile}`); + await finish(1); +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..efc7df7 --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "@setkernel/runcoder", + "version": "0.1.0", + "description": "One command for a private open-source coding model on a Google Cloud Run GPU: starts it, opens Qwen Code, and deletes everything when you are done.", + "type": "module", + "bin": { "runcoder": "bin/runcoder.mjs" }, + "files": ["bin", "src", "README.md", "LICENSE.md"], + "engines": { "node": ">=22" }, + "os": ["darwin", "linux", "win32"], + "packageManager": "pnpm@12.25.1", + "scripts": { + "test": "node --test --test-concurrency=1 --test-force-exit --test-timeout=300000 \"tests/*.test.mjs\"", + "check": "node scripts/check.mjs" + }, + "dependencies": { + "@qwen-code/qwen-code": "0.28.7", + "cross-spawn": "7.0.6" + }, + "keywords": ["cloud-run", "gpu", "ollama", "qwen-code", "coding-assistant", "self-hosted", "gcloud"], + "license": "SEE LICENSE IN LICENSE.md", + "repository": { "type": "git", "url": "git+https://github.com/setkernel/runcoder.git" }, + "homepage": "https://github.com/setkernel/runcoder#readme" +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..a15a1fe --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,792 @@ +--- +lockfileVersion: '9.0' + +importers: + + .: + configDependencies: {} + packageManagerDependencies: + pnpm: + specifier: 12.25.1 + version: 12.25.1 + +packages: + + '@pnpm/exe.android-arm64@12.25.1': + resolution: {integrity: sha512-QHXIyWMsuntq05xq9twYS6upQZS2TYeJIfmBWDFw1Xyi8XQxiaD06DSTWwZYjR38GwOP/dveeMC2jk2Y68IAAg==} + cpu: [arm64] + os: [android] + + '@pnpm/exe.android-x64@12.25.1': + resolution: {integrity: sha512-bOJZTzi5c0MrI8xn6qU+0QzYu3gHMUtwLxb8ZRzuk/by7u6XhGXpn+gfppw7BF3te+rxpqK/mSR2PXb40d/7kg==} + cpu: [x64] + os: [android] + + '@pnpm/exe.darwin-arm64@12.25.1': + resolution: {integrity: sha512-NXG2kaXA7ui3T7aznhAmG8AwWZ/BmKkxqT9DIIQJ0jU1jLKkRhGce1gbyJ+RAeGKx0HcRHAJbRi38lcHgpCteA==} + cpu: [arm64] + os: [darwin] + + '@pnpm/exe.darwin-x64@12.25.1': + resolution: {integrity: sha512-cDnnUeocsg6ESvgjxTs9az5SUt9MEaINaMKGzAEqrfFMCRvaYgkC+0Ct7eYb/41i9WYPvd9DFv8H29LHECwcVA==} + cpu: [x64] + os: [darwin] + + '@pnpm/exe.freebsd-x64@12.25.1': + resolution: {integrity: sha512-LEDM+BE5BdYEetfEHKSD9f5IhOWmMAHix9bMqhds6dn3cMICNQeJZQaoimwUDeVVAR8yMtvaDwRZGuWXOq5gJw==} + cpu: [x64] + os: [freebsd] + + '@pnpm/exe.linux-arm64-musl@12.25.1': + resolution: {integrity: sha512-LtURUp1sJoS0ENQtKLk+oTI7oSlcEDHl3SOxxS8AUD/FTmP1AM1htwYwxi+91J+MTinOYqcUFrgb1f87Zn1Vfw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-arm64@12.25.1': + resolution: {integrity: sha512-55Ni6+zebnL2zdvKq23tZCEWbtPSMKeQ1MwJAwqDqS/VjD/Z6hT0BlJSTFvHKUgrWOBxnH501iTIyQgLVD+Cfw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-loong64@12.25.1': + resolution: {integrity: sha512-52Fzal3IdcqsJ1kChNZC00JoFcwA9tDem/qTuZxpeJcc0KTALXTI5U/LbVF1+OXBfn72ADjS0Hxewkng7Q1iBA==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-ppc64@12.25.1': + resolution: {integrity: sha512-x3b9VQyrmHi1IIejDGqZWrdmgbtTV/qgE3Sca0NVYmY6gT1cAvkKFq6tQvHJEgeEdny7hGKl+1sk6YkKRs1Sfg==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-riscv64@12.25.1': + resolution: {integrity: sha512-lPQ5PjYog/N07VsOBEZr661GgZ7y39wQLRCviHcL4RfpMBpe4XeJKK3W7YKl9NJz6+5/nzMYYfTcvZPFLWuMvA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-s390x@12.25.1': + resolution: {integrity: sha512-5kdJeOXns1O/PYqdR2Zk/0ci/0mCz1LhaJDIA6NiqNdgFxwCC6ufRTBiu9u4FB/F2MWBLPDtyHxwzpcbBFCP9Q==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-x64-musl@12.25.1': + resolution: {integrity: sha512-GRsFj54bSmdhceZwrA+zReMfGJw6X6qpC4pJh6iLaUcy3p0fG7A7Zqr70AKmtzvW1Zm2VGkeeIzja6QSkN09Vw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-x64@12.25.1': + resolution: {integrity: sha512-Db2T6CtSNO8hjG6FISkOaZ2PW/OpynoXcT+jWEh44xDgSBt68rgbjGIbzjXSKJ+vH2mkoUxaUZCcLLusBVqelw==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.netbsd-x64@12.25.1': + resolution: {integrity: sha512-2hU5yNM/C8FT5eqbrNzB+0yGw/SS3oMJ1afk8pXEDsGU4vWdiiWxSqQ0kM8GHIvCDa/qRyw9ns98XWu5KZxxiA==} + cpu: [x64] + os: [netbsd] + + '@pnpm/exe.win32-arm64@12.25.1': + resolution: {integrity: sha512-v7YduE+TgEid1AiIThVBmYBnF0dj6vtk3ymcCkcM5FvanAM8MXoZhSiQYayQruh8xDwTXf5n8Zgn1OOi8WtqDg==} + cpu: [arm64] + os: [win32] + + '@pnpm/exe.win32-x64@12.25.1': + resolution: {integrity: sha512-cMfLsOE4zxSYBZYWyK1tr6BvCKVDyC81CnZg953t/6MEL592D8gk0eGdHQilEcd+yO+o6Ey1W9LLQdjl7pglsQ==} + cpu: [x64] + os: [win32] + + pnpm@12.25.1: + resolution: {integrity: sha512-psZ31wNNPXmvE28z2zPNbUEz1z+lZaBr1kqPCW0lN92HoI1o4Y/zd3cf9RwY4uwxvgO0RnDrGeJBiQ6uOu0Bag==} + engines: {node: '>=18'} + hasBin: true + +snapshots: + + '@pnpm/exe.android-arm64@12.25.1': + optional: true + + '@pnpm/exe.android-x64@12.25.1': + optional: true + + '@pnpm/exe.darwin-arm64@12.25.1': + optional: true + + '@pnpm/exe.darwin-x64@12.25.1': + optional: true + + '@pnpm/exe.freebsd-x64@12.25.1': + optional: true + + '@pnpm/exe.linux-arm64-musl@12.25.1': + optional: true + + '@pnpm/exe.linux-arm64@12.25.1': + optional: true + + '@pnpm/exe.linux-loong64@12.25.1': + optional: true + + '@pnpm/exe.linux-ppc64@12.25.1': + optional: true + + '@pnpm/exe.linux-riscv64@12.25.1': + optional: true + + '@pnpm/exe.linux-s390x@12.25.1': + optional: true + + '@pnpm/exe.linux-x64-musl@12.25.1': + optional: true + + '@pnpm/exe.linux-x64@12.25.1': + optional: true + + '@pnpm/exe.netbsd-x64@12.25.1': + optional: true + + '@pnpm/exe.win32-arm64@12.25.1': + optional: true + + '@pnpm/exe.win32-x64@12.25.1': + optional: true + + pnpm@12.25.1: + optionalDependencies: + '@pnpm/exe.android-arm64': 12.25.1 + '@pnpm/exe.android-x64': 12.25.1 + '@pnpm/exe.darwin-arm64': 12.25.1 + '@pnpm/exe.darwin-x64': 12.25.1 + '@pnpm/exe.freebsd-x64': 12.25.1 + '@pnpm/exe.linux-arm64': 12.25.1 + '@pnpm/exe.linux-arm64-musl': 12.25.1 + '@pnpm/exe.linux-loong64': 12.25.1 + '@pnpm/exe.linux-ppc64': 12.25.1 + '@pnpm/exe.linux-riscv64': 12.25.1 + '@pnpm/exe.linux-s390x': 12.25.1 + '@pnpm/exe.linux-x64': 12.25.1 + '@pnpm/exe.linux-x64-musl': 12.25.1 + '@pnpm/exe.netbsd-x64': 12.25.1 + '@pnpm/exe.win32-arm64': 12.25.1 + '@pnpm/exe.win32-x64': 12.25.1 + +--- +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@qwen-code/qwen-code': + specifier: 0.28.7 + version: 0.28.7 + cross-spawn: + specifier: 7.0.6 + version: 7.0.6 + +packages: + + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} + + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [darwin] + + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [darwin] + + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} + cpu: [arm64] + os: [darwin] + + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} + engines: {node: '>=20.9.0'} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} + engines: {node: '>=20.9.0'} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} + engines: {node: '>=20.9.0'} + cpu: [wasm32] + + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} + engines: {node: ^20.9.0} + cpu: [ia32] + os: [win32] + + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [win32] + + '@lydell/node-pty-darwin-arm64@1.2.0-beta.10': + resolution: {integrity: sha512-C+eqDyRNHRYvx7RaHj6VVCx6nCpRBPuuxhTcc3JH3GuBMoxTsYeY4GkWH2XOktrgbAq1BG8e/Y8bu/wNQreCEw==} + cpu: [arm64] + os: [darwin] + + '@lydell/node-pty-darwin-x64@1.2.0-beta.10': + resolution: {integrity: sha512-aZoIK6HtJO5BiT4ELm683U4dyHtt8b7wNgq3NJqYAQwSXrcPv576Z8vY3BIulVxfcFkht/SPLKou9TtdFXdNpg==} + cpu: [x64] + os: [darwin] + + '@lydell/node-pty-linux-arm64@1.2.0-beta.10': + resolution: {integrity: sha512-0cKX2iMyXFNBE4fGtGK6B7IkdXcDMZajyEDoGMOgQQs/DDtoI5tSPcBcqNY9VitVrsRQA8+gFt6eKYU9Ye/lUA==} + cpu: [arm64] + os: [linux] + + '@lydell/node-pty-linux-x64@1.2.0-beta.10': + resolution: {integrity: sha512-J9HnxvSzEeMH748+Ul1VrmCLWMo7iCVJy9EGijRR62+YO/Yk5GaCydUTZ+KzlH0/X5aTrgt5cfiof4vx45tRRg==} + cpu: [x64] + os: [linux] + + '@lydell/node-pty-win32-arm64@1.2.0-beta.10': + resolution: {integrity: sha512-PlDJpJX/pnKyy6OmADKzhf+INZDDnzTBGaI0LT4laVNc6NblZNqUSkCMjLFWbeakeuQp0VG37M49WQSN9FDfeA==} + cpu: [arm64] + os: [win32] + + '@lydell/node-pty-win32-x64@1.2.0-beta.10': + resolution: {integrity: sha512-ExFgWrzyldNAMi45U9PLIOu+g/RatP+f0c/dZxaooifME6yLW32BoHveH26/TtoAjZyJrc2iL0u48pgnR1fzmg==} + cpu: [x64] + os: [win32] + + '@lydell/node-pty@1.2.0-beta.10': + resolution: {integrity: sha512-Fv+A3+MZVA8qhkBIZsM1E6dCdHNMyXXz22mAYiMWd03LlyK///F3OH6CKPX9mj4id7LUlxpr45yPzyBVy9aDPw==} + + '@oven/bun-darwin-aarch64@1.4.4': + resolution: {integrity: sha512-zW/hxwc8sJAILGwB5eTC4i48ouGXf0V4lrxmEOk3JIE6JkYVW1TZh1E2pIempqsezgW1sckTIIDudFON8bJ2Mw==} + cpu: [arm64] + os: [darwin] + + '@oven/bun-darwin-x64@1.4.4': + resolution: {integrity: sha512-oKGcxLsvh4oHjAo28nPm8c/xN0o/OmGyj1IHYc94vprkWsW2hNg2keEZt5f40cI5Hvu4jDlSRTR0UNpv1UIAxw==} + cpu: [x64] + os: [darwin] + + '@oven/bun-linux-aarch64@1.4.4': + resolution: {integrity: sha512-ZTVtpf9zmHSBVPX1sBwe5agGb/rN34yPGg/Hby8e2Ax2uCUA2URZKlZH7qLntK7qaFJCMXh9v0GWNYN2zINz1w==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oven/bun-linux-x64@1.4.4': + resolution: {integrity: sha512-CHbbkmHVM28T1GFq+6GL4Ao4ujwwYwj1CxFFwEFzLanPfNsId9AhbIP0Q4reWuWBkGimUkoQygrK7Rgjtj3vog==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@qwen-code/audio-capture@0.28.7': + resolution: {integrity: sha512-/OrJ8ejhMoWQDaZ/M39jKabeCuce4xEGA+VHDx1bou7lsKyyuiClhXHBZooxNCGOHiThd7LG+5fRUBVPEMJKTg==} + engines: {node: '>=22'} + + '@qwen-code/qwen-code@0.28.7': + resolution: {integrity: sha512-iNbhKkFRjvl3iKsBrTuV8g6FTCc3WOQDeaAeEoeVyipl+M/P0CrzOR6WFXJURbb07zt7WxlJRF/pEmZcEj2ctA==} + engines: {node: '>=22.0.0'} + hasBin: true + + '@teddyzhu/clipboard-darwin-arm64@0.0.5': + resolution: {integrity: sha512-FB3yykRAcw0VLmSjIGFddgew2t20UnLp80NZvi5e/lbsy/3mruHibMHkxHWqzCncuZsHdRsRXS/FmR/ggepW9A==} + engines: {node: '>= 10.16.0 < 11 || >= 11.8.0 < 12 || >= 12.0.0'} + cpu: [arm64] + os: [darwin] + + '@teddyzhu/clipboard-darwin-x64@0.0.5': + resolution: {integrity: sha512-tiDazMpLf2dS7BZUif3da3DLJima8E/CnexB3CNgjQf12CFJ+D1cPcj/CgfvMYZgFQSsYyACpQNfXn4hmVbymA==} + engines: {node: '>= 10.16.0 < 11 || >= 11.8.0 < 12 || >= 12.0.0'} + cpu: [x64] + os: [darwin] + + '@teddyzhu/clipboard-linux-arm64-gnu@0.0.5': + resolution: {integrity: sha512-qcokM+BaXn4iG4o4nYGHdfC04pr54S2F7x2o5osFhG3hMVYHZLR/8NKcYDKELnebpH612nW2bNRoWWy14lM45g==} + engines: {node: '>= 10.16.0 < 11 || >= 11.8.0 < 12 || >= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@teddyzhu/clipboard-linux-x64-gnu@0.0.5': + resolution: {integrity: sha512-Ogh4zYM9s537WJszSvKrPAoKQZ2grnY7Xy6szyJp2+84uQKWNbvZkATODAsRUn48zr9gqL3PZeUqkIBaz8sCpQ==} + engines: {node: '>= 10.16.0 < 11 || >= 11.8.0 < 12 || >= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@teddyzhu/clipboard-win32-arm64-msvc@0.0.5': + resolution: {integrity: sha512-TuU+7e8qYc0T++sIArHTmqr+nfqiTfJ6gdrb1e8yDJb6MM3EFxCd2VonTqLQL1YpUdfcH+/rdMarG2rvCwvEhQ==} + engines: {node: '>= 10.16.0 < 11 || >= 11.8.0 < 12 || >= 12.0.0'} + cpu: [arm64] + os: [win32] + + '@teddyzhu/clipboard-win32-x64-msvc@0.0.5': + resolution: {integrity: sha512-f1Br5bI+INNDifjkOI1woZsIxsoW0rRej/4kaaJvZcMxxkSG9TMT2LYOjTF2g+DtXw32lsGvWICN6c3JiHeG7Q==} + engines: {node: '>= 10.16.0 < 11 || >= 11.8.0 < 12 || >= 12.0.0'} + cpu: [x64] + os: [win32] + + '@teddyzhu/clipboard@0.0.5': + resolution: {integrity: sha512-XA6MG7nLPZzj51agCwDYaVnVVrt0ByJ3G9rl3ar6N4GETAjUKKup6u76SLp2C5yHRWYV9hwMYDn04OGLar0MVg==} + engines: {node: '>= 10.16.0 < 11 || >= 11.8.0 < 12 || >= 12.0.0'} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + node-gyp-build@4.8.4: + resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} + hasBin: true + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} + engines: {node: '>=10'} + hasBin: true + + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} + engines: {node: '>=20.9.0'} + peerDependencies: + '@types/node': '*' + peerDependenciesMeta: + '@types/node': + optional: true + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + tslib@2.9.1: + resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + +snapshots: + + '@emnapi/runtime@1.11.3': + dependencies: + tslib: 2.9.1 + optional: true + + '@img/colour@1.1.0': + optional: true + + '@img/sharp-darwin-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-darwin-arm64': 1.3.4 + optional: true + + '@img/sharp-darwin-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-darwin-x64': 1.3.4 + optional: true + + '@img/sharp-freebsd-wasm32@0.35.5': + dependencies: + '@img/sharp-wasm32': 0.35.5 + optional: true + + '@img/sharp-libvips-darwin-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-darwin-x64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.4': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.4': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + optional: true + + '@img/sharp-linux-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.4 + optional: true + + '@img/sharp-linux-arm@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.4 + optional: true + + '@img/sharp-linux-ppc64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.4 + optional: true + + '@img/sharp-linux-riscv64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.4 + optional: true + + '@img/sharp-linux-s390x@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.4 + optional: true + + '@img/sharp-linux-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + optional: true + + '@img/sharp-wasm32@0.35.5': + dependencies: + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.5': + dependencies: + '@img/sharp-wasm32': 0.35.5 + optional: true + + '@img/sharp-win32-arm64@0.35.5': + optional: true + + '@img/sharp-win32-ia32@0.35.5': + optional: true + + '@img/sharp-win32-x64@0.35.5': + optional: true + + '@lydell/node-pty-darwin-arm64@1.2.0-beta.10': + optional: true + + '@lydell/node-pty-darwin-x64@1.2.0-beta.10': + optional: true + + '@lydell/node-pty-linux-arm64@1.2.0-beta.10': + optional: true + + '@lydell/node-pty-linux-x64@1.2.0-beta.10': + optional: true + + '@lydell/node-pty-win32-arm64@1.2.0-beta.10': + optional: true + + '@lydell/node-pty-win32-x64@1.2.0-beta.10': + optional: true + + '@lydell/node-pty@1.2.0-beta.10': + optionalDependencies: + '@lydell/node-pty-darwin-arm64': 1.2.0-beta.10 + '@lydell/node-pty-darwin-x64': 1.2.0-beta.10 + '@lydell/node-pty-linux-arm64': 1.2.0-beta.10 + '@lydell/node-pty-linux-x64': 1.2.0-beta.10 + '@lydell/node-pty-win32-arm64': 1.2.0-beta.10 + '@lydell/node-pty-win32-x64': 1.2.0-beta.10 + optional: true + + '@oven/bun-darwin-aarch64@1.4.4': + optional: true + + '@oven/bun-darwin-x64@1.4.4': + optional: true + + '@oven/bun-linux-aarch64@1.4.4': + optional: true + + '@oven/bun-linux-x64@1.4.4': + optional: true + + '@qwen-code/audio-capture@0.28.7': + dependencies: + node-gyp-build: 4.8.4 + optional: true + + '@qwen-code/qwen-code@0.28.7': + optionalDependencies: + '@lydell/node-pty': 1.2.0-beta.10 + '@lydell/node-pty-darwin-arm64': 1.2.0-beta.10 + '@lydell/node-pty-darwin-x64': 1.2.0-beta.10 + '@lydell/node-pty-linux-arm64': 1.2.0-beta.10 + '@lydell/node-pty-linux-x64': 1.2.0-beta.10 + '@lydell/node-pty-win32-arm64': 1.2.0-beta.10 + '@lydell/node-pty-win32-x64': 1.2.0-beta.10 + '@oven/bun-darwin-aarch64': 1.4.4 + '@oven/bun-darwin-x64': 1.4.4 + '@oven/bun-linux-aarch64': 1.4.4 + '@oven/bun-linux-x64': 1.4.4 + '@qwen-code/audio-capture': 0.28.7 + '@teddyzhu/clipboard': 0.0.5 + '@teddyzhu/clipboard-darwin-arm64': 0.0.5 + '@teddyzhu/clipboard-darwin-x64': 0.0.5 + '@teddyzhu/clipboard-linux-arm64-gnu': 0.0.5 + '@teddyzhu/clipboard-linux-x64-gnu': 0.0.5 + '@teddyzhu/clipboard-win32-arm64-msvc': 0.0.5 + '@teddyzhu/clipboard-win32-x64-msvc': 0.0.5 + sharp: 0.35.5 + transitivePeerDependencies: + - '@types/node' + + '@teddyzhu/clipboard-darwin-arm64@0.0.5': + optional: true + + '@teddyzhu/clipboard-darwin-x64@0.0.5': + optional: true + + '@teddyzhu/clipboard-linux-arm64-gnu@0.0.5': + optional: true + + '@teddyzhu/clipboard-linux-x64-gnu@0.0.5': + optional: true + + '@teddyzhu/clipboard-win32-arm64-msvc@0.0.5': + optional: true + + '@teddyzhu/clipboard-win32-x64-msvc@0.0.5': + optional: true + + '@teddyzhu/clipboard@0.0.5': + optionalDependencies: + '@teddyzhu/clipboard-darwin-arm64': 0.0.5 + '@teddyzhu/clipboard-darwin-x64': 0.0.5 + '@teddyzhu/clipboard-linux-arm64-gnu': 0.0.5 + '@teddyzhu/clipboard-linux-x64-gnu': 0.0.5 + '@teddyzhu/clipboard-win32-arm64-msvc': 0.0.5 + '@teddyzhu/clipboard-win32-x64-msvc': 0.0.5 + optional: true + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + detect-libc@2.1.2: + optional: true + + isexe@2.0.0: {} + + node-gyp-build@4.8.4: + optional: true + + path-key@3.1.1: {} + + semver@7.8.6: + optional: true + + sharp@0.35.5: + dependencies: + '@img/colour': 1.1.0 + detect-libc: 2.1.2 + semver: 7.8.6 + optionalDependencies: + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 + optional: true + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + tslib@2.9.1: + optional: true + + which@2.0.2: + dependencies: + isexe: 2.0.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..ed04b12 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +# Qwen Code's optional voice-input add-on ships prebuilt binaries; its install script is not run. +allowBuilds: + '@qwen-code/audio-capture': false diff --git a/scripts/check.mjs b/scripts/check.mjs new file mode 100644 index 0000000..7ecdc45 --- /dev/null +++ b/scripts/check.mjs @@ -0,0 +1,29 @@ +// The repo's whole check, the same on macOS, Linux and Windows: a syntax pass over every +// module, then the test suite (fake gcloud, fake Google APIs, fake Ollama; nothing reaches Google). +// pnpm check +import { readdirSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const files = []; +const walk = (dir) => { + for (const e of readdirSync(join(root, dir), { withFileTypes: true })) { + const p = join(dir, e.name); + if (e.isDirectory() && e.name !== "tmp") walk(p); + else if (e.name.endsWith(".mjs")) files.push(p); + } +}; +["bin", "src", "scripts", "tests"].forEach(walk); + +let bad = 0; +for (const f of files) { + const r = spawnSync(process.execPath, ["--check", join(root, f)], { stdio: "inherit" }); + if (r.status !== 0) bad++; +} +console.log(`syntax: ${files.length - bad}/${files.length} files ok`); +if (bad) process.exit(1); + +const t = spawnSync(process.execPath, ["--test", "--test-concurrency=1", "--test-force-exit", "--test-timeout=300000", "tests/*.test.mjs"], { stdio: "inherit", cwd: root }); +process.exit(t.status ?? 1); diff --git a/src/cloud.mjs b/src/cloud.mjs new file mode 100644 index 0000000..d904b5f --- /dev/null +++ b/src/cloud.mjs @@ -0,0 +1,128 @@ +// Google Cloud through the gcloud CLI: login and project checks, deploy, delete. gcloud does all +// the signing in (`gcloud auth login`); runcoder keeps no credentials of its own. + +import { run, sleep } from "./proc.mjs"; +import { say, warn, die, log } from "./ui.mjs"; + +export function gcloud(s, args, opts) { + const project = s.project ? [`--project=${s.project}`] : []; + return run("gcloud", [...project, "--quiet", ...args], opts).then((r) => { + if (r.stderr.trim()) log(`gcloud ${args.slice(0, 4).join(" ")}: ${r.stderr.trim().slice(-2000)}`); + return r; + }); +} + +export async function gcloudInstalled() { + try { + return (await run("gcloud", ["--version"])).code === 0; + } catch { + return false; + } +} +export async function account() { + const r = await run("gcloud", ["auth", "list", "--filter=status:ACTIVE", "--format=value(account)"]).catch(() => ({ stdout: "" })); + return r.stdout.trim().split(/\r?\n/)[0] || ""; +} +export async function accessToken() { + const r = await run("gcloud", ["auth", "print-access-token"]).catch(() => ({ code: 1, stdout: "" })); + return r.code === 0 ? r.stdout.trim() : ""; +} +export async function apiEnabled(s, api) { + const r = await gcloud(s, ["services", "list", "--enabled", `--filter=config.name=${api}`, "--format=value(config.name)"]); + return r.code === 0 && r.stdout.includes(api); +} + +// The regions where the service exists. Throws if Cloud Run cannot be listed, so a network or +// login problem is never mistaken for "nothing is running". +export async function serviceRegions(s) { + const found = []; + for (const region of s.regions) { + const r = await gcloud(s, ["run", "services", "list", `--region=${region}`, "--format=value(metadata.name)"]); + if (r.code !== 0) throw new Error(`could not list Cloud Run services in ${region}`); + if (r.stdout.split(/\r?\n/).some((l) => l.trim() === s.service)) found.push(region); + } + return found; +} + +// Deletes the service in every region and confirms it is gone. Returns false if that cannot be confirmed. +export async function deleteEverything(s) { + for (let attempt = 1; attempt <= 5; attempt++) { + let regions; + try { + regions = await serviceRegions(s); + } catch { + warn(`Could not list Cloud Run services (attempt ${attempt} of 5); retrying.`); + await sleep(10); + continue; + } + if (!regions.length) return true; + for (const region of regions) { + say(`Deleting ${s.service} in ${region}...`); + const r = await gcloud(s, ["run", "services", "delete", s.service, `--region=${region}`]); + if (r.code !== 0) { + warn(`Delete in ${region} failed (attempt ${attempt} of 5); retrying.`); // e.g. a deploy still in progress + await sleep(10); + } + } + } + try { + return (await serviceRegions(s)).length === 0; + } catch { + return false; + } +} + +export async function activeInstances(s) { + const token = await accessToken(); + if (!token) return "unknown"; + const end = new Date(); + const q = new URLSearchParams({ + filter: `metric.type="run.googleapis.com/container/instance_count" AND resource.labels.service_name="${s.service}" AND metric.labels.state="active"`, + "interval.startTime": new Date(end - 180e3).toISOString(), + "interval.endTime": end.toISOString(), + }); + try { + const res = await fetch(`${s.monitoringApi}/v3/projects/${s.project}/timeSeries?${q}`, { + headers: { Authorization: `Bearer ${token}` }, + signal: AbortSignal.timeout(20000), + }); + const body = await res.json(); + return String(body.timeSeries?.[0]?.points?.[0]?.value?.int64Value ?? 0); + } catch { + return "unknown"; + } +} + +export async function preflight(s) { + if (!s.project) die("No Google Cloud project is set. Run: runcoder setup"); + if (!(await gcloudInstalled())) die("gcloud (the Google Cloud CLI) is not installed: https://cloud.google.com/sdk/docs/install"); + if (!(await account())) die("gcloud is not logged in. Run: gcloud auth login"); + const r = await gcloud(s, ["projects", "describe", s.project, "--format=value(projectId)"]); + if (r.code !== 0) die(`The current gcloud login cannot open project ${s.project}. Run: runcoder setup`); + if (!(await apiEnabled(s, "run.googleapis.com"))) die(`The Cloud Run API is off in ${s.project}. Run: runcoder setup`); +} + +// Starts the GPU service, trying each region in turn. Returns the region it runs in. +export async function deploy(s, onAttempt) { + for (const region of s.regions) { + say(`Starting the GPU server in ${region} (takes 1-2 minutes)...`); + onAttempt(region); + const r = await gcloud(s, [ + "run", "deploy", s.service, `--region=${region}`, `--image=${s.image}`, + `--cpu=${s.cpu}`, `--memory=${s.memory}`, "--gpu=1", `--gpu-type=${s.gpu}`, "--no-gpu-zonal-redundancy", + "--no-cpu-throttling", "--min-instances=0", "--max-instances=1", "--concurrency=4", "--timeout=3600", + "--no-allow-unauthenticated", "--labels=managed-by=runcoder", + `--set-env-vars=OLLAMA_HOST=0.0.0.0:8080,OLLAMA_KEEP_ALIVE=-1,OLLAMA_CONTEXT_LENGTH=${s.context},OLLAMA_NUM_PARALLEL=1`, + "--command=bash", + `--args=-c,ollama serve & sleep 5; until ollama pull ${s.model}; do sleep 10; done; wait`, + ]); + if (r.code === 0) { + say(`GPU server is up in ${region}.`); + return region; + } + const err = r.stderr.split(/\r?\n/).filter((l) => l.includes("ERROR")).pop() || r.stderr.trim().split(/\r?\n/).pop() || ""; + warn(`Could not start in ${region}: ${err.slice(0, 220)}`); + await gcloud(s, ["run", "services", "delete", s.service, `--region=${region}`]); + } + die(`Could not start the GPU server in any of: ${s.regions.join(" ")}.`); +} diff --git a/src/config.mjs b/src/config.mjs new file mode 100644 index 0000000..5aca70e --- /dev/null +++ b/src/config.mjs @@ -0,0 +1,100 @@ +// Settings, folders and the config file. +// +// Every setting is a RUNCODER_* variable. The config file (written by `runcoder setup`) holds +// KEY=value lines and is read as data, never run. A variable set in the environment wins over the +// file, so `RUNCODER_MAX_MINUTES=60 runcoder` changes one run. + +import { readFileSync, mkdirSync, writeFileSync, renameSync, existsSync } from "node:fs"; +import { homedir } from "node:os"; +import { join, dirname } from "node:path"; + +const env = process.env; +const home = homedir(); +const windows = process.platform === "win32"; + +// Folders: XDG on macOS and Linux (and anywhere the XDG variables are set); on Windows the config +// is in %APPDATA%\runcoder and the rest in %LOCALAPPDATA%\runcoder. +const local = env.LOCALAPPDATA || join(home, "AppData", "Local"); +const xdg = (v, unix, win) => (env[v] ? join(env[v], "runcoder") : windows ? win : join(home, ...unix, "runcoder")); +export const paths = { + configFile: env.RUNCODER_CONFIG || join(xdg("XDG_CONFIG_HOME", [".config"], join(env.APPDATA || join(home, "AppData", "Roaming"), "runcoder")), "config"), + state: xdg("XDG_STATE_HOME", [".local", "state"], join(local, "runcoder", "state")), // lock, logs, price cache, Qwen Code launcher + data: xdg("XDG_DATA_HOME", [".local", "share"], join(local, "runcoder", "data")), // Qwen Code's settings and saved sessions +}; +paths.logs = join(paths.state, "logs"); +paths.lock = join(paths.state, "lock"); +paths.qwenPid = join(paths.state, "qwen.pid"); +paths.proxyPid = join(paths.state, "proxy.pid"); +paths.qwenHome = join(paths.data, "qwen-home"); + +export function readConfigFile(file = paths.configFile) { + const values = {}; + let text = ""; + try { + text = readFileSync(file, "utf8"); + } catch { + return values; + } + for (const line of text.split(/\r?\n/)) { + const m = line.match(/^\s*(RUNCODER_[A-Z0-9_]+)=(.*)$/); + if (!m) continue; + let v = m[2].replace(/\s+#.*$/, "").trim(); + const q = v.match(/^"(.*)"$|^'(.*)'$/); + if (q) v = q[1] ?? q[2]; + values[m[1]] = v; + } + return values; +} + +export const configExists = () => existsSync(paths.configFile); + +// Writes the setup values, keeping any other RUNCODER_* lines the user added. +export function writeConfigFile(values, file = paths.configFile) { + const keep = Object.entries(readConfigFile(file)).filter(([k]) => !(k in values)); + const lines = [ + `# runcoder settings, written by runcoder setup on ${new Date().toISOString().slice(0, 10)}. Any RUNCODER_* setting`, + "# can go here; see the README for the list. Lines are KEY=value; nothing here is run as code.", + ...Object.entries(values).map(([k, v]) => `${k}=${v}`), + ...keep.map(([k, v]) => `${k}=${v}`), + ]; + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(`${file}.new`, lines.join("\n") + "\n"); + renameSync(`${file}.new`, file); +} + +export function loadSettings() { + const file = readConfigFile(); + const get = (k, d) => env[`RUNCODER_${k}`] ?? file[`RUNCODER_${k}`] ?? d; + const num = (k, d) => { + const v = Number(get(k, d)); + if (!Number.isFinite(v)) throw new Error(`RUNCODER_${k} must be a number`); + return v; + }; + const s = { + project: get("PROJECT", ""), // Google Cloud project (runcoder setup asks) + regions: get("REGIONS", "us-central1 europe-west4").split(/\s+/).filter(Boolean), // tried in order + service: get("SERVICE", "runcoder"), // Cloud Run service name + model: get("MODEL", "qwen3.8:27b-q8_0"), // any Ollama model that fits the GPU + context: num("CONTEXT", 131072), // tokens + gpu: get("GPU", "nvidia-rtx-pro-6000"), // Cloud Run GPU type: nvidia-rtx-pro-6000 or nvidia-l4 + cpu: num("CPU", 20), // vCPU; Cloud Run ties the memory range to it + memory: get("MEMORY", "80Gi"), + image: get("IMAGE", "ollama/ollama:0.40.19"), + port: num("PORT", 11435), // local end of the private tunnel + maxMinutes: num("MAX_MINUTES", 150), // hard stop for one session + qwenIdleMinutes: num("QWEN_IDLE_MINUTES", 15), // shut down this long after Qwen Code closes + pullTimeoutMinutes: num("PULL_TIMEOUT_MINUTES", 45), + open: get("OPEN", "auto"), // auto | none (print the command instead) + tick: num("TICK", 30), // seconds between keep-alive checks + monthlyCredit: num("MONTHLY_CREDIT", 0), // monthly Google Cloud credit to track; 0 = off + currency: get("CURRENCY", "USD"), // the billing account's currency (setup detects it) + freeTier: get("FREE_TIER", "1") !== "0", // off if other Cloud Run use on the account takes it + allowPaid: get("ALLOW_PAID", "0") === "1", // lets a run without a keyboard go past the credit + // For tests: where Google's APIs are, and keys typed through a pipe count as a keyboard. + monitoringApi: get("MONITORING_API", "https://monitoring.googleapis.com"), + billingApi: get("BILLING_API", "https://cloudbilling.googleapis.com"), + interactive: process.stdin.isTTY === true || env.RUNCODER_INTERACTIVE === "1", + }; + s.baseUrl = `http://localhost:${s.port}`; + return s; +} diff --git a/src/cost.mjs b/src/cost.mjs new file mode 100644 index 0000000..845f2a6 --- /dev/null +++ b/src/cost.mjs @@ -0,0 +1,217 @@ +// Cost and credit from Google's own numbers. +// +// Usage: Cloud Monitoring's run.googleapis.com/container/billable_instance_time for the service, +// the time Google bills, per revision (one per run), a few minutes behind. The running session is +// added from its own clock, which slightly overcounts the deploy. +// Prices: Google's price list (Cloud Billing catalog) in the billing account's currency, cached for +// a week in the state folder. +// Free tier: Cloud Run takes 240,000 vCPU-seconds and 450,000 GiB-seconds a month off the CPU and +// memory charge, as a spend discount at Tier 1 (us-central1) prices, shared by the billing account. +// GPUs have no free tier. Billing months follow Pacific time. + +import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { join } from "node:path"; +import { paths } from "./config.mjs"; +import { accessToken } from "./cloud.mjs"; +import { warn, log } from "./ui.mjs"; + +const WEEK = 7 * 24 * 3600 * 1000; +const FREE_VCPU_SECONDS = 240000; +const FREE_GIB_SECONDS = 450000; +const RUN_SERVICE_ID = "152E-C115-5142"; // Cloud Run in the billing catalog +// The price list's name for each Cloud Run GPU type (runcoder deploys without zonal redundancy). +const GPU_SKU = { "nvidia-rtx-pro-6000": "NVIDIA RTX Pro 6000 GPU", "nvidia-l4": "NVIDIA L4 GPU" }; + +export function parseMemory(m) { + const n = parseFloat(m); + if (/Mi$/.test(m)) return n / 1024; + if (/G$/.test(m)) return (n * 1e9) / 2 ** 30; + return n; // Gi +} + +async function getJson(url, token) { + const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(30000) }); + if (!res.ok) throw new Error(`${res.status} ${(await res.text()).slice(0, 200)}`); + return res.json(); +} + +function unitPrice(sku) { + const tiers = sku.pricingInfo?.[0]?.pricingExpression?.tieredRates || []; + const t = tiers.find((r) => !r.startUsageAmount) || tiers[0]; + if (!t) return undefined; + return Number(t.unitPrice.units || 0) + (t.unitPrice.nanos || 0) / 1e9; +} + +async function fetchPrices(s, regions, token) { + const gpuName = GPU_SKU[s.gpu]; + if (!gpuName) throw new Error(`no price list name known for GPU type ${s.gpu}`); + const found = {}; + let pageToken = ""; + do { + const q = new URLSearchParams({ currencyCode: s.currency, pageSize: "5000" }); + if (pageToken) q.set("pageToken", pageToken); + const page = await getJson(`${s.billingApi}/v1/services/${RUN_SERVICE_ID}/skus?${q}`, token); + for (const sku of page.skus || []) { + const d = sku.description || ""; + for (const r of regions) { + if (!d.endsWith(` in ${r}`)) continue; + const p = (found[r] ||= {}); + if (d.startsWith(`${gpuName} with no zonal redundancy`)) p.gpu = unitPrice(sku); + else if (d.startsWith("Services CPU (Instance-based billing)")) p.cpu = unitPrice(sku); + else if (d.startsWith("Services Memory (Instance-based billing)")) p.mem = unitPrice(sku); + } + } + pageToken = page.nextPageToken || ""; + } while (pageToken); + for (const r of regions) { + const p = found[r]; + if (!p || !(p.gpu > 0 && p.cpu > 0 && p.mem > 0)) throw new Error(`the price list has no ${s.gpu} prices for ${r}`); + } + return { currency: s.currency, gpu: s.gpu, fetched: new Date().toISOString(), regions: found }; +} + +async function prices(s, regions, token) { + const file = join(paths.state, `prices-${s.currency}-${s.gpu}.json`); + let cache; + try { + cache = JSON.parse(readFileSync(file, "utf8")); + } catch {} + const usable = cache && regions.every((r) => cache.regions?.[r]); + const label = (c, extra = "") => `Google's price list of ${c.fetched.slice(0, 10)}${extra}`; + if (usable && Date.now() - Date.parse(cache.fetched) < WEEK) return [cache, label(cache)]; + try { + const live = await fetchPrices(s, regions, token); + mkdirSync(paths.state, { recursive: true }); + writeFileSync(file, JSON.stringify(live, null, 1)); + return [live, label(live)]; + } catch (e) { + log(`price list: ${e.message}`); + if (usable) return [cache, label(cache, " (could not refresh it)")]; + return [undefined, "unknown (Google's price list could not be read)"]; + } +} + +// Start of the current billing month: midnight Pacific time on the 1st. +export function monthStart(now = new Date()) { + const la = (opts, d) => new Intl.DateTimeFormat("en-US", { timeZone: "America/Los_Angeles", ...opts }).formatToParts(d); + const parts = Object.fromEntries(la({ year: "numeric", month: "2-digit" }, now).map((p) => [p.type, p.value])); + const y = Number(parts.year); + const m = Number(parts.month); + const label = `${y}-${String(m).padStart(2, "0")}`; + for (const offset of [8, 7]) { + const d = new Date(Date.UTC(y, m - 1, 1, offset)); + const hour = la({ hour: "numeric", hourCycle: "h23" }, d).find((p) => p.type === "hour").value; + if (Number(hour) === 0) return [d, label]; + } + return [new Date(Date.UTC(y, m - 1, 1, 8)), label]; +} + +// Billable seconds per run this month: [{region, start, seconds}], oldest first. +async function billedRuns(s, start, end, token) { + const filter = `metric.type="run.googleapis.com/container/billable_instance_time" AND resource.labels.service_name="${s.service}"`; + const byRun = new Map(); + let pageToken = ""; + do { + const q = new URLSearchParams({ + filter, + "interval.startTime": start.toISOString(), + "interval.endTime": end.toISOString(), + "aggregation.alignmentPeriod": "300s", + "aggregation.perSeriesAligner": "ALIGN_SUM", + }); + if (pageToken) q.set("pageToken", pageToken); + const page = await getJson(`${s.monitoringApi}/v3/projects/${s.project}/timeSeries?${q}`, token); + for (const ts of page.timeSeries || []) { + const region = ts.resource?.labels?.location || "?"; + const key = `${region}/${ts.resource?.labels?.revision_name || "?"}`; + const run = byRun.get(key) || { region, start: Infinity, seconds: 0 }; + for (const p of ts.points || []) { + const v = Number(p.value?.doubleValue ?? p.value?.int64Value ?? 0); + if (!(v > 0)) continue; + run.seconds += v; + run.start = Math.min(run.start, Date.parse(p.interval.endTime) - v * 1000); + } + byRun.set(key, run); + } + pageToken = page.nextPageToken || ""; + } while (pageToken); + return [...byRun.values()].filter((r) => r.seconds > 0).sort((a, b) => a.start - b.start); +} + +const round2 = (x) => Math.round(x * 100) / 100; + +// The month so far and the rates for `region`. Never throws; pricesOk / usageOk say what is known. +export async function loadCost(s, region = s.regions[0]) { + const regions = [...new Set(["us-central1", ...s.regions])]; // us-central1 prices the free tier + const token = await accessToken(); + const [list, source] = await prices(s, regions, token); + const [start, month] = monthStart(); + let symbol = s.currency; + try { + symbol = new Intl.NumberFormat("en-US", { style: "currency", currency: s.currency }).formatToParts(0).find((p) => p.type === "currency").value; + } catch {} + const c = { month, symbol, prices: source, pricesOk: !!list, usageOk: false, monthCost: 0, freeLeft: 0, gpuPerS: 0, cpumemPerS: 0, sessions: [], credit: s.monthlyCredit }; + if (!list) { + warn("Could not read Google's price list, so costs are unknown (details in the log)."); + return c; + } + const gib = parseMemory(s.memory); + const rate = (r) => list.regions[r] || list.regions["us-central1"]; + const cpumem = (p) => s.cpu * p.cpu + gib * p.mem; + const tier1 = list.regions["us-central1"]; + c.gpuPerS = rate(region).gpu; + c.cpumemPerS = cpumem(rate(region)); + c.freeLeft = s.freeTier ? FREE_VCPU_SECONDS * tier1.cpu + FREE_GIB_SECONDS * tier1.mem : 0; + try { + if (!s.project) throw new Error("no project set"); + for (const r of await billedRuns(s, start, new Date(), token)) { + const p = rate(r.region); + const cm = r.seconds * cpumem(p); + const covered = Math.min(cm, c.freeLeft); + c.freeLeft -= covered; + const cost = r.seconds * p.gpu + cm - covered; + c.monthCost += cost; + c.sessions.push({ start: new Date(r.start), region: r.region, minutes: r.seconds / 60, cost }); + } + c.usageOk = true; + } catch (e) { + log(`cloud monitoring: ${e.message}`); + warn("Could not read this month's billed time from Cloud Monitoring, so the credit left is unknown (details in the log)."); + } + return c; +} + +// ---------------------------------------------------------------- figures for the messages +export const money = (c, x) => (c.pricesOk ? `${c.symbol}${round2(x).toFixed(2)}` : "an unknown amount"); +// Cost of `seconds` of this run: the GPU always, CPU and memory only past the free tier left. +export const sessionCost = (c, seconds) => seconds * c.gpuPerS + Math.max(0, seconds * c.cpumemPerS - c.freeLeft); +export const fullRate = (c) => (c.gpuPerS + c.cpumemPerS) * 3600; +export function rateLine(c, seconds = 0) { + if (!c.pricesOk) return "an unknown hourly rate (no price list)"; + const left = c.freeLeft - seconds * c.cpumemPerS; + if (left > 0) { + return `${c.symbol}${(c.gpuPerS * 3600).toFixed(2)} per hour while Cloud Run's free CPU and memory last (about ${Math.floor(left / c.cpumemPerS / 60)} more minutes), then ${c.symbol}${fullRate(c).toFixed(2)}`; + } + return `${c.symbol}${fullRate(c).toFixed(2)} per hour`; +} +export const costKnown = (c) => c.pricesOk && c.usageOk; +export const monthUsed = (c, seconds = 0) => round2(c.monthCost) + round2(sessionCost(c, seconds)); +export const creditLeft = (c, seconds = 0) => c.credit - monthUsed(c, seconds); +export function minutesLeft(c, seconds = 0) { + const left = creditLeft(c, seconds); + const free = Math.max(0, c.freeLeft - seconds * c.cpumemPerS); + const fs = free / c.cpumemPerS; + const t = left <= c.gpuPerS * fs ? left / c.gpuPerS : fs + (left - c.gpuPerS * fs) / (c.gpuPerS + c.cpumemPerS); + return Math.max(0, Math.floor(t / 60)); +} +export const creditEnabled = (c) => c.credit > 0; +export const creditUsedUp = (c, seconds = 0) => creditEnabled(c) && costKnown(c) && creditLeft(c, seconds) <= 0; +export function creditLine(c, seconds = 0) { + if (!costKnown(c)) return "Credit left this month: unknown (see the warning above). Check Billing > Credits in the Cloud console."; + const used = money(c, monthUsed(c, seconds)); + const left = creditLeft(c, seconds); + if (left > 0) { + return `Credit left this month: about ${money(c, left)} of ${money(c, c.credit)} (${used} billed to runcoder, about ${minutesLeft(c, seconds)} more GPU minutes).`; + } + return `Credit this month looks USED UP: ${used} billed to runcoder against ${money(c, c.credit)}. Further use is charged to your card.`; +} diff --git a/src/proc.mjs b/src/proc.mjs new file mode 100644 index 0000000..ea7ab0d --- /dev/null +++ b/src/proc.mjs @@ -0,0 +1,88 @@ +// Running other programs the same way on macOS, Linux and Windows. cross-spawn finds gcloud.cmd +// and npm-style shims on Windows and quotes arguments for them safely. + +import spawn from "cross-spawn"; + +// Runs a program to the end: { code, stdout, stderr }. Never throws for a non-zero exit; rejects +// only if the program cannot be started (for example it is not installed). +export function run(cmd, args = [], { timeoutSeconds = 0, env, cwd, stdio } = {}) { + return new Promise((resolve, reject) => { + let child; + try { + child = spawn(cmd, args, { env: env ?? process.env, cwd, stdio: stdio ?? ["ignore", "pipe", "pipe"], windowsHide: true }); + } catch (e) { + return reject(e); + } + let stdout = ""; + let stderr = ""; + child.stdout?.on("data", (d) => (stdout += d)); + child.stderr?.on("data", (d) => (stderr += d)); + const timer = timeoutSeconds ? setTimeout(() => killTree(child.pid), timeoutSeconds * 1000) : null; + child.on("error", (e) => { + if (timer) clearTimeout(timer); + reject(e); + }); + child.on("close", (code, signal) => { + if (timer) clearTimeout(timer); + resolve({ code: code ?? (signal ? 1 : 0), stdout, stderr }); + }); + }); +} + +// Starts a program in the background; returns the child process. +export function start(cmd, args = [], { env, cwd, detached = false, stdio } = {}) { + const child = spawn(cmd, args, { env: env ?? process.env, cwd, detached, stdio: stdio ?? "ignore", windowsHide: !detached }); + child.on("error", () => {}); + return child; +} + +export async function has(cmd) { + try { + const probe = process.platform === "win32" ? await run("where", [cmd]) : await run("sh", ["-c", `command -v "$1"`, "sh", cmd]); + return probe.code === 0; + } catch { + return false; + } +} + +export function alive(pid) { + if (!pid) return false; + try { + process.kill(pid, 0); + return true; + } catch (e) { + return e.code === "EPERM"; + } +} + +// The command line of a running process, or "" (used to check a PID before killing it). +export async function commandOf(pid) { + try { + if (process.platform === "win32") { + const r = await run("powershell.exe", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`]); + return r.stdout.trim(); + } + return (await run("ps", ["-p", String(pid), "-o", "command="])).stdout.trim(); + } catch { + return ""; + } +} + +// Ends a process and everything it started. +export function killTree(pid) { + if (!pid) return; + if (process.platform === "win32") { + try { + spawn.sync("taskkill", ["/pid", String(pid), "/t", "/f"], { stdio: "ignore", windowsHide: true }); + } catch {} + return; + } + try { + process.kill(-pid, "SIGTERM"); // the process group, when it leads one + } catch {} + try { + process.kill(pid, "SIGTERM"); + } catch {} +} + +export const sleep = (seconds) => new Promise((r) => setTimeout(r, seconds * 1000)); diff --git a/src/qwen-window.mjs b/src/qwen-window.mjs new file mode 100644 index 0000000..0a30edd --- /dev/null +++ b/src/qwen-window.mjs @@ -0,0 +1,15 @@ +// Runs in Qwen Code's own terminal window: records this process's ID for runcoder, then runs +// Qwen Code in the project folder and passes its exit code on. Started by runcoder; not a command. + +import { readFileSync, writeFileSync } from "node:fs"; +import { spawn } from "node:child_process"; + +const job = JSON.parse(readFileSync(process.argv[2], "utf8")); +writeFileSync(job.pidFile, String(process.pid)); +const child = spawn(process.execPath, [job.entry, ...job.args], { cwd: job.cwd, env: { ...process.env, ...job.env }, stdio: "inherit" }); +for (const sig of ["SIGTERM", "SIGHUP", "SIGINT"]) { + process.on(sig, () => { + if (sig !== "SIGINT") child.kill(sig); // Ctrl+C belongs to Qwen Code itself + }); +} +child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0))); diff --git a/src/qwen.mjs b/src/qwen.mjs new file mode 100644 index 0000000..6b41ba9 --- /dev/null +++ b/src/qwen.mjs @@ -0,0 +1,111 @@ +// Qwen Code: its settings, saved sessions, and its own terminal window. + +import { mkdirSync, writeFileSync, readFileSync, rmSync, chmodSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { paths } from "./config.mjs"; +import { run, start, alive, commandOf, killTree, has } from "./proc.mjs"; +import { say, log } from "./ui.mjs"; + +const require = createRequire(import.meta.url); +const here = dirname(fileURLToPath(import.meta.url)); + +// Qwen Code's command-line entry, installed with runcoder as an npm dependency. +export function qwenEntry() { + const pkgFile = require.resolve("@qwen-code/qwen-code/package.json"); + const pkg = JSON.parse(readFileSync(pkgFile, "utf8")); + const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin.qwen || Object.values(pkg.bin)[0]; + return join(dirname(pkgFile), bin); +} + +const qwenEnv = (s) => ({ ...process.env, QWEN_HOME: paths.qwenHome, OPENAI_API_KEY: "ollama", OPENAI_BASE_URL: `${s.baseUrl}/v1`, OPENAI_MODEL: s.model }); + +export function writeQwenSettings(s) { + mkdirSync(paths.qwenHome, { recursive: true }); + const settings = { + modelProviders: { + openai: [{ id: s.model, name: `${s.model} on Cloud Run`, baseUrl: `${s.baseUrl}/v1`, envKey: "OPENAI_API_KEY", generationConfig: { contextWindowSize: s.context, timeout: 600000 } }], + }, + security: { auth: { selectedType: "openai" } }, + model: { name: s.model }, + privacy: { usageStatisticsEnabled: false }, + telemetry: { enabled: false }, + }; + writeFileSync(join(paths.qwenHome, "settings.json"), JSON.stringify(settings, null, 2)); +} + +// Earlier Qwen Code sessions for the folder, newest first: [{ id, label }]. +export async function qwenSessions(s, workdir) { + const r = await run(process.execPath, [qwenEntry(), "sessions", "list"], { cwd: workdir, env: qwenEnv(s), timeoutSeconds: 60 }).catch(() => ({ stdout: "" })); + return r.stdout + .split(/\r?\n/) + .filter((l) => /^[0-9a-f]{8}-[0-9a-f]{4}-/.test(l)) + .map((l) => { + const [id, ...rest] = l.trim().split(/\s+/); + return { id, label: rest.join(" ") }; + }) + .sort((a, b) => (a.label < b.label ? 1 : -1)); +} + +// The window opens `node qwen-window.mjs `; that small program records its PID, so +// runcoder can tell when Qwen Code was closed, and runs Qwen Code in the folder. +export function openQwen(s, workdir, mode = "") { + rmSync(paths.qwenPid, { force: true }); + const job = join(paths.state, "qwen-window.json"); + writeFileSync(job, JSON.stringify({ entry: qwenEntry(), cwd: workdir, env: { QWEN_HOME: paths.qwenHome, OPENAI_API_KEY: "ollama", OPENAI_BASE_URL: `${s.baseUrl}/v1`, OPENAI_MODEL: s.model }, args: mode ? [mode] : [], pidFile: paths.qwenPid })); + const cmd = [process.execPath, join(here, "qwen-window.mjs"), job]; + const quoted = cmd.map((a) => `'${a.replace(/'/g, `'\\''`)}'`).join(" "); + const launcher = join(paths.state, process.platform === "win32" ? "qwen-session.cmd" : "qwen-session.command"); + if (process.platform === "win32") writeFileSync(launcher, `@echo off\r\n"${cmd[0]}" "${cmd[1]}" "${cmd[2]}"\r\n`); + else { + writeFileSync(launcher, `#!/bin/sh\n# Written by runcoder for one session.\nexec ${quoted}\n`); + chmodSync(launcher, 0o755); + } + return launchWindow(s, launcher, workdir); +} + +async function launchWindow(s, launcher, workdir) { + if (s.open === "auto") { + const opened = async () => { + if (process.platform === "darwin") return (await run("open", ["-a", "Terminal", launcher])).code === 0; + if (process.platform === "win32") { + start("cmd.exe", ["/d", "/c", "start", "Qwen Code", "cmd.exe", "/k", launcher], { detached: true }); + return true; + } + for (const [term, args] of [["x-terminal-emulator", ["-e", launcher]], ["gnome-terminal", ["--", launcher]], ["konsole", ["-e", launcher]], ["xterm", ["-e", launcher]]]) { + if (await has(term)) { + start(term, args, { detached: true }).unref(); + return true; + } + } + return false; + }; + try { + if (await opened()) { + say(`Qwen Code is opening in a new terminal window, in ${workdir}.`); + return; + } + } catch (e) { + log(`opening a terminal: ${e.message}`); + } + } + say(`Open Qwen Code yourself in another terminal with: ${launcher}`); +} + +const qwenPid = () => { + try { + return Number(readFileSync(paths.qwenPid, "utf8")); + } catch { + return 0; + } +}; +export const qwenAlive = () => alive(qwenPid()); +export async function stopQwen() { + const pid = qwenPid(); + if (pid && alive(pid) && (await commandOf(pid)).includes("qwen-window")) { + killTree(pid); + say("Closed Qwen Code."); + } + rmSync(paths.qwenPid, { force: true }); +} diff --git a/src/session.mjs b/src/session.mjs new file mode 100644 index 0000000..a36a154 --- /dev/null +++ b/src/session.mjs @@ -0,0 +1,291 @@ +// One run from start to delete, plus status, credit and down. + +import { mkdirSync, readFileSync, writeFileSync, rmSync, statSync, realpathSync } from "node:fs"; +import { resolve } from "node:path"; +import { paths, configExists } from "./config.mjs"; +import { serviceRegions, deleteEverything, activeInstances, preflight, deploy } from "./cloud.mjs"; +import * as cost from "./cost.mjs"; +import { Tunnel, httpCode, modelReady, freePort, waitForTunnel, waitForModel, warmModel, keepAwake } from "./tunnel.mjs"; +import { writeQwenSettings, qwenSessions, openQwen, qwenAlive, stopQwen } from "./qwen.mjs"; +import { alive, commandOf, killTree, sleep } from "./proc.mjs"; +import { say, warn, die, notify, key, startKeyboard, stopKeyboard, logFile, isInteractive } from "./ui.mjs"; + +// What cleanup needs to know about this run. +export const state = { deploying: null, own: false, locked: false, deployStart: 0, tunnel: null, awake: null, c: null, s: null, cleaning: false }; +const liveSeconds = () => (state.deployStart ? (Date.now() - state.deployStart) / 1000 : 0); +const costSoFar = () => cost.money(state.c, cost.sessionCost(state.c, liveSeconds())); + +function acquireLock() { + mkdirSync(paths.state, { recursive: true }); + try { + mkdirSync(paths.lock); + } catch { + let pid = 0; + try { + pid = Number(readFileSync(`${paths.lock}/pid`, "utf8")); + } catch {} + return pid; + } + writeFileSync(`${paths.lock}/pid`, String(process.pid)); + state.locked = true; + return 0; +} +async function lock() { + const other = acquireLock(); + if (!other) return; + // Only a live runcoder counts; a stale lock whose process ID was reused does not. + if (alive(other) && (await commandOf(other)).includes("runcoder")) { + die(`runcoder is already running (process ${other}). Use that window, or run: runcoder down`); + } + rmSync(paths.lock, { recursive: true, force: true }); + if (acquireLock()) die("Could not take the lock; another runcoder is starting."); +} + +// Runs once, on q, a limit, Ctrl+C, a closed window or an error: closes Qwen Code and the tunnel, +// deletes the service and confirms it is gone. Returns the exit code to use. +export async function cleanup(rc) { + if (state.cleaning) return rc; + state.cleaning = true; + stopKeyboard(); + if (state.locked) await stopQwen(); // only the run holding the lock owns the Qwen window + state.tunnel?.close(); + if (state.awake) killTree(state.awake.pid); + if (state.own) { + const { s, c } = state; + if (state.deploying) { + // Deleting while gcloud is still deploying fails or races it; let the deploy finish first. + say("Waiting for the deploy in progress to finish, then deleting..."); + await Promise.race([state.deploying.catch(() => {}), sleep(600)]); + } + say("Shutting down and deleting the Cloud Run service..."); + if (await deleteEverything(s)) { + if (state.deployStart && c) { + say(`This session ran ${Math.floor(liveSeconds() / 60)} minutes and cost about ${costSoFar()}.`); + if (cost.creditEnabled(c)) say(cost.creditLine(c, liveSeconds())); + say("Google's billed minutes for it show up in: runcoder credit (a few minutes from now)."); + } + say(`Done: ${s.service} is deleted, nothing is running or billing.`); + notify("runcoder is deleted. Nothing is billing."); + } else { + say(`!!! Could not confirm that ${s.service} is deleted. Run this to finish: runcoder down`); + if (c?.pricesOk) say(`!!! Until it is deleted it can bill up to about ${cost.money(c, cost.fullRate(c))} per hour while an instance runs.`); + notify("deletion NOT confirmed. Run runcoder down."); + rc = 1; + } + } + state.tunnel?.close(); + if (state.locked) rmSync(paths.lock, { recursive: true, force: true }); + return rc; +} + +async function keepAlive(s, tunnel, region) { + if (!tunnel.alive()) { + warn("The tunnel stopped; reopening it."); + tunnel.start(); + await waitForTunnel(s, tunnel); + } + // One failed check is not enough: a tunnel hiccup ("connection reset") looks the same for a moment. + for (let i = 0; i < 3; i++) { + if (await modelReady(s)) return; + await sleep(5); + } + const code = await httpCode(s, "/api/tags"); + if (code === 200) { + warn("The server restarted and lost the model (for example after this computer slept). Downloading it again."); + notify("the server restarted, downloading the model again"); + await waitForModel(s, region, tunnel, costSoFar); + await warmModel(s); + say("runcoder is ready again."); + notify("runcoder is ready again"); + } else { + warn(`The server is not answering right now (HTTP ${code || "none"}); checking again shortly.`); + } +} + +async function session(s, workdir, tunnel, region) { + const c = state.c; + const started = Date.now(); + let warned = false; + let qwenSeen = false; + let qwenGoneAt = 0; + let lastReport = 0; + let creditWarned = cost.creditUsedUp(c, liveSeconds()); + say("Press q here when you are done (or Ctrl+C, or close this window): everything is shut down and deleted."); + say(`Press r to reopen Qwen Code where you left off. It stops by itself after ${s.maxMinutes} minutes.`); + for (;;) { + const k = isInteractive() ? await key(s.tick) : (await sleep(s.tick), ""); + if (/^[qQ]$/.test(k)) { + say("q pressed."); + return; + } + if (/^[rR]$/.test(k)) { + await openQwen(s, workdir, "--continue"); + qwenSeen = false; + qwenGoneAt = 0; + } + await keepAlive(s, tunnel, region); + const minutes = Math.floor((Date.now() - started) / 60e3); + + if (qwenAlive()) { + qwenSeen = true; + qwenGoneAt = 0; + } else if (qwenSeen && !qwenGoneAt) { + qwenGoneAt = Date.now(); + say(`Qwen Code was closed. Press q to delete everything, or r to reopen it where you left off. Shutting down by itself in ${s.qwenIdleMinutes} minutes.`); + notify("Qwen Code closed: press q in the runcoder window to delete everything"); + } + if (qwenGoneAt && Date.now() - qwenGoneAt >= s.qwenIdleMinutes * 60e3) { + say(`Qwen Code has been closed for ${s.qwenIdleMinutes} minutes; shutting down.`); + return; + } + if (minutes - lastReport >= 10) { + lastReport = minutes; + say(`Session ${minutes} min, cost so far about ${costSoFar()}, now ${cost.rateLine(c, liveSeconds())}.`); + if (cost.creditEnabled(c)) say(` ${cost.creditLine(c, liveSeconds())}`); + } + if (!creditWarned && cost.creditUsedUp(c, liveSeconds())) { + creditWarned = true; + warn(cost.creditLine(c, liveSeconds())); + notify("monthly credit used up, now charging your card"); + } + if (minutes >= s.maxMinutes - 10 && !warned) { + warned = true; + say(`Stopping by itself in 10 minutes (limit ${s.maxMinutes} minutes; set RUNCODER_MAX_MINUTES to change).`); + notify("runcoder stops in 10 minutes"); + } + if (minutes >= s.maxMinutes) { + say(`Reached the ${s.maxMinutes}-minute limit; shutting down.`); + return; + } + } +} + +// Decides which Qwen Code session to open, before the long wait so you can walk away. +async function chooseQwenSession(s, workdir, chosen) { + if (chosen !== null) return chosen; + const sessions = await qwenSessions(s, workdir); + if (!sessions.length) { + say("Qwen Code will start a new session (none saved yet for this folder)."); + return ""; + } + say(`This folder has ${sessions.length} earlier Qwen Code session(s). Latest: ${sessions[0].label.slice(0, 70)}`); + if (!isInteractive()) { + say("Starting a new session (no keyboard here; use -c to continue the last one)."); + return ""; + } + say("Press c to continue the latest, p to pick one from a list, or Enter for a new session (new in 60s)."); + const k = await key(60); + const mode = /^[cC]$/.test(k) ? "--continue" : /^[pP]$/.test(k) ? "--resume" : ""; + say(mode === "--continue" ? "Qwen Code will continue the latest session." : mode ? "Qwen Code will show its session list when it opens." : "Qwen Code will start a new session."); + return mode; +} + +export async function cmdUp(s, argv) { + let dir = ""; + let mode = null; // null: ask + for (const a of argv) { + if (a === "-c" || a === "--continue") mode = "--continue"; + else if (a === "-p" || a === "--pick" || a === "--resume") mode = "--resume"; + else if (a === "-n" || a === "--new") mode = ""; + else if (a.startsWith("-")) die(`Unknown option: ${a} (see: runcoder help)`); + else dir = a; + } + let workdir; + try { + workdir = realpathSync(resolve(dir || process.cwd())); + if (!statSync(workdir).isDirectory()) throw new Error(); + } catch { + die(`Folder not found: ${dir}`); + } + if (!configExists() && !s.project) die("runcoder is not set up yet. Run: runcoder setup"); + state.s = s; + startKeyboard(s.interactive); + await lock(); + say(`runcoder: ${s.model} on a Cloud Run GPU (${s.gpu}), for Qwen Code in ${workdir}. Log: ${logFile}`); + await preflight(s); + state.c = await cost.loadCost(s); + const c = state.c; + say(`It bills ${cost.rateLine(c)} while the GPU runs.`); + if (cost.creditEnabled(c)) { + say(cost.creditLine(c)); + if (cost.creditUsedUp(c)) { + if (isInteractive()) { + say(`This session would be charged to your card at ${cost.rateLine(c)}. Press y to go ahead, anything else to stop.`); + if (!/^[yY]$/.test(await key())) die("Stopped before starting anything; nothing was charged."); + } else if (!s.allowPaid) die("Credit looks used up; set RUNCODER_ALLOW_PAID=1 to run on your card anyway."); + } + } + writeQwenSettings(s); + mode = await chooseQwenSession(s, workdir, mode); + await freePort(s); + let leftover; + try { + leftover = await serviceRegions(s); + } catch { + die("Could not reach Google Cloud."); + } + if (leftover.length) { + warn(`A ${s.service} service from an earlier run still exists in: ${leftover.join(" ")}. It will be replaced and deleted at the end.`); + state.own = true; + } + state.awake = await keepAwake(); + state.deploying = deploy(s, () => { + state.own = true; + state.deployStart ||= Date.now(); // a fallback region keeps counting from the first attempt + }); + const region = await state.deploying; + state.deploying = null; + if (region !== s.regions[0]) state.c = await cost.loadCost(s, region); // prices differ by region + const tunnel = (state.tunnel = new Tunnel(s, region)); + tunnel.start(); + await waitForTunnel(s, tunnel); + await waitForModel(s, region, tunnel, costSoFar); + await warmModel(s); + notify("runcoder is ready"); + await openQwen(s, workdir, mode); + await session(s, workdir, tunnel, region); +} + +export async function cmdStatus(s) { + if (!s.project) die("No Google Cloud project is set. Run: runcoder setup"); + let regions; + try { + regions = await serviceRegions(s); + } catch { + die("Could not reach Google Cloud to check."); + } + const c = await cost.loadCost(s); + if (!regions.length) say(`No ${s.service} service exists in ${s.project}. Nothing is running or billing.`); + else { + say(`${s.service} exists in: ${regions.join(" ")}. Active instances now: ${await activeInstances(s)}.`); + say(`While an instance runs it bills ${cost.rateLine(c)}. Delete it with: runcoder down`); + } + if (cost.creditEnabled(c)) say(cost.creditLine(c)); +} + +export async function cmdCredit(s) { + if (!s.project) die("No Google Cloud project is set. Run: runcoder setup"); + const c = await cost.loadCost(s); + say(`${s.service} runs this billing month (${c.month}, Pacific time), as Google bills them:`); + if (!c.sessions.length) say(" none yet"); + for (const r of c.sessions) { + const when = r.start.toLocaleString("sv-SE", { dateStyle: "short", timeStyle: "short" }); + console.log(` ${when} ${r.region.padEnd(12)} ${r.minutes.toFixed(1).padStart(6)} min ${cost.money(c, r.cost)}`); + } + if (cost.costKnown(c)) { + say(`Total ${cost.money(c, cost.monthUsed(c))}: GPU time plus CPU and memory beyond Cloud Run's free tier (${cost.money(c, c.freeLeft)} of it left this month).`); + say(`Rate now: ${cost.rateLine(c)}.`); + } + say(`Prices: ${c.prices}. Billed minutes are a few minutes behind.`); + if (cost.creditEnabled(c)) { + say(cost.creditLine(c)); + say("Billing > Credits in the Cloud console is exact but runs up to a day behind, and includes anything else on the billing account."); + } else say("Credit tracking is off (set RUNCODER_MONTHLY_CREDIT, or run: runcoder setup)."); +} + +export function cmdDown(s) { + if (!s.project) die("No Google Cloud project is set. Run: runcoder setup"); + state.s = s; + state.own = true; // cleanup deletes and confirms + say(`Deleting any ${s.service} service in ${s.project}...`); +} diff --git a/src/setup.mjs b/src/setup.mjs new file mode 100644 index 0000000..216c94a --- /dev/null +++ b/src/setup.mjs @@ -0,0 +1,93 @@ +// runcoder setup: checks this computer and a Google Cloud project, then writes the config file. +// It signs in only through gcloud and asks before changing anything in Google Cloud. +// runcoder setup [--project ID] [--credit AMOUNT] [--yes] + +import { writeConfigFile, paths } from "./config.mjs"; +import { gcloud, gcloudInstalled, account, apiEnabled } from "./cloud.mjs"; +import { run } from "./proc.mjs"; +import * as cost from "./cost.mjs"; +import { say, die, confirm, line, startKeyboard, isInteractive } from "./ui.mjs"; + +export async function cmdSetup(s, argv) { + const opt = { project: "", credit: "", yes: false }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--project") opt.project = argv[++i] ?? die("--project needs a project ID"); + else if (a === "--credit") opt.credit = argv[++i] ?? die("--credit needs an amount"); + else if (a === "--yes" || a === "-y") opt.yes = true; + else die(`Unknown setup option: ${a} (see: runcoder help)`); + } + startKeyboard(s.interactive); + + say("Checking this computer..."); + const major = Number(process.versions.node.split(".")[0]); + if (major < 22) die(`Node.js ${process.version} is too old; runcoder and Qwen Code need 22 or later: https://nodejs.org`); + if (!(await gcloudInstalled())) die("gcloud (the Google Cloud CLI) is not installed. Install it, then run runcoder setup again: https://cloud.google.com/sdk/docs/install"); + say(` Node.js ${process.version} and gcloud: ok`); + + let who = await account(); + if (!who) { + if (isInteractive() && (await confirm("gcloud is not logged in. Log in now in your browser (gcloud auth login)?"))) { + await run("gcloud", ["auth", "login"], { stdio: "inherit" }); + who = await account(); + } + if (!who) die("gcloud is not logged in. Run: gcloud auth login"); + } + say(` gcloud is logged in as ${who}.`); + + // Project + let project = opt.project; + if (!project) { + const current = s.project || (await run("gcloud", ["config", "get-value", "project"]).catch(() => ({ stdout: "" }))).stdout.trim(); + const list = (await gcloud({}, ["projects", "list", "--format=value(projectId)", "--sort-by=projectId"])).stdout.split(/\r?\n/).filter(Boolean); + if (list.length && isInteractive()) { + say("Your Google Cloud projects:"); + list.forEach((p, i) => console.log(` ${String(i + 1).padStart(2)} ${p}`)); + } + let choice = await line(`Project to run the GPU in (number or project ID)${current ? ` [${current}]` : ""}:`, current); + if (/^\d+$/.test(choice) && list[Number(choice) - 1]) choice = list[Number(choice) - 1]; + project = choice; + } + if (!project) die("No project chosen. Create one at https://console.cloud.google.com/projectcreate and run runcoder setup again."); + const p = { ...s, project }; + if ((await gcloud(p, ["projects", "describe", project, "--format=value(projectId)"])).code !== 0) die(`Your gcloud login cannot open project ${project}.`); + say(` project: ${project}`); + + // Billing and its currency + const info = (await gcloud({}, ["billing", "projects", "describe", project, "--format=value(billingEnabled,billingAccountName)"])).stdout.trim(); + if (!/^True/i.test(info)) { + die(`Billing is not turned on for ${project} (or your login cannot see it). Link a billing account: https://console.cloud.google.com/billing/linkedaccount?project=${project}`); + } + const accountId = info.split("billingAccounts/")[1]?.trim(); + let currency = accountId ? (await gcloud({}, ["billing", "accounts", "describe", accountId, "--format=value(currencyCode)"])).stdout.trim() : ""; + if (!/^[A-Z]{3}$/.test(currency)) currency = (await line("Could not read the billing account's currency. Its three-letter code [USD]:", "USD")).toUpperCase(); + say(` billing: on, in ${currency}`); + + // APIs + const missing = []; + for (const api of ["run.googleapis.com", "monitoring.googleapis.com"]) if (!(await apiEnabled(p, api))) missing.push(api); + if (!missing.length) say(" Cloud Run and Cloud Monitoring APIs: on"); + else { + say(`These APIs are off in ${project}: ${missing.join(" ")}. Turning them on costs nothing by itself.`); + if (opt.yes || (await confirm("Turn them on now?"))) { + if ((await gcloud(p, ["services", "enable", ...missing])).code !== 0) die(`Could not turn on: ${missing.join(" ")}`); + say(` turned on: ${missing.join(" ")}`); + } else die(`runcoder needs ${missing.join(" ")}. Turn them on and run runcoder setup again.`); + } + + // Credit + let credit = opt.credit; + if (!credit) { + say("If your Google Cloud billing has a monthly credit (Google AI Pro and Ultra include one), runcoder"); + say("can track it. Billing > Credits in the Cloud console shows the amount."); + credit = await line(`Monthly credit in ${currency} (0 for none) [${s.monthlyCredit}]:`, String(s.monthlyCredit)); + } + if (!/^\d+(\.\d+)?$/.test(credit)) die("The credit must be a number, like 14.25."); + + writeConfigFile({ RUNCODER_PROJECT: project, RUNCODER_CURRENCY: currency, RUNCODER_MONTHLY_CREDIT: credit }); + say(`Saved settings to ${paths.configFile}`); + const c = await cost.loadCost({ ...p, currency, monthlyCredit: Number(credit) }); + say(`Ready. A GPU session bills ${cost.rateLine(c)}.`); + if (cost.creditEnabled(c)) say(cost.creditLine(c)); + say("Start one with: runcoder ~/path/to/your/project"); +} diff --git a/src/tunnel.mjs b/src/tunnel.mjs new file mode 100644 index 0000000..b6bce4c --- /dev/null +++ b/src/tunnel.mjs @@ -0,0 +1,170 @@ +// The private tunnel to the server (`gcloud run services proxy`), and the model on it. + +import { readFileSync, writeFileSync, rmSync } from "node:fs"; +import { paths } from "./config.mjs"; +import { gcloud } from "./cloud.mjs"; +import { start, alive, commandOf, killTree, has, sleep } from "./proc.mjs"; +import { say, warn, die, log } from "./ui.mjs"; + +export class Tunnel { + constructor(s, region) { + this.s = s; + this.region = region; + this.child = null; + } + start() { + if (this.closed) return; // cleanup closed it; a loop still running must not reopen it + this.stop(); + const s = this.s; + this.child = start("gcloud", [`--project=${s.project}`, "--quiet", "run", "services", "proxy", s.service, `--region=${this.region}`, `--port=${s.port}`], { + stdio: ["ignore", "ignore", "pipe"], + }); + this.child.stderr?.on("data", (d) => log(`proxy: ${String(d).trim()}`)); + writeFileSync(paths.proxyPid, String(this.child.pid ?? "")); + } + stop() { + if (this.child) { + killTree(this.child.pid); + this.child = null; + } + rmSync(paths.proxyPid, { force: true }); + } + close() { + this.closed = true; + this.stop(); + } + alive() { + return !!this.child && this.child.exitCode === null && this.child.signalCode === null; + } +} + +// HTTP status for a path on the tunnel, or 0 if nothing answers. +export async function httpCode(s, path, seconds = 20) { + try { + const res = await fetch(`${s.baseUrl}${path}`, { signal: AbortSignal.timeout(seconds * 1000) }); + await res.arrayBuffer(); + return res.status; + } catch { + return 0; + } +} +export async function modelReady(s) { + try { + const res = await fetch(`${s.baseUrl}/api/tags`, { signal: AbortSignal.timeout(20000) }); + const body = await res.json(); + return (body.models || []).some((m) => m.name === s.model || m.model === s.model); + } catch { + return false; + } +} + +// A run killed outright (kill -9, power loss) leaves its tunnel holding the port; close only that. +export async function freePort(s) { + if ((await httpCode(s, "/", 2)) === 0) return; + let pid = 0; + try { + pid = Number(readFileSync(paths.proxyPid, "utf8")); + } catch {} + if (pid && alive(pid) && (await commandOf(pid)).includes(`run services proxy ${s.service}`)) { + warn(`Closing a tunnel left behind by an earlier run (process ${pid}).`); + killTree(pid); + rmSync(paths.proxyPid, { force: true }); + await sleep(2); + } + if ((await httpCode(s, "/", 2)) !== 0) die(`Port ${s.port} is already in use on this machine by another program. Free it or set RUNCODER_PORT.`); +} + +export async function waitForTunnel(s, tunnel) { + say(`Opening a private tunnel to the server on localhost:${s.port}...`); + for (let i = 0; i < 60; i++) { + if ((await httpCode(s, "/api/tags", 30)) === 200) return; + if (!tunnel.alive()) tunnel.start(); + await sleep(2); + } + die("The tunnel to Cloud Run did not come up."); +} + +// Ollama's progress bar arrives as log lines full of terminal codes; keep "54% 16 GB/ 30 GB 59 MB/s 4m01s". +async function pullProgress(s, region) { + const r = await gcloud(s, ["run", "services", "logs", "read", s.service, `--region=${region}`, "--limit=40"]); + const lines = r.stdout + .split(/\r?\n/) + .filter((l) => l.includes("GB/")) + .map((l) => + l + .replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "") + .replace(/pulling manifest.*/, "") + .replace(/[^ -~]+/g, "") + .replace(/.*pulling [0-9a-f]+: */, "") + .replace(/ +/g, " ") + .trim(), + ); + return lines.pop() || ""; +} + +export async function waitForModel(s, region, tunnel, costSoFar) { + const deadline = Date.now() + s.pullTimeoutMinutes * 60e3; + let last = ""; + say(`Downloading ${s.model} to the server (about 10 minutes for 30 GB)...`); + while (!(await modelReady(s))) { + if (Date.now() > deadline) die(`The model was not ready after ${s.pullTimeoutMinutes} minutes.`); + if (!tunnel.alive()) { + warn("The tunnel stopped; reopening it."); + tunnel.start(); + } + const progress = await pullProgress(s, region); + if (progress && progress !== last) { + say(` download: ${progress} (cost so far about ${costSoFar()})`); + last = progress; + } + await sleep(Math.min(15, s.tick)); + } + say("Model downloaded."); +} + +async function generate(s, prompt, maxTokens) { + const res = await fetch(`${s.baseUrl}/api/generate`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ model: s.model, prompt, stream: false, keep_alive: -1, think: false, options: { num_predict: maxTokens } }), + signal: AbortSignal.timeout(900e3), + }); + return res.json(); +} + +// Loads the model onto the GPU, then times a second answer: the first one includes the GPU's +// one-time warm-up and reads far slower (3 tokens/s against about 48 for qwen3.8:27b-q8_0 on an +// RTX PRO 6000). +export async function warmModel(s) { + const t0 = Date.now(); + say("Loading the model onto the GPU (about a minute)..."); + let first; + try { + first = await generate(s, "Say OK.", 8); + } catch (e) { + die(`The model did not answer a test request (${e.message}).`); + } + log(JSON.stringify(first).slice(0, 400)); + if (first?.done !== true) die(`The model's test answer was not complete: ${JSON.stringify(first).slice(0, 200)}`); + let second; + try { + second = await generate(s, "Write a Python function that checks whether a number is prime.", 128); + } catch (e) { + die(`The model did not answer a second test request (${e.message}).`); + } + const secs = Math.round((Date.now() - t0) / 1000); + if (second?.eval_count && second?.eval_duration) { + say(`Model is ready after ${secs}s and writes about ${Math.round(second.eval_count / (second.eval_duration / 1e9))} tokens/s.`); + } else say(`Model is ready after ${secs}s.`); +} + +// Keeps this computer from sleeping while runcoder runs. Returns the helper process, if any. +export async function keepAwake() { + if (process.platform === "darwin") return start("caffeinate", ["-i", "-w", String(process.pid)]); + if (process.platform === "win32") { + const ps = `$t=Add-Type -PassThru -Name P -Namespace W -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);'; while(Get-Process -Id ${process.pid} -ErrorAction SilentlyContinue){ [void]$t::SetThreadExecutionState(0x80000001); Start-Sleep 30 }`; + return start("powershell.exe", ["-NoProfile", "-Command", ps]); + } + if (await has("systemd-inhibit")) return start("systemd-inhibit", ["--what=idle:sleep", "--who=runcoder", "--why=GPU session running", "sleep", "86400"]); + return null; +} diff --git a/src/ui.mjs b/src/ui.mjs new file mode 100644 index 0000000..a3a821d --- /dev/null +++ b/src/ui.mjs @@ -0,0 +1,149 @@ +// Output, the run log, notifications and the keyboard. + +import { appendFileSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs"; +import { join } from "node:path"; +import { emitKeypressEvents } from "node:readline"; +import { paths } from "./config.mjs"; +import { run } from "./proc.mjs"; + +const stamp = () => new Date().toTimeString().slice(0, 8); +const fileStamp = () => new Date().toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15); + +mkdirSync(paths.logs, { recursive: true }); +export const logFile = join(paths.logs, `${fileStamp()}-${process.pid}.log`); +for (const f of readdirSync(paths.logs)) { + // keep two months of logs + const p = join(paths.logs, f); + try { + if (Date.now() - statSync(p).mtimeMs > 60 * 86400e3) unlinkSync(p); + } catch {} +} + +// The log may be shared to get help, so it never holds an account name: gcloud logins (and the +// errors gcloud prints, which name them) are email addresses, written here as . +const accounts = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+/g; +export function log(text) { + const line = String(text).replace(accounts, ""); + try { + appendFileSync(logFile, line.endsWith("\n") ? line : `${line}\n`); + } catch {} +} +// A closed window takes the terminal with it, and a write to it then fails later, as an 'error' +// event (EIO, or EPIPE on a pipe) rather than a throw. Unhandled, that would end runcoder before +// it deletes the server. Drop those writes; the log file keeps every line. +for (const stream of [process.stdout, process.stderr]) stream.on("error", () => {}); + +export function say(text) { + const line = `${stamp()} ${text}`; + try { + process.stdout.write(`${line}\n`); + } catch {} // the window may already be closed + log(line); +} +export const warn = (text) => say(`WARNING: ${text}`); + +// A stop the user should read: runcoder prints it, cleans up and exits 1. +export class Stop extends Error {} +export function die(text) { + throw new Stop(text); +} + +export function notify(text) { + if (process.platform === "darwin") { + run("osascript", ["-e", `display notification ${JSON.stringify(text)} with title "runcoder" sound name "Glass"`]).catch(() => {}); + } else if (process.platform === "linux") { + run("notify-send", ["runcoder", text]).catch(() => {}); + } else { + try { + process.stdout.write("\x07"); // Windows: the terminal bell + } catch {} + } +} + +// ---------------------------------------------------------------- keyboard +// Keys typed in this window, one at a time, while runcoder waits. Ctrl+C in raw mode arrives as a +// key, so it is turned back into SIGINT. +const queue = []; +let waiting = null; +let started = false; +let interactive = false; +export function startKeyboard(isInteractive) { + interactive = isInteractive; + if (started || !interactive) return; + started = true; + if (process.stdin.isTTY) { + emitKeypressEvents(process.stdin); + process.stdin.setRawMode(true); + process.stdin.on("keypress", (str, key) => { + if (key?.ctrl && key.name === "c") return process.emit("SIGINT", "SIGINT"); + push(str ?? key?.name ?? ""); + }); + } else { + process.stdin.setEncoding("utf8"); + process.stdin.on("data", (chunk) => { + for (const ch of chunk) push(ch === "\n" ? "\r" : ch); + }); + } + process.stdin.on("error", () => {}); + process.stdin.resume(); +} +function push(k) { + if (waiting) { + const w = waiting; + waiting = null; + w(k); + } else queue.push(k); +} +export function stopKeyboard() { + if (!started) return; + try { + if (process.stdin.isTTY) process.stdin.setRawMode(false); + } catch {} + process.stdin.pause(); +} +// The next key, or "" after the timeout (or at once without a keyboard). +export function key(timeoutSeconds = Infinity) { + if (!interactive) return Promise.resolve(""); + if (queue.length) return Promise.resolve(queue.shift()); + return new Promise((resolve) => { + const timer = Number.isFinite(timeoutSeconds) + ? setTimeout(() => { + waiting = null; + resolve(""); + }, timeoutSeconds * 1000) + : null; + waiting = (k) => { + if (timer) clearTimeout(timer); + resolve(k); + }; + }); +} +// A typed line (Enter ends it), shown as it is typed; the default without a keyboard. +export async function line(prompt, fallback) { + if (!interactive) return fallback; + process.stdout.write(`${prompt} `); + let text = ""; + for (;;) { + const k = await key(); + if (k === "\r" || k === "\n" || k === "return" || k === "enter") break; + if (k === "\x7f" || k === "\b" || k === "backspace") { + if (text) { + text = text.slice(0, -1); + process.stdout.write("\b \b"); + } + continue; + } + if (k.length === 1 && k >= " ") { + text += k; + process.stdout.write(k); + } + } + process.stdout.write("\n"); + return text.trim() || fallback; +} +export async function confirm(question, fallback = false) { + if (!interactive) return fallback; + say(`${question} Press y for yes, anything else for no.`); + return /^[yY]$/.test(await key()); +} +export const isInteractive = () => interactive; diff --git a/tests/1-run.test.mjs b/tests/1-run.test.mjs new file mode 100644 index 0000000..87bf639 --- /dev/null +++ b/tests/1-run.test.mjs @@ -0,0 +1,71 @@ +// A normal run, Ctrl+C, closing the window, and falling back to the second region. +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { readdirSync, readFileSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { sandbox, start, startGoogle, noService, touch, calls, killLeftovers, windows } from "./helpers.mjs"; + +let server; +before(async () => (server = await startGoogle())); +after(() => server.close()); + +test("a normal run: download progress, warm speed, q deletes everything", async () => { + const ctx = sandbox("t1", { readyAfter: 6 }); + const r = start(ctx); + assert.ok(await r.waitFor("download: 54% 16 GB/ 30 GB 59 MB/s 4m01s", 40), r.out()); + assert.ok(await r.waitFor("writes about 60 tokens/s", 40), r.out()); + assert.ok(await r.waitFor("Press q here", 10), r.out()); + r.press("q"); + assert.equal(await r.done(), 0, r.out()); + assert.ok(r.has("Done: runcoder is deleted"), r.out()); + assert.ok(noService(ctx)); + killLeftovers(ctx); +}); + +test("Ctrl+C during the download deletes everything and exits 130", { skip: windows && "signals differ on Windows" }, async () => { + const ctx = sandbox("t2", { readyAfter: 30 }); + const r = start(ctx); + assert.ok(await r.waitFor("Downloading", 30), r.out()); + r.child.kill("SIGINT"); + assert.equal(await r.done(30), 130, r.out()); + assert.ok(r.has("Done: runcoder is deleted"), r.out()); + assert.ok(noService(ctx)); +}); + +test("closing the window (SIGHUP) deletes everything", { skip: windows && "signals differ on Windows" }, async () => { + const ctx = sandbox("t3"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + r.child.kill("SIGHUP"); + await r.done(30); + assert.ok(r.has("Done: runcoder is deleted"), r.out()); + assert.ok(noService(ctx)); +}); + +// A closed window takes the terminal with it: every later write fails. Destroying the pipes makes +// runcoder's writes fail the same way (EPIPE here, EIO on a real terminal). +test("closing the window after the terminal is gone still deletes everything", { skip: windows && "signals differ on Windows" }, async () => { + const ctx = sandbox("t3b"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + r.child.stdout.destroy(); + r.child.stderr.destroy(); + r.child.kill("SIGHUP"); + assert.equal(await r.done(60), 129); + assert.ok(noService(ctx), calls(ctx)); + const logs = readdirSync(join(ctx.state, "logs")).map((f) => readFileSync(join(ctx.state, "logs", f), "utf8")).join(""); + assert.match(logs, /Done: runcoder is deleted/); + assert.ok(!existsSync(join(ctx.state, "lock"))); +}); + +test("falls back to the next region and cleans both", async () => { + const ctx = sandbox("t4"); + touch(ctx, "deployfail-us-central1"); + const r = start(ctx); + assert.ok(await r.waitFor("GPU server is up in europe-west4", 60), r.out()); + assert.ok(r.has("Could not start in us-central1: ERROR: (gcloud.run.deploy) fake capacity error"), r.out()); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + r.press("q"); + assert.equal(await r.done(), 0, r.out()); + assert.ok(noService(ctx)); +}); diff --git a/tests/2-recovery.test.mjs b/tests/2-recovery.test.mjs new file mode 100644 index 0000000..ed9518b --- /dev/null +++ b/tests/2-recovery.test.mjs @@ -0,0 +1,130 @@ +// Tunnel and server trouble, a second copy, a busy port, status/down, failed deletes, leftovers. +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { rmSync, existsSync } from "node:fs"; +import { sandbox, start, once, startGoogle, noService, touch, fake, setReady, calls, killLeftovers, sleep, PORT, windows } from "./helpers.mjs"; +import { startOllama } from "./fake/ollama.mjs"; + +let server; +before(async () => (server = await startGoogle())); +after(() => server.close()); + +// The whole gcloud process tree, as a crash would end it: on Windows a plain kill would end only +// the gcloud.cmd wrapper and leave the proxy under it holding the port. +const killProxy = async (ctx) => { + const { readFileSync } = await import("node:fs"); + const { killTree } = await import("../src/proc.mjs"); + killTree(Number(readFileSync(`${ctx.state}/proxy.pid`, "utf8"))); +}; + +test("the tunnel dies mid-session: reopened, no re-download", async () => { + const ctx = sandbox("t5"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + setReady(ctx, 0); + await killProxy(ctx); + assert.ok(await r.waitFor("The tunnel stopped; reopening it.", 20), r.out()); + await sleep(5); + assert.ok(!r.has("lost the model"), r.out()); + r.press("q"); + assert.equal(await r.done(), 0, r.out()); + assert.ok(noService(ctx)); +}); + +test("the server lost the model: detected after retries, downloaded again", async () => { + const ctx = sandbox("t6"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + setReady(ctx, 40); // the restarted fake stays empty longer than the three retries + await killProxy(ctx); + assert.ok(await r.waitFor("lost the model", 40), r.out()); + assert.ok(await r.waitFor("runcoder is ready again", 90), r.out()); + r.press("q"); + assert.equal(await r.done(), 0, r.out()); + assert.ok(noService(ctx)); +}); + +test("a brief hiccup is not reported as a lost model", async () => { + const ctx = sandbox("t24"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + touch(ctx, "empty"); + await sleep(7); + rmSync(fake(ctx, "empty")); + await sleep(12); + assert.ok(!r.has("lost the model"), r.out()); + r.press("q"); + await r.done(); + assert.ok(noService(ctx)); +}); + +test("a second copy is refused and leaves the first alone", async () => { + const ctx = sandbox("t7"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + const second = await once(ctx, ["-n", ctx.work], { RUNCODER_PORT: String(PORT + 1) }); + assert.equal(second.code, 1); + assert.match(second.out, /already running/); + assert.ok(existsSync(fake(ctx, "svc-us-central1"))); + r.press("q"); + await r.done(); + assert.ok(noService(ctx)); +}); + +test("a port used by another program is refused before anything starts", async () => { + const ctx = sandbox("t8"); + const other = await startOllama({ port: PORT, model: "x" }); + const r = await once(ctx, ["-n", ctx.work]); + other.close(); + assert.match(r.out, new RegExp(`Port ${PORT} is already in use`)); + assert.doesNotMatch(calls(ctx), /run deploy|services delete/); +}); + +test("status and down", async () => { + const ctx = sandbox("t9"); + assert.match((await once(ctx, ["status"])).out, /Nothing is running/); + touch(ctx, "svc-europe-west4"); + assert.match((await once(ctx, ["status"])).out, /exists in: europe-west4/); + assert.match((await once(ctx, ["down"])).out, /Done: runcoder is deleted/); + assert.ok(noService(ctx)); + assert.match((await once(ctx, ["down"])).out, /Done: runcoder is deleted/); +}); + +test("a delete that keeps failing is reported loudly; down finishes it", async () => { + const ctx = sandbox("t10"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + touch(ctx, "deletefail"); + r.press("q"); + assert.equal(await r.done(200), 1, r.out()); + assert.ok(r.has("Could not confirm that runcoder is deleted"), r.out()); + rmSync(fake(ctx, "deletefail")); + assert.match((await once(ctx, ["down"])).out, /Done: runcoder is deleted/); + assert.ok(noService(ctx)); +}); + +test("a leftover service in another region is deleted too", async () => { + const ctx = sandbox("t11", { touch: ["svc-europe-west4"] }); + const r = start(ctx); + assert.ok(await r.waitFor("from an earlier run still exists in: europe-west4", 30), r.out()); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + r.press("q"); + await r.done(); + assert.ok(noService(ctx)); +}); + +test("killed outright: the next run closes the old tunnel and deletes the old service", { skip: windows && "kill -9 differs on Windows" }, async () => { + const ctx = sandbox("t22"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + r.child.kill("SIGKILL"); + await r.exit; + await sleep(1); + const next = start(ctx); + assert.ok(await next.waitFor("Closing a tunnel left behind", 30), next.out()); + assert.ok(await next.waitFor("Press q here", 60), next.out()); + next.press("q"); + assert.equal(await next.done(), 0, next.out()); + assert.ok(noService(ctx)); + killLeftovers(ctx); +}); diff --git a/tests/3-qwen.test.mjs b/tests/3-qwen.test.mjs new file mode 100644 index 0000000..ffec05e --- /dev/null +++ b/tests/3-qwen.test.mjs @@ -0,0 +1,158 @@ +// Qwen Code: its window, idle shutdown, q closes it, the resume choices; limits, login, bad folder. +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync, existsSync } from "node:fs"; +import { spawn } from "node:child_process"; +import { join } from "node:path"; +import { sandbox, start, once, startGoogle, noService, touch, calls, sleep, ROOT, PORT } from "./helpers.mjs"; +import { startOllama } from "./fake/ollama.mjs"; + +let server; +before(async () => (server = await startGoogle())); +after(() => server.close()); + +const job = (ctx) => JSON.parse(readFileSync(join(ctx.state, "qwen-window.json"), "utf8")); +// Opens the Qwen Code window the way the terminal would, with a stand-in for Qwen Code itself. +function openWindow(ctx, { real = false } = {}) { + const file = join(ctx.state, "qwen-window.json"); + if (!real) writeFileSync(file, JSON.stringify({ ...job(ctx), entry: join(ROOT, "tests", "fake", "qwen-stub.mjs") })); + return spawn(process.execPath, [join(ROOT, "src", "qwen-window.mjs"), file], { stdio: "ignore" }); +} +const qwenPid = (ctx) => Number(readFileSync(join(ctx.state, "qwen.pid"), "utf8")); + +test("the window runs the installed Qwen Code", async () => { + const ctx = sandbox("q0"); + const r = start(ctx); + assert.ok(await r.waitFor("Open Qwen Code yourself", 60), r.out()); + const file = join(ctx.state, "qwen-window.json"); + writeFileSync(file, JSON.stringify({ ...job(ctx), args: ["--version"] })); + const w = spawn(process.execPath, [join(ROOT, "src", "qwen-window.mjs"), file]); + let text = ""; + w.stdout.on("data", (d) => (text += d)); + await new Promise((res) => w.on("exit", res)); + assert.match(text, /^0\.28\.7/m); + r.press("q"); + await r.done(); +}); + +test("Qwen Code closed: runcoder notices and shuts down after the idle time", async () => { + const ctx = sandbox("t12"); + const r = start(ctx, undefined, { env: { RUNCODER_QWEN_IDLE_MINUTES: "0" } }); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + const w = openWindow(ctx); + await sleep(6); + assert.equal(qwenPid(ctx), w.pid); + w.kill(); + assert.ok(await r.waitFor("Qwen Code was closed", 20), r.out()); + assert.ok(await r.waitFor("has been closed for 0 minutes; shutting down", 20), r.out()); + assert.equal(await r.done(), 0); + assert.ok(noService(ctx)); +}); + +test("q closes a running Qwen Code too", async () => { + const ctx = sandbox("t13"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + const w = openWindow(ctx); + await sleep(4); + r.press("q"); + assert.ok(await r.waitFor("Closed Qwen Code.", 20), r.out()); + await r.done(); + await sleep(1); + assert.notEqual(w.exitCode ?? w.signalCode, null, "the Qwen Code window is still running"); + assert.ok(noService(ctx)); +}); + +test("a refused second run does not close the first run's Qwen Code", async () => { + const ctx = sandbox("t19"); + const r = start(ctx); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + const w = openWindow(ctx); + await sleep(4); + const second = await once(ctx, ["-n", ctx.work], { RUNCODER_PORT: String(PORT + 1) }); + assert.match(second.out, /already running/); + assert.doesNotMatch(second.out, /Closed Qwen Code/); + assert.equal(w.exitCode, null, "Qwen Code was closed"); + r.press("q"); + await r.done(); + assert.ok(noService(ctx)); +}); + +test("the time limit stops the run", async () => { + const ctx = sandbox("t14"); + const r = start(ctx, undefined, { env: { RUNCODER_MAX_MINUTES: "0" } }); + assert.ok(await r.waitFor("Reached the 0-minute limit", 60), r.out()); + await r.done(); + assert.ok(noService(ctx)); +}); + +test("not logged in: explains, starts nothing", async () => { + const ctx = sandbox("t15", { touch: ["loggedout"] }); + const r = await once(ctx, ["-n", ctx.work]); + assert.match(r.out, /gcloud auth login/); + assert.doesNotMatch(calls(ctx), /run deploy/); +}); + +test("a download that never finishes gives up and deletes", async () => { + const ctx = sandbox("t16", { readyAfter: 999 }); + const r = start(ctx, undefined, { env: { RUNCODER_PULL_TIMEOUT_MINUTES: "0" } }); + assert.ok(await r.waitFor("was not ready after 0 minutes", 60), r.out()); + await r.done(); + assert.ok(noService(ctx)); +}); + +test("a missing folder is refused", async () => { + const ctx = sandbox("t17"); + const r = await once(ctx, ["/no/such/folder"]); + assert.match(r.out, /Folder not found/); + assert.doesNotMatch(calls(ctx), /run deploy/); +}); + +test("help and version", async () => { + const ctx = sandbox("t18"); + assert.match((await once(ctx, ["help"])).out, /runcoder status/); + assert.match((await once(ctx, ["version"])).out, /^runcoder \d+\.\d+\.\d+/); +}); + +test("resume: asks when sessions exist; c, r, -p and a new session", async () => { + const ctx = sandbox("t23"); + // a real Qwen Code session for the folder, made against the fake model + const first = start(ctx); // writes Qwen Code's settings + assert.ok(await first.waitFor("Press q here", 60), first.out()); + first.press("q"); + await first.done(); + const ollama = await startOllama({ port: PORT, model: "qwen3.8:27b-q8_0" }); + const { qwenEntry } = await import("../src/qwen.mjs"); + const env = { ...ctx.env, QWEN_HOME: join(ctx.data, "qwen-home"), OPENAI_API_KEY: "ollama" }; + await new Promise((res) => spawn(process.execPath, [qwenEntry(), "say hi"], { cwd: ctx.work, env, stdio: "ignore" }).on("exit", res)); + ollama.close(); + assert.ok(existsSync(join(ctx.data, "qwen-home"))); + + let r = start(ctx, [ctx.work]); + assert.ok(await r.waitFor("Press c to continue the latest", 40), r.out()); + r.press("c"); + assert.ok(await r.waitFor("will continue the latest session", 5), r.out()); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + assert.deepEqual(job(ctx).args, ["--continue"]); + r.press("r"); + await sleep(4); + assert.deepEqual(job(ctx).args, ["--continue"]); + r.press("q"); + await r.done(); + + r = start(ctx, ["-p", ctx.work]); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + assert.deepEqual(job(ctx).args, ["--resume"]); + r.press("q"); + await r.done(); + + r = start(ctx, [ctx.work]); + assert.ok(await r.waitFor("Press c to continue", 40), r.out()); + r.press("x"); + assert.ok(await r.waitFor("will start a new session", 5), r.out()); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + assert.deepEqual(job(ctx).args, []); + r.press("q"); + await r.done(); + assert.ok(noService(ctx)); +}); diff --git a/tests/4-cost.test.mjs b/tests/4-cost.test.mjs new file mode 100644 index 0000000..5728d50 --- /dev/null +++ b/tests/4-cost.test.mjs @@ -0,0 +1,89 @@ +// Cost and credit from Google's billed time, price list and free tier (fake APIs). +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { sandbox, start, once, startGoogle, noService, calls, google } from "./helpers.mjs"; + +let server; +before(async () => (server = await startGoogle())); +after(() => server.close()); +const hour = [["us-central1", "runcoder-00001-aaa", 3600]]; + +test("one billed hour costs only the GPU while the free tier lasts", async () => { + const ctx = sandbox("t20", { billed: hour }); + const r = start(ctx); + assert.ok(await r.waitFor("Credit left this month: about CA$12.37 of CA$14.24", 30), r.out()); + assert.ok(r.has("It bills CA$1.87 per hour while Cloud Run's free CPU and memory last (about 107 more minutes), then CA$4.54"), r.out()); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + r.press("q"); + await r.done(); + assert.match(r.out().split("Shutting down")[1], /Credit left this month: about CA\$12\.3/); + const c = (await once(ctx, ["credit"])).out; + assert.match(c, /us-central1\s+60\.0 min {2}CA\$1\.87/); + assert.match(c, /Total CA\$1\.87: GPU time plus CPU and memory beyond Cloud Run's free tier \(CA\$4\.77 of it left/); + assert.match(c, /about CA\$12\.37 of CA\$14\.24 \(CA\$1\.87 billed to runcoder, about 226 more GPU minutes\)/); +}); + +test("credit used up: asks first, n stops, y goes ahead at the full rate", async () => { + const used = [["us-central1", "runcoder-00001-bbb", 20000]]; + let ctx = sandbox("t21", { billed: used }); + let r = start(ctx); + assert.ok(await r.waitFor("looks USED UP: CA$17.78 billed to runcoder", 20), r.out()); + assert.ok(await r.waitFor("Press y to go ahead", 5), r.out()); + r.press("n"); + assert.equal(await r.done(), 1); + assert.ok(r.has("Stopped before starting anything"), r.out()); + assert.doesNotMatch(calls(ctx), /run deploy/); + + ctx = sandbox("t21b", { billed: used }); + r = start(ctx); + assert.ok(await r.waitFor("Press y to go ahead", 20), r.out()); + r.press("y"); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + assert.ok(r.has("It bills CA$4.54 per hour while"), r.out()); + r.press("q"); + await r.done(); + assert.ok(noService(ctx)); + + ctx = sandbox("t21c", { billed: used }); + const n = await once(ctx, ["-n", ctx.work]); + assert.equal(n.code, 1); + assert.match(n.out, /RUNCODER_ALLOW_PAID=1/); + assert.doesNotMatch(calls(ctx), /run deploy/); +}); + +test("Google's APIs unreachable: costs unknown, the run still works and deletes", async () => { + const ctx = sandbox("t25", { googleDown: true }); + const r = start(ctx); + assert.ok(await r.waitFor("Could not read Google's price list", 30), r.out()); + assert.ok(await r.waitFor("Credit left this month: unknown", 5), r.out()); + assert.ok(await r.waitFor("Press q here", 60), r.out()); + assert.ok(!r.has("Press y"), r.out()); + r.press("q"); + await r.done(); + assert.ok(r.has("cost about an unknown amount"), r.out()); + assert.ok(noService(ctx)); +}); + +test("the price list is cached for a week and used when Google is down", async () => { + const ctx = sandbox("t26"); + await once(ctx, ["credit"]); + await once(ctx, ["credit"]); + assert.equal(google.calls.filter((p) => p.endsWith("/skus")).length, 1); + assert.equal(google.calls.filter((p) => p.endsWith("/timeSeries")).length, 2); + assert.ok(existsSync(join(ctx.state, "prices-CAD-nvidia-rtx-pro-6000.json"))); + google.down = true; + assert.match((await once(ctx, ["credit"])).out, /Prices: Google's price list of/); +}); + +test("RUNCODER_FREE_TIER=0 charges CPU and memory from the first second", async () => { + const ctx = sandbox("t27", { billed: hour }); + assert.match((await once(ctx, ["credit"], { RUNCODER_FREE_TIER: "0" })).out, /60\.0 min {2}CA\$4\.54/); +}); + +test("the L4 GPU is priced from its own price list entry", async () => { + const ctx = sandbox("t28", { billed: hour }); + const r = await once(ctx, ["credit"], { RUNCODER_GPU: "nvidia-l4", RUNCODER_CPU: "8", RUNCODER_MEMORY: "32Gi" }); + assert.match(r.out, /60\.0 min {2}CA\$0\.96/); +}); diff --git a/tests/5-setup.test.mjs b/tests/5-setup.test.mjs new file mode 100644 index 0000000..e9e6853 --- /dev/null +++ b/tests/5-setup.test.mjs @@ -0,0 +1,88 @@ +// runcoder setup, the config file, and running before setup. +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync, existsSync, appendFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import { sandbox, start, once, startGoogle, calls } from "./helpers.mjs"; + +let server; +before(async () => (server = await startGoogle())); +after(() => server.close()); +const conf = (ctx) => readFileSync(ctx.conf, "utf8"); + +test("setup from flags, without a keyboard", async () => { + const ctx = sandbox("s1", { config: false }); + const r = await once(ctx, ["setup", "--project", "test-project", "--credit", "14.25", "--yes"]); + assert.equal(r.code, 0, r.out); + assert.match(conf(ctx), /^RUNCODER_PROJECT=test-project$/m); + assert.match(conf(ctx), /^RUNCODER_CURRENCY=CAD$/m); + assert.match(conf(ctx), /^RUNCODER_MONTHLY_CREDIT=14\.25$/m); + assert.match(r.out, /Ready\. A GPU session bills CA\$1\.87 per hour/); + assert.doesNotMatch(calls(ctx), /services enable|run deploy/); + // the account shows on screen but never reaches the log, which users may share + assert.match(r.out, /logged in as tester@example\.com/); + const logs = readdirSync(join(ctx.state, "logs")).map((f) => readFileSync(join(ctx.state, "logs", f), "utf8")).join(""); + assert.match(logs, /logged in as /); + assert.doesNotMatch(logs, /@example\.com/); +}); + +test("setup with a keyboard: pick a project by number, agree to an API, type the credit", async () => { + const ctx = sandbox("s2", { config: false, touch: ["apioff-monitoring.googleapis.com"] }); + const r = start(ctx, ["setup"]); + assert.ok(await r.waitFor("Project to run the GPU in", 20), r.out()); + r.press("2\n"); + assert.ok(await r.waitFor("These APIs are off in test-project: monitoring.googleapis.com", 20), r.out()); + r.press("y"); + assert.ok(await r.waitFor("Monthly credit in CAD", 20), r.out()); + r.press("10\n"); + assert.equal(await r.done(60), 0, r.out()); + assert.match(conf(ctx), /^RUNCODER_PROJECT=test-project$/m); // gcloud's current project is other-project + assert.match(conf(ctx), /^RUNCODER_MONTHLY_CREDIT=10$/m); + assert.match(calls(ctx), /services enable monitoring\.googleapis\.com/); +}); + +test("saying no to an API stops without writing a config", async () => { + const ctx = sandbox("s3", { config: false, touch: ["apioff-run.googleapis.com"] }); + const r = start(ctx, ["setup", "--project", "test-project", "--credit", "0"]); + assert.ok(await r.waitFor("Turn them on now?", 20), r.out()); + r.press("n"); + assert.equal(await r.done(30), 1); + assert.ok(r.has("runcoder needs run.googleapis.com"), r.out()); + assert.doesNotMatch(calls(ctx), /services enable/); + assert.ok(!existsSync(ctx.conf)); +}); + +test("billing off is explained", async () => { + const ctx = sandbox("s4", { config: false, touch: ["nobilling"] }); + const r = await once(ctx, ["setup", "--project", "test-project", "--credit", "0", "--yes"]); + assert.match(r.out, /Billing is not turned on for test-project/); +}); + +test("not logged in: setup says to run gcloud auth login", async () => { + const ctx = sandbox("s9", { config: false, touch: ["loggedout"] }); + const r = await once(ctx, ["setup", "--project", "test-project", "--credit", "0", "--yes"]); + assert.match(r.out, /gcloud is not logged in\. Run: gcloud auth login/); +}); + +test("a rerun keeps settings the user added", async () => { + const ctx = sandbox("s5"); + appendFileSync(ctx.conf, "RUNCODER_MAX_MINUTES=60\n"); + await once(ctx, ["setup", "--project", "test-project", "--credit", "5", "--yes"]); + assert.match(conf(ctx), /^RUNCODER_MAX_MINUTES=60$/m); + assert.match(conf(ctx), /^RUNCODER_MONTHLY_CREDIT=5$/m); +}); + +test("running before setup asks for setup", async () => { + const ctx = sandbox("s6", { config: false }); + assert.match((await once(ctx, ["-n", ctx.work])).out, /not set up yet\. Run: runcoder setup/); +}); + +test("the config file is data, never run; the environment overrides it", async () => { + const ctx = sandbox("s7"); + const marker = join(ctx.dir, "ran"); + writeFileSync(ctx.conf, `RUNCODER_PROJECT=$(touch ${marker})\n`); + await once(ctx, ["status"]); + assert.ok(!existsSync(marker)); + const ctx2 = sandbox("s8"); + assert.match((await once(ctx2, ["status"], { RUNCODER_PROJECT: "from-env" })).out, /in from-env/); +}); diff --git a/tests/fake/bin/gcloud b/tests/fake/bin/gcloud new file mode 100755 index 0000000..d17f4ed --- /dev/null +++ b/tests/fake/bin/gcloud @@ -0,0 +1,2 @@ +#!/bin/sh +exec node "$(dirname "$0")/../gcloud.mjs" "$@" diff --git a/tests/fake/bin/gcloud.cmd b/tests/fake/bin/gcloud.cmd new file mode 100755 index 0000000..c54d1ac --- /dev/null +++ b/tests/fake/bin/gcloud.cmd @@ -0,0 +1 @@ +@node "%~dp0..\gcloud.mjs" %* diff --git a/tests/fake/bin/notify-send b/tests/fake/bin/notify-send new file mode 100755 index 0000000..ef2e71e --- /dev/null +++ b/tests/fake/bin/notify-send @@ -0,0 +1,3 @@ +#!/bin/sh +# test stub: no real notifications +exit 0 diff --git a/tests/fake/bin/osascript b/tests/fake/bin/osascript new file mode 100755 index 0000000..ef2e71e --- /dev/null +++ b/tests/fake/bin/osascript @@ -0,0 +1,3 @@ +#!/bin/sh +# test stub: no real notifications +exit 0 diff --git a/tests/fake/gcloud.mjs b/tests/fake/gcloud.mjs new file mode 100644 index 0000000..296d999 --- /dev/null +++ b/tests/fake/gcloud.mjs @@ -0,0 +1,56 @@ +// Fake gcloud for runcoder's tests. State lives in $FAKE_DIR: +// svc- the service exists there deployfail- deploy fails there +// deletefail / listfail delete or list fails loggedout no active account +// apioff- that API is off nobilling billing is off +// ready_after seconds before the fake model is ready (read by the fake tunnel) +import { appendFileSync, existsSync, writeFileSync, rmSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { startOllama } from "./ollama.mjs"; + +const F = process.env.FAKE_DIR; +const argv = process.argv.slice(2); +appendFileSync(join(F, "calls.log"), `gcloud ${argv.join(" ")}\n`); +const flag = (name) => argv.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3) ?? ""; +const words = argv.filter((a) => !a.startsWith("--")); +const cmd = words.join(" "); +const region = flag("region"); +const has = (f) => existsSync(join(F, f)); +const out = (s) => process.stdout.write(s); +const fail = (msg, code = 1) => { + process.stderr.write(`${msg}\n`); + process.exit(code); +}; +const service = process.env.RUNCODER_SERVICE || "runcoder"; + +if (argv.includes("--version")) out("Google Cloud SDK 999.0.0 (fake)\n"); +else if (cmd === "auth list") has("loggedout") || out("tester@example.com\n"); +else if (cmd === "auth login") rmSync(join(F, "loggedout"), { force: true }); +else if (cmd === "auth print-access-token") out("tok\n"); +else if (cmd === "config get-value project") out("other-project\n"); +else if (cmd === "projects list") out("other-project\ntest-project\n"); +else if (cmd.startsWith("projects describe")) has("noproject") ? fail("ERROR: not found") : out("test-project\n"); +else if (cmd.startsWith("billing projects describe")) out(has("nobilling") ? "False\t\n" : "True\tbillingAccounts/000000-000000-000000\n"); +else if (cmd.startsWith("billing accounts describe")) out("CAD\n"); +else if (cmd === "services list") { + const api = flag("filter").replace("config.name=", ""); + has(`apioff-${api}`) || out(`${api}\n`); +} else if (cmd.startsWith("services enable")) for (const api of words.slice(2)) rmSync(join(F, `apioff-${api}`), { force: true }); +else if (cmd === "run services list") { + if (has("listfail")) fail("ERROR: network"); + if (has(`svc-${region}`)) out(`${service}\n`); +} else if (cmd.startsWith("run deploy")) { + await new Promise((r) => setTimeout(r, 1000)); + writeFileSync(join(F, `svc-${region}`), ""); + if (has(`deployfail-${region}`)) fail(`ERROR: (gcloud.run.deploy) fake capacity error in ${region}`); + out("Service deployed\n"); +} else if (cmd.startsWith("run services delete")) { + if (has("deletefail")) fail("ERROR: delete failed"); + rmSync(join(F, `svc-${region}`), { force: true }); +} else if (cmd.startsWith("run services proxy")) { + // The fake tunnel: a fake Ollama on the local port, in this process, so its command line reads + // "... run services proxy ..." like the real one. + const readyAfter = Number(has("ready_after") ? readFileSync(join(F, "ready_after"), "utf8") : 4); + await startOllama({ port: Number(flag("port")), model: "qwen3.8:27b-q8_0", readyAfter, emptyFile: join(F, "empty"), logFile: join(F, "mock.log") }).catch((e) => fail(`ERROR: ${e.message}`)); +} else if (cmd.startsWith("run services logs read")) { + out("2026-12-02 07:15:20 pulling 30e51a7cb1cf: 54% ▕██ ▏ 16 GB/ 30 GB 59 MB/s 4m01s\x1b[K\x1b[?25hpulling manifest\n"); +} else fail(`fake gcloud: unhandled: ${cmd}`, 2); diff --git a/tests/fake/ollama.mjs b/tests/fake/ollama.mjs new file mode 100644 index 0000000..97a1aaa --- /dev/null +++ b/tests/fake/ollama.mjs @@ -0,0 +1,46 @@ +// A fake Ollama server: /api/tags, /api/generate, /v1/models, /v1/chat/completions. The model is +// "ready" READY_AFTER seconds after start, unless the EMPTY file exists. Requests go to LOG. +import { createServer } from "node:http"; +import { appendFileSync, existsSync } from "node:fs"; + +export function startOllama({ port, model, readyAfter = 0, emptyFile = "", logFile = "" }) { + const t0 = Date.now(); + const server = createServer((req, res) => { + let body = ""; + req.on("data", (d) => (body += d)); + req.on("end", () => { + if (logFile) appendFileSync(logFile, `${req.method} ${req.url} ${body.slice(0, 300)}\n`); + const ready = (Date.now() - t0) / 1000 >= readyAfter && !(emptyFile && existsSync(emptyFile)); + const json = (o, code = 200) => { + res.writeHead(code, { "Content-Type": "application/json" }); + res.end(JSON.stringify(o)); + }; + if (req.url.startsWith("/api/tags")) return json({ models: ready ? [{ name: model }] : [] }); + if (req.url.startsWith("/v1/models")) return json({ object: "list", data: ready ? [{ id: model, object: "model" }] : [] }); + if (req.url.startsWith("/api/generate")) return json({ model, response: "ok", done: true, eval_count: 48, eval_duration: 800000000 }); + if (req.url.startsWith("/v1/chat/completions")) { + const req2 = JSON.parse(body || "{}"); + const base = { id: "c1", created: Math.floor(Date.now() / 1000), model }; + const usage = { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 }; + if (req2.stream) { + res.writeHead(200, { "Content-Type": "text/event-stream" }); + res.write(`data: ${JSON.stringify({ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "MOCK-REPLY-OK" }, finish_reason: null }] })}\n\n`); + res.write(`data: ${JSON.stringify({ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage })}\n\n`); + return res.end("data: [DONE]\n\n"); + } + return json({ ...base, object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: "MOCK-REPLY-OK" }, finish_reason: "stop" }], usage }); + } + json({ error: "not found" }, 404); + }); + }); + return new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(port, "127.0.0.1", () => resolve(server)); + }); +} + +// Run directly: node ollama.mjs PORT MODEL READY_AFTER (stays up until killed) +if (process.argv[1] && import.meta.url.endsWith(process.argv[1].split(/[\\/]/).pop())) { + const [port, model, readyAfter] = process.argv.slice(2); + await startOllama({ port: Number(port), model, readyAfter: Number(readyAfter || 0) }); +} diff --git a/tests/fake/qwen-stub.mjs b/tests/fake/qwen-stub.mjs new file mode 100644 index 0000000..e832bc2 --- /dev/null +++ b/tests/fake/qwen-stub.mjs @@ -0,0 +1,2 @@ +// Stands in for Qwen Code in tests: stays open until killed. +setInterval(() => {}, 1000); diff --git a/tests/helpers.mjs b/tests/helpers.mjs new file mode 100644 index 0000000..f9761d2 --- /dev/null +++ b/tests/helpers.mjs @@ -0,0 +1,151 @@ +// Test helpers: a sandbox per test (its own config, state and data folders and fake gcloud +// state), runcoder started as a child process with keys fed through stdin, and a fake Cloud +// Monitoring and price list. Nothing reaches Google. + +import { spawn } from "node:child_process"; +import { createServer } from "node:http"; +import { mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; +import { join, delimiter, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { killTree } from "../src/proc.mjs"; + +export const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +export const BIN = join(ROOT, "bin", "runcoder.mjs"); +export const PORT = 18435; +export const windows = process.platform === "win32"; +const TMP = join(ROOT, "tests", "tmp"); + +// ---------------------------------------------------------------- fake Google APIs +const PRICES = { + "NVIDIA RTX Pro 6000 GPU with no zonal redundancy": 520091, + "NVIDIA L4 GPU with no zonal redundancy": 265870, + "Services CPU (Instance-based billing)": 25632, + "Services Memory (Instance-based billing)": 2848, +}; +export const google = { billed: [], down: false, calls: [], url: "" }; +export async function startGoogle() { + const server = createServer((req, res) => { + const path = req.url.split("?")[0]; + google.calls.push(path); + const json = (o, code = 200) => { + res.writeHead(code, { "Content-Type": "application/json" }); + res.end(JSON.stringify(o)); + }; + if (google.down) return json({ error: { message: "down" } }, 503); + if (path.endsWith("/skus")) { + const skus = []; + for (const region of ["us-central1", "europe-west4"]) + for (const [name, nanos] of Object.entries(PRICES)) + skus.push({ description: `${name} in ${region}`, pricingInfo: [{ pricingExpression: { tieredRates: [{ startUsageAmount: 0, unitPrice: { units: "0", nanos } }] } }] }); + return json({ skus }); + } + if (path.endsWith("/timeSeries")) { + const end = new Date(Date.now() - 600e3).toISOString(); + const timeSeries = google.billed.map(([region, rev, seconds]) => ({ + resource: { labels: { location: region, revision_name: rev, service_name: "runcoder" } }, + points: [{ interval: { endTime: end }, value: { doubleValue: seconds } }], + })); + return json(timeSeries.length ? { timeSeries } : {}); + } + json({ error: "not found" }, 404); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + google.url = `http://127.0.0.1:${server.address().port}`; + return server; +} + +// ---------------------------------------------------------------- sandboxes +// A fresh fake Google Cloud and, unless config is false, a set-up config file. +export function sandbox(name, { config = true, billed = [], googleDown = false, touch = [], readyAfter = 2 } = {}) { + const dir = join(TMP, name); + rmSync(dir, { recursive: true, force: true }); + const ctx = { + dir, + fake: join(dir, "fake"), + work: join(dir, "work"), + state: join(dir, "state", "runcoder"), + data: join(dir, "data", "runcoder"), + conf: join(dir, "config", "runcoder", "config"), + }; + for (const d of [ctx.fake, ctx.work, dirname(ctx.conf)]) mkdirSync(d, { recursive: true }); + if (config) writeFileSync(ctx.conf, "RUNCODER_PROJECT=test-project\nRUNCODER_CURRENCY=CAD\nRUNCODER_MONTHLY_CREDIT=14.24\n"); + for (const f of touch) writeFileSync(join(ctx.fake, f), ""); + writeFileSync(join(ctx.fake, "ready_after"), String(readyAfter)); + google.billed = billed; + google.down = googleDown; + google.calls = []; + ctx.env = { + ...process.env, + PATH: `${join(ROOT, "tests", "fake", "bin")}${delimiter}${process.env.PATH}`, + FAKE_DIR: ctx.fake, + XDG_CONFIG_HOME: join(dir, "config"), + XDG_STATE_HOME: join(dir, "state"), + XDG_DATA_HOME: join(dir, "data"), + RUNCODER_PORT: String(PORT), + RUNCODER_TICK: "2", + RUNCODER_OPEN: "none", + RUNCODER_MONITORING_API: google.url, + RUNCODER_BILLING_API: google.url, + }; + return ctx; +} +export const fake = (ctx, f) => join(ctx.fake, f); +export const touch = (ctx, f) => writeFileSync(fake(ctx, f), ""); +export const setReady = (ctx, seconds) => writeFileSync(fake(ctx, "ready_after"), String(seconds)); +export const calls = (ctx) => (existsSync(fake(ctx, "calls.log")) ? readFileSync(fake(ctx, "calls.log"), "utf8") : ""); +export const noService = (ctx) => !calls(ctx) || !["us-central1", "europe-west4"].some((r) => existsSync(fake(ctx, `svc-${r}`))); + +// ---------------------------------------------------------------- running runcoder +// Starts runcoder; keys typed with run.press() reach it as a keyboard would. +export function start(ctx, args = ["-n", ctx.work], { env = {}, keyboard = true } = {}) { + const child = spawn(process.execPath, [BIN, ...args], { + env: { ...ctx.env, ...(keyboard ? { RUNCODER_INTERACTIVE: "1" } : {}), ...env }, + stdio: [keyboard ? "pipe" : "ignore", "pipe", "pipe"], + }); + let text = ""; + child.stdout.on("data", (d) => (text += d)); + child.stderr.on("data", (d) => (text += d)); + const exit = new Promise((r) => child.on("exit", (code, signal) => r(code ?? signal))); + return { + child, + out: () => text, + has: (s) => text.includes(s), + press: (k) => child.stdin.write(k), + exit, + async waitFor(s, seconds = 60) { + const end = Date.now() + seconds * 1000; + while (Date.now() < end) { + if (text.includes(s)) return true; + if (child.exitCode !== null && !text.includes(s)) { + await sleep(0.2); + return text.includes(s); + } + await sleep(0.25); + } + return false; + }, + async done(seconds = 150) { + const t = setTimeout(() => child.kill("SIGKILL"), seconds * 1000); + const code = await exit; + clearTimeout(t); + if (keyboard) child.stdin.end(); + return code; + }, + }; +} +// Runs runcoder to the end without a keyboard: { code, out }. +export async function once(ctx, args, env = {}) { + const r = start(ctx, args, { env, keyboard: false }); + const code = await r.done(120); + return { code, out: r.out() }; +} +export const sleep = (s) => new Promise((r) => setTimeout(r, s * 1000)); + +// Kills a tunnel or Qwen Code window a test left running. +export function killLeftovers(ctx) { + for (const f of ["proxy.pid", "qwen.pid"]) { + try { + killTree(Number(readFileSync(join(ctx.state, f), "utf8"))); + } catch {} + } +}