@thehammer/danx-dashboard-mcp 0.1.172 → 0.1.175

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.
@@ -1,12 +1,12 @@
1
1
  /**
2
- * `danx-dashboard-mcp background-work <count|clear>` — the ONE-SHOT client of
2
+ * `danx-dashboard-mcp background-work <count|clear> <event-at>` — the ONE-SHOT client of
3
3
  * `PUT /api/plan-sessions/me/background-work` (DX-3367).
4
4
  *
5
5
  * WHO RUNS IT. The danxbot Claude Code plugin's `Stop` / `SubagentStop` /
6
6
  * `SessionStart` / `StopFailure` hooks (`danxbot/hooks/hooks.json` in
7
7
  * claude-plugins), via the SAME `npx -y @thehammer/danx-dashboard-mcp`
8
- * MECHANISM the plugin already uses for `bridge` and `plan-state` — no
9
- * separate install, no deep import of this package's `dist/` internals.
8
+ * MECHANISM the plugin already uses for `bridge` — no separate install, no
9
+ * deep import of this package's `dist/` internals.
10
10
  * DX-3367 fix-up — that does NOT mean the SAME PINNED VERSION: `npx -y
11
11
  * <pkg>` resolves whatever version string that ONE hook's own invocation
12
12
  * names, and this plugin's hooks pin each call independently (verified
@@ -18,9 +18,8 @@
18
18
  * sending `clear` on `SessionStart`/`StopFailure`); this module only
19
19
  * delivers the report.
20
20
  *
21
- * THE CONTRACT, mirroring `plan-state.ts`'s (binding the same way, so a
22
- * future plugin build against this module can trust it without re-reading
23
- * this file):
21
+ * THE CONTRACT (binding, so a future plugin build against this module can
22
+ * trust it without re-reading this file):
24
23
  * - print EXACTLY ONE JSON line on stdout, and ALWAYS exit 0 — success or
25
24
  * failure alike, because a hook must stay silent rather than spam the
26
25
  * session's own turn with a stack trace;
@@ -29,34 +28,39 @@
29
28
  * no-op — `{"ok":false,"reason":"no_connection_record"}` — the plugin
30
29
  * hook simply does not forward anything further in this case, exactly
31
30
  * what "no-op when the session isn't plan-connected" means in practice;
32
- * - on success, `{"ok":true,"count":<number|null>}` echoes the `count`
33
- * that was SUBMITTED for storage, not a re-read of the row — see
34
- * `recordBackgroundWork`'s own doc (`db/plan-session-background-work.ts`)
35
- * for why a plain no-op write is indistinguishable from a real one here;
31
+ * - on success, `{"ok":true,"count":<number|null>,"applied":<boolean>}`
32
+ * echoes the SUBMITTED `count`; `applied` is the server's answer to
33
+ * whether it was stored (DX-3676: `false` for an out-of-order report
34
+ * older than the one already on file — the caller must not treat it as
35
+ * the dashboard's current count);
36
+ * - DX-3676 — `<event-at>` is the ISO-8601 UTC time the reporting HOOK
37
+ * fired, captured by the caller, never this process's own clock: the
38
+ * hooks are async and can finish out of order, and the server orders
39
+ * reports by this time;
36
40
  * - human-readable diagnostics go to stderr only, never stdout.
37
41
  *
38
- * THE CREDENTIAL — the SAME resolver `bridge` and `plan-state` use, via
39
- * `resolveBridgeOptions` (`bridge.ts`): the dashboard URL, credential
40
- * source, and credential come from the connection record this session's OWN
41
- * danx-dashboard MCP server wrote on its last successful `plan_connect`
42
- * (`session-connection.ts`), never from this process's own ambient env —
43
- * the identical DX-2862 reasoning `plan-state.ts` already gives for itself.
42
+ * THE CREDENTIAL — the SAME resolver `bridge` uses, via `resolveBridgeOptions`
43
+ * (`bridge.ts`): the dashboard URL, credential source, and credential come
44
+ * from the connection record this session's OWN danx-dashboard MCP server
45
+ * wrote on its last successful `plan_connect` (`session-connection.ts`),
46
+ * never from this process's own ambient env (DX-2862).
44
47
  *
45
48
  * A HARD TIMEOUT — `BACKGROUND_WORK_REQUEST_TIMEOUT_MS`. A `Stop` hook
46
49
  * blocks the session's turn boundary, so this call must never hang: a slow
47
50
  * or wedged dashboard is `{ok:false, reason:"timeout"}`, not a stuck hook.
48
51
  *
49
- * THE REQUEST/RUN SCAFFOLDING IS SHARED WITH `plan-state.ts`
50
- * (`one-shot-session-request.ts`, DX-3367 fix-up) — the two subcommands no
51
- * longer maintain independent copies of the authenticated-fetch-with-
52
- * timeout logic or the session/credential resolution boilerplate.
52
+ * THE REQUEST/RUN SCAFFOLDING (`one-shot-session-request.ts`, DX-3367
53
+ * fix-up) is shared, general-purpose plumbing for any one-shot subcommand
54
+ * shaped like this one — not maintained as an independent copy of the
55
+ * authenticated-fetch-with-timeout logic or the session/credential
56
+ * resolution boilerplate.
53
57
  */
54
58
  import { resolveSessionOptions, sendSessionRequest, tryParseJsonBody } from "./one-shot-session-request.js";
55
59
  export const BACKGROUND_WORK_SUBCOMMAND = "background-work";
56
60
  export const BACKGROUND_WORK_PATH = "/api/plan-sessions/me/background-work";
57
61
  /** How long this one-shot call may take before it counts as a timeout. */
58
62
  export const BACKGROUND_WORK_REQUEST_TIMEOUT_MS = 5_000;
59
- const USAGE = `usage: CLAUDE_CODE_SESSION_ID=<session-id> danx-dashboard-mcp ${BACKGROUND_WORK_SUBCOMMAND} <non-negative-integer|clear>`;
63
+ const USAGE = `usage: CLAUDE_CODE_SESSION_ID=<session-id> danx-dashboard-mcp ${BACKGROUND_WORK_SUBCOMMAND} <non-negative-integer|clear> <event-at ISO-8601 UTC>`;
60
64
  /**
61
65
  * Parse the ONE positional argument: `clear`, or a non-negative integer
62
66
  * string. Anything else is a usage error — never guessed or floored.
@@ -68,6 +72,15 @@ export function parseCountArg(raw) {
68
72
  return { error: `count must be "clear" or a non-negative integer, got "${raw}"` };
69
73
  return Number.parseInt(raw, 10);
70
74
  }
75
+ /** DX-3676 — an ISO-8601 UTC instant, as `Date#toISOString` writes it (the server accepts exactly this). */
76
+ const ISO_UTC_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
77
+ /** Parse the event-time argument (DX-3676). Never substituted with this process's clock. */
78
+ export function parseEventAtArg(raw) {
79
+ if (!ISO_UTC_INSTANT.test(raw) || Number.isNaN(Date.parse(raw))) {
80
+ return { error: `event-at must be an ISO-8601 UTC timestamp (e.g. 2026-09-30T00:00:00.000Z), got "${raw}"` };
81
+ }
82
+ return raw;
83
+ }
71
84
  /**
72
85
  * One authenticated PUT, with a hard timeout, classified into the output
73
86
  * shape this subcommand always prints — never a throw, never a non-2xx
@@ -76,13 +89,13 @@ export function parseCountArg(raw) {
76
89
  * DX-3367 fix-up — STATUS IS CHECKED BEFORE THE BODY IS EVER PARSED. A 5xx
77
90
  * (or any other non-2xx) response can carry an HTML error page instead of
78
91
  * JSON; parsing first would misreport that as `bad_response` when the true
79
- * classification is `http_error`. Unlike `plan-state.ts`'s `fetchTurnState`,
80
- * this subcommand has no status that needs the BODY inspected to classify
81
- * (no `409 session_not_connected` equivalent), so status alone decides
82
- * whether a body read is even attempted.
92
+ * classification is `http_error`. This subcommand has no status that needs
93
+ * the BODY inspected to classify (no `409 session_not_connected`
94
+ * equivalent), so status alone decides whether a body read is even
95
+ * attempted.
83
96
  */
84
- export async function putBackgroundWork(options, count, deps) {
85
- const sent = await sendSessionRequest(options, BACKGROUND_WORK_PATH, { method: "PUT", body: JSON.stringify({ count }) }, deps);
97
+ export async function putBackgroundWork(options, report, deps) {
98
+ const sent = await sendSessionRequest(options, BACKGROUND_WORK_PATH, { method: "PUT", body: JSON.stringify({ count: report.count, eventAt: report.eventAt }) }, deps);
86
99
  if ("reason" in sent)
87
100
  return sent;
88
101
  const { status, text } = sent;
@@ -99,10 +112,12 @@ export async function putBackgroundWork(options, count, deps) {
99
112
  if (typeof body !== "object" ||
100
113
  body === null ||
101
114
  !("count" in body) ||
102
- (body.count !== null && typeof body.count !== "number")) {
115
+ (body.count !== null && typeof body.count !== "number") ||
116
+ typeof body.applied !== "boolean") {
103
117
  return { ok: false, reason: "bad_response" };
104
118
  }
105
- return { ok: true, count: body.count };
119
+ const shaped = body;
120
+ return { ok: true, count: shaped.count, applied: shaped.applied };
106
121
  }
107
122
  /** The bin's `background-work` subcommand, wired to the real process. Always resolves to exit code 0. */
108
123
  export async function runBackgroundWorkCommand(argv, env = process.env,
@@ -111,7 +126,7 @@ resolveFrom = {}) {
111
126
  const write = (output) => {
112
127
  process.stdout.write(`${JSON.stringify(output)}\n`);
113
128
  };
114
- if (argv.length !== 1) {
129
+ if (argv.length !== 2) {
115
130
  write({ ok: false, reason: "usage" });
116
131
  process.stderr.write(`${USAGE}\n`);
117
132
  return 0;
@@ -123,6 +138,12 @@ resolveFrom = {}) {
123
138
  return 0;
124
139
  }
125
140
  const count = parsed;
141
+ const eventAt = parseEventAtArg(argv[1]);
142
+ if (typeof eventAt === "object") {
143
+ write({ ok: false, reason: "usage" });
144
+ process.stderr.write(`${eventAt.error}\n${USAGE}\n`);
145
+ return 0;
146
+ }
126
147
  const resolved = await resolveSessionOptions(env, resolveFrom, USAGE);
127
148
  if (!resolved.ok) {
128
149
  // A session that never `plan_connect`-ed has no connection record — this
@@ -132,7 +153,7 @@ resolveFrom = {}) {
132
153
  process.stderr.write(`${resolved.detail}\n`);
133
154
  return 0;
134
155
  }
135
- const output = await putBackgroundWork(resolved.options, count, {
156
+ const output = await putBackgroundWork(resolved.options, { count, eventAt }, {
136
157
  fetch: (input, init) => fetch(input, init),
137
158
  requestTimeoutMs: BACKGROUND_WORK_REQUEST_TIMEOUT_MS,
138
159
  });
@@ -10,11 +10,10 @@
10
10
  * collapse into the one hook + this one subcommand). `<event>` is one of
11
11
  * `session_start` | `session_resume` | `after_compaction` |
12
12
  * `sub_agent_start` — the SAME `npx -y @thehammer/danx-dashboard-mcp@<pin>`
13
- * path the plugin's other dashboard calls already use (`plan-state`,
14
- * `bridge`) — never a separate install, never a deep import of this
15
- * package's `dist/` internals.
13
+ * path the plugin's other dashboard calls already use (`bridge`) — never a
14
+ * separate install, never a deep import of this package's `dist/` internals.
16
15
  *
17
- * THE CREDENTIAL — the SAME resolver `bridge` / `plan-state` use
16
+ * THE CREDENTIAL — the SAME resolver `bridge` uses
18
17
  * (`resolveBridgeOptions`, `bridge.ts`): the dashboard URL, credential source
19
18
  * and credential all come from the connection record this session's OWN
20
19
  * danx-dashboard MCP server wrote on its last successful `plan_connect`
@@ -37,8 +36,8 @@
37
36
  * stderr, exit 1. `event-hook.sh` is the one that decides what to print
38
37
  * for the agent — this module only reports whether the fetch worked.
39
38
  *
40
- * A HARD TIMEOUT (mirrors `plan-state.ts`) — a SessionStart hook must never
41
- * hang on a wedged dashboard.
39
+ * A HARD TIMEOUT — a SessionStart hook must never hang on a wedged
40
+ * dashboard.
42
41
  */
43
42
  import { SESSION_ID_HEADER, resolveBridgeOptions } from "./bridge.js";
44
43
  export const EVENT_TEXT_SUBCOMMAND = "event-text";
package/dist/index.js CHANGED
@@ -74,7 +74,6 @@
74
74
  */
75
75
  import { isEntrypointModule } from "./entrypoint.js";
76
76
  import { BRIDGE_SUBCOMMAND, runBridgeCommand } from "./bridge.js";
77
- import { PLAN_STATE_SUBCOMMAND, runPlanStateCommand } from "./plan-state.js";
78
77
  import { BACKGROUND_WORK_SUBCOMMAND, runBackgroundWorkCommand } from "./background-work.js";
79
78
  import { EVENT_TEXT_SUBCOMMAND, runEventTextCommand } from "./event-text.js";
80
79
  import { resolveDeclaredCredential } from "./credential.js";
@@ -460,22 +459,14 @@ async function main() {
460
459
  // symlink-aware (DX-1647) so it holds under the symlinked `npx` bin the worker
461
460
  // spawns, not just a direct `node dist/index.js`.
462
461
  //
463
- // `bridge` and `plan-state` are the two subcommands. `bridge` is the session
464
- // event stream client the danxbot plugin's plan event bridge runs. It never
465
- // boots the MCP server; its only input is `CLAUDE_CODE_SESSION_ID` (read from
466
- // its environment) plus `--resume-ids` — the dashboard URL, credential source,
467
- // and credential itself come from the session-connection record this server's
468
- // own `plan_connect` wrote (`session-connection.ts`), never from the bridge's
469
- // own environment (DX-2862: a bridge trusting its own ambient
470
- // `DANXBOT_DISPATCH_TOKEN` is the exact bug this repo fixed).
471
- //
472
- // `plan-state` (DX-2921) is the ONE-SHOT client of
473
- // `GET /api/plan-sessions/me/turn-state`, run by the DX-2888 plugin's
474
- // turn-start / turn-end hooks — see `plan-state.ts`'s own doc comment for the
475
- // full contract. It ALWAYS exits 0 (success or failure alike: the hook must
476
- // stay silent), so even an unexpected rejection here is caught and reported
477
- // the same `{ok:false, reason}` way rather than propagating a non-zero exit
478
- // or an uncaught stack trace into the hook.
462
+ // `bridge` is the session event stream client the danxbot plugin's plan
463
+ // event bridge runs. It never boots the MCP server; its only input is
464
+ // `CLAUDE_CODE_SESSION_ID` (read from its environment) plus `--resume-ids` —
465
+ // the dashboard URL, credential source, and credential itself come from the
466
+ // session-connection record this server's own `plan_connect` wrote
467
+ // (`session-connection.ts`), never from the bridge's own environment
468
+ // (DX-2862: a bridge trusting its own ambient `DANXBOT_DISPATCH_TOKEN` is the
469
+ // exact bug this repo fixed).
479
470
  //
480
471
  // Any OTHER argument is refused rather than ignored, so a typo cannot
481
472
  // silently start an MCP server on stdio where a subcommand was meant to run.
@@ -487,13 +478,6 @@ if (isEntrypointModule(import.meta.url, process.argv[1])) {
487
478
  process.exit(1);
488
479
  });
489
480
  }
490
- else if (subcommand === PLAN_STATE_SUBCOMMAND) {
491
- runPlanStateCommand(rest).then((code) => process.exit(code), (err) => {
492
- console.error(`[danx-dashboard-mcp] plan-state fatal: ${err.message}`);
493
- process.stdout.write(`${JSON.stringify({ ok: false, reason: "fatal" })}\n`);
494
- process.exit(0);
495
- });
496
- }
497
481
  else if (subcommand === BACKGROUND_WORK_SUBCOMMAND) {
498
482
  runBackgroundWorkCommand(rest).then((code) => process.exit(code), (err) => {
499
483
  console.error(`[danx-dashboard-mcp] background-work fatal: ${err.message}`);
@@ -502,12 +486,11 @@ if (isEntrypointModule(import.meta.url, process.argv[1])) {
502
486
  });
503
487
  }
504
488
  else if (subcommand === EVENT_TEXT_SUBCOMMAND) {
505
- // DX-3421 (was DX-3366's `mantra` subcommand) — unlike plan-state/
506
- // background-work, a rejection here is a genuine fatal (never expected:
507
- // runEventTextCommand itself already classifies every network/shape
508
- // failure into its own {ok:false} exit 1), so it exits 1 too rather than
509
- // the "always 0, stay silent" contract those two hook-only subcommands
510
- // use.
489
+ // DX-3421 (was DX-3366's `mantra` subcommand) — unlike background-work, a
490
+ // rejection here is a genuine fatal (never expected: runEventTextCommand
491
+ // itself already classifies every network/shape failure into its own
492
+ // {ok:false} exit 1), so it exits 1 too rather than the "always 0, stay
493
+ // silent" contract background-work's hook-only subcommand uses.
511
494
  runEventTextCommand(rest).then((code) => process.exit(code), (err) => {
512
495
  console.error(`[danx-dashboard-mcp] event-text fatal: ${err.message}`);
513
496
  process.exit(1);
@@ -515,7 +498,7 @@ if (isEntrypointModule(import.meta.url, process.argv[1])) {
515
498
  }
516
499
  else if (subcommand !== undefined) {
517
500
  console.error(`[danx-dashboard-mcp] unknown subcommand "${subcommand}" (the only ones are ` +
518
- `"${BRIDGE_SUBCOMMAND}", "${PLAN_STATE_SUBCOMMAND}", "${BACKGROUND_WORK_SUBCOMMAND}", and "${EVENT_TEXT_SUBCOMMAND}")`);
501
+ `"${BRIDGE_SUBCOMMAND}", "${BACKGROUND_WORK_SUBCOMMAND}", and "${EVENT_TEXT_SUBCOMMAND}")`);
519
502
  process.exit(2);
520
503
  }
521
504
  else {
package/dist/listen.js CHANGED
@@ -284,6 +284,11 @@ function cardList(cards) {
284
284
  * this signal cannot support. See `evaluateIdleNudge`'s own doc comment
285
285
  * (`src/issues/db/session-idle-nudge.ts`) for why a sub-agent-awareness
286
286
  * special case was rejected instead of this wording fix.
287
+ *
288
+ * DX-3676 — every named card clears every dispatch gate, so if the session
289
+ * still cannot work one, the card's recorded state is wrong (DX-3400 sat in
290
+ * ToDo with its real blocker only in a comment). The line therefore ends by
291
+ * naming each state-correcting move, which is also what stops the nudge.
287
292
  */
288
293
  export function formatNudgeLine(event) {
289
294
  const invalid = invalidNudgeReason(event);
@@ -294,7 +299,9 @@ export function formatNudgeLine(event) {
294
299
  parts.push(`startable: ${cardList(event.startable)}`);
295
300
  if (event.held.length > 0)
296
301
  parts.push(`held: ${cardList(event.held)}`);
297
- return oneLine(`${LINE_PREFIX} this session has not made an MCP call in ${event.idleMinutes}m — ${parts.join("; ")}`);
302
+ return oneLine(`${LINE_PREFIX} this session has not made an MCP call in ${event.idleMinutes}m — ${parts.join("; ")}. ` +
303
+ "Work these cards; any you cannot work, update to its true state: open a problem, add depends_on or " +
304
+ "conflict_on, block it with the real reason, or rollback_pickup.");
298
305
  }
299
306
  /**
300
307
  * Incremental SSE parser. Comment lines (keep-alives, the connect marker) and
@@ -1,21 +1,22 @@
1
1
  /**
2
2
  * DX-3367 fix-up — shared scaffolding for a "one-shot session request"
3
- * subcommand: `plan-state` (`GET /api/plan-sessions/me/turn-state`) and
4
- * `background-work` (`PUT /api/plan-sessions/me/background-work`) each
5
- * duplicated this exact shape independently (`fetchTurnState` /
6
- * `putBackgroundWork`, `runPlanStateCommand` / `runBackgroundWorkCommand`).
7
- * This module is the ONE place that shape lives now; a future one-shot
8
- * subcommand extends it instead of copying either file again.
3
+ * subcommand. Extracted when `plan-state` (`GET /api/plan-sessions/me/turn-state`,
4
+ * removed by DX-3689 — it never had a caller) and `background-work`
5
+ * (`PUT /api/plan-sessions/me/background-work`) turned out to duplicate this
6
+ * exact shape independently (`fetchTurnState` / `putBackgroundWork`,
7
+ * `runPlanStateCommand` / `runBackgroundWorkCommand`). This module is the ONE
8
+ * place that shape lives now; a future one-shot subcommand extends it
9
+ * instead of copying `background-work.ts` again.
9
10
  *
10
- * Two pieces, matching the two duplicated concerns:
11
+ * Two pieces:
11
12
  * - `sendSessionRequest` — the authenticated HTTP call itself: bearer +
12
13
  * session header, a hard abort-timeout, and network-level failure
13
14
  * classification (`timeout` / `request_failed`). Returns the raw
14
15
  * `{status, text}` UNPARSED — each caller decides for itself which
15
- * statuses need the body inspected (e.g. `plan-state`'s 409
16
- * `session_not_connected`) and which don't, so a non-2xx status with an
17
- * unparseable (e.g. HTML) body is classified from the status alone
18
- * rather than colliding with "the JSON didn't parse" (`bad_response`).
16
+ * statuses need the body inspected and which don't, so a non-2xx status
17
+ * with an unparseable (e.g. HTML) body is classified from the status
18
+ * alone rather than colliding with "the JSON didn't parse"
19
+ * (`bad_response`).
19
20
  * - `resolveSessionOptions` — session-id + credential resolution via
20
21
  * `resolveBridgeOptions`, with `BridgeStartError` narrowed by
21
22
  * `instanceof` rather than an unchecked `as BridgeStartError` cast, so
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thehammer/danx-dashboard-mcp",
3
- "version": "0.1.172",
3
+ "version": "0.1.175",
4
4
  "description": "Stdio MCP server fronting danxbot's dashboard API for agents (operator sessions and dispatched workers alike): the generic danxbot_api/danxbot_api_list/danxbot_api_spec tools reach any route the caller's credential may call, plus dedicated agent-specific tools (plan_connect, danxbot_complete, and other per-dispatch lifecycle callbacks) (DX-3465, PLN-11 R-25).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,174 +0,0 @@
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
- * THE REQUEST/RUN SCAFFOLDING IS SHARED WITH `background-work.ts`
49
- * (`one-shot-session-request.ts`, DX-3367 fix-up).
50
- */
51
- import { resolveSessionOptions, sendSessionRequest, tryParseJsonBody } from "./one-shot-session-request.js";
52
- export const PLAN_STATE_SUBCOMMAND = "plan-state";
53
- export const TURN_STATE_PATH = "/api/plan-sessions/me/turn-state";
54
- /** How long this one-shot call may take before it counts as a timeout. */
55
- export const PLAN_STATE_REQUEST_TIMEOUT_MS = 5_000;
56
- const USAGE = `usage: CLAUDE_CODE_SESSION_ID=<session-id> danx-dashboard-mcp ${PLAN_STATE_SUBCOMMAND}`;
57
- function errorCodeOf(body) {
58
- return typeof body === "object" && body !== null && typeof body.error === "string"
59
- ? body.error
60
- : null;
61
- }
62
- function isFiniteNumber(v) {
63
- return typeof v === "number" && Number.isFinite(v);
64
- }
65
- function isCardRef(v) {
66
- return (typeof v === "object" &&
67
- v !== null &&
68
- typeof v.id === "string" &&
69
- typeof v.title === "string");
70
- }
71
- /**
72
- * The strict shape check the contract pins (comment 4245): finite counts, a
73
- * `plan` with `id` + `name`, and a string `id` + `title` on every
74
- * `startable` / `held` entry. `null` on anything short of that — a 200 whose
75
- * body does not match is `bad_response`, exactly like a non-2xx.
76
- */
77
- export function parseTurnStateBody(body) {
78
- if (typeof body !== "object" || body === null)
79
- return null;
80
- const b = body;
81
- const plan = b.plan;
82
- if (typeof plan !== "object" || plan === null)
83
- return null;
84
- const p = plan;
85
- if (!isFiniteNumber(p.id) || typeof p.name !== "string")
86
- return null;
87
- const counts = b.counts;
88
- if (typeof counts !== "object" || counts === null)
89
- return null;
90
- const c = counts;
91
- if (!isFiniteNumber(c.open) || !isFiniteNumber(c.inProgress) || !isFiniteNumber(c.needsYou))
92
- return null;
93
- if (!Array.isArray(b.startable) || !b.startable.every(isCardRef))
94
- return null;
95
- if (!Array.isArray(b.held) || !b.held.every(isCardRef))
96
- return null;
97
- return {
98
- plan: { id: p.id, name: p.name },
99
- counts: { open: c.open, inProgress: c.inProgress, needsYou: c.needsYou },
100
- startable: b.startable,
101
- held: b.held,
102
- };
103
- }
104
- /**
105
- * One authenticated GET, with a hard timeout, classified into the output
106
- * shape this subcommand always prints — never a throw, never a non-2xx
107
- * bubbling past this function.
108
- *
109
- * DX-3367 fix-up — status is checked BEFORE the body is parsed, except for
110
- * the ONE status (`409`) whose classification genuinely depends on the body
111
- * (`session_not_connected`). Any other non-2xx — including a 5xx that comes
112
- * back as an HTML error page instead of JSON — is `http_error` without ever
113
- * attempting to parse it, so a body-parse failure on those statuses can
114
- * never be misreported as `bad_response`.
115
- */
116
- export async function fetchTurnState(options, deps) {
117
- const sent = await sendSessionRequest(options, TURN_STATE_PATH, { method: "GET" }, deps);
118
- if ("reason" in sent)
119
- return sent;
120
- const { status, text } = sent;
121
- if (status === 409) {
122
- // The exact literal the plugin's no-log-spam rule keys on (AC 30672 /
123
- // comment 4245) — the dashboard's own 409 error code for an unconnected
124
- // session, passed through verbatim rather than renamed. A 409 whose body
125
- // does NOT carry that code falls through to the ordinary `http_error`
126
- // classification below, same as any other non-2xx.
127
- const parsed409 = tryParseJsonBody(text);
128
- if (parsed409.ok && errorCodeOf(parsed409.body) === "session_not_connected") {
129
- return { ok: false, reason: "session_not_connected" };
130
- }
131
- }
132
- if (status === 401 || status === 403) {
133
- return { ok: false, reason: "unauthorized" };
134
- }
135
- if (status < 200 || status >= 300) {
136
- return { ok: false, reason: "http_error" };
137
- }
138
- const parsed = tryParseJsonBody(text);
139
- if (!parsed.ok)
140
- return { ok: false, reason: "bad_response" };
141
- const turnState = parseTurnStateBody(parsed.body);
142
- if (turnState === null) {
143
- return { ok: false, reason: "bad_response" };
144
- }
145
- return { ok: true, ...turnState };
146
- }
147
- /** The bin's `plan-state` subcommand, wired to the real process. Always resolves to exit code 0. */
148
- export async function runPlanStateCommand(argv, env = process.env,
149
- /** Test seam: the home the session's connection record is read from. */
150
- resolveFrom = {}) {
151
- const write = (output) => {
152
- process.stdout.write(`${JSON.stringify(output)}\n`);
153
- };
154
- if (argv.length !== 0) {
155
- // A malformed invocation is still a "the hook must stay silent" failure,
156
- // not a crash — same ok:false/exit-0 contract as every other failure
157
- // path here, with the usage line reserved for a human reading stderr.
158
- write({ ok: false, reason: "usage" });
159
- process.stderr.write(`${USAGE}\n`);
160
- return 0;
161
- }
162
- const resolved = await resolveSessionOptions(env, resolveFrom, USAGE);
163
- if (!resolved.ok) {
164
- write(resolved.output);
165
- process.stderr.write(`${resolved.detail}\n`);
166
- return 0;
167
- }
168
- const output = await fetchTurnState(resolved.options, {
169
- fetch: (input, init) => fetch(input, init),
170
- requestTimeoutMs: PLAN_STATE_REQUEST_TIMEOUT_MS,
171
- });
172
- write(output);
173
- return 0;
174
- }