@immediately-run/sdk 0.90.1 → 0.93.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.
- package/dist/bundleLinkPath.cjs +104 -0
- package/dist/bundleLinkPath.cjs.map +1 -0
- package/dist/bundleLinkPath.d.cts +28 -0
- package/dist/bundleLinkPath.d.ts +28 -0
- package/dist/bundleLinkPath.js +81 -0
- package/dist/bundleLinkPath.js.map +1 -0
- package/dist/followBundleLink.cjs +47 -0
- package/dist/followBundleLink.cjs.map +1 -0
- package/dist/followBundleLink.d.cts +20 -0
- package/dist/followBundleLink.d.ts +20 -0
- package/dist/followBundleLink.js +24 -0
- package/dist/followBundleLink.js.map +1 -0
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/llm.cjs +110 -4
- package/dist/llm.cjs.map +1 -1
- package/dist/llm.d.cts +101 -3
- package/dist/llm.d.ts +101 -3
- package/dist/llm.js +110 -5
- package/dist/llm.js.map +1 -1
- package/dist/mounts.cjs.map +1 -1
- package/dist/mounts.d.cts +38 -9
- package/dist/mounts.d.ts +38 -9
- package/dist/mounts.js.map +1 -1
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +2 -2
package/dist/llm.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
|
-
import { invokeStream } from "./catalog.js";
|
|
2
|
+
import { invoke, invokeStream } from "./catalog.js";
|
|
3
3
|
import { createPushChannel } from "./pushChannel.js";
|
|
4
4
|
import { LLM_PROVIDER, REQUEST_LLM_PROVIDER } from "./generated/protocol.js";
|
|
5
5
|
function chat(req) {
|
|
6
6
|
const { signal, ...params } = req;
|
|
7
7
|
return invokeStream("llm:chat", params, signal);
|
|
8
8
|
}
|
|
9
|
+
function embed(req) {
|
|
10
|
+
return invoke("llm:embed", req);
|
|
11
|
+
}
|
|
9
12
|
const EXECUTORS = ["browser-direct", "backend-proxied"];
|
|
10
13
|
const usableModels = (raw) => {
|
|
11
14
|
if (!raw || typeof raw !== "object") return void 0;
|
|
@@ -13,12 +16,101 @@ const usableModels = (raw) => {
|
|
|
13
16
|
return typeof fast === "string" && fast && typeof smart === "string" && smart ? { fast, smart } : void 0;
|
|
14
17
|
};
|
|
15
18
|
const withReasoningClosed = (f) => ({ ...f, reasoning: f.reasoning === true });
|
|
19
|
+
const positiveInt = (v) => typeof v === "number" && Number.isInteger(v) && v > 0;
|
|
20
|
+
const tokenCount = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
16
21
|
const usableFeatures = (raw) => {
|
|
17
22
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
18
23
|
const f = raw;
|
|
19
|
-
if (typeof f.vision !== "boolean" || typeof f.tools !== "boolean" || typeof f.jsonMode !== "boolean" ||
|
|
24
|
+
if (typeof f.vision !== "boolean" || typeof f.tools !== "boolean" || typeof f.jsonMode !== "boolean" || !tokenCount(f.maxContextTokens))
|
|
20
25
|
return void 0;
|
|
21
|
-
|
|
26
|
+
const { vision, tools, jsonMode, maxContextTokens } = f;
|
|
27
|
+
return withReasoningClosed({ vision, tools, jsonMode, reasoning: f.reasoning, maxContextTokens });
|
|
28
|
+
};
|
|
29
|
+
const MODEL_KINDS = {
|
|
30
|
+
chat: true,
|
|
31
|
+
embedding: true,
|
|
32
|
+
image: true,
|
|
33
|
+
speech: true,
|
|
34
|
+
transcription: true,
|
|
35
|
+
video: true,
|
|
36
|
+
reranking: true
|
|
37
|
+
};
|
|
38
|
+
const usableModelsByKind = (raw) => {
|
|
39
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
40
|
+
const out = {};
|
|
41
|
+
for (const [kind, list] of Object.entries(raw)) {
|
|
42
|
+
if (!Object.prototype.hasOwnProperty.call(MODEL_KINDS, kind) || !Array.isArray(list)) continue;
|
|
43
|
+
const models = [];
|
|
44
|
+
for (const m of list) {
|
|
45
|
+
if (!m || typeof m !== "object" || Array.isArray(m)) continue;
|
|
46
|
+
const { id, name, dimensions, maxInputs } = m;
|
|
47
|
+
if (typeof id !== "string" || !id || typeof name !== "string" || !name) continue;
|
|
48
|
+
models.push({
|
|
49
|
+
id,
|
|
50
|
+
name,
|
|
51
|
+
...positiveInt(dimensions) ? { dimensions } : {},
|
|
52
|
+
...positiveInt(maxInputs) ? { maxInputs } : {}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
if (models.length > 0) out[kind] = models;
|
|
56
|
+
}
|
|
57
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
58
|
+
};
|
|
59
|
+
const nonEmptyString = (v) => typeof v === "string" && v.length > 0;
|
|
60
|
+
const stringList = (v) => Array.isArray(v) && v.every(nonEmptyString) ? [...v] : void 0;
|
|
61
|
+
const nonNegativeNumber = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
|
|
62
|
+
const usableThinking = (raw) => {
|
|
63
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
64
|
+
const { levels: rawLevels, default: rawDefault } = raw;
|
|
65
|
+
const levels = stringList(rawLevels);
|
|
66
|
+
if (!levels || typeof rawDefault !== "string") return void 0;
|
|
67
|
+
if (levels.length > 0 && !levels.includes(rawDefault)) return void 0;
|
|
68
|
+
return { levels, default: rawDefault };
|
|
69
|
+
};
|
|
70
|
+
const usablePricing = (raw) => {
|
|
71
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
72
|
+
const { inputPerMTok, outputPerMTok, unit } = raw;
|
|
73
|
+
return nonNegativeNumber(inputPerMTok) && nonNegativeNumber(outputPerMTok) && nonEmptyString(unit) ? { inputPerMTok, outputPerMTok, unit } : void 0;
|
|
74
|
+
};
|
|
75
|
+
const usableModelInfo = (raw) => {
|
|
76
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
77
|
+
const m = raw;
|
|
78
|
+
const { id, name, contextTokens, outputTokens } = m;
|
|
79
|
+
if (!nonEmptyString(id) || !nonEmptyString(name)) return void 0;
|
|
80
|
+
if (!positiveInt(contextTokens) || !positiveInt(outputTokens)) return void 0;
|
|
81
|
+
const features = usableFeatures(m.features);
|
|
82
|
+
const thinking = usableThinking(m.thinking);
|
|
83
|
+
const inputModalities = stringList(m.inputModalities);
|
|
84
|
+
const outputModalities = stringList(m.outputModalities);
|
|
85
|
+
if (!features || !thinking || !inputModalities || !outputModalities) return void 0;
|
|
86
|
+
const pricing = usablePricing(m.pricing);
|
|
87
|
+
return {
|
|
88
|
+
id,
|
|
89
|
+
name,
|
|
90
|
+
features,
|
|
91
|
+
contextTokens,
|
|
92
|
+
outputTokens,
|
|
93
|
+
inputModalities,
|
|
94
|
+
outputModalities,
|
|
95
|
+
thinking,
|
|
96
|
+
...pricing ? { pricing } : {}
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
const partitionModels = (raw) => {
|
|
100
|
+
const ids = [];
|
|
101
|
+
const infos = [];
|
|
102
|
+
if (!Array.isArray(raw)) return { ids, infos };
|
|
103
|
+
for (const entry of raw) {
|
|
104
|
+
if (nonEmptyString(entry)) {
|
|
105
|
+
ids.push(entry);
|
|
106
|
+
} else if (entry && typeof entry === "object" && !Array.isArray(entry)) {
|
|
107
|
+
const info = usableModelInfo(entry);
|
|
108
|
+
if (info && !infos.some((i) => i.id === info.id)) infos.push(info);
|
|
109
|
+
const id = entry.id;
|
|
110
|
+
if (nonEmptyString(id)) ids.push(id);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return { ids: [...new Set(ids)], infos };
|
|
22
114
|
};
|
|
23
115
|
const usableConnectedProviders = (raw) => {
|
|
24
116
|
if (!Array.isArray(raw)) return void 0;
|
|
@@ -28,9 +120,21 @@ const usableConnectedProviders = (raw) => {
|
|
|
28
120
|
const { providerId, displayName, models } = item;
|
|
29
121
|
if (typeof providerId !== "string" || !providerId) continue;
|
|
30
122
|
if (typeof displayName !== "string" || !displayName) continue;
|
|
31
|
-
const
|
|
123
|
+
const { ids, infos } = partitionModels(models);
|
|
124
|
+
const wireIds = item.modelIds;
|
|
125
|
+
const wireIdList = Array.isArray(wireIds) ? [...new Set(wireIds.filter(nonEmptyString))] : [];
|
|
126
|
+
const modelIds = wireIdList.length > 0 ? wireIdList : ids;
|
|
127
|
+
const described = wireIdList.length > 0 ? infos.filter((i) => wireIdList.includes(i.id)) : infos;
|
|
32
128
|
const features = usableFeatures(item.features);
|
|
33
|
-
|
|
129
|
+
const modelsByKind = usableModelsByKind(item.modelsByKind);
|
|
130
|
+
out.push({
|
|
131
|
+
providerId,
|
|
132
|
+
displayName,
|
|
133
|
+
models: modelIds,
|
|
134
|
+
...described.length > 0 ? { modelInfo: described } : {},
|
|
135
|
+
...features ? { features } : {},
|
|
136
|
+
...modelsByKind ? { modelsByKind } : {}
|
|
137
|
+
});
|
|
34
138
|
}
|
|
35
139
|
return out.length > 0 ? out : void 0;
|
|
36
140
|
};
|
|
@@ -87,6 +191,7 @@ export {
|
|
|
87
191
|
deriveChatProviderState,
|
|
88
192
|
describeChat,
|
|
89
193
|
describeChatState,
|
|
194
|
+
embed,
|
|
90
195
|
normalizeProviderInfo,
|
|
91
196
|
onChatProviderChange,
|
|
92
197
|
onChatProviderStateChange,
|
package/dist/llm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// Provider-agnostic LLM chat — the `llm.chat@1` slot (SERVICE_PROVIDERS_SPEC;\n// LLM_AND_AGENTS_SPEC §8 D5).\n//\n// An app calls ONE chat slot and never worries about which provider the user has a\n// key for: the HOST resolves which vendor answers from the key the user holds\n// (`SecretView.boundOrigin`) plus their `preferredImplementation` choice, normalizes\n// the wire format, injects the key host-side at the §6 net:fetch point (the\n// look-at-nothing proxy), and streams normalized deltas back. The app never names a\n// vendor, never sees the key, and needs NO `net:fetch`/`secrets` grant of its own —\n// only the `llm:chat` capability (elevated, app-scoped: a fork earns it by consent).\n//\n// Inert until the host implements `protocol-llm` (the `chat` stream) + the\n// `llm-provider` describe channel; the contract ships here so apps (the file-explorer\n// summarize fork) can be written against it — exactly how `secrets.ts` shipped ahead\n// of `protocol-secrets`.\nimport { invokeStream } from './catalog';\nimport { createPushChannel } from './pushChannel';\nimport { LLM_PROVIDER, REQUEST_LLM_PROVIDER } from './generated/protocol';\n\n/** Who authored a {@link ChatMessage}. */\nexport type ChatRole = 'system' | 'user' | 'assistant' | 'tool';\n\n/** A part of a message. `image` is only honored when the resolved provider\n * advertises `features.vision` (§2.5); `tool-use`/`tool-result` only when it\n * advertises `features.tools` — branch on {@link describeChat} first. */\nexport type ContentPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; data: string } // data: base64, no data: URL prefix\n // A tool call the model emitted on a prior `assistant` turn — replay it in the\n // conversation so a follow-up request carries the agentic history. Pairs with the\n // streamed `tool-call` {@link ChatDelta} that first surfaced it.\n | { type: 'tool-use'; id: string; name: string; input: Record<string, unknown> }\n // A block of the model's own REASONING from a prior `assistant` turn (R3-335).\n // Honored only when the resolved provider advertises `features.reasoning`.\n //\n // Echo these back. On some providers a reasoning block must be replayed — with its\n // `signature` intact and BEFORE the turn's text/tool-use — for the following turn to\n // be accepted at all; a loop that drops them is quietly lossy across turns in a way\n // that shows up as degraded output rather than an error. Pairs with the streamed\n // `reasoning` {@link ChatDelta}.\n | { type: 'reasoning'; text: string; signature?: string }\n // Reasoning the provider REDACTED: opaque bytes with no readable text, which still\n // have to be echoed back in place to keep the chain valid. Never render it.\n | { type: 'reasoning-redacted'; data: string }\n // The result of executing a `tool-use`, fed back so the model can continue. Carried\n // on a `user`/`tool`-role message; `toolCallId` matches the `tool-use` `id`.\n | { type: 'tool-result'; toolCallId: string; content: string; isError?: boolean };\n\n/** One message in a {@link ChatRequest}: a role plus its content parts. */\nexport interface ChatMessage {\n role: ChatRole;\n content: ContentPart[];\n}\n\n/** A tool the model may call — honored only when `features.tools`. */\nexport interface ToolDef {\n name: string;\n description?: string;\n /** JSON-Schema for the tool's arguments. */\n inputSchema: Record<string, unknown>;\n}\n\n/** A host-brokered chat completion request: the messages plus optional tools,\n * response format, and model hint (each honored per the provider's features). */\nexport interface ChatRequest {\n messages: ChatMessage[];\n /** Honored only when the resolved provider advertises `features.tools`. */\n tools?: ToolDef[];\n /** `'json'` honored only when `features.jsonMode`. Defaults to `'text'`. */\n responseFormat?: 'text' | 'json';\n maxTokens?: number;\n /** An ABSTRACT tier hint, never a vendor model id — the host maps it to a concrete\n * model on the resolved provider. Omit to take the provider's default. */\n modelHint?: 'fast' | 'smart';\n /** A concrete provider-and-model choice, naming one of the user's CONNECTED providers\n * (R3-620, LLM_AND_AGENTS_SPEC §0 editing-session exception). When present it WINS over\n * `modelHint`; the host validates the pair against the user's connected set and refuses\n * with `provider-not-connected` otherwise. Only an editing-session principal may read the\n * chooseable set (via `describeChat()`'s `connectedProviders`, gated `llm:chooseModel`);\n * a stage app still passes at most the abstract hint. */\n model?: { providerId: string; model: string };\n /** Abort the completion mid-stream. When it fires, the SDK sends the host a cancel\n * frame so the host aborts the upstream provider request and STOPS BILLING the\n * user's key — not merely stops the app-side iterator (LLM_AND_AGENTS_SPEC §3.3\n * \"abort the in-flight LLM request\", R3-224). Not sent over the wire (an\n * `AbortSignal` isn't serializable); handled SDK-side. */\n signal?: AbortSignal;\n}\n\n/** One streamed chunk. Consumers typically accumulate `text-delta`s. */\nexport type ChatDelta =\n | { type: 'text-delta'; text: string }\n | { type: 'tool-call'; id: string; name: string; input: unknown }\n // R3-335 — the model's reasoning as it streams. `reasoning-delta` carries the text\n // incrementally (render it live); the terminal `reasoning` carries the WHOLE block\n // plus the `signature` the provider may require on the echo, and is what a caller\n // should put back into the conversation. A provider without reasoning emits neither.\n | { type: 'reasoning-delta'; text: string }\n | { type: 'reasoning'; text: string; signature?: string }\n | { type: 'reasoning-redacted'; data: string }\n // Token accounting for the turn. `cacheReadTokens`/`cacheWriteTokens` are present\n // only on providers that report prompt caching (R3-336) — they are what makes a\n // caching claim verifiable rather than believed, and their ABSENCE is meaningful:\n // it says this provider reports nothing, not that nothing was cached.\n | {\n type: 'usage';\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n /** R3-1124 (LLM_AND_AGENTS §4.2): the round's price. The host's estimate from the\n * catalogue rates unless the provider returned its own cost (OpenRouter's\n * `usage.cost` — then `estimated` is false and that value wins). Absent when no\n * rate and no schedule exists — unknown is absent, never zero. Credits are the\n * plan's own unit, never converted. */\n cost?: { amount: number; unit: 'usd' | 'credits'; estimated: boolean; rule?: string };\n };\n\n/** Why generation stopped: natural `end`, `length` cap, a `tool` call, or content `filtered`. */\nexport type ChatStopReason = 'end' | 'length' | 'tool' | 'filtered';\n\n/** The terminal value of the {@link chat} stream. */\nexport interface ChatResult {\n stopReason: ChatStopReason;\n}\n\n/**\n * Stream a chat completion from whichever provider the user has configured.\n *\n * ```ts\n * let summary = '';\n * for await (const d of chat({ messages: [{ role: 'user', content: [{ type: 'text', text }] }] })) {\n * if (d.type === 'text-delta') summary += d.text;\n * }\n * ```\n *\n * Requires the `llm:chat` capability. If no provider is bound, the host first\n * draws the SP-7 connect-me gate itself (R3-456: the app never draws a\n * credential prompt — that is host chrome, SECRETS_SPEC S3):\n * - the user connects a key → the call retries once and streams normally;\n * - the user declines → the generator throws `code: 'cancelled'` (the same code\n * a declined powerbox produces — a working degraded state: catch it and\n * degrade, e.g. skip the AI feature);\n * - an older host without the gate throws `code: 'provider-not-configured'`.\n *\n * `provider-not-configured` also fires when a key EXISTS but was never entered\n * under the routing the provider now takes (R3-583, SECRETS_SPEC §2.1 C6 /\n * §7.1 S4): a key an app added through `requestAddSecret`, or one sealed before\n * the provider's row moved to the proxied path, is refused because its routing\n * disclosure was never shown. The host raises the same connect gate in-call,\n * carrying the re-entry door, so the throw means the user declined it or\n * settled without a usable key; the recovery is the user entering the key again\n * under the disclosure. The app cannot repair this itself — surface the refusal\n * (its message is the re-entry instruction). A decline latches for the app's\n * session (TS-19/21: the dialog must not be farmed), so a retry re-throws\n * without re-opening the gate; the user re-enters the key from Settings or in a\n * fresh session. Do not retry in a loop.\n *\n * A signed-out user throws `code: 'auth-required'`; an un-granted call throws\n * `forbidden`.\n */\nexport function chat(req: ChatRequest): AsyncGenerator<ChatDelta, ChatResult, void> {\n // Peel `signal` out of the request before it becomes wire params — an AbortSignal\n // can't cross the postMessage boundary as data; it drives the SDK-side cancel frame.\n const { signal, ...params } = req;\n return invokeStream<ChatDelta, ChatResult>('llm:chat', params as unknown as Record<string, unknown>, signal);\n}\n\n/** The resolved provider's advertised abilities (SERVICE_PROVIDERS_SPEC §2.5) — read\n * to branch/degrade (offer image upload only when `vision`). */\nexport interface ChatFeatures {\n vision: boolean;\n tools: boolean;\n jsonMode: boolean;\n /** R3-335: the provider emits reasoning blocks. Read it to decide whether to render\n * a thinking surface at all — an empty affordance on a provider that never thinks\n * is worse than none. Normalized to `false` by the channel when a host predating\n * R3-335 omits it, so this is never `undefined` in practice. */\n reasoning: boolean;\n maxContextTokens: number;\n}\n\n/** How the resolved provider's requests physically leave the browser. Read it to\n * DESCRIBE routing where that matters to the person (\"runs in your browser\" vs\n * \"routed through immediately.run\") — never to draw host chrome or a consent prompt,\n * which remain the host's (UI_AS_APPS §8 T15). */\nexport type ChatExecutor = 'browser-direct' | 'backend-proxied';\n\n/** The concrete model each abstract tier resolves to right now. */\nexport interface ChatTierModels {\n fast: string;\n smart: string;\n}\n\n/** One CONNECTED provider the user may choose a model from, for a per-conversation model\n * choice in an editing-session workbench (R3-620, LLM_AND_AGENTS_SPEC §0). Names and ids\n * only — never keys, usage, balance or routing. */\nexport interface ChatProviderChoice {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — matches {@link ChatRequest.model}.providerId. */\n providerId: string;\n /** The provider's human name, for a picker label. */\n displayName: string;\n /** The chooseable model names — the catalogue-recommended set plus the two the user has\n * chosen. A closed list here would re-introduce the ids-rot problem, so `model` is passed\n * through to the adapter exactly as the Settings field is; this list is suggestions. */\n models: string[];\n /** R3-1074: THIS provider's adapter features, so a run on a chosen provider sizes itself\n * by that provider's context window and vision rather than the default provider's (or the\n * conservative nothing). Absent on a host predating the field — keep your conservative\n * answer then. Optional on the wire, so an older host stays valid. */\n features?: ChatFeatures;\n}\n\n/** Info about the provider the host resolved for this app. `null` when no provider\n * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */\nexport interface ChatProviderInfo {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — never a vendor secret or model id. */\n providerId: string;\n /** True for Host-proxied providers (host-vouched, SP-9); false for app-level ones,\n * whose `features` are an untrusted claim. */\n hostVouched: boolean;\n features: ChatFeatures;\n /** The provider's human name, e.g. `OpenRouter` — what to put in front of a person.\n * Absent on a host that predates the field: fall back to your own copy rather than\n * rendering the id, which is a platform identifier and not a name. */\n displayName?: string;\n /** How this provider's requests leave the browser. Absent on a host that predates the\n * field, which is NOT the same as `browser-direct` — say nothing about routing rather\n * than guess at it. */\n executor?: ChatExecutor;\n /**\n * The concrete model each {@link ChatRequest.modelHint} tier resolves to — what a\n * `smart` request would actually run, after the user's own preference.\n *\n * Read-only, and it does not weaken `LLM_AND_AGENTS_SPEC §0`: an app still names no\n * model, and {@link ChatRequest} still carries only the abstract hint. It is here so an\n * app can be HONEST about what answered — a transcript that says which model wrote a\n * reply, a warning that names the model about to be spent on — instead of showing a\n * blank where the platform knows the answer. The user picks the model in host settings;\n * the app reports it.\n *\n * Absent on a host that predates the field. It changes when the user changes their\n * preference, so read it through {@link onChatProviderChange} rather than caching it.\n */\n models?: ChatTierModels;\n /**\n * The user's CONNECTED providers and their chooseable models, for a per-conversation\n * model choice (R3-620). Only present when this frame holds the ELEVATED `llm:chooseModel`\n * capability (an editing-session workbench); the host strips it for everyone else, so a\n * stage app sees `undefined` and can offer only the abstract `modelHint` path.\n *\n * Read-only: names and ids only. No keys, usage, balance or routing. Absent also on a host\n * that predates the field.\n */\n connectedProviders?: ChatProviderChoice[];\n}\n\n/**\n * Whether the host has told us about a provider yet, and if so whether one is bound —\n * and, since R3-688, whether this frame may ask at all.\n *\n * THREE states, because two is the bug (R3-300). `describeChat()` returns `null` both\n * when no provider is configured AND when the channel has not answered — so an app\n * cannot tell \"you need a key\" from \"ask again in a moment\", and consuming apps\n * rendered a misleading \"connect a key\" banner at users who had one. `unknown` is the\n * state before the host answers; it is not an error and not a prompt to act.\n *\n * **`unknown` is TRANSIENT — the host answers every frame** (R3-419;\n * `LLM_AND_AGENTS_SPEC §4.1` R-LLM-1..3). An app that does not hold `llm:chat` is not\n * met with silence. So it is correct to treat a `unknown` that persists as a host bug\n * rather than as a state to design around, and WRONG to render a spinner with no\n * timeout on it. (Before R3-419 the host withheld the channel entirely from an\n * ungranted frame, and `unknown` stood forever — that is the failure this note exists\n * to keep from being re-created on the app side.)\n *\n * The FOURTH state, `ungranted` (R3-688; `LLM_AND_AGENTS_SPEC §4.1` R-LLM-2 as\n * annotated, `GROVE_AGENT_SPEC` G-GA-10): the host answered, and the reason this frame\n * cannot reach a model is that **it does not hold `llm:chat`** — not that the user has\n * no key. R3-419 deliberately answered an ungranted frame with the same payload as a\n * keyless one, because the SDK could not carry the difference; that made the distinct\n * \"not granted\" cause the reach-card contract promises (G-GA-10) uncomputable — an\n * ungranted fork of an app rendered \"connect a key\" at a user who had one. The host now\n * marks the grantless answer with an optional `ungranted: true` on the SAME message\n * (additive — an older SDK never reads the field and degrades to `not-configured`;\n * an older host never sends the field and the app degrades the same way). The mark is\n * HOST-derived from the frame's resolved grant set at push time (the channel view in\n * `channelAcl.ts`), never from anything this frame asserts.\n */\nexport type ChatProviderState =\n | { status: 'unknown' }\n | { status: 'not-configured' }\n | { status: 'ungranted' }\n | { status: 'configured'; provider: ChatProviderInfo };\n\n// The `llm-provider` describe channel (Recipe A): the host pushes the resolved\n// provider info on change and replays it on register-frame, gated by `llm:chat`.\n// A message with no `provider` key is ignored; an explicit `null` means \"no provider\n// bound\", which is now REPRESENTABLE as distinct from \"not yet answered\".\n// The channel's VALUE stays exactly what the wire carries — `ChatProviderInfo | null` —\n// because the protocol snapshot gate reads this type as the channel's shape. The state\n// read lives BESIDE it: `answered` records whether the host has ever spoken on this\n// channel, which is the one bit `null` cannot carry, and `ungrantedMark` (R3-688) reads\n// the host's optional grantless marker off the same message — also beside the value, not\n// inside it. Deriving the state rather than widening the channel keeps the declared wire\n// VALUE unchanged (SDK_PACKAGING_SPEC §9: additive-only; the optional message field\n// follows the `theme`/`form-factor` insets precedent — old readers ignore it, and the\n// sandbox-protocol descriptor's \"read off\" line catches up at its next release).\n/**\n * Reconcile what the host actually sent with what this SDK declares.\n *\n * `features.reasoning` arrived after `ChatFeatures` shipped, so a host predating it\n * omits the key. `undefined` reads as falsy everywhere EXCEPT a `'reasoning' in\n * features` check, which is exactly the kind of difference that produces one wrong\n * branch a year later — so it is normalized here, once, rather than left to every\n * caller. Absent means \"does not reason\": the fail-closed reading.\n *\n * `displayName`, `executor` and `models` arrived later still, and for them absence is a\n * REAL answer an app is told to handle (\"this host does not say\"), so they are left\n * absent rather than filled in. What is dropped is a value that is present but not\n * usable — an `executor` outside the union, a `models` missing a tier — because a\n * half-answer rendered as fact is worse than the honest blank the app already handles.\n *\n * Exported for its own test; not part of the public surface (`index.ts` re-exports\n * this module wholesale, so it is reachable — it is documented as internal rather\n * than hidden behind a lie).\n * @internal\n */\nconst EXECUTORS: readonly ChatExecutor[] = ['browser-direct', 'backend-proxied'];\n\nconst usableModels = (raw: unknown): ChatTierModels | undefined => {\n if (!raw || typeof raw !== 'object') return undefined;\n const { fast, smart } = raw as Partial<ChatTierModels>;\n return typeof fast === 'string' && fast && typeof smart === 'string' && smart ? { fast, smart } : undefined;\n};\n\n/** The one reasoning-fails-closed normalization both features reads share (R3-1074,\n * review round 1's R6 — a second copy is where the next ChatFeatures key drifts). */\nconst withReasoningClosed = (f: Partial<ChatFeatures>): ChatFeatures =>\n ({ ...f, reasoning: f.reasoning === true } as ChatFeatures);\n\n/** A choice's features cross only COMPLETE (R3-1074): a present half-answer — a\n * non-object, an array, or an object missing a required key — is dropped, exactly\n * like a half-answered `models` pair. Absent stays absent (an older host); present\n * but unusable never renders as fact. */\nconst usableFeatures = (raw: unknown): ChatFeatures | undefined => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const f = raw as Partial<ChatFeatures>;\n if (\n typeof f.vision !== 'boolean' ||\n typeof f.tools !== 'boolean' ||\n typeof f.jsonMode !== 'boolean' ||\n typeof f.maxContextTokens !== 'number'\n )\n return undefined;\n return withReasoningClosed(f);\n};\n\n/** Validate the wire's `connectedProviders` list, keeping only usable entries. The gating\n * (whether the list arrives at all) is the host's — `normalizeProviderInfo` merely refuses\n * to pass through a malformed list, exactly as it refuses a half-answered `models` pair. */\nconst usableConnectedProviders = (raw: unknown): ChatProviderChoice[] | undefined => {\n if (!Array.isArray(raw)) return undefined;\n const out: ChatProviderChoice[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const { providerId, displayName, models } = item as Partial<ChatProviderChoice>;\n if (typeof providerId !== 'string' || !providerId) continue;\n if (typeof displayName !== 'string' || !displayName) continue;\n const cleanModels = Array.isArray(models) ? models.filter((m): m is string => typeof m === 'string' && !!m) : [];\n const features = usableFeatures((item as Partial<ChatProviderChoice>).features);\n out.push({ providerId, displayName, models: cleanModels, ...(features ? { features } : {}) });\n }\n return out.length > 0 ? out : undefined;\n};\n\nexport function normalizeProviderInfo(provider: ChatProviderInfo | null): ChatProviderInfo | null {\n if (!provider) return null;\n // The LATER fields (displayName/executor/models/connectedProviders) are taken OFF the value\n // and put back only if usable — spreading and then overwriting would leave an unusable key\n // present, and `key in provider` is exactly how an app is told to ask whether the host said\n // anything.\n const {\n displayName: rawName,\n executor: rawExecutor,\n models: rawModels,\n connectedProviders: rawConnected,\n ...rest\n } = provider;\n // The wire value is whatever the host sent, which may predate any of these fields — so\n // read it as partial rather than trusting the declared type, and decide each explicitly.\n const wire = provider.features as Partial<ChatFeatures>;\n const executor = EXECUTORS.includes(rawExecutor as ChatExecutor) ? (rawExecutor as ChatExecutor) : undefined;\n const displayName = typeof rawName === 'string' && rawName ? rawName : undefined;\n const models = usableModels(rawModels);\n const connectedProviders = usableConnectedProviders(rawConnected);\n return {\n ...rest,\n features: withReasoningClosed(wire),\n ...(displayName ? { displayName } : {}),\n ...(executor ? { executor } : {}),\n ...(models ? { models } : {}),\n ...(connectedProviders ? { connectedProviders } : {}),\n };\n}\n\nlet answered = false;\n// R3-688 — the host's grantless marker, read off the SAME message (`ungranted: true`\n// beside `provider`). It is message-arrival state beside `answered`, not part of the\n// wire VALUE: the channel's value stays `ChatProviderInfo | null`, so the protocol\n// snapshot gate keeps reading the unchanged shape.\nlet ungrantedMark = false;\nconst channel = createPushChannel<ChatProviderInfo | null>({\n pushType: LLM_PROVIDER,\n requestType: REQUEST_LLM_PROVIDER,\n initial: null,\n parse: (msg) => {\n if (!('provider' in msg)) return undefined;\n answered = true;\n ungrantedMark = msg.ungranted === true;\n return normalizeProviderInfo((msg.provider as ChatProviderInfo | null) ?? null);\n },\n});\n\n/**\n * Derive the four-state read from what the host has said. Pure, and exported for its\n * own test (`llmProviderState.test.ts`) like `normalizeProviderInfo` — not part of the\n * public surface beyond `index.ts`'s wholesale re-export.\n *\n * Order is load-bearing: `unknown` wins until the host answers (an `ungranted` mark\n * cannot exist before an answer — it arrives ON the answer); then the host's grantless\n * mark; then the provider. A host that predates the mark never sets it, so its\n * grantless answer derives `not-configured` — the exact pre-R3-688 contract, which is\n * the additive degradation the fourth state promises.\n *\n * @internal\n */\nexport function deriveChatProviderState(\n answered: boolean,\n ungranted: boolean,\n provider: ChatProviderInfo | null,\n): ChatProviderState {\n if (!answered) return { status: 'unknown' };\n if (ungranted) return { status: 'ungranted' };\n return provider ? { status: 'configured', provider } : { status: 'not-configured' };\n}\n\n/** Derive the state from the wire value plus what the host has said beside it. */\nconst stateOf = (provider: ChatProviderInfo | null): ChatProviderState =>\n deriveChatProviderState(answered, ungrantedMark, provider);\n\n/**\n * The provider the host resolved for this app, or `null`.\n *\n * Kept for compatibility (`ways_of_working §6`, additive-only): it collapses `unknown`\n * and `not-configured` to `null`. Prefer {@link describeChatState} when the difference\n * matters — which is any time you would render \"connect a key\", because doing that in\n * the `unknown` state is exactly the false banner R3-300 fixes.\n */\nexport const describeChat = (): ChatProviderInfo | null => channel.get();\n\n/** The four-state read: `unknown` before the host answers; then the host's `ungranted`\n * mark, or the provider (configured / not-configured). */\nexport const describeChatState = (): ChatProviderState => stateOf(channel.get());\n\n/** Subscribe to provider changes (key added/revoked, preference changed). Invoked\n * immediately with the current value, then on every change. Returns unsubscribe. */\nexport const onChatProviderChange = (listener: (provider: ChatProviderInfo | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/** Subscribe to the provider-state description. */\nexport const onChatProviderStateChange = (listener: (state: ChatProviderState) => void): (() => void) =>\n channel.onChange((p) => listener(stateOf(p)));\n\n/** React hook returning the resolved chat provider (or `null`), re-rendering on\n * change — gate the summarize affordance on `provider !== null`. */\nexport const useChatProvider = (): ChatProviderInfo | null => channel.use();\n\n/**\n * React hook returning the four-state description.\n *\n * Use this to render provider state honestly: show nothing (or a neutral placeholder)\n * while `unknown`, the connect affordance only on `not-configured`, the NOT-GRANTED\n * cause — never the connect copy — on `ungranted`, and the provider's name on\n * `configured`.\n */\nexport const useChatProviderState = (): ChatProviderState => stateOf(channel.use());\n"],"mappings":";AAeA,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,cAAc,4BAA4B;AAgJ5C,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,SAAO,aAAoC,YAAY,QAA8C,MAAM;AAC7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AM,oBAAoB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;AAIxE,MAAM,uBAAuB,CAAC,aACnC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,4BAA4B,CAAC,aACxC,QAAQ,SAAS,CAAC,MAAM,SAAS,QAAQ,CAAC,CAAC,CAAC;AAIvC,MAAM,kBAAkB,MAA+B,QAAQ,IAAI;AAUnE,MAAM,uBAAuB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;","names":["answered"]}
|
|
1
|
+
{"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// Provider-agnostic LLM chat — the `llm.chat@1` slot (SERVICE_PROVIDERS_SPEC;\n// LLM_AND_AGENTS_SPEC §8 D5).\n//\n// An app calls ONE chat slot and never worries about which provider the user has a\n// key for: the HOST resolves which vendor answers from the key the user holds\n// (`SecretView.boundOrigin`) plus their `preferredImplementation` choice, normalizes\n// the wire format, injects the key host-side at the §6 net:fetch point (the\n// look-at-nothing proxy), and streams normalized deltas back. The app never names a\n// vendor, never sees the key, and needs NO `net:fetch`/`secrets` grant of its own —\n// only the `llm:chat` capability (elevated, app-scoped: a fork earns it by consent).\n// `embed()` and the other non-chat kinds need `llm:model` instead (also elevated and\n// app-scoped); a concrete model pair on either needs `llm:chooseModel` on top.\n//\n// Inert until the host implements `protocol-llm` (the `chat` stream) + the\n// `llm-provider` describe channel; the contract ships here so apps (the file-explorer\n// summarize fork) can be written against it — exactly how `secrets.ts` shipped ahead\n// of `protocol-secrets`.\nimport { invoke, invokeStream } from './catalog';\nimport { createPushChannel } from './pushChannel';\nimport { LLM_PROVIDER, REQUEST_LLM_PROVIDER } from './generated/protocol';\nimport type { ModelKind } from '@immediately-run/sandbox-protocol';\n\n/** The model-kind taxonomy (LLM_AND_AGENTS_SPEC §4.4): `chat` plus the non-chat kinds\n * `llm:model` gates. The protocol package owns it; this is that type, re-exported. */\nexport type { ModelKind };\n\n/** Who authored a {@link ChatMessage}. */\nexport type ChatRole = 'system' | 'user' | 'assistant' | 'tool';\n\n/** A part of a message. `image` is only honored when the resolved provider\n * advertises `features.vision` (§2.5); `tool-use`/`tool-result` only when it\n * advertises `features.tools` — branch on {@link describeChat} first. */\nexport type ContentPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; data: string } // data: base64, no data: URL prefix\n // A tool call the model emitted on a prior `assistant` turn — replay it in the\n // conversation so a follow-up request carries the agentic history. Pairs with the\n // streamed `tool-call` {@link ChatDelta} that first surfaced it.\n | { type: 'tool-use'; id: string; name: string; input: Record<string, unknown> }\n // A block of the model's own REASONING from a prior `assistant` turn (R3-335).\n // Honored only when the resolved provider advertises `features.reasoning`.\n //\n // Echo these back. On some providers a reasoning block must be replayed — with its\n // `signature` intact and BEFORE the turn's text/tool-use — for the following turn to\n // be accepted at all; a loop that drops them is quietly lossy across turns in a way\n // that shows up as degraded output rather than an error. Pairs with the streamed\n // `reasoning` {@link ChatDelta}.\n | { type: 'reasoning'; text: string; signature?: string }\n // Reasoning the provider REDACTED: opaque bytes with no readable text, which still\n // have to be echoed back in place to keep the chain valid. Never render it.\n | { type: 'reasoning-redacted'; data: string }\n // The result of executing a `tool-use`, fed back so the model can continue. Carried\n // on a `user`/`tool`-role message; `toolCallId` matches the `tool-use` `id`.\n | { type: 'tool-result'; toolCallId: string; content: string; isError?: boolean };\n\n/** One message in a {@link ChatRequest}: a role plus its content parts. */\nexport interface ChatMessage {\n role: ChatRole;\n content: ContentPart[];\n}\n\n/** A tool the model may call — honored only when `features.tools`. */\nexport interface ToolDef {\n name: string;\n description?: string;\n /** JSON-Schema for the tool's arguments. */\n inputSchema: Record<string, unknown>;\n}\n\n/** A host-brokered chat completion request: the messages plus optional tools,\n * response format, and model hint (each honored per the provider's features). */\nexport interface ChatRequest {\n messages: ChatMessage[];\n /** Honored only when the resolved provider advertises `features.tools`. */\n tools?: ToolDef[];\n /** `'json'` honored only when `features.jsonMode`. Defaults to `'text'`. */\n responseFormat?: 'text' | 'json';\n maxTokens?: number;\n /** An ABSTRACT tier hint, never a vendor model id — the host maps it to a concrete\n * model on the resolved provider. Omit to take the provider's default. */\n modelHint?: 'fast' | 'smart';\n /** A concrete provider-and-model choice, naming one of the user's CONNECTED providers\n * (R3-620, LLM_AND_AGENTS_SPEC §0 editing-session exception). When present it WINS over\n * `modelHint`; the host validates the pair against the user's connected set and refuses\n * with `provider-not-connected` otherwise. Only an editing-session principal may read the\n * chooseable set (via `describeChat()`'s `connectedProviders`, gated `llm:chooseModel`);\n * a stage app still passes at most the abstract hint. */\n model?: { providerId: string; model: string };\n /** A per-request thinking level (R3-1122) — one of the chosen model's\n * `thinking.levels`; the host refuses anything else with `invalid-params`\n * naming the model and its levels. Omit for the Settings level, then the\n * model's default; never sent to a model whose `levels` are empty. */\n thinking?: string;\n /** Abort the completion mid-stream. When it fires, the SDK sends the host a cancel\n * frame so the host aborts the upstream provider request and STOPS BILLING the\n * user's key — not merely stops the app-side iterator (LLM_AND_AGENTS_SPEC §3.3\n * \"abort the in-flight LLM request\", R3-224). Not sent over the wire (an\n * `AbortSignal` isn't serializable); handled SDK-side. */\n signal?: AbortSignal;\n}\n\n/** One streamed chunk. Consumers typically accumulate `text-delta`s. */\nexport type ChatDelta =\n | { type: 'text-delta'; text: string }\n | { type: 'tool-call'; id: string; name: string; input: unknown }\n // R3-335 — the model's reasoning as it streams. `reasoning-delta` carries the text\n // incrementally (render it live); the terminal `reasoning` carries the WHOLE block\n // plus the `signature` the provider may require on the echo, and is what a caller\n // should put back into the conversation. A provider without reasoning emits neither.\n | { type: 'reasoning-delta'; text: string }\n | { type: 'reasoning'; text: string; signature?: string }\n | { type: 'reasoning-redacted'; data: string }\n // Token accounting for the turn. `cacheReadTokens`/`cacheWriteTokens` are present\n // only on providers that report prompt caching (R3-336) — they are what makes a\n // caching claim verifiable rather than believed, and their ABSENCE is meaningful:\n // it says this provider reports nothing, not that nothing was cached.\n | {\n type: 'usage';\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n /** R3-1124 (LLM_AND_AGENTS §4.2): the round's price. The host's estimate from the\n * catalogue rates unless the provider returned its own cost (OpenRouter's\n * `usage.cost` — then `estimated` is false and that value wins). Absent when no\n * rate and no schedule exists — unknown is absent, never zero. Credits are the\n * plan's own unit, never converted. */\n cost?: { amount: number; unit: 'usd' | 'credits'; estimated: boolean; rule?: string };\n };\n\n/** Why generation stopped: natural `end`, `length` cap, a `tool` call, or content `filtered`. */\nexport type ChatStopReason = 'end' | 'length' | 'tool' | 'filtered';\n\n/** The terminal value of the {@link chat} stream. */\nexport interface ChatResult {\n stopReason: ChatStopReason;\n}\n\n/**\n * Stream a chat completion from whichever provider the user has configured.\n *\n * ```ts\n * let summary = '';\n * for await (const d of chat({ messages: [{ role: 'user', content: [{ type: 'text', text }] }] })) {\n * if (d.type === 'text-delta') summary += d.text;\n * }\n * ```\n *\n * Requires the `llm:chat` capability. If no provider is bound, the host first\n * draws the SP-7 connect-me gate itself (R3-456: the app never draws a\n * credential prompt — that is host chrome, SECRETS_SPEC S3):\n * - the user connects a key → the call retries once and streams normally;\n * - the user declines → the generator throws `code: 'cancelled'` (the same code\n * a declined powerbox produces — a working degraded state: catch it and\n * degrade, e.g. skip the AI feature);\n * - an older host without the gate throws `code: 'provider-not-configured'`.\n *\n * `provider-not-configured` also fires when a key EXISTS but was never entered\n * under the routing the provider now takes (R3-583, SECRETS_SPEC §2.1 C6 /\n * §7.1 S4): a key an app added through `requestAddSecret`, or one sealed before\n * the provider's row moved to the proxied path, is refused because its routing\n * disclosure was never shown. The host raises the same connect gate in-call,\n * carrying the re-entry door, so the throw means the user declined it or\n * settled without a usable key; the recovery is the user entering the key again\n * under the disclosure. The app cannot repair this itself — surface the refusal\n * (its message is the re-entry instruction). A decline latches for the app's\n * session (TS-19/21: the dialog must not be farmed), so a retry re-throws\n * without re-opening the gate; the user re-enters the key from Settings or in a\n * fresh session. Do not retry in a loop.\n *\n * A signed-out user throws `code: 'auth-required'`; an un-granted call throws\n * `forbidden`.\n */\nexport function chat(req: ChatRequest): AsyncGenerator<ChatDelta, ChatResult, void> {\n // Peel `signal` out of the request before it becomes wire params — an AbortSignal\n // can't cross the postMessage boundary as data; it drives the SDK-side cancel frame.\n const { signal, ...params } = req;\n return invokeStream<ChatDelta, ChatResult>('llm:chat', params as unknown as Record<string, unknown>, signal);\n}\n\n// ── embed() — the first non-chat kind (LLM_AND_AGENTS_SPEC §4.4, R3-1127) ─────\n\n/** An embeddings request: the texts plus an optional concrete model pair. */\nexport interface EmbedRequest {\n /** The texts to embed — at most 256 values and 1 MiB of text per call (the host\n * refuses larger with `invalid-params`). */\n values: string[];\n /** A concrete model on a connected provider. Requires `llm:chooseModel` ON TOP OF\n * `llm:model` (the same rule as chat's `model`); absent, the host uses the bound\n * provider's first embedding model. */\n model?: { providerId: string; model: string };\n}\n\n/** The embeddings reply: one vector per input value, in order. */\nexport interface EmbedResult {\n embeddings: number[][];\n /** The model that answered (the host's choice when the request named none). */\n model: string;\n usage?: { inputTokens?: number };\n}\n\n/**\n * Embed texts with whichever provider the user has connected — the first non-chat kind\n * on the `llm:model` capability (elevated, app-scoped; earned like `llm:chat`).\n * NOT streamed: one request, one reply. A frame without `llm:model` throws\n * `forbidden`; an over-limit call throws `invalid-params`; no provider with an\n * embedding model throws `unsupported` naming the kind. The same connect-gate and\n * key-routing rules as {@link chat} apply to the resolved provider.\n */\nexport function embed(req: EmbedRequest): Promise<EmbedResult> {\n return invoke<EmbedResult>('llm:embed', req as unknown as Record<string, unknown>);\n}\n\n/** The resolved provider's advertised abilities (SERVICE_PROVIDERS_SPEC §2.5) — read\n * to branch/degrade (offer image upload only when `vision`). */\nexport interface ChatFeatures {\n vision: boolean;\n tools: boolean;\n jsonMode: boolean;\n /** R3-335: the provider emits reasoning blocks. Read it to decide whether to render\n * a thinking surface at all — an empty affordance on a provider that never thinks\n * is worse than none. Normalized to `false` by the channel when a host predating\n * R3-335 omits it, so this is never `undefined` in practice. */\n reasoning: boolean;\n maxContextTokens: number;\n}\n\n/** How the resolved provider's requests physically leave the browser. Read it to\n * DESCRIBE routing where that matters to the person (\"runs in your browser\" vs\n * \"routed through immediately.run\") — never to draw host chrome or a consent prompt,\n * which remain the host's (UI_AS_APPS §8 T15). */\nexport type ChatExecutor = 'browser-direct' | 'backend-proxied';\n\n/** The concrete model each abstract tier resolves to right now. */\nexport interface ChatTierModels {\n fast: string;\n smart: string;\n}\n\n/** One chat model a connected provider offers, described per model (R3-1122): what a\n * picker sizes itself by. The host sends it as an object entry of a choice's wire\n * `models` list. It crosses only complete and rebuilt: an entry missing a required\n * field, or carrying one of the wrong type, is not described at all (its `id` still\n * joins {@link ChatProviderChoice.models}), and a key not declared here never crosses.\n * Names, ids, features and prices only — never keys, usage or balance. */\nexport interface ChatModelInfo {\n /** The model id exactly as {@link ChatRequest.model}.model takes it. */\n id: string;\n /** The model's human name, for a picker label. */\n name: string;\n /** This model's features, normalized like the provider-level set (`reasoning` fails\n * closed to `false`). */\n features: ChatFeatures;\n /** The model's context window in tokens. */\n contextTokens: number;\n /** The model's output limit in tokens. */\n outputTokens: number;\n /** The input modalities the model accepts (e.g. `['text','image']`). */\n inputModalities: string[];\n /** The output modalities the model produces. */\n outputModalities: string[];\n /** The thinking levels the model accepts and the one it uses when a request names\n * none. `default` is always one of `levels`; `levels` is empty for a model with no\n * thinking knob, and then `default` means nothing — send no `thinking` to it. */\n thinking: { levels: string[]; default: string };\n /** A price summary per million tokens in `unit`, when the host knows one. */\n pricing?: { inputPerMTok: number; outputPerMTok: number; unit: string };\n}\n\n/** One CONNECTED provider the user may choose a model from, for a per-conversation model\n * choice in an editing-session workbench (R3-620, LLM_AND_AGENTS_SPEC §0). Names and ids\n * only — never keys, usage, balance or routing. */\nexport interface ChatProviderChoice {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — matches {@link ChatRequest.model}.providerId. */\n providerId: string;\n /** The provider's human name, for a picker label. */\n displayName: string;\n /** The chooseable model ids — the catalogue-recommended set plus the two the user has\n * chosen. A closed list here would re-introduce the ids-rot problem, so `model` is passed\n * through to the adapter exactly as the Settings field is; this list is suggestions.\n * Read from the wire's `modelIds` when a host sends one, else from the wire's `models`:\n * its string entries plus the `id` of each object entry, described or not. Every host\n * so far sends `models` as ids only. */\n models: string[];\n /** R3-1122: per-model descriptions of the models above that the host describes, in the\n * host's order. Absent on a host that sends ids only — today, every host — and when no\n * entry crossed complete; fall back to {@link ChatProviderChoice.features} then. */\n modelInfo?: ChatModelInfo[];\n /** R3-1074: THIS provider's adapter features, so a run on a chosen provider sizes itself\n * by that provider's context window and vision rather than the default provider's (or the\n * conservative nothing). Absent on a host predating the field — keep your conservative\n * answer then. Optional on the wire, so an older host stays valid. */\n features?: ChatFeatures;\n /** R3-1127 (§4.4): the provider's NON-CHAT models by kind (embeddings first). Sent\n * only when your frame holds BOTH `llm:model` and `llm:chooseModel`; absent otherwise\n * and on any older host. Only kinds the host listed a usable model for are present. */\n modelsByKind?: Partial<Record<ModelKind, KindModelInfo[]>>;\n}\n\n/** One non-chat model a connected provider offers (R3-1127): its id (what\n * {@link EmbedRequest.model}.model takes), its human name, and, for an embedding\n * model, its vector size and per-call input limit, when the host knows them. */\nexport interface KindModelInfo {\n id: string;\n name: string;\n dimensions?: number;\n /** The provider's own limit on values per call. The host's cap on an\n * {@link EmbedRequest} (256 values, 1 MiB of text) applies first, so the most one\n * `embed()` call can carry is `min(maxInputs, 256)`. */\n maxInputs?: number;\n}\n\n/** Info about the provider the host resolved for this app. `null` when no provider\n * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */\nexport interface ChatProviderInfo {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — never a vendor secret or model id. */\n providerId: string;\n /** True for Host-proxied providers (host-vouched, SP-9); false for app-level ones,\n * whose `features` are an untrusted claim. */\n hostVouched: boolean;\n features: ChatFeatures;\n /** The provider's human name, e.g. `OpenRouter` — what to put in front of a person.\n * Absent on a host that predates the field: fall back to your own copy rather than\n * rendering the id, which is a platform identifier and not a name. */\n displayName?: string;\n /** How this provider's requests leave the browser. Absent on a host that predates the\n * field, which is NOT the same as `browser-direct` — say nothing about routing rather\n * than guess at it. */\n executor?: ChatExecutor;\n /**\n * The concrete model each {@link ChatRequest.modelHint} tier resolves to — what a\n * `smart` request would actually run, after the user's own preference.\n *\n * Read-only, and it does not weaken `LLM_AND_AGENTS_SPEC §0`: an app still names no\n * model, and {@link ChatRequest} still carries only the abstract hint. It is here so an\n * app can be HONEST about what answered — a transcript that says which model wrote a\n * reply, a warning that names the model about to be spent on — instead of showing a\n * blank where the platform knows the answer. The user picks the model in host settings;\n * the app reports it.\n *\n * Absent on a host that predates the field. It changes when the user changes their\n * preference, so read it through {@link onChatProviderChange} rather than caching it.\n */\n models?: ChatTierModels;\n /**\n * The user's CONNECTED providers and their chooseable models, for a per-conversation\n * model choice (R3-620). Only present when this frame holds the ELEVATED `llm:chooseModel`\n * capability (an editing-session workbench); the host strips it for everyone else, so a\n * stage app sees `undefined` and can offer only the abstract `modelHint` path.\n *\n * Read-only: names and ids only. No keys, usage, balance or routing. Absent also on a host\n * that predates the field.\n */\n connectedProviders?: ChatProviderChoice[];\n}\n\n/**\n * Whether the host has told us about a provider yet, and if so whether one is bound —\n * and, since R3-688, whether this frame may ask at all.\n *\n * THREE states, because two is the bug (R3-300). `describeChat()` returns `null` both\n * when no provider is configured AND when the channel has not answered — so an app\n * cannot tell \"you need a key\" from \"ask again in a moment\", and consuming apps\n * rendered a misleading \"connect a key\" banner at users who had one. `unknown` is the\n * state before the host answers; it is not an error and not a prompt to act.\n *\n * **`unknown` is TRANSIENT — the host answers every frame** (R3-419;\n * `LLM_AND_AGENTS_SPEC §4.1` R-LLM-1..3). An app that does not hold `llm:chat` is not\n * met with silence. So it is correct to treat a `unknown` that persists as a host bug\n * rather than as a state to design around, and WRONG to render a spinner with no\n * timeout on it. (Before R3-419 the host withheld the channel entirely from an\n * ungranted frame, and `unknown` stood forever — that is the failure this note exists\n * to keep from being re-created on the app side.)\n *\n * The FOURTH state, `ungranted` (R3-688; `LLM_AND_AGENTS_SPEC §4.1` R-LLM-2 as\n * annotated, `GROVE_AGENT_SPEC` G-GA-10): the host answered, and the reason this frame\n * cannot reach a model is that **it does not hold `llm:chat`** — not that the user has\n * no key. R3-419 deliberately answered an ungranted frame with the same payload as a\n * keyless one, because the SDK could not carry the difference; that made the distinct\n * \"not granted\" cause the reach-card contract promises (G-GA-10) uncomputable — an\n * ungranted fork of an app rendered \"connect a key\" at a user who had one. The host now\n * marks the grantless answer with an optional `ungranted: true` on the SAME message\n * (additive — an older SDK never reads the field and degrades to `not-configured`;\n * an older host never sends the field and the app degrades the same way). The mark is\n * HOST-derived from the frame's resolved grant set at push time (the channel view in\n * `channelAcl.ts`), never from anything this frame asserts.\n */\nexport type ChatProviderState =\n | { status: 'unknown' }\n | { status: 'not-configured' }\n | { status: 'ungranted' }\n | { status: 'configured'; provider: ChatProviderInfo };\n\n// The `llm-provider` describe channel (Recipe A): the host pushes the resolved\n// provider info on change and replays it on register-frame, gated by `llm:chat`.\n// A message with no `provider` key is ignored; an explicit `null` means \"no provider\n// bound\", which is now REPRESENTABLE as distinct from \"not yet answered\".\n// The channel's VALUE stays exactly what the wire carries — `ChatProviderInfo | null` —\n// because the protocol snapshot gate reads this type as the channel's shape. The state\n// read lives BESIDE it: `answered` records whether the host has ever spoken on this\n// channel, which is the one bit `null` cannot carry, and `ungrantedMark` (R3-688) reads\n// the host's optional grantless marker off the same message — also beside the value, not\n// inside it. Deriving the state rather than widening the channel keeps the declared wire\n// VALUE unchanged (SDK_PACKAGING_SPEC §9: additive-only; the optional message field\n// follows the `theme`/`form-factor` insets precedent — old readers ignore it, and the\n// sandbox-protocol descriptor's \"read off\" line catches up at its next release).\n/**\n * Reconcile what the host actually sent with what this SDK declares.\n *\n * `features.reasoning` arrived after `ChatFeatures` shipped, so a host predating it\n * omits the key. `undefined` reads as falsy everywhere EXCEPT a `'reasoning' in\n * features` check, which is exactly the kind of difference that produces one wrong\n * branch a year later — so it is normalized here, once, rather than left to every\n * caller. Absent means \"does not reason\": the fail-closed reading.\n *\n * `displayName`, `executor` and `models` arrived later still, and for them absence is a\n * REAL answer an app is told to handle (\"this host does not say\"), so they are left\n * absent rather than filled in. What is dropped is a value that is present but not\n * usable — an `executor` outside the union, a `models` missing a tier — because a\n * half-answer rendered as fact is worse than the honest blank the app already handles.\n *\n * Exported for its own test; not part of the public surface (`index.ts` re-exports\n * this module wholesale, so it is reachable — it is documented as internal rather\n * than hidden behind a lie).\n * @internal\n */\nconst EXECUTORS: readonly ChatExecutor[] = ['browser-direct', 'backend-proxied'];\n\nconst usableModels = (raw: unknown): ChatTierModels | undefined => {\n if (!raw || typeof raw !== 'object') return undefined;\n const { fast, smart } = raw as Partial<ChatTierModels>;\n return typeof fast === 'string' && fast && typeof smart === 'string' && smart ? { fast, smart } : undefined;\n};\n\n/** The one reasoning-fails-closed normalization both features reads share (R3-1074,\n * review round 1's R6 — a second copy is where the next ChatFeatures key drifts). */\nconst withReasoningClosed = (f: Partial<ChatFeatures>): ChatFeatures =>\n ({ ...f, reasoning: f.reasoning === true } as ChatFeatures);\n\nconst positiveInt = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v > 0;\n\n/** A token count where 0 is meaningful: the host sends `maxContextTokens: 0` for \"assume\n * no capacity\" (LLM_AND_AGENTS_SPEC §4.1, the dev proxy). NaN, ±Infinity, negatives and\n * fractions are not counts. */\nconst tokenCount = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0;\n\n/** A choice's features cross only COMPLETE (R3-1074): a present half-answer — a\n * non-object, an array, or an object missing a required key — is dropped, exactly\n * like a half-answered `models` pair. Absent stays absent (an older host); present\n * but unusable never renders as fact. */\nconst usableFeatures = (raw: unknown): ChatFeatures | undefined => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const f = raw as Partial<ChatFeatures>;\n if (\n typeof f.vision !== 'boolean' ||\n typeof f.tools !== 'boolean' ||\n typeof f.jsonMode !== 'boolean' ||\n !tokenCount(f.maxContextTokens)\n )\n return undefined;\n // Rebuilt from the declared keys, so nothing else the wire object carries crosses.\n const { vision, tools, jsonMode, maxContextTokens } = f;\n return withReasoningClosed({ vision, tools, jsonMode, reasoning: f.reasoning, maxContextTokens });\n};\n\n/** Every {@link ModelKind}, as a runtime set — typed as a full record so a kind the\n * protocol adds and this list misses is a compile error, not a silently dropped key. */\nconst MODEL_KINDS: Record<ModelKind, true> = {\n chat: true,\n embedding: true,\n image: true,\n speech: true,\n transcription: true,\n video: true,\n reranking: true,\n};\n\n/** A choice's `modelsByKind` crosses rebuilt (R3-1127): only known kinds, only entries\n * with a non-empty `id` and `name`, `dimensions`/`maxInputs` kept only as positive\n * integers, and no other key. A kind left with no usable entry is omitted; a map left\n * with no kind is absent, exactly like a host that never sent it. */\nconst usableModelsByKind = (raw: unknown): ChatProviderChoice['modelsByKind'] => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const out: Partial<Record<ModelKind, KindModelInfo[]>> = {};\n for (const [kind, list] of Object.entries(raw as Record<string, unknown>)) {\n if (!Object.prototype.hasOwnProperty.call(MODEL_KINDS, kind) || !Array.isArray(list)) continue;\n const models: KindModelInfo[] = [];\n for (const m of list) {\n if (!m || typeof m !== 'object' || Array.isArray(m)) continue;\n const { id, name, dimensions, maxInputs } = m as Partial<KindModelInfo>;\n if (typeof id !== 'string' || !id || typeof name !== 'string' || !name) continue;\n models.push({\n id,\n name,\n ...(positiveInt(dimensions) ? { dimensions } : {}),\n ...(positiveInt(maxInputs) ? { maxInputs } : {}),\n });\n }\n if (models.length > 0) out[kind as ModelKind] = models;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst nonEmptyString = (v: unknown): v is string => typeof v === 'string' && v.length > 0;\n\n/** A list of non-empty strings, or undefined when the value is not one (an empty list is one). */\nconst stringList = (v: unknown): string[] | undefined =>\n Array.isArray(v) && v.every(nonEmptyString) ? [...v] : undefined;\n\nconst nonNegativeNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v >= 0;\n\n/** A model's thinking block: every level a non-empty string, and `default` one of them\n * (any string when there are no levels, since it then names nothing). */\nconst usableThinking = (raw: unknown): ChatModelInfo['thinking'] | undefined => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const { levels: rawLevels, default: rawDefault } = raw as Record<string, unknown>;\n const levels = stringList(rawLevels);\n if (!levels || typeof rawDefault !== 'string') return undefined;\n if (levels.length > 0 && !levels.includes(rawDefault)) return undefined;\n return { levels, default: rawDefault };\n};\n\nconst usablePricing = (raw: unknown): ChatModelInfo['pricing'] => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const { inputPerMTok, outputPerMTok, unit } = raw as Record<string, unknown>;\n return nonNegativeNumber(inputPerMTok) && nonNegativeNumber(outputPerMTok) && nonEmptyString(unit)\n ? { inputPerMTok, outputPerMTok, unit }\n : undefined;\n};\n\n/** Rebuild one per-model entry from its declared fields (R3-1122), or undefined when a\n * required one is missing or mistyped. The optional `pricing` is dropped alone when it is\n * unusable. Nothing else on the wire object crosses. */\nconst usableModelInfo = (raw: unknown): ChatModelInfo | undefined => {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const m = raw as Record<string, unknown>;\n const { id, name, contextTokens, outputTokens } = m;\n if (!nonEmptyString(id) || !nonEmptyString(name)) return undefined;\n if (!positiveInt(contextTokens) || !positiveInt(outputTokens)) return undefined;\n const features = usableFeatures(m.features);\n const thinking = usableThinking(m.thinking);\n const inputModalities = stringList(m.inputModalities);\n const outputModalities = stringList(m.outputModalities);\n if (!features || !thinking || !inputModalities || !outputModalities) return undefined;\n const pricing = usablePricing(m.pricing);\n return {\n id,\n name,\n features,\n contextTokens,\n outputTokens,\n inputModalities,\n outputModalities,\n thinking,\n ...(pricing ? { pricing } : {}),\n };\n};\n\n/** Split a choice's wire `models` per entry: a string is an id; an object is run through\n * {@link usableModelInfo}, and its `id`, when it has one, is an id whether or not it was\n * described. One bad entry costs only itself. Ids and descriptions are each deduplicated\n * by id, first wins. */\nconst partitionModels = (raw: unknown): { ids: string[]; infos: ChatModelInfo[] } => {\n const ids: string[] = [];\n const infos: ChatModelInfo[] = [];\n if (!Array.isArray(raw)) return { ids, infos };\n for (const entry of raw) {\n if (nonEmptyString(entry)) {\n ids.push(entry);\n } else if (entry && typeof entry === 'object' && !Array.isArray(entry)) {\n // A second description of an id already described is dropped, first wins — the\n // same rule as the ids, so `modelInfo` never holds two answers for one model.\n const info = usableModelInfo(entry);\n if (info && !infos.some((i) => i.id === info.id)) infos.push(info);\n const id = (entry as Record<string, unknown>).id;\n if (nonEmptyString(id)) ids.push(id);\n }\n }\n return { ids: [...new Set(ids)], infos };\n};\n\n/** Validate the wire's `connectedProviders` list, keeping only usable entries. The gating\n * (whether the list arrives at all) is the host's — `normalizeProviderInfo` merely refuses\n * to pass through a malformed list, exactly as it refuses a half-answered `models` pair. */\nconst usableConnectedProviders = (raw: unknown): ChatProviderChoice[] | undefined => {\n if (!Array.isArray(raw)) return undefined;\n const out: ChatProviderChoice[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const { providerId, displayName, models } = item as Partial<ChatProviderChoice>;\n if (typeof providerId !== 'string' || !providerId) continue;\n if (typeof displayName !== 'string' || !displayName) continue;\n // R3-1122: the ids come from a wire `modelIds` when the host sends a usable one,\n // else from `models` itself; the per-model descriptions only from `models`.\n const { ids, infos } = partitionModels(models);\n const wireIds = (item as { modelIds?: unknown }).modelIds;\n const wireIdList = Array.isArray(wireIds) ? [...new Set(wireIds.filter(nonEmptyString))] : [];\n const modelIds = wireIdList.length > 0 ? wireIdList : ids;\n // `modelInfo` describes models in `models` and nothing else: when a wire `modelIds`\n // wins, a description of an id it does not name is dropped.\n const described = wireIdList.length > 0 ? infos.filter((i) => wireIdList.includes(i.id)) : infos;\n const features = usableFeatures((item as Partial<ChatProviderChoice>).features);\n const modelsByKind = usableModelsByKind((item as Partial<ChatProviderChoice>).modelsByKind);\n out.push({\n providerId,\n displayName,\n models: modelIds,\n ...(described.length > 0 ? { modelInfo: described } : {}),\n ...(features ? { features } : {}),\n ...(modelsByKind ? { modelsByKind } : {}),\n });\n }\n return out.length > 0 ? out : undefined;\n};\n\nexport function normalizeProviderInfo(provider: ChatProviderInfo | null): ChatProviderInfo | null {\n if (!provider) return null;\n // The LATER fields (displayName/executor/models/connectedProviders) are taken OFF the value\n // and put back only if usable — spreading and then overwriting would leave an unusable key\n // present, and `key in provider` is exactly how an app is told to ask whether the host said\n // anything.\n const {\n displayName: rawName,\n executor: rawExecutor,\n models: rawModels,\n connectedProviders: rawConnected,\n ...rest\n } = provider;\n // The wire value is whatever the host sent, which may predate any of these fields — so\n // read it as partial rather than trusting the declared type, and decide each explicitly.\n const wire = provider.features as Partial<ChatFeatures>;\n const executor = EXECUTORS.includes(rawExecutor as ChatExecutor) ? (rawExecutor as ChatExecutor) : undefined;\n const displayName = typeof rawName === 'string' && rawName ? rawName : undefined;\n const models = usableModels(rawModels);\n const connectedProviders = usableConnectedProviders(rawConnected);\n return {\n ...rest,\n features: withReasoningClosed(wire),\n ...(displayName ? { displayName } : {}),\n ...(executor ? { executor } : {}),\n ...(models ? { models } : {}),\n ...(connectedProviders ? { connectedProviders } : {}),\n };\n}\n\nlet answered = false;\n// R3-688 — the host's grantless marker, read off the SAME message (`ungranted: true`\n// beside `provider`). It is message-arrival state beside `answered`, not part of the\n// wire VALUE: the channel's value stays `ChatProviderInfo | null`, so the protocol\n// snapshot gate keeps reading the unchanged shape.\nlet ungrantedMark = false;\nconst channel = createPushChannel<ChatProviderInfo | null>({\n pushType: LLM_PROVIDER,\n requestType: REQUEST_LLM_PROVIDER,\n initial: null,\n parse: (msg) => {\n if (!('provider' in msg)) return undefined;\n answered = true;\n ungrantedMark = msg.ungranted === true;\n return normalizeProviderInfo((msg.provider as ChatProviderInfo | null) ?? null);\n },\n});\n\n/**\n * Derive the four-state read from what the host has said. Pure, and exported for its\n * own test (`llmProviderState.test.ts`) like `normalizeProviderInfo` — not part of the\n * public surface beyond `index.ts`'s wholesale re-export.\n *\n * Order is load-bearing: `unknown` wins until the host answers (an `ungranted` mark\n * cannot exist before an answer — it arrives ON the answer); then the host's grantless\n * mark; then the provider. A host that predates the mark never sets it, so its\n * grantless answer derives `not-configured` — the exact pre-R3-688 contract, which is\n * the additive degradation the fourth state promises.\n *\n * @internal\n */\nexport function deriveChatProviderState(\n answered: boolean,\n ungranted: boolean,\n provider: ChatProviderInfo | null,\n): ChatProviderState {\n if (!answered) return { status: 'unknown' };\n if (ungranted) return { status: 'ungranted' };\n return provider ? { status: 'configured', provider } : { status: 'not-configured' };\n}\n\n/** Derive the state from the wire value plus what the host has said beside it. */\nconst stateOf = (provider: ChatProviderInfo | null): ChatProviderState =>\n deriveChatProviderState(answered, ungrantedMark, provider);\n\n/**\n * The provider the host resolved for this app, or `null`.\n *\n * Kept for compatibility (`ways_of_working §6`, additive-only): it collapses `unknown`\n * and `not-configured` to `null`. Prefer {@link describeChatState} when the difference\n * matters — which is any time you would render \"connect a key\", because doing that in\n * the `unknown` state is exactly the false banner R3-300 fixes.\n */\nexport const describeChat = (): ChatProviderInfo | null => channel.get();\n\n/** The four-state read: `unknown` before the host answers; then the host's `ungranted`\n * mark, or the provider (configured / not-configured). */\nexport const describeChatState = (): ChatProviderState => stateOf(channel.get());\n\n/** Subscribe to provider changes (key added/revoked, preference changed). Invoked\n * immediately with the current value, then on every change. Returns unsubscribe. */\nexport const onChatProviderChange = (listener: (provider: ChatProviderInfo | null) => void): (() => void) =>\n channel.onChange(listener);\n\n/** Subscribe to the provider-state description. */\nexport const onChatProviderStateChange = (listener: (state: ChatProviderState) => void): (() => void) =>\n channel.onChange((p) => listener(stateOf(p)));\n\n/** React hook returning the resolved chat provider (or `null`), re-rendering on\n * change — gate the summarize affordance on `provider !== null`. */\nexport const useChatProvider = (): ChatProviderInfo | null => channel.use();\n\n/**\n * React hook returning the four-state description.\n *\n * Use this to render provider state honestly: show nothing (or a neutral placeholder)\n * while `unknown`, the connect affordance only on `not-configured`, the NOT-GRANTED\n * cause — never the connect copy — on `ungranted`, and the provider's name on\n * `configured`.\n */\nexport const useChatProviderState = (): ChatProviderState => stateOf(channel.use());\n"],"mappings":";AAiBA,SAAS,QAAQ,oBAAoB;AACrC,SAAS,yBAAyB;AAClC,SAAS,cAAc,4BAA4B;AA0J5C,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,SAAO,aAAoC,YAAY,QAA8C,MAAM;AAC7G;AA+BO,SAAS,MAAM,KAAyC;AAC7D,SAAO,OAAoB,aAAa,GAAyC;AACnF;AAuNA,MAAM,YAAqC,CAAC,kBAAkB,iBAAiB;AAE/E,MAAM,eAAe,CAAC,QAA6C;AACjE,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,EAAE,MAAM,MAAM,IAAI;AACxB,SAAO,OAAO,SAAS,YAAY,QAAQ,OAAO,UAAU,YAAY,QAAQ,EAAE,MAAM,MAAM,IAAI;AACpG;AAIA,MAAM,sBAAsB,CAAC,OAC1B,EAAE,GAAG,GAAG,WAAW,EAAE,cAAc,KAAK;AAE3C,MAAM,cAAc,CAAC,MAA4B,OAAO,MAAM,YAAY,OAAO,UAAU,CAAC,KAAK,IAAI;AAKrG,MAAM,aAAa,CAAC,MAA4B,OAAO,MAAM,YAAY,OAAO,UAAU,CAAC,KAAK,KAAK;AAMrG,MAAM,iBAAiB,CAAC,QAA2C;AACjE,MAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,EAAG,QAAO;AAClE,QAAM,IAAI;AACV,MACE,OAAO,EAAE,WAAW,aACpB,OAAO,EAAE,UAAU,aACnB,OAAO,EAAE,aAAa,aACtB,CAAC,WAAW,EAAE,gBAAgB;AAE9B,WAAO;AAET,QAAM,EAAE,QAAQ,OAAO,UAAU,iBAAiB,IAAI;AACtD,SAAO,oBAAoB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IAAI,gBAAgB;AACpB,MAAM,UAAU,kBAA2C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QAAQ;AACd,QAAI,EAAE,cAAc,KAAM,QAAO;AACjC,eAAW;AACX,oBAAgB,IAAI,cAAc;AAClC,WAAO,sBAAuB,IAAI,YAAwC,IAAI;AAAA,EAChF;AACF,CAAC;AAeM,SAAS,wBACdA,WACA,WACA,UACmB;AACnB,MAAI,CAACA,UAAU,QAAO,EAAE,QAAQ,UAAU;AAC1C,MAAI,UAAW,QAAO,EAAE,QAAQ,YAAY;AAC5C,SAAO,WAAW,EAAE,QAAQ,cAAc,SAAS,IAAI,EAAE,QAAQ,iBAAiB;AACpF;AAGA,MAAM,UAAU,CAAC,aACf,wBAAwB,UAAU,eAAe,QAAQ;AAUpD,MAAM,eAAe,MAA+B,QAAQ,IAAI;AAIhE,MAAM,oBAAoB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;AAIxE,MAAM,uBAAuB,CAAC,aACnC,QAAQ,SAAS,QAAQ;AAGpB,MAAM,4BAA4B,CAAC,aACxC,QAAQ,SAAS,CAAC,MAAM,SAAS,QAAQ,CAAC,CAAC,CAAC;AAIvC,MAAM,kBAAkB,MAA+B,QAAQ,IAAI;AAUnE,MAAM,uBAAuB,MAAyB,QAAQ,QAAQ,IAAI,CAAC;","names":["answered"]}
|
package/dist/mounts.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { APP_ROOT } from '@immediately-run/platform-constants';\nimport { throwOnRefusal } from './protocolRefusal';\n\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// R3-166 — the `spaces:*` family is GENERATED from the capability descriptor set\n// (`scripts/codegen-prototype/descriptors.spaces.mjs`) rather than hand-written here.\n// Re-exported from this module so every existing import path keeps working: the\n// swap is a no-op to consumers (SDK_SIMPLIFICATION_SPEC §7 step 3), which is\n// asserted by the emitted-`.d.ts` before/after comparison, not assumed. The five\n// invite-inbox verbs joined the generated family with their `Invite` type (the\n// declared \"next migration increment\" after #85); the mount verbs and the live\n// inbox channel trio below stay hand-written — they are not request wrappers.\n//\n// The invite channel's parse below uses `Invite`, so it is imported (not only\n// re-exported).\nimport type { Invite } from './generated/spaces';\nexport type { Role, SpaceInfo, Member, ResolvedUser, GrantRecord, Invite } from './generated/spaces';\nexport {\n listSpaces,\n listAllSpaces,\n getSpaceMembers,\n inviteToSpace,\n unshareSpace,\n setSpaceRole,\n lookupUser,\n listGrants,\n revokeGrant,\n listPendingInvites,\n revokeInvite,\n listMyInvites,\n acceptInvite,\n declineInvite,\n // R3-723 — the space lifecycle verbs (FILE_SHARING_SPEC §6.2/§9.7): soft\n // delete + undo, leave, rename, and the named one-way conversion.\n deleteSpace,\n restoreSpace,\n leaveSpace,\n renameSpace,\n convertSpaceToShared,\n} from './generated/spaces';\nexport type {\n DeleteSpaceError,\n RestoreSpaceError,\n LeaveSpaceError,\n RenameSpaceError,\n ConvertSpaceToSharedError,\n} from './generated/spaces';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\nimport {\n INVITATIONS,\n MOUNT_ADD,\n MOUNT_REMOVE,\n PROTOCOL_LOCALSTORE,\n PROTOCOL_SETTINGS,\n PROTOCOL_SPACES,\n REQUEST_INVITATIONS,\n REQUEST_MOUNTS,\n REQUEST_SESSION_MOUNTS,\n SESSION_MOUNTS,\n} from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\nimport { invoke } from './catalog';\n// Re-exported here so an app needs ONE import for a federated mount's bundle facts\n// (`SandboxMount.bundle` + the layout type it carries) — the same root-export\n// convention `linkSpace.ts` applies to the mdx-plugins link types.\nimport type { BundleLayout } from '@immediately-run/mdx-plugins';\nexport type { BundleLayout };\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? APP_ROOT;\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: 'ro' | 'rw';\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n /**\n * R3-546 (BUNDLE_EMBEDDING §4a.3, gate G-BE-19): bundle facts, when this mount is a\n * federated `bundle:` view over another bundle. The host parses the target bundle's\n * marker and hands the consumer its `kind` and its LAYOUT **pruned to this mount's\n * subtree view** — a record set, `tree` entry or `unique` reference the view cannot\n * reach is absent, so the description is never an existence map of what the chroot\n * answers `ENOENT` for. Pure data: nothing in it is authority, and the consumer\n * could have read it if it held the target's root. Absent on every non-bundle mount\n * and on older hosts.\n */\n bundle?: SandboxMountBundle;\n /**\n * R3-876 (APP_CUSTOMIZATION_SPEC §5a): the host's advisory reading of whether the\n * READER can edit this delegation's source — computed from the reader's own\n * authority (their role on the source space, or sign-in for a working tree), NOT\n * from anything about your own mount. Gate an Edit affordance on it\n * (`requestEdit({ bundleFile })` is the call it hints at): offer the control when\n * `true`, hide it when `false`, and treat an absent hint (older host, non-delegation\n * mount) as \"unknown — offer and let the refusal tell you\". Display-only: it is\n * never an authority input, and the host re-announces the mount when a role change\n * flips it.\n */\n readerCanEdit?: boolean;\n}\n\n/** The bundle facts a federated mount descriptor carries (§4a.3). */\nexport interface SandboxMountBundle {\n /** The target bundle's declared `kind`, when it declares one. */\n kind?: string;\n /**\n * R3-184 (PERSISTENCE_SPEC §8.0/§8.5) — the DECLARED in-bundle mount name\n * (`requests.mounts[].at`, e.g. `/items`): the alias the declaring bundle's own\n * documents address this view by, carried beside the mount's `path` (the\n * host-assigned task slot, §8.3). Pure data — it is never authority and never a\n * second mount point; a bundle-carrying app matches the alias back to the\n * declaration that minted the view. Absent on older hosts.\n */\n at?: string;\n /** The target's layout, pruned to this mount's view (`pruneLayoutToView`). */\n layout?: BundleLayout;\n /**\n * Why a refused or `forbidden` `bundle:` mount degraded the DECLARING bundle's\n * render (PERSISTENCE §8.0 containment: the carrying filesystem stays mounted).\n * Mount-resolution refusal codes (`escapes-filesystem`, `not-a-bundle`,\n * `unsafe-subtree`, `subtree-in-nested-bundle`, …), surfaced so the callee can\n * read them — the declaring bundle always renders, degraded wherever a\n * declaration did not resolve.\n */\n diagnostics?: readonly string[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason = 'revoked' | 'unshared' | 'signed-out' | 'unmounted' | 'deleted';\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value) ? (value as MountRemoveReason) : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\n/** @deprecated-path The injected `bundler.mounts` read — window opened 2026-08-25\n * (R3-278). The protocol equivalent is `transportMountService()` below (the\n * `mount-add`/`mount-remove` mirror + `request-mounts` replay), which the dual-mode\n * chooser already falls back to. Injection stays preferred for byte-compat through\n * the window; see DEPRECATION_CANDIDATES.md.\n */\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener(MOUNT_ADD, (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener(MOUNT_REMOVE, (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage(REQUEST_MOUNTS);\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean => mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined => getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n *\n * `timeoutMs` (optional, additive) rejects with a `timeout`-coded error instead of\n * waiting forever. Omit it to keep the original unbounded behaviour — but prefer\n * setting it on any path whose caller would otherwise hang silently: a mount that\n * never arrives is indistinguishable from one that is merely slow, and an awaited\n * promise that never settles surfaces to the user as a feature that quietly does\n * nothing.\n *\n * **Hazard — `onMountsChange` calls its listener SYNCHRONOUSLY on subscribe** (the\n * documented initial replay). So when the mount is already present — the common\n * case, since callers typically `await` the host request that creates it first —\n * the callback below runs *during* the `onMountsChange(...)` call, before the\n * assignment to `unsubscribe` completes. `unsubscribe` is therefore declared with\n * `let` ABOVE the subscription and read only inside a deferred closure: writing\n * `const unsubscribe = onMountsChange(...)` and referencing it in the callback\n * throws `ReferenceError: Cannot access 'unsubscribe' before initialization` (a\n * temporal-dead-zone read) on exactly that path. That bug silently broke\n * `openSettings()` — and with it the agent's conversation memory.\n */\nexport const waitForMount = (query: MountQuery, timeoutMs?: number): Promise<SandboxMount> =>\n awaitMatchingMount(onMountsChange, query, timeoutMs);\n\n/** The framework-free core of {@link waitForMount}, with the subscription injected\n * so a test can drive the synchronous-initial-replay case that broke it. */\nexport const awaitMatchingMount = (\n subscribe: (listener: (mounts: SandboxMount[]) => void) => () => void,\n query: MountQuery,\n timeoutMs?: number,\n): Promise<SandboxMount> =>\n new Promise((resolve, reject) => {\n // `let`, declared BEFORE `subscribe(...)` — see the hazard note above. A\n // `const` bound to the subscribe call is in its temporal dead zone while the\n // synchronous initial replay runs, and any read of it from the listener\n // throws.\n let unsubscribe: (() => void) | undefined;\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n // Deferred so we never dispose the subscription from inside its own initial\n // replay, and late enough that `unsubscribe` is always assigned.\n const stop = (): void => {\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n void Promise.resolve().then(() => unsubscribe?.());\n };\n unsubscribe = subscribe((mounts) => {\n if (settled) return;\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n stop();\n resolve(found);\n }\n });\n // The initial replay may have settled us above, before `unsubscribe` existed;\n // `stop()`'s deferred read picks it up, so nothing more is needed here.\n if (!settled && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (settled) return;\n stop();\n const err = new Error(\n `waitForMount timed out after ${timeoutMs}ms waiting for ${JSON.stringify(query)}`,\n ) as SpaceError;\n err.code = 'timeout';\n reject(err);\n }, timeoutMs);\n }\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: SESSION_MOUNTS,\n requestType: REQUEST_SESSION_MOUNTS,\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (listener: (mounts: SessionMount[]) => void): (() => void) =>\n sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** An error from a space operation, carrying a machine-readable `code`.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface\n * documents the `.code` VALUES the host sends. Nothing enforces the union at runtime —\n * `.code` is whatever string arrived — so treat an unlisted code as possible and\n * `instanceof Error` as the only reliable test.\n */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n // Client-side, never from the host: a bounded `waitForMount` gave up.\n | 'timeout'\n | 'unknown';\n}\n\ntype SpaceResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and throwing\n// a coded refusal on failure — `throwOnRefusal` raises a `CodedRefusalError` whose `code`\n// is whatever string the host sent, NOT a `SpaceError` (nothing enforces that union, and\n// this helper no longer performs the throw). See `protocolRefusal.ts`.\nconst request = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES], method, [query])) as SpaceResult;\n throwOnRefusal(res, 'space request failed');\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (method: string, query: Record<string, unknown>): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> => requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> => mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> => requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n *\n * The body repeats {@link capFile} rather than calling it, and that is deliberate:\n * `tasks.ts` registers a host listener at module load, so a VALUE import of it here\n * would run that side effect in every importer of `mounts` (which is why the\n * `FileCap` import above is type-only). The shape the two share is the spec's, and\n * the `FileCap` type is what holds them to it.\n */\nexport const makeContentRef = (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/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a coded refusal\n// on failure (mirrors `request`; the thrown value is a `CodedRefusalError`, not a\n// `SpaceError` — see `protocolRefusal.ts`).\nconst settingsRequest = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SETTINGS], method, [query])) as SpaceResult;\n throwOnRefusal(res, 'settings request failed');\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n *\n * **Which filesystem you get, and when that can change** (R3-413): for an\n * ordinary app — including one holding space grants, powerbox-picked or\n * declared — this is ALWAYS the app-level store (same mount id every call, so\n * \"which space did I pick\" style state survives later grants; no need to open\n * early and keep the handle). The one exception: an instance the host has\n * **floored** below its app tier (the generic-viewer containment,\n * `TRUST_MODES_SPEC` §5) gets a per-origin partition instead — a DIFFERENT\n * filesystem, chosen by the host, that changes when the loaded origin changes\n * and refuses (`forbidden`) when the floor forbids the write. If your app can\n * run floored and needs continuity across origins, keep state per-mount (the\n * returned `SandboxMount.id` tells you which partition you are in).\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway: an unbounded wait\n // here turns any delivery failure into a promise that never settles, and every\n // caller of `openSettings()` is doing it to reach durable state — so the app\n // just quietly loses that state with nothing to report.\n return waitForMount({ id: mount.id ?? mount.path }, SETTINGS_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openSettings()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst SETTINGS_MOUNT_TIMEOUT_MS = 15_000;\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> => settingsRequest<string[]>('list');\n\n// ---------------------------------------------------------------------------\n// Device-local store — the per-app, device-local, IndexedDB-backed filesystem\n// (FILESYSTEM_SPEC §2.8). The distinction from `settings:` is durability, stated\n// to the app via the mount's `type: 'localstore'`, never a guess.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-localstore` request, unwrapping {ok,data} and throwing a coded refusal\n// on failure (mirrors `settingsRequest`; a `CodedRefusalError`, not a `SpaceError`).\nconst localStoreRequest = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_LOCALSTORE], method, [query])) as SpaceResult;\n throwOnRefusal(res, 'localstore request failed');\n return res.data as T;\n};\n\n/**\n * Mount this app's **device-local** store — a private, per-device, IndexedDB-backed\n * filesystem, NOT synced (unlike {@link openSettings}). The cheap, throwaway-able\n * home for a cache, a draft, a scroll position, a checkpoint; the wrong home for\n * anything the user would mourn (the browser may evict it under storage pressure,\n * and the docs say so). Read/write it through `fs` at the returned mount's `path`,\n * with `type: 'localstore'`.\n *\n * Isolation is the store itself, keyed on the app's `appKey` — an app can never\n * name another app's local store, there is deliberately no `openOf` sibling, and\n * nothing written here is synced. Capability: baseline `storage:local` (no consent\n * prompt). Rejects with a {@link SpaceError}: `auth-required` when signed out,\n * `forbidden` when the capability is absent. A quota/external failure surfaces the\n * underlying error unchanged, so an app can tell \"the browser evicted me\" from\n * \"I never wrote anything\".\n */\nexport const openLocalStore = async (): Promise<SandboxMount> => {\n const mount = await localStoreRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway, for the same reason\n // `openSettings()` bounds its wait: an unbounded wait turns any delivery failure\n // into a promise that never settles, and the caller reached for durable state.\n return waitForMount({ id: mount.id ?? mount.path }, LOCALSTORE_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openLocalStore()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst LOCALSTORE_MOUNT_TIMEOUT_MS = 15_000;\n\n/** Create a brand-new, empty platform-hosted space, granted to THIS app in full\n * (read-write) — the user's create consent is consent for the app to create\n * storage for itself, and the host records the same durable grant the\n * {@link requestMount} powerbox would. So the returned mount can be re-opened\n * later with {@link mountSpace} / {@link mount} (`space:<id>`) with no prompt —\n * on the next load, in another tab, after sign-out/sign-in — until the user\n * revokes the grant in their grants surface, after which `mount` answers\n * `forbidden`. Other apps get nothing: they still reach the space only through\n * the powerbox. (Before site-main R3-406 no grant was recorded and the space\n * could only be re-found via the powerbox.) */\nexport const createSpace = (opts: { name?: string } = {}): Promise<SandboxMount> =>\n requestMountInternal('create', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n//\n// The request verbs above (invite inbox included) are generated from the\n// descriptor set; what remains hand-written here is the live invitations\n// channel (FILE_SHARING §6.4/§9.8): the host pushes the caller's current\n// invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects\n// within one snapshot — no poll. Mirrors the host's\n// `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: INVITATIONS,\n requestType: REQUEST_INVITATIONS,\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n\n// ---------------------------------------------------------------------------\n// The space keyring (REALTIME_MESSAGING_SPEC §6.1, R3-633f). Hand-written on\n// purpose, and NOT moved into the generated family: the generated wrappers\n// return the wire payload as typed, while this boundary must PROJECT — a host\n// reply that (wrongly) carried a private half (a `d` field) is never\n// propagated, because the type is the boundary and the projection is the\n// proof (§16's must-establish row: \"a member's space private key is never\n// returned to an app sandbox\"). Both calls are `spaces:user` (§6.5(d): public\n// halves only — no new capability).\n\n/** One member's published space key — the PUBLIC half only. The ECDH P-256\n * public JWK carries exactly `kty`/`crv`/`x`/`y`; there is no field for the\n * private scalar anywhere in this type (and none named `d`), so the shape\n * cannot carry one. */\nexport interface PublishedSpaceKey {\n /** The member the key belongs to. */\n uid: string;\n /** The key id (write-once; rotation appends a new kid). */\n kid: string;\n /** The public JWK (four fields, no `d`). */\n pub: { kty: string; crv: string; x: string; y: string };\n /** The algorithm label (see the host's SPACE_KEY_ALG_LABEL). */\n alg: string;\n /** Epoch milliseconds when the key was published. */\n addedAt: number;\n}\n\n/** Publish the caller's own space key (REALTIME_MESSAGING §6.1) — minted at join\n * time by the host already; this call is the explicit retry/self-heal an app can\n * offer. Idempotent: a member who has published resolves the existing kid with\n * `created: false`. The private half is sealed under the member's passkey-derived\n * KEK host-side and never crosses this boundary. Rejects with a typed refusal:\n * `cancelled` (the passkey prompt was dismissed), `unsupported` (the platform\n * cannot seal here), `forbidden` (not a member), `auth-required` when signed out. */\nexport const publishSpaceKey = async (spaceId: string): Promise<{ kid: string; created: boolean }> => {\n // `invoke`, not the local `request` helper: the wire-shape gate\n // (check-protocol-snapshot) extracts the catalog front door's call sites, and\n // a helper call is invisible to it — the published contract and this source\n // must agree byte-for-byte. Same envelope unwrap + coded refusal, with one\n // recorded difference: `request`'s throwOnRefusal coerces a NON-STRING refusal\n // code/message to 'unknown'/a fallback, while catalog.ts's invoke assigns\n // `res?.code ?? 'unknown'` unchecked (its pre-fold shape — protocolRefusal.ts's\n // census). The wire sends strings; the difference is unreachable today.\n const r = await invoke<{ ok: true; kid: string; created: boolean }>('spaces:publishSpaceKey', { spaceId });\n return { kid: r.kid, created: r.created };\n};\n\n/** The published public halves of a space's members (REALTIME_MESSAGING §6.1) —\n * readable by every member, refused `forbidden` for a non-member (the store read\n * is the membership gate). Members who have not published are simply ABSENT\n * (§6.2's fail-closed create reads that absence; the targeted probe is the\n * optional `uid` form, which answers `not-found` for an unpublished member).\n * The returned rows are PROJECTED to {@link PublishedSpaceKey}: a wire row\n * carrying anything more (e.g. a `d` field) is not propagated. */\nexport const listSpaceKeys = async (spaceId: string, uid?: string): Promise<PublishedSpaceKey[]> => {\n // One declared params type (never a conditional literal) so the wire-shape\n // gate fingerprints `uid` as `string | undefined` — the published snapshot's\n // recorded shape (sandbox-protocol 0.15.0). `invoke` here for the same reason\n // as publishSpaceKey above (the gate extracts the catalog front door's call\n // sites); the same invoke-vs-throwOnRefusal coercion note applies.\n const params: { spaceId: string; uid?: string } = { spaceId };\n if (uid !== undefined) params.uid = uid;\n const rows = await invoke<Array<Record<string, unknown>>>('spaces:listSpaceKeys', params);\n // Project, never coerce (the host store's own doctrine): the four public JWK\n // fields are copied verbatim and EVERYTHING else is dropped — a row carrying a\n // private half (`d`) does not propagate; a malformed row is the host's to\n // reject upstream (its project() refuses one), never this layer's to repair.\n return rows.map((row) => {\n const pub = row.pub as PublishedSpaceKey['pub'];\n return {\n uid: row.uid as string,\n kid: row.kid as string,\n pub: { kty: pub.kty, crv: pub.crv, x: pub.x, y: pub.y },\n alg: row.alg as string,\n addedAt: row.addedAt as number,\n };\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAyB;AACzB,6BAA+B;AAE/B,mBAAoC;AACpC,0BAA0D;AAC1D,yBAAkC;AAClC,yBAA+B;AAC/B,wBAA6B;AAc7B,oBAsBO;AAWP,sBAWO;AACP,6BAAwB;AACxB,qBAAuB;AAehB,MAAM,kBAAkB,UAAc,mCAAe,GAAG,gBAAgB;AA8H/E,MAAM,WAAW,CAAC,MAA4B,EAAE,MAAM,EAAE;AAExD,MAAM,uBAA4C,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AAA,MACT,SAAS,IAAI;AAAA,IACf;AAAA,EACF,CAAC;AACH;","names":["mount"]}
|
|
1
|
+
{"version":3,"sources":["../src/mounts.ts"],"sourcesContent":["import { APP_ROOT } from '@immediately-run/platform-constants';\nimport { throwOnRefusal } from './protocolRefusal';\n\nimport { useEffect, useState } from 'react';\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { createPushChannel } from './pushChannel';\nimport { getHostRuntime } from './hostRuntime';\nimport { mountMatches } from './mountMatch';\n// R3-166 — the `spaces:*` family is GENERATED from the capability descriptor set\n// (`scripts/codegen-prototype/descriptors.spaces.mjs`) rather than hand-written here.\n// Re-exported from this module so every existing import path keeps working: the\n// swap is a no-op to consumers (SDK_SIMPLIFICATION_SPEC §7 step 3), which is\n// asserted by the emitted-`.d.ts` before/after comparison, not assumed. The five\n// invite-inbox verbs joined the generated family with their `Invite` type (the\n// declared \"next migration increment\" after #85); the mount verbs and the live\n// inbox channel trio below stay hand-written — they are not request wrappers.\n//\n// The invite channel's parse below uses `Invite`, so it is imported (not only\n// re-exported).\nimport type { Invite } from './generated/spaces';\nexport type { Role, SpaceInfo, Member, ResolvedUser, GrantRecord, Invite } from './generated/spaces';\nexport {\n listSpaces,\n listAllSpaces,\n getSpaceMembers,\n inviteToSpace,\n unshareSpace,\n setSpaceRole,\n lookupUser,\n listGrants,\n revokeGrant,\n listPendingInvites,\n revokeInvite,\n listMyInvites,\n acceptInvite,\n declineInvite,\n // R3-723 — the space lifecycle verbs (FILE_SHARING_SPEC §6.2/§9.7): soft\n // delete + undo, leave, rename, and the named one-way conversion.\n deleteSpace,\n restoreSpace,\n leaveSpace,\n renameSpace,\n convertSpaceToShared,\n} from './generated/spaces';\nexport type {\n DeleteSpaceError,\n RestoreSpaceError,\n LeaveSpaceError,\n RenameSpaceError,\n ConvertSpaceToSharedError,\n} from './generated/spaces';\n// Type-only: `tasks.ts` registers a host listener at module load, so we reuse the\n// FileCap SHAPE without pulling that side effect into every `mounts` importer.\nimport type { FileCap } from './tasks';\nimport {\n INVITATIONS,\n MOUNT_ADD,\n MOUNT_REMOVE,\n PROTOCOL_LOCALSTORE,\n PROTOCOL_SETTINGS,\n PROTOCOL_SPACES,\n REQUEST_INVITATIONS,\n REQUEST_MOUNTS,\n REQUEST_SESSION_MOUNTS,\n SESSION_MOUNTS,\n} from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\nimport { invoke } from './catalog';\n// Re-exported here so an app needs ONE import for a federated mount's bundle facts\n// (`SandboxMount.bundle` + the layout type it carries) — the same root-export\n// convention `linkSpace.ts` applies to the mdx-plugins link types.\nimport type { BundleLayout } from '@immediately-run/mdx-plugins';\nexport type { BundleLayout };\n\n/**\n * The absolute path where this app's own repository filesystem is mounted\n * (FILE_SHARING_SPEC §11.2). Prefer this over hardcoding `/app`: the repo is\n * dual-mounted at both `/app` (back-compat) and its canonical `/mnt/{hash}`\n * address, and this returns the canonical one the host reports. Falls back to\n * `/app` when the host hasn't reported a canonical path (older host / before the\n * report arrives) — both paths are live, so either resolves the same files.\n */\nexport const getAppMountPath = (): string => getHostRuntime()?.appMountPath ?? APP_ROOT;\n\n/**\n * A filesystem mount available to the sandbox, mirrored from the host window.\n *\n * Mounts appear on demand — call {@link openSettings} for this app's own settings,\n * or {@link mountSpace} / {@link requestMount} to mount a Firestore-backed \"space\".\n * Read or subscribe to the set, then access the files through the `fs` module at\n * the mount's `path`.\n */\nexport interface SandboxMount {\n /** Absolute path where the mount is reachable (e.g. `/spaces/{id}`). */\n path: string;\n /** Backend kind, e.g. `'firestore'`. */\n type: string;\n /** Optional stable identifier (the spaceId, for spaces). */\n id?: string;\n /**\n * Access mode of the granted view: `'rw'` (read-write) or `'ro'` (read-only).\n * A live role downgrade re-announces the same mount with `mode: 'ro'`; apps\n * observing `onMountsChange` see the change and writes start failing `EROFS`.\n * Absent on the primary repo mount (treated as read-write).\n */\n mode?: 'ro' | 'rw';\n /**\n * Human-readable label for the mount — the space's display name, or the repo\n * label for the primary working-tree mount (R3-69). Use this to show users and\n * agents *what* a mount is: the `path` (`/mnt/{hash}`) and `id` (the spaceId)\n * are opaque, and space names are not unique, so neither alone tells you which\n * filesystem you're looking at. Absent when the host can't resolve a name\n * (older host, or a name it never learned) — fall back to `id`/`path`.\n */\n name?: string;\n /**\n * The granted scopes of this mount (plan 12 §8.7 / §F): each `{subtree, mode}`\n * is a path prefix you hold and at what access, at the mount's backend-natural\n * paths. Use it to reason about per-path writability — which subtree is `rw` —\n * WITHOUT probing `EROFS`. A single whole-mount grant is `[{ subtree: '/', mode }]`.\n * Absent on the primary repo mount and on an older host that doesn't report it.\n */\n rules?: MountRule[];\n /**\n * R3-546 (BUNDLE_EMBEDDING §4a.3, gate G-BE-19): bundle facts, when this mount is a\n * federated `bundle:` view over another bundle. The host parses the target bundle's\n * marker and hands the consumer its `kind` and its LAYOUT **pruned to this mount's\n * subtree view** — a record set, `tree` entry or `unique` reference the view cannot\n * reach is absent, so the description is never an existence map of what the chroot\n * answers `ENOENT` for. Pure data: nothing in it is authority, and the consumer\n * could have read it if it held the target's root. Absent on every non-bundle mount\n * and on older hosts.\n */\n bundle?: SandboxMountBundle;\n /**\n * R3-876 (APP_CUSTOMIZATION_SPEC §5a): the host's advisory reading of whether the\n * READER can edit this delegation's source — computed from the reader's own\n * authority (their role on the source space, or sign-in for a working tree), NOT\n * from anything about your own mount. Gate an Edit affordance on it\n * (`requestEdit({ bundleFile })` is the call it hints at): offer the control when\n * `true`, hide it when `false`, and treat an absent hint (older host, non-delegation\n * mount) as \"unknown — offer and let the refusal tell you\". Display-only: it is\n * never an authority input, and the host re-announces the mount when a role change\n * flips it.\n */\n readerCanEdit?: boolean;\n}\n\n/** The bundle facts a federated mount descriptor carries (§4a.3). */\nexport interface SandboxMountBundle {\n /** The target bundle's declared `kind`, when it declares one. */\n kind?: string;\n /**\n * R3-184 (PERSISTENCE_SPEC §8.0/§8.5) — the DECLARED in-bundle mount name\n * (`requests.mounts[].at`, e.g. `/items`): the alias the declaring bundle's own\n * documents address this view by, carried beside the mount's `path` (the\n * host-assigned task slot, §8.3). Pure data — it is never authority and never a\n * second mount point; a bundle-carrying app matches the alias back to the\n * declaration that minted the view. Absent on older hosts.\n */\n at?: string;\n /** The target's layout, pruned to this mount's view (`pruneLayoutToView`). */\n layout?: BundleLayout;\n /**\n * Why a refused or `forbidden` `bundle:` mount degraded the DECLARING bundle's\n * render (PERSISTENCE §8.0 containment: the carrying filesystem stays mounted).\n * Mount-resolution refusal codes (`escapes-filesystem`, `not-a-bundle`,\n * `unsafe-subtree`, `subtree-in-nested-bundle`, …), surfaced so the callee can\n * read them — the declaring bundle always renders, degraded wherever a\n * declaration did not resolve.\n */\n diagnostics?: readonly string[];\n}\n\n/** One granted scope of a mount (plan 12 §F): a backend-natural path prefix and\n * the access mode there. The most specific (longest) matching rule governs a path. */\nexport interface MountRule {\n subtree: string;\n mode: 'ro' | 'rw';\n}\n\n/**\n * Why a mounted filesystem was removed, surfaced on the removed descriptor so an\n * app can say *why* it vanished instead of failing mutely (auth-mount §\"mount-remove\"\n * / AM2-4):\n * - `revoked` — a durable grant was revoked (revokeGrant / consent withdrawal);\n * - `unshared` — the granting user's membership was removed (or downgraded out);\n * - `signed-out` — sign-out tore down every mount;\n * - `unmounted` — the app's own `unmountSpace` (or region teardown);\n * - `deleted` — the space was soft-deleted.\n * An older host that sends no reason is read as `'revoked'` (most conservative).\n */\nexport type MountRemoveReason = 'revoked' | 'unshared' | 'signed-out' | 'unmounted' | 'deleted';\n\n/** A descriptor delivered as REMOVED to a mounts-change listener: the mount that\n * went away, plus the `reason` it did. */\nexport interface RemovedMount extends SandboxMount {\n reason: MountRemoveReason;\n}\n\ninterface MountService {\n getMounts(): SandboxMount[];\n onChange(listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void): { dispose(): void };\n}\n\n// The stable key of a mount: its `id` (spaceId) when present, else its `path`.\n// Matches the sandbox `MountService.mountKey` so add/replace/remove agree on both\n// sides of the wire (a role downgrade re-announces the SAME key with `mode: 'ro'`).\nconst mountKey = (m: SandboxMount): string => m.id ?? m.path;\n\nconst MOUNT_REMOVE_REASONS: ReadonlySet<string> = new Set<MountRemoveReason>([\n 'revoked',\n 'unshared',\n 'signed-out',\n 'unmounted',\n 'deleted',\n]);\n\n// Normalize an over-the-wire `mount-remove` reason; an absent/unknown value (older\n// host) reads as `'revoked'`, the most conservative reading (mirrors the sandbox).\nconst asMountRemoveReason = (value: unknown): MountRemoveReason =>\n typeof value === 'string' && MOUNT_REMOVE_REASONS.has(value) ? (value as MountRemoveReason) : 'revoked';\n\n// The injected sandbox-bundler mount service (`module.evaluation.module.bundler.mounts`),\n// or null when the SDK is npm-fetched with no injection — same dual-mode shape as\n// `sandboxUtils.transport()` and the metadata emitter (SDK_PACKAGING_SPEC §4/§8).\n/** @deprecated-path The injected `bundler.mounts` read — window opened 2026-08-25\n * (R3-278). The protocol equivalent is `transportMountService()` below (the\n * `mount-add`/`mount-remove` mirror + `request-mounts` replay), which the dual-mode\n * chooser already falls back to. Injection stays preferred for byte-compat through\n * the window; see DEPRECATION_CANDIDATES.md.\n */\nconst injectedMountService = (): MountService | null => {\n try {\n // @ts-ignore - injected by the sandbox runtime\n const svc = module?.evaluation?.module?.bundler?.mounts;\n return svc && typeof svc.getMounts === 'function' ? svc : null;\n } catch {\n return null;\n }\n};\n\n// Transport-backed descriptor cache (R3-51b): the npm-fetched fallback that builds\n// the same `getMounts()`/`onChange()` view the injected `bundler.mounts` provides,\n// directly from the host's `mount-add`/`mount-remove` messages over the §4 transport.\n// The host already posts these (it's how the in-iframe bundler service is populated);\n// the `MessagePort` a `mount-add` transfers is consumed by the sandbox runtime to wire\n// ZenFS and is irrelevant here — the SDK only mirrors the *descriptors*. A lazy\n// singleton so `getMounts`/`onMountsChange` share one cache, one subscription, and one\n// `request-mounts` replay (the host re-announces every current mount, like a poll).\nlet transportSvc: MountService | null = null;\n\nconst transportMountService = (): MountService => {\n if (transportSvc) return transportSvc;\n let mounts: SandboxMount[] = [];\n const listeners = new Set<(m: SandboxMount[], r: RemovedMount[]) => void>();\n const fire = (removed: RemovedMount[]) => {\n for (const l of [...listeners]) l(mounts, removed);\n };\n\n addListener(MOUNT_ADD, (msg: Record<string, any>) => {\n const mount: SandboxMount | undefined = msg.mount;\n if (!mount) return;\n const key = mountKey(mount);\n mounts = [...mounts.filter((m) => mountKey(m) !== key), mount];\n fire([]);\n });\n addListener(MOUNT_REMOVE, (msg: Record<string, any>) => {\n const key: string | undefined = msg.id ?? msg.path;\n if (key == null) return;\n const reason = asMountRemoveReason(msg.reason);\n const removed = mounts.filter((m) => mountKey(m) === key).map((m) => ({ ...m, reason }));\n if (removed.length === 0) return;\n mounts = mounts.filter((m) => mountKey(m) !== key);\n fire(removed);\n });\n\n // Ask the host to replay the current set (the matching `mount-add`s may have been\n // sent before this SDK subscribed). Best-effort: a transport not yet ready throws.\n try {\n sendMessage(REQUEST_MOUNTS);\n } catch {\n /* transport not ready — the live mount-add stream still populates the cache */\n }\n\n transportSvc = {\n getMounts: () => mounts,\n onChange: (listener) => {\n listeners.add(listener);\n listener(mounts, []); // immediate replay to the new subscriber\n return { dispose: () => listeners.delete(listener) };\n },\n };\n return transportSvc;\n};\n\n// Phase-5 dual mode: prefer the injected bundler service (the live path, behaviour\n// byte-for-byte unchanged); fall back to the transport-built cache when npm-fetched.\nconst mountService = (): MountService => injectedMountService() ?? transportMountService();\n\n/** A predicate-style matcher for {@link findMount} / {@link waitForMount}. Any\n * combination of coordinates; `name` matches the human-readable mount label. */\nexport type MountQuery = { type?: string; id?: string; path?: string; name?: string };\n\nconst matches = (mount: SandboxMount, query: MountQuery): boolean => mountMatches(mount, query);\n\n/**\n * Returns the mounts currently available. Poll this whenever you need a one-off\n * read; use {@link onMountsChange} or {@link useMounts} to react to changes.\n * Each descriptor carries its `id` (the spaceId), `path` (`/mnt/{hash}`) and —\n * when the host can resolve it — a human-readable `name` (R3-69), so this doubles\n * as a queryable mount→space mapping for showing or locating a mount by name.\n */\nexport const getMounts = (): SandboxMount[] => mountService().getMounts();\n\n/** Returns the first mount matching `query`, or `undefined`. */\nexport const findMount = (query: MountQuery): SandboxMount | undefined => getMounts().find((m) => matches(m, query));\n\n/**\n * Subscribe to mount changes. The listener is invoked immediately with the\n * current mounts (and an empty `removed`), then again on every change. The second\n * argument carries the descriptors REMOVED by that change, each with its `reason`\n * (AM2-4) — so an app can react to *why* a mount vanished (e.g. tell the user a\n * shared space was `unshared` vs `deleted`). It is empty on adds and on the\n * initial replay. Returns an unsubscribe fn.\n */\nexport const onMountsChange = (listener: (mounts: SandboxMount[], removed: RemovedMount[]) => void): (() => void) => {\n const disposable = mountService().onChange(listener);\n return () => disposable.dispose();\n};\n\n/**\n * Resolves once a mount matching `query` is present (immediately if it already\n * is). Handy for \"use it when it appears\" — e.g.\n * `await waitForMount({ type: 'firestore' })` before reading `/firestore`.\n *\n * `timeoutMs` (optional, additive) rejects with a `timeout`-coded error instead of\n * waiting forever. Omit it to keep the original unbounded behaviour — but prefer\n * setting it on any path whose caller would otherwise hang silently: a mount that\n * never arrives is indistinguishable from one that is merely slow, and an awaited\n * promise that never settles surfaces to the user as a feature that quietly does\n * nothing.\n *\n * **Hazard — `onMountsChange` calls its listener SYNCHRONOUSLY on subscribe** (the\n * documented initial replay). So when the mount is already present — the common\n * case, since callers typically `await` the host request that creates it first —\n * the callback below runs *during* the `onMountsChange(...)` call, before the\n * assignment to `unsubscribe` completes. `unsubscribe` is therefore declared with\n * `let` ABOVE the subscription and read only inside a deferred closure: writing\n * `const unsubscribe = onMountsChange(...)` and referencing it in the callback\n * throws `ReferenceError: Cannot access 'unsubscribe' before initialization` (a\n * temporal-dead-zone read) on exactly that path. That bug silently broke\n * `openSettings()` — and with it the agent's conversation memory.\n */\nexport const waitForMount = (query: MountQuery, timeoutMs?: number): Promise<SandboxMount> =>\n awaitMatchingMount(onMountsChange, query, timeoutMs);\n\n/** The framework-free core of {@link waitForMount}, with the subscription injected\n * so a test can drive the synchronous-initial-replay case that broke it. */\nexport const awaitMatchingMount = (\n subscribe: (listener: (mounts: SandboxMount[]) => void) => () => void,\n query: MountQuery,\n timeoutMs?: number,\n): Promise<SandboxMount> =>\n new Promise((resolve, reject) => {\n // `let`, declared BEFORE `subscribe(...)` — see the hazard note above. A\n // `const` bound to the subscribe call is in its temporal dead zone while the\n // synchronous initial replay runs, and any read of it from the listener\n // throws.\n let unsubscribe: (() => void) | undefined;\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n // Deferred so we never dispose the subscription from inside its own initial\n // replay, and late enough that `unsubscribe` is always assigned.\n const stop = (): void => {\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n void Promise.resolve().then(() => unsubscribe?.());\n };\n unsubscribe = subscribe((mounts) => {\n if (settled) return;\n const found = mounts.find((m) => matches(m, query));\n if (found) {\n stop();\n resolve(found);\n }\n });\n // The initial replay may have settled us above, before `unsubscribe` existed;\n // `stop()`'s deferred read picks it up, so nothing more is needed here.\n if (!settled && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (settled) return;\n stop();\n const err = new Error(\n `waitForMount timed out after ${timeoutMs}ms waiting for ${JSON.stringify(query)}`,\n ) as SpaceError;\n err.code = 'timeout';\n reject(err);\n }, timeoutMs);\n }\n });\n\n/** React hook returning the mounts currently available, re-rendering on change. */\nexport const useMounts = (): SandboxMount[] => {\n const [mounts, setMounts] = useState<SandboxMount[]>(getMounts);\n useEffect(() => onMountsChange(setMounts), []);\n return mounts;\n};\n\n// ---------------------------------------------------------------------------\n// Session-scope mounts — the first-party \"App | Session\" lens (PRINCIPALS §9 B2).\n// ---------------------------------------------------------------------------\n\n/** A mount as seen through the first-party **Session** lens (PRINCIPALS_SPEC §9 B2):\n * the session's mounts BEYOND this app's own (the editor/agent session's). This is\n * a metadata view — no filesystem port — so it extends {@link SandboxMount} with only\n * {@link forwardedToApp}. */\nexport interface SessionMount extends SandboxMount {\n /** True iff this mount is ALSO in the app's own {@link useMounts} (the App lens);\n * `false` for a session-export-only mount visible only to the editor/agent + the\n * Session lens. */\n forwardedToApp: boolean;\n}\n\n// The host pushes the session mount list ONLY to a FIRST-PARTY frame — the channel\n// is gated by the first-party-only `mounts:registry` capability (§8.9.1 / D-PRIN-4).\n// A URL-loaded/previewed app (or a fork of the File Explorer) never holds it, so the\n// push never arrives and `initial: []` stands — the Session lens is simply absent,\n// fail-closed. Mirrors the host's `session-mounts`/`request-session-mounts` wiring.\nconst sessionMountsChannel = createPushChannel<SessionMount[]>({\n pushType: SESSION_MOUNTS,\n requestType: REQUEST_SESSION_MOUNTS,\n initial: [],\n parse: (msg) => (Array.isArray(msg.mounts) ? (msg.mounts as SessionMount[]) : undefined),\n});\n\n/** The session's mounts (the \"Session\" lens superset), or `[]` when this frame is\n * not first-party. One-off read; use {@link onSessionMountsChange}/{@link useSessionMounts}\n * to react live. First-party only (`mounts:registry`) — a fork always sees `[]`. */\nexport const getSessionMounts = (): SessionMount[] => sessionMountsChannel.get();\n\n/** Subscribe to Session-lens mount changes. Invoked immediately with the current\n * list (`[]` for a non-first-party frame), then on every change. Returns an\n * unsubscribe. */\nexport const onSessionMountsChange = (listener: (mounts: SessionMount[]) => void): (() => void) =>\n sessionMountsChannel.onChange(listener);\n\n/** React hook returning the live \"Session\" lens mount list, re-rendering on change.\n * Empty for any non-first-party frame (the host withholds the channel), so a URL-\n * loaded File Explorer fork renders no Session lens. */\nexport const useSessionMounts = (): SessionMount[] => sessionMountsChannel.use();\n\n// ---------------------------------------------------------------------------\n// Spaces — on-demand, shareable Firestore-backed filesystems.\n// The host owns all UX: if you aren't signed in, or the space doesn't exist or\n// isn't accessible, the parent window presents sign-in / create / request-access\n// and only then resolves these calls. See docs/specs/FILE_SHARING_SPEC.md.\n// ---------------------------------------------------------------------------\n\n/** An error from a space operation, carrying a machine-readable `code`.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. This interface\n * documents the `.code` VALUES the host sends. Nothing enforces the union at runtime —\n * `.code` is whatever string arrived — so treat an unlisted code as possible and\n * `instanceof Error` as the only reliable test.\n */\nexport interface SpaceError extends Error {\n code:\n | 'auth-required'\n | 'cancelled'\n | 'forbidden'\n | 'not-found'\n | 'unsupported-scheme'\n // Client-side, never from the host: a bounded `waitForMount` gave up.\n | 'timeout'\n | 'unknown';\n}\n\ntype SpaceResult = { ok: true; data: unknown } | { ok: false; code: string; message: string };\n\n// Issue a spaces protocol request, unwrapping the host's {ok,data} envelope and throwing\n// a coded refusal on failure — `throwOnRefusal` raises a `CodedRefusalError` whose `code`\n// is whatever string the host sent, NOT a `SpaceError` (nothing enforces that union, and\n// this helper no longer performs the throw). See `protocolRefusal.ts`.\nconst request = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SPACES], method, [query])) as SpaceResult;\n throwOnRefusal(res, 'space request failed');\n return res.data as T;\n};\n\n// Request a space mount, then wait until the host actually registers it. The\n// host announces the mount (`mount-add`) separately from the protocol reply, so\n// an immediate read could otherwise race the mount.\nconst requestMountInternal = async (method: string, query: Record<string, unknown>): Promise<SandboxMount> => {\n const mount = await request<SandboxMount>(method, query);\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * Mount a filesystem by its **universal mount id** (UI_AS_APPS_SPEC §3.5) —\n * `scheme:locator`, e.g. `space:{spaceId}` or `github:owner/repo@ref`. Backend-blind:\n * the host resolves the scheme. A scheme with no resolver rejects with\n * {@link SpaceError} `unsupported-scheme`.\n */\nexport const mount = (mountId: string): Promise<SandboxMount> => requestMountInternal('mount', { mount: mountId });\n\n/** Mount a specific space by id (e.g. one shared with you, or from a link). A thin\n * shim over {@link mount} with the `space:` scheme. */\nexport const mountSpace = (query: { spaceId: string }): Promise<SandboxMount> => mount(`space:${query.spaceId}`);\n\n/**\n * Ask the user to grant a filesystem to this app — the §8.6 powerbox. The app\n * asks; the HOST shows the user their spaces and, for the chosen one, its PROJECT\n * FOLDERS (§8.7). The user picks ONE project — so a shared space opens scoped to\n * just that project, never the whole space — and makes an EXPLICIT read-only vs\n * read-write decision (there is no default). The app never sees the list; it\n * resolves with the single granted mount, or rejects with a {@link SpaceError}\n * (`cancelled`) if declined. The granted scope is enforced host-side: the mount\n * is chroot'd to the project folder and `ro`-limited accordingly, so paths\n * outside the project are unnameable and writes on a `ro` grant fail `EROFS`.\n *\n * A project folder is the macOS-bundle-like unit an app works in inside a space;\n * the host records which app a folder belongs to (a `.immediately.run/` sidecar),\n * so the picker can surface the app's own projects or let the user create a new\n * one. Observe the granted access via {@link SandboxMount.mode}.\n *\n * Backend-general (§3.5): the picker offers whatever mounts the user has (today,\n * their spaces). Returns the granted mount by its universal id.\n */\nexport const requestMount = (): Promise<SandboxMount> => requestMountInternal('request', {});\n\n/** Prompt the user to grant a mount, returning the granted {@link SandboxMount}.\n * @deprecated renamed to {@link requestMount} (backend-general, §3.5). */\nexport const requestSpace = requestMount;\n\n// ── content references (plan 12 §E / FILE_SHARING §7) ────────────────────────\n\n/**\n * Build a persisted CONTENT REFERENCE to a file in a mount — a `{mountId, relPath}`\n * pointer your app serializes into ITS OWN content (a board's JSON, an MDX file's\n * frontmatter, an album manifest — the platform doesn't dictate the container) so a\n * later viewer can resolve it. It is exactly the §5.7 {@link capFile} shape: ONE\n * capability, two delivery modes — runtime delegation (a task param, authorized by\n * the caller) vs a durable reference (authorized per-viewer by {@link resolveContentRef}).\n * `relPath` is BACKEND-NATURAL, so the reference resolves to the SAME path for every\n * viewer. Cross-app/cross-project references default to `ro`.\n *\n * const ref = makeContentRef({ mountId: 'space:ACME', relPath: 'office-seating/desk.mdx' }, { mode: 'ro' });\n *\n * The body repeats {@link capFile} rather than calling it, and that is deliberate:\n * `tasks.ts` registers a host listener at module load, so a VALUE import of it here\n * would run that side effect in every importer of `mounts` (which is why the\n * `FileCap` import above is type-only). The shape the two share is the spec's, and\n * the `FileCap` type is what holds them to it.\n */\nexport const makeContentRef = (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/**\n * Resolve a content reference your app found in content it ALREADY holds\n * (FILE_SHARING §7 / UI_AS_APPS §8.7; \"plan 12 §E\"). This is a RELAY, not a\n * fabrication: the host honors it ONLY when your app\n * already holds a grant to `ref.mountId` (else `forbidden`) — apps follow\n * writer-authored links inside granted content; they cannot name a space from\n * nothing (T27). The host runs a per-VIEWER consent prompt (named via the owning\n * app's project sidecar), and existence is never leaked — a decline and a\n * non-existent path are indistinguishable.\n *\n * On allow, the host APPENDS a read scope for the referenced path to your grant\n * (durable; same §8.15 lifecycle) and returns the STABLE absolute `path` the file\n * is mounted at — identical for every viewer, so a path the author stored resolves\n * the same for you. Read it through the `fs` module at that path. Rejects with a\n * {@link SpaceError}: `forbidden` (you don't hold the referenced mount) or\n * `cancelled` (the viewer declined / the path doesn't exist — no oracle).\n *\n * const { path } = await resolveContentRef(ref);\n * const text = await fs.promises.readFile(path, 'utf8');\n */\nexport const resolveContentRef = async (ref: FileCap): Promise<{ path: string }> => {\n const path = await request<string>('resolveRef', { ref });\n return { path };\n};\n\n/**\n * Resolve a BATCH of content references in ONE consent round (FILE_SHARING §7 /\n * UI_AS_APPS §8.7; \"plan 12 §E\"). When a\n * board opens with several embedded references, pass them all here: the host\n * coalesces them into a SINGLE consent prompt listing every target, instead of one\n * prompt per reference. Same relay gate and per-viewer semantics as\n * {@link resolveContentRef} (each ref's mount must already be held), applied to the\n * whole set — it is all-or-nothing: the user allows the batch or declines it.\n *\n * Resolves `{ paths }` with the STABLE absolute path of each ref, in input order.\n * Rejects with a {@link SpaceError}: `forbidden` (a referenced mount isn't held) or\n * `cancelled` (the viewer declined).\n *\n * const { paths } = await resolveContentRefs(board.references);\n */\nexport const resolveContentRefs = async (refs: FileCap[]): Promise<{ paths: string[] }> => {\n const paths = await request<string[]>('resolveRefs', { refs });\n return { paths };\n};\n\n// ---------------------------------------------------------------------------\n// Settings — the per-user \"~/.config\"-style space (UI_AS_APPS_SPEC §3.3/§3.5/§8.2).\n// Each app gets its OWN settings subdir, auto-provisioned and chroot'd by the host\n// (no dialog, no powerbox). Read/write it through the returned mount's filesystem\n// port — there is deliberately no key/value get/set API; settings are just files.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-settings` request, unwrapping {ok,data} and throwing a coded refusal\n// on failure (mirrors `request`; the thrown value is a `CodedRefusalError`, not a\n// `SpaceError` — see `protocolRefusal.ts`).\nconst settingsRequest = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_SETTINGS], method, [query])) as SpaceResult;\n throwOnRefusal(res, 'settings request failed');\n return res.data as T;\n};\n\n/**\n * Mount this app's per-user settings — a private `~/.config`-style filesystem,\n * auto-provisioned for the signed-in user and isolated to THIS app (the host\n * chroots it; a different app can never name it). Read/write config files through\n * the returned mount. Rejects with a {@link SpaceError} (`auth-required`) when\n * signed out. Capability: baseline `settings:app`.\n *\n * **Which filesystem you get, and when that can change** (R3-413): for an\n * ordinary app — including one holding space grants, powerbox-picked or\n * declared — this is the app-level store (same mount id every call, so \"which\n * space did I pick\" style state survives later grants; no need to open early and\n * keep the handle). An instance the host has **floored** below its app tier (the\n * generic-viewer containment, `TRUST_MODES_SPEC` §5) keeps that app-level store\n * unless exactly one origin it opened at runtime is less trusted than the app; in\n * that one case it gets a per-origin partition instead — a DIFFERENT filesystem,\n * chosen by the host, that changes when the loaded origin changes. That\n * partition is normally writable: it is tiered by that origin's own trust.\n *\n * **A floored instance's settings mount may open read-only; the call still\n * resolves.** A floor below the app's tier can make the store you get read-only,\n * and that is most often the app's own app-level store above, not the per-origin\n * partition. An ordinary app that holds a space shared more widely than itself is\n * floored this way, so \"my app is ordinary\" does not mean \"my settings mount is\n * writable\".\n *\n * The open is not refused when writing is forbidden. You get a mount whose\n * descriptor is `mode: 'ro'`; any write through it fails with `EROFS`; and the\n * host shows its own notice explaining why. So check `mount.mode` on resolution\n * rather than treating this call as always-writable. A refloor mid-session ends\n * the app's realm and restarts it, so checking on each resolution covers that too.\n * Never surface an `EROFS` from a write as a fatal error: the app can still read,\n * and the remedy is the user's — revoking the widely-shared space in Settings →\n * App permissions.\n *\n * Which partition you get is still host-chosen and still changes with the loaded\n * origin. If your app can run floored and needs continuity across origins, keep\n * state per-mount (the returned `SandboxMount.id` tells you which partition you\n * are in).\n */\nexport const openSettings = async (): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway: an unbounded wait\n // here turns any delivery failure into a promise that never settles, and every\n // caller of `openSettings()` is doing it to reach durable state — so the app\n // just quietly loses that state with nothing to report.\n return waitForMount({ id: mount.id ?? mount.path }, SETTINGS_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openSettings()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst SETTINGS_MOUNT_TIMEOUT_MS = 15_000;\n\n/**\n * One-time SEED of this app's settings from the parent it declares as `forkOf`\n * (its `package.json` `immediately.run.forkOf`) — so a fork inherits your\n * preferences from the original app (UI_AS_APPS_SPEC §3.4). The host asks the user\n * to confirm (a full consent when the apps have different owners, a light confirm\n * when the same owner publishes both) and copies the parent's settings into this\n * app's own subdir, skipping any file you already have. Non-throwing: resolves\n * `{ ok:false, code }` on decline (`cancelled`), no declared parent (`forbidden`),\n * or signed-out (`auth-required`). After `{ ok:true }`, read {@link openSettings}.\n * Capability: baseline `settings:fork`.\n */\nexport const importSettingsFromParent = async (): Promise<\n { ok: true; copied: number } | { ok: false; code: string }\n> => {\n try {\n const data = await settingsRequest<{ copied: number }>('importFromParent');\n return { ok: true, copied: data.copied };\n } catch (e) {\n return { ok: false, code: (e as SpaceError).code ?? 'unknown' };\n }\n};\n\n/**\n * Mount ANOTHER app's per-user settings by its `appKey` — the elevated \"file\n * commander\" surface. Rejects `forbidden` unless this app holds the first-party-\n * only `settings:all` capability. Most apps want {@link openSettings} instead.\n */\nexport const openSettingsOf = async (appKey: string): Promise<SandboxMount> => {\n const mount = await settingsRequest<SandboxMount>('openOf', { appKey });\n return waitForMount({ id: mount.id ?? mount.path });\n};\n\n/**\n * List every app that has per-user settings — the elevated \"file commander\"\n * enumeration. Pair with {@link openSettingsOf} to mount any of them. Rejects\n * `forbidden` unless this app holds the first-party-only `settings:all`.\n */\nexport const listSettingsApps = (): Promise<string[]> => settingsRequest<string[]>('list');\n\n// ---------------------------------------------------------------------------\n// Device-local store — the per-app, device-local, IndexedDB-backed filesystem\n// (FILESYSTEM_SPEC §2.8). The distinction from `settings:` is durability, stated\n// to the app via the mount's `type: 'localstore'`, never a guess.\n// ---------------------------------------------------------------------------\n\n// Issue a `protocol-localstore` request, unwrapping {ok,data} and throwing a coded refusal\n// on failure (mirrors `settingsRequest`; a `CodedRefusalError`, not a `SpaceError`).\nconst localStoreRequest = async <T = unknown>(method: string, query: Record<string, unknown> = {}): Promise<T> => {\n const res = (await protocolRequest(SCHEMES[PROTOCOL_LOCALSTORE], method, [query])) as SpaceResult;\n throwOnRefusal(res, 'localstore request failed');\n return res.data as T;\n};\n\n/**\n * Mount this app's **device-local** store — a private, per-device, IndexedDB-backed\n * filesystem, NOT synced (unlike {@link openSettings}). The cheap, throwaway-able\n * home for a cache, a draft, a scroll position, a checkpoint; the wrong home for\n * anything the user would mourn (the browser may evict it under storage pressure,\n * and the docs say so). Read/write it through `fs` at the returned mount's `path`,\n * with `type: 'localstore'`.\n *\n * Isolation is the store itself, keyed on the app's `appKey` — an app can never\n * name another app's local store, there is deliberately no `openOf` sibling, and\n * nothing written here is synced. Capability: baseline `storage:local` (no consent\n * prompt). Rejects with a {@link SpaceError}: `auth-required` when signed out,\n * `forbidden` when the capability is absent. A quota/external failure surfaces the\n * underlying error unchanged, so an app can tell \"the browser evicted me\" from\n * \"I never wrote anything\".\n *\n * **A floored instance's local store may open read-only; the call still\n * resolves.** The same degrade {@link openSettings} documents applies here: when\n * the host has floored the instance below its app tier, the store may be announced\n * `mode: 'ro'`, writes through it fail `EROFS`, and the host shows its own notice.\n * Check the mount's `mode` as you would a settings mount, and never surface that\n * `EROFS` as fatal — but do not treat a failed write as harmless: this store holds\n * drafts and checkpoints too, so tell the user their save did not happen rather\n * than swallowing it.\n */\nexport const openLocalStore = async (): Promise<SandboxMount> => {\n const mount = await localStoreRequest<SandboxMount>('open');\n // The host has already accepted the request and announced the mount, so this\n // normally resolves on the initial replay. Bounded anyway, for the same reason\n // `openSettings()` bounds its wait: an unbounded wait turns any delivery failure\n // into a promise that never settles, and the caller reached for durable state.\n return waitForMount({ id: mount.id ?? mount.path }, LOCALSTORE_MOUNT_TIMEOUT_MS);\n};\n\n/** How long `openLocalStore()` waits for the host to deliver the mount it just\n * agreed to create. Generous — this is a hang-breaker, not a latency budget. */\nconst LOCALSTORE_MOUNT_TIMEOUT_MS = 15_000;\n\n/** Create a brand-new, empty platform-hosted space, granted to THIS app in full\n * (read-write) — the user's create consent is consent for the app to create\n * storage for itself, and the host records the same durable grant the\n * {@link requestMount} powerbox would. So the returned mount can be re-opened\n * later with {@link mountSpace} / {@link mount} (`space:<id>`) with no prompt —\n * on the next load, in another tab, after sign-out/sign-in — until the user\n * revokes the grant in their grants surface, after which `mount` answers\n * `forbidden`. Other apps get nothing: they still reach the space only through\n * the powerbox. (Before site-main R3-406 no grant was recorded and the space\n * could only be re-found via the powerbox.) */\nexport const createSpace = (opts: { name?: string } = {}): Promise<SandboxMount> =>\n requestMountInternal('create', opts);\n\n/** Release a mounted space (stops its listener on the host). */\nexport const unmountSpace = async (query: { spaceId: string }): Promise<void> => {\n await request('unmount', query);\n};\n\n// ---------------------------------------------------------------------------\n// Space management (the space-manager app) — UI_AS_APPS_SPEC §5.2. These are\n// ELEVATED: enumerating all the user's spaces is `spaces:user`; mutating\n// membership (share/unshare/setRole) and resolving handles is `spaces:admin`.\n// The host enforces the owner-lockout invariant (a space always keeps an owner,\n// T41) and rate-limits handle lookups (L1); the OAuth/identity token never\n// crosses to the app.\n//\n// The request verbs above (invite inbox included) are generated from the\n// descriptor set; what remains hand-written here is the live invitations\n// channel (FILE_SHARING §6.4/§9.8): the host pushes the caller's current\n// invitations on change and replays on register-frame; gated `spaces:user`.\n// So an invite that arrives (or an accepted/declined one leaving) reflects\n// within one snapshot — no poll. Mirrors the host's\n// `invitations`/`request-invitations` wiring.\nconst invitesChannel = createPushChannel<Invite[]>({\n pushType: INVITATIONS,\n requestType: REQUEST_INVITATIONS,\n initial: [],\n parse: (msg) => (Array.isArray(msg.invites) ? (msg.invites as Invite[]) : undefined),\n});\n\n/** The caller's current invitations (`spaces:user`). One-off read; use\n * {@link onInvitesChange}/{@link useInvites} to react live. */\nexport const getInvites = (): Invite[] => invitesChannel.get();\n\n/** Subscribe to invitation-inbox changes (arrived / accepted / declined). Invoked\n * immediately with the current list, then on every change. Returns an unsubscribe. */\nexport const onInvitesChange = (listener: (invites: Invite[]) => void): (() => void) =>\n invitesChannel.onChange(listener);\n\n/** React hook returning the caller's live invitation inbox, re-rendering on change\n * (the space-manager Invitations inbox, §9.8). */\nexport const useInvites = (): Invite[] => invitesChannel.use();\n\n// ---------------------------------------------------------------------------\n// The space keyring (REALTIME_MESSAGING_SPEC §6.1, R3-633f). Hand-written on\n// purpose, and NOT moved into the generated family: the generated wrappers\n// return the wire payload as typed, while this boundary must PROJECT — a host\n// reply that (wrongly) carried a private half (a `d` field) is never\n// propagated, because the type is the boundary and the projection is the\n// proof (§16's must-establish row: \"a member's space private key is never\n// returned to an app sandbox\"). Both calls are `spaces:user` (§6.5(d): public\n// halves only — no new capability).\n\n/** One member's published space key — the PUBLIC half only. The ECDH P-256\n * public JWK carries exactly `kty`/`crv`/`x`/`y`; there is no field for the\n * private scalar anywhere in this type (and none named `d`), so the shape\n * cannot carry one. */\nexport interface PublishedSpaceKey {\n /** The member the key belongs to. */\n uid: string;\n /** The key id (write-once; rotation appends a new kid). */\n kid: string;\n /** The public JWK (four fields, no `d`). */\n pub: { kty: string; crv: string; x: string; y: string };\n /** The algorithm label (see the host's SPACE_KEY_ALG_LABEL). */\n alg: string;\n /** Epoch milliseconds when the key was published. */\n addedAt: number;\n}\n\n/** Publish the caller's own space key (REALTIME_MESSAGING §6.1) — minted at join\n * time by the host already; this call is the explicit retry/self-heal an app can\n * offer. Idempotent: a member who has published resolves the existing kid with\n * `created: false`. The private half is sealed under the member's passkey-derived\n * KEK host-side and never crosses this boundary. Rejects with a typed refusal:\n * `cancelled` (the passkey prompt was dismissed), `unsupported` (the platform\n * cannot seal here), `forbidden` (not a member), `auth-required` when signed out. */\nexport const publishSpaceKey = async (spaceId: string): Promise<{ kid: string; created: boolean }> => {\n // `invoke`, not the local `request` helper: the wire-shape gate\n // (check-protocol-snapshot) extracts the catalog front door's call sites, and\n // a helper call is invisible to it — the published contract and this source\n // must agree byte-for-byte. Same envelope unwrap + coded refusal, with one\n // recorded difference: `request`'s throwOnRefusal coerces a NON-STRING refusal\n // code/message to 'unknown'/a fallback, while catalog.ts's invoke assigns\n // `res?.code ?? 'unknown'` unchecked (its pre-fold shape — protocolRefusal.ts's\n // census). The wire sends strings; the difference is unreachable today.\n const r = await invoke<{ ok: true; kid: string; created: boolean }>('spaces:publishSpaceKey', { spaceId });\n return { kid: r.kid, created: r.created };\n};\n\n/** The published public halves of a space's members (REALTIME_MESSAGING §6.1) —\n * readable by every member, refused `forbidden` for a non-member (the store read\n * is the membership gate). Members who have not published are simply ABSENT\n * (§6.2's fail-closed create reads that absence; the targeted probe is the\n * optional `uid` form, which answers `not-found` for an unpublished member).\n * The returned rows are PROJECTED to {@link PublishedSpaceKey}: a wire row\n * carrying anything more (e.g. a `d` field) is not propagated. */\nexport const listSpaceKeys = async (spaceId: string, uid?: string): Promise<PublishedSpaceKey[]> => {\n // One declared params type (never a conditional literal) so the wire-shape\n // gate fingerprints `uid` as `string | undefined` — the published snapshot's\n // recorded shape (sandbox-protocol 0.15.0). `invoke` here for the same reason\n // as publishSpaceKey above (the gate extracts the catalog front door's call\n // sites); the same invoke-vs-throwOnRefusal coercion note applies.\n const params: { spaceId: string; uid?: string } = { spaceId };\n if (uid !== undefined) params.uid = uid;\n const rows = await invoke<Array<Record<string, unknown>>>('spaces:listSpaceKeys', params);\n // Project, never coerce (the host store's own doctrine): the four public JWK\n // fields are copied verbatim and EVERYTHING else is dropped — a row carrying a\n // private half (`d`) does not propagate; a malformed row is the host's to\n // reject upstream (its project() refuses one), never this layer's to repair.\n return rows.map((row) => {\n const pub = row.pub as PublishedSpaceKey['pub'];\n return {\n uid: row.uid as string,\n kid: row.kid as string,\n pub: { kty: pub.kty, crv: pub.crv, x: pub.x, y: pub.y },\n alg: row.alg as string,\n addedAt: row.addedAt as number,\n };\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAyB;AACzB,6BAA+B;AAE/B,mBAAoC;AACpC,0BAA0D;AAC1D,yBAAkC;AAClC,yBAA+B;AAC/B,wBAA6B;AAc7B,oBAsBO;AAWP,sBAWO;AACP,6BAAwB;AACxB,qBAAuB;AAehB,MAAM,kBAAkB,UAAc,mCAAe,GAAG,gBAAgB;AA8H/E,MAAM,WAAW,CAAC,MAA4B,EAAE,MAAM,EAAE;AAExD,MAAM,uBAA4C,oBAAI,IAAuB;AAAA,EAC3E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAID,MAAM,sBAAs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