Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Changelog

## 0.2.0 — 2026-11-07

- Support the 3.17 client prompt layout, with extraction checked against official 3.17.1 and 3.17.2 bundles. Read client versions from package/ASAR metadata or explicit `provision --app-version`.
- Replace retired billing/current discovery with billing/balance plans and capability buckets, preserving activation times and plan selection.
- Discover free grants from billing previews and explicit marketing banner/popup claim actions. Enable scheduled claims by default, with `ZCODE_AUTO_CLAIM=false` as an opt-out.
- Persist actual grant expiry and bounded retry holds so undated recurring offers are revisited. Respect provider server time, Retry-After, CAPTCHA, authentication and risk responses.
- Add `promos` for discovery without claims and `claim` for one maintenance cycle. Expose sanitized offers, campaigns and per-source failures through existing authenticated usage/plan APIs.
- Keep legacy private templates, encrypted account data and all existing API protocols compatible. No npm production dependencies added.

Live verification covered current billing, marketing, process health and HTTP authentication. The available account had no active grant; successful live claims and inference with 3.17.2 were not verified. See [verification](docs/verification.md).
29 changes: 22 additions & 7 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

Use your own ZCode Start Plan accounts through OpenAI and Anthropic-compatible APIs. This standalone Node.js gateway supports OAuth login, an encrypted multi-account vault, streamed model output and function-tool conversations. It can run behind OmniRoute or be used directly.

This is an independent integration with an undocumented ZCode endpoint. It is not affiliated with Z.ai. Compatibility was checked against ZCode desktop **3.16.3**, with **GLM-5.3** and **GLM-5.3-Flash** entitlements. Provider changes can break the integration.
This is an independent integration with an undocumented ZCode endpoint. It is not affiliated with Z.ai. Updated for the ZCode **3.17.2** client format, including prompt extraction, versioned requests, billing and campaign discovery. Extraction was also checked with **3.17.1**. See [verification notes](docs/verification.md) for live-test limits; provider changes can break the integration.

## Supported endpoints

Expand Down Expand Up @@ -43,7 +43,9 @@ node --env-file=.env src/cli.ts provision 'C:\Program Files\ZCode\resources\glm\

`init` creates `.env` with independent random ZCODE_MASTER_KEY and ZCODE_API_KEYS values. For the API Key field in OmniRoute or another app, copy one value from `ZCODE_API_KEYS` in `.env`, without the `ZCODE_API_KEYS=` prefix. Do not use `ZCODE_MASTER_KEY` for API requests. Keep `.env` and `data/` out of Git. The server binds to `127.0.0.1:8080` by default.

Provisioning extracts only the supported prompt functions from your installed official client into `data/template.json`. It does not execute the installed application's entrypoint or modify ZCode. Vendor prompt text is **not distributed in this repository** and is not covered by this project's MIT license. The extractor fails when its expected bundle structure is absent; do not force it against another release without verification.
Provisioning extracts the supported private prompt sections from your installed official client into `data/template.json`. It does not execute the installed application's entrypoint or modify ZCode. Vendor prompt text is **not distributed in this repository** and is not covered by this project's MIT license. The extractor fails when its expected bundle structure is absent; do not force it against another release without verification.

The app version is read from adjacent `package.json` or `app.asar` metadata and passed to OAuth, billing, claims and inference. Run `provision` again after updating the desktop app. For a standalone bundle without its metadata, use `provision /path/zcode.cjs --app-version 3.17.2` with its actual release version. Legacy 3.16.3 templates remain readable. Unknown prompt structures fail instead of guessing compatibility.

The private template also records the provisioning machine's platform, shell, locale, timezone and working directory. Both upstream headers and environment context preserve those original values when the gateway moves to a VPS. This keeps the request consistent with the desktop profile being delegated; it does not grant the gateway access to that desktop's files or tools. Treat this metadata as private and regenerate the template when intentionally moving to a different client profile.

Expand Down Expand Up @@ -74,15 +76,28 @@ node --env-file=.env src/cli.ts remove ACCOUNT_ID

Selection rotates among enabled, model-entitled accounts, with one in-flight request per account. Quota, authentication and transient failures may try another account before any response content is sent. Risk-control rejection code 3012 pauses that account locally for 15 minutes and returns the error without trying to bypass its block. This delay is local policy, not an upstream reset guarantee. Streams are never replayed after output begins. Account credentials that fail authorization require a new login; the gateway does not pretend an undocumented refresh endpoint exists.

`quota` reads reported plan and balance data. Unknown counters remain unknown. The scheduler uses entitlements and provider errors, rather than guessing token balances from missing fields. Automatic claims are opt-in; see below.
`quota` reads reported plan and balance data. Unknown counters remain unknown. The scheduler uses entitlements and provider errors, rather than guessing token balances from missing fields. Automatic free-grant claims are enabled by default; see below.

## Automatic promotions and events

The worker runs at startup and every five minutes without inbound HTTP traffic. Automatic claims are **enabled by default**; set `ZCODE_AUTO_CLAIM=false` to opt out. An existing explicit false remains respected. `ZCODE_AUTO_CLAIM_INTERVAL_MS` defaults to `300000`, with a one-minute minimum. Restart the process or recreate the Compose service after changing settings.

Two official channels are queried per eligible Start Plan account: billing preview model grants, and marketing touch banner/popup buttons with the explicit `claim_zcode_plan` action. Campaign names and grant IDs come from provider responses. Paid preview entries, external URLs, navigation, invitation and copy actions are never executed. Subscription accounts, disabled accounts and accounts requiring login are skipped.

## Automatic free-plan claims
Offers are deduplicated across channels. Real expiry from claim responses prevents successful undated previews from suppressing future periods forever. Unknown claim expiry uses a bounded retry hold. After claims, entitlement discovery reads **billing balance**, replacing the retired `billing/current` endpoint. Capability buckets are matched to active plan instances; future and expired entitlements are excluded.

Stop `serve` before either one-shot command:

```sh
node --env-file=.env src/cli.ts promos # Discover only; no claims
node --env-file=.env src/cli.ts claim # Run one free-grant claim cycle
```

Set `ZCODE_AUTO_CLAIM=true` in `.env` and restart the service. `ZCODE_AUTO_CLAIM_INTERVAL_MS` defaults to `300000` (five minutes), with a one-minute minimum. Docker Compose forwards both settings; recreate the service after changing them.
Both commands persist discovery diagnostics in the encrypted vault. Authenticated `/api/usage` and `/api/plans` expose `accounts[].autoClaim`, including `sources`, `offers`, sanitized `campaigns`, claim results, grant expiry and retry times. `idle` means both channels were read successfully, including empty results; `discovery_partial` means a source was unavailable; `discovery_failed` means neither succeeded. Success codes without required payloads report `missing_data` instead of pretending discovery was complete.

The worker refreshes entitlements and checks provider previews at startup and periodically without inbound HTTP traffic. It considers unexpired model grants without payment fields, skips subscription accounts and accounts requiring login, and never purchases a paid plan. Successful claims and retry holds are persisted in the encrypted vault. Claims already held for the same period are skipped; a later period can reuse the same plan ID. Future activation does not prevent claiming, but model discovery waits for entitlement activation.
HTTP and provider error codes are checked separately, including numeric string codes and plain-text HTTP errors. `Retry-After` is honored. CAPTCHA, risk-control and login failures stop further claims for that account. The worker does not bypass verification, buy plans, open campaign links or send invitations.

Authenticated `/api/usage` and `/api/plans` expose per-account `autoClaim` status. An empty preview produces `idle`. Required or unknown CAPTCHA verification requires manual action, as does reauthorization. Availability and eligibility remain provider-controlled; a `one_time` grant does not promise daily refills.
Coverage is limited to the two verified official offer channels. Referral, payment or manual eligibility conditions remain provider-controlled. Unknown future endpoints are not automatically supported. A `daily` entitlement period does not guarantee a new offer every day, and a `one_time` grant does not promise refills.

Model discovery refreshes before publishing the catalog or rejecting a missing model. During account cooldown, rate-limit failures retain their upstream status and safe error reason with `Retry-After` instead of becoming a generic no-account error.

Expand Down
40 changes: 32 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

Pakai model dari akun ZCode Anda di OmniRoute atau aplikasi yang mendukung API OpenAI dan Anthropic. Anda bisa menambahkan beberapa akun, melihat sisa kuota, dan memilih paket untuk tiap akun.

Sudah diuji dengan ZCode **3.16.3**, **GLM-5.3**, dan **GLM-5.3-Flash**. Proyek ini dibuat secara independen. Jika ZCode mengubah layanannya, integrasi ini mungkin perlu diperbarui.
Diperbarui untuk format klien ZCode **3.17.2**: template, versi request, billing, serta penawaran promo dan kampanye. Ekstraksi juga diperiksa pada **3.17.1**. Hasil dan batas uji langsung tercatat di [catatan pengujian](docs/verification.md). Proyek ini dibuat secara independen; perubahan layanan ZCode bisa memerlukan pembaruan integrasi.

## Mulai dari sini

Expand Down Expand Up @@ -46,7 +46,15 @@ node --env-file=.env src/cli.ts provision "C:/Program Files/ZCode/resources/glm/

Ganti lokasi file jika ZCode Anda terpasang di folder lain. Untuk sistem lain, gunakan lokasi `resources/glm/zcode.cjs` dari instalasi ZCode Anda.

Perintah ini membuat `data/template.json` dari aplikasi ZCode yang terpasang. File ini diperlukan agar request bisa dikirim ke ZCode. Instalasi ZCode Anda tetap seperti semula.
Perintah ini membuat `data/template.json` dari aplikasi ZCode yang terpasang. Versi klien dibaca dari metadata aplikasi; header login, billing, klaim, dan inferensi memakai versi tersebut. Instalasi ZCode Anda tetap seperti semula. Jalankan `provision` lagi setelah memperbarui aplikasi.

Jika hanya menyalin `zcode.cjs` tanpa metadata aplikasi, sertakan versi asalnya secara eksplisit:

```sh
node --env-file=.env src/cli.ts provision /lokasi/zcode.cjs --app-version 3.17.2
```

Template lama versi 3.16.3 tetap dapat dibaca. Ekstraktor akan menolak struktur prompt yang belum dikenali; tidak ada jaminan kompatibilitas dengan rilis yang belum diuji.

### 4. Tambahkan akun

Expand Down Expand Up @@ -129,22 +137,38 @@ Ganti `ACCOUNT_ID` dengan ID dari perintah `accounts`. Menghapus akun di sini ti

Request dibagi bergiliran ke akun aktif yang mendukung model tersebut. Setiap akun menangani satu request pada satu waktu. Jika satu akun gagal sebelum jawaban mulai dikirim, ZCode Gateway dapat mencoba akun lain.

## Klaim otomatis paket gratis
## Promo dan event otomatis

Klaim otomatis dapat diaktifkan untuk akun Start Plan yang terhubung dengan menambahkan pengaturan berikut ke `.env`, lalu memulai ulang layanan:
Pemeriksaan dan klaim grant gratis **aktif secara default** ketika `serve` berjalan. Gateway memeriksa saat mulai dan setiap lima menit, termasuk ketika tidak ada request API. Pengaturannya:

```dotenv
ZCODE_AUTO_CLAIM=true
ZCODE_AUTO_CLAIM_INTERVAL_MS=300000
```

Gateway memeriksa penawaran saat mulai dan setiap lima menit, tanpa menunggu request masuk. Interval minimum adalah satu menit. Untuk Docker Compose, jalankan ulang `docker compose up -d` setelah mengubah pengaturan.
Interval minimum satu menit. Isi `ZCODE_AUTO_CLAIM=false` untuk mematikannya. Nilai `false` yang sudah ada tetap dihormati. Restart layanan setelah mengubah `.env`; pada Docker, jalankan `docker compose up -d` untuk menerapkan pengaturan.

Dua sumber resmi dibaca untuk setiap akun Start Plan aktif:

- **Billing preview**: grant model yang ditawarkan akun, belum kedaluwarsa, dan tidak mencantumkan biaya.
- **Marketing touch**: kampanye banner dan popup dengan aksi eksplisit `claim_zcode_plan`. Nama event dan ID paket berasal dari respons provider; tidak dikunci ke daftar promo tertentu.

Penawaran yang sama dari dua sumber hanya diproses sekali. Masa berlaku dari respons klaim disimpan agar preview tanpa tanggal tidak menghalangi klaim periode berikutnya. Setelah klaim, model dan kuota diperbarui dari **billing balance**, pengganti endpoint `billing/current` yang sudah tidak dipakai klien terbaru. Model menunggu waktu aktivasi entitlement.

Untuk memeriksa tanpa mengklaim atau menjalankan satu siklus klaim, hentikan `serve` terlebih dahulu:

```sh
node --env-file=.env src/cli.ts promos
node --env-file=.env src/cli.ts claim
```

`promos` hanya melakukan discovery; `claim` mencoba grant gratis yang ditawarkan. Keduanya menyimpan status pemeriksaan di vault. Akun yang dinonaktifkan, perlu login ulang, atau memakai route Coding Plan dilewati.

Hanya paket grant model yang ditawarkan endpoint preview, belum kedaluwarsa, dan tidak mencantumkan biaya yang diproses. Langganan berbayar tidak dibeli. Paket yang aktif pada periode yang sama serta klaim yang sudah berhasil tidak diulang; paket periode berikutnya tetap diperiksa meskipun ID-nya sama. Paket boleh diklaim sebelum waktu aktivasinya, tetapi model baru tersedia setelah entitlement aktif.
Respons berautentikasi `/api/usage` dan `/api/plans` memuat `accounts[].autoClaim`: `sources`, `offers`, ringkasan `campaigns`, hasil klaim, masa berlaku, dan waktu retry. `idle` berarti kedua kanal berhasil dibaca; `discovery_partial` berarti hanya sebagian sumber tersedia, sedangkan `discovery_failed` berarti discovery gagal. Kode sukses tanpa payload diberi alasan `missing_data`, bukan dianggap bukti bahwa seluruh promo kosong. Daftar kosong dapat tetap menghasilkan `idle`.

Status per akun tersedia pada `autoClaim` di respons berautentikasi `/api/usage` atau `/api/plans`. Jika penawaran kosong, statusnya `idle`. CAPTCHA atau login ulang yang diwajibkan provider memerlukan tindakan manual. Fitur ini tidak menjamin ada penawaran setiap hari; paket berperiode `one_time` tidak menjanjikan isi ulang kuota harian.
Rate limit mengikuti `Retry-After`. Respons CAPTCHA, login ulang, atau pembatasan risiko menghentikan klaim berikutnya pada akun itu dan menyimpan status tindakan yang diperlukan. Tidak ada pemecahan CAPTCHA, pembelian langganan, pembukaan tautan promosi, atau pengiriman undangan otomatis.

Daftar model juga disegarkan sebelum katalog ditampilkan dan sebelum model yang belum tercatat ditolak. Jika provider menolak request dengan rate limit, gateway mempertahankan penyebab penolakan serta header `Retry-After` selama masa jeda akun.
**Cakupan otomatis mengikuti kanal dan izin yang disediakan ZCode.** Event dengan syarat referral, pembelian, atau tindakan manual tetap membutuhkan syarat tersebut. Promo dari kanal lain atau endpoint baru tidak dijamin terambil. Label `daily` menunjukkan periode entitlement provider; gateway tidak membuat kuota baru dan tidak menjamin promo tersedia setiap hari.

## Ganti paket yang dipakai

Expand Down
2 changes: 1 addition & 1 deletion compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ services:
environment:
ZCODE_MASTER_KEY: ${ZCODE_MASTER_KEY:?set master key}
ZCODE_API_KEYS: ${ZCODE_API_KEYS:?set client keys}
ZCODE_AUTO_CLAIM: ${ZCODE_AUTO_CLAIM:-false}
ZCODE_AUTO_CLAIM: ${ZCODE_AUTO_CLAIM:-true}
ZCODE_AUTO_CLAIM_INTERVAL_MS: ${ZCODE_AUTO_CLAIM_INTERVAL_MS:-300000}
volumes:
- ./data:/data
Expand Down
17 changes: 17 additions & 0 deletions docs/updates/2026-11-07-compatibility.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# ZCode 3.17 compatibility and automatic offers

Scope: update the existing gateway for the official 3.17.2 client and automatically process provider-offered free grants. Keep Node 24.14+, the encrypted vault, existing protocols and legacy templates. No paid purchases, fabricated eligibility, referral creation or verification bypass.

Evidence: official release v3.17.2, source commit a9fe401eede6e6e5e01be9048679c206fe6f02d9. The Windows release archive matches its published SHA256SUMS. The client uses billing preview/claim and marketing/touch; the old agent/configs CAPTCHA preflight is absent from the current claim flow. Preview grants may omit dates. Claim responses contain the actual grant period. Marketing buttons explicitly distinguish claim_zcode_plan from navigation and external URLs.

Implementation plan:

- [x] Add failing tests for modern template extraction, metadata version discovery and propagation to billing.
- [x] Read the app version from adjacent package metadata/ASAR (or explicit provision argument); extract modern prompt sections without depending on minified symbol names. Preserve legacy extraction and templates.
- [x] Add failing tests for marketing claims, repeated undated offers, grant expiry, HTTP errors, numeric string codes, per-source failures and server time.
- [x] Query billing preview and marketing touch independently. Merge only explicit claim actions and free model grants. Persist real claim expiry, provider retry holds and bounded diagnostic summaries. Refresh entitlements after claims. Stop on login/risk/verification requirements.
- [x] Expose authenticated offer status and add a one-shot claims CLI. Enable automatic claims for new installations, preserving an explicit false opt-out.
- [x] Run all tests and syntax checks, provision from the verified 3.17.2 archive, then perform available authenticated live checks without publishing credentials.
- [x] Update both guides, release notes and CI; publish the verified branch as a pull request and provide a source archive and patch.

Coverage limit: automatically handles the two verified official offer channels. Invitations, paid plans, CAPTCHA, eligibility requirements and future unknown endpoints remain provider-controlled. An empty preview is not proof that no other promotion exists.
Loading
Loading