@tangle-network/agent-app 0.53.8 → 0.53.10

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.
@@ -137,4 +137,4 @@ export {
137
137
  createTangleRouterModelConfig,
138
138
  resolveTangleModelConfig
139
139
  };
140
- //# sourceMappingURL=chunk-JML7WKWU.js.map
140
+ //# sourceMappingURL=chunk-CP36C5LZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime/model.ts"],"sourcesContent":["/**\n * Resolve the model config a Tangle agent's sandbox/runtime runs on.\n *\n * Every Tangle agent product resolves the SAME thing from env: the Tangle Router\n * (OpenAI-compatible, metered at the platform markup against a single\n * `TANGLE_API_KEY`) by default, with a direct-Anthropic BYOK escape hatch. The\n * shape feeds the sandbox backend's role-named model fields (see\n * `backendModelFields`). Lifted here so no product\n * hand-rolls the env parsing + the router default.\n */\n\nexport interface TangleModelConfig {\n /** The Tangle Router is OpenAI-compatible → driven via `openai-compat`.\n * `anthropic` is the BYOK escape hatch. */\n provider: 'openai-compat' | 'anthropic'\n model: string\n apiKey: string\n baseUrl: string\n}\n\n/** Define the environment context for executing Tangle operations */\nexport type TangleExecutionEnvironment = 'development' | 'staging' | 'production' | 'test'\n/** Resolve the source of the Tangle execution key as either local environment or user input */\nexport type TangleExecutionKeySource = 'local-env' | 'user'\n/** Define error codes for Tangle execution key issues related to API key and account connection */\nexport type TangleExecutionKeyErrorCode =\n | 'local_tangle_api_key_required'\n | 'tangle_account_not_connected'\n\n/** Resolve options for model configuration including environment variables and default router base URL */\nexport interface ResolveModelOptions {\n /** Env to read (defaults to process.env). */\n env?: Record<string, string | undefined>\n /** Router base URL default when `TANGLE_ROUTER_BASE_URL` is unset. */\n defaultRouterBaseUrl?: string\n}\n\n/** Resolve options for retrieving user API keys within a specific Tangle execution environment */\nexport interface ResolveUserTangleExecutionKeyOptions {\n /** Deployment context. Only local development may fall back to env keys. */\n environment?: TangleExecutionEnvironment\n /** Env to read for the local-development fallback. */\n env?: Record<string, string | undefined>\n /** App-owned lookup for the caller's linked platform API key. */\n getUserApiKey: () => string | null | undefined | Promise<string | null | undefined>\n}\n\n/** Resolve options for retrieving a user's Tangle execution key with environment and API key access parameters */\nexport interface ResolveUserTangleExecutionKeyForUserOptions<UserId = string> {\n userId: UserId\n environment?: TangleExecutionEnvironment\n env?: Record<string, string | undefined>\n getUserApiKey: (userId: UserId) => string | null | undefined | Promise<string | null | undefined>\n}\n\n/** Define a resolved key combining an API key with its Tangle execution source */\nexport interface ResolvedTangleExecutionKey {\n apiKey: string\n source: TangleExecutionKeySource\n}\n\n/** Resolve options for retrieving a Tangle developer or user API key based on environment and context */\nexport interface ResolveTangleDevOrUserKeyOptions {\n /** Deployment context. Only local development may use the env key. */\n environment?: TangleExecutionEnvironment\n /** Env to read for the local-development fallback. */\n env?: Record<string, string | undefined>\n /** App-owned lookup for the caller's linked platform API key. */\n getUserApiKey: () => string | null | undefined | Promise<string | null | undefined>\n}\n\n/** Represent HTTP error response containing status, error message, and specific error code */\nexport interface TangleExecutionKeyHttpError {\n status: number\n body: {\n error: string\n code: TangleExecutionKeyErrorCode\n }\n}\n\n/** Define configuration options for creating a Tangle router model including API key and model details */\nexport interface CreateTangleRouterModelConfigOptions {\n apiKey: string\n model: string\n baseUrl?: string\n}\n\n/** Define options for configuring billing enforcement environment variables and overrides */\nexport interface TangleBillingEnforcementOptions {\n /** Env to read (defaults to process.env). */\n env?: Record<string, string | undefined>\n /**\n * Optional app-specific override flag, e.g. `GTM_BILLING_ENFORCEMENT`.\n * Defaults to the shared `TANGLE_BILLING_ENFORCEMENT`.\n */\n enforcementEnvVar?: string\n}\n\n/** Provide the default base URL for the Tangle router API endpoint */\nexport const DEFAULT_TANGLE_ROUTER_BASE_URL = 'https://router.tangle.tools/v1'\n/** Define the default environment variable name for Tangle billing enforcement */\nexport const DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR = 'TANGLE_BILLING_ENFORCEMENT'\n\nfunction requireEnv(env: Record<string, string | undefined>, name: string): string {\n const value = env[name]?.trim()\n if (!value) throw new Error(`${name} is required`)\n return value\n}\n\n/** Resolve a string by trimming whitespace or returning null if empty or undefined */\nexport function trimOrNull(value: string | null | undefined): string | null {\n const trimmed = value?.trim()\n return trimmed ? trimmed : null\n}\n\nfunction isTangleExecutionKeyErrorCode(value: unknown): value is TangleExecutionKeyErrorCode {\n return value === 'local_tangle_api_key_required' || value === 'tangle_account_not_connected'\n}\n\n/** Represent execution key errors with specific codes and HTTP status information */\nexport class TangleExecutionKeyError extends Error {\n readonly code: TangleExecutionKeyErrorCode\n readonly status: number\n\n constructor(code: TangleExecutionKeyErrorCode, message: string, status: number) {\n super(message)\n this.name = 'TangleExecutionKeyError'\n this.code = code\n this.status = status\n }\n}\n\n/** Identify whether an error is a TangleExecutionKeyError based on its properties and type */\nexport function isTangleExecutionKeyError(error: unknown): error is TangleExecutionKeyError {\n return error instanceof TangleExecutionKeyError\n || (\n typeof error === 'object'\n && error !== null\n && (error as { name?: unknown }).name === 'TangleExecutionKeyError'\n && typeof (error as { message?: unknown }).message === 'string'\n && isTangleExecutionKeyErrorCode((error as { code?: unknown }).code)\n && typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Resolve the current Tangle execution environment based on provided or process environment variables */\nexport function resolveTangleExecutionEnvironment(\n env: Record<string, string | undefined> = process.env as Record<string, string | undefined>,\n): TangleExecutionEnvironment {\n const raw = (env.APP_ENV ?? env.NODE_ENV ?? '').trim().toLowerCase()\n if (raw === 'development' || raw === 'dev' || raw === 'local') return 'development'\n if (raw === 'staging') return 'staging'\n if (raw === 'test') return 'test'\n return 'production'\n}\n\n/**\n * Shared policy for agent products that bill through the Tangle Platform.\n *\n * Local development defaults billing enforcement off so apps can use a local\n * `TANGLE_API_KEY` without requiring a browser-linked platform account. Any\n * non-development environment defaults enforcement on. Apps may pass their own\n * override flag (`FOO_BILLING_ENFORCEMENT`) while new apps can use the shared\n * `TANGLE_BILLING_ENFORCEMENT`.\n */\nexport function isTangleBillingEnforcementDisabled(\n opts: TangleBillingEnforcementOptions = {},\n): boolean {\n const env = opts.env ?? (process.env as Record<string, string | undefined>)\n const enforcementEnvVar = opts.enforcementEnvVar ?? DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR\n const override = env[enforcementEnvVar]?.trim().toLowerCase()\n\n if (override === 'disabled') return true\n if (override === 'enabled') return false\n\n return resolveTangleExecutionEnvironment(env) === 'development'\n}\n\n/** Resolve and format TangleExecutionKey HTTP errors into a standardized error object or return null */\nexport function tangleExecutionKeyHttpError(error: unknown): TangleExecutionKeyHttpError | null {\n if (!isTangleExecutionKeyError(error)) return null\n return {\n status: error.status,\n body: {\n error: error.message,\n code: error.code,\n },\n }\n}\n\n/**\n * Shared dev-aware Tangle key resolution. Local development may use a server\n * `TANGLE_API_KEY`; otherwise the caller's linked platform key is used. Returns\n * null when neither resolves, so each caller can throw its own domain error\n * (e.g. model-execution 503/401 vs hub `tangle_link_required` 412).\n */\nexport async function resolveTangleDevOrUserKey(\n opts: ResolveTangleDevOrUserKeyOptions,\n): Promise<ResolvedTangleExecutionKey | null> {\n const env = opts.env ?? (process.env as Record<string, string | undefined>)\n const environment = opts.environment ?? resolveTangleExecutionEnvironment(env)\n\n if (environment === 'development') {\n const apiKey = trimOrNull(env.TANGLE_API_KEY)\n if (apiKey) return { apiKey, source: 'local-env' }\n }\n\n const apiKey = trimOrNull(await opts.getUserApiKey())\n if (apiKey) return { apiKey, source: 'user' }\n\n return null\n}\n\n/**\n * Resolve the user-facing Tangle API key for model execution.\n *\n * Local development may use a server env key so apps remain easy to run.\n * Deployed contexts must use the caller's linked platform key; this keeps\n * model execution, billing, and account ownership aligned across products.\n */\nexport async function resolveUserTangleExecutionKey(\n opts: ResolveUserTangleExecutionKeyOptions,\n): Promise<ResolvedTangleExecutionKey> {\n const env = opts.env ?? (process.env as Record<string, string | undefined>)\n const environment = opts.environment ?? resolveTangleExecutionEnvironment(env)\n\n const resolved = await resolveTangleDevOrUserKey({ environment, env, getUserApiKey: opts.getUserApiKey })\n if (resolved) return resolved\n\n if (environment === 'development') {\n throw new TangleExecutionKeyError(\n 'local_tangle_api_key_required',\n 'TANGLE_API_KEY or a linked Tangle account is required for local Tangle model execution.',\n 503,\n )\n }\n\n throw new TangleExecutionKeyError(\n 'tangle_account_not_connected',\n 'Connect your Tangle account before invoking this agent.',\n 401,\n )\n}\n\n/** Resolve the Tangle execution key for a specified user using provided environment and API key options */\nexport async function resolveUserTangleExecutionKeyForUser<UserId = string>(\n opts: ResolveUserTangleExecutionKeyForUserOptions<UserId>,\n): Promise<ResolvedTangleExecutionKey> {\n return resolveUserTangleExecutionKey({\n environment: opts.environment,\n env: opts.env,\n getUserApiKey: () => opts.getUserApiKey(opts.userId),\n })\n}\n\n/**\n * Build an OpenAI-compatible Tangle Router model config from an already\n * resolved execution key. This intentionally does not read TANGLE_API_KEY.\n */\nexport function createTangleRouterModelConfig(\n opts: CreateTangleRouterModelConfigOptions,\n): TangleModelConfig {\n const apiKey = opts.apiKey.trim()\n if (!apiKey) throw new Error('apiKey is required')\n const model = opts.model.trim()\n if (!model) throw new Error('model is required')\n return {\n provider: 'openai-compat',\n model,\n apiKey,\n baseUrl: (opts.baseUrl?.trim() || DEFAULT_TANGLE_ROUTER_BASE_URL).replace(/\\/+$/, ''),\n }\n}\n\n/**\n * Resolve the model config from env. DEFAULT path (`MODEL_PROVIDER` unset or\n * `openai-compat`/`tangle-router`/`tcloud`): the Tangle Router, authenticated\n * with `TANGLE_API_KEY`, model from `MODEL_NAME`. BYOK path\n * (`MODEL_PROVIDER=anthropic`): direct Anthropic with `ANTHROPIC_API_KEY` +\n * `ANTHROPIC_BASE_URL`. Throws (fail-loud) on a missing required var so a\n * misconfigured deploy fails at boot, not mid-turn.\n */\nexport function resolveTangleModelConfig(opts: ResolveModelOptions = {}): TangleModelConfig {\n const env = opts.env ?? (process.env as Record<string, string | undefined>)\n const provider = env.MODEL_PROVIDER?.trim() || 'openai-compat'\n const model = requireEnv(env, 'MODEL_NAME')\n\n if (provider === 'openai-compat' || provider === 'tangle-router' || provider === 'tcloud') {\n return {\n provider: 'openai-compat',\n model,\n apiKey: requireEnv(env, 'TANGLE_API_KEY'),\n baseUrl: (env.TANGLE_ROUTER_BASE_URL?.trim() || opts.defaultRouterBaseUrl || DEFAULT_TANGLE_ROUTER_BASE_URL).replace(/\\/+$/, ''),\n }\n }\n\n if (provider === 'anthropic') {\n return {\n provider,\n model,\n apiKey: requireEnv(env, 'ANTHROPIC_API_KEY'),\n baseUrl: requireEnv(env, 'ANTHROPIC_BASE_URL'),\n }\n }\n\n throw new Error(`Unsupported MODEL_PROVIDER: ${provider} (use openai-compat for the Tangle Router, or anthropic for BYOK)`)\n}\n"],"mappings":";AAmGO,IAAM,iCAAiC;AAEvC,IAAM,6CAA6C;AAE1D,SAAS,WAAW,KAAyC,MAAsB;AACjF,QAAM,QAAQ,IAAI,IAAI,GAAG,KAAK;AAC9B,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,GAAG,IAAI,cAAc;AACjD,SAAO;AACT;AAGO,SAAS,WAAW,OAAiD;AAC1E,QAAM,UAAU,OAAO,KAAK;AAC5B,SAAO,UAAU,UAAU;AAC7B;AAEA,SAAS,8BAA8B,OAAsD;AAC3F,SAAO,UAAU,mCAAmC,UAAU;AAChE;AAGO,IAAM,0BAAN,cAAsC,MAAM;AAAA,EACxC;AAAA,EACA;AAAA,EAET,YAAY,MAAmC,SAAiB,QAAgB;AAC9E,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAGO,SAAS,0BAA0B,OAAkD;AAC1F,SAAO,iBAAiB,2BAEpB,OAAO,UAAU,YACd,UAAU,QACT,MAA6B,SAAS,6BACvC,OAAQ,MAAgC,YAAY,YACpD,8BAA+B,MAA6B,IAAI,KAChE,OAAQ,MAA+B,WAAW;AAE3D;AAGO,SAAS,kCACd,MA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,WAAW,KAAK,oBAAoB;AAAA,IAC/C;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,+BAA+B,QAAQ,mEAAmE;AAC5H;","names":["apiKey"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isTangleBillingEnforcementDisabled
3
- } from "./chunk-JML7WKWU.js";
3
+ } from "./chunk-CP36C5LZ.js";
4
4
  import {
5
5
  clearCookieHeader,
6
6
  readCookieValue,
@@ -494,4 +494,4 @@ export {
494
494
  createAdminGuard,
495
495
  assertBillableBalance
496
496
  };
497
- //# sourceMappingURL=chunk-SMRF4UMN.js.map
497
+ //# sourceMappingURL=chunk-L57CYCXN.js.map
@@ -23,7 +23,8 @@ function buildUtilityRe(suffix) {
23
23
  function definedVars(cssFiles) {
24
24
  const defs = /* @__PURE__ */ new Set();
25
25
  const visited = /* @__PURE__ */ new Set();
26
- const visit = (file) => {
26
+ const visit = (inputFile) => {
27
+ const file = resolve(inputFile);
27
28
  if (visited.has(file)) return;
28
29
  visited.add(file);
29
30
  let css;
@@ -35,7 +36,14 @@ function definedVars(cssFiles) {
35
36
  for (const m of css.matchAll(/^\s*(--[a-z0-9-]+)\s*:/gim)) if (m[1]) defs.add(m[1]);
36
37
  for (const m of css.matchAll(/@import\s+['"]([^'"]+)['"]/g)) {
37
38
  if (!m[1]) continue;
38
- const imported = m[1].startsWith(".") ? resolve(dirname(file), m[1]) : createRequire(file).resolve(m[1]);
39
+ let imported;
40
+ try {
41
+ imported = m[1].startsWith(".") ? resolve(dirname(file), m[1]) : createRequire(file).resolve(m[1]);
42
+ } catch (error) {
43
+ const code = error.code;
44
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED") continue;
45
+ throw error;
46
+ }
39
47
  visit(imported);
40
48
  }
41
49
  };
@@ -96,4 +104,4 @@ function displayPath(file) {
96
104
  export {
97
105
  checkThemeContract
98
106
  };
99
- //# sourceMappingURL=chunk-ZVNPAJ7Z.js.map
107
+ //# sourceMappingURL=chunk-LUKLQDIK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/theme-contract/index.ts"],"sourcesContent":["/**\n * Exportable theme-token contract checker — the incident guard for the\n * invisible-popover class of bugs.\n *\n * The failure mode (tax-agent's transparent model dropdown; the whole\n * `bg-surface-container-*` family): a consumer app ships a component that\n * references a theme token — either as `var(--popover)` or as a Tailwind class\n * like `bg-surface-container-high` that the agent-app preset maps to\n * `hsl(var(--popover))` — but the app's OWN build never emits that custom\n * property (it forgot `import '@tangle-network/agent-app/styles'`, or dropped a\n * token in its local tokens.css). CSS resolves the missing var to nothing, the\n * surface paints transparent, and NOTHING errors. It ships invisible.\n *\n * `tests/theme/tokens-contract.test.ts` guards agent-app's OWN components. This\n * module lifts that walking logic into a function every CONSUMER app can run\n * against ITS OWN source in CI, comparing references to the tokens.css agent-app\n * ships plus any extra CSS the app defines.\n *\n * ── What each check covers (scope is deliberately honest) ────────────────────\n *\n * 1. var(--…) check — COMPLETE. Every `var(--name)` literal in the scanned\n * source (inline styles, `bg-[var(--name)]` arbitrary Tailwind values, CSS\n * template strings) is matched and compared against the defined token set.\n * This is exact: a `var(--x)` reference is unambiguous. It is a raw-text\n * scan (no AST), so a `var(--x)` written inside a comment or string literal\n * counts too — deliberate: it keeps the single-source logic identical to the\n * agent-app self-test, and a dangling `var(--x)` in a comment is a smell\n * worth surfacing. Suppress a deliberate one with `allowlist`.\n *\n * 2. Tailwind-utility check — INTENTIONALLY PARTIAL. Bare classes like\n * `bg-card` carry no `var(--)` and so are invisible to check 1; Tailwind\n * resolves them to `hsl(var(--card))` at build via the preset. Fully\n * resolving arbitrary Tailwind config is out of scope (it would mean\n * re-implementing Tailwind). Instead we check the SPECIFIC known-dangerous\n * families that have actually shipped invisible: the MD3 surface ladder\n * (`surface-container` / `-high` / `-highest`) and the `card` / `popover`\n * elevation pairs — exactly the utilities the agent-app tailwind-preset\n * registers onto elevation tokens (see src/theme/tailwind-preset.ts, the\n * source of truth for this mapping). The canvas/sequence aliases\n * (`--bg-input`, `--text-primary`, …) are consumed as `bg-[var(--…)]`\n * arbitrary values and so are already covered fully by check 1 — they need\n * no entry here.\n *\n * Node-only (reads the filesystem) → this lives in the `./theme-contract`\n * subpath, NOT `./theme`, which must stay browser-clean (it's in the\n * browser-safe manifest test).\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, relative, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { walkSources } from '../legibility/walk-sources'\n\n/** Define options for scanning source directories and CSS token files in a theme contract */\nexport interface ThemeContractOptions {\n /** Consumer source directories to scan for token references (recursively). */\n srcDirs: string[]\n /**\n * Path to the base tokens.css whose `--name:` definitions are the ground\n * truth. Defaults to the tokens.css agent-app ships (`./styles`) — the set a\n * consumer gets from `import '@tangle-network/agent-app/styles'`.\n */\n tokensCss?: string\n /**\n * Additional CSS files whose `--name:` definitions also count as defined —\n * the app's own overrides/extensions layered on top of the base tokens.\n */\n extraTokensCss?: string[]\n /**\n * Token names (e.g. `--my-app-accent`) to treat as always-defined, suppressing\n * them from the missing list. For app-specific vars defined outside any CSS\n * the checker can see (injected at runtime, from a third-party stylesheet, …).\n */\n allowlist?: string[]\n}\n\n/** Describe a missing theme contract variable and where it was referenced */\nexport interface ThemeContractMiss {\n /** The undefined custom property, e.g. `--popover`. */\n varName: string\n /**\n * Where it was referenced: `path/to/file.tsx`, or\n * `path/to/file.tsx (via bg-surface-container-high)` when the reference is a\n * Tailwind utility that resolves to the token rather than a literal var().\n */\n referencedIn: string\n}\n\n/** Describe the result of validating a theme contract including success status and missing items */\nexport interface ThemeContractResult {\n ok: boolean\n missing: ThemeContractMiss[]\n}\n\n/**\n * Known-dangerous Tailwind utility families and the elevation token each\n * resolves to, mirroring src/theme/tailwind-preset.ts. Ordered longest-suffix\n * first so `surface-container-highest` is matched before `surface-container`.\n * The negative look-around in {@link buildUtilityRe} makes ordering belt-and-\n * suspenders rather than load-bearing.\n */\nconst DANGEROUS_UTILITIES: ReadonlyArray<{ suffix: string; varName: string }> = [\n { suffix: 'surface-container-highest', varName: '--md3-surface-container-highest' },\n { suffix: 'surface-container-high', varName: '--md3-surface-container-high' },\n { suffix: 'surface-container', varName: '--md3-surface-container' },\n { suffix: 'card-foreground', varName: '--card-foreground' },\n { suffix: 'popover-foreground', varName: '--popover-foreground' },\n { suffix: 'card', varName: '--card' },\n { suffix: 'popover', varName: '--popover' },\n]\n\n/** Tailwind color-utility prefixes that can carry a background/text/border color. */\nconst UTILITY_PREFIXES = 'bg|text|border|ring|fill|stroke'\n\n/**\n * Match a whole utility class for `suffix`, tolerant of variants (`hover:`,\n * `dark:`) and opacity (`/95`) but not of longer siblings: the trailing\n * `(?![\\w-])` stops `bg-surface-container` from matching inside\n * `bg-surface-container-high`, and `bg-card` from matching inside\n * `bg-card-foreground`.\n */\nfunction buildUtilityRe(suffix: string): RegExp {\n return new RegExp(`(?<![\\\\w-])(?:${UTILITY_PREFIXES})-${suffix}(?![\\\\w-])`, 'g')\n}\n\n/**\n * Every `--name:` DEFINITION across the given CSS files. A definition is\n * `--name:` at the start of a (trimmed) line; RHS references like\n * `hsl(var(--card))` are mid-line and are never counted as definitions.\n */\nfunction definedVars(cssFiles: string[]): Set<string> {\n const defs = new Set<string>()\n const visited = new Set<string>()\n const visit = (inputFile: string): void => {\n // CLI paths are relative to cwd; createRequire needs an absolute filename.\n const file = resolve(inputFile)\n if (visited.has(file)) return\n visited.add(file)\n let css: string\n try {\n css = readFileSync(file, 'utf8')\n } catch {\n return\n }\n for (const m of css.matchAll(/^\\s*(--[a-z0-9-]+)\\s*:/gim)) if (m[1]) defs.add(m[1])\n // Source tokens.css imports the published Brand sheet and its checked\n // projection. The packed public sheet has already inlined both. Follow\n // local imports here so the source and installed consumer see the same\n // definitions without making Brand a runtime dependency of the package.\n for (const m of css.matchAll(/@import\\s+['\"]([^'\"]+)['\"]/g)) {\n if (!m[1]) continue\n let imported: string\n try {\n imported = m[1].startsWith('.')\n ? resolve(dirname(file), m[1])\n : createRequire(file).resolve(m[1])\n } catch (error) {\n // CSS build tools can resolve packages/exports unavailable to Node\n // (e.g. tailwindcss). Keep scanning local definitions and imports;\n // references to any uncollected tokens still fail the contract.\n const code = (error as NodeJS.ErrnoException).code\n if (code === 'MODULE_NOT_FOUND' || code === 'ERR_PACKAGE_PATH_NOT_EXPORTED') continue\n throw error\n }\n visit(imported)\n }\n }\n for (const file of cssFiles) visit(file)\n return defs\n}\n\n/**\n * Default tokens.css: the one agent-app ships as `./styles`. Resolved relative\n * to this module's URL, but tolerant of where the bundler lands the running\n * code — tsup code-splits shared logic into a chunk at the dist ROOT, so the\n * tokens.css sits one directory DIFFERENTLY depending on layout:\n * - source (src/theme-contract/index.ts) → ../theme/tokens.css (src/theme)\n * - split chunk (dist/contract-*.js) → ./theme/tokens.css (dist/theme)\n * - unsplit entry (dist/theme-contract/index.js) → ../theme/tokens.css\n * Probe both and return the one that exists; fall back to the first for a\n * sensible error path if neither is present.\n */\nfunction defaultTokensCss(): string {\n const candidates = ['../theme/tokens.css', './theme/tokens.css'].map((rel) =>\n fileURLToPath(new URL(rel, import.meta.url)),\n )\n return candidates.find((p) => existsSync(p)) ?? candidates[0]!\n}\n\n/**\n * Check that every theme token a consumer's source references is actually\n * defined in the CSS that consumer ships. Returns the full missing set; the\n * caller decides how to fail (the bin exits non-zero on any miss).\n */\nexport function checkThemeContract(opts: ThemeContractOptions): ThemeContractResult {\n const tokensCss = opts.tokensCss ?? defaultTokensCss()\n const defined = definedVars([tokensCss, ...(opts.extraTokensCss ?? [])])\n const allow = new Set(opts.allowlist ?? [])\n const isDefined = (name: string) => defined.has(name) || allow.has(name)\n\n const files = opts.srcDirs.flatMap((dir) => walkSources(dir, ['.d.ts']))\n const utilityMatchers = DANGEROUS_UTILITIES.map((u) => ({ ...u, re: buildUtilityRe(u.suffix) }))\n\n // Dedupe by varName (literal check) and by varName+utility (utility check),\n // keeping the FIRST referencing file — enough to locate the offender without\n // drowning the report when one token is referenced across many files.\n const seenVar = new Map<string, string>()\n const seenUtility = new Map<string, string>()\n\n for (const file of files) {\n let text: string\n try {\n text = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n const where = displayPath(file)\n\n // Check 1 — literal var(--…) references.\n for (const m of text.matchAll(/var\\(\\s*(--[a-z0-9-]+)/gi)) {\n const name = m[1]\n if (!name || isDefined(name) || seenVar.has(name)) continue\n seenVar.set(name, where)\n }\n\n // Check 2 — known-dangerous Tailwind utility classes.\n for (const u of utilityMatchers) {\n if (isDefined(u.varName)) continue\n const key = `${u.varName}::${u.suffix}`\n if (seenUtility.has(key)) continue\n u.re.lastIndex = 0\n if (u.re.test(text)) seenUtility.set(key, `${where} (via ${firstUtilityHit(text, u.suffix)})`)\n }\n }\n\n const missing: ThemeContractMiss[] = [\n ...[...seenVar].map(([varName, referencedIn]) => ({ varName, referencedIn })),\n ...[...seenUtility].map(([key, referencedIn]) => ({ varName: key.split('::')[0]!, referencedIn })),\n ]\n return { ok: missing.length === 0, missing }\n}\n\n/** The literal utility class (with prefix) first seen in `text` for `suffix`, for the report. */\nfunction firstUtilityHit(text: string, suffix: string): string {\n const m = buildUtilityRe(suffix).exec(text)\n return m?.[0] ?? `<utility>-${suffix}`\n}\n\n/** Path relative to cwd when it stays inside it, else the path as given — for readable reports. */\nfunction displayPath(file: string): string {\n const rel = relative(process.cwd(), file)\n return rel && !rel.startsWith('..') ? rel : file\n}\n"],"mappings":";;;;;AAgDA,SAAS,YAAY,oBAAoB;AACzC,SAAS,qBAAqB;AAC9B,SAAS,SAAS,UAAU,eAAe;AAC3C,SAAS,qBAAqB;AAmD9B,IAAM,sBAA0E;AAAA,EAC9E,EAAE,QAAQ,6BAA6B,SAAS,kCAAkC;AAAA,EAClF,EAAE,QAAQ,0BAA0B,SAAS,+BAA+B;AAAA,EAC5E,EAAE,QAAQ,qBAAqB,SAAS,0BAA0B;AAAA,EAClE,EAAE,QAAQ,mBAAmB,SAAS,oBAAoB;AAAA,EAC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AgB,MAAM,EAAE,MAAM,CAAC,GAAG;AAAA,IAC/F;AAAA,EACF;AAEA,QAAM,UAA+B;AAAA,IACnC,GAAG,CAAC,GAAG,OAAO,EAAE,IAAI,CAAC,CAAC,SAAS,YAAY,OAAO,EAAE,SAAS,aAAa,EAAE;AAAA,IAC5E,GAAG,CAAC,GAAG,WAAW,EAAE,IAAI,CAAC,CAAC,KAAK,YAAY,OAAO,EAAE,SAAS,IAAI,MAAM,IAAI,EAAE,CAAC,GAAI,aAAa,EAAE;AAAA,EACnG;AACA,SAAO,EAAE,IAAI,QAAQ,WAAW,GAAG,QAAQ;AAC7C;AAGA,SAAS,gBAAgB,MAAc,QAAwB;AAC7D,QAAM,IAAI,eAAe,MAAM,EAAE,KAAK,IAAI;AAC1C,SAAO,IAAI,CAAC,KAAK,aAAa,MAAM;AACtC;AAGA,SAAS,YAAY,MAAsB;AACzC,QAAM,MAAM,SAAS,QAAQ,IAAI,GAAG,IAAI;AACxC,SAAO,OAAO,CAAC,IAAI,WAAW,IAAI,IAAI,MAAM;AAC9C;","names":[]}
@@ -13,10 +13,10 @@ import {
13
13
  resolveTangleSsoAccount,
14
14
  signSessionCookieValue,
15
15
  verifySignedSsoState
16
- } from "../chunk-SMRF4UMN.js";
16
+ } from "../chunk-L57CYCXN.js";
17
17
  import {
18
18
  resolveTangleExecutionEnvironment
19
- } from "../chunk-JML7WKWU.js";
19
+ } from "../chunk-CP36C5LZ.js";
20
20
  import "../chunk-YNSPVKMS.js";
21
21
  import {
22
22
  parseJsonObjectBody
@@ -16,7 +16,7 @@ import {
16
16
  resolveUserTangleExecutionKeyForUser,
17
17
  tangleExecutionKeyHttpError,
18
18
  trimOrNull
19
- } from "../chunk-JML7WKWU.js";
19
+ } from "../chunk-CP36C5LZ.js";
20
20
  import {
21
21
  MAX_RECOMMENDED_MODELS,
22
22
  __resetCatalogCache,
@@ -4,7 +4,8 @@
4
4
  * Every Tangle agent product resolves the SAME thing from env: the Tangle Router
5
5
  * (OpenAI-compatible, metered at the platform markup against a single
6
6
  * `TANGLE_API_KEY`) by default, with a direct-Anthropic BYOK escape hatch. The
7
- * shape feeds the sandbox SDK's `backend.model`. Lifted here so no product
7
+ * shape feeds the sandbox backend's role-named model fields (see
8
+ * `backendModelFields`). Lifted here so no product
8
9
  * hand-rolls the env parsing + the router default.
9
10
  */
10
11
  export interface TangleModelConfig {
@@ -7,10 +7,10 @@ import { type TangleExecutionEnvironment } from '../runtime/model';
7
7
  import { type Outcome } from './outcome';
8
8
  import { type ProfileFingerprint } from '../profile/fingerprint';
9
9
  import { type ComposeProfileBudget } from '../profile/budget';
10
- import { resolveModel, resolveModelSelection, requireTransportableModel, SandboxModelResolutionError, type ProviderResolutionConfig, type ResolvedModel, type ModelSelection, type ModelSelectionFailure, type ModelSelectionError, type ModelSelectionSource } from './model';
10
+ import { resolveModel, resolveModelSelection, backendModelFields, requireTransportableModel, SandboxModelResolutionError, type ProviderResolutionConfig, type ResolvedModel, type ModelSelection, type ModelSelectionFailure, type ModelSelectionError, type ModelSelectionSource } from './model';
11
11
  export type { Outcome } from './outcome';
12
12
  export * from './binary-read';
13
- export { resolveModel, resolveModelSelection, requireTransportableModel, SandboxModelResolutionError, };
13
+ export { resolveModel, resolveModelSelection, backendModelFields, requireTransportableModel, SandboxModelResolutionError, };
14
14
  export type { ProviderResolutionConfig, ResolvedModel, ModelSelection, ModelSelectionFailure, ModelSelectionError, ModelSelectionSource, };
15
15
  /** Define client credentials for accessing the sandbox environment with API key and base URL */
16
16
  export interface SandboxClientCredentials {
@@ -706,9 +706,18 @@ export type SandboxPromptConfig = Pick<SandboxRuntimeConfig, 'provider' | 'defer
706
706
  * Reuse the returned backend for preflight and dispatch so they inspect identical configuration.
707
707
  */
708
708
  export declare function resolveSandboxPromptBackend(shell: SandboxPromptConfig, options: StreamSandboxPromptOptions, operation?: string): Promise<{
709
+ modelId?: string | undefined;
710
+ provider?: string | undefined;
711
+ apiKey?: string;
712
+ baseUrl?: string;
713
+ model?: {
714
+ model: string;
715
+ provider: string;
716
+ apiKey?: string;
717
+ baseUrl?: string;
718
+ } | undefined;
709
719
  type: Harness;
710
720
  profile: AgentProfile;
711
- model?: ResolvedModel | undefined;
712
721
  interactions?: {
713
722
  question?: boolean;
714
723
  permission?: boolean;
@@ -31,6 +31,7 @@ import {
31
31
  assertProvisionPayloadWithinCap,
32
32
  assessWorkspaceSandboxSnapshot,
33
33
  attachReasoningEffort,
34
+ backendModelFields,
34
35
  buildAppToolMcpServers,
35
36
  buildProductEgressPolicy,
36
37
  buildSandboxToolBinDirScript,
@@ -99,7 +100,7 @@ import {
99
100
  workspaceSandboxRecoveryMessage,
100
101
  workspaceSandboxRecoveryRecommendedActions,
101
102
  writeProfileFilesToBox
102
- } from "../chunk-2TZLCQ5U.js";
103
+ } from "../chunk-4KFM7VTH.js";
103
104
  import "../chunk-MCYJON3F.js";
104
105
  import "../chunk-LWSJK546.js";
105
106
  import "../chunk-P2GXQRFR.js";
@@ -109,7 +110,7 @@ import "../chunk-UGWQLQDS.js";
109
110
  import "../chunk-S5SRJJQG.js";
110
111
  import "../chunk-LFMP73W3.js";
111
112
  import "../chunk-T52MKPHE.js";
112
- import "../chunk-JML7WKWU.js";
113
+ import "../chunk-CP36C5LZ.js";
113
114
  export {
114
115
  DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,
115
116
  DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS,
@@ -143,6 +144,7 @@ export {
143
144
  assertProvisionPayloadWithinCap,
144
145
  assessWorkspaceSandboxSnapshot,
145
146
  attachReasoningEffort,
147
+ backendModelFields,
146
148
  buildAppToolMcpServers,
147
149
  buildProductEgressPolicy,
148
150
  buildSandboxToolBinDirScript,
@@ -9,6 +9,29 @@ export interface ProviderResolutionConfig {
9
9
  allowKeylessModel?: boolean;
10
10
  }
11
11
  /** Represent a fully configured model with optional API key and base URL for sandbox platform integration */
12
+ /**
13
+ * Spread a {@link ResolvedModel} onto a sandbox backend config as role-named
14
+ * fields. The model id's home on a standalone backend is `modelId`; routing
15
+ * rides `provider`/`apiKey`/`baseUrl` flat — the SDK folds them onto the wire.
16
+ *
17
+ * The deprecated nested `model` object rides along while agent-app's peer
18
+ * range still admits pre-fold SDK versions (< the 0.60.14 develop train):
19
+ * old SDKs forward only the nested object and drop the unknown flat fields,
20
+ * fold-aware SDKs see two AGREEING spellings and fold them. Delete the
21
+ * nested half when the peer floor moves past the fold.
22
+ */
23
+ export declare function backendModelFields(model: ResolvedModel): {
24
+ modelId: string;
25
+ provider: string;
26
+ apiKey?: string;
27
+ baseUrl?: string;
28
+ model: {
29
+ model: string;
30
+ provider: string;
31
+ apiKey?: string;
32
+ baseUrl?: string;
33
+ };
34
+ };
12
35
  export interface ResolvedModel {
13
36
  model: string;
14
37
  provider: string;
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  checkThemeContract
4
- } from "../chunk-ZVNPAJ7Z.js";
4
+ } from "../chunk-LUKLQDIK.js";
5
5
  import "../chunk-EMLGWEHV.js";
6
6
  import {
7
7
  invokedAsScript
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  checkThemeContract
3
- } from "../chunk-ZVNPAJ7Z.js";
3
+ } from "../chunk-LUKLQDIK.js";
4
4
  import "../chunk-EMLGWEHV.js";
5
5
  export {
6
6
  checkThemeContract
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.53.8",
3
+ "version": "0.53.10",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [