thuthi-plugin 0.0.0-stage → 0.1.0

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 (115) hide show
  1. package/.claude-plugin/marketplace.json +55 -0
  2. package/README.md +13 -2
  3. package/bin/parallel-browser.js +109 -0
  4. package/extension/background.js +1329 -0
  5. package/extension/config.json +1 -0
  6. package/extension/guard.js +44 -0
  7. package/extension/manifest.json +10 -0
  8. package/extension/overlay.js +104 -0
  9. package/extension/popup.html +34 -0
  10. package/extension/popup.js +39 -0
  11. package/extension-reloader/manifest.json +13 -0
  12. package/extension-reloader/sw.js +17 -0
  13. package/package.json +13 -4
  14. package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
  15. package/plugins/thuthi/context.md +3 -0
  16. package/plugins/thuthi/hooks/hooks.json +15 -0
  17. package/plugins/thuthi/skills/setup/SKILL.md +55 -0
  18. package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
  19. package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
  20. package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
  21. package/plugins/thuthi/tools/legacy_launcher.py +65 -0
  22. package/plugins/thuthi/tools/statusline/statusline.py +8 -0
  23. package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
  24. package/plugins/thuthi-accounts/bin/claude-switch +5 -0
  25. package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
  26. package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
  27. package/plugins/thuthi-accounts/lib/tls.py +68 -0
  28. package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
  29. package/plugins/thuthi-accounts/setup_check.py +21 -0
  30. package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
  31. package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
  32. package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
  33. package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
  34. package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
  35. package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
  36. package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
  37. package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
  38. package/plugins/thuthi-agenda-picker/context.md +3 -0
  39. package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
  40. package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
  41. package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
  42. package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
  43. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
  44. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
  45. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
  46. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
  47. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
  48. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
  49. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
  50. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
  51. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
  52. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
  53. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
  54. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
  55. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
  56. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
  57. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
  58. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
  59. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
  60. package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
  61. package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
  62. package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
  63. package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
  64. package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
  65. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
  66. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
  67. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
  68. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
  69. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
  70. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
  71. package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
  72. package/plugins/thuthi-browser/context.md +3 -0
  73. package/plugins/thuthi-browser/hooks/hooks.json +15 -0
  74. package/plugins/thuthi-browser/lib/pbpage.py +397 -0
  75. package/plugins/thuthi-browser/setup_check.py +93 -0
  76. package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
  77. package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
  78. package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
  79. package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
  80. package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
  81. package/plugins/thuthi-demo-video/setup_check.py +14 -0
  82. package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
  83. package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
  84. package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
  85. package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
  86. package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
  87. package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
  88. package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
  89. package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
  90. package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
  91. package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
  92. package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
  93. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
  94. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
  95. package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
  96. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
  97. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
  98. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
  99. package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
  100. package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
  101. package/plugins/thuthi-orca/context.md +5 -0
  102. package/plugins/thuthi-orca/hooks/hooks.json +18 -0
  103. package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
  104. package/plugins/thuthi-orca/setup_check.py +12 -0
  105. package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
  106. package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
  107. package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
  108. package/runtime/client.js +69 -0
  109. package/runtime/daemon.js +503 -0
  110. package/runtime/focus-monitor.js +53 -0
  111. package/runtime/keys.js +86 -0
  112. package/runtime/owner.js +64 -0
  113. package/runtime/recorder.js +267 -0
  114. package/runtime/relay.js +95 -0
  115. package/runtime/session.js +1599 -0
@@ -0,0 +1,417 @@
1
+ """Claude Code 자격증명 저장소 (python3 3.9 표준 라이브러리만). OS 마다 Claude Code 가 쓰는 곳을 그대로 읽고 쓴다.
2
+
3
+ macOS Keychain 서비스 "Claude Code-credentials" (계정 = 로그인 사용자) `security` 명령
4
+ Linux 파일 <config>/.credentials.json (0600)
5
+ Windows 파일 %USERPROFILE%\\.claude\\.credentials.json (기본)
6
+ 자격 증명 관리자 Claude Code 의 실험 설정(tengu_windows_credman)이나 CLAUDE_CODE_FORCE_WINDOWS_CREDMAN=1
7
+ 이 켜진 PC. 2400자 조각(<name>#0 … #m)으로 나눠 저장한다. 읽을 때는 관리자에 있으면 그것을,
8
+ 없으면 파일을 쓴다 (Claude Code 도 같은 순서로 읽는다).
9
+
10
+ 저장 내용은 한 JSON 이다: {"claudeAiOauth": {accessToken, refreshToken, expiresAt, …}, (mcpOAuth 등 다른 키)}.
11
+ claude-switch 는 계정을 바꿀 때 claudeAiOauth 만 갈아 끼우고 나머지 키는 그대로 둔다.
12
+
13
+ 계정별 백업 (claude-switch 자신의 것):
14
+ macOS Keychain 서비스 "Claude Code-credentials-<email>" (예전 bash 판과 같은 자리)
15
+ 그 밖 파일 <state>/backups/<email>/credentials.json (0600)
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from contextlib import contextmanager
25
+ from pathlib import Path
26
+ from typing import Optional
27
+
28
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "lib"))
29
+ import usage_store as us # noqa: E402
30
+
31
+ # 시험은 CLAUDE_SWITCH_KC_SERVICE 로 다른 이름을 써서 진짜 자격증명을 건드리지 않는다
32
+ KC_SERVICE = os.environ.get("CLAUDE_SWITCH_KC_SERVICE") or "Claude Code-credentials"
33
+ CHUNK = 2400 # 자격 증명 관리자 조각 크기 (Claude Code 와 같다)
34
+ MAX_CHUNKS = 256
35
+
36
+
37
+ def config_dir() -> Path:
38
+ env = os.environ.get("CLAUDE_CONFIG_DIR")
39
+ return Path(env) if env else Path.home() / ".claude"
40
+
41
+
42
+ def claude_json_path() -> Path:
43
+ env = os.environ.get("CLAUDE_CONFIG_DIR")
44
+ return Path(env) / ".claude.json" if env else Path.home() / ".claude.json"
45
+
46
+
47
+ def load_json(path: Path) -> Optional[dict]:
48
+ try:
49
+ v = json.loads(path.read_text(encoding="utf-8"))
50
+ return v if isinstance(v, dict) else None
51
+ except (OSError, ValueError):
52
+ return None
53
+
54
+
55
+ def parse_blob(text: Optional[str]) -> Optional[dict]:
56
+ if not text:
57
+ return None
58
+ try:
59
+ v = json.loads(text)
60
+ except ValueError:
61
+ return None
62
+ return v if isinstance(v, dict) else None
63
+
64
+
65
+ def compact(data: dict) -> str:
66
+ return json.dumps(data, separators=(",", ":"), ensure_ascii=False)
67
+
68
+
69
+ def os_user() -> str:
70
+ for k in ("USER", "USERNAME", "LOGNAME"):
71
+ if os.environ.get(k):
72
+ return os.environ[k]
73
+ try:
74
+ import getpass
75
+ return getpass.getuser()
76
+ except Exception: # noqa: BLE001
77
+ return "user"
78
+
79
+
80
+ # ─── macOS Keychain ──────────────────────────────────────────────
81
+
82
+ class KeychainStore:
83
+ """`security` 명령으로 generic password 하나를 다룬다. CLAUDE_SWITCH_KEYCHAIN 이 있으면 그 keychain 파일만 쓴다 (시험용)."""
84
+
85
+ def __init__(self, service: str):
86
+ self.service = service
87
+ self.keychain = os.environ.get("CLAUDE_SWITCH_KEYCHAIN") or ""
88
+ self.label = f"Keychain: {service}"
89
+
90
+ def _kc(self) -> list:
91
+ return [self.keychain] if self.keychain else []
92
+
93
+ def get(self) -> Optional[dict]:
94
+ try:
95
+ r = subprocess.run(["security", "find-generic-password", "-s", self.service, "-w", *self._kc()],
96
+ capture_output=True, text=True, timeout=10)
97
+ except (OSError, subprocess.TimeoutExpired):
98
+ return None
99
+ raw = r.stdout.strip() if r.returncode == 0 else ""
100
+ # `security` 는 개행이 든 값을 hex 로 돌려준다 (예전 판이 남긴 값 복구용)
101
+ if raw and len(raw) % 2 == 0 and all(c in "0123456789abcdefABCDEF" for c in raw):
102
+ try:
103
+ raw = bytes.fromhex(raw).decode("utf-8")
104
+ except ValueError:
105
+ pass
106
+ return parse_blob(raw)
107
+
108
+ def set(self, data: dict) -> bool:
109
+ hexval = compact(data).encode("utf-8").hex()
110
+ kc = f' "{self.keychain}"' if self.keychain else ""
111
+ line = f'add-generic-password -U -a "{os_user()}" -s "{self.service}" -X {hexval}{kc}\n'
112
+ try:
113
+ if len(line) <= 4000:
114
+ # 값이 프로세스 인자에 드러나지 않게 stdin 으로 넘긴다 (Claude Code 도 같은 방식)
115
+ r = subprocess.run(["security", "-i"], input=line, capture_output=True, text=True, timeout=10)
116
+ else:
117
+ r = subprocess.run(["security", "add-generic-password", "-U", "-a", os_user(), "-s", self.service,
118
+ "-X", hexval, *self._kc()], capture_output=True, text=True, timeout=10)
119
+ except (OSError, subprocess.TimeoutExpired):
120
+ return False
121
+ return r.returncode == 0 and "error" not in (r.stderr or "").lower()
122
+
123
+ def delete(self) -> bool:
124
+ try:
125
+ r = subprocess.run(["security", "delete-generic-password", "-s", self.service, *self._kc()],
126
+ capture_output=True, text=True, timeout=10)
127
+ except (OSError, subprocess.TimeoutExpired):
128
+ return False
129
+ return r.returncode == 0
130
+
131
+
132
+ # ─── 파일 ────────────────────────────────────────────────────────
133
+
134
+ class FileStore:
135
+ def __init__(self, path: Path):
136
+ self.path = path
137
+ self.label = str(path)
138
+
139
+ def get(self) -> Optional[dict]:
140
+ try:
141
+ return parse_blob(self.path.read_text(encoding="utf-8"))
142
+ except (OSError, UnicodeDecodeError):
143
+ return None
144
+
145
+ def set(self, data: dict) -> bool:
146
+ try:
147
+ us.write_atomic(self.path, compact(data), mode=0o600)
148
+ return True
149
+ except OSError:
150
+ return False
151
+
152
+ def delete(self) -> bool:
153
+ try:
154
+ self.path.unlink()
155
+ return True
156
+ except FileNotFoundError:
157
+ return True
158
+ except OSError:
159
+ return False
160
+
161
+
162
+ # ─── Windows 자격 증명 관리자 ────────────────────────────────────
163
+
164
+ class _Credman:
165
+ """advapi32 CredReadW / CredWriteW / CredDeleteW / CredEnumerateW (generic credential)."""
166
+
167
+ CRED_TYPE_GENERIC = 1
168
+ CRED_PERSIST_LOCAL_MACHINE = 2
169
+ CRED_PERSIST_ENTERPRISE = 3
170
+ ERROR_NOT_FOUND = 1168
171
+
172
+ def __init__(self):
173
+ import ctypes
174
+ from ctypes import wintypes
175
+ self.ctypes = ctypes
176
+
177
+ class FILETIME(ctypes.Structure):
178
+ _fields_ = [("dwLowDateTime", wintypes.DWORD), ("dwHighDateTime", wintypes.DWORD)]
179
+
180
+ class CREDENTIALW(ctypes.Structure):
181
+ _fields_ = [("Flags", wintypes.DWORD), ("Type", wintypes.DWORD), ("TargetName", wintypes.LPWSTR),
182
+ ("Comment", wintypes.LPWSTR), ("LastWritten", FILETIME),
183
+ ("CredentialBlobSize", wintypes.DWORD), ("CredentialBlob", ctypes.POINTER(ctypes.c_ubyte)),
184
+ ("Persist", wintypes.DWORD), ("AttributeCount", wintypes.DWORD),
185
+ ("Attributes", ctypes.c_void_p), ("TargetAlias", wintypes.LPWSTR),
186
+ ("UserName", wintypes.LPWSTR)]
187
+
188
+ self.CREDENTIALW = CREDENTIALW
189
+ PCRED = ctypes.POINTER(CREDENTIALW)
190
+ a = ctypes.WinDLL("advapi32", use_last_error=True)
191
+ self.read_ = a.CredReadW
192
+ self.read_.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(PCRED)]
193
+ self.read_.restype = wintypes.BOOL
194
+ self.write_ = a.CredWriteW
195
+ self.write_.argtypes = [ctypes.POINTER(CREDENTIALW), wintypes.DWORD]
196
+ self.write_.restype = wintypes.BOOL
197
+ self.delete_ = a.CredDeleteW
198
+ self.delete_.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD]
199
+ self.delete_.restype = wintypes.BOOL
200
+ self.enum_ = a.CredEnumerateW
201
+ self.enum_.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD),
202
+ ctypes.POINTER(ctypes.POINTER(PCRED))]
203
+ self.enum_.restype = wintypes.BOOL
204
+ self.free = a.CredFree
205
+ self.free.argtypes = [ctypes.c_void_p]
206
+
207
+ @staticmethod
208
+ def decode(blob: bytes) -> str:
209
+ # Bun.secrets 는 UTF-8 로 쓴다. 다른 도구가 UTF-16 으로 쓴 값도 읽게 둘 다 본다
210
+ if len(blob) >= 2 and blob[1:2] == b"\x00":
211
+ try:
212
+ return blob.decode("utf-16-le")
213
+ except UnicodeDecodeError:
214
+ pass
215
+ return blob.decode("utf-8", "replace")
216
+
217
+ def read(self, target: str) -> Optional[str]:
218
+ ct = self.ctypes
219
+ p = ct.POINTER(self.CREDENTIALW)()
220
+ if not self.read_(target, self.CRED_TYPE_GENERIC, 0, ct.byref(p)):
221
+ return None
222
+ try:
223
+ c = p.contents
224
+ return self.decode(ct.string_at(c.CredentialBlob, c.CredentialBlobSize))
225
+ finally:
226
+ self.free(p)
227
+
228
+ def write(self, target: str, user: str, value: str) -> bool:
229
+ ct = self.ctypes
230
+ blob = value.encode("utf-8")
231
+ buf = (ct.c_ubyte * len(blob)).from_buffer_copy(blob)
232
+ c = self.CREDENTIALW()
233
+ c.Type = self.CRED_TYPE_GENERIC
234
+ c.TargetName = target
235
+ c.CredentialBlobSize = len(blob)
236
+ c.CredentialBlob = ct.cast(buf, ct.POINTER(ct.c_ubyte))
237
+ c.Persist = self.CRED_PERSIST_ENTERPRISE
238
+ c.UserName = user
239
+ return bool(self.write_(ct.byref(c), 0))
240
+
241
+ def delete(self, target: str) -> bool:
242
+ if self.delete_(target, self.CRED_TYPE_GENERIC, 0):
243
+ return True
244
+ return self.ctypes.get_last_error() == self.ERROR_NOT_FOUND
245
+
246
+ def targets(self, filt: str) -> list:
247
+ ct = self.ctypes
248
+ from ctypes import wintypes
249
+ n = wintypes.DWORD()
250
+ arr = ct.POINTER(ct.POINTER(self.CREDENTIALW))()
251
+ if not self.enum_(filt, 0, ct.byref(n), ct.byref(arr)):
252
+ return []
253
+ try:
254
+ return [arr[i].contents.TargetName for i in range(n.value)]
255
+ finally:
256
+ self.free(arr)
257
+
258
+
259
+ class CredmanStore:
260
+ """Claude Code(Bun.secrets) 가 쓰는 형식: TargetName "<service>/<name>", 조각 "<name>#0" … "<name>#(n-1)",
261
+ 메타 "<name>#m" = {"n":조각 수,"l":전체 길이}. 쓸 때는 늘 조각으로 쓰고 바탕 이름은 지운다 (Claude Code 와 같다)."""
262
+
263
+ def __init__(self, service: str, name: str):
264
+ self.service, self.name = service, name
265
+ self.cm = _Credman()
266
+ self.label = f"자격 증명 관리자: {service}/{name}"
267
+
268
+ def _t(self, suffix: str = "") -> str:
269
+ return f"{self.service}/{self.name}{suffix}"
270
+
271
+ def get(self) -> Optional[dict]:
272
+ whole = self.cm.read(self._t())
273
+ if whole:
274
+ return parse_blob(whole)
275
+ meta = parse_blob(self.cm.read(self._t("#m")))
276
+ if not meta:
277
+ return None
278
+ n, total = us.to_int(meta.get("n")), us.to_int(meta.get("l"))
279
+ if not (0 < n <= MAX_CHUNKS):
280
+ return None
281
+ parts = []
282
+ for i in range(n):
283
+ part = self.cm.read(self._t(f"#{i}"))
284
+ if part is None:
285
+ return None
286
+ parts.append(part)
287
+ text = "".join(parts)
288
+ return parse_blob(text) if len(text) == total else None
289
+
290
+ def _old_n(self) -> int:
291
+ meta = parse_blob(self.cm.read(self._t("#m"))) or {}
292
+ return us.to_int(meta.get("n"))
293
+
294
+ def set(self, data: dict) -> bool:
295
+ text = compact(data)
296
+ chunks = [text[i:i + CHUNK] for i in range(0, len(text), CHUNK)] or [""]
297
+ if len(chunks) > MAX_CHUNKS:
298
+ return False
299
+ old_n = self._old_n()
300
+ ok = self.cm.write(self._t("#p"), self.name, str(max(old_n, len(chunks))))
301
+ for i, part in enumerate(chunks):
302
+ ok = self.cm.write(self._t(f"#{i}"), self.name, part) and ok
303
+ ok = self.cm.write(self._t("#m"), self.name, json.dumps({"n": len(chunks), "l": len(text)})) and ok
304
+ if not ok:
305
+ return False
306
+ self.cm.delete(self._t())
307
+ for i in range(len(chunks), old_n):
308
+ self.cm.delete(self._t(f"#{i}"))
309
+ self.cm.delete(self._t("#p"))
310
+ return True
311
+
312
+ def delete(self) -> bool:
313
+ n = max(self._old_n(), 0)
314
+ ok = self.cm.delete(self._t())
315
+ for i in range(n):
316
+ ok = self.cm.delete(self._t(f"#{i}")) and ok
317
+ self.cm.delete(self._t("#m"))
318
+ self.cm.delete(self._t("#p"))
319
+ return ok
320
+
321
+
322
+ def windows_credman_enabled() -> bool:
323
+ if os.environ.get("CLAUDE_CODE_FORCE_WINDOWS_CREDMAN") == "1":
324
+ return True
325
+ cj = load_json(claude_json_path()) or {}
326
+ return (cj.get("cachedGrowthBookFeatures") or {}).get("tengu_windows_credman") is True
327
+
328
+
329
+ class FirstOfStore:
330
+ """여럿 중 값이 있는 첫 저장소를 읽고, 거기에 쓴다 (모두 비었으면 첫 저장소). Claude Code 의 '<a>-with-<b>-fallback' 과 같다."""
331
+
332
+ def __init__(self, stores: list):
333
+ self.stores = stores
334
+
335
+ def _pick(self):
336
+ for s in self.stores:
337
+ if s.get() is not None:
338
+ return s
339
+ return self.stores[0]
340
+
341
+ @property
342
+ def label(self) -> str:
343
+ return self._pick().label
344
+
345
+ def get(self) -> Optional[dict]:
346
+ for s in self.stores:
347
+ v = s.get()
348
+ if v is not None:
349
+ return v
350
+ return None
351
+
352
+ def set(self, data: dict) -> bool:
353
+ return self._pick().set(data)
354
+
355
+ def delete(self) -> bool:
356
+ return all([s.delete() for s in self.stores])
357
+
358
+
359
+ # ─── 고르기 ──────────────────────────────────────────────────────
360
+
361
+ def backend() -> str:
362
+ """CLAUDE_SWITCH_STORE=file|keychain 으로 덮을 수 있다 (시험용)."""
363
+ env = os.environ.get("CLAUDE_SWITCH_STORE")
364
+ if env:
365
+ return env
366
+ return "keychain" if sys.platform == "darwin" else "file"
367
+
368
+
369
+ def active_store():
370
+ if backend() == "keychain":
371
+ return KeychainStore(KC_SERVICE)
372
+ file_store = FileStore(config_dir() / ".credentials.json")
373
+ if sys.platform == "win32" and windows_credman_enabled():
374
+ return FirstOfStore([CredmanStore(KC_SERVICE, os_user()), file_store])
375
+ return file_store
376
+
377
+
378
+ def backup_store(email: str):
379
+ if backend() == "keychain":
380
+ return KeychainStore(f"{KC_SERVICE}-{email}")
381
+ return FileStore(us.backup_dir() / email / "credentials.json")
382
+
383
+
384
+ # ─── Claude Code 와 같은 쓰기 락 (proper-lockfile: <config>/.storage-write.lock 디렉터리, 15초면 낡은 것) ──
385
+
386
+ @contextmanager
387
+ def storage_lock(timeout: float = 3.0, stale: float = 15.0):
388
+ lock = config_dir() / ".storage-write.lock"
389
+ held = False
390
+ try:
391
+ lock.parent.mkdir(parents=True, exist_ok=True)
392
+ except OSError:
393
+ pass
394
+ deadline = time.time() + timeout
395
+ while time.time() < deadline:
396
+ try:
397
+ os.mkdir(lock)
398
+ held = True
399
+ break
400
+ except FileExistsError:
401
+ try:
402
+ if time.time() - lock.stat().st_mtime > stale:
403
+ os.rmdir(lock)
404
+ continue
405
+ except OSError:
406
+ pass
407
+ time.sleep(0.2)
408
+ except OSError:
409
+ break
410
+ try:
411
+ yield held
412
+ finally:
413
+ if held:
414
+ try:
415
+ os.rmdir(lock)
416
+ except OSError:
417
+ pass