Skip to content
Open
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
7 changes: 4 additions & 3 deletions generator/captcha_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,11 +225,12 @@ def _need_ocr(self):
Returns None (and logs) when ddddocr is missing instead of raising
out of calculate().
"""
if self.ocr is None and self._ocr_factory is not None:
self.ocr = self._ocr_factory()
if self.ocr is None:
try:
return self._get_ocr()
# the factory IS _get_ocr in production: its RuntimeError
# must not escape only because it arrived via the factory
self.ocr = (self._ocr_factory() if self._ocr_factory is not None
else self._get_ocr())
except RuntimeError as e:
self.logger.warning(str(e))
return None
Expand Down
3 changes: 2 additions & 1 deletion generator/claim500.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

from invite_claim import ( # noqa: E402
_VERIFY,
client_timezone,
device_login,
per_account_device_mid,
_proxies,
Expand All @@ -51,7 +52,6 @@
'http-referer': 'https://zcode.z.ai',
'user-agent': 'ZCode/3.18.0',
'x-client-language': 'en-US',
'x-client-timezone': 'Asia/Tehran',
'x-os-category': 'windows',
'x-os-version': 'Windows 11 Pro',
'x-platform': 'win32-x64',
Expand Down Expand Up @@ -111,6 +111,7 @@ def _headers(zjwt: str) -> dict:
h = dict(CLAIM_HEADERS_BASE)
h['authorization'] = 'Bearer ' + zjwt
h['x-device-mid'] = per_account_device_mid(zjwt)
h['x-client-timezone'] = client_timezone()
h['x-request-id'] = str(__import__('uuid').uuid4())
return h

Expand Down
87 changes: 47 additions & 40 deletions generator/export_starter.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import sys

from plan_check import get_zcode_jwt, get_plan, is_start_plan, DEVICE_MID
import plan_check

HERE = os.path.dirname(os.path.abspath(__file__))
# destination for exported snapshots; override per machine (or copy the
Expand Down Expand Up @@ -99,48 +100,54 @@ def main():
print(f"candidate accounts: {len(accounts)}")
os.makedirs(GATEWAY_ACCOUNTS, exist_ok=True)
exported = 0
failed = 0
for email, chat_token in accounts:
print(f"\n=== {email} ===")
zjwt = get_zcode_jwt(chat_token, log=lambda *a: print(' ', *a))
if not zjwt:
print(" no zcodeJWT — skip")
continue
plan = get_plan(zjwt)
if not plan:
print(" no plan data — skip")
continue
starter = plan.get('starter')
referral = plan.get('referral')
print(f" plans={plan.get('plans')} starter={starter} referral={referral}")
if not (starter or referral or export_all):
continue
payload = jwt_payload(zjwt)
ident = payload.get('user_id') or payload.get('sub') or email
plans_list = plan.get('plans') or []
chosen_plan = next((p for p in plans_list if is_start_plan(p)),
plans_list[0] if plans_list else '')
fields = {
'captured_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'source': 'ZCODEAUTO chat.z.ai signup (OAuth CLI)',
'account_id': ident,
'email': email,
'name': '',
'device_mid': DEVICE_MID,
'plan': chosen_plan,
'access_token': zjwt,
}
if payload.get('exp'):
fields['expires_at'] = str(payload['exp'])
fields['expires_at_ms'] = str(int(payload['exp']) * 1000)
else:
fields['expires_at_ms'] = '0'
# drop empty values so the file matches ZcodeGate's own output exactly
fields = {k: v for k, v in fields.items() if v != ''}
dest = os.path.join(GATEWAY_ACCOUNTS, safe_name(email))
write_snapshot(dest, fields)
exported += 1
print(f" -> wrote {dest}")
print(f"\nexported {exported} account(s) to {GATEWAY_ACCOUNTS}")
try:
zjwt = get_zcode_jwt(chat_token, log=lambda *a: print(' ', *a))
if not zjwt:
print(" no zcodeJWT — skip")
continue
plan = get_plan(zjwt)
if not plan:
print(" no plan data — skip")
continue
starter = plan.get('starter')
referral = plan.get('referral')
print(f" plans={plan.get('plans')} starter={starter} referral={referral}")
if not (starter or referral or export_all):
continue
payload = jwt_payload(zjwt)
ident = payload.get('user_id') or payload.get('sub') or email
plans_list = plan.get('plans') or []
chosen_plan = next((p for p in plans_list if is_start_plan(p)),
plans_list[0] if plans_list else '')
fields = {
'captured_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'source': 'ZCODEAUTO chat.z.ai signup (OAuth CLI)',
'account_id': ident,
'email': email,
'name': '',
'device_mid': plan_check.per_account_device_mid(zjwt) or DEVICE_MID,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Derive the device id from chat_token, not zjwt. zjwt is re-minted on every run, so a re-export gives the account a new device_mid. The or DEVICE_MID fallback is also unreachable, since per_account_device_mid never returns an empty string.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/export_starter.py, line 131:

<comment>Derive the device id from `chat_token`, not `zjwt`. `zjwt` is re-minted on every run, so a re-export gives the account a new `device_mid`. The `or DEVICE_MID` fallback is also unreachable, since `per_account_device_mid` never returns an empty string.</comment>

<file context>
@@ -99,48 +100,54 @@ def main():
+                'account_id': ident,
+                'email': email,
+                'name': '',
+                'device_mid': plan_check.per_account_device_mid(zjwt) or DEVICE_MID,
+                'plan': chosen_plan,
+                'access_token': zjwt,
</file context>
Suggested change
'device_mid': plan_check.per_account_device_mid(zjwt) or DEVICE_MID,
'device_mid': plan_check.per_account_device_mid(chat_token),

'plan': chosen_plan,
'access_token': zjwt,
}
if payload.get('exp'):
fields['expires_at'] = str(payload['exp'])
fields['expires_at_ms'] = str(int(payload['exp']) * 1000)
else:
fields['expires_at_ms'] = '0'
# drop empty values so the file matches ZcodeGate's own output exactly
fields = {k: v for k, v in fields.items() if v != ''}
dest = os.path.join(GATEWAY_ACCOUNTS, safe_name(email))
write_snapshot(dest, fields)
exported += 1
print(f" -> wrote {dest}")
except Exception as e:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The exit status ignores failed, so a run where every account errors still exits 0. Exit non-zero when failed is set so callers and pipelines can detect the failure.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/export_starter.py, line 146:

<comment>The exit status ignores `failed`, so a run where every account errors still exits 0. Exit non-zero when `failed` is set so callers and pipelines can detect the failure.</comment>

<file context>
@@ -99,48 +100,54 @@ def main():
+            write_snapshot(dest, fields)
+            exported += 1
+            print(f"    -> wrote {dest}")
+        except Exception as e:
+            failed += 1
+            print(f"    failed ({type(e).__name__}: {e}) — skip")
</file context>

failed += 1
print(f" failed ({type(e).__name__}: {e}) — skip")
print(f"\nexported {exported} account(s) to {GATEWAY_ACCOUNTS}"
+ (f" ({failed} failed)" if failed else ""))


if __name__ == '__main__':
Expand Down
49 changes: 35 additions & 14 deletions generator/invite_claim.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
sys.stderr.reconfigure(encoding='utf-8', errors='replace')

from utils import BROWSER_ARGS
from plan_check import APP_VERSION, _request, direct_requests
from plan_check import APP_VERSION, _request, client_timezone, direct_requests

# NOTE: playwright is imported lazily inside claim_invite(). The referral
# helpers below (referral_summary / send_one_message) are imported by the
Expand Down Expand Up @@ -502,6 +502,27 @@ def _proxies():
return {'http': raw, 'https': raw}


def _pw_proxy(proxy_url):
"""Playwright proxy dict for `proxy_url`, or None for a direct connection.

A portless value (socks5://1.2.3.4) would otherwise become
"socks5://1.2.3.4:None" and Chromium refuses to launch — same guard as
main.pw_proxy(). Credentials travel as separate fields: Chromium drops
them from 'server' alone and then shows an auth popup.
"""
if not proxy_url:
return None
from urllib.parse import urlparse
u = urlparse(proxy_url)
if not u.hostname or not u.port:
return None
d = {'server': f"{u.scheme or 'http'}://{u.hostname}:{u.port}"}
if u.username:
d['username'] = u.username
d['password'] = u.password or ''
return d


def _direct_proxy_while(fn):
"""Run `fn` with direct mode when force_direct=True; always restore."""
import functools
Expand Down Expand Up @@ -539,7 +560,6 @@ def per_account_device_mid(token: str) -> str:
'http-referer': 'https://zcode.z.ai',
'user-agent': 'ZCode/' + APP_VERSION,
'x-client-language': 'en-US',
'x-client-timezone': 'Asia/Tehran',
'x-device-mid': '58aca3b3-3239-4cb7-9c70-df3e5488fb99',
'x-os-category': 'windows',
'x-os-version': '10.0.26200',
Expand Down Expand Up @@ -577,12 +597,15 @@ def report_login_device(zjwt: str, user_id: str = None, device_mid: str = None,
mid = device_mid or per_account_device_mid(zjwt)
h = dict(APP_HEADERS)
h['authorization'] = 'Bearer ' + zjwt
h['x-client-timezone'] = client_timezone()
if mid:
h['x-device-mid'] = mid

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: device_login uses a chat-token device ID for OAuth but report_login_device now uses a zcode-JWT device ID, so one login reports two device IDs. Pass the OAuth mid as device_mid=mid to report_login_device.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/invite_claim.py, line 602:

<comment>`device_login` uses a chat-token device ID for OAuth but `report_login_device` now uses a zcode-JWT device ID, so one login reports two device IDs. Pass the OAuth `mid` as `device_mid=mid` to `report_login_device`.</comment>

<file context>
@@ -577,12 +597,15 @@ def report_login_device(zjwt: str, user_id: str = None, device_mid: str = None,
     h['authorization'] = 'Bearer ' + zjwt
+    h['x-client-timezone'] = client_timezone()
+    if mid:
+        h['x-device-mid'] = mid
     endpoint = 'https://zcode.z.ai/api/v1/event/report'
 
</file context>

endpoint = 'https://zcode.z.ai/api/v1/event/report'

# 1. app_login_ck
body_ck = {
'event_id': str(_uuid.uuid4()),
'client_timezone': 'Asia/Tehran',
'client_timezone': client_timezone(),
'client_language': 'en-US',
'element_name': 'app_login_ck',
'event_region': 'app',
Expand All @@ -608,7 +631,7 @@ def report_login_device(zjwt: str, user_id: str = None, device_mid: str = None,
# 2. app_login_success (the critical event that credits login_device)
body_success = {
'event_id': str(_uuid.uuid4()),
'client_timezone': 'Asia/Tehran',
'client_timezone': client_timezone(),
'client_language': 'en-US',
'element_name': 'app_login_success',
'event_region': 'app_profile',
Expand Down Expand Up @@ -667,6 +690,10 @@ def device_login(chat_token, log=print, force_direct: bool = False):
poll_token = secrets.token_hex(32)
h = dict(APP_HEADERS)
h['authorization'] = 'Bearer ' + poll_token
h['x-client-timezone'] = client_timezone()
mid = per_account_device_mid(chat_token)
if mid:
h['x-device-mid'] = mid
# zcode.z.ai answers 502 in bursts; init is idempotent (it just opens a
# new flow), so a few quick retries beat aborting the whole login
r = None
Expand Down Expand Up @@ -848,19 +875,13 @@ def claim_invite(chat_token: str, invite_code: str = 'MT9GNDQ8', log=print,
viewport={'width': 1280, 'height': 820}, user_agent=UA,
locale='en-US', timezone_id='America/New_York')
_px = _proxies()
if _px and _px.get('https'):
# embedded credentials (http://user:pass@host:port) must be split
# into separate fields — Chromium drops them from 'server' alone
# and then shows an auth popup (net::ERR_INVALID_AUTH_CREDENTIALS)
from urllib.parse import urlparse
_u = urlparse(_px['https'])
_pd = {'server': f"{_u.scheme or 'http'}://{_u.hostname}:{_u.port}"}
if _u.username:
_pd['username'] = _u.username
_pd['password'] = _u.password or ''
_pd = _pw_proxy((_px or {}).get('https'))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Rejecting a portless proxy launches Chromium directly but still fingerprints it with that proxy URL. Pass only the validated _pd proxy URL to make_identity, or pass None whenever _pw_proxy rejects the configured proxy.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/invite_claim.py, line 878:

<comment>Rejecting a portless proxy launches Chromium directly but still fingerprints it with that proxy URL. Pass only the validated `_pd` proxy URL to `make_identity`, or pass `None` whenever `_pw_proxy` rejects the configured proxy.</comment>

<file context>
@@ -848,19 +875,13 @@ def claim_invite(chat_token: str, invite_code: str = 'MT9GNDQ8', log=print,
-            if _u.username:
-                _pd['username'] = _u.username
-                _pd['password'] = _u.password or ''
+        _pd = _pw_proxy((_px or {}).get('https'))
+        if _pd:
             launch_kwargs['proxy'] = _pd
</file context>

if _pd:
launch_kwargs['proxy'] = _pd
elif force_direct:
log(' invite: direct mode — claiming on the real IP')
elif _px and _px.get('https'):
log(' invite: proxy has no host:port — launching direct')
Comment on lines +883 to +884

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: When a proxy is configured but has no host:port, the browser claim now launches on the real IP instead of failing. Raise an error here so the claim aborts rather than leaking the home IP.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/invite_claim.py, line 883:

<comment>When a proxy is configured but has no host:port, the browser claim now launches on the real IP instead of failing. Raise an error here so the claim aborts rather than leaking the home IP.</comment>

<file context>
@@ -848,19 +875,13 @@ def claim_invite(chat_token: str, invite_code: str = 'MT9GNDQ8', log=print,
             launch_kwargs['proxy'] = _pd
         elif force_direct:
             log('  invite: direct mode — claiming on the real IP')
+        elif _px and _px.get('https'):
+            log('  invite: proxy has no host:port — launching direct')
 
</file context>
Suggested change
elif _px and _px.get('https'):
log(' invite: proxy has no host:port — launching direct')
elif _px and _px.get('https'):
raise RuntimeError('invite: proxy has no host:port — refusing to claim on the real IP')


import fingerprint as _fp
_px_url = (_px or {}).get('https')
Expand Down
2 changes: 1 addition & 1 deletion generator/plan_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ def _plan_events(zjwt):
pass
mid = per_account_device_mid(zjwt)
base = {
"client_timezone": "Asia/Tehran",
"client_timezone": client_timezone(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: client_timezone() caches one timezone for the whole generator process, so later accounts can report the first account’s proxy timezone after set_proxy rotates exits. Key the cache by the active proxy/override or resolve the timezone per account.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/plan_check.py, line 499:

<comment>`client_timezone()` caches one timezone for the whole generator process, so later accounts can report the first account’s proxy timezone after `set_proxy` rotates exits. Key the cache by the active proxy/override or resolve the timezone per account.</comment>

<file context>
@@ -496,7 +496,7 @@ def _plan_events(zjwt):
     mid = per_account_device_mid(zjwt)
     base = {
-        "client_timezone": "Asia/Tehran",
+        "client_timezone": client_timezone(),
         "client_language": "en-US",
         "event_text": "",
</file context>

"client_language": "en-US",
"event_text": "",
"user_id": jwt_user_id(zjwt),
Expand Down
7 changes: 6 additions & 1 deletion generator/proxy_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,13 @@ def _is_private_octets(parts: list[int]) -> bool:
def valid_endpoint(host: str, port: int) -> bool:
if not (0 < port < 65536):
return False
octets = host.split(".")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The new leading-zero check is ASCII-only, so fullwidth digits still bypass the loopback and link-local guards. PROXY_RE matches Unicode \d, int() accepts those digits, and getaddrinfo normalizes them to ASCII. Reject non-ASCII hosts before splitting so valid_endpoint only accepts plain dotted quads.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/proxy_parse.py, line 83:

<comment>The new leading-zero check is ASCII-only, so fullwidth digits still bypass the loopback and link-local guards. `PROXY_RE` matches Unicode `\d`, `int()` accepts those digits, and `getaddrinfo` normalizes them to ASCII. Reject non-ASCII hosts before splitting so `valid_endpoint` only accepts plain dotted quads.</comment>

<file context>
@@ -80,8 +80,13 @@ def _is_private_octets(parts: list[int]) -> bool:
 def valid_endpoint(host: str, port: int) -> bool:
     if not (0 < port < 65536):
         return False
+    octets = host.split(".")
+    # getaddrinfo/inet_aton read a leading zero as octal ("0177" == 127), so a
+    # dotted quad like 0177.0.0.1 would slip past the loopback check below
</file context>
Suggested change
octets = host.split(".")
if not host.isascii():
return False
octets = host.split(".")

# getaddrinfo/inet_aton read a leading zero as octal ("0177" == 127), so a
# dotted quad like 0177.0.0.1 would slip past the loopback check below
if any(len(o) > 1 and o.startswith("0") for o in octets):
return False
try:
parts = [int(o) for o in host.split(".")]
parts = [int(o) for o in octets]
except ValueError:
return False
if len(parts) != 4 or any(p > 255 for p in parts):
Expand Down
69 changes: 39 additions & 30 deletions generator/recheck_plans.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,42 +96,51 @@ def main():
log = lambda m: print(m, flush=True)

got = 0
failed = 0
for n, (email, _password, token) in enumerate(rows, 1):
log(f"[{n}/{len(rows)}] {email}")
zjwt = get_zcode_jwt(token, log=lambda *a, **k: None)
if not zjwt:
log(' login failed')
record = {'email': email, 'plans': None, 'error': 'login'}
else:
plan = get_plan(zjwt, log=lambda *a, **k: None) or {}
ids = plan.get('plans') or []
if not ids and escalate:
log(' no plan — escalating to the full desktop device_login')
try:
from invite_claim import device_login
zjwt2, _ = device_login(token, log=lambda *a, **k: None)
if zjwt2:
zjwt = zjwt2
time.sleep(2)
plan = get_plan(zjwt, log=lambda *a, **k: None) or {}
ids = plan.get('plans') or []
except Exception as e:
log(f' escalate failed ({type(e).__name__}: {e})')
has_start = any(is_start_plan(p) for p in ids)
got += 1 if has_start else 0
record = {'email': email, 'plans': ids, 'starter': has_start,
'referral': plan.get('referral'),
'campaign': plan.get('campaign'),
'entitlements': plan.get('entitlements'),
'ts': int(time.time())}
if has_start:
with open(startplan_path, 'a', encoding='utf-8') as f:
f.write(f"{email}:{_password}:{token}\n")
log(f" -> {ids}")
try:
zjwt = get_zcode_jwt(token, log=lambda *a, **k: None)
if not zjwt:
log(' login failed')
record = {'email': email, 'plans': None, 'error': 'login'}
else:
plan = get_plan(zjwt, log=lambda *a, **k: None) or {}
ids = plan.get('plans') or []
if not ids and escalate:
log(' no plan — escalating to the full desktop device_login')
try:
from invite_claim import device_login
zjwt2, _ = device_login(token, log=lambda *a, **k: None)
if zjwt2:
zjwt = zjwt2
time.sleep(2)
plan = get_plan(zjwt, log=lambda *a, **k: None) or {}
ids = plan.get('plans') or []
except Exception as e:
log(f' escalate failed ({type(e).__name__}: {e})')
has_start = any(is_start_plan(p) for p in ids)
got += 1 if has_start else 0
record = {'email': email, 'plans': ids, 'starter': has_start,
'referral': plan.get('referral'),
'campaign': plan.get('campaign'),
'entitlements': plan.get('entitlements'),
'ts': int(time.time())}
if has_start:
with open(startplan_path, 'a', encoding='utf-8') as f:
f.write(f"{email}:{_password}:{token}\n")
Comment on lines +129 to +131

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A failed startplan.txt append is caught by the new outer except, so a confirmed Start Plan account is recorded as an error and dropped from startplan.txt. Guard only the append so a write failure is logged without replacing the successful record.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At generator/recheck_plans.py, line 129:

<comment>A failed `startplan.txt` append is caught by the new outer `except`, so a confirmed Start Plan account is recorded as an error and dropped from `startplan.txt`. Guard only the append so a write failure is logged without replacing the successful record.</comment>

<file context>
@@ -96,42 +96,51 @@ def main():
+                          'campaign': plan.get('campaign'),
+                          'entitlements': plan.get('entitlements'),
+                          'ts': int(time.time())}
+                if has_start:
+                    with open(startplan_path, 'a', encoding='utf-8') as f:
+                        f.write(f"{email}:{_password}:{token}\n")
</file context>
Suggested change
if has_start:
with open(startplan_path, 'a', encoding='utf-8') as f:
f.write(f"{email}:{_password}:{token}\n")
if has_start:
try:
with open(startplan_path, 'a', encoding='utf-8') as f:
f.write(f"{email}:{_password}:{token}\n")
except OSError as e:
log(f' startplan write failed ({e})')

log(f" -> {ids}")
except Exception as e:
failed += 1
log(f' failed ({type(e).__name__}: {e})')
record = {'email': email, 'plans': None,
'error': f'{type(e).__name__}: {e}'}
with open(plans_path, 'a', encoding='utf-8') as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")

log(f"\n{got}/{len(rows)} accounts currently hold a Start Plan")
if failed:
log(f"{failed} account(s) failed — see the error field in {plans_path}")
log(f"ledger: {plans_path}")
return 0

Expand Down
6 changes: 6 additions & 0 deletions scripts/smoke/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ async def run(args):
if args.infer:
with tempfile.TemporaryDirectory() as folder:
store = Store(str(Path(folder) / 'smoke.db'))
service = None
try:
service = ChatService(cfg, pool, tokens, client, Registry(), store, JsonlCapture(folder, False))
model = 'GLM-5.3-Flash'
Expand All @@ -43,6 +44,11 @@ async def run(args):
message = json.loads(result.raw)
print('Live inference OK:', message['stop_reason'], json.dumps(message['usage']))
finally:
if service is not None:
# complete() returns before the usage record lands in
# the store's executor; draining it first avoids a
# silent write-after-close
await service.aclose()
store.close()
return 0
except Exception as exc:
Expand Down
Loading