// @bun
import {
  ConfigurableShortcutHint,
  OAuthService,
  Select,
  SelectMulti,
  Spinner,
  TextInput,
  init_ConfigurableShortcutHint,
  init_CustomSelect,
  init_SelectMulti,
  init_Spinner,
  init_TextInput,
  init_oauth,
  init_useTerminalSize
} from "./chunk-4vz571bb.js";
import"./chunk-14p6wvsq.js";
import"./chunk-8hseq8b1.js";
import"./chunk-ddtxq6k5.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-ptxteaeh.js";
import"./chunk-wd53a7m4.js";
import"./chunk-hms8ge0k.js";
import"./chunk-whpphypt.js";
import"./chunk-pht800m5.js";
import"./chunk-pjkqh1kq.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-qd3r2s2n.js";
import"./chunk-djzd7tef.js";
import"./chunk-gyhnpbkx.js";
import"./chunk-71sdcaq6.js";
import"./chunk-60gf7p5s.js";
import"./chunk-sj3d0nqx.js";
import"./chunk-9pk9rk2w.js";
import"./chunk-javpza6a.js";
import"./chunk-6v7bre98.js";
import"./chunk-24kv69g3.js";
import {
  init_useExitOnCtrlCDWithKeybindings,
  useExitOnCtrlCDWithKeybindings
} from "./chunk-fcqebw9m.js";
import"./chunk-dnfd3c9s.js";
import"./chunk-15ezj4ww.js";
import"./chunk-1h284c6e.js";
import"./chunk-582g9yce.js";
import {
  init_useKeybinding
} from "./chunk-y3ztgztb.js";
import"./chunk-4spgkgr3.js";
import"./chunk-n8kbhswc.js";
import"./chunk-60fkafk2.js";
import"./chunk-fgbkrbk3.js";
import"./chunk-ssw61jfd.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-k8wq4qsj.js";
import"./chunk-g7d3xx1p.js";
import"./chunk-3wrx2943.js";
import"./chunk-7p9kkh0f.js";
import"./chunk-qp8cgz66.js";
import {
  init_browser,
  openBrowser
} from "./chunk-1mg610h2.js";
import"./chunk-93hc149s.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-nnat9jw5.js";
import"./chunk-hqxp6b72.js";
import"./chunk-4jzkqgf1.js";
import"./chunk-33rd41ng.js";
import"./chunk-f257kqw9.js";
import"./chunk-w5hnghah.js";
import"./chunk-36twraxy.js";
import"./chunk-1bkvnj0y.js";
import"./chunk-akdpcc5p.js";
import {
  getAnthropicApiKey,
  init_auth,
  init_config1 as init_config,
  init_stringUtils,
  isAnthropicAuthEnabled,
  plural,
  saveGlobalConfig,
  saveOAuthTokensIfNeeded
} from "./chunk-7rrkrej7.js";
import"./chunk-6r0bxrh6.js";
import"./chunk-d6500tvx.js";
import"./chunk-jg4bw4hp.js";
import"./chunk-epvbnq43.js";
import"./chunk-tn2sx7j6.js";
import"./chunk-6tzyv21c.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-ch4pgvwq.js";
import"./chunk-99jc4tcw.js";
import"./chunk-fghczfqt.js";
import"./chunk-vwenx8ke.js";
import"./chunk-f86mwfyd.js";
import"./chunk-v4ypszbb.js";
import"./chunk-bk6ck5c2.js";
import"./chunk-ym6j0wv1.js";
import"./chunk-hjmatcgt.js";
import"./chunk-6mdh70q0.js";
import"./chunk-ch92ycde.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-nt5dmk8q.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-0gp4q8aq.js";
import"./chunk-hn4w9pkj.js";
import {
  Byline,
  Dialog,
  KeyboardShortcutHint,
  Link,
  ThemedBox_default,
  ThemedText,
  color,
  init_src,
  require_react,
  setClipboard,
  useKeybinding,
  useKeybindings,
  useTerminalSize,
  useTheme
} from "./chunk-0r6npc3t.js";
import {
  require_jsx_runtime
} from "./chunk-gxyx8b8w.js";
import {
  init_analytics,
  logEvent
} from "./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-t0450ma3.js";
import {
  getGithubRepo,
  init_git
} from "./chunk-0cqw3y8h.js";
import"./chunk-k1sw7km0.js";
import"./chunk-e3j7m7k2.js";
import {
  execFileNoThrow,
  init_execFileNoThrow
} from "./chunk-sc9ycxra.js";
import"./chunk-hhta0nge.js";
import {
  init_log,
  logError
} from "./chunk-8wsj9fff.js";
import"./chunk-m28vg9w4.js";
import"./chunk-f8prtxs3.js";
import"./chunk-41a6f2kv.js";
import {
  execa,
  init_execa
} from "./chunk-c1yc761e.js";
import {
  figures_default,
  init_figures
} from "./chunk-c5g9shkw.js";
import"./chunk-byd20vdq.js";
import"./chunk-kb3758f7.js";
import"./chunk-3j8w0rq8.js";
import"./chunk-tj0dzck2.js";
import"./chunk-aeysytks.js";
import"./chunk-ns1htxgd.js";
import"./chunk-ztqzmfx1.js";
import"./chunk-6k1rsk85.js";
import"./chunk-nxzx0ey9.js";
import"./chunk-yes1my80.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __esm,
  __toESM
} from "./chunk-hhsxm2yr.js";

// src/components/WorkflowMultiselectDialog.tsx
function renderInputGuide(exitState) {
  if (exitState.pending) {
    return /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
      children: [
        "Press ",
        exitState.keyName,
        " again to exit"
      ]
    });
  }
  return /* @__PURE__ */ jsx_runtime.jsxs(Byline, {
    children: [
      /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
        shortcut: "\u2191\u2193",
        action: "navigate"
      }),
      /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
        shortcut: "Space",
        action: "toggle"
      }),
      /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
        shortcut: "Enter",
        action: "confirm"
      }),
      /* @__PURE__ */ jsx_runtime.jsx(ConfigurableShortcutHint, {
        action: "confirm:no",
        context: "Confirmation",
        fallback: "Esc",
        description: "cancel"
      })
    ]
  });
}
function WorkflowMultiselectDialog({ onSubmit, defaultSelections }) {
  const [showError, setShowError] = import_react.useState(false);
  const handleSubmit = import_react.useCallback((selectedValues) => {
    if (selectedValues.length === 0) {
      setShowError(true);
      return;
    }
    setShowError(false);
    onSubmit(selectedValues);
  }, [onSubmit]);
  const handleChange = import_react.useCallback(() => {
    setShowError(false);
  }, []);
  const handleCancel = import_react.useCallback(() => {
    setShowError(true);
  }, []);
  return /* @__PURE__ */ jsx_runtime.jsxs(Dialog, {
    title: "Select GitHub workflows to install",
    subtitle: "We'll create a workflow file in your repository for each one you select.",
    onCancel: handleCancel,
    inputGuide: renderInputGuide,
    children: [
      /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
          dimColor: true,
          children: [
            "More workflow examples (issue triage, CI fixes, etc.) at:",
            " ",
            /* @__PURE__ */ jsx_runtime.jsx(Link, {
              url: "https://github.com/anthropics/claude-code-action/blob/main/examples/",
              children: "https://github.com/anthropics/claude-code-action/blob/main/examples/"
            })
          ]
        })
      }),
      /* @__PURE__ */ jsx_runtime.jsx(SelectMulti, {
        options: WORKFLOWS.map((workflow) => ({
          label: workflow.label,
          value: workflow.value
        })),
        defaultValue: defaultSelections,
        onSubmit: handleSubmit,
        onChange: handleChange,
        onCancel: handleCancel,
        hideIndexes: true
      }),
      showError && /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          color: "error",
          children: "You must select at least one workflow to continue"
        })
      })
    ]
  });
}
var import_react, jsx_runtime, WORKFLOWS;
var init_WorkflowMultiselectDialog = __esm(() => {
  init_src();
  init_ConfigurableShortcutHint();
  init_SelectMulti();
  import_react = __toESM(require_react(), 1);
  jsx_runtime = __toESM(require_jsx_runtime(), 1);
  WORKFLOWS = [
    {
      value: "claude",
      label: "@Chris Code - Tag @claude in issues and PR comments"
    },
    {
      value: "claude-review",
      label: "Chris Code Review - Automated code review on new PRs"
    }
  ];
});

// src/constants/github-app.ts
var PR_TITLE = "Add Chris Code GitHub Workflow", GITHUB_ACTION_SETUP_DOCS_URL = "https://github.com/anthropics/claude-code-action/blob/main/docs/setup.md", WORKFLOW_CONTENT = `name: Chris Code

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened, assigned]
  pull_request_review:
    types: [submitted]

jobs:
  claude:
    if: |
      (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
      (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: read
      issues: read
      id-token: write
      actions: read # Required for Claude to read CI results on PRs
    steps:
      - name: Checkout repository
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2, 2026-04-25
        with:
          fetch-depth: 1

      - name: Run Chris Code
        id: claude
        uses: anthropics/claude-code-action@567fe954a4527e81f132d87d1bdbcc94f7737434 # v1, 2026-04-25
        with:
          anthropic_api_key: \${{ secrets.ANTHROPIC_API_KEY }}

          # This is an optional setting that allows Claude to read CI results on PRs
          additional_permissions: |
            actions: read

          # Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
          # prompt: 'Update the pull request description to include a summary of changes.'

          # Optional: Add claude_args to customize behavior and configuration
          # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
          # or https://code.claude.com/docs/en/cli-reference for available options
          # claude_args: '--allowed-tools Bash(gh pr:*)'

`, PR_BODY = `## \uD83E\uDD16 Installing Chris Code GitHub App

This PR adds a GitHub Actions workflow that enables Chris Code integration in our repository.

### What is Chris Code?

[Chris Code](https://claude.com/claude-code) is an AI coding agent that can help with:
- Bug fixes and improvements  
- Documentation updates
- Implementing new features
- Code reviews and suggestions
- Writing tests
- And more!

### How it works

Once this PR is merged, we'll be able to interact with Claude by mentioning @claude in a pull request or issue comment.
Once the workflow is triggered, Claude will analyze the comment and surrounding context, and execute on the request in a GitHub action.

### Important Notes

- **This workflow won't take effect until this PR is merged**
- **@claude mentions won't work until after the merge is complete**
- The workflow runs automatically whenever Claude is mentioned in PR or issue comments
- Claude gets access to the entire PR or issue context including files, diffs, and previous comments

### Security

- Our Anthropic API key is securely stored as a GitHub Actions secret
- Only users with write access to the repository can trigger the workflow
- All Claude runs are stored in the GitHub Actions run history
- Claude's default tools are limited to reading/writing files and interacting with our repo by creating comments, branches, and commits.
- We can add more allowed tools by adding them to the workflow file like:

\`\`\`
allowed_tools: Bash(npm install),Bash(npm run build),Bash(npm run lint),Bash(npm run test)
\`\`\`

There's more information in the [Chris Code action repo](https://github.com/anthropics/claude-code-action).

After merging this PR, let's try mentioning @claude in a comment on any PR to get started!`, CODE_REVIEW_PLUGIN_WORKFLOW_CONTENT = `name: Chris Code Review

on:
  pull_request:
    types: [opened, synchronize, ready_for_review, reopened]
    # Optional: Only run on specific file changes
    # paths:
    #   - "src/**/*.ts"
    #   - "src/**/*.tsx"
    #   - "src/**/*.js"
    #   - "src/**/*.jsx"

jobs:
  claude-review:
    # Optional: Filter by PR author
    # if: |
    #   github.event.pull_request.user.login == 'external-contributor' ||
    #   github.event.pull_request.user.login == 'new-developer' ||
    #   github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'

    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: read
      issues: read
      id-token: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2, 2026-04-25
        with:
          fetch-depth: 1

      - name: Run Chris Code Review
        id: claude-review
        uses: anthropics/claude-code-action@567fe954a4527e81f132d87d1bdbcc94f7737434 # v1, 2026-04-25
        with:
          anthropic_api_key: \${{ secrets.ANTHROPIC_API_KEY }}
          plugin_marketplaces: 'https://github.com/anthropics/claude-code.git'
          plugins: 'code-review@claude-code-plugins'
          prompt: '/code-review:code-review \${{ github.repository }}/pull/\${{ github.event.pull_request.number }}'
          # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
          # or https://code.claude.com/docs/en/cli-reference for available options

`;
var init_github_app = () => {};

// src/commands/install-github-app/ApiKeyStep.tsx
function ApiKeyStep({
  existingApiKey,
  apiKeyOrOAuthToken,
  onApiKeyChange,
  onSubmit,
  onToggleUseExistingKey,
  onCreateOAuthToken,
  selectedOption = existingApiKey ? "existing" : onCreateOAuthToken ? "oauth" : "new",
  onSelectOption
}) {
  const [cursorOffset, setCursorOffset] = import_react2.useState(0);
  const terminalSize = useTerminalSize();
  const [theme] = useTheme();
  const handlePrevious = import_react2.useCallback(() => {
    if (selectedOption === "new" && onCreateOAuthToken) {
      onSelectOption?.("oauth");
    } else if (selectedOption === "oauth" && existingApiKey) {
      onSelectOption?.("existing");
      onToggleUseExistingKey(true);
    }
  }, [selectedOption, onCreateOAuthToken, existingApiKey, onSelectOption, onToggleUseExistingKey]);
  const handleNext = import_react2.useCallback(() => {
    if (selectedOption === "existing") {
      onSelectOption?.(onCreateOAuthToken ? "oauth" : "new");
      onToggleUseExistingKey(false);
    } else if (selectedOption === "oauth") {
      onSelectOption?.("new");
    }
  }, [selectedOption, onCreateOAuthToken, onSelectOption, onToggleUseExistingKey]);
  const handleConfirm = import_react2.useCallback(() => {
    if (selectedOption === "oauth" && onCreateOAuthToken) {
      onCreateOAuthToken();
    } else {
      onSubmit();
    }
  }, [selectedOption, onCreateOAuthToken, onSubmit]);
  const isTextInputVisible = selectedOption === "new";
  useKeybindings({
    "confirm:previous": handlePrevious,
    "confirm:next": handleNext,
    "confirm:yes": handleConfirm
  }, { context: "Confirmation", isActive: !isTextInputVisible });
  useKeybindings({
    "confirm:previous": handlePrevious,
    "confirm:next": handleNext
  }, { context: "Confirmation", isActive: isTextInputVisible });
  return /* @__PURE__ */ jsx_runtime2.jsxs(jsx_runtime2.Fragment, {
    children: [
      /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
        flexDirection: "column",
        borderStyle: "round",
        paddingX: 1,
        children: [
          /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
            flexDirection: "column",
            marginBottom: 1,
            children: [
              /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
                bold: true,
                children: "Install GitHub App"
              }),
              /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
                dimColor: true,
                children: "Choose API key"
              })
            ]
          }),
          existingApiKey && /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
              children: [
                selectedOption === "existing" ? color("success", theme)("> ") : "  ",
                "Use your existing Chris Code API key"
              ]
            })
          }),
          onCreateOAuthToken && /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
              children: [
                selectedOption === "oauth" ? color("success", theme)("> ") : "  ",
                "Create a long-lived token with your Claude subscription"
              ]
            })
          }),
          /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
              children: [
                selectedOption === "new" ? color("success", theme)("> ") : "  ",
                "Enter a new API key"
              ]
            })
          }),
          selectedOption === "new" && /* @__PURE__ */ jsx_runtime2.jsx(TextInput, {
            value: apiKeyOrOAuthToken,
            onChange: onApiKeyChange,
            onSubmit,
            onPaste: onApiKeyChange,
            focus: true,
            placeholder: "sk-ant\u2026 (Create a new key at https://platform.claude.com/settings/keys)",
            mask: "*",
            columns: terminalSize.columns,
            cursorOffset,
            onChangeCursorOffset: setCursorOffset,
            showCursor: true
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
        marginLeft: 3,
        children: /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          dimColor: true,
          children: "\u2191/\u2193 to select \xB7 Enter to continue"
        })
      })
    ]
  });
}
var import_react2, jsx_runtime2;
var init_ApiKeyStep = __esm(() => {
  init_TextInput();
  init_useTerminalSize();
  init_src();
  init_useKeybinding();
  import_react2 = __toESM(require_react(), 1);
  jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/CheckExistingSecretStep.tsx
function CheckExistingSecretStep({
  useExistingSecret,
  secretName,
  onToggleUseExistingSecret,
  onSecretNameChange,
  onSubmit
}) {
  const [cursorOffset, setCursorOffset] = import_react3.useState(0);
  const terminalSize = useTerminalSize();
  const [theme] = useTheme();
  const handlePrevious = import_react3.useCallback(() => onToggleUseExistingSecret(true), [onToggleUseExistingSecret]);
  const handleNext = import_react3.useCallback(() => onToggleUseExistingSecret(false), [onToggleUseExistingSecret]);
  useKeybindings({
    "confirm:previous": handlePrevious,
    "confirm:next": handleNext,
    "confirm:yes": onSubmit
  }, { context: "Confirmation", isActive: useExistingSecret });
  useKeybindings({
    "confirm:previous": handlePrevious,
    "confirm:next": handleNext
  }, { context: "Confirmation", isActive: !useExistingSecret });
  return /* @__PURE__ */ jsx_runtime3.jsxs(jsx_runtime3.Fragment, {
    children: [
      /* @__PURE__ */ jsx_runtime3.jsxs(ThemedBox_default, {
        flexDirection: "column",
        borderStyle: "round",
        paddingX: 1,
        children: [
          /* @__PURE__ */ jsx_runtime3.jsxs(ThemedBox_default, {
            flexDirection: "column",
            marginBottom: 1,
            children: [
              /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
                bold: true,
                children: "Install GitHub App"
              }),
              /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
                dimColor: true,
                children: "Setup API key secret"
              })
            ]
          }),
          /* @__PURE__ */ jsx_runtime3.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
              color: "warning",
              children: "ANTHROPIC_API_KEY already exists in repository secrets!"
            })
          }),
          /* @__PURE__ */ jsx_runtime3.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
              children: "Would you like to:"
            })
          }),
          /* @__PURE__ */ jsx_runtime3.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
              children: [
                useExistingSecret ? color("success", theme)("> ") : "  ",
                "Use the existing API key"
              ]
            })
          }),
          /* @__PURE__ */ jsx_runtime3.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
              children: [
                !useExistingSecret ? color("success", theme)("> ") : "  ",
                "Create a new secret with a different name"
              ]
            })
          }),
          !useExistingSecret && /* @__PURE__ */ jsx_runtime3.jsxs(jsx_runtime3.Fragment, {
            children: [
              /* @__PURE__ */ jsx_runtime3.jsx(ThemedBox_default, {
                marginBottom: 1,
                children: /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
                  children: "Enter new secret name (alphanumeric with underscores):"
                })
              }),
              /* @__PURE__ */ jsx_runtime3.jsx(TextInput, {
                value: secretName,
                onChange: onSecretNameChange,
                onSubmit,
                focus: true,
                placeholder: "e.g., CLAUDE_API_KEY",
                columns: terminalSize.columns,
                cursorOffset,
                onChangeCursorOffset: setCursorOffset,
                showCursor: true
              })
            ]
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime3.jsx(ThemedBox_default, {
        marginLeft: 3,
        children: /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
          dimColor: true,
          children: "\u2191/\u2193 to select \xB7 Enter to continue"
        })
      })
    ]
  });
}
var import_react3, jsx_runtime3;
var init_CheckExistingSecretStep = __esm(() => {
  init_TextInput();
  init_useTerminalSize();
  init_src();
  init_useKeybinding();
  import_react3 = __toESM(require_react(), 1);
  jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/CheckGitHubStep.tsx
function CheckGitHubStep() {
  return /* @__PURE__ */ jsx_runtime4.jsx(ThemedText, {
    children: "Checking GitHub CLI installation\u2026"
  });
}
var jsx_runtime4;
var init_CheckGitHubStep = __esm(() => {
  init_src();
  jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/ChooseRepoStep.tsx
function ChooseRepoStep({
  currentRepo,
  useCurrentRepo,
  repoUrl,
  onRepoUrlChange,
  onSubmit,
  onToggleUseCurrentRepo
}) {
  const [cursorOffset, setCursorOffset] = import_react4.useState(0);
  const [showEmptyError, setShowEmptyError] = import_react4.useState(false);
  const terminalSize = useTerminalSize();
  const textInputColumns = terminalSize.columns;
  const handleSubmit = import_react4.useCallback(() => {
    const repoName = useCurrentRepo ? currentRepo : repoUrl;
    if (!repoName?.trim()) {
      setShowEmptyError(true);
      return;
    }
    onSubmit();
  }, [useCurrentRepo, currentRepo, repoUrl, onSubmit]);
  const isTextInputVisible = !useCurrentRepo || !currentRepo;
  const handlePrevious = import_react4.useCallback(() => {
    onToggleUseCurrentRepo(true);
    setShowEmptyError(false);
  }, [onToggleUseCurrentRepo]);
  const handleNext = import_react4.useCallback(() => {
    onToggleUseCurrentRepo(false);
    setShowEmptyError(false);
  }, [onToggleUseCurrentRepo]);
  useKeybindings({
    "confirm:previous": handlePrevious,
    "confirm:next": handleNext,
    "confirm:yes": handleSubmit
  }, { context: "Confirmation", isActive: !isTextInputVisible });
  useKeybindings({
    "confirm:previous": handlePrevious,
    "confirm:next": handleNext
  }, { context: "Confirmation", isActive: isTextInputVisible });
  return /* @__PURE__ */ jsx_runtime5.jsxs(jsx_runtime5.Fragment, {
    children: [
      /* @__PURE__ */ jsx_runtime5.jsxs(ThemedBox_default, {
        flexDirection: "column",
        borderStyle: "round",
        paddingX: 1,
        children: [
          /* @__PURE__ */ jsx_runtime5.jsxs(ThemedBox_default, {
            flexDirection: "column",
            marginBottom: 1,
            children: [
              /* @__PURE__ */ jsx_runtime5.jsx(ThemedText, {
                bold: true,
                children: "Install GitHub App"
              }),
              /* @__PURE__ */ jsx_runtime5.jsx(ThemedText, {
                dimColor: true,
                children: "Select GitHub repository"
              })
            ]
          }),
          currentRepo && /* @__PURE__ */ jsx_runtime5.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime5.jsxs(ThemedText, {
              bold: useCurrentRepo,
              color: useCurrentRepo ? "permission" : undefined,
              children: [
                useCurrentRepo ? "> " : "  ",
                "Use current repository: ",
                currentRepo
              ]
            })
          }),
          /* @__PURE__ */ jsx_runtime5.jsx(ThemedBox_default, {
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime5.jsxs(ThemedText, {
              bold: !useCurrentRepo || !currentRepo,
              color: !useCurrentRepo || !currentRepo ? "permission" : undefined,
              children: [
                !useCurrentRepo || !currentRepo ? "> " : "  ",
                currentRepo ? "Enter a different repository" : "Enter repository"
              ]
            })
          }),
          (!useCurrentRepo || !currentRepo) && /* @__PURE__ */ jsx_runtime5.jsx(ThemedBox_default, {
            marginLeft: 2,
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime5.jsx(TextInput, {
              value: repoUrl,
              onChange: (value) => {
                onRepoUrlChange(value);
                setShowEmptyError(false);
              },
              onSubmit: handleSubmit,
              focus: true,
              placeholder: "Enter a repo as owner/repo or https://github.com/owner/repo\u2026",
              columns: textInputColumns,
              cursorOffset,
              onChangeCursorOffset: setCursorOffset,
              showCursor: true
            })
          })
        ]
      }),
      showEmptyError && /* @__PURE__ */ jsx_runtime5.jsx(ThemedBox_default, {
        marginLeft: 3,
        marginBottom: 1,
        children: /* @__PURE__ */ jsx_runtime5.jsx(ThemedText, {
          color: "error",
          children: "Please enter a repository name to continue"
        })
      }),
      /* @__PURE__ */ jsx_runtime5.jsx(ThemedBox_default, {
        marginLeft: 3,
        children: /* @__PURE__ */ jsx_runtime5.jsxs(ThemedText, {
          dimColor: true,
          children: [
            currentRepo ? "\u2191/\u2193 to select \xB7 " : "",
            "Enter to continue"
          ]
        })
      })
    ]
  });
}
var import_react4, jsx_runtime5;
var init_ChooseRepoStep = __esm(() => {
  init_TextInput();
  init_useTerminalSize();
  init_src();
  init_useKeybinding();
  import_react4 = __toESM(require_react(), 1);
  jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/CreatingStep.tsx
function CreatingStep({
  currentWorkflowInstallStep,
  secretExists,
  useExistingSecret,
  secretName,
  skipWorkflow = false,
  selectedWorkflows
}) {
  const progressSteps = skipWorkflow ? [
    "Getting repository information",
    secretExists && useExistingSecret ? "Using existing API key secret" : `Setting up ${secretName} secret`
  ] : [
    "Getting repository information",
    "Creating branch",
    selectedWorkflows.length > 1 ? "Creating workflow files" : "Creating workflow file",
    secretExists && useExistingSecret ? "Using existing API key secret" : `Setting up ${secretName} secret`,
    "Opening pull request page"
  ];
  return /* @__PURE__ */ jsx_runtime6.jsx(jsx_runtime6.Fragment, {
    children: /* @__PURE__ */ jsx_runtime6.jsxs(ThemedBox_default, {
      flexDirection: "column",
      borderStyle: "round",
      paddingX: 1,
      children: [
        /* @__PURE__ */ jsx_runtime6.jsxs(ThemedBox_default, {
          flexDirection: "column",
          marginBottom: 1,
          children: [
            /* @__PURE__ */ jsx_runtime6.jsx(ThemedText, {
              bold: true,
              children: "Install GitHub App"
            }),
            /* @__PURE__ */ jsx_runtime6.jsx(ThemedText, {
              dimColor: true,
              children: "Create GitHub Actions workflow"
            })
          ]
        }),
        progressSteps.map((stepText, index) => {
          let status = "pending";
          if (index < currentWorkflowInstallStep) {
            status = "completed";
          } else if (index === currentWorkflowInstallStep) {
            status = "in-progress";
          }
          return /* @__PURE__ */ jsx_runtime6.jsx(ThemedBox_default, {
            children: /* @__PURE__ */ jsx_runtime6.jsxs(ThemedText, {
              color: status === "completed" ? "success" : status === "in-progress" ? "warning" : undefined,
              children: [
                status === "completed" ? "\u2713 " : "",
                stepText,
                status === "in-progress" ? "\u2026" : ""
              ]
            })
          }, index);
        })
      ]
    })
  });
}
var jsx_runtime6;
var init_CreatingStep = __esm(() => {
  init_src();
  jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/ErrorStep.tsx
function ErrorStep({ error, errorReason, errorInstructions }) {
  return /* @__PURE__ */ jsx_runtime7.jsxs(jsx_runtime7.Fragment, {
    children: [
      /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
        flexDirection: "column",
        borderStyle: "round",
        paddingX: 1,
        children: [
          /* @__PURE__ */ jsx_runtime7.jsx(ThemedBox_default, {
            flexDirection: "column",
            marginBottom: 1,
            children: /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
              bold: true,
              children: "Install GitHub App"
            })
          }),
          /* @__PURE__ */ jsx_runtime7.jsxs(ThemedText, {
            color: "error",
            children: [
              "Error: ",
              error
            ]
          }),
          errorReason && /* @__PURE__ */ jsx_runtime7.jsx(ThemedBox_default, {
            marginTop: 1,
            children: /* @__PURE__ */ jsx_runtime7.jsxs(ThemedText, {
              dimColor: true,
              children: [
                "Reason: ",
                errorReason
              ]
            })
          }),
          errorInstructions && errorInstructions.length > 0 && /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
            flexDirection: "column",
            marginTop: 1,
            children: [
              /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
                dimColor: true,
                children: "How to fix:"
              }),
              errorInstructions.map((instruction, index) => /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
                marginLeft: 2,
                children: [
                  /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
                    dimColor: true,
                    children: "\u2022 "
                  }),
                  /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
                    children: instruction
                  })
                ]
              }, index))
            ]
          }),
          /* @__PURE__ */ jsx_runtime7.jsx(ThemedBox_default, {
            marginTop: 1,
            children: /* @__PURE__ */ jsx_runtime7.jsxs(ThemedText, {
              dimColor: true,
              children: [
                "For manual setup instructions, see: ",
                /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
                  color: "claude",
                  children: GITHUB_ACTION_SETUP_DOCS_URL
                })
              ]
            })
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime7.jsx(ThemedBox_default, {
        marginLeft: 3,
        children: /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
          dimColor: true,
          children: "Press any key to exit"
        })
      })
    ]
  });
}
var jsx_runtime7;
var init_ErrorStep = __esm(() => {
  init_github_app();
  init_src();
  jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/ExistingWorkflowStep.tsx
function ExistingWorkflowStep({ repoName, onSelectAction }) {
  const options = [
    {
      label: "Update workflow file with latest version",
      value: "update"
    },
    {
      label: "Skip workflow update (configure secrets only)",
      value: "skip"
    },
    {
      label: "Exit without making changes",
      value: "exit"
    }
  ];
  const handleSelect = (value) => {
    onSelectAction(value);
  };
  const handleCancel = () => {
    onSelectAction("exit");
  };
  return /* @__PURE__ */ jsx_runtime8.jsxs(ThemedBox_default, {
    flexDirection: "column",
    borderStyle: "round",
    borderDimColor: true,
    paddingX: 1,
    children: [
      /* @__PURE__ */ jsx_runtime8.jsxs(ThemedBox_default, {
        flexDirection: "column",
        marginBottom: 1,
        children: [
          /* @__PURE__ */ jsx_runtime8.jsx(ThemedText, {
            bold: true,
            children: "Existing Workflow Found"
          }),
          /* @__PURE__ */ jsx_runtime8.jsxs(ThemedText, {
            dimColor: true,
            children: [
              "Repository: ",
              repoName
            ]
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime8.jsxs(ThemedBox_default, {
        flexDirection: "column",
        marginBottom: 1,
        children: [
          /* @__PURE__ */ jsx_runtime8.jsxs(ThemedText, {
            children: [
              "A Claude workflow file already exists at ",
              /* @__PURE__ */ jsx_runtime8.jsx(ThemedText, {
                color: "claude",
                children: ".github/workflows/claude.yml"
              })
            ]
          }),
          /* @__PURE__ */ jsx_runtime8.jsx(ThemedText, {
            dimColor: true,
            children: "What would you like to do?"
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime8.jsx(ThemedBox_default, {
        flexDirection: "column",
        children: /* @__PURE__ */ jsx_runtime8.jsx(Select, {
          options,
          onChange: handleSelect,
          onCancel: handleCancel
        })
      }),
      /* @__PURE__ */ jsx_runtime8.jsx(ThemedBox_default, {
        marginTop: 1,
        children: /* @__PURE__ */ jsx_runtime8.jsxs(ThemedText, {
          dimColor: true,
          children: [
            "View the latest workflow template at:",
            " ",
            /* @__PURE__ */ jsx_runtime8.jsx(ThemedText, {
              color: "claude",
              children: "https://github.com/anthropics/claude-code-action/blob/main/examples/claude.yml"
            })
          ]
        })
      })
    ]
  });
}
var jsx_runtime8;
var init_ExistingWorkflowStep = __esm(() => {
  init_CustomSelect();
  init_src();
  jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/InstallAppStep.tsx
function InstallAppStep({ repoUrl, onSubmit }) {
  useKeybinding("confirm:yes", onSubmit, { context: "Confirmation" });
  return /* @__PURE__ */ jsx_runtime9.jsxs(ThemedBox_default, {
    flexDirection: "column",
    borderStyle: "round",
    borderDimColor: true,
    paddingX: 1,
    children: [
      /* @__PURE__ */ jsx_runtime9.jsx(ThemedBox_default, {
        flexDirection: "column",
        marginBottom: 1,
        children: /* @__PURE__ */ jsx_runtime9.jsx(ThemedText, {
          bold: true,
          children: "Install the Claude GitHub App"
        })
      }),
      /* @__PURE__ */ jsx_runtime9.jsx(ThemedBox_default, {
        marginBottom: 1,
        children: /* @__PURE__ */ jsx_runtime9.jsx(ThemedText, {
          children: "Opening browser to install the Claude GitHub App\u2026"
        })
      }),
      /* @__PURE__ */ jsx_runtime9.jsx(ThemedBox_default, {
        marginBottom: 1,
        children: /* @__PURE__ */ jsx_runtime9.jsx(ThemedText, {
          children: "If your browser doesn't open automatically, visit:"
        })
      }),
      /* @__PURE__ */ jsx_runtime9.jsx(ThemedBox_default, {
        marginBottom: 1,
        children: /* @__PURE__ */ jsx_runtime9.jsx(ThemedText, {
          underline: true,
          children: "https://github.com/apps/claude"
        })
      }),
      /* @__PURE__ */ jsx_runtime9.jsx(ThemedBox_default, {
        marginBottom: 1,
        children: /* @__PURE__ */ jsx_runtime9.jsxs(ThemedText, {
          children: [
            "Please install the app for repository: ",
            /* @__PURE__ */ jsx_runtime9.jsx(ThemedText, {
              bold: true,
              children: repoUrl
            })
          ]
        })
      }),
      /* @__PURE__ */ jsx_runtime9.jsx(ThemedBox_default, {
        marginBottom: 1,
        children: /* @__PURE__ */ jsx_runtime9.jsx(ThemedText, {
          dimColor: true,
          children: "Important: Make sure to grant access to this specific repository"
        })
      }),
      /* @__PURE__ */ jsx_runtime9.jsx(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_runtime9.jsxs(ThemedText, {
          bold: true,
          color: "permission",
          children: [
            "Press Enter once you've installed the app",
            figures_default.ellipsis
          ]
        })
      }),
      /* @__PURE__ */ jsx_runtime9.jsx(ThemedBox_default, {
        marginTop: 1,
        children: /* @__PURE__ */ jsx_runtime9.jsxs(ThemedText, {
          dimColor: true,
          children: [
            "Having trouble? See manual setup instructions at: ",
            /* @__PURE__ */ jsx_runtime9.jsx(ThemedText, {
              color: "claude",
              children: GITHUB_ACTION_SETUP_DOCS_URL
            })
          ]
        })
      })
    ]
  });
}
var jsx_runtime9;
var init_InstallAppStep = __esm(() => {
  init_figures();
  init_github_app();
  init_src();
  init_useKeybinding();
  jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/OAuthFlowStep.tsx
function OAuthFlowStep({ onSuccess, onCancel }) {
  const [oauthStatus, setOAuthStatus] = import_react5.useState({
    state: "starting"
  });
  const [oauthService] = import_react5.useState(() => new OAuthService);
  const [pastedCode, setPastedCode] = import_react5.useState("");
  const [cursorOffset, setCursorOffset] = import_react5.useState(0);
  const [showPastePrompt, setShowPastePrompt] = import_react5.useState(false);
  const [urlCopied, setUrlCopied] = import_react5.useState(false);
  const timersRef = import_react5.useRef(new Set);
  const urlCopiedTimerRef = import_react5.useRef(undefined);
  const terminalSize = useTerminalSize();
  const textInputColumns = Math.max(50, terminalSize.columns - PASTE_HERE_MSG.length - 4);
  function handleKeyDown(e) {
    if (oauthStatus.state !== "error")
      return;
    e.preventDefault();
    if (e.key === "return" && oauthStatus.toRetry) {
      setPastedCode("");
      setCursorOffset(0);
      setOAuthStatus({
        state: "about_to_retry",
        nextState: oauthStatus.toRetry
      });
    } else {
      onCancel();
    }
  }
  async function handleSubmitCode(value, url) {
    try {
      const [authorizationCode, state] = value.split("#");
      if (!authorizationCode || !state) {
        setOAuthStatus({
          state: "error",
          message: "Invalid code. Please make sure the full code was copied",
          toRetry: { state: "waiting_for_login", url }
        });
        return;
      }
      logEvent("tengu_oauth_manual_entry", {});
      oauthService.handleManualAuthCodeInput({
        authorizationCode,
        state
      });
    } catch (err) {
      logError(err);
      setOAuthStatus({
        state: "error",
        message: err.message,
        toRetry: { state: "waiting_for_login", url }
      });
    }
  }
  const startOAuth = import_react5.useCallback(async () => {
    timersRef.current.forEach((timer) => clearTimeout(timer));
    timersRef.current.clear();
    try {
      const result = await oauthService.startOAuthFlow(async (url) => {
        setOAuthStatus({ state: "waiting_for_login", url });
        const timer = setTimeout(setShowPastePrompt, 3000, true);
        timersRef.current.add(timer);
      }, {
        loginWithClaudeAi: true,
        inferenceOnly: true,
        expiresIn: 365 * 24 * 60 * 60
      });
      setOAuthStatus({ state: "processing" });
      saveOAuthTokensIfNeeded(result);
      const timer1 = setTimeout((setOAuthStatus2, accessToken, onSuccess2, timersRef2) => {
        setOAuthStatus2({ state: "success", token: accessToken });
        const timer2 = setTimeout(onSuccess2, 1000, accessToken);
        timersRef2.current.add(timer2);
      }, 100, setOAuthStatus, result.accessToken, onSuccess, timersRef);
      timersRef.current.add(timer1);
    } catch (err) {
      const errorMessage = err.message;
      setOAuthStatus({
        state: "error",
        message: errorMessage,
        toRetry: { state: "starting" }
      });
      logError(err);
      logEvent("tengu_oauth_error", {
        error: errorMessage
      });
    }
  }, [oauthService, onSuccess]);
  import_react5.useEffect(() => {
    if (oauthStatus.state === "starting") {
      startOAuth();
    }
  }, [oauthStatus.state, startOAuth]);
  import_react5.useEffect(() => {
    if (oauthStatus.state === "about_to_retry") {
      const timer = setTimeout((nextState, setShowPastePrompt2, setOAuthStatus2) => {
        setShowPastePrompt2(nextState.state === "waiting_for_login");
        setOAuthStatus2(nextState);
      }, 500, oauthStatus.nextState, setShowPastePrompt, setOAuthStatus);
      timersRef.current.add(timer);
    }
  }, [oauthStatus]);
  import_react5.useEffect(() => {
    if (pastedCode === "c" && oauthStatus.state === "waiting_for_login" && showPastePrompt && !urlCopied) {
      setClipboard(oauthStatus.url).then((raw) => {
        if (raw)
          process.stdout.write(raw);
        setUrlCopied(true);
        clearTimeout(urlCopiedTimerRef.current);
        urlCopiedTimerRef.current = setTimeout(setUrlCopied, 2000, false);
      });
      setPastedCode("");
    }
  }, [pastedCode, oauthStatus, showPastePrompt, urlCopied]);
  import_react5.useEffect(() => {
    const timers = timersRef.current;
    return () => {
      oauthService.cleanup();
      timers.forEach((timer) => clearTimeout(timer));
      timers.clear();
      clearTimeout(urlCopiedTimerRef.current);
    };
  }, [oauthService]);
  function renderStatusMessage() {
    switch (oauthStatus.state) {
      case "starting":
        return /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
          children: [
            /* @__PURE__ */ jsx_runtime10.jsx(Spinner, {}),
            /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
              children: "Starting authentication\u2026"
            })
          ]
        });
      case "waiting_for_login":
        return /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
          flexDirection: "column",
          gap: 1,
          children: [
            !showPastePrompt && /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
              children: [
                /* @__PURE__ */ jsx_runtime10.jsx(Spinner, {}),
                /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
                  children: "Opening browser to sign in with your Claude account\u2026"
                })
              ]
            }),
            showPastePrompt && /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
              children: [
                /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
                  children: PASTE_HERE_MSG
                }),
                /* @__PURE__ */ jsx_runtime10.jsx(TextInput, {
                  value: pastedCode,
                  onChange: setPastedCode,
                  onSubmit: (value) => handleSubmitCode(value, oauthStatus.url),
                  cursorOffset,
                  onChangeCursorOffset: setCursorOffset,
                  columns: textInputColumns
                })
              ]
            })
          ]
        });
      case "processing":
        return /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
          children: [
            /* @__PURE__ */ jsx_runtime10.jsx(Spinner, {}),
            /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
              children: "Processing authentication\u2026"
            })
          ]
        });
      case "success":
        return /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
          flexDirection: "column",
          gap: 1,
          children: [
            /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
              color: "success",
              children: "\u2713 Authentication token created successfully!"
            }),
            /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
              dimColor: true,
              children: "Using token for GitHub Actions setup\u2026"
            })
          ]
        });
      case "error":
        return /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
          flexDirection: "column",
          gap: 1,
          children: [
            /* @__PURE__ */ jsx_runtime10.jsxs(ThemedText, {
              color: "error",
              children: [
                "OAuth error: ",
                oauthStatus.message
              ]
            }),
            oauthStatus.toRetry ? /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
              dimColor: true,
              children: "Press Enter to try again, or any other key to cancel"
            }) : /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
              dimColor: true,
              children: "Press any key to return to API key selection"
            })
          ]
        });
      case "about_to_retry":
        return /* @__PURE__ */ jsx_runtime10.jsx(ThemedBox_default, {
          flexDirection: "column",
          gap: 1,
          children: /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
            color: "permission",
            children: "Retrying\u2026"
          })
        });
      default:
        return null;
    }
  }
  return /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
    flexDirection: "column",
    gap: 1,
    tabIndex: 0,
    autoFocus: true,
    onKeyDown: handleKeyDown,
    children: [
      oauthStatus.state === "starting" && /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
        flexDirection: "column",
        gap: 1,
        paddingBottom: 1,
        children: [
          /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
            bold: true,
            children: "Create Authentication Token"
          }),
          /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
            dimColor: true,
            children: "Creating a long-lived token for GitHub Actions"
          })
        ]
      }),
      oauthStatus.state !== "success" && oauthStatus.state !== "starting" && oauthStatus.state !== "processing" && /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
        flexDirection: "column",
        gap: 1,
        paddingBottom: 1,
        children: [
          /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
            bold: true,
            children: "Create Authentication Token"
          }),
          /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
            dimColor: true,
            children: "Creating a long-lived token for GitHub Actions"
          })
        ]
      }, "header"),
      oauthStatus.state === "waiting_for_login" && showPastePrompt && /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
        flexDirection: "column",
        gap: 1,
        paddingBottom: 1,
        children: [
          /* @__PURE__ */ jsx_runtime10.jsxs(ThemedBox_default, {
            paddingX: 1,
            children: [
              /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
                dimColor: true,
                children: "Browser didn't open? Use the url below to sign in "
              }),
              urlCopied ? /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
                color: "success",
                children: "(Copied!)"
              }) : /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
                dimColor: true,
                children: /* @__PURE__ */ jsx_runtime10.jsx(KeyboardShortcutHint, {
                  shortcut: "c",
                  action: "copy",
                  parens: true
                })
              })
            ]
          }),
          /* @__PURE__ */ jsx_runtime10.jsx(Link, {
            url: oauthStatus.url,
            children: /* @__PURE__ */ jsx_runtime10.jsx(ThemedText, {
              dimColor: true,
              children: oauthStatus.url
            })
          })
        ]
      }, "urlToCopy"),
      /* @__PURE__ */ jsx_runtime10.jsx(ThemedBox_default, {
        paddingLeft: 1,
        flexDirection: "column",
        gap: 1,
        children: renderStatusMessage()
      })
    ]
  });
}
var import_react5, jsx_runtime10, PASTE_HERE_MSG = "Paste code here if prompted > ";
var init_OAuthFlowStep = __esm(() => {
  init_analytics();
  init_src();
  init_Spinner();
  init_TextInput();
  init_useTerminalSize();
  init_src();
  init_oauth();
  init_auth();
  init_log();
  import_react5 = __toESM(require_react(), 1);
  jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/SuccessStep.tsx
function SuccessStep({
  secretExists,
  useExistingSecret,
  secretName,
  skipWorkflow = false
}) {
  return /* @__PURE__ */ jsx_runtime11.jsxs(jsx_runtime11.Fragment, {
    children: [
      /* @__PURE__ */ jsx_runtime11.jsxs(ThemedBox_default, {
        flexDirection: "column",
        borderStyle: "round",
        paddingX: 1,
        children: [
          /* @__PURE__ */ jsx_runtime11.jsxs(ThemedBox_default, {
            flexDirection: "column",
            marginBottom: 1,
            children: [
              /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
                bold: true,
                children: "Install GitHub App"
              }),
              /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
                dimColor: true,
                children: "Success"
              })
            ]
          }),
          !skipWorkflow && /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
            color: "success",
            children: "\u2713 GitHub Actions workflow created!"
          }),
          secretExists && useExistingSecret && /* @__PURE__ */ jsx_runtime11.jsx(ThemedBox_default, {
            marginTop: 1,
            children: /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
              color: "success",
              children: "\u2713 Using existing ANTHROPIC_API_KEY secret"
            })
          }),
          (!secretExists || !useExistingSecret) && /* @__PURE__ */ jsx_runtime11.jsx(ThemedBox_default, {
            marginTop: 1,
            children: /* @__PURE__ */ jsx_runtime11.jsxs(ThemedText, {
              color: "success",
              children: [
                "\u2713 API key saved as ",
                secretName,
                " secret"
              ]
            })
          }),
          /* @__PURE__ */ jsx_runtime11.jsx(ThemedBox_default, {
            marginTop: 1,
            children: /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
              children: "Next steps:"
            })
          }),
          skipWorkflow ? /* @__PURE__ */ jsx_runtime11.jsxs(jsx_runtime11.Fragment, {
            children: [
              /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
                children: "1. Install the Claude GitHub App if you haven't already"
              }),
              /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
                children: "2. Your workflow file was kept unchanged"
              }),
              /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
                children: "3. API key is configured and ready to use"
              })
            ]
          }) : /* @__PURE__ */ jsx_runtime11.jsxs(jsx_runtime11.Fragment, {
            children: [
              /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
                children: "1. A pre-filled PR page has been created"
              }),
              /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
                children: "2. Install the Claude GitHub App if you haven't already"
              }),
              /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
                children: "3. Merge the PR to enable Claude PR assistance"
              })
            ]
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime11.jsx(ThemedBox_default, {
        marginLeft: 3,
        children: /* @__PURE__ */ jsx_runtime11.jsx(ThemedText, {
          dimColor: true,
          children: "Press any key to exit"
        })
      })
    ]
  });
}
var jsx_runtime11;
var init_SuccessStep = __esm(() => {
  init_src();
  jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/setupGitHubActions.ts
async function createWorkflowFile(repoName, branchName, workflowPath, workflowContent, secretName, message, context) {
  const checkFileResult = await execFileNoThrow("gh", [
    "api",
    `repos/${repoName}/contents/${workflowPath}`,
    "--jq",
    ".sha"
  ]);
  let fileSha = null;
  if (checkFileResult.code === 0) {
    fileSha = checkFileResult.stdout.trim();
  }
  let content = workflowContent;
  if (secretName === "CLAUDE_CODE_OAUTH_TOKEN") {
    content = workflowContent.replace(/anthropic_api_key: \$\{\{ secrets\.ANTHROPIC_API_KEY \}\}/g, `claude_code_oauth_token: \${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}`);
  } else if (secretName !== "ANTHROPIC_API_KEY") {
    content = workflowContent.replace(/anthropic_api_key: \$\{\{ secrets\.ANTHROPIC_API_KEY \}\}/g, `anthropic_api_key: \${{ secrets.${secretName} }}`);
  }
  const base64Content = Buffer.from(content).toString("base64");
  const apiParams = [
    "api",
    "--method",
    "PUT",
    `repos/${repoName}/contents/${workflowPath}`,
    "-f",
    `message=${fileSha ? `"Update ${message}"` : `"${message}"`}`,
    "-f",
    `content=${base64Content}`,
    "-f",
    `branch=${branchName}`
  ];
  if (fileSha) {
    apiParams.push("-f", `sha=${fileSha}`);
  }
  const createFileResult = await execFileNoThrow("gh", apiParams);
  if (createFileResult.code !== 0) {
    if (createFileResult.stderr.includes("422") && createFileResult.stderr.includes("sha")) {
      logEvent("tengu_setup_github_actions_failed", {
        reason: "failed_to_create_workflow_file",
        exit_code: createFileResult.code,
        ...context
      });
      throw new Error(`Failed to create workflow file ${workflowPath}: A Claude workflow file already exists in this repository. Please remove it first or update it manually.`);
    }
    logEvent("tengu_setup_github_actions_failed", {
      reason: "failed_to_create_workflow_file",
      exit_code: createFileResult.code,
      ...context
    });
    const helpText = `

Need help? Common issues:
` + `\xB7 Permission denied \u2192 Run: gh auth refresh -h github.com -s repo,workflow
` + `\xB7 Not authorized \u2192 Ensure you have admin access to the repository
` + "\xB7 For manual setup \u2192 Visit: https://github.com/anthropics/claude-code-action";
    throw new Error(`Failed to create workflow file ${workflowPath}: ${createFileResult.stderr}${helpText}`);
  }
}
async function setupGitHubActions(repoName, apiKeyOrOAuthToken, secretName, updateProgress, skipWorkflow = false, selectedWorkflows, authType, context) {
  try {
    logEvent("tengu_setup_github_actions_started", {
      skip_workflow: skipWorkflow,
      has_api_key: !!apiKeyOrOAuthToken,
      using_default_secret_name: secretName === "ANTHROPIC_API_KEY",
      selected_claude_workflow: selectedWorkflows.includes("claude"),
      selected_claude_review_workflow: selectedWorkflows.includes("claude-review"),
      ...context
    });
    const repoCheckResult = await execFileNoThrow("gh", [
      "api",
      `repos/${repoName}`,
      "--jq",
      ".id"
    ]);
    if (repoCheckResult.code !== 0) {
      logEvent("tengu_setup_github_actions_failed", {
        reason: "repo_not_found",
        exit_code: repoCheckResult.code,
        ...context
      });
      throw new Error(`Failed to access repository ${repoName}: ${repoCheckResult.stderr}`);
    }
    const defaultBranchResult = await execFileNoThrow("gh", [
      "api",
      `repos/${repoName}`,
      "--jq",
      ".default_branch"
    ]);
    if (defaultBranchResult.code !== 0) {
      logEvent("tengu_setup_github_actions_failed", {
        reason: "failed_to_get_default_branch",
        exit_code: defaultBranchResult.code,
        ...context
      });
      throw new Error(`Failed to get default branch: ${defaultBranchResult.stderr}`);
    }
    const defaultBranch = defaultBranchResult.stdout.trim();
    const shaResult = await execFileNoThrow("gh", [
      "api",
      `repos/${repoName}/git/ref/heads/${defaultBranch}`,
      "--jq",
      ".object.sha"
    ]);
    if (shaResult.code !== 0) {
      logEvent("tengu_setup_github_actions_failed", {
        reason: "failed_to_get_branch_sha",
        exit_code: shaResult.code,
        ...context
      });
      throw new Error(`Failed to get branch SHA: ${shaResult.stderr}`);
    }
    const sha = shaResult.stdout.trim();
    let branchName = null;
    if (!skipWorkflow) {
      updateProgress();
      branchName = `add-claude-github-actions-${Date.now()}`;
      const createBranchResult = await execFileNoThrow("gh", [
        "api",
        "--method",
        "POST",
        `repos/${repoName}/git/refs`,
        "-f",
        `ref=refs/heads/${branchName}`,
        "-f",
        `sha=${sha}`
      ]);
      if (createBranchResult.code !== 0) {
        logEvent("tengu_setup_github_actions_failed", {
          reason: "failed_to_create_branch",
          exit_code: createBranchResult.code,
          ...context
        });
        throw new Error(`Failed to create branch: ${createBranchResult.stderr}`);
      }
      updateProgress();
      const workflows = [];
      if (selectedWorkflows.includes("claude")) {
        workflows.push({
          path: ".github/workflows/claude.yml",
          content: WORKFLOW_CONTENT,
          message: "Claude PR Assistant workflow"
        });
      }
      if (selectedWorkflows.includes("claude-review")) {
        workflows.push({
          path: ".github/workflows/claude-code-review.yml",
          content: CODE_REVIEW_PLUGIN_WORKFLOW_CONTENT,
          message: "Chris Code Review workflow"
        });
      }
      for (const workflow of workflows) {
        await createWorkflowFile(repoName, branchName, workflow.path, workflow.content, secretName, workflow.message, context);
      }
    }
    updateProgress();
    if (apiKeyOrOAuthToken) {
      const setSecretResult = await execFileNoThrow("gh", [
        "secret",
        "set",
        secretName,
        "--body",
        apiKeyOrOAuthToken,
        "--repo",
        repoName
      ]);
      if (setSecretResult.code !== 0) {
        logEvent("tengu_setup_github_actions_failed", {
          reason: "failed_to_set_api_key_secret",
          exit_code: setSecretResult.code,
          ...context
        });
        const helpText = `

Need help? Common issues:
` + `\xB7 Permission denied \u2192 Run: gh auth refresh -h github.com -s repo
` + `\xB7 Not authorized \u2192 Ensure you have admin access to the repository
` + "\xB7 For manual setup \u2192 Visit: https://github.com/anthropics/claude-code-action";
        throw new Error(`Failed to set API key secret: ${setSecretResult.stderr || "Unknown error"}${helpText}`);
      }
    }
    if (!skipWorkflow && branchName) {
      updateProgress();
      const compareUrl = `https://github.com/${repoName}/compare/${defaultBranch}...${branchName}?quick_pull=1&title=${encodeURIComponent(PR_TITLE)}&body=${encodeURIComponent(PR_BODY)}`;
      await openBrowser(compareUrl);
    }
    logEvent("tengu_setup_github_actions_completed", {
      skip_workflow: skipWorkflow,
      has_api_key: !!apiKeyOrOAuthToken,
      auth_type: authType,
      using_default_secret_name: secretName === "ANTHROPIC_API_KEY",
      selected_claude_workflow: selectedWorkflows.includes("claude"),
      selected_claude_review_workflow: selectedWorkflows.includes("claude-review"),
      ...context
    });
    saveGlobalConfig((current) => ({
      ...current,
      githubActionSetupCount: (current.githubActionSetupCount ?? 0) + 1
    }));
  } catch (error) {
    if (!error || !(error instanceof Error) || !error.message.includes("Failed to")) {
      logEvent("tengu_setup_github_actions_failed", {
        reason: "unexpected_error",
        ...context
      });
    }
    if (error instanceof Error) {
      logError(error);
    }
    throw error;
  }
}
var init_setupGitHubActions = __esm(() => {
  init_analytics();
  init_config();
  init_github_app();
  init_browser();
  init_execFileNoThrow();
  init_log();
});

// src/commands/install-github-app/WarningsStep.tsx
function WarningsStep({ warnings, onContinue }) {
  useKeybinding("confirm:yes", onContinue, { context: "Confirmation" });
  return /* @__PURE__ */ jsx_runtime12.jsx(jsx_runtime12.Fragment, {
    children: /* @__PURE__ */ jsx_runtime12.jsxs(ThemedBox_default, {
      flexDirection: "column",
      borderStyle: "round",
      paddingX: 1,
      children: [
        /* @__PURE__ */ jsx_runtime12.jsxs(ThemedBox_default, {
          flexDirection: "column",
          marginBottom: 1,
          children: [
            /* @__PURE__ */ jsx_runtime12.jsxs(ThemedText, {
              bold: true,
              children: [
                figures_default.warning,
                " Setup Warnings"
              ]
            }),
            /* @__PURE__ */ jsx_runtime12.jsx(ThemedText, {
              dimColor: true,
              children: "We found some potential issues, but you can continue anyway"
            })
          ]
        }),
        warnings.map((warning, index) => /* @__PURE__ */ jsx_runtime12.jsxs(ThemedBox_default, {
          flexDirection: "column",
          marginBottom: 1,
          children: [
            /* @__PURE__ */ jsx_runtime12.jsx(ThemedText, {
              color: "warning",
              bold: true,
              children: warning.title
            }),
            /* @__PURE__ */ jsx_runtime12.jsx(ThemedText, {
              children: warning.message
            }),
            warning.instructions.length > 0 && /* @__PURE__ */ jsx_runtime12.jsx(ThemedBox_default, {
              flexDirection: "column",
              marginLeft: 2,
              marginTop: 1,
              children: warning.instructions.map((instruction, i) => /* @__PURE__ */ jsx_runtime12.jsxs(ThemedText, {
                dimColor: true,
                children: [
                  "\u2022 ",
                  instruction
                ]
              }, i))
            })
          ]
        }, index)),
        /* @__PURE__ */ jsx_runtime12.jsx(ThemedBox_default, {
          marginTop: 1,
          children: /* @__PURE__ */ jsx_runtime12.jsx(ThemedText, {
            bold: true,
            color: "permission",
            children: "Press Enter to continue anyway, or Ctrl+C to exit and fix issues"
          })
        }),
        /* @__PURE__ */ jsx_runtime12.jsx(ThemedBox_default, {
          marginTop: 1,
          children: /* @__PURE__ */ jsx_runtime12.jsxs(ThemedText, {
            dimColor: true,
            children: [
              "You can also try the manual setup steps if needed:",
              " ",
              /* @__PURE__ */ jsx_runtime12.jsx(ThemedText, {
                color: "claude",
                children: GITHUB_ACTION_SETUP_DOCS_URL
              })
            ]
          })
        })
      ]
    })
  });
}
var jsx_runtime12;
var init_WarningsStep = __esm(() => {
  init_figures();
  init_github_app();
  init_src();
  init_useKeybinding();
  jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/install-github-app/install-github-app.tsx
function InstallGitHubApp(props) {
  const [existingApiKey] = import_react6.useState(() => getAnthropicApiKey());
  const [state, setState] = import_react6.useState({
    ...INITIAL_STATE,
    useExistingKey: !!existingApiKey,
    selectedApiKeyOption: existingApiKey ? "existing" : isAnthropicAuthEnabled() ? "oauth" : "new"
  });
  useExitOnCtrlCDWithKeybindings();
  import_react6.default.useEffect(() => {
    logEvent("tengu_install_github_app_started", {});
  }, []);
  const checkGitHubCLI = import_react6.useCallback(async () => {
    const warnings = [];
    const ghVersionResult = await execa("gh --version", {
      shell: true,
      reject: false
    });
    if (ghVersionResult.exitCode !== 0) {
      warnings.push({
        title: "GitHub CLI not found",
        message: "GitHub CLI (gh) does not appear to be installed or accessible.",
        instructions: [
          "Install GitHub CLI from https://cli.github.com/",
          "macOS: brew install gh",
          "Windows: winget install --id GitHub.cli",
          "Linux: See installation instructions at https://github.com/cli/cli#installation"
        ]
      });
    }
    const authResult = await execa("gh auth status -a", {
      shell: true,
      reject: false
    });
    if (authResult.exitCode !== 0) {
      warnings.push({
        title: "GitHub CLI not authenticated",
        message: "GitHub CLI does not appear to be authenticated.",
        instructions: [
          "Run: gh auth login",
          "Follow the prompts to authenticate with GitHub",
          "Or set up authentication using environment variables or other methods"
        ]
      });
    } else {
      const tokenScopesMatch = authResult.stdout.match(/Token scopes:.*$/m);
      if (tokenScopesMatch) {
        const scopes = tokenScopesMatch[0];
        const missingScopes = [];
        if (!scopes.includes("repo")) {
          missingScopes.push("repo");
        }
        if (!scopes.includes("workflow")) {
          missingScopes.push("workflow");
        }
        if (missingScopes.length > 0) {
          setState((prev) => ({
            ...prev,
            step: "error",
            error: `GitHub CLI is missing required permissions: ${missingScopes.join(", ")}.`,
            errorReason: "Missing required scopes",
            errorInstructions: [
              `Your GitHub CLI authentication is missing the "${missingScopes.join('" and "')}" ${plural(missingScopes.length, "scope")} needed to manage GitHub Actions and secrets.`,
              "",
              "To fix this, run:",
              "  gh auth refresh -h github.com -s repo,workflow",
              "",
              "This will add the necessary permissions to manage workflows and secrets."
            ]
          }));
          return;
        }
      }
    }
    const currentRepo = await getGithubRepo() ?? "";
    logEvent("tengu_install_github_app_step_completed", {
      step: "check-gh"
    });
    setState((prev) => ({
      ...prev,
      warnings,
      currentRepo,
      selectedRepoName: currentRepo,
      useCurrentRepo: !!currentRepo,
      step: warnings.length > 0 ? "warnings" : "choose-repo"
    }));
  }, []);
  import_react6.default.useEffect(() => {
    if (state.step === "check-gh") {
      checkGitHubCLI();
    }
  }, [state.step, checkGitHubCLI]);
  const runSetupGitHubActions = import_react6.useCallback(async (apiKeyOrOAuthToken, secretName) => {
    setState((prev) => ({
      ...prev,
      step: "creating",
      currentWorkflowInstallStep: 0
    }));
    try {
      await setupGitHubActions(state.selectedRepoName, apiKeyOrOAuthToken, secretName, () => {
        setState((prev) => ({
          ...prev,
          currentWorkflowInstallStep: prev.currentWorkflowInstallStep + 1
        }));
      }, state.workflowAction === "skip", state.selectedWorkflows, state.authType, {
        useCurrentRepo: state.useCurrentRepo,
        workflowExists: state.workflowExists,
        secretExists: state.secretExists
      });
      logEvent("tengu_install_github_app_step_completed", {
        step: "creating"
      });
      setState((prev) => ({ ...prev, step: "success" }));
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Failed to set up GitHub Actions";
      if (errorMessage.includes("workflow file already exists")) {
        logEvent("tengu_install_github_app_error", {
          reason: "workflow_file_exists"
        });
        setState((prev) => ({
          ...prev,
          step: "error",
          error: "A Claude workflow file already exists in this repository.",
          errorReason: "Workflow file conflict",
          errorInstructions: [
            "The file .github/workflows/claude.yml already exists",
            "You can either:",
            "  1. Delete the existing file and run this command again",
            "  2. Update the existing file manually using the template from:",
            `     ${GITHUB_ACTION_SETUP_DOCS_URL}`
          ]
        }));
      } else {
        logEvent("tengu_install_github_app_error", {
          reason: "setup_github_actions_failed"
        });
        setState((prev) => ({
          ...prev,
          step: "error",
          error: errorMessage,
          errorReason: "GitHub Actions setup failed",
          errorInstructions: []
        }));
      }
    }
  }, [
    state.selectedRepoName,
    state.workflowAction,
    state.selectedWorkflows,
    state.useCurrentRepo,
    state.workflowExists,
    state.secretExists,
    state.authType
  ]);
  async function openGitHubAppInstallation() {
    const installUrl = "https://github.com/apps/claude";
    await openBrowser(installUrl);
  }
  async function checkRepositoryPermissions(repoName) {
    try {
      const result = await execFileNoThrow("gh", ["api", `repos/${repoName}`, "--jq", ".permissions.admin"]);
      if (result.code === 0) {
        const hasAdmin = result.stdout.trim() === "true";
        return { hasAccess: hasAdmin };
      }
      if (result.stderr.includes("404") || result.stderr.includes("Not Found")) {
        return {
          hasAccess: false,
          error: "repository_not_found"
        };
      }
      return { hasAccess: false };
    } catch {
      return { hasAccess: false };
    }
  }
  async function checkExistingWorkflowFile(repoName) {
    const checkFileResult = await execFileNoThrow("gh", [
      "api",
      `repos/${repoName}/contents/.github/workflows/claude.yml`,
      "--jq",
      ".sha"
    ]);
    return checkFileResult.code === 0;
  }
  async function checkExistingSecret() {
    const checkSecretsResult = await execFileNoThrow("gh", [
      "secret",
      "list",
      "--app",
      "actions",
      "--repo",
      state.selectedRepoName
    ]);
    if (checkSecretsResult.code === 0) {
      const lines = checkSecretsResult.stdout.split(`
`);
      const hasAnthropicKey = lines.some((line) => {
        return /^ANTHROPIC_API_KEY\s+/.test(line);
      });
      if (hasAnthropicKey) {
        setState((prev) => ({
          ...prev,
          secretExists: true,
          step: "check-existing-secret"
        }));
      } else {
        if (existingApiKey) {
          setState((prev) => ({
            ...prev,
            apiKeyOrOAuthToken: existingApiKey,
            useExistingKey: true
          }));
          await runSetupGitHubActions(existingApiKey, state.secretName);
        } else {
          setState((prev) => ({ ...prev, step: "api-key" }));
        }
      }
    } else {
      if (existingApiKey) {
        setState((prev) => ({
          ...prev,
          apiKeyOrOAuthToken: existingApiKey,
          useExistingKey: true
        }));
        await runSetupGitHubActions(existingApiKey, state.secretName);
      } else {
        setState((prev) => ({ ...prev, step: "api-key" }));
      }
    }
  }
  const handleSubmit = async () => {
    if (state.step === "warnings") {
      logEvent("tengu_install_github_app_step_completed", {
        step: "warnings"
      });
      setState((prev) => ({ ...prev, step: "install-app" }));
      setTimeout(openGitHubAppInstallation, 0);
    } else if (state.step === "choose-repo") {
      let repoName = state.useCurrentRepo ? state.currentRepo : state.selectedRepoName;
      if (!repoName.trim()) {
        return;
      }
      const repoWarnings = [];
      if (repoName.includes("github.com")) {
        const match = repoName.match(/github\.com[:/]([^/]+\/[^/]+)(\.git)?$/);
        if (!match) {
          repoWarnings.push({
            title: "Invalid GitHub URL format",
            message: "The repository URL format appears to be invalid.",
            instructions: ["Use format: owner/repo or https://github.com/owner/repo", "Example: anthropics/claude-cli"]
          });
        } else {
          repoName = match[1]?.replace(/\.git$/, "") || "";
        }
      }
      if (!repoName.includes("/")) {
        repoWarnings.push({
          title: "Repository format warning",
          message: 'Repository should be in format "owner/repo"',
          instructions: ["Use format: owner/repo", "Example: anthropics/claude-cli"]
        });
      }
      const permissionCheck = await checkRepositoryPermissions(repoName);
      if (permissionCheck.error === "repository_not_found") {
        repoWarnings.push({
          title: "Repository not found",
          message: `Repository ${repoName} was not found or you don't have access.`,
          instructions: [
            `Check that the repository name is correct: ${repoName}`,
            "Ensure you have access to this repository",
            'For private repositories, make sure your GitHub token has the "repo" scope',
            "You can add the repo scope with: gh auth refresh -h github.com -s repo,workflow"
          ]
        });
      } else if (!permissionCheck.hasAccess) {
        repoWarnings.push({
          title: "Admin permissions required",
          message: `You might need admin permissions on ${repoName} to set up GitHub Actions.`,
          instructions: [
            "Repository admins can install GitHub Apps and set secrets",
            "Ask a repository admin to run this command if setup fails",
            "Alternatively, you can use the manual setup instructions"
          ]
        });
      }
      const workflowExists = await checkExistingWorkflowFile(repoName);
      if (repoWarnings.length > 0) {
        const allWarnings = [...state.warnings, ...repoWarnings];
        setState((prev) => ({
          ...prev,
          selectedRepoName: repoName,
          workflowExists,
          warnings: allWarnings,
          step: "warnings"
        }));
      } else {
        logEvent("tengu_install_github_app_step_completed", {
          step: "choose-repo"
        });
        setState((prev) => ({
          ...prev,
          selectedRepoName: repoName,
          workflowExists,
          step: "install-app"
        }));
        setTimeout(openGitHubAppInstallation, 0);
      }
    } else if (state.step === "install-app") {
      logEvent("tengu_install_github_app_step_completed", {
        step: "install-app"
      });
      if (state.workflowExists) {
        setState((prev) => ({ ...prev, step: "check-existing-workflow" }));
      } else {
        setState((prev) => ({ ...prev, step: "select-workflows" }));
      }
    } else if (state.step === "check-existing-workflow") {
      return;
    } else if (state.step === "select-workflows") {
      return;
    } else if (state.step === "check-existing-secret") {
      logEvent("tengu_install_github_app_step_completed", {
        step: "check-existing-secret"
      });
      if (state.useExistingSecret) {
        await runSetupGitHubActions(null, state.secretName);
      } else {
        await runSetupGitHubActions(state.apiKeyOrOAuthToken, state.secretName);
      }
    } else if (state.step === "api-key") {
      if (state.selectedApiKeyOption === "oauth") {
        return;
      }
      const apiKeyToUse = state.selectedApiKeyOption === "existing" ? existingApiKey : state.apiKeyOrOAuthToken;
      if (!apiKeyToUse) {
        logEvent("tengu_install_github_app_error", {
          reason: "api_key_missing"
        });
        setState((prev) => ({
          ...prev,
          step: "error",
          error: "API key is required"
        }));
        return;
      }
      setState((prev) => ({
        ...prev,
        apiKeyOrOAuthToken: apiKeyToUse,
        useExistingKey: state.selectedApiKeyOption === "existing"
      }));
      const checkSecretsResult = await execFileNoThrow("gh", [
        "secret",
        "list",
        "--app",
        "actions",
        "--repo",
        state.selectedRepoName
      ]);
      if (checkSecretsResult.code === 0) {
        const lines = checkSecretsResult.stdout.split(`
`);
        const hasAnthropicKey = lines.some((line) => {
          return /^ANTHROPIC_API_KEY\s+/.test(line);
        });
        if (hasAnthropicKey) {
          logEvent("tengu_install_github_app_step_completed", {
            step: "api-key"
          });
          setState((prev) => ({
            ...prev,
            secretExists: true,
            step: "check-existing-secret"
          }));
        } else {
          logEvent("tengu_install_github_app_step_completed", {
            step: "api-key"
          });
          await runSetupGitHubActions(apiKeyToUse, state.secretName);
        }
      } else {
        logEvent("tengu_install_github_app_step_completed", {
          step: "api-key"
        });
        await runSetupGitHubActions(apiKeyToUse, state.secretName);
      }
    }
  };
  const handleRepoUrlChange = (value) => {
    setState((prev) => ({ ...prev, selectedRepoName: value }));
  };
  const handleApiKeyChange = (value) => {
    setState((prev) => ({ ...prev, apiKeyOrOAuthToken: value }));
  };
  const handleApiKeyOptionChange = (option) => {
    setState((prev) => ({ ...prev, selectedApiKeyOption: option }));
  };
  const handleCreateOAuthToken = import_react6.useCallback(() => {
    logEvent("tengu_install_github_app_step_completed", {
      step: "api-key"
    });
    setState((prev) => ({ ...prev, step: "oauth-flow" }));
  }, []);
  const handleOAuthSuccess = import_react6.useCallback((token) => {
    logEvent("tengu_install_github_app_step_completed", {
      step: "oauth-flow"
    });
    setState((prev) => ({
      ...prev,
      apiKeyOrOAuthToken: token,
      useExistingKey: false,
      secretName: "CLAUDE_CODE_OAUTH_TOKEN",
      authType: "oauth_token"
    }));
    runSetupGitHubActions(token, "CLAUDE_CODE_OAUTH_TOKEN");
  }, [runSetupGitHubActions]);
  const handleOAuthCancel = import_react6.useCallback(() => {
    setState((prev) => ({ ...prev, step: "api-key" }));
  }, []);
  const handleSecretNameChange = (value) => {
    if (value && !/^[a-zA-Z0-9_]+$/.test(value))
      return;
    setState((prev) => ({ ...prev, secretName: value }));
  };
  const handleToggleUseCurrentRepo = (useCurrentRepo) => {
    setState((prev) => ({
      ...prev,
      useCurrentRepo,
      selectedRepoName: useCurrentRepo ? prev.currentRepo : ""
    }));
  };
  const handleToggleUseExistingKey = (useExistingKey) => {
    setState((prev) => ({ ...prev, useExistingKey }));
  };
  const handleToggleUseExistingSecret = (useExistingSecret) => {
    setState((prev) => ({
      ...prev,
      useExistingSecret,
      secretName: useExistingSecret ? "ANTHROPIC_API_KEY" : ""
    }));
  };
  const handleWorkflowAction = async (action) => {
    if (action === "exit") {
      props.onDone("Installation cancelled by user");
      return;
    }
    logEvent("tengu_install_github_app_step_completed", {
      step: "check-existing-workflow"
    });
    setState((prev) => ({ ...prev, workflowAction: action }));
    if (action === "skip" || action === "update") {
      if (existingApiKey) {
        await checkExistingSecret();
      } else {
        setState((prev) => ({ ...prev, step: "api-key" }));
      }
    }
  };
  function handleDismissKeyDown(e) {
    e.preventDefault();
    if (state.step === "success") {
      logEvent("tengu_install_github_app_completed", {});
    }
    props.onDone(state.step === "success" ? "GitHub Actions setup complete!" : state.error ? `Couldn't install GitHub App: ${state.error}
For manual setup instructions, see: ${GITHUB_ACTION_SETUP_DOCS_URL}` : `GitHub App installation failed
For manual setup instructions, see: ${GITHUB_ACTION_SETUP_DOCS_URL}`);
  }
  switch (state.step) {
    case "check-gh":
      return /* @__PURE__ */ jsx_runtime13.jsx(CheckGitHubStep, {});
    case "warnings":
      return /* @__PURE__ */ jsx_runtime13.jsx(WarningsStep, {
        warnings: state.warnings,
        onContinue: handleSubmit
      });
    case "choose-repo":
      return /* @__PURE__ */ jsx_runtime13.jsx(ChooseRepoStep, {
        currentRepo: state.currentRepo,
        useCurrentRepo: state.useCurrentRepo,
        repoUrl: state.selectedRepoName,
        onRepoUrlChange: handleRepoUrlChange,
        onToggleUseCurrentRepo: handleToggleUseCurrentRepo,
        onSubmit: handleSubmit
      });
    case "install-app":
      return /* @__PURE__ */ jsx_runtime13.jsx(InstallAppStep, {
        repoUrl: state.selectedRepoName,
        onSubmit: handleSubmit
      });
    case "check-existing-workflow":
      return /* @__PURE__ */ jsx_runtime13.jsx(ExistingWorkflowStep, {
        repoName: state.selectedRepoName,
        onSelectAction: handleWorkflowAction
      });
    case "check-existing-secret":
      return /* @__PURE__ */ jsx_runtime13.jsx(CheckExistingSecretStep, {
        useExistingSecret: state.useExistingSecret,
        secretName: state.secretName,
        onToggleUseExistingSecret: handleToggleUseExistingSecret,
        onSecretNameChange: handleSecretNameChange,
        onSubmit: handleSubmit
      });
    case "api-key":
      return /* @__PURE__ */ jsx_runtime13.jsx(ApiKeyStep, {
        existingApiKey,
        useExistingKey: state.useExistingKey,
        apiKeyOrOAuthToken: state.apiKeyOrOAuthToken,
        onApiKeyChange: handleApiKeyChange,
        onToggleUseExistingKey: handleToggleUseExistingKey,
        onSubmit: handleSubmit,
        onCreateOAuthToken: isAnthropicAuthEnabled() ? handleCreateOAuthToken : undefined,
        selectedOption: state.selectedApiKeyOption,
        onSelectOption: handleApiKeyOptionChange
      });
    case "creating":
      return /* @__PURE__ */ jsx_runtime13.jsx(CreatingStep, {
        currentWorkflowInstallStep: state.currentWorkflowInstallStep,
        secretExists: state.secretExists,
        useExistingSecret: state.useExistingSecret,
        secretName: state.secretName,
        skipWorkflow: state.workflowAction === "skip",
        selectedWorkflows: state.selectedWorkflows
      });
    case "success":
      return /* @__PURE__ */ jsx_runtime13.jsx(ThemedBox_default, {
        tabIndex: 0,
        autoFocus: true,
        onKeyDown: handleDismissKeyDown,
        children: /* @__PURE__ */ jsx_runtime13.jsx(SuccessStep, {
          secretExists: state.secretExists,
          useExistingSecret: state.useExistingSecret,
          secretName: state.secretName,
          skipWorkflow: state.workflowAction === "skip"
        })
      });
    case "error":
      return /* @__PURE__ */ jsx_runtime13.jsx(ThemedBox_default, {
        tabIndex: 0,
        autoFocus: true,
        onKeyDown: handleDismissKeyDown,
        children: /* @__PURE__ */ jsx_runtime13.jsx(ErrorStep, {
          error: state.error,
          errorReason: state.errorReason,
          errorInstructions: state.errorInstructions
        })
      });
    case "select-workflows":
      return /* @__PURE__ */ jsx_runtime13.jsx(WorkflowMultiselectDialog, {
        defaultSelections: state.selectedWorkflows,
        onSubmit: (selectedWorkflows) => {
          logEvent("tengu_install_github_app_step_completed", {
            step: "select-workflows"
          });
          setState((prev) => ({
            ...prev,
            selectedWorkflows
          }));
          if (existingApiKey) {
            checkExistingSecret();
          } else {
            setState((prev) => ({ ...prev, step: "api-key" }));
          }
        }
      });
    case "oauth-flow":
      return /* @__PURE__ */ jsx_runtime13.jsx(OAuthFlowStep, {
        onSuccess: handleOAuthSuccess,
        onCancel: handleOAuthCancel
      });
  }
}
async function call(onDone) {
  return /* @__PURE__ */ jsx_runtime13.jsx(InstallGitHubApp, {
    onDone
  });
}
var import_react6, jsx_runtime13, INITIAL_STATE;
var init_install_github_app = __esm(() => {
  init_execa();
  init_analytics();
  init_WorkflowMultiselectDialog();
  init_github_app();
  init_useExitOnCtrlCDWithKeybindings();
  init_src();
  init_auth();
  init_browser();
  init_execFileNoThrow();
  init_git();
  init_stringUtils();
  init_ApiKeyStep();
  init_CheckExistingSecretStep();
  init_CheckGitHubStep();
  init_ChooseRepoStep();
  init_CreatingStep();
  init_ErrorStep();
  init_ExistingWorkflowStep();
  init_InstallAppStep();
  init_OAuthFlowStep();
  init_SuccessStep();
  init_setupGitHubActions();
  init_WarningsStep();
  import_react6 = __toESM(require_react(), 1);
  jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
  INITIAL_STATE = {
    step: "check-gh",
    selectedRepoName: "",
    currentRepo: "",
    useCurrentRepo: false,
    apiKeyOrOAuthToken: "",
    useExistingKey: true,
    currentWorkflowInstallStep: 0,
    warnings: [],
    secretExists: false,
    secretName: "ANTHROPIC_API_KEY",
    useExistingSecret: true,
    workflowExists: false,
    selectedWorkflows: ["claude", "claude-review"],
    selectedApiKeyOption: "new",
    authType: "api_key"
  };
});
init_install_github_app();

export {
  call
};

//# debugId=9DC8FF949F12863E64756E2164756E21
//# sourceMappingURL=chunk-4rkn75p1.js.map
