@50arms/platform-mcp 0.1.469 → 0.1.471

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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Stdio MCP server fronting the 50 Arms dashboard HTTP API. Since DX-3465 it exposes three generic tools (`50arms_api`, `50arms_api_list`, `50arms_api_spec` — see "Tool surface" below) that reach any route the caller's credential may reach, plus a few dedicated tools for what no route call can do (`session_connect`, `request_permission`, `attach_file`, `50arms_slack_reply`) — there is no per-operation tool any more, and since DX-4525 no dispatch-callback tool either: `50arms_api` is every agent's primary channel to the dashboard (ending a dispatch, gate sign-off, Slack update, thread link, Slack recovery, evaluator summary and template-app load/save are all `50arms_api` calls to the routes in `src/dispatch/callback-routes.ts`). The server instructions and the `50arms_api_spec` description tell an agent to read the spec before its first call to a route it has not called before.
4
4
 
5
- `50arms_api` is Zod-validated at the MCP boundary, fetches under the hood, and passes the server response back to the agent verbatim. Refusal envelopes (`{error, ...extra}` with `failed_gate`, `non_terminal_phases`, `offending_keys`, etc.) come through as `{ok: false, status, body}` so the agent can pick the right next action without guessing. 5xx and network failures throw.
5
+ `50arms_api` is Zod-validated at the MCP boundary, fetches under the hood, and passes the server response back to the agent verbatim. Refusal envelopes (`{error, ...extra}` with `failed_gate`, `non_terminal_phases`, `offending_keys`, etc.) come through as `{ok: false, status, body}` so the agent can pick the right next action without guessing. A call that gets no usable answer never reaches the agent as a thrown error it may step past (DX-7110, DEC-736). A read (a GET whose route does not write) that fails in transit (nothing connected, a timeout, 502/503/504, 408/429) is retried with backoff for up to 90 s, which outlasts a deploy restart and a lock stall; a write is sent once, because its first send may have landed. What is left is answered `{ok: false, status: 503, body: {error: "dashboard_unreachable", unreachable_since, detail, message}}`, and a write adds `applied`: `false` when the request was never sent, `"unknown"` once it was. A 500 or other 5xx is answered at once `{error: "server_error"}`: 50 Arms is up and broken, so it is neither retried nor an outage. Once retries run out the process records `unreachable_since`; later calls make one short attempt and answer `dashboard_unreachable` at once, a `GET /health` ping with backoff (or the relay's heartbeat) watches for 50 Arms to return, and the session gets one line when it does (on the relay's event channel, else in the next `50arms_api` answer's `reminders[]`). Every attempt, this process's own requests included, is bounded by `request-bound.ts` (`request-policy.ts` holds the numbers).
6
6
 
7
7
  ## Env vars (required, fail-loud at boot)
8
8
 
@@ -78,7 +78,7 @@ The contract the plugin builds against:
78
78
  - **The accepted restart gap.** Only an insert that commits more than the dashboard's 30 s overlap after the event it follows can be missed, and only by a restart resume (the dashboard's own limit); a running relay never misses one. A burst of more than 64 events inside the overlap can replay the oldest once (a duplicate, never a loss).
79
79
  - **One plan.** `plan_id` is the number of the plan the session is on (the `n` of `PLAN-n`, within the team). A plan different from the last call's drops the plan-scoped records buffered or held for the plan it left (dashboard events, the digest, the idle nudge), so a plan move starts clean. Session-scoped records (the pacing and auto-resume messages, which are never replayed, and the relay's own failure and revoked-key notices) are kept across a plan move and across the gap below. One wait is pending at a time: a newer call supersedes the pending one (which answers empty at once); an aborted request drops its waiter.
80
80
  - **One heartbeat window.** `POST /api/plan-sessions/me/heartbeat` every 15 s while a call is pending or was made within the last 40 s; after that the stream is closed and heartbeats stop, so a dead or unloaded plugin module reads not-healthy (the dashboard's liveness window is 60 s). The plugin therefore waits 20 s per call and backs off at most 10 s between failed calls. Stats and the transcript title ride the heartbeat when `transcript_path` is given. The sequence survives the gap, so a cursor stays valid across it.
81
- - **Failures inside the server.** A transient mint failure (network, timeout, 408, 429, 5xx) and a dropped stream back off 1 s doubling to 30 s (the one schedule, `listen.ts`); a lapsed ticket lease (15 min) re-mints and re-reads a failed plan inventory; three heartbeats in a row that fail to land on an open stream force a fresh connection silently (a line on stderr, then an immediate heartbeat on the new stream), and the session is told only once the heartbeat has failed continuously for `HEARTBEAT_SUSTAINED_OUTAGE_MS` (5 minutes), in any connection state, once per outage, so a dashboard restart never wakes it; a revoked key tells the session once.
81
+ - **Failures inside the server.** A transient mint failure (network, timeout, 408, 429, 5xx) and a dropped stream back off 1 s doubling to 30 s (the one schedule, `listen.ts`); a lapsed ticket lease (15 min) re-mints and re-reads a failed plan inventory; three heartbeats in a row that fail to land on an open stream force a fresh connection silently (a line on stderr, then an immediate heartbeat on the new stream), and the session is told only once requests (heartbeats and calls alike) have failed continuously for `SUSTAINED_OUTAGE_MS` (5 minutes, `dashboard-reachability.ts`), in any connection state, once per outage, so a dashboard restart never wakes it, and once more when 50 Arms answers again; a revoked key tells the session once.
82
82
  - **Nothing outlives the session.** The heartbeat interval, the backoff sleep and the digest hold are unref'd; `close()` (run when the transport closes and when stdin ends) aborts the stream and the mint and inventory requests and clears a pending call's wait timer, the one ref'd timer, which otherwise holds the process only until the call answers.
83
83
  - **Credential and audience.** The server's own, from its boot-time `CLAUDE_CODE_SESSION_ID`: no connection record, fingerprint check or environment variable is involved. The tool is advertised only to a person's session holding `plans.view`, never to a dispatch. The stream's advisory frames (the idle nudge, DX-4340's pacing message, DX-4342's auto-resume message) arrive as records like any event, at once and never held for a digest. The digest (agent and machine events held up to 10 minutes) is one record, `[plan events] digest`, and a held id is never acknowledged before it is returned.
84
84
 
@@ -1,9 +1,13 @@
1
- import { assertVersionFloorSatisfied, MCP_MIN_VERSION_HEADER, } from "./version-floor.js";
1
+ import { boundRequest } from "./request-bound.js";
2
+ import { REQUEST_POLICY } from "./request-policy.js";
3
+ import { assertVersionFloorSatisfied, MCP_MIN_VERSION_HEADER, McpOutdatedError, } from "./version-floor.js";
2
4
  function baseOf(dashboardUrl) {
3
5
  return dashboardUrl.replace(/\/+$/, "");
4
6
  }
5
7
  export async function postPublic(fetchImpl, url, body) {
8
+ const bound = boundRequest(REQUEST_POLICY.readAttemptMs);
6
9
  let res;
10
+ let text;
7
11
  try {
8
12
  res = await fetchImpl(url, {
9
13
  method: "POST",
@@ -12,13 +16,19 @@ export async function postPublic(fetchImpl, url, body) {
12
16
  Accept: "application/json",
13
17
  },
14
18
  body: JSON.stringify(body),
19
+ signal: bound.signal,
15
20
  });
21
+ assertVersionFloorSatisfied(res.headers.get(MCP_MIN_VERSION_HEADER));
22
+ text = await res.text();
16
23
  }
17
24
  catch (err) {
18
- throw new Error(`[platform-mcp] network failure on POST ${url}: ${err instanceof Error ? err.message : String(err)}`);
25
+ if (err instanceof McpOutdatedError)
26
+ throw err;
27
+ throw new Error(`[platform-mcp] network failure on POST ${url}: ${bound.aborted() ? "timed out" : err instanceof Error ? err.message : String(err)}`);
28
+ }
29
+ finally {
30
+ bound.release();
19
31
  }
20
- assertVersionFloorSatisfied(res.headers.get(MCP_MIN_VERSION_HEADER));
21
- const text = await res.text();
22
32
  if (res.status >= 500) {
23
33
  throw new Error(`[platform-mcp] server error ${res.status} on POST ${url}: ${text.slice(0, 500)}`);
24
34
  }
@@ -53,6 +53,10 @@ export const DANXBOT_API_EXAMPLES = {
53
53
  type: "Bug",
54
54
  title: "<title>",
55
55
  summary: "<one plain line: what this card is>",
56
+ justification: {
57
+ quote: "<the exact part of the type's rules you rely on>",
58
+ reasoning: "<why this card matches it>",
59
+ },
56
60
  description: "<markdown>",
57
61
  plan: null,
58
62
  },
@@ -107,7 +111,7 @@ export function danxbotApiExamplesText() {
107
111
  return (
108
112
  // DX-7003: a card read answers each comment's shorter version; the tool's description says how to reach the originals.
109
113
  `Correct first calls: card read ${render(e.cardRead)} (\`fields\` is an object, never a comma string; \`comments\` answers each comment's shorter version when it has one: \`comments: {"expanded": true}\` reads the originals, the ones a decision's provenance quote is copied from, and \`comments: {"q": "<words>"}\` searches them); ` +
110
- `card create ${render(e.cardCreate)} (\`plan\` required: "mine" or null; \`summary\` required, on every phase_children[] item too); ` +
114
+ `card create ${render(e.cardCreate)} (\`plan\` required: "mine" or null; \`summary\` and \`justification\` required, on every phase_children[] item too); ` +
111
115
  `card edit ${render(e.cardEdit)} (only the keys you change; \`ac\` replaces the list); ` +
112
116
  `AC tick ${render(e.acTick)}; ` +
113
117
  `transition ${render(e.transition)}; ` +
@@ -0,0 +1,74 @@
1
+ export class DashboardUnreachableError extends Error {
2
+ failure;
3
+ code = "dashboard_unreachable";
4
+ constructor(message, failure) {
5
+ super(message);
6
+ this.failure = failure;
7
+ this.name = "DashboardUnreachableError";
8
+ }
9
+ }
10
+ export class DashboardServerError extends Error {
11
+ failure;
12
+ code = "server_error";
13
+ constructor(message, failure) {
14
+ super(message);
15
+ this.failure = failure;
16
+ this.name = "DashboardServerError";
17
+ }
18
+ }
19
+ function seconds(ms) {
20
+ return `${Math.round(ms / 1000)} s`;
21
+ }
22
+ /** Whether an answer is the `dashboard_unreachable` one `failureAnswer` made. */
23
+ export function isUnreachableAnswer(result) {
24
+ const body = result.body;
25
+ return (!result.ok &&
26
+ typeof body === "object" &&
27
+ body !== null &&
28
+ body.error === "dashboard_unreachable");
29
+ }
30
+ /** The answer an agent's tool call gets for a request that failed as above, or null for any other error (which stays a thrown failure). */
31
+ export function failureAnswer(err) {
32
+ if (err instanceof DashboardUnreachableError) {
33
+ const { method, write, applied, detail, since, triedMs } = err.failure;
34
+ const lead = triedMs > 0
35
+ ? `${method} did not get an answer from 50 Arms after retrying for ${seconds(triedMs)} (${detail}).`
36
+ : `${method} did not get an answer from 50 Arms (${detail}).`;
37
+ const effect = !write
38
+ ? ""
39
+ : applied === false
40
+ ? " The request was never sent, so nothing was stored."
41
+ : " The request was sent but no answer came back, so it may or may not have been stored: read the record back before sending it again.";
42
+ return {
43
+ ok: false,
44
+ status: 503,
45
+ body: {
46
+ error: "dashboard_unreachable",
47
+ message: `${lead}${effect} Never carry on as if this call had worked: stop the work that depends on it and tell the person. ` +
48
+ `This session is told when 50 Arms answers again.`,
49
+ ...(write ? { applied } : {}),
50
+ unreachable_since: since === null ? null : new Date(since).toISOString(),
51
+ detail,
52
+ },
53
+ };
54
+ }
55
+ if (err instanceof DashboardServerError) {
56
+ const { status, write, text } = err.failure;
57
+ return {
58
+ ok: false,
59
+ status,
60
+ body: {
61
+ error: "server_error",
62
+ message: `50 Arms answered ${status}: it is running but failed this request, so retrying it unchanged is unlikely to help. ` +
63
+ `Never carry on as if this call had worked.` +
64
+ (write
65
+ ? " The write may or may not have been stored: read the record back before sending it again."
66
+ : ""),
67
+ ...(write ? { applied: "unknown" } : {}),
68
+ status,
69
+ detail: text,
70
+ },
71
+ };
72
+ }
73
+ return null;
74
+ }
@@ -0,0 +1,123 @@
1
+ import { backoffAt, REQUEST_POLICY } from "./request-policy.js";
2
+ /**
3
+ * DX-5088 - how long requests must keep failing (counted from the first failure, across every reconnect, until one answers) before the
4
+ * MODEL is told. 5 minutes: a production deploy replaces the single dashboard container, an outage the investigation measured at about 35 s
5
+ * (DX-5085 comment 14821), and the lock-convoy stalls around it ran 8-27 s more; 5 minutes is roughly 8x the restart, so a deploy never
6
+ * wakes a session, while an outage that outlasts it is one the session's person should hear about.
7
+ */
8
+ export const SUSTAINED_OUTAGE_MS = 5 * 60_000;
9
+ /** A span of time in words: seconds under two minutes, whole minutes after. */
10
+ export function durationWording(ms) {
11
+ return ms < 120_000
12
+ ? `${Math.max(1, Math.round(ms / 1000))} seconds`
13
+ : `${Math.round(ms / 60_000)} minutes`;
14
+ }
15
+ /** The back-again line, the one wording every session is given: a relay's event line and a `50arms_api` reminder both say it. */
16
+ export function backAgainText(ms) {
17
+ return (`50 Arms answers again after ${durationWording(ms)}. Calls work again. A write that answered dashboard_unreachable with applied "unknown" ` +
18
+ `may or may not have been stored: read it back before sending it again.`);
19
+ }
20
+ /** The generic wording of a notice, for a session with no relay (a relay words its own sustained notice: `heartbeat-reporter.ts`). */
21
+ export function noticeReminder(notice) {
22
+ return notice.kind === "sustained"
23
+ ? {
24
+ key: "dashboard_unreachable",
25
+ text: `50 Arms has not answered this session for ${durationWording(notice.ms)}. Its calls fail with dashboard_unreachable meanwhile: a write that answered ` +
26
+ `applied "unknown" may or may not have been stored, so read it back before sending it again. This session is told when 50 Arms answers again.`,
27
+ }
28
+ : { key: "dashboard_back", text: backAgainText(notice.ms) };
29
+ }
30
+ export class DashboardReachability {
31
+ deps;
32
+ failingSince = null;
33
+ unreachableSince = null;
34
+ sustainedAnnounced = false;
35
+ pinging = false;
36
+ sink = null;
37
+ pending = [];
38
+ constructor(deps) {
39
+ this.deps = deps;
40
+ }
41
+ /** When this process recorded 50 Arms as unreachable (epoch ms), or null while it is not. */
42
+ unreachableSinceMs() {
43
+ return this.unreachableSince;
44
+ }
45
+ isUnreachable() {
46
+ return this.unreachableSince !== null;
47
+ }
48
+ /** A request or heartbeat got no usable answer. Counts toward the five-minute notice. */
49
+ noteFailure() {
50
+ const now = this.deps.now();
51
+ this.failingSince ??= now;
52
+ const downMs = now - this.failingSince;
53
+ if (downMs >= SUSTAINED_OUTAGE_MS && !this.sustainedAnnounced) {
54
+ this.sustainedAnnounced = true;
55
+ this.emit({ kind: "sustained", ms: downMs });
56
+ }
57
+ }
58
+ /** A request ran out of retries, or was a write (which gets none): calls answer `dashboard_unreachable` at once until 50 Arms answers. */
59
+ noteUnreachable() {
60
+ this.noteFailure();
61
+ this.unreachableSince ??= this.failingSince;
62
+ this.startPinging();
63
+ }
64
+ /** 50 Arms answered (any status that is the dashboard's own). */
65
+ noteReachable() {
66
+ const since = this.failingSince;
67
+ const told = this.unreachableSince !== null || this.sustainedAnnounced;
68
+ this.failingSince = null;
69
+ this.unreachableSince = null;
70
+ this.sustainedAnnounced = false;
71
+ if (told && since !== null)
72
+ this.emit({ kind: "back", ms: this.deps.now() - since });
73
+ }
74
+ /** Send notices to the relay's event channel until the returned function is called. A notice that waited for a sink stays where it is. */
75
+ attachSink(sink) {
76
+ this.sink = sink;
77
+ return () => {
78
+ if (this.sink === sink)
79
+ this.sink = null;
80
+ };
81
+ }
82
+ /** The notices that had no relay to go to, as reminders for the next `50arms_api` answer; each is returned once. */
83
+ takePending() {
84
+ const reminders = this.pending.map(noticeReminder);
85
+ this.pending = [];
86
+ return reminders;
87
+ }
88
+ emit(notice) {
89
+ if (this.sink !== null)
90
+ this.sink(notice);
91
+ else
92
+ this.pending.push(notice);
93
+ }
94
+ startPinging() {
95
+ if (this.pinging)
96
+ return;
97
+ this.pinging = true;
98
+ this.pingUntilReachable().catch((err) => {
99
+ // A bug in the ping must not take the server down; the next failed call starts the loop again.
100
+ this.deps.log(`[platform-mcp] the 50 Arms reachability ping failed: ${err instanceof Error ? err.message : String(err)}`);
101
+ });
102
+ }
103
+ async pingUntilReachable() {
104
+ const waits = REQUEST_POLICY.pingBackoffMs;
105
+ // The flag is cleared on the same tick the loop ends, so an outage recorded right after it ended starts a new loop.
106
+ try {
107
+ for (let i = 0; this.unreachableSince !== null; i++) {
108
+ await this.deps.sleep(backoffAt(waits, i));
109
+ // An answer to a call or a heartbeat while this slept already ended the outage.
110
+ if (this.unreachableSince === null)
111
+ return;
112
+ if (await this.deps.ping()) {
113
+ this.noteReachable();
114
+ return;
115
+ }
116
+ this.noteFailure();
117
+ }
118
+ }
119
+ finally {
120
+ this.pinging = false;
121
+ }
122
+ }
123
+ }
@@ -1,4 +1,5 @@
1
1
  import { agentGateHalt } from "./agent-gate.js";
2
+ import { failureAnswer } from "./dashboard-errors.js";
2
3
  import { withForbiddenHint } from "./forbidden-hint.js";
3
4
  /**
4
5
  * DX-5549 / DX-5724 - the one way a tool reaches the dashboard, built over late-bound access and the agent gate (read at CALL time, as `index.ts` binds them in `boot()`).
@@ -6,6 +7,7 @@ import { withForbiddenHint } from "./forbidden-hint.js";
6
7
  * (`opts.gateOpen`: `isAgentGateOpenCall` for the proposal routes - proposing an agent is how a session with none gets one - and the no-agent `50arms_api_list` / `50arms_api_spec` answers about them). Then the sign-in halt.
7
8
  *
8
9
  * DX-4434: a refused call's `403 forbidden` gains its `request_permission` hint here, the ONE place it is added.
10
+ * DX-7110: and a call that got no usable answer becomes its `dashboard_unreachable` / `server_error` answer here (`dashboard-errors.ts`), the ONE place that is done.
9
11
  */
10
12
  export function makeGuardedCalls(deps) {
11
13
  // DX-7098: `foreignKey` - the call went out on a system job's key, so a 401 says nothing about the session's own key (`SessionAccess.guard`).
@@ -15,9 +17,19 @@ export function makeGuardedCalls(deps) {
15
17
  if (noAgent !== null)
16
18
  return { halt: noAgent };
17
19
  }
18
- const guarded = await deps
19
- .access()
20
- .guard(run, { foreignKey: opts.foreignKey === true });
20
+ // DX-7110: a request that got no usable answer (`dashboard_unreachable`, `server_error`) reaches the agent as that answer, never as a thrown error it may step past.
21
+ let guarded;
22
+ try {
23
+ guarded = await deps
24
+ .access()
25
+ .guard(run, { foreignKey: opts.foreignKey === true });
26
+ }
27
+ catch (err) {
28
+ const answer = failureAnswer(err);
29
+ if (answer === null)
30
+ throw err;
31
+ return { result: answer };
32
+ }
21
33
  return "halt" in guarded
22
34
  ? guarded
23
35
  : { result: withForbiddenHint(guarded.result) };
@@ -10,11 +10,28 @@
10
10
  import { keyRevokedHalt } from "./key-revoked-halt.js";
11
11
  import { oneLine } from "./one-line.js";
12
12
  import { DIGEST_PREFIX } from "./digest-hold.js";
13
- import { HEARTBEAT_SILENT_FAILURE_THRESHOLD, HEARTBEAT_SUSTAINED_OUTAGE_MS, sendHeartbeat, } from "./session-stream.js";
13
+ import { HEARTBEAT_SILENT_FAILURE_THRESHOLD, sendHeartbeat, } from "./session-stream.js";
14
14
  import { OperatorSessionStats, } from "./session-stats.js";
15
15
  import { TranscriptTitleReader } from "./session-title.js";
16
+ import { backAgainText, durationWording, } from "./dashboard-reachability.js";
16
17
  /** DX-5415: how long a stop waits for the final settle (drain + one stats flush) before giving up; shutdown must stay bounded. */
17
18
  export const FINAL_SETTLE_BOUND_MS = 10_000;
19
+ /**
20
+ * DX-5088 / DX-7110 - what a relay says of a notice from the shared reachability state: the sustained-outage wording follows the listener's
21
+ * state, because a stopped relay (a terminal outcome) does not reconnect by itself, so "keeps reconnecting" would be false.
22
+ */
23
+ function noticeLine(notice, connection) {
24
+ if (notice.kind === "back")
25
+ return oneLine(`${DIGEST_PREFIX} ${backAgainText(notice.ms)}`);
26
+ const length = durationWording(notice.ms);
27
+ const wording = connection.state === "stopped"
28
+ ? `this session's listener has stopped${connection.reason === undefined ? "" : ` (${connection.reason})`} and does not reconnect by itself, ` +
29
+ `so the dashboard has heard nothing from it for ${length}. The next plan_events_wait call says why it stopped and what to do; ` +
30
+ `a person can also restart the session.`
31
+ : `this session's listener has not reached the dashboard for ${length} (its heartbeats keep failing). ` +
32
+ `It keeps reconnecting on its own, and nothing is needed from you.`;
33
+ return oneLine(`${DIGEST_PREFIX} ${wording}`);
34
+ }
18
35
  function settleBound() {
19
36
  return AbortSignal.timeout(FINAL_SETTLE_BOUND_MS);
20
37
  }
@@ -30,9 +47,8 @@ export class HeartbeatReporter {
30
47
  lastTitleError = null;
31
48
  // DX-3099 - consecutive heartbeats that failed to LAND on one open stream (DX-5088: per stream, reset whenever the state leaves `streaming`).
32
49
  failureStreak = 0;
33
- // DX-5088 - when the heartbeat first failed to land in the current outage (across every reconnect); null while the last one landed.
34
- outageSince = null;
35
- outageAnnounced = false;
50
+ // DX-7110: ends the delivery of the shared reachability notices to this relay's event channel.
51
+ detachSink;
36
52
  // DX-4418 - the stop notice for a revoked key goes out once per revocation; every later beat is refused the same way. DX-6894: a beat the
37
53
  // dashboard accepts again (a person signed the session back in) re-arms it, so a second revocation is announced too.
38
54
  revocationAnnounced = false;
@@ -44,6 +60,8 @@ export class HeartbeatReporter {
44
60
  transcriptPath === null
45
61
  ? null
46
62
  : new TranscriptTitleReader(transcriptPath);
63
+ // DX-5088 / DX-7110: the five-minutes-down notice and the back-again line are the shared state's; while this relay runs they go to its event channel.
64
+ this.detachSink = deps.reachability.attachSink((notice) => deps.announce(noticeLine(notice, deps.connection()), "relay_notice"));
47
65
  }
48
66
  /**
49
67
  * The relay learns the session's transcript from each `plan_events_wait` call, after the reporter exists: a different path
@@ -67,6 +85,7 @@ export class HeartbeatReporter {
67
85
  }
68
86
  /** DX-5415: settle the collector's held sub-agent finals (bounded), then stop tailing the transcript. Idempotent. */
69
87
  async stop() {
88
+ this.detachSink();
70
89
  await this.sessionStats.stop(this.send(undefined), settleBound());
71
90
  }
72
91
  /** One heartbeat as the reporter sends it: the carried answer's title and revocation are applied here. */
@@ -112,30 +131,13 @@ export class HeartbeatReporter {
112
131
  void this.sessionStats
113
132
  .tick(this.send(title))
114
133
  .then((landed) => {
115
- const now = this.deps.now();
134
+ // DX-5088 / DX-7110: the outage is the shared state's, and it tells the model once it is sustained.
116
135
  if (landed) {
117
136
  this.failureStreak = 0;
118
- this.outageSince = null;
119
- this.outageAnnounced = false;
137
+ this.deps.reachability.noteReachable();
120
138
  return;
121
139
  }
122
- this.outageSince ??= now;
123
- // DX-5088 - the model hears of an outage only once it is sustained, in any connection state (a dashboard that stays down keeps
124
- // the stream reconnecting, and that is exactly the outage worth saying); a blip such as a ~35 s deploy restart is stderr only.
125
- const downMs = now - this.outageSince;
126
- if (downMs >= HEARTBEAT_SUSTAINED_OUTAGE_MS && !this.outageAnnounced) {
127
- this.outageAnnounced = true;
128
- const minutes = Math.round(downMs / 60_000);
129
- const connection = this.deps.connection();
130
- // DX-5088: the wording follows the state. A stopped relay (a terminal outcome) does not reconnect by itself, so "keeps reconnecting" would be false.
131
- const wording = connection.state === "stopped"
132
- ? `this session's listener has stopped${connection.reason === undefined ? "" : ` (${connection.reason})`} and does not reconnect by itself, ` +
133
- `so the dashboard has heard nothing from it for ${minutes} minutes. The next plan_events_wait call says why it stopped and what to do; ` +
134
- `a person can also restart the session.`
135
- : `this session's listener has not reached the dashboard for ${minutes} minutes (its heartbeats keep failing). ` +
136
- `It keeps reconnecting on its own, and nothing is needed from you.`;
137
- this.deps.announce(oneLine(`${DIGEST_PREFIX} ${wording}`), "relay_notice");
138
- }
140
+ this.deps.reachability.noteFailure();
139
141
  // DX-3099 - the self-heal counts only while a stream is open: that is the desync the card found (the client's stream reads
140
142
  // open; the dashboard has nothing recent for it). DX-5088: while it is reconnecting the reconnect already owns recovery, and
141
143
  // aborting it would restart the backoff, so a failure then neither counts nor forces anything.
@@ -1,6 +1,10 @@
1
- import { boardStampOf, takesBoardInBody } from "./route-board-scope.js";
1
+ import { boardStampOf, isReadRoute, takesBoardInBody, } from "./route-board-scope.js";
2
2
  import { assertVersionFloorSatisfied, MCP_MIN_VERSION_HEADER, MCP_VERSION_HEADER, readOwnVersion, } from "./version-floor.js";
3
3
  import { PLUGIN_BACKGROUND_HEADER } from "./session-options.js";
4
+ import { boundRequest } from "./request-bound.js";
5
+ import { backoffAt, REQUEST_POLICY, } from "./request-policy.js";
6
+ import { DashboardReachability } from "./dashboard-reachability.js";
7
+ import { DashboardServerError, DashboardUnreachableError, } from "./dashboard-errors.js";
4
8
  /** `<basePath><path>` with the path's own query string cut off and its leading slash normalised (an empty or "/" path adds nothing). */
5
9
  function routePathOf(path, basePath = "/api/issues") {
6
10
  const [rawPath] = path.split("?", 2);
@@ -8,15 +12,76 @@ function routePathOf(path, basePath = "/api/issues") {
8
12
  return basePath;
9
13
  return `${basePath}${rawPath.startsWith("/") ? rawPath : `/${rawPath}`}`;
10
14
  }
15
+ const holdingSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
16
+ const unrefSleep = (ms) => new Promise((resolve) => {
17
+ const timer = setTimeout(resolve, ms);
18
+ timer.unref();
19
+ });
20
+ // DX-7110: a refused connection, an unknown host or an unreachable network is a failure before anything was sent, so a write that met one cannot have landed.
21
+ const NEVER_SENT_CODES = new Set([
22
+ "ECONNREFUSED",
23
+ "ENOTFOUND",
24
+ "EAI_AGAIN",
25
+ "ENETUNREACH",
26
+ "EHOSTUNREACH",
27
+ ]);
28
+ /** The error codes of a fetch failure: undici wraps the socket error in `cause` (a connection tried over several addresses in an AggregateError). */
29
+ function codesOf(err, seen = new Set()) {
30
+ if (typeof err !== "object" || err === null || seen.has(err))
31
+ return [];
32
+ seen.add(err);
33
+ const { code, cause, errors } = err;
34
+ return [
35
+ ...(typeof code === "string" ? [code] : []),
36
+ ...codesOf(cause, seen),
37
+ ...(Array.isArray(errors) ? errors.flatMap((e) => codesOf(e, seen)) : []),
38
+ ];
39
+ }
40
+ /** A fetch failure in words: undici's own message says only `fetch failed`, so the socket error under it is named too. */
41
+ function describeFailure(err) {
42
+ if (!(err instanceof Error))
43
+ return String(err);
44
+ const cause = err.cause instanceof Error ? `: ${err.cause.message}` : "";
45
+ return `${err.message}${cause}`;
46
+ }
47
+ /** Whether an attempt got the dashboard's own answer, was told to come back (it is up, and busy), or got none. */
48
+ function verdictOf(attempt) {
49
+ if (attempt.kind === "failed")
50
+ return "down";
51
+ if (attempt.status === 408 || attempt.status === 429)
52
+ return "busy";
53
+ return attempt.status === 502 ||
54
+ attempt.status === 503 ||
55
+ attempt.status === 504
56
+ ? "down"
57
+ : "answer";
58
+ }
11
59
  export class DashboardHttpClient {
12
60
  config;
13
61
  fetchImpl;
62
+ deps;
63
+ /** DX-7110: whether 50 Arms is reachable, shared with the relay's heartbeat and the session's notices. */
64
+ reachability;
14
65
  // DX-3597 — true once this instance has made ONE request, regardless of
15
66
  // outcome. Drives the "first call OR any 4xx" version-floor check below.
16
67
  hasCheckedVersionFloor = false;
17
- constructor(config, fetchImpl = fetch) {
68
+ constructor(config, fetchImpl = fetch, deps = {}) {
18
69
  this.config = config;
19
70
  this.fetchImpl = fetchImpl;
71
+ this.deps = {
72
+ now: Date.now,
73
+ sleep: holdingSleep,
74
+ pingSleep: unrefSleep,
75
+ policy: REQUEST_POLICY,
76
+ log: (line) => console.error(line),
77
+ ...deps,
78
+ };
79
+ this.reachability = new DashboardReachability({
80
+ now: this.deps.now,
81
+ ping: () => this.ping(),
82
+ sleep: this.deps.pingSleep,
83
+ log: this.deps.log,
84
+ });
20
85
  }
21
86
  /**
22
87
  * DX-4390 — the bearer this client stamps. A session signs in (or out) while the server runs, so
@@ -31,9 +96,13 @@ export class DashboardHttpClient {
31
96
  * permission-request create) goes through `request` instead. No call site sets `background` by hand.
32
97
  */
33
98
  requestOwn(args) {
34
- return this.request({ ...args, background: true });
99
+ return this.send({ ...args, background: true }, "own");
35
100
  }
36
- async request(args) {
101
+ /** A request the agent made: its read is retried through a deploy restart, its write is sent once (see the module doc). */
102
+ request(args) {
103
+ return this.send(args, "agent");
104
+ }
105
+ async send(args, caller) {
37
106
  if (this.config.token === "") {
38
107
  // DX-4390 — a caller reaches here only past the sign-in halt; a bearer-less call is a bug.
39
108
  throw new Error("[platform-mcp] request attempted while signed out");
@@ -82,17 +151,106 @@ export class DashboardHttpClient {
82
151
  headers["Content-Type"] = "application/json";
83
152
  payload = JSON.stringify(this.withBodyBoard(args));
84
153
  }
85
- let res;
154
+ const write = !isReadRoute(args.method, routePathOf(args.path, args.basePath));
155
+ const policy = this.deps.policy;
156
+ // DX-7110: a read the agent made rides out a blip; a write, a request of this process's own, and any call made while 50 Arms is recorded
157
+ // unreachable get one attempt (the last a short one, so the answer comes at once).
158
+ const retrying = caller === "agent" && !write && !this.reachability.isUnreachable();
159
+ const startedAt = this.deps.now();
160
+ for (let attempt = 0;; attempt++) {
161
+ const outcome = await this.attemptOnce(args.method, url, { headers, body: payload }, this.attemptMs(caller, write, retrying, policy.readWindowMs - (this.deps.now() - startedAt)));
162
+ const verdict = verdictOf(outcome);
163
+ if (verdict === "down")
164
+ this.reachability.noteFailure();
165
+ else
166
+ this.reachability.noteReachable();
167
+ if (outcome.kind === "response") {
168
+ if (verdict === "answer" || (verdict === "busy" && !retrying))
169
+ return this.answerOf(outcome, args.method, url, write);
170
+ }
171
+ if (retrying) {
172
+ const backoffMs = backoffAt(policy.backoffMs, attempt);
173
+ if (policy.readWindowMs - (this.deps.now() - startedAt) > backoffMs) {
174
+ await this.deps.sleep(backoffMs);
175
+ continue;
176
+ }
177
+ // Out of window. A dashboard that kept saying "come back later" is up and busy: its last words are the answer.
178
+ if (outcome.kind === "response" && verdict === "busy")
179
+ return this.answerOf(outcome, args.method, url, write);
180
+ }
181
+ throw this.unreachable(args.method, url, write, outcome, caller, retrying ? this.deps.now() - startedAt : 0);
182
+ }
183
+ }
184
+ /**
185
+ * The bound of one attempt: a read's is clipped to what is left of its window, so the window is a real limit on the call. This process's own
186
+ * requests get the bound of their kind (a GET the read bound, a POST the write bound): a blip that lasts 8-27 s must not fail them early.
187
+ */
188
+ attemptMs(caller, write, retrying, remainingMs) {
189
+ const policy = this.deps.policy;
190
+ if (retrying)
191
+ return Math.max(1, Math.min(policy.readAttemptMs, remainingMs));
192
+ if (caller === "agent" && this.reachability.isUnreachable())
193
+ return policy.shortAttemptMs;
194
+ return write ? policy.writeAttemptMs : policy.readAttemptMs;
195
+ }
196
+ /** One bounded request, answer body included: the bound ends when the body has been read, not when the headers arrive. */
197
+ async attemptOnce(method, url, init, timeoutMs) {
198
+ const bound = boundRequest(timeoutMs);
86
199
  try {
87
- res = await this.fetchImpl(url, {
88
- method: args.method,
89
- headers,
90
- body: payload,
200
+ const res = await this.fetchImpl(url, {
201
+ method,
202
+ headers: init.headers,
203
+ body: init.body,
204
+ signal: bound.signal,
91
205
  });
206
+ return {
207
+ kind: "response",
208
+ status: res.status,
209
+ headers: res.headers,
210
+ text: await res.text(),
211
+ };
92
212
  }
93
213
  catch (err) {
94
- throw new Error(`[platform-mcp] network failure on ${args.method} ${url}: ${err instanceof Error ? err.message : String(err)}`);
214
+ const codes = codesOf(err);
215
+ // A request URL fetch cannot parse is a configuration bug, not 50 Arms being away.
216
+ if (codes.includes("ERR_INVALID_URL"))
217
+ throw err;
218
+ if (bound.aborted())
219
+ return {
220
+ kind: "failed",
221
+ detail: `timed out after ${Math.round(timeoutMs / 1000)} s`,
222
+ sent: true,
223
+ };
224
+ return {
225
+ kind: "failed",
226
+ detail: describeFailure(err),
227
+ sent: !codes.some((code) => NEVER_SENT_CODES.has(code)),
228
+ };
229
+ }
230
+ finally {
231
+ bound.release();
95
232
  }
233
+ }
234
+ unreachable(method, url, write, outcome, caller, triedMs) {
235
+ // DX-7110: an agent's call that is out of retries (a write has none) is the outage; this process's own request is only one more failure.
236
+ if (caller === "agent")
237
+ this.reachability.noteUnreachable();
238
+ const applied = outcome.kind === "failed" && !outcome.sent ? false : "unknown";
239
+ const detail = outcome.kind === "failed" ? outcome.detail : `HTTP ${outcome.status}`;
240
+ const message = outcome.kind === "failed"
241
+ ? `[platform-mcp] network failure on ${method} ${url}: ${detail}`
242
+ : `[platform-mcp] server error ${outcome.status} on ${method} ${url}: ${outcome.text.slice(0, 500)}`;
243
+ return new DashboardUnreachableError(message, {
244
+ method: `${method} ${new URL(url).pathname}`,
245
+ write,
246
+ applied,
247
+ detail,
248
+ since: this.reachability.unreachableSinceMs(),
249
+ triedMs,
250
+ });
251
+ }
252
+ /** The dashboard's own answer to a request, passed through as the module doc says. */
253
+ answerOf(res, method, url, write) {
96
254
  // DX-3597 — proactive on the first call this instance ever makes
97
255
  // (regardless of outcome: a stale client can otherwise look fine for a
98
256
  // while on routes whose shape didn't change), and on every subsequent
@@ -105,7 +263,10 @@ export class DashboardHttpClient {
105
263
  if (isFirstCall || (res.status >= 400 && res.status < 500)) {
106
264
  assertVersionFloorSatisfied(res.headers.get(MCP_MIN_VERSION_HEADER));
107
265
  }
108
- const text = await res.text();
266
+ const text = res.text;
267
+ if (res.status >= 500) {
268
+ throw new DashboardServerError(`[platform-mcp] server error ${res.status} on ${method} ${url}: ${text.slice(0, 500)}`, { status: res.status, write, text: text.slice(0, 500) });
269
+ }
109
270
  let parsed = null;
110
271
  if (text !== "") {
111
272
  try {
@@ -114,17 +275,32 @@ export class DashboardHttpClient {
114
275
  catch {
115
276
  // Non-JSON response from a v2 route is a server-side fault —
116
277
  // throw rather than fabricate an envelope.
117
- throw new Error(`[platform-mcp] non-JSON response (status ${res.status}) from ${args.method} ${url}: ${text.slice(0, 200)}`);
278
+ throw new Error(`[platform-mcp] non-JSON response (status ${res.status}) from ${method} ${url}: ${text.slice(0, 200)}`);
118
279
  }
119
280
  }
120
- if (res.status >= 500) {
121
- throw new Error(`[platform-mcp] server error ${res.status} on ${args.method} ${url}: ${text.slice(0, 500)}`);
122
- }
123
281
  if (res.status >= 200 && res.status < 300) {
124
282
  return { ok: true, status: res.status, body: parsed };
125
283
  }
126
284
  return { ok: false, status: res.status, body: parsed };
127
285
  }
286
+ /**
287
+ * DX-7110 - one `GET /health` attempt, for the reachability ping: whether 50 Arms answered healthy. The probe is public (no bearer) and
288
+ * a failure to connect is its answer, `false`, not an error.
289
+ */
290
+ async ping() {
291
+ const bound = boundRequest(this.deps.policy.shortAttemptMs);
292
+ try {
293
+ const res = await this.fetchImpl(`${this.config.baseUrl.replace(/\/+$/, "")}/health`, { method: "GET", signal: bound.signal });
294
+ await res.body?.cancel();
295
+ return res.status === 200;
296
+ }
297
+ catch {
298
+ return false;
299
+ }
300
+ finally {
301
+ bound.release();
302
+ }
303
+ }
128
304
  /**
129
305
  * DX-5337 - the body of a request whose route reads the board from `body.board` (issue create/import): the board the caller wrote is kept;
130
306
  * with none, the call's `board` argument or the dispatch's board is filled in. DX-3465 deleted the per-operation `issue_create` tool that
package/dist/index.js CHANGED
@@ -78,7 +78,8 @@ import { compactionFilesIn } from "./compaction-control.js";
78
78
  import { clearFilesIn } from "./clear-control.js";
79
79
  import { PlanEventRelay, WAIT_MAX_MS, WAIT_MIN_MS, } from "./plan-events-relay.js";
80
80
  import { READ_IDLE_TIMEOUT_MS } from "./listen.js";
81
- import { REQUEST_TIMEOUT_MS, realScheduleInterval, realSleep, } from "./session-stream.js";
81
+ import { realScheduleInterval, realSleep } from "./session-stream.js";
82
+ import { REQUEST_POLICY } from "./request-policy.js";
82
83
  import { servePlanEventsWait } from "./plan-events-tool.js";
83
84
  import { lookupRestartNotice, RESTART_NOTICE_ARGS } from "./restart-notice.js";
84
85
  import { HOST_SESSION_ID_ENV, startSessionHostClaim, } from "./session-host.js";
@@ -93,7 +94,8 @@ import { JobKeyHolder, sendWithJobKey } from "./job-key.js";
93
94
  import { readOwnVersion } from "./version-floor.js";
94
95
  import { createCheckoutDocsRootReporter, readCheckoutRepo, } from "./checkout-docs-root.js";
95
96
  import { isPickupConnect, projectKeyOf, recordSessionConnectionAfterConnect, removeSessionConnectionAfterLeave, } from "./session-connection.js";
96
- import { createListenerReminder, isPlanConnectedOnThisMachine, } from "./listener-reminder.js";
97
+ import { createListenerReminder, isPlanConnectedOnThisMachine, mergeReminders, } from "./listener-reminder.js";
98
+ import { isUnreachableAnswer } from "./dashboard-errors.js";
97
99
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
98
100
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
99
101
  import { z } from "zod";
@@ -111,7 +113,7 @@ import { bodyValueSchema, queryValueSchema } from "./types.js";
111
113
  import { termsAcceptanceCallHalt, termsHaltFor } from "./terms-halt.js";
112
114
  import { danxbotApiExamplesText } from "./danxbot-api-examples.js";
113
115
  import { assertWithinTextLimit } from "./text-limit.js";
114
- import { registerLifecycleTools, presentCallbacksFromEnv, } from "./lifecycle.js";
116
+ import { callbackRoute, registerLifecycleTools, presentCallbacksFromEnv, } from "./lifecycle.js";
115
117
  import { LEGACY_TOOL_NAMES, TOOL_ACCESS } from "./tool-access.js";
116
118
  import { ToolAccessSync, ToolSurface } from "./tool-surface.js";
117
119
  import { PermissionWatch } from "./permission-watch.js";
@@ -256,7 +258,8 @@ function boot() {
256
258
  sleep: realSleep,
257
259
  now: Date.now,
258
260
  readIdleTimeoutMs: READ_IDLE_TIMEOUT_MS,
259
- requestTimeoutMs: REQUEST_TIMEOUT_MS,
261
+ requestTimeoutMs: REQUEST_POLICY.relayAttemptMs,
262
+ reachability: dashboardClient.reachability,
260
263
  scheduleInterval: realScheduleInterval,
261
264
  compactionFiles: compactionFilesIn(),
262
265
  clearFiles: clearFilesIn(),
@@ -589,7 +592,13 @@ function renamedTool(name, description, shape, handlerFor) {
589
592
  // ---------------- lifecycle tool set (DX-3465 / PLN-11 R-25, DX-4525) ----------------
590
593
  // One tool is left, `50arms_slack_reply` (it reads local files); every other dispatch callback is a `50arms_api` call
591
594
  // (see `lifecycle.ts`). `toolsFor` (`tool-access.ts`) decides whether a session sees it.
592
- registerLifecycleTools(renamedTool);
595
+ // DX-7110: the reply is one of the client's own requests, so it carries the bearer, the write policy and the `dashboard_unreachable` answer of every other call.
596
+ registerLifecycleTools(renamedTool, (callbackUrl, body) => guardedCall(() => client.request({
597
+ method: "POST",
598
+ basePath: "",
599
+ path: callbackRoute(callbackUrl, config.baseUrl),
600
+ body,
601
+ })));
593
602
  // Optional per-call board override shared by every tool. Omitted → the
594
603
  // dispatch's env-derived board (`DANXBOT_BOARD_ID`) is used; provided → that
595
604
  // board is targeted instead (the dashboard owns board→repo and 404s an
@@ -688,7 +697,11 @@ renamedTool("50arms_api",
688
697
  // DX-6556: a manual pickup that connected the session is a connect, whatever tool carried it.
689
698
  if (isPickupConnect(spilled))
690
699
  return finishConnect(calledAs, spilled, false);
691
- return boundedJsonResult(await listenerReminder.apply(spilled));
700
+ // DX-7110: an answer that says 50 Arms is unreachable is not followed by a health read of it; either way the notices no relay carried ride on it.
701
+ const answered = isUnreachableAnswer(spilled)
702
+ ? spilled
703
+ : await listenerReminder.apply(spilled);
704
+ return boundedJsonResult(mergeReminders(answered, client.reachability.takePending()));
692
705
  });
693
706
  // ---------------- 50arms_api_list (DX-3465 A5, PLN-11 R-25) ----------------
694
707
  renamedTool("50arms_api_list",
package/dist/lifecycle.js CHANGED
@@ -16,32 +16,25 @@ import { readFile, stat } from "node:fs/promises";
16
16
  import { basename, isAbsolute } from "node:path";
17
17
  import { z } from "zod";
18
18
  import { CALLBACK_ENV } from "./tool-access.js";
19
- import { CREDENTIAL_TOKEN_ENV } from "./credential.js";
20
19
  /** The callbacks whose URL the worker injected into this process's environment (an empty value reads as absent): what `toolsFor` takes as this dispatch's callbacks. */
21
20
  export function presentCallbacksFromEnv() {
22
21
  return new Set(Object.keys(CALLBACK_ENV).filter((name) => (process.env[CALLBACK_ENV[name]] ?? "") !== ""));
23
22
  }
24
- async function postJson(url, body, bearer) {
25
- return fetch(url, {
26
- method: "POST",
27
- headers: {
28
- "Content-Type": "application/json",
29
- Authorization: `Bearer ${bearer}`,
30
- },
31
- body: JSON.stringify(body),
32
- });
33
- }
34
23
  /**
35
- * DX-4525 - the dispatch's own credential, the one `50arms_api` calls the dashboard with: a dispatch declares it in
36
- * `DANX_DASHBOARD_CREDENTIAL` (`credential.ts`) and it never signs out. Read here, not through the late-bound `SessionAccess`,
37
- * so the tool works wherever the module is imported; a missing one is a loud failure, never an unauthenticated post.
24
+ * DX-7110 - the route a callback URL names, on the dashboard this server is connected to. The reply goes out through `DashboardHttpClient` (its
25
+ * bearer, its bound, its write policy and its `dashboard_unreachable` answer), which only ever talks to that one dashboard: a URL on another host
26
+ * is a wiring bug and fails here, never a request carrying this session's key somewhere else. Only the path is carried over, so a URL with a query
27
+ * string is refused too: dropping it silently would send a different request than the one the worker named.
38
28
  */
39
- function dispatchCredential(calledAs) {
40
- const token = process.env[CREDENTIAL_TOKEN_ENV];
41
- if (typeof token !== "string" || token.trim() === "") {
42
- throw new Error(`${calledAs}: ${CREDENTIAL_TOKEN_ENV} is not set for this dispatch`);
29
+ export function callbackRoute(callbackUrl, dashboardUrl) {
30
+ const callback = new URL(callbackUrl);
31
+ if (callback.origin !== new URL(dashboardUrl).origin) {
32
+ throw new Error(`the callback URL ${callbackUrl} is not on this server's dashboard ${dashboardUrl}`);
33
+ }
34
+ if (callback.search !== "") {
35
+ throw new Error(`the callback URL ${callbackUrl} carries a query string, which the reply does not send`);
43
36
  }
44
- return token.trim();
37
+ return callback.pathname;
45
38
  }
46
39
  /** Must match `MAX_DECODED_BYTES` in danxbot's `src/issues/attachment-limits.ts` (duplicated, not imported: this package is published on its own). */
47
40
  const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
@@ -73,16 +66,14 @@ async function readAttachments(paths) {
73
66
  };
74
67
  }));
75
68
  }
76
- /** A refused callback's body is the only place the server says why — relay it, never just the status. */
77
- async function responseFailure(label, response) {
78
- const text = await response.text();
79
- return new Error(`${label} returned HTTP ${response.status}${text ? `: ${text}` : ""}`);
69
+ function failure(text) {
70
+ return { content: [{ type: "text", text }], isError: true };
80
71
  }
81
72
  /**
82
73
  * Registers the lifecycle tool on `server` via the caller's `strictTool` wrapper (so it gets the same DX-3238 strict-shape
83
74
  * guard the rest of this package's tools use).
84
75
  */
85
- export function registerLifecycleTools(renamedTool) {
76
+ export function registerLifecycleTools(renamedTool, postReply) {
86
77
  // ---------------- 50arms_slack_reply (and `danxbot_slack_reply` until DX-6864) ----------------
87
78
  renamedTool("50arms_slack_reply",
88
79
  // DX-4253 — no ordering against another tool here: the Slack persona (`src/agent/persona.ts`) and the
@@ -104,9 +95,13 @@ export function registerLifecycleTools(renamedTool) {
104
95
  const body = { text: args.text };
105
96
  if (files.length > 0)
106
97
  body.files = files;
107
- const response = await postJson(url, body, dispatchCredential(calledAs));
108
- if (!response.ok)
109
- throw await responseFailure("Slack reply API", response);
98
+ // DX-7110: a halt, a refusal and a request that got no answer all reach the agent as an error saying so; the last as the same
99
+ // `dashboard_unreachable` answer a `50arms_api` call gets, whose `applied` says whether the reply may have been posted.
100
+ const guarded = await postReply(url, body);
101
+ if ("halt" in guarded)
102
+ return failure(guarded.halt);
103
+ if (!guarded.result.ok)
104
+ return failure(JSON.stringify(guarded.result));
110
105
  return {
111
106
  content: [
112
107
  {
@@ -24,6 +24,31 @@ function readReminders(result) {
24
24
  }
25
25
  return reminders.map(({ key, text }) => ({ key, text }));
26
26
  }
27
+ /**
28
+ * DX-7110 - `result` with `extra` appended to its body's `reminders[]` (a key the body already carries is not repeated). A body that is not a
29
+ * JSON object, or whose own `reminders` is not an array, is returned as it is: a reminder never alters an answer it cannot sit beside.
30
+ */
31
+ export function mergeReminders(result, extra) {
32
+ const body = result.body;
33
+ if (typeof body !== "object" || body === null || Array.isArray(body))
34
+ return result;
35
+ const existing = body.reminders;
36
+ if (existing !== undefined && !Array.isArray(existing))
37
+ return result;
38
+ const present = new Set((existing ?? []).map((r) => (isReminder(r) ? r.key : null)));
39
+ const fresh = extra.filter((r) => {
40
+ if (present.has(r.key))
41
+ return false;
42
+ present.add(r.key);
43
+ return true;
44
+ });
45
+ if (fresh.length === 0)
46
+ return result;
47
+ return {
48
+ ...result,
49
+ body: { ...body, reminders: [...(existing ?? []), ...fresh] },
50
+ };
51
+ }
27
52
  export function createListenerReminder(deps) {
28
53
  let cached = null;
29
54
  let inFlight = null;
@@ -97,20 +122,7 @@ export function createListenerReminder(deps) {
97
122
  }
98
123
  return result;
99
124
  }
100
- const relayed = await remindersNow();
101
- const present = new Set((existing ?? []).map((r) => (isReminder(r) ? r.key : null)));
102
- const fresh = relayed.filter((r) => {
103
- if (present.has(r.key))
104
- return false;
105
- present.add(r.key);
106
- return true;
107
- });
108
- if (fresh.length === 0)
109
- return result;
110
- return {
111
- ...result,
112
- body: { ...body, reminders: [...(existing ?? []), ...fresh] },
113
- };
125
+ return mergeReminders(result, await remindersNow());
114
126
  },
115
127
  invalidate() {
116
128
  generation += 1;
@@ -612,7 +612,7 @@ var readOwnManifest = () => JSON.parse(
612
612
  readFileSync(new URL("../../package.json", import.meta.url), "utf8")
613
613
  ).version;
614
614
  var TOOLKIT_VERSION = resolveToolkitVersion(
615
- false ? void 0 : "0.1.469",
615
+ false ? void 0 : "0.1.471",
616
616
  readOwnManifest
617
617
  );
618
618
  function envelope(now) {
@@ -334,7 +334,7 @@ export class PlanEventRelay {
334
334
  },
335
335
  http: this.deps,
336
336
  makeStatsWatcher: this.deps.makeStatsWatcher,
337
- now: this.deps.now,
337
+ reachability: this.deps.reachability,
338
338
  connection: () => heartbeatConnection(this.connectionState, this.stoppedReason, this.lastInventoryError),
339
339
  streaming: () => this.connectionState === "streaming",
340
340
  // `origin: null` skips the agent/machine hold: the notice reaches the session at once. It is about the session, not a plan.
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * DX-4632 - the ONE bound every dashboard request of this package shares: a timeout of its own, plus an OUTER signal that ends
3
- * the request early (a lookup's one deadline, a closed relay). Used by `sendSessionRequest` (`restart-notice.ts`) and by `request` in `session-stream.ts` (the relay's mint, inventory and
4
- * heartbeat), so the controller, the timer, the link to the outer signal and the cleanup exist once.
3
+ * the request early (a lookup's one deadline, a closed relay). Used by `sendSessionRequest` (`restart-notice.ts`), by `request` in `session-stream.ts` (the relay's mint, inventory and
4
+ * heartbeat), and (DX-7110) by every attempt of `DashboardHttpClient` (an agent's calls, this process's own and the Slack reply) and the public sign-in calls (`access-request.ts`), so the controller, the timer, the link to the outer signal and the cleanup exist once. The long-lived streams (the event stream, the permission watch) are
5
+ * the one kind of request with no timeout: they end when they are closed or read nothing for too long (`listen.ts`).
5
6
  */
6
7
  export function boundRequest(timeoutMs, outer) {
7
8
  const controller = new AbortController();
@@ -0,0 +1,13 @@
1
+ export const REQUEST_POLICY = {
2
+ readAttemptMs: 30_000,
3
+ writeAttemptMs: 120_000,
4
+ relayAttemptMs: 10_000,
5
+ shortAttemptMs: 5_000,
6
+ readWindowMs: 90_000,
7
+ backoffMs: [1_000, 2_000, 4_000, 8_000, 15_000],
8
+ pingBackoffMs: [1_000, 2_000, 4_000, 8_000, 15_000, 30_000],
9
+ };
10
+ /** The wait at retry `attempt` (0-based) of a backoff schedule: the last entry repeats. */
11
+ export function backoffAt(waits, attempt) {
12
+ return waits[Math.min(attempt, waits.length - 1)];
13
+ }
@@ -108,3 +108,11 @@ export const BODY_BOARD_ROUTES = [
108
108
  ["POST", "/api/issues"],
109
109
  ["POST", "/api/issues/import"],
110
110
  ];
111
+ /** DX-7110 - the GET route templates that write (`readOnlyException`): a GET is a read, safe to retry, unless it is listed here. */
112
+ export const WRITING_GET_ROUTES = [
113
+ "/api/dev-login",
114
+ "/api/dispatches/:dispatchId/pull",
115
+ "/api/github/callback",
116
+ "/api/plan-sessions/stream",
117
+ "/api/system-vitals",
118
+ ];
@@ -10,8 +10,10 @@
10
10
  *
11
11
  * Only GET routes are listed - the server refuses an unknown query key on a read alone - so every other method takes the key. A
12
12
  * GET path no template matches takes it too: the server answers it with a 404 whatever the query.
13
+ *
14
+ * DX-7110 - the same route table also says which GET routes WRITE (`WRITING_GET_ROUTES`), so `isReadRoute` can tell a request that is safe to retry.
13
15
  */
14
- import { BODY_BOARD_ROUTES, GET_ROUTE_BOARD_SCOPE, } from "./route-board-scope.generated.js";
16
+ import { BODY_BOARD_ROUTES, GET_ROUTE_BOARD_SCOPE, WRITING_GET_ROUTES, } from "./route-board-scope.generated.js";
15
17
  const RANK = { literal: 2, param: 1, rest: 0 };
16
18
  function compile(template, stamp) {
17
19
  const segments = template
@@ -73,3 +75,16 @@ export function takesBoardInBody(method, routePath) {
73
75
  const parts = routePath.replace(/\/+$/, "").slice(1).split("/");
74
76
  return BODY_BOARD.some((entry) => entry.method === method && matches(entry.route, parts));
75
77
  }
78
+ const WRITING_GETS = WRITING_GET_ROUTES.map((template) => compile(template, "stamp"));
79
+ /**
80
+ * DX-7110 - whether `<method> <routePath>` (no query string) only reads: a GET (the client sends no HEAD) whose route does not declare a
81
+ * `readOnlyException` in the server's route table. A read that failed in transit is sent again; anything else is sent once, because the
82
+ * first send may have been applied. A path no listed template matches is a read, like a GET path the table does not name: the listed
83
+ * templates are the only routes that write on a GET.
84
+ */
85
+ export function isReadRoute(method, routePath) {
86
+ if (method !== "GET")
87
+ return false;
88
+ const parts = routePath.replace(/\/+$/, "").slice(1).split("/");
89
+ return !WRITING_GETS.some((route) => matches(route, parts));
90
+ }
@@ -30,8 +30,6 @@ export const PLAN_MINE_PATH = "/api/plans/mine";
30
30
  // route, `plan-sessions-routes.ts#handleHeartbeat`). Every 15s this process
31
31
  // reports its truthful streaming state; see `sendHeartbeat` below.
32
32
  export const HEARTBEAT_PATH = "/api/plan-sessions/me/heartbeat";
33
- /** How long one dashboard request may take before it counts as a transient failure. */
34
- export const REQUEST_TIMEOUT_MS = 10_000;
35
33
  /** A freshly minted ticket refused this many times in a row is a terminal outcome, not a loop. */
36
34
  export const MAX_REFUSED_TICKETS_IN_A_ROW = 2;
37
35
  /** DX-3028 (AC1) — the dashboard's own heartbeat cadence; see the card's AC1. */
@@ -57,14 +55,6 @@ export const HEARTBEAT_INTERVAL_MS = 15_000;
57
55
  * of the obvious wrong fixes this constant is not).
58
56
  */
59
57
  export const HEARTBEAT_SILENT_FAILURE_THRESHOLD = 3;
60
- /**
61
- * DX-5088 - how long the heartbeat must keep failing to land (counted from the first failure, across every reconnect, until one
62
- * lands) before the MODEL is told. 5 minutes: a production deploy replaces the single dashboard container, an outage the
63
- * investigation measured at about 35 s (DX-5085 comment 14821), and the lock-convoy stalls around it ran 8-27 s more; 5 minutes is
64
- * roughly 8x the restart, so a deploy never wakes a session, while an outage that outlasts it is one the session's person should hear
65
- * about (the dashboard has long read the session `unattached`). Below it the self-heal is silent and logged to stderr.
66
- */
67
- export const HEARTBEAT_SUSTAINED_OUTAGE_MS = 5 * 60_000;
68
58
  const TRANSIENT_CLIENT_STATUSES = new Set([408, 429]);
69
59
  /**
70
60
  * One authenticated request, with a timeout, classifying the failures that are
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@50arms/platform-mcp",
3
- "version": "0.1.469",
3
+ "version": "0.1.471",
4
4
  "description": "Stdio MCP server fronting the 50 Arms dashboard API for agents (operator sessions and dispatched workers alike): the generic 50arms_api/50arms_api_list/50arms_api_spec tools reach any route the caller's credential may call, plus dedicated agent-specific tools (session_connect, request_permission, attach_file, and 50arms_slack_reply) (DX-3465, PLN-11 R-25).",
5
5
  "license": "MIT",
6
6
  "type": "module",