Files
persona/hooks/session_start.py
T
2026-07-29 14:37:20 +00:00

74 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""SessionStart:清理死鎖、續租、並把 PERSONA_SESSION 與人格清單注入上下文。
session_id 只有 hook 拿得到,所以這裡把它注入上下文;後續 skill 呼叫 CLI 時
必須帶 `--session <這個值>`guard hook 會驗證,程序無法冒用別人的身分。
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
import persona_lib as pl # noqa: E402
def main() -> int:
try:
event = json.load(sys.stdin)
except json.JSONDecodeError:
return 0
session_id = event.get("session_id") or "unknown"
source = event.get("source") or "startup"
cwd = event.get("cwd")
pl.gc_runtime()
data = pl.load_session(session_id)
host = data.get("host")
lines = [
"<persona-runtime>",
f"PERSONA_SESSION={session_id}",
f"人格倉庫:{pl.persona_home()}",
"規則:",
" 1. 呼叫 persona.py 一律帶 `--session " + session_id + "`(值不符會被 hook 拒絕)。",
" 2. 一個程序只能載入一個人格;要與別的人格對話請用 /jsc-persona:persona-invite。",
" 3. 禁止直接讀寫非當前人格的目錄,hook 會擋下(跨人格資料隔離)。",
]
if host and pl.persona_exists(host):
# resume / compact / clear:把鎖續租回來,並帶回人格狀態
try:
pl.acquire_lock(host, session_id, cwd=cwd)
lines.append(f"已接續人格 `{host}`session 恢復:{source})。")
lines.append(pl.turn_context(host, session_id))
except pl.LockError as exc:
lines.append(f"⚠ 無法接續人格 `{host}`{exc}")
else:
personas = pl.list_personas()
if personas:
lines.append("尚未載入人格。可用人格:")
for slug in personas:
status = pl.lock_status(slug)
mark = "🔒" if status["locked"] else "🔓"
lines.append(f" - {mark} `{slug}` {pl.identity_brief(slug)}")
lines.append("載入方式:/jsc-persona:persona-chat <slug>")
else:
lines.append("尚無任何人格,可用 /jsc-persona:persona-create 建立。")
lines.append("</persona-runtime>")
print(json.dumps({
"hookSpecificOutput": {
"hookEventName": "SessionStart",
"additionalContext": "\n".join(lines),
},
"suppressOutput": True,
}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())