{"version":3,"sources":["../src/model-list-store.ts","../src/model-policy.ts","../src/turn-retry-policy.ts","../src/session-preset-resolver.ts","../src/user-presets.ts"],"names":["z","resolve","homedir","readFile","join","mkdir","writeFile"],"mappings":";;;;;;;;;;;AAwBA,IAAM,kBAAA,GAAqB,CAAA,CAAE,kBAAA,CAAmB,MAAA,EAAQ;AAAA,EACtD,CAAA,CAAE,MAAA,CAAO,EAAE,IAAA,EAAM,EAAE,OAAA,CAAQ,OAAO,CAAA,EAAG,EAAA,EAAI,EAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,GAAG,CAAA;AAAA,EAC5D,CAAA,CAAE,MAAA,CAAO,EAAE,IAAA,EAAM,EAAE,OAAA,CAAQ,KAAK,CAAA,EAAG,KAAA,EAAO,EAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,GAAG,CAAA;AAAA,EAC7D,CAAA,CAAE,MAAA,CAAO,EAAE,IAAA,EAAM,EAAE,OAAA,CAAQ,UAAU,CAAA,EAAG,KAAA,EAAO,EAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,GAAG,CAAA;AAAA,EAClE,EAAE,MAAA,CAAO;AAAA,IACP,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,WAAW,CAAA;AAAA,IAC3B,KAAA,EAAO,EAAE,IAAA,CAAK,CAAC,OAAO,KAAA,EAAO,MAAA,EAAQ,SAAS,CAAC;AAAA,GAChD,CAAA;AAAA,EACD,EAAE,MAAA,CAAO;AAAA,IACP,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,MAAM,CAAA;AAAA,IACtB,KAAA,EAAO,EAAE,IAAA,CAAK,CAAC,OAAO,OAAA,EAAS,OAAA,EAAS,OAAO,CAAC;AAAA,GACjD;AACH,CAAC,CAAA;AAEM,IAAM,mBAAA,GAAsB,EAAE,KAAA,CAAM;AAAA,EACzC,kBAAA;AAAA,EACA,EAAE,MAAA,CAAO;AAAA,IACP,IAAA,EAAM,CAAA,CAAE,OAAA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tF,GAAI,KAAK,GAAA,GAAM,EAAE,KAAK,IAAA,CAAK,GAAA,KAAQ;AAAC,KACtC;AACA,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA;AACjC,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,GAAG,CAAA,EAAG;AACnB,IAAA,IAAA,CAAK,IAAI,GAAG,CAAA;AACZ,IAAA,GAAA,CAAI,KAAK,EAAE,GAAG,MAAA,EAAQ,MAAA,EAAQ,MAAM,CAAA;AAAA,EACtC;AACA,EAAA,OAAO,GAAA;AACT","file":"user-presets.mjs","sourcesContent":["/**\n * User-owned model lists — the persisted form of a named model selection.\n *\n * `~/.agentproto/model-lists.json` holds `{ version: 1, lists: ModelList[] }`.\n * The file is seeded with `zero-cost` (price 0/0) on first load. Model rules\n * never read it by name: a session's `ModelPolicy` (model-policy.ts) refers to\n * list ids chosen by the user.\n *\n * Writes are 0600 like the sibling stores. A MALFORMED file is a hard error\n * naming the path — unlike the preset stores, silently treating a broken list\n * file as empty would make every free model look paid and break spawning\n * without telling anyone.\n */\n\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\nimport { z } from \"zod\"\nimport {\n  inModelList,\n  type ModelList,\n  type ModelListSource,\n} from \"@agentproto/model-catalog/lists\"\n\nconst accessTargetSchema = z.discriminatedUnion(\"kind\", [\n  z.object({ kind: z.literal(\"model\"), id: z.string().min(1) }),\n  z.object({ kind: z.literal(\"tag\"), value: z.string().min(1) }),\n  z.object({ kind: z.literal(\"provider\"), value: z.string().min(1) }),\n  z.object({\n    kind: z.literal(\"priceTier\"),\n    value: z.enum([\"low\", \"mid\", \"high\", \"premium\"]),\n  }),\n  z.object({\n    kind: z.literal(\"kind\"),\n    value: z.enum([\"llm\", \"image\", \"video\", \"audio\"]),\n  }),\n])\n\nexport const modelSelectorSchema = z.union([\n  accessTargetSchema,\n  z.object({\n    kind: z.literal(\"price\"),\n    maxInPer1M: z.number().nonnegative().optional(),\n    maxOutPer1M: z.number().nonnegative().optional(),\n  }),\n  z.object({ kind: z.literal(\"context\"), min: z.number().nonnegative() }),\n  z.object({ kind: z.literal(\"variant\"), value: z.string().min(1) }),\n  z.object({ kind: z.literal(\"list\"), id: z.string().min(1) }),\n])\n\nexport const modelListSchema = z.object({\n  id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/),\n  label: z.string().min(1).optional(),\n  include: z.array(modelSelectorSchema).optional(),\n  exclude: z.array(modelSelectorSchema).optional(),\n  ids: z.array(z.string().min(1)).optional(),\n  order: z\n    .enum([\"listed\", \"cheapest\", \"largest-context\", \"newest\"])\n    .optional(),\n  rotation: z\n    .enum([\"priority\", \"round-robin\", \"least-recently-limited\"])\n    .optional(),\n}) satisfies z.ZodType<ModelList>\n\nconst modelListsFileSchema = z.object({\n  version: z.literal(1),\n  lists: z.array(modelListSchema),\n})\n\nexport type ModelListsFile = z.infer<typeof modelListsFileSchema>\n\nexport const ZERO_COST_LIST_ID = \"zero-cost\"\nexport const DEFAULT_ROTATION_LIST_ID = \"default-rotation\"\n\n/** Seeds whose definition is an entitlement boundary, never user data. An\n *  agent that can rewrite `zero-cost` can widen a `free-only` profile, so its\n *  stored definition is ignored and edits are refused. */\nexport const IMMUTABLE_SEED_LIST_IDS: ReadonlySet<string> = new Set([\n  ZERO_COST_LIST_ID,\n])\n\n/** Seed lists. Absent seeds are added on every load (so a file written by an\n *  earlier build gains new seeds). An existing list with the same id is kept\n *  as user data, except an immutable seed, which is always restored. */\nexport const SEED_MODEL_LISTS: readonly ModelList[] = [\n  {\n    id: ZERO_COST_LIST_ID,\n    label: \"Zero-cost models\",\n    include: [{ kind: \"tag\", value: \"price:zero\" }],\n  },\n  {\n    id: DEFAULT_ROTATION_LIST_ID,\n    label: \"Default rotation targets\",\n    ids: [\n      \"opencode/mimo-v2.6-flash-free\",\n      \"opencode/deepseek-v4.1-flash-free\",\n      \"opencode-go/glm-5.3-flash\",\n    ],\n  },\n]\n\nexport class ModelListStoreError extends Error {\n  readonly name = \"ModelListStoreError\"\n}\n\nexport function modelListsPath(): string {\n  return resolve(homedir(), \".agentproto\", \"model-lists.json\")\n}\n\nfunction seedFile(): ModelListsFile {\n  return {\n    version: 1,\n    lists: SEED_MODEL_LISTS.map(list => structuredClone(list)),\n  }\n}\n\n/** Append every seed list whose id is missing. An existing user-edited list is\n *  kept, except for an immutable seed (the entitlement boundary), which is\n *  always restored to its built-in definition. */\nfunction withMissingSeeds(file: ModelListsFile): {\n  file: ModelListsFile\n  changed: boolean\n} {\n  let changed = false\n  for (const seed of SEED_MODEL_LISTS) {\n    const index = file.lists.findIndex(list => list.id === seed.id)\n    if (index === -1) {\n      file.lists.push(structuredClone(seed))\n      changed = true\n      continue\n    }\n    if (!IMMUTABLE_SEED_LIST_IDS.has(seed.id)) continue\n    if (JSON.stringify(file.lists[index]) === JSON.stringify(seed)) continue\n    file.lists[index] = structuredClone(seed)\n    changed = true\n  }\n  return { file, changed }\n}\n\nasync function writeModelLists(file: ModelListsFile): Promise<void> {\n  const dir = join(homedir(), \".agentproto\")\n  await mkdir(dir, { recursive: true })\n  await writeFile(modelListsPath(), JSON.stringify(file, null, 2) + \"\\n\", {\n    encoding: \"utf8\",\n    mode: 0o600,\n  })\n}\n\n/** Load the persisted file. Absent = write and return the seed; malformed =\n *  throw naming the path (never silently empty). */\nexport async function loadModelLists(): Promise<ModelListsFile> {\n  let raw: string\n  try {\n    raw = await readFile(modelListsPath(), \"utf8\")\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n      const file = seedFile()\n      await writeModelLists(file)\n      return file\n    }\n    throw err\n  }\n  try {\n    const parsed = modelListsFileSchema.parse(JSON.parse(raw))\n    const merged = withMissingSeeds(parsed)\n    if (merged.changed) await writeModelLists(merged.file)\n    return merged.file\n  } catch (err) {\n    throw new ModelListStoreError(\n      `model lists file at ${modelListsPath()} is malformed: ` +\n        `${err instanceof Error ? err.message : String(err)}. ` +\n        `Fix it or move it aside to ${modelListsPath()}.bak; it is never ` +\n        `silently treated as empty.`,\n    )\n  }\n}\n\nexport async function listModelLists(): Promise<ModelList[]> {\n  return (await loadModelLists()).lists\n}\n\nexport async function getModelList(id: string): Promise<ModelList | undefined> {\n  return (await loadModelLists()).lists.find(list => list.id === id)\n}\n\nconst SEED_BY_ID = new Map(SEED_MODEL_LISTS.map(list => [list.id, list]))\n\n/** Seed lists fall back to their built-in definition when the stored file has\n *  lost them, so a deleted/corrupted file can never make a seed id look\n *  absent (fail closed: the model stays zero-cost, the rotation set stays).\n *  An immutable seed always resolves to its built-in definition, even if the\n *  file carries a tampered copy. */\nexport function modelListSourceFromLists(\n  lists: readonly ModelList[],\n): ModelListSource {\n  const byId = new Map(lists.map(list => [list.id, list]))\n  return {\n    get: id =>\n      IMMUTABLE_SEED_LIST_IDS.has(id)\n        ? SEED_BY_ID.get(id)\n        : (byId.get(id) ?? SEED_BY_ID.get(id)),\n  }\n}\n\n/** The seed-backed source, valid before the daemon has loaded the file. */\nexport function seedModelListSource(): ModelListSource {\n  return modelListSourceFromLists(SEED_MODEL_LISTS)\n}\n\nlet syncSource: ModelListSource | undefined\n\n/** Process-wide synchronous source. Before boot it serves the seed. */\nexport function getModelListSource(): ModelListSource {\n  return syncSource ?? seedModelListSource()\n}\n\n/** Load the file at daemon boot and install it as the sync source. */\nexport async function loadModelListSource(): Promise<ModelListSource> {\n  const file = await loadModelLists()\n  syncSource = modelListSourceFromLists(file.lists)\n  return syncSource\n}\n\n/** Fail-closed membership for entitlement / rotation hot paths: an unknown\n *  list or a cycle is \"not in the list\", never a throw on spawn or retry. */\nexport function isInModelList(\n  model: string,\n  id: string,\n  src: ModelListSource = getModelListSource(),\n): boolean {\n  try {\n    return inModelList(model, id, src)\n  } catch {\n    return false\n  }\n}\n\nfunction referencesList(list: ModelList, id: string): boolean {\n  return [...(list.include ?? []), ...(list.exclude ?? [])].some(\n    selector => selector.kind === \"list\" && selector.id === id,\n  )\n}\n\n/** Add or replace a list by id (validated), then refresh the sync source. */\nexport async function saveModelList(list: ModelList): Promise<ModelList> {\n  const validated = modelListSchema.parse(list)\n  if (IMMUTABLE_SEED_LIST_IDS.has(validated.id)) {\n    throw new ModelListStoreError(\n      `model list \"${validated.id}\" is built-in and cannot be edited; ` +\n        `create a new list instead.`,\n    )\n  }\n  const file = await loadModelLists()\n  const index = file.lists.findIndex(existing => existing.id === validated.id)\n  if (index === -1) file.lists.push(validated)\n  else file.lists[index] = validated\n  await writeModelLists(file)\n  syncSource = modelListSourceFromLists(file.lists)\n  return validated\n}\n\nexport async function deleteModelList(id: string): Promise<boolean> {\n  if (SEED_BY_ID.has(id)) {\n    throw new ModelListStoreError(\n      `model list \"${id}\" is a built-in seed and cannot be deleted.`,\n    )\n  }\n  const file = await loadModelLists()\n  const index = file.lists.findIndex(list => list.id === id)\n  if (index === -1) return false\n  const referencing = file.lists\n    .filter(list => list.id !== id && referencesList(list, id))\n    .map(list => list.id)\n  if (referencing.length > 0) {\n    throw new ModelListStoreError(\n      `model list \"${id}\" is referenced by ${referencing\n        .map(ref => `\"${ref}\"`)\n        .join(\", \")}; update or delete those lists first.`,\n    )\n  }\n  file.lists.splice(index, 1)\n  await writeModelLists(file)\n  syncSource = modelListSourceFromLists(file.lists)\n  return true\n}\n\n/** Test helper: forget any loaded source so the seed applies again. */\nexport function resetModelListSource(): void {\n  syncSource = undefined\n}\n","/**\n * Generic model policy: the only model rule a session can carry. `allow` and\n * `block` hold model-list ids (see `model-list-store.ts`); nothing here knows\n * about price. A session without a policy may use any model its account allows.\n */\n\nimport { z } from \"zod\"\nimport { inModelList, ModelListError, type ModelListSource } from \"@agentproto/model-catalog/lists\"\n\nexport interface ModelPolicy {\n  /** List ids. When present, a model outside every one of them is refused,\n   *  uncataloged ids included. */\n  allow?: string[]\n  /** List ids. A model in any of them is refused; always wins over `allow`. */\n  block?: string[]\n  /** Composition form: every entry must pass. Used when two policies are\n   *  combined (a session preset's and the request's) and the intersection of\n   *  their `allow` lists cannot be represented by one list id array. Never\n   *  accepted from caller input; see {@link composeModelPolicies}. */\n  all?: ModelPolicy[]\n}\n\nexport type PolicyVerdict =\n  | { ok: true }\n  | {\n      ok: false\n      code: \"model_blocked\" | \"model_not_allowed\" | \"model_unresolved\" | \"unknown_list\"\n      reason: string\n    }\n\nexport const modelPolicySchema = z.object({\n  allow: z.array(z.string().min(1)).max(32).optional(),\n  block: z.array(z.string().min(1)).max(32).optional(),\n})\n\n/** Strict schema for caller input (`agent_start`, HTTP spawn): an unknown key\n *  such as `allows` is a validation error, never a silently dropped\n *  restriction. */\nexport const modelPolicyInputSchema = modelPolicySchema.strict()\n\n/** Tolerant normalizer for already-validated or stored descriptors: dedupes,\n *  returns undefined when the value is not a policy or has neither key. An\n *  empty `allow` is kept: it means \"nothing is allowed\". Never use it to\n *  validate caller input; use {@link modelPolicyInputSchema}. */\nexport function normalizeModelPolicy(raw: unknown): ModelPolicy | undefined {\n  const parsed = modelPolicySchema.safeParse(raw)\n  if (!parsed.success) return undefined\n  const { allow, block } = parsed.data\n  if (!allow && !block) return undefined\n  return {\n    ...(allow ? { allow: [...new Set(allow)] } : {}),\n    ...(block ? { block: [...new Set(block)] } : {}),\n  }\n}\n\nfunction unknownList(err: unknown): PolicyVerdict {\n  return {\n    ok: false,\n    code: \"unknown_list\",\n    reason: err instanceof Error ? err.message : String(err),\n  }\n}\n\n/** Compose policies so BOTH apply: a model must pass every one. A single\n *  policy passes through unchanged; otherwise the result is an `all` node\n *  (an intersection of two allow lists has no single-list representation).\n *  `undefined` when no policy contributes a rule. */\nexport function composeModelPolicies(\n  ...policies: Array<ModelPolicy | undefined>\n): ModelPolicy | undefined {\n  const present = policies.filter(\n    (policy): policy is ModelPolicy =>\n      policy !== undefined &&\n      (policy.all !== undefined || policy.allow !== undefined || policy.block !== undefined),\n  )\n  if (present.length === 0) return undefined\n  if (present.length === 1) return present[0]\n  return { all: present }\n}\n\nexport function checkModelPolicy(\n  model: string | undefined,\n  policy: ModelPolicy | undefined,\n  src: ModelListSource,\n): PolicyVerdict {\n  if (!policy) return { ok: true }\n  for (const nested of policy.all ?? []) {\n    const verdict = checkModelPolicy(model, nested, src)\n    if (!verdict.ok) return verdict\n  }\n  for (const id of [...(policy.block ?? []), ...(policy.allow ?? [])]) {\n    if (!src.get(id)) return unknownList(new Error(`unknown model list \"${id}\"`))\n  }\n  if (model === undefined) {\n    // No model means no way to prove the model is inside an allow list. A\n    // block-only policy is still safe: there is no model it could admit.\n    return policy.allow === undefined\n      ? { ok: true }\n      : {\n          ok: false,\n          code: \"model_unresolved\",\n          reason: `model policy has an allow list (${policy.allow.join(\", \") || \"none\"}) but no model could be resolved to check`,\n        }\n  }\n  try {\n    for (const id of policy.block ?? []) {\n      if (inModelList(model, id, src)) {\n        return { ok: false, code: \"model_blocked\", reason: `model \"${model}\" is in blocked list \"${id}\"` }\n      }\n    }\n    if (policy.allow && !policy.allow.some(id => inModelList(model, id, src))) {\n      return {\n        ok: false,\n        code: \"model_not_allowed\",\n        reason: `model \"${model}\" is not in any allowed list (${policy.allow.join(\", \") || \"none\"})`,\n      }\n    }\n    return { ok: true }\n  } catch (err) {\n    if (err instanceof ModelListError) return unknownList(err)\n    throw err\n  }\n}\n","/**\n * `turnRetry` spawn option — the policy SHAPE only (zod schema, type,\n * defaults, tolerant parser). Kept free of any `sessions.ts` import so the\n * descriptor, the `agent_start` schema, the HTTP body parser, and the user\n * preset store can all share it without an import cycle. The behaviour lives\n * in `turn-retry.ts`.\n *\n * OFF by default for interactive supervisor sessions and ON by default for\n * executor / sandbox spawns: a spawn without `turnRetry` gets the DEFAULT\n * policy below (see {@link defaultTurnRetryForSpawn}), while a supervisor\n * turn that fails on a 429/5xx, or stalls silently while the provider\n * retries internally, just stops. DISTINCT from `restartPolicy`,\n * which revives a DEAD process; `turnRetry` re-prompts a LIVE session whose\n * last turn failed for a transient provider reason.\n */\n\nimport { z } from \"zod\"\nimport { resolveModelList } from \"@agentproto/model-catalog/lists\"\nimport { DEFAULT_ROTATION_LIST_ID, getModelListSource, isInModelList } from \"./model-list-store.js\"\nimport { checkModelPolicy, type ModelPolicy } from \"./model-policy.js\"\n\n/** Turn-failure classes `turnRetry.on` can opt into. */\nexport const TURN_RETRY_CLASSES = [\"rate-limit\", \"upstream-5xx\", \"no-output-stall\", \"usage-limit\"] as const\nexport type TurnRetryClass = (typeof TURN_RETRY_CLASSES)[number]\n\n/** Names AIP-46 `FailureClass` uses for a class this host calls otherwise, accepted\n *  on input (`on`, `rotateOn`) and mapped to the canonical class when the policy\n *  is resolved. `usage-limit` stays canonical: it is what descriptors, events\n *  (`session:turn-retry`) and stored presets already carry, so the alias is\n *  purely additive. (AIP-46 `auth-failed` is this host's `auth`, which is never\n *  a retry class and so never appears in `on`.) */\nexport const TURN_RETRY_CLASS_ALIASES = { \"quota-exhausted\": \"usage-limit\" } as const satisfies Record<string, TurnRetryClass>\nexport type TurnRetryClassInput = TurnRetryClass | keyof typeof TURN_RETRY_CLASS_ALIASES\nconst TURN_RETRY_CLASS_INPUTS = [...TURN_RETRY_CLASSES, ...Object.keys(TURN_RETRY_CLASS_ALIASES)] as [\n  TurnRetryClassInput,\n  ...TurnRetryClassInput[],\n]\n\n/** The canonical class of an accepted class name (an alias maps, a class is itself). */\nexport function canonicalTurnRetryClass(name: TurnRetryClassInput): TurnRetryClass {\n  return name in TURN_RETRY_CLASS_ALIASES\n    ? TURN_RETRY_CLASS_ALIASES[name as keyof typeof TURN_RETRY_CLASS_ALIASES]\n    : (name as TurnRetryClass)\n}\n\n/** What a matching failure does. `retry` (the default) re-prompts the same\n *  live session after backoff; `migrate` moves a SANDBOX session to a fresh\n *  box (new IP) and re-prompts it there — see `turn-retry.ts`. */\nexport const TURN_RETRY_ACTIONS = [\"retry\", \"migrate\"] as const\nexport type TurnRetryAction = (typeof TURN_RETRY_ACTIONS)[number]\n\nexport interface TurnRetryPolicy {\n  /** Which transient failure classes trigger a retry:\n   *  - `rate-limit` — HTTP 429 / \"rate limit\" / \"too many requests\";\n   *  - `upstream-5xx` — HTTP 5xx / \"overloaded\" / \"bad gateway\" / \"endpoint unavailable\" /\n   *    \"at capacity; retry shortly\" / a network-level failure (EPROTO \"TLS\n   *    handshake failed\", ECONNRESET, ETIMEDOUT, EPIPE, EAI_AGAIN, \"socket\n   *    hang up\") …;\n   *  - `no-output-stall` — the stall watchdog flagged a turn that produced\n   *    nothing since its prompt (`NO_OUTPUT_STALL_TURN_ERROR`, the opencode\n   *    silent-429 loop). That turn is still running, so the retry interrupts\n   *    it before re-prompting;\n   *  - `usage-limit`: a provider usage cap (\"Free usage limit reached\",\n   *    \"usage limit exceeded\"). Opt-in only (never in the default set): a cap\n   *    does not recover with backoff, so there is NO same-config retry. The\n   *    session moves straight to `rotate` / `fallback` (or, with\n   *    `action: \"migrate\"`, a fresh box = a new IP, the fix for a per-IP cap)\n   *    and gives up when none of those is available. */\n  on: TurnRetryClass[]\n  /** What a matching failure does: `retry` re-prompts the same live session\n   *  after backoff; `migrate` moves a sandbox session to a fresh box (new IP)\n   *  and re-prompts it there. Default `retry` — fully backward compatible. */\n  action: TurnRetryAction\n  /** Consecutive retries allowed without a clean turn in between. */\n  maxRetries: number\n  /** Box migrations allowed without a clean turn in between (action `migrate`\n   *  only). Independent of `maxRetries`: once the cap is spent the failure\n   *  falls back to a normal retry / give-up. Non-negative — `0` means the\n   *  migrate action never migrates. Default {@link TURN_MIGRATE_DEFAULTS}. */\n  maxMigrations: number\n  /** First retry's backoff delay (ms), before `factor` compounds it. */\n  baseDelayMs: number\n  /** Exponential backoff multiplier per consecutive retry. */\n  factor: number\n  /** Backoff ceiling (ms). Also caps a provider `retry-after` hint. */\n  maxDelayMs: number\n  /** Retry even when the failed turn already made a tool call that may have\n   *  side effects (anything not provably read-only, see\n   *  `read-only-tool-call.ts`). Default\n   *  false: such a turn is NOT retried, because the continuation could\n   *  repeat a write/exec the agent already did. */\n  retryAfterToolCalls?: boolean\n  /** Ordered fallback models. When a retry fires for a class in `rotateOn`,\n   *  the session is switched (live, before the continuation prompt) to the\n   *  first target that is not cooling down and passes the eligibility checks.\n   *  v1 switches the model on the session's CURRENT profile only: a target\n   *  naming a different `profileRef` is skipped. Absent ⇒ never rotate. */\n  rotate?: TurnRetryRotateTarget[]\n  /** Classes that rotate (must be a subset of what `on` retries). Default\n   *  `rate-limit` + `no-output-stall` (+ `usage-limit` when `on` lists it); add\n   *  `upstream-5xx` to rotate on those too. */\n  rotateOn?: TurnRetryClass[]\n  /** How long a rate-limited model is skipped, daemon-wide, when the error\n   *  carries no retry-after hint (ms). Default {@link TURN_ROTATE_DEFAULTS}. */\n  cooldownMs?: number\n  /** Ordered config overlays tried after same-config retries are exhausted.\n   *  Each overlay is merged over the session's BASE (spawn) config; the first\n   *  eligible one is applied with the least disruptive transition. `rotate`\n   *  is the model-only special case. Absent ⇒ no fallback chain. */\n  fallback?: TurnRetryFallbackOverlay[]\n}\n\n/** One overlay of `turnRetry.fallback`. Omitted axes keep the base value. */\nexport interface TurnRetryFallbackOverlay {\n  model?: string\n  access?: { profileRef: string }\n  harness?: string\n}\n\n/** One fallback target of `turnRetry.rotate`. */\nexport interface TurnRetryRotateTarget {\n  model: string\n  /** Billing profile the target must run under. v1: must equal the session's\n   *  current profile (or be omitted = \"the current profile\"). */\n  profileRef?: string\n}\n\nexport const TURN_RETRY_DEFAULTS = {\n  maxRetries: 3,\n  baseDelayMs: 5_000,\n  factor: 2,\n  maxDelayMs: 60_000,\n} as const\n\nexport const TURN_MIGRATE_DEFAULTS = {\n  maxMigrations: 2,\n} as const\n\nexport const TURN_ROTATE_DEFAULTS = {\n  rotateOn: [\"rate-limit\", \"no-output-stall\"] as TurnRetryClass[],\n  cooldownMs: 10 * 60_000,\n} as const\n\n/** Failure classes the DEFAULT always-on policy covers (executor / sandbox\n *  spawns that gave no explicit `turnRetry`). */\nexport const TURN_RETRY_DEFAULT_ON: TurnRetryClass[] = [\"rate-limit\", \"upstream-5xx\", \"no-output-stall\"]\n\n/** Consecutive retries the default policy allows. */\nexport const TURN_RETRY_DEFAULT_MAX_RETRIES = 6\n\n/** The same bare key used to drop the current model from the default list:\n *  `@route` stripped, last `/` segment, lowercased. */\nfunction bareKey(model: string): string {\n  return (model.split(\"@\")[0] ?? model).split(\"/\").pop()?.toLowerCase() ?? \"\"\n}\n\n/** The default rotate targets: the curated `default-rotation` list minus the\n *  current model (by bare key), filtered by the session policy, in list order. */\nfunction defaultRotateTargets(currentModel: string, policy: ModelPolicy | undefined): TurnRetryRotateTarget[] {\n  const key = bareKey(currentModel)\n  const source = getModelListSource()\n  let ids: string[]\n  try {\n    ids = resolveModelList(DEFAULT_ROTATION_LIST_ID, source)\n  } catch {\n    // A broken/cyclic rotation list must fail closed: no rotation, no throw\n    // on the spawn hot path.\n    return []\n  }\n  return ids\n    .filter(id => bareKey(id) !== key)\n    .filter(id => checkModelPolicy(id, policy, source).ok)\n    .map(model => ({ model }))\n}\n\n/** Build the turnRetry INPUT a spawn with no explicit `turnRetry` (explicit\n *  or via a preset) receives when the default is ON, i.e. for an executor\n *  role or a `sandbox` spawn. When the current model is itself in the\n *  `default-rotation` model list, the default also ROTATES on every covered\n *  class (rate limits and 5xx alike) onto the other members of that list the\n *  session policy allows; any other model gets no rotate list. */\nexport function defaultTurnRetryForSpawn(\n  currentModel?: string,\n  policy?: ModelPolicy,\n): Exclude<TurnRetryInput, null> {\n  const base: Exclude<TurnRetryInput, null> = {\n    on: [...TURN_RETRY_DEFAULT_ON],\n    maxRetries: TURN_RETRY_DEFAULT_MAX_RETRIES,\n  }\n  if (!currentModel || !isInModelList(currentModel, DEFAULT_ROTATION_LIST_ID)) {\n    return base\n  }\n  const rotate = defaultRotateTargets(currentModel, policy)\n  if (rotate.length === 0) return base\n  return { ...base, rotate, rotateOn: [...TURN_RETRY_DEFAULT_ON] }\n}\n\n/** Spawn-time check: every rotate target must pass the session's model\n *  policy, if any. Returns an error message, or undefined when fine. */\nexport function validateTurnRetryRotate(\n  rotate: readonly TurnRetryRotateTarget[] | undefined,\n  policy: ModelPolicy | undefined,\n): string | undefined {\n  if (!rotate?.length || !policy) return undefined\n  const source = getModelListSource()\n  const refused = rotate\n    .map(t => ({ model: t.model, verdict: checkModelPolicy(t.model, policy, source) }))\n    .filter(t => !t.verdict.ok)\n  if (refused.length === 0) return undefined\n  return (\n    `turnRetry.rotate: targets refused by the session model policy. ` +\n    refused.map(t => (t.verdict.ok ? \"\" : `${t.model} (${t.verdict.reason})`)).join(\"; \")\n  )\n}\n\n/** Input shape (agent_start / user preset): only `on` is required; the\n *  numeric knobs default to {@link TURN_RETRY_DEFAULTS}, `action` to `retry`\n *  and `maxMigrations` to {@link TURN_MIGRATE_DEFAULTS}. Opt-OUT stays an\n *  explicit choice: `null`, or an object whose `on` list is empty, resolves\n *  to a session that never retries (the spawn-time default is skipped for\n *  an explicit `turnRetry`, even a disabling one). */\nexport const turnRetryObjectSchema = z.object({\n  on: z.array(z.enum(TURN_RETRY_CLASS_INPUTS)),\n  action: z.enum(TURN_RETRY_ACTIONS).optional(),\n  maxRetries: z.number().int().positive().optional(),\n  baseDelayMs: z.number().int().nonnegative().optional(),\n  factor: z.number().min(1).optional(),\n  maxDelayMs: z.number().int().nonnegative().optional(),\n  maxMigrations: z.number().int().nonnegative().optional(),\n  retryAfterToolCalls: z.boolean().optional(),\n  rotate: z\n    .array(z.object({ model: z.string().min(1), profileRef: z.string().min(1).optional() }))\n    .max(16)\n    .optional(),\n  rotateOn: z.array(z.enum(TURN_RETRY_CLASS_INPUTS)).min(1).optional(),\n  cooldownMs: z.number().int().positive().optional(),\n  fallback: z\n    .array(\n      z\n        .object({\n          model: z.string().min(1).optional(),\n          access: z.object({ profileRef: z.string().min(1) }).optional(),\n          harness: z.string().min(1).optional(),\n        })\n        .refine(o => o.model !== undefined || o.access !== undefined || o.harness !== undefined, {\n          message: \"a fallback overlay must set model, access or harness\",\n        }),\n    )\n    .max(16)\n    .optional(),\n})\n\nexport const turnRetryInputSchema = z.union([turnRetryObjectSchema, z.null()])\n\nexport type TurnRetryPolicyInput = z.infer<typeof turnRetryObjectSchema>\nexport type TurnRetryInput = TurnRetryPolicyInput | null\n\n/** Fill defaults and dedupe `on`. `maxDelayMs` is raised to `baseDelayMs`\n *  when given lower, so the curve is never inverted. An empty `on` resolves\n *  to a policy that matches nothing — the explicit \"never retry\" shape. */\nexport function resolveTurnRetryPolicy(raw: TurnRetryPolicyInput): TurnRetryPolicy {\n  // Accept the AIP-46 class names beside this host's own, once, at the boundary.\n  const { rotateOn: rawRotateOn, ...rest } = raw\n  const input = {\n    ...rest,\n    on: raw.on.map(canonicalTurnRetryClass),\n    ...(rawRotateOn ? { rotateOn: rawRotateOn.map(canonicalTurnRetryClass) } : {}),\n  }\n  const baseDelayMs = input.baseDelayMs ?? TURN_RETRY_DEFAULTS.baseDelayMs\n  return {\n    on: [...new Set(input.on)],\n    action: input.action ?? \"retry\",\n    maxRetries: input.maxRetries ?? TURN_RETRY_DEFAULTS.maxRetries,\n    baseDelayMs,\n    factor: input.factor ?? TURN_RETRY_DEFAULTS.factor,\n    maxDelayMs: Math.max(input.maxDelayMs ?? TURN_RETRY_DEFAULTS.maxDelayMs, baseDelayMs),\n    maxMigrations: input.maxMigrations ?? TURN_MIGRATE_DEFAULTS.maxMigrations,\n    ...(input.retryAfterToolCalls ? { retryAfterToolCalls: true } : {}),\n    ...(input.rotate?.length\n      ? {\n          rotate: input.rotate.map(t => ({ model: t.model, ...(t.profileRef ? { profileRef: t.profileRef } : {}) })),\n          rotateOn: [\n            ...new Set(\n              input.rotateOn ??\n                (input.on.includes(\"usage-limit\")\n                  ? [...TURN_ROTATE_DEFAULTS.rotateOn, \"usage-limit\" as const]\n                  : TURN_ROTATE_DEFAULTS.rotateOn),\n            ),\n          ],\n        }\n      : {}),\n    ...(input.cooldownMs !== undefined ? { cooldownMs: input.cooldownMs } : {}),\n    ...(input.fallback?.length\n      ? {\n          fallback: input.fallback.map(o => ({\n            ...(o.model !== undefined ? { model: o.model } : {}),\n            ...(o.access !== undefined ? { access: { profileRef: o.access.profileRef } } : {}),\n            ...(o.harness !== undefined ? { harness: o.harness } : {}),\n          })),\n        }\n      : {}),\n  }\n}\n\n/** Tolerant parser for the HTTP body / CLI: accepts the object, a\n *  JSON-stringified object, or a shorthand string — a comma list of classes\n *  (`\"rate-limit,upstream-5xx\"`), `\"all\"` for every transient class (not\n *  `usage-limit`), or `\"off\"` for an\n *  explicit opt-out (a policy that matches nothing). Returns `undefined` for\n *  anything else that does not validate (never a partial policy). */\nexport function parseTurnRetryPolicy(raw: unknown): TurnRetryPolicy | undefined {\n  let value: unknown = raw\n  if (typeof raw === \"string\") {\n    const trimmed = raw.trim()\n    if (trimmed.startsWith(\"{\")) {\n      try {\n        value = JSON.parse(trimmed)\n      } catch {\n        return undefined\n      }\n    } else if (trimmed === \"all\") {\n      // The transient classes only: `usage-limit` stays an explicit opt-in.\n      value = { on: [...TURN_RETRY_DEFAULT_ON] }\n    } else if (trimmed === \"off\") {\n      value = { on: [] }\n    } else {\n      value = { on: trimmed.split(\",\").map(s => s.trim()).filter(Boolean) }\n    }\n  } else if (raw === null) {\n    value = { on: [] }\n  }\n  const parsed = turnRetryObjectSchema.safeParse(value)\n  return parsed.success ? resolveTurnRetryPolicy(parsed.data) : undefined\n}\n","/**\n * Pure session-config resolution (AIP-46 §Session config, presets and\n * fallback). Builds the effective config axis by axis from the layers, lowest\n * precedence first:\n *\n *   manifest -> host -> definition -> harness preset -> preset (defaultFor,\n *   then the named preset after its extends chain) -> request\n *\n * Each axis is replaced whole by the highest layer that sets it, except:\n * `options` merges key by key, `tags` union, and `modelPolicy` entries\n * accumulate (both apply). No I/O lives here, so the spawn path, the CLI and\n * the MCP tools all resolve a config through the same code.\n */\n\nimport {\n  composeModelPolicies,\n  type ModelPolicy,\n} from \"./model-policy.js\"\nimport type {\n  ContextProfile,\n  EffortLevel,\n  Posture,\n  RouteSpec,\n} from \"./session-config.js\"\nimport type { SpawnBrowserMode } from \"./browser-mount.js\"\nimport type { TurnRetryInput } from \"./turn-retry-policy.js\"\nimport type { UserPreset } from \"./user-presets.js\"\n\n/** Every axis the resolver knows. Placement (sandbox, worktree) is out of\n *  scope by contract. */\nexport type SessionConfigAxis =\n  | \"harness\"\n  | \"model\"\n  | \"effort\"\n  | \"access\"\n  | \"route\"\n  | \"posture\"\n  | \"contextProfile\"\n  | \"cwd\"\n  | \"skills\"\n  | \"bundles\"\n  | \"browser\"\n  | \"turnRetry\"\n  | \"options\"\n  | \"tags\"\n  | \"modelPolicy\"\n\n/** Where an axis came from. `preset:<id>` is a named preset (or a member of\n *  its `extends` chain); `preset-default:<id>` is the `defaultFor` preset. */\nexport type SessionConfigLayer =\n  | \"manifest\"\n  | \"host\"\n  | \"definition\"\n  | \"harness-preset\"\n  | `preset:${string}`\n  | `preset-default:${string}`\n  | \"request\"\n\nexport interface SessionConfigAxes {\n  harness?: string\n  model?: string\n  effort?: EffortLevel\n  access?: { profileRef?: string }\n  route?: RouteSpec\n  posture?: Posture\n  contextProfile?: ContextProfile\n  cwd?: string\n  skills?: string[]\n  bundles?: string[]\n  browser?: SpawnBrowserMode\n  turnRetry?: TurnRetryInput\n  /** Harness-native options not covered by an axis; merged key by key. */\n  options?: Record<string, unknown>\n  /** Preset discovery tags; unioned across layers. */\n  tags?: string[]\n  /** This implementation's form of the AIP-38 policy. */\n  modelPolicy?: ModelPolicy\n}\n\nexport interface SessionConfigResolution {\n  config: SessionConfigAxes\n  /** The layer that produced each axis. Absent = no layer set it. */\n  layers: Partial<Record<SessionConfigAxis, SessionConfigLayer>>\n}\n\n/** The legacy harness default (`harness-presets.json`) projected onto the\n *  session-config axes. It ranks below the `defaultFor` session preset. */\nexport interface HarnessPresetOverlay {\n  id: string\n  access?: { profileRef?: string }\n  model?: string\n  turnRetry?: TurnRetryInput\n}\n\nexport interface ResolveSessionConfigInput {\n  /** Explicit spawn request axes: the highest layer. */\n  request?: SessionConfigAxes\n  /** The user's session preset store. */\n  presets?: readonly UserPreset[]\n  /** The harness slug the request resolves to. */\n  harness?: string\n  /** Named preset id. `request.presetId` is accepted for convenience. */\n  presetId?: string\n  manifest?: SessionConfigAxes\n  host?: SessionConfigAxes\n  definition?: SessionConfigAxes\n  harnessPreset?: HarnessPresetOverlay\n}\n\n/** Typed resolution failure (missing extends target or a cycle). Save-time\n *  validation in `user-presets.ts` also uses these codes. */\nexport class SessionPresetResolutionError extends Error {\n  constructor(\n    readonly code: \"unknown_extends\" | \"extends_cycle\",\n    message: string,\n  ) {\n    super(message)\n    this.name = \"SessionPresetResolutionError\"\n  }\n}\n\nconst REPLACED_AXES = [\n  \"harness\",\n  \"model\",\n  \"effort\",\n  \"access\",\n  \"route\",\n  \"posture\",\n  \"contextProfile\",\n  \"cwd\",\n  \"skills\",\n  \"bundles\",\n  \"browser\",\n  \"turnRetry\",\n] as const satisfies readonly SessionConfigAxis[]\n\nfunction presetById(presets: readonly UserPreset[], id: string): UserPreset {\n  const preset = presets.find(entry => entry.id === id)\n  if (!preset) {\n    throw new SessionPresetResolutionError(\n      \"unknown_extends\",\n      `session preset \"${id}\" does not exist`,\n    )\n  }\n  return preset\n}\n\n/** The preset followed by its `extends` ancestors, applied order: ancestors\n *  first, left to right, then the preset itself. Throws on a missing target\n *  or a cycle. */\nexport function presetChain(\n  id: string,\n  presets: readonly UserPreset[],\n): UserPreset[] {\n  const out: UserPreset[] = []\n  const visiting: string[] = []\n\n  const visit = (current: string): void => {\n    const cycleAt = visiting.indexOf(current)\n    if (cycleAt !== -1) {\n      const cycle = [...visiting.slice(cycleAt), current].join(\" -> \")\n      throw new SessionPresetResolutionError(\n        \"extends_cycle\",\n        `session preset extends cycle: ${cycle}`,\n      )\n    }\n    const preset = presetById(presets, current)\n    visiting.push(current)\n    for (const parent of preset.extends ?? []) visit(parent)\n    visiting.pop()\n    out.push(preset)\n  }\n\n  visit(id)\n  return out\n}\n\n/** The preset whose `defaultFor` names `harness`, if any. Save-time\n *  validation keeps this unique; a hand-edited file resolves to the first. */\nexport function defaultPresetFor(\n  harness: string | undefined,\n  presets: readonly UserPreset[],\n): UserPreset | undefined {\n  if (!harness) return undefined\n  return presets.find(preset => preset.defaultFor === harness)\n}\n\n/** A preset's flat fields with any nested `config` underneath them. Flat\n *  fields win when both name the same axis (AIP-46 migration note). */\nexport function presetAxes(preset: UserPreset): SessionConfigAxes {\n  const nested = (preset.config ?? {}) as SessionConfigAxes\n  const flat: SessionConfigAxes = {\n    harness: preset.harness,\n    model: preset.model,\n    effort: preset.effort,\n    access: preset.access,\n    route: preset.route,\n    posture: preset.posture,\n    contextProfile: preset.contextProfile,\n    cwd: preset.cwd,\n    skills: preset.skills,\n    bundles: preset.bundles,\n    browser: preset.browser,\n    turnRetry: preset.turnRetry,\n    options: preset.options,\n  }\n  const merged: SessionConfigAxes = { ...nested }\n  for (const axis of REPLACED_AXES) {\n    const value = flat[axis]\n    if (value !== undefined) (merged as Record<string, unknown>)[axis] = value\n  }\n  if (flat.options !== undefined) merged.options = { ...(nested.options ?? {}), ...flat.options }\n  if (preset.tags !== undefined) merged.tags = preset.tags\n  if (preset.modelPolicy !== undefined) merged.modelPolicy = preset.modelPolicy\n  return merged\n}\n\ninterface Accumulator {\n  config: SessionConfigAxes\n  layers: Partial<Record<SessionConfigAxis, SessionConfigLayer>>\n}\n\nfunction applyLayer(\n  acc: Accumulator,\n  axes: SessionConfigAxes | undefined,\n  layer: SessionConfigLayer,\n): void {\n  if (!axes) return\n  for (const axis of REPLACED_AXES) {\n    const value = axes[axis]\n    if (value !== undefined) {\n      ;(acc.config as Record<string, unknown>)[axis] = value\n      acc.layers[axis] = layer\n    }\n  }\n  if (axes.options !== undefined) {\n    acc.config.options = { ...(acc.config.options ?? {}), ...axes.options }\n    acc.layers.options = layer\n  }\n  if (axes.tags !== undefined && axes.tags.length > 0) {\n    acc.config.tags = [...new Set([...(acc.config.tags ?? []), ...axes.tags])]\n    acc.layers.tags = layer\n  }\n  if (axes.modelPolicy !== undefined) {\n    acc.config.modelPolicy = composeModelPolicies(acc.config.modelPolicy, axes.modelPolicy)\n    acc.layers.modelPolicy = layer\n  }\n}\n\nexport function resolveSessionConfig(\n  input: ResolveSessionConfigInput,\n): SessionConfigResolution {\n  const presets = input.presets ?? []\n  const request = input.request ?? {}\n  const namedId = input.presetId\n  const namedPreset = namedId ? presets.find(preset => preset.id === namedId) : undefined\n  const harness = input.harness ?? request.harness ?? namedPreset?.harness\n\n  const acc: Accumulator = { config: {}, layers: {} }\n  applyLayer(acc, input.manifest, \"manifest\")\n  applyLayer(acc, input.host, \"host\")\n  applyLayer(acc, input.definition, \"definition\")\n\n  if (input.harnessPreset) {\n    applyLayer(\n      acc,\n      {\n        access: input.harnessPreset.access,\n        model: input.harnessPreset.model,\n        turnRetry: input.harnessPreset.turnRetry,\n      },\n      \"harness-preset\",\n    )\n  }\n\n  const defaultPreset = defaultPresetFor(harness, presets)\n  if (defaultPreset && defaultPreset.id !== namedId) {\n    for (const entry of presetChain(defaultPreset.id, presets)) {\n      applyLayer(acc, presetAxes(entry), `preset-default:${entry.id}`)\n    }\n  }\n\n  if (namedId) {\n    for (const entry of presetChain(namedId, presets)) {\n      applyLayer(acc, presetAxes(entry), `preset:${entry.id}`)\n    }\n  }\n\n  applyLayer(acc, request, \"request\")\n  return acc\n}\n","/**\n * User-owned spawn presets.\n *\n * This is deliberately separate from `preset-tools.ts`: provider presets are\n * static gateway definitions shipped by packages, while a UserPreset is a\n * private saved combination of the orthogonal session-config axes.\n */\n\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\nimport { z } from \"zod\"\nimport type {\n  ContextProfile,\n  EffortLevel,\n  Posture,\n  RouteSpec,\n  SessionConfig,\n} from \"./session-config.js\"\nimport type { SpawnBrowserMode } from \"./browser-mount.js\"\nimport type { SessionDescriptor } from \"./sessions.js\"\nimport { turnRetryInputSchema, type TurnRetryInput } from \"./turn-retry-policy.js\"\nimport { modelPolicyInputSchema, type ModelPolicy } from \"./model-policy.js\"\nimport {\n  defaultPresetFor,\n  presetChain,\n  SessionPresetResolutionError,\n} from \"./session-preset-resolver.js\"\n\nconst effortSchema = z.enum([\"low\", \"medium\", \"high\", \"xhigh\", \"max\", \"ultracode\"])\nconst postureSchema = z.union([\n  z.enum([\"default\", \"plan\", \"accept-edits\", \"bypass\", \"read-only\"]),\n  z.object({ harnessModeId: z.string().min(1) }),\n])\nconst routeSchema = z.object({\n  gateway: z.string().min(1),\n  baseUrl: z.string().url().optional(),\n})\n\n/** A reusable, user-scoped subset of the spawn/session config axes. */\nexport interface UserPreset extends Partial<SessionConfig> {\n  /** Stable machine-local id, e.g. `fast-deepseek`. */\n  id: string\n  /** Human-readable name shown by CLI and editor pickers. */\n  label: string\n  /** @deprecated Alias of `harness`, kept as a mirrored duplicate for old\n   *  readers; removed in the next major of @agentproto/runtime. */\n  adapter?: string\n  /** Harness to use (canonical). Omitted means the caller selects one. */\n  harness?: string\n  model?: string\n  route?: RouteSpec\n  access?: { profileRef?: string }\n  posture?: Posture\n  effort?: EffortLevel\n  contextProfile?: ContextProfile\n  /** Working directory the favorite pins to. When set, a spawn from this\n   *  preset lands here regardless of the caller's active folder — the axis\n   *  that makes a favorite fully location-pinned (true zero-input). Omitted\n   *  means the caller's cwd ladder resolves it as before. */\n  cwd?: string\n  /** Skills to preload for a spawn from this preset — the same axis as\n   *  `SpawnAgentSessionInput.skills`. Omitted means the adapter/defaults\n   *  decide. */\n  skills?: string[]\n  /** Capability bundle ids (`bundle_list`) for a spawn from this preset — the\n   *  same axis as `SpawnAgentSessionInput.bundles`. Omitted means the\n   *  adapter/defaults decide. */\n  bundles?: string[]\n  /** `agent_start.browser` for spawns from this preset. Ranks below the\n   *  role's own default (see `resolveBrowserMode`). */\n  browser?: SpawnBrowserMode\n  /** `agent_start.turnRetry` for spawns from this preset (opt-in retry of a\n   *  turn that failed on a transient provider error). An explicit\n   *  `turnRetry` on the spawn wins. */\n  turnRetry?: TurnRetryInput\n  /** Discovery tags; unioned with the request's when this preset resolves. */\n  tags?: string[]\n  /** Other session presets applied first, left to right. A missing target or\n   *  a cycle is rejected at save time. */\n  extends?: string[]\n  /** Harness slug this preset is the default for. At most one preset per\n   *  harness; a second one is rejected at save time. */\n  defaultFor?: string\n  /** This implementation's form of the AIP-38 policy (the preset's policy).\n   *  Composes with the request's: both apply. */\n  modelPolicy?: ModelPolicy\n  /** Harness-native options not covered by an axis; merged key by key. */\n  options?: Record<string, unknown>\n  /** Nested form of the same axes, accepted on input for AIP-46 callers. Flat\n   *  fields win when both name an axis. The store persists the flattened\n   *  form. */\n  config?: Partial<SessionConfig> & { options?: Record<string, unknown> }\n  /** ISO 8601 timestamp of the last spawn that resolved a `presetId` to this\n   *  preset (agent_start, `/sessions/agent`, `/sessions/chat` — stamped once\n   *  in `spawnAgentSession`, the shared core all three route through). Never\n   *  set by a caller directly; `saveUserPreset` preserves the existing value\n   *  across an edit unless the write explicitly overrides it. Absent for a\n   *  preset that has never been used to spawn. */\n  lastUsedAt?: string\n}\n\nconst presetConfigSchema = z.object({\n  harness: z.string().min(1).optional(),\n  model: z.string().min(1).optional(),\n  route: routeSchema.optional(),\n  access: z.object({ profileRef: z.string().min(1).optional() }).optional(),\n  posture: postureSchema.optional(),\n  effort: effortSchema.optional(),\n  contextProfile: z.string().min(1).optional(),\n  cwd: z.string().min(1).optional(),\n  skills: z.array(z.string().min(1)).optional(),\n  bundles: z.array(z.string().min(1)).optional(),\n  browser: z.union([z.literal(\"headless\"), z.literal(false)]).optional(),\n  options: z.record(z.string(), z.unknown()).optional(),\n  turnRetry: turnRetryInputSchema.optional(),\n})\n\nexport const userPresetSchema = z.object({\n  id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/),\n  label: z.string().min(1),\n  adapter: z\n    .string()\n    .min(1)\n    .optional()\n    .describe(\"Deprecated alias of `harness`; removed in the next major of @agentproto/runtime.\"),\n  harness: z.string().min(1).optional().describe(\"Harness slug this preset spawns.\"),\n  model: z.string().min(1).optional(),\n  route: routeSchema.optional(),\n  access: z.object({ profileRef: z.string().min(1).optional() }).optional(),\n  posture: postureSchema.optional(),\n  effort: effortSchema.optional(),\n  contextProfile: z.string().min(1).optional(),\n  cwd: z.string().min(1).optional(),\n  skills: z.array(z.string().min(1)).optional(),\n  bundles: z.array(z.string().min(1)).optional(),\n  browser: z.union([z.literal(\"headless\"), z.literal(false)]).optional(),\n  turnRetry: turnRetryInputSchema.optional(),\n  tags: z.array(z.string().min(1)).optional(),\n  extends: z.array(z.string().min(1)).optional(),\n  defaultFor: z.string().min(1).optional(),\n  modelPolicy: modelPolicyInputSchema.optional(),\n  options: z.record(z.string(), z.unknown()).optional(),\n  config: presetConfigSchema.optional(),\n  lastUsedAt: z.string().min(1).optional(),\n}) satisfies z.ZodType<UserPreset>\n\nconst userPresetsFileSchema = z.object({\n  version: z.literal(1),\n  presets: z.array(userPresetSchema),\n})\n\nexport type UserPresetsFile = {\n  version: 1\n  presets: UserPreset[]\n}\n\n/** A save-time invariant failure: a typed, actionable error rather than a\n *  generic parse message. */\nexport class UserPresetValidationError extends Error {\n  constructor(\n    readonly code: \"unknown_extends\" | \"extends_cycle\" | \"duplicate_default_for\",\n    message: string,\n  ) {\n    super(message)\n    this.name = \"UserPresetValidationError\"\n  }\n}\n\n/** Flatten the optional nested `config` under the flat fields. The flat field\n *  wins when both name an axis, per the AIP-46 migration note. */\nexport function normalizeUserPreset(input: UserPreset): UserPreset {\n  return mirrorPresetHarness(flattenPresetConfig(input))\n}\n\nfunction flattenPresetConfig(input: UserPreset): UserPreset {\n  if (!input.config) return input\n  const { config, ...flat } = input\n  const options =\n    config.options || flat.options\n      ? { ...(config.options ?? {}), ...(flat.options ?? {}) }\n      : undefined\n  return {\n    ...config,\n    ...flat,\n    ...(options ? { options } : {}),\n  } as UserPreset\n}\n\n/** `harness` is canonical: resolved as `harness ?? adapter`, then mirrored\n *  into the deprecated `adapter` so a reader of either key sees the same\n *  slug. A preset saved by an older daemon (only `adapter`) loads as such. */\nfunction mirrorPresetHarness(preset: UserPreset): UserPreset {\n  const harness = preset.harness ?? preset.adapter\n  if (!harness) return preset\n  return { ...preset, harness, adapter: harness }\n}\n\nfunction validateSessionPresets(presets: readonly UserPreset[]): void {\n  for (const preset of presets) {\n    try {\n      presetChain(preset.id, presets)\n    } catch (err) {\n      if (err instanceof SessionPresetResolutionError) {\n        throw new UserPresetValidationError(err.code, err.message)\n      }\n      throw err\n    }\n  }\n  const defaults = new Map<string, string>()\n  for (const preset of presets) {\n    if (!preset.defaultFor) continue\n    const existing = defaults.get(preset.defaultFor)\n    if (existing && existing !== preset.id) {\n      throw new UserPresetValidationError(\n        \"duplicate_default_for\",\n        `harness \"${preset.defaultFor}\" already has default session preset ` +\n          `\"${existing}\"; \"${preset.id}\" cannot be a second default`,\n      )\n    }\n    defaults.set(preset.defaultFor, preset.id)\n  }\n}\n\nfunction emptyFile(): UserPresetsFile {\n  return { version: 1, presets: [] }\n}\n\nexport function userPresetsPath(): string {\n  return resolve(homedir(), \".agentproto\", \"presets.json\")\n}\n\n/** Missing or malformed user config is treated as empty — a bad preset must\n * never prevent the daemon from starting. Writes always restore valid JSON. */\nexport async function loadUserPresets(): Promise<UserPresetsFile> {\n  try {\n    const parsed = userPresetsFileSchema.parse(JSON.parse(await readFile(userPresetsPath(), \"utf8\")))\n    return { version: 1, presets: parsed.presets.map(normalizeUserPreset) }\n  } catch {\n    return emptyFile()\n  }\n}\n\nasync function writeUserPresets(file: UserPresetsFile): Promise<void> {\n  const dir = join(homedir(), \".agentproto\")\n  await mkdir(dir, { recursive: true })\n  await writeFile(userPresetsPath(), JSON.stringify(file, null, 2) + \"\\n\", {\n    encoding: \"utf8\",\n    mode: 0o600,\n  })\n}\n\nexport async function listUserPresets(): Promise<UserPreset[]> {\n  return (await loadUserPresets()).presets\n}\n\nexport async function getUserPreset(id: string): Promise<UserPreset | undefined> {\n  return (await loadUserPresets()).presets.find(preset => preset.id === id)\n}\n\n/** Add or replace a preset by id. The parser makes this the single validation\n * boundary for CLI, MCP and editor callers. An edit that doesn't name its own\n * `lastUsedAt` keeps the existing preset's stamp rather than wiping it — a\n * rename/retune of a favorite must not erase its recency. */\nexport async function saveUserPreset(preset: UserPreset): Promise<void> {\n  const validated = normalizeUserPreset(userPresetSchema.parse(preset))\n  const file = await loadUserPresets()\n  const index = file.presets.findIndex(existing => existing.id === validated.id)\n  const lastUsedAt = validated.lastUsedAt ?? (index === -1 ? undefined : file.presets[index]?.lastUsedAt)\n  const next: UserPreset = { ...validated, ...(lastUsedAt ? { lastUsedAt } : {}) }\n  if (index === -1) file.presets.push(next)\n  else file.presets[index] = next\n  validateSessionPresets(file.presets)\n  await writeUserPresets(file)\n}\n\nexport async function deleteUserPreset(id: string): Promise<boolean> {\n  const file = await loadUserPresets()\n  const index = file.presets.findIndex(preset => preset.id === id)\n  if (index === -1) return false\n  for (const preset of file.presets) {\n    if (preset.id === id) continue\n    if ((preset.extends ?? []).includes(id)) {\n      throw new UserPresetValidationError(\n        \"unknown_extends\",\n        `cannot delete session preset \"${id}\" because \"${preset.id}\" extends it`,\n      )\n    }\n  }\n  file.presets.splice(index, 1)\n  await writeUserPresets(file)\n  return true\n}\n\n/** Stamp `lastUsedAt` on the preset a spawn just resolved `presetId` to.\n * Best-effort: an unknown id is a no-op, and a write failure here must never\n * fail the spawn it's timestamping — callers should await it inside a\n * `.catch(() => {})`. */\nexport async function touchUserPreset(id: string): Promise<void> {\n  const file = await loadUserPresets()\n  const index = file.presets.findIndex(preset => preset.id === id)\n  if (index === -1) return\n  file.presets[index] = { ...file.presets[index]!, lastUsedAt: new Date().toISOString() }\n  await writeUserPresets(file)\n}\n\n/** One de-duplicated recent spawn configuration, derived from session\n *  history rather than persisted — the `user_preset_list({ includeRecent:\n *  true })` / `GET /user-presets?includeRecent=1` companion view to actual\n *  favorites, so a caller can \"save as favorite\" something they've spawned\n *  before without retyping it. */\nexport interface RecentSpawnConfig {\n  /** Canonical harness slug. */\n  harness?: string\n  /** @deprecated Mirror of `harness`; removed in the next major of @agentproto/runtime. */\n  adapter?: string\n  model?: string\n  profileRef?: string\n  cwd?: string\n  /** Always true — the marker that distinguishes a derived row from a\n   *  persisted {@link UserPreset} when the two are rendered in one list. */\n  recent: true\n}\n\n/** Derive up to `limit` distinct recent spawn configurations (adapter,\n *  model, profileRef, cwd) from the registry's own newest-first session\n *  list. Only `agent-cli` sessions carry a spawn config; a session that\n *  named neither `harness` nor `adapterSlug` is skipped (nothing to offer\n *  as a favorite). Distinctness is by the exact (adapter, model, profileRef,\n *  cwd) tuple, keeping only the most recent occurrence of each. */\nexport function deriveRecentSpawnConfigs(\n  descriptors: readonly SessionDescriptor[],\n  limit = 5,\n): RecentSpawnConfig[] {\n  const seen = new Set<string>()\n  const out: RecentSpawnConfig[] = []\n  for (const desc of descriptors) {\n    if (out.length >= limit) break\n    if (desc.kind !== \"agent-cli\") continue\n    const adapter = desc.harness ?? desc.adapterSlug\n    if (!adapter) continue\n    const config: Omit<RecentSpawnConfig, \"recent\"> = {\n      harness: adapter,\n      adapter,\n      ...(desc.model ? { model: desc.model } : {}),\n      ...(desc.accessProfile?.profileRef ? { profileRef: desc.accessProfile.profileRef } : {}),\n      ...(desc.cwd ? { cwd: desc.cwd } : {}),\n    }\n    const key = JSON.stringify(config)\n    if (seen.has(key)) continue\n    seen.add(key)\n    out.push({ ...config, recent: true })\n  }\n  return out\n}\n"]}