Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

27.3 KB
Raw Blame
/**
 * `ruflo proxy` β€” Meta LLM Proxy control surface (ADR-304/307/313).
 *
 * This command currently implements the ADR-313 sponsored-downtime
 * subcommands only (`sponsor-enable` / `sponsor-disable` / `sponsor-status`).
 * The full lifecycle command set ADR-307 specifies
 * (`install|start|stop|status|logs|update|uninstall`) manages the proxy
 * *process* itself and is out of scope here β€” this surface only manages
 * the consent-gated sponsored-mode flag the already-running proxy reads
 * from its config mirror.
 *
 * Consent (ADR-302/313): granting `sponsored-downtime` consent here writes
 * BOTH the ruflo-side consent receipt (source of truth) AND a mirror flag
 * into ~/.ruflo/proxy-config.toml (the file the Rust proxy binary reads).
 * The proxy never writes this file β€” ruflo does, exactly once per
 * enable/disable action.
 */

import * as fs from 'fs';
import type { Command, CommandResult } from '../types.js';
import { output } from '../output.js';
import { hasConsent, recordConsent, revokeConsent, funnelStateDir } from '../funnel/index.js';
import { recordFunnelEvent } from '../funnel/events.js';
import { clearRateLimitStatus, readRateLimitStatus } from '../funnel/rate-limit-notifier.js';
import { clearQuotaLowStatus, readQuotaLowStatus } from '../funnel/power-saver-notifier.js';
import { getInstalledCliVersion } from '../init/helper-refresh.js';
import * as path from 'path';
import { proxyLifecycleSubcommands, printProxyConsoleGuidance, DEFAULT_PROXY_RELEASE } from './proxy-lifecycle.js';
import { getProxyStatus } from '../proxy/lifecycle.js';

const PROXY_CONFIG_FILE = 'proxy-config.toml';

/**
 * Minimal hand-rolled TOML writer β€” this config has exactly one boolean
 * field ruflo needs to set (`sponsored_consent_granted`); every other field
 * the proxy binary defaults itself (ADR-307 "a malformed config must never
 * crash the proxy β€” it degrades to safe defaults"). We read-modify-write
 * the raw text so a user's own bind/backend customizations survive, only
 * ever touching this one line. No TOML parser dependency needed for this.
 */
function readProxyConfigRaw(): string {
  try {
    return fs.readFileSync(path.join(funnelStateDir(), PROXY_CONFIG_FILE), 'utf-8');
  } catch {
    return '';
  }
}

function writeConfigLine(field: string, rawValue: string): void {
  const dir = funnelStateDir();
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
  const target = path.join(dir, PROXY_CONFIG_FILE);
  const raw = readProxyConfigRaw();
  const line = `${field} = ${rawValue}`;
  const pattern = new RegExp(`^${field}\\s*=.*$`, 'm');
  let next: string;
  if (pattern.test(raw)) {
    next = raw.replace(pattern, line);
  } else {
    next = raw.length > 0 ? `${raw.trimEnd()}\n${line}\n` : `${line}\n`;
  }
  const tmp = `${target}.tmp`;
  fs.writeFileSync(tmp, next, { encoding: 'utf-8', mode: 0o600 });
  fs.renameSync(tmp, target);
}

function writeConsentMirrorLine(field: string, value: boolean): void {
  writeConfigLine(field, String(value));
}

function writeSponsoredConsentMirror(granted: boolean): void {
  writeConsentMirrorLine('sponsored_consent_granted', granted);
}

function writePowerSaverConsentMirror(granted: boolean): void {
  writeConsentMirrorLine('power_saver_consent_granted', granted);
}

function writeTrainingShareConsentMirror(granted: boolean): void {
  writeConsentMirrorLine('training_share_consent_granted', granted);
}

/**
 * `default_data_plane` β€” the ADR-304 cloud-routing toggle. Values confirmed
 * against meta-proxy's actual `DataPlane` enum (`src/config.rs`,
 * `#[serde(rename_all = "snake_case")]`): "local" | "cloud" | "sponsored" |
 * "passthrough" (the last two are not written by this command β€” sponsored
 * is ADR-313's own consent flag, passthrough is the proxy's own default).
 */
function readDataPlane(): string {
  const raw = readProxyConfigRaw();
  const match = raw.match(/^default_data_plane\s*=\s*"([^"]*)"/m);
  return match ? match[1] : 'passthrough'; // matches the Rust struct's own default
}

function writeDataPlane(plane: 'local' | 'cloud' | 'passthrough'): void {
  writeConfigLine('default_data_plane', `"${plane}"`);
}

/**
 * How to get back to a given plane, for "restore what you had" guidance.
 * `sponsored` is ADR-313's own consent flow and is deliberately absent β€” this
 * command must not offer a one-flag route into someone else's consent gate.
 */
const PLANE_RESTORE_COMMAND: Record<string, string> = {
  passthrough: 'ruflo proxy config --passthrough',
  local: 'ruflo proxy config --local-only',
};

/**
 * One line describing a plane in the terms that matter β€” who serves the
 * request. Kept together so the no-flag report and the restore hints cannot
 * describe the same plane two different ways.
 */
function describePlane(plane: string): string {
  switch (plane) {
    case 'cloud':
      return 'Cloud routing is ON β€” cloud-tier requests go to api.cognitum.one.';
    case 'passthrough':
      return 'Passthrough β€” requests go to your own Claude subscription. Prompts do not go to Cognitum.';
    case 'local':
      return 'Local-only β€” requests go to your own backend (Ollama/vLLM/SGLang) and never leave this machine.';
    case 'sponsored':
      return "Sponsored β€” requests go to Cognitum's sponsored capacity (ADR-313).";
    default:
      return `Unrecognized plane "${plane}" β€” meta-proxy will fall back to its own default (passthrough).`;
  }
}

/**
 * `routing_mode` β€” how the Cloud plane picks a tier (meta-proxy ADR-321
 * rev-2). Values match the Rust `RoutingMode` enum (`src/config.rs`, also
 * `#[serde(rename_all = "snake_case")]`); absent from the file means `auto`,
 * so an existing config keeps working untouched.
 */
const ROUTING_MODES = ['auto', 'low', 'mid', 'high'] as const;
type RoutingMode = (typeof ROUTING_MODES)[number];

function readRoutingMode(): RoutingMode {
  const match = readProxyConfigRaw().match(/^routing_mode\s*=\s*"([^"]*)"/m);
  const value = match?.[1];
  return (ROUTING_MODES as readonly string[]).includes(value ?? '') ? (value as RoutingMode) : 'auto';
}

function writeRoutingMode(mode: RoutingMode): void {
  writeConfigLine('routing_mode', `"${mode}"`);
}

/**
 * ADR-304/321. This is the terminal-side equivalent of the Developer
 * Console's Cloud selector disclosure β€” meta-proxy#43 M5a covered the
 * console, M5b covers "any terminal flow that explicitly activates Cloud",
 * which is this command.
 *
 * It answers the three questions activating Cloud actually decides, because
 * each has a different answer than the plane the user is leaving:
 * who processes the prompt, who pays for it, and which model runs. The third
 * is the one the previous text omitted entirely, and it is not a detail β€”
 * on the Cloud plane the client's requested model is deliberately NOT used.
 */
const CLOUD_ROUTING_DISCLOSURE = [
  'Enabling cloud routing.',
  '',
  'Who processes your prompts:',
  '  Prompts for cloud-tier requests are sent to api.cognitum.one and',
  '  forwarded to the selected provider (Claude / GPT / Gemini / DeepSeek /',
  '  OpenRouter). Cognitum handles them server-side.',
  '',
  'Who pays:',
  '  Cloud-tier requests are metered against your Cognitum account, not',
  '  against your own Claude subscription. Your subscription is used only',
  '  by the Passthrough plane (the proxy\'s default), which is unaffected',
  '  by everything below.',
  '',
  'Which model runs:',
  '  The cloud plane picks the tier per prompt instead of using the model',
  '  your client asked for (ADR-321). That is the point of the plane: a',
  '  trivial question is not served at frontier rates because the client',
  '  happened to name a frontier model. The scorer reads prompt shape, not',
  '  task difficulty, so pin a tier if you disagree with its judgement:',
  '    ruflo proxy config --routing-mode high',
  '',
  'Requests routed to local backends never leave this machine.',
  '',
  'Turning it off is a choice of where to go back to, not one command:',
  '  ruflo proxy config --passthrough    Your own Claude subscription',
  '  ruflo proxy config --local-only     Your own local backend',
].join('\n');

const configSub: Command = {
  name: 'config',
  description: 'Toggle cloud routing and its tier selection (ADR-304/321) β€” local backends only by default',
  options: [
    { name: 'cloud', description: 'Enable cloud routing (requires cloud-routing consent)', type: 'boolean', default: false },
    { name: 'local-only', description: 'Disable cloud routing; route to your own local backend', type: 'boolean', default: false },
    {
      name: 'passthrough',
      description: "Disable cloud routing; route to your own Claude subscription (meta-proxy's own default)",
      type: 'boolean',
      default: false,
    },
    {
      name: 'routing-mode',
      description: `How the cloud plane picks a tier: ${ROUTING_MODES.join(' | ')} (default: auto)`,
      type: 'string',
    },
    { name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
  ],
  action: async (ctx): Promise<CommandResult> => {
    const wantCloud = Boolean(ctx.flags.cloud);
    const wantLocalOnly = Boolean(ctx.flags.localOnly ?? ctx.flags['local-only']);
    const wantPassthrough = Boolean(ctx.flags.passthrough);
    const rawRoutingMode = ctx.flags.routingMode ?? ctx.flags['routing-mode'];
    const wantRoutingMode = typeof rawRoutingMode === 'string' ? rawRoutingMode : undefined;

    const planeFlags = [
      wantCloud && '--cloud',
      wantLocalOnly && '--local-only',
      wantPassthrough && '--passthrough',
    ].filter(Boolean) as string[];
    if (planeFlags.length > 1) {
      output.printError(`Pass one plane at a time β€” got ${planeFlags.join(' and ')}.`);
      return { success: false, exitCode: 1 };
    }

    if (wantRoutingMode !== undefined && !(ROUTING_MODES as readonly string[]).includes(wantRoutingMode)) {
      output.printError(
        `Unknown routing mode "${wantRoutingMode}". Valid values: ${ROUTING_MODES.join(', ')}.`,
      );
      return { success: false, exitCode: 1 };
    }
    const routingMode = wantRoutingMode as RoutingMode | undefined;

    // A tier only means anything on the Cloud plane, and these flags leave
    // it. Writing both would record a preference the same command just made
    // unreachable, so say so instead of silently picking one.
    const leavingCloud = wantLocalOnly || wantPassthrough;
    if (routingMode && leavingCloud) {
      output.printError(
        `--routing-mode only governs the cloud plane, which ${planeFlags[0]} turns off. Pass one or the other.`,
      );
      return { success: false, exitCode: 1 };
    }

    if (!wantCloud && !leavingCloud && !routingMode) {
      const plane = readDataPlane();
      output.writeln(`Current data plane: ${plane}`);
      output.writeln(`  ${describePlane(plane)}`);
      const mode = readRoutingMode();
      output.writeln(
        mode === 'auto'
          ? '  Tier selection: auto β€” Cognitum scores each prompt and picks low/mid/high.'
          : `  Tier selection: pinned to ${mode}.`,
      );
      if (plane !== 'cloud') output.writeln('  (Tier selection applies only while cloud routing is ON.)');
      // meta-proxy routing.rs gates automatic quota failover on the plane
      // being Passthrough β€” it is the only plane that sees Anthropic's own
      // rate-limit headers. Worth saying, because nothing else reveals that
      // sitting on `local` silently opts you out of ADR-321 entirely.
      if (plane === 'local') {
        output.writeln('  Note: automatic quota failover (ADR-321) applies only on passthrough.');
        output.writeln('        Use your Claude subscription instead: ruflo proxy config --passthrough');
      }
      return { success: true, data: { plane, routingMode: mode } };
    }

    // Setting a tier must never activate Cloud β€” meta-proxy ADR-321
    // Revision 3 keeps the plane choice and this Cloud-only secondary
    // setting as separate controls, so `--routing-mode` alone writes only
    // `routing_mode` and asks for no consent it does not need.
    if (routingMode && !wantCloud) {
      writeRoutingMode(routingMode);
      output.printSuccess(
        routingMode === 'auto'
          ? 'Cloud tier selection set to auto β€” Cognitum scores each prompt.'
          : `Cloud tier selection pinned to ${routingMode}.`,
      );
      if (readDataPlane() !== 'cloud') {
        output.writeln('  Cloud routing is currently OFF, so this takes effect once you enable it:');
        output.writeln('    ruflo proxy config --cloud --yes');
      }
      return { success: true, data: { routingMode } };
    }

    if (leavingCloud) {
      const plane = wantPassthrough ? 'passthrough' : 'local';
      writeDataPlane(plane);
      revokeConsent('cloud-routing', wantPassthrough ? 'proxy-config-passthrough' : 'proxy-config-local-only');
      output.printSuccess(`Cloud routing disabled β€” now on ${plane}.`);
      output.writeln(`  ${describePlane(plane)}`);
      // Naming the other option here is the point: "disable cloud" has two
      // destinations, and the one you land on decides whether your own
      // subscription is used at all.
      if (plane === 'local') {
        output.writeln('  Your own Claude subscription is NOT used on this plane. To use it instead:');
        output.writeln('    ruflo proxy config --passthrough');
      }
      return { success: true, data: { plane } };
    }

    // wantCloud. Read the plane being left BEFORE overwriting it β€” this is
    // the only moment ruflo knows where the user was, and "how do I get back"
    // is otherwise unanswerable from the config file afterwards.
    const previousPlane = readDataPlane();
    if (!hasConsent('cloud-routing')) {
      output.writeln(CLOUD_ROUTING_DISCLOSURE);
      output.writeln('');
      if (!ctx.flags.yes) {
        output.writeln('Re-run with --yes to confirm: ruflo proxy config --cloud --yes');
        // Nothing is written on the unconfirmed path β€” including any
        // --routing-mode passed alongside, which would otherwise leave a
        // trace of an activation the user never confirmed.
        return { success: true, data: { confirmed: false } };
      }
      recordConsent('cloud-routing', true, 'proxy-config-cloud');
    }
    writeDataPlane('cloud');
    if (routingMode) writeRoutingMode(routingMode);
    const effectiveMode = routingMode ?? readRoutingMode();
    output.printSuccess('Cloud routing enabled.');
    output.writeln(
      effectiveMode === 'auto'
        ? '  Tier selection: auto β€” Cognitum scores each prompt and picks low/mid/high.'
        : `  Tier selection: pinned to ${effectiveMode}.`,
    );
    output.writeln('  Requests routed to local backends still never leave this machine.');
    const restore = previousPlane === 'cloud' ? undefined : PLANE_RESTORE_COMMAND[previousPlane];
    if (restore) {
      output.writeln(`  Previous plane: ${previousPlane}. Restore it with:`);
      output.writeln(`    ${restore}`);
    } else {
      output.writeln('  Turn it off with: ruflo proxy config --passthrough (or --local-only)');
    }
    return { success: true, data: { plane: 'cloud', routingMode: effectiveMode, previousPlane } };
  },
};

const SPONSOR_DISCLOSURE = [
  'Enabling sponsored downtime mode.',
  '',
  "While your Claude usage limit resets, requests can be routed through",
  "Cognitum's own model capacity, sponsored at no cost to you. This is a",
  'separate data plane from your own cloud-routing config β€” Cognitum sees',
  'these prompts (server-side, same handling as any api.cognitum.one',
  'request), never your own Claude account.',
  '',
  'Sponsored capacity is rate-limited and best-effort β€” Cognitum may',
  'throttle or decline requests under load. Disable anytime:',
  '  ruflo proxy sponsor-disable',
].join('\n');

const sponsorEnableSub: Command = {
  name: 'sponsor-enable',
  description: "Opt into Cognitum-sponsored downtime capacity (ADR-313)",
  options: [
    { name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
  ],
  action: async (ctx): Promise<CommandResult> => {
    if (hasConsent('sponsored-downtime')) {
      output.writeln('Sponsored downtime mode is already enabled.');
      return { success: true, data: { alreadyEnabled: true } };
    }
    output.writeln(SPONSOR_DISCLOSURE);
    output.writeln('');
    if (!ctx.flags.yes) {
      output.writeln('Re-run with --yes to confirm: ruflo proxy sponsor-enable --yes');
      return { success: true, data: { confirmed: false } };
    }
    recordConsent('sponsored-downtime', true, 'proxy-sponsor-enable');
    writeSponsoredConsentMirror(true);
    recordFunnelEvent('sponsor_mode_enabled', 'statusline', getInstalledCliVersion());
    output.printSuccess('Sponsored downtime mode enabled.');
    output.writeln('The proxy will use it automatically while ruflo settings notices');
    output.writeln('rate-limited is flagged. Disable anytime: ruflo proxy sponsor-disable');
    return { success: true, data: { confirmed: true } };
  },
};

const sponsorDisableSub: Command = {
  name: 'sponsor-disable',
  description: 'Revoke sponsored-downtime consent and stop using sponsored capacity',
  action: async (): Promise<CommandResult> => {
    revokeConsent('sponsored-downtime', 'proxy-sponsor-disable');
    writeSponsoredConsentMirror(false);
    recordFunnelEvent('sponsor_mode_disabled', 'statusline', getInstalledCliVersion());
    output.printSuccess('Sponsored downtime mode disabled.');
    return { success: true };
  },
};

const sponsorStatusSub: Command = {
  name: 'sponsor-status',
  description: 'Show sponsored-downtime consent + rate-limit flag state',
  action: async (): Promise<CommandResult> => {
    const consented = hasConsent('sponsored-downtime');
    const rateLimited = readRateLimitStatus();
    output.writeln(`Sponsored downtime consent: ${consented ? 'granted' : 'not granted'}`);
    output.writeln(`Rate-limit flag: ${rateLimited.limited ? `set (since ${rateLimited.since})` : 'not set'}`);
    if (rateLimited.limited && !consented) {
      output.writeln('');
      output.writeln('You are flagged as rate-limited but have not enabled sponsored');
      output.writeln('capacity. Enable it with: ruflo proxy sponsor-enable --yes');
    }
    return { success: true, data: { consented, rateLimited } };
  },
};

/** Convenience: clear the rate-limited flag once you're back to normal. */
const sponsorClearSub: Command = {
  name: 'sponsor-clear',
  description: 'Clear the rate-limited flag (your Claude limit has reset)',
  action: async (): Promise<CommandResult> => {
    const changed = clearRateLimitStatus();
    if (!changed) {
      output.printError('Rate-limit flag was just toggled β€” try again in a few minutes (ADR-314 anti-abuse cooldown).');
      return { success: false };
    }
    output.printSuccess('Rate-limit flag cleared.');
    return { success: true };
  },
};

const POWER_SAVER_DISCLOSURE = [
  'Enabling power saver mode.',
  '',
  "Everyday requests will route through Cognitum's own difficulty-based",
  'router (cognitum-auto) instead of your Claude subscription directly β€”',
  'simple messages stay cheap, genuinely hard reasoning still escalates to',
  'a comparable frontier model. This is billed to YOUR OWN Cognitum',
  'account (cloud-routing), not sponsored/free capacity β€” a separate',
  'decision from sponsored downtime mode.',
  '',
  'Disable anytime: ruflo proxy power-saver-disable',
].join('\n');

const powerSaverEnableSub: Command = {
  name: 'power-saver-enable',
  description: 'Opt into power saver mode β€” route everyday requests through your own Cognitum account (ADR-314)',
  options: [
    { name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
  ],
  action: async (ctx): Promise<CommandResult> => {
    if (hasConsent('power-saver')) {
      output.writeln('Power saver mode is already enabled.');
      return { success: true, data: { alreadyEnabled: true } };
    }
    output.writeln(POWER_SAVER_DISCLOSURE);
    output.writeln('');
    if (!ctx.flags.yes) {
      output.writeln('Re-run with --yes to confirm: ruflo proxy power-saver-enable --yes');
      return { success: true, data: { confirmed: false } };
    }
    recordConsent('power-saver', true, 'proxy-power-saver-enable');
    writePowerSaverConsentMirror(true);
    recordFunnelEvent('power_saver_enabled', 'statusline', getInstalledCliVersion());
    output.printSuccess('Power saver mode enabled.');
    output.writeln('Flag it active with: ruflo settings notices quota-low');
    output.writeln('Disable anytime: ruflo proxy power-saver-disable');
    return { success: true, data: { confirmed: true } };
  },
};

const powerSaverDisableSub: Command = {
  name: 'power-saver-disable',
  description: 'Revoke power-saver consent and stop routing through Cognitum for cost savings',
  action: async (): Promise<CommandResult> => {
    revokeConsent('power-saver', 'proxy-power-saver-disable');
    writePowerSaverConsentMirror(false);
    recordFunnelEvent('power_saver_disabled', 'statusline', getInstalledCliVersion());
    output.printSuccess('Power saver mode disabled.');
    return { success: true };
  },
};

const powerSaverStatusSub: Command = {
  name: 'power-saver-status',
  description: 'Show power-saver consent + quota-low flag state',
  action: async (): Promise<CommandResult> => {
    const consented = hasConsent('power-saver');
    const quotaLow = readQuotaLowStatus();
    output.writeln(`Power saver consent: ${consented ? 'granted' : 'not granted'}`);
    output.writeln(`Quota-low flag: ${quotaLow.low ? `set (since ${quotaLow.since})` : 'not set'}`);
    if (quotaLow.low && !consented) {
      output.writeln('');
      output.writeln('You are flagged as running low but have not enabled power saver');
      output.writeln('mode. Enable it with: ruflo proxy power-saver-enable --yes');
    }
    return { success: true, data: { consented, quotaLow } };
  },
};

/** Convenience: clear the quota-low flag once you're back to normal. */
const powerSaverClearSub: Command = {
  name: 'power-saver-clear',
  description: 'Clear the quota-low flag',
  action: async (): Promise<CommandResult> => {
    const changed = clearQuotaLowStatus();
    if (!changed) {
      output.printError('Quota-low flag was just toggled β€” try again in a few minutes (ADR-314 anti-abuse cooldown).');
      return { success: false };
    }
    output.printSuccess('Quota-low flag cleared.');
    return { success: true };
  },
};

const TRAINING_SHARE_DISCLOSURE = [
  'Enabling training-data sharing.',
  '',
  'When a request runs on the sponsored plane, the proxy will attach a',
  'consent header telling Cognitum it may retain that interaction β€”',
  '(post safety-scan) β€” as input to its MicroLoRA training pipeline',
  '(meta-llm ADR-251), gated through its existing SHADOW/promotion-rule',
  'safety net; adaptations are never auto-served. This is content, not',
  'just metadata, and is entirely separate from sponsored-downtime',
  'consent β€” using free capacity never implicitly means this is on.',
  '',
  'Declining has zero effect on sponsored-capacity access.',
  '',
  'Disable anytime: ruflo proxy training-share-disable',
].join('\n');

const trainingShareEnableSub: Command = {
  name: 'training-share-enable',
  description: 'Opt into sharing sponsored-plane interaction content for meta-llm training (ADR-315)',
  options: [
    { name: 'yes', description: 'Skip the confirmation prompt', type: 'boolean', default: false },
  ],
  action: async (ctx): Promise<CommandResult> => {
    if (hasConsent('training-data-sharing')) {
      output.writeln('Training-data sharing is already enabled.');
      return { success: true, data: { alreadyEnabled: true } };
    }
    output.writeln(TRAINING_SHARE_DISCLOSURE);
    output.writeln('');
    if (!ctx.flags.yes) {
      output.writeln('Re-run with --yes to confirm: ruflo proxy training-share-enable --yes');
      return { success: true, data: { confirmed: false } };
    }
    recordConsent('training-data-sharing', true, 'proxy-training-share-enable');
    writeTrainingShareConsentMirror(true);
    recordFunnelEvent('training_share_enabled', 'statusline', getInstalledCliVersion());
    output.printSuccess('Training-data sharing enabled.');
    output.writeln('Only sponsored-plane requests carry the consent header. Disable anytime:');
    output.writeln('  ruflo proxy training-share-disable');
    return { success: true, data: { confirmed: true } };
  },
};

const trainingShareDisableSub: Command = {
  name: 'training-share-disable',
  description: 'Revoke training-data-sharing consent β€” stop sending the training consent header',
  action: async (): Promise<CommandResult> => {
    revokeConsent('training-data-sharing', 'proxy-training-share-disable');
    writeTrainingShareConsentMirror(false);
    recordFunnelEvent('training_share_disabled', 'statusline', getInstalledCliVersion());
    output.printSuccess('Training-data sharing disabled.');
    return { success: true };
  },
};

const trainingShareStatusSub: Command = {
  name: 'training-share-status',
  description: 'Show training-data-sharing consent state',
  action: async (): Promise<CommandResult> => {
    const consented = hasConsent('training-data-sharing');
    output.writeln(`Training-data sharing consent: ${consented ? 'granted' : 'not granted'}`);
    if (consented) {
      output.writeln('Sponsored-plane requests carry X-Cognitum-Training-Consent: true.');
    }
    return { success: true, data: { consented } };
  },
};

export const proxyCommand: Command = {
  name: 'proxy',
  description: 'Meta LLM Proxy β€” install/lifecycle + sponsored downtime + power saver + training-data sharing (ADR-304/307/313/314/315)',
  subcommands: [
    ...proxyLifecycleSubcommands,
    configSub,
    sponsorEnableSub, sponsorDisableSub, sponsorStatusSub, sponsorClearSub,
    powerSaverEnableSub, powerSaverDisableSub, powerSaverStatusSub, powerSaverClearSub,
    trainingShareEnableSub, trainingShareDisableSub, trainingShareStatusSub,
  ],
  examples: [
    { command: 'ruflo proxy install --yes', description: `Install the signed Meta-Proxy v${DEFAULT_PROXY_RELEASE} binary` },
    { command: 'ruflo proxy start', description: 'Start meta-proxy in the foreground' },
    { command: 'ruflo proxy status', description: 'Show install + process status' },
    { command: 'ruflo proxy config --cloud --yes', description: 'Enable cloud routing (ADR-304)' },
    { command: 'ruflo proxy config --routing-mode high', description: 'Pin the cloud tier instead of auto (ADR-321)' },
    { command: 'ruflo proxy config --passthrough', description: 'Turn cloud routing off, back to your Claude subscription' },
    { command: 'ruflo proxy config --local-only', description: 'Revert to local-only routing' },
    { command: 'ruflo proxy sponsor-status', description: 'Show current sponsored-mode state' },
    { command: 'ruflo proxy sponsor-enable --yes', description: 'Opt into sponsored downtime capacity' },
    { command: 'ruflo proxy power-saver-enable --yes', description: 'Opt into power saver mode' },
    { command: 'ruflo proxy training-share-enable --yes', description: 'Opt into training-data sharing (ADR-315)' },
  ],
  action: async () => {
    const status = getProxyStatus();
    output.writeln('Meta Proxy');
    output.writeln(`  Installation: ${status.installed ? 'ready' : 'not installed'}`);
    output.writeln(`  Process: ${status.running ? `running (pid ${status.pid})` : 'not running'}`);
    if (status.stalePidFile) output.writeln('  (a stale PID file was found and will be cleared on next start)');
    printProxyConsoleGuidance(status);
    return { success: true, data: status };
  },
};

export default proxyCommand;