@tangle-network/agent-app 0.50.13 → 0.50.15
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/assistant/index.js +5 -5
- package/dist/catalog/index.js +1 -1
- package/dist/chat-react/index.js +3 -3
- package/dist/{chunk-YWHLMR3N.js → chunk-5BDSNHWW.js} +2 -2
- package/dist/{chunk-SUUQ2QCS.js → chunk-7YA4QNTU.js} +22 -4
- package/dist/chunk-7YA4QNTU.js.map +1 -0
- package/dist/{chunk-6AIJSXAX.js → chunk-BPSRJTJG.js} +2 -2
- package/dist/{chunk-56VZACEN.js → chunk-CPL7LLO5.js} +3 -3
- package/dist/{chunk-7JTWJ5NN.js → chunk-ZNSR7RSQ.js} +2 -2
- package/dist/{mention-editor-NUQ2NJ6Z.js → mention-editor-BCLZUAF7.js} +3 -3
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/model-catalog.d.ts +5 -5
- package/dist/studio-react/index.js +3 -3
- package/dist/web-react/index.js +5 -5
- package/dist/workspace-apps/data-bridge.d.ts +41 -0
- package/dist/workspace-apps/index.d.ts +2 -0
- package/dist/workspace-apps/index.js +203 -0
- package/dist/workspace-apps/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-SUUQ2QCS.js.map +0 -1
- /package/dist/{chunk-YWHLMR3N.js.map → chunk-5BDSNHWW.js.map} +0 -0
- /package/dist/{chunk-6AIJSXAX.js.map → chunk-BPSRJTJG.js.map} +0 -0
- /package/dist/{chunk-56VZACEN.js.map → chunk-CPL7LLO5.js.map} +0 -0
- /package/dist/{chunk-7JTWJ5NN.js.map → chunk-ZNSR7RSQ.js.map} +0 -0
- /package/dist/{mention-editor-NUQ2NJ6Z.js.map → mention-editor-BCLZUAF7.js.map} +0 -0
package/dist/assistant/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ChatEmptyState,
|
|
3
3
|
ChatMessages
|
|
4
|
-
} from "../chunk-
|
|
5
|
-
import "../chunk-
|
|
4
|
+
} from "../chunk-ZNSR7RSQ.js";
|
|
5
|
+
import "../chunk-BPSRJTJG.js";
|
|
6
6
|
import "../chunk-3HUFJ5LO.js";
|
|
7
7
|
import "../chunk-FBVLEGEG.js";
|
|
8
8
|
import "../chunk-ENLRJYVW.js";
|
|
9
9
|
import {
|
|
10
10
|
ChatComposer
|
|
11
|
-
} from "../chunk-
|
|
11
|
+
} from "../chunk-CPL7LLO5.js";
|
|
12
12
|
import "../chunk-L7MB2LLM.js";
|
|
13
13
|
import {
|
|
14
14
|
ModelPicker
|
|
15
|
-
} from "../chunk-
|
|
15
|
+
} from "../chunk-5BDSNHWW.js";
|
|
16
16
|
import "../chunk-BATKJP3P.js";
|
|
17
17
|
import "../chunk-SJWIZT7B.js";
|
|
18
18
|
import "../chunk-GEYACSFW.js";
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
import "../chunk-FQYAJYPW.js";
|
|
23
23
|
import "../chunk-NU7QSZBR.js";
|
|
24
24
|
import "../chunk-MCYJON3F.js";
|
|
25
|
-
import "../chunk-
|
|
25
|
+
import "../chunk-7YA4QNTU.js";
|
|
26
26
|
import "../chunk-RACQDXJ7.js";
|
|
27
27
|
import "../chunk-X47R2IVO.js";
|
|
28
28
|
import "../chunk-ZVEEWGDK.js";
|
package/dist/catalog/index.js
CHANGED
package/dist/chat-react/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ComposerModeControls,
|
|
3
3
|
EntryComposer
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-CPL7LLO5.js";
|
|
5
5
|
import "../chunk-L7MB2LLM.js";
|
|
6
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-5BDSNHWW.js";
|
|
7
7
|
import "../chunk-SJWIZT7B.js";
|
|
8
8
|
import "../chunk-NU7QSZBR.js";
|
|
9
9
|
import "../chunk-MCYJON3F.js";
|
|
10
|
-
import "../chunk-
|
|
10
|
+
import "../chunk-7YA4QNTU.js";
|
|
11
11
|
import "../chunk-X47R2IVO.js";
|
|
12
12
|
import "../chunk-TXD5HXLE.js";
|
|
13
13
|
export {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MAX_RECOMMENDED_MODELS,
|
|
3
3
|
sortModelsByFreshness
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-7YA4QNTU.js";
|
|
5
5
|
|
|
6
6
|
// src/web-react/provider-logo.tsx
|
|
7
7
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
@@ -562,4 +562,4 @@ export {
|
|
|
562
562
|
EffortMeter,
|
|
563
563
|
EffortPicker
|
|
564
564
|
};
|
|
565
|
-
//# sourceMappingURL=chunk-
|
|
565
|
+
//# sourceMappingURL=chunk-5BDSNHWW.js.map
|
|
@@ -38,6 +38,9 @@ function providerForModel(model) {
|
|
|
38
38
|
var MAX_RECOMMENDED_MODELS = 8;
|
|
39
39
|
var EXCLUDED_ID = /(embedding|tts|transcribe|whisper|audio|realtime|image|lyria|sora|dall-e|moderation|content-safety|search-preview|search-api|deep-research|:batch$)/;
|
|
40
40
|
var DEFAULT_CANDIDATE_RULES = [
|
|
41
|
+
{ providers: ["zai", "z-ai"], match: /^glm-5\.3$/ },
|
|
42
|
+
{ providers: ["openai"], match: /^gpt-6\.1-sol$/ },
|
|
43
|
+
{ providers: ["openai"], match: /^gpt-6-astra$/ },
|
|
41
44
|
{ providers: ["anthropic"], match: /^claude-sonnet-[\d-]+$/ },
|
|
42
45
|
{ providers: ["anthropic"], match: /^claude-opus-[\d-]+$/ },
|
|
43
46
|
{ providers: ["anthropic"], match: /^claude-haiku-[\d-]+$/ },
|
|
@@ -52,14 +55,28 @@ var DEFAULT_CANDIDATE_RULES = [
|
|
|
52
55
|
{ providers: ["mistral"], match: /^mistral-(large|medium)-?[\d.-]*$/ }
|
|
53
56
|
];
|
|
54
57
|
var RECOMMENDED_FAMILIES = [
|
|
55
|
-
{ provider: "anthropic", match: /^claude-opus-\d+(?:[-.]\d+)*$/, minVersion: [5] },
|
|
56
|
-
{ provider: "anthropic", match: /^claude-sonnet-\d+(?:[-.]\d+)*$/, minVersion: [5] },
|
|
58
|
+
{ provider: "anthropic", match: /^claude-opus-\d+(?:[-.]\d+)*$/, minVersion: [5, 5] },
|
|
59
|
+
{ provider: "anthropic", match: /^claude-sonnet-\d+(?:[-.]\d+)*$/, minVersion: [5, 5] },
|
|
57
60
|
{ provider: "openai", match: /^gpt-\d+(?:\.\d+)?-sol$/, minVersion: [6] },
|
|
58
61
|
{ provider: "openai", match: /^gpt-\d+(?:\.\d+)?-astra$/, minVersion: [6] },
|
|
59
62
|
{ provider: "google", match: /^gemini-\d+(?:\.\d+)?-flash(?:-preview)?$/, minVersion: [3, 5] },
|
|
60
63
|
{ provider: "zai", match: /^glm-\d+(?:\.\d+)?$/, minVersion: [5, 3] }
|
|
61
64
|
];
|
|
62
65
|
var RECOMMENDATION_WINDOW_MS = 120 * 24 * 60 * 60 * 1e3;
|
|
66
|
+
var VERIFIED_RELEASE_DATES = {
|
|
67
|
+
// https://www.anthropic.com/claude-opus-5-5
|
|
68
|
+
"claude-opus-5-5": "2026-09-22",
|
|
69
|
+
// https://www.anthropic.com/claude-sonnet-5-5
|
|
70
|
+
"claude-sonnet-5-5": "2026-09-28",
|
|
71
|
+
// https://developers.openai.com/api/docs/changelog
|
|
72
|
+
"gpt-6.1-sol": "2026-09-29",
|
|
73
|
+
// https://openai.com/index/safety-overview-gpt-6-astra/
|
|
74
|
+
"gpt-6-astra": "2026-09-03",
|
|
75
|
+
// https://blog.google/innovation-and-ai/models-and-research/gemini-models/introducing-gemini-3-7-flash/
|
|
76
|
+
"gemini-3.7-flash": "2026-08-13",
|
|
77
|
+
// https://z.ai/blog/glm-5.3
|
|
78
|
+
"glm-5.3": "2026-08-14"
|
|
79
|
+
};
|
|
63
80
|
function releaseDateFromRouter(model) {
|
|
64
81
|
const value = model.release_date ?? model.released_at;
|
|
65
82
|
if (!value || !/^\d{4}-\d{2}-\d{2}(?:T|$)/.test(value)) return void 0;
|
|
@@ -180,7 +197,8 @@ function buildCatalog(raw, opts) {
|
|
|
180
197
|
group.sort((a, b) => aliasPenalty(a.id) - aliasPenalty(b.id) || a.id.length - b.id.length);
|
|
181
198
|
const rep = group[0];
|
|
182
199
|
const mergedParams = new Set(group.flatMap((m) => m.supported_parameters ?? []));
|
|
183
|
-
const
|
|
200
|
+
const verifiedDate = VERIFIED_RELEASE_DATES[normalizeModelId(rep.id)];
|
|
201
|
+
const releaseDate = group.map(releaseDateFromRouter).find((date) => date !== void 0) ?? (verifiedDate ? new Date(verifiedDate).toISOString() : void 0);
|
|
184
202
|
reps.push({ model: rep, normId: normalizeModelId(rep.id), mergedParams, releaseDate });
|
|
185
203
|
}
|
|
186
204
|
const defaultCandidateIds = [];
|
|
@@ -263,4 +281,4 @@ export {
|
|
|
263
281
|
fetchModelCatalog,
|
|
264
282
|
__resetCatalogCache
|
|
265
283
|
};
|
|
266
|
-
//# sourceMappingURL=chunk-
|
|
284
|
+
//# sourceMappingURL=chunk-7YA4QNTU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/model-catalog.ts"],"sourcesContent":["/**\n * Model catalogue — computed live from the Tangle Router, never hand-curated.\n * Lifted from tuner-agent so every agent app's model picker shares one\n * filter/dedupe/rank/feature pipeline instead of re-deriving it.\n *\n * The router's /models endpoint returns every routeable model (~200), which is\n * unusable as a picker list: it mixes chat models with TTS/embedding/realtime\n * endpoints, dated snapshots alias their parents, and provider-prefixed ids\n * duplicate canonical ones. This module turns that into a product catalogue:\n *\n * filter (chat-capable, routeable) → dedupe (snapshot/prefix/:free aliases)\n * → rank (provider tier, current generation) → recommend (current families)\n * → default (env override or preferred family)\n *\n * The router is the authority for routeability. Its current response has no\n * release dates, so exact vendor-announced dates supplement it for known\n * models. Undated newer models use a conservative family floor. Other\n * routeable models stay available through search and explicit browsing.\n */\n\nexport interface RouterModel {\n id: string\n name?: string\n description?: string\n release_date?: string\n released_at?: string\n _provider?: string\n provider?: string\n pricing?: { prompt?: string | null; completion?: string | null }\n context_length?: number\n architecture?: {\n modality?: string\n input_modalities?: string[]\n output_modalities?: string[]\n }\n supported_parameters?: string[]\n routeability?: {\n status?: string\n routeable?: boolean\n provider?: string\n endpoints?: {\n chat_completions?: {\n status?: string\n routeable?: boolean\n }\n }\n }\n}\n\n/** Define the structure and capabilities of a catalog item with optional pricing and feature flags */\nexport interface CatalogModel {\n id: string\n name: string\n provider: string\n description?: string\n /** Router-supplied or vendor-verified release date; never inferred from an id. */\n releaseDate?: string\n contextLength?: number\n pricing?: { prompt?: string; completion?: string }\n supportsTools: boolean\n supportsReasoning: boolean\n featured: boolean\n}\n\n/** Define a catalog containing models with a default ID and fetch timestamp */\nexport interface ModelCatalog {\n defaultModelId: string | null\n fetchedAt: string\n models: CatalogModel[]\n}\n\n/** Display order. Unlisted providers sort after these, alphabetically. */\nconst PROVIDER_TIER: string[] = [\n 'anthropic',\n 'openai',\n 'google',\n 'xai',\n 'deepseek',\n 'moonshot',\n 'zai',\n 'mistral',\n 'groq',\n 'nvidia',\n 'cohere',\n 'cerebras',\n]\n\n/** Router aliases that are one provider in a user-facing catalogue. */\nfunction normalizeProvider(provider: string): string {\n const normalized = provider.toLowerCase()\n if (normalized === 'moonshotai') return 'moonshot'\n if (normalized === 'z-ai') return 'zai'\n if (normalized === 'x-ai') return 'xai'\n if (normalized === 'mistralai') return 'mistral'\n return normalized\n}\n\n/** Resolve provider metadata across router response versions. */\nfunction providerForModel(model: RouterModel): string {\n const declared = model._provider ?? model.provider ?? model.routeability?.provider\n if (declared) return normalizeProvider(declared)\n\n const id = normalizeModelId(model.id).toLowerCase()\n if (/^claude-/.test(id)) return 'anthropic'\n if (/^(?:gpt-|o\\d)/.test(id)) return 'openai'\n if (/^gemini-/.test(id)) return 'google'\n if (/^grok-/.test(id)) return 'xai'\n if (/^deepseek-/.test(id)) return 'deepseek'\n if (/^kimi-/.test(id)) return 'moonshot'\n if (/^glm-/.test(id)) return 'zai'\n if (/^mistral/.test(id)) return 'mistral'\n return 'unknown'\n}\n\n/** A short, varied first screen. All other routeable entries remain searchable. */\nexport const MAX_RECOMMENDED_MODELS = 8\n\n/** Non-chat endpoints that pollute the router list (matched on normalized id). */\nconst EXCLUDED_ID = /(embedding|tts|transcribe|whisper|audio|realtime|image|lyria|sora|dall-e|moderation|content-safety|search-preview|search-api|deep-research|:batch$)/\n\n/**\n * Default families, in preference order. Each rule finds the highest-version\n * routeable model whose normalized id matches. Patterns anchor on the family\n * name and stop before specialty suffixes (codex, nano, lite, …) so the\n * mainline model wins.\n */\nconst DEFAULT_CANDIDATE_RULES: Array<{ providers: string[]; match: RegExp }> = [\n { providers: ['zai', 'z-ai'], match: /^glm-5\\.3$/ },\n { providers: ['openai'], match: /^gpt-6\\.1-sol$/ },\n { providers: ['openai'], match: /^gpt-6-astra$/ },\n { providers: ['anthropic'], match: /^claude-sonnet-[\\d-]+$/ },\n { providers: ['anthropic'], match: /^claude-opus-[\\d-]+$/ },\n { providers: ['anthropic'], match: /^claude-haiku-[\\d-]+$/ },\n { providers: ['openai'], match: /^gpt-\\d+(\\.\\d+)?$/ },\n { providers: ['openai'], match: /^gpt-\\d+(\\.\\d+)?-mini$/ },\n { providers: ['google'], match: /^gemini-[\\d.]+-pro(-preview)?$/ },\n { providers: ['google'], match: /^gemini-[\\d.]+-flash(-preview)?$/ },\n { providers: ['xai'], match: /^grok-[\\d.]+$/ },\n { providers: ['deepseek'], match: /^deepseek-(chat|v[\\d.]+(-\\w+)?)$/ },\n { providers: ['moonshotai', 'moonshot'], match: /^kimi-k[\\d.]+$/ },\n { providers: ['zai', 'z-ai'], match: /^glm-[\\d.]+$/ },\n { providers: ['mistral'], match: /^mistral-(large|medium)-?[\\d.-]*$/ },\n]\n\n/**\n * Current families are checked against the Router catalogue and live\n * completions. The 2026-09-30 probes served GPT 6.1 Sol, Astra, Gemini 3.7\n * Flash, and GLM 5.3. Opus/Sonnet 5 returned quota 503, so only their 5.5\n * successors may be featured once Router marks them routeable. DeepSeek V4.1\n * Flash and Kimi K3 remain searchable after quota/upstream failures.\n * An undated future member uses its family floor, not an invented launch date.\n */\nconst RECOMMENDED_FAMILIES: Array<{\n provider: string\n match: RegExp\n minVersion: number[]\n}> = [\n { provider: 'anthropic', match: /^claude-opus-\\d+(?:[-.]\\d+)*$/, minVersion: [5, 5] },\n { provider: 'anthropic', match: /^claude-sonnet-\\d+(?:[-.]\\d+)*$/, minVersion: [5, 5] },\n { provider: 'openai', match: /^gpt-\\d+(?:\\.\\d+)?-sol$/, minVersion: [6] },\n { provider: 'openai', match: /^gpt-\\d+(?:\\.\\d+)?-astra$/, minVersion: [6] },\n { provider: 'google', match: /^gemini-\\d+(?:\\.\\d+)?-flash(?:-preview)?$/, minVersion: [3, 5] },\n { provider: 'zai', match: /^glm-\\d+(?:\\.\\d+)?$/, minVersion: [5, 3] },\n]\n\nconst RECOMMENDATION_WINDOW_MS = 120 * 24 * 60 * 60 * 1000\n\n/** Exact launch dates from vendor announcements, checked 2026-09-30. */\nconst VERIFIED_RELEASE_DATES: Record<string, string> = {\n // https://www.anthropic.com/claude-opus-5-5\n 'claude-opus-5-5': '2026-09-22',\n // https://www.anthropic.com/claude-sonnet-5-5\n 'claude-sonnet-5-5': '2026-09-28',\n // https://developers.openai.com/api/docs/changelog\n 'gpt-6.1-sol': '2026-09-29',\n // https://openai.com/index/safety-overview-gpt-6-astra/\n 'gpt-6-astra': '2026-09-03',\n // https://blog.google/innovation-and-ai/models-and-research/gemini-models/introducing-gemini-3-7-flash/\n 'gemini-3.7-flash': '2026-08-13',\n // https://z.ai/blog/glm-5.3\n 'glm-5.3': '2026-08-14',\n}\n\nfunction releaseDateFromRouter(model: RouterModel): string | undefined {\n const value = model.release_date ?? model.released_at\n if (!value || !/^\\d{4}-\\d{2}-\\d{2}(?:T|$)/.test(value)) return undefined\n const time = Date.parse(value)\n return Number.isFinite(time) ? new Date(time).toISOString() : undefined\n}\n\n/** Families known to support tool calls even when router metadata omits it\n * (dated snapshots often lack the supported_parameters of their parent). */\nconst TOOL_CAPABLE_FAMILY = /^(claude|gpt-\\d|gpt-oss|o[134]|gemini|grok|deepseek|glm|kimi|mistral|ministral|magistral|command|nemotron|llama)/\n\n/** Strip provider prefix, :free suffix, and trailing date stamps. */\nexport function normalizeModelId(id: string): string {\n let tail = id.split('/').pop() ?? id\n tail = tail.replace(/:free$/, '')\n tail = tail.replace(/-\\d{8}$/, '')\n tail = tail.replace(/-\\d{4}-\\d{2}-\\d{2}$/, '')\n return tail\n}\n\n/** All numeric groups in a normalized id, for version comparison. */\nfunction versionOf(normId: string): number[] {\n return (normId.match(/\\d+/g) ?? []).map(Number)\n}\n\nfunction compareVersions(a: number[], b: number[]): number {\n const len = Math.max(a.length, b.length)\n for (let i = 0; i < len; i++) {\n const d = (a[i] ?? -1) - (b[i] ?? -1)\n if (d !== 0) return d\n }\n return 0\n}\n\n/**\n * Read the generation attached to a known model family.\n *\n * This deliberately does not read every number in the id. A parameter count\n * such as `gpt-oss-120b` is not newer than GPT 5.6.\n */\nfunction releaseVersion(id: string): number[] {\n const normalized = normalizeModelId(id).toLowerCase()\n const patterns = [\n /^claude-[a-z0-9]+-(\\d+(?:[.-]\\d+)*)/,\n /^gpt-(\\d+(?:\\.\\d+)*)/,\n /^o(\\d+(?:\\.\\d+)*)/,\n /^gemini-(\\d+(?:\\.\\d+)*)/,\n /^deepseek-v(\\d+(?:\\.\\d+)*)/,\n /^kimi-k(\\d+(?:\\.\\d+)*)/,\n /^glm-(\\d+(?:\\.\\d+)*)/,\n /^grok-(\\d+(?:\\.\\d+)*)/,\n /^mistral-(?:large|medium)-?(\\d+(?:[.-]\\d+)*)/,\n /^qwen-?(\\d+(?:\\.\\d+)*)/,\n /^llama-?(\\d+(?:\\.\\d+)*)/,\n ]\n for (const pattern of patterns) {\n const match = normalized.match(pattern)\n if (match?.[1]) return match[1].split(/[.-]/).map(Number)\n }\n return []\n}\n\n/**\n * Return a copy sorted for a model menu.\n *\n * Providers keep the shared display order. Within each provider, current\n * generations come first across families. Stable ids win ties with previews.\n * Callers can sort separate sections without changing `featured` or defaults.\n */\nexport function sortModelsByFreshness(models: readonly CatalogModel[]): CatalogModel[] {\n return [...models].sort((a, b) => {\n const providerA = normalizeProvider(a.provider)\n const providerB = normalizeProvider(b.provider)\n const providerOrder = providerRank(providerA) - providerRank(providerB)\n if (providerOrder !== 0) return providerOrder\n if (providerA !== providerB) return providerA.localeCompare(providerB)\n\n const generationOrder = compareVersions(releaseVersion(b.id), releaseVersion(a.id))\n if (generationOrder !== 0) return generationOrder\n\n const previewOrder = Number(/preview/i.test(a.id)) - Number(/preview/i.test(b.id))\n if (previewOrder !== 0) return previewOrder\n return a.id.localeCompare(b.id)\n })\n}\n\n/** Lower = preferred representative for an alias group. */\nfunction aliasPenalty(id: string): number {\n let p = 0\n if (id.includes('/')) p += 4\n if (/-\\d{8}$|-\\d{4}-\\d{2}-\\d{2}$/.test(id.replace(/:free$/, ''))) p += 2\n if (id.endsWith(':free')) p += 1\n return p\n}\n\nfunction providerRank(provider: string): number {\n const i = PROVIDER_TIER.indexOf(normalizeProvider(provider))\n return i === -1 ? PROVIDER_TIER.length : i\n}\n\n/**\n * Can this router entry serve a text chat turn?\n *\n * The router lists every routeable endpoint, which is not the same list a chat\n * picker should show: measured against the live catalogue (504 entries), this\n * rejects 35 — image generators, TTS voices, embedding models, and the\n * audio-IN transcription endpoints (`whisper-1`, `gpt-4o-transcribe`, …) that\n * emit text but cannot take a text prompt.\n *\n * A model whose metadata omits either modality list is KEPT. The router is the\n * source of that metadata and it is occasionally sparse; dropping a usable\n * model because a field is missing is the worse failure of the two.\n *\n * Exported because a picker needs the same answer `buildCatalog` uses — the\n * fleet had this predicate copied into a product component, where its narrower\n * spelling let the 10 transcription endpoints through.\n */\nexport function isChatCapableModel(m: RouterModel): boolean {\n const arch = m.architecture\n if (!arch?.input_modalities || !arch?.output_modalities) return true\n return arch.input_modalities.includes('text') && arch.output_modalities.includes('text')\n}\n\nconst isChatModel = isChatCapableModel\n\nfunction isRouteable(m: RouterModel): boolean {\n const routeability = m.routeability\n if (!routeability) return true\n const chatEndpoint = routeability.endpoints?.chat_completions\n if (chatEndpoint?.routeable === false) return false\n if (chatEndpoint?.status !== undefined && chatEndpoint.status !== 'routeable') return false\n if (routeability.routeable === true || routeability.status === 'routeable') return true\n if (routeability.routeable === false) return false\n return routeability.status === undefined\n}\n\n/** Find a catalogue row by direct or provider-prefixed model id. */\nexport function catalogModelForId(\n models: readonly CatalogModel[],\n requestedId: string | undefined,\n): CatalogModel | undefined {\n const requested = requestedId?.trim()\n if (!requested) return undefined\n\n const exact = models.find((model) => model.id === requested)\n if (exact) return exact\n\n const slash = requested.indexOf('/')\n const requestedProvider = slash > 0 ? normalizeProvider(requested.slice(0, slash)) : undefined\n const normalized = normalizeModelId(requested)\n return models.find((model) => {\n if (normalizeModelId(model.id) !== normalized) return false\n return requestedProvider === undefined || normalizeProvider(model.provider) === requestedProvider\n })\n}\n\n/**\n * Reconcile a persisted selection against the live catalogue.\n *\n * The returned id is always a catalogue id once the catalogue has entries.\n * This keeps a removed model from remaining selected while preserving the\n * current value during the brief empty/loading state.\n */\nexport function resolveCatalogModelId(\n models: readonly CatalogModel[],\n selectedId?: string,\n fallbackId?: string,\n): string | undefined {\n if (models.length === 0) return selectedId?.trim() || fallbackId?.trim()\n return catalogModelForId(models, selectedId)?.id\n ?? catalogModelForId(models, fallbackId)?.id\n ?? models[0]?.id\n}\n\n/**\n * Pure catalogue pipeline. `preferredDefault` (typically the MODEL_NAME env\n * var) wins when it survives filtering; otherwise the first featured model.\n */\nexport function buildCatalog(raw: RouterModel[], opts?: { preferredDefault?: string }): ModelCatalog {\n // Filter to chat-capable, routeable, non-specialty models\n const candidates = raw.filter(\n (m) =>\n m.id &&\n isRouteable(m) &&\n isChatModel(m) &&\n !EXCLUDED_ID.test(normalizeModelId(m.id)),\n )\n\n // Dedupe alias groups (dated snapshots, provider prefixes, :free variants).\n // Within a group, merge metadata so the representative keeps the richest\n // supported_parameters claim (snapshots often omit what the parent lists).\n const groups = new Map<string, RouterModel[]>()\n for (const m of candidates) {\n const key = `${providerForModel(m)}::${normalizeModelId(m.id)}`\n const g = groups.get(key)\n if (g) g.push(m)\n else groups.set(key, [m])\n }\n\n const reps: Array<{ model: RouterModel; normId: string; mergedParams: Set<string>; releaseDate?: string }> = []\n for (const group of groups.values()) {\n group.sort((a, b) => aliasPenalty(a.id) - aliasPenalty(b.id) || a.id.length - b.id.length)\n const rep = group[0]!\n const mergedParams = new Set<string>(group.flatMap((m) => m.supported_parameters ?? []))\n const verifiedDate = VERIFIED_RELEASE_DATES[normalizeModelId(rep.id)]\n const releaseDate = group.map(releaseDateFromRouter).find((date) => date !== undefined) ??\n (verifiedDate ? new Date(verifiedDate).toISOString() : undefined)\n reps.push({ model: rep, normId: normalizeModelId(rep.id), mergedParams, releaseDate })\n }\n\n // Resolve the default independently from menu recommendations.\n const defaultCandidateIds: string[] = []\n for (const rule of DEFAULT_CANDIDATE_RULES) {\n const matches = reps.filter(\n (r) =>\n rule.providers.map(normalizeProvider).includes(providerForModel(r.model)) &&\n rule.match.test(r.normId) &&\n !defaultCandidateIds.includes(r.model.id),\n )\n if (!matches.length) continue\n matches.sort(\n (a, b) =>\n compareVersions(versionOf(b.normId), versionOf(a.normId)) ||\n Number(a.normId.includes('preview')) - Number(b.normId.includes('preview')) ||\n a.model.id.length - b.model.id.length,\n )\n defaultCandidateIds.push(matches[0]!.model.id)\n }\n\n const toCatalogModel = (r: (typeof reps)[number]): CatalogModel => {\n const m = r.model\n const provider = providerForModel(m)\n return {\n id: m.id,\n name: m.name ?? m.id,\n provider,\n description: m.description ? m.description.slice(0, 160) : undefined,\n releaseDate: r.releaseDate,\n contextLength: m.context_length,\n pricing:\n m.pricing?.prompt || m.pricing?.completion\n ? { prompt: m.pricing.prompt ?? undefined, completion: m.pricing.completion ?? undefined }\n : undefined,\n supportsTools: r.mergedParams.has('tools') || TOOL_CAPABLE_FAMILY.test(r.normId),\n supportsReasoning: r.mergedParams.has('reasoning') || r.mergedParams.has('include_reasoning'),\n featured: false,\n }\n }\n\n // Family rules retain the intentional default preference. Display order is\n // independent: every catalogue consumer gets provider-grouped freshness,\n // even when it does not render ModelPicker.\n const defaultCandidatesInRuleOrder = defaultCandidateIds\n .map((id) => reps.find((r) => r.model.id === id)!)\n .map(toCatalogModel)\n const sorted = sortModelsByFreshness(reps.map(toCatalogModel))\n const recommendedIds = new Set<string>()\n const recentSince = Date.now() - RECOMMENDATION_WINDOW_MS\n for (const family of RECOMMENDED_FAMILIES) {\n const current = sorted.find((model) =>\n normalizeProvider(model.provider) === family.provider &&\n family.match.test(normalizeModelId(model.id)) &&\n compareVersions(releaseVersion(model.id), family.minVersion) >= 0 &&\n (model.releaseDate === undefined || Date.parse(model.releaseDate) >= recentSince),\n )\n if (current) recommendedIds.add(current.id)\n if (recommendedIds.size >= MAX_RECOMMENDED_MODELS) break\n }\n const models = sorted.map((model) =>\n recommendedIds.has(model.id) ? { ...model, featured: true } : model,\n )\n\n const preferred = opts?.preferredDefault\n const defaultModelId =\n (preferred && models.find((m) => m.id === preferred || normalizeModelId(m.id) === normalizeModelId(preferred))?.id) ||\n defaultCandidatesInRuleOrder.find((m) => m.supportsTools)?.id ||\n models[0]?.id ||\n null\n\n return { defaultModelId, fetchedAt: new Date().toISOString(), models }\n}\n\n// ── Cached fetch ─────────────────────────────────────────────────────────\n\nconst CATALOG_TTL_MS = 5 * 60 * 1000\n\nlet _cache: { catalog: ModelCatalog; at: number } | null = null\n\n/**\n * Fetch the router model list and build the catalogue, with an in-isolate\n * cache (TTL 5 min). On router failure a stale catalogue is served rather\n * than erroring the picker.\n */\nexport async function fetchModelCatalog(cfg: {\n baseUrl: string\n apiKey: string\n preferredDefault?: string\n}): Promise<ModelCatalog> {\n if (_cache && Date.now() - _cache.at < CATALOG_TTL_MS) {\n return _cache.catalog\n }\n try {\n const res = await fetch(`${cfg.baseUrl}/models`, {\n headers: { Authorization: `Bearer ${cfg.apiKey}` },\n })\n if (!res.ok) throw new Error(`Router /models returned ${res.status}`)\n const data = (await res.json()) as { data?: RouterModel[] }\n const catalog = buildCatalog(data.data ?? [], { preferredDefault: cfg.preferredDefault })\n _cache = { catalog, at: Date.now() }\n return catalog\n } catch (err) {\n if (_cache) return _cache.catalog\n throw err\n }\n}\n\n/** Test-only: clear the catalogue cache. */\nexport function __resetCatalogCache(): void {\n _cache = null\n}\n"],"mappings":";AAwEA,IAAM,gBAA0B;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,SAAS,kBAAkB,UAA0B;AACnD,QAAM,aAAa,SAAS,YAAY;AACxC,MAAI,eAAe,aAAc,QAAO;AACxC,MAAI,eAAe,OAAQ,QAAO;AAClC,MAAI,eAAe,OAAQ,QAAO;AAClC,MAAI,eAAe,YAAa,QAAO;AACvC,SAAO;AACT;AAGA,SAAS,iBAAiB,OAA4B;AACpD,QAAM,WAAW,MAAM,aAAa,MAAM,YAAY,MAAM,cAAc;AAC1E,MAAI,SAAU,QAAO,kBAAkB,QAAQ;AAE/C,QAAM,KAAK,iBAAiB,MAAM,EAAE,EAAE,YAAY;AAClD,MAAI,WAAW,KAAK,EAAE,EAAG,QAAO;AAChC,MAAI,gBAAgB,KAAK,EAAE,EAAG,QAAO;AACrC,MAAI,WAAW,KAAK,EAAE,EAAG,QAAO;AAChC,MAAI,SAAS,KAAK,EAAE,EAAG,QAAO;AAC9B,MAAI,aAAa,KAAK,EAAE,EAAG,QAAO;AAClC,MAAI,SAAS,KAAK,EAAE,EAAG,QAAO;AAC9B,MAAI,QAAQ,KAAK,EAAE,EAAG,QAAO;AAC7B,MAAI,WAAW,KAAK,EA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,GAAG;AAAA,IACnD,CAAC;AACD,QAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,2BAA2B,IAAI,MAAM,EAAE;AACpE,UAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,UAAM,UAAU,aAAa,KAAK,QAAQ,CAAC,GAAG,EAAE,kBAAkB,IAAI,iBAAiB,CAAC;AACxF,aAAS,EAAE,SAAS,IAAI,KAAK,IAAI,EAAE;AACnC,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,OAAQ,QAAO,OAAO;AAC1B,UAAM;AAAA,EACR;AACF;AAGO,SAAS,sBAA4B;AAC1C,WAAS;AACX;","names":[]}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
OVERLAY_SHADOW,
|
|
3
3
|
PopoverSurface,
|
|
4
4
|
usePopover
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-5BDSNHWW.js";
|
|
6
6
|
import {
|
|
7
7
|
UNTITLED_SESSION_LABEL,
|
|
8
8
|
mergeSessionPages,
|
|
@@ -812,4 +812,4 @@ export {
|
|
|
812
812
|
formatSessionTimestamp,
|
|
813
813
|
SessionHistoryPanel
|
|
814
814
|
};
|
|
815
|
-
//# sourceMappingURL=chunk-
|
|
815
|
+
//# sourceMappingURL=chunk-BPSRJTJG.js.map
|
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
pickerRootClass,
|
|
12
12
|
quietPickerTriggerClass,
|
|
13
13
|
usePopover
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-5BDSNHWW.js";
|
|
15
15
|
import {
|
|
16
16
|
filterCommandPaletteItems
|
|
17
17
|
} from "./chunk-SJWIZT7B.js";
|
|
@@ -323,7 +323,7 @@ import {
|
|
|
323
323
|
} from "react";
|
|
324
324
|
import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
325
325
|
function createLazyMentionEditor() {
|
|
326
|
-
return lazy(() => import("./mention-editor-
|
|
326
|
+
return lazy(() => import("./mention-editor-BCLZUAF7.js").then((m) => m.loadMentionEditor()));
|
|
327
327
|
}
|
|
328
328
|
var IS_APPLE_PLATFORM = typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/i.test(navigator.platform);
|
|
329
329
|
function SendGlyph({ className }) {
|
|
@@ -1888,4 +1888,4 @@ export {
|
|
|
1888
1888
|
ComposerModeControls,
|
|
1889
1889
|
EntryComposer
|
|
1890
1890
|
};
|
|
1891
|
-
//# sourceMappingURL=chunk-
|
|
1891
|
+
//# sourceMappingURL=chunk-CPL7LLO5.js.map
|
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
PopoverSurface,
|
|
24
24
|
usePending,
|
|
25
25
|
usePopover
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-5BDSNHWW.js";
|
|
27
27
|
import {
|
|
28
28
|
filterCommandPaletteItems,
|
|
29
29
|
groupCommandPaletteItems
|
|
@@ -6544,4 +6544,4 @@ export {
|
|
|
6544
6544
|
useThinkingSeconds,
|
|
6545
6545
|
ChatMessages
|
|
6546
6546
|
};
|
|
6547
|
-
//# sourceMappingURL=chunk-
|
|
6547
|
+
//# sourceMappingURL=chunk-ZNSR7RSQ.js.map
|
|
@@ -10,8 +10,8 @@ import {
|
|
|
10
10
|
} from "./chunk-L7MB2LLM.js";
|
|
11
11
|
import {
|
|
12
12
|
PopoverSurface
|
|
13
|
-
} from "./chunk-
|
|
14
|
-
import "./chunk-
|
|
13
|
+
} from "./chunk-5BDSNHWW.js";
|
|
14
|
+
import "./chunk-7YA4QNTU.js";
|
|
15
15
|
|
|
16
16
|
// src/web-react/mention-editor.tsx
|
|
17
17
|
import { useEffect as useEffect2, useId, useRef as useRef2, useState as useState2 } from "react";
|
|
@@ -524,4 +524,4 @@ export {
|
|
|
524
524
|
loadMentionEditor,
|
|
525
525
|
loadTiptapModules
|
|
526
526
|
};
|
|
527
|
-
//# sourceMappingURL=mention-editor-
|
|
527
|
+
//# sourceMappingURL=mention-editor-BCLZUAF7.js.map
|
package/dist/runtime/index.js
CHANGED
|
@@ -12,10 +12,10 @@
|
|
|
12
12
|
* → rank (provider tier, current generation) → recommend (current families)
|
|
13
13
|
* → default (env override or preferred family)
|
|
14
14
|
*
|
|
15
|
-
* The router is the authority for
|
|
16
|
-
* release dates
|
|
17
|
-
*
|
|
18
|
-
* models stay
|
|
15
|
+
* The router is the authority for routeability. Its current response has no
|
|
16
|
+
* release dates, so exact vendor-announced dates supplement it for known
|
|
17
|
+
* models. Undated newer models use a conservative family floor. Other
|
|
18
|
+
* routeable models stay available through search and explicit browsing.
|
|
19
19
|
*/
|
|
20
20
|
export interface RouterModel {
|
|
21
21
|
id: string;
|
|
@@ -54,7 +54,7 @@ export interface CatalogModel {
|
|
|
54
54
|
name: string;
|
|
55
55
|
provider: string;
|
|
56
56
|
description?: string;
|
|
57
|
-
/** Router-supplied release date
|
|
57
|
+
/** Router-supplied or vendor-verified release date; never inferred from an id. */
|
|
58
58
|
releaseDate?: string;
|
|
59
59
|
contextLength?: number;
|
|
60
60
|
pricing?: {
|
|
@@ -38,7 +38,7 @@ import {
|
|
|
38
38
|
} from "../chunk-TY2DALJG.js";
|
|
39
39
|
import {
|
|
40
40
|
useInfiniteScroll
|
|
41
|
-
} from "../chunk-
|
|
41
|
+
} from "../chunk-BPSRJTJG.js";
|
|
42
42
|
import {
|
|
43
43
|
CheckGlyph,
|
|
44
44
|
ChevronDown,
|
|
@@ -48,9 +48,9 @@ import {
|
|
|
48
48
|
PopoverSurface,
|
|
49
49
|
ProviderLogo,
|
|
50
50
|
usePopover
|
|
51
|
-
} from "../chunk-
|
|
51
|
+
} from "../chunk-5BDSNHWW.js";
|
|
52
52
|
import "../chunk-SJWIZT7B.js";
|
|
53
|
-
import "../chunk-
|
|
53
|
+
import "../chunk-7YA4QNTU.js";
|
|
54
54
|
|
|
55
55
|
// src/studio-react/use-studio-generations.ts
|
|
56
56
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
package/dist/web-react/index.js
CHANGED
|
@@ -129,14 +129,14 @@ import {
|
|
|
129
129
|
withoutRecordGridCreated,
|
|
130
130
|
withoutRecordGridRemoved,
|
|
131
131
|
withoutRecordGridUpdate
|
|
132
|
-
} from "../chunk-
|
|
132
|
+
} from "../chunk-ZNSR7RSQ.js";
|
|
133
133
|
import {
|
|
134
134
|
SessionHistoryPanel,
|
|
135
135
|
formatSessionTimestamp,
|
|
136
136
|
useInfiniteScroll,
|
|
137
137
|
useSessionActions,
|
|
138
138
|
useSessionHistory
|
|
139
|
-
} from "../chunk-
|
|
139
|
+
} from "../chunk-BPSRJTJG.js";
|
|
140
140
|
import {
|
|
141
141
|
MENTION_PILL_CLASS
|
|
142
142
|
} from "../chunk-3HUFJ5LO.js";
|
|
@@ -169,7 +169,7 @@ import {
|
|
|
169
169
|
renamePastedImages,
|
|
170
170
|
useComposerAttachments,
|
|
171
171
|
useDictation
|
|
172
|
-
} from "../chunk-
|
|
172
|
+
} from "../chunk-CPL7LLO5.js";
|
|
173
173
|
import "../chunk-L7MB2LLM.js";
|
|
174
174
|
import {
|
|
175
175
|
DEFAULT_EFFORT_LEVELS,
|
|
@@ -187,7 +187,7 @@ import {
|
|
|
187
187
|
reconcileEffortLevels,
|
|
188
188
|
usePending,
|
|
189
189
|
usePopover
|
|
190
|
-
} from "../chunk-
|
|
190
|
+
} from "../chunk-5BDSNHWW.js";
|
|
191
191
|
import {
|
|
192
192
|
tabTerminalConnectionId,
|
|
193
193
|
useSandboxTerminalConnection
|
|
@@ -202,7 +202,7 @@ import {
|
|
|
202
202
|
ATTACHMENT_ACCEPT
|
|
203
203
|
} from "../chunk-NU7QSZBR.js";
|
|
204
204
|
import "../chunk-MCYJON3F.js";
|
|
205
|
-
import "../chunk-
|
|
205
|
+
import "../chunk-7YA4QNTU.js";
|
|
206
206
|
import {
|
|
207
207
|
attachmentInputToPart,
|
|
208
208
|
attachmentKindForMime,
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { WorkspaceAppRecord } from './index';
|
|
2
|
+
export interface WorkspaceAppDataEntry {
|
|
3
|
+
value: string;
|
|
4
|
+
revision: number;
|
|
5
|
+
}
|
|
6
|
+
export declare class WorkspaceAppDataConflict extends Error {
|
|
7
|
+
constructor();
|
|
8
|
+
}
|
|
9
|
+
export interface WorkspaceAppDataHostOptions {
|
|
10
|
+
/** Product-authorized registration for the current viewer. */
|
|
11
|
+
app: Pick<WorkspaceAppRecord, 'id' | 'previewUrl' | 'status'>;
|
|
12
|
+
frame: HTMLIFrameElement;
|
|
13
|
+
/** Product callbacks are bound to the authorized business and app namespace. */
|
|
14
|
+
read(key: string): Promise<WorkspaceAppDataEntry | null>;
|
|
15
|
+
/** Null creates only if absent; a revision updates only that version. */
|
|
16
|
+
write(key: string, value: string, expectedRevision: number | null): Promise<{
|
|
17
|
+
revision: number;
|
|
18
|
+
}>;
|
|
19
|
+
remove(key: string, expectedRevision: number): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
export interface WorkspaceAppDataHost {
|
|
22
|
+
dispose(): void;
|
|
23
|
+
}
|
|
24
|
+
export interface WorkspaceAppDataClientOptions {
|
|
25
|
+
appId: string;
|
|
26
|
+
/** Exact authenticated product origin, provided by the product. */
|
|
27
|
+
parentOrigin: string;
|
|
28
|
+
}
|
|
29
|
+
export interface WorkspaceAppDataClient {
|
|
30
|
+
ready(): Promise<void>;
|
|
31
|
+
read(key: string): Promise<WorkspaceAppDataEntry | null>;
|
|
32
|
+
write(key: string, value: string, expectedRevision: number | null): Promise<{
|
|
33
|
+
revision: number;
|
|
34
|
+
}>;
|
|
35
|
+
remove(key: string, expectedRevision: number): Promise<void>;
|
|
36
|
+
dispose(): void;
|
|
37
|
+
}
|
|
38
|
+
/** Bind one registered preview to a product-authorized data adapter. */
|
|
39
|
+
export declare function createWorkspaceAppDataHost(options: WorkspaceAppDataHostOptions): WorkspaceAppDataHost;
|
|
40
|
+
/** Use inside a registered preview; no product credential crosses the frame. */
|
|
41
|
+
export declare function createWorkspaceAppDataClient(options: WorkspaceAppDataClientOptions): WorkspaceAppDataClient;
|
|
@@ -70,3 +70,5 @@ export type WorkspaceAppBuilderInstructionsOptions = {
|
|
|
70
70
|
};
|
|
71
71
|
/** Portable instructions for an agent profile that builds workspace apps. */
|
|
72
72
|
export declare function workspaceAppBuilderInstructions(options: WorkspaceAppBuilderInstructionsOptions): string[];
|
|
73
|
+
export { WorkspaceAppDataConflict, createWorkspaceAppDataClient, createWorkspaceAppDataHost, } from './data-bridge';
|
|
74
|
+
export type { WorkspaceAppDataClient, WorkspaceAppDataClientOptions, WorkspaceAppDataEntry, WorkspaceAppDataHost, WorkspaceAppDataHostOptions, } from './data-bridge';
|
|
@@ -1,3 +1,203 @@
|
|
|
1
|
+
// src/workspace-apps/data-bridge.ts
|
|
2
|
+
var protocol = "tangle.workspace-app-data.v1";
|
|
3
|
+
var maxBytes = 65536;
|
|
4
|
+
var maxPending = 16;
|
|
5
|
+
var keyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
|
|
6
|
+
var idPattern = /^[A-Za-z0-9_-]{1,80}$/;
|
|
7
|
+
var WorkspaceAppDataConflict = class extends Error {
|
|
8
|
+
constructor() {
|
|
9
|
+
super("Workspace app data changed. Read it again before saving.");
|
|
10
|
+
this.name = "WorkspaceAppDataConflict";
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
function object(value) {
|
|
14
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
15
|
+
}
|
|
16
|
+
function key(value) {
|
|
17
|
+
return typeof value === "string" && keyPattern.test(value) && value !== "." && value !== "..";
|
|
18
|
+
}
|
|
19
|
+
function revision(value) {
|
|
20
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
21
|
+
}
|
|
22
|
+
function bounded(value) {
|
|
23
|
+
return typeof value === "string" && value.length <= maxBytes && new TextEncoder().encode(value).byteLength <= maxBytes;
|
|
24
|
+
}
|
|
25
|
+
function appId(value) {
|
|
26
|
+
if (!idPattern.test(value)) throw new Error("Invalid workspace app ID");
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
function origin(value) {
|
|
30
|
+
const url = new URL(value);
|
|
31
|
+
if (url.origin !== value || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname))) {
|
|
32
|
+
throw new Error("Invalid workspace app data origin");
|
|
33
|
+
}
|
|
34
|
+
return url.origin;
|
|
35
|
+
}
|
|
36
|
+
function packet(value) {
|
|
37
|
+
return object(value) && value.protocol === protocol && typeof value.appId === "string" && typeof value.requestId === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value.requestId) && typeof value.action === "string" && ["ready", "read", "write", "remove"].includes(value.action);
|
|
38
|
+
}
|
|
39
|
+
function createWorkspaceAppDataHost(options) {
|
|
40
|
+
const { app, frame } = options;
|
|
41
|
+
appId(app.id);
|
|
42
|
+
if (app.status !== "ready") throw new Error("Workspace app is not ready");
|
|
43
|
+
const preview = new URL(app.previewUrl);
|
|
44
|
+
const previewOrigin = origin(preview.origin);
|
|
45
|
+
if (preview.protocol !== "https:" || preview.username || preview.password || preview.search || preview.hash || new URL(frame.src).href !== preview.href) {
|
|
46
|
+
throw new Error("Iframe does not render the registered workspace app preview");
|
|
47
|
+
}
|
|
48
|
+
let closed = false;
|
|
49
|
+
let active = 0;
|
|
50
|
+
let messagesLeft = 64;
|
|
51
|
+
let nextWindow = Date.now() + 1e3;
|
|
52
|
+
const onMessage = (event) => {
|
|
53
|
+
if (closed || event.source !== frame.contentWindow || event.origin !== previewOrigin || !packet(event.data) || event.data.appId !== app.id) return;
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
if (now >= nextWindow) {
|
|
56
|
+
messagesLeft = 64;
|
|
57
|
+
nextWindow = now + 1e3;
|
|
58
|
+
}
|
|
59
|
+
if (messagesLeft-- <= 0) return;
|
|
60
|
+
const message = event.data;
|
|
61
|
+
const reply = (result) => {
|
|
62
|
+
if (closed || event.source !== frame.contentWindow) return;
|
|
63
|
+
frame.contentWindow?.postMessage({
|
|
64
|
+
protocol,
|
|
65
|
+
appId: app.id,
|
|
66
|
+
requestId: message.requestId,
|
|
67
|
+
action: message.action,
|
|
68
|
+
...result
|
|
69
|
+
}, previewOrigin);
|
|
70
|
+
};
|
|
71
|
+
if (message.action === "ready") {
|
|
72
|
+
reply({ ok: true });
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (!key(message.key) || message.action === "write" && (!bounded(message.value) || !(message.expectedRevision === null || revision(message.expectedRevision))) || message.action === "remove" && !revision(message.expectedRevision)) {
|
|
76
|
+
reply({ ok: false, error: "invalid" });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (active >= maxPending) {
|
|
80
|
+
reply({ ok: false, error: "unavailable" });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
active += 1;
|
|
84
|
+
const checkedKey = message.key;
|
|
85
|
+
void (async () => {
|
|
86
|
+
try {
|
|
87
|
+
if (message.action === "read") {
|
|
88
|
+
const entry = await options.read(checkedKey);
|
|
89
|
+
if (entry !== null && (!bounded(entry.value) || !revision(entry.revision))) throw new Error("Invalid entry");
|
|
90
|
+
reply({ ok: true, entry });
|
|
91
|
+
} else if (message.action === "write") {
|
|
92
|
+
const result = await options.write(checkedKey, message.value, message.expectedRevision);
|
|
93
|
+
if (!revision(result.revision)) throw new Error("Invalid revision");
|
|
94
|
+
reply({ ok: true, revision: result.revision });
|
|
95
|
+
} else {
|
|
96
|
+
await options.remove(checkedKey, message.expectedRevision);
|
|
97
|
+
reply({ ok: true });
|
|
98
|
+
}
|
|
99
|
+
} catch (error) {
|
|
100
|
+
reply({ ok: false, error: error instanceof WorkspaceAppDataConflict ? "conflict" : "unavailable" });
|
|
101
|
+
} finally {
|
|
102
|
+
active -= 1;
|
|
103
|
+
}
|
|
104
|
+
})();
|
|
105
|
+
};
|
|
106
|
+
window.addEventListener("message", onMessage);
|
|
107
|
+
return { dispose() {
|
|
108
|
+
closed = true;
|
|
109
|
+
window.removeEventListener("message", onMessage);
|
|
110
|
+
} };
|
|
111
|
+
}
|
|
112
|
+
function createWorkspaceAppDataClient(options) {
|
|
113
|
+
const id = appId(options.appId);
|
|
114
|
+
const parentOrigin = origin(options.parentOrigin);
|
|
115
|
+
if (window.parent === window) throw new Error("Workspace app data requires an embedded preview");
|
|
116
|
+
const pending = /* @__PURE__ */ new Map();
|
|
117
|
+
let closed = false;
|
|
118
|
+
let readyPromise;
|
|
119
|
+
const onMessage = (event) => {
|
|
120
|
+
if (closed || event.source !== window.parent || event.origin !== parentOrigin || !packet(event.data) || event.data.appId !== id || typeof event.data.ok !== "boolean") return;
|
|
121
|
+
const waiting = pending.get(event.data.requestId);
|
|
122
|
+
if (!waiting || waiting.action !== event.data.action) return;
|
|
123
|
+
pending.delete(event.data.requestId);
|
|
124
|
+
clearTimeout(waiting.timeout);
|
|
125
|
+
if (event.data.ok) waiting.resolve(event.data);
|
|
126
|
+
else waiting.reject(event.data.error === "conflict" ? new WorkspaceAppDataConflict() : new Error("Workspace app data unavailable"));
|
|
127
|
+
};
|
|
128
|
+
window.addEventListener("message", onMessage);
|
|
129
|
+
const send = (action, fields = {}, timeoutMs = 1e4) => {
|
|
130
|
+
if (closed) return Promise.reject(new Error("Workspace app data client is closed"));
|
|
131
|
+
if (pending.size >= maxPending) return Promise.reject(new Error("Too many workspace app data requests"));
|
|
132
|
+
const requestId = crypto.randomUUID();
|
|
133
|
+
return new Promise((resolve, reject) => {
|
|
134
|
+
const timeout = setTimeout(() => {
|
|
135
|
+
pending.delete(requestId);
|
|
136
|
+
reject(new Error("Workspace app data timed out"));
|
|
137
|
+
}, timeoutMs);
|
|
138
|
+
pending.set(requestId, { action, resolve, reject, timeout });
|
|
139
|
+
window.parent.postMessage({ protocol, appId: id, requestId, action, ...fields }, parentOrigin);
|
|
140
|
+
});
|
|
141
|
+
};
|
|
142
|
+
const ready = () => {
|
|
143
|
+
if (readyPromise) return readyPromise;
|
|
144
|
+
readyPromise = new Promise((resolve, reject) => {
|
|
145
|
+
const deadline = Date.now() + 1e4;
|
|
146
|
+
const attempt = () => {
|
|
147
|
+
if (closed) {
|
|
148
|
+
reject(new Error("Workspace app data client is closed"));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (Date.now() >= deadline) {
|
|
152
|
+
reject(new Error("Workspace app data host did not become ready"));
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
void send("ready", {}, 300).then(() => resolve(), () => setTimeout(attempt, 200));
|
|
156
|
+
};
|
|
157
|
+
attempt();
|
|
158
|
+
}).catch((error) => {
|
|
159
|
+
readyPromise = void 0;
|
|
160
|
+
throw error;
|
|
161
|
+
});
|
|
162
|
+
return readyPromise;
|
|
163
|
+
};
|
|
164
|
+
return {
|
|
165
|
+
ready,
|
|
166
|
+
async read(value) {
|
|
167
|
+
if (!key(value)) throw new Error("Invalid workspace app data key");
|
|
168
|
+
await ready();
|
|
169
|
+
const response = await send("read", { key: value });
|
|
170
|
+
if (response.entry !== null && (!object(response.entry) || !bounded(response.entry.value) || !revision(response.entry.revision))) {
|
|
171
|
+
throw new Error("Invalid workspace app data response");
|
|
172
|
+
}
|
|
173
|
+
return response.entry ?? null;
|
|
174
|
+
},
|
|
175
|
+
async write(value, data, expectedRevision) {
|
|
176
|
+
if (!key(value) || !bounded(data) || !(expectedRevision === null || revision(expectedRevision))) {
|
|
177
|
+
throw new Error("Invalid workspace app data write");
|
|
178
|
+
}
|
|
179
|
+
await ready();
|
|
180
|
+
const response = await send("write", { key: value, value: data, expectedRevision });
|
|
181
|
+
if (!revision(response.revision)) throw new Error("Invalid workspace app data response");
|
|
182
|
+
return { revision: response.revision };
|
|
183
|
+
},
|
|
184
|
+
async remove(value, expectedRevision) {
|
|
185
|
+
if (!key(value) || !revision(expectedRevision)) throw new Error("Invalid workspace app data remove");
|
|
186
|
+
await ready();
|
|
187
|
+
await send("remove", { key: value, expectedRevision });
|
|
188
|
+
},
|
|
189
|
+
dispose() {
|
|
190
|
+
closed = true;
|
|
191
|
+
window.removeEventListener("message", onMessage);
|
|
192
|
+
for (const waiting of pending.values()) {
|
|
193
|
+
clearTimeout(waiting.timeout);
|
|
194
|
+
waiting.reject(new Error("Workspace app data client is closed"));
|
|
195
|
+
}
|
|
196
|
+
pending.clear();
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
1
201
|
// src/workspace-apps/index.ts
|
|
2
202
|
function nonempty(value, field) {
|
|
3
203
|
if (typeof value !== "string" || !value.trim() || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
@@ -110,7 +310,10 @@ function workspaceAppBuilderInstructions(options) {
|
|
|
110
310
|
];
|
|
111
311
|
}
|
|
112
312
|
export {
|
|
313
|
+
WorkspaceAppDataConflict,
|
|
113
314
|
confirmWorkspaceAppReady,
|
|
315
|
+
createWorkspaceAppDataClient,
|
|
316
|
+
createWorkspaceAppDataHost,
|
|
114
317
|
refreshWorkspaceAppPreview,
|
|
115
318
|
workspaceAppBuilderInstructions,
|
|
116
319
|
workspaceAppFromPreviewLink
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/workspace-apps/index.ts"],"sourcesContent":["/** A sandbox app registered in one product workspace. Products persist and authorize these rows. */\nexport interface WorkspaceAppRecord {\n id: string\n workspaceId: string\n name: string\n sandboxId: string\n previewId: string\n port: number\n previewUrl: string\n status: 'starting' | 'ready' | 'unavailable'\n createdAt: string\n updatedAt: string\n}\n\n/** Structural shape returned by the Sandbox SDK previewLinks API. */\nexport interface WorkspaceAppPreviewLink {\n previewId: string\n sandboxId: string\n port: number\n protocol: 'tcp' | 'udp'\n hostname: string\n url: string\n status: 'provisioning' | 'ready' | 'error' | 'disabled'\n}\n\nexport interface WorkspaceAppIdentity {\n /** Assigned by the product, stable across preview updates and deliberate republishes. */\n id: string\n /** Taken from the authenticated route or session, never agent tool arguments. */\n workspaceId: string\n /** Current box resolved by the product from that workspace or session. */\n sandboxId: string\n name: string\n /** Preserve this when republishing the same app onto a replacement sandbox. */\n createdAt?: string\n updatedAt?: string\n}\n\nfunction nonempty(value: string, field: string): string {\n if (typeof value !== 'string' || !value.trim() || /[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error('Invalid workspace app ' + field)\n }\n return value.trim()\n}\n\nfunction checkedLink(link: WorkspaceAppPreviewLink, sandboxId: string): void {\n if (link.sandboxId !== sandboxId) {\n throw new Error('Preview link belongs to another sandbox')\n }\n nonempty(link.previewId, 'previewId')\n if (link.protocol !== 'tcp') throw new Error('Workspace app preview must use TCP')\n if (!Number.isInteger(link.port) || link.port < 1 || link.port > 65535) {\n throw new Error('Invalid workspace app port')\n }\n if (!['provisioning', 'ready', 'error', 'disabled'].includes(link.status)) {\n throw new Error('Invalid workspace app preview status')\n }\n let url: URL\n try {\n url = new URL(link.url)\n } catch {\n throw new Error('Invalid workspace app preview URL')\n }\n if (\n url.protocol !== 'https:' ||\n !url.hostname ||\n url.hostname !== link.hostname ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n ) {\n throw new Error('Invalid workspace app preview URL')\n }\n}\n\nfunction appStatus(status: WorkspaceAppPreviewLink['status']): WorkspaceAppRecord['status'] {\n if (status === 'ready' || status === 'provisioning') return 'starting'\n return 'unavailable'\n}\n\n/**\n * Build a durable registration from a preview link created on the box that\n * the authenticated product request resolved. The product owns row identity,\n * access policy, persistence, and the decision to publish.\n */\nexport function workspaceAppFromPreviewLink(\n identity: WorkspaceAppIdentity,\n link: WorkspaceAppPreviewLink,\n): WorkspaceAppRecord {\n const sandboxId = nonempty(identity.sandboxId, 'sandboxId')\n checkedLink(link, sandboxId)\n const timestamp = identity.updatedAt ?? new Date().toISOString()\n return {\n id: nonempty(identity.id, 'id'),\n workspaceId: nonempty(identity.workspaceId, 'workspaceId'),\n name: nonempty(identity.name, 'name'),\n sandboxId,\n previewId: link.previewId,\n port: link.port,\n previewUrl: link.url,\n status: appStatus(link.status),\n createdAt: identity.createdAt ?? timestamp,\n updatedAt: timestamp,\n }\n}\n\nexport interface WorkspaceAppHttpProof {\n /** The exact trusted SDK preview URL requested by the server. */\n previewUrl: string\n status: number\n contentType: string\n /** Number of bytes read from the response body, excluding headers. */\n bodyBytes: number\n checkedAt: string\n}\n\n/**\n * Mark an app ready only after the host fetched its HTML over the trusted\n * preview URL. The host owns the request timeout, redirect and credential\n * policy, authorization, and compare-and-swap storage update.\n */\nexport function confirmWorkspaceAppReady(\n app: WorkspaceAppRecord,\n proof: WorkspaceAppHttpProof,\n): WorkspaceAppRecord {\n if (\n proof.previewUrl !== app.previewUrl ||\n proof.status !== 200 ||\n !/^text\\/html(?:\\s*;|\\s*$)/i.test(proof.contentType) ||\n !Number.isInteger(proof.bodyBytes) ||\n proof.bodyBytes < 1 ||\n !Number.isFinite(Date.parse(proof.checkedAt))\n ) {\n throw new Error('Workspace app HTML preview is not ready')\n }\n return { ...app, status: 'ready', updatedAt: proof.checkedAt }\n}\n\n/** Refresh delivery state without changing which sandbox service this app means. */\nexport function refreshWorkspaceAppPreview(\n app: WorkspaceAppRecord,\n link: WorkspaceAppPreviewLink,\n updatedAt = new Date().toISOString(),\n): WorkspaceAppRecord {\n checkedLink(link, app.sandboxId)\n if (link.previewId !== app.previewId || link.port !== app.port) {\n throw new Error('Preview link does not match workspace app')\n }\n return {\n ...app,\n previewUrl: link.url,\n status: appStatus(link.status),\n updatedAt,\n }\n}\n\nexport type WorkspaceAppBuilderInstructionsOptions =\n | {\n /** Host tool that writes the registration after creating a trusted preview. */\n publishTool: string\n /** Optional host tool for finding app IDs the builder may update. */\n listTool?: string\n manifestPath?: never\n }\n | {\n /** Host-scoped manifest the builder writes after creating runnable projects. */\n manifestPath: string\n publishTool?: never\n listTool?: never\n }\n\nfunction toolName(value: string): string {\n if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(value)) {\n throw new Error('Invalid workspace app tool name')\n }\n return value\n}\n\nfunction builderManifestPath(value: string): string {\n if (\n !/^[A-Za-z0-9._-]+(?:[/][A-Za-z0-9._-]+)*$/.test(value) ||\n value.split('/').some(segment => segment === '..' || segment === '.')\n ) {\n throw new Error('Invalid workspace app manifest path')\n }\n return value\n}\n\n/** Portable instructions for an agent profile that builds workspace apps. */\nexport function workspaceAppBuilderInstructions(\n options: WorkspaceAppBuilderInstructionsOptions,\n): string[] {\n const common = [\n 'Build a working HTTP application in the current sandbox when the user asks for an app.',\n 'Keep the same app ID for later revisions of that app.',\n 'Treat a preview link as public. Do not embed secrets or private business facts in client code or responses.',\n 'Read real business data through authorized product APIs. Do not fabricate records to make the app look complete.',\n 'Report the app as available only after the host confirms its preview is ready.',\n ] as const\n if (options.manifestPath !== undefined) {\n const path = builderManifestPath(options.manifestPath)\n return [\n common[0],\n 'Inspect the existing app projects and manifest before creating or updating an app.',\n 'Keep each runnable project under apps/<id> relative to the sandbox working directory. Give it a package.json dev script; its HTTP server must listen on 0.0.0.0 and use PORT when supplied.',\n 'Write ' + path + ' as JSON with exactly an apps array of { id, name, projectPath } records; each projectPath is apps/<id>.',\n 'Do not put URLs, credentials, tokens, sandbox IDs, or preview IDs in that manifest.',\n 'The host reads this manifest and owns server launch, port selection, preview creation, registration, and access policy.',\n ...common.slice(1),\n ]\n }\n const publish = toolName(options.publishTool)\n const list = options.listTool ? toolName(options.listTool) : undefined\n return [\n common[0],\n ...(list ? ['Use ' + list + ' to inspect the existing apps before creating or updating one.'] : []),\n 'Start its server on 0.0.0.0 using an available, unclaimed port.',\n 'Call ' + publish + ' with the app name, stable app ID when updating, and listening port.',\n 'Use the host tool result as the source of the registered app URL and status; never invent a preview URL.',\n ...common.slice(1),\n ]\n}\n"],"mappings":";AAsCA,SAAS,SAAS,OAAe,OAAuB;AACtD,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,wBAAwB,KAAK,KAAK,GAAG;AACrF,UAAM,IAAI,MAAM,2BAA2B,KAAK;AAAA,EAClD;AACA,SAAO,MAAM,KAAK;AACpB;AAE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ACrD,WAAO;AAAA,MACL,OAAO,CAAC;AAAA,MACR;AAAA,MACA;AAAA,MACA,WAAW,OAAO;AAAA,MAClB;AAAA,MACA;AAAA,MACA,GAAG,OAAO,MAAM,CAAC;AAAA,IACnB;AAAA,EACF;AACA,QAAM,UAAU,SAAS,QAAQ,WAAW;AAC5C,QAAM,OAAO,QAAQ,WAAW,SAAS,QAAQ,QAAQ,IAAI;AAC7D,SAAO;AAAA,IACL,OAAO,CAAC;AAAA,IACR,GAAI,OAAO,CAAC,SAAS,OAAO,gEAAgE,IAAI,CAAC;AAAA,IACjG;AAAA,IACA,UAAU,UAAU;AAAA,IACpB;AAAA,IACA,GAAG,OAAO,MAAM,CAAC;AAAA,EACnB;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/workspace-apps/data-bridge.ts","../../src/workspace-apps/index.ts"],"sourcesContent":["import type { WorkspaceAppRecord } from './index'\n\nconst protocol = 'tangle.workspace-app-data.v1'\nconst maxBytes = 65_536\nconst maxPending = 16\nconst keyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/\nconst idPattern = /^[A-Za-z0-9_-]{1,80}$/\n\nexport interface WorkspaceAppDataEntry { value: string; revision: number }\nexport class WorkspaceAppDataConflict extends Error {\n constructor() {\n super('Workspace app data changed. Read it again before saving.')\n this.name = 'WorkspaceAppDataConflict'\n }\n}\nexport interface WorkspaceAppDataHostOptions {\n /** Product-authorized registration for the current viewer. */\n app: Pick<WorkspaceAppRecord, 'id' | 'previewUrl' | 'status'>\n frame: HTMLIFrameElement\n /** Product callbacks are bound to the authorized business and app namespace. */\n read(key: string): Promise<WorkspaceAppDataEntry | null>\n /** Null creates only if absent; a revision updates only that version. */\n write(key: string, value: string, expectedRevision: number | null): Promise<{ revision: number }>\n remove(key: string, expectedRevision: number): Promise<void>\n}\nexport interface WorkspaceAppDataHost { dispose(): void }\nexport interface WorkspaceAppDataClientOptions {\n appId: string\n /** Exact authenticated product origin, provided by the product. */\n parentOrigin: string\n}\nexport interface WorkspaceAppDataClient {\n ready(): Promise<void>\n read(key: string): Promise<WorkspaceAppDataEntry | null>\n write(key: string, value: string, expectedRevision: number | null): Promise<{ revision: number }>\n remove(key: string, expectedRevision: number): Promise<void>\n dispose(): void\n}\n\ntype Action = 'ready' | 'read' | 'write' | 'remove'\ntype Packet = {\n protocol: typeof protocol\n appId: string\n requestId: string\n action: Action\n key?: string\n value?: string\n expectedRevision?: number | null\n ok?: boolean\n entry?: WorkspaceAppDataEntry | null\n revision?: number\n error?: 'invalid' | 'conflict' | 'unavailable'\n}\nfunction object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\nfunction key(value: unknown): value is string {\n return typeof value === 'string' && keyPattern.test(value) && value !== '.' && value !== '..'\n}\nfunction revision(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\nfunction bounded(value: unknown): value is string {\n return typeof value === 'string' && value.length <= maxBytes && new TextEncoder().encode(value).byteLength <= maxBytes\n}\nfunction appId(value: string): string {\n if (!idPattern.test(value)) throw new Error('Invalid workspace app ID')\n return value\n}\nfunction origin(value: string): string {\n const url = new URL(value)\n if (url.origin !== value || (url.protocol !== 'https:' &&\n !(url.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(url.hostname)))) {\n throw new Error('Invalid workspace app data origin')\n }\n return url.origin\n}\nfunction packet(value: unknown): value is Packet {\n return object(value) && value.protocol === protocol &&\n typeof value.appId === 'string' && typeof value.requestId === 'string' &&\n /^[A-Za-z0-9_-]{1,64}$/.test(value.requestId) &&\n typeof value.action === 'string' && ['ready', 'read', 'write', 'remove'].includes(value.action)\n}\n\n/** Bind one registered preview to a product-authorized data adapter. */\nexport function createWorkspaceAppDataHost(options: WorkspaceAppDataHostOptions): WorkspaceAppDataHost {\n const { app, frame } = options\n appId(app.id)\n if (app.status !== 'ready') throw new Error('Workspace app is not ready')\n const preview = new URL(app.previewUrl)\n const previewOrigin = origin(preview.origin)\n if (preview.protocol !== 'https:' || preview.username || preview.password || preview.search || preview.hash ||\n new URL(frame.src).href !== preview.href) {\n throw new Error('Iframe does not render the registered workspace app preview')\n }\n let closed = false\n let active = 0\n let messagesLeft = 64\n let nextWindow = Date.now() + 1000\n const onMessage = (event: MessageEvent<unknown>): void => {\n if (closed || event.source !== frame.contentWindow || event.origin !== previewOrigin ||\n !packet(event.data) || event.data.appId !== app.id) return\n const now = Date.now()\n if (now >= nextWindow) { messagesLeft = 64; nextWindow = now + 1000 }\n if (messagesLeft-- <= 0) return\n const message = event.data\n const reply = (result: Pick<Packet, 'ok' | 'entry' | 'revision' | 'error'>): void => {\n if (closed || event.source !== frame.contentWindow) return\n frame.contentWindow?.postMessage({\n protocol, appId: app.id, requestId: message.requestId, action: message.action, ...result,\n } satisfies Packet, previewOrigin)\n }\n if (message.action === 'ready') { reply({ ok: true }); return }\n if (!key(message.key) ||\n (message.action === 'write' && (!bounded(message.value) ||\n !(message.expectedRevision === null || revision(message.expectedRevision)))) ||\n (message.action === 'remove' && !revision(message.expectedRevision))) {\n reply({ ok: false, error: 'invalid' }); return\n }\n if (active >= maxPending) { reply({ ok: false, error: 'unavailable' }); return }\n active += 1\n const checkedKey = message.key\n void (async () => {\n try {\n if (message.action === 'read') {\n const entry = await options.read(checkedKey)\n if (entry !== null && (!bounded(entry.value) || !revision(entry.revision))) throw new Error('Invalid entry')\n reply({ ok: true, entry })\n } else if (message.action === 'write') {\n const result = await options.write(checkedKey, message.value as string, message.expectedRevision as number | null)\n if (!revision(result.revision)) throw new Error('Invalid revision')\n reply({ ok: true, revision: result.revision })\n } else {\n await options.remove(checkedKey, message.expectedRevision as number)\n reply({ ok: true })\n }\n } catch (error) {\n reply({ ok: false, error: error instanceof WorkspaceAppDataConflict ? 'conflict' : 'unavailable' })\n } finally { active -= 1 }\n })()\n }\n window.addEventListener('message', onMessage)\n return { dispose() { closed = true; window.removeEventListener('message', onMessage) } }\n}\n\n/** Use inside a registered preview; no product credential crosses the frame. */\nexport function createWorkspaceAppDataClient(options: WorkspaceAppDataClientOptions): WorkspaceAppDataClient {\n const id = appId(options.appId)\n const parentOrigin = origin(options.parentOrigin)\n if (window.parent === window) throw new Error('Workspace app data requires an embedded preview')\n const pending = new Map<string, {\n action: Action\n resolve(value: Packet): void\n reject(error: Error): void\n timeout: ReturnType<typeof setTimeout>\n }>()\n let closed = false\n let readyPromise: Promise<void> | undefined\n const onMessage = (event: MessageEvent<unknown>): void => {\n if (closed || event.source !== window.parent || event.origin !== parentOrigin || !packet(event.data) ||\n event.data.appId !== id || typeof event.data.ok !== 'boolean') return\n const waiting = pending.get(event.data.requestId)\n if (!waiting || waiting.action !== event.data.action) return\n pending.delete(event.data.requestId)\n clearTimeout(waiting.timeout)\n if (event.data.ok) waiting.resolve(event.data)\n else waiting.reject(event.data.error === 'conflict' ? new WorkspaceAppDataConflict() :\n new Error('Workspace app data unavailable'))\n }\n window.addEventListener('message', onMessage)\n const send = (action: Action, fields: Partial<Packet> = {}, timeoutMs = 10_000): Promise<Packet> => {\n if (closed) return Promise.reject(new Error('Workspace app data client is closed'))\n if (pending.size >= maxPending) return Promise.reject(new Error('Too many workspace app data requests'))\n const requestId = crypto.randomUUID()\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => { pending.delete(requestId); reject(new Error('Workspace app data timed out')) }, timeoutMs)\n pending.set(requestId, { action, resolve, reject, timeout })\n window.parent.postMessage({ protocol, appId: id, requestId, action, ...fields } satisfies Packet, parentOrigin)\n })\n }\n const ready = (): Promise<void> => {\n if (readyPromise) return readyPromise\n readyPromise = new Promise<void>((resolve, reject) => {\n const deadline = Date.now() + 10_000\n const attempt = (): void => {\n if (closed) { reject(new Error('Workspace app data client is closed')); return }\n if (Date.now() >= deadline) { reject(new Error('Workspace app data host did not become ready')); return }\n void send('ready', {}, 300).then(() => resolve(), () => setTimeout(attempt, 200))\n }\n attempt()\n }).catch((error: unknown) => { readyPromise = undefined; throw error })\n return readyPromise\n }\n return {\n ready,\n async read(value) {\n if (!key(value)) throw new Error('Invalid workspace app data key')\n await ready()\n const response = await send('read', { key: value })\n if (response.entry !== null && (!object(response.entry) ||\n !bounded(response.entry.value) || !revision(response.entry.revision))) {\n throw new Error('Invalid workspace app data response')\n }\n return response.entry ?? null\n },\n async write(value, data, expectedRevision) {\n if (!key(value) || !bounded(data) || !(expectedRevision === null || revision(expectedRevision))) {\n throw new Error('Invalid workspace app data write')\n }\n await ready()\n const response = await send('write', { key: value, value: data, expectedRevision })\n if (!revision(response.revision)) throw new Error('Invalid workspace app data response')\n return { revision: response.revision }\n },\n async remove(value, expectedRevision) {\n if (!key(value) || !revision(expectedRevision)) throw new Error('Invalid workspace app data remove')\n await ready()\n await send('remove', { key: value, expectedRevision })\n },\n dispose() {\n closed = true\n window.removeEventListener('message', onMessage)\n for (const waiting of pending.values()) {\n clearTimeout(waiting.timeout)\n waiting.reject(new Error('Workspace app data client is closed'))\n }\n pending.clear()\n },\n }\n}\n","/** A sandbox app registered in one product workspace. Products persist and authorize these rows. */\nexport interface WorkspaceAppRecord {\n id: string\n workspaceId: string\n name: string\n sandboxId: string\n previewId: string\n port: number\n previewUrl: string\n status: 'starting' | 'ready' | 'unavailable'\n createdAt: string\n updatedAt: string\n}\n\n/** Structural shape returned by the Sandbox SDK previewLinks API. */\nexport interface WorkspaceAppPreviewLink {\n previewId: string\n sandboxId: string\n port: number\n protocol: 'tcp' | 'udp'\n hostname: string\n url: string\n status: 'provisioning' | 'ready' | 'error' | 'disabled'\n}\n\nexport interface WorkspaceAppIdentity {\n /** Assigned by the product, stable across preview updates and deliberate republishes. */\n id: string\n /** Taken from the authenticated route or session, never agent tool arguments. */\n workspaceId: string\n /** Current box resolved by the product from that workspace or session. */\n sandboxId: string\n name: string\n /** Preserve this when republishing the same app onto a replacement sandbox. */\n createdAt?: string\n updatedAt?: string\n}\n\nfunction nonempty(value: string, field: string): string {\n if (typeof value !== 'string' || !value.trim() || /[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error('Invalid workspace app ' + field)\n }\n return value.trim()\n}\n\nfunction checkedLink(link: WorkspaceAppPreviewLink, sandboxId: string): void {\n if (link.sandboxId !== sandboxId) {\n throw new Error('Preview link belongs to another sandbox')\n }\n nonempty(link.previewId, 'previewId')\n if (link.protocol !== 'tcp') throw new Error('Workspace app preview must use TCP')\n if (!Number.isInteger(link.port) || link.port < 1 || link.port > 65535) {\n throw new Error('Invalid workspace app port')\n }\n if (!['provisioning', 'ready', 'error', 'disabled'].includes(link.status)) {\n throw new Error('Invalid workspace app preview status')\n }\n let url: URL\n try {\n url = new URL(link.url)\n } catch {\n throw new Error('Invalid workspace app preview URL')\n }\n if (\n url.protocol !== 'https:' ||\n !url.hostname ||\n url.hostname !== link.hostname ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n ) {\n throw new Error('Invalid workspace app preview URL')\n }\n}\n\nfunction appStatus(status: WorkspaceAppPreviewLink['status']): WorkspaceAppRecord['status'] {\n if (status === 'ready' || status === 'provisioning') return 'starting'\n return 'unavailable'\n}\n\n/**\n * Build a durable registration from a preview link created on the box that\n * the authenticated product request resolved. The product owns row identity,\n * access policy, persistence, and the decision to publish.\n */\nexport function workspaceAppFromPreviewLink(\n identity: WorkspaceAppIdentity,\n link: WorkspaceAppPreviewLink,\n): WorkspaceAppRecord {\n const sandboxId = nonempty(identity.sandboxId, 'sandboxId')\n checkedLink(link, sandboxId)\n const timestamp = identity.updatedAt ?? new Date().toISOString()\n return {\n id: nonempty(identity.id, 'id'),\n workspaceId: nonempty(identity.workspaceId, 'workspaceId'),\n name: nonempty(identity.name, 'name'),\n sandboxId,\n previewId: link.previewId,\n port: link.port,\n previewUrl: link.url,\n status: appStatus(link.status),\n createdAt: identity.createdAt ?? timestamp,\n updatedAt: timestamp,\n }\n}\n\nexport interface WorkspaceAppHttpProof {\n /** The exact trusted SDK preview URL requested by the server. */\n previewUrl: string\n status: number\n contentType: string\n /** Number of bytes read from the response body, excluding headers. */\n bodyBytes: number\n checkedAt: string\n}\n\n/**\n * Mark an app ready only after the host fetched its HTML over the trusted\n * preview URL. The host owns the request timeout, redirect and credential\n * policy, authorization, and compare-and-swap storage update.\n */\nexport function confirmWorkspaceAppReady(\n app: WorkspaceAppRecord,\n proof: WorkspaceAppHttpProof,\n): WorkspaceAppRecord {\n if (\n proof.previewUrl !== app.previewUrl ||\n proof.status !== 200 ||\n !/^text\\/html(?:\\s*;|\\s*$)/i.test(proof.contentType) ||\n !Number.isInteger(proof.bodyBytes) ||\n proof.bodyBytes < 1 ||\n !Number.isFinite(Date.parse(proof.checkedAt))\n ) {\n throw new Error('Workspace app HTML preview is not ready')\n }\n return { ...app, status: 'ready', updatedAt: proof.checkedAt }\n}\n\n/** Refresh delivery state without changing which sandbox service this app means. */\nexport function refreshWorkspaceAppPreview(\n app: WorkspaceAppRecord,\n link: WorkspaceAppPreviewLink,\n updatedAt = new Date().toISOString(),\n): WorkspaceAppRecord {\n checkedLink(link, app.sandboxId)\n if (link.previewId !== app.previewId || link.port !== app.port) {\n throw new Error('Preview link does not match workspace app')\n }\n return {\n ...app,\n previewUrl: link.url,\n status: appStatus(link.status),\n updatedAt,\n }\n}\n\nexport type WorkspaceAppBuilderInstructionsOptions =\n | {\n /** Host tool that writes the registration after creating a trusted preview. */\n publishTool: string\n /** Optional host tool for finding app IDs the builder may update. */\n listTool?: string\n manifestPath?: never\n }\n | {\n /** Host-scoped manifest the builder writes after creating runnable projects. */\n manifestPath: string\n publishTool?: never\n listTool?: never\n }\n\nfunction toolName(value: string): string {\n if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(value)) {\n throw new Error('Invalid workspace app tool name')\n }\n return value\n}\n\nfunction builderManifestPath(value: string): string {\n if (\n !/^[A-Za-z0-9._-]+(?:[/][A-Za-z0-9._-]+)*$/.test(value) ||\n value.split('/').some(segment => segment === '..' || segment === '.')\n ) {\n throw new Error('Invalid workspace app manifest path')\n }\n return value\n}\n\n/** Portable instructions for an agent profile that builds workspace apps. */\nexport function workspaceAppBuilderInstructions(\n options: WorkspaceAppBuilderInstructionsOptions,\n): string[] {\n const common = [\n 'Build a working HTTP application in the current sandbox when the user asks for an app.',\n 'Keep the same app ID for later revisions of that app.',\n 'Treat a preview link as public. Do not embed secrets or private business facts in client code or responses.',\n 'Read real business data through authorized product APIs. Do not fabricate records to make the app look complete.',\n 'Report the app as available only after the host confirms its preview is ready.',\n ] as const\n if (options.manifestPath !== undefined) {\n const path = builderManifestPath(options.manifestPath)\n return [\n common[0],\n 'Inspect the existing app projects and manifest before creating or updating an app.',\n 'Keep each runnable project under apps/<id> relative to the sandbox working directory. Give it a package.json dev script; its HTTP server must listen on 0.0.0.0 and use PORT when supplied.',\n 'Write ' + path + ' as JSON with exactly an apps array of { id, name, projectPath } records; each projectPath is apps/<id>.',\n 'Do not put URLs, credentials, tokens, sandbox IDs, or preview IDs in that manifest.',\n 'The host reads this manifest and owns server launch, port selection, preview creation, registration, and access policy.',\n ...common.slice(1),\n ]\n }\n const publish = toolName(options.publishTool)\n const list = options.listTool ? toolName(options.listTool) : undefined\n return [\n common[0],\n ...(list ? ['Use ' + list + ' to inspect the existing apps before creating or updating one.'] : []),\n 'Start its server on 0.0.0.0 using an available, unclaimed port.',\n 'Call ' + publish + ' with the app name, stable app ID when updating, and listening port.',\n 'Use the host tool result as the source of the registered app URL and status; never invent a preview URL.',\n ...common.slice(1),\n ]\n}\n\nexport {\n WorkspaceAppDataConflict,\n createWorkspaceAppDataClient,\n createWorkspaceAppDataHost,\n} from './data-bridge'\nexport type {\n WorkspaceAppDataClient,\n WorkspaceAppDataClientOptions,\n WorkspaceAppDataEntry,\n WorkspaceAppDataHost,\n WorkspaceAppDataHostOptions,\n} from './data-bridge'\n"],"mappings":";AAEA,IAAM,WAAW;AACjB,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,aAAa;AACnB,IAAM,YAAY;AAGX,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,cAAc;AACZ,UAAM,0DAA0D;AAChE,SAAK,O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og.ts"],"sourcesContent":["/**\n * Model catalogue — computed live from the Tangle Router, never hand-curated.\n * Lifted from tuner-agent so every agent app's model picker shares one\n * filter/dedupe/rank/feature pipeline instead of re-deriving it.\n *\n * The router's /models endpoint returns every routeable model (~200), which is\n * unusable as a picker list: it mixes chat models with TTS/embedding/realtime\n * endpoints, dated snapshots alias their parents, and provider-prefixed ids\n * duplicate canonical ones. This module turns that into a product catalogue:\n *\n * filter (chat-capable, routeable) → dedupe (snapshot/prefix/:free aliases)\n * → rank (provider tier, current generation) → recommend (current families)\n * → default (env override or preferred family)\n *\n * The router is the authority for availability, but its response has no\n * release dates. The shortlist therefore uses the newest routeable entry in\n * each current family, with a conservative generation floor. Other routeable\n * models stay in the catalogue for search and explicit browsing.\n */\n\nexport interface RouterModel {\n id: string\n name?: string\n description?: string\n release_date?: string\n released_at?: string\n _provider?: string\n provider?: string\n pricing?: { prompt?: string | null; completion?: string | null }\n context_length?: number\n architecture?: {\n modality?: string\n input_modalities?: string[]\n output_modalities?: string[]\n }\n supported_parameters?: string[]\n routeability?: {\n status?: string\n routeable?: boolean\n provider?: string\n endpoints?: {\n chat_completions?: {\n status?: string\n routeable?: boolean\n }\n }\n }\n}\n\n/** Define the structure and capabilities of a catalog item with optional pricing and feature flags */\nexport interface CatalogModel {\n id: string\n name: string\n provider: string\n description?: string\n /** Router-supplied release date when available; never inferred from an id. */\n releaseDate?: string\n contextLength?: number\n pricing?: { prompt?: string; completion?: string }\n supportsTools: boolean\n supportsReasoning: boolean\n featured: boolean\n}\n\n/** Define a catalog containing models with a default ID and fetch timestamp */\nexport interface ModelCatalog {\n defaultModelId: string | null\n fetchedAt: string\n models: CatalogModel[]\n}\n\n/** Display order. Unlisted providers sort after these, alphabetically. */\nconst PROVIDER_TIER: string[] = [\n 'anthropic',\n 'openai',\n 'google',\n 'xai',\n 'deepseek',\n 'moonshot',\n 'zai',\n 'mistral',\n 'groq',\n 'nvidia',\n 'cohere',\n 'cerebras',\n]\n\n/** Router aliases that are one provider in a user-facing catalogue. */\nfunction normalizeProvider(provider: string): string {\n const normalized = provider.toLowerCase()\n if (normalized === 'moonshotai') return 'moonshot'\n if (normalized === 'z-ai') return 'zai'\n if (normalized === 'x-ai') return 'xai'\n if (normalized === 'mistralai') return 'mistral'\n return normalized\n}\n\n/** Resolve provider metadata across router response versions. */\nfunction providerForModel(model: RouterModel): string {\n const declared = model._provider ?? model.provider ?? model.routeability?.provider\n if (declared) return normalizeProvider(declared)\n\n const id = normalizeModelId(model.id).toLowerCase()\n if (/^claude-/.test(id)) return 'anthropic'\n if (/^(?:gpt-|o\\d)/.test(id)) return 'openai'\n if (/^gemini-/.test(id)) return 'google'\n if (/^grok-/.test(id)) return 'xai'\n if (/^deepseek-/.test(id)) return 'deepseek'\n if (/^kimi-/.test(id)) return 'moonshot'\n if (/^glm-/.test(id)) return 'zai'\n if (/^mistral/.test(id)) return 'mistral'\n return 'unknown'\n}\n\n/** A short, varied first screen. All other routeable entries remain searchable. */\nexport const MAX_RECOMMENDED_MODELS = 8\n\n/** Non-chat endpoints that pollute the router list (matched on normalized id). */\nconst EXCLUDED_ID = /(embedding|tts|transcribe|whisper|audio|realtime|image|lyria|sora|dall-e|moderation|content-safety|search-preview|search-api|deep-research|:batch$)/\n\n/**\n * Default families, in preference order. Each rule finds the highest-version\n * routeable model whose normalized id matches. Patterns anchor on the family\n * name and stop before specialty suffixes (codex, nano, lite, …) so the\n * mainline model wins.\n */\nconst DEFAULT_CANDIDATE_RULES: Array<{ providers: string[]; match: RegExp }> = [\n { providers: ['anthropic'], match: /^claude-sonnet-[\\d-]+$/ },\n { providers: ['anthropic'], match: /^claude-opus-[\\d-]+$/ },\n { providers: ['anthropic'], match: /^claude-haiku-[\\d-]+$/ },\n { providers: ['openai'], match: /^gpt-\\d+(\\.\\d+)?$/ },\n { providers: ['openai'], match: /^gpt-\\d+(\\.\\d+)?-mini$/ },\n { providers: ['google'], match: /^gemini-[\\d.]+-pro(-preview)?$/ },\n { providers: ['google'], match: /^gemini-[\\d.]+-flash(-preview)?$/ },\n { providers: ['xai'], match: /^grok-[\\d.]+$/ },\n { providers: ['deepseek'], match: /^deepseek-(chat|v[\\d.]+(-\\w+)?)$/ },\n { providers: ['moonshotai', 'moonshot'], match: /^kimi-k[\\d.]+$/ },\n { providers: ['zai', 'z-ai'], match: /^glm-[\\d.]+$/ },\n { providers: ['mistral'], match: /^mistral-(large|medium)-?[\\d.-]*$/ },\n]\n\n/**\n * Current-family floors are based on the routeable Router catalogue checked\n * 2026-09-29. Router entries do not carry release dates, so these are version\n * checks, not claims about a model's launch month. Never promote an older\n * generation merely because a newer route becomes unavailable; browsing and\n * search retain it. A newer routeable version in a family replaces its peer.\n * DeepSeek V4.1 Flash and Kimi K3 remain searchable but are excluded until\n * a live completion succeeds (2026-09-29 probes: quota 503 and server 500).\n */\nconst RECOMMENDED_FAMILIES: Array<{\n provider: string\n match: RegExp\n minVersion: number[]\n}> = [\n { provider: 'anthropic', match: /^claude-opus-\\d+(?:[-.]\\d+)*$/, minVersion: [5] },\n { provider: 'anthropic', match: /^claude-sonnet-\\d+(?:[-.]\\d+)*$/, minVersion: [5] },\n { provider: 'openai', match: /^gpt-\\d+(?:\\.\\d+)?-sol$/, minVersion: [6] },\n { provider: 'openai', match: /^gpt-\\d+(?:\\.\\d+)?-astra$/, minVersion: [6] },\n { provider: 'google', match: /^gemini-\\d+(?:\\.\\d+)?-flash(?:-preview)?$/, minVersion: [3, 5] },\n { provider: 'zai', match: /^glm-\\d+(?:\\.\\d+)?$/, minVersion: [5, 3] },\n]\n\nconst RECOMMENDATION_WINDOW_MS = 120 * 24 * 60 * 60 * 1000\n\nfunction releaseDateFromRouter(model: RouterModel): string | undefined {\n const value = model.release_date ?? model.released_at\n if (!value || !/^\\d{4}-\\d{2}-\\d{2}(?:T|$)/.test(value)) return undefined\n const time = Date.parse(value)\n return Number.isFinite(time) ? new Date(time).toISOString() : undefined\n}\n\n/** Families known to support tool calls even when router metadata omits it\n * (dated snapshots often lack the supported_parameters of their parent). */\nconst TOOL_CAPABLE_FAMILY = /^(claude|gpt-\\d|gpt-oss|o[134]|gemini|grok|deepseek|glm|kimi|mistral|ministral|magistral|command|nemotron|llama)/\n\n/** Strip provider prefix, :free suffix, and trailing date stamps. */\nexport function normalizeModelId(id: string): string {\n let tail = id.split('/').pop() ?? id\n tail = tail.replace(/:free$/, '')\n tail = tail.replace(/-\\d{8}$/, '')\n tail = tail.replace(/-\\d{4}-\\d{2}-\\d{2}$/, '')\n return tail\n}\n\n/** All numeric groups in a normalized id, for version comparison. */\nfunction versionOf(normId: string): number[] {\n return (normId.match(/\\d+/g) ?? []).map(Number)\n}\n\nfunction compareVersions(a: number[], b: number[]): number {\n const len = Math.max(a.length, b.length)\n for (let i = 0; i < len; i++) {\n const d = (a[i] ?? -1) - (b[i] ?? -1)\n if (d !== 0) return d\n }\n return 0\n}\n\n/**\n * Read the generation attached to a known model family.\n *\n * This deliberately does not read every number in the id. A parameter count\n * such as `gpt-oss-120b` is not newer than GPT 5.6.\n */\nfunction releaseVersion(id: string): number[] {\n const normalized = normalizeModelId(id).toLowerCase()\n const patterns = [\n /^claude-[a-z0-9]+-(\\d+(?:[.-]\\d+)*)/,\n /^gpt-(\\d+(?:\\.\\d+)*)/,\n /^o(\\d+(?:\\.\\d+)*)/,\n /^gemini-(\\d+(?:\\.\\d+)*)/,\n /^deepseek-v(\\d+(?:\\.\\d+)*)/,\n /^kimi-k(\\d+(?:\\.\\d+)*)/,\n /^glm-(\\d+(?:\\.\\d+)*)/,\n /^grok-(\\d+(?:\\.\\d+)*)/,\n /^mistral-(?:large|medium)-?(\\d+(?:[.-]\\d+)*)/,\n /^qwen-?(\\d+(?:\\.\\d+)*)/,\n /^llama-?(\\d+(?:\\.\\d+)*)/,\n ]\n for (const pattern of patterns) {\n const match = normalized.match(pattern)\n if (match?.[1]) return match[1].split(/[.-]/).map(Number)\n }\n return []\n}\n\n/**\n * Return a copy sorted for a model menu.\n *\n * Providers keep the shared display order. Within each provider, current\n * generations come first across families. Stable ids win ties with previews.\n * Callers can sort separate sections without changing `featured` or defaults.\n */\nexport function sortModelsByFreshness(models: readonly CatalogModel[]): CatalogModel[] {\n return [...models].sort((a, b) => {\n const providerA = normalizeProvider(a.provider)\n const providerB = normalizeProvider(b.provider)\n const providerOrder = providerRank(providerA) - providerRank(providerB)\n if (providerOrder !== 0) return providerOrder\n if (providerA !== providerB) return providerA.localeCompare(providerB)\n\n const generationOrder = compareVersions(releaseVersion(b.id), releaseVersion(a.id))\n if (generationOrder !== 0) return generationOrder\n\n const previewOrder = Number(/preview/i.test(a.id)) - Number(/preview/i.test(b.id))\n if (previewOrder !== 0) return previewOrder\n return a.id.localeCompare(b.id)\n })\n}\n\n/** Lower = preferred representative for an alias group. */\nfunction aliasPenalty(id: string): number {\n let p = 0\n if (id.includes('/')) p += 4\n if (/-\\d{8}$|-\\d{4}-\\d{2}-\\d{2}$/.test(id.replace(/:free$/, ''))) p += 2\n if (id.endsWith(':free')) p += 1\n return p\n}\n\nfunction providerRank(provider: string): number {\n const i = PROVIDER_TIER.indexOf(normalizeProvider(provider))\n return i === -1 ? PROVIDER_TIER.length : i\n}\n\n/**\n * Can this router entry serve a text chat turn?\n *\n * The router lists every routeable endpoint, which is not the same list a chat\n * picker should show: measured against the live catalogue (504 entries), this\n * rejects 35 — image generators, TTS voices, embedding models, and the\n * audio-IN transcription endpoints (`whisper-1`, `gpt-4o-transcribe`, …) that\n * emit text but cannot take a text prompt.\n *\n * A model whose metadata omits either modality list is KEPT. The router is the\n * source of that metadata and it is occasionally sparse; dropping a usable\n * model because a field is missing is the worse failure of the two.\n *\n * Exported because a picker needs the same answer `buildCatalog` uses — the\n * fleet had this predicate copied into a product component, where its narrower\n * spelling let the 10 transcription endpoints through.\n */\nexport function isChatCapableModel(m: RouterModel): boolean {\n const arch = m.architecture\n if (!arch?.input_modalities || !arch?.output_modalities) return true\n return arch.input_modalities.includes('text') && arch.output_modalities.includes('text')\n}\n\nconst isChatModel = isChatCapableModel\n\nfunction isRouteable(m: RouterModel): boolean {\n const routeability = m.routeability\n if (!routeability) return true\n const chatEndpoint = routeability.endpoints?.chat_completions\n if (chatEndpoint?.routeable === false) return false\n if (chatEndpoint?.status !== undefined && chatEndpoint.status !== 'routeable') return false\n if (routeability.routeable === true || routeability.status === 'routeable') return true\n if (routeability.routeable === false) return false\n return routeability.status === undefined\n}\n\n/** Find a catalogue row by direct or provider-prefixed model id. */\nexport function catalogModelForId(\n models: readonly CatalogModel[],\n requestedId: string | undefined,\n): CatalogModel | undefined {\n const requested = requestedId?.trim()\n if (!requested) return undefined\n\n const exact = models.find((model) => model.id === requested)\n if (exact) return exact\n\n const slash = requested.indexOf('/')\n const requestedProvider = slash > 0 ? normalizeProvider(requested.slice(0, slash)) : undefined\n const normalized = normalizeModelId(requested)\n return models.find((model) => {\n if (normalizeModelId(model.id) !== normalized) return false\n return requestedProvider === undefined || normalizeProvider(model.provider) === requestedProvider\n })\n}\n\n/**\n * Reconcile a persisted selection against the live catalogue.\n *\n * The returned id is always a catalogue id once the catalogue has entries.\n * This keeps a removed model from remaining selected while preserving the\n * current value during the brief empty/loading state.\n */\nexport function resolveCatalogModelId(\n models: readonly CatalogModel[],\n selectedId?: string,\n fallbackId?: string,\n): string | undefined {\n if (models.length === 0) return selectedId?.trim() || fallbackId?.trim()\n return catalogModelForId(models, selectedId)?.id\n ?? catalogModelForId(models, fallbackId)?.id\n ?? models[0]?.id\n}\n\n/**\n * Pure catalogue pipeline. `preferredDefault` (typically the MODEL_NAME env\n * var) wins when it survives filtering; otherwise the first featured model.\n */\nexport function buildCatalog(raw: RouterModel[], opts?: { preferredDefault?: string }): ModelCatalog {\n // Filter to chat-capable, routeable, non-specialty models\n const candidates = raw.filter(\n (m) =>\n m.id &&\n isRouteable(m) &&\n isChatModel(m) &&\n !EXCLUDED_ID.test(normalizeModelId(m.id)),\n )\n\n // Dedupe alias groups (dated snapshots, provider prefixes, :free variants).\n // Within a group, merge metadata so the representative keeps the richest\n // supported_parameters claim (snapshots often omit what the parent lists).\n const groups = new Map<string, RouterModel[]>()\n for (const m of candidates) {\n const key = `${providerForModel(m)}::${normalizeModelId(m.id)}`\n const g = groups.get(key)\n if (g) g.push(m)\n else groups.set(key, [m])\n }\n\n const reps: Array<{ model: RouterModel; normId: string; mergedParams: Set<string>; releaseDate?: string }> = []\n for (const group of groups.values()) {\n group.sort((a, b) => aliasPenalty(a.id) - aliasPenalty(b.id) || a.id.length - b.id.length)\n const rep = group[0]!\n const mergedParams = new Set<string>(group.flatMap((m) => m.supported_parameters ?? []))\n const releaseDate = group.map(releaseDateFromRouter).find((date) => date !== undefined)\n reps.push({ model: rep, normId: normalizeModelId(rep.id), mergedParams, releaseDate })\n }\n\n // Resolve the default independently from menu recommendations.\n const defaultCandidateIds: string[] = []\n for (const rule of DEFAULT_CANDIDATE_RULES) {\n const matches = reps.filter(\n (r) =>\n rule.providers.map(normalizeProvider).includes(providerForModel(r.model)) &&\n rule.match.test(r.normId) &&\n !defaultCandidateIds.includes(r.model.id),\n )\n if (!matches.length) continue\n matches.sort(\n (a, b) =>\n compareVersions(versionOf(b.normId), versionOf(a.normId)) ||\n Number(a.normId.includes('preview')) - Number(b.normId.includes('preview')) ||\n a.model.id.length - b.model.id.length,\n )\n defaultCandidateIds.push(matches[0]!.model.id)\n }\n\n const toCatalogModel = (r: (typeof reps)[number]): CatalogModel => {\n const m = r.model\n const provider = providerForModel(m)\n return {\n id: m.id,\n name: m.name ?? m.id,\n provider,\n description: m.description ? m.description.slice(0, 160) : undefined,\n releaseDate: r.releaseDate,\n contextLength: m.context_length,\n pricing:\n m.pricing?.prompt || m.pricing?.completion\n ? { prompt: m.pricing.prompt ?? undefined, completion: m.pricing.completion ?? undefined }\n : undefined,\n supportsTools: r.mergedParams.has('tools') || TOOL_CAPABLE_FAMILY.test(r.normId),\n supportsReasoning: r.mergedParams.has('reasoning') || r.mergedParams.has('include_reasoning'),\n featured: false,\n }\n }\n\n // Family rules retain the intentional default preference. Display order is\n // independent: every catalogue consumer gets provider-grouped freshness,\n // even when it does not render ModelPicker.\n const defaultCandidatesInRuleOrder = defaultCandidateIds\n .map((id) => reps.find((r) => r.model.id === id)!)\n .map(toCatalogModel)\n const sorted = sortModelsByFreshness(reps.map(toCatalogModel))\n const recommendedIds = new Set<string>()\n const recentSince = Date.now() - RECOMMENDATION_WINDOW_MS\n for (const family of RECOMMENDED_FAMILIES) {\n const current = sorted.find((model) =>\n normalizeProvider(model.provider) === family.provider &&\n family.match.test(normalizeModelId(model.id)) &&\n compareVersions(releaseVersion(model.id), family.minVersion) >= 0 &&\n (model.releaseDate === undefined || Date.parse(model.releaseDate) >= recentSince),\n )\n if (current) recommendedIds.add(current.id)\n if (recommendedIds.size >= MAX_RECOMMENDED_MODELS) break\n }\n const models = sorted.map((model) =>\n recommendedIds.has(model.id) ? { ...model, featured: true } : model,\n )\n\n const preferred = opts?.preferredDefault\n const defaultModelId =\n (preferred && models.find((m) => m.id === preferred || normalizeModelId(m.id) === normalizeModelId(preferred))?.id) ||\n defaultCandidatesInRuleOrder.find((m) => m.supportsTools)?.id ||\n models[0]?.id ||\n null\n\n return { defaultModelId, fetchedAt: new Date().toISOString(), models }\n}\n\n// ── Cached fetch ─────────────────────────────────────────────────────────\n\nconst CATALOG_TTL_MS = 5 * 60 * 1000\n\nlet _cache: { catalog: ModelCatalog; at: number } | null = null\n\n/**\n * Fetch the router model list and build the catalogue, with an in-isolate\n * cache (TTL 5 min). On router failure a stale catalogue is served rather\n * than erroring the picker.\n */\nexport async function fetchModelCatalog(cfg: {\n baseUrl: string\n apiKey: string\n preferredDefault?: string\n}): Promise<ModelCatalog> {\n if (_cache && Date.now() - _cache.at < CATALOG_TTL_MS) {\n return _cache.catalog\n }\n try {\n const res = await fetch(`${cfg.baseUrl}/models`, {\n headers: { Authorization: `Bearer ${cfg.apiKey}` },\n })\n if (!res.ok) throw new Error(`Router /models returned ${res.status}`)\n const data = (await res.json()) as { data?: RouterModel[] }\n const catalog = buildCatalog(data.data ?? [], { preferredDefault: cfg.preferredDefault })\n _cache = { catalog, at: Date.now() }\n return catalog\n } catch (err) {\n if (_cache) return _cache.catalog\n throw err\n }\n}\n\n/** Test-only: clear the catalogue cache. */\nexport function __resetCatalogCache(): void {\n _cache = null\n}\n"],"mappings":";AAwEA,IAAM,gBAA0B;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,SAAS,kBAAkB,UAA0B;AACnD,QAAM,aAAa,SAAS,YAAY;AACxC,MAAI,eAAe,aAAc,QAAO;AACxC,MAAI,eAAe,OAAQ,QAAO;AAClC,MAAI,eAAe,OAAQ,QAAO;AAClC,MAAI,eAAe,YAAa,QAAO;AACvC,SAAO;AACT;AAGA,SAAS,iBAAiB,OAA4B;AACpD,QAAM,WAAW,MAAM,aAAa,MAAM,YAAY,MAAM,cAAc;AAC1E,MAAI,SAAU,QAAO,kBAAkB,QAAQ;AAE/C,QAAM,KAAK,iBAAiB,MAAM,EAAE,EAAE,YAAY;AAClD,MAAI,WAAW,KAAK,EAAE,EAAG,QAAO;AAChC,MAAI,gBAAgB,KAAK,EAAE,EAAG,QAAO;AACrC,MAAI,WAAW,KAAK,EAAE,EAAG,QAAO;AAChC,MAAI,SAAS,KAAK,EAAE,EAAG,QAAO;AAC9B,MAAI,aAAa,KAAK,EAAE,EAAG,QAAO;AAClC,MAAI,SAAS,KAAK,EAAE,EAAG,QAAO;AAC9B,MAAI,QAAQ,KAAK,EAAE,EAAG,QAAO;AAC7B,MAAI,WAAW,KAAK,EAAE,EAAG,QAAO;AAChC,SAAO;AACT;AAGO,IAAM,yBAAyB;AAGtC,IAAM,cAAc;AAQpB,IAAM,0BAAyE;AAAA,EAC7E,EAAE,WAAW,CAAC,WAAW,GAAG,OAAO,yBAAyB;AAAA,EAC5D,EAAE,WAAW,CAAC,WAA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AEA,QAAM,YAAY,MAAM;AACxB,QAAM,iBACH,aAAa,OAAO,KAAK,CAAC,MAAM,EAAE,OAAO,aAAa,iBAAiB,EAAE,EAAE,MAAM,iBAAiB,SAAS,CAAC,GAAG,MAChH,6BAA6B,KAAK,CAAC,MAAM,EAAE,aAAa,GAAG,MAC3D,OAAO,CAAC,GAAG,MACX;AAEF,SAAO,EAAE,gBAAgB,YAAW,oBAAI,KAAK,GAAE,YAAY,GAAG,OAAO;AACvE;AAIA,IAAM,iBAAiB,IAAI,KAAK;AAEhC,IAAI,SAAuD;AAO3D,eAAsB,kBAAkB,KAId;AACxB,MAAI,UAAU,KAAK,IAAI,IAAI,OAAO,KAAK,gBAAgB;AACrD,WAAO,OAAO;AAAA,EAChB;AACA,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,GAAG,IAAI,OAAO,WAAW;AAAA,MAC/C,SAAS,EAAE,eAAe,UAAU,IAAI,MAAM,GAAG;AAAA,IACnD,CAAC;AACD,QAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,2BAA2B,IAAI,MAAM,EAAE;AACpE,UAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,UAAM,UAAU,aAAa,KAAK,QAAQ,CAAC,GAAG,EAAE,kBAAkB,IAAI,iBAAiB,CAAC;AACxF,aAAS,EAAE,SAAS,IAAI,KAAK,IAAI,EAAE;AACnC,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,OAAQ,QAAO,OAAO;AAC1B,UAAM;AAAA,EACR;AACF;AAGO,SAAS,sBAA4B;AAC1C,WAAS;AACX;","names":[]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|