@50arms/platform-mcp 0.1.464 → 0.1.466

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.
Files changed (67) hide show
  1. package/dist/access-request.js +19 -6
  2. package/dist/agent-gate.js +19 -5
  3. package/dist/board-id.js +8 -2
  4. package/dist/checkout-docs-root.js +10 -2
  5. package/dist/clear-control.js +18 -4
  6. package/dist/compaction-control.js +30 -7
  7. package/dist/credential.js +10 -2
  8. package/dist/danxbot-api-examples.js +20 -3
  9. package/dist/design-screenshot.js +22 -5
  10. package/dist/digest-hold.js +14 -3
  11. package/dist/docs-tools.js +46 -12
  12. package/dist/durable-write.js +10 -2
  13. package/dist/forbidden-hint.js +13 -2
  14. package/dist/guarded-calls.js +6 -2
  15. package/dist/handlers.js +66 -14
  16. package/dist/heartbeat-reporter.js +8 -3
  17. package/dist/http-client.js +4 -2
  18. package/dist/index.js +242 -80
  19. package/dist/job-key.js +3 -1
  20. package/dist/json-body.js +3 -1
  21. package/dist/key-revoked-halt.js +2 -1
  22. package/dist/leftover-wire.js +17 -4
  23. package/dist/lifecycle.js +11 -3
  24. package/dist/listen.js +242 -64
  25. package/dist/listener-reminder.js +8 -2
  26. package/dist/machine-daemon/autostart.js +16 -4
  27. package/dist/machine-daemon/beat.js +18 -4
  28. package/dist/machine-daemon/cli.js +15 -4
  29. package/dist/machine-daemon/install.js +33 -9
  30. package/dist/machine-daemon/leftovers.js +134 -30
  31. package/dist/machine-daemon/state.js +9 -3
  32. package/dist/machine-daemon.js +531 -128
  33. package/dist/machine-registration.js +27 -6
  34. package/dist/machine-secret.js +8 -3
  35. package/dist/machine-toolkit.js +377 -81
  36. package/dist/mini-app-build.js +19 -5
  37. package/dist/mini-app-checkout.js +38 -10
  38. package/dist/mini-app-output.js +22 -5
  39. package/dist/mini-app-publish.js +34 -11
  40. package/dist/mini-app-restore.js +30 -9
  41. package/dist/one-line.js +3 -1
  42. package/dist/permission-request.js +14 -3
  43. package/dist/permission-watch.js +10 -3
  44. package/dist/plan-events-relay.js +96 -19
  45. package/dist/plan-events-tool.js +9 -2
  46. package/dist/plugin-publish.js +23 -6
  47. package/dist/plugin-screenshot.js +18 -6
  48. package/dist/restart-notice.js +47 -15
  49. package/dist/result-limit.js +6 -1
  50. package/dist/role-instruction-file.js +16 -4
  51. package/dist/route-board-scope.generated.js +1 -0
  52. package/dist/route-board-scope.js +6 -2
  53. package/dist/session-access.js +110 -32
  54. package/dist/session-connection.js +23 -7
  55. package/dist/session-control-file.js +1 -1
  56. package/dist/session-key.js +12 -4
  57. package/dist/session-options.js +6 -2
  58. package/dist/session-stats.js +2 -1
  59. package/dist/session-stream.js +81 -20
  60. package/dist/shutdown.js +3 -1
  61. package/dist/subagents-live.js +8 -2
  62. package/dist/terms-halt.js +4 -2
  63. package/dist/tool-access.js +17 -4
  64. package/dist/tool-surface.js +9 -2
  65. package/dist/transcript-lineage.js +5 -2
  66. package/dist/urgent-records.js +1 -0
  67. package/package.json +1 -1
@@ -26,9 +26,9 @@
26
26
  */
27
27
  import { existsSync } from "node:fs";
28
28
  import { hostname } from "node:os";
29
- import { claimAccessRequest, createAccessRequest } from "./access-request.js";
30
- import { credentialFingerprint } from "./credential.js";
31
- import { keyRevocationOf, keyRevokedHalt } from "./key-revoked-halt.js";
29
+ import { claimAccessRequest, createAccessRequest, } from "./access-request.js";
30
+ import { credentialFingerprint, } from "./credential.js";
31
+ import { keyRevocationOf, keyRevokedHalt, } from "./key-revoked-halt.js";
32
32
  import { callMachineRegistration, deleteMachineRegistration, readMachineRegistration, writeMachineRegistration, } from "./machine-registration.js";
33
33
  import { machineSecretFor } from "./machine-secret.js";
34
34
  import { deleteSessionKey, writeSessionKey } from "./session-key.js";
@@ -78,7 +78,9 @@ function claimRefusalError(body, role) {
78
78
  case "unknown_role":
79
79
  return `the team has no role "${role}"; call session_connect again without \`role\` (the default "${DEFAULT_SESSION_ROLE}" role) or with a role key the team has`;
80
80
  case "role_exceeds_owner": {
81
- const missing = Array.isArray(refusal?.missingPermissions) ? refusal.missingPermissions.filter((k) => typeof k === "string") : [];
81
+ const missing = Array.isArray(refusal?.missingPermissions)
82
+ ? refusal.missingPermissions.filter((k) => typeof k === "string")
83
+ : [];
82
84
  const lacks = missing.length === 0 ? "" : ` (their role lacks ${missing.join(", ")})`;
83
85
  if (role === DEFAULT_SESSION_ROLE) {
84
86
  return (`the person this machine is registered to cannot sign in an agent session on this team: their role is smaller than the "${DEFAULT_SESSION_ROLE}" role a session signs in on${lacks}. ` +
@@ -118,7 +120,8 @@ function launchRefusalWhy(claim) {
118
120
  case "refused": {
119
121
  const body = claim.body;
120
122
  if (claim.status === 409 && body?.error === "launch_grant_refused") {
121
- const missing = Array.isArray(body.missingPermissions) && body.missingPermissions.length > 0
123
+ const missing = Array.isArray(body.missingPermissions) &&
124
+ body.missingPermissions.length > 0
122
125
  ? ` (missing permissions: ${body.missingPermissions.join(", ")})`
123
126
  : "";
124
127
  return `the dashboard refused the launch grant: ${String(body.reason)}${missing}`;
@@ -175,11 +178,15 @@ export class SessionAccess {
175
178
  }
176
179
  /** DX-4523: the key this session holds now, or "" when it holds none (the permission stream opens with it). */
177
180
  currentToken() {
178
- return this.credential === null || this.revoked !== null ? "" : this.credential.token;
181
+ return this.credential === null || this.revoked !== null
182
+ ? ""
183
+ : this.credential.token;
179
184
  }
180
185
  /** DX-4418: the stop halt once a person revoked the key, else null. */
181
186
  revokedHalt() {
182
- return this.revoked === null ? null : keyRevokedHalt(this.revoked.revocation, this.revoked.dispatched);
187
+ return this.revoked === null
188
+ ? null
189
+ : keyRevokedHalt(this.revoked.revocation, this.revoked.dispatched);
183
190
  }
184
191
  /**
185
192
  * DX-6894 (DEC-589): a person pressed Sign in on a session whose key a person revoked: leave the revoked state so the next ask starts a
@@ -202,7 +209,10 @@ export class SessionAccess {
202
209
  const revocation = keyRevocationOf(result);
203
210
  if (revocation === null)
204
211
  return null;
205
- this.revoked ??= { revocation, dispatched: this.credential?.source.kind === "env" };
212
+ this.revoked ??= {
213
+ revocation,
214
+ dispatched: this.credential?.source.kind === "env",
215
+ };
206
216
  this.dropKey(result);
207
217
  return this.revokedHalt();
208
218
  }
@@ -222,7 +232,8 @@ export class SessionAccess {
222
232
  * caused it; one stderr line names the key's fingerprint, its file and that answer, and later halts repeat it.
223
233
  */
224
234
  dropKey(refusal) {
225
- if (this.credential === null || this.credential.source.kind !== "session-key")
235
+ if (this.credential === null ||
236
+ this.credential.source.kind !== "session-key")
226
237
  return false;
227
238
  const { fingerprint, source } = this.credential;
228
239
  this.signedOutCause = `dropped the session key ${fingerprint} (${source.path}): the dashboard answered ${refusal.status} ${JSON.stringify(refusal.body).slice(0, REFUSAL_LOG_LIMIT)}`;
@@ -267,10 +278,15 @@ export class SessionAccess {
267
278
  if (credential === null || credential.source.kind !== "session-key")
268
279
  return;
269
280
  const now = this.now();
270
- if (now - this.lastKeyFileWrite < KEEP_KEY_FILE_EVERY_MS && existsSync(credential.source.path))
281
+ if (now - this.lastKeyFileWrite < KEEP_KEY_FILE_EVERY_MS &&
282
+ existsSync(credential.source.path))
271
283
  return;
272
284
  try {
273
- writeSessionKey({ dashboardUrl: this.deps.dashboardUrl, sessionId: this.deps.sessionId, apiKey: credential.token }, { home: this.deps.home, now });
285
+ writeSessionKey({
286
+ dashboardUrl: this.deps.dashboardUrl,
287
+ sessionId: this.deps.sessionId,
288
+ apiKey: credential.token,
289
+ }, { home: this.deps.home, now });
274
290
  this.lastKeyFileWrite = now;
275
291
  }
276
292
  catch (err) {
@@ -304,7 +320,9 @@ export class SessionAccess {
304
320
  }
305
321
  let note;
306
322
  // DX-6801: only while no request of this process is open (a person's approval already in flight stays the way in).
307
- if (launchToken !== undefined && !this.launchTokenTried && this.pending === null) {
323
+ if (launchToken !== undefined &&
324
+ !this.launchTokenTried &&
325
+ this.pending === null) {
308
326
  this.launchTokenTried = true;
309
327
  const claim = await claimAccessRequest(this.fetchImpl, this.deps.dashboardUrl, launchToken, sessionId);
310
328
  if (claim.kind === "approved") {
@@ -330,7 +348,9 @@ export class SessionAccess {
330
348
  }
331
349
  const created = await this.createRequest(sessionId, title, note, role ?? DEFAULT_SESSION_ROLE);
332
350
  // DX-6801: a refused or failed request carries the launch note too, so the reason is never lost.
333
- if (note !== undefined && !created.signedIn && !("note" in created.answer)) {
351
+ if (note !== undefined &&
352
+ !created.signedIn &&
353
+ !("note" in created.answer)) {
334
354
  return { ...created, answer: { ...created.answer, note } };
335
355
  }
336
356
  return created;
@@ -361,19 +381,33 @@ export class SessionAccess {
361
381
  this.storeRegistration(first);
362
382
  return null;
363
383
  case "pending":
364
- this.registration = { latest: first, settled: Promise.resolve({ kind: "registered" }) };
384
+ this.registration = {
385
+ latest: first,
386
+ settled: Promise.resolve({ kind: "registered" }),
387
+ };
365
388
  this.registration.settled = this.pollRegistration(this.registration);
366
389
  return notReady(this.registrationAnswer("machine_registration_required", first, note), false);
367
390
  case "dashboard_outdated":
368
391
  return notReady({ state: "dashboard_outdated", error: REGISTRATION_OUTDATED_ERROR }, true);
369
392
  case "rate_limited":
370
- return notReady({ state: "rate_limited", retryAfterSeconds: first.retryAfterSeconds, error: RATE_LIMITED_ERROR }, true);
393
+ return notReady({
394
+ state: "rate_limited",
395
+ retryAfterSeconds: first.retryAfterSeconds,
396
+ error: RATE_LIMITED_ERROR,
397
+ }, true);
371
398
  case "refused":
372
- return notReady({ state: "request_refused", status: first.status, body: first.body }, true);
399
+ return notReady({
400
+ state: "request_refused",
401
+ status: first.status,
402
+ body: first.body,
403
+ }, true);
373
404
  }
374
405
  }
375
406
  const open = this.registration;
376
- const outcome = await Promise.race([open.settled, this.sleep(this.awaitMs).then(() => null)]);
407
+ const outcome = await Promise.race([
408
+ open.settled,
409
+ this.sleep(this.awaitMs).then(() => null),
410
+ ]);
377
411
  if (outcome === null)
378
412
  return notReady(this.registrationAnswer("machine_registration_pending", open.latest, note), false);
379
413
  this.registration = null;
@@ -386,18 +420,26 @@ export class SessionAccess {
386
420
  state,
387
421
  registrationUrl: pending.registrationUrl,
388
422
  claimCode: pending.claimCode,
389
- instruction: state === "machine_registration_required" ? MACHINE_REGISTRATION_REQUIRED_INSTRUCTION : MACHINE_REGISTRATION_PENDING_INSTRUCTION,
423
+ instruction: state === "machine_registration_required"
424
+ ? MACHINE_REGISTRATION_REQUIRED_INSTRUCTION
425
+ : MACHINE_REGISTRATION_PENDING_INSTRUCTION,
390
426
  ...(note === undefined ? {} : { note }),
391
427
  };
392
428
  }
393
429
  callRegistration() {
394
430
  return callMachineRegistration(this.fetchImpl, this.deps.dashboardUrl, {
395
- machineSecret: machineSecretFor(this.deps.dashboardUrl, { home: this.deps.home, now: this.now() }),
431
+ machineSecret: machineSecretFor(this.deps.dashboardUrl, {
432
+ home: this.deps.home,
433
+ now: this.now(),
434
+ }),
396
435
  machine: this.deps.machine ?? hostname(),
397
436
  });
398
437
  }
399
438
  storeRegistration(accepted) {
400
- writeMachineRegistration(this.deps.dashboardUrl, accepted, { home: this.deps.home, now: this.now() });
439
+ writeMachineRegistration(this.deps.dashboardUrl, accepted, {
440
+ home: this.deps.home,
441
+ now: this.now(),
442
+ });
401
443
  }
402
444
  /** Reads the local file first on every tick, so one session's write ends every other session's poll with no network call. */
403
445
  async pollRegistration(open) {
@@ -406,7 +448,8 @@ export class SessionAccess {
406
448
  await this.sleep(waitMs);
407
449
  waitMs = open.latest.pollMs;
408
450
  try {
409
- if (readMachineRegistration(this.deps.dashboardUrl, this.deps.home) !== null)
451
+ if (readMachineRegistration(this.deps.dashboardUrl, this.deps.home) !==
452
+ null)
410
453
  return { kind: "registered" };
411
454
  }
412
455
  catch (err) {
@@ -442,7 +485,10 @@ export class SessionAccess {
442
485
  case "dashboard_outdated":
443
486
  return { kind: "failed", error: REGISTRATION_OUTDATED_ERROR };
444
487
  case "refused":
445
- return { kind: "failed", error: `the dashboard refused the machine registration (${call.status}): ${JSON.stringify(call.body)}` };
488
+ return {
489
+ kind: "failed",
490
+ error: `the dashboard refused the machine registration (${call.status}): ${JSON.stringify(call.body)}`,
491
+ };
446
492
  }
447
493
  }
448
494
  }
@@ -452,7 +498,10 @@ export class SessionAccess {
452
498
  * request that lapsed is asked again, an auto-approved one is an error.
453
499
  */
454
500
  async awaitPending(pending) {
455
- const outcome = await Promise.race([pending.settled, this.sleep(this.awaitMs).then(() => null)]);
501
+ const outcome = await Promise.race([
502
+ pending.settled,
503
+ this.sleep(this.awaitMs).then(() => null),
504
+ ]);
456
505
  if (outcome === null)
457
506
  return notReady(this.requestAnswer("approval_pending", pending.request), false);
458
507
  this.pending = null;
@@ -487,14 +536,20 @@ export class SessionAccess {
487
536
  team: String(registration.teamId),
488
537
  person: registration.userId,
489
538
  role,
490
- machineSecret: machineSecretFor(this.deps.dashboardUrl, { home: this.deps.home, now: this.now() }),
539
+ machineSecret: machineSecretFor(this.deps.dashboardUrl, {
540
+ home: this.deps.home,
541
+ now: this.now(),
542
+ }),
491
543
  });
492
544
  switch (created.kind) {
493
545
  case "dashboard_outdated":
494
546
  return notReady({ state: "dashboard_outdated", error: DASHBOARD_OUTDATED_ERROR }, true);
495
547
  case "machine_registration_mismatch": {
496
548
  if (reRegistered)
497
- return notReady({ state: "request_failed", error: REGISTRATION_STILL_MISMATCHED_ERROR }, true);
549
+ return notReady({
550
+ state: "request_failed",
551
+ error: REGISTRATION_STILL_MISMATCHED_ERROR,
552
+ }, true);
498
553
  deleteMachineRegistration(this.deps.dashboardUrl, this.deps.home);
499
554
  this.registration = null;
500
555
  const unregistered = await this.machineRegistrationAnswer(note);
@@ -503,20 +558,37 @@ export class SessionAccess {
503
558
  return this.createRequest(sessionId, title, note, role, true);
504
559
  }
505
560
  case "rate_limited":
506
- return notReady({ state: "rate_limited", retryAfterSeconds: created.retryAfterSeconds, error: RATE_LIMITED_ERROR }, true);
561
+ return notReady({
562
+ state: "rate_limited",
563
+ retryAfterSeconds: created.retryAfterSeconds,
564
+ error: RATE_LIMITED_ERROR,
565
+ }, true);
507
566
  case "refused": {
508
567
  const error = claimRefusalError(created.body, role);
509
- return notReady({ state: "request_refused", status: created.status, body: created.body, ...(error === null ? {} : { error }) }, true);
568
+ return notReady({
569
+ state: "request_refused",
570
+ status: created.status,
571
+ body: created.body,
572
+ ...(error === null ? {} : { error }),
573
+ }, true);
510
574
  }
511
575
  case "created":
512
- this.pending = { request: created.request, settled: this.pollUntilSettled(created.request) };
576
+ this.pending = {
577
+ request: created.request,
578
+ settled: this.pollUntilSettled(created.request),
579
+ };
513
580
  // 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,
514
581
  // and never hand the agent a link.
515
582
  if (created.request.autoApproved) {
516
583
  const settled = await this.awaitPending(this.pending);
517
- return settled === "expired" ? notReady({ state: "request_failed", error: AUTO_APPROVED_EXPIRED_ERROR }, true) : settled;
584
+ return settled === "expired"
585
+ ? notReady({ state: "request_failed", error: AUTO_APPROVED_EXPIRED_ERROR }, true)
586
+ : settled;
518
587
  }
519
- return notReady({ ...this.requestAnswer("approval_required", created.request), ...(note ? { note } : {}) }, false);
588
+ return notReady({
589
+ ...this.requestAnswer("approval_required", created.request),
590
+ ...(note ? { note } : {}),
591
+ }, false);
520
592
  }
521
593
  }
522
594
  requestAnswer(state, request) {
@@ -526,7 +598,9 @@ export class SessionAccess {
526
598
  state,
527
599
  approvalUrl: request.approvalUrl,
528
600
  confirmCode: request.confirmCode,
529
- instruction: state === "approval_required" ? APPROVAL_REQUIRED_INSTRUCTION : APPROVAL_PENDING_INSTRUCTION,
601
+ instruction: state === "approval_required"
602
+ ? APPROVAL_REQUIRED_INSTRUCTION
603
+ : APPROVAL_PENDING_INSTRUCTION,
530
604
  };
531
605
  }
532
606
  // DX-4530: no give-up time - the polls are what keep the request open, until the dashboard answers how it ended.
@@ -574,7 +648,11 @@ export class SessionAccess {
574
648
  storeKey(apiKey) {
575
649
  const now = this.now();
576
650
  try {
577
- const path = writeSessionKey({ dashboardUrl: this.deps.dashboardUrl, sessionId: this.deps.sessionId, apiKey }, { home: this.deps.home, now });
651
+ const path = writeSessionKey({
652
+ dashboardUrl: this.deps.dashboardUrl,
653
+ sessionId: this.deps.sessionId,
654
+ apiKey,
655
+ }, { home: this.deps.home, now });
578
656
  this.credential = {
579
657
  source: { kind: "session-key", path },
580
658
  token: apiKey,
@@ -27,7 +27,7 @@
27
27
  * dashboard keeps only a week of events, so an older session cannot resume
28
28
  * anything anyway.
29
29
  */
30
- import { mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
30
+ import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, } from "node:fs";
31
31
  import { writeFileDurable } from "./durable-write.js";
32
32
  import { homedir } from "node:os";
33
33
  import { join, resolve, win32 } from "node:path";
@@ -183,7 +183,10 @@ export function recordSessionConnectionAfterConnect(result, inputs, write = writ
183
183
  * handled as a connect, so no record or tool sync is missed.
184
184
  */
185
185
  export function isPickupConnect(result) {
186
- return result.ok && typeof result.body === "object" && result.body !== null && result.body.connectedByPickup === true;
186
+ return (result.ok &&
187
+ typeof result.body === "object" &&
188
+ result.body !== null &&
189
+ result.body.connectedByPickup === true);
187
190
  }
188
191
  /**
189
192
  * DX-2985 — drop this session's local connection record after a successful leave (`session_connect {disconnect: true}`), so
@@ -204,7 +207,13 @@ export function invalidRecordReason(value) {
204
207
  return (`schemaVersion is ${JSON.stringify(r.schemaVersion)}, not ${SESSION_CONNECTION_SCHEMA_VERSION} — ` +
205
208
  "a session connected by an older MCP server wrote it; call session_connect again to rewrite it");
206
209
  }
207
- for (const field of ["sessionId", "projectKey", "dashboardUrl", "fingerprint", "connectedAt"]) {
210
+ for (const field of [
211
+ "sessionId",
212
+ "projectKey",
213
+ "dashboardUrl",
214
+ "fingerprint",
215
+ "connectedAt",
216
+ ]) {
208
217
  if (typeof r[field] !== "string" || r[field] === "")
209
218
  return `${field} is not a non-empty string`;
210
219
  }
@@ -212,9 +221,13 @@ export function invalidRecordReason(value) {
212
221
  if (typeof source !== "object" || source === null)
213
222
  return "source is not an object";
214
223
  if (source.kind === "session-key")
215
- return typeof source.path === "string" && source.path !== "" ? null : "source.path is not a path";
224
+ return typeof source.path === "string" && source.path !== ""
225
+ ? null
226
+ : "source.path is not a path";
216
227
  if (source.kind === "env")
217
- return typeof source.name === "string" && source.name !== "" ? null : "source.name is not a variable name";
228
+ return typeof source.name === "string" && source.name !== ""
229
+ ? null
230
+ : "source.name is not a variable name";
218
231
  return `source.kind is ${JSON.stringify(source.kind)}, which this version does not know`;
219
232
  }
220
233
  /**
@@ -253,12 +266,15 @@ export function findPredecessorCandidates(projectKey, currentSessionId, options
253
266
  if (invalidRecordReason(parsed) !== null)
254
267
  continue;
255
268
  const record = parsed;
256
- if (record.projectKey !== projectKey || record.sessionId === currentSessionId)
269
+ if (record.projectKey !== projectKey ||
270
+ record.sessionId === currentSessionId)
257
271
  continue;
258
272
  const connectedAt = Date.parse(record.connectedAt);
259
273
  if (!Number.isFinite(connectedAt) || now - connectedAt > STALE_RECORD_MS)
260
274
  continue;
261
275
  found.push({ record, connectedAt });
262
276
  }
263
- return found.sort((x, y) => y.connectedAt - x.connectedAt).map((f) => f.record);
277
+ return found
278
+ .sort((x, y) => y.connectedAt - x.connectedAt)
279
+ .map((f) => f.record);
264
280
  }
@@ -8,7 +8,7 @@ import { mkdirSync, readFileSync, utimesSync } from "node:fs";
8
8
  import { homedir } from "node:os";
9
9
  import { dirname, join } from "node:path";
10
10
  import { writeFileDurable } from "./durable-write.js";
11
- import { assertSessionIdSegment, pruneStaleSessionFiles } from "./session-connection.js";
11
+ import { assertSessionIdSegment, pruneStaleSessionFiles, } from "./session-connection.js";
12
12
  /** `~/.config/danxbot/<dirName>`, next to the plugin's other per-session records. */
13
13
  export function sessionControlDir(dirName, home = homedir()) {
14
14
  return join(home, ".config", "danxbot", dirName);
@@ -15,14 +15,17 @@
15
15
  * concurrently sees the old file or the new one, never a torn one.
16
16
  */
17
17
  import { createHash } from "node:crypto";
18
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
18
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, } from "node:fs";
19
19
  import { writeFileDurable } from "./durable-write.js";
20
20
  import { homedir } from "node:os";
21
21
  import { join } from "node:path";
22
- import { assertSessionIdSegment, pruneStaleSessionFiles } from "./session-connection.js";
22
+ import { assertSessionIdSegment, pruneStaleSessionFiles, } from "./session-connection.js";
23
23
  /** One canonical shape (CLAUDE.md Core Principle 1): a file of any other version is refused. */
24
24
  export const SESSION_KEY_SCHEMA_VERSION = 1;
25
- const dashboardHash = (dashboardUrl) => createHash("sha256").update(dashboardUrl.replace(/\/+$/, "")).digest("hex").slice(0, 12);
25
+ const dashboardHash = (dashboardUrl) => createHash("sha256")
26
+ .update(dashboardUrl.replace(/\/+$/, ""))
27
+ .digest("hex")
28
+ .slice(0, 12);
26
29
  export function sessionKeyRoot(home = homedir()) {
27
30
  return join(home, ".config", "danxbot", "session-keys");
28
31
  }
@@ -59,7 +62,12 @@ function invalidKeyReason(value) {
59
62
  if (r.schemaVersion !== SESSION_KEY_SCHEMA_VERSION) {
60
63
  return `schemaVersion is ${JSON.stringify(r.schemaVersion)}, not ${SESSION_KEY_SCHEMA_VERSION}`;
61
64
  }
62
- for (const field of ["dashboardUrl", "sessionId", "apiKey", "savedAt"]) {
65
+ for (const field of [
66
+ "dashboardUrl",
67
+ "sessionId",
68
+ "apiKey",
69
+ "savedAt",
70
+ ]) {
63
71
  if (typeof r[field] !== "string" || r[field] === "")
64
72
  return `${field} is not a non-empty string`;
65
73
  }
@@ -6,7 +6,7 @@
6
6
  * lives inside the server that holds the credential.
7
7
  */
8
8
  import { homedir } from "node:os";
9
- import { credentialFingerprint, describeCredentialSource, readCredential } from "./credential.js";
9
+ import { credentialFingerprint, describeCredentialSource, readCredential, } from "./credential.js";
10
10
  import { readSessionConnection } from "./session-connection.js";
11
11
  import { fixForStop } from "./stop-fixes.js";
12
12
  export const SESSION_ID_HEADER = "x-danx-session-id";
@@ -56,5 +56,9 @@ export function resolveDashboardAuth(sessionId, env, options = {}) {
56
56
  throw new SessionStartError("credential_mismatch", `${describeCredentialSource(record.source)} now yields credential ${fingerprint}, but this session's ` +
57
57
  `platform MCP server is using ${record.fingerprint} — a lookup would authenticate as somebody else`, fixForStop("credential_mismatch"));
58
58
  }
59
- return { dashboardUrl: record.dashboardUrl.replace(/\/+$/, ""), token, sessionId };
59
+ return {
60
+ dashboardUrl: record.dashboardUrl.replace(/\/+$/, ""),
61
+ token,
62
+ sessionId,
63
+ };
60
64
  }
@@ -163,7 +163,8 @@ export class OperatorSessionStats {
163
163
  // DX-5415: a failed or refused flush re-queues nothing for a collector that is stopping, so it says what it costs.
164
164
  const flushed = (await this.flushVia(send)).outcome;
165
165
  if (flushed !== "ok")
166
- process.stderr.write(`operator session stats: the final flush was ${flushed}; held sub-agent finals may be lost
166
+ process.stderr
167
+ .write(`operator session stats: the final flush was ${flushed}; held sub-agent finals may be lost
167
168
  `);
168
169
  return "settled";
169
170
  })();
@@ -8,10 +8,10 @@
8
8
  */
9
9
  import { errorCodeOf } from "./json-body.js";
10
10
  import { boundRequest } from "./request-bound.js";
11
- import { keyRevocationOf, keyRevokedHalt } from "./key-revoked-halt.js";
11
+ import { keyRevocationOf, keyRevokedHalt, } from "./key-revoked-halt.js";
12
12
  import { oneLine } from "./one-line.js";
13
- import { PLUGIN_BACKGROUND_HEADER, SESSION_ID_HEADER } from "./session-options.js";
14
- import { isClaimState } from "@50arms/session-telemetry";
13
+ import { PLUGIN_BACKGROUND_HEADER, SESSION_ID_HEADER, } from "./session-options.js";
14
+ import { isClaimState, } from "@50arms/session-telemetry";
15
15
  /**
16
16
  * DX-3912 — the longest heartbeat `reason` the relay sends: one under the dashboard's own
17
17
  * limit (`HEARTBEAT_REASON_MAX_CHARS` = 200, `src/issues/db/plan-session-heartbeat.ts`),
@@ -129,7 +129,9 @@ function badTicketReason(body) {
129
129
  return "ticket is not a non-empty string";
130
130
  if (typeof b.streamPath !== "string" || !b.streamPath.startsWith("/"))
131
131
  return "streamPath is not a path";
132
- if (typeof b.leaseMs !== "number" || !Number.isSafeInteger(b.leaseMs) || b.leaseMs <= 0) {
132
+ if (typeof b.leaseMs !== "number" ||
133
+ !Number.isSafeInteger(b.leaseMs) ||
134
+ b.leaseMs <= 0) {
133
135
  return "leaseMs is not a positive integer";
134
136
  }
135
137
  return null;
@@ -150,23 +152,43 @@ export async function mintTicket(options, deps) {
150
152
  // dispatch (`SessionIsWorkerError`, the same shape the heartbeat route
151
153
  // already gives it, DX-2952).
152
154
  if (status === 409 && errorCodeOf(body) === "session_is_worker") {
153
- return { kind: "terminal", reason: "session_is_worker", detail: "this session id belongs to a worker dispatch, not an operator plan session" };
155
+ return {
156
+ kind: "terminal",
157
+ reason: "session_is_worker",
158
+ detail: "this session id belongs to a worker dispatch, not an operator plan session",
159
+ };
154
160
  }
155
161
  // DX-4418 - a key a person revoked is not a lapsed one: the detail IS the stop halt (who revoked it, what to do), so the record
156
162
  // the plugin relays to the session says it in full.
157
163
  const revocation = keyRevocationOf({ ok: false, status, body });
158
164
  if (revocation !== null) {
159
- return { kind: "terminal", reason: "key_revoked", detail: keyRevokedHalt(revocation, false) };
165
+ return {
166
+ kind: "terminal",
167
+ reason: "key_revoked",
168
+ detail: keyRevokedHalt(revocation, false),
169
+ };
160
170
  }
161
171
  if (status === 401 || status === 403) {
162
- return { kind: "terminal", reason: "unauthorized", detail: `ticket mint HTTP ${status} ${oneLine(text, 300)}` };
172
+ return {
173
+ kind: "terminal",
174
+ reason: "unauthorized",
175
+ detail: `ticket mint HTTP ${status} ${oneLine(text, 300)}`,
176
+ };
163
177
  }
164
178
  if (status < 200 || status >= 300) {
165
- return { kind: "terminal", reason: "mint_refused", detail: `ticket mint HTTP ${status} ${oneLine(text, 300)}` };
179
+ return {
180
+ kind: "terminal",
181
+ reason: "mint_refused",
182
+ detail: `ticket mint HTTP ${status} ${oneLine(text, 300)}`,
183
+ };
166
184
  }
167
185
  const bad = badTicketReason(body);
168
186
  if (bad !== null) {
169
- return { kind: "terminal", reason: "mint_bad_response", detail: `ticket mint HTTP ${status}: ${bad}` };
187
+ return {
188
+ kind: "terminal",
189
+ reason: "mint_bad_response",
190
+ detail: `ticket mint HTTP ${status}: ${bad}`,
191
+ };
170
192
  }
171
193
  const ticket = body;
172
194
  return {
@@ -191,7 +213,8 @@ function badInventoryReason(body) {
191
213
  return "the body is not a JSON object";
192
214
  if (!("boards" in body))
193
215
  return `boards is missing (response keys: ${Object.keys(body).join(", ")})`;
194
- if (!Array.isArray(body.boards) || body.boards.some((x) => typeof x !== "number" || !Number.isSafeInteger(x) || x <= 0)) {
216
+ if (!Array.isArray(body.boards) ||
217
+ body.boards.some((x) => typeof x !== "number" || !Number.isSafeInteger(x) || x <= 0)) {
195
218
  return "boards is not an array of board ids (positive integers)";
196
219
  }
197
220
  if (!("card_count" in body))
@@ -219,11 +242,17 @@ export async function fetchPlanInventory(options, deps) {
219
242
  return { kind: "unavailable", detail: outcome.detail };
220
243
  const { status, text, body } = outcome;
221
244
  if (status < 200 || status >= 300) {
222
- return { kind: "unavailable", detail: `plan inventory read HTTP ${status} ${oneLine(text, 300)}` };
245
+ return {
246
+ kind: "unavailable",
247
+ detail: `plan inventory read HTTP ${status} ${oneLine(text, 300)}`,
248
+ };
223
249
  }
224
250
  const bad = badInventoryReason(body);
225
251
  if (bad !== null) {
226
- return { kind: "unavailable", detail: `plan inventory read HTTP ${status}: ${bad}` };
252
+ return {
253
+ kind: "unavailable",
254
+ detail: `plan inventory read HTTP ${status}: ${bad}`,
255
+ };
227
256
  }
228
257
  const b = body;
229
258
  return { kind: "ok", boards: b.boards, cardCount: b.card_count };
@@ -263,9 +292,15 @@ export function heartbeatConnection(state, stoppedReason, inventoryError) {
263
292
  if (state === "streaming") {
264
293
  return inventoryError === null
265
294
  ? { state, inventory: "ok" }
266
- : { state, inventory: "unavailable", reason: oneLine(inventoryError, HEARTBEAT_REASON_MAX_CODE_POINTS) };
295
+ : {
296
+ state,
297
+ inventory: "unavailable",
298
+ reason: oneLine(inventoryError, HEARTBEAT_REASON_MAX_CODE_POINTS),
299
+ };
267
300
  }
268
- return state === "stopped" ? { state, reason: stoppedReason ?? undefined } : { state };
301
+ return state === "stopped"
302
+ ? { state, reason: stoppedReason ?? undefined }
303
+ : { state };
269
304
  }
270
305
  /**
271
306
  * One heartbeat POST. Never throws on a failure of the request itself and NEVER stops the relay on one
@@ -298,7 +333,12 @@ statsHeld) {
298
333
  body.inventory = connection.inventory;
299
334
  const outcome = await request(options, deps, "heartbeat", `${options.dashboardUrl}${HEARTBEAT_PATH}`, {
300
335
  method: "POST",
301
- body: JSON.stringify({ connection: body, ...(stats !== undefined ? { stats } : {}), ...(title !== undefined ? { title } : {}), ...(statsHeld === true ? { statsHeld } : {}) }),
336
+ body: JSON.stringify({
337
+ connection: body,
338
+ ...(stats !== undefined ? { stats } : {}),
339
+ ...(title !== undefined ? { title } : {}),
340
+ ...(statsHeld === true ? { statsHeld } : {}),
341
+ }),
302
342
  });
303
343
  // DX-3099 — this is now the ONE place a heartbeat's own outcome is
304
344
  // inspected. `request()` still never throws, and a 401/403 is still an
@@ -308,7 +348,15 @@ statsHeld) {
308
348
  // request never landed at all, which is exactly the signal the silent-
309
349
  // failure counter in the relay below needs. Still never throws.
310
350
  if (outcome.kind !== "answer")
311
- return { landed: false, status: null, stats: null, statsNotStored: null, acceptsStatsHeld: false, revocation: null, title: null };
351
+ return {
352
+ landed: false,
353
+ status: null,
354
+ stats: null,
355
+ statsNotStored: null,
356
+ acceptsStatsHeld: false,
357
+ revocation: null,
358
+ title: null,
359
+ };
312
360
  // DX-2954 — the answer's `stats` (the operator dispatch's stored or
313
361
  // just-written totals and cursors) feed the session's stats collector.
314
362
  const ok = outcome.status >= 200 && outcome.status < 300;
@@ -316,7 +364,9 @@ statsHeld) {
316
364
  // landed; its `stats` are the stored values, so the collector must re-queue
317
365
  // rather than treat them as the answer to its write.
318
366
  const applied = ok && isRecord(outcome.body) && outcome.body.statsError === undefined;
319
- const statsBody = applied && isRecord(outcome.body) && isRecord(outcome.body.stats) ? outcome.body.stats : null;
367
+ const statsBody = applied && isRecord(outcome.body) && isRecord(outcome.body.stats)
368
+ ? outcome.body.stats
369
+ : null;
320
370
  // DX-3962: an answer from a server that predates attribution stores cursors with no `claims`. Treated exactly like
321
371
  // an answer with no stats (the older-server path): the collector never starts, the heartbeat still lands, and
322
372
  // nothing is recorded until the server is deployed. Handing it on would crash the collector at attach.
@@ -328,15 +378,26 @@ statsHeld) {
328
378
  : null;
329
379
  // DX-4418 - the dashboard refuses the beat of a session whose key a person revoked, and says so.
330
380
  // DX-4461 - the dashboard's stored title for this session; an answer without one is an older dashboard's.
331
- const storedTitle = ok && isRecord(outcome.body) && typeof outcome.body.title === "string" ? outcome.body.title : null;
381
+ const storedTitle = ok && isRecord(outcome.body) && typeof outcome.body.title === "string"
382
+ ? outcome.body.title
383
+ : null;
332
384
  return {
333
385
  landed: true,
334
386
  status: outcome.status,
335
387
  stats: answered,
336
388
  acceptsStatsHeld: ok && isRecord(outcome.body) && outcome.body.acceptsStatsHeld === true,
337
389
  // DX-4892: the dashboard says why carried stats were not stored (a session on no plan), instead of the relay inferring it from a missing `stats`.
338
- statsNotStored: ok && isRecord(outcome.body) && isRecord(outcome.body.statsError) && outcome.body.statsError.kind === "no_plan" ? "no_plan" : null,
339
- revocation: keyRevocationOf({ ok: false, status: outcome.status, body: outcome.body }),
390
+ statsNotStored: ok &&
391
+ isRecord(outcome.body) &&
392
+ isRecord(outcome.body.statsError) &&
393
+ outcome.body.statsError.kind === "no_plan"
394
+ ? "no_plan"
395
+ : null,
396
+ revocation: keyRevocationOf({
397
+ ok: false,
398
+ status: outcome.status,
399
+ body: outcome.body,
400
+ }),
340
401
  title: storedTitle,
341
402
  };
342
403
  }
package/dist/shutdown.js CHANGED
@@ -18,7 +18,9 @@ export function stopWhenSessionEnds(wiring) {
18
18
  wiring.stdin.once("end", wiring.stop);
19
19
  const exitAfterStop = () => {
20
20
  // A synchronous throw from `stop` takes the same "shutdown failed" path as a rejection.
21
- void Promise.resolve().then(wiring.stop).then(() => wiring.exit(0), (err) => {
21
+ void Promise.resolve()
22
+ .then(wiring.stop)
23
+ .then(() => wiring.exit(0), (err) => {
22
24
  process.stderr.write(`platform-mcp: shutdown failed: ${err instanceof Error ? err.message : String(err)}\n`);
23
25
  wiring.exit(1);
24
26
  });