tokenmaxxing 0.17.0 → 0.19.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/DESIGN.md +17 -2
- package/README.md +1 -0
- package/package.json +5 -1
- package/src/cli/doctor.ts +1 -0
- package/src/cli/render.ts +27 -0
- package/src/cli/serve.ts +312 -0
- package/src/cli/status.ts +18 -3
- package/src/entries/statusline.ts +53 -53
- package/src/entries/subagentstatusline.ts +78 -0
- package/src/lib/decide.ts +1 -1
- package/src/lib/paths.ts +7 -0
- package/src/lib/picker.ts +11 -2
- package/src/lib/settings.ts +17 -6
- package/src/lib/slackbridge.ts +180 -0
- package/src/lib/slackstate.ts +131 -0
- package/src/lib/slackstream.ts +189 -0
- package/src/lib/types.ts +22 -0
- package/src/lib/usage.ts +1 -1
- package/src/main.ts +5 -0
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
// Native statusLine. Reads Claude's statusLine stdin, tees the rate-limit data
|
|
2
2
|
// to usage.json (write-on-change, O(ms)), then renders ONE line:
|
|
3
|
-
// worktree name (linked worktrees only), model
|
|
4
|
-
// +added/-removed, then quota as
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
// green ◆ (per-model by initial
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
3
|
+
// worktree name (linked worktrees only), model name painted by context fill
|
|
4
|
+
// (effort in parens), +added/-removed, then quota as COLOR (user decisions
|
|
5
|
+
// 2026-07-18): each window is its time-to-reset painted on a continuous
|
|
6
|
+
// green->yellow->red ramp by used% - "◆ 𝒇 2h 1d ◇ 2d ◇ full" - the
|
|
7
|
+
// active account's windows after a green ◆ (per-model by bare initial
|
|
8
|
+
// first, fable as 𝒇, other families uppercased; "𝒇?" unpainted when the
|
|
9
|
+
// cap applies but is unmeasured, then session/5h, then week), then EVERY
|
|
10
|
+
// parked account's week after its own cyan ◇ (red ✗ if needs-reauth),
|
|
11
|
+
// sorted by earliest upcoming reset (needs-reauth last). A window with no
|
|
12
|
+
// upcoming reset renders "0" (empty again); measured usage with an unknown
|
|
13
|
+
// reset clock renders a painted "?". With color disabled the numeric format
|
|
14
|
+
// returns ("2h5" = resets in 2h, 5 used; "ctx 42"): without color a drained
|
|
15
|
+
// window must not look fresh. Blocks are joined by TWO spaces, tokens
|
|
12
16
|
// within a block by one. Per-model resets are omitted (they match the
|
|
13
17
|
// weekly reset).
|
|
14
18
|
// Must NEVER break the status line: render what parses, skip what doesn't.
|
|
@@ -17,14 +21,13 @@ import { sortBy } from "es-toolkit";
|
|
|
17
21
|
import { z } from "zod";
|
|
18
22
|
import { readOAuthAccount } from "../lib/claudejson.ts";
|
|
19
23
|
import { loadAccounts, loadConfig, loadLastSwapAt, loadModelUsage, writeUsage } from "../lib/state.ts";
|
|
20
|
-
import { familyTokens,
|
|
21
|
-
import {
|
|
24
|
+
import { familyTokens, matchedFamily, parseStatusLineStdin, parseStatusLineModel } from "../lib/usage.ts";
|
|
25
|
+
import { earliestReset, weeklyExpiry } from "../lib/picker.ts";
|
|
22
26
|
import { worktreeName } from "../lib/worktree.ts";
|
|
23
|
-
import { fmtResetShort, makeColors } from "../cli/render.ts";
|
|
27
|
+
import { fmtResetShort, makeColors, makeUsagePaint } from "../cli/render.ts";
|
|
24
28
|
import {
|
|
25
29
|
AccountsIndexSchema,
|
|
26
30
|
StatusLineStdinSchema,
|
|
27
|
-
ThresholdsSchema,
|
|
28
31
|
UsageWindowSchema,
|
|
29
32
|
type Account,
|
|
30
33
|
type UsageState,
|
|
@@ -42,15 +45,16 @@ const RenderCtxSchema = z.object({
|
|
|
42
45
|
perModel: z.record(z.string(), UsageWindowSchema),
|
|
43
46
|
/** families (lowercased) whose per-model weekly cap gates a switch. */
|
|
44
47
|
switchModels: z.array(z.string()),
|
|
45
|
-
thresholds: ThresholdsSchema,
|
|
46
48
|
/** linked-worktree basename, null in a main checkout. */
|
|
47
49
|
worktree: z.string().nullable(),
|
|
48
50
|
now: z.number(),
|
|
49
51
|
color: z.boolean(),
|
|
52
|
+
/** terminal advertises 24-bit color (COLORTERM); false steps the ramp to the 256-color cube. */
|
|
53
|
+
truecolor: z.boolean(),
|
|
50
54
|
});
|
|
51
55
|
export type RenderCtx = z.infer<typeof RenderCtxSchema>;
|
|
52
56
|
|
|
53
|
-
async function readStdin(): Promise<string> {
|
|
57
|
+
export async function readStdin(): Promise<string> {
|
|
54
58
|
const chunks: Uint8Array[] = [];
|
|
55
59
|
for await (const c of Bun.stdin.stream()) chunks.push(c);
|
|
56
60
|
return Buffer.concat(chunks).toString("utf8");
|
|
@@ -59,8 +63,7 @@ async function readStdin(): Promise<string> {
|
|
|
59
63
|
/** Pure renderer: statusLine stdin + tokenmaxxing state → the emitted line. */
|
|
60
64
|
export function renderStatusline(stdinObj: unknown, ctx: RenderCtx): string {
|
|
61
65
|
const col = makeColors(ctx.color);
|
|
62
|
-
const
|
|
63
|
-
const gauge = (u: number) => col.bold(severity(u)(`${Math.round(u)}`));
|
|
66
|
+
const paint = makeUsagePaint({ enabled: ctx.color, truecolor: ctx.truecolor });
|
|
64
67
|
// Used quota in a window; one whose reset has passed is empty again.
|
|
65
68
|
const used = (w: UsageWindow) => (w.resetsAt != null && w.resetsAt <= ctx.now ? 0 : w.usedPercentage);
|
|
66
69
|
const reset = (epochMs: number | null) => fmtResetShort(epochMs, ctx.now);
|
|
@@ -71,29 +74,43 @@ export function renderStatusline(stdinObj: unknown, ctx: RenderCtx): string {
|
|
|
71
74
|
// ---- info block: worktree, model, ctx, diff
|
|
72
75
|
const info: string[] = [];
|
|
73
76
|
if (ctx.worktree != null) info.push(ctx.worktree);
|
|
77
|
+
// The model name carries the context-fill color (user rule 2026-07-18, no
|
|
78
|
+
// ctx token); colorless mode keeps the numeric ctx token instead.
|
|
74
79
|
const modelName = d?.model?.display_name ?? d?.model?.id;
|
|
80
|
+
const ctxUsed = d?.context_window?.used_percentage;
|
|
75
81
|
if (modelName) {
|
|
76
82
|
const effort = d?.effort?.level;
|
|
77
|
-
|
|
83
|
+
const body = ctxUsed != null ? col.bold(paint(ctxUsed)(modelName)) : col.bold(modelName);
|
|
84
|
+
info.push(body + (effort ? ` (${effort})` : ""));
|
|
78
85
|
}
|
|
79
|
-
|
|
80
|
-
if (ctxUsed != null) info.push(`ctx ${gauge(ctxUsed)}`);
|
|
86
|
+
if (!ctx.color && ctxUsed != null) info.push(`ctx ${Math.round(ctxUsed)}`);
|
|
81
87
|
const added = d?.cost?.total_lines_added ?? 0;
|
|
82
88
|
const removed = d?.cost?.total_lines_removed ?? 0;
|
|
83
89
|
// -removed stays unpainted: red means quota alarm and nothing else.
|
|
84
90
|
if (added > 0 || removed > 0) info.push(`${col.green(`+${added}`)}/-${removed}`);
|
|
85
91
|
|
|
86
92
|
// ---- active account block
|
|
87
|
-
|
|
88
|
-
|
|
93
|
+
// A window token: color carries the used%, the text is the reset countdown
|
|
94
|
+
// (or the bare per-model initial - per-model resets are omitted). "0" = no
|
|
95
|
+
// upcoming reset (the window is empty again); a painted "?" = measured usage
|
|
96
|
+
// whose reset clock is unknown. Colorless mode glues the number back on.
|
|
97
|
+
const seg = (label: string, w: UsageWindow, resetAt: number | null) => {
|
|
98
|
+
const u = used(w);
|
|
99
|
+
if (!ctx.color) return `${label}${reset(resetAt)}${Math.round(u)}`;
|
|
100
|
+
const body = label !== "" ? label : reset(resetAt);
|
|
101
|
+
return col.bold(paint(u)(body !== "" ? body : u > 0 ? "?" : "0"));
|
|
102
|
+
};
|
|
103
|
+
// Per-model initial: fable renders 𝒇 (user rule 2026-07-18), family-matched
|
|
104
|
+
// as always; other families keep their uppercased first letter.
|
|
105
|
+
const initial = (name: string) => (familyTokens(name).includes("fable") ? "𝒇" : name.slice(0, 1).toUpperCase());
|
|
89
106
|
const wins = parseStatusLineStdin(stdinObj);
|
|
90
107
|
const windows: string[] = [];
|
|
91
108
|
// A capacity-constrained model whose cap is unmeasured must not look safe.
|
|
92
109
|
const family = matchedFamily(parseStatusLineModel(stdinObj), ctx.switchModels);
|
|
93
110
|
if (family && !Object.keys(ctx.perModel).some((k) => familyTokens(k).includes(family))) {
|
|
94
|
-
windows.push(`${family
|
|
111
|
+
windows.push(`${initial(family)}?`);
|
|
95
112
|
}
|
|
96
|
-
for (const [name, w] of Object.entries(ctx.perModel)) windows.push(seg(name
|
|
113
|
+
for (const [name, w] of Object.entries(ctx.perModel)) windows.push(seg(initial(name), w, null));
|
|
97
114
|
if (wins) {
|
|
98
115
|
windows.push(seg("", wins.fiveHour, wins.fiveHour.resetsAt));
|
|
99
116
|
windows.push(seg("", wins.sevenDay, wins.sevenDay.resetsAt));
|
|
@@ -105,49 +122,31 @@ export function renderStatusline(stdinObj: unknown, ctx: RenderCtx): string {
|
|
|
105
122
|
? `${col.green("◆")} ?`
|
|
106
123
|
: "";
|
|
107
124
|
|
|
108
|
-
// ---- parked accounts,
|
|
109
|
-
const pickCtx = {
|
|
110
|
-
now: ctx.now,
|
|
111
|
-
thresholds: ctx.thresholds,
|
|
112
|
-
currentAccountUuid: ctx.accounts.activeAccountUuid,
|
|
113
|
-
switchFamilies: gatedFamilies(parseStatusLineModel(stdinObj), ctx.switchModels),
|
|
114
|
-
};
|
|
125
|
+
// ---- parked accounts, earliest upcoming reset first (needs-reauth last)
|
|
115
126
|
const parked = sortBy(
|
|
116
127
|
ctx.accounts.accounts.filter((a) => a.accountUuid !== ctx.accounts.activeAccountUuid),
|
|
117
|
-
[(a) => (a.needsReauth
|
|
128
|
+
[(a) => (a.needsReauth ? 1 : 0), (a) => earliestReset(a, ctx.now)],
|
|
118
129
|
);
|
|
119
|
-
|
|
130
|
+
// Every parked account renders its own marker (user rule 2026-07-18: the
|
|
131
|
+
// old counted collapse "◇ 3 full" hid the pool size and read as confusing).
|
|
132
|
+
const poolSeg = (a: Account): string => {
|
|
120
133
|
const marker = a.needsReauth ? col.red("✗") : col.cyan("◇");
|
|
121
|
-
const mergeable = !a.needsReauth;
|
|
122
|
-
|
|
123
134
|
const week = a.lastUsage?.sevenDay;
|
|
124
|
-
if (week == null) return
|
|
135
|
+
if (week == null) return `${marker} ?`;
|
|
125
136
|
const weekUsed = used(week);
|
|
126
|
-
if (Math.round(weekUsed) <= 0) return
|
|
137
|
+
if (Math.round(weekUsed) <= 0) return `${marker} ${paint(0)("full")}`;
|
|
127
138
|
|
|
128
139
|
const parts: string[] = [];
|
|
129
140
|
// A per-model weekly cap with more used than the aggregate is the binding constraint - surface it.
|
|
130
141
|
for (const [name, w] of Object.entries(a.lastPerModel ?? {})) {
|
|
131
|
-
if (used(w) > weekUsed) parts.push(seg(name
|
|
142
|
+
if (used(w) > weekUsed) parts.push(seg(initial(name), w, null));
|
|
132
143
|
}
|
|
133
144
|
const expiry = weeklyExpiry(a, ctx.now);
|
|
134
145
|
parts.push(seg("", week, Number.isFinite(expiry) ? expiry : null));
|
|
135
|
-
return
|
|
146
|
+
return `${marker} ${parts.join(" ")}`;
|
|
136
147
|
};
|
|
137
148
|
|
|
138
|
-
|
|
139
|
-
const pool: string[] = [];
|
|
140
|
-
const segs = parked.map(poolSeg);
|
|
141
|
-
for (let i = 0; i < segs.length; ) {
|
|
142
|
-
const s = segs[i]!;
|
|
143
|
-
let j = i + 1;
|
|
144
|
-
while (s.kind !== "other" && j < segs.length && segs[j]!.kind === s.kind) j++;
|
|
145
|
-
if (j - i >= 2) pool.push(`${col.cyan("◇")} ${j - i} ${s.kind === "full" ? col.green("full") : "?"}`);
|
|
146
|
-
else pool.push(s.text);
|
|
147
|
-
i = j;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
return [info.join(" "), active, ...pool].filter((l) => l !== "").join(" ");
|
|
149
|
+
return [info.join(" "), active, ...parked.map(poolSeg)].filter((l) => l !== "").join(" ");
|
|
151
150
|
}
|
|
152
151
|
|
|
153
152
|
export async function runStatusline(): Promise<number> {
|
|
@@ -178,14 +177,15 @@ export async function runStatusline(): Promise<number> {
|
|
|
178
177
|
const modelUsage = loadModelUsage();
|
|
179
178
|
const stdin = StatusLineStdinSchema.safeParse(obj);
|
|
180
179
|
const dir = stdin.success ? (stdin.data.workspace?.current_dir ?? stdin.data.workspace?.project_dir ?? null) : null;
|
|
180
|
+
const colorterm = z.string().optional().parse(process.env.COLORTERM);
|
|
181
181
|
const ctx: RenderCtx = {
|
|
182
182
|
accounts: loadAccounts(),
|
|
183
183
|
perModel: modelUsage && modelUsage.org === org ? modelUsage.perModel : {},
|
|
184
184
|
switchModels: cfg.policy.switchModels,
|
|
185
|
-
thresholds: effectiveBars(cfg),
|
|
186
185
|
worktree: dir == null ? null : worktreeName(dir),
|
|
187
186
|
now,
|
|
188
187
|
color: !process.env.NO_COLOR,
|
|
188
|
+
truecolor: colorterm != null && (colorterm.includes("truecolor") || colorterm.includes("24bit")),
|
|
189
189
|
};
|
|
190
190
|
process.stdout.write(renderStatusline(obj, ctx) + "\n");
|
|
191
191
|
return 0;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Renders claude's subagentStatusLine: one {id, content} JSON line per active
|
|
2
|
+
// subagent task, so the agents panel shows each subagent's model, effort, and
|
|
3
|
+
// ctx fill the way the main statusline shows the session's (user ask
|
|
4
|
+
// 2026-07-18). This per-row panel surface is the only place subagent info can
|
|
5
|
+
// appear: the main statusLine command never learns which subagent the UI is
|
|
6
|
+
// viewing (verified against the 2.1.214 bundle). Row shape mirrors the main
|
|
7
|
+
// info block, info first so claude's end-truncation eats the label instead:
|
|
8
|
+
// "fable (high) <task label>" - the family name painted by the task's
|
|
9
|
+
// context fill (colorless mode keeps a numeric ctx token).
|
|
10
|
+
// A task we emit nothing for keeps claude's default row (emitting empty
|
|
11
|
+
// content would HIDE it). Must NEVER break the panel: render what parses,
|
|
12
|
+
// skip what doesn't.
|
|
13
|
+
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
import { makeColors, makeUsagePaint } from "../cli/render.ts";
|
|
16
|
+
import { readStdin } from "./statusline.ts";
|
|
17
|
+
import { SubagentStatusLineStdinSchema } from "../lib/types.ts";
|
|
18
|
+
|
|
19
|
+
const RowCtxSchema = z.object({ color: z.boolean(), truecolor: z.boolean() });
|
|
20
|
+
export type RowCtx = z.infer<typeof RowCtxSchema>;
|
|
21
|
+
|
|
22
|
+
/** "claude-fable-5" -> "fable" (lowercase family, matching the chart-label
|
|
23
|
+
* convention); an id without the claude- prefix passes through whole. */
|
|
24
|
+
function modelFamily(id: string): string {
|
|
25
|
+
const [head, family] = id.split("-");
|
|
26
|
+
return head === "claude" && family ? family : id;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Pure renderer: subagentStatusLine stdin -> {id, content} JSON lines. */
|
|
30
|
+
export function renderSubagentRows(stdinObj: unknown, ctx: RowCtx): string[] {
|
|
31
|
+
const parsed = SubagentStatusLineStdinSchema.safeParse(stdinObj);
|
|
32
|
+
if (!parsed.success) return [];
|
|
33
|
+
const col = makeColors(ctx.color);
|
|
34
|
+
const paint = makeUsagePaint({ enabled: ctx.color, truecolor: ctx.truecolor });
|
|
35
|
+
|
|
36
|
+
const rows: string[] = [];
|
|
37
|
+
for (const t of parsed.data.tasks ?? []) {
|
|
38
|
+
if (t.id == null) continue;
|
|
39
|
+
const pct =
|
|
40
|
+
t.tokenCount != null && t.contextWindowSize != null && t.contextWindowSize > 0
|
|
41
|
+
? Math.round((t.tokenCount / t.contextWindowSize) * 100)
|
|
42
|
+
: null;
|
|
43
|
+
const info: string[] = [];
|
|
44
|
+
// The model name carries the task's context-fill color (same rule as the
|
|
45
|
+
// main line); colorless mode keeps the numeric ctx token instead.
|
|
46
|
+
if (t.model != null) {
|
|
47
|
+
const family = modelFamily(t.model);
|
|
48
|
+
const body = pct != null ? col.bold(paint(pct)(family)) : col.bold(family);
|
|
49
|
+
info.push(body + (t.effort ? ` (${t.effort})` : ""));
|
|
50
|
+
}
|
|
51
|
+
if (!ctx.color && pct != null) info.push(`ctx ${pct}`);
|
|
52
|
+
|
|
53
|
+
const label = t.label ?? t.description ?? t.name;
|
|
54
|
+
const parts: string[] = [];
|
|
55
|
+
if (info.length > 0) parts.push(info.join(" "));
|
|
56
|
+
if (label != null && label !== "") parts.push(label);
|
|
57
|
+
if (parts.length === 0) continue;
|
|
58
|
+
rows.push(JSON.stringify({ id: t.id, content: parts.join(" ") }));
|
|
59
|
+
}
|
|
60
|
+
return rows;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function runSubagentStatusline(): Promise<number> {
|
|
64
|
+
const raw = await readStdin();
|
|
65
|
+
let obj: unknown = null;
|
|
66
|
+
try {
|
|
67
|
+
obj = JSON.parse(raw);
|
|
68
|
+
} catch {
|
|
69
|
+
// malformed stdin - emit nothing, claude keeps its default rows
|
|
70
|
+
}
|
|
71
|
+
const colorterm = z.string().optional().parse(process.env.COLORTERM);
|
|
72
|
+
const rows = renderSubagentRows(obj, {
|
|
73
|
+
color: !process.env.NO_COLOR,
|
|
74
|
+
truecolor: colorterm != null && (colorterm.includes("truecolor") || colorterm.includes("24bit")),
|
|
75
|
+
});
|
|
76
|
+
if (rows.length > 0) process.stdout.write(rows.join("\n") + "\n");
|
|
77
|
+
return 0;
|
|
78
|
+
}
|
package/src/lib/decide.ts
CHANGED
|
@@ -111,7 +111,7 @@ function usageFresh(u: UsageState | null, org: string | null, ttl: number, now:
|
|
|
111
111
|
* are absent, org-drifted, or older than the poll TTL. ONE probe carries all
|
|
112
112
|
* three limit kinds, so a success refreshes BOTH files; anything less leaves a
|
|
113
113
|
* headless box (no rendering statusLine to tee) evaluating frozen or
|
|
114
|
-
* org-mismatched values forever - the 2026-07-12
|
|
114
|
+
* org-mismatched values forever - the 2026-07-12 ARM-box blindness. The
|
|
115
115
|
* refreshed usage carries model: null (whatever session stamped the old model
|
|
116
116
|
* may be gone), which gates every configured family. model-usage.json's ts also
|
|
117
117
|
* stamps FAILED attempts, so a busy live token cannot cause a probe storm
|
package/src/lib/paths.ts
CHANGED
|
@@ -35,6 +35,13 @@ export const paths = {
|
|
|
35
35
|
/** linux only: parked credential .json files (0700 dir, 0600 files). */
|
|
36
36
|
credsDir: join(TM_HOME, "creds"),
|
|
37
37
|
|
|
38
|
+
/** `xx serve` slack bridge: tokens + channel->repo links (0600: holds the
|
|
39
|
+
* xoxb-/xapp- tokens), per-thread claude session records, and the git
|
|
40
|
+
* worktrees threads run in. */
|
|
41
|
+
slackJson: join(TM_HOME, "slack.json"),
|
|
42
|
+
slackThreadsDir: join(TM_HOME, "slack-threads"),
|
|
43
|
+
slackWorktreesDir: join(TM_HOME, "slack-worktrees"),
|
|
44
|
+
|
|
38
45
|
/** ~/.claude.json - holds the active `oauthAccount` identity object. */
|
|
39
46
|
claudeJson: env("TOKENMAXXING_CLAUDE_JSON", join(HOME, ".claude.json")),
|
|
40
47
|
/** ~/.claude/settings.json - user-owned; we merge three entries into it. */
|
package/src/lib/picker.ts
CHANGED
|
@@ -98,6 +98,16 @@ export function weeklyExpiry(a: Account, now: number): number {
|
|
|
98
98
|
return nextWeeklyReset(a.lastUsage?.sevenDay.resetsAt ?? null, now) ?? Number.POSITIVE_INFINITY;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
/** Soonest upcoming reset among the account's cached windows: the 5h session
|
|
102
|
+
* reset if still ahead, else the extrapolated weekly expiry; Infinity with no
|
|
103
|
+
* known reset anchor (sorts last). Display order for `status` and the
|
|
104
|
+
* statusLine pool (user decision 2026-07-18) - deliberately decoupled from
|
|
105
|
+
* swapPreference, which keeps ranking actual swaps. */
|
|
106
|
+
export function earliestReset(a: Account, now: number): number {
|
|
107
|
+
const fiveHour = a.lastUsage?.fiveHour.resetsAt;
|
|
108
|
+
return Math.min(fiveHour != null && fiveHour > now ? fiveHour : Number.POSITIVE_INFINITY, weeklyExpiry(a, now));
|
|
109
|
+
}
|
|
110
|
+
|
|
101
111
|
/** How far behind its own weekly pace the account is, measured forward: the
|
|
102
112
|
* burn rate (percent per ms) its remaining weekly quota must be consumed at
|
|
103
113
|
* to beat the reset that forfeits it. A backward-looking used/expected ratio
|
|
@@ -116,8 +126,7 @@ export function pacePressure(a: Account, now: number): number {
|
|
|
116
126
|
|
|
117
127
|
/** The switch preference: furthest behind its own weekly pace first (highest
|
|
118
128
|
* pacePressure), tiebreak soonest weekly expiry then lowest 7-day usage.
|
|
119
|
-
*
|
|
120
|
-
* swap order. */
|
|
129
|
+
* Ranks swaps only; display surfaces order by earliestReset instead. */
|
|
121
130
|
export const swapPreference = (now: number) => [
|
|
122
131
|
(a: Account) => -pacePressure(a, now),
|
|
123
132
|
(a: Account) => weeklyExpiry(a, now),
|
package/src/lib/settings.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
// Idempotent merge of tokenmaxxing's
|
|
2
|
-
// ~/.claude/settings.json: our statusLine, a Stop hook,
|
|
3
|
-
// Hooks APPEND to existing arrays; the statusLine
|
|
4
|
-
// tokenmaxxing renders
|
|
1
|
+
// Idempotent merge of tokenmaxxing's entries into the user-owned
|
|
2
|
+
// ~/.claude/settings.json: our statusLine + subagentStatusLine, a Stop hook,
|
|
3
|
+
// a SessionStart hook. Hooks APPEND to existing arrays; the statusLine slots
|
|
4
|
+
// are ours outright - tokenmaxxing renders them natively, so any other
|
|
5
|
+
// statusLine command is replaced.
|
|
5
6
|
|
|
6
7
|
import { existsSync, readFileSync } from "node:fs";
|
|
7
8
|
import { join } from "node:path";
|
|
@@ -19,6 +20,7 @@ const HookGroupSchema = z.looseObject({ matcher: z.string().optional(), hooks: z
|
|
|
19
20
|
const StatusLineSchema = z.looseObject({ type: z.string(), command: z.string() });
|
|
20
21
|
const SettingsSchema = z.looseObject({
|
|
21
22
|
statusLine: StatusLineSchema.optional(),
|
|
23
|
+
subagentStatusLine: StatusLineSchema.optional(),
|
|
22
24
|
hooks: z.record(z.string(), z.array(HookGroupSchema)).optional(),
|
|
23
25
|
});
|
|
24
26
|
type Settings = z.infer<typeof SettingsSchema>;
|
|
@@ -26,6 +28,7 @@ type HookGroup = z.infer<typeof HookGroupSchema>;
|
|
|
26
28
|
|
|
27
29
|
const SUBCMD = {
|
|
28
30
|
statusline: "__statusline",
|
|
31
|
+
subagentStatusline: "__subagent-statusline",
|
|
29
32
|
stop: "__stop-hook",
|
|
30
33
|
sessionStart: "__session-start",
|
|
31
34
|
} as const;
|
|
@@ -44,6 +47,7 @@ export function isOurCommand(cmd: string | undefined): boolean {
|
|
|
44
47
|
if (!cmd) return false;
|
|
45
48
|
return (
|
|
46
49
|
cmd.includes(SUBCMD.statusline) ||
|
|
50
|
+
cmd.includes(SUBCMD.subagentStatusline) ||
|
|
47
51
|
cmd.includes(SUBCMD.stop) ||
|
|
48
52
|
cmd.includes(SUBCMD.sessionStart) ||
|
|
49
53
|
// also match the installed bin path even if the subcommand text changes
|
|
@@ -70,29 +74,35 @@ function removeHook(s: Settings, event: string, sub: string): void {
|
|
|
70
74
|
if (s.hooks![event]!.length === 0) delete s.hooks![event];
|
|
71
75
|
}
|
|
72
76
|
|
|
73
|
-
/** Install the
|
|
77
|
+
/** Install the entries: take both statusLine slots, append our hooks. */
|
|
74
78
|
export function installSettings(): void {
|
|
75
79
|
const s = readSettings();
|
|
76
80
|
s.statusLine = {
|
|
77
81
|
type: "command",
|
|
78
82
|
command: `${JSON.stringify(installedBin())} ${SUBCMD.statusline}`,
|
|
79
83
|
};
|
|
84
|
+
s.subagentStatusLine = {
|
|
85
|
+
type: "command",
|
|
86
|
+
command: `${JSON.stringify(installedBin())} ${SUBCMD.subagentStatusline}`,
|
|
87
|
+
};
|
|
80
88
|
appendHook(s, "Stop", SUBCMD.stop);
|
|
81
89
|
appendHook(s, "SessionStart", SUBCMD.sessionStart);
|
|
82
90
|
writeSettings(s);
|
|
83
91
|
}
|
|
84
92
|
|
|
85
|
-
/** Remove our
|
|
93
|
+
/** Remove our entries. The statusLine slots are deleted only if they are ours. */
|
|
86
94
|
export function uninstallSettings(): void {
|
|
87
95
|
const s = readSettings();
|
|
88
96
|
removeHook(s, "Stop", SUBCMD.stop);
|
|
89
97
|
removeHook(s, "SessionStart", SUBCMD.sessionStart);
|
|
90
98
|
if (s.statusLine && isOurCommand(s.statusLine.command)) delete s.statusLine;
|
|
99
|
+
if (s.subagentStatusLine && isOurCommand(s.subagentStatusLine.command)) delete s.subagentStatusLine;
|
|
91
100
|
writeSettings(s);
|
|
92
101
|
}
|
|
93
102
|
|
|
94
103
|
const SettingsCheckSchema = z.object({
|
|
95
104
|
statusLineOk: z.boolean(),
|
|
105
|
+
subagentStatusLineOk: z.boolean(),
|
|
96
106
|
stopOk: z.boolean(),
|
|
97
107
|
sessionStartOk: z.boolean(),
|
|
98
108
|
});
|
|
@@ -104,6 +114,7 @@ export function checkSettings(): SettingsCheck {
|
|
|
104
114
|
!!s.hooks?.[event]?.some((g) => g.hooks?.some((h) => h.command?.includes(sub)));
|
|
105
115
|
return {
|
|
106
116
|
statusLineOk: isOurCommand(s.statusLine?.command),
|
|
117
|
+
subagentStatusLineOk: isOurCommand(s.subagentStatusLine?.command),
|
|
107
118
|
stopOk: has("Stop", SUBCMD.stop),
|
|
108
119
|
sessionStartOk: has("SessionStart", SUBCMD.sessionStart),
|
|
109
120
|
};
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// The Slack->claude relay. One claude turn per Slack message via the Agent SDK
|
|
2
|
+
// (re-query with resume, never a persistent streaming query: the SDK subprocess
|
|
3
|
+
// reads credentials at spawn, so per-turn spawns are what let the pool decision
|
|
4
|
+
// pick the freshest account at every boundary and let the daemon restart
|
|
5
|
+
// without losing threads). Verified against @anthropic-ai/claude-agent-sdk
|
|
6
|
+
// 0.3.214 and code.claude.com/docs 2026-07-18; both change monthly.
|
|
7
|
+
|
|
8
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
12
|
+
import type { StreamChunk } from "chat";
|
|
13
|
+
import { ensureBestAccount, pooledOptions, stopHookCheck } from "../sdk.ts";
|
|
14
|
+
import { paths } from "./paths.ts";
|
|
15
|
+
import { threadKey, type SlackLink } from "./slackstate.ts";
|
|
16
|
+
import { agentEventChunks, newStreamMapState, SegmentBreakSchema } from "./slackstream.ts";
|
|
17
|
+
import { log } from "./log.ts";
|
|
18
|
+
|
|
19
|
+
export const TurnOutcomeSchema = z.object({
|
|
20
|
+
sessionId: z.string().nullable(),
|
|
21
|
+
failed: z.boolean(),
|
|
22
|
+
});
|
|
23
|
+
export type TurnOutcome = z.infer<typeof TurnOutcomeSchema>;
|
|
24
|
+
|
|
25
|
+
const SegmentChunkSchema = z.union([z.string(), z.custom<StreamChunk>()]);
|
|
26
|
+
type SegmentChunk = z.infer<typeof SegmentChunkSchema>;
|
|
27
|
+
|
|
28
|
+
/** A hand-pushed async iterable: relayThread feeds one of these per Slack
|
|
29
|
+
* message segment while thread.post concurrently drains it. */
|
|
30
|
+
function pushableStream(): {
|
|
31
|
+
iterable: AsyncIterable<SegmentChunk>;
|
|
32
|
+
push: (chunk: SegmentChunk) => void;
|
|
33
|
+
end: () => void;
|
|
34
|
+
} {
|
|
35
|
+
const queue: SegmentChunk[] = [];
|
|
36
|
+
let done = false;
|
|
37
|
+
let notify: (() => void) | null = null;
|
|
38
|
+
return {
|
|
39
|
+
push(chunk) {
|
|
40
|
+
queue.push(chunk);
|
|
41
|
+
notify?.();
|
|
42
|
+
},
|
|
43
|
+
end() {
|
|
44
|
+
done = true;
|
|
45
|
+
notify?.();
|
|
46
|
+
},
|
|
47
|
+
iterable: {
|
|
48
|
+
async *[Symbol.asyncIterator]() {
|
|
49
|
+
while (true) {
|
|
50
|
+
for (let next = queue.shift(); next !== undefined; next = queue.shift()) yield next;
|
|
51
|
+
if (done) return;
|
|
52
|
+
await new Promise<void>((resolve) => {
|
|
53
|
+
notify = resolve;
|
|
54
|
+
});
|
|
55
|
+
notify = null;
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Run one git command against a repo; throws with trimmed stderr on failure. */
|
|
63
|
+
function git(repo: string, args: string[]): string {
|
|
64
|
+
const r = Bun.spawnSync(["git", "-C", repo, ...args], { stdout: "pipe", stderr: "pipe" });
|
|
65
|
+
const stderr = new TextDecoder().decode(r.stderr).trim();
|
|
66
|
+
if (r.exitCode !== 0) throw new Error(`git ${args[0]} failed: ${stderr.slice(0, 200)}`);
|
|
67
|
+
return new TextDecoder().decode(r.stdout).trim();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The stable cwd a thread's turns run in. Worktree mode (default) creates
|
|
72
|
+
* `slack-worktrees/<threadKey>` on branch `tm-slack-<threadKey>` cut from the
|
|
73
|
+
* repo's current HEAD, once; both survive daemon restarts because resume is
|
|
74
|
+
* cwd-keyed. Worktrees are never auto-deleted (they hold the thread's work):
|
|
75
|
+
* clean up with `git worktree remove` when done.
|
|
76
|
+
*/
|
|
77
|
+
export function ensureThreadCwd(input: { link: SlackLink; threadId: string }): string {
|
|
78
|
+
if (!input.link.worktree) return input.link.repo;
|
|
79
|
+
const key = threadKey(input.threadId);
|
|
80
|
+
const dir = join(paths.slackWorktreesDir, key);
|
|
81
|
+
if (existsSync(dir)) return dir;
|
|
82
|
+
mkdirSync(paths.slackWorktreesDir, { recursive: true });
|
|
83
|
+
const branch = `tm-slack-${key}`;
|
|
84
|
+
const branchExists = Bun.spawnSync(["git", "-C", input.link.repo, "rev-parse", "--verify", "--quiet", branch]).exitCode === 0;
|
|
85
|
+
// a crash between branch creation and worktree add leaves the branch behind;
|
|
86
|
+
// reattach instead of failing on -b collision.
|
|
87
|
+
if (branchExists) git(input.link.repo, ["worktree", "add", dir, branch]);
|
|
88
|
+
else git(input.link.repo, ["worktree", "add", dir, "-b", branch]);
|
|
89
|
+
log("serve.worktree_created", { dir, branch });
|
|
90
|
+
return dir;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* One claude turn relayed into a Slack thread as a SEQUENCE of messages: reply
|
|
95
|
+
* text streams natively, thinking and tool calls stream as task_update cards
|
|
96
|
+
* (see slackstream.ts), and a segment_break (a tool starting after streamed
|
|
97
|
+
* text) closes the current Slack message and opens the next one, so a turn
|
|
98
|
+
* reads as separate messages around its tool runs (user ask 2026-07-18).
|
|
99
|
+
* Segments post strictly in order: the next opens only after the previous
|
|
100
|
+
* post resolves. Never throws: a failure posts a short diagnostic line and
|
|
101
|
+
* sets outcome.failed (the daemon must keep serving other threads). Error
|
|
102
|
+
* text is message-only - a raw error body could echo request material.
|
|
103
|
+
*/
|
|
104
|
+
export async function relayThread(input: {
|
|
105
|
+
cwd: string;
|
|
106
|
+
sessionId: string | null;
|
|
107
|
+
prompt: string;
|
|
108
|
+
link: SlackLink;
|
|
109
|
+
post: (m: AsyncIterable<SegmentChunk>) => Promise<unknown>;
|
|
110
|
+
}): Promise<TurnOutcome> {
|
|
111
|
+
const outcome: TurnOutcome = { sessionId: input.sessionId, failed: false };
|
|
112
|
+
let segment: ReturnType<typeof pushableStream> | null = null;
|
|
113
|
+
let lastPost: Promise<unknown> = Promise.resolve();
|
|
114
|
+
let postedText = false;
|
|
115
|
+
const push = async (chunk: SegmentChunk) => {
|
|
116
|
+
let seg = segment;
|
|
117
|
+
if (!seg) {
|
|
118
|
+
await lastPost; // strict message order: previous segment fully posted first
|
|
119
|
+
seg = pushableStream();
|
|
120
|
+
segment = seg;
|
|
121
|
+
lastPost = input.post(seg.iterable).catch((e: unknown) => {
|
|
122
|
+
const detail = (e instanceof Error ? e.message : String(e)).slice(0, 300);
|
|
123
|
+
log("serve.post_error", { err: detail });
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
if (!postedText && !(chunk instanceof Object)) postedText = true;
|
|
127
|
+
seg.push(chunk);
|
|
128
|
+
};
|
|
129
|
+
const breakSegment = () => {
|
|
130
|
+
segment?.end();
|
|
131
|
+
segment = null;
|
|
132
|
+
};
|
|
133
|
+
try {
|
|
134
|
+
// the switch decision runs at the spawn boundary, same as the CLI hooks.
|
|
135
|
+
await ensureBestAccount();
|
|
136
|
+
const q = query({
|
|
137
|
+
prompt: input.prompt,
|
|
138
|
+
options: {
|
|
139
|
+
...pooledOptions(),
|
|
140
|
+
cwd: input.cwd,
|
|
141
|
+
permissionMode: input.link.permissionMode,
|
|
142
|
+
// the SDK refuses bypassPermissions without this explicit opt-in.
|
|
143
|
+
...(input.link.permissionMode === "bypassPermissions" ? { allowDangerouslySkipPermissions: true } : {}),
|
|
144
|
+
includePartialMessages: true,
|
|
145
|
+
// no one can answer an interactive question dialog through Slack;
|
|
146
|
+
// without the tool the model asks in prose and the user's thread
|
|
147
|
+
// reply becomes the next turn.
|
|
148
|
+
disallowedTools: ["AskUserQuestion"],
|
|
149
|
+
hooks: { Stop: [{ hooks: [stopHookCheck] }] },
|
|
150
|
+
...(input.link.model ? { model: input.link.model } : {}),
|
|
151
|
+
...(input.sessionId ? { resume: input.sessionId } : {}),
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
const mapState = newStreamMapState();
|
|
155
|
+
let result: string | null = null;
|
|
156
|
+
for await (const message of q) {
|
|
157
|
+
if (message.type === "system" && message.subtype === "init") outcome.sessionId = message.session_id;
|
|
158
|
+
if (message.type === "result") {
|
|
159
|
+
outcome.sessionId = message.session_id;
|
|
160
|
+
if (message.subtype === "success") result = message.result;
|
|
161
|
+
else outcome.failed = true;
|
|
162
|
+
}
|
|
163
|
+
for (const part of agentEventChunks({ state: mapState, message })) {
|
|
164
|
+
if (SegmentBreakSchema.safeParse(part).success) breakSegment();
|
|
165
|
+
else await push(SegmentChunkSchema.parse(part));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// a turn that produced no streamed text (tool-only turns) still reports.
|
|
169
|
+
if (!postedText && result) await push(result);
|
|
170
|
+
if (!postedText && !result && outcome.failed) await push("the turn ended without a result (limit or error) - trying again may help");
|
|
171
|
+
} catch (e) {
|
|
172
|
+
outcome.failed = true;
|
|
173
|
+
const detail = (e instanceof Error ? e.message : String(e)).slice(0, 300);
|
|
174
|
+
log("serve.turn_error", { err: detail });
|
|
175
|
+
await push(`tokenmaxxing: turn failed: ${detail}`);
|
|
176
|
+
}
|
|
177
|
+
breakSegment();
|
|
178
|
+
await lastPost;
|
|
179
|
+
return outcome;
|
|
180
|
+
}
|