magic-campus-cli 0.1.0__py3-none-any.whl

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 (53) hide show
  1. magic_campus_cli-0.1.0.dist-info/METADATA +51 -0
  2. magic_campus_cli-0.1.0.dist-info/RECORD +53 -0
  3. magic_campus_cli-0.1.0.dist-info/WHEEL +5 -0
  4. magic_campus_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. magic_campus_cli-0.1.0.dist-info/top_level.txt +2 -0
  6. magiccampus_cli/__init__.py +1 -0
  7. magiccampus_cli/__main__.py +9 -0
  8. magiccampus_cli/accounts.py +144 -0
  9. magiccampus_cli/cli.py +176 -0
  10. magiccampus_cli/client.py +54 -0
  11. magiccampus_cli/commands/auth.py +32 -0
  12. magiccampus_cli/commands/comment.py +38 -0
  13. magiccampus_cli/commands/config.py +95 -0
  14. magiccampus_cli/commands/feed.py +26 -0
  15. magiccampus_cli/commands/group.py +346 -0
  16. magiccampus_cli/commands/im.py +47 -0
  17. magiccampus_cli/commands/notify.py +81 -0
  18. magiccampus_cli/commands/playgroup.py +49 -0
  19. magiccampus_cli/commands/reaction.py +50 -0
  20. magiccampus_cli/commands/space.py +134 -0
  21. magiccampus_cli/commands/user.py +311 -0
  22. magiccampus_cli/config_store.py +61 -0
  23. magiccampus_cli/notify.py +493 -0
  24. magiccampus_cli/output.py +104 -0
  25. magiccampus_cli/prompts.py +58 -0
  26. magiccampus_cli/targets.py +26 -0
  27. magiccampus_cli/update.py +149 -0
  28. magiccampus_cli/utils.py +67 -0
  29. magiccampus_sdk/__init__.py +43 -0
  30. magiccampus_sdk/auth.py +111 -0
  31. magiccampus_sdk/comment_client.py +107 -0
  32. magiccampus_sdk/feed_api.py +61 -0
  33. magiccampus_sdk/feed_client.py +30 -0
  34. magiccampus_sdk/group_api.py +139 -0
  35. magiccampus_sdk/group_client.py +242 -0
  36. magiccampus_sdk/http/__init__.py +1 -0
  37. magiccampus_sdk/http/group_info_api.py +47 -0
  38. magiccampus_sdk/http/http_api.py +58 -0
  39. magiccampus_sdk/http/http_send.py +758 -0
  40. magiccampus_sdk/http/media.py +839 -0
  41. magiccampus_sdk/http/models.py +645 -0
  42. magiccampus_sdk/http/self_user_info_api.py +182 -0
  43. magiccampus_sdk/http/text.py +75 -0
  44. magiccampus_sdk/models.py +279 -0
  45. magiccampus_sdk/platform_client.py +137 -0
  46. magiccampus_sdk/platform_http.py +71 -0
  47. magiccampus_sdk/playgroup_api.py +104 -0
  48. magiccampus_sdk/playgroup_client.py +45 -0
  49. magiccampus_sdk/reaction_api.py +110 -0
  50. magiccampus_sdk/space_api.py +170 -0
  51. magiccampus_sdk/space_client.py +93 -0
  52. magiccampus_sdk/user_client.py +211 -0
  53. magiccampus_sdk/user_info_api.py +593 -0
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ from magiccampus_sdk import MagicCampusClient, MagicCampusClientConfig
4
+
5
+ from ..config_store import read_config_root
6
+ from ..utils import trim_string
7
+ from .auth import resolve_account_or_throw
8
+
9
+
10
+ def run_reaction_command(subcommand: str | None, argv: list[str], parse_options):
11
+ if subcommand not in {"add", "delete"}:
12
+ raise RuntimeError(f"Unknown im reaction subcommand: {subcommand}")
13
+
14
+ options, _ = parse_options(argv)
15
+ required = {
16
+ "conversation-id": "conversation_id",
17
+ "server-msg-id": "server_msg_id",
18
+ "msg-sender-id": "msg_sender_id",
19
+ }
20
+ if subcommand == "add":
21
+ required["reaction-code"] = "reaction_code"
22
+ else:
23
+ required["reaction-id"] = "reaction_id"
24
+
25
+ kwargs = {}
26
+ for option, argument in required.items():
27
+ raw = options.get(option)
28
+ value = trim_string(raw)
29
+ if raw is True or not value:
30
+ raise RuntimeError(f"im reaction {subcommand} requires --{option} <value>.")
31
+ kwargs[argument] = value
32
+
33
+ account = resolve_account_or_throw(read_config_root(), options.get("account"))
34
+ client = MagicCampusClient(
35
+ MagicCampusClientConfig(
36
+ apiurl=account.apiurl,
37
+ apikey=account.apikey,
38
+ platform=account.platform,
39
+ )
40
+ )
41
+ action = client.im.add_message_reaction if subcommand == "add" else client.im.delete_message_reaction
42
+ return {
43
+ "ok": True,
44
+ "accountId": account.account_id,
45
+ "provider": "magiccampus",
46
+ "resource": "messageReaction",
47
+ "action": subcommand,
48
+ "transport": "http_api",
49
+ "result": action(**kwargs),
50
+ }
@@ -0,0 +1,134 @@
1
+ from __future__ import annotations
2
+
3
+ from magiccampus_sdk import MagicCampusClient, MagicCampusClientConfig
4
+
5
+ from ..config_store import read_config_root
6
+ from ..utils import trim_string
7
+ from .auth import resolve_account_or_throw
8
+
9
+
10
+ def run_space_command(subcommand: str | None, argv: list[str], parse_options):
11
+ if subcommand == "get":
12
+ raise RuntimeError("space get was removed; use playgroup get --id <spaceId>.")
13
+
14
+ if subcommand == "list-notice":
15
+ options, _ = parse_options(argv)
16
+ space_id = _require_space_id(options, "list-notice")
17
+
18
+ root = read_config_root()
19
+ account = resolve_account_or_throw(root, options.get("account"))
20
+ client = MagicCampusClient(
21
+ MagicCampusClientConfig(
22
+ apiurl=account.apiurl,
23
+ apikey=account.apikey,
24
+ platform=account.platform,
25
+ )
26
+ )
27
+ return client.space.list_notices(space_id)
28
+
29
+ if subcommand == "create-notice":
30
+ options, _ = parse_options(argv)
31
+ space_id = _require_space_id(options, "create-notice")
32
+ title = trim_string(options.get("title"))
33
+ if not title:
34
+ raise RuntimeError("space create-notice requires --title <title>.")
35
+ text = trim_string(options.get("text"))
36
+ if not text:
37
+ raise RuntimeError("space create-notice requires --text <text>.")
38
+ raw_expiretime = options.get("expiretime")
39
+ if raw_expiretime is None:
40
+ raw_expiretime = options.get("expire-time")
41
+ if raw_expiretime is None or raw_expiretime is True:
42
+ raise RuntimeError("space create-notice requires --expiretime <timestamp>.")
43
+ try:
44
+ expiretime = int(trim_string(raw_expiretime))
45
+ except ValueError as exc:
46
+ raise RuntimeError("space create-notice --expiretime must be an integer.") from exc
47
+
48
+ root = read_config_root()
49
+ account = resolve_account_or_throw(root, options.get("account"))
50
+ client = MagicCampusClient(
51
+ MagicCampusClientConfig(
52
+ apiurl=account.apiurl,
53
+ apikey=account.apikey,
54
+ platform=account.platform,
55
+ )
56
+ )
57
+ result = client.space.create_notice(
58
+ space_id=space_id,
59
+ title=title,
60
+ text=text,
61
+ expiretime=expiretime,
62
+ )
63
+ output = {
64
+ "ok": True,
65
+ "accountId": account.account_id,
66
+ "provider": "magiccampus",
67
+ "resource": "spaceNotice",
68
+ "action": "create",
69
+ "transport": "http_api",
70
+ "spaceId": space_id,
71
+ "title": title,
72
+ "text": text,
73
+ "expiretime": expiretime,
74
+ "result": result,
75
+ "magiccampus": {
76
+ "apiUrl": account.apiurl,
77
+ "platform": account.platform,
78
+ },
79
+ }
80
+ return output
81
+
82
+ if subcommand == "group":
83
+ return _run_space_group_command(argv, parse_options)
84
+
85
+ raise RuntimeError(f"Unknown space subcommand: {subcommand}")
86
+
87
+
88
+ def _run_space_group_command(argv: list[str], parse_options):
89
+ action = argv[0] if argv else None
90
+ if action not in {"update-name", "update_name", "rename"}:
91
+ raise RuntimeError(f"Unknown space group subcommand: {action}")
92
+
93
+ options, _ = parse_options(argv[1:])
94
+ group_id = trim_string(options.get("group") or options.get("group-id"))
95
+ if not group_id:
96
+ raise RuntimeError("space group update-name requires --group <groupId>.")
97
+ name = trim_string(options.get("name"))
98
+ if not name:
99
+ raise RuntimeError("space group update-name requires --name <name>.")
100
+
101
+ root = read_config_root()
102
+ account = resolve_account_or_throw(root, options.get("account"))
103
+ client = MagicCampusClient(
104
+ MagicCampusClientConfig(
105
+ apiurl=account.apiurl,
106
+ apikey=account.apikey,
107
+ platform=account.platform,
108
+ )
109
+ )
110
+ updated = client.space.update_group_name(group_id, name)
111
+ return {
112
+ "ok": updated,
113
+ "accountId": account.account_id,
114
+ "provider": "magiccampus",
115
+ "resource": "spaceGroup",
116
+ "action": "updateName",
117
+ "transport": "http_api",
118
+ "groupId": group_id,
119
+ "name": name,
120
+ "updated": updated,
121
+ "magiccampus": {
122
+ "apiUrl": account.apiurl,
123
+ "platform": account.platform,
124
+ },
125
+ }
126
+
127
+
128
+ def _require_space_id(options: dict[str, object], command: str) -> str:
129
+ if "group" in options or "group-id" in options:
130
+ raise RuntimeError(f"space {command} no longer accepts --group; use --space <spaceId> from playgroup list.")
131
+ value = options.get("space") or options.get("space-id")
132
+ if not isinstance(value, str) or not value.strip():
133
+ raise RuntimeError(f"space {command} requires --space <spaceId>.")
134
+ return value.strip()
@@ -0,0 +1,311 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from magiccampus_sdk import MagicCampusClient, MagicCampusClientConfig
8
+ from magiccampus_sdk.user_info_api import ACADEMY_CODES, normalize_academy_code, validate_user_ext, validate_user_info
9
+
10
+ from ..config_store import read_config_root
11
+ from ..utils import parse_optional_bool, trim_string
12
+ from .auth import resolve_account_or_throw
13
+
14
+
15
+ ELEMENT_DELTA_OPTIONS = (
16
+ ("metal-delta", "metal_delta", "metalDelta"),
17
+ ("wood-delta", "wood_delta", "woodDelta"),
18
+ ("water-delta", "water_delta", "waterDelta"),
19
+ ("fire-delta", "fire_delta", "fireDelta"),
20
+ ("earth-delta", "earth_delta", "earthDelta"),
21
+ )
22
+
23
+
24
+ def _parse_fields(value: object) -> tuple[str, ...] | None:
25
+ if value is None:
26
+ return None
27
+ if value is True:
28
+ raise RuntimeError("user list --fields requires a comma-separated field list.")
29
+
30
+ fields = tuple(dict.fromkeys(part.strip() for part in str(value).split(",") if part.strip()))
31
+ if not fields:
32
+ raise RuntimeError("user list --fields requires a comma-separated field list.")
33
+
34
+ return fields
35
+
36
+
37
+ def _parse_element_deltas(options: dict[str, object]) -> tuple[dict[str, int], dict[str, int]]:
38
+ client_kwargs: dict[str, int] = {}
39
+ payload: dict[str, int] = {}
40
+ for option_name, argument_name, payload_name in ELEMENT_DELTA_OPTIONS:
41
+ if option_name not in options:
42
+ continue
43
+ raw_value = options[option_name]
44
+ if raw_value is True:
45
+ raise RuntimeError(
46
+ f"user adjust-elements --{option_name} requires a value."
47
+ )
48
+ try:
49
+ value = int(trim_string(raw_value))
50
+ except ValueError as exc:
51
+ raise RuntimeError(
52
+ f"user adjust-elements --{option_name} must be an integer."
53
+ ) from exc
54
+ client_kwargs[argument_name] = value
55
+ payload[payload_name] = value
56
+
57
+ if not client_kwargs:
58
+ option_list = ", ".join(f"--{name}" for name, _, _ in ELEMENT_DELTA_OPTIONS)
59
+ raise RuntimeError(
60
+ f"user adjust-elements requires at least one of {option_list}."
61
+ )
62
+ return client_kwargs, payload
63
+
64
+
65
+ def _parse_ext_body(options: dict[str, object], positionals: list[str]) -> dict[str, str]:
66
+ if "id" in options or "user-id" in options:
67
+ raise RuntimeError("user update-ext uses the authenticated identity; --id and --user-id are unsupported.")
68
+ if positionals or options.keys() - {"json", "body", "account"}:
69
+ raise RuntimeError("user update-ext accepts only --json, --body and --account.")
70
+ if ("json" in options) == ("body" in options):
71
+ raise RuntimeError("user update-ext requires exactly one of --json <object> or --body <path|->.")
72
+ source = "json" if "json" in options else "body"
73
+ value = options[source]
74
+ if not isinstance(value, str) or not value:
75
+ raise RuntimeError(f"user update-ext --{source} requires a value.")
76
+ text = value
77
+ if source == "body":
78
+ text = sys.stdin.read() if value == "-" else Path(value).read_text(encoding="utf-8")
79
+ try:
80
+ ext = json.loads(text)
81
+ except json.JSONDecodeError as exc:
82
+ raise RuntimeError("user update-ext body must be valid JSON.") from exc
83
+ return validate_user_ext(ext)
84
+
85
+
86
+ def _parse_info_body(options: dict[str, object], positionals: list[str]) -> dict[str, object]:
87
+ fields = {"nickname": "nickname", "avatar-url": "avatarUrl", "introduction": "introduction",
88
+ "birth": "birth", "gender": "gender", "tags": "tags"}
89
+ if "id" in options or "user-id" in options:
90
+ raise RuntimeError("user update-info uses the authenticated identity; --id and --user-id are unsupported.")
91
+ if positionals or options.keys() - (fields.keys() | {"json", "body", "account"}):
92
+ raise RuntimeError("user update-info accepts only basic profile fields, --json, --body and --account.")
93
+ sources = options.keys() & {"json", "body"}
94
+ if sources:
95
+ if len(sources) != 1 or options.keys() & fields.keys():
96
+ raise RuntimeError("user update-info accepts either field flags, --json or --body; do not combine them.")
97
+ source = next(iter(sources))
98
+ value = options[source]
99
+ if not isinstance(value, str) or not value:
100
+ raise RuntimeError(f"user update-info --{source} requires a value.")
101
+ raw = value if source == "json" else (sys.stdin.read() if value == "-" else Path(value).read_text(encoding="utf-8"))
102
+ try:
103
+ info = json.loads(raw)
104
+ except json.JSONDecodeError as exc:
105
+ raise RuntimeError("user update-info body must be valid JSON.") from exc
106
+ else:
107
+ info = {}
108
+ for flag, field in fields.items():
109
+ if flag not in options:
110
+ continue
111
+ value = options[flag]
112
+ if not isinstance(value, str):
113
+ raise RuntimeError(f"user update-info --{flag} requires a value.")
114
+ if flag == "tags":
115
+ try:
116
+ value = json.loads(value)
117
+ except json.JSONDecodeError as exc:
118
+ raise RuntimeError("user update-info --tags requires a JSON string array.") from exc
119
+ info[field] = value
120
+ return validate_user_info(info)
121
+
122
+
123
+ def run_user_command(subcommand: str | None, argv: list[str], parse_options):
124
+ if subcommand not in {
125
+ "get",
126
+ "list",
127
+ "update-profile",
128
+ "update-info",
129
+ "update-ext",
130
+ "adjust-elements",
131
+ "get-growth-profile",
132
+ "init-growth-profile",
133
+ "set-academy",
134
+ }:
135
+ raise RuntimeError(f"Unknown user subcommand: {subcommand}")
136
+
137
+ options, positionals = parse_options(argv)
138
+ if subcommand == "update-info":
139
+ info = _parse_info_body(options, positionals)
140
+ elif subcommand == "update-ext":
141
+ ext = _parse_ext_body(options, positionals)
142
+ elif subcommand == "list":
143
+ list_all = "all" in options
144
+ list_random = "random" in options
145
+ if not list_all and not list_random:
146
+ raise RuntimeError("user list requires --all or --random.")
147
+ if list_all and list_random:
148
+ raise RuntimeError("user list accepts only one of --all or --random.")
149
+ fields = _parse_fields(options.get("fields"))
150
+ academy_code = None
151
+ if "academy-code" in options:
152
+ raw_academy_code = options["academy-code"]
153
+ academy_code = trim_string(raw_academy_code)
154
+ if raw_academy_code is True or not academy_code:
155
+ raise RuntimeError("user list --academy-code requires a value.")
156
+ elif subcommand == "get":
157
+ user_id = trim_string(options.get("id") or options.get("user-id"))
158
+ if not user_id:
159
+ raise RuntimeError("user get requires --id <userId>.")
160
+ elif subcommand in {"get-growth-profile", "init-growth-profile"}:
161
+ raw_user_id = options.get("id") or options.get("user-id")
162
+ user_id = trim_string(raw_user_id)
163
+ if raw_user_id is True or not user_id:
164
+ raise RuntimeError(f"user {subcommand} requires --id <userId>.")
165
+ if subcommand == "init-growth-profile":
166
+ try:
167
+ reset = parse_optional_bool(options.get("reset"), False)
168
+ except ValueError as exc:
169
+ raise RuntimeError(
170
+ "user init-growth-profile --reset must be true or false."
171
+ ) from exc
172
+ elif subcommand == "set-academy":
173
+ raw_user_id = options.get("id") or options.get("user-id")
174
+ user_id = trim_string(raw_user_id)
175
+ if raw_user_id is True or not user_id:
176
+ raise RuntimeError("user set-academy requires --id <userId>.")
177
+
178
+ raw_academy_code = options.get("academy-code") or options.get("academy")
179
+ if raw_academy_code is True or not trim_string(raw_academy_code):
180
+ raise RuntimeError(
181
+ "user set-academy requires --academy-code <code>."
182
+ )
183
+ try:
184
+ academy_code = normalize_academy_code(raw_academy_code)
185
+ except ValueError as exc:
186
+ raise RuntimeError(
187
+ "user set-academy --academy-code must be one of: "
188
+ f"{', '.join(ACADEMY_CODES)}."
189
+ ) from exc
190
+ elif subcommand == "update-profile":
191
+ user_id = trim_string(options.get("id") or options.get("user-id"))
192
+ if not user_id:
193
+ raise RuntimeError("user update-profile requires --id <userId>.")
194
+
195
+ has_nickname = "nickname" in options
196
+ has_avatar_url = "avatar-url" in options
197
+ if not has_nickname and not has_avatar_url:
198
+ raise RuntimeError(
199
+ "user update-profile requires --nickname <name> or --avatar-url <url>."
200
+ )
201
+ if options.get("nickname") is True:
202
+ raise RuntimeError("user update-profile --nickname requires a value.")
203
+ if options.get("avatar-url") is True:
204
+ raise RuntimeError("user update-profile --avatar-url requires a value.")
205
+
206
+ nickname = trim_string(options.get("nickname")) if has_nickname else None
207
+ avatar_url = trim_string(options.get("avatar-url")) if has_avatar_url else None
208
+ else:
209
+ raw_user_id = options.get("id") or options.get("user-id")
210
+ user_id = trim_string(raw_user_id)
211
+ if raw_user_id is True or not user_id:
212
+ raise RuntimeError("user adjust-elements requires --id <userId>.")
213
+ element_kwargs, adjustments = _parse_element_deltas(options)
214
+
215
+ root = read_config_root()
216
+ account = resolve_account_or_throw(root, options.get("account"))
217
+ client = MagicCampusClient(
218
+ MagicCampusClientConfig(
219
+ apiurl=account.apiurl,
220
+ apikey=account.apikey,
221
+ platform=account.platform,
222
+ )
223
+ )
224
+
225
+ if subcommand == "update-info":
226
+ kwargs = {("avatar_url" if key == "avatarUrl" else key): value for key, value in info.items()}
227
+ result = client.user.update_info(**kwargs)
228
+ return {"ok": True, "resource": "userInfo", "action": "update", "result": result}
229
+
230
+ if subcommand == "update-ext":
231
+ result = client.user.update_ext(ext)
232
+ return {
233
+ "ok": True,
234
+ "accountId": account.account_id,
235
+ "provider": "magiccampus",
236
+ "resource": "userExt",
237
+ "action": "update",
238
+ "transport": "http_api",
239
+ "result": result,
240
+ }
241
+
242
+ if subcommand == "list":
243
+ list_kwargs = {"academy_code": academy_code} if academy_code is not None else {}
244
+ users = (
245
+ client.user.list_random(**list_kwargs)
246
+ if list_random
247
+ else client.user.list_all(**list_kwargs)
248
+ )
249
+ return [
250
+ {field: payload.get(field) for field in fields} if fields is not None else payload
251
+ for payload in users
252
+ ]
253
+
254
+ if subcommand == "get-growth-profile":
255
+ return client.user.get_growth_profile(user_id)
256
+
257
+ if subcommand == "init-growth-profile":
258
+ result = client.user.init_growth_profile(user_id, reset=reset)
259
+ return {
260
+ "ok": True,
261
+ "userId": user_id,
262
+ "reset": reset,
263
+ "result": result,
264
+ }
265
+
266
+ if subcommand == "set-academy":
267
+ result = client.user.set_academy(user_id, academy_code)
268
+ return {
269
+ "ok": True,
270
+ "userId": user_id,
271
+ "academyCode": academy_code,
272
+ "result": result,
273
+ }
274
+
275
+ if subcommand == "update-profile":
276
+ print("Deprecated: use user update-info for current-user/owner fields; update-profile retains its explicit target.", file=sys.stderr)
277
+ result = client.user.update_profile(
278
+ user_id,
279
+ nickname=nickname,
280
+ avatar_url=avatar_url,
281
+ )
282
+ output = {
283
+ "ok": True,
284
+ "accountId": account.account_id,
285
+ "provider": "magiccampus",
286
+ "resource": "userProfile",
287
+ "action": "update",
288
+ "transport": "http_api",
289
+ "userId": user_id,
290
+ "result": result,
291
+ "magiccampus": {
292
+ "apiUrl": account.apiurl,
293
+ "platform": account.platform,
294
+ },
295
+ }
296
+ if nickname is not None:
297
+ output["nickname"] = nickname
298
+ if avatar_url is not None:
299
+ output["avatarUrl"] = avatar_url
300
+ return output
301
+
302
+ if subcommand == "adjust-elements":
303
+ result = client.user.adjust_elements(user_id, **element_kwargs)
304
+ return {
305
+ "ok": True,
306
+ "userId": user_id,
307
+ "adjustments": adjustments,
308
+ "result": result,
309
+ }
310
+
311
+ return client.user.get(user_id)
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from .utils import env_string
7
+
8
+
9
+ def get_magic_campus_home() -> Path:
10
+ configured = env_string("MAGIC_CAMPUS_HOME") or env_string("MUSHROOM_HOME")
11
+ if configured:
12
+ return Path(configured).expanduser()
13
+ return Path.home() / ".magic-campus"
14
+
15
+
16
+ def get_mushroom_home() -> Path:
17
+ return get_magic_campus_home()
18
+
19
+
20
+ def get_auth_home() -> Path:
21
+ return get_magic_campus_home() / "auth"
22
+
23
+
24
+ def get_runtime_data_dir() -> Path:
25
+ return get_magic_campus_home() / "data"
26
+
27
+
28
+ def get_config_path() -> Path:
29
+ return get_auth_home() / "magiccampus-im-sdk.json"
30
+
31
+
32
+ def normalize_config_root(raw: object) -> dict[str, object]:
33
+ source = raw if isinstance(raw, dict) else {}
34
+ accounts = source.get("accounts")
35
+ normalized_accounts = accounts if isinstance(accounts, dict) else {}
36
+ account_ids = list(normalized_accounts.keys())
37
+ preferred_default = str(source.get("defaultAccountId") or "").strip()
38
+ return {
39
+ "defaultAccountId": preferred_default or (account_ids[0] if account_ids else "default"),
40
+ "accounts": normalized_accounts,
41
+ }
42
+
43
+
44
+ def read_config_root() -> dict[str, object]:
45
+ path = get_config_path()
46
+ if not path.exists():
47
+ return normalize_config_root({})
48
+
49
+ try:
50
+ parsed = json.loads(path.read_text(encoding="utf-8"))
51
+ except Exception:
52
+ return normalize_config_root({})
53
+ return normalize_config_root(parsed)
54
+
55
+
56
+ def write_config_root(root: dict[str, object]) -> dict[str, object]:
57
+ normalized = normalize_config_root(root)
58
+ auth_home = get_auth_home()
59
+ auth_home.mkdir(parents=True, exist_ok=True)
60
+ get_config_path().write_text(json.dumps(normalized, ensure_ascii=False, indent=2), encoding="utf-8")
61
+ return normalized