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AA,OAAA,CAAQ,GAAA;AAAA,UACN,CAAA,CAAE,KAAA;AAAA,UACF,CAAA,QAAA,EAAW,EAAE,CAAA,4BAAA,EAA+B,EAAE,CAAA,4BAAA;AAAA,SAChD;AACA,QAAA;AAAA,MACF;AAAA,IACF;AACA,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,CAAE,KAAA,EAAO,CAAC,CAAA;AAAA,EACxB;AACA,EAAA,OAAO,EAAE,SAAS,CAAC,GAAG,QAAQ,MAAA,EAAQ,GAAG,OAAA,EAAQ;AACnD;AAOO,SAAS,0BACd,OAAA,EACQ;AACR,EAAA,MAAM,IAAA,GAAO,mBAAmB,OAAO,CAAA,CACpC,IAAI,CAAC,CAAA,KAAM,OAAO,IAAA,CAAK,SAAA,CAAU,GAAG,IAAA,EAAM,CAAC,EAAE,OAAA,CAAQ,KAAA,EAAO,MAAM,CAAA,GAAI,GAAG,CAAA,CACzE,IAAA,CAAK,IAAI,CAAA;AACZ,EAAA,OAAO,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA,EAeP,IAAI;AAAA;AAAA,CAAA;AAGN","file":"first-party-catalog-gen.mjs","sourcesContent":["/**\n * App catalog — a static, hand-curated `~/.agentproto/app-catalog.json`\n * listing apps a user could `app_install`, independent of whether any are\n * installed yet, plus optional remote catalog `sources` (each an HTTP URL\n * returning `{ entries: AppCatalogEntry[] }`). Read-only from the daemon's\n * side; `app_catalog` (app-tools.ts) merges local entries, remote entries and\n * `AppRegistry.listApps()` to report installed/hasUi status.\n *\n * Sources (see `resolveCatalogSources`): the default public catalog\n * (`DEFAULT_CATALOG_SOURCE_URL`, config `catalog.defaultSource`) comes\n * first, then config `catalog.sources` — which win over (replace) `sources`\n * in the catalog file when set. Extra sources ADD to the default one. Remote\n * catalogs follow the `app-catalog/v1` format; the last good copy of each is\n * cached on disk so `app_catalog` keeps working offline.\n */\n\nimport { createHash } from \"node:crypto\"\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\nimport { z } from \"zod\"\nimport type { AppSource } from \"./app-registry.js\"\n\nexport type { AppSource }\n\nexport type AppPlacement = \"local\" | \"box\" | \"any\" | \"split\"\n\nexport type AppCatalogTier = \"git\" | \"bundle\" | \"hosted\"\n\nexport interface AppCatalogLicense {\n  kind: \"free\" | \"paid\" | \"private\"\n  url?: string\n}\n\n/** A store-page screenshot (`app-catalog/v1` listing fields). */\nexport interface AppCatalogScreenshot {\n  url: string\n  alt: string\n  width?: number\n  height?: number\n}\n\nexport interface AppCatalogRequires {\n  browser?: boolean\n  fs?: boolean\n  secrets?: string[]\n}\n\n/** Remote catalog entry (`app-catalog/v1`). `source` lets a store call\n *  `app_install {url, ref, subdir, sha}` (git) or `app_install {url, sha256}`\n *  (`.agentapp`). Every field but `appId` + `source` is optional, so\n *  pre-v1 catalogs (`{ entries }` only) keep validating. */\nexport interface AppCatalogEntry {\n  appId: string\n  name?: string\n  description?: string\n  category?: string\n  source: AppSource\n  placement?: AppPlacement\n  icon?: string\n  version?: string\n  tier?: AppCatalogTier\n  publisher?: string\n  /** https URL of the publisher (their site), rendered as the publisher link. */\n  publisherUrl?: string\n  license?: AppCatalogLicense\n  minAgentprotoVersion?: string\n  requires?: AppCatalogRequires\n  featured?: boolean\n  /** Listing fields for a store page (agentproto.sh/apps/<slug>, the\n   *  daemon's /store). Shapes only here; `agentproto app pack --entry` and\n   *  `agentproto catalog verify` enforce the limits (CATALOG_LISTING_LIMITS). */\n  tagline?: string\n  /** Markdown (CommonMark + GFM); raw HTML is not rendered by consumers. */\n  longDescription?: string\n  screenshots?: AppCatalogScreenshot[]\n  /** Multi-valued successor of `category` (both are read). */\n  categories?: string[]\n  homepage?: string\n  repository?: string\n}\n\n/** Limits on the listing fields, enforced when an entry is produced\n *  (`app pack --entry`) and checked before it is published (`catalog\n *  verify`). The runtime schema stays shape-only so an older daemon never\n *  drops an entry over a limit change. */\nexport const CATALOG_LISTING_LIMITS = {\n  taglineMaxChars: 120,\n  longDescriptionMaxChars: 20_000,\n  screenshotsMax: 8,\n  screenshotMaxBytes: 1_000_000,\n  iconMaxBytes: 256_000,\n  altMaxChars: 200,\n  categoriesMax: 5,\n  categoryPattern: /^[a-z0-9-]{1,32}$/,\n} as const\n\n/** Entry of the local `app-catalog.json` `apps` array: a directory on disk. */\nexport interface AppCatalogFileEntry {\n  readonly appId: string\n  readonly name?: string\n  readonly description?: string\n  readonly dir: string\n  readonly category?: string\n}\n\nexport interface AppCatalogSource {\n  readonly url: string\n}\n\nexport interface AppCatalogFile {\n  readonly apps: readonly AppCatalogFileEntry[]\n  readonly sources?: readonly AppCatalogSource[]\n}\n\nconst AppSourceSchema: z.ZodType<AppSource> = z.discriminatedUnion(\"kind\", [\n  z.object({ kind: z.literal(\"local\") }),\n  z.object({\n    kind: z.literal(\"git\"),\n    url: z.string().min(1),\n    ref: z.string().optional(),\n    sha: z.string().min(1),\n    subdir: z.string().optional(),\n  }),\n  z.object({\n    kind: z.literal(\"agentapp\"),\n    url: z.string().min(1),\n    sha256: z.string().min(1),\n    version: z.string().min(1),\n    size: z.number().int().nonnegative().optional(),\n  }),\n])\n\nexport const AppCatalogEntrySchema: z.ZodType<AppCatalogEntry> = z.object({\n  appId: z.string().min(1),\n  name: z.string().optional(),\n  description: z.string().optional(),\n  category: z.string().optional(),\n  source: AppSourceSchema,\n  placement: z.enum([\"local\", \"box\", \"any\", \"split\"]).optional(),\n  icon: z.string().optional(),\n  version: z.string().optional(),\n  tier: z.enum([\"git\", \"bundle\", \"hosted\"]).optional(),\n  publisher: z.string().optional(),\n  publisherUrl: z\n    .string()\n    .regex(/^https:\\/\\/[^\\s]+$/i, \"publisherUrl must be an https URL\")\n    .optional(),\n  license: z\n    .object({ kind: z.enum([\"free\", \"paid\", \"private\"]), url: z.string().optional() })\n    .optional(),\n  minAgentprotoVersion: z.string().optional(),\n  requires: z\n    .object({\n      browser: z.boolean().optional(),\n      fs: z.boolean().optional(),\n      secrets: z.array(z.string()).optional(),\n    })\n    .optional(),\n  featured: z.boolean().optional(),\n  tagline: z.string().min(1).optional(),\n  longDescription: z.string().min(1).optional(),\n  screenshots: z\n    .array(\n      z.object({\n        url: z.string().min(1),\n        alt: z.string().min(1),\n        width: z.number().int().positive().optional(),\n        height: z.number().int().positive().optional(),\n      }),\n    )\n    .optional(),\n  categories: z.array(z.string().min(1)).optional(),\n  homepage: z.string().min(1).optional(),\n  repository: z.string().min(1).optional(),\n})\n\n/** `schema` tag of a v1 catalog document. */\nexport const CATALOG_SCHEMA_V1 = \"app-catalog/v1\"\n\nconst RemoteCatalogSchema = z.object({\n  schema: z.string().optional(),\n  generatedAt: z.string().optional(),\n  entries: z.array(z.unknown()),\n})\n\n/**\n * Default public catalog, queried by `app_catalog` unless config\n * `catalog.defaultSource` is `false` (a URL string replaces it). The file is\n * a static `apps.json` served by the agentproto/site repo\n * (`public/catalog/v1/apps.json`). Bundles it references are GitHub Release\n * assets of the public `agentproto/apps` repo. A failing default source is\n * never fatal: `app_catalog` falls back to the last good copy cached on\n * disk, then to the embedded first-party list (`first-party-catalog.ts`).\n */\nexport const DEFAULT_CATALOG_SOURCE_URL = \"https://agentproto.sh/catalog/v1/apps.json\"\n\nconst EMPTY_CATALOG: AppCatalogFile = { apps: [] }\n\nexport function defaultAppCatalogPath(): string {\n  return join(homedir(), \".agentproto\", \"app-catalog.json\")\n}\n\n/**\n * Read + parse the catalog file at `path` (default `~/.agentproto/app-catalog.json`).\n * Tolerates a missing file (returns an empty catalog) and a malformed one\n * (unreadable JSON, non-array `apps`, entries missing `appId`/`dir`, and\n * `sources` without a string `url` are dropped) — never throws.\n */\nexport async function loadAppCatalogFile(path?: string): Promise<AppCatalogFile> {\n  const catalogPath = path ?? defaultAppCatalogPath()\n  let raw: string\n  try {\n    raw = await readFile(catalogPath, \"utf8\")\n  } catch {\n    return EMPTY_CATALOG\n  }\n  try {\n    const parsed = JSON.parse(raw) as { apps?: unknown; sources?: unknown }\n    const sources = parseSources(parsed.sources)\n    const apps = Array.isArray(parsed.apps)\n      ? parsed.apps.filter((e): e is AppCatalogFileEntry => {\n          if (typeof e !== \"object\" || e === null) return false\n          const rec = e as Record<string, unknown>\n          return typeof rec.appId === \"string\" && typeof rec.dir === \"string\"\n        })\n      : []\n    return sources.length > 0 ? { apps, sources } : { apps }\n  } catch {\n    return EMPTY_CATALOG\n  }\n}\n\nfunction parseSources(raw: unknown): AppCatalogSource[] {\n  if (!Array.isArray(raw)) return []\n  const out: AppCatalogSource[] = []\n  for (const s of raw) {\n    if (typeof s !== \"object\" || s === null) continue\n    const url = (s as Record<string, unknown>).url\n    if (typeof url === \"string\" && url.length > 0) out.push({ url })\n  }\n  return out\n}\n\nexport type CatalogSourceOrigin = \"default\" | \"config\" | \"file\"\n\nexport interface ResolvedCatalogSource extends AppCatalogSource {\n  readonly origin: CatalogSourceOrigin\n}\n\n/**\n * Remote sources `app_catalog` queries, in precedence order (first wins on\n * an `appId` collision): the default source (unless `defaultSource: false`;\n * a non-empty string replaces its URL), then config `catalog.sources` when\n * set (even empty), else the catalog file's `sources`. Config/file sources\n * ADD to the default one, they never replace it. Duplicate URLs are dropped.\n */\nexport function resolveCatalogSources(\n  fileSources: readonly AppCatalogSource[] | undefined,\n  config: { sources?: unknown; defaultSource?: unknown } | undefined,\n): ResolvedCatalogSource[] {\n  const out: ResolvedCatalogSource[] = []\n  const seen = new Set<string>()\n  const push = (url: string, origin: CatalogSourceOrigin): void => {\n    if (seen.has(url)) return\n    seen.add(url)\n    out.push({ url, origin })\n  }\n  const def = config?.defaultSource\n  if (def !== false) {\n    push(typeof def === \"string\" && def.length > 0 ? def : DEFAULT_CATALOG_SOURCE_URL, \"default\")\n  }\n  if (Array.isArray(config?.sources)) {\n    for (const s of parseSources(config.sources)) push(s.url, \"config\")\n  } else {\n    for (const s of fileSources ?? []) push(s.url, \"file\")\n  }\n  return out\n}\n\n/** One source's outcome, in the order sources were passed. */\nexport interface CatalogSourceResult {\n  url: string\n  entries: AppCatalogEntry[]\n  /** True when `entries` come from the disk cache because the live fetch failed. */\n  stale: boolean\n  /** When the entries were fetched (live or cached), ISO-8601. */\n  fetchedAt?: string\n  /** False when the source yielded nothing at all (fetch failed, no cache). */\n  ok: boolean\n}\n\nexport interface RemoteCatalogResult {\n  entries: AppCatalogEntry[]\n  warnings: string[]\n  bySource: CatalogSourceResult[]\n}\n\nexport interface RemoteCatalogClientOptions {\n  /** Default 5 minutes. */\n  ttlMs?: number\n  /** Per-source request timeout. Default 5000. */\n  timeoutMs?: number\n  fetchImpl?: typeof fetch\n  now?: () => number\n  /** Directory for the last-good copy of each source (`<sha1(url)>.json`).\n   *  Absent = no disk cache (in-memory TTL cache only). */\n  cacheDir?: string\n}\n\nexport interface RemoteCatalogClient {\n  /** Fetch + validate every source (in order, in parallel). A failing source\n   *  never throws: it yields a `warnings` line and either its last cached\n   *  copy (`stale`) or no entries. Live results are cached per URL in memory\n   *  for `ttlMs` and on disk (when `cacheDir` is set); `refresh` bypasses the\n   *  in-memory cache. */\n  fetchSources(\n    sources: readonly AppCatalogSource[],\n    opts?: { refresh?: boolean },\n  ): Promise<RemoteCatalogResult>\n}\n\nexport const DEFAULT_REMOTE_CATALOG_TTL_MS = 5 * 60_000\nexport const DEFAULT_REMOTE_CATALOG_TIMEOUT_MS = 5_000\n\n/** Disk-cache file for `url` under `cacheDir`. */\nexport function catalogCachePath(cacheDir: string, url: string): string {\n  return join(cacheDir, `${createHash(\"sha1\").update(url).digest(\"hex\")}.json`)\n}\n\ninterface CatalogDiskCache {\n  url: string\n  fetchedAt: string\n  entries: unknown[]\n}\n\ntype SourceFetch = CatalogSourceResult & { warnings: string[] }\n\nexport function createRemoteCatalogClient(\n  options: RemoteCatalogClientOptions = {},\n): RemoteCatalogClient {\n  const ttlMs = options.ttlMs ?? DEFAULT_REMOTE_CATALOG_TTL_MS\n  const timeoutMs = options.timeoutMs ?? DEFAULT_REMOTE_CATALOG_TIMEOUT_MS\n  const fetchImpl = options.fetchImpl ?? fetch\n  const now = options.now ?? Date.now\n  const cacheDir = options.cacheDir\n  const cache = new Map<string, { at: number; result: SourceFetch }>()\n\n  async function readDiskCache(url: string): Promise<{ entries: AppCatalogEntry[]; fetchedAt: string } | undefined> {\n    if (cacheDir === undefined) return undefined\n    try {\n      const raw = JSON.parse(await readFile(catalogCachePath(cacheDir, url), \"utf8\")) as Partial<CatalogDiskCache>\n      if (raw.url !== url || !Array.isArray(raw.entries) || typeof raw.fetchedAt !== \"string\") return undefined\n      const entries: AppCatalogEntry[] = []\n      for (const e of raw.entries) {\n        const parsed = AppCatalogEntrySchema.safeParse(e)\n        if (parsed.success) entries.push(parsed.data)\n      }\n      return { entries, fetchedAt: raw.fetchedAt }\n    } catch {\n      return undefined\n    }\n  }\n\n  async function writeDiskCache(url: string, entries: AppCatalogEntry[], fetchedAt: string): Promise<void> {\n    if (cacheDir === undefined) return\n    try {\n      await mkdir(cacheDir, { recursive: true })\n      const file = catalogCachePath(cacheDir, url)\n      const tmp = `${file}.tmp-${process.pid}`\n      const body: CatalogDiskCache = { url, fetchedAt, entries }\n      await writeFile(tmp, JSON.stringify(body, null, 2) + \"\\n\", \"utf8\")\n      await rename(tmp, file)\n    } catch {\n      // Best-effort — a cache write failure must not fail the listing.\n    }\n  }\n\n  async function failed(url: string, warning: string): Promise<SourceFetch> {\n    const cached = await readDiskCache(url)\n    if (cached === undefined) return { url, entries: [], warnings: [warning], stale: false, ok: false }\n    return {\n      url,\n      entries: cached.entries,\n      warnings: [`${warning}; using the copy cached at ${cached.fetchedAt}`],\n      stale: true,\n      fetchedAt: cached.fetchedAt,\n      ok: true,\n    }\n  }\n\n  async function fetchOne(url: string): Promise<SourceFetch> {\n    let body: unknown\n    try {\n      const res = await fetchImpl(url, {\n        headers: { Accept: \"application/json\" },\n        signal: AbortSignal.timeout(timeoutMs),\n      })\n      if (!res.ok) throw new Error(`HTTP ${res.status}`)\n      body = await res.json()\n    } catch (err) {\n      const timedOut = err instanceof Error && (err.name === \"TimeoutError\" || err.name === \"AbortError\")\n      const reason = timedOut\n        ? `timed out after ${timeoutMs}ms`\n        : err instanceof Error\n          ? err.message\n          : String(err)\n      return failed(url, `catalog source ${url}: ${reason}`)\n    }\n    const shape = RemoteCatalogSchema.safeParse(body)\n    if (!shape.success) {\n      return failed(url, `catalog source ${url}: expected { entries: [...] }`)\n    }\n    const entries: AppCatalogEntry[] = []\n    const warnings: string[] = []\n    if (shape.data.schema !== undefined && shape.data.schema !== CATALOG_SCHEMA_V1) {\n      warnings.push(\n        `catalog source ${url}: unknown schema \"${shape.data.schema}\" — reading its entries as ${CATALOG_SCHEMA_V1}`,\n      )\n    }\n    shape.data.entries.forEach((raw, i) => {\n      const parsed = AppCatalogEntrySchema.safeParse(raw)\n      if (parsed.success) entries.push(parsed.data)\n      else warnings.push(`catalog source ${url}: entries[${i}] invalid (${parsed.error.issues[0]?.message ?? \"schema mismatch\"})`)\n    })\n    const fetchedAt = new Date(now()).toISOString()\n    await writeDiskCache(url, entries, fetchedAt)\n    return { url, entries, warnings, stale: false, fetchedAt, ok: true }\n  }\n\n  return {\n    async fetchSources(sources, opts = {}) {\n      const results = await Promise.all(\n        sources.map(async ({ url }) => {\n          const hit = cache.get(url)\n          if (!opts.refresh && hit && now() - hit.at < ttlMs) return hit.result\n          const result = await fetchOne(url)\n          // Neither failures nor stale disk fallbacks are cached in memory,\n          // so a flaky source retries on the next call.\n          if (!result.stale && (result.entries.length > 0 || result.warnings.length === 0)) {\n            cache.set(url, { at: now(), result })\n          } else {\n            cache.delete(url)\n          }\n          return result\n        }),\n      )\n      return {\n        entries: results.flatMap(r => r.entries),\n        warnings: results.flatMap(r => r.warnings),\n        bySource: results.map(({ warnings: _warnings, ...rest }) => rest),\n      }\n    },\n  }\n}\n\n/**\n * Compare dotted numeric versions (`1.2.10` > `1.2.9`); a pre-release suffix\n * (`1.2.0-beta`) ranks below the same core. Returns -1 | 0 | 1, or\n * `undefined` when either side isn't `N.N.N`-shaped.\n */\nexport function compareCatalogVersions(a: string, b: string): number | undefined {\n  const parse = (v: string): { core: number[]; pre: boolean } | undefined => {\n    const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(-.+)?$/.exec(v.trim())\n    return m ? { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] !== undefined } : undefined\n  }\n  const pa = parse(a)\n  const pb = parse(b)\n  if (pa === undefined || pb === undefined) return undefined\n  for (let i = 0; i < 3; i++) {\n    const d = pa.core[i]! - pb.core[i]!\n    if (d !== 0) return d < 0 ? -1 : 1\n  }\n  if (pa.pre === pb.pre) return 0\n  return pa.pre ? -1 : 1\n}\n\n/**\n * Is catalog `entry` an update for an installed app (recorded `source`,\n * APP.md `version`)? Only for the same source kind, only when the pin\n * differs (bundle sha256 / git commit), and never when the entry's version\n * is LOWER than the installed one — a catalog listing an older release is\n * not an update.\n */\nexport function isCatalogUpdate(\n  installed: { readonly source?: AppSource; readonly version?: string },\n  entry: AppCatalogEntry,\n): boolean {\n  const s = installed.source\n  if (s === undefined || s.kind === \"local\" || s.kind !== entry.source.kind) return false\n  const offered = entry.source\n  const differs =\n    s.kind === \"agentapp\"\n      ? offered.kind === \"agentapp\" && offered.sha256.toLowerCase() !== s.sha256.toLowerCase()\n      : offered.kind === \"git\" && offered.sha.toLowerCase() !== s.sha.toLowerCase()\n  if (!differs) return false\n  const installedVersion = s.kind === \"agentapp\" ? s.version : installed.version\n  const offeredVersion = offered.kind === \"agentapp\" ? offered.version : entry.version\n  if (installedVersion !== undefined && offeredVersion !== undefined) {\n    const cmp = compareCatalogVersions(offeredVersion, installedVersion)\n    if (cmp !== undefined && cmp < 0) return false\n  }\n  return true\n}\n","/**\n * Publishing-pipeline helpers shared by `agentproto catalog build`\n * (`packages/cli`) and the `catalog:first-party` sync script\n * (`packages/runtime/scripts/sync-first-party-catalog.mjs`): sorting +\n * merging catalog entries, and rendering the embedded first-party\n * catalog TypeScript file. Single source of truth -- no copies.\n */\n\nimport { CATALOG_SCHEMA_V1, type AppCatalogEntry } from \"./app-catalog.js\"\n\n/** A v1 catalog document as published at `DEFAULT_CATALOG_SOURCE_URL`. */\nexport interface CatalogDocument {\n  schema: string\n  generatedAt: string\n  entries: AppCatalogEntry[]\n}\n\n/** Entries sorted by `appId` (stable order for deterministic output). */\nexport function sortCatalogEntries(\n  entries: readonly AppCatalogEntry[],\n): AppCatalogEntry[] {\n  return [...entries].sort((a, b) => (a.appId < b.appId ? -1 : a.appId > b.appId ? 1 : 0))\n}\n\n/** Build a v1 catalog document with deterministic entry order. */\nexport function buildCatalogDocument(\n  entries: readonly AppCatalogEntry[],\n  generatedAt: string,\n): CatalogDocument {\n  return { schema: CATALOG_SCHEMA_V1, generatedAt, entries: sortCatalogEntries(entries) }\n}\n\n/** JSON serialization used for every published catalog file (2-space\n *  indent, trailing newline) so diffs stay clean. */\nexport function serializeCatalogDocument(doc: CatalogDocument): string {\n  return JSON.stringify(doc, null, 2) + \"\\n\"\n}\n\nexport interface MergeCatalogResult {\n  entries: AppCatalogEntry[]\n  /** `appId -> reason` for incoming entries that were NOT applied. */\n  skipped: Map<string, string>\n}\n\n/**\n * Merge incoming entries over `base` by `appId`: the incoming entry replaces\n * the existing one when its version is >= (per `compareCatalogVersions`;\n * unparseable versions always let the incoming entry win). An incoming\n * entry with a LOWER version is skipped with a warning and the existing\n * entry stays. Incoming entries with a version that ties or is unparseable\n * replace too -- publishing the same version twice is a no-op rewrite.\n */\nexport function mergeCatalogEntries(\n  base: readonly AppCatalogEntry[],\n  incoming: readonly AppCatalogEntry[],\n  compare: (a: string, b: string) => number | undefined,\n): MergeCatalogResult {\n  const byAppId = new Map<string, AppCatalogEntry>()\n  for (const e of base) byAppId.set(e.appId, e)\n  const skipped = new Map<string, string>()\n  for (const e of incoming) {\n    const existing = byAppId.get(e.appId)\n    if (existing === undefined) {\n      byAppId.set(e.appId, e)\n      continue\n    }\n    const ev = existing.version\n    const nv = e.version\n    if (ev !== undefined && nv !== undefined) {\n      const cmp = compare(nv, ev)\n      if (cmp !== undefined && cmp < 0) {\n        skipped.set(\n          e.appId,\n          `version ${nv} is older than the existing ${ev}; keeping the existing entry`,\n        )\n        continue\n      }\n    }\n    byAppId.set(e.appId, e)\n  }\n  return { entries: [...byAppId.values()], skipped }\n}\n\n/**\n * Render the embedded first-party catalog TypeScript file. The emitted\n * source must pass typecheck and lint as-is: entries are serialized as\n * plain literals (key order preserved from the validated entry).\n */\nexport function renderFirstPartyCatalogTs(\n  entries: readonly AppCatalogEntry[],\n): string {\n  const body = sortCatalogEntries(entries)\n    .map((e) => \"  \" + JSON.stringify(e, null, 2).replace(/\\n/g, \"\\n  \") + \",\")\n    .join(\"\\n\")\n  return `/**\n * Embedded first-party catalog -- the offline fallback for the DEFAULT\n * catalog source (\\`DEFAULT_CATALOG_SOURCE_URL\\`, app-catalog.ts) when it is\n * unreachable and no copy of it is cached on disk, so a fresh offline\n * daemon's \\`app_catalog\\` still lists first-party apps. Entries carry\n * metadata + URLs: they install once the network is back.\n *\n * GENERATED by \\`pnpm --filter @agentproto/runtime catalog:first-party\\`\n * from the published catalog -- do not hand-edit. \\`app_install {sha256}\\`\n * refuses any digest mismatch.\n */\n\nimport type { AppCatalogEntry } from \"./app-catalog.js\"\n\nexport const FIRST_PARTY_CATALOG_ENTRIES: readonly AppCatalogEntry[] = [\n${body}\n]\n`\n}\n"]}