@50arms/platform-mcp 0.1.447 → 0.1.449

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.
@@ -12,7 +12,7 @@ export function assertMcpTeamRef(value) {
12
12
  function baseOf(dashboardUrl) {
13
13
  return dashboardUrl.replace(/\/+$/, "");
14
14
  }
15
- async function postPublic(fetchImpl, url, body) {
15
+ export async function postPublic(fetchImpl, url, body) {
16
16
  let res;
17
17
  try {
18
18
  res = await fetchImpl(url, {
@@ -42,7 +42,7 @@ async function postPublic(fetchImpl, url, body) {
42
42
  }
43
43
  /** When a 429 carries no usable `Retry-After`, wait this long before the next try. */
44
44
  const DEFAULT_RETRY_AFTER_SECONDS = 1;
45
- function retryAfterSeconds(headers) {
45
+ export function retryAfterSeconds(headers) {
46
46
  const seconds = Number(headers.get("retry-after"));
47
47
  return Number.isFinite(seconds) && seconds > 0 ? seconds : DEFAULT_RETRY_AFTER_SECONDS;
48
48
  }
package/dist/index.js CHANGED
@@ -880,16 +880,17 @@ strictTool("session_connect",
880
880
  // action's rule in the event line itself (`listen.ts`), the mantra in the reply's own `reminders[]` text.
881
881
  // DX-4390 — signed out, this is also how the session asks for access.
882
882
  // 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: " +
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. Omit `target` only to sign in (it still takes your team agent). Signed out, it requests access: " +
884
884
  "the reply is `state: approval_required` or `approval_pending` with an `approvalUrl` and `confirmCode` " +
885
885
  "(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`); " +
886
+ "Unregistered machine: `machine_registration_required` or `_pending` with `registrationUrl` and `claimCode`: give both to the user and stop. " +
887
+ "Signed in, the reply carries `owedComments` (unanswered person comments: read first, answer each, ack then reply), `missedEvents` (untold operator " +
888
+ "events: read next), `naming` and `listenerHealth` (when its `state` is not `healthy`, do its `nextStep`); " +
888
889
  "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. " +
890
+ "Holds a plan or a card, never both: connecting elsewhere moves it (`movedFrom` names the plan it left). " +
891
+ "A plan's second session is refused `plan_has_live_session`; do not retry. " +
891
892
  "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`, " +
893
+ "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
894
  "no other dashboard work until `session_connect` holds an agent. A `naming` block (status `needed`) gives the exact " +
894
895
  "`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
896
  "A `title` in that format naming another agent than yours is refused `session_title_not_agent_name` with the title to use.", {
@@ -918,11 +919,19 @@ strictTool("session_connect",
918
919
  .describe(
919
920
  // 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
921
  "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."),
922
+ registration_only: z
923
+ .boolean()
924
+ .optional()
925
+ .describe(
926
+ // DX-7010: set only by the plugin band; it answers before `ensureAccess`, so it makes no access request and claims no team agent.
927
+ "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
928
  },
922
929
  // 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
930
  // dashboard MCP servers a session may have configured, the one that connected the plan or card is the one whose credential they
924
931
  // must resolve (the relay needs none of this: it lives in each server, with that server's own credential).
925
932
  async (args) => {
933
+ if (args.registration_only === true)
934
+ return accessReply({ signedIn: false, ...(await access.registrationOnly()) });
926
935
  // DX-6894 — a person's Sign in press leaves the revoked stop; every call without it still answers that stop.
927
936
  if (args.person_sign_in === true)
928
937
  access.personSignIn();
@@ -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,108 @@
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 } 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
+ function asPending(json, url) {
72
+ if (typeof json.claimCode !== "string" || typeof json.registrationUrl !== "string" || typeof json.pollMs !== "number") {
73
+ throw new Error(`[platform-mcp] POST ${url} answered pending without its fields: ${JSON.stringify(json)}`);
74
+ }
75
+ return { kind: "pending", claimCode: json.claimCode, registrationUrl: json.registrationUrl, pollMs: json.pollMs };
76
+ }
77
+ function asAccepted(json, url) {
78
+ if (typeof json.machineId !== "string" || typeof json.teamId !== "number" || typeof json.teamName !== "string" || typeof json.userId !== "number" || typeof json.username !== "string") {
79
+ throw new Error(`[platform-mcp] POST ${url} answered accepted without its fields: ${JSON.stringify(json)}`);
80
+ }
81
+ return {
82
+ kind: "accepted",
83
+ machineId: json.machineId,
84
+ teamId: json.teamId,
85
+ teamName: json.teamName,
86
+ userId: json.userId,
87
+ username: json.username,
88
+ ...(typeof json.bearer === "string" ? { bearer: json.bearer } : {}),
89
+ };
90
+ }
91
+ /** `POST /api/machine-registrations`, classified as `access-request.ts` classifies its calls. A 5xx or a network failure throws. */
92
+ export async function callMachineRegistration(fetchImpl, dashboardUrl, input) {
93
+ const url = `${dashboardUrl.replace(/\/+$/, "")}/api/machine-registrations`;
94
+ const { status, headers, json } = await postPublic(fetchImpl, url, input);
95
+ if (status === 200) {
96
+ const body = json;
97
+ if (body?.status === "pending")
98
+ return asPending(body, url);
99
+ if (body?.status === "accepted")
100
+ return asAccepted(body, url);
101
+ throw new Error(`[platform-mcp] POST ${url} answered an unknown status: ${JSON.stringify(json)}`);
102
+ }
103
+ if (status === 404)
104
+ return { kind: "dashboard_outdated" };
105
+ if (status === 429)
106
+ return { kind: "rate_limited", retryAfterSeconds: retryAfterSeconds(headers) };
107
+ return { kind: "refused", status, body: json };
108
+ }
@@ -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.449", 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, 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,6 +53,11 @@ 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";
@@ -105,6 +111,8 @@ export class SessionAccess {
105
111
  // 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
112
  revoked = null;
107
113
  pending = null;
114
+ // DX-7010: at most one background poll per process, restarted after a settled one if the file is gone again.
115
+ registration = null;
108
116
  // DX-4390: two concurrent signed-out session_connect calls must not each post a request.
109
117
  ensureQueue = Promise.resolve();
110
118
  lastKeyFileWrite = 0;
@@ -274,6 +282,10 @@ export class SessionAccess {
274
282
  note = launchNote(launchRefusalWhy(claim));
275
283
  }
276
284
  }
285
+ // DX-7010: a machine with no registration makes no access request; `env` credentials and launch tokens returned above and never reach this.
286
+ const unregistered = await this.machineRegistrationAnswer(note);
287
+ if (unregistered !== null)
288
+ return unregistered;
277
289
  if (this.pending !== null) {
278
290
  const settled = await this.awaitPending(this.pending);
279
291
  if (settled !== "expired")
@@ -287,6 +299,117 @@ export class SessionAccess {
287
299
  }
288
300
  return created;
289
301
  }
302
+ /**
303
+ * 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.
304
+ */
305
+ registrationOnly() {
306
+ const run = this.ensureQueue.then(async () => {
307
+ const unregistered = await this.machineRegistrationAnswer(undefined);
308
+ if (unregistered === null)
309
+ return { answer: { state: "machine_registered" }, isError: false };
310
+ if (unregistered.signedIn)
311
+ throw new Error("machineRegistrationAnswer never signs a session in");
312
+ return unregistered;
313
+ });
314
+ this.ensureQueue = run.catch(() => undefined);
315
+ return run;
316
+ }
317
+ /** 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`. */
318
+ async machineRegistrationAnswer(note) {
319
+ if (readMachineRegistration(this.deps.dashboardUrl, this.deps.home) !== null)
320
+ return null;
321
+ if (this.registration === null) {
322
+ const first = await this.callRegistration();
323
+ switch (first.kind) {
324
+ case "accepted":
325
+ this.storeRegistration(first);
326
+ return null;
327
+ case "pending":
328
+ this.registration = { latest: first, settled: Promise.resolve({ kind: "registered" }) };
329
+ this.registration.settled = this.pollRegistration(this.registration);
330
+ return notReady(this.registrationAnswer("machine_registration_required", first, note), false);
331
+ case "dashboard_outdated":
332
+ return notReady({ state: "dashboard_outdated", error: REGISTRATION_OUTDATED_ERROR }, true);
333
+ case "rate_limited":
334
+ return notReady({ state: "rate_limited", retryAfterSeconds: first.retryAfterSeconds, error: RATE_LIMITED_ERROR }, true);
335
+ case "refused":
336
+ return notReady({ state: "request_refused", status: first.status, body: first.body }, true);
337
+ }
338
+ }
339
+ const open = this.registration;
340
+ const outcome = await Promise.race([open.settled, this.sleep(this.awaitMs).then(() => null)]);
341
+ if (outcome === null)
342
+ return notReady(this.registrationAnswer("machine_registration_pending", open.latest, note), false);
343
+ this.registration = null;
344
+ if (outcome.kind === "failed")
345
+ return notReady({ state: "request_failed", error: outcome.error }, true);
346
+ return this.machineRegistrationAnswer(note);
347
+ }
348
+ registrationAnswer(state, pending, note) {
349
+ return {
350
+ state,
351
+ registrationUrl: pending.registrationUrl,
352
+ claimCode: pending.claimCode,
353
+ instruction: state === "machine_registration_required" ? MACHINE_REGISTRATION_REQUIRED_INSTRUCTION : MACHINE_REGISTRATION_PENDING_INSTRUCTION,
354
+ ...(note === undefined ? {} : { note }),
355
+ };
356
+ }
357
+ callRegistration() {
358
+ return callMachineRegistration(this.fetchImpl, this.deps.dashboardUrl, {
359
+ machineSecret: machineSecretFor(this.deps.dashboardUrl, { home: this.deps.home, now: this.now() }),
360
+ machine: this.deps.machine ?? hostname(),
361
+ });
362
+ }
363
+ storeRegistration(accepted) {
364
+ writeMachineRegistration(this.deps.dashboardUrl, accepted, { home: this.deps.home, now: this.now() });
365
+ }
366
+ /** Reads the local file first on every tick, so one session's write ends every other session's poll with no network call. */
367
+ async pollRegistration(open) {
368
+ let waitMs = open.latest.pollMs;
369
+ for (;;) {
370
+ await this.sleep(waitMs);
371
+ waitMs = open.latest.pollMs;
372
+ try {
373
+ if (readMachineRegistration(this.deps.dashboardUrl, this.deps.home) !== null)
374
+ return { kind: "registered" };
375
+ }
376
+ catch (err) {
377
+ return { kind: "failed", error: err.message };
378
+ }
379
+ let call;
380
+ try {
381
+ call = await this.callRegistration();
382
+ }
383
+ catch (err) {
384
+ if (err instanceof McpOutdatedError)
385
+ return { kind: "failed", error: err.message };
386
+ this.deps.log?.(`[platform-mcp] machine registration poll failed, retrying: ${err.message}`);
387
+ continue;
388
+ }
389
+ switch (call.kind) {
390
+ case "pending":
391
+ open.latest = call;
392
+ continue;
393
+ case "rate_limited":
394
+ waitMs = Math.max(open.latest.pollMs, call.retryAfterSeconds * 1000);
395
+ continue;
396
+ case "accepted":
397
+ try {
398
+ this.storeRegistration(call);
399
+ return { kind: "registered" };
400
+ }
401
+ catch (err) {
402
+ // A failed write is a retry: the next tick finds another session's file, or writes again.
403
+ this.deps.log?.(`[platform-mcp] could not store the machine registration, retrying: ${err.message}`);
404
+ continue;
405
+ }
406
+ case "dashboard_outdated":
407
+ return { kind: "failed", error: REGISTRATION_OUTDATED_ERROR };
408
+ case "refused":
409
+ return { kind: "failed", error: `the dashboard refused the machine registration (${call.status}): ${JSON.stringify(call.body)}` };
410
+ }
411
+ }
412
+ }
290
413
  /**
291
414
  * 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
415
  * auto-approved request the plain "signing in" state, which has no link), denied or failed. `expired` is for the caller: a person's
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.449",
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",