@immediately-run/sdk 0.73.0 → 0.74.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 (67) hide show
  1. package/dist/dnd.cjs +2 -5
  2. package/dist/dnd.cjs.map +1 -1
  3. package/dist/dnd.d.cts +8 -1
  4. package/dist/dnd.d.ts +8 -1
  5. package/dist/dnd.js +2 -5
  6. package/dist/dnd.js.map +1 -1
  7. package/dist/editor.cjs +2 -5
  8. package/dist/editor.cjs.map +1 -1
  9. package/dist/editor.d.cts +34 -5
  10. package/dist/editor.d.ts +34 -5
  11. package/dist/editor.js +2 -5
  12. package/dist/editor.js.map +1 -1
  13. package/dist/generated/spaces.cjs +40 -0
  14. package/dist/generated/spaces.cjs.map +1 -1
  15. package/dist/generated/spaces.d.cts +96 -1
  16. package/dist/generated/spaces.d.ts +96 -1
  17. package/dist/generated/spaces.js +35 -0
  18. package/dist/generated/spaces.js.map +1 -1
  19. package/dist/index.d.cts +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/ipc.cjs +3 -10
  22. package/dist/ipc.cjs.map +1 -1
  23. package/dist/ipc.js +3 -10
  24. package/dist/ipc.js.map +1 -1
  25. package/dist/llm.cjs.map +1 -1
  26. package/dist/llm.d.cts +14 -0
  27. package/dist/llm.d.ts +14 -0
  28. package/dist/llm.js.map +1 -1
  29. package/dist/mounts.cjs +12 -10
  30. package/dist/mounts.cjs.map +1 -1
  31. package/dist/mounts.d.cts +9 -2
  32. package/dist/mounts.d.ts +9 -2
  33. package/dist/mounts.js +13 -11
  34. package/dist/mounts.js.map +1 -1
  35. package/dist/openExternal.cjs.map +1 -1
  36. package/dist/openExternal.d.cts +7 -7
  37. package/dist/openExternal.d.ts +7 -7
  38. package/dist/openExternal.js.map +1 -1
  39. package/dist/openRepository.cjs.map +1 -1
  40. package/dist/openRepository.d.cts +7 -7
  41. package/dist/openRepository.d.ts +7 -7
  42. package/dist/openRepository.js.map +1 -1
  43. package/dist/protocolRefusal.cjs.map +1 -1
  44. package/dist/protocolRefusal.d.cts +29 -5
  45. package/dist/protocolRefusal.d.ts +29 -5
  46. package/dist/protocolRefusal.js.map +1 -1
  47. package/dist/secrets.cjs.map +1 -1
  48. package/dist/secrets.d.cts +8 -1
  49. package/dist/secrets.d.ts +8 -1
  50. package/dist/secrets.js.map +1 -1
  51. package/dist/spacesMode.cjs.map +1 -1
  52. package/dist/spacesMode.d.cts +7 -1
  53. package/dist/spacesMode.d.ts +7 -1
  54. package/dist/spacesMode.js.map +1 -1
  55. package/dist/vcs.cjs +2 -5
  56. package/dist/vcs.cjs.map +1 -1
  57. package/dist/vcs.d.cts +8 -1
  58. package/dist/vcs.d.ts +8 -1
  59. package/dist/vcs.js +2 -5
  60. package/dist/vcs.js.map +1 -1
  61. package/dist/version.cjs +1 -1
  62. package/dist/version.cjs.map +1 -1
  63. package/dist/version.d.cts +1 -1
  64. package/dist/version.d.ts +1 -1
  65. package/dist/version.js +1 -1
  66. package/dist/version.js.map +1 -1
  67. package/package.json +4 -3
@@ -7,7 +7,13 @@
7
7
  * - `declined` — the host showed the confirmation and the user did not confirm.
8
8
  * - `forbidden` — the app does not hold the baseline `link:open` capability.
9
9
  * - `unsupported` — this host has no outward-link surface wired (an older host).
10
- * - `unknown` — the host refused without naming a code. */
10
+ * - `unknown` — the host refused without naming a code.
11
+ *
12
+ * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
13
+ * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the
14
+ * `.code` VALUES the host sends; the union was always a cast and is not enforced at
15
+ * runtime, so treat an unlisted code as possible and `instanceof Error` as the only
16
+ * reliable test. */
11
17
  type OpenExternalErrorCode = 'invalid' | 'no-activation' | 'declined' | 'forbidden' | 'unsupported' | 'unknown';
12
18
  interface OpenExternalError extends Error {
13
19
  code: OpenExternalErrorCode;
@@ -19,12 +25,6 @@ interface OpenExternalError extends Error {
19
25
  * the opened tab loading. Rejects with a typed {@link OpenExternalError} carrying `code` when
20
26
  * the host refuses.
21
27
  *
22
- * **Known gap, 2026-09-25 (R3-778): this does NOT reject today.** The host handler
23
- * RETURNS its refusals — `invalid`, `no-activation` and **`declined`** (the user pressing "no" on the host's confirmation) — and site-main's dispatcher wraps a
24
- * handler's return value in an `ok: true` envelope, so every one of those refusals
25
- * reaches this function as a SUCCESS and `openExternal()` resolves. Do not rely on the
26
- * `code` branch until R3-778 lands; see `protocolRefusal.ts` for the mechanism.
27
- *
28
28
  * Call it directly from a user gesture. The host samples its own transient activation when
29
29
  * the request arrives, so anything that defers the call past the gesture (an `await` before
30
30
  * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
@@ -7,7 +7,13 @@
7
7
  * - `declined` — the host showed the confirmation and the user did not confirm.
8
8
  * - `forbidden` — the app does not hold the baseline `link:open` capability.
9
9
  * - `unsupported` — this host has no outward-link surface wired (an older host).
10
- * - `unknown` — the host refused without naming a code. */
10
+ * - `unknown` — the host refused without naming a code.
11
+ *
12
+ * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
13
+ * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the
14
+ * `.code` VALUES the host sends; the union was always a cast and is not enforced at
15
+ * runtime, so treat an unlisted code as possible and `instanceof Error` as the only
16
+ * reliable test. */
11
17
  type OpenExternalErrorCode = 'invalid' | 'no-activation' | 'declined' | 'forbidden' | 'unsupported' | 'unknown';
12
18
  interface OpenExternalError extends Error {
13
19
  code: OpenExternalErrorCode;
@@ -19,12 +25,6 @@ interface OpenExternalError extends Error {
19
25
  * the opened tab loading. Rejects with a typed {@link OpenExternalError} carrying `code` when
20
26
  * the host refuses.
21
27
  *
22
- * **Known gap, 2026-09-25 (R3-778): this does NOT reject today.** The host handler
23
- * RETURNS its refusals — `invalid`, `no-activation` and **`declined`** (the user pressing "no" on the host's confirmation) — and site-main's dispatcher wraps a
24
- * handler's return value in an `ok: true` envelope, so every one of those refusals
25
- * reaches this function as a SUCCESS and `openExternal()` resolves. Do not rely on the
26
- * `code` branch until R3-778 lands; see `protocolRefusal.ts` for the mechanism.
27
- *
28
28
  * Call it directly from a user gesture. The host samples its own transient activation when
29
29
  * the request arrives, so anything that defers the call past the gesture (an `await` before
30
30
  * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/openExternal.ts"],"sourcesContent":["// Host-mediated \"open this external link in a new tab\" (R3-619).\n//\n// An app frame cannot open an ordinary top-level tab itself for a destination that has to\n// act as itself: a `window.open` or `<a target=\"_blank\">` from inside the sandboxed frame\n// inherits the sandbox (`allow-popups` without `allow-popups-to-escape-sandbox`), so the\n// opened tab runs at the same opaque origin and anything that signs in or posts fails.\n//\n// Unlike `openRepository`, the app here names a URL, not coordinates — the destination is\n// arbitrary, not a platform route. So the host validates the URL and confirms every call\n// (the full destination in its own chrome, opened only on the user's click). The app never\n// receives a `Window` handle; it asks, and the host decides whether and how to open.\n//\n// The same two host-side conditions as `openRepository` hold, and neither is something this\n// call can assert for itself: the confirmation needs the HOST document's live transient\n// user activation (a real click, which the host samples rather than believes), and the\n// confirmation must not consume that activation before the open. Both surface here as\n// ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENLINK } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Why the host refused to open the link.\n *\n * - `invalid` — the URL is not a clean `https:` external destination (scheme, credentials,\n * length, or the host's own origin).\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this.\n * - `declined` — the host showed the confirmation and the user did not confirm.\n * - `forbidden` — the app does not hold the baseline `link:open` capability.\n * - `unsupported` — this host has no outward-link surface wired (an older host).\n * - `unknown` — the host refused without naming a code. */\nexport type OpenExternalErrorCode = 'invalid' | 'no-activation' | 'declined' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenExternalError extends Error {\n code: OpenExternalErrorCode;\n}\n\n/** The host's reply: the envelope resolves inside the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenExternalReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open an external link in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenExternalError} carrying `code` when\n * the host refuses.\n *\n * **Known gap, 2026-09-25 (R3-778): this does NOT reject today.** The host handler\n * RETURNS its refusals — `invalid`, `no-activation` and **`declined`** (the user pressing \"no\" on the host's confirmation) — and site-main's dispatcher wraps a\n * handler's return value in an `ok: true` envelope, so every one of those refusals\n * reaches this function as a SUCCESS and `openExternal()` resolves. Do not rely on the\n * `code` branch until R3-778 lands; see `protocolRefusal.ts` for the mechanism.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openExternal(url: string): Promise<void> {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENLINK], 'open', [{ url }])) as OpenExternalReply;\n throwOnRefusal(res, 'external link open refused');\n}\n"],"mappings":";AAiBA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,eAAe;AAwCxB,eAAsB,aAAa,KAA4B;AAC7D,QAAM,MAAO,MAAM,gBAAgB,QAAQ,iBAAiB,GAAG,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC;AAChF,iBAAe,KAAK,4BAA4B;AAClD;","names":[]}
1
+ {"version":3,"sources":["../src/openExternal.ts"],"sourcesContent":["// Host-mediated \"open this external link in a new tab\" (R3-619).\n//\n// An app frame cannot open an ordinary top-level tab itself for a destination that has to\n// act as itself: a `window.open` or `<a target=\"_blank\">` from inside the sandboxed frame\n// inherits the sandbox (`allow-popups` without `allow-popups-to-escape-sandbox`), so the\n// opened tab runs at the same opaque origin and anything that signs in or posts fails.\n//\n// Unlike `openRepository`, the app here names a URL, not coordinates — the destination is\n// arbitrary, not a platform route. So the host validates the URL and confirms every call\n// (the full destination in its own chrome, opened only on the user's click). The app never\n// receives a `Window` handle; it asks, and the host decides whether and how to open.\n//\n// The same two host-side conditions as `openRepository` hold, and neither is something this\n// call can assert for itself: the confirmation needs the HOST document's live transient\n// user activation (a real click, which the host samples rather than believes), and the\n// confirmation must not consume that activation before the open. Both surface here as\n// ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENLINK } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Why the host refused to open the link.\n *\n * - `invalid` — the URL is not a clean `https:` external destination (scheme, credentials,\n * length, or the host's own origin).\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this.\n * - `declined` — the host showed the confirmation and the user did not confirm.\n * - `forbidden` — the app does not hold the baseline `link:open` capability.\n * - `unsupported` — this host has no outward-link surface wired (an older host).\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends; the union was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test. */\nexport type OpenExternalErrorCode = 'invalid' | 'no-activation' | 'declined' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenExternalError extends Error {\n code: OpenExternalErrorCode;\n}\n\n/** The host's reply: the envelope resolves inside the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenExternalReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open an external link in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenExternalError} carrying `code` when\n * the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openExternal(url: string): Promise<void> {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENLINK], 'open', [{ url }])) as OpenExternalReply;\n throwOnRefusal(res, 'external link open refused');\n}\n"],"mappings":";AAiBA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,eAAe;AAwCxB,eAAsB,aAAa,KAA4B;AAC7D,QAAM,MAAO,MAAM,gBAAgB,QAAQ,iBAAiB,GAAG,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC;AAChF,iBAAe,KAAK,4BAA4B;AAClD;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code. */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * **Known gap, 2026-09-25 (R3-778): this does NOT reject today.** The host handler\n * RETURNS its refusals — `invalid` and `no-activation` — and site-main's dispatcher wraps a\n * handler's return value in an `ok: true` envelope, so every one of those refusals\n * reaches this function as a SUCCESS and `openRepository()` resolves. Do not rely on the\n * `code` branch until R3-778 lands; see `protocolRefusal.ts` for the mechanism.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [\n { provider, namespace, repository },\n ])) as OpenRepositoryReply;\n throwOnRefusal(res, 'repository open refused');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,0BAAgC;AAChC,6BAA+B;AAC/B,sBAAkC;AAClC,6BAAwB;AAgDxB,eAAsB,eAAe,aAAmD;AACtF,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAC5C,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,iCAAiB,GAAG,QAAQ;AAAA,IACrE,EAAE,UAAU,WAAW,WAAW;AAAA,EACpC,CAAC;AACD,6CAAe,KAAK,yBAAyB;AAC/C;","names":[]}
1
+ {"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends; the union was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test. */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [\n { provider, namespace, repository },\n ])) as OpenRepositoryReply;\n throwOnRefusal(res, 'repository open refused');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,0BAAgC;AAChC,6BAA+B;AAC/B,sBAAkC;AAClC,6BAAwB;AAgDxB,eAAsB,eAAe,aAAmD;AACtF,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAC5C,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,iCAAiB,GAAG,QAAQ;AAAA,IACrE,EAAE,UAAU,WAAW,WAAW;AAAA,EACpC,CAAC;AACD,6CAAe,KAAK,yBAAyB;AAC/C;","names":[]}
@@ -14,7 +14,13 @@ interface RepositoryCoordinates {
14
14
  * buys exactly one tab and the next needs a real second click.
15
15
  * - `forbidden` — the app does not hold the baseline `route:read` capability.
16
16
  * - `unsupported` — this host has no repository-open surface wired.
17
- * - `unknown` — the host refused without naming a code. */
17
+ * - `unknown` — the host refused without naming a code.
18
+ *
19
+ * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
20
+ * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the
21
+ * `.code` VALUES the host sends; the union was always a cast and is not enforced at
22
+ * runtime, so treat an unlisted code as possible and `instanceof Error` as the only
23
+ * reliable test. */
18
24
  type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';
19
25
  interface OpenRepositoryError extends Error {
20
26
  code: OpenRepositoryErrorCode;
@@ -26,12 +32,6 @@ interface OpenRepositoryError extends Error {
26
32
  * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`
27
33
  * when the host refuses.
28
34
  *
29
- * **Known gap, 2026-09-25 (R3-778): this does NOT reject today.** The host handler
30
- * RETURNS its refusals — `invalid` and `no-activation` — and site-main's dispatcher wraps a
31
- * handler's return value in an `ok: true` envelope, so every one of those refusals
32
- * reaches this function as a SUCCESS and `openRepository()` resolves. Do not rely on the
33
- * `code` branch until R3-778 lands; see `protocolRefusal.ts` for the mechanism.
34
- *
35
35
  * Call it directly from a user gesture. The host samples its own transient activation when
36
36
  * the request arrives, so anything that defers the call past the gesture (an `await` before
37
37
  * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
@@ -14,7 +14,13 @@ interface RepositoryCoordinates {
14
14
  * buys exactly one tab and the next needs a real second click.
15
15
  * - `forbidden` — the app does not hold the baseline `route:read` capability.
16
16
  * - `unsupported` — this host has no repository-open surface wired.
17
- * - `unknown` — the host refused without naming a code. */
17
+ * - `unknown` — the host refused without naming a code.
18
+ *
19
+ * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
20
+ * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the
21
+ * `.code` VALUES the host sends; the union was always a cast and is not enforced at
22
+ * runtime, so treat an unlisted code as possible and `instanceof Error` as the only
23
+ * reliable test. */
18
24
  type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';
19
25
  interface OpenRepositoryError extends Error {
20
26
  code: OpenRepositoryErrorCode;
@@ -26,12 +32,6 @@ interface OpenRepositoryError extends Error {
26
32
  * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`
27
33
  * when the host refuses.
28
34
  *
29
- * **Known gap, 2026-09-25 (R3-778): this does NOT reject today.** The host handler
30
- * RETURNS its refusals — `invalid` and `no-activation` — and site-main's dispatcher wraps a
31
- * handler's return value in an `ok: true` envelope, so every one of those refusals
32
- * reaches this function as a SUCCESS and `openRepository()` resolves. Do not rely on the
33
- * `code` branch until R3-778 lands; see `protocolRefusal.ts` for the mechanism.
34
- *
35
35
  * Call it directly from a user gesture. The host samples its own transient activation when
36
36
  * the request arrives, so anything that defers the call past the gesture (an `await` before
37
37
  * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code. */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * **Known gap, 2026-09-25 (R3-778): this does NOT reject today.** The host handler\n * RETURNS its refusals — `invalid` and `no-activation` — and site-main's dispatcher wraps a\n * handler's return value in an `ok: true` envelope, so every one of those refusals\n * reaches this function as a SUCCESS and `openRepository()` resolves. Do not rely on the\n * `code` branch until R3-778 lands; see `protocolRefusal.ts` for the mechanism.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [\n { provider, namespace, repository },\n ])) as OpenRepositoryReply;\n throwOnRefusal(res, 'repository open refused');\n}\n"],"mappings":";AAgBA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,eAAe;AAgDxB,eAAsB,eAAe,aAAmD;AACtF,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAC5C,QAAM,MAAO,MAAM,gBAAgB,QAAQ,iBAAiB,GAAG,QAAQ;AAAA,IACrE,EAAE,UAAU,WAAW,WAAW;AAAA,EACpC,CAAC;AACD,iBAAe,KAAK,yBAAyB;AAC/C;","names":[]}
1
+ {"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends; the union was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test. */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [\n { provider, namespace, repository },\n ])) as OpenRepositoryReply;\n throwOnRefusal(res, 'repository open refused');\n}\n"],"mappings":";AAgBA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,eAAe;AAgDxB,eAAsB,eAAe,aAAmD;AACtF,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAC5C,QAAM,MAAO,MAAM,gBAAgB,QAAQ,iBAAiB,GAAG,QAAQ;AAAA,IACrE,EAAE,UAAU,WAAW,WAAW;AAAA,EACpC,CAAC;AACD,iBAAe,KAAK,yBAAyB;AAC/C;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — counted wrong twice, so here is how to re-derive it\n// ---------------------------------------------------------------------------\n//\n// Review round 1 found three copies of this block and this file said \"three\". Round 2\n// found five. Round 3 counted the grep and found the TYPED family is **ten**, across\n// eight files — `mounts.ts` alone has three separate request helpers, each with its own\n// copy, which round 2 read as one helper reached from three call sites.\n//\n// This PR folds the five that its own review rounds actually looked at:\n//\n// openExternal.ts · openRepository.ts · spacesMode.ts · secrets.ts · mounts.ts `request`\n//\n// The other five — `mounts.ts`'s `settingsRequest` and `localStoreRequest`, `editor.ts`,\n// `vcs.ts`, `dnd.ts` and `ipc.ts` (two sites) — were folded here too and then SPLIT BACK\n// OUT, because the gate caps at three rounds and they landed after the last one; nothing\n// had reviewed them. They go in their own PR. If you are reading this and that PR has\n// merged, this paragraph is the thing to delete.\n//\n// Not folded at all, deliberately: the UNTYPED family — `catalog.ts`, `feed.ts`,\n// `netFetch.ts`, `recents.ts`, `tasks.ts`, `theme.ts` (three sites) and `launch.ts`. They\n// are not alike: `launch.ts` folds an extra `!res.data?.launchId` into the same condition,\n// and the rest build their errors differently. Folding them is a behaviour change, not an\n// extraction.\n//\n// **Do not trust any list above; re-derive it.** `grep -n 'ok !== true' src/ | grep -v\n// '\\.test\\.'` is the whole population, and both miscounts came from reading files instead\n// of counting the grep. `check:clones` cannot help: minLines 6, minTokens 50, and no\n// identifier normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers do this today (site-main; audited round 2):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reports that to the app as a successful open. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That is a live defect in site-main's handlers, not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. The five call sites this replaced\n * tested for PRESENCE (`'code' in res`, `res?.message ?? …`), so a host sending\n * `code: 42` surfaced `err.code === 42` on a field the type declares `string`, and\n * `message: 42` became the string `\"42\"`. Both now fall back. That is a deliberate\n * tightening, pinned by tests, not an accident of the rewrite.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAmGO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
1
+ {"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. The count is:\n//\n// **twelve CALL SITES across nine FILES** — `grep -n 'throwOnRefusal(' src/*.ts`, minus\n// the declaration here and minus `*.test.*`:\n//\n// dnd.ts · editor.ts · ipc.ts (×2) · mounts.ts (×3) · openExternal.ts ·\n// openRepository.ts · secrets.ts · spacesMode.ts · vcs.ts\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// Not folded, deliberately, and the reason is NOT that they are all unalike — that was the\n// previous excuse and it was false for three of them:\n//\n// · `catalog.ts`, `recents.ts`, `tasks.ts` are pure copies of the shape `ipc.ts` had\n// until R3-780 folded it — untyped `Error & { code?: string }`, `res?.code ??\n// 'unknown'`. (`recents.ts` casts `code` as required rather than optional; immaterial,\n// the cast erases.) They are foldable and nothing here argues otherwise;\n// · `feed.ts`, `netFetch.ts` and `theme.ts` (×3) read `res && 'code' in res`, which\n// THROWS `TypeError: Cannot use 'in' operator` on a string reply. Folding them fixes\n// that, so it is a behaviour change — an improvement, but not an extraction. Note the\n// precedent cuts both ways: R3-708 already folded two sites carrying this exact form\n// (`openExternal`, `openRepository`), so \"behaviour change\" is a reason to review them\n// as their own item, not a reason they cannot be folded;\n// · `launch.ts` folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// So the remaining work is two items, not one, and they are not the same size.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL TWELVE SITES\n// ---------------------------------------------------------------------------\n//\n// Measured: changing the guard to `r.ok !== false` compiles clean and leaves **ten of the\n// twelve SITES** green — seven of the nine files: `dnd`, `editor`, `ipc`, `mounts`,\n// `secrets`, `spacesMode` and `vcs`. Every one of them stubs an explicit `{ ok: false }`,\n// so they pin \"throws on a refusal envelope\" and nothing about a malformed or absent\n// reply. Only `openExternal` and `openRepository` — two sites — plus\n// `protocolRefusal.test.ts` catch it: 7 tests across 3 suites.\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and twelve near-duplicate malformed\n// -reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Twelve sites call this; **eleven** had\n * an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708 and\n * replaced nothing). All eleven tested for PRESENCE, in **three** shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **two** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as\n * Code) ?? 'unknown'` — `openExternal`, `openRepository`, both folded in R3-708;\n * - **two** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc.ts`.\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply. Two revisions of this paragraph got that backwards — first\n * claiming the `in` form was among the shapes replaced without saying which sites, then\n * \"correcting\" that to say NO replaced site used it. It was two of them. Both errors came\n * from reading `main`, where R3-708 had already erased the form, instead of the tree before\n * it (`d4b07cc1^`).\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAyJO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
@@ -9,11 +9,35 @@ interface CodedRefusalError<C extends string = string> extends Error {
9
9
  * the code when it refused without one — a refusal is never reported as a success just
10
10
  * because it arrived under-specified.
11
11
  *
12
- * `code` and `message` must be STRINGS to be used. The five call sites this replaced
13
- * tested for PRESENCE (`'code' in res`, `res?.message ?? …`), so a host sending
14
- * `code: 42` surfaced `err.code === 42` on a field the type declares `string`, and
15
- * `message: 42` became the string `"42"`. Both now fall back. That is a deliberate
16
- * tightening, pinned by tests, not an accident of the rewrite.
12
+ * `code` and `message` must be STRINGS to be used. Twelve sites call this; **eleven** had
13
+ * an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708 and
14
+ * replaced nothing). All eleven tested for PRESENCE, in **three** shapes:
15
+ *
16
+ * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —
17
+ * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;
18
+ * - **two** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as
19
+ * Code) ?? 'unknown'` — `openExternal`, `openRepository`, both folded in R3-708;
20
+ * - **two** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —
21
+ * `ipc.ts`.
22
+ *
23
+ * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field
24
+ * declared `string`, and turned `message: 42` into the string `"42"`. Both now fall back,
25
+ * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by
26
+ * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is
27
+ * where a consumer learns of it.
28
+ *
29
+ * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL
30
+ * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old
31
+ * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back
32
+ * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`
33
+ * can stop.
34
+ *
35
+ * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`
36
+ * throws on a string reply. Two revisions of this paragraph got that backwards — first
37
+ * claiming the `in` form was among the shapes replaced without saying which sites, then
38
+ * "correcting" that to say NO replaced site used it. It was two of them. Both errors came
39
+ * from reading `main`, where R3-708 had already erased the form, instead of the tree before
40
+ * it (`d4b07cc1^`).
17
41
  *
18
42
  * It is an ASSERTION function, not a `void` one, because the inline form it replaced
19
43
  * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read
@@ -9,11 +9,35 @@ interface CodedRefusalError<C extends string = string> extends Error {
9
9
  * the code when it refused without one — a refusal is never reported as a success just
10
10
  * because it arrived under-specified.
11
11
  *
12
- * `code` and `message` must be STRINGS to be used. The five call sites this replaced
13
- * tested for PRESENCE (`'code' in res`, `res?.message ?? …`), so a host sending
14
- * `code: 42` surfaced `err.code === 42` on a field the type declares `string`, and
15
- * `message: 42` became the string `"42"`. Both now fall back. That is a deliberate
16
- * tightening, pinned by tests, not an accident of the rewrite.
12
+ * `code` and `message` must be STRINGS to be used. Twelve sites call this; **eleven** had
13
+ * an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708 and
14
+ * replaced nothing). All eleven tested for PRESENCE, in **three** shapes:
15
+ *
16
+ * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —
17
+ * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;
18
+ * - **two** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as
19
+ * Code) ?? 'unknown'` — `openExternal`, `openRepository`, both folded in R3-708;
20
+ * - **two** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —
21
+ * `ipc.ts`.
22
+ *
23
+ * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field
24
+ * declared `string`, and turned `message: 42` into the string `"42"`. Both now fall back,
25
+ * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by
26
+ * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is
27
+ * where a consumer learns of it.
28
+ *
29
+ * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL
30
+ * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old
31
+ * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back
32
+ * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`
33
+ * can stop.
34
+ *
35
+ * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`
36
+ * throws on a string reply. Two revisions of this paragraph got that backwards — first
37
+ * claiming the `in` form was among the shapes replaced without saying which sites, then
38
+ * "correcting" that to say NO replaced site used it. It was two of them. Both errors came
39
+ * from reading `main`, where R3-708 had already erased the form, instead of the tree before
40
+ * it (`d4b07cc1^`).
17
41
  *
18
42
  * It is an ASSERTION function, not a `void` one, because the inline form it replaced
19
43
  * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — counted wrong twice, so here is how to re-derive it\n// ---------------------------------------------------------------------------\n//\n// Review round 1 found three copies of this block and this file said \"three\". Round 2\n// found five. Round 3 counted the grep and found the TYPED family is **ten**, across\n// eight files — `mounts.ts` alone has three separate request helpers, each with its own\n// copy, which round 2 read as one helper reached from three call sites.\n//\n// This PR folds the five that its own review rounds actually looked at:\n//\n// openExternal.ts · openRepository.ts · spacesMode.ts · secrets.ts · mounts.ts `request`\n//\n// The other five — `mounts.ts`'s `settingsRequest` and `localStoreRequest`, `editor.ts`,\n// `vcs.ts`, `dnd.ts` and `ipc.ts` (two sites) — were folded here too and then SPLIT BACK\n// OUT, because the gate caps at three rounds and they landed after the last one; nothing\n// had reviewed them. They go in their own PR. If you are reading this and that PR has\n// merged, this paragraph is the thing to delete.\n//\n// Not folded at all, deliberately: the UNTYPED family — `catalog.ts`, `feed.ts`,\n// `netFetch.ts`, `recents.ts`, `tasks.ts`, `theme.ts` (three sites) and `launch.ts`. They\n// are not alike: `launch.ts` folds an extra `!res.data?.launchId` into the same condition,\n// and the rest build their errors differently. Folding them is a behaviour change, not an\n// extraction.\n//\n// **Do not trust any list above; re-derive it.** `grep -n 'ok !== true' src/ | grep -v\n// '\\.test\\.'` is the whole population, and both miscounts came from reading files instead\n// of counting the grep. `check:clones` cannot help: minLines 6, minTokens 50, and no\n// identifier normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers do this today (site-main; audited round 2):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reports that to the app as a successful open. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That is a live defect in site-main's handlers, not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. The five call sites this replaced\n * tested for PRESENCE (`'code' in res`, `res?.message ?? …`), so a host sending\n * `code: 42` surfaced `err.code === 42` on a field the type declares `string`, and\n * `message: 42` became the string `\"42\"`. Both now fall back. That is a deliberate\n * tightening, pinned by tests, not an accident of the rewrite.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";AAmGO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
1
+ {"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. The count is:\n//\n// **twelve CALL SITES across nine FILES** — `grep -n 'throwOnRefusal(' src/*.ts`, minus\n// the declaration here and minus `*.test.*`:\n//\n// dnd.ts · editor.ts · ipc.ts (×2) · mounts.ts (×3) · openExternal.ts ·\n// openRepository.ts · secrets.ts · spacesMode.ts · vcs.ts\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// Not folded, deliberately, and the reason is NOT that they are all unalike — that was the\n// previous excuse and it was false for three of them:\n//\n// · `catalog.ts`, `recents.ts`, `tasks.ts` are pure copies of the shape `ipc.ts` had\n// until R3-780 folded it — untyped `Error & { code?: string }`, `res?.code ??\n// 'unknown'`. (`recents.ts` casts `code` as required rather than optional; immaterial,\n// the cast erases.) They are foldable and nothing here argues otherwise;\n// · `feed.ts`, `netFetch.ts` and `theme.ts` (×3) read `res && 'code' in res`, which\n// THROWS `TypeError: Cannot use 'in' operator` on a string reply. Folding them fixes\n// that, so it is a behaviour change — an improvement, but not an extraction. Note the\n// precedent cuts both ways: R3-708 already folded two sites carrying this exact form\n// (`openExternal`, `openRepository`), so \"behaviour change\" is a reason to review them\n// as their own item, not a reason they cannot be folded;\n// · `launch.ts` folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// So the remaining work is two items, not one, and they are not the same size.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL TWELVE SITES\n// ---------------------------------------------------------------------------\n//\n// Measured: changing the guard to `r.ok !== false` compiles clean and leaves **ten of the\n// twelve SITES** green — seven of the nine files: `dnd`, `editor`, `ipc`, `mounts`,\n// `secrets`, `spacesMode` and `vcs`. Every one of them stubs an explicit `{ ok: false }`,\n// so they pin \"throws on a refusal envelope\" and nothing about a malformed or absent\n// reply. Only `openExternal` and `openRepository` — two sites — plus\n// `protocolRefusal.test.ts` catch it: 7 tests across 3 suites.\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and twelve near-duplicate malformed\n// -reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Twelve sites call this; **eleven** had\n * an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708 and\n * replaced nothing). All eleven tested for PRESENCE, in **three** shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **two** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as\n * Code) ?? 'unknown'` — `openExternal`, `openRepository`, both folded in R3-708;\n * - **two** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc.ts`.\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply. Two revisions of this paragraph got that backwards — first\n * claiming the `in` form was among the shapes replaced without saying which sites, then\n * \"correcting\" that to say NO replaced site used it. It was two of them. Both errors came\n * from reading `main`, where R3-708 had already erased the form, instead of the tree before\n * it (`d4b07cc1^`).\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";AAyJO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/secrets.ts"],"sourcesContent":["// The host-owned secret store — app-facing surface (SECRETS_SPEC §4/§5).\n//\n// An app can ASK the user to store a secret (`requestAddSecret`), be GRANTED the\n// right to USE a specific secret (`requestSecret`, the powerbox flow), LIST\n// secret METADATA (`getSecrets`/`useSecrets`, never values), and REVOKE one\n// (`revokeSecret`). The secret VALUE never crosses this boundary: it is read\n// host-side, once, at the `net:fetch` injection point (SECRETS_SPEC §6). These\n// functions move only hints, metadata, and grant handles.\n//\n// Resolves LLM_AND_AGENTS_SPEC D2 — the host-mediated BYOK key store. Inert until\n// the host implements `protocol-secrets` + the `secrets-metadata` channel\n// (SECRETS_SPEC §3/§6 host work, roadmap P1.E); the contract is shipped here so\n// apps (e.g. the in-browser coding agent, P3-73) can be written against it.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { PROTOCOL_SECRETS, REQUEST_SECRETS_METADATA, SECRETS_METADATA } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The closed secret-type vocabulary (SECRETS_SPEC §2). `api-key` is always\n * origin-bound; `oauth-refresh` is reserved (no substitution in v1). */\nexport type SecretType = 'api-key' | 'bearer-token' | 'oauth-refresh';\n\n/**\n * The metadata-only projection of a stored secret (SECRETS_SPEC §2/§4) — exactly\n * what `secrets:list` and the powerbox return. **There is no `value` field by\n * design**: the plaintext is never part of any record an app receives.\n */\nexport interface SecretView {\n id: string;\n type: SecretType;\n family?: string;\n description: string;\n /** Required for `type:'api-key'` — the one https origin it may be sent to. */\n boundOrigin?: string;\n /** ISO-8601, or null if never used (drives the §8.15 90-day expiry). */\n lastUsedAt: string | null;\n}\n\n/** Hints for the host's \"add secret\" modal (SECRETS_SPEC §4 `secrets:add`). The\n * app supplies only hints; the user types the value into host chrome. */\nexport interface SecretHints {\n type?: SecretType;\n family?: string;\n /** Pre-fill the bound origin (e.g. `https://api.anthropic.com`). */\n suggestedOrigin?: string;\n description?: string;\n}\n\n/** What `requestSecret()` matches against in the powerbox picker (SECRETS_SPEC §5). */\nexport interface SecretQuery {\n type?: SecretType;\n family?: string;\n}\n\n/**\n * The result of a granted `requestSecret()` — a durable `(appKey, secretId)` use\n * grant plus the secret's metadata. **Never the value.** Hold onto nothing but\n * this; the host substitutes the value into matching `net:fetch` requests.\n */\nexport interface SecretGrant {\n /** Opaque handle for the minted `(appKey, secretId)` grant. */\n grantId: string;\n /** Metadata of the bound secret (no value). */\n secret: SecretView;\n}\n\n/** An error from a secret operation, carrying a machine-readable `code`. */\nexport interface SecretError extends Error {\n code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'invalid-params' | 'unknown';\n}\n\ntype SecretResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\n// Issue a `protocol-secrets` request, unwrapping the host's {ok,data} envelope\n// and throwing a typed SecretError on failure (mirrors mounts.ts `request`).\nconst request = async <T = unknown>(method: string, query: object = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SECRETS], method, [query])) as SecretResult;\n throwOnRefusal(res, 'secret request failed');\n return res.data as T;\n};\n\n/**\n * Ask the user to store a new secret (SECRETS_SPEC §4 `secrets:add`). Opens a\n * **host-drawn** modal (the value is typed into host chrome, never via the app);\n * resolves with the new secret's {@link SecretView} metadata, or rejects with a\n * {@link SecretError} (`cancelled` if the user dismisses the modal). Requires the\n * `secrets:add` capability.\n */\nexport const requestAddSecret = (hints: SecretHints = {}): Promise<SecretView> => request<SecretView>('add', hints);\n\n/**\n * Ask the user to bind one of their stored secrets to this app (SECRETS_SPEC §5,\n * the powerbox flow — modeled on `requestSpace()`). The host draws a picker of\n * **only the user's matching secrets**; the user picks, declines, or creates one.\n * On success the host records a durable `(appKey, secretId)` grant and resolves\n * with a {@link SecretGrant} (handle + metadata, **never the value**).\n *\n * **No existence oracle (T20/T27):** a decline, an ungranted secret, and a\n * nonexistent secret are indistinguishable — all reject with a {@link SecretError}\n * `cancelled`; the app never sees the list it chose from.\n */\nexport const requestSecret = (query: SecretQuery = {}): Promise<SecretGrant> => request<SecretGrant>('request', query);\n\n/**\n * Delete a stored secret and tombstone every dependent per-app use grant\n * (SECRETS_SPEC §4 `secrets:revoke`, §8.15 cascade). Requires `secrets:revoke`.\n */\nexport const revokeSecret = async (id: string): Promise<void> => {\n await request('revoke', { id });\n};\n\n// The metadata-only `secrets-metadata` channel (Recipe A): the host pushes the\n// current secret metadata on change and replays it on register-frame; gated by\n// `secrets:list`. NEVER carries a value (SECRETS_SPEC §4).\nconst channel = createPushChannel<SecretView[]>({\n pushType: SECRETS_METADATA,\n requestType: REQUEST_SECRETS_METADATA,\n initial: [],\n parse: (msg) => (Array.isArray(msg.secrets) ? (msg.secrets as SecretView[]) : undefined),\n});\n\n/** The metadata of the user's stored secrets (never values), `secrets:list`. Poll\n * for a one-off read; use {@link onSecretsChange}/{@link useSecrets} to react. */\nexport const getSecrets = (): SecretView[] => channel.get();\n\n/** Subscribe to secret-metadata changes (added/revoked). Invoked immediately with\n * the current list, then on every change. Returns an unsubscribe fn. */\nexport const onSecretsChange = (listener: (secrets: SecretView[]) => void): (() => void) => channel.onChange(listener);\n\n/** React hook returning the user's secret metadata (never values), re-rendering\n * on change. For the Settings app (SECRETS_SPEC §7). */\nexport const useSecrets = (): SecretView[] => channel.use();\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaA,0BAAgC;AAChC,6BAA+B;AAC/B,yBAAkC;AAClC,sBAA6E;AAC7E,6BAAwB;AA2DxB,MAAM,UAAU,OAAoB,QAAgB,QAAgB,CAAC,MAAkB;AACrF,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,gCAAgB,GAAG,QAAQ,CAAC,KAAK,CAAC;AAC7E,6CAAe,KAAK,uBAAuB;AAC3C,SAAO,IAAI;AACb;AASO,MAAM,mBAAmB,CAAC,QAAqB,CAAC,MAA2B,QAAoB,OAAO,KAAK;AAa3G,MAAM,gBAAgB,CAAC,QAAqB,CAAC,MAA4B,QAAqB,WAAW,KAAK;AAM9G,MAAM,eAAe,OAAO,OAA8B;AAC/D,QAAM,QAAQ,UAAU,EAAE,GAAG,CAAC;AAChC;AAKA,MAAM,cAAU,sCAAgC;AAAA,EAC9C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS,CAAC;AAAA,EACV,OAAO,CAAC,QAAS,MAAM,QAAQ,IAAI,OAAO,IAAK,IAAI,UAA2B;AAChF,CAAC;AAIM,MAAM,aAAa,MAAoB,QAAQ,IAAI;AAInD,MAAM,kBAAkB,CAAC,aAA4D,QAAQ,SAAS,QAAQ;AAI9G,MAAM,aAAa,MAAoB,QAAQ,IAAI;","names":[]}
1
+ {"version":3,"sources":["../src/secrets.ts"],"sourcesContent":["// The host-owned secret store — app-facing surface (SECRETS_SPEC §4/§5).\n//\n// An app can ASK the user to store a secret (`requestAddSecret`), be GRANTED the\n// right to USE a specific secret (`requestSecret`, the powerbox flow), LIST\n// secret METADATA (`getSecrets`/`useSecrets`, never values), and REVOKE one\n// (`revokeSecret`). The secret VALUE never crosses this boundary: it is read\n// host-side, once, at the `net:fetch` injection point (SECRETS_SPEC §6). These\n// functions move only hints, metadata, and grant handles.\n//\n// Resolves LLM_AND_AGENTS_SPEC D2 — the host-mediated BYOK key store. Inert until\n// the host implements `protocol-secrets` + the `secrets-metadata` channel\n// (SECRETS_SPEC §3/§6 host work, roadmap P1.E); the contract is shipped here so\n// apps (e.g. the in-browser coding agent, P3-73) can be written against it.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { PROTOCOL_SECRETS, REQUEST_SECRETS_METADATA, SECRETS_METADATA } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The closed secret-type vocabulary (SECRETS_SPEC §2). `api-key` is always\n * origin-bound; `oauth-refresh` is reserved (no substitution in v1). */\nexport type SecretType = 'api-key' | 'bearer-token' | 'oauth-refresh';\n\n/**\n * The metadata-only projection of a stored secret (SECRETS_SPEC §2/§4) — exactly\n * what `secrets:list` and the powerbox return. **There is no `value` field by\n * design**: the plaintext is never part of any record an app receives.\n */\nexport interface SecretView {\n id: string;\n type: SecretType;\n family?: string;\n description: string;\n /** Required for `type:'api-key'` — the one https origin it may be sent to. */\n boundOrigin?: string;\n /** ISO-8601, or null if never used (drives the §8.15 90-day expiry). */\n lastUsedAt: string | null;\n}\n\n/** Hints for the host's \"add secret\" modal (SECRETS_SPEC §4 `secrets:add`). The\n * app supplies only hints; the user types the value into host chrome. */\nexport interface SecretHints {\n type?: SecretType;\n family?: string;\n /** Pre-fill the bound origin (e.g. `https://api.anthropic.com`). */\n suggestedOrigin?: string;\n description?: string;\n}\n\n/** What `requestSecret()` matches against in the powerbox picker (SECRETS_SPEC §5). */\nexport interface SecretQuery {\n type?: SecretType;\n family?: string;\n}\n\n/**\n * The result of a granted `requestSecret()` — a durable `(appKey, secretId)` use\n * grant plus the secret's metadata. **Never the value.** Hold onto nothing but\n * this; the host substitutes the value into matching `net:fetch` requests.\n */\nexport interface SecretGrant {\n /** Opaque handle for the minted `(appKey, secretId)` grant. */\n grantId: string;\n /** Metadata of the bound secret (no value). */\n secret: SecretView;\n}\n\n/** An error from a secret operation, carrying a machine-readable `code`.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface\n * documents the `.code` VALUES the host sends; it was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test.\n */\nexport interface SecretError extends Error {\n code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'invalid-params' | 'unknown';\n}\n\ntype SecretResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\n// Issue a `protocol-secrets` request, unwrapping the host's {ok,data} envelope and\n// throwing a coded refusal on failure (mirrors mounts.ts `request`; a\n// `CodedRefusalError`, not a `SecretError` — see `protocolRefusal.ts`).\nconst request = async <T = unknown>(method: string, query: object = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SECRETS], method, [query])) as SecretResult;\n throwOnRefusal(res, 'secret request failed');\n return res.data as T;\n};\n\n/**\n * Ask the user to store a new secret (SECRETS_SPEC §4 `secrets:add`). Opens a\n * **host-drawn** modal (the value is typed into host chrome, never via the app);\n * resolves with the new secret's {@link SecretView} metadata, or rejects with a\n * {@link SecretError} (`cancelled` if the user dismisses the modal). Requires the\n * `secrets:add` capability.\n */\nexport const requestAddSecret = (hints: SecretHints = {}): Promise<SecretView> => request<SecretView>('add', hints);\n\n/**\n * Ask the user to bind one of their stored secrets to this app (SECRETS_SPEC §5,\n * the powerbox flow — modeled on `requestSpace()`). The host draws a picker of\n * **only the user's matching secrets**; the user picks, declines, or creates one.\n * On success the host records a durable `(appKey, secretId)` grant and resolves\n * with a {@link SecretGrant} (handle + metadata, **never the value**).\n *\n * **No existence oracle (T20/T27):** a decline, an ungranted secret, and a\n * nonexistent secret are indistinguishable — all reject with a {@link SecretError}\n * `cancelled`; the app never sees the list it chose from.\n */\nexport const requestSecret = (query: SecretQuery = {}): Promise<SecretGrant> => request<SecretGrant>('request', query);\n\n/**\n * Delete a stored secret and tombstone every dependent per-app use grant\n * (SECRETS_SPEC §4 `secrets:revoke`, §8.15 cascade). Requires `secrets:revoke`.\n */\nexport const revokeSecret = async (id: string): Promise<void> => {\n await request('revoke', { id });\n};\n\n// The metadata-only `secrets-metadata` channel (Recipe A): the host pushes the\n// current secret metadata on change and replays it on register-frame; gated by\n// `secrets:list`. NEVER carries a value (SECRETS_SPEC §4).\nconst channel = createPushChannel<SecretView[]>({\n pushType: SECRETS_METADATA,\n requestType: REQUEST_SECRETS_METADATA,\n initial: [],\n parse: (msg) => (Array.isArray(msg.secrets) ? (msg.secrets as SecretView[]) : undefined),\n});\n\n/** The metadata of the user's stored secrets (never values), `secrets:list`. Poll\n * for a one-off read; use {@link onSecretsChange}/{@link useSecrets} to react. */\nexport const getSecrets = (): SecretView[] => channel.get();\n\n/** Subscribe to secret-metadata changes (added/revoked). Invoked immediately with\n * the current list, then on every change. Returns an unsubscribe fn. */\nexport const onSecretsChange = (listener: (secrets: SecretView[]) => void): (() => void) => channel.onChange(listener);\n\n/** React hook returning the user's secret metadata (never values), re-rendering\n * on change. For the Settings app (SECRETS_SPEC §7). */\nexport const useSecrets = (): SecretView[] => channel.use();\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaA,0BAAgC;AAChC,6BAA+B;AAC/B,yBAAkC;AAClC,sBAA6E;AAC7E,6BAAwB;AAmExB,MAAM,UAAU,OAAoB,QAAgB,QAAgB,CAAC,MAAkB;AACrF,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,gCAAgB,GAAG,QAAQ,CAAC,KAAK,CAAC;AAC7E,6CAAe,KAAK,uBAAuB;AAC3C,SAAO,IAAI;AACb;AASO,MAAM,mBAAmB,CAAC,QAAqB,CAAC,MAA2B,QAAoB,OAAO,KAAK;AAa3G,MAAM,gBAAgB,CAAC,QAAqB,CAAC,MAA4B,QAAqB,WAAW,KAAK;AAM9G,MAAM,eAAe,OAAO,OAA8B;AAC/D,QAAM,QAAQ,UAAU,EAAE,GAAG,CAAC;AAChC;AAKA,MAAM,cAAU,sCAAgC;AAAA,EAC9C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS,CAAC;AAAA,EACV,OAAO,CAAC,QAAS,MAAM,QAAQ,IAAI,OAAO,IAAK,IAAI,UAA2B;AAChF,CAAC;AAIM,MAAM,aAAa,MAAoB,QAAQ,IAAI;AAInD,MAAM,kBAAkB,CAAC,aAA4D,QAAQ,SAAS,QAAQ;AAI9G,MAAM,aAAa,MAAoB,QAAQ,IAAI;","names":[]}
@@ -41,7 +41,14 @@ interface SecretGrant {
41
41
  /** Metadata of the bound secret (no value). */
42
42
  secret: SecretView;
43
43
  }
44
- /** An error from a secret operation, carrying a machine-readable `code`. */
44
+ /** An error from a secret operation, carrying a machine-readable `code`.
45
+ *
46
+ * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
47
+ * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface
48
+ * documents the `.code` VALUES the host sends; it was always a cast and is not enforced at
49
+ * runtime, so treat an unlisted code as possible and `instanceof Error` as the only
50
+ * reliable test.
51
+ */
45
52
  interface SecretError extends Error {
46
53
  code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'invalid-params' | 'unknown';
47
54
  }
package/dist/secrets.d.ts CHANGED
@@ -41,7 +41,14 @@ interface SecretGrant {
41
41
  /** Metadata of the bound secret (no value). */
42
42
  secret: SecretView;
43
43
  }
44
- /** An error from a secret operation, carrying a machine-readable `code`. */
44
+ /** An error from a secret operation, carrying a machine-readable `code`.
45
+ *
46
+ * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
47
+ * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface
48
+ * documents the `.code` VALUES the host sends; it was always a cast and is not enforced at
49
+ * runtime, so treat an unlisted code as possible and `instanceof Error` as the only
50
+ * reliable test.
51
+ */
45
52
  interface SecretError extends Error {
46
53
  code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'invalid-params' | 'unknown';
47
54
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/secrets.ts"],"sourcesContent":["// The host-owned secret store — app-facing surface (SECRETS_SPEC §4/§5).\n//\n// An app can ASK the user to store a secret (`requestAddSecret`), be GRANTED the\n// right to USE a specific secret (`requestSecret`, the powerbox flow), LIST\n// secret METADATA (`getSecrets`/`useSecrets`, never values), and REVOKE one\n// (`revokeSecret`). The secret VALUE never crosses this boundary: it is read\n// host-side, once, at the `net:fetch` injection point (SECRETS_SPEC §6). These\n// functions move only hints, metadata, and grant handles.\n//\n// Resolves LLM_AND_AGENTS_SPEC D2 — the host-mediated BYOK key store. Inert until\n// the host implements `protocol-secrets` + the `secrets-metadata` channel\n// (SECRETS_SPEC §3/§6 host work, roadmap P1.E); the contract is shipped here so\n// apps (e.g. the in-browser coding agent, P3-73) can be written against it.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { PROTOCOL_SECRETS, REQUEST_SECRETS_METADATA, SECRETS_METADATA } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The closed secret-type vocabulary (SECRETS_SPEC §2). `api-key` is always\n * origin-bound; `oauth-refresh` is reserved (no substitution in v1). */\nexport type SecretType = 'api-key' | 'bearer-token' | 'oauth-refresh';\n\n/**\n * The metadata-only projection of a stored secret (SECRETS_SPEC §2/§4) — exactly\n * what `secrets:list` and the powerbox return. **There is no `value` field by\n * design**: the plaintext is never part of any record an app receives.\n */\nexport interface SecretView {\n id: string;\n type: SecretType;\n family?: string;\n description: string;\n /** Required for `type:'api-key'` — the one https origin it may be sent to. */\n boundOrigin?: string;\n /** ISO-8601, or null if never used (drives the §8.15 90-day expiry). */\n lastUsedAt: string | null;\n}\n\n/** Hints for the host's \"add secret\" modal (SECRETS_SPEC §4 `secrets:add`). The\n * app supplies only hints; the user types the value into host chrome. */\nexport interface SecretHints {\n type?: SecretType;\n family?: string;\n /** Pre-fill the bound origin (e.g. `https://api.anthropic.com`). */\n suggestedOrigin?: string;\n description?: string;\n}\n\n/** What `requestSecret()` matches against in the powerbox picker (SECRETS_SPEC §5). */\nexport interface SecretQuery {\n type?: SecretType;\n family?: string;\n}\n\n/**\n * The result of a granted `requestSecret()` — a durable `(appKey, secretId)` use\n * grant plus the secret's metadata. **Never the value.** Hold onto nothing but\n * this; the host substitutes the value into matching `net:fetch` requests.\n */\nexport interface SecretGrant {\n /** Opaque handle for the minted `(appKey, secretId)` grant. */\n grantId: string;\n /** Metadata of the bound secret (no value). */\n secret: SecretView;\n}\n\n/** An error from a secret operation, carrying a machine-readable `code`. */\nexport interface SecretError extends Error {\n code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'invalid-params' | 'unknown';\n}\n\ntype SecretResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\n// Issue a `protocol-secrets` request, unwrapping the host's {ok,data} envelope\n// and throwing a typed SecretError on failure (mirrors mounts.ts `request`).\nconst request = async <T = unknown>(method: string, query: object = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SECRETS], method, [query])) as SecretResult;\n throwOnRefusal(res, 'secret request failed');\n return res.data as T;\n};\n\n/**\n * Ask the user to store a new secret (SECRETS_SPEC §4 `secrets:add`). Opens a\n * **host-drawn** modal (the value is typed into host chrome, never via the app);\n * resolves with the new secret's {@link SecretView} metadata, or rejects with a\n * {@link SecretError} (`cancelled` if the user dismisses the modal). Requires the\n * `secrets:add` capability.\n */\nexport const requestAddSecret = (hints: SecretHints = {}): Promise<SecretView> => request<SecretView>('add', hints);\n\n/**\n * Ask the user to bind one of their stored secrets to this app (SECRETS_SPEC §5,\n * the powerbox flow — modeled on `requestSpace()`). The host draws a picker of\n * **only the user's matching secrets**; the user picks, declines, or creates one.\n * On success the host records a durable `(appKey, secretId)` grant and resolves\n * with a {@link SecretGrant} (handle + metadata, **never the value**).\n *\n * **No existence oracle (T20/T27):** a decline, an ungranted secret, and a\n * nonexistent secret are indistinguishable — all reject with a {@link SecretError}\n * `cancelled`; the app never sees the list it chose from.\n */\nexport const requestSecret = (query: SecretQuery = {}): Promise<SecretGrant> => request<SecretGrant>('request', query);\n\n/**\n * Delete a stored secret and tombstone every dependent per-app use grant\n * (SECRETS_SPEC §4 `secrets:revoke`, §8.15 cascade). Requires `secrets:revoke`.\n */\nexport const revokeSecret = async (id: string): Promise<void> => {\n await request('revoke', { id });\n};\n\n// The metadata-only `secrets-metadata` channel (Recipe A): the host pushes the\n// current secret metadata on change and replays it on register-frame; gated by\n// `secrets:list`. NEVER carries a value (SECRETS_SPEC §4).\nconst channel = createPushChannel<SecretView[]>({\n pushType: SECRETS_METADATA,\n requestType: REQUEST_SECRETS_METADATA,\n initial: [],\n parse: (msg) => (Array.isArray(msg.secrets) ? (msg.secrets as SecretView[]) : undefined),\n});\n\n/** The metadata of the user's stored secrets (never values), `secrets:list`. Poll\n * for a one-off read; use {@link onSecretsChange}/{@link useSecrets} to react. */\nexport const getSecrets = (): SecretView[] => channel.get();\n\n/** Subscribe to secret-metadata changes (added/revoked). Invoked immediately with\n * the current list, then on every change. Returns an unsubscribe fn. */\nexport const onSecretsChange = (listener: (secrets: SecretView[]) => void): (() => void) => channel.onChange(listener);\n\n/** React hook returning the user's secret metadata (never values), re-rendering\n * on change. For the Settings app (SECRETS_SPEC §7). */\nexport const useSecrets = (): SecretView[] => channel.use();\n"],"mappings":";AAaA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,kBAAkB,0BAA0B,wBAAwB;AAC7E,SAAS,eAAe;AA2DxB,MAAM,UAAU,OAAoB,QAAgB,QAAgB,CAAC,MAAkB;AACrF,QAAM,MAAO,MAAM,gBAAgB,QAAQ,gBAAgB,GAAG,QAAQ,CAAC,KAAK,CAAC;AAC7E,iBAAe,KAAK,uBAAuB;AAC3C,SAAO,IAAI;AACb;AASO,MAAM,mBAAmB,CAAC,QAAqB,CAAC,MAA2B,QAAoB,OAAO,KAAK;AAa3G,MAAM,gBAAgB,CAAC,QAAqB,CAAC,MAA4B,QAAqB,WAAW,KAAK;AAM9G,MAAM,eAAe,OAAO,OAA8B;AAC/D,QAAM,QAAQ,UAAU,EAAE,GAAG,CAAC;AAChC;AAKA,MAAM,UAAU,kBAAgC;AAAA,EAC9C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS,CAAC;AAAA,EACV,OAAO,CAAC,QAAS,MAAM,QAAQ,IAAI,OAAO,IAAK,IAAI,UAA2B;AAChF,CAAC;AAIM,MAAM,aAAa,MAAoB,QAAQ,IAAI;AAInD,MAAM,kBAAkB,CAAC,aAA4D,QAAQ,SAAS,QAAQ;AAI9G,MAAM,aAAa,MAAoB,QAAQ,IAAI;","names":[]}
1
+ {"version":3,"sources":["../src/secrets.ts"],"sourcesContent":["// The host-owned secret store — app-facing surface (SECRETS_SPEC §4/§5).\n//\n// An app can ASK the user to store a secret (`requestAddSecret`), be GRANTED the\n// right to USE a specific secret (`requestSecret`, the powerbox flow), LIST\n// secret METADATA (`getSecrets`/`useSecrets`, never values), and REVOKE one\n// (`revokeSecret`). The secret VALUE never crosses this boundary: it is read\n// host-side, once, at the `net:fetch` injection point (SECRETS_SPEC §6). These\n// functions move only hints, metadata, and grant handles.\n//\n// Resolves LLM_AND_AGENTS_SPEC D2 — the host-mediated BYOK key store. Inert until\n// the host implements `protocol-secrets` + the `secrets-metadata` channel\n// (SECRETS_SPEC §3/§6 host work, roadmap P1.E); the contract is shipped here so\n// apps (e.g. the in-browser coding agent, P3-73) can be written against it.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { PROTOCOL_SECRETS, REQUEST_SECRETS_METADATA, SECRETS_METADATA } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The closed secret-type vocabulary (SECRETS_SPEC §2). `api-key` is always\n * origin-bound; `oauth-refresh` is reserved (no substitution in v1). */\nexport type SecretType = 'api-key' | 'bearer-token' | 'oauth-refresh';\n\n/**\n * The metadata-only projection of a stored secret (SECRETS_SPEC §2/§4) — exactly\n * what `secrets:list` and the powerbox return. **There is no `value` field by\n * design**: the plaintext is never part of any record an app receives.\n */\nexport interface SecretView {\n id: string;\n type: SecretType;\n family?: string;\n description: string;\n /** Required for `type:'api-key'` — the one https origin it may be sent to. */\n boundOrigin?: string;\n /** ISO-8601, or null if never used (drives the §8.15 90-day expiry). */\n lastUsedAt: string | null;\n}\n\n/** Hints for the host's \"add secret\" modal (SECRETS_SPEC §4 `secrets:add`). The\n * app supplies only hints; the user types the value into host chrome. */\nexport interface SecretHints {\n type?: SecretType;\n family?: string;\n /** Pre-fill the bound origin (e.g. `https://api.anthropic.com`). */\n suggestedOrigin?: string;\n description?: string;\n}\n\n/** What `requestSecret()` matches against in the powerbox picker (SECRETS_SPEC §5). */\nexport interface SecretQuery {\n type?: SecretType;\n family?: string;\n}\n\n/**\n * The result of a granted `requestSecret()` — a durable `(appKey, secretId)` use\n * grant plus the secret's metadata. **Never the value.** Hold onto nothing but\n * this; the host substitutes the value into matching `net:fetch` requests.\n */\nexport interface SecretGrant {\n /** Opaque handle for the minted `(appKey, secretId)` grant. */\n grantId: string;\n /** Metadata of the bound secret (no value). */\n secret: SecretView;\n}\n\n/** An error from a secret operation, carrying a machine-readable `code`.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface\n * documents the `.code` VALUES the host sends; it was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test.\n */\nexport interface SecretError extends Error {\n code: 'auth-required' | 'cancelled' | 'forbidden' | 'not-found' | 'invalid-params' | 'unknown';\n}\n\ntype SecretResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\n// Issue a `protocol-secrets` request, unwrapping the host's {ok,data} envelope and\n// throwing a coded refusal on failure (mirrors mounts.ts `request`; a\n// `CodedRefusalError`, not a `SecretError` — see `protocolRefusal.ts`).\nconst request = async <T = unknown>(method: string, query: object = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SECRETS], method, [query])) as SecretResult;\n throwOnRefusal(res, 'secret request failed');\n return res.data as T;\n};\n\n/**\n * Ask the user to store a new secret (SECRETS_SPEC §4 `secrets:add`). Opens a\n * **host-drawn** modal (the value is typed into host chrome, never via the app);\n * resolves with the new secret's {@link SecretView} metadata, or rejects with a\n * {@link SecretError} (`cancelled` if the user dismisses the modal). Requires the\n * `secrets:add` capability.\n */\nexport const requestAddSecret = (hints: SecretHints = {}): Promise<SecretView> => request<SecretView>('add', hints);\n\n/**\n * Ask the user to bind one of their stored secrets to this app (SECRETS_SPEC §5,\n * the powerbox flow — modeled on `requestSpace()`). The host draws a picker of\n * **only the user's matching secrets**; the user picks, declines, or creates one.\n * On success the host records a durable `(appKey, secretId)` grant and resolves\n * with a {@link SecretGrant} (handle + metadata, **never the value**).\n *\n * **No existence oracle (T20/T27):** a decline, an ungranted secret, and a\n * nonexistent secret are indistinguishable — all reject with a {@link SecretError}\n * `cancelled`; the app never sees the list it chose from.\n */\nexport const requestSecret = (query: SecretQuery = {}): Promise<SecretGrant> => request<SecretGrant>('request', query);\n\n/**\n * Delete a stored secret and tombstone every dependent per-app use grant\n * (SECRETS_SPEC §4 `secrets:revoke`, §8.15 cascade). Requires `secrets:revoke`.\n */\nexport const revokeSecret = async (id: string): Promise<void> => {\n await request('revoke', { id });\n};\n\n// The metadata-only `secrets-metadata` channel (Recipe A): the host pushes the\n// current secret metadata on change and replays it on register-frame; gated by\n// `secrets:list`. NEVER carries a value (SECRETS_SPEC §4).\nconst channel = createPushChannel<SecretView[]>({\n pushType: SECRETS_METADATA,\n requestType: REQUEST_SECRETS_METADATA,\n initial: [],\n parse: (msg) => (Array.isArray(msg.secrets) ? (msg.secrets as SecretView[]) : undefined),\n});\n\n/** The metadata of the user's stored secrets (never values), `secrets:list`. Poll\n * for a one-off read; use {@link onSecretsChange}/{@link useSecrets} to react. */\nexport const getSecrets = (): SecretView[] => channel.get();\n\n/** Subscribe to secret-metadata changes (added/revoked). Invoked immediately with\n * the current list, then on every change. Returns an unsubscribe fn. */\nexport const onSecretsChange = (listener: (secrets: SecretView[]) => void): (() => void) => channel.onChange(listener);\n\n/** React hook returning the user's secret metadata (never values), re-rendering\n * on change. For the Settings app (SECRETS_SPEC §7). */\nexport const useSecrets = (): SecretView[] => channel.use();\n"],"mappings":";AAaA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,kBAAkB,0BAA0B,wBAAwB;AAC7E,SAAS,eAAe;AAmExB,MAAM,UAAU,OAAoB,QAAgB,QAAgB,CAAC,MAAkB;AACrF,QAAM,MAAO,MAAM,gBAAgB,QAAQ,gBAAgB,GAAG,QAAQ,CAAC,KAAK,CAAC;AAC7E,iBAAe,KAAK,uBAAuB;AAC3C,SAAO,IAAI;AACb;AASO,MAAM,mBAAmB,CAAC,QAAqB,CAAC,MAA2B,QAAoB,OAAO,KAAK;AAa3G,MAAM,gBAAgB,CAAC,QAAqB,CAAC,MAA4B,QAAqB,WAAW,KAAK;AAM9G,MAAM,eAAe,OAAO,OAA8B;AAC/D,QAAM,QAAQ,UAAU,EAAE,GAAG,CAAC;AAChC;AAKA,MAAM,UAAU,kBAAgC;AAAA,EAC9C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS,CAAC;AAAA,EACV,OAAO,CAAC,QAAS,MAAM,QAAQ,IAAI,OAAO,IAAK,IAAI,UAA2B;AAChF,CAAC;AAIM,MAAM,aAAa,MAAoB,QAAQ,IAAI;AAInD,MAAM,kBAAkB,CAAC,aAA4D,QAAQ,SAAS,QAAQ;AAI9G,MAAM,aAAa,MAAoB,QAAQ,IAAI;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/spacesMode.ts"],"sourcesContent":["// The spaces mode's route channel and its one navigation verb (R3-708).\n//\n// The spaces mode runs ONE app across six frames — three activity pairs — and they must\n// agree on which space, activity and bundle is selected. A reload or a pasted link has to\n// land every frame on the same state, so the selection is a route the HOST owns and\n// deep-links to (`SPACES_BRIEF` §3), not something the frames negotiate between\n// themselves.\n//\n// Two halves, and the asymmetry is the point:\n//\n// read `useSpacesMode()` — the host's parsed route, pushed down.\n// write `navigateSpaces(target)` — a request to MOVE, taking coordinates.\n//\n// The write half never takes a path string, now or later. An app that could spell the\n// destination could open anything (`BUNDLE_EMBEDDING_SPEC` §6.1a), so the SDK offers no\n// string overload and the host builds every URL from its own grammar\n// (`SPACES_BRIEF` §7, \"the host spells the URL\"). That is also why an app reads\n// `space.root` for its files rather than assuming a mount path.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { SPACES_MODE, REQUEST_SPACES_MODE, PROTOCOL_SPACES_MODE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The spaces mode's four top-level activities. */\nexport type SpacesActivity = 'spaces' | 'inbox' | 'people' | 'settings';\n\n/**\n * Where the user is inside the spaces mode, as the host parsed it.\n *\n * `spaceId` is `null` on a route that names no space, which is TWO routes, not one: the\n * launcher (`activity: 'spaces'`) and the **cross-space inbox** (`activity: 'inbox'` —\n * `/spaces/-/inbox`, every room across every space). Branch on the pair, not on `spaceId`\n * alone.\n *\n * The `-` in that URL is the host's reserved segment and never reaches here: it is not an\n * id, and an app must not send `spaceId: '-'` hoping to mean \"all spaces\" — say\n * `{ spaceId: null, activity: 'inbox' }`. The host spells the URL (`SPACES_BRIEF` §7); the\n * SDK never sees that grammar.\n *\n * The optional fields are the per-activity tail: `path` a bundle-relative file, `roomId` a\n * conversation, `member` the uid of `/spaces/<id>/people/<uid>`, `section` a settings pane.\n */\nexport interface SpacesRoute {\n spaceId: string | null;\n activity: SpacesActivity;\n path?: string;\n roomId?: string;\n member?: string;\n section?: string;\n}\n\n/**\n * The selected space, as the host resolved it for THIS frame.\n *\n * `root` is the path the host mounted the space at in this frame, at the reader's role —\n * or `null` in every frame the host did not mount it into. Read files under `root`; never\n * assume a mount path.\n *\n * `name` is untrusted display text supplied by whoever named the space. React escapes it\n * on render and the SDK does not sanitise it — treat it as content, not markup.\n *\n * `kind` (not `mode`) matches site-main's `SpaceKind`: one noun for the personal/shared\n * axis (R-IX-6).\n *\n * **None of this is a grant.** The object describes what the host chose to tell this\n * frame; it confers nothing. `role` is a label for deciding which affordances to *show* —\n * it is not permission to act, and an app that branches on `role === 'owner'` to skip\n * asking has only skipped its own UI, not the check. What IS enforced host-side is the\n * mount: `root` is mounted at the reader's role, so a reader's frame cannot write through\n * it (`site-main` `filesystem/liveRevocation.ts` derives the mount mode from the role, and\n * `editor/spaceHandler.ts` re-checks `role` on the owner-only paths).\n *\n * What is NOT enforced, and must not be read into the above: per-APP authority.\n * `UI_AS_APPS_SPEC` §8's audited gap is explicit that `mount` \"accepts an arbitrary\n * `spaceId` and enforces only user membership … every app currently inherits the user's\n * full authority\". So the host answers \"may the USER do this\", not \"may this app\", and a\n * frame holding this object is no more constrained than the reader is. Treat it as a\n * description of the reader's position, never as a sandbox around the app.\n *\n * A frame the host does not push to reads `null` — an absence of information, not a\n * denial, and equally not a reason to assume access.\n */\nexport interface SpacesModeSpace {\n id: string;\n name: string;\n role: 'owner' | 'writer' | 'reader';\n kind: 'personal' | 'shared';\n root: string | null;\n}\n\n/** The host's view of this frame: where the user is, and which space that resolves to. */\nexport interface SpacesModeState {\n route: SpacesRoute;\n space: SpacesModeSpace | null;\n}\n\n/**\n * Where to move to.\n *\n * Either a route inside the mode, or the one host destination outside it —\n * `{ destination: 'notifications' }`, which the inventory panel's line pointing at pending\n * invitations uses so the app never spells a mode path itself.\n */\nexport type SpacesTarget = SpacesRoute | { destination: 'notifications' };\n\n/** Why the host refused to navigate.\n *\n * - `invalid` — the target is not a route this host can build. This is also the code for\n * a space the reader has no membership-granted view of, **deliberately**: P7 forbids an\n * existence oracle, and `SPACES_BRIEF` §7 says a doclink into a space the reader is not\n * a member of \"renders the same not-found as a link to nothing\". A distinct code here\n * would be exactly the oracle — an app could enumerate spaceIds and read membership off\n * the difference. Non-member and never-existed are one answer.\n * - `forbidden` — this frame lacks the CAPABILITY to navigate at all. It is a statement\n * about the caller, never about the target, so it discloses nothing about what exists.\n * - `unsupported` — this host has no spaces mode wired.\n * - `unknown` — the host refused without naming a code. */\nexport type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface NavigateSpacesError extends Error {\n code: NavigateSpacesErrorCode;\n}\n\nconst ACTIVITIES: readonly string[] = ['spaces', 'inbox', 'people', 'settings'];\nconst ROLES: readonly string[] = ['owner', 'writer', 'reader'];\nconst KINDS: readonly string[] = ['personal', 'shared'];\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** A present field must be a string; an absent one is fine. Anything else fails. */\nconst optionalString = (v: unknown): boolean => v === undefined || typeof v === 'string';\n\nconst parseRoute = (v: unknown): SpacesRoute | undefined => {\n if (!isRecord(v)) return undefined;\n if (typeof v.activity !== 'string' || !ACTIVITIES.includes(v.activity)) return undefined;\n if (!(v.spaceId === null || typeof v.spaceId === 'string')) return undefined;\n if (!optionalString(v.path) || !optionalString(v.roomId)) return undefined;\n if (!optionalString(v.member) || !optionalString(v.section)) return undefined;\n const route: SpacesRoute = {\n spaceId: v.spaceId as string | null,\n activity: v.activity as SpacesActivity,\n };\n // Copied field by field rather than spread: a host that adds a field tomorrow must not\n // have it silently appear on an object apps treat as this version's shape.\n if (typeof v.path === 'string') route.path = v.path;\n if (typeof v.roomId === 'string') route.roomId = v.roomId;\n if (typeof v.member === 'string') route.member = v.member;\n if (typeof v.section === 'string') route.section = v.section;\n return route;\n};\n\nconst parseSpace = (v: unknown): SpacesModeSpace | null | undefined => {\n if (v === null) return null;\n if (!isRecord(v)) return undefined;\n if (typeof v.id !== 'string' || typeof v.name !== 'string') return undefined;\n if (typeof v.role !== 'string' || !ROLES.includes(v.role)) return undefined;\n if (typeof v.kind !== 'string' || !KINDS.includes(v.kind)) return undefined;\n if (!(v.root === null || typeof v.root === 'string')) return undefined;\n return {\n id: v.id,\n name: v.name,\n role: v.role as SpacesModeSpace['role'],\n kind: v.kind as SpacesModeSpace['kind'],\n root: v.root as string | null,\n };\n};\n\n// Tolerant parse. `undefined` means \"ignore this message\", so a malformed push from a\n// newer or older host leaves the LAST GOOD value standing instead of flipping every frame\n// to a route nobody sent. Nothing in here throws: a throw in the listener would take down\n// the push loop for every channel sharing it.\nconst parseState = (state: unknown): SpacesModeState | null | undefined => {\n // A pushed `null` is a RETRACTION, not a malformed message, and the wire says so: the\n // channel's declared value is `SpacesModeState | null` (sandbox-protocol 0.11.0,\n // `snapshots/sdk.json`, `spaces-mode.value`). Folding it into the `isRecord` guard below\n // made it mean \"ignore\", which left the host with no way to say \"this frame has left the\n // mode\" — the last route would stand forever, and an app would keep rendering a space it\n // is no longer in. `null` here is distinct from `undefined`: it SETS the value.\n if (state === null) return null;\n if (!isRecord(state)) return undefined;\n const route = parseRoute(state.route);\n if (!route) return undefined;\n const space = parseSpace(state.space);\n if (space === undefined) return undefined;\n return { route, space };\n};\n\n// `initial: null` is the whole compatibility story, and it is deliberately NOT a synthetic\n// `{ activity: 'spaces' }`: an app must be able to tell \"the host has not told me anything\"\n// from \"the host says I am on the launcher\". A frame outside the mode, a standalone tab,\n// `vite dev`, an older host, or a frame lacking the read capability all stay `null`, and an\n// app falls back to its pre-mode UI there.\nconst channel = createPushChannel<SpacesModeState | null>({\n pushType: SPACES_MODE,\n requestType: REQUEST_SPACES_MODE,\n initial: null,\n // Written inline, reading `msg.state` here rather than inside the helper: the snapshot\n // gate extracts a push channel's `reads` from THIS expression, and a bare function\n // reference tells it nothing — it falls back to the parameter type and the wire shape\n // reads `Record<string, unknown>` instead of `{reads:[\"state\"]}`.\n parse: (msg) => parseState(msg.state),\n});\n\n/**\n * The host's spaces-mode state for this frame, or `null` when this app is not running in\n * the spaces mode — a standalone tab, `vite dev`, an older host, or a frame the host does\n * not push this to.\n *\n * `null` is a real answer, not a placeholder: fall back to your own UI rather than\n * assuming a route.\n */\nexport const getSpacesMode = (): SpacesModeState | null => channel.get();\n\n/**\n * Subscribe to spaces-mode changes. The listener is invoked immediately with the current\n * value, then on every change. Returns an unsubscribe function.\n */\nexport const onSpacesModeChange = (listener: (state: SpacesModeState | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/**\n * React hook form of {@link getSpacesMode} — re-renders when the host's route changes.\n *\n * ```tsx\n * const mode = useSpacesMode();\n * if (!mode) return <MyStandaloneUI />; // not in the spaces mode\n * if (!mode.space) return <Launcher />; // no space selected\n * if (!mode.space.root) return <NotMountedHere />; // selected, but not mounted into THIS\n * return <Files root={mode.space.root} />; // never assume a mount path\n * ```\n *\n * The third guard is not defensive padding: `root` is `null` in every frame the host did\n * not mount the space into, which is every frame but the launcher's. Passing it through\n * unchecked is the mistake this example exists to prevent.\n */\nexport const useSpacesMode = (): SpacesModeState | null => channel.use();\n\n/** The host's reply ENVELOPE (site-main's `SpaceResult`). A refusal is a RESOLVED\n * `{ ok: false, code, message }` frame, not a transport-level rejection — see\n * `protocolRefusal.ts` for which `ok` this is and why a handler must THROW\n * `spaceError` rather than return `{ ok: false }`. R3-707's `navigate` handler must\n * throw. */\ntype NavigateReply = { ok: true; data?: unknown } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to move the spaces mode to `target`.\n *\n * Resolves once the host has navigated. Rejects with a typed {@link NavigateSpacesError}\n * carrying `code` when the host refuses.\n *\n * The target is always structured coordinates — there is no path-string form, because an\n * app that could spell the destination could open anything. To leave the mode for the one\n * host destination outside it, pass `{ destination: 'notifications' }`.\n *\n * ```ts\n * await navigateSpaces({ spaceId: 'abc', activity: 'spaces', path: 'notes/today.mdx' });\n * await navigateSpaces({ destination: 'notifications' });\n * ```\n */\nexport async function navigateSpaces(target: SpacesTarget): Promise<void> {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES_MODE], 'navigate', [target])) as NavigateReply;\n throwOnRefusal(res, 'spaces navigation refused');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,0BAAgC;AAChC,6BAA+B;AAC/B,yBAAkC;AAClC,sBAAuE;AACvE,6BAAwB;AAsGxB,MAAM,aAAgC,CAAC,UAAU,SAAS,UAAU,UAAU;AAC9E,MAAM,QAA2B,CAAC,SAAS,UAAU,QAAQ;AAC7D,MAAM,QAA2B,CAAC,YAAY,QAAQ;AAEtD,MAAM,WAAW,CAAC,MAA6C,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAGtH,MAAM,iBAAiB,CAAC,MAAwB,MAAM,UAAa,OAAO,MAAM;AAEhF,MAAM,aAAa,CAAC,MAAwC;AAC1D,MAAI,CAAC,SAAS,CAAC,EAAG,QAAO;AACzB,MAAI,OAAO,EAAE,aAAa,YAAY,CAAC,WAAW,SAAS,EAAE,QAAQ,EAAG,QAAO;AAC/E,MAAI,EAAE,EAAE,YAAY,QAAQ,OAAO,EAAE,YAAY,UAAW,QAAO;AACnE,MAAI,CAAC,eAAe,EAAE,IAAI,KAAK,CAAC,eAAe,EAAE,MAAM,EAAG,QAAO;AACjE,MAAI,CAAC,eAAe,EAAE,MAAM,KAAK,CAAC,eAAe,EAAE,OAAO,EAAG,QAAO;AACpE,QAAM,QAAqB;AAAA,IACzB,SAAS,EAAE;AAAA,IACX,UAAU,EAAE;AAAA,EACd;AAGA,MAAI,OAAO,EAAE,SAAS,SAAU,OAAM,OAAO,EAAE;AAC/C,MAAI,OAAO,EAAE,WAAW,SAAU,OAAM,SAAS,EAAE;AACnD,MAAI,OAAO,EAAE,WAAW,SAAU,OAAM,SAAS,EAAE;AACnD,MAAI,OAAO,EAAE,YAAY,SAAU,OAAM,UAAU,EAAE;AACrD,SAAO;AACT;AAEA,MAAM,aAAa,CAAC,MAAmD;AACrE,MAAI,MAAM,KAAM,QAAO;AACvB,MAAI,CAAC,SAAS,CAAC,EAAG,QAAO;AACzB,MAAI,OAAO,EAAE,OAAO,YAAY,OAAO,EAAE,SAAS,SAAU,QAAO;AACnE,MAAI,OAAO,EAAE,SAAS,YAAY,CAAC,MAAM,SAAS,EAAE,IAAI,EAAG,QAAO;AAClE,MAAI,OAAO,EAAE,SAAS,YAAY,CAAC,MAAM,SAAS,EAAE,IAAI,EAAG,QAAO;AAClE,MAAI,EAAE,EAAE,SAAS,QAAQ,OAAO,EAAE,SAAS,UAAW,QAAO;AAC7D,SAAO;AAAA,IACL,IAAI,EAAE;AAAA,IACN,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,EACV;AACF;AAMA,MAAM,aAAa,CAAC,UAAuD;AAOzE,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,QAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,EAAE,OAAO,MAAM;AACxB;AAOA,MAAM,cAAU,sCAA0C;AAAA,EACxD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAKT,OAAO,CAAC,QAAQ,WAAW,IAAI,KAAK;AACtC,CAAC;AAUM,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAMhE,MAAM,qBAAqB,CAAC,aACjC,QAAQ,SAAS,QAAQ;AAiBpB,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAwBvE,eAAsB,eAAe,QAAqC;AACxE,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,oCAAoB,GAAG,YAAY,CAAC,MAAM,CAAC;AACtF,6CAAe,KAAK,2BAA2B;AACjD;","names":[]}
1
+ {"version":3,"sources":["../src/spacesMode.ts"],"sourcesContent":["// The spaces mode's route channel and its one navigation verb (R3-708).\n//\n// The spaces mode runs ONE app across six frames — three activity pairs — and they must\n// agree on which space, activity and bundle is selected. A reload or a pasted link has to\n// land every frame on the same state, so the selection is a route the HOST owns and\n// deep-links to (`SPACES_BRIEF` §3), not something the frames negotiate between\n// themselves.\n//\n// Two halves, and the asymmetry is the point:\n//\n// read `useSpacesMode()` — the host's parsed route, pushed down.\n// write `navigateSpaces(target)` — a request to MOVE, taking coordinates.\n//\n// The write half never takes a path string, now or later. An app that could spell the\n// destination could open anything (`BUNDLE_EMBEDDING_SPEC` §6.1a), so the SDK offers no\n// string overload and the host builds every URL from its own grammar\n// (`SPACES_BRIEF` §7, \"the host spells the URL\"). That is also why an app reads\n// `space.root` for its files rather than assuming a mount path.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { createPushChannel } from './pushChannel';\nimport { SPACES_MODE, REQUEST_SPACES_MODE, PROTOCOL_SPACES_MODE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** The spaces mode's four top-level activities. */\nexport type SpacesActivity = 'spaces' | 'inbox' | 'people' | 'settings';\n\n/**\n * Where the user is inside the spaces mode, as the host parsed it.\n *\n * `spaceId` is `null` on a route that names no space, which is TWO routes, not one: the\n * launcher (`activity: 'spaces'`) and the **cross-space inbox** (`activity: 'inbox'` —\n * `/spaces/-/inbox`, every room across every space). Branch on the pair, not on `spaceId`\n * alone.\n *\n * The `-` in that URL is the host's reserved segment and never reaches here: it is not an\n * id, and an app must not send `spaceId: '-'` hoping to mean \"all spaces\" — say\n * `{ spaceId: null, activity: 'inbox' }`. The host spells the URL (`SPACES_BRIEF` §7); the\n * SDK never sees that grammar.\n *\n * The optional fields are the per-activity tail: `path` a bundle-relative file, `roomId` a\n * conversation, `member` the uid of `/spaces/<id>/people/<uid>`, `section` a settings pane.\n */\nexport interface SpacesRoute {\n spaceId: string | null;\n activity: SpacesActivity;\n path?: string;\n roomId?: string;\n member?: string;\n section?: string;\n}\n\n/**\n * The selected space, as the host resolved it for THIS frame.\n *\n * `root` is the path the host mounted the space at in this frame, at the reader's role —\n * or `null` in every frame the host did not mount it into. Read files under `root`; never\n * assume a mount path.\n *\n * `name` is untrusted display text supplied by whoever named the space. React escapes it\n * on render and the SDK does not sanitise it — treat it as content, not markup.\n *\n * `kind` (not `mode`) matches site-main's `SpaceKind`: one noun for the personal/shared\n * axis (R-IX-6).\n *\n * **None of this is a grant.** The object describes what the host chose to tell this\n * frame; it confers nothing. `role` is a label for deciding which affordances to *show* —\n * it is not permission to act, and an app that branches on `role === 'owner'` to skip\n * asking has only skipped its own UI, not the check. What IS enforced host-side is the\n * mount: `root` is mounted at the reader's role, so a reader's frame cannot write through\n * it (`site-main` `filesystem/liveRevocation.ts` derives the mount mode from the role, and\n * `editor/spaceHandler.ts` re-checks `role` on the owner-only paths).\n *\n * What is NOT enforced, and must not be read into the above: per-APP authority.\n * `UI_AS_APPS_SPEC` §8's audited gap is explicit that `mount` \"accepts an arbitrary\n * `spaceId` and enforces only user membership … every app currently inherits the user's\n * full authority\". So the host answers \"may the USER do this\", not \"may this app\", and a\n * frame holding this object is no more constrained than the reader is. Treat it as a\n * description of the reader's position, never as a sandbox around the app.\n *\n * A frame the host does not push to reads `null` — an absence of information, not a\n * denial, and equally not a reason to assume access.\n */\nexport interface SpacesModeSpace {\n id: string;\n name: string;\n role: 'owner' | 'writer' | 'reader';\n kind: 'personal' | 'shared';\n root: string | null;\n}\n\n/** The host's view of this frame: where the user is, and which space that resolves to. */\nexport interface SpacesModeState {\n route: SpacesRoute;\n space: SpacesModeSpace | null;\n}\n\n/**\n * Where to move to.\n *\n * Either a route inside the mode, or the one host destination outside it —\n * `{ destination: 'notifications' }`, which the inventory panel's line pointing at pending\n * invitations uses so the app never spells a mode path itself.\n */\nexport type SpacesTarget = SpacesRoute | { destination: 'notifications' };\n\n/** Why the host refused to navigate.\n *\n * - `invalid` — the target is not a route this host can build. This is also the code for\n * a space the reader has no membership-granted view of, **deliberately**: P7 forbids an\n * existence oracle, and `SPACES_BRIEF` §7 says a doclink into a space the reader is not\n * a member of \"renders the same not-found as a link to nothing\". A distinct code here\n * would be exactly the oracle — an app could enumerate spaceIds and read membership off\n * the difference. Non-member and never-existed are one answer.\n * - `forbidden` — this frame lacks the CAPABILITY to navigate at all. It is a statement\n * about the caller, never about the target, so it discloses nothing about what exists.\n * - `unsupported` — this host has no spaces mode wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends; the union was always a cast and is not enforced at\n * runtime, so treat an unlisted code as possible and `instanceof Error` as the only\n * reliable test. */\nexport type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface NavigateSpacesError extends Error {\n code: NavigateSpacesErrorCode;\n}\n\nconst ACTIVITIES: readonly string[] = ['spaces', 'inbox', 'people', 'settings'];\nconst ROLES: readonly string[] = ['owner', 'writer', 'reader'];\nconst KINDS: readonly string[] = ['personal', 'shared'];\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** A present field must be a string; an absent one is fine. Anything else fails. */\nconst optionalString = (v: unknown): boolean => v === undefined || typeof v === 'string';\n\nconst parseRoute = (v: unknown): SpacesRoute | undefined => {\n if (!isRecord(v)) return undefined;\n if (typeof v.activity !== 'string' || !ACTIVITIES.includes(v.activity)) return undefined;\n if (!(v.spaceId === null || typeof v.spaceId === 'string')) return undefined;\n if (!optionalString(v.path) || !optionalString(v.roomId)) return undefined;\n if (!optionalString(v.member) || !optionalString(v.section)) return undefined;\n const route: SpacesRoute = {\n spaceId: v.spaceId as string | null,\n activity: v.activity as SpacesActivity,\n };\n // Copied field by field rather than spread: a host that adds a field tomorrow must not\n // have it silently appear on an object apps treat as this version's shape.\n if (typeof v.path === 'string') route.path = v.path;\n if (typeof v.roomId === 'string') route.roomId = v.roomId;\n if (typeof v.member === 'string') route.member = v.member;\n if (typeof v.section === 'string') route.section = v.section;\n return route;\n};\n\nconst parseSpace = (v: unknown): SpacesModeSpace | null | undefined => {\n if (v === null) return null;\n if (!isRecord(v)) return undefined;\n if (typeof v.id !== 'string' || typeof v.name !== 'string') return undefined;\n if (typeof v.role !== 'string' || !ROLES.includes(v.role)) return undefined;\n if (typeof v.kind !== 'string' || !KINDS.includes(v.kind)) return undefined;\n if (!(v.root === null || typeof v.root === 'string')) return undefined;\n return {\n id: v.id,\n name: v.name,\n role: v.role as SpacesModeSpace['role'],\n kind: v.kind as SpacesModeSpace['kind'],\n root: v.root as string | null,\n };\n};\n\n// Tolerant parse. `undefined` means \"ignore this message\", so a malformed push from a\n// newer or older host leaves the LAST GOOD value standing instead of flipping every frame\n// to a route nobody sent. Nothing in here throws: a throw in the listener would take down\n// the push loop for every channel sharing it.\nconst parseState = (state: unknown): SpacesModeState | null | undefined => {\n // A pushed `null` is a RETRACTION, not a malformed message, and the wire says so: the\n // channel's declared value is `SpacesModeState | null` (sandbox-protocol 0.11.0,\n // `snapshots/sdk.json`, `spaces-mode.value`). Folding it into the `isRecord` guard below\n // made it mean \"ignore\", which left the host with no way to say \"this frame has left the\n // mode\" — the last route would stand forever, and an app would keep rendering a space it\n // is no longer in. `null` here is distinct from `undefined`: it SETS the value.\n if (state === null) return null;\n if (!isRecord(state)) return undefined;\n const route = parseRoute(state.route);\n if (!route) return undefined;\n const space = parseSpace(state.space);\n if (space === undefined) return undefined;\n return { route, space };\n};\n\n// `initial: null` is the whole compatibility story, and it is deliberately NOT a synthetic\n// `{ activity: 'spaces' }`: an app must be able to tell \"the host has not told me anything\"\n// from \"the host says I am on the launcher\". A frame outside the mode, a standalone tab,\n// `vite dev`, an older host, or a frame lacking the read capability all stay `null`, and an\n// app falls back to its pre-mode UI there.\nconst channel = createPushChannel<SpacesModeState | null>({\n pushType: SPACES_MODE,\n requestType: REQUEST_SPACES_MODE,\n initial: null,\n // Written inline, reading `msg.state` here rather than inside the helper: the snapshot\n // gate extracts a push channel's `reads` from THIS expression, and a bare function\n // reference tells it nothing — it falls back to the parameter type and the wire shape\n // reads `Record<string, unknown>` instead of `{reads:[\"state\"]}`.\n parse: (msg) => parseState(msg.state),\n});\n\n/**\n * The host's spaces-mode state for this frame, or `null` when this app is not running in\n * the spaces mode — a standalone tab, `vite dev`, an older host, or a frame the host does\n * not push this to.\n *\n * `null` is a real answer, not a placeholder: fall back to your own UI rather than\n * assuming a route.\n */\nexport const getSpacesMode = (): SpacesModeState | null => channel.get();\n\n/**\n * Subscribe to spaces-mode changes. The listener is invoked immediately with the current\n * value, then on every change. Returns an unsubscribe function.\n */\nexport const onSpacesModeChange = (listener: (state: SpacesModeState | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/**\n * React hook form of {@link getSpacesMode} — re-renders when the host's route changes.\n *\n * ```tsx\n * const mode = useSpacesMode();\n * if (!mode) return <MyStandaloneUI />; // not in the spaces mode\n * if (!mode.space) return <Launcher />; // no space selected\n * if (!mode.space.root) return <NotMountedHere />; // selected, but not mounted into THIS\n * return <Files root={mode.space.root} />; // never assume a mount path\n * ```\n *\n * The third guard is not defensive padding: `root` is `null` in every frame the host did\n * not mount the space into, which is every frame but the launcher's. Passing it through\n * unchecked is the mistake this example exists to prevent.\n */\nexport const useSpacesMode = (): SpacesModeState | null => channel.use();\n\n/** The host's reply ENVELOPE (site-main's `SpaceResult`). A refusal is a RESOLVED\n * `{ ok: false, code, message }` frame, not a transport-level rejection — see\n * `protocolRefusal.ts` for which `ok` this is and why a handler must THROW\n * `spaceError` rather than return `{ ok: false }`. R3-707's `navigate` handler must\n * throw. */\ntype NavigateReply = { ok: true; data?: unknown } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to move the spaces mode to `target`.\n *\n * Resolves once the host has navigated. Rejects with a typed {@link NavigateSpacesError}\n * carrying `code` when the host refuses.\n *\n * The target is always structured coordinates — there is no path-string form, because an\n * app that could spell the destination could open anything. To leave the mode for the one\n * host destination outside it, pass `{ destination: 'notifications' }`.\n *\n * ```ts\n * await navigateSpaces({ spaceId: 'abc', activity: 'spaces', path: 'notes/today.mdx' });\n * await navigateSpaces({ destination: 'notifications' });\n * ```\n */\nexport async function navigateSpaces(target: SpacesTarget): Promise<void> {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES_MODE], 'navigate', [target])) as NavigateReply;\n throwOnRefusal(res, 'spaces navigation refused');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,0BAAgC;AAChC,6BAA+B;AAC/B,yBAAkC;AAClC,sBAAuE;AACvE,6BAAwB;AA4GxB,MAAM,aAAgC,CAAC,UAAU,SAAS,UAAU,UAAU;AAC9E,MAAM,QAA2B,CAAC,SAAS,UAAU,QAAQ;AAC7D,MAAM,QAA2B,CAAC,YAAY,QAAQ;AAEtD,MAAM,WAAW,CAAC,MAA6C,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAGtH,MAAM,iBAAiB,CAAC,MAAwB,MAAM,UAAa,OAAO,MAAM;AAEhF,MAAM,aAAa,CAAC,MAAwC;AAC1D,MAAI,CAAC,SAAS,CAAC,EAAG,QAAO;AACzB,MAAI,OAAO,EAAE,aAAa,YAAY,CAAC,WAAW,SAAS,EAAE,QAAQ,EAAG,QAAO;AAC/E,MAAI,EAAE,EAAE,YAAY,QAAQ,OAAO,EAAE,YAAY,UAAW,QAAO;AACnE,MAAI,CAAC,eAAe,EAAE,IAAI,KAAK,CAAC,eAAe,EAAE,MAAM,EAAG,QAAO;AACjE,MAAI,CAAC,eAAe,EAAE,MAAM,KAAK,CAAC,eAAe,EAAE,OAAO,EAAG,QAAO;AACpE,QAAM,QAAqB;AAAA,IACzB,SAAS,EAAE;AAAA,IACX,UAAU,EAAE;AAAA,EACd;AAGA,MAAI,OAAO,EAAE,SAAS,SAAU,OAAM,OAAO,EAAE;AAC/C,MAAI,OAAO,EAAE,WAAW,SAAU,OAAM,SAAS,EAAE;AACnD,MAAI,OAAO,EAAE,WAAW,SAAU,OAAM,SAAS,EAAE;AACnD,MAAI,OAAO,EAAE,YAAY,SAAU,OAAM,UAAU,EAAE;AACrD,SAAO;AACT;AAEA,MAAM,aAAa,CAAC,MAAmD;AACrE,MAAI,MAAM,KAAM,QAAO;AACvB,MAAI,CAAC,SAAS,CAAC,EAAG,QAAO;AACzB,MAAI,OAAO,EAAE,OAAO,YAAY,OAAO,EAAE,SAAS,SAAU,QAAO;AACnE,MAAI,OAAO,EAAE,SAAS,YAAY,CAAC,MAAM,SAAS,EAAE,IAAI,EAAG,QAAO;AAClE,MAAI,OAAO,EAAE,SAAS,YAAY,CAAC,MAAM,SAAS,EAAE,IAAI,EAAG,QAAO;AAClE,MAAI,EAAE,EAAE,SAAS,QAAQ,OAAO,EAAE,SAAS,UAAW,QAAO;AAC7D,SAAO;AAAA,IACL,IAAI,EAAE;AAAA,IACN,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,IACR,MAAM,EAAE;AAAA,EACV;AACF;AAMA,MAAM,aAAa,CAAC,UAAuD;AAOzE,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,CAAC,SAAS,KAAK,EAAG,QAAO;AAC7B,QAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,QAAQ,WAAW,MAAM,KAAK;AACpC,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,EAAE,OAAO,MAAM;AACxB;AAOA,MAAM,cAAU,sCAA0C;AAAA,EACxD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAKT,OAAO,CAAC,QAAQ,WAAW,IAAI,KAAK;AACtC,CAAC;AAUM,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAMhE,MAAM,qBAAqB,CAAC,aACjC,QAAQ,SAAS,QAAQ;AAiBpB,MAAM,gBAAgB,MAA8B,QAAQ,IAAI;AAwBvE,eAAsB,eAAe,QAAqC;AACxE,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,oCAAoB,GAAG,YAAY,CAAC,MAAM,CAAC;AACtF,6CAAe,KAAK,2BAA2B;AACjD;","names":[]}
@@ -88,7 +88,13 @@ type SpacesTarget = SpacesRoute | {
88
88
  * - `forbidden` — this frame lacks the CAPABILITY to navigate at all. It is a statement
89
89
  * about the caller, never about the target, so it discloses nothing about what exists.
90
90
  * - `unsupported` — this host has no spaces mode wired.
91
- * - `unknown` — the host refused without naming a code. */
91
+ * - `unknown` — the host refused without naming a code.
92
+ *
93
+ * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a
94
+ * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the
95
+ * `.code` VALUES the host sends; the union was always a cast and is not enforced at
96
+ * runtime, so treat an unlisted code as possible and `instanceof Error` as the only
97
+ * reliable test. */
92
98
  type NavigateSpacesErrorCode = 'invalid' | 'forbidden' | 'unsupported' | 'unknown';
93
99
  interface NavigateSpacesError extends Error {
94
100
  code: NavigateSpacesErrorCode;