@50arms/platform-mcp 0.1.465 → 0.1.467

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/dist/index.js CHANGED
@@ -81,6 +81,7 @@ import { READ_IDLE_TIMEOUT_MS } from "./listen.js";
81
81
  import { REQUEST_TIMEOUT_MS, realScheduleInterval, realSleep, } from "./session-stream.js";
82
82
  import { servePlanEventsWait } from "./plan-events-tool.js";
83
83
  import { lookupRestartNotice, RESTART_NOTICE_ARGS } from "./restart-notice.js";
84
+ import { HOST_SESSION_ID_ENV, startSessionHostClaim, } from "./session-host.js";
84
85
  import { makeSessionStop, stopWhenSessionEnds } from "./shutdown.js";
85
86
  import { SUBAGENTS_LIVE_SUBCOMMAND, runSubagentsLiveCommand, } from "./subagents-live.js";
86
87
  import { resolveBootCredential, } from "./credential.js";
@@ -173,6 +174,8 @@ let toolAccessSync;
173
174
  let permissionWatch;
174
175
  // DX-4233 - late-bound with `access`; see `plan-events-relay.ts`. The plugin's relay loop (a person's session) and an orchestrator's waiter sub-agent (DX-4667) call `plan_events_wait` on it.
175
176
  let planEventRelay;
177
+ // DX-7236 - the pointer file a command-line tool of this desktop session reads to learn which session id this server is; `null` for a server with no host id (a dispatch).
178
+ let sessionHostClaim;
176
179
  /**
177
180
  * Read the dispatch's default board from DANXBOT_BOARD_ID (the board's ref number the worker injects at the spawn site) and build the HTTP client.
178
181
  * Unset (DX-4555) leaves the server board-less: a call that needs a board must then carry its own `board`
@@ -265,6 +268,13 @@ function boot() {
265
268
  sync: () => toolAccessSync.sync(),
266
269
  log: (line) => console.error(line),
267
270
  });
271
+ sessionHostClaim = startSessionHostClaim({
272
+ hostSessionId: readEnvOptional(HOST_SESSION_ID_ENV),
273
+ sessionId: session?.id,
274
+ pid: process.pid,
275
+ scheduleInterval: realScheduleInterval,
276
+ log: (line) => console.error(line),
277
+ });
268
278
  }
269
279
  /**
270
280
  * DX-4523 - this key's current permissions (`GET /api/auth/permissions`, DX-6369: the key list alone, where `/api/auth/me` composed a 27.6 KB payload that took seconds under load). A dashboard failure throws, a 401 or 403 included: a key the
@@ -1226,7 +1236,7 @@ async function main() {
1226
1236
  stdin: process.stdin,
1227
1237
  signals: process,
1228
1238
  exit: (code) => process.exit(code),
1229
- stop: makeSessionStop(permissionWatch, planEventRelay),
1239
+ stop: makeSessionStop(permissionWatch, planEventRelay, sessionHostClaim),
1230
1240
  });
1231
1241
  const transport = new StdioServerTransport();
1232
1242
  await server.connect(transport);
@@ -678,7 +678,7 @@ var readOwnManifest = () => JSON.parse(
678
678
  readFileSync2(new URL("../../package.json", import.meta.url), "utf8")
679
679
  ).version;
680
680
  var TOOLKIT_VERSION = resolveToolkitVersion(
681
- false ? void 0 : "0.1.465",
681
+ false ? void 0 : "0.1.467",
682
682
  readOwnManifest
683
683
  );
684
684
  function envelope(now) {
@@ -1,6 +1,7 @@
1
1
  export const GET_ROUTE_BOARD_SCOPE = [
2
2
  ["/api/access-requests", "refuse"],
3
3
  ["/api/account/sessions", "refuse"],
4
+ ["/api/agent-session-analytics", "refuse"],
4
5
  ["/api/agents/:agentId/halt-history", "refuse"],
5
6
  ["/api/audit-events", "refuse"],
6
7
  ["/api/boards", "refuse"],
@@ -0,0 +1,178 @@
1
+ /**
2
+ * DX-7236 (DEC-846) - which session id a desktop session's command-line tools act as, after a clear.
3
+ *
4
+ * A clear gives every process the session starts afterwards a new `CLAUDE_CODE_SESSION_ID`, but a clear that keeps the Claude process keeps its MCP server running, still
5
+ * holding the old id, the key the person approved for it and the `assigned_agent` the cards carry. The server therefore stays the session's identity, and the CLI (`make land`
6
+ * among them) only has to learn which id that is. `CLAUDE_CODE_HOST_SESSION_ID` is the desktop app's own id for the session row: every process of one desktop session inherits it
7
+ * and it survives a clear, so the server writes a pointer file keyed by it and the CLI reads it.
8
+ *
9
+ * `~/.config/danxbot/session-hosts/<host session id>.json` holds `{schema_version, sessionId, pid}`: the session id of the MCP server serving that desktop session, and that server's pid.
10
+ * No key moves between session ids (PBLM-3624): the key stays bound to the id it was approved for.
11
+ *
12
+ * Owner rule: a LIVE owner wins. A `claude` started inside a session (a `claude -p` from a Bash call) inherits the parent's host id while the parent is alive, and its server must never take the
13
+ * parent's pointer. A server re-claims on its own interval, because in a clear that replaces the Claude process the new server can boot while the old one is still in its shutdown settle: its boot
14
+ * claim stands aside, and only a later claim, once the old one has exited, takes the pointer over.
15
+ *
16
+ * Known limit: a pointer whose owner died without cleaning up, and whose pid the OS reuses before the next server's claim, reads as live. The window is the seconds between the old server's death and
17
+ * the new one's re-claim; accepted, not designed out.
18
+ *
19
+ * This module imports nothing but `node:` and the session-id segment check, so a CLI that loads it runs in a plain shell.
20
+ */
21
+ import { readFileSync, rmSync } from "node:fs";
22
+ import { homedir } from "node:os";
23
+ import { join } from "node:path";
24
+ import { writeFileDurable } from "./durable-write.js";
25
+ import { assertSessionIdSegment } from "./session-connection.js";
26
+ /** One canonical shape (CLAUDE.md Core Principle 1): a file of any other version is refused. */
27
+ export const SESSION_HOST_SCHEMA_VERSION = 1;
28
+ /** The desktop app's own id for the session row; survives a clear and is inherited by every process of the session. A terminal host does not set it. */
29
+ export const HOST_SESSION_ID_ENV = "CLAUDE_CODE_HOST_SESSION_ID";
30
+ /** How often a server repeats its claim. */
31
+ export const SESSION_HOST_CLAIM_INTERVAL_MS = 15_000;
32
+ export function sessionHostDir(home = homedir()) {
33
+ return join(home, ".config", "danxbot", "session-hosts");
34
+ }
35
+ export function sessionHostPath(hostSessionId, home = homedir()) {
36
+ assertSessionIdSegment(hostSessionId);
37
+ return join(sessionHostDir(home), `${hostSessionId}.json`);
38
+ }
39
+ /** A pointer file that is there but unreadable or of another shape: named by path, never skipped. */
40
+ export class SessionHostUnusableError extends Error {
41
+ path;
42
+ constructor(path, why) {
43
+ super(`the session host pointer ${path} is unusable: ${why}`);
44
+ this.path = path;
45
+ this.name = "SessionHostUnusableError";
46
+ }
47
+ }
48
+ /** Whether `pid` names a running process. `EPERM` means it exists and belongs to someone else, so it is alive. */
49
+ export function isPidAlive(pid) {
50
+ try {
51
+ process.kill(pid, 0);
52
+ return true;
53
+ }
54
+ catch (err) {
55
+ return err.code === "EPERM";
56
+ }
57
+ }
58
+ function invalidReason(value) {
59
+ if (typeof value !== "object" || value === null)
60
+ return "it is not an object";
61
+ const r = value;
62
+ if (r.schema_version !== SESSION_HOST_SCHEMA_VERSION) {
63
+ return `schema_version is ${JSON.stringify(r.schema_version)}, not ${SESSION_HOST_SCHEMA_VERSION}`;
64
+ }
65
+ if (typeof r.sessionId !== "string" || r.sessionId === "")
66
+ return "sessionId is not a non-empty string";
67
+ if (!Number.isInteger(r.pid) || r.pid <= 0)
68
+ return "pid is not a positive integer";
69
+ return null;
70
+ }
71
+ /** The pointer in `path`, or `null` when there is none. Any other trouble throws `SessionHostUnusableError`. */
72
+ export function readSessionHost(path) {
73
+ let raw;
74
+ try {
75
+ raw = readFileSync(path, "utf-8");
76
+ }
77
+ catch (err) {
78
+ if (err.code === "ENOENT")
79
+ return null;
80
+ throw new SessionHostUnusableError(path, err.message);
81
+ }
82
+ let parsed;
83
+ try {
84
+ parsed = JSON.parse(raw);
85
+ }
86
+ catch (err) {
87
+ throw new SessionHostUnusableError(path, `not JSON (${err.message})`);
88
+ }
89
+ const invalid = invalidReason(parsed);
90
+ if (invalid !== null)
91
+ throw new SessionHostUnusableError(path, invalid);
92
+ return parsed;
93
+ }
94
+ /**
95
+ * Take the pointer for this server's desktop session: write it unless the file already names a different pid that is still alive. An absent file and a dead owner are taken over. A file that is there but
96
+ * unusable throws (`SessionHostUnusableError`).
97
+ */
98
+ export function claimSessionHost(identity) {
99
+ const { hostSessionId, sessionId, pid, home } = identity;
100
+ const isAlive = identity.isAlive ?? isPidAlive;
101
+ const path = sessionHostPath(hostSessionId, home);
102
+ const current = readSessionHost(path);
103
+ if (current !== null) {
104
+ if (current.pid === pid && current.sessionId === sessionId)
105
+ return "held";
106
+ if (current.pid !== pid && isAlive(current.pid))
107
+ return "owned-by-other";
108
+ }
109
+ const record = {
110
+ schema_version: SESSION_HOST_SCHEMA_VERSION,
111
+ sessionId,
112
+ pid,
113
+ };
114
+ writeFileDurable(path, JSON.stringify(record));
115
+ return "claimed";
116
+ }
117
+ /** Delete the pointer, only when it still names this server's pid: another server may have taken it over. An absent file is nothing to do. */
118
+ export function releaseSessionHost(identity) {
119
+ const path = sessionHostPath(identity.hostSessionId, identity.home);
120
+ const current = readSessionHost(path);
121
+ if (current !== null && current.pid === identity.pid)
122
+ rmSync(path, { force: true });
123
+ }
124
+ /**
125
+ * The server's claim: take the pointer now (a failure throws, so a pointer this code cannot read stops the boot), then repeat on `scheduleInterval` every `SESSION_HOST_CLAIM_INTERVAL_MS`. `null` for a
126
+ * server with no host id or no session id (a dispatch server): it writes nothing. A failing re-claim is logged and tried again on the next tick, since a throw from a timer would end the server.
127
+ */
128
+ export function startSessionHostClaim(input) {
129
+ const { hostSessionId, sessionId, pid, home, isAlive, log } = input;
130
+ if (hostSessionId === undefined || sessionId === undefined)
131
+ return null;
132
+ const identity = {
133
+ hostSessionId,
134
+ sessionId,
135
+ pid,
136
+ home,
137
+ isAlive,
138
+ };
139
+ claimSessionHost(identity);
140
+ const timer = input.scheduleInterval(() => {
141
+ try {
142
+ claimSessionHost(identity);
143
+ }
144
+ catch (err) {
145
+ log(`[platform-mcp] could not re-claim the session host pointer: ${err.message}`);
146
+ }
147
+ }, SESSION_HOST_CLAIM_INTERVAL_MS);
148
+ let stopped = false;
149
+ return {
150
+ stop: () => {
151
+ if (stopped)
152
+ return;
153
+ stopped = true;
154
+ timer.stop();
155
+ releaseSessionHost(identity);
156
+ },
157
+ };
158
+ }
159
+ /**
160
+ * The session id a command-line tool acts as, or `null` for none. In order:
161
+ * 1. `CLAUDE_CODE_SESSION_ID` unset or empty: none, whatever the host id says. Dropping the session id is how a detached run that outlives its session (`start-pass`, `finish-card-now`, DX-5809) is told to use the machine
162
+ * credential instead of the session's key, which can be revoked once the session ends. Those runs still inherit the host id, so reading the pointer first would hand them that key.
163
+ * 2. the pointer's `sessionId`, when `CLAUDE_CODE_HOST_SESSION_ID` is set and its pointer names a live pid: the live MCP server's id, the one the key and the cards' `assigned_agent` are bound to.
164
+ * 3. the process's own `CLAUDE_CODE_SESSION_ID`: with no live server for this host id, the process's own id is the live session's id (a clear that replaces the process gives the new server and the new shells the same new id).
165
+ * A pointer that is there but unusable throws, naming its path.
166
+ */
167
+ export function resolveSessionId(env, home, isAlive = isPidAlive) {
168
+ const own = env.CLAUDE_CODE_SESSION_ID;
169
+ if (own === undefined || own === "")
170
+ return null;
171
+ const hostSessionId = env[HOST_SESSION_ID_ENV];
172
+ if (hostSessionId !== undefined && hostSessionId !== "") {
173
+ const pointer = readSessionHost(sessionHostPath(hostSessionId, home));
174
+ if (pointer !== null && isAlive(pointer.pid))
175
+ return pointer.sessionId;
176
+ }
177
+ return own;
178
+ }
package/dist/shutdown.js CHANGED
@@ -31,10 +31,14 @@ export function stopWhenSessionEnds(wiring) {
31
31
  /**
32
32
  * DX-5415: the server's stop callback, the one link from every shutdown trigger to the relay's settle: it returns the relay's
33
33
  * pending `close()` so a signal handler can wait for it before exiting.
34
+ * DX-7236: it also stops the server's session host claim (`session-host.ts`): the re-claim interval ends and the pointer file is deleted when it still names this server.
34
35
  */
35
- export function makeSessionStop(permissionWatch, planEventRelay) {
36
+ export function makeSessionStop(permissionWatch, planEventRelay, sessionHostClaim) {
36
37
  return () => {
37
38
  permissionWatch.stop();
38
- return planEventRelay.close();
39
+ // DX-7236: starts the relay's settle first, so a pointer file this server cannot read (its release throws) never costs the held finals.
40
+ const closing = planEventRelay.close();
41
+ sessionHostClaim?.stop();
42
+ return closing;
39
43
  };
40
44
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@50arms/platform-mcp",
3
- "version": "0.1.465",
3
+ "version": "0.1.467",
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",