tokenmaxxing 0.18.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 CHANGED
@@ -90,8 +90,11 @@ A local Socket Mode daemon (no public URL) that turns Slack threads into Claude
90
90
  - **Config**: `slack.json` (0600 - it holds the xoxb-/xapp- tokens) with per-channel links `{channel, repo, worktree, permissionMode, model?}`. `serve setup` prints the app manifest (minimal scopes: app_mentions:read, channels:history, groups:history, chat:write, files:write, users:read + socket mode) and prompts for the tokens; `serve link <channel-id> <repo>` manages links (channel IDs only - names drift, ids don't).
91
91
  - **Thread = session**: a bot mention in a linked channel subscribes the thread, creates `slack-worktrees/<threadKey>` (branch `tm-slack-<threadKey>` cut from the repo's HEAD; `--no-worktree` links run in the repo itself), and records `{threadId, cwd, sessionId}` under `slack-threads/`. Resume is cwd-keyed in claude, so the cwd stays byte-stable for the thread's life; worktrees are never auto-deleted (they hold the thread's work).
92
92
  - **Turn = spawn**: each thread message runs ONE `query()` with `resume: sessionId` (never a persistent streaming query - the SDK subprocess reads credentials at spawn, so per-turn spawns are what let `ensureBestAccount()` land each turn on the freshest account, and the daemon can restart without losing threads). `stopHookCheck` rides along as the SDK Stop hook. Streamed `text_delta`s feed `thread.post(AsyncIterable)` (the adapter debounces edits); tool-only turns post the final result text.
93
- - **Safety posture**: per-link `permissionMode`, default `acceptEdits`; `--dangerous` opts a link into `bypassPermissions`. Turn failures post a trimmed message-only diagnostic (never a raw error body). The socket loop aborts visibly after 3 consecutive connection failures.
94
- - **Verified hermetically** (2026-07-18): schema/link management, worktree creation + idempotency, arg parsing, daemon fail-fast paths. **Not yet live-verified**: a real Socket Mode connection under Bun (needs real tokens; the underlying ws/undici primitives tested clean) and a real relayed turn (meters an account). Run one live smoke test before relying on it.
93
+ - **Safety posture**: per-link `permissionMode`, default `acceptEdits`; `--yolo` (alias `--dangerous`) opts a link into `bypassPermissions`, and relayThread pairs it with the SDK's mandatory `allowDangerouslySkipPermissions: true` opt-in. `AskUserQuestion` is disallowed (unanswerable over Slack; the model asks in prose instead). Turn failures post a trimmed message-only diagnostic (never a raw error body).
94
+ - **Socket lifecycle**: `bot.initialize()` starts the persistent auto-reconnecting SocketModeClient; the daemon then just stays alive. The leased `startSocketModeListener` API must never be looped: it returns instantly without `waitUntil` and the loop starves the event loop (live incident 2026-07-18 - connected but silent).
95
+ - **Id mapping**: Chat SDK ids are adapter-prefixed (`thread.channelId` = `slack:C0123`, `thread.id` = `slack:C0123:<threadTs>`) while links store bare Slack ids - lookups strip the prefix via `bareChannelId`. Subscriptions live in the daemon's memory state, so every mention re-subscribes its thread (a restarted daemon revives an old thread on the next mention); queue-skipped messages (`context.skipped`) fold into the next prompt, with the queue-entry TTL raised to 900s; unlinked-channel traffic logs `serve.unlinked_channel` and stays silent in Slack.
96
+ - **Agent representation** (`src/lib/slackstream.ts`): turns stream natively (`chat.startStream`, which works in channel threads regardless of the assistant:write scope): thinking and tool calls as task cards ("Thinking"/tool name/"Turn", input summary + truncated output), reply text as native markdown with rendered code fences, and a segment break whenever a tool starts after streamed text, so one turn posts as separate ordered Slack messages around its tool runs.
97
+ - **Live-verified end-to-end** (2026-07-18, #tokenmaxxing-dogfooding): mention opens worktree + session, replies stream, thread follow-ups resume with context, cards + fenced code render, segmentation and queue folding behave. Plus the hermetic suite: schemas/links, worktree idempotency, stream mapping, fail-fast paths.
95
98
 
96
99
  ---
97
100
 
@@ -124,7 +127,7 @@ A local Socket Mode daemon (no public URL) that turns Slack threads into Claude
124
127
  ---
125
128
 
126
129
  ## 8. Stack
127
- TypeScript on Bun, shipped as source: one multi-call entry (`src/main.ts`, `#!/usr/bin/env bun`) serves the CLI, the `claude` supervisor, the statusLine shim, and the hooks; `init` installs a 2-line shim that `exec`s bun on the installed package's entry (the Stop path runs every turn; bun's start-up stays low-millisecond). Published to npm as `tokenmaxxing` (source, platform-independent - a compiled binary was tried and shipped one architecture's Mach-O to every platform). The supervisor needs a real PTY layer (spawn claude on a pty, forward resize/signals, restore mode between runs).
130
+ TypeScript on Bun, shipped as source: one multi-call entry (`src/main.ts`, `#!/usr/bin/env bun`) serves the CLI, the `claude` supervisor, the statusLine shim, and the hooks; `init` installs a 2-line shim that `exec`s bun on the installed package's entry (the Stop path runs every turn; bun's start-up stays low-millisecond). Published to npm as `tokenmaxxing` (source, platform-independent - a compiled binary was tried and shipped one architecture's Mach-O to every platform). Shipping is PR-based since 2026-07-18: work reaches main only through a pull request (branch, PR, CI green, review handled, merge), and a release is a PR-landed version bump followed by `gh release create` (details in AGENTS.md "Release and CI"). The supervisor needs a real PTY layer (spawn claude on a pty, forward resize/signals, restore mode between runs).
128
131
 
129
132
  ---
130
133
 
package/README.md CHANGED
@@ -45,7 +45,7 @@ claude # use claude as always
45
45
  | `tokenmaxxing status --force` | additionally ping every account (one tiny haiku request each) so all 5h session timers start now, then sample fresh |
46
46
  | `tokenmaxxing watch [seconds]` | live status: re-render every N seconds (default 120, floor 30; never pings) |
47
47
  | `tokenmaxxing config` | effective config with sources; `get`/`set`/`unset` dotted keys, `tidy` prunes unknown keys |
48
- | `tokenmaxxing serve` | Slack bridge daemon (Socket Mode, no public URL): `setup` prints the app manifest and stores the two tokens, `link <channel-id> <repo>` ties a channel to a repo, then mentioning the bot in that channel opens a Claude Code session per thread (own git worktree by default) and thread messages relay in and out |
48
+ | `tokenmaxxing serve` | Slack bridge daemon (Socket Mode, no public URL): `setup` prints the app manifest and stores the two tokens, `link <channel-id> <repo>` ties a channel to a repo (`--yolo` for full-autonomy bypassPermissions sessions), then mentioning the bot in that channel opens a Claude Code session per thread (own git worktree by default) and thread messages relay in and out |
49
49
  | `tokenmaxxing doctor` | verify the supervisor + settings entries survived |
50
50
  | `tokenmaxxing rename [--codex] <sel> <label>` / `rm <sel>` | manage the pool (`--codex` targets the codex pool: one email can hold both a claude and a codex account) |
51
51
  | `tokenmaxxing uninstall` | remove supervisor + settings entries (accounts/credentials kept) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenmaxxing",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "Automatic Claude Code account switching: pool multiple accounts and hot-swap when quota fills, resuming your session on the fresh account.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/cli/serve.ts CHANGED
@@ -14,10 +14,11 @@
14
14
  // serve run the daemon
15
15
 
16
16
  import { existsSync, realpathSync } from "node:fs";
17
- import { Chat } from "chat";
17
+ import { Chat, type StreamChunk } from "chat";
18
18
  import { createSlackAdapter } from "@chat-adapter/slack";
19
19
  import { createMemoryState } from "@chat-adapter/state-memory";
20
20
  import {
21
+ bareChannelId,
21
22
  isChannelId,
22
23
  linkForChannel,
23
24
  loadSlackConfig,
@@ -30,20 +31,24 @@ import {
30
31
  SlackLinkSchema,
31
32
  type SlackConfig,
32
33
  } from "../lib/slackstate.ts";
33
- import { ensureThreadCwd, relayTurn, type TurnOutcome } from "../lib/slackbridge.ts";
34
+ import { ensureThreadCwd, relayThread } from "../lib/slackbridge.ts";
34
35
  import { log } from "../lib/log.ts";
35
36
  import { c, count } from "./render.ts";
36
37
 
37
- const SERVE_USAGE = "usage: tokenmaxxing serve [setup | link <channel-id> <repo> [--no-worktree] [--dangerous] [--model <m>] | unlink <channel-id> | links]";
38
+ const SERVE_USAGE = "usage: tokenmaxxing serve [setup | link <channel-id> <repo> [--no-worktree] [--yolo | --dangerous] [--model <m>] | unlink <channel-id> | links]";
38
39
 
39
40
  /** The manifest the user pastes at api.slack.com/apps > From an app manifest.
40
- * Scopes/events verified against docs.slack.dev 2026-07-18: exactly what a
41
- * channel-thread relay needs, nothing more. */
41
+ * Scopes/events verified against docs.slack.dev 2026-07-18: a channel-thread
42
+ * relay plus Slack's Agent messaging experience (agent_view + assistant:write
43
+ * power the DM assistant surface and typing status; channel-thread streaming
44
+ * works without them, verified live). Changing scopes on an existing app
45
+ * requires reinstalling it to the workspace. */
42
46
  const APP_MANIFEST = `display_information:
43
47
  name: tokenmaxxing
44
48
  description: bridges Slack threads to Claude Code sessions
45
49
 
46
50
  features:
51
+ agent_view: true
47
52
  bot_user:
48
53
  display_name: tokenmaxxing
49
54
  always_online: true
@@ -52,6 +57,7 @@ oauth_config:
52
57
  scopes:
53
58
  bot:
54
59
  - app_mentions:read
60
+ - assistant:write
55
61
  - channels:history
56
62
  - groups:history
57
63
  - chat:write
@@ -61,9 +67,12 @@ oauth_config:
61
67
  settings:
62
68
  event_subscriptions:
63
69
  bot_events:
70
+ - app_context_changed
71
+ - app_home_opened
64
72
  - app_mention
65
73
  - message.channels
66
74
  - message.groups
75
+ - message.im
67
76
  socket_mode_enabled: true
68
77
  org_deploy_enabled: false
69
78
  token_rotation_enabled: false`;
@@ -77,6 +86,7 @@ function printSetupInstructions(): void {
77
86
  console.log("2. OAuth & Permissions > Install to Workspace, copy the Bot User OAuth Token (xoxb-...).");
78
87
  console.log("3. Basic Information > App-Level Tokens > Generate (add the connections:write scope), copy the token (xapp-...).");
79
88
  console.log(`4. Run ${c.cyan("tokenmaxxing serve setup")} and paste both tokens, then ${c.cyan("tokenmaxxing serve link <channel-id> <repo>")} and invite the bot to that channel.`);
89
+ console.log(`${c.dim("Existing app? Paste the manifest over App Manifest in its settings, then reinstall to the workspace (scope changes need it). Tokens stay valid unless you rotate them.")}`);
80
90
  }
81
91
 
82
92
  function cmdServeSetup(): number {
@@ -103,7 +113,8 @@ function cmdServeSetup(): number {
103
113
 
104
114
  function cmdServeLink(argv: string[]): number {
105
115
  const worktree = !argv.includes("--no-worktree");
106
- const dangerous = argv.includes("--dangerous");
116
+ // yolo mode = the SDK's bypassPermissions; --dangerous is the same switch.
117
+ const dangerous = argv.includes("--yolo") || argv.includes("--dangerous");
107
118
  const modelIdx = argv.indexOf("--model");
108
119
  const model = modelIdx >= 0 ? argv[modelIdx + 1] : undefined;
109
120
  const rest = argv.filter((a, i) => !a.startsWith("--") && (modelIdx < 0 || i !== modelIdx + 1));
@@ -172,12 +183,6 @@ function cmdServeLinks(): number {
172
183
  return 0;
173
184
  }
174
185
 
175
- /** One socket lease: how long each startSocketModeListener call holds the
176
- * WebSocket before the loop reconnects (the adapter treats the listener as
177
- * leased, not infinite). */
178
- const SOCKET_LEASE_MS = 3_600_000;
179
- const MAX_CONSECUTIVE_FAILURES = 3;
180
-
181
186
  async function runDaemon(): Promise<number> {
182
187
  const cfg = loadSlackConfig();
183
188
  if (!cfg) {
@@ -189,66 +194,107 @@ async function runDaemon(): Promise<number> {
189
194
  return 1;
190
195
  }
191
196
 
192
- const slack = createSlackAdapter({ mode: "socket", botToken: cfg.botToken, appToken: cfg.appToken });
197
+ const slack = createSlackAdapter({
198
+ mode: "socket",
199
+ botToken: cfg.botToken,
200
+ appToken: cfg.appToken,
201
+ // Native append-streaming (chat.startStream) with task cards is the
202
+ // correct mode (user-confirmed live 2026-07-18): it works in channel
203
+ // threads even when auth.test reports no assistant:write, so never gate
204
+ // it on a scope probe. The adapter falls back to post-and-edit by itself
205
+ // when a workspace truly rejects streaming. agentView matches the
206
+ // manifest's Agent messaging experience for the DM surface.
207
+ agentView: true,
208
+ // the web-api default retry policy (tenRetriesInAboutThirtyMinutes) can
209
+ // stall a streamed turn ~30min on one rate-limited edit; this is
210
+ // @slack/web-api's fiveRetriesInFiveMinutes literal (dep not declared,
211
+ // so the values are inlined).
212
+ webClientOptions: { retryConfig: { retries: 5, factor: 3.86 }, timeout: 15_000 },
213
+ });
193
214
  const bot = new Chat({
194
215
  userName: "tokenmaxxing",
195
216
  adapters: { slack },
196
217
  state: createMemoryState(),
197
218
  // per-thread lock with queueing: a message landing mid-turn waits its turn
198
- // instead of being dropped or racing a second claude spawn on the same cwd.
199
- concurrency: "queue",
219
+ // instead of racing a second claude spawn on the same cwd. The default
220
+ // 90s queue-entry TTL silently discards anything queued behind a turn
221
+ // longer than that (claude turns routinely are), hence the override.
222
+ concurrency: { strategy: "queue", queueEntryTtlMs: 900_000 },
223
+ // without this a cards-only segment in post-and-edit fallback would
224
+ // strand a bare "..." placeholder message.
225
+ fallbackStreamingPlaceholderText: null,
200
226
  logger: "warn",
201
227
  });
202
228
 
203
- const handleTurn = async (thread: { id: string; channelId: string; post: (m: AsyncIterable<string>) => Promise<unknown>; subscribe: () => Promise<void> }, rawText: string, isMention: boolean) => {
204
- const link = linkForChannel(cfg, thread.channelId);
205
- if (!link) return; // not a linked channel - stay silent
206
- const prompt = stripLeadingMention(rawText);
229
+ const handleTurn = async (input: {
230
+ thread: { id: string; channelId: string; post: (m: AsyncIterable<string | StreamChunk>) => Promise<unknown>; subscribe: () => Promise<void>; startTyping: () => Promise<void> };
231
+ texts: string[];
232
+ isMention: boolean;
233
+ }) => {
234
+ const { thread, texts, isMention } = input;
235
+ const link = linkForChannel(cfg, bareChannelId(thread.channelId));
236
+ if (!link) {
237
+ log("serve.unlinked_channel", { channel: thread.channelId });
238
+ return; // not a linked channel - stay silent in Slack
239
+ }
240
+ log("serve.message", { thread: thread.id, isMention, texts: texts.length });
241
+ // texts carries queue-skipped messages plus the triggering one: the queue
242
+ // strategy hands a turn only the LATEST message and the rest via
243
+ // context.skipped, so they are folded into one prompt here.
244
+ const prompt = texts
245
+ .map((t) => stripLeadingMention(t))
246
+ .filter((t) => t !== "")
247
+ .join("\n\n");
207
248
  if (!prompt) return;
208
249
  let record = loadSlackThread(thread.id);
209
250
  if (!record) {
210
251
  if (!isMention) return; // only a mention opens a session
211
- await thread.subscribe();
212
252
  const cwd = ensureThreadCwd({ link, threadId: thread.id });
213
253
  record = { threadId: thread.id, repo: link.repo, cwd, sessionId: null, createdAt: new Date().toISOString() };
214
254
  saveSlackThread(record);
215
255
  log("serve.thread_opened", { thread: thread.id, cwd });
216
256
  }
217
- const outcome: TurnOutcome = { sessionId: record.sessionId, failed: false };
218
- await thread.post(relayTurn({ cwd: record.cwd, sessionId: record.sessionId, prompt, link }, outcome));
257
+ // subscriptions live in the memory state, so a daemon restart forgets
258
+ // them; every mention re-subscribes to keep follow-up replies flowing.
259
+ if (isMention) await thread.subscribe();
260
+ // "is working..." assistant status; a no-op until the Slack app has the
261
+ // agent feature + assistant:write (the adapter warns instead of throwing).
262
+ await thread.startTyping();
263
+ const outcome = await relayThread({
264
+ cwd: record.cwd,
265
+ sessionId: record.sessionId,
266
+ prompt,
267
+ link,
268
+ post: (m) => thread.post(m),
269
+ });
219
270
  if (outcome.sessionId !== record.sessionId) {
220
271
  saveSlackThread({ ...record, sessionId: outcome.sessionId });
221
272
  }
222
273
  };
223
274
 
224
- bot.onNewMention(async (thread, message) => {
225
- await handleTurn(thread, message.text, true);
275
+ const relayable = (m: { author: { isMe: boolean; isBot?: boolean | "unknown" } }) => !m.author.isMe && m.author.isBot !== true;
276
+
277
+ bot.onNewMention(async (thread, message, context) => {
278
+ const texts = [...(context?.skipped ?? []).filter(relayable), message].map((m) => m.text);
279
+ await handleTurn({ thread, texts, isMention: true });
226
280
  });
227
- bot.onSubscribedMessage(async (thread, message) => {
228
- if (message.author.isMe || message.author.isBot === true) return; // never relay our own posts
229
- await handleTurn(thread, message.text, false);
281
+ bot.onSubscribedMessage(async (thread, message, context) => {
282
+ if (!relayable(message)) return; // never relay our own posts
283
+ const texts = [...(context?.skipped ?? []).filter(relayable), message].map((m) => m.text);
284
+ await handleTurn({ thread, texts, isMention: false });
230
285
  });
231
286
 
287
+ // initialize() starts the PERSISTENT Socket Mode client (auto-reconnecting)
288
+ // wired straight into event routing; the daemon only has to stay alive.
289
+ // Never call startSocketModeListener here: that is the serverless leased
290
+ // variant (it demands options.waitUntil and returns instantly without it),
291
+ // and awaiting it in a loop starved the event loop so hard the WebSocket
292
+ // never delivered a single event (live incident 2026-07-18).
232
293
  await bot.initialize();
233
- console.log(`${c.green("●")} serving ${count({ n: cfg.links.length, noun: "linked channel" })} over Slack Socket Mode - mention the bot in a linked channel to open a session`);
234
-
235
- let consecutiveFailures = 0;
236
- while (true) {
237
- try {
238
- await slack.startSocketModeListener({}, SOCKET_LEASE_MS);
239
- consecutiveFailures = 0;
240
- } catch (e) {
241
- consecutiveFailures += 1;
242
- const err = (e instanceof Error ? e.message : String(e)).slice(0, 200);
243
- console.error(c.red(`socket listener failed (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}): ${err}`));
244
- log("serve.socket_error", { err, consecutiveFailures });
245
- if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
246
- console.error(c.red("giving up after 3 consecutive socket failures - check the tokens with `tokenmaxxing serve setup`"));
247
- return 1;
248
- }
249
- await Bun.sleep(5_000);
250
- }
251
- }
294
+ console.log(`${c.green("●")} serving ${count({ n: cfg.links.length, noun: "linked channel" })} over Slack Socket Mode - mention the bot in a linked channel to open a session (Ctrl-C to stop)`);
295
+ log("serve.started", { links: cfg.links.length });
296
+ await new Promise<never>(() => {});
297
+ return 0;
252
298
  }
253
299
 
254
300
  export async function cmdServe(argv: string[]): Promise<number> {
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 stella blindness. The
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
@@ -9,19 +9,56 @@ import { existsSync, mkdirSync } from "node:fs";
9
9
  import { join } from "node:path";
10
10
  import { z } from "zod";
11
11
  import { query } from "@anthropic-ai/claude-agent-sdk";
12
+ import type { StreamChunk } from "chat";
12
13
  import { ensureBestAccount, pooledOptions, stopHookCheck } from "../sdk.ts";
13
14
  import { paths } from "./paths.ts";
14
15
  import { threadKey, type SlackLink } from "./slackstate.ts";
16
+ import { agentEventChunks, newStreamMapState, SegmentBreakSchema } from "./slackstream.ts";
15
17
  import { log } from "./log.ts";
16
18
 
17
- /** Mutated in place by relayTurn so the caller can hand the generator straight
18
- * to thread.post(AsyncIterable) and still read the turn's outcome afterward. */
19
19
  export const TurnOutcomeSchema = z.object({
20
20
  sessionId: z.string().nullable(),
21
21
  failed: z.boolean(),
22
22
  });
23
23
  export type TurnOutcome = z.infer<typeof TurnOutcomeSchema>;
24
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
+
25
62
  /** Run one git command against a repo; throws with trimmed stderr on failure. */
26
63
  function git(repo: string, args: string[]): string {
27
64
  const r = Bun.spawnSync(["git", "-C", repo, ...args], { stdout: "pipe", stderr: "pipe" });
@@ -54,16 +91,45 @@ export function ensureThreadCwd(input: { link: SlackLink; threadId: string }): s
54
91
  }
55
92
 
56
93
  /**
57
- * One claude turn, yielded as streaming text deltas (feed directly to
58
- * thread.post). Never throws: a failure yields a short diagnostic line and
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
59
101
  * sets outcome.failed (the daemon must keep serving other threads). Error
60
102
  * text is message-only - a raw error body could echo request material.
61
103
  */
62
- export async function* relayTurn(
63
- input: { cwd: string; sessionId: string | null; prompt: string; link: SlackLink },
64
- outcome: TurnOutcome,
65
- ): AsyncGenerator<string> {
66
- let yieldedAny = false;
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
+ };
67
133
  try {
68
134
  // the switch decision runs at the spawn boundary, same as the CLI hooks.
69
135
  await ensureBestAccount();
@@ -73,35 +139,42 @@ export async function* relayTurn(
73
139
  ...pooledOptions(),
74
140
  cwd: input.cwd,
75
141
  permissionMode: input.link.permissionMode,
142
+ // the SDK refuses bypassPermissions without this explicit opt-in.
143
+ ...(input.link.permissionMode === "bypassPermissions" ? { allowDangerouslySkipPermissions: true } : {}),
76
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"],
77
149
  hooks: { Stop: [{ hooks: [stopHookCheck] }] },
78
150
  ...(input.link.model ? { model: input.link.model } : {}),
79
151
  ...(input.sessionId ? { resume: input.sessionId } : {}),
80
152
  },
81
153
  });
154
+ const mapState = newStreamMapState();
82
155
  let result: string | null = null;
83
156
  for await (const message of q) {
84
157
  if (message.type === "system" && message.subtype === "init") outcome.sessionId = message.session_id;
85
- if (message.type === "stream_event") {
86
- const event = message.event;
87
- if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
88
- yieldedAny = true;
89
- yield event.delta.text;
90
- }
91
- }
92
158
  if (message.type === "result") {
93
159
  outcome.sessionId = message.session_id;
94
160
  if (message.subtype === "success") result = message.result;
95
161
  else outcome.failed = true;
96
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
+ }
97
167
  }
98
168
  // a turn that produced no streamed text (tool-only turns) still reports.
99
- if (!yieldedAny && result) yield result;
100
- if (!yieldedAny && !result && outcome.failed) yield "the turn ended without a result (limit or error) - trying again may help";
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");
101
171
  } catch (e) {
102
172
  outcome.failed = true;
103
173
  const detail = (e instanceof Error ? e.message : String(e)).slice(0, 300);
104
174
  log("serve.turn_error", { err: detail });
105
- yield `${yieldedAny ? "\n\n" : ""}tokenmaxxing: turn failed: ${detail}`;
175
+ await push(`tokenmaxxing: turn failed: ${detail}`);
106
176
  }
177
+ breakSegment();
178
+ await lastPost;
179
+ return outcome;
107
180
  }
@@ -115,6 +115,12 @@ export function linkForChannel(cfg: SlackConfig, channel: string): SlackLink | n
115
115
  return cfg.links.find((l) => l.channel === channel) ?? null;
116
116
  }
117
117
 
118
+ /** Chat SDK channel ids are adapter-prefixed ("slack:C0123"); links store the
119
+ * bare Slack id, so lookups must strip the prefix. */
120
+ export function bareChannelId(id: string): string {
121
+ return id.startsWith("slack:") ? id.slice("slack:".length) : id;
122
+ }
123
+
118
124
  /** Strip a leading Slack mention token ("<@U0123> rest") from message text. */
119
125
  export function stripLeadingMention(text: string): string {
120
126
  const trimmed = text.trimStart();
@@ -0,0 +1,189 @@
1
+ // Maps Claude Agent SDK messages onto Chat SDK stream chunks so a relayed
2
+ // Slack turn shows the agent's process natively: task cards for thinking and
3
+ // tool calls (pending -> in_progress -> complete/error), streamed text via
4
+ // markdown_text, and a closing turn card with model/cost/duration. Structured
5
+ // chunks render only when the Slack app has the agent feature + assistant:write
6
+ // (the adapter drops them gracefully otherwise); plain text streams either way.
7
+
8
+ import { z } from "zod";
9
+ import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
10
+ import type { StreamChunk } from "chat";
11
+
12
+ const DETAILS_MAX = 400;
13
+ const OUTPUT_MAX = 600;
14
+
15
+ /** Tool-input fields worth showing on a task card, most human-readable first. */
16
+ const SUMMARY_FIELDS = ["command", "description", "file_path", "pattern", "prompt", "query", "url"] as const;
17
+
18
+ const OpenBlockSchema = z.object({
19
+ kind: z.enum(["thinking", "tool"]),
20
+ id: z.string(),
21
+ title: z.string(),
22
+ /** accumulated thinking text or partial tool-input JSON. */
23
+ acc: z.string(),
24
+ });
25
+ type OpenBlock = z.infer<typeof OpenBlockSchema>;
26
+
27
+ export const StreamMapStateSchema = z.object({
28
+ /** open content blocks by stream index. */
29
+ open: z.record(z.string(), OpenBlockSchema),
30
+ /** tool_use id -> tool name, for labeling the eventual tool_result. */
31
+ toolTitles: z.record(z.string(), z.string()),
32
+ thinkingCount: z.number(),
33
+ /** reply text streamed since the last segment break. */
34
+ textSinceBreak: z.boolean(),
35
+ });
36
+ export type StreamMapState = z.infer<typeof StreamMapStateSchema>;
37
+
38
+ export function newStreamMapState(): StreamMapState {
39
+ return { open: {}, toolTitles: {}, thinkingCount: 0, textSinceBreak: false };
40
+ }
41
+
42
+ /** Emitted when a tool starts after streamed reply text: the bridge closes the
43
+ * current Slack message there and posts the rest as a new one, mirroring how
44
+ * an agent turn reads as separate messages around its tool runs. */
45
+ export const SegmentBreakSchema = z.object({ type: z.literal("segment_break") });
46
+ export type SegmentBreak = z.infer<typeof SegmentBreakSchema>;
47
+
48
+ export const StreamPartSchema = z.union([z.string(), z.custom<StreamChunk>(), SegmentBreakSchema]);
49
+ export type StreamPart = z.infer<typeof StreamPartSchema>;
50
+
51
+ function truncate(input: { text: string; max: number }): string {
52
+ return input.text.length > input.max ? `${input.text.slice(0, input.max)}...` : input.text;
53
+ }
54
+
55
+ /** One human line out of a tool-input JSON blob; null when nothing fits. */
56
+ export function toolInputSummary(rawJson: string): string | null {
57
+ let parsed: unknown;
58
+ try {
59
+ parsed = JSON.parse(rawJson);
60
+ } catch {
61
+ return null; // partial or empty input JSON - show the bare tool name
62
+ }
63
+ const obj = z.record(z.string(), z.unknown()).safeParse(parsed);
64
+ if (!obj.success) return null;
65
+ for (const field of SUMMARY_FIELDS) {
66
+ const value = z.string().min(1).safeParse(obj.data[field]);
67
+ if (value.success) return truncate({ text: value.data, max: DETAILS_MAX });
68
+ }
69
+ const compact = JSON.stringify(parsed);
70
+ return compact === "{}" ? null : truncate({ text: compact, max: DETAILS_MAX });
71
+ }
72
+
73
+ const ToolResultBlockSchema = z.object({
74
+ type: z.literal("tool_result"),
75
+ tool_use_id: z.string(),
76
+ content: z.union([z.string(), z.array(z.unknown())]).optional(),
77
+ is_error: z.boolean().optional(),
78
+ });
79
+
80
+ const TextPartSchema = z.object({ type: z.literal("text"), text: z.string() });
81
+
82
+ function resultText(content: z.infer<typeof ToolResultBlockSchema>["content"]): string | undefined {
83
+ if (content === undefined) return undefined;
84
+ const joined = Array.isArray(content)
85
+ ? content
86
+ .flatMap((part) => {
87
+ const p = TextPartSchema.safeParse(part);
88
+ return p.success ? [p.data.text] : [];
89
+ })
90
+ .join("\n")
91
+ : content;
92
+ const trimmed = joined.trim();
93
+ return trimmed === "" ? undefined : truncate({ text: trimmed, max: OUTPUT_MAX });
94
+ }
95
+
96
+ /**
97
+ * Consume one SDK message, mutating state, and return the stream chunks it
98
+ * produces (strings are streamed reply text; objects are native task cards).
99
+ * Subagent events (parent_tool_use_id set) contribute their TOOL cards to the
100
+ * timeline (user ask 2026-07-18: subagent activity shows as accordions like
101
+ * tool calls) but never reply text, thinking cards, or segment breaks: a
102
+ * subagent runs inside a top-level Task tool, so its churn decorates the
103
+ * current message rather than reshaping it. Open blocks are keyed per stream
104
+ * (parent + index) because concurrent subagent streams reuse index space.
105
+ */
106
+ export function agentEventChunks(input: { state: StreamMapState; message: SDKMessage }): StreamPart[] {
107
+ const { state, message } = input;
108
+ if (message.type === "stream_event") {
109
+ const isMain = message.parent_tool_use_id === null;
110
+ const event = message.event;
111
+ if (event.type === "content_block_start") {
112
+ const key = `${message.parent_tool_use_id ?? "main"}:${event.index}`;
113
+ if (event.content_block.type === "thinking" && isMain) {
114
+ state.thinkingCount += 1;
115
+ const id = `thinking-${state.thinkingCount}`;
116
+ state.open[key] = { kind: "thinking", id, title: "Thinking", acc: "" };
117
+ return [{ type: "task_update", id, title: "Thinking", status: "in_progress" }];
118
+ }
119
+ if (event.content_block.type === "tool_use") {
120
+ const { id, name } = event.content_block;
121
+ state.open[key] = { kind: "tool", id, title: name, acc: "" };
122
+ state.toolTitles[id] = name;
123
+ const card: StreamPart = { type: "task_update", id, title: name, status: "in_progress" };
124
+ if (isMain && state.textSinceBreak) {
125
+ state.textSinceBreak = false;
126
+ return [{ type: "segment_break" }, card];
127
+ }
128
+ return [card];
129
+ }
130
+ return [];
131
+ }
132
+ if (event.type === "content_block_delta") {
133
+ const open = state.open[`${message.parent_tool_use_id ?? "main"}:${event.index}`];
134
+ if (event.delta.type === "text_delta") {
135
+ if (!isMain) return [];
136
+ state.textSinceBreak = true;
137
+ return [event.delta.text];
138
+ }
139
+ if (event.delta.type === "thinking_delta" && open) open.acc += event.delta.thinking;
140
+ if (event.delta.type === "input_json_delta" && open) open.acc += event.delta.partial_json;
141
+ return [];
142
+ }
143
+ if (event.type === "content_block_stop") {
144
+ const key = `${message.parent_tool_use_id ?? "main"}:${event.index}`;
145
+ const open = state.open[key];
146
+ if (!open) return [];
147
+ delete state.open[key];
148
+ if (open.kind === "thinking") {
149
+ return [{ type: "task_update", id: open.id, title: open.title, status: "complete", details: truncate({ text: open.acc.trim(), max: DETAILS_MAX }) }];
150
+ }
151
+ const details = toolInputSummary(open.acc);
152
+ return [{ type: "task_update", id: open.id, title: open.title, status: "in_progress", ...(details ? { details } : {}) }];
153
+ }
154
+ return [];
155
+ }
156
+ if (message.type === "user") {
157
+ const content = message.message.content;
158
+ if (!Array.isArray(content)) return [];
159
+ const chunks: StreamChunk[] = [];
160
+ for (const block of content) {
161
+ const parsed = ToolResultBlockSchema.safeParse(block);
162
+ if (!parsed.success) continue;
163
+ const title = state.toolTitles[parsed.data.tool_use_id];
164
+ if (title === undefined) continue;
165
+ const output = resultText(parsed.data.content);
166
+ chunks.push({
167
+ type: "task_update",
168
+ id: parsed.data.tool_use_id,
169
+ title,
170
+ status: parsed.data.is_error === true ? "error" : "complete",
171
+ ...(output ? { output } : {}),
172
+ });
173
+ }
174
+ return chunks;
175
+ }
176
+ if (message.type === "result") {
177
+ const models = Object.keys(message.modelUsage).join(" ");
178
+ const cost = `$${message.total_cost_usd.toFixed(4)}`;
179
+ const secs = `${Math.round(message.duration_ms / 1000)}s`;
180
+ return [{
181
+ type: "task_update",
182
+ id: "turn",
183
+ title: "Turn",
184
+ status: message.subtype === "success" ? "complete" : "error",
185
+ details: [models, cost, secs].filter((p) => p !== "").join(" "),
186
+ }];
187
+ }
188
+ return [];
189
+ }
package/src/lib/usage.ts CHANGED
@@ -76,7 +76,7 @@ export function matchedFamily(model: ModelInfo | null, families: string[]): stri
76
76
  * unknown. The unknown case matters on headless boxes: a swap clears the
77
77
  * snapshots and only an actively-rendering statusLine restores the model, so
78
78
  * the periodic check ran model-blind for hours while the active account sat at
79
- * its Fable cap (the 2026-07-12 stella incident). */
79
+ * its Fable cap (the 2026-07-12 ARM-box incident). */
80
80
  export function gatedFamilies(model: ModelInfo | null, families: string[]): string[] {
81
81
  if (!model) return families;
82
82
  const family = matchedFamily(model, families);