spendbyteam 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SpendByTeam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,177 @@
1
- # Temporary Holding Version
1
+ # spendbyteam
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ See what [Claude Code](https://code.claude.com) costs, per project, model, branch or day. Then share it with your team on **SpendByTeam**.
4
+
5
+ ## See your own spend (no account needed)
6
+
7
+ ```bash
8
+ npx spendbyteam report
9
+ ```
10
+
11
+ ```
12
+ Claude Code spend on this machine 2026-10-20 → 2026-11-18
13
+ At API list prices. On a Pro, Max or Team seat you pay a flat fee; this is what the same tokens cost on the API.
14
+
15
+ Project Cost Share Sessions Tokens Top model
16
+ checkout-api $412.80 38% 41 980.2M opus-5-5
17
+ web $301.15 28% 33 702.6M opus-5-5
18
+ infra $118.40 11% 9 250.1M sonnet-5-5
19
+ …
20
+ Total $1,086.20 112 2.4B
21
+ ```
22
+
23
+ `report` reads the session logs Claude Code already keeps on your machine (`~/.claude/projects`, or `$CLAUDE_CONFIG_DIR`). It works offline and **sends nothing anywhere**. Costs use Anthropic's API list prices, including cache reads, 5-minute and 1-hour cache writes, and fast mode.
24
+
25
+ | Option | |
26
+ |---|---|
27
+ | `--days=N` | Last N days, including today (default 30) |
28
+ | `--all` | Everything in the logs |
29
+ | `--by=project\|model\|branch\|day` | How to group (default `project`; sub-folders of a git repo count as one project) |
30
+ | `--json` | Machine-readable output |
31
+
32
+ ## Track it for the whole team
33
+
34
+ ```bash
35
+ npx spendbyteam connect
36
+ ```
37
+
38
+ `connect` prints a short code and opens your browser. Sign up (free for 3 developers) or log in, check the code matches, and click **Connect**. The panel issues an ingest token for this machine and the CLI installs it, so there is nothing to copy. Before you approve, the only thing sent is this machine's name, so the page can show which machine is asking. Use `--no-browser` on a server or over SSH.
39
+
40
+ Already have a token, or setting up many machines? Use `init` directly:
41
+
42
+ ```bash
43
+ npx spendbyteam init --token=sbt_ing_xxxxxxxx
44
+ ```
45
+
46
+ This package is open source (MIT) so you can check exactly what leaves your machine. The short version: **numbers only.** No prompts, no code, no file contents, no file paths.
47
+
48
+ ---
49
+
50
+ ## What gets sent
51
+
52
+ There are only two data flows. Both use your write-only ingest token (`sbt_ing_...`). It can send data but cannot read anything back.
53
+
54
+ ### 1. Claude Code OpenTelemetry metrics (sent by Claude Code itself)
55
+
56
+ `init` turns on Claude Code's built-in telemetry, **metrics only**:
57
+
58
+ | Setting | Value | Why |
59
+ |---|---|---|
60
+ | `CLAUDE_CODE_ENABLE_TELEMETRY` | `1` | turn telemetry on |
61
+ | `OTEL_METRICS_EXPORTER` | `otlp` | send metrics |
62
+ | `OTEL_LOGS_EXPORTER` | `none` | **no log events** (these can carry prompts and tool details) |
63
+ | `OTEL_TRACES_EXPORTER` | `none` | **no traces** |
64
+ | `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/json` | |
65
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | `https://ingest.spendbyteam.com` | |
66
+ | `OTEL_EXPORTER_OTLP_HEADERS` | `Authorization=Bearer sbt_ing_...` | your ingest token |
67
+ | `OTEL_METRICS_INCLUDE_SESSION_ID` | `true` | group metrics per session |
68
+ | `OTEL_METRICS_INCLUDE_REPOSITORY` | `true` | map cost to a project (Claude Code ≥ 2.1.269) |
69
+ | `OTEL_METRICS_INCLUDE_VERSION` | `true` | Claude Code version |
70
+ | `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | once a minute |
71
+ | `OTEL_RESOURCE_ATTRIBUTES` | `team.id=<id>` | only if you pass `--team-id` |
72
+
73
+ The content flags `OTEL_LOG_USER_PROMPTS`, `OTEL_LOG_TOOL_DETAILS` and `OTEL_LOG_RAW_API_BODIES` are **never set**. They stay off (the default).
74
+
75
+ Claude Code then sends counters such as `claude_code.cost.usage`, `claude_code.token.usage`, `claude_code.session.count`, `claude_code.lines_of_code.count`, `claude_code.commit.count`, `claude_code.pull_request.count`, `claude_code.code_edit_tool.decision` and `claude_code.active_time.total`. Each one comes with attributes like `session.id`, `user.email`, `organization.id`, `model`, `type` and `vcs.repository.url.full`.
76
+
77
+ The server keeps only an allowlist of attributes and drops everything else:
78
+ `session.id, user.email, user.account_uuid, organization.id, model, type, query_source, agent.name, skill.name, decision, start_type, vcs.repository.url.full, vcs.repository.name, vcs.owner.name, vcs.provider.name, team.id, app.version, terminal.type`.
79
+ `/v1/logs` and `/v1/traces` accept requests and throw them away unread, even if some other setting turns those exporters on.
80
+
81
+ ### 2. The context hook (`~/.spendbyteam/hook.sh`)
82
+
83
+ OTel metrics don't include your git branch, so a small hook runs on the `SessionStart` and `CwdChanged` events (async, so it never slows Claude Code down). It sends **one** request to `POST {endpoint}/v1/context`. This is the complete body:
84
+
85
+ ```json
86
+ {
87
+ "session_id": "6f1c1f1e-3a51-4c2e-9d4c-5f0e2b7d8a90",
88
+ "event": "SessionStart",
89
+ "repo_url": "https://github.com/acme/web.git",
90
+ "branch": "feature/ABC-123-login",
91
+ "ticket": "ABC-123",
92
+ "at": "2026-11-03T09:14:05Z"
93
+ }
94
+ ```
95
+
96
+ | Field | Source |
97
+ |---|---|
98
+ | `session_id` | from Claude Code's hook input |
99
+ | `event` | `SessionStart` or `CwdChanged` |
100
+ | `repo_url` | `git config --get remote.origin.url`, with embedded credentials, query and fragment removed (`https://user:token@host/...` → `https://host/...`). Local-path and `file://` remotes are never sent (empty string). |
101
+ | `branch` | `git rev-parse --abbrev-ref HEAD`; empty in a repo without commits or on a detached HEAD |
102
+ | `ticket` | first `ABC-123` style match in the branch name, otherwise empty |
103
+ | `at` | current UTC time |
104
+
105
+ The hook **never** sends the working directory path (`cwd`), your username or home directory, the transcript path, or any file contents. Outside a git repo, `repo_url`, `branch` and `ticket` are empty strings.
106
+
107
+ The hook always exits `0`. If something is missing or broken (no config, no `jq`, no network, not a git repo), it does nothing and can never break a Claude Code session. Read it yourself: [`hook/hook.sh`](hook/hook.sh) is about 35 lines. The token is passed to `curl` through a file descriptor, never on its command line, and nothing is sent unless the endpoint is `https://` (plain `http://` only for localhost).
108
+
109
+ ---
110
+
111
+ ## Commands
112
+
113
+ ```bash
114
+ npx spendbyteam init --token=sbt_ing_... [--endpoint=URL] [--team-id=ID] [--no-ping]
115
+ npx spendbyteam status
116
+ npx spendbyteam doctor [--no-ping]
117
+ npx spendbyteam uninstall
118
+ npx spendbyteam print-managed --token=sbt_ing_... [--endpoint=URL] [--team-id=ID]
119
+ ```
120
+
121
+ ### `init`
122
+
123
+ 1. Runs `claude --version` and warns if it is older than **2.1.269**. Older versions don't send repository attributes, so project mapping falls back to the hook. It also warns if `claude` isn't installed. Neither stops the install.
124
+ 2. Warns if `jq`, `git` or `curl` is missing. The hook needs them; the cost metrics don't.
125
+ 3. **Merges** the env block and the two hooks into `~/.claude/settings.json`:
126
+ - copies the current file to `~/.claude/settings.json.bak` before it writes anything
127
+ - keeps every other setting, env var and hook as it was
128
+ - is idempotent: running it again changes nothing, and running it with a new token or endpoint updates the existing entries in place (no duplicate hooks)
129
+ - stops without writing anything if `settings.json` is not valid JSON
130
+ - restricts the file to the owner (`go-rwx`), because it now contains the ingest token
131
+ 4. Writes `~/.spendbyteam/config.json` as `{ "token": "...", "endpoint": "..." }` with mode **600** (directory 700). The hook reads it because Claude Code doesn't pass `OTEL_*` variables to hooks.
132
+ 5. Writes `~/.spendbyteam/state.json` (mode 600): the values your env keys had before the install, so `uninstall` can put them back.
133
+ 6. Copies the hook to `~/.spendbyteam/hook.sh` (mode 755).
134
+ 7. Sends `GET {endpoint}/v1/ping` with the token so the panel shows the machine as connected. Skip this with `--no-ping`.
135
+
136
+ Restart running Claude Code sessions afterwards.
137
+
138
+ ### `uninstall`
139
+
140
+ Removes the two hook entries, restores env keys to their pre-install values (deleting keys that didn't exist before) and deletes `~/.spendbyteam/`. If you changed one of those keys yourself after installing, your value is kept. Before writing, it saves a backup to `~/.claude/settings.json.bak`. That backup still contains the ingest token; delete it if you don't need it.
141
+
142
+ ### `status` / `doctor`
143
+
144
+ `status` shows what is installed and exits `1` if anything is missing. `doctor` also checks `jq`/`git`/`curl`, the Claude Code version, the config file's permissions and whether the hook is executable, and pings the endpoint. It exits `1` if any check fails.
145
+
146
+ ### `print-managed` (Team / Enterprise)
147
+
148
+ Prints [managed settings](https://code.claude.com/docs/en/settings) JSON with the same `env` block, so an admin can roll it out to everyone at once:
149
+
150
+ ```bash
151
+ npx spendbyteam print-managed --token=sbt_ing_... > managed-settings.json
152
+ ```
153
+
154
+ Put the file at `/Library/Application Support/ClaudeCode/managed-settings.json` (macOS) or `/etc/claude-code/managed-settings.json` (Linux/WSL), or paste it into server-managed settings (this also covers claude.ai/code cloud sessions). When the endpoint and headers come from managed settings, Claude Code ignores endpoints set by individual developers. The hook needs a script on each machine, so it isn't included here; developers who want branch/ticket attribution also run `npx spendbyteam init`.
155
+
156
+ ---
157
+
158
+ ## Requirements
159
+
160
+ - Node.js ≥ 18.17 (only for running the CLI; nothing stays running)
161
+ - macOS, Linux or WSL
162
+ - Claude Code ≥ 2.1.269 recommended
163
+ - `jq`, `git`, `curl` for the context hook
164
+
165
+ ## Development
166
+
167
+ ```bash
168
+ npm install
169
+ npm test # vitest unit tests (temporary HOME) + shell tests for hook.sh
170
+ npm run build # → dist/
171
+ ```
172
+
173
+ The unit tests run every command against a throwaway `HOME` and a fake `PATH`, so they never touch your real `~/.claude`. `test/hook.test.sh` runs the real `hook.sh` with a fake `curl` and checks the exact payload: no `cwd`, credentials removed from the remote, exit 0 on any failure.
174
+
175
+ ## License
176
+
177
+ [MIT](LICENSE)
package/dist/checks.js ADDED
@@ -0,0 +1,81 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { HOOK_DEPS, MIN_CLAUDE_VERSION } from './constants.js';
5
+ /** Look a binary up on PATH without spawning a shell. */
6
+ export function which(name, envPath = process.env.PATH ?? '') {
7
+ for (const dir of envPath.split(path.delimiter)) {
8
+ if (!dir)
9
+ continue;
10
+ const candidate = path.join(dir, name);
11
+ try {
12
+ fs.accessSync(candidate, fs.constants.X_OK);
13
+ if (fs.statSync(candidate).isFile())
14
+ return candidate;
15
+ }
16
+ catch {
17
+ /* not here */
18
+ }
19
+ }
20
+ return undefined;
21
+ }
22
+ export function missingDeps(envPath) {
23
+ return HOOK_DEPS.filter((d) => !which(d, envPath));
24
+ }
25
+ export function parseVersion(text) {
26
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(text);
27
+ if (!m)
28
+ return undefined;
29
+ return [Number(m[1]), Number(m[2]), Number(m[3])];
30
+ }
31
+ export function compareVersions(a, b) {
32
+ for (let i = 0; i < 3; i++) {
33
+ const d = a[i] - b[i];
34
+ if (d !== 0)
35
+ return d < 0 ? -1 : 1;
36
+ }
37
+ return 0;
38
+ }
39
+ export function checkClaudeVersion() {
40
+ const bin = which('claude');
41
+ if (!bin)
42
+ return { status: 'missing' };
43
+ const res = spawnSync(bin, ['--version'], { encoding: 'utf8', timeout: 10_000 });
44
+ const out = `${res.stdout ?? ''}${res.stderr ?? ''}`.trim();
45
+ const v = parseVersion(out);
46
+ if (!v)
47
+ return { status: 'unknown', output: out };
48
+ const version = v.join('.');
49
+ const min = parseVersion(MIN_CLAUDE_VERSION);
50
+ return compareVersions(v, min) >= 0 ? { status: 'ok', version } : { status: 'old', version };
51
+ }
52
+ export function describeClaudeVersion(c) {
53
+ switch (c.status) {
54
+ case 'ok':
55
+ return `Claude Code ${c.version} (>= ${MIN_CLAUDE_VERSION})`;
56
+ case 'old':
57
+ return `Claude Code ${c.version} is older than ${MIN_CLAUDE_VERSION}: repository attributes (vcs.*) will not be sent; projects fall back to hook context. Update with "claude update".`;
58
+ case 'missing':
59
+ return `"claude" was not found on PATH. Settings are written anyway; install Claude Code >= ${MIN_CLAUDE_VERSION}.`;
60
+ case 'unknown':
61
+ return `Could not read the Claude Code version (got: ${c.output || 'no output'}). Make sure it is >= ${MIN_CLAUDE_VERSION}.`;
62
+ }
63
+ }
64
+ /** GET {endpoint}/v1/ping with the ingest token (TECHNICAL.md §5). */
65
+ export async function ping(endpoint, token, timeoutMs = 5000) {
66
+ try {
67
+ const res = await fetch(`${endpoint}/v1/ping`, {
68
+ method: 'GET',
69
+ headers: { Authorization: `Bearer ${token}`, 'User-Agent': 'spendbyteam-cli' },
70
+ signal: AbortSignal.timeout(timeoutMs),
71
+ });
72
+ if (res.ok)
73
+ return { ok: true, status: res.status };
74
+ if (res.status === 401 || res.status === 403)
75
+ return { ok: false, error: `token rejected (HTTP ${res.status})` };
76
+ return { ok: false, error: `HTTP ${res.status}` };
77
+ }
78
+ catch (err) {
79
+ return { ok: false, error: err.message };
80
+ }
81
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { createRequire } from 'node:module';
4
+ import { init } from './init.js';
5
+ import { uninstall } from './uninstall.js';
6
+ import { status } from './status.js';
7
+ import { doctor } from './doctor.js';
8
+ import { managedSettingsJson } from './managed.js';
9
+ import { report, GROUPS } from './report.js';
10
+ import { connect } from './connect.js';
11
+ import { UsageError } from './env.js';
12
+ import { JsonFileError } from './fsutil.js';
13
+ import { consoleLogger } from './log.js';
14
+ const HELP = `spendbyteam — see and share what Claude Code costs (metrics only, no prompts or code)
15
+
16
+ Usage:
17
+ npx spendbyteam report [--days=30 | --all] [--by=project|model|branch|day] [--json]
18
+ npx spendbyteam connect [--team-id=ID] [--no-browser]
19
+ npx spendbyteam init --token=sbt_ing_... [--endpoint=URL] [--team-id=ID] [--no-ping]
20
+ npx spendbyteam uninstall
21
+ npx spendbyteam status
22
+ npx spendbyteam doctor [--no-ping]
23
+ npx spendbyteam print-managed --token=sbt_ing_... [--endpoint=URL] [--team-id=ID]
24
+
25
+ Commands:
26
+ report What Claude Code cost on this machine, per project, model, branch or day, at API list
27
+ prices. Reads the local session logs only: works offline, no account or token needed.
28
+ connect Sign up or log in in the browser, approve this machine, and set it up: no token to copy.
29
+ init Merge the OTel env + context hook into ~/.claude/settings.json (backup: settings.json.bak),
30
+ write ~/.spendbyteam/config.json (mode 600) and ~/.spendbyteam/hook.sh. Safe to re-run.
31
+ uninstall Undo everything init did (restores env values that existed before).
32
+ status Show what is installed.
33
+ doctor Check jq/git/curl, Claude Code version, settings, permissions and connectivity.
34
+ print-managed Print managed-settings JSON for Team/Enterprise admins (stdout).
35
+
36
+ Options:
37
+ --token Ingest token from the SpendByTeam panel (write-only).
38
+ --endpoint Ingest endpoint (default https://ingest.spendbyteam.com).
39
+ --team-id Optional static team id, sent as OTEL_RESOURCE_ATTRIBUTES=team.id=<id>.
40
+ --no-ping Skip the GET /v1/ping connectivity test.
41
+ --days report: how many days back to look, including today (default 30).
42
+ --all report: everything in the logs.
43
+ --by report: group by project (default), model, branch or day.
44
+ --json report: print JSON instead of a table.
45
+ --no-browser connect: print the approval link instead of opening a browser.
46
+ --app-url connect: panel URL (default https://app.spendbyteam.com).
47
+ -h, --help Show this help.
48
+ -v, --version Show version.
49
+ `;
50
+ function version() {
51
+ const require = createRequire(import.meta.url);
52
+ return require('../package.json').version;
53
+ }
54
+ export async function main(argv) {
55
+ const { values, positionals } = parseArgs({
56
+ args: argv,
57
+ allowPositionals: true,
58
+ strict: true,
59
+ options: {
60
+ token: { type: 'string' },
61
+ endpoint: { type: 'string' },
62
+ 'team-id': { type: 'string' },
63
+ 'no-ping': { type: 'boolean', default: false },
64
+ days: { type: 'string' },
65
+ all: { type: 'boolean', default: false },
66
+ by: { type: 'string' },
67
+ json: { type: 'boolean', default: false },
68
+ 'no-browser': { type: 'boolean', default: false },
69
+ 'app-url': { type: 'string' },
70
+ help: { type: 'boolean', short: 'h', default: false },
71
+ version: { type: 'boolean', short: 'v', default: false },
72
+ },
73
+ });
74
+ if (values.version) {
75
+ console.log(version());
76
+ return 0;
77
+ }
78
+ const cmd = positionals[0];
79
+ if (values.help || !cmd || cmd === 'help') {
80
+ console.log(HELP);
81
+ return cmd || values.help ? 0 : 1;
82
+ }
83
+ if (positionals.length > 1)
84
+ throw new UsageError(`Unexpected argument: ${positionals[1]}`);
85
+ const envOpts = { token: values.token ?? '', endpoint: values.endpoint, teamId: values['team-id'] };
86
+ switch (cmd) {
87
+ case 'report': {
88
+ const days = values.days === undefined ? undefined : Number(values.days);
89
+ if (values.by !== undefined && !GROUPS.includes(values.by)) {
90
+ throw new UsageError(`--by must be one of: ${GROUPS.join(', ')}.`);
91
+ }
92
+ await report({ days, all: values.all, by: values.by, json: values.json });
93
+ return 0;
94
+ }
95
+ case 'connect':
96
+ await connect({ appUrl: values['app-url'], teamId: values['team-id'], open: !values['no-browser'], ping: !values['no-ping'] });
97
+ return 0;
98
+ case 'init':
99
+ await init({ ...envOpts, ping: !values['no-ping'] });
100
+ return 0;
101
+ case 'uninstall':
102
+ uninstall();
103
+ return 0;
104
+ case 'status':
105
+ return status().installed ? 0 : 1;
106
+ case 'doctor':
107
+ return (await doctor({ ping: !values['no-ping'] })) ? 0 : 1;
108
+ case 'print-managed':
109
+ process.stdout.write(managedSettingsJson(envOpts));
110
+ console.error('# Put this in managed-settings.json (macOS: /Library/Application Support/ClaudeCode/, Linux/WSL: /etc/claude-code/)\n' +
111
+ '# or in server-managed settings. Developers still run `npx spendbyteam init` for the branch/ticket hook.');
112
+ return 0;
113
+ default:
114
+ throw new UsageError(`Unknown command "${cmd}". Run "npx spendbyteam --help".`);
115
+ }
116
+ }
117
+ main(process.argv.slice(2)).then((code) => {
118
+ process.exitCode = code;
119
+ }, (err) => {
120
+ if (err instanceof UsageError || err instanceof JsonFileError || err.code?.startsWith('ERR_PARSE_ARGS')) {
121
+ consoleLogger.error(err.message);
122
+ process.exitCode = 2;
123
+ }
124
+ else {
125
+ consoleLogger.error(`Unexpected error: ${err.stack ?? String(err)}`);
126
+ process.exitCode = 1;
127
+ }
128
+ });
@@ -0,0 +1,124 @@
1
+ import os from 'node:os';
2
+ import { spawn } from 'node:child_process';
3
+ import { init } from './init.js';
4
+ import { UsageError } from './env.js';
5
+ import { consoleLogger } from './log.js';
6
+ /**
7
+ * `spendbyteam connect`: set up this machine without copying a token.
8
+ *
9
+ * Device-authorization flow: ask the panel for a code, open the browser where the person signs
10
+ * up or logs in and approves that code, then poll until the panel hands over an ingest token,
11
+ * and run `init` with it. The only thing sent before approval is this machine's hostname, so the
12
+ * approval page can say which machine is asking.
13
+ */
14
+ export const DEFAULT_APP_URL = 'https://app.spendbyteam.com';
15
+ export function normalizeAppUrl(raw) {
16
+ const value = (raw ?? process.env.SPENDBYTEAM_APP_URL ?? DEFAULT_APP_URL).trim();
17
+ let url;
18
+ try {
19
+ url = new URL(value);
20
+ }
21
+ catch {
22
+ throw new UsageError(`Invalid --app-url: ${value}`);
23
+ }
24
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
25
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
26
+ throw new UsageError('--app-url must use https:// (http:// is only allowed for localhost).');
27
+ }
28
+ return url.origin;
29
+ }
30
+ /** A name the approval page can show. macOS sometimes reports a LAN IP as the hostname: say "Mac" instead. */
31
+ export function machineLabel(hostname = os.hostname(), platform = process.platform) {
32
+ const name = hostname.replace(/\.local$/i, '').trim();
33
+ if (!name || /^\d{1,3}(\.\d{1,3}){3}$/.test(name) || name.includes(':')) {
34
+ return platform === 'darwin' ? 'Mac' : platform === 'win32' ? 'Windows PC' : platform === 'linux' ? 'Linux machine' : 'machine';
35
+ }
36
+ return name.slice(0, 64);
37
+ }
38
+ export function openInBrowser(url) {
39
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
40
+ try {
41
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
42
+ child.on('error', () => { });
43
+ child.unref();
44
+ }
45
+ catch {
46
+ // No browser here (SSH, container): the URL is printed anyway.
47
+ }
48
+ }
49
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
50
+ async function postJson(fetchImpl, url, body) {
51
+ const res = await fetchImpl(url, {
52
+ method: 'POST',
53
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
54
+ body: JSON.stringify(body),
55
+ signal: AbortSignal.timeout(15_000),
56
+ });
57
+ let data = null;
58
+ try {
59
+ data = await res.json();
60
+ }
61
+ catch {
62
+ // Non-JSON error page: status code says enough.
63
+ }
64
+ return { status: res.status, data };
65
+ }
66
+ export async function connect(opts = {}) {
67
+ const log = opts.logger ?? consoleLogger;
68
+ const fetchImpl = opts.fetchImpl ?? fetch;
69
+ const sleep = opts.sleep ?? wait;
70
+ const appUrl = normalizeAppUrl(opts.appUrl);
71
+ let start;
72
+ try {
73
+ start = await postJson(fetchImpl, `${appUrl}/cli/connect/start`, { client_name: machineLabel() });
74
+ }
75
+ catch (err) {
76
+ throw new UsageError(`Could not reach ${appUrl} (${err.message}). Check your connection and try again.`);
77
+ }
78
+ if (start.status !== 200 || !start.data?.device_code) {
79
+ throw new UsageError(start.status === 429 ? 'Too many attempts. Wait a minute and try again.' : `${appUrl} answered ${start.status}. Try again in a moment.`);
80
+ }
81
+ const s = start.data;
82
+ log.info('');
83
+ log.info(` Your code: ${s.user_code}`);
84
+ log.info('');
85
+ log.info(`Approve it in your browser (sign up free if you have no account):`);
86
+ log.info(` ${s.verification_uri_complete}`);
87
+ if (opts.open !== false)
88
+ (opts.openBrowser ?? openInBrowser)(s.verification_uri_complete);
89
+ log.info('');
90
+ log.info('Waiting for approval… (Ctrl+C to stop)');
91
+ let interval = Math.max(1, s.interval) * 1000;
92
+ const deadline = Date.now() + s.expires_in * 1000;
93
+ let failures = 0;
94
+ while (Date.now() < deadline) {
95
+ await sleep(interval);
96
+ let poll;
97
+ try {
98
+ poll = await postJson(fetchImpl, `${appUrl}/cli/connect/poll`, { device_code: s.device_code });
99
+ failures = 0;
100
+ }
101
+ catch {
102
+ if (++failures >= 5)
103
+ throw new UsageError(`Lost the connection to ${appUrl}. Run \`npx spendbyteam connect\` again.`);
104
+ continue;
105
+ }
106
+ if (poll.status === 429) {
107
+ interval += 2000;
108
+ continue;
109
+ }
110
+ if (poll.status === 200 && poll.data?.status === 'approved' && typeof poll.data.token === 'string') {
111
+ log.ok('Approved. Setting up Claude Code on this machine…');
112
+ const result = await init({ token: poll.data.token, endpoint: poll.data.endpoint, teamId: opts.teamId, ping: opts.ping, logger: log });
113
+ log.info('');
114
+ log.ok('Connected. New Claude Code sessions here now show up in your SpendByTeam workspace.');
115
+ return result;
116
+ }
117
+ if (poll.status === 410) {
118
+ throw new UsageError(poll.data?.status === 'denied'
119
+ ? 'The connection was cancelled in the browser. Nothing was changed on this machine.'
120
+ : 'The code expired. Run `npx spendbyteam connect` again.');
121
+ }
122
+ }
123
+ throw new UsageError('The code expired before it was approved. Run `npx spendbyteam connect` again.');
124
+ }
@@ -0,0 +1,11 @@
1
+ export const DEFAULT_ENDPOINT = 'https://ingest.spendbyteam.com';
2
+ export const MIN_CLAUDE_VERSION = '2.1.269';
3
+ /** Command written into ~/.claude/settings.json (TECHNICAL.md §4.1). */
4
+ export const HOOK_COMMAND = '~/.spendbyteam/hook.sh';
5
+ export const HOOK_EVENTS = ['SessionStart', 'CwdChanged'];
6
+ export const HOOK_TIMEOUT_SECONDS = 10;
7
+ /** Any hook command pointing at our script counts as "ours" (also absolute-path variants). */
8
+ export const HOOK_COMMAND_RE = /(^|\/)\.spendbyteam\/hook\.sh$/;
9
+ export const TOKEN_RE = /^sbt_ing_[A-Za-z0-9_-]{8,}$/;
10
+ /** Dependencies the hook script needs at runtime. */
11
+ export const HOOK_DEPS = ['jq', 'git', 'curl'];
package/dist/doctor.js ADDED
@@ -0,0 +1,71 @@
1
+ import { HOOK_DEPS } from './constants.js';
2
+ import { checkClaudeVersion, describeClaudeVersion, missingDeps, ping } from './checks.js';
3
+ import { collectStatus } from './status.js';
4
+ import { paths } from './paths.js';
5
+ import { consoleLogger } from './log.js';
6
+ export async function runDoctor(opts = {}) {
7
+ const p = paths();
8
+ const checks = [];
9
+ const add = (level, name, detail) => checks.push({ level, name, detail });
10
+ const missing = missingDeps();
11
+ for (const dep of HOOK_DEPS) {
12
+ if (missing.includes(dep))
13
+ add('warn', dep, `${dep} not found on PATH: the context hook (branch/ticket) will not send anything`);
14
+ else
15
+ add('ok', dep, `${dep} found`);
16
+ }
17
+ const claude = checkClaudeVersion();
18
+ add(claude.status === 'ok' ? 'ok' : 'warn', 'claude', describeClaudeVersion(claude));
19
+ const s = collectStatus();
20
+ if (!s.config)
21
+ add('fail', 'config', `${p.config} missing or invalid (run init)`);
22
+ else
23
+ add('ok', 'config', `${p.config}`);
24
+ if (s.configMode !== undefined) {
25
+ if (s.configMode === 0o600)
26
+ add('ok', 'config mode', '600');
27
+ else
28
+ add('fail', 'config mode', `${s.configMode.toString(8)} (expected 600; fix: chmod 600 ${p.config})`);
29
+ }
30
+ if (s.settingsError)
31
+ add('fail', 'settings', s.settingsError);
32
+ else if (s.inspection) {
33
+ if (s.inspection.envMatches)
34
+ add('ok', 'settings env', 'OTel env present and matches config');
35
+ else
36
+ add('fail', 'settings env', `missing or changed: ${s.inspection.mismatchedKeys.join(', ') || 'no config to compare'}`);
37
+ for (const [event, ok] of Object.entries(s.inspection.hookEvents)) {
38
+ add(ok ? 'ok' : 'fail', `${event} hook`, ok ? 'registered' : 'not registered in settings.json');
39
+ }
40
+ }
41
+ if (!s.hookInstalled)
42
+ add('fail', 'hook.sh', `${p.hook} missing`);
43
+ else if (!s.hookExecutable)
44
+ add('fail', 'hook.sh', `${p.hook} not executable (fix: chmod +x ${p.hook})`);
45
+ else
46
+ add('ok', 'hook.sh', p.hook);
47
+ if (opts.ping !== false && s.config) {
48
+ const r = await ping(s.config.endpoint, s.config.token);
49
+ if (r.ok)
50
+ add('ok', 'ingest', `${s.config.endpoint}/v1/ping reachable`);
51
+ else
52
+ add('fail', 'ingest', `${s.config.endpoint}/v1/ping: ${r.error}`);
53
+ }
54
+ return checks;
55
+ }
56
+ export async function doctor(opts = {}) {
57
+ const log = opts.logger ?? consoleLogger;
58
+ const checks = await runDoctor(opts);
59
+ for (const c of checks) {
60
+ const line = `${c.name}: ${c.detail}`;
61
+ if (c.level === 'ok')
62
+ log.ok(line);
63
+ else if (c.level === 'warn')
64
+ log.warn(line);
65
+ else
66
+ log.error(line);
67
+ }
68
+ const failed = checks.filter((c) => c.level === 'fail').length;
69
+ log.info(failed === 0 ? 'No problems found.' : `${failed} problem(s) found.`);
70
+ return failed === 0;
71
+ }