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,338 @@
1
+ #!/usr/bin/env python3
2
+ """Orca agent-teams tmux shim 감싸기: 팀원 칸을 "팀장 1줄 + 한 줄에 4명" 으로 나눈다.
3
+
4
+ Orca `claude-teams` 팀장 세션에서 hooks/orca-team-grid.ts 가 이 폴더를 PATH 맨 앞에 붙이면,
5
+ Claude Code 가 팀원 칸을 만들려고 부르는 `tmux` 가 여기로 온다. 칸 나누기(split-window)만 바꾸고
6
+ 나머지는 Orca shim(`$ORCA_AGENT_TEAMS_SHIM_BIN agent-teams-tmux`) 에 그대로 넘긴다.
7
+
8
+ - 새 줄은 팀장 바로 아래에 생긴다 (Orca 는 칸 하나만 나눌 수 있고 크기를 못 정한다): 6명이면 팀장 / 2명 / 4명.
9
+ - 한 줄 4칸은 반씩 두 번 나눠 같은 폭이 된다 (보이는 순서 1, 3, 2, 4).
10
+ - Orca 는 tmux 와 방향 이름이 반대로 보인다: 새 줄(위아래)은 -h, 같은 줄 옆 칸은 -h 없이.
11
+ - 무엇이든 실패하면 원래 요청을 그대로 넘긴다 (팀원 생성이 막히지 않는다).
12
+
13
+ 상태 · 로그: $ORCA_TEAM_GRID_HOME (기본 ~/.local/share/orca-team-grid)
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+ import time
20
+
21
+ PER_ROW = 4
22
+
23
+ HOME = os.environ.get('ORCA_TEAM_GRID_HOME') or os.path.expanduser('~/.local/share/orca-team-grid')
24
+ LOG = os.path.join(HOME, 'tmux.log')
25
+
26
+ shim = os.environ.get('ORCA_AGENT_TEAMS_SHIM_BIN', '')
27
+ orig = sys.argv[1:]
28
+ T0 = time.time()
29
+
30
+
31
+ def log(*parts):
32
+ try:
33
+ os.makedirs(HOME, exist_ok=True)
34
+ if os.path.exists(LOG) and os.path.getsize(LOG) > 1_000_000:
35
+ os.replace(LOG, LOG + '.1')
36
+ with open(LOG, 'a') as f:
37
+ f.write(' '.join(str(p) for p in parts) + '\n')
38
+ except Exception:
39
+ pass
40
+
41
+
42
+ def passthrough():
43
+ os.execv(shim, [shim, 'agent-teams-tmux'] + orig)
44
+
45
+
46
+ if not shim:
47
+ sys.stderr.write('orca-team-grid: ORCA_AGENT_TEAMS_SHIM_BIN 이 없다 (Orca claude-teams 밖)\n')
48
+ sys.exit(127)
49
+ if os.environ.get('ORCA_TEAM_GRID') != '1':
50
+ passthrough()
51
+
52
+ # tmux 전역 옵션(-S 소켓, -L 이름)은 명령 앞에 온다
53
+ args, glob = list(orig), []
54
+ while len(args) > 1 and args[0] in ('-S', '-L'):
55
+ glob += args[:2]
56
+ args = args[2:]
57
+ real = [shim, 'agent-teams-tmux'] + glob
58
+ cmd = args[0] if args else ''
59
+
60
+ # main-vertical 로 바꾸려는 요청은 무시 (Orca 가 팀원을 오른쪽 기둥에 쌓게 된다)
61
+ if cmd == 'select-layout':
62
+ sys.exit(0)
63
+ if cmd not in ('split-window', 'splitw', '__reap__', 'respawn-pane', 'respawnp'):
64
+ passthrough()
65
+
66
+
67
+ def parse(rest_args):
68
+ value = {'-c', '-F', '-l', '-t', '-e'}
69
+ opts, flags, rest = {}, set(), []
70
+ i = 0
71
+ while i < len(rest_args):
72
+ a = rest_args[i]
73
+ if a == '--':
74
+ rest = rest_args[i:]
75
+ break
76
+ if a in value and i + 1 < len(rest_args):
77
+ opts[a] = rest_args[i + 1]
78
+ i += 2
79
+ continue
80
+ if a.startswith('-') and len(a) > 1:
81
+ flags.update('-' + ch for ch in a[1:])
82
+ i += 1
83
+ continue
84
+ rest = rest_args[i:]
85
+ break
86
+ return opts, flags, rest
87
+
88
+
89
+ # split 이 실패한 뒤 늦게 생기는 칸을 기다리는 시간, 실패 뒤 정리 작업이 유령 칸을 지켜보는 시간 (초)
90
+ # 앞 팀원 칸이 respawn(진짜 명령으로 바뀜)을 마칠 때까지 다음 split 을 기다리는 최대 시간 (초)
91
+ RESPAWN_WAIT = float(os.environ.get('ORCA_TEAM_GRID_RESPAWN_WAIT', '30'))
92
+ GHOST_WAIT = float(os.environ.get('ORCA_TEAM_GRID_GHOST_WAIT', '8'))
93
+ REAP_FOR = float(os.environ.get('ORCA_TEAM_GRID_REAP_FOR', '60'))
94
+ REAP_EVERY = float(os.environ.get('ORCA_TEAM_GRID_REAP_EVERY', '2'))
95
+
96
+
97
+ def num(pane):
98
+ try:
99
+ return int(pane.lstrip('%'))
100
+ except ValueError:
101
+ return -1
102
+
103
+
104
+ def list_panes():
105
+ out = subprocess.run(real + ['list-panes', '-t', '@0', '-F', '#{pane_id}'], capture_output=True, text=True)
106
+ if out.returncode != 0:
107
+ return None
108
+ return [p for p in out.stdout.split() if p.startswith('%')]
109
+
110
+
111
+ def unknown_panes(state, leader):
112
+ """실패가 난 뒤에 생겼고 아직 아무 자리에도 없는 칸 (= Orca 가 늦게 만든 유령 칸)."""
113
+ floor = state.get('ghost_floor')
114
+ if floor is None:
115
+ return []
116
+ known = {leader, *state.get('killed', []), *(p for r in state['rows'] for p in r)}
117
+ panes = list_panes() or []
118
+ return sorted((p for p in panes if p not in known and num(p) > floor), key=num)
119
+
120
+
121
+ def kill(state, panes, team):
122
+ for p in panes:
123
+ subprocess.run(real + ['kill-pane', '-t', p], capture_output=True)
124
+ state.setdefault('killed', []).append(p)
125
+ log(team, 'kill ghost', p)
126
+
127
+
128
+ class Locked:
129
+ def __init__(self, team):
130
+ import fcntl
131
+ self.fcntl = fcntl
132
+ os.makedirs(os.path.join(HOME, 'state'), exist_ok=True)
133
+ self.path = os.path.join(HOME, 'state', f'{team}.json')
134
+
135
+ def __enter__(self):
136
+ self.lock = open(self.path + '.lock', 'w')
137
+ self.fcntl.flock(self.lock, self.fcntl.LOCK_EX)
138
+ try:
139
+ with open(self.path) as f:
140
+ self.state = json.load(f)
141
+ except Exception:
142
+ self.state = {'rows': []}
143
+ return self.state
144
+
145
+ def save(self):
146
+ with open(self.path, 'w') as f:
147
+ json.dump(self.state, f)
148
+
149
+ def __exit__(self, *exc):
150
+ self.lock.close()
151
+
152
+
153
+ def place(state, pane, new_row):
154
+ if new_row:
155
+ state['rows'].append([pane])
156
+ else:
157
+ state['rows'][-1].append(pane)
158
+
159
+
160
+ def start_reaper():
161
+ try:
162
+ subprocess.Popen([sys.executable, os.path.abspath(__file__)] + glob + ['__reap__'],
163
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
164
+ start_new_session=True)
165
+ except Exception as e:
166
+ log('reaper start failed', repr(e))
167
+
168
+
169
+ def reap(team, leader):
170
+ """실패 뒤 다음 요청이 없을 때(마지막 팀원 등) 늦게 생긴 유령 칸을 닫는다.
171
+ 실패한 자리가 아직 비어 있으면(pending) Claude 의 재시도가 그 칸을 쓰도록 남겨 둔다."""
172
+ deadline = time.time() + REAP_FOR
173
+ while time.time() < deadline:
174
+ time.sleep(REAP_EVERY)
175
+ db = Locked(team)
176
+ with db as state:
177
+ if state.get('pending') is not None:
178
+ continue
179
+ ghosts = unknown_panes(state, leader)
180
+ if ghosts:
181
+ kill(state, ghosts, team)
182
+ db.save()
183
+
184
+
185
+ def respawn():
186
+ """Orca 의 respawn-pane 은 칸을 닫고 처음 나눈 칸에서 다시 나눈다. 그 사이 그 칸이나 그 부모가
187
+ 다음 split 의 대상이 되면 칸 나무가 틀어진다: respawn 이 끝났다고 적어서 다음 split 이 기다리게 한다."""
188
+ team = os.environ.get('ORCA_AGENT_TEAMS_TEAM_ID', 'default')
189
+ opts, _flags, _rest = parse(args[1:])
190
+ pane = opts.get('-t', '')
191
+ out = subprocess.run(real + args, capture_output=True, text=True)
192
+ db = Locked(team)
193
+ with db as state:
194
+ waiting = state.get('await_respawn', [])
195
+ if pane in waiting:
196
+ waiting.remove(pane)
197
+ db.save()
198
+ log(team, 'respawn', pane, '->', out.returncode, f'total={int((time.time() - T0) * 1000)}ms',
199
+ out.stderr.strip()[:200])
200
+ sys.stdout.write(out.stdout)
201
+ sys.stderr.write(out.stderr)
202
+ sys.exit(out.returncode)
203
+
204
+
205
+ def split():
206
+ opts, flags, rest = parse(args[1:])
207
+ team = os.environ.get('ORCA_AGENT_TEAMS_TEAM_ID', 'default')
208
+ leader = os.environ.get('ORCA_AGENT_TEAMS_LEADER_PANE', '%1')
209
+
210
+ # Orca 의 respawn-pane 은 칸을 닫고 처음 나눈 칸(부모)에서 다시 나눈다. 그래서 이번에 나눌 칸이
211
+ # (a) 아직 respawn 전이거나 (b) respawn 전인 칸의 부모이면 칸 나무가 틀어진다: 그때만 기다린다.
212
+ db = Locked(team)
213
+ deadline = time.time() + RESPAWN_WAIT
214
+ while True:
215
+ state = db.__enter__()
216
+ n = sum(len(r) for r in state['rows'])
217
+ row, col = divmod(n, PER_ROW)
218
+ new_row = col == 0
219
+ # 한 줄 4칸: 0 | 0→1 | 0→2 | 1→3
220
+ if new_row:
221
+ target = leader
222
+ elif col in (1, 2):
223
+ target = state['rows'][row][0]
224
+ else:
225
+ target = state['rows'][row][1]
226
+ waiting = state.get('await_respawn', [])
227
+ parents = state.get('parent', {})
228
+ blockers = [p for p in waiting if p == target or parents.get(p) == target]
229
+ if not blockers:
230
+ break
231
+ if time.time() > deadline:
232
+ log(team, 'respawn wait timed out', blockers)
233
+ state['await_respawn'] = [p for p in waiting if p not in blockers]
234
+ db.save()
235
+ break
236
+ db.__exit__(None, None, None)
237
+ time.sleep(0.1)
238
+ waited = int((time.time() - T0) * 1000)
239
+
240
+ try:
241
+ # 앞서 실패한 split 이 늦게 만든 칸: 그 자리가 아직 비어 있으면 쓰고, 아니면 닫는다
242
+ ghosts = unknown_panes(state, leader)
243
+ pane = None
244
+ if ghosts and state.get('pending') == n:
245
+ pane, ghosts = ghosts[0], ghosts[1:]
246
+ log(team, 'slot', n, 'adopt late pane', pane)
247
+ if ghosts:
248
+ kill(state, ghosts, team)
249
+
250
+ if pane is None:
251
+ new = ['split-window', '-P', '-F', '#{pane_id}', '-t', target]
252
+ if new_row:
253
+ new.append('-h')
254
+ # 팀장을 -h 로 나누면 Orca 가 main-vertical 규칙을 켠다: 앞뒤로 꺼 둔다
255
+ subprocess.run(real + ['select-layout', 'tiled'], capture_output=True)
256
+ for f in sorted(flags - {'-h', '-v', '-P', '-b', '-f'}):
257
+ new.append(f)
258
+ for k in ('-c', '-e'):
259
+ if k in opts:
260
+ new += [k, opts[k]]
261
+ new += rest
262
+
263
+ t_orca = time.time()
264
+ out = subprocess.run(real + new, capture_output=True, text=True)
265
+ orca_ms = int((time.time() - t_orca) * 1000)
266
+ if new_row:
267
+ subprocess.run(real + ['select-layout', 'tiled'], capture_output=True)
268
+ got = out.stdout.strip()
269
+ log(team, 'slot', n, 'row', row, 'col', col, 'target', target, '->', out.returncode, got,
270
+ f'orca={orca_ms}ms', out.stderr.strip()[:200])
271
+
272
+ if out.returncode == 0 and got.startswith('%'):
273
+ pane = got
274
+ else:
275
+ # 실패라고 답해도 Orca 가 칸을 늦게 만들 수 있다: 이 뒤에 생긴 칸만 유령 후보
276
+ known = [leader, *state.get('killed', []), *(p for r in state['rows'] for p in r)]
277
+ floor = max(num(p) for p in known)
278
+ state['ghost_floor'] = min(state.get('ghost_floor', floor), floor)
279
+ state['pending'] = n
280
+ deadline = time.time() + GHOST_WAIT
281
+ while time.time() < deadline:
282
+ time.sleep(0.5)
283
+ late = unknown_panes(state, leader)
284
+ if late:
285
+ pane, extra = late[0], late[1:]
286
+ log(team, 'slot', n, 'adopt late pane', pane)
287
+ if extra:
288
+ kill(state, extra, team)
289
+ break
290
+
291
+ if pane is None:
292
+ # 원래 요청으로 다시 나누지 않는다 (엉뚱한 자리에 칸이 생긴다): 실패를 Claude 에 돌려준다
293
+ db.save()
294
+ start_reaper()
295
+ sys.stderr.write((out.stderr or 'orca-team-grid: split failed') + '\n')
296
+ sys.exit(out.returncode or 1)
297
+
298
+ place(state, pane, new_row)
299
+ state.pop('pending', None)
300
+ state.setdefault('parent', {})[pane] = target
301
+ if 'cat' in rest: # Claude Code 는 cat 칸을 만든 뒤 바로 respawn-pane 으로 진짜 명령을 띄운다
302
+ state.setdefault('await_respawn', []).append(pane)
303
+ db.save()
304
+ log(team, 'slot', n, 'done', pane, f'waited={waited}ms', f'total={int((time.time() - T0) * 1000)}ms')
305
+ finally:
306
+ db.__exit__(None, None, None)
307
+
308
+ if '-P' in flags:
309
+ fmt = opts.get('-F', '#{pane_id}')
310
+ if fmt == '#{pane_id}':
311
+ sys.stdout.write(pane + '\n')
312
+ else:
313
+ shown = subprocess.run(real + ['display-message', '-p', '-t', pane, fmt], capture_output=True, text=True)
314
+ sys.stdout.write(shown.stdout)
315
+ return pane
316
+
317
+
318
+ if cmd in ('respawn-pane', 'respawnp'):
319
+ try:
320
+ respawn()
321
+ except SystemExit:
322
+ raise
323
+ except Exception as e:
324
+ log('error', repr(e), json.dumps(orig))
325
+ passthrough()
326
+
327
+ if cmd == '__reap__':
328
+ reap(os.environ.get('ORCA_AGENT_TEAMS_TEAM_ID', 'default'), os.environ.get('ORCA_AGENT_TEAMS_LEADER_PANE', '%1'))
329
+ sys.exit(0)
330
+
331
+ try:
332
+ split()
333
+ except SystemExit:
334
+ raise
335
+ except Exception as e:
336
+ # 이 스크립트 자체의 버그: 팀원 생성이 막히지 않게 원래 요청을 넘긴다 (배치는 Orca 기본)
337
+ log('error', repr(e), json.dumps(orig))
338
+ passthrough()
@@ -0,0 +1,299 @@
1
+ #!/usr/bin/env python3
2
+ """orca-team-grid 의 tmux 감싸기를 가짜 Orca shim 으로 돌려 본다 (macOS · Linux, Windows 는 건너뛴다).
3
+
4
+ python3 tests/selftest.py exit 0 = 통과
5
+
6
+ 가짜 shim 은 칸 목록을 파일로 들고 split-window · list-panes · kill-pane 에 답한다. FAKE_FAIL 로
7
+ Orca 가 시간 초과를 내는 경우(칸을 만들고 실패라고 답함 / 늦게 만듦 / 안 만듦)를 흉내 낸다.
8
+ 진짜 Orca 는 건드리지 않는다.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ import tempfile
17
+ import time
18
+ from pathlib import Path
19
+
20
+ HERE = Path(__file__).resolve().parent
21
+ TMUX = HERE.parent / "bin" / "tmux"
22
+ FAILS: list = []
23
+
24
+ FAKE_SHIM = r'''#!/usr/bin/env python3
25
+ import fcntl, json, os, subprocess, sys, time
26
+ d = os.environ["FAKE_DIR"]
27
+ _lock = open(os.path.join(d, "fake.lock"), "w")
28
+ panes_path = os.path.join(d, "panes.json")
29
+ args = sys.argv[1:]
30
+ with open(os.path.join(d, "rec.jsonl"), "a") as f:
31
+ f.write(json.dumps(args) + "\n")
32
+
33
+ def load():
34
+ try:
35
+ return json.load(open(panes_path))
36
+ except Exception:
37
+ return {"panes": ["%1"], "next": 2}
38
+
39
+ def save(st):
40
+ json.dump(st, open(panes_path, "w"))
41
+
42
+ def create():
43
+ fcntl.flock(_lock, fcntl.LOCK_EX) # 늦게 만드는 칸과 split 이 동시에 와도 칸 목록이 엉키지 않게
44
+ st = load()
45
+ p = "%" + str(st["next"])
46
+ st["next"] += 1
47
+ st["panes"].append(p)
48
+ save(st)
49
+ fcntl.flock(_lock, fcntl.LOCK_UN)
50
+ return p
51
+
52
+ rest = args[1:]
53
+ while len(rest) > 1 and rest[0] in ("-S", "-L"):
54
+ rest = rest[2:]
55
+ cmd = rest[0] if rest else ""
56
+ if cmd == "__late__":
57
+ time.sleep(float(rest[1]))
58
+ create()
59
+ elif cmd == "split-window":
60
+ mode_path = os.path.join(d, "fail")
61
+ mode = open(mode_path).read().strip() if os.path.exists(mode_path) else ""
62
+ if mode:
63
+ os.remove(mode_path) # 한 번만
64
+ if mode == "created":
65
+ create()
66
+ elif mode.startswith("late:"):
67
+ subprocess.Popen([sys.executable, __file__, "agent-teams-tmux", "__late__", mode[5:]], start_new_session=True,
68
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
69
+ sys.stderr.write("Timed out waiting for the Orca runtime to respond.")
70
+ sys.exit(1)
71
+ print(create())
72
+ elif cmd == "list-panes":
73
+ print("\n".join(load()["panes"]))
74
+ elif cmd == "kill-pane":
75
+ fcntl.flock(_lock, fcntl.LOCK_EX)
76
+ st = load()
77
+ t = rest[rest.index("-t") + 1]
78
+ st["panes"] = [p for p in st["panes"] if p != t]
79
+ save(st)
80
+ '''
81
+
82
+
83
+ def check(cond: bool, what: str, detail: str = "") -> None:
84
+ print((" ok " if cond else " FAIL ") + what + ("" if cond else f"\n {detail}"), flush=True)
85
+ if not cond:
86
+ FAILS.append(what)
87
+
88
+
89
+ class Fake:
90
+ def __init__(self, root: Path, team: str):
91
+ self.dir = root / team
92
+ self.dir.mkdir()
93
+ shim = root / "fake-orca"
94
+ if not shim.exists():
95
+ shim.write_text(FAKE_SHIM)
96
+ shim.chmod(0o755)
97
+ self.env = dict(os.environ)
98
+ self.env.update({
99
+ "ORCA_AGENT_TEAMS_SHIM_BIN": str(shim),
100
+ "ORCA_AGENT_TEAMS_TEAM_ID": team,
101
+ "ORCA_AGENT_TEAMS_LEADER_PANE": "%1",
102
+ "ORCA_TEAM_GRID_HOME": str(root / "home"),
103
+ "ORCA_TEAM_GRID": "1",
104
+ "ORCA_TEAM_GRID_GHOST_WAIT": "2",
105
+ "ORCA_TEAM_GRID_REAP_FOR": "4",
106
+ "ORCA_TEAM_GRID_REAP_EVERY": "0.3",
107
+ "ORCA_TEAM_GRID_RESPAWN_WAIT": "0.3",
108
+ "FAKE_DIR": str(self.dir),
109
+ })
110
+ self.sock = ["-S", f"/tmp/orca-claude-agent-teams/{team}"]
111
+ self.state = root / "home" / "state" / f"{team}.json"
112
+
113
+ def run(self, *args: str, **extra: str) -> subprocess.CompletedProcess:
114
+ return subprocess.run([sys.executable, str(TMUX), *args], env={**self.env, **extra},
115
+ capture_output=True, text=True)
116
+
117
+ def split(self) -> subprocess.CompletedProcess:
118
+ return self.run(*self.sock, "split-window", "-d", "-t", "%1", "-h", "-l", "70%",
119
+ "-P", "-F", "#{pane_id}", "--", "cat")
120
+
121
+ def fail_next(self, mode: str) -> None:
122
+ (self.dir / "fail").write_text(mode)
123
+
124
+ def calls(self) -> list:
125
+ rec = self.dir / "rec.jsonl"
126
+ if not rec.exists():
127
+ return []
128
+ out = [json.loads(line) for line in rec.read_text().splitlines()]
129
+ rec.unlink()
130
+ return out
131
+
132
+ def panes(self) -> list:
133
+ return json.load(open(self.dir / "panes.json"))["panes"]
134
+
135
+ def rows(self) -> list:
136
+ return json.load(open(self.state))["rows"]
137
+
138
+
139
+ def main() -> int:
140
+ if os.name == "nt":
141
+ print("Windows 는 Orca agent-teams 가 tmux shim 을 쓰지 않아 건너뛴다")
142
+ return 0
143
+
144
+ with tempfile.TemporaryDirectory() as tmp:
145
+ root = Path(tmp)
146
+
147
+ print("split-window 6번: 팀장 / 2명 / 4명")
148
+ f = Fake(root, "team-basic")
149
+ want = [("%1", True), ("%2", False), ("%2", False), ("%3", False), ("%1", True), ("%6", False)]
150
+ for i, (target, new_row) in enumerate(want):
151
+ got = f.split()
152
+ check(got.returncode == 0 and got.stdout.strip() == f"%{i + 2}", f"{i + 1}번째 칸 id %{i + 2}",
153
+ f"rc={got.returncode} out={got.stdout!r} err={got.stderr!r}")
154
+ sent = [c for c in f.calls() if "split-window" in c]
155
+ check(len(sent) == 1, f"{i + 1}번째: Orca 에 split 한 번", str(sent))
156
+ s = sent[0] if sent else []
157
+ check(s[1:3] == f.sock, f"{i + 1}번째: -S 소켓 유지", str(s))
158
+ check("-t" in s and s[s.index("-t") + 1] == target, f"{i + 1}번째: 대상 {target}", str(s))
159
+ check(("-h" in s) == new_row, f"{i + 1}번째: {'새 줄(-h)' if new_row else '옆 칸(-h 없음)'}", str(s))
160
+ check(s[-2:] == ["--", "cat"] and "-l" not in s, f"{i + 1}번째: 실행 명령 '-- cat' 유지, -l 버림", str(s))
161
+ check(f.rows() == [["%2", "%3", "%4", "%5"], ["%6", "%7"]], "상태: 4명 줄 + 2명 줄", str(f.rows()))
162
+
163
+ print("select-layout 은 무시, 다른 명령은 그대로")
164
+ got = f.run(*f.sock, "select-layout", "-t", "@0", "main-vertical")
165
+ check(got.returncode == 0 and f.calls() == [], "select-layout main-vertical 버림")
166
+ f.run(*f.sock, "list-panes", "-t", "@0", "-F", "#{pane_id}")
167
+ check(f.calls() == [["agent-teams-tmux", *f.sock, "list-panes", "-t", "@0", "-F", "#{pane_id}"]],
168
+ "list-panes 그대로 넘김")
169
+
170
+ print("ORCA_TEAM_GRID 가 1 이 아니면 split 도 그대로")
171
+ f.run(*f.sock, "split-window", "-d", "-t", "%2", "-v", "--", "cat", ORCA_TEAM_GRID="0")
172
+ check(f.calls()[-1] == ["agent-teams-tmux", *f.sock, "split-window", "-d", "-t", "%2", "-v", "--", "cat"],
173
+ "꺼져 있으면 원래 요청 그대로")
174
+
175
+ print("시간 초과인데 칸은 만들어짐: 그 칸을 이 자리로 쓴다")
176
+ f = Fake(root, "team-created")
177
+ for _ in range(3):
178
+ f.split()
179
+ f.fail_next("created")
180
+ f.calls()
181
+ got = f.split()
182
+ check(got.returncode == 0 and got.stdout.strip() == "%5", "4번째 자리 = 늦게 생긴 %5", repr(got))
183
+ splits = [c for c in f.calls() if "split-window" in c]
184
+ check(len(splits) == 1, "원래 요청으로 다시 나누지 않음", str(splits))
185
+ f.split()
186
+ check(f.rows() == [["%2", "%3", "%4", "%5"], ["%6"]], "다음 팀원은 새 줄", str(f.rows()))
187
+ check(sorted(f.panes(), key=lambda p: int(p[1:])) == ["%1", "%2", "%3", "%4", "%5", "%6"], "남는 칸 없음",
188
+ str(f.panes()))
189
+
190
+ def clean(f: Fake, teammates: int, what: str) -> None:
191
+ rows = f.rows()
192
+ placed = [p for r in rows for p in r]
193
+ check(len(placed) == teammates, f"{what}: 팀원 자리 {teammates}개", str(rows))
194
+ check(sorted(f.panes()) == sorted(["%1", *placed]), f"{what}: 팀장 · 팀원 자리 밖의 칸 없음",
195
+ f"{f.panes()} {rows}")
196
+
197
+ print("시간 초과 뒤 칸이 1초 늦게 생김: 기다렸다가 쓴다")
198
+ f = Fake(root, "team-late")
199
+ f.split()
200
+ f.fail_next("late:1")
201
+ t0 = time.time()
202
+ got = f.split()
203
+ check(got.returncode == 0 and got.stdout.strip() == "%3", "2번째 자리 = 늦게 생긴 %3", repr(got))
204
+ check(time.time() - t0 < 6, "대기 시간 안에 끝남", f"{time.time() - t0:.1f}s")
205
+ clean(f, 2, "늦게 생긴 칸")
206
+
207
+ print("시간 초과, 칸 없음: 실패를 돌려주고 재시도가 같은 자리를 채운다")
208
+ f = Fake(root, "team-none")
209
+ f.split()
210
+ f.fail_next("late:30") # 대기 시간(2초) 안에는 안 생긴다
211
+ f.calls()
212
+ got = f.split()
213
+ check(got.returncode != 0 and "Timed out" in got.stderr, "Claude 에 실패를 돌려줌", repr(got))
214
+ splits = [c for c in f.calls() if "split-window" in c]
215
+ check(len(splits) == 1, "원래 요청으로 다시 나누지 않음", str(splits))
216
+ got = f.split() # Claude 의 재시도
217
+ check(got.returncode == 0 and f.rows() == [["%2", got.stdout.strip()]], "재시도가 2번째 자리", str(f.rows()))
218
+
219
+ # 아래 둘은 유령 칸이 재시도보다 먼저 생기면 그 자리로 쓰고, 나중에 생기면 닫는다 (부하에 따라 다르다).
220
+ # 어느 쪽이든 팀장 · 팀원 자리 밖의 칸이 남지 않아야 하고, 팀원 칸은 닫히지 않아야 한다.
221
+ print("실패 뒤 재시도 사이에 유령 칸이 늦게 생김: 쓰거나 닫는다")
222
+ f = Fake(root, "team-ghost-next")
223
+ f.split()
224
+ f.fail_next("late:2.5")
225
+ a1 = f.split() # 실패, 또는 대기 중 유령이 생기면 그 칸을 씀
226
+ f.split() # 재시도 (또는 다음 팀원)
227
+ time.sleep(1.5)
228
+ f.split() # 다음 팀원: 남은 유령이 있으면 닫는다
229
+ time.sleep(1)
230
+ clean(f, 3 if a1.returncode else 4, "다음 split 뒤")
231
+
232
+ print("마지막 팀원 뒤 유령 칸: 정리 작업이 닫는다")
233
+ f = Fake(root, "team-ghost-last")
234
+ f.split()
235
+ f.fail_next("late:2.5")
236
+ a1 = f.split() # 실패 → 정리 작업 시작
237
+ f.split() # 재시도, 더 이상 요청 없음
238
+ time.sleep(4) # 유령이 생기고 정리 작업이 돈다
239
+ clean(f, 2 if a1.returncode else 3, "정리 작업 뒤")
240
+
241
+ last = f
242
+ print("앞 칸이 respawn 을 마칠 때까지 다음 split 이 기다린다 (동시에 띄울 때 칸 나무가 틀어지지 않게)")
243
+ f = Fake(root, "team-respawn")
244
+ f.env["ORCA_TEAM_GRID_RESPAWN_WAIT"] = "10"
245
+ f.split() # %2, respawn 대기
246
+ f.calls()
247
+ cmd = [sys.executable, str(TMUX), *f.sock, "split-window", "-d", "-t", "%1", "-P", "-F", "#{pane_id}", "--", "cat"]
248
+ t0 = time.time()
249
+ nxt = subprocess.Popen(cmd, env=f.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
250
+ time.sleep(1.0)
251
+ check(nxt.poll() is None, "respawn 전에는 다음 split 이 기다림")
252
+ check(not any("split-window" in c for c in f.calls()), "기다리는 동안 Orca 에 split 안 보냄")
253
+ got = f.run(*f.sock, "respawn-pane", "-k", "-t", "%2", "--", "claude --agent-id t1")
254
+ check(got.returncode == 0, "respawn-pane 성공", repr(got))
255
+ out, _ = nxt.communicate(timeout=10)
256
+ check(out.strip() == "%3" and time.time() - t0 < 3, "respawn 뒤 바로 다음 split", f"{out!r} {time.time() - t0:.1f}s")
257
+ sent = f.calls()
258
+ check(["agent-teams-tmux", *f.sock, "respawn-pane", "-k", "-t", "%2", "--", "claude --agent-id t1"] in sent,
259
+ "respawn-pane 은 그대로 Orca 에 넘김", str(sent))
260
+ f.env["ORCA_TEAM_GRID_RESPAWN_WAIT"] = "0.5"
261
+ t0 = time.time()
262
+ got = f.split() # %3 의 respawn 이 안 와도 최대 대기 뒤 진행
263
+ check(got.returncode == 0 and 0.4 < time.time() - t0 < 3, "respawn 이 안 오면 최대 대기 뒤 진행",
264
+ f"{time.time() - t0:.1f}s")
265
+
266
+ print("respawn 전인 칸이 이번 split 과 상관없으면 기다리지 않는다")
267
+ f = Fake(root, "team-nowait")
268
+ f.env["ORCA_TEAM_GRID_RESPAWN_WAIT"] = "10"
269
+ respawn = lambda p: f.run(*f.sock, "respawn-pane", "-k", "-t", p, "--", "claude")
270
+ f.split(); respawn("%2") # 1번째 %2
271
+ f.split(); respawn("%3") # 2번째 %3 (%2 를 나눔)
272
+ f.split() # 3번째 %4 (%2 를 나눔), respawn 안 함
273
+ t0 = time.time()
274
+ got = f.split() # 4번째 (%3 을 나눔): %4 의 부모는 %2 라 기다릴 필요 없음
275
+ check(got.returncode == 0 and time.time() - t0 < 3, "4번째 칸은 바로 나눔", f"{time.time() - t0:.1f}s {got!r}")
276
+ t0 = time.time()
277
+ got = f.split() # 5번째 새 줄 (팀장 %1 을 나눔): %4 · %5 는 팀장의 자식이 아님
278
+ check(got.returncode == 0 and time.time() - t0 < 3, "새 줄도 바로 나눔", f"{time.time() - t0:.1f}s")
279
+ check(f.rows() == [["%2", "%3", "%4", "%5"], ["%6"]], "배치 그대로", str(f.rows()))
280
+ t0 = time.time()
281
+ nxt = subprocess.Popen([sys.executable, str(TMUX), *f.sock, "split-window", "-d", "-t", "%1", "-P", "-F",
282
+ "#{pane_id}", "--", "cat"], env=f.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
283
+ text=True) # 6번째 (%6 을 나눔): %6 이 respawn 전이라 기다려야 함
284
+ time.sleep(1.0)
285
+ check(nxt.poll() is None, "나눌 칸이 respawn 전이면 기다림")
286
+ respawn("%6")
287
+ out, _ = nxt.communicate(timeout=10)
288
+ check(out.strip() == "%7", "respawn 뒤 나눔", repr(out))
289
+
290
+ print("정상 칸은 절대 닫지 않는다")
291
+ placed = [p for r in last.rows() for p in r]
292
+ check(all(p in last.panes() for p in placed) and "%1" in last.panes(), "팀장 · 팀원 칸 남음", str(last.panes()))
293
+
294
+ print("통과" if not FAILS else f"실패 {len(FAILS)}건")
295
+ return 0 if not FAILS else 1
296
+
297
+
298
+ if __name__ == "__main__":
299
+ sys.exit(main())