@immediately-run/sdk 0.82.0 → 0.83.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/launch.ts"],"sourcesContent":["// Launch — the TO-RUN twin of `invokeTask` (STANDING_APP_LIFECYCLE_SPEC §1–§6).\n// Where `invokeTask` is FOR-RESULT (await one value, callee exits), `launch` is\n// TO-RUN (non-blocking, standing): it starts a bound program RUNNING in a region\n// and hands back a HANDLE, never a typed value (R-SAL-1). The launched app earns\n// its OWN grants — the only launcher→launched data path is the explicitly\n// delegated `capDir`/`capFile` in `input` (§5), attenuated + tainted + gated host-\n// side. The host owns the whole lifecycle (visibility, budget, revocation,\n// teardown); the launcher only OBSERVES via the handle.\n//\n// A caller that wants a typed value back uses `invokeTask` instead — the two are\n// siblings, not a replacement.\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { LAUNCH_DISMISS, LAUNCH_ENDED, PROTOCOL_LAUNCH } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a launched program runs (§6). `overlay` covers the caller's own region\n * with opaque host chrome; `stage` replaces the focal app (the elevated into-\n * stage surface, §7 — refused above the stage-principal ceiling). */\nexport type LaunchRegion = 'overlay' | 'stage';\n\n/**\n * What to launch (§3) — binding-resolved, NEVER a caller-named app. Exactly one of:\n * - `entryPoint`: a sibling entry point of the caller's OWN repo (the mini-app\n * case, `AGENT_AUTHORING §5`) — **rejected `forbidden` until program-identity\n * `appKey` lands** (R-SAL-2a);\n * - `task`: a task contract (`open-project`, …), resolved through the user-\n * overridable `task.<name>` binding to whichever app the user bound (§3 kind 2).\n */\nexport interface LaunchTarget {\n /** Kind 1 — a sibling entry point of the caller's own repo (mini-app overlay). */\n entryPoint?: string;\n /** Kind 2 — a task contract name (the host resolves the bound provider). */\n task?: string;\n /** Optional accepted contract version for a `task` target (semver, e.g. `^1`). */\n version?: string;\n}\n\nexport interface LaunchOptions {\n /** Where it runs (§6). */\n region: LaunchRegion;\n /**\n * Delegations + plain data handed to the launched app. `$cap:'dir'|'file'`\n * markers (`capDir`/`capFile`, exported from `./tasks`) are resolved against the\n * launcher's OWN grants and minted as attenuated, `ro`-by-default chroots (§5) —\n * you can only delegate what you already hold. Everything else is plain data.\n */\n input?: Record<string, unknown>;\n}\n\n/** The live state of a launch (§2). Terminal states (`dismissed`/`revoked`/\n * `failed`) are reached identically for self-exit, user dismiss, and host revoke —\n * the host debounces so the launcher gets no timing oracle (R-SAL-1 / §6.4). */\nexport type LaunchStatus = 'running' | 'dismissed' | 'revoked' | 'failed';\n\n/** Machine codes a refused `launch` resolves with (§8). */\nexport type LaunchErrorCode =\n | 'forbidden' // undeclared target; sibling (pre-AA-01); self-resolving target; stage cap absent\n | 'unsupported' // no provider bound / entry point absent / unknown contract version\n | 'budget' // over an R-SAL-8 concurrency/rate limit\n | 'revoked' // a delegated mount was revoked during the create-and-bind window\n | 'cancelled' // the user dismissed the host launch affordance (into-stage only)\n | 'invalid-params' // a malformed `capDir`/`capFile` (`..`/absolute/mode-escalation)\n | 'unknown';\n\n/**\n * The control channel back to a launch — the ONLY thing a launcher gets (§2).\n * There is no typed return value (R-SAL-1); `status`/`onDismiss` are debounced so\n * they cannot time-distinguish a self-exit from a user dismiss.\n */\nexport interface LaunchHandle {\n /** Host-assigned id for this launch. */\n readonly launchId: string;\n /** The current lifecycle state (§2). */\n readonly status: LaunchStatus;\n /** Ask the host to tear this launch down. Idempotent (double-dismiss is a no-op). */\n dismiss(): void;\n /**\n * Observe the launch ending (self-exit / user dismiss / host revoke — fired\n * identically, R-SAL-1). Returns an unsubscribe fn. Fires at most once; if the\n * launch has already ended it fires on the next tick.\n */\n onDismiss(cb: () => void): () => void;\n}\n\ninterface LaunchEndedMessage {\n launchId: string;\n status: Exclude<LaunchStatus, 'running'>;\n}\n\n/** Live handles awaiting their terminal `launch-ended` message, keyed by launchId. */\nconst liveHandles = new Map<string, LaunchHandleImpl>();\n\n/**\n * Terminal statuses that arrived BEFORE their handle existed, keyed by launchId.\n *\n * The window is real: `launch()` registers the listener before it sends `create`,\n * but the handle only enters `liveHandles` once the create RESPONSE resolves. A\n * short-lived launch (or a revoke during binding) can end inside that gap, and a\n * dropped terminal message leaves the handle `running` for ever with `onDismiss`\n * never firing — the one failure a launcher cannot detect or recover from. So the\n * message is BUFFERED and applied when the handle lands.\n *\n * Bounded, because the host is not this module's to trust: entries are only kept\n * while a create is actually in flight, and no more than {@link MAX_PENDING_ENDED}\n * of them (oldest evicted). A `launch-ended` for an id we never created is still\n * ignored, exactly as before.\n */\nconst pendingEnded = new Map<string, Exclude<LaunchStatus, 'running'>>();\nconst MAX_PENDING_ENDED = 16;\n/** How many `launch()` calls are between their create request and its response. */\nlet createsInFlight = 0;\n\n// The host delivers ONE `launch-ended` message per launch when it tears down —\n// the SAME message shape for self-exit, dismiss, and revoke (the host debounces\n// so the timing is not an oracle, §6.4). We fan it out to the matching handle, or\n// buffer it for a handle that has not landed yet (above).\n//\n// Registered LAZILY, on the first `launch()` call, not at module evaluation\n// (R3-421 — no subpath may throw at import time off-host). Unlike `task-input`\n// (tasks.ts), first-use registration loses nothing here: a `launch-ended` can only\n// ever follow a launch THIS module created, and `launch()` registers the listener\n// before it sends the create request — so the listener always exists before any\n// launchId it must match. That is a claim about the LISTENER only; the handle it\n// must reach can still be a response away, which is what `pendingEnded` covers.\nlet endedListenerRegistered = false;\nconst ensureEndedListener = (): void => {\n if (endedListenerRegistered) return;\n try {\n addListener(LAUNCH_ENDED, (m: LaunchEndedMessage) => {\n const h = liveHandles.get(m.launchId);\n if (h) {\n h._end(m.status);\n return;\n }\n // No handle yet. Buffer only while a create could still produce one; anything\n // else is a stale or unknown id and is ignored.\n if (createsInFlight === 0) return;\n if (pendingEnded.size >= MAX_PENDING_ENDED) {\n const oldest = pendingEnded.keys().next();\n if (!oldest.done) pendingEnded.delete(oldest.value);\n }\n pendingEnded.set(m.launchId, m.status);\n });\n } catch {\n return; // off-host: no transport — the create request below will fail anyway\n }\n endedListenerRegistered = true;\n};\n\nclass LaunchHandleImpl implements LaunchHandle {\n #status: LaunchStatus = 'running';\n #dismissListeners = new Set<() => void>();\n #ended = false;\n\n constructor(readonly launchId: string) {\n liveHandles.set(launchId, this);\n // A terminal message that beat this handle into existence (see `pendingEnded`):\n // apply it now, so the handle is born ended rather than stuck `running`.\n const early = pendingEnded.get(launchId);\n if (early !== undefined) {\n pendingEnded.delete(launchId);\n this._end(early);\n }\n }\n\n get status(): LaunchStatus {\n return this.#status;\n }\n\n dismiss(): void {\n if (this.#ended) return;\n // Fire-and-forget: the host owns teardown and answers with `launch-ended`,\n // which drives `_end` (so status/onDismiss are host-authoritative, never\n // optimistically local — a dismiss the host refuses would otherwise desync).\n sendMessage(LAUNCH_DISMISS, { launchId: this.launchId });\n }\n\n onDismiss(cb: () => void): () => void {\n if (this.#ended) {\n // Already ended: fire on the next tick so the contract (\"returns an\n // unsubscribe\") holds and the callback never runs synchronously mid-register.\n queueMicrotask(cb);\n return () => {};\n }\n this.#dismissListeners.add(cb);\n return () => {\n this.#dismissListeners.delete(cb);\n };\n }\n\n /** Host-driven terminal transition — the only writer of `status`. Idempotent. */\n _end(status: Exclude<LaunchStatus, 'running'>): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#status = status;\n liveHandles.delete(this.launchId);\n const listeners = [...this.#dismissListeners];\n this.#dismissListeners.clear();\n for (const l of listeners) {\n try {\n l();\n } catch {\n /* a launcher's own callback must never wedge teardown */\n }\n }\n }\n}\n\n/**\n * Launch a bound program to RUN in a region (§2). Non-blocking: resolves once the\n * frame is created and bound, with a {@link LaunchHandle} — or a typed\n * `{ ok:false, code }` on refusal (§8), NEVER a throw for an ordinary refusal (so\n * a launcher branches on `code` without a try/catch). The launched app runs under\n * its OWN grants; the launcher's authority does not flow to it (R-SAL-4).\n *\n * const h = await launch({ task: 'open-project' }, {\n * region: 'stage',\n * input: { dir: capDir({ mountId: 'space:abc', relPath: 'proj' }, { mode: 'ro' }) },\n * });\n * if ('ok' in h && h.ok === false) { ...handle h.code... }\n * else { h.onDismiss(() => ...); }\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to run a launch in.\n */\nexport const launch = async (\n target: LaunchTarget,\n opts: LaunchOptions,\n): Promise<LaunchHandle | { ok: false; code: LaunchErrorCode }> => {\n // Before the create request, so the terminal message can never beat the listener.\n ensureEndedListener();\n // The host wraps a successful handler return as `{ ok:true, data }` (the same\n // Recipe-B framing `invokeTask` uses); a refusal is `{ ok:false, code }`.\n createsInFlight += 1;\n let res: { ok: true; data: { launchId: string } } | { ok: false; code?: LaunchErrorCode } | undefined;\n try {\n res = (await protocolRequest(SCHEMES[PROTOCOL_LAUNCH], 'create', [{ target, opts }])) as typeof res;\n } finally {\n createsInFlight -= 1;\n }\n // Once nothing is in flight, anything still buffered belongs to a launch that will\n // never produce a handle — drop it rather than keep it for ever. Done AFTER the\n // handle below is constructed (its constructor drains its own entry first), so the\n // sweep can never eat the message this very call was waiting for.\n const sweep = (): void => {\n if (createsInFlight === 0) pendingEnded.clear();\n };\n if (!res || res.ok !== true || !res.data?.launchId) {\n sweep();\n const code = res && res.ok === false ? res.code ?? 'unknown' : 'unknown';\n return { ok: false, code };\n }\n // The constructor drains a terminal message that arrived while `create` was in\n // flight, so this handle can be returned already-ended rather than stuck `running`.\n const handle = new LaunchHandleImpl(res.data.launchId);\n sweep();\n return handle;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,0BAA0D;AAC1D,sBAA8D;AAC9D,6BAAwB;AAbxB;AA0FA,MAAM,cAAc,oBAAI,IAA8B;AAiBtD,MAAM,eAAe,oBAAI,IAA8C;AACvE,MAAM,oBAAoB;AAE1B,IAAI,kBAAkB;AActB,IAAI,0BAA0B;AAC9B,MAAM,sBAAsB,MAAY;AACtC,MAAI,wBAAyB;AAC7B,MAAI;AAC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,CAAC,GAAG,mBAAK,kBAAiB;AAC5C,uBAAK,mBAAkB,MAAM;AAC7B,eAAW,KAAK,WAAW;AACzB,UAAI;AACF,UAAE;AAAA,MACJ,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;AAxDE;AACA;AACA;AAyEK,MAAM,SAAS,OACpB,QACA,SACiE;AAEjE,sBAAoB;AAGpB,qBAAmB;AACnB,MAAI;AACJ,MAAI;AACF,UAAO,UAAM,qCAAgB,+BAAQ,+BAAe,GAAG,UAAU,CAAC,EAAE,QAAQ,KAAK,CAAC,CAAC;AAAA,EACrF,UAAE;AACA,uBAAmB;AAAA,EACrB;AAKA,QAAM,QAAQ,MAAY;AACxB,QAAI,oBAAoB,EAAG,cAAa,MAAM;AAAA,EAChD;AACA,MAAI,CAAC,OAAO,IAAI,OAAO,QAAQ,CAAC,IAAI,MAAM,UAAU;AAClD,UAAM;AACN,UAAM,OAAO,OAAO,IAAI,OAAO,QAAQ,IAAI,QAAQ,YAAY;AAC/D,WAAO,EAAE,IAAI,OAAO,KAAK;AAAA,EAC3B;AAGA,QAAM,SAAS,IAAI,iBAAiB,IAAI,KAAK,QAAQ;AACrD,QAAM;AACN,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/launch.ts"],"sourcesContent":["// Launch — the TO-RUN twin of `invokeTask` (STANDING_APP_LIFECYCLE_SPEC §1–§6).\n// Where `invokeTask` is FOR-RESULT (await one value, callee exits), `launch` is\n// TO-RUN (non-blocking, standing): it starts a bound program RUNNING in a region\n// and hands back a HANDLE, never a typed value (R-SAL-1). The launched app earns\n// its OWN grants — the only launcher→launched data path is the explicitly\n// delegated `capDir`/`capFile` in `input` (§5), attenuated + tainted + gated host-\n// side. The host owns the whole lifecycle (visibility, budget, revocation,\n// teardown); the launcher only OBSERVES via the handle.\n//\n// A caller that wants a typed value back uses `invokeTask` instead — the two are\n// siblings, not a replacement.\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { LAUNCH_DISMISS, LAUNCH_ENDED, PROTOCOL_LAUNCH } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a launched program runs (§6). `overlay` covers the caller's own region\n * with opaque host chrome; `stage` replaces the focal app (the elevated into-\n * stage surface, §7 — refused above the stage-principal ceiling). */\nexport type LaunchRegion = 'overlay' | 'stage';\n\n/**\n * What to launch (§3) — binding-resolved, NEVER a caller-named app. Exactly one of:\n * - `entryPoint`: a sibling entry point of the caller's OWN repo (the mini-app\n * case, `AGENT_AUTHORING §5`) — **rejected `forbidden` until program-identity\n * `appKey` lands** (R-SAL-2a);\n * - `task`: a task contract (`open-project`, …), resolved through the user-\n * overridable `task.<name>` binding to whichever app the user bound (§3 kind 2).\n */\nexport interface LaunchTarget {\n /** Kind 1 — a sibling entry point of the caller's own repo (mini-app overlay). */\n entryPoint?: string;\n /** Kind 2 — a task contract name (the host resolves the bound provider). */\n task?: string;\n /** Optional accepted contract version for a `task` target (semver, e.g. `^1`). */\n version?: string;\n}\n\nexport interface LaunchOptions {\n /** Where it runs (§6). */\n region: LaunchRegion;\n /**\n * Delegations + plain data handed to the launched app. `$cap:'dir'|'file'`\n * markers (`capDir`/`capFile`, exported from `./tasks`) are resolved against the\n * launcher's OWN grants and minted as attenuated, `ro`-by-default chroots (§5) —\n * you can only delegate what you already hold. Everything else is plain data.\n */\n input?: Record<string, unknown>;\n}\n\n/** The live state of a launch (§2). Terminal states (`dismissed`/`revoked`/\n * `failed`) are reached identically for self-exit, user dismiss, and host revoke —\n * the host debounces so the launcher gets no timing oracle (R-SAL-1 / §6.4). */\nexport type LaunchStatus = 'running' | 'dismissed' | 'revoked' | 'failed';\n\n/** Machine codes a refused `launch` resolves with (§8). */\nexport type LaunchErrorCode =\n | 'forbidden' // undeclared target; sibling (pre-AA-01); self-resolving target; stage cap absent\n | 'unsupported' // no provider bound / entry point absent / unknown contract version\n | 'budget' // over an R-SAL-8 concurrency/rate limit\n | 'revoked' // a delegated mount was revoked during the create-and-bind window\n | 'cancelled' // the user dismissed the host launch affordance (into-stage only)\n | 'invalid-params' // a malformed `capDir`/`capFile` (`..`/absolute/mode-escalation)\n | 'unknown';\n\n/**\n * The control channel back to a launch — the ONLY thing a launcher gets (§2).\n * There is no typed return value (R-SAL-1); `status`/`onDismiss` are debounced so\n * they cannot time-distinguish a self-exit from a user dismiss.\n */\nexport interface LaunchHandle {\n /** Host-assigned id for this launch. */\n readonly launchId: string;\n /** The current lifecycle state (§2). */\n readonly status: LaunchStatus;\n /** Ask the host to tear this launch down. Idempotent (double-dismiss is a no-op). */\n dismiss(): void;\n /**\n * Observe the launch ending (self-exit / user dismiss / host revoke — fired\n * identically, R-SAL-1). Returns an unsubscribe fn. Fires at most once; if the\n * launch has already ended it fires on the next tick.\n */\n onDismiss(cb: () => void): () => void;\n}\n\ninterface LaunchEndedMessage {\n launchId: string;\n status: Exclude<LaunchStatus, 'running'>;\n}\n\n/** Live handles awaiting their terminal `launch-ended` message, keyed by launchId. */\nconst liveHandles = new Map<string, LaunchHandleImpl>();\n\n/**\n * Terminal statuses that arrived BEFORE their handle existed, keyed by launchId.\n *\n * The window is real: `launch()` registers the listener before it sends `create`,\n * but the handle only enters `liveHandles` once the create RESPONSE resolves. A\n * short-lived launch (or a revoke during binding) can end inside that gap, and a\n * dropped terminal message leaves the handle `running` for ever with `onDismiss`\n * never firing — the one failure a launcher cannot detect or recover from. So the\n * message is BUFFERED and applied when the handle lands.\n *\n * Bounded, because the host is not this module's to trust: entries are only kept\n * while a create is actually in flight, and no more than {@link MAX_PENDING_ENDED}\n * of them (oldest evicted). A `launch-ended` for an id we never created is still\n * ignored, exactly as before.\n */\nconst pendingEnded = new Map<string, Exclude<LaunchStatus, 'running'>>();\nconst MAX_PENDING_ENDED = 16;\n/** How many `launch()` calls are between their create request and its response. */\nlet createsInFlight = 0;\n\n// The host delivers ONE `launch-ended` message per launch when it tears down —\n// the SAME message shape for self-exit, dismiss, and revoke (the host debounces\n// so the timing is not an oracle, §6.4). We fan it out to the matching handle, or\n// buffer it for a handle that has not landed yet (above).\n//\n// Registered LAZILY, on the first `launch()` call, not at module evaluation\n// (R3-421 — no subpath may throw at import time off-host). First-use registration\n// loses nothing here: a `launch-ended` can only\n// ever follow a launch THIS module created, and `launch()` registers the listener\n// before it sends the create request — so the listener always exists before any\n// launchId it must match. That is a claim about the LISTENER only; the handle it\n// must reach can still be a response away, which is what `pendingEnded` covers.\nlet endedListenerRegistered = false;\nconst ensureEndedListener = (): void => {\n if (endedListenerRegistered) return;\n try {\n addListener(LAUNCH_ENDED, (m: LaunchEndedMessage) => {\n const h = liveHandles.get(m.launchId);\n if (h) {\n h._end(m.status);\n return;\n }\n // No handle yet. Buffer only while a create could still produce one; anything\n // else is a stale or unknown id and is ignored.\n if (createsInFlight === 0) return;\n if (pendingEnded.size >= MAX_PENDING_ENDED) {\n const oldest = pendingEnded.keys().next();\n if (!oldest.done) pendingEnded.delete(oldest.value);\n }\n pendingEnded.set(m.launchId, m.status);\n });\n } catch {\n return; // off-host: no transport — the create request below will fail anyway\n }\n endedListenerRegistered = true;\n};\n\nclass LaunchHandleImpl implements LaunchHandle {\n #status: LaunchStatus = 'running';\n #dismissListeners = new Set<() => void>();\n #ended = false;\n\n constructor(readonly launchId: string) {\n liveHandles.set(launchId, this);\n // A terminal message that beat this handle into existence (see `pendingEnded`):\n // apply it now, so the handle is born ended rather than stuck `running`.\n const early = pendingEnded.get(launchId);\n if (early !== undefined) {\n pendingEnded.delete(launchId);\n this._end(early);\n }\n }\n\n get status(): LaunchStatus {\n return this.#status;\n }\n\n dismiss(): void {\n if (this.#ended) return;\n // Fire-and-forget: the host owns teardown and answers with `launch-ended`,\n // which drives `_end` (so status/onDismiss are host-authoritative, never\n // optimistically local — a dismiss the host refuses would otherwise desync).\n sendMessage(LAUNCH_DISMISS, { launchId: this.launchId });\n }\n\n onDismiss(cb: () => void): () => void {\n if (this.#ended) {\n // Already ended: fire on the next tick so the contract (\"returns an\n // unsubscribe\") holds and the callback never runs synchronously mid-register.\n queueMicrotask(cb);\n return () => {};\n }\n this.#dismissListeners.add(cb);\n return () => {\n this.#dismissListeners.delete(cb);\n };\n }\n\n /** Host-driven terminal transition — the only writer of `status`. Idempotent. */\n _end(status: Exclude<LaunchStatus, 'running'>): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#status = status;\n liveHandles.delete(this.launchId);\n const listeners = [...this.#dismissListeners];\n this.#dismissListeners.clear();\n for (const l of listeners) {\n try {\n l();\n } catch {\n /* a launcher's own callback must never wedge teardown */\n }\n }\n }\n}\n\n/**\n * Launch a bound program to RUN in a region (§2). Non-blocking: resolves once the\n * frame is created and bound, with a {@link LaunchHandle} — or a typed\n * `{ ok:false, code }` on refusal (§8), NEVER a throw for an ordinary refusal (so\n * a launcher branches on `code` without a try/catch). The launched app runs under\n * its OWN grants; the launcher's authority does not flow to it (R-SAL-4).\n *\n * const h = await launch({ task: 'open-project' }, {\n * region: 'stage',\n * input: { dir: capDir({ mountId: 'space:abc', relPath: 'proj' }, { mode: 'ro' }) },\n * });\n * if ('ok' in h && h.ok === false) { ...handle h.code... }\n * else { h.onDismiss(() => ...); }\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to run a launch in.\n */\nexport const launch = async (\n target: LaunchTarget,\n opts: LaunchOptions,\n): Promise<LaunchHandle | { ok: false; code: LaunchErrorCode }> => {\n // Before the create request, so the terminal message can never beat the listener.\n ensureEndedListener();\n // The host wraps a successful handler return as `{ ok:true, data }` (the same\n // Recipe-B framing `invokeTask` uses); a refusal is `{ ok:false, code }`.\n createsInFlight += 1;\n let res: { ok: true; data: { launchId: string } } | { ok: false; code?: LaunchErrorCode } | undefined;\n try {\n res = (await protocolRequest(SCHEMES[PROTOCOL_LAUNCH], 'create', [{ target, opts }])) as typeof res;\n } finally {\n createsInFlight -= 1;\n }\n // Once nothing is in flight, anything still buffered belongs to a launch that will\n // never produce a handle — drop it rather than keep it for ever. Done AFTER the\n // handle below is constructed (its constructor drains its own entry first), so the\n // sweep can never eat the message this very call was waiting for.\n const sweep = (): void => {\n if (createsInFlight === 0) pendingEnded.clear();\n };\n if (!res || res.ok !== true || !res.data?.launchId) {\n sweep();\n const code = res && res.ok === false ? res.code ?? 'unknown' : 'unknown';\n return { ok: false, code };\n }\n // The constructor drains a terminal message that arrived while `create` was in\n // flight, so this handle can be returned already-ended rather than stuck `running`.\n const handle = new LaunchHandleImpl(res.data.launchId);\n sweep();\n return handle;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,0BAA0D;AAC1D,sBAA8D;AAC9D,6BAAwB;AAbxB;AA0FA,MAAM,cAAc,oBAAI,IAA8B;AAiBtD,MAAM,eAAe,oBAAI,IAA8C;AACvE,MAAM,oBAAoB;AAE1B,IAAI,kBAAkB;AActB,IAAI,0BAA0B;AAC9B,MAAM,sBAAsB,MAAY;AACtC,MAAI,wBAAyB;AAC7B,MAAI;AACF,yCAAY,8BAAc,CAAC,MAA0B;AACnD,YAAM,IAAI,YAAY,IAAI,EAAE,QAAQ;AACpC,UAAI,GAAG;AACL,UAAE,KAAK,EAAE,MAAM;AACf;AAAA,MACF;AAGA,UAAI,oBAAoB,EAAG;AAC3B,UAAI,aAAa,QAAQ,mBAAmB;AAC1C,cAAM,SAAS,aAAa,KAAK,EAAE,KAAK;AACxC,YAAI,CAAC,OAAO,KAAM,cAAa,OAAO,OAAO,KAAK;AAAA,MACpD;AACA,mBAAa,IAAI,EAAE,UAAU,EAAE,MAAM;AAAA,IACvC,CAAC;AAAA,EACH,QAAQ;AACN;AAAA,EACF;AACA,4BAA0B;AAC5B;AAEA,MAAM,iBAAyC;AAAA,EAK7C,YAAqB,UAAkB;AAAlB;AAJrB,gCAAwB;AACxB,0CAAoB,oBAAI,IAAgB;AACxC,+BAAS;AAGP,gBAAY,IAAI,UAAU,IAAI;AAG9B,UAAM,QAAQ,aAAa,IAAI,QAAQ;AACvC,QAAI,UAA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AC/D,WAAO,EAAE,IAAI,OAAO,KAAK;AAAA,EAC3B;AAGA,QAAM,SAAS,IAAI,iBAAiB,IAAI,KAAK,QAAQ;AACrD,QAAM;AACN,SAAO;AACT;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/launch.ts"],"sourcesContent":["// Launch — the TO-RUN twin of `invokeTask` (STANDING_APP_LIFECYCLE_SPEC §1–§6).\n// Where `invokeTask` is FOR-RESULT (await one value, callee exits), `launch` is\n// TO-RUN (non-blocking, standing): it starts a bound program RUNNING in a region\n// and hands back a HANDLE, never a typed value (R-SAL-1). The launched app earns\n// its OWN grants — the only launcher→launched data path is the explicitly\n// delegated `capDir`/`capFile` in `input` (§5), attenuated + tainted + gated host-\n// side. The host owns the whole lifecycle (visibility, budget, revocation,\n// teardown); the launcher only OBSERVES via the handle.\n//\n// A caller that wants a typed value back uses `invokeTask` instead — the two are\n// siblings, not a replacement.\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { LAUNCH_DISMISS, LAUNCH_ENDED, PROTOCOL_LAUNCH } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a launched program runs (§6). `overlay` covers the caller's own region\n * with opaque host chrome; `stage` replaces the focal app (the elevated into-\n * stage surface, §7 — refused above the stage-principal ceiling). */\nexport type LaunchRegion = 'overlay' | 'stage';\n\n/**\n * What to launch (§3) — binding-resolved, NEVER a caller-named app. Exactly one of:\n * - `entryPoint`: a sibling entry point of the caller's OWN repo (the mini-app\n * case, `AGENT_AUTHORING §5`) — **rejected `forbidden` until program-identity\n * `appKey` lands** (R-SAL-2a);\n * - `task`: a task contract (`open-project`, …), resolved through the user-\n * overridable `task.<name>` binding to whichever app the user bound (§3 kind 2).\n */\nexport interface LaunchTarget {\n /** Kind 1 — a sibling entry point of the caller's own repo (mini-app overlay). */\n entryPoint?: string;\n /** Kind 2 — a task contract name (the host resolves the bound provider). */\n task?: string;\n /** Optional accepted contract version for a `task` target (semver, e.g. `^1`). */\n version?: string;\n}\n\nexport interface LaunchOptions {\n /** Where it runs (§6). */\n region: LaunchRegion;\n /**\n * Delegations + plain data handed to the launched app. `$cap:'dir'|'file'`\n * markers (`capDir`/`capFile`, exported from `./tasks`) are resolved against the\n * launcher's OWN grants and minted as attenuated, `ro`-by-default chroots (§5) —\n * you can only delegate what you already hold. Everything else is plain data.\n */\n input?: Record<string, unknown>;\n}\n\n/** The live state of a launch (§2). Terminal states (`dismissed`/`revoked`/\n * `failed`) are reached identically for self-exit, user dismiss, and host revoke —\n * the host debounces so the launcher gets no timing oracle (R-SAL-1 / §6.4). */\nexport type LaunchStatus = 'running' | 'dismissed' | 'revoked' | 'failed';\n\n/** Machine codes a refused `launch` resolves with (§8). */\nexport type LaunchErrorCode =\n | 'forbidden' // undeclared target; sibling (pre-AA-01); self-resolving target; stage cap absent\n | 'unsupported' // no provider bound / entry point absent / unknown contract version\n | 'budget' // over an R-SAL-8 concurrency/rate limit\n | 'revoked' // a delegated mount was revoked during the create-and-bind window\n | 'cancelled' // the user dismissed the host launch affordance (into-stage only)\n | 'invalid-params' // a malformed `capDir`/`capFile` (`..`/absolute/mode-escalation)\n | 'unknown';\n\n/**\n * The control channel back to a launch — the ONLY thing a launcher gets (§2).\n * There is no typed return value (R-SAL-1); `status`/`onDismiss` are debounced so\n * they cannot time-distinguish a self-exit from a user dismiss.\n */\nexport interface LaunchHandle {\n /** Host-assigned id for this launch. */\n readonly launchId: string;\n /** The current lifecycle state (§2). */\n readonly status: LaunchStatus;\n /** Ask the host to tear this launch down. Idempotent (double-dismiss is a no-op). */\n dismiss(): void;\n /**\n * Observe the launch ending (self-exit / user dismiss / host revoke — fired\n * identically, R-SAL-1). Returns an unsubscribe fn. Fires at most once; if the\n * launch has already ended it fires on the next tick.\n */\n onDismiss(cb: () => void): () => void;\n}\n\ninterface LaunchEndedMessage {\n launchId: string;\n status: Exclude<LaunchStatus, 'running'>;\n}\n\n/** Live handles awaiting their terminal `launch-ended` message, keyed by launchId. */\nconst liveHandles = new Map<string, LaunchHandleImpl>();\n\n/**\n * Terminal statuses that arrived BEFORE their handle existed, keyed by launchId.\n *\n * The window is real: `launch()` registers the listener before it sends `create`,\n * but the handle only enters `liveHandles` once the create RESPONSE resolves. A\n * short-lived launch (or a revoke during binding) can end inside that gap, and a\n * dropped terminal message leaves the handle `running` for ever with `onDismiss`\n * never firing — the one failure a launcher cannot detect or recover from. So the\n * message is BUFFERED and applied when the handle lands.\n *\n * Bounded, because the host is not this module's to trust: entries are only kept\n * while a create is actually in flight, and no more than {@link MAX_PENDING_ENDED}\n * of them (oldest evicted). A `launch-ended` for an id we never created is still\n * ignored, exactly as before.\n */\nconst pendingEnded = new Map<string, Exclude<LaunchStatus, 'running'>>();\nconst MAX_PENDING_ENDED = 16;\n/** How many `launch()` calls are between their create request and its response. */\nlet createsInFlight = 0;\n\n// The host delivers ONE `launch-ended` message per launch when it tears down —\n// the SAME message shape for self-exit, dismiss, and revoke (the host debounces\n// so the timing is not an oracle, §6.4). We fan it out to the matching handle, or\n// buffer it for a handle that has not landed yet (above).\n//\n// Registered LAZILY, on the first `launch()` call, not at module evaluation\n// (R3-421 — no subpath may throw at import time off-host). Unlike `task-input`\n// (tasks.ts), first-use registration loses nothing here: a `launch-ended` can only\n// ever follow a launch THIS module created, and `launch()` registers the listener\n// before it sends the create request — so the listener always exists before any\n// launchId it must match. That is a claim about the LISTENER only; the handle it\n// must reach can still be a response away, which is what `pendingEnded` covers.\nlet endedListenerRegistered = false;\nconst ensureEndedListener = (): void => {\n if (endedListenerRegistered) return;\n try {\n addListener(LAUNCH_ENDED, (m: LaunchEndedMessage) => {\n const h = liveHandles.get(m.launchId);\n if (h) {\n h._end(m.status);\n return;\n }\n // No handle yet. Buffer only while a create could still produce one; anything\n // else is a stale or unknown id and is ignored.\n if (createsInFlight === 0) return;\n if (pendingEnded.size >= MAX_PENDING_ENDED) {\n const oldest = pendingEnded.keys().next();\n if (!oldest.done) pendingEnded.delete(oldest.value);\n }\n pendingEnded.set(m.launchId, m.status);\n });\n } catch {\n return; // off-host: no transport — the create request below will fail anyway\n }\n endedListenerRegistered = true;\n};\n\nclass LaunchHandleImpl implements LaunchHandle {\n #status: LaunchStatus = 'running';\n #dismissListeners = new Set<() => void>();\n #ended = false;\n\n constructor(readonly launchId: string) {\n liveHandles.set(launchId, this);\n // A terminal message that beat this handle into existence (see `pendingEnded`):\n // apply it now, so the handle is born ended rather than stuck `running`.\n const early = pendingEnded.get(launchId);\n if (early !== undefined) {\n pendingEnded.delete(launchId);\n this._end(early);\n }\n }\n\n get status(): LaunchStatus {\n return this.#status;\n }\n\n dismiss(): void {\n if (this.#ended) return;\n // Fire-and-forget: the host owns teardown and answers with `launch-ended`,\n // which drives `_end` (so status/onDismiss are host-authoritative, never\n // optimistically local — a dismiss the host refuses would otherwise desync).\n sendMessage(LAUNCH_DISMISS, { launchId: this.launchId });\n }\n\n onDismiss(cb: () => void): () => void {\n if (this.#ended) {\n // Already ended: fire on the next tick so the contract (\"returns an\n // unsubscribe\") holds and the callback never runs synchronously mid-register.\n queueMicrotask(cb);\n return () => {};\n }\n this.#dismissListeners.add(cb);\n return () => {\n this.#dismissListeners.delete(cb);\n };\n }\n\n /** Host-driven terminal transition — the only writer of `status`. Idempotent. */\n _end(status: Exclude<LaunchStatus, 'running'>): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#status = status;\n liveHandles.delete(this.launchId);\n const listeners = [...this.#dismissListeners];\n this.#dismissListeners.clear();\n for (const l of listeners) {\n try {\n l();\n } catch {\n /* a launcher's own callback must never wedge teardown */\n }\n }\n }\n}\n\n/**\n * Launch a bound program to RUN in a region (§2). Non-blocking: resolves once the\n * frame is created and bound, with a {@link LaunchHandle} — or a typed\n * `{ ok:false, code }` on refusal (§8), NEVER a throw for an ordinary refusal (so\n * a launcher branches on `code` without a try/catch). The launched app runs under\n * its OWN grants; the launcher's authority does not flow to it (R-SAL-4).\n *\n * const h = await launch({ task: 'open-project' }, {\n * region: 'stage',\n * input: { dir: capDir({ mountId: 'space:abc', relPath: 'proj' }, { mode: 'ro' }) },\n * });\n * if ('ok' in h && h.ok === false) { ...handle h.code... }\n * else { h.onDismiss(() => ...); }\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to run a launch in.\n */\nexport const launch = async (\n target: LaunchTarget,\n opts: LaunchOptions,\n): Promise<LaunchHandle | { ok: false; code: LaunchErrorCode }> => {\n // Before the create request, so the terminal message can never beat the listener.\n ensureEndedListener();\n // The host wraps a successful handler return as `{ ok:true, data }` (the same\n // Recipe-B framing `invokeTask` uses); a refusal is `{ ok:false, code }`.\n createsInFlight += 1;\n let res: { ok: true; data: { launchId: string } } | { ok: false; code?: LaunchErrorCode } | undefined;\n try {\n res = (await protocolRequest(SCHEMES[PROTOCOL_LAUNCH], 'create', [{ target, opts }])) as typeof res;\n } finally {\n createsInFlight -= 1;\n }\n // Once nothing is in flight, anything still buffered belongs to a launch that will\n // never produce a handle — drop it rather than keep it for ever. Done AFTER the\n // handle below is constructed (its constructor drains its own entry first), so the\n // sweep can never eat the message this very call was waiting for.\n const sweep = (): void => {\n if (createsInFlight === 0) pendingEnded.clear();\n };\n if (!res || res.ok !== true || !res.data?.launchId) {\n sweep();\n const code = res && res.ok === false ? res.code ?? 'unknown' : 'unknown';\n return { ok: false, code };\n }\n // The constructor drains a terminal message that arrived while `create` was in\n // flight, so this handle can be returned already-ended rather than stuck `running`.\n const handle = new LaunchHandleImpl(res.data.launchId);\n sweep();\n return handle;\n};\n"],"mappings":";;;;;AAAA;AAWA,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,gBAAgB,cAAc,uBAAuB;AAC9D,SAAS,eAAe;AA6ExB,MAAM,cAAc,oBAAI,IAA8B;AAiBtD,MAAM,eAAe,oBAAI,IAA8C;AACvE,MAAM,oBAAoB;AAE1B,IAAI,kBAAkB;AActB,IAAI,0BAA0B;AAC9B,MAAM,sBAAsB,MAAY;AACtC,MAAI,wBAAyB;A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C,UAAM,YAAY,CAAC,GAAG,mBAAK,kBAAiB;AAC5C,uBAAK,mBAAkB,MAAM;AAC7B,eAAW,KAAK,WAAW;AACzB,UAAI;AACF,UAAE;AAAA,MACJ,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;AAxDE;AACA;AACA;AAyEK,MAAM,SAAS,OACpB,QACA,SACiE;AAEjE,sBAAoB;AAGpB,qBAAmB;AACnB,MAAI;AACJ,MAAI;AACF,UAAO,MAAM,gBAAgB,QAAQ,eAAe,GAAG,UAAU,CAAC,EAAE,QAAQ,KAAK,CAAC,CAAC;AAAA,EACrF,UAAE;AACA,uBAAmB;AAAA,EACrB;AAKA,QAAM,QAAQ,MAAY;AACxB,QAAI,oBAAoB,EAAG,cAAa,MAAM;AAAA,EAChD;AACA,MAAI,CAAC,OAAO,IAAI,OAAO,QAAQ,CAAC,IAAI,MAAM,UAAU;AAClD,UAAM;AACN,UAAM,OAAO,OAAO,IAAI,OAAO,QAAQ,IAAI,QAAQ,YAAY;AAC/D,WAAO,EAAE,IAAI,OAAO,KAAK;AAAA,EAC3B;AAGA,QAAM,SAAS,IAAI,iBAAiB,IAAI,KAAK,QAAQ;AACrD,QAAM;AACN,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/launch.ts"],"sourcesContent":["// Launch — the TO-RUN twin of `invokeTask` (STANDING_APP_LIFECYCLE_SPEC §1–§6).\n// Where `invokeTask` is FOR-RESULT (await one value, callee exits), `launch` is\n// TO-RUN (non-blocking, standing): it starts a bound program RUNNING in a region\n// and hands back a HANDLE, never a typed value (R-SAL-1). The launched app earns\n// its OWN grants — the only launcher→launched data path is the explicitly\n// delegated `capDir`/`capFile` in `input` (§5), attenuated + tainted + gated host-\n// side. The host owns the whole lifecycle (visibility, budget, revocation,\n// teardown); the launcher only OBSERVES via the handle.\n//\n// A caller that wants a typed value back uses `invokeTask` instead — the two are\n// siblings, not a replacement.\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { LAUNCH_DISMISS, LAUNCH_ENDED, PROTOCOL_LAUNCH } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a launched program runs (§6). `overlay` covers the caller's own region\n * with opaque host chrome; `stage` replaces the focal app (the elevated into-\n * stage surface, §7 — refused above the stage-principal ceiling). */\nexport type LaunchRegion = 'overlay' | 'stage';\n\n/**\n * What to launch (§3) — binding-resolved, NEVER a caller-named app. Exactly one of:\n * - `entryPoint`: a sibling entry point of the caller's OWN repo (the mini-app\n * case, `AGENT_AUTHORING §5`) — **rejected `forbidden` until program-identity\n * `appKey` lands** (R-SAL-2a);\n * - `task`: a task contract (`open-project`, …), resolved through the user-\n * overridable `task.<name>` binding to whichever app the user bound (§3 kind 2).\n */\nexport interface LaunchTarget {\n /** Kind 1 — a sibling entry point of the caller's own repo (mini-app overlay). */\n entryPoint?: string;\n /** Kind 2 — a task contract name (the host resolves the bound provider). */\n task?: string;\n /** Optional accepted contract version for a `task` target (semver, e.g. `^1`). */\n version?: string;\n}\n\nexport interface LaunchOptions {\n /** Where it runs (§6). */\n region: LaunchRegion;\n /**\n * Delegations + plain data handed to the launched app. `$cap:'dir'|'file'`\n * markers (`capDir`/`capFile`, exported from `./tasks`) are resolved against the\n * launcher's OWN grants and minted as attenuated, `ro`-by-default chroots (§5) —\n * you can only delegate what you already hold. Everything else is plain data.\n */\n input?: Record<string, unknown>;\n}\n\n/** The live state of a launch (§2). Terminal states (`dismissed`/`revoked`/\n * `failed`) are reached identically for self-exit, user dismiss, and host revoke —\n * the host debounces so the launcher gets no timing oracle (R-SAL-1 / §6.4). */\nexport type LaunchStatus = 'running' | 'dismissed' | 'revoked' | 'failed';\n\n/** Machine codes a refused `launch` resolves with (§8). */\nexport type LaunchErrorCode =\n | 'forbidden' // undeclared target; sibling (pre-AA-01); self-resolving target; stage cap absent\n | 'unsupported' // no provider bound / entry point absent / unknown contract version\n | 'budget' // over an R-SAL-8 concurrency/rate limit\n | 'revoked' // a delegated mount was revoked during the create-and-bind window\n | 'cancelled' // the user dismissed the host launch affordance (into-stage only)\n | 'invalid-params' // a malformed `capDir`/`capFile` (`..`/absolute/mode-escalation)\n | 'unknown';\n\n/**\n * The control channel back to a launch — the ONLY thing a launcher gets (§2).\n * There is no typed return value (R-SAL-1); `status`/`onDismiss` are debounced so\n * they cannot time-distinguish a self-exit from a user dismiss.\n */\nexport interface LaunchHandle {\n /** Host-assigned id for this launch. */\n readonly launchId: string;\n /** The current lifecycle state (§2). */\n readonly status: LaunchStatus;\n /** Ask the host to tear this launch down. Idempotent (double-dismiss is a no-op). */\n dismiss(): void;\n /**\n * Observe the launch ending (self-exit / user dismiss / host revoke — fired\n * identically, R-SAL-1). Returns an unsubscribe fn. Fires at most once; if the\n * launch has already ended it fires on the next tick.\n */\n onDismiss(cb: () => void): () => void;\n}\n\ninterface LaunchEndedMessage {\n launchId: string;\n status: Exclude<LaunchStatus, 'running'>;\n}\n\n/** Live handles awaiting their terminal `launch-ended` message, keyed by launchId. */\nconst liveHandles = new Map<string, LaunchHandleImpl>();\n\n/**\n * Terminal statuses that arrived BEFORE their handle existed, keyed by launchId.\n *\n * The window is real: `launch()` registers the listener before it sends `create`,\n * but the handle only enters `liveHandles` once the create RESPONSE resolves. A\n * short-lived launch (or a revoke during binding) can end inside that gap, and a\n * dropped terminal message leaves the handle `running` for ever with `onDismiss`\n * never firing — the one failure a launcher cannot detect or recover from. So the\n * message is BUFFERED and applied when the handle lands.\n *\n * Bounded, because the host is not this module's to trust: entries are only kept\n * while a create is actually in flight, and no more than {@link MAX_PENDING_ENDED}\n * of them (oldest evicted). A `launch-ended` for an id we never created is still\n * ignored, exactly as before.\n */\nconst pendingEnded = new Map<string, Exclude<LaunchStatus, 'running'>>();\nconst MAX_PENDING_ENDED = 16;\n/** How many `launch()` calls are between their create request and its response. */\nlet createsInFlight = 0;\n\n// The host delivers ONE `launch-ended` message per launch when it tears down —\n// the SAME message shape for self-exit, dismiss, and revoke (the host debounces\n// so the timing is not an oracle, §6.4). We fan it out to the matching handle, or\n// buffer it for a handle that has not landed yet (above).\n//\n// Registered LAZILY, on the first `launch()` call, not at module evaluation\n// (R3-421 — no subpath may throw at import time off-host). First-use registration\n// loses nothing here: a `launch-ended` can only\n// ever follow a launch THIS module created, and `launch()` registers the listener\n// before it sends the create request — so the listener always exists before any\n// launchId it must match. That is a claim about the LISTENER only; the handle it\n// must reach can still be a response away, which is what `pendingEnded` covers.\nlet endedListenerRegistered = false;\nconst ensureEndedListener = (): void => {\n if (endedListenerRegistered) return;\n try {\n addListener(LAUNCH_ENDED, (m: LaunchEndedMessage) => {\n const h = liveHandles.get(m.launchId);\n if (h) {\n h._end(m.status);\n return;\n }\n // No handle yet. Buffer only while a create could still produce one; anything\n // else is a stale or unknown id and is ignored.\n if (createsInFlight === 0) return;\n if (pendingEnded.size >= MAX_PENDING_ENDED) {\n const oldest = pendingEnded.keys().next();\n if (!oldest.done) pendingEnded.delete(oldest.value);\n }\n pendingEnded.set(m.launchId, m.status);\n });\n } catch {\n return; // off-host: no transport — the create request below will fail anyway\n }\n endedListenerRegistered = true;\n};\n\nclass LaunchHandleImpl implements LaunchHandle {\n #status: LaunchStatus = 'running';\n #dismissListeners = new Set<() => void>();\n #ended = false;\n\n constructor(readonly launchId: string) {\n liveHandles.set(launchId, this);\n // A terminal message that beat this handle into existence (see `pendingEnded`):\n // apply it now, so the handle is born ended rather than stuck `running`.\n const early = pendingEnded.get(launchId);\n if (early !== undefined) {\n pendingEnded.delete(launchId);\n this._end(early);\n }\n }\n\n get status(): LaunchStatus {\n return this.#status;\n }\n\n dismiss(): void {\n if (this.#ended) return;\n // Fire-and-forget: the host owns teardown and answers with `launch-ended`,\n // which drives `_end` (so status/onDismiss are host-authoritative, never\n // optimistically local — a dismiss the host refuses would otherwise desync).\n sendMessage(LAUNCH_DISMISS, { launchId: this.launchId });\n }\n\n onDismiss(cb: () => void): () => void {\n if (this.#ended) {\n // Already ended: fire on the next tick so the contract (\"returns an\n // unsubscribe\") holds and the callback never runs synchronously mid-register.\n queueMicrotask(cb);\n return () => {};\n }\n this.#dismissListeners.add(cb);\n return () => {\n this.#dismissListeners.delete(cb);\n };\n }\n\n /** Host-driven terminal transition — the only writer of `status`. Idempotent. */\n _end(status: Exclude<LaunchStatus, 'running'>): void {\n if (this.#ended) return;\n this.#ended = true;\n this.#status = status;\n liveHandles.delete(this.launchId);\n const listeners = [...this.#dismissListeners];\n this.#dismissListeners.clear();\n for (const l of listeners) {\n try {\n l();\n } catch {\n /* a launcher's own callback must never wedge teardown */\n }\n }\n }\n}\n\n/**\n * Launch a bound program to RUN in a region (§2). Non-blocking: resolves once the\n * frame is created and bound, with a {@link LaunchHandle} — or a typed\n * `{ ok:false, code }` on refusal (§8), NEVER a throw for an ordinary refusal (so\n * a launcher branches on `code` without a try/catch). The launched app runs under\n * its OWN grants; the launcher's authority does not flow to it (R-SAL-4).\n *\n * const h = await launch({ task: 'open-project' }, {\n * region: 'stage',\n * input: { dir: capDir({ mountId: 'space:abc', relPath: 'proj' }, { mode: 'ro' }) },\n * });\n * if ('ok' in h && h.ok === false) { ...handle h.code... }\n * else { h.onDismiss(() => ...); }\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to run a launch in.\n */\nexport const launch = async (\n target: LaunchTarget,\n opts: LaunchOptions,\n): Promise<LaunchHandle | { ok: false; code: LaunchErrorCode }> => {\n // Before the create request, so the terminal message can never beat the listener.\n ensureEndedListener();\n // The host wraps a successful handler return as `{ ok:true, data }` (the same\n // Recipe-B framing `invokeTask` uses); a refusal is `{ ok:false, code }`.\n createsInFlight += 1;\n let res: { ok: true; data: { launchId: string } } | { ok: false; code?: LaunchErrorCode } | undefined;\n try {\n res = (await protocolRequest(SCHEMES[PROTOCOL_LAUNCH], 'create', [{ target, opts }])) as typeof res;\n } finally {\n createsInFlight -= 1;\n }\n // Once nothing is in flight, anything still buffered belongs to a launch that will\n // never produce a handle — drop it rather than keep it for ever. Done AFTER the\n // handle below is constructed (its constructor drains its own entry first), so the\n // sweep can never eat the message this very call was waiting for.\n const sweep = (): void => {\n if (createsInFlight === 0) pendingEnded.clear();\n };\n if (!res || res.ok !== true || !res.data?.launchId) {\n sweep();\n const code = res && res.ok === false ? res.code ?? 'unknown' : 'unknown';\n return { ok: false, code };\n }\n // The constructor drains a terminal message that arrived while `create` was in\n // flight, so this handle can be returned already-ended rather than stuck `running`.\n const handle = new LaunchHandleImpl(res.data.launchId);\n sweep();\n return handle;\n};\n"],"mappings":";;;;;AAAA;AAWA,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,gBAAgB,cAAc,uBAAuB;AAC9D,SAAS,eAAe;AA6ExB,MAAM,cAAc,oBAAI,IAA8B;AAiBtD,MAAM,eAAe,oBAAI,IAA8C;AACvE,MAAM,oBAAoB;AAE1B,IAAI,kBAAkB;AActB,IAAI,0BAA0B;AAC9B,MAAM,sBAAsB,MAAY;AACtC,MAAI,wBAAyB;AAC7B,MAAI;AACF,gBAAY,cAAc,CAAC,MAA0B;AACnD,YAAM,IAAI,YAAY,IAAI,EAAE,QAAQ;AACpC,UAAI,GAAG;AACL,UAAE,KAAK,EAAE,MAAM;AACf;AAAA,MACF;AAGA,UAAI,oBAAoB,EAAG;AAC3B,UAAI,aAAa,QAAQ,mBAAmB;AAC1C,cAAM,SAAS,aAAa,KAAK,EAAE,KAAK;AACxC,YAAI,CAAC,OAAO,KAAM,cAAa,OAAO,OAAO,KAAK;AAAA,MACpD;AACA,mBAAa,IAAI,EAAE,UAAU,EAAE,MAAM;AAAA,IACvC,CAAC;AAAA,EACH,QAAQ;AACN;AAAA,EACF;AACA,4BAA0B;AAC5B;AAEA,MAAM,iBAAyC;AAAA,EAK7C,YAAqB,UAAkB;AAAlB;AAJrB,gCAAwB;AACxB,0CAAoB,oBAAI,IAAgB;AACxC,+BAAS;AAGP,gBAAY,IAAI,UAAU,IAAI;AAG9B,UAAM,QAAQ,aAAa,IAAI,QAAQ;AACvC,QAAI,UAA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/D,WAAO,EAAE,IAAI,OAAO,KAAK;AAAA,EAC3B;AAGA,QAAM,SAAS,IAAI,iBAAiB,IAAI,KAAK,QAAQ;AACrD,QAAM;AACN,SAAO;AACT;","names":[]}
@@ -34,6 +34,19 @@ class ModuleCache {
34
34
  (0, import_sandboxUtils.addListener)(import_protocol.COMPILE, () => {
35
35
  });
36
36
  }
37
+ // PROMISE-IDENTITY INVARIANT (the app-frame Suspense replay; pinned by
38
+ // src/boot.suspenseReplay.test.tsx): the promise returned by
39
+ // `getEvaluationContext` for a given key must be THE SAME promise for the
40
+ // whole realm boot. `Include` hands it straight to React's `use()` — a new
41
+ // identity for the same key mid-session re-suspends the boundary and REPLAYS
42
+ // every effect under it while the component instance, refs, DOM and
43
+ // in-flight promise chains survive (the Suspense hide/reveal signature). The
44
+ // invariant holds because the cache lives for the whole boot (one instance
45
+ // per `boot()` call), entries are never evicted (the compile seam above
46
+ // stays disabled), and the key — base-module filepath + module name — is
47
+ // stable for a stable URL. Any change that lets the same key answer a fresh
48
+ // promise (eviction, a scoped compile reset, a re-created cache) re-opens
49
+ // the replay, and the named test then fails loudly.
37
50
  getCacheKey(mod, moduleName) {
38
51
  return `${mod.evaluation.module.filepath}|${moduleName}`;
39
52
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/moduleCache.tsx"],"sourcesContent":["// based on: https://www.bbss.dev/posts/react-learn-suspense/#fetchcache-provider\n\nimport { createContext, ReactNode } from 'react';\nimport { EvaluationContext } from './sandboxTypes';\nimport { addListener } from './sandboxUtils';\nimport { COMPILE } from './generated/protocol';\n\nexport class ModuleCache {\n nameResolutionPromises: Record<string, Promise<string>> = {};\n evaluationContextPromises: Record<string, Promise<EvaluationContext>> = {};\n\n constructor() {\n // A compile-time cache reset, deliberately NOT performed. Resetting here\n // replaced every <Include>'s module-evaluation-context promise with a new\n // promise for the same value on EVERY compilation, including compilations that\n // do not affect that module, so the component lost its state for nothing. The\n // listener stays registered (and the reset stays here, disabled) because the\n // fix is to scope the reset to the modules a compile actually changed, not to\n // drop the seam.\n addListener(COMPILE, () => {\n // this.nameResolutionPromises = {};\n // this.evaluationContextPromises = {};\n });\n }\n\n private getCacheKey(mod: EvaluationContext, moduleName: string): string {\n return `${mod.evaluation.module.filepath}|${moduleName}`;\n }\n\n resolveModuleName(moduleName: string, baseModule?: EvaluationContext): Promise<string> {\n // note: uses current module as base module if none specified by caller\n // @ts-ignore\n const mod = baseModule ?? (module as EvaluationContext);\n const cacheKey = this.getCacheKey(mod, moduleName);\n if (!(cacheKey in this.nameResolutionPromises)) {\n this.nameResolutionPromises[cacheKey] = mod.resolve(moduleName);\n }\n return this.nameResolutionPromises[cacheKey];\n }\n\n getEvaluationContext(moduleName: string, baseModule?: EvaluationContext): Promise<EvaluationContext> {\n // note: uses current module as base module if none specified by caller\n // @ts-ignore\n const mod = baseModule ?? (module as EvaluationContext);\n const cacheKey = this.getCacheKey(mod, moduleName);\n if (!(cacheKey in this.evaluationContextPromises)) {\n this.evaluationContextPromises[cacheKey] = mod.getModuleEvaluationContext(moduleName);\n }\n return this.evaluationContextPromises[cacheKey];\n }\n}\n\nexport const ModuleCacheContext = createContext<null | ModuleCache>(null);\n\nexport const ModuleCacheContextProvider = ({\n children,\n moduleCache,\n}: {\n children: ReactNode;\n moduleCache: ModuleCache;\n}) => {\n return <ModuleCacheContext.Provider value={moduleCache}>{children}</ModuleCacheContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6DS;AA3DT,mBAAyC;AAEzC,0BAA4B;AAC5B,sBAAwB;AAEjB,MAAM,YAAY;AAAA,EAIvB,cAAc;AAHd,kCAA0D,CAAC;AAC3D,qCAAwE,CAAC;AAUvE,yCAAY,yBAAS,MAAM;AAAA,IAG3B,CAAC;AAAA,EACH;AAAA,EAEQ,YAAY,KAAwB,YAA4B;AACtE,WAAO,GAAG,IAAI,WAAW,OAAO,QAAQ,IAAI,UAAU;AAAA,EACxD;AAAA,EAEA,kBAAkB,YAAoB,YAAiD;AAGrF,UAAM,MAAM,cAAe;AAC3B,UAAM,WAAW,KAAK,YAAY,KAAK,UAAU;AACjD,QAAI,EAAE,YAAY,KAAK,yBAAyB;AAC9C,WAAK,uBAAuB,QAAQ,IAAI,IAAI,QAAQ,UAAU;AAAA,IAChE;AACA,WAAO,KAAK,uBAAuB,QAAQ;AAAA,EAC7C;AAAA,EAEA,qBAAqB,YAAoB,YAA4D;AAGnG,UAAM,MAAM,cAAe;AAC3B,UAAM,WAAW,KAAK,YAAY,KAAK,UAAU;AACjD,QAAI,EAAE,YAAY,KAAK,4BAA4B;AACjD,WAAK,0BAA0B,QAAQ,IAAI,IAAI,2BAA2B,UAAU;AAAA,IACtF;AACA,WAAO,KAAK,0BAA0B,QAAQ;AAAA,EAChD;AACF;AAEO,MAAM,yBAAqB,4BAAkC,IAAI;AAEjE,MAAM,6BAA6B,CAAC;AAAA,EACzC;AAAA,EACA;AACF,MAGM;AACJ,SAAO,4CAAC,mBAAmB,UAAnB,EAA4B,OAAO,aAAc,UAAS;AACpE;","names":[]}
1
+ {"version":3,"sources":["../src/moduleCache.tsx"],"sourcesContent":["// based on: https://www.bbss.dev/posts/react-learn-suspense/#fetchcache-provider\n\nimport { createContext, ReactNode } from 'react';\nimport { EvaluationContext } from './sandboxTypes';\nimport { addListener } from './sandboxUtils';\nimport { COMPILE } from './generated/protocol';\n\nexport class ModuleCache {\n nameResolutionPromises: Record<string, Promise<string>> = {};\n evaluationContextPromises: Record<string, Promise<EvaluationContext>> = {};\n\n constructor() {\n // A compile-time cache reset, deliberately NOT performed. Resetting here\n // replaced every <Include>'s module-evaluation-context promise with a new\n // promise for the same value on EVERY compilation, including compilations that\n // do not affect that module, so the component lost its state for nothing. The\n // listener stays registered (and the reset stays here, disabled) because the\n // fix is to scope the reset to the modules a compile actually changed, not to\n // drop the seam.\n addListener(COMPILE, () => {\n // this.nameResolutionPromises = {};\n // this.evaluationContextPromises = {};\n });\n }\n\n // PROMISE-IDENTITY INVARIANT (the app-frame Suspense replay; pinned by\n // src/boot.suspenseReplay.test.tsx): the promise returned by\n // `getEvaluationContext` for a given key must be THE SAME promise for the\n // whole realm boot. `Include` hands it straight to React's `use()` — a new\n // identity for the same key mid-session re-suspends the boundary and REPLAYS\n // every effect under it while the component instance, refs, DOM and\n // in-flight promise chains survive (the Suspense hide/reveal signature). The\n // invariant holds because the cache lives for the whole boot (one instance\n // per `boot()` call), entries are never evicted (the compile seam above\n // stays disabled), and the key — base-module filepath + module name — is\n // stable for a stable URL. Any change that lets the same key answer a fresh\n // promise (eviction, a scoped compile reset, a re-created cache) re-opens\n // the replay, and the named test then fails loudly.\n\n private getCacheKey(mod: EvaluationContext, moduleName: string): string {\n return `${mod.evaluation.module.filepath}|${moduleName}`;\n }\n\n resolveModuleName(moduleName: string, baseModule?: EvaluationContext): Promise<string> {\n // note: uses current module as base module if none specified by caller\n // @ts-ignore\n const mod = baseModule ?? (module as EvaluationContext);\n const cacheKey = this.getCacheKey(mod, moduleName);\n if (!(cacheKey in this.nameResolutionPromises)) {\n this.nameResolutionPromises[cacheKey] = mod.resolve(moduleName);\n }\n return this.nameResolutionPromises[cacheKey];\n }\n\n getEvaluationContext(moduleName: string, baseModule?: EvaluationContext): Promise<EvaluationContext> {\n // note: uses current module as base module if none specified by caller\n // @ts-ignore\n const mod = baseModule ?? (module as EvaluationContext);\n const cacheKey = this.getCacheKey(mod, moduleName);\n if (!(cacheKey in this.evaluationContextPromises)) {\n this.evaluationContextPromises[cacheKey] = mod.getModuleEvaluationContext(moduleName);\n }\n return this.evaluationContextPromises[cacheKey];\n }\n}\n\nexport const ModuleCacheContext = createContext<null | ModuleCache>(null);\n\nexport const ModuleCacheContextProvider = ({\n children,\n moduleCache,\n}: {\n children: ReactNode;\n moduleCache: ModuleCache;\n}) => {\n return <ModuleCacheContext.Provider value={moduleCache}>{children}</ModuleCacheContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2ES;AAzET,mBAAyC;AAEzC,0BAA4B;AAC5B,sBAAwB;AAEjB,MAAM,YAAY;AAAA,EAIvB,cAAc;AAHd,kCAA0D,CAAC;AAC3D,qCAAwE,CAAC;AAUvE,yCAAY,yBAAS,MAAM;AAAA,IAG3B,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBQ,YAAY,KAAwB,YAA4B;AACtE,WAAO,GAAG,IAAI,WAAW,OAAO,QAAQ,IAAI,UAAU;AAAA,EACxD;AAAA,EAEA,kBAAkB,YAAoB,YAAiD;AAGrF,UAAM,MAAM,cAAe;AAC3B,UAAM,WAAW,KAAK,YAAY,KAAK,UAAU;AACjD,QAAI,EAAE,YAAY,KAAK,yBAAyB;AAC9C,WAAK,uBAAuB,QAAQ,IAAI,IAAI,QAAQ,UAAU;AAAA,IAChE;AACA,WAAO,KAAK,uBAAuB,QAAQ;AAAA,EAC7C;AAAA,EAEA,qBAAqB,YAAoB,YAA4D;AAGnG,UAAM,MAAM,cAAe;AAC3B,UAAM,WAAW,KAAK,YAAY,KAAK,UAAU;AACjD,QAAI,EAAE,YAAY,KAAK,4BAA4B;AACjD,WAAK,0BAA0B,QAAQ,IAAI,IAAI,2BAA2B,UAAU;AAAA,IACtF;AACA,WAAO,KAAK,0BAA0B,QAAQ;AAAA,EAChD;AACF;AAEO,MAAM,yBAAqB,4BAAkC,IAAI;AAEjE,MAAM,6BAA6B,CAAC;AAAA,EACzC;AAAA,EACA;AACF,MAGM;AACJ,SAAO,4CAAC,mBAAmB,UAAnB,EAA4B,OAAO,aAAc,UAAS;AACpE;","names":[]}
@@ -10,6 +10,19 @@ class ModuleCache {
10
10
  addListener(COMPILE, () => {
11
11
  });
12
12
  }
13
+ // PROMISE-IDENTITY INVARIANT (the app-frame Suspense replay; pinned by
14
+ // src/boot.suspenseReplay.test.tsx): the promise returned by
15
+ // `getEvaluationContext` for a given key must be THE SAME promise for the
16
+ // whole realm boot. `Include` hands it straight to React's `use()` — a new
17
+ // identity for the same key mid-session re-suspends the boundary and REPLAYS
18
+ // every effect under it while the component instance, refs, DOM and
19
+ // in-flight promise chains survive (the Suspense hide/reveal signature). The
20
+ // invariant holds because the cache lives for the whole boot (one instance
21
+ // per `boot()` call), entries are never evicted (the compile seam above
22
+ // stays disabled), and the key — base-module filepath + module name — is
23
+ // stable for a stable URL. Any change that lets the same key answer a fresh
24
+ // promise (eviction, a scoped compile reset, a re-created cache) re-opens
25
+ // the replay, and the named test then fails loudly.
13
26
  getCacheKey(mod, moduleName) {
14
27
  return `${mod.evaluation.module.filepath}|${moduleName}`;
15
28
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/moduleCache.tsx"],"sourcesContent":["// based on: https://www.bbss.dev/posts/react-learn-suspense/#fetchcache-provider\n\nimport { createContext, ReactNode } from 'react';\nimport { EvaluationContext } from './sandboxTypes';\nimport { addListener } from './sandboxUtils';\nimport { COMPILE } from './generated/protocol';\n\nexport class ModuleCache {\n nameResolutionPromises: Record<string, Promise<string>> = {};\n evaluationContextPromises: Record<string, Promise<EvaluationContext>> = {};\n\n constructor() {\n // A compile-time cache reset, deliberately NOT performed. Resetting here\n // replaced every <Include>'s module-evaluation-context promise with a new\n // promise for the same value on EVERY compilation, including compilations that\n // do not affect that module, so the component lost its state for nothing. The\n // listener stays registered (and the reset stays here, disabled) because the\n // fix is to scope the reset to the modules a compile actually changed, not to\n // drop the seam.\n addListener(COMPILE, () => {\n // this.nameResolutionPromises = {};\n // this.evaluationContextPromises = {};\n });\n }\n\n private getCacheKey(mod: EvaluationContext, moduleName: string): string {\n return `${mod.evaluation.module.filepath}|${moduleName}`;\n }\n\n resolveModuleName(moduleName: string, baseModule?: EvaluationContext): Promise<string> {\n // note: uses current module as base module if none specified by caller\n // @ts-ignore\n const mod = baseModule ?? (module as EvaluationContext);\n const cacheKey = this.getCacheKey(mod, moduleName);\n if (!(cacheKey in this.nameResolutionPromises)) {\n this.nameResolutionPromises[cacheKey] = mod.resolve(moduleName);\n }\n return this.nameResolutionPromises[cacheKey];\n }\n\n getEvaluationContext(moduleName: string, baseModule?: EvaluationContext): Promise<EvaluationContext> {\n // note: uses current module as base module if none specified by caller\n // @ts-ignore\n const mod = baseModule ?? (module as EvaluationContext);\n const cacheKey = this.getCacheKey(mod, moduleName);\n if (!(cacheKey in this.evaluationContextPromises)) {\n this.evaluationContextPromises[cacheKey] = mod.getModuleEvaluationContext(moduleName);\n }\n return this.evaluationContextPromises[cacheKey];\n }\n}\n\nexport const ModuleCacheContext = createContext<null | ModuleCache>(null);\n\nexport const ModuleCacheContextProvider = ({\n children,\n moduleCache,\n}: {\n children: ReactNode;\n moduleCache: ModuleCache;\n}) => {\n return <ModuleCacheContext.Provider value={moduleCache}>{children}</ModuleCacheContext.Provider>;\n};\n"],"mappings":";AA6DS;AA3DT,SAAS,qBAAgC;AAEzC,SAAS,mBAAmB;AAC5B,SAAS,eAAe;AAEjB,MAAM,YAAY;AAAA,EAIvB,cAAc;AAHd,kCAA0D,CAAC;AAC3D,qCAAwE,CAAC;AAUvE,gBAAY,SAAS,MAAM;AAAA,IAG3B,CAAC;AAAA,EACH;AAAA,EAEQ,YAAY,KAAwB,YAA4B;AACtE,WAAO,GAAG,IAAI,WAAW,OAAO,QAAQ,IAAI,UAAU;AAAA,EACxD;AAAA,EAEA,kBAAkB,YAAoB,YAAiD;AAGrF,UAAM,MAAM,cAAe;AAC3B,UAAM,WAAW,KAAK,YAAY,KAAK,UAAU;AACjD,QAAI,EAAE,YAAY,KAAK,yBAAyB;AAC9C,WAAK,uBAAuB,QAAQ,IAAI,IAAI,QAAQ,UAAU;AAAA,IAChE;AACA,WAAO,KAAK,uBAAuB,QAAQ;AAAA,EAC7C;AAAA,EAEA,qBAAqB,YAAoB,YAA4D;AAGnG,UAAM,MAAM,cAAe;AAC3B,UAAM,WAAW,KAAK,YAAY,KAAK,UAAU;AACjD,QAAI,EAAE,YAAY,KAAK,4BAA4B;AACjD,WAAK,0BAA0B,QAAQ,IAAI,IAAI,2BAA2B,UAAU;AAAA,IACtF;AACA,WAAO,KAAK,0BAA0B,QAAQ;AAAA,EAChD;AACF;AAEO,MAAM,qBAAqB,cAAkC,IAAI;AAEjE,MAAM,6BAA6B,CAAC;AAAA,EACzC;AAAA,EACA;AACF,MAGM;AACJ,SAAO,oBAAC,mBAAmB,UAAnB,EAA4B,OAAO,aAAc,UAAS;AACpE;","names":[]}
1
+ {"version":3,"sources":["../src/moduleCache.tsx"],"sourcesContent":["// based on: https://www.bbss.dev/posts/react-learn-suspense/#fetchcache-provider\n\nimport { createContext, ReactNode } from 'react';\nimport { EvaluationContext } from './sandboxTypes';\nimport { addListener } from './sandboxUtils';\nimport { COMPILE } from './generated/protocol';\n\nexport class ModuleCache {\n nameResolutionPromises: Record<string, Promise<string>> = {};\n evaluationContextPromises: Record<string, Promise<EvaluationContext>> = {};\n\n constructor() {\n // A compile-time cache reset, deliberately NOT performed. Resetting here\n // replaced every <Include>'s module-evaluation-context promise with a new\n // promise for the same value on EVERY compilation, including compilations that\n // do not affect that module, so the component lost its state for nothing. The\n // listener stays registered (and the reset stays here, disabled) because the\n // fix is to scope the reset to the modules a compile actually changed, not to\n // drop the seam.\n addListener(COMPILE, () => {\n // this.nameResolutionPromises = {};\n // this.evaluationContextPromises = {};\n });\n }\n\n // PROMISE-IDENTITY INVARIANT (the app-frame Suspense replay; pinned by\n // src/boot.suspenseReplay.test.tsx): the promise returned by\n // `getEvaluationContext` for a given key must be THE SAME promise for the\n // whole realm boot. `Include` hands it straight to React's `use()` — a new\n // identity for the same key mid-session re-suspends the boundary and REPLAYS\n // every effect under it while the component instance, refs, DOM and\n // in-flight promise chains survive (the Suspense hide/reveal signature). The\n // invariant holds because the cache lives for the whole boot (one instance\n // per `boot()` call), entries are never evicted (the compile seam above\n // stays disabled), and the key — base-module filepath + module name — is\n // stable for a stable URL. Any change that lets the same key answer a fresh\n // promise (eviction, a scoped compile reset, a re-created cache) re-opens\n // the replay, and the named test then fails loudly.\n\n private getCacheKey(mod: EvaluationContext, moduleName: string): string {\n return `${mod.evaluation.module.filepath}|${moduleName}`;\n }\n\n resolveModuleName(moduleName: string, baseModule?: EvaluationContext): Promise<string> {\n // note: uses current module as base module if none specified by caller\n // @ts-ignore\n const mod = baseModule ?? (module as EvaluationContext);\n const cacheKey = this.getCacheKey(mod, moduleName);\n if (!(cacheKey in this.nameResolutionPromises)) {\n this.nameResolutionPromises[cacheKey] = mod.resolve(moduleName);\n }\n return this.nameResolutionPromises[cacheKey];\n }\n\n getEvaluationContext(moduleName: string, baseModule?: EvaluationContext): Promise<EvaluationContext> {\n // note: uses current module as base module if none specified by caller\n // @ts-ignore\n const mod = baseModule ?? (module as EvaluationContext);\n const cacheKey = this.getCacheKey(mod, moduleName);\n if (!(cacheKey in this.evaluationContextPromises)) {\n this.evaluationContextPromises[cacheKey] = mod.getModuleEvaluationContext(moduleName);\n }\n return this.evaluationContextPromises[cacheKey];\n }\n}\n\nexport const ModuleCacheContext = createContext<null | ModuleCache>(null);\n\nexport const ModuleCacheContextProvider = ({\n children,\n moduleCache,\n}: {\n children: ReactNode;\n moduleCache: ModuleCache;\n}) => {\n return <ModuleCacheContext.Provider value={moduleCache}>{children}</ModuleCacheContext.Provider>;\n};\n"],"mappings":";AA2ES;AAzET,SAAS,qBAAgC;AAEzC,SAAS,mBAAmB;AAC5B,SAAS,eAAe;AAEjB,MAAM,YAAY;AAAA,EAIvB,cAAc;AAHd,kCAA0D,CAAC;AAC3D,qCAAwE,CAAC;AAUvE,gBAAY,SAAS,MAAM;AAAA,IAG3B,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBQ,YAAY,KAAwB,YAA4B;AACtE,WAAO,GAAG,IAAI,WAAW,OAAO,QAAQ,IAAI,UAAU;AAAA,EACxD;AAAA,EAEA,kBAAkB,YAAoB,YAAiD;AAGrF,UAAM,MAAM,cAAe;AAC3B,UAAM,WAAW,KAAK,YAAY,KAAK,UAAU;AACjD,QAAI,EAAE,YAAY,KAAK,yBAAyB;AAC9C,WAAK,uBAAuB,QAAQ,IAAI,IAAI,QAAQ,UAAU;AAAA,IAChE;AACA,WAAO,KAAK,uBAAuB,QAAQ;AAAA,EAC7C;AAAA,EAEA,qBAAqB,YAAoB,YAA4D;AAGnG,UAAM,MAAM,cAAe;AAC3B,UAAM,WAAW,KAAK,YAAY,KAAK,UAAU;AACjD,QAAI,EAAE,YAAY,KAAK,4BAA4B;AACjD,WAAK,0BAA0B,QAAQ,IAAI,IAAI,2BAA2B,UAAU;AAAA,IACtF;AACA,WAAO,KAAK,0BAA0B,QAAQ;AAAA,EAChD;AACF;AAEO,MAAM,qBAAqB,cAAkC,IAAI;AAEjE,MAAM,6BAA6B,CAAC;AAAA,EACzC;AAAA,EACA;AACF,MAGM;AACJ,SAAO,oBAAC,mBAAmB,UAAnB,EAA4B,OAAO,aAAc,UAAS;AACpE;","names":[]}
package/dist/tasks.cjs CHANGED
@@ -60,17 +60,40 @@ const captureAudio = (options = {}) => invokeTask("capture-audio", { ...options
60
60
  let latestInput = null;
61
61
  const inputListeners = /* @__PURE__ */ new Set();
62
62
  let inputListenerRegistered = false;
63
- const ensureInputListener = () => {
64
- if (inputListenerRegistered) return;
63
+ const sameTaskInput = (a, b) => {
64
+ if (a.task !== b.task) return false;
65
65
  try {
66
- (0, import_sandboxUtils.addListener)(import_protocol.TASK_INPUT, (m) => {
67
- latestInput = { task: m.task, params: m.params ?? {} };
68
- inputListeners.forEach((l) => l(latestInput));
69
- });
66
+ return JSON.stringify(a.params) === JSON.stringify(b.params);
70
67
  } catch {
71
- return;
68
+ return false;
69
+ }
70
+ };
71
+ let inputPolled = false;
72
+ let inputPollFailureReported = false;
73
+ const ensureInputListener = () => {
74
+ if (!inputListenerRegistered) {
75
+ try {
76
+ (0, import_sandboxUtils.addListener)(import_protocol.TASK_INPUT, (m) => {
77
+ const next = { task: m.task, params: m.params ?? {} };
78
+ if (latestInput && sameTaskInput(latestInput, next)) return;
79
+ latestInput = next;
80
+ inputListeners.forEach((l) => l(next));
81
+ });
82
+ } catch {
83
+ return;
84
+ }
85
+ inputListenerRegistered = true;
86
+ }
87
+ if (inputPolled) return;
88
+ try {
89
+ (0, import_sandboxUtils.sendMessage)(import_protocol.REQUEST_TASK_INPUT);
90
+ inputPolled = true;
91
+ } catch (err) {
92
+ if (!inputPollFailureReported) {
93
+ inputPollFailureReported = true;
94
+ console.warn("[immediately.run] the task-input poll could not be sent; it is retried on the next read.", err);
95
+ }
72
96
  }
73
- inputListenerRegistered = true;
74
97
  };
75
98
  ensureInputListener();
76
99
  const getTaskInput = () => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\n//\n// OFF-HOST (plain `vite dev`, node/jsdom tests — no sandbox, no host transport):\n// importing this module is always safe (R3-421 — no subpath may throw at import\n// time), and the surface degrades instead of crashing: `getTaskInput()` /\n// `useTaskInput()` stay `null` forever (you are never a task callee without a\n// host), `completeTask` / `cancelTask` are no-ops, and `invokeTask` rejects with\n// a \"no host transport\" error. Under the @immediately-run/dev-fs substrate the\n// transport resolves but no task ever arrives — same observable behaviour.\n// The no-op is scoped to the ABSENCE of a host: when there IS one, a failed send\n// throws instead of leaving the caller to hang out its deadline.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { transport } from './hostTransport';\nimport { PROTOCOL_TASK, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): FileCap => ({\n $cap: 'file',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): DirCap => ({\n $cap: 'dir',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (missing `task:invoke`, or a\n * file delegation you don't hold), `not-declared` (the task is missing from your\n * `immediately.run.invokes`), `no-such-task` (no app is bound to that contract),\n * `task-cycle`/`task-depth-exceeded`/`task-version-mismatch`, or `invalid-params`\n * (result failed the contract schema). **Read `err.message`** — since R3-418 the host\n * says which capability, which declaration or which param was at fault; the code alone\n * does not distinguish them.\n *\n * Two things must BOTH be true before any invoke is admitted, and they are separate:\n * 1. your `package.json` `immediately.run.invokes` lists the task (else `not-declared`);\n * 2. your app holds the `task:invoke` capability — declare it in\n * `immediately.run.capabilities` so the user can grant it (else `forbidden`).\n * Declaring the invoke does not imply the capability.\n *\n * ── `pick-file`: `roots` is required (SPACES_UI_SPEC §4.1) ───────────────────\n * ```ts\n * import { invokeTask, capDir, requestMount } from '@immediately-run/sdk';\n *\n * const mount = await requestMount(); // the user picks a space\n * // `invokeTask` returns `unknown` — name the result type, or the destructuring\n * // below does not compile.\n * const { root, path } = await invokeTask<{ root: number; path: string }>('pick-file', {\n * // `SandboxMount.id` is optional (absent on the primary repo mount) — fall back to\n * // `path`, which is always present and is what the host resolves against.\n * roots: [capDir({ mountId: mount.id ?? mount.path, relPath: 'boards' }, { mode: 'ro' })],\n * });\n * ```\n * - `roots` is a NON-EMPTY `DirCap[]` of directories you **already hold**. The result\n * names its target as `{ root, path }` where `root` INDEXES `params.roots`, so\n * `invokeTask('pick-file', {})` can never produce a valid result and is rejected.\n * There is no rootless \"pick from any of my spaces\" mode by design: enumerating the\n * user's spaces is the host's powerbox (`requestMount()`), and composing the two —\n * as above — is that flow. See SPACES_UI_SPEC R-SPACES-5/R-SPACES-12.\n * - Each `capDir` is attenuated against your own grant. **`{ mode: 'rw' }` over a space\n * the user granted `ro` is refused `forbidden`** — the commonest failure, because the\n * mount *was* granted and the path *is* inside it. Pass the mode you actually hold;\n * `ro` is right for a plain pick.\n * - The `requestMount()` grant is DURABLE and survives a cancelled pick: the user\n * consented to the mount in host chrome, separately from the pick (SPACES_UI_SPEC §4.1).\n * Reuse it for later picks rather than re-requesting.\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to resolve the task binding.\n */\nexport const invokeTask = async <R = unknown>(task: string, params: Record<string, unknown> = {}): Promise<R> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }])) as\n | { ok: true; data: R }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `task '${task}' failed`) as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n// ── the host-provided CAPTURE contracts (R3-425) ────────────────────────────\n\n/** Bytes captured by the host, as `capturePhoto()` / `captureAudio()` return them.\n * `bytes` is a transferable `ArrayBuffer` — write it to a space, decode it, upload\n * it. You never receive a `MediaStream` or a `MediaStreamTrack`, and that is not an\n * omission: a track cannot be transferred into an app frame at all\n * (`DataCloneError`), and the frame's opaque origin cannot open a device itself\n * (`getUserMedia` throws `SecurityError: Invalid security origin`). */\nexport interface CaptureResult {\n bytes: ArrayBuffer;\n /** e.g. `image/jpeg`, `audio/webm`. Chosen by the HOST, not by you. */\n mimeType: string;\n /** How long the device was open, in ms. */\n durationMs: number;\n}\n\n/** Optional hints for a capture. They deliberately name NOTHING — no device id, no\n * camera index — because the host chooses everything about how the capture is\n * performed. That is what lets the grant be a plain on/off instead of a per-call\n * target list the way `net:fetch` needs. */\nexport interface CaptureOptions {\n /** Which way the camera should face, if the device has a choice. A HINT: the host\n * may ignore it. Ignored for audio. */\n facing?: 'user' | 'environment';\n}\n\n/**\n * Take one photo, or record one audio clip, through the HOST's capture UI\n * (`BROWSER_CAPABILITIES_SPEC` §3 grade 1).\n *\n * The host opens the device at its own origin, draws the viewfinder, and hands you\n * the bytes when the user presses Done. **You are never in the loop while the device\n * is live** — that is the point of the design, not a limitation of it:\n *\n * - The capture UI is drawn by the host, so a user can trust it the way they trust\n * the sign-in dialog. Do not build a lookalike; imitating host chrome is spoofing.\n * - While the device is open the host shows a persistent \"camera on\" / \"microphone\n * on\" indicator in its own chrome, for the whole session. You cannot hide it and\n * should not try to.\n * - If the user cancels, this rejects `cancelled` and **nothing was recorded**. There\n * is no partial result — do not write error handling that hopes for one.\n *\n * ```ts\n * import { capturePhoto, requestMount, openFs } from '@immediately-run/sdk';\n *\n * try {\n * const { bytes, mimeType } = await capturePhoto({ facing: 'environment' });\n * const mount = await requestMount(); // the user picks a space to save into\n * const fs = openFs(mount); // writeFile is a METHOD on the MountFs\n * await fs.mkdir('photos', { recursive: true }); // writeFile does not create parents\n * await fs.writeFile(`photos/latest.${mimeType === 'image/png' ? 'png' : 'jpg'}`, new Uint8Array(bytes));\n * } catch (e) {\n * if ((e as { code?: string }).code === 'cancelled') return; // the user said no\n * throw e;\n * }\n * ```\n * (The extension follows `mimeType` because the HOST chooses the format — do not assume\n * JPEG. `openAppFs()` is the variant that writes to your own app space with no pick.)\n *\n * Two things must BOTH be true, exactly as for any other task:\n * 1. `immediately.run.invokes` lists `capture-photo` (or `capture-audio`);\n * 2. your app holds `task:invoke` **and** `device:camera` (or `device:microphone`)\n * — declare them in `immediately.run.capabilities` so the user can grant them.\n *\n * Rejects with `.code`: `cancelled` (the user dismissed the capture — nothing was\n * recorded), `forbidden` (you lack the capability; `message: 'browser-denied'` means\n * the BROWSER refused immediately.run itself, which your consent cannot fix),\n * `unavailable` (no such device on this machine, or it would not start),\n * `unsupported` (this host cannot capture), `not-declared`, `timeout`.\n *\n * *Zero-platform alternative, still worth knowing:* `<input type=\"file\"\n * accept=\"image/*\" capture=\"environment\">` opens the OS camera from inside the\n * sandbox (file choosers are not permission-gated). It needs no capability and no\n * host support; it also gives you no indicator and no host-drawn surface.\n */\nexport const capturePhoto = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-photo', { ...options });\n\n/** Record one audio clip through the host's capture UI. See {@link capturePhoto} —\n * every rule there applies verbatim, with `device:microphone` and `capture-audio`. */\nexport const captureAudio = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-audio', { ...options });\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\nlet inputListenerRegistered = false;\n\n// Register the `task-input` listener IF a host transport is reachable; otherwise do\n// nothing (and let the next call retry — the same pattern as pushChannel's `start`).\n// Split out so both the module-eval attempt below and the first-use call sites share\n// one idempotent path.\nconst ensureInputListener = (): void => {\n if (inputListenerRegistered) return;\n try {\n addListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n latestInput = { task: m.task, params: m.params ?? {} };\n inputListeners.forEach((l) => l(latestInput!));\n });\n } catch {\n return; // off-host: the transport resolver threw — no host to listen on\n }\n inputListenerRegistered = true;\n};\n\n// The host delivers a `task-input` message to the callee's iframe right after it\n// mounts the overlay (the §5.7 \"params via the region's mount event\"). That wire\n// message is a plain one-shot host→app message with NO replay/poll counterpart —\n// the contract (`@immediately-run/sandbox-protocol/sdk`) marks replayable state as\n// \"push … polled with request-*\" (mounts, theme, auth-state, …) and `task-input`\n// is not one of them — so a listener registered only on first use could miss an\n// input delivered between module evaluation and the app's first render. Hence:\n// register EAGERLY when a host transport is already present at module eval\n// (on-host, byte-for-byte the pre-R3-421 behaviour), and lazily-on-first-use\n// otherwise, so importing this module off-host (plain `vite dev`) never throws.\nensureInputListener();\n\n/** The task params this app was invoked with, or null if it isn't a task callee.\n * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke\n * this app as a callee. */\nexport const getTaskInput = (): TaskInput | null => {\n ensureInputListener();\n return latestInput;\n};\n\n/**\n * Is a host transport reachable from this realm at all?\n *\n * The R3-421 off-host no-op below must mean EXACTLY \"there is nobody to answer\" —\n * plain `vite dev`, node, jsdom. A blanket try/catch around the send meant it also\n * swallowed a genuine failure against a REAL host (`DataCloneError` because the\n * result holds a DOM node, a function or a live class instance, being the usual\n * one): the host was then never told the task finished, and the caller's\n * `invokeTask` hung to its deadline with no diagnostic anywhere. Absence is\n * therefore decided BEFORE the send, and the send itself is left to throw.\n */\nconst hostReachable = (): boolean => {\n try {\n transport();\n return true;\n } catch {\n return false; // no injected bundler bus and no §4 discovery global — off-host\n }\n};\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n *\n * `result` must be STRUCTURED-CLONEABLE — it crosses a frame boundary. A DOM node, a\n * function, a class instance with methods, a `MediaStreamTrack`: all `DataCloneError`.\n * **That throws**, deliberately and loudly: the alternative is a caller left hanging to\n * its `invokeTask` deadline while this app believes it answered.\n *\n * Off-host (plain `vite dev` — no host transport) this is a no-op: there is no caller\n * to answer. That case, and only that case, is silent.\n */\nexport const completeTask = (result: unknown): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n // On-host, a failure here is REAL and the caller is waiting on this exact message.\n sendMessage(TASK_COMPLETE, { result });\n};\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`.\n * Off-host (plain `vite dev` — no host transport) this is a no-op; on-host a failed\n * send throws rather than leaving the caller waiting, exactly as {@link completeTask}. */\nexport const cancelTask = (): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n sendMessage(TASK_CANCEL, {});\n};\n\n/** React hook: the task input for this callee, re-rendering when it arrives.\n * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee\n * state rather than waiting on it. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete(l);\n };\n }, []);\n return input;\n};\n"],"mappings":";;;;;;;;;;;;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AAC;AAAA,EACH,QAAQ;AACN;AAAA,EACF;AACA,4BAA0B;AAC5B;AAYA,oBAAoB;AAKb,MAAM,eAAe,MAAwB;AAClD,sBAAoB;AACpB,SAAO;AACT;AAaA,MAAM,gBAAgB,MAAe;AACnC,MAAI;AACF,wCAAU;AACV,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAeO,MAAM,eAAe,CAAC,WAA0B;AACrD,MAAI,CAAC,cAAc,EAAG;AAEtB,uCAAY,+BAAe,EAAE,OAAO,CAAC;AACvC;AAKO,MAAM,aAAa,MAAY;AACpC,MAAI,CAAC,cAAc,EAAG;AACtB,uCAAY,6BAAa,CAAC,CAAC;AAC7B;AAKO,MAAM,eAAe,MAAwB;AAClD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAA2B,YAAY;AACjE,8BAAU,MAAM;AACd,UAAM,IAAI,CAAC,MAAiB,SAAS,CAAC;AACtC,mBAAe,IAAI,CAAC;AACpB,QAAI,YAAa,UAAS,WAAW;AACrC,WAAO,MAAM;AACX,qBAAe,OAAO,CAAC;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\n//\n// OFF-HOST (plain `vite dev`, node/jsdom tests — no sandbox, no host transport):\n// importing this module is always safe (R3-421 — no subpath may throw at import\n// time), and the surface degrades instead of crashing: `getTaskInput()` /\n// `useTaskInput()` stay `null` forever (you are never a task callee without a\n// host), `completeTask` / `cancelTask` are no-ops, and `invokeTask` rejects with\n// a \"no host transport\" error. Under the @immediately-run/dev-fs substrate the\n// transport resolves but no task ever arrives — same observable behaviour.\n// The no-op is scoped to the ABSENCE of a host: when there IS one, a failed send\n// throws instead of leaving the caller to hang out its deadline.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { transport } from './hostTransport';\nimport { PROTOCOL_TASK, REQUEST_TASK_INPUT, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): FileCap => ({\n $cap: 'file',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): DirCap => ({\n $cap: 'dir',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (missing `task:invoke`, or a\n * file delegation you don't hold), `not-declared` (the task is missing from your\n * `immediately.run.invokes`), `no-such-task` (no app is bound to that contract),\n * `task-cycle`/`task-depth-exceeded`/`task-version-mismatch`, or `invalid-params`\n * (result failed the contract schema). **Read `err.message`** — since R3-418 the host\n * says which capability, which declaration or which param was at fault; the code alone\n * does not distinguish them.\n *\n * Two things must BOTH be true before any invoke is admitted, and they are separate:\n * 1. your `package.json` `immediately.run.invokes` lists the task (else `not-declared`);\n * 2. your app holds the `task:invoke` capability — declare it in\n * `immediately.run.capabilities` so the user can grant it (else `forbidden`).\n * Declaring the invoke does not imply the capability.\n *\n * ── `pick-file`: `roots` is required (SPACES_UI_SPEC §4.1) ───────────────────\n * ```ts\n * import { invokeTask, capDir, requestMount } from '@immediately-run/sdk';\n *\n * const mount = await requestMount(); // the user picks a space\n * // `invokeTask` returns `unknown` — name the result type, or the destructuring\n * // below does not compile.\n * const { root, path } = await invokeTask<{ root: number; path: string }>('pick-file', {\n * // `SandboxMount.id` is optional (absent on the primary repo mount) — fall back to\n * // `path`, which is always present and is what the host resolves against.\n * roots: [capDir({ mountId: mount.id ?? mount.path, relPath: 'boards' }, { mode: 'ro' })],\n * });\n * ```\n * - `roots` is a NON-EMPTY `DirCap[]` of directories you **already hold**. The result\n * names its target as `{ root, path }` where `root` INDEXES `params.roots`, so\n * `invokeTask('pick-file', {})` can never produce a valid result and is rejected.\n * There is no rootless \"pick from any of my spaces\" mode by design: enumerating the\n * user's spaces is the host's powerbox (`requestMount()`), and composing the two —\n * as above — is that flow. See SPACES_UI_SPEC R-SPACES-5/R-SPACES-12.\n * - Each `capDir` is attenuated against your own grant. **`{ mode: 'rw' }` over a space\n * the user granted `ro` is refused `forbidden`** — the commonest failure, because the\n * mount *was* granted and the path *is* inside it. Pass the mode you actually hold;\n * `ro` is right for a plain pick.\n * - The `requestMount()` grant is DURABLE and survives a cancelled pick: the user\n * consented to the mount in host chrome, separately from the pick (SPACES_UI_SPEC §4.1).\n * Reuse it for later picks rather than re-requesting.\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to resolve the task binding.\n */\nexport const invokeTask = async <R = unknown>(task: string, params: Record<string, unknown> = {}): Promise<R> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }])) as\n | { ok: true; data: R }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `task '${task}' failed`) as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n// ── the host-provided CAPTURE contracts (R3-425) ────────────────────────────\n\n/** Bytes captured by the host, as `capturePhoto()` / `captureAudio()` return them.\n * `bytes` is a transferable `ArrayBuffer` — write it to a space, decode it, upload\n * it. You never receive a `MediaStream` or a `MediaStreamTrack`, and that is not an\n * omission: a track cannot be transferred into an app frame at all\n * (`DataCloneError`), and the frame's opaque origin cannot open a device itself\n * (`getUserMedia` throws `SecurityError: Invalid security origin`). */\nexport interface CaptureResult {\n bytes: ArrayBuffer;\n /** e.g. `image/jpeg`, `audio/webm`. Chosen by the HOST, not by you. */\n mimeType: string;\n /** How long the device was open, in ms. */\n durationMs: number;\n}\n\n/** Optional hints for a capture. They deliberately name NOTHING — no device id, no\n * camera index — because the host chooses everything about how the capture is\n * performed. That is what lets the grant be a plain on/off instead of a per-call\n * target list the way `net:fetch` needs. */\nexport interface CaptureOptions {\n /** Which way the camera should face, if the device has a choice. A HINT: the host\n * may ignore it. Ignored for audio. */\n facing?: 'user' | 'environment';\n}\n\n/**\n * Take one photo, or record one audio clip, through the HOST's capture UI\n * (`BROWSER_CAPABILITIES_SPEC` §3 grade 1).\n *\n * The host opens the device at its own origin, draws the viewfinder, and hands you\n * the bytes when the user presses Done. **You are never in the loop while the device\n * is live** — that is the point of the design, not a limitation of it:\n *\n * - The capture UI is drawn by the host, so a user can trust it the way they trust\n * the sign-in dialog. Do not build a lookalike; imitating host chrome is spoofing.\n * - While the device is open the host shows a persistent \"camera on\" / \"microphone\n * on\" indicator in its own chrome, for the whole session. You cannot hide it and\n * should not try to.\n * - If the user cancels, this rejects `cancelled` and **nothing was recorded**. There\n * is no partial result — do not write error handling that hopes for one.\n *\n * ```ts\n * import { capturePhoto, requestMount, openFs } from '@immediately-run/sdk';\n *\n * try {\n * const { bytes, mimeType } = await capturePhoto({ facing: 'environment' });\n * const mount = await requestMount(); // the user picks a space to save into\n * const fs = openFs(mount); // writeFile is a METHOD on the MountFs\n * await fs.mkdir('photos', { recursive: true }); // writeFile does not create parents\n * await fs.writeFile(`photos/latest.${mimeType === 'image/png' ? 'png' : 'jpg'}`, new Uint8Array(bytes));\n * } catch (e) {\n * if ((e as { code?: string }).code === 'cancelled') return; // the user said no\n * throw e;\n * }\n * ```\n * (The extension follows `mimeType` because the HOST chooses the format — do not assume\n * JPEG. `openAppFs()` is the variant that writes to your own app space with no pick.)\n *\n * Two things must BOTH be true, exactly as for any other task:\n * 1. `immediately.run.invokes` lists `capture-photo` (or `capture-audio`);\n * 2. your app holds `task:invoke` **and** `device:camera` (or `device:microphone`)\n * — declare them in `immediately.run.capabilities` so the user can grant them.\n *\n * Rejects with `.code`: `cancelled` (the user dismissed the capture — nothing was\n * recorded), `forbidden` (you lack the capability; `message: 'browser-denied'` means\n * the BROWSER refused immediately.run itself, which your consent cannot fix),\n * `unavailable` (no such device on this machine, or it would not start),\n * `unsupported` (this host cannot capture), `not-declared`, `timeout`.\n *\n * *Zero-platform alternative, still worth knowing:* `<input type=\"file\"\n * accept=\"image/*\" capture=\"environment\">` opens the OS camera from inside the\n * sandbox (file choosers are not permission-gated). It needs no capability and no\n * host support; it also gives you no indicator and no host-drawn surface.\n */\nexport const capturePhoto = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-photo', { ...options });\n\n/** Record one audio clip through the host's capture UI. See {@link capturePhoto} —\n * every rule there applies verbatim, with `device:microphone` and `capture-audio`. */\nexport const captureAudio = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-audio', { ...options });\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\nlet inputListenerRegistered = false;\n\n/**\n * Whether two deliveries carry the same input, compared by their JSON image. The host does\n * not check that params are JSON; the hosts' senders build them from strings and plain\n * objects, for which the image is faithful. A value JSON cannot serialise at all (it\n * throws) is treated as a change; a value JSON writes lossily (a `Map`, a `Blob`) is not\n * told apart, so two inputs differing only there compare equal.\n */\nconst sameTaskInput = (a: TaskInput, b: TaskInput): boolean => {\n if (a.task !== b.task) return false;\n try {\n return JSON.stringify(a.params) === JSON.stringify(b.params);\n } catch {\n return false;\n }\n};\n\n// Register the `task-input` listener IF a host transport is reachable; otherwise do\n// nothing (and let the next call retry — the same pattern as pushChannel's `start`).\n// Split out so both the module-eval attempt below and the first-use call sites share\n// one idempotent path.\n//\n// Registration then pulls the input once with `request-task-input`, the way `mounts`\n// pulls with `request-mounts`: the host answers a callee frame with its current\n// `task-input` and answers nothing to any other frame. So the input arrives whenever\n// this listener comes to exist, and a host send that landed before it is not lost.\n//\n// The poll has its own latch, set only once a send returns. The listener registering\n// proves there is a host, so a send that then throws is a real failure, not the off-host\n// case: it is reported once and tried again on the next read, because a poll that never\n// goes out leaves a callee looking exactly like an app that is not one.\nlet inputPolled = false;\nlet inputPollFailureReported = false;\nconst ensureInputListener = (): void => {\n if (!inputListenerRegistered) {\n try {\n addListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n const next: TaskInput = { task: m.task, params: m.params ?? {} };\n // The host sends the same input several times (at mount, past each compile, and\n // in answer to the poll). A repeat keeps the object the app already has, so an\n // effect keyed on the input does not run again for a value that did not change.\n if (latestInput && sameTaskInput(latestInput, next)) return;\n latestInput = next;\n inputListeners.forEach((l) => l(next));\n });\n } catch {\n return; // off-host: the transport resolver threw — no host to listen on\n }\n inputListenerRegistered = true;\n }\n if (inputPolled) return;\n try {\n sendMessage(REQUEST_TASK_INPUT);\n inputPolled = true;\n } catch (err) {\n if (!inputPollFailureReported) {\n inputPollFailureReported = true;\n console.warn('[immediately.run] the task-input poll could not be sent; it is retried on the next read.', err);\n }\n }\n};\n\n// Register eagerly when a host transport is already present at module evaluation, and\n// lazily on first use otherwise, so importing this module off-host (plain `vite dev`)\n// never throws. Either way the registration polls, so against a host that answers the\n// poll its timing no longer decides whether the input is seen; against an older host the\n// eager registration is still what catches the send made at mount.\nensureInputListener();\n\n/** The task params this app was invoked with, or null if it isn't a task callee.\n * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke\n * this app as a callee. The object changes only when the task or its params change:\n * the host may deliver the same input more than once, and a repeat returns the same\n * object. */\nexport const getTaskInput = (): TaskInput | null => {\n ensureInputListener();\n return latestInput;\n};\n\n/**\n * Is a host transport reachable from this realm at all?\n *\n * The R3-421 off-host no-op below must mean EXACTLY \"there is nobody to answer\" —\n * plain `vite dev`, node, jsdom. A blanket try/catch around the send meant it also\n * swallowed a genuine failure against a REAL host (`DataCloneError` because the\n * result holds a DOM node, a function or a live class instance, being the usual\n * one): the host was then never told the task finished, and the caller's\n * `invokeTask` hung to its deadline with no diagnostic anywhere. Absence is\n * therefore decided BEFORE the send, and the send itself is left to throw.\n */\nconst hostReachable = (): boolean => {\n try {\n transport();\n return true;\n } catch {\n return false; // no injected bundler bus and no §4 discovery global — off-host\n }\n};\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n *\n * `result` must be STRUCTURED-CLONEABLE — it crosses a frame boundary. A DOM node, a\n * function, a class instance with methods, a `MediaStreamTrack`: all `DataCloneError`.\n * **That throws**, deliberately and loudly: the alternative is a caller left hanging to\n * its `invokeTask` deadline while this app believes it answered.\n *\n * Off-host (plain `vite dev` — no host transport) this is a no-op: there is no caller\n * to answer. That case, and only that case, is silent.\n */\nexport const completeTask = (result: unknown): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n // On-host, a failure here is REAL and the caller is waiting on this exact message.\n sendMessage(TASK_COMPLETE, { result });\n};\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`.\n * Off-host (plain `vite dev` — no host transport) this is a no-op; on-host a failed\n * send throws rather than leaving the caller waiting, exactly as {@link completeTask}. */\nexport const cancelTask = (): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n sendMessage(TASK_CANCEL, {});\n};\n\n/** React hook: the task input for this callee, re-rendering when it arrives.\n * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee\n * state rather than waiting on it. A repeated delivery of the same input is not\n * announced: the value's identity changes only when the task or its params do. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete(l);\n };\n }, []);\n return input;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,mBAAoC;AACpC,0BAA0D;AAC1D,2BAA0B;AAC1B,sBAA0F;AAC1F,6BAAwB;AAmBjB,MAAM,UAAU,CAAC,KAA2C,UAA0C;AAAA,EAC3G,MAAM;A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AAa,IAAI,EAAG;AACrD,sBAAc;AACd,uBAAe,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC;AAAA,MACvC,CAAC;AAAA,IACH,QAAQ;AACN;AAAA,IACF;AACA,8BAA0B;AAAA,EAC5B;AACA,MAAI,YAAa;AACjB,MAAI;AACF,yCAAY,kCAAkB;AAC9B,kBAAc;AAAA,EAChB,SAAS,KAAK;AACZ,QAAI,CAAC,0BAA0B;AAC7B,iCAA2B;AAC3B,cAAQ,KAAK,4FAA4F,GAAG;AAAA,IAC9G;AAAA,EACF;AACF;AAOA,oBAAoB;AAOb,MAAM,eAAe,MAAwB;AAClD,sBAAoB;AACpB,SAAO;AACT;AAaA,MAAM,gBAAgB,MAAe;AACnC,MAAI;AACF,wCAAU;AACV,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAeO,MAAM,eAAe,CAAC,WAA0B;AACrD,MAAI,CAAC,cAAc,EAAG;AAEtB,uCAAY,+BAAe,EAAE,OAAO,CAAC;AACvC;AAKO,MAAM,aAAa,MAAY;AACpC,MAAI,CAAC,cAAc,EAAG;AACtB,uCAAY,6BAAa,CAAC,CAAC;AAC7B;AAMO,MAAM,eAAe,MAAwB;AAClD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAA2B,YAAY;AACjE,8BAAU,MAAM;AACd,UAAM,IAAI,CAAC,MAAiB,SAAS,CAAC;AACtC,mBAAe,IAAI,CAAC;AACpB,QAAI,YAAa,UAAS,WAAW;AACrC,WAAO,MAAM;AACX,qBAAe,OAAO,CAAC;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO;AACT;","names":[]}
package/dist/tasks.d.cts CHANGED
@@ -171,7 +171,9 @@ interface TaskInput {
171
171
  }
172
172
  /** The task params this app was invoked with, or null if it isn't a task callee.
173
173
  * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke
174
- * this app as a callee. */
174
+ * this app as a callee. The object changes only when the task or its params change:
175
+ * the host may deliver the same input more than once, and a repeat returns the same
176
+ * object. */
175
177
  declare const getTaskInput: () => TaskInput | null;
176
178
  /**
177
179
  * Finish the task, returning a result to the caller. The host validates it against
@@ -193,7 +195,8 @@ declare const completeTask: (result: unknown) => void;
193
195
  declare const cancelTask: () => void;
194
196
  /** React hook: the task input for this callee, re-rendering when it arrives.
195
197
  * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee
196
- * state rather than waiting on it. */
198
+ * state rather than waiting on it. A repeated delivery of the same input is not
199
+ * announced: the value's identity changes only when the task or its params do. */
197
200
  declare const useTaskInput: () => TaskInput | null;
198
201
 
199
202
  export { type CaptureOptions, type CaptureResult, type DirCap, type FileCap, type TaskInput, cancelTask, capDir, capFile, captureAudio, capturePhoto, completeTask, getTaskInput, invokeTask, useTaskInput };
package/dist/tasks.d.ts CHANGED
@@ -171,7 +171,9 @@ interface TaskInput {
171
171
  }
172
172
  /** The task params this app was invoked with, or null if it isn't a task callee.
173
173
  * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke
174
- * this app as a callee. */
174
+ * this app as a callee. The object changes only when the task or its params change:
175
+ * the host may deliver the same input more than once, and a repeat returns the same
176
+ * object. */
175
177
  declare const getTaskInput: () => TaskInput | null;
176
178
  /**
177
179
  * Finish the task, returning a result to the caller. The host validates it against
@@ -193,7 +195,8 @@ declare const completeTask: (result: unknown) => void;
193
195
  declare const cancelTask: () => void;
194
196
  /** React hook: the task input for this callee, re-rendering when it arrives.
195
197
  * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee
196
- * state rather than waiting on it. */
198
+ * state rather than waiting on it. A repeated delivery of the same input is not
199
+ * announced: the value's identity changes only when the task or its params do. */
197
200
  declare const useTaskInput: () => TaskInput | null;
198
201
 
199
202
  export { type CaptureOptions, type CaptureResult, type DirCap, type FileCap, type TaskInput, cancelTask, capDir, capFile, captureAudio, capturePhoto, completeTask, getTaskInput, invokeTask, useTaskInput };
package/dist/tasks.js CHANGED
@@ -2,7 +2,7 @@ import "./chunk-VHAA22YE.js";
2
2
  import { useEffect, useState } from "react";
3
3
  import { protocolRequest, sendMessage, addListener } from "./sandboxUtils.js";
4
4
  import { transport } from "./hostTransport.js";
5
- import { PROTOCOL_TASK, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from "./generated/protocol.js";
5
+ import { PROTOCOL_TASK, REQUEST_TASK_INPUT, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from "./generated/protocol.js";
6
6
  import { SCHEMES } from "./protocolSchemes.js";
7
7
  const capFile = (ref, opts) => ({
8
8
  $cap: "file",
@@ -30,17 +30,40 @@ const captureAudio = (options = {}) => invokeTask("capture-audio", { ...options
30
30
  let latestInput = null;
31
31
  const inputListeners = /* @__PURE__ */ new Set();
32
32
  let inputListenerRegistered = false;
33
- const ensureInputListener = () => {
34
- if (inputListenerRegistered) return;
33
+ const sameTaskInput = (a, b) => {
34
+ if (a.task !== b.task) return false;
35
35
  try {
36
- addListener(TASK_INPUT, (m) => {
37
- latestInput = { task: m.task, params: m.params ?? {} };
38
- inputListeners.forEach((l) => l(latestInput));
39
- });
36
+ return JSON.stringify(a.params) === JSON.stringify(b.params);
40
37
  } catch {
41
- return;
38
+ return false;
39
+ }
40
+ };
41
+ let inputPolled = false;
42
+ let inputPollFailureReported = false;
43
+ const ensureInputListener = () => {
44
+ if (!inputListenerRegistered) {
45
+ try {
46
+ addListener(TASK_INPUT, (m) => {
47
+ const next = { task: m.task, params: m.params ?? {} };
48
+ if (latestInput && sameTaskInput(latestInput, next)) return;
49
+ latestInput = next;
50
+ inputListeners.forEach((l) => l(next));
51
+ });
52
+ } catch {
53
+ return;
54
+ }
55
+ inputListenerRegistered = true;
56
+ }
57
+ if (inputPolled) return;
58
+ try {
59
+ sendMessage(REQUEST_TASK_INPUT);
60
+ inputPolled = true;
61
+ } catch (err) {
62
+ if (!inputPollFailureReported) {
63
+ inputPollFailureReported = true;
64
+ console.warn("[immediately.run] the task-input poll could not be sent; it is retried on the next read.", err);
65
+ }
42
66
  }
43
- inputListenerRegistered = true;
44
67
  };
45
68
  ensureInputListener();
46
69
  const getTaskInput = () => {
package/dist/tasks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\n//\n// OFF-HOST (plain `vite dev`, node/jsdom tests — no sandbox, no host transport):\n// importing this module is always safe (R3-421 — no subpath may throw at import\n// time), and the surface degrades instead of crashing: `getTaskInput()` /\n// `useTaskInput()` stay `null` forever (you are never a task callee without a\n// host), `completeTask` / `cancelTask` are no-ops, and `invokeTask` rejects with\n// a \"no host transport\" error. Under the @immediately-run/dev-fs substrate the\n// transport resolves but no task ever arrives — same observable behaviour.\n// The no-op is scoped to the ABSENCE of a host: when there IS one, a failed send\n// throws instead of leaving the caller to hang out its deadline.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { transport } from './hostTransport';\nimport { PROTOCOL_TASK, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): FileCap => ({\n $cap: 'file',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): DirCap => ({\n $cap: 'dir',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (missing `task:invoke`, or a\n * file delegation you don't hold), `not-declared` (the task is missing from your\n * `immediately.run.invokes`), `no-such-task` (no app is bound to that contract),\n * `task-cycle`/`task-depth-exceeded`/`task-version-mismatch`, or `invalid-params`\n * (result failed the contract schema). **Read `err.message`** — since R3-418 the host\n * says which capability, which declaration or which param was at fault; the code alone\n * does not distinguish them.\n *\n * Two things must BOTH be true before any invoke is admitted, and they are separate:\n * 1. your `package.json` `immediately.run.invokes` lists the task (else `not-declared`);\n * 2. your app holds the `task:invoke` capability — declare it in\n * `immediately.run.capabilities` so the user can grant it (else `forbidden`).\n * Declaring the invoke does not imply the capability.\n *\n * ── `pick-file`: `roots` is required (SPACES_UI_SPEC §4.1) ───────────────────\n * ```ts\n * import { invokeTask, capDir, requestMount } from '@immediately-run/sdk';\n *\n * const mount = await requestMount(); // the user picks a space\n * // `invokeTask` returns `unknown` — name the result type, or the destructuring\n * // below does not compile.\n * const { root, path } = await invokeTask<{ root: number; path: string }>('pick-file', {\n * // `SandboxMount.id` is optional (absent on the primary repo mount) — fall back to\n * // `path`, which is always present and is what the host resolves against.\n * roots: [capDir({ mountId: mount.id ?? mount.path, relPath: 'boards' }, { mode: 'ro' })],\n * });\n * ```\n * - `roots` is a NON-EMPTY `DirCap[]` of directories you **already hold**. The result\n * names its target as `{ root, path }` where `root` INDEXES `params.roots`, so\n * `invokeTask('pick-file', {})` can never produce a valid result and is rejected.\n * There is no rootless \"pick from any of my spaces\" mode by design: enumerating the\n * user's spaces is the host's powerbox (`requestMount()`), and composing the two —\n * as above — is that flow. See SPACES_UI_SPEC R-SPACES-5/R-SPACES-12.\n * - Each `capDir` is attenuated against your own grant. **`{ mode: 'rw' }` over a space\n * the user granted `ro` is refused `forbidden`** — the commonest failure, because the\n * mount *was* granted and the path *is* inside it. Pass the mode you actually hold;\n * `ro` is right for a plain pick.\n * - The `requestMount()` grant is DURABLE and survives a cancelled pick: the user\n * consented to the mount in host chrome, separately from the pick (SPACES_UI_SPEC §4.1).\n * Reuse it for later picks rather than re-requesting.\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to resolve the task binding.\n */\nexport const invokeTask = async <R = unknown>(task: string, params: Record<string, unknown> = {}): Promise<R> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }])) as\n | { ok: true; data: R }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `task '${task}' failed`) as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n// ── the host-provided CAPTURE contracts (R3-425) ────────────────────────────\n\n/** Bytes captured by the host, as `capturePhoto()` / `captureAudio()` return them.\n * `bytes` is a transferable `ArrayBuffer` — write it to a space, decode it, upload\n * it. You never receive a `MediaStream` or a `MediaStreamTrack`, and that is not an\n * omission: a track cannot be transferred into an app frame at all\n * (`DataCloneError`), and the frame's opaque origin cannot open a device itself\n * (`getUserMedia` throws `SecurityError: Invalid security origin`). */\nexport interface CaptureResult {\n bytes: ArrayBuffer;\n /** e.g. `image/jpeg`, `audio/webm`. Chosen by the HOST, not by you. */\n mimeType: string;\n /** How long the device was open, in ms. */\n durationMs: number;\n}\n\n/** Optional hints for a capture. They deliberately name NOTHING — no device id, no\n * camera index — because the host chooses everything about how the capture is\n * performed. That is what lets the grant be a plain on/off instead of a per-call\n * target list the way `net:fetch` needs. */\nexport interface CaptureOptions {\n /** Which way the camera should face, if the device has a choice. A HINT: the host\n * may ignore it. Ignored for audio. */\n facing?: 'user' | 'environment';\n}\n\n/**\n * Take one photo, or record one audio clip, through the HOST's capture UI\n * (`BROWSER_CAPABILITIES_SPEC` §3 grade 1).\n *\n * The host opens the device at its own origin, draws the viewfinder, and hands you\n * the bytes when the user presses Done. **You are never in the loop while the device\n * is live** — that is the point of the design, not a limitation of it:\n *\n * - The capture UI is drawn by the host, so a user can trust it the way they trust\n * the sign-in dialog. Do not build a lookalike; imitating host chrome is spoofing.\n * - While the device is open the host shows a persistent \"camera on\" / \"microphone\n * on\" indicator in its own chrome, for the whole session. You cannot hide it and\n * should not try to.\n * - If the user cancels, this rejects `cancelled` and **nothing was recorded**. There\n * is no partial result — do not write error handling that hopes for one.\n *\n * ```ts\n * import { capturePhoto, requestMount, openFs } from '@immediately-run/sdk';\n *\n * try {\n * const { bytes, mimeType } = await capturePhoto({ facing: 'environment' });\n * const mount = await requestMount(); // the user picks a space to save into\n * const fs = openFs(mount); // writeFile is a METHOD on the MountFs\n * await fs.mkdir('photos', { recursive: true }); // writeFile does not create parents\n * await fs.writeFile(`photos/latest.${mimeType === 'image/png' ? 'png' : 'jpg'}`, new Uint8Array(bytes));\n * } catch (e) {\n * if ((e as { code?: string }).code === 'cancelled') return; // the user said no\n * throw e;\n * }\n * ```\n * (The extension follows `mimeType` because the HOST chooses the format — do not assume\n * JPEG. `openAppFs()` is the variant that writes to your own app space with no pick.)\n *\n * Two things must BOTH be true, exactly as for any other task:\n * 1. `immediately.run.invokes` lists `capture-photo` (or `capture-audio`);\n * 2. your app holds `task:invoke` **and** `device:camera` (or `device:microphone`)\n * — declare them in `immediately.run.capabilities` so the user can grant them.\n *\n * Rejects with `.code`: `cancelled` (the user dismissed the capture — nothing was\n * recorded), `forbidden` (you lack the capability; `message: 'browser-denied'` means\n * the BROWSER refused immediately.run itself, which your consent cannot fix),\n * `unavailable` (no such device on this machine, or it would not start),\n * `unsupported` (this host cannot capture), `not-declared`, `timeout`.\n *\n * *Zero-platform alternative, still worth knowing:* `<input type=\"file\"\n * accept=\"image/*\" capture=\"environment\">` opens the OS camera from inside the\n * sandbox (file choosers are not permission-gated). It needs no capability and no\n * host support; it also gives you no indicator and no host-drawn surface.\n */\nexport const capturePhoto = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-photo', { ...options });\n\n/** Record one audio clip through the host's capture UI. See {@link capturePhoto} —\n * every rule there applies verbatim, with `device:microphone` and `capture-audio`. */\nexport const captureAudio = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-audio', { ...options });\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\nlet inputListenerRegistered = false;\n\n// Register the `task-input` listener IF a host transport is reachable; otherwise do\n// nothing (and let the next call retry — the same pattern as pushChannel's `start`).\n// Split out so both the module-eval attempt below and the first-use call sites share\n// one idempotent path.\nconst ensureInputListener = (): void => {\n if (inputListenerRegistered) return;\n try {\n addListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n latestInput = { task: m.task, params: m.params ?? {} };\n inputListeners.forEach((l) => l(latestInput!));\n });\n } catch {\n return; // off-host: the transport resolver threw — no host to listen on\n }\n inputListenerRegistered = true;\n};\n\n// The host delivers a `task-input` message to the callee's iframe right after it\n// mounts the overlay (the §5.7 \"params via the region's mount event\"). That wire\n// message is a plain one-shot host→app message with NO replay/poll counterpart —\n// the contract (`@immediately-run/sandbox-protocol/sdk`) marks replayable state as\n// \"push … polled with request-*\" (mounts, theme, auth-state, …) and `task-input`\n// is not one of them — so a listener registered only on first use could miss an\n// input delivered between module evaluation and the app's first render. Hence:\n// register EAGERLY when a host transport is already present at module eval\n// (on-host, byte-for-byte the pre-R3-421 behaviour), and lazily-on-first-use\n// otherwise, so importing this module off-host (plain `vite dev`) never throws.\nensureInputListener();\n\n/** The task params this app was invoked with, or null if it isn't a task callee.\n * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke\n * this app as a callee. */\nexport const getTaskInput = (): TaskInput | null => {\n ensureInputListener();\n return latestInput;\n};\n\n/**\n * Is a host transport reachable from this realm at all?\n *\n * The R3-421 off-host no-op below must mean EXACTLY \"there is nobody to answer\" —\n * plain `vite dev`, node, jsdom. A blanket try/catch around the send meant it also\n * swallowed a genuine failure against a REAL host (`DataCloneError` because the\n * result holds a DOM node, a function or a live class instance, being the usual\n * one): the host was then never told the task finished, and the caller's\n * `invokeTask` hung to its deadline with no diagnostic anywhere. Absence is\n * therefore decided BEFORE the send, and the send itself is left to throw.\n */\nconst hostReachable = (): boolean => {\n try {\n transport();\n return true;\n } catch {\n return false; // no injected bundler bus and no §4 discovery global — off-host\n }\n};\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n *\n * `result` must be STRUCTURED-CLONEABLE — it crosses a frame boundary. A DOM node, a\n * function, a class instance with methods, a `MediaStreamTrack`: all `DataCloneError`.\n * **That throws**, deliberately and loudly: the alternative is a caller left hanging to\n * its `invokeTask` deadline while this app believes it answered.\n *\n * Off-host (plain `vite dev` — no host transport) this is a no-op: there is no caller\n * to answer. That case, and only that case, is silent.\n */\nexport const completeTask = (result: unknown): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n // On-host, a failure here is REAL and the caller is waiting on this exact message.\n sendMessage(TASK_COMPLETE, { result });\n};\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`.\n * Off-host (plain `vite dev` — no host transport) this is a no-op; on-host a failed\n * send throws rather than leaving the caller waiting, exactly as {@link completeTask}. */\nexport const cancelTask = (): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n sendMessage(TASK_CANCEL, {});\n};\n\n/** React hook: the task input for this callee, re-rendering when it arrives.\n * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee\n * state rather than waiting on it. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete(l);\n };\n }, []);\n return input;\n};\n"],"mappings":";AAqBA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,iBAAiB;AAC1B,SAAS,eAAe,aAAa,eAAe,kBAAkB;AACtE,SAAS,eAAe;AAmBjB,MAAM,UAAU,CAAC,KAA2C,UAA0C;AAAA,EAC3G,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAoBO,MAAM,SAAS,CAAC,KAA2C,UAAyC;AAAA,EACzG,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAiDO,MAAM,aAAa,OAAoB,MAAc,SAAk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,CAAC,OAAO,QAAQ,IAAI,SAA2B,YAAY;AACjE,YAAU,MAAM;AACd,UAAM,IAAI,CAAC,MAAiB,SAAS,CAAC;AACtC,mBAAe,IAAI,CAAC;AACpB,QAAI,YAAa,UAAS,WAAW;AACrC,WAAO,MAAM;AACX,qBAAe,OAAO,CAAC;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/tasks.ts"],"sourcesContent":["// Task invocation — apps invoking apps (UI_AS_APPS_SPEC §5.7). The\n// `startActivityForResult` pattern: one app invokes another by TASK CONTRACT\n// (never by app name — the user's override picks the bound app), passes typed\n// params, and awaits a typed result. The callee runs in a host-owned overlay\n// under ITS OWN grants — data crosses, your authority does not (§5.7).\n//\n// Two roles:\n// - CALLER: `invokeTask(task, params)` (Recipe B — a deferred reply the host\n// holds open until the callee finishes). Delegate a file with `capFile(...)`:\n// the host resolves it against YOUR grants and mints an attenuated chroot.\n// - CALLEE: read `useTaskInput()`, then `completeTask(result)` / `cancelTask()`.\n//\n// OFF-HOST (plain `vite dev`, node/jsdom tests — no sandbox, no host transport):\n// importing this module is always safe (R3-421 — no subpath may throw at import\n// time), and the surface degrades instead of crashing: `getTaskInput()` /\n// `useTaskInput()` stay `null` forever (you are never a task callee without a\n// host), `completeTask` / `cancelTask` are no-ops, and `invokeTask` rejects with\n// a \"no host transport\" error. Under the @immediately-run/dev-fs substrate the\n// transport resolves but no task ever arrives — same observable behaviour.\n// The no-op is scoped to the ABSENCE of a host: when there IS one, a failed send\n// throws instead of leaving the caller to hang out its deadline.\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { transport } from './hostTransport';\nimport { PROTOCOL_TASK, REQUEST_TASK_INPUT, TASK_CANCEL, TASK_COMPLETE, TASK_INPUT } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n// ── caller side ─────────────────────────────────────────────────────────────\n\n/** A delegated FILE capability marker for a task param (§5.7). */\nexport interface FileCap {\n $cap: 'file';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated file reference for a task param. The host resolves it against\n * YOUR OWN grants and mints an attenuated, task-scoped chroot for the callee — you\n * can only delegate a path you already hold (attenuation only, never escalation).\n *\n * file: capFile({ mountId: 'space:abc', relPath: 'photos/cat.jpg' }, { mode: 'rw' })\n */\nexport const capFile = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): FileCap => ({\n $cap: 'file',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/** A delegated DIRECTORY capability marker for a task param (D2). Like {@link FileCap}\n * but `relPath` names a DIRECTORY: the host chroots the callee AT that directory\n * (the whole subtree). Used for the `pick-file` `roots` — one chroot per root. */\nexport interface DirCap {\n $cap: 'dir';\n mountId: string;\n relPath: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Build a delegated DIRECTORY reference for a task param (the directory analogue of\n * {@link capFile}). The host resolves it against YOUR OWN grants and mints an\n * attenuated, task-scoped chroot of that directory for the callee — you can only\n * delegate a directory you already hold (attenuation only, never escalation):\n *\n * roots: [capDir({ mountId: 'space:abc', relPath: 'boards' }, { mode: 'rw' })]\n */\nexport const capDir = (ref: { mountId: string; relPath: string }, opts: { mode: 'ro' | 'rw' }): DirCap => ({\n $cap: 'dir',\n mountId: ref.mountId,\n relPath: ref.relPath,\n mode: opts.mode,\n});\n\n/**\n * Invoke another app via a task contract and await its typed result (Recipe B).\n * Rejects with a machine `.code` on refusal: `cancelled` (user dismissed the\n * overlay), `timeout` (§5.7.1 liveness), `forbidden` (missing `task:invoke`, or a\n * file delegation you don't hold), `not-declared` (the task is missing from your\n * `immediately.run.invokes`), `no-such-task` (no app is bound to that contract),\n * `task-cycle`/`task-depth-exceeded`/`task-version-mismatch`, or `invalid-params`\n * (result failed the contract schema). **Read `err.message`** — since R3-418 the host\n * says which capability, which declaration or which param was at fault; the code alone\n * does not distinguish them.\n *\n * Two things must BOTH be true before any invoke is admitted, and they are separate:\n * 1. your `package.json` `immediately.run.invokes` lists the task (else `not-declared`);\n * 2. your app holds the `task:invoke` capability — declare it in\n * `immediately.run.capabilities` so the user can grant it (else `forbidden`).\n * Declaring the invoke does not imply the capability.\n *\n * ── `pick-file`: `roots` is required (SPACES_UI_SPEC §4.1) ───────────────────\n * ```ts\n * import { invokeTask, capDir, requestMount } from '@immediately-run/sdk';\n *\n * const mount = await requestMount(); // the user picks a space\n * // `invokeTask` returns `unknown` — name the result type, or the destructuring\n * // below does not compile.\n * const { root, path } = await invokeTask<{ root: number; path: string }>('pick-file', {\n * // `SandboxMount.id` is optional (absent on the primary repo mount) — fall back to\n * // `path`, which is always present and is what the host resolves against.\n * roots: [capDir({ mountId: mount.id ?? mount.path, relPath: 'boards' }, { mode: 'ro' })],\n * });\n * ```\n * - `roots` is a NON-EMPTY `DirCap[]` of directories you **already hold**. The result\n * names its target as `{ root, path }` where `root` INDEXES `params.roots`, so\n * `invokeTask('pick-file', {})` can never produce a valid result and is rejected.\n * There is no rootless \"pick from any of my spaces\" mode by design: enumerating the\n * user's spaces is the host's powerbox (`requestMount()`), and composing the two —\n * as above — is that flow. See SPACES_UI_SPEC R-SPACES-5/R-SPACES-12.\n * - Each `capDir` is attenuated against your own grant. **`{ mode: 'rw' }` over a space\n * the user granted `ro` is refused `forbidden`** — the commonest failure, because the\n * mount *was* granted and the path *is* inside it. Pass the mode you actually hold;\n * `ro` is right for a plain pick.\n * - The `requestMount()` grant is DURABLE and survives a cancelled pick: the user\n * consented to the mount in host chrome, separately from the pick (SPACES_UI_SPEC §4.1).\n * Reuse it for later picks rather than re-requesting.\n *\n * Off-host (plain `vite dev` — no host transport) it rejects with a plain\n * \"no host transport\" error: there is no host to resolve the task binding.\n */\nexport const invokeTask = async <R = unknown>(task: string, params: Record<string, unknown> = {}): Promise<R> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_TASK], 'invoke', [{ task, params }])) as\n | { ok: true; data: R }\n | { ok: false; code?: string; message?: string }\n | undefined;\n if (!res || res.ok !== true) {\n const err = new Error(res?.message ?? `task '${task}' failed`) as Error & { code?: string };\n err.code = res?.code ?? 'unknown';\n throw err;\n }\n return res.data;\n};\n\n// ── the host-provided CAPTURE contracts (R3-425) ────────────────────────────\n\n/** Bytes captured by the host, as `capturePhoto()` / `captureAudio()` return them.\n * `bytes` is a transferable `ArrayBuffer` — write it to a space, decode it, upload\n * it. You never receive a `MediaStream` or a `MediaStreamTrack`, and that is not an\n * omission: a track cannot be transferred into an app frame at all\n * (`DataCloneError`), and the frame's opaque origin cannot open a device itself\n * (`getUserMedia` throws `SecurityError: Invalid security origin`). */\nexport interface CaptureResult {\n bytes: ArrayBuffer;\n /** e.g. `image/jpeg`, `audio/webm`. Chosen by the HOST, not by you. */\n mimeType: string;\n /** How long the device was open, in ms. */\n durationMs: number;\n}\n\n/** Optional hints for a capture. They deliberately name NOTHING — no device id, no\n * camera index — because the host chooses everything about how the capture is\n * performed. That is what lets the grant be a plain on/off instead of a per-call\n * target list the way `net:fetch` needs. */\nexport interface CaptureOptions {\n /** Which way the camera should face, if the device has a choice. A HINT: the host\n * may ignore it. Ignored for audio. */\n facing?: 'user' | 'environment';\n}\n\n/**\n * Take one photo, or record one audio clip, through the HOST's capture UI\n * (`BROWSER_CAPABILITIES_SPEC` §3 grade 1).\n *\n * The host opens the device at its own origin, draws the viewfinder, and hands you\n * the bytes when the user presses Done. **You are never in the loop while the device\n * is live** — that is the point of the design, not a limitation of it:\n *\n * - The capture UI is drawn by the host, so a user can trust it the way they trust\n * the sign-in dialog. Do not build a lookalike; imitating host chrome is spoofing.\n * - While the device is open the host shows a persistent \"camera on\" / \"microphone\n * on\" indicator in its own chrome, for the whole session. You cannot hide it and\n * should not try to.\n * - If the user cancels, this rejects `cancelled` and **nothing was recorded**. There\n * is no partial result — do not write error handling that hopes for one.\n *\n * ```ts\n * import { capturePhoto, requestMount, openFs } from '@immediately-run/sdk';\n *\n * try {\n * const { bytes, mimeType } = await capturePhoto({ facing: 'environment' });\n * const mount = await requestMount(); // the user picks a space to save into\n * const fs = openFs(mount); // writeFile is a METHOD on the MountFs\n * await fs.mkdir('photos', { recursive: true }); // writeFile does not create parents\n * await fs.writeFile(`photos/latest.${mimeType === 'image/png' ? 'png' : 'jpg'}`, new Uint8Array(bytes));\n * } catch (e) {\n * if ((e as { code?: string }).code === 'cancelled') return; // the user said no\n * throw e;\n * }\n * ```\n * (The extension follows `mimeType` because the HOST chooses the format — do not assume\n * JPEG. `openAppFs()` is the variant that writes to your own app space with no pick.)\n *\n * Two things must BOTH be true, exactly as for any other task:\n * 1. `immediately.run.invokes` lists `capture-photo` (or `capture-audio`);\n * 2. your app holds `task:invoke` **and** `device:camera` (or `device:microphone`)\n * — declare them in `immediately.run.capabilities` so the user can grant them.\n *\n * Rejects with `.code`: `cancelled` (the user dismissed the capture — nothing was\n * recorded), `forbidden` (you lack the capability; `message: 'browser-denied'` means\n * the BROWSER refused immediately.run itself, which your consent cannot fix),\n * `unavailable` (no such device on this machine, or it would not start),\n * `unsupported` (this host cannot capture), `not-declared`, `timeout`.\n *\n * *Zero-platform alternative, still worth knowing:* `<input type=\"file\"\n * accept=\"image/*\" capture=\"environment\">` opens the OS camera from inside the\n * sandbox (file choosers are not permission-gated). It needs no capability and no\n * host support; it also gives you no indicator and no host-drawn surface.\n */\nexport const capturePhoto = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-photo', { ...options });\n\n/** Record one audio clip through the host's capture UI. See {@link capturePhoto} —\n * every rule there applies verbatim, with `device:microphone` and `capture-audio`. */\nexport const captureAudio = (options: CaptureOptions = {}): Promise<CaptureResult> =>\n invokeTask<CaptureResult>('capture-audio', { ...options });\n\n// ── callee side ─────────────────────────────────────────────────────────────\n\n/** The params this app was invoked with as a task callee. */\nexport interface TaskInput {\n task: string;\n params: Record<string, unknown>;\n}\n\nlet latestInput: TaskInput | null = null;\nconst inputListeners = new Set<(i: TaskInput) => void>();\nlet inputListenerRegistered = false;\n\n/**\n * Whether two deliveries carry the same input, compared by their JSON image. The host does\n * not check that params are JSON; the hosts' senders build them from strings and plain\n * objects, for which the image is faithful. A value JSON cannot serialise at all (it\n * throws) is treated as a change; a value JSON writes lossily (a `Map`, a `Blob`) is not\n * told apart, so two inputs differing only there compare equal.\n */\nconst sameTaskInput = (a: TaskInput, b: TaskInput): boolean => {\n if (a.task !== b.task) return false;\n try {\n return JSON.stringify(a.params) === JSON.stringify(b.params);\n } catch {\n return false;\n }\n};\n\n// Register the `task-input` listener IF a host transport is reachable; otherwise do\n// nothing (and let the next call retry — the same pattern as pushChannel's `start`).\n// Split out so both the module-eval attempt below and the first-use call sites share\n// one idempotent path.\n//\n// Registration then pulls the input once with `request-task-input`, the way `mounts`\n// pulls with `request-mounts`: the host answers a callee frame with its current\n// `task-input` and answers nothing to any other frame. So the input arrives whenever\n// this listener comes to exist, and a host send that landed before it is not lost.\n//\n// The poll has its own latch, set only once a send returns. The listener registering\n// proves there is a host, so a send that then throws is a real failure, not the off-host\n// case: it is reported once and tried again on the next read, because a poll that never\n// goes out leaves a callee looking exactly like an app that is not one.\nlet inputPolled = false;\nlet inputPollFailureReported = false;\nconst ensureInputListener = (): void => {\n if (!inputListenerRegistered) {\n try {\n addListener(TASK_INPUT, (m: { task: string; params?: Record<string, unknown> }) => {\n const next: TaskInput = { task: m.task, params: m.params ?? {} };\n // The host sends the same input several times (at mount, past each compile, and\n // in answer to the poll). A repeat keeps the object the app already has, so an\n // effect keyed on the input does not run again for a value that did not change.\n if (latestInput && sameTaskInput(latestInput, next)) return;\n latestInput = next;\n inputListeners.forEach((l) => l(next));\n });\n } catch {\n return; // off-host: the transport resolver threw — no host to listen on\n }\n inputListenerRegistered = true;\n }\n if (inputPolled) return;\n try {\n sendMessage(REQUEST_TASK_INPUT);\n inputPolled = true;\n } catch (err) {\n if (!inputPollFailureReported) {\n inputPollFailureReported = true;\n console.warn('[immediately.run] the task-input poll could not be sent; it is retried on the next read.', err);\n }\n }\n};\n\n// Register eagerly when a host transport is already present at module evaluation, and\n// lazily on first use otherwise, so importing this module off-host (plain `vite dev`)\n// never throws. Either way the registration polls, so against a host that answers the\n// poll its timing no longer decides whether the input is seen; against an older host the\n// eager registration is still what catches the send made at mount.\nensureInputListener();\n\n/** The task params this app was invoked with, or null if it isn't a task callee.\n * Off-host (plain `vite dev`) this is always `null` — there is no host to invoke\n * this app as a callee. The object changes only when the task or its params change:\n * the host may deliver the same input more than once, and a repeat returns the same\n * object. */\nexport const getTaskInput = (): TaskInput | null => {\n ensureInputListener();\n return latestInput;\n};\n\n/**\n * Is a host transport reachable from this realm at all?\n *\n * The R3-421 off-host no-op below must mean EXACTLY \"there is nobody to answer\" —\n * plain `vite dev`, node, jsdom. A blanket try/catch around the send meant it also\n * swallowed a genuine failure against a REAL host (`DataCloneError` because the\n * result holds a DOM node, a function or a live class instance, being the usual\n * one): the host was then never told the task finished, and the caller's\n * `invokeTask` hung to its deadline with no diagnostic anywhere. Absence is\n * therefore decided BEFORE the send, and the send itself is left to throw.\n */\nconst hostReachable = (): boolean => {\n try {\n transport();\n return true;\n } catch {\n return false; // no injected bundler bus and no §4 discovery global — off-host\n }\n};\n\n/**\n * Finish the task, returning a result to the caller. The host validates it against\n * the contract's result schema before resolving the caller (`invalid-params` on\n * violation), then tears down this overlay.\n *\n * `result` must be STRUCTURED-CLONEABLE — it crosses a frame boundary. A DOM node, a\n * function, a class instance with methods, a `MediaStreamTrack`: all `DataCloneError`.\n * **That throws**, deliberately and loudly: the alternative is a caller left hanging to\n * its `invokeTask` deadline while this app believes it answered.\n *\n * Off-host (plain `vite dev` — no host transport) this is a no-op: there is no caller\n * to answer. That case, and only that case, is silent.\n */\nexport const completeTask = (result: unknown): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n // On-host, a failure here is REAL and the caller is waiting on this exact message.\n sendMessage(TASK_COMPLETE, { result });\n};\n\n/** Abort the task; the caller's `invokeTask` rejects with `cancelled`.\n * Off-host (plain `vite dev` — no host transport) this is a no-op; on-host a failed\n * send throws rather than leaving the caller waiting, exactly as {@link completeTask}. */\nexport const cancelTask = (): void => {\n if (!hostReachable()) return; // off-host: no caller to answer — documented no-op\n sendMessage(TASK_CANCEL, {});\n};\n\n/** React hook: the task input for this callee, re-rendering when it arrives.\n * Off-host (plain `vite dev`) it stays `null` forever — render the non-callee\n * state rather than waiting on it. A repeated delivery of the same input is not\n * announced: the value's identity changes only when the task or its params do. */\nexport const useTaskInput = (): TaskInput | null => {\n const [input, setInput] = useState<TaskInput | null>(getTaskInput);\n useEffect(() => {\n const l = (i: TaskInput) => setInput(i);\n inputListeners.add(l);\n if (latestInput) setInput(latestInput);\n return () => {\n inputListeners.delete(l);\n };\n }, []);\n return input;\n};\n"],"mappings":";AAqBA,SAAS,WAAW,gBAAgB;AACpC,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,iBAAiB;AAC1B,SAAS,eAAe,oBAAoB,aAAa,eAAe,kBAAkB;AAC1F,SAAS,eAAe;AAmBjB,MAAM,UAAU,CAAC,KAA2C,UAA0C;AAAA,EAC3G,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAoBO,MAAM,SAAS,CAAC,KAA2C,UAAyC;AAAA,EACzG,MAAM;AAAA,EACN,SAAS,IAAI;AAAA,EACb,SAAS,IAAI;AAAA,EACb,MAAM,KAAK;AACb;AAiDO,MAAM,aAAa,OAAoB,MAAc,SAAkC,CAAC,MAAkB;AAC/G,QAAM,MAAO,MAAM,gBAAgB,QAAQ,aAAa,GAAG,UAAU,CAAC,EAAE,MAAM,OAAO,CAAC,CAAC;AAIvF,MAAI,CAAC,OAAO,IAAI,OAAO,MAAM;AAC3B,UAAM,MAAM,IAAI,MAAM,KAAK,WAAW,SAAS,IAAI,UAAU;AAC7D,QAAI,OAAO,KAAK,QAAQ;AACxB,UAAM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N,WAAO;AAAA,EACT;AACF;AAeO,MAAM,eAAe,CAAC,WAA0B;AACrD,MAAI,CAAC,cAAc,EAAG;AAEtB,cAAY,eAAe,EAAE,OAAO,CAAC;AACvC;AAKO,MAAM,aAAa,MAAY;AACpC,MAAI,CAAC,cAAc,EAAG;AACtB,cAAY,aAAa,CAAC,CAAC;AAC7B;AAMO,MAAM,eAAe,MAAwB;AAClD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAA2B,YAAY;AACjE,YAAU,MAAM;AACd,UAAM,IAAI,CAAC,MAAiB,SAAS,CAAC;AACtC,mBAAe,IAAI,CAAC;AACpB,QAAI,YAAa,UAAS,WAAW;AACrC,WAAO,MAAM;AACX,qBAAe,OAAO,CAAC;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AACL,SAAO;AACT;","names":[]}
package/dist/theme.cjs CHANGED
@@ -41,7 +41,8 @@ var import_protocolSchemes = require("./protocolSchemes");
41
41
  const DEFAULT_SELECTION = {
42
42
  theme: "dark",
43
43
  themeKey: "immediately-run-default",
44
- modeId: "dark"
44
+ modeId: "dark",
45
+ modeSelection: "dark"
45
46
  };
46
47
  const channel = (0, import_pushChannel.createPushChannel)({
47
48
  pushType: import_protocol.THEME,
@@ -50,7 +51,12 @@ const channel = (0, import_pushChannel.createPushChannel)({
50
51
  parse: (msg) => {
51
52
  if (msg.theme !== "light" && msg.theme !== "dark") return void 0;
52
53
  if (typeof msg.themeKey !== "string" || typeof msg.modeId !== "string") return void 0;
53
- return { theme: msg.theme, themeKey: msg.themeKey, modeId: msg.modeId };
54
+ return {
55
+ theme: msg.theme,
56
+ themeKey: msg.themeKey,
57
+ modeId: msg.modeId,
58
+ modeSelection: typeof msg.modeSelection === "string" ? msg.modeSelection : msg.modeId
59
+ };
54
60
  }
55
61
  });
56
62
  const getHostTheme = () => channel.get().theme;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme polarity, mirrored from the immediately.run host window into\n * the sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n *\n * `HostTheme` is the RESOLVED POLARITY only. The full selection — which theme is\n * active and which of its modes — is {@link HostThemeSelection}.\n */\nexport type HostTheme = 'light' | 'dark';\n\n/**\n * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity\n * plus the active theme's registry key and resolved mode. Carried on the widened\n * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —\n * an app wants to know what is on screen).\n */\nexport interface HostThemeSelection {\n /** Resolved polarity — the same value the legacy `theme` field carried. */\n theme: HostTheme;\n /** The host-minted registry key of the active theme. */\n themeKey: string;\n /** The resolved active mode id of the active theme. */\n modeId: string;\n}\n\n/**\n * The selection assumed before the host reports. The platform default theme is\n * `immediately-run-default` (dark polarity first-paint, matching the shipped\n * provider default — HOST_THEMING_SPEC §3 build-time correction).\n */\nconst DEFAULT_SELECTION: HostThemeSelection = {\n theme: 'dark',\n themeKey: 'immediately-run-default',\n modeId: 'dark',\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The parse\n// reads ALL THREE fields so the full selection survives the transport; the\n// polarity-only surface derives from it.\nconst channel = createPushChannel<HostThemeSelection>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: DEFAULT_SELECTION,\n parse: (msg) => {\n if (msg.theme !== 'light' && msg.theme !== 'dark') return undefined;\n if (typeof msg.themeKey !== 'string' || typeof msg.modeId !== 'string') return undefined;\n return { theme: msg.theme, themeKey: msg.themeKey, modeId: msg.modeId };\n },\n});\n\n/**\n * Returns the current host theme polarity. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get().theme;\n\n/**\n * Subscribe to host theme polarity changes. The listener is invoked immediately\n * with the current polarity, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange((sel) => listener(sel.theme));\n\n/**\n * React hook returning the current host theme polarity, re-rendering when it\n * changes. The recommended way to implement an app's own `useTheme`: follow the\n * host, allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use().theme;\n\n/**\n * Returns the current full host theme selection — polarity, active theme key, and\n * resolved mode. Use {@link useHostThemeSelection} to react to changes.\n */\nexport const getHostThemeSelection = (): HostThemeSelection => channel.get();\n\n/**\n * Subscribe to full host theme selection changes. The listener is invoked\n * immediately with the current selection, then again on every change. Returns an\n * unsubscribe fn.\n */\nexport const onHostThemeSelectionChange = (listener: (selection: HostThemeSelection) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current full host theme selection. */\nexport const useHostThemeSelection = (): HostThemeSelection => channel.use();\n\n/**\n * One entry of the theme catalogue: a selectable theme and its modes. The\n * catalogue is projected per grant — the baseline `theme:read` projection carries\n * NO source identities (no repo coordinates, no spaceIds), and labels are bounded.\n */\nexport interface ThemeCatalogEntry {\n themeKey: string;\n label: string;\n modes: { id: string; polarity: 'light' | 'dark' }[];\n}\n\n/**\n * The loaded-theme catalogue (HOST_THEMING_SPEC §9.2): every selectable theme, so\n * a theme-aware app can render a picker and match chrome. Pushed on\n * `theme-catalog` / polled with `request-theme-catalog`.\n */\nexport interface ThemeCatalog {\n themes: ThemeCatalogEntry[];\n}\n\nconst DEFAULT_CATALOG: ThemeCatalog = { themes: [] };\n\nconst catalogChannel = createPushChannel<ThemeCatalog>({\n pushType: THEME_CATALOG,\n requestType: REQUEST_THEME_CATALOG,\n initial: DEFAULT_CATALOG,\n parse: (msg) => {\n const themes = msg.themes;\n if (!Array.isArray(themes)) return undefined;\n const out: ThemeCatalogEntry[] = [];\n for (const t of themes as unknown[]) {\n if (!t || typeof t !== 'object') return undefined;\n const entry = t as { themeKey?: unknown; label?: unknown; modes?: unknown };\n if (typeof entry.themeKey !== 'string' || typeof entry.label !== 'string' || !Array.isArray(entry.modes)) {\n return undefined;\n }\n const modes: ThemeCatalogEntry['modes'] = [];\n for (const m of entry.modes) {\n if (!m || typeof m !== 'object') return undefined;\n const mode = m as { id?: unknown; polarity?: unknown };\n if (typeof mode.id !== 'string' || (mode.polarity !== 'light' && mode.polarity !== 'dark')) {\n return undefined;\n }\n modes.push({ id: mode.id, polarity: mode.polarity });\n }\n out.push({ themeKey: entry.themeKey, label: entry.label, modes });\n }\n return { themes: out };\n },\n});\n\n/**\n * Returns the current theme catalogue (themes + their modes). Use\n * {@link useThemeCatalog} to react to changes.\n */\nexport const getThemeCatalog = (): ThemeCatalog => catalogChannel.get();\n\n/**\n * Subscribe to theme catalogue changes. The listener is invoked immediately with\n * the current catalogue, then again on every change. Returns an unsubscribe fn.\n */\nexport const onThemeCatalogChange = (listener: (catalog: ThemeCatalog) => void): (() => void) =>\n catalogChannel.onChange(listener);\n\n/** React hook returning the current theme catalogue. */\nexport const useThemeCatalog = (): ThemeCatalog => catalogChannel.use();\n\n/**\n * A location the open-bundle picker returned — a repo or a space, with a\n * confined in-bundle path (OPEN_BUNDLE_SPEC §2). Carried to the host's\n * `theme:sources` `add-source` verb.\n */\nexport type ThemeBundleLocation =\n | { kind: 'repo'; repo: string; ref?: string; path: string }\n | { kind: 'space'; spaceId: string; path: string };\n\n/**\n * The canonical `theme:set` params (HOST_THEMING_SPEC §9.3). `theme` is the\n * registry key of the theme to select (or the legacy `'light' | 'dark'` polarity —\n * the host disambiguates by the reserved-id rule: legacy iff the value is\n * light/dark AND `mode` is absent). `mode` is one of that theme's modes or\n * `'system'`.\n */\nexport interface SetHostThemeSelectionParams {\n theme: string;\n mode?: string;\n}\n\n/** The one `set` call site, so the wire shape is fingerprint-stable. */\nconst setTheme = async (params: SetHostThemeSelectionParams): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [params])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'setHostTheme failed');\n};\n\n/**\n * Set the host theme selection — the ELEVATED `theme:set` action\n * (HOST_THEMING_SPEC §9.3). `theme` is the registry key of the theme to select,\n * `mode` is one of that theme's modes or `'system'`. The host applies it and\n * re-pushes the new selection to every `theme:read` iframe, so your own\n * {@link useHostThemeSelection} confirms the change (the loop closes with no\n * special case). Only a grant holding `theme:set` (e.g. the theme-toggle system\n * app) may call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims.\n */\nexport const setHostThemeSelection = async (selection: { theme: string; mode: string }): Promise<void> => {\n await setTheme(selection);\n};\n\n/**\n * Set the host UI theme polarity — the LEGACY form of `theme:set` (§9.3). The host\n * applies that polarity to the CURRENT theme (never resets to the default), then\n * re-pushes. Keep this alias for old-SDK callers; new code should prefer\n * {@link setHostThemeSelection}.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n await setTheme({ theme });\n};\n\n/**\n * Add a theme source — the ELEVATED `theme:sources` `add-source` verb\n * (HOST_THEMING_SPEC §9.3). `location` must be a location the host journal saw a\n * RECENT open-bundle invocation OF THIS APP return (the picker-provenance rule —\n * \"the pick is the consent\", machine-checked); anything else is rejected with a\n * readable reason. The host fetches, gates, and registers the theme before\n * returning, so a rejected pick surfaces inline in the switcher. Only a grant\n * holding `theme:sources` (the theme switcher) may call this.\n */\nexport const addThemeSource = async (location: ThemeBundleLocation): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'add-source', [{ location }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'addThemeSource failed');\n};\n\n/**\n * Remove a theme source — the `theme:sources` `remove-source` verb (§9.3). If the\n * removed theme is the current selection, the host falls back to the default theme\n * (keeping the mode selection where it exists). The default theme is never\n * removable. Only a grant holding `theme:sources` may call this.\n */\nexport const removeThemeSource = async (themeKey: string): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'remove-source', [{ themeKey }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'removeThemeSource failed');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAkC;AAClC,0BAAgC;AAChC,6BAA+B;AAC/B,sBAA2F;AAC3F,6BAAwB;AAoCxB,MAAM,oBAAwC;AAAA,EAC5C,OAAO;AAAA,EACP,UAAU;AAAA,EACV,QAAQ;AACV;AAMA,MAAM,cAAU,sCAAsC;AAAA,EACpD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,IAAI,UAAU,WAAW,IAAI,UAAU,OAAQ,QAAO;AAC1D,QAAI,OAAO,IAAI,aAAa,YAAY,OAAO,IAAI,WAAW,SAAU,QAAO;AAC/E,WAAO,EAAE,OAAO,IAAI,OAAO,UAAU,IAAI,UAAU,QAAQ,IAAI,OAAO;AAAA,EACxE;AACF,CAAC;AAMM,MAAM,eAAe,MAAiB,QAAQ,IAAI,EAAE;AAMpD,MAAM,oBAAoB,CAAC,aAChC,QAAQ,SAAS,CAAC,QAAQ,SAAS,IAAI,KAAK,CAAC;AAOxC,MAAM,eAAe,MAAiB,QAAQ,IAAI,EAAE;AAMpD,MAAM,wBAAwB,MAA0B,QAAQ,IAAI;AAOpE,MAAM,6BAA6B,CAAC,aACzC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,wBAA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AO,cAA8D;AACxG,QAAM,SAAS,SAAS;AAC1B;AAQO,MAAM,eAAe,OAAO,UAAoC;AACrE,QAAM,SAAS,EAAE,MAAM,CAAC;AAC1B;AAWO,MAAM,iBAAiB,OAAO,aAAiD;AACpF,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,8BAAc,GAAG,cAAc,CAAC,EAAE,SAAS,CAAC,CAAC;AAIxF,6CAAe,KAAK,uBAAuB;AAC7C;AAQO,MAAM,oBAAoB,OAAO,aAAoC;AAC1E,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,8BAAc,GAAG,iBAAiB,CAAC,EAAE,SAAS,CAAC,CAAC;AAI3F,6CAAe,KAAK,0BAA0B;AAChD;","names":[]}
1
+ {"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme polarity, mirrored from the immediately.run host window into\n * the sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n *\n * `HostTheme` is the RESOLVED POLARITY only. The full selection — which theme is\n * active and which of its modes — is {@link HostThemeSelection}.\n */\nexport type HostTheme = 'light' | 'dark';\n\n/**\n * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity\n * plus the active theme's registry key and resolved mode. Carried on the widened\n * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —\n * an app wants to know what is on screen); `modeSelection` is what was chosen.\n */\nexport interface HostThemeSelection {\n /** Resolved polarity — the same value the legacy `theme` field carried. */\n theme: HostTheme;\n /** The host-minted registry key of the active theme. */\n themeKey: string;\n /** The resolved active mode id of the active theme. */\n modeId: string;\n /**\n * What the user selected on the mode axis (HOST_THEMING_SPEC §2): a mode id of the\n * active theme, or the literal `'system'` when the host follows the OS preference.\n * A theme switcher highlights this; `modeId` stays what is on screen. Against a\n * host that predates the field it equals `modeId`.\n */\n modeSelection: string;\n}\n\n/**\n * The selection assumed before the host reports. The platform default theme is\n * `immediately-run-default` (dark polarity first-paint, matching the shipped\n * provider default — HOST_THEMING_SPEC §3 build-time correction).\n */\nconst DEFAULT_SELECTION: HostThemeSelection = {\n theme: 'dark',\n themeKey: 'immediately-run-default',\n modeId: 'dark',\n modeSelection: 'dark',\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The parse\n// reads every field so the full selection survives the transport; the\n// polarity-only surface derives from it. `modeSelection` is the one tolerant\n// field: a host that predates it still sends a usable polarity, so its absence\n// falls back to the resolved mode instead of dropping the message.\nconst channel = createPushChannel<HostThemeSelection>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: DEFAULT_SELECTION,\n parse: (msg) => {\n if (msg.theme !== 'light' && msg.theme !== 'dark') return undefined;\n if (typeof msg.themeKey !== 'string' || typeof msg.modeId !== 'string') return undefined;\n return {\n theme: msg.theme,\n themeKey: msg.themeKey,\n modeId: msg.modeId,\n modeSelection: typeof msg.modeSelection === 'string' ? msg.modeSelection : msg.modeId,\n };\n },\n});\n\n/**\n * Returns the current host theme polarity. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get().theme;\n\n/**\n * Subscribe to host theme polarity changes. The listener is invoked immediately\n * with the current polarity, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange((sel) => listener(sel.theme));\n\n/**\n * React hook returning the current host theme polarity, re-rendering when it\n * changes. The recommended way to implement an app's own `useTheme`: follow the\n * host, allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use().theme;\n\n/**\n * Returns the current full host theme selection — polarity, active theme key,\n * resolved mode and mode selection. Use {@link useHostThemeSelection} to react to changes.\n */\nexport const getHostThemeSelection = (): HostThemeSelection => channel.get();\n\n/**\n * Subscribe to full host theme selection changes. The listener is invoked\n * immediately with the current selection, then again on every change. Returns an\n * unsubscribe fn.\n */\nexport const onHostThemeSelectionChange = (listener: (selection: HostThemeSelection) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current full host theme selection. */\nexport const useHostThemeSelection = (): HostThemeSelection => channel.use();\n\n/**\n * One entry of the theme catalogue: a selectable theme and its modes. The\n * catalogue is projected per grant — the baseline `theme:read` projection carries\n * NO source identities (no repo coordinates, no spaceIds), and labels are bounded.\n */\nexport interface ThemeCatalogEntry {\n themeKey: string;\n label: string;\n modes: { id: string; polarity: 'light' | 'dark' }[];\n}\n\n/**\n * The loaded-theme catalogue (HOST_THEMING_SPEC §9.2): every selectable theme, so\n * a theme-aware app can render a picker and match chrome. Pushed on\n * `theme-catalog` / polled with `request-theme-catalog`.\n */\nexport interface ThemeCatalog {\n themes: ThemeCatalogEntry[];\n}\n\nconst DEFAULT_CATALOG: ThemeCatalog = { themes: [] };\n\nconst catalogChannel = createPushChannel<ThemeCatalog>({\n pushType: THEME_CATALOG,\n requestType: REQUEST_THEME_CATALOG,\n initial: DEFAULT_CATALOG,\n parse: (msg) => {\n const themes = msg.themes;\n if (!Array.isArray(themes)) return undefined;\n const out: ThemeCatalogEntry[] = [];\n for (const t of themes as unknown[]) {\n if (!t || typeof t !== 'object') return undefined;\n const entry = t as { themeKey?: unknown; label?: unknown; modes?: unknown };\n if (typeof entry.themeKey !== 'string' || typeof entry.label !== 'string' || !Array.isArray(entry.modes)) {\n return undefined;\n }\n const modes: ThemeCatalogEntry['modes'] = [];\n for (const m of entry.modes) {\n if (!m || typeof m !== 'object') return undefined;\n const mode = m as { id?: unknown; polarity?: unknown };\n if (typeof mode.id !== 'string' || (mode.polarity !== 'light' && mode.polarity !== 'dark')) {\n return undefined;\n }\n modes.push({ id: mode.id, polarity: mode.polarity });\n }\n out.push({ themeKey: entry.themeKey, label: entry.label, modes });\n }\n return { themes: out };\n },\n});\n\n/**\n * Returns the current theme catalogue (themes + their modes). Use\n * {@link useThemeCatalog} to react to changes.\n */\nexport const getThemeCatalog = (): ThemeCatalog => catalogChannel.get();\n\n/**\n * Subscribe to theme catalogue changes. The listener is invoked immediately with\n * the current catalogue, then again on every change. Returns an unsubscribe fn.\n */\nexport const onThemeCatalogChange = (listener: (catalog: ThemeCatalog) => void): (() => void) =>\n catalogChannel.onChange(listener);\n\n/** React hook returning the current theme catalogue. */\nexport const useThemeCatalog = (): ThemeCatalog => catalogChannel.use();\n\n/**\n * A location the open-bundle picker returned — a repo or a space, with a\n * confined in-bundle path (OPEN_BUNDLE_SPEC §2). Carried to the host's\n * `theme:sources` `add-source` verb.\n */\nexport type ThemeBundleLocation =\n | { kind: 'repo'; repo: string; ref?: string; path: string }\n | { kind: 'space'; spaceId: string; path: string };\n\n/**\n * The canonical `theme:set` params (HOST_THEMING_SPEC §9.3). `theme` is the\n * registry key of the theme to select (or the legacy `'light' | 'dark'` polarity —\n * the host disambiguates by the reserved-id rule: legacy iff the value is\n * light/dark AND `mode` is absent). `mode` is one of that theme's modes or\n * `'system'`.\n */\nexport interface SetHostThemeSelectionParams {\n theme: string;\n mode?: string;\n}\n\n/** The one `set` call site, so the wire shape is fingerprint-stable. */\nconst setTheme = async (params: SetHostThemeSelectionParams): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [params])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'setHostTheme failed');\n};\n\n/**\n * Set the host theme selection — the ELEVATED `theme:set` action\n * (HOST_THEMING_SPEC §9.3). `theme` is the registry key of the theme to select,\n * `mode` is one of that theme's modes or `'system'`. The host applies it and\n * re-pushes the new selection to every `theme:read` iframe, so your own\n * {@link useHostThemeSelection} confirms the change (the loop closes with no\n * special case). Only a grant holding `theme:set` (e.g. the theme-toggle system\n * app) may call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims.\n */\nexport const setHostThemeSelection = async (selection: { theme: string; mode: string }): Promise<void> => {\n await setTheme(selection);\n};\n\n/**\n * Set the host UI theme polarity — the LEGACY form of `theme:set` (§9.3). The host\n * applies that polarity to the CURRENT theme (never resets to the default), then\n * re-pushes. Keep this alias for old-SDK callers; new code should prefer\n * {@link setHostThemeSelection}.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n await setTheme({ theme });\n};\n\n/**\n * Add a theme source — the ELEVATED `theme:sources` `add-source` verb\n * (HOST_THEMING_SPEC §9.3). `location` must be a location the host journal saw a\n * RECENT open-bundle invocation OF THIS APP return (the picker-provenance rule —\n * \"the pick is the consent\", machine-checked); anything else is rejected with a\n * readable reason. The host fetches, gates, and registers the theme before\n * returning, so a rejected pick surfaces inline in the switcher. Only a grant\n * holding `theme:sources` (the theme switcher) may call this.\n */\nexport const addThemeSource = async (location: ThemeBundleLocation): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'add-source', [{ location }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'addThemeSource failed');\n};\n\n/**\n * Remove a theme source — the `theme:sources` `remove-source` verb (§9.3). If the\n * removed theme is the current selection, the host falls back to the default theme\n * (keeping the mode selection where it exists). The default theme is never\n * removable. Only a grant holding `theme:sources` may call this.\n */\nexport const removeThemeSource = async (themeKey: string): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'remove-source', [{ themeKey }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'removeThemeSource failed');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,oBAAoB,OAAO,aAAoC;AAC1E,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,8BAAc,GAAG,iBAAiB,CAAC,EAAE,SAAS,CAAC,CAAC;AAI3F,6CAAe,KAAK,0BAA0B;AAChD;","names":[]}
package/dist/theme.d.cts CHANGED
@@ -15,7 +15,7 @@ type HostTheme = 'light' | 'dark';
15
15
  * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity
16
16
  * plus the active theme's registry key and resolved mode. Carried on the widened
17
17
  * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —
18
- * an app wants to know what is on screen).
18
+ * an app wants to know what is on screen); `modeSelection` is what was chosen.
19
19
  */
20
20
  interface HostThemeSelection {
21
21
  /** Resolved polarity — the same value the legacy `theme` field carried. */
@@ -24,6 +24,13 @@ interface HostThemeSelection {
24
24
  themeKey: string;
25
25
  /** The resolved active mode id of the active theme. */
26
26
  modeId: string;
27
+ /**
28
+ * What the user selected on the mode axis (HOST_THEMING_SPEC §2): a mode id of the
29
+ * active theme, or the literal `'system'` when the host follows the OS preference.
30
+ * A theme switcher highlights this; `modeId` stays what is on screen. Against a
31
+ * host that predates the field it equals `modeId`.
32
+ */
33
+ modeSelection: string;
27
34
  }
28
35
  /**
29
36
  * Returns the current host theme polarity. Poll this for a one-off read; use
@@ -42,8 +49,8 @@ declare const onHostThemeChange: (listener: (theme: HostTheme) => void) => (() =
42
49
  */
43
50
  declare const useHostTheme: () => HostTheme;
44
51
  /**
45
- * Returns the current full host theme selection — polarity, active theme key, and
46
- * resolved mode. Use {@link useHostThemeSelection} to react to changes.
52
+ * Returns the current full host theme selection — polarity, active theme key,
53
+ * resolved mode and mode selection. Use {@link useHostThemeSelection} to react to changes.
47
54
  */
48
55
  declare const getHostThemeSelection: () => HostThemeSelection;
49
56
  /**
package/dist/theme.d.ts CHANGED
@@ -15,7 +15,7 @@ type HostTheme = 'light' | 'dark';
15
15
  * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity
16
16
  * plus the active theme's registry key and resolved mode. Carried on the widened
17
17
  * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —
18
- * an app wants to know what is on screen).
18
+ * an app wants to know what is on screen); `modeSelection` is what was chosen.
19
19
  */
20
20
  interface HostThemeSelection {
21
21
  /** Resolved polarity — the same value the legacy `theme` field carried. */
@@ -24,6 +24,13 @@ interface HostThemeSelection {
24
24
  themeKey: string;
25
25
  /** The resolved active mode id of the active theme. */
26
26
  modeId: string;
27
+ /**
28
+ * What the user selected on the mode axis (HOST_THEMING_SPEC §2): a mode id of the
29
+ * active theme, or the literal `'system'` when the host follows the OS preference.
30
+ * A theme switcher highlights this; `modeId` stays what is on screen. Against a
31
+ * host that predates the field it equals `modeId`.
32
+ */
33
+ modeSelection: string;
27
34
  }
28
35
  /**
29
36
  * Returns the current host theme polarity. Poll this for a one-off read; use
@@ -42,8 +49,8 @@ declare const onHostThemeChange: (listener: (theme: HostTheme) => void) => (() =
42
49
  */
43
50
  declare const useHostTheme: () => HostTheme;
44
51
  /**
45
- * Returns the current full host theme selection — polarity, active theme key, and
46
- * resolved mode. Use {@link useHostThemeSelection} to react to changes.
52
+ * Returns the current full host theme selection — polarity, active theme key,
53
+ * resolved mode and mode selection. Use {@link useHostThemeSelection} to react to changes.
47
54
  */
48
55
  declare const getHostThemeSelection: () => HostThemeSelection;
49
56
  /**
package/dist/theme.js CHANGED
@@ -7,7 +7,8 @@ import { SCHEMES } from "./protocolSchemes.js";
7
7
  const DEFAULT_SELECTION = {
8
8
  theme: "dark",
9
9
  themeKey: "immediately-run-default",
10
- modeId: "dark"
10
+ modeId: "dark",
11
+ modeSelection: "dark"
11
12
  };
12
13
  const channel = createPushChannel({
13
14
  pushType: THEME,
@@ -16,7 +17,12 @@ const channel = createPushChannel({
16
17
  parse: (msg) => {
17
18
  if (msg.theme !== "light" && msg.theme !== "dark") return void 0;
18
19
  if (typeof msg.themeKey !== "string" || typeof msg.modeId !== "string") return void 0;
19
- return { theme: msg.theme, themeKey: msg.themeKey, modeId: msg.modeId };
20
+ return {
21
+ theme: msg.theme,
22
+ themeKey: msg.themeKey,
23
+ modeId: msg.modeId,
24
+ modeSelection: typeof msg.modeSelection === "string" ? msg.modeSelection : msg.modeId
25
+ };
20
26
  }
21
27
  });
22
28
  const getHostTheme = () => channel.get().theme;
package/dist/theme.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme polarity, mirrored from the immediately.run host window into\n * the sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n *\n * `HostTheme` is the RESOLVED POLARITY only. The full selection — which theme is\n * active and which of its modes — is {@link HostThemeSelection}.\n */\nexport type HostTheme = 'light' | 'dark';\n\n/**\n * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity\n * plus the active theme's registry key and resolved mode. Carried on the widened\n * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —\n * an app wants to know what is on screen).\n */\nexport interface HostThemeSelection {\n /** Resolved polarity — the same value the legacy `theme` field carried. */\n theme: HostTheme;\n /** The host-minted registry key of the active theme. */\n themeKey: string;\n /** The resolved active mode id of the active theme. */\n modeId: string;\n}\n\n/**\n * The selection assumed before the host reports. The platform default theme is\n * `immediately-run-default` (dark polarity first-paint, matching the shipped\n * provider default — HOST_THEMING_SPEC §3 build-time correction).\n */\nconst DEFAULT_SELECTION: HostThemeSelection = {\n theme: 'dark',\n themeKey: 'immediately-run-default',\n modeId: 'dark',\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The parse\n// reads ALL THREE fields so the full selection survives the transport; the\n// polarity-only surface derives from it.\nconst channel = createPushChannel<HostThemeSelection>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: DEFAULT_SELECTION,\n parse: (msg) => {\n if (msg.theme !== 'light' && msg.theme !== 'dark') return undefined;\n if (typeof msg.themeKey !== 'string' || typeof msg.modeId !== 'string') return undefined;\n return { theme: msg.theme, themeKey: msg.themeKey, modeId: msg.modeId };\n },\n});\n\n/**\n * Returns the current host theme polarity. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get().theme;\n\n/**\n * Subscribe to host theme polarity changes. The listener is invoked immediately\n * with the current polarity, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange((sel) => listener(sel.theme));\n\n/**\n * React hook returning the current host theme polarity, re-rendering when it\n * changes. The recommended way to implement an app's own `useTheme`: follow the\n * host, allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use().theme;\n\n/**\n * Returns the current full host theme selection — polarity, active theme key, and\n * resolved mode. Use {@link useHostThemeSelection} to react to changes.\n */\nexport const getHostThemeSelection = (): HostThemeSelection => channel.get();\n\n/**\n * Subscribe to full host theme selection changes. The listener is invoked\n * immediately with the current selection, then again on every change. Returns an\n * unsubscribe fn.\n */\nexport const onHostThemeSelectionChange = (listener: (selection: HostThemeSelection) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current full host theme selection. */\nexport const useHostThemeSelection = (): HostThemeSelection => channel.use();\n\n/**\n * One entry of the theme catalogue: a selectable theme and its modes. The\n * catalogue is projected per grant — the baseline `theme:read` projection carries\n * NO source identities (no repo coordinates, no spaceIds), and labels are bounded.\n */\nexport interface ThemeCatalogEntry {\n themeKey: string;\n label: string;\n modes: { id: string; polarity: 'light' | 'dark' }[];\n}\n\n/**\n * The loaded-theme catalogue (HOST_THEMING_SPEC §9.2): every selectable theme, so\n * a theme-aware app can render a picker and match chrome. Pushed on\n * `theme-catalog` / polled with `request-theme-catalog`.\n */\nexport interface ThemeCatalog {\n themes: ThemeCatalogEntry[];\n}\n\nconst DEFAULT_CATALOG: ThemeCatalog = { themes: [] };\n\nconst catalogChannel = createPushChannel<ThemeCatalog>({\n pushType: THEME_CATALOG,\n requestType: REQUEST_THEME_CATALOG,\n initial: DEFAULT_CATALOG,\n parse: (msg) => {\n const themes = msg.themes;\n if (!Array.isArray(themes)) return undefined;\n const out: ThemeCatalogEntry[] = [];\n for (const t of themes as unknown[]) {\n if (!t || typeof t !== 'object') return undefined;\n const entry = t as { themeKey?: unknown; label?: unknown; modes?: unknown };\n if (typeof entry.themeKey !== 'string' || typeof entry.label !== 'string' || !Array.isArray(entry.modes)) {\n return undefined;\n }\n const modes: ThemeCatalogEntry['modes'] = [];\n for (const m of entry.modes) {\n if (!m || typeof m !== 'object') return undefined;\n const mode = m as { id?: unknown; polarity?: unknown };\n if (typeof mode.id !== 'string' || (mode.polarity !== 'light' && mode.polarity !== 'dark')) {\n return undefined;\n }\n modes.push({ id: mode.id, polarity: mode.polarity });\n }\n out.push({ themeKey: entry.themeKey, label: entry.label, modes });\n }\n return { themes: out };\n },\n});\n\n/**\n * Returns the current theme catalogue (themes + their modes). Use\n * {@link useThemeCatalog} to react to changes.\n */\nexport const getThemeCatalog = (): ThemeCatalog => catalogChannel.get();\n\n/**\n * Subscribe to theme catalogue changes. The listener is invoked immediately with\n * the current catalogue, then again on every change. Returns an unsubscribe fn.\n */\nexport const onThemeCatalogChange = (listener: (catalog: ThemeCatalog) => void): (() => void) =>\n catalogChannel.onChange(listener);\n\n/** React hook returning the current theme catalogue. */\nexport const useThemeCatalog = (): ThemeCatalog => catalogChannel.use();\n\n/**\n * A location the open-bundle picker returned — a repo or a space, with a\n * confined in-bundle path (OPEN_BUNDLE_SPEC §2). Carried to the host's\n * `theme:sources` `add-source` verb.\n */\nexport type ThemeBundleLocation =\n | { kind: 'repo'; repo: string; ref?: string; path: string }\n | { kind: 'space'; spaceId: string; path: string };\n\n/**\n * The canonical `theme:set` params (HOST_THEMING_SPEC §9.3). `theme` is the\n * registry key of the theme to select (or the legacy `'light' | 'dark'` polarity —\n * the host disambiguates by the reserved-id rule: legacy iff the value is\n * light/dark AND `mode` is absent). `mode` is one of that theme's modes or\n * `'system'`.\n */\nexport interface SetHostThemeSelectionParams {\n theme: string;\n mode?: string;\n}\n\n/** The one `set` call site, so the wire shape is fingerprint-stable. */\nconst setTheme = async (params: SetHostThemeSelectionParams): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [params])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'setHostTheme failed');\n};\n\n/**\n * Set the host theme selection — the ELEVATED `theme:set` action\n * (HOST_THEMING_SPEC §9.3). `theme` is the registry key of the theme to select,\n * `mode` is one of that theme's modes or `'system'`. The host applies it and\n * re-pushes the new selection to every `theme:read` iframe, so your own\n * {@link useHostThemeSelection} confirms the change (the loop closes with no\n * special case). Only a grant holding `theme:set` (e.g. the theme-toggle system\n * app) may call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims.\n */\nexport const setHostThemeSelection = async (selection: { theme: string; mode: string }): Promise<void> => {\n await setTheme(selection);\n};\n\n/**\n * Set the host UI theme polarity — the LEGACY form of `theme:set` (§9.3). The host\n * applies that polarity to the CURRENT theme (never resets to the default), then\n * re-pushes. Keep this alias for old-SDK callers; new code should prefer\n * {@link setHostThemeSelection}.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n await setTheme({ theme });\n};\n\n/**\n * Add a theme source — the ELEVATED `theme:sources` `add-source` verb\n * (HOST_THEMING_SPEC §9.3). `location` must be a location the host journal saw a\n * RECENT open-bundle invocation OF THIS APP return (the picker-provenance rule —\n * \"the pick is the consent\", machine-checked); anything else is rejected with a\n * readable reason. The host fetches, gates, and registers the theme before\n * returning, so a rejected pick surfaces inline in the switcher. Only a grant\n * holding `theme:sources` (the theme switcher) may call this.\n */\nexport const addThemeSource = async (location: ThemeBundleLocation): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'add-source', [{ location }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'addThemeSource failed');\n};\n\n/**\n * Remove a theme source — the `theme:sources` `remove-source` verb (§9.3). If the\n * removed theme is the current selection, the host falls back to the default theme\n * (keeping the mode selection where it exists). The default theme is never\n * removable. Only a grant holding `theme:sources` may call this.\n */\nexport const removeThemeSource = async (themeKey: string): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'remove-source', [{ themeKey }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'removeThemeSource failed');\n};\n"],"mappings":";AAAA,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,gBAAgB,eAAe,uBAAuB,OAAO,qBAAqB;AAC3F,SAAS,eAAe;AAoCxB,MAAM,oBAAwC;AAAA,EAC5C,OAAO;AAAA,EACP,UAAU;AAAA,EACV,QAAQ;AACV;AAMA,MAAM,UAAU,kBAAsC;AAAA,EACpD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,IAAI,UAAU,WAAW,IAAI,UAAU,OAAQ,QAAO;AAC1D,QAAI,OAAO,IAAI,aAAa,YAAY,OAAO,IAAI,WAAW,SAAU,QAAO;AAC/E,WAAO,EAAE,OAAO,IAAI,OAAO,UAAU,IAAI,UAAU,QAAQ,IAAI,OAAO;AAAA,EACxE;AACF,CAAC;AAMM,MAAM,eAAe,MAAiB,QAAQ,IAAI,EA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uB,CAAC,aACnC,eAAe,SAAS,QAAQ;AAG3B,MAAM,kBAAkB,MAAoB,eAAe,IAAI;AAwBtE,MAAM,WAAW,OAAO,WAAuD;AAC7E,QAAM,MAAO,MAAM,gBAAgB,QAAQ,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;AAI3E,iBAAe,KAAK,qBAAqB;AAC3C;AAYO,MAAM,wBAAwB,OAAO,cAA8D;AACxG,QAAM,SAAS,SAAS;AAC1B;AAQO,MAAM,eAAe,OAAO,UAAoC;AACrE,QAAM,SAAS,EAAE,MAAM,CAAC;AAC1B;AAWO,MAAM,iBAAiB,OAAO,aAAiD;AACpF,QAAM,MAAO,MAAM,gBAAgB,QAAQ,cAAc,GAAG,cAAc,CAAC,EAAE,SAAS,CAAC,CAAC;AAIxF,iBAAe,KAAK,uBAAuB;AAC7C;AAQO,MAAM,oBAAoB,OAAO,aAAoC;AAC1E,QAAM,MAAO,MAAM,gBAAgB,QAAQ,cAAc,GAAG,iBAAiB,CAAC,EAAE,SAAS,CAAC,CAAC;AAI3F,iBAAe,KAAK,0BAA0B;AAChD;","names":[]}
1
+ {"version":3,"sources":["../src/theme.ts"],"sourcesContent":["import { createPushChannel } from './pushChannel';\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_THEME, REQUEST_THEME, REQUEST_THEME_CATALOG, THEME, THEME_CATALOG } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/**\n * The host UI theme polarity, mirrored from the immediately.run host window into\n * the sandbox. Your app can read this to render in step with the host chrome\n * (light / dark).\n *\n * This is the baseline `theme:read` capability — every app may read it. Changing\n * the host theme is a separate, elevated action (`theme:set`), available only to\n * the theme-toggle system app.\n *\n * `HostTheme` is the RESOLVED POLARITY only. The full selection — which theme is\n * active and which of its modes — is {@link HostThemeSelection}.\n */\nexport type HostTheme = 'light' | 'dark';\n\n/**\n * The full host theme selection (HOST_THEMING_SPEC §2/§9.1): the resolved polarity\n * plus the active theme's registry key and resolved mode. Carried on the widened\n * `theme` push. `modeId` is always the RESOLVED mode (never the literal `system` —\n * an app wants to know what is on screen); `modeSelection` is what was chosen.\n */\nexport interface HostThemeSelection {\n /** Resolved polarity — the same value the legacy `theme` field carried. */\n theme: HostTheme;\n /** The host-minted registry key of the active theme. */\n themeKey: string;\n /** The resolved active mode id of the active theme. */\n modeId: string;\n /**\n * What the user selected on the mode axis (HOST_THEMING_SPEC §2): a mode id of the\n * active theme, or the literal `'system'` when the host follows the OS preference.\n * A theme switcher highlights this; `modeId` stays what is on screen. Against a\n * host that predates the field it equals `modeId`.\n */\n modeSelection: string;\n}\n\n/**\n * The selection assumed before the host reports. The platform default theme is\n * `immediately-run-default` (dark polarity first-paint, matching the shipped\n * provider default — HOST_THEMING_SPEC §3 build-time correction).\n */\nconst DEFAULT_SELECTION: HostThemeSelection = {\n theme: 'dark',\n themeKey: 'immediately-run-default',\n modeId: 'dark',\n modeSelection: 'dark',\n};\n\n// Read over the transport (SDK_PACKAGING_SPEC §4): the host pushes `theme` and\n// answers `request-theme` (wire format: site-main channelBridge.ts). The parse\n// reads every field so the full selection survives the transport; the\n// polarity-only surface derives from it. `modeSelection` is the one tolerant\n// field: a host that predates it still sends a usable polarity, so its absence\n// falls back to the resolved mode instead of dropping the message.\nconst channel = createPushChannel<HostThemeSelection>({\n pushType: THEME,\n requestType: REQUEST_THEME,\n initial: DEFAULT_SELECTION,\n parse: (msg) => {\n if (msg.theme !== 'light' && msg.theme !== 'dark') return undefined;\n if (typeof msg.themeKey !== 'string' || typeof msg.modeId !== 'string') return undefined;\n return {\n theme: msg.theme,\n themeKey: msg.themeKey,\n modeId: msg.modeId,\n modeSelection: typeof msg.modeSelection === 'string' ? msg.modeSelection : msg.modeId,\n };\n },\n});\n\n/**\n * Returns the current host theme polarity. Poll this for a one-off read; use\n * {@link onHostThemeChange} or {@link useHostTheme} to react to changes.\n */\nexport const getHostTheme = (): HostTheme => channel.get().theme;\n\n/**\n * Subscribe to host theme polarity changes. The listener is invoked immediately\n * with the current polarity, then again on every change. Returns an unsubscribe fn.\n */\nexport const onHostThemeChange = (listener: (theme: HostTheme) => void): (() => void) =>\n channel.onChange((sel) => listener(sel.theme));\n\n/**\n * React hook returning the current host theme polarity, re-rendering when it\n * changes. The recommended way to implement an app's own `useTheme`: follow the\n * host, allow a local override.\n */\nexport const useHostTheme = (): HostTheme => channel.use().theme;\n\n/**\n * Returns the current full host theme selection — polarity, active theme key,\n * resolved mode and mode selection. Use {@link useHostThemeSelection} to react to changes.\n */\nexport const getHostThemeSelection = (): HostThemeSelection => channel.get();\n\n/**\n * Subscribe to full host theme selection changes. The listener is invoked\n * immediately with the current selection, then again on every change. Returns an\n * unsubscribe fn.\n */\nexport const onHostThemeSelectionChange = (listener: (selection: HostThemeSelection) => void): (() => void) =>\n channel.onChange(listener);\n\n/** React hook returning the current full host theme selection. */\nexport const useHostThemeSelection = (): HostThemeSelection => channel.use();\n\n/**\n * One entry of the theme catalogue: a selectable theme and its modes. The\n * catalogue is projected per grant — the baseline `theme:read` projection carries\n * NO source identities (no repo coordinates, no spaceIds), and labels are bounded.\n */\nexport interface ThemeCatalogEntry {\n themeKey: string;\n label: string;\n modes: { id: string; polarity: 'light' | 'dark' }[];\n}\n\n/**\n * The loaded-theme catalogue (HOST_THEMING_SPEC §9.2): every selectable theme, so\n * a theme-aware app can render a picker and match chrome. Pushed on\n * `theme-catalog` / polled with `request-theme-catalog`.\n */\nexport interface ThemeCatalog {\n themes: ThemeCatalogEntry[];\n}\n\nconst DEFAULT_CATALOG: ThemeCatalog = { themes: [] };\n\nconst catalogChannel = createPushChannel<ThemeCatalog>({\n pushType: THEME_CATALOG,\n requestType: REQUEST_THEME_CATALOG,\n initial: DEFAULT_CATALOG,\n parse: (msg) => {\n const themes = msg.themes;\n if (!Array.isArray(themes)) return undefined;\n const out: ThemeCatalogEntry[] = [];\n for (const t of themes as unknown[]) {\n if (!t || typeof t !== 'object') return undefined;\n const entry = t as { themeKey?: unknown; label?: unknown; modes?: unknown };\n if (typeof entry.themeKey !== 'string' || typeof entry.label !== 'string' || !Array.isArray(entry.modes)) {\n return undefined;\n }\n const modes: ThemeCatalogEntry['modes'] = [];\n for (const m of entry.modes) {\n if (!m || typeof m !== 'object') return undefined;\n const mode = m as { id?: unknown; polarity?: unknown };\n if (typeof mode.id !== 'string' || (mode.polarity !== 'light' && mode.polarity !== 'dark')) {\n return undefined;\n }\n modes.push({ id: mode.id, polarity: mode.polarity });\n }\n out.push({ themeKey: entry.themeKey, label: entry.label, modes });\n }\n return { themes: out };\n },\n});\n\n/**\n * Returns the current theme catalogue (themes + their modes). Use\n * {@link useThemeCatalog} to react to changes.\n */\nexport const getThemeCatalog = (): ThemeCatalog => catalogChannel.get();\n\n/**\n * Subscribe to theme catalogue changes. The listener is invoked immediately with\n * the current catalogue, then again on every change. Returns an unsubscribe fn.\n */\nexport const onThemeCatalogChange = (listener: (catalog: ThemeCatalog) => void): (() => void) =>\n catalogChannel.onChange(listener);\n\n/** React hook returning the current theme catalogue. */\nexport const useThemeCatalog = (): ThemeCatalog => catalogChannel.use();\n\n/**\n * A location the open-bundle picker returned — a repo or a space, with a\n * confined in-bundle path (OPEN_BUNDLE_SPEC §2). Carried to the host's\n * `theme:sources` `add-source` verb.\n */\nexport type ThemeBundleLocation =\n | { kind: 'repo'; repo: string; ref?: string; path: string }\n | { kind: 'space'; spaceId: string; path: string };\n\n/**\n * The canonical `theme:set` params (HOST_THEMING_SPEC §9.3). `theme` is the\n * registry key of the theme to select (or the legacy `'light' | 'dark'` polarity —\n * the host disambiguates by the reserved-id rule: legacy iff the value is\n * light/dark AND `mode` is absent). `mode` is one of that theme's modes or\n * `'system'`.\n */\nexport interface SetHostThemeSelectionParams {\n theme: string;\n mode?: string;\n}\n\n/** The one `set` call site, so the wire shape is fingerprint-stable. */\nconst setTheme = async (params: SetHostThemeSelectionParams): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'set', [params])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'setHostTheme failed');\n};\n\n/**\n * Set the host theme selection — the ELEVATED `theme:set` action\n * (HOST_THEMING_SPEC §9.3). `theme` is the registry key of the theme to select,\n * `mode` is one of that theme's modes or `'system'`. The host applies it and\n * re-pushes the new selection to every `theme:read` iframe, so your own\n * {@link useHostThemeSelection} confirms the change (the loop closes with no\n * special case). Only a grant holding `theme:set` (e.g. the theme-toggle system\n * app) may call this; any other app is rejected host-side with a `forbidden`\n * {@link Error} (carrying `.code`), regardless of what the app claims.\n */\nexport const setHostThemeSelection = async (selection: { theme: string; mode: string }): Promise<void> => {\n await setTheme(selection);\n};\n\n/**\n * Set the host UI theme polarity — the LEGACY form of `theme:set` (§9.3). The host\n * applies that polarity to the CURRENT theme (never resets to the default), then\n * re-pushes. Keep this alias for old-SDK callers; new code should prefer\n * {@link setHostThemeSelection}.\n */\nexport const setHostTheme = async (theme: HostTheme): Promise<void> => {\n await setTheme({ theme });\n};\n\n/**\n * Add a theme source — the ELEVATED `theme:sources` `add-source` verb\n * (HOST_THEMING_SPEC §9.3). `location` must be a location the host journal saw a\n * RECENT open-bundle invocation OF THIS APP return (the picker-provenance rule —\n * \"the pick is the consent\", machine-checked); anything else is rejected with a\n * readable reason. The host fetches, gates, and registers the theme before\n * returning, so a rejected pick surfaces inline in the switcher. Only a grant\n * holding `theme:sources` (the theme switcher) may call this.\n */\nexport const addThemeSource = async (location: ThemeBundleLocation): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'add-source', [{ location }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'addThemeSource failed');\n};\n\n/**\n * Remove a theme source — the `theme:sources` `remove-source` verb (§9.3). If the\n * removed theme is the current selection, the host falls back to the default theme\n * (keeping the mode selection where it exists). The default theme is never\n * removable. Only a grant holding `theme:sources` may call this.\n */\nexport const removeThemeSource = async (themeKey: string): Promise<void> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_THEME], 'remove-source', [{ themeKey }])) as\n | { ok: true; data?: unknown }\n | { ok: false; code?: string; message?: string }\n | undefined;\n throwOnRefusal(res, 'removeThemeSource failed');\n};\n"],"mappings":";AAAA,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,gBAAgB,eAAe,uBAAuB,OAAO,qBAAqB;AAC3F,SAAS,eAAe;AA2CxB,MAAM,oBAAwC;AAAA,EAC5C,OAAO;AAAA,EACP,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,eAAe;AACjB;AAQA,MAAM,UAAU,kBAAsC;AAAA,EACpD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,IAAI,UAAU,WAAW,IAAI,UAAU,OAAQ,QAAO;AAC1D,QAAI,OAAO,IAAI,aAAa,YAAY,OAAO,IAAI,WAAW,SAAU,QAAO;AAC/E,WAAO;AAAA,MACL,OAAO,IAAI;AAAA,MACX,UAAU,IAAI;AAAA,MACd,QAAQ,IAAI;AAAA,MACZ,eAAe,OAAO,IAAI,kBAAkB,WAAW,IAAI,gBAAgB,IAAI;AAAA,IACjF;AAAA,EACF;AACF,CAAC;AAMM,MAAM,eAAe,MAAiB,QAAQ,IAAI,EAAE;AAMpD,MAAM,oBAAoB,CAAC,aAChC,QAAQ,SAAS,CAAC,QAAQ,SAAS,IAAI,KAAK,CAAC;AAOxC,MAAM,eAAe,MAAiB,QAAQ,IAAI,EAAE;AAMpD,MAAM,wBAAwB,MAA0B,QAAQ,IAAI;AAOpE,MAAM,6BAA6B,CAAC,aACzC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,wBAAwB,MAA0B,QAAQ,IAAI;AAsB3E,MAAM,kBAAgC,EAAE,QAAQ,CAAC,EAAE;AAEnD,MAAM,iBAAiB,kBAAgC;AAAA,EACrD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;AAWO,MAAM,iBAAiB,OAAO,aAAiD;AACpF,QAAM,MAAO,MAAM,gBAAgB,QAAQ,cAAc,GAAG,cAAc,CAAC,EAAE,SAAS,CAAC,CAAC;AAIxF,iBAAe,KAAK,uBAAuB;AAC7C;AAQO,MAAM,oBAAoB,OAAO,aAAoC;AAC1E,QAAM,MAAO,MAAM,gBAAgB,QAAQ,cAAc,GAAG,iBAAiB,CAAC,EAAE,SAAS,CAAC,CAAC;AAI3F,iBAAe,KAAK,0BAA0B;AAChD;","names":[]}
package/dist/version.cjs CHANGED
@@ -21,7 +21,7 @@ __export(version_exports, {
21
21
  SDK_VERSION: () => SDK_VERSION
22
22
  });
23
23
  module.exports = __toCommonJS(version_exports);
24
- const SDK_VERSION = "0.82.0";
24
+ const SDK_VERSION = "0.83.0";
25
25
  // Annotate the CommonJS export names for ESM import in node:
26
26
  0 && (module.exports = {
27
27
  SDK_VERSION
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.82.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,MAAM,cAAc;","names":[]}
1
+ {"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.83.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIO,MAAM,cAAc;","names":[]}
@@ -1,4 +1,4 @@
1
1
  /** This SDK's package version, baked from package.json at build (SP2-6). */
2
- declare const SDK_VERSION = "0.82.0";
2
+ declare const SDK_VERSION = "0.83.0";
3
3
 
4
4
  export { SDK_VERSION };
package/dist/version.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** This SDK's package version, baked from package.json at build (SP2-6). */
2
- declare const SDK_VERSION = "0.82.0";
2
+ declare const SDK_VERSION = "0.83.0";
3
3
 
4
4
  export { SDK_VERSION };
package/dist/version.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "./chunk-VHAA22YE.js";
2
- const SDK_VERSION = "0.82.0";
2
+ const SDK_VERSION = "0.83.0";
3
3
  export {
4
4
  SDK_VERSION
5
5
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.82.0';\n"],"mappings":";AAIO,MAAM,cAAc;","names":[]}
1
+ {"version":3,"sources":["../src/version.ts"],"sourcesContent":["// GENERATED by scripts/gen-version.mjs from package.json — do not edit by hand.\n// Regenerated on every build (prebuild); kept honest by version.test.ts.\n\n/** This SDK's package version, baked from package.json at build (SP2-6). */\nexport const SDK_VERSION = '0.83.0';\n"],"mappings":";AAIO,MAAM,cAAc;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@immediately-run/sdk",
3
- "version": "0.82.0",
3
+ "version": "0.83.0",
4
4
  "description": "Runtime SDK for code executing inside an immediately.run sandbox.",
5
5
  "license": "MIT",
6
6
  "repository": "github:immediately-run/immediately-run-sdk",
@@ -46,7 +46,7 @@
46
46
  "check:clones": "node scripts/check-clones.mjs",
47
47
  "check:unused": "node scripts/check-unused.mjs",
48
48
  "check:untested": "node scripts/check-untested.mjs",
49
- "verify": "npm run check:lock-version && npm run check:pins && npm run check:publish-version && npm run check:published && npm run check:verify-parity && npm run format:check && npm run check:circular && npm run check:clones && npm run check:unused && npm run check:untested && npm run check:bundler:selftest && npm run check:bundler && npm run build && npm run check:published && npm run check:reproducible && npm test && npm run test:safe-content && npm run test:metadata-e2e && npm run test:subpath-imports && npm run test:netfetch-bytes-e2e && npm run api:selftest && npm run api:check && npm run compat:selftest && npm run compat:previous && npm run protocol:check && npm run protocol:selftest && npm run check:ambient:selftest && npm run check:ambient && npm run check:selfhost:selftest && npm run check:selfhost && npm run check:dist-specifiers:selftest && npm run verify:codegen-parity && npm run verify:descriptor-lockstep",
49
+ "verify": "npm run check:lock-version && npm run check:pins && npm run check:publish-version && npm run check:published && npm run check:verify-parity && npm run format:check && npm run check:format-staged && npm run check:circular && npm run check:clones && npm run check:unused && npm run check:untested && npm run check:bundler:selftest && npm run check:bundler && npm run build && npm run check:published && npm run check:reproducible && npm test && npm run test:safe-content && npm run test:metadata-e2e && npm run test:subpath-imports && npm run test:netfetch-bytes-e2e && npm run api:selftest && npm run api:check && npm run compat:selftest && npm run compat:previous && npm run protocol:check && npm run protocol:selftest && npm run check:ambient:selftest && npm run check:ambient && npm run check:selfhost:selftest && npm run check:selfhost && npm run check:dist-specifiers:selftest && npm run verify:codegen-parity && npm run verify:descriptor-lockstep",
50
50
  "docs": "typedoc --json docs/api.json && node scripts/gen-descriptor-docs.mjs && node scripts/gen-llms.mjs",
51
51
  "prepublishOnly": "npm run check:circular && npm run build && npm run api:selftest && npm run api:check",
52
52
  "test:safe-content": "node scripts/build-safecontent-e2e.mjs && node --test test/safeContent.e2e.mjs",
@@ -64,7 +64,8 @@
64
64
  "check:dist-specifiers:selftest": "node scripts/fix-dist-esm-specifiers.mjs --self-test",
65
65
  "check:ambient:selftest": "node scripts/check-ambient-types.mjs --self-test",
66
66
  "check:lock-version": "node scripts/check-lock-version.mjs --self-test && node scripts/check-lock-version.mjs",
67
- "test:netfetch-bytes-e2e": "node --test test/netFetchBytes.e2e.mjs"
67
+ "test:netfetch-bytes-e2e": "node --test test/netFetchBytes.e2e.mjs",
68
+ "check:format-staged": "node scripts/check-format-staged.mjs --self-test"
68
69
  },
69
70
  "peerDependencies": {
70
71
  "react": "^19.0.0",
@@ -74,7 +75,7 @@
74
75
  "@immediately-run/mdx-plugins": "0.7.1",
75
76
  "@immediately-run/platform-constants": "0.2.0",
76
77
  "@immediately-run/safe-content": "0.1.0",
77
- "@immediately-run/sandbox-protocol": "^0.18.0",
78
+ "@immediately-run/sandbox-protocol": "^0.19.0",
78
79
  "react-error-boundary": "^6.0.0"
79
80
  },
80
81
  "devDependencies": {