@immediately-run/sdk 0.30.0 → 0.32.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/boot.cjs +5 -1
- package/dist/boot.cjs.map +1 -1
- package/dist/boot.js +5 -1
- package/dist/boot.js.map +1 -1
- package/dist/catalog.cjs +6 -3
- package/dist/catalog.cjs.map +1 -1
- package/dist/catalog.d.cts +3 -2
- package/dist/catalog.d.ts +3 -2
- package/dist/catalog.js +6 -3
- package/dist/catalog.js.map +1 -1
- package/dist/components/Link.cjs +25 -0
- package/dist/components/Link.cjs.map +1 -1
- package/dist/components/Link.d.cts +7 -1
- package/dist/components/Link.d.ts +7 -1
- package/dist/components/Link.js +24 -0
- package/dist/components/Link.js.map +1 -1
- package/dist/components/ScrollAfterNavigation.cjs +66 -0
- package/dist/components/ScrollAfterNavigation.cjs.map +1 -0
- package/dist/components/ScrollAfterNavigation.d.cts +24 -0
- package/dist/components/ScrollAfterNavigation.d.ts +24 -0
- package/dist/components/ScrollAfterNavigation.js +41 -0
- package/dist/components/ScrollAfterNavigation.js.map +1 -0
- package/dist/components/WikiLink.cjs +10 -2
- package/dist/components/WikiLink.cjs.map +1 -1
- package/dist/components/WikiLink.d.cts +11 -3
- package/dist/components/WikiLink.d.ts +11 -3
- package/dist/components/WikiLink.js +10 -2
- package/dist/components/WikiLink.js.map +1 -1
- package/dist/llm.cjs +6 -1
- package/dist/llm.cjs.map +1 -1
- package/dist/llm.d.cts +6 -0
- package/dist/llm.d.ts +6 -0
- package/dist/llm.js +6 -1
- package/dist/llm.js.map +1 -1
- package/dist/protocolStream.cjs +20 -4
- package/dist/protocolStream.cjs.map +1 -1
- package/dist/protocolStream.d.cts +15 -2
- package/dist/protocolStream.d.ts +15 -2
- package/dist/protocolStream.js +20 -4
- package/dist/protocolStream.js.map +1 -1
- package/dist/scrollToId.cjs +46 -0
- package/dist/scrollToId.cjs.map +1 -0
- package/dist/scrollToId.d.cts +12 -0
- package/dist/scrollToId.d.ts +12 -0
- package/dist/scrollToId.js +22 -0
- package/dist/scrollToId.js.map +1 -0
- package/dist/urlUtils.cjs +9 -1
- package/dist/urlUtils.cjs.map +1 -1
- package/dist/urlUtils.d.cts +10 -1
- package/dist/urlUtils.d.ts +10 -1
- package/dist/urlUtils.js +8 -1
- package/dist/urlUtils.js.map +1 -1
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { use, useEffect } from "react";
|
|
2
|
+
import { TinkerableContext } from "../TinkerableContext";
|
|
3
|
+
import { scrollToId } from "../scrollToId";
|
|
4
|
+
const useScrollAfterNavigation = () => {
|
|
5
|
+
const { navigationState } = use(TinkerableContext);
|
|
6
|
+
const frag = navigationState.hash;
|
|
7
|
+
const navKey = `${navigationState.sandboxPath}\0${frag}`;
|
|
8
|
+
useEffect(() => {
|
|
9
|
+
if (!frag || typeof document === "undefined") return;
|
|
10
|
+
if (scrollToId(frag)) return;
|
|
11
|
+
let done = false;
|
|
12
|
+
const finish = () => {
|
|
13
|
+
done = true;
|
|
14
|
+
observer.disconnect();
|
|
15
|
+
timers.forEach(clearTimeout);
|
|
16
|
+
clearTimeout(finalTimer);
|
|
17
|
+
};
|
|
18
|
+
const tryScroll = () => {
|
|
19
|
+
if (!done && scrollToId(frag)) finish();
|
|
20
|
+
};
|
|
21
|
+
const observer = new MutationObserver(tryScroll);
|
|
22
|
+
const timers = [120, 300, 600].map((ms) => setTimeout(tryScroll, ms));
|
|
23
|
+
const finalTimer = setTimeout(() => {
|
|
24
|
+
if (!done) {
|
|
25
|
+
finish();
|
|
26
|
+
window.scrollTo?.(0, 0);
|
|
27
|
+
}
|
|
28
|
+
}, 900);
|
|
29
|
+
observer.observe(document.body, { childList: true, subtree: true });
|
|
30
|
+
return finish;
|
|
31
|
+
}, [navKey, frag]);
|
|
32
|
+
};
|
|
33
|
+
const ScrollAfterNavigation = () => {
|
|
34
|
+
useScrollAfterNavigation();
|
|
35
|
+
return null;
|
|
36
|
+
};
|
|
37
|
+
export {
|
|
38
|
+
ScrollAfterNavigation,
|
|
39
|
+
useScrollAfterNavigation
|
|
40
|
+
};
|
|
41
|
+
//# sourceMappingURL=ScrollAfterNavigation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/components/ScrollAfterNavigation.tsx"],"sourcesContent":["import { use, useEffect } from 'react';\n\nimport { TinkerableContext } from '../TinkerableContext';\nimport { scrollToId } from '../scrollToId';\n\n/**\n * Deep-linking Capability C (MARKDOWN_SYNTAX_SPEC §13.5): after an in-app navigation\n * whose URL carries a `#fragment`, scroll the target section into view.\n *\n * In-app navigation swaps the rendered file **asynchronously** — the destination\n * file's tree mounts *after* the route change — so the element the fragment\n * addresses does not exist at click time. This effect records the pending fragment\n * and retries until the target appears: an immediate attempt, a `MutationObserver`\n * over late-mounting subtrees, and a few timed retries (the `[120, 300, 600]ms`\n * cadence `grove/src/components/Toc.tsx` proves for late-mounting prose). If the\n * target never appears within the window it degrades to top-of-page — a missing\n * fragment is never a hard failure.\n *\n * It re-runs when the destination page **or** the fragment changes, so a fresh click\n * on the same target re-scrolls. Mounted once inside the navigation provider (see\n * `boot`'s `TinkerableApp`) so it is uniform for **every** MDX app — the SDK router\n * owns cross-page anchor navigation, not any one consumer (Grove).\n */\nexport const useScrollAfterNavigation = (): void => {\n const { navigationState } = use(TinkerableContext);\n const frag = navigationState.hash;\n // Re-run when the destination page OR the fragment changes.\n const navKey = `${navigationState.sandboxPath}\u0000${frag}`;\n\n useEffect(() => {\n if (!frag || typeof document === 'undefined') return;\n // Fast path: the target is already in the DOM (same page, or the tree mounted\n // synchronously) — scroll now, no observer/timer churn.\n if (scrollToId(frag)) return;\n\n let done = false;\n const finish = () => {\n done = true;\n observer.disconnect();\n timers.forEach(clearTimeout);\n clearTimeout(finalTimer);\n };\n const tryScroll = () => {\n if (!done && scrollToId(frag)) finish();\n };\n\n const observer = new MutationObserver(tryScroll);\n const timers = [120, 300, 600].map((ms) => setTimeout(tryScroll, ms));\n // Final fallback once the retry window closes: if the fragment never resolved,\n // scroll to the top rather than strand the reader at the previous page's offset.\n const finalTimer = setTimeout(() => {\n if (!done) {\n finish();\n window.scrollTo?.(0, 0);\n }\n }, 900);\n\n observer.observe(document.body, { childList: true, subtree: true });\n return finish;\n }, [navKey, frag]);\n};\n\n/** Null-rendering mount point for {@link useScrollAfterNavigation} inside the\n * navigation provider. */\nexport const ScrollAfterNavigation = (): null => {\n useScrollAfterNavigation();\n return null;\n};\n"],"mappings":"AAAA,SAAS,KAAK,iBAAiB;AAE/B,SAAS,yBAAyB;AAClC,SAAS,kBAAkB;AAoBpB,MAAM,2BAA2B,MAAY;AAClD,QAAM,EAAE,gBAAgB,IAAI,IAAI,iBAAiB;AACjD,QAAM,OAAO,gBAAgB;AAE7B,QAAM,SAAS,GAAG,gBAAgB,WAAW,KAAI,IAAI;AAErD,YAAU,MAAM;AACd,QAAI,CAAC,QAAQ,OAAO,aAAa,YAAa;AAG9C,QAAI,WAAW,IAAI,EAAG;AAEtB,QAAI,OAAO;AACX,UAAM,SAAS,MAAM;AACnB,aAAO;AACP,eAAS,WAAW;AACpB,aAAO,QAAQ,YAAY;AAC3B,mBAAa,UAAU;AAAA,IACzB;AACA,UAAM,YAAY,MAAM;AACtB,UAAI,CAAC,QAAQ,WAAW,IAAI,EAAG,QAAO;AAAA,IACxC;AAEA,UAAM,WAAW,IAAI,iBAAiB,SAAS;AAC/C,UAAM,SAAS,CAAC,KAAK,KAAK,GAAG,EAAE,IAAI,CAAC,OAAO,WAAW,WAAW,EAAE,CAAC;AAGpE,UAAM,aAAa,WAAW,MAAM;AAClC,UAAI,CAAC,MAAM;AACT,eAAO;AACP,eAAO,WAAW,GAAG,CAAC;AAAA,MACxB;AAAA,IACF,GAAG,GAAG;AAEN,aAAS,QAAQ,SAAS,MAAM,EAAE,WAAW,MAAM,SAAS,KAAK,CAAC;AAClE,WAAO;AAAA,EACT,GAAG,CAAC,QAAQ,IAAI,CAAC;AACnB;AAIO,MAAM,wBAAwB,MAAY;AAC/C,2BAAyB;AACzB,SAAO;AACT;","names":[]}
|
|
@@ -26,6 +26,7 @@ var import_react = require("react");
|
|
|
26
26
|
var import_Link = require("./Link");
|
|
27
27
|
var import_Include = require("./Include");
|
|
28
28
|
var import_TinkerableContext = require("../TinkerableContext");
|
|
29
|
+
var import_urlUtils = require("../urlUtils");
|
|
29
30
|
const labelFromTarget = (target) => {
|
|
30
31
|
const base = target.split(/[\\/]/).pop() ?? target;
|
|
31
32
|
return base.replace(/\.mdx?$/i, "") || target;
|
|
@@ -55,15 +56,22 @@ const WikiLink = ({
|
|
|
55
56
|
const renderContext = (0, import_react.use)(import_Include.RenderExportedComponentContext);
|
|
56
57
|
const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;
|
|
57
58
|
const rawTarget = target ?? "";
|
|
58
|
-
const
|
|
59
|
+
const [pathPart, frag] = (0, import_urlUtils.splitHash)(rawTarget);
|
|
60
|
+
const text = children ?? label ?? (rawTarget ? labelFromTarget(pathPart || frag || rawTarget) : "");
|
|
59
61
|
if (!rawTarget) {
|
|
60
62
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ir-wikilink", ...rest, children: text });
|
|
61
63
|
}
|
|
62
|
-
|
|
64
|
+
if (pathPart === "" && frag) {
|
|
65
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Link.Link, { href: `#${frag}`, className: "ir-wikilink", "data-state": "anchor", ...rest, children: text });
|
|
66
|
+
}
|
|
67
|
+
const resolved = resolveWikiTarget(pathPart, currentFile);
|
|
63
68
|
const files = filesMetadata ?? {};
|
|
64
69
|
const loaded = Object.keys(files).length > 0;
|
|
65
70
|
if (resolved !== void 0) {
|
|
66
71
|
if (currentFile && resolved === currentFile) {
|
|
72
|
+
if (frag) {
|
|
73
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Link.Link, { href: `#${frag}`, className: "ir-wikilink", "data-state": "anchor", ...rest, children: text });
|
|
74
|
+
}
|
|
67
75
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "ir-wikilink ir-wikilink-self", "data-state": "self", ...rest, children: text });
|
|
68
76
|
}
|
|
69
77
|
const exists = !loaded || resolved in files;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/WikiLink.tsx"],"sourcesContent":["import { ReactNode, use } from 'react';\nimport { Link } from './Link';\nimport { RenderExportedComponentContext } from './Include';\nimport { TinkerableContext } from '../TinkerableContext';\n\n/** Derive a human label from a target path: basename without the extension. */\nconst labelFromTarget = (target: string): string => {\n const base = target.split(/[\\\\/]/).pop() ?? target;\n return base.replace(/\\.mdx?$/i, '') || target;\n};\n\n/** Collapse `.`/`..`/empty segments into a clean absolute path. */\nconst normalize = (path: string): string => {\n const out: string[] = [];\n for (const seg of path.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') out.pop();\n else out.push(seg);\n }\n return '/' + out.join('/');\n};\n\n/**\n * Resolve a wiki-link target to an absolute sandbox path, or `undefined` when it\n * cannot be resolved (a relative target with no known current file). An\n * **absolute** target (`/…`) is taken verbatim; a **relative** target resolves\n * against the current file's directory. Pure path arithmetic (MARKDOWN_SYNTAX_SPEC\n * §13.2) — it never touches the filesystem or any other file.\n */\nconst resolveWikiTarget = (target: string, currentFile?: string): string | undefined => {\n if (target.startsWith('/')) return normalize(target);\n if (!currentFile) return undefined;\n const dir = currentFile.slice(0, currentFile.lastIndexOf('/'));\n return normalize(`${dir}/${target}`);\n};\n\n/**\n * Default MDX `WikiLink` component — the render target for the `[[target]]` /\n * `[[label|target]]` wiki-link syntax. The transpiler remark plugin (R3-153)\n * compiles that syntax to `<WikiLink target=\"…\" label=\"…\">`, carrying the raw\n * target/label verbatim; **resolution lives here** (MARKDOWN_SYNTAX_SPEC §13.2).\n *\n * Registered in {@link DEFAULT_MDX_COMPONENTS} so wiki-links render even in a\n * plain-markdown repo (§11.2 phantom defaults). Targets are **paths only** —\n * relative (resolved against the current file's directory) or absolute — with\n * **no implicit search path** (§13.3, a deliberate departure from Obsidian).\n *\n * The **current file** — the one the link is *authored in* — is read from the\n * ambient `<Include>` render context. Every MDX file renders through `<Include>`\n * (`FileRouter` renders even the top-level file that way), and Include publishes\n * the rendered module's `EvaluationContext` to its subtree via\n * {@link RenderExportedComponentContext}; the nearest one's\n * `evaluation.module.filepath` is this file's own `/app/…` path. Because that\n * context nests with each `<Include>`, a relative target inside an included\n * fragment resolves against the **fragment**, not the top-level page in the URL.\n *\n * The resolved path is checked for **existence** against the live metadata store\n * (keyed by absolute `/app/…` paths) for the
|
|
1
|
+
{"version":3,"sources":["../../src/components/WikiLink.tsx"],"sourcesContent":["import { ReactNode, use } from 'react';\nimport { Link } from './Link';\nimport { RenderExportedComponentContext } from './Include';\nimport { TinkerableContext } from '../TinkerableContext';\nimport { splitHash } from '../urlUtils';\n\n/** Derive a human label from a target path: basename without the extension. */\nconst labelFromTarget = (target: string): string => {\n const base = target.split(/[\\\\/]/).pop() ?? target;\n return base.replace(/\\.mdx?$/i, '') || target;\n};\n\n/** Collapse `.`/`..`/empty segments into a clean absolute path. */\nconst normalize = (path: string): string => {\n const out: string[] = [];\n for (const seg of path.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') out.pop();\n else out.push(seg);\n }\n return '/' + out.join('/');\n};\n\n/**\n * Resolve a wiki-link target to an absolute sandbox path, or `undefined` when it\n * cannot be resolved (a relative target with no known current file). An\n * **absolute** target (`/…`) is taken verbatim; a **relative** target resolves\n * against the current file's directory. Pure path arithmetic (MARKDOWN_SYNTAX_SPEC\n * §13.2) — it never touches the filesystem or any other file.\n */\nconst resolveWikiTarget = (target: string, currentFile?: string): string | undefined => {\n if (target.startsWith('/')) return normalize(target);\n if (!currentFile) return undefined;\n const dir = currentFile.slice(0, currentFile.lastIndexOf('/'));\n return normalize(`${dir}/${target}`);\n};\n\n/**\n * Default MDX `WikiLink` component — the render target for the `[[target]]` /\n * `[[label|target]]` wiki-link syntax. The transpiler remark plugin (R3-153)\n * compiles that syntax to `<WikiLink target=\"…\" label=\"…\">`, carrying the raw\n * target/label verbatim; **resolution lives here** (MARKDOWN_SYNTAX_SPEC §13.2).\n *\n * Registered in {@link DEFAULT_MDX_COMPONENTS} so wiki-links render even in a\n * plain-markdown repo (§11.2 phantom defaults). Targets are **paths only** —\n * relative (resolved against the current file's directory) or absolute — with\n * **no implicit search path** (§13.3, a deliberate departure from Obsidian).\n *\n * The **current file** — the one the link is *authored in* — is read from the\n * ambient `<Include>` render context. Every MDX file renders through `<Include>`\n * (`FileRouter` renders even the top-level file that way), and Include publishes\n * the rendered module's `EvaluationContext` to its subtree via\n * {@link RenderExportedComponentContext}; the nearest one's\n * `evaluation.module.filepath` is this file's own `/app/…` path. Because that\n * context nests with each `<Include>`, a relative target inside an included\n * fragment resolves against the **fragment**, not the top-level page in the URL.\n *\n * A target may carry a `#fragment` (`[[FILE.mdx#sec-8-9]]`, `[[#sec-8-9]]`): the\n * fragment is **split off** ({@link splitHash}, §13.5) and existence is resolved on\n * the **fragment-stripped path**, so a section citation to an existing file resolves\n * (not \"broken\"). The fragment then rides to navigation, where the scroll-after-nav\n * effect ({@link useScrollAfterNavigation}) lands the reader on the section.\n *\n * The resolved path is checked for **existence** against the live metadata store\n * (keyed by absolute `/app/…` paths) for the states (§13.3, §13.5):\n * - **anchor** — a fragment with no path (`[[#sec-8-9]]`), or a fragment whose path is\n * the current file: a same-page {@link Link} that scrolls in place, no route change.\n * - **self** — the resolved path is the current file (no fragment): inert text, no link.\n * - **broken** — no file at the resolved path (and the store has loaded): rendered\n * as marked text, **not** a throw.\n * - **resolved** — routed through {@link Link} (in-app navigation for a same-app\n * href, a plain `<a>` otherwise), carrying any `#fragment`.\n *\n * The check is **optimistic until the metadata store loads** (an empty store never\n * flashes \"broken\"), and a relative target with no ambient render context (MDX\n * rendered outside `<Include>`) routes optimistically. Such an app overrides this\n * component (§11) for precise resolution.\n */\nexport const WikiLink = ({\n target,\n label,\n children,\n ...rest\n}: {\n target?: string;\n label?: ReactNode;\n children?: ReactNode;\n} & Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>): ReactNode => {\n const { filesMetadata } = use(TinkerableContext);\n const renderContext = use(RenderExportedComponentContext);\n const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;\n\n const rawTarget = target ?? '';\n const [pathPart, frag] = splitHash(rawTarget);\n const text = children ?? label ?? (rawTarget ? labelFromTarget(pathPart || frag || rawTarget) : '');\n\n // Defensive: the kernel never emits an empty target, but a hand-written\n // `<WikiLink>` might. Render inert text rather than a link to nowhere.\n if (!rawTarget) {\n return (\n <span className=\"ir-wikilink\" {...rest}>\n {text}\n </span>\n );\n }\n\n // Same-page anchor: a fragment with no path (`[[#sec-8-9]]`). Scroll within the\n // current file — no route change (§13.5). <Link> intercepts a bare `#`-href.\n if (pathPart === '' && frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n\n const resolved = resolveWikiTarget(pathPart, currentFile);\n const files = filesMetadata ?? {};\n const loaded = Object.keys(files).length > 0;\n\n // `resolved === undefined` ⇒ a relative target with no known current file: route\n // it optimistically (can't check existence or self-ness generically).\n if (resolved !== undefined) {\n if (currentFile && resolved === currentFile) {\n // The target IS this file. With a fragment it is a same-page anchor to another\n // of this file's sections; without one it is an inert self-reference.\n if (frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n return (\n <span className=\"ir-wikilink ir-wikilink-self\" data-state=\"self\" {...rest}>\n {text}\n </span>\n );\n }\n // Existence is checked on the FRAGMENT-STRIPPED path (optimistic until loaded).\n const exists = !loaded || resolved in files;\n if (!exists) {\n return (\n <span\n className=\"ir-wikilink ir-wikilink-broken\"\n data-state=\"broken\"\n title={`No file at ${resolved}`}\n {...rest}\n >\n {text}\n </span>\n );\n }\n }\n // Resolved cross-file target: route through <Link>, carrying the raw target so its\n // `#fragment` rides through navigation to the scroll-after-nav effect (§13.5).\n return (\n <Link href={rawTarget} className=\"ir-wikilink\" data-state=\"resolved\" {...rest}>\n {text}\n </Link>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAoGM;AApGN,mBAA+B;AAC/B,kBAAqB;AACrB,qBAA+C;AAC/C,+BAAkC;AAClC,sBAA0B;AAG1B,MAAM,kBAAkB,CAAC,WAA2B;AAClD,QAAM,OAAO,OAAO,MAAM,OAAO,EAAE,IAAI,KAAK;AAC5C,SAAO,KAAK,QAAQ,YAAY,EAAE,KAAK;AACzC;AAGA,MAAM,YAAY,CAAC,SAAyB;AAC1C,QAAM,MAAgB,CAAC;AACvB,aAAW,OAAO,KAAK,MAAM,GAAG,GAAG;AACjC,QAAI,QAAQ,MAAM,QAAQ,IAAK;AAC/B,QAAI,QAAQ,KAAM,KAAI,IAAI;AAAA,QACrB,KAAI,KAAK,GAAG;AAAA,EACnB;AACA,SAAO,MAAM,IAAI,KAAK,GAAG;AAC3B;AASA,MAAM,oBAAoB,CAAC,QAAgB,gBAA6C;AACtF,MAAI,OAAO,WAAW,GAAG,EAAG,QAAO,UAAU,MAAM;AACnD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,MAAM,YAAY,MAAM,GAAG,YAAY,YAAY,GAAG,CAAC;AAC7D,SAAO,UAAU,GAAG,GAAG,IAAI,MAAM,EAAE;AACrC;AA2CO,MAAM,WAAW,CAAC;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,MAI+E;AAC7E,QAAM,EAAE,cAAc,QAAI,kBAAI,0CAAiB;AAC/C,QAAM,oBAAgB,kBAAI,6CAA8B;AACxD,QAAM,cAAc,eAAe,mBAAmB,YAAY,QAAQ;AAE1E,QAAM,YAAY,UAAU;AAC5B,QAAM,CAAC,UAAU,IAAI,QAAI,2BAAU,SAAS;AAC5C,QAAM,OAAO,YAAY,UAAU,YAAY,gBAAgB,YAAY,QAAQ,SAAS,IAAI;AAIhG,MAAI,CAAC,WAAW;AACd,WACE,4CAAC,UAAK,WAAU,eAAe,GAAG,MAC/B,gBACH;AAAA,EAEJ;AAIA,MAAI,aAAa,MAAM,MAAM;AAC3B,WACE,4CAAC,oBAAK,MAAM,IAAI,IAAI,IAAI,WAAU,eAAc,cAAW,UAAU,GAAG,MACrE,gBACH;AAAA,EAEJ;AAEA,QAAM,WAAW,kBAAkB,UAAU,WAAW;AACxD,QAAM,QAAQ,iBAAiB,CAAC;AAChC,QAAM,SAAS,OAAO,KAAK,KAAK,EAAE,SAAS;AAI3C,MAAI,aAAa,QAAW;AAC1B,QAAI,eAAe,aAAa,aAAa;AAG3C,UAAI,MAAM;AACR,eACE,4CAAC,oBAAK,MAAM,IAAI,IAAI,IAAI,WAAU,eAAc,cAAW,UAAU,GAAG,MACrE,gBACH;AAAA,MAEJ;AACA,aACE,4CAAC,UAAK,WAAU,gCAA+B,cAAW,QAAQ,GAAG,MAClE,gBACH;AAAA,IAEJ;AAEA,UAAM,SAAS,CAAC,UAAU,YAAY;AACtC,QAAI,CAAC,QAAQ;AACX,aACE;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,OAAO,cAAc,QAAQ;AAAA,UAC5B,GAAG;AAAA,UAEH;AAAA;AAAA,MACH;AAAA,IAEJ;AAAA,EACF;AAGA,SACE,4CAAC,oBAAK,MAAM,WAAW,WAAU,eAAc,cAAW,YAAY,GAAG,MACtE,gBACH;AAEJ;","names":[]}
|
|
@@ -20,13 +20,21 @@ import { ReactNode } from 'react';
|
|
|
20
20
|
* context nests with each `<Include>`, a relative target inside an included
|
|
21
21
|
* fragment resolves against the **fragment**, not the top-level page in the URL.
|
|
22
22
|
*
|
|
23
|
+
* A target may carry a `#fragment` (`[[FILE.mdx#sec-8-9]]`, `[[#sec-8-9]]`): the
|
|
24
|
+
* fragment is **split off** ({@link splitHash}, §13.5) and existence is resolved on
|
|
25
|
+
* the **fragment-stripped path**, so a section citation to an existing file resolves
|
|
26
|
+
* (not "broken"). The fragment then rides to navigation, where the scroll-after-nav
|
|
27
|
+
* effect ({@link useScrollAfterNavigation}) lands the reader on the section.
|
|
28
|
+
*
|
|
23
29
|
* The resolved path is checked for **existence** against the live metadata store
|
|
24
|
-
* (keyed by absolute `/app/…` paths) for the
|
|
25
|
-
* - **
|
|
30
|
+
* (keyed by absolute `/app/…` paths) for the states (§13.3, §13.5):
|
|
31
|
+
* - **anchor** — a fragment with no path (`[[#sec-8-9]]`), or a fragment whose path is
|
|
32
|
+
* the current file: a same-page {@link Link} that scrolls in place, no route change.
|
|
33
|
+
* - **self** — the resolved path is the current file (no fragment): inert text, no link.
|
|
26
34
|
* - **broken** — no file at the resolved path (and the store has loaded): rendered
|
|
27
35
|
* as marked text, **not** a throw.
|
|
28
36
|
* - **resolved** — routed through {@link Link} (in-app navigation for a same-app
|
|
29
|
-
* href, a plain `<a>` otherwise)
|
|
37
|
+
* href, a plain `<a>` otherwise), carrying any `#fragment`.
|
|
30
38
|
*
|
|
31
39
|
* The check is **optimistic until the metadata store loads** (an empty store never
|
|
32
40
|
* flashes "broken"), and a relative target with no ambient render context (MDX
|
|
@@ -20,13 +20,21 @@ import { ReactNode } from 'react';
|
|
|
20
20
|
* context nests with each `<Include>`, a relative target inside an included
|
|
21
21
|
* fragment resolves against the **fragment**, not the top-level page in the URL.
|
|
22
22
|
*
|
|
23
|
+
* A target may carry a `#fragment` (`[[FILE.mdx#sec-8-9]]`, `[[#sec-8-9]]`): the
|
|
24
|
+
* fragment is **split off** ({@link splitHash}, §13.5) and existence is resolved on
|
|
25
|
+
* the **fragment-stripped path**, so a section citation to an existing file resolves
|
|
26
|
+
* (not "broken"). The fragment then rides to navigation, where the scroll-after-nav
|
|
27
|
+
* effect ({@link useScrollAfterNavigation}) lands the reader on the section.
|
|
28
|
+
*
|
|
23
29
|
* The resolved path is checked for **existence** against the live metadata store
|
|
24
|
-
* (keyed by absolute `/app/…` paths) for the
|
|
25
|
-
* - **
|
|
30
|
+
* (keyed by absolute `/app/…` paths) for the states (§13.3, §13.5):
|
|
31
|
+
* - **anchor** — a fragment with no path (`[[#sec-8-9]]`), or a fragment whose path is
|
|
32
|
+
* the current file: a same-page {@link Link} that scrolls in place, no route change.
|
|
33
|
+
* - **self** — the resolved path is the current file (no fragment): inert text, no link.
|
|
26
34
|
* - **broken** — no file at the resolved path (and the store has loaded): rendered
|
|
27
35
|
* as marked text, **not** a throw.
|
|
28
36
|
* - **resolved** — routed through {@link Link} (in-app navigation for a same-app
|
|
29
|
-
* href, a plain `<a>` otherwise)
|
|
37
|
+
* href, a plain `<a>` otherwise), carrying any `#fragment`.
|
|
30
38
|
*
|
|
31
39
|
* The check is **optimistic until the metadata store loads** (an empty store never
|
|
32
40
|
* flashes "broken"), and a relative target with no ambient render context (MDX
|
|
@@ -3,6 +3,7 @@ import { use } from "react";
|
|
|
3
3
|
import { Link } from "./Link";
|
|
4
4
|
import { RenderExportedComponentContext } from "./Include";
|
|
5
5
|
import { TinkerableContext } from "../TinkerableContext";
|
|
6
|
+
import { splitHash } from "../urlUtils";
|
|
6
7
|
const labelFromTarget = (target) => {
|
|
7
8
|
const base = target.split(/[\\/]/).pop() ?? target;
|
|
8
9
|
return base.replace(/\.mdx?$/i, "") || target;
|
|
@@ -32,15 +33,22 @@ const WikiLink = ({
|
|
|
32
33
|
const renderContext = use(RenderExportedComponentContext);
|
|
33
34
|
const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;
|
|
34
35
|
const rawTarget = target ?? "";
|
|
35
|
-
const
|
|
36
|
+
const [pathPart, frag] = splitHash(rawTarget);
|
|
37
|
+
const text = children ?? label ?? (rawTarget ? labelFromTarget(pathPart || frag || rawTarget) : "");
|
|
36
38
|
if (!rawTarget) {
|
|
37
39
|
return /* @__PURE__ */ jsx("span", { className: "ir-wikilink", ...rest, children: text });
|
|
38
40
|
}
|
|
39
|
-
|
|
41
|
+
if (pathPart === "" && frag) {
|
|
42
|
+
return /* @__PURE__ */ jsx(Link, { href: `#${frag}`, className: "ir-wikilink", "data-state": "anchor", ...rest, children: text });
|
|
43
|
+
}
|
|
44
|
+
const resolved = resolveWikiTarget(pathPart, currentFile);
|
|
40
45
|
const files = filesMetadata ?? {};
|
|
41
46
|
const loaded = Object.keys(files).length > 0;
|
|
42
47
|
if (resolved !== void 0) {
|
|
43
48
|
if (currentFile && resolved === currentFile) {
|
|
49
|
+
if (frag) {
|
|
50
|
+
return /* @__PURE__ */ jsx(Link, { href: `#${frag}`, className: "ir-wikilink", "data-state": "anchor", ...rest, children: text });
|
|
51
|
+
}
|
|
44
52
|
return /* @__PURE__ */ jsx("span", { className: "ir-wikilink ir-wikilink-self", "data-state": "self", ...rest, children: text });
|
|
45
53
|
}
|
|
46
54
|
const exists = !loaded || resolved in files;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/WikiLink.tsx"],"sourcesContent":["import { ReactNode, use } from 'react';\nimport { Link } from './Link';\nimport { RenderExportedComponentContext } from './Include';\nimport { TinkerableContext } from '../TinkerableContext';\n\n/** Derive a human label from a target path: basename without the extension. */\nconst labelFromTarget = (target: string): string => {\n const base = target.split(/[\\\\/]/).pop() ?? target;\n return base.replace(/\\.mdx?$/i, '') || target;\n};\n\n/** Collapse `.`/`..`/empty segments into a clean absolute path. */\nconst normalize = (path: string): string => {\n const out: string[] = [];\n for (const seg of path.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') out.pop();\n else out.push(seg);\n }\n return '/' + out.join('/');\n};\n\n/**\n * Resolve a wiki-link target to an absolute sandbox path, or `undefined` when it\n * cannot be resolved (a relative target with no known current file). An\n * **absolute** target (`/…`) is taken verbatim; a **relative** target resolves\n * against the current file's directory. Pure path arithmetic (MARKDOWN_SYNTAX_SPEC\n * §13.2) — it never touches the filesystem or any other file.\n */\nconst resolveWikiTarget = (target: string, currentFile?: string): string | undefined => {\n if (target.startsWith('/')) return normalize(target);\n if (!currentFile) return undefined;\n const dir = currentFile.slice(0, currentFile.lastIndexOf('/'));\n return normalize(`${dir}/${target}`);\n};\n\n/**\n * Default MDX `WikiLink` component — the render target for the `[[target]]` /\n * `[[label|target]]` wiki-link syntax. The transpiler remark plugin (R3-153)\n * compiles that syntax to `<WikiLink target=\"…\" label=\"…\">`, carrying the raw\n * target/label verbatim; **resolution lives here** (MARKDOWN_SYNTAX_SPEC §13.2).\n *\n * Registered in {@link DEFAULT_MDX_COMPONENTS} so wiki-links render even in a\n * plain-markdown repo (§11.2 phantom defaults). Targets are **paths only** —\n * relative (resolved against the current file's directory) or absolute — with\n * **no implicit search path** (§13.3, a deliberate departure from Obsidian).\n *\n * The **current file** — the one the link is *authored in* — is read from the\n * ambient `<Include>` render context. Every MDX file renders through `<Include>`\n * (`FileRouter` renders even the top-level file that way), and Include publishes\n * the rendered module's `EvaluationContext` to its subtree via\n * {@link RenderExportedComponentContext}; the nearest one's\n * `evaluation.module.filepath` is this file's own `/app/…` path. Because that\n * context nests with each `<Include>`, a relative target inside an included\n * fragment resolves against the **fragment**, not the top-level page in the URL.\n *\n * The resolved path is checked for **existence** against the live metadata store\n * (keyed by absolute `/app/…` paths) for the
|
|
1
|
+
{"version":3,"sources":["../../src/components/WikiLink.tsx"],"sourcesContent":["import { ReactNode, use } from 'react';\nimport { Link } from './Link';\nimport { RenderExportedComponentContext } from './Include';\nimport { TinkerableContext } from '../TinkerableContext';\nimport { splitHash } from '../urlUtils';\n\n/** Derive a human label from a target path: basename without the extension. */\nconst labelFromTarget = (target: string): string => {\n const base = target.split(/[\\\\/]/).pop() ?? target;\n return base.replace(/\\.mdx?$/i, '') || target;\n};\n\n/** Collapse `.`/`..`/empty segments into a clean absolute path. */\nconst normalize = (path: string): string => {\n const out: string[] = [];\n for (const seg of path.split('/')) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') out.pop();\n else out.push(seg);\n }\n return '/' + out.join('/');\n};\n\n/**\n * Resolve a wiki-link target to an absolute sandbox path, or `undefined` when it\n * cannot be resolved (a relative target with no known current file). An\n * **absolute** target (`/…`) is taken verbatim; a **relative** target resolves\n * against the current file's directory. Pure path arithmetic (MARKDOWN_SYNTAX_SPEC\n * §13.2) — it never touches the filesystem or any other file.\n */\nconst resolveWikiTarget = (target: string, currentFile?: string): string | undefined => {\n if (target.startsWith('/')) return normalize(target);\n if (!currentFile) return undefined;\n const dir = currentFile.slice(0, currentFile.lastIndexOf('/'));\n return normalize(`${dir}/${target}`);\n};\n\n/**\n * Default MDX `WikiLink` component — the render target for the `[[target]]` /\n * `[[label|target]]` wiki-link syntax. The transpiler remark plugin (R3-153)\n * compiles that syntax to `<WikiLink target=\"…\" label=\"…\">`, carrying the raw\n * target/label verbatim; **resolution lives here** (MARKDOWN_SYNTAX_SPEC §13.2).\n *\n * Registered in {@link DEFAULT_MDX_COMPONENTS} so wiki-links render even in a\n * plain-markdown repo (§11.2 phantom defaults). Targets are **paths only** —\n * relative (resolved against the current file's directory) or absolute — with\n * **no implicit search path** (§13.3, a deliberate departure from Obsidian).\n *\n * The **current file** — the one the link is *authored in* — is read from the\n * ambient `<Include>` render context. Every MDX file renders through `<Include>`\n * (`FileRouter` renders even the top-level file that way), and Include publishes\n * the rendered module's `EvaluationContext` to its subtree via\n * {@link RenderExportedComponentContext}; the nearest one's\n * `evaluation.module.filepath` is this file's own `/app/…` path. Because that\n * context nests with each `<Include>`, a relative target inside an included\n * fragment resolves against the **fragment**, not the top-level page in the URL.\n *\n * A target may carry a `#fragment` (`[[FILE.mdx#sec-8-9]]`, `[[#sec-8-9]]`): the\n * fragment is **split off** ({@link splitHash}, §13.5) and existence is resolved on\n * the **fragment-stripped path**, so a section citation to an existing file resolves\n * (not \"broken\"). The fragment then rides to navigation, where the scroll-after-nav\n * effect ({@link useScrollAfterNavigation}) lands the reader on the section.\n *\n * The resolved path is checked for **existence** against the live metadata store\n * (keyed by absolute `/app/…` paths) for the states (§13.3, §13.5):\n * - **anchor** — a fragment with no path (`[[#sec-8-9]]`), or a fragment whose path is\n * the current file: a same-page {@link Link} that scrolls in place, no route change.\n * - **self** — the resolved path is the current file (no fragment): inert text, no link.\n * - **broken** — no file at the resolved path (and the store has loaded): rendered\n * as marked text, **not** a throw.\n * - **resolved** — routed through {@link Link} (in-app navigation for a same-app\n * href, a plain `<a>` otherwise), carrying any `#fragment`.\n *\n * The check is **optimistic until the metadata store loads** (an empty store never\n * flashes \"broken\"), and a relative target with no ambient render context (MDX\n * rendered outside `<Include>`) routes optimistically. Such an app overrides this\n * component (§11) for precise resolution.\n */\nexport const WikiLink = ({\n target,\n label,\n children,\n ...rest\n}: {\n target?: string;\n label?: ReactNode;\n children?: ReactNode;\n} & Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>): ReactNode => {\n const { filesMetadata } = use(TinkerableContext);\n const renderContext = use(RenderExportedComponentContext);\n const currentFile = renderContext?.evaluationContext?.evaluation?.module?.filepath;\n\n const rawTarget = target ?? '';\n const [pathPart, frag] = splitHash(rawTarget);\n const text = children ?? label ?? (rawTarget ? labelFromTarget(pathPart || frag || rawTarget) : '');\n\n // Defensive: the kernel never emits an empty target, but a hand-written\n // `<WikiLink>` might. Render inert text rather than a link to nowhere.\n if (!rawTarget) {\n return (\n <span className=\"ir-wikilink\" {...rest}>\n {text}\n </span>\n );\n }\n\n // Same-page anchor: a fragment with no path (`[[#sec-8-9]]`). Scroll within the\n // current file — no route change (§13.5). <Link> intercepts a bare `#`-href.\n if (pathPart === '' && frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n\n const resolved = resolveWikiTarget(pathPart, currentFile);\n const files = filesMetadata ?? {};\n const loaded = Object.keys(files).length > 0;\n\n // `resolved === undefined` ⇒ a relative target with no known current file: route\n // it optimistically (can't check existence or self-ness generically).\n if (resolved !== undefined) {\n if (currentFile && resolved === currentFile) {\n // The target IS this file. With a fragment it is a same-page anchor to another\n // of this file's sections; without one it is an inert self-reference.\n if (frag) {\n return (\n <Link href={`#${frag}`} className=\"ir-wikilink\" data-state=\"anchor\" {...rest}>\n {text}\n </Link>\n );\n }\n return (\n <span className=\"ir-wikilink ir-wikilink-self\" data-state=\"self\" {...rest}>\n {text}\n </span>\n );\n }\n // Existence is checked on the FRAGMENT-STRIPPED path (optimistic until loaded).\n const exists = !loaded || resolved in files;\n if (!exists) {\n return (\n <span\n className=\"ir-wikilink ir-wikilink-broken\"\n data-state=\"broken\"\n title={`No file at ${resolved}`}\n {...rest}\n >\n {text}\n </span>\n );\n }\n }\n // Resolved cross-file target: route through <Link>, carrying the raw target so its\n // `#fragment` rides through navigation to the scroll-after-nav effect (§13.5).\n return (\n <Link href={rawTarget} className=\"ir-wikilink\" data-state=\"resolved\" {...rest}>\n {text}\n </Link>\n );\n};\n"],"mappings":"AAoGM;AApGN,SAAoB,WAAW;AAC/B,SAAS,YAAY;AACrB,SAAS,sCAAsC;AAC/C,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAG1B,MAAM,kBAAkB,CAAC,WAA2B;AAClD,QAAM,OAAO,OAAO,MAAM,OAAO,EAAE,IAAI,KAAK;AAC5C,SAAO,KAAK,QAAQ,YAAY,EAAE,KAAK;AACzC;AAGA,MAAM,YAAY,CAAC,SAAyB;AAC1C,QAAM,MAAgB,CAAC;AACvB,aAAW,OAAO,KAAK,MAAM,GAAG,GAAG;AACjC,QAAI,QAAQ,MAAM,QAAQ,IAAK;AAC/B,QAAI,QAAQ,KAAM,KAAI,IAAI;AAAA,QACrB,KAAI,KAAK,GAAG;AAAA,EACnB;AACA,SAAO,MAAM,IAAI,KAAK,GAAG;AAC3B;AASA,MAAM,oBAAoB,CAAC,QAAgB,gBAA6C;AACtF,MAAI,OAAO,WAAW,GAAG,EAAG,QAAO,UAAU,MAAM;AACnD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,MAAM,YAAY,MAAM,GAAG,YAAY,YAAY,GAAG,CAAC;AAC7D,SAAO,UAAU,GAAG,GAAG,IAAI,MAAM,EAAE;AACrC;AA2CO,MAAM,WAAW,CAAC;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,MAI+E;AAC7E,QAAM,EAAE,cAAc,IAAI,IAAI,iBAAiB;AAC/C,QAAM,gBAAgB,IAAI,8BAA8B;AACxD,QAAM,cAAc,eAAe,mBAAmB,YAAY,QAAQ;AAE1E,QAAM,YAAY,UAAU;AAC5B,QAAM,CAAC,UAAU,IAAI,IAAI,UAAU,SAAS;AAC5C,QAAM,OAAO,YAAY,UAAU,YAAY,gBAAgB,YAAY,QAAQ,SAAS,IAAI;AAIhG,MAAI,CAAC,WAAW;AACd,WACE,oBAAC,UAAK,WAAU,eAAe,GAAG,MAC/B,gBACH;AAAA,EAEJ;AAIA,MAAI,aAAa,MAAM,MAAM;AAC3B,WACE,oBAAC,QAAK,MAAM,IAAI,IAAI,IAAI,WAAU,eAAc,cAAW,UAAU,GAAG,MACrE,gBACH;AAAA,EAEJ;AAEA,QAAM,WAAW,kBAAkB,UAAU,WAAW;AACxD,QAAM,QAAQ,iBAAiB,CAAC;AAChC,QAAM,SAAS,OAAO,KAAK,KAAK,EAAE,SAAS;AAI3C,MAAI,aAAa,QAAW;AAC1B,QAAI,eAAe,aAAa,aAAa;AAG3C,UAAI,MAAM;AACR,eACE,oBAAC,QAAK,MAAM,IAAI,IAAI,IAAI,WAAU,eAAc,cAAW,UAAU,GAAG,MACrE,gBACH;AAAA,MAEJ;AACA,aACE,oBAAC,UAAK,WAAU,gCAA+B,cAAW,QAAQ,GAAG,MAClE,gBACH;AAAA,IAEJ;AAEA,UAAM,SAAS,CAAC,UAAU,YAAY;AACtC,QAAI,CAAC,QAAQ;AACX,aACE;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,OAAO,cAAc,QAAQ;AAAA,UAC5B,GAAG;AAAA,UAEH;AAAA;AAAA,MACH;AAAA,IAEJ;AAAA,EACF;AAGA,SACE,oBAAC,QAAK,MAAM,WAAW,WAAU,eAAc,cAAW,YAAY,GAAG,MACtE,gBACH;AAEJ;","names":[]}
|
package/dist/llm.cjs
CHANGED
|
@@ -27,7 +27,12 @@ module.exports = __toCommonJS(llm_exports);
|
|
|
27
27
|
var import_catalog = require("./catalog");
|
|
28
28
|
var import_pushChannel = require("./pushChannel");
|
|
29
29
|
function chat(req) {
|
|
30
|
-
|
|
30
|
+
const { signal, ...params } = req;
|
|
31
|
+
return (0, import_catalog.invokeStream)(
|
|
32
|
+
"llm:chat",
|
|
33
|
+
params,
|
|
34
|
+
signal
|
|
35
|
+
);
|
|
31
36
|
}
|
|
32
37
|
const channel = (0, import_pushChannel.createPushChannel)({
|
|
33
38
|
pushType: "llm-provider",
|
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';\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 // 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}\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 | { type: 'usage'; inputTokens: number; outputTokens: number };\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 fails the\n * stream into the SP-7 connect-me prompt (the user adds a key) — the generator\n * throws with `code: 'auth-required'`; an un-granted call throws `forbidden`.\n */\nexport function chat(req: ChatRequest): AsyncGenerator<ChatDelta, ChatResult, void> {\n return invokeStream<ChatDelta, ChatResult>('llm:chat'
|
|
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';\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 // 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 /** 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 | { type: 'usage'; inputTokens: number; outputTokens: number };\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 fails the\n * stream into the SP-7 connect-me prompt (the user adds a key) — the generator\n * throws with `code: 'auth-required'`; an un-granted call throws `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>(\n 'llm:chat',\n params as unknown as Record<string, unknown>,\n signal,\n );\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 maxContextTokens: number;\n}\n\n/** Info about the provider the host resolved for this app. `null` when no provider\n * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */\nexport interface ChatProviderInfo {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — never a vendor secret or model id. */\n providerId: string;\n /** True for Host-proxied providers (host-vouched, SP-9); false for app-level ones,\n * whose `features` are an untrusted claim. */\n hostVouched: boolean;\n features: ChatFeatures;\n}\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\" (distinct from \"not yet answered\", which keeps the `initial` null).\nconst channel = createPushChannel<ChatProviderInfo | null>({\n pushType: 'llm-provider',\n requestType: 'request-llm-provider',\n initial: null,\n parse: (msg) =>\n 'provider' in msg ? (msg.provider as ChatProviderInfo | null) : undefined,\n});\n\n/** The provider the host resolved for this app (or `null` if none bound). Poll for a\n * one-off read; use {@link onChatProviderChange}/{@link useChatProvider} to react. */\nexport const describeChat = (): ChatProviderInfo | null => 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 = (\n listener: (provider: ChatProviderInfo | null) => void,\n): (() => void) => channel.onChange(listener);\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"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,qBAA6B;AAC7B,yBAAkC;AAiF3B,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,aAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AA0BA,MAAM,cAAU,sCAA2C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QACN,cAAc,MAAO,IAAI,WAAuC;AACpE,CAAC;AAIM,MAAM,eAAe,MAA+B,QAAQ,IAAI;AAIhE,MAAM,uBAAuB,CAClC,aACiB,QAAQ,SAAS,QAAQ;AAIrC,MAAM,kBAAkB,MAA+B,QAAQ,IAAI;","names":[]}
|
package/dist/llm.d.cts
CHANGED
|
@@ -45,6 +45,12 @@ interface ChatRequest {
|
|
|
45
45
|
/** An ABSTRACT tier hint, never a vendor model id — the host maps it to a concrete
|
|
46
46
|
* model on the resolved provider. Omit to take the provider's default. */
|
|
47
47
|
modelHint?: 'fast' | 'smart';
|
|
48
|
+
/** Abort the completion mid-stream. When it fires, the SDK sends the host a cancel
|
|
49
|
+
* frame so the host aborts the upstream provider request and STOPS BILLING the
|
|
50
|
+
* user's key — not merely stops the app-side iterator (LLM_AND_AGENTS_SPEC §3.3
|
|
51
|
+
* "abort the in-flight LLM request", R3-224). Not sent over the wire (an
|
|
52
|
+
* `AbortSignal` isn't serializable); handled SDK-side. */
|
|
53
|
+
signal?: AbortSignal;
|
|
48
54
|
}
|
|
49
55
|
/** One streamed chunk. Consumers typically accumulate `text-delta`s. */
|
|
50
56
|
type ChatDelta = {
|
package/dist/llm.d.ts
CHANGED
|
@@ -45,6 +45,12 @@ interface ChatRequest {
|
|
|
45
45
|
/** An ABSTRACT tier hint, never a vendor model id — the host maps it to a concrete
|
|
46
46
|
* model on the resolved provider. Omit to take the provider's default. */
|
|
47
47
|
modelHint?: 'fast' | 'smart';
|
|
48
|
+
/** Abort the completion mid-stream. When it fires, the SDK sends the host a cancel
|
|
49
|
+
* frame so the host aborts the upstream provider request and STOPS BILLING the
|
|
50
|
+
* user's key — not merely stops the app-side iterator (LLM_AND_AGENTS_SPEC §3.3
|
|
51
|
+
* "abort the in-flight LLM request", R3-224). Not sent over the wire (an
|
|
52
|
+
* `AbortSignal` isn't serializable); handled SDK-side. */
|
|
53
|
+
signal?: AbortSignal;
|
|
48
54
|
}
|
|
49
55
|
/** One streamed chunk. Consumers typically accumulate `text-delta`s. */
|
|
50
56
|
type ChatDelta = {
|
package/dist/llm.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { invokeStream } from "./catalog";
|
|
2
2
|
import { createPushChannel } from "./pushChannel";
|
|
3
3
|
function chat(req) {
|
|
4
|
-
|
|
4
|
+
const { signal, ...params } = req;
|
|
5
|
+
return invokeStream(
|
|
6
|
+
"llm:chat",
|
|
7
|
+
params,
|
|
8
|
+
signal
|
|
9
|
+
);
|
|
5
10
|
}
|
|
6
11
|
const channel = createPushChannel({
|
|
7
12
|
pushType: "llm-provider",
|
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';\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 // 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}\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 | { type: 'usage'; inputTokens: number; outputTokens: number };\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 fails the\n * stream into the SP-7 connect-me prompt (the user adds a key) — the generator\n * throws with `code: 'auth-required'`; an un-granted call throws `forbidden`.\n */\nexport function chat(req: ChatRequest): AsyncGenerator<ChatDelta, ChatResult, void> {\n return invokeStream<ChatDelta, ChatResult>('llm:chat'
|
|
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';\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 // 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 /** 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 | { type: 'usage'; inputTokens: number; outputTokens: number };\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 fails the\n * stream into the SP-7 connect-me prompt (the user adds a key) — the generator\n * throws with `code: 'auth-required'`; an un-granted call throws `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>(\n 'llm:chat',\n params as unknown as Record<string, unknown>,\n signal,\n );\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 maxContextTokens: number;\n}\n\n/** Info about the provider the host resolved for this app. `null` when no provider\n * is bound (SP-7: prompt the user to add a key before calling {@link chat}). */\nexport interface ChatProviderInfo {\n /** Opaque provider id, e.g. `llm.chat.anthropic` — never a vendor secret or model id. */\n providerId: string;\n /** True for Host-proxied providers (host-vouched, SP-9); false for app-level ones,\n * whose `features` are an untrusted claim. */\n hostVouched: boolean;\n features: ChatFeatures;\n}\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\" (distinct from \"not yet answered\", which keeps the `initial` null).\nconst channel = createPushChannel<ChatProviderInfo | null>({\n pushType: 'llm-provider',\n requestType: 'request-llm-provider',\n initial: null,\n parse: (msg) =>\n 'provider' in msg ? (msg.provider as ChatProviderInfo | null) : undefined,\n});\n\n/** The provider the host resolved for this app (or `null` if none bound). Poll for a\n * one-off read; use {@link onChatProviderChange}/{@link useChatProvider} to react. */\nexport const describeChat = (): ChatProviderInfo | null => 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 = (\n listener: (provider: ChatProviderInfo | null) => void,\n): (() => void) => channel.onChange(listener);\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"],"mappings":"AAeA,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAiF3B,SAAS,KAAK,KAA+D;AAGlF,QAAM,EAAE,QAAQ,GAAG,OAAO,IAAI;AAC9B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AA0BA,MAAM,UAAU,kBAA2C;AAAA,EACzD,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AAAA,EACT,OAAO,CAAC,QACN,cAAc,MAAO,IAAI,WAAuC;AACpE,CAAC;AAIM,MAAM,eAAe,MAA+B,QAAQ,IAAI;AAIhE,MAAM,uBAAuB,CAClC,aACiB,QAAQ,SAAS,QAAQ;AAIrC,MAAM,kBAAkB,MAA+B,QAAQ,IAAI;","names":[]}
|
package/dist/protocolStream.cjs
CHANGED
|
@@ -36,9 +36,11 @@ const nextMsgId = () => {
|
|
|
36
36
|
streamCounter = (streamCounter + 1) % Number.MAX_SAFE_INTEGER;
|
|
37
37
|
return streamCounter;
|
|
38
38
|
};
|
|
39
|
-
async function* consumeStream(transport, type, method, params, msgId = nextMsgId()) {
|
|
39
|
+
async function* consumeStream(transport, type, method, params, msgId = nextMsgId(), signal) {
|
|
40
40
|
const queue = [];
|
|
41
41
|
let wake = null;
|
|
42
|
+
let settled = false;
|
|
43
|
+
let started = false;
|
|
42
44
|
const push = (frame) => {
|
|
43
45
|
queue.push(frame);
|
|
44
46
|
const w = wake;
|
|
@@ -49,9 +51,18 @@ async function* consumeStream(transport, type, method, params, msgId = nextMsgId
|
|
|
49
51
|
if (msg.msgId !== msgId || !msg.stream) return;
|
|
50
52
|
push(msg.stream);
|
|
51
53
|
});
|
|
54
|
+
const onAbort = () => {
|
|
55
|
+
const w = wake;
|
|
56
|
+
wake = null;
|
|
57
|
+
w?.();
|
|
58
|
+
};
|
|
59
|
+
if (signal) signal.addEventListener("abort", onAbort);
|
|
52
60
|
try {
|
|
61
|
+
if (signal?.aborted) throw new StreamError("aborted", "stream aborted before start");
|
|
53
62
|
transport.send({ type, method, params, msgId, stream: true });
|
|
63
|
+
started = true;
|
|
54
64
|
while (true) {
|
|
65
|
+
if (signal?.aborted) throw new StreamError("aborted", "stream aborted");
|
|
55
66
|
if (queue.length === 0) {
|
|
56
67
|
await new Promise((resolve) => {
|
|
57
68
|
wake = resolve;
|
|
@@ -62,21 +73,26 @@ async function* consumeStream(transport, type, method, params, msgId = nextMsgId
|
|
|
62
73
|
if (frame.kind === "event") {
|
|
63
74
|
yield frame.value;
|
|
64
75
|
} else if (frame.kind === "done") {
|
|
76
|
+
settled = true;
|
|
65
77
|
return frame.value;
|
|
66
78
|
} else {
|
|
79
|
+
settled = true;
|
|
67
80
|
throw new StreamError(frame.code, frame.message);
|
|
68
81
|
}
|
|
69
82
|
}
|
|
70
83
|
} finally {
|
|
71
84
|
unsubscribe();
|
|
85
|
+
if (signal) signal.removeEventListener("abort", onAbort);
|
|
86
|
+
if (started && !settled) transport.cancel?.({ type, msgId, cancel: true });
|
|
72
87
|
}
|
|
73
88
|
}
|
|
74
89
|
const bundlerTransport = {
|
|
75
90
|
send: (msg) => (0, import_sandboxUtils.sendMessage)(msg.type, msg),
|
|
76
|
-
subscribe: (type, handler) => (0, import_sandboxUtils.addListener)(type, (msg) => handler(msg))
|
|
91
|
+
subscribe: (type, handler) => (0, import_sandboxUtils.addListener)(type, (msg) => handler(msg)),
|
|
92
|
+
cancel: (msg) => (0, import_sandboxUtils.sendMessage)(msg.type, msg)
|
|
77
93
|
};
|
|
78
|
-
function protocolStream(protocolName, method, params) {
|
|
79
|
-
return consumeStream(bundlerTransport, protocolName, method, params);
|
|
94
|
+
function protocolStream(protocolName, method, params, signal) {
|
|
95
|
+
return consumeStream(bundlerTransport, protocolName, method, params, void 0, signal);
|
|
80
96
|
}
|
|
81
97
|
// Annotate the CommonJS export names for ESM import in node:
|
|
82
98
|
0 && (module.exports = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocolStream.ts"],"sourcesContent":["// SDK-side consumer for the host streaming transport (UI_AS_APPS_SPEC §5.1).\n//\n// The host `pumpGenerator` emits, per request msgId, a run of `stream.event`\n// frames terminated by one `stream.done` (with the return value) or `stream.error`\n// frame. This reassembles that run into an AsyncGenerator: each `event` is a\n// `yield`, the `done` value is the generator's `return`, an `error` is a `throw`.\n//\n// `consumeStream` takes an injected `StreamTransport` so it's unit-tested with a\n// fake send/subscribe — no bundler. `protocolStream`/`contribute` below wire it to\n// the real sandbox messageBus via sandboxUtils.\nimport { addListener, sendMessage } from './sandboxUtils';\n\n/** One frame of a host stream: an `event` value, the terminal `done` value, or an `error`. */\nexport type StreamFrame =\n | { kind: 'event'; value: unknown }\n | { kind: 'done'; value: unknown }\n | { kind: 'error'; code: string; message: string };\n\n/** The send/subscribe transport {@link consumeStream} drives (injected so it can be faked in tests). */\nexport interface StreamTransport {\n // Fire the request that starts the stream. The host replies with frames tagged\n // by the same `msgId`.\n send: (msg: { type: string; method: string; params: unknown[]; msgId: number; stream: true }) => void;\n // Subscribe to inbound frames for `type`; returns an unsubscribe.\n subscribe: (\n type: string,\n handler: (msg: { msgId?: number; stream?: StreamFrame }) => void\n ) => () => void;\n}\n\n/** Thrown when a stream ends in an `error` frame; carries the host's `code`. */\nexport class StreamError extends Error {\n code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = 'StreamError';\n this.code = code;\n }\n}\n\nlet streamCounter = 0;\nconst nextMsgId = (): number => {\n // Distinct from the bundler's own protocolRequest counter space is unnecessary —\n // frames are filtered by (type, msgId, stream) so a collision with a one-shot\n // reply (which has `result`, not `stream`) can't be misread.\n streamCounter = (streamCounter + 1) % Number.MAX_SAFE_INTEGER;\n return streamCounter;\n};\n\n/**\n * Drive one streamed request to completion over an injected transport.\n *\n * Yields each event value; returns the `done` value; throws `StreamError` on an\n * error frame. Always unsubscribes (via the generator's `finally`) so an early\n * `break` in the consumer doesn't leak the listener.\n */\nexport async function* consumeStream<T = unknown, R = unknown>(\n transport: StreamTransport,\n type: string,\n method: string,\n params: unknown[],\n msgId: number = nextMsgId()\n): AsyncGenerator<T, R, void> {\n const queue: StreamFrame[] = [];\n let wake: (() => void) | null = null;\n const push = (frame: StreamFrame) => {\n queue.push(frame);\n const w = wake;\n wake = null;\n w?.();\n };\n\n const unsubscribe = transport.subscribe(type, (msg) => {\n if (msg.msgId !== msgId || !msg.stream) return;\n push(msg.stream);\n });\n\n try {\n transport.send({ type, method, params, msgId, stream: true });\n while (true) {\n if (queue.length === 0) {\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n continue;\n }\n const frame = queue.shift() as StreamFrame;\n if (frame.kind === 'event') {\n yield frame.value as T;\n } else if (frame.kind === 'done') {\n return frame.value as R;\n } else {\n throw new StreamError(frame.code, frame.message);\n }\n }\n } finally {\n unsubscribe();\n }\n}\n\n// The real sandbox transport, built from the bundler messageBus helpers.\nconst bundlerTransport: StreamTransport = {\n send: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n subscribe: (type, handler) =>\n addListener(type, (msg) => handler(msg as { msgId?: number; stream?: StreamFrame })),\n};\n\n/**\n * Consume an elevated streaming protocol method from app code.\n *\n * `for await (const ev of protocolStream('protocol-contribute', 'run', [opts])) …`\n */\nexport function protocolStream<T = unknown, R = unknown>(\n protocolName: string,\n method: string,\n params: unknown[]\n): AsyncGenerator<T, R, void> {\n return consumeStream<T, R>(bundlerTransport, protocolName, method, params);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,0BAAyC;
|
|
1
|
+
{"version":3,"sources":["../src/protocolStream.ts"],"sourcesContent":["// SDK-side consumer for the host streaming transport (UI_AS_APPS_SPEC §5.1).\n//\n// The host `pumpGenerator` emits, per request msgId, a run of `stream.event`\n// frames terminated by one `stream.done` (with the return value) or `stream.error`\n// frame. This reassembles that run into an AsyncGenerator: each `event` is a\n// `yield`, the `done` value is the generator's `return`, an `error` is a `throw`.\n//\n// `consumeStream` takes an injected `StreamTransport` so it's unit-tested with a\n// fake send/subscribe — no bundler. `protocolStream`/`contribute` below wire it to\n// the real sandbox messageBus via sandboxUtils.\nimport { addListener, sendMessage } from './sandboxUtils';\n\n/** One frame of a host stream: an `event` value, the terminal `done` value, or an `error`. */\nexport type StreamFrame =\n | { kind: 'event'; value: unknown }\n | { kind: 'done'; value: unknown }\n | { kind: 'error'; code: string; message: string };\n\n/** The send/subscribe transport {@link consumeStream} drives (injected so it can be faked in tests). */\nexport interface StreamTransport {\n // Fire the request that starts the stream. The host replies with frames tagged\n // by the same `msgId`.\n send: (msg: { type: string; method: string; params: unknown[]; msgId: number; stream: true }) => void;\n // Subscribe to inbound frames for `type`; returns an unsubscribe.\n subscribe: (\n type: string,\n handler: (msg: { msgId?: number; stream?: StreamFrame }) => void\n ) => () => void;\n // Tell the host to STOP the stream early — abort the in-flight generation (and,\n // for `llm:chat`, the upstream provider fetch so it stops BILLING). Sent when the\n // consumer bails before a terminal frame: an early `break`/`return` out of the\n // `for await`, or an `AbortSignal` firing. Carries the same `(type, msgId)` the\n // host tagged its frames with, so the host aborts the matching generator\n // (LLM_AND_AGENTS_SPEC §3.3 \"abort the in-flight LLM request\"). Optional — a\n // transport predating the cancel frame simply omits it and the old behavior\n // (host runs to completion) stands.\n cancel?: (msg: { type: string; msgId: number; cancel: true }) => void;\n}\n\n/** Thrown when a stream ends in an `error` frame; carries the host's `code`. */\nexport class StreamError extends Error {\n code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = 'StreamError';\n this.code = code;\n }\n}\n\nlet streamCounter = 0;\nconst nextMsgId = (): number => {\n // Distinct from the bundler's own protocolRequest counter space is unnecessary —\n // frames are filtered by (type, msgId, stream) so a collision with a one-shot\n // reply (which has `result`, not `stream`) can't be misread.\n streamCounter = (streamCounter + 1) % Number.MAX_SAFE_INTEGER;\n return streamCounter;\n};\n\n/**\n * Drive one streamed request to completion over an injected transport.\n *\n * Yields each event value; returns the `done` value; throws `StreamError` on an\n * error frame. Always unsubscribes (via the generator's `finally`) so an early\n * `break` in the consumer doesn't leak the listener.\n *\n * `signal` wires a caller {@link AbortSignal} to mid-stream cancellation: when it\n * fires (or the consumer `break`s before a terminal frame), the `finally` sends a\n * `cancel` frame back over `transport.cancel` so the HOST stops generating — without\n * it, aborting only stops the app-side iterator while the upstream provider keeps\n * streaming and BILLING (LLM_AND_AGENTS_SPEC §3.3, R3-224 / adversarial F2).\n */\nexport async function* consumeStream<T = unknown, R = unknown>(\n transport: StreamTransport,\n type: string,\n method: string,\n params: unknown[],\n msgId: number = nextMsgId(),\n signal?: AbortSignal\n): AsyncGenerator<T, R, void> {\n const queue: StreamFrame[] = [];\n let wake: (() => void) | null = null;\n // True once a terminal (`done`/`error`) frame arrived — so the `finally` knows the\n // host already stopped and must NOT send a redundant cancel. Left false when the\n // consumer bails early or the signal aborts (the two cases that DO need a cancel).\n let settled = false;\n // True once the request frame went out. A cancel is only meaningful for a stream\n // the host actually started — an abort BEFORE `send` sends nothing to cancel.\n let started = false;\n const push = (frame: StreamFrame) => {\n queue.push(frame);\n const w = wake;\n wake = null;\n w?.();\n };\n\n const unsubscribe = transport.subscribe(type, (msg) => {\n if (msg.msgId !== msgId || !msg.stream) return;\n push(msg.stream);\n });\n\n // An abort wakes the pull loop out of its idle `await`; the loop then throws.\n const onAbort = () => {\n const w = wake;\n wake = null;\n w?.();\n };\n if (signal) signal.addEventListener('abort', onAbort);\n\n try {\n if (signal?.aborted) throw new StreamError('aborted', 'stream aborted before start');\n transport.send({ type, method, params, msgId, stream: true });\n started = true;\n while (true) {\n if (signal?.aborted) throw new StreamError('aborted', 'stream aborted');\n if (queue.length === 0) {\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n continue;\n }\n const frame = queue.shift() as StreamFrame;\n if (frame.kind === 'event') {\n yield frame.value as T;\n } else if (frame.kind === 'done') {\n settled = true;\n return frame.value as R;\n } else {\n settled = true;\n throw new StreamError(frame.code, frame.message);\n }\n }\n } finally {\n unsubscribe();\n if (signal) signal.removeEventListener('abort', onAbort);\n // Consumer stopped pulling before a terminal frame (early break/return, or the\n // signal aborted): tell the host to stop the in-flight generation + billing.\n if (started && !settled) transport.cancel?.({ type, msgId, cancel: true });\n }\n}\n\n// The real sandbox transport, built from the bundler messageBus helpers. `cancel`\n// rides the same messageBus as `send` — a `{type, msgId, cancel:true}` frame the\n// host dispatcher routes to the in-flight generator's AbortController.\nconst bundlerTransport: StreamTransport = {\n send: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n subscribe: (type, handler) =>\n addListener(type, (msg) => handler(msg as { msgId?: number; stream?: StreamFrame })),\n cancel: (msg) => sendMessage(msg.type, msg as unknown as Record<string, unknown>),\n};\n\n/**\n * Consume an elevated streaming protocol method from app code.\n *\n * `for await (const ev of protocolStream('protocol-contribute', 'run', [opts])) …`\n *\n * Pass `signal` to abort the stream (and the host's in-flight work) mid-flight.\n */\nexport function protocolStream<T = unknown, R = unknown>(\n protocolName: string,\n method: string,\n params: unknown[],\n signal?: AbortSignal\n): AsyncGenerator<T, R, void> {\n return consumeStream<T, R>(bundlerTransport, protocolName, method, params, undefined, signal);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA,0BAAyC;AA8BlC,MAAM,oBAAoB,MAAM;AAAA,EAErC,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAI,gBAAgB;AACpB,MAAM,YAAY,MAAc;AAI9B,mBAAiB,gBAAgB,KAAK,OAAO;AAC7C,SAAO;AACT;AAeA,gBAAuB,cACrB,WACA,MACA,QACA,QACA,QAAgB,UAAU,GAC1B,QAC4B;AAC5B,QAAM,QAAuB,CAAC;AAC9B,MAAI,OAA4B;AAIhC,MAAI,UAAU;AAGd,MAAI,UAAU;AACd,QAAM,OAAO,CAAC,UAAuB;AACnC,UAAM,KAAK,KAAK;AAChB,UAAM,IAAI;AACV,WAAO;AACP,QAAI;AAAA,EACN;AAEA,QAAM,cAAc,UAAU,UAAU,MAAM,CAAC,QAAQ;AACrD,QAAI,IAAI,UAAU,SAAS,CAAC,IAAI,OAAQ;AACxC,SAAK,IAAI,MAAM;AAAA,EACjB,CAAC;AAGD,QAAM,UAAU,MAAM;AACpB,UAAM,IAAI;AACV,WAAO;AACP,QAAI;AAAA,EACN;AACA,MAAI,OAAQ,QAAO,iBAAiB,SAAS,OAAO;AAEpD,MAAI;AACF,QAAI,QAAQ,QAAS,OAAM,IAAI,YAAY,WAAW,6BAA6B;AACnF,cAAU,KAAK,EAAE,MAAM,QAAQ,QAAQ,OAAO,QAAQ,KAAK,CAAC;AAC5D,cAAU;AACV,WAAO,MAAM;AACX,UAAI,QAAQ,QAAS,OAAM,IAAI,YAAY,WAAW,gBAAgB;AACtE,UAAI,MAAM,WAAW,GAAG;AACtB,cAAM,IAAI,QAAc,CAAC,YAAY;AACnC,iBAAO;AAAA,QACT,CAAC;AACD;AAAA,MACF;AACA,YAAM,QAAQ,MAAM,MAAM;AAC1B,UAAI,MAAM,SAAS,SAAS;AAC1B,cAAM,MAAM;AAAA,MACd,WAAW,MAAM,SAAS,QAAQ;AAChC,kBAAU;AACV,eAAO,MAAM;AAAA,MACf,OAAO;AACL,kBAAU;AACV,cAAM,IAAI,YAAY,MAAM,MAAM,MAAM,OAAO;AAAA,MACjD;AAAA,IACF;AAAA,EACF,UAAE;AACA,gBAAY;AACZ,QAAI,OAAQ,QAAO,oBAAoB,SAAS,OAAO;AAGvD,QAAI,WAAW,CAAC,QAAS,WAAU,SAAS,EAAE,MAAM,OAAO,QAAQ,KAAK,CAAC;AAAA,EAC3E;AACF;AAKA,MAAM,mBAAoC;AAAA,EACxC,MAAM,CAAC,YAAQ,iCAAY,IAAI,MAAM,GAAyC;AAAA,EAC9E,WAAW,CAAC,MAAM,gBAChB,iCAAY,MAAM,CAAC,QAAQ,QAAQ,GAA+C,CAAC;AAAA,EACrF,QAAQ,CAAC,YAAQ,iCAAY,IAAI,MAAM,GAAyC;AAClF;AASO,SAAS,eACd,cACA,QACA,QACA,QAC4B;AAC5B,SAAO,cAAoB,kBAAkB,cAAc,QAAQ,QAAQ,QAAW,MAAM;AAC9F;","names":[]}
|
|
@@ -23,6 +23,11 @@ interface StreamTransport {
|
|
|
23
23
|
msgId?: number;
|
|
24
24
|
stream?: StreamFrame;
|
|
25
25
|
}) => void) => () => void;
|
|
26
|
+
cancel?: (msg: {
|
|
27
|
+
type: string;
|
|
28
|
+
msgId: number;
|
|
29
|
+
cancel: true;
|
|
30
|
+
}) => void;
|
|
26
31
|
}
|
|
27
32
|
/** Thrown when a stream ends in an `error` frame; carries the host's `code`. */
|
|
28
33
|
declare class StreamError extends Error {
|
|
@@ -35,13 +40,21 @@ declare class StreamError extends Error {
|
|
|
35
40
|
* Yields each event value; returns the `done` value; throws `StreamError` on an
|
|
36
41
|
* error frame. Always unsubscribes (via the generator's `finally`) so an early
|
|
37
42
|
* `break` in the consumer doesn't leak the listener.
|
|
43
|
+
*
|
|
44
|
+
* `signal` wires a caller {@link AbortSignal} to mid-stream cancellation: when it
|
|
45
|
+
* fires (or the consumer `break`s before a terminal frame), the `finally` sends a
|
|
46
|
+
* `cancel` frame back over `transport.cancel` so the HOST stops generating — without
|
|
47
|
+
* it, aborting only stops the app-side iterator while the upstream provider keeps
|
|
48
|
+
* streaming and BILLING (LLM_AND_AGENTS_SPEC §3.3, R3-224 / adversarial F2).
|
|
38
49
|
*/
|
|
39
|
-
declare function consumeStream<T = unknown, R = unknown>(transport: StreamTransport, type: string, method: string, params: unknown[], msgId?: number): AsyncGenerator<T, R, void>;
|
|
50
|
+
declare function consumeStream<T = unknown, R = unknown>(transport: StreamTransport, type: string, method: string, params: unknown[], msgId?: number, signal?: AbortSignal): AsyncGenerator<T, R, void>;
|
|
40
51
|
/**
|
|
41
52
|
* Consume an elevated streaming protocol method from app code.
|
|
42
53
|
*
|
|
43
54
|
* `for await (const ev of protocolStream('protocol-contribute', 'run', [opts])) …`
|
|
55
|
+
*
|
|
56
|
+
* Pass `signal` to abort the stream (and the host's in-flight work) mid-flight.
|
|
44
57
|
*/
|
|
45
|
-
declare function protocolStream<T = unknown, R = unknown>(protocolName: string, method: string, params: unknown[]): AsyncGenerator<T, R, void>;
|
|
58
|
+
declare function protocolStream<T = unknown, R = unknown>(protocolName: string, method: string, params: unknown[], signal?: AbortSignal): AsyncGenerator<T, R, void>;
|
|
46
59
|
|
|
47
60
|
export { StreamError, type StreamFrame, type StreamTransport, consumeStream, protocolStream };
|
package/dist/protocolStream.d.ts
CHANGED
|
@@ -23,6 +23,11 @@ interface StreamTransport {
|
|
|
23
23
|
msgId?: number;
|
|
24
24
|
stream?: StreamFrame;
|
|
25
25
|
}) => void) => () => void;
|
|
26
|
+
cancel?: (msg: {
|
|
27
|
+
type: string;
|
|
28
|
+
msgId: number;
|
|
29
|
+
cancel: true;
|
|
30
|
+
}) => void;
|
|
26
31
|
}
|
|
27
32
|
/** Thrown when a stream ends in an `error` frame; carries the host's `code`. */
|
|
28
33
|
declare class StreamError extends Error {
|
|
@@ -35,13 +40,21 @@ declare class StreamError extends Error {
|
|
|
35
40
|
* Yields each event value; returns the `done` value; throws `StreamError` on an
|
|
36
41
|
* error frame. Always unsubscribes (via the generator's `finally`) so an early
|
|
37
42
|
* `break` in the consumer doesn't leak the listener.
|
|
43
|
+
*
|
|
44
|
+
* `signal` wires a caller {@link AbortSignal} to mid-stream cancellation: when it
|
|
45
|
+
* fires (or the consumer `break`s before a terminal frame), the `finally` sends a
|
|
46
|
+
* `cancel` frame back over `transport.cancel` so the HOST stops generating — without
|
|
47
|
+
* it, aborting only stops the app-side iterator while the upstream provider keeps
|
|
48
|
+
* streaming and BILLING (LLM_AND_AGENTS_SPEC §3.3, R3-224 / adversarial F2).
|
|
38
49
|
*/
|
|
39
|
-
declare function consumeStream<T = unknown, R = unknown>(transport: StreamTransport, type: string, method: string, params: unknown[], msgId?: number): AsyncGenerator<T, R, void>;
|
|
50
|
+
declare function consumeStream<T = unknown, R = unknown>(transport: StreamTransport, type: string, method: string, params: unknown[], msgId?: number, signal?: AbortSignal): AsyncGenerator<T, R, void>;
|
|
40
51
|
/**
|
|
41
52
|
* Consume an elevated streaming protocol method from app code.
|
|
42
53
|
*
|
|
43
54
|
* `for await (const ev of protocolStream('protocol-contribute', 'run', [opts])) …`
|
|
55
|
+
*
|
|
56
|
+
* Pass `signal` to abort the stream (and the host's in-flight work) mid-flight.
|
|
44
57
|
*/
|
|
45
|
-
declare function protocolStream<T = unknown, R = unknown>(protocolName: string, method: string, params: unknown[]): AsyncGenerator<T, R, void>;
|
|
58
|
+
declare function protocolStream<T = unknown, R = unknown>(protocolName: string, method: string, params: unknown[], signal?: AbortSignal): AsyncGenerator<T, R, void>;
|
|
46
59
|
|
|
47
60
|
export { StreamError, type StreamFrame, type StreamTransport, consumeStream, protocolStream };
|