@thehammer/danx-dashboard-mcp 0.1.80 → 0.1.82
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/README.md +2 -2
- package/dist/bridge.js +174 -140
- package/dist/index.js +29 -11
- package/dist/json-body.js +23 -0
- package/dist/listen.js +118 -10
- package/dist/plan-state.js +194 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -60,10 +60,10 @@ CLAUDE_CODE_SESSION_ID=<session> npx -y @thehammer/danx-dashboard-mcp@<version>
|
|
|
60
60
|
```
|
|
61
61
|
|
|
62
62
|
- **Credential — the session's own, never the ambient one (DX-2862).** The session id is the only thing `bridge` takes from its environment; `--resume-ids` is the only argument and holds no secret. Everything else comes from the connection record this session's own danx-dashboard MCP server wrote on `plan_connect` (`src/session-connection.ts`): the dashboard URL, the credential's SOURCE, and its FINGERPRINT. `bridge` resolves that source through the same resolver the server used and refuses to run unless the result fingerprints identically — `credential_mismatch`. Before that fix it used whatever `DANXBOT_DISPATCH_TOKEN` the session's environment held, and on a machine where that differed from the server's credential the dashboard admitted the stream and dropped every event, with nothing logged anywhere.
|
|
63
|
-
- **
|
|
63
|
+
- **No client-side reach check (DX-2920).** `bridge` used to prove board reach itself, before ever opening the stream (`GET /api/plans/mine?fields=cards` + a per-board `GET /api/issues/:id/problems`). That check is DELETED — the dashboard (DX-2863) now enforces the identical requirement server-side, and a second client-side copy of the same check was a duplicate source of truth, not a safety net: it refuses a mint (`403 issuer_cannot_read_plan_boards`), refuses stream admission (the SAME 403), and ends a live stream (`event: end`, `{"reason":"scope_narrowed","boards":[…]}`) the instant it stops being true. `bridge` only MAPS those refusals now — see "Stopping" below — it never independently verifies anything before streaming. Once a ticket is minted, `bridge` emits, once, `{"type":"ready"}` — no `boards` field, since reach is no longer proven client-side.
|
|
64
64
|
- **Ticket.** `bridge` mints the session's listener ticket (`POST /api/plan-sessions/me/stream-ticket`, 10 s timeout) and keeps it in the process. A ticket authorizes reading that one session's event stream and nothing else, and is only issued while the session is connected to a plan. Minting a new one ends the previous listener.
|
|
65
65
|
- **Output — JSON Lines.** One `{"type":"event","id":<id|null>,"text":"…"}` per event on the connected plan's cards, where `text` is `[DX-8 "Title" repo:board] newms87 answered "Which rollout order?": chose "Pause E2E" — note: "only this week"`, `… answered "…": "<free-form answer>"`, `… commented: "…"`, `… opened a problem: "…"`, `… blocked the card: "…"`, or `… unblocked the card`. An event it cannot read still produces one, with a `could not read event` text. Nothing for keep-alives, reconnects or re-mints. The session's own writes are never echoed back to it.
|
|
66
|
-
- **Stopping.** Last, one `{"type":"stopped","reason":"…","detail":"…","fix":"…"}` and exit, only on a terminal outcome. `fix` is the remedy shown to the session (`STOP_FIXES` in `src/bridge.ts` — never a log-only hint), so a session that hits a stop it cannot otherwise see still knows what to do about it. Terminal reasons: `no_connection_record` / `credential_unavailable` / `credential_mismatch` (the start-time checks above), `not_connected
|
|
66
|
+
- **Stopping.** Last, one `{"type":"stopped","reason":"…","detail":"…","fix":"…"}` and exit, only on a terminal outcome. `fix` is the remedy shown to the session (`STOP_FIXES` in `src/bridge.ts` — never a log-only hint), so a session that hits a stop it cannot otherwise see still knows what to do about it. Terminal reasons: `no_connection_record` / `credential_unavailable` / `credential_mismatch` (the start-time checks above), `not_connected` (a `409 session_not_connected` at mint OR at stream admission, or a live `end("not_connected")` — all three mapped identically), `unauthorized` (401/403 for a reason OTHER than an unreadable board), `mint_refused` (any other non-transient mint refusal), `mint_bad_response`, `board_unreadable` (a `403 issuer_cannot_read_plan_boards` at mint OR at stream admission, naming the unreadable boards — DX-2920), `scope_narrowed` (a LIVE stream's `end("scope_narrowed", boards)` — the server's `end()` REQUIRES `boards` for this reason at the type level, `bridge` parses them off the wire and names them in `detail`/`fix`, never a generic message), `bad_end_payload` (a `scope_narrowed` end whose `boards` array was missing or malformed — a protocol error surfaced loudly, never silently downgraded to a boards-less `scope_narrowed`), `superseded` / `replaced` (exit 0 — a newer or replacing connection already serves this session, so `fix` says no action is needed), `revoked`, or `refused` (two freshly minted tickets refused in a row with no more specific classification). A transient mint failure (network, timeout, 408, 429, 5xx) backs off and retries; a lapsed ticket lease re-mints.
|
|
67
67
|
- **Reconnect and resume.** A read-idle timeout (three missed keep-alives) turns a silently dead connection into a drop. Capped exponential backoff (1s → 30s) that resets only after a healthy connection, with `Last-Event-ID`, so a dashboard restart replays what was missed and nothing is emitted twice. `--resume-ids` carries the same guarantee across a process restart: the ids already delivered seed the duplicate guard, and the highest is the first `Last-Event-ID`. The dashboard floors that replay at the later of the session's first ticket and when it joined its current plan, so a restart loses nothing and a plan move replays nothing from before the move.
|
|
68
68
|
|
|
69
69
|
## Build + test
|
package/dist/bridge.js
CHANGED
|
@@ -20,29 +20,59 @@
|
|
|
20
20
|
* credential from its session's tools streamed happily and relayed nothing.
|
|
21
21
|
* 3. Mints the session's listener ticket (`POST /api/plan-sessions/me/stream-ticket`).
|
|
22
22
|
* The ticket stays in this process.
|
|
23
|
-
* 4.
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
23
|
+
* 4. DX-2920 — board-coverage reach is a SERVER-ENFORCED property now, never a
|
|
24
|
+
* client-side verify: the stream admits an event only when the ticket
|
|
25
|
+
* issuer's board allowlist covers that event's board (`isVisibleToStream`,
|
|
26
|
+
* dashboard), and the dashboard itself (DX-2863) refuses to hand out a
|
|
27
|
+
* ticket, refuses to admit a connection, and ends a live stream the instant
|
|
28
|
+
* that stops being true — `403 issuer_cannot_read_plan_boards` at MINT
|
|
29
|
+
* (`mintTicket`) AND at stream ADMISSION (`classifyAdmissionRefusal`,
|
|
30
|
+
* reading `listen.ts`'s structured `refusal`) are BOTH mapped to
|
|
31
|
+
* `board_unreadable`, naming the boards; `409 session_not_connected` at
|
|
32
|
+
* mint AND at admission are both mapped to `not_connected`; and
|
|
33
|
+
* `end("scope_narrowed", boards)` / `end("not_connected")` cover the
|
|
34
|
+
* same two failures once the stream is already live — `end`'s own
|
|
35
|
+
* overloaded signature in `plan-session-stream.ts` REQUIRES `boards` for
|
|
36
|
+
* `scope_narrowed` at the type level (round 3), and `listen.ts` parses
|
|
37
|
+
* them off the wire the same way it parses `reason`, so this module can
|
|
38
|
+
* name them in `scope_narrowed`'s detail/fix exactly like it already
|
|
39
|
+
* does for `board_unreadable`. This module no longer runs its own
|
|
40
|
+
* duplicate board-by-board check before streaming — see DX-2920 and the
|
|
41
|
+
* deleted `verifyPlanBoardsReadable`.
|
|
29
42
|
* 5. Streams through `runListener` (`listen.ts`), which reconnects within the
|
|
30
43
|
* ticket, and re-mints when that ticket's lease runs out or a fresh ticket
|
|
31
44
|
* is refused once.
|
|
32
|
-
* 6. Writes JSON Lines to stdout: ONE `{type:"ready"
|
|
33
|
-
* is
|
|
34
|
-
* `{type:"stopped", reason, detail, fix}` before exiting.
|
|
45
|
+
* 6. Writes JSON Lines to stdout: ONE `{type:"ready"}` once a ticket has been
|
|
46
|
+
* minted and streaming is about to start, `{type:"event", id, text}` per
|
|
47
|
+
* event, and ONE final `{type:"stopped", reason, detail, fix}` before exiting.
|
|
35
48
|
*
|
|
36
49
|
* TERMINAL OUTCOMES — each ends the process with its stop record, never a retry:
|
|
37
50
|
* - `no_connection_record` this session has no connection record to read;
|
|
38
51
|
* - `credential_unavailable` its declared credential cannot be resolved here;
|
|
39
52
|
* - `credential_mismatch` what resolved is not the server's credential;
|
|
40
|
-
* - `not_connected` the mint
|
|
41
|
-
*
|
|
53
|
+
* - `not_connected` the mint, or the stream's admission / keep-alive,
|
|
54
|
+
* answered `session_not_connected` (409 at mint and
|
|
55
|
+
* at admission; `end("not_connected")` once live);
|
|
56
|
+
* - `unauthorized` the mint answered 401 / 403 for a reason OTHER
|
|
57
|
+
* than an unreadable board;
|
|
42
58
|
* - `mint_refused` any other non-transient mint refusal (400, 404, …);
|
|
43
59
|
* - `mint_bad_response` a 2xx mint whose body is not a ticket;
|
|
44
|
-
* - `board_unreadable` the
|
|
45
|
-
*
|
|
60
|
+
* - `board_unreadable` the mint OR the stream's admission was refused
|
|
61
|
+
* `403 issuer_cannot_read_plan_boards`, naming the
|
|
62
|
+
* boards this credential cannot read (DX-2920);
|
|
63
|
+
* - `scope_narrowed` a LIVE stream ended because the plan grew, or the
|
|
64
|
+
* credential's allowlist shrank past, a board this
|
|
65
|
+
* credential can no longer read — `boards` names
|
|
66
|
+
* them, parsed from the dashboard's own `end`
|
|
67
|
+
* payload by `listen.ts` the same way `reason`
|
|
68
|
+
* itself is parsed, and `detail`/`fix` are built
|
|
69
|
+
* dynamically from them (DX-2920 round 3 —
|
|
70
|
+
* `boardUnreadableDetail` / `scopeNarrowedFix`),
|
|
71
|
+
* never a static generic message;
|
|
72
|
+
* - `bad_end_payload` a `scope_narrowed` end whose `boards` array was
|
|
73
|
+
* missing or malformed — a PROTOCOL error, never
|
|
74
|
+
* silently downgraded to a boards-less
|
|
75
|
+
* `scope_narrowed` stop (DX-2920 round 3);
|
|
46
76
|
* - `superseded` / `replaced` (exit 0) — another listener now holds the session;
|
|
47
77
|
* - `revoked` the dashboard revoked the ticket or its issuer;
|
|
48
78
|
* - `refused` freshly minted tickets were refused twice in a row.
|
|
@@ -54,14 +84,13 @@
|
|
|
54
84
|
* session's own MCP server declared, resolved here from that declaration.
|
|
55
85
|
*/
|
|
56
86
|
import { homedir } from "node:os";
|
|
87
|
+
import { errorCodeOf } from "./json-body.js";
|
|
57
88
|
import { oneLine } from "./one-line.js";
|
|
58
89
|
import { credentialFingerprint, describeCredentialSource, readCredential, } from "./credential.js";
|
|
59
90
|
import { readSessionConnection } from "./session-connection.js";
|
|
60
91
|
import { DELIVERED_ID_MEMORY, HEALTHY_CONNECTION_MS, READ_IDLE_TIMEOUT_MS, runListener, } from "./listen.js";
|
|
61
92
|
export const BRIDGE_SUBCOMMAND = "bridge";
|
|
62
93
|
export const STREAM_TICKET_PATH = "/api/plan-sessions/me/stream-ticket";
|
|
63
|
-
export const PLAN_MINE_PATH = "/api/plans/mine";
|
|
64
|
-
export const ISSUES_PATH = "/api/issues";
|
|
65
94
|
export const SESSION_ID_HEADER = "x-danx-session-id";
|
|
66
95
|
/** How long one dashboard request may take before it counts as a transient failure. */
|
|
67
96
|
export const REQUEST_TIMEOUT_MS = 10_000;
|
|
@@ -69,10 +98,7 @@ export const MINT_INITIAL_BACKOFF_MS = 1_000;
|
|
|
69
98
|
export const MINT_MAX_BACKOFF_MS = 60_000;
|
|
70
99
|
/** A freshly minted ticket refused this many times in a row is a terminal outcome, not a loop. */
|
|
71
100
|
export const MAX_REFUSED_TICKETS_IN_A_ROW = 2;
|
|
72
|
-
/** One page of the connected plan's cards, for the board-reach check. The server's ceiling. */
|
|
73
|
-
export const PLAN_CARDS_PAGE_SIZE = 1_000;
|
|
74
101
|
const TRANSIENT_CLIENT_STATUSES = new Set([408, 429]);
|
|
75
|
-
const TAKEOVER_REASONS = new Set(["superseded", "replaced"]);
|
|
76
102
|
const USAGE = `usage: CLAUDE_CODE_SESSION_ID=<session-id> danx-dashboard-mcp ${BRIDGE_SUBCOMMAND} ` +
|
|
77
103
|
`[--resume-ids <event-id>[,<event-id>...]]`;
|
|
78
104
|
/**
|
|
@@ -95,7 +121,11 @@ export const STOP_FIXES = {
|
|
|
95
121
|
mint_refused: "check that this session is connected to a plan on the dashboard its MCP server points at, then call plan_connect again",
|
|
96
122
|
mint_bad_response: "check that DANXBOT_DASHBOARD_URL for this session's MCP server points at a danxbot dashboard",
|
|
97
123
|
board_unreadable: "scope this session's dashboard credential to read that board, or connect a plan whose cards all live on boards it can read",
|
|
98
|
-
|
|
124
|
+
// DX-2920 (round 3) — a `scope_narrowed` end whose `boards` array was
|
|
125
|
+
// missing or invalid (`listen.ts`'s parse-time check). Named separately
|
|
126
|
+
// from `scope_narrowed` itself, which always carries boards and never
|
|
127
|
+
// reaches this generic map at all.
|
|
128
|
+
bad_end_payload: "call plan_connect again to mint a new listener ticket for this session",
|
|
99
129
|
// A newer ticket exists (superseded) or another connection is already using
|
|
100
130
|
// this one (replaced) — THIS process is ending because the session is
|
|
101
131
|
// already served elsewhere, not because anything is broken.
|
|
@@ -127,6 +157,11 @@ export function parseBridgeArgs(argv, env) {
|
|
|
127
157
|
}
|
|
128
158
|
/** A start this process cannot make, named the way the session will be told about it. */
|
|
129
159
|
export class BridgeStartError extends Error {
|
|
160
|
+
// DX-2920 (round 4) — `ListenStopReason`, not `string`: a start-time failure
|
|
161
|
+
// is always one of `no_connection_record` / `credential_unavailable` /
|
|
162
|
+
// `credential_mismatch`, never `scope_narrowed` (there is no stream yet), so
|
|
163
|
+
// this can be the closed reason type the eventual `write({type:"stopped",
|
|
164
|
+
// reason: start.reason, ...})` needs it to be.
|
|
130
165
|
reason;
|
|
131
166
|
fix;
|
|
132
167
|
constructor(reason, detail, fix) {
|
|
@@ -175,15 +210,43 @@ export function resolveBridgeOptions(args, env, options = {}) {
|
|
|
175
210
|
resumeIds: args.resumeIds,
|
|
176
211
|
};
|
|
177
212
|
}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
213
|
+
/**
|
|
214
|
+
* DX-2920 — `body.boards` off a `403 issuer_cannot_read_plan_boards` refusal
|
|
215
|
+
* (`unreadableBoardsRefusal`, dashboard `plan-scope.ts`), or `[]` when the body
|
|
216
|
+
* doesn't carry a readable list (defensive — never trust the wire shape blindly).
|
|
217
|
+
*/
|
|
218
|
+
function boardsOf(body) {
|
|
219
|
+
if (typeof body !== "object" || body === null)
|
|
220
|
+
return [];
|
|
221
|
+
const boards = body.boards;
|
|
222
|
+
return Array.isArray(boards) ? boards.filter((b) => typeof b === "string") : [];
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* DX-2920 — the ONE `board_unreadable` detail-line builder, shared by the mint
|
|
226
|
+
* 403 classification and the stream admission's identical 403, so the two can
|
|
227
|
+
* never drift into two different ideas of how to phrase "these boards".
|
|
228
|
+
*/
|
|
229
|
+
function boardUnreadableDetail(boards, fallback) {
|
|
230
|
+
return boards.length > 0
|
|
231
|
+
? `this session's dashboard credential cannot read board(s) ${boards.join(", ")} on the connected plan`
|
|
232
|
+
: fallback;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* DX-2920 (round 3) — `scope_narrowed`'s fix, built dynamically from the
|
|
236
|
+
* boards `listen.ts` parsed off the dashboard's own `end` payload (AC 30661:
|
|
237
|
+
* "naming the missing boards and how to widen scope"), replacing the static
|
|
238
|
+
* generic `STOP_FIXES` entry round 2 shipped before the server actually sent
|
|
239
|
+
* a board list.
|
|
240
|
+
*/
|
|
241
|
+
function scopeNarrowedFix(boards) {
|
|
242
|
+
return boards.length > 0
|
|
243
|
+
? `widen this session's dashboard credential to cover board(s) ${boards.join(", ")}, or connect a plan whose cards all live on boards it can read`
|
|
244
|
+
: "widen this session's dashboard credential to cover every board the connected plan's cards live on, or connect a plan whose cards all live on boards it can read";
|
|
182
245
|
}
|
|
183
246
|
/**
|
|
184
247
|
* One authenticated request, with a timeout, classifying the failures that are
|
|
185
|
-
* about THIS MOMENT (network, timeout, 408/429, 5xx) as transient. Shared by
|
|
186
|
-
*
|
|
248
|
+
* about THIS MOMENT (network, timeout, 408/429, 5xx) as transient. Shared by
|
|
249
|
+
* every request this module makes so they can never disagree about which
|
|
187
250
|
* failures are worth retrying.
|
|
188
251
|
*/
|
|
189
252
|
async function request(options, deps, what, url, init = { method: "GET" }) {
|
|
@@ -259,6 +322,19 @@ export async function mintTicket(options, deps) {
|
|
|
259
322
|
if (status === 409 && errorCodeOf(body) === "session_not_connected") {
|
|
260
323
|
return { kind: "terminal", reason: "not_connected", detail: "the session is not connected to a plan" };
|
|
261
324
|
}
|
|
325
|
+
// DX-2920 (AC 30660) — this credential IS accepted; it just cannot read every
|
|
326
|
+
// board the connected plan covers (`unreadableBoardsRefusal`, dashboard
|
|
327
|
+
// `plan-scope.ts`). Calling that `unauthorized` told the session to fix its
|
|
328
|
+
// credential, which was the wrong remedy for a scope problem — this is
|
|
329
|
+
// `board_unreadable`, naming the boards, checked BEFORE the generic 401/403
|
|
330
|
+
// fallback below so it never falls into it.
|
|
331
|
+
if (status === 403 && errorCodeOf(body) === "issuer_cannot_read_plan_boards") {
|
|
332
|
+
return {
|
|
333
|
+
kind: "terminal",
|
|
334
|
+
reason: "board_unreadable",
|
|
335
|
+
detail: boardUnreadableDetail(boardsOf(body), `ticket mint HTTP 403: issuer_cannot_read_plan_boards ${oneLine(text, 300)}`),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
262
338
|
if (status === 401 || status === 403) {
|
|
263
339
|
return { kind: "terminal", reason: "unauthorized", detail: `ticket mint HTTP ${status} ${oneLine(text, 300)}` };
|
|
264
340
|
}
|
|
@@ -277,121 +353,60 @@ export async function mintTicket(options, deps) {
|
|
|
277
353
|
leaseMs: ticket.leaseMs,
|
|
278
354
|
};
|
|
279
355
|
}
|
|
280
|
-
/** One card per board of the connected plan, read a page at a time. */
|
|
281
|
-
function cardsPageOf(body) {
|
|
282
|
-
if (typeof body !== "object" || body === null)
|
|
283
|
-
return "the body is not a JSON object";
|
|
284
|
-
const b = body;
|
|
285
|
-
if (!Array.isArray(b.cards))
|
|
286
|
-
return "cards is not an array";
|
|
287
|
-
if (typeof b.cards_total !== "number" || !Number.isSafeInteger(b.cards_total))
|
|
288
|
-
return "cards_total is not an integer";
|
|
289
|
-
const cards = [];
|
|
290
|
-
for (const card of b.cards) {
|
|
291
|
-
if (typeof card !== "object" || card === null)
|
|
292
|
-
return "a card is not an object";
|
|
293
|
-
const c = card;
|
|
294
|
-
if (typeof c.id !== "string" || typeof c.boardId !== "string")
|
|
295
|
-
return "a card has no id / boardId";
|
|
296
|
-
cards.push({ id: c.id, boardId: c.boardId });
|
|
297
|
-
}
|
|
298
|
-
return { cards, total: b.cards_total };
|
|
299
|
-
}
|
|
300
356
|
/**
|
|
301
|
-
*
|
|
357
|
+
* DX-2920 — a stream admission refusal (`listen.ts`'s STRUCTURED `refused`
|
|
358
|
+
* outcome — `{status, errorCode, body}`, parsed once in `connectOnce`) whose
|
|
359
|
+
* shape matches one the mint route already gives its OWN name to. Two cases:
|
|
302
360
|
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
306
|
-
*
|
|
307
|
-
*
|
|
308
|
-
*
|
|
361
|
+
* - `409 session_not_connected` — the SAME shape the mint route uses for "no
|
|
362
|
+
* plan connected" (`plan-session-stream.ts`, DX-2863 review finding M2). A
|
|
363
|
+
* session with no plan connected is the identical terminal state whether
|
|
364
|
+
* the dashboard says so at mint or at the stream's own admission check,
|
|
365
|
+
* and the session should see ONE remedy either way.
|
|
366
|
+
* - `403 issuer_cannot_read_plan_boards` — the SAME shape the mint route's
|
|
367
|
+
* board-coverage refusal uses (AC 30660's fix 4 — a ticket minted before a
|
|
368
|
+
* board became unreadable can still be refused ADMISSION for it later; that
|
|
369
|
+
* refusal deserves the same `board_unreadable` naming as the mint-time one,
|
|
370
|
+
* not a re-mint-and-retry loop that just hits the identical refusal again).
|
|
309
371
|
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
* (`withV2Handler` + `resolveIssueBoardId`). Deliberately NOT `GET /api/issues`
|
|
314
|
-
* or `GET /api/issues/:id`: neither checks the caller's board allowlist at all,
|
|
315
|
-
* so a check built on them would pass precisely where the stream drops events.
|
|
372
|
+
* Classifies by STATUS + ERROR CODE, never by re-deriving them from the
|
|
373
|
+
* flattened `detail` string — the second-source-of-truth shape this card's fix
|
|
374
|
+
* round closed (the regex-based `isSessionNotConnectedRefusal` it replaced).
|
|
316
375
|
*/
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
const outcome = await request(options, deps, "plan read", url);
|
|
323
|
-
if (outcome.kind === "transient")
|
|
324
|
-
return outcome;
|
|
325
|
-
const { status, text, body } = outcome;
|
|
326
|
-
if (status === 409 && errorCodeOf(body) === "session_not_connected") {
|
|
327
|
-
return { kind: "terminal", reason: "not_connected", detail: "the session is not connected to a plan" };
|
|
328
|
-
}
|
|
329
|
-
if (status === 401 || status === 403) {
|
|
330
|
-
return { kind: "terminal", reason: "unauthorized", detail: `plan read HTTP ${status} ${oneLine(text, 300)}` };
|
|
331
|
-
}
|
|
332
|
-
if (status < 200 || status >= 300) {
|
|
333
|
-
return { kind: "terminal", reason: "scope_check_failed", detail: `plan read HTTP ${status} ${oneLine(text, 300)}` };
|
|
334
|
-
}
|
|
335
|
-
const page = cardsPageOf(body);
|
|
336
|
-
if (typeof page === "string") {
|
|
337
|
-
return { kind: "terminal", reason: "scope_check_failed", detail: `plan read HTTP ${status}: ${page}` };
|
|
338
|
-
}
|
|
339
|
-
for (const card of page.cards) {
|
|
340
|
-
if (!firstCardPerBoard.has(card.boardId))
|
|
341
|
-
firstCardPerBoard.set(card.boardId, card.id);
|
|
342
|
-
}
|
|
343
|
-
offset += page.cards.length;
|
|
344
|
-
if (page.cards.length === 0 || offset >= page.total)
|
|
345
|
-
break;
|
|
376
|
+
function classifyAdmissionRefusal(refusal) {
|
|
377
|
+
if (refusal === undefined)
|
|
378
|
+
return null;
|
|
379
|
+
if (refusal.status === 409 && refusal.errorCode === "session_not_connected") {
|
|
380
|
+
return { reason: "not_connected", detail: "the session is not connected to a plan" };
|
|
346
381
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const outcome = await request(options, deps, `board read of ${boardId}`, url);
|
|
353
|
-
if (outcome.kind === "transient")
|
|
354
|
-
return outcome;
|
|
355
|
-
const { status, text } = outcome;
|
|
356
|
-
if (status === 403) {
|
|
357
|
-
return {
|
|
358
|
-
kind: "terminal",
|
|
359
|
-
reason: "board_unreadable",
|
|
360
|
-
detail: `this session's dashboard credential cannot read board ${boardId}, which the connected plan's card ` +
|
|
361
|
-
`${cardId} lives on — the event stream drops that board's events silently (${oneLine(text, 200)})`,
|
|
362
|
-
};
|
|
363
|
-
}
|
|
364
|
-
if (status === 401) {
|
|
365
|
-
return { kind: "terminal", reason: "unauthorized", detail: `board read of ${boardId} HTTP 401 ${oneLine(text, 200)}` };
|
|
366
|
-
}
|
|
367
|
-
if (status === 404) {
|
|
368
|
-
// The card moved or was deleted between the two reads. Nothing is wrong
|
|
369
|
-
// with the credential — re-read the plan rather than accuse it.
|
|
370
|
-
return { kind: "transient", detail: `card ${cardId} vanished between the plan read and the board read` };
|
|
371
|
-
}
|
|
372
|
-
if (status < 200 || status >= 300) {
|
|
373
|
-
return {
|
|
374
|
-
kind: "terminal",
|
|
375
|
-
reason: "scope_check_failed",
|
|
376
|
-
detail: `board read of ${boardId} HTTP ${status} ${oneLine(text, 200)}`,
|
|
377
|
-
};
|
|
378
|
-
}
|
|
382
|
+
if (refusal.status === 403 && refusal.errorCode === "issuer_cannot_read_plan_boards") {
|
|
383
|
+
return {
|
|
384
|
+
reason: "board_unreadable",
|
|
385
|
+
detail: boardUnreadableDetail(boardsOf(refusal.body), "this session's dashboard credential cannot read a board on the connected plan"),
|
|
386
|
+
};
|
|
379
387
|
}
|
|
380
|
-
return
|
|
388
|
+
return null;
|
|
381
389
|
}
|
|
382
390
|
/**
|
|
383
|
-
* Mint,
|
|
384
|
-
*
|
|
391
|
+
* Mint, stream, re-mint — until a terminal outcome, which it writes as the one
|
|
392
|
+
* `stopped` record. Returns 0 when another listener took over, 1 otherwise.
|
|
385
393
|
*/
|
|
386
394
|
export async function runBridge(options, deps) {
|
|
387
395
|
const delivered = options.resumeIds.slice(-DELIVERED_ID_MEMORY);
|
|
388
|
-
|
|
389
|
-
|
|
396
|
+
function stop(reason, detail, code, extra) {
|
|
397
|
+
if (reason === "scope_narrowed") {
|
|
398
|
+
if (extra?.boards === undefined) {
|
|
399
|
+
throw new Error('stop("scope_narrowed", ...) requires boards — unreachable through the exported overloads above');
|
|
400
|
+
}
|
|
401
|
+
deps.write({ type: "stopped", reason, detail, boards: extra.boards, fix: scopeNarrowedFix(extra.boards) });
|
|
402
|
+
return code;
|
|
403
|
+
}
|
|
404
|
+
deps.write({ type: "stopped", reason, detail, refusal: extra?.refusal, fix: extra?.fix ?? fixForStop(reason) });
|
|
390
405
|
return code;
|
|
391
|
-
}
|
|
406
|
+
}
|
|
392
407
|
let backoff = MINT_INITIAL_BACKOFF_MS;
|
|
393
408
|
let refusedInRow = 0;
|
|
394
|
-
let
|
|
409
|
+
let readyEmitted = false;
|
|
395
410
|
for (;;) {
|
|
396
411
|
const minted = await mintTicket(options, deps);
|
|
397
412
|
if (minted.kind === "terminal")
|
|
@@ -401,19 +416,13 @@ export async function runBridge(options, deps) {
|
|
|
401
416
|
backoff = Math.min(MINT_MAX_BACKOFF_MS, backoff * 2);
|
|
402
417
|
continue;
|
|
403
418
|
}
|
|
404
|
-
//
|
|
405
|
-
//
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
await deps.sleep(backoff);
|
|
412
|
-
backoff = Math.min(MINT_MAX_BACKOFF_MS, backoff * 2);
|
|
413
|
-
continue;
|
|
414
|
-
}
|
|
415
|
-
verified = true;
|
|
416
|
-
deps.write({ type: "ready", boards: scope.boards });
|
|
419
|
+
// DX-2920 — `ready` fires once, on the FIRST successful mint, now that
|
|
420
|
+
// board reach is proven by the dashboard's own mint refusal rather than a
|
|
421
|
+
// client-side check run here (see the module docblock + the deleted
|
|
422
|
+
// `verifyPlanBoardsReadable`). A re-mint (a lapsed lease) never repeats it.
|
|
423
|
+
if (!readyEmitted) {
|
|
424
|
+
readyEmitted = true;
|
|
425
|
+
deps.write({ type: "ready" });
|
|
417
426
|
}
|
|
418
427
|
backoff = MINT_INITIAL_BACKOFF_MS;
|
|
419
428
|
const run = { stopped: null, emitted: false };
|
|
@@ -437,12 +446,28 @@ export async function runBridge(options, deps) {
|
|
|
437
446
|
const stopped = run.stopped;
|
|
438
447
|
if (stopped === null)
|
|
439
448
|
throw new Error("the stream reader ended without a stop record");
|
|
440
|
-
|
|
449
|
+
// DX-2920 (round 4) — direct equality, not `TAKEOVER_REASONS.has(...)`:
|
|
450
|
+
// `Set.has()` is a runtime check only, so it cannot narrow `stopped.reason`
|
|
451
|
+
// for the compiler — leaving it a `Set` lookup here would keep every
|
|
452
|
+
// downstream branch's exhaustive narrowing (which is what makes the final
|
|
453
|
+
// fallthrough's `stop(stopped.reason, ...)` call type-check against the
|
|
454
|
+
// closed `ListenStopReason` overload) from working.
|
|
455
|
+
if (stopped.reason === "superseded" || stopped.reason === "replaced")
|
|
441
456
|
return stop(stopped.reason, stopped.detail, 0);
|
|
442
457
|
if (stopped.reason === "lease_expired") {
|
|
443
458
|
refusedInRow = 0;
|
|
444
459
|
continue;
|
|
445
460
|
}
|
|
461
|
+
if (stopped.reason === "refused") {
|
|
462
|
+
const classified = classifyAdmissionRefusal(stopped.refusal);
|
|
463
|
+
if (classified !== null) {
|
|
464
|
+
// DX-2920 — a NAMED admission refusal is terminal at once, exactly
|
|
465
|
+
// like its mint-time counterpart — never counted toward the generic
|
|
466
|
+
// refused-ticket retry budget below, which exists for an admission
|
|
467
|
+
// refusal with no more specific explanation than "not admitted".
|
|
468
|
+
return stop(classified.reason, classified.detail, 1);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
446
471
|
if (stopped.reason === "refused") {
|
|
447
472
|
const provedHealthy = run.emitted || deps.now() - startedAt >= HEALTHY_CONNECTION_MS;
|
|
448
473
|
refusedInRow = provedHealthy ? 1 : refusedInRow + 1;
|
|
@@ -451,6 +476,15 @@ export async function runBridge(options, deps) {
|
|
|
451
476
|
}
|
|
452
477
|
continue;
|
|
453
478
|
}
|
|
479
|
+
if (stopped.reason === "scope_narrowed") {
|
|
480
|
+
// DX-2920 (round 4) — `stopped.boards` is REQUIRED at the type level now
|
|
481
|
+
// (`ListenStopped`'s `scope_narrowed` member), populated by `listen.ts`'s
|
|
482
|
+
// parse of the dashboard's own `end` payload (never a re-derivation from
|
|
483
|
+
// `detail`) — no `?? []`, no optional check, `stopped.boards` IS
|
|
484
|
+
// `string[]` once narrowed to this branch.
|
|
485
|
+
const boards = stopped.boards;
|
|
486
|
+
return stop("scope_narrowed", boardUnreadableDetail(boards, stopped.detail), 1, { boards });
|
|
487
|
+
}
|
|
454
488
|
return stop(stopped.reason, stopped.detail, 1);
|
|
455
489
|
}
|
|
456
490
|
}
|
package/dist/index.js
CHANGED
|
@@ -94,6 +94,7 @@
|
|
|
94
94
|
*/
|
|
95
95
|
import { isEntrypointModule } from "./entrypoint.js";
|
|
96
96
|
import { BRIDGE_SUBCOMMAND, runBridgeCommand } from "./bridge.js";
|
|
97
|
+
import { PLAN_STATE_SUBCOMMAND, runPlanStateCommand } from "./plan-state.js";
|
|
97
98
|
import { resolveDeclaredCredential } from "./credential.js";
|
|
98
99
|
import { recordSessionConnectionAfterConnect } from "./session-connection.js";
|
|
99
100
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -881,16 +882,25 @@ async function main() {
|
|
|
881
882
|
// symlink-aware (DX-1647) so it holds under the symlinked `npx` bin the worker
|
|
882
883
|
// spawns, not just a direct `node dist/index.js`.
|
|
883
884
|
//
|
|
884
|
-
// `bridge`
|
|
885
|
-
// plugin's plan event bridge runs. It never
|
|
886
|
-
// input is `CLAUDE_CODE_SESSION_ID` (read from
|
|
887
|
-
// `--resume-ids` — the dashboard URL, credential source,
|
|
888
|
-
// come from the session-connection record this server's
|
|
889
|
-
// wrote (`session-connection.ts`), never from the bridge's
|
|
890
|
-
// (DX-2862: a bridge trusting its own ambient
|
|
891
|
-
// exact bug this repo fixed).
|
|
892
|
-
//
|
|
893
|
-
//
|
|
885
|
+
// `bridge` and `plan-state` are the two subcommands. `bridge` is the session
|
|
886
|
+
// event stream client the danxbot plugin's plan event bridge runs. It never
|
|
887
|
+
// boots the MCP server; its only input is `CLAUDE_CODE_SESSION_ID` (read from
|
|
888
|
+
// its environment) plus `--resume-ids` — the dashboard URL, credential source,
|
|
889
|
+
// and credential itself come from the session-connection record this server's
|
|
890
|
+
// own `plan_connect` wrote (`session-connection.ts`), never from the bridge's
|
|
891
|
+
// own environment (DX-2862: a bridge trusting its own ambient
|
|
892
|
+
// `DANXBOT_DISPATCH_TOKEN` is the exact bug this repo fixed).
|
|
893
|
+
//
|
|
894
|
+
// `plan-state` (DX-2921) is the ONE-SHOT client of
|
|
895
|
+
// `GET /api/plan-sessions/me/turn-state`, run by the DX-2888 plugin's
|
|
896
|
+
// turn-start / turn-end hooks — see `plan-state.ts`'s own doc comment for the
|
|
897
|
+
// full contract. It ALWAYS exits 0 (success or failure alike: the hook must
|
|
898
|
+
// stay silent), so even an unexpected rejection here is caught and reported
|
|
899
|
+
// the same `{ok:false, reason}` way rather than propagating a non-zero exit
|
|
900
|
+
// or an uncaught stack trace into the hook.
|
|
901
|
+
//
|
|
902
|
+
// Any OTHER argument is refused rather than ignored, so a typo cannot
|
|
903
|
+
// silently start an MCP server on stdio where a subcommand was meant to run.
|
|
894
904
|
if (isEntrypointModule(import.meta.url, process.argv[1])) {
|
|
895
905
|
const [subcommand, ...rest] = process.argv.slice(2);
|
|
896
906
|
if (subcommand === BRIDGE_SUBCOMMAND) {
|
|
@@ -899,8 +909,16 @@ if (isEntrypointModule(import.meta.url, process.argv[1])) {
|
|
|
899
909
|
process.exit(1);
|
|
900
910
|
});
|
|
901
911
|
}
|
|
912
|
+
else if (subcommand === PLAN_STATE_SUBCOMMAND) {
|
|
913
|
+
runPlanStateCommand(rest).then((code) => process.exit(code), (err) => {
|
|
914
|
+
console.error(`[danx-dashboard-mcp] plan-state fatal: ${err.message}`);
|
|
915
|
+
process.stdout.write(`${JSON.stringify({ ok: false, reason: "fatal" })}\n`);
|
|
916
|
+
process.exit(0);
|
|
917
|
+
});
|
|
918
|
+
}
|
|
902
919
|
else if (subcommand !== undefined) {
|
|
903
|
-
console.error(`[danx-dashboard-mcp] unknown subcommand "${subcommand}" (the only
|
|
920
|
+
console.error(`[danx-dashboard-mcp] unknown subcommand "${subcommand}" (the only ones are ` +
|
|
921
|
+
`"${BRIDGE_SUBCOMMAND}" and "${PLAN_STATE_SUBCOMMAND}")`);
|
|
904
922
|
process.exit(2);
|
|
905
923
|
}
|
|
906
924
|
else {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DX-2920 — the ONE place that reads a JSON body's top-level `.error` string.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS EXISTS. `bridge.ts` (classifying a mint refusal) and `listen.ts`
|
|
5
|
+
* (classifying a stream admission refusal) both need to answer "what error
|
|
6
|
+
* code did this JSON body carry", and before this card each answered it a
|
|
7
|
+
* different way: `bridge.ts` parsed the body directly, `listen.ts` never
|
|
8
|
+
* looked past a flattened, human-readable detail string at all — a caller
|
|
9
|
+
* that wanted to react to a SPECIFIC refusal (the admission-time 409 the
|
|
10
|
+
* mint route also uses) had to regex-scrape that flattened string back apart,
|
|
11
|
+
* a second, fragile source of truth for the same fact. This module is generic
|
|
12
|
+
* — it knows nothing about "session_not_connected" or "issuer_cannot_read_plan_boards",
|
|
13
|
+
* only that a JSON object may carry a top-level string field named `error` —
|
|
14
|
+
* so it can live in BOTH the domain-aware `bridge.ts` and the deliberately
|
|
15
|
+
* generic `listen.ts` (whose own docblock states it carries no domain
|
|
16
|
+
* knowledge of the dashboard's specific error shapes) without either one
|
|
17
|
+
* importing the other.
|
|
18
|
+
*/
|
|
19
|
+
export function errorCodeOf(body) {
|
|
20
|
+
return typeof body === "object" && body !== null && typeof body.error === "string"
|
|
21
|
+
? body.error
|
|
22
|
+
: null;
|
|
23
|
+
}
|
package/dist/listen.js
CHANGED
|
@@ -12,9 +12,27 @@
|
|
|
12
12
|
* `text` is what the session reads; an event it cannot read still produces one
|
|
13
13
|
* (`could not read event …`), never silence. `id` is `null` only for a frame
|
|
14
14
|
* that carried no usable id.
|
|
15
|
-
* - `{type:"stopped", reason, detail}` — once, last. `reason`
|
|
16
|
-
* own end reason (`superseded`, `replaced`, `revoked
|
|
17
|
-
*
|
|
15
|
+
* - `{type:"stopped", reason, detail, refusal?, boards?}` — once, last. `reason`
|
|
16
|
+
* is the dashboard's own end reason (`superseded`, `replaced`, `revoked`,
|
|
17
|
+
* `scope_narrowed`, `not_connected`), `refused` (the ticket was not
|
|
18
|
+
* admitted), `bad_end_payload` (a `scope_narrowed` end whose `boards` array
|
|
19
|
+
* was missing/invalid — a protocol error, never silently downgraded), or
|
|
20
|
+
* `lease_expired` (no healthy connection for the lease). DX-2920 —
|
|
21
|
+
* `refusal` is populated ONLY for `reason === "refused"`: `{status,
|
|
22
|
+
* errorCode, body}`, the admission response parsed ONCE here, so a
|
|
23
|
+
* consumer can recognize a SPECIFIC refusal (the dashboard's own
|
|
24
|
+
* `409 session_not_connected`, the same shape the mint route uses) by
|
|
25
|
+
* status + error code rather than re-deriving it from the flattened
|
|
26
|
+
* `detail` string. `boards` is REQUIRED (round 4 — a discriminated union,
|
|
27
|
+
* not an optional field: see `ListenStopped` / `ListenStopReason`) for
|
|
28
|
+
* `reason === "scope_narrowed"` and absent for every other reason, parsed
|
|
29
|
+
* from the dashboard's `end` payload the SAME way `reason` itself is
|
|
30
|
+
* parsed — never re-derived from `detail`. A wire `reason` value this
|
|
31
|
+
* build does not recognize (a newer dashboard's reason an older bridge
|
|
32
|
+
* hasn't shipped yet) normalizes to `"unknown"` rather than passing the
|
|
33
|
+
* raw string through, so the closed set stays closed — `fixForStop`'s
|
|
34
|
+
* generic `DEFAULT_STOP_FIX` handles it exactly as it already handled a
|
|
35
|
+
* verbatim unrecognized string.
|
|
18
36
|
* - nothing for keep-alives, the connect marker, or a successful reconnect.
|
|
19
37
|
*
|
|
20
38
|
* RECONNECT AND RESUME. The stream drops whenever the dashboard restarts, and can
|
|
@@ -32,6 +50,7 @@
|
|
|
32
50
|
* (`src/issues/db/issue-activity.ts`); this published package cannot import
|
|
33
51
|
* danxbot source.
|
|
34
52
|
*/
|
|
53
|
+
import { errorCodeOf } from "./json-body.js";
|
|
35
54
|
import { oneLine } from "./one-line.js";
|
|
36
55
|
export const INITIAL_BACKOFF_MS = 1_000;
|
|
37
56
|
export const MAX_BACKOFF_MS = 30_000;
|
|
@@ -181,6 +200,23 @@ function parseBlock(block) {
|
|
|
181
200
|
}
|
|
182
201
|
return sawField ? { id, event, data: data.join("\n") } : null;
|
|
183
202
|
}
|
|
203
|
+
/**
|
|
204
|
+
* DX-2920 (round 4) — the dashboard's own `StreamEndReason` values this
|
|
205
|
+
* client recognizes on the wire, EXCLUDING `scope_narrowed` (parsed by its own
|
|
206
|
+
* dedicated branch in `handle()` below, since it alone carries `boards`).
|
|
207
|
+
* Hand-copied from `StreamEndReason` in `src/issues/plan-session-listeners.ts`
|
|
208
|
+
* — this published package cannot import danxbot source. A wire `reason` this
|
|
209
|
+
* set does not contain (a newer dashboard's reason this build predates)
|
|
210
|
+
* normalizes to `"unknown"` rather than passing the raw string through, which
|
|
211
|
+
* is what lets `Outcome`'s `reason` field below be a closed union instead of
|
|
212
|
+
* `string` — see `ListenStopReason`'s docblock for why that closure is what
|
|
213
|
+
* makes the `scope_narrowed`-requires-`boards` invariant an actual compile
|
|
214
|
+
* error rather than a comment's promise.
|
|
215
|
+
*/
|
|
216
|
+
const KNOWN_WIRE_END_REASONS = new Set(["superseded", "replaced", "revoked", "not_connected"]);
|
|
217
|
+
function isKnownWireEndReason(reason) {
|
|
218
|
+
return KNOWN_WIRE_END_REASONS.has(reason);
|
|
219
|
+
}
|
|
184
220
|
/** Statuses that describe the moment, not the ticket — retry them. */
|
|
185
221
|
const RETRYABLE_CLIENT_STATUSES = new Set([408, 429]);
|
|
186
222
|
/**
|
|
@@ -201,14 +237,55 @@ export async function runListener(options, deps) {
|
|
|
201
237
|
};
|
|
202
238
|
for (const id of options.resumeIds.slice(-DELIVERED_ID_MEMORY))
|
|
203
239
|
remember(id);
|
|
204
|
-
|
|
205
|
-
|
|
240
|
+
function stop(reason, detail, code, extra) {
|
|
241
|
+
if (reason === "scope_narrowed") {
|
|
242
|
+
if (extra?.boards === undefined) {
|
|
243
|
+
throw new Error('stop("scope_narrowed", ...) requires boards — unreachable through the exported overloads above');
|
|
244
|
+
}
|
|
245
|
+
deps.write({ type: "stopped", reason, detail, boards: extra.boards });
|
|
246
|
+
return code;
|
|
247
|
+
}
|
|
248
|
+
deps.write({ type: "stopped", reason, detail, refusal: extra?.refusal });
|
|
206
249
|
return code;
|
|
207
|
-
}
|
|
250
|
+
}
|
|
208
251
|
const handle = (message) => {
|
|
209
252
|
if (message.event === "end") {
|
|
210
|
-
|
|
211
|
-
|
|
253
|
+
// DX-2920 (round 3) — a JSON.parse failure here falls through to the
|
|
254
|
+
// pre-existing "unknown" reason below via `isRecord(null)`, unchanged
|
|
255
|
+
// from before this round. Only a `scope_narrowed` reason additionally
|
|
256
|
+
// REQUIRES a valid `boards` string array (matching the server's `end`
|
|
257
|
+
// overload, which cannot emit `scope_narrowed` without one) — a
|
|
258
|
+
// `scope_narrowed` frame that fails that check is a PROTOCOL error
|
|
259
|
+
// (a server too old to have sent boards, or a corrupted frame), never
|
|
260
|
+
// silently downgraded to the generic "the dashboard ended this
|
|
261
|
+
// listener" message the caller cannot act on.
|
|
262
|
+
let parsed;
|
|
263
|
+
try {
|
|
264
|
+
parsed = JSON.parse(message.data);
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
parsed = null;
|
|
268
|
+
}
|
|
269
|
+
const reasonRaw = isRecord(parsed) ? parsed.reason : undefined;
|
|
270
|
+
const reason = typeof reasonRaw === "string" ? reasonRaw : "unknown";
|
|
271
|
+
if (reason === "scope_narrowed") {
|
|
272
|
+
const boardsRaw = isRecord(parsed) ? parsed.boards : undefined;
|
|
273
|
+
const boards = Array.isArray(boardsRaw) && boardsRaw.length > 0 && boardsRaw.every((b) => typeof b === "string")
|
|
274
|
+
? boardsRaw
|
|
275
|
+
: null;
|
|
276
|
+
if (boards === null) {
|
|
277
|
+
return { kind: "ended", reason: "bad_end_payload" };
|
|
278
|
+
}
|
|
279
|
+
return { kind: "ended", reason, boards };
|
|
280
|
+
}
|
|
281
|
+
// DX-2920 (round 4) — a wire reason this build does not recognize (a
|
|
282
|
+
// newer dashboard's reason an older bridge hasn't shipped yet)
|
|
283
|
+
// normalizes to "unknown" rather than passing the raw string through:
|
|
284
|
+
// `Outcome`'s "ended" reason is now a closed set (`EndedReason`), and an
|
|
285
|
+
// open passthrough here would be exactly the hole that lets a
|
|
286
|
+
// missing-`boards` "scope_narrowed" construction slip past the compiler
|
|
287
|
+
// elsewhere — see `ListenStopReason`'s docblock.
|
|
288
|
+
return { kind: "ended", reason: isKnownWireEndReason(reason) ? reason : "unknown" };
|
|
212
289
|
}
|
|
213
290
|
if (message.event !== "activity")
|
|
214
291
|
return null;
|
|
@@ -262,7 +339,25 @@ export async function runListener(options, deps) {
|
|
|
262
339
|
armIdle();
|
|
263
340
|
const response = await deps.fetch(options.streamUrl, { headers, signal: controller.signal });
|
|
264
341
|
if (response.status >= 400 && response.status < 500 && !RETRYABLE_CLIENT_STATUSES.has(response.status)) {
|
|
265
|
-
|
|
342
|
+
const text = await response.text();
|
|
343
|
+
// DX-2920 — parsed ONCE, here, into a structured outcome a consumer can
|
|
344
|
+
// classify by status + error code (`bridge.ts` does, matching a specific
|
|
345
|
+
// admission refusal such as the dashboard's own `409 session_not_connected`)
|
|
346
|
+
// rather than re-deriving it from the flattened `detail` string below.
|
|
347
|
+
let body = null;
|
|
348
|
+
try {
|
|
349
|
+
body = text === "" ? null : JSON.parse(text);
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
body = null;
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
kind: "refused",
|
|
356
|
+
status: response.status,
|
|
357
|
+
errorCode: errorCodeOf(body),
|
|
358
|
+
body,
|
|
359
|
+
detail: `HTTP ${response.status} ${oneLine(text, 300)}`,
|
|
360
|
+
};
|
|
266
361
|
}
|
|
267
362
|
if (!response.ok || response.body === null) {
|
|
268
363
|
await response.body?.cancel();
|
|
@@ -296,10 +391,23 @@ export async function runListener(options, deps) {
|
|
|
296
391
|
if (outcome.reason === "superseded" || outcome.reason === "replaced") {
|
|
297
392
|
return stop(outcome.reason, "another listener for this session took over", 0);
|
|
298
393
|
}
|
|
394
|
+
if (outcome.reason === "bad_end_payload") {
|
|
395
|
+
return stop("bad_end_payload", "the dashboard's scope_narrowed end event carried no valid boards array — this is a protocol error, not an ordinary end", 1);
|
|
396
|
+
}
|
|
397
|
+
// DX-2920 (round 4) — split explicitly rather than the old conditional
|
|
398
|
+
// `outcome.boards === undefined ? undefined : {boards}` pass-through:
|
|
399
|
+
// `Outcome`'s "ended" kind is now itself discriminated on `reason`, so
|
|
400
|
+
// `outcome.boards` is GUARANTEED present here (no `?? []`, no optional
|
|
401
|
+
// check needed) once narrowed to `"scope_narrowed"`.
|
|
402
|
+
if (outcome.reason === "scope_narrowed") {
|
|
403
|
+
return stop("scope_narrowed", "the dashboard ended this listener", 1, { boards: outcome.boards });
|
|
404
|
+
}
|
|
299
405
|
return stop(outcome.reason, "the dashboard ended this listener", 1);
|
|
300
406
|
}
|
|
301
407
|
if (outcome.kind === "refused") {
|
|
302
|
-
return stop("refused", `the dashboard refused the listener ticket: ${outcome.detail}`, 1
|
|
408
|
+
return stop("refused", `the dashboard refused the listener ticket: ${outcome.detail}`, 1, {
|
|
409
|
+
refusal: { status: outcome.status, errorCode: outcome.errorCode, body: outcome.body },
|
|
410
|
+
});
|
|
303
411
|
}
|
|
304
412
|
if (outcome.healthy) {
|
|
305
413
|
unhealthySince = null;
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `danx-dashboard-mcp plan-state` — the ONE-SHOT client of
|
|
3
|
+
* `GET /api/plan-sessions/me/turn-state` (DX-2921).
|
|
4
|
+
*
|
|
5
|
+
* WHO RUNS IT. The danxbot Claude Code plugin's DX-2888 turn-start /
|
|
6
|
+
* turn-end hooks, via the plugin's existing `bridgeCommand()` npx path — the
|
|
7
|
+
* SAME package pin, no separate install, no deep import of this package's
|
|
8
|
+
* `dist/` internals (that was DX-2921's whole reason to exist: the DX-2888
|
|
9
|
+
* architecture review found the first build of this logic vendored a private
|
|
10
|
+
* copy of the MCP package and hardcoded the dashboard HTTP contract inside
|
|
11
|
+
* the PLUGIN). The plugin decides what to DO with the answer (inject plan
|
|
12
|
+
* numbers at turn start, refuse to let a turn end while the session could
|
|
13
|
+
* legally start work and has nothing running); this module only fetches it.
|
|
14
|
+
*
|
|
15
|
+
* THE CONTRACT (agreed with the DX-2888 plugin side, issue comment 4245 on
|
|
16
|
+
* DX-2921 — binding, because the plugin is already built against it):
|
|
17
|
+
* - print EXACTLY ONE JSON line on stdout, and ALWAYS exit 0 — success or
|
|
18
|
+
* failure alike, because the hook must stay silent rather than spam the
|
|
19
|
+
* session's own turn with a stack trace;
|
|
20
|
+
* - a session that is not connected to a plan prints
|
|
21
|
+
* `{"ok":false,"reason":"session_not_connected"}` — that EXACT literal,
|
|
22
|
+
* because the plugin keys its no-log-spam rule on it (it is also the
|
|
23
|
+
* dashboard's own 409 error code for this case — see
|
|
24
|
+
* `requireConnectedPlanId`, `plan-session-context.ts`);
|
|
25
|
+
* - on success, every count is a finite number, `plan` carries `id` +
|
|
26
|
+
* `name`, and every `startable` / `held` entry carries a string `id` +
|
|
27
|
+
* `title` — the plugin rejects anything else as `bad_response`, so this
|
|
28
|
+
* module validates the server's response BEFORE printing it, rather than
|
|
29
|
+
* trusting a 200 status to mean a well-shaped body;
|
|
30
|
+
* - human-readable diagnostics go to stderr only, never stdout.
|
|
31
|
+
*
|
|
32
|
+
* THE CREDENTIAL — the SAME resolver `bridge` uses (DX-2862 / DX-2921 AC),
|
|
33
|
+
* via `resolveBridgeOptions` (`bridge.ts`): the dashboard URL, credential
|
|
34
|
+
* source and credential all come from the connection record this session's
|
|
35
|
+
* OWN danx-dashboard MCP server wrote on its last successful `plan_connect`
|
|
36
|
+
* (`session-connection.ts`), never from this process's own ambient env. That
|
|
37
|
+
* is deliberate here for the identical reason it is deliberate for `bridge`:
|
|
38
|
+
* a hook process trusting whatever `DANXBOT_DISPATCH_TOKEN` happens to be in
|
|
39
|
+
* its environment is precisely the DX-2862 bug (a hook's ambient credential
|
|
40
|
+
* silently pointed at a different dashboard from the one the session's tools
|
|
41
|
+
* actually use).
|
|
42
|
+
*
|
|
43
|
+
* A HARD TIMEOUT (AC 30672) — `PLAN_STATE_REQUEST_TIMEOUT_MS`. This call
|
|
44
|
+
* blocks a turn boundary the plugin is holding open, so it must never hang:
|
|
45
|
+
* a slow or wedged dashboard is `{ok:false, reason:"timeout"}`, not a stuck
|
|
46
|
+
* hook.
|
|
47
|
+
*/
|
|
48
|
+
import { SESSION_ID_HEADER, resolveBridgeOptions } from "./bridge.js";
|
|
49
|
+
export const PLAN_STATE_SUBCOMMAND = "plan-state";
|
|
50
|
+
export const TURN_STATE_PATH = "/api/plan-sessions/me/turn-state";
|
|
51
|
+
/** How long this one-shot call may take before it counts as a timeout. */
|
|
52
|
+
export const PLAN_STATE_REQUEST_TIMEOUT_MS = 5_000;
|
|
53
|
+
const USAGE = `usage: CLAUDE_CODE_SESSION_ID=<session-id> danx-dashboard-mcp ${PLAN_STATE_SUBCOMMAND}`;
|
|
54
|
+
function errorCodeOf(body) {
|
|
55
|
+
return typeof body === "object" && body !== null && typeof body.error === "string"
|
|
56
|
+
? body.error
|
|
57
|
+
: null;
|
|
58
|
+
}
|
|
59
|
+
function isFiniteNumber(v) {
|
|
60
|
+
return typeof v === "number" && Number.isFinite(v);
|
|
61
|
+
}
|
|
62
|
+
function isCardRef(v) {
|
|
63
|
+
return (typeof v === "object" &&
|
|
64
|
+
v !== null &&
|
|
65
|
+
typeof v.id === "string" &&
|
|
66
|
+
typeof v.title === "string");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The strict shape check the contract pins (comment 4245): finite counts, a
|
|
70
|
+
* `plan` with `id` + `name`, and a string `id` + `title` on every
|
|
71
|
+
* `startable` / `held` entry. `null` on anything short of that — a 200 whose
|
|
72
|
+
* body does not match is `bad_response`, exactly like a non-2xx.
|
|
73
|
+
*/
|
|
74
|
+
export function parseTurnStateBody(body) {
|
|
75
|
+
if (typeof body !== "object" || body === null)
|
|
76
|
+
return null;
|
|
77
|
+
const b = body;
|
|
78
|
+
const plan = b.plan;
|
|
79
|
+
if (typeof plan !== "object" || plan === null)
|
|
80
|
+
return null;
|
|
81
|
+
const p = plan;
|
|
82
|
+
if (!isFiniteNumber(p.id) || typeof p.name !== "string")
|
|
83
|
+
return null;
|
|
84
|
+
const counts = b.counts;
|
|
85
|
+
if (typeof counts !== "object" || counts === null)
|
|
86
|
+
return null;
|
|
87
|
+
const c = counts;
|
|
88
|
+
if (!isFiniteNumber(c.open) || !isFiniteNumber(c.inProgress) || !isFiniteNumber(c.needsYou))
|
|
89
|
+
return null;
|
|
90
|
+
if (!Array.isArray(b.startable) || !b.startable.every(isCardRef))
|
|
91
|
+
return null;
|
|
92
|
+
if (!Array.isArray(b.held) || !b.held.every(isCardRef))
|
|
93
|
+
return null;
|
|
94
|
+
return {
|
|
95
|
+
plan: { id: p.id, name: p.name },
|
|
96
|
+
counts: { open: c.open, inProgress: c.inProgress, needsYou: c.needsYou },
|
|
97
|
+
startable: b.startable,
|
|
98
|
+
held: b.held,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* One authenticated GET, with a hard timeout, classified into the output
|
|
103
|
+
* shape this subcommand always prints — never a throw, never a non-2xx
|
|
104
|
+
* bubbling past this function.
|
|
105
|
+
*/
|
|
106
|
+
export async function fetchTurnState(options, deps) {
|
|
107
|
+
const controller = new AbortController();
|
|
108
|
+
const timer = setTimeout(() => controller.abort(), deps.requestTimeoutMs);
|
|
109
|
+
let status;
|
|
110
|
+
let text;
|
|
111
|
+
try {
|
|
112
|
+
try {
|
|
113
|
+
const response = await deps.fetch(`${options.dashboardUrl}${TURN_STATE_PATH}`, {
|
|
114
|
+
method: "GET",
|
|
115
|
+
headers: {
|
|
116
|
+
Authorization: `Bearer ${options.token}`,
|
|
117
|
+
Accept: "application/json",
|
|
118
|
+
[SESSION_ID_HEADER]: options.sessionId,
|
|
119
|
+
},
|
|
120
|
+
signal: controller.signal,
|
|
121
|
+
});
|
|
122
|
+
status = response.status;
|
|
123
|
+
text = await response.text();
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
return { ok: false, reason: controller.signal.aborted ? "timeout" : "request_failed" };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
}
|
|
132
|
+
let body = null;
|
|
133
|
+
try {
|
|
134
|
+
body = text === "" ? null : JSON.parse(text);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return { ok: false, reason: "bad_response" };
|
|
138
|
+
}
|
|
139
|
+
// The exact literal the plugin's no-log-spam rule keys on (AC 30672 /
|
|
140
|
+
// comment 4245) — the dashboard's own 409 error code for an unconnected
|
|
141
|
+
// session, passed through verbatim rather than renamed.
|
|
142
|
+
if (status === 409 && errorCodeOf(body) === "session_not_connected") {
|
|
143
|
+
return { ok: false, reason: "session_not_connected" };
|
|
144
|
+
}
|
|
145
|
+
if (status === 401 || status === 403) {
|
|
146
|
+
return { ok: false, reason: "unauthorized" };
|
|
147
|
+
}
|
|
148
|
+
if (status < 200 || status >= 300) {
|
|
149
|
+
return { ok: false, reason: "http_error" };
|
|
150
|
+
}
|
|
151
|
+
const parsed = parseTurnStateBody(body);
|
|
152
|
+
if (parsed === null) {
|
|
153
|
+
return { ok: false, reason: "bad_response" };
|
|
154
|
+
}
|
|
155
|
+
return { ok: true, ...parsed };
|
|
156
|
+
}
|
|
157
|
+
/** The bin's `plan-state` subcommand, wired to the real process. Always resolves to exit code 0. */
|
|
158
|
+
export async function runPlanStateCommand(argv, env = process.env,
|
|
159
|
+
/** Test seam: the home the session's connection record is read from. */
|
|
160
|
+
resolveFrom = {}) {
|
|
161
|
+
const write = (output) => {
|
|
162
|
+
process.stdout.write(`${JSON.stringify(output)}\n`);
|
|
163
|
+
};
|
|
164
|
+
if (argv.length !== 0) {
|
|
165
|
+
// A malformed invocation is still a "the hook must stay silent" failure,
|
|
166
|
+
// not a crash — same ok:false/exit-0 contract as every other failure
|
|
167
|
+
// path here, with the usage line reserved for a human reading stderr.
|
|
168
|
+
write({ ok: false, reason: "usage" });
|
|
169
|
+
process.stderr.write(`${USAGE}\n`);
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
172
|
+
const sessionId = env.CLAUDE_CODE_SESSION_ID;
|
|
173
|
+
if (!sessionId) {
|
|
174
|
+
write({ ok: false, reason: "no_session_id" });
|
|
175
|
+
process.stderr.write(`${USAGE}\n`);
|
|
176
|
+
return 0;
|
|
177
|
+
}
|
|
178
|
+
let options;
|
|
179
|
+
try {
|
|
180
|
+
options = resolveBridgeOptions({ sessionId, resumeIds: [] }, env, resolveFrom);
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
const start = err;
|
|
184
|
+
write({ ok: false, reason: start.reason });
|
|
185
|
+
process.stderr.write(`${start.reason}: ${start.message}. Fix: ${start.fix}.\n`);
|
|
186
|
+
return 0;
|
|
187
|
+
}
|
|
188
|
+
const output = await fetchTurnState(options, {
|
|
189
|
+
fetch: (input, init) => fetch(input, init),
|
|
190
|
+
requestTimeoutMs: PLAN_STATE_REQUEST_TIMEOUT_MS,
|
|
191
|
+
});
|
|
192
|
+
write(output);
|
|
193
|
+
return 0;
|
|
194
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thehammer/danx-dashboard-mcp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.82",
|
|
4
4
|
"description": "Stdio MCP server wrapping danxbot's dashboard /api/issues/* normalized DB-backed HTTP routes for dispatched agents (DX-704 Phase 2).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|