@tangle-network/agent-app 0.45.1 → 0.45.3

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 (36) hide show
  1. package/dist/assistant/index.js +3 -3
  2. package/dist/assistant/index.js.map +1 -1
  3. package/dist/chat-routes/index.js +4 -4
  4. package/dist/{chunk-CQZSAR77.js → chunk-73F3CKVK.js} +28 -18
  5. package/dist/chunk-73F3CKVK.js.map +1 -0
  6. package/dist/{chunk-EC7CUA4L.js → chunk-AOQ4FCSH.js} +4 -4
  7. package/dist/chunk-AOQ4FCSH.js.map +1 -0
  8. package/dist/{chunk-ICOHEZK6.js → chunk-ITCINLSU.js} +2 -2
  9. package/dist/{chunk-3EJ6SFJI.js → chunk-IVEKCOM7.js} +68 -26
  10. package/dist/chunk-IVEKCOM7.js.map +1 -0
  11. package/dist/{chunk-WXWU2FEB.js → chunk-YRFB2KEA.js} +96 -87
  12. package/dist/chunk-YRFB2KEA.js.map +1 -0
  13. package/dist/design-canvas/index.d.ts +2 -1
  14. package/dist/design-canvas/index.js +1 -1
  15. package/dist/harness/index.d.ts +25 -8
  16. package/dist/harness/index.js +1 -1
  17. package/dist/mcp-BOgNWSED.d.ts +174 -0
  18. package/dist/run/index.js +1 -1
  19. package/dist/runtime/index.d.ts +17 -7
  20. package/dist/runtime/index.js.map +1 -1
  21. package/dist/sandbox/index.d.ts +31 -1
  22. package/dist/sandbox/index.js +4 -4
  23. package/dist/sequences/index.d.ts +2 -1
  24. package/dist/sequences/index.js +1 -1
  25. package/dist/skills-placement/index.js +1 -1
  26. package/dist/tools/index.d.ts +2 -1
  27. package/dist/tools/index.js +5 -3
  28. package/dist/web-react/index.d.ts +9 -2
  29. package/dist/web-react/index.js +2 -2
  30. package/package.json +3 -3
  31. package/dist/chunk-3EJ6SFJI.js.map +0 -1
  32. package/dist/chunk-CQZSAR77.js.map +0 -1
  33. package/dist/chunk-EC7CUA4L.js.map +0 -1
  34. package/dist/chunk-WXWU2FEB.js.map +0 -1
  35. package/dist/mcp-Dt4V4ZLT.d.ts +0 -95
  36. /package/dist/{chunk-ICOHEZK6.js.map → chunk-ITCINLSU.js.map} +0 -0
@@ -32,32 +32,67 @@ async function readToolArgs(request) {
32
32
  }
33
33
 
34
34
  // src/tools/mcp.ts
35
+ import {
36
+ agentProfileMcpServerSchema,
37
+ defineAgentProfilePublicConfig,
38
+ defineAgentProfileSecretRef
39
+ } from "@tangle-network/agent-interface";
35
40
  var DEFAULT_APP_TOOL_PATHS = {
36
41
  submit_proposal: "/api/tools/propose",
37
42
  schedule_followup: "/api/tools/followup",
38
43
  render_ui: "/api/tools/render-ui",
39
44
  add_citation: "/api/tools/citation"
40
45
  };
46
+ var ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
47
+ function assertSecretEnvKey(key, label) {
48
+ if (!ENV_NAME_PATTERN.test(key)) {
49
+ throw new Error(
50
+ `${label}: tokenEnvKey must be an environment-variable NAME the sandbox box carries (e.g. 'APP_CAPABILITY_TOKEN'), not a token value \u2014 got ${JSON.stringify(key)}. A profile may only REFERENCE a credential; the value is placed on the box by SandboxRuntimeConfig.env or the platform secret store.`
51
+ );
52
+ }
53
+ return key;
54
+ }
55
+ function assertProfileMcpServer(server, label) {
56
+ const result = agentProfileMcpServerSchema.safeParse(server);
57
+ if (!result.success) {
58
+ const issues = result.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
59
+ throw new Error(
60
+ `${label} produced an MCP server the AgentProfile contract rejects: ${issues}. Requires @tangle-network/agent-interface >= 0.38.0 (tagged MCP config values).`
61
+ );
62
+ }
63
+ return server;
64
+ }
65
+ function unresolvableSurfaceCredential(surface) {
66
+ throw new Error(
67
+ `The ${surface} MCP surface cannot be mounted: its capability token is scoped to a single user and resource, and an AgentProfile may only reference a credential the sandbox can resolve from the box environment, which is workspace-wide and fixed at sandbox creation. Mounting it needs a per-session secret channel on the sandbox API, or a route that authenticates the workspace rather than the caller.`
68
+ );
69
+ }
41
70
  function buildHttpMcpServer(opts) {
42
71
  const base = opts.baseUrl.replace(/\/+$/, "");
43
72
  const h = opts.headerNames ?? DEFAULT_HEADER_NAMES;
44
- return {
45
- transport: "http",
46
- url: `${base}${opts.path}`,
47
- headers: {
48
- Authorization: `Bearer ${opts.token}`,
49
- [h.userId]: opts.ctx.userId,
50
- ...opts.ctx.workspaceId ? { [h.workspaceId]: opts.ctx.workspaceId } : {},
51
- ...opts.ctx.threadId ? { [h.threadId]: opts.ctx.threadId } : {},
52
- "Content-Type": "application/json"
73
+ return assertProfileMcpServer(
74
+ {
75
+ transport: "http",
76
+ url: `${base}${opts.path}`,
77
+ headers: {
78
+ Authorization: defineAgentProfileSecretRef(
79
+ assertSecretEnvKey(opts.tokenEnvKey, "buildHttpMcpServer"),
80
+ "bearer"
81
+ ),
82
+ [h.userId]: defineAgentProfilePublicConfig(opts.ctx.userId),
83
+ ...opts.ctx.workspaceId ? { [h.workspaceId]: defineAgentProfilePublicConfig(opts.ctx.workspaceId) } : {},
84
+ ...opts.ctx.threadId ? { [h.threadId]: defineAgentProfilePublicConfig(opts.ctx.threadId) } : {},
85
+ "Content-Type": defineAgentProfilePublicConfig("application/json")
86
+ },
87
+ enabled: true,
88
+ metadata: { description: opts.description }
53
89
  },
54
- enabled: true,
55
- metadata: { description: opts.description }
56
- };
90
+ "buildHttpMcpServer"
91
+ );
57
92
  }
58
93
  function buildScopedMcpServerEntry(opts) {
59
- if (opts.token.trim().length === 0) {
60
- throw new Error(`${opts.label} requires a capability token \u2014 omit the MCP server when none is available`);
94
+ if (opts.tokenEnvKey.trim().length === 0) {
95
+ throw new Error(`${opts.label} requires a capability token env key \u2014 omit the MCP server when none is available`);
61
96
  }
62
97
  if (!opts.path.startsWith("/")) {
63
98
  throw new Error(`${opts.label} path must start with "/" (got "${opts.path}")`);
@@ -67,22 +102,28 @@ function buildScopedMcpServerEntry(opts) {
67
102
  return buildHttpMcpServer({
68
103
  path: opts.path,
69
104
  baseUrl: opts.baseUrl,
70
- token: opts.token,
105
+ tokenEnvKey: opts.tokenEnvKey,
71
106
  ctx: opts.ctx,
72
107
  description,
73
108
  headerNames: opts.headerNames ?? DEFAULT_HEADER_NAMES
74
109
  });
75
110
  }
76
- return {
77
- transport: "http",
78
- url: `${opts.baseUrl.replace(/\/+$/, "")}${opts.path}`,
79
- headers: {
80
- Authorization: `Bearer ${opts.token}`,
81
- "Content-Type": "application/json"
111
+ return assertProfileMcpServer(
112
+ {
113
+ transport: "http",
114
+ url: `${opts.baseUrl.replace(/\/+$/, "")}${opts.path}`,
115
+ headers: {
116
+ Authorization: defineAgentProfileSecretRef(
117
+ assertSecretEnvKey(opts.tokenEnvKey, opts.label),
118
+ "bearer"
119
+ ),
120
+ "Content-Type": defineAgentProfilePublicConfig("application/json")
121
+ },
122
+ enabled: true,
123
+ metadata: { description }
82
124
  },
83
- enabled: true,
84
- metadata: { description }
85
- };
125
+ opts.label
126
+ );
86
127
  }
87
128
  function buildAppToolMcpServer(opts) {
88
129
  const path = typeof opts.tool === "string" ? opts.paths?.[opts.tool] ?? DEFAULT_APP_TOOL_PATHS[opts.tool] : opts.paths?.[opts.tool.name] ?? opts.tool.path;
@@ -93,7 +134,7 @@ function buildAppToolMcpServer(opts) {
93
134
  return buildHttpMcpServer({
94
135
  path,
95
136
  baseUrl: opts.baseUrl,
96
- token: opts.token,
137
+ tokenEnvKey: opts.tokenEnvKey,
97
138
  ctx: opts.ctx,
98
139
  description: opts.description,
99
140
  headerNames: opts.headerNames
@@ -220,10 +261,11 @@ export {
220
261
  authenticateToolRequest,
221
262
  readToolArgs,
222
263
  DEFAULT_APP_TOOL_PATHS,
264
+ unresolvableSurfaceCredential,
223
265
  buildHttpMcpServer,
224
266
  buildScopedMcpServerEntry,
225
267
  buildAppToolMcpServer,
226
268
  MCP_PROTOCOL_VERSIONS,
227
269
  createMcpToolHandler
228
270
  };
229
- //# sourceMappingURL=chunk-3EJ6SFJI.js.map
271
+ //# sourceMappingURL=chunk-IVEKCOM7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/auth.ts","../src/tools/mcp.ts","../src/tools/mcp-rpc.ts"],"sourcesContent":["import type { AppToolContext } from './types'\n\n/**\n * Header names carrying the server-set per-turn context + the capability token.\n * Defaults are product-neutral (`X-Agent-App-*`); a product that already ships\n * a header convention (e.g. `X-Acme-User-Id`) passes its own.\n */\nexport interface ToolHeaderNames {\n userId: string\n workspaceId: string\n threadId: string\n}\n\n/** Provide default HTTP header names for user, workspace, and thread identification */\nexport const DEFAULT_HEADER_NAMES: ToolHeaderNames = {\n userId: 'X-Agent-App-User-Id',\n workspaceId: 'X-Agent-App-Workspace-Id',\n threadId: 'X-Agent-App-Thread-Id',\n}\n\n/** Define options to verify bearer tokens and customize authentication header names */\nexport interface AuthenticateOptions {\n /** Verify the bearer capability token belongs to `userId`. The product's\n * HMAC/JWT impl — the seam that keeps token crypto out of this package. */\n verifyToken: (userId: string, bearer: string) => Promise<boolean>\n headerNames?: ToolHeaderNames\n}\n\n/** Represent the result of tool authentication with success context or failure response */\nexport type ToolAuthResult =\n | { ok: true; ctx: AppToolContext }\n | { ok: false; response: Response }\n\n/**\n * Recover + verify the trusted context for a tool request. The user comes from\n * a server-set header and the bearer token MUST verify against THAT user; the\n * workspace comes from a header too — never from tool args — so the model can\n * neither forge identity nor target another workspace. Fail-closed: any missing\n * credential or a token minted for another user yields a 401/400 Response.\n */\nexport async function authenticateToolRequest(request: Request, opts: AuthenticateOptions): Promise<ToolAuthResult> {\n const h = opts.headerNames ?? DEFAULT_HEADER_NAMES\n const userId = request.headers.get(h.userId)?.trim()\n const workspaceId = request.headers.get(h.workspaceId)?.trim()\n const threadId = request.headers.get(h.threadId)?.trim() || null\n const bearer = request.headers.get('authorization')?.match(/^Bearer\\s+(.+)$/i)?.[1]\n\n if (!userId || !bearer) {\n return { ok: false, response: Response.json({ error: 'Missing capability credentials' }, { status: 401 }) }\n }\n if (!(await opts.verifyToken(userId, bearer))) {\n return { ok: false, response: Response.json({ error: 'Invalid capability token' }, { status: 401 }) }\n }\n if (!workspaceId) {\n return { ok: false, response: Response.json({ error: 'Missing workspace context' }, { status: 400 }) }\n }\n return { ok: true, ctx: { userId, workspaceId, threadId } }\n}\n\n/** Read a tool's argument object from the request body, tolerant of MCP host\n * aliases (`args` / `arguments`) or a bare body. Returns null on non-JSON. */\nexport async function readToolArgs<T>(request: Request): Promise<T | null> {\n let body: { args?: T; arguments?: T }\n try {\n body = (await request.json()) as typeof body\n } catch {\n return null\n }\n return (body.args ?? body.arguments ?? (body as T)) as T\n}\n","/**\n * The tagged-configuration contract for every MCP server this package emits.\n *\n * An `AgentProfile` is digested, diffed, stored, and logged, so a credential\n * that rides it as plain text is a leak by construction. `@tangle-network/\n * agent-interface` closed that at **0.38.0**: `args`, `env`, and `headers` on\n * an `AgentProfileMcpServer` no longer take strings. Every value is either\n * deliberately public profile material (`defineAgentProfilePublicConfig`) or an\n * opaque reference to a credential (`defineAgentProfileSecretRef`) resolved\n * privately at materialization, validated by a `z.discriminatedUnion('kind')`.\n *\n * The schema also refuses to let a secret hide as public material: a `public`\n * value under a credential-bearing key name (`Authorization`, `*_TOKEN`,\n * `*_API_KEY`, `*_SECRET`, `Cookie`, …) is rejected with \"credential-bearing\n * config names require a secret-ref\", and any value whose bytes look like a\n * credential (`Bearer …`, `sk-…`, `ghp_…`) is rejected outright. So the\n * capability token this package used to inline as `Bearer <token>` cannot be\n * expressed at all — it must become a reference.\n *\n * **A reference resolves ONLY from an environment variable present on the box,\n * named by `key`.** That is why the builders below take a `tokenEnvKey` (the\n * box-env variable NAME) instead of a token VALUE: agent-app cannot guess the\n * name, and a reference to a key nothing places fails the turn at\n * materialization rather than running credential-less. The box env is what\n * `SandboxRuntimeConfig.env` (and the platform secret store via\n * `SandboxRuntimeConfig.secrets`) writes at sandbox creation, so the key must\n * name a variable one of those places — and it must therefore be a real\n * environment-variable name, which this module enforces.\n *\n * A per-request credential is only referenceable when the value written at box\n * creation is byte-identical to the one every later turn would mint (a\n * deterministic derivation such as an HMAC over the workspace id). A token\n * scoped narrower than the box — per-user, per-document — cannot be referenced\n * at all; {@link unresolvableSurfaceCredential} names that blocker instead of\n * emitting a reference that resolves to nothing.\n */\nimport {\n agentProfileMcpServerSchema,\n defineAgentProfilePublicConfig,\n defineAgentProfileSecretRef,\n type AgentProfileConfigValue,\n} from '@tangle-network/agent-interface'\nimport type { AppToolContext } from './types'\nimport type { AppToolName } from './openai'\nimport type { AppToolDefinition } from './registry'\nimport type { ToolHeaderNames } from './auth'\nimport { DEFAULT_HEADER_NAMES } from './auth'\n\n/** Default route path each app tool is served at. A product mounts its routes\n * at these paths (or supplies its own via {@link BuildMcpServerOptions.paths}). */\nexport const DEFAULT_APP_TOOL_PATHS: Record<AppToolName, string> = {\n submit_proposal: '/api/tools/propose',\n schedule_followup: '/api/tools/followup',\n render_ui: '/api/tools/render-ui',\n add_citation: '/api/tools/citation',\n}\n\n/** The portable MCP server entry the sandbox SDK accepts (transport + url +\n * tagged headers). Assignable to `AgentProfileMcpServer` without a cast —\n * products spread it into their profile's `mcp` map. */\nexport interface AppToolMcpServer {\n transport: 'http'\n url: string\n headers: Record<string, AgentProfileConfigValue>\n enabled: true\n metadata: { description: string }\n}\n\n/** POSIX environment-variable name — the same shape `agent-interface`'s\n * `environmentNameSchema` accepts for an env key. A secret reference resolves\n * from the box environment, so a key outside this shape can never resolve. */\nconst ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/**\n * Reject a secret-reference key that names nothing the box can hold.\n *\n * `agent-interface` accepts any non-credential string as a reference key, so a\n * typo or a token VALUE passed where a key belongs validates against the\n * profile schema and fails much later, inside materialization, as an opaque\n * missing-secret error. Failing here names the parameter.\n */\nfunction assertSecretEnvKey(key: string, label: string): string {\n if (!ENV_NAME_PATTERN.test(key)) {\n throw new Error(\n `${label}: tokenEnvKey must be an environment-variable NAME the sandbox box carries ` +\n `(e.g. 'APP_CAPABILITY_TOKEN'), not a token value — got ${JSON.stringify(key)}. ` +\n 'A profile may only REFERENCE a credential; the value is placed on the box by ' +\n 'SandboxRuntimeConfig.env or the platform secret store.',\n )\n }\n return key\n}\n\n/**\n * Validate one emitted entry against the REAL `agentProfileMcpServerSchema`.\n *\n * The contract's rules (which key names demand a reference, which byte patterns\n * read as a credential) live in `agent-interface`. Re-implementing them here\n * would drift the moment that package moves — which it does: 0.36.0 → 0.40.0 in\n * three days. Running the shipped validator instead means a product that passes\n * a credential-bearing custom header name, a relative base URL, or a URL with\n * embedded credentials fails at the builder with the contract's own message.\n *\n * It is also the loud failure for a version skew: if the resolved\n * `@tangle-network/agent-interface` predates 0.38.0, its schema rejects the\n * tagged shape this package now emits, and that surfaces here instead of as a\n * sandbox provisioning error.\n */\nfunction assertProfileMcpServer<T extends AppToolMcpServer>(server: T, label: string): T {\n const result = agentProfileMcpServerSchema.safeParse(server)\n if (!result.success) {\n const issues = result.error.issues\n .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('; ')\n throw new Error(\n `${label} produced an MCP server the AgentProfile contract rejects: ${issues}. ` +\n 'Requires @tangle-network/agent-interface >= 0.38.0 (tagged MCP config values).',\n )\n }\n return server\n}\n\n/**\n * Refuse to mount a surface whose credential is scoped narrower than the box.\n *\n * A per-user or per-resource capability token is minted per request. The box\n * environment is written once at sandbox creation and shared by every turn and\n * every member of the workspace, so such a token can neither be placed there\n * ahead of time nor referenced from a per-turn profile. Widening the channel to\n * a workspace-bound token is not a substitute when the route authenticates the\n * CALLER: the agent can read its own box env, so it could forge that identity.\n *\n * Mounting the surface anyway would emit a plain-string `Authorization` header\n * (rejected by the schema) or a reference to a key nothing places (rejected at\n * materialization). Throwing here names the actual blocker. Exported because\n * every product with per-document MCP surfaces hits it and was writing this\n * message itself.\n */\nexport function unresolvableSurfaceCredential(surface: string): never {\n throw new Error(\n `The ${surface} MCP surface cannot be mounted: its capability token is scoped to a single ` +\n 'user and resource, and an AgentProfile may only reference a credential the sandbox can ' +\n 'resolve from the box environment, which is workspace-wide and fixed at sandbox creation. ' +\n 'Mounting it needs a per-session secret channel on the sandbox API, or a route that ' +\n 'authenticates the workspace rather than the caller.',\n )\n}\n\n/** Define configuration options for building an HTTP MCP server including path, baseUrl, token env key, context, and description */\nexport interface BuildHttpMcpServerOptions {\n /** Route path on the app the sandbox POSTs to (e.g. `/api/tools/propose`). */\n path: string\n /** App base URL the sandbox reaches back to (no trailing slash required). */\n baseUrl: string\n /**\n * NAME of the box-environment variable holding the capability token — never\n * the token itself. The emitted `Authorization` header is a `secret-ref` to\n * this key with `format: 'bearer'`, so the sandbox resolves the value\n * privately and the profile carries only the name.\n *\n * The key MUST name a variable the box actually carries (placed by\n * `SandboxRuntimeConfig.env` at creation, or injected from the platform\n * secret store via `SandboxRuntimeConfig.secrets`), and the value written\n * there must be the token this route will accept for every turn — which in\n * practice means a deterministic derivation (e.g. an HMAC over the workspace\n * id), not a freshly-random per-request mint. A token scoped narrower than\n * the box is not referenceable: see {@link unresolvableSurfaceCredential}.\n */\n tokenEnvKey: string\n ctx: AppToolContext\n /** Tool description the model sees. */\n description: string\n headerNames?: ToolHeaderNames\n}\n\n/**\n * Build ONE HTTP MCP server entry — the generic agent→app bridge. The\n * capability token (as a secret reference) + the user/workspace/thread ids ride\n * in server-set headers (never tool args), so the model can't forge identity or\n * target another workspace. Workspace/thread headers are omitted when their\n * `ctx` value is empty/null (e.g. an integration-invoke bridge that's\n * user-scoped only). Used directly for non-app-tool bridges\n * (integration_invoke) and via {@link buildAppToolMcpServer} for the four app\n * tools.\n */\nexport function buildHttpMcpServer(opts: BuildHttpMcpServerOptions): AppToolMcpServer {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const h = opts.headerNames ?? DEFAULT_HEADER_NAMES\n return assertProfileMcpServer(\n {\n transport: 'http',\n url: `${base}${opts.path}`,\n headers: {\n Authorization: defineAgentProfileSecretRef(\n assertSecretEnvKey(opts.tokenEnvKey, 'buildHttpMcpServer'),\n 'bearer',\n ),\n [h.userId]: defineAgentProfilePublicConfig(opts.ctx.userId),\n ...(opts.ctx.workspaceId\n ? { [h.workspaceId]: defineAgentProfilePublicConfig(opts.ctx.workspaceId) }\n : {}),\n ...(opts.ctx.threadId\n ? { [h.threadId]: defineAgentProfilePublicConfig(opts.ctx.threadId) }\n : {}),\n 'Content-Type': defineAgentProfilePublicConfig('application/json'),\n },\n enabled: true,\n metadata: { description: opts.description },\n },\n 'buildHttpMcpServer',\n )\n}\n\n/** Options for a per-document/scoped MCP channel entry (design-canvas,\n * sequences, …). The capability token + path scope ONE resource; the document\n * id lives in the path, never a tool argument. */\nexport interface ScopedMcpServerEntryOptions {\n /** App base URL the sandbox reaches back to (trailing slash tolerated). */\n baseUrl: string\n /** Product route serving the resource's MCP handler — id is part of the path. */\n path: string\n /**\n * NAME of the box-environment variable holding this channel's capability\n * token — never the token itself. See\n * {@link BuildHttpMcpServerOptions.tokenEnvKey}.\n *\n * A per-(user, resource) token cannot satisfy this: the box environment is\n * workspace-wide and fixed at sandbox creation. A product whose channel needs\n * one calls {@link unresolvableSurfaceCredential} rather than mounting an\n * entry that cannot resolve.\n */\n tokenEnvKey: string\n /** Override the channel's default tool-server description. */\n description?: string\n /** Identity headers for products whose route recovers the user via\n * `authenticateToolRequest`. Omit when the bearer token is self-contained. */\n ctx?: AppToolContext\n headerNames?: ToolHeaderNames\n}\n\n/**\n * Build the `AgentProfileMcpServer`-shaped entry for a scoped, per-resource MCP\n * channel. The shared mechanism behind the per-domain entry builders\n * (`buildDesignCanvasMcpServerEntry`, `buildSequencesMcpServerEntry`): same\n * token/path guards, same description default, same ctx-vs-self-contained-token\n * branching. The domain is two parameters — `label` (for guard messages) and\n * `defaultDescription` — never baked.\n *\n * The no-`ctx` branch is a GENUINE behavioral path, not a shortcut: it emits a\n * self-contained-token entry with ONLY `Authorization` + `Content-Type`.\n * Routing it through {@link buildHttpMcpServer} would unconditionally write a\n * `userId` identity header (here `undefined`), so it stays a distinct branch.\n */\nexport function buildScopedMcpServerEntry(\n opts: ScopedMcpServerEntryOptions & { label: string; defaultDescription: string },\n): AppToolMcpServer {\n if (opts.tokenEnvKey.trim().length === 0) {\n throw new Error(`${opts.label} requires a capability token env key — omit the MCP server when none is available`)\n }\n if (!opts.path.startsWith('/')) {\n throw new Error(`${opts.label} path must start with \"/\" (got \"${opts.path}\")`)\n }\n const description = opts.description ?? opts.defaultDescription\n\n if (opts.ctx) {\n return buildHttpMcpServer({\n path: opts.path,\n baseUrl: opts.baseUrl,\n tokenEnvKey: opts.tokenEnvKey,\n ctx: opts.ctx,\n description,\n headerNames: opts.headerNames ?? DEFAULT_HEADER_NAMES,\n })\n }\n\n return assertProfileMcpServer(\n {\n transport: 'http',\n url: `${opts.baseUrl.replace(/\\/+$/, '')}${opts.path}`,\n headers: {\n Authorization: defineAgentProfileSecretRef(\n assertSecretEnvKey(opts.tokenEnvKey, opts.label),\n 'bearer',\n ),\n 'Content-Type': defineAgentProfilePublicConfig('application/json'),\n },\n enabled: true,\n metadata: { description },\n },\n opts.label,\n )\n}\n\n/** Define configuration options required to build an MCP server including tool, baseUrl, token, and context */\nexport interface BuildMcpServerOptions {\n /** A built-in app tool name, or a product-registered {@link AppToolDefinition}.\n * A custom tool supplies its route via `AppToolDefinition.path` (or `paths`). */\n tool: AppToolName | AppToolDefinition\n baseUrl: string\n /** NAME of the box-environment variable holding the capability token — see\n * {@link BuildHttpMcpServerOptions.tokenEnvKey}. */\n tokenEnvKey: string\n ctx: AppToolContext\n description: string\n headerNames?: ToolHeaderNames\n paths?: Partial<Record<string, string>>\n}\n\n/** Build one app-tool MCP server entry — a thin wrapper over\n * {@link buildHttpMcpServer} that resolves the tool's route path. Built-ins map\n * through {@link DEFAULT_APP_TOOL_PATHS}; a custom tool uses its own `path`\n * (or a `paths` override). */\nexport function buildAppToolMcpServer(opts: BuildMcpServerOptions): AppToolMcpServer {\n const path =\n typeof opts.tool === 'string'\n ? opts.paths?.[opts.tool] ?? DEFAULT_APP_TOOL_PATHS[opts.tool]\n : opts.paths?.[opts.tool.name] ?? opts.tool.path\n if (!path) {\n const name = typeof opts.tool === 'string' ? opts.tool : opts.tool.name\n throw new Error(`buildAppToolMcpServer: tool \"${name}\" has no route path — set AppToolDefinition.path or pass it via opts.paths`)\n }\n return buildHttpMcpServer({\n path,\n baseUrl: opts.baseUrl,\n tokenEnvKey: opts.tokenEnvKey,\n ctx: opts.ctx,\n description: opts.description,\n headerNames: opts.headerNames,\n })\n}\n","/**\n * Generic streamable-HTTP JSON-RPC 2.0 envelope for a tools-only MCP server.\n * Stateless, Workers-compatible: no session table, no SSE — every request gets\n * a single `application/json` response, which the streamable-HTTP transport\n * explicitly permits for tools-only servers.\n *\n * Protocol surface:\n * initialize → echo client's protocolVersion if supported, else latest\n * ping → empty result {}\n * notifications/* (no `id`) → 202 with no body\n * tools/list → tool manifest\n * tools/call → run + surface execution failures as isError text results\n * anything else → -32601\n *\n * Execution failures (argument shape, validation, store throws) become `isError`\n * tool results carrying the thrown message verbatim — the model reads WHY and\n * retries. Protocol misuse becomes a JSON-RPC error object.\n */\n\nexport const MCP_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'] as const\n/** Resolve a valid protocol version from the predefined MCP_PROTOCOL_VERSIONS array */\nexport type McpProtocolVersion = (typeof MCP_PROTOCOL_VERSIONS)[number]\n\nconst LATEST_PROTOCOL_VERSION: McpProtocolVersion = MCP_PROTOCOL_VERSIONS[0]\n\n/** Describe the structure of server information including name and version */\nexport interface McpServerInfo {\n name: string\n version: string\n}\n\n/** One tool entry in the registry the handler owns. */\nexport interface McpToolDefinition<TEnv = Record<string, never>> {\n name: string\n description: string\n /** JSON Schema for the `params.arguments` object. */\n inputSchema: Record<string, unknown>\n /** Receive validated (Record) args + the env the handler threaded; throw to\n * surface an isError result — never throw for protocol/framing issues. */\n run(args: Record<string, unknown>, env: TEnv): Promise<unknown>\n}\n\n/** Define options for creating a handler that manages MCP tools with environment support */\nexport interface CreateMcpToolHandlerOptions<TEnv = Record<string, never>> {\n serverInfo: McpServerInfo\n /** Full tool list; order IS the tools/list order. */\n tools: McpToolDefinition<TEnv>[]\n /** Per-request environment threaded into every `run` call. If your tools are\n * stateless (or carry state through closure) pass an empty builder:\n * `() => ({} as TEnv)`. */\n buildEnv(request: Request): TEnv | Promise<TEnv>\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\ntype JsonRpcId = string | number | null\n\ninterface ToolCallContent {\n content: Array<{ type: 'text'; text: string }>\n isError?: true\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction rpcResult(id: JsonRpcId, result: unknown): Response {\n return Response.json({ jsonrpc: '2.0', id, result })\n}\n\nfunction rpcError(id: JsonRpcId, code: number, message: string, status = 200): Response {\n return Response.json({ jsonrpc: '2.0', id, error: { code, message } }, { status })\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build a request handler for a tools-only MCP server. The returned function\n * accepts a standard `Request` and resolves to a `Response` — mount it on any\n * Cloudflare Worker route or Remix `loader`.\n *\n * The handler calls `buildEnv` exactly ONCE per `tools/call` request (after\n * the tool is found, before `run`) — non-`tools/call` paths skip it entirely\n * so metadata requests do not pay env-build cost.\n */\nexport function createMcpToolHandler<TEnv = Record<string, never>>(\n opts: CreateMcpToolHandlerOptions<TEnv>,\n): (request: Request) => Promise<Response> {\n const toolMap = new Map<string, McpToolDefinition<TEnv>>()\n for (const tool of opts.tools) {\n if (toolMap.has(tool.name)) throw new Error(`duplicate MCP tool name: ${tool.name}`)\n toolMap.set(tool.name, tool)\n }\n\n return async (request: Request): Promise<Response> => {\n if (request.method !== 'POST') {\n return new Response('MCP server accepts JSON-RPC 2.0 over POST only', {\n status: 405,\n headers: { Allow: 'POST' },\n })\n }\n\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return rpcError(null, -32700, 'Parse error: request body is not valid JSON', 400)\n }\n\n if (Array.isArray(body)) {\n return rpcError(null, -32600, 'Invalid request: JSON-RPC batching is not supported', 400)\n }\n if (!isRecord(body) || body.jsonrpc !== '2.0' || typeof body.method !== 'string') {\n return rpcError(\n null,\n -32600,\n 'Invalid request: expected a JSON-RPC 2.0 object with jsonrpc \"2.0\" and a string method',\n 400,\n )\n }\n\n const method = body.method\n const params = isRecord(body.params) ? body.params : {}\n\n // Notifications have no `id` — acknowledge without a JSON-RPC body.\n if (!('id' in body) || body.id === undefined) {\n return new Response(null, { status: 202 })\n }\n const id = body.id as JsonRpcId\n\n switch (method) {\n case 'initialize': {\n const requested = typeof params.protocolVersion === 'string' ? params.protocolVersion : undefined\n const protocolVersion =\n requested !== undefined && (MCP_PROTOCOL_VERSIONS as readonly string[]).includes(requested)\n ? requested\n : LATEST_PROTOCOL_VERSION\n return rpcResult(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: opts.serverInfo,\n })\n }\n\n case 'ping':\n return rpcResult(id, {})\n\n case 'tools/list':\n return rpcResult(id, {\n tools: opts.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n })),\n })\n\n case 'tools/call': {\n const name = params.name\n if (typeof name !== 'string' || name.length === 0) {\n return rpcError(id, -32602, 'tools/call requires params.name (string)')\n }\n const tool = toolMap.get(name)\n if (!tool) {\n return rpcError(\n id,\n -32602,\n `Unknown tool: ${name}. Available tools: ${opts.tools.map((t) => t.name).join(', ')}`,\n )\n }\n if (params.arguments !== undefined && !isRecord(params.arguments)) {\n return rpcError(id, -32602, 'tools/call params.arguments must be an object when provided')\n }\n const args = isRecord(params.arguments) ? params.arguments : {}\n let env: TEnv\n try {\n env = await opts.buildEnv(request)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n const payload: ToolCallContent = {\n content: [{ type: 'text', text: `${name} failed to build env: ${message}` }],\n isError: true,\n }\n return rpcResult(id, payload)\n }\n try {\n const result = await tool.run(args, env)\n const payload: ToolCallContent = { content: [{ type: 'text', text: JSON.stringify(result) }] }\n return rpcResult(id, payload)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n const payload: ToolCallContent = {\n content: [{ type: 'text', text: `${name} failed: ${message}` }],\n isError: true,\n }\n return rpcResult(id, payload)\n }\n }\n\n default:\n return rpcError(id, -32601, `Method not found: ${method}`)\n }\n }\n}\n"],"mappings":";AAcO,IAAM,uBAAwC;AAAA,EACnD,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,UAAU;AACZ;AAsBA,eAAsB,wBAAwB,SAAkB,MAAoD;AAClH,QAAM,IAAI,KAAK,eAAe;AAC9B,QAAM,SAAS,QAAQ,QAAQ,IAAI,EAAE,MAAM,GAAG,KAAK;AACnD,QAAM,cAAc,QAAQ,QAAQ,IAAI,EAAE,WAAW,GAAG,KAAK;AAC7D,QAAM,WAAW,QAAQ,QAAQ,IAAI,EAAE,QAAQ,GAAG,KAAK,KAAK;AAC5D,QAAM,SAAS,QAAQ,QAAQ,IAAI,eAAe,GAAG,MAAM,kBAAkB,IAAI,CAAC;AAElF,MAAI,CAAC,UAAU,CAAC,QAAQ;AACtB,WAAO,EAAE,IAAI,OAAO,UAAU,SAAS,KAAK,EAAE,OAAO,iCAAiC,GAAG,EAAE,QAAQ,IAAI,CAAC,EAAE;AAAA,EAC5G;AACA,MAAI,CAAE,MAAM,KAAK,YAAY,QAAQ,MAAM,GAAI;AAC7C,WAAO,EAAE,IAAI,OAAO,UAAU,SAAS,KAAK,EAAE,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC,EAAE;AAAA,EACtG;AACA,MAAI,CAAC,aAAa;AAChB,WAAO,EAAE,IAAI,OAAO,UAAU,SAAS,KAAK,EAAE,OAAO,4BAA4B,GAAG,EAAE,QAAQ,IAAI,CAAC,EAAE;AAAA,EACvG;AACA,SAAO,EAAE,IAAI,MAAM,KAAK,EAAE,QAAQ,aAAa,SAAS,EAAE;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,KAAK;AACZ,gBAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,gBAAM,UAA2B;AAAA,YAC/B,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,GAAG,IAAI,YAAY,OAAO,GAAG,CAAC;AAAA,YAC9D,SAAS;AAAA,UACX;AACA,iBAAO,UAAU,IAAI,OAAO;AAAA,QAC9B;AAAA,MACF;AAAA,MAEA;AACE,eAAO,SAAS,IAAI,QAAQ,qBAAqB,MAAM,EAAE;AAAA,IAC7D;AAAA,EACF;AACF;","names":[]}
@@ -33,7 +33,7 @@ import {
33
33
  import {
34
34
  snapHarnessToModel,
35
35
  snapModelToHarness
36
- } from "./chunk-CQZSAR77.js";
36
+ } from "./chunk-73F3CKVK.js";
37
37
 
38
38
  // src/web-react/index.tsx
39
39
  import { useEffect as useEffect10, useMemo as useMemo8, useRef as useRef9, useState as useState14, memo } from "react";
@@ -1601,7 +1601,7 @@ function ChatComposer({
1601
1601
  seed,
1602
1602
  onSeedApplied,
1603
1603
  controls,
1604
- controlsPlacement = "above",
1604
+ controlsPlacement = "inline",
1605
1605
  onAttach,
1606
1606
  onAttachFolder,
1607
1607
  pendingFiles = [],
@@ -1735,8 +1735,8 @@ function ChatComposer({
1735
1735
  );
1736
1736
  const folderChips = pendingFiles.filter((f) => f.kind === "folder");
1737
1737
  const fileChips = pendingFiles.filter((f) => f.kind !== "folder");
1738
- const showFooter = controls != null && controlsPlacement === "footer";
1739
1738
  const showAbove = controls != null && controlsPlacement === "above";
1739
+ const showInline = controls != null && !showAbove;
1740
1740
  return /* @__PURE__ */ jsxs7(
1741
1741
  "div",
1742
1742
  {
@@ -1779,89 +1779,98 @@ function ChatComposer({
1779
1779
  },
1780
1780
  f.id
1781
1781
  )) }),
1782
- /* @__PURE__ */ jsxs7("div", { className: "flex items-end gap-2 rounded-2xl border border-border bg-card px-2.5 py-2 transition focus-within:border-primary/40 focus-within:ring-2 focus-within:ring-primary/15", children: [
1783
- onAttach && /* @__PURE__ */ jsxs7(Fragment3, { children: [
1784
- /* @__PURE__ */ jsx9(
1785
- "button",
1786
- {
1787
- type: "button",
1788
- onClick: () => fileInputRef.current?.click(),
1789
- disabled,
1790
- "aria-label": "Attach files",
1791
- title: "Attach files",
1792
- className: "mb-0.5 shrink-0 rounded-lg p-2 text-muted-foreground transition hover:bg-accent/40 hover:text-foreground disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",
1793
- children: /* @__PURE__ */ jsx9(PaperclipGlyph, { className: "h-4 w-4" })
1794
- }
1795
- ),
1796
- /* @__PURE__ */ jsx9("input", { ref: fileInputRef, type: "file", multiple: true, className: "hidden", accept, onChange: handleFileChange })
1797
- ] }),
1798
- onAttachFolder && /* @__PURE__ */ jsxs7(Fragment3, { children: [
1799
- /* @__PURE__ */ jsx9(
1800
- "button",
1801
- {
1802
- type: "button",
1803
- onClick: () => folderInputRef.current?.click(),
1804
- disabled,
1805
- "aria-label": "Attach folder",
1806
- title: "Attach folder",
1807
- className: "mb-0.5 shrink-0 rounded-lg p-2 text-muted-foreground transition hover:bg-accent/40 hover:text-foreground disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",
1808
- children: /* @__PURE__ */ jsx9(FolderGlyph, { className: "h-4 w-4" })
1809
- }
1810
- ),
1811
- /* @__PURE__ */ jsx9(
1812
- "input",
1813
- {
1814
- ref: folderInputRef,
1815
- type: "file",
1816
- multiple: true,
1817
- className: "hidden",
1818
- onChange: handleFolderChange,
1819
- ...{ webkitdirectory: "" }
1820
- }
1821
- )
1822
- ] }),
1823
- /* @__PURE__ */ jsx9(
1824
- "textarea",
1825
- {
1826
- ref: textareaRef,
1827
- value: text,
1828
- onChange: (e) => setText(e.target.value),
1829
- onKeyDown: handleKeyDown,
1830
- placeholder,
1831
- disabled,
1832
- rows: 1,
1833
- "aria-label": "Message input",
1834
- className: "max-h-[168px] min-h-[40px] flex-1 resize-none bg-transparent px-1.5 py-2 text-[15px] leading-6 text-foreground outline-none placeholder:text-muted-foreground disabled:opacity-50"
1835
- }
1836
- ),
1837
- showFooter && /* @__PURE__ */ jsx9("div", { className: "mb-0.5 flex shrink-0 items-center gap-1.5", children: controls }),
1838
- isStreaming ? /* @__PURE__ */ jsxs7(
1839
- "button",
1840
- {
1841
- type: "button",
1842
- onClick: onCancel,
1843
- "aria-label": "Stop response",
1844
- className: "mb-0.5 inline-flex shrink-0 items-center gap-1.5 rounded-full bg-destructive/15 px-3.5 py-2 text-sm font-medium text-destructive transition hover:bg-destructive/25 focus:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",
1845
- children: [
1846
- /* @__PURE__ */ jsx9(StopGlyph, { className: "h-3.5 w-3.5" }),
1847
- /* @__PURE__ */ jsx9("span", { children: "Stop" })
1848
- ]
1849
- }
1850
- ) : /* @__PURE__ */ jsxs7(
1851
- "button",
1852
- {
1853
- type: "button",
1854
- onClick: send,
1855
- disabled: !canSend,
1856
- "aria-label": sendLabel,
1857
- className: "mb-0.5 inline-flex shrink-0 items-center gap-1.5 rounded-full bg-primary px-3.5 py-2 text-sm font-medium text-primary-foreground shadow-sm transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card",
1858
- children: [
1859
- /* @__PURE__ */ jsx9(SendGlyph, { className: "h-3.5 w-3.5" }),
1860
- /* @__PURE__ */ jsx9("span", { children: sendLabel })
1861
- ]
1862
- }
1863
- )
1864
- ] }),
1782
+ /* @__PURE__ */ jsxs7(
1783
+ "div",
1784
+ {
1785
+ "data-testid": "composer-card",
1786
+ className: "flex flex-col gap-1.5 rounded-2xl border border-border bg-card px-3 py-2.5 transition focus-within:border-primary/40 focus-within:ring-2 focus-within:ring-primary/15",
1787
+ children: [
1788
+ /* @__PURE__ */ jsx9(
1789
+ "textarea",
1790
+ {
1791
+ ref: textareaRef,
1792
+ value: text,
1793
+ onChange: (e) => setText(e.target.value),
1794
+ onKeyDown: handleKeyDown,
1795
+ placeholder,
1796
+ disabled,
1797
+ rows: 2,
1798
+ "aria-label": "Message input",
1799
+ className: "max-h-[168px] min-h-[56px] w-full resize-none bg-transparent px-1.5 py-1 text-[15px] leading-6 text-foreground outline-none placeholder:text-muted-foreground disabled:opacity-50"
1800
+ }
1801
+ ),
1802
+ /* @__PURE__ */ jsxs7("div", { className: "flex items-end gap-2", children: [
1803
+ onAttach && /* @__PURE__ */ jsxs7(Fragment3, { children: [
1804
+ /* @__PURE__ */ jsx9(
1805
+ "button",
1806
+ {
1807
+ type: "button",
1808
+ onClick: () => fileInputRef.current?.click(),
1809
+ disabled,
1810
+ "aria-label": "Attach files",
1811
+ title: "Attach files",
1812
+ className: "shrink-0 rounded-lg p-2 text-muted-foreground transition hover:bg-accent/40 hover:text-foreground disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",
1813
+ children: /* @__PURE__ */ jsx9(PaperclipGlyph, { className: "h-4 w-4" })
1814
+ }
1815
+ ),
1816
+ /* @__PURE__ */ jsx9("input", { ref: fileInputRef, type: "file", multiple: true, className: "hidden", accept, onChange: handleFileChange })
1817
+ ] }),
1818
+ onAttachFolder && /* @__PURE__ */ jsxs7(Fragment3, { children: [
1819
+ /* @__PURE__ */ jsx9(
1820
+ "button",
1821
+ {
1822
+ type: "button",
1823
+ onClick: () => folderInputRef.current?.click(),
1824
+ disabled,
1825
+ "aria-label": "Attach folder",
1826
+ title: "Attach folder",
1827
+ className: "shrink-0 rounded-lg p-2 text-muted-foreground transition hover:bg-accent/40 hover:text-foreground disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",
1828
+ children: /* @__PURE__ */ jsx9(FolderGlyph, { className: "h-4 w-4" })
1829
+ }
1830
+ ),
1831
+ /* @__PURE__ */ jsx9(
1832
+ "input",
1833
+ {
1834
+ ref: folderInputRef,
1835
+ type: "file",
1836
+ multiple: true,
1837
+ className: "hidden",
1838
+ onChange: handleFolderChange,
1839
+ ...{ webkitdirectory: "" }
1840
+ }
1841
+ )
1842
+ ] }),
1843
+ /* @__PURE__ */ jsx9("div", { className: "flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden", children: showInline && controls }),
1844
+ isStreaming ? /* @__PURE__ */ jsxs7(
1845
+ "button",
1846
+ {
1847
+ type: "button",
1848
+ onClick: onCancel,
1849
+ "aria-label": "Stop response",
1850
+ className: "inline-flex shrink-0 items-center gap-1.5 rounded-full bg-destructive/15 px-3.5 py-2 text-sm font-medium text-destructive transition hover:bg-destructive/25 focus:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",
1851
+ children: [
1852
+ /* @__PURE__ */ jsx9(StopGlyph, { className: "h-3.5 w-3.5" }),
1853
+ /* @__PURE__ */ jsx9("span", { children: "Stop" })
1854
+ ]
1855
+ }
1856
+ ) : /* @__PURE__ */ jsxs7(
1857
+ "button",
1858
+ {
1859
+ type: "button",
1860
+ onClick: send,
1861
+ disabled: !canSend,
1862
+ "aria-label": sendLabel,
1863
+ className: "inline-flex shrink-0 items-center gap-1.5 rounded-full bg-primary px-3.5 py-2 text-sm font-medium text-primary-foreground shadow-sm transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card",
1864
+ children: [
1865
+ /* @__PURE__ */ jsx9(SendGlyph, { className: "h-3.5 w-3.5" }),
1866
+ /* @__PURE__ */ jsx9("span", { children: sendLabel })
1867
+ ]
1868
+ }
1869
+ )
1870
+ ] })
1871
+ ]
1872
+ }
1873
+ ),
1865
1874
  focusShortcut && /* @__PURE__ */ jsx9("div", { className: "mt-1.5 flex justify-end px-1", children: /* @__PURE__ */ jsxs7("span", { className: "text-xs text-muted-foreground", children: [
1866
1875
  /* @__PURE__ */ jsx9("kbd", { className: "rounded border border-border bg-background px-1 py-0.5 text-[10px]", children: "Cmd" }),
1867
1876
  /* @__PURE__ */ jsx9("kbd", { className: "ml-0.5 rounded border border-border bg-background px-1 py-0.5 text-[10px]", children: "L" }),
@@ -4300,4 +4309,4 @@ export {
4300
4309
  useThinkingSeconds,
4301
4310
  ChatMessages
4302
4311
  };
4303
- //# sourceMappingURL=chunk-WXWU2FEB.js.map
4312
+ //# sourceMappingURL=chunk-YRFB2KEA.js.map