scope-agent-workbench 0.2.0 → 0.2.3

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.
Files changed (88) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/bridge/agent-email-relay.mjs +160 -160
  3. package/bridge/app-server-websocket-transport.mjs +219 -219
  4. package/bridge/archive/service.mjs +130 -130
  5. package/bridge/auth-profile-failover.mjs +58 -58
  6. package/bridge/auth-profile-manager.mjs +215 -215
  7. package/bridge/capacity-recovery.mjs +90 -90
  8. package/bridge/gpu-usage-history.mjs +322 -322
  9. package/bridge/local/history.mjs +20 -5
  10. package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -236
  11. package/bridge/plugins/aliyun-dlc/probe.mjs +701 -701
  12. package/bridge/private-gateway.mjs +371 -371
  13. package/bridge/private-start.mjs +22 -22
  14. package/bridge/probes/app-server-handoff-probe.mjs +87 -87
  15. package/bridge/probes/app-server-writer-probe.mjs +69 -69
  16. package/bridge/probes/assistant-search-probe.mjs +321 -321
  17. package/bridge/probes/dialogue-probe.mjs +462 -462
  18. package/bridge/probes/history-probe.mjs +430 -345
  19. package/bridge/probes/new-session-preflight.mjs +14 -14
  20. package/bridge/probes/profile-cancel-probe.mjs +17 -17
  21. package/bridge/probes/profile-delete-probe.mjs +26 -26
  22. package/bridge/probes/profile-list-probe.mjs +114 -114
  23. package/bridge/probes/profile-write-probe.mjs +109 -109
  24. package/bridge/probes/raw-context-probe.mjs +51 -51
  25. package/bridge/probes/remote-probe.mjs +627 -626
  26. package/bridge/probes/submission-probe.mjs +2 -2
  27. package/bridge/probes/takeover-probe.mjs +326 -326
  28. package/bridge/probes/vscode-open-preflight.mjs +21 -21
  29. package/bridge/providers/claude-interactive.py +463 -341
  30. package/bridge/providers/cli-command.mjs +103 -103
  31. package/bridge/providers/conversations.mjs +231 -231
  32. package/bridge/providers/native-commands.py +38 -38
  33. package/bridge/providers/native-session-state.mjs +14 -14
  34. package/bridge/providers/native-session-state.py +96 -96
  35. package/bridge/providers/remote-job.py +130 -130
  36. package/bridge/remote-app-server-command.mjs +121 -121
  37. package/bridge/remote-directory-listing.mjs +148 -148
  38. package/bridge/rollout-summary.mjs +20 -2
  39. package/bridge/routes/dialogue.mjs +48 -3
  40. package/bridge/routes/models.mjs +312 -312
  41. package/bridge/server.mjs +3357 -3332
  42. package/bridge/session-attachments.mjs +150 -150
  43. package/bridge/session-catalog/agy-history.py +141 -2
  44. package/bridge/session-catalog/catalog.mjs +17 -0
  45. package/bridge/session-catalog/probe.py +1207 -331
  46. package/bridge/session-catalog/routes.mjs +6 -0
  47. package/bridge/start.mjs +205 -205
  48. package/bridge/state-persistence.mjs +9 -1
  49. package/bridge/tmux-session-control.mjs +29 -29
  50. package/bridge/vscode-opener.mjs +157 -157
  51. package/bridge/web-terminal.mjs +52 -52
  52. package/bridge/workbench/manager-context.mjs +51 -51
  53. package/bridge/workbench/service.mjs +301 -301
  54. package/dist/client/.vite/manifest.json +4 -4
  55. package/dist/client/assets/{index-Enu1x0PS.js → index-BMior55c.js} +2 -2
  56. package/dist/client/assets/{layout-segment-context-CmJzExWq.js → layout-segment-context-DjGudgXn.js} +1 -1
  57. package/dist/client/assets/page-CJqXlhDs.js +551 -0
  58. package/dist/client/assets/page-LYzRz6_S.css +1 -0
  59. package/dist/client/favicon.svg +6 -6
  60. package/dist/server/__vite_rsc_assets_manifest.js +8 -8
  61. package/dist/server/index.js +7 -7
  62. package/dist/server/ssr/__vite_rsc_assets_manifest.js +8 -8
  63. package/dist/server/ssr/assets/{page-CYYyCnKD.js → page-BB9Dri2u.js} +2416 -271
  64. package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -0
  65. package/dist/server/ssr/index.js +1 -1
  66. package/dist/server/ssr/vinext-server.json +1 -1
  67. package/dist/server/vinext-server.json +1 -1
  68. package/dist/server/wrangler.json +1 -1
  69. package/lib/browser-snapshot-cache.js +53 -53
  70. package/lib/formula-preview.js +1 -1
  71. package/lib/incremental-snapshot.js +300 -300
  72. package/lib/markdown-math.js +151 -151
  73. package/lib/remote-links.js +95 -95
  74. package/lib/runtime-config.js +70 -70
  75. package/lib/session-filters.js +38 -38
  76. package/lib/ssh-config.js +26 -26
  77. package/lib/stable-order.js +39 -39
  78. package/lib/subagent-display-prefs.ts +130 -0
  79. package/package.json +1 -1
  80. package/scripts/agent-email-relay.mjs +104 -104
  81. package/scripts/email-notification-cli.mjs +28 -28
  82. package/scripts/enable-private-access.ps1 +109 -109
  83. package/scripts/fixtures/native-conversations.mjs +164 -6
  84. package/scripts/fixtures/workbench-conversations.mjs +475 -352
  85. package/scripts/preview-workbench.mjs +669 -669
  86. package/dist/client/assets/page-COBv6VWj.css +0 -1
  87. package/dist/client/assets/page-DVjU6VG_.js +0 -550
  88. package/dist/server/ssr/assets/page-COBv6VWj.css +0 -1
@@ -1,16 +1,16 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const NEW_SESSION_PREFLIGHT = String.raw`
3
- import json
4
- import os
5
- import sys
6
-
7
- requested = sys.argv[1]
8
- if not requested.startswith("/") or "\n" in requested or "\r" in requested:
9
- print("工作目录必须是远端绝对路径", file=sys.stderr)
10
- raise SystemExit(2)
11
- resolved = os.path.realpath(requested)
12
- if not os.path.isdir(resolved):
13
- print("工作目录不存在:" + resolved, file=sys.stderr)
14
- raise SystemExit(3)
15
- print(json.dumps({"ok": True, "cwd": resolved}, ensure_ascii=False))
2
+ export const NEW_SESSION_PREFLIGHT = String.raw`
3
+ import json
4
+ import os
5
+ import sys
6
+
7
+ requested = sys.argv[1]
8
+ if not requested.startswith("/") or "\n" in requested or "\r" in requested:
9
+ print("工作目录必须是远端绝对路径", file=sys.stderr)
10
+ raise SystemExit(2)
11
+ resolved = os.path.realpath(requested)
12
+ if not os.path.isdir(resolved):
13
+ print("工作目录不存在:" + resolved, file=sys.stderr)
14
+ raise SystemExit(3)
15
+ print(json.dumps({"ok": True, "cwd": resolved}, ensure_ascii=False))
16
16
  `;
@@ -1,19 +1,19 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const PROFILE_CANCEL_PROBE = String.raw`
3
- import json
4
- import os
5
- import shutil
6
- import sys
7
-
8
- slug = sys.argv[1]
9
- root = os.path.realpath(os.path.expanduser("~/.codex/scope-auth-profiles"))
10
- target = os.path.realpath(os.path.join(root, slug))
11
- if os.path.commonpath([root, target]) != root or target == root:
12
- raise RuntimeError("拒绝清理 Profile 根目录之外的路径")
13
- auth_path = os.path.join(target, "home", "auth.json")
14
- removed = False
15
- if os.path.isdir(target) and not os.path.isfile(auth_path):
16
- shutil.rmtree(target)
17
- removed = True
18
- print(json.dumps({"ok": True, "removed": removed}, separators=(",", ":")))
2
+ export const PROFILE_CANCEL_PROBE = String.raw`
3
+ import json
4
+ import os
5
+ import shutil
6
+ import sys
7
+
8
+ slug = sys.argv[1]
9
+ root = os.path.realpath(os.path.expanduser("~/.codex/scope-auth-profiles"))
10
+ target = os.path.realpath(os.path.join(root, slug))
11
+ if os.path.commonpath([root, target]) != root or target == root:
12
+ raise RuntimeError("拒绝清理 Profile 根目录之外的路径")
13
+ auth_path = os.path.join(target, "home", "auth.json")
14
+ removed = False
15
+ if os.path.isdir(target) and not os.path.isfile(auth_path):
16
+ shutil.rmtree(target)
17
+ removed = True
18
+ print(json.dumps({"ok": True, "removed": removed}, separators=(",", ":")))
19
19
  `;
@@ -1,28 +1,28 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const PROFILE_DELETE_PROBE = String.raw`
3
- import json
4
- import os
5
- import shutil
6
- import sys
7
-
8
- slug, confirmation = sys.argv[1:3]
9
- if confirmation != slug:
10
- raise RuntimeError("删除确认与 Profile 不匹配")
11
- root = os.path.realpath(os.path.expanduser("~/.codex/scope-auth-profiles"))
12
- target = os.path.realpath(os.path.join(root, slug))
13
- if os.path.commonpath([root, target]) != root or target == root:
14
- raise RuntimeError("拒绝删除 Profile 根目录之外的路径")
15
- marker_path = os.path.join(root, "active")
16
- try:
17
- with open(marker_path, "r", encoding="utf-8") as handle:
18
- active_slug = handle.read().strip()
19
- except Exception:
20
- active_slug = ""
21
- if active_slug == slug:
22
- raise RuntimeError("当前正在使用的 Profile 不能删除;请先切换账号")
23
- removed = False
24
- if os.path.isdir(target):
25
- shutil.rmtree(target)
26
- removed = True
27
- print(json.dumps({"ok": True, "slug": slug, "removed": removed}, separators=(",", ":")))
2
+ export const PROFILE_DELETE_PROBE = String.raw`
3
+ import json
4
+ import os
5
+ import shutil
6
+ import sys
7
+
8
+ slug, confirmation = sys.argv[1:3]
9
+ if confirmation != slug:
10
+ raise RuntimeError("删除确认与 Profile 不匹配")
11
+ root = os.path.realpath(os.path.expanduser("~/.codex/scope-auth-profiles"))
12
+ target = os.path.realpath(os.path.join(root, slug))
13
+ if os.path.commonpath([root, target]) != root or target == root:
14
+ raise RuntimeError("拒绝删除 Profile 根目录之外的路径")
15
+ marker_path = os.path.join(root, "active")
16
+ try:
17
+ with open(marker_path, "r", encoding="utf-8") as handle:
18
+ active_slug = handle.read().strip()
19
+ except Exception:
20
+ active_slug = ""
21
+ if active_slug == slug:
22
+ raise RuntimeError("当前正在使用的 Profile 不能删除;请先切换账号")
23
+ removed = False
24
+ if os.path.isdir(target):
25
+ shutil.rmtree(target)
26
+ removed = True
27
+ print(json.dumps({"ok": True, "slug": slug, "removed": removed}, separators=(",", ":")))
28
28
  `;
@@ -1,117 +1,117 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const PROFILE_LIST_PROBE = String.raw`
3
- import hashlib
4
- import ast
5
- import base64
6
- import json
7
- import os
8
-
9
- root = os.path.expanduser("~/.codex/scope-auth-profiles")
10
- default_auth = os.path.expanduser("~/.codex/auth.json")
11
- marker_slug = ""
12
- try:
13
- with open(os.path.join(root, "active"), "r", encoding="utf-8") as handle:
14
- marker_slug = handle.read().strip()
15
- except Exception:
16
- pass
17
-
18
- def digest(path):
19
- try:
20
- with open(path, "rb") as handle:
21
- return hashlib.sha256(handle.read()).hexdigest()
22
- except Exception:
23
- return ""
24
-
25
- default_digest = digest(default_auth)
26
-
27
- def current_account(path):
28
- try:
29
- with open(path, "r", encoding="utf-8") as handle:
30
- data = json.load(handle)
31
- except Exception:
32
- return None
33
- tokens = data.get("tokens") if isinstance(data.get("tokens"), dict) else {}
34
- candidates = [tokens.get("id_token"), data.get("id_token"), tokens.get("access_token")]
35
- claims = {}
36
- for token in candidates:
37
- if not isinstance(token, str) or token.count(".") < 2:
38
- continue
39
- try:
40
- segment = token.split(".")[1]
41
- segment += "=" * (-len(segment) % 4)
42
- claims = json.loads(base64.urlsafe_b64decode(segment).decode("utf-8"))
43
- break
44
- except Exception:
45
- continue
46
- auth_claims = claims.get("https://api.openai.com/auth")
47
- if not isinstance(auth_claims, dict):
48
- auth_claims = {}
49
- email = claims.get("email") or auth_claims.get("email") or ""
50
- plan = (
51
- auth_claims.get("chatgpt_plan_type")
52
- or claims.get("chatgpt_plan_type")
53
- or claims.get("plan_type")
54
- or "unknown"
55
- )
56
- mode = str(data.get("auth_mode") or "chatgpt").lower()
57
- account_type = "apiKey" if "api" in mode and "chatgpt" not in mode else "chatgpt"
58
- return {
59
- "type": account_type,
60
- "email": str(email)[:320],
61
- "planType": str(plan)[:80],
62
- }
63
-
64
- def safe_account(value):
65
- if not isinstance(value, dict):
66
- return None
67
- account_type = str(value.get("type") or "")[:40]
68
- if account_type not in ("chatgpt", "apiKey", "amazonBedrock"):
69
- return None
70
- return {
71
- "type": account_type,
72
- "email": str(value.get("email") or "")[:320],
73
- "planType": str(value.get("planType") or "")[:80],
74
- }
75
-
76
- profiles = []
77
- if os.path.isdir(root):
78
- for slug in sorted(os.listdir(root)):
79
- directory = os.path.join(root, slug)
80
- if not os.path.isdir(directory):
81
- continue
82
- auth_path = os.path.join(directory, "home", "auth.json")
83
- metadata_path = os.path.join(directory, "metadata.json")
84
- metadata = {}
85
- try:
86
- with open(metadata_path, "r", encoding="utf-8") as handle:
87
- metadata = json.load(handle)
88
- except Exception:
89
- pass
90
- profile_digest = digest(auth_path)
91
- profiles.append({
92
- "slug": slug,
93
- "name": str(metadata.get("name") or slug)[:80],
94
- "createdAt": metadata.get("createdAt"),
95
- "updatedAt": metadata.get("updatedAt"),
2
+ export const PROFILE_LIST_PROBE = String.raw`
3
+ import hashlib
4
+ import ast
5
+ import base64
6
+ import json
7
+ import os
8
+
9
+ root = os.path.expanduser("~/.codex/scope-auth-profiles")
10
+ default_auth = os.path.expanduser("~/.codex/auth.json")
11
+ marker_slug = ""
12
+ try:
13
+ with open(os.path.join(root, "active"), "r", encoding="utf-8") as handle:
14
+ marker_slug = handle.read().strip()
15
+ except Exception:
16
+ pass
17
+
18
+ def digest(path):
19
+ try:
20
+ with open(path, "rb") as handle:
21
+ return hashlib.sha256(handle.read()).hexdigest()
22
+ except Exception:
23
+ return ""
24
+
25
+ default_digest = digest(default_auth)
26
+
27
+ def current_account(path):
28
+ try:
29
+ with open(path, "r", encoding="utf-8") as handle:
30
+ data = json.load(handle)
31
+ except Exception:
32
+ return None
33
+ tokens = data.get("tokens") if isinstance(data.get("tokens"), dict) else {}
34
+ candidates = [tokens.get("id_token"), data.get("id_token"), tokens.get("access_token")]
35
+ claims = {}
36
+ for token in candidates:
37
+ if not isinstance(token, str) or token.count(".") < 2:
38
+ continue
39
+ try:
40
+ segment = token.split(".")[1]
41
+ segment += "=" * (-len(segment) % 4)
42
+ claims = json.loads(base64.urlsafe_b64decode(segment).decode("utf-8"))
43
+ break
44
+ except Exception:
45
+ continue
46
+ auth_claims = claims.get("https://api.openai.com/auth")
47
+ if not isinstance(auth_claims, dict):
48
+ auth_claims = {}
49
+ email = claims.get("email") or auth_claims.get("email") or ""
50
+ plan = (
51
+ auth_claims.get("chatgpt_plan_type")
52
+ or claims.get("chatgpt_plan_type")
53
+ or claims.get("plan_type")
54
+ or "unknown"
55
+ )
56
+ mode = str(data.get("auth_mode") or "chatgpt").lower()
57
+ account_type = "apiKey" if "api" in mode and "chatgpt" not in mode else "chatgpt"
58
+ return {
59
+ "type": account_type,
60
+ "email": str(email)[:320],
61
+ "planType": str(plan)[:80],
62
+ }
63
+
64
+ def safe_account(value):
65
+ if not isinstance(value, dict):
66
+ return None
67
+ account_type = str(value.get("type") or "")[:40]
68
+ if account_type not in ("chatgpt", "apiKey", "amazonBedrock"):
69
+ return None
70
+ return {
71
+ "type": account_type,
72
+ "email": str(value.get("email") or "")[:320],
73
+ "planType": str(value.get("planType") or "")[:80],
74
+ }
75
+
76
+ profiles = []
77
+ if os.path.isdir(root):
78
+ for slug in sorted(os.listdir(root)):
79
+ directory = os.path.join(root, slug)
80
+ if not os.path.isdir(directory):
81
+ continue
82
+ auth_path = os.path.join(directory, "home", "auth.json")
83
+ metadata_path = os.path.join(directory, "metadata.json")
84
+ metadata = {}
85
+ try:
86
+ with open(metadata_path, "r", encoding="utf-8") as handle:
87
+ metadata = json.load(handle)
88
+ except Exception:
89
+ pass
90
+ profile_digest = digest(auth_path)
91
+ profiles.append({
92
+ "slug": slug,
93
+ "name": str(metadata.get("name") or slug)[:80],
94
+ "createdAt": metadata.get("createdAt"),
95
+ "updatedAt": metadata.get("updatedAt"),
96
96
  "account": current_account(auth_path) or safe_account(metadata.get("account")),
97
- "ready": bool(profile_digest),
98
- "active": False,
99
- "matchesDefault": bool(default_digest and profile_digest == default_digest),
100
- })
101
-
102
- ready_slugs = {item["slug"] for item in profiles if item["ready"]}
103
- matching_slugs = [item["slug"] for item in profiles if item["matchesDefault"]]
104
- active_slug = marker_slug if marker_slug in ready_slugs else ""
105
- if not active_slug and len(matching_slugs) == 1:
106
- active_slug = matching_slugs[0]
107
- for item in profiles:
108
- item["active"] = item["slug"] == active_slug
109
- item.pop("matchesDefault", None)
110
-
111
- print(json.dumps({
112
- "profiles": profiles,
113
- "defaultAuthPresent": bool(default_digest),
114
- "activeProfile": active_slug or None,
115
- "currentAccount": current_account(default_auth) if default_digest else None,
116
- }, ensure_ascii=False, separators=(",", ":")))
97
+ "ready": bool(profile_digest),
98
+ "active": False,
99
+ "matchesDefault": bool(default_digest and profile_digest == default_digest),
100
+ })
101
+
102
+ ready_slugs = {item["slug"] for item in profiles if item["ready"]}
103
+ matching_slugs = [item["slug"] for item in profiles if item["matchesDefault"]]
104
+ active_slug = marker_slug if marker_slug in ready_slugs else ""
105
+ if not active_slug and len(matching_slugs) == 1:
106
+ active_slug = matching_slugs[0]
107
+ for item in profiles:
108
+ item["active"] = item["slug"] == active_slug
109
+ item.pop("matchesDefault", None)
110
+
111
+ print(json.dumps({
112
+ "profiles": profiles,
113
+ "defaultAuthPresent": bool(default_digest),
114
+ "activeProfile": active_slug or None,
115
+ "currentAccount": current_account(default_auth) if default_digest else None,
116
+ }, ensure_ascii=False, separators=(",", ":")))
117
117
  `;
@@ -1,111 +1,111 @@
1
1
  /** Remote probe, kept independent of HTTP and local mutable state. */
2
- export const PROFILE_WRITE_PROBE = String.raw`
3
- import base64
4
- import json
5
- import os
6
- import shutil
7
- import sys
8
- import tempfile
9
- from datetime import datetime, timezone
10
-
11
- action, slug, encoded = sys.argv[1:4]
12
- payload = json.loads(base64.b64decode(encoded).decode("utf-8"))
13
- root = os.path.realpath(os.path.expanduser("~/.codex/scope-auth-profiles"))
14
- profile_dir = os.path.realpath(os.path.join(root, slug))
15
- if os.path.commonpath([root, profile_dir]) != root or profile_dir == root:
16
- raise RuntimeError("拒绝访问 Profile 根目录之外的路径")
17
- home_dir = os.path.join(profile_dir, "home")
18
- auth_path = os.path.join(home_dir, "auth.json")
19
- default_home = os.path.expanduser("~/.codex")
20
- default_auth = os.path.join(default_home, "auth.json")
21
- os.makedirs(home_dir, mode=0o700, exist_ok=True)
22
- os.chmod(profile_dir, 0o700)
23
- os.chmod(home_dir, 0o700)
24
-
25
- def atomic_copy(source, target):
26
- if not os.path.isfile(source):
27
- raise RuntimeError("找不到远端 auth.json;请先在该主机登录 Codex")
28
- os.makedirs(os.path.dirname(target), mode=0o700, exist_ok=True)
29
- fd, temporary = tempfile.mkstemp(prefix=".scope-auth-", dir=os.path.dirname(target))
30
- os.close(fd)
31
- try:
32
- shutil.copyfile(source, temporary)
33
- os.chmod(temporary, 0o600)
34
- os.replace(temporary, target)
35
- finally:
36
- try:
37
- os.unlink(temporary)
38
- except FileNotFoundError:
39
- pass
40
-
41
- if action == "save-current":
42
- atomic_copy(default_auth, auth_path)
43
- os.makedirs(root, mode=0o700, exist_ok=True)
44
- fd, marker_tmp = tempfile.mkstemp(prefix=".active-", dir=root)
45
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
46
- handle.write(slug + "\n")
47
- os.replace(marker_tmp, os.path.join(root, "active"))
48
- elif action == "select-default":
49
- # Web default selection must not replace credentials used by live writers.
50
- if not os.path.isfile(auth_path):
51
- raise RuntimeError("该 Profile 尚未完成登录")
52
- fd, marker_tmp = tempfile.mkstemp(prefix=".active-", dir=root)
53
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
54
- handle.write(slug + "\n")
55
- os.replace(marker_tmp, os.path.join(root, "active"))
56
- elif action == "activate":
57
- if not os.path.isfile(auth_path):
58
- raise RuntimeError("该 Profile 尚未完成登录")
59
- marker_path = os.path.join(root, "active")
60
- try:
61
- with open(marker_path, "r", encoding="utf-8") as handle:
62
- previous_slug = handle.read().strip()
63
- except Exception:
64
- previous_slug = ""
65
- if previous_slug and previous_slug != slug and os.path.isfile(default_auth):
66
- previous_profile = os.path.realpath(os.path.join(root, previous_slug))
67
- previous_home = os.path.join(previous_profile, "home")
68
- if (
69
- os.path.commonpath([root, previous_profile]) == root
70
- and previous_profile != root
71
- and os.path.isdir(previous_home)
72
- # An isolated writer owns its refreshed credentials. Never replace
73
- # them with a potentially older canonical-home token snapshot.
74
- and not os.path.exists(os.path.join(previous_home, "app-server-control", "scope-account-" + previous_slug + ".sock"))
75
- ):
76
- atomic_copy(default_auth, os.path.join(previous_home, "auth.json"))
77
- atomic_copy(auth_path, default_auth)
78
- os.makedirs(root, mode=0o700, exist_ok=True)
79
- fd, marker_tmp = tempfile.mkstemp(prefix=".active-", dir=root)
80
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
81
- handle.write(slug + "\n")
82
- os.replace(marker_tmp, marker_path)
83
- elif action == "finalize":
84
- if not os.path.isfile(auth_path):
85
- raise RuntimeError("Device auth 已返回成功,但远端未生成 auth.json")
86
- os.chmod(auth_path, 0o600)
87
- else:
88
- raise RuntimeError("未知 Profile 操作")
89
-
90
- metadata_path = os.path.join(profile_dir, "metadata.json")
91
- existing = {}
92
- try:
93
- with open(metadata_path, "r", encoding="utf-8") as handle:
94
- existing = json.load(handle)
95
- except Exception:
96
- pass
97
- now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
98
- metadata = {
99
- "name": str(payload.get("name") or slug)[:80],
100
- "createdAt": existing.get("createdAt") or now,
101
- "updatedAt": now,
102
- "account": payload.get("account") if isinstance(payload.get("account"), dict) else existing.get("account"),
103
- }
104
- fd, metadata_tmp = tempfile.mkstemp(prefix=".metadata-", dir=profile_dir)
105
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
106
- json.dump(metadata, handle, ensure_ascii=False, separators=(",", ":"))
107
- handle.write("\n")
108
- os.chmod(metadata_tmp, 0o600)
109
- os.replace(metadata_tmp, metadata_path)
110
- print(json.dumps({"ok": True, "slug": slug, "action": action}, separators=(",", ":")))
2
+ export const PROFILE_WRITE_PROBE = String.raw`
3
+ import base64
4
+ import json
5
+ import os
6
+ import shutil
7
+ import sys
8
+ import tempfile
9
+ from datetime import datetime, timezone
10
+
11
+ action, slug, encoded = sys.argv[1:4]
12
+ payload = json.loads(base64.b64decode(encoded).decode("utf-8"))
13
+ root = os.path.realpath(os.path.expanduser("~/.codex/scope-auth-profiles"))
14
+ profile_dir = os.path.realpath(os.path.join(root, slug))
15
+ if os.path.commonpath([root, profile_dir]) != root or profile_dir == root:
16
+ raise RuntimeError("拒绝访问 Profile 根目录之外的路径")
17
+ home_dir = os.path.join(profile_dir, "home")
18
+ auth_path = os.path.join(home_dir, "auth.json")
19
+ default_home = os.path.expanduser("~/.codex")
20
+ default_auth = os.path.join(default_home, "auth.json")
21
+ os.makedirs(home_dir, mode=0o700, exist_ok=True)
22
+ os.chmod(profile_dir, 0o700)
23
+ os.chmod(home_dir, 0o700)
24
+
25
+ def atomic_copy(source, target):
26
+ if not os.path.isfile(source):
27
+ raise RuntimeError("找不到远端 auth.json;请先在该主机登录 Codex")
28
+ os.makedirs(os.path.dirname(target), mode=0o700, exist_ok=True)
29
+ fd, temporary = tempfile.mkstemp(prefix=".scope-auth-", dir=os.path.dirname(target))
30
+ os.close(fd)
31
+ try:
32
+ shutil.copyfile(source, temporary)
33
+ os.chmod(temporary, 0o600)
34
+ os.replace(temporary, target)
35
+ finally:
36
+ try:
37
+ os.unlink(temporary)
38
+ except FileNotFoundError:
39
+ pass
40
+
41
+ if action == "save-current":
42
+ atomic_copy(default_auth, auth_path)
43
+ os.makedirs(root, mode=0o700, exist_ok=True)
44
+ fd, marker_tmp = tempfile.mkstemp(prefix=".active-", dir=root)
45
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
46
+ handle.write(slug + "\n")
47
+ os.replace(marker_tmp, os.path.join(root, "active"))
48
+ elif action == "select-default":
49
+ # Web default selection must not replace credentials used by live writers.
50
+ if not os.path.isfile(auth_path):
51
+ raise RuntimeError("该 Profile 尚未完成登录")
52
+ fd, marker_tmp = tempfile.mkstemp(prefix=".active-", dir=root)
53
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
54
+ handle.write(slug + "\n")
55
+ os.replace(marker_tmp, os.path.join(root, "active"))
56
+ elif action == "activate":
57
+ if not os.path.isfile(auth_path):
58
+ raise RuntimeError("该 Profile 尚未完成登录")
59
+ marker_path = os.path.join(root, "active")
60
+ try:
61
+ with open(marker_path, "r", encoding="utf-8") as handle:
62
+ previous_slug = handle.read().strip()
63
+ except Exception:
64
+ previous_slug = ""
65
+ if previous_slug and previous_slug != slug and os.path.isfile(default_auth):
66
+ previous_profile = os.path.realpath(os.path.join(root, previous_slug))
67
+ previous_home = os.path.join(previous_profile, "home")
68
+ if (
69
+ os.path.commonpath([root, previous_profile]) == root
70
+ and previous_profile != root
71
+ and os.path.isdir(previous_home)
72
+ # An isolated writer owns its refreshed credentials. Never replace
73
+ # them with a potentially older canonical-home token snapshot.
74
+ and not os.path.exists(os.path.join(previous_home, "app-server-control", "scope-account-" + previous_slug + ".sock"))
75
+ ):
76
+ atomic_copy(default_auth, os.path.join(previous_home, "auth.json"))
77
+ atomic_copy(auth_path, default_auth)
78
+ os.makedirs(root, mode=0o700, exist_ok=True)
79
+ fd, marker_tmp = tempfile.mkstemp(prefix=".active-", dir=root)
80
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
81
+ handle.write(slug + "\n")
82
+ os.replace(marker_tmp, marker_path)
83
+ elif action == "finalize":
84
+ if not os.path.isfile(auth_path):
85
+ raise RuntimeError("Device auth 已返回成功,但远端未生成 auth.json")
86
+ os.chmod(auth_path, 0o600)
87
+ else:
88
+ raise RuntimeError("未知 Profile 操作")
89
+
90
+ metadata_path = os.path.join(profile_dir, "metadata.json")
91
+ existing = {}
92
+ try:
93
+ with open(metadata_path, "r", encoding="utf-8") as handle:
94
+ existing = json.load(handle)
95
+ except Exception:
96
+ pass
97
+ now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
98
+ metadata = {
99
+ "name": str(payload.get("name") or slug)[:80],
100
+ "createdAt": existing.get("createdAt") or now,
101
+ "updatedAt": now,
102
+ "account": payload.get("account") if isinstance(payload.get("account"), dict) else existing.get("account"),
103
+ }
104
+ fd, metadata_tmp = tempfile.mkstemp(prefix=".metadata-", dir=profile_dir)
105
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
106
+ json.dump(metadata, handle, ensure_ascii=False, separators=(",", ":"))
107
+ handle.write("\n")
108
+ os.chmod(metadata_tmp, 0o600)
109
+ os.replace(metadata_tmp, metadata_path)
110
+ print(json.dumps({"ok": True, "slug": slug, "action": action}, separators=(",", ":")))
111
111
  `;