@immediately-run/sdk 0.87.1 → 0.89.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/catalog.cjs +2 -7
- package/dist/catalog.cjs.map +1 -1
- package/dist/catalog.js +2 -7
- package/dist/catalog.js.map +1 -1
- package/dist/llm.cjs +11 -2
- package/dist/llm.cjs.map +1 -1
- package/dist/llm.d.cts +5 -0
- package/dist/llm.d.ts +5 -0
- package/dist/llm.js +11 -2
- package/dist/llm.js.map +1 -1
- package/dist/protocolRefusal.cjs +1 -0
- package/dist/protocolRefusal.cjs.map +1 -1
- package/dist/protocolRefusal.d.cts +7 -5
- package/dist/protocolRefusal.d.ts +7 -5
- package/dist/protocolRefusal.js +1 -0
- package/dist/protocolRefusal.js.map +1 -1
- package/dist/providerIcons/NOTICE.md +37 -0
- package/dist/providerIcons/ProviderIcon.cjs +61 -0
- package/dist/providerIcons/ProviderIcon.cjs.map +1 -0
- package/dist/providerIcons/ProviderIcon.d.cts +13 -0
- package/dist/providerIcons/ProviderIcon.d.ts +13 -0
- package/dist/providerIcons/ProviderIcon.js +38 -0
- package/dist/providerIcons/ProviderIcon.js.map +1 -0
- package/dist/providerIcons/sprite.generated.cjs +138 -0
- package/dist/providerIcons/sprite.generated.cjs.map +1 -0
- package/dist/providerIcons/sprite.generated.d.cts +8 -0
- package/dist/providerIcons/sprite.generated.d.ts +8 -0
- package/dist/providerIcons/sprite.generated.js +114 -0
- package/dist/providerIcons/sprite.generated.js.map +1 -0
- package/dist/providerIcons.cjs +32 -0
- package/dist/providerIcons.cjs.map +1 -0
- package/dist/providerIcons.d.cts +3 -0
- package/dist/providerIcons.d.ts +3 -0
- package/dist/providerIcons.js +8 -0
- package/dist/providerIcons.js.map +1 -0
- 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 -1
package/dist/catalog.cjs
CHANGED
|
@@ -26,6 +26,7 @@ __export(catalog_exports, {
|
|
|
26
26
|
});
|
|
27
27
|
module.exports = __toCommonJS(catalog_exports);
|
|
28
28
|
var import_sandboxUtils = require("./sandboxUtils");
|
|
29
|
+
var import_protocolRefusal = require("./protocolRefusal");
|
|
29
30
|
var import_protocolStream = require("./protocolStream");
|
|
30
31
|
var import_pushChannel = require("./pushChannel");
|
|
31
32
|
var import_protocol = require("./generated/protocol");
|
|
@@ -37,13 +38,7 @@ const split = (name) => {
|
|
|
37
38
|
const invoke = async (name, params = {}) => {
|
|
38
39
|
const [scheme, method] = split(name);
|
|
39
40
|
const res = await (0, import_sandboxUtils.protocolRequest)(scheme, method, [params]);
|
|
40
|
-
|
|
41
|
-
const err = new Error(res?.message ?? `${name} failed`);
|
|
42
|
-
err.code = res?.code ?? "unknown";
|
|
43
|
-
const wait = res?.retryAfter;
|
|
44
|
-
if (Number.isFinite(wait)) err.retryAfter = wait;
|
|
45
|
-
throw err;
|
|
46
|
-
}
|
|
41
|
+
(0, import_protocolRefusal.throwOnRefusal)(res, `${name} failed`);
|
|
47
42
|
return res.data;
|
|
48
43
|
};
|
|
49
44
|
const streamTransport = {
|
package/dist/catalog.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/catalog.ts"],"sourcesContent":["// The method catalog (UI_AS_APPS_SPEC §5.5) — the app's own grant-filtered RPC\n// surface, and a generic way to call it. The host advertises exactly the methods\n// this app may invoke (MCP-tool-shaped); `invoke()` calls one by its catalog name.\n// Handing the catalog to an embedded agent as its tool list confines the agent to\n// the app's authority (agent sandboxing falls out of the capability model, §5.9).\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport type { StreamFrame, StreamTransport } from './protocolStream';\nimport { consumeStream } from './protocolStream';\nimport { createPushChannel } from './pushChannel';\nimport { API_CATALOG, REQUEST_API_CATALOG } from './generated/protocol';\n\n/** One advertised method, as the host generated it from its gate table. */\nexport interface ApiMethod {\n /** Catalog name, `protocol-` stripped — e.g. `spaces:invite`, `contribute:run`. */\n name: string;\n /** The capability this method requires (already held — it's in your catalog). */\n capability: string;\n /** True when the method STREAMS (use {@link invokeStream}) vs. single-reply. */\n stream?: boolean;\n /**\n * JSON Schema for the method's single object argument, when the host declares one.\n * Self-describes the call so a catalog-as-tools bridge (an embedded agent) can\n * advertise the real param shape — e.g. that `authoring:typecheck` takes a nested\n * `{ files: [{ path, content }] }` array — instead of a permissive \"any object\".\n * Absent for methods the host advertises without a schema.\n */\n paramsSchema?: Record<string, unknown>;\n}\n\n// `scheme:method` → ['scheme', 'method'] (the wire protocol is `protocol-scheme`).\nconst split = (name: string): [string, string] => {\n const i = name.indexOf(':');\n if (i <= 0) throw new Error(`invalid catalog method name: ${name}`);\n return [name.slice(0, i), name.slice(i + 1)];\n};\n\n/**\n * Call a catalog method by name — `invoke('spaces:invite', { spaceId, login, role })`.\n * A thin generic over the host protocol: the host validates params and gates the\n * call (an un-granted method → `forbidden`, even if you name it directly). For a\n * STREAMING method (`ApiMethod.stream`), use {@link invokeStream}.\n */\nexport const invoke = async <T = unknown>(name: string, params: Record<string, unknown> = {}): Promise<T> => {\n const [scheme, method] = split(name);\n // The host replies with an `{ ok, data } | { ok:false, code }` envelope; unwrap\n // it and THROW on refusal (a `.code` like `forbidden` for an off-catalog call)\n // so callers — and any agent driving `invoke` — see the gate's verdict.\n const res = (await protocolRequest(scheme, method, [params])) as\n | { ok: true; data: unknown }\n | { ok: false; code?: string; message?: string; retryAfter?: unknown }\n | undefined;\n
|
|
1
|
+
{"version":3,"sources":["../src/catalog.ts"],"sourcesContent":["// The method catalog (UI_AS_APPS_SPEC §5.5) — the app's own grant-filtered RPC\n// surface, and a generic way to call it. The host advertises exactly the methods\n// this app may invoke (MCP-tool-shaped); `invoke()` calls one by its catalog name.\n// Handing the catalog to an embedded agent as its tool list confines the agent to\n// the app's authority (agent sandboxing falls out of the capability model, §5.9).\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport type { StreamFrame, StreamTransport } from './protocolStream';\nimport { consumeStream } from './protocolStream';\nimport { createPushChannel } from './pushChannel';\nimport { API_CATALOG, REQUEST_API_CATALOG } from './generated/protocol';\n\n/** One advertised method, as the host generated it from its gate table. */\nexport interface ApiMethod {\n /** Catalog name, `protocol-` stripped — e.g. `spaces:invite`, `contribute:run`. */\n name: string;\n /** The capability this method requires (already held — it's in your catalog). */\n capability: string;\n /** True when the method STREAMS (use {@link invokeStream}) vs. single-reply. */\n stream?: boolean;\n /**\n * JSON Schema for the method's single object argument, when the host declares one.\n * Self-describes the call so a catalog-as-tools bridge (an embedded agent) can\n * advertise the real param shape — e.g. that `authoring:typecheck` takes a nested\n * `{ files: [{ path, content }] }` array — instead of a permissive \"any object\".\n * Absent for methods the host advertises without a schema.\n */\n paramsSchema?: Record<string, unknown>;\n}\n\n// `scheme:method` → ['scheme', 'method'] (the wire protocol is `protocol-scheme`).\nconst split = (name: string): [string, string] => {\n const i = name.indexOf(':');\n if (i <= 0) throw new Error(`invalid catalog method name: ${name}`);\n return [name.slice(0, i), name.slice(i + 1)];\n};\n\n/**\n * Call a catalog method by name — `invoke('spaces:invite', { spaceId, login, role })`.\n * A thin generic over the host protocol: the host validates params and gates the\n * call (an un-granted method → `forbidden`, even if you name it directly). For a\n * STREAMING method (`ApiMethod.stream`), use {@link invokeStream}.\n */\nexport const invoke = async <T = unknown>(name: string, params: Record<string, unknown> = {}): Promise<T> => {\n const [scheme, method] = split(name);\n // The host replies with an `{ ok, data } | { ok:false, code }` envelope; unwrap\n // it and THROW on refusal (a `.code` like `forbidden` for an off-catalog call)\n // so callers — and any agent driving `invoke` — see the gate's verdict.\n const res = (await protocolRequest(scheme, method, [params])) as\n | { ok: true; data: unknown }\n | { ok: false; code?: string; message?: string; retryAfter?: unknown }\n | undefined;\n // R3-1089: folded onto the shared helper (the last inline unwrap; it stayed out\n // until the helper learned retryAfter — R3-954's rate-limit wait rides it now).\n throwOnRefusal(res, `${name} failed`);\n return res.data as T;\n};\n\n// Stream transport over the resolver (SDK_PACKAGING_SPEC §4) — sendMessage /\n// addListener route through `transport()` (injected bundler messageBus or the §4\n// global), never `bundler.messageBus` directly.\nconst streamTransport: StreamTransport = {\n send: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n subscribe: (type, handler) => addListener(type, (msg) => handler(msg as { msgId?: number; stream?: StreamFrame })),\n // Early-cancel: route a `{type, msgId, cancel:true}` frame back to the host so it\n // aborts the in-flight generation (and, for `llm:chat`, stops billing) — §3.3.\n cancel: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n};\n\n/** Call a STREAMING catalog method by name, yielding its events. Pass `signal` to\n * abort mid-stream: the host stops generating and (for `llm:chat`) stops billing. */\nexport function invokeStream<T = unknown, R = unknown>(\n name: string,\n params: Record<string, unknown> = {},\n signal?: AbortSignal,\n): AsyncGenerator<T, R, void> {\n const [scheme, method] = split(name);\n return consumeStream<T, R>(streamTransport, `protocol-${scheme}`, method, [params], undefined, signal);\n}\n\n// The catalog list is read over the transport (§4): the host pushes `api-catalog`\n// and answers `request-api-catalog` with this app's grant-filtered methods (wire\n// format: site-main channelBridge.ts).\nconst channel = createPushChannel<ApiMethod[]>({\n pushType: API_CATALOG,\n requestType: REQUEST_API_CATALOG,\n initial: [],\n parse: (msg) => (Array.isArray(msg.methods) ? (msg.methods as ApiMethod[]) : undefined),\n});\n\n/** The methods this app may call (grant-filtered, §5.5). Poll for a one-off read;\n * use {@link onCatalogChange} / {@link useCatalog} to react. */\nexport const getCatalog = (): ApiMethod[] => channel.get();\n\n/** Subscribe to catalog changes (e.g. a grant added/revoked). Invoked immediately\n * with the current catalog, then on every change. Returns an unsubscribe fn. */\nexport const onCatalogChange = (listener: (catalog: ApiMethod[]) => void): (() => void) => channel.onChange(listener);\n\n/** React hook returning this app's method catalog, re-rendering on change. Hand\n * it to an embedded agent as its tool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AAI,OAAO,IAAK,IAAI,UAA0B;AAC/E,CAAC;AAIM,MAAM,aAAa,MAAmB,QAAQ,IAAI;AAIlD,MAAM,kBAAkB,CAAC,aAA2D,QAAQ,SAAS,QAAQ;AAK7G,MAAM,aAAa,MAAmB,QAAQ,IAAI;","names":[]}
|
package/dist/catalog.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import "./chunk-VHAA22YE.js";
|
|
2
2
|
import { protocolRequest, sendMessage, addListener } from "./sandboxUtils.js";
|
|
3
|
+
import { throwOnRefusal } from "./protocolRefusal.js";
|
|
3
4
|
import { consumeStream } from "./protocolStream.js";
|
|
4
5
|
import { createPushChannel } from "./pushChannel.js";
|
|
5
6
|
import { API_CATALOG, REQUEST_API_CATALOG } from "./generated/protocol.js";
|
|
@@ -11,13 +12,7 @@ const split = (name) => {
|
|
|
11
12
|
const invoke = async (name, params = {}) => {
|
|
12
13
|
const [scheme, method] = split(name);
|
|
13
14
|
const res = await protocolRequest(scheme, method, [params]);
|
|
14
|
-
|
|
15
|
-
const err = new Error(res?.message ?? `${name} failed`);
|
|
16
|
-
err.code = res?.code ?? "unknown";
|
|
17
|
-
const wait = res?.retryAfter;
|
|
18
|
-
if (Number.isFinite(wait)) err.retryAfter = wait;
|
|
19
|
-
throw err;
|
|
20
|
-
}
|
|
15
|
+
throwOnRefusal(res, `${name} failed`);
|
|
21
16
|
return res.data;
|
|
22
17
|
};
|
|
23
18
|
const streamTransport = {
|
package/dist/catalog.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/catalog.ts"],"sourcesContent":["// The method catalog (UI_AS_APPS_SPEC §5.5) — the app's own grant-filtered RPC\n// surface, and a generic way to call it. The host advertises exactly the methods\n// this app may invoke (MCP-tool-shaped); `invoke()` calls one by its catalog name.\n// Handing the catalog to an embedded agent as its tool list confines the agent to\n// the app's authority (agent sandboxing falls out of the capability model, §5.9).\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport type { StreamFrame, StreamTransport } from './protocolStream';\nimport { consumeStream } from './protocolStream';\nimport { createPushChannel } from './pushChannel';\nimport { API_CATALOG, REQUEST_API_CATALOG } from './generated/protocol';\n\n/** One advertised method, as the host generated it from its gate table. */\nexport interface ApiMethod {\n /** Catalog name, `protocol-` stripped — e.g. `spaces:invite`, `contribute:run`. */\n name: string;\n /** The capability this method requires (already held — it's in your catalog). */\n capability: string;\n /** True when the method STREAMS (use {@link invokeStream}) vs. single-reply. */\n stream?: boolean;\n /**\n * JSON Schema for the method's single object argument, when the host declares one.\n * Self-describes the call so a catalog-as-tools bridge (an embedded agent) can\n * advertise the real param shape — e.g. that `authoring:typecheck` takes a nested\n * `{ files: [{ path, content }] }` array — instead of a permissive \"any object\".\n * Absent for methods the host advertises without a schema.\n */\n paramsSchema?: Record<string, unknown>;\n}\n\n// `scheme:method` → ['scheme', 'method'] (the wire protocol is `protocol-scheme`).\nconst split = (name: string): [string, string] => {\n const i = name.indexOf(':');\n if (i <= 0) throw new Error(`invalid catalog method name: ${name}`);\n return [name.slice(0, i), name.slice(i + 1)];\n};\n\n/**\n * Call a catalog method by name — `invoke('spaces:invite', { spaceId, login, role })`.\n * A thin generic over the host protocol: the host validates params and gates the\n * call (an un-granted method → `forbidden`, even if you name it directly). For a\n * STREAMING method (`ApiMethod.stream`), use {@link invokeStream}.\n */\nexport const invoke = async <T = unknown>(name: string, params: Record<string, unknown> = {}): Promise<T> => {\n const [scheme, method] = split(name);\n // The host replies with an `{ ok, data } | { ok:false, code }` envelope; unwrap\n // it and THROW on refusal (a `.code` like `forbidden` for an off-catalog call)\n // so callers — and any agent driving `invoke` — see the gate's verdict.\n const res = (await protocolRequest(scheme, method, [params])) as\n | { ok: true; data: unknown }\n | { ok: false; code?: string; message?: string; retryAfter?: unknown }\n | undefined;\n
|
|
1
|
+
{"version":3,"sources":["../src/catalog.ts"],"sourcesContent":["// The method catalog (UI_AS_APPS_SPEC §5.5) — the app's own grant-filtered RPC\n// surface, and a generic way to call it. The host advertises exactly the methods\n// this app may invoke (MCP-tool-shaped); `invoke()` calls one by its catalog name.\n// Handing the catalog to an embedded agent as its tool list confines the agent to\n// the app's authority (agent sandboxing falls out of the capability model, §5.9).\nimport { protocolRequest, sendMessage, addListener } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport type { StreamFrame, StreamTransport } from './protocolStream';\nimport { consumeStream } from './protocolStream';\nimport { createPushChannel } from './pushChannel';\nimport { API_CATALOG, REQUEST_API_CATALOG } from './generated/protocol';\n\n/** One advertised method, as the host generated it from its gate table. */\nexport interface ApiMethod {\n /** Catalog name, `protocol-` stripped — e.g. `spaces:invite`, `contribute:run`. */\n name: string;\n /** The capability this method requires (already held — it's in your catalog). */\n capability: string;\n /** True when the method STREAMS (use {@link invokeStream}) vs. single-reply. */\n stream?: boolean;\n /**\n * JSON Schema for the method's single object argument, when the host declares one.\n * Self-describes the call so a catalog-as-tools bridge (an embedded agent) can\n * advertise the real param shape — e.g. that `authoring:typecheck` takes a nested\n * `{ files: [{ path, content }] }` array — instead of a permissive \"any object\".\n * Absent for methods the host advertises without a schema.\n */\n paramsSchema?: Record<string, unknown>;\n}\n\n// `scheme:method` → ['scheme', 'method'] (the wire protocol is `protocol-scheme`).\nconst split = (name: string): [string, string] => {\n const i = name.indexOf(':');\n if (i <= 0) throw new Error(`invalid catalog method name: ${name}`);\n return [name.slice(0, i), name.slice(i + 1)];\n};\n\n/**\n * Call a catalog method by name — `invoke('spaces:invite', { spaceId, login, role })`.\n * A thin generic over the host protocol: the host validates params and gates the\n * call (an un-granted method → `forbidden`, even if you name it directly). For a\n * STREAMING method (`ApiMethod.stream`), use {@link invokeStream}.\n */\nexport const invoke = async <T = unknown>(name: string, params: Record<string, unknown> = {}): Promise<T> => {\n const [scheme, method] = split(name);\n // The host replies with an `{ ok, data } | { ok:false, code }` envelope; unwrap\n // it and THROW on refusal (a `.code` like `forbidden` for an off-catalog call)\n // so callers — and any agent driving `invoke` — see the gate's verdict.\n const res = (await protocolRequest(scheme, method, [params])) as\n | { ok: true; data: unknown }\n | { ok: false; code?: string; message?: string; retryAfter?: unknown }\n | undefined;\n // R3-1089: folded onto the shared helper (the last inline unwrap; it stayed out\n // until the helper learned retryAfter — R3-954's rate-limit wait rides it now).\n throwOnRefusal(res, `${name} failed`);\n return res.data as T;\n};\n\n// Stream transport over the resolver (SDK_PACKAGING_SPEC §4) — sendMessage /\n// addListener route through `transport()` (injected bundler messageBus or the §4\n// global), never `bundler.messageBus` directly.\nconst streamTransport: StreamTransport = {\n send: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n subscribe: (type, handler) => addListener(type, (msg) => handler(msg as { msgId?: number; stream?: StreamFrame })),\n // Early-cancel: route a `{type, msgId, cancel:true}` frame back to the host so it\n // aborts the in-flight generation (and, for `llm:chat`, stops billing) — §3.3.\n cancel: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n};\n\n/** Call a STREAMING catalog method by name, yielding its events. Pass `signal` to\n * abort mid-stream: the host stops generating and (for `llm:chat`) stops billing. */\nexport function invokeStream<T = unknown, R = unknown>(\n name: string,\n params: Record<string, unknown> = {},\n signal?: AbortSignal,\n): AsyncGenerator<T, R, void> {\n const [scheme, method] = split(name);\n return consumeStream<T, R>(streamTransport, `protocol-${scheme}`, method, [params], undefined, signal);\n}\n\n// The catalog list is read over the transport (§4): the host pushes `api-catalog`\n// and answers `request-api-catalog` with this app's grant-filtered methods (wire\n// format: site-main channelBridge.ts).\nconst channel = createPushChannel<ApiMethod[]>({\n pushType: API_CATALOG,\n requestType: REQUEST_API_CATALOG,\n initial: [],\n parse: (msg) => (Array.isArray(msg.methods) ? (msg.methods as ApiMethod[]) : undefined),\n});\n\n/** The methods this app may call (grant-filtered, §5.5). Poll for a one-off read;\n * use {@link onCatalogChange} / {@link useCatalog} to react. */\nexport const getCatalog = (): ApiMethod[] => channel.get();\n\n/** Subscribe to catalog changes (e.g. a grant added/revoked). Invoked immediately\n * with the current catalog, then on every change. Returns an unsubscribe fn. */\nexport const onCatalogChange = (listener: (catalog: ApiMethod[]) => void): (() => void) => channel.onChange(listener);\n\n/** React hook returning this app's method catalog, re-rendering on change. Hand\n * it to an embedded agent as its tool list to confine the agent to the app's\n * authority (§5.9). */\nexport const useCatalog = (): ApiMethod[] => channel.use();\n"],"mappings":";AAKA,SAAS,iBAAiB,aAAa,mBAAmB;AAC1D,SAAS,sBAAsB;AAE/B,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAClC,SAAS,aAAa,2BAA2B;AAqBjD,MAAM,QAAQ,CAAC,SAAmC;AAChD,QAAM,IAAI,KAAK,QAAQ,GAAG;AAC1B,MAAI,KAAK,EAAG,OAAM,IAAI,MAAM,gCAAgC,IAAI,EAAE;AAClE,SAAO,CAAC,KAAK,MAAM,GAAG,CAAC,GAAG,KAAK,MAAM,IAAI,CAAC,CAAC;AAC7C;AAQO,MAAM,SAAS,OAAoB,MAAc,SAAkC,CAAC,MAAkB;AAC3G,QAAM,CAAC,QAAQ,MAAM,IAAI,MAAM,IAAI;AAInC,QAAM,MAAO,MAAM,gBAAgB,QAAQ,QAAQ,CAAC,MAAM,CAAC;AAM3D,iBAAe,KAAK,GAAG,IAAI,SAAS;AACpC,SAAO,IAAI;AACb;AAKA,MAAM,kBAAmC;AAAA,EACvC,MAAM,CAAC,QAAQ,YAAY,IAAI,MAAM,GAAyC;AAAA,EAC9E,WAAW,CAAC,MAAM,YAAY,YAAY,MAAM,CAAC,QAAQ,QAAQ,GAA+C,CAAC;AAAA;AAAA;AAAA,EAGjH,QAAQ,CAAC,QAAQ,YAAY,IAAI,MAAM,GAAyC;AAClF;AAIO,SAAS,aACd,MACA,SAAkC,CAAC,GACnC,QAC4B;AAC5B,QAAM,CAAC,QAAQ,MAAM,IAAI,MAAM,IAAI;AACnC,SAAO,cAAoB,iBAAiB,YAAY,MAAM,IAAI,QAAQ,CAAC,MAAM,GAAG,QAAW,MAAM;AACvG;AAKA,MAAM,UAAU,kBAA+B;AAAA,EAC7C,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS,CAAC;AAAA,EACV,OAAO,CAAC,QAAS,MAAM,QAAQ,IAAI,OAAO,IAAK,IAAI,UAA0B;AAC/E,CAAC;AAIM,MAAM,aAAa,MAAmB,QAAQ,IAAI;AAIlD,MAAM,kBAAkB,CAAC,aAA2D,QAAQ,SAAS,QAAQ;AAK7G,MAAM,aAAa,MAAmB,QAAQ,IAAI;","names":[]}
|
package/dist/llm.cjs
CHANGED
|
@@ -42,6 +42,14 @@ const usableModels = (raw) => {
|
|
|
42
42
|
const { fast, smart } = raw;
|
|
43
43
|
return typeof fast === "string" && fast && typeof smart === "string" && smart ? { fast, smart } : void 0;
|
|
44
44
|
};
|
|
45
|
+
const withReasoningClosed = (f) => ({ ...f, reasoning: f.reasoning === true });
|
|
46
|
+
const usableFeatures = (raw) => {
|
|
47
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
48
|
+
const f = raw;
|
|
49
|
+
if (typeof f.vision !== "boolean" || typeof f.tools !== "boolean" || typeof f.jsonMode !== "boolean" || typeof f.maxContextTokens !== "number")
|
|
50
|
+
return void 0;
|
|
51
|
+
return withReasoningClosed(f);
|
|
52
|
+
};
|
|
45
53
|
const usableConnectedProviders = (raw) => {
|
|
46
54
|
if (!Array.isArray(raw)) return void 0;
|
|
47
55
|
const out = [];
|
|
@@ -51,7 +59,8 @@ const usableConnectedProviders = (raw) => {
|
|
|
51
59
|
if (typeof providerId !== "string" || !providerId) continue;
|
|
52
60
|
if (typeof displayName !== "string" || !displayName) continue;
|
|
53
61
|
const cleanModels = Array.isArray(models) ? models.filter((m) => typeof m === "string" && !!m) : [];
|
|
54
|
-
|
|
62
|
+
const features = usableFeatures(item.features);
|
|
63
|
+
out.push({ providerId, displayName, models: cleanModels, ...features ? { features } : {} });
|
|
55
64
|
}
|
|
56
65
|
return out.length > 0 ? out : void 0;
|
|
57
66
|
};
|
|
@@ -71,7 +80,7 @@ function normalizeProviderInfo(provider) {
|
|
|
71
80
|
const connectedProviders = usableConnectedProviders(rawConnected);
|
|
72
81
|
return {
|
|
73
82
|
...rest,
|
|
74
|
-
features:
|
|
83
|
+
features: withReasoningClosed(wire),
|
|
75
84
|
...displayName ? { displayName } : {},
|
|
76
85
|
...executor ? { executor } : {},
|
|
77
86
|
...models ? { models } : {},
|
package/dist/llm.cjs.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 };\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}\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/** 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 out.push({ providerId, displayName, models: cleanModels });\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: { ...wire, reasoning: wire.reasoning === true } as ChatFeatures,\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":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,qBAA6B;AAC7B,yBAAkC;AAClC,sBAAmD;AA0I5C,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,aAAO,6BAAoC,YAAY,QAA8C,MAAM;AAC7G;AA4JA,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;AAKA,MAAM,2BAA2B,CAAC,QAAmD;AACnF,MAAI,CAAC,MAAM,QAAQ,GAAG,EAAG,QAAO;AA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AAS;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"]}
|
|
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 };\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":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,qBAA6B;AAC7B,yBAAkC;AAClC,sBAAmD;AA0I5C,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,aAAO,6BAAoC,YAAY,QAA8C,MAAM;AAC7G;AAiKA,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;AAM3C,MAAM,iBAAiB,CAAC,Q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|
|
|
172
172
|
* chosen. A closed list here would re-introduce the ids-rot problem, so `model` is passed
|
|
173
173
|
* through to the adapter exactly as the Settings field is; this list is suggestions. */
|
|
174
174
|
models: string[];
|
|
175
|
+
/** R3-1074: THIS provider's adapter features, so a run on a chosen provider sizes itself
|
|
176
|
+
* by that provider's context window and vision rather than the default provider's (or the
|
|
177
|
+
* conservative nothing). Absent on a host predating the field — keep your conservative
|
|
178
|
+
* answer then. Optional on the wire, so an older host stays valid. */
|
|
179
|
+
features?: ChatFeatures;
|
|
175
180
|
}
|
|
176
181
|
/** Info about the provider the host resolved for this app. `null` when no provider
|
|
177
182
|
* is bound (SP-7: prompt the user to add a key before calling {@link chat}). */
|
package/dist/llm.d.ts
CHANGED
|
@@ -172,6 +172,11 @@ interface ChatProviderChoice {
|
|
|
172
172
|
* chosen. A closed list here would re-introduce the ids-rot problem, so `model` is passed
|
|
173
173
|
* through to the adapter exactly as the Settings field is; this list is suggestions. */
|
|
174
174
|
models: string[];
|
|
175
|
+
/** R3-1074: THIS provider's adapter features, so a run on a chosen provider sizes itself
|
|
176
|
+
* by that provider's context window and vision rather than the default provider's (or the
|
|
177
|
+
* conservative nothing). Absent on a host predating the field — keep your conservative
|
|
178
|
+
* answer then. Optional on the wire, so an older host stays valid. */
|
|
179
|
+
features?: ChatFeatures;
|
|
175
180
|
}
|
|
176
181
|
/** Info about the provider the host resolved for this app. `null` when no provider
|
|
177
182
|
* is bound (SP-7: prompt the user to add a key before calling {@link chat}). */
|
package/dist/llm.js
CHANGED
|
@@ -12,6 +12,14 @@ const usableModels = (raw) => {
|
|
|
12
12
|
const { fast, smart } = raw;
|
|
13
13
|
return typeof fast === "string" && fast && typeof smart === "string" && smart ? { fast, smart } : void 0;
|
|
14
14
|
};
|
|
15
|
+
const withReasoningClosed = (f) => ({ ...f, reasoning: f.reasoning === true });
|
|
16
|
+
const usableFeatures = (raw) => {
|
|
17
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
18
|
+
const f = raw;
|
|
19
|
+
if (typeof f.vision !== "boolean" || typeof f.tools !== "boolean" || typeof f.jsonMode !== "boolean" || typeof f.maxContextTokens !== "number")
|
|
20
|
+
return void 0;
|
|
21
|
+
return withReasoningClosed(f);
|
|
22
|
+
};
|
|
15
23
|
const usableConnectedProviders = (raw) => {
|
|
16
24
|
if (!Array.isArray(raw)) return void 0;
|
|
17
25
|
const out = [];
|
|
@@ -21,7 +29,8 @@ const usableConnectedProviders = (raw) => {
|
|
|
21
29
|
if (typeof providerId !== "string" || !providerId) continue;
|
|
22
30
|
if (typeof displayName !== "string" || !displayName) continue;
|
|
23
31
|
const cleanModels = Array.isArray(models) ? models.filter((m) => typeof m === "string" && !!m) : [];
|
|
24
|
-
|
|
32
|
+
const features = usableFeatures(item.features);
|
|
33
|
+
out.push({ providerId, displayName, models: cleanModels, ...features ? { features } : {} });
|
|
25
34
|
}
|
|
26
35
|
return out.length > 0 ? out : void 0;
|
|
27
36
|
};
|
|
@@ -41,7 +50,7 @@ function normalizeProviderInfo(provider) {
|
|
|
41
50
|
const connectedProviders = usableConnectedProviders(rawConnected);
|
|
42
51
|
return {
|
|
43
52
|
...rest,
|
|
44
|
-
features:
|
|
53
|
+
features: withReasoningClosed(wire),
|
|
45
54
|
...displayName ? { displayName } : {},
|
|
46
55
|
...executor ? { executor } : {},
|
|
47
56
|
...models ? { models } : {},
|
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 };\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}\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/** 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 out.push({ providerId, displayName, models: cleanModels });\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: { ...wire, reasoning: wire.reasoning === true } as ChatFeatures,\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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kB,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//\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 };\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;AA0I5C,SAAS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GA,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/protocolRefusal.cjs
CHANGED
|
@@ -26,6 +26,7 @@ function throwOnRefusal(res, fallbackMessage) {
|
|
|
26
26
|
if (r && r.ok === true) return;
|
|
27
27
|
const err = new Error(typeof r?.message === "string" ? r.message : fallbackMessage);
|
|
28
28
|
err.code = typeof r?.code === "string" ? r.code : "unknown";
|
|
29
|
+
if (Number.isFinite(r?.retryAfter)) err.retryAfter = r.retryAfter;
|
|
29
30
|
throw err;
|
|
30
31
|
}
|
|
31
32
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. After R3-816 folded the pure copies, the count is:\n//\n// **twenty CALL SITES across fifteen FILES** — `grep -n 'throwOnRefusal(' src/*.ts`, minus\n// the declaration here, minus `*.test.*`, and minus this census's own mention of the\n// pattern (the recipe's literal matches it):\n//\n// dnd.ts · editor.ts · feed.ts · ipc.ts (×2) · mounts.ts (×3) · netFetch.ts ·\n// openBundle.ts · openExternal.ts · openRepository.ts · recents.ts · secrets.ts ·\n// spacesMode.ts · tasks.ts · theme.ts (×3) · vcs.ts\n//\n// `catalog.ts` is the one named NOT-folded site: its refusal copy is no longer pure —\n// R3-954 gave `invoke`'s error a `retryAfter` field this helper does not build, so the\n// fold's premise (a byte-identical copy) stopped holding for it between this branch's\n// review and its landing. `recents` and `tasks` folded as prescribed.\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// R3-816 folded the pure copies of the shape `ipc.ts` had until R3-780 — `recents` and\n// `tasks` here (two of the three the item named; the third, `catalog`, is the exemption\n// above) — and the fold changed nothing observable. R3-817 (merged as #192, 0.74.3) then\n// folded the `res && 'code' in res` family — `openExternal`, `openRepository`, `feed`,\n// `netFetch` and `theme` (×3) — fixing the `TypeError: Cannot use 'in' operator` a string\n// reply used to throw there. That form is gone from main; nothing remains to fold in\n// either family.\n//\n// Still deliberately NOT folded:\n//\n// · `catalog.ts` — the exemption above (R3-954's `retryAfter`, a field this helper\n// does not build);\n// · `launch.ts` — it folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL TWENTY SITES\n// ---------------------------------------------------------------------------\n//\n// Measured on this tree (2026-10-07, the take-over's re-run — the recipe, not the\n// history: apply the injection in a scratch copy and run the suite):\n//\n// - guard weakened to `r.ok === false` (a REFUSAL stops throwing and a success starts\n// throwing; an absent reply still throws through the `r &&` short-circuit):\n// **120 of 1002** tests redden, across **17 suites**;\n// - the FULL no-op neuter (the helper's body replaced by a bare return): **90 tests**\n// redden across **17 failed suites** — the sharper probe, and the one the\n// absent-reply cases redden under (they stay green under the guard-weakening,\n// which is the reason they exist).\n//\n// (An earlier take-over draft recorded 86 across 42 — a broken probe whose import\n// errors failed suites before their tests ran; the 90/17 pair is the stable re-run,\n// twice.)\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and fifteen near-duplicate\n// malformed-reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Twenty sites call this; **eighteen**\n * had an inline copy it replaced (`spacesMode.ts` was written against the helper in R3-708\n * and `openBundle.ts` against it in R3-808, so neither replaced anything; `catalog.ts`'s\n * copy returned inline in R3-954 — its error carries a `retryAfter` this helper does not\n * build, the one named not-folded site). They tested for PRESENCE, in **three** shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **seven** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as\n * Code) ?? 'unknown'` — `openExternal` and `openRepository` (folded in R3-708) and\n * `feed`, `netFetch` and `theme` (×3) (folded in R3-817, #192);\n * - **four** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc` (×2), `recents`, `tasks` (folded in R3-816).\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply.\n *\n * ONE revision of this paragraph got that backwards, and this is the fourth attempt to\n * describe it accurately. The original text was right FOR ITS REFERENT — it named\n * `'code' in res` as a shape replaced, without saying which sites, and at the time the\n * sites it referred to were R3-708's four, two of which used that form. R3-780 then folded\n * five DIFFERENT files and inherited the sentence unchanged, so it became false in place\n * without anyone editing it. That silent shift is the likeliest reason the next revision\n * \"corrected\" it to say NO replaced site used it — which is false the other way:\n * `openExternal` and `openRepository` did.\n *\n * The mechanism is worth more than the correction, because it is repeatable. `'code' in\n * res` is GONE from `main` — R3-817 (merged as #192, 0.74.3) folded the five sites that\n * carried it (`feed`, `netFetch`, `theme` ×3), beside R3-708's two (`openExternal`,\n * `openRepository`). A grep of `main` today finds the form only in this file's comments\n * and in test files. The tree that shows the form at the sites is the one before the\n * folds, `d4b07cc1^`. Read that before rewriting this paragraph again.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoLO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. After R3-816 folded the pure copies, and R3-1089 folded `catalog.ts` (the helper\n// learned `retryAfter` for it — the fold's premise holds again), the count is:\n//\n// **twenty-one CALL SITES across sixteen FILES** — `grep -n 'throwOnRefusal(' src/*.ts`,\n// minus the declaration here, minus `*.test.*`, and minus this census's own mention of\n// the pattern (the recipe's literal matches it):\n//\n// catalog.ts · dnd.ts · editor.ts · feed.ts · ipc.ts (×2) · mounts.ts (×3) · netFetch.ts ·\n// openBundle.ts · openExternal.ts · openRepository.ts · recents.ts · secrets.ts ·\n// spacesMode.ts · tasks.ts · theme.ts (×3) · vcs.ts\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// R3-816 folded the pure copies of the shape `ipc.ts` had until R3-780 — `recents` and\n// `tasks` here (two of the three the item named; the third, `catalog`, is the exemption\n// above) — and the fold changed nothing observable. R3-817 (merged as #192, 0.74.3) then\n// folded the `res && 'code' in res` family — `openExternal`, `openRepository`, `feed`,\n// `netFetch` and `theme` (×3) — fixing the `TypeError: Cannot use 'in' operator` a string\n// reply used to throw there. That form is gone from main; nothing remains to fold in\n// either family.\n//\n// Still deliberately NOT folded:\n//\n// · `launch.ts` — it folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// (`catalog.ts` folded in R3-1089 — the helper now builds R3-954's `retryAfter`, so the\n// exemption's premise is gone.)\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL TWENTY SITES\n// ---------------------------------------------------------------------------\n//\n// Measured on this tree (2026-10-07, the take-over's re-run — the recipe, not the\n// history: apply the injection in a scratch copy and run the suite):\n//\n// - guard weakened to `r.ok === false` (a REFUSAL stops throwing and a success starts\n// throwing; an absent reply still throws through the `r &&` short-circuit):\n// **120 of 1002** tests redden, across **17 suites**;\n// - the FULL no-op neuter (the helper's body replaced by a bare return): **90 tests**\n// redden across **17 failed suites** — the sharper probe, and the one the\n// absent-reply cases redden under (they stay green under the guard-weakening,\n// which is the reason they exist).\n//\n// (An earlier take-over draft recorded 86 across 42 — a broken probe whose import\n// errors failed suites before their tests ran; the 90/17 pair is the stable re-run,\n// twice.)\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and fifteen near-duplicate\n// malformed-reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n /** A provider rate-limit's wait in seconds, when the refusal carried one (R3-954). */\n retryAfter?: number;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Twenty-three sites call this;\n * **eighteen** had an inline copy it replaced (`spacesMode.ts` was written against the\n * helper in R3-708, `openBundle.ts` against it in R3-808, and `catalog.ts` folded in\n * R3-1089 once the helper learned `retryAfter` — the one site R3-954's copy had kept\n * out). They tested for PRESENCE, in **three** shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **seven** used the `in` operator: `((res && 'code' in res ? res.code : undefined) as\n * Code) ?? 'unknown'` — `openExternal` and `openRepository` (folded in R3-708) and\n * `feed`, `netFetch` and `theme` (×3) (folded in R3-817, #192);\n * - **four** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc` (×2), `recents`, `tasks` (folded in R3-816).\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply.\n *\n * ONE revision of this paragraph got that backwards, and this is the fourth attempt to\n * describe it accurately. The original text was right FOR ITS REFERENT — it named\n * `'code' in res` as a shape replaced, without saying which sites, and at the time the\n * sites it referred to were R3-708's four, two of which used that form. R3-780 then folded\n * five DIFFERENT files and inherited the sentence unchanged, so it became false in place\n * without anyone editing it. That silent shift is the likeliest reason the next revision\n * \"corrected\" it to say NO replaced site used it — which is false the other way:\n * `openExternal` and `openRepository` did.\n *\n * The mechanism is worth more than the correction, because it is repeatable. `'code' in\n * res` is GONE from `main` — R3-817 (merged as #192, 0.74.3) folded the five sites that\n * carried it (`feed`, `netFetch`, `theme` ×3), beside R3-708's two (`openExternal`,\n * `openRepository`). A grep of `main` today finds the form only in this file's comments\n * and in test files. The tree that shows the form at the sites is the one before the\n * folds, `d4b07cc1^`. Read that before rewriting this paragraph again.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown; retryAfter?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n // R3-1089: R3-954's retryAfter (a provider rate-limit's wait in seconds) rides\n // the refusal here too, so catalog.ts's invoke() folds like every other site.\n // Number.isFinite, not typeof: NaN and Infinity are numbers the\n // structured-clone transport carries intact.\n if (Number.isFinite(r?.retryAfter)) err.retryAfter = (r as { retryAfter: number }).retryAfter;\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAmLO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAKlD,MAAI,OAAO,SAAS,GAAG,UAAU,EAAG,KAAI,aAAc,EAA6B;AACnF,QAAM;AACR;","names":[]}
|