coze_lab 0.1.44 → 0.1.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,57 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- CozeLoop token refresh hook — runs at SessionStart.
4
- Checks credentials.json and refreshes the token if expiring soon.
5
- Writes the fresh token back so subsequent Stop hooks pick it up.
6
- """
7
- import json, os, sys, time, urllib.request
8
- from pathlib import Path
9
-
10
- CLIENT_ID = "08972682140163281554629748278108.app.coze"
11
- COZE_API = "https://api.coze.cn"
12
- THRESHOLD = 10 * 60 # 10 minutes
13
- CREDS = Path.home() / ".cozeloop" / "credentials.json"
14
-
15
- def load():
16
- try: return json.loads(CREDS.read_text())
17
- except: return None
18
-
19
- def save(c):
20
- CREDS.parent.mkdir(parents=True, exist_ok=True)
21
- CREDS.write_text(json.dumps(c, indent=2))
22
- os.chmod(CREDS, 0o600)
23
-
24
- def refresh(rt):
25
- try:
26
- body = json.dumps({"grant_type":"refresh_token","client_id":CLIENT_ID,"refresh_token":rt}).encode()
27
- req = urllib.request.Request(f"{COZE_API}/api/permission/oauth2/token",
28
- data=body, headers={
29
- "Content-Type":"application/json",
30
- })
31
- with urllib.request.urlopen(req, timeout=10) as r:
32
- d = json.loads(r.read())
33
- if d.get("access_token"):
34
- existing = load() or {}
35
- save({"access_token":d["access_token"],
36
- "refresh_token":d.get("refresh_token",rt),
37
- "expires_at":d.get("expires_in",0)*1000,
38
- "workspace_id":existing.get("workspace_id","")})
39
- return True
40
- except Exception as e:
41
- print(f"[cozeloop_refresh] refresh failed: {e}", file=sys.stderr)
42
- return False
43
-
44
- def main():
45
- creds = load()
46
- if not creds: return
47
- # expires_at 由 index.js 以毫秒存储;先减去当前毫秒时间再换算成秒,与 THRESHOLD(秒) 比较。
48
- remaining = (creds.get("expires_at",0) - time.time()*1000)/1000
49
- if remaining > THRESHOLD: return # still fresh
50
- print(f"[cozeloop_refresh] token expiring in {int(remaining)}s, refreshing...", file=sys.stderr)
51
- if creds.get("refresh_token"):
52
- if refresh(creds["refresh_token"]):
53
- print("[cozeloop_refresh] token refreshed OK", file=sys.stderr)
54
- else:
55
- print("[cozeloop_refresh] refresh failed, token may expire soon", file=sys.stderr)
56
-
57
- main()