diff --git a/.gitignore b/.gitignore index 252a570..d5b5f3a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules/ +captcha_node/node_modules/ *.log config.yaml .omo/evidence/ @@ -8,3 +9,6 @@ dist/ /.omo /_reverse /zcode-proxy.exe +runner/__pycache__/* +runner/explore +runner/lib/__pycache__ diff --git a/README.md b/README.md index 7878cea..24a3f8b 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,9 @@ cp config.example.yaml config.yaml # Start the proxy bun run src/index.ts +# Open the web dashboard +# http://localhost:8080/app + # Or specify a config path bun run src/index.ts /path/to/config.yaml ``` @@ -64,6 +67,93 @@ If you already use the ZCode desktop app, import the API key directly: bun run src/index.ts auth login bigmodel --import ``` +### Option 4: ZCode Start Plan (free tier, JWT + captcha) + +Start Plan uses `zcode.z.ai` with OAuth JWT and Aliyun traceless captcha — not the paid `api.z.ai` key. + +**Web dashboard (recommended):** + +```bash +bun run src/index.ts +# open http://localhost:8080/app +``` + +Click **Add account (OAuth)** — sign in, quota provisioning, and pool setup happen automatically. + +**CLI alternatives:** + +```bash +bun run src/index.ts auth onboard zai # new account +bun run src/index.ts auth import-jwt # existing ZCode desktop login +``` + +**Then configure and start:** + +```yaml +auth: + mode: oauth + proxyApiKey: "your-proxy-secret" +plan: start-plan +provider: zai + +identity: + appVersion: "3.1.2" +``` + +```bash +bun run src/index.ts +``` + +Requires Node.js for captcha solver (`captcha_node/` — installed automatically on first use). + +```bash +curl http://localhost:8080/v1/messages \ + -H "x-api-key: your-proxy-secret" \ + -H "Content-Type: application/json" \ + -d '{"model":"glm-5.2","max_tokens":32,"messages":[{"role":"user","content":"say ok"}]}' +``` + +Re-run `auth import-jwt` or `auth onboard zai` after switching accounts. **Test one message at a time** — burst captcha requests can trigger abuse block (3012). + +### Multi-account pool (one app, load balancing) + +**Use the web dashboard** at `http://localhost:8080/app` — add accounts via OAuth, import from desktop, paste JWTs, pause/remove accounts, and send test messages. No CLI required. + +Add multiple Start Plan accounts; the proxy round-robins and auto-fails over on quota (`1005`), abuse block (`3012`), or bad JWT (`401`). + +```bash +# Add accounts (each runs OAuth + optional ZCode provisioning) +bun run src/index.ts auth onboard zai --name acct-1 +bun run src/index.ts auth onboard zai --name acct-2 + +# Or add an existing JWT +bun run src/index.ts auth add acct-3 --jwt eyJ... + +# List / remove +bun run src/index.ts auth accounts +bun run src/index.ts auth remove +``` + +Enable in `config.yaml` (default when accounts exist): + +```yaml +pool: + enabled: true + maxAccountAttempts: 5 # try up to N accounts per request +``` + +HTTP admin (requires `auth.proxyApiKey`): + +```bash +curl http://localhost:8080/admin/accounts -H "x-api-key: your-proxy-secret" +curl -X POST http://localhost:8080/admin/accounts//enable -H "x-api-key: your-proxy-secret" +curl -X DELETE http://localhost:8080/admin/accounts/ -H "x-api-key: your-proxy-secret" +``` + +`GET /health` includes pool summary (account count, enabled, last errors). + +Fixes #2. + ## Endpoints | Method | Path | Description | @@ -71,7 +161,11 @@ bun run src/index.ts auth login bigmodel --import | `POST` | `/v1/chat/completions` | OpenAI-compatible chat completions (streaming + non-streaming) | | `POST` | `/v1/messages` | Anthropic-format messages (streaming + non-streaming) | | `GET` | `/v1/models` | List available models | -| `GET` | `/health` | Health check | +| `GET` | `/app` | Web dashboard (account management UI) | +| `GET` | `/health` | Health check (+ pool summary when enabled) | +| `GET` | `/admin/accounts` | List account pool (proxy API key required) | +| `POST` | `/admin/accounts/:id/enable` | Re-enable a disabled account | +| `DELETE` | `/admin/accounts/:id` | Remove account from pool | ## Usage Examples @@ -129,7 +223,8 @@ curl http://localhost:8080/v1/models \ | `auth.apiKey` | `ZCODE_API_KEY` | — | Upstream API key | | `auth.proxyApiKey` | `ZCODE_PROXY_API_KEY` | — | Client auth key | | `provider` | `ZCODE_PROVIDER` | `zai` | Upstream provider | -| `identity.appVersion` | `ZCODE_APP_VERSION` | `3.1.1` | `User-Agent: ZCode/{version}` | +| `identity.appVersion` | `ZCODE_APP_VERSION` | `3.1.2` | `User-Agent: ZCode/{version}` | +| `plan` | — | `coding-plan` | `start-plan` for ZCode free tier (JWT + captcha) | | `identity.sourceTitle` | `ZCODE_SOURCE_TITLE` | `cli` | `X-Title: Z Code@{title}` | | `identity.refererOrigin` | `ZCODE_REFERER_ORIGIN` | `https://zcode.z.ai` | `HTTP-Referer` URL | diff --git a/bun.lock b/bun.lock index de3a316..7aceed7 100644 --- a/bun.lock +++ b/bun.lock @@ -10,9 +10,6 @@ "devDependencies": { "@types/bun": "latest", }, - "optionalDependencies": { - "playwright": "^1.61.0", - }, }, }, "packages": { @@ -22,12 +19,6 @@ "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], - "fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="], - - "playwright": ["playwright@1.61.0", "", { "dependencies": { "playwright-core": "1.61.0" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-Z+7BeeqQPRRzklHsVFP4KTGIyMxKUmfeRA4WisM6G3/XW6nwGeX6fX9qYaDa+CiUqpOkb2f6X3nar05R3kSuJQ=="], - - "playwright-core": ["playwright-core@1.61.0", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-caX7TrY3Ml6egyDX0WUcTHDxodl/b51y5wJOdCEA36QviK/s2g081hvmGs8eaE3DWb6NYZQ6BjO/QkNRPenoPA=="], - "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], "yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="], diff --git a/captcha_node/package-lock.json b/captcha_node/package-lock.json new file mode 100644 index 0000000..f94d100 --- /dev/null +++ b/captcha_node/package-lock.json @@ -0,0 +1,783 @@ +{ + "name": "zcode-proxy-captcha-solver", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "zcode-proxy-captcha-solver", + "version": "1.0.0", + "dependencies": { + "jsdom": "^24.1.0" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/cssstyle/node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "license": "MIT" + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "license": "MIT" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "24.1.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-24.1.3.tgz", + "integrity": "sha512-MyL55p3Ut3cXbeBEG7Hcv0mVM8pp8PBNWxRqchZnSfAiES1v1mRnMeFfaHWIPULpwsYfvO+ZmMZz5tGCnjzDUQ==", + "license": "MIT", + "dependencies": { + "cssstyle": "^4.0.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.4.3", + "form-data": "^4.0.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.5", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.12", + "parse5": "^7.1.2", + "rrweb-cssom": "^0.7.1", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^4.1.4", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^2.11.2" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nwsapi": { + "version": "2.2.24", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.24.tgz", + "integrity": "sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==", + "license": "MIT" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/psl": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz", + "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "funding": { + "url": "https://github.com/sponsors/lupomontero" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "license": "MIT" + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, + "node_modules/rrweb-cssom": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz", + "integrity": "sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==", + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", + "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "license": "BSD-3-Clause", + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.2.0", + "url-parse": "^1.5.3" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/universalify": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", + "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "license": "MIT" + } + } +} diff --git a/captcha_node/package.json b/captcha_node/package.json new file mode 100644 index 0000000..bb2c188 --- /dev/null +++ b/captcha_node/package.json @@ -0,0 +1,11 @@ +{ + "name": "zcode-proxy-captcha-solver", + "version": "1.0.0", + "private": true, + "description": "Headless Aliyun traceless captcha solver (jsdom)", + "type": "commonjs", + "main": "solver.js", + "dependencies": { + "jsdom": "^24.1.0" + } +} diff --git a/captcha_node/solver.js b/captcha_node/solver.js new file mode 100644 index 0000000..12b46b2 --- /dev/null +++ b/captcha_node/solver.js @@ -0,0 +1,213 @@ +const { JSDOM, VirtualConsole } = require('jsdom'); +const SCENE = process.argv[2] || '11xygtvd'; +const REGION = process.argv[3] || 'sgp'; +const PREFIX = process.argv[4] || 'no8xfe'; +const vc = new VirtualConsole(); +vc.on('error', (...a) => process.stderr.write('[jsdom] ' + a.join(' ') + '\n')); +vc.on('warn', (...a) => process.stderr.write('[jsdom warn] ' + a.join(' ') + '\n')); +const html = ` +
+ +`; +const USER_AGENT = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'; +function applyPolyfills(window) { + window.matchMedia = () => ({ + matches: false, + media: '', + onchange: null, + addListener() {}, + removeListener() {}, + addEventListener() {}, + removeEventListener() {}, + dispatchEvent() { + return false; + }, + }); + const proto = window.HTMLCanvasElement.prototype; + proto.getContext = function (type) { + if (/webgl/i.test(type)) { + return { + canvas: this, + getParameter: () => 'Intel Inc.', + getExtension: () => null, + getSupportedExtensions: () => ['WEBGL_debug_renderer_info'], + getContextAttributes: () => ({}), + getShaderPrecisionFormat: () => ({ precision: 23, rangeMin: 127, rangeMax: 127 }), + }; + } + return { + canvas: this, + fillRect() {}, + clearRect() {}, + getImageData: (x, y, w = 1, h = 1) => ({ data: new Uint8ClampedArray(w * h * 4) }), + putImageData() {}, + createImageData: (w = 1, h = 1) => ({ data: new Uint8ClampedArray(w * h * 4) }), + setTransform() {}, + transform() {}, + drawImage() {}, + save() {}, + restore() {}, + beginPath() {}, + moveTo() {}, + lineTo() {}, + bezierCurveTo() {}, + quadraticCurveTo() {}, + closePath() {}, + clip() {}, + stroke() {}, + fill() {}, + arc() {}, + rect() {}, + ellipse() {}, + translate() {}, + scale() {}, + rotate() {}, + fillText() {}, + strokeText() {}, + measureText: (t) => ({ width: ('' + t).length * 8 }), + createLinearGradient: () => ({ addColorStop() {} }), + createRadialGradient: () => ({ addColorStop() {} }), + createPattern: () => ({}), + isPointInPath: () => false, + font: '10px sans-serif', + textBaseline: 'alphabetic', + textAlign: 'start', + fillStyle: '#000', + strokeStyle: '#000', + globalAlpha: 1, + lineWidth: 1, + shadowBlur: 0, + shadowColor: '', + }; + }; + proto.toDataURL = () => + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='; + proto.toBlob = (cb) => cb && cb(null); + window.Worker = class { + constructor() {} + postMessage() {} + terminate() {} + addEventListener() {} + removeEventListener() {} + onmessage = null; + onerror = null; + }; + window.OffscreenCanvas = + window.OffscreenCanvas || + class { + constructor(w, h) { + this.width = w; + this.height = h; + } + getContext() { + return proto.getContext.call(this); + } + }; + try { + Object.defineProperty(window.document, 'hidden', { value: false, configurable: true }); + Object.defineProperty(window.document, 'visibilityState', { + value: 'visible', + configurable: true, + }); + } catch (_) {} + const nav = window.navigator; + const navPatch = { + userAgent: USER_AGENT, + platform: 'Win32', + language: 'en-US', + languages: ['en-US', 'en'], + vendor: 'Google Inc.', + webdriver: false, + hardwareConcurrency: 8, + deviceMemory: 8, + maxTouchPoints: 0, + cookieEnabled: true, + plugins: { length: 3, item: () => null, namedItem: () => null, refresh() {} }, + mimeTypes: { length: 0, item: () => null, namedItem: () => null }, + }; + for (const [k, v] of Object.entries(navPatch)) { + try { + Object.defineProperty(nav, k, { value: v, configurable: true }); + } catch (_) {} + } + window.screen = { + width: 1920, + height: 1080, + availWidth: 1920, + availHeight: 1040, + colorDepth: 24, + pixelDepth: 24, + }; + window.chrome = { runtime: {} }; + window.outerWidth = 1920; + window.outerHeight = 1080; + window.innerWidth = 1280; + window.innerHeight = 720; + window.devicePixelRatio = 1; +} +const dom = new JSDOM(html, { + url: 'https://zcode.z.ai/', + runScripts: 'dangerously', + resources: 'usable', + pretendToBeVisual: true, + virtualConsole: vc, + userAgent: USER_AGENT, + beforeParse(window) { + applyPolyfills(window); + window.AliyunCaptchaConfig = { region: REGION, prefix: PREFIX }; + }, +}); +const { window } = dom; +function waitFor(cond, t = 12000) { + return new Promise((res, rej) => { + const s = Date.now(); + const i = setInterval(() => { + let ok = false; + try { + ok = cond(); + } catch (_) {} + if (ok) { + clearInterval(i); + res(); + } else if (Date.now() - s > t) { + clearInterval(i); + rej(new Error('timeout')); + } + }, 80); + }); +} +(async () => { + await waitFor(() => typeof window.initAliyunCaptcha === 'function'); + window.initAliyunCaptcha({ + SceneId: SCENE, + mode: 'popup', + region: REGION, + prefix: PREFIX, + language: 'en', + element: '#cap', + button: '#btn', + captchaLogoImg: '', + showErrorTip: false, + getInstance: (inst) => { + try { + (inst.startTracelessVerification || inst.show).call(inst); + } catch (e) { + console.error('start', e.message); + } + }, + success: (param) => { + console.log('VERIFY_PARAM=' + param); + process.exit(0); + }, + fail: (err) => { + process.stderr.write('fail=' + JSON.stringify(err) + '\n'); + process.exit(4); + }, + onError: (err) => { + process.stderr.write('onError=' + JSON.stringify(err) + '\n'); + process.exit(5); + }, + }); + setTimeout(() => process.exit(2), 25000); +})().catch(() => process.exit(3)); diff --git a/config.example.yaml b/config.example.yaml index cbb528f..9e31429 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -3,11 +3,11 @@ server: host: "0.0.0.0" auth: - # "apikey" = use a pre-obtained API key directly - # "oauth" = use OAuth login flow (run `bun run src/cli/login.ts` first) + # "apikey" = use a pre-obtained API key directly (coding-plan) + # "oauth" = use OAuth or import-jwt (required for start-plan) mode: apikey - # For apikey mode: + # For apikey mode (coding-plan): # Z.AI: "yourApiKey.yourSecretKey" # Bigmodel: "yourApiKey" apiKey: "YOUR_API_KEY_HERE" @@ -16,15 +16,12 @@ auth: # Set to null/omit to disable client auth. proxyApiKey: "your-proxy-secret" - # For oauth mode (path to stored credentials from login flow): - # oauthCredentialsPath: "~/.zcode-proxy/credentials.json" - # Which upstream provider to use: "zai" or "bigmodel" provider: zai # Which plan tier to use: -# "coding-plan" (default) — direct upstream endpoints, permanent API key -# "start-plan" — routes through zcode.z.ai with JWT auth (requires `auth login`) +# "coding-plan" (default) — api.z.ai with API key, no captcha +# "start-plan" — zcode.z.ai with JWT + Aliyun captcha (see README) plan: coding-plan providers: @@ -48,18 +45,17 @@ models: - glm-5.1 - glm-5.2 -# Identity headers injected on every upstream request to mimic the ZCode -# desktop client (User-Agent, X-ZCode-App-Version, X-Title, X-ZCode-Agent, -# HTTP-Referer). All optional; env vars override YAML, which overrides defaults. identity: - # Mirrors process.env.ZCODE_APP_VERSION in the ZCode bundle. - # Must be printable ASCII; non-conforming values fall back to the default. - # Default: "3.1.1" (current ZCode release). Override to match your real client. - appVersion: "3.1.1" - # X-Title suffix → "Z Code@{sourceTitle}". Default "cli". + # Must match your ZCode desktop app version for start-plan. + appVersion: "3.1.2" sourceTitle: "cli" - # HTTP-Referer URL. Default "https://zcode.z.ai". refererOrigin: "https://zcode.z.ai" +pool: + enabled: true + maxAccountAttempts: 5 + quotaRefreshIntervalSec: 300 + quotaFetchDelaySec: 5 + logging: level: info diff --git a/package.json b/package.json index 3573a00..78ec3bd 100644 --- a/package.json +++ b/package.json @@ -10,9 +10,6 @@ "dependencies": { "yaml": "^2.5.0" }, - "optionalDependencies": { - "playwright": "^1.61.0" - }, "devDependencies": { "@types/bun": "latest" } diff --git a/runner/.env.example b/runner/.env.example new file mode 100644 index 0000000..4c3a6b3 --- /dev/null +++ b/runner/.env.example @@ -0,0 +1,42 @@ +# Copy to .env and fill in: +# cp .env.example .env + +# Sequential accounts: zcode1@codexin.lol, zcode2@..., saved to state/accounts.jsonl +EMAIL_PREFIX=zcode +EMAIL_DOMAIN=codexin.lol +EMAIL_START_INDEX=1 +ACCOUNT_PASSWORD=Zcode@123 +ACCOUNT_USERNAME=Zcode + +# Resend inbound email (verification link/code) +RESEND_API_KEY=re_xxxxxxxx + +# Proxy must be running: bun run src/index.ts +PROXY_URL=http://127.0.0.1:8080 + +# Browser +HEADLESS=false +SLOW_MO_MS=80 +STEP_TIMEOUT_MS=90000 +PROFILES_DIR=profiles +STATE_DIR=state +BATCH_COUNT=1 +SPAWN_COUNT=1 +# Seconds between launching each spawned runner (random in range) +SPAWN_STAGGER_MIN_SEC=5 +SPAWN_STAGGER_MAX_SEC=10 + +# Z.AI signup (Open WebUI at /auth) +SIGNUP_URL=https://chat.z.ai/auth + +# Onboard / quota waits (gentle polling — do not lower much) +ONBOARD_POLL_SEC=5 +QUOTA_POLL_SEC=8 +ONBOARD_TIMEOUT_SEC=300 +QUOTA_TIMEOUT_SEC=300 +LAUNCH_ZCODE=true + +# Desktop notification when captcha needed +CAPTCHA_NOTIFY_MSG=please do the captcha +CAPTCHA_POLL_INTERVAL_SEC=1 +CAPTCHA_TIMEOUT_SEC=600 diff --git a/runner/.gitignore b/runner/.gitignore new file mode 100644 index 0000000..5059142 --- /dev/null +++ b/runner/.gitignore @@ -0,0 +1,5 @@ +profiles/ +results/ +state/ +.env +explore-chrome-profile/ diff --git a/runner/README.md b/runner/README.md new file mode 100644 index 0000000..8a2704c --- /dev/null +++ b/runner/README.md @@ -0,0 +1,80 @@ +# Z.AI account runner + +Headed Playwright runner that creates Z.AI accounts and links them into **zcode-proxy**. + +## Prerequisites + +1. **zcode-proxy** running locally: + + ```bash + cd .. && bun run src/index.ts + ``` + +2. **Resend** inbound domain configured (`RESEND_API_KEY`, `EMAIL_DOMAIN`). + +3. **Chromium** for Playwright: + + ```bash + pip install -r requirements.txt + playwright install chromium + ``` + +## Setup + +```bash +cd runner +cp .env.example .env +# Edit .env — RESEND_API_KEY, EMAIL_DOMAIN, ACCOUNT_PASSWORD +``` + +## Run + +```bash +python run.py --count 3 +python run_spawn.py --count 4 # 4 browsers, staggered 5–10s apart, unique zcodeN@ +``` + +Each account: + + +1. Fresh Chromium profile (`profiles/run-*`) +2. Sign up on Z.AI → verification email via Resend API +3. **Captcha #1** — `notify-send "please do the captcha"`, then press Enter +4. Open proxy dashboard → **Sign in with Z.AI** → OAuth tab +5. **Captcha #2** — same notification + Enter +6. Login + authorize → proxy polls OAuth and provisions quota +7. Profile directory deleted + +## Account naming + +Emails auto-increment: `zcode1@codexin.lol`, `zcode2@...` (configurable via `EMAIL_PREFIX`, `EMAIL_START_INDEX`). + +| Env | Default | +|-----|---------| +| `EMAIL_PREFIX` | `zcode` | +| `EMAIL_DOMAIN` | `codexin.lol` | +| `ACCOUNT_PASSWORD` | `Zcode@123` | +| `ACCOUNT_USERNAME` | `Zcode` | + +Successful accounts append to `state/accounts.jsonl`. **JWTs** are backed up separately to `state/tokens.jsonl` (email, password, jwt, pool id). Failures go to `state/failed.jsonl`. + +After OAuth, the runner waits for the proxy **onboard job** to finish (polls every 5s by default). When the job reports `quotaReady`, it continues immediately — it does **not** wait for the dashboard quota cache refresh cycle. + +## Options + +| Flag | Description | +|------|-------------| +| `--count N` | Accounts to create (default: `1` or `BATCH_COUNT`) | +| `run_spawn.py --count N` | N separate `run.py` processes, unique reserved emails | +| `--headless` | Headless browser (default: **headed**) | +| `--no-zcode` | Skip launching ZCode desktop during quota provisioning | + +## Env tuning + +- `SIGNUP_URL`, `SIGNUP_*_SELECTOR` — if Z.AI signup UI changes +- `ONBOARD_POLL_SEC` — seconds between onboard status polls (default 5) +- `QUOTA_POLL_SEC` — only used if onboard finishes without `quotaReady` (fallback quota-cache poll; default 8) +- `USE_DASHBOARD_SIGNIN=false` — use admin API + direct authorize URL instead of dashboard button +- `CAPTCHA_NOTIFY_MSG` — desktop notification text (default: `please do the captcha`) + +Results are written to `results/batch-{ok}-of-{count}.json`. diff --git a/runner/explore_cdp.py b/runner/explore_cdp.py new file mode 100644 index 0000000..3c87e1a --- /dev/null +++ b/runner/explore_cdp.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Connect to headed Chrome/Brave on CDP and dump page state for flow exploration.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +from playwright.sync_api import sync_playwright + +CDP_URL = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:9223" +OUT = Path(__file__).parent / "explore" +OUT.mkdir(exist_ok=True) + + +def dump(page, label: str) -> None: + safe = label.replace("/", "_").replace(" ", "_")[:80] + page.screenshot(path=str(OUT / f"{safe}.png"), full_page=True) + (OUT / f"{safe}.url").write_text(page.url, encoding="utf-8") + (OUT / f"{safe}.html").write_text(page.content(), encoding="utf-8") + + roles: dict[str, list[str]] = {} + for role in ["heading", "button", "link", "textbox", "checkbox", "tab"]: + names: list[str] = [] + for node in page.get_by_role(role).all()[:40]: + try: + t = node.inner_text(timeout=500).strip().replace("\n", " ")[:120] + if t: + names.append(t) + except Exception: + pass + if names: + roles[role] = names + + inputs = [] + for inp in page.locator("input, textarea, select").all()[:30]: + try: + inputs.append( + { + "tag": inp.evaluate("el => el.tagName"), + "type": inp.get_attribute("type"), + "name": inp.get_attribute("name"), + "placeholder": inp.get_attribute("placeholder"), + "id": inp.get_attribute("id"), + "visible": inp.is_visible(), + } + ) + except Exception: + pass + + meta = {"url": page.url, "title": page.title(), "roles": roles, "inputs": inputs} + (OUT / f"{safe}.json").write_text(json.dumps(meta, indent=2), encoding="utf-8") + print(f"\n=== {label} ===") + print(f"URL: {page.url}") + print(f"Title: {page.title()}") + for role, names in roles.items(): + print(f" {role}: {names[:8]}") + print(f" inputs: {len(inputs)}") + print(f" saved → explore/{safe}.*") + + +def main() -> None: + steps = sys.argv[2:] if len(sys.argv) > 2 else ["status"] + pw = sync_playwright().start() + browser = pw.chromium.connect_over_cdp(CDP_URL) + context = browser.contexts[0] if browser.contexts else browser.new_context() + page = context.pages[0] if context.pages else context.new_page() + + if "status" in steps: + print(f"Connected CDP {CDP_URL}") + print(f"Contexts: {len(browser.contexts)}") + for i, p in enumerate(context.pages): + print(f" tab[{i}] {p.url}") + + for step in steps: + if step == "status": + continue + if step.startswith("goto:"): + url = step[5:] + print(f"Navigating → {url}") + page.goto(url, wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(2000) + dump(page, url.split("//")[-1].replace("?", "_")[:60]) + elif step.startswith("dump:"): + dump(page, step[5:]) + elif step == "tabs": + for i, p in enumerate(context.pages): + print(f"tab[{i}] {p.url}") + + pw.stop() + + +if __name__ == "__main__": + main() diff --git a/runner/explore_flow.py b/runner/explore_flow.py new file mode 100644 index 0000000..dba301d --- /dev/null +++ b/runner/explore_flow.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Interactive CDP flow exploration — click through signup/login paths.""" + +from __future__ import annotations + +import os + +from playwright.sync_api import sync_playwright + +CDP = os.environ.get("CDP_URL", "http://127.0.0.1:9223") +OUT = __import__("pathlib").Path(__file__).parent / "explore" + + +def snap(page, name: str) -> None: + OUT.mkdir(exist_ok=True) + page.screenshot(path=str(OUT / f"{name}.png"), full_page=True) + (OUT / f"{name}.url").write_text(page.url) + print(f"{name}: {page.url}") + + +def try_click(page, selectors: list[str], label: str) -> bool: + for sel in selectors: + loc = page.locator(sel).first + try: + if loc.count() and loc.is_visible(): + print(f"click {label}: {sel}") + loc.click() + page.wait_for_timeout(2500) + return True + except Exception as e: + print(f" skip {sel}: {e}") + return False + + +def main() -> None: + pw = sync_playwright().start() + browser = pw.chromium.connect_over_cdp(CDP) + ctx = browser.contexts[0] + page = ctx.new_page() + + # --- 1. Z.AI homepage → find login/signup --- + page.goto("https://chat.z.ai/", wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(3000) + snap(page, "01_home") + + # Bottom-left profile / login triggers + try_click( + page, + [ + 'text="Log in"', + 'text="Sign in"', + 'text="登录"', + 'text="注册"', + 'button:has-text("Log in")', + 'button:has-text("Sign in")', + '[class*="avatar"]', + '[class*="user"]', + 'img[alt*="avatar" i]', + ], + "login_entry", + ) + snap(page, "02_after_login_click") + + # Try sending a message (may prompt login) + chat = page.locator("#chat-input, textarea").first + if chat.count() and chat.is_visible(): + chat.fill("test login prompt") + page.keyboard.press("Enter") + page.wait_for_timeout(3000) + snap(page, "03_after_send") + + # Direct auth URLs to try + for url in [ + "https://chat.z.ai/login", + "https://chat.z.ai/signup", + "https://chat.z.ai/register", + "https://open.bigmodel.cn/usercenter/login", + "https://z.ai/login", + ]: + try: + page.goto(url, wait_until="domcontentloaded", timeout=30000) + page.wait_for_timeout(2000) + safe = url.split("//")[-1].replace("/", "_") + snap(page, f"04_direct_{safe}") + if page.locator('input[type="email"], input[type="password"]').count(): + print(f"FOUND auth form at {url}") + break + except Exception as e: + print(f"fail {url}: {e}") + + # --- 2. Proxy dashboard --- + page.goto("http://127.0.0.1:8080/app", wait_until="domcontentloaded", timeout=30000) + page.wait_for_timeout(2000) + snap(page, "05_proxy_app") + + sign_in = page.locator("#btn-signin:visible, #btn-signin-empty:visible").first + if sign_in.count(): + print("Found proxy sign-in button") + with page.expect_response(lambda r: "/admin/onboard/start" in r.url) as resp_info: + with ctx.expect_page() as pop: + sign_in.click() + oauth = pop.value + job = resp_info.value.json() + print(f"onboard job: {job.get('id')}") + print(f"authorize: {job.get('authorizeUrl')}") + oauth.wait_for_load_state("domcontentloaded") + page.wait_for_timeout(3000) + snap(oauth, "06_oauth_authorize") + (OUT / "06_oauth_authorize.json").write_text( + __import__("json").dumps( + { + "url": oauth.url, + "inputs": [ + { + "type": i.get_attribute("type"), + "name": i.get_attribute("name"), + "placeholder": i.get_attribute("placeholder"), + } + for i in oauth.locator("input").all()[:20] + ], + "buttons": oauth.locator("button").all_inner_texts()[:15], + }, + indent=2, + ) + ) + + pw.stop() + print("done — see runner/explore/") + + +if __name__ == "__main__": + main() diff --git a/runner/explore_session.py b/runner/explore_session.py new file mode 100644 index 0000000..1209d90 --- /dev/null +++ b/runner/explore_session.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +""" +Launch fresh headed Chromium on a debug port, connect via CDP, explore flows. +Keeps the browser alive for the whole session (does not use Brave). +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import time +import urllib.request +from pathlib import Path + +from playwright.sync_api import sync_playwright + +ROOT = Path(__file__).parent +OUT = ROOT / "explore" +PORT = int(os.environ.get("DEBUG_PORT", "9223")) +CDP = f"http://127.0.0.1:{PORT}" +PROFILE = ROOT / "explore-chrome-profile" +CHROME = os.environ.get( + "CHROME", + str(Path.home() / ".cache/ms-playwright/chromium-1223/chrome-linux64/chrome"), +) + + +def wait_cdp(timeout: float = 30) -> None: + deadline = time.time() + timeout + url = f"{CDP}/json/version" + while time.time() < deadline: + try: + with urllib.request.urlopen(url, timeout=2) as r: + if r.status == 200: + return + except Exception: + time.sleep(0.25) + raise TimeoutError(f"CDP not ready on {CDP}") + + +def launch_chrome() -> subprocess.Popen: + PROFILE.mkdir(parents=True, exist_ok=True) + for lock in PROFILE.glob("Singleton*"): + try: + lock.unlink() + except OSError: + pass + + env = os.environ.copy() + env.setdefault("DISPLAY", ":0") + + cmd = [ + CHROME, + f"--remote-debugging-port={PORT}", + f"--user-data-dir={PROFILE}", + "--no-first-run", + "--no-default-browser-check", + "--disable-session-crashed-bubble", + "--no-sandbox", + "--disable-dev-shm-usage", + "about:blank", + ] + print(f"Launching Chromium → CDP {CDP}") + print(f"Profile: {PROFILE}") + proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) + wait_cdp() + print("CDP ready") + return proc + + +def snap(page, name: str) -> dict: + OUT.mkdir(exist_ok=True) + page.screenshot(path=str(OUT / f"{name}.png"), full_page=True) + (OUT / f"{name}.url").write_text(page.url, encoding="utf-8") + + meta = { + "url": page.url, + "title": page.title(), + "buttons": page.locator("button").all_inner_texts()[:25], + "links": page.locator("a").all_inner_texts()[:25], + "inputs": [ + { + "type": el.get_attribute("type"), + "name": el.get_attribute("name"), + "placeholder": el.get_attribute("placeholder"), + "id": el.get_attribute("id"), + "visible": el.is_visible(), + } + for el in page.locator("input, textarea").all()[:25] + ], + } + (OUT / f"{name}.json").write_text(json.dumps(meta, indent=2), encoding="utf-8") + print(f"\n[{name}] {page.url}") + return meta + + +def try_clicks(page, labels: list[str]) -> None: + for text in labels: + for sel in [f'button:has-text("{text}")', f'a:has-text("{text}")', f'text="{text}"']: + loc = page.locator(sel).first + try: + if loc.count() and loc.is_visible(): + print(f" click → {text}") + loc.click() + page.wait_for_timeout(2000) + return + except Exception: + pass + + +def explore_signup(page) -> None: + page.goto("https://chat.z.ai/", wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(3000) + snap(page, "01_chat_home") + + # Guest / logged-out entry points + try_clicks(page, ["Log in", "Sign in", "登录", "注册", "Sign up", "Register"]) + + # Bottom-left avatar area (logged-out shows login) + for sel in [ + '[class*="avatar"]', + '[class*="user-info"]', + 'div[class*="sidebar"] >> nth=-1', + ]: + try: + loc = page.locator(sel).first + if loc.count() and loc.is_visible(): + loc.click() + page.wait_for_timeout(2000) + snap(page, "02_after_avatar") + try_clicks(page, ["Log in", "Sign in", "登录", "注册", "Sign up"]) + break + except Exception: + pass + + snap(page, "03_login_state") + + # Known auth URL patterns + for path in ["/login", "/signin", "/signup", "/register", "/auth/login"]: + url = f"https://chat.z.ai{path}" + try: + page.goto(url, wait_until="domcontentloaded", timeout=30000) + page.wait_for_timeout(2000) + meta = snap(page, f"04_path_{path.strip('/')}") + if any(i.get("type") in ("email", "password", "text") for i in meta["inputs"]): + print(f" ** auth form at {url}") + return + except Exception as exc: + print(f" skip {url}: {exc}") + + # bigmodel passport (Zhipu account system) + for url in [ + "https://open.bigmodel.cn/usercenter/login", + "https://passport.bigmodel.cn/login", + ]: + try: + page.goto(url, wait_until="domcontentloaded", timeout=30000) + page.wait_for_timeout(2000) + snap(page, f"05_{url.split('//')[-1].replace('/', '_')}") + except Exception as exc: + print(f" skip {url}: {exc}") + + +def explore_proxy_oauth(ctx, page) -> None: + page.goto("http://127.0.0.1:8080/app", wait_until="domcontentloaded", timeout=30000) + page.wait_for_timeout(2000) + snap(page, "10_proxy_dashboard") + + sign_in = page.locator("#btn-signin:visible, #btn-signin-empty:visible").first + if not sign_in.count(): + print("No sign-in button on dashboard") + return + + with page.expect_response(lambda r: "/admin/onboard/start" in r.url and r.request.method == "POST") as resp_info: + with ctx.expect_page(timeout=60000) as pop_info: + sign_in.click() + oauth = pop_info.value + + job = resp_info.value.json() + print(f"onboard id={job.get('id')}") + print(f"authorize={job.get('authorizeUrl')}") + + oauth.wait_for_load_state("domcontentloaded", timeout=60000) + page.wait_for_timeout(3000) + snap(oauth, "11_oauth_authorize") + + +def main() -> int: + # Reuse running CDP if already up + chrome_proc = None + try: + wait_cdp(timeout=2) + print(f"Reusing existing CDP at {CDP}") + except TimeoutError: + chrome_proc = launch_chrome() + + pw = sync_playwright().start() + try: + browser = pw.chromium.connect_over_cdp(CDP) + ctx = browser.contexts[0] if browser.contexts else browser.new_context() + page = ctx.pages[0] if ctx.pages else ctx.new_page() + + explore_signup(page) + explore_proxy_oauth(ctx, page) + + print(f"\nArtifacts → {OUT}/") + print("Browser left open on CDP", CDP) + finally: + pw.stop() + # Do NOT kill chrome — user can inspect manually + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/runner/lib/__init__.py b/runner/lib/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/runner/lib/account_store.py b/runner/lib/account_store.py new file mode 100644 index 0000000..ab799f6 --- /dev/null +++ b/runner/lib/account_store.py @@ -0,0 +1,124 @@ +"""Sequential accounts: zcode1@codexin.lol, zcode2@..., persisted to state/.""" + +from __future__ import annotations + +import fcntl +import json +import os +import threading +from contextlib import contextmanager +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path + +STATE_DIR = Path(os.environ.get("STATE_DIR", "state")) +INDEX_FILE = STATE_DIR / "email_index.json" +ACCOUNTS_FILE = STATE_DIR / "accounts.jsonl" +FAILED_FILE = STATE_DIR / "failed.jsonl" +INDEX_LOCK_FILE = STATE_DIR / ".index.lock" +_WRITE_LOCK = threading.Lock() + + +@contextmanager +def _index_lock(): + STATE_DIR.mkdir(parents=True, exist_ok=True) + with INDEX_LOCK_FILE.open("a+", encoding="utf-8") as fh: + fcntl.flock(fh.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(fh.fileno(), fcntl.LOCK_UN) + + +@dataclass +class Account: + email: str + index: int + password: str + username: str + + +def _account_defaults() -> tuple[str, str, str, str]: + prefix = os.environ.get("EMAIL_PREFIX", "zcode") + domain = os.environ.get("EMAIL_DOMAIN", "codexin.lol") + if "@" in domain: + domain = domain.split("@")[-1] + password = os.environ.get("ACCOUNT_PASSWORD", "Zcode@123") + username = os.environ.get("ACCOUNT_USERNAME", "Zcode") + return prefix, domain, password, username + + +def _load_next_index() -> int: + STATE_DIR.mkdir(parents=True, exist_ok=True) + if not INDEX_FILE.exists(): + return int(os.environ.get("EMAIL_START_INDEX", "1")) + data = json.loads(INDEX_FILE.read_text(encoding="utf-8")) + return int(data["next_index"]) + + +def _save_next_index(next_index: int) -> None: + STATE_DIR.mkdir(parents=True, exist_ok=True) + INDEX_FILE.write_text(json.dumps({"next_index": next_index}, indent=2) + "\n", encoding="utf-8") + + +def account_at_index(index: int) -> Account: + prefix, domain, password, username = _account_defaults() + email = f"{prefix}{index}@{domain}" + return Account(email=email, index=index, password=password, username=username) + + +def reserve_accounts(count: int) -> list[Account]: + """Reserve `count` sequential emails and advance the index upfront (parallel-safe).""" + count = max(1, count) + with _index_lock(): + start = _load_next_index() + _save_next_index(start + count) + return [account_at_index(start + i) for i in range(count)] + + +def next_account() -> Account: + with _index_lock(): + index = _load_next_index() + return account_at_index(index) + + +def advance_index() -> None: + with _index_lock(): + _save_next_index(_load_next_index() + 1) + + +def save_account(account: Account, *, extra: dict | None = None, advance: bool = True) -> None: + STATE_DIR.mkdir(parents=True, exist_ok=True) + entry = { + **asdict(account), + "saved_at": datetime.now(timezone.utc).isoformat(), + **(extra or {}), + } + with _WRITE_LOCK: + with ACCOUNTS_FILE.open("a", encoding="utf-8") as f: + f.write(json.dumps(entry) + "\n") + if advance: + advance_index() + print(f"Saved account → {ACCOUNTS_FILE} ({account.email})") + + +def record_failure( + account: Account, + reason: str, + *, + stage: str, + advance: bool = True, +) -> None: + STATE_DIR.mkdir(parents=True, exist_ok=True) + entry = { + **asdict(account), + "reason": reason, + "stage": stage, + "failed_at": datetime.now(timezone.utc).isoformat(), + } + with _WRITE_LOCK: + with FAILED_FILE.open("a", encoding="utf-8") as f: + f.write(json.dumps(entry) + "\n") + if advance: + advance_index() + print(f"Failed account logged → {FAILED_FILE} ({account.email})") diff --git a/runner/lib/browser.py b/runner/lib/browser.py new file mode 100644 index 0000000..e1f5868 --- /dev/null +++ b/runner/lib/browser.py @@ -0,0 +1,67 @@ +"""Browser profile lifecycle — fresh profile per account run.""" + +from __future__ import annotations + +import os +import random +import shutil +import time +import uuid +from pathlib import Path + +from playwright.sync_api import BrowserContext, Page, sync_playwright + +from lib.account_store import Account, next_account + +PROFILES_DIR = Path(os.environ.get("PROFILES_DIR", "profiles")) +HEADLESS = os.environ.get("HEADLESS", "false").lower() in ("1", "true", "yes") +SLOW_MO_MS = int(os.environ.get("SLOW_MO_MS", "80")) +STEP_TIMEOUT_MS = int(os.environ.get("STEP_TIMEOUT_MS", "90000")) + + +def human_pause(min_s: float = 0.4, max_s: float = 1.0) -> None: + time.sleep(random.uniform(min_s, max_s)) + + +def new_credentials() -> dict[str, str]: + acct = next_account() + return { + "email": acct.email, + "password": acct.password, + "username": acct.username, + "index": str(acct.index), + } + + +def launch_fresh_context(profile_dir: Path) -> tuple[object, BrowserContext]: + profile_dir.mkdir(parents=True, exist_ok=True) + pw = sync_playwright().start() + context = pw.chromium.launch_persistent_context( + user_data_dir=str(profile_dir), + headless=HEADLESS, + slow_mo=SLOW_MO_MS, + viewport={"width": 1320, "height": 900}, + args=["--disable-blink-features=AutomationControlled"], + ) + return pw, context + + +def delete_profile(profile_dir: Path) -> None: + shutil.rmtree(profile_dir, ignore_errors=True) + + +def new_profile_dir() -> Path: + return PROFILES_DIR / f"run-{uuid.uuid4().hex}" + + +def fill_verification_code(page: Page, code: str) -> None: + inputs = page.locator('input[inputmode="numeric"], input[autocomplete="one-time-code"]') + if inputs.count() >= len(code): + for i, ch in enumerate(code): + inputs.nth(i).fill(ch) + return + single = page.locator( + 'input[name="code"], input[type="text"][placeholder*="code" i], input[type="tel"]' + ).first + single.wait_for(state="visible", timeout=STEP_TIMEOUT_MS) + single.fill(code) diff --git a/runner/lib/captcha.py b/runner/lib/captcha.py new file mode 100644 index 0000000..5d66c07 --- /dev/null +++ b/runner/lib/captcha.py @@ -0,0 +1,222 @@ +"""Wait for manual Aliyun captcha — notify-send + auto-detect when solved.""" + +from __future__ import annotations + +import os +import re +import subprocess +import sys +import time +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from playwright.sync_api import Page + +POLL_INTERVAL_SEC = float(os.environ.get("CAPTCHA_POLL_INTERVAL_SEC", "1")) +POLL_TIMEOUT_SEC = float(os.environ.get("CAPTCHA_TIMEOUT_SEC", "600")) + +# Z.AI Open WebUI / Aliyun captcha success markers (from manual exploration) +_PASSED_TEXT = re.compile( + r"verification passed|verify success|验证通过|验证成功|captcha success", + re.I, +) +_PENDING_TEXT = re.compile( + r"click to start verification|请完成验证|滑动验证|请进行验证|点击开始验证|点击.*验证", + re.I, +) +_START_CLICK_TEXT = re.compile( + r"click to start verification|点击开始验证|点击按钮开始验证|请完成验证|请进行验证", + re.I, +) +_CAPTCHA_WIDGET_SELECTORS = ( + "#aliyunCaptcha", + "#captcha-element", + "#captcha-button", + '[id*="aliyunCaptcha"]', + '[id*="captcha-element"]', + '[class*="aliyun-captcha"]', + '[class*="captcha-verify"]', + '[class*="captcha"]', +) +_SLIDER_SELECTORS = ( + '[class*="slider"]', + '[id*="slider"]', + '[class*="slide-verify"]', + '[class*="puzzle"]', + "canvas", +) + + +def _captcha_passed(page: Page) -> bool: + try: + if page.get_by_text(_PASSED_TEXT).count(): + loc = page.get_by_text(_PASSED_TEXT).first + if loc.is_visible(): + return True + + body = page.locator("body").inner_text(timeout=2000).lower() + if "verification passed" in body or "验证通过" in body: + return True + + # Pending UI gone and no obvious captcha modal + if not page.get_by_text(_PENDING_TEXT).count(): + # Only treat as done if we previously had pending OR captcha widget visible + slider = page.locator( + '[class*="captcha"], [id*="captcha"], iframe[src*="captcha"], #aliyunCaptcha' + ) + if slider.count() == 0: + return False + except Exception: + pass + return False + + +def _slider_visible(page: Page) -> bool: + """True when the slide puzzle is already open (user can drag immediately).""" + for sel in _SLIDER_SELECTORS: + loc = page.locator(sel).first + try: + if loc.count() and loc.is_visible(): + return True + except Exception: + pass + for frame in page.frames: + url = (frame.url or "").lower() + if "captcha" not in url and "aliyun" not in url: + continue + for sel in _SLIDER_SELECTORS: + try: + loc = frame.locator(sel).first + if loc.count() and loc.is_visible(): + return True + except Exception: + pass + return False + + +def _try_click(locator, label: str) -> bool: + try: + if locator.count() and locator.first.is_visible(): + locator.first.click(timeout=3000) + print(f" clicked captcha trigger: {label}") + time.sleep(0.8) + return True + except Exception: + pass + return False + + +def trigger_captcha_start(page: Page) -> bool: + """ + Click the Aliyun 'start verification' control so the slider is open + when the user arrives — they only need to slide. + """ + if _captcha_passed(page): + return False + if _slider_visible(page): + print(" captcha slider already open") + return True + + time.sleep(0.4) + + if _try_click(page.get_by_text(_START_CLICK_TEXT).first, "start verification text"): + return True + if _try_click( + page.get_by_role("button", name=_START_CLICK_TEXT).first, + "start verification button", + ): + return True + + for sel in _CAPTCHA_WIDGET_SELECTORS: + if _try_click(page.locator(sel).first, sel): + return True + + for frame in page.frames: + url = (frame.url or "").lower() + if "captcha" not in url and "aliyun" not in url: + continue + if _try_click(frame.get_by_text(_START_CLICK_TEXT).first, f"iframe text ({url[:40]})"): + return True + for sel in ("#aliyunCaptcha", "#captcha-button", ".btn_slide", '[class*="verify"]', "button"): + if _try_click(frame.locator(sel).first, f"iframe {sel}"): + return True + + print(" captcha start button not found — click it manually if needed") + return False + + +def notify_batch_captcha(step: str, *, count: int = 1) -> None: + """Single desktop notification for a batch of browser windows.""" + base = os.environ.get("CAPTCHA_NOTIFY_MSG", "please do the captcha") + message = f"{base} ({count} window{'s' if count != 1 else ''})" + try: + subprocess.run(["notify-send", message], check=False) + except FileNotFoundError: + print("(notify-send not found — check the browser windows)") + + print() + print("=" * 60) + print(f"CAPTCHA required: {step} — {count} browser window(s)") + print(f"Notification sent: notify-send {message!r}") + print("=" * 60) + + +def wait_for_captcha_on_page(page: Page, step: str) -> None: + """Poll one page for captcha completion (no notify-send).""" + print(f" waiting for captcha on {step} …") + trigger_captcha_start(page) + retried = False + deadline = time.time() + POLL_TIMEOUT_SEC + while time.time() < deadline: + if _captcha_passed(page): + print(" captcha complete.") + time.sleep(0.5) + return + if not retried and page.get_by_text(_PENDING_TEXT).count(): + try: + if page.get_by_text(_PENDING_TEXT).first.is_visible(): + trigger_captcha_start(page) + retried = True + except Exception: + pass + time.sleep(POLL_INTERVAL_SEC) + raise TimeoutError(f"Captcha not completed within {POLL_TIMEOUT_SEC:.0f}s ({step})") + + +def wait_for_manual_captcha(step: str, *, page: Page | None = None) -> None: + notify_batch_captcha(step, count=1) + if page is not None: + print(f"Polling every {POLL_INTERVAL_SEC:.0f}s for captcha completion…") + elif sys.stdin.isatty(): + print("Complete the captcha in the browser, then press Enter here.") + else: + print(f"Waiting up to {POLL_TIMEOUT_SEC:.0f}s for manual captcha …") + print("=" * 60) + + if page is not None: + wait_for_captcha_on_page(page, step) + return + + if sys.stdin.isatty(): + input("Press Enter when captcha is done… ") + return + + time.sleep(POLL_TIMEOUT_SEC) + + +def wait_for_captcha_on_pages(step: str, *pages: Page) -> None: + """Poll multiple tabs for captcha completion (caller sends notify).""" + print(f"\nCAPTCHA required: {step} — polling {len(pages)} tab(s) every {POLL_INTERVAL_SEC:.0f}s") + + deadline = time.time() + POLL_TIMEOUT_SEC + while time.time() < deadline: + for page in pages: + try: + if not page.is_closed() and _captcha_passed(page): + print("Captcha detected as complete.") + time.sleep(0.5) + return + except Exception: + pass + time.sleep(POLL_INTERVAL_SEC) + raise TimeoutError(f"Captcha not completed within {POLL_TIMEOUT_SEC:.0f}s ({step})") diff --git a/runner/lib/proxy_api.py b/runner/lib/proxy_api.py new file mode 100644 index 0000000..9f54140 --- /dev/null +++ b/runner/lib/proxy_api.py @@ -0,0 +1,297 @@ +"""HTTP helpers for zcode-proxy dashboard / admin API (gentle polling).""" + +from __future__ import annotations + +import os +import time +from typing import Any + +import requests + +PROXY_URL = os.environ.get("PROXY_URL", "http://127.0.0.1:8080").rstrip("/") +# Seconds between polls — keep high enough to avoid hammering proxy / Z.AI billing cache +ONBOARD_POLL_SEC = float(os.environ.get("ONBOARD_POLL_SEC", "5")) +QUOTA_POLL_SEC = float(os.environ.get("QUOTA_POLL_SEC", "8")) +ONBOARD_TIMEOUT_SEC = float(os.environ.get("ONBOARD_TIMEOUT_SEC", "300")) +QUOTA_TIMEOUT_SEC = float(os.environ.get("QUOTA_TIMEOUT_SEC", "300")) + + +def start_onboard(*, launch_desktop: bool = True) -> dict[str, Any]: + response = requests.post( + f"{PROXY_URL}/admin/onboard/start", + json={"launchDesktop": launch_desktop}, + timeout=30, + ) + response.raise_for_status() + return response.json() + + +def poll_onboard(job_id: str) -> dict[str, Any]: + response = requests.get(f"{PROXY_URL}/admin/onboard/{job_id}", timeout=30) + response.raise_for_status() + return response.json() + + +def fetch_account_credential(account_id: str) -> dict[str, Any]: + response = requests.get(f"{PROXY_URL}/admin/accounts/{account_id}/credential", timeout=30) + response.raise_for_status() + return response.json() + + +def _job_has_quota(job: dict[str, Any]) -> bool: + return bool(job.get("quotaReady") or (job.get("balanceCount") or 0) > 0) + + +def _account_stub_from_job( + job: dict[str, Any], + credential: dict[str, Any] | None, +) -> dict[str, Any]: + """Minimal account dict when onboard already confirmed billing buckets.""" + balance_count = int(job.get("balanceCount") or 0) + return { + "id": job.get("accountId"), + "userId": (credential or {}).get("userId"), + "balances": [{}] * balance_count if balance_count else [], + } + + +def _credential_for_job(job: dict[str, Any]) -> tuple[dict[str, Any] | None, str | None]: + account_id = job.get("accountId") + if not account_id: + return None, None + try: + credential = fetch_account_credential(str(account_id)) + return credential, credential.get("userId") + except Exception: + return None, None + + +def wait_for_onboard(job_id: str) -> dict[str, Any]: + deadline = time.time() + ONBOARD_TIMEOUT_SEC + last_phase: str | None = None + while time.time() < deadline: + job = poll_onboard(job_id) + phase = job.get("phase") + if phase != last_phase: + print(f" onboard phase → {phase}") + last_phase = phase + if phase == "done": + return job + if phase == "error": + raise RuntimeError(job.get("error") or "onboard failed") + time.sleep(ONBOARD_POLL_SEC) + raise TimeoutError(f"Onboard job {job_id} timed out after {ONBOARD_TIMEOUT_SEC}s") + + +def wait_for_new_pool_account(before_count: int, *, user_id: str | None = None) -> dict[str, Any]: + """Wait until pool has a new account with quota buckets (reads cached /admin/quota).""" + deadline = time.time() + QUOTA_TIMEOUT_SEC + attempt = 0 + while time.time() < deadline: + attempt += 1 + response = requests.get(f"{PROXY_URL}/admin/quota", timeout=30) + response.raise_for_status() + data = response.json() + accounts = data.get("accounts") or [] + + candidates = accounts if len(accounts) <= before_count else accounts[before_count:] + for acct in reversed(candidates): + if user_id and acct.get("userId") and str(acct.get("userId")) != user_id: + continue + balances = acct.get("balances") or [] + if balances: + print(f" quota ready ({len(balances)} bucket(s)) after {attempt} poll(s)") + return acct + + if attempt == 1 or attempt % 5 == 0: + cache = data.get("cache") or {} + if cache.get("refreshing"): + print(" waiting for quota cache refresh…") + else: + print(f" waiting for quota buckets… (poll {attempt})") + + time.sleep(QUOTA_POLL_SEC) + raise TimeoutError("New pool account with quota not ready within timeout") + + +def wait_for_onboards_batch(job_ids: list[str]) -> dict[str, dict[str, Any]]: + """Poll all onboard jobs in one loop (single sleep between cycles).""" + pending = set(job_ids) + done: dict[str, dict[str, Any]] = {} + deadline = time.time() + ONBOARD_TIMEOUT_SEC + last_phases: dict[str, str | None] = {jid: None for jid in job_ids} + + print(f"Batch onboard poll for {len(job_ids)} job(s) every {ONBOARD_POLL_SEC:.0f}s …") + + while pending and time.time() < deadline: + for job_id in list(pending): + try: + job = poll_onboard(job_id) + except Exception as exc: + print(f" onboard poll {job_id} error: {exc}") + continue + phase = job.get("phase") + if phase != last_phases.get(job_id): + print(f" {job_id[:8]}… phase → {phase}") + last_phases[job_id] = phase + if phase == "done": + done[job_id] = job + pending.discard(job_id) + elif phase == "error": + raise RuntimeError(job.get("error") or f"onboard failed for {job_id}") + if pending: + time.sleep(ONBOARD_POLL_SEC) + + if pending: + raise TimeoutError( + f"Onboard jobs timed out after {ONBOARD_TIMEOUT_SEC}s: {', '.join(sorted(pending))}" + ) + return done + + +def wait_for_new_pool_accounts_batch( + specs: list[tuple[str, str | None, str | None]], +) -> dict[str, dict[str, Any]]: + """ + Wait for multiple pool accounts. Each spec is (key, account_id, user_id). + Returns key -> account dict. + """ + pending = {key: (account_id, user_id) for key, account_id, user_id in specs} + found: dict[str, dict[str, Any]] = {} + deadline = time.time() + QUOTA_TIMEOUT_SEC + attempt = 0 + + print(f"Batch quota poll for {len(specs)} account(s) every {QUOTA_POLL_SEC:.0f}s …") + + while pending and time.time() < deadline: + attempt += 1 + try: + response = requests.get(f"{PROXY_URL}/admin/quota", timeout=30) + response.raise_for_status() + data = response.json() + except Exception as exc: + print(f" quota poll error: {exc}") + time.sleep(QUOTA_POLL_SEC) + continue + + accounts = data.get("accounts") or [] + for key, (account_id, user_id) in list(pending.items()): + for acct in accounts: + if account_id and acct.get("id") != account_id: + continue + if user_id and acct.get("userId") and str(acct.get("userId")) != user_id: + continue + if account_id or user_id: + balances = acct.get("balances") or [] + if balances: + print(f" {key[:8]}… quota ready ({len(balances)} bucket(s))") + found[key] = acct + del pending[key] + break + + if pending: + if attempt == 1 or attempt % 5 == 0: + cache = data.get("cache") or {} + if cache.get("refreshing"): + print(" waiting for quota cache refresh…") + else: + print(f" waiting for quota buckets… (poll {attempt}, {len(pending)} left)") + time.sleep(QUOTA_POLL_SEC) + + if pending: + raise TimeoutError( + f"Quota not ready for {len(pending)} account(s) within {QUOTA_TIMEOUT_SEC}s" + ) + return found + + +def wait_until_accounts_usable_batch( + jobs: list[tuple[str, int]], +) -> dict[str, dict[str, Any]]: + """ + Post-OAuth for multiple accounts. jobs: [(job_id, before_count), ...]. + before_count is kept for logging only; matching uses accountId/userId from the job. + Returns job_id -> {job, account, credential, account_id, quota_ready}. + """ + job_ids = [jid for jid, _ in jobs] + onboarded = wait_for_onboards_batch(job_ids) + + specs: list[tuple[str, str | None, str | None]] = [] + prefilled: dict[str, dict[str, Any]] = {} + credentials: dict[str, dict[str, Any] | None] = {} + + for job_id, job in onboarded.items(): + credential, user_id = _credential_for_job(job) + credentials[job_id] = credential + if _job_has_quota(job): + prefilled[job_id] = _account_stub_from_job(job, credential) + print( + f" {job_id[:8]}… quota ready from onboard " + f"({job.get('balanceCount', '?')} bucket(s))" + ) + continue + account_id = job.get("accountId") + specs.append((job_id, str(account_id) if account_id else None, user_id)) + + accounts = wait_for_new_pool_accounts_batch(specs) if specs else {} + accounts.update(prefilled) + + results: dict[str, dict[str, Any]] = {} + for job_id, job in onboarded.items(): + acct = accounts[job_id] + credential = credentials.get(job_id) + pool_id = job.get("accountId") or acct.get("id") + results[job_id] = { + "job": job, + "account": acct, + "credential": credential, + "account_id": pool_id, + "quota_ready": _job_has_quota(job) or bool(acct.get("balances")), + } + return results + + +def wait_until_account_usable(job_id: str, before_count: int) -> dict[str, Any]: + """ + Full post-OAuth pipeline: onboard job → provisioning → JWT export. + When the onboard job reports quotaReady, skip polling the dashboard quota cache. + """ + print(f"Onboarding (poll every {ONBOARD_POLL_SEC:.0f}s)…") + job = wait_for_onboard(job_id) + + credential, user_id = _credential_for_job(job) + + if _job_has_quota(job): + print(f" quota ready from onboard ({job.get('balanceCount', '?')} bucket(s))") + acct = _account_stub_from_job(job, credential) + else: + print(" provision finished — waiting for billing buckets in quota cache…") + acct = wait_for_new_pool_account(before_count, user_id=user_id) + if pool_id := job.get("accountId") or acct.get("id"): + try: + credential = fetch_account_credential(str(pool_id)) + except Exception as exc: + print(f" warning: could not fetch JWT backup: {exc}") + + pool_id = job.get("accountId") or acct.get("id") + + return { + "job": job, + "account": acct, + "credential": credential, + "account_id": pool_id, + "quota_ready": _job_has_quota(job) or bool(acct.get("balances")), + } + + +def pool_summary() -> dict[str, Any]: + status = requests.get(f"{PROXY_URL}/admin/status", timeout=15).json() + quota = requests.get(f"{PROXY_URL}/admin/quota", timeout=15).json() + return {"status": status, "quota": quota} + + +def count_pool_accounts() -> int: + response = requests.get(f"{PROXY_URL}/admin/quota", timeout=15) + response.raise_for_status() + data = response.json() + return len(data.get("accounts") or []) diff --git a/runner/lib/resend_client.py b/runner/lib/resend_client.py new file mode 100644 index 0000000..ffba0d9 --- /dev/null +++ b/runner/lib/resend_client.py @@ -0,0 +1,259 @@ +"""Resend inbound email: poll API, extract verification codes and links.""" + +from __future__ import annotations + +import os +import re +import time +from typing import Any +from urllib.parse import unquote + +import requests + +RESEND_API_KEY = os.environ.get("RESEND_API_KEY", "") +POLL_INTERVAL_SEC = float(os.environ.get("RESEND_POLL_INTERVAL_SEC", "3")) +POLL_TIMEOUT_SEC = float(os.environ.get("RESEND_POLL_TIMEOUT_SEC", "180")) + +CODE_PATTERNS = [ + r"verification code[\s\S]{0,120}?(\d{6})", + r"验证码[\s\S]{0,80}?(\d{6})", + r">\s*(\d{6})\s*<", + r"(?]+)', + r'(https://z\.ai[^\s"\'<>]+)', + r'(https://zcode\.z\.ai[^\s"\'<>]+)', +] + + +def _headers() -> dict[str, str]: + if not RESEND_API_KEY: + raise RuntimeError("RESEND_API_KEY is not set") + return {"Authorization": f"Bearer {RESEND_API_KEY}"} + + +def list_received(limit: int = 20) -> list[dict[str, Any]]: + response = requests.get( + "https://api.resend.com/emails/receiving", + headers=_headers(), + params={"limit": limit}, + timeout=30, + ) + response.raise_for_status() + payload = response.json() + return payload.get("data") or payload.get("emails") or [] + + +def fetch_received(email_id: str) -> dict[str, Any]: + response = requests.get( + f"https://api.resend.com/emails/receiving/{email_id}", + headers=_headers(), + timeout=30, + ) + response.raise_for_status() + return response.json() + + +def _normalize_to(value: Any) -> list[str]: + if isinstance(value, str): + return [value.lower()] + if isinstance(value, list): + return [str(v).lower() for v in value] + return [] + + +def _matches_recipient(meta: dict[str, Any], email: str) -> bool: + target = email.lower() + for key in ("to", "recipient", "recipients"): + for addr in _normalize_to(meta.get(key)): + if addr == target or target in addr: + return True + return False + + +def extract_code(text: str) -> str | None: + if not text: + return None + for pattern in CODE_PATTERNS: + match = re.search(pattern, text, re.IGNORECASE) + if match: + return match.group(1) + return None + + +def extract_link(text: str) -> str | None: + if not text: + return None + for pattern in LINK_PATTERNS: + match = re.search(pattern, text, re.IGNORECASE) + if match: + return unquote(match.group(1)) + return None + + +def verification_from_email(email_payload: dict[str, Any]) -> tuple[str | None, str | None]: + """Return (code, link) — whichever is found first in body.""" + bodies = [ + email_payload.get("text") or "", + email_payload.get("html") or "", + email_payload.get("subject") or "", + ] + code = None + link = None + for body in bodies: + if not code: + code = extract_code(body) + if not link: + link = extract_link(body) + if code and link: + break + return code, link + + +def wait_for_verification( + email: str, + *, + timeout_sec: float | None = None, + after_ts: float | None = None, +) -> dict[str, Any]: + """Poll Resend until an email arrives for `email`. Returns {code?, link?, email_id, subject}.""" + deadline = time.time() + (timeout_sec if timeout_sec is not None else POLL_TIMEOUT_SEC) + seen_ids: set[str] = set() + + print(f"Polling Resend inbox for {email} …") + + while time.time() < deadline: + try: + items = list_received() + except Exception as exc: + print(f" Resend list error: {exc}") + time.sleep(POLL_INTERVAL_SEC) + continue + + for item in items: + email_id = str(item.get("id") or item.get("email_id") or "") + if not email_id or email_id in seen_ids: + continue + if not _matches_recipient(item, email): + continue + + received_at = item.get("created_at") or item.get("received_at") + if after_ts and received_at: + try: + from datetime import datetime + + if isinstance(received_at, str): + ts = datetime.fromisoformat(received_at.replace("Z", "+00:00")).timestamp() + if ts < after_ts - 5: + continue + except Exception: + pass + + try: + full = fetch_received(email_id) + except Exception as exc: + print(f" fetch {email_id} failed: {exc}") + continue + + code, link = verification_from_email(full) + if code or link: + print(f" got verification for {email} (code={bool(code)}, link={bool(link)})") + return { + "code": code, + "link": link, + "email_id": email_id, + "subject": full.get("subject") or item.get("subject"), + } + seen_ids.add(email_id) + + time.sleep(POLL_INTERVAL_SEC) + + raise TimeoutError(f"No verification email for {email} within {POLL_TIMEOUT_SEC}s") + + +def wait_for_verifications_batch( + emails: list[str], + *, + after_ts: dict[str, float] | None = None, + timeout_sec: float | None = None, +) -> dict[str, dict[str, Any]]: + """ + Poll Resend once per interval until every email has a verification message. + Avoids N parallel pollers hammering the API and staggering results. + """ + pending = {e.lower(): e for e in emails} + results: dict[str, dict[str, Any]] = {} + after_ts = after_ts or {} + deadline = time.time() + (timeout_sec if timeout_sec is not None else POLL_TIMEOUT_SEC) + seen_ids: set[str] = set() + + print(f"Polling Resend for {len(pending)} verification email(s) in one loop …") + + while pending and time.time() < deadline: + try: + items = list_received(limit=max(20, len(emails) * 3)) + except Exception as exc: + print(f" Resend list error: {exc}") + time.sleep(POLL_INTERVAL_SEC) + continue + + for item in items: + email_id = str(item.get("id") or item.get("email_id") or "") + if not email_id or email_id in seen_ids: + continue + + matched = None + for key in ("to", "recipient", "recipients"): + for addr in _normalize_to(item.get(key)): + if addr in pending: + matched = pending[addr] + break + if matched: + break + if not matched: + continue + + received_at = item.get("created_at") or item.get("received_at") + cutoff = after_ts.get(matched) + if cutoff and received_at: + try: + from datetime import datetime + + if isinstance(received_at, str): + ts = datetime.fromisoformat(received_at.replace("Z", "+00:00")).timestamp() + if ts < cutoff - 5: + continue + except Exception: + pass + + try: + full = fetch_received(email_id) + except Exception as exc: + print(f" fetch {email_id} failed: {exc}") + continue + + code, link = verification_from_email(full) + if code or link: + print(f" got verification for {matched} (code={bool(code)}, link={bool(link)})") + results[matched] = { + "code": code, + "link": link, + "email_id": email_id, + "subject": full.get("subject") or item.get("subject"), + } + del pending[matched.lower()] + seen_ids.add(email_id) + + if pending: + time.sleep(POLL_INTERVAL_SEC) + + if pending: + missing = ", ".join(pending.values()) + raise TimeoutError( + f"No verification email for [{missing}] within " + f"{timeout_sec if timeout_sec is not None else POLL_TIMEOUT_SEC}s" + ) + return results diff --git a/runner/lib/token_store.py b/runner/lib/token_store.py new file mode 100644 index 0000000..1a2d5cb --- /dev/null +++ b/runner/lib/token_store.py @@ -0,0 +1,51 @@ +"""Backup Start Plan JWTs from the proxy pool — separate from accounts.jsonl metadata.""" + +from __future__ import annotations + +import json +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +STATE_DIR = Path(os.environ.get("STATE_DIR", "state")) +TOKENS_FILE = STATE_DIR / "tokens.jsonl" + + +def save_token_backup( + *, + email: str, + password: str, + username: str, + index: int, + credential: dict[str, Any] | None, + account: dict[str, Any] | None, + job: dict[str, Any] | None, +) -> None: + """Append JWT + pool metadata to state/tokens.jsonl (gitignored).""" + STATE_DIR.mkdir(parents=True, exist_ok=True) + + entry: dict[str, Any] = { + "email": email, + "password": password, + "username": username, + "index": index, + "saved_at": datetime.now(timezone.utc).isoformat(), + "proxy_account_id": (credential or {}).get("id") or (account or {}).get("id"), + "user_id": (credential or {}).get("userId") or (account or {}).get("userId"), + "jwt": (credential or {}).get("jwt"), + "provider": (credential or {}).get("provider"), + "status": (credential or {}).get("status") or (account or {}).get("status"), + "quota_ready": bool((job or {}).get("quotaReady") or (account or {}).get("balances")), + "balance_count": (job or {}).get("balanceCount") or len((account or {}).get("balances") or []), + "balances": (account or {}).get("balances"), + "onboard_job_id": (job or {}).get("id"), + } + + with TOKENS_FILE.open("a", encoding="utf-8") as f: + f.write(json.dumps(entry) + "\n") + + if entry.get("jwt"): + print(f"JWT backup → {TOKENS_FILE} ({email})") + else: + print(f"warning: no JWT in backup for {email} — check proxy pool") diff --git a/runner/lib/zai_flow.py b/runner/lib/zai_flow.py new file mode 100644 index 0000000..449f6b0 --- /dev/null +++ b/runner/lib/zai_flow.py @@ -0,0 +1,254 @@ +"""Z.AI signup + zcode-proxy OAuth link flow (chat.z.ai/auth, Open WebUI).""" + +from __future__ import annotations + +import os +import re +import time +from typing import Any + +from playwright.sync_api import BrowserContext, Page + +from lib.browser import STEP_TIMEOUT_MS, human_pause +from lib.captcha import notify_batch_captcha, wait_for_captcha_on_page, wait_for_manual_captcha +from lib.proxy_api import ( + PROXY_URL, + count_pool_accounts, + start_onboard, + wait_until_account_usable, +) +from lib.resend_client import wait_for_verification + +SIGNUP_URL = os.environ.get("SIGNUP_URL", "https://chat.z.ai/auth") +ACCOUNT_USERNAME = os.environ.get("ACCOUNT_USERNAME", "Zcode") +LAUNCH_ZCODE = os.environ.get("LAUNCH_ZCODE", "true").lower() in ("1", "true", "yes") +USE_DASHBOARD_SIGNIN = os.environ.get("USE_DASHBOARD_SIGNIN", "true").lower() in ("1", "true", "yes") + + +def _click_role(page: Page, role: str, name: str) -> bool: + loc = page.get_by_role(role, name=name).first + try: + if loc.count() and loc.is_visible(): + loc.click() + return True + except Exception: + pass + return False + + +def _fill_placeholder(page: Page, placeholder: str, value: str) -> None: + loc = page.get_by_placeholder(placeholder).first + loc.wait_for(state="visible", timeout=STEP_TIMEOUT_MS) + loc.fill(value) + + +def _complete_email_verify_password(page: Page, password: str) -> None: + """After verify link: set password + confirm on /auth/verify_email.""" + if "verify_email" not in page.url: + return + human_pause(1.0, 2.0) + for ph in ("Enter your password", "Confirm your password"): + box = page.get_by_placeholder(ph) + if box.count() and box.first.is_visible(): + box.first.fill(password) + human_pause(0.2, 0.4) + if _click_role(page, "button", "Complete Registration"): + page.wait_for_load_state("domcontentloaded", timeout=STEP_TIMEOUT_MS) + human_pause(2.0, 3.0) + + +def prepare_signup_form(page: Page, creds: dict[str, str]) -> float: + """Navigate and fill signup form; return timestamp before Create Account.""" + username = creds.get("username") or ACCOUNT_USERNAME + print(f"Signup → {SIGNUP_URL} as {creds['email']}") + + page.goto(SIGNUP_URL, wait_until="domcontentloaded", timeout=STEP_TIMEOUT_MS) + human_pause(1.5, 2.5) + + if _click_role(page, "button", "Continue with Email"): + human_pause(0.8, 1.2) + + if not _click_role(page, "button", "Sign up"): + raise RuntimeError('Could not find "Sign up" on /auth') + + human_pause(0.5, 0.8) + started_at = time.time() + + _fill_placeholder(page, "Enter Your Full Name", username) + human_pause(0.2, 0.4) + _fill_placeholder(page, "Enter Your Email", creds["email"]) + human_pause(0.2, 0.4) + _fill_placeholder(page, "Enter Your Password", creds["password"]) + human_pause(0.3, 0.6) + return started_at + + +def click_create_account(page: Page) -> None: + if not _click_role(page, "button", "Create Account"): + raise RuntimeError('Could not find "Create Account" button') + page.wait_for_load_state("domcontentloaded", timeout=STEP_TIMEOUT_MS) + human_pause(1.0, 1.5) + + +def apply_email_verification( + page: Page, + creds: dict[str, str], + verification: dict[str, Any], +) -> None: + if verification.get("link"): + link = verification["link"].replace("&", "&") + print(f"Opening verification link for {creds['email']} …") + page.goto(link, wait_until="domcontentloaded", timeout=STEP_TIMEOUT_MS) + human_pause(2.0, 3.0) + _complete_email_verify_password(page, creds["password"]) + elif verification.get("code"): + from lib.browser import fill_verification_code + + fill_verification_code(page, verification["code"]) + human_pause(0.3, 0.6) + _click_role(page, "button", "Complete Registration") + page.wait_for_load_state("domcontentloaded", timeout=STEP_TIMEOUT_MS) + else: + raise RuntimeError("Verification email had no link or code") + print(f"Signup complete for {creds['email']} → {page.url}") + + +def signup_on_zai(page: Page, creds: dict[str, str]) -> None: + """Create account: /auth → Sign up → captcha → Create Account → verify email.""" + started_at = prepare_signup_form(page, creds) + wait_for_manual_captcha("Z.AI signup (1/2)", page=page) + click_create_account(page) + verification = wait_for_verification(creds["email"], after_ts=started_at) + apply_email_verification(page, creds, verification) + + +def prepare_oauth_login(page: Page, creds: dict[str, str]) -> bool: + """Fill OAuth login form if shown. Returns True when captcha is needed.""" + page.wait_for_load_state("domcontentloaded", timeout=STEP_TIMEOUT_MS) + human_pause(1.0, 1.5) + + if page.get_by_placeholder("Enter Your Email").count(): + if _click_role(page, "button", "Continue with Email"): + human_pause(0.8, 1.2) + _fill_placeholder(page, "Enter Your Email", creds["email"]) + _fill_placeholder(page, "Enter Your Password", creds["password"]) + return True + return False + + +def complete_oauth_authorize(page: Page) -> None: + """After captcha/login: accept terms and authorize.""" + if page.get_by_role("heading", name=re.compile(r"access your Z", re.I)).count(): + terms = page.get_by_text("Terms of Service and Privacy Policy") + if terms.count(): + terms.first.click() + human_pause(0.3, 0.6) + _click_role(page, "button", "Continue") + page.wait_for_load_state("domcontentloaded", timeout=STEP_TIMEOUT_MS) + return + + for label in ("Authorize", "Allow", "Continue", "授权", "同意"): + if _click_role(page, "button", label): + return + + +def authorize_oauth_tab(page: Page, creds: dict[str, str]) -> None: + """OAuth authorize page — login if needed, accept terms, Continue.""" + needs_captcha = prepare_oauth_login(page, creds) + if needs_captcha: + wait_for_manual_captcha("Z.AI OAuth login (2/2)", page=page) + _click_role(page, "button", "Sign in") + page.wait_for_load_state("domcontentloaded", timeout=STEP_TIMEOUT_MS) + human_pause(1.0, 1.5) + complete_oauth_authorize(page) + + +def _click_add_account(dashboard: Page) -> None: + """Top-bar Add account button (always visible, not at bottom of list).""" + btn = dashboard.locator("#btn-add-account:visible").first + if not btn.count(): + btn = dashboard.get_by_role("button", name=re.compile(r"add account.*sign in", re.I)).first + btn.wait_for(state="visible", timeout=STEP_TIMEOUT_MS) + btn.click() + + +def _open_oauth_via_dashboard(context: BrowserContext) -> tuple[Page, Page, str]: + dashboard = context.new_page() + dashboard.goto(f"{PROXY_URL}/app", wait_until="domcontentloaded", timeout=STEP_TIMEOUT_MS) + human_pause(0.8, 1.2) + + with dashboard.expect_response( + lambda r: "/admin/onboard/start" in r.url and r.request.method == "POST", + timeout=STEP_TIMEOUT_MS, + ) as response_info: + with context.expect_page(timeout=STEP_TIMEOUT_MS) as page_info: + _click_add_account(dashboard) + oauth = page_info.value + + response = response_info.value + if not response.ok: + raise RuntimeError(f"onboard/start failed: HTTP {response.status}") + job = response.json() + job_id = job["id"] + print(f"Dashboard onboard job {job_id}") + print(f"Authorize → {job.get('authorizeUrl')}") + + oauth.wait_for_load_state("domcontentloaded", timeout=STEP_TIMEOUT_MS) + return dashboard, oauth, job_id + + +def _open_oauth_via_api(context: BrowserContext) -> tuple[Page, Page, str]: + job = start_onboard(launch_desktop=LAUNCH_ZCODE) + job_id = job["id"] + authorize_url = job["authorizeUrl"] + print(f"Onboard job {job_id}") + print(f"Authorize → {authorize_url}") + + dashboard = context.new_page() + dashboard.goto(f"{PROXY_URL}/app", wait_until="domcontentloaded", timeout=STEP_TIMEOUT_MS) + human_pause(0.5, 0.8) + + oauth = context.new_page() + oauth.goto(authorize_url, wait_until="domcontentloaded", timeout=STEP_TIMEOUT_MS) + return dashboard, oauth, job_id + + +def open_proxy_oauth(context: BrowserContext) -> tuple[Page, Page, str, int]: + """Open dashboard + OAuth tab. Returns (dashboard, oauth, job_id, before_count).""" + before_count = count_pool_accounts() + if USE_DASHBOARD_SIGNIN: + dashboard, oauth, job_id = _open_oauth_via_dashboard(context) + else: + dashboard, oauth, job_id = _open_oauth_via_api(context) + return dashboard, oauth, job_id, before_count + + +def link_account_via_proxy( + context: BrowserContext, + creds: dict[str, str], +) -> dict[str, Any]: + dashboard, oauth, job_id, before_count = open_proxy_oauth(context) + + human_pause(1.0, 1.5) + authorize_oauth_tab(oauth, creds) + + print("Waiting for proxy onboard …") + usable = wait_until_account_usable(job_id, before_count) + result = usable["job"] + acct = usable["account"] + print( + f"Pool account ready: {acct.get('userId')} " + f"({len(acct.get('balances') or [])} buckets, usable={usable.get('quota_ready')})" + ) + + return { + "ok": True, + "job": result, + "account": acct, + "credential": usable.get("credential"), + "account_id": usable.get("account_id"), + "quota_ready": usable.get("quota_ready"), + "job_id": job_id, + "final_oauth_url": oauth.url if not oauth.is_closed() else None, + "dashboard_url": dashboard.url if not dashboard.is_closed() else None, + } diff --git a/runner/onboard_existing.py b/runner/onboard_existing.py new file mode 100644 index 0000000..4873cee --- /dev/null +++ b/runner/onboard_existing.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +""" +Provision quota for pool accounts that were added but have no billing buckets. + +Uses live /admin/accounts/{id}/balance (not cache) and POST .../provision +with gentle delays between accounts. + + cd runner && .venv/bin/python onboard_existing.py + .venv/bin/python onboard_existing.py --dry-run + .venv/bin/python onboard_existing.py --ids e42a7c68c93f,27e07e475b2a +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time +from pathlib import Path + +from dotenv import load_dotenv + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT)) +load_dotenv(ROOT / ".env") + +import requests + +from lib.token_store import save_token_backup + +PROXY_URL = os.environ.get("PROXY_URL", "http://127.0.0.1:8080").rstrip("/") +GAP_SEC = float(os.environ.get("PROVISION_GAP_SEC", "10")) +BALANCE_POLL_SEC = float(os.environ.get("PROVISION_BALANCE_POLL_SEC", "5")) +STATE_DIR = Path(os.environ.get("STATE_DIR", "state")) +ACCOUNTS_FILE = STATE_DIR / "accounts.jsonl" + + +def api(method: str, path: str, **kwargs) -> dict: + url = f"{PROXY_URL}{path}" + resp = requests.request(method, url, timeout=120, **kwargs) + resp.raise_for_status() + return resp.json() if resp.text else {} + + +def live_balance(account_id: str) -> dict: + return api("GET", f"/admin/accounts/{account_id}/balance") + + +def needs_provision(account_id: str) -> tuple[bool, dict]: + bal = live_balance(account_id) + buckets = bal.get("balances") or [] + return len(buckets) == 0, bal + + +def provision_account(account_id: str, *, launch_desktop: bool) -> dict: + return api( + "POST", + f"/admin/accounts/{account_id}/provision", + json={"launchDesktop": launch_desktop}, + ) + + +def load_runner_accounts() -> list[dict]: + if not ACCOUNTS_FILE.exists(): + return [] + rows = [] + for line in ACCOUNTS_FILE.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if line: + rows.append(json.loads(line)) + return rows + + +def backfill_token(email_row: dict, cred: dict, bal: dict) -> None: + save_token_backup( + email=email_row.get("email", ""), + password=email_row.get("password", ""), + username=email_row.get("username", "Zcode"), + index=int(email_row.get("index", 0)), + credential=cred, + account={"id": cred.get("id"), "userId": cred.get("userId"), "balances": bal.get("balances")}, + job={"quotaReady": bool(bal.get("balances"))}, + ) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Provision existing pool accounts missing quota") + parser.add_argument("--dry-run", action="store_true", help="Only list accounts needing provision") + parser.add_argument("--ids", help="Comma-separated pool account ids (default: all in pool)") + parser.add_argument("--no-zcode", action="store_true", help="Skip launching ZCode desktop") + parser.add_argument("--backfill-tokens", action="store_true", help="Also write tokens.jsonl for all with JWT") + args = parser.parse_args() + + pool = api("GET", "/admin/accounts") + accounts = pool.get("accounts") or [] + if args.ids: + wanted = {x.strip() for x in args.ids.split(",") if x.strip()} + accounts = [a for a in accounts if a["id"] in wanted] + + print(f"Checking {len(accounts)} pool account(s)…\n") + pending: list[tuple[dict, dict]] = [] + + for acct in accounts: + aid = acct["id"] + time.sleep(BALANCE_POLL_SEC) + need, bal = needs_provision(aid) + buckets = len(bal.get("balances") or []) + label = acct.get("userId") or acct.get("name") or aid + if need: + print(f" NEED {aid} {label} (0 buckets)") + pending.append((acct, bal)) + else: + print(f" OK {aid} {label} ({buckets} buckets)") + + if not pending: + print("\nAll accounts already have quota buckets.") + if args.backfill_tokens: + _backfill_all(accounts) + return 0 + + print(f"\n{len(pending)} account(s) need provisioning.\n") + if args.dry_run: + return 0 + + ok = 0 + for i, (acct, _) in enumerate(pending): + aid = acct["id"] + print(f"[{i + 1}/{len(pending)}] Provisioning {aid} ({acct.get('userId', '?')})…") + try: + result = provision_account(aid, launch_desktop=not args.no_zcode) + if result.get("quotaReady"): + print(f" ✓ quota ready ({result.get('balanceCount')} buckets)") + ok += 1 + else: + print(" ⚠ provision finished but buckets still empty") + except Exception as exc: + print(f" ✗ failed: {exc}") + if i < len(pending) - 1: + print(f" waiting {GAP_SEC:.0f}s before next account…") + time.sleep(GAP_SEC) + + print(f"\nProvisioned {ok}/{len(pending)}") + if args.backfill_tokens or ok: + _backfill_all(accounts) + return 0 if ok == len(pending) else 1 + + +def _backfill_all(accounts: list[dict]) -> None: + rows = {r.get("proxy_user_id"): r for r in load_runner_accounts()} + print("\nBackfilling tokens.jsonl…") + for acct in accounts: + aid = acct["id"] + try: + cred = api("GET", f"/admin/accounts/{aid}/credential") + time.sleep(BALANCE_POLL_SEC) + bal = live_balance(aid) + row = rows.get(cred.get("userId")) or { + "email": f"pool-{aid}@local", + "password": "", + "username": "Zcode", + "index": 0, + } + backfill_token(row, cred, bal) + except Exception as exc: + print(f" skip {aid}: {exc}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/runner/requirements.txt b/runner/requirements.txt new file mode 100644 index 0000000..206e4f7 --- /dev/null +++ b/runner/requirements.txt @@ -0,0 +1,3 @@ +playwright>=1.49.0 +requests>=2.32.0 +python-dotenv>=1.0.0 diff --git a/runner/run.py b/runner/run.py new file mode 100644 index 0000000..83c3ba6 --- /dev/null +++ b/runner/run.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +""" +Headed browser runner: create Z.AI accounts and link them into zcode-proxy. + +Per account: + 1. Fresh Chromium profile + 2. Sign up on Z.AI (Resend inbox for verification link/code) + 3. Manual captcha #1 (notify-send) + 4. Open proxy OAuth authorize URL + 5. Manual captcha #2 + login if needed + 6. Wait for proxy onboard (quota buckets confirmed by onboard job — no quota-cache wait) + 7. Delete profile directory + +Usage: + cd runner && cp .env.example .env # fill RESEND_API_KEY, EMAIL_DOMAIN, etc. + pip install -r requirements.txt + playwright install chromium + + python run.py --count 3 + python run_spawn.py --count 4 # 4 separate processes, unique zcodeN emails + python run.py --count 1 --no-zcode # skip launching ZCode for quota + +Requires zcode-proxy running: bun run src/index.ts +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import traceback +from pathlib import Path + +from dotenv import load_dotenv + +# runner/ as cwd +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT)) +load_dotenv(ROOT / ".env") + +from lib.account_store import Account, account_at_index, next_account, record_failure, save_account +from lib.token_store import save_token_backup +from lib.browser import ( # noqa: E402 + delete_profile, + launch_fresh_context, + new_profile_dir, +) +from lib.proxy_api import pool_summary # noqa: E402 +from lib.zai_flow import link_account_via_proxy, signup_on_zai # noqa: E402 + + +def run_one(account: Account | None = None, *, advance_index: bool | None = None) -> dict: + reserved = account is not None + acct = account if reserved else next_account() + should_advance = False if reserved else True + if advance_index is not None: + should_advance = advance_index + creds = { + "email": acct.email, + "password": acct.password, + "username": acct.username, + "index": str(acct.index), + } + profile_dir = new_profile_dir() + print(f"\n{'=' * 60}") + print(f"Account: {creds['email']} (index {acct.index})") + print(f"Username: {creds['username']}") + print(f"Profile: {profile_dir}") + print(f"{'=' * 60}\n") + + result: dict = { + "ok": False, + "email": creds["email"], + "index": acct.index, + "username": creds["username"], + "profile": str(profile_dir), + } + pw = None + stage = "init" + + try: + pw, context = launch_fresh_context(profile_dir) + page = context.pages[0] if context.pages else context.new_page() + + stage = "signup" + signup_on_zai(page, creds) + stage = "proxy_link" + link = link_account_via_proxy(context, creds) + + result.update( + { + "ok": True, + "proxy_link": link, + "pool": pool_summary(), + } + ) + if not link.get("quota_ready"): + raise RuntimeError("Account onboarded but quota buckets not ready") + + save_account( + acct, + extra={ + "proxy_user_id": link.get("account", {}).get("userId"), + "proxy_account_id": link.get("account_id"), + "job_id": link.get("job_id"), + "quota_ready": True, + }, + advance=should_advance, + ) + save_token_backup( + email=acct.email, + password=acct.password, + username=acct.username, + index=acct.index, + credential=link.get("credential"), + account=link.get("account"), + job=link.get("job"), + ) + context.close() + pw.stop() + pw = None + + except Exception as exc: + result["error"] = str(exc) + result["traceback"] = traceback.format_exc() + result["stage"] = stage + print(f"FAILED at {stage}: {exc}") + record_failure(acct, str(exc), stage=stage, advance=should_advance) + if pw: + try: + pw.stop() + except Exception: + pass + finally: + delete_profile(profile_dir) + print(f"Deleted profile {profile_dir}") + + return result + + +def main() -> int: + parser = argparse.ArgumentParser(description="Z.AI account runner for zcode-proxy") + parser.add_argument( + "--count", + type=int, + default=int(os.environ.get("BATCH_COUNT", "1")), + help="How many accounts to create (default: 1 or BATCH_COUNT env)", + ) + parser.add_argument( + "--account-index", + type=int, + metavar="N", + help="Use reserved email index N (from run_spawn.py; does not re-claim index)", + ) + parser.add_argument( + "--headless", + action="store_true", + help="Run without visible browser (default: headed)", + ) + parser.add_argument( + "--no-zcode", + action="store_true", + help="Do not launch ZCode desktop during quota provisioning", + ) + args = parser.parse_args() + + if args.headless: + os.environ["HEADLESS"] = "true" + else: + os.environ["HEADLESS"] = "false" + + if args.no_zcode: + os.environ["LAUNCH_ZCODE"] = "false" + + count = max(1, args.count) + reserved_account: Account | None = None + if args.account_index is not None: + reserved_account = account_at_index(args.account_index) + count = 1 + + print(f"Z.AI runner — {count} account(s), headless={os.environ['HEADLESS']}") + + results = [] + ok = 0 + for i in range(count): + if reserved_account: + acct = reserved_account + print(f"\n>>> Spawned run for {acct.email} (index {acct.index})") + else: + acct = None + print(f"\n>>> Run {i + 1}/{count}") + r = run_one(acct, advance_index=False if reserved_account else None) + results.append(r) + if r.get("ok"): + ok += 1 + + if args.account_index is not None: + out = ROOT / "results" / f"spawn-{args.account_index}.json" + else: + out = ROOT / "results" / f"batch-{ok}-of-{count}.json" + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(results, indent=2), encoding="utf-8") + print(f"\nFinished: {ok}/{count} succeeded") + print(f"Results → {out}") + return 0 if ok == count else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/runner/run_spawn.py b/runner/run_spawn.py new file mode 100755 index 0000000..e01242a --- /dev/null +++ b/runner/run_spawn.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +""" +Spawn N independent run.py processes — one headed browser each, unique account numbers. + +Reserves zcodeN..zcodeN+count-1 upfront (file-locked), then starts one subprocess +per account. Each child runs the normal sequential flow; no threads, no shared state. + + cd runner && python run_spawn.py --count 4 + python run_spawn.py --count 4 --no-zcode + python run_spawn.py --count 4 --detach # fire-and-forget + +Requires zcode-proxy running: bun run src/index.ts +""" + +from __future__ import annotations + +import argparse +import json +import os +import random +import subprocess +import sys +import time +from pathlib import Path + +from dotenv import load_dotenv + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT)) +load_dotenv(ROOT / ".env") + +from lib.account_store import reserve_accounts # noqa: E402 + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Spawn parallel run.py workers with unique reserved account numbers", + ) + parser.add_argument( + "--count", + type=int, + default=int(os.environ.get("SPAWN_COUNT", "1")), + help="How many browser processes to start (default: 1 or SPAWN_COUNT env)", + ) + parser.add_argument("--headless", action="store_true") + parser.add_argument("--no-zcode", action="store_true") + parser.add_argument( + "--detach", + action="store_true", + help="Start processes and exit without waiting", + ) + parser.add_argument( + "--stagger-min", + type=float, + default=float(os.environ.get("SPAWN_STAGGER_MIN_SEC", "5")), + help="Min seconds between starting each runner (default: 5)", + ) + parser.add_argument( + "--stagger-max", + type=float, + default=float(os.environ.get("SPAWN_STAGGER_MAX_SEC", "10")), + help="Max seconds between starting each runner (default: 10)", + ) + args = parser.parse_args() + + count = max(1, args.count) + stagger_min = max(0.0, args.stagger_min) + stagger_max = max(stagger_min, args.stagger_max) + accounts = reserve_accounts(count) + + print(f"Spawn runner — {count} process(es), indices {accounts[0].index}–{accounts[-1].index}") + if count > 1 and stagger_max > 0: + print(f" stagger {stagger_min:.0f}–{stagger_max:.0f}s between each start") + for acct in accounts: + print(f" reserved {acct.email}") + + run_py = ROOT / "run.py" + children: list[tuple[object, subprocess.Popen]] = [] + + for i, acct in enumerate(accounts): + if i > 0 and stagger_max > 0: + delay = random.uniform(stagger_min, stagger_max) + print(f" waiting {delay:.1f}s before next runner …") + time.sleep(delay) + + cmd = [ + sys.executable, + str(run_py), + "--account-index", + str(acct.index), + "--count", + "1", + ] + if args.headless: + cmd.append("--headless") + if args.no_zcode: + cmd.append("--no-zcode") + + proc = subprocess.Popen(cmd, cwd=ROOT) + children.append((acct, proc)) + print(f" PID {proc.pid} → {acct.email}") + + if args.detach: + print("\nDetached — children running independently.") + return 0 + + print("\nWaiting for all processes …") + results: list[dict] = [] + ok = 0 + for acct, proc in children: + code = proc.wait() + result_path = ROOT / "results" / f"spawn-{acct.index}.json" + if result_path.exists(): + results.append(json.loads(result_path.read_text(encoding="utf-8"))) + if code == 0: + ok += 1 + print(f" ✓ {acct.email} (exit {code})") + else: + print(f" ✗ {acct.email} (exit {code})") + + summary = ROOT / "results" / f"spawn-{ok}-of-{count}.json" + summary.parent.mkdir(parents=True, exist_ok=True) + summary.write_text(json.dumps(results, indent=2), encoding="utf-8") + print(f"\nFinished: {ok}/{count} succeeded") + print(f"Summary → {summary}") + return 0 if ok == count else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/runner/start_chrome_debug.sh b/runner/start_chrome_debug.sh new file mode 100755 index 0000000..9ea7317 --- /dev/null +++ b/runner/start_chrome_debug.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Fresh headed Chromium for manual/CDP flow exploration (not Brave). +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")" && pwd)" +CHROME="${CHROME:-$HOME/.cache/ms-playwright/chromium-1223/chrome-linux64/chrome}" +PORT="${DEBUG_PORT:-9223}" +PROFILE="${CHROME_PROFILE:-$ROOT/explore-chrome-profile}" +LOG="$ROOT/explore-chrome.log" + +mkdir -p "$PROFILE" + +if ss -ltn 2>/dev/null | rg -q ":${PORT}\s"; then + echo "Port $PORT already in use" + exit 1 +fi + +export DISPLAY="${DISPLAY:-:0}" + +nohup "$CHROME" \ + --remote-debugging-port="$PORT" \ + --user-data-dir="$PROFILE" \ + --no-first-run \ + --no-default-browser-check \ + --disable-session-crashed-bubble \ + --disable-features=TranslateUI \ + --no-sandbox \ + --disable-dev-shm-usage \ + about:blank \ + >"$LOG" 2>&1 & + +echo $! > "$ROOT/explore-chrome.pid" +echo "Chromium PID $(cat "$ROOT/explore-chrome.pid")" +echo "CDP: http://127.0.0.1:$PORT" +echo "Profile: $PROFILE" +echo "Log: $LOG" + +for i in $(seq 1 30); do + if curl -s "http://127.0.0.1:$PORT/json/version" >/dev/null 2>&1; then + curl -s "http://127.0.0.1:$PORT/json/version" | head -c 200 + echo "" + exit 0 + fi + sleep 0.2 +done +echo "Timed out waiting for CDP on port $PORT" >&2 +exit 1 diff --git a/runner/stop_chrome_debug.sh b/runner/stop_chrome_debug.sh new file mode 100755 index 0000000..5e60930 --- /dev/null +++ b/runner/stop_chrome_debug.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "$0")" && pwd)" +PID_FILE="$ROOT/explore-chrome.pid" +if [[ -f "$PID_FILE" ]]; then + kill "$(cat "$PID_FILE")" 2>/dev/null || true + rm -f "$PID_FILE" +fi +pkill -f "remote-debugging-port=${DEBUG_PORT:-9223}.*explore-chrome-profile" 2>/dev/null || true +echo "stopped" diff --git a/src/auth/account-pool.test.ts b/src/auth/account-pool.test.ts new file mode 100644 index 0000000..5d1eaed --- /dev/null +++ b/src/auth/account-pool.test.ts @@ -0,0 +1,52 @@ +import { describe, it, expect, beforeEach, afterEach } from "bun:test"; +import { existsSync, unlinkSync } from "node:fs"; +import { AccountPool, getAccountsStorePath } from "./account-pool.js"; +import type { Credential } from "./types.js"; + +const CRED: Credential = { + apiKey: "k", + provider: "zai", + jwt: "eyJhbG.header.payload", + userId: "user-a", +}; + +describe("AccountPool", () => { + beforeEach(() => { + const path = getAccountsStorePath(); + if (existsSync(path)) unlinkSync(path); + }); + + afterEach(() => { + const path = getAccountsStorePath(); + if (existsSync(path)) unlinkSync(path); + }); + + it("adds and round-robins accounts", () => { + const pool = new AccountPool(); + const id1 = pool.addFromCredential(CRED); + const id2 = pool.addFromCredential( + { ...CRED, jwt: "eyJ.other.jwt", userId: "user-b" }, + ); + + expect(pool.activeCount()).toBe(2); + const first = pool.acquire(); + const second = pool.acquire([first!.id]); + expect(first?.id).toBe(id1); + expect(second?.id).toBe(id2); + }); + + it("dedupes same jwt on re-add", () => { + const pool = new AccountPool(); + const id1 = pool.addFromCredential(CRED); + const id2 = pool.addFromCredential(CRED); + expect(id1).toBe(id2); + expect(pool.size()).toBe(1); + }); + + it("skips exhausted accounts", () => { + const pool = new AccountPool(); + const id = pool.addFromCredential(CRED); + pool.markExhausted(id, "1005"); + expect(pool.acquire()).toBeNull(); + }); +}); diff --git a/src/auth/account-pool.ts b/src/auth/account-pool.ts new file mode 100644 index 0000000..649036e --- /dev/null +++ b/src/auth/account-pool.ts @@ -0,0 +1,235 @@ +/** + * Multi-account pool for start-plan JWT rotation (~/.zcode-proxy/accounts.json). + */ +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { randomBytes } from "node:crypto"; +import type { Credential } from "./types.js"; +import type { ProviderId } from "../provider/types.js"; +import { loadCredential } from "./store.js"; +import { decodeJwtUserId } from "./zcode-credentials.js"; + +export type AccountStatus = "active" | "exhausted" | "blocked" | "disabled"; + +export interface PoolAccount { + id: string; + name: string; + provider: ProviderId; + jwt: string; + apiKey?: string; + userId?: string; + status: AccountStatus; + enabled: boolean; + addedAt: string; + lastUsedAt: string | null; + lastError: string | null; + usageCount: number; +} + +interface AccountsFile { + accounts: PoolAccount[]; +} + +const STORE_DIR = join(homedir(), ".zcode-proxy"); +const ACCOUNTS_FILE = join(STORE_DIR, "accounts.json"); + +function nowIso(): string { + return new Date().toISOString(); +} + +function newId(): string { + return randomBytes(6).toString("hex"); +} + +export function getAccountsStorePath(): string { + return ACCOUNTS_FILE; +} + +export class AccountPool { + private accounts = new Map(); + private roundRobinIndex = 0; + + constructor() { + this.load(); + } + + private load(): void { + if (!existsSync(ACCOUNTS_FILE)) return; + try { + const data = JSON.parse(readFileSync(ACCOUNTS_FILE, "utf-8")) as AccountsFile; + for (const entry of data.accounts ?? []) { + if (entry.jwt?.trim()) { + this.accounts.set(entry.id, { ...entry, jwt: entry.jwt.trim() }); + } + } + } catch (err) { + console.error("[pool] failed to load accounts:", err); + } + } + + persist(): void { + mkdirSync(dirname(ACCOUNTS_FILE), { recursive: true }); + const data: AccountsFile = { accounts: [...this.accounts.values()] }; + const tmp = `${ACCOUNTS_FILE}.tmp`; + writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 }); + renameSync(tmp, ACCOUNTS_FILE); + } + + /** Import legacy single credential from ~/.zcode-proxy/credentials.json once. */ + async migrateFromLegacyCredential(): Promise { + if (this.accounts.size > 0) return false; + const cred = await loadCredential(); + if (!cred?.jwt?.trim()) return false; + this.addFromCredential(cred); + return true; + } + + size(): number { + return this.accounts.size; + } + + activeCount(): number { + return this.listSelectable().length; + } + + list(): PoolAccount[] { + return [...this.accounts.values()].sort((a, b) => a.addedAt.localeCompare(b.addedAt)); + } + + listPublic(): Array & { jwtPrefix: string }> { + return this.list().map(({ jwt, apiKey: _apiKey, ...rest }) => ({ + ...rest, + jwtPrefix: `${jwt.slice(0, 16)}...`, + })); + } + + get(id: string): PoolAccount | undefined { + return this.accounts.get(id); + } + + addFromCredential(cred: Credential): string { + const jwt = cred.jwt?.trim(); + if (!jwt) throw new Error("Credential has no start-plan JWT"); + + const existing = this.list().find((a) => a.jwt === jwt); + if (existing) { + existing.apiKey = cred.apiKey; + existing.userId = cred.userId ?? existing.userId; + existing.name = cred.userId ?? existing.name; + existing.status = "active"; + existing.enabled = true; + existing.lastError = null; + this.persist(); + return existing.id; + } + + const id = newId(); + const userId = cred.userId ?? decodeJwtUserId(jwt); + const entry: PoolAccount = { + id, + name: userId ?? id, + provider: cred.provider, + jwt, + apiKey: cred.apiKey, + userId: cred.userId, + status: "active", + enabled: true, + addedAt: nowIso(), + lastUsedAt: null, + lastError: null, + usageCount: 0, + }; + this.accounts.set(id, entry); + this.persist(); + return id; + } + + remove(id: string): boolean { + const ok = this.accounts.delete(id); + if (ok) this.persist(); + return ok; + } + + setEnabled(id: string, enabled: boolean): boolean { + const entry = this.accounts.get(id); + if (!entry) return false; + entry.enabled = enabled; + if (enabled && entry.status !== "blocked") entry.status = "active"; + this.persist(); + return true; + } + + clear(): void { + this.accounts.clear(); + this.persist(); + } + + private listSelectable(excludeIds: string[] = []): PoolAccount[] { + const exclude = new Set(excludeIds); + return this.list().filter( + (a) => a.enabled && a.status === "active" && a.jwt.length > 0 && !exclude.has(a.id), + ); + } + + acquire(excludeIds: string[] = []): PoolAccount | null { + const candidates = this.listSelectable(excludeIds); + if (candidates.length === 0) return null; + const idx = this.roundRobinIndex % candidates.length; + this.roundRobinIndex += 1; + return candidates[idx]; + } + + release(id: string): void { + const entry = this.accounts.get(id); + if (!entry) return; + entry.usageCount += 1; + entry.lastUsedAt = nowIso(); + this.persist(); + } + + markExhausted(id: string, message: string): void { + const entry = this.accounts.get(id); + if (!entry) return; + entry.status = "exhausted"; + entry.lastError = message; + this.persist(); + } + + /** Restore an exhausted account to the rotation pool. */ + markActive(id: string): boolean { + const entry = this.accounts.get(id); + if (!entry || entry.status === "blocked" || !entry.enabled) return false; + if (entry.status === "active") return true; + entry.status = "active"; + entry.lastError = null; + this.persist(); + return true; + } + + markBlocked(id: string, message: string): void { + const entry = this.accounts.get(id); + if (!entry) return; + entry.status = "blocked"; + entry.enabled = false; + entry.lastError = message; + this.persist(); + } + + markAuthError(id: string, message: string): void { + const entry = this.accounts.get(id); + if (!entry) return; + entry.status = "disabled"; + entry.lastError = message; + this.persist(); + } + + toCredential(account: PoolAccount): Credential { + return { + apiKey: account.apiKey ?? "start-plan", + provider: account.provider, + jwt: account.jwt, + userId: account.userId, + }; + } +} diff --git a/src/auth/billing.ts b/src/auth/billing.ts new file mode 100644 index 0000000..1ac29b8 --- /dev/null +++ b/src/auth/billing.ts @@ -0,0 +1,86 @@ +/** + * Start Plan billing helpers — quota buckets must exist before /v1/messages works. + */ +const BILLING_BASE = "https://zcode.z.ai/api/v1/zcode-plan/billing"; + +export interface BalanceBucket { + bucket_id?: string; + show_name?: string; + entitlement_id?: string; + total_units?: number; + used_units?: number; + remaining_units?: number; + available_units?: number; + period_start?: number; + period_end?: number; + expires_at?: number; +} + +export interface BalanceResponse { + ok: boolean; + status: number; + serverTime?: number; + balances: BalanceBucket[]; + raw?: string; +} + +function authHeaders(jwt: string): Record { + return { + authorization: `Bearer ${jwt}`, + accept: "application/json", + "User-Agent": "ZCode/3.1.2", + "X-ZCode-App-Version": "3.1.2", + }; +} + +export async function fetchBillingBalance(jwt: string): Promise { + const resp = await fetch(`${BILLING_BASE}/balance`, { headers: authHeaders(jwt) }); + const text = await resp.text(); + try { + const json = JSON.parse(text) as { + data?: { balances?: BalanceBucket[]; server_time?: number }; + }; + const balances = json?.data?.balances ?? []; + return { + ok: resp.ok, + status: resp.status, + serverTime: json?.data?.server_time, + balances, + raw: text, + }; + } catch { + return { ok: resp.ok, status: resp.status, balances: [], raw: text }; + } +} + +/** billing/current often appears before balance buckets are allocated for new accounts. */ +export async function fetchBillingCurrent(jwt: string): Promise<{ ok: boolean; status: number }> { + const resp = await fetch(`${BILLING_BASE}/current?app_version=3.1.2`, { + headers: authHeaders(jwt), + }); + return { ok: resp.ok, status: resp.status }; +} + +export async function waitForQuotaBuckets( + jwt: string, + opts: { timeoutMs?: number; intervalMs?: number } = {}, +): Promise { + const timeoutMs = opts.timeoutMs ?? 120_000; + const intervalMs = opts.intervalMs ?? 2_000; + const deadline = Date.now() + timeoutMs; + + let last: BalanceResponse = { ok: false, status: 0, balances: [] }; + + while (Date.now() < deadline) { + await fetchBillingCurrent(jwt); + last = await fetchBillingBalance(jwt); + if (last.balances.length > 0) return last; + await sleep(intervalMs); + } + + return last; +} + +function sleep(ms: number): Promise { + return new Promise((r) => setTimeout(r, ms)); +} diff --git a/src/auth/oauth.ts b/src/auth/oauth.ts index e2fc5e8..7ac20ca 100644 --- a/src/auth/oauth.ts +++ b/src/auth/oauth.ts @@ -36,6 +36,8 @@ export interface OAuthResult { userId?: string; /** ZCode plan JWT for start-plan (zcode.z.ai). The OAuth poll/exchange response includes this alongside the provider access_token. */ jwt?: string; + /** Raw OAuth user object (email, avatar, …) for desktop credential sync. */ + user?: Record; } export type FetchFn = typeof fetch; @@ -142,6 +144,7 @@ export class ZaiOAuthClient { token?: string; zai?: { access_token?: string }; userId?: string; + user?: Record; }> { const resp = await this.fetchImpl( `${ZCODE_OAUTH_BASE}/oauth/cli/poll/${encodeURIComponent(flowId)}`, @@ -174,12 +177,19 @@ export class ZaiOAuthClient { return { status }; } if (status === "ready") { - const user = data.user as { user_id?: string } | undefined; + const user = data.user as Record | undefined; + const userId = + typeof user?.user_id === "string" + ? user.user_id + : typeof user?.user_id === "number" + ? String(user.user_id) + : undefined; return { status: "ready", token: data.token as string | undefined, zai: data.zai as { access_token?: string } | undefined, - userId: typeof user?.user_id === "string" ? user.user_id : undefined, + userId, + user, }; } @@ -204,7 +214,13 @@ export class ZaiOAuthClient { if (!accessToken || typeof accessToken !== "string") { throw new Error("OAuth ready but no access_token in response"); } - return { accessToken, provider: "zai", userId: result.userId, jwt: result.token }; + return { + accessToken, + provider: "zai", + userId: result.userId, + jwt: result.token, + user: result.user, + }; } if (result.status === "failed") { throw new Error("Authorization failed. Please retry login."); diff --git a/src/auth/onboard-jobs.ts b/src/auth/onboard-jobs.ts new file mode 100644 index 0000000..9709045 --- /dev/null +++ b/src/auth/onboard-jobs.ts @@ -0,0 +1,156 @@ +/** + * Web-driven Start Plan onboarding — OAuth poll + quota provisioning. + */ +import { randomBytes } from "node:crypto"; +import { ZaiOAuthClient, type OAuthInitResponse } from "./oauth.js"; +import { onboardStartPlan } from "./onboard.js"; +import { saveCredential } from "./store.js"; +import type { AccountPool } from "./account-pool.js"; + +export type OnboardPhase = + | "oauth_pending" + | "provisioning" + | "done" + | "error"; + +export interface OnboardJobPublic { + id: string; + phase: OnboardPhase; + authorizeUrl?: string; + expiresAt?: number; + error?: string; + accountId?: string; + quotaReady?: boolean; + balanceCount?: number; +} + +interface OnboardJob extends OnboardJobPublic { + oauthInit?: OAuthInitResponse; + launchDesktop: boolean; + accountPool: AccountPool; + polling: boolean; +} + +export class OnboardJobManager { + private jobs = new Map(); + + start(opts: { launchDesktop?: boolean; accountPool: AccountPool }): Promise { + return this.createJob(opts); + } + + private async createJob(opts: { + launchDesktop?: boolean; + accountPool: AccountPool; + }): Promise { + const oauth = new ZaiOAuthClient(); + const init = await oauth.init("zai"); + const id = randomBytes(8).toString("hex"); + const job: OnboardJob = { + id, + phase: "oauth_pending", + authorizeUrl: init.authorizeUrl, + expiresAt: init.expiresAt, + oauthInit: init, + launchDesktop: opts.launchDesktop !== false, + accountPool: opts.accountPool, + polling: false, + }; + this.jobs.set(id, job); + void this.runOAuthPoll(job, oauth); + return this.publicView(job); + } + + get(id: string): OnboardJobPublic | undefined { + const job = this.jobs.get(id); + return job ? this.publicView(job) : undefined; + } + + private publicView(job: OnboardJob): OnboardJobPublic { + return { + id: job.id, + phase: job.phase, + authorizeUrl: job.authorizeUrl, + expiresAt: job.expiresAt, + error: job.error, + accountId: job.accountId, + quotaReady: job.quotaReady, + balanceCount: job.balanceCount, + }; + } + + private async runOAuthPoll(job: OnboardJob, oauth: ZaiOAuthClient): Promise { + if (job.polling || !job.oauthInit) return; + job.polling = true; + + const init = job.oauthInit; + const deadline = init.expiresAt; + const intervalMs = Math.max(1000, init.pollIntervalSec * 1000); + + try { + while (Date.now() < deadline && job.phase === "oauth_pending") { + await sleep(intervalMs); + const result = await oauth.poll(init.flowId, init.pollToken); + if (result.status === "failed") { + job.phase = "error"; + job.error = "Authorization failed or expired."; + return; + } + if (result.status === "ready") { + const accessToken = result.zai?.access_token ?? result.token; + const jwt = result.token; + if (!accessToken || !jwt?.trim()) { + job.phase = "error"; + job.error = "OAuth succeeded but no Start Plan JWT was returned."; + return; + } + job.phase = "provisioning"; + await this.provision(job, { + accessToken, + jwt: jwt.trim(), + userId: result.userId, + user: result.user, + }); + return; + } + } + if (job.phase === "oauth_pending") { + job.phase = "error"; + job.error = "Authorization timed out."; + } + } catch (err) { + job.phase = "error"; + job.error = (err as Error).message; + } finally { + job.polling = false; + } + } + + private async provision( + job: OnboardJob, + oauth: { accessToken: string; jwt: string; userId?: string; user?: Record }, + ): Promise { + try { + const result = await onboardStartPlan({ + provider: "zai", + jwt: oauth.jwt, + accessToken: oauth.accessToken, + userId: oauth.userId, + userInfo: oauth.user, + launchDesktop: job.launchDesktop, + }); + await saveCredential(result.credential); + const accountId = job.accountPool.addFromCredential(result.credential); + job.accountId = accountId; + job.quotaReady = result.quotaReady; + job.balanceCount = result.balanceCount; + job.phase = "done"; + } catch (err) { + job.phase = "error"; + job.error = (err as Error).message; + } + } +} + +function sleep(ms: number): Promise { + return new Promise((r) => setTimeout(r, ms)); +} diff --git a/src/auth/onboard.ts b/src/auth/onboard.ts new file mode 100644 index 0000000..5e742c8 --- /dev/null +++ b/src/auth/onboard.ts @@ -0,0 +1,91 @@ +/** + * Full Start Plan onboarding: OAuth → sync desktop creds → provision quota → proxy store. + */ +import type { Credential } from "./types.js"; +import type { ProviderId } from "../provider/types.js"; +import { + writeDesktopCredentials, + syncStartPlanConfigJwt, + decodeJwtUserId, +} from "./zcode-credentials.js"; +import { waitForQuotaBuckets } from "./billing.js"; +import { launchZcode, stopZcode } from "./zcode-launcher.js"; + +export interface OnboardOptions { + provider: ProviderId; + jwt: string; + accessToken: string; + userId?: string; + userInfo?: Record; + /** Launch ZCode GUI to trigger bucket allocation (default true). */ + launchDesktop?: boolean; + quotaTimeoutMs?: number; + /** Delay between billing polls while waiting for buckets (default 5s). */ + quotaPollIntervalMs?: number; +} + +export interface OnboardResult { + credential: Credential; + quotaReady: boolean; + balanceCount: number; +} + +export async function onboardStartPlan(opts: OnboardOptions): Promise { + const userId = opts.userId ?? decodeJwtUserId(opts.jwt); + + console.log("Writing credentials to ~/.zcode/v2/credentials.json ..."); + writeDesktopCredentials({ + jwt: opts.jwt, + accessToken: opts.accessToken, + userId, + userInfo: opts.userInfo, + activeProvider: opts.provider, + }); + syncStartPlanConfigJwt(opts.jwt); + + if (opts.launchDesktop !== false) { + console.log("Launching ZCode to provision Start Plan quota (close automatically when ready)..."); + try { + launchZcode(); + } catch (err) { + console.warn(`Could not launch ZCode: ${(err as Error).message}`); + console.warn("Continuing with API-only quota polling..."); + } + } + + console.log("Waiting for billing balance buckets..."); + const balance = await waitForQuotaBuckets(opts.jwt, { + timeoutMs: opts.quotaTimeoutMs ?? 120_000, + intervalMs: opts.quotaPollIntervalMs ?? 5_000, + }); + + if (opts.launchDesktop !== false) { + stopZcode(); + } + + const quotaReady = balance.balances.length > 0; + if (quotaReady) { + const first = balance.balances[0]; + console.log( + `Quota ready: ${balance.balances.length} bucket(s), ` + + `${first?.show_name ?? "model"} has ${first?.remaining_units ?? "?"} tokens left`, + ); + } else { + console.warn( + "Quota buckets still empty. Open ZCode, send one message in the app, then run: auth import-jwt", + ); + } + + const credential: Credential = { + apiKey: opts.accessToken, + provider: opts.provider, + jwt: opts.jwt, + userId, + }; + + return { + credential, + quotaReady, + balanceCount: balance.balances.length, + }; +} diff --git a/src/auth/quota-cache.test.ts b/src/auth/quota-cache.test.ts new file mode 100644 index 0000000..69e1aa3 --- /dev/null +++ b/src/auth/quota-cache.test.ts @@ -0,0 +1,30 @@ +import { describe, it, expect, mock } from "bun:test"; +import { AccountPool } from "./account-pool.js"; +import { QuotaCache } from "./quota-cache.js"; + +describe("QuotaCache", () => { + it("returns cached snapshot without live billing calls", async () => { + const pool = new AccountPool(); + pool.addFromCredential({ + apiKey: "start-plan", + provider: "zai", + jwt: "jwt-a", + userId: "user-a", + }); + + const fetchBalance = mock(async () => ({ + ok: true, + serverTime: 1000, + balances: [{ show_name: "GLM", total_units: 100, used_units: 0, remaining_units: 100, period_end: 2000, period_start: 0 }], + })); + + const cache = new QuotaCache(pool, 300, 0, fetchBalance); + await (cache as unknown as { runCycle(): Promise }).runCycle(); + + const snap = cache.getSnapshot(); + expect(snap.accounts).toHaveLength(1); + expect(snap.accounts[0]?.balances).toHaveLength(1); + expect(snap.cache.cycleIntervalSec).toBe(300); + expect(fetchBalance).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/auth/quota-cache.ts b/src/auth/quota-cache.ts new file mode 100644 index 0000000..ae4e47b --- /dev/null +++ b/src/auth/quota-cache.ts @@ -0,0 +1,173 @@ +/** + * Staggered Z.AI billing cache for the dashboard — one account per tick to avoid rate limits. + */ +import type { AccountPool } from "./account-pool.js"; +import { fetchBillingBalance, type BalanceBucket, type BalanceResponse } from "./billing.js"; +import { accountHasQuota } from "./quota-refresh.js"; + +export interface QuotaCacheAccount { + id: string; + userId?: string; + status: string; + enabled: boolean; + usageCount: number; + lastUsedAt: number | null; + ok: boolean; + serverTime?: number; + balances: Array<{ + show_name: string; + total_units: number; + used_units: number; + remaining_units: number; + period_end: number; + period_start: number; + }>; + fetchedAt: number | null; +} + +export interface QuotaCacheSnapshot { + accounts: QuotaCacheAccount[]; + cache: { + refreshing: boolean; + cycleIntervalSec: number; + fetchDelaySec: number; + /** Epoch milliseconds when the next refresh cycle starts. */ + nextRefreshAt: number | null; + lastCompletedAt: number | null; + }; +} + +function mapBalances(balances: BalanceBucket[]) { + return balances.map((b) => ({ + show_name: b.show_name, + total_units: b.total_units, + used_units: b.used_units, + remaining_units: b.remaining_units, + period_end: b.period_end, + period_start: b.period_start, + })); +} + +function entryFromAccount( + account: ReturnType[number], + balance: BalanceResponse | null, +): QuotaCacheAccount { + return { + id: account.id, + userId: account.userId, + status: account.status, + enabled: account.enabled, + usageCount: account.usageCount, + lastUsedAt: account.lastUsedAt, + ok: balance?.ok ?? false, + serverTime: balance?.serverTime, + balances: balance ? mapBalances(balance.balances) : [], + fetchedAt: balance ? Date.now() : null, + }; +} + +export class QuotaCache { + private entries = new Map(); + private cycleTimer: ReturnType | null = null; + private refreshing = false; + private nextRefreshAt: number | null = null; + private lastCompletedAt: number | null = null; + + constructor( + private pool: AccountPool, + private cycleIntervalSec: number, + private fetchDelaySec: number, + private fetchBalance: (jwt: string) => Promise = fetchBillingBalance, + ) {} + + start(): void { + if (this.cycleTimer) return; + void this.scheduleNextCycle(0); + } + + stop(): void { + if (this.cycleTimer) { + clearTimeout(this.cycleTimer); + this.cycleTimer = null; + } + } + + getSnapshot(): QuotaCacheSnapshot { + const accounts = this.pool.list().map((account) => { + const cached = this.entries.get(account.id); + if (cached) { + return { + ...cached, + status: account.status, + enabled: account.enabled, + usageCount: account.usageCount, + lastUsedAt: account.lastUsedAt, + userId: account.userId ?? cached.userId, + }; + } + return entryFromAccount(account, null); + }); + + return { + accounts, + cache: { + refreshing: this.refreshing, + cycleIntervalSec: this.cycleIntervalSec, + fetchDelaySec: this.fetchDelaySec, + nextRefreshAt: this.nextRefreshAt, + lastCompletedAt: this.lastCompletedAt, + }, + }; + } + + private scheduleNextCycle(delayMs: number): void { + if (this.cycleTimer) clearTimeout(this.cycleTimer); + this.cycleTimer = setTimeout(() => void this.runCycle(), delayMs); + } + + private async runCycle(): Promise { + if (this.refreshing) return; + this.refreshing = true; + this.nextRefreshAt = null; + + const accounts = this.pool.list(); + const delayMs = this.fetchDelaySec * 1000; + + try { + for (let i = 0; i < accounts.length; i++) { + const account = accounts[i]!; + try { + const balance = await this.fetchBalance(account.jwt); + this.entries.set(account.id, entryFromAccount(account, balance)); + + if (account.status === "exhausted" && account.enabled && accountHasQuota(balance)) { + if (this.pool.markActive(account.id)) { + const label = account.userId ?? account.id; + const first = balance.balances.find((b) => (b.remaining_units ?? 0) > 0); + console.log( + `[pool] reactivated ${label}` + + (first?.show_name ? ` (${first.show_name}: ${first.remaining_units} tokens)` : ""), + ); + } + } + } catch (err) { + console.warn(`[quota-cache] billing failed for ${account.id}: ${(err as Error).message}`); + this.entries.set(account.id, entryFromAccount(account, null)); + } + + if (i < accounts.length - 1 && delayMs > 0) { + await sleep(delayMs); + } + } + this.lastCompletedAt = Date.now(); + } finally { + this.refreshing = false; + this.nextRefreshAt = Date.now() + this.cycleIntervalSec * 1000; + this.scheduleNextCycle(this.cycleIntervalSec * 1000); + } + } +} + +function sleep(ms: number): Promise { + return new Promise((r) => setTimeout(r, ms)); +} diff --git a/src/auth/quota-refresh.test.ts b/src/auth/quota-refresh.test.ts new file mode 100644 index 0000000..33ff203 --- /dev/null +++ b/src/auth/quota-refresh.test.ts @@ -0,0 +1,95 @@ +import { describe, it, expect, beforeEach, afterEach } from "bun:test"; +import { existsSync, unlinkSync } from "node:fs"; +import { AccountPool, getAccountsStorePath } from "./account-pool.js"; +import { QuotaRefreshScheduler, accountHasQuota } from "./quota-refresh.js"; +import type { BalanceResponse } from "./billing.js"; + +const CRED = { + apiKey: "k", + provider: "zai" as const, + jwt: "eyJhbG.header.payload", + userId: "user-a", +}; + +describe("accountHasQuota", () => { + it("returns true when any bucket has remaining tokens", () => { + expect( + accountHasQuota({ + ok: true, + status: 200, + balances: [{ remaining_units: 100, total_units: 1000 }], + }), + ).toBe(true); + }); + + it("returns false when all buckets empty", () => { + expect( + accountHasQuota({ + ok: true, + status: 200, + balances: [{ remaining_units: 0, total_units: 1000 }], + }), + ).toBe(false); + }); +}); + +describe("QuotaRefreshScheduler", () => { + beforeEach(() => { + const path = getAccountsStorePath(); + if (existsSync(path)) unlinkSync(path); + }); + + afterEach(() => { + const path = getAccountsStorePath(); + if (existsSync(path)) unlinkSync(path); + }); + + it("reactivates exhausted account when billing shows quota", async () => { + const pool = new AccountPool(); + const id = pool.addFromCredential(CRED); + pool.markExhausted(id, "1005"); + expect(pool.activeCount()).toBe(0); + + const scheduler = new QuotaRefreshScheduler(pool, 60_000, async () => ({ + ok: true, + status: 200, + balances: [{ show_name: "GLM-5.2", remaining_units: 500_000, total_units: 3_000_000 }], + })); + + const n = await scheduler.runOnce(); + expect(n).toBe(1); + expect(pool.activeCount()).toBe(1); + expect(pool.get(id)?.status).toBe("active"); + expect(pool.get(id)?.lastError).toBeNull(); + }); + + it("leaves exhausted when billing still empty", async () => { + const pool = new AccountPool(); + const id = pool.addFromCredential(CRED); + pool.markExhausted(id, "1005"); + + const scheduler = new QuotaRefreshScheduler(pool, 60_000, async () => ({ + ok: true, + status: 200, + balances: [{ remaining_units: 0, total_units: 3_000_000 }], + })); + + expect(await scheduler.runOnce()).toBe(0); + expect(pool.get(id)?.status).toBe("exhausted"); + }); + + it("does not reactivate blocked accounts", async () => { + const pool = new AccountPool(); + const id = pool.addFromCredential(CRED); + pool.markBlocked(id, "3012"); + + const scheduler = new QuotaRefreshScheduler(pool, 60_000, async () => ({ + ok: true, + status: 200, + balances: [{ remaining_units: 1_000_000 }], + })); + + expect(await scheduler.runOnce()).toBe(0); + expect(pool.get(id)?.status).toBe("blocked"); + }); +}); diff --git a/src/auth/quota-refresh.ts b/src/auth/quota-refresh.ts new file mode 100644 index 0000000..dbbb8ed --- /dev/null +++ b/src/auth/quota-refresh.ts @@ -0,0 +1,61 @@ +/** + * Periodically re-check billing for exhausted accounts and reactivate when quota returns. + */ +import type { AccountPool } from "./account-pool.js"; +import { fetchBillingBalance, type BalanceResponse } from "./billing.js"; + +export type FetchBalanceFn = (jwt: string) => Promise; + +export function accountHasQuota(balance: BalanceResponse): boolean { + if (!balance.ok || balance.balances.length === 0) return false; + return balance.balances.some( + (b) => (b.remaining_units ?? b.available_units ?? 0) > 0, + ); +} + +export class QuotaRefreshScheduler { + private timer: ReturnType | null = null; + + constructor( + private pool: AccountPool, + private intervalMs: number, + private fetchBalance: FetchBalanceFn = fetchBillingBalance, + ) {} + + start(): void { + if (this.timer) return; + void this.runOnce(); + this.timer = setInterval(() => void this.runOnce(), this.intervalMs); + } + + stop(): void { + if (this.timer) { + clearInterval(this.timer); + this.timer = null; + } + } + + /** Check exhausted accounts; return count reactivated. */ + async runOnce(): Promise { + let reactivated = 0; + for (const account of this.pool.list()) { + if (account.status !== "exhausted" || !account.enabled) continue; + try { + const balance = await this.fetchBalance(account.jwt); + if (!accountHasQuota(balance)) continue; + if (this.pool.markActive(account.id)) { + reactivated += 1; + const label = account.userId ?? account.id; + const first = balance.balances.find((b) => (b.remaining_units ?? 0) > 0); + console.log( + `[pool] reactivated ${label}` + + (first?.show_name ? ` (${first.show_name}: ${first.remaining_units} tokens)` : ""), + ); + } + } catch (err) { + console.warn(`[pool] quota refresh failed for ${account.id}: ${(err as Error).message}`); + } + } + return reactivated; + } +} diff --git a/src/auth/zcode-credentials.test.ts b/src/auth/zcode-credentials.test.ts new file mode 100644 index 0000000..b01cb7a --- /dev/null +++ b/src/auth/zcode-credentials.test.ts @@ -0,0 +1,21 @@ +import { describe, it, expect } from "bun:test"; +import { + encryptCredential, + decryptStoredCredential, + decodeJwtUserId, +} from "./zcode-credentials.js"; + +describe("zcode-credentials", () => { + it("encrypt/decrypt round-trips", () => { + const plain = "eyJhbGciOi.test.jwt"; + const enc = encryptCredential(plain); + expect(enc.startsWith("enc:v1:")).toBe(true); + expect(decryptStoredCredential(enc)).toBe(plain); + }); + + it("decodeJwtUserId reads user_id from payload", () => { + const payload = Buffer.from(JSON.stringify({ user_id: "abc-123" })).toString("base64url"); + const jwt = `x.${payload}.y`; + expect(decodeJwtUserId(jwt)).toBe("abc-123"); + }); +}); diff --git a/src/auth/zcode-credentials.ts b/src/auth/zcode-credentials.ts new file mode 100644 index 0000000..5668fe3 --- /dev/null +++ b/src/auth/zcode-credentials.ts @@ -0,0 +1,123 @@ +/** + * Read/write encrypted credentials in ZCode desktop store (~/.zcode/v2/credentials.json). + */ +import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { homedir, platform, userInfo } from "node:os"; +import { dirname, join } from "node:path"; + +const ENC_PREFIX = "enc:v1:"; +const ZCODE_V2_DIR = join(homedir(), ".zcode", "v2"); +const CREDENTIALS_FILE = join(ZCODE_V2_DIR, "credentials.json"); +const CONFIG_FILE = join(ZCODE_V2_DIR, "config.json"); + +function deriveKey(): Buffer { + const fromEnv = process.env.ZCODE_CREDENTIAL_SECRET?.trim(); + let username = "unknown"; + try { + username = userInfo().username; + } catch { + // ignore + } + const secret = fromEnv ?? `zcode-credential-fallback:${platform()}:${homedir()}:${username}`; + return createHash("sha256").update(secret).digest(); +} + +export function encryptCredential(plaintext: string): string { + const key = deriveKey(); + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", key, iv); + const encrypted = Buffer.concat([cipher.update(plaintext, "utf-8"), cipher.final()]); + const tag = cipher.getAuthTag(); + return `${ENC_PREFIX}${iv.toString("base64url")}.${tag.toString("base64url")}.${encrypted.toString("base64url")}`; +} + +function decryptCredential(value: string): string { + if (!value.startsWith(ENC_PREFIX)) return value; + const parts = value.slice(ENC_PREFIX.length).split("."); + if (parts.length !== 3) throw new Error("Invalid encrypted credential format"); + const [ivB64, tagB64, cipherB64] = parts; + const key = deriveKey(); + const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64url")); + decipher.setAuthTag(Buffer.from(tagB64, "base64url")); + return Buffer.concat([ + decipher.update(Buffer.from(cipherB64, "base64url")), + decipher.final(), + ]).toString("utf-8"); +} + +export function zcodeCredentialsPath(): string { + return CREDENTIALS_FILE; +} + +export function loadZcodeJwtFromDesktop(): string | null { + if (!existsSync(CREDENTIALS_FILE)) return null; + const store = JSON.parse(readFileSync(CREDENTIALS_FILE, "utf-8")) as Record; + const raw = store.zcodejwttoken; + if (!raw) return null; + return decryptCredential(raw).trim() || null; +} + +export interface DesktopCredentialWrite { + jwt: string; + accessToken?: string; + userId?: string; + /** Full OAuth user object when available (email, avatar, name, …). */ + userInfo?: Record; + activeProvider?: string; +} + +/** Write OAuth session into ZCode desktop credential store (encrypted). */ +export function writeDesktopCredentials(opts: DesktopCredentialWrite): void { + mkdirSync(dirname(CREDENTIALS_FILE), { recursive: true }); + + let store: Record = {}; + if (existsSync(CREDENTIALS_FILE)) { + store = JSON.parse(readFileSync(CREDENTIALS_FILE, "utf-8")) as Record; + } + + store.zcodejwttoken = encryptCredential(opts.jwt); + if (opts.accessToken) { + store["oauth:zai:access_token"] = encryptCredential(opts.accessToken); + } + const userInfo = + opts.userInfo ?? + (opts.userId ? { user_id: opts.userId } : undefined); + if (userInfo) { + store["oauth:zai:user_info"] = encryptCredential(JSON.stringify(userInfo)); + } + store["oauth:active_provider"] = encryptCredential(opts.activeProvider ?? "zai"); + + writeFileSync(CREDENTIALS_FILE, JSON.stringify(store, null, 2), { mode: 0o600 }); +} + +/** Point builtin:zai-start-plan at the new JWT in config.json. */ +export function syncStartPlanConfigJwt(jwt: string): void { + if (!existsSync(CONFIG_FILE)) return; + + const config = JSON.parse(readFileSync(CONFIG_FILE, "utf-8")) as { + provider?: Record; + }; + const entry = config.provider?.["builtin:zai-start-plan"]; + if (!entry?.options) return; + + entry.options.apiKey = jwt; + writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 }); +} + +export function decodeJwtUserId(jwt: string): string | undefined { + try { + const payload = JSON.parse(Buffer.from(jwt.split(".")[1]!, "base64url").toString("utf-8")) as { + user_id?: string; + sub?: string; + }; + return payload.user_id ?? payload.sub; + } catch { + return undefined; + } +} + +/** Round-trip helper for tests. */ +export function decryptStoredCredential(enc: string): string { + return decryptCredential(enc); +} diff --git a/src/auth/zcode-launcher.ts b/src/auth/zcode-launcher.ts new file mode 100644 index 0000000..dff214e --- /dev/null +++ b/src/auth/zcode-launcher.ts @@ -0,0 +1,43 @@ +/** + * Launch ZCode briefly so the host process provisions Start Plan balance buckets. + */ +import { spawn, execSync } from "node:child_process"; +import { existsSync } from "node:fs"; + +const DEFAULT_PATHS = ["/opt/ZCode/zcode", "/usr/bin/zcode"]; + +export function resolveZcodeBinary(): string { + const fromEnv = process.env.ZCODE_BIN?.trim(); + if (fromEnv && existsSync(fromEnv)) return fromEnv; + for (const p of DEFAULT_PATHS) { + if (existsSync(p)) return p; + } + try { + return execSync("which zcode", { encoding: "utf-8" }).trim(); + } catch { + throw new Error("ZCode binary not found. Set ZCODE_BIN=/path/to/zcode"); + } +} + +/** Start ZCode detached (GUI). Returns child pid when available. */ +export function launchZcode(): number | undefined { + const bin = resolveZcodeBinary(); + const child = spawn(bin, [], { + detached: true, + stdio: "ignore", + }); + child.unref(); + return child.pid ?? undefined; +} + +/** Best-effort shutdown of ZCode processes started for onboarding. */ +export function stopZcode(): void { + const patterns = ["/opt/ZCode/zcode", "ZCode/zcode"]; + for (const pattern of patterns) { + try { + execSync(`pkill -f "${pattern}"`, { stdio: "ignore" }); + } catch { + // no matching process + } + } +} diff --git a/src/config/loader.test.ts b/src/config/loader.test.ts index 38a8a2e..f4027a5 100644 --- a/src/config/loader.test.ts +++ b/src/config/loader.test.ts @@ -162,7 +162,7 @@ auth: apiKey: "abc" `); const cfg = loadConfig(path); - expect(cfg.identity.appVersion).toBe("3.1.1"); + expect(cfg.identity.appVersion).toBe("3.1.2"); expect(cfg.identity.sourceTitle).toBe("cli"); expect(cfg.identity.refererOrigin).toBe("https://zcode.z.ai"); }); @@ -205,6 +205,6 @@ identity: appVersion: "v3.1.1-中文" `); const cfg = loadConfig(path); - expect(cfg.identity.appVersion).toBe("3.1.1"); + expect(cfg.identity.appVersion).toBe("3.1.2"); }); }); diff --git a/src/config/loader.ts b/src/config/loader.ts index 0035000..e213622 100644 --- a/src/config/loader.ts +++ b/src/config/loader.ts @@ -28,7 +28,7 @@ const DEFAULTS = { ZAI_OPENAI_BASE: "https://api.z.ai/api/coding/paas/v4", BIGMODEL_ANTHROPIC_BASE: "https://open.bigmodel.cn/api/anthropic", BIGMODEL_OPENAI_BASE: "https://open.bigmodel.cn/api/coding/paas/v4", - APP_VERSION: "3.1.1", + APP_VERSION: "3.1.2", SOURCE_TITLE: "cli", REFERER_ORIGIN: "https://zcode.z.ai", }; @@ -101,6 +101,7 @@ export function loadConfig(path: string): ProxyConfig { models, identity, logging: { level: logLevel }, + pool: resolvePool(parsed.pool), }; validate(config); @@ -131,6 +132,28 @@ function resolvePlan(raw: unknown): "coding-plan" | "start-plan" { return DEFAULTS.PLAN; } +function resolvePool(raw: unknown): ProxyConfig["pool"] { + if (!raw || typeof raw !== "object") { + return { enabled: true, maxAccountAttempts: 5, quotaRefreshIntervalSec: 300, quotaFetchDelaySec: 5 }; + } + const p = raw as Record; + return { + enabled: p.enabled !== false, + maxAccountAttempts: + typeof p.maxAccountAttempts === "number" && p.maxAccountAttempts > 0 + ? p.maxAccountAttempts + : 5, + quotaRefreshIntervalSec: + typeof p.quotaRefreshIntervalSec === "number" && p.quotaRefreshIntervalSec > 0 + ? p.quotaRefreshIntervalSec + : 300, + quotaFetchDelaySec: + typeof p.quotaFetchDelaySec === "number" && p.quotaFetchDelaySec >= 0 + ? p.quotaFetchDelaySec + : 5, + }; +} + /** Resolve log level with fallback. */ function resolveLogLevel(raw: unknown): "debug" | "info" | "warn" | "error" { const levels = ["debug", "info", "warn", "error"] as const; diff --git a/src/config/types.ts b/src/config/types.ts index 9c97a6e..b80ac3b 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -72,4 +72,15 @@ export interface ProxyConfig { logging: { level: "debug" | "info" | "warn" | "error"; }; + /** Start-plan multi-account pool (optional). */ + pool?: { + /** Enable JWT account rotation for start-plan (default: true when accounts exist). */ + enabled?: boolean; + /** Max accounts to try per client request (default 5). */ + maxAccountAttempts?: number; + /** How often to run a full staggered billing refresh cycle (seconds, default 300). */ + quotaRefreshIntervalSec?: number; + /** Delay between each account billing API call within a cycle (seconds, default 5). */ + quotaFetchDelaySec?: number; + }; } diff --git a/src/index.ts b/src/index.ts index 07c740d..cf3af7d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,6 +9,13 @@ import { startServer } from "./server/server.js"; import { loadCredential, saveCredential, clearCredential, getStorePath } from "./auth/store.js"; import { ZaiOAuthClient, BigmodelOAuthClient } from "./auth/oauth.js"; import { KeyResolver } from "./auth/resolver.js"; +import { loadZcodeJwtFromDesktop, decodeJwtUserId } from "./auth/zcode-credentials.js"; +import { onboardStartPlan } from "./auth/onboard.js"; +import { AccountPool } from "./auth/account-pool.js"; +import { OnboardJobManager } from "./auth/onboard-jobs.js"; +import { RequestLogStore } from "./server/request-logs.js"; +import { QuotaCache } from "./auth/quota-cache.js"; +import { getProactiveCaptchaHeaders } from "./proxy/captcha.js"; import type { Credential } from "./auth/types.js"; import type { ProviderId } from "./provider/types.js"; import { spawn } from "node:child_process"; @@ -45,19 +52,26 @@ function printHelp(): void { Usage: zcode-proxy serve [config.yaml] Start the proxy server (default) - zcode-proxy auth login Login via OAuth (provider: zai | bigmodel) - zcode-proxy auth login --import - Import API key from ~/.zcode/v2/config.json + zcode-proxy auth login [--import] + OAuth login, or import API key from ~/.zcode/v2/config.json + zcode-proxy auth import-jwt [zai] Import Start Plan JWT from ~/.zcode/v2/credentials.json + zcode-proxy auth onboard OAuth + sync desktop + provision quota (adds to pool) + zcode-proxy auth accounts List account pool + zcode-proxy auth add [name] Add JWT to pool (desktop or --jwt) + zcode-proxy auth remove Remove account from pool zcode-proxy auth logout Clear stored credentials zcode-proxy auth status Show current authentication state zcode-proxy version Show version zcode-proxy help Show this help +Web dashboard (recommended): open http://localhost:8080/app after starting the server. +Manage accounts, OAuth onboard, and test requests from the browser. + Examples: zcode-proxy Start server with default config.yaml - zcode-proxy auth login bigmodel OAuth login for Bigmodel - zcode-proxy auth login bigmodel --import - Import existing key from ZCode config + zcode-proxy auth login zai OAuth login for Z.AI (captures start-plan JWT) + zcode-proxy auth import-jwt Import JWT from ZCode desktop (start-plan) + zcode-proxy auth onboard zai Full new-account setup (OAuth → ZCode → quota) zcode-proxy auth status Check if logged in `); } @@ -71,6 +85,27 @@ async function serve(configPath?: string): Promise { } const config = loadConfig(path); + if (config.plan === "start-plan" && config.auth.mode !== "oauth") { + console.error("start-plan requires auth.mode: oauth (set plan: start-plan and auth.mode: oauth in config.yaml)"); + process.exit(1); + } + + const accountPool = new AccountPool(); + await accountPool.migrateFromLegacyCredential(); + + if (accountPool.size() === 0 && config.plan === "start-plan") { + const desktopJwt = loadZcodeJwtFromDesktop(); + if (desktopJwt) { + accountPool.addFromCredential({ + apiKey: "start-plan", + provider: config.provider, + jwt: desktopJwt, + userId: decodeJwtUserId(desktopJwt), + }); + console.log("Auto-imported Start Plan JWT from ZCode desktop"); + } + } + const auth = new AuthManager({ mode: config.auth.mode, provider: config.provider, @@ -78,28 +113,66 @@ async function serve(configPath?: string): Promise { }); if (config.auth.mode === "oauth") { - const cred = await loadCredential(); - if (!cred) { - console.error("Not logged in. Run: zcode-proxy auth login " + config.provider); - process.exit(1); + if (config.plan === "start-plan") { + if (accountPool.activeCount() === 0) { + const cred = await loadCredential(); + if (cred?.jwt) { + accountPool.addFromCredential(cred); + } + } + const cred = await loadCredential(); + if (cred) auth.setOAuthCredential(cred); + } else { + const cred = await loadCredential(); + if (!cred) { + console.error("Not logged in. Run: zcode-proxy auth login " + config.provider); + process.exit(1); + } + auth.setOAuthCredential(cred); } - auth.setOAuthCredential(cred); } - const server = startServer({ config, auth }); + const onboardJobs = new OnboardJobManager(); + const requestLogs = new RequestLogStore(); + + let quotaCache: QuotaCache | undefined; + if (config.plan === "start-plan" && config.pool?.enabled !== false) { + const cycleSec = config.pool?.quotaRefreshIntervalSec ?? 300; + const delaySec = config.pool?.quotaFetchDelaySec ?? 5; + quotaCache = new QuotaCache(accountPool, cycleSec, delaySec); + quotaCache.start(); + } + + const server = startServer({ config, auth, accountPool, onboardJobs, requestLogs, quotaCache }); const url = `http://${server.hostname}:${server.port}`; console.log(`zcode-proxy listening on ${url}`); + console.log(` dashboard: ${url}/app`); console.log(` provider: ${config.provider}`); console.log(` plan: ${config.plan}`); console.log(` auth mode: ${config.auth.mode}`); console.log(` models: ${config.models.length} available`); + if (config.plan === "start-plan") { + const n = accountPool.activeCount(); + const cycleSec = config.pool?.quotaRefreshIntervalSec ?? 300; + const delaySec = config.pool?.quotaFetchDelaySec ?? 5; + console.log(` account pool: ${n}/${accountPool.size()} active`); + console.log(` quota cache: cycle ${cycleSec}s, ${delaySec}s between Z.AI billing calls`); + if (n === 0) { + console.log(` → add accounts at ${url}/app`); + } + void getProactiveCaptchaHeaders(config.identity.appVersion) + .then(() => console.log(" captcha: pre-warmed")) + .catch((err) => console.warn(" captcha pre-warm failed:", (err as Error).message)); + } process.on("SIGINT", () => { console.log("\nShutting down..."); + quotaCache?.stop(); server.stop(true); process.exit(0); }); process.on("SIGTERM", () => { + quotaCache?.stop(); server.stop(true); process.exit(0); }); @@ -110,16 +183,95 @@ function authCommand(args: string[]): void { if (sub === "login") { authLogin(args.slice(1)); + } else if (sub === "import-jwt") { + authImportJwt(args.slice(1)); + } else if (sub === "onboard") { + authOnboard(args.slice(1)); + } else if (sub === "accounts") { + authAccounts(); + } else if (sub === "add") { + authAdd(args.slice(1)); + } else if (sub === "remove") { + authRemove(args.slice(1)); } else if (sub === "logout") { authLogout(); } else if (sub === "status") { authStatus(); } else { - console.error("Usage: zcode-proxy auth "); + console.error("Usage: zcode-proxy auth "); process.exit(1); } } +async function authOnboard(args: string[]): Promise { + const provider = (args.find((a) => a === "zai" || a === "bigmodel") ?? "zai") as ProviderId; + const skipDesktop = args.includes("--no-zcode"); + + if (provider !== "zai") { + console.error("Start Plan onboard currently supports: zai"); + process.exit(1); + } + + console.log("Start Plan onboard — OAuth login, sync ZCode desktop, provision quota\n"); + + const { accessToken, userId, jwt, user } = await runOAuth(provider); + if (!jwt?.trim()) { + console.error("OAuth succeeded but no Start Plan JWT in response. Try logging into ZCode desktop instead."); + process.exit(1); + } + + const result = await onboardStartPlan({ + provider, + jwt, + accessToken, + userId, + userInfo: user, + launchDesktop: !skipDesktop, + }); + + await saveCredential(result.credential); + const pool = new AccountPool(); + const poolId = pool.addFromCredential(result.credential); + + console.log(`\nOnboard complete (${result.quotaReady ? "quota ready" : "quota pending"}).`); + console.log(` User ID: ${result.credential.userId ?? "?"}`); + console.log(` Pool id: ${poolId}`); + console.log(` Pool: ${getAccountsStorePath()}`); + console.log("\nStart proxy: bun run src/index.ts"); + if (!result.quotaReady) process.exit(1); +} + +async function authImportJwt(args: string[]): Promise { + const provider = (args[0] ?? "zai") as ProviderId; + if (provider !== "zai" && provider !== "bigmodel") { + console.error("Usage: zcode-proxy auth import-jwt [zai|bigmodel]"); + process.exit(1); + } + + const jwt = loadZcodeJwtFromDesktop(); + if (!jwt) { + console.error("No JWT in ~/.zcode/v2/credentials.json."); + console.error("Log into the ZCode desktop app first, then retry."); + process.exit(1); + } + + const cred: Credential = { + apiKey: "start-plan", + provider, + jwt, + userId: decodeJwtUserId(jwt), + }; + + await saveCredential(cred); + const pool = new AccountPool(); + const poolId = pool.addFromCredential(cred); + + console.log(`\nImported start-plan JWT for ${provider}.`); + if (cred.userId) console.log(` User ID: ${cred.userId}`); + console.log(` Pool id: ${poolId}`); + console.log(` JWT: ${jwt.slice(0, 16)}...`); +} + async function authLogin(args: string[]): Promise { const provider = args[0] as ProviderId | undefined; const importMode = args.includes("--import"); @@ -145,21 +297,81 @@ async function authLogin(args: string[]): Promise { await saveCredential(cred); console.log(`\nLogged in as ${provider}.`); - console.log(` API Key: ${cred.apiKey.substring(0, 12)}...`); + if (cred.apiKey && cred.apiKey !== "start-plan") { + console.log(` API Key: ${cred.apiKey.substring(0, 12)}...`); + } + if (cred.jwt) console.log(` Start-plan JWT: ${cred.jwt.slice(0, 16)}...`); if (cred.userId) console.log(` User ID: ${cred.userId}`); console.log(` Stored: ${getStorePath()}`); } function authLogout(): void { + const pool = new AccountPool(); + pool.clear(); if (!existsSync(getStorePath())) { console.log("Not logged in."); return; } clearCredential(); - console.log("Logged out. Credentials removed."); + console.log("Logged out. Credentials and account pool cleared."); +} + +function authAccounts(): void { + const pool = new AccountPool(); + const accounts = pool.listPublic(); + if (accounts.length === 0) { + console.log("Account pool is empty."); + console.log("Run: bun run src/index.ts auth onboard zai"); + return; + } + console.log(`Account pool (${pool.activeCount()} active / ${accounts.length} total)\n`); + console.log("ID | Status | Name | User ID | Uses"); + console.log("---------|-----------|----------------------|--------------------------------------|-----"); + for (const a of accounts) { + console.log( + `${a.id.padEnd(8)} | ${a.status.padEnd(9)} | ${a.name.slice(0, 20).padEnd(20)} | ${(a.userId ?? "-").padEnd(36)} | ${a.usageCount}`, + ); + } + console.log(`\nStore: ${getAccountsStorePath()}`); +} + +async function authAdd(args: string[]): Promise { + const jwtFlag = args.findIndex((a) => a === "--jwt"); + const jwt = + jwtFlag >= 0 && args[jwtFlag + 1] + ? args[jwtFlag + 1]!.trim() + : loadZcodeJwtFromDesktop(); + if (!jwt) { + console.error("No JWT. Use --jwt or log into ZCode desktop first."); + process.exit(1); + } + const pool = new AccountPool(); + const id = pool.addFromCredential( + { apiKey: "start-plan", provider: "zai", jwt, userId: decodeJwtUserId(jwt) }, + ); + console.log(`Added to pool: ${decodeJwtUserId(jwt) ?? id} (${id})`); +} + +function authRemove(args: string[]): void { + const id = args[0]; + if (!id) { + console.error("Usage: zcode-proxy auth remove "); + process.exit(1); + } + const pool = new AccountPool(); + if (!pool.remove(id)) { + console.error(`Account not found: ${id}`); + process.exit(1); + } + console.log(`Removed account ${id}`); } async function authStatus(): Promise { + const pool = new AccountPool(); + if (pool.size() > 0) { + authAccounts(); + return; + } const cred = await loadCredential(); if (!cred) { console.log("Not logged in."); @@ -167,11 +379,23 @@ async function authStatus(): Promise { return; } console.log(`Logged in: ${cred.provider}`); - console.log(` API Key: ${cred.apiKey.substring(0, 12)}...`); + if (cred.userId) console.log(` User ID: ${cred.userId}`); + if (cred.apiKey && cred.apiKey !== "start-plan") { + console.log(` API Key: ${cred.apiKey.substring(0, 12)}...`); + } + if (cred.jwt) console.log(` Start-plan JWT: ${cred.jwt.slice(0, 16)}...`); console.log(` Store: ${getStorePath()}`); + if (!cred.jwt) { + console.log("\n For start-plan: bun run src/index.ts auth import-jwt"); + } } -async function runOAuth(provider: ProviderId): Promise<{ accessToken: string; userId?: string; jwt?: string }> { +async function runOAuth(provider: ProviderId): Promise<{ + accessToken: string; + userId?: string; + jwt?: string; + user?: Record; +}> { if (provider === "bigmodel") { const oauth = new BigmodelOAuthClient(); const result = await oauth.authorize((url) => { @@ -193,7 +417,12 @@ async function runOAuth(provider: ProviderId): Promise<{ accessToken: string; us openBrowser(init.authorizeUrl); const result = await oauth.waitForAuth(init); - return { accessToken: result.accessToken, userId: result.userId, jwt: result.jwt }; + return { + accessToken: result.accessToken, + userId: result.userId, + jwt: result.jwt, + user: result.user, + }; } function importFromZCodeConfig(provider: ProviderId): Credential { @@ -221,7 +450,8 @@ function importFromZCodeConfig(provider: ProviderId): Credential { } const startPlanKey = `builtin:${provider}-start-plan`; - const jwt = config.provider?.[startPlanKey]?.options?.apiKey?.trim() || undefined; + let jwt = config.provider?.[startPlanKey]?.options?.apiKey?.trim() || undefined; + if (!jwt) jwt = loadZcodeJwtFromDesktop() ?? undefined; console.log(`Imported from ${configPath}`); if (jwt) console.log(` Start-plan JWT: ${jwt.slice(0, 12)}...`); diff --git a/src/proxy/body-transformer.test.ts b/src/proxy/body-transformer.test.ts index b4f6ecf..caf6cc3 100644 --- a/src/proxy/body-transformer.test.ts +++ b/src/proxy/body-transformer.test.ts @@ -221,3 +221,26 @@ describe("transformRequestBody — metadata.user_id (Anthropic)", () => { expect(parsed.metadata).toBeUndefined(); }); }); + +describe("transformRequestBody — start-plan system blocks", () => { + it("injects official ZCode gateway blocks for start-plan anthropic requests", () => { + const body = JSON.stringify({ + model: "glm-5.2", + messages: [{ role: "user", content: "hi" }], + }); + const out = transformRequestBody(body, { format: "anthropic", plan: "start-plan" }); + const parsed = JSON.parse(out as string); + expect(Array.isArray(parsed.system)).toBe(true); + expect(parsed.system.length).toBeGreaterThanOrEqual(2); + expect(parsed.system[0].text).toContain("ZCode"); + }); + + it("does NOT inject system blocks for coding-plan", () => { + const body = JSON.stringify({ + messages: [{ role: "user", content: "hi" }], + }); + const out = transformRequestBody(body, { format: "anthropic", plan: "coding-plan" }); + const parsed = JSON.parse(out as string); + expect(parsed.system).toBeUndefined(); + }); +}); diff --git a/src/proxy/body-transformer.ts b/src/proxy/body-transformer.ts index 663445d..d1f0151 100644 --- a/src/proxy/body-transformer.ts +++ b/src/proxy/body-transformer.ts @@ -18,9 +18,11 @@ * @see _reverse/NOTEPAD.md "How Credential is Used for LLM Calls" */ import type { Format } from "../translator/types.js"; +import { injectOfficialZcodeSystem } from "./system-prompt.js"; export interface TransformContext { format: Format; + plan?: "coding-plan" | "start-plan"; /** When set (OAuth mode), the Anthropic-format body gets `metadata.user_id` injected. */ userId?: string; } @@ -47,6 +49,9 @@ export function transformRequestBody(body: string | undefined, ctx: TransformCon } if (ctx.format === "anthropic") { const obj = parsed as Record; + if (ctx.plan === "start-plan") { + modified = injectOfficialZcodeSystem(obj) || modified; + } modified = applyAnthropicCacheControl(obj) || modified; if (ctx.userId) { modified = applyAnthropicUserId(obj, ctx.userId) || modified; diff --git a/src/proxy/captcha-jsdom.ts b/src/proxy/captcha-jsdom.ts new file mode 100644 index 0000000..ff92ea2 --- /dev/null +++ b/src/proxy/captcha-jsdom.ts @@ -0,0 +1,168 @@ +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const CAPTCHA_NODE_DIR = path.join(ROOT, "captcha_node"); +const SOLVER_JS = path.join(CAPTCHA_NODE_DIR, "solver.js"); + +const CACHE_TTL_MS = Number(process.env.CAPTCHA_CACHE_TTL_MS || 45_000); +const SOLVE_RETRIES = Number(process.env.ZCODE_CAPTCHA_RETRIES || 4); +const SOLVE_TIMEOUT_MS = Number(process.env.ZCODE_CAPTCHA_TIMEOUT || 40) * 1000; +const NODE_BIN = process.env.ZCODE_NODE_PATH?.trim() || "node"; + +type CacheEntry = { param: string; cachedAt: number }; + +class JsdomCaptchaManager { + private cache: CacheEntry | null = null; + private lock: Promise | null = null; + private depsReady: Promise | null = null; + + invalidate(): void { + this.cache = null; + } + + async getVerifyParam(cfg: CaptchaConfig): Promise { + const now = Date.now(); + if (this.cache && now - this.cache.cachedAt < CACHE_TTL_MS) { + return this.cache.param; + } + + if (this.lock) return this.lock; + + const work = this.solveFresh(cfg).finally(() => { + this.lock = null; + }); + this.lock = work; + return work; + } + + private async solveFresh(cfg: CaptchaConfig): Promise { + const now = Date.now(); + if (this.cache && now - this.cache.cachedAt < CACHE_TTL_MS) { + return this.cache.param; + } + + await ensureCaptchaDeps(); + + let lastErr: string | null = null; + for (let attempt = 1; attempt <= SOLVE_RETRIES; attempt++) { + try { + const param = await runSolver(cfg.sceneId, cfg.region, cfg.prefix); + if (param) { + this.cache = { param, cachedAt: Date.now() }; + return param; + } + lastErr = "solver returned empty"; + } catch (err) { + lastErr = err instanceof Error ? err.message : String(err); + } + } + + throw new Error(`jsdom captcha failed after ${SOLVE_RETRIES} attempts: ${lastErr ?? "unknown"}`); + } +} + +export interface CaptchaConfig { + enabled: boolean; + prefix: string; + sceneId: string; + region: string; +} + +const manager = new JsdomCaptchaManager(); + +export function invalidateJsdomCaptcha(): void { + manager.invalidate(); +} + +export async function solveCaptchaJsdom(cfg: CaptchaConfig): Promise { + if (!cfg.enabled || !cfg.prefix || !cfg.sceneId) { + throw new Error("Captcha config unavailable from ZCode API"); + } + return manager.getVerifyParam(cfg); +} + +/** Lazy install jsdom in captcha_node (avoids postinstall on every bun install). */ +let depsReady: Promise | null = null; + +async function ensureCaptchaDeps(): Promise { + const jsdomPath = path.join(CAPTCHA_NODE_DIR, "node_modules", "jsdom"); + if (fs.existsSync(jsdomPath)) return; + if (depsReady) return depsReady; + + depsReady = new Promise((resolve, reject) => { + const proc = spawn("npm", ["install", "--omit=dev"], { + cwd: CAPTCHA_NODE_DIR, + stdio: ["ignore", "pipe", "pipe"], + }); + let stderr = ""; + proc.stderr?.on("data", (c: Buffer) => { + stderr += c.toString("utf8"); + }); + proc.on("error", (err) => reject(new Error(`npm install failed: ${err.message}`))); + proc.on("close", (code) => { + if (code === 0) resolve(); + else reject(new Error(`npm install in captcha_node failed (${code}): ${stderr.slice(0, 200)}`)); + }); + }); + + try { + await depsReady; + } finally { + depsReady = null; + } +} + +function runSolver(scene: string, region: string, prefix: string): Promise { + if (!fs.existsSync(SOLVER_JS)) { + return Promise.reject(new Error(`Missing ${SOLVER_JS}`)); + } + + return new Promise((resolve, reject) => { + const proc = spawn(NODE_BIN, [SOLVER_JS, scene, region, prefix], { + cwd: CAPTCHA_NODE_DIR, + env: { ...process.env }, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }); + + let stdout = ""; + let stderr = ""; + proc.stdout?.on("data", (chunk: Buffer) => { + stdout += chunk.toString("utf8"); + }); + proc.stderr?.on("data", (chunk: Buffer) => { + stderr += chunk.toString("utf8"); + }); + + const timer = setTimeout(() => { + proc.kill("SIGKILL"); + reject(new Error(`jsdom captcha timeout (${SOLVE_TIMEOUT_MS}ms)`)); + }, SOLVE_TIMEOUT_MS); + + proc.on("error", (err) => { + clearTimeout(timer); + reject(new Error(`cannot spawn ${NODE_BIN}: ${err.message}`)); + }); + + proc.on("close", (code) => { + clearTimeout(timer); + for (const line of stdout.split(/\r?\n/)) { + if (line.startsWith("VERIFY_PARAM=")) { + const param = line.slice("VERIFY_PARAM=".length).trim(); + if (param.length > 20) { + resolve(param); + return; + } + } + } + reject( + new Error( + `jsdom captcha exit ${code ?? "?"}: ${stderr.slice(0, 200) || stdout.slice(0, 200) || "no output"}`, + ), + ); + }); + }); +} diff --git a/src/proxy/captcha.ts b/src/proxy/captcha.ts index 448f7d0..3b5e3e7 100644 --- a/src/proxy/captcha.ts +++ b/src/proxy/captcha.ts @@ -1,29 +1,19 @@ /** - * Aliyun Captcha V3 headless solver for start-plan tier. - * - * Captcha config (prefix/sceneId/region) is auto-fetched from - * https://zcode.z.ai/api/v1/client/configs — no user configuration needed. - * - * When zcode.z.ai returns a captcha challenge (response header - * `x-aliyun-captcha-verify-param`), this module solves it headlessly via - * Playwright + the official AliyunCaptcha.js SDK, then returns the solved token. - * - * @see _reverse/zcode.cjs `o5r()` / `createZcodePlanCaptchaEmptyStreamBusinessError` + * Aliyun Captcha V3 — proactive traceless verification via jsdom. + * @see https://github.com/TriDefender/zcode-api/issues/2 */ +import { invalidateJsdomCaptcha, solveCaptchaJsdom, type CaptchaConfig } from "./captcha-jsdom.js"; -const CAPTCHA_HEADER = "x-aliyun-captcha-verify-param"; -const REGION_HEADER = "x-aliyun-captcha-verify-region"; -const ALIYUN_CAPTCHA_SDK_URL = "https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"; -const CONFIGS_API = "https://zcode.z.ai/api/v1/client/configs"; +export const CAPTCHA_HEADER = "x-aliyun-captcha-verify-param"; +export const REGION_HEADER = "x-aliyun-captcha-verify-region"; +export const RETRY_HEADERS = { PARAM: CAPTCHA_HEADER, REGION: REGION_HEADER }; -interface FetchedCaptchaConfig { - enabled: boolean; - prefix: string; - sceneId: string; - region: string; -} +const CONFIGS_API = "https://zcode.z.ai/api/v1/client/configs"; +const DEFAULT_SCENE = "11xygtvd"; +const DEFAULT_PREFIX = "no8xfe"; +const DEFAULT_REGION = "sgp"; -let cachedConfig: { value: FetchedCaptchaConfig | null; expiresAt: number } = { value: null, expiresAt: 0 }; +let cachedConfig: { value: CaptchaConfig | null; expiresAt: number } = { value: null, expiresAt: 0 }; export function detectCaptchaChallenge(resp: Response): string | null { const v = resp.headers.get(CAPTCHA_HEADER); @@ -32,133 +22,58 @@ export function detectCaptchaChallenge(resp: Response): string | null { return trimmed.length > 0 ? trimmed : null; } -async function fetchCaptchaConfig(): Promise { +export async function fetchCaptchaConfig(appVersion = "3.1.2"): Promise { if (cachedConfig.value && cachedConfig.expiresAt > Date.now()) { return cachedConfig.value; } - try { - const url = `${CONFIGS_API}?app_version=3.1.1&platform=win32-x64`; - const resp = await fetch(url); - const json = (await resp.json()) as { code?: number; data?: { configs?: { captcha?: FetchedCaptchaConfig } } }; - const cfg = json?.data?.configs?.captcha ?? null; - cachedConfig = { value: cfg, expiresAt: Date.now() + 60000 }; - return cfg; - } catch { - return null; - } -} - -/** - * Solve an Aliyun captcha challenge headlessly. - * - * Fetches captcha config from ZCode API, launches Chromium, loads - * AliyunCaptcha.js, and waits for the SDK success callback. - * - * @returns Object with verifyParam and region for the retry request headers - * @throws Error if config unavailable, Playwright missing, or solve times out - */ -export async function solveCaptcha(challenge: string): Promise<{ verifyParam: string; region: string }> { - const cfg = await fetchCaptchaConfig(); - if (!cfg || !cfg.enabled || !cfg.prefix || !cfg.sceneId) { - throw new Error("Captcha config unavailable from ZCode API"); - } - const playwright = await loadPlaywright(); - const browser = await playwright.chromium.launch({ headless: true }); - try { - const page = await browser.newPage(); - await page.setContent(buildSolverHtml(cfg), { waitUntil: "domcontentloaded" }); - await page.addScriptTag({ url: ALIYUN_CAPTCHA_SDK_URL }); - - const verifyParam = await page.evaluate( - (args: { prefix: string; sceneId: string; region: string }): Promise => { - const { prefix, sceneId, region } = args; - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => reject(new Error("captcha solve timeout after 30s")), 30000); - const w = window as unknown as { - AliyunCaptchaConfig?: { region: string; prefix: string }; - initAliyunCaptcha?: (opts: Record) => void; - }; - w.AliyunCaptchaConfig = { region, prefix }; - if (!w.initAliyunCaptcha) { - clearTimeout(timeout); - reject(new Error("AliyunCaptcha.js failed to load")); - return; - } - w.initAliyunCaptcha({ - SceneId: sceneId, - prefix, - mode: "popup", - language: "cn", - showErrorTip: false, - element: "#captcha-element", - button: "#captcha-button", - getInstance: () => {}, - success: (param: string) => { - clearTimeout(timeout); - resolve(param); - }, - fail: (err: unknown) => { - clearTimeout(timeout); - reject(new Error(`Aliyun SDK fail: ${JSON.stringify(err)}`)); - }, - onError: (err: unknown) => { - clearTimeout(timeout); - reject(new Error(`Aliyun SDK error: ${JSON.stringify(err)}`)); - }, - }); - }); - }, - { prefix: cfg.prefix, sceneId: cfg.sceneId, region: cfg.region }, - ); - - void challenge; - return { verifyParam, region: cfg.region }; - } finally { - await browser.close(); - } -} - -function buildSolverHtml(cfg: FetchedCaptchaConfig): string { - return ` - -captcha-solver - - - -
- - -`; -} - -export const RETRY_HEADERS = { PARAM: CAPTCHA_HEADER, REGION: REGION_HEADER }; + const defaults: CaptchaConfig = { + enabled: true, + prefix: DEFAULT_PREFIX, + sceneId: DEFAULT_SCENE, + region: DEFAULT_REGION, + }; -async function loadPlaywright(): Promise { - const moduleName = "playwright"; try { - const mod = await import(/* @vite-ignore */ moduleName); - return mod as unknown as PlaywrightModule; + const url = `${CONFIGS_API}?app_version=${encodeURIComponent(appVersion)}&platform=linux`; + const resp = await fetch(url); + const json = (await resp.json()) as { + data?: { configs?: { captcha?: Partial } }; + }; + const cap = json?.data?.configs?.captcha; + const cfg: CaptchaConfig = { + enabled: cap?.enabled !== false, + prefix: String(cap?.prefix || DEFAULT_PREFIX), + sceneId: String(cap?.sceneId || DEFAULT_SCENE), + region: String(cap?.region || DEFAULT_REGION), + }; + cachedConfig = { value: cfg, expiresAt: Date.now() + 60_000 }; + return cfg; } catch { - throw new Error( - "playwright is not installed. Install with: bun add -d playwright && bunx playwright install chromium", - ); + cachedConfig = { value: defaults, expiresAt: Date.now() + 60_000 }; + return defaults; } } -interface PlaywrightModule { - chromium: { - launch(opts: { headless: boolean }): Promise; +/** Proactive traceless solve — attach verifyParam before the chat request. */ +export async function getProactiveCaptchaHeaders(appVersion = "3.1.2"): Promise> { + const cfg = await fetchCaptchaConfig(appVersion); + const verifyParam = await solveCaptchaJsdom(cfg); + return { + [CAPTCHA_HEADER]: verifyParam, + [REGION_HEADER]: cfg.region, }; } -interface PlaywrightBrowser { - newPage(): Promise; - close(): Promise; +/** Reactive re-solve after challenge header or captcha error body. */ +export async function solveCaptcha( + _challenge: string, + appVersion = "3.1.2", +): Promise<{ verifyParam: string; region: string }> { + invalidateJsdomCaptcha(); + const cfg = await fetchCaptchaConfig(appVersion); + const verifyParam = await solveCaptchaJsdom(cfg); + return { verifyParam, region: cfg.region }; } -interface PlaywrightPage { - setContent(html: string, opts: { waitUntil: string }): Promise; - addScriptTag(opts: { url: string }): Promise; - evaluate(fn: (args: { prefix: string; sceneId: string; region: string }) => Promise, args: { prefix: string; sceneId: string; region: string }): Promise; -} +export { invalidateJsdomCaptcha }; diff --git a/src/proxy/format-bridge.test.ts b/src/proxy/format-bridge.test.ts new file mode 100644 index 0000000..82eab1a --- /dev/null +++ b/src/proxy/format-bridge.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "bun:test"; +import { bridgeAnthropicResponse, bridgeOpenAIRequest } from "./format-bridge.js"; + +describe("bridgeOpenAIRequest", () => { + it("passes through anthropic clients unchanged", () => { + const body = JSON.stringify({ model: "glm-5.2", max_tokens: 16, messages: [] }); + const out = bridgeOpenAIRequest(body, "anthropic", "start-plan"); + expect(out.body).toBe(body); + expect(out.upstreamFormat).toBe("anthropic"); + expect(out.translateResponse).toBe(false); + }); + + it("translates openai to anthropic on start-plan", () => { + const body = JSON.stringify({ + model: "glm-5.2", + messages: [{ role: "user", content: "Hi" }], + stream: true, + }); + const out = bridgeOpenAIRequest(body, "openai", "start-plan"); + expect(out.upstreamFormat).toBe("anthropic"); + expect(out.translateResponse).toBe(true); + const parsed = JSON.parse(out.body!); + expect(parsed.model).toBe("glm-5.2"); + expect(parsed.max_tokens).toBeGreaterThan(0); + expect(parsed.messages).toEqual([{ role: "user", content: "Hi" }]); + expect(parsed.stream).toBe(true); + }); + + it("does not translate openai on coding-plan", () => { + const body = JSON.stringify({ model: "glm-4.6", messages: [] }); + const out = bridgeOpenAIRequest(body, "openai", "coding-plan"); + expect(out.body).toBe(body); + expect(out.upstreamFormat).toBe("openai"); + expect(out.translateResponse).toBe(false); + }); +}); + +describe("bridgeAnthropicResponse", () => { + it("translates anthropic JSON to openai chat completion", async () => { + const upstream = new Response( + JSON.stringify({ + id: "msg_1", + type: "message", + role: "assistant", + model: "GLM-5.2", + content: [{ type: "text", text: "Hello" }], + stop_reason: "end_turn", + stop_sequence: null, + usage: { input_tokens: 3, output_tokens: 2 }, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + + const resp = await bridgeAnthropicResponse(upstream, "glm-5.2"); + const body = await resp.json(); + expect(body.object).toBe("chat.completion"); + expect(body.choices[0].message.content).toBe("Hello"); + expect(body.choices[0].finish_reason).toBe("stop"); + }); +}); diff --git a/src/proxy/format-bridge.ts b/src/proxy/format-bridge.ts new file mode 100644 index 0000000..15d48c9 --- /dev/null +++ b/src/proxy/format-bridge.ts @@ -0,0 +1,72 @@ +/** + * Bridge OpenAI client requests to Anthropic upstream (start-plan). + */ +import type { Format, OpenAIChatRequest, AnthropicMessagesResponse } from "../translator/types.js"; +import { translateRequestOpenAIToAnthropic, translateResponseAnthropicToOpenAI } from "../translator/openai-to-anthropic.js"; +import { anthropicSseToOpenaiSse } from "../translator/sse-translator.js"; + +export interface RequestBridge { + body: string | undefined; + upstreamFormat: Format; + translateResponse: boolean; +} + +/** start-plan upstream is Anthropic-only; translate OpenAI chat bodies on ingress. */ +export function bridgeOpenAIRequest( + body: string | undefined, + clientFormat: Format, + plan: "coding-plan" | "start-plan", +): RequestBridge { + if (plan !== "start-plan" || clientFormat !== "openai") { + return { body, upstreamFormat: clientFormat, translateResponse: false }; + } + + if (!body) { + return { body, upstreamFormat: "anthropic", translateResponse: true }; + } + + const parsed = JSON.parse(body) as OpenAIChatRequest; + const anthropic = translateRequestOpenAIToAnthropic(parsed); + return { + body: JSON.stringify(anthropic), + upstreamFormat: "anthropic", + translateResponse: true, + }; +} + +/** Convert Anthropic JSON or SSE responses back to OpenAI for the client. */ +export async function bridgeAnthropicResponse( + upstream: Response, + clientModel: string, +): Promise { + const contentType = upstream.headers.get("content-type") ?? ""; + + if (contentType.includes("text/event-stream") && upstream.body) { + const headers = new Headers(upstream.headers); + headers.set("content-type", "text/event-stream; charset=utf-8"); + headers.delete("content-encoding"); + return new Response(anthropicSseToOpenaiSse(upstream.body, clientModel), { + status: upstream.status, + headers, + }); + } + + const text = await upstream.text(); + try { + const parsed = JSON.parse(text) as AnthropicMessagesResponse; + if (parsed.type === "message") { + const openai = translateResponseAnthropicToOpenAI(parsed, clientModel); + return new Response(JSON.stringify(openai), { + status: upstream.status, + headers: { "content-type": "application/json" }, + }); + } + } catch { + // Non-JSON error bodies pass through unchanged. + } + + return new Response(text, { + status: upstream.status, + headers: { "content-type": contentType || "application/json" }, + }); +} diff --git a/src/proxy/handler.ts b/src/proxy/handler.ts index edefe3e..a5957fa 100644 --- a/src/proxy/handler.ts +++ b/src/proxy/handler.ts @@ -3,19 +3,40 @@ * @see .omo/plans/zcode-proxy.md Task 6 */ import type { Format } from "../translator/types.js"; -import type { ProxyConfig } from "../config/types.js"; +import { randomUUID } from "node:crypto"; +import type { ProxyConfig, ProxyIdentity } from "../config/types.js"; import type { AuthManager } from "../auth/manager.js"; +import type { AccountPool } from "../auth/account-pool.js"; +import type { ProviderDef } from "../provider/types.js"; +import type { Credential } from "../auth/types.js"; import { getProvider } from "../provider/providers.js"; import { buildUpstreamRequest } from "./upstream.js"; import { transformRequestBody } from "./body-transformer.js"; -import { detectCaptchaChallenge, solveCaptcha, RETRY_HEADERS } from "./captcha.js"; +import { + detectCaptchaChallenge, + getProactiveCaptchaHeaders, + invalidateJsdomCaptcha, + solveCaptcha, + RETRY_HEADERS, +} from "./captcha.js"; +import { normalizeStartPlanBody } from "./start-plan-body.js"; +import { bridgeAnthropicResponse, bridgeOpenAIRequest } from "./format-bridge.js"; +import { anthropicSseToResponsesSse, anthropicMessageToResponses, responsesLifecycleEvents } from "./responses-bridge.js"; +import { anthropicSseToOpenaiSse } from "../translator/sse-translator.js"; +import { classifyUpstreamFailure } from "./upstream-errors.js"; +import type { RequestLogStore, RequestTokenUsage } from "../server/request-logs.js"; +import { mergeTokenUsage, normalizeTokenUsage, usageFromResponseBody, usageFromSsePayload } from "../server/request-logs.js"; /** Options for the proxy handler. */ export interface ProxyHandlerOptions { config: ProxyConfig; auth: AuthManager; + accountPool?: AccountPool; + requestLogs?: RequestLogStore; /** Override the global fetch (for testing). Defaults to global `fetch`. */ fetchImpl?: typeof fetch; + /** Translate Anthropic upstream responses to OpenAI Responses API (Codex). */ + responseBridge?: "responses"; } /** @@ -34,13 +55,12 @@ export async function proxyRequest( format: Format, opts: ProxyHandlerOptions, ): Promise { - const { config, auth } = opts; + const { config, auth, accountPool, requestLogs, responseBridge } = opts; const fetchImpl = opts.fetchImpl ?? fetch; const started = Date.now(); const reqId = nextReqId(); const body = await readBody(clientReq); - const meta = peekBody(body); const staticProvider = getProvider(config.provider); @@ -50,74 +70,676 @@ export async function proxyRequest( openaiBaseURL: config.providers[config.provider].openaiBase, }; + const usePool = + config.plan === "start-plan" && + config.pool?.enabled !== false && + accountPool && + accountPool.activeCount() > 0; + + if (usePool && accountPool) { + return proxyRequestWithPool({ + clientReq, + format, + config, + provider, + accountPool, + fetchImpl, + body, + meta, + reqId, + started, + requestLogs, + responseBridge, + }); + } + let cred; try { cred = await auth.getCredential(); } catch (err) { - printRow(reqId, format, meta, 503, started, Date.now(), 0, 0, 0); + recordRequest(reqId, format, meta, 503, started, Date.now(), 0, 0, 0, { requestLogs }); return errorResponse(503, "credential_unavailable", (err as Error).message); } - // start-plan only exposes the Anthropic endpoint (OpenAI path returns 404). - // Reject OpenAI-format requests early with a clear message. - if (config.plan === "start-plan" && format === "openai") { - printRow(reqId, format, meta, 400, started, Date.now(), 0, 0, 0); - return errorResponse(400, "unsupported_format", "start-plan only supports the Anthropic API format. Use POST /v1/messages instead of /v1/chat/completions."); + return (await proxyRequestWithCredential({ + clientReq, + format, + config, + provider, + cred, + fetchImpl, + body, + meta, + reqId, + started, + requestLogs, + responseBridge, + })).response; +} + +async function proxyRequestWithPool(opts: { + clientReq: Request; + format: Format; + config: ProxyConfig; + provider: ProviderDef; + accountPool: AccountPool; + fetchImpl: typeof fetch; + body: string | undefined; + meta: RequestMeta; + reqId: string; + started: number; + requestLogs?: RequestLogStore; + responseBridge?: "responses"; +}): Promise { + const maxAttempts = opts.config.pool?.maxAccountAttempts ?? 5; + const excludeIds: string[] = []; + + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { + const account = opts.accountPool.acquire(excludeIds); + if (!account) break; + + console.log(`${opts.reqId} pool → ${account.userId ?? account.id.slice(0, 8)}`); + + const cred = opts.accountPool.toCredential(account); + const logCtx = { + requestLogs: opts.requestLogs, + accountId: account.id, + accountUserId: account.userId, + }; + const result = await proxyRequestWithCredential({ + ...opts, + cred, + ...logCtx, + }); + + if (result.outcome === "success") { + opts.accountPool.release(account.id); + return result.response; + } + + excludeIds.push(account.id); + const msg = result.message ?? "upstream error"; + + if (result.outcome === "quota") { + opts.accountPool.markExhausted(account.id, msg); + console.log(`${opts.reqId} account ${account.name} quota exhausted, trying next...`); + continue; + } + if (result.outcome === "blocked") { + opts.accountPool.markBlocked(account.id, msg); + console.log(`${opts.reqId} account ${account.name} blocked (3012), trying next...`); + continue; + } + if (result.outcome === "auth") { + opts.accountPool.markAuthError(account.id, msg); + console.log(`${opts.reqId} account ${account.name} JWT invalid, trying next...`); + continue; + } + if (result.outcome === "captcha") { + console.log(`${opts.reqId} captcha failed on ${account.name}, trying next account...`); + continue; + } + + return result.response; + } + + recordRequest(opts.reqId, opts.format, opts.meta, 503, opts.started, Date.now(), 0, 0, 0, { + requestLogs: opts.requestLogs, + }); + return errorResponse( + 503, + "no_available_account", + `All ${excludeIds.length} pool account(s) failed or exhausted. Run: auth accounts`, + ); +} + +type ProxyOutcome = + | { outcome: "success"; response: Response } + | { outcome: "quota" | "blocked" | "auth" | "captcha" | "error"; response: Response; message: string }; + +function responsesStreamHeaders(): Headers { + const headers = new Headers(); + headers.set("content-type", "text/event-stream; charset=utf-8"); + headers.set("cache-control", "no-cache"); + headers.set("connection", "keep-alive"); + return headers; +} + +function proxyResponsesEarlyStream(opts: { + clientReq: Request; + format: Format; + config: ProxyConfig; + provider: ProviderDef; + cred: Credential; + fetchImpl: typeof fetch; + bridge: ReturnType; + upstreamBody: string | undefined; + meta: RequestMeta; + reqId: string; + started: number; + logCtx: RowLogCtx; +}): ProxyOutcome { + const { + clientReq, config, provider, cred, fetchImpl, bridge, upstreamBody, + meta, reqId, started, logCtx, format, + } = opts; + const responseId = `resp_${randomUUID().slice(0, 12)}`; + const encoder = new TextEncoder(); + const abort = new AbortController(); + let clientGone = false; + + const stream = new ReadableStream({ + cancel() { + clientGone = true; + abort.abort(); + }, + async start(controller) { + const safeEnqueue = (chunk: Uint8Array): boolean => { + if (clientGone) return false; + try { + controller.enqueue(chunk); + return true; + } catch { + clientGone = true; + abort.abort(); + return false; + } + }; + + safeEnqueue(encoder.encode(responsesLifecycleEvents(responseId, meta.model))); + + const keepalive = setInterval(() => { + if (!safeEnqueue(encoder.encode(": keepalive\n\n"))) { + clearInterval(keepalive); + } + }, 2000); + + const emitError = (message: string, type = "api_error") => { + safeEnqueue(encoder.encode( + `event: error\ndata: ${JSON.stringify({ type: "error", error: { type, message } })}\n\n`, + )); + }; + + const safeClose = () => { + clearInterval(keepalive); + if (!clientGone) { + try { + controller.close(); + } catch { + // already closed + } + } + }; + + try { + let captchaHeaders: Record = {}; + if (config.plan === "start-plan") { + try { + captchaHeaders = await getProactiveCaptchaHeaders(config.identity.appVersion); + console.log(`${reqId} proactive captcha ready (${captchaHeaders[RETRY_HEADERS.PARAM]?.length ?? 0} chars)`); + } catch (err) { + recordRequest(reqId, format, meta, 503, started, Date.now(), 0, 0, 0, logCtx); + emitError((err as Error).message, "captcha_solve_failed"); + safeClose(); + return; + } + } + + if (clientGone) return; + + let upstreamReq: Request; + try { + upstreamReq = buildUpstreamRequest( + clientReq, + bridge.upstreamFormat, + provider, + cred, + upstreamBody, + config.identity, + config.plan, + captchaHeaders, + ); + } catch (err) { + recordRequest(reqId, format, meta, 500, started, Date.now(), 0, 0, 0, logCtx); + emitError((err as Error).message, "configuration_error"); + safeClose(); + return; + } + + let upstreamResp: Response; + try { + upstreamResp = await fetchImpl(upstreamReq, { decompress: false, signal: abort.signal }); + } catch (err) { + if (clientGone || abort.signal.aborted) return; + recordRequest(reqId, format, meta, 502, started, Date.now(), 0, 0, 0, logCtx); + emitError((err as Error).message, "upstream_unreachable"); + safeClose(); + return; + } + const headersAt = Date.now(); + + if (config.plan === "start-plan") { + const blocked = await readAccountBlock(upstreamResp); + if (blocked) { + try { upstreamResp.body?.cancel(); } catch {} + emitError("Account blocked (3012)", "account_blocked"); + safeClose(); + return; + } + + const retried = await retryStartPlanIfNeeded({ + fetchImpl, + clientReq, + upstreamFormat: bridge.upstreamFormat, + provider, + cred, + upstreamBody, + identity: config.identity, + reqId, + upstreamResp, + }); + if (retried.error) { + if (clientGone) return; + const errText = await retried.error.clone().text().catch(() => "error"); + emitError(errText); + safeClose(); + return; + } + upstreamResp = retried.response; + } + + const failureKind = await classifyUpstreamFailure(upstreamResp, isCaptchaFailure); + if (failureKind !== "ok") { + if (clientGone) return; + const errText = await upstreamResp.clone().text().catch(() => "upstream error"); + emitError(errText); + safeClose(); + return; + } + + if (!upstreamResp.body) { + recordRequest(reqId, format, meta, upstreamResp.status, started, headersAt, 0, 0, 0, logCtx); + safeClose(); + return; + } + + const translated = anthropicSseToResponsesSse(upstreamResp.body, meta.model, { + responseId, + skipLifecycle: true, + }); + const [clientBody, statsBody] = translated.tee(); + observeStream(reqId, format, meta, upstreamResp.status, started, statsBody, undefined, logCtx); + const reader = clientBody.getReader(); + while (!clientGone) { + const { done, value } = await reader.read(); + if (done) break; + if (!value || !safeEnqueue(value)) break; + } + try { + await reader.cancel(); + } catch {} + } catch (err) { + if (!clientGone) emitError((err as Error).message); + } finally { + safeClose(); + } + }, + }); + + return { + outcome: "success", + response: new Response(stream, { status: 200, headers: responsesStreamHeaders() }), + }; +} + +async function proxyRequestWithCredential(opts: { + clientReq: Request; + format: Format; + config: ProxyConfig; + provider: ProviderDef; + cred: Credential; + fetchImpl: typeof fetch; + body: string | undefined; + meta: RequestMeta; + reqId: string; + started: number; + requestLogs?: RequestLogStore; + accountId?: string; + accountUserId?: string; + responseBridge?: "responses"; +}): Promise { + const { config, cred, fetchImpl, clientReq, format, provider, body, meta, reqId, started, requestLogs, accountId, accountUserId, responseBridge } = opts; + const logCtx = { requestLogs, accountId, accountUserId }; + + let bridge; + try { + bridge = bridgeOpenAIRequest(body, format, config.plan); + } catch { + recordRequest(reqId, format, meta, 400, started, Date.now(), 0, 0, 0, logCtx); + return { + outcome: "error", + response: errorResponse(400, "invalid_request_error", "Invalid JSON in OpenAI chat request body"), + message: "invalid json", + }; + } + + const transformedBody = transformRequestBody(bridge.body, { + format: bridge.upstreamFormat, + plan: config.plan, + userId: cred.userId, + }); + const upstreamBody = + config.plan === "start-plan" ? normalizeStartPlanBody(transformedBody) : transformedBody; + + // Codex times out if no SSE bytes arrive during captcha/upstream TTFB — flush lifecycle first. + if (responseBridge === "responses" && meta.stream !== false) { + return proxyResponsesEarlyStream({ + clientReq, + format, + config, + provider, + cred, + fetchImpl, + bridge, + upstreamBody, + meta, + reqId, + started, + logCtx, + }); + } + + let captchaHeaders: Record = {}; + if (config.plan === "start-plan") { + try { + captchaHeaders = await getProactiveCaptchaHeaders(config.identity.appVersion); + console.log(`${reqId} proactive captcha ready (${captchaHeaders[RETRY_HEADERS.PARAM]?.length ?? 0} chars)`); + } catch (err) { + recordRequest(reqId, format, meta, 503, started, Date.now(), 0, 0, 0, logCtx); + return { + outcome: "error", + response: errorResponse(503, "captcha_solve_failed", (err as Error).message), + message: (err as Error).message, + }; + } } - const transformedBody = transformRequestBody(body, { format, userId: cred.userId }); - let upstreamReq = buildUpstreamRequest(clientReq, format, provider, cred, transformedBody, config.identity, config.plan); + let upstreamReq: Request; + try { + upstreamReq = buildUpstreamRequest( + clientReq, + bridge.upstreamFormat, + provider, + cred, + upstreamBody, + config.identity, + config.plan, + captchaHeaders, + ); + } catch (err) { + recordRequest(reqId, format, meta, 500, started, Date.now(), 0, 0, 0, logCtx); + return { + outcome: "error", + response: errorResponse(500, "configuration_error", (err as Error).message), + message: (err as Error).message, + }; + } let upstreamResp: Response; try { upstreamResp = await fetchImpl(upstreamReq, { decompress: false }); } catch (err) { - printRow(reqId, format, meta, 502, started, Date.now(), 0, 0, 0); - return errorResponse(502, "upstream_unreachable", (err as Error).message); + recordRequest(reqId, format, meta, 502, started, Date.now(), 0, 0, 0, logCtx); + return { + outcome: "error", + response: errorResponse(502, "upstream_unreachable", (err as Error).message), + message: (err as Error).message, + }; } const headersAt = Date.now(); - if (upstreamResp.status === 401 && config.plan === "start-plan") { - printRow(reqId, format, meta, 401, started, headersAt, 0, 0, 0); - return errorResponse(401, "start_plan_jwt_invalid", "Start-plan JWT was rejected. Re-run: zcode-proxy auth login"); - } - - // start-plan captcha challenge: detect via response header, solve headlessly, retry once if (config.plan === "start-plan") { - const challenge = detectCaptchaChallenge(upstreamResp); - if (challenge) { + const blocked = await readAccountBlock(upstreamResp); + if (blocked) { try { upstreamResp.body?.cancel(); } catch {} - console.log(`${reqId} captcha challenge detected, solving headlessly...`); - const { verifyParam, region } = await solveCaptcha(challenge); - console.log(`${reqId} captcha solved (token ${verifyParam.length} chars), retrying...`); - upstreamReq = buildUpstreamRequest(clientReq, format, provider, cred, transformedBody, config.identity, config.plan, { - [RETRY_HEADERS.PARAM]: verifyParam, - [RETRY_HEADERS.REGION]: region, - }); - try { - upstreamResp = await fetchImpl(upstreamReq, { decompress: false }); - } catch (err) { - printRow(reqId, format, meta, 502, started, Date.now(), 0, 0, 0); - return errorResponse(502, "upstream_unreachable", (err as Error).message); - } - if (detectCaptchaChallenge(upstreamResp)) { - try { upstreamResp.body?.cancel(); } catch {} - printRow(reqId, format, meta, 403, started, Date.now(), 0, 0, 0); - return errorResponse(403, "captcha_verification_failed", "Captcha was solved but upstream still rejected the token"); - } + return { + outcome: "blocked", + response: errorResponse(405, "account_blocked", "Account blocked (3012)"), + message: "3012", + }; + } + + const retried = await retryStartPlanIfNeeded({ + fetchImpl, + clientReq, + upstreamFormat: bridge.upstreamFormat, + provider, + cred, + upstreamBody, + identity: config.identity, + reqId, + upstreamResp, + }); + if (retried.error) { + const kind = await classifyUpstreamFailure(retried.error, isCaptchaFailure); + return { + outcome: kind === "ok" ? "error" : kind, + response: retried.error, + message: await retried.error.clone().text().catch(() => "error"), + }; } + upstreamResp = retried.response; + } + + const failureKind = await classifyUpstreamFailure(upstreamResp, isCaptchaFailure); + if (failureKind !== "ok") { + const errText = await upstreamResp.clone().text().catch(() => ""); + if (failureKind === "auth") { + return { outcome: "auth", response: passthroughResponse(upstreamResp), message: errText }; + } + if (failureKind === "quota") { + return { outcome: "quota", response: passthroughResponse(upstreamResp), message: errText }; + } + if (failureKind === "blocked") { + return { outcome: "blocked", response: passthroughResponse(upstreamResp), message: errText }; + } + if (failureKind === "captcha") { + return { outcome: "captcha", response: passthroughResponse(upstreamResp), message: errText }; + } + recordRequest(reqId, format, meta, upstreamResp.status, started, headersAt, 0, 0, 0, logCtx); + return { outcome: "error", response: passthroughResponse(upstreamResp), message: errText }; } const isSSE = upstreamResp.headers.get("content-type")?.includes("text/event-stream") ?? false; if (isSSE && upstreamResp.body) { + if (responseBridge === "responses") { + const translated = anthropicSseToResponsesSse(upstreamResp.body, meta.model); + const [clientBody, statsBody] = translated.tee(); + observeStream(reqId, format, meta, upstreamResp.status, started, statsBody, undefined, logCtx); + const headers = new Headers(); + headers.set("content-type", "text/event-stream; charset=utf-8"); + headers.set("cache-control", "no-cache"); + return { + outcome: "success", + response: new Response(clientBody, { status: upstreamResp.status, headers }), + }; + } + if (bridge.translateResponse) { + const translated = anthropicSseToOpenaiSse(upstreamResp.body, meta.model); + const [clientBody, statsBody] = translated.tee(); + observeStream(reqId, format, meta, upstreamResp.status, started, statsBody, undefined, logCtx); + const headers = new Headers(upstreamResp.headers); + headers.set("content-type", "text/event-stream; charset=utf-8"); + headers.delete("content-encoding"); + return { + outcome: "success", + response: new Response(clientBody, { status: upstreamResp.status, headers }), + }; + } const [clientBody, statsBody] = upstreamResp.body.tee(); - observeStream(reqId, format, meta, upstreamResp.status, started, statsBody, upstreamResp.headers.get("content-encoding")); - return passthroughResponse(upstreamResp, clientBody); + observeStream(reqId, format, meta, upstreamResp.status, started, statsBody, upstreamResp.headers.get("content-encoding"), logCtx); + return { outcome: "success", response: passthroughResponse(upstreamResp, clientBody) }; + } + + const text = await upstreamResp.text(); + let usage = normalizeTokenUsage(null); + try { + usage = normalizeTokenUsage(usageFromResponseBody(JSON.parse(text))); + } catch { + // non-JSON body } + const endAt = Date.now(); + const totalMs = endAt - started; + const avgTps = usage.outputTokens > 0 && totalMs > 0 ? usage.outputTokens / (totalMs / 1000) : 0; + recordRequest( + reqId, + format, + meta, + upstreamResp.status, + started, + headersAt, + usage.outputTokens, + avgTps, + endAt, + logCtx, + usage, + ); - printRow(reqId, format, meta, upstreamResp.status, started, headersAt, 0, 0, 0); - return passthroughResponse(upstreamResp); + const rebuilt = new Response(text, { status: upstreamResp.status, headers: upstreamResp.headers }); + if (responseBridge === "responses") { + try { + const parsed = JSON.parse(text) as Record; + if (parsed.type === "message") { + return { + outcome: "success", + response: new Response(JSON.stringify(anthropicMessageToResponses(parsed, meta.model)), { + status: upstreamResp.status, + headers: { "content-type": "application/json" }, + }), + }; + } + } catch { + // fall through + } + return { outcome: "success", response: rebuilt }; + } + if (bridge.translateResponse) { + return { outcome: "success", response: await bridgeAnthropicResponse(rebuilt, meta.model) }; + } + return { outcome: "success", response: rebuilt }; +} + +async function retryStartPlanIfNeeded(opts: { + fetchImpl: typeof fetch; + clientReq: Request; + upstreamFormat: Format; + provider: ProviderDef; + cred: Credential; + upstreamBody: string | undefined; + identity: ProxyIdentity; + reqId: string; + upstreamResp: Response; +}): Promise<{ response: Response; error?: Response }> { + const needsRetry = + detectCaptchaChallenge(opts.upstreamResp) !== null || + (await isCaptchaFailure(opts.upstreamResp)); + + if (!needsRetry) { + return { response: opts.upstreamResp }; + } + + try { + opts.upstreamResp.body?.cancel(); + } catch {} + + console.log(`${opts.reqId} captcha rejected — re-solving traceless and retrying once...`); + invalidateJsdomCaptcha(); + + let captchaHeaders: Record; + try { + captchaHeaders = await getProactiveCaptchaHeaders(opts.identity.appVersion); + } catch (err) { + return { + response: opts.upstreamResp, + error: errorResponse(503, "captcha_solve_failed", (err as Error).message), + }; + } + + const challenge = detectCaptchaChallenge(opts.upstreamResp); + if (challenge) { + try { + const { verifyParam, region } = await solveCaptcha(challenge, opts.identity.appVersion); + captchaHeaders = { + [RETRY_HEADERS.PARAM]: verifyParam, + [RETRY_HEADERS.REGION]: region, + }; + } catch (err) { + return { + response: opts.upstreamResp, + error: errorResponse(503, "captcha_solve_failed", (err as Error).message), + }; + } + } + + const upstreamReq = buildUpstreamRequest( + opts.clientReq, + opts.upstreamFormat, + opts.provider, + opts.cred, + opts.upstreamBody, + opts.identity, + "start-plan", + captchaHeaders, + ); + + try { + const upstreamResp = await opts.fetchImpl(upstreamReq, { decompress: false }); + if (await readAccountBlock(upstreamResp)) { + try { + upstreamResp.body?.cancel(); + } catch {} + return { + response: upstreamResp, + error: errorResponse(405, "account_blocked", "Account blocked (3012). Use a fresh ZCode login."), + }; + } + if (detectCaptchaChallenge(upstreamResp) || (await isCaptchaFailure(upstreamResp))) { + try { + upstreamResp.body?.cancel(); + } catch {} + return { + response: upstreamResp, + error: errorResponse( + 403, + "captcha_verification_failed", + "Captcha was solved but upstream still rejected the token", + ), + }; + } + return { response: upstreamResp }; + } catch (err) { + return { + response: opts.upstreamResp, + error: errorResponse(502, "upstream_unreachable", (err as Error).message), + }; + } +} + +/** 3012 = abuse block — never treat as captcha retry. */ +async function readAccountBlock(resp: Response): Promise { + if (resp.status !== 405) return false; + const text = await resp.clone().text().catch(() => ""); + return text.includes("3012"); +} + +/** Narrow captcha detection — avoid masking unrelated 403s (PR review #3). */ +async function isCaptchaFailure(resp: Response): Promise { + if (detectCaptchaChallenge(resp)) return true; + const text = await resp.clone().text().catch(() => ""); + const low = text.toLowerCase(); + if (low.includes("3012")) return false; + return low.includes("3007") || (low.includes("captcha") && resp.status === 403); } /** Read the request body as a string, returning undefined for empty bodies. */ @@ -199,14 +821,20 @@ function printHeader(): void { if (headerPrinted) return; headerPrinted = true; console.log( - "| # | Time | Fmt | Model | Mode | Stat | TTFB | Tok | tok/s | Total |", + "| # | Time | Fmt | Model | Mode | Stat | TTFB | In | Out | Cache | tok/s | Total |", ); console.log( - "|------|------------|-----|-------------|--------|------|---------|-------|--------|---------|", + "|------|------------|-----|-------------|--------|------|---------|-------|-------|-------|--------|---------|", ); } -function printRow( +interface RowLogCtx { + requestLogs?: RequestLogStore; + accountId?: string; + accountUserId?: string; +} + +function recordRequest( reqId: string, format: Format, meta: RequestMeta, @@ -216,6 +844,51 @@ function printRow( tokens: number, avgTps: number, streamEndAt: number, + ctx: RowLogCtx = {}, + tokenUsage?: Partial, +): void { + const usage = mergeTokenUsage( + { + inputTokens: 0, + outputTokens: tokens, + cachedTokens: 0, + reasoningTokens: 0, + }, + tokenUsage, + ); + if (usage.outputTokens === 0 && tokens > 0) { + usage.outputTokens = tokens; + } + printRow(reqId, format, meta, status, started, headersAt, usage, avgTps, streamEndAt); + ctx.requestLogs?.append({ + id: reqId, + format, + model: meta.model, + stream: meta.stream, + status, + ttfbMs: Math.max(0, headersAt - started), + tokens: usage.outputTokens, + inputTokens: usage.inputTokens, + outputTokens: usage.outputTokens, + cachedTokens: usage.cachedTokens, + reasoningTokens: usage.reasoningTokens, + tokPerSec: avgTps, + totalMs: streamEndAt > started ? streamEndAt - started : Math.max(0, headersAt - started), + accountId: ctx.accountId, + accountUserId: ctx.accountUserId, + }); +} + +function printRow( + reqId: string, + format: Format, + meta: RequestMeta, + status: number, + started: number, + headersAt: number, + usage: RequestTokenUsage, + avgTps: number, + streamEndAt: number, ): void { printHeader(); const ts = new Date(started).toISOString().slice(11, 19); @@ -223,10 +896,12 @@ function printRow( const mode = meta.stream ? "stream" : "batch"; const ttfb = `${headersAt - started}ms`; const total = streamEndAt > started ? `${streamEndAt - started}ms` : "-"; - const tok = tokens > 0 ? String(tokens) : "-"; + const outTok = usage.outputTokens > 0 ? String(usage.outputTokens) : "-"; + const inTok = usage.inputTokens > 0 ? String(usage.inputTokens) : "-"; + const cacheTok = usage.cachedTokens > 0 ? String(usage.cachedTokens) : "-"; const tps = avgTps > 0 ? avgTps.toFixed(1) : "-"; console.log( - `| ${reqId.padEnd(4)} | ${ts.padEnd(10)} | ${tag} | ${meta.model.padEnd(11)} | ${mode.padEnd(6)} | ${String(status).padStart(4)} | ${ttfb.padStart(7)} | ${tok.padStart(5)} | ${tps.padStart(6)} | ${total.padStart(7)} |`, + `| ${reqId.padEnd(4)} | ${ts.padEnd(10)} | ${tag} | ${meta.model.padEnd(11)} | ${mode.padEnd(6)} | ${String(status).padStart(4)} | ${ttfb.padStart(7)} | ${inTok.padStart(5)} | ${outTok.padStart(5)} | ${cacheTok.padStart(5)} | ${tps.padStart(6)} | ${total.padStart(7)} |`, ); } @@ -238,9 +913,16 @@ function observeStream( requestSentAt: number, body: ReadableStream, contentEncoding: string | null, + ctx: RowLogCtx = {}, ): void { const compressed = contentEncoding !== null; - let tokens = 0; + let usage: RequestTokenUsage = { + inputTokens: 0, + outputTokens: 0, + cachedTokens: 0, + reasoningTokens: 0, + }; + let outputChunks = 0; let sseBuffer = ""; let firstChunkAt = 0; @@ -249,15 +931,14 @@ function observeStream( if (!line.startsWith("data:") || line.includes("[DONE]")) continue; try { const j = JSON.parse(line.slice(5).trim()); - if (j.usage?.completion_tokens) { tokens = j.usage.completion_tokens; continue; } - if (j.usage?.output_tokens) { tokens = j.usage.output_tokens; continue; } - // OpenAI content delta: choices[0].delta.content + usage = mergeTokenUsage(usage, usageFromSsePayload(j)); + if (j.usage?.completion_tokens) { outputChunks = j.usage.completion_tokens; continue; } + if (j.usage?.output_tokens) { outputChunks = j.usage.output_tokens; continue; } const oai = j.choices?.[0]?.delta?.content; - if (typeof oai === "string" && oai.length > 0) { tokens++; continue; } - // Anthropic content delta: type=content_block_delta, delta.type=text_delta + if (typeof oai === "string" && oai.length > 0) { outputChunks++; continue; } if (j.type === "content_block_delta" && j.delta?.type === "text_delta") { const t = j.delta?.text; - if (typeof t === "string" && t.length > 0) tokens++; + if (typeof t === "string" && t.length > 0) outputChunks++; } } catch {} } @@ -285,7 +966,22 @@ function observeStream( const endAt = Date.now(); const ttfbMs = (firstChunkAt > 0 ? firstChunkAt : endAt) - requestSentAt; const totalMs = endAt - requestSentAt; - const avgTps = tokens > 0 && totalMs > 0 ? tokens / (totalMs / 1000) : 0; - printRow(reqId, format, meta, status, requestSentAt, requestSentAt + ttfbMs, tokens, avgTps, endAt); + if (usage.outputTokens === 0 && outputChunks > 0) { + usage.outputTokens = outputChunks; + } + const avgTps = usage.outputTokens > 0 && totalMs > 0 ? usage.outputTokens / (totalMs / 1000) : 0; + recordRequest( + reqId, + format, + meta, + status, + requestSentAt, + requestSentAt + ttfbMs, + usage.outputTokens, + avgTps, + endAt, + ctx, + usage, + ); })().catch(() => {}); } diff --git a/src/proxy/responses-bridge.test.ts b/src/proxy/responses-bridge.test.ts new file mode 100644 index 0000000..a11861f --- /dev/null +++ b/src/proxy/responses-bridge.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "bun:test"; +import { anthropicSseToResponsesSse } from "./responses-bridge.js"; + +async function collectSse(stream: ReadableStream): Promise { + const reader = stream.getReader(); + const decoder = new TextDecoder(); + let out = ""; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + out += decoder.decode(value, { stream: true }); + } + return out; +} + +function parseEvents(raw: string): Array<{ event: string; data: Record }> { + const events: Array<{ event: string; data: Record }> = []; + for (const block of raw.split("\n\n")) { + const lines = block.trim().split("\n").filter(Boolean); + if (lines.length === 0) continue; + let event = ""; + let dataStr = ""; + for (const line of lines) { + if (line.startsWith("event: ")) event = line.slice(7); + if (line.startsWith("data: ")) dataStr = line.slice(6); + } + if (event && dataStr) { + events.push({ event, data: JSON.parse(dataStr) as Record }); + } + } + return events; +} + +describe("anthropicSseToResponsesSse", () => { + it("emits output_item.done for function_call before response.completed", async () => { + const upstream = new ReadableStream({ + start(controller) { + const enc = new TextEncoder(); + const chunks = [ + 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","usage":{"input_tokens":10}}}\n\n', + 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_abc","name":"write"}}\n\n', + 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"path\\":\\"a\\"}"}}\n\n', + 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n', + 'event: message_delta\ndata: {"type":"message_delta","usage":{"output_tokens":5}}\n\n', + 'event: message_stop\ndata: {"type":"message_stop"}\n\n', + ]; + for (const c of chunks) controller.enqueue(enc.encode(c)); + controller.close(); + }, + }); + + const events = parseEvents(await collectSse(anthropicSseToResponsesSse(upstream, "glm-5.2"))); + const names = events.map((e) => e.event); + const doneIdx = names.indexOf("response.output_item.done"); + const completedIdx = names.indexOf("response.completed"); + expect(doneIdx).toBeGreaterThanOrEqual(0); + expect(completedIdx).toBeGreaterThan(doneIdx); + + const done = events[doneIdx]!; + expect(done.data.item).toMatchObject({ + type: "function_call", + call_id: "call_abc", + name: "write", + arguments: '{"path":"a"}', + }); + + const completed = events[completedIdx]!; + const response = completed.data.response as Record; + const output = response.output as Array>; + expect(output[0]).toMatchObject({ + type: "function_call", + call_id: "call_abc", + name: "write", + }); + }); +}); diff --git a/src/proxy/responses-bridge.ts b/src/proxy/responses-bridge.ts new file mode 100644 index 0000000..493f308 --- /dev/null +++ b/src/proxy/responses-bridge.ts @@ -0,0 +1,495 @@ +/** + * Anthropic SSE → OpenAI Responses API SSE (Codex wire_api=responses). + */ +import { randomUUID } from "node:crypto"; + +function isRecord(v: unknown): v is Record { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +function formatEvent(event: string, data: unknown): string { + const payload = + typeof data === "object" && data !== null && !Array.isArray(data) + ? { type: event, ...(data as Record) } + : { type: event, data }; + return `event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`; +} + +export function responsesLifecycleEvents(responseId: string, model: string): string { + return ( + formatEvent("response.created", { response: { id: responseId, model } }) + + formatEvent("response.in_progress", { response: { id: responseId } }) + ); +} + +export interface ResponsesSseOptions { + /** Pre-assigned response id when lifecycle events were already sent. */ + responseId?: string; + /** Skip response.created / response.in_progress (already sent to client). */ + skipLifecycle?: boolean; +} + +function parseSseChunk(raw: string): Array<{ event: string; data: unknown }> { + const results: Array<{ event: string; data: unknown }> = []; + for (const block of raw.split("\n\n")) { + const lines = block.trim().split("\n").filter(Boolean); + if (lines.length === 0) continue; + let eventType = ""; + let dataStr = ""; + for (const line of lines) { + if (line.startsWith("event: ")) eventType = line.slice(7).trim(); + else if (line.startsWith("data: ")) dataStr = line.slice(6); + } + if (!dataStr) continue; + try { + results.push({ event: eventType, data: JSON.parse(dataStr) }); + } catch { + // skip malformed + } + } + return results; +} + +interface TextBlockState { + outputIndex: number; + contentIndex: number; + itemId: string; + textBuffer: string; + itemAdded: boolean; + partAdded: boolean; + itemDone: boolean; +} + +interface ToolBlockState { + id: string; + name: string; + argBuffer: string; + outputIndex: number; + itemId: string; + itemDone: boolean; +} + +/** Transform Anthropic message SSE into Responses API SSE for Codex. */ +export function anthropicSseToResponsesSse( + upstream: ReadableStream, + model: string, + options: ResponsesSseOptions = {}, +): ReadableStream { + const decoder = new TextDecoder(); + const encoder = new TextEncoder(); + let buffer = ""; + const responseId = options.responseId ?? `resp_${randomUUID().slice(0, 12)}`; + const skipLifecycle = options.skipLifecycle === true; + let sentCreated = skipLifecycle; + let sentInProgress = skipLifecycle; + let inputTokens = 0; + let outputTokens = 0; + let cachedTokens = 0; + let messageOutputIndex = 0; + let nextOutputIndex = 0; + let reasoningTokens = 0; + const textBlocks = new Map(); + const toolBlocks = new Map(); + + const emit = (controller: ReadableStreamDefaultController, event: string, data: unknown) => { + controller.enqueue(encoder.encode(formatEvent(event, data))); + }; + + const ensureLifecycle = (controller: ReadableStreamDefaultController) => { + if (!sentCreated) { + emit(controller, "response.created", { response: { id: responseId, model } }); + sentCreated = true; + } + if (!sentInProgress) { + emit(controller, "response.in_progress", { response: { id: responseId } }); + sentInProgress = true; + } + }; + + const getTextBlock = (index: number): TextBlockState => { + let block = textBlocks.get(index); + if (!block) { + if (textBlocks.size === 0) { + messageOutputIndex = nextOutputIndex; + nextOutputIndex += 1; + } + block = { + outputIndex: messageOutputIndex, + contentIndex: 0, + itemId: `msg_${randomUUID().slice(0, 12)}`, + textBuffer: "", + itemAdded: false, + partAdded: false, + itemDone: false, + }; + textBlocks.set(index, block); + } + return block; + }; + + const ensureTextItem = ( + controller: ReadableStreamDefaultController, + block: TextBlockState, + ) => { + if (!block.itemAdded) { + emit(controller, "response.output_item.added", { + output_index: block.outputIndex, + item: { + id: block.itemId, + type: "message", + role: "assistant", + status: "in_progress", + content: [], + }, + }); + block.itemAdded = true; + } + if (!block.partAdded) { + emit(controller, "response.content_part.added", { + output_index: block.outputIndex, + content_index: block.contentIndex, + item_id: block.itemId, + part: { type: "output_text", annotations: [], logprobs: [], text: "" }, + }); + block.partAdded = true; + } + }; + + const finishToolBlock = ( + controller: ReadableStreamDefaultController, + tool: ToolBlockState, + ) => { + if (tool.itemDone) return; + emit(controller, "response.function_call_arguments.done", { + call_id: tool.id, + name: tool.name, + arguments: tool.argBuffer, + output_index: tool.outputIndex, + }); + emit(controller, "response.output_item.done", { + output_index: tool.outputIndex, + item: { + type: "function_call", + id: tool.itemId, + call_id: tool.id, + name: tool.name, + arguments: tool.argBuffer, + }, + }); + tool.itemDone = true; + }; + + const finishTextBlock = ( + controller: ReadableStreamDefaultController, + textBlock: TextBlockState, + ) => { + if (!textBlock.itemAdded || textBlock.itemDone) return; + emit(controller, "response.output_item.done", { + output_index: textBlock.outputIndex, + item: { + id: textBlock.itemId, + type: "message", + role: "assistant", + status: "completed", + content: [{ + type: "output_text", + text: textBlock.textBuffer, + annotations: [], + }], + }, + }); + textBlock.itemDone = true; + }; + + const buildResponseOutput = (): Record[] => { + const items: Array<{ outputIndex: number; item: Record }> = []; + for (const textBlock of textBlocks.values()) { + if (!textBlock.itemAdded) continue; + items.push({ + outputIndex: textBlock.outputIndex, + item: { + id: textBlock.itemId, + type: "message", + role: "assistant", + status: "completed", + content: [{ + type: "output_text", + text: textBlock.textBuffer, + annotations: [], + }], + }, + }); + } + for (const tool of toolBlocks.values()) { + items.push({ + outputIndex: tool.outputIndex, + item: { + type: "function_call", + id: tool.itemId, + call_id: tool.id, + name: tool.name, + arguments: tool.argBuffer, + }, + }); + } + return items + .sort((a, b) => a.outputIndex - b.outputIndex) + .map((entry) => entry.item); + }; + + return new ReadableStream({ + async start(controller) { + const reader = upstream.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + + let boundary = buffer.indexOf("\n\n"); + while (boundary !== -1) { + const chunk = buffer.slice(0, boundary + 2); + buffer = buffer.slice(boundary + 2); + boundary = buffer.indexOf("\n\n"); + + for (const { event, data } of parseSseChunk(chunk)) { + if (!isRecord(data)) continue; + + switch (event) { + case "message_start": { + const msg = isRecord(data.message) ? data.message : null; + if (msg && typeof msg.id === "string") { + void msg.id; + } + const usage = msg && isRecord(msg.usage) ? msg.usage : null; + if (usage && typeof usage.input_tokens === "number") { + inputTokens = usage.input_tokens; + } + if (usage && typeof usage.cache_read_input_tokens === "number") { + cachedTokens = usage.cache_read_input_tokens; + } + ensureLifecycle(controller); + break; + } + case "content_block_start": { + const block = isRecord(data.content_block) ? data.content_block : null; + const index = typeof data.index === "number" ? data.index : 0; + ensureLifecycle(controller); + + if (block?.type === "tool_use") { + const toolId = typeof block.id === "string" ? block.id : `call_${randomUUID().slice(0, 8)}`; + const toolName = typeof block.name === "string" ? block.name : ""; + const outputIndex = nextOutputIndex; + const itemId = `item_${outputIndex}`; + nextOutputIndex += 1; + toolBlocks.set(index, { + id: toolId, + name: toolName, + argBuffer: "", + outputIndex, + itemId, + itemDone: false, + }); + emit(controller, "response.output_item.added", { + output_index: outputIndex, + item: { + type: "function_call", + id: itemId, + call_id: toolId, + name: toolName, + }, + }); + } else if (block?.type === "text") { + ensureTextItem(controller, getTextBlock(index)); + } + break; + } + case "content_block_delta": { + const delta = isRecord(data.delta) ? data.delta : null; + const index = typeof data.index === "number" ? data.index : 0; + if (!delta) break; + ensureLifecycle(controller); + + if (delta.type === "text_delta" && typeof delta.text === "string") { + const textBlock = getTextBlock(index); + ensureTextItem(controller, textBlock); + textBlock.textBuffer += delta.text; + emit(controller, "response.output_text.delta", { + item_id: textBlock.itemId, + output_index: textBlock.outputIndex, + content_index: textBlock.contentIndex, + delta: delta.text, + }); + } else if (delta.type === "thinking_delta" && typeof delta.thinking === "string") { + reasoningTokens += 1; + emit(controller, "response.reasoning_summary_text.delta", { delta: delta.thinking }); + } else if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") { + const tool = toolBlocks.get(index); + if (tool) { + tool.argBuffer += delta.partial_json; + emit(controller, "response.function_call_arguments.delta", { + call_id: tool.id, + delta: delta.partial_json, + output_index: tool.outputIndex, + }); + } + } + break; + } + case "content_block_stop": { + const index = typeof data.index === "number" ? data.index : -1; + const tool = toolBlocks.get(index); + if (tool) { + finishToolBlock(controller, tool); + break; + } + + const textBlock = textBlocks.get(index); + if (textBlock && textBlock.partAdded) { + emit(controller, "response.output_text.done", { + item_id: textBlock.itemId, + output_index: textBlock.outputIndex, + content_index: textBlock.contentIndex, + text: textBlock.textBuffer, + }); + emit(controller, "response.content_part.done", { + output_index: textBlock.outputIndex, + content_index: textBlock.contentIndex, + item_id: textBlock.itemId, + part: { + type: "output_text", + annotations: [], + logprobs: [], + text: textBlock.textBuffer, + }, + }); + } + break; + } + case "message_delta": { + const usage = isRecord(data.usage) ? data.usage : null; + if (usage && typeof usage.output_tokens === "number") { + outputTokens = usage.output_tokens; + } + if (usage && typeof usage.cache_read_input_tokens === "number") { + cachedTokens = Math.max(cachedTokens, usage.cache_read_input_tokens); + } + break; + } + case "message_stop": { + for (const tool of toolBlocks.values()) { + finishToolBlock(controller, tool); + } + for (const textBlock of textBlocks.values()) { + finishTextBlock(controller, textBlock); + } + + const output = buildResponseOutput(); + emit(controller, "response.completed", { + response: { + id: responseId, + model, + status: "completed", + output, + usage: { + input_tokens: inputTokens, + output_tokens: outputTokens, + total_tokens: inputTokens + outputTokens, + reasoning_tokens: reasoningTokens, + input_tokens_details: { cached_tokens: cachedTokens }, + output_tokens_details: { reasoning_tokens: reasoningTokens }, + }, + }, + }); + break; + } + case "error": { + const err = isRecord(data.error) ? data.error : data; + emit(controller, "error", { + error: { + type: typeof err.type === "string" ? err.type : "api_error", + message: typeof err.message === "string" ? err.message : "Upstream error", + }, + }); + break; + } + default: + break; + } + } + } + } + } finally { + reader.releaseLock(); + controller.close(); + } + }, + }); +} + +/** Convert a non-streaming Anthropic message to Responses API JSON. */ +export function anthropicMessageToResponses( + resp: Record, + model: string, +): Record { + const id = typeof resp.id === "string" ? resp.id : `resp_${randomUUID().slice(0, 12)}`; + const content = Array.isArray(resp.content) ? resp.content : []; + const output: Record[] = []; + let outputIndex = 0; + + const textParts = content + .filter((b) => isRecord(b) && b.type === "text") + .map((b) => (isRecord(b) ? String(b.text ?? "") : "")) + .join(""); + if (textParts) { + output.push({ + type: "message", + id: `msg_${id}`, + role: "assistant", + status: "completed", + content: [{ type: "output_text", text: textParts, annotations: [] }], + }); + outputIndex += 1; + } + + for (const block of content) { + if (!isRecord(block) || block.type !== "tool_use") continue; + const name = typeof block.name === "string" ? block.name : "tool"; + const callId = typeof block.id === "string" ? block.id : `call_${name}`; + const args = block.input != null ? JSON.stringify(block.input) : "{}"; + output.push({ + type: "function_call", + id: `item_${outputIndex}`, + call_id: callId, + name, + arguments: args, + }); + outputIndex += 1; + } + + if (output.length === 0) { + output.push({ + type: "message", + id: `msg_${id}`, + role: "assistant", + status: "completed", + content: [{ type: "output_text", text: "", annotations: [] }], + }); + } + + const usage = isRecord(resp.usage) ? resp.usage : {}; + return { + id, + object: "response", + model, + status: "completed", + output, + usage: { + input_tokens: typeof usage.input_tokens === "number" ? usage.input_tokens : 0, + output_tokens: typeof usage.output_tokens === "number" ? usage.output_tokens : 0, + total_tokens: + (typeof usage.input_tokens === "number" ? usage.input_tokens : 0) + + (typeof usage.output_tokens === "number" ? usage.output_tokens : 0), + }, + }; +} diff --git a/src/proxy/start-plan-body.ts b/src/proxy/start-plan-body.ts new file mode 100644 index 0000000..a491b95 --- /dev/null +++ b/src/proxy/start-plan-body.ts @@ -0,0 +1,49 @@ +/** Normalize Anthropic bodies for zcode-plan upstream (matches ZCode desktop). */ + +const MODEL_MAP: Record = { + "glm-5.2": "GLM-5.2", + "glm-5-turbo": "GLM-5-Turbo", + "glm-5.1": "GLM-5.1", + "glm-4.7": "GLM-4.7", +}; + +export function normalizeStartPlanBody(body: string | undefined): string | undefined { + if (!body) return body; + let parsed: Record; + try { + parsed = JSON.parse(body) as Record; + } catch { + return body; + } + + let changed = false; + + if (typeof parsed.model === "string") { + const mapped = MODEL_MAP[parsed.model.toLowerCase()] ?? parsed.model; + if (mapped !== parsed.model) { + parsed.model = mapped; + changed = true; + } + } + + if (parsed.stream !== true) { + parsed.stream = true; + changed = true; + } + + const messages = parsed.messages; + if (Array.isArray(messages)) { + const bridged = messages.map((msg) => { + if (typeof msg !== "object" || msg === null) return msg; + const m = msg as Record; + if (typeof m.content === "string") { + changed = true; + return { ...m, content: [{ type: "text", text: m.content }] }; + } + return msg; + }); + if (changed) parsed.messages = bridged; + } + + return changed ? JSON.stringify(parsed) : body; +} diff --git a/src/proxy/system-prompt.test.ts b/src/proxy/system-prompt.test.ts new file mode 100644 index 0000000..9cb7edf --- /dev/null +++ b/src/proxy/system-prompt.test.ts @@ -0,0 +1,36 @@ +import { describe, it, expect } from "bun:test"; +import { injectOfficialZcodeSystem, ZCODE_SYSTEM_BLOCKS } from "./system-prompt.js"; + +describe("injectOfficialZcodeSystem", () => { + it("prepends two official gateway blocks", () => { + const body: Record = { + messages: [{ role: "user", content: "hi" }], + }; + injectOfficialZcodeSystem(body); + const system = body.system as Array<{ type: string; text: string }>; + expect(system).toHaveLength(2); + expect(system[0].text).toBe(ZCODE_SYSTEM_BLOCKS[0].text); + expect(system[1].text).toBe(ZCODE_SYSTEM_BLOCKS[1].text); + }); + + it("appends user system blocks after official blocks", () => { + const body: Record = { + system: [{ type: "text", text: "custom rules" }], + messages: [], + }; + injectOfficialZcodeSystem(body); + const system = body.system as Array<{ text: string }>; + expect(system).toHaveLength(3); + expect(system[2].text).toBe("custom rules"); + }); + + it("handles malformed text block without throwing", () => { + const body: Record = { + system: [{ type: "text", text: 123 }], + messages: [], + }; + expect(() => injectOfficialZcodeSystem(body)).not.toThrow(); + const system = body.system as Array<{ text: string }>; + expect(system).toHaveLength(2); + }); +}); diff --git a/src/proxy/system-prompt.ts b/src/proxy/system-prompt.ts new file mode 100644 index 0000000..c0a0d97 --- /dev/null +++ b/src/proxy/system-prompt.ts @@ -0,0 +1,46 @@ +import systemBlocks from "./zcode_system.json" with { type: "json" }; + +type SystemBlock = { + type: "text"; + text: string; + cache_control?: { type: "ephemeral" }; +}; + +/** Official ZCode gateway blocks (positions 0/1) — required or upstream returns 3012. */ +export const ZCODE_SYSTEM_BLOCKS = systemBlocks as SystemBlock[]; + +function normalizeUserSystem(system: unknown): SystemBlock[] { + if (system == null) return []; + if (typeof system === "string") { + const text = system.trim(); + return text ? [{ type: "text", text }] : []; + } + if (!Array.isArray(system)) return []; + const out: SystemBlock[] = []; + for (const item of system) { + if (typeof item === "string") { + if (item.trim()) out.push({ type: "text", text: item }); + } else if (item && typeof item === "object" && (item as SystemBlock).type === "text") { + const b = item as SystemBlock; + const text = typeof b.text === "string" ? b.text.trim() : ""; + if (text) { + out.push({ + type: "text", + text, + ...(b.cache_control ? { cache_control: b.cache_control } : {}), + }); + } + } + } + return out; +} + +/** Prepend official blocks; client system (if any) goes after position 1. */ +export function injectOfficialZcodeSystem(body: Record): boolean { + const userBlocks = normalizeUserSystem(body.system); + const official = ZCODE_SYSTEM_BLOCKS.map((b) => structuredClone(b)); + const next = [...official, ...userBlocks]; + const prev = JSON.stringify(body.system ?? null); + body.system = next; + return prev !== JSON.stringify(next); +} diff --git a/src/proxy/upstream-errors.ts b/src/proxy/upstream-errors.ts new file mode 100644 index 0000000..0c9f9de --- /dev/null +++ b/src/proxy/upstream-errors.ts @@ -0,0 +1,34 @@ +/** Classify upstream failures for account pool rotation. */ +export type UpstreamFailureKind = + | "ok" + | "quota" + | "blocked" + | "auth" + | "captcha" + | "other"; + +export async function classifyUpstreamFailure( + resp: Response, + isCaptchaFailure: (r: Response) => Promise, +): Promise { + if (resp.ok) return "ok"; + + const text = await resp.clone().text().catch(() => ""); + const low = text.toLowerCase(); + + if (low.includes("3012") || (resp.status === 405 && low.includes("method not allowed"))) { + return "blocked"; + } + if ( + low.includes("1005") || + low.includes("exceed quota") || + low.includes("quota limit") || + low.includes("insufficient") || + resp.status === 402 + ) { + return "quota"; + } + if (resp.status === 401) return "auth"; + if (await isCaptchaFailure(resp)) return "captcha"; + return "other"; +} diff --git a/src/proxy/upstream.test.ts b/src/proxy/upstream.test.ts index 4c5c50d..3d2019c 100644 --- a/src/proxy/upstream.test.ts +++ b/src/proxy/upstream.test.ts @@ -46,6 +46,12 @@ describe("buildUpstreamURL", () => { ); }); + it("builds start-plan URL on zcode.z.ai", () => { + expect(buildUpstreamURL("anthropic", ZAI_PROVIDER, "start-plan")).toBe( + "https://zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages", + ); + }); + it("builds OpenAI URL for Bigmodel", () => { expect(buildUpstreamURL("openai", BIGMODEL_PROVIDER)).toBe( "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions", @@ -100,6 +106,19 @@ describe("buildAuthHeaders", () => { expect(h1["x-zcode-trace-id"]).not.toBe(h2["x-zcode-trace-id"]); expect(h1["x-query-id"]).not.toBe(h2["x-query-id"]); }); + + it("uses Bearer JWT for start-plan (no x-api-key, no anthropic-version)", () => { + const cred: Credential = { apiKey: "unused", provider: "zai", jwt: "eyJ.test.jwt" }; + const h = buildAuthHeaders("anthropic", cred, IDENTITY, "start-plan"); + expect(h.authorization).toBe("Bearer eyJ.test.jwt"); + expect(h["x-api-key"]).toBeUndefined(); + expect(h["anthropic-version"]).toBeUndefined(); + }); + + it("throws when start-plan has no JWT", () => { + const cred: Credential = { apiKey: "k", provider: "zai" }; + expect(() => buildAuthHeaders("anthropic", cred, IDENTITY, "start-plan")).toThrow(/JWT/); + }); }); describe("buildUpstreamRequest", () => { @@ -164,6 +183,7 @@ describe("proxyRequest", () => { models: ["glm-4.6"], identity: IDENTITY, logging: { level: "info" }, + pool: { enabled: false, maxAccountAttempts: 5 }, }; it("forwards request to upstream with injected auth", async () => { diff --git a/src/proxy/upstream.ts b/src/proxy/upstream.ts index 97cb46d..7aac13d 100644 --- a/src/proxy/upstream.ts +++ b/src/proxy/upstream.ts @@ -41,7 +41,6 @@ export function buildUpstreamURL(format: Format, provider: ProviderDef, plan: "c } export function buildAuthHeaders(format: Format, cred: Credential, identity: ProxyIdentity, plan: "coding-plan" | "start-plan" = "coding-plan"): Record { - const credStr = plan === "start-plan" && cred.jwt ? cred.jwt : credentialString(cred); const base: Record = { ...buildIdentityHeaders(identity), "x-request-id": crypto.randomUUID(), @@ -50,11 +49,22 @@ export function buildAuthHeaders(format: Format, cred: Credential, identity: Pro "x-session-id": crypto.randomUUID(), }; + // Start Plan: JWT as Bearer on zcode-plan — no anthropic-version (matches ZCode rollout). + if (plan === "start-plan") { + const jwt = cred.jwt?.trim(); + if (!jwt) { + throw new Error("start-plan requires OAuth JWT — run: bun run src/index.ts auth login zai"); + } + base.authorization = `Bearer ${jwt}`; + return base; + } + + const credStr = credentialString(cred); if (format === "anthropic") { base["x-api-key"] = credStr; base["anthropic-version"] = ANTHROPIC_VERSION; } else { - base["authorization"] = `Bearer ${credStr}`; + base.authorization = `Bearer ${credStr}`; } return base; diff --git a/src/proxy/zcode_system.json b/src/proxy/zcode_system.json new file mode 100644 index 0000000..0f33dc0 --- /dev/null +++ b/src/proxy/zcode_system.json @@ -0,0 +1,16 @@ +[ + { + "type": "text", + "text": "You are ZCode, an interactive coding agent", + "cache_control": { + "type": "ephemeral" + } + }, + { + "type": "text", + "text": "\nYou are an interactive ZCode agent that helps users with software engineering tasks.\n\nIMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.\n\n# Harness\n- Text you output outside of tool use is displayed to the user as Github-flavored markdown in a terminal.\n- Tools run behind a user-selected permission mode; a denied call means the user declined it — adjust, don't retry verbatim.\n- `` tags in messages and tool results are injected by the harness, not the user. Hooks may intercept tool calls; treat hook output as user feedback.\n- Prefer the dedicated file/search tools over shell commands when one fits. Independent tool calls can run in parallel in one response.\n- Reference code as `file_path:line_number` — it's clickable.", + "cache_control": { + "type": "ephemeral" + } + } +] diff --git a/src/server/request-logs.test.ts b/src/server/request-logs.test.ts new file mode 100644 index 0000000..62ce778 --- /dev/null +++ b/src/server/request-logs.test.ts @@ -0,0 +1,85 @@ +import { describe, it, expect } from "bun:test"; +import { + RequestLogStore, + usageFromResponseBody, + usageFromSsePayload, + mergeTokenUsage, +} from "./request-logs.js"; + +describe("RequestLogStore", () => { + it("stores and summarizes logs", () => { + const store = new RequestLogStore(10); + store.append({ + id: "#001", + format: "anthropic", + model: "glm-5.2", + stream: false, + status: 200, + ttfbMs: 120, + tokens: 42, + inputTokens: 1000, + outputTokens: 42, + cachedTokens: 800, + tokPerSec: 10, + totalMs: 500, + accountUserId: "user-1", + }); + const { entries, total, summary } = store.list(); + expect(total).toBe(1); + expect(entries[0]?.model).toBe("glm-5.2"); + expect(entries[0]?.cachedTokens).toBe(800); + expect(summary.last24h).toBe(1); + expect(summary.totalTokens24h).toBe(42); + expect(summary.totalInputTokens24h).toBe(1000); + expect(summary.totalCachedTokens24h).toBe(800); + expect(summary.cacheHitRate24h).toBe(80); + }); +}); + +describe("usage parsers", () => { + it("reads Anthropic message_start usage", () => { + const u = usageFromSsePayload({ + type: "message_start", + message: { usage: { input_tokens: 500, cache_read_input_tokens: 400 } }, + }); + expect(u).toEqual({ inputTokens: 500, cachedTokens: 400 }); + }); + + it("reads Responses API response.completed usage", () => { + const u = usageFromSsePayload({ + type: "response.completed", + response: { + usage: { + input_tokens: 1200, + output_tokens: 88, + input_tokens_details: { cached_tokens: 900 }, + output_tokens_details: { reasoning_tokens: 12 }, + }, + }, + }); + expect(u).toEqual({ + inputTokens: 1200, + outputTokens: 88, + cachedTokens: 900, + reasoningTokens: 12, + }); + }); + + it("reads Anthropic JSON message body", () => { + const u = usageFromResponseBody({ + type: "message", + usage: { input_tokens: 300, output_tokens: 50, cache_read_input_tokens: 200 }, + }); + expect(u).toEqual({ inputTokens: 300, outputTokens: 50, cachedTokens: 200 }); + }); + + it("merges usage patches", () => { + const merged = mergeTokenUsage( + { inputTokens: 10, outputTokens: 0, cachedTokens: 0, reasoningTokens: 0 }, + { outputTokens: 20, cachedTokens: 5 }, + ); + expect(merged.outputTokens).toBe(20); + expect(merged.inputTokens).toBe(10); + expect(merged.cachedTokens).toBe(5); + }); +}); diff --git a/src/server/request-logs.ts b/src/server/request-logs.ts new file mode 100644 index 0000000..ab19c1d --- /dev/null +++ b/src/server/request-logs.ts @@ -0,0 +1,241 @@ +/** + * In-memory request log for the web dashboard. + */ +export interface RequestTokenUsage { + inputTokens: number; + outputTokens: number; + cachedTokens: number; + reasoningTokens: number; +} + +export interface RequestLogEntry { + id: string; + at: string; + format: "anthropic" | "openai"; + model: string; + stream: boolean; + status: number; + ttfbMs: number; + /** Output tokens (legacy field name). */ + tokens: number; + inputTokens: number; + outputTokens: number; + cachedTokens: number; + reasoningTokens: number; + tokPerSec: number; + totalMs: number; + accountId?: string; + accountUserId?: string; +} + +function isRecord(v: unknown): v is Record { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +function num(v: unknown): number { + return typeof v === "number" && Number.isFinite(v) ? v : 0; +} + +/** Merge usage fields from an SSE JSON payload (Anthropic or Responses API). */ +export function usageFromSsePayload(data: unknown): Partial | null { + if (!isRecord(data)) return null; + + if (data.type === "message_start" && isRecord(data.message) && isRecord(data.message.usage)) { + const u = data.message.usage; + return { + inputTokens: num(u.input_tokens), + cachedTokens: num(u.cache_read_input_tokens), + }; + } + + if (data.type === "message_delta" && isRecord(data.usage)) { + const u = data.usage; + return { + outputTokens: num(u.output_tokens), + cachedTokens: num(u.cache_read_input_tokens), + }; + } + + if (data.type === "response.completed" && isRecord(data.response) && isRecord(data.response.usage)) { + const u = data.response.usage; + const inDet = isRecord(u.input_tokens_details) ? u.input_tokens_details : {}; + const outDet = isRecord(u.output_tokens_details) ? u.output_tokens_details : {}; + return { + inputTokens: num(u.input_tokens), + outputTokens: num(u.output_tokens), + cachedTokens: num(inDet.cached_tokens), + reasoningTokens: num(outDet.reasoning_tokens) || num(u.reasoning_tokens), + }; + } + + if (isRecord(data.usage)) { + const u = data.usage; + return { + inputTokens: num(u.prompt_tokens) || num(u.input_tokens), + outputTokens: num(u.completion_tokens) || num(u.output_tokens), + cachedTokens: num(u.cache_read_input_tokens), + }; + } + + return null; +} + +/** Usage from a complete JSON response body (Anthropic message, OpenAI chat, Responses API). */ +export function usageFromResponseBody(data: unknown): Partial | null { + if (!isRecord(data)) return null; + + if (data.type === "message" && isRecord(data.usage)) { + const u = data.usage; + return { + inputTokens: num(u.input_tokens), + outputTokens: num(u.output_tokens), + cachedTokens: num(u.cache_read_input_tokens), + }; + } + + if (isRecord(data.usage)) { + const u = data.usage; + const inDet = isRecord(u.input_tokens_details) ? u.input_tokens_details : {}; + const outDet = isRecord(u.output_tokens_details) ? u.output_tokens_details : {}; + return { + inputTokens: num(u.prompt_tokens) || num(u.input_tokens), + outputTokens: num(u.completion_tokens) || num(u.output_tokens), + cachedTokens: num(u.cache_read_input_tokens) || num(inDet.cached_tokens), + reasoningTokens: num(outDet.reasoning_tokens) || num(u.reasoning_tokens), + }; + } + + return null; +} + +export function mergeTokenUsage( + base: RequestTokenUsage, + patch: Partial | null | undefined, +): RequestTokenUsage { + if (!patch) return base; + return { + inputTokens: patch.inputTokens ?? base.inputTokens, + outputTokens: patch.outputTokens ?? base.outputTokens, + cachedTokens: patch.cachedTokens ?? base.cachedTokens, + reasoningTokens: patch.reasoningTokens ?? base.reasoningTokens, + }; +} + +export function normalizeTokenUsage( + partial?: Partial | null, + legacyOutputTokens = 0, +): RequestTokenUsage { + const output = partial?.outputTokens ?? legacyOutputTokens; + return { + inputTokens: partial?.inputTokens ?? 0, + outputTokens: output, + cachedTokens: partial?.cachedTokens ?? 0, + reasoningTokens: partial?.reasoningTokens ?? 0, + }; +} + +export class RequestLogStore { + private entries: RequestLogEntry[] = []; + private counter = 0; + + constructor(private maxEntries = 1000) {} + + append( + partial: Omit & { + at?: string; + tokens?: number; + outputTokens?: number; + inputTokens?: number; + cachedTokens?: number; + reasoningTokens?: number; + }, + ): RequestLogEntry { + const usage = normalizeTokenUsage( + { + inputTokens: partial.inputTokens, + outputTokens: partial.outputTokens ?? partial.tokens, + cachedTokens: partial.cachedTokens, + reasoningTokens: partial.reasoningTokens, + }, + partial.tokens ?? 0, + ); + const entry: RequestLogEntry = { + id: partial.id, + at: partial.at ?? new Date().toISOString(), + format: partial.format, + model: partial.model, + stream: partial.stream, + status: partial.status, + ttfbMs: partial.ttfbMs, + tokens: usage.outputTokens, + inputTokens: usage.inputTokens, + outputTokens: usage.outputTokens, + cachedTokens: usage.cachedTokens, + reasoningTokens: usage.reasoningTokens, + tokPerSec: partial.tokPerSec, + totalMs: partial.totalMs, + accountId: partial.accountId, + accountUserId: partial.accountUserId, + }; + this.entries.unshift(entry); + if (this.entries.length > this.maxEntries) { + this.entries.length = this.maxEntries; + } + return entry; + } + + list(opts: { limit?: number; offset?: number } = {}): { + entries: RequestLogEntry[]; + total: number; + summary: LogSummary; + } { + const limit = Math.min(opts.limit ?? 100, 500); + const offset = opts.offset ?? 0; + const slice = this.entries.slice(offset, offset + limit); + return { entries: slice, total: this.entries.length, summary: this.summary() }; + } + + summary(): LogSummary { + const now = Date.now(); + const dayAgo = now - 86_400_000; + let last24h = 0; + let ok = 0; + let outputTokens = 0; + let inputTokens = 0; + let cachedTokens = 0; + + for (const e of this.entries) { + const t = Date.parse(e.at); + if (t >= dayAgo) { + last24h += 1; + if (e.status >= 200 && e.status < 300) ok += 1; + outputTokens += e.outputTokens || e.tokens; + inputTokens += e.inputTokens; + cachedTokens += e.cachedTokens; + } + } + + return { + total: this.entries.length, + last24h, + successRate: last24h > 0 ? Math.round((ok / last24h) * 100) : 100, + totalTokens24h: outputTokens, + totalInputTokens24h: inputTokens, + totalOutputTokens24h: outputTokens, + totalCachedTokens24h: cachedTokens, + cacheHitRate24h: inputTokens > 0 ? Math.round((cachedTokens / inputTokens) * 100) : 0, + }; + } +} + +export interface LogSummary { + total: number; + last24h: number; + successRate: number; + /** @deprecated use totalOutputTokens24h */ + totalTokens24h: number; + totalInputTokens24h: number; + totalOutputTokens24h: number; + totalCachedTokens24h: number; + cacheHitRate24h: number; +} diff --git a/src/server/routes-admin.ts b/src/server/routes-admin.ts new file mode 100644 index 0000000..feec3e1 --- /dev/null +++ b/src/server/routes-admin.ts @@ -0,0 +1,271 @@ +/** + * Admin API + web dashboard backend. + */ +import type { AccountPool } from "../auth/account-pool.js"; +import { errorResponse } from "../proxy/handler.js"; +import { decodeJwtUserId, loadZcodeJwtFromDesktop } from "../auth/zcode-credentials.js"; +import type { QuotaCache } from "../auth/quota-cache.js"; +import { fetchBillingBalance } from "../auth/billing.js"; +import { saveCredential } from "../auth/store.js"; +import { onboardStartPlan } from "../auth/onboard.js"; +import type { OnboardJobManager } from "../auth/onboard-jobs.js"; +import type { RequestLogStore } from "./request-logs.js"; +import type { ProxyConfig } from "../config/types.js"; +import type { ProviderId } from "../provider/types.js"; + +export interface AdminContext { + accountPool: AccountPool; + config: ProxyConfig; + onboardJobs: OnboardJobManager; + requestLogs: RequestLogStore; + quotaCache?: QuotaCache; +} + +export function handleAdminRoute( + req: Request, + ctx: AdminContext, +): Promise | Response { + const { accountPool, config, onboardJobs, requestLogs, quotaCache } = ctx; + const url = new URL(req.url); + const path = url.pathname; + + if (path === "/admin/status" && req.method === "GET") { + const poolEnabled = + config.plan === "start-plan" && + (config.pool?.enabled !== false || accountPool.size() > 0); + return Response.json({ + status: "ok", + plan: config.plan, + provider: config.provider, + authMode: config.auth.mode, + requiresProxyKey: Boolean(config.auth.proxyApiKey), + pool: { + enabled: poolEnabled, + total: accountPool.size(), + active: accountPool.activeCount(), + maxAttempts: config.pool?.maxAccountAttempts ?? 5, + }, + server: config.server, + defaultModel: config.defaultModel, + models: config.models, + identity: config.identity, + logs: requestLogs.summary(), + }); + } + + if (path === "/admin/logs" && req.method === "GET") { + const limit = Number(url.searchParams.get("limit") ?? "100"); + const offset = Number(url.searchParams.get("offset") ?? "0"); + return Response.json(requestLogs.list({ limit, offset })); + } + + if (path === "/admin/quota" && req.method === "GET") { + if (quotaCache) { + return Response.json(quotaCache.getSnapshot()); + } + const accounts = accountPool.list(); + return Promise.all( + accounts.map(async (account) => { + const { fetchBillingBalance } = await import("../auth/billing.js"); + const balance = await fetchBillingBalance(account.jwt); + return { + id: account.id, + userId: account.userId, + status: account.status, + enabled: account.enabled, + usageCount: account.usageCount, + lastUsedAt: account.lastUsedAt, + ok: balance.ok, + serverTime: balance.serverTime, + balances: balance.balances.map((b) => ({ + show_name: b.show_name, + total_units: b.total_units, + used_units: b.used_units, + remaining_units: b.remaining_units, + period_end: b.period_end, + period_start: b.period_start, + })), + fetchedAt: Date.now(), + }; + }), + ).then((items) => + Response.json({ + accounts: items, + cache: { + refreshing: false, + cycleIntervalSec: 0, + fetchDelaySec: 0, + nextRefreshAt: null, + lastCompletedAt: null, + }, + }), + ); + } + + if (path === "/admin/accounts" && req.method === "GET") { + return Response.json({ + accounts: accountPool.listPublic(), + active: accountPool.activeCount(), + total: accountPool.size(), + }); + } + + if (path === "/admin/accounts" && req.method === "POST") { + return req.json().then((body: { jwt?: string; provider?: ProviderId }) => { + const jwt = body.jwt?.trim(); + if (!jwt) { + return errorResponse(400, "invalid_request", "jwt is required"); + } + const cred = { + apiKey: "start-plan", + provider: body.provider ?? "zai", + jwt, + userId: decodeJwtUserId(jwt), + }; + const id = accountPool.addFromCredential(cred); + void saveCredential(cred); + return Response.json({ id, ok: true }, { status: 201 }); + }); + } + + if (path === "/admin/import-desktop" && req.method === "POST") { + return (async () => { + const jwt = loadZcodeJwtFromDesktop(); + if (!jwt) { + return errorResponse( + 404, + "not_found", + "No JWT in ~/.zcode/v2/credentials.json. Log into ZCode desktop first.", + ); + } + const cred = { + apiKey: "start-plan", + provider: "zai" as const, + jwt, + userId: decodeJwtUserId(jwt), + }; + await saveCredential(cred); + const id = accountPool.addFromCredential(cred); + return Response.json({ id, ok: true, userId: cred.userId }, { status: 201 }); + })(); + } + + if (path === "/admin/onboard/start" && req.method === "POST") { + return req.json().then(async (body: { launchDesktop?: boolean }) => { + try { + const job = await onboardJobs.start({ + launchDesktop: body.launchDesktop, + accountPool, + }); + return Response.json(job, { status: 201 }); + } catch (err) { + return errorResponse(500, "onboard_error", (err as Error).message); + } + }); + } + + const onboardMatch = path.match(/^\/admin\/onboard\/([^/]+)$/); + if (onboardMatch && req.method === "GET") { + const job = onboardJobs.get(onboardMatch[1]!); + if (!job) { + return errorResponse(404, "not_found", "onboard session not found"); + } + return Response.json(job); + } + + const balanceMatch = path.match(/^\/admin\/accounts\/([^/]+)\/balance$/); + if (balanceMatch && req.method === "GET") { + const account = accountPool.get(balanceMatch[1]!); + if (!account) { + return errorResponse(404, "not_found", "account not found"); + } + return fetchBillingBalance(account.jwt).then((balance) => + Response.json({ + accountId: account.id, + ok: balance.ok, + serverTime: balance.serverTime, + balances: balance.balances, + }), + ); + } + + const credentialMatch = path.match(/^\/admin\/accounts\/([^/]+)\/credential$/); + if (credentialMatch && req.method === "GET") { + const account = accountPool.get(credentialMatch[1]!); + if (!account) { + return errorResponse(404, "not_found", "account not found"); + } + return Response.json({ + id: account.id, + userId: account.userId, + provider: account.provider, + jwt: account.jwt, + status: account.status, + enabled: account.enabled, + }); + } + + const provisionMatch = path.match(/^\/admin\/accounts\/([^/]+)\/provision$/); + if (provisionMatch && req.method === "POST") { + return req.json().then(async (body: { launchDesktop?: boolean }) => { + const account = accountPool.get(provisionMatch[1]!); + if (!account) { + return errorResponse(404, "not_found", "account not found"); + } + const accessToken = + account.apiKey && account.apiKey !== "start-plan" ? account.apiKey : account.jwt; + try { + const result = await onboardStartPlan({ + provider: account.provider, + jwt: account.jwt, + accessToken, + userId: account.userId, + launchDesktop: body.launchDesktop !== false, + quotaTimeoutMs: 300_000, + quotaPollIntervalMs: (config.pool?.quotaFetchDelaySec ?? 5) * 1000, + }); + if (result.quotaReady) { + accountPool.markActive(account.id); + } + return Response.json({ + accountId: account.id, + userId: account.userId, + ok: true, + quotaReady: result.quotaReady, + balanceCount: result.balanceCount, + }); + } catch (err) { + return errorResponse(500, "provision_error", (err as Error).message); + } + }); + } + + const removeMatch = path.match(/^\/admin\/accounts\/([^/]+)$/); + if (removeMatch && req.method === "DELETE") { + const id = removeMatch[1]!; + if (!accountPool.remove(id)) { + return errorResponse(404, "not_found", "account not found"); + } + return Response.json({ ok: true }); + } + + const enableMatch = path.match(/^\/admin\/accounts\/([^/]+)\/enable$/); + if (enableMatch && req.method === "POST") { + const id = enableMatch[1]!; + if (!accountPool.setEnabled(id, true)) { + return errorResponse(404, "not_found", "account not found"); + } + return Response.json({ ok: true }); + } + + const disableMatch = path.match(/^\/admin\/accounts\/([^/]+)\/disable$/); + if (disableMatch && req.method === "POST") { + const id = disableMatch[1]!; + if (!accountPool.setEnabled(id, false)) { + return errorResponse(404, "not_found", "account not found"); + } + return Response.json({ ok: true }); + } + + return errorResponse(404, "not_found", `No admin route for ${req.method} ${path}`); +} diff --git a/src/server/routes-openai.ts b/src/server/routes-openai.ts index 71a6641..4a31723 100644 --- a/src/server/routes-openai.ts +++ b/src/server/routes-openai.ts @@ -2,9 +2,66 @@ * OpenAI-format route handlers: /v1/chat/completions + /v1/models. * @see .omo/plans/zcode-proxy.md Task 7 */ -import { proxyRequest, type ProxyHandlerOptions } from "../proxy/handler.js"; -import { MODELS } from "../provider/models.js"; +import { proxyRequest, errorResponse, type ProxyHandlerOptions } from "../proxy/handler.js"; +import { MODELS, getModel } from "../provider/models.js"; import type { OpenAIModelList } from "../translator/types.js"; +import type { ModelDef } from "../provider/types.js"; + +const MODEL_CREATED_TIMESTAMP = 1_700_000_000; + +const GLM52_REASONING_EFFORTS = [ + { reasoningEffort: "minimal", description: "Minimal reasoning" }, + { reasoningEffort: "low", description: "Fastest responses" }, + { reasoningEffort: "medium", description: "Balanced speed and quality" }, + { reasoningEffort: "high", description: "Deeper reasoning" }, + { reasoningEffort: "xhigh", description: "Maximum reasoning depth" }, +]; + +/** Codex-compatible model metadata (GET /v1/models/:id/info). */ +export interface CodexModelInfo { + id: string; + displayName: string; + description: string; + isDefault: boolean; + supportedReasoningEfforts: { reasoningEffort: string; description: string }[]; + defaultReasoningEffort: string; + inputModalities: string[]; + outputModalities: string[]; + supportsPersonality: boolean; + upgrade: string | null; + contextWindow?: number; + maxContextWindow?: number; + maxOutputTokens?: number; +} + +function toCodexModelInfo(model: ModelDef, isDefault = false): CodexModelInfo { + const reasoningEfforts = + model.id === "glm-5.2" && model.reasoning + ? GLM52_REASONING_EFFORTS + : model.reasoning + ? [ + { reasoningEffort: "low", description: "Fastest responses" }, + { reasoningEffort: "medium", description: "Balanced speed and quality" }, + { reasoningEffort: "high", description: "Deepest reasoning" }, + ] + : [{ reasoningEffort: "low", description: "Fastest responses" }]; + + return { + id: model.id, + displayName: model.name, + description: `${model.name} via zcode-proxy`, + isDefault, + supportedReasoningEfforts: reasoningEfforts, + defaultReasoningEffort: model.id === "glm-5.2" ? "medium" : model.reasoning ? "medium" : "low", + inputModalities: ["text"], + outputModalities: ["text"], + supportsPersonality: false, + upgrade: null, + contextWindow: model.contextWindow, + maxOutputTokens: model.maxOutputTokens, + maxContextWindow: model.contextWindow, + }; +} /** Handle POST /v1/chat/completions — forward to upstream OpenAI endpoint. */ export async function handleChatCompletions( @@ -21,6 +78,7 @@ export function handleListModels(): Response { data: MODELS.map((m) => ({ id: m.id, object: "model" as const, + created: MODEL_CREATED_TIMESTAMP, owned_by: "zcode-proxy", })), }; @@ -29,3 +87,49 @@ export function handleListModels(): Response { headers: { "content-type": "application/json" }, }); } + +/** Handle GET /v1/models/catalog — full Codex model catalog. */ +export function handleListModelCatalog(): Response { + const catalog = MODELS.map((m) => ({ + ...toCodexModelInfo(m, m.id === "glm-5.2"), + outputModalities: ["text"], + source: "static" as const, + })); + return new Response(JSON.stringify(catalog), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +/** Handle GET /v1/models/:modelId — single model in OpenAI format. */ +export function handleGetModel(modelId: string): Response { + const model = getModel(modelId); + if (!model) { + return errorResponse(404, "model_not_found", `Model '${modelId}' not found`); + } + return new Response(JSON.stringify({ + id: model.id, + object: "model", + created: MODEL_CREATED_TIMESTAMP, + owned_by: "zcode-proxy", + }), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +/** Handle GET /v1/models/:modelId/info — extended metadata for Codex. */ +export function handleGetModelInfo(modelId: string): Response { + const model = getModel(modelId); + if (!model) { + return new Response(JSON.stringify({ error: `Model '${modelId}' not found` }), { + status: 404, + headers: { "content-type": "application/json" }, + }); + } + const isDefault = model.id === "glm-5.2"; + return new Response(JSON.stringify(toCodexModelInfo(model, isDefault)), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} diff --git a/src/server/routes-responses.ts b/src/server/routes-responses.ts new file mode 100644 index 0000000..de1ea9e --- /dev/null +++ b/src/server/routes-responses.ts @@ -0,0 +1,40 @@ +/** + * OpenAI Responses API route (Codex wire_api=responses). + */ +import { proxyRequest, errorResponse, type ProxyHandlerOptions } from "../proxy/handler.js"; +import { translateResponsesToAnthropic } from "../translator/responses-to-anthropic.js"; + +/** Handle POST /responses and POST /v1/responses. */ +export async function handleResponses( + req: Request, + opts: ProxyHandlerOptions, +): Promise { + const raw = await req.text(); + if (!raw) { + return errorResponse(400, "invalid_request_error", "Missing request body"); + } + + let parsed: Record; + try { + parsed = JSON.parse(raw) as Record; + } catch { + return errorResponse(400, "invalid_request_error", "Invalid JSON in Responses API body"); + } + + if (process.env.ZCODE_PROXY_LOG_RESPONSES === "1") { + try { + await Bun.write("/tmp/last-responses-req.json", JSON.stringify(parsed, null, 2)); + } catch { + // ignore + } + } + + const anthropic = translateResponsesToAnthropic(parsed); + const syntheticReq = new Request(req.url, { + method: "POST", + headers: req.headers, + body: JSON.stringify(anthropic), + }); + + return proxyRequest(syntheticReq, "anthropic", { ...opts, responseBridge: "responses" }); +} diff --git a/src/server/routes-web.ts b/src/server/routes-web.ts new file mode 100644 index 0000000..3c71a50 --- /dev/null +++ b/src/server/routes-web.ts @@ -0,0 +1,18 @@ +/** + * Serve the built-in web dashboard (single-page app). + */ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +const DASHBOARD_PATH = join(import.meta.dir, "../web/dashboard.html"); + +export function handleDashboard(_req: Request): Response { + const html = readFileSync(DASHBOARD_PATH, "utf-8"); + return new Response(html, { + status: 200, + headers: { + "content-type": "text/html; charset=utf-8", + "cache-control": "no-cache", + }, + }); +} diff --git a/src/server/server.test.ts b/src/server/server.test.ts index e81893f..4d7b637 100644 --- a/src/server/server.test.ts +++ b/src/server/server.test.ts @@ -22,6 +22,7 @@ function makeConfig(overrides: Partial = {}): ProxyConfig { defaultModel: "glm-4.6", models: ["glm-4.6"], identity: { appVersion: "test-1.0.0", sourceTitle: "cli", refererOrigin: "https://zcode.z.ai" }, + pool: { enabled: false, maxAccountAttempts: 5 }, logging: { level: "info" }, ...overrides, }; @@ -106,6 +107,18 @@ describe("server routing", () => { expect(body.status).toBe("ok"); }); + it("GET /app returns dashboard HTML", async () => { + const config = makeConfig(); + const auth = new AuthManager({ mode: "apikey", provider: "zai", apiKey: "test" }); + const handler = createFetchHandler({ config, auth }); + + const resp = await handler(new Request("http://localhost/app")); + expect(resp.status).toBe(200); + expect(resp.headers.get("content-type")).toContain("text/html"); + const html = await resp.text(); + expect(html).toContain("ZCode Proxy"); + }); + it("unknown route returns 404", async () => { const config = makeConfig(); const auth = new AuthManager({ mode: "apikey", provider: "zai", apiKey: "test" }); @@ -197,3 +210,62 @@ describe("route handler exports", () => { expect(typeof handleMessages).toBe("function"); }); }); + +describe("responses and model metadata routes", () => { + it("GET /v1/models/glm-5.2 returns model", async () => { + const config = makeConfig({ auth: { mode: "apikey", apiKey: "test" } }); + const auth = new AuthManager({ mode: "apikey", provider: "zai", apiKey: "test" }); + const handler = createFetchHandler({ config, auth, fetchImpl: mockUpstream() }); + + const resp = await handler(new Request("http://localhost/v1/models/glm-5.2")); + expect(resp.status).toBe(200); + const body = await resp.json() as { id: string }; + expect(body.id).toBe("glm-5.2"); + }); + + it("GET /v1/models/glm-5.2/info returns Codex metadata", async () => { + const config = makeConfig({ auth: { mode: "apikey", apiKey: "test" } }); + const auth = new AuthManager({ mode: "apikey", provider: "zai", apiKey: "test" }); + const handler = createFetchHandler({ config, auth, fetchImpl: mockUpstream() }); + + const resp = await handler(new Request("http://localhost/v1/models/glm-5.2/info")); + expect(resp.status).toBe(200); + const body = await resp.json() as { id: string; supportedReasoningEfforts: unknown[] }; + expect(body.id).toBe("glm-5.2"); + expect(body.supportedReasoningEfforts.length).toBe(5); + }); + + it("POST /responses is routed (not 404)", async () => { + const config = makeConfig({ + auth: { mode: "apikey", apiKey: "test" }, + plan: "start-plan", + pool: { enabled: false, maxAccountAttempts: 5 }, + }); + const auth = new AuthManager({ mode: "apikey", provider: "zai", apiKey: "test" }); + const handler = createFetchHandler({ + config, + auth, + fetchImpl: async (req: Request) => { + if (req.url.includes("/v1/messages")) { + const sse = [ + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"m1\",\"usage\":{\"input_tokens\":1}}}\n\n", + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n", + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", + ].join(""); + return new Response(sse, { + status: 200, + headers: { "content-type": "text/event-stream" }, + }); + } + return new Response("{}", { status: 404 }); + }, + }); + + const resp = await handler(new Request("http://localhost/responses", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "glm-5.2", input: "hello" }), + })); + expect(resp.status).not.toBe(404); + }); +}); diff --git a/src/server/server.ts b/src/server/server.ts index dbcd9b8..6fdc4e3 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -4,34 +4,64 @@ */ import type { ProxyConfig } from "../config/types.js"; import type { AuthManager } from "../auth/manager.js"; -import { handleChatCompletions, handleListModels } from "./routes-openai.js"; +import type { AccountPool } from "../auth/account-pool.js"; +import type { OnboardJobManager } from "../auth/onboard-jobs.js"; +import type { QuotaCache } from "../auth/quota-cache.js"; +import { RequestLogStore } from "./request-logs.js"; +import { handleChatCompletions, handleListModels, handleListModelCatalog, handleGetModel, handleGetModelInfo } from "./routes-openai.js"; import { handleMessages } from "./routes-anthropic.js"; +import { handleResponses } from "./routes-responses.js"; +import { handleAdminRoute } from "./routes-admin.js"; +import { handleDashboard } from "./routes-web.js"; import { errorResponse } from "../proxy/handler.js"; export interface ServerOptions { config: ProxyConfig; auth: AuthManager; + accountPool?: AccountPool; + onboardJobs?: OnboardJobManager; + requestLogs?: RequestLogStore; + quotaCache?: QuotaCache; /** Override fetch for testing. */ fetchImpl?: typeof fetch; } /** Create a Bun.serve-compatible fetch handler. */ export function createFetchHandler(opts: ServerOptions): (req: Request) => Promise { - const { config, auth } = opts; - const proxyOpts = { config, auth, fetchImpl: opts.fetchImpl }; + const { config, auth, accountPool, onboardJobs, requestLogs, quotaCache } = opts; + const proxyOpts = { config, auth, accountPool, requestLogs, fetchImpl: opts.fetchImpl }; return async (req: Request): Promise => { const url = new URL(req.url); const path = url.pathname; const method = req.method; + if (process.env.ZCODE_PROXY_LOG_REQUESTS === "1") { + console.log(`[req] ${method} ${path}`); + } + // CORS preflight if (method === "OPTIONS") { return corsResponse(); } - // Proxy API key auth (if configured) - if (config.auth.proxyApiKey) { + // Web dashboard + admin API — no proxy key required + if (path === "/app" || path === "/app/") { + return handleDashboard(req); + } + + // Browser root → dashboard + if (path === "/" && method === "GET" && wantsHtml(req)) { + return handleDashboard(req); + } + + const isAdmin = path.startsWith("/admin/"); + const isProxyApi = + path.startsWith("/v1/") || + path === "/responses"; + + // Proxy API key protects LLM endpoints only — dashboard + /admin are open locally + if (isProxyApi && config.auth.proxyApiKey) { const authHeader = req.headers.get("authorization") ?? req.headers.get("x-api-key"); if (!authHeader || !checkProxyKey(authHeader, config.auth.proxyApiKey)) { return errorResponse(401, "authentication_error", "Invalid or missing proxy API key"); @@ -40,31 +70,55 @@ export function createFetchHandler(opts: ServerOptions): (req: Request) => Promi // --- Routing --- - // OpenAI routes if (path === "/v1/chat/completions" && method === "POST") { return handleChatCompletions(req, proxyOpts); } + if ((path === "/v1/responses" || path === "/responses") && method === "POST") { + return handleResponses(req, proxyOpts); + } if (path === "/v1/models" && method === "GET") { return handleListModels(); } + if (path === "/v1/models/catalog" && method === "GET") { + return handleListModelCatalog(); + } + const modelInfoMatch = path.match(/^\/v1\/models\/([^/]+)\/info$/); + if (modelInfoMatch && method === "GET") { + return handleGetModelInfo(decodeURIComponent(modelInfoMatch[1]!)); + } + const modelMatch = path.match(/^\/v1\/models\/([^/]+)$/); + if (modelMatch && method === "GET") { + return handleGetModel(decodeURIComponent(modelMatch[1]!)); + } - // Anthropic routes if (path === "/v1/messages" && method === "POST") { return handleMessages(req, proxyOpts); } - // Health check - if (path === "/health" || path === "/") { - return new Response(JSON.stringify({ status: "ok", provider: config.provider }), { + if (path === "/health" || (path === "/" && method === "GET")) { + const poolInfo = + accountPool && config.plan === "start-plan" + ? { pool: { total: accountPool.size(), active: accountPool.activeCount() } } + : {}; + return new Response(JSON.stringify({ status: "ok", provider: config.provider, ...poolInfo }), { status: 200, headers: { "content-type": "application/json" }, }); } + if (isAdmin && accountPool && onboardJobs && requestLogs) { + return handleAdminRoute(req, { accountPool, config, onboardJobs, requestLogs, quotaCache }); + } + return errorResponse(404, "not_found_error", `No route for ${method} ${path}`); }; } +function wantsHtml(req: Request): boolean { + const accept = req.headers.get("accept") ?? ""; + return accept.includes("text/html"); +} + /** Start the Bun.serve server. Returns the server instance. */ export function startServer(opts: ServerOptions): ReturnType { const handler = createFetchHandler(opts); @@ -73,26 +127,21 @@ export function startServer(opts: ServerOptions): ReturnType { return Bun.serve({ port, hostname: host, - idleTimeout: 0, // 自用代理:禁用空闲超时,避免长 reasoning 的 LLM 请求被杀 + idleTimeout: 0, fetch(req) { - // Add CORS headers to all responses return handler(req).then((resp) => addCorsHeaders(resp)); }, }); } -/** Check whether the client provided the correct proxy API key. */ function checkProxyKey(authHeader: string, expected: string): boolean { - // Accept "Bearer {key}" or bare key const trimmed = authHeader.trim(); if (trimmed.startsWith("Bearer ")) { return trimmed.slice(7).trim() === expected; } - // Also accept x-api-key: {key} return trimmed === expected; } -/** Build a CORS preflight response. */ function corsResponse(): Response { return new Response(null, { status: 204, @@ -100,7 +149,6 @@ function corsResponse(): Response { }); } -/** Add CORS headers to an existing response (non-mutating). */ function addCorsHeaders(resp: Response): Response { const headers = new Headers(resp.headers); for (const [k, v] of Object.entries(corsHeaders())) { @@ -116,7 +164,7 @@ function addCorsHeaders(resp: Response): Response { function corsHeaders(): Record { return { "access-control-allow-origin": "*", - "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-methods": "GET, POST, DELETE, OPTIONS", "access-control-allow-headers": "Content-Type, Authorization, x-api-key, anthropic-version, anthropic-beta", "access-control-max-age": "86400", }; diff --git a/src/server/startup.test.ts b/src/server/startup.test.ts new file mode 100644 index 0000000..3586706 --- /dev/null +++ b/src/server/startup.test.ts @@ -0,0 +1,63 @@ +/** + * Smoke test: server wiring must start without ReferenceError. + */ +import { describe, it, expect } from "bun:test"; +import { createFetchHandler } from "./server.js"; +import { AuthManager } from "../auth/manager.js"; +import { AccountPool } from "../auth/account-pool.js"; +import { OnboardJobManager } from "../auth/onboard-jobs.js"; +import { RequestLogStore } from "./request-logs.js"; +import type { ProxyConfig } from "../config/types.js"; + +function makeConfig(): ProxyConfig { + return { + server: { port: 0, host: "127.0.0.1" }, + auth: { mode: "oauth", proxyApiKey: "test-secret" }, + provider: "zai", + plan: "start-plan", + providers: { + zai: { anthropicBase: "https://api.z.ai/api/anthropic", openaiBase: "https://api.z.ai/api/coding/paas/v4" }, + bigmodel: { anthropicBase: "https://open.bigmodel.cn/api/anthropic", openaiBase: "https://open.bigmodel.cn/api/coding/paas/v4" }, + }, + defaultModel: "glm-5.2", + models: ["glm-5.2"], + identity: { appVersion: "3.1.2", sourceTitle: "cli", refererOrigin: "https://zcode.z.ai" }, + pool: { enabled: true, maxAccountAttempts: 5 }, + logging: { level: "info" }, + }; +} + +describe("server startup wiring", () => { + it("admin routes work with full server context", async () => { + const config = makeConfig(); + const auth = new AuthManager({ mode: "oauth", provider: "zai" }); + const accountPool = new AccountPool(); + const onboardJobs = new OnboardJobManager(); + const requestLogs = new RequestLogStore(); + + const handler = createFetchHandler({ + config, + auth, + accountPool, + onboardJobs, + requestLogs, + }); + + const app = await handler(new Request("http://localhost/app")); + expect(app.status).toBe(200); + const html = await app.text(); + expect(html).toContain("btn-add-account"); + expect(html).toContain("btn-show-accounts"); + + const status = await handler(new Request("http://localhost/admin/status")); + expect(status.status).toBe(200); + const body = await status.json(); + expect(body.logs).toBeDefined(); + + const quota = await handler(new Request("http://localhost/admin/quota")); + expect(quota.status).toBe(200); + + const logs = await handler(new Request("http://localhost/admin/logs")); + expect(logs.status).toBe(200); + }); +}); diff --git a/src/translator/responses-to-anthropic.test.ts b/src/translator/responses-to-anthropic.test.ts new file mode 100644 index 0000000..f5de732 --- /dev/null +++ b/src/translator/responses-to-anthropic.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "bun:test"; +import { translateResponsesToAnthropic } from "./responses-to-anthropic.js"; + +describe("translateResponsesToAnthropic", () => { + it("converts simple string input to anthropic user message", () => { + const out = translateResponsesToAnthropic({ + model: "glm-5.2", + input: "hello", + stream: true, + }); + expect(out.model).toBe("glm-5.2"); + expect(out.stream).toBe(true); + expect(out.messages).toEqual([{ role: "user", content: "hello" }]); + expect(out.max_tokens).toBe(8192); + }); + + it("merges instructions into system", () => { + const out = translateResponsesToAnthropic({ + model: "glm-5.2", + instructions: "Be concise", + input: [{ role: "user", content: "hi" }], + }); + expect(out.system).toBe("Be concise"); + }); + + it("defaults stream to true when omitted", () => { + const out = translateResponsesToAnthropic({ model: "glm-5.2", input: "x" }); + expect(out.stream).toBe(true); + }); +}); diff --git a/src/translator/responses-to-anthropic.ts b/src/translator/responses-to-anthropic.ts new file mode 100644 index 0000000..8985472 --- /dev/null +++ b/src/translator/responses-to-anthropic.ts @@ -0,0 +1,239 @@ +/** + * OpenAI Responses API → Anthropic messages (for Codex wire_api=responses). + */ +import type { AnthropicMessagesRequest, AnthropicMessage, AnthropicContentBlock } from "./types.js"; + +const DEFAULT_MAX_TOKENS = 8192; + +const REASONING_EFFORT_BUDGET: Record = { + minimal: 512, + low: 1024, + medium: 8192, + high: 16000, + xhigh: 32000, +}; + +function isRecord(v: unknown): v is Record { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +function str(v: unknown): string | undefined { + return typeof v === "string" ? v : undefined; +} + +function contentToText(content: unknown): string { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content + .map((part) => { + if (!isRecord(part)) return ""; + if (typeof part.text === "string") return part.text; + if (typeof part.output === "string") return part.output; + return ""; + }) + .filter(Boolean) + .join("\n"); +} + +function normalizeContent(content: unknown): string | AnthropicContentBlock[] { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + + const blocks: AnthropicContentBlock[] = []; + for (const part of content) { + if (!isRecord(part)) continue; + const type = part.type; + if (type === "text" || type === "input_text" || type === "output_text") { + blocks.push({ type: "text", text: str(part.text) ?? "" }); + continue; + } + if (type === "image_url" || type === "input_image") { + const url = + str(isRecord(part.image_url) ? part.image_url.url : undefined) ?? + str(part.url) ?? + str(part.image_url); + if (url?.startsWith("data:")) { + const m = url.match(/^data:([^;]+);base64,(.+)$/); + if (m) { + blocks.push({ + type: "image", + source: { type: "base64", media_type: m[1]!, data: m[2]! }, + }); + } + } + } + } + return blocks.length > 0 ? blocks : ""; +} + +function inputItemToMessages(item: unknown): AnthropicMessage[] { + if (typeof item === "string") { + return [{ role: "user", content: item }]; + } + if (!isRecord(item)) return []; + + if (item.type === "function_call") { + const name = str(item.name); + if (!name) return []; + const callId = str(item.call_id) ?? str(item.id) ?? `call_${name}`; + let input: Record = {}; + try { + const args = item.arguments; + input = typeof args === "string" ? JSON.parse(args) : (args as Record) ?? {}; + } catch { + input = {}; + } + return [{ + role: "assistant", + content: [{ type: "tool_use", id: callId, name, input }], + }]; + } + + if (item.type === "function_call_output") { + const callId = str(item.call_id) ?? str(item.id) ?? "unknown"; + return [{ + role: "user", + content: [{ + type: "tool_result", + tool_use_id: callId, + content: contentToText(item.output ?? item.content), + }], + }]; + } + + const role = str(item.role); + if (role === "assistant" || role === "user") { + const msg: AnthropicMessage = { + role, + content: normalizeContent(item.content), + }; + if (Array.isArray(item.tool_calls) && item.tool_calls.length > 0) { + const blocks: AnthropicContentBlock[] = Array.isArray(msg.content) + ? [...msg.content] + : msg.content ? [{ type: "text", text: msg.content }] : []; + for (const tc of item.tool_calls) { + if (!isRecord(tc) || !isRecord(tc.function)) continue; + const name = str(tc.function.name); + if (!name) continue; + const id = str(tc.id) ?? `call_${name}`; + let input: Record = {}; + try { + input = JSON.parse(str(tc.function.arguments) ?? "{}"); + } catch { + input = {}; + } + blocks.push({ type: "tool_use", id, name, input }); + } + msg.content = blocks; + } + return [msg]; + } + + if (item.type === "message" && role) { + return [{ role: role === "assistant" ? "assistant" : "user", content: normalizeContent(item.content) }]; + } + + if (item.type === "input_text" || item.type === "output_text") { + return [{ role: "user", content: str(item.text) ?? "" }]; + } + + return []; +} + +function normalizeInput(input: unknown): AnthropicMessage[] { + if (typeof input === "string") return [{ role: "user", content: input }]; + if (Array.isArray(input)) return input.flatMap(inputItemToMessages); + if (isRecord(input)) return inputItemToMessages(input); + return []; +} + +function normalizeTools(tools: unknown): AnthropicMessagesRequest["tools"] { + if (!Array.isArray(tools)) return undefined; + const out: NonNullable = []; + for (const tool of tools) { + if (!isRecord(tool)) continue; + if (tool.type === "function" && isRecord(tool.function)) { + out.push({ + name: str(tool.function.name) ?? "tool", + ...(str(tool.function.description) ? { description: tool.function.description } : {}), + ...(isRecord(tool.function.parameters) ? { input_schema: tool.function.parameters } : {}), + }); + continue; + } + if (tool.type === "function" || tool.type === "custom") { + const name = str(tool.name); + if (!name) continue; + out.push({ + name, + ...(str(tool.description) ? { description: tool.description } : {}), + ...(isRecord(tool.parameters) ? { input_schema: tool.parameters } : {}), + ...(isRecord(tool.input_schema) ? { input_schema: tool.input_schema } : {}), + }); + } + } + return out.length > 0 ? out : undefined; +} + +/** Translate a Responses API request body to Anthropic /v1/messages. */ +export function translateResponsesToAnthropic(body: Record): AnthropicMessagesRequest { + const model = str(body.model) ?? "glm-5.2"; + const stream = body.stream !== false; + + const systemParts: string[] = []; + const instructions = str(body.instructions); + if (instructions) systemParts.push(instructions); + + const messages = normalizeInput(body.input); + for (const msg of [...messages]) { + // Pull system/developer out of input if present (re-parse from raw input) + void msg; + } + if (Array.isArray(body.input)) { + for (const item of body.input) { + if (!isRecord(item)) continue; + const role = str(item.role); + if (role === "system" || role === "developer") { + const text = contentToText(item.content); + if (text) systemParts.push(text); + } + } + } + + const filtered = Array.isArray(body.input) + ? normalizeInput( + body.input.filter((item) => { + if (!isRecord(item)) return true; + const role = str(item.role); + return role !== "system" && role !== "developer"; + }), + ) + : messages; + + const maxTokens = + typeof body.max_output_tokens === "number" ? body.max_output_tokens : + typeof body.max_tokens === "number" ? body.max_tokens : + DEFAULT_MAX_TOKENS; + + const result: AnthropicMessagesRequest = { + model, + messages: filtered.length > 0 ? filtered : [{ role: "user", content: "" }], + max_tokens: maxTokens, + stream, + }; + + if (systemParts.length > 0) result.system = systemParts.join("\n\n"); + if (typeof body.temperature === "number") result.temperature = body.temperature; + if (typeof body.top_p === "number") result.top_p = body.top_p; + + const tools = normalizeTools(body.tools); + if (tools) result.tools = tools; + + const reasoning = isRecord(body.reasoning) ? body.reasoning : null; + const effort = reasoning && typeof reasoning.effort === "string" ? reasoning.effort : null; + if (effort && effort !== "none") { + const budget = REASONING_EFFORT_BUDGET[effort] ?? REASONING_EFFORT_BUDGET.medium!; + (result as Record).thinking = { type: "enabled", budget_tokens: budget }; + } + + return result; +} diff --git a/src/web/dashboard.html b/src/web/dashboard.html new file mode 100644 index 0000000..91895c7 --- /dev/null +++ b/src/web/dashboard.html @@ -0,0 +1,612 @@ + + + + + + ZCode Proxy + + + + + + +
+
+
+

ZCode Proxy

+

—

+
+
+ + + +
+
+ +
+
+ +
+ +
+ +
+
+
+

Request log

+

+ Prompt caching: the proxy marks the last message block with cache_control: ephemeral (same as ZCode). + Repeat requests with the same prefix bill fewer input tokens — cached shows how many were read from cache. +

+
+ + + + + + + + + + + + + + + + +
TimeIDModelAccountStatTTFBInOutCacheTotal
+
+ +
+
+
+ + + +
+ + + +