Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

181 KB
Raw Blame
import type { OrgChannelNoticeKind, StorageCandidateRule, StorageClass } from "@adelie/server/api";

/**
 * CLI text internationalization (i18n).
 *
 * Language comes from the `ADELIE_LANG` env var (`en` / `zh`), defaulting to English (en) —
 * independent of Project config or CLI options. This module centralizes all user-visible text:
 * command/option help descriptions and runtime output, one implementation per language.
 */

/** UI language. */
export type Language = "en" | "zh";

/** Installer locations are localized at the message boundary, not embedded in update logic. */
export type InstallerSource = "configured" | "github";

/** Readiness probe failure classes; selects which hint `webProbeFailed` appends. */
export type WebProbeFailureKind =
  "timeout" | "refused" | "reset" | "permission" | "dns" | "unknown";

/** Resolve the language from the env var; `zh` matches exactly, everything else falls back to English (see comment #2). */
export function resolveLanguage(): Language {
  const v = (process.env.ADELIE_LANG ?? "").trim().toLowerCase();
  return v === "zh" ? "zh" : "en";
}

export interface Messages {
  // —— Command/option help descriptions ——
  cliDescription: string;
  versionDesc: string;
  common: {
    projectId: string;
    agentId: string;
    modelId: string;
    /** run/chat's --provider: must be given together with --model-id (the group is never inferred). */
    provider: string;
    /** Data root directory option (priority: --root > ADELIE_HOME > ~/.adelie/data). */
    root: string;
    workspace: string;
    approve: string;
    /** run/chat's --thinking: the session's thinking level (selectable tiers only, mirrors the web picker). */
    thinking: string;
    /** Machine-readable output (raw JSON instead of the rendered/tabular form). */
    json: string;
    /** --server: explicit server URL (overrides ADELIE_API_URL, the local lock and auto-start). */
    server: string;
    /** --timeout: soft-yield wait budget on run/input/logs -f (30s / 5m / 2h / bare seconds). */
    timeout: string;
    /** input/logs' --agent-id: whose most recent session the omitted session argument means. */
    latestAgentId: string;
  };
  /** Commander's own parse failures, rebuilt in the user's language (see usage-error.ts). */
  usage: {
    /** A required positional argument was not given. */
    missingArgument(name: string): string;
    /** A required option (commander's requiredOption) was not given. */
    missingOption(flags: string): string;
    /** An option that takes a value was given none. */
    optionMissingArgument(flags: string): string;
    unknownOption(flag: string): string;
    unknownCommand(name: string): string;
    /** Everything else commander rejects: its own detail rides verbatim, so nothing is swallowed. */
    other(detail: string): string;
    /** Second line of a usage error: how the command is spelled, and where its full option list is. */
    hint(command: string, usage: string): string;
  };
  config: {
    desc: string;
    modelDesc: string;
    addDesc: string;
    addModelId: string;
    addProvider: string;
    addApiKey: string;
    addBaseUrl: string;
    addContextWindow: string;
    addMaxTokens: string;
    addClientType: string;
    addVision: string;
    addNoVision: string;
    addFastMode: string;
    addNoFastMode: string;
    fastModeUnsupported: (ref: string) => string;
    addPriceCacheRead: string;
    addPriceCacheWrite: string;
    addPriceOutput: string;
    addSetDefault: string;
    defaultDesc: string;
    visionDesc: string;
    /** `model default` / `model vision` / `model remove`'s --model-id: the upstream request id (pairs with --provider as a reference). */
    refModelId: string;
    /** `model default` / `model vision` / `model remove`'s --provider: the provider group of the referenced entry (required). */
    refProvider: string;
    listDesc: string;
    removeDesc: string;
    langDesc: string;
    langArg: string;
    vaultDesc: string;
    vaultSetDesc: string;
    vaultListDesc: string;
    vaultRemoveDesc: string;
    vaultKey: string;
    vaultValue: string;
  };
  run: {
    desc: string;
    message: string;
    /** run's --goal: goal mode, with an optional token budget value (`--goal 500k`). */
    goal: string;
    /** run's --session: reuse an existing Session (full id or unique fragment). */
    session: string;
    /** run's --background: POST the task and exit immediately, printing the session id. */
    background: string;
    /** --session combined with --workspace / the model pair: both fixed at creation. */
    sessionNoOverride(): string;
    /** The retired --source given a value other than `benchmark`. Removed at 0.3.0 with the flag. */
    sourceInvalid(value: string): string;
    /** The retired `--source benchmark`, accepted as a no-op until 0.3.0: why it is ignored. */
    sourceIgnored(): string;
    /** --background never waits, so a wait budget cannot apply to it. */
    timeoutWithBackground(): string;
  };
  chat: {
    desc: string;
    resume: string;
    /** chat's --verbose: start with full tool output (collapsing off). */
    verbose: string;
  };
  /** `penguin ls`: session listing. */
  ls: {
    desc: string;
    /** -a/--all: include archived sessions. */
    all: string;
    /** --days: keep sessions last active within the trailing n calendar days (today = day 1). */
    days: string;
    daysInvalid(value: string): string;
    empty(projectId: string): string;
    colId(): string;
    colAgent(): string;
    colTitle(): string;
    colState(): string;
    colLast(): string;
    colWorkspace(): string;
    stateIdle(): string;
    stateRunning(): string;
  };
  /** `penguin input`: send a message into an existing session (steer when running, task when idle). */
  input: {
    desc: string;
    message: string;
    /** Poll form on a session that has produced no assistant text yet. */
    noReplyYet(): string;
  };
  /** `penguin logs`: render a session's history, optionally following the live stream. */
  logs: {
    desc: string;
    tail: string;
    follow: string;
    tailInvalid(value: string): string;
    /** --timeout without -f: there is no wait to bound. */
    timeoutNeedsFollow(): string;
  };
  /** `penguin agent`: agent listing and creation. */
  agent: {
    desc: string;
    lsDesc: string;
    createDesc: string;
    createId: string;
    createName: string;
    createDescription: string;
    /** --plugins: comma-separated library plugin names to seed the new agent with. */
    createPlugins: string;
    created(agentId: string, projectId: string): string;
    colId(): string;
    colName(): string;
    colSessions(): string;
    colDescription(): string;
    /** `penguin agent api …`: an agent's public API (this server's switches, approval mode and keys). */
    apiDesc: string;
    apiStatusDesc: string;
    apiEnableDesc: string;
    apiDisableDesc: string;
    apiSetDesc: string;
    /** --open / --no-open: keyless access on or off. */
    apiOpen: string;
    apiNoOpen: string;
    /** --approve on enable/set: the mode API conversations are created with. */
    apiApprove: string;
    /** `set` given nothing to change. */
    apiNothingToSet(): string;
    apiKeysDesc: string;
    apiKeysLsDesc: string;
    apiKeysCreateDesc: string;
    apiKeysRmDesc: string;
    /** --name of `keys create`. */
    apiKeyName: string;
    apiServerDesc: string;
    /** `server <state>` given something other than on/off. */
    apiServerStateInvalid(value: string): string;
    /** The status block: its heading, then one labelled line per fact. */
    apiStatusTitle(agentRef: string): string;
    apiFieldEnabled(): string;
    apiFieldOpen(): string;
    apiFieldApproval(): string;
    apiFieldBaseUrl(): string;
    apiFieldAgentId(): string;
    apiFieldKeys(): string;
    apiFieldServer(): string;
    apiYes(): string;
    apiNo(): string;
    apiServerOn(): string;
    apiServerOff(): string;
    /** `keys ls` columns, and the line for an agent with none. */
    apiColKeyId(): string;
    apiColKeyName(): string;
    apiColPrefix(): string;
    apiColCreated(): string;
    apiColLastUsed(): string;
    apiKeyNever(): string;
    apiKeysEmpty(agentRef: string): string;
    /** stderr beside the bare secret on stdout. */
    apiKeyCreated(name: string, prefix: string, agentRef: string): string;
    apiKeyDeleted(keyId: string, agentRef: string): string;
    /** After `server on|off`. */
    apiServerSet(on: boolean): string;
    /** A write refused 403 human_required: it carried the local API token, and no stored sign-in stood in. */
    apiSignInRequired(): string;
    /** On stderr after `--open` switched keyless access on. */
    apiOpenWarning(): string;
  };
  /** `penguin project`: project listing. */
  project: {
    desc: string;
    lsDesc: string;
    colId(): string;
    colName(): string;
    colRole(): string;
  };
  /** `penguin cost`: token/cost aggregates. */
  cost: {
    desc: string;
    days: string;
    from: string;
    to: string;
    by: string;
    rangeIncomplete(): string;
    daysInvalid(value: string): string;
    byInvalid(value: string): string;
    today(): string;
    last7d(): string;
    total(): string;
    empty(): string;
    /** Cost cell when no model in the bucket has pricing configured. */
    noPricing(): string;
    colTokens(): string;
    colRequests(): string;
    colCost(): string;
    colGroup(dimension: string): string;
  };
  /**
   * `penguin storage`: the data root's storage ledger. Report-only text — there is no
   * message here for a deletion, because this command has no way to cause one.
   */
  storage: {
    desc: string;
    top: string;
    topInvalid(value: string): string;
    /** Header: the data root, what the ledger accounts for, and the volume when it is known. */
    heading(
      root: string,
      total: string,
      disk: { free: string; total: string; usedPercent: string } | null,
    ): string;
    /** Below the low-free threshold; says what to do (read the list) and what will not happen (nothing acts). */
    lowFree(free: string): string;
    colClass(): string;
    colBytes(): string;
    colFiles(): string;
    colEntries(): string;
    colCandidates(): string;
    candidateCell(entries: number, bytes: string): string;
    candidatesHeading(): string;
    candidatesEmpty(): string;
    colModified(): string;
    colRules(): string;
    colPath(): string;
    moreCandidates(n: number): string;
    /** One sentence per class about what clearing it would cost, before anyone picks. */
    candidateCosts(): string;
    unknownDate(): string;
    groupsHeading(): string;
    groupKind(kind: "name" | "structure"): string;
    groupLine(kind: string, key: string, members: number, bytes: string): string;
    unreadableHeading(): string;
    /** Closing sentence of the bare report when the cleanup mode is off. */
    modeOffNotice(): string;
    /** Closing sentence of the bare report when the mode is on: what the next step is. */
    modeOnNotice(): string;
    className(key: StorageClass): string;
    ruleLabel(rule: StorageCandidateRule): string;
    // ── the reviewed cleanup: scan → plan → apply → trash, and the mode switch ──
    scanDesc: string;
    planDesc: string;
    applyDesc: string;
    applyPath: string;
    applyAll: string;
    applyNoSelection(): string;
    applyNothing(): string;
    applyMoved(moved: number, bytes: string, trashId: string): string;
    applyFailedLine(path: string, reason: string): string;
    /** The `trash` group itself: what a trash is for, in one line. */
    trashDesc: string;
    /** `trash list` (the group's default): the entries a person can restore or purge. */
    trashListDesc: string;
    trashRestoreDesc: string;
    trashPurgeDesc: string;
    trashEmpty(): string;
    trashRestored(id: string, restored: number, remaining: boolean): string;
    trashSkippedLine(path: string, reason: string): string;
    trashPurgeNothing(): string;
    trashPurgedLine(id: string, bytes: string): string;
    /** Days a trash entry is kept; the retention the server reports beside the list. */
    trashTtlDays(days: number): string;
    /** Cell of a trash row that is past the retention and may be purged. */
    expired(ttl: string): string;
    modeDesc: string;
    modeUsage(): string;
    modeIs(enabled: boolean, ttlDays: number, pins: number): string;
    modeSet(enabled: boolean, ttlDays: number, pins: number): string;
    billHeading(id: string, entries: number, bytes: string, expires: string): string;
    billEmpty(): string;
    billExcluded(n: number): string;
    billReportOnly(classes: string[]): string;
    billNotice(id: string): string;
    billSpent(id: string): string;
    /** Mark in the bill's table for an entry this version only reports. */
    reportOnlyMark(): string;
    /** Mark in the bill's table for an entry an apply would accept. */
    moveMark(): string;
    plansEmpty(): string;
    planStateOpen(): string;
    planStateApplied(at: string): string;
    planStateExpired(at: string): string;
    colExecutable(): string;
    colPlanId(): string;
    colCreated(): string;
    colState(): string;
    colTrashId(): string;
    colItems(): string;
    colExpired(): string;
  };
  /** `penguin schedule`: scheduled-task listing and management (a validated writer over the schedules API; the TOML file stays the single source of truth). */
  schedule: {
    desc: string;
    lsDesc: string;
    addDesc: string;
    updateDesc: string;
    rmDesc: string;
    /** --prompt: the text the firing sends. */
    prompt: string;
    /** --start-at: first fire time, ISO 8601 — or the literal `now` for the current instant (a one-shot needs a future time, so `now` only suits a periodic task). */
    startAt: string;
    /** --period: fixed interval (30m / 12h / 1d / 7d, minimum 5m); omitted = one-shot. */
    period: string;
    /** --end-at: stop firing after this instant (ISO 8601). */
    endAt: string;
    /** --session-id: bind firings to one session (excludes the new-session form). */
    sessionId: string;
    /** --workspace: new-session mode's workspace (omitted = a temp workspace per firing). */
    workspace: string;
    /** add's --disabled: opt out of the CLI's enabled-by-default divergence. */
    disabledOpt: string;
    /** update's --enable / --disable pair. */
    enableOpt: string;
    disableOpt: string;
    enableDisableConflict(): string;
    /** --session-id given together with the new-session form: the target is one or the other. */
    targetConflict(): string;
    /** Confirmation after add/update; nextFireAt is absent for done/disabled/invalid tasks. */
    written(name: string, enabledText: string, nextFireAt: string | undefined): string;
    removed(name: string): string;
    enabled(): string;
    disabled(): string;
    /** Period column for a one-off task (no period configured). */
    oneShot(): string;
    /** Target column when the schedule creates a new session each firing. */
    newSession(): string;
    empty(projectId: string): string;
    colName(): string;
    colEnabled(): string;
    colStartAt(): string;
    colPeriod(): string;
    colTarget(): string;
    colLastFired(): string;
    colStatus(): string;
  };
  /** `penguin org`: company mode — a thin client over the organization API (the organization's files stay the single source of truth; every DTO is a projection). */
  org: {
    desc: string;
    lsDesc: string;
    createDesc: string;
    showDesc: string;
    chartDesc: string;
    hireDesc: string;
    employeeDesc: string;
    employeeSetDesc: string;
    leaveDesc: string;
    deskDesc: string;
    deskShowDesc: string;
    deskRenewDesc: string;
    calendarDesc: string;
    calendarLsDesc: string;
    calendarAddDesc: string;
    calendarUpdateDesc: string;
    calendarRmDesc: string;
    ticketDesc: string;
    ticketLsDesc: string;
    ticketShowDesc: string;
    ticketCreateDesc: string;
    ticketMoveDesc: string;
    ticketAssignDesc: string;
    ticketBlockDesc: string;
    ticketUnblockDesc: string;
    ticketProgressDesc: string;
    ticketStartDesc: string;
    ticketAttachDesc: string;
    channelDesc: string;
    channelLsDesc: string;
    channelCreateDesc: string;
    channelShowDesc: string;
    channelInviteDesc: string;
    channelJoinDesc: string;
    channelLeaveDesc: string;
    channelRemoveDesc: string;
    channelArchiveDesc: string;
    channelUnarchiveDesc: string;
    channelTailDesc: string;
    channelSendDesc: string;
    handbookDesc: string;
    handbookListDesc: string;
    handbookShowDesc: string;
    handbookWriteDesc: string;
    handbookRmDesc: string;
    financeDesc: string;
    /** --org-id: the organization (defaults to ADELIE_ORG_ID, the control environment of desk and ticket sessions). */
    orgId: string;
    /** create's --org-id: the id to create (never taken from the environment). */
    newOrgId: string;
    mission: string;
    orgName: string;
    /** create's --language: the organization's working language (default: detected from the mission). */
    orgLanguageOption: string;
    /** hire's --agent-id: employ an existing Agent (XOR --new-agent). */
    hireAgentId: string;
    /** hire's --new-agent: create the Agent and employ it. */
    newAgent: string;
    newAgentName: string;
    newAgentDescription: string;
    /** --skills: extra library plugins for the new Agent, comma-separated (added to the required pair). */
    skills: string;
    title: string;
    reportsTo: string;
    /** Employee workspace: a sub-directory of the shared workspace (`.` = all of it) or an absolute path, written as given. */
    employeeWorkspace: string;
    /** hire's --workspace: the same spec, with the default the employee's own sub-directory. */
    hireWorkspace: string;
    /** --budget: monthly USD for the employee plus every subordinate. */
    budget: string;
    /** create's --ceo-budget: the CEO's monthly USD, which is the whole company's. */
    ceoBudget: string;
    duties: string;
    /** calendar's --agent-id: the employee the event belongs to (defaults to ADELIE_AGENT_ID); a filter on `ls`. */
    calendarAgentId: string;
    calendarTitle: string;
    /** ticket ls filters. */
    statusFilter: string;
    ownerFilter: string;
    blockedFilter: string;
    ticketTitle: string;
    /** create's --slug: the words of the ticket id, for a title that yields none. */
    ticketSlug: string;
    goal: string;
    criteria: string;
    /** --body-file: the whole Markdown body from a file (XOR --goal). */
    bodyFile: string;
    /** --owner: the ONE responsible principal; defaults to the caller on `create`. */
    owner: string;
    parent: string;
    /** --notify: principals told when the ticket ends, comma-separated. */
    notify: string;
    priority: string;
    due: string;
    /** move's --to: the target column. */
    moveTo: string;
    /** move's --reason: required when moving into rejected. */
    moveReason: string;
    blockReason: string;
    /** block's --by: who or which ticket the ticket waits for. */
    blockedBy: string;
    progressText: string;
    /** start's -m: a note appended to the ticket text the session opens with. */
    startMessage: string;
    /** start's --workspace: another directory inside the shared workspace (default: the employee's desk workspace). */
    startWorkspace: string;
    /** start's --agent-id: which employee the ticket session runs as (default: the caller inside a session, else the ticket's owner). */
    startAgentId: string;
    /** attach's --session: the session to attach (default: the calling session). */
    attachSession: string;
    /** tail / send's --channel: which channel to read or write in (default: the all-hands channel). */
    channelOpt: string;
    /** create's --name / --purpose. */
    channelName: string;
    channelPurpose: string;
    channelDate: string;
    channelCount: string;
    channelText: string;
    handbookPath: string;
    handbookText: string;
    handbookFile: string;
    handbookOneSource: string;
    refTicket: string;
    refSession: string;
    /** finance's --period: yyyy-mm (default: the current month). */
    period: string;
    /** No --org-id and no ADELIE_ORG_ID: there is no default organization. */
    orgIdMissing(): string;
    /** hire: --agent-id XOR --new-agent. */
    hireTargetConflict(): string;
    /** hire: --name / --description / --skills describe the new Agent only. */
    newAgentFieldsOnly(): string;
    /** A non-numeric or negative budget on any of the budget flags (named, since there are several). */
    budgetInvalid(flag: string, value: string): string;
    /** employee set with no field to change. */
    nothingToSet(): string;
    /** A --language value that is neither zh nor en. */
    languageInvalid(value: string): string;
    /** A --status / --to value that is not a kanban column. */
    statusInvalid(value: string): string;
    priorityInvalid(value: string): string;
    /** ticket create: --goal XOR --body-file. */
    ticketBodyConflict(): string;
    criteriaNeedsGoal(): string;
    bodyFileUnreadable(file: string): string;
    countInvalid(value: string): string;
    /** An id or handbook path with a `.` / `..` segment: the URL would collapse onto another route. */
    pathSegmentInvalid(value: string): string;
    /** ticket attach outside a session and without --session. */
    attachSessionMissing(): string;
    /** Confirmations of the write commands. */
    created(orgId: string, ceoDeskSessionId: string | undefined): string;
    hired(agentId: string, title: string, reportsTo: string | null): string;
    employeeUpdated(agentId: string): string;
    left(agentId: string): string;
    desk(
      agentId: string,
      sessionId: string,
      workspace: string,
      openedAt: string,
      created: boolean,
    ): string;
    deskRenewed(agentId: string, sessionId: string): string;
    calendarWritten(
      agentId: string,
      name: string,
      enabledText: string,
      nextFireAt: string | undefined,
    ): string;
    /** One advisory rota line the server answered a calendar write with (its text stays English). */
    calendarWarning(warning: string): string;
    calendarRemoved(agentId: string, name: string): string;
    ticketCreated(ticketId: string, status: string): string;
    ticketMoved(ticketId: string, status: string): string;
    ticketAssigned(ticketId: string, owner: string): string;
    ticketBlocked(ticketId: string): string;
    ticketUnblocked(ticketId: string): string;
    progressRecorded(ticketId: string): string;
    ticketAttached(ticketId: string, sessionId: string): string;
    channelCreated(channelId: string): string;
    channelInvited(channelId: string, principal: string): string;
    channelJoined(channelId: string): string;
    channelLeft(channelId: string): string;
    channelMemberRemoved(channelId: string, principal: string): string;
    channelArchived(channelId: string): string;
    channelUnarchived(channelId: string): string;
    messageSent(id: string): string;
    handbookWritten(path: string): string;
    handbookRemoved(path: string): string;
    /** Empty states. */
    empty(projectId: string): string;
    calendarEmpty(): string;
    ticketsEmpty(): string;
    channelsEmpty(): string;
    channelEmpty(channelId: string, date: string): string;
    /** `show`: one line per fact. */
    showHead(name: string, orgId: string, status: string): string;
    showMission(mission: string): string;
    showLanguage(language: string): string;
    showEmployees(count: number, running: number, paused: number): string;
    showBoard(counts: string, blocked: number): string;
    showSpend(period: string, spend: string): string;
    showPending(mentions: number, review: number, blockedByMe: number): string;
    /** An invalid organization / employee / ticket, with the reason (a line in `show`, a cell in tables). */
    invalid(reason: string): string;
    /** `ticket show`: the derived state above the file. */
    ticketHead(
      ticketId: string,
      status: string,
      running: boolean,
      blocked: string | undefined,
    ): string;
    ticketFigures(cost: string, rolledUp: string, sessions: number, children: number): string;
    /** `ticket show`: the labels of the ticket's frontmatter fields, above the prose sections. */
    ticketFields(): Record<
      | "title"
      | "owner"
      | "parent"
      | "notify"
      | "priority"
      | "due"
      | "blocked"
      | "blockedBy"
      | "sessions",
      string
    >;
    /** `ticket show`: the heading above the operation history; the actions themselves stay in English. */
    ticketHistory(): string;
    /**
     * A `system` line rendered from its structured notice, in the reader's language; a kind
     * this build does not know falls back to the message's English `text`.
     */
    notices: Record<OrgChannelNoticeKind, (p: Record<string, string>) => string>;
    /** The all-hands channel's label; its stored name is never shown. */
    allHands(): string;
    /** `channel tail` on any channel but the default one: a dim line naming it above the messages. */
    channelHeader(channelId: string): string;
    /** `channel show`: the head line, then the lines the channel actually has. */
    channelHead(name: string, channelId: string, members: number, archived: boolean): string;
    channelPurposeLine(purpose: string): string;
    channelCreatedBy(principal: string, createdAt: string): string;
    channelLastMessage(time: string): string;
    financeTotal(period: string, total: string): string;
    /** stderr note under `finance`: some usage had no pricing, so the total is a lower bound. */
    unpriced(): string;
    colEmployees(): string;
    colRunning(): string;
    colOpen(): string;
    colBlocked(): string;
    colSpend(): string;
    colNote(): string;
    /** Chart / finance: the employee's job title. */
    colJobTitle(): string;
    /** Tickets: the ticket title. */
    colTitle(): string;
    colState(): string;
    colOwn(): string;
    colCumulative(): string;
    colBudget(): string;
    colNext(): string;
    colPriority(): string;
    colOwner(): string;
    colTicket(): string;
    colRolledUp(): string;
    colMembers(): string;
    colArchived(): string;
    colUnread(): string;
    colMentions(): string;
    colPrincipal(): string;
  };
  /** `penguin browser`: the desktop app's built-in browser (commands/browser.ts, browser-output.ts). */
  browser: {
    desc: string;
    statusDesc: string;
    tabsDesc: string;
    openDesc: string;
    switchDesc: string;
    closeDesc: string;
    scanDesc: string;
    execDesc: string;
    clickDesc: string;
    typeDesc: string;
    screenshotDesc: string;
    cdpDesc: string;
    importDesc: string;
    historyDesc: string;
    /** --tab: which tab the command acts on. */
    tab: string;
    urlArg: string;
    newTab: string;
    tabIdArg: string;
    closeTabArg: string;
    textOnly: string;
    maxChars: string;
    scriptArg: string;
    file: string;
    save: string;
    noMonitor: string;
    timeout: string;
    selectorArg: string;
    index: string;
    at: string;
    textArg: string;
    selector: string;
    submit: string;
    /** exec / click / type --accept-dialogs: accept every dialog, not only alerts. */
    acceptDialogs: string;
    output: string;
    fullPage: string;
    methodArg: string;
    params: string;
    list: string;
    from: string;
    cookies: string;
    history: string;
    domain: string;
    queryArg: string;
    count: string;
    /** The labels of the output lines; `line` joins one with its value. */
    label: {
      status: string;
      tab: string;
      tabs: string;
      page: string;
      return: string;
      error: string;
      diff: string;
      transients: string;
      newTabs: string;
      note: string;
      clicked: string;
      source: string;
      cookies: string;
      history: string;
      warning: string;
      screenshot: string;
      dialog: string;
      memory: string;
    };
    /** `label: value`, in the language's punctuation. */
    line(label: string, value: string): string;
    /** The header naming a tab: `tab 12 · title · url`. */
    tabHead(id: number, title: string, url: string, loading: boolean): string;
    /** The value of `tabs:` when none is open. */
    noTabs(): string;
    available(): string;
    unavailable(reason: string): string;
    /** Why the browser cannot be driven, and what to do: it lives in the desktop app, which must be open. */
    unavailableHint(reason: string | undefined): string;
    /**
     * The value of `memory:`: what the browser's pages hold together and how many tabs, then this
     * computer's free and total memory when the server reports them.
     */
    memoryLine(total: string, tabs: number, system?: { free: string; total: string }): string;
    /** The `warning:` a load warning adds (the server's codes): what is wrong, and how an agent eases it. */
    loadWarning(warnings: readonly string[]): string;
    closed(tab: string): string;
    closedActive(): string;
    /** The value of `page:` when the page navigated or reloaded during the call. */
    reloaded(): string;
    elementsChanged(count: number): string;
    clickedAt(tag: string | undefined, text: string | undefined, x: number, y: number): string;
    /** The value of `dialog:`: the dialog and how the call answered it (a dismissal says how to accept). */
    dialogAnswered(type: string, message: string, accepted: boolean): string;
    /** Appended to a `return:` value cut at the display limit. */
    truncatedSave(): string;
    /** Appended to a `cdp` result cut at the display limit. */
    truncatedJson(): string;
    /** Appended to the start of a value `--save` wrote to a file. */
    savedTo(path: string): string;
    screenshotSaved(path: string, size: string, kilobytes: number): string;
    importData(cookies: boolean, history: boolean): string;
    importCookies(c: { found: number; imported: number; skipped: number; failed: number }): string;
    importHistory(h: { found: number; imported: number }): string;
    noSources(): string;
    noHistory(): string;
    /** A history line's visit count, the order the lines come in. */
    visits(count: number): string;
    colId(): string;
    colTitle(): string;
    colUrl(): string;
    colBrowser(): string;
    colProfile(): string;
    colData(): string;
    /** The one error line: `error: <code>: <message>`. */
    errorLine(code: string, message: string): string;
    tabInvalid(value: string): string;
    positiveInt(flag: string, value: string): string;
    indexInvalid(value: string): string;
    atInvalid(value: string): string;
    clickTarget(): string;
    newTabWithTab(): string;
    paramsInvalid(): string;
    methodInvalid(value: string): string;
    scriptSources(): string;
    scriptMissing(): string;
    scriptEmpty(): string;
    fileUnreadable(path: string, detail: string): string;
    fileUnwritable(path: string, detail: string): string;
    importMode(): string;
    sourceNotFound(from: string, known: string[]): string;
    sourceAmbiguous(from: string, ids: string[]): string;
  };
  /** Server-connection layer: resolution, auto-start, tokens, streams. */
  client: {
    invalidServerUrl(value: string): string;
    /** --server names a non-loopback URL and no ADELIE_API_TOKEN is set (the local token file must not travel). */
    remoteNeedsToken(url: string): string;
    /** No server reachable and auto-start was disabled by the caller. */
    noServer(): string;
    /** Auto-start impossible: the CLI entry is not plain-node runnable (tsx dev run). */
    autoStartUnavailable(): string;
    autoStartFailed(logPath: string): string;
    /** Printed to stderr when a server was auto-started for this invocation. */
    autoStarted(url: string, logPath: string): string;
    /** 401 with no token found anywhere (env or file). */
    noToken(url: string, tokenPath: string): string;
    /** 401 despite presenting a token. */
    authFailed(url: string): string;
    httpError(status: number, code: string, message: string): string;
    sessionNotFound(ref: string, projectId: string): string;
    sessionAmbiguous(ref: string, candidates: string[]): string;
    /** The SSE stream dropped and reconnecting gave up. */
    streamLost(detail: string): string;
    /** resync_required: the reconnect fell off the server's replay buffer (a display gap, not data loss). */
    streamResynced(): string;
    /** Invalid --timeout value (names the accepted shapes). */
    timeoutInvalid(value: string): string;
    /** Soft-yield detach: the wait budget expired, the task keeps running server-side. */
    stillRunning(shortId: string): string;
    /** Caller-context lookup failed (ADELIE_SESSION_ID names a session this server cannot answer for): plain defaults apply. */
    callerDefaultsFailed(sessionId: string): string;
    /** Dim stderr note naming the session a bare `logs` / `input` resolved to (the agent's most recent). */
    latestSession(sessionId: string): string;
    /** Bare `logs` / `input` when the agent has no session at all: what to run to get one. */
    noSessionsYet(agentId: string, projectId: string): string;
  };
  /** `/thinking` display when the Session pins no level: the Agent's configured default applies. */
  chatThinkingConfigured(): string;
  serve: {
    serverDesc: string;
    webDesc: string;
    port: string;
    host: string;
    noOpen: string;
    /** Printed by the supervising process as it relaunches the service on a restart request (the web UI's "restart to update"). */
    restarting: string;
    app: string;
  };
  /** `penguin server reset-admin-password`: help text and every line the command can print. */
  auth: {
    desc: string;
    loginDesc: string;
    statusDesc: string;
    logoutDesc: string;
    server: string;
    userId: string;
    password: string;
    print: string;
    accountPrompt(fallback: string): string;
    prompt(userId: string): string;
    emptyPassword: string;
    noServer(root: string): string;
    unreachable(server: string, detail: string): string;
    refused(status: number, detail: string): string;
    noCookie: string;
    loggedIn(userId: string, server: string, file: string): string;
    notLoggedIn(file: string): string;
    statusLine(userId: string, server: string): string;
    expires(when: string): string;
    expired(when: string): string;
    loggedOut(server: string): string;
    loggedOutLocally(server: string): string;
  };
  authToken: {
    desc: string;
    userId: string;
    ttlSeconds: string;
    mark: string;
    badTtl: string;
    noServer(root: string): string;
    failed(detail: string): string;
  };
  /** `penguin server status`: help text. */
  serverStatus: {
    /** One-line description in `penguin server --help`. */
    desc: string;
  };
  /** `penguin server stop`: help text. */
  serverStop: {
    desc: string;
  };
  resetPassword: {
    desc: string;
    /** Refusal while a live server owns the data root (stop it first, then retry). */
    serverRunning(url: string): string;
    /** The root has no Web database: nothing to reset. */
    noDatabase(dbPath: string): string;
    /** The database exists but the admin was never seeded. */
    noAdmin(): string;
    /** Success header, printed above the framed credentials notice. */
    done(root: string): string;
    /** Hint printed below the notice. */
    next(): string;
  };
  /** `penguin version`: help text only — the command's output is data, never prose. */
  version: {
    description: string;
    json: string;
  };
  /** `penguin update`: help text and every line the command can print. */
  update: {
    desc: string;
    check: string;
    releaseOpt: string;
    yes: string;
    /** `--check` header: the running version against the resolved target. */
    checkReport(current: string, latest: string): string;
    upgradeAvailable(target: string): string;
    upToDate(current: string): string;
    /** `--release` naming a release older than the running one: allowed, but said out loud. */
    targetIsOlder(target: string): string;
    /** Pre-confirmation plan for a tarball install (mechanism, target, install dir, data-dir guarantee). */
    planTarball(current: string, target: string, installDir: string, universal: boolean): string;
    /** Pre-confirmation plan for a global npm install. */
    planNpm(current: string, target: string, manager: string, command: string): string;
    confirm(): string;
    /** stdin is not a TTY: require --yes instead of blocking on a prompt nobody can answer. */
    needsYes(): string;
    cancelled(): string;
    done(version: string): string;
    failed(): string;
    /** Running from a source checkout: refuse, because overwriting a working tree destroys work. */
    sourceCheckout(): string;
    /** Bundled into the desktop app: refuse, because the app updates itself. */
    desktopApp(): string;
    unknownInstall(modulePath: string): string;
    /** A global install whose package manager could not be identified: print the command, never guess. */
    npmUnknownManager(globalRoot: string, target: string): string;
    /** Windows, tarball install: the official installer is a POSIX shell script. */
    windowsUnsupported(): string;
    /**
     * Windows, global install: `spawn` cannot run a `.cmd` shim without a shell, so hand the user
     * the exact command instead of failing generically.
     */
    windowsGlobalInstall(command: string): string;
    networkFailed(url: string): string;
    rateLimited(): string;
    apiFailed(status: number): string;
    apiMalformed(): string;
    invalidDownloadSource(): string;
    downloadBaseMustBeHttps(name: string): string;
    installerFetchFailed(sources: InstallerSource[]): string;
  };

  // —— Runtime output ——
  /** Startup banner: product + subcommand + CLI version on the first line, then Agent / Workspace / Model each on its own line. */
  header(
    kind: "chat" | "run",
    version: string,
    agentId: string,
    workspace: string,
    model: string,
  ): string;
  chatHints(): string;
  confirmExit(): string;
  taskInterrupted(): string;
  /** Acknowledgment printed when a line typed mid-run is queued as steering (echoes the text; delivered between turns). */
  steerQueued(text: string): string;
  /** Prefix for a rendered [user_steering] line (a mid-run user message delivered between turns). */
  steerLinePrefix(): string;
  error(message: string): string;
  /** Approval prompt text (the tool call is already streamed above and directly precedes this prompt, so no index and no re-rendering). */
  approvePrompt(): string;
  /**
   * Stats shown at the end of each Task: Session cumulative values plus this task's delta —
   * context window length, Token usage, elapsed time. Delta strings carry their own sign
   * (contextDelta can be negative after context is compacted), e.g.
   * `[stats] context 4k (+1k) · tokens 6k (+1.2k) · 5.1s (+2.3s)`.
   */
  taskStats(s: {
    context: string;
    contextDelta: string;
    tokens: string;
    tokensDelta: string;
    elapsed: string;
    elapsedDelta: string;
  }): string;
  /** Abort line (user interruptions only): the cause localizes from `errorCode`; `errorMessage` (raw, untranslatable) rides verbatim; a legacy Trace without a code renders its English `reason` prose as-is. */
  abortLabel(abort?: { errorCode?: string; errorMessage?: string; reason?: string }): string;
  /** Run-ending LLM failure (request_end status fatal — no abort event follows); the provider's error text rides verbatim. */
  llmFatalLabel(errorMessage?: string): string;
  /** The retry ladder gave up (request_end `retryable` with no planned retry); `attempt` is the final attempt's ordinal, `errorMessage` the last failure's detail. */
  reconnectGaveUpLabel(attempt: number, errorMessage?: string): string;
  /**
   * request_end ended with a status the engine reconnects on: the engine retries carrying
   * already-produced content; attempt is the retry count. The cause wording localizes from
   * `errorCode` (legacy Traces: the retired status spellings say the same thing).
   */
  reconnectLabel(
    status: "retryable" | "failed" | "timeout" | "malformed",
    attempt: number,
    errorCode?: string,
  ): string;
  /** compaction start event: indicates compaction in progress (mode is summarize/discard, reason is context/turns/manual). */
  compactionStart(mode: string, reason: string): string;
  /**
   * compaction stop event: the compaction result (status is completed/failed/aborted;
   * completed varies its text by mode). tokens is Token usage (same convention as the stats
   * line: total = Session cumulative, delta = consumed by this compaction, carrying its own
   * sign); when present it is appended at the end of the line, e.g. ` · tokens 14k (+6k)`.
   */
  compactionStop(
    mode: string,
    status: string,
    tokens?: { total: string; delta: string },
    errorMessage?: string,
  ): string;
  /** mcp_connect_begin event: the configured MCP servers are being connected (the first run, or a new context after compaction). */
  mcpConnectStart(servers: string[]): string;
  /** mcp_connect_end event, one line: total wall time; `failures` carries "server (reason)" per failed connect (empty = all ok); `aborted` = the user interrupted mid-connect. */
  mcpConnectStop(
    durationMs: number,
    failures: { server: string; error: string }[],
    aborted: boolean,
  ): string;
  /** Prompt shown when `/compact` has nothing to compact (session just started / two consecutive compactions). */
  compactNothing(): string;
  /** Feedback after `/clear`: a fresh blank Session is now active; the old Session stays on disk (its resume command is printed right above when it has a Trace record). */
  clearDone(): string;
  /** Dim line announcing one goal round (printed before the round runs). */
  goalRound(round: number): string;
  /** Dim summary line after a goal ends: how it ended, rounds run, tokens consumed. */
  goalFinished(
    outcome: "complete" | "blocked" | "budget_limited" | "aborted",
    rounds: number,
    tokens: string,
  ): string;
  /** Dim line for a hook's answer (any hook but goal, whose own lines cover it): name, decision, reason. */
  hookEvent(name: string, decision: string | undefined, reason: string | undefined): string;
  /** `/goal` usage error (missing objective / malformed command). */
  goalUsage(): string;
  /** Invalid token-budget value (chat `/goal:<budget>` or run `--goal <budget>`). */
  goalBudgetInvalid(value: string): string;
  /** run's --goal given an empty/whitespace -m (the objective must be non-empty text). */
  goalObjectiveEmpty(): string;
  /** `/thinking` with no argument: the level this Session is pinned to (by `--thinking` or `/thinking`), else the Agent's configured level. */
  thinkingCurrent(level: string): string;
  /** `/thinking <level>` accepted: the Session is pinned to it, effective from the next request; the reply advises compacting first — a mid-context change invalidates the provider's cached context (never written to the Agent config). */
  thinkingSet(level: string): string;
  /** Invalid `--thinking` / `/thinking` value (lists the selectable levels). */
  thinkingInvalid(value: string): string;
  /** Bare `/switch-model`: the Session's current model (a formatted label) plus the usage; a switch compacts first. */
  switchModelCurrent(model: string): string;
  /** `/switch-model` with anything but exactly `<provider> <model_id>`. */
  switchModelUsage(): string;
  /** After `/switch-model` completed: the model the Session was on and the one it is on now (formatted labels). */
  switchModelDone(previous: string, next: string): string;
  /** 409 `task_in_progress` / `compacting`: the Session is busy (possibly driven from another surface). */
  switchModelBusy(): string;
  /** 409 `same_model`: the Session already runs on the target. */
  switchModelSame(model: string): string;
  /** 409 `model_not_configured`: the target is not in the Project config; names the `penguin config model` commands to list and add models. */
  switchModelNotConfigured(model: string, listCommand: string, addCommand: string): string;
  /** 409 `model_unavailable`: the target is configured but cannot be constructed (e.g. no credential); `detail` is the server's message, verbatim (may be empty). */
  switchModelUnavailable(model: string, detail: string): string;
  /** 409 `compaction_not_configured`: a switch always compacts first, and this Session has no compaction. */
  switchModelNoCompaction(): string;
  /** `/verbose` toggled on: tool output renders in full from here on. */
  verboseOn(): string;
  /** `/verbose` toggled off: long tool output is collapsed again from here on. */
  verboseOff(): string;
  /** Dim elision-marker line inside a collapsed tool output; `hidden` = lines not shown (>= 2). */
  toolOutputElided(hidden: number): string;
  /** Prompt for an invalid --approve mode. */
  approveModeInvalid(value: string): string;
  /** Render label for an approval decision (frontend renders the approval_decision event; one label each for allow/deny). */
  approvalDecision(decision: "allow" | "deny" | "forbidden"): string;
  /** run/chat given only one of --model-id / --provider: a model reference is always an explicit pair, never a lookup. */
  modelRefIncomplete(): string;
  /** --resume is mutually exclusive with --workspace/--model-id/--provider (the resumed Session keeps its own); points at `/switch-model` for changing the model inside the chat. */
  resumeNoOverride(): string;
  /** --resume given without a session id, and the current Agent has no Session at all. */
  resumeNoSession(): string;
  /** One-line prompt shown after a successful resume, before rendering history. */
  resumedBanner(sessionId: string, messageCount: number): string;
  /** Example resume command shown when the REPL exits (dim print; only when this session has a resumable record). */
  resumeHint(command: string): string;
  langInvalid(value: string): string;
  /** `config lang` persists via POSIX shell startup files; on Windows it refuses with a pointer to a user env var instead. */
  langWindowsUnsupported(lang: string): string;
  langSet(lang: string, rcPath: string): string;
  langRestartConfirm(): string;
  langRestart(): string;
  langRestartHint(rcPath: string): string;
  /** Result output for model add/default/vision/remove: the argument is the already-formatted pair reference (formatModelRef). */
  modelAdded(model: string, defaultModel: string | undefined): string;
  modelUpdated(model: string, defaultModel: string | undefined): string;
  defaultModelSet(model: string): string;
  visionModelSet(model: string): string;
  modelRemoved(model: string, defaultModel: string | undefined): string;
  /** `model remove` on a pair the Project config doesn't have. */
  modelNotConfigured(model: string): string;
  /** `model add` refused: a new entry in a first-party vendor group under a model id AgentHub cannot route. */
  modelNotRoutable(model: string): string;
  /** A new entry in a built-in group that takes no hand-added models (everything but custom and vLLM). */
  modelNotAddable(model: string, group: string): string;
  /** Follows modelRemoved when the removed entry was also the vision model. */
  visionModelCleared(): string;
  modelListTitle(): string;
  modelListEmpty(): string;
  vaultSet(key: string): string;
  vaultRemoved(key: string): string;
  vaultKeyMissing(key: string): string;
  vaultListTitle(): string;
  vaultListEmpty(): string;
  /** URL prompt once the `penguin web` service is ready. */
  webReady(url: string): string;
  /** Refusal when `penguin server` finds a live server on the same data root. */
  serverAlreadyRunning(url: string): string;
  /** Notice when `penguin web` finds a live server on the same data root (it opens that instance instead). */
  webAlreadyRunning(url: string): string;
  /** Diagnostic shown after the `penguin web` ready-poll times out (15s). */
  webProbeFailed(url: string, detail: string, kind: WebProbeFailureKind, port: number): string;
}

function headerEn(
  kind: "chat" | "run",
  version: string,
  agentId: string,
  workspace: string,
  model: string,
): string {
  return [
    `Adelie ${kind} v${version}`,
    `Agent: ${agentId}`,
    `Workspace: ${workspace}`,
    `Model: ${model}`,
  ].join("\n");
}

function headerZh(
  kind: "chat" | "run",
  version: string,
  agentId: string,
  workspace: string,
  model: string,
): string {
  return [
    `Adelie ${kind} v${version}`,
    `Agent:${agentId}`,
    `Workspace:${workspace}`,
    `模型:${model}`,
  ].join("\n");
}

const en: Messages = {
  cliDescription: "Adelie CLI",
  versionDesc: "output the version number",
  common: {
    projectId: "Project id",
    agentId: "Agent id",
    modelId: "Model to use (upstream model id; defaults to the Project default model)",
    provider:
      "Provider group of --model-id; required whenever --model-id is given (the group is never inferred)",
    root: "Data root directory (overrides ADELIE_HOME and ~/.adelie/data)",
    workspace: "Workspace directory; must already exist (defaults to the current directory)",
    approve:
      "Approval mode: allow-all (auto-approve, default), deny-all (auto-reject), read-only (auto-approve read-only tools, prompt for the rest), always-ask (prompt per tool)",
    thinking:
      "Thinking level for this session: low, medium, high, xhigh, or max (defaults to the Agent's configured level)",
    json: "Print raw JSON instead of the rendered output",
    server:
      "Server URL to connect to (defaults to ADELIE_API_URL, then the local running server, then auto-start)",
    timeout:
      "Wait at most this long (30s / 5m / 2h, or bare seconds), then detach and leave the task running (exit 0)",
    latestAgentId: "Agent whose most recent session is used when no session id is given",
  },
  usage: {
    missingArgument: (name) => `missing required argument <${name}>`,
    missingOption: (flags) => `missing required option ${flags}`,
    optionMissingArgument: (flags) => `option ${flags} needs a value`,
    unknownOption: (flag) => `unknown option ${flag}`,
    unknownCommand: (name) => `unknown command ${name}`,
    other: (detail) => detail,
    hint: (command, usage) =>
      `Usage: ${command} ${usage}  (run \`${command} --help\` for every option)`,
  },
  config: {
    desc: "Manage Project configuration",
    modelDesc: "Manage model credentials and the default model",
    addDesc: "Add or update a model, optionally writing a credential",
    addModelId: "Upstream model id sent to AgentHub as-is (e.g. claude-sonnet-4-6)",
    addProvider:
      "Provider group stored alongside model_id; required, never inferred (use custom for anything without a vendor group)",
    addApiKey: "API key, stored inline in the Project's hidden .project_config.toml",
    addBaseUrl: "Custom base URL",
    addContextWindow: "Context window size (tokens)",
    addMaxTokens:
      "Per-model max output tokens (positive integer); when set it overrides the Agent's max_tokens, omit to inherit — lower it for small-context models",
    addClientType:
      "AgentHub client type (e.g. openai-chat); defaults by provider group when omitted",
    addVision: "Mark the model as supporting image input (vision)",
    addNoVision: "Mark the model as NOT supporting image input; omit both to keep current",
    addFastMode:
      "Enable fast mode: faster output at premium pricing (models without a fast tier reject requests carrying it)",
    addNoFastMode: "Disable fast mode (the default); omit both to keep current",
    fastModeUnsupported: (ref: string): string =>
      `Warning: ${ref} cannot serve fast mode — AgentHub's client for it rejects the parameter, so its requests will fail. Re-run with --no-fast-mode to turn it off.`,
    addPriceCacheRead: "Price per 1M tokens: cache read (USD)",
    addPriceCacheWrite: "Price per 1M tokens: cache write (USD)",
    addPriceOutput: "Price per 1M tokens: output (USD)",
    addSetDefault: "Also set as the Project default model",
    defaultDesc: "Set the Project default model",
    visionDesc:
      "Set the vision model that reads images for non-vision session models (read_file hands images to it)",
    refModelId: "Upstream model id; forms the (provider, model_id) pair reference with --provider",
    refProvider: "Provider group of the referenced entry (see `penguin config model list`)",
    listDesc: "List the Project's models (API keys hidden)",
    removeDesc: "Remove a model from the Project (clears the default / vision pointers naming it)",
    langDesc: "Set the interface language (en|zh); persists ADELIE_LANG to your shell startup file",
    langArg: "Language: en or zh",
    vaultDesc: "Manage an Agent's vault (environment variables injected into its shell commands)",
    vaultSetDesc: "Set a vault environment variable (added or overwritten)",
    vaultListDesc: "List vault environment variables (values masked)",
    vaultRemoveDesc: "Remove a vault environment variable",
    vaultKey: "Variable name (letters, digits and underscores; must not start with a digit)",
    vaultValue: "Variable value, written to the Agent's agent_state/.vault.toml",
  },
  run: {
    desc: "Run a single Task",
    message: "Prompt for this Task",
    goal: "Goal mode: loop until the goal completes; optional token budget (e.g. 500k, 2m)",
    session: "Reuse an existing Session (full id or a unique fragment, e.g. the 8-hex tail)",
    background: "Post the task and exit immediately, printing the session id",
    sessionNoOverride: () =>
      "--session reuses an existing Session: --workspace, --model-id and --provider cannot be combined with it (the Session keeps its own; /switch-model inside penguin chat --resume changes its model, compacting first).",
    sourceInvalid: (value) =>
      `Invalid --source value "${value}". penguin run takes no --source: every Session it creates is a CLI Session.`,
    sourceIgnored: () =>
      "--source benchmark is no longer needed and is ignored: every Session penguin run creates is a CLI Session, listed in the Web App's Background folder.",
    timeoutWithBackground: () =>
      "--timeout bounds the wait, and --background does not wait: drop one of them.",
  },
  chat: {
    desc: "Open the interactive REPL",
    resume:
      "Resume an existing Session (defaults to the agent's most recent one); workspace and model follow the original Session (/switch-model changes the model inside the chat, compacting first)",
    verbose:
      "Show full tool output (by default long tool outputs are collapsed to their first and last lines; /verbose toggles it mid-chat)",
  },
  ls: {
    desc: "List the project's sessions (all agents unless --agent-id is given)",
    all: "Include archived sessions",
    days: "Only sessions last active within the trailing <n> calendar days (today counts as day 1)",
    daysInvalid: (value) => `Invalid --days value "${value}": expected a positive integer.`,
    empty: (projectId) => `No sessions in project ${projectId} yet.`,
    colId: () => "ID",
    colAgent: () => "AGENT",
    colTitle: () => "TITLE",
    colState: () => "STATE",
    colLast: () => "LAST",
    colWorkspace: () => "WORKSPACE",
    stateIdle: () => "idle",
    stateRunning: () => "running",
  },
  input: {
    desc: "Send a message into a session (steering while it runs, a new task when idle); without -m, print its most recent assistant reply. The session defaults to the agent's most recent one",
    message: "Message text (omit to poll the session's last assistant reply instead)",
    noReplyYet: () => "(no assistant reply yet)",
  },
  logs: {
    desc: "Render a session's history (defaults to the agent's most recent session)",
    tail: "Show only the last <n> entries",
    follow: "Keep following the live stream after the history",
    tailInvalid: (value) => `Invalid --tail value "${value}": expected a positive integer.`,
    timeoutNeedsFollow: () =>
      "--timeout only applies to -f/--follow: without it, logs never waits.",
  },
  agent: {
    desc: "Manage the project's agents",
    lsDesc: "List the project's agents",
    createDesc: "Create an agent",
    createId: "Agent id (directory name; letters, digits, underscores)",
    createName: "Display name (defaults to the id)",
    createDescription: "Description",
    createPlugins:
      "Library plugins to preinstall, comma-separated (e.g. software-development,goal)",
    created: (agentId, projectId) => `Agent ${agentId} created in project ${projectId}.`,
    colId: () => "ID",
    colName: () => "NAME",
    colSessions: () => "SESSIONS",
    colDescription: () => "DESCRIPTION",
    apiDesc: "Manage an agent's public API: the switch, keyless access, approval mode and keys",
    apiStatusDesc: "Show the agent's API settings, its address and the server-wide switch",
    apiEnableDesc: "Turn the agent's API on",
    apiDisableDesc: "Turn the agent's API off (settings and keys are kept)",
    apiSetDesc: "Change keyless access or the approval mode without turning the API on or off",
    apiOpen: "Allow keyless access: anything that can reach the server can talk to the agent",
    apiNoOpen: "Require a key",
    apiApprove:
      "Approval mode new API conversations start with: allow-all, deny-all, read-only or always-ask (asks go to the caller)",
    apiNothingToSet: () => "Nothing to change: pass --open, --no-open or --approve <mode>.",
    apiKeysDesc: "Manage the agent's API keys",
    apiKeysLsDesc: "List the agent's API keys",
    apiKeysCreateDesc: "Create an API key; the key is printed once, alone on stdout",
    apiKeysRmDesc: "Delete an API key; programs using it are refused from then on",
    apiKeyName: "Name of the key (1-64 characters)",
    apiServerDesc: "Turn the Agent API on or off for the whole server (admins only)",
    apiServerStateInvalid: (value) => `Invalid state "${value}": expected on or off.`,
    apiStatusTitle: (agentRef) => `Agent API of ${agentRef}`,
    apiFieldEnabled: () => "Enabled",
    apiFieldOpen: () => "Keyless access",
    apiFieldApproval: () => "Approval mode",
    apiFieldBaseUrl: () => "Base URL",
    apiFieldAgentId: () => "Agent ID",
    apiFieldKeys: () => "Keys",
    apiFieldServer: () => "Server switch",
    apiYes: () => "yes",
    apiNo: () => "no",
    apiServerOn: () => "on",
    apiServerOff: () => "off (every API request is refused)",
    apiColKeyId: () => "ID",
    apiColKeyName: () => "NAME",
    apiColPrefix: () => "PREFIX",
    apiColCreated: () => "CREATED",
    apiColLastUsed: () => "LAST USED",
    apiKeyNever: () => "never",
    apiKeysEmpty: (agentRef) => `${agentRef} has no API keys.`,
    apiKeyCreated: (name, prefix, agentRef) =>
      `Created key "${name}" (${prefix}…) for ${agentRef}. It is shown once, above; store it now.`,
    apiKeyDeleted: (keyId, agentRef) => `Deleted key ${keyId} of ${agentRef}.`,
    apiServerSet: (on) =>
      on
        ? "The Agent API is on for this server."
        : "The Agent API is off for this server: every request is refused; per-agent settings and keys are kept.",
    apiSignInRequired: () =>
      "Sign in first: `penguin auth login` (or `penguin auth token` on the server's machine). The local API token may not change an Agent's exposure.",
    apiOpenWarning: () =>
      "Warning: keyless access is on. Anything that can reach this server's address can now talk to the agent without a key, on the Project's models and credentials. Keep it on only for a server that listens on loopback; `--no-open` turns it off.",
  },
  project: {
    desc: "Manage projects",
    lsDesc: "List the projects this account can reach",
    colId: () => "ID",
    colName: () => "NAME",
    colRole: () => "ROLE",
  },
  cost: {
    desc: "Show token usage and cost (summary card by default; --by prints a grouped table)",
    days: "Trailing window in days (sets --from/--to)",
    from: "Range start (yyyy-mm-dd); requires --to",
    to: "Range end (yyyy-mm-dd); requires --from",
    by: "Group the table by: date, agent, model or session",
    rangeIncomplete: () => "--from and --to must be given together.",
    daysInvalid: (value) => `Invalid --days value "${value}": expected a positive integer.`,
    byInvalid: (value) => `Invalid --by value "${value}": expected date, agent, model or session.`,
    today: () => "today",
    last7d: () => "last 7 days",
    total: () => "total",
    empty: () => "No usage recorded for this range.",
    noPricing: () => "-",
    colTokens: () => "TOKENS",
    colRequests: () => "REQUESTS",
    colCost: () => "COST",
    colGroup: (dimension) => dimension.toUpperCase(),
  },
  storage: {
    desc: "Show what occupies the data root (read-only: this command deletes nothing)",
    top: "How many candidates to print (0 prints every one)",
    topInvalid: (value) => `Invalid --top value "${value}": expected zero or a positive integer.`,
    heading: (root, total, disk) =>
      disk === null
        ? `Data root ${root} · ledger total ${total} · volume unknown`
        : `Data root ${root} · ledger total ${total} · ${disk.free} free of ${disk.total} (${disk.usedPercent}% used)`,
    lowFree: (free) =>
      `Low on space: ${free} free. Read the candidates below — none of them is removed until you approve a specific list.`,
    colClass: () => "CLASS",
    colBytes: () => "SIZE",
    colFiles: () => "FILES",
    colEntries: () => "ENTRIES",
    colCandidates: () => "CANDIDATES",
    candidateCell: (entries, bytes) => `${entries} (${bytes})`,
    candidatesHeading: () =>
      "Candidates — a report, not a to-do list: nothing is removed without your approval.",
    candidatesEmpty: () => "Nothing is a candidate under the current thresholds.",
    colModified: () => "MODIFIED",
    colRules: () => "WHY",
    colPath: () => "PATH",
    moreCandidates: (n) => `… and ${n} more (raise --top, or --top 0 for all).`,
    candidateCosts: () =>
      "What clearing each class costs: session drafts — attachments in older messages stop previewing; traces — history replay and the Costs page lose their rebuild source; tool environments — reinstalling the next time the tool is used; temporary workspaces — whatever is inside goes with them.",
    unknownDate: () => "unknown",
    groupsHeading: () =>
      "Environments that look like the same toolchain installed more than once (report only — merging is a change a person triggers):",
    groupKind: (kind) => (kind === "name" ? "same name" : "same contents"),
    groupLine: (kind, key, members, bytes) =>
      `- ${kind} (${key}): ${members} environments, ${bytes} together`,
    unreadableHeading: () =>
      "Could not be read (so the totals above are a floor, not a measurement):",
    modeOffNotice: () =>
      "Read-only report: cleanup mode is off, so nothing here can move a file. Reviewing a candidate list is the next step — `penguin storage scan`. And nothing runs on a timer.",
    modeOnNotice: () =>
      "Cleanup mode is on. `penguin storage scan` writes a bill; `penguin storage apply <planId> --path <path>` moves the entries you select into the trash. Nothing here removes data, and nothing runs on a timer.",
    className: (key) =>
      key === "protected"
        ? "user data"
        : key === "tmp_workspaces"
          ? "temp workspaces"
          : key === "session_drafts"
            ? "session drafts"
            : key === "traces"
              ? "traces"
              : key === "shared_env"
                ? "tool environments"
                : key === "trash"
                  ? "trash"
                  : key === "database"
                    ? "database"
                    : "other",
    ruleLabel: (rule) =>
      rule === "empty"
        ? "empty"
        : rule === "unreferenced"
          ? "unreferenced"
          : rule === "orphan"
            ? "session gone"
            : rule === "idle"
              ? "idle"
              : "over budget",
    scanDesc:
      "Scan the data root and write a plan you can review (read-only; needs cleanup mode on)",
    planDesc: "Read a plan back, or list the recent ones when no id is given",
    applyDesc:
      "Move the entries you name into the trash: needs the plan's paths (there is no --yes, and no way to clean everything at once)",
    applyPath: "A path the plan lists (repeatable, or comma-separated)",
    applyAll:
      "Move every entry of this plan that this version may move (the plan marks which those are)",
    applyNoSelection: () =>
      "Nothing selected: give --path <path> for each entry you reviewed, or --all for every entry the plan marks cleanable.",
    applyNothing: () => "Nothing was moved (see the failures above).",
    applyMoved: (moved, bytes, trashId) =>
      `Moved ${moved} entr${moved === 1 ? "y" : "ies"} (${bytes}) into the trash as ${trashId}.`,
    applyFailedLine: (path, reason) => `  not moved: ${path} — ${reason}`,
    trashDesc:
      "Where a cleanup moves things instead of deleting them: list what is there, put it back, or purge it",
    trashListDesc: "List what previous cleanups moved (listing removes nothing)",
    trashRestoreDesc: "Put a trash entry's contents back where they came from",
    trashPurgeDesc:
      "Delete a trash entry for good — the named one, or everything past the retention",
    trashEmpty: () => "The trash is empty.",
    trashRestored: (id, restored, remaining) =>
      `Restored ${restored} entr${restored === 1 ? "y" : "ies"} from ${id}.` +
      (remaining ? " The entry still holds what could not be put back." : ""),
    trashSkippedLine: (path, reason) => `  not restored: ${path} — ${reason}`,
    trashPurgeNothing: () => "Nothing to purge (nothing is past the retention).",
    trashPurgedLine: (id, bytes) => `Purged ${id} (${bytes}).`,
    trashTtlDays: (days) => `${days}d`,
    expired: (ttl) => `past the retention (${ttl})`,
    modeDesc:
      "Show the cleanup mode, or turn it on/off (off — the default — refuses every cleanup write)",
    modeUsage: () => "usage: penguin storage mode [on|off]",
    modeIs: (enabled, ttlDays, pins) =>
      `Cleanup mode is ${enabled ? "on" : "off"}. Trash retention ${ttlDays} days, ${pins} pinned path(s).`,
    modeSet: (enabled, ttlDays, pins) =>
      `Cleanup mode is now ${enabled ? "on" : "off"}. Trash retention ${ttlDays} days, ${pins} pinned path(s).`,
    billHeading: (id, entries, bytes, expires) =>
      `Plan ${id} · ${entries} entr${entries === 1 ? "y" : "ies"} · ${bytes} · review it and approve with \`penguin storage apply\` · valid until ${expires}`,
    billEmpty: () => "No entry is a candidate under the current thresholds.",
    billExcluded: (n) => `${n} pinned path(s) left out of this plan.`,
    billReportOnly: (classes) =>
      `This version only moves ${classes.join(", ")}; every other entry is on the bill to be read, not selected.`,
    billNotice: (id) =>
      `Nothing has moved. Approve the entries you select: penguin storage apply ${id} --path <path> (or --all).`,
    billSpent: (id) =>
      `This plan cannot be applied (already used, or older than its day). Scan again for a new bill: penguin storage scan.`,
    reportOnlyMark: () => "—",
    moveMark: () => "✓",
    plansEmpty: () => "No plan has been written yet (`penguin storage scan`).",
    planStateOpen: () => "open",
    planStateApplied: (at) => `applied ${at}`,
    planStateExpired: (at) => `expired ${at}`,
    colExecutable: () => "MOVE",
    colPlanId: () => "PLAN",
    colCreated: () => "CREATED",
    colState: () => "STATE",
    colTrashId: () => "TRASH",
    colItems: () => "ITEMS",
    colExpired: () => "RETENTION",
  },

  schedule: {
    desc: "Manage scheduled tasks",
    lsDesc: "List the project's scheduled tasks (all agents unless --agent-id is given)",
    addDesc:
      "Create a scheduled task (writes the schedule file through the API; enabled by default — use --disabled to opt out)",
    updateDesc:
      "Update a scheduled task (read-modify-write: unspecified fields keep their stored values)",
    rmDesc: "Delete a scheduled task (no prompt; the server's owner authorization applies)",
    prompt: "The text each firing sends",
    startAt:
      "First fire time (ISO 8601), or the literal `now` for the current instant; a one-shot task needs a future time, so `now` only works with --period",
    period: "Fixed interval, minimum 5m (e.g. 30m, 12h, 1d, 7d); omitted = one-shot",
    endAt: "Stop firing after this instant (ISO 8601)",
    sessionId: "Bind firings to one session (excludes --workspace / the model pair)",
    workspace: "New-session mode: workspace for each firing (omitted = a temp workspace)",
    disabledOpt: "Create the task disabled (the CLI default is enabled)",
    enableOpt: "Enable the task",
    disableOpt: "Disable the task",
    enableDisableConflict: () => "--enable and --disable are mutually exclusive.",
    targetConflict: () =>
      "--session-id and the new-session form (--workspace / --model-id / --provider) are mutually exclusive: the target is one or the other.",
    written: (name, enabledText, nextFireAt) =>
      `Schedule ${name} written (${enabledText}${nextFireAt !== undefined ? `, next fire ${nextFireAt}` : ""}).`,
    removed: (name) => `Schedule ${name} removed.`,
    enabled: () => "on",
    disabled: () => "off",
    oneShot: () => "once",
    newSession: () => "new session",
    empty: (projectId) => `No scheduled tasks in project ${projectId}.`,
    colName: () => "NAME",
    colEnabled: () => "ENABLED",
    colStartAt: () => "START",
    colPeriod: () => "PERIOD",
    colTarget: () => "TARGET",
    colLastFired: () => "LAST FIRED",
    colStatus: () => "STATUS",
  },
  org: {
    desc: "Company mode: manage an organization (employees, desks, calendar, tickets, channels, finance)",
    lsDesc: "List the project's organizations",
    createDesc:
      "Create an organization: its CEO Agent, the CEO's desk session and the initialization run",
    showDesc:
      "Overview: employees and their states, board counts, spend against budget, pending items",
    chartDesc: "The employee tree with titles, states, spend and budgets",
    hireDesc:
      "Employ an Agent: an existing one (--agent-id) or a new one (--new-agent), under --reports-to",
    employeeDesc: "Manage employees",
    employeeSetDesc: "Update an employee's entry in the tree (only the given fields change)",
    leaveDesc: "Remove an employee from the organization (not the CEO); the Agent itself stays",
    deskDesc: "Desk sessions (one standing session per employee)",
    deskShowDesc: "The employee's desk session id and Workspace (opens the desk if it has none)",
    deskRenewDesc: "Open a fresh desk session for the employee (resets its context)",
    calendarDesc: "Calendar events (schedules that fire into the employee's desk session)",
    calendarLsDesc: "List the organization's calendar events (one employee's with --agent-id)",
    calendarAddDesc:
      "Create a calendar event (writes the event file through the API; enabled by default — use --disabled to opt out)",
    calendarUpdateDesc:
      "Update a calendar event (read-modify-write: unspecified fields keep their stored values)",
    calendarRmDesc: "Delete a calendar event (no prompt)",
    ticketDesc: "Tickets on the kanban board",
    ticketLsDesc: "List the board's tickets (filtered locally by --status / --owner / --blocked)",
    ticketShowDesc: "Show a ticket: the derived figures, then the ticket file",
    ticketCreateDesc: "Create a ticket in the proposed column",
    ticketMoveDesc: "Move a ticket to another column (a reason is required for rejected)",
    ticketAssignDesc: "Set a ticket's owner",
    ticketBlockDesc: "Mark a ticket blocked (it stays in its column)",
    ticketUnblockDesc: "Clear a ticket's blocked state",
    ticketProgressDesc: "Append a progress entry (attributed to the calling session)",
    ticketStartDesc:
      "Open a ticket session that works on the ticket in the background; prints the session id. Only the ticket's owner (its desk) or a person may start one — assign the ticket to move it to another employee",
    ticketAttachDesc:
      "Attach an existing session as a contributor (defaults to the calling session)",
    channelDesc:
      "The organization's channels (default_channel is the all-hands one everybody is in)",
    channelLsDesc: "List the channels: every one of them for a person, its own for an employee",
    channelCreateDesc:
      "Open a channel; only its creator is in it, everyone else arrives by invitation",
    channelShowDesc: "Show a channel and its members",
    channelInviteDesc: "Invite principals into a channel (any member may)",
    channelJoinDesc: "Join a channel yourself (people only; an employee waits to be invited)",
    channelLeaveDesc: "Leave a channel",
    channelRemoveDesc: "Remove another member from a channel (people only)",
    channelArchiveDesc: "Archive a channel: read-only until it is unarchived (people only)",
    channelUnarchiveDesc: "Unarchive a channel (people only)",
    channelTailDesc: "Print a channel's last messages of a day (20 unless -n is given)",
    channelSendDesc:
      "Send a message to a channel (@agent:<id> / @all mention its members and trigger their desks)",
    handbookDesc:
      "The organization handbook: the knowledge base under handbook/, whose README.md is the index every run reads first",
    handbookListDesc: "List the handbook files (path, size, updated), the index first",
    handbookShowDesc: "Print a handbook document (the index when no path is given)",
    handbookWriteDesc: "Create or replace a handbook document from -m or --file",
    handbookRmDesc: "Delete a handbook document (the index cannot be deleted)",
    financeDesc: "Spend per employee (along the reporting line) and per ticket, against budgets",
    orgId:
      "Organization id (defaults to ADELIE_ORG_ID, set inside desk and ticket sessions; no other default)",
    newOrgId:
      "Id of the organization to create (letters, digits, underscores; also its directory name)",
    mission: "The organization's mission",
    orgName: "Display name (defaults to the id)",
    orgLanguageOption:
      "Working language of everything the organization writes: zh or en (defaults to the mission's own language)",
    hireAgentId: "Employ this existing Agent (mutually exclusive with --new-agent)",
    newAgent: "Create an Agent with this id and employ it (mutually exclusive with --agent-id)",
    newAgentName: "Display name of the new Agent",
    newAgentDescription: "Description of the new Agent",
    skills:
      "Extra library plugins for the new Agent, comma-separated (added to agent-company,agent-development)",
    title: "Job title",
    reportsTo: "Agent id of the manager",
    employeeWorkspace:
      "Workspace: a sub-directory of the shared workspace (. = all of it) or an absolute path, written as given",
    hireWorkspace:
      "Workspace: a sub-directory of the shared workspace or an absolute path, written as given (defaults to a sub-directory named after the employee)",
    budget: "Monthly budget in USD for the employee plus everyone below it",
    ceoBudget:
      "The CEO's monthly budget in USD, which is the whole company's (budgets accumulate along the reporting line)",
    duties: "Duties, in prose",
    calendarAgentId:
      "Employee the event belongs to (defaults to ADELIE_AGENT_ID); on ls, list only this employee's events",
    calendarTitle: "Event title",
    statusFilter: "Only this column: proposed, in_progress, review, done or rejected",
    ownerFilter: "Only tickets owned by this principal (agent:<id> / user:<id>)",
    blockedFilter: "Only blocked tickets",
    ticketTitle: "Ticket title",
    ticketSlug: "The ticket id's words: lowercase English words joined by hyphens",
    goal: "The goal, naming every input it relies on by full path (mutually exclusive with --body-file)",
    criteria: "Acceptance criteria, naming the expected deliverables by full path (with --goal)",
    bodyFile: "Read the whole Markdown body from this file (the header is still generated)",
    owner: "The responsible principal (agent:<id> / user:<id>); defaults to you on create",
    parent: "Parent ticket id",
    notify: "Principals notified when the ticket ends, comma-separated",
    priority: "Priority: P0, P1 or P2",
    due: "Due date (yyyy-mm-dd)",
    moveTo: "Target column: proposed, in_progress, review, done or rejected",
    moveReason: "Why (required when moving into rejected; recorded under Result)",
    blockReason: "Why the ticket is blocked",
    blockedBy: "Who or which ticket it waits for (a principal or a ticket id)",
    progressText: "The progress entry, naming the files it refers to by full path",
    startMessage: "A note appended to the ticket text the session opens with",
    startWorkspace:
      "Another directory inside the shared workspace (defaults to the employee's desk workspace)",
    startAgentId:
      "Which employee the session runs as: a colleague you enlist on your own ticket (defaults to you inside a session, otherwise the ticket's owner)",
    attachSession:
      "The session to attach, full id or unique fragment (defaults to ADELIE_SESSION_ID)",
    channelOpt: "Channel to read or write in (default: default_channel, the all-hands channel)",
    channelName: "Display name (defaults to the id)",
    channelPurpose: "What the channel is for",
    channelDate: "Day to read (yyyy-mm-dd in the organization's timezone; defaults to today)",
    channelCount: "Number of messages to print (default 20)",
    channelText: "Message text (@agent:<id> or @all to mention, inside the channel's membership)",
    handbookPath:
      "Path relative to handbook/ (plain segments, e.g. decisions/2026-09-02-hire-plan.md)",
    handbookText: "Document text",
    handbookFile: "Read the document text from a local file",
    handbookOneSource: "Give exactly one of -m <text> or --file <file>.",
    refTicket: "Ticket the message refers to",
    refSession: "Session the message refers to",
    period: "Month to report (yyyy-mm; defaults to the current month)",
    orgIdMissing: () =>
      "No organization given: pass --org-id <id>, or set ADELIE_ORG_ID (desk and ticket sessions carry it in their environment).",
    hireTargetConflict: () =>
      "Pass exactly one of --agent-id (an existing Agent) and --new-agent (create one).",
    newAgentFieldsOnly: () => "--name, --description and --skills describe --new-agent only.",
    budgetInvalid: (flag, value) =>
      `Invalid ${flag} value "${value}": expected a non-negative amount in USD.`,
    nothingToSet: () => "Nothing to update: pass at least one field.",
    languageInvalid: (value) => `Invalid --language value "${value}": expected zh or en.`,
    statusInvalid: (value) =>
      `Invalid column "${value}": expected proposed, in_progress, review, done or rejected.`,
    priorityInvalid: (value) => `Invalid --priority value "${value}": expected P0, P1 or P2.`,
    ticketBodyConflict: () => "Pass exactly one of --goal and --body-file.",
    criteriaNeedsGoal: () => "--criteria goes with --goal.",
    bodyFileUnreadable: (file) => `Cannot read --body-file ${file}.`,
    countInvalid: (value) => `Invalid -n value "${value}": expected a positive integer.`,
    pathSegmentInvalid: (value) =>
      `Invalid name "${value}": "." and ".." are neither an id nor a handbook path.`,
    attachSessionMissing: () =>
      "No session to attach: pass --session <id>, or run inside a session (ADELIE_SESSION_ID).",
    created: (orgId, ceoDeskSessionId) =>
      `Organization ${orgId} created${ceoDeskSessionId !== undefined ? ` (CEO desk session ${ceoDeskSessionId})` : ""}.`,
    hired: (agentId, title, reportsTo) =>
      `Employee ${agentId} hired as ${title}${reportsTo !== null ? `, reporting to ${reportsTo}` : ""}.`,
    employeeUpdated: (agentId) => `Employee ${agentId} updated.`,
    left: (agentId) => `Employee ${agentId} left the organization.`,
    desk: (agentId, sessionId, workspace, openedAt, created) =>
      `Desk of ${agentId}: session ${sessionId} (workspace ${workspace}, opened ${openedAt})${created ? " — opened just now" : ""}`,
    deskRenewed: (agentId, sessionId) => `Desk of ${agentId} renewed: session ${sessionId}.`,
    calendarWritten: (agentId, name, enabledText, nextFireAt) =>
      `Calendar event ${agentId}/${name} written (${enabledText}${nextFireAt !== undefined ? `, next fire ${nextFireAt}` : ""}).`,
    calendarWarning: (warning) => `Rota notice: ${warning}`,
    calendarRemoved: (agentId, name) => `Calendar event ${agentId}/${name} removed.`,
    ticketCreated: (ticketId, status) => `Ticket ${ticketId} created (${status}).`,
    ticketMoved: (ticketId, status) => `Ticket ${ticketId} moved to ${status}.`,
    ticketAssigned: (ticketId, owner) => `Ticket ${ticketId} assigned to ${owner}.`,
    ticketBlocked: (ticketId) => `Ticket ${ticketId} marked blocked.`,
    ticketUnblocked: (ticketId) => `Ticket ${ticketId} unblocked.`,
    progressRecorded: (ticketId) => `Progress recorded on ticket ${ticketId}.`,
    ticketAttached: (ticketId, sessionId) => `Session ${sessionId} attached to ticket ${ticketId}.`,
    channelCreated: (channelId) => `Channel ${channelId} created.`,
    channelInvited: (channelId, principal) => `${principal} invited to ${channelId}.`,
    channelJoined: (channelId) => `Joined ${channelId}.`,
    channelLeft: (channelId) => `Left ${channelId}.`,
    channelMemberRemoved: (channelId, principal) => `${principal} removed from ${channelId}.`,
    channelArchived: (channelId) => `Channel ${channelId} archived.`,
    channelUnarchived: (channelId) => `Channel ${channelId} unarchived.`,
    messageSent: (id) => `Message ${id} sent.`,
    handbookWritten: (path) => `Handbook document ${path} written.`,
    handbookRemoved: (path) => `Handbook document ${path} removed.`,
    empty: (projectId) => `No organizations in project ${projectId}.`,
    calendarEmpty: () => "No calendar events.",
    ticketsEmpty: () => "No tickets match.",
    channelsEmpty: () => "No channels.",
    channelEmpty: (channelId, date) => `No messages in ${channelId} on ${date}.`,
    showHead: (name, orgId, status) => `${name} (${orgId}) — ${status}`,
    showMission: (mission) => `Mission: ${mission}`,
    showLanguage: (language) => `Working language: ${language}`,
    showEmployees: (count, running, paused) =>
      `Employees: ${count} (${running} running, ${paused} paused)`,
    showBoard: (counts, blocked) => `Board: ${counts} (${blocked} blocked)`,
    showSpend: (period, spend) => `Spend (${period}): ${spend}`,
    showPending: (mentions, review, blockedByMe) =>
      `Pending: ${mentions} mentions, ${review} tickets to review, ${blockedByMe} blocked by me`,
    invalid: (reason) => `invalid: ${reason}`,
    ticketHead: (ticketId, status, running, blocked) =>
      `Ticket ${ticketId}: ${status}${running ? ", running" : ""}${blocked !== undefined ? `, blocked (${blocked})` : ""}`,
    ticketFigures: (cost, rolledUp, sessions, children) =>
      `Cost ${cost} (rolled up ${rolledUp}), ${sessions} sessions, ${children} child tickets`,
    ticketFields: () => ({
      title: "Title",
      owner: "Owner",
      parent: "Parent",
      notify: "Notify",
      priority: "Priority",
      due: "Due",
      blocked: "Blocked",
      blockedBy: "Blocked by",
      sessions: "Sessions",
    }),
    ticketHistory: () => "History:",
    notices: {
      employee_joined: (p) => `${p.agent} joined as ${p.title}, reporting to ${p.reportsTo}.`,
      employee_left: (p) => `${p.agent} left the organization; reports now go to ${p.reportsTo}.`,
      channel_created: (p) => `${p.by} created the channel.`,
      channel_archived: (p) => `${p.by} archived the channel.`,
      channel_unarchived: (p) => `${p.by} unarchived the channel.`,
      channel_joined: (p) => `${p.principal} joined the channel.`,
      channel_invited: (p) => `${p.by} invited ${p.principal} to the channel.`,
      channel_left: (p) => `${p.principal} left the channel.`,
      channel_removed: (p) => `${p.by} removed ${p.principal} from the channel.`,
      budget_warned: (p) =>
        `Budget warning: ${p.agent} has used ${p.percent}% of its ${p.period} budget (${p.cost} / ${p.budget} USD).`,
      budget_paused: (p) =>
        `Budget pause: ${p.agent} reached ${p.percent}% of its ${p.period} budget (${p.cost} / ${p.budget} USD); its calendar and its subordinates' are paused.`,
      ticket_blocked: (p) => `Ticket ${p.ticket} (${p.title}) is now blocked.`,
      ticket_done: (p) => `Ticket ${p.ticket} (${p.title}) is now done.`,
      ticket_rejected: (p) => `Ticket ${p.ticket} (${p.title}) is now rejected.`,
    },
    allHands: () => "All hands",
    channelHeader: (channelId) => `[channel ${channelId}]`,
    channelHead: (name, channelId, members, archived) =>
      `${name} (${channelId}) — ${members} members${archived ? ", archived" : ""}`,
    channelPurposeLine: (purpose) => `Purpose: ${purpose}`,
    channelCreatedBy: (principal, createdAt) => `Created by ${principal} on ${createdAt}`,
    channelLastMessage: (time) => `Last message: ${time}`,
    financeTotal: (period, total) => `Total (${period}): ${total}`,
    unpriced: () =>
      "[unpriced] some usage ran on a model without pricing: the figures are a lower bound",
    colEmployees: () => "EMPLOYEES",
    colRunning: () => "RUNNING",
    colOpen: () => "OPEN",
    colBlocked: () => "BLOCKED",
    colSpend: () => "SPEND",
    colNote: () => "NOTE",
    colJobTitle: () => "TITLE",
    colTitle: () => "TITLE",
    colState: () => "STATE",
    colOwn: () => "OWN",
    colCumulative: () => "CUMULATIVE",
    colBudget: () => "BUDGET",
    colNext: () => "NEXT",
    colPriority: () => "PRIORITY",
    colOwner: () => "OWNER",
    colTicket: () => "TICKET",
    colRolledUp: () => "ROLLED UP",
    colMembers: () => "MEMBERS",
    colArchived: () => "ARCHIVED",
    colUnread: () => "UNREAD",
    colMentions: () => "@ME",
    colPrincipal: () => "PRINCIPAL",
  },
  browser: {
    desc: "The desktop app's built-in browser: read pages, run JavaScript, click and type, import sign-ins",
    statusDesc: "Whether the built-in browser is available, and its tabs",
    tabsDesc: "List the open tabs (* marks the active one)",
    openDesc:
      "Open a URL in the active tab (in a new one when none is open), or in a new tab with --new-tab",
    switchDesc: "Make a tab the active one",
    closeDesc: "Close a tab (default: the active one)",
    scanDesc:
      "Read the page as simplified HTML (or plain text with --text), after the tab list; hidden list items show as a [FAKE ELEMENT] hint",
    execDesc:
      "Run JavaScript in the page; prints its return value, the elements that changed, transient messages and new tabs",
    clickDesc: "Click an element by CSS selector, or a point with --at, with trusted mouse events",
    typeDesc:
      "Type text into the focused element (or --selector), optionally pressing Enter afterwards",
    screenshotDesc: "Save a PNG screenshot of the tab",
    cdpDesc: "Send a raw Chrome DevTools Protocol command to the tab",
    importDesc:
      "Import cookies (sign-ins) and history from a browser installed on this machine (neither flag: both)",
    historyDesc: "Search the built-in browser's history (most visited first, then most recent)",
    tab: 'Tab id, or "active" (default)',
    urlArg: "URL to open; https:// is added to a bare host",
    newTab: "Open it in a new tab",
    tabIdArg: "Tab id",
    closeTabArg: 'Tab id, or "active" (default)',
    textOnly: "Plain text instead of simplified HTML (fewer tokens)",
    maxChars: "Longest body to return, in characters (default 35000; a third of it with --text)",
    scriptArg:
      'JavaScript, run as the body of an async function: end with `return <value>`. "-" reads it from stdin',
    file: "Read the script from this file",
    save: "Write the whole return value to this file and print only its start",
    noMonitor: "Skip change tracking: faster, for scripts that only read",
    timeout: "Script time limit: 30s, 2m or bare seconds (default 15s)",
    selectorArg: "CSS selector of the element to click",
    index: "Which match of the selector to click, from 0 (default 0)",
    at: "Click this viewport point instead, as x,y in CSS pixels",
    textArg: "Text to type",
    selector: "Focus this element first (CSS selector)",
    submit: "Press Enter afterwards",
    acceptDialogs:
      "Accept the page's confirm, prompt and leave-page dialogs too (alerts always are; without this the others are dismissed)",
    output: "PNG file to write (default: screenshot-<time>.png in the working directory)",
    fullPage: "Capture the whole page, not only the viewport",
    methodArg: "CDP method, e.g. DOM.getDocument",
    params: "The method's parameters as a JSON object",
    list: "List the browser profiles on this machine",
    from: "Profile to import from: a source id from --list, or a browser (chrome, edge, firefox…) for its Default profile",
    cookies: "Import cookies and sign-ins",
    history: "Import history",
    domain: "Only the cookies of this site and its subdomains (repeatable, or comma-separated)",
    queryArg: "Words to find in titles and URLs",
    count: "How many entries (default 20)",
    label: {
      status: "status",
      tab: "tab",
      tabs: "tabs",
      page: "page",
      return: "return",
      error: "error",
      diff: "diff",
      transients: "transients",
      newTabs: "new tabs",
      note: "note",
      clicked: "clicked",
      source: "source",
      cookies: "cookies",
      history: "history",
      warning: "warning",
      screenshot: "screenshot",
      dialog: "dialog",
      memory: "memory",
    },
    line: (label, value) => `${label}: ${value}`,
    tabHead: (id, title, url, loading) =>
      `tab ${id} · ${title || "(untitled)"} · ${url}${loading ? " · loading" : ""}`,
    noTabs: () => "none",
    available: () => "available",
    unavailable: (reason) => `unavailable (${reason})`,
    unavailableHint: (reason) => {
      const base = "The built-in browser needs the Adelie desktop app, and the app must be open";
      if (reason === "shell_unsupported")
        return `${base}: this desktop app is too old for it, so update the app.`;
      if (reason === "no_window") return `${base}: it has no open window, so open it.`;
      if (reason === "not_desktop") return `${base}: this server is not running inside it.`;
      return `${base}.`;
    },
    memoryLine: (total, tabs, system) =>
      `${total} across ${tabs} ${tabs === 1 ? "tab" : "tabs"}` +
      (system !== undefined ? ` · this computer: ${system.free} free of ${system.total}` : ""),
    loadWarning: (warnings) => {
      const said = [
        warnings.includes("memory") ? "the browser holds a lot of memory" : "",
        warnings.includes("low_system_memory") ? "this computer is low on memory" : "",
        warnings.includes("many_tabs") ? "many tabs are open" : "",
      ].filter(Boolean);
      const text = said.join(", and ") || "the browser is heavy";
      return `${text.charAt(0).toUpperCase()}${text.slice(1)}. Close the tabs you no longer need (penguin browser close <tab-id>).`;
    },
    closed: (tab) => `Closed tab ${tab}.`,
    closedActive: () => "Closed the active tab.",
    reloaded: () => "reloaded",
    elementsChanged: (count) => (count === 1 ? "1 element changed" : `${count} elements changed`),
    clickedAt: (tag, text, x, y) => `${tag ?? "element"}${text ? ` "${text}"` : ""} at ${x},${y}`,
    dialogAnswered: (type, message, accepted) =>
      `${type} "${message}" → ${accepted ? "accepted" : "dismissed (rerun with --accept-dialogs to accept)"}`,
    truncatedSave: () => "[truncated — use --save]",
    truncatedJson: () => "[truncated — use --json]",
    savedTo: (path) => `[saved to ${path}]`,
    screenshotSaved: (path, size, kilobytes) => `${path} (${size}, ${kilobytes} KB)`,
    importData: (cookies, history) =>
      [cookies ? "cookies" : "", history ? "history" : ""].filter(Boolean).join(", ") || "-",
    importCookies: (c) =>
      `${c.imported} imported, ${c.skipped} skipped, ${c.failed} failed (${c.found} found)`,
    importHistory: (h) => `${h.imported} imported (${h.found} found)`,
    noSources: () => "No browser profiles to import from were found on this machine.",
    noHistory: () => "No history matches.",
    visits: (count) => (count === 1 ? "1 visit" : `${count} visits`),
    colId: () => "ID",
    colTitle: () => "TITLE",
    colUrl: () => "URL",
    colBrowser: () => "BROWSER",
    colProfile: () => "PROFILE",
    colData: () => "DATA",
    errorLine: (code, message) => `error: ${code}: ${message}`,
    tabInvalid: (value) => `A tab is a tab id or "active", not "${value}".`,
    positiveInt: (flag, value) => `${flag} takes a positive whole number, not "${value}".`,
    indexInvalid: (value) => `--index takes a whole number from 0, not "${value}".`,
    atInvalid: (value) => `--at takes x,y in CSS pixels (e.g. --at 120,340), not "${value}".`,
    clickTarget: () => "Give either a selector (with --index) or --at x,y.",
    newTabWithTab: () => "--new-tab opens a new tab, so it takes no --tab.",
    paramsInvalid: () => "--params must be a JSON object.",
    methodInvalid: (value) =>
      `"${value}" is not a CDP method: write Domain.method, e.g. DOM.getDocument.`,
    scriptSources: () => "Give the script one way only: as an argument, with --file, or on stdin.",
    scriptMissing: () =>
      "No script: pass it as an argument, with --file, or on stdin (penguin browser exec <<'EOF' … EOF).",
    scriptEmpty: () => "The script is empty.",
    fileUnreadable: (path, detail) => `Cannot read ${path}: ${detail}`,
    fileUnwritable: (path, detail) => `Cannot write ${path}: ${detail}`,
    importMode: () =>
      "Use --list to see the browser profiles, or --from <source-id|browser> to import from one.",
    sourceNotFound: (from, known) =>
      `No browser profile matches "${from}"${known.length > 0 ? ` (this machine has: ${known.join(", ")})` : ""}; see penguin browser import --list.`,
    sourceAmbiguous: (from, ids) =>
      `${from} has several profiles and none is Default: ${ids.join(", ")}. Pass one with --from.`,
  },
  client: {
    invalidServerUrl: (value) => `Invalid server URL "${value}": expected http(s)://host[:port].`,
    remoteNeedsToken: (url) =>
      `${url} is not this machine: set ADELIE_API_TOKEN to authenticate against a remote server (the local api-token file never leaves its own data root).`,
    noServer: () => "No running server found for this data root.",
    autoStartUnavailable: () =>
      "No running server found, and this CLI entry cannot auto-start one (development run). Start it yourself with `penguin server`.",
    autoStartFailed: (logPath) =>
      `The auto-started server did not come up. Its output is in ${logPath}.`,
    autoStarted: (url, logPath) => `Started a local server at ${url} (log: ${logPath}).`,
    noToken: (url, tokenPath) =>
      `${url} rejected the request (401) and no API token is available: set ADELIE_API_TOKEN, or make sure the server's token file is readable at ${tokenPath}.`,
    authFailed: (url) =>
      `${url} rejected the API token (401). If the server restarted, its token rotated — check ADELIE_API_TOKEN, or let the CLI read the current api-token file.`,
    httpError: (status, code, message) =>
      `Server error ${status} (${code})${message ? `: ${message}` : ""}`,
    sessionNotFound: (ref, projectId) =>
      `No session matching "${ref}" in project ${projectId} (try \`penguin ls\`).`,
    sessionAmbiguous: (ref, candidates) =>
      `"${ref}" matches ${candidates.length} sessions:\n  ${candidates.join("\n  ")}\nUse a longer fragment or the full id.`,
    streamLost: (detail) => `Lost the server stream and reconnecting failed: ${detail}`,
    streamResynced: () =>
      "[stream] reconnected past the server's replay buffer; some output may be missing here (penguin logs shows the full history)",
    timeoutInvalid: (value) =>
      `Invalid --timeout value "${value}": expected 30s, 5m, 2h, or a bare number of seconds.`,
    stillRunning: (shortId) =>
      `[still running] session ${shortId} continues on the server — follow with \`penguin logs -f ${shortId}\` or poll with \`penguin input ${shortId}\``,
    callerDefaultsFailed: (sessionId) =>
      `[caller context] could not read calling session ${sessionId}; using the plain defaults`,
    latestSession: (sessionId) => `[latest] session ${sessionId}`,
    noSessionsYet: (agentId, projectId) =>
      `Agent ${agentId} has no sessions in project ${projectId} yet: start one with \`penguin run -m "..."\` or \`penguin chat\`.`,
  },
  chatThinkingConfigured: () => "agent default",
  serve: {
    serverDesc:
      "Start the Web service (HTTP API and the built-in frontend, same process); subcommand reset-admin-password resets a forgotten admin password",
    webDesc: "Start the Web service and open the UI in a browser once it is ready",
    port: "Listen port (falls back to the PORT env var, default 4000)",
    host: "Listen address (falls back to the HOST env var, default 127.0.0.1)",
    noOpen: "Do not open a browser automatically",
    restarting: "Restarting the service to apply the update…",
    app: "Open one workflow page as the whole app: <project>/<agent>/<workflow>[/<tab>] (Ctrl+P or Ctrl+Shift+P in the page opens the command palette to leave)",
  },
  auth: {
    desc: "Sign in to an Adelie server from the terminal",
    loginDesc: "Sign in with a password and remember the session",
    statusDesc: "Show the remembered session, if there is one",
    logoutDesc: "Revoke the remembered session and forget it",
    server: "Server URL (default: the server running on this data root)",
    userId: "Account to sign in as (asked for when omitted; default admin)",
    password: "Password (also read from ADELIE_PASSWORD; prompted when neither is given)",
    print: "Also print the session token to stdout",
    accountPrompt: (fallback) => `Account [${fallback}]: `,
    prompt: (userId) => `Password for ${userId}: `,
    emptyPassword: "No password given.",
    noServer: (root) =>
      `No server is running on ${root}, so there is nothing to sign in to \u2014 pass --server <url>.`,
    unreachable: (server, detail) => `Could not reach ${server}: ${detail}`,
    refused: (status, detail) => `The server refused the sign-in (${status}): ${detail}`,
    noCookie: "The server accepted the sign-in but issued no session cookie.",
    loggedIn: (userId, server, file) => `Signed in as ${userId} on ${server}. Saved to ${file}.`,
    notLoggedIn: (file) => `Not signed in (no ${file}).`,
    statusLine: (userId, server) => `Signed in as ${userId} on ${server}.`,
    expires: (when) => `Expires ${when}.`,
    expired: (when) => `Expired ${when} \u2014 sign in again.`,
    loggedOut: (server) => `Signed out of ${server}; the session was revoked there.`,
    loggedOutLocally: (server) =>
      `Forgotten locally, but ${server} could not be reached \u2014 the session may still be valid there until it expires.`,
  },
  authToken: {
    desc: "Mint a short-lived API session token for this data root (for a controller reaching this machine over ssh)",
    userId: "Account to mint for (default: admin)",
    ttlSeconds: "Lifetime in seconds (default: 3600)",
    mark: "Print a fixed marker line before the token, for callers parsing it out of a shell",
    badTtl: "--ttl-seconds must be a positive integer.",
    noServer: (root) =>
      `${root} has no web.db — no server has ever run on this data root, so there is no account to mint for.`,
    failed: (detail) => `Could not mint a token: ${detail}`,
  },
  serverStatus: {
    desc: "Print this data root's server state and machine id as one line of JSON",
  },
  serverStop: {
    desc: "Stop the server running on this data root and report the outcome as JSON",
  },
  resetPassword: {
    desc: "Reset the Web admin account so the next server start prints a new first-login link (the server must be stopped)",
    serverRunning: (url) =>
      `An Adelie server is running on this data root: ${url}\n` +
      `Stop it first, then run \`penguin server reset-admin-password\` again.`,
    noDatabase: (dbPath) =>
      `No Web database at ${dbPath} — nothing to reset. ` +
      `Start the service once (\`penguin web\`) to create the admin account.`,
    noAdmin: () =>
      "The Web database has no admin account yet — nothing to reset. " +
      "Start the service once (`penguin web`) to seed it.",
    done: (root) =>
      `The admin account on data root ${root} was returned to its unclaimed state, and all of its sign-in sessions were revoked.`,
    next: () =>
      "Start the service (`penguin web`): it will print a sign-in link that claims the account — usable until a password is set.",
  },
  version: {
    description: "Show which build is running",
    json: "Print the full build info as JSON (the body of GET /api/version)",
  },
  update: {
    desc: "Upgrade this Adelie install in place",
    check: "Only report the current and latest versions; change nothing",
    releaseOpt:
      "Target a specific release tag instead of the latest (e.g. v0.1.2 or 0.1.2); named --release because -v/--version is the CLI's own version flag",
    yes: "Skip the confirmation prompt",
    checkReport: (current, latest) => `Installed ${current} · latest ${latest}`,
    upgradeAvailable: (target) =>
      `An upgrade is available: run \`penguin update\` to install ${target}.`,
    upToDate: (current) => `Already on the latest version (${current}); nothing to do.`,
    targetIsOlder: (target) =>
      `${target} is older than the installed version — this would be a downgrade.`,
    planTarball: (current, target, installDir, universal) =>
      [
        `Upgrade ${current} -> ${target}`,
        `  how:         re-run the official installer (this install came from the tarball)`,
        `  install dir: ${installDir}${universal ? " (universal package, no bundled Node runtime)" : ""}`,
        `  replaces:    bin, lib, web${universal ? "" : ", node"} — your data dir is NOT touched`,
      ].join("\n"),
    planNpm: (current, target, manager, command) =>
      [
        `Upgrade ${current} -> ${target}`,
        `  how:     global ${manager} install (this install came from ${manager})`,
        `  command: ${command}`,
        `  your data dir is NOT touched`,
      ].join("\n"),
    confirm: () => "Proceed? [y/N] ",
    needsYes: () =>
      "Not running in a terminal, so the confirmation cannot be answered. Re-run with --yes to upgrade non-interactively.",
    cancelled: () => "Cancelled; nothing was changed.",
    done: (version) =>
      `Adelie ${version} installed. Run \`penguin --version\` in a new shell to confirm.`,
    failed: () => "Upgrade failed; the previous install was left in place where possible.",
    sourceCheckout: () =>
      "This penguin runs from a source checkout, so there is nothing to download — update it with `git pull` and rebuild (`pnpm install && pnpm -r build`).",
    desktopApp: () =>
      "This penguin ships inside the Adelie desktop app and is replaced when the app updates — check for updates from the application menu.",
    unknownInstall: (modulePath) =>
      `Cannot tell how this penguin was installed (running from ${modulePath}), so it will not be replaced. Re-install with the official installer, or upgrade with the package manager you used.`,
    npmUnknownManager: (globalRoot, target) =>
      `This is a global install under ${globalRoot}, but the package manager that owns it could not be identified. Upgrade it yourself with that manager, e.g. \`npm install -g @adelie/cli@${target}\`.`,
    windowsUnsupported: () =>
      "The official installer is a POSIX shell script and does not run on Windows. Re-install from the GitHub Releases page, or use a global npm install instead.",
    windowsGlobalInstall: (command) =>
      [
        "On Windows, penguin cannot run your package manager for you: Node will not execute an npm/pnpm/yarn `.cmd` shim without a shell.",
        "Run this yourself in a terminal, then reopen it:",
        `  ${command}`,
      ].join("\n"),
    networkFailed: (url) => `Could not reach ${url}. Check your network and retry.`,
    rateLimited: () =>
      "GitHub rate-limited the release lookup. Wait a few minutes and retry, or pass --release <tag> to skip the lookup.",
    apiFailed: (status) => `The GitHub release lookup failed with HTTP ${status}.`,
    apiMalformed: () =>
      "The GitHub release lookup returned an unexpected response with no usable version tag.",
    invalidDownloadSource: () => "PENGUIN_DOWNLOAD_SOURCE must be auto or github.",
    downloadBaseMustBeHttps: (name) => `${name} must be an absolute HTTPS URL.`,
    installerFetchFailed: (sources) =>
      `Could not download the installer from ${sources
        .map((source) => (source === "configured" ? "the configured mirror" : "GitHub"))
        .join(" or ")}. Check your network and retry.`,
  },

  header: headerEn,
  chatHints: () =>
    "Type a message to start a conversation; end a line with \\; typing while a task runs steers the agent; /goal runs a goal to completion; /compact to compact the context; /clear to start a fresh session; /thinking changes the thinking level; /switch-model <provider> <model_id> switches the model (compacting the context first); /verbose toggles full tool output; /exit to quit; and Ctrl-C interrupts the current conversation.",
  confirmExit: () => "Exit penguin? [y/N] ",
  taskInterrupted: () => "[current conversation interrupted]",
  steerQueued: (text) => `» steering queued (delivered with the next turn): ${text}`,
  steerLinePrefix: () => "↪ user: ",
  error: (message) => `[error] ${message}`,
  approvePrompt: () => "? Approve this tool call? [Y/n] ",
  taskStats: (s) =>
    `[stats] context ${s.context} (${s.contextDelta}) · tokens ${s.tokens} (${s.tokensDelta}) · ${s.elapsed} (${s.elapsedDelta})`,
  abortLabel: (abort) => {
    const cause =
      abort?.errorCode === "user_abort"
        ? "aborted by user"
        : abort?.errorCode === "backoff_interrupted"
          ? "aborted during reconnect backoff"
          : abort?.errorCode === "compaction_interrupted"
            ? "aborted during compaction"
            : (abort?.errorCode ?? abort?.reason ?? "");
    const text = cause ? `${cause}${abort?.errorMessage ? `: ${abort.errorMessage}` : ""}` : "";
    return `[abort]${text ? `: ${text}` : ""}`;
  },
  llmFatalLabel: (errorMessage) =>
    `[error] llm request error${errorMessage ? `: ${errorMessage}` : ""}`,
  reconnectGaveUpLabel: (attempt, errorMessage) =>
    `[retry] giving up after attempt ${attempt}${errorMessage ? `: ${errorMessage}` : ""}`,
  reconnectLabel: (status, attempt, errorCode) =>
    // The live protocol carries the classified cause on error_code; the legacy status
    // spellings say the same thing for pre-convergence Traces.
    `[retry] ${((kind) =>
      kind === "timeout"
        ? "connection timed out"
        : kind === "malformed"
          ? "response incomplete or unparseable"
          : kind === "network"
            ? "network or service temporarily unavailable"
            : kind === "failed"
              ? "the model provider returned an error"
              : "the request failed")(errorCode ?? status)}; sending retry #${attempt}…`,
  compactionStart: (mode, reason) =>
    mode === "discard"
      ? `[compaction] discarding context (${reason})…`
      : `[compaction] summarizing context (${reason})…`,
  mcpConnectStart: (servers) => `[mcp] connecting MCP servers (${servers.join(", ")})…`,
  mcpConnectStop: (durationMs, failures, aborted) =>
    aborted
      ? "[mcp] connect interrupted — reconnects on the next run"
      : failures.length === 0
        ? `[mcp] connected in ${(durationMs / 1000).toFixed(1)}s`
        : `[mcp] connected in ${(durationMs / 1000).toFixed(1)}s; unavailable: ${failures.map((f) => `${f.server} (${f.error})`).join(", ")}`,
  compactionStop: (mode, status, tokens, errorMessage) =>
    (status === "completed"
      ? mode === "discard"
        ? "[compaction] done; old context discarded"
        : "[compaction] done; continuing with the summarized context"
      : status === "aborted"
        ? "[compaction] aborted; keeping the current context"
        : `[compaction] failed${errorMessage !== undefined ? ` (${errorMessage})` : ""}; keeping the current context${
            // retryable = abandoned this time, retried at the next trigger; fatal = a config
            // or credential change has to come first. Legacy Traces spell both "failed".
            status === "retryable"
              ? "; retries at the next trigger"
              : status === "fatal"
                ? "; fix the model configuration to retry"
                : ""
          }`) + (tokens ? ` · tokens ${tokens.total} (${tokens.delta})` : ""),
  compactNothing: () => "[compaction] nothing to compact yet",
  clearDone: () => "[clear] started a fresh session (the previous one is kept and resumable)",
  goalRound: (round) => `[goal] round ${round}`,
  goalFinished: (outcome, rounds, tokens) => {
    const label = {
      complete: "completed",
      blocked: "blocked (see the final reply for what it needs)",
      budget_limited: "stopped: token budget exhausted",
      aborted: "interrupted",
    }[outcome];
    return `[goal] ${label} · ${rounds} round${rounds === 1 ? "" : "s"} · tokens ${tokens}`;
  },
  hookEvent: (name, decision, reason) =>
    `[hook] ${[name, decision, reason].filter(Boolean).join(" · ")}`,
  goalUsage: () => "Usage: /goal[:<budget>] <objective>  (e.g. /goal:500k fix all failing tests)",
  goalBudgetInvalid: (value) =>
    `Invalid token budget "${value}". Use a positive number with an optional k/m suffix (500k, 2m).`,
  goalObjectiveEmpty: () => "Goal mode requires a non-empty objective: pass it via -m.",
  thinkingCurrent: (level) =>
    `[thinking] level: ${level} (this Session's) — change with /thinking <low|medium|high|xhigh|max>`,
  thinkingSet: (level) =>
    `[thinking] level pinned to ${level} for this Session, effective from the next request — changing it invalidates the model's cached context, so /compact first is recommended (the Agent config is unchanged)`,
  thinkingInvalid: (value) =>
    `Invalid thinking level "${value}". Use low, medium, high, xhigh, or max.`,
  switchModelCurrent: (model) =>
    `[model switch] current model: ${model} — switch with /switch-model <provider> <model_id> (the context is compacted on the current model first)`,
  switchModelUsage: () =>
    "Usage: /switch-model <provider> <model_id>  (e.g. /switch-model deepseek deepseek-v4-pro; penguin config model list shows the configured models)",
  switchModelDone: (previous, next) => `[model switch] model: ${previous} → ${next}`,
  switchModelBusy: () =>
    "[model switch] the Session is busy (a task or a compaction is running); switch once it finishes",
  switchModelSame: (model) => `[model switch] already on ${model}; nothing to switch`,
  switchModelNotConfigured: (model, listCommand, addCommand) =>
    `[model switch] ${model} is not in the Project config: ${listCommand} lists the configured models, ${addCommand} adds it`,
  switchModelUnavailable: (model, detail) =>
    `[model switch] ${model} is configured but cannot be used${detail ? `: ${detail}` : ""}`,
  switchModelNoCompaction: () =>
    "[model switch] context compaction is not configured for this Session, and a model switch always compacts first",
  verboseOn: () => "[verbose] on — tool output from here on shows in full",
  verboseOff: () =>
    "[verbose] off — long tool output from here on is collapsed (/verbose to toggle)",
  toolOutputElided: (hidden) => `… (+${hidden} lines, /verbose for full output)`,
  approveModeInvalid: (value) =>
    `Invalid approval mode "${value}". Use allow-all, deny-all, read-only, or always-ask.`,
  approvalDecision: (decision) =>
    decision === "allow"
      ? "✓ [approved]"
      : decision === "forbidden"
        ? "× [forbidden by policy]"
        : "× [denied]",
  modelRefIncomplete: () =>
    "--model-id and --provider must be given together: a model reference is always an explicit (provider, model_id) pair. Omit both to use the Project default model.",
  resumeNoOverride: () =>
    "--resume does not accept --workspace, --model-id or --provider: the resumed Session keeps its own. To change its model, run /switch-model <provider> <model_id> inside the chat (it compacts the context first).",
  resumeNoSession: () => "No session to resume: this agent has no recorded sessions yet.",
  resumedBanner: (sessionId, messageCount) =>
    `[resumed] ${sessionId} · ${messageCount} message${messageCount === 1 ? "" : "s"} in the current context`,
  resumeHint: (command) => `To continue this conversation: ${command}`,
  langInvalid: (value) => `Invalid language "${value}". Use en or zh.`,
  langWindowsUnsupported: (lang) =>
    `penguin config lang persists via POSIX shell startup files, which Windows does not have.\n` +
    `Set the user environment variable instead: setx ADELIE_LANG ${lang} (new terminals pick it up).`,
  langSet: (lang, rcPath) => `Language set to ${lang}; wrote ADELIE_LANG to ${rcPath}.`,
  langRestartConfirm: () => "Open a new shell now to apply? [y/N] ",
  langRestart: () => "Opening a new shell with the new language (type exit to return)…",
  langRestartHint: (rcPath) => `Open a new terminal, or run: source ${rcPath}`,
  modelAdded: (model, def) => `Added model ${model}. Default model: ${def ?? "(unset)"}`,
  modelUpdated: (model, def) => `Updated model ${model}. Default model: ${def ?? "(unset)"}`,
  defaultModelSet: (model) => `Default model set to ${model}.`,
  visionModelSet: (model) => `Vision model set to ${model}.`,
  modelRemoved: (model, def) => `Removed model ${model}. Default model: ${def ?? "(unset)"}`,
  modelNotConfigured: (model) => `Model ${model} is not in the Project config.`,
  modelNotRoutable: (model) =>
    `Model ${model} cannot be routed: a vendor group carries built-in models only. ` +
    `Add it under a custom group (--provider custom) with --client-type and --base-url, ` +
    `or pass --client-type to pin the protocol this model speaks.`,
  modelNotAddable: (model, group) =>
    `Model ${model} cannot be added: the ${group} group carries its built-in models only. ` +
    `Add it under a custom group (--provider custom, or a group name of your own) ` +
    `with --client-type and --base-url.`,
  visionModelCleared: () => "It was also the vision model; that setting is now unset.",
  modelListTitle: () => "Configured models:",
  modelListEmpty: () => "No models configured yet. Add one with `penguin config model add`.",
  vaultSet: (key) =>
    `Saved vault entry ${key}. New conversations pick it up right away; running ones after their next compaction.`,
  vaultRemoved: (key) =>
    `Removed vault entry ${key}. New conversations pick it up right away; running ones after their next compaction.`,
  vaultKeyMissing: (key) => `Vault entry ${key} does not exist.`,
  vaultListTitle: () => "Vault environment variables (values masked):",
  vaultListEmpty: () => "The vault is empty. Add one with `penguin config vault set`.",
  webReady: (url) => `Web UI ready: ${url}`,
  serverAlreadyRunning: (url) =>
    `An Adelie server is already running on this data root: ${url}\n` +
    `Stop it first, or point ADELIE_HOME at a separate data root.`,
  webAlreadyRunning: (url) =>
    `Already running on this data root — opening the existing instance: ${url}`,
  webProbeFailed: (url, detail, kind, port) => {
    const hint = {
      timeout:
        `The connection timed out. Check whether a firewall or security application is blocking it. ` +
        `Allow Adelie to communicate on local port ${port}.`,
      refused:
        "Nothing accepted the connection. Check whether the server exited or HOST/PORT points somewhere else.",
      reset:
        "The connection closed before an HTTP response. Check local security software and retry.",
      permission:
        "The operating system denied the connection. Check firewall or security policy permissions.",
      dns: "The host name could not be resolved. Check --host or HOST.",
      unknown: `Open ${url} manually after the server is ready.`,
    }[kind];
    return `Server readiness check failed for ${url}.\nLast probe error: ${detail}\n${hint}`;
  },
};

const zh: Messages = {
  cliDescription: "Adelie CLI",
  versionDesc: "输出版本号",
  common: {
    projectId: "Project id",
    agentId: "Agent id",
    modelId: "本次使用的模型(上游模型 id;默认 Project 默认模型)",
    provider: "--model-id 的 provider 分组;给出 --model-id 时必须一并给出(分组不作任何推断)",
    root: "数据根目录(优先于 ADELIE_HOME 与 ~/.adelie/data)",
    workspace: "Workspace 目录,须为已存在目录(默认当前目录)",
    approve:
      "审批模式:allow-all(全部放行,缺省)、deny-all(全部拒绝)、read-only(自动放行只读工具,其余仍逐个询问)、always-ask(逐个询问)",
    thinking: "本会话的思考等级:low、medium、high、xhigh 或 max(缺省用 Agent 配置的等级)",
    json: "输出原始 JSON,不做渲染",
    server: "要连接的服务器地址(缺省依次取 ADELIE_API_URL、本机运行中的服务器、自动拉起)",
    timeout:
      "最长等待时长(30s / 5m / 2h,或纯数字秒数);到时脱开、任务继续在服务端运行(退出码 0)",
    latestAgentId: "省略 session id 时,取哪个 Agent 的最近一次会话",
  },
  usage: {
    missingArgument: (name) => `缺少必填参数 <${name}>`,
    missingOption: (flags) => `缺少必填选项 ${flags}`,
    optionMissingArgument: (flags) => `选项 ${flags} 缺少取值`,
    unknownOption: (flag) => `未知选项 ${flag}`,
    unknownCommand: (name) => `未知命令 ${name}`,
    other: (detail) => detail,
    hint: (command, usage) =>
      `用法:${command} ${usage}(运行 \`${command} --help\` 查看全部选项)`,
  },
  config: {
    desc: "管理 Project 配置",
    modelDesc: "管理模型 credential 与默认模型",
    addDesc: "新增或更新一个模型,并可写入 credential",
    addModelId: "上游模型 id(如 claude-sonnet-4-6,原样发给 AgentHub)",
    addProvider: "与 model_id 分列存储的 provider 分组;必填,不作推断(无厂商分组时填 custom)",
    addApiKey: "API key,内联存入 Project 的隐藏文件 .project_config.toml",
    addBaseUrl: "自定义 base url",
    addContextWindow: "上下文窗口大小(token 数)",
    addMaxTokens:
      "该模型的最大输出长度(正整数);设置后覆盖 Agent 的 max_tokens,缺省沿用——小上下文模型建议调低",
    addClientType: "AgentHub 客户端协议(如 openai-chat);缺省按 provider 分组的语义取值",
    addVision: "标注该模型支持图片输入(视觉)",
    addNoVision: "标注该模型不支持图片输入;两者都不给则保留原值",
    addFastMode: "开启快速模式:输出更快、按溢价计费(不支持 fast 档位的模型会拒绝请求)",
    addNoFastMode: "关闭快速模式(缺省即关闭);两者都不给则保留原值",
    fastModeUnsupported: (ref: string): string =>
      `警告:${ref} 不支持快速模式——AgentHub 为它选用的 client 会拒绝该参数,其请求都会失败。请用 --no-fast-mode 重新执行以关闭。`,
    addPriceCacheRead: "每百万 token 价格:缓存命中(USD)",
    addPriceCacheWrite: "每百万 token 价格:缓存未命中(USD)",
    addPriceOutput: "每百万 token 价格:输出(USD)",
    addSetDefault: "同时设为该 Project 的默认模型",
    defaultDesc: "设置 Project 的默认模型",
    visionDesc: "设置代读图片的视觉模型(不支持图片的会话模型用 read_file 读图时由它代读)",
    refModelId: "上游模型 id;与 --provider 构成 (provider, model_id) 成对引用",
    refProvider: "引用条目的 provider 分组(见 `penguin config model list`)",
    listDesc: "列出当前 Project 的模型(API key 隐藏)",
    removeDesc: "从当前 Project 删除一个模型(指向它的默认模型 / 视觉模型设置一并清空)",
    langDesc: "设置界面语言(en|zh);将 ADELIE_LANG 写入 shell 启动文件并持久化",
    langArg: "语言:en 或 zh",
    vaultDesc: "管理 Agent vault(注入该 Agent shell 命令的环境变量)",
    vaultSetDesc: "写入一个 vault 环境变量(不存在则新增,存在则覆盖)",
    vaultListDesc: "列出 vault 环境变量(值掩码显示)",
    vaultRemoveDesc: "删除一个 vault 环境变量",
    vaultKey: "变量名(字母、数字与下划线,不能以数字开头)",
    vaultValue: "变量值,写入该 Agent 的 agent_state/.vault.toml",
  },
  run: {
    desc: "单次运行一个 Task",
    message: "本次 Task 的 Prompt",
    goal: "目标模式:循环运行直至目标完成;可选 token 预算(如 500k、2m)",
    session: "复用既有 Session(完整 id 或唯一片段,如末尾 8 位十六进制)",
    background: "提交任务后立即退出,打印 session id",
    sessionNoOverride: () =>
      "--session 复用既有 Session:不能与 --workspace、--model-id、--provider 同时使用(均沿用该 Session;如需换模型,在 penguin chat --resume 内用 /switch-model,会先压缩上下文)。",
    sourceInvalid: (value) =>
      `无效的 --source 取值 "${value}"。penguin run 不再接受 --source:它创建的每个会话都是 CLI 会话。`,
    sourceIgnored: () =>
      "--source benchmark 已不再需要,已忽略:penguin run 创建的每个会话都是 CLI 会话,列在 Web App 的「后台会话」折叠夹中。",
    timeoutWithBackground: () => "--timeout 限定等待,而 --background 不等待:二者去其一。",
  },
  chat: {
    desc: "打开交互式 REPL",
    resume:
      "恢复既有 Session 继续对话(缺省恢复当前 Agent 最近一次);Workspace 与模型沿用原 Session(会话内可用 /switch-model 切换模型,会先压缩上下文)",
    verbose: "显示完整工具输出(缺省折叠过长的工具输出、只保留首尾数行;/verbose 可随时切换)",
  },
  ls: {
    desc: "列出 Project 的会话(未指定 --agent-id 时覆盖全部 Agent)",
    all: "包含已归档会话",
    days: "只列最近 <n> 个自然日内活跃过的会话(今天算第 1 天)",
    daysInvalid: (value) => `--days 值「${value}」无效:应为正整数。`,
    empty: (projectId) => `Project ${projectId} 还没有会话。`,
    colId: () => "ID",
    colAgent: () => "AGENT",
    colTitle: () => "标题",
    colState: () => "状态",
    colLast: () => "最近活动",
    colWorkspace: () => "WORKSPACE",
    stateIdle: () => "空闲",
    stateRunning: () => "运行中",
  },
  input: {
    desc: "向会话发送消息(运行中即插话,空闲时发起新 Task);不带 -m 时输出其最近一条助手回复。省略 session id 即取当前 Agent 最近一次会话",
    message: "消息文本(省略时改为轮询该会话的最近助手回复)",
    noReplyYet: () => "(还没有助手回复)",
  },
  logs: {
    desc: "渲染会话的历史消息(省略 session id 即取当前 Agent 最近一次会话)",
    tail: "只显示最后 <n> 条",
    follow: "渲染历史后继续跟随实时输出流",
    tailInvalid: (value) => `--tail 值「${value}」无效:应为正整数。`,
    timeoutNeedsFollow: () => "--timeout 只与 -f/--follow 搭配:不跟随时 logs 不等待。",
  },
  agent: {
    desc: "管理 Project 的 Agent",
    lsDesc: "列出 Project 的 Agent",
    createDesc: "创建 Agent",
    createId: "Agent id(即目录名;字母、数字、下划线)",
    createName: "显示名(缺省同 id)",
    createDescription: "描述",
    createPlugins: "预装的插件库插件,逗号分隔(如 software-development,goal)",
    created: (agentId, projectId) => `已在 Project ${projectId} 创建 Agent ${agentId}。`,
    colId: () => "ID",
    colName: () => "名称",
    colSessions: () => "会话数",
    colDescription: () => "描述",
    apiDesc: "管理 Agent 的对外 API:开关、无密钥访问、审批模式与密钥",
    apiStatusDesc: "查看 Agent 的 API 设置、访问地址与服务器总开关",
    apiEnableDesc: "开启 Agent 的 API 访问",
    apiDisableDesc: "关闭 Agent 的 API 访问(设置与密钥保留)",
    apiSetDesc: "更改无密钥访问或审批模式,不改变开关",
    apiOpen: "允许无密钥访问:任何能访问服务器的程序都能与该 Agent 对话",
    apiNoOpen: "要求密钥",
    apiApprove:
      "新建 API 会话使用的审批模式:allow-all、deny-all、read-only 或 always-ask(需要确认时发给调用方)",
    apiNothingToSet: () => "没有要更改的内容:请给出 --open、--no-open 或 --approve <mode>。",
    apiKeysDesc: "管理 Agent 的 API 密钥",
    apiKeysLsDesc: "列出 Agent 的 API 密钥",
    apiKeysCreateDesc: "新建 API 密钥;密钥只输出一次,单独占据 stdout",
    apiKeysRmDesc: "删除 API 密钥;使用它的程序此后会被拒绝",
    apiKeyName: "密钥名称(1–64 个字符)",
    apiServerDesc: "为整个服务器开启或关闭 Agent API(仅管理员)",
    apiServerStateInvalid: (value) => `状态「${value}」无效:应为 on 或 off。`,
    apiStatusTitle: (agentRef) => `${agentRef} 的 Agent API`,
    apiFieldEnabled: () => "已开启",
    apiFieldOpen: () => "无密钥访问",
    apiFieldApproval: () => "审批模式",
    apiFieldBaseUrl: () => "Base URL",
    apiFieldAgentId: () => "Agent ID",
    apiFieldKeys: () => "密钥数",
    apiFieldServer: () => "服务器总开关",
    apiYes: () => "是",
    apiNo: () => "否",
    apiServerOn: () => "开",
    apiServerOff: () => "关(所有 API 请求均被拒绝)",
    apiColKeyId: () => "ID",
    apiColKeyName: () => "名称",
    apiColPrefix: () => "前缀",
    apiColCreated: () => "创建时间",
    apiColLastUsed: () => "最近使用",
    apiKeyNever: () => "从未",
    apiKeysEmpty: (agentRef) => `${agentRef} 还没有 API 密钥。`,
    apiKeyCreated: (name, prefix, agentRef) =>
      `已为 ${agentRef} 新建密钥「${name}」(${prefix}…)。密钥只在上方显示这一次,请立即保存。`,
    apiKeyDeleted: (keyId, agentRef) => `已删除 ${agentRef} 的密钥 ${keyId}。`,
    apiServerSet: (on) =>
      on
        ? "这台服务器的 Agent API 已开启。"
        : "这台服务器的 Agent API 已关闭:所有请求均被拒绝,各 Agent 的设置与密钥保留。",
    apiSignInRequired: () =>
      "请先登录:`penguin auth login`(或在服务器本机运行 `penguin auth token`)。本机 API token 不能改变 Agent 的对外暴露。",
    apiOpenWarning: () =>
      "警告:已开启无密钥访问。任何能访问此服务器地址的程序现在都无需密钥即可与该 Agent 对话,用的是本 Project 的模型与凭据。仅建议在只监听本机的服务器上保持开启;`--no-open` 可关闭。",
  },
  project: {
    desc: "管理 Project",
    lsDesc: "列出当前账号可用的 Project",
    colId: () => "ID",
    colName: () => "名称",
    colRole: () => "角色",
  },
  cost: {
    desc: "查看 Token 用量与成本(缺省打印汇总卡片;--by 打印分组表格)",
    days: "最近 n 天(自动换算为 --from/--to)",
    from: "起始日期(yyyy-mm-dd);须与 --to 成对",
    to: "结束日期(yyyy-mm-dd);须与 --from 成对",
    by: "分组维度:date、agent、model 或 session",
    rangeIncomplete: () => "--from 与 --to 必须成对给出。",
    daysInvalid: (value) => `--days 值「${value}」无效:应为正整数。`,
    byInvalid: (value) => `--by 值「${value}」无效:应为 date、agent、model 或 session。`,
    today: () => "今日",
    last7d: () => "近 7 天",
    total: () => "累计",
    empty: () => "该范围内没有用量记录。",
    noPricing: () => "-",
    colTokens: () => "TOKEN",
    colRequests: () => "请求数",
    colCost: () => "成本",
    colGroup: (dimension) => dimension.toUpperCase(),
  },
  storage: {
    desc: "查看数据根被什么占满(只读:本命令不删除任何东西)",
    top: "打印多少条候选(0 表示全部)",
    topInvalid: (value) => `--top 只能是 0 或正整数,收到 "${value}"。`,
    heading: (root, total, disk) =>
      disk === null
        ? `数据根 ${root} · 账本合计 ${total} · 磁盘信息不可用`
        : `数据根 ${root} · 账本合计 ${total} · 磁盘剩余 ${disk.free} / ${disk.total}(已用 ${disk.usedPercent}%)`,
    lowFree: (free) =>
      `磁盘余量偏低(剩 ${free})。下面列出的是候选,需要你审核具体清单之后才会清理,本命令不会动手。`,
    colClass: () => "类别",
    colBytes: () => "占用",
    colFiles: () => "文件数",
    colEntries: () => "条目",
    colCandidates: () => "可清理",
    candidateCell: (entries, bytes) => `${entries} 条(${bytes})`,
    candidatesHeading: () =>
      "可清理候选 —— 这是一份清单,不是待办:没有你的批准,任何东西都不会被删除。",
    candidatesEmpty: () => "按当前阈值没有候选。",
    colModified: () => "最后改动",
    colRules: () => "命中规则",
    colPath: () => "路径",
    moreCandidates: (n) => `…另有 ${n} 条未打印(用 --top 提高上限,--top 0 打印全部)。`,
    candidateCosts: () =>
      "各代价先说清:会话草稿 —— 旧消息里的附件图片不再能预览;轨迹 —— 历史回放与成本页失去重建依据;工具环境 —— 下次用到要重新装;临时工作区 —— 里面的东西会随它一起走。",
    unknownDate: () => "未知",
    groupsHeading: () => "看起来是同一套工具链装了多份的环境(仅报告,合并需要你手动触发一次):",
    groupKind: (kind) => (kind === "name" ? "同名" : "同结构"),
    groupLine: (kind, key, members, bytes) =>
      `- ${kind}(${key}):${members} 个环境,合计 ${bytes}`,
    unreadableHeading: () => "读不到的部分(所以上面的合计是下限,不是精确值):",
    modeOffNotice: () =>
      "只读报告:清理模式未开启,这里没有任何操作会移动文件。下一步是审核一份清单 —— penguin storage scan。没有任何定时任务在跑。",
    modeOnNotice: () =>
      "清理模式已开启。用 penguin storage scan 生成账单;用 penguin storage apply <账单 id> --path <路径> 把你选中的条目移入回收站。这里不删数据,也没有任何定时任务在跑。",
    className: (key) =>
      key === "protected"
        ? "用户资产"
        : key === "tmp_workspaces"
          ? "临时工作区"
          : key === "session_drafts"
            ? "会话草稿"
            : key === "traces"
              ? "轨迹"
              : key === "shared_env"
                ? "工具环境"
                : key === "trash"
                  ? "回收站"
                  : key === "database"
                    ? "数据库"
                    : "其他",
    ruleLabel: (rule) =>
      rule === "empty"
        ? "空目录"
        : rule === "unreferenced"
          ? "无引用"
          : rule === "orphan"
            ? "会话已删除"
            : rule === "idle"
              ? "静默超期"
              : "超出预算",
    scanDesc: "扫描数据根并写出一份可审核的账单(只读;需要先开启清理模式)",
    planDesc: "读回一份账单;不给 id 时列出最近的几份",
    applyDesc: "把你指定的条目移入回收站:必须给出账单里的路径(没有 --yes,也不能一次清空全部)",
    applyPath: "账单里的一条路径(可重复给出,或用逗号分隔)",
    applyAll: "移动这份账单里本版本可以移动的全部条目(账单会标出哪些是)",
    applyNoSelection: () =>
      "没有选中任何条目:用 --path <路径> 逐条给出你审核过的项,或用 --all 选中账单里全部可清理项。",
    applyNothing: () => "什么都没移动(原因见上面的失败项)。",
    applyMoved: (moved, bytes, trashId) =>
      `已把 ${moved} 个条目(${bytes})移入回收站 ${trashId}。`,
    applyFailedLine: (path, reason) => `  未移动:${path} —— ${reason}`,
    trashDesc: "清理把东西搬去的去处:列出、还原、或彻底清除",
    trashListDesc: "列出此前清理搬走的东西(列出本身不会删除任何东西)",
    trashRestoreDesc: "把某个回收站条目的内容放回原处",
    trashPurgeDesc: "彻底删除一个回收站条目:给 id 删那一个,不给则删所有超过保留期的",
    trashEmpty: () => "回收站是空的。",
    trashRestored: (id, restored, remaining) =>
      `已从 ${id} 还原 ${restored} 个条目。${remaining ? "放不回去的部分仍留在该条目里。" : ""}`,
    trashSkippedLine: (path, reason) => `  未还原:${path} —— ${reason}`,
    trashPurgeNothing: () => "没有可清除的条目(没有超过保留期的)。",
    trashPurgedLine: (id, bytes) => `已清除 ${id}(${bytes})。`,
    trashTtlDays: (days) => `${days} 天`,
    expired: (ttl) => `已过保留期(${ttl})`,
    modeDesc: "查看清理模式,或开启/关闭它(默认关闭;关闭时任何清理写操作都会被拒绝)",
    modeUsage: () => "用法:penguin storage mode [on|off]",
    modeIs: (enabled, ttlDays, pins) =>
      `清理模式当前为${enabled ? "开启" : "关闭"}。回收站保留 ${ttlDays} 天,已保留(pin)${pins} 条路径。`,
    modeSet: (enabled, ttlDays, pins) =>
      `清理模式已${enabled ? "开启" : "关闭"}。回收站保留 ${ttlDays} 天,已保留(pin)${pins} 条路径。`,
    billHeading: (id, entries, bytes, expires) =>
      `账单 ${id} · ${entries} 个条目 · ${bytes} · 审核后用 penguin storage apply 批准 · 有效期至 ${expires}`,
    billEmpty: () => "按当前阈值没有候选。",
    billExcluded: (n) => `有 ${n} 条路径已被 pin,未进入本账单。`,
    billReportOnly: (classes) =>
      `本版本只能移动${classes.join("、")};其余条目出现在账单里供阅读,不会被选中。`,
    billNotice: (id) =>
      `尚未移动任何东西。批准你选中的条目:penguin storage apply ${id} --path <路径>(或 --all)。`,
    billSpent: (id) =>
      `账单 ${id} 已不可执行(已用过,或超过有效期)。重新扫描即可得到新账单:penguin storage scan。`,
    reportOnlyMark: () => "—",
    moveMark: () => "✓",
    plansEmpty: () => "还没有生成过账单(penguin storage scan)。",
    planStateOpen: () => "待审核",
    planStateApplied: (at) => `已执行 ${at}`,
    planStateExpired: (at) => `已过期 ${at}`,
    colExecutable: () => "可移动",
    colPlanId: () => "账单",
    colCreated: () => "创建时间",
    colState: () => "状态",
    colTrashId: () => "回收站",
    colItems: () => "条目",
    colExpired: () => "保留期",
  },
  schedule: {
    desc: "管理定时任务",
    lsDesc: "列出 Project 的定时任务(未指定 --agent-id 时覆盖全部 Agent)",
    addDesc: "创建定时任务(经 API 写入任务文件;缺省即启用——用 --disabled 关闭)",
    updateDesc: "更新定时任务(读改写:未指定的字段保留存储值)",
    rmDesc: "删除定时任务(不做确认;服务端的 owner 授权照旧生效)",
    prompt: "每次触发要发送的内容",
    startAt:
      "首次触发时刻(ISO 8601),或字面量 `now` 表示当前时刻;一次性任务须用未来时刻,`now` 只适用于带 --period 的任务",
    period: "固定间隔,下限 5m(如 30m、12h、1d、7d);省略即一次性任务",
    endAt: "此时刻之后不再触发(ISO 8601)",
    sessionId: "绑定到某个会话触发(与 --workspace / 模型对互斥)",
    workspace: "新建会话模式:每次触发所用 Workspace(省略即自动创建临时工作区)",
    disabledOpt: "以停用状态创建(CLI 缺省为启用)",
    enableOpt: "启用该任务",
    disableOpt: "停用该任务",
    enableDisableConflict: () => "--enable 与 --disable 互斥。",
    targetConflict: () =>
      "--session-id 与新建会话形式(--workspace / --model-id / --provider)互斥:目标二选一。",
    written: (name, enabledText, nextFireAt) =>
      `定时任务 ${name} 已写入(${enabledText}${nextFireAt !== undefined ? `,下次触发 ${nextFireAt}` : ""})。`,
    removed: (name) => `定时任务 ${name} 已删除。`,
    enabled: () => "开",
    disabled: () => "关",
    oneShot: () => "一次性",
    newSession: () => "新建会话",
    empty: (projectId) => `Project ${projectId} 没有定时任务。`,
    colName: () => "名称",
    colEnabled: () => "启用",
    colStartAt: () => "开始时刻",
    colPeriod: () => "周期",
    colTarget: () => "目标",
    colLastFired: () => "最近触发",
    colStatus: () => "状态",
  },
  org: {
    desc: "公司模式:管理组织(员工、工位、日程、工单、频道、财务)",
    lsDesc: "列出 Project 的组织",
    createDesc: "创建组织:生成 CEO Agent、开 CEO 的工位会话并发起初始化会话",
    showDesc: "概览:员工与状态、看板计数、预算占用、待处理事项",
    chartDesc: "员工树:头衔、状态、支出与预算",
    hireDesc: "招募员工:既有 Agent(--agent-id)或新建 Agent(--new-agent),汇报给 --reports-to",
    employeeDesc: "管理员工",
    employeeSetDesc: "更新员工树条目(只改动给出的字段)",
    leaveDesc: "将员工移出组织(CEO 不可);Agent 本身保留",
    deskDesc: "工位会话(每位员工一个常设会话)",
    deskShowDesc: "员工的工位会话 id 与 Workspace(尚无工位时开一个)",
    deskRenewDesc: "为员工换一个新的工位会话(重置上下文)",
    calendarDesc: "日程项(定时发往员工工位会话的任务)",
    calendarLsDesc: "列出组织的日程项(--agent-id 限定为某位员工)",
    calendarAddDesc: "创建日程项(经 API 写入日程文件;缺省即启用——用 --disabled 关闭)",
    calendarUpdateDesc: "更新日程项(读改写:未指定的字段保留存储值)",
    calendarRmDesc: "删除日程项(不做确认)",
    ticketDesc: "看板上的工单",
    ticketLsDesc: "列出看板工单(--status / --owner / --blocked 在本地过滤)",
    ticketShowDesc: "查看工单:先打印派生数据,再打印工单文件",
    ticketCreateDesc: "在 proposed 列创建工单",
    ticketMoveDesc: "把工单移到另一列(移入 rejected 须给 --reason)",
    ticketAssignDesc: "设置工单负责人",
    ticketBlockDesc: "标记工单为阻塞(留在所在列)",
    ticketUnblockDesc: "清除工单的阻塞状态",
    ticketProgressDesc: "追加一条进展(记为当前会话所写)",
    ticketStartDesc:
      "新开一个在后台处理该工单的工单会话;打印会话 id。只有工单的负责人(其工位)或人可以发起——要交给别的员工,改派负责人",
    ticketAttachDesc: "把既有会话挂为贡献会话(缺省当前会话)",
    channelDesc: "组织的频道(default_channel 是全员频道,所有人都在其中)",
    channelLsDesc: "列出频道:人看到全部频道,员工只看到自己所在的",
    channelCreateDesc: "新建频道;初始成员只有创建者,其余人经邀请加入",
    channelShowDesc: "查看频道及其成员",
    channelInviteDesc: "邀请若干 principal 加入频道(任一成员均可)",
    channelJoinDesc: "自行加入频道(仅限人;员工只能等成员邀请)",
    channelLeaveDesc: "退出频道",
    channelRemoveDesc: "把另一位成员移出频道(仅限人)",
    channelArchiveDesc: "归档频道:在取消归档前只读(仅限人)",
    channelUnarchiveDesc: "取消频道的归档(仅限人)",
    channelTailDesc: "打印某个频道某一天的最后若干条消息(未给 -n 时 20 条)",
    channelSendDesc: "向频道发送消息(@agent:<id> / @all 提及频道成员并触发其工位)",
    handbookDesc: "组织手册:handbook/ 下的知识库,其 README.md 是每轮先读的索引",
    handbookListDesc: "列出手册文件(路径、大小、更新时间),索引在前",
    handbookShowDesc: "打印一份手册文档(不给路径时打印索引)",
    handbookWriteDesc: "用 -m 或 --file 的内容创建或替换一份手册文档",
    handbookRmDesc: "删除一份手册文档(索引不可删)",
    financeDesc: "支出:按员工(沿汇报线累计)与按工单,对照预算",
    orgId: "组织 id(缺省取 ADELIE_ORG_ID,工位会话与工单会话内自带;此外没有缺省值)",
    newOrgId: "要创建的组织 id(字母、数字、下划线;同时是目录名)",
    mission: "组织的使命",
    orgName: "显示名(缺省同 id)",
    orgLanguageOption: "组织书写一切内容所用的工作语言:zh 或 en(缺省取使命本身的语言)",
    hireAgentId: "招募这个既有 Agent(与 --new-agent 互斥)",
    newAgent: "以此 id 新建 Agent 并招募(与 --agent-id 互斥)",
    newAgentName: "新 Agent 的显示名",
    newAgentDescription: "新 Agent 的描述",
    skills: "新 Agent 额外的插件库插件,逗号分隔(在 agent-company,agent-development 之上追加)",
    title: "头衔",
    reportsTo: "上级的 Agent id",
    employeeWorkspace: "Workspace:公共工作区的子目录(. 即整个工作区)或绝对路径,原样写入",
    hireWorkspace:
      "Workspace:公共工作区的子目录或绝对路径,原样写入(缺省为以该员工命名的子目录)",
    budget: "月预算(美元),含该员工及其全部下属",
    ceoBudget: "CEO 的月预算(美元);预算沿汇报线累计,CEO 的预算就是整家公司的",
    duties: "职责描述",
    calendarAgentId: "日程项所属员工(缺省 ADELIE_AGENT_ID);ls 上只列该员工的日程项",
    calendarTitle: "日程项标题",
    statusFilter: "只看这一列:proposed、in_progress、review、done 或 rejected",
    ownerFilter: "只看该负责人的工单(agent:<id> / user:<id>)",
    blockedFilter: "只看被阻塞的工单",
    ticketTitle: "工单标题",
    ticketSlug: "工单 id 的词:小写英文单词,用连字符连接",
    goal: "目标,所依赖的输入一律写完整路径(与 --body-file 互斥)",
    criteria: "验收标准,预期交付物一律写完整路径(与 --goal 配合)",
    bodyFile: "从文件读取整个 Markdown 正文(头部仍由服务端生成)",
    owner: "负责人(agent:<id> / user:<id>);create 时缺省为调用方",
    parent: "父工单 id",
    notify: "工单结束时通知的对象,逗号分隔",
    priority: "优先级:P0、P1 或 P2",
    due: "截止日期(yyyy-mm-dd)",
    moveTo: "目标列:proposed、in_progress、review、done 或 rejected",
    moveReason: "原因(移入 rejected 时必填;记入 Result)",
    blockReason: "阻塞原因",
    blockedBy: "在等谁或等哪个工单(principal 或工单 id)",
    progressText: "进展内容,涉及的文件一律写完整路径",
    startMessage: "附在工单正文之后、随会话首条输入发出的附言",
    startWorkspace: "公共工作区内的另一个目录(缺省为该员工工位的 Workspace)",
    startAgentId:
      "会话以哪名员工的身份运行:可以拉同事来做自己名下的工单(会话内缺省为你自己,否则为工单负责人)",
    attachSession: "要挂接的会话,完整 id 或唯一片段(缺省 ADELIE_SESSION_ID)",
    channelOpt: "要读取或写入的频道(缺省 default_channel,即全员频道)",
    channelName: "显示名(缺省同 id)",
    channelPurpose: "频道用途",
    channelDate: "要读的日期(组织时区的 yyyy-mm-dd;缺省今天)",
    channelCount: "打印的消息条数(缺省 20)",
    channelText: "消息内容(@agent:<id> 或 @all 表示提及,只能提及频道内的成员)",
    handbookPath: "相对 handbook/ 的路径(普通片段,如 decisions/2026-09-02-hire-plan.md)",
    handbookText: "文档内容",
    handbookFile: "从本地文件读取文档内容",
    handbookOneSource: "-m <text> 与 --file <file> 只能给一个。",
    refTicket: "消息关联的工单",
    refSession: "消息关联的会话",
    period: "统计月份(yyyy-mm;缺省当月)",
    orgIdMissing: () =>
      "未指定组织:请传 --org-id <id>,或设置 ADELIE_ORG_ID(工位会话与工单会话的环境里自带)。",
    hireTargetConflict: () =>
      "--agent-id(既有 Agent)与 --new-agent(新建)二选一,且必须给一个。",
    newAgentFieldsOnly: () => "--name、--description 与 --skills 只用于描述 --new-agent。",
    budgetInvalid: (flag, value) => `${flag} 值「${value}」无效:应为非负的美元金额。`,
    nothingToSet: () => "没有要更新的内容:至少给出一个字段。",
    languageInvalid: (value) => `--language 值「${value}」无效:应为 zh 或 en。`,
    statusInvalid: (value) =>
      `列名「${value}」无效:应为 proposed、in_progress、review、done 或 rejected。`,
    priorityInvalid: (value) => `--priority 值「${value}」无效:应为 P0、P1 或 P2。`,
    ticketBodyConflict: () => "--goal 与 --body-file 二选一,且必须给一个。",
    criteriaNeedsGoal: () => "--criteria 须与 --goal 一起使用。",
    bodyFileUnreadable: (file) => `无法读取 --body-file ${file}。`,
    countInvalid: (value) => `-n 值「${value}」无效:应为正整数。`,
    pathSegmentInvalid: (value) => `名称「${value}」无效:「.」与「..」既不是 id,也不是手册路径。`,
    attachSessionMissing: () =>
      "没有可挂接的会话:请传 --session <id>,或在会话内运行(ADELIE_SESSION_ID)。",
    created: (orgId, ceoDeskSessionId) =>
      `已创建组织 ${orgId}${ceoDeskSessionId !== undefined ? `(CEO 工位会话 ${ceoDeskSessionId})` : ""}。`,
    hired: (agentId, title, reportsTo) =>
      `已招募员工 ${agentId},头衔 ${title}${reportsTo !== null ? `,汇报给 ${reportsTo}` : ""}。`,
    employeeUpdated: (agentId) => `已更新员工 ${agentId}。`,
    left: (agentId) => `员工 ${agentId} 已离开组织。`,
    desk: (agentId, sessionId, workspace, openedAt, created) =>
      `${agentId} 的工位:会话 ${sessionId}(Workspace ${workspace},开于 ${openedAt})${created ? "——刚刚新开" : ""}`,
    deskRenewed: (agentId, sessionId) => `${agentId} 的工位已换新:会话 ${sessionId}。`,
    calendarWritten: (agentId, name, enabledText, nextFireAt) =>
      `日程项 ${agentId}/${name} 已写入(${enabledText}${nextFireAt !== undefined ? `,下次触发 ${nextFireAt}` : ""})。`,
    calendarWarning: (warning) => `排班提醒:${warning}`,
    calendarRemoved: (agentId, name) => `日程项 ${agentId}/${name} 已删除。`,
    ticketCreated: (ticketId, status) => `已创建工单 ${ticketId}(${status})。`,
    ticketMoved: (ticketId, status) => `工单 ${ticketId} 已移到 ${status}。`,
    ticketAssigned: (ticketId, owner) => `工单 ${ticketId} 已指派给 ${owner}。`,
    ticketBlocked: (ticketId) => `工单 ${ticketId} 已标记为阻塞。`,
    ticketUnblocked: (ticketId) => `工单 ${ticketId} 已解除阻塞。`,
    progressRecorded: (ticketId) => `已在工单 ${ticketId} 记录进展。`,
    ticketAttached: (ticketId, sessionId) => `会话 ${sessionId} 已挂接到工单 ${ticketId}。`,
    channelCreated: (channelId) => `已创建频道 ${channelId}。`,
    channelInvited: (channelId, principal) => `已邀请 ${principal} 加入 ${channelId}。`,
    channelJoined: (channelId) => `已加入 ${channelId}。`,
    channelLeft: (channelId) => `已退出 ${channelId}。`,
    channelMemberRemoved: (channelId, principal) => `已把 ${principal} 移出 ${channelId}。`,
    channelArchived: (channelId) => `频道 ${channelId} 已归档。`,
    channelUnarchived: (channelId) => `频道 ${channelId} 已取消归档。`,
    messageSent: (id) => `消息 ${id} 已发送。`,
    handbookWritten: (path) => `手册文档 ${path} 已写入。`,
    handbookRemoved: (path) => `手册文档 ${path} 已删除。`,
    empty: (projectId) => `Project ${projectId} 没有组织。`,
    calendarEmpty: () => "没有日程项。",
    ticketsEmpty: () => "没有匹配的工单。",
    channelsEmpty: () => "没有频道。",
    channelEmpty: (channelId, date) => `${channelId} 在 ${date} 没有消息。`,
    showHead: (name, orgId, status) => `${name}(${orgId})——${status}`,
    showMission: (mission) => `使命:${mission}`,
    showLanguage: (language) => `工作语言:${language}`,
    showEmployees: (count, running, paused) =>
      `员工:${count}(运行中 ${running},已暂停 ${paused})`,
    showBoard: (counts, blocked) => `看板:${counts}(阻塞 ${blocked})`,
    showSpend: (period, spend) => `支出(${period}):${spend}`,
    showPending: (mentions, review, blockedByMe) =>
      `待处理:@我 ${mentions} 条,待审核工单 ${review} 个,等我的阻塞 ${blockedByMe} 个`,
    invalid: (reason) => `invalid: ${reason}`,
    ticketHead: (ticketId, status, running, blocked) =>
      `工单 ${ticketId}:${status}${running ? ",运行中" : ""}${blocked !== undefined ? `,已阻塞(${blocked})` : ""}`,
    ticketFigures: (cost, rolledUp, sessions, children) =>
      `成本 ${cost}(含子工单 ${rolledUp}),贡献会话 ${sessions} 个,子工单 ${children} 个`,
    ticketFields: () => ({
      title: "标题",
      owner: "负责人",
      parent: "父工单",
      notify: "通知",
      priority: "优先级",
      due: "截止",
      blocked: "阻塞原因",
      blockedBy: "阻塞于",
      sessions: "贡献会话",
    }),
    ticketHistory: () => "操作历史:",
    notices: {
      employee_joined: (p) => `${p.agent} 加入,职位 ${p.title},汇报给 ${p.reportsTo}。`,
      employee_left: (p) => `${p.agent} 已离开组织,其汇报关系转由 ${p.reportsTo} 承接。`,
      channel_created: (p) => `${p.by} 创建了该频道。`,
      channel_archived: (p) => `${p.by} 归档了该频道。`,
      channel_unarchived: (p) => `${p.by} 取消归档了该频道。`,
      channel_joined: (p) => `${p.principal} 加入了该频道。`,
      channel_invited: (p) => `${p.by} 邀请 ${p.principal} 加入该频道。`,
      channel_left: (p) => `${p.principal} 退出了该频道。`,
      channel_removed: (p) => `${p.by} 将 ${p.principal} 移出该频道。`,
      budget_warned: (p) =>
        `预算预警:${p.agent} 已用掉 ${p.period} 预算的 ${p.percent}%(${p.cost} / ${p.budget} USD)。`,
      budget_paused: (p) =>
        `预算暂停:${p.agent} 达到 ${p.period} 预算的 ${p.percent}%(${p.cost} / ${p.budget} USD),其本人与下属的日程已暂停。`,
      ticket_blocked: (p) => `工单 ${p.ticket}(${p.title})已被阻塞。`,
      ticket_done: (p) => `工单 ${p.ticket}(${p.title})已完成。`,
      ticket_rejected: (p) => `工单 ${p.ticket}(${p.title})已被否决。`,
    },
    allHands: () => "全员频道",
    channelHeader: (channelId) => `[频道 ${channelId}]`,
    channelHead: (name, channelId, members, archived) =>
      `${name}(${channelId})——成员 ${members}${archived ? ",已归档" : ""}`,
    channelPurposeLine: (purpose) => `用途:${purpose}`,
    channelCreatedBy: (principal, createdAt) => `由 ${principal} 创建于 ${createdAt}`,
    channelLastMessage: (time) => `最后一条消息:${time}`,
    financeTotal: (period, total) => `合计(${period}):${total}`,
    unpriced: () => "[unpriced] 部分用量所用模型未配置价格:以上数字是下限",
    colEmployees: () => "员工数",
    colRunning: () => "运行中",
    colOpen: () => "未结",
    colBlocked: () => "阻塞",
    colSpend: () => "支出",
    colNote: () => "备注",
    colJobTitle: () => "头衔",
    colTitle: () => "标题",
    colState: () => "状态",
    colOwn: () => "自身",
    colCumulative: () => "累计",
    colBudget: () => "预算",
    colNext: () => "下次触发",
    colPriority: () => "优先级",
    colOwner: () => "负责人",
    colTicket: () => "工单",
    colRolledUp: () => "含子工单",
    colMembers: () => "成员数",
    colArchived: () => "归档",
    colUnread: () => "未读",
    colMentions: () => "@我",
    colPrincipal: () => "主体",
  },
  browser: {
    desc: "桌面应用的内置浏览器:读取页面、运行 JavaScript、点击与输入、导入登录状态",
    statusDesc: "内置浏览器是否可用,以及它的标签页",
    tabsDesc: "列出打开的标签页(* 标出当前标签页)",
    openDesc: "在当前标签页打开 URL(没有标签页时新开一个);--new-tab 则在新标签页打开",
    switchDesc: "把一个标签页设为当前标签页",
    closeDesc: "关闭标签页(缺省为当前标签页)",
    scanDesc:
      "读取页面:先列标签页,再输出简化后的 HTML(--text 时为纯文本);列表中被隐藏的条目以 [FAKE ELEMENT] 提示标出",
    execDesc: "在页面中运行 JavaScript;输出返回值、发生变化的元素、瞬时提示与新开的标签页",
    clickDesc: "用可信的鼠标事件点击一个元素(CSS 选择器),或用 --at 点击一个坐标",
    typeDesc: "向当前聚焦的元素(或 --selector 指定的元素)输入文字,可随后按下回车",
    screenshotDesc: "把标签页截图保存为 PNG",
    cdpDesc: "向标签页发送一条原始的 Chrome DevTools Protocol 命令",
    importDesc: "从本机安装的浏览器导入 Cookie(登录状态)与历史记录(两个开关都不给时两者都导入)",
    historyDesc: "搜索内置浏览器的历史记录(访问次数多的在前,次数相同时较近的在前)",
    tab: "标签页 id,或 active(缺省)",
    urlArg: "要打开的 URL;只写主机名时自动补上 https://",
    newTab: "在新标签页中打开",
    tabIdArg: "标签页 id",
    closeTabArg: "标签页 id,或 active(缺省)",
    textOnly: "输出纯文本而非简化 HTML(更省 Token)",
    maxChars: "正文最多返回多少个字符(缺省 35000;加 --text 时取其三分之一)",
    scriptArg:
      "JavaScript,作为一个 async 函数的函数体运行:以 `return <值>` 结尾;写 - 则从 stdin 读取",
    file: "从这个文件读取脚本",
    save: "把完整返回值写入这个文件,终端只显示开头部分",
    noMonitor: "不追踪页面变化:更快,适用于只读取不改动的脚本",
    timeout: "脚本时限:30s、2m 或纯数字秒数(缺省 15s)",
    selectorArg: "要点击的元素的 CSS 选择器",
    index: "点击选择器的第几个匹配,从 0 开始(缺省 0)",
    at: "改为点击视口中的这个坐标,格式为 x,y(CSS 像素)",
    textArg: "要输入的文字",
    selector: "先聚焦这个元素(CSS 选择器)",
    submit: "输入后按下回车",
    acceptDialogs:
      "同时接受页面的确认、输入和离开页面对话框(提示框总会接受;不加此选项时其余一律拒绝)",
    output: "要写入的 PNG 文件(缺省为工作目录下的 screenshot-<时间>.png)",
    fullPage: "截取整个页面,而不只是视口",
    methodArg: "CDP 方法,例如 DOM.getDocument",
    params: "方法参数,一个 JSON 对象",
    list: "列出本机的浏览器个人资料",
    from: "从哪个个人资料导入:--list 列出的来源 id,或浏览器名(chrome、edge、firefox……)以使用它的 Default 个人资料",
    cookies: "导入 Cookie 与登录状态",
    history: "导入历史记录",
    domain: "只导入这个网站及其子域名的 Cookie(可重复给出,也可用逗号分隔)",
    queryArg: "要在标题和 URL 中查找的词",
    count: "显示多少条(缺省 20)",
    label: {
      status: "状态",
      tab: "标签页",
      tabs: "标签页列表",
      page: "页面",
      return: "返回值",
      error: "错误",
      diff: "变化",
      transients: "瞬时提示",
      newTabs: "新标签页",
      note: "提示",
      clicked: "已点击",
      source: "来源",
      cookies: "Cookie",
      history: "历史记录",
      warning: "警告",
      screenshot: "截图",
      dialog: "对话框",
      memory: "内存",
    },
    line: (label, value) => `${label}:${value}`,
    tabHead: (id, title, url, loading) =>
      `标签页 ${id} · ${title || "(无标题)"} · ${url}${loading ? " · 加载中" : ""}`,
    noTabs: () => "无",
    available: () => "可用",
    unavailable: (reason) => `不可用(${reason})`,
    unavailableHint: (reason) => {
      const base = "内置浏览器需要 Adelie 桌面应用,且应用必须处于打开状态";
      if (reason === "shell_unsupported") return `${base}:当前桌面应用版本过旧,请更新应用。`;
      if (reason === "no_window") return `${base}:应用当前没有打开的窗口,请打开它。`;
      if (reason === "not_desktop") return `${base}:当前服务器不是在桌面应用中运行的。`;
      return `${base}。`;
    },
    memoryLine: (total, tabs, system) =>
      `${total}(${tabs} 个标签页)` +
      (system !== undefined ? ` · 本机可用 ${system.free},共 ${system.total}` : ""),
    loadWarning: (warnings) => {
      const said = [
        warnings.includes("memory") ? "浏览器占用的内存较多" : "",
        warnings.includes("low_system_memory") ? "本机可用内存不足" : "",
        warnings.includes("many_tabs") ? "打开的标签页过多" : "",
      ].filter(Boolean);
      return `${said.join(",") || "浏览器负载较高"}。请关闭不再需要的标签页(penguin browser close <tab-id>)。`;
    },
    closed: (tab) => `已关闭标签页 ${tab}。`,
    closedActive: () => "已关闭当前标签页。",
    reloaded: () => "已重新加载",
    elementsChanged: (count) => `${count} 个元素有变化`,
    clickedAt: (tag, text, x, y) => `${tag ?? "元素"}${text ? `「${text}」` : ""},位于 ${x},${y}`,
    dialogAnswered: (type, message, accepted) =>
      `${type}「${message}」→ ${accepted ? "已接受" : "已拒绝(加 --accept-dialogs 重新运行即可接受)"}`,
    truncatedSave: () => "[已截断——完整内容请用 --save]",
    truncatedJson: () => "[已截断——完整结果请用 --json]",
    savedTo: (path) => `[已保存到 ${path}]`,
    screenshotSaved: (path, size, kilobytes) => `${path}(${size},${kilobytes} KB)`,
    importData: (cookies, history) =>
      [cookies ? "Cookie" : "", history ? "历史记录" : ""].filter(Boolean).join("、") || "-",
    importCookies: (c) =>
      `导入 ${c.imported},跳过 ${c.skipped},失败 ${c.failed}(共找到 ${c.found})`,
    importHistory: (h) => `导入 ${h.imported}(共找到 ${h.found})`,
    noSources: () => "本机没有找到可导入的浏览器个人资料。",
    noHistory: () => "没有匹配的历史记录。",
    visits: (count) => `${count} 次访问`,
    colId: () => "ID",
    colTitle: () => "标题",
    colUrl: () => "URL",
    colBrowser: () => "浏览器",
    colProfile: () => "个人资料",
    colData: () => "数据",
    errorLine: (code, message) => `错误:${code}:${message}`,
    tabInvalid: (value) => `标签页应为标签页 id 或 active,而不是「${value}」。`,
    positiveInt: (flag, value) => `${flag} 的值应为正整数,而不是「${value}」。`,
    indexInvalid: (value) => `--index 的值应为从 0 起的整数,而不是「${value}」。`,
    atInvalid: (value) => `--at 的格式为 x,y(CSS 像素,例如 --at 120,340),而不是「${value}」。`,
    clickTarget: () => "请给出选择器(可加 --index)或 --at x,y,二者选一。",
    newTabWithTab: () => "--new-tab 会新开一个标签页,因此不接受 --tab。",
    paramsInvalid: () => "--params 必须是一个 JSON 对象。",
    methodInvalid: (value) =>
      `「${value}」不是 CDP 方法:应写作 Domain.method,例如 DOM.getDocument。`,
    scriptSources: () => "脚本只能用一种方式给出:参数、--file 或 stdin。",
    scriptMissing: () =>
      "没有脚本:请作为参数给出、用 --file 指定,或从 stdin 传入(penguin browser exec <<'EOF' … EOF)。",
    scriptEmpty: () => "脚本是空的。",
    fileUnreadable: (path, detail) => `无法读取 ${path}:${detail}`,
    fileUnwritable: (path, detail) => `无法写入 ${path}:${detail}`,
    importMode: () => "用 --list 查看浏览器个人资料,或用 --from <来源 id|浏览器> 从其中之一导入。",
    sourceNotFound: (from, known) =>
      `没有与「${from}」匹配的浏览器个人资料${known.length > 0 ? `(本机有:${known.join("、")})` : ""};请查看 penguin browser import --list。`,
    sourceAmbiguous: (from, ids) =>
      `${from} 有多个个人资料,且没有 Default:${ids.join("、")}。请用 --from 指定其中一个。`,
  },
  client: {
    invalidServerUrl: (value) => `服务器地址「${value}」无效:应为 http(s)://host[:port]。`,
    remoteNeedsToken: (url) =>
      `${url} 不是本机:连接远端服务器须设置 ADELIE_API_TOKEN(本机的 api-token 文件不会发往其它主机)。`,
    noServer: () => "该数据根目录没有正在运行的服务器。",
    autoStartUnavailable: () =>
      "没有正在运行的服务器,且当前 CLI 入口无法自动拉起(开发态运行)。请自行执行 `penguin server`。",
    autoStartFailed: (logPath) => `自动启动的服务器未能就绪,输出见 ${logPath}。`,
    autoStarted: (url, logPath) => `已在本机启动服务器 ${url}(日志:${logPath})。`,
    noToken: (url, tokenPath) =>
      `${url} 拒绝了请求(401),且没有可用的 API token:请设置 ADELIE_API_TOKEN,或确认服务器的 token 文件可读(${tokenPath})。`,
    authFailed: (url) =>
      `${url} 拒绝了 API token(401)。服务器重启会轮换 token——检查 ADELIE_API_TOKEN,或让 CLI 读取最新的 api-token 文件。`,
    httpError: (status, code, message) =>
      `服务器错误 ${status}(${code})${message ? `:${message}` : ""}`,
    sessionNotFound: (ref, projectId) =>
      `Project ${projectId} 中没有匹配「${ref}」的会话(可用 \`penguin ls\` 查看)。`,
    sessionAmbiguous: (ref, candidates) =>
      `「${ref}」匹配到 ${candidates.length} 个会话:\n  ${candidates.join("\n  ")}\n请使用更长的片段或完整 id。`,
    streamLost: (detail) => `与服务器的输出流断开且重连失败:${detail}`,
    streamResynced: () =>
      "[stream] 重连时已超出服务端回放缓冲,此处可能缺少部分输出(penguin logs 可查看完整历史)",
    timeoutInvalid: (value) => `--timeout 值「${value}」无效:应为 30s、5m、2h 或纯数字秒数。`,
    stillRunning: (shortId) =>
      `[仍在运行] 会话 ${shortId} 继续在服务端执行——可用 \`penguin logs -f ${shortId}\` 跟随,或 \`penguin input ${shortId}\` 轮询`,
    callerDefaultsFailed: (sessionId) =>
      `[调用方上下文] 无法读取调用方会话 ${sessionId},改用普通缺省值`,
    latestSession: (sessionId) => `[latest] 会话 ${sessionId}`,
    noSessionsYet: (agentId, projectId) =>
      `Agent ${agentId} 在 Project ${projectId} 下还没有任何会话:先用 \`penguin run -m "..."\` 或 \`penguin chat\` 开始一个。`,
  },
  chatThinkingConfigured: () => "Agent 配置值",
  serve: {
    serverDesc:
      "启动 Web 服务(HTTP API 与内置前端,同一进程);子命令 reset-admin-password 重置忘记的管理员密码",
    webDesc: "启动 Web 服务,就绪后用浏览器打开界面",
    port: "监听端口(其次取环境变量 PORT,缺省 4000)",
    host: "监听地址(其次取环境变量 HOST,缺省 127.0.0.1)",
    noOpen: "不自动打开浏览器",
    restarting: "正在重启服务以应用更新…",
    app: "以某个 workflow 页面占满整个应用打开:<project>/<agent>/<workflow>[/<tab>](页面内按 Ctrl+P 或 Ctrl+Shift+P 打开命令面板可退出)",
  },
  auth: {
    desc: "在终端里登录 Adelie 服务",
    loginDesc: "用密码登录并记住会话",
    statusDesc: "显示已记住的会话",
    logoutDesc: "吊销并忘记已记住的会话",
    server: "服务地址(默认:该数据根上正在运行的服务)",
    userId: "登录的账号(不给时会询问;默认 admin)",
    password: "密码(也可用 ADELIE_PASSWORD;都没给时会提示输入)",
    print: "同时把会话令牌打印到 stdout",
    accountPrompt: (fallback) => `账号 [${fallback}]:`,
    prompt: (userId) => `${userId} 的密码:`,
    emptyPassword: "没有输入密码。",
    noServer: (root) => `${root} 上没有正在运行的服务,无处登录——请用 --server <url> 指定。`,
    unreachable: (server, detail) => `连接不上 ${server}:${detail}`,
    refused: (status, detail) => `服务拒绝了登录(${status}):${detail}`,
    noCookie: "服务接受了登录,但没有下发会话 Cookie。",
    loggedIn: (userId, server, file) => `已以 ${userId} 登录 ${server},会话保存在 ${file}。`,
    notLoggedIn: (file) => `尚未登录(没有 ${file})。`,
    statusLine: (userId, server) => `已以 ${userId} 登录 ${server}。`,
    expires: (when) => `有效期至 ${when}。`,
    expired: (when) => `已于 ${when} 过期——请重新登录。`,
    loggedOut: (server) => `已登出 ${server},该会话已在服务端吊销。`,
    loggedOutLocally: (server) =>
      `已在本地忘记,但连接不上 ${server}——该会话可能在过期前仍然有效。`,
  },
  authToken: {
    desc: "为该数据根签发短期 API 会话令牌(供通过 ssh 连接本机的控制端使用)",
    userId: "签发给哪个账号(默认 admin)",
    ttlSeconds: "有效期秒数(默认 3600)",
    mark: "在令牌前打印固定标记行,供需要从 shell 输出里解析它的调用方使用",
    badTtl: "--ttl-seconds 必须是正整数。",
    noServer: (root) => `${root} 上没有 web.db——该数据根上从未运行过服务,因此没有可签发的账号。`,
    failed: (detail) => `签发失败:${detail}`,
  },
  serverStatus: {
    desc: "以单行 JSON 打印本数据根目录的服务状态与本机 id",
  },
  serverStop: {
    desc: "停止本数据根目录上运行的服务,并以 JSON 报告结果",
  },
  resetPassword: {
    desc: "重置 Web 管理员账号,下次启动服务时会打印新的首次登录链接(须先停止服务)",
    serverRunning: (url) =>
      `该数据根目录已有 Adelie 服务在运行:${url}\n` +
      `请先停止它,再重新执行 \`penguin server reset-admin-password\`。`,
    noDatabase: (dbPath) =>
      `${dbPath} 处没有 Web 数据库,无可重置。请先执行 \`penguin web\` 启动一次服务以创建管理员账号。`,
    noAdmin: () =>
      "Web 数据库中尚无管理员账号,无可重置。请先执行 `penguin web` 启动一次服务完成种子创建。",
    done: (root) => `数据根目录 ${root} 的管理员账号已退回未认领状态,其全部登录会话已吊销。`,
    next: () =>
      "启动服务(`penguin web`),它会打印一条登录链接用于认领该账号——在密码被设置之前一直有效。",
  },
  version: {
    description: "显示当前运行的是哪个构建",
    json: "以 JSON 输出完整构建信息(即 GET /api/version 的响应体)",
  },
  update: {
    desc: "原地升级当前的 Adelie 安装",
    check: "只报告当前版本与最新版本,不做任何修改",
    releaseOpt:
      "指定目标版本而不是最新版(如 v0.1.2 或 0.1.2);之所以叫 --release,是因为 -v/--version 是 CLI 自身的版本参数",
    yes: "跳过确认提示",
    checkReport: (current, latest) => `已安装 ${current} · 最新 ${latest}`,
    upgradeAvailable: (target) => `有可用升级:执行 \`penguin update\` 安装 ${target}。`,
    upToDate: (current) => `已是最新版本(${current}),无需升级。`,
    targetIsOlder: (target) => `${target} 低于当前已安装的版本——这将是一次降级。`,
    planTarball: (current, target, installDir, universal) =>
      [
        `升级 ${current} -> ${target}`,
        `  方式:    重新执行官方安装脚本(当前安装来自 tarball)`,
        `  安装目录:${installDir}${universal ? "(universal 包,不含内置 Node 运行时)" : ""}`,
        `  将替换:  bin、lib、web${universal ? "" : "、node"}——数据目录不会被改动`,
      ].join("\n"),
    planNpm: (current, target, manager, command) =>
      [
        `升级 ${current} -> ${target}`,
        `  方式:  ${manager} 全局安装(当前安装来自 ${manager})`,
        `  命令:  ${command}`,
        `  数据目录不会被改动`,
      ].join("\n"),
    confirm: () => "确认继续?[y/N] ",
    needsYes: () => "当前不在终端中,无法回答确认提示。请加 --yes 以非交互方式升级。",
    cancelled: () => "已取消,未做任何修改。",
    done: (version) => `Adelie ${version} 安装完成。在新 shell 中执行 \`penguin --version\` 确认。`,
    failed: () => "升级失败;在可能的情况下已保留原有安装。",
    sourceCheckout: () =>
      "当前 penguin 运行自源码检出,无需下载——请用 `git pull` 更新并重新构建(`pnpm install && pnpm -r build`)。",
    desktopApp: () =>
      "当前 penguin 随 Adelie 桌面应用一同分发,会在应用更新时一并替换——请从应用菜单检查更新。",
    unknownInstall: (modulePath) =>
      `无法判断当前 penguin 的安装方式(运行自 ${modulePath}),因此不会替换它。请用官方安装脚本重新安装,或用你当初使用的包管理器升级。`,
    npmUnknownManager: (globalRoot, target) =>
      `这是位于 ${globalRoot} 的全局安装,但无法确定是哪个包管理器安装的。请自行用该包管理器升级,例如 \`npm install -g @adelie/cli@${target}\`。`,
    windowsUnsupported: () =>
      "官方安装脚本是 POSIX shell 脚本,无法在 Windows 上运行。请从 GitHub Releases 页面重新安装,或改用 npm 全局安装。",
    windowsGlobalInstall: (command) =>
      [
        "在 Windows 上,penguin 无法代你调用包管理器:Node 不会在没有 shell 的情况下执行 npm/pnpm/yarn 的 `.cmd` 包装脚本。",
        "请在终端里自行执行下面的命令,然后重新打开终端:",
        `  ${command}`,
      ].join("\n"),
    networkFailed: (url) => `无法访问 ${url}。请检查网络后重试。`,
    rateLimited: () =>
      "GitHub 对版本查询做了限流。请等待几分钟后重试,或用 --release <tag> 跳过查询。",
    apiFailed: (status) => `GitHub 版本查询失败,HTTP ${status}。`,
    apiMalformed: () => "GitHub 版本查询返回了非预期的响应,其中没有可用的版本号。",
    invalidDownloadSource: () => "PENGUIN_DOWNLOAD_SOURCE 必须是 auto 或 github。",
    downloadBaseMustBeHttps: (name) => `${name} 必须是绝对 HTTPS URL。`,
    installerFetchFailed: (sources) => {
      const sourceText = sources
        .map((source) => (source === "configured" ? "配置的镜像" : "GitHub"))
        .join("或 ");
      const leadingSpace = /^[A-Za-z]/.test(sourceText) ? " " : "";
      const trailingSpace = /[A-Za-z]$/.test(sourceText) ? " " : "";
      return `无法从${leadingSpace}${sourceText}${trailingSpace}下载安装脚本。请检查网络后重试。`;
    },
  },

  header: headerZh,
  chatHints: () =>
    "输入消息发起对话;行尾 \\ 续行;运行中输入可插话引导;/goal 以目标模式运行至完成;/compact 压缩上下文;/clear 开启全新会话;/thinking 调整思考等级;/switch-model <provider> <model_id> 切换模型(先压缩上下文);/verbose 切换完整工具输出;/exit 退出;Ctrl-C 中断对话。",
  confirmExit: () => "确认退出 penguin?[y/N] ",
  taskInterrupted: () => "[已中断当前对话]",
  steerQueued: (text) => `» 插话已排队(随下一轮送达):${text}`,
  steerLinePrefix: () => "↪ 用户: ",
  error: (message) => `[错误] ${message}`,
  approvePrompt: () => "? 批准此工具调用?[Y/n] ",
  taskStats: (s) =>
    `[统计信息] 上下文 ${s.context} (${s.contextDelta}) · tokens ${s.tokens} (${s.tokensDelta}) · 用时 ${s.elapsed} (${s.elapsedDelta})`,
  abortLabel: (abort) => {
    const cause =
      abort?.errorCode === "user_abort"
        ? "用户中断"
        : abort?.errorCode === "backoff_interrupted"
          ? "重试等待中被中断"
          : abort?.errorCode === "compaction_interrupted"
            ? "压缩过程中被中断"
            : (abort?.errorCode ?? abort?.reason ?? "");
    const text = cause ? `${cause}${abort?.errorMessage ? `:${abort.errorMessage}` : ""}` : "";
    return `[已中断]${text ? `:${text}` : ""}`;
  },
  llmFatalLabel: (errorMessage) => `[错误] 模型请求错误${errorMessage ? `:${errorMessage}` : ""}`,
  reconnectGaveUpLabel: (attempt, errorMessage) =>
    `[重试] 第 ${attempt} 次尝试后放弃${errorMessage ? `:${errorMessage}` : ""}`,
  reconnectLabel: (status, attempt, errorCode) =>
    `[重试] ${((kind) =>
      kind === "timeout"
        ? "连接超时或网络中断"
        : kind === "malformed"
          ? "响应不完整或无法解析"
          : kind === "network"
            ? "网络或服务暂时不可用"
            : kind === "failed"
              ? "模型服务返回错误"
              : "请求失败")(errorCode ?? status)},正在发起第 ${attempt} 次重试……`,
  compactionStart: (mode, reason) =>
    mode === "discard"
      ? `[压缩] 正在丢弃旧上下文(${reason})……`
      : `[压缩] 正在总结压缩上下文(${reason})……`,
  mcpConnectStart: (servers) => `[mcp] 正在连接 MCP Server(${servers.join("、")})……`,
  mcpConnectStop: (durationMs, failures, aborted) =>
    aborted
      ? "[mcp] 连接已中断,下次运行时重新连接"
      : failures.length === 0
        ? `[mcp] 连接完成,耗时 ${(durationMs / 1000).toFixed(1)}s`
        : `[mcp] 连接完成,耗时 ${(durationMs / 1000).toFixed(1)}s;不可用:${failures.map((f) => `${f.server}(${f.error})`).join("、")}`,
  compactionStop: (mode, status, tokens, errorMessage) =>
    (status === "completed"
      ? mode === "discard"
        ? "[压缩] 完成,旧上下文已丢弃"
        : "[压缩] 完成,已切换到摘要后的新上下文"
      : status === "aborted"
        ? "[压缩] 已中断,保留当前上下文"
        : `[压缩] 失败${errorMessage !== undefined ? `(${errorMessage})` : ""},保留当前上下文${
            // retryable = abandoned this time, retried at the next trigger; fatal = a config
            // or credential change has to come first. Legacy Traces spell both "failed".
            status === "retryable"
              ? ",下次触发时重试"
              : status === "fatal"
                ? ",需修复模型配置后重试"
                : ""
          }`) + (tokens ? ` · tokens ${tokens.total} (${tokens.delta})` : ""),
  compactNothing: () => "[压缩] 当前上下文为空,无需压缩",
  clearDone: () => "[清空] 已开启全新 Session(原会话仍保留,可恢复)",
  goalRound: (round) => `[目标] 第 ${round} 轮`,
  goalFinished: (outcome, rounds, tokens) => {
    const label = {
      complete: "已完成",
      blocked: "受阻(所缺条件见最后一条回复)",
      budget_limited: "已停止:token 预算耗尽",
      aborted: "已中断",
    }[outcome];
    return `[目标] ${label} · 共 ${rounds} 轮 · tokens ${tokens}`;
  },
  hookEvent: (name, decision, reason) =>
    `[钩子] ${[name, decision, reason].filter(Boolean).join(" · ")}`,
  goalUsage: () => "用法:/goal[:<预算>] <目标>(例如 /goal:500k 修复所有失败的测试)",
  goalBudgetInvalid: (value) =>
    `无效的 token 预算 "${value}":应为正数,可带 k/m 后缀(500k、2m)。`,
  goalObjectiveEmpty: () => "目标模式需要非空的目标文本:请通过 -m 传入。",
  thinkingCurrent: (level) =>
    `[思考] 当前等级:${level}(本 Session)——用 /thinking <low|medium|high|xhigh|max> 修改`,
  thinkingSet: (level) =>
    `[思考] 本 Session 的等级已钉为 ${level},下一轮请求起生效——更换思考等级会使模型缓存失效,建议先 /compact 压缩上下文(不改动 Agent 配置)`,
  thinkingInvalid: (value) => `无效的思考等级 "${value}"。请使用 low、medium、high、xhigh 或 max。`,
  switchModelCurrent: (model) =>
    `[切换模型] 当前模型:${model}——用 /switch-model <provider> <model_id> 切换(会先用当前模型压缩上下文)`,
  switchModelUsage: () =>
    "用法:/switch-model <provider> <model_id>(例如 /switch-model deepseek deepseek-v4-pro;penguin config model list 列出已配置的模型)",
  switchModelDone: (previous, next) => `[切换模型] 模型:${previous} → ${next}`,
  switchModelBusy: () => "[切换模型] 会话正忙(任务或压缩进行中),请待其结束后再切换",
  switchModelSame: (model) => `[切换模型] 已在使用 ${model},无需切换`,
  switchModelNotConfigured: (model, listCommand, addCommand) =>
    `[切换模型] Project 配置中没有 ${model}:${listCommand} 列出已配置的模型,${addCommand} 可添加它`,
  switchModelUnavailable: (model, detail) =>
    `[切换模型] ${model} 已配置但无法使用${detail ? `:${detail}` : ""}`,
  switchModelNoCompaction: () =>
    "[切换模型] 本 Session 未配置上下文压缩,而切换模型必须先压缩,因此无法切换",
  verboseOn: () => "[详细输出] 已开启——后续工具输出完整显示(/verbose 切换)",
  verboseOff: () => "[详细输出] 已关闭——后续过长的工具输出将折叠(/verbose 切换)",
  toolOutputElided: (hidden) => `……(另有 ${hidden} 行,/verbose 显示完整输出)`,
  approveModeInvalid: (value) =>
    `无效的审批模式 "${value}"。请使用 allow-all、deny-all、read-only 或 always-ask。`,
  approvalDecision: (decision) =>
    decision === "allow" ? "✓ [已批准]" : decision === "forbidden" ? "× [策略禁止]" : "× [已拒绝]",
  modelRefIncomplete: () =>
    "--model-id 与 --provider 必须成对给出:模型引用始终是显式的 (provider, model_id) 组合。两者都不给则使用 Project 默认模型。",
  resumeNoOverride: () =>
    "--resume 不接受 --workspace、--model-id 与 --provider:均沿用原 Session。如需换模型,请在会话内使用 /switch-model <provider> <model_id>(会先压缩上下文)。",
  resumeNoSession: () => "没有可恢复的 Session:当前 Agent 还没有任何会话记录。",
  resumedBanner: (sessionId, messageCount) =>
    `[已恢复] ${sessionId} · 当前上下文共 ${messageCount} 条消息`,
  resumeHint: (command) => `继续本次对话:${command}`,
  langInvalid: (value) => `无效的语言 "${value}"。请使用 en 或 zh。`,
  langWindowsUnsupported: (lang) =>
    `penguin config lang 通过 POSIX shell 启动文件持久化语言,Windows 上没有对应机制。\n` +
    `请改为设置用户环境变量:setx ADELIE_LANG ${lang}(新终端生效)。`,
  langSet: (lang, rcPath) => `语言已设为 ${lang};已将 ADELIE_LANG 写入 ${rcPath}。`,
  langRestartConfirm: () => "现在打开新 shell 使其生效?[y/N] ",
  langRestart: () => "正在打开使用新语言的新 shell(输入 exit 可返回)……",
  langRestartHint: (rcPath) => `请打开新终端,或执行:source ${rcPath}`,
  modelAdded: (model, def) => `已添加模型 ${model}。当前默认模型:${def ?? "(未设置)"}`,
  modelUpdated: (model, def) => `已更新模型 ${model}。当前默认模型:${def ?? "(未设置)"}`,
  defaultModelSet: (model) => `默认模型已设为 ${model}。`,
  visionModelSet: (model) => `视觉模型已设为 ${model}。`,
  modelRemoved: (model, def) => `已删除模型 ${model}。当前默认模型:${def ?? "(未设置)"}`,
  modelNotConfigured: (model) => `模型 ${model} 不在当前 Project 配置中。`,
  modelNotRoutable: (model) =>
    `模型 ${model} 无法路由:厂商分组只承载内置模型。` +
    `请改用自定义分组(--provider custom)并附上 --client-type 与 --base-url,` +
    `或用 --client-type 指定该模型所用的协议。`,
  modelNotAddable: (model, group) =>
    `模型 ${model} 无法添加:${group} 分组只承载内置模型。` +
    `请改用自定义分组(--provider custom,或自己命名的分组)并附上 --client-type 与 --base-url。`,
  visionModelCleared: () => "它同时是视觉模型,该设置已一并清空。",
  modelListTitle: () => "已配置的模型:",
  modelListEmpty: () => "尚未配置任何模型。用 `penguin config model add` 添加。",
  vaultSet: (key) => `已保存 vault 条目 ${key}。新对话立即生效;进行中的对话在下一次压缩后生效。`,
  vaultRemoved: (key) =>
    `已删除 vault 条目 ${key}。新对话立即生效;进行中的对话在下一次压缩后生效。`,
  vaultKeyMissing: (key) => `vault 条目 ${key} 不存在。`,
  vaultListTitle: () => "vault 环境变量(值已掩码):",
  vaultListEmpty: () => "vault 为空。用 `penguin config vault set` 添加。",
  webReady: (url) => `Web 界面已就绪:${url}`,
  serverAlreadyRunning: (url) =>
    `该数据根目录已有 Adelie 服务在运行:${url}\n请先停止它,或用 ADELIE_HOME 指定另一个数据根目录。`,
  webAlreadyRunning: (url) => `该数据根目录已有服务在运行,打开既有实例:${url}`,
  webProbeFailed: (url, detail, kind, port) => {
    const hint = {
      timeout: `连接超时。请检查防火墙或安全软件是否拦截。请允许 Adelie 在本机端口 ${port} 上通信。`,
      refused: "没有进程接受连接。请检查服务是否已经退出,或 HOST/PORT 是否指向了其他地址。",
      reset: "连接在收到 HTTP 响应前已关闭。请检查本机安全软件后重试。",
      permission: "操作系统拒绝了连接。请检查防火墙或安全策略权限。",
      dns: "无法解析主机名。请检查 --host 或 HOST。",
      unknown: `请在服务就绪后手动打开 ${url}。`,
    }[kind];
    return `服务探活失败:${url}\n最后一次探测错误:${detail}\n${hint}`;
  },
};

/** Get the message set for a language. */
export function getMessages(language: Language): Messages {
  return language === "zh" ? zh : en;
}

/** Resolve the language from the env var and return its message set (the default used when no explicit `t` is given). */
export function defaultMessages(): Messages {
  return getMessages(resolveLanguage());
}

/** Mask an API key: keep only a few trailing characters; return `-` when unconfigured. */
export function maskApiKey(apiKey: string | undefined): string {
  if (!apiKey) return "-";
  // Mask the whole thing when ≤12 chars: `****last4` reveals too much of a short secret (same threshold as the server-side mask).
  if (apiKey.length <= 12) return "***";
  return `****${apiKey.slice(-4)}`;
}