# The dsh-tui bundle patch: the interactive terminal front door over the
# dsh-base layer. Applied after dsh-base's insert; rows here override base
# rows by id, with the profile's own cordis.patch.yml and any --patch
# overlays still to come.
#
# A patch replaces the targeted row's whole `config`, so each row below
# restates every key it owns (see the dsh-base patch for the shared
# defaults). The dsh-base core rows that need no dsh-tui value — tools,
# sandbox/approval policy, skills, goal, plan mode, workspace context,
# telemetry — are inherited unless this surface explicitly restates them.

# ── surface-specific values over the dsh-base layer ─────────────────────────

# The ChatCode CLI TUI persona; CHATCODE_CLI_TUI_PERSONA overrides the default
# default (the base persona is empty).
- id: system-prompt
  config:
    persona: !!js process.env.CHATCODE_CLI_TUI_PERSONA ?? process.env.DSH_TUI_PERSONA ?? 'You are ChatCode CLI, an AI coding agent.'

# Keep the DeepSeek adapter available for explicit user configuration, but
# replace its default four-model catalog with an empty list so those native
# entries do not appear in startup fallback, completion, or the /model picker.
- id: llm-deepseek
  config:
    models: []

# The base bundle starts a second model request on every new session solely to
# rewrite the fallback title. On single-flight/user-managed routes that helper
# can take the provider slot before the real agent request (observed as a
# 48-second first-token delay), and failed title calls add latency without ever
# improving the title. Keep the session-title service itself active so its
# deterministic first-prompt fallback and /rename continue to work; only the
# auxiliary LLM provider is disabled for the interactive TUI.
- id: session-title-llm
  disabled: true

# The TUI creates (or resumes) its agent at runtime through the agent
# factory; no declarative agents are started at boot, and the configured
# agent list stays the base's empty default.
- id: agent-loop
  config:
    agents: []

# Preserve the TUI's opt-in privacy stance across the 0.1.2 base default
# change to FEEDBACK_ONLY. An explicit DSH_TELEMETRY_MODE still wins. This
# restates the whole 0.1.2 config because include patches replace config
# objects rather than merging them.
- id: session-telemetry-otel
  config:
    mode: !!js process.env.DSH_TELEMETRY_MODE || 'DISABLED'
    shutdownTimeoutMillis: 3000
    exporter:
      url: !!js process.env.DSH_TELEMETRY_OTLP_URL ?? 'https://harness-telemetry.deepseeksvc.com/v1/logs'
      compression: gzip
      timeoutMillis: 1000
    processor:
      scheduledDelayMillis: 10000
      maxQueueSize: 2048
      maxExportBatchSize: 2048
      exportTimeoutMillis: 1500

# The 0.1.2 base sends the active Loader package inventory on official
# DeepSeek requests by default. TUI keeps that diagnostic metadata opt-in.
- id: plugin-package-inventory-deepseek
  config:
    enabled: false

# ── agent presets (issue #8) ────────────────────────────────────────────────
#
# The model-facing plugin set moves INTO the agent-presets roster: every
# session composes its tools/prompt sections from one preset directory
# (standard/ptc/minimal/cordis) instead of the host rows below. The TUI's
# roster row uses the scoped `dsh-tui-agent-presets` id. The 0.1.2 generation
# prepends its bundled system root; legacy 0.1.1-rc.2 still needs the dsh CLI's
# `config/agent-presets/` directory supplied explicitly. Both append
# `$DSH_HOME/.agent-presets`. Mirroring the official dsh-web-app patch: every
# dsh-base row a preset now owns is disabled here, so a minimal agent does not
# leak host-layer tools (an agent's registry view resolves agent → preset →
# global).

- id: agent-instructions
  disabled: true

- id: command-compact
  disabled: true

# compaction lives in the preset's own isolate realm (standard/ptc/cordis
# carry `compaction-basic` with package defaults; minimal has none). The
# CC_TUI_COMPACT_RATIO/CC_TUI_COMPACT_RETAIN tunables retired with this host
# row — preset compositions own their compaction config.
- id: compaction-basic
  disabled: true

- id: plan-mode
  disabled: true

- id: skill-filesystem
  disabled: true

- id: tool-bash
  disabled: true

- id: tool-fs
  disabled: true

- id: tool-fs-search
  disabled: true

- id: command-goal
  # Legacy rc.2 presets do not carry this command, so their host row must
  # remain active. Later legacy packages disable it only when their shipped
  # standard preset owns it. Starting in 0.1.7, the active declarative preset
  # registry owns the command instead; yield to that official row without
  # treating mere package availability as activation (the CLI profile may
  # resolve web packages that it does not mount).
  disabled: !!js >-
    (() => {
      const require = process.getBuiltinModule('node:module').createRequire(ctx.baseUrl)
      const fs = process.getBuiltinModule('node:fs')
      const path = process.getBuiltinModule('node:path')
      if ([...ctx.loader.entries()].some(entry => entry.options.id === 'agent-preset-registry' && entry.options.name === '@deepseek-ai/dsh-agent-preset-registry' && !entry.disabled)) {
        return true
      }
      try {
        const manifest = require.resolve('@deepseek-ai/dsh-agent-presets/package.json')
        const preset = path.join(path.dirname(manifest), 'presets', 'standard', 'agent.cordis.yml')
        return fs.readFileSync(preset, 'utf8')
          .split(/\r?\n/u)
          .some(line => line.trim() === '- id: command-goal')
      } catch {
        return false
      }
    })()

- id: tool-goal
  disabled: true

- id: tool-jobs
  disabled: true

- id: tool-pwsh
  disabled: true

- id: tool-ralph
  disabled: true

- id: tool-result-pruner
  disabled: true

- id: tool-skill
  disabled: true

# Delegation tools (subagent spawn/fork, controls, workflows) are preset rows
# now; the preset's `delegation` group re-adds them with package defaults, so
# the former TUI's depth-1 cap no longer applies.
- id: tool-subagent
  disabled: true

- id: tool-subagent-control
  disabled: true

- id: tool-subagent-fork
  disabled: true

- id: tool-subagent-list-agents
  disabled: true

- id: tool-todo
  disabled: true

- id: tool-web
  disabled: true

- id: tool-workflow
  disabled: true

- id: workflow-worker-thread
  disabled: true

# Windows has no sandbox confinement backend yet (sandbox-local's win32
# chain is empty); use danger-full-access on Windows so bash commands can
# run. Other platforms keep the base workspace-write default.
- id: sandbox-policy
  config:
    mode: !!js "process.platform === 'win32' ? 'danger-full-access' : ((process.env.CHATCODE_CLI_PERMISSION_MODE ?? process.env.DSH_PERMISSION_MODE) ?? 'workspace-write')"
    workspaceRoot: !!js process.cwd()

# On Windows, skip approval prompts (no sandbox = the user's terminal trust
# model, matching every other terminal coding agent).
- id: approval
  config:
    policy: !!js "process.platform === 'win32' ? 'never' : (((process.env.CHATCODE_CLI_PERMISSION_MODE ?? process.env.DSH_PERMISSION_MODE) ?? 'workspace-write') === 'danger-full-access' ? 'never' : 'ask')"

# Sessions live in the shared JSONL store under the resolved ChatCode CLI home — the same
# backend `chatcode-cli web` writes — so /resume here and the web session list see each
# other (#24). The row itself comes from the dsh-base layer; this override
# only re-points the root when a TUI session-root variable is set (test isolation).
- id: session-persistence-jsonl
  config:
    root: !!js process.env.CHATCODE_CLI_TUI_SESSION_ROOT ?? process.env.DSH_TUI_SESSION_ROOT ?? dshHomePath('sessions')

# ── dsh-tui rows ────────────────────────────────────────────────────────────

# The `user-interaction` service row comes from the dsh-base bundle layer
# (mounted before this layer); do not insert it again — the include patch
# semantics would create a duplicate row. dsh-tui defensively creates the
# service on its own context when no composition provides it (bare
# `dsh --config cordis.yml` boots), then mounts the model-facing
# ask_user_question tool. On legacy hosts it registers the TUI provider on
# `ctx.userQuestions`; on Alpha it answers the scoped
# `user-questions/request` waterfall.

- insert:
    # Workspace grouping is a separate durable ledger, not a cwd-derived
    # projection. Mount the same domain stack and storage root as dsh-web-app
    # so TUI-created sessions can attach to the exact registry Web reads.
    #
    # These rows own host-plane services that the official web-app bundle may
    # already mount. Loader entry ids are process-global, so these
    # rows use dsh-tui-* scoped ids and self-disable when an enabled row with
    # the official id/name is already present in the tree. The disabled check
    # is evaluated during the same include update that inserts every row, so
    # it sees the web-app rows regardless of their activation state.
    - id: dsh-tui-storage
      name: '@deepseek-ai/dsh-storage'
      disabled: !!js "[...ctx.loader.entries()].some(entry => entry.options.id === 'storage' && entry.options.name === '@deepseek-ai/dsh-storage' && !entry.disabled)"

    - id: dsh-tui-storage-json
      name: '@deepseek-ai/dsh-storage-json'
      disabled: !!js "[...ctx.loader.entries()].some(entry => entry.options.id === 'storage-json' && entry.options.name === '@deepseek-ai/dsh-storage-json' && !entry.disabled)"
      config:
        root: !!js dshHomePath('storages')

    - id: dsh-tui-storage-domain
      name: '@deepseek-ai/dsh-storage-domain'
      disabled: !!js "[...ctx.loader.entries()].some(entry => entry.options.id === 'storage-domain' && entry.options.name === '@deepseek-ai/dsh-storage-domain' && !entry.disabled)"
      config:
        backend: json

    # Alpha moved the durable storage stack into dsh-base, so these three
    # scoped copies self-disable there. Keep them for the validated rc lines,
    # whose base layer does not provide the stack to a TUI-only profile.

    - id: dsh-tui-workspace
      name: '@deepseek-ai/dsh-workspace'
      disabled: !!js "[...ctx.loader.entries()].some(entry => entry.options.id === 'workspace' && entry.options.name === '@deepseek-ai/dsh-workspace' && !entry.disabled)"

    # Legacy PTC presentation waits on this Host service. 0.1.6-alpha.2
    # retired the package in favor of dsh-ptc-runtime-node/workflow-ptc, so
    # probe the package before Loader attempts the import. The scoped row
    # still supports old TUI-only profiles and yields to an official row.
    - id: dsh-tui-code-runtime
      name: '@deepseek-ai/dsh-code-runtime-worker-thread'
      disabled: !!js >-
        (() => {
          const require = process.getBuiltinModule('node:module').createRequire(ctx.baseUrl)
          try {
            require.resolve('@deepseek-ai/dsh-code-runtime-worker-thread')
          } catch {
            return true
          }
          return [...ctx.loader.entries()].some(entry => entry.options.id === 'code-runtime' && entry.options.name === '@deepseek-ai/dsh-code-runtime-worker-thread' && !entry.disabled)
        })()

    # 0.1.2 presets opt their delegation tool into Host-owned model-selection
    # settings. Without this service standard/ptc/cordis preset mounting fails.
    # The package subpath does not exist on rc.2, so resolve that capability
    # directly before Loader attempts the import. An enabled official row still
    # owns the seat in mixed profiles.
    - id: dsh-tui-subagent-model-selection-settings
      name: '@deepseek-ai/dsh-tool-subagent/model-selection-settings'
      disabled: !!js >-
        (() => {
          const require = process.getBuiltinModule('node:module').createRequire(ctx.baseUrl)
          try {
            require.resolve('@deepseek-ai/dsh-tool-subagent/model-selection-settings')
          } catch {
            return true
          }
          return [...ctx.loader.entries()].some(entry => entry.options.id === 'subagent-model-selection-settings' && entry.options.name === '@deepseek-ai/dsh-tool-subagent/model-selection-settings' && !entry.disabled)
        })()

    # Whole-session timings and decode totals are an official projection.
    # dsh-base owns session-projection; Web normally adds this consumer, so a
    # TUI-only profile supplies a scoped copy and yields in mixed profiles.
    - id: dsh-tui-session-stats
      name: '@deepseek-ai/dsh-session-stats'
      disabled: !!js "[...ctx.loader.entries()].some(entry => entry.options.id === 'session-stats' && entry.options.name === '@deepseek-ai/dsh-session-stats' && !entry.disabled)"

    # Generic terminal workspace registry. Optional plugins add providers;
    # the TUI itself always supplies LOCAL and has no provider-specific code.
    - id: dsh-tui-workspaces
      name: '@chatcode/cco-tui/workspaces'

    # Optional plugins contribute nested slash-command completion here;
    # execution and durable command events remain owned by dsh-commands.
    - id: dsh-tui-command-trees
      name: '@chatcode/cco-tui/command-trees'
    # Optional plugins declare editable settings sections here (issue #165);
    # storage, validation and writes remain owned by the dsh settings service.
    - id: dsh-tui-settings-sections
      name: '@chatcode/cco-tui/settings-sections'

    # Optional plugins register full-screen scenes (trajectory-style whole-
    # terminal views) here and open them from their own command handlers;
    # rendering and input ownership remain owned by the TUI's Chat screen.
    - id: dsh-tui-scenes
      name: '@chatcode/cco-tui/scenes'

    # Plugin-interop anchor (Community Consensus v0.15): the unified grant
    # store, runtime generation id, and Host Descriptor live here; later
    # contract surfaces (plugin storage, message observation, effect
    # ledger) mount off THIS row's apply, so the patch surface changes only
    # once for the whole alignment. Mounted ahead of the extensions row and
    # any third-party plugin row.
    - id: dsh-tui-plugin-host
      name: '@chatcode/cco-tui/plugin-host'

    # Plugin-facing UI seams (the pi-style extension surface): managed
    # dialogs (select/confirm/input), keyed status-line contributions,
    # keyboard shortcuts, and custom session-entry text renderers. The
    # decision events (tui/input, tui/rewind-prompt, tui/session-switch,
    # tui/compact, …) are fired by the channel on the cordis bus directly
    # and need no row.
    - id: dsh-tui-extensions
      name: '@chatcode/cco-tui/extensions'

    # The agent-preset roster (issue #8): `ctx.agentPresets`, the service the
    # TUI composes every session's model-facing world from. 0.1.2 packages
    # prepend their bundled presets as the read-only system root; legacy rc.2
    # packages have no bundled root and still scan the dsh CLI directory. Both append
    # `$DSH_HOME/.agent-presets` as the user root. Deployment-added roots may
    # still be supplied by a later patch.
    - id: dsh-tui-agent-presets
      name: '@deepseek-ai/dsh-agent-presets'
      disabled: !!js "[...ctx.loader.entries()].some(entry => entry.options.id === 'agent-presets' && entry.options.name === '@deepseek-ai/dsh-agent-presets' && !entry.disabled)"
      config: !!js >-
        (() => {
          const require = process.getBuiltinModule('node:module').createRequire(ctx.baseUrl)
          const fs = process.getBuiltinModule('node:fs')
          const path = process.getBuiltinModule('node:path')
          try {
            const manifest = require.resolve('@deepseek-ai/dsh-agent-presets/package.json')
            if (fs.existsSync(path.join(path.dirname(manifest), 'presets'))) {
              return { default: 'standard' }
            }
          } catch {
            // Let the roster import report a missing package; preserve the rc
            // root fallback below for every package generation without one.
          }
          const base = ctx.baseUrl
          if (!base) return { default: 'standard' }
          const root = new URL('../node_modules/@deepseek-ai/dsh/config/agent-presets/', base)
          let rootPath = decodeURIComponent(root.pathname)
          if (/^\/[A-Za-z]:/.test(rootPath)) rootPath = rootPath.slice(1)
          return { default: 'standard', roots: [{ path: rootPath, trust: 'system' }] }
        })()

    # Host-plane services the `cordis` preset's plugin-experimentation tool
    # waits on (dynamicCordisRunner/cordisInspect); dsh-base carries no such
    # row — the official web app inserts it the same way, so this copy yields
    # to it when it is already present.
    - id: dsh-tui-cordis-host-runner
      name: '@deepseek-ai/dsh-cordis-host-runner'
      disabled: !!js "[...ctx.loader.entries()].some(entry => entry.options.id === 'cordis-host-runner' && entry.options.name === '@deepseek-ai/dsh-cordis-host-runner' && !entry.disabled)"

    # The interactive front door. The plugin creates/resumes its agent at
    # runtime, seeds the startup status line, and disposes the whole app tree
    # (exiting the process) when the TUI unmounts. `dsh-tui --resume`
    # feeds the session id through CHATCODE_CLI_TUI_RESUME_SESSION; legacy
    # DSH_TUI_RESUME_SESSION and DSH_CC_RESUME_SESSION remain read inputs.
    - id: dsh-tui
      name: '@chatcode/cco-tui'
      # The entry-level dependency augments the plugin's `agents` inject and
      # prevents startup Session creation from racing WorkspaceRegistry init.
      inject: [workspaceRegistry, agents, tuiWorkspaces, tuiScenes, tuiDialogs, tuiStatus, tuiShortcuts, tuiRenderers, tuiThemes]
      # `tuiWorkspaces`/`tuiScenes` (and the dsh-tui-extensions services,
      # including `tuiThemes`)
      # live in the entry-level inject ONLY as an ordering (and reload-rebind)
      # guarantee alongside their service rows
      # above — they are deliberately absent from the plugin's code-level
      # inject (issue #183): the dsh CLI may read this patch from an older
      # copy of the package than the plugin module it loads, and a hard
      # code-level inject then deadlocks the tree at boot ("pending (waiting
      # for service: tuiWorkspaces)"). Without the rows the TUI degrades:
      # /workspace falls back to the local-only runtime, plugin scenes never
      # open. (The comment sits below the inject line:
      # verify-workspace-attachment.mjs asserts the name→inject distance.)
      config:
        # Alt-screen fullscreen（CC 同款）：应用内鼠标选区（选择即复制, OSC 52 +
        # wl-copy/xclip/xsel 兜底）、滚轮滚动、双击选词/三击选行。出厂默认开启，
        # 与 schema 默认（index.ts fullscreen default true）保持一致——两处必须
        # 同步翻转，否则本覆盖层会盖住 schema 默认，更新后用户仍落在 inline。
        # 想退回 inline 主屏（终端原生滚动/选择）：/settings 全屏开关或 cordis.yml
        # `fullscreen: false`——显式选择始终优先于默认。
        fullscreen: true
        # Edit/Write diff 呈现：auto（≥110 列双栏对照，窄屏统一式）/
        # split（强制双栏）/ unified（强制统一式）。/settings 屏可实时改。
        # diffLayout: auto
        # Shift+Tab session-mode cycle (array order IS the cycle order;
        # absent → the built-in default/plan/full trio below). Each entry
        # may declare any subset of the plan (on/off), sandbox (read-only/
        # workspace-write/danger-full-access), and approval (ask/never)
        # atoms; undeclared atoms are untouched. Entry index 0 is the
        # unmarked base mode.
        # modes:
        #   - id: default
        #     plan: false
        #     sandbox: workspace-write
        #     approval: ask
        #   - id: plan
        #     plan: true
        #     sandbox: read-only
        #     approval: ask
        #   - id: full
        #     plan: false
        #     sandbox: danger-full-access
        #     approval: never
        # Static preset choice (CHATCODE_CLI_TUI_PRESET overrides): wins over the
        # persisted `/preset` preference below `<CHATCODE_CLI_HOME>/tui`, which
        # wins over the roster default (standard).
        preset: !!js process.env.CHATCODE_CLI_TUI_PRESET ?? process.env.DSH_TUI_PRESET ?? undefined
        workspace: !!js process.env.CHATCODE_CLI_TUI_WORKSPACE_TARGET ?? process.env.DSH_TUI_WORKSPACE_TARGET ?? undefined
        sessionId: !!js process.env.CHATCODE_CLI_TUI_RESUME_SESSION ?? process.env.DSH_TUI_RESUME_SESSION ?? process.env.DSH_CC_RESUME_SESSION ?? undefined

    # Live working-line data source (thinking copy / running tool / turn
    # summary). Mounted through @chatcode/cco-tui's own
    # `./working-activity` re-export, NOT the bare `dsh-working-activity`
    # name: the dsh Loader resolves row names from the profile directory,
    # and pnpm's isolated node_modules layout never links a transitive
    # dependency into the profile root (npm's flat layout hid this), so the
    # bare name died with ERR_MODULE_NOT_FOUND and disposed the whole app at
    # boot (#60).
    # The plugin stays mounted for its narration/system-prompt features. The
    # TUI derives its working line in-process from the base session stream;
    # never persist activity/status, so the shared log remains Web-readable.
    - id: working-activity
      name: '@chatcode/cco-tui/working-activity'
      config:
        publish: false
        publishIntervalMs: 500
