tokenmaxxing 1.1.0 → 1.1.1
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 +2 -2
- package/package.json +1 -1
- package/src/lib/slackbridge.ts +176 -47
package/DESIGN.md
CHANGED
|
@@ -97,13 +97,13 @@ A local Socket Mode daemon (no public URL) that turns Slack threads into Claude
|
|
|
97
97
|
- **Serve skills** (`src/serve-plugin/`, ships in the package via `files: ["src"]`): a Claude Code plugin loaded per turn (`plugins: [{type: "local", path}]`; discovered skills are enabled by default, so no `skills` option). `tokenmaxxing:ask-the-user` teaches the decision protocol - when input is needed, tag the requester with the raw Slack mention token `<@U...>`, ask compactly, END the turn (the thread reply is the next turn); `tokenmaxxing:serve-session` documents how the session runs (shared repo checkout, resume across turns, worktree-by-default for mutating tasks, handoff). The one dynamic fact skills cannot carry - who asked - rides in per turn via a `UserPromptSubmit` hook whose `additionalContext` ("Slack relay context: ...", built by `serveTurnContext`) names the triggering message author's mention token. The mention survives the pipeline because streamed `markdown_text` deltas pass verbatim and the post-and-edit fallback's `finalize` only linkifies bare `@U...`, never escaping an already-formed `<@U...>`. Skills are independent of the system prompt choice (probe-verified 2026-07-18 under the custom-string `SLACK_SYSTEM_PROMPT`: the init message lists the plugin + both skills + the Skill tool; the skill listing arrives as a conversation system-reminder, and CLAUDE.md loads via settingSources).
|
|
98
98
|
- **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).
|
|
99
99
|
- **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; queue-skipped messages (`context.skipped`) fold into the next prompt, with the queue-entry TTL raised to 1h (expiry is silent - no app callback in chat 4.34.0 - so it must outlast a depleted-pool park plus a long turn); per-thread turn serialization is owned by the daemon itself (a promise chain per thread id), because the SDK's queue dispatch lock has a 30s TTL extended only between dispatches and every claude turn outlives it; unlinked-channel traffic logs `serve.unlinked_channel` and stays silent in Slack.
|
|
100
|
-
- **Restart resilience** (0.19.0, from the 2026-07-18 dead-thread incident: a deploy restart cut a turn mid-answer and left the thread deaf to follow-ups): startup re-subscribes every `slack-threads/` record straight on the state adapter (`state.subscribe(threadId)`; message routing checks `stateAdapter.isSubscribed`, verified in chat 4.34.0), so open threads survive restarts without needing a fresh mention. SIGTERM/SIGINT drains instead of dying: new turns are dropped loudly (`serve.drain_dropped` plus a tracked in-thread notice - a log-only drop reads as the bot thinking), tracked in-flight turns get up to 300s to finish (a re-snapshotting wait, so late-added notices still flush), then `Chat.shutdown()`; a second signal forces exit; the drain also aborts any depleted-pool park so a countdown never delays a restart. The claude child spawns detached in its own process group (`detachedClaudeSpawn` via the SDK's `spawnClaudeCodeProcess` hook), because a terminal Ctrl-C signals the whole foreground group and a non-detached child died with the daemon before the drain could save the turn; the signal handlers register before `bot.initialize()` so no turn can start while the process still has default signal disposition, and a rejecting `Chat.shutdown()` is caught so the drain always reaches its exit. When a `thread.post` rejects mid-turn (e.g. Slack finalizes an idle stream: `message_not_in_streaming_state`), relayThread
|
|
100
|
+
- **Restart resilience** (0.19.0, from the 2026-07-18 dead-thread incident: a deploy restart cut a turn mid-answer and left the thread deaf to follow-ups): startup re-subscribes every `slack-threads/` record straight on the state adapter (`state.subscribe(threadId)`; message routing checks `stateAdapter.isSubscribed`, verified in chat 4.34.0), so open threads survive restarts without needing a fresh mention. SIGTERM/SIGINT drains instead of dying: new turns are dropped loudly (`serve.drain_dropped` plus a tracked in-thread notice - a log-only drop reads as the bot thinking), tracked in-flight turns get up to 300s to finish (a re-snapshotting wait, so late-added notices still flush), then `Chat.shutdown()`; a second signal forces exit; the drain also aborts any depleted-pool park so a countdown never delays a restart. The claude child spawns detached in its own process group (`detachedClaudeSpawn` via the SDK's `spawnClaudeCodeProcess` hook), because a terminal Ctrl-C signals the whole foreground group and a non-detached child died with the daemon before the drain could save the turn; the signal handlers register before `bot.initialize()` so no turn can start while the process still has default signal disposition, and a rejecting `Chat.shutdown()` is caught so the drain always reaches its exit. When a `thread.post` rejects mid-turn (e.g. Slack finalizes an idle stream after an undocumented window: `message_not_in_streaming_state`), relayThread salvages the dead segment in TEXT space: proven-delivered text is a mirror StreamingMarkdownRenderer's committable prefix over the confirmed chunks (each pull proves the previous append landed; the adapter's renderer holds back the trailing unterminated line until its post-iteration forced flush, so chunk-granular salvage would miss a final reply with no trailing newline - the live 2026-07-21 incident), and the remainder re-posts as a fresh message split at line boundaries, plus unconfirmed cards, bounded by a futility budget that refills on delivery progress; the textLost diagnostic remains only for exhausted salvage, and ambiguous failures duplicate a tail line rather than lose it.
|
|
101
101
|
- **Interrupted-turn recovery** (from the second 2026-07-18 restart incident: a redeploy killed a ship turn 8 minutes in with zero notice - drain cannot save a long turn, and a group-wide kill can take the claude child even detached): the thread record persists the claude session id the moment the init message assigns it, and every turn is wrapped in a durable `activeTurn` marker (original prompt, start time, resume count) written before the spawn and cleared when the turn returns - except that a turn failing DURING a drain keeps its marker, since that failure is presumed to be the shutdown signal killing the child. On startup, a surviving marker means a restart killed that turn: the daemon posts a notice into the thread (the chat-sdk's documented proactive handle, rebuilt with the thread's newest human message as streaming recipient context so the resumed turn keeps its native task cards, that message's author becoming the turn's requester) and auto-resumes the work - resuming the recorded session with a continuation prompt, or replaying the original prompt fresh when the kill landed before the session opened; resumed turns settle like inbound ones (outcome log + finish_thread GC). Retries cap at 3 (each spends real quota) with a loud give-up notice posted before its marker clears; a per-thread turn lock keeps a startup resume from ever racing an inbound message turn in the same cwd, every recovery branch recomputes its decision from a fresh record reload under that lock (so a resume superseded by a faster inbound turn no-ops instead of double-running), and a blocking singleton flock makes a new daemon generation wait for the previous one - drain included - to fully exit before touching any thread record. Uncatchable deaths cannot leak a working child either: SIGHUP drains like SIGTERM (its default disposition skips the exit hook that kills the detached group), and the marker records the child's group pid plus its C-locale ps start-time token at spawn, so recovery kills only an exactly-identified SIGKILL-orphaned claude (never a recycled pid) before resuming its turn.
|
|
102
102
|
- **Depleted-pool recovery** (harvested from Slaude, reshaped around the pool): relayThread consumes the spawn-boundary switch decision instead of discarding it - a depleted pool with a known recovery inside the message's one 14min parking deadline (shared across chained parks, so the thread's queue slot is never held longer in total) posts a park notice and retries at the reset. A mid-turn limit - detected ONLY on errored results, since `is_error` can ride subtype `"success"` (`Claude AI usage limit reached|<epoch>`) and a successful answer discussing limits must never be re-run - is persisted into usage.json first (`recordObservedLimit`: the serve process has no statusLine tee, and the snapshot TTL would otherwise feed the retry the stale pre-limit state), then retried silently after a short beat, so a pool swap makes the hiccup invisible. Bounded recoveries; every drop the relay performs is announced in-thread.
|
|
103
103
|
- **Usage-limit auto-resume** (2026-07-21, superseding the drop-beats-false-promise rule for the known-wake case): a turn that ends at a usage limit with a KNOWN recovery time defers instead of dropping. relayThread reports `deferUntil`, the thread's durable activeTurn marker keeps a `resumeAt`, and a per-thread daemon timer (cancelled on drain, re-armed from the record at startup: future wakes schedule, past wakes recover immediately) fires the same interrupted-turn recovery path - serialized chain, fresh-reload supersede check, pool-recovery notice, `resumeDecision` capping total resumes. The defer triggers: known recovery past the parking deadline or recovery budget, retries exhausted while a post-burn pool probe reports a wake, and an unclassifiable child failure (no limit phrase in the error) converted by a pool probe reporting exhaustion - the pool state is the evidence the error text did not carry. Only an unknown recovery time still posts the honest re-send drop.
|
|
104
104
|
- **Slack-native output hygiene**: relayed turns run a small standalone `systemPrompt` telling the model replies render as Slack markdown, never HTML (a live turn once answered with a literal `<br>`; the SDK's default system prompt is minimal since 0.1.0, so the string replaces nothing).
|
|
105
105
|
- **Slash commands** (2026-07-18): a mention-stripped thread message that starts with `/` runs as a claude slash command - the SDK delivers a string prompt as one stream-json user message and the CLI routes a leading-slash prompt through its command table, on fresh and resumed sessions alike (live-verified with free `/usage` and `/context` reads). Local command output (`num_turns` 0) arrives as a non-streamed assistant message plus `result.result`, which relayThread's no-text fallback posts; `slackstream` also maps the documented `system/local_command_output` wire subtype in case a claude update flips the emitter. `/goal` (built-in since 2.1.139) works headless and its active goal is restored on resume, so it survives the per-message resume pattern. Slack gotcha: the composer eats ANY message whose first character is `/` client-side (channels and thread replies; registered app commands cannot even dispatch from threads), so the supported forms are `@bot /usage` (mention-first) and ` /usage` (leading space, Slack's own documented workaround) - both normalize to a position-0 command via `stripLeadingMention`.
|
|
106
|
-
- **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) that Slack groups into ONE collapsible plan block per turn (the serve edge wraps every posted segment in a `StreamingPlan` with `groupTasks: "plan"`, Slack's `task_display_mode: "plan"`; user ask 2026-07-20 "squash them into one dropdown", superseding the 2026-07-18 separate-messages shape), and reply text as native markdown with rendered code fences - so one turn streams as a single Slack message: the reply plus one dropdown of its activity. A later main text block (typically post-tool prose) opens on a `\n\n` paragraph break (`textStreamed`), restoring the separation the per-tool message split used to provide; whitespace-only deltas do not arm it. Notices still post as their own messages, and a rejected append (Slack's message cap, a finalized idle stream)
|
|
106
|
+
- **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) that Slack groups into ONE collapsible plan block per turn (the serve edge wraps every posted segment in a `StreamingPlan` with `groupTasks: "plan"`, Slack's `task_display_mode: "plan"`; user ask 2026-07-20 "squash them into one dropdown", superseding the 2026-07-18 separate-messages shape), and reply text as native markdown with rendered code fences - so one turn streams as a single Slack message: the reply plus one dropdown of its activity. A later main text block (typically post-tool prose) opens on a `\n\n` paragraph break (`textStreamed`), restoring the separation the per-tool message split used to provide; whitespace-only deltas do not arm it. Notices still post as their own messages, and a rejected append (Slack's message cap, a finalized idle stream) carries its undelivered chunks into a follow-on message via the dead-segment salvage.
|
|
107
107
|
- **Todo checklist card**: TodoWrite is bookkeeping, not a real tool run, so it never opens a generic card. Instead each stream gets one stable-id "Todos" card (id `todos`, subagents `todos-<parent_tool_use_id>`) that updates in place on every TodoWrite: `✅ content` for completed, `🔄 activeForm` for the in-progress item (live narration), `⬜ content` for pending (the Chat SDK Plan object's own iconography); card status goes complete only when every item is completed. The "Todos have been modified successfully" tool_result is suppressed, but a FAILED TodoWrite flips the card to error (the optimistic checklist must not claim a state that never took effect). Card ids do not carry across messages, so a TodoWrite after a dead-segment recovery starts a fresh card in the follow-on message: accepted, the latest state is always in the newest message. claude >= 2.1.142 defaults to the structured Task tools and never emits TodoWrite, so relayThread sets `CLAUDE_CODE_ENABLE_TASKS: "0"` in the spawn env (the documented opt-out; without it the checklist card is inert).
|
|
108
108
|
- **Terminal echo** (2026-07-18): the daemon registers a `log()` echo (`setLogEcho` in log.ts, off by default so hooks and the statusline keep their stdout protocols clean), so every event while it runs - serve.* plus the in-process swap/decision events from `ensureBestAccount()`/`stopHookCheck` - also prints one colored line in the foreground terminal (`formatLogLine`: dim HH:MM:SS, event painted red/yellow/cyan by structural endsWith severity, redacted fields). `serve.turn_done`/`serve.turn_failed` (with seconds) close every relayed turn, so a foreground `xx serve` is observable without tailing `tokenmaxxing.log`.
|
|
109
109
|
- **Live-verified end-to-end** (2026-07-18, #tokenmaxxing-dogfooding): mention opens a session (worktree-per-thread at the time), replies stream, thread follow-ups resume with context, cards + fenced code render, segmentation and queue folding behave. Plus the hermetic suite: schemas/links, stream mapping, fail-fast paths.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokenmaxxing",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
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/lib/slackbridge.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { join } from "node:path";
|
|
|
10
10
|
import { z } from "zod";
|
|
11
11
|
import { delay } from "es-toolkit";
|
|
12
12
|
import { createSdkMcpServer, query, tool, type SpawnOptions } from "@anthropic-ai/claude-agent-sdk";
|
|
13
|
-
import type
|
|
13
|
+
import { StreamingMarkdownRenderer, type StreamChunk } from "chat";
|
|
14
14
|
import { ensureBestAccount, pooledOptions, stopHookCheck, type SwapDecision } from "../sdk.ts";
|
|
15
15
|
import { POST_SWAP_COOLDOWN_MS } from "./decide.ts";
|
|
16
16
|
import { readOAuthAccount } from "./claudejson.ts";
|
|
@@ -217,23 +217,41 @@ function pushableStream(): {
|
|
|
217
217
|
iterable: AsyncIterable<SegmentChunk>;
|
|
218
218
|
push: (chunk: SegmentChunk) => void;
|
|
219
219
|
end: () => void;
|
|
220
|
+
ledger: () => { chunks: SegmentChunk[]; confirmed: number };
|
|
220
221
|
} {
|
|
221
|
-
const
|
|
222
|
+
const chunks: SegmentChunk[] = [];
|
|
223
|
+
let cursor = 0;
|
|
224
|
+
let confirmed = 0;
|
|
222
225
|
let done = false;
|
|
223
226
|
let notify: (() => void) | null = null;
|
|
224
227
|
return {
|
|
225
228
|
push(chunk) {
|
|
226
|
-
|
|
229
|
+
chunks.push(chunk);
|
|
227
230
|
notify?.();
|
|
228
231
|
},
|
|
229
232
|
end() {
|
|
230
233
|
done = true;
|
|
231
234
|
notify?.();
|
|
232
235
|
},
|
|
236
|
+
/** Everything ever pushed plus how much of it the consumer PROVED
|
|
237
|
+
* delivered. The Slack adapter pulls one chunk, awaits its Slack append,
|
|
238
|
+
* then pulls the next (verified in @chat-adapter/slack 4.34.0 stream()),
|
|
239
|
+
* so each pull confirms the append for the previous chunk landed; a
|
|
240
|
+
* consumer that dies mid-append unwinds the for-await with an implicit
|
|
241
|
+
* return() at the yield, leaving that chunk and everything after it
|
|
242
|
+
* unconfirmed. */
|
|
243
|
+
ledger() {
|
|
244
|
+
return { chunks: [...chunks], confirmed };
|
|
245
|
+
},
|
|
233
246
|
iterable: {
|
|
234
247
|
async *[Symbol.asyncIterator]() {
|
|
235
248
|
while (true) {
|
|
236
|
-
|
|
249
|
+
while (cursor < chunks.length) {
|
|
250
|
+
const next = chunks[cursor]!;
|
|
251
|
+
cursor += 1;
|
|
252
|
+
yield next;
|
|
253
|
+
confirmed = cursor;
|
|
254
|
+
}
|
|
237
255
|
if (done) return;
|
|
238
256
|
await new Promise<void>((resolve) => {
|
|
239
257
|
notify = resolve;
|
|
@@ -415,57 +433,168 @@ export async function relayThread(input: {
|
|
|
415
433
|
let segment: ReturnType<typeof pushableStream> | null = null;
|
|
416
434
|
let segmentMeta: { text: boolean } | null = null;
|
|
417
435
|
let lastPost: Promise<unknown> = Promise.resolve();
|
|
418
|
-
// Reply TEXT that
|
|
419
|
-
// by a later text-bearing segment: the
|
|
420
|
-
// card-only segment never sets this
|
|
421
|
-
// Tradeoff (flagged and accepted): a later
|
|
422
|
-
// flag even though it is a continuation,
|
|
423
|
-
//
|
|
424
|
-
//
|
|
425
|
-
//
|
|
426
|
-
//
|
|
436
|
+
// Reply TEXT that died with a rejected segment and was neither salvaged into
|
|
437
|
+
// a follow-on message nor re-delivered by a later text-bearing segment: the
|
|
438
|
+
// user has not seen the answer. A lost card-only segment never sets this
|
|
439
|
+
// (decoration, not the answer). Tradeoff (flagged and accepted): a later
|
|
440
|
+
// delivered text segment clears the flag even though it is a continuation,
|
|
441
|
+
// because a rejection whose text chunks were all consumed pre-append-failure
|
|
442
|
+
// was almost certainly delivered (the adapter appends per chunk) except for
|
|
443
|
+
// an unobservable renderer-held tail; sticky loss would fail every long turn
|
|
444
|
+
// with a spurious diagnostic.
|
|
427
445
|
let textLost = false;
|
|
428
446
|
let textLostDetail: string | null = null;
|
|
429
447
|
let postedText = false;
|
|
448
|
+
// Salvage: a rejected post's undelivered chunks re-post as a fresh message
|
|
449
|
+
// (Slack finalizes an idle stream after an UNDOCUMENTED window - verified
|
|
450
|
+
// absent from the chat.startStream/appendStream docs 2026-07-21 - so
|
|
451
|
+
// recovery is reactive on any append failure, never a keepalive tuned to a
|
|
452
|
+
// guessed constant). The budget bounds FUTILITY, not recovery: a death
|
|
453
|
+
// after the message delivered something is progress and refills it (a long
|
|
454
|
+
// turn can outlive any number of idle finalizations, each losing only the
|
|
455
|
+
// gap tail), while a surface that delivers nothing (revoked channel, hard
|
|
456
|
+
// cap on the very first append) burns a strike per attempt and stops.
|
|
457
|
+
const MAX_SEGMENT_SALVAGES = 5;
|
|
458
|
+
let salvagesLeft = MAX_SEGMENT_SALVAGES;
|
|
459
|
+
const openSegment = () => {
|
|
460
|
+
const seg = pushableStream();
|
|
461
|
+
segment = seg;
|
|
462
|
+
const meta = { text: false };
|
|
463
|
+
segmentMeta = meta;
|
|
464
|
+
lastPost = input.post(seg.iterable).then(
|
|
465
|
+
() => {
|
|
466
|
+
salvagesLeft = MAX_SEGMENT_SALVAGES;
|
|
467
|
+
// segments settle in order (push awaits lastPost before opening the
|
|
468
|
+
// next), so delivered text supersedes an earlier loss.
|
|
469
|
+
if (meta.text) textLost = false;
|
|
470
|
+
},
|
|
471
|
+
(e: unknown) => {
|
|
472
|
+
const detail = (e instanceof Error ? e.message : String(e)).slice(0, 300);
|
|
473
|
+
log("serve.post_error", { err: detail });
|
|
474
|
+
// the consumer is gone (e.g. Slack finalized an idle stream:
|
|
475
|
+
// message_not_in_streaming_state). Salvage runs in TEXT space, not
|
|
476
|
+
// chunk space, because the adapter's renderer buffers across chunks
|
|
477
|
+
// (it holds back the trailing unterminated line, unconfirmed table
|
|
478
|
+
// headers, and unclosed inline markers until the post-iteration
|
|
479
|
+
// finish() flush - pullfrog catch on PR #45: a reply whose last line
|
|
480
|
+
// has no trailing newline dies entirely in that forced flush, with
|
|
481
|
+
// every chunk already consumed). Proven-delivered text = the mirror
|
|
482
|
+
// renderer's committable prefix over the CONFIRMED chunks (each pull
|
|
483
|
+
// proves the previous append landed; the adapter runs the renderer
|
|
484
|
+
// with wrapTablesForAppend: false, so committable is a raw prefix and
|
|
485
|
+
// the mirror is chunking-invariant). Renderer drift would break the
|
|
486
|
+
// prefix check and degrade to a full re-post: duplication, never
|
|
487
|
+
// loss. Same tradeoff for a stop()-failure after a complete flush:
|
|
488
|
+
// the held tail re-posts once rather than risking silent loss.
|
|
489
|
+
const { chunks, confirmed } = seg.ledger();
|
|
490
|
+
if (segment === seg) segment = null;
|
|
491
|
+
const confirmedRaw = chunks
|
|
492
|
+
.slice(0, confirmed)
|
|
493
|
+
.flatMap((c) => (c instanceof Object ? [] : [c]))
|
|
494
|
+
.join("");
|
|
495
|
+
const fullRaw = chunks.flatMap((c) => (c instanceof Object ? [] : [c])).join("");
|
|
496
|
+
const mirror = new StreamingMarkdownRenderer({ wrapTablesForAppend: false });
|
|
497
|
+
mirror.push(confirmedRaw);
|
|
498
|
+
const committed = mirror.getCommittableText();
|
|
499
|
+
const deliveredLen = confirmedRaw.startsWith(committed) ? committed.length : 0;
|
|
500
|
+
const textRemainder = fullRaw.slice(deliveredLen);
|
|
501
|
+
// A confirmed card's append landed (the adapter sends a card inline
|
|
502
|
+
// in the loop body before the next pull), so unconfirmed cards are
|
|
503
|
+
// the set it never appended.
|
|
504
|
+
const deliveredCard = chunks.slice(0, confirmed).some((c) => c instanceof Object);
|
|
505
|
+
// Delivery progress means this death does not count toward the
|
|
506
|
+
// futility budget: only a message that delivered nothing burns one.
|
|
507
|
+
// The key is ACTUAL delivery (committable text or a landed card),
|
|
508
|
+
// never chunk consumption: a reply whose final line has no trailing
|
|
509
|
+
// newline is consumed whole (confirmed advances) while its only
|
|
510
|
+
// append is the post-iteration forced flush, so a consumption key
|
|
511
|
+
// would refill the budget on every persistently failing flush and
|
|
512
|
+
// salvage the same held-back text forever (vercel review catch,
|
|
513
|
+
// PR #45). deliveredLen stays 0 there, the strike is spent, and the
|
|
514
|
+
// zero-delivery case terminates.
|
|
515
|
+
if (deliveredLen > 0 || deliveredCard) salvagesLeft = MAX_SEGMENT_SALVAGES;
|
|
516
|
+
// The salvage sequence preserves STREAM ORDER (cursor review catch,
|
|
517
|
+
// PR #45: re-posting all remainder text and then all cards showed
|
|
518
|
+
// task cards after prose that originally followed them): walk the
|
|
519
|
+
// ledger in order, keeping each text chunk's undelivered suffix and
|
|
520
|
+
// each unconfirmed card at its original position. Text splits at
|
|
521
|
+
// line boundaries (rendering is unchanged: chunks concatenate) so a
|
|
522
|
+
// salvage message that dies too still confirms per line, keeping
|
|
523
|
+
// progress attribution fine-grained.
|
|
524
|
+
const lost: SegmentChunk[] = [];
|
|
525
|
+
let offset = 0;
|
|
526
|
+
for (const [i, c] of chunks.entries()) {
|
|
527
|
+
if (c instanceof Object) {
|
|
528
|
+
if (i >= confirmed) lost.push(c);
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
const end = offset + c.length;
|
|
532
|
+
let rest = end > deliveredLen ? c.slice(Math.max(0, deliveredLen - offset)) : "";
|
|
533
|
+
offset = end;
|
|
534
|
+
while (rest !== "") {
|
|
535
|
+
const nl = rest.indexOf("\n");
|
|
536
|
+
if (nl === -1) {
|
|
537
|
+
lost.push(rest);
|
|
538
|
+
break;
|
|
539
|
+
}
|
|
540
|
+
lost.push(rest.slice(0, nl + 1));
|
|
541
|
+
rest = rest.slice(nl + 1);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (lost.length > 0 && salvagesLeft > 0) {
|
|
545
|
+
salvagesLeft -= 1;
|
|
546
|
+
log("serve.post_salvage", { chunks: lost.length, left: salvagesLeft });
|
|
547
|
+
// this handler runs synchronously as the post settles, so opening
|
|
548
|
+
// the salvage segment here keeps the salvaged content ordered ahead
|
|
549
|
+
// of any push still awaiting lastPost; the salvage segment's own
|
|
550
|
+
// settle then decides whether its text counts as delivered.
|
|
551
|
+
const next = openSegment();
|
|
552
|
+
for (const c of lost) next.pushInto(c);
|
|
553
|
+
} else if (textRemainder !== "") {
|
|
554
|
+
textLost = true;
|
|
555
|
+
textLostDetail = detail;
|
|
556
|
+
}
|
|
557
|
+
},
|
|
558
|
+
);
|
|
559
|
+
const pushInto = (chunk: SegmentChunk) => {
|
|
560
|
+
// meta.text only, NEVER postedText: salvaged text was already counted
|
|
561
|
+
// at its original push, and postedText is attempt-scoped - a salvage
|
|
562
|
+
// landing after a retry reset would otherwise re-arm it and suppress
|
|
563
|
+
// the retry's `!postedText && result` fallback, silently dropping a
|
|
564
|
+
// result-only answer (adversarial-review catch on PR #45).
|
|
565
|
+
if (!(chunk instanceof Object)) meta.text = true;
|
|
566
|
+
seg.push(chunk);
|
|
567
|
+
};
|
|
568
|
+
return { seg, pushInto };
|
|
569
|
+
};
|
|
430
570
|
const push = async (chunk: SegmentChunk) => {
|
|
431
|
-
|
|
432
|
-
if (!seg) {
|
|
571
|
+
if (segment === null) {
|
|
433
572
|
await lastPost; // strict message order: previous segment fully posted first
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
const meta = { text: false };
|
|
438
|
-
segmentMeta = meta;
|
|
439
|
-
lastPost = input.post(seg.iterable).then(
|
|
440
|
-
() => {
|
|
441
|
-
// segments settle in order (push awaits lastPost before opening the
|
|
442
|
-
// next), so delivered text supersedes an earlier loss.
|
|
443
|
-
if (meta.text) textLost = false;
|
|
444
|
-
},
|
|
445
|
-
(e: unknown) => {
|
|
446
|
-
const detail = (e instanceof Error ? e.message : String(e)).slice(0, 300);
|
|
447
|
-
log("serve.post_error", { err: detail });
|
|
448
|
-
if (meta.text) {
|
|
449
|
-
textLost = true;
|
|
450
|
-
textLostDetail = detail;
|
|
451
|
-
}
|
|
452
|
-
// the consumer is gone (e.g. Slack finalized an idle stream:
|
|
453
|
-
// message_not_in_streaming_state) - drop the dead segment so the
|
|
454
|
-
// next chunk opens a fresh message instead of vanishing into it.
|
|
455
|
-
if (segment === posted) segment = null;
|
|
456
|
-
},
|
|
457
|
-
);
|
|
573
|
+
// a rejection handler may have opened a salvage segment during the wait;
|
|
574
|
+
// joining it instead of opening another keeps its post from being
|
|
575
|
+
// orphaned un-ended.
|
|
458
576
|
}
|
|
577
|
+
const target = segment ?? openSegment().seg;
|
|
459
578
|
if (!(chunk instanceof Object)) {
|
|
460
579
|
postedText = true;
|
|
461
580
|
segmentMeta!.text = true;
|
|
462
581
|
}
|
|
463
|
-
|
|
582
|
+
target.push(chunk);
|
|
464
583
|
};
|
|
465
584
|
const breakSegment = () => {
|
|
466
585
|
segment?.end();
|
|
467
586
|
segment = null;
|
|
468
587
|
};
|
|
588
|
+
// settle the whole post chain: a rejection handler may replace lastPost with
|
|
589
|
+
// a salvage segment's post, which still needs ending and settling.
|
|
590
|
+
const settlePosts = async () => {
|
|
591
|
+
while (true) {
|
|
592
|
+
breakSegment();
|
|
593
|
+
const settled = lastPost;
|
|
594
|
+
await settled;
|
|
595
|
+
if (lastPost === settled) return;
|
|
596
|
+
}
|
|
597
|
+
};
|
|
469
598
|
// a recovery status line reads as its own Slack message, not part of a
|
|
470
599
|
// streamed segment.
|
|
471
600
|
const notify = async (text: string) => {
|
|
@@ -487,7 +616,7 @@ export async function relayThread(input: {
|
|
|
487
616
|
* its own delivery resets textLost. */
|
|
488
617
|
const notifyDelivered = async (text: string) => {
|
|
489
618
|
await notify(text);
|
|
490
|
-
await
|
|
619
|
+
await settlePosts();
|
|
491
620
|
return !textLost;
|
|
492
621
|
};
|
|
493
622
|
// false when the daemon started draining mid-sleep.
|
|
@@ -768,12 +897,12 @@ export async function relayThread(input: {
|
|
|
768
897
|
break;
|
|
769
898
|
}
|
|
770
899
|
}
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
//
|
|
774
|
-
// the answer silently vanished while the outcome would
|
|
775
|
-
// the turn and make one best-effort fresh-message
|
|
776
|
-
//
|
|
900
|
+
await settlePosts();
|
|
901
|
+
// Reply text died with a rejected segment, salvage could not re-deliver it
|
|
902
|
+
// (budget exhausted or the salvage posts died too), and nothing later
|
|
903
|
+
// re-delivered it: the answer silently vanished while the outcome would
|
|
904
|
+
// report success. Fail the turn and make one best-effort fresh-message
|
|
905
|
+
// diagnostic.
|
|
777
906
|
if (textLost) {
|
|
778
907
|
outcome.failed = true;
|
|
779
908
|
const detail = textLostDetail ?? "unknown error";
|