fairshare-cli 0.1.1__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.
- fairshare/__init__.py +2 -0
- fairshare/browser.py +91 -0
- fairshare/cli.py +3266 -0
- fairshare/hub.py +272 -0
- fairshare/model.py +411 -0
- fairshare/plans/__init__.py +0 -0
- fairshare/plans/claude-max.toml +15 -0
- fairshare/plans/claude-pro.toml +13 -0
- fairshare/plans/claude-ultra.toml +17 -0
- fairshare/policy.py +73 -0
- fairshare/providers/__init__.py +12 -0
- fairshare/providers/base.py +193 -0
- fairshare/providers/claude.py +1176 -0
- fairshare/providers/claude_skill/SKILL.md +55 -0
- fairshare/session.py +113 -0
- fairshare/store.py +648 -0
- fairshare_cli-0.1.1.dist-info/METADATA +152 -0
- fairshare_cli-0.1.1.dist-info/RECORD +21 -0
- fairshare_cli-0.1.1.dist-info/WHEEL +4 -0
- fairshare_cli-0.1.1.dist-info/entry_points.txt +2 -0
- fairshare_cli-0.1.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1176 @@
|
|
|
1
|
+
"""Claude Code. Usage arrives on the statusLine command's stdin (documented), one account per
|
|
2
|
+
CLAUDE_CONFIG_DIR, and is asked for at launch through the tool's own `/usage` command. fairshare
|
|
3
|
+
never reads or copies a login.
|
|
4
|
+
|
|
5
|
+
Everything Anthropic may rename lives in the constants below and nowhere else in fairshare."""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import contextlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import hashlib
|
|
12
|
+
import re
|
|
13
|
+
import shlex
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
from dataclasses import replace
|
|
17
|
+
from datetime import datetime, timedelta
|
|
18
|
+
from importlib import resources
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from zoneinfo import ZoneInfo
|
|
21
|
+
|
|
22
|
+
from .. import store
|
|
23
|
+
from ..model import (EFFORT_NONE, NOTE_THINKING, NOTE_WRITING, USAGE_MODEL_TURN, USAGE_NO_ANSWER,
|
|
24
|
+
USAGE_NOT_UNDERSTOOD, USAGE_SIGNED_OUT, Account, AccountStatus, Candidate,
|
|
25
|
+
Capture, LiveSession, NoteEvent, SessionSeen, Window, model_window, plan_for,
|
|
26
|
+
window_names)
|
|
27
|
+
|
|
28
|
+
name = "claude" # fairshare's own id for this provider (accounts.toml, plans)
|
|
29
|
+
tool = "Claude Code" # the tool as users know it, for messages
|
|
30
|
+
web = "claude.ai" # where a subscription signs in and out in a browser
|
|
31
|
+
default_plan = "claude-pro"
|
|
32
|
+
|
|
33
|
+
# The command-line tool.
|
|
34
|
+
BINARY = "claude"
|
|
35
|
+
command = BINARY
|
|
36
|
+
STATUS_ARGS = ("auth", "status", "--json") # the sign-in check; accounts.toml may override it
|
|
37
|
+
LOGIN_ARGS = ("auth", "login") # interactive: the tool owns the browser sign-in
|
|
38
|
+
LOGOUT_ARGS = ("auth", "logout")
|
|
39
|
+
VERSION_ARGS = ("--version",)
|
|
40
|
+
PROBE_TIMEOUT = 5.0 # seconds
|
|
41
|
+
# The usage probe: the tool's own `/usage`, a local command (no model call, verified on 2.1.322,
|
|
42
|
+
# 2026-11-11), printed as a JSON envelope so that a release which sends it to the model instead
|
|
43
|
+
# shows up. The user's hooks are switched off for it: they would otherwise run at every launch,
|
|
44
|
+
# once per account (command-line settings beat the folder's own, verified the same day).
|
|
45
|
+
# accounts.toml may override it per account; `usage_args = []` turns it off.
|
|
46
|
+
USAGE_ARGS = ("-p", "--no-session-persistence", "--output-format", "json",
|
|
47
|
+
"--settings", '{"disableAllHooks":true}', "/usage")
|
|
48
|
+
USAGE_TIMEOUT = 6.0 # seconds; measured 1.1-2.4 s
|
|
49
|
+
usage_timeout = USAGE_TIMEOUT
|
|
50
|
+
# A pickup in the background: `claude --bg --name <name> <prompt>` starts a session with no
|
|
51
|
+
# terminal and prints how to attach to it. `--bg` passes the caller's environment on to the
|
|
52
|
+
# session (2.1.322, planner): only CONFIG_DIR_ENV arrives, so nothing else can travel that way.
|
|
53
|
+
# `--resume <id>` continues a session under its own id (any account can: the hub shares where
|
|
54
|
+
# the tool keeps sessions), in the foreground or with `--bg` (docs: CLI reference, /sessions and
|
|
55
|
+
# /agent-view, read 2026-11-12: on 2.1.257 or later the same id, or a copy with a `note:` line);
|
|
56
|
+
# `--fork-session` continues a copy under a new id. `--model <id>` and `--effort <level>` set the
|
|
57
|
+
# session's model and effort level (CLI reference, read 2026-11-12).
|
|
58
|
+
BG_ARGS, NAME_ARGS, RESUME_ARGS, FORK_ARGS = ("--bg",), ("--name",), ("--resume",), \
|
|
59
|
+
("--fork-session",)
|
|
60
|
+
MODEL_ARGS, EFFORT_ARGS = ("--model",), ("--effort",)
|
|
61
|
+
# The handoff note: one headless turn of a stopped session, resumed with the arguments above,
|
|
62
|
+
# in print mode with streamed JSON output and no tools (`--tools ""` disables every built-in
|
|
63
|
+
# tool). CLI reference, read 2026-11-12: `--include-partial-messages` requires `--print` and
|
|
64
|
+
# `--output-format stream-json`, its example also passes `--verbose`. One JSON object per line
|
|
65
|
+
# (2.1.322, planner, 2026-11-12): `system` lines (`thinking_tokens` while it thinks), then
|
|
66
|
+
# `stream_event` lines whose `event` is a `content_block_start` (`content_block.type`
|
|
67
|
+
# `thinking` or `text`) or a `content_block_delta` (`delta.type` `thinking_delta`, or
|
|
68
|
+
# `text_delta` with `delta.text`), among others; last, `{"type": "result", "is_error": ...,
|
|
69
|
+
# "result": <the answer's text>}` (/sessions, "Access conversations from scripts").
|
|
70
|
+
NOTE_ARGS = ("-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages",
|
|
71
|
+
"--tools", "")
|
|
72
|
+
NOTE_TYPE, NOTE_SUBTYPE, NOTE_EVENT = "type", "subtype", "event"
|
|
73
|
+
NOTE_SYSTEM, NOTE_THINKING_TOKENS, NOTE_STREAM = "system", "thinking_tokens", "stream_event"
|
|
74
|
+
NOTE_BLOCK_START, NOTE_BLOCK = "content_block_start", "content_block"
|
|
75
|
+
NOTE_DELTA_EVENT, NOTE_DELTA, NOTE_DELTA_TEXT = "content_block_delta", "delta", "text"
|
|
76
|
+
NOTE_THINKING_PARTS = ("thinking", "thinking_delta")
|
|
77
|
+
NOTE_TEXT_BLOCK, NOTE_TEXT_DELTA = "text", "text_delta"
|
|
78
|
+
# The running sessions: `claude agents --json`, items with `sessionId`, `name` and `status`
|
|
79
|
+
# (`busy` / `idle`), among others (`pid`, `cwd`, `kind`, `startedAt`); ended sessions are not
|
|
80
|
+
# listed (2.1.322, planner, 2026-11-11). A background session's name appeared within 4 s.
|
|
81
|
+
AGENTS_ARGS = ("agents", "--json")
|
|
82
|
+
# At its limit the tool tells the agent first (a user-side record: `[Usage limit reached; a short
|
|
83
|
+
# grace allowance remains, then this turn is cut off without warning. …]`), then ends the turn
|
|
84
|
+
# (`isApiErrorMessage`, `error: "rate_limit"`, `You've hit your 5-hour limit · resets 8:40pm
|
|
85
|
+
# (Zone)`). After the reset it queues, by itself, `I hit my usage limit while you were working,
|
|
86
|
+
# but it has reset now. Please continue from where you left off.` (`promptSource: "queued"`)
|
|
87
|
+
# and the session carries on. Observed, not documented: 2.1.322, 2026-11-11 (planner; a
|
|
88
|
+
# background and an interactive session). fairshare reads none of these texts; it relies only on
|
|
89
|
+
# the resume, to leave a session whose limit resets soon waiting (`resume_wait_minutes`).
|
|
90
|
+
RESUMES_AT_RESET = True
|
|
91
|
+
resumes_at_reset = RESUMES_AT_RESET
|
|
92
|
+
AGENT_ID, AGENT_NAME, AGENT_STATUS, AGENT_BUSY, AGENT_IDLE = (
|
|
93
|
+
"sessionId", "name", "status", "busy", "idle")
|
|
94
|
+
|
|
95
|
+
# Environment variables.
|
|
96
|
+
CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR" # picks the account's folder
|
|
97
|
+
# Variables that pick a login or a provider: dropped, and the launcher says so (names only).
|
|
98
|
+
LOGIN_OVERRIDE_ENV = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN",
|
|
99
|
+
"ANTHROPIC_BASE_URL", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX",
|
|
100
|
+
"CLAUDE_CODE_USE_FOUNDRY")
|
|
101
|
+
# What a running session injects into its children: dropped silently. Everything else, such as
|
|
102
|
+
# CLAUDE_CODE_MAX_OUTPUT_TOKENS, is the user's and passes through. Verified on Claude Code
|
|
103
|
+
# 2.1.322, 2026-11-09.
|
|
104
|
+
SESSION_MARK_ENV = "CLAUDECODE" # set in every child of a running session
|
|
105
|
+
SESSION_ENV = (SESSION_MARK_ENV, "CLAUDE_PID", "CLAUDE_EFFORT", "CLAUDE_JOB_DIR",
|
|
106
|
+
"CLAUDE_CODE_BRIDGE_SESSION_ID", "CLAUDE_CODE_CHILD_SESSION",
|
|
107
|
+
"CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_EXECPATH", "CLAUDE_CODE_MESSAGING_SOCKET",
|
|
108
|
+
"CLAUDE_CODE_MESSAGING_TOKEN", "CLAUDE_CODE_SESSION_ATTENDED",
|
|
109
|
+
"CLAUDE_CODE_SESSION_ID")
|
|
110
|
+
WATCH_ENV_PREFIX = "CLAUDE_" # inside a session, other such variables are reported
|
|
111
|
+
# Of those, what a command run inside a session (a tool's shell, `!`) learns of it: the session's
|
|
112
|
+
# full id, and the session's own process (2.1.322, planner).
|
|
113
|
+
SESSION_ID_ENV, SESSION_PID_ENV = "CLAUDE_CODE_SESSION_ID", "CLAUDE_PID"
|
|
114
|
+
|
|
115
|
+
# Files and folders.
|
|
116
|
+
SETTINGS_FILE = "settings.json" # holds the statusLine hook
|
|
117
|
+
# What every account shares through the hub; a name ending in "/" is a folder. Everything else in
|
|
118
|
+
# an account's folder (its login, STATE_FILE, caches, jobs, locks) stays its own. Observed in real
|
|
119
|
+
# config dirs on 2.1.322; CLAUDE.md, agents/, commands/, output-styles/ and keybindings.json are
|
|
120
|
+
# documented as user-level files (code.claude.com/docs/en/claude-directory, 2026-11-09), and so
|
|
121
|
+
# are rules/, workflows/, agent-memory/ and themes/ (same page, 2026-11-10).
|
|
122
|
+
SHARED = ("projects/", "history.jsonl", "file-history/", "paste-cache/", "plugins/", "skills/",
|
|
123
|
+
"tasks/", SETTINGS_FILE, "sessions/", "CLAUDE.md", "agents/", "commands/",
|
|
124
|
+
"output-styles/", "keybindings.json", "rules/", "workflows/", "agent-memory/",
|
|
125
|
+
"themes/")
|
|
126
|
+
shared = SHARED
|
|
127
|
+
# Shared, but never copied in by join: the sessions running now, each with its own key. A copy
|
|
128
|
+
# would be stale on arrival and would carry another session's key.
|
|
129
|
+
NOT_COPIED = ("sessions/",)
|
|
130
|
+
not_copied = NOT_COPIED
|
|
131
|
+
STATE_FILE = ".claude.json" # the tool's own state, inside CONFIG_DIR_ENV's folder
|
|
132
|
+
STATE_LOCK = STATE_FILE + ".lock" # the folder the tool holds while it writes STATE_FILE
|
|
133
|
+
STATE_LOCK_WAIT = 10.0 # seconds fairshare waits for that folder
|
|
134
|
+
STATE_LOCK_STALE = 30.0 # a lock folder untouched this long is left over: the tool
|
|
135
|
+
# leaves one behind at times (`auth status`, 2.1.322) and
|
|
136
|
+
# writes past an old one itself (one seen 25 s old)
|
|
137
|
+
DEFAULT_DIR = ".claude" # the folder used without CONFIG_DIR_ENV; its STATE_FILE is
|
|
138
|
+
# beside it in HOME
|
|
139
|
+
default_dir = "~/" + DEFAULT_DIR
|
|
140
|
+
ACCOUNT_DIR_GLOB = ".claude*" # folders under HOME that may be accounts (discovery only)
|
|
141
|
+
RC_FILES = (".zshrc", ".zprofile", ".zshenv", ".bashrc", ".bash_profile", ".bash_aliases",
|
|
142
|
+
".profile") # read-only, for aliases that set CONFIG_DIR_ENV
|
|
143
|
+
_ALIAS = re.compile(r"""^\s*alias\s+([\w.-]+)=["']?\s*(?:env\s+)?"""
|
|
144
|
+
+ re.escape(CONFIG_DIR_ENV) + r"""=("[^"]*"|'[^']*'|[^\s"';]+)""")
|
|
145
|
+
|
|
146
|
+
# JSON fields: the statusLine entry in the settings file, and the usage payload it is given.
|
|
147
|
+
STATUS_LINE_KEY = "statusLine"
|
|
148
|
+
HOOK_TYPE_KEY, HOOK_TYPE = "type", "command"
|
|
149
|
+
HOOK_COMMAND_KEY = "command"
|
|
150
|
+
SETTINGS_ENV = "env" # variables the settings file sets: values never shown
|
|
151
|
+
CAPTURE_LIMITS, CAPTURE_USED, CAPTURE_RESET = "rate_limits", "used_percentage", "resets_at"
|
|
152
|
+
# The session, in the statusLine payload and in every hook's input alike (documented:
|
|
153
|
+
# code.claude.com/docs/en/statusline and /hooks, read 2026-11-11).
|
|
154
|
+
SESSION_ID, SESSION_TRANSCRIPT, SESSION_CWD = "session_id", "transcript_path", "cwd"
|
|
155
|
+
# The statusLine payload's model (`model.id`, `model.display_name`) and effort level
|
|
156
|
+
# (`effort.level`: the session's level, the one actually run when the model does not support
|
|
157
|
+
# the one set; absent when the model takes no effort level). Documented: /statusline, read
|
|
158
|
+
# 2026-11-12.
|
|
159
|
+
CAPTURE_MODEL, CAPTURE_MODEL_ID, CAPTURE_MODEL_NAME = "model", "id", "display_name"
|
|
160
|
+
CAPTURE_EFFORT, CAPTURE_EFFORT_LEVEL = "effort", "level"
|
|
161
|
+
# The session's running cost (`cost.total_cost_usd`): an estimate at list price, computed by the
|
|
162
|
+
# tool, not a bill; it resets to 0 when `/clear` starts a new session. Documented: /statusline,
|
|
163
|
+
# read 2026-11-12.
|
|
164
|
+
CAPTURE_COST, CAPTURE_COST_TOTAL = "cost", "total_cost_usd"
|
|
165
|
+
# The statusLine re-runs on a timer as well as on events (seconds, minimum 1; documented). The bar
|
|
166
|
+
# then re-reads the local snapshot once a minute, which costs nothing.
|
|
167
|
+
STATUS_REFRESH_KEY, STATUS_REFRESH_S = "refreshInterval", 60
|
|
168
|
+
|
|
169
|
+
# fairshare's own hooks in the settings file: `hooks.<event>` is a list of groups, each a
|
|
170
|
+
# `matcher` and a `hooks` list of commands (documented, read 2026-11-11). Keyed by fairshare's
|
|
171
|
+
# name for the hook (`fairshare hook <name>`): the tool's event and the matcher (None: the
|
|
172
|
+
# event takes none, and the group is written without one). StopFailure fires instead of Stop
|
|
173
|
+
# when an API error ended the turn; its output and exit code are ignored, and its input names
|
|
174
|
+
# the error in HOOK_ERROR. PostToolUse (after every tool call; "*" matches every tool) and
|
|
175
|
+
# UserPromptSubmit (no matcher support: one would be ignored) take a JSON answer whose
|
|
176
|
+
# `hookSpecificOutput.additionalContext` is added to the model's context (documented: /hooks,
|
|
177
|
+
# read 2026-11-11). Every hook's input names a subagent or teammate it fired in by `agent_id`.
|
|
178
|
+
HOOKS_KEY, HOOK_MATCHER_KEY, HOOK_LIST_KEY = "hooks", "matcher", "hooks"
|
|
179
|
+
STOP_FAILURE, RATE_LIMIT = "StopFailure", "rate_limit"
|
|
180
|
+
POST_TOOL, ALL_TOOLS, PROMPT = "PostToolUse", "*", "UserPromptSubmit"
|
|
181
|
+
HOOK_ERROR, HOOK_AGENT = "error", "agent_id"
|
|
182
|
+
HOOK_OUTPUT, HOOK_EVENT_NAME, HOOK_CONTEXT = "hookSpecificOutput", "hookEventName", "additionalContext"
|
|
183
|
+
FAIRSHARE_HOOKS = {"stop-failure": (STOP_FAILURE, RATE_LIMIT), "post-tool": (POST_TOOL, ALL_TOOLS),
|
|
184
|
+
"prompt": (PROMPT, None)}
|
|
185
|
+
CONTEXT_EVENTS = (POST_TOOL, PROMPT) # the events whose hooks may speak to the model
|
|
186
|
+
|
|
187
|
+
# fairshare's skill, which teaches main sessions to use workers, watch and checkpoints: a folder
|
|
188
|
+
# holding SKILL.md, whose front matter (between `---` lines) gives `name` and `description`
|
|
189
|
+
# (documented: code.claude.com/docs/en/skills, read 2026-11-11). Shipped as package data beside
|
|
190
|
+
# this file, installed as the hub's shared `skills/fairshare/`, recognised by its `name`.
|
|
191
|
+
SKILLS_DIR, SKILL_FILE, SKILL_NAME = "skills", "SKILL.md", "fairshare"
|
|
192
|
+
SKILL_SOURCE = "claude_skill" # the shipped folder, in this package
|
|
193
|
+
SKILL_FENCE, SKILL_NAME_KEY = "---", "name"
|
|
194
|
+
|
|
195
|
+
# JSON fields of STATE_FILE that join may carry over from a user's folder, after asking, and nothing
|
|
196
|
+
# else (never identity, tokens or account fields). Onboarding is marked done by these two keys, set
|
|
197
|
+
# together when the first-run screens finish (2.1.322); the theme chosen there goes to
|
|
198
|
+
# SETTINGS_FILE. Folder trust is `projects.<path>.hasTrustDialogAccepted`, per account; so is the
|
|
199
|
+
# Claude in Chrome consent (seen 2026-11-10).
|
|
200
|
+
STATE_PROJECTS, STATE_TRUST = "projects", "hasTrustDialogAccepted"
|
|
201
|
+
STATE_MCP = "mcpServers"
|
|
202
|
+
STATE_ONBOARDING = ("hasCompletedOnboarding", "lastOnboardingVersion")
|
|
203
|
+
STATE_CHROME = ("hasCompletedClaudeInChromeOnboarding", "claudeInChromeDefaultEnabled")
|
|
204
|
+
|
|
205
|
+
# Which folder's trust covers a working folder (verified on 2.1.322, 2026-11-10, throwaway dirs):
|
|
206
|
+
# the folder and its parents up to the root of the git repository it is in (inclusive), plus the
|
|
207
|
+
# main repository's root for a git worktree; outside a repository, every parent. The tool's own
|
|
208
|
+
# dialog writes the main repository's root when accepted inside a repository, else the folder.
|
|
209
|
+
# Paths are the OS-canonical spelling. These name git's own files.
|
|
210
|
+
GIT_DIR = ".git" # a folder in a repository's root; a file in a worktree's
|
|
211
|
+
GIT_FILE_PREFIX = "gitdir:" # that file's one line names the worktree's git folder
|
|
212
|
+
GIT_COMMONDIR = "commondir" # in which this file names the main repository's .git
|
|
213
|
+
|
|
214
|
+
# JSON fields and values of the sign-in check's output.
|
|
215
|
+
STATUS_LOGGED_IN, STATUS_METHOD = "loggedIn", "authMethod"
|
|
216
|
+
STATUS_SUBSCRIPTION = "claude.ai" # the STATUS_METHOD of a subscription login
|
|
217
|
+
STATUS_ORG, STATUS_EMAIL, STATUS_PLAN = "orgId", "email", "planTier"
|
|
218
|
+
STATUS_EXPIRES = "loginExpiresAt" # ISO time the sign-in ends; null when signed out
|
|
219
|
+
|
|
220
|
+
# The usage probe's JSON envelope, and the text in its `result` (or on stdout without the
|
|
221
|
+
# envelope). Only lines starting with a known label are read: `<label>: N% used · resets <when>`,
|
|
222
|
+
# where <when> is `Nov 11 at 3:40pm (Zone/Name)` (2.1.322) or a bare `9pm` (2.1.321). The rest
|
|
223
|
+
# (tips, with local paths) is never parsed or kept. A signed-out folder answers with the cost
|
|
224
|
+
# summary instead (2.1.322, 2026-11-11).
|
|
225
|
+
USAGE_RESULT, USAGE_IS_ERROR = "result", "is_error"
|
|
226
|
+
USAGE_LOCAL, USAGE_LOCAL_NAME, USAGE_TURNS = "local_command", "usage", "num_turns"
|
|
227
|
+
USAGE_COST = "total_cost_usd"
|
|
228
|
+
USAGE_SESSION = "Current session"
|
|
229
|
+
USAGE_WEEK = "Current week (all models)"
|
|
230
|
+
USAGE_MODEL_WEEK = "Current week ({})" # {}: the model's name, e.g. Fable
|
|
231
|
+
USAGE_WINDOWS = {USAGE_SESSION: "five_hour", USAGE_WEEK: "seven_day"} # checked against plans
|
|
232
|
+
USAGE_COST_VIEW = "Total cost:" # the signed-out answer's first words
|
|
233
|
+
USAGE_MONTHS = ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov",
|
|
234
|
+
"dec")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _spaced(text: str) -> str:
|
|
238
|
+
"""A pattern for `text` that takes any run of spaces where it has one."""
|
|
239
|
+
return re.escape(text).replace(r"\ ", r"\s+")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
_MODEL_LABEL = (_spaced(USAGE_MODEL_WEEK.partition("{}")[0]) + r"\s*(?P<model>[^()]+?)\s*"
|
|
243
|
+
+ _spaced(USAGE_MODEL_WEEK.partition("{}")[2]))
|
|
244
|
+
_USAGE_LINE = re.compile(r"^\s*(?P<label>" + "|".join(_spaced(x) for x in USAGE_WINDOWS)
|
|
245
|
+
+ "|" + _MODEL_LABEL + r")\s*:\s*(?P<pct>\d+(?:\.\d+)?)\s*%\s*(?:used)?"
|
|
246
|
+
r"\s*(?:\u00b7\s*resets\s+(?P<when>.*?))?\s*$", re.I)
|
|
247
|
+
# "Nov 17 at 4pm" on macOS; "Nov 17, 4pm" from the same release on Linux (2.1.326)
|
|
248
|
+
_WHEN = re.compile(r"(?:(?P<month>[a-z]{3})[a-z]*\.?\s+(?P<day>\d{1,2})(?:\s+at\s+|\s*,\s*))?"
|
|
249
|
+
r"(?P<hour>\d{1,2})(?::(?P<minute>\d{2}))?\s*(?P<half>am|pm)"
|
|
250
|
+
r"\s*(?:\((?P<zone>[^()]+)\))?", re.I)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def parse_capture(raw: dict) -> dict[str, Window]:
|
|
254
|
+
known = window_names(name) # the plan files say which windows exist
|
|
255
|
+
out = {}
|
|
256
|
+
for key, w in (raw.get(CAPTURE_LIMITS) or {}).items():
|
|
257
|
+
if key in known and isinstance(w, dict) and CAPTURE_USED in w and CAPTURE_RESET in w:
|
|
258
|
+
out[key] = Window(float(w[CAPTURE_USED]), float(w[CAPTURE_RESET]))
|
|
259
|
+
return out
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _str(d: object, key: str) -> str | None:
|
|
263
|
+
v = d.get(key) if isinstance(d, dict) else None
|
|
264
|
+
return v if isinstance(v, str) and v else None
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _session(raw: object) -> SessionSeen | None:
|
|
268
|
+
"""The session a hook input (or a statusLine payload) names: id, folder, transcript."""
|
|
269
|
+
if (sid := _str(raw, SESSION_ID)) is None:
|
|
270
|
+
return None
|
|
271
|
+
return SessionSeen(sid, _str(raw, SESSION_CWD), _str(raw, SESSION_TRANSCRIPT))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def session_of(raw: object) -> SessionSeen | None:
|
|
275
|
+
"""The session a statusLine payload describes, with its running cost when given and its
|
|
276
|
+
model and effort level when the payload names a model; else None."""
|
|
277
|
+
if (seen := _session(raw)) is None:
|
|
278
|
+
return None
|
|
279
|
+
cost = raw[CAPTURE_COST].get(CAPTURE_COST_TOTAL) if isinstance(raw.get(CAPTURE_COST),
|
|
280
|
+
dict) else None
|
|
281
|
+
if isinstance(cost, (int, float)) and not isinstance(cost, bool) and cost >= 0:
|
|
282
|
+
seen = replace(seen, cost=float(cost))
|
|
283
|
+
if (model := _str(raw.get(CAPTURE_MODEL), CAPTURE_MODEL_ID)) is None:
|
|
284
|
+
return seen
|
|
285
|
+
return replace(seen, model=model, model_name=_str(raw[CAPTURE_MODEL], CAPTURE_MODEL_NAME),
|
|
286
|
+
effort=_str(raw.get(CAPTURE_EFFORT), CAPTURE_EFFORT_LEVEL) or EFFORT_NONE)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def current_session() -> str | None:
|
|
290
|
+
"""The id of the session this process runs inside, else None."""
|
|
291
|
+
return os.environ.get(SESSION_ID_ENV) or None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def session_pid() -> int | None:
|
|
295
|
+
"""The process id of the session this process runs inside, else None."""
|
|
296
|
+
try:
|
|
297
|
+
return int(os.environ[SESSION_PID_ENV])
|
|
298
|
+
except (KeyError, ValueError):
|
|
299
|
+
return None
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def resume_args(session_id: str, fork: bool = False) -> list[str]:
|
|
303
|
+
return [*RESUME_ARGS, session_id, *(FORK_ARGS if fork else ())]
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def model_args(model: str | None, effort: str | None) -> list[str]:
|
|
307
|
+
"""Arguments that start a session on `model` at `effort` (EFFORT_NONE or None: no effort
|
|
308
|
+
argument); none for what is None."""
|
|
309
|
+
return [*((*MODEL_ARGS, model) if model else ()),
|
|
310
|
+
*((*EFFORT_ARGS, effort) if effort and effort != EFFORT_NONE else ())]
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def uses_week(model: str, week: str) -> bool:
|
|
314
|
+
"""Whether the per-model week the usage report names `week` (`Fable`) limits `model` (an
|
|
315
|
+
id such as `claude-fable-5-2`, an alias or a display name): every word of the week's name
|
|
316
|
+
is in the model's."""
|
|
317
|
+
words = week.lower().split()
|
|
318
|
+
return bool(words) and all(w in model.lower() for w in words)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def background(account: Account, name: str, prompt: str, extra: list[str] = ()
|
|
322
|
+
) -> tuple[list[str], dict[str, str]]:
|
|
323
|
+
"""The command and environment that start a session of `account` with no terminal, named
|
|
324
|
+
`name`, with `extra` arguments (a resume, a model) and `prompt` as its first message."""
|
|
325
|
+
return ([real_binary(), *BG_ARGS, *NAME_ARGS, name, *extra, prompt],
|
|
326
|
+
clean_env(account.config_dir))
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def note_command(account: Account, session_id: str, extra: list[str], prompt: str
|
|
330
|
+
) -> tuple[list[str], dict[str, str]]:
|
|
331
|
+
"""One headless turn of the stopped session `session_id` on `account`: no tools, streamed
|
|
332
|
+
JSON out, with `extra` arguments (a model) and `prompt` as the turn's message. The id stays
|
|
333
|
+
the same."""
|
|
334
|
+
return ([real_binary(), *NOTE_ARGS, *resume_args(session_id), *extra, prompt],
|
|
335
|
+
clean_env(account.config_dir))
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def note_event(line: str) -> NoteEvent | None:
|
|
339
|
+
"""What one line of that turn's output says: thinking, or writing (with the new text); None
|
|
340
|
+
for any other line, or one that does not parse."""
|
|
341
|
+
try:
|
|
342
|
+
d = json.loads(line)
|
|
343
|
+
except ValueError:
|
|
344
|
+
return None
|
|
345
|
+
if not isinstance(d, dict):
|
|
346
|
+
return None
|
|
347
|
+
if d.get(NOTE_TYPE) == NOTE_SYSTEM:
|
|
348
|
+
return NoteEvent(NOTE_THINKING) if d.get(NOTE_SUBTYPE) == NOTE_THINKING_TOKENS else None
|
|
349
|
+
e = d.get(NOTE_EVENT) if d.get(NOTE_TYPE) == NOTE_STREAM else None
|
|
350
|
+
part = e.get({NOTE_BLOCK_START: NOTE_BLOCK, NOTE_DELTA_EVENT: NOTE_DELTA}.get(
|
|
351
|
+
e.get(NOTE_TYPE), "")) if isinstance(e, dict) else None
|
|
352
|
+
kind = part.get(NOTE_TYPE) if isinstance(part, dict) else None
|
|
353
|
+
if kind in NOTE_THINKING_PARTS:
|
|
354
|
+
return NoteEvent(NOTE_THINKING)
|
|
355
|
+
if kind == NOTE_TEXT_BLOCK:
|
|
356
|
+
return NoteEvent(NOTE_WRITING)
|
|
357
|
+
if kind == NOTE_TEXT_DELTA:
|
|
358
|
+
return NoteEvent(NOTE_WRITING, _str(part, NOTE_DELTA_TEXT) or "")
|
|
359
|
+
return None
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def note_text(out: str) -> str | None:
|
|
363
|
+
"""The answer's text in that turn's final output line (a JSON document); None for an error
|
|
364
|
+
or no text."""
|
|
365
|
+
try:
|
|
366
|
+
d = json.loads(out)
|
|
367
|
+
except ValueError:
|
|
368
|
+
return None
|
|
369
|
+
text = _str(d, USAGE_RESULT)
|
|
370
|
+
return None if not isinstance(d, dict) or d.get(USAGE_IS_ERROR) is True or not text \
|
|
371
|
+
else text.strip() or None
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def list_sessions(account: Account) -> list[LiveSession] | None:
|
|
375
|
+
"""The sessions running now, as the tool lists them (any account's folder sees them all:
|
|
376
|
+
the hub shares where the tool keeps them); None when the list could not be had."""
|
|
377
|
+
try:
|
|
378
|
+
r = subprocess.run([real_binary(), *AGENTS_ARGS], env=clean_env(account.config_dir),
|
|
379
|
+
stdin=subprocess.DEVNULL, capture_output=True, text=True,
|
|
380
|
+
timeout=PROBE_TIMEOUT)
|
|
381
|
+
raw = json.loads(r.stdout)
|
|
382
|
+
except (SystemExit, OSError, subprocess.SubprocessError, ValueError):
|
|
383
|
+
return None
|
|
384
|
+
if isinstance(raw, dict): # a list inside an object would do as well
|
|
385
|
+
raw = next((v for v in raw.values() if isinstance(v, list)), None)
|
|
386
|
+
if not isinstance(raw, list):
|
|
387
|
+
return None
|
|
388
|
+
status = {AGENT_BUSY: True, AGENT_IDLE: False}
|
|
389
|
+
return [LiveSession(i[AGENT_ID], i.get(AGENT_NAME) if isinstance(i.get(AGENT_NAME), str)
|
|
390
|
+
else None, status.get(i.get(AGENT_STATUS)))
|
|
391
|
+
for i in raw if isinstance(i, dict) and isinstance(i.get(AGENT_ID), str)]
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
# The transcript (`transcript_path`, internal and per version: one JSON record per line; fixture
|
|
395
|
+
# tests/fixtures/claude-2.1.322/transcript.jsonl). Only records of these types that are not on a
|
|
396
|
+
# side chain (a subagent's) are the conversation; their text is the message's content, a string
|
|
397
|
+
# or a list of blocks of which only the text blocks are words (thinking, tool use and tool results
|
|
398
|
+
# are not). Every other record type (copies of requests among them) is never shown.
|
|
399
|
+
T_TYPE, T_SIDECHAIN, T_MESSAGE, T_CONTENT = "type", "isSidechain", "message", "content"
|
|
400
|
+
T_ROLES = {"user": "user", "assistant": "assistant"} # record type -> fairshare's role
|
|
401
|
+
T_BLOCK_TYPE, T_TEXT_BLOCK, T_TEXT = "type", "text", "text"
|
|
402
|
+
# A `!` command typed in a session is a user message of its own, `<bash-input>cmd</bash-input>`,
|
|
403
|
+
# and its output another, `<bash-stdout>...</bash-stdout>` with `<bash-stderr>...</bash-stderr>`
|
|
404
|
+
# (2.1.322, planner, 2026-11-11). They become the roles "command" and "output".
|
|
405
|
+
T_BANG_INPUT, T_BANG_OUTPUT = "bash-input", ("bash-stdout", "bash-stderr")
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _tagged(text: str, tag: str) -> str | None:
|
|
409
|
+
"""What `<tag>...</tag>` holds in `text`, else None."""
|
|
410
|
+
m = re.search(f"<{tag}>(.*?)</{tag}>", text, re.S)
|
|
411
|
+
return m.group(1) if m else None
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _bang(text: str) -> tuple[str, str] | None:
|
|
415
|
+
"""A `!` command's message as ("command", the command) or ("output", what it printed),
|
|
416
|
+
else None."""
|
|
417
|
+
if text.startswith(f"<{T_BANG_INPUT}>") and (cmd := _tagged(text, T_BANG_INPUT)) is not None:
|
|
418
|
+
return "command", cmd.strip()
|
|
419
|
+
found = [x for tag in T_BANG_OUTPUT if (x := _tagged(text, tag)) is not None]
|
|
420
|
+
if found and text.startswith(tuple(f"<{tag}>" for tag in T_BANG_OUTPUT)):
|
|
421
|
+
return "output", "\n".join(x.strip("\n") for x in found if x.strip())
|
|
422
|
+
return None
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _text_of(content: object) -> str | None:
|
|
426
|
+
if isinstance(content, str):
|
|
427
|
+
return content
|
|
428
|
+
if isinstance(content, list):
|
|
429
|
+
return "\n\n".join(b[T_TEXT] for b in content if isinstance(b, dict)
|
|
430
|
+
and b.get(T_BLOCK_TYPE) == T_TEXT_BLOCK and isinstance(b.get(T_TEXT), str))
|
|
431
|
+
return None
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def transcript_text(path: Path) -> list[tuple[str, str]] | None:
|
|
435
|
+
"""The main conversation of a transcript, oldest first, as (role, text) pairs with role
|
|
436
|
+
"user" or "assistant", or "command" and "output" for a `!` command the user ran: only
|
|
437
|
+
words, never tool calls, tool results, thinking, side chains or other records. [] when it
|
|
438
|
+
holds no such message; None when it cannot be read."""
|
|
439
|
+
try:
|
|
440
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
441
|
+
except (OSError, UnicodeDecodeError):
|
|
442
|
+
return None
|
|
443
|
+
out = []
|
|
444
|
+
for line in lines:
|
|
445
|
+
try:
|
|
446
|
+
r = json.loads(line)
|
|
447
|
+
except ValueError:
|
|
448
|
+
continue
|
|
449
|
+
if not isinstance(r, dict) or r.get(T_TYPE) not in T_ROLES \
|
|
450
|
+
or r.get(T_SIDECHAIN) is not False or not isinstance(r.get(T_MESSAGE), dict):
|
|
451
|
+
continue
|
|
452
|
+
if (text := _text_of(r[T_MESSAGE].get(T_CONTENT))) and text.strip():
|
|
453
|
+
role = T_ROLES[r[T_TYPE]]
|
|
454
|
+
bang = _bang(text.strip()) if role == "user" else None
|
|
455
|
+
if bang is None:
|
|
456
|
+
out.append((role, text.strip()))
|
|
457
|
+
elif bang[1]:
|
|
458
|
+
out.append(bang)
|
|
459
|
+
return out
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def hook_session(hook: str, raw: object) -> SessionSeen | None:
|
|
463
|
+
"""For fairshare's hook `hook`: the session its input describes, when the input is the event
|
|
464
|
+
fairshare wired it for (an input naming another error is not); else None. A hook that
|
|
465
|
+
speaks to the model gets None for an input from inside a subagent: the main session
|
|
466
|
+
decides."""
|
|
467
|
+
if hook not in FAIRSHARE_HOOKS or not isinstance(raw, dict):
|
|
468
|
+
return None
|
|
469
|
+
event, matcher = FAIRSHARE_HOOKS[hook]
|
|
470
|
+
if event in CONTEXT_EVENTS:
|
|
471
|
+
if raw.get(HOOK_AGENT) is not None:
|
|
472
|
+
return None
|
|
473
|
+
elif (error := raw.get(HOOK_ERROR)) is not None and error != matcher:
|
|
474
|
+
return None
|
|
475
|
+
return _session(raw)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def hook_output(hook: str, text: str) -> str:
|
|
479
|
+
"""What fairshare's hook `hook` prints so that `text` reaches the model as context."""
|
|
480
|
+
return json.dumps({HOOK_OUTPUT: {HOOK_EVENT_NAME: FAIRSHARE_HOOKS[hook][0],
|
|
481
|
+
HOOK_CONTEXT: text}}, ensure_ascii=False)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def launch(account: Account) -> tuple[list[str], dict[str, str]]:
|
|
485
|
+
return [real_binary()], clean_env(account.config_dir)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def login_command(config_dir: Path) -> tuple[list[str], dict[str, str]]:
|
|
489
|
+
return [real_binary(), *LOGIN_ARGS], clean_env(config_dir)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def logout_command(config_dir: Path) -> tuple[list[str], dict[str, str]]:
|
|
493
|
+
return [real_binary(), *LOGOUT_ARGS], clean_env(config_dir)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def session_dir() -> Path | None:
|
|
497
|
+
"""The account folder of the session this process runs in (a usage hook's), else None."""
|
|
498
|
+
d = os.environ.get(CONFIG_DIR_ENV)
|
|
499
|
+
return Path(d) if d else None
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _scrubbed_env() -> dict[str, str]:
|
|
503
|
+
return {k: v for k, v in os.environ.items()
|
|
504
|
+
if k not in LOGIN_OVERRIDE_ENV and k not in SESSION_ENV}
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def clean_env(config_dir: Path) -> dict[str, str]:
|
|
508
|
+
"""The environment for a child claude of one account: this process's, minus every variable
|
|
509
|
+
that would pick another login or carry another session's state, with the account's dir."""
|
|
510
|
+
return {**_scrubbed_env(), CONFIG_DIR_ENV: str(config_dir)}
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def dropped_login_vars() -> list[str]:
|
|
514
|
+
return [k for k in LOGIN_OVERRIDE_ENV if k in os.environ]
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def passed_session_vars() -> list[str]:
|
|
518
|
+
"""Inside a running session: names of the other CLAUDE_* variables the child will inherit,
|
|
519
|
+
so a session variable a new release adds shows up instead of silently misleading the child.
|
|
520
|
+
Empty outside a session."""
|
|
521
|
+
if SESSION_MARK_ENV not in os.environ:
|
|
522
|
+
return []
|
|
523
|
+
return sorted(k for k in os.environ if k.startswith(WATCH_ENV_PREFIX)
|
|
524
|
+
and k not in SESSION_ENV and k not in LOGIN_OVERRIDE_ENV and k != CONFIG_DIR_ENV)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _iso(value: object) -> float | None:
|
|
528
|
+
"""Unix seconds of an ISO time with a zone (`2030-01-02T03:04:05.678Z`), else None."""
|
|
529
|
+
try:
|
|
530
|
+
t = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
531
|
+
return t.timestamp() if t.tzinfo else None
|
|
532
|
+
except (AttributeError, ValueError):
|
|
533
|
+
return None
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def parse_account_status(raw: object) -> AccountStatus | None:
|
|
537
|
+
"""The status JSON as an AccountStatus; None when it is not the shape we know."""
|
|
538
|
+
if not isinstance(raw, dict) or not isinstance(raw.get(STATUS_LOGGED_IN), bool):
|
|
539
|
+
return None
|
|
540
|
+
if not raw[STATUS_LOGGED_IN]:
|
|
541
|
+
return AccountStatus(False, False)
|
|
542
|
+
org, email = raw.get(STATUS_ORG), raw.get(STATUS_EMAIL)
|
|
543
|
+
who = hashlib.sha256(f"{org}\n{email}".encode()).hexdigest() if org and email else None
|
|
544
|
+
return AccountStatus(True, raw.get(STATUS_METHOD) == STATUS_SUBSCRIPTION, who,
|
|
545
|
+
plan_for(name, raw.get(STATUS_PLAN)), _iso(raw.get(STATUS_EXPIRES)))
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _account_env(account: Account) -> dict[str, str]:
|
|
549
|
+
"""The environment for asking the tool about `account`: for the user's DEFAULT_DIR without
|
|
550
|
+
CONFIG_DIR_ENV, as the tool itself runs there (setting it may name a different login
|
|
551
|
+
entry)."""
|
|
552
|
+
env = clean_env(account.config_dir)
|
|
553
|
+
if account.config_dir == Path.home() / DEFAULT_DIR:
|
|
554
|
+
del env[CONFIG_DIR_ENV]
|
|
555
|
+
return env
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def account_status(account: Account) -> AccountStatus | None:
|
|
559
|
+
"""Ask the installed claude who `account` is. Reads no login file; the output is parsed in
|
|
560
|
+
memory and only its yes/no, a hash, a plan name and the sign-in's end survive. None on any
|
|
561
|
+
failure. The exit code is not read: a signed-out folder prints its answer and exits 1
|
|
562
|
+
(2.1.322)."""
|
|
563
|
+
env = _account_env(account)
|
|
564
|
+
try:
|
|
565
|
+
r = subprocess.run([real_binary(), *(account.status_args or STATUS_ARGS)],
|
|
566
|
+
env=env, stdin=subprocess.DEVNULL,
|
|
567
|
+
capture_output=True, text=True, timeout=PROBE_TIMEOUT)
|
|
568
|
+
return parse_account_status(json.loads(r.stdout))
|
|
569
|
+
except (SystemExit, OSError, subprocess.SubprocessError, ValueError):
|
|
570
|
+
return None
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _reset_at(when: str, now: float) -> float | None:
|
|
574
|
+
"""Unix seconds of a printed reset (`Nov 12 at 3am (America/Denver)`, or a bare `9pm`), in
|
|
575
|
+
the zone it names (local time for a missing or unknown one); None when it cannot be read.
|
|
576
|
+
There is no year: the first candidate after `now - SAME_WINDOW_S` (the printed minute jitters,
|
|
577
|
+
so a reset a minute ago is that one, not next year's or tomorrow's); a bare clock time is its
|
|
578
|
+
next occurrence on that rule."""
|
|
579
|
+
m = _WHEN.fullmatch(when.strip())
|
|
580
|
+
if not m or int(m["hour"]) > 12 or int(m["minute"] or 0) > 59:
|
|
581
|
+
return None
|
|
582
|
+
try:
|
|
583
|
+
zone = ZoneInfo(m["zone"].strip()) if m["zone"] else None
|
|
584
|
+
except (KeyError, ValueError, OSError): # ZoneInfoNotFoundError is a KeyError
|
|
585
|
+
zone = None
|
|
586
|
+
hour = int(m["hour"]) % 12 + (12 if m["half"].lower() == "pm" else 0)
|
|
587
|
+
minute = int(m["minute"] or 0)
|
|
588
|
+
base = datetime.fromtimestamp(now, zone).replace(hour=hour, minute=minute, second=0,
|
|
589
|
+
microsecond=0)
|
|
590
|
+
if not m["month"]:
|
|
591
|
+
days = [base + timedelta(days=d) for d in (-1, 0, 1)]
|
|
592
|
+
elif (month := m["month"].lower()) not in USAGE_MONTHS:
|
|
593
|
+
return None
|
|
594
|
+
else:
|
|
595
|
+
days = []
|
|
596
|
+
for year in (base.year - 1, base.year, base.year + 1):
|
|
597
|
+
with contextlib.suppress(ValueError): # Feb 29 in a common year
|
|
598
|
+
days.append(base.replace(year=year, month=USAGE_MONTHS.index(month) + 1,
|
|
599
|
+
day=int(m["day"])))
|
|
600
|
+
return next((t for d in days if (t := d.timestamp()) > now - store.SAME_WINDOW_S), None)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def parse_usage(text: str, now: float) -> dict[str, Window]:
|
|
604
|
+
"""The windows in `/usage` text, keyed as parse_capture keys them, plus per-model weeks under
|
|
605
|
+
`model_window`. A line with no readable reset is dropped: a window without one is useless."""
|
|
606
|
+
known, out = window_names(name), {}
|
|
607
|
+
for line in text.splitlines():
|
|
608
|
+
if not (m := _USAGE_LINE.match(line)) or not m["when"]:
|
|
609
|
+
continue
|
|
610
|
+
said = " ".join(m["label"].split()).lower()
|
|
611
|
+
label = next((k for k in USAGE_WINDOWS if k.lower() == said), None)
|
|
612
|
+
key = USAGE_WINDOWS[label] if label else model_window(USAGE_WINDOWS[USAGE_WEEK],
|
|
613
|
+
m["model"].strip())
|
|
614
|
+
if (label and key not in known) or (at := _reset_at(m["when"], now)) is None:
|
|
615
|
+
continue
|
|
616
|
+
out[key] = Window(float(m["pct"]), at)
|
|
617
|
+
return out
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def read_usage(account: Account, now: float) -> dict[str, Window] | str | None:
|
|
621
|
+
"""Ask the installed claude for `account`'s usage (USAGE_ARGS, or the account's own
|
|
622
|
+
`usage_args`). The windows it read; else a short, value-free reason (a string); None when the
|
|
623
|
+
account's `usage_args` turn the probe off. Never raises. Runs like account_status: clean
|
|
624
|
+
environment, stdin from /dev/null, in this process's folder. With the JSON envelope, an answer
|
|
625
|
+
that was not the local command (the model ran) gives USAGE_MODEL_TURN and no windows; plain
|
|
626
|
+
text (an override without the envelope) is read too, but then that guard is blind."""
|
|
627
|
+
args = USAGE_ARGS if account.usage_args is None else account.usage_args
|
|
628
|
+
if not args:
|
|
629
|
+
return None
|
|
630
|
+
try:
|
|
631
|
+
r = subprocess.run([real_binary(), *args], env=_account_env(account),
|
|
632
|
+
stdin=subprocess.DEVNULL, capture_output=True, text=True,
|
|
633
|
+
timeout=USAGE_TIMEOUT)
|
|
634
|
+
except subprocess.TimeoutExpired:
|
|
635
|
+
return f"{USAGE_NO_ANSWER}: timed out"
|
|
636
|
+
except (SystemExit, OSError, subprocess.SubprocessError, ValueError):
|
|
637
|
+
return f"{USAGE_NO_ANSWER}: could not run {BINARY}"
|
|
638
|
+
try:
|
|
639
|
+
envelope = json.loads(r.stdout)
|
|
640
|
+
except ValueError:
|
|
641
|
+
envelope = None
|
|
642
|
+
if isinstance(envelope, dict):
|
|
643
|
+
# A model turn shows as turns or cost, never as a missing field alone: an error answer
|
|
644
|
+
# (no network, say) must not tell the user to switch the probe off.
|
|
645
|
+
turns, cost = envelope.get(USAGE_TURNS), envelope.get(USAGE_COST)
|
|
646
|
+
if (isinstance(turns, int) and turns > 0) or (isinstance(cost, (int, float)) and cost > 0):
|
|
647
|
+
return USAGE_MODEL_TURN
|
|
648
|
+
text = envelope.get(USAGE_RESULT)
|
|
649
|
+
if envelope.get(USAGE_IS_ERROR) is True or not isinstance(text, str):
|
|
650
|
+
return f"{USAGE_NO_ANSWER}: error"
|
|
651
|
+
if envelope.get(USAGE_LOCAL) != USAGE_LOCAL_NAME:
|
|
652
|
+
return USAGE_NOT_UNDERSTOOD
|
|
653
|
+
elif r.returncode != 0:
|
|
654
|
+
return f"{USAGE_NO_ANSWER}: exit {r.returncode}"
|
|
655
|
+
elif not (text := r.stdout).strip():
|
|
656
|
+
return f"{USAGE_NO_ANSWER}: no output"
|
|
657
|
+
if windows := parse_usage(text, now):
|
|
658
|
+
return windows
|
|
659
|
+
return USAGE_SIGNED_OUT if text.lstrip().startswith(USAGE_COST_VIEW) else USAGE_NOT_UNDERSTOOD
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def find_binary(path: str | None = None) -> str | None:
|
|
663
|
+
"""The first BINARY on PATH (or on `path`, when given)."""
|
|
664
|
+
return shutil.which(BINARY, path=path)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def real_binary(path: str | None = None) -> str:
|
|
668
|
+
if (found := find_binary(path)) is None:
|
|
669
|
+
raise SystemExit(f"fairshare: no {BINARY} found on PATH")
|
|
670
|
+
return found
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def version() -> str | None:
|
|
674
|
+
"""The first line the tool prints for VERSION_ARGS, in a scrubbed environment; None on any
|
|
675
|
+
failure."""
|
|
676
|
+
try:
|
|
677
|
+
r = subprocess.run([real_binary(), *VERSION_ARGS], env=_scrubbed_env(),
|
|
678
|
+
stdin=subprocess.DEVNULL, capture_output=True, text=True,
|
|
679
|
+
timeout=PROBE_TIMEOUT)
|
|
680
|
+
lines = r.stdout.strip().splitlines() if r.returncode == 0 else []
|
|
681
|
+
return lines[0][:80] if lines else None
|
|
682
|
+
except (SystemExit, OSError, subprocess.SubprocessError):
|
|
683
|
+
return None
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def discover(home: Path) -> list[Candidate]:
|
|
687
|
+
"""Folders set up under `home`: aliases of the form `alias X="CONFIG_DIR_ENV=P ..."` in
|
|
688
|
+
shell rc files (best effort), and ACCOUNT_DIR_GLOB dirs the tool has run in: holding their
|
|
689
|
+
own STATE_FILE, or DEFAULT_DIR with HOME's beside it. Shared items alone (a folder of shared
|
|
690
|
+
sessions, say) do not make an account. DEFAULT_DIR first, then by id. Reads no login."""
|
|
691
|
+
found: dict[Path, Candidate] = {}
|
|
692
|
+
for rc in RC_FILES:
|
|
693
|
+
try:
|
|
694
|
+
lines = (home / rc).read_text(errors="replace").splitlines()
|
|
695
|
+
except OSError:
|
|
696
|
+
continue
|
|
697
|
+
for line in lines:
|
|
698
|
+
if m := _ALIAS.match(line):
|
|
699
|
+
d = _expand(m.group(2).strip("\"'"), home)
|
|
700
|
+
found.setdefault(d, Candidate(m.group(1), name, d, f"alias in ~/{rc}"))
|
|
701
|
+
for d in sorted(home.glob(ACCOUNT_DIR_GLOB)):
|
|
702
|
+
if d in found or not d.is_dir():
|
|
703
|
+
continue
|
|
704
|
+
if (d / STATE_FILE).is_file() or (d == home / DEFAULT_DIR
|
|
705
|
+
and (home / STATE_FILE).is_file()):
|
|
706
|
+
found[d] = Candidate(d.name.lstrip("."), name, d, f"folder ~/{d.name}")
|
|
707
|
+
return sorted(found.values(), key=lambda c: (c.config_dir != home / DEFAULT_DIR, c.id))
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def _expand(p: str, home: Path) -> Path:
|
|
711
|
+
for prefix in ("~/", "$HOME/", "${HOME}/"):
|
|
712
|
+
if p.startswith(prefix):
|
|
713
|
+
return home / p[len(prefix):]
|
|
714
|
+
return home if p in ("~", "$HOME", "${HOME}") else Path(p)
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
# --- The tool's state file: which one a folder uses, and what join may carry over from it.
|
|
718
|
+
|
|
719
|
+
def state_file(folder: Path, home: Path) -> Path:
|
|
720
|
+
"""The STATE_FILE that `folder` uses: its own, or for DEFAULT_DIR (used without
|
|
721
|
+
CONFIG_DIR_ENV) the one beside it in HOME."""
|
|
722
|
+
inside = folder / STATE_FILE
|
|
723
|
+
if not inside.exists() and folder == home / DEFAULT_DIR:
|
|
724
|
+
return home / STATE_FILE
|
|
725
|
+
return inside
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def state_lock(state: Path) -> Path:
|
|
729
|
+
"""The folder the tool holds while it writes `state`; fairshare takes it too."""
|
|
730
|
+
return state.with_name(STATE_LOCK)
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def hold_state(state: Path):
|
|
734
|
+
"""Hold the tool's own lock folder for `state` while the block runs, as the tool does: wait
|
|
735
|
+
up to STATE_LOCK_WAIT seconds, take over one left over (older than STATE_LOCK_STALE), else
|
|
736
|
+
raise OSError."""
|
|
737
|
+
return store.held(state_lock(state), STATE_LOCK_WAIT, STATE_LOCK_STALE)
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def _read_state(state: Path) -> dict:
|
|
741
|
+
"""STATE_FILE's object ({} when there is none). Raises for one that cannot be read or decoded:
|
|
742
|
+
it is never taken for absent."""
|
|
743
|
+
if not state.exists():
|
|
744
|
+
return {}
|
|
745
|
+
d = json.loads(state.read_text(encoding="utf-8"))
|
|
746
|
+
if not isinstance(d, dict):
|
|
747
|
+
raise ValueError("not a JSON object")
|
|
748
|
+
return d
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def _git_root(path: Path) -> Path | None:
|
|
752
|
+
"""The root of the git repository (or worktree) `path` is in, else None."""
|
|
753
|
+
for p in (path, *path.parents):
|
|
754
|
+
if os.path.lexists(p / GIT_DIR):
|
|
755
|
+
return p
|
|
756
|
+
return None
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def _main_root(root: Path) -> Path:
|
|
760
|
+
"""For a git worktree's root, the main repository's root; otherwise `root` itself."""
|
|
761
|
+
dot = root / GIT_DIR
|
|
762
|
+
if not dot.is_file():
|
|
763
|
+
return root
|
|
764
|
+
try:
|
|
765
|
+
line = dot.read_text(encoding="utf-8").strip()
|
|
766
|
+
if not line.startswith(GIT_FILE_PREFIX):
|
|
767
|
+
return root
|
|
768
|
+
gitdir = (root / line[len(GIT_FILE_PREFIX):].strip()).resolve()
|
|
769
|
+
common = (gitdir / (gitdir / GIT_COMMONDIR).read_text(encoding="utf-8").strip()).resolve()
|
|
770
|
+
except (OSError, UnicodeDecodeError):
|
|
771
|
+
return root # a submodule, or something else: its own root
|
|
772
|
+
return common.parent if common.name == GIT_DIR else root
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def trust_paths(path: Path) -> list[Path]:
|
|
776
|
+
"""The folders whose trust covers the canonical folder `path`, as the tool looks them up."""
|
|
777
|
+
root = _git_root(path)
|
|
778
|
+
if root is None:
|
|
779
|
+
return [path, *path.parents]
|
|
780
|
+
up = [path, *(p for p in path.parents if p.is_relative_to(root))]
|
|
781
|
+
main = _main_root(root)
|
|
782
|
+
return up + ([main] if main != root else [])
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def trust_key(path: Path) -> Path:
|
|
786
|
+
"""The folder whose entry the tool's own dialog writes when it is accepted in `path`."""
|
|
787
|
+
root = _git_root(path)
|
|
788
|
+
return _main_root(root) if root else path
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def trusts(config_dir: Path, path: Path) -> bool | None:
|
|
792
|
+
"""Whether the account folder `config_dir` trusts the canonical folder `path`; None when its
|
|
793
|
+
STATE_FILE cannot be read or decoded."""
|
|
794
|
+
try:
|
|
795
|
+
projects = _read_state(config_dir / STATE_FILE).get(STATE_PROJECTS)
|
|
796
|
+
except (OSError, UnicodeDecodeError, ValueError):
|
|
797
|
+
return None
|
|
798
|
+
if not isinstance(projects, dict):
|
|
799
|
+
return False
|
|
800
|
+
return any(isinstance(e := projects.get(str(p)), dict) and e.get(STATE_TRUST) is True
|
|
801
|
+
for p in trust_paths(path))
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def trust(config_dir: Path, path: Path, backups: Path) -> Path:
|
|
805
|
+
"""Make the account folder `config_dir` trust the canonical folder `path`, writing the entry
|
|
806
|
+
where the tool itself would (`trust_key`), and return that folder. Under the tool's lock: a
|
|
807
|
+
file that cannot be read or decoded is refused, the old one is backed up into `backups`,
|
|
808
|
+
only that key is set (every other key and value kept), the file is replaced atomically and
|
|
809
|
+
read back. A missing STATE_FILE is created holding only that entry. Raises OSError or
|
|
810
|
+
ValueError and writes nothing when it cannot."""
|
|
811
|
+
state, key = config_dir / STATE_FILE, trust_key(path)
|
|
812
|
+
with hold_state(state):
|
|
813
|
+
d = _read_state(state)
|
|
814
|
+
projects = d.get(STATE_PROJECTS, {})
|
|
815
|
+
entry = projects.get(str(key), {}) if isinstance(projects, dict) else None
|
|
816
|
+
if not isinstance(entry, dict):
|
|
817
|
+
raise ValueError(f"{state}: unexpected layout under {STATE_PROJECTS}")
|
|
818
|
+
new = {**d, STATE_PROJECTS: {**projects, str(key): {**entry, STATE_TRUST: True}}}
|
|
819
|
+
store.write_with_backup(state, json.dumps(new, indent=2, ensure_ascii=False) + "\n",
|
|
820
|
+
backups)
|
|
821
|
+
if _read_state(state) != new:
|
|
822
|
+
raise OSError(f"{state} did not read back as written")
|
|
823
|
+
return key
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def check_state(config_dir: Path) -> tuple[bool, str]:
|
|
827
|
+
"""For doctor: STATE_FILE reads, and when it holds project entries, at least one uses
|
|
828
|
+
STATE_TRUST (else the tool may have renamed the field). (ok, text without paths)."""
|
|
829
|
+
if not (config_dir / STATE_FILE).exists():
|
|
830
|
+
return True, "no state file yet"
|
|
831
|
+
try:
|
|
832
|
+
projects = _read_state(config_dir / STATE_FILE).get(STATE_PROJECTS)
|
|
833
|
+
except (OSError, UnicodeDecodeError, ValueError) as e:
|
|
834
|
+
return False, f"state file cannot be read ({type(e).__name__})"
|
|
835
|
+
if isinstance(projects, dict) and projects and not any(
|
|
836
|
+
isinstance(e, dict) and STATE_TRUST in e for e in projects.values()):
|
|
837
|
+
return False, f"trust field not found; {tool} may have renamed it"
|
|
838
|
+
return True, "state file reads" + (", trust field found" if projects else "")
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def merge_state(dest: dict, src: dict) -> tuple[dict, list[str]]:
|
|
842
|
+
"""`dest` plus what may be carried over from `src`: trust for the projects `src` trusts, the
|
|
843
|
+
user MCP servers `dest` lacks, the onboarding keys and the Claude in Chrome consent. Every other key of `dest` stays as it
|
|
844
|
+
is, and nothing else of `src` is read. Also returns what was added, for the user: counts and
|
|
845
|
+
names only, never a value."""
|
|
846
|
+
new, what = dict(dest), []
|
|
847
|
+
projects = dict(new.get(STATE_PROJECTS) or {})
|
|
848
|
+
trusted = [p for p, e in (src.get(STATE_PROJECTS) or {}).items()
|
|
849
|
+
if isinstance(e, dict) and e.get(STATE_TRUST) is True
|
|
850
|
+
and isinstance(projects.get(p, {}), dict)
|
|
851
|
+
and projects.get(p, {}).get(STATE_TRUST) is not True]
|
|
852
|
+
for p in trusted:
|
|
853
|
+
projects[p] = {**projects.get(p, {}), STATE_TRUST: True}
|
|
854
|
+
if trusted:
|
|
855
|
+
new[STATE_PROJECTS] = projects
|
|
856
|
+
what.append(f"trust for {len(trusted)} project{'s' * (len(trusted) != 1)}")
|
|
857
|
+
servers = src.get(STATE_MCP)
|
|
858
|
+
mine = new.get(STATE_MCP) if isinstance(new.get(STATE_MCP), dict) else {}
|
|
859
|
+
added = sorted(k for k in servers if k not in mine) if isinstance(servers, dict) else []
|
|
860
|
+
if added:
|
|
861
|
+
new[STATE_MCP] = {**mine, **{k: servers[k] for k in added}}
|
|
862
|
+
what.append(f"MCP servers {', '.join(added)}")
|
|
863
|
+
for label, group in (("onboarding", STATE_ONBOARDING),
|
|
864
|
+
("Claude in Chrome consent", STATE_CHROME)):
|
|
865
|
+
keys = [k for k in group if k in src and k not in new]
|
|
866
|
+
for k in keys:
|
|
867
|
+
new[k] = src[k]
|
|
868
|
+
if keys:
|
|
869
|
+
what.append(f"{label} ({', '.join(keys)})")
|
|
870
|
+
return new, what
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def masked(item: str, text: str) -> str:
|
|
874
|
+
"""A shared item's text fit to show the user in a diff: the settings file with the values of
|
|
875
|
+
the variables it sets hidden (and laid out uniformly), or a placeholder when it is not JSON.
|
|
876
|
+
Other items are shown as they are."""
|
|
877
|
+
if item != SETTINGS_FILE:
|
|
878
|
+
return text
|
|
879
|
+
try:
|
|
880
|
+
d = json.loads(text)
|
|
881
|
+
except ValueError:
|
|
882
|
+
return "(not valid JSON: not shown)\n"
|
|
883
|
+
if isinstance(d, dict) and isinstance(d.get(SETTINGS_ENV), dict):
|
|
884
|
+
d = {**d, SETTINGS_ENV: {k: "(hidden)" for k in d[SETTINGS_ENV]}}
|
|
885
|
+
return json.dumps(d, indent=2, ensure_ascii=False) + "\n"
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
# --- fairshare's skill.
|
|
889
|
+
|
|
890
|
+
def skill(shared: Path) -> tuple[Path, str]:
|
|
891
|
+
"""Where fairshare's skill goes among the hub's shared items, and its shipped text."""
|
|
892
|
+
text = (resources.files(__package__) / SKILL_SOURCE / SKILL_FILE).read_text(encoding="utf-8")
|
|
893
|
+
return shared / SKILLS_DIR / SKILL_NAME / SKILL_FILE, text
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def own_skill(text: str) -> bool:
|
|
897
|
+
"""Whether a skill file's front matter names it fairshare's."""
|
|
898
|
+
lines = text.splitlines()
|
|
899
|
+
if not lines or lines[0].strip() != SKILL_FENCE:
|
|
900
|
+
return False
|
|
901
|
+
for line in lines[1:]:
|
|
902
|
+
if line.strip() == SKILL_FENCE:
|
|
903
|
+
return False
|
|
904
|
+
key, sep, value = line.partition(":")
|
|
905
|
+
if sep and key.strip() == SKILL_NAME_KEY:
|
|
906
|
+
return value.strip().strip("\"'") == SKILL_NAME
|
|
907
|
+
return False
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
# --- The usage hook: pure text-in, text-out. One settings file serves every account.
|
|
911
|
+
|
|
912
|
+
def capture_file(shared: Path) -> Path:
|
|
913
|
+
return shared / SETTINGS_FILE
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
def capture_of(command: str) -> Capture | None:
|
|
917
|
+
"""The capture a statusLine `command` is, else None. Reads any form fairshare ever wrote: the
|
|
918
|
+
installed command by path, or an older `python -I -c '<code>'` that ran this very fairshare
|
|
919
|
+
(both are everything before the word `capture`), with or without the account id that came
|
|
920
|
+
after `capture` before the hub."""
|
|
921
|
+
try:
|
|
922
|
+
t = shlex.split(command)
|
|
923
|
+
except ValueError:
|
|
924
|
+
return None
|
|
925
|
+
i = t.index("capture") if "capture" in t else -1
|
|
926
|
+
if i < 1 or not any("fairshare" in x for x in t[:i]):
|
|
927
|
+
return None
|
|
928
|
+
rest = t[i + 1:]
|
|
929
|
+
if rest and not rest[0].startswith("-"):
|
|
930
|
+
rest = rest[1:] # an account id: the form before the hub
|
|
931
|
+
return Capture(tuple(t[:i]), rest[1] if rest[:1] == ["--then"] and len(rest) > 1 else None)
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
def wired(text: str | None) -> Capture | None:
|
|
935
|
+
try:
|
|
936
|
+
d = json.loads(text) if text and text.strip() else {}
|
|
937
|
+
return capture_of(d[STATUS_LINE_KEY][HOOK_COMMAND_KEY])
|
|
938
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
939
|
+
return None
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
def hook_of(command: str) -> tuple[tuple[str, ...], str | None] | None:
|
|
943
|
+
"""(runner, hook name) when a hook `command` is fairshare's `<runner> hook <name>`, else
|
|
944
|
+
None; recognised as `capture_of` recognises the capture."""
|
|
945
|
+
try:
|
|
946
|
+
t = shlex.split(command)
|
|
947
|
+
except ValueError:
|
|
948
|
+
return None
|
|
949
|
+
i = t.index("hook") if "hook" in t else -1
|
|
950
|
+
if i < 1 or not any("fairshare" in x for x in t[:i]):
|
|
951
|
+
return None
|
|
952
|
+
return tuple(t[:i]), t[i + 1] if len(t) > i + 1 else None
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
def _own_hooks(d: dict) -> dict[str, tuple[int, int, dict, str]]:
|
|
956
|
+
"""fairshare's hooks found in the settings object `d`: for each of its hook names, where it
|
|
957
|
+
is in its event's list (group, command) and that group and command."""
|
|
958
|
+
found = {}
|
|
959
|
+
hooks = d.get(HOOKS_KEY)
|
|
960
|
+
for name, (event, _) in FAIRSHARE_HOOKS.items():
|
|
961
|
+
groups = hooks.get(event) if isinstance(hooks, dict) else None
|
|
962
|
+
for gi, g in enumerate(groups if isinstance(groups, list) else []):
|
|
963
|
+
cmds = g.get(HOOK_LIST_KEY) if isinstance(g, dict) else None
|
|
964
|
+
for hi, h in enumerate(cmds if isinstance(cmds, list) else []):
|
|
965
|
+
cmd = h.get(HOOK_COMMAND_KEY) if isinstance(h, dict) else None
|
|
966
|
+
if (name not in found and isinstance(cmd, str) and (own := hook_of(cmd))
|
|
967
|
+
and own[1] == name):
|
|
968
|
+
found[name] = (gi, hi, g, cmd)
|
|
969
|
+
return found
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def hooked(text: str | None) -> tuple[str, ...] | None:
|
|
973
|
+
"""The fairshare command that every one of fairshare's hooks in that settings text runs, with
|
|
974
|
+
its matcher (where its event takes one); None when one is missing (or they run different
|
|
975
|
+
commands)."""
|
|
976
|
+
try:
|
|
977
|
+
d = json.loads(text) if text and text.strip() else {}
|
|
978
|
+
except ValueError:
|
|
979
|
+
return None
|
|
980
|
+
found = _own_hooks(d) if isinstance(d, dict) else {}
|
|
981
|
+
matched = [hook_of(cmd)[0] for name, (_, _, g, cmd) in found.items()
|
|
982
|
+
if FAIRSHARE_HOOKS[name][1] is None
|
|
983
|
+
or g.get(HOOK_MATCHER_KEY) == FAIRSHARE_HOOKS[name][1]]
|
|
984
|
+
runners = set(matched)
|
|
985
|
+
return runners.pop() if len(matched) == len(FAIRSHARE_HOOKS) and len(runners) == 1 else None
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def wire(text: str | None, command: str) -> str | None:
|
|
989
|
+
"""Settings text whose statusLine runs `<command> capture`, after which it runs the user's
|
|
990
|
+
own statusLine (`--then`), re-run every STATUS_REFRESH_S seconds unless it already names an
|
|
991
|
+
interval, and which holds fairshare's hooks (`<command> hook <name>` under each one's event
|
|
992
|
+
and matcher); None when it already does all that. An older capture is replaced by this one
|
|
993
|
+
and keeps the user's command it wrapped; an older hook of fairshare's is changed in place.
|
|
994
|
+
A missing hook is added at the end of its event's list: no other hook is changed, moved or
|
|
995
|
+
removed, and every byte outside what changes stays. Raises ValueError for a text that is not
|
|
996
|
+
a settings object of the expected layout."""
|
|
997
|
+
d = json.loads(text) if text and text.strip() else {}
|
|
998
|
+
if not isinstance(d, dict) or not isinstance(d.get(STATUS_LINE_KEY, {}), dict) \
|
|
999
|
+
or not isinstance(d.get(HOOKS_KEY, {}), dict) \
|
|
1000
|
+
or any(not isinstance(d.get(HOOKS_KEY, {}).get(ev, []), list)
|
|
1001
|
+
for ev, _ in FAIRSHARE_HOOKS.values()):
|
|
1002
|
+
raise ValueError("unexpected layout")
|
|
1003
|
+
sl = d.get(STATUS_LINE_KEY) or {}
|
|
1004
|
+
theirs = sl.get(HOOK_COMMAND_KEY) if isinstance(sl.get(HOOK_COMMAND_KEY), str) else None
|
|
1005
|
+
if theirs and (cap := capture_of(theirs)):
|
|
1006
|
+
theirs = cap.then
|
|
1007
|
+
cmd = f"{command} capture" + (f" --then {shlex.quote(theirs)}" if theirs else "")
|
|
1008
|
+
line = {HOOK_TYPE_KEY: HOOK_TYPE, HOOK_COMMAND_KEY: cmd}
|
|
1009
|
+
empty = not (text and text.strip())
|
|
1010
|
+
if empty:
|
|
1011
|
+
text = new = "{}"
|
|
1012
|
+
new = _json_set(new, [STATUS_LINE_KEY], {**line, STATUS_REFRESH_KEY: STATUS_REFRESH_S})
|
|
1013
|
+
elif STATUS_LINE_KEY not in d:
|
|
1014
|
+
new = _json_set(text, [STATUS_LINE_KEY], {**line, STATUS_REFRESH_KEY: STATUS_REFRESH_S})
|
|
1015
|
+
else:
|
|
1016
|
+
new = text
|
|
1017
|
+
if sl.get(HOOK_TYPE_KEY) != HOOK_TYPE:
|
|
1018
|
+
new = _json_set(new, [STATUS_LINE_KEY, HOOK_TYPE_KEY], HOOK_TYPE)
|
|
1019
|
+
if sl.get(HOOK_COMMAND_KEY) != cmd:
|
|
1020
|
+
new = _json_set(new, [STATUS_LINE_KEY, HOOK_COMMAND_KEY], cmd)
|
|
1021
|
+
if STATUS_REFRESH_KEY not in sl:
|
|
1022
|
+
new = _json_set(new, [STATUS_LINE_KEY, STATUS_REFRESH_KEY], STATUS_REFRESH_S)
|
|
1023
|
+
want = {**d, STATUS_LINE_KEY: {**sl, **line}}
|
|
1024
|
+
want[STATUS_LINE_KEY].setdefault(STATUS_REFRESH_KEY, STATUS_REFRESH_S)
|
|
1025
|
+
found = _own_hooks(json.loads(new))
|
|
1026
|
+
hooks = dict(want.get(HOOKS_KEY) or {})
|
|
1027
|
+
for name, (event, matcher) in FAIRSHARE_HOOKS.items():
|
|
1028
|
+
hook_cmd = f"{command} hook {name}"
|
|
1029
|
+
groups = list(hooks.get(event) or [])
|
|
1030
|
+
if name in found:
|
|
1031
|
+
gi, hi, g, old = found[name]
|
|
1032
|
+
if old != hook_cmd:
|
|
1033
|
+
new = _json_set(new, [HOOKS_KEY, event, gi, HOOK_LIST_KEY, hi, HOOK_COMMAND_KEY],
|
|
1034
|
+
hook_cmd)
|
|
1035
|
+
if matcher is not None and g.get(HOOK_MATCHER_KEY) != matcher:
|
|
1036
|
+
new = _json_set(new, [HOOKS_KEY, event, gi, HOOK_MATCHER_KEY], matcher)
|
|
1037
|
+
cmds = list(g[HOOK_LIST_KEY])
|
|
1038
|
+
cmds[hi] = {**cmds[hi], HOOK_COMMAND_KEY: hook_cmd}
|
|
1039
|
+
groups[gi] = {**g, **({HOOK_MATCHER_KEY: matcher} if matcher is not None else {}),
|
|
1040
|
+
HOOK_LIST_KEY: cmds}
|
|
1041
|
+
else:
|
|
1042
|
+
group = {**({HOOK_MATCHER_KEY: matcher} if matcher is not None else {}),
|
|
1043
|
+
HOOK_LIST_KEY: [{HOOK_TYPE_KEY: HOOK_TYPE, HOOK_COMMAND_KEY: hook_cmd}]}
|
|
1044
|
+
if event in hooks:
|
|
1045
|
+
new = _json_append(new, [HOOKS_KEY, event], group)
|
|
1046
|
+
else:
|
|
1047
|
+
new = _json_set(new, [HOOKS_KEY, event], [group])
|
|
1048
|
+
groups.append(group)
|
|
1049
|
+
hooks[event] = groups
|
|
1050
|
+
want[HOOKS_KEY] = hooks
|
|
1051
|
+
if empty:
|
|
1052
|
+
return json.dumps(want, indent=2) + "\n"
|
|
1053
|
+
if new == text:
|
|
1054
|
+
return None
|
|
1055
|
+
if json.loads(new) != want:
|
|
1056
|
+
raise ValueError("could not change fairshare's own entries alone")
|
|
1057
|
+
return new
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
def repath(text: str, old: str, new: str) -> tuple[str | None, list[str]]:
|
|
1061
|
+
"""Settings text in which every string value naming the folder `old` (the path itself or
|
|
1062
|
+
something inside it) names `new` instead, and where each was (key paths, never values).
|
|
1063
|
+
Keys and every other byte stay. (None, []) when nothing names it. Raises ValueError for a
|
|
1064
|
+
text it cannot change safely."""
|
|
1065
|
+
d, places = json.loads(text), []
|
|
1066
|
+
after = r"(?![\w.-])" # /x/hub matches /x/hub and /x/hub/a, not /x/hub2
|
|
1067
|
+
|
|
1068
|
+
def walk(v, where: str):
|
|
1069
|
+
if isinstance(v, str):
|
|
1070
|
+
if re.search(re.escape(old) + after, v):
|
|
1071
|
+
places.append(where)
|
|
1072
|
+
return re.sub(re.escape(old) + after, lambda m: new, v)
|
|
1073
|
+
return v
|
|
1074
|
+
if isinstance(v, dict):
|
|
1075
|
+
return {k: walk(x, f"{where}.{k}" if where else k) for k, x in v.items()}
|
|
1076
|
+
if isinstance(v, list):
|
|
1077
|
+
return [walk(x, f"{where}[{i}]") for i, x in enumerate(v)]
|
|
1078
|
+
return v
|
|
1079
|
+
want = walk(d, "")
|
|
1080
|
+
if not places:
|
|
1081
|
+
return None, []
|
|
1082
|
+
esc_old, esc_new = (json.dumps(x, ensure_ascii=False)[1:-1] for x in (old, new))
|
|
1083
|
+
out = re.sub(re.escape(esc_old) + after, lambda m: esc_new, text)
|
|
1084
|
+
if json.loads(out) != want:
|
|
1085
|
+
raise ValueError("the old path is not only in string values")
|
|
1086
|
+
return out, places
|
|
1087
|
+
|
|
1088
|
+
|
|
1089
|
+
_WS = re.compile(r"\s*")
|
|
1090
|
+
_DECODER = json.JSONDecoder()
|
|
1091
|
+
|
|
1092
|
+
|
|
1093
|
+
def _members(text: str, start: int) -> list[tuple[str, int, int, int]]:
|
|
1094
|
+
"""(key, key start, value start, value end) of each member of the JSON object at `start`."""
|
|
1095
|
+
if text[start:start + 1] != "{":
|
|
1096
|
+
raise ValueError("not an object")
|
|
1097
|
+
out, i = [], _WS.match(text, start + 1).end()
|
|
1098
|
+
if text[i:i + 1] == "}":
|
|
1099
|
+
return out
|
|
1100
|
+
while True:
|
|
1101
|
+
k0 = i
|
|
1102
|
+
if text[i:i + 1] != '"':
|
|
1103
|
+
raise ValueError("bad object")
|
|
1104
|
+
key, i = json.decoder.scanstring(text, i + 1)
|
|
1105
|
+
i = _WS.match(text, i).end()
|
|
1106
|
+
if text[i:i + 1] != ":":
|
|
1107
|
+
raise ValueError("bad object")
|
|
1108
|
+
v0 = _WS.match(text, i + 1).end()
|
|
1109
|
+
_, v1 = _DECODER.raw_decode(text, v0)
|
|
1110
|
+
out.append((key, k0, v0, v1))
|
|
1111
|
+
i = _WS.match(text, v1).end()
|
|
1112
|
+
if text[i:i + 1] == "}":
|
|
1113
|
+
return out
|
|
1114
|
+
if text[i:i + 1] != ",":
|
|
1115
|
+
raise ValueError("bad object")
|
|
1116
|
+
i = _WS.match(text, i + 1).end()
|
|
1117
|
+
|
|
1118
|
+
|
|
1119
|
+
def _elements(text: str, start: int) -> list[tuple[int, int]]:
|
|
1120
|
+
"""(value start, value end) of each element of the JSON array at `start`."""
|
|
1121
|
+
if text[start:start + 1] != "[":
|
|
1122
|
+
raise ValueError("not an array")
|
|
1123
|
+
out, i = [], _WS.match(text, start + 1).end()
|
|
1124
|
+
if text[i:i + 1] == "]":
|
|
1125
|
+
return out
|
|
1126
|
+
while True:
|
|
1127
|
+
_, end = _DECODER.raw_decode(text, i)
|
|
1128
|
+
out.append((i, end))
|
|
1129
|
+
i = _WS.match(text, end).end()
|
|
1130
|
+
if text[i:i + 1] == "]":
|
|
1131
|
+
return out
|
|
1132
|
+
if text[i:i + 1] != ",":
|
|
1133
|
+
raise ValueError("bad array")
|
|
1134
|
+
i = _WS.match(text, i + 1).end()
|
|
1135
|
+
|
|
1136
|
+
|
|
1137
|
+
def _json_set(text: str, keys: list, value) -> str:
|
|
1138
|
+
"""`text` with the value at `keys` (member names, or indexes of array elements that exist)
|
|
1139
|
+
replaced, or added as the last member of the innermost object that exists, laid out like its
|
|
1140
|
+
first member; every other byte stays."""
|
|
1141
|
+
start = _WS.match(text).end()
|
|
1142
|
+
for depth, key in enumerate(keys):
|
|
1143
|
+
if isinstance(key, int):
|
|
1144
|
+
v0, v1 = _elements(text, start)[key]
|
|
1145
|
+
else:
|
|
1146
|
+
members = _members(text, start)
|
|
1147
|
+
hit = [m for m in members if m[0] == key]
|
|
1148
|
+
if not hit:
|
|
1149
|
+
for k in reversed(keys[depth + 1:]):
|
|
1150
|
+
value = {k: value}
|
|
1151
|
+
member = f"{json.dumps(key)}: {json.dumps(value, ensure_ascii=False)}"
|
|
1152
|
+
if not members:
|
|
1153
|
+
return text[:start + 1] + member + text[start + 1:]
|
|
1154
|
+
lead = text[start + 1:members[0][1]] or " "
|
|
1155
|
+
return text[:members[-1][3]] + "," + lead + member + text[members[-1][3]:]
|
|
1156
|
+
_, _, v0, v1 = hit[-1] # the last of duplicate keys is the one read
|
|
1157
|
+
if depth == len(keys) - 1:
|
|
1158
|
+
return text[:v0] + json.dumps(value, ensure_ascii=False) + text[v1:]
|
|
1159
|
+
start = v0
|
|
1160
|
+
return text
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
def _json_append(text: str, keys: list, value) -> str:
|
|
1164
|
+
"""`text` with `value` added as the last element of the array at `keys` (which exists), laid
|
|
1165
|
+
out like its first element; every other byte stays."""
|
|
1166
|
+
start = _WS.match(text).end()
|
|
1167
|
+
for key in keys:
|
|
1168
|
+
if isinstance(key, int):
|
|
1169
|
+
start = _elements(text, start)[key][0]
|
|
1170
|
+
else:
|
|
1171
|
+
start = [m for m in _members(text, start) if m[0] == key][-1][2]
|
|
1172
|
+
items, item = _elements(text, start), json.dumps(value, ensure_ascii=False)
|
|
1173
|
+
if not items:
|
|
1174
|
+
return text[:start + 1] + item + text[start + 1:]
|
|
1175
|
+
lead = text[start + 1:items[0][0]]
|
|
1176
|
+
return text[:items[-1][1]] + "," + lead + item + text[items[-1][1]:]
|