@50arms/platform-mcp 0.1.447 → 0.1.450

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
@@ -10,7 +10,6 @@ Stdio MCP server fronting the 50 Arms dashboard HTTP API. Since DX-3465 it expos
10
10
  |---|---|
11
11
  | `DANXBOT_DASHBOARD_URL` | Dashboard base, e.g. `http://danxbot-dashboard:5555` (inside compose) or `http://localhost:5555` (host). An operator session gets it from the 50arms plugin: its `dashboard_url` option (default the hosted dashboard), chosen per session folder: see the repo's `.claude/rules/dashboard-api-access.md`, the one owner of that rule |
12
12
  | `DANX_DASHBOARD_CREDENTIAL` | A DISPATCH's credential: the bearer verbatim, substituted into the materialized `.mcp.json` from its overlay (DX-2862, `src/credential.ts`). Authoritative when set; it never signs out. An operator session sets nothing: with no credential the server boots SIGNED OUT, every tool except `session_connect` returns one "not signed in" halt, and `session_connect` requests access (below). `restart_notice` uses the same resolver, so a session's tools and its predecessor lookups can never sign in as two different identities; the relay in this server (`plan_events_wait`) signs in with the server's own credential |
13
- | `DANXBOT_TEAM` | OPTIONAL, non-secret (DX-4446): the team slug (or id) whose approvers see this session's access request in their danxbot site. Set it in your shell or a repo's committed `.claude/settings.json` `env` block. Unset, the request is answered by link only. A value that is not a team slug fails at boot; a team the dashboard does not know makes `session_connect` answer `unknown_team` (fix `DANXBOT_TEAM`), never a silent link fallback |
14
13
  | `DANXBOT_BOARD_ID` | OPTIONAL (DX-4555, DX-5512): the dispatch's board, the board's ref, the positive integer that numbers it within its team (never its database id; the dispatch injects it). Anything else exits at boot. Unset (the 50arms plugin's own server) the server has no default board: a call that needs a board must carry its `board` argument or the dashboard answers 400 (plan and plan-session routes take their boards from the plan and need none) |
15
14
 
16
15
  BOARD-ONLY (DX-1171): board is the first-level concept; repo is DERIVED from board server-side, never passed. At boot the package reads the dispatch's board ref from `DANXBOT_BOARD_ID` and appends it as `?board=<ref>` (and `body.board` on create) to every `/api/issues/*` request, except `GET /api/issues` (the list), whose board is OPTIONAL (DX-4542): there it sends a board only when the caller names one, because no board is the team's whole list across every board. Each tool exposes an optional `board` arg - a board ref, the number (or its decimal text) - that overrides it per-call for cross-board reads/writes (unknown board -> 404). The dashboard owns board->repo resolution; this package never sends `repo`.
@@ -1,18 +1,8 @@
1
1
  import { assertVersionFloorSatisfied, MCP_MIN_VERSION_HEADER } from "./version-floor.js";
2
- // DX-4446: mirrors TEAM_SLUG_PATTERN in src/lib/auth-rules.ts (this package cannot import the main src/); a team ref is a slug,
3
- // and a team id's digits are a slug too. Keep the two in step.
4
- const TEAM_REF_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
5
- /** DX-4446: the `DANXBOT_TEAM` value, or a loud error naming the variable. */
6
- export function assertMcpTeamRef(value) {
7
- if (!TEAM_REF_PATTERN.test(value)) {
8
- throw new Error(`[platform-mcp] DANXBOT_TEAM "${value}" is not a team slug or id: lowercase letters and digits, joined by single hyphens`);
9
- }
10
- return value;
11
- }
12
2
  function baseOf(dashboardUrl) {
13
3
  return dashboardUrl.replace(/\/+$/, "");
14
4
  }
15
- async function postPublic(fetchImpl, url, body) {
5
+ export async function postPublic(fetchImpl, url, body) {
16
6
  let res;
17
7
  try {
18
8
  res = await fetchImpl(url, {
@@ -42,7 +32,7 @@ async function postPublic(fetchImpl, url, body) {
42
32
  }
43
33
  /** When a 429 carries no usable `Retry-After`, wait this long before the next try. */
44
34
  const DEFAULT_RETRY_AFTER_SECONDS = 1;
45
- function retryAfterSeconds(headers) {
35
+ export function retryAfterSeconds(headers) {
46
36
  const seconds = Number(headers.get("retry-after"));
47
37
  return Number.isFinite(seconds) && seconds > 0 ? seconds : DEFAULT_RETRY_AFTER_SECONDS;
48
38
  }
@@ -60,9 +50,8 @@ function isCreated(value) {
60
50
  export async function createAccessRequest(fetchImpl, dashboardUrl, input) {
61
51
  const url = `${baseOf(dashboardUrl)}/api/access-requests`;
62
52
  const { status, headers, json } = await postPublic(fetchImpl, url, input);
63
- if (status === 400 && input.team !== undefined && json?.error === "unknown_team") {
64
- return { kind: "unknown_team", team: input.team };
65
- }
53
+ if (status === 403 && json?.error === "machine_registration_mismatch")
54
+ return { kind: "machine_registration_mismatch" };
66
55
  if (status === 201) {
67
56
  if (!isCreated(json)) {
68
57
  throw new Error(`[platform-mcp] POST ${url} answered 201 without the access request fields: ${JSON.stringify(json)}`);
package/dist/index.js CHANGED
@@ -61,12 +61,6 @@
61
61
  * otherwise this session's approved key (`session-key.ts`), else none: the
62
62
  * server boots SIGNED OUT, every tool but `session_connect`
63
63
  * halts, and `session_connect` requests access (`session-access.ts`)
64
- * DANXBOT_TEAM OPTIONAL (DX-4446), non-secret: the team slug (or id) whose
65
- * approvers see this session's access request in their danxbot
66
- * site. Set it in your shell or a repo's committed `.claude/settings.json` `env` block.
67
- * Unset: the request is answered by link only. Set but not a
68
- * valid ref, or unknown to the dashboard: fails loud, never a
69
- * silent fall back to the link flow.
70
64
  * DANXBOT_BOARD_ID OPTIONAL (DX-4555): the dispatch's board, the board's ref number the worker injects;
71
65
  * a positive integer (anything else exits loudly), appended as ?board=<ref>.
72
66
  * Each tool's optional `board` arg (a board ref)
@@ -91,7 +85,6 @@ import { makeSessionStop, stopWhenSessionEnds } from "./shutdown.js";
91
85
  import { SUBAGENTS_LIVE_SUBCOMMAND, runSubagentsLiveCommand } from "./subagents-live.js";
92
86
  import { resolveBootCredential } from "./credential.js";
93
87
  import { SessionKeyUnusableError, deleteSessionKey } from "./session-key.js";
94
- import { assertMcpTeamRef } from "./access-request.js";
95
88
  import { SessionAccess } from "./session-access.js";
96
89
  import { PermissionRequests } from "./permission-request.js";
97
90
  import { makeGuardedCalls } from "./guarded-calls.js";
@@ -154,19 +147,6 @@ function readBoardId() {
154
147
  }
155
148
  return id;
156
149
  }
157
- /** DX-4446: optional `DANXBOT_TEAM`; set, it must be a valid team ref or boot fails loud (no fallback to the link flow). */
158
- function readTeamRef() {
159
- const team = readEnvOptional("DANXBOT_TEAM");
160
- if (team === undefined)
161
- return undefined;
162
- try {
163
- return assertMcpTeamRef(team);
164
- }
165
- catch (err) {
166
- console.error(err.message);
167
- process.exit(1);
168
- }
169
- }
170
150
  // The dispatch config + HTTP client are LATE-BOUND (assigned by `boot()` at
171
151
  // entrypoint, below). Tool registration happens at module import and the
172
152
  // callbacks close over these `let` bindings, reading them at CALL time — so the
@@ -219,7 +199,6 @@ function boot() {
219
199
  dashboardUrl,
220
200
  sessionId: session?.id,
221
201
  clientVersion: readOwnVersion(),
222
- team: readTeamRef(),
223
202
  readRepo: () => readCheckoutRepo(process.cwd()),
224
203
  setToken: (token) => dashboardClient.setToken(token),
225
204
  initial: resolveInitialCredential(dashboardUrl, session?.id),
@@ -880,16 +859,17 @@ strictTool("session_connect",
880
859
  // action's rule in the event line itself (`listen.ts`), the mantra in the reply's own `reminders[]` text.
881
860
  // DX-4390 — signed out, this is also how the session asks for access.
882
861
  // DX-4608 / DX-5549: a title in the format naming another agent than the held one is refused.
883
- "Connect THIS session to ONE plan or card, named by `target`: `PLAN-n`, or a card's id for a card on no plan. One call is enough to start; omit `target` only to sign in (it still takes your team agent). Signed out, it requests access: " +
862
+ "Connect THIS session to ONE plan or card, named by `target`: `PLAN-n`, or a card's id for a card on no plan. Omit `target` only to sign in (it still takes your team agent). Signed out, it requests access: " +
884
863
  "the reply is `state: approval_required` or `approval_pending` with an `approvalUrl` and `confirmCode` " +
885
864
  "(show the code, open the URL, then call again; a call re-asks an expired one). " +
886
- "Signed in, the reply carries `owedComments` (person comments no agent has answered yet: read first, answer each, ack then reply), `missedEvents` (operator " +
887
- "events no session had been told about: read next), `naming` and `listenerHealth` (when its `state` is not `healthy`, do its `nextStep`); " +
865
+ "Unregistered machine: `machine_registration_required` or `_pending` with `registrationUrl` and `claimCode`: give both to the user and stop. " +
866
+ "Signed in, the reply carries `owedComments` (unanswered person comments: read first, answer each, ack then reply), `missedEvents` (untold operator " +
867
+ "events: read next), `naming` and `listenerHealth` (when its `state` is not `healthy`, do its `nextStep`); " +
888
868
  "for a plan also `browserInstruction` (do it now), `briefing` (goals, rules, caveats, architecture, open cards) and `docsLandJob` (a docs land assignment's job). " +
889
- "A session holds a plan or a card, never both: connecting elsewhere moves it (`movedFrom` names the plan it left). " +
890
- "A plan holds one live session: another on it refuses the connect (`plan_has_live_session`); do not retry. " +
869
+ "Holds a plan or a card, never both: connecting elsewhere moves it (`movedFrom` names the plan it left). " +
870
+ "A plan's second session is refused `plan_has_live_session`; do not retry. " +
891
871
  "A card is refused `card_on_plan` when it or a card above it is on a plan (connect to that plan) and `card_held` when another live session holds it; holding one assigns it to you, like a manual pickup. " +
892
- "Afterwards `50arms_api` calls to `/api/plans/mine/...` act on your plan, no plan id. Connecting signs you in as a team agent; with none to sign in as: `agent_needed` or `agent_limit_reached` (the cap is full: ask the person), nothing connects: follow its `instruction`, " +
872
+ "Then `50arms_api` calls to `/api/plans/mine/...` act on your plan. Connecting signs you in as a team agent; with none to sign in as: `agent_needed` or `agent_limit_reached` (the cap is full: ask the person), nothing connects: follow its `instruction`, " +
893
873
  "no other dashboard work until `session_connect` holds an agent. A `naming` block (status `needed`) gives the exact " +
894
874
  "`title`, `{Name}: PLAN-NNN {short title}` or `{Name}: {CARD-ID} {card title}`; rename this thread to it (`set_session_title`, or ask for `/rename`), then connect again with that `title`. " +
895
875
  "A `title` in that format naming another agent than yours is refused `session_title_not_agent_name` with the title to use.", {
@@ -907,6 +887,13 @@ strictTool("session_connect",
907
887
  'The `naming` block\'s exact `{Name}: PLAN-NNN {short title}` or `{Name}: {CARD-ID} {card title}`, after renaming this thread. Omit on the first connect.'),
908
888
  assignment_id: z.number().int().positive().optional().describe("The assignment this connect answers, when a person's assignment message names one. Refused `assignment_ended` once it is over: then do nothing more about it."),
909
889
  disconnect: z.boolean().optional().describe("true = leave `target` (the plan or card you hold); no `title`."),
890
+ role: z
891
+ .string()
892
+ .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/)
893
+ .optional()
894
+ .describe(
895
+ // DX-6939: read only by a call that makes a sign-in claim; a signed-in session's call ignores it.
896
+ "The key of the team role this session's key is minted with when this call signs it in: default `agent`, the system agent role every team has. It must be an agent role within what the person this machine is registered to holds, or the sign-in is refused. Omit it unless a person named another role."),
910
897
  launch_token: z
911
898
  .string()
912
899
  .min(1)
@@ -918,11 +905,19 @@ strictTool("session_connect",
918
905
  .describe(
919
906
  // DX-6894 (DEC-589): set only by the plugin band when a PERSON presses its Sign in; the one call that leaves a revoked key's stop.
920
907
  "Set only by the plugin's Sign in button when a person presses it; an agent never sets it. On a session whose key a person revoked it lifts the stop and starts a new access request a person must approve; any call without it still answers the stop."),
908
+ registration_only: z
909
+ .boolean()
910
+ .optional()
911
+ .describe(
912
+ // DX-7010: set only by the plugin band; it answers before `ensureAccess`, so it makes no access request and claims no team agent.
913
+ "Set only by the plugin's band; an agent never sets it. Answers whether this machine is registered, `machine_registered` or the registration link, and makes no access request."),
921
914
  },
922
915
  // DX-2862 — the connect is also the moment the session's connection record is written for `restart_notice` and the listener reminder: of the
923
916
  // dashboard MCP servers a session may have configured, the one that connected the plan or card is the one whose credential they
924
917
  // must resolve (the relay needs none of this: it lives in each server, with that server's own credential).
925
918
  async (args) => {
919
+ if (args.registration_only === true)
920
+ return accessReply({ signedIn: false, ...(await access.registrationOnly()) });
926
921
  // DX-6894 — a person's Sign in press leaves the revoked stop; every call without it still answers that stop.
927
922
  if (args.person_sign_in === true)
928
923
  access.personSignIn();
@@ -931,7 +926,7 @@ async (args) => {
931
926
  return haltResult("session_connect: `disconnect: true` needs `target`, the plan or card this session currently holds");
932
927
  }
933
928
  // DX-4390 — no key yet: ask for one (or wait for the approval already asked for).
934
- const ready = await access.ensureAccess(args.title, args.launch_token);
929
+ const ready = await access.ensureAccess(args.title, args.launch_token, args.role);
935
930
  if (!ready.signedIn)
936
931
  return accessReply(ready);
937
932
  if (args.target === undefined) {
@@ -960,7 +955,7 @@ async (args) => {
960
955
  return haltResult(revokedHalt);
961
956
  // DX-4390 — the dashboard no longer accepts the stored key: drop it and ask again in the same call.
962
957
  if (result.status === 401 && access.dropKey(result)) {
963
- return accessReply(await access.ensureAccess(args.title), "the dashboard no longer accepted this session's key");
958
+ return accessReply(await access.ensureAccess(args.title, undefined, args.role), "the dashboard no longer accepted this session's key");
964
959
  }
965
960
  return finishConnect("session_connect", result, args.disconnect === true);
966
961
  });
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * DX-5902 — `install-daemon`, `status` and `uninstall-daemon` for the machine daemon.
3
3
  *
4
- * install: asks the dashboard for a `machine` access request (the DX-5809 flow), prints the approval link and confirm code, and
5
- * polls until a person approves. The approved key is used ONCE: to register this machine, which returns the machine's own
4
+ * install: a desktop (`dev`) registers at its claim-code link (DX-7010): the dashboard answers its machine id and its own reporting bearer. A worker host asks the dashboard for a `machine` access request (the DX-5809
5
+ * flow), prints the approval link and confirm code, and polls until a person approves; the approved key is used ONCE, to register this machine, which returns the machine's own
6
6
  * reporting bearer. The key is never written to disk or printed. The bearer goes to `machine-daemon.json` (0600). The daemon
7
7
  * and toolkit bundles are copied under `~/.danxbot/machine-daemon/` and the start-at-logon entry is registered.
8
8
  *
@@ -15,6 +15,8 @@ import { copyFileSync, existsSync, mkdirSync, rmSync } from "node:fs";
15
15
  import { hostname } from "node:os";
16
16
  import { join } from "node:path";
17
17
  import { claimAccessRequest } from "../access-request.js";
18
+ import { callMachineRegistration } from "../machine-registration.js";
19
+ import { machineSecretFor, machineSecretHome } from "../machine-secret.js";
18
20
  import { installAutostart, productionAutostartDeps, removeAutostart } from "./autostart.js";
19
21
  import { DAEMON_VERSION } from "./version.js";
20
22
  import { toolkitBundlePath, daemonBundleDir, daemonConfigPath, daemonStatusPath, danxbotHome, machineIdentityPath, readJsonIfPresent, writeOwnerOnlyJson, } from "./state.js";
@@ -76,16 +78,56 @@ async function registerWithKey(deps, machineId, machineKey) {
76
78
  throw new Error("machine registration answered without a reporting bearer");
77
79
  return bearer;
78
80
  }
81
+ /**
82
+ * DX-7010 (DEC-670): a desktop's daemon joins its machine's one row at the same claim-code link every session uses. The dashboard mints the machine's id and the daemon's reporting token, and authentication after this is unchanged.
83
+ */
84
+ async function registerDesktop(deps) {
85
+ const machineSecret = machineSecretFor(deps.dashboardUrl, { home: deps.machineHome });
86
+ let shownCode = null;
87
+ for (;;) {
88
+ const call = await callMachineRegistration(deps.fetchFn, deps.dashboardUrl, {
89
+ machineSecret,
90
+ machine: deps.label,
91
+ daemonVersion: DAEMON_VERSION,
92
+ profile: deps.profile,
93
+ });
94
+ switch (call.kind) {
95
+ case "accepted":
96
+ if (call.bearer === undefined)
97
+ throw new Error("the machine registration answered without a reporting bearer");
98
+ return { machineId: call.machineId, bearer: call.bearer };
99
+ case "pending":
100
+ if (call.claimCode !== shownCode) {
101
+ shownCode = call.claimCode;
102
+ deps.print(`Open this link, check the code is ${call.claimCode}, and register this machine:`);
103
+ deps.print(call.registrationUrl);
104
+ deps.print("Waiting for the registration...");
105
+ }
106
+ await deps.sleep(call.pollMs);
107
+ break;
108
+ case "rate_limited":
109
+ await deps.sleep(call.retryAfterSeconds * 1000);
110
+ break;
111
+ case "dashboard_outdated":
112
+ throw new Error("this dashboard does not support machine registration yet: it must be updated first");
113
+ case "refused":
114
+ throw new Error(`the dashboard refused the machine registration (HTTP ${call.status})`);
115
+ }
116
+ }
117
+ }
118
+ async function registerWorkerHost(deps) {
119
+ const existing = readJsonIfPresent(machineIdentityPath(deps.home));
120
+ const machineId = existing?.machine_id ?? deps.newId();
121
+ const machineKey = await approveMachineKey(deps);
122
+ return { machineId, bearer: await registerWithKey(deps, machineId, machineKey) };
123
+ }
79
124
  export async function installDaemon(deps) {
80
125
  // DX-6537: checked before registering, which replaces the bearer of a daemon already running here: a half-installed package changes nothing.
81
126
  for (const source of [deps.bundleSource, deps.toolkitBundleSource]) {
82
127
  if (!existsSync(source))
83
128
  throw new Error(`this package has no ${source}: it cannot install the daemon`);
84
129
  }
85
- const existing = readJsonIfPresent(machineIdentityPath(deps.home));
86
- const machineId = existing?.machine_id ?? deps.newId();
87
- const machineKey = await approveMachineKey(deps);
88
- const bearer = await registerWithKey(deps, machineId, machineKey);
130
+ const { machineId, bearer } = deps.kind === "dev" ? await registerDesktop(deps) : await registerWorkerHost(deps);
89
131
  writeOwnerOnlyJson(machineIdentityPath(deps.home), { machine_id: machineId });
90
132
  const config = {
91
133
  dashboard_url: base(deps.dashboardUrl),
@@ -159,6 +201,7 @@ export function productionInstallDeps(opts) {
159
201
  fetchFn: fetch,
160
202
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
161
203
  home,
204
+ machineHome: machineSecretHome(),
162
205
  bundleSource: opts.bundleSource,
163
206
  toolkitBundleSource: opts.toolkitBundleSource,
164
207
  autostart: autostartDeps,
@@ -0,0 +1,115 @@
1
+ /**
2
+ * DX-7010 (PLAN-116 G-3, R-10) - this machine's copy of its registration, and the one public dashboard call that starts and polls it.
3
+ *
4
+ * `~/.config/danxbot/machine-registrations/<sha12(dashboard url)>.json` (mode 0600): who the machine is registered to, for all future sign-ins. Its presence is what lets a session skip the registration step; a file of
5
+ * another shape is a loud error, never a guess (CLAUDE.md Core Principle 1). Every session on the machine writes the same content, so an atomic rename is enough.
6
+ */
7
+ import { readFileSync, rmSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { postPublic, retryAfterSeconds } from "./access-request.js";
11
+ import { writeFileDurable } from "./durable-write.js";
12
+ import { dashboardHash } from "./machine-secret.js";
13
+ export const MACHINE_REGISTRATION_SCHEMA_VERSION = 1;
14
+ export function machineRegistrationPath(dashboardUrl, home = homedir()) {
15
+ return join(home, ".config", "danxbot", "machine-registrations", `${dashboardHash(dashboardUrl)}.json`);
16
+ }
17
+ function unusable(path, why) {
18
+ return new Error(`[platform-mcp] the machine registration file ${path} is unusable: ${why}; fix or delete it, then call session_connect again`);
19
+ }
20
+ /** This machine's registration with `dashboardUrl`, or null when the file is absent. A file of another shape throws. */
21
+ export function readMachineRegistration(dashboardUrl, home) {
22
+ const path = machineRegistrationPath(dashboardUrl, home);
23
+ let raw;
24
+ try {
25
+ raw = readFileSync(path, "utf-8");
26
+ }
27
+ catch (err) {
28
+ if (err.code === "ENOENT")
29
+ return null;
30
+ throw unusable(path, err.message);
31
+ }
32
+ let parsed;
33
+ try {
34
+ parsed = JSON.parse(raw);
35
+ }
36
+ catch (err) {
37
+ throw unusable(path, `not JSON (${err.message})`);
38
+ }
39
+ if (typeof parsed !== "object" || parsed === null)
40
+ throw unusable(path, "it is not an object");
41
+ const record = parsed;
42
+ if (record.schemaVersion !== MACHINE_REGISTRATION_SCHEMA_VERSION) {
43
+ throw unusable(path, `schemaVersion is ${JSON.stringify(record.schemaVersion)}, not ${MACHINE_REGISTRATION_SCHEMA_VERSION}`);
44
+ }
45
+ for (const key of ["dashboardUrl", "machineId", "teamName", "username", "registeredAt"]) {
46
+ if (typeof record[key] !== "string")
47
+ throw unusable(path, `${key} is not a string`);
48
+ }
49
+ for (const key of ["teamId", "userId"]) {
50
+ if (typeof record[key] !== "number")
51
+ throw unusable(path, `${key} is not a number`);
52
+ }
53
+ if (record.dashboardUrl.replace(/\/+$/, "") !== dashboardUrl.replace(/\/+$/, "")) {
54
+ throw unusable(path, `it names the dashboard ${JSON.stringify(record.dashboardUrl)}, not ${dashboardUrl}`);
55
+ }
56
+ return record;
57
+ }
58
+ export function writeMachineRegistration(dashboardUrl, accepted, options) {
59
+ const record = {
60
+ schemaVersion: MACHINE_REGISTRATION_SCHEMA_VERSION,
61
+ dashboardUrl: dashboardUrl.replace(/\/+$/, ""),
62
+ machineId: accepted.machineId,
63
+ teamId: accepted.teamId,
64
+ teamName: accepted.teamName,
65
+ userId: accepted.userId,
66
+ username: accepted.username,
67
+ registeredAt: new Date(options.now).toISOString(),
68
+ };
69
+ writeFileDurable(machineRegistrationPath(dashboardUrl, options.home), JSON.stringify(record), { mode: 0o600 });
70
+ }
71
+ /**
72
+ * DX-6939 (DEC-655) - forget this machine's registration with `dashboardUrl`: the dashboard refused a sign-in as not matching it (released, or its person left the team), so the
73
+ * machine registers again. Absent already is fine: another session on the machine may have cleared it first.
74
+ */
75
+ export function deleteMachineRegistration(dashboardUrl, home) {
76
+ rmSync(machineRegistrationPath(dashboardUrl, home), { force: true });
77
+ }
78
+ function asPending(json, url) {
79
+ if (typeof json.claimCode !== "string" || typeof json.registrationUrl !== "string" || typeof json.pollMs !== "number") {
80
+ throw new Error(`[platform-mcp] POST ${url} answered pending without its fields: ${JSON.stringify(json)}`);
81
+ }
82
+ return { kind: "pending", claimCode: json.claimCode, registrationUrl: json.registrationUrl, pollMs: json.pollMs };
83
+ }
84
+ function asAccepted(json, url) {
85
+ if (typeof json.machineId !== "string" || typeof json.teamId !== "number" || typeof json.teamName !== "string" || typeof json.userId !== "number" || typeof json.username !== "string") {
86
+ throw new Error(`[platform-mcp] POST ${url} answered accepted without its fields: ${JSON.stringify(json)}`);
87
+ }
88
+ return {
89
+ kind: "accepted",
90
+ machineId: json.machineId,
91
+ teamId: json.teamId,
92
+ teamName: json.teamName,
93
+ userId: json.userId,
94
+ username: json.username,
95
+ ...(typeof json.bearer === "string" ? { bearer: json.bearer } : {}),
96
+ };
97
+ }
98
+ /** `POST /api/machine-registrations`, classified as `access-request.ts` classifies its calls. A 5xx or a network failure throws. */
99
+ export async function callMachineRegistration(fetchImpl, dashboardUrl, input) {
100
+ const url = `${dashboardUrl.replace(/\/+$/, "")}/api/machine-registrations`;
101
+ const { status, headers, json } = await postPublic(fetchImpl, url, input);
102
+ if (status === 200) {
103
+ const body = json;
104
+ if (body?.status === "pending")
105
+ return asPending(body, url);
106
+ if (body?.status === "accepted")
107
+ return asAccepted(body, url);
108
+ throw new Error(`[platform-mcp] POST ${url} answered an unknown status: ${JSON.stringify(json)}`);
109
+ }
110
+ if (status === 404)
111
+ return { kind: "dashboard_outdated" };
112
+ if (status === 429)
113
+ return { kind: "rate_limited", retryAfterSeconds: retryAfterSeconds(headers) };
114
+ return { kind: "refused", status, body: json };
115
+ }
@@ -22,8 +22,10 @@ export const MACHINE_SECRET_SCHEMA_VERSION = 1;
22
22
  /** The dashboard refuses a shorter secret (`MACHINE_SECRET_MIN` in `src/dashboard/access-request-routes.ts`); 32 random bytes as hex is twice that. */
23
23
  const SECRET_BYTES = 32;
24
24
  const SECRET_MIN_LENGTH = 32;
25
- const dashboardHash = (dashboardUrl) => createHash("sha256").update(dashboardUrl.replace(/\/+$/, "")).digest("hex").slice(0, 12);
26
- export function machineSecretPath(dashboardUrl, home = homedir()) {
25
+ export const dashboardHash = (dashboardUrl) => createHash("sha256").update(dashboardUrl.replace(/\/+$/, "")).digest("hex").slice(0, 12);
26
+ /** DX-7010: the one home every process on a host resolves the secret from, the MCP and the daemon's installer alike: a different home would be a second secret and a second identity for the host. */
27
+ export const machineSecretHome = () => homedir();
28
+ export function machineSecretPath(dashboardUrl, home = machineSecretHome()) {
27
29
  return join(home, ".config", "danxbot", "machine-secrets", `${dashboardHash(dashboardUrl)}.json`);
28
30
  }
29
31
  function unusable(path, why) {
@@ -250,7 +250,7 @@ function resolveToolkitVersion(stamped, readManifest) {
250
250
  return stamped ?? readManifest();
251
251
  }
252
252
  var readOwnManifest = () => JSON.parse(readFileSync2(new URL("../../package.json", import.meta.url), "utf8")).version;
253
- var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.447", readOwnManifest);
253
+ var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.450", readOwnManifest);
254
254
  function envelope(now) {
255
255
  return { contract_version: CONTRACT_VERSION, toolkit_version: TOOLKIT_VERSION, profile: PROFILE, measured_at: now.toISOString() };
256
256
  }
@@ -29,6 +29,7 @@ import { hostname } from "node:os";
29
29
  import { claimAccessRequest, createAccessRequest } from "./access-request.js";
30
30
  import { credentialFingerprint } from "./credential.js";
31
31
  import { keyRevocationOf, keyRevokedHalt } from "./key-revoked-halt.js";
32
+ import { callMachineRegistration, deleteMachineRegistration, readMachineRegistration, writeMachineRegistration, } from "./machine-registration.js";
32
33
  import { machineSecretFor } from "./machine-secret.js";
33
34
  import { deleteSessionKey, writeSessionKey } from "./session-key.js";
34
35
  import { McpOutdatedError } from "./version-floor.js";
@@ -52,11 +53,38 @@ const APPROVAL_PENDING_INSTRUCTION = "Still waiting for the user to approve; the
52
53
  /** DX-6764: a machine grant approved the request; nothing for the user to open or confirm, the next call picks the sign-in up. */
53
54
  const SIGNING_IN_INSTRUCTION = "This machine's auto-approval signs the session in; no approval link is involved. Call `session_connect` again in a moment.";
54
55
  const AUTO_APPROVED_EXPIRED_ERROR = "the dashboard approved this request by itself, but it expired before this process claimed the key; call session_connect again";
56
+ // DX-7010: the agent is the person's way to the link; the plugin's band shows the same link.
57
+ const MACHINE_REGISTRATION_REQUIRED_INSTRUCTION = "This machine is not registered with 50 Arms yet. Give the user the registration URL and the code; they open the link and check the code matches the one shown here. This is once per machine, and every session " +
58
+ "on it waits for the same link. End your turn now and do not poll: the session goes on when the user asks again.";
59
+ const MACHINE_REGISTRATION_PENDING_INSTRUCTION = "Still waiting for the user to register this machine. Remind them of the registration URL and the code, then end your turn; do not poll.";
60
+ const REGISTRATION_OUTDATED_ERROR = "this dashboard does not support machine registration yet (POST /api/machine-registrations answered 404): it must be updated before this session can sign in";
55
61
  const DENIED_INSTRUCTION = "The user denied the request. Do not retry unless they ask; a new `session_connect` makes a new request.";
56
62
  const DASHBOARD_OUTDATED_ERROR = "this dashboard does not support request-and-approve yet (POST /api/access-requests answered 404): " +
57
63
  "it must be updated before this session can sign in";
58
64
  const RATE_LIMITED_ERROR = "too many access requests from this address; wait, then call session_connect again";
59
- const unknownTeamError = (team) => `the dashboard has no team "${team}" (DANXBOT_TEAM); fix DANXBOT_TEAM in this server's env (your shell, or a repo's committed .claude/settings.json env block) and restart the session`;
65
+ /**
66
+ * DX-6939 - the role a session's sign-in claim asks for unless `session_connect` names another: the system agent role every team holds and cannot delete
67
+ * (`src/auth/permissions.ts`), what the app calls the default agent role.
68
+ */
69
+ export const DEFAULT_SESSION_ROLE = "agent";
70
+ /** DX-6939 - why the dashboard refused a sign-in claim, in words the agent can act on; null for a refusal it does not name. */
71
+ function claimRefusalError(body, role) {
72
+ const error = body?.error;
73
+ switch (error) {
74
+ case "unknown_role":
75
+ return `the team has no role "${role}"; call session_connect again without \`role\` (the default agent role) or with a role key the team has`;
76
+ case "role_exceeds_owner":
77
+ return `the role "${role}" holds permissions the person this machine is registered to lacks, so the dashboard refused the sign-in; ask them which role to use, or have a team admin widen their own role`;
78
+ case "session_role_must_be_agent":
79
+ return `the role "${role}" is a person's role, not an agent role; call session_connect again with an agent role, or without \`role\``;
80
+ case "claim_target_required":
81
+ return "the dashboard refused the sign-in for naming no team, person or role; update the 50 Arms plugin";
82
+ default:
83
+ return null;
84
+ }
85
+ }
86
+ /** DX-6939 - the dashboard kept refusing the claim as not matching this machine's registration even after the machine registered again. */
87
+ const REGISTRATION_STILL_MISMATCHED_ERROR = "the dashboard refused this sign-in as not matching this machine's registration even after the machine registered again; call session_connect again";
60
88
  const NO_SESSION_ID_ERROR = "this server has no CLAUDE_CODE_SESSION_ID, so it cannot request a session key";
61
89
  const CLAIMED_LOST_ERROR = "the dashboard says this request was already claimed, but this process never received the key; " +
62
90
  "start a new request";
@@ -105,6 +133,8 @@ export class SessionAccess {
105
133
  // DX-4418: set once the dashboard says a person revoked the key. Only `personSignIn` clears it (DX-6894); a restarted server is a new process.
106
134
  revoked = null;
107
135
  pending = null;
136
+ // DX-7010: at most one background poll per process, restarted after a settled one if the file is gone again.
137
+ registration = null;
108
138
  // DX-4390: two concurrent signed-out session_connect calls must not each post a request.
109
139
  ensureQueue = Promise.resolve();
110
140
  lastKeyFileWrite = 0;
@@ -242,12 +272,12 @@ export class SessionAccess {
242
272
  * (once per process) through the public claim route, with no person approving. Any answer but `approved` spends the token and
243
273
  * falls through to the person's request, the answer carrying a `note` that says why the token was not used.
244
274
  */
245
- ensureAccess(title, launchToken) {
246
- const run = this.ensureQueue.then(() => this.ensureAccessNow(title, launchToken));
275
+ ensureAccess(title, launchToken, role) {
276
+ const run = this.ensureQueue.then(() => this.ensureAccessNow(title, launchToken, role));
247
277
  this.ensureQueue = run.catch(() => undefined);
248
278
  return run;
249
279
  }
250
- async ensureAccessNow(title, launchToken) {
280
+ async ensureAccessNow(title, launchToken, role) {
251
281
  // DX-4418: a person revoked this session's access; it asks again only after `personSignIn` (DX-6894).
252
282
  const revokedHalt = this.revokedHalt();
253
283
  if (revokedHalt !== null)
@@ -274,19 +304,134 @@ export class SessionAccess {
274
304
  note = launchNote(launchRefusalWhy(claim));
275
305
  }
276
306
  }
307
+ // DX-7010: a machine with no registration makes no access request; `env` credentials and launch tokens returned above and never reach this.
308
+ const unregistered = await this.machineRegistrationAnswer(note);
309
+ if (unregistered !== null)
310
+ return unregistered;
277
311
  if (this.pending !== null) {
278
312
  const settled = await this.awaitPending(this.pending);
279
313
  if (settled !== "expired")
280
314
  return settled;
281
315
  note = EXPIRED_NOTE;
282
316
  }
283
- const created = await this.createRequest(sessionId, title, note);
317
+ const created = await this.createRequest(sessionId, title, note, role ?? DEFAULT_SESSION_ROLE);
284
318
  // DX-6801: a refused or failed request carries the launch note too, so the reason is never lost.
285
319
  if (note !== undefined && !created.signedIn && !("note" in created.answer)) {
286
320
  return { ...created, answer: { ...created.answer, note } };
287
321
  }
288
322
  return created;
289
323
  }
324
+ /**
325
+ * DX-7010: what `session_connect` with `registration_only` answers, set only by the plugin's band: no access request and no team agent. `machine_registered` once the file exists, else the two waiting states.
326
+ */
327
+ registrationOnly() {
328
+ const run = this.ensureQueue.then(async () => {
329
+ const unregistered = await this.machineRegistrationAnswer(undefined);
330
+ if (unregistered === null)
331
+ return { answer: { state: "machine_registered" }, isError: false };
332
+ if (unregistered.signedIn)
333
+ throw new Error("machineRegistrationAnswer never signs a session in");
334
+ return unregistered;
335
+ });
336
+ this.ensureQueue = run.catch(() => undefined);
337
+ return run;
338
+ }
339
+ /** Null when this machine holds a registration; otherwise the answer that says so. The first answer of a process is `required`, later ones wait up to `awaitMs` and are `pending`. */
340
+ async machineRegistrationAnswer(note) {
341
+ if (readMachineRegistration(this.deps.dashboardUrl, this.deps.home) !== null)
342
+ return null;
343
+ if (this.registration === null) {
344
+ const first = await this.callRegistration();
345
+ switch (first.kind) {
346
+ case "accepted":
347
+ this.storeRegistration(first);
348
+ return null;
349
+ case "pending":
350
+ this.registration = { latest: first, settled: Promise.resolve({ kind: "registered" }) };
351
+ this.registration.settled = this.pollRegistration(this.registration);
352
+ return notReady(this.registrationAnswer("machine_registration_required", first, note), false);
353
+ case "dashboard_outdated":
354
+ return notReady({ state: "dashboard_outdated", error: REGISTRATION_OUTDATED_ERROR }, true);
355
+ case "rate_limited":
356
+ return notReady({ state: "rate_limited", retryAfterSeconds: first.retryAfterSeconds, error: RATE_LIMITED_ERROR }, true);
357
+ case "refused":
358
+ return notReady({ state: "request_refused", status: first.status, body: first.body }, true);
359
+ }
360
+ }
361
+ const open = this.registration;
362
+ const outcome = await Promise.race([open.settled, this.sleep(this.awaitMs).then(() => null)]);
363
+ if (outcome === null)
364
+ return notReady(this.registrationAnswer("machine_registration_pending", open.latest, note), false);
365
+ this.registration = null;
366
+ if (outcome.kind === "failed")
367
+ return notReady({ state: "request_failed", error: outcome.error }, true);
368
+ return this.machineRegistrationAnswer(note);
369
+ }
370
+ registrationAnswer(state, pending, note) {
371
+ return {
372
+ state,
373
+ registrationUrl: pending.registrationUrl,
374
+ claimCode: pending.claimCode,
375
+ instruction: state === "machine_registration_required" ? MACHINE_REGISTRATION_REQUIRED_INSTRUCTION : MACHINE_REGISTRATION_PENDING_INSTRUCTION,
376
+ ...(note === undefined ? {} : { note }),
377
+ };
378
+ }
379
+ callRegistration() {
380
+ return callMachineRegistration(this.fetchImpl, this.deps.dashboardUrl, {
381
+ machineSecret: machineSecretFor(this.deps.dashboardUrl, { home: this.deps.home, now: this.now() }),
382
+ machine: this.deps.machine ?? hostname(),
383
+ });
384
+ }
385
+ storeRegistration(accepted) {
386
+ writeMachineRegistration(this.deps.dashboardUrl, accepted, { home: this.deps.home, now: this.now() });
387
+ }
388
+ /** Reads the local file first on every tick, so one session's write ends every other session's poll with no network call. */
389
+ async pollRegistration(open) {
390
+ let waitMs = open.latest.pollMs;
391
+ for (;;) {
392
+ await this.sleep(waitMs);
393
+ waitMs = open.latest.pollMs;
394
+ try {
395
+ if (readMachineRegistration(this.deps.dashboardUrl, this.deps.home) !== null)
396
+ return { kind: "registered" };
397
+ }
398
+ catch (err) {
399
+ return { kind: "failed", error: err.message };
400
+ }
401
+ let call;
402
+ try {
403
+ call = await this.callRegistration();
404
+ }
405
+ catch (err) {
406
+ if (err instanceof McpOutdatedError)
407
+ return { kind: "failed", error: err.message };
408
+ this.deps.log?.(`[platform-mcp] machine registration poll failed, retrying: ${err.message}`);
409
+ continue;
410
+ }
411
+ switch (call.kind) {
412
+ case "pending":
413
+ open.latest = call;
414
+ continue;
415
+ case "rate_limited":
416
+ waitMs = Math.max(open.latest.pollMs, call.retryAfterSeconds * 1000);
417
+ continue;
418
+ case "accepted":
419
+ try {
420
+ this.storeRegistration(call);
421
+ return { kind: "registered" };
422
+ }
423
+ catch (err) {
424
+ // A failed write is a retry: the next tick finds another session's file, or writes again.
425
+ this.deps.log?.(`[platform-mcp] could not store the machine registration, retrying: ${err.message}`);
426
+ continue;
427
+ }
428
+ case "dashboard_outdated":
429
+ return { kind: "failed", error: REGISTRATION_OUTDATED_ERROR };
430
+ case "refused":
431
+ return { kind: "failed", error: `the dashboard refused the machine registration (${call.status}): ${JSON.stringify(call.body)}` };
432
+ }
433
+ }
434
+ }
290
435
  /**
291
436
  * Wait up to `awaitMs` for the open request, then answer how it stands: signed in, still pending (the link to open, or for an
292
437
  * auto-approved request the plain "signing in" state, which has no link), denied or failed. `expired` is for the caller: a person's
@@ -308,7 +453,15 @@ export class SessionAccess {
308
453
  return "expired";
309
454
  }
310
455
  }
311
- async createRequest(sessionId, title, note) {
456
+ /**
457
+ * DX-6939 (DEC-613) - the sign-in claim: for the team and person this machine is registered to (its registration file, the MCP's one source of both) and `role`.
458
+ * A `machine_registration_mismatch` deletes the file and goes back through registration (DEC-655: the one place the file is cleared), then claims again once.
459
+ */
460
+ async createRequest(sessionId, title, note, role, reRegistered = false) {
461
+ const registration = readMachineRegistration(this.deps.dashboardUrl, this.deps.home);
462
+ // Only reached once `machineRegistrationAnswer` found the file, so a missing one is a bug, loud.
463
+ if (registration === null)
464
+ throw new Error("[platform-mcp] createRequest ran with no machine registration file");
312
465
  const repo = await this.deps.readRepo();
313
466
  const created = await createAccessRequest(this.fetchImpl, this.deps.dashboardUrl, {
314
467
  kind: "session",
@@ -317,18 +470,30 @@ export class SessionAccess {
317
470
  machine: this.deps.machine ?? hostname(),
318
471
  clientVersion: this.deps.clientVersion,
319
472
  ...(repo === null ? {} : { repo }),
320
- ...(this.deps.team === undefined ? {} : { team: this.deps.team }),
473
+ team: String(registration.teamId),
474
+ person: registration.userId,
475
+ role,
321
476
  machineSecret: machineSecretFor(this.deps.dashboardUrl, { home: this.deps.home, now: this.now() }),
322
477
  });
323
478
  switch (created.kind) {
324
479
  case "dashboard_outdated":
325
480
  return notReady({ state: "dashboard_outdated", error: DASHBOARD_OUTDATED_ERROR }, true);
326
- case "unknown_team":
327
- return notReady({ state: "unknown_team", team: created.team, error: unknownTeamError(created.team) }, true);
481
+ case "machine_registration_mismatch": {
482
+ if (reRegistered)
483
+ return notReady({ state: "request_failed", error: REGISTRATION_STILL_MISMATCHED_ERROR }, true);
484
+ deleteMachineRegistration(this.deps.dashboardUrl, this.deps.home);
485
+ this.registration = null;
486
+ const unregistered = await this.machineRegistrationAnswer(note);
487
+ if (unregistered !== null)
488
+ return unregistered;
489
+ return this.createRequest(sessionId, title, note, role, true);
490
+ }
328
491
  case "rate_limited":
329
492
  return notReady({ state: "rate_limited", retryAfterSeconds: created.retryAfterSeconds, error: RATE_LIMITED_ERROR }, true);
330
- case "refused":
331
- return notReady({ state: "request_refused", status: created.status, body: created.body }, true);
493
+ case "refused": {
494
+ const error = claimRefusalError(created.body, role);
495
+ return notReady({ state: "request_refused", status: created.status, body: created.body, ...(error === null ? {} : { error }) }, true);
496
+ }
332
497
  case "created":
333
498
  this.pending = { request: created.request, settled: this.pollUntilSettled(created.request) };
334
499
  // DX-6764: a machine grant approved it: no person decides, so the key is a claim away. Wait for it as a second call would,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@50arms/platform-mcp",
3
- "version": "0.1.447",
3
+ "version": "0.1.450",
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",