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.
- package/.claude-plugin/marketplace.json +55 -0
- package/README.md +13 -2
- package/bin/parallel-browser.js +109 -0
- package/extension/background.js +1329 -0
- package/extension/config.json +1 -0
- package/extension/guard.js +44 -0
- package/extension/manifest.json +10 -0
- package/extension/overlay.js +104 -0
- package/extension/popup.html +34 -0
- package/extension/popup.js +39 -0
- package/extension-reloader/manifest.json +13 -0
- package/extension-reloader/sw.js +17 -0
- package/package.json +13 -4
- package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
- package/plugins/thuthi/context.md +3 -0
- package/plugins/thuthi/hooks/hooks.json +15 -0
- package/plugins/thuthi/skills/setup/SKILL.md +55 -0
- package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
- package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
- package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
- package/plugins/thuthi/tools/legacy_launcher.py +65 -0
- package/plugins/thuthi/tools/statusline/statusline.py +8 -0
- package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-accounts/bin/claude-switch +5 -0
- package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
- package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
- package/plugins/thuthi-accounts/lib/tls.py +68 -0
- package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
- package/plugins/thuthi-accounts/setup_check.py +21 -0
- package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
- package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
- package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
- package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
- package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
- package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
- package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-agenda-picker/context.md +3 -0
- package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
- package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
- package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
- package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
- package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
- package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
- package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
- package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
- package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-browser/context.md +3 -0
- package/plugins/thuthi-browser/hooks/hooks.json +15 -0
- package/plugins/thuthi-browser/lib/pbpage.py +397 -0
- package/plugins/thuthi-browser/setup_check.py +93 -0
- package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
- package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
- package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
- package/plugins/thuthi-demo-video/setup_check.py +14 -0
- package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
- package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
- package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
- package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
- package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
- package/plugins/thuthi-orca/context.md +5 -0
- package/plugins/thuthi-orca/hooks/hooks.json +18 -0
- package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
- package/plugins/thuthi-orca/setup_check.py +12 -0
- package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
- package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
- package/runtime/client.js +69 -0
- package/runtime/daemon.js +503 -0
- package/runtime/focus-monitor.js +53 -0
- package/runtime/keys.js +86 -0
- package/runtime/owner.js +64 -0
- package/runtime/recorder.js +267 -0
- package/runtime/relay.js +95 -0
- package/runtime/session.js +1599 -0
|
@@ -0,0 +1,1286 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""agenda-picker: 안건 선택 페이지를 만들고, 띄우고, 사용자가 보낸 선택을 받는다.
|
|
3
|
+
|
|
4
|
+
picker.py check <dir> agenda.json 검사 (exit 1 = 오류)
|
|
5
|
+
picker.py build <dir> index.html 정적 파일 생성 (file:// 로 열 때용, 보내기 대신 복사)
|
|
6
|
+
picker.py serve <dir> [--open] 로컬 서버를 독립 프로세스로 띄우고 URL 을 찍은 뒤 바로 끝난다 (요청 없이 12시간이면 서버도 끝난다)
|
|
7
|
+
picker.py open <dir> 페이지를 연다. Orca 안이면 Orca 브라우저 탭 (보내면 그 탭을 닫는다), 밖이면 open -g
|
|
8
|
+
picker.py wait <dir> 사용자가 보낼 때까지 기다렸다가 선택 내용을 찍고 끝난다 (Orca 밖에서 run_in_background 로)
|
|
9
|
+
picker.py status <dir>
|
|
10
|
+
picker.py stop <dir>
|
|
11
|
+
|
|
12
|
+
폴더 안 파일:
|
|
13
|
+
agenda.json Claude 가 쓰는 안건 정의
|
|
14
|
+
selections.json 페이지가 쓰는 현재 선택 (고를 때마다 갱신)
|
|
15
|
+
submissions/0001.json [Claude 로 보내기] 한 번에 하나
|
|
16
|
+
index.html 정적 사본 (서버가 선택이 바뀔 때마다 다시 쓴다)
|
|
17
|
+
.picker/ token, server.json, server.log, waiter.pid, consumed, tab.json (Orca 탭 id),
|
|
18
|
+
target.json (보내기를 넣을 Orca 터미널), inbox.json (Claude 세션 인박스 소켓 · 토큰, 0600),
|
|
19
|
+
delivery.json (마지막 전달 결과)
|
|
20
|
+
|
|
21
|
+
[Claude 로 보내기] 전달 경로:
|
|
22
|
+
Orca 안 serve · open 을 부른 Claude 터미널($ORCA_TERMINAL_HANDLE) 입력창에 서버가 한 줄을 넣는다 (orca terminal send).
|
|
23
|
+
넣기 전에 그 터미널에 아직 에이전트가 떠 있는지 orca terminal show 의 agentIdentity 로 본다 (비었으면 셸이라 넣지 않는다).
|
|
24
|
+
Orca 밖 백그라운드 wait 가 끝나며 세션을 깨운다. wait 가 떠 있으면 Orca 안에서도 wait 가 받는다.
|
|
25
|
+
|
|
26
|
+
orca CLI 는 샌드박스에서 막힌다. serve · open · stop 은 샌드박스 밖에서 실행한다.
|
|
27
|
+
|
|
28
|
+
python3 3.9 표준 라이브러리만 쓴다.
|
|
29
|
+
"""
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import argparse
|
|
33
|
+
import binascii
|
|
34
|
+
import functools
|
|
35
|
+
import hashlib
|
|
36
|
+
import html
|
|
37
|
+
import json
|
|
38
|
+
import os
|
|
39
|
+
import re
|
|
40
|
+
import secrets
|
|
41
|
+
import shlex
|
|
42
|
+
import shutil
|
|
43
|
+
import signal
|
|
44
|
+
import subprocess
|
|
45
|
+
import sys
|
|
46
|
+
import threading
|
|
47
|
+
import time
|
|
48
|
+
import urllib.request
|
|
49
|
+
from datetime import datetime
|
|
50
|
+
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
|
51
|
+
from pathlib import Path
|
|
52
|
+
from urllib.parse import unquote, urlsplit
|
|
53
|
+
|
|
54
|
+
SELF = Path(__file__).resolve()
|
|
55
|
+
TEMPLATE = SELF.parent / "template.html"
|
|
56
|
+
|
|
57
|
+
SPEC_F = "agenda.json"
|
|
58
|
+
STATE_F = "selections.json"
|
|
59
|
+
SUBS_D = "submissions"
|
|
60
|
+
PRIV_D = ".picker"
|
|
61
|
+
|
|
62
|
+
ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
|
|
63
|
+
SHOT_KEYS = ("src", "light", "dark")
|
|
64
|
+
# 라이트 · 다크를 따로 넣은 옛 방식 그림을 알아본다 (캡션이나 파일 이름으로).
|
|
65
|
+
THEME_CAPTIONS = {"라이트", "다크", "light", "dark", "라이트 모드", "다크 모드"}
|
|
66
|
+
THEME_FILE_RE = re.compile(r"[-_.](light|dark)\.\w+$", re.I)
|
|
67
|
+
# 이 확장자면 페이지가 <img> 대신 <video> (소리 없이 반복 재생) 로 그린다. template.html 의 isVideo 와 맞춘다.
|
|
68
|
+
VIDEO_RE = re.compile(r"\.(mp4|webm|mov|m4v)$", re.I)
|
|
69
|
+
# 이 확장자면 페이지가 스크린샷 대신 iframe 으로 바로 그린다 (개념 그림). template.html 의 isFrame 과 맞춘다.
|
|
70
|
+
FRAME_RE = re.compile(r"\.html?$", re.I)
|
|
71
|
+
# 그림 데이터 (figure) 를 그릴 때 쓰는 공통 스타일. 페이지가 figure 를 HTML 로 만들 때 넣고, 그림 HTML 파일도 링크해 쓴다.
|
|
72
|
+
FIG_CSS = SELF.parent.parent / "references" / "diagram" / "base.css"
|
|
73
|
+
FIG_KINDS = {"", "new", "warn", "muted"}
|
|
74
|
+
SIZE_RE = re.compile(r"^\d{2,5}x\d{2,5}$")
|
|
75
|
+
RANGE_RE = re.compile(r"bytes=(\d*)-(\d*)")
|
|
76
|
+
SUB_RE = re.compile(r"^(\d{4,})\.json$")
|
|
77
|
+
MAX_BODY = 2 * 1024 * 1024
|
|
78
|
+
POLL_SEC = 0.5
|
|
79
|
+
TAB_CLOSE_DELAY = 1.5
|
|
80
|
+
IDLE_SEC = 12 * 3600 # 요청 없이 이만큼 지나면 서버가 스스로 끝난다
|
|
81
|
+
# 검사(selftest)가 가짜 orca 로 바꿔 끼운다. 이름은 전체 경로로 찾는다 (Windows 의 orca 는 .cmd 일 수 있어 이름만으로는 실행되지 않는다)
|
|
82
|
+
ORCA = os.environ.get("AGENDA_PICKER_ORCA") or shutil.which("orca") or "orca"
|
|
83
|
+
LINE_MAX = 600
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ---------------------------------------------------------------- 공통
|
|
87
|
+
|
|
88
|
+
def now_iso() -> str:
|
|
89
|
+
return datetime.now().astimezone().isoformat(timespec="seconds")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def show_time(iso: str) -> str:
|
|
93
|
+
try:
|
|
94
|
+
return datetime.fromisoformat(iso).strftime("%Y-%m-%d %H:%M:%S")
|
|
95
|
+
except (TypeError, ValueError):
|
|
96
|
+
return str(iso)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def atomic_write(path: Path, text: str) -> None:
|
|
100
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
|
|
102
|
+
tmp.write_text(text, encoding="utf-8")
|
|
103
|
+
os.replace(tmp, path)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def write_json(path: Path, obj) -> None:
|
|
107
|
+
atomic_write(path, json.dumps(obj, ensure_ascii=False, indent=2) + "\n")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def read_json(path: Path, default=None):
|
|
111
|
+
try:
|
|
112
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
113
|
+
except FileNotFoundError:
|
|
114
|
+
return default
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def pid_alive(pid) -> bool:
|
|
118
|
+
if not isinstance(pid, int) or pid <= 0:
|
|
119
|
+
return False
|
|
120
|
+
try:
|
|
121
|
+
os.kill(pid, 0)
|
|
122
|
+
except ProcessLookupError:
|
|
123
|
+
return False
|
|
124
|
+
except PermissionError:
|
|
125
|
+
return True
|
|
126
|
+
return True
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def priv(d: Path) -> Path:
|
|
130
|
+
p = d / PRIV_D
|
|
131
|
+
p.mkdir(exist_ok=True)
|
|
132
|
+
return p
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def token_of(d: Path) -> str:
|
|
136
|
+
f = priv(d) / "token"
|
|
137
|
+
if f.exists():
|
|
138
|
+
return f.read_text().strip()
|
|
139
|
+
t = secrets.token_urlsafe(24)
|
|
140
|
+
f.write_text(t)
|
|
141
|
+
f.chmod(0o600)
|
|
142
|
+
return t
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def dir_key(d: Path) -> str:
|
|
146
|
+
return hashlib.sha1(str(d).encode()).hexdigest()[:12]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def preferred_port(d: Path) -> int:
|
|
150
|
+
# 폴더마다 같은 포트를 쓰려고 한다. 서버를 다시 띄워도 열려 있던 탭이 새로고침만으로 이어진다.
|
|
151
|
+
return 47100 + binascii.crc32(str(d).encode()) % 1800
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def spec_version(d: Path) -> str:
|
|
155
|
+
try:
|
|
156
|
+
return hashlib.sha1((d / SPEC_F).read_bytes()).hexdigest()[:12]
|
|
157
|
+
except FileNotFoundError:
|
|
158
|
+
return ""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def latest_seq(d: Path) -> int:
|
|
162
|
+
best = 0
|
|
163
|
+
try:
|
|
164
|
+
for name in os.listdir(d / SUBS_D):
|
|
165
|
+
m = SUB_RE.match(name)
|
|
166
|
+
if m:
|
|
167
|
+
best = max(best, int(m.group(1)))
|
|
168
|
+
except FileNotFoundError:
|
|
169
|
+
pass
|
|
170
|
+
return best
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def read_consumed(d: Path) -> int:
|
|
174
|
+
try:
|
|
175
|
+
return int((d / PRIV_D / "consumed").read_text().strip() or 0)
|
|
176
|
+
except (FileNotFoundError, ValueError):
|
|
177
|
+
return 0
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def read_pid(path: Path) -> int:
|
|
181
|
+
try:
|
|
182
|
+
return int(path.read_text().strip())
|
|
183
|
+
except (FileNotFoundError, ValueError):
|
|
184
|
+
return 0
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def watch_parent(on_orphan) -> None:
|
|
188
|
+
"""부모(Claude 세션의 셸)가 사라지면 따라 끝낸다. 세션이 끝난 뒤 서버 · 대기가 남지 않게."""
|
|
189
|
+
ppid = os.getppid()
|
|
190
|
+
if ppid == 1:
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
def loop():
|
|
194
|
+
while True:
|
|
195
|
+
time.sleep(2)
|
|
196
|
+
if os.getppid() != ppid:
|
|
197
|
+
on_orphan()
|
|
198
|
+
return
|
|
199
|
+
|
|
200
|
+
threading.Thread(target=loop, daemon=True).start()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# ---------------------------------------------------------------- 안건 정의
|
|
204
|
+
|
|
205
|
+
def norm_shots(raw) -> list:
|
|
206
|
+
"""그림 한 항목: "shots/A.png" · {"src", "caption"} · {"light", "dark", "caption"} (페이지 테마에 맞는 쪽만 보인다)."""
|
|
207
|
+
out = []
|
|
208
|
+
for s in raw if isinstance(raw, list) else []:
|
|
209
|
+
if isinstance(s, str):
|
|
210
|
+
s = {"src": s}
|
|
211
|
+
if isinstance(s, dict):
|
|
212
|
+
item = {k: str(s.get(k) or "") for k in (*SHOT_KEYS, "caption", "size")}
|
|
213
|
+
item["figure"] = s.get("figure")
|
|
214
|
+
out.append(item)
|
|
215
|
+
return out
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def decided_of(ag: dict) -> str:
|
|
219
|
+
dv = ag.get("decided")
|
|
220
|
+
ok = isinstance(dv, str) and any(isinstance(o, dict) and o.get("id") == dv for o in ag.get("options") or [])
|
|
221
|
+
return dv if ok else ""
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def load_spec(d: Path):
|
|
225
|
+
"""(spec, errors, warnings). spec 을 못 읽으면 None."""
|
|
226
|
+
path = d / SPEC_F
|
|
227
|
+
if not path.exists():
|
|
228
|
+
return None, [f"{path} 가 없다"], []
|
|
229
|
+
try:
|
|
230
|
+
spec = json.loads(path.read_text(encoding="utf-8"))
|
|
231
|
+
except json.JSONDecodeError as e:
|
|
232
|
+
return None, [f"{SPEC_F} JSON 오류: {e}"], []
|
|
233
|
+
errs, warns = validate(spec, d)
|
|
234
|
+
return spec, errs, warns
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def figure_errors(fig) -> list:
|
|
238
|
+
"""figure: {"title", "lanes": [{"who", "nodes": ["글|작은 글", {"t", "s", "k"}]}], "html", "css", "note"}. lanes 나 html 중 하나는 있어야 한다."""
|
|
239
|
+
if not isinstance(fig, dict):
|
|
240
|
+
return ["figure 가 객체가 아니다"]
|
|
241
|
+
errs = []
|
|
242
|
+
lanes, frag = fig.get("lanes"), fig.get("html")
|
|
243
|
+
if lanes is None and not frag:
|
|
244
|
+
errs.append("figure 에 lanes (그래프) 나 html (자유 그림) 이 없다")
|
|
245
|
+
for k in ("title", "note", "html", "css"):
|
|
246
|
+
if fig.get(k) is not None and not isinstance(fig.get(k), str):
|
|
247
|
+
errs.append(f"figure.{k} 는 문자열이어야 한다")
|
|
248
|
+
if lanes is not None:
|
|
249
|
+
if not isinstance(lanes, list) or not lanes:
|
|
250
|
+
return errs + ["figure.lanes 는 비지 않은 배열이어야 한다"]
|
|
251
|
+
for i, ln in enumerate(lanes, 1):
|
|
252
|
+
nodes = ln.get("nodes") if isinstance(ln, dict) else None
|
|
253
|
+
if not isinstance(nodes, list) or not nodes:
|
|
254
|
+
errs.append(f"figure.lanes[{i}].nodes 가 비었다")
|
|
255
|
+
continue
|
|
256
|
+
for j, n in enumerate(nodes, 1):
|
|
257
|
+
if isinstance(n, str):
|
|
258
|
+
continue
|
|
259
|
+
if not isinstance(n, dict) or not str(n.get("t") or "").strip():
|
|
260
|
+
errs.append(f"figure.lanes[{i}].nodes[{j}] 는 \"글|작은 글\" 이나 {{\"t\": …}} 여야 한다")
|
|
261
|
+
elif str(n.get("k") or "") not in FIG_KINDS:
|
|
262
|
+
errs.append(f"figure.lanes[{i}].nodes[{j}].k 는 new · warn · muted 중 하나다: {n.get('k')!r}")
|
|
263
|
+
return errs
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def validate(spec, d: Path):
|
|
267
|
+
errs, warns = [], []
|
|
268
|
+
if not isinstance(spec, dict):
|
|
269
|
+
return ["최상위가 객체가 아니다"], warns
|
|
270
|
+
if not str(spec.get("title", "")).strip():
|
|
271
|
+
errs.append("title 이 비었다")
|
|
272
|
+
ags = spec.get("agendas")
|
|
273
|
+
if not isinstance(ags, list) or not ags:
|
|
274
|
+
errs.append("agendas 가 비었다")
|
|
275
|
+
return errs, warns
|
|
276
|
+
|
|
277
|
+
html_fields = [("lead", spec.get("lead"))]
|
|
278
|
+
text_fields = [("title", spec.get("title"))]
|
|
279
|
+
seen = set()
|
|
280
|
+
for i, ag in enumerate(ags, 1):
|
|
281
|
+
where = f"agendas[{i}]"
|
|
282
|
+
if not isinstance(ag, dict):
|
|
283
|
+
errs.append(f"{where} 가 객체가 아니다")
|
|
284
|
+
continue
|
|
285
|
+
aid = ag.get("id")
|
|
286
|
+
if not isinstance(aid, str) or not ID_RE.match(aid):
|
|
287
|
+
errs.append(f"{where}.id 가 없거나 형식이 틀렸다 (영문 · 숫자로 시작, 영문 · 숫자 · - _ . 만): {aid!r}")
|
|
288
|
+
elif aid in seen:
|
|
289
|
+
errs.append(f"{where}.id 가 겹친다: {aid}")
|
|
290
|
+
else:
|
|
291
|
+
seen.add(aid)
|
|
292
|
+
where = f"안건 {aid}"
|
|
293
|
+
if not str(ag.get("title", "")).strip():
|
|
294
|
+
errs.append(f"{where}: title 이 비었다")
|
|
295
|
+
text_fields.append((f"{where}.title", ag.get("title")))
|
|
296
|
+
html_fields += [(f"{where}.summary", ag.get("summary")), (f"{where}.context", ag.get("context"))]
|
|
297
|
+
|
|
298
|
+
blocks = []
|
|
299
|
+
cur = ag.get("current")
|
|
300
|
+
if cur is not None:
|
|
301
|
+
if isinstance(cur, dict):
|
|
302
|
+
blocks.append((f"{where}.current", cur))
|
|
303
|
+
else:
|
|
304
|
+
errs.append(f"{where}: current 가 객체가 아니다")
|
|
305
|
+
|
|
306
|
+
opts = ag.get("options")
|
|
307
|
+
if not isinstance(opts, list) or not opts:
|
|
308
|
+
errs.append(f"{where}: options 가 비었다")
|
|
309
|
+
opts = []
|
|
310
|
+
elif len(opts) < 2:
|
|
311
|
+
warns.append(f"{where}: 안이 1개뿐이다")
|
|
312
|
+
oseen, recs = set(), 0
|
|
313
|
+
for j, op in enumerate(opts, 1):
|
|
314
|
+
ow = f"{where}.options[{j}]"
|
|
315
|
+
if not isinstance(op, dict):
|
|
316
|
+
errs.append(f"{ow} 가 객체가 아니다")
|
|
317
|
+
continue
|
|
318
|
+
oid = op.get("id")
|
|
319
|
+
if not isinstance(oid, str) or not ID_RE.match(oid):
|
|
320
|
+
errs.append(f"{ow}.id 가 없거나 형식이 틀렸다: {oid!r}")
|
|
321
|
+
elif oid in oseen:
|
|
322
|
+
errs.append(f"{ow}.id 가 겹친다: {oid}")
|
|
323
|
+
else:
|
|
324
|
+
oseen.add(oid)
|
|
325
|
+
ow = f"{where} 안 {oid}"
|
|
326
|
+
if not str(op.get("title", "")).strip():
|
|
327
|
+
errs.append(f"{ow}: title 이 비었다")
|
|
328
|
+
if op.get("recommended"):
|
|
329
|
+
recs += 1
|
|
330
|
+
blocks.append((ow, op))
|
|
331
|
+
if recs > 1:
|
|
332
|
+
warns.append(f"{where}: 권장안이 {recs}개다 (보통 하나)")
|
|
333
|
+
dv = ag.get("decided")
|
|
334
|
+
if dv is not None and (not isinstance(dv, str) or dv not in oseen):
|
|
335
|
+
errs.append(f"{where}: decided 는 이 안건의 안 id 여야 한다 ({', '.join(sorted(oseen))}): {dv!r}")
|
|
336
|
+
if ag.get("decidedNote") is not None and dv is None:
|
|
337
|
+
warns.append(f"{where}: decidedNote 만 있고 decided 가 없다")
|
|
338
|
+
text_fields.append((f"{where}.decidedNote", ag.get("decidedNote")))
|
|
339
|
+
|
|
340
|
+
# 비교 보기는 지금 그림과 안 그림을 caption 이 모두 있으면 이름으로, 아니면 순서로 짝짓는다.
|
|
341
|
+
cur_shots = norm_shots(cur.get("shots")) if isinstance(cur, dict) else []
|
|
342
|
+
for bw, b in blocks:
|
|
343
|
+
caps = [s["caption"].strip() for s in norm_shots(b.get("shots"))]
|
|
344
|
+
dup = sorted({c for c in caps if c and caps.count(c) > 1})
|
|
345
|
+
if dup:
|
|
346
|
+
warns.append(f"{bw}: 같은 caption 이 겹친다 ({', '.join(dup)}). 짝을 이름으로 맞추므로 그림마다 다른 이름을 단다")
|
|
347
|
+
if b is not cur:
|
|
348
|
+
pair = caps + [s["caption"].strip() for s in cur_shots]
|
|
349
|
+
if any(pair) and not all(pair):
|
|
350
|
+
warns.append(f"{bw}: 지금 · 이 안의 그림 중 일부에만 caption 이 있다. 모두 있어야 이름으로 짝을 맞추고, 아니면 순서로 맞춘다")
|
|
351
|
+
for bw, b in blocks:
|
|
352
|
+
text_fields.append((f"{bw}.title", b.get("title")))
|
|
353
|
+
html_fields.append((f"{bw}.body", b.get("body")))
|
|
354
|
+
if b.get("shots") is not None and not isinstance(b.get("shots"), list):
|
|
355
|
+
errs.append(f"{bw}: shots 가 배열이 아니다")
|
|
356
|
+
shots = norm_shots(b.get("shots"))
|
|
357
|
+
for s in shots:
|
|
358
|
+
paths = [s[k] for k in SHOT_KEYS if s[k]]
|
|
359
|
+
if s["figure"] is not None:
|
|
360
|
+
if paths:
|
|
361
|
+
errs.append(f"{bw}: 그림 항목에 figure 와 src · light · dark 를 같이 썼다 (하나만)")
|
|
362
|
+
errs += [f"{bw}: {e}" for e in figure_errors(s["figure"])]
|
|
363
|
+
if isinstance(s["figure"], dict) and re.search(r"<script|\son[a-z]+\s*=", str(s["figure"].get("html") or ""), re.I):
|
|
364
|
+
warns.append(f"{bw}: figure.html 에 <script> 나 on* 속성이 있다. 그림의 스크립트는 막힌다 (CSS · SVG 로만 그린다)")
|
|
365
|
+
elif not paths:
|
|
366
|
+
errs.append(f"{bw}: 그림 항목에 figure · src · light · dark 가 다 없다")
|
|
367
|
+
for src in paths:
|
|
368
|
+
if re.match(r"^(https?:|data:)", src):
|
|
369
|
+
continue
|
|
370
|
+
parts = [p for p in src.split("/") if p]
|
|
371
|
+
if src.startswith("/") or ".." in parts or any(p.startswith(".") for p in parts):
|
|
372
|
+
errs.append(f"{bw}: 그림 경로는 폴더 안 상대 경로여야 한다: {src!r}")
|
|
373
|
+
elif not (d / src).is_file():
|
|
374
|
+
errs.append(f"{bw}: 스크린샷 파일이 없다: {src}")
|
|
375
|
+
if s["light"] and s["dark"] and bool(VIDEO_RE.search(s["light"])) != bool(VIDEO_RE.search(s["dark"])):
|
|
376
|
+
errs.append(f"{bw}: light · dark 중 한쪽만 영상이다 (둘 다 그림이거나 둘 다 영상이어야 한다)")
|
|
377
|
+
if s["light"] and s["dark"] and bool(FRAME_RE.search(s["light"])) != bool(FRAME_RE.search(s["dark"])):
|
|
378
|
+
errs.append(f"{bw}: light · dark 중 한쪽만 HTML 이다 (HTML 그림은 한 파일에서 data-theme 으로 다크를 그린다)")
|
|
379
|
+
if s["size"] and not SIZE_RE.match(s["size"]):
|
|
380
|
+
errs.append(f"{bw}: size 는 \"1200x460\" 꼴이어야 한다: {s['size']!r}")
|
|
381
|
+
for src in paths:
|
|
382
|
+
f = d / src
|
|
383
|
+
if FRAME_RE.search(src) and f.is_file():
|
|
384
|
+
txt = f.read_text(encoding="utf-8", errors="replace")
|
|
385
|
+
if re.search(r"<script|\son[a-z]+\s*=", txt, re.I):
|
|
386
|
+
warns.append(f"{bw}: HTML 그림 {src} 에 <script> 나 on* 속성이 있다. 페이지는 그림 HTML 의 스크립트를 막는다 (CSS · SVG 로만 그린다)")
|
|
387
|
+
if "prefers-color-scheme" in txt and "data-theme" not in txt:
|
|
388
|
+
warns.append(f"{bw}: HTML 그림 {src} 이 prefers-color-scheme 으로 다크를 그린다. 페이지의 [라이트 | 다크] 를 따르려면 :root[data-theme=\"dark\"] 로 쓴다")
|
|
389
|
+
split = [s for s in shots if s["src"] and not s["light"] and not s["dark"]
|
|
390
|
+
and (s["caption"].strip().lower() in THEME_CAPTIONS or THEME_FILE_RE.search(s["src"]))]
|
|
391
|
+
if len(split) >= 2:
|
|
392
|
+
warns.append(f"{bw}: 라이트 · 다크 그림을 따로 넣었다. "
|
|
393
|
+
'{"light": "…", "dark": "…"} 한 항목으로 묶으면 페이지 테마에 맞는 쪽 하나만 보인다')
|
|
394
|
+
|
|
395
|
+
for name, v in html_fields:
|
|
396
|
+
if isinstance(v, str) and re.search(r"<script|\son[a-z]+\s*=", v, re.I):
|
|
397
|
+
warns.append(f"{name}: <script> 나 on* 속성이 있다 (페이지가 그대로 실행한다)")
|
|
398
|
+
dashed = [name for name, v in html_fields + text_fields if isinstance(v, str) and "—" in v]
|
|
399
|
+
if dashed:
|
|
400
|
+
warns.append("em dash(—) 가 있다. 한국어 문장은 쉼표 · 괄호 · 문장 끊기로 쓴다: " + ", ".join(dashed[:6])
|
|
401
|
+
+ (" …" if len(dashed) > 6 else ""))
|
|
402
|
+
return errs, warns
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def clean_state(st) -> dict:
|
|
406
|
+
st = st if isinstance(st, dict) else {}
|
|
407
|
+
|
|
408
|
+
def str_map(m):
|
|
409
|
+
return {k: v for k, v in (m.items() if isinstance(m, dict) else []) if isinstance(k, str) and isinstance(v, str)}
|
|
410
|
+
|
|
411
|
+
return {
|
|
412
|
+
"version": 1,
|
|
413
|
+
"updatedAt": st.get("updatedAt") if isinstance(st.get("updatedAt"), str) else "",
|
|
414
|
+
"picks": str_map(st.get("picks")),
|
|
415
|
+
"memos": {k: v for k, v in str_map(st.get("memos")).items() if v.strip()},
|
|
416
|
+
"note": st.get("note") if isinstance(st.get("note"), str) else "",
|
|
417
|
+
"seeded": str_map(st.get("seeded")), # 페이지가 미리 골라 둔 decided 값 (같은 값을 다시 덮지 않으려고)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def seed_decided(spec: dict, st: dict) -> dict:
|
|
422
|
+
"""페이지와 같은 규칙으로 decided 를 미리 고른다 (페이지가 아직 저장하지 않았을 때 status 가 같은 결과를 보이게)."""
|
|
423
|
+
for ag in spec["agendas"]:
|
|
424
|
+
dv = decided_of(ag)
|
|
425
|
+
if dv and st["seeded"].get(ag["id"]) != dv:
|
|
426
|
+
st["picks"][ag["id"]] = dv
|
|
427
|
+
st["seeded"][ag["id"]] = dv
|
|
428
|
+
return st
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
# ---------------------------------------------------------------- 페이지
|
|
432
|
+
|
|
433
|
+
def js_json(obj) -> str:
|
|
434
|
+
# <script type="application/json"> 안에 넣는다. </script> 로 끊기지 않게 < 를 모두 이스케이프.
|
|
435
|
+
return json.dumps(obj, ensure_ascii=False).replace("<", "\\u003c")
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def error_page(d: Path, errs) -> str:
|
|
439
|
+
items = "".join(f"<li>{html.escape(e)}</li>" for e in errs)
|
|
440
|
+
return f"""<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta http-equiv="refresh" content="3">
|
|
441
|
+
<title>agenda.json 오류</title><style>body{{font-family:"Pretendard","Apple SD Gothic Neo",sans-serif;margin:40px;color:#1d1d1b}}
|
|
442
|
+
li{{margin:6px 0}}code{{font-family:ui-monospace,Menlo,monospace}}</style></head><body>
|
|
443
|
+
<h1>agenda.json 을 읽지 못했다</h1><p><code>{html.escape(str(d / SPEC_F))}</code></p><ul>{items}</ul>
|
|
444
|
+
<p>고치면 3초 안에 다시 읽는다.</p></body></html>"""
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def render(d: Path, mode: str, token: str = "", port: int = 0) -> str:
|
|
448
|
+
spec, errs, _ = load_spec(d)
|
|
449
|
+
if errs:
|
|
450
|
+
return error_page(d, errs)
|
|
451
|
+
if not port:
|
|
452
|
+
port = (read_json(d / PRIV_D / "server.json", {}) or {}).get("port") or preferred_port(d)
|
|
453
|
+
cfg = {"mode": mode, "token": token, "dirKey": dir_key(d), "dir": str(d), "port": port,
|
|
454
|
+
"specVersion": spec_version(d), "figCss": FIG_CSS.read_text(encoding="utf-8") if FIG_CSS.is_file() else ""}
|
|
455
|
+
values = {
|
|
456
|
+
"TITLE": html.escape(str(spec.get("title", ""))),
|
|
457
|
+
"SPEC": js_json(spec),
|
|
458
|
+
"STATE": js_json(clean_state(read_json(d / STATE_F, {}))),
|
|
459
|
+
"CONFIG": js_json(cfg),
|
|
460
|
+
}
|
|
461
|
+
return re.sub(r"@@([A-Z]+)@@", lambda m: values.get(m.group(1), m.group(0)), TEMPLATE.read_text(encoding="utf-8"))
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def build_static(d: Path) -> Path:
|
|
465
|
+
out = d / "index.html"
|
|
466
|
+
atomic_write(out, render(d, "static"))
|
|
467
|
+
return out
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
# ---------------------------------------------------------------- 보내기
|
|
471
|
+
|
|
472
|
+
def resolve(spec: dict, st: dict) -> list:
|
|
473
|
+
items = []
|
|
474
|
+
for ag in spec["agendas"]:
|
|
475
|
+
oid = st["picks"].get(ag["id"])
|
|
476
|
+
op = next((o for o in ag["options"] if o.get("id") == oid), None)
|
|
477
|
+
items.append({
|
|
478
|
+
"id": ag["id"],
|
|
479
|
+
"title": ag["title"],
|
|
480
|
+
"pick": {"id": op["id"], "title": op["title"], "recommended": bool(op.get("recommended"))} if op else None,
|
|
481
|
+
"decided": decided_of(ag) or None,
|
|
482
|
+
"memo": st["memos"].get(ag["id"], "").strip(),
|
|
483
|
+
})
|
|
484
|
+
return items
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def indent_block(label: str, text: str, pad: str = " ") -> list:
|
|
488
|
+
lines = text.strip().splitlines() or [""]
|
|
489
|
+
out = [f"{pad}{label}{lines[0]}"]
|
|
490
|
+
out += [f"{pad}{' ' * len(label)}{ln}" for ln in lines[1:]]
|
|
491
|
+
return out
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def pick_line(it: dict) -> str:
|
|
495
|
+
p, dv = it["pick"], it.get("decided")
|
|
496
|
+
notes = ["권장안"] if p and p["recommended"] else []
|
|
497
|
+
if dv:
|
|
498
|
+
notes.append("대화에서 정한 안 그대로" if p and p["id"] == dv
|
|
499
|
+
else f"대화에서 정한 {dv} 에서 바꿈" if p else f"대화에서 정한 {dv} 를 풀었다")
|
|
500
|
+
tail = f" ({', '.join(notes)})" if notes else ""
|
|
501
|
+
return f" 선택: {p['id']}. {p['title']}{tail}" if p else f" 선택: 미정{tail}"
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def format_message(sub: dict, d: Path, superseded=()) -> str:
|
|
505
|
+
items = sub["items"]
|
|
506
|
+
lines = [f"[agenda-picker] 사용자가 안건 선택을 보냈다 (#{sub['seq']}, {show_time(sub['sentAt'])})",
|
|
507
|
+
f"페이지: {sub['title']}",
|
|
508
|
+
f"폴더: {d}"]
|
|
509
|
+
if superseded:
|
|
510
|
+
lines.append(f"(기다리지 않는 동안 먼저 온 {', '.join('#%d' % s for s in superseded)} 는 이 #{sub['seq']} 가 대신한다)")
|
|
511
|
+
lines.append("")
|
|
512
|
+
for i, it in enumerate(items, 1):
|
|
513
|
+
lines.append(f"{i}. {it['title']} [{it['id']}]")
|
|
514
|
+
lines.append(pick_line(it))
|
|
515
|
+
if it["memo"]:
|
|
516
|
+
lines += indent_block("메모: ", it["memo"])
|
|
517
|
+
if sub.get("note", "").strip():
|
|
518
|
+
lines.append("")
|
|
519
|
+
lines += indent_block("전체 메모: ", sub["note"], pad="")
|
|
520
|
+
decided = sum(1 for it in items if it["pick"])
|
|
521
|
+
qd = shlex.quote(str(d))
|
|
522
|
+
lines += ["", f"결정 {decided}/{len(items)}",
|
|
523
|
+
f"원본: {d / SUBS_D / ('%04d.json' % sub['seq'])}"]
|
|
524
|
+
orca = sub.get("via") in ("orca", "inbox")
|
|
525
|
+
if sub.get("tabClosed"):
|
|
526
|
+
again = ("다시 보내면 이 세션에 다시 들어온다." if orca
|
|
527
|
+
else f"wait 를 백그라운드로 띄운다 (python3 {SELF} wait {qd}).")
|
|
528
|
+
lines.append(f"페이지 탭은 닫았다. 다시 고치게 하려면 다시 연다 (python3 {SELF} open {qd}, 샌드박스 밖). {again}")
|
|
529
|
+
elif orca:
|
|
530
|
+
lines.append("페이지는 열려 있다. 다시 보내면 이 세션에 다시 들어온다.")
|
|
531
|
+
else:
|
|
532
|
+
lines.append(f"다음 보내기를 받으려면 다시 백그라운드로 띄운다: python3 {SELF} wait {qd}")
|
|
533
|
+
return "\n".join(lines)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def one_line(sub: dict, d: Path) -> str:
|
|
537
|
+
"""Orca 터미널 입력창에 넣을 한 줄. 줄바꿈이 들어가면 중간에 제출될 수 있어 한 줄로만 만든다.
|
|
538
|
+
|
|
539
|
+
사용자가 쓴 글(메모 · 제목)은 넣지 않는다. 안건 id · 안 id 는 ID_RE 로 걸러져 있고, 나머지는 파일에서 읽게 한다.
|
|
540
|
+
"""
|
|
541
|
+
items = sub["items"]
|
|
542
|
+
picks = ", ".join(f"{it['id']}={it['pick']['id'] if it['pick'] else '미정'}" for it in items)
|
|
543
|
+
memos = sum(1 for it in items if it["memo"]) + (1 if sub.get("note", "").strip() else 0)
|
|
544
|
+
path = d / SUBS_D / f"{sub['seq']:04d}.json"
|
|
545
|
+
head = f"[agenda-picker] 사용자가 안건 선택을 보냈다 #{sub['seq']} · 결정 {sum(1 for it in items if it['pick'])}/{len(items)}"
|
|
546
|
+
tail = (f" · 메모 {memos}건" if memos else "") + f" · 내용은 {path} 의 message 를 읽는다"
|
|
547
|
+
line = f"{head} ({picks}){tail}"
|
|
548
|
+
if len(line) > LINE_MAX:
|
|
549
|
+
line = head + tail
|
|
550
|
+
return re.sub(r"\s+", " ", line).strip()
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
# ---------------------------------------------------------------- 서버
|
|
554
|
+
|
|
555
|
+
class App:
|
|
556
|
+
def __init__(self, d: Path, port: int):
|
|
557
|
+
self.d = d
|
|
558
|
+
self.port = port
|
|
559
|
+
self.lock = threading.Lock()
|
|
560
|
+
self.token = token_of(d)
|
|
561
|
+
self.hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
|
|
562
|
+
self.origins = {f"http://{h}" for h in self.hosts}
|
|
563
|
+
self.last_request = time.time()
|
|
564
|
+
|
|
565
|
+
def state(self) -> dict:
|
|
566
|
+
return clean_state(read_json(self.d / STATE_F, {}))
|
|
567
|
+
|
|
568
|
+
def last_sent(self):
|
|
569
|
+
seq = latest_seq(self.d)
|
|
570
|
+
if not seq:
|
|
571
|
+
return None
|
|
572
|
+
sub = read_json(self.d / SUBS_D / f"{seq:04d}.json", {}) or {}
|
|
573
|
+
return {"seq": seq, "sentAt": sub.get("sentAt", ""), "stateUpdatedAt": sub.get("stateUpdatedAt", "")}
|
|
574
|
+
|
|
575
|
+
def receiver(self) -> dict:
|
|
576
|
+
"""보내기를 누가 받는가. Claude 세션 인박스 소켓 → wait → Orca 터미널 순. 셋 다 없으면 아무도 못 받는다."""
|
|
577
|
+
if inbox_target(self.d):
|
|
578
|
+
return {"via": "inbox", "ready": True}
|
|
579
|
+
if pid_alive(read_pid(self.d / PRIV_D / "waiter.pid")):
|
|
580
|
+
return {"via": "wait", "ready": True}
|
|
581
|
+
if target_terminal(self.d):
|
|
582
|
+
return {"via": "orca", "ready": True}
|
|
583
|
+
return {"via": "wait", "ready": False}
|
|
584
|
+
|
|
585
|
+
def meta(self) -> dict:
|
|
586
|
+
r = self.receiver()
|
|
587
|
+
return {
|
|
588
|
+
"specVersion": spec_version(self.d),
|
|
589
|
+
"stateUpdatedAt": self.state()["updatedAt"],
|
|
590
|
+
"lastSent": self.last_sent(),
|
|
591
|
+
"consumed": read_consumed(self.d),
|
|
592
|
+
"waiter": r["ready"],
|
|
593
|
+
"via": r["via"],
|
|
594
|
+
"delivery": read_json(self.d / PRIV_D / "delivery.json", None),
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
def _save(self, st: dict) -> dict:
|
|
598
|
+
cur = self.state()
|
|
599
|
+
# 늦게 도착한 옛 저장 요청이 새 상태를 덮지 않게 한다.
|
|
600
|
+
if cur["updatedAt"] and st["updatedAt"] and st["updatedAt"] < cur["updatedAt"]:
|
|
601
|
+
return cur
|
|
602
|
+
write_json(self.d / STATE_F, st)
|
|
603
|
+
try:
|
|
604
|
+
build_static(self.d)
|
|
605
|
+
except Exception as e: # 정적 사본은 부가 기능이라 저장을 막지 않는다
|
|
606
|
+
print(f"index.html 갱신 실패: {e}", file=sys.stderr, flush=True)
|
|
607
|
+
return st
|
|
608
|
+
|
|
609
|
+
def save(self, st) -> dict:
|
|
610
|
+
with self.lock:
|
|
611
|
+
return self._save(clean_state(st))
|
|
612
|
+
|
|
613
|
+
def submit(self, st) -> dict:
|
|
614
|
+
spec, errs, _ = load_spec(self.d)
|
|
615
|
+
if errs:
|
|
616
|
+
raise ValueError("agenda.json 오류: " + "; ".join(errs))
|
|
617
|
+
via = self.receiver()["via"]
|
|
618
|
+
with self.lock:
|
|
619
|
+
st = self._save(clean_state(st))
|
|
620
|
+
seq = latest_seq(self.d) + 1
|
|
621
|
+
sub = {
|
|
622
|
+
"seq": seq,
|
|
623
|
+
"sentAt": now_iso(),
|
|
624
|
+
"title": spec["title"],
|
|
625
|
+
"dir": str(self.d),
|
|
626
|
+
"stateUpdatedAt": st["updatedAt"],
|
|
627
|
+
"items": resolve(spec, st),
|
|
628
|
+
"note": st["note"].strip(),
|
|
629
|
+
"via": via,
|
|
630
|
+
"tabClosed": bool(opened_tab(self.d)),
|
|
631
|
+
}
|
|
632
|
+
sub["message"] = format_message(sub, self.d)
|
|
633
|
+
if via in ("inbox", "orca"):
|
|
634
|
+
# 서버가 넣기 전에 wait 가 먼저 집어 가 두 번 들어가지 않게, 쓰기 전에 전달한 것으로 적어 둔다.
|
|
635
|
+
atomic_write(priv(self.d) / "consumed", str(seq))
|
|
636
|
+
write_json(self.d / SUBS_D / f"{seq:04d}.json", sub)
|
|
637
|
+
delivery = None
|
|
638
|
+
if via == "inbox":
|
|
639
|
+
delivery = deliver_inbox(self.d, sub)
|
|
640
|
+
if not delivery["ok"] and target_terminal(self.d) and not pid_alive(read_pid(self.d / PRIV_D / "waiter.pid")):
|
|
641
|
+
via = "orca" # 소켓이 죽었으면 (세션 재시작 등) Orca 입력창으로 넘어간다
|
|
642
|
+
if via == "orca":
|
|
643
|
+
delivery = deliver_orca(self.d, sub)
|
|
644
|
+
if delivery is not None and not delivery["ok"]:
|
|
645
|
+
with self.lock:
|
|
646
|
+
# 못 넣었으면 다음에 띄우는 wait 가 받을 수 있게 되돌린다.
|
|
647
|
+
if read_consumed(self.d) == seq:
|
|
648
|
+
atomic_write(priv(self.d) / "consumed", str(seq - 1))
|
|
649
|
+
close = sub["tabClosed"] and (delivery is None or delivery["ok"])
|
|
650
|
+
if close:
|
|
651
|
+
# 응답이 페이지에 닿아 "보냈다" 를 보인 뒤에 닫는다. 못 넣었으면 사용자가 안내를 보게 탭을 남긴다.
|
|
652
|
+
threading.Timer(TAB_CLOSE_DELAY, close_tab, args=(self.d,)).start()
|
|
653
|
+
r = self.receiver()
|
|
654
|
+
return {"lastSent": {"seq": seq, "sentAt": sub["sentAt"], "stateUpdatedAt": sub["stateUpdatedAt"]},
|
|
655
|
+
"consumed": read_consumed(self.d),
|
|
656
|
+
"waiter": r["ready"],
|
|
657
|
+
"via": via,
|
|
658
|
+
"delivery": delivery,
|
|
659
|
+
"closeTab": close}
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
class Handler(SimpleHTTPRequestHandler):
|
|
663
|
+
server_version = "agenda-picker/1"
|
|
664
|
+
|
|
665
|
+
@property
|
|
666
|
+
def app(self) -> App:
|
|
667
|
+
return self.server.app # type: ignore[attr-defined]
|
|
668
|
+
|
|
669
|
+
def log_message(self, fmt, *args):
|
|
670
|
+
pass
|
|
671
|
+
|
|
672
|
+
def end_headers(self):
|
|
673
|
+
self.send_header("Cache-Control", "no-store")
|
|
674
|
+
if getattr(self, "_frame_file", False):
|
|
675
|
+
# 폴더 안 HTML (개념 그림 등) 은 스크립트를 막는다. 그림 HTML 이 같은 origin 에서 돌면 페이지를 읽어 보내기 토큰을
|
|
676
|
+
# 얻을 수 있기 때문이다. allow-same-origin 은 남겨 페이지가 내용 높이를 재고 테마를 넘기게 한다.
|
|
677
|
+
self.send_header("Content-Security-Policy", "sandbox allow-same-origin")
|
|
678
|
+
super().end_headers()
|
|
679
|
+
|
|
680
|
+
def list_directory(self, path):
|
|
681
|
+
self.send_error(404)
|
|
682
|
+
return None
|
|
683
|
+
|
|
684
|
+
def _send(self, code: int, body: bytes, ctype: str):
|
|
685
|
+
self.send_response(code)
|
|
686
|
+
self.send_header("Content-Type", ctype)
|
|
687
|
+
self.send_header("Content-Length", str(len(body)))
|
|
688
|
+
self.end_headers()
|
|
689
|
+
self.wfile.write(body)
|
|
690
|
+
|
|
691
|
+
def _json(self, code: int, obj):
|
|
692
|
+
self._send(code, json.dumps(obj, ensure_ascii=False).encode(), "application/json; charset=utf-8")
|
|
693
|
+
|
|
694
|
+
def _guard(self) -> bool:
|
|
695
|
+
self.app.last_request = time.time()
|
|
696
|
+
# Host 검사: DNS rebinding 으로 다른 사이트가 이 서버를 같은 출처처럼 읽는 것을 막는다.
|
|
697
|
+
if self.headers.get("Host", "") not in self.app.hosts:
|
|
698
|
+
self._json(403, {"error": "host", "message": "허용하지 않는 Host"})
|
|
699
|
+
return False
|
|
700
|
+
origin = self.headers.get("Origin")
|
|
701
|
+
if origin and origin not in self.app.origins:
|
|
702
|
+
self._json(403, {"error": "origin", "message": "허용하지 않는 Origin"})
|
|
703
|
+
return False
|
|
704
|
+
return True
|
|
705
|
+
|
|
706
|
+
def _api_guard(self) -> bool:
|
|
707
|
+
# 토큰은 서버가 그린 페이지에만 들어 있다. 다른 탭의 웹페이지가 보내기를 흉내 내지 못하게 한다.
|
|
708
|
+
if self.headers.get("X-Picker-Token") != self.app.token:
|
|
709
|
+
self._json(403, {"error": "token", "message": "페이지가 오래됐다. 새로고침한다."})
|
|
710
|
+
return False
|
|
711
|
+
return True
|
|
712
|
+
|
|
713
|
+
def _body(self):
|
|
714
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
715
|
+
if n <= 0 or n > MAX_BODY:
|
|
716
|
+
raise ValueError("본문 크기가 맞지 않는다")
|
|
717
|
+
return json.loads(self.rfile.read(n).decode("utf-8"))
|
|
718
|
+
|
|
719
|
+
def do_GET(self):
|
|
720
|
+
if not self._guard():
|
|
721
|
+
return
|
|
722
|
+
path = unquote(urlsplit(self.path).path)
|
|
723
|
+
if path in ("/", "/index.html"):
|
|
724
|
+
body = render(self.app.d, "server", self.app.token, self.app.port).encode()
|
|
725
|
+
return self._send(200, body, "text/html; charset=utf-8")
|
|
726
|
+
if path.startswith("/api/"):
|
|
727
|
+
if not self._api_guard():
|
|
728
|
+
return
|
|
729
|
+
if path == "/api/meta":
|
|
730
|
+
return self._json(200, self.app.meta())
|
|
731
|
+
if path == "/api/state":
|
|
732
|
+
return self._json(200, self.app.state())
|
|
733
|
+
return self._json(404, {"error": "not found"})
|
|
734
|
+
if any(seg.startswith(".") for seg in path.split("/") if seg):
|
|
735
|
+
return self._json(404, {"error": "not found"})
|
|
736
|
+
self._frame_file = bool(FRAME_RE.search(path))
|
|
737
|
+
if self.headers.get("Range") and self._send_range():
|
|
738
|
+
return None
|
|
739
|
+
return super().do_GET()
|
|
740
|
+
|
|
741
|
+
def _send_range(self) -> bool:
|
|
742
|
+
"""Range 요청이면 206 으로 그 구간만 보낸다. Safari 는 이것 없이는 영상을 틀지 않고, 영상 앞뒤 이동도 이것에 기댄다.
|
|
743
|
+
한 구간 요청만 받는다. 아니면 False 를 돌려 파일 전체를 보내게 한다."""
|
|
744
|
+
m = RANGE_RE.fullmatch(self.headers.get("Range", "").strip())
|
|
745
|
+
f = Path(self.translate_path(self.path))
|
|
746
|
+
if not m or m.groups() == ("", "") or not f.is_file():
|
|
747
|
+
return False
|
|
748
|
+
size = f.stat().st_size
|
|
749
|
+
a, b = m.groups()
|
|
750
|
+
start, end = (int(a), min(int(b), size - 1) if b else size - 1) if a else (max(size - int(b), 0), size - 1)
|
|
751
|
+
if start > end:
|
|
752
|
+
self.send_response(416)
|
|
753
|
+
self.send_header("Content-Range", f"bytes */{size}")
|
|
754
|
+
self.send_header("Content-Length", "0")
|
|
755
|
+
self.end_headers()
|
|
756
|
+
return True
|
|
757
|
+
self.send_response(206)
|
|
758
|
+
self.send_header("Content-Type", self.guess_type(str(f)))
|
|
759
|
+
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
|
|
760
|
+
self.send_header("Content-Length", str(end - start + 1))
|
|
761
|
+
self.send_header("Accept-Ranges", "bytes")
|
|
762
|
+
self.end_headers()
|
|
763
|
+
with f.open("rb") as fh:
|
|
764
|
+
fh.seek(start)
|
|
765
|
+
left = end - start + 1
|
|
766
|
+
while left > 0:
|
|
767
|
+
chunk = fh.read(min(left, 1 << 16))
|
|
768
|
+
if not chunk:
|
|
769
|
+
break
|
|
770
|
+
self.wfile.write(chunk)
|
|
771
|
+
left -= len(chunk)
|
|
772
|
+
return True
|
|
773
|
+
|
|
774
|
+
def do_HEAD(self):
|
|
775
|
+
self._json(405, {"error": "method"})
|
|
776
|
+
|
|
777
|
+
def _write(self, fn):
|
|
778
|
+
if not (self._guard() and self._api_guard()):
|
|
779
|
+
return
|
|
780
|
+
try:
|
|
781
|
+
self._json(200, fn(self._body()))
|
|
782
|
+
except (ValueError, json.JSONDecodeError) as e:
|
|
783
|
+
self._json(400, {"error": "bad request", "message": str(e)})
|
|
784
|
+
|
|
785
|
+
def do_PUT(self):
|
|
786
|
+
if urlsplit(self.path).path == "/api/state":
|
|
787
|
+
return self._write(lambda b: {"ok": True, "state": self.app.save(b)})
|
|
788
|
+
self._json(404, {"error": "not found"})
|
|
789
|
+
|
|
790
|
+
def do_POST(self):
|
|
791
|
+
if urlsplit(self.path).path == "/api/submit":
|
|
792
|
+
return self._write(self.app.submit)
|
|
793
|
+
self._json(404, {"error": "not found"})
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def ping(d: Path, url: str) -> bool:
|
|
797
|
+
req = urllib.request.Request(url.rstrip("/") + "/api/meta", headers={"X-Picker-Token": token_of(d)})
|
|
798
|
+
try:
|
|
799
|
+
with urllib.request.urlopen(req, timeout=1) as r:
|
|
800
|
+
return r.status == 200
|
|
801
|
+
except Exception:
|
|
802
|
+
return False
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def running_server(d: Path):
|
|
806
|
+
info = read_json(d / PRIV_D / "server.json", None)
|
|
807
|
+
if isinstance(info, dict) and pid_alive(info.get("pid")) and ping(d, info.get("url", "")):
|
|
808
|
+
return info
|
|
809
|
+
return None
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def in_orca() -> bool:
|
|
813
|
+
return os.environ.get("TERM_PROGRAM") == "Orca" and shutil.which(ORCA) is not None
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def orca_json(*args, timeout: float = 20) -> dict:
|
|
817
|
+
r = subprocess.run([ORCA, *args, "--json"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout)
|
|
818
|
+
try:
|
|
819
|
+
data = json.loads(r.stdout)
|
|
820
|
+
except json.JSONDecodeError:
|
|
821
|
+
raise RuntimeError((r.stderr or r.stdout).strip()[:300] or f"exit {r.returncode}")
|
|
822
|
+
if not data.get("ok"):
|
|
823
|
+
raise RuntimeError(json.dumps(data.get("error") or data, ensure_ascii=False)[:300])
|
|
824
|
+
return data.get("result") or {}
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def remember_target(d: Path) -> None:
|
|
828
|
+
"""보내기를 넣을 Orca 터미널을 적어 둔다. serve · open 을 부른 Claude 세션의 터미널이다.
|
|
829
|
+
|
|
830
|
+
서버는 처음 띄운 세션의 환경을 물려받으므로, 다른 세션이 같은 폴더로 serve · open 을 다시 부르면 그쪽으로 바꾼다.
|
|
831
|
+
"""
|
|
832
|
+
f = priv(d) / "target.json"
|
|
833
|
+
handle = os.environ.get("ORCA_TERMINAL_HANDLE", "").strip()
|
|
834
|
+
if in_orca() and handle:
|
|
835
|
+
write_json(f, {"terminal": handle, "worktree": os.environ.get("ORCA_WORKTREE_ID", ""), "savedAt": now_iso()})
|
|
836
|
+
else:
|
|
837
|
+
f.unlink(missing_ok=True)
|
|
838
|
+
# Claude Code 는 세션마다 인박스 소켓을 열고, 그 경로와 토큰을 Bash · 훅 환경에 넘긴다. 토큰이 있어 0600 으로 적는다
|
|
839
|
+
ib = priv(d) / "inbox.json"
|
|
840
|
+
sock, tok = os.environ.get("CLAUDE_CODE_MESSAGING_SOCKET", ""), os.environ.get("CLAUDE_CODE_MESSAGING_TOKEN", "")
|
|
841
|
+
if sock and tok:
|
|
842
|
+
write_json(ib, {"socket": sock, "token": tok, "sessionId": os.environ.get("CLAUDE_CODE_SESSION_ID", ""),
|
|
843
|
+
"savedAt": now_iso()})
|
|
844
|
+
try:
|
|
845
|
+
os.chmod(ib, 0o600)
|
|
846
|
+
except OSError:
|
|
847
|
+
pass
|
|
848
|
+
else:
|
|
849
|
+
ib.unlink(missing_ok=True)
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
def inbox_target(d: Path) -> dict:
|
|
853
|
+
"""적어 둔 인박스 소켓이 아직 있으면 그 정보 (세션이 끝나면 소켓 파일이 사라진다)."""
|
|
854
|
+
info = read_json(d / PRIV_D / "inbox.json", None)
|
|
855
|
+
if not isinstance(info, dict) or not info.get("socket") or not info.get("token"):
|
|
856
|
+
return {}
|
|
857
|
+
sock = info["socket"]
|
|
858
|
+
if not sock.startswith("\\\\.\\pipe\\") and not os.path.exists(sock):
|
|
859
|
+
return {}
|
|
860
|
+
return info
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
# 쓰자마자 끝나는 도우미. 상주 프로세스가 소켓에 직접 쓰면 Claude Code 가 살아 있는 다른 프로세스로 보고 승인 대기에
|
|
864
|
+
# 걸 수 있어서, 연결 · 전송 후 바로 끝나 토큰으로 확인받게 한다 (wire 플러그인 broker 와 같은 방식).
|
|
865
|
+
INBOX_HELPER = r"""
|
|
866
|
+
import json, os, socket, sys
|
|
867
|
+
cfg = json.loads(sys.stdin.read())
|
|
868
|
+
lines = (json.dumps({"type": "auth", "token": cfg["token"]}) + "\n"
|
|
869
|
+
+ json.dumps({"type": "user", "message": {"role": "user", "content": cfg["text"]}}, ensure_ascii=False) + "\n").encode()
|
|
870
|
+
path = cfg["socket"]
|
|
871
|
+
if path.startswith("\\\\.\\pipe\\"): # Windows named pipe
|
|
872
|
+
with open(path, "wb", buffering=0) as f:
|
|
873
|
+
f.write(lines)
|
|
874
|
+
else:
|
|
875
|
+
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
876
|
+
s.settimeout(5)
|
|
877
|
+
s.connect(path)
|
|
878
|
+
s.sendall(lines)
|
|
879
|
+
s.close()
|
|
880
|
+
"""
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def deliver_inbox(d: Path, sub: dict) -> dict:
|
|
884
|
+
"""Claude 세션 인박스 소켓으로 보낸 내용 전체를 바로 넣는다 (0.1초 안팎, 2026-10-07 실측). 타이핑이 아니라 셸에 들어갈
|
|
885
|
+
걱정이 없고, 세션이 쉬고 있으면 깨어나고 일하는 중이면 끼어 들어간다. Claude 쪽에는 다른 세션이 보낸 메시지로 보인다."""
|
|
886
|
+
info = inbox_target(d)
|
|
887
|
+
res = {"seq": sub["seq"], "via": "inbox", "ok": False, "message": ""}
|
|
888
|
+
t0 = time.time()
|
|
889
|
+
if not info:
|
|
890
|
+
res["message"] = "Claude 세션 인박스 소켓이 없다 (세션이 끝났거나 다시 시작됐다)."
|
|
891
|
+
else:
|
|
892
|
+
try:
|
|
893
|
+
r = subprocess.run([sys.executable, "-c", INBOX_HELPER], input=json.dumps(
|
|
894
|
+
{"socket": info["socket"], "token": info["token"], "text": sub["message"]}, ensure_ascii=False),
|
|
895
|
+
capture_output=True, text=True, encoding="utf-8", timeout=10)
|
|
896
|
+
if r.returncode == 0:
|
|
897
|
+
res.update(ok=True, message="Claude 세션에 바로 넣었다.")
|
|
898
|
+
else:
|
|
899
|
+
res["message"] = "Claude 세션에 넣지 못했다: " + (r.stderr.strip().splitlines() or ["?"])[-1][:200]
|
|
900
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
901
|
+
res["message"] = f"Claude 세션에 넣지 못했다: {e}"
|
|
902
|
+
res.update(at=now_iso(), tookSec=round(time.time() - t0, 2))
|
|
903
|
+
print(f"전달 #{sub['seq']} ({res['tookSec']}초, inbox): {res['message']}", flush=True)
|
|
904
|
+
write_json(priv(d) / "delivery.json", res)
|
|
905
|
+
return res
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def target_terminal(d: Path) -> str:
|
|
909
|
+
info = read_json(d / PRIV_D / "target.json", None)
|
|
910
|
+
return info.get("terminal", "") if isinstance(info, dict) else ""
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def deliver_orca(d: Path, sub: dict) -> dict:
|
|
914
|
+
"""에이전트 터미널 입력창에 한 줄을 넣고 Enter. 그 터미널에 이제 에이전트가 없으면(셸로 돌아갔으면) 넣지 않는다.
|
|
915
|
+
|
|
916
|
+
agentIdentity 가 비었을 때만 막는다. 값은 가리지 않는다: Claude 는 "claude", Orca 팀 에이전트로 연 Claude 는
|
|
917
|
+
"claude-agent-teams" 이고 (2026-10-07 실측), 다른 에이전트도 넣는 한 줄(submissions 파일을 읽으라는 안내)을 그대로 처리한다.
|
|
918
|
+
셸 · python · pnpm 같은 터미널은 null 이다. 막는 까닭은 셸에 넣은 글이 명령으로 실행되는 것 하나다.
|
|
919
|
+
"""
|
|
920
|
+
handle = target_terminal(d)
|
|
921
|
+
res = {"seq": sub["seq"], "via": "orca", "terminal": handle, "ok": False, "message": ""}
|
|
922
|
+
# terminal send 는 몇 초 걸린다 (실측). 그동안 페이지가 "전달됐다" 로 앞서 보이지 않게 넣는 중임을 적어 둔다.
|
|
923
|
+
write_json(priv(d) / "delivery.json", dict(res, pending=True, message="Claude 입력창에 넣는 중이다."))
|
|
924
|
+
t0 = time.time()
|
|
925
|
+
try:
|
|
926
|
+
show = orca_json("terminal", "show", "--terminal", handle)
|
|
927
|
+
term = show.get("terminal") if isinstance(show.get("terminal"), dict) else show
|
|
928
|
+
who = term.get("agentIdentity")
|
|
929
|
+
if not who:
|
|
930
|
+
res["message"] = ("그 터미널에 지금 에이전트가 없어(셸로 돌아갔다) 넣지 않았다. "
|
|
931
|
+
f"보낸 내용은 submissions/{sub['seq']:04d}.json 에 있다.")
|
|
932
|
+
else:
|
|
933
|
+
# Claude 가 일하는 중에 넣으면 8초 남짓 걸렸다 (2026-10-05 실측). 시간 초과로 실패라 적었는데 실제로는 들어가 있으면
|
|
934
|
+
# 뒤의 wait 가 한 번 더 받으므로 넉넉히 기다린다.
|
|
935
|
+
orca_json("terminal", "send", "--terminal", handle, "--text", one_line(sub, d), "--enter", timeout=45)
|
|
936
|
+
res.update(ok=True, message="Claude 입력창에 넣었다.")
|
|
937
|
+
except (RuntimeError, OSError, subprocess.TimeoutExpired) as e:
|
|
938
|
+
res["message"] = f"Claude 터미널에 넣지 못했다: {e}"
|
|
939
|
+
res.update(at=now_iso(), tookSec=round(time.time() - t0, 2))
|
|
940
|
+
print(f"전달 #{sub['seq']} ({res['tookSec']}초): {res['message']}", flush=True)
|
|
941
|
+
write_json(priv(d) / "delivery.json", res)
|
|
942
|
+
return res
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
def own_worktree() -> str:
|
|
946
|
+
"""이 명령을 부른 Claude 세션이 떠 있는 Orca worktree 의 선택자.
|
|
947
|
+
|
|
948
|
+
--worktree 를 빼면 Orca 는 화면에서 지금 보고 있는 worktree 에 탭을 만든다 (실측). 스킬을 켜 두고 다른 worktree 로
|
|
949
|
+
옮겨 가 있으면 탭이 엉뚱한 곳에 뜨므로, 세션 터미널이 물려받은 ORCA_WORKTREE_ID (<repoId>::<path>) 로 고정한다.
|
|
950
|
+
떠 있는 터미널(global-floating-terminal)은 worktree 가 아니라 선택자로 가리킬 수 없어 "" 를 돌려준다.
|
|
951
|
+
"""
|
|
952
|
+
return sel_of(os.environ.get("ORCA_WORKTREE_ID", "").strip())
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
def sel_of(worktree_id) -> str:
|
|
956
|
+
return f"id:{worktree_id}" if isinstance(worktree_id, str) and "::" in worktree_id else ""
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
def find_tab(page: str, wt: str = "") -> dict:
|
|
960
|
+
tabs = orca_json("tab", "list", *(["--worktree", wt] if wt else [])).get("tabs", [])
|
|
961
|
+
return next((t for t in tabs if t.get("browserPageId") == page), {}) if page else {}
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def switch_tab(page: str, wt: str) -> None:
|
|
965
|
+
"""화면을 그 탭으로 바꾼다. 사용자가 요청한 동작이다 (Orca 안의 탭 전환이라 다른 앱의 포커스는 건드리지 않는다)."""
|
|
966
|
+
try:
|
|
967
|
+
orca_json("tab", "switch", "--page", page, *(["--worktree", wt] if wt else []), "--focus")
|
|
968
|
+
except (RuntimeError, OSError, subprocess.TimeoutExpired) as e:
|
|
969
|
+
print(f"탭은 열었지만 화면을 그 탭으로 바꾸지 못했다: {e}", file=sys.stderr, flush=True)
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def tab_info(d: Path) -> dict:
|
|
973
|
+
info = read_json(d / PRIV_D / "tab.json", None)
|
|
974
|
+
return info if isinstance(info, dict) and info.get("pageId") else {}
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def opened_tab(d: Path) -> str:
|
|
978
|
+
return tab_info(d).get("pageId", "")
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
def close_tab(d: Path) -> bool:
|
|
982
|
+
info = tab_info(d)
|
|
983
|
+
page = info.get("pageId", "")
|
|
984
|
+
if not page:
|
|
985
|
+
return False
|
|
986
|
+
try:
|
|
987
|
+
orca_json("tab", "close", "--page", page, *(["--worktree", info["worktree"]] if info.get("worktree") else []))
|
|
988
|
+
print(f"Orca 탭을 닫았다 (page {page})", flush=True)
|
|
989
|
+
return True
|
|
990
|
+
except (RuntimeError, OSError, subprocess.TimeoutExpired) as e:
|
|
991
|
+
print(f"Orca 탭을 닫지 못했다 (page {page}): {e}", file=sys.stderr, flush=True)
|
|
992
|
+
return False
|
|
993
|
+
finally:
|
|
994
|
+
# 닫았든, 사용자가 먼저 닫아 없든 다시 시도하지 않는다.
|
|
995
|
+
(d / PRIV_D / "tab.json").unlink(missing_ok=True)
|
|
996
|
+
|
|
997
|
+
|
|
998
|
+
def open_page(d: Path, url: str) -> int:
|
|
999
|
+
if not in_orca():
|
|
1000
|
+
# 포커스를 가져가지 않게 -g (백그라운드로 연다)
|
|
1001
|
+
if sys.platform == "darwin":
|
|
1002
|
+
subprocess.run(["open", "-g", url], check=False)
|
|
1003
|
+
print(f"기본 브라우저로 열었다: {url}", flush=True)
|
|
1004
|
+
else:
|
|
1005
|
+
print(f"브라우저에서 연다: {url}", flush=True)
|
|
1006
|
+
return 0
|
|
1007
|
+
own = own_worktree()
|
|
1008
|
+
info = tab_info(d)
|
|
1009
|
+
try:
|
|
1010
|
+
hit = find_tab(info.get("pageId", ""), info.get("worktree", ""))
|
|
1011
|
+
if hit:
|
|
1012
|
+
page, wt = hit["browserPageId"], info.get("worktree", "")
|
|
1013
|
+
print(f"Orca 탭이 이미 열려 있어 그 탭으로 바꾼다 (page {page}). 새로고침만 하면 된다: {url}", flush=True)
|
|
1014
|
+
else:
|
|
1015
|
+
page = orca_json("tab", "create", "--url", url, *(["--worktree", own] if own else [])).get("browserPageId", "")
|
|
1016
|
+
wt = own
|
|
1017
|
+
if not wt:
|
|
1018
|
+
# 떠 있는 터미널은 worktree 가 아니라 선택자로 고를 수 없다. Orca 는 지금 화면에 보이는 worktree 에 탭을 만들고,
|
|
1019
|
+
# 떠 있는 터미널은 그 위에 떠 있으니 사용자가 보는 곳이다. 붙은 곳을 적어 두고 닫을 때 쓴다.
|
|
1020
|
+
wt = sel_of(find_tab(page).get("worktreeId"))
|
|
1021
|
+
write_json(priv(d) / "tab.json", {"pageId": page, "url": url, "worktree": wt, "openedAt": now_iso()})
|
|
1022
|
+
print(f"Orca 탭으로 열었다: {url} (page {page}, worktree {wt or '화면에 보이는 곳'})", flush=True)
|
|
1023
|
+
except (RuntimeError, OSError, subprocess.TimeoutExpired) as e:
|
|
1024
|
+
print(f"Orca 탭을 열지 못했다: {e}\n샌드박스 밖에서 실행했는지 본다 (dangerouslyDisableSandbox).", file=sys.stderr)
|
|
1025
|
+
return 1
|
|
1026
|
+
switch_tab(page, wt)
|
|
1027
|
+
return 0
|
|
1028
|
+
|
|
1029
|
+
|
|
1030
|
+
def route_text(d: Path) -> str:
|
|
1031
|
+
if inbox_target(d):
|
|
1032
|
+
return "이 Claude 세션 인박스 (바로 넣는다" + (", 안 되면 이 Orca 터미널 입력창" if target_terminal(d) else "") + ")"
|
|
1033
|
+
if target_terminal(d):
|
|
1034
|
+
return "이 Orca 터미널 입력창 (" + target_terminal(d) + ")"
|
|
1035
|
+
return "wait (백그라운드로 띄운다)"
|
|
1036
|
+
|
|
1037
|
+
|
|
1038
|
+
def cmd_open(d: Path) -> int:
|
|
1039
|
+
info = running_server(d)
|
|
1040
|
+
if not info:
|
|
1041
|
+
print("서버가 떠 있지 않다. serve 를 먼저 띄운다.", file=sys.stderr)
|
|
1042
|
+
return 1
|
|
1043
|
+
remember_target(d)
|
|
1044
|
+
return open_page(d, info["url"])
|
|
1045
|
+
|
|
1046
|
+
|
|
1047
|
+
def cmd_serve(d: Path, port: int, open_: bool, idle: float, foreground: bool) -> int:
|
|
1048
|
+
if foreground:
|
|
1049
|
+
return run_server(d, port, idle)
|
|
1050
|
+
_, errs, warns = load_spec(d)
|
|
1051
|
+
for w in warns:
|
|
1052
|
+
print(f"WARN {w}", flush=True)
|
|
1053
|
+
for e in errs:
|
|
1054
|
+
print(f"ERROR {e} (고칠 때까지 페이지는 오류 화면을 보인다)", flush=True)
|
|
1055
|
+
|
|
1056
|
+
remember_target(d)
|
|
1057
|
+
info = running_server(d)
|
|
1058
|
+
if info:
|
|
1059
|
+
print(f"URL: {info['url']}", flush=True)
|
|
1060
|
+
print(f"이미 떠 있다 (pid {info['pid']}). 열려 있던 탭은 새로고침만 하면 된다.", flush=True)
|
|
1061
|
+
print(f"보내기 전달: {route_text(d)}",
|
|
1062
|
+
flush=True)
|
|
1063
|
+
return open_page(d, info["url"]) if open_ else 0
|
|
1064
|
+
|
|
1065
|
+
# Claude 백그라운드 작업은 한도(기본 30분, 최대 2시간)가 지나면 끝나 페이지가 끊겼다. 그래서 서버는 새 세션(setsid)의
|
|
1066
|
+
# 독립 프로세스로 떼어 내고, 요청 없이 idle 초가 지나면 스스로 끝나게 한다. 이 명령은 서버가 뜨는 것만 보고 끝난다.
|
|
1067
|
+
log = priv(d) / "server.log"
|
|
1068
|
+
cmd = [sys.executable, str(SELF), "serve", str(d), "--foreground", "--idle", str(idle)] + (["--port", str(port)] if port else [])
|
|
1069
|
+
with open(log, "ab") as f:
|
|
1070
|
+
proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=f, stderr=subprocess.STDOUT,
|
|
1071
|
+
start_new_session=True, close_fds=True)
|
|
1072
|
+
deadline = time.time() + 10
|
|
1073
|
+
while time.time() < deadline:
|
|
1074
|
+
info = running_server(d)
|
|
1075
|
+
if info and info.get("pid") == proc.pid:
|
|
1076
|
+
break
|
|
1077
|
+
if proc.poll() is not None:
|
|
1078
|
+
tail = log.read_text(encoding="utf-8", errors="replace").splitlines()[-5:]
|
|
1079
|
+
print("서버가 뜨지 못했다:\n" + "\n".join(tail), file=sys.stderr)
|
|
1080
|
+
return 1
|
|
1081
|
+
time.sleep(0.1)
|
|
1082
|
+
else:
|
|
1083
|
+
print(f"서버가 10초 안에 응답하지 않았다. 로그: {log}", file=sys.stderr)
|
|
1084
|
+
return 1
|
|
1085
|
+
print(f"URL: {info['url']}", flush=True)
|
|
1086
|
+
print(f"폴더: {d}", flush=True)
|
|
1087
|
+
print(f"서버: pid {proc.pid}, 독립 프로세스 (요청 없이 {idle / 3600:g}시간이면 끝난다), 로그 {log}", flush=True)
|
|
1088
|
+
print(f"보내기 전달: {route_text(d)}",
|
|
1089
|
+
flush=True)
|
|
1090
|
+
return open_page(d, info["url"]) if open_ else 0
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
def run_server(d: Path, port: int, idle: float) -> int:
|
|
1094
|
+
handler = functools.partial(Handler, directory=str(d))
|
|
1095
|
+
ports = [port] if port else [preferred_port(d) + i for i in range(20)]
|
|
1096
|
+
srv = None
|
|
1097
|
+
for p in ports:
|
|
1098
|
+
try:
|
|
1099
|
+
srv = ThreadingHTTPServer(("127.0.0.1", p), handler)
|
|
1100
|
+
break
|
|
1101
|
+
except OSError:
|
|
1102
|
+
continue
|
|
1103
|
+
if srv is None:
|
|
1104
|
+
print(f"포트를 잡지 못했다: {ports[0]}~{ports[-1]}", file=sys.stderr)
|
|
1105
|
+
return 1
|
|
1106
|
+
p = srv.server_address[1]
|
|
1107
|
+
srv.app = App(d, p) # type: ignore[attr-defined]
|
|
1108
|
+
url = f"http://127.0.0.1:{p}/"
|
|
1109
|
+
info_f = priv(d) / "server.json"
|
|
1110
|
+
write_json(info_f, {"pid": os.getpid(), "port": p, "url": url, "startedAt": now_iso(), "idleSec": idle})
|
|
1111
|
+
try:
|
|
1112
|
+
build_static(d)
|
|
1113
|
+
except Exception as e: # 정적 사본은 부가 기능이라 서버를 막지 않는다
|
|
1114
|
+
print(f"index.html 생성 실패: {e}", file=sys.stderr, flush=True)
|
|
1115
|
+
|
|
1116
|
+
def bye(*_):
|
|
1117
|
+
try:
|
|
1118
|
+
if (read_json(info_f, {}) or {}).get("pid") == os.getpid():
|
|
1119
|
+
info_f.unlink()
|
|
1120
|
+
finally:
|
|
1121
|
+
os._exit(0)
|
|
1122
|
+
|
|
1123
|
+
def idle_watch():
|
|
1124
|
+
while True:
|
|
1125
|
+
time.sleep(max(0.5, min(60.0, idle / 4)))
|
|
1126
|
+
if time.time() - srv.app.last_request > idle: # type: ignore[attr-defined]
|
|
1127
|
+
print(f"{now_iso()} 요청 없이 {idle:g}초가 지나 끝낸다", flush=True)
|
|
1128
|
+
bye()
|
|
1129
|
+
|
|
1130
|
+
signal.signal(signal.SIGTERM, bye)
|
|
1131
|
+
signal.signal(signal.SIGHUP, signal.SIG_IGN) # 띄운 셸이 끝나도 남는다
|
|
1132
|
+
if idle > 0:
|
|
1133
|
+
threading.Thread(target=idle_watch, daemon=True).start()
|
|
1134
|
+
print(f"{now_iso()} URL: {url} (pid {os.getpid()})", flush=True)
|
|
1135
|
+
try:
|
|
1136
|
+
srv.serve_forever()
|
|
1137
|
+
except KeyboardInterrupt:
|
|
1138
|
+
bye()
|
|
1139
|
+
return 0
|
|
1140
|
+
|
|
1141
|
+
|
|
1142
|
+
def cmd_wait(d: Path, timeout: float) -> int:
|
|
1143
|
+
pidf = priv(d) / "waiter.pid"
|
|
1144
|
+
old = read_pid(pidf)
|
|
1145
|
+
if old and old != os.getpid() and pid_alive(old):
|
|
1146
|
+
# 대기는 하나만 둔다. 새로 띄운 쪽이 이어받는다.
|
|
1147
|
+
os.kill(old, signal.SIGTERM)
|
|
1148
|
+
for _ in range(20):
|
|
1149
|
+
if not pid_alive(old):
|
|
1150
|
+
break
|
|
1151
|
+
time.sleep(0.1)
|
|
1152
|
+
pidf.write_text(str(os.getpid()))
|
|
1153
|
+
|
|
1154
|
+
def cleanup():
|
|
1155
|
+
if read_pid(pidf) == os.getpid():
|
|
1156
|
+
pidf.unlink(missing_ok=True)
|
|
1157
|
+
|
|
1158
|
+
def on_term(*_):
|
|
1159
|
+
cleanup()
|
|
1160
|
+
print("[agenda-picker] 이 대기는 끝났다 (새 wait 가 이어받았거나 stop 으로 멈췄다). 따로 할 일은 없다.", flush=True)
|
|
1161
|
+
os._exit(0)
|
|
1162
|
+
|
|
1163
|
+
signal.signal(signal.SIGTERM, on_term)
|
|
1164
|
+
signal.signal(signal.SIGHUP, on_term)
|
|
1165
|
+
ppid = os.getppid()
|
|
1166
|
+
deadline = time.time() + timeout if timeout > 0 else None
|
|
1167
|
+
try:
|
|
1168
|
+
while True:
|
|
1169
|
+
latest, consumed = latest_seq(d), read_consumed(d)
|
|
1170
|
+
if latest > consumed:
|
|
1171
|
+
subs = [s for s in (read_json(d / SUBS_D / f"{n:04d}.json") for n in range(consumed + 1, latest + 1)) if s]
|
|
1172
|
+
atomic_write(d / PRIV_D / "consumed", str(latest))
|
|
1173
|
+
if subs:
|
|
1174
|
+
print(format_message(subs[-1], d, [s["seq"] for s in subs[:-1]]), flush=True)
|
|
1175
|
+
return 0
|
|
1176
|
+
if deadline and time.time() > deadline:
|
|
1177
|
+
print(f"[agenda-picker] {int(timeout)}초 동안 보낸 것이 없어 대기를 끝냈다. 계속 받으려면 wait 를 다시 띄운다.", flush=True)
|
|
1178
|
+
return 3
|
|
1179
|
+
if not d.exists():
|
|
1180
|
+
print(f"[agenda-picker] 폴더가 없어져 대기를 끝냈다: {d}", flush=True)
|
|
1181
|
+
return 4
|
|
1182
|
+
if ppid != 1 and os.getppid() != ppid:
|
|
1183
|
+
return 0
|
|
1184
|
+
time.sleep(POLL_SEC)
|
|
1185
|
+
finally:
|
|
1186
|
+
cleanup()
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
def cmd_status(d: Path) -> int:
|
|
1190
|
+
spec, errs, warns = load_spec(d)
|
|
1191
|
+
st = clean_state(read_json(d / STATE_F, {}))
|
|
1192
|
+
if spec and not errs:
|
|
1193
|
+
st = seed_decided(spec, st)
|
|
1194
|
+
info = running_server(d)
|
|
1195
|
+
waiter = read_pid(d / PRIV_D / "waiter.pid")
|
|
1196
|
+
print(f"폴더: {d}")
|
|
1197
|
+
print(f"서버: {'떠 있음 ' + info['url'] + ' (pid %d)' % info['pid'] if info else '꺼짐'}")
|
|
1198
|
+
print(f"대기(wait): {'대기 중 (pid %d)' % waiter if pid_alive(waiter) else '없음'}")
|
|
1199
|
+
print(f"Orca 탭: {opened_tab(d) or '없음'}")
|
|
1200
|
+
print(f"보내기 전달: {route_text(d)}")
|
|
1201
|
+
dl = read_json(d / PRIV_D / "delivery.json", None)
|
|
1202
|
+
if isinstance(dl, dict):
|
|
1203
|
+
print(f"마지막 전달: #{dl.get('seq')} {dl.get('message', '')}")
|
|
1204
|
+
if spec and not errs:
|
|
1205
|
+
items = resolve(spec, st)
|
|
1206
|
+
print(f"선택: 결정 {sum(1 for i in items if i['pick'])}/{len(items)}, 마지막 저장 {st['updatedAt'] or '-'}")
|
|
1207
|
+
for i, it in enumerate(items, 1):
|
|
1208
|
+
print(f" {i}. [{it['id']}]{pick_line(it)[len(' 선택:'):]}")
|
|
1209
|
+
for e in errs:
|
|
1210
|
+
print(f"ERROR {e}")
|
|
1211
|
+
for w in warns:
|
|
1212
|
+
print(f"WARN {w}")
|
|
1213
|
+
seq = latest_seq(d)
|
|
1214
|
+
print(f"보냄: {'#%d' % seq if seq else '없음'}, Claude 에 전달된 마지막 번호 #{read_consumed(d)}")
|
|
1215
|
+
return 0
|
|
1216
|
+
|
|
1217
|
+
|
|
1218
|
+
def cmd_stop(d: Path) -> int:
|
|
1219
|
+
stopped = []
|
|
1220
|
+
info = read_json(d / PRIV_D / "server.json", None)
|
|
1221
|
+
if isinstance(info, dict) and pid_alive(info.get("pid")):
|
|
1222
|
+
os.kill(info["pid"], signal.SIGTERM)
|
|
1223
|
+
stopped.append(f"서버 pid {info['pid']}")
|
|
1224
|
+
w = read_pid(d / PRIV_D / "waiter.pid")
|
|
1225
|
+
if pid_alive(w):
|
|
1226
|
+
os.kill(w, signal.SIGTERM)
|
|
1227
|
+
stopped.append(f"wait pid {w}")
|
|
1228
|
+
if opened_tab(d) and close_tab(d):
|
|
1229
|
+
stopped.append("Orca 탭")
|
|
1230
|
+
print("멈춤: " + ", ".join(stopped) if stopped else "떠 있는 것이 없다")
|
|
1231
|
+
return 0
|
|
1232
|
+
|
|
1233
|
+
|
|
1234
|
+
def main() -> int:
|
|
1235
|
+
for _f in (sys.stdout, sys.stderr): # Windows 콘솔(cp949)에서 ✓ · 한글을 찍다 죽지 않게
|
|
1236
|
+
try:
|
|
1237
|
+
_f.reconfigure(encoding="utf-8", errors="replace")
|
|
1238
|
+
except (AttributeError, ValueError):
|
|
1239
|
+
pass
|
|
1240
|
+
ap = argparse.ArgumentParser(description="안건 선택 페이지")
|
|
1241
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
1242
|
+
for name in ("check", "build", "open", "status", "stop"):
|
|
1243
|
+
sub.add_parser(name).add_argument("dir")
|
|
1244
|
+
s = sub.add_parser("serve")
|
|
1245
|
+
s.add_argument("dir")
|
|
1246
|
+
s.add_argument("--port", type=int, default=0)
|
|
1247
|
+
s.add_argument("--open", action="store_true", help="띄운 뒤 open 과 같이 연다")
|
|
1248
|
+
s.add_argument("--idle", type=float, default=IDLE_SEC, help="초. 요청 없이 이만큼 지나면 서버가 끝난다 (0 = 끝나지 않는다)")
|
|
1249
|
+
s.add_argument("--foreground", action="store_true", help="떼어 내지 않고 이 프로세스에서 서버를 돌린다")
|
|
1250
|
+
w = sub.add_parser("wait")
|
|
1251
|
+
w.add_argument("dir")
|
|
1252
|
+
w.add_argument("--timeout", type=float, default=0, help="초. 0 = 제한 없음 (세션이 끝나면 같이 끝난다)")
|
|
1253
|
+
a = ap.parse_args()
|
|
1254
|
+
|
|
1255
|
+
d = Path(a.dir).expanduser().resolve()
|
|
1256
|
+
if not d.is_dir():
|
|
1257
|
+
print(f"폴더가 없다: {d}", file=sys.stderr)
|
|
1258
|
+
return 1
|
|
1259
|
+
if a.cmd == "check":
|
|
1260
|
+
_, errs, warns = load_spec(d)
|
|
1261
|
+
for w_ in warns:
|
|
1262
|
+
print(f"WARN {w_}")
|
|
1263
|
+
for e in errs:
|
|
1264
|
+
print(f"ERROR {e}")
|
|
1265
|
+
print("OK" if not errs else f"오류 {len(errs)}개")
|
|
1266
|
+
return 1 if errs else 0
|
|
1267
|
+
if a.cmd == "build":
|
|
1268
|
+
_, errs, _ = load_spec(d)
|
|
1269
|
+
out = build_static(d)
|
|
1270
|
+
print(f"{out}{' (오류 화면)' if errs else ''}")
|
|
1271
|
+
return 1 if errs else 0
|
|
1272
|
+
if a.cmd == "serve":
|
|
1273
|
+
return cmd_serve(d, a.port, a.open, a.idle, a.foreground)
|
|
1274
|
+
if a.cmd == "wait":
|
|
1275
|
+
return cmd_wait(d, a.timeout)
|
|
1276
|
+
if a.cmd == "open":
|
|
1277
|
+
return cmd_open(d)
|
|
1278
|
+
if a.cmd == "status":
|
|
1279
|
+
return cmd_status(d)
|
|
1280
|
+
if a.cmd == "stop":
|
|
1281
|
+
return cmd_stop(d)
|
|
1282
|
+
return 1
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
if __name__ == "__main__":
|
|
1286
|
+
sys.exit(main())
|