@tangle-network/agent-app 0.60.121 → 0.60.123

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.
Files changed (52) hide show
  1. package/dist/assistant/index.js +10 -10
  2. package/dist/catalog/index.js +1 -1
  3. package/dist/chat-react/index.js +5 -5
  4. package/dist/chat-routes/index.js +3 -3
  5. package/dist/{chunk-6KCN2VQS.js → chunk-2E32OQIR.js} +3 -3
  6. package/dist/{chunk-HYR3XFTY.js → chunk-2PWMBH67.js} +3 -3
  7. package/dist/{chunk-4U2CA7N2.js → chunk-AJF4O5IS.js} +49 -6
  8. package/dist/chunk-AJF4O5IS.js.map +1 -0
  9. package/dist/{chunk-26N7PO6M.js → chunk-B3O3WKUJ.js} +4 -4
  10. package/dist/{chunk-I2SDMEM7.js → chunk-DESG72EM.js} +10 -5
  11. package/dist/chunk-DESG72EM.js.map +1 -0
  12. package/dist/{chunk-GS6LD5P2.js → chunk-EOJZLMY3.js} +2 -2
  13. package/dist/{chunk-WEMHBHV2.js → chunk-ICBQWN4L.js} +3 -3
  14. package/dist/{chunk-RFLC7BPY.js → chunk-MJ7ZFURI.js} +1 -1
  15. package/dist/chunk-MJ7ZFURI.js.map +1 -0
  16. package/dist/{chunk-PT7H37YH.js → chunk-OJCBSHSQ.js} +1 -1
  17. package/dist/chunk-OJCBSHSQ.js.map +1 -0
  18. package/dist/{chunk-VTYNU3LN.js → chunk-OQEGCPXR.js} +2 -2
  19. package/dist/{chunk-2HGAMEOY.js → chunk-QSBQPPLI.js} +2 -2
  20. package/dist/{chunk-PTTPLOWC.js → chunk-VYCAYJ7T.js} +3 -3
  21. package/dist/{chunk-ANHMZ5BS.js → chunk-WJEATJW6.js} +2 -2
  22. package/dist/{mention-editor-MEUNCF5P.js → mention-editor-DWY2UH2C.js} +3 -3
  23. package/dist/public-consultation/index.d.ts +1 -1
  24. package/dist/runtime/index.js +11 -5
  25. package/dist/runtime/index.js.map +1 -1
  26. package/dist/runtime/model-catalog.d.ts +5 -0
  27. package/dist/runtime/router-turn.d.ts +20 -1
  28. package/dist/runtime/router-turn.js +10 -4
  29. package/dist/runtime/turn-continuation.d.ts +43 -0
  30. package/dist/studio/generation.d.ts +9 -0
  31. package/dist/studio/index.js +1 -1
  32. package/dist/studio-react/composer-option-controls.d.ts +1 -19
  33. package/dist/studio-react/index.js +49 -91
  34. package/dist/studio-react/index.js.map +1 -1
  35. package/dist/web-react/agent-profile-editor.js +5 -5
  36. package/dist/web-react/index.js +10 -10
  37. package/dist/workspace-react/index.js +5 -5
  38. package/package.json +3 -3
  39. package/dist/chunk-4U2CA7N2.js.map +0 -1
  40. package/dist/chunk-I2SDMEM7.js.map +0 -1
  41. package/dist/chunk-PT7H37YH.js.map +0 -1
  42. package/dist/chunk-RFLC7BPY.js.map +0 -1
  43. /package/dist/{chunk-6KCN2VQS.js.map → chunk-2E32OQIR.js.map} +0 -0
  44. /package/dist/{chunk-HYR3XFTY.js.map → chunk-2PWMBH67.js.map} +0 -0
  45. /package/dist/{chunk-26N7PO6M.js.map → chunk-B3O3WKUJ.js.map} +0 -0
  46. /package/dist/{chunk-GS6LD5P2.js.map → chunk-EOJZLMY3.js.map} +0 -0
  47. /package/dist/{chunk-WEMHBHV2.js.map → chunk-ICBQWN4L.js.map} +0 -0
  48. /package/dist/{chunk-VTYNU3LN.js.map → chunk-OQEGCPXR.js.map} +0 -0
  49. /package/dist/{chunk-2HGAMEOY.js.map → chunk-QSBQPPLI.js.map} +0 -0
  50. /package/dist/{chunk-PTTPLOWC.js.map → chunk-VYCAYJ7T.js.map} +0 -0
  51. /package/dist/{chunk-ANHMZ5BS.js.map → chunk-WJEATJW6.js.map} +0 -0
  52. /package/dist/{mention-editor-MEUNCF5P.js.map → mention-editor-DWY2UH2C.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,OAGK;AAkBA,SAAS,wBAAwB,QAAoD;AAC1F,QAAM,SAAS,4BAA4B,MAAM;AACjD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,aAAO,EAAE,GAAG,MAAM,cAAc,MAAM,OAAO,QAAQ,KAAK,YAAY,EAAE;AAAA,IAC1E;AAAA,IACA,SAAS,MAAM,OAAO,QAAQ,EAAE,OAAO,KAAK,CAAC;AAAA,IAC7C,SAAS,OAAO;AAAA,EAClB;AACF;;;ACwCO,SAAS,kBAAwB,MAGR;AAC9B,MAAI,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG;AACnF,UAAM,IAAI,MAAM,mEAAmE,KAAK,UAAU,KAAK,IAAI,CAAC,GAAG;AAAA,EACjH;AACA,MAAI,OAAO,KAAK,UAAU,YAAY;AACpC,UAAM,IAAI,MAAM,iBAAiB,KAAK,IAAI,6BAA6B;AAAA,EACzE;AACA,SAAO,EAAE,MAAM,KAAK,MAAM,OAAO,KAAK,MAAM;AAC9C;AAgBO,SAAS,sBAAsB,OAAmD;AACvF,QAAM,SAAS,oBAAI,IAA4B;AAC/C,aAAW,cAAc,OAAO;AAC9B,QAAI,OAAO,IAAI,WAAW,IAAI,GAAG;AAC/B,YAAM,IAAI,MAAM,2BAA2B,WAAW,IAAI,oDAA+C;AAAA,IAC3G;AACA,WAAO,IAAI,WAAW,MAAM,UAAU;AAAA,EACxC;AAEA,SAAO;AAAA,IACL,MAAM,QAAQ,MAAM,KAAK;AACvB,YAAM,aAAa,OAAO,IAAI,IAAI;AAClC,UAAI,CAA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2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,OAGK;AAkBA,SAAS,wBAAwB,QAAoD;AAC1F,QAAM,SAAS,4BAA4B,MAAM;AACjD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,aAAO,EAAE,GAAG,MAAM,cAAc,MAAM,OAAO,QAAQ,KAAK,YAAY,EAAE;AAAA,IAC1E;AAAA,IACA,SAAS,MAAM,OAAO,QAAQ,EAAE,OAAO,KAAK,CAAC;AAAA,IAC7C,SAAS,OAAO;AAAA,EAClB;AACF;;;ACwCO,SAAS,kBAAwB,MAGR;AAC9B,MAAI,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG;AACnF,UAAM,IAAI,MAAM,mEAAmE,KAAK,UAAU,KAAK,IAAI,CAAC,GAAG;AAAA,EACjH;AACA,MAAI,OAAO,KAAK,UAAU,YAAY;AACpC,UAAM,IAAI,MAAM,iBAAiB,KAAK,IAAI,6BAA6B;AAAA,EACzE;AACA,SAAO,EAAE,MAAM,KAAK,MAAM,OAAO,KAAK,MAAM;AAC9C;AAgBO,SAAS,sBAAsB,OAAmD;AACvF,QAAM,SAAS,oBAAI,IAA4B;AAC/C,aAAW,cAAc,OAAO;AAC9B,QAAI,OAAO,IAAI,WAAW,IAAI,GAAG;AAC/B,YAAM,IAAI,MAA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,EACF;AACA,MAAI,QAAQ,gBAAgB,QAAW;AACrC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,WAAW,GAAG;AAC9D,UAAI,EAAE,SAAS,sBAAsB;AACnC,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,GAAG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -73,6 +73,11 @@ export interface CatalogModel {
73
73
  previewUrl?: string;
74
74
  /** One line on what the model is for, shown under its name. */
75
75
  capability?: string;
76
+ /** Whether the model can be sent now. Absent means available. A limited or
77
+ * unavailable model stays selectable; the picker marks it in a warning tone. */
78
+ status?: 'available' | 'limited' | 'unavailable';
79
+ /** Why a limited or unavailable model is so, in words a person can act on. */
80
+ statusReason?: string;
76
81
  supportsTools: boolean;
77
82
  supportsReasoning: boolean;
78
83
  featured: boolean;
@@ -21,6 +21,7 @@
21
21
  import { type LoopMessage } from './loop';
22
22
  import { type TurnKnowledgeFile } from './turn-knowledge';
23
23
  import { type PlacementRecord, type VacuousAxis } from '@tangle-network/agent-runtime/placement';
24
+ export { DURABLE_HOP_BUDGET_MS, turnCheckpointPath, workspaceTurnCheckpoints, type CheckpointWorkspaceStore, type TurnCheckpointStore } from './turn-continuation';
24
25
  export { budgetTurnKnowledge, turnKnowledgeInstructions, workspaceKnowledgeForTurn, type TurnKnowledgeBudget, type TurnKnowledgeFile } from './turn-knowledge';
25
26
  /** A tool the turn may call. Structurally an `McpToolDefinition` whose env is already bound. */
26
27
  export interface RouterTurnTool {
@@ -112,9 +113,24 @@ export interface RouterTurnOutcome {
112
113
  /** Every side event the turn's tools reported, in order (at most 500). */
113
114
  toolEvents: RouterTurnToolEvent[];
114
115
  failure?: RouterTurnFailure;
116
+ /**
117
+ * Set instead of a failure when the turn reached its budget at a clean point
118
+ * (every tool call answered). The turn is not over: persist this and call
119
+ * `runRouterTurn` again with `continueFrom` in a durable process to finish it.
120
+ * `text` holds everything the turn has written so far, across hops.
121
+ */
122
+ continuation?: RouterTurnContinuation;
115
123
  /** Where the turn was placed, when the caller asked for placement. */
116
124
  placement?: PlacementRecord;
117
125
  }
126
+ /** A checkpointed Router turn: the conversation after the system prompt, ready to continue. JSON-safe. */
127
+ export interface RouterTurnContinuation {
128
+ messages: LoopMessage[];
129
+ /** Hops this turn has already run, including this one. */
130
+ hops: number;
131
+ /** Reply text every hop so far wrote; the final hop's outcome `text` includes it. */
132
+ text: string;
133
+ }
118
134
  /**
119
135
  * What placement reads for a Router turn: the resolved profile, the tools the
120
136
  * turn would hold, and a model the sender chose. Declared data only.
@@ -159,8 +175,11 @@ export interface RouterTurnOptions {
159
175
  content: string;
160
176
  } | LoopMessage>;
161
177
  tools?: RouterTurnTool[];
162
- /** Wall-clock budget in ms. Default 90 s. A caller whose retry window is shorter passes less. */
178
+ /** Wall-clock budget in ms for this hop. Default 90 s. At the budget the outcome carries a
179
+ * `continuation` instead of failing; the model call or tool already running finishes first. */
163
180
  budgetMs?: number;
181
+ /** Continue a checkpointed turn; `userMessage` and `history` are ignored. */
182
+ continueFrom?: RouterTurnContinuation;
164
183
  /** Runaway backstop on model turns. Default 12. */
165
184
  maxToolTurns?: number;
166
185
  maxTokens?: number;
@@ -1,21 +1,27 @@
1
1
  import {
2
+ DURABLE_HOP_BUDGET_MS,
2
3
  budgetTurnKnowledge,
3
4
  composeRouterTurnPrompt,
4
5
  placeRouterTurn,
5
6
  routerFunctionName,
6
7
  runRouterTurn,
8
+ turnCheckpointPath,
7
9
  turnKnowledgeInstructions,
8
- workspaceKnowledgeForTurn
9
- } from "../chunk-4U2CA7N2.js";
10
+ workspaceKnowledgeForTurn,
11
+ workspaceTurnCheckpoints
12
+ } from "../chunk-AJF4O5IS.js";
10
13
  import "../chunk-D6UJEOZQ.js";
11
- import "../chunk-RFLC7BPY.js";
14
+ import "../chunk-MJ7ZFURI.js";
12
15
  export {
16
+ DURABLE_HOP_BUDGET_MS,
13
17
  budgetTurnKnowledge,
14
18
  composeRouterTurnPrompt,
15
19
  placeRouterTurn,
16
20
  routerFunctionName,
17
21
  runRouterTurn,
22
+ turnCheckpointPath,
18
23
  turnKnowledgeInstructions,
19
- workspaceKnowledgeForTurn
24
+ workspaceKnowledgeForTurn,
25
+ workspaceTurnCheckpoints
20
26
  };
21
27
  //# sourceMappingURL=router-turn.js.map
@@ -0,0 +1,43 @@
1
+ /**
2
+ * A Router turn never fails because of time. `runRouterTurn` stops at its hop
3
+ * budget at a clean point and returns a `continuation`; the host saves it here
4
+ * and runs the next hop in a durable process (a Durable Object alarm or a Queue
5
+ * consumer: 15 minutes of wall time each), posting into the same conversation.
6
+ *
7
+ * Checkpoints live in the app's workspace store under `/turns/<turnId>/`, which
8
+ * a Files view (`/files/`) never lists.
9
+ */
10
+ import type { RouterTurnContinuation } from './router-turn';
11
+ /** Wall time a durable hop may plan for: a Durable Object alarm or Queue consumer gets 15 minutes. */
12
+ export declare const DURABLE_HOP_BUDGET_MS: number;
13
+ /** Where a turn's checkpoint waits between hops. */
14
+ export interface TurnCheckpointStore {
15
+ save(turnId: string, continuation: RouterTurnContinuation): Promise<void>;
16
+ load(turnId: string): Promise<RouterTurnContinuation | null>;
17
+ clear(turnId: string): Promise<void>;
18
+ }
19
+ interface CheckpointEntry {
20
+ content?: string;
21
+ revision: number;
22
+ }
23
+ /** The fields of an agent-runtime `WorkspaceStore` a checkpoint needs; structural so any adapter fits. */
24
+ export interface CheckpointWorkspaceStore {
25
+ get(workspaceId: string, path: string): Promise<CheckpointEntry | null>;
26
+ put(input: {
27
+ workspaceId: string;
28
+ path: string;
29
+ kind: 'file';
30
+ ifRevision: number | null;
31
+ actor: string;
32
+ content: string;
33
+ }): Promise<unknown>;
34
+ delete(input: {
35
+ workspaceId: string;
36
+ path: string;
37
+ actor: string;
38
+ }): Promise<unknown>;
39
+ }
40
+ export declare function turnCheckpointPath(turnId: string): string;
41
+ /** Turn checkpoints in a workspace store, written as `actor`. */
42
+ export declare function workspaceTurnCheckpoints(store: CheckpointWorkspaceStore, workspaceId: string, actor: string): TurnCheckpointStore;
43
+ export {};
@@ -1,3 +1,4 @@
1
+ import type { CatalogModel } from '../runtime/model-catalog';
1
2
  import type { ModelOptionsMetadata } from './model-options';
2
3
  /** Define generation categories for media including image, video, speech, avatar, and transcription */
3
4
  export type GenerationType = 'image' | 'video' | 'speech' | 'avatar' | 'transcription';
@@ -25,6 +26,14 @@ export interface MediaModelOption {
25
26
  status: MediaModelStatus;
26
27
  reason?: string;
27
28
  options?: ModelOptionsMetadata;
29
+ /** USD per unit of output as the catalog publishes it (one image, one second
30
+ * of video, one minute of audio, 1,000 characters of speech). Absent when no
31
+ * price is published; the picker then shows none rather than a guess. */
32
+ outputPrice?: CatalogModel['outputPrice'];
33
+ /** An example output (an image, or a video poster frame) for the picker row. */
34
+ previewUrl?: string;
35
+ /** One line on what the model is for, shown under its name in the picker. */
36
+ capability?: string;
28
37
  }
29
38
  /** Represent media model catalog with default values, model options, and optional error message */
30
39
  export interface MediaModelCatalogResponse {
@@ -47,7 +47,7 @@ import {
47
47
  textToVideoSibling,
48
48
  userSafeGenerationMessage,
49
49
  validateCustomImageSize
50
- } from "../chunk-PT7H37YH.js";
50
+ } from "../chunk-OJCBSHSQ.js";
51
51
  export {
52
52
  FALLBACK_VIDEO_MODEL_OPTIONS,
53
53
  GENERATION_TYPES,
@@ -15,7 +15,7 @@
15
15
  */
16
16
  import { type JSX, type ReactNode, type RefObject } from 'react';
17
17
  import { type LucideIcon } from 'lucide-react';
18
- import { type MediaModelOption, type ModelOptionValue } from '../studio';
18
+ import { type ModelOptionValue } from '../studio';
19
19
  /** One media lane's segment: the icon it shows collapsed, the word it shows
20
20
  * when active. */
21
21
  export interface MediaTypeSegment<T extends string> {
@@ -129,24 +129,6 @@ export declare function ReferencePill({ url, onAttach, onRemove, pick, bandRef,
129
129
  pick?: () => Promise<string | null>;
130
130
  bandRef: RefObject<HTMLDivElement | null>;
131
131
  }): JSX.Element;
132
- /**
133
- * The model pill — first in the band on every lane, and the only pill that is
134
- * always there. A model with no published option metadata renders this and
135
- * nothing else, which is the honest reading of "we do not know what this model
136
- * takes".
137
- */
138
- export declare function ModelPill({ models, value, displayName, provider, unavailable, onSelect, bandRef, }: {
139
- models: readonly MediaModelOption[];
140
- value: string;
141
- /** What the pill reads. Falls back to the id — including for a model the
142
- * catalog does not list, such as an image-to-video sibling. */
143
- displayName: string;
144
- provider?: string;
145
- /** The selected model is listed but not routable — the pill carries the warning instead of any status line. */
146
- unavailable?: boolean;
147
- onSelect: (id: string) => void;
148
- bandRef: RefObject<HTMLDivElement | null>;
149
- }): JSX.Element;
150
132
  /**
151
133
  * How a wire value reads, with the wire value itself untouched underneath.
152
134
  *
@@ -36,25 +36,26 @@ import {
36
36
  textToVideoSibling,
37
37
  userSafeGenerationMessage,
38
38
  validateCustomImageSize
39
- } from "../chunk-PT7H37YH.js";
39
+ } from "../chunk-OJCBSHSQ.js";
40
40
  import {
41
41
  useInfiniteScroll
42
- } from "../chunk-WEMHBHV2.js";
43
- import "../chunk-ANHMZ5BS.js";
42
+ } from "../chunk-ICBQWN4L.js";
43
+ import "../chunk-WJEATJW6.js";
44
44
  import {
45
45
  CheckGlyph,
46
46
  ChevronDown,
47
+ ModelPicker,
47
48
  OVERLAY_SHADOW,
48
49
  POPOVER_OPTION_FOCUS,
49
50
  POPOVER_SURFACE_ATTR,
50
51
  PopoverSurface,
51
52
  usePopover
52
- } from "../chunk-I2SDMEM7.js";
53
+ } from "../chunk-DESG72EM.js";
53
54
  import "../chunk-SJWIZT7B.js";
54
55
  import {
55
56
  ProviderLogo
56
57
  } from "../chunk-MLG6XKPV.js";
57
- import "../chunk-RFLC7BPY.js";
58
+ import "../chunk-MJ7ZFURI.js";
58
59
 
59
60
  // src/studio-react/use-studio-generations.ts
60
61
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -127,7 +128,7 @@ import {
127
128
  Scaling,
128
129
  SlidersHorizontal,
129
130
  Sparkles,
130
- TriangleAlert as TriangleAlert2,
131
+ TriangleAlert,
131
132
  Video
132
133
  } from "lucide-react";
133
134
 
@@ -138,7 +139,7 @@ import {
138
139
  useId,
139
140
  useState as useState2
140
141
  } from "react";
141
- import { ImagePlus, TriangleAlert, Volume2, VolumeX, X } from "lucide-react";
142
+ import { ImagePlus, Volume2, VolumeX, X } from "lucide-react";
142
143
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
143
144
  var PILL = "inline-flex h-7 flex-none items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-2.5 text-[14px] font-medium text-foreground transition hover:bg-accent";
144
145
  var PILL_LABEL = "[text-box:trim-both_cap_alphabetic]";
@@ -605,78 +606,6 @@ function ReferencePill({
605
606
  )
606
607
  ] });
607
608
  }
608
- function ModelPill({
609
- models,
610
- value,
611
- displayName,
612
- provider,
613
- unavailable,
614
- onSelect,
615
- bandRef
616
- }) {
617
- const [open, setOpen] = useState2(false);
618
- const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(open, setOpen);
619
- const panelId = useId();
620
- useCloseWhenScrolledOut(open, setOpen, triggerRef, bandRef);
621
- return /* @__PURE__ */ jsxs("div", { ref: containerRef, className: "relative inline-flex flex-none", children: [
622
- /* @__PURE__ */ jsxs(
623
- "button",
624
- {
625
- type: "button",
626
- ...triggerProps,
627
- "aria-controls": open ? panelId : void 0,
628
- title: "Model",
629
- "aria-label": `Model: ${displayName}${unavailable ? " (unavailable)" : ""}`,
630
- onClick: () => setOpen(!open),
631
- className: `${PILL}${unavailable ? " border-warning/50" : ""}`,
632
- children: [
633
- unavailable && /* @__PURE__ */ jsx(TriangleAlert, { "aria-hidden": true, className: "h-3.5 w-3.5 shrink-0 text-warning", strokeWidth: 2 }),
634
- provider && /* @__PURE__ */ jsx(ProviderLogo, { provider, size: 14 }),
635
- /* @__PURE__ */ jsx("span", { className: "max-w-[168px] truncate leading-normal", children: displayName }),
636
- /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3 shrink-0 text-muted-foreground" })
637
- ]
638
- }
639
- ),
640
- /* @__PURE__ */ jsxs(
641
- PopoverSurface,
642
- {
643
- open,
644
- id: panelId,
645
- role: "menu",
646
- triggerRef,
647
- panelRef,
648
- className: `${MENU_PANEL} max-w-[320px]`,
649
- children: [
650
- /* @__PURE__ */ jsx("div", { className: MENU_HEADER, children: "Model" }),
651
- models.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-2.5 py-2 text-[14px] text-muted-foreground", children: "No models are available for this media type." }),
652
- models.map((model) => /* @__PURE__ */ jsxs(
653
- "button",
654
- {
655
- type: "button",
656
- role: "menuitemradio",
657
- "aria-checked": model.id === value,
658
- onClick: () => {
659
- onSelect(model.id);
660
- setOpen(false);
661
- },
662
- className: menuRowClass(model.id === value),
663
- children: [
664
- model.provider && /* @__PURE__ */ jsx("span", { className: model.status === "unavailable" ? "opacity-45" : void 0, children: /* @__PURE__ */ jsx(ProviderLogo, { provider: model.provider, size: 14 }) }),
665
- /* @__PURE__ */ jsx("span", { className: `truncate${model.status === "unavailable" ? " opacity-45" : ""}`, children: model.name || model.id }),
666
- model.status === "unavailable" ? /* @__PURE__ */ jsxs(Fragment, { children: [
667
- /* @__PURE__ */ jsx("span", { className: "ml-auto shrink-0 text-[14px] text-warning", children: "Unavailable" }),
668
- /* @__PURE__ */ jsx(TriangleAlert, { "aria-hidden": true, className: "h-3.5 w-3.5 shrink-0 text-warning", strokeWidth: 2 })
669
- ] }) : model.status === "limited" && /* @__PURE__ */ jsx("span", { className: "ml-auto shrink-0 text-[14px] capitalize text-muted-foreground", children: model.status }),
670
- model.id === value && /* @__PURE__ */ jsx(CheckGlyph, { className: `${model.status === "available" ? "ml-auto " : ""}h-3.5 w-3.5 shrink-0 text-primary` })
671
- ]
672
- },
673
- model.id
674
- ))
675
- ]
676
- }
677
- )
678
- ] });
679
- }
680
609
  function optionValueLabel(param, value) {
681
610
  if (typeof value === "boolean") return value ? "On" : "Off";
682
611
  const text = String(value);
@@ -786,6 +715,30 @@ function choicesFor(param, meta) {
786
715
  }
787
716
  return optionChoices(meta);
788
717
  }
718
+ var LANE_OUTPUT = {
719
+ image: "image",
720
+ video: "video",
721
+ speech: "speech"
722
+ };
723
+ function isPublishedPrice(price) {
724
+ return Boolean(price) && Number.isFinite(price?.usd) && (price?.usd ?? 0) > 0 && ["image", "second", "minute", "1k_chars"].includes(price?.unit ?? "");
725
+ }
726
+ function pickerModel(model, type) {
727
+ const reason = model.reason?.trim();
728
+ const capability = model.status === "unavailable" ? `Unavailable${reason ? ` \xB7 ${reason}` : ""}` : model.status === "limited" ? `Limited${reason ? ` \xB7 ${reason}` : ""}` : model.capability?.trim() || void 0;
729
+ return {
730
+ id: model.id,
731
+ name: model.name || model.id,
732
+ provider: model.provider ?? "",
733
+ output: LANE_OUTPUT[type],
734
+ ...isPublishedPrice(model.outputPrice) ? { outputPrice: model.outputPrice } : {},
735
+ ...model.previewUrl?.trim() ? { previewUrl: model.previewUrl.trim() } : {},
736
+ ...capability ? { capability } : {},
737
+ supportsTools: false,
738
+ supportsReasoning: false,
739
+ featured: false
740
+ };
741
+ }
789
742
  function visibleParams(type, options) {
790
743
  if (!options) return [];
791
744
  return PILL_ORDER[type].filter((param) => {
@@ -1059,6 +1012,9 @@ function StudioComposer({
1059
1012
  const loadingModels = Boolean(workspaceId) && (catalogLoading || !catalog && !catalogError);
1060
1013
  const modelStatus = loadingModels ? "Loading media models\u2026" : catalogError ?? (laneDown ? laneDownMessage : null);
1061
1014
  const showModelMenu = catalogReady && curatedModels.length > 0;
1015
+ const pickerModels = useMemo2(() => curatedModels.map((model) => pickerModel(model, type)), [curatedModels, type]);
1016
+ const modelDisplayName = laneDown ? "Unavailable" : modelOption?.name || modelId || "Select a model";
1017
+ const modelUnavailable = laneDown || modelOption?.status === "unavailable";
1062
1018
  const canReloadModels = Boolean(workspaceId) && !loadingModels && Boolean(catalogError || catalogReady && curatedModels.length === 0);
1063
1019
  function reloadModels() {
1064
1020
  if (!workspaceId || catalogLoading || catalogPendingRef.current) return;
@@ -1091,7 +1047,7 @@ function StudioComposer({
1091
1047
  ),
1092
1048
  modelStatus && /* @__PURE__ */ jsxs2("div", { id: laneWarningId, role: "status", className: "flex flex-wrap items-center gap-2 px-1.5 pb-3 pt-1.5 text-[14px] text-muted-foreground", children: [
1093
1049
  /* @__PURE__ */ jsxs2("span", { className: "flex min-w-0 max-w-full items-start gap-2", children: [
1094
- !loadingModels && /* @__PURE__ */ jsx2(TriangleAlert2, { "aria-hidden": true, className: "mt-0.5 h-4 w-4 shrink-0 text-warning", strokeWidth: 2 }),
1050
+ !loadingModels && /* @__PURE__ */ jsx2(TriangleAlert, { "aria-hidden": true, className: "mt-0.5 h-4 w-4 shrink-0 text-warning", strokeWidth: 2 }),
1095
1051
  /* @__PURE__ */ jsx2("span", { className: "min-w-0", children: modelStatus })
1096
1052
  ] }),
1097
1053
  canReloadModels && /* @__PURE__ */ jsx2("button", { type: "button", onClick: reloadModels, className: "rounded-md px-1 font-medium text-foreground underline underline-offset-4 hover:decoration-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring", children: catalogError ? "Retry models" : "Refresh models" })
@@ -1099,18 +1055,21 @@ function StudioComposer({
1099
1055
  /* @__PURE__ */ jsxs2("div", { className: "flex flex-wrap items-center gap-2 @[640px]/studio-composer:flex-nowrap", children: [
1100
1056
  /* @__PURE__ */ jsx2(MediaTypeSegments, { value: type, segments: SEGMENTS, onChange: setType }),
1101
1057
  /* @__PURE__ */ jsxs2(ComposerBand, { bandRef, resetKey: type, children: [
1102
- showModelMenu && /* @__PURE__ */ jsx2(
1103
- ModelPill,
1058
+ showModelMenu && /* @__PURE__ */ jsx2("div", { className: "flex-none", children: /* @__PURE__ */ jsx2(
1059
+ ModelPicker,
1104
1060
  {
1105
- models: curatedModels,
1106
- value: laneDown ? "" : modelId,
1107
- displayName: laneDown ? "Unavailable" : modelOption?.name || modelId || "Select a model",
1108
- provider: laneDown ? void 0 : modelOption?.provider,
1109
- unavailable: laneDown || modelOption?.status === "unavailable",
1110
- onSelect: chooseModel,
1111
- bandRef
1061
+ value: laneDown ? "" : textToVideoSibling(modelId) ?? modelId,
1062
+ onChange: chooseModel,
1063
+ models: pickerModels,
1064
+ priorityGroup: { label: `${laneLabel} models`, match: () => true },
1065
+ "aria-label": `Model: ${modelDisplayName}${modelUnavailable ? " (unavailable)" : ""}`,
1066
+ triggerContent: /* @__PURE__ */ jsxs2("span", { className: "contents", children: [
1067
+ modelUnavailable && /* @__PURE__ */ jsx2(TriangleAlert, { "aria-hidden": true, className: "h-3.5 w-3.5 shrink-0 text-warning", strokeWidth: 2 }),
1068
+ !laneDown && modelOption?.provider && /* @__PURE__ */ jsx2("span", { className: "shrink-0", "aria-hidden": true, children: /* @__PURE__ */ jsx2(ProviderLogo, { provider: modelOption.provider, size: 16 }) }),
1069
+ /* @__PURE__ */ jsx2("span", { className: "max-w-[160px] truncate leading-normal", children: modelDisplayName })
1070
+ ] })
1112
1071
  }
1113
- ),
1072
+ ) }),
1114
1073
  params.map((param) => /* @__PURE__ */ jsx2("div", { className: "studio-pill-in flex-none", children: /* @__PURE__ */ jsx2(
1115
1074
  OptionPill,
1116
1075
  {
@@ -3376,7 +3335,6 @@ export {
3376
3335
  MediaTypeSegments,
3377
3336
  MediaViewerModal,
3378
3337
  MenuPill,
3379
- ModelPill,
3380
3338
  OptionPill,
3381
3339
  ReferencePill,
3382
3340
  StudioComposer,