@immediately-run/sdk 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/dist/MDXProvider.js +1 -0
  2. package/dist/MDXProvider.js.map +1 -1
  3. package/dist/TinkerableContext.js +1 -0
  4. package/dist/TinkerableContext.js.map +1 -1
  5. package/dist/auth.js +1 -0
  6. package/dist/auth.js.map +1 -1
  7. package/dist/boot.js +1 -0
  8. package/dist/boot.js.map +1 -1
  9. package/dist/catalog.js +1 -0
  10. package/dist/catalog.js.map +1 -1
  11. package/dist/chunk-VHAA22YE.js +14 -0
  12. package/dist/chunk-VHAA22YE.js.map +1 -0
  13. package/dist/components/Admonition.js +1 -0
  14. package/dist/components/Admonition.js.map +1 -1
  15. package/dist/components/FileRouter.js +1 -0
  16. package/dist/components/FileRouter.js.map +1 -1
  17. package/dist/components/HeadingAnchor.js +1 -0
  18. package/dist/components/HeadingAnchor.js.map +1 -1
  19. package/dist/components/Include.js +1 -0
  20. package/dist/components/Include.js.map +1 -1
  21. package/dist/components/Link.js +1 -0
  22. package/dist/components/Link.js.map +1 -1
  23. package/dist/components/MDXComponents.js +1 -0
  24. package/dist/components/MDXComponents.js.map +1 -1
  25. package/dist/components/MainContent.js +1 -0
  26. package/dist/components/MainContent.js.map +1 -1
  27. package/dist/components/MountImage.js +1 -0
  28. package/dist/components/MountImage.js.map +1 -1
  29. package/dist/components/Routes.js +1 -0
  30. package/dist/components/Routes.js.map +1 -1
  31. package/dist/components/ScrollAfterNavigation.js +1 -0
  32. package/dist/components/ScrollAfterNavigation.js.map +1 -1
  33. package/dist/components/WikiLink.js +1 -0
  34. package/dist/components/WikiLink.js.map +1 -1
  35. package/dist/components/defaults.js +1 -0
  36. package/dist/components/defaults.js.map +1 -1
  37. package/dist/components/errors.js +1 -0
  38. package/dist/components/errors.js.map +1 -1
  39. package/dist/contextUtils.js +1 -0
  40. package/dist/contextUtils.js.map +1 -1
  41. package/dist/contribute.js +1 -0
  42. package/dist/contribute.js.map +1 -1
  43. package/dist/debug.js +1 -0
  44. package/dist/debug.js.map +1 -1
  45. package/dist/diagnostics.js +1 -0
  46. package/dist/diagnostics.js.map +1 -1
  47. package/dist/dnd.js +1 -0
  48. package/dist/dnd.js.map +1 -1
  49. package/dist/editor.js +1 -0
  50. package/dist/editor.js.map +1 -1
  51. package/dist/editorContext.js +1 -0
  52. package/dist/editorContext.js.map +1 -1
  53. package/dist/formFactor.js +1 -0
  54. package/dist/formFactor.js.map +1 -1
  55. package/dist/fs.js +1 -0
  56. package/dist/fs.js.map +1 -1
  57. package/dist/hooks.js +1 -0
  58. package/dist/hooks.js.map +1 -1
  59. package/dist/hostRuntime.js +1 -0
  60. package/dist/hostRuntime.js.map +1 -1
  61. package/dist/index.cjs +2 -0
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/index.d.cts +1 -0
  64. package/dist/index.d.ts +1 -0
  65. package/dist/index.js +1 -0
  66. package/dist/index.js.map +1 -1
  67. package/dist/injectedBundler.js +1 -0
  68. package/dist/injectedBundler.js.map +1 -1
  69. package/dist/ipc.js +1 -0
  70. package/dist/ipc.js.map +1 -1
  71. package/dist/irMarkers.js +1 -0
  72. package/dist/irMarkers.js.map +1 -1
  73. package/dist/launch.cjs +95 -0
  74. package/dist/launch.cjs.map +1 -0
  75. package/dist/launch.d.cts +76 -0
  76. package/dist/launch.d.ts +76 -0
  77. package/dist/launch.js +69 -0
  78. package/dist/launch.js.map +1 -0
  79. package/dist/llm.js +1 -0
  80. package/dist/llm.js.map +1 -1
  81. package/dist/loading.js +1 -0
  82. package/dist/loading.js.map +1 -1
  83. package/dist/markers.js +1 -0
  84. package/dist/markers.js.map +1 -1
  85. package/dist/moduleCache.js +1 -0
  86. package/dist/moduleCache.js.map +1 -1
  87. package/dist/mountMatch.js +1 -0
  88. package/dist/mountMatch.js.map +1 -1
  89. package/dist/mounts.js +1 -0
  90. package/dist/mounts.js.map +1 -1
  91. package/dist/netFetch.js +1 -0
  92. package/dist/netFetch.js.map +1 -1
  93. package/dist/onFsChange.js +1 -0
  94. package/dist/onFsChange.js.map +1 -1
  95. package/dist/pathUtils.js +1 -0
  96. package/dist/pathUtils.js.map +1 -1
  97. package/dist/protocolStream.js +1 -0
  98. package/dist/protocolStream.js.map +1 -1
  99. package/dist/pushChannel.js +1 -0
  100. package/dist/pushChannel.js.map +1 -1
  101. package/dist/ready.js +1 -0
  102. package/dist/ready.js.map +1 -1
  103. package/dist/region.js +1 -0
  104. package/dist/region.js.map +1 -1
  105. package/dist/routeMatch.js +1 -0
  106. package/dist/routeMatch.js.map +1 -1
  107. package/dist/routing.js +1 -0
  108. package/dist/routing.js.map +1 -1
  109. package/dist/runtime.js +1 -0
  110. package/dist/runtime.js.map +1 -1
  111. package/dist/safeContent/SafeContent.js +1 -0
  112. package/dist/safeContent/SafeContent.js.map +1 -1
  113. package/dist/safeContent/index.js +1 -0
  114. package/dist/safeContent/index.js.map +1 -1
  115. package/dist/safeContent/mdastDeps.cjs +186 -1
  116. package/dist/safeContent/mdastDeps.js +186 -1
  117. package/dist/safeContent/parseSafeMdast.cjs +26 -17
  118. package/dist/safeContent/parseSafeMdast.cjs.map +1 -1
  119. package/dist/safeContent/parseSafeMdast.js +27 -21
  120. package/dist/safeContent/parseSafeMdast.js.map +1 -1
  121. package/dist/safeContent/renderMdast.js +1 -0
  122. package/dist/safeContent/renderMdast.js.map +1 -1
  123. package/dist/safeContent/sanitizeUrl.js +1 -0
  124. package/dist/safeContent/sanitizeUrl.js.map +1 -1
  125. package/dist/safeContent/wikilink.js +1 -0
  126. package/dist/safeContent/wikilink.js.map +1 -1
  127. package/dist/sandboxUtils.js +1 -0
  128. package/dist/sandboxUtils.js.map +1 -1
  129. package/dist/scrollToId.js +1 -0
  130. package/dist/scrollToId.js.map +1 -1
  131. package/dist/secrets.js +1 -0
  132. package/dist/secrets.js.map +1 -1
  133. package/dist/tasks.js +1 -0
  134. package/dist/tasks.js.map +1 -1
  135. package/dist/testing.js +1 -0
  136. package/dist/testing.js.map +1 -1
  137. package/dist/theme.js +1 -0
  138. package/dist/theme.js.map +1 -1
  139. package/dist/urlUtils.js +1 -0
  140. package/dist/urlUtils.js.map +1 -1
  141. package/dist/vcs.js +1 -0
  142. package/dist/vcs.js.map +1 -1
  143. package/dist/version.cjs +1 -1
  144. package/dist/version.cjs.map +1 -1
  145. package/dist/version.d.cts +1 -1
  146. package/dist/version.d.ts +1 -1
  147. package/dist/version.js +2 -1
  148. package/dist/version.js.map +1 -1
  149. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? '/app';\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: \"ro\" | \"rw\";\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason =\n | \"revoked\"\n | \"unshared\"\n | \"signed-out\"\n | \"unmounted\"\n | \"deleted\";\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n ): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value)\n ? (value as MountRemoveReason)\n : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener('mount-add', (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener('mount-remove', (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage('request-mounts');\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean =>\n mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined =>\n getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n */\nexport const waitForMount = (query: MountQuery): Promise<SandboxMount> =>\n new Promise((resolve) => {\n const unsubscribe = onMountsChange((mounts) => {\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n // Defer unsubscribe so we don't dispose during the initial replay call.\n Promise.resolve().then(unsubscribe);\n resolve(found);\n }\n });\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: 'session-mounts',\n requestType: 'request-session-mounts',\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (\n listener: (mounts: SessionMount[]) => void,\n): (() => void) => sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** Summary of a space, as returned by {@link listSpaces}. */\nexport interface SpaceInfo {\n spaceId: string;\n role?: 'owner' | 'writer' | 'reader';\n owner?: string;\n name?: string;\n}\n\n/** An error from a space operation, carrying a machine-readable `code`. */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n | 'unknown';\n}\n\ntype SpaceResult =\n | { ok: true; data: unknown }\n | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and\n// throwing a typed SpaceError on failure.\nconst request = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('spaces', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'space request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (\n method: string,\n query: Record<string, unknown>,\n): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> =>\n requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> =>\n mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> =>\n requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n */\nexport const makeContentRef = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): FileCap => ({ $cap: 'file', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `request` for the spaces surface).\nconst settingsRequest = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('settings', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'settings request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> =>\n settingsRequest<string[]>('list');\n\n/** Create a brand-new, empty platform-hosted space. The app reaches it (or any\n * other space) afterward through the {@link requestMount} powerbox or\n * {@link mountSpace}; there is no implicit per-app binding. */\nexport const createSpace = (\n opts: { name?: string } = {}\n): Promise<SandboxMount> => requestMountInternal('create', opts);\n\n/** List spaces you can access — all of them, or just those bound to this app. */\nexport const listSpaces = (opts: { app?: boolean } = {}): Promise<SpaceInfo[]> =>\n request<SpaceInfo[]>('list', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n// ---------------------------------------------------------------------------\n\n/** A collaborator's role on a shared space: full `owner`, read-write `writer`, or read-only `reader`. */\nexport type Role = 'owner' | 'writer' | 'reader';\n\n/** A member of a space (for the share/manage UI). */\nexport interface Member {\n /**\n * The **grantee** — `user:{uid}` | `group:{gid}`. This is the canonical name\n * (core_concepts §4: \"principal\" is reserved for the authority context; a space\n * member is a *grantee*). The host populates this on every member row.\n */\n grantee: string;\n /**\n * @deprecated Use {@link Member.grantee}. Kept as an alias (same value) for\n * back-compat during the `principal`→`grantee` migration; will be removed in a\n * future major. The host still populates both.\n */\n principal: string;\n role: Role;\n login?: string;\n avatarUrl?: string;\n}\n\n/** A handle resolved to a principal (handle → who). */\nexport interface ResolvedUser {\n uid: string;\n login: string;\n avatarUrl?: string;\n}\n\n/** A pending invitation to a space (pull-based sharing, FILE_SHARING_SPEC §6.4).\n * It grants NO access until accepted — the recipient accepts it from their inbox\n * ({@link listMyInvites} → {@link acceptInvite}), materializing membership. The\n * display fields (`name`/`login`/`avatarUrl`) are untrusted for rendering. */\nexport interface Invite {\n spaceId: string;\n /** The invitee's uid — carried so the owner's pending list can\n * {@link revokeInvite}(spaceId, uid). */\n uid: string;\n role: Role;\n owner: string;\n name?: string;\n invitedBy: string;\n /** epoch ms (server-stamped); absent until the write settles. */\n invitedAt?: number;\n login?: string;\n avatarUrl?: string;\n}\n\n/** Enumerate ALL the user's spaces (not just this app's) — `spaces:user`. */\nexport const listAllSpaces = (): Promise<SpaceInfo[]> => request<SpaceInfo[]>('listAll', {});\n\n/** Read a space's members one-shot — `spaces:admin`. */\nexport const getSpaceMembers = (spaceId: string): Promise<Member[]> =>\n request<Member[]>('members', { spaceId });\n\n/** Invite a user (by provider handle) to a space at a role — `spaces:admin`. The\n * host resolves the handle, so the app never sees other users' uids except the one\n * it invited. Pull-based (FILE_SHARING_SPEC §6.4): this writes an INVITATION, not\n * membership — the recipient must {@link acceptInvite}. Re-inviting an already-\n * invited/member user is idempotent. */\nexport const inviteToSpace = async (spaceId: string, login: string, role: Role): Promise<void> => {\n await request('invite', { spaceId, login, role });\n};\n\n/** The owner's outstanding invitations for a space — `spaces:admin`. */\nexport const listPendingInvites = (spaceId: string): Promise<Invite[]> =>\n request<Invite[]>('pendingInvites', { spaceId });\n\n/** Withdraw a pending invitation (distinct from {@link unshareSpace}, which removes\n * an ACCEPTED member) — `spaces:admin`. */\nexport const revokeInvite = async (spaceId: string, uid: string): Promise<void> => {\n await request('revokeInvite', { spaceId, uid });\n};\n\n/** The caller's OWN invitation inbox — `spaces:user`. */\nexport const listMyInvites = (): Promise<Invite[]> => request<Invite[]>('listInvites', {});\n\n/** Accept an invitation: materialize your membership at the invited role and clear\n * the invite — `spaces:user`. An invitation the caller doesn't hold rejects with\n * `forbidden` (indistinguishable from a nonexistent space; no existence oracle). */\nexport const acceptInvite = async (spaceId: string): Promise<void> => {\n await request('acceptInvite', { spaceId });\n};\n\n/** Decline (dismiss) an invitation from your inbox; writes no membership —\n * `spaces:user`. */\nexport const declineInvite = async (spaceId: string): Promise<void> => {\n await request('declineInvite', { spaceId });\n};\n\n// The live invitations inbox (FILE_SHARING §6.4/§9.8): the host pushes the caller's\n// current invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects within one\n// snapshot — no poll. Mirrors the host's `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: 'invitations',\n requestType: 'request-invitations',\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n\n/** Remove a member from a space — `spaces:admin`. Refused if it would orphan the\n * space (owner-lockout, T41). */\nexport const unshareSpace = async (spaceId: string, uid: string): Promise<void> => {\n await request('unshare', { spaceId, uid });\n};\n\n/** Change a member's role — `spaces:admin`. Refused if it would drop the sole\n * owner (owner-lockout, T41). */\nexport const setSpaceRole = async (spaceId: string, uid: string, role: Role): Promise<void> => {\n await request('setRole', { spaceId, uid, role });\n};\n\n/** Resolve a provider handle to a principal (for the invite flow) — `spaces:admin`,\n * rate-limited host-side. */\nexport const lookupUser = (login: string): Promise<ResolvedUser> =>\n request<ResolvedUser>('lookupUser', { login });\n\n/** One durable grant an app holds, for the §8.11 capability audit view. */\nexport interface GrantRecord {\n /** The app's provider-qualified identity (`provider__namespace__repository`). */\n appKey: string;\n spaceId: string;\n /** Universal mount id (§3.5). */\n mountId: string;\n subtree?: string;\n mode: 'ro' | 'rw';\n name?: string;\n}\n\n/** Enumerate every (app, mount) grant the user holds — the audit view\n * (§8.11). Elevated `spaces:admin`. */\nexport const listGrants = (): Promise<GrantRecord[]> => request<GrantRecord[]>('grants', {});\n\n/** Revoke one app's grant on a space — durable (the app can't re-mount) plus a\n * best-effort live teardown. Elevated `spaces:admin`. */\nexport const revokeGrant = async (appKey: string, spaceId: string): Promise<void> => {\n await request('revokeGrant', { appKey, spaceId });\n};\n"],"mappings":"AAAA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,yBAAyB;AAClC,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAatB,MAAM,kBAAkB,MAAc,eAAe,GAAG,gBAAgB;AAoF/E,MAAM,WAAW,CAAC,MAA4B,EAAE,MAAM,EAAE;AAExD,MAAM,uBAA4C,oBAAI,IAAuB;AAAA,EAC3E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,MAAM,sBAAsB,CAAC,UAC3B,OAAO,UAAU,YAAY,qBAAqB,IAAI,KAAK,IACtD,QACD;AAKN,MAAM,uBAAuB,MAA2B;AACtD,MAAI;AAEF,UAAM,MAAM,QAAQ,YAAY,QAAQ,SAAS;AACjD,WAAO,OAAO,OAAO,IAAI,cAAc,aAAa,MAAM;AAAA,EAC5D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAUA,IAAI,eAAoC;AAExC,MAAM,wBAAwB,MAAoB;AAChD,MAAI,aAAc,QAAO;AACzB,MAAI,SAAyB,CAAC;AAC9B,QAAM,YAAY,oBAAI,IAAoD;AAC1E,QAAM,OAAO,CAAC,YAA4B;AACxC,eAAW,KAAK,CAAC,GAAG,SAAS,EAAG,GAAE,QAAQ,OAAO;AAAA,EACnD;AAEA,cAAY,aAAa,CAAC,QAA6B;AACrD,UAAMA,SAAkC,IAAI;AAC5C,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,SAAiB,QAA+B;AACjF,QAAM,QAAQ,WAAW,EAAE,SAAS,IAAI,CAAC;AAC3C;AAIO,MAAM,eAAe,OAAO,SAAiB,KAAa,SAA8B;AAC7F,QAAM,QAAQ,WAAW,EAAE,SAAS,KAAK,KAAK,CAAC;AACjD;AAIO,MAAM,aAAa,CAAC,UACzB,QAAsB,cAAc,EAAE,MAAM,CAAC;AAgBxC,MAAM,aAAa,MAA8B,QAAuB,UAAU,CAAC,CAAC;AAIpF,MAAM,cAAc,OAAO,QAAgB,YAAmC;AACnF,QAAM,QAAQ,eAAe,EAAE,QAAQ,QAAQ,CAAC;AAClD;","names":["mount"]}
1
+ {"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? '/app';\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: \"ro\" | \"rw\";\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason =\n | \"revoked\"\n | \"unshared\"\n | \"signed-out\"\n | \"unmounted\"\n | \"deleted\";\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n ): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value)\n ? (value as MountRemoveReason)\n : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener('mount-add', (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener('mount-remove', (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage('request-mounts');\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean =>\n mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined =>\n getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (\n listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void,\n): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n */\nexport const waitForMount = (query: MountQuery): Promise<SandboxMount> =>\n new Promise((resolve) => {\n const unsubscribe = onMountsChange((mounts) => {\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n // Defer unsubscribe so we don't dispose during the initial replay call.\n Promise.resolve().then(unsubscribe);\n resolve(found);\n }\n });\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: 'session-mounts',\n requestType: 'request-session-mounts',\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (\n listener: (mounts: SessionMount[]) => void,\n): (() => void) => sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** Summary of a space, as returned by {@link listSpaces}. */\nexport interface SpaceInfo {\n spaceId: string;\n role?: 'owner' | 'writer' | 'reader';\n owner?: string;\n name?: string;\n}\n\n/** An error from a space operation, carrying a machine-readable `code`. */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n | 'unknown';\n}\n\ntype SpaceResult =\n | { ok: true; data: unknown }\n | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and\n// throwing a typed SpaceError on failure.\nconst request = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('spaces', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'space request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (\n method: string,\n query: Record<string, unknown>,\n): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> =>\n requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> =>\n mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> =>\n requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n */\nexport const makeContentRef = (\n ref: { mountId: string; relPath: string },\n opts: { mode: 'ro' | 'rw' },\n): FileCap => ({ $cap: 'file', mountId: ref.mountId, relPath: ref.relPath, mode: opts.mode });\n\n/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a typed\n// SpaceError on failure (mirrors `request` for the spaces surface).\nconst settingsRequest = async <T = unknown>(\n method: string,\n query: Record<string, unknown> = {},\n): Promise<T> => {\n const res = (await protocolRequest('settings', method, [query])) as SpaceResult;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'settings request failed') as SpaceError;\n err.code = (res?.code as SpaceError['code']) ?? 'unknown';\n throw err;\n }\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> =>\n settingsRequest<string[]>('list');\n\n/** Create a brand-new, empty platform-hosted space. The app reaches it (or any\n * other space) afterward through the {@link requestMount} powerbox or\n * {@link mountSpace}; there is no implicit per-app binding. */\nexport const createSpace = (\n opts: { name?: string } = {}\n): Promise<SandboxMount> => requestMountInternal('create', opts);\n\n/** List spaces you can access — all of them, or just those bound to this app. */\nexport const listSpaces = (opts: { app?: boolean } = {}): Promise<SpaceInfo[]> =>\n request<SpaceInfo[]>('list', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n// ---------------------------------------------------------------------------\n\n/** A collaborator's role on a shared space: full `owner`, read-write `writer`, or read-only `reader`. */\nexport type Role = 'owner' | 'writer' | 'reader';\n\n/** A member of a space (for the share/manage UI). */\nexport interface Member {\n /**\n * The **grantee** — `user:{uid}` | `group:{gid}`. This is the canonical name\n * (core_concepts §4: \"principal\" is reserved for the authority context; a space\n * member is a *grantee*). The host populates this on every member row.\n */\n grantee: string;\n /**\n * @deprecated Use {@link Member.grantee}. Kept as an alias (same value) for\n * back-compat during the `principal`→`grantee` migration; will be removed in a\n * future major. The host still populates both.\n */\n principal: string;\n role: Role;\n login?: string;\n avatarUrl?: string;\n}\n\n/** A handle resolved to a principal (handle → who). */\nexport interface ResolvedUser {\n uid: string;\n login: string;\n avatarUrl?: string;\n}\n\n/** A pending invitation to a space (pull-based sharing, FILE_SHARING_SPEC §6.4).\n * It grants NO access until accepted — the recipient accepts it from their inbox\n * ({@link listMyInvites} → {@link acceptInvite}), materializing membership. The\n * display fields (`name`/`login`/`avatarUrl`) are untrusted for rendering. */\nexport interface Invite {\n spaceId: string;\n /** The invitee's uid — carried so the owner's pending list can\n * {@link revokeInvite}(spaceId, uid). */\n uid: string;\n role: Role;\n owner: string;\n name?: string;\n invitedBy: string;\n /** epoch ms (server-stamped); absent until the write settles. */\n invitedAt?: number;\n login?: string;\n avatarUrl?: string;\n}\n\n/** Enumerate ALL the user's spaces (not just this app's) — `spaces:user`. */\nexport const listAllSpaces = (): Promise<SpaceInfo[]> => request<SpaceInfo[]>('listAll', {});\n\n/** Read a space's members one-shot — `spaces:admin`. */\nexport const getSpaceMembers = (spaceId: string): Promise<Member[]> =>\n request<Member[]>('members', { spaceId });\n\n/** Invite a user (by provider handle) to a space at a role — `spaces:admin`. The\n * host resolves the handle, so the app never sees other users' uids except the one\n * it invited. Pull-based (FILE_SHARING_SPEC §6.4): this writes an INVITATION, not\n * membership — the recipient must {@link acceptInvite}. Re-inviting an already-\n * invited/member user is idempotent. */\nexport const inviteToSpace = async (spaceId: string, login: string, role: Role): Promise<void> => {\n await request('invite', { spaceId, login, role });\n};\n\n/** The owner's outstanding invitations for a space — `spaces:admin`. */\nexport const listPendingInvites = (spaceId: string): Promise<Invite[]> =>\n request<Invite[]>('pendingInvites', { spaceId });\n\n/** Withdraw a pending invitation (distinct from {@link unshareSpace}, which removes\n * an ACCEPTED member) — `spaces:admin`. */\nexport const revokeInvite = async (spaceId: string, uid: string): Promise<void> => {\n await request('revokeInvite', { spaceId, uid });\n};\n\n/** The caller's OWN invitation inbox — `spaces:user`. */\nexport const listMyInvites = (): Promise<Invite[]> => request<Invite[]>('listInvites', {});\n\n/** Accept an invitation: materialize your membership at the invited role and clear\n * the invite — `spaces:user`. An invitation the caller doesn't hold rejects with\n * `forbidden` (indistinguishable from a nonexistent space; no existence oracle). */\nexport const acceptInvite = async (spaceId: string): Promise<void> => {\n await request('acceptInvite', { spaceId });\n};\n\n/** Decline (dismiss) an invitation from your inbox; writes no membership —\n * `spaces:user`. */\nexport const declineInvite = async (spaceId: string): Promise<void> => {\n await request('declineInvite', { spaceId });\n};\n\n// The live invitations inbox (FILE_SHARING §6.4/§9.8): the host pushes the caller's\n// current invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects within one\n// snapshot — no poll. Mirrors the host's `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: 'invitations',\n requestType: 'request-invitations',\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n\n/** Remove a member from a space — `spaces:admin`. Refused if it would orphan the\n * space (owner-lockout, T41). */\nexport const unshareSpace = async (spaceId: string, uid: string): Promise<void> => {\n await request('unshare', { spaceId, uid });\n};\n\n/** Change a member's role — `spaces:admin`. Refused if it would drop the sole\n * owner (owner-lockout, T41). */\nexport const setSpaceRole = async (spaceId: string, uid: string, role: Role): Promise<void> => {\n await request('setRole', { spaceId, uid, role });\n};\n\n/** Resolve a provider handle to a principal (for the invite flow) — `spaces:admin`,\n * rate-limited host-side. */\nexport const lookupUser = (login: string): Promise<ResolvedUser> =>\n request<ResolvedUser>('lookupUser', { login });\n\n/** One durable grant an app holds, for the §8.11 capability audit view. */\nexport interface GrantRecord {\n /** The app's provider-qualified identity (`provider__namespace__repository`). */\n appKey: string;\n spaceId: string;\n /** Universal mount id (§3.5). */\n mountId: string;\n subtree?: string;\n mode: 'ro' | 'rw';\n name?: string;\n}\n\n/** Enumerate every (app, mount) grant the user holds — the audit view\n * (§8.11). Elevated `spaces:admin`. */\nexport const listGrants = (): Promise<GrantRecord[]> => request<GrantRecord[]>('grants', {});\n\n/** Revoke one app's grant on a space — durable (the app can't re-mount) plus a\n * best-effort live teardown. Elevated `spaces:admin`. */\nexport const revokeGrant = async (appKey: string, spaceId: string): Promise<void> => {\n await request('revokeGrant', { appKey, spaceId });\n};\n"],"mappings":";AAAA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,yBAAyB;AAClC,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAatB,MAAM,kBAAkB,MAAc,eAAe,GAAG,gBAAgB;AAoF/E,MAAM,WAAW,CAAC,MAA4B,EAAE,MAAM,EAAE;AAExD,MAAM,uBAA4C,oBAAI,IAAuB;AAAA,EAC3E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,MAAM,sBAAsB,CAAC,UAC3B,OAAO,UAAU,YAAY,qBAAqB,IAAI,KAAK,IACtD,QACD;AAKN,MAAM,uBAAuB,MAA2B;AACtD,MAAI;AAEF,UAAM,MAAM,QAAQ,YAAY,QAAQ,SAAS;AACjD,WAAO,OAAO,OAAO,IAAI,cAAc,aAAa,MAAM;AAAA,EAC5D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAUA,IAAI,eAAoC;AAExC,MAAM,wBAAwB,MAAoB;AAChD,MAAI,aAAc,QAAO;AACzB,MAAI,SAAyB,CAAC;AAC9B,QAAM,YAAY,oBAAI,IAAoD;AAC1E,QAAM,OAAO,CAAC,YAA4B;AACxC,eAAW,KAAK,CAAC,GAAG,SAAS,EAAG,GAAE,QAAQ,OAAO;AAAA,EACnD;AAEA,cAAY,aAAa,CAAC,QAA6B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eAAe,IAAI;AAItD,MAAM,eAAe,OAAO,SAAiB,QAA+B;AACjF,QAAM,QAAQ,WAAW,EAAE,SAAS,IAAI,CAAC;AAC3C;AAIO,MAAM,eAAe,OAAO,SAAiB,KAAa,SAA8B;AAC7F,QAAM,QAAQ,WAAW,EAAE,SAAS,KAAK,KAAK,CAAC;AACjD;AAIO,MAAM,aAAa,CAAC,UACzB,QAAsB,cAAc,EAAE,MAAM,CAAC;AAgBxC,MAAM,aAAa,MAA8B,QAAuB,UAAU,CAAC,CAAC;AAIpF,MAAM,cAAc,OAAO,QAAgB,YAAmC;AACnF,QAAM,QAAQ,eAAe,EAAE,QAAQ,QAAQ,CAAC;AAClD;","names":["mount"]}
package/dist/netFetch.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  import { protocolRequest } from "./sandboxUtils";
2
3
  import { protocolStream } from "./protocolStream";
3
4
  const hostFetch = async (url, init = {}) => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/netFetch.ts"],"sourcesContent":["// hostFetch — the app-facing side of the §5.11 parent-fetch proxy. The app calls\n// `hostFetch(url, init)`; the HOST performs the fetch with its real origin, but\n// only after validating `url` against your manifest's\n// `requests.\"net:fetch\".hosts` ∩ the user's consented hosts, blocking SSRF\n// targets, omitting immediately.run credentials, refusing redirects, and bounding\n// the response size. No raw network handle ever crosses the boundary (§8.10) —\n// only the serialized response.\n\nimport { protocolRequest } from './sandboxUtils';\nimport { protocolStream } from './protocolStream';\n\n/** Request options for {@link hostFetch}: method, headers, and a string body. */\nexport interface HostFetchInit {\n method?: string;\n headers?: Record<string, string>;\n /** Request body for non-GET/HEAD methods (string). */\n body?: string;\n}\n\n/** The serialized response from {@link hostFetch} (no live stream crosses the boundary). */\nexport interface HostFetchResponse {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n body: string;\n /** True if the body hit the host's size cap and was truncated. */\n truncated: boolean;\n}\n\n/**\n * Fetch through the host's parent-fetch proxy (§5.11). Requires the `net:fetch`\n * capability with `url`'s origin in your effective allowlist (manifest ∩ the\n * user's consent) — both are arranged at load via the consent screen.\n *\n * A reachable server's reply (including a non-2xx status) RESOLVES — inspect\n * `.status`. A gate/SSRF/transport failure REJECTS with an {@link Error} carrying\n * a machine `.code`: `forbidden` (outside the allowlist), `blocked` (SSRF target),\n * `invalid` (bad url/scheme), `redirect` (the host refuses to follow redirects),\n * `too-large`, or `network`.\n */\nexport const hostFetch = async (\n url: string,\n init: HostFetchInit = {},\n): Promise<HostFetchResponse> => {\n const res = (await protocolRequest('fetch', 'fetch', [\n { url, method: init.method, headers: init.headers, body: init.body },\n ])) as\n | { ok: true; data: HostFetchResponse }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'hostFetch failed') as Error & { code?: string };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n/** One streamed slice of the response body (a chunk as it arrives from the\n * host). Concatenate `.chunk` across the stream to rebuild the body. */\nexport interface HostFetchStreamEvent {\n chunk: string;\n}\n\n/** The terminal value of a {@link hostFetchStream} run — the response metadata,\n * delivered once after the last body chunk. There is no `body` field: the body\n * arrived as the stream of {@link HostFetchStreamEvent}s. */\nexport interface HostFetchStreamResult {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n /** True if the stream hit the host's cumulative byte cap and was truncated. */\n truncated: boolean;\n /** Total decoded body bytes delivered. */\n bytes: number;\n}\n\n/**\n * Stream a response through the host's parent-fetch proxy (§5.11 streaming;\n * `LLM_AND_AGENTS_SPEC §2.2`) — the streaming counterpart of {@link hostFetch},\n * for SSE / LLM token streaming. Same `net:fetch` gate (manifest ∩ consent),\n * same credential-less rule and per-hop SSRF re-check; the response body is\n * pumped as a sequence of {@link HostFetchStreamEvent} chunks instead of a single\n * buffered reply.\n *\n * ```ts\n * let body = '';\n * for await (const { chunk } of hostFetchStream(url, { method: 'POST', body })) {\n * body += chunk; // e.g. parse SSE / token deltas as they arrive\n * }\n * ```\n *\n * The generator **returns** a {@link HostFetchStreamResult} (status + headers +\n * `truncated`/`bytes`) when the body completes. A gate/SSRF/transport failure —\n * or one of the host's stream bounds — **throws** a `StreamError` (from\n * `./protocolStream`) carrying a\n * machine `.code`: `forbidden` (outside the allowlist), `blocked` (SSRF target),\n * `invalid` (bad url/scheme), `redirect` (the host refuses to follow redirects),\n * `idle-timeout` / `total-timeout` (the host's stream bounds), `byte-cap`, or\n * `network`. The stream is bounded by the host's idle/total timeouts and a\n * cumulative byte cap, so it cannot be used as an unbounded transfer channel.\n *\n * Requires the host to implement the `protocol-fetch` streaming emitter; until\n * that lands a streaming request fails with `not-streamable` and callers should\n * fall back to {@link hostFetch} (`LLM_AND_AGENTS_SPEC §2.2`, roadmap P3-71).\n */\nexport function hostFetchStream(\n url: string,\n init: HostFetchInit = {},\n): AsyncGenerator<HostFetchStreamEvent, HostFetchStreamResult, void> {\n return protocolStream<HostFetchStreamEvent, HostFetchStreamResult>(\n 'protocol-fetch',\n 'fetchStream',\n [{ url, method: init.method, headers: init.headers, body: init.body }],\n );\n}\n"],"mappings":"AAQA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AA+BxB,MAAM,YAAY,OACvB,KACA,OAAsB,CAAC,MACQ;AAC/B,QAAM,MAAO,MAAM,gBAAgB,SAAS,SAAS;AAAA,IACnD,EAAE,KAAK,QAAQ,KAAK,QAAQ,SAAS,KAAK,SAAS,MAAM,KAAK,KAAK;AAAA,EACrE,CAAC;AAID,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,kBAAkB;AACxD,QAAI,QAAQ,OAAO,UAAU,MAAM,IAAI,OAAO,WAAc;AAC5D,UAAM;AAAA,EACR;AACA,SAAO,IAAI;AACb;AAkDO,SAAS,gBACd,KACA,OAAsB,CAAC,GAC4C;AACnE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,CAAC,EAAE,KAAK,QAAQ,KAAK,QAAQ,SAAS,KAAK,SAAS,MAAM,KAAK,KAAK,CAAC;AAAA,EACvE;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/netFetch.ts"],"sourcesContent":["// hostFetch — the app-facing side of the §5.11 parent-fetch proxy. The app calls\n// `hostFetch(url, init)`; the HOST performs the fetch with its real origin, but\n// only after validating `url` against your manifest's\n// `requests.\"net:fetch\".hosts` ∩ the user's consented hosts, blocking SSRF\n// targets, omitting immediately.run credentials, refusing redirects, and bounding\n// the response size. No raw network handle ever crosses the boundary (§8.10) —\n// only the serialized response.\n\nimport { protocolRequest } from './sandboxUtils';\nimport { protocolStream } from './protocolStream';\n\n/** Request options for {@link hostFetch}: method, headers, and a string body. */\nexport interface HostFetchInit {\n method?: string;\n headers?: Record<string, string>;\n /** Request body for non-GET/HEAD methods (string). */\n body?: string;\n}\n\n/** The serialized response from {@link hostFetch} (no live stream crosses the boundary). */\nexport interface HostFetchResponse {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n body: string;\n /** True if the body hit the host's size cap and was truncated. */\n truncated: boolean;\n}\n\n/**\n * Fetch through the host's parent-fetch proxy (§5.11). Requires the `net:fetch`\n * capability with `url`'s origin in your effective allowlist (manifest ∩ the\n * user's consent) — both are arranged at load via the consent screen.\n *\n * A reachable server's reply (including a non-2xx status) RESOLVES — inspect\n * `.status`. A gate/SSRF/transport failure REJECTS with an {@link Error} carrying\n * a machine `.code`: `forbidden` (outside the allowlist), `blocked` (SSRF target),\n * `invalid` (bad url/scheme), `redirect` (the host refuses to follow redirects),\n * `too-large`, or `network`.\n */\nexport const hostFetch = async (\n url: string,\n init: HostFetchInit = {},\n): Promise<HostFetchResponse> => {\n const res = (await protocolRequest('fetch', 'fetch', [\n { url, method: init.method, headers: init.headers, body: init.body },\n ])) as\n | { ok: true; data: HostFetchResponse }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? 'hostFetch failed') as Error & { code?: string };\n err.code = (res && 'code' in res ? res.code : undefined) ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n/** One streamed slice of the response body (a chunk as it arrives from the\n * host). Concatenate `.chunk` across the stream to rebuild the body. */\nexport interface HostFetchStreamEvent {\n chunk: string;\n}\n\n/** The terminal value of a {@link hostFetchStream} run — the response metadata,\n * delivered once after the last body chunk. There is no `body` field: the body\n * arrived as the stream of {@link HostFetchStreamEvent}s. */\nexport interface HostFetchStreamResult {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n /** True if the stream hit the host's cumulative byte cap and was truncated. */\n truncated: boolean;\n /** Total decoded body bytes delivered. */\n bytes: number;\n}\n\n/**\n * Stream a response through the host's parent-fetch proxy (§5.11 streaming;\n * `LLM_AND_AGENTS_SPEC §2.2`) — the streaming counterpart of {@link hostFetch},\n * for SSE / LLM token streaming. Same `net:fetch` gate (manifest ∩ consent),\n * same credential-less rule and per-hop SSRF re-check; the response body is\n * pumped as a sequence of {@link HostFetchStreamEvent} chunks instead of a single\n * buffered reply.\n *\n * ```ts\n * let body = '';\n * for await (const { chunk } of hostFetchStream(url, { method: 'POST', body })) {\n * body += chunk; // e.g. parse SSE / token deltas as they arrive\n * }\n * ```\n *\n * The generator **returns** a {@link HostFetchStreamResult} (status + headers +\n * `truncated`/`bytes`) when the body completes. A gate/SSRF/transport failure —\n * or one of the host's stream bounds — **throws** a `StreamError` (from\n * `./protocolStream`) carrying a\n * machine `.code`: `forbidden` (outside the allowlist), `blocked` (SSRF target),\n * `invalid` (bad url/scheme), `redirect` (the host refuses to follow redirects),\n * `idle-timeout` / `total-timeout` (the host's stream bounds), `byte-cap`, or\n * `network`. The stream is bounded by the host's idle/total timeouts and a\n * cumulative byte cap, so it cannot be used as an unbounded transfer channel.\n *\n * Requires the host to implement the `protocol-fetch` streaming emitter; until\n * that lands a streaming request fails with `not-streamable` and callers should\n * fall back to {@link hostFetch} (`LLM_AND_AGENTS_SPEC §2.2`, roadmap P3-71).\n */\nexport function hostFetchStream(\n url: string,\n init: HostFetchInit = {},\n): AsyncGenerator<HostFetchStreamEvent, HostFetchStreamResult, void> {\n return protocolStream<HostFetchStreamEvent, HostFetchStreamResult>(\n 'protocol-fetch',\n 'fetchStream',\n [{ url, method: init.method, headers: init.headers, body: init.body }],\n );\n}\n"],"mappings":";AAQA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AA+BxB,MAAM,YAAY,OACvB,KACA,OAAsB,CAAC,MACQ;AAC/B,QAAM,MAAO,MAAM,gBAAgB,SAAS,SAAS;AAAA,IACnD,EAAE,KAAK,QAAQ,KAAK,QAAQ,SAAS,KAAK,SAAS,MAAM,KAAK,KAAK;AAAA,EACrE,CAAC;AAID,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,kBAAkB;AACxD,QAAI,QAAQ,OAAO,UAAU,MAAM,IAAI,OAAO,WAAc;AAC5D,UAAM;AAAA,EACR;AACA,SAAO,IAAI;AACb;AAkDO,SAAS,gBACd,KACA,OAAsB,CAAC,GAC4C;AACnE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,CAAC,EAAE,KAAK,QAAQ,KAAK,QAAQ,SAAS,KAAK,SAAS,MAAM,KAAK,KAAK,CAAC;AAAA,EACvE;AACF;","names":[]}
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  import { createPushChannel } from "./pushChannel";
2
3
  const isStringArray = (v) => Array.isArray(v) && v.every((p) => typeof p === "string");
3
4
  const channel = createPushChannel({
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/onFsChange.ts"],"sourcesContent":["// Working-tree change stream (EDITOR_AS_APP_SPEC §4.2). The host pushes the\n// repo-relative paths that just changed in the working tree — from ANY writer: an\n// agent's port write, a host `editor:write` action (create/delete/rename), or the\n// preview's own copy-on-write. A working-tree observer (the editor app, the file\n// explorer) reacts by re-reading the affected files instead of polling.\n//\n// Elevated `editor:read` — a previewed app holds no `editor:read`, so it never sees\n// the stream (the host channel ACL withholds it). Push-only: there is no past-event\n// state worth polling, so the empty initial stands until the first write.\n//\n// Origin-exclusion is the CONSUMER's responsibility: the editor must ignore the\n// echo of its OWN write (a debounced write lags the buffer, so re-reading it as\n// \"external\" would surface a false conflict). Compare the changed file's bytes to\n// what you last wrote; if they match, it is your echo, not an external change.\nimport { createPushChannel } from './pushChannel';\n\n/** One working-tree change batch the host pushes: the changed paths plus an epoch. */\nexport interface FsChange {\n /** Repo-relative paths (leading slash, e.g. `/src/App.tsx`) that just changed. */\n paths: string[];\n /**\n * Monotonic batch id — bumps on every change even if the path set repeats, so a\n * subscriber re-fires for a second edit to the same file (the value is never\n * deduplicated away). `0` is the pre-first-event initial.\n */\n epoch: number;\n}\n\nconst isStringArray = (v: unknown): v is string[] =>\n Array.isArray(v) && v.every((p) => typeof p === 'string');\n\nconst channel = createPushChannel<FsChange>({\n pushType: 'fs-change',\n initial: { paths: [], epoch: 0 },\n parse: (msg) =>\n isStringArray(msg.paths) && typeof msg.epoch === 'number'\n ? { paths: msg.paths, epoch: msg.epoch }\n : undefined,\n});\n\n/** The most recent working-tree change batch (the empty initial until the first). */\nexport const getFsChange = (): FsChange => channel.get();\n\n/**\n * Subscribe to working-tree changes. The listener fires immediately with the\n * current batch, then on every host push. Returns an unsubscribe fn. The common\n * use: re-read an open file when its path appears in `change.paths`.\n */\nexport const onFsChange = (listener: (change: FsChange) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook: the current working-tree change batch, re-rendering on every push. */\nexport const useFsChange = (): FsChange => channel.use();\n"],"mappings":"AAcA,SAAS,yBAAyB;AAclC,MAAM,gBAAgB,CAAC,MACrB,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,OAAO,MAAM,QAAQ;AAE1D,MAAM,UAAU,kBAA4B;AAAA,EAC1C,UAAU;AAAA,EACV,SAAS,EAAE,OAAO,CAAC,GAAG,OAAO,EAAE;AAAA,EAC/B,OAAO,CAAC,QACN,cAAc,IAAI,KAAK,KAAK,OAAO,IAAI,UAAU,WAC7C,EAAE,OAAO,IAAI,OAAO,OAAO,IAAI,MAAM,IACrC;AACR,CAAC;AAGM,MAAM,cAAc,MAAgB,QAAQ,IAAI;AAOhD,MAAM,aAAa,CAAC,aACzB,QAAQ,SAAS,QAAQ;AAGpB,MAAM,cAAc,MAAgB,QAAQ,IAAI;","names":[]}
1
+ {"version":3,"sources":["../src/onFsChange.ts"],"sourcesContent":["// Working-tree change stream (EDITOR_AS_APP_SPEC §4.2). The host pushes the\n// repo-relative paths that just changed in the working tree — from ANY writer: an\n// agent's port write, a host `editor:write` action (create/delete/rename), or the\n// preview's own copy-on-write. A working-tree observer (the editor app, the file\n// explorer) reacts by re-reading the affected files instead of polling.\n//\n// Elevated `editor:read` — a previewed app holds no `editor:read`, so it never sees\n// the stream (the host channel ACL withholds it). Push-only: there is no past-event\n// state worth polling, so the empty initial stands until the first write.\n//\n// Origin-exclusion is the CONSUMER's responsibility: the editor must ignore the\n// echo of its OWN write (a debounced write lags the buffer, so re-reading it as\n// \"external\" would surface a false conflict). Compare the changed file's bytes to\n// what you last wrote; if they match, it is your echo, not an external change.\nimport { createPushChannel } from './pushChannel';\n\n/** One working-tree change batch the host pushes: the changed paths plus an epoch. */\nexport interface FsChange {\n /** Repo-relative paths (leading slash, e.g. `/src/App.tsx`) that just changed. */\n paths: string[];\n /**\n * Monotonic batch id — bumps on every change even if the path set repeats, so a\n * subscriber re-fires for a second edit to the same file (the value is never\n * deduplicated away). `0` is the pre-first-event initial.\n */\n epoch: number;\n}\n\nconst isStringArray = (v: unknown): v is string[] =>\n Array.isArray(v) && v.every((p) => typeof p === 'string');\n\nconst channel = createPushChannel<FsChange>({\n pushType: 'fs-change',\n initial: { paths: [], epoch: 0 },\n parse: (msg) =>\n isStringArray(msg.paths) && typeof msg.epoch === 'number'\n ? { paths: msg.paths, epoch: msg.epoch }\n : undefined,\n});\n\n/** The most recent working-tree change batch (the empty initial until the first). */\nexport const getFsChange = (): FsChange => channel.get();\n\n/**\n * Subscribe to working-tree changes. The listener fires immediately with the\n * current batch, then on every host push. Returns an unsubscribe fn. The common\n * use: re-read an open file when its path appears in `change.paths`.\n */\nexport const onFsChange = (listener: (change: FsChange) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook: the current working-tree change batch, re-rendering on every push. */\nexport const useFsChange = (): FsChange => channel.use();\n"],"mappings":";AAcA,SAAS,yBAAyB;AAclC,MAAM,gBAAgB,CAAC,MACrB,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,OAAO,MAAM,QAAQ;AAE1D,MAAM,UAAU,kBAA4B;AAAA,EAC1C,UAAU;AAAA,EACV,SAAS,EAAE,OAAO,CAAC,GAAG,OAAO,EAAE;AAAA,EAC/B,OAAO,CAAC,QACN,cAAc,IAAI,KAAK,KAAK,OAAO,IAAI,UAAU,WAC7C,EAAE,OAAO,IAAI,OAAO,OAAO,IAAI,MAAM,IACrC;AACR,CAAC;AAGM,MAAM,cAAc,MAAgB,QAAQ,IAAI;AAOhD,MAAM,aAAa,CAAC,aACzB,QAAQ,SAAS,QAAQ;AAGpB,MAAM,cAAc,MAAgB,QAAQ,IAAI;","names":[]}
package/dist/pathUtils.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  const PATH_SEPARATOR = "/";
2
3
  const joinPaths = (...pathPart) => pathPart.reduce((acc, part) => {
3
4
  const left = acc.endsWith(PATH_SEPARATOR) ? acc.slice(0, -1) : acc;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pathUtils.ts"],"sourcesContent":["const PATH_SEPARATOR = \"/\";\n\nexport const joinPaths = (...pathPart: string[]) => pathPart.reduce((acc, part) => {\n const left = (acc.endsWith(PATH_SEPARATOR)) ? acc.slice(0, -1) : acc;\n const right = (part.startsWith(PATH_SEPARATOR)) ? part.substring(1) : part;\n if (left || acc === PATH_SEPARATOR) {\n return `${left}${PATH_SEPARATOR}${right}`;\n }\n if (part.startsWith(PATH_SEPARATOR)) {\n return `${PATH_SEPARATOR}${right}`;\n }\n return right;\n}, \"\");\n\nexport const absPath = (rawPath: string): string => {\n const absCandidate = joinPaths.apply(\n null,\n rawPath.split(PATH_SEPARATOR).reduce(\n (partialAbsPath: string[], currentPathPart: string) => {\n if (currentPathPart == '.') {\n return partialAbsPath;\n }\n if (currentPathPart == '..') {\n return partialAbsPath.slice(0, -1)\n }\n return partialAbsPath.concat(currentPathPart);\n },\n []\n ));\n if (absCandidate === '' && rawPath.startsWith(PATH_SEPARATOR)) {\n return PATH_SEPARATOR;\n }\n return absCandidate;\n}\n"],"mappings":"AAAA,MAAM,iBAAiB;AAEhB,MAAM,YAAY,IAAI,aAAuB,SAAS,OAAO,CAAC,KAAK,SAAS;AACjF,QAAM,OAAQ,IAAI,SAAS,cAAc,IAAK,IAAI,MAAM,GAAG,EAAE,IAAI;AACjE,QAAM,QAAS,KAAK,WAAW,cAAc,IAAK,KAAK,UAAU,CAAC,IAAI;AACtE,MAAI,QAAQ,QAAQ,gBAAgB;AAClC,WAAO,GAAG,IAAI,GAAG,cAAc,GAAG,KAAK;AAAA,EACzC;AACA,MAAI,KAAK,WAAW,cAAc,GAAG;AACnC,WAAO,GAAG,cAAc,GAAG,KAAK;AAAA,EAClC;AACA,SAAO;AACT,GAAG,EAAE;AAEE,MAAM,UAAU,CAAC,YAA4B;AAClD,QAAM,eAAe,UAAU;AAAA,IAC7B;AAAA,IACA,QAAQ,MAAM,cAAc,EAAE;AAAA,MAC5B,CAAC,gBAA0B,oBAA4B;AACrD,YAAI,mBAAmB,KAAK;AAC1B,iBAAO;AAAA,QACT;AACA,YAAI,mBAAmB,MAAM;AAC3B,iBAAO,eAAe,MAAM,GAAG,EAAE;AAAA,QACnC;AACA,eAAO,eAAe,OAAO,eAAe;AAAA,MAC9C;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EAAC;AACH,MAAI,iBAAiB,MAAM,QAAQ,WAAW,cAAc,GAAG;AAC7D,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/pathUtils.ts"],"sourcesContent":["const PATH_SEPARATOR = \"/\";\n\nexport const joinPaths = (...pathPart: string[]) => pathPart.reduce((acc, part) => {\n const left = (acc.endsWith(PATH_SEPARATOR)) ? acc.slice(0, -1) : acc;\n const right = (part.startsWith(PATH_SEPARATOR)) ? part.substring(1) : part;\n if (left || acc === PATH_SEPARATOR) {\n return `${left}${PATH_SEPARATOR}${right}`;\n }\n if (part.startsWith(PATH_SEPARATOR)) {\n return `${PATH_SEPARATOR}${right}`;\n }\n return right;\n}, \"\");\n\nexport const absPath = (rawPath: string): string => {\n const absCandidate = joinPaths.apply(\n null,\n rawPath.split(PATH_SEPARATOR).reduce(\n (partialAbsPath: string[], currentPathPart: string) => {\n if (currentPathPart == '.') {\n return partialAbsPath;\n }\n if (currentPathPart == '..') {\n return partialAbsPath.slice(0, -1)\n }\n return partialAbsPath.concat(currentPathPart);\n },\n []\n ));\n if (absCandidate === '' && rawPath.startsWith(PATH_SEPARATOR)) {\n return PATH_SEPARATOR;\n }\n return absCandidate;\n}\n"],"mappings":";AAAA,MAAM,iBAAiB;AAEhB,MAAM,YAAY,IAAI,aAAuB,SAAS,OAAO,CAAC,KAAK,SAAS;AACjF,QAAM,OAAQ,IAAI,SAAS,cAAc,IAAK,IAAI,MAAM,GAAG,EAAE,IAAI;AACjE,QAAM,QAAS,KAAK,WAAW,cAAc,IAAK,KAAK,UAAU,CAAC,IAAI;AACtE,MAAI,QAAQ,QAAQ,gBAAgB;AAClC,WAAO,GAAG,IAAI,GAAG,cAAc,GAAG,KAAK;AAAA,EACzC;AACA,MAAI,KAAK,WAAW,cAAc,GAAG;AACnC,WAAO,GAAG,cAAc,GAAG,KAAK;AAAA,EAClC;AACA,SAAO;AACT,GAAG,EAAE;AAEE,MAAM,UAAU,CAAC,YAA4B;AAClD,QAAM,eAAe,UAAU;AAAA,IAC7B;AAAA,IACA,QAAQ,MAAM,cAAc,EAAE;AAAA,MAC5B,CAAC,gBAA0B,oBAA4B;AACrD,YAAI,mBAAmB,KAAK;AAC1B,iBAAO;AAAA,QACT;AACA,YAAI,mBAAmB,MAAM;AAC3B,iBAAO,eAAe,MAAM,GAAG,EAAE;AAAA,QACnC;AACA,eAAO,eAAe,OAAO,eAAe;AAAA,MAC9C;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EAAC;AACH,MAAI,iBAAiB,MAAM,QAAQ,WAAW,cAAc,GAAG;AAC7D,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":[]}
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  import { addListener, sendMessage } from "./sandboxUtils";
2
3
  class StreamError extends Error {
3
4
  constructor(code, message) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/protocolStream.ts"],"sourcesContent":["// SDK-side consumer for the host streaming transport (UI_AS_APPS_SPEC §5.1).\n//\n// The host `pumpGenerator` emits, per request msgId, a run of `stream.event`\n// frames terminated by one `stream.done` (with the return value) or `stream.error`\n// frame. This reassembles that run into an AsyncGenerator: each `event` is a\n// `yield`, the `done` value is the generator's `return`, an `error` is a `throw`.\n//\n// `consumeStream` takes an injected `StreamTransport` so it's unit-tested with a\n// fake send/subscribe — no bundler. `protocolStream`/`contribute` below wire it to\n// the real sandbox messageBus via sandboxUtils.\nimport { addListener, sendMessage } from './sandboxUtils';\n\n/** One frame of a host stream: an `event` value, the terminal `done` value, or an `error`. */\nexport type StreamFrame =\n | { kind: 'event'; value: unknown }\n | { kind: 'done'; value: unknown }\n | { kind: 'error'; code: string; message: string };\n\n/** The send/subscribe transport {@link consumeStream} drives (injected so it can be faked in tests). */\nexport interface StreamTransport {\n // Fire the request that starts the stream. The host replies with frames tagged\n // by the same `msgId`.\n send: (msg: { type: string; method: string; params: unknown[]; msgId: number; stream: true }) => void;\n // Subscribe to inbound frames for `type`; returns an unsubscribe.\n subscribe: (\n type: string,\n handler: (msg: { msgId?: number; stream?: StreamFrame }) => void\n ) => () => void;\n // Tell the host to STOP the stream early — abort the in-flight generation (and,\n // for `llm:chat`, the upstream provider fetch so it stops BILLING). Sent when the\n // consumer bails before a terminal frame: an early `break`/`return` out of the\n // `for await`, or an `AbortSignal` firing. Carries the same `(type, msgId)` the\n // host tagged its frames with, so the host aborts the matching generator\n // (LLM_AND_AGENTS_SPEC §3.3 \"abort the in-flight LLM request\"). Optional — a\n // transport predating the cancel frame simply omits it and the old behavior\n // (host runs to completion) stands.\n cancel?: (msg: { type: string; msgId: number; cancel: true }) => void;\n}\n\n/** Thrown when a stream ends in an `error` frame; carries the host's `code`. */\nexport class StreamError extends Error {\n code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = 'StreamError';\n this.code = code;\n }\n}\n\nlet streamCounter = 0;\nconst nextMsgId = (): number => {\n // Distinct from the bundler's own protocolRequest counter space is unnecessary —\n // frames are filtered by (type, msgId, stream) so a collision with a one-shot\n // reply (which has `result`, not `stream`) can't be misread.\n streamCounter = (streamCounter + 1) % Number.MAX_SAFE_INTEGER;\n return streamCounter;\n};\n\n/**\n * Drive one streamed request to completion over an injected transport.\n *\n * Yields each event value; returns the `done` value; throws `StreamError` on an\n * error frame. Always unsubscribes (via the generator's `finally`) so an early\n * `break` in the consumer doesn't leak the listener.\n *\n * `signal` wires a caller {@link AbortSignal} to mid-stream cancellation: when it\n * fires (or the consumer `break`s before a terminal frame), the `finally` sends a\n * `cancel` frame back over `transport.cancel` so the HOST stops generating — without\n * it, aborting only stops the app-side iterator while the upstream provider keeps\n * streaming and BILLING (LLM_AND_AGENTS_SPEC §3.3, R3-224 / adversarial F2).\n */\nexport async function* consumeStream<T = unknown, R = unknown>(\n transport: StreamTransport,\n type: string,\n method: string,\n params: unknown[],\n msgId: number = nextMsgId(),\n signal?: AbortSignal\n): AsyncGenerator<T, R, void> {\n const queue: StreamFrame[] = [];\n let wake: (() => void) | null = null;\n // True once a terminal (`done`/`error`) frame arrived — so the `finally` knows the\n // host already stopped and must NOT send a redundant cancel. Left false when the\n // consumer bails early or the signal aborts (the two cases that DO need a cancel).\n let settled = false;\n // True once the request frame went out. A cancel is only meaningful for a stream\n // the host actually started — an abort BEFORE `send` sends nothing to cancel.\n let started = false;\n const push = (frame: StreamFrame) => {\n queue.push(frame);\n const w = wake;\n wake = null;\n w?.();\n };\n\n const unsubscribe = transport.subscribe(type, (msg) => {\n if (msg.msgId !== msgId || !msg.stream) return;\n push(msg.stream);\n });\n\n // An abort wakes the pull loop out of its idle `await`; the loop then throws.\n const onAbort = () => {\n const w = wake;\n wake = null;\n w?.();\n };\n if (signal) signal.addEventListener('abort', onAbort);\n\n try {\n if (signal?.aborted) throw new StreamError('aborted', 'stream aborted before start');\n transport.send({ type, method, params, msgId, stream: true });\n started = true;\n while (true) {\n if (signal?.aborted) throw new StreamError('aborted', 'stream aborted');\n if (queue.length === 0) {\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n continue;\n }\n const frame = queue.shift() as StreamFrame;\n if (frame.kind === 'event') {\n yield frame.value as T;\n } else if (frame.kind === 'done') {\n settled = true;\n return frame.value as R;\n } else {\n settled = true;\n throw new StreamError(frame.code, frame.message);\n }\n }\n } finally {\n unsubscribe();\n if (signal) signal.removeEventListener('abort', onAbort);\n // Consumer stopped pulling before a terminal frame (early break/return, or the\n // signal aborted): tell the host to stop the in-flight generation + billing.\n if (started && !settled) transport.cancel?.({ type, msgId, cancel: true });\n }\n}\n\n// The real sandbox transport, built from the bundler messageBus helpers. `cancel`\n// rides the same messageBus as `send` — a `{type, msgId, cancel:true}` frame the\n// host dispatcher routes to the in-flight generator's AbortController.\nconst bundlerTransport: StreamTransport = {\n send: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n subscribe: (type, handler) =>\n addListener(type, (msg) => handler(msg as { msgId?: number; stream?: StreamFrame })),\n cancel: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n};\n\n/**\n * Consume an elevated streaming protocol method from app code.\n *\n * `for await (const ev of protocolStream('protocol-contribute', 'run', [opts])) …`\n *\n * Pass `signal` to abort the stream (and the host's in-flight work) mid-flight.\n */\nexport function protocolStream<T = unknown, R = unknown>(\n protocolName: string,\n method: string,\n params: unknown[],\n signal?: AbortSignal\n): AsyncGenerator<T, R, void> {\n return consumeStream<T, R>(bundlerTransport, protocolName, method, params, undefined, signal);\n}\n"],"mappings":"AAUA,SAAS,aAAa,mBAAmB;AA8BlC,MAAM,oBAAoB,MAAM;AAAA,EAErC,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAI,gBAAgB;AACpB,MAAM,YAAY,MAAc;AAI9B,mBAAiB,gBAAgB,KAAK,OAAO;AAC7C,SAAO;AACT;AAeA,gBAAuB,cACrB,WACA,MACA,QACA,QACA,QAAgB,UAAU,GAC1B,QAC4B;AAC5B,QAAM,QAAuB,CAAC;AAC9B,MAAI,OAA4B;AAIhC,MAAI,UAAU;AAGd,MAAI,UAAU;AACd,QAAM,OAAO,CAAC,UAAuB;AACnC,UAAM,KAAK,KAAK;AAChB,UAAM,IAAI;AACV,WAAO;AACP,QAAI;AAAA,EACN;AAEA,QAAM,cAAc,UAAU,UAAU,MAAM,CAAC,QAAQ;AACrD,QAAI,IAAI,UAAU,SAAS,CAAC,IAAI,OAAQ;AACxC,SAAK,IAAI,MAAM;AAAA,EACjB,CAAC;AAGD,QAAM,UAAU,MAAM;AACpB,UAAM,IAAI;AACV,WAAO;AACP,QAAI;AAAA,EACN;AACA,MAAI,OAAQ,QAAO,iBAAiB,SAAS,OAAO;AAEpD,MAAI;AACF,QAAI,QAAQ,QAAS,OAAM,IAAI,YAAY,WAAW,6BAA6B;AACnF,cAAU,KAAK,EAAE,MAAM,QAAQ,QAAQ,OAAO,QAAQ,KAAK,CAAC;AAC5D,cAAU;AACV,WAAO,MAAM;AACX,UAAI,QAAQ,QAAS,OAAM,IAAI,YAAY,WAAW,gBAAgB;AACtE,UAAI,MAAM,WAAW,GAAG;AACtB,cAAM,IAAI,QAAc,CAAC,YAAY;AACnC,iBAAO;AAAA,QACT,CAAC;AACD;AAAA,MACF;AACA,YAAM,QAAQ,MAAM,MAAM;AAC1B,UAAI,MAAM,SAAS,SAAS;AAC1B,cAAM,MAAM;AAAA,MACd,WAAW,MAAM,SAAS,QAAQ;AAChC,kBAAU;AACV,eAAO,MAAM;AAAA,MACf,OAAO;AACL,kBAAU;AACV,cAAM,IAAI,YAAY,MAAM,MAAM,MAAM,OAAO;AAAA,MACjD;AAAA,IACF;AAAA,EACF,UAAE;AACA,gBAAY;AACZ,QAAI,OAAQ,QAAO,oBAAoB,SAAS,OAAO;AAGvD,QAAI,WAAW,CAAC,QAAS,WAAU,SAAS,EAAE,MAAM,OAAO,QAAQ,KAAK,CAAC;AAAA,EAC3E;AACF;AAKA,MAAM,mBAAoC;AAAA,EACxC,MAAM,CAAC,QAAQ,YAAY,IAAI,MAAM,GAAyC;AAAA,EAC9E,WAAW,CAAC,MAAM,YAChB,YAAY,MAAM,CAAC,QAAQ,QAAQ,GAA+C,CAAC;AAAA,EACrF,QAAQ,CAAC,QAAQ,YAAY,IAAI,MAAM,GAAyC;AAClF;AASO,SAAS,eACd,cACA,QACA,QACA,QAC4B;AAC5B,SAAO,cAAoB,kBAAkB,cAAc,QAAQ,QAAQ,QAAW,MAAM;AAC9F;","names":[]}
1
+ {"version":3,"sources":["../src/protocolStream.ts"],"sourcesContent":["// SDK-side consumer for the host streaming transport (UI_AS_APPS_SPEC §5.1).\n//\n// The host `pumpGenerator` emits, per request msgId, a run of `stream.event`\n// frames terminated by one `stream.done` (with the return value) or `stream.error`\n// frame. This reassembles that run into an AsyncGenerator: each `event` is a\n// `yield`, the `done` value is the generator's `return`, an `error` is a `throw`.\n//\n// `consumeStream` takes an injected `StreamTransport` so it's unit-tested with a\n// fake send/subscribe — no bundler. `protocolStream`/`contribute` below wire it to\n// the real sandbox messageBus via sandboxUtils.\nimport { addListener, sendMessage } from './sandboxUtils';\n\n/** One frame of a host stream: an `event` value, the terminal `done` value, or an `error`. */\nexport type StreamFrame =\n | { kind: 'event'; value: unknown }\n | { kind: 'done'; value: unknown }\n | { kind: 'error'; code: string; message: string };\n\n/** The send/subscribe transport {@link consumeStream} drives (injected so it can be faked in tests). */\nexport interface StreamTransport {\n // Fire the request that starts the stream. The host replies with frames tagged\n // by the same `msgId`.\n send: (msg: { type: string; method: string; params: unknown[]; msgId: number; stream: true }) => void;\n // Subscribe to inbound frames for `type`; returns an unsubscribe.\n subscribe: (\n type: string,\n handler: (msg: { msgId?: number; stream?: StreamFrame }) => void\n ) => () => void;\n // Tell the host to STOP the stream early — abort the in-flight generation (and,\n // for `llm:chat`, the upstream provider fetch so it stops BILLING). Sent when the\n // consumer bails before a terminal frame: an early `break`/`return` out of the\n // `for await`, or an `AbortSignal` firing. Carries the same `(type, msgId)` the\n // host tagged its frames with, so the host aborts the matching generator\n // (LLM_AND_AGENTS_SPEC §3.3 \"abort the in-flight LLM request\"). Optional — a\n // transport predating the cancel frame simply omits it and the old behavior\n // (host runs to completion) stands.\n cancel?: (msg: { type: string; msgId: number; cancel: true }) => void;\n}\n\n/** Thrown when a stream ends in an `error` frame; carries the host's `code`. */\nexport class StreamError extends Error {\n code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = 'StreamError';\n this.code = code;\n }\n}\n\nlet streamCounter = 0;\nconst nextMsgId = (): number => {\n // Distinct from the bundler's own protocolRequest counter space is unnecessary —\n // frames are filtered by (type, msgId, stream) so a collision with a one-shot\n // reply (which has `result`, not `stream`) can't be misread.\n streamCounter = (streamCounter + 1) % Number.MAX_SAFE_INTEGER;\n return streamCounter;\n};\n\n/**\n * Drive one streamed request to completion over an injected transport.\n *\n * Yields each event value; returns the `done` value; throws `StreamError` on an\n * error frame. Always unsubscribes (via the generator's `finally`) so an early\n * `break` in the consumer doesn't leak the listener.\n *\n * `signal` wires a caller {@link AbortSignal} to mid-stream cancellation: when it\n * fires (or the consumer `break`s before a terminal frame), the `finally` sends a\n * `cancel` frame back over `transport.cancel` so the HOST stops generating — without\n * it, aborting only stops the app-side iterator while the upstream provider keeps\n * streaming and BILLING (LLM_AND_AGENTS_SPEC §3.3, R3-224 / adversarial F2).\n */\nexport async function* consumeStream<T = unknown, R = unknown>(\n transport: StreamTransport,\n type: string,\n method: string,\n params: unknown[],\n msgId: number = nextMsgId(),\n signal?: AbortSignal\n): AsyncGenerator<T, R, void> {\n const queue: StreamFrame[] = [];\n let wake: (() => void) | null = null;\n // True once a terminal (`done`/`error`) frame arrived — so the `finally` knows the\n // host already stopped and must NOT send a redundant cancel. Left false when the\n // consumer bails early or the signal aborts (the two cases that DO need a cancel).\n let settled = false;\n // True once the request frame went out. A cancel is only meaningful for a stream\n // the host actually started — an abort BEFORE `send` sends nothing to cancel.\n let started = false;\n const push = (frame: StreamFrame) => {\n queue.push(frame);\n const w = wake;\n wake = null;\n w?.();\n };\n\n const unsubscribe = transport.subscribe(type, (msg) => {\n if (msg.msgId !== msgId || !msg.stream) return;\n push(msg.stream);\n });\n\n // An abort wakes the pull loop out of its idle `await`; the loop then throws.\n const onAbort = () => {\n const w = wake;\n wake = null;\n w?.();\n };\n if (signal) signal.addEventListener('abort', onAbort);\n\n try {\n if (signal?.aborted) throw new StreamError('aborted', 'stream aborted before start');\n transport.send({ type, method, params, msgId, stream: true });\n started = true;\n while (true) {\n if (signal?.aborted) throw new StreamError('aborted', 'stream aborted');\n if (queue.length === 0) {\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n continue;\n }\n const frame = queue.shift() as StreamFrame;\n if (frame.kind === 'event') {\n yield frame.value as T;\n } else if (frame.kind === 'done') {\n settled = true;\n return frame.value as R;\n } else {\n settled = true;\n throw new StreamError(frame.code, frame.message);\n }\n }\n } finally {\n unsubscribe();\n if (signal) signal.removeEventListener('abort', onAbort);\n // Consumer stopped pulling before a terminal frame (early break/return, or the\n // signal aborted): tell the host to stop the in-flight generation + billing.\n if (started && !settled) transport.cancel?.({ type, msgId, cancel: true });\n }\n}\n\n// The real sandbox transport, built from the bundler messageBus helpers. `cancel`\n// rides the same messageBus as `send` — a `{type, msgId, cancel:true}` frame the\n// host dispatcher routes to the in-flight generator's AbortController.\nconst bundlerTransport: StreamTransport = {\n send: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n subscribe: (type, handler) =>\n addListener(type, (msg) => handler(msg as { msgId?: number; stream?: StreamFrame })),\n cancel: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n};\n\n/**\n * Consume an elevated streaming protocol method from app code.\n *\n * `for await (const ev of protocolStream('protocol-contribute', 'run', [opts])) …`\n *\n * Pass `signal` to abort the stream (and the host's in-flight work) mid-flight.\n */\nexport function protocolStream<T = unknown, R = unknown>(\n protocolName: string,\n method: string,\n params: unknown[],\n signal?: AbortSignal\n): AsyncGenerator<T, R, void> {\n return consumeStream<T, R>(bundlerTransport, protocolName, method, params, undefined, signal);\n}\n"],"mappings":";AAUA,SAAS,aAAa,mBAAmB;AA8BlC,MAAM,oBAAoB,MAAM;AAAA,EAErC,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAI,gBAAgB;AACpB,MAAM,YAAY,MAAc;AAI9B,mBAAiB,gBAAgB,KAAK,OAAO;AAC7C,SAAO;AACT;AAeA,gBAAuB,cACrB,WACA,MACA,QACA,QACA,QAAgB,UAAU,GAC1B,QAC4B;AAC5B,QAAM,QAAuB,CAAC;AAC9B,MAAI,OAA4B;AAIhC,MAAI,UAAU;AAGd,MAAI,UAAU;AACd,QAAM,OAAO,CAAC,UAAuB;AACnC,UAAM,KAAK,KAAK;AAChB,UAAM,IAAI;AACV,WAAO;AACP,QAAI;AAAA,EACN;AAEA,QAAM,cAAc,UAAU,UAAU,MAAM,CAAC,QAAQ;AACrD,QAAI,IAAI,UAAU,SAAS,CAAC,IAAI,OAAQ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AAW,MAAM;AAC9F;","names":[]}
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  import { useEffect, useState } from "react";
2
3
  import { sendMessage as defaultSend, addListener as defaultAddListener } from "./sandboxUtils";
3
4
  function createPushChannel(opts, transport = { sendMessage: defaultSend, addListener: defaultAddListener }) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pushChannel.ts"],"sourcesContent":["// Generic host→sandbox state channel read over the TRANSPORT\n// (SDK_PACKAGING_SPEC §4, expose-transport). The host pushes a `pushType`\n// message whenever the value changes and answers a `requestType` poll with the\n// current value — gated per-frame by the read ACL (site-main channelBridge.ts /\n// channelRouter). Historically the SDK read these values off injected sandbox\n// service objects (`module.evaluation.module.bundler.auth` etc.); this caches\n// the latest value SDK-side instead, so the SDK is self-contained and the\n// bundler services can eventually be retired.\n//\n// Every state helper (formFactor, auth, editorContext, theme, catalog) is a thin\n// wrapper over one of these — the get / onChange / use trio is identical.\nimport { useEffect, useState } from 'react';\nimport { sendMessage as defaultSend, addListener as defaultAddListener } from './sandboxUtils';\n\nexport interface PushChannel<T> {\n /** Pollable snapshot of the current value. */\n get(): T;\n /** Subscribe; invoked immediately with the current value, then on every change. Returns unsubscribe. */\n onChange(listener: (value: T) => void): () => void;\n /** React hook returning the current value, re-rendering on change. */\n use(): T;\n}\n\n/** Injectable transport — defaults to the real one; overridden in tests. */\nexport interface ChannelTransport {\n sendMessage: (type: string, data?: Record<string, unknown>) => void;\n addListener: (type: string, handler: (msg: Record<string, unknown>) => void) => () => void;\n}\n\nexport function createPushChannel<T>(\n opts: {\n /** Host→sandbox push message type (e.g. `form-factor`). */\n pushType: string;\n /** Poll message type the SDK sends to pull the current value (e.g. `request-form-factor`). */\n requestType?: string;\n /** Value assumed before the host answers — also the value when the app may not read the channel. */\n initial: T;\n /** Extract + validate the value from a push message; return `undefined` to ignore the message. */\n parse: (msg: Record<string, unknown>) => T | undefined;\n },\n transport: ChannelTransport = { sendMessage: defaultSend, addListener: defaultAddListener },\n): PushChannel<T> {\n let current = opts.initial;\n const listeners = new Set<(value: T) => void>();\n let started = false;\n\n // Lazily start on first read: register the push listener + send one poll, so a\n // late-mounting app still gets the current value. A channel the app may not\n // read is simply never answered → `initial` stands.\n const start = () => {\n if (started) return;\n started = true;\n transport.addListener(opts.pushType, (msg) => {\n const next = opts.parse(msg);\n if (next !== undefined) {\n current = next;\n listeners.forEach((l) => l(current));\n }\n });\n if (opts.requestType) {\n try {\n transport.sendMessage(opts.requestType);\n } catch {\n /* transport not ready — a proactive push will still arrive */\n }\n }\n };\n\n const get = (): T => {\n start();\n return current;\n };\n\n const onChange = (listener: (value: T) => void): (() => void) => {\n start();\n listeners.add(listener);\n listener(current);\n return () => {\n listeners.delete(listener);\n };\n };\n\n const use = (): T => {\n const [value, setValue] = useState<T>(get);\n useEffect(() => onChange(setValue), []);\n return value;\n };\n\n return { get, onChange, use };\n}\n"],"mappings":"AAWA,SAAS,WAAW,gBAAgB;AACpC,SAAS,eAAe,aAAa,eAAe,0BAA0B;AAiBvE,SAAS,kBACd,MAUA,YAA8B,EAAE,aAAa,aAAa,aAAa,mBAAmB,GAC1E;AAChB,MAAI,UAAU,KAAK;AACnB,QAAM,YAAY,oBAAI,IAAwB;AAC9C,MAAI,UAAU;AAKd,QAAM,QAAQ,MAAM;AAClB,QAAI,QAAS;AACb,cAAU;AACV,cAAU,YAAY,KAAK,UAAU,CAAC,QAAQ;AAC5C,YAAM,OAAO,KAAK,MAAM,GAAG;AAC3B,UAAI,SAAS,QAAW;AACtB,kBAAU;AACV,kBAAU,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;AAAA,MACrC;AAAA,IACF,CAAC;AACD,QAAI,KAAK,aAAa;AACpB,UAAI;AACF,kBAAU,YAAY,KAAK,WAAW;AAAA,MACxC,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AAEA,QAAM,MAAM,MAAS;AACnB,UAAM;AACN,WAAO;AAAA,EACT;AAEA,QAAM,WAAW,CAAC,aAA+C;AAC/D,UAAM;AACN,cAAU,IAAI,QAAQ;AACtB,aAAS,OAAO;AAChB,WAAO,MAAM;AACX,gBAAU,OAAO,QAAQ;AAAA,IAC3B;AAAA,EACF;AAEA,QAAM,MAAM,MAAS;AACnB,UAAM,CAAC,OAAO,QAAQ,IAAI,SAAY,GAAG;AACzC,cAAU,MAAM,SAAS,QAAQ,GAAG,CAAC,CAAC;AACtC,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,KAAK,UAAU,IAAI;AAC9B;","names":[]}
1
+ {"version":3,"sources":["../src/pushChannel.ts"],"sourcesContent":["// Generic host→sandbox state channel read over the TRANSPORT\n// (SDK_PACKAGING_SPEC §4, expose-transport). The host pushes a `pushType`\n// message whenever the value changes and answers a `requestType` poll with the\n// current value — gated per-frame by the read ACL (site-main channelBridge.ts /\n// channelRouter). Historically the SDK read these values off injected sandbox\n// service objects (`module.evaluation.module.bundler.auth` etc.); this caches\n// the latest value SDK-side instead, so the SDK is self-contained and the\n// bundler services can eventually be retired.\n//\n// Every state helper (formFactor, auth, editorContext, theme, catalog) is a thin\n// wrapper over one of these — the get / onChange / use trio is identical.\nimport { useEffect, useState } from 'react';\nimport { sendMessage as defaultSend, addListener as defaultAddListener } from './sandboxUtils';\n\nexport interface PushChannel<T> {\n /** Pollable snapshot of the current value. */\n get(): T;\n /** Subscribe; invoked immediately with the current value, then on every change. Returns unsubscribe. */\n onChange(listener: (value: T) => void): () => void;\n /** React hook returning the current value, re-rendering on change. */\n use(): T;\n}\n\n/** Injectable transport — defaults to the real one; overridden in tests. */\nexport interface ChannelTransport {\n sendMessage: (type: string, data?: Record<string, unknown>) => void;\n addListener: (type: string, handler: (msg: Record<string, unknown>) => void) => () => void;\n}\n\nexport function createPushChannel<T>(\n opts: {\n /** Host→sandbox push message type (e.g. `form-factor`). */\n pushType: string;\n /** Poll message type the SDK sends to pull the current value (e.g. `request-form-factor`). */\n requestType?: string;\n /** Value assumed before the host answers — also the value when the app may not read the channel. */\n initial: T;\n /** Extract + validate the value from a push message; return `undefined` to ignore the message. */\n parse: (msg: Record<string, unknown>) => T | undefined;\n },\n transport: ChannelTransport = { sendMessage: defaultSend, addListener: defaultAddListener },\n): PushChannel<T> {\n let current = opts.initial;\n const listeners = new Set<(value: T) => void>();\n let started = false;\n\n // Lazily start on first read: register the push listener + send one poll, so a\n // late-mounting app still gets the current value. A channel the app may not\n // read is simply never answered → `initial` stands.\n const start = () => {\n if (started) return;\n started = true;\n transport.addListener(opts.pushType, (msg) => {\n const next = opts.parse(msg);\n if (next !== undefined) {\n current = next;\n listeners.forEach((l) => l(current));\n }\n });\n if (opts.requestType) {\n try {\n transport.sendMessage(opts.requestType);\n } catch {\n /* transport not ready — a proactive push will still arrive */\n }\n }\n };\n\n const get = (): T => {\n start();\n return current;\n };\n\n const onChange = (listener: (value: T) => void): (() => void) => {\n start();\n listeners.add(listener);\n listener(current);\n return () => {\n listeners.delete(listener);\n };\n };\n\n const use = (): T => {\n const [value, setValue] = useState<T>(get);\n useEffect(() => onChange(setValue), []);\n return value;\n };\n\n return { get, onChange, use };\n}\n"],"mappings":";AAWA,SAAS,WAAW,gBAAgB;AACpC,SAAS,eAAe,aAAa,eAAe,0BAA0B;AAiBvE,SAAS,kBACd,MAUA,YAA8B,EAAE,aAAa,aAAa,aAAa,mBAAmB,GAC1E;AAChB,MAAI,UAAU,KAAK;AACnB,QAAM,YAAY,oBAAI,IAAwB;AAC9C,MAAI,UAAU;AAKd,QAAM,QAAQ,MAAM;AAClB,QAAI,QAAS;AACb,cAAU;AACV,cAAU,YAAY,KAAK,UAAU,CAAC,QAAQ;AAC5C,YAAM,OAAO,KAAK,MAAM,GAAG;AAC3B,UAAI,SAAS,QAAW;AACtB,kBAAU;AACV,kBAAU,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;AAAA,MACrC;AAAA,IACF,CAAC;AACD,QAAI,KAAK,aAAa;AACpB,UAAI;AACF,kBAAU,YAAY,KAAK,WAAW;AAAA,MACxC,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AAEA,QAAM,MAAM,MAAS;AACnB,UAAM;AACN,WAAO;AAAA,EACT;AAEA,QAAM,WAAW,CAAC,aAA+C;AAC/D,UAAM;AACN,cAAU,IAAI,QAAQ;AACtB,aAAS,OAAO;AAChB,WAAO,MAAM;AACX,gBAAU,OAAO,QAAQ;AAAA,IAC3B;AAAA,EACF;AAEA,QAAM,MAAM,MAAS;AACnB,UAAM,CAAC,OAAO,QAAQ,IAAI,SAAY,GAAG;AACzC,cAAU,MAAM,SAAS,QAAQ,GAAG,CAAC,CAAC;AACtC,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,KAAK,UAAU,IAAI;AAC9B;","names":[]}
package/dist/ready.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  import { sendMessage as defaultSend } from "./sandboxUtils";
2
3
  const realNow = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
3
4
  const defaultDeps = { send: defaultSend, now: realNow };
package/dist/ready.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ready.ts"],"sourcesContent":["// The `ir.interactive` boot signal — the app-facing `reportReady()` / `onReady()` /\n// `getReadyState()` surface (LOAD_PROFILING_SPEC §3.1, R3-46). This closes the\n// \"existing SDK boot signal\" that `UI_AS_APPS_SPEC §6.2` referenced but never\n// defined.\n//\n// The runtime marks `ir.interactive` when the app's root render commits. An app\n// whose USEFULLY-interactive moment is later than first commit (e.g. after an\n// initial data load) calls `reportReady()` to DELAY the signal — which, per LP2-3,\n// can only ever push interactive later, never earlier than the commit (the host\n// resolves `max(commit, reportReady)`; see `resolveInteractive`). `onReady` /\n// `getReadyState` expose the report state in the same poll+subscribe shape as\n// `auth` / `mounts`.\n\nimport { sendMessage as defaultSend } from \"./sandboxUtils\";\n\n/** The app's `reportReady()` state, mirrored by {@link onReady}/{@link getReadyState}. */\nexport interface ReadyState {\n /** Whether the app has called `reportReady()`. */\n reported: boolean;\n /** The app-reported timestamp (`performance.now()`), if it has reported. */\n reportedAt?: number;\n}\n\ninterface ReadyDeps {\n send: (type: string, data?: Record<string, unknown>) => void;\n now: () => number;\n}\n\nconst realNow = (): number =>\n typeof performance !== \"undefined\" && typeof performance.now === \"function\"\n ? performance.now()\n : Date.now();\n\nconst defaultDeps: ReadyDeps = { send: defaultSend, now: realNow };\n\nlet deps: ReadyDeps = defaultDeps;\nlet state: ReadyState = { reported: false };\nconst listeners = new Set<(s: ReadyState) => void>();\n\n/**\n * Signal that the app is usefully interactive (e.g. after an initial data load).\n * IDEMPOTENT — only the FIRST call counts; later calls are ignored. Forwards the\n * report to the runtime (`ir-report-ready`) so the host can resolve\n * `ir.interactive = max(rootRenderCommit, reportedAt)` (LP2-3) — calling it before\n * the root render commits can only delay the signal, never advance it.\n *\n * UX contract (LOADING_UX_SPEC §9.1): calling this tells the host *\"keep your\n * loading skeleton up; I am not done yet\"* — the host holds the §3 reveal until\n * this call (or the load budget). Call it ONCE, when the first USEFULLY-interactive\n * frame is on screen — not at mount, and not after every async settle. An app that\n * never calls it reveals automatically at the root-render commit (the default path).\n */\nexport function reportReady(): void {\n if (state.reported) return;\n state = { reported: true, reportedAt: deps.now() };\n try {\n deps.send(\"ir-report-ready\", { at: state.reportedAt });\n } catch {\n /* transport not ready — the runtime still marks interactive at root commit */\n }\n for (const l of listeners) l(state);\n}\n\n/** Pollable snapshot of the report state. */\nexport function getReadyState(): ReadyState {\n return state;\n}\n\n/**\n * Subscribe to the ready signal. Invoked immediately with the current state (so a\n * late subscriber after `reportReady()` still fires) and again whenever it reports.\n * Returns an unsubscribe.\n */\nexport function onReady(listener: (s: ReadyState) => void): () => void {\n listeners.add(listener);\n listener(state);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/** Test seam: override the transport/clock. */\nexport function __setReadyDeps(d: Partial<ReadyDeps>): void {\n deps = { ...defaultDeps, ...d };\n}\n\n/** Test seam: reset module state between cases. */\nexport function __resetReady(): void {\n deps = defaultDeps;\n state = { reported: false };\n listeners.clear();\n}\n"],"mappings":"AAaA,SAAS,eAAe,mBAAmB;AAe3C,MAAM,UAAU,MACd,OAAO,gBAAgB,eAAe,OAAO,YAAY,QAAQ,aAC7D,YAAY,IAAI,IAChB,KAAK,IAAI;AAEf,MAAM,cAAyB,EAAE,MAAM,aAAa,KAAK,QAAQ;AAEjE,IAAI,OAAkB;AACtB,IAAI,QAAoB,EAAE,UAAU,MAAM;AAC1C,MAAM,YAAY,oBAAI,IAA6B;AAe5C,SAAS,cAAoB;AAClC,MAAI,MAAM,SAAU;AACpB,UAAQ,EAAE,UAAU,MAAM,YAAY,KAAK,IAAI,EAAE;AACjD,MAAI;AACF,SAAK,KAAK,mBAAmB,EAAE,IAAI,MAAM,WAAW,CAAC;AAAA,EACvD,QAAQ;AAAA,EAER;AACA,aAAW,KAAK,UAAW,GAAE,KAAK;AACpC;AAGO,SAAS,gBAA4B;AAC1C,SAAO;AACT;AAOO,SAAS,QAAQ,UAA+C;AACrE,YAAU,IAAI,QAAQ;AACtB,WAAS,KAAK;AACd,SAAO,MAAM;AACX,cAAU,OAAO,QAAQ;AAAA,EAC3B;AACF;AAGO,SAAS,eAAe,GAA6B;AAC1D,SAAO,EAAE,GAAG,aAAa,GAAG,EAAE;AAChC;AAGO,SAAS,eAAqB;AACnC,SAAO;AACP,UAAQ,EAAE,UAAU,MAAM;AAC1B,YAAU,MAAM;AAClB;","names":[]}
1
+ {"version":3,"sources":["../src/ready.ts"],"sourcesContent":["// The `ir.interactive` boot signal — the app-facing `reportReady()` / `onReady()` /\n// `getReadyState()` surface (LOAD_PROFILING_SPEC §3.1, R3-46). This closes the\n// \"existing SDK boot signal\" that `UI_AS_APPS_SPEC §6.2` referenced but never\n// defined.\n//\n// The runtime marks `ir.interactive` when the app's root render commits. An app\n// whose USEFULLY-interactive moment is later than first commit (e.g. after an\n// initial data load) calls `reportReady()` to DELAY the signal — which, per LP2-3,\n// can only ever push interactive later, never earlier than the commit (the host\n// resolves `max(commit, reportReady)`; see `resolveInteractive`). `onReady` /\n// `getReadyState` expose the report state in the same poll+subscribe shape as\n// `auth` / `mounts`.\n\nimport { sendMessage as defaultSend } from \"./sandboxUtils\";\n\n/** The app's `reportReady()` state, mirrored by {@link onReady}/{@link getReadyState}. */\nexport interface ReadyState {\n /** Whether the app has called `reportReady()`. */\n reported: boolean;\n /** The app-reported timestamp (`performance.now()`), if it has reported. */\n reportedAt?: number;\n}\n\ninterface ReadyDeps {\n send: (type: string, data?: Record<string, unknown>) => void;\n now: () => number;\n}\n\nconst realNow = (): number =>\n typeof performance !== \"undefined\" && typeof performance.now === \"function\"\n ? performance.now()\n : Date.now();\n\nconst defaultDeps: ReadyDeps = { send: defaultSend, now: realNow };\n\nlet deps: ReadyDeps = defaultDeps;\nlet state: ReadyState = { reported: false };\nconst listeners = new Set<(s: ReadyState) => void>();\n\n/**\n * Signal that the app is usefully interactive (e.g. after an initial data load).\n * IDEMPOTENT — only the FIRST call counts; later calls are ignored. Forwards the\n * report to the runtime (`ir-report-ready`) so the host can resolve\n * `ir.interactive = max(rootRenderCommit, reportedAt)` (LP2-3) — calling it before\n * the root render commits can only delay the signal, never advance it.\n *\n * UX contract (LOADING_UX_SPEC §9.1): calling this tells the host *\"keep your\n * loading skeleton up; I am not done yet\"* — the host holds the §3 reveal until\n * this call (or the load budget). Call it ONCE, when the first USEFULLY-interactive\n * frame is on screen — not at mount, and not after every async settle. An app that\n * never calls it reveals automatically at the root-render commit (the default path).\n */\nexport function reportReady(): void {\n if (state.reported) return;\n state = { reported: true, reportedAt: deps.now() };\n try {\n deps.send(\"ir-report-ready\", { at: state.reportedAt });\n } catch {\n /* transport not ready — the runtime still marks interactive at root commit */\n }\n for (const l of listeners) l(state);\n}\n\n/** Pollable snapshot of the report state. */\nexport function getReadyState(): ReadyState {\n return state;\n}\n\n/**\n * Subscribe to the ready signal. Invoked immediately with the current state (so a\n * late subscriber after `reportReady()` still fires) and again whenever it reports.\n * Returns an unsubscribe.\n */\nexport function onReady(listener: (s: ReadyState) => void): () => void {\n listeners.add(listener);\n listener(state);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/** Test seam: override the transport/clock. */\nexport function __setReadyDeps(d: Partial<ReadyDeps>): void {\n deps = { ...defaultDeps, ...d };\n}\n\n/** Test seam: reset module state between cases. */\nexport function __resetReady(): void {\n deps = defaultDeps;\n state = { reported: false };\n listeners.clear();\n}\n"],"mappings":";AAaA,SAAS,eAAe,mBAAmB;AAe3C,MAAM,UAAU,MACd,OAAO,gBAAgB,eAAe,OAAO,YAAY,QAAQ,aAC7D,YAAY,IAAI,IAChB,KAAK,IAAI;AAEf,MAAM,cAAyB,EAAE,MAAM,aAAa,KAAK,QAAQ;AAEjE,IAAI,OAAkB;AACtB,IAAI,QAAoB,EAAE,UAAU,MAAM;AAC1C,MAAM,YAAY,oBAAI,IAA6B;AAe5C,SAAS,cAAoB;AAClC,MAAI,MAAM,SAAU;AACpB,UAAQ,EAAE,UAAU,MAAM,YAAY,KAAK,IAAI,EAAE;AACjD,MAAI;AACF,SAAK,KAAK,mBAAmB,EAAE,IAAI,MAAM,WAAW,CAAC;AAAA,EACvD,QAAQ;AAAA,EAER;AACA,aAAW,KAAK,UAAW,GAAE,KAAK;AACpC;AAGO,SAAS,gBAA4B;AAC1C,SAAO;AACT;AAOO,SAAS,QAAQ,UAA+C;AACrE,YAAU,IAAI,QAAQ;AACtB,WAAS,KAAK;AACd,SAAO,MAAM;AACX,cAAU,OAAO,QAAQ;AAAA,EAC3B;AACF;AAGO,SAAS,eAAe,GAA6B;AAC1D,SAAO,EAAE,GAAG,aAAa,GAAG,EAAE;AAChC;AAGO,SAAS,eAAqB;AACnC,SAAO;AACP,UAAQ,EAAE,UAAU,MAAM;AAC1B,YAAU,MAAM;AAClB;","names":[]}
package/dist/region.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  import { useEffect, useState } from "react";
2
3
  import { getHostRuntime } from "./hostRuntime";
3
4
  const getRegion = () => getHostRuntime()?.region ?? null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/region.ts"],"sourcesContent":["// Region-awareness (UI_AS_APPS_SPEC §4.1). The host can mount the SAME app in more\n// than one chrome region — e.g. the agents activity puts one app in BOTH the panel\n// slot (`panel.agent`, the conversation list) and the stage slot\n// (`stage.conversation`, the selected conversation). `getRegion()` lets that one app\n// tell the slots apart and render the right view.\n//\n// This is descriptive only: the region id is a non-secret string the host already\n// knows. It grants nothing and gates nothing — it just names where the app is\n// mounted. The host reports it on the §4 discovery global beside `appMountPath`.\n\nimport { useEffect, useState } from 'react';\nimport { getHostRuntime } from './hostRuntime';\n\n/**\n * The chrome region this app instance is mounted in (e.g. `\"panel.agent\"`,\n * `\"stage.conversation\"`), or `null` when unknown — a standalone app, local\n * `vite dev`, or an older host that doesn't report it.\n */\nexport const getRegion = (): string | null => getHostRuntime()?.region ?? null;\n\n/**\n * React hook form of {@link getRegion}. The region is fixed for an app instance's\n * lifetime, but the discovery global can arrive just after first paint, so this\n * re-reads once the host runtime's `ready` promise resolves.\n */\nexport const useRegion = (): string | null => {\n const [region, setRegion] = useState<string | null>(getRegion);\n useEffect(() => {\n if (region !== null) return;\n let live = true;\n void getHostRuntime()?.ready?.then(() => {\n if (live) setRegion(getRegion());\n });\n return () => {\n live = false;\n };\n }, [region]);\n return region;\n};\n"],"mappings":"AAUA,SAAS,WAAW,gBAAgB;AACpC,SAAS,sBAAsB;AAOxB,MAAM,YAAY,MAAqB,eAAe,GAAG,UAAU;AAOnE,MAAM,YAAY,MAAqB;AAC5C,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAwB,SAAS;AAC7D,YAAU,MAAM;AACd,QAAI,WAAW,KAAM;AACrB,QAAI,OAAO;AACX,SAAK,eAAe,GAAG,OAAO,KAAK,MAAM;AACvC,UAAI,KAAM,WAAU,UAAU,CAAC;AAAA,IACjC,CAAC;AACD,WAAO,MAAM;AACX,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AACX,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/region.ts"],"sourcesContent":["// Region-awareness (UI_AS_APPS_SPEC §4.1). The host can mount the SAME app in more\n// than one chrome region — e.g. the agents activity puts one app in BOTH the panel\n// slot (`panel.agent`, the conversation list) and the stage slot\n// (`stage.conversation`, the selected conversation). `getRegion()` lets that one app\n// tell the slots apart and render the right view.\n//\n// This is descriptive only: the region id is a non-secret string the host already\n// knows. It grants nothing and gates nothing — it just names where the app is\n// mounted. The host reports it on the §4 discovery global beside `appMountPath`.\n\nimport { useEffect, useState } from 'react';\nimport { getHostRuntime } from './hostRuntime';\n\n/**\n * The chrome region this app instance is mounted in (e.g. `\"panel.agent\"`,\n * `\"stage.conversation\"`), or `null` when unknown — a standalone app, local\n * `vite dev`, or an older host that doesn't report it.\n */\nexport const getRegion = (): string | null => getHostRuntime()?.region ?? null;\n\n/**\n * React hook form of {@link getRegion}. The region is fixed for an app instance's\n * lifetime, but the discovery global can arrive just after first paint, so this\n * re-reads once the host runtime's `ready` promise resolves.\n */\nexport const useRegion = (): string | null => {\n const [region, setRegion] = useState<string | null>(getRegion);\n useEffect(() => {\n if (region !== null) return;\n let live = true;\n void getHostRuntime()?.ready?.then(() => {\n if (live) setRegion(getRegion());\n });\n return () => {\n live = false;\n };\n }, [region]);\n return region;\n};\n"],"mappings":";AAUA,SAAS,WAAW,gBAAgB;AACpC,SAAS,sBAAsB;AAOxB,MAAM,YAAY,MAAqB,eAAe,GAAG,UAAU;AAOnE,MAAM,YAAY,MAAqB;AAC5C,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAwB,SAAS;AAC7D,YAAU,MAAM;AACd,QAAI,WAAW,KAAM;AACrB,QAAI,OAAO;AACX,SAAK,eAAe,GAAG,OAAO,KAAK,MAAM;AACvC,UAAI,KAAM,WAAU,UAAU,CAAC;AAAA,IACjC,CAAC;AACD,WAAO,MAAM;AACX,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AACX,SAAO;AACT;","names":[]}
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  const escapeForRegexp = (str) => str.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
2
3
  const WILDCARD_GROUP = "wild";
3
4
  const compileTemplate = (template) => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/routeMatch.ts"],"sourcesContent":["import type { RouteParams } from './RoutingSpec';\n\n// from: https://stackoverflow.com/a/63838890\nconst escapeForRegexp = (str: string): string => str.replace(/[.*+\\-?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n// Internal group name standing in for a `*` wildcard (which is not a valid JS\n// regex group identifier); remapped to the `*` param key after matching.\nconst WILDCARD_GROUP = 'wild';\n\n/**\n * Compile a path template to an anchored RegExp with named groups:\n * `:name` → one non-slash segment `*` → the rest (greedy)\n * A template with neither token is a literal exact match. Raw RegExp patterns\n * never reach here — they are the escape hatch, used as authored.\n */\nexport const compileTemplate = (template: string): RegExp => {\n const token = /(:[A-Za-z_][A-Za-z0-9_]*)|\\*/g;\n let src = '';\n let last = 0;\n let m: RegExpExecArray | null;\n while ((m = token.exec(template)) !== null) {\n src += escapeForRegexp(template.slice(last, m.index));\n src += m[1] ? `(?<${m[1].slice(1)}>[^/]+)` : `(?<${WILDCARD_GROUP}>.*)`;\n last = m.index + m[0].length;\n }\n src += escapeForRegexp(template.slice(last));\n return new RegExp(`^${src}$`);\n};\n\nconst templateCache = new Map<string, RegExp>();\n\n/** Resolve a pattern to a RegExp: templates are compiled (and cached), RegExp passes through. */\nexport const toRegExp = (pattern: string | RegExp): RegExp => {\n if (pattern instanceof RegExp) {\n return pattern;\n }\n let compiled = templateCache.get(pattern);\n if (!compiled) {\n compiled = compileTemplate(pattern);\n templateCache.set(pattern, compiled);\n }\n return compiled;\n};\n\n/**\n * Match a `sandboxPath` against a route pattern. Returns the named params on a\n * match (the `*` wildcard surfaces under the `'*'` key), or `null` otherwise.\n */\nexport const matchRoute = (pattern: string | RegExp, path: string): RouteParams | null => {\n const match = path.match(toRegExp(pattern));\n if (!match) {\n return null;\n }\n const params: RouteParams = {};\n for (const [key, value] of Object.entries(match.groups ?? {})) {\n if (value !== undefined) {\n params[key === WILDCARD_GROUP ? '*' : key] = value;\n }\n }\n return params;\n};\n"],"mappings":"AAGA,MAAM,kBAAkB,CAAC,QAAwB,IAAI,QAAQ,yBAAyB,MAAM;AAI5F,MAAM,iBAAiB;AAQhB,MAAM,kBAAkB,CAAC,aAA6B;AAC3D,QAAM,QAAQ;AACd,MAAI,MAAM;AACV,MAAI,OAAO;AACX,MAAI;AACJ,UAAQ,IAAI,MAAM,KAAK,QAAQ,OAAO,MAAM;AAC1C,WAAO,gBAAgB,SAAS,MAAM,MAAM,EAAE,KAAK,CAAC;AACpD,WAAO,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,YAAY,MAAM,cAAc;AACjE,WAAO,EAAE,QAAQ,EAAE,CAAC,EAAE;AAAA,EACxB;AACA,SAAO,gBAAgB,SAAS,MAAM,IAAI,CAAC;AAC3C,SAAO,IAAI,OAAO,IAAI,GAAG,GAAG;AAC9B;AAEA,MAAM,gBAAgB,oBAAI,IAAoB;AAGvC,MAAM,WAAW,CAAC,YAAqC;AAC5D,MAAI,mBAAmB,QAAQ;AAC7B,WAAO;AAAA,EACT;AACA,MAAI,WAAW,cAAc,IAAI,OAAO;AACxC,MAAI,CAAC,UAAU;AACb,eAAW,gBAAgB,OAAO;AAClC,kBAAc,IAAI,SAAS,QAAQ;AAAA,EACrC;AACA,SAAO;AACT;AAMO,MAAM,aAAa,CAAC,SAA0B,SAAqC;AACxF,QAAM,QAAQ,KAAK,MAAM,SAAS,OAAO,CAAC;AAC1C,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AACA,QAAM,SAAsB,CAAC;AAC7B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,UAAU,CAAC,CAAC,GAAG;AAC7D,QAAI,UAAU,QAAW;AACvB,aAAO,QAAQ,iBAAiB,MAAM,GAAG,IAAI;AAAA,IAC/C;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/routeMatch.ts"],"sourcesContent":["import type { RouteParams } from './RoutingSpec';\n\n// from: https://stackoverflow.com/a/63838890\nconst escapeForRegexp = (str: string): string => str.replace(/[.*+\\-?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n// Internal group name standing in for a `*` wildcard (which is not a valid JS\n// regex group identifier); remapped to the `*` param key after matching.\nconst WILDCARD_GROUP = 'wild';\n\n/**\n * Compile a path template to an anchored RegExp with named groups:\n * `:name` → one non-slash segment `*` → the rest (greedy)\n * A template with neither token is a literal exact match. Raw RegExp patterns\n * never reach here — they are the escape hatch, used as authored.\n */\nexport const compileTemplate = (template: string): RegExp => {\n const token = /(:[A-Za-z_][A-Za-z0-9_]*)|\\*/g;\n let src = '';\n let last = 0;\n let m: RegExpExecArray | null;\n while ((m = token.exec(template)) !== null) {\n src += escapeForRegexp(template.slice(last, m.index));\n src += m[1] ? `(?<${m[1].slice(1)}>[^/]+)` : `(?<${WILDCARD_GROUP}>.*)`;\n last = m.index + m[0].length;\n }\n src += escapeForRegexp(template.slice(last));\n return new RegExp(`^${src}$`);\n};\n\nconst templateCache = new Map<string, RegExp>();\n\n/** Resolve a pattern to a RegExp: templates are compiled (and cached), RegExp passes through. */\nexport const toRegExp = (pattern: string | RegExp): RegExp => {\n if (pattern instanceof RegExp) {\n return pattern;\n }\n let compiled = templateCache.get(pattern);\n if (!compiled) {\n compiled = compileTemplate(pattern);\n templateCache.set(pattern, compiled);\n }\n return compiled;\n};\n\n/**\n * Match a `sandboxPath` against a route pattern. Returns the named params on a\n * match (the `*` wildcard surfaces under the `'*'` key), or `null` otherwise.\n */\nexport const matchRoute = (pattern: string | RegExp, path: string): RouteParams | null => {\n const match = path.match(toRegExp(pattern));\n if (!match) {\n return null;\n }\n const params: RouteParams = {};\n for (const [key, value] of Object.entries(match.groups ?? {})) {\n if (value !== undefined) {\n params[key === WILDCARD_GROUP ? '*' : key] = value;\n }\n }\n return params;\n};\n"],"mappings":";AAGA,MAAM,kBAAkB,CAAC,QAAwB,IAAI,QAAQ,yBAAyB,MAAM;AAI5F,MAAM,iBAAiB;AAQhB,MAAM,kBAAkB,CAAC,aAA6B;AAC3D,QAAM,QAAQ;AACd,MAAI,MAAM;AACV,MAAI,OAAO;AACX,MAAI;AACJ,UAAQ,IAAI,MAAM,KAAK,QAAQ,OAAO,MAAM;AAC1C,WAAO,gBAAgB,SAAS,MAAM,MAAM,EAAE,KAAK,CAAC;AACpD,WAAO,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,YAAY,MAAM,cAAc;AACjE,WAAO,EAAE,QAAQ,EAAE,CAAC,EAAE;AAAA,EACxB;AACA,SAAO,gBAAgB,SAAS,MAAM,IAAI,CAAC;AAC3C,SAAO,IAAI,OAAO,IAAI,GAAG,GAAG;AAC9B;AAEA,MAAM,gBAAgB,oBAAI,IAAoB;AAGvC,MAAM,WAAW,CAAC,YAAqC;AAC5D,MAAI,mBAAmB,QAAQ;AAC7B,WAAO;AAAA,EACT;AACA,MAAI,WAAW,cAAc,IAAI,OAAO;AACxC,MAAI,CAAC,UAAU;AACb,eAAW,gBAAgB,OAAO;AAClC,kBAAc,IAAI,SAAS,QAAQ;AAAA,EACrC;AACA,SAAO;AACT;AAMO,MAAM,aAAa,CAAC,SAA0B,SAAqC;AACxF,QAAM,QAAQ,KAAK,MAAM,SAAS,OAAO,CAAC;AAC1C,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AACA,QAAM,SAAsB,CAAC;AAC7B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,UAAU,CAAC,CAAC,GAAG;AAC7D,QAAI,UAAU,QAAW;AACvB,aAAO,QAAQ,iBAAiB,MAAM,GAAG,IAAI;AAAA,IAC/C;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
package/dist/routing.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  import { jsx } from "react/jsx-runtime";
2
3
  import { use, useContext } from "react";
3
4
  import { sendMessage } from "./sandboxUtils";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/routing.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { use, useContext } from 'react';\n\nimport { sendMessage } from './sandboxUtils';\nimport { NavigationState, TinkerableContext } from './TinkerableContext';\nimport { RouteParams, RoutingRule, RoutingSpec } from './RoutingSpec';\nimport { matchRoute } from './routeMatch';\nimport { constructUrl, isAbsolutePath, parseTarget } from './urlUtils';\nimport { joinPaths } from './pathUtils';\n\n/** The result of matching a path: the winning {@link RoutingRule} plus its captured params. */\nexport type AppliedRoutingRule = {\n routingRule: RoutingRule,\n pathParameters?: Record<string, string>;\n}\n\n/** Build the full outer href for an in-app target (absolute `sandboxPath` or a\n * path relative to the current route), e.g. for an `href` attribute. */\nexport const useTinkerableLink = (newSandboxLocation: string) => {\n const { outerHref, navigationState: navigation } = use(TinkerableContext);\n let newNavigationState = parseTarget(newSandboxLocation, navigation);\n if (!isAbsolutePath(newSandboxLocation)) {\n newNavigationState.sandboxPath = joinPaths(navigation.sandboxPath, newSandboxLocation)\n } else {\n newNavigationState.sandboxPath = newSandboxLocation\n }\n return constructUrl(outerHref, newNavigationState);\n}\n\n/** Find the first rule in `routingSpec` whose pattern matches the current\n * `sandboxPath`, returning it with the captured params (or `undefined`). */\nexport const applyRoutingRule = (routingSpec:RoutingSpec, navigationState: NavigationState): AppliedRoutingRule | undefined => {\n const { sandboxPath } = navigationState;\n for (const routingRule of routingSpec.routes) {\n const pathParameters = matchRoute(routingRule.pattern, sandboxPath);\n if (pathParameters) {\n return { routingRule, pathParameters };\n }\n }\n return undefined;\n}\n\n/** Render a matched rule, passing params to a `component` and falling back to `element`/`reactNode`. */\nexport const renderRoute = (routingRule: RoutingRule, params: RouteParams): ReactNode => {\n if (routingRule.component) {\n const Component = routingRule.component;\n return <Component params={params} />;\n }\n return routingRule.element ?? routingRule.reactNode ?? null;\n};\n\n/** Render the route matched for the current location (set up by `boot`'s route table). */\nexport const Router = () => {\n const context = useContext(TinkerableContext);\n const {navigationState: {routingRule, pathParameters}} = context;\n if (!routingRule) {\n // TODO: better error\n throw new Error(`No route registered for path ${context.navigationState.sandboxPath}!`);\n }\n\n return renderRoute(routingRule, pathParameters ?? {});\n};\n\n/** Read the current route's matched params (`:name` segments and the `*` wildcard). */\nexport const useRouteParams = <T extends RouteParams = RouteParams>(): T =>\n (use(TinkerableContext).navigationState.pathParameters ?? {}) as T;\n\n/**\n * Read the current route: the matched rule's `name`, its `params`, the app-owned\n * `sandboxPath`, and the read-only platform prefix fields (`mode`, `provider`,\n * `namespace`, `repository`, `ref`) — e.g. to tell `/edit` from `/present`.\n */\nexport const useRoute = () => {\n const { navigationState } = use(TinkerableContext);\n const { routingRule, pathParameters, sandboxPath, mode, provider, namespace, repository, ref } = navigationState;\n return {\n name: routingRule?.name,\n params: (pathParameters ?? {}) as RouteParams,\n sandboxPath,\n mode,\n provider,\n namespace,\n repository,\n ref,\n };\n};\n\n\n/**\n * Navigate within the app. Messages the host to update the URL; the host then\n * pushes the new href back, which drives the actual route change.\n */\nexport const navigate = (target: string) => {\n console.log(`[Sandbox] Navigating to ${target}`)\n sendMessage('urlchange', {\n url: target,\n back: false,\n forward: false,\n });\n};\n"],"mappings":"AA8CW;AA7CX,SAAS,KAAK,kBAAkB;AAEhC,SAAS,mBAAmB;AAC5B,SAA0B,yBAAyB;AAEnD,SAAS,kBAAkB;AAC3B,SAAS,cAAc,gBAAgB,mBAAmB;AAC1D,SAAS,iBAAiB;AAUnB,MAAM,oBAAoB,CAAC,uBAA+B;AAC/D,QAAM,EAAE,WAAW,iBAAiB,WAAW,IAAI,IAAI,iBAAiB;AACxE,MAAI,qBAAqB,YAAY,oBAAoB,U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M,WAAW,CAAC,WAAmB;AAC1C,UAAQ,IAAI,2BAA2B,MAAM,EAAE;AAC/C,cAAY,aAAa;AAAA,IACvB,KAAK;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/routing.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { use, useContext } from 'react';\n\nimport { sendMessage } from './sandboxUtils';\nimport { NavigationState, TinkerableContext } from './TinkerableContext';\nimport { RouteParams, RoutingRule, RoutingSpec } from './RoutingSpec';\nimport { matchRoute } from './routeMatch';\nimport { constructUrl, isAbsolutePath, parseTarget } from './urlUtils';\nimport { joinPaths } from './pathUtils';\n\n/** The result of matching a path: the winning {@link RoutingRule} plus its captured params. */\nexport type AppliedRoutingRule = {\n routingRule: RoutingRule,\n pathParameters?: Record<string, string>;\n}\n\n/** Build the full outer href for an in-app target (absolute `sandboxPath` or a\n * path relative to the current route), e.g. for an `href` attribute. */\nexport const useTinkerableLink = (newSandboxLocation: string) => {\n const { outerHref, navigationState: navigation } = use(TinkerableContext);\n let newNavigationState = parseTarget(newSandboxLocation, navigation);\n if (!isAbsolutePath(newSandboxLocation)) {\n newNavigationState.sandboxPath = joinPaths(navigation.sandboxPath, newSandboxLocation)\n } else {\n newNavigationState.sandboxPath = newSandboxLocation\n }\n return constructUrl(outerHref, newNavigationState);\n}\n\n/** Find the first rule in `routingSpec` whose pattern matches the current\n * `sandboxPath`, returning it with the captured params (or `undefined`). */\nexport const applyRoutingRule = (routingSpec:RoutingSpec, navigationState: NavigationState): AppliedRoutingRule | undefined => {\n const { sandboxPath } = navigationState;\n for (const routingRule of routingSpec.routes) {\n const pathParameters = matchRoute(routingRule.pattern, sandboxPath);\n if (pathParameters) {\n return { routingRule, pathParameters };\n }\n }\n return undefined;\n}\n\n/** Render a matched rule, passing params to a `component` and falling back to `element`/`reactNode`. */\nexport const renderRoute = (routingRule: RoutingRule, params: RouteParams): ReactNode => {\n if (routingRule.component) {\n const Component = routingRule.component;\n return <Component params={params} />;\n }\n return routingRule.element ?? routingRule.reactNode ?? null;\n};\n\n/** Render the route matched for the current location (set up by `boot`'s route table). */\nexport const Router = () => {\n const context = useContext(TinkerableContext);\n const {navigationState: {routingRule, pathParameters}} = context;\n if (!routingRule) {\n // TODO: better error\n throw new Error(`No route registered for path ${context.navigationState.sandboxPath}!`);\n }\n\n return renderRoute(routingRule, pathParameters ?? {});\n};\n\n/** Read the current route's matched params (`:name` segments and the `*` wildcard). */\nexport const useRouteParams = <T extends RouteParams = RouteParams>(): T =>\n (use(TinkerableContext).navigationState.pathParameters ?? {}) as T;\n\n/**\n * Read the current route: the matched rule's `name`, its `params`, the app-owned\n * `sandboxPath`, and the read-only platform prefix fields (`mode`, `provider`,\n * `namespace`, `repository`, `ref`) — e.g. to tell `/edit` from `/present`.\n */\nexport const useRoute = () => {\n const { navigationState } = use(TinkerableContext);\n const { routingRule, pathParameters, sandboxPath, mode, provider, namespace, repository, ref } = navigationState;\n return {\n name: routingRule?.name,\n params: (pathParameters ?? {}) as RouteParams,\n sandboxPath,\n mode,\n provider,\n namespace,\n repository,\n ref,\n };\n};\n\n\n/**\n * Navigate within the app. Messages the host to update the URL; the host then\n * pushes the new href back, which drives the actual route change.\n */\nexport const navigate = (target: string) => {\n console.log(`[Sandbox] Navigating to ${target}`)\n sendMessage('urlchange', {\n url: target,\n back: false,\n forward: false,\n });\n};\n"],"mappings":";AA8CW;AA7CX,SAAS,KAAK,kBAAkB;AAEhC,SAAS,mBAAmB;AAC5B,SAA0B,yBAAyB;AAEnD,SAAS,kBAAkB;AAC3B,SAAS,cAAc,gBAAgB,mBAAmB;AAC1D,SAAS,iBAAiB;AAUnB,MAAM,oBAAoB,CAAC,uBAA+B;AAC/D,QAAM,EAAE,WAAW,iBAAiB,WAAW,IAAI,IAAI,iBAAiB;AACxE,MAAI,qBAAqB,YAAY,oBAAoB,UAAU;AACnE,MAAI,CAAC,eAAe,kBAAkB,GAAG;AACvC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B,MAAM,EAAE;AAC/C,cAAY,aAAa;AAAA,IACvB,KAAK;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACH;","names":[]}
package/dist/runtime.js CHANGED
@@ -1,3 +1,4 @@
1
+ import "./chunk-VHAA22YE.js";
1
2
  import { sendMessage, addListener } from "./sandboxUtils";
2
3
  import { SDK_VERSION } from "./version";
3
4
  import { getHostRuntime } from "./hostRuntime";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime.ts"],"sourcesContent":["// Runtime discovery + version handshake (SDK_PACKAGING_SPEC §4/§6).\n//\n// Today the SDK reaches the host through the INJECTED sandbox services\n// (`module.evaluation.module.bundler.*`, see sandboxUtils). The packaging migration\n// makes the SDK an app-pinnable npm dependency that finds the runtime through a\n// stable, versioned global the sandbox publishes BEFORE evaluating app code:\n//\n// globalThis.__immediatelyRun__ = { runtimeVersion, protocolVersion, transport }\n//\n// Phase 1 (behind a flag, injection still active): the SDK can READ that global\n// when present (else fall back to injection), and ANNOUNCE its own version +\n// protocol so the host can record + version-check it (§6/T45). The transport itself\n// is unchanged here — this only wires the discovery + handshake fields so the check\n// exists when app-pinned versions become real.\nimport { sendMessage, addListener } from './sandboxUtils';\nimport { SDK_VERSION } from './version';\n\n// `getHostRuntime` + `ImmediatelyRunGlobal` live in the leaf `hostRuntime` module\n// (imports nothing) and are re-exported here for a stable public API. This breaks\n// the sandboxUtils↔runtime import cycle: sandboxUtils reads `getHostRuntime` from\n// the leaf, while runtime still imports sandboxUtils for the handshake — one\n// direction only, no cycle.\nexport { getHostRuntime } from './hostRuntime';\nexport type { ImmediatelyRunGlobal } from './hostRuntime';\n\n/** The wire protocol (postMessage envelope / channels / methods) THIS SDK speaks.\n * Additive-only (§9); bump only for a backwards-compatible extension. */\nexport const SDK_PROTOCOL_VERSION = '1.0.0';\n\n/** This SDK's package version, baked from package.json at build (SP2-6,\n * `scripts/gen-version.mjs`). Re-exported so the public surface is unchanged\n * (`@immediately-run/sdk` → `SDK_VERSION`); imported above for the handshake. */\nexport { SDK_VERSION };\n\n/** This SDK's handshake payload — the version + protocol the host records + checks\n * against `HOST_PROTOCOL_VERSION` (§6/T45). */\nexport interface SdkHandshake {\n sdkVersion: string;\n protocolVersion: string;\n}\n/** Build this SDK's handshake payload (version + protocol) for the host to record. */\nexport const sdkHandshake = (): SdkHandshake => ({\n sdkVersion: SDK_VERSION,\n protocolVersion: SDK_PROTOCOL_VERSION,\n});\n\n/**\n * Announce this SDK's version to the host (§6). Sends `sdk-handshake` eagerly\n * (best-effort — the host may already be listening) AND replies to a host\n * `request-handshake` (the robust path, mirroring the other `request-*` pulls).\n * Idempotent; safe to call more than once. Returns an unsubscribe fn.\n */\nexport function announceHandshake(): () => void {\n const send = () => {\n try {\n sendMessage('sdk-handshake', sdkHandshake() as unknown as Record<string, unknown>);\n } catch {\n /* transport not ready yet — the request-handshake reply covers it */\n }\n };\n send();\n return addListener('request-handshake', send);\n}\n"],"mappings":"AAcA,SAAS,aAAa,mBAAmB;AACzC,SAAS,mBAAmB;AAO5B,SAAS,sBAAsB;AAKxB,MAAM,uBAAuB;AAc7B,MAAM,eAAe,OAAqB;AAAA,EAC/C,YAAY;AAAA,EACZ,iBAAiB;AACnB;AAQO,SAAS,oBAAgC;AAC9C,QAAM,OAAO,MAAM;AACjB,QAAI;AACF,kBAAY,iBAAiB,aAAa,CAAuC;AAAA,IACnF,QAAQ;AAAA,IAER;AAAA,EACF;AACA,OAAK;AACL,SAAO,YAAY,qBAAqB,IAAI;AAC9C;","names":[]}
1
+ {"version":3,"sources":["../src/runtime.ts"],"sourcesContent":["// Runtime discovery + version handshake (SDK_PACKAGING_SPEC §4/§6).\n//\n// Today the SDK reaches the host through the INJECTED sandbox services\n// (`module.evaluation.module.bundler.*`, see sandboxUtils). The packaging migration\n// makes the SDK an app-pinnable npm dependency that finds the runtime through a\n// stable, versioned global the sandbox publishes BEFORE evaluating app code:\n//\n// globalThis.__immediatelyRun__ = { runtimeVersion, protocolVersion, transport }\n//\n// Phase 1 (behind a flag, injection still active): the SDK can READ that global\n// when present (else fall back to injection), and ANNOUNCE its own version +\n// protocol so the host can record + version-check it (§6/T45). The transport itself\n// is unchanged here — this only wires the discovery + handshake fields so the check\n// exists when app-pinned versions become real.\nimport { sendMessage, addListener } from './sandboxUtils';\nimport { SDK_VERSION } from './version';\n\n// `getHostRuntime` + `ImmediatelyRunGlobal` live in the leaf `hostRuntime` module\n// (imports nothing) and are re-exported here for a stable public API. This breaks\n// the sandboxUtils↔runtime import cycle: sandboxUtils reads `getHostRuntime` from\n// the leaf, while runtime still imports sandboxUtils for the handshake — one\n// direction only, no cycle.\nexport { getHostRuntime } from './hostRuntime';\nexport type { ImmediatelyRunGlobal } from './hostRuntime';\n\n/** The wire protocol (postMessage envelope / channels / methods) THIS SDK speaks.\n * Additive-only (§9); bump only for a backwards-compatible extension. */\nexport const SDK_PROTOCOL_VERSION = '1.0.0';\n\n/** This SDK's package version, baked from package.json at build (SP2-6,\n * `scripts/gen-version.mjs`). Re-exported so the public surface is unchanged\n * (`@immediately-run/sdk` → `SDK_VERSION`); imported above for the handshake. */\nexport { SDK_VERSION };\n\n/** This SDK's handshake payload — the version + protocol the host records + checks\n * against `HOST_PROTOCOL_VERSION` (§6/T45). */\nexport interface SdkHandshake {\n sdkVersion: string;\n protocolVersion: string;\n}\n/** Build this SDK's handshake payload (version + protocol) for the host to record. */\nexport const sdkHandshake = (): SdkHandshake => ({\n sdkVersion: SDK_VERSION,\n protocolVersion: SDK_PROTOCOL_VERSION,\n});\n\n/**\n * Announce this SDK's version to the host (§6). Sends `sdk-handshake` eagerly\n * (best-effort — the host may already be listening) AND replies to a host\n * `request-handshake` (the robust path, mirroring the other `request-*` pulls).\n * Idempotent; safe to call more than once. Returns an unsubscribe fn.\n */\nexport function announceHandshake(): () => void {\n const send = () => {\n try {\n sendMessage('sdk-handshake', sdkHandshake() as unknown as Record<string, unknown>);\n } catch {\n /* transport not ready yet — the request-handshake reply covers it */\n }\n };\n send();\n return addListener('request-handshake', send);\n}\n"],"mappings":";AAcA,SAAS,aAAa,mBAAmB;AACzC,SAAS,mBAAmB;AAO5B,SAAS,sBAAsB;AAKxB,MAAM,uBAAuB;AAc7B,MAAM,eAAe,OAAqB;AAAA,EAC/C,YAAY;AAAA,EACZ,iBAAiB;AACnB;AAQO,SAAS,oBAAgC;AAC9C,QAAM,OAAO,MAAM;AACjB,QAAI;AACF,kBAAY,iBAAiB,aAAa,CAAuC;AAAA,IACnF,QAAQ;AAAA,IAER;AAAA,EACF;AACA,OAAK;AACL,SAAO,YAAY,qBAAqB,IAAI;AAC9C;","names":[]}
@@ -1,3 +1,4 @@
1
+ import "../chunk-VHAA22YE.js";
1
2
  import { useEffect, useMemo, useRef, useState } from "react";
2
3
  import { parseSafeMdast } from "./parseSafeMdast";
3
4
  import { renderMdast } from "./renderMdast";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/safeContent/SafeContent.tsx"],"sourcesContent":["import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { parseSafeMdast } from './parseSafeMdast';\nimport { renderMdast, type RenderMdastOptions } from './renderMdast';\n\n// R3-213 — sharing the component map: `parseSafeMdast` runs the SAME kernel remark\n// plugins the compiled path uses, so it emits `<Admonition>` / `<WikiLink>` /\n// `<HeadingAnchor>` element nodes. To render them identically to the compiled path (and\n// so pick up the R3-212 fragment resolver + scroll), an interpreter app passes the SAME\n// `DEFAULT_MDX_COMPONENTS` it hands `boot({ mdxComponents })` as this component's\n// `components` — that shared map IS the uniformity (no forked second component set). We\n// deliberately do NOT import DEFAULT_MDX_COMPONENTS here: the safe renderer is a lean,\n// dep-light security primitive (render-as-data, no evaluator, ESM-clean for the e2e\n// bundle), and must not pull the full component library into its module graph.\n\n// `<SafeContent>` — the host/SDK-owned safe renderer (TRUST_MODES_SPEC §5.1,\n// AGENT_AUTHORING §10). An interpreter app renders untrusted Markdown/MDX-syntax\n// content — a shared board's body, a multi-writer wiki entry — through THIS component\n// so **no author JavaScript ever executes** while `<Component/>` syntax still reaches\n// the app's own safe components. It is the mandatory terminal for the MDX-from-mount\n// gate: a shared board is a multi-writer (M3) source, and compiled/executable MDX\n// would run board-author code with the app's authority (the WHITEBOARD §8 blast\n// radius this gate bounds).\n//\n// The parse (no-acorn, ESM-only deps) is async, so this renders a small placeholder\n// until the tree is ready, then the pure synchronous `renderMdast`. Parsing is keyed\n// on the source string; a changed source re-parses, and a stale async result is\n// discarded (the ref guard) so a fast source swap can't paint the wrong content.\n\nexport interface SafeContentProps extends RenderMdastOptions {\n /** The untrusted Markdown/MDX-syntax source to render as data. */\n source: string;\n /** Rendered while the async parse is in flight (default: nothing). */\n fallback?: ReactNode;\n}\n\nexport function SafeContent({ source, fallback = null, ...options }: SafeContentProps): ReactNode {\n const [tree, setTree] = useState<Awaited<ReturnType<typeof parseSafeMdast>> | null>(null);\n const runId = useRef(0);\n\n useEffect(() => {\n const id = ++runId.current;\n setTree(null);\n let cancelled = false;\n parseSafeMdast(source)\n .then((parsed) => {\n // Discard a stale result (source changed / unmounted) so we never paint the\n // wrong tree — the render-as-data guarantee also needs the RIGHT data shown.\n if (!cancelled && runId.current === id) setTree(parsed);\n })\n .catch(() => {\n if (!cancelled && runId.current === id) setTree(null);\n });\n return () => {\n cancelled = true;\n };\n }, [source]);\n\n // `renderMdast` is pure; memoise on the tree + the option identities the caller\n // passes. (Callers should memoise `components`/`resolveWikiLink` themselves for a\n // stable identity; changing them re-renders, which is correct.)\n const rendered = useMemo(\n () => (tree ? renderMdast(tree, options) : null),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [tree, options.components, options.resolveWikiLink],\n );\n\n return tree ? rendered : fallback;\n}\n"],"mappings":"AAAA,SAAS,WAAW,SAAS,QAAQ,gBAAgC;AACrE,SAAS,sBAAsB;AAC/B,SAAS,mBAA4C;AAiC9C,SAAS,YAAY,EAAE,QAAQ,WAAW,MAAM,GAAG,QAAQ,GAAgC;AAChG,QAAM,CAAC,MAAM,OAAO,IAAI,SAA4D,IAAI;AACxF,QAAM,QAAQ,OAAO,CAAC;AAEtB,YAAU,MAAM;AACd,UAAM,KAAK,EAAE,MAAM;AACnB,YAAQ,IAAI;AACZ,QAAI,YAAY;AAChB,mBAAe,MAAM,EAClB,KAAK,CAAC,WAAW;AAGhB,UAAI,CAAC,aAAa,MAAM,YAAY,GAAI,SAAQ,MAAM;AAAA,IACxD,CAAC,EACA,MAAM,MAAM;AACX,UAAI,CAAC,aAAa,MAAM,YAAY,GAAI,SAAQ,IAAI;AAAA,IACtD,CAAC;AACH,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAKX,QAAM,WAAW;AAAA,IACf,MAAO,OAAO,YAAY,MAAM,OAAO,IAAI;AAAA;AAAA,IAE3C,CAAC,MAAM,QAAQ,YAAY,QAAQ,eAAe;AAAA,EACpD;AAEA,SAAO,OAAO,WAAW;AAC3B;","names":[]}
1
+ {"version":3,"sources":["../../src/safeContent/SafeContent.tsx"],"sourcesContent":["import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { parseSafeMdast } from './parseSafeMdast';\nimport { renderMdast, type RenderMdastOptions } from './renderMdast';\n\n// R3-213 — sharing the component map: `parseSafeMdast` runs the SAME kernel remark\n// plugins the compiled path uses, so it emits `<Admonition>` / `<WikiLink>` /\n// `<HeadingAnchor>` element nodes. To render them identically to the compiled path (and\n// so pick up the R3-212 fragment resolver + scroll), an interpreter app passes the SAME\n// `DEFAULT_MDX_COMPONENTS` it hands `boot({ mdxComponents })` as this component's\n// `components` — that shared map IS the uniformity (no forked second component set). We\n// deliberately do NOT import DEFAULT_MDX_COMPONENTS here: the safe renderer is a lean,\n// dep-light security primitive (render-as-data, no evaluator, ESM-clean for the e2e\n// bundle), and must not pull the full component library into its module graph.\n\n// `<SafeContent>` — the host/SDK-owned safe renderer (TRUST_MODES_SPEC §5.1,\n// AGENT_AUTHORING §10). An interpreter app renders untrusted Markdown/MDX-syntax\n// content — a shared board's body, a multi-writer wiki entry — through THIS component\n// so **no author JavaScript ever executes** while `<Component/>` syntax still reaches\n// the app's own safe components. It is the mandatory terminal for the MDX-from-mount\n// gate: a shared board is a multi-writer (M3) source, and compiled/executable MDX\n// would run board-author code with the app's authority (the WHITEBOARD §8 blast\n// radius this gate bounds).\n//\n// The parse (no-acorn, ESM-only deps) is async, so this renders a small placeholder\n// until the tree is ready, then the pure synchronous `renderMdast`. Parsing is keyed\n// on the source string; a changed source re-parses, and a stale async result is\n// discarded (the ref guard) so a fast source swap can't paint the wrong content.\n\nexport interface SafeContentProps extends RenderMdastOptions {\n /** The untrusted Markdown/MDX-syntax source to render as data. */\n source: string;\n /** Rendered while the async parse is in flight (default: nothing). */\n fallback?: ReactNode;\n}\n\nexport function SafeContent({ source, fallback = null, ...options }: SafeContentProps): ReactNode {\n const [tree, setTree] = useState<Awaited<ReturnType<typeof parseSafeMdast>> | null>(null);\n const runId = useRef(0);\n\n useEffect(() => {\n const id = ++runId.current;\n setTree(null);\n let cancelled = false;\n parseSafeMdast(source)\n .then((parsed) => {\n // Discard a stale result (source changed / unmounted) so we never paint the\n // wrong tree — the render-as-data guarantee also needs the RIGHT data shown.\n if (!cancelled && runId.current === id) setTree(parsed);\n })\n .catch(() => {\n if (!cancelled && runId.current === id) setTree(null);\n });\n return () => {\n cancelled = true;\n };\n }, [source]);\n\n // `renderMdast` is pure; memoise on the tree + the option identities the caller\n // passes. (Callers should memoise `components`/`resolveWikiLink` themselves for a\n // stable identity; changing them re-renders, which is correct.)\n const rendered = useMemo(\n () => (tree ? renderMdast(tree, options) : null),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [tree, options.components, options.resolveWikiLink],\n );\n\n return tree ? rendered : fallback;\n}\n"],"mappings":";AAAA,SAAS,WAAW,SAAS,QAAQ,gBAAgC;AACrE,SAAS,sBAAsB;AAC/B,SAAS,mBAA4C;AAiC9C,SAAS,YAAY,EAAE,QAAQ,WAAW,MAAM,GAAG,QAAQ,GAAgC;AAChG,QAAM,CAAC,MAAM,OAAO,IAAI,SAA4D,IAAI;AACxF,QAAM,QAAQ,OAAO,CAAC;AAEtB,YAAU,MAAM;AACd,UAAM,KAAK,EAAE,MAAM;AACnB,YAAQ,IAAI;AACZ,QAAI,YAAY;AAChB,mBAAe,MAAM,EAClB,KAAK,CAAC,WAAW;AAGhB,UAAI,CAAC,aAAa,MAAM,YAAY,GAAI,SAAQ,MAAM;AAAA,IACxD,CAAC,EACA,MAAM,MAAM;AACX,UAAI,CAAC,aAAa,MAAM,YAAY,GAAI,SAAQ,IAAI;AAAA,IACtD,CAAC;AACH,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAKX,QAAM,WAAW;AAAA,IACf,MAAO,OAAO,YAAY,MAAM,OAAO,IAAI;AAAA;AAAA,IAE3C,CAAC,MAAM,QAAQ,YAAY,QAAQ,eAAe;AAAA,EACpD;AAEA,SAAO,OAAO,WAAW;AAC3B;","names":[]}
@@ -1,3 +1,4 @@
1
+ import "../chunk-VHAA22YE.js";
1
2
  import { SafeContent } from "./SafeContent";
2
3
  import { renderMdast } from "./renderMdast";
3
4
  import { parseSafeMdast } from "./parseSafeMdast";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/safeContent/index.ts"],"sourcesContent":["// Safe content rendering — non-executable MDX (TRUST_MODES_SPEC §5.1, AGENT_AUTHORING\n// §10). The host/SDK-owned renderer an INTERPRETER app uses to render untrusted\n// Markdown/MDX-syntax content as data, with **no evaluator anywhere in the pipeline**.\n// This is the mandatory terminal for the MDX-from-mount gate (§10 delta 1) — a shared\n// (multi-writer / M3) board or wiki entry MUST render through here, never compiled MDX.\n//\n// It is a **T2 tool, not a platform gate**: it stops content executing as code; it does\n// not certify anything to the host, and CO-4 data-fencing is still required for anything\n// that *reads* the content (the agent case).\n\nexport { SafeContent } from './SafeContent';\nexport type { SafeContentProps } from './SafeContent';\nexport { renderMdast } from './renderMdast';\nexport type {\n RenderMdastOptions,\n SafeContentComponents,\n} from './renderMdast';\nexport { parseSafeMdast } from './parseSafeMdast';\nexport type { SafeMdastNode, SafeMdxAttribute, ParseSafeMdastOptions } from './parseSafeMdast';\nexport { sanitizeUrl } from './sanitizeUrl';\nexport { splitWikiLinks, parseWikiInner } from './wikilink';\nexport type { WikiLinkToken, WikiPart } from './wikilink';\n"],"mappings":"AAUA,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAK5B,SAAS,sBAAsB;AAE/B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;","names":[]}
1
+ {"version":3,"sources":["../../src/safeContent/index.ts"],"sourcesContent":["// Safe content rendering — non-executable MDX (TRUST_MODES_SPEC §5.1, AGENT_AUTHORING\n// §10). The host/SDK-owned renderer an INTERPRETER app uses to render untrusted\n// Markdown/MDX-syntax content as data, with **no evaluator anywhere in the pipeline**.\n// This is the mandatory terminal for the MDX-from-mount gate (§10 delta 1) — a shared\n// (multi-writer / M3) board or wiki entry MUST render through here, never compiled MDX.\n//\n// It is a **T2 tool, not a platform gate**: it stops content executing as code; it does\n// not certify anything to the host, and CO-4 data-fencing is still required for anything\n// that *reads* the content (the agent case).\n\nexport { SafeContent } from './SafeContent';\nexport type { SafeContentProps } from './SafeContent';\nexport { renderMdast } from './renderMdast';\nexport type {\n RenderMdastOptions,\n SafeContentComponents,\n} from './renderMdast';\nexport { parseSafeMdast } from './parseSafeMdast';\nexport type { SafeMdastNode, SafeMdxAttribute, ParseSafeMdastOptions } from './parseSafeMdast';\nexport { sanitizeUrl } from './sanitizeUrl';\nexport { splitWikiLinks, parseWikiInner } from './wikilink';\nexport type { WikiLinkToken, WikiPart } from './wikilink';\n"],"mappings":";AAUA,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAK5B,SAAS,sBAAsB;AAE/B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;","names":[]}