@agent-deck/backend 2.4.0 → 2.5.1

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 (74) 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/mcp-server.d.ts +107 -1
  15. package/dist/mcp-server.d.ts.map +1 -1
  16. package/dist/mcp-server.js +491 -55
  17. package/dist/mcp-server.js.map +1 -1
  18. package/dist/mcp-session-binding.d.ts +15 -0
  19. package/dist/mcp-session-binding.d.ts.map +1 -1
  20. package/dist/mcp-session-binding.js +20 -0
  21. package/dist/mcp-session-binding.js.map +1 -1
  22. package/package.json +2 -2
  23. package/dist/execution-authority/bearer.d.ts +0 -15
  24. package/dist/execution-authority/bearer.d.ts.map +0 -1
  25. package/dist/execution-authority/bearer.js +0 -35
  26. package/dist/execution-authority/bearer.js.map +0 -1
  27. package/dist/execution-authority/index.d.ts +0 -6
  28. package/dist/execution-authority/index.d.ts.map +0 -1
  29. package/dist/execution-authority/index.js +0 -8
  30. package/dist/execution-authority/index.js.map +0 -1
  31. package/dist/execution-authority/ledger.d.ts +0 -85
  32. package/dist/execution-authority/ledger.d.ts.map +0 -1
  33. package/dist/execution-authority/ledger.js +0 -507
  34. package/dist/execution-authority/ledger.js.map +0 -1
  35. package/dist/execution-authority/store.d.ts +0 -55
  36. package/dist/execution-authority/store.d.ts.map +0 -1
  37. package/dist/execution-authority/store.js +0 -256
  38. package/dist/execution-authority/store.js.map +0 -1
  39. package/dist/execution-authority/types.d.ts +0 -119
  40. package/dist/execution-authority/types.d.ts.map +0 -1
  41. package/dist/execution-authority/types.js +0 -9
  42. package/dist/execution-authority/types.js.map +0 -1
  43. package/dist/lib/execution-authority-http.d.ts +0 -23
  44. package/dist/lib/execution-authority-http.d.ts.map +0 -1
  45. package/dist/lib/execution-authority-http.js +0 -101
  46. package/dist/lib/execution-authority-http.js.map +0 -1
  47. package/dist/mcp-stdio.d.ts +0 -2
  48. package/dist/mcp-stdio.d.ts.map +0 -1
  49. package/dist/mcp-stdio.js.map +0 -1
  50. package/dist/playbooks/playbook-parser.d.ts +0 -8
  51. package/dist/playbooks/playbook-parser.d.ts.map +0 -1
  52. package/dist/playbooks/playbook-parser.js +0 -76
  53. package/dist/playbooks/playbook-parser.js.map +0 -1
  54. package/dist/playbooks/playbook-service.d.ts +0 -9
  55. package/dist/playbooks/playbook-service.d.ts.map +0 -1
  56. package/dist/playbooks/playbook-service.js +0 -107
  57. package/dist/playbooks/playbook-service.js.map +0 -1
  58. package/dist/routes/execution-authority.d.ts +0 -8
  59. package/dist/routes/execution-authority.d.ts.map +0 -1
  60. package/dist/routes/execution-authority.js +0 -498
  61. package/dist/routes/execution-authority.js.map +0 -1
  62. package/dist/scope/bindings-sidecar.d.ts +0 -9
  63. package/dist/scope/bindings-sidecar.d.ts.map +0 -1
  64. package/dist/scope/bindings-sidecar.js +0 -57
  65. package/dist/scope/bindings-sidecar.js.map +0 -1
  66. package/dist/scope/repo-deck.d.ts +0 -10
  67. package/dist/scope/repo-deck.d.ts.map +0 -1
  68. package/dist/scope/repo-deck.js +0 -63
  69. package/dist/scope/repo-deck.js.map +0 -1
  70. package/dist/test-local-mcp-e2e.d.ts +0 -3
  71. package/dist/test-local-mcp-e2e.d.ts.map +0 -1
  72. package/dist/test-local-mcp-e2e.js +0 -104
  73. package/dist/test-local-mcp-e2e.js.map +0 -1
  74. 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) {
@@ -1437,8 +1513,13 @@ class AgentDeckMCPServer {
1437
1513
  readLaunchExecutionWorkspace(req) {
1438
1514
  return readWorkspaceRootHeader(req) ?? (process.env.AGENT_DECK_WORKSPACE?.trim() || undefined);
1439
1515
  }
1440
- async authenticateLaunchDeck(sessionId, req) {
1441
- const deckId = readLaunchDeckHeader(req);
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);
1442
1523
  if (!deckId) {
1443
1524
  throw new Error('GRANT_REQUIRED');
1444
1525
  }
@@ -1528,9 +1609,19 @@ class AgentDeckMCPServer {
1528
1609
  return true;
1529
1610
  }
1530
1611
  const launchDeck = readLaunchDeckHeader(req);
1531
- 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) {
1532
1623
  try {
1533
- await this.authenticateLaunchDeck(sessionId, req);
1624
+ await this.authenticateLaunchDeck(sessionId, req, launchDeck ?? this.sessionBinding.getBinding(sessionId).deckId);
1534
1625
  return true;
1535
1626
  }
1536
1627
  catch (error) {
@@ -1556,6 +1647,19 @@ class AgentDeckMCPServer {
1556
1647
  id: null,
1557
1648
  });
1558
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
+ }
1559
1663
  /**
1560
1664
  * NOT-318: initialize with a bearer grant. Authenticates before
1561
1665
  * advertising any `mcp-session-id`: failure answers the uniform 401
@@ -1603,42 +1707,143 @@ class AgentDeckMCPServer {
1603
1707
  });
1604
1708
  await this.establishTransportSession(req, res, sessionId);
1605
1709
  }
1606
- async handleMcpPost(req, res) {
1607
- const sessionIdHeader = this.getSessionIdHeader(req);
1608
- const existing = sessionIdHeader ? this.sessions.get(sessionIdHeader) : undefined;
1609
- const bearerRequired = isBearerGrantRequired();
1610
- if (existing && sessionIdHeader) {
1611
- // Grant-bound sessions revalidate the bearer on every request and
1612
- // never take the trust-the-header launch path: a forged deck header
1613
- // is denied by the grant allowlist, not trusted into a new deck.
1614
- if (this.sessionBinding.isGrantSession(sessionIdHeader)) {
1615
- if (!(await this.requireGrantFollowUp(sessionIdHeader, req, res))) {
1616
- return;
1617
- }
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;
1618
1724
  }
1619
- else {
1620
- // Hosted mode has no bearer-free sessions; a non-grant session id
1621
- // is unusable there — fail closed before touching the transport.
1622
- if (bearerRequired) {
1623
- this.sendGrantRequired(res);
1624
- 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;
1625
1778
  }
1626
- if (!(await this.requireFollowUpDeckHeader(sessionIdHeader, req, res))) {
1627
- 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
+ }
1628
1805
  }
1806
+ args[args.length - 1] = translated;
1629
1807
  }
1630
- // The auth above awaits, so re-check: a sweep may have expired the
1631
- // session while it ran, and answering on a dead transport would hang.
1632
- const live = this.sessions.get(sessionIdHeader);
1633
- if (!live) {
1634
- this.sendSessionNotFound(sessionIdHeader, res);
1635
- return;
1808
+ return originalWriteHead(...args);
1809
+ });
1810
+ try {
1811
+ return await serve();
1812
+ }
1813
+ finally {
1814
+ if (previousHeader === undefined) {
1815
+ delete req.headers[headerKey];
1636
1816
  }
1637
- this.noteClientActivity(sessionIdHeader, req);
1638
- this.touchLiveDisplay(sessionIdHeader);
1639
- await this.handleTransportPost(sessionIdHeader, req, res);
1817
+ else {
1818
+ req.headers[headerKey] = previousHeader;
1819
+ }
1820
+ if (Array.isArray(previousRawHeaders)) {
1821
+ req.rawHeaders = previousRawHeaders;
1822
+ }
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);
1640
1835
  return;
1641
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
+ }
1642
1847
  const body = req.body;
1643
1848
  const isInit = body &&
1644
1849
  typeof body === 'object' &&
@@ -1671,7 +1876,15 @@ class AgentDeckMCPServer {
1671
1876
  // A session id we don't know is a restart, not a malformed request — 404 so
1672
1877
  // the client re-initializes. An initialize carrying a stale id falls through
1673
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.
1674
1884
  if (sessionIdHeader) {
1885
+ if (await this.tryRecoverStaleSession(req, res, sessionIdHeader)) {
1886
+ return;
1887
+ }
1675
1888
  this.sendSessionNotFound(sessionIdHeader, res);
1676
1889
  return;
1677
1890
  }
@@ -1694,37 +1907,237 @@ class AgentDeckMCPServer {
1694
1907
  this.sendGrantRequired(res);
1695
1908
  return;
1696
1909
  }
1697
- 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);
1698
1915
  const skipDeckHeader = (0, mcp_unassigned_1.skipDeckHeaderAuth)();
1699
- const unassigned = !launchDeck && !skipDeckHeader;
1916
+ const unassigned = !effectiveDeck && !skipDeckHeader;
1700
1917
  // Authenticate before advertising mcp-session-id.
1701
1918
  const sessionId = (0, node_crypto_1.randomUUID)();
1702
- if (launchDeck) {
1919
+ if (effectiveDeck) {
1703
1920
  try {
1704
- await this.authenticateLaunchDeck(sessionId, req);
1921
+ await this.authenticateLaunchDeck(sessionId, req, effectiveDeck);
1922
+ if (manifestDeck && !launchDeck) {
1923
+ this.sessionBinding.markUseManifestSession(sessionId);
1924
+ }
1705
1925
  }
1706
1926
  catch (error) {
1707
- this.getAuditStore()?.append({
1708
- actor: 'local-launch',
1709
- event: 'deck.selection_denied',
1710
- targetId: (0, store_1.auditDeckTarget)(launchDeck),
1711
- outcome: 'denied',
1712
- reasonCode: 'resource_out_of_scope',
1713
- });
1714
- console.warn('[agent-deck] Launch-deck auth failed before MCP init:', error instanceof Error ? error.message : error);
1715
- this.sendLaunchDeckInvalid(res, error instanceof Error ? error.message : 'LAUNCH_DECK_INVALID');
1716
- 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
+ }
1717
1950
  }
1718
1951
  }
1719
1952
  else if (unassigned) {
1720
1953
  this.sessionBinding.markUnassigned(sessionId);
1721
- const workspaceRoot = readWorkspaceRootHeader(req);
1722
1954
  if (workspaceRoot) {
1723
1955
  this.sessionBinding.setWorkspace(sessionId, workspaceRoot);
1724
1956
  }
1725
1957
  }
1726
1958
  await this.establishTransportSession(req, res, sessionId);
1727
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
+ }
1728
2141
  /**
1729
2142
  * Shared transport handshake tail: create the per-session MCP server,
1730
2143
  * connect the streamable transport, and register the live session. Runs
@@ -1790,7 +2203,7 @@ class AgentDeckMCPServer {
1790
2203
  }
1791
2204
  }
1792
2205
  async handleMcpSessionRequest(req, res) {
1793
- const sessionId = this.getSessionIdHeader(req);
2206
+ const sessionIdHeader = this.getSessionIdHeader(req);
1794
2207
  const bearerRequired = isBearerGrantRequired();
1795
2208
  // Hosted endpoints run the Bearer [REDACTED] before session existence
1796
2209
  // (same no-oracle order as POST): 401 before any 404 metadata.
@@ -1798,13 +2211,31 @@ class AgentDeckMCPServer {
1798
2211
  this.sendGrantRequired(res);
1799
2212
  return;
1800
2213
  }
1801
- if (!sessionId) {
2214
+ if (!sessionIdHeader) {
1802
2215
  res.status(400).send('Invalid or missing session ID');
1803
2216
  return;
1804
2217
  }
1805
- const session = this.sessions.get(sessionId);
1806
- if (!session) {
1807
- 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);
1808
2239
  return;
1809
2240
  }
1810
2241
  if (this.sessionBinding.isGrantSession(sessionId)) {
@@ -1840,7 +2271,12 @@ class AgentDeckMCPServer {
1840
2271
  return;
1841
2272
  }
1842
2273
  this.touchLiveDisplay(sessionId);
1843
- 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
+ }
1844
2280
  }
1845
2281
  async start() {
1846
2282
  if (this.httpServer) {