usage-cli 0.29.32__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- adapters/__init__.py +5 -0
- adapters/agy.py +68 -0
- adapters/claude.py +215 -0
- adapters/codex.py +209 -0
- adapters/rate_limits.py +76 -0
- adapters/registry.py +17 -0
- adapters/types.py +139 -0
- agy_disk_cache.py +135 -0
- agy_loader.py +416 -0
- agy_quota_probe.py +748 -0
- agy_window_keeper.py +185 -0
- analyzer/__init__.py +5 -0
- analyzer/aggregator.py +139 -0
- analyzer/blocks.py +80 -0
- analyzer/diagnoser.py +638 -0
- analyzer/insights.py +277 -0
- analyzer/persona_loader.py +199 -0
- analyzer/reporter.py +989 -0
- analyzer/subscription.py +108 -0
- burn_rate.py +75 -0
- cache_quarantine.py +50 -0
- codex_disk_cache.py +227 -0
- codex_events.py +136 -0
- codex_fork_replay.py +111 -0
- codex_loader.py +1426 -0
- codex_paths.py +20 -0
- critter_frames.py +26 -0
- discussion_bridge.py +1196 -0
- discussion_cli.py +844 -0
- discussion_session.py +622 -0
- discussion_usage.py +13 -0
- discussion_window.py +955 -0
- disk_cache_common.py +132 -0
- disk_cache_lifecycle.py +39 -0
- doctor.py +452 -0
- fsevents_watch.py +207 -0
- history_disk_cache.py +110 -0
- history_loader.py +416 -0
- i18n.py +88 -0
- jsonl_limits.py +17 -0
- jsonl_utils.py +40 -0
- login_item.py +154 -0
- main.py +387 -0
- menubar.py +1201 -0
- menubar_actions.py +204 -0
- menubar_agy.py +193 -0
- menubar_chrome.py +156 -0
- menubar_menu.py +169 -0
- menubar_notify.py +102 -0
- menubar_popover.py +233 -0
- menubar_prefs.py +118 -0
- menubar_refresh.py +285 -0
- menubar_state.py +1200 -0
- menubar_title.py +157 -0
- menubar_update.py +123 -0
- panel_window.py +78 -0
- panel_window_state.py +159 -0
- panels/__init__.py +186 -0
- panels/base.py +83 -0
- panels/dynamic_height.py +140 -0
- panels/payload.py +178 -0
- panels/web_panel.py +513 -0
- panels/window_drag.py +56 -0
- prefs.py +44 -0
- pricing.py +452 -0
- project_resolver.py +112 -0
- service_status.py +383 -0
- session_hooks.py +1154 -0
- setup_app.py +171 -0
- setup_hook.py +1011 -0
- statusline_settings.py +160 -0
- talent_market_bridge.py +243 -0
- time_utils.py +24 -0
- tui.py +288 -0
- tui_sprite.py +206 -0
- ui/__init__.py +5 -0
- ui/html_report.py +923 -0
- ui/report_scripts.py +251 -0
- ui/report_styles.py +370 -0
- ui/tables.py +888 -0
- update_checker.py +156 -0
- update_gate.py +66 -0
- update_release_notes.py +49 -0
- usage_cli-0.29.32.data/data/share/usage/i18n.json +2427 -0
- usage_cli-0.29.32.dist-info/METADATA +223 -0
- usage_cli-0.29.32.dist-info/RECORD +109 -0
- usage_cli-0.29.32.dist-info/WHEEL +5 -0
- usage_cli-0.29.32.dist-info/entry_points.txt +3 -0
- usage_cli-0.29.32.dist-info/licenses/LICENSE +663 -0
- usage_cli-0.29.32.dist-info/top_level.txt +80 -0
- usage_cli.py +827 -0
- usage_client.py +487 -0
- usage_diagnosis_snapshot.py +143 -0
- usage_dir_sweeper.py +100 -0
- usage_lang.py +79 -0
- usage_logging.py +75 -0
- usage_notifications.py +96 -0
- usage_rate.py +97 -0
- usage_session_resume.py +913 -0
- usage_statusline.py +810 -0
- usage_statusline_agy.py +397 -0
- usage_statusline_forwarder.py +88 -0
- usage_terse_mode.py +223 -0
- usage_terse_reminder.py +151 -0
- win_login_item.py +53 -0
- window_keeper.py +264 -0
- windows_watch.py +443 -0
- wintray.py +2014 -0
- wintray_menu.py +136 -0
usage_session_resume.py
ADDED
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# SPDX-License-Identifier: AGPL-3.0-only
|
|
3
|
+
# Copyright (C) 2026 lollapalooza <https://github.com/aqua5230>
|
|
4
|
+
#
|
|
5
|
+
# Part of "usage". Free software licensed under the GNU Affero General Public
|
|
6
|
+
# License v3.0 only; see the LICENSE file for full terms and the warranty disclaimer.
|
|
7
|
+
|
|
8
|
+
"""usage SessionStart hook — inject "where you left off" into a new Claude Code session.
|
|
9
|
+
|
|
10
|
+
This is the session resume feature. Claude Code runs this on SessionStart (matcher
|
|
11
|
+
``startup|clear``) and pipes the session JSON on stdin; the script locates the project's
|
|
12
|
+
*previous* session log, gathers the *evidence* of that session — the most recent user
|
|
13
|
+
requests (newest first, so a session that drifted topics is still read correctly), the
|
|
14
|
+
commits made, the files edited, and any pending todos — and hands it to Claude via
|
|
15
|
+
``hookSpecificOutput.additionalContext`` with an instruction to *reason over* it rather
|
|
16
|
+
than transcribe it. The model that reads this is Claude itself, so the intelligence of
|
|
17
|
+
the handoff lives in Claude's reply, not in this script's string-formatting.
|
|
18
|
+
|
|
19
|
+
**Stdlib-only and 3.9-safe** — same constraint as ``usage_statusline.py``: it may run
|
|
20
|
+
under macOS's bundled ``/usr/bin/python3`` (3.9), so no third-party imports, no
|
|
21
|
+
``datetime.UTC``, no runtime ``X | Y`` types. The session-log parse is self-contained here
|
|
22
|
+
(no app imports), so the hook stays loadable under the bundled interpreter.
|
|
23
|
+
|
|
24
|
+
When there's no fresh progress to hand over (brand-new project, the previous session
|
|
25
|
+
did nothing extractable, or it's older than the cutoff) the hook still checks in with
|
|
26
|
+
a short greeting rather than going silent.
|
|
27
|
+
|
|
28
|
+
The prompt wording stays single-sourced: ``setup_hook`` writes ``report_rw_prompt`` /
|
|
29
|
+
``report_rw_none`` / ``report_rw_inject_lead`` / ``report_rw_empty`` from ``i18n.json`` to
|
|
30
|
+
a sidecar that this script reads. If the sidecar is missing it falls back to embedded
|
|
31
|
+
templates for the detected language. The script never raises into the session — any
|
|
32
|
+
failure exits 0 with no output.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import contextlib
|
|
38
|
+
import json
|
|
39
|
+
import os
|
|
40
|
+
import re
|
|
41
|
+
import subprocess
|
|
42
|
+
import sys
|
|
43
|
+
import tempfile
|
|
44
|
+
from collections.abc import Mapping
|
|
45
|
+
from datetime import datetime, timedelta, timezone
|
|
46
|
+
from pathlib import Path
|
|
47
|
+
from typing import Any, cast
|
|
48
|
+
|
|
49
|
+
__version__ = "1.6"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _configure_windows_utf8_output() -> None:
|
|
53
|
+
"""Make SessionStart JSON UTF-8 when Claude Code reads a Windows pipe."""
|
|
54
|
+
if os.name != "nt":
|
|
55
|
+
return
|
|
56
|
+
for stream in (sys.stdout, sys.stderr):
|
|
57
|
+
with contextlib.suppress(AttributeError, OSError, ValueError):
|
|
58
|
+
# Test runners and embedders may replace the TextIOWrapper streams.
|
|
59
|
+
cast(Any, stream).reconfigure(encoding="utf-8")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _read_stdin_utf8() -> str:
|
|
63
|
+
buffer = getattr(sys.stdin, "buffer", None)
|
|
64
|
+
if buffer is None:
|
|
65
|
+
return sys.stdin.read()
|
|
66
|
+
return cast(bytes, buffer.read()).decode("utf-8", "replace")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
PROMPT_SIDECAR = Path(os.path.expanduser("~/.claude/usage-resume-prompt.json"))
|
|
70
|
+
DIAGNOSIS_SNAPSHOT = Path(os.path.expanduser("~/.claude/usage-diagnosis.json"))
|
|
71
|
+
DIAGNOSIS_STATE = Path(os.path.expanduser("~/.claude/usage-diagnosis-state.json"))
|
|
72
|
+
|
|
73
|
+
# Only a heredoc that feeds git's commit message — `-F -` / `--file -` or `-m "$(cat`.
|
|
74
|
+
# Anchoring on these keeps an unrelated heredoc in the same command (e.g. a python
|
|
75
|
+
# `<<PYEOF` script whose first line is `import ...`) from being mistaken for a title.
|
|
76
|
+
_COMMIT_HEREDOC = re.compile(
|
|
77
|
+
r"""(?:-F\s*-?|--file[=\s]\s*-?|\$\(\s*cat)\s*<<-?\s*['"]?\w+['"]?\s*\n(.+?)\n""", re.S
|
|
78
|
+
)
|
|
79
|
+
_COMMIT_INLINE = re.compile(r"""-m\s+["']([^"'\n]{4,90})""")
|
|
80
|
+
_MAX_AGE_DAYS = 30
|
|
81
|
+
_MAX_COMMITS = 3
|
|
82
|
+
_MAX_TODOS = 5
|
|
83
|
+
_MAX_FILES = 5
|
|
84
|
+
_MAX_UNCOMMITTED_FILES = 3
|
|
85
|
+
_MAX_REQUESTS = 3
|
|
86
|
+
_MAX_REQUEST_CHARS = 280
|
|
87
|
+
_MIN_SUBSTANTIVE_CHARS = 7
|
|
88
|
+
_IMAGE_MARKER = re.compile(r"\[Image(?:\s+#[0-9]+)?\]", re.I)
|
|
89
|
+
_DIAGNOSIS_MAX_AGE = timedelta(hours=48)
|
|
90
|
+
_DIAGNOSIS_REMINDER_COOLDOWN = timedelta(days=7)
|
|
91
|
+
_DIAGNOSIS_CAUSE_KEYS = (
|
|
92
|
+
"repeated_reads",
|
|
93
|
+
"polluter_dirs",
|
|
94
|
+
"anomaly_session",
|
|
95
|
+
"noisy_bash",
|
|
96
|
+
"repeated_bash",
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
_DEFAULT_PROMPT = (
|
|
100
|
+
"Project: {project} (last active {when})\n"
|
|
101
|
+
"Recently working on (newest first): {last_request}\n"
|
|
102
|
+
"Progress made: {commits}\n"
|
|
103
|
+
"Open to-dos: {todos}"
|
|
104
|
+
)
|
|
105
|
+
_DEFAULT_NONE = "(none recorded)"
|
|
106
|
+
_DEFAULT_EMPTY = (
|
|
107
|
+
"(At the very start of your first reply in this session, say one line: "
|
|
108
|
+
'"🐾 Welcome back — nothing to pick up on this project yet.", '
|
|
109
|
+
"then respond normally.)"
|
|
110
|
+
)
|
|
111
|
+
_DEFAULT_TEMPLATES: dict[str, dict[str, Any]] = {
|
|
112
|
+
"en": {
|
|
113
|
+
"prompt": _DEFAULT_PROMPT,
|
|
114
|
+
"none": _DEFAULT_NONE,
|
|
115
|
+
"lead": (
|
|
116
|
+
"(This is a resume handoff. At the very start of your first reply, lead "
|
|
117
|
+
'with one line: "🐾 Picked up where you left off — let\'s keep going!", '
|
|
118
|
+
"then, instead of reading the traces below aloud, digest them like a sharp, "
|
|
119
|
+
"thoughtful partner: first work out what the user was actually in the middle of "
|
|
120
|
+
'("Recently working on" is newest-first, so trust the topmost item and don\'t get '
|
|
121
|
+
"pulled back to older ones); in a sentence or two, warmly and concretely recap "
|
|
122
|
+
"where they left off and what got done; then give the single concrete next step "
|
|
123
|
+
'you would take — be specific, don\'t ask "what should I do". Use only what is '
|
|
124
|
+
"below; invent nothing. If the traces are too thin to tell, say so plainly and "
|
|
125
|
+
"list the threads you can see for them to pick. Then respond normally.)\n\n"
|
|
126
|
+
),
|
|
127
|
+
"empty": _DEFAULT_EMPTY,
|
|
128
|
+
"uncommitted": (
|
|
129
|
+
"Left uncommitted last time: {count} changed file(s) on branch {branch} ({files})"
|
|
130
|
+
),
|
|
131
|
+
"diagnosis_reminder": (
|
|
132
|
+
'Health check: about {waste_pct}% waste from {cause}. Say "fix it" '
|
|
133
|
+
"and I'll read the full diagnosis at {path}."
|
|
134
|
+
),
|
|
135
|
+
"diagnosis_reminder_explain": (
|
|
136
|
+
'Health check: about {waste_pct}% waste from {cause}. Say "show me" '
|
|
137
|
+
"and I'll walk you through the full diagnosis at {path}."
|
|
138
|
+
),
|
|
139
|
+
"diagnosis_default_cause": "avoidable context waste",
|
|
140
|
+
"diagnosis_causes": {
|
|
141
|
+
"repeated_reads": "re-reading the same files",
|
|
142
|
+
"polluter_dirs": "scanning generated folders",
|
|
143
|
+
"anomaly_session": "one oversized session",
|
|
144
|
+
"noisy_bash": "oversized Bash output",
|
|
145
|
+
"repeated_bash": "re-running the same Bash command",
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
"zh-TW": {
|
|
149
|
+
"prompt": (
|
|
150
|
+
"專案:{project}(最後活動 {when})\n"
|
|
151
|
+
"最近在忙的(新→舊):{last_request}\n"
|
|
152
|
+
"完成的進度:{commits}\n"
|
|
153
|
+
"未完成待辦:{todos}"
|
|
154
|
+
),
|
|
155
|
+
"none": "(未記錄)",
|
|
156
|
+
"lead": (
|
|
157
|
+
"(這是進度交接。請在這次對話第一則回覆的最前面,先說一行"
|
|
158
|
+
"「🐾 已接回上次進度,繼續吧!」,然後別照唸下面的線索,"
|
|
159
|
+
"而是像聰明又貼心的搭檔那樣消化它:先判斷使用者最後真正在忙的是什麼"
|
|
160
|
+
"(「最近在忙的」是新到舊排列,以最前面那筆為準,別被較舊的帶偏),"
|
|
161
|
+
"用一兩句溫暖具體地說他上次做到哪、完成了什麼,再直接給出你判斷最該"
|
|
162
|
+
"接著做的下一步——要具體,別反問「要做什麼」。只能根據下面線索講,"
|
|
163
|
+
"沒有的別編;若線索太少看不出方向,就坦白說、並列出你看到的幾條線讓他挑。"
|
|
164
|
+
"接著正常回應。)\n\n"
|
|
165
|
+
),
|
|
166
|
+
"empty": (
|
|
167
|
+
"(請在你這次對話的第一則回覆最前面,說一行「🐾 歡迎回來,"
|
|
168
|
+
"這個專案目前沒有要接的進度。」,再正常回應。)"
|
|
169
|
+
),
|
|
170
|
+
"uncommitted": (
|
|
171
|
+
"上次離開時還留著:{branch} 分支有 {count} 個檔案改了還沒提交({files})"
|
|
172
|
+
),
|
|
173
|
+
},
|
|
174
|
+
"zh-CN": {
|
|
175
|
+
"prompt": (
|
|
176
|
+
"项目:{project}(最后活动 {when})\n"
|
|
177
|
+
"最近在忙的(新→旧):{last_request}\n"
|
|
178
|
+
"完成的进度:{commits}\n"
|
|
179
|
+
"未完成待办:{todos}"
|
|
180
|
+
),
|
|
181
|
+
"none": "(未记录)",
|
|
182
|
+
"lead": (
|
|
183
|
+
"(这是进度交接。请在这次对话第一则回复的最前面,先说一行"
|
|
184
|
+
"「🐾 已接回上次进度,继续吧!」,然后别照念下面的线索,"
|
|
185
|
+
"而是像聪明又贴心的搭档那样消化它:先判断用户最后真正在忙的是什么"
|
|
186
|
+
"(「最近在忙的」是新到旧排列,以最前面那笔为准,别被较旧的带偏),"
|
|
187
|
+
"用一两句温暖具体地说他上次做到哪、完成了什么,再直接给出你判断最该"
|
|
188
|
+
"接着做的下一步——要具体,别反问「要做什么」。只能根据下面线索讲,"
|
|
189
|
+
"没有的别编;若线索太少看不出方向,就坦白说、并列出你看到的几条线让他挑。"
|
|
190
|
+
"接着正常回应。)\n\n"
|
|
191
|
+
),
|
|
192
|
+
"empty": (
|
|
193
|
+
"(请在你这次对话的第一则回复最前面,说一行「🐾 欢迎回来,"
|
|
194
|
+
"这个项目目前没有要接的进度。」,再正常回应。)"
|
|
195
|
+
),
|
|
196
|
+
"uncommitted": (
|
|
197
|
+
"上次离开时还留着:{branch} 分支有 {count} 个文件改了还没提交({files})"
|
|
198
|
+
),
|
|
199
|
+
},
|
|
200
|
+
"ja": {
|
|
201
|
+
"prompt": (
|
|
202
|
+
"プロジェクト:{project}(最終アクティブ {when})\n"
|
|
203
|
+
"最近の作業(新しい順):{last_request}\n"
|
|
204
|
+
"完了した進捗:{commits}\n"
|
|
205
|
+
"未完了のToDo:{todos}"
|
|
206
|
+
),
|
|
207
|
+
"none": "(記録なし)",
|
|
208
|
+
"lead": (
|
|
209
|
+
"(これは進捗の引き継ぎです。最初の返信の冒頭で、まず一行"
|
|
210
|
+
"「🐾 前回の続き、引き継ぎ済みです!そのままどうぞ!」と述べ、"
|
|
211
|
+
"下記の手がかりをそのまま読み上げるのではなく、賢く気の利いた相棒のように"
|
|
212
|
+
"消化してください:まずユーザーが最後に実際に取り組んでいたことを見極め"
|
|
213
|
+
"(「最近の作業」は新しい順なので、先頭の項目を信頼し、古いものに引きずられない"
|
|
214
|
+
"こと)、前回どこまで進んだか・何が完了したかを一、二文で温かく具体的に振り返り、"
|
|
215
|
+
"次に取るべき具体的な一歩を提示してください——具体的に述べ、「何をしますか」と"
|
|
216
|
+
"聞き返さないこと。下記にある情報だけを使い、無いことは創作しないこと。手がかりが"
|
|
217
|
+
"乏しくて判断できない場合は正直にそう述べ、見えるスレッドを挙げて選んでもらうこと。"
|
|
218
|
+
"その後、通常どおり応答してください。)\n\n"
|
|
219
|
+
),
|
|
220
|
+
"empty": (
|
|
221
|
+
"(このセッションの最初の返信の冒頭に、一行「🐾 おかえりなさい!"
|
|
222
|
+
"このプロジェクトはまだこれからですね。」と述べてから、通常どおり応答してください。)"
|
|
223
|
+
),
|
|
224
|
+
"uncommitted": (
|
|
225
|
+
"前回の終了時に未コミット:{branch} ブランチに変更済み未コミットのファイルが "
|
|
226
|
+
"{count} 件({files})"
|
|
227
|
+
),
|
|
228
|
+
},
|
|
229
|
+
"ko": {
|
|
230
|
+
"prompt": (
|
|
231
|
+
"프로젝트: {project} (마지막 활동 {when})\n"
|
|
232
|
+
"최근 작업한 내용 (최신순): {last_request}\n"
|
|
233
|
+
"완료한 진행: {commits}\n"
|
|
234
|
+
"미완료 할 일: {todos}"
|
|
235
|
+
),
|
|
236
|
+
"none": "(기록 없음)",
|
|
237
|
+
"lead": (
|
|
238
|
+
"(이것은 진행 상황 인수인계입니다. 첫 답변 맨 앞에 먼저 한 줄 "
|
|
239
|
+
'"🐾 지난 작업을 불러왔어요! 이어서 가볼까요?"라고 '
|
|
240
|
+
"말한 뒤, 아래 단서를 그대로 읽지 말고 똑똑하고 사려 깊은 동료처럼 소화하세요: "
|
|
241
|
+
"먼저 사용자가 마지막에 실제로 무엇을 하고 있었는지 파악하고(\"최근 작업한 내용\"은 "
|
|
242
|
+
"최신순이므로 맨 위 항목을 신뢰하고 오래된 것에 끌려가지 마세요), 지난번에 어디까지 "
|
|
243
|
+
"했고 무엇을 완료했는지 한두 문장으로 따뜻하고 구체적으로 짚어 준 뒤, 이어서 취해야 "
|
|
244
|
+
'할 구체적인 다음 단계 하나를 제시하세요 — 구체적으로 말하고 "무엇을 할까요"라고 '
|
|
245
|
+
"되묻지 마세요. 아래 있는 내용만 사용하고 없는 것은 지어내지 마세요. 단서가 너무 "
|
|
246
|
+
"적어 판단하기 어려우면 솔직히 그렇게 말하고 보이는 갈래들을 나열해 고르게 하세요. "
|
|
247
|
+
"그런 다음 평소대로 응답하세요.)\n\n"
|
|
248
|
+
),
|
|
249
|
+
"empty": (
|
|
250
|
+
'(이 세션의 첫 답변 맨 앞에 한 줄 "🐾 돌아오셨네요! '
|
|
251
|
+
'이 프로젝트는 아직 이어갈 내용이 없어요."라고 말한 뒤 평소대로 응답하세요.)'
|
|
252
|
+
),
|
|
253
|
+
"uncommitted": (
|
|
254
|
+
"지난번 종료 시 미커밋: {branch} 브랜치에 변경된 미커밋 파일 {count}개 ({files})"
|
|
255
|
+
),
|
|
256
|
+
},
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def main() -> int:
|
|
261
|
+
_configure_windows_utf8_output()
|
|
262
|
+
try:
|
|
263
|
+
payload = json.loads(_read_stdin_utf8() or "{}")
|
|
264
|
+
except (json.JSONDecodeError, ValueError):
|
|
265
|
+
return 0
|
|
266
|
+
if not isinstance(payload, dict):
|
|
267
|
+
return 0
|
|
268
|
+
try:
|
|
269
|
+
prompt = _build_prompt(payload)
|
|
270
|
+
except Exception:
|
|
271
|
+
return 0
|
|
272
|
+
if not prompt:
|
|
273
|
+
return 0
|
|
274
|
+
output = {
|
|
275
|
+
"hookSpecificOutput": {
|
|
276
|
+
"hookEventName": "SessionStart",
|
|
277
|
+
"additionalContext": prompt,
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
print(json.dumps(output, ensure_ascii=False))
|
|
281
|
+
return 0
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _build_prompt(payload: dict[str, Any]) -> str:
|
|
285
|
+
transcript = payload.get("transcript_path")
|
|
286
|
+
cwd = payload.get("cwd")
|
|
287
|
+
if not isinstance(transcript, str) or not transcript:
|
|
288
|
+
return ""
|
|
289
|
+
project_dir = Path(transcript).parent
|
|
290
|
+
if not project_dir.is_dir():
|
|
291
|
+
return ""
|
|
292
|
+
|
|
293
|
+
(
|
|
294
|
+
lead,
|
|
295
|
+
template,
|
|
296
|
+
none_label,
|
|
297
|
+
empty,
|
|
298
|
+
uncommitted_template,
|
|
299
|
+
diagnosis_reminder,
|
|
300
|
+
diagnosis_reminder_explain,
|
|
301
|
+
diagnosis_default_cause,
|
|
302
|
+
diagnosis_causes,
|
|
303
|
+
) = _load_template(_detect_lang())
|
|
304
|
+
project = _project_from_cwd(cwd) if isinstance(cwd, str) and cwd else project_dir.name
|
|
305
|
+
uncommitted = _git_dirty(cwd) if isinstance(cwd, str) and cwd else None
|
|
306
|
+
report = _build_report(
|
|
307
|
+
project_dir,
|
|
308
|
+
Path(transcript).name,
|
|
309
|
+
project,
|
|
310
|
+
lead,
|
|
311
|
+
template,
|
|
312
|
+
none_label,
|
|
313
|
+
uncommitted_template,
|
|
314
|
+
uncommitted,
|
|
315
|
+
)
|
|
316
|
+
# The resume hook always checks in: when there's no fresh progress to hand over, it
|
|
317
|
+
# greets instead of going silent.
|
|
318
|
+
prompt = report or empty
|
|
319
|
+
diagnosis_instruction = _build_diagnosis_instruction(
|
|
320
|
+
diagnosis_reminder=diagnosis_reminder,
|
|
321
|
+
diagnosis_reminder_explain=diagnosis_reminder_explain,
|
|
322
|
+
diagnosis_default_cause=diagnosis_default_cause,
|
|
323
|
+
diagnosis_causes=diagnosis_causes,
|
|
324
|
+
)
|
|
325
|
+
if diagnosis_instruction:
|
|
326
|
+
prompt += "\n\n" + diagnosis_instruction
|
|
327
|
+
return prompt
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _build_report(
|
|
331
|
+
project_dir: Path,
|
|
332
|
+
current_name: str,
|
|
333
|
+
project: str,
|
|
334
|
+
lead: str,
|
|
335
|
+
template: str,
|
|
336
|
+
none_label: str,
|
|
337
|
+
uncommitted_template: str,
|
|
338
|
+
uncommitted: tuple[str, int, list[str]] | None,
|
|
339
|
+
) -> str:
|
|
340
|
+
"""The "I loaded your last progress" prompt, or "" when there's nothing fresh to report."""
|
|
341
|
+
parsed = None
|
|
342
|
+
for candidate in _other_jsonls_by_mtime(project_dir, exclude=current_name):
|
|
343
|
+
parsed = _parse_session(candidate)
|
|
344
|
+
if parsed is not None:
|
|
345
|
+
break
|
|
346
|
+
if parsed is None:
|
|
347
|
+
return ""
|
|
348
|
+
last_active, last_request, commits, todos, edited_files = parsed
|
|
349
|
+
if last_active < _cutoff():
|
|
350
|
+
return ""
|
|
351
|
+
request_text = last_request or none_label
|
|
352
|
+
done_items = commits[:_MAX_COMMITS] or edited_files[:_MAX_FILES]
|
|
353
|
+
commits_text = " · ".join(done_items) or none_label
|
|
354
|
+
todos_text = " · ".join(todos[:_MAX_TODOS]) or none_label
|
|
355
|
+
report = lead + template.format(
|
|
356
|
+
project=project,
|
|
357
|
+
when=_format_time(last_active),
|
|
358
|
+
last_request=request_text,
|
|
359
|
+
commits=commits_text,
|
|
360
|
+
todos=todos_text,
|
|
361
|
+
)
|
|
362
|
+
if uncommitted is not None:
|
|
363
|
+
branch, count, files = uncommitted
|
|
364
|
+
report += "\n" + uncommitted_template.format(
|
|
365
|
+
branch=branch,
|
|
366
|
+
count=count,
|
|
367
|
+
files=", ".join(files),
|
|
368
|
+
)
|
|
369
|
+
return report
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _git_dirty(cwd: str) -> tuple[str, int, list[str]] | None:
|
|
373
|
+
try:
|
|
374
|
+
branch_proc = subprocess.run(
|
|
375
|
+
["git", "-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"],
|
|
376
|
+
stdout=subprocess.PIPE,
|
|
377
|
+
stderr=subprocess.DEVNULL,
|
|
378
|
+
timeout=2,
|
|
379
|
+
encoding="utf-8",
|
|
380
|
+
check=False,
|
|
381
|
+
)
|
|
382
|
+
if branch_proc.returncode != 0:
|
|
383
|
+
return None
|
|
384
|
+
branch = branch_proc.stdout.strip()
|
|
385
|
+
if not branch:
|
|
386
|
+
return None
|
|
387
|
+
status_proc = subprocess.run(
|
|
388
|
+
["git", "-C", cwd, "status", "--porcelain"],
|
|
389
|
+
stdout=subprocess.PIPE,
|
|
390
|
+
stderr=subprocess.DEVNULL,
|
|
391
|
+
timeout=2,
|
|
392
|
+
encoding="utf-8",
|
|
393
|
+
check=False,
|
|
394
|
+
)
|
|
395
|
+
if status_proc.returncode != 0:
|
|
396
|
+
return None
|
|
397
|
+
changed = [line for line in status_proc.stdout.splitlines() if line.strip()]
|
|
398
|
+
if not changed:
|
|
399
|
+
return None
|
|
400
|
+
files: list[str] = []
|
|
401
|
+
for line in changed:
|
|
402
|
+
path = line[3:].strip() if len(line) > 3 else line.strip()
|
|
403
|
+
if " -> " in path:
|
|
404
|
+
path = path.rsplit(" -> ", 1)[1]
|
|
405
|
+
base = os.path.basename(path.strip('"'))
|
|
406
|
+
if base and base not in files:
|
|
407
|
+
files.append(base)
|
|
408
|
+
if len(files) >= _MAX_UNCOMMITTED_FILES:
|
|
409
|
+
break
|
|
410
|
+
return branch, len(changed), files
|
|
411
|
+
except Exception:
|
|
412
|
+
return None
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _cutoff() -> datetime:
|
|
416
|
+
return datetime.now().astimezone() - timedelta(days=_MAX_AGE_DAYS)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _other_jsonls_by_mtime(project_dir: Path, exclude: str) -> list[Path]:
|
|
420
|
+
"""Other session logs in the project, newest first.
|
|
421
|
+
|
|
422
|
+
Newest-first so the caller can skip a freshly-written but empty/corrupt log and
|
|
423
|
+
still fall back to the previous session that actually has progress to report.
|
|
424
|
+
"""
|
|
425
|
+
candidates: list[tuple[float, Path]] = []
|
|
426
|
+
for jsonl in project_dir.glob("*.jsonl"):
|
|
427
|
+
if jsonl.name == exclude:
|
|
428
|
+
continue
|
|
429
|
+
try:
|
|
430
|
+
mtime = jsonl.stat().st_mtime
|
|
431
|
+
except OSError:
|
|
432
|
+
continue
|
|
433
|
+
candidates.append((mtime, jsonl))
|
|
434
|
+
candidates.sort(key=lambda item: item[0], reverse=True)
|
|
435
|
+
return [path for _, path in candidates]
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _parse_session(path: Path) -> tuple[datetime, str, list[str], list[str], list[str]] | None:
|
|
439
|
+
"""Return (last_active, recent_requests, commits, todos, edited_files) for the previous session.
|
|
440
|
+
|
|
441
|
+
``recent_requests`` is the last few substantive user requests joined newest-first: a
|
|
442
|
+
session often drifts (you start on task A and end deep in task B), so what you were
|
|
443
|
+
*last* working on — not the opening request — is where you want to resume. Trailing
|
|
444
|
+
reactions, screenshot markers, and interruption notes are filtered out by
|
|
445
|
+
``_clean_request``, so "most recent" stays meaningful. ``todos`` are the pending items
|
|
446
|
+
from the latest TodoWrite, if the session used one. ``edited_files`` are the basenames
|
|
447
|
+
of files touched by Edit / Write / NotebookEdit, deduplicated and in first-seen order.
|
|
448
|
+
"""
|
|
449
|
+
requests: list[str] = []
|
|
450
|
+
seen_requests: set[str] = set()
|
|
451
|
+
commits: list[str] = []
|
|
452
|
+
todos: list[str] = []
|
|
453
|
+
edited_files: list[str] = []
|
|
454
|
+
last_ts: datetime | None = None
|
|
455
|
+
|
|
456
|
+
try:
|
|
457
|
+
with path.open(encoding="utf-8") as file:
|
|
458
|
+
for raw_line in file:
|
|
459
|
+
line = raw_line.strip()
|
|
460
|
+
if not line:
|
|
461
|
+
continue
|
|
462
|
+
try:
|
|
463
|
+
data = json.loads(line)
|
|
464
|
+
except json.JSONDecodeError:
|
|
465
|
+
continue
|
|
466
|
+
if not isinstance(data, dict):
|
|
467
|
+
continue
|
|
468
|
+
|
|
469
|
+
timestamp = _parse_timestamp(data.get("timestamp"))
|
|
470
|
+
if timestamp is not None and (last_ts is None or timestamp > last_ts):
|
|
471
|
+
last_ts = timestamp
|
|
472
|
+
|
|
473
|
+
if data.get("isMeta") is True:
|
|
474
|
+
continue
|
|
475
|
+
|
|
476
|
+
entry_type = data.get("type")
|
|
477
|
+
if entry_type == "last-prompt":
|
|
478
|
+
text = _clean_request(data.get("lastPrompt"))
|
|
479
|
+
if text and text not in seen_requests:
|
|
480
|
+
requests.append(text)
|
|
481
|
+
seen_requests.add(text)
|
|
482
|
+
continue
|
|
483
|
+
if entry_type == "user":
|
|
484
|
+
text = _user_request_text(data.get("message"))
|
|
485
|
+
if text and text not in seen_requests:
|
|
486
|
+
requests.append(text)
|
|
487
|
+
seen_requests.add(text)
|
|
488
|
+
continue
|
|
489
|
+
if entry_type != "assistant":
|
|
490
|
+
continue
|
|
491
|
+
message = data.get("message")
|
|
492
|
+
if not isinstance(message, dict):
|
|
493
|
+
continue
|
|
494
|
+
content = message.get("content")
|
|
495
|
+
if not isinstance(content, list):
|
|
496
|
+
continue
|
|
497
|
+
_collect_tools(content, commits, todos, edited_files)
|
|
498
|
+
except OSError:
|
|
499
|
+
return None
|
|
500
|
+
|
|
501
|
+
if last_ts is None or not (requests or commits or todos or edited_files):
|
|
502
|
+
return None
|
|
503
|
+
# Newest-first, capped: the most recent request leads so Claude resumes the latest
|
|
504
|
+
# thread, with a little prior context to spot a topic drift.
|
|
505
|
+
last_request = " · ".join(reversed(requests[-_MAX_REQUESTS:]))
|
|
506
|
+
return last_ts, last_request, commits, todos, edited_files
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _user_request_text(message: object) -> str:
|
|
510
|
+
if not isinstance(message, dict):
|
|
511
|
+
return ""
|
|
512
|
+
content = message.get("content")
|
|
513
|
+
if isinstance(content, str):
|
|
514
|
+
return _clean_request(content)
|
|
515
|
+
if isinstance(content, list):
|
|
516
|
+
parts = [
|
|
517
|
+
part.get("text")
|
|
518
|
+
for part in content
|
|
519
|
+
if isinstance(part, dict) and part.get("type") == "text"
|
|
520
|
+
]
|
|
521
|
+
return _clean_request(" ".join(p for p in parts if isinstance(p, str) and p.strip()))
|
|
522
|
+
return ""
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _clean_request(value: object) -> str:
|
|
526
|
+
if not isinstance(value, str):
|
|
527
|
+
return ""
|
|
528
|
+
text = " ".join(value.split())
|
|
529
|
+
# Skip the interruption marker Claude Code writes as a user turn — it is noise,
|
|
530
|
+
# not a request.
|
|
531
|
+
if not text or text.startswith("[Request interrupted"):
|
|
532
|
+
return ""
|
|
533
|
+
starts_with_image = text.startswith("[Image")
|
|
534
|
+
text = _IMAGE_MARKER.sub("", text).strip()
|
|
535
|
+
if not text:
|
|
536
|
+
return ""
|
|
537
|
+
substantive_len = _substantive_len(text)
|
|
538
|
+
if substantive_len == 0:
|
|
539
|
+
return ""
|
|
540
|
+
if starts_with_image and substantive_len < _MIN_SUBSTANTIVE_CHARS:
|
|
541
|
+
return ""
|
|
542
|
+
if substantive_len < _MIN_SUBSTANTIVE_CHARS and not _has_structural_signal(text):
|
|
543
|
+
return ""
|
|
544
|
+
if len(text) > _MAX_REQUEST_CHARS:
|
|
545
|
+
text = text[: _MAX_REQUEST_CHARS - 1].rstrip() + "…"
|
|
546
|
+
return text
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def _substantive_len(text: str) -> int:
|
|
550
|
+
return sum(1 for char in text if char.isalnum())
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _has_structural_signal(text: str) -> bool:
|
|
554
|
+
return any(marker in text for marker in ("/", "\\", ".", "_", "-", "#", ":", "`", "(", ")"))
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _pending_todos(items: list[Any]) -> list[str]:
|
|
558
|
+
result: list[str] = []
|
|
559
|
+
for item in items:
|
|
560
|
+
if not isinstance(item, dict):
|
|
561
|
+
continue
|
|
562
|
+
if item.get("status") not in ("pending", "in_progress"):
|
|
563
|
+
continue
|
|
564
|
+
text = item.get("content")
|
|
565
|
+
if isinstance(text, str) and text.strip():
|
|
566
|
+
result.append(_clean_request(text))
|
|
567
|
+
return [t for t in result if t]
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _collect_tools(
|
|
571
|
+
content: list[Any],
|
|
572
|
+
commits: list[str],
|
|
573
|
+
todos: list[str],
|
|
574
|
+
edited_files: list[str],
|
|
575
|
+
) -> None:
|
|
576
|
+
for part in content:
|
|
577
|
+
if not isinstance(part, dict) or part.get("type") != "tool_use":
|
|
578
|
+
continue
|
|
579
|
+
name = part.get("name")
|
|
580
|
+
raw_input = part.get("input")
|
|
581
|
+
if not isinstance(raw_input, dict):
|
|
582
|
+
continue
|
|
583
|
+
if name == "TodoWrite":
|
|
584
|
+
items = raw_input.get("todos")
|
|
585
|
+
if isinstance(items, list):
|
|
586
|
+
pending = _pending_todos(items)
|
|
587
|
+
if pending:
|
|
588
|
+
todos[:] = pending # latest TodoWrite wins — it is the current state
|
|
589
|
+
elif name == "Bash":
|
|
590
|
+
command = raw_input.get("command")
|
|
591
|
+
if isinstance(command, str) and "git commit" in command:
|
|
592
|
+
title = _extract_commit_title(command)
|
|
593
|
+
if title and title not in commits:
|
|
594
|
+
commits.append(title)
|
|
595
|
+
elif name in {"Edit", "Write", "NotebookEdit"}:
|
|
596
|
+
fp = raw_input.get("file_path")
|
|
597
|
+
if isinstance(fp, str):
|
|
598
|
+
base = os.path.basename(fp)
|
|
599
|
+
if base and base not in edited_files:
|
|
600
|
+
edited_files.append(base)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def _extract_commit_title(command: str) -> str:
|
|
604
|
+
heredoc = _COMMIT_HEREDOC.search(command)
|
|
605
|
+
if heredoc:
|
|
606
|
+
return heredoc.group(1).strip()
|
|
607
|
+
inline = _COMMIT_INLINE.search(command)
|
|
608
|
+
if inline:
|
|
609
|
+
return inline.group(1).strip()
|
|
610
|
+
return ""
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def _parse_timestamp(value: object) -> datetime | None:
|
|
614
|
+
if not isinstance(value, str):
|
|
615
|
+
return None
|
|
616
|
+
try:
|
|
617
|
+
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
618
|
+
except ValueError:
|
|
619
|
+
return None
|
|
620
|
+
# A naive timestamp (no offset) can't be compared against the aware _cutoff();
|
|
621
|
+
# assume local time so the comparison stays type-safe.
|
|
622
|
+
return parsed if parsed.tzinfo is not None else parsed.astimezone()
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _build_diagnosis_instruction(
|
|
626
|
+
*,
|
|
627
|
+
diagnosis_reminder: str,
|
|
628
|
+
diagnosis_reminder_explain: str,
|
|
629
|
+
diagnosis_default_cause: str,
|
|
630
|
+
diagnosis_causes: Mapping[str, str],
|
|
631
|
+
) -> str:
|
|
632
|
+
snapshot = _read_json_file(DIAGNOSIS_SNAPSHOT)
|
|
633
|
+
if not isinstance(snapshot, dict):
|
|
634
|
+
return ""
|
|
635
|
+
|
|
636
|
+
now = datetime.now(timezone.utc)
|
|
637
|
+
generated_at = _parse_timestamp(snapshot.get("generated_at"))
|
|
638
|
+
if generated_at is None:
|
|
639
|
+
return ""
|
|
640
|
+
if now - generated_at.astimezone(timezone.utc) > _DIAGNOSIS_MAX_AGE:
|
|
641
|
+
return ""
|
|
642
|
+
if snapshot.get("has_data") is not True:
|
|
643
|
+
return ""
|
|
644
|
+
|
|
645
|
+
raw_findings = snapshot.get("findings")
|
|
646
|
+
findings = raw_findings if isinstance(raw_findings, list) else []
|
|
647
|
+
waste_pct = _coerce_float(snapshot.get("waste_pct"))
|
|
648
|
+
has_critical = any(
|
|
649
|
+
isinstance(finding, dict) and finding.get("severity") == "critical"
|
|
650
|
+
for finding in findings
|
|
651
|
+
)
|
|
652
|
+
if waste_pct < 5.0 and not has_critical:
|
|
653
|
+
return ""
|
|
654
|
+
|
|
655
|
+
fingerprint = _diagnosis_fingerprint(snapshot)
|
|
656
|
+
if not fingerprint:
|
|
657
|
+
return ""
|
|
658
|
+
if _diagnosis_cooldown_active(fingerprint, now):
|
|
659
|
+
return ""
|
|
660
|
+
|
|
661
|
+
primary = _pick_primary_finding(findings)
|
|
662
|
+
kind = primary.get("kind") if isinstance(primary, dict) else None
|
|
663
|
+
cause = diagnosis_causes.get(str(kind), diagnosis_default_cause)
|
|
664
|
+
# When nothing is auto-fixable, don't promise a fix: invite a walkthrough instead.
|
|
665
|
+
fixable_tokens = _coerce_float(snapshot.get("fixable_waste_tokens"))
|
|
666
|
+
template = diagnosis_reminder if fixable_tokens > 0 else diagnosis_reminder_explain
|
|
667
|
+
reminder_line = template.format(
|
|
668
|
+
waste_pct=_format_percent_number(waste_pct),
|
|
669
|
+
cause=cause,
|
|
670
|
+
path=str(DIAGNOSIS_SNAPSHOT),
|
|
671
|
+
)
|
|
672
|
+
_write_diagnosis_state(
|
|
673
|
+
{
|
|
674
|
+
"last_fingerprint": fingerprint,
|
|
675
|
+
"last_reminded_at": _format_utc_timestamp(now),
|
|
676
|
+
}
|
|
677
|
+
)
|
|
678
|
+
return (
|
|
679
|
+
"(At the end of your first reply in this session, add exactly one line: "
|
|
680
|
+
+ json.dumps(reminder_line, ensure_ascii=False)
|
|
681
|
+
+ ")"
|
|
682
|
+
)
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def _read_json_file(path: Path) -> dict[str, Any] | None:
|
|
686
|
+
try:
|
|
687
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
688
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
689
|
+
return None
|
|
690
|
+
return data if isinstance(data, dict) else None
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def _coerce_float(value: object) -> float:
|
|
694
|
+
if isinstance(value, (int, float)):
|
|
695
|
+
return float(value)
|
|
696
|
+
return 0.0
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _pick_primary_finding(findings: object) -> dict[str, Any]:
|
|
700
|
+
if not isinstance(findings, list):
|
|
701
|
+
return {}
|
|
702
|
+
|
|
703
|
+
candidates = [finding for finding in findings if isinstance(finding, dict)]
|
|
704
|
+
if not candidates:
|
|
705
|
+
return {}
|
|
706
|
+
candidates.sort(
|
|
707
|
+
key=lambda finding: (
|
|
708
|
+
-int(finding.get("estimated_waste_tokens") or 0),
|
|
709
|
+
0 if finding.get("severity") == "critical" else 1,
|
|
710
|
+
str(finding.get("kind") or ""),
|
|
711
|
+
)
|
|
712
|
+
)
|
|
713
|
+
return candidates[0]
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _diagnosis_fingerprint(snapshot: Mapping[str, object]) -> str:
|
|
717
|
+
value = snapshot.get("findings_fingerprint")
|
|
718
|
+
if isinstance(value, str) and value:
|
|
719
|
+
return value
|
|
720
|
+
return ""
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def _diagnosis_cooldown_active(fingerprint: str, now: datetime) -> bool:
|
|
724
|
+
state = _read_json_file(DIAGNOSIS_STATE)
|
|
725
|
+
if not isinstance(state, dict):
|
|
726
|
+
return False
|
|
727
|
+
previous = state.get("last_fingerprint")
|
|
728
|
+
reminded_at = _parse_timestamp(state.get("last_reminded_at"))
|
|
729
|
+
if previous != fingerprint:
|
|
730
|
+
return False
|
|
731
|
+
if reminded_at is None:
|
|
732
|
+
return False
|
|
733
|
+
return now - reminded_at.astimezone(timezone.utc) < _DIAGNOSIS_REMINDER_COOLDOWN
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _write_diagnosis_state(data: Mapping[str, object]) -> None:
|
|
737
|
+
DIAGNOSIS_STATE.parent.mkdir(parents=True, exist_ok=True)
|
|
738
|
+
tmp_path = None
|
|
739
|
+
try:
|
|
740
|
+
fd, tmp_path = tempfile.mkstemp(dir=str(DIAGNOSIS_STATE.parent), suffix=".tmp")
|
|
741
|
+
with os.fdopen(fd, "w", encoding="utf-8") as file:
|
|
742
|
+
json.dump(data, file, ensure_ascii=False, indent=2)
|
|
743
|
+
file.write("\n")
|
|
744
|
+
os.replace(tmp_path, DIAGNOSIS_STATE)
|
|
745
|
+
tmp_path = None
|
|
746
|
+
finally:
|
|
747
|
+
if tmp_path and os.path.exists(tmp_path):
|
|
748
|
+
with contextlib.suppress(OSError):
|
|
749
|
+
os.unlink(tmp_path)
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def _format_utc_timestamp(value: datetime) -> str:
|
|
753
|
+
return value.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def _format_percent_number(value: float) -> str:
|
|
757
|
+
rounded = round(value, 1)
|
|
758
|
+
if rounded.is_integer():
|
|
759
|
+
return str(int(rounded))
|
|
760
|
+
return str(rounded)
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def _format_time(parsed: datetime) -> str:
|
|
764
|
+
if parsed.tzinfo is not None:
|
|
765
|
+
parsed = parsed.astimezone()
|
|
766
|
+
return f"{parsed.month}/{parsed.day} {parsed.hour:02d}:{parsed.minute:02d}"
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def _project_from_cwd(cwd: str) -> str:
|
|
770
|
+
home = os.path.expanduser("~")
|
|
771
|
+
rel = cwd[len(home):] if cwd.startswith(home) else cwd
|
|
772
|
+
# Windows sessions read transcripts whose cwd may use either separator
|
|
773
|
+
# (e.g. POSIX-style paths). POSIX filenames may legitimately contain
|
|
774
|
+
# backslashes, so only normalize them on Windows.
|
|
775
|
+
if sys.platform == "win32":
|
|
776
|
+
rel = rel.replace("\\", "/")
|
|
777
|
+
sep = "/"
|
|
778
|
+
else:
|
|
779
|
+
sep = os.sep
|
|
780
|
+
rel = rel.strip(sep)
|
|
781
|
+
parts = rel.split(sep)
|
|
782
|
+
return parts[-1] if parts and parts[-1] else (rel or "unknown")
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def _windows_system_lang() -> str:
|
|
786
|
+
if os.name != "nt":
|
|
787
|
+
return ""
|
|
788
|
+
try:
|
|
789
|
+
import ctypes
|
|
790
|
+
import locale as _locale
|
|
791
|
+
|
|
792
|
+
windll = getattr(ctypes, "windll", None)
|
|
793
|
+
if windll is None:
|
|
794
|
+
return ""
|
|
795
|
+
lang_id = int(windll.kernel32.GetUserDefaultUILanguage())
|
|
796
|
+
return _locale.windows_locale.get(lang_id, "") or ""
|
|
797
|
+
except Exception:
|
|
798
|
+
return ""
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _detect_lang() -> str:
|
|
802
|
+
# Windows 上的 LANG 多半是 Git Bash / MSYS 帶進來的,不代表使用者的系統語言。
|
|
803
|
+
keys = (
|
|
804
|
+
("USAGE_LANG", "TT_LANG") if sys.platform == "win32" else ("USAGE_LANG", "TT_LANG", "LANG")
|
|
805
|
+
)
|
|
806
|
+
for key in keys:
|
|
807
|
+
value = os.environ.get(key, "").strip()
|
|
808
|
+
if value:
|
|
809
|
+
return _normalize_lang(value)
|
|
810
|
+
return _normalize_lang(_windows_system_lang())
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def _normalize_lang(code: str) -> str:
|
|
814
|
+
normalized = code.split(".")[0].strip().lower().replace("_", "-")
|
|
815
|
+
if normalized in {"zh-tw", "zh-hk", "zh-hant"} or normalized.startswith(("zh-tw-", "zh-hant")):
|
|
816
|
+
return "zh-TW"
|
|
817
|
+
if normalized in {"zh-cn", "zh-sg", "zh-hans", "zh"} or normalized.startswith(
|
|
818
|
+
("zh-cn-", "zh-hans")
|
|
819
|
+
):
|
|
820
|
+
return "zh-CN"
|
|
821
|
+
if normalized.startswith("ja"):
|
|
822
|
+
return "ja"
|
|
823
|
+
if normalized.startswith("ko"):
|
|
824
|
+
return "ko"
|
|
825
|
+
return "en"
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _load_template(lang: str) -> tuple[
|
|
829
|
+
str,
|
|
830
|
+
str,
|
|
831
|
+
str,
|
|
832
|
+
str,
|
|
833
|
+
str,
|
|
834
|
+
str,
|
|
835
|
+
str,
|
|
836
|
+
str,
|
|
837
|
+
dict[str, str],
|
|
838
|
+
]:
|
|
839
|
+
"""Return (lead, prompt, none, empty, uncommitted). ``lead`` is a short instruction prepended to
|
|
840
|
+
the injected context so Claude's first reply visibly acknowledges it loaded the
|
|
841
|
+
progress — the only way a SessionStart hook can surface itself to the user.
|
|
842
|
+
``empty`` is the standalone greeting shown when there's no fresh progress to report."""
|
|
843
|
+
fallback = _template_from_entry(_DEFAULT_TEMPLATES.get(lang) or _DEFAULT_TEMPLATES["en"])
|
|
844
|
+
try:
|
|
845
|
+
bundle = json.loads(PROMPT_SIDECAR.read_text(encoding="utf-8"))
|
|
846
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
847
|
+
return fallback
|
|
848
|
+
if not isinstance(bundle, dict):
|
|
849
|
+
return fallback
|
|
850
|
+
entry = bundle.get(lang) or bundle.get("en")
|
|
851
|
+
if not isinstance(entry, dict):
|
|
852
|
+
return fallback
|
|
853
|
+
return _template_from_entry(entry, fallback)
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _template_from_entry(
|
|
857
|
+
entry: Mapping[str, object],
|
|
858
|
+
fallback: tuple[str, str, str, str, str, str, str, str, dict[str, str]] | None = None,
|
|
859
|
+
) -> tuple[str, str, str, str, str, str, str, str, dict[str, str]]:
|
|
860
|
+
if fallback is None:
|
|
861
|
+
fallback = (
|
|
862
|
+
"",
|
|
863
|
+
_DEFAULT_PROMPT,
|
|
864
|
+
_DEFAULT_NONE,
|
|
865
|
+
_DEFAULT_EMPTY,
|
|
866
|
+
_DEFAULT_TEMPLATES["en"]["uncommitted"],
|
|
867
|
+
_DEFAULT_TEMPLATES["en"]["diagnosis_reminder"],
|
|
868
|
+
_DEFAULT_TEMPLATES["en"]["diagnosis_reminder_explain"],
|
|
869
|
+
_DEFAULT_TEMPLATES["en"]["diagnosis_default_cause"],
|
|
870
|
+
_DEFAULT_TEMPLATES["en"]["diagnosis_causes"],
|
|
871
|
+
)
|
|
872
|
+
lead = entry.get("lead")
|
|
873
|
+
prompt = entry.get("prompt")
|
|
874
|
+
none_label = entry.get("none")
|
|
875
|
+
empty = entry.get("empty")
|
|
876
|
+
uncommitted = entry.get("uncommitted")
|
|
877
|
+
diagnosis_reminder = entry.get("diagnosis_reminder")
|
|
878
|
+
diagnosis_reminder_explain = entry.get("diagnosis_reminder_explain")
|
|
879
|
+
diagnosis_default_cause = entry.get("diagnosis_default_cause")
|
|
880
|
+
raw_causes = entry.get("diagnosis_causes")
|
|
881
|
+
causes = dict(fallback[8])
|
|
882
|
+
if isinstance(raw_causes, Mapping):
|
|
883
|
+
for key in _DIAGNOSIS_CAUSE_KEYS:
|
|
884
|
+
value = raw_causes.get(key)
|
|
885
|
+
if isinstance(value, str) and value:
|
|
886
|
+
causes[key] = value
|
|
887
|
+
return (
|
|
888
|
+
lead if isinstance(lead, str) else fallback[0],
|
|
889
|
+
prompt if isinstance(prompt, str) and prompt else fallback[1],
|
|
890
|
+
none_label if isinstance(none_label, str) and none_label else fallback[2],
|
|
891
|
+
empty if isinstance(empty, str) and empty else fallback[3],
|
|
892
|
+
uncommitted if isinstance(uncommitted, str) and uncommitted else fallback[4],
|
|
893
|
+
(
|
|
894
|
+
diagnosis_reminder
|
|
895
|
+
if isinstance(diagnosis_reminder, str) and diagnosis_reminder
|
|
896
|
+
else fallback[5]
|
|
897
|
+
),
|
|
898
|
+
(
|
|
899
|
+
diagnosis_reminder_explain
|
|
900
|
+
if isinstance(diagnosis_reminder_explain, str) and diagnosis_reminder_explain
|
|
901
|
+
else fallback[6]
|
|
902
|
+
),
|
|
903
|
+
(
|
|
904
|
+
diagnosis_default_cause
|
|
905
|
+
if isinstance(diagnosis_default_cause, str) and diagnosis_default_cause
|
|
906
|
+
else fallback[7]
|
|
907
|
+
),
|
|
908
|
+
causes,
|
|
909
|
+
)
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
if __name__ == "__main__":
|
|
913
|
+
sys.exit(main())
|