@agent-deck/backend 2.3.2 → 2.5.0

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 (105) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/agent-run/adapter.d.ts +14 -10
  3. package/dist/agent-run/adapter.d.ts.map +1 -1
  4. package/dist/agent-run/adapter.js +8 -4
  5. package/dist/agent-run/adapter.js.map +1 -1
  6. package/dist/agent-run/claude.d.ts +23 -21
  7. package/dist/agent-run/claude.d.ts.map +1 -1
  8. package/dist/agent-run/claude.js +25 -18
  9. package/dist/agent-run/claude.js.map +1 -1
  10. package/dist/agent-run/codex.d.ts +29 -12
  11. package/dist/agent-run/codex.d.ts.map +1 -1
  12. package/dist/agent-run/codex.js +37 -20
  13. package/dist/agent-run/codex.js.map +1 -1
  14. package/dist/agent-run/service.d.ts +10 -1
  15. package/dist/agent-run/service.d.ts.map +1 -1
  16. package/dist/agent-run/service.js +9 -1
  17. package/dist/agent-run/service.js.map +1 -1
  18. package/dist/agent-run-api/host.d.ts.map +1 -1
  19. package/dist/agent-run-api/host.js +9 -0
  20. package/dist/agent-run-api/host.js.map +1 -1
  21. package/dist/mcp-server.d.ts +114 -1
  22. package/dist/mcp-server.d.ts.map +1 -1
  23. package/dist/mcp-server.js +507 -55
  24. package/dist/mcp-server.js.map +1 -1
  25. package/dist/mcp-session-binding.d.ts +32 -0
  26. package/dist/mcp-session-binding.d.ts.map +1 -1
  27. package/dist/mcp-session-binding.js +52 -0
  28. package/dist/mcp-session-binding.js.map +1 -1
  29. package/dist/mcp-tools/register.d.ts +5 -1
  30. package/dist/mcp-tools/register.d.ts.map +1 -1
  31. package/dist/mcp-tools/register.js +2 -0
  32. package/dist/mcp-tools/register.js.map +1 -1
  33. package/dist/mcp-tools/run-tools.d.ts +3 -0
  34. package/dist/mcp-tools/run-tools.d.ts.map +1 -0
  35. package/dist/mcp-tools/run-tools.js +102 -0
  36. package/dist/mcp-tools/run-tools.js.map +1 -0
  37. package/dist/routes/agent-runs.d.ts +1 -1
  38. package/dist/routes/agent-runs.d.ts.map +1 -1
  39. package/dist/routes/agent-runs.js +231 -46
  40. package/dist/routes/agent-runs.js.map +1 -1
  41. package/dist/routes/trusted-session.d.ts.map +1 -1
  42. package/dist/routes/trusted-session.js +12 -0
  43. package/dist/routes/trusted-session.js.map +1 -1
  44. package/dist/trusted-session/route-policy-registry.d.ts.map +1 -1
  45. package/dist/trusted-session/route-policy-registry.js +8 -0
  46. package/dist/trusted-session/route-policy-registry.js.map +1 -1
  47. package/dist/trusted-session/store.d.ts +11 -0
  48. package/dist/trusted-session/store.d.ts.map +1 -1
  49. package/dist/trusted-session/store.js +24 -3
  50. package/dist/trusted-session/store.js.map +1 -1
  51. package/package.json +2 -2
  52. package/static-ui/assets/{index-BSYloDBW.js → index-Bbu6K9ON.js} +1 -1
  53. package/static-ui/index.html +1 -1
  54. package/dist/execution-authority/bearer.d.ts +0 -15
  55. package/dist/execution-authority/bearer.d.ts.map +0 -1
  56. package/dist/execution-authority/bearer.js +0 -35
  57. package/dist/execution-authority/bearer.js.map +0 -1
  58. package/dist/execution-authority/index.d.ts +0 -6
  59. package/dist/execution-authority/index.d.ts.map +0 -1
  60. package/dist/execution-authority/index.js +0 -8
  61. package/dist/execution-authority/index.js.map +0 -1
  62. package/dist/execution-authority/ledger.d.ts +0 -85
  63. package/dist/execution-authority/ledger.d.ts.map +0 -1
  64. package/dist/execution-authority/ledger.js +0 -507
  65. package/dist/execution-authority/ledger.js.map +0 -1
  66. package/dist/execution-authority/store.d.ts +0 -55
  67. package/dist/execution-authority/store.d.ts.map +0 -1
  68. package/dist/execution-authority/store.js +0 -256
  69. package/dist/execution-authority/store.js.map +0 -1
  70. package/dist/execution-authority/types.d.ts +0 -119
  71. package/dist/execution-authority/types.d.ts.map +0 -1
  72. package/dist/execution-authority/types.js +0 -9
  73. package/dist/execution-authority/types.js.map +0 -1
  74. package/dist/lib/execution-authority-http.d.ts +0 -23
  75. package/dist/lib/execution-authority-http.d.ts.map +0 -1
  76. package/dist/lib/execution-authority-http.js +0 -101
  77. package/dist/lib/execution-authority-http.js.map +0 -1
  78. package/dist/mcp-stdio.d.ts +0 -2
  79. package/dist/mcp-stdio.d.ts.map +0 -1
  80. package/dist/mcp-stdio.js.map +0 -1
  81. package/dist/playbooks/playbook-parser.d.ts +0 -8
  82. package/dist/playbooks/playbook-parser.d.ts.map +0 -1
  83. package/dist/playbooks/playbook-parser.js +0 -76
  84. package/dist/playbooks/playbook-parser.js.map +0 -1
  85. package/dist/playbooks/playbook-service.d.ts +0 -9
  86. package/dist/playbooks/playbook-service.d.ts.map +0 -1
  87. package/dist/playbooks/playbook-service.js +0 -107
  88. package/dist/playbooks/playbook-service.js.map +0 -1
  89. package/dist/routes/execution-authority.d.ts +0 -8
  90. package/dist/routes/execution-authority.d.ts.map +0 -1
  91. package/dist/routes/execution-authority.js +0 -498
  92. package/dist/routes/execution-authority.js.map +0 -1
  93. package/dist/scope/bindings-sidecar.d.ts +0 -9
  94. package/dist/scope/bindings-sidecar.d.ts.map +0 -1
  95. package/dist/scope/bindings-sidecar.js +0 -57
  96. package/dist/scope/bindings-sidecar.js.map +0 -1
  97. package/dist/scope/repo-deck.d.ts +0 -10
  98. package/dist/scope/repo-deck.d.ts.map +0 -1
  99. package/dist/scope/repo-deck.js +0 -63
  100. package/dist/scope/repo-deck.js.map +0 -1
  101. package/dist/test-local-mcp-e2e.d.ts +0 -3
  102. package/dist/test-local-mcp-e2e.d.ts.map +0 -1
  103. package/dist/test-local-mcp-e2e.js +0 -104
  104. package/dist/test-local-mcp-e2e.js.map +0 -1
  105. package/static-ui/favicon.png +0 -0
@@ -37,6 +37,18 @@ function readLaunchDeckHeader(req) {
37
37
  const value = typeof raw === 'string' ? raw.trim() : '';
38
38
  return value || undefined;
39
39
  }
40
+ /**
41
+ * NOT-562: resolve the deck assigned to a folder for workspace-header-only
42
+ * hosts (pure MCP, no launcher). Reads ONLY `<folder>/.agent-deck/use.json`
43
+ * — the same file the launcher reads today, on the same loopback — via the
44
+ * shared `readUseManifest`. Returns undefined when the file is missing,
45
+ * unreadable, corrupt, or not a v3 manifest, so the caller keeps the
46
+ * existing unassigned flow.
47
+ */
48
+ function resolveUseManifestDeckId(workspaceRoot) {
49
+ const deckId = (0, stub_sync_1.readUseManifest)(workspaceRoot)?.deckId?.trim();
50
+ return deckId || undefined;
51
+ }
40
52
  /**
41
53
  * Opaque run-correlation id for launch-selected sessions (NOT-304).
42
54
  * Returned unvalidated — the binding store normalizes and adopt-once
@@ -222,8 +234,21 @@ class AgentDeckMCPServer {
222
234
  instanceId = (0, node_crypto_1.randomUUID)();
223
235
  startedAt = new Date().toISOString();
224
236
  staleSessionCount = 0;
225
- /** Pre-restart session id → whether its client has since re-initialized. */
237
+ /**
238
+ * Pre-restart session id → whether its client has since come back: by
239
+ * re-initializing (our bridge names the session it lost on the replayed
240
+ * handshake) or by server-side recovery from rebindable headers (NOT-569).
241
+ */
226
242
  staleSessionsById = new Map();
243
+ /**
244
+ * NOT-569: stale pre-restart session id → live recovered session id.
245
+ * Hosts that never re-initialize after a 404 (observed: Cursor, Muse)
246
+ * keep sending the old id; once a request on it is recovered from
247
+ * deck-resolving headers, the alias keeps serving later requests on that
248
+ * id. Bounded with the same oldest-first discipline as the stale tally
249
+ * and the closed set — diagnostics/routing, not a ledger.
250
+ */
251
+ recoveredSessionAlias = new Map();
227
252
  /**
228
253
  * Sessions this process issued and then closed. A late request on one of them is
229
254
  * an ordinary end-of-session race, not a client left behind by a restart, and
@@ -670,6 +695,14 @@ class AgentDeckMCPServer {
670
695
  const session = this.sessions.get(sessionId);
671
696
  this.sessions.delete(sessionId);
672
697
  this.rememberClosedSession(sessionId);
698
+ // NOT-569: drop recovery aliases pointing at the cleaned session, so a
699
+ // later request on a stale id re-recovers from headers instead of
700
+ // resolving to a dead session.
701
+ for (const [staleId, liveId] of this.recoveredSessionAlias) {
702
+ if (liveId === sessionId) {
703
+ this.recoveredSessionAlias.delete(staleId);
704
+ }
705
+ }
673
706
  this.pendingSessionClose.delete(sessionId);
674
707
  this.lastClientActivityAtMs.delete(sessionId);
675
708
  this.heartbeatCapableSessions.delete(sessionId);
@@ -1219,6 +1252,13 @@ class AgentDeckMCPServer {
1219
1252
  * `Mcp-Session-Id`, and that a client seeing 404 MUST re-initialize. The old
1220
1253
  * 400 "Bad Request: No valid session ID provided" was indistinguishable from a
1221
1254
  * malformed request, so bridges parked on it forever instead of reconnecting.
1255
+ *
1256
+ * Narrow exception (NOT-569): the POST handler tries
1257
+ * `tryRecoverStaleSession` before reaching here. A non-initialize request
1258
+ * whose headers rebind the folder's deck exactly as an initialize would is
1259
+ * served on a recovered session instead — for hosts that never
1260
+ * re-initialize (observed: Cursor, Muse). Everything this method still
1261
+ * sees keeps the 404 behavior exactly.
1222
1262
  */
1223
1263
  sendSessionNotFound(sessionId, res) {
1224
1264
  if (this.closedSessionIds.has(sessionId)) {
@@ -1275,6 +1315,42 @@ class AgentDeckMCPServer {
1275
1315
  }
1276
1316
  this.closedSessionIds.add(sessionId);
1277
1317
  }
1318
+ /**
1319
+ * NOT-569: remember a stale → recovered alias, evicting the oldest alias
1320
+ * first when full — the same size discipline as the stale tally and the
1321
+ * closed set. Eviction drops routing only; the underlying live session
1322
+ * keeps its normal idle-TTL retention, and a later request on the evicted
1323
+ * stale id simply recovers again.
1324
+ */
1325
+ rememberRecoveryAlias(staleSessionId, liveSessionId) {
1326
+ if (!this.recoveredSessionAlias.has(staleSessionId) &&
1327
+ this.recoveredSessionAlias.size >= AgentDeckMCPServer.STALE_SESSION_SAMPLE_LIMIT) {
1328
+ const oldest = this.recoveredSessionAlias.keys().next().value;
1329
+ if (oldest !== undefined) {
1330
+ this.recoveredSessionAlias.delete(oldest);
1331
+ }
1332
+ }
1333
+ this.recoveredSessionAlias.set(staleSessionId, liveSessionId);
1334
+ }
1335
+ /**
1336
+ * NOT-569: count a stale id recovered from headers as recovered in the
1337
+ * tally, so `/health` (and `agent-deck status`) stop warning for hosts
1338
+ * that recover this way. Mirrors `markStaleSessionRecovered` without
1339
+ * needing a replayed handshake: a known entry flips to recovered, an
1340
+ * unknown one is recorded as recovered within the same bound. The request
1341
+ * counter is untouched — the request was served, not answered 404.
1342
+ */
1343
+ markStaleSessionRecoveredById(staleSessionId) {
1344
+ const at = new Date().toISOString();
1345
+ const known = this.staleSessionsById.get(staleSessionId);
1346
+ if (known) {
1347
+ known.recovered = true;
1348
+ known.lastAt = at;
1349
+ }
1350
+ else if (this.staleSessionsById.size < AgentDeckMCPServer.STALE_SESSION_SAMPLE_LIMIT) {
1351
+ this.staleSessionsById.set(staleSessionId, { recovered: true, lastAt: at });
1352
+ }
1353
+ }
1278
1354
  async refreshRuntimeSession(sessionId) {
1279
1355
  const binding = this.sessionBinding.getBinding(sessionId);
1280
1356
  if (!binding.runtimeSessionId) {
@@ -1428,8 +1504,22 @@ class AgentDeckMCPServer {
1428
1504
  this.adoptPlaybookPin(sessionId, req);
1429
1505
  return true;
1430
1506
  }
1431
- async authenticateLaunchDeck(sessionId, req) {
1432
- const deckId = readLaunchDeckHeader(req);
1507
+ /**
1508
+ * NOT-539: the launch-bound execution workspace for `start_run` comes from
1509
+ * the launcher only — the workspace header on the initial launch request or
1510
+ * the host's AGENT_DECK_WORKSPACE — never from `bind_workspace` or a
1511
+ * follow-up request. Read once, at initial launch authentication.
1512
+ */
1513
+ readLaunchExecutionWorkspace(req) {
1514
+ return readWorkspaceRootHeader(req) ?? (process.env.AGENT_DECK_WORKSPACE?.trim() || undefined);
1515
+ }
1516
+ /**
1517
+ * NOT-562: `deckIdOverride` carries a deck resolved somewhere other than
1518
+ * the deck header — the folder assignment for workspace-header-only hosts.
1519
+ * Omitted callers behave exactly as before (header or GRANT_REQUIRED).
1520
+ */
1521
+ async authenticateLaunchDeck(sessionId, req, deckIdOverride) {
1522
+ const deckId = deckIdOverride ?? readLaunchDeckHeader(req);
1433
1523
  if (!deckId) {
1434
1524
  throw new Error('GRANT_REQUIRED');
1435
1525
  }
@@ -1444,6 +1534,8 @@ class AgentDeckMCPServer {
1444
1534
  if (workspaceRoot) {
1445
1535
  this.sessionBinding.setWorkspace(sessionId, workspaceRoot);
1446
1536
  }
1537
+ // The execution workspace — present or absent — was frozen at initial
1538
+ // launch authentication; a follow-up header never grants or moves it.
1447
1539
  // Adopt-once: a launch that arrived without correlation can still
1448
1540
  // attach one; an established value never moves (NOT-304).
1449
1541
  const followUpCorrelation = readCorrelationIdHeader(req);
@@ -1453,12 +1545,14 @@ class AgentDeckMCPServer {
1453
1545
  this.adoptPlaybookPin(sessionId, req);
1454
1546
  return;
1455
1547
  }
1548
+ const executionWorkspace = this.readLaunchExecutionWorkspace(req);
1456
1549
  const response = await fetch(`${this.backendUrl}/api/trusted-session/mcp/connect-deck`, {
1457
1550
  method: 'POST',
1458
1551
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
1459
1552
  body: JSON.stringify({
1460
1553
  deckId,
1461
1554
  mcpSessionId: sessionId,
1555
+ ...(executionWorkspace ? { executionWorkspace } : {}),
1462
1556
  }),
1463
1557
  });
1464
1558
  const body = (await response.json());
@@ -1474,6 +1568,9 @@ class AgentDeckMCPServer {
1474
1568
  workspaceRoot,
1475
1569
  mode: body.data.mode,
1476
1570
  });
1571
+ // Freezes presence and absence alike: a launch without workspace metadata
1572
+ // keeps returning WORKSPACE_REQUIRED for the session lifetime.
1573
+ this.sessionBinding.freezeExecutionWorkspace(sessionId, executionWorkspace);
1477
1574
  // Attach the opaque run-correlation id to this launch-selected session
1478
1575
  // (NOT-304). Adopt-once and validated inside the store: an invalid or
1479
1576
  // later-changed value can never affect deck, workspace, mode, or auth.
@@ -1512,9 +1609,19 @@ class AgentDeckMCPServer {
1512
1609
  return true;
1513
1610
  }
1514
1611
  const launchDeck = readLaunchDeckHeader(req);
1515
- if (launchDeck) {
1612
+ // NOT-562: sessions bound from the folder assignment carry no deck
1613
+ // header on follow-ups either, so re-validate through the same launch
1614
+ // follow-up (runtime lease refresh) instead of demanding the header.
1615
+ // The assignment file is authoritative only at initialize: like a
1616
+ // changed deck header (NOT-108), a later use.json edit is sticky for
1617
+ // the session lifetime and takes effect when the client re-initializes
1618
+ // — a live session is never failed on file drift.
1619
+ const useManifestFollowUp = !launchDeck &&
1620
+ this.sessionBinding.isLaunchSession(sessionId) &&
1621
+ this.sessionBinding.isUseManifestSession(sessionId);
1622
+ if (launchDeck || useManifestFollowUp) {
1516
1623
  try {
1517
- await this.authenticateLaunchDeck(sessionId, req);
1624
+ await this.authenticateLaunchDeck(sessionId, req, launchDeck ?? this.sessionBinding.getBinding(sessionId).deckId);
1518
1625
  return true;
1519
1626
  }
1520
1627
  catch (error) {
@@ -1540,6 +1647,19 @@ class AgentDeckMCPServer {
1540
1647
  id: null,
1541
1648
  });
1542
1649
  }
1650
+ /**
1651
+ * Resolve the deck a bearer-free request binds (NOT-562, shared by the
1652
+ * initialize path and NOT-569 recovery so the two resolve identically):
1653
+ * an explicit deck header wins, else the folder assignment from
1654
+ * `<workspace>/.agent-deck/use.json`. Anything else is not a deck —
1655
+ * recovery refuses it and initialize takes the unassigned flow.
1656
+ */
1657
+ resolveHeaderDeck(req) {
1658
+ const launchDeck = readLaunchDeckHeader(req);
1659
+ const workspaceRoot = readWorkspaceRootHeader(req);
1660
+ const manifestDeck = !launchDeck && workspaceRoot ? resolveUseManifestDeckId(workspaceRoot) : undefined;
1661
+ return { launchDeck, workspaceRoot, manifestDeck, effectiveDeck: launchDeck ?? manifestDeck };
1662
+ }
1543
1663
  /**
1544
1664
  * NOT-318: initialize with a bearer grant. Authenticates before
1545
1665
  * advertising any `mcp-session-id`: failure answers the uniform 401
@@ -1587,42 +1707,143 @@ class AgentDeckMCPServer {
1587
1707
  });
1588
1708
  await this.establishTransportSession(req, res, sessionId);
1589
1709
  }
1590
- async handleMcpPost(req, res) {
1591
- const sessionIdHeader = this.getSessionIdHeader(req);
1592
- const existing = sessionIdHeader ? this.sessions.get(sessionIdHeader) : undefined;
1593
- const bearerRequired = isBearerGrantRequired();
1594
- if (existing && sessionIdHeader) {
1595
- // Grant-bound sessions revalidate the bearer on every request and
1596
- // never take the trust-the-header launch path: a forged deck header
1597
- // is denied by the grant allowlist, not trusted into a new deck.
1598
- if (this.sessionBinding.isGrantSession(sessionIdHeader)) {
1599
- if (!(await this.requireGrantFollowUp(sessionIdHeader, req, res))) {
1600
- return;
1601
- }
1710
+ /**
1711
+ * Serve one follow-up request on a live session. `presentedSessionId` is
1712
+ * the id the client sent when it differs from the live session id (a
1713
+ * NOT-569 recovery alias): the headers are translated so the transport
1714
+ * validates and answers under the live id while the client keeps seeing
1715
+ * the id it sent.
1716
+ */
1717
+ async serveFollowUp(sessionId, req, res, presentedSessionId) {
1718
+ // Grant-bound sessions revalidate the bearer on every request and
1719
+ // never take the trust-the-header launch path: a forged deck header
1720
+ // is denied by the grant allowlist, not trusted into a new deck.
1721
+ if (this.sessionBinding.isGrantSession(sessionId)) {
1722
+ if (!(await this.requireGrantFollowUp(sessionId, req, res))) {
1723
+ return;
1602
1724
  }
1603
- else {
1604
- // Hosted mode has no bearer-free sessions; a non-grant session id
1605
- // is unusable there — fail closed before touching the transport.
1606
- if (bearerRequired) {
1607
- this.sendGrantRequired(res);
1608
- return;
1725
+ }
1726
+ else {
1727
+ // Hosted mode has no bearer-free sessions; a non-grant session id
1728
+ // is unusable there — fail closed before touching the transport.
1729
+ if (isBearerGrantRequired()) {
1730
+ this.sendGrantRequired(res);
1731
+ return;
1732
+ }
1733
+ if (!(await this.requireFollowUpDeckHeader(sessionId, req, res))) {
1734
+ return;
1735
+ }
1736
+ }
1737
+ // The auth above awaits, so re-check: a sweep may have expired the
1738
+ // session while it ran, and answering on a dead transport would hang.
1739
+ const live = this.sessions.get(sessionId);
1740
+ if (!live) {
1741
+ this.sendSessionNotFound(presentedSessionId ?? sessionId, res);
1742
+ return;
1743
+ }
1744
+ this.noteClientActivity(sessionId, req);
1745
+ this.touchLiveDisplay(sessionId);
1746
+ if (presentedSessionId && presentedSessionId !== sessionId) {
1747
+ await this.withPresentedSessionId(sessionId, presentedSessionId, req, res, () => this.handleTransportPost(sessionId, req, res));
1748
+ }
1749
+ else {
1750
+ await this.handleTransportPost(sessionId, req, res);
1751
+ }
1752
+ }
1753
+ /**
1754
+ * NOT-569: run `serve` with the wire session id translated. The request
1755
+ * header is rewritten to the live id so the transport's own session
1756
+ * validation passes, and every response header write is translated back
1757
+ * so the client keeps seeing the id it sent. Both `setHeader` and
1758
+ * `writeHead` are covered — the Hono Node adapter answers JSON
1759
+ * responses through `writeHead` — and `rawHeaders` is translated too,
1760
+ * because that same adapter rebuilds the request headers from the raw
1761
+ * pairs without ever reading the parsed `headers` object: without the
1762
+ * raw rewrite the transport validates the stale id and answers 404.
1763
+ */
1764
+ async withPresentedSessionId(liveSessionId, presentedSessionId, req, res, serve) {
1765
+ const headerKey = 'mcp-session-id';
1766
+ const previousHeader = req.headers[headerKey];
1767
+ req.headers[headerKey] = liveSessionId;
1768
+ // The Hono Node adapter (@hono/node-server, inside the SDK Express
1769
+ // wrapper) rebuilds the request headers from `rawHeaders`, never
1770
+ // reading the parsed `headers` object — translate the raw pairs too,
1771
+ // or the transport validates the stale id and answers its own 404.
1772
+ const previousRawHeaders = req.rawHeaders;
1773
+ if (Array.isArray(previousRawHeaders)) {
1774
+ const translated = previousRawHeaders.slice();
1775
+ for (let index = 0; index + 1 < translated.length; index += 2) {
1776
+ if (translated[index].toLowerCase() === headerKey) {
1777
+ translated[index + 1] = liveSessionId;
1609
1778
  }
1610
- if (!(await this.requireFollowUpDeckHeader(sessionIdHeader, req, res))) {
1611
- return;
1779
+ }
1780
+ req.rawHeaders = translated;
1781
+ }
1782
+ const resRecord = res;
1783
+ // Pristine refs for an exact restore; bound copies for calling through.
1784
+ const pristineSetHeader = resRecord.setHeader;
1785
+ const pristineWriteHead = resRecord.writeHead;
1786
+ const originalSetHeader = pristineSetHeader.bind(res);
1787
+ const originalWriteHead = pristineWriteHead.bind(res);
1788
+ resRecord.setHeader = ((name, value) => {
1789
+ if (typeof name === 'string' && name.toLowerCase() === headerKey && value === liveSessionId) {
1790
+ return originalSetHeader(name, presentedSessionId);
1791
+ }
1792
+ return originalSetHeader(name, value);
1793
+ });
1794
+ resRecord.writeHead = ((...args) => {
1795
+ // writeHead(status[, statusMessage][, headers]) — translate a headers
1796
+ // object in the trailing position without mutating the caller's copy.
1797
+ const last = args[args.length - 1];
1798
+ if (last && typeof last === 'object' && !Array.isArray(last)) {
1799
+ const headers = last;
1800
+ const translated = { ...headers };
1801
+ for (const key of Object.keys(translated)) {
1802
+ if (key.toLowerCase() === headerKey && translated[key] === liveSessionId) {
1803
+ translated[key] = presentedSessionId;
1804
+ }
1612
1805
  }
1806
+ args[args.length - 1] = translated;
1613
1807
  }
1614
- // The auth above awaits, so re-check: a sweep may have expired the
1615
- // session while it ran, and answering on a dead transport would hang.
1616
- const live = this.sessions.get(sessionIdHeader);
1617
- if (!live) {
1618
- this.sendSessionNotFound(sessionIdHeader, res);
1619
- return;
1808
+ return originalWriteHead(...args);
1809
+ });
1810
+ try {
1811
+ return await serve();
1812
+ }
1813
+ finally {
1814
+ if (previousHeader === undefined) {
1815
+ delete req.headers[headerKey];
1816
+ }
1817
+ else {
1818
+ req.headers[headerKey] = previousHeader;
1819
+ }
1820
+ if (Array.isArray(previousRawHeaders)) {
1821
+ req.rawHeaders = previousRawHeaders;
1620
1822
  }
1621
- this.noteClientActivity(sessionIdHeader, req);
1622
- this.touchLiveDisplay(sessionIdHeader);
1623
- await this.handleTransportPost(sessionIdHeader, req, res);
1823
+ resRecord.setHeader = pristineSetHeader;
1824
+ resRecord.writeHead = pristineWriteHead;
1825
+ }
1826
+ }
1827
+ async handleMcpPost(req, res) {
1828
+ const sessionIdHeader = this.getSessionIdHeader(req);
1829
+ const bearerRequired = isBearerGrantRequired();
1830
+ // Direct hit, or a NOT-569 recovery alias from a stale pre-restart id.
1831
+ // An alias pointing at a dead session is dropped so the request below
1832
+ // re-recovers from headers instead of sticking to it.
1833
+ if (sessionIdHeader && this.sessions.has(sessionIdHeader)) {
1834
+ await this.serveFollowUp(sessionIdHeader, req, res);
1624
1835
  return;
1625
1836
  }
1837
+ if (sessionIdHeader) {
1838
+ const aliased = this.recoveredSessionAlias.get(sessionIdHeader);
1839
+ if (aliased && this.sessions.has(aliased)) {
1840
+ await this.serveFollowUp(aliased, req, res, sessionIdHeader);
1841
+ return;
1842
+ }
1843
+ if (aliased) {
1844
+ this.recoveredSessionAlias.delete(sessionIdHeader);
1845
+ }
1846
+ }
1626
1847
  const body = req.body;
1627
1848
  const isInit = body &&
1628
1849
  typeof body === 'object' &&
@@ -1655,7 +1876,15 @@ class AgentDeckMCPServer {
1655
1876
  // A session id we don't know is a restart, not a malformed request — 404 so
1656
1877
  // the client re-initializes. An initialize carrying a stale id falls through
1657
1878
  // and gets a fresh session, which is exactly the recovery we want.
1879
+ //
1880
+ // NOT-569: before the 404, a bearer-free request whose headers rebind
1881
+ // the deck gets one narrow exception — hosts that never re-initialize
1882
+ // (observed: Cursor, Muse) are served on a recovered session instead.
1883
+ // Anything recovery refuses keeps the NOT-101 404 below.
1658
1884
  if (sessionIdHeader) {
1885
+ if (await this.tryRecoverStaleSession(req, res, sessionIdHeader)) {
1886
+ return;
1887
+ }
1659
1888
  this.sendSessionNotFound(sessionIdHeader, res);
1660
1889
  return;
1661
1890
  }
@@ -1678,37 +1907,237 @@ class AgentDeckMCPServer {
1678
1907
  this.sendGrantRequired(res);
1679
1908
  return;
1680
1909
  }
1681
- const launchDeck = readLaunchDeckHeader(req);
1910
+ // NOT-562: workspace-header-only hosts (pure MCP, no launcher) resolve
1911
+ // the deck from the folder assignment. An explicit deck header still
1912
+ // wins; the manifest is consulted only when it is absent. Shared with
1913
+ // NOT-569 recovery so both paths resolve identically.
1914
+ const { launchDeck, workspaceRoot, manifestDeck, effectiveDeck } = this.resolveHeaderDeck(req);
1682
1915
  const skipDeckHeader = (0, mcp_unassigned_1.skipDeckHeaderAuth)();
1683
- const unassigned = !launchDeck && !skipDeckHeader;
1916
+ const unassigned = !effectiveDeck && !skipDeckHeader;
1684
1917
  // Authenticate before advertising mcp-session-id.
1685
1918
  const sessionId = (0, node_crypto_1.randomUUID)();
1686
- if (launchDeck) {
1919
+ if (effectiveDeck) {
1687
1920
  try {
1688
- await this.authenticateLaunchDeck(sessionId, req);
1921
+ await this.authenticateLaunchDeck(sessionId, req, effectiveDeck);
1922
+ if (manifestDeck && !launchDeck) {
1923
+ this.sessionBinding.markUseManifestSession(sessionId);
1924
+ }
1689
1925
  }
1690
1926
  catch (error) {
1691
- this.getAuditStore()?.append({
1692
- actor: 'local-launch',
1693
- event: 'deck.selection_denied',
1694
- targetId: (0, store_1.auditDeckTarget)(launchDeck),
1695
- outcome: 'denied',
1696
- reasonCode: 'resource_out_of_scope',
1697
- });
1698
- console.warn('[agent-deck] Launch-deck auth failed before MCP init:', error instanceof Error ? error.message : error);
1699
- this.sendLaunchDeckInvalid(res, error instanceof Error ? error.message : 'LAUNCH_DECK_INVALID');
1700
- return;
1927
+ // NOT-562: the assignment names a deck the backend cannot bind
1928
+ // (deleted deck) or the bind itself failed — the file is an
1929
+ // opportunistic hint, not a credential, so degrade to the existing
1930
+ // unassigned flow rather than erroring. The header path below keeps
1931
+ // its fail-closed 401.
1932
+ if (manifestDeck && !launchDeck) {
1933
+ this.sessionBinding.markUnassigned(sessionId);
1934
+ if (workspaceRoot) {
1935
+ this.sessionBinding.setWorkspace(sessionId, workspaceRoot);
1936
+ }
1937
+ }
1938
+ else {
1939
+ this.getAuditStore()?.append({
1940
+ actor: 'local-launch',
1941
+ event: 'deck.selection_denied',
1942
+ targetId: (0, store_1.auditDeckTarget)(launchDeck),
1943
+ outcome: 'denied',
1944
+ reasonCode: 'resource_out_of_scope',
1945
+ });
1946
+ console.warn('[agent-deck] Launch-deck auth failed before MCP init:', error instanceof Error ? error.message : error);
1947
+ this.sendLaunchDeckInvalid(res, error instanceof Error ? error.message : 'LAUNCH_DECK_INVALID');
1948
+ return;
1949
+ }
1701
1950
  }
1702
1951
  }
1703
1952
  else if (unassigned) {
1704
1953
  this.sessionBinding.markUnassigned(sessionId);
1705
- const workspaceRoot = readWorkspaceRootHeader(req);
1706
1954
  if (workspaceRoot) {
1707
1955
  this.sessionBinding.setWorkspace(sessionId, workspaceRoot);
1708
1956
  }
1709
1957
  }
1710
1958
  await this.establishTransportSession(req, res, sessionId);
1711
1959
  }
1960
+ /**
1961
+ * NOT-569: narrow exception to the NOT-101 404 rule. In local
1962
+ * (non-hosted, bearer-free) mode only, a non-initialize request that
1963
+ * carries an unknown session id plus headers resolving to a deck exactly
1964
+ * as an initialize would is served on a fresh recovered session instead
1965
+ * of answered 404 — for hosts that never re-initialize (observed:
1966
+ * Cursor, Muse). Returns whether the request was served; anything
1967
+ * refused (no deck-resolving header, unresolvable workspace, an id this
1968
+ * process closed itself, any bearer/hosted/grant request, a bind or
1969
+ * handshake failure) keeps the NOT-101 404 at the call site.
1970
+ *
1971
+ * Recovery mints a fresh transport session for the deck, remembers a
1972
+ * bounded stale → live alias, performs the MCP initialize handshake on
1973
+ * the host's behalf, and serves the request with the wire id translated
1974
+ * back to the id the client sent — the client needs no change, and
1975
+ * later requests on the same stale id serve from the alias. A bind
1976
+ * failure answers 404, never a new 401 surface on follow-up requests.
1977
+ */
1978
+ async tryRecoverStaleSession(req, res, staleSessionId) {
1979
+ // Local bearer-free mode only: hosted requests keep the 401 gate (or
1980
+ // the 404 below once authenticated), and any request carrying a grant
1981
+ // bearer keeps the restart 404 — grant clients re-initialize.
1982
+ if (isBearerGrantRequired()) {
1983
+ return false;
1984
+ }
1985
+ if (readBearerToken(req)) {
1986
+ return false;
1987
+ }
1988
+ // A session this process closed stays closed — never resurrect it.
1989
+ if (this.closedSessionIds.has(staleSessionId)) {
1990
+ return false;
1991
+ }
1992
+ const { launchDeck, manifestDeck, effectiveDeck } = this.resolveHeaderDeck(req);
1993
+ if (!effectiveDeck) {
1994
+ return false;
1995
+ }
1996
+ // A racing recovery may have installed an alias while headers resolved.
1997
+ if (await this.serveFromRecoveryAlias(req, res, staleSessionId)) {
1998
+ return true;
1999
+ }
2000
+ const freshSessionId = (0, node_crypto_1.randomUUID)();
2001
+ try {
2002
+ await this.authenticateLaunchDeck(freshSessionId, req, effectiveDeck);
2003
+ if (manifestDeck && !launchDeck) {
2004
+ this.sessionBinding.markUseManifestSession(freshSessionId);
2005
+ }
2006
+ }
2007
+ catch {
2008
+ // Opportunistic: a bind failure falls back to the NOT-101 404 the
2009
+ // call site answers — silently, so a retrying host cannot spam one
2010
+ // line per request (the 404 path logs first-seen ids already).
2011
+ this.sessionBinding.clearSession(freshSessionId);
2012
+ return false;
2013
+ }
2014
+ // Adopt a concurrent winner instead of minting a second session.
2015
+ if (await this.serveFromRecoveryAlias(req, res, staleSessionId)) {
2016
+ await this.disconnectTrustedSession(freshSessionId, req);
2017
+ this.sessionBinding.clearSession(freshSessionId);
2018
+ return true;
2019
+ }
2020
+ const server = await this.createMcpServer(freshSessionId);
2021
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
2022
+ sessionIdGenerator: () => freshSessionId,
2023
+ enableJsonResponse: true,
2024
+ onsessioninitialized: (initializedSessionId) => {
2025
+ this.sessions.set(initializedSessionId, { transport, server });
2026
+ },
2027
+ });
2028
+ transport.onclose = () => {
2029
+ const closedSessionId = transport.sessionId;
2030
+ if (closedSessionId) {
2031
+ void this.startCleanupSession(closedSessionId, { closeTransport: false });
2032
+ }
2033
+ };
2034
+ try {
2035
+ await server.connect(transport);
2036
+ await this.performRecoveryHandshake(transport, req);
2037
+ }
2038
+ catch {
2039
+ this.sessions.delete(freshSessionId);
2040
+ await this.disconnectTrustedSession(freshSessionId, req);
2041
+ this.sessionBinding.clearSession(freshSessionId);
2042
+ return false;
2043
+ }
2044
+ if (!this.sessions.has(freshSessionId)) {
2045
+ this.sessions.set(freshSessionId, { transport, server });
2046
+ }
2047
+ // Atomic install: a concurrent recovery may have won during the
2048
+ // handshake above — the check and the set below run with no await
2049
+ // between them, so exactly one winner installs the alias.
2050
+ const lateWinner = this.recoveredSessionAlias.get(staleSessionId);
2051
+ if (lateWinner && this.sessions.has(lateWinner)) {
2052
+ await this.startCleanupSession(freshSessionId, { closeTransport: true });
2053
+ await this.serveFollowUp(lateWinner, req, res, staleSessionId);
2054
+ return true;
2055
+ }
2056
+ if (lateWinner) {
2057
+ this.recoveredSessionAlias.delete(staleSessionId);
2058
+ }
2059
+ this.rememberRecoveryAlias(staleSessionId, freshSessionId);
2060
+ this.markStaleSessionRecoveredById(staleSessionId);
2061
+ // One line per recovered session id, not per request — the host keeps
2062
+ // sending the stale id on every later call.
2063
+ console.warn(`[agent-deck] MCP session ${staleSessionId} recovered from headers as ${freshSessionId} ` +
2064
+ `(deck ${effectiveDeck}); the client never re-initialized after the restart.`);
2065
+ // NOT-513: adopt the host-side session id before the first live-display
2066
+ // register, so the entry carries it from the start.
2067
+ this.adoptHostSessionId(freshSessionId, req);
2068
+ if (!this.sessionBinding.isUnassigned(freshSessionId)) {
2069
+ void this.registerLiveDisplay(freshSessionId).catch(() => { });
2070
+ }
2071
+ await this.serveFollowUp(freshSessionId, req, res, staleSessionId);
2072
+ return true;
2073
+ }
2074
+ /**
2075
+ * NOT-569: serve one request from an installed recovery alias. Returns
2076
+ * whether an alias served the request; a dead alias is dropped so the
2077
+ * caller re-recovers from headers instead of sticking to it.
2078
+ */
2079
+ async serveFromRecoveryAlias(req, res, staleSessionId) {
2080
+ const aliased = this.recoveredSessionAlias.get(staleSessionId);
2081
+ if (!aliased) {
2082
+ return false;
2083
+ }
2084
+ if (this.sessions.has(aliased)) {
2085
+ await this.serveFollowUp(aliased, req, res, staleSessionId);
2086
+ return true;
2087
+ }
2088
+ this.recoveredSessionAlias.delete(staleSessionId);
2089
+ return false;
2090
+ }
2091
+ /**
2092
+ * NOT-569: perform the MCP initialize handshake on the host's behalf so
2093
+ * the recovered transport is initialized before it serves the request.
2094
+ * The host's original handshake died with the previous process, so the
2095
+ * client identity is synthetic and marked as such (`agent-deck-recovery`
2096
+ * with empty capabilities — form elicitation degrades to the browser
2097
+ * fallback on recovered sessions); the protocol version reuses the
2098
+ * client's when it sent one. Runs entirely in memory — the host never
2099
+ * sees this exchange.
2100
+ */
2101
+ async performRecoveryHandshake(transport, req) {
2102
+ const webTransport = transport._webStandardTransport;
2103
+ const requestedVersion = req.headers['mcp-protocol-version'];
2104
+ const protocolVersion = typeof requestedVersion === 'string' && requestedVersion.trim()
2105
+ ? requestedVersion.trim()
2106
+ : types_js_1.LATEST_PROTOCOL_VERSION;
2107
+ const initializeBody = {
2108
+ jsonrpc: '2.0',
2109
+ id: 'agent-deck-recovery',
2110
+ method: 'initialize',
2111
+ params: {
2112
+ protocolVersion,
2113
+ capabilities: {},
2114
+ clientInfo: { name: 'agent-deck-recovery', version: '0.0.0' },
2115
+ },
2116
+ };
2117
+ const initializeResponse = await webTransport.handleRequest(new globalThis.Request('http://127.0.0.1/mcp', {
2118
+ method: 'POST',
2119
+ headers: {
2120
+ 'content-type': 'application/json',
2121
+ accept: 'application/json, text/event-stream',
2122
+ },
2123
+ body: JSON.stringify(initializeBody),
2124
+ }), { parsedBody: initializeBody });
2125
+ await initializeResponse.arrayBuffer();
2126
+ if (!initializeResponse.ok || !transport.sessionId) {
2127
+ throw new Error(`recovery handshake failed (status ${initializeResponse.status})`);
2128
+ }
2129
+ const initializedBody = { jsonrpc: '2.0', method: 'notifications/initialized' };
2130
+ const initializedResponse = await webTransport.handleRequest(new globalThis.Request('http://127.0.0.1/mcp', {
2131
+ method: 'POST',
2132
+ headers: {
2133
+ 'content-type': 'application/json',
2134
+ accept: 'application/json, text/event-stream',
2135
+ 'mcp-session-id': transport.sessionId,
2136
+ },
2137
+ body: JSON.stringify(initializedBody),
2138
+ }), { parsedBody: initializedBody });
2139
+ await initializedResponse.arrayBuffer();
2140
+ }
1712
2141
  /**
1713
2142
  * Shared transport handshake tail: create the per-session MCP server,
1714
2143
  * connect the streamable transport, and register the live session. Runs
@@ -1774,7 +2203,7 @@ class AgentDeckMCPServer {
1774
2203
  }
1775
2204
  }
1776
2205
  async handleMcpSessionRequest(req, res) {
1777
- const sessionId = this.getSessionIdHeader(req);
2206
+ const sessionIdHeader = this.getSessionIdHeader(req);
1778
2207
  const bearerRequired = isBearerGrantRequired();
1779
2208
  // Hosted endpoints run the Bearer [REDACTED] before session existence
1780
2209
  // (same no-oracle order as POST): 401 before any 404 metadata.
@@ -1782,13 +2211,31 @@ class AgentDeckMCPServer {
1782
2211
  this.sendGrantRequired(res);
1783
2212
  return;
1784
2213
  }
1785
- if (!sessionId) {
2214
+ if (!sessionIdHeader) {
1786
2215
  res.status(400).send('Invalid or missing session ID');
1787
2216
  return;
1788
2217
  }
1789
- const session = this.sessions.get(sessionId);
1790
- if (!session) {
1791
- this.sendSessionNotFound(sessionId, res);
2218
+ // Direct hit, or a NOT-569 recovery alias from a stale pre-restart id.
2219
+ // GET/DELETE honor an installed alias but never mint a fresh recovery
2220
+ // on their own — only POST (tool calls) does that.
2221
+ let sessionId;
2222
+ let presentedSessionId;
2223
+ if (this.sessions.has(sessionIdHeader)) {
2224
+ sessionId = sessionIdHeader;
2225
+ }
2226
+ else {
2227
+ const aliased = this.recoveredSessionAlias.get(sessionIdHeader);
2228
+ if (aliased && this.sessions.has(aliased)) {
2229
+ sessionId = aliased;
2230
+ presentedSessionId = sessionIdHeader;
2231
+ }
2232
+ else if (aliased) {
2233
+ this.recoveredSessionAlias.delete(sessionIdHeader);
2234
+ }
2235
+ }
2236
+ const session = sessionId ? this.sessions.get(sessionId) : undefined;
2237
+ if (!sessionId || !session) {
2238
+ this.sendSessionNotFound(sessionIdHeader, res);
1792
2239
  return;
1793
2240
  }
1794
2241
  if (this.sessionBinding.isGrantSession(sessionId)) {
@@ -1824,7 +2271,12 @@ class AgentDeckMCPServer {
1824
2271
  return;
1825
2272
  }
1826
2273
  this.touchLiveDisplay(sessionId);
1827
- await live.transport.handleRequest(req, res);
2274
+ if (presentedSessionId) {
2275
+ await this.withPresentedSessionId(sessionId, presentedSessionId, req, res, () => live.transport.handleRequest(req, res));
2276
+ }
2277
+ else {
2278
+ await live.transport.handleRequest(req, res);
2279
+ }
1828
2280
  }
1829
2281
  async start() {
1830
2282
  if (this.httpServer) {