SLOPSHOPPER

env

Edit .env files in a pane inside Claude Code. Claude manages keys and asks you for values without ever seeing them.

panebandguardcommandtoasttool
★ 4v0.5.0MITupdated 2026-10-13davekiss/env
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · env
│ ┃ env ✕ › fix the failing auth test and add an audit log call │ ┃ + .env.local │ ┃ ⏺ Read(src/auth.ts) │ ┃ No .env files in the project root yet. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(cat .env) │ ⎿ Denied by env: env: .env files are edited by the user in │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /env │ ⎿ env: Opened the env pane. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · env
+ .env.local No .env files in the project root yet.
README

<img src="assets/logo.png" alt="env" width="160">

<h1 align="center">env</h1>

A Claude Code mod for <code>.env</code> files.<br> Claude knows which keys exist and asks you for values. You paste them into a pane it can't read.

<img src="https://img.shields.io/badge/version-0.5.0-000" alt="Version 0.5.0"> <img src="https://img.shields.io/badge/Claude%20Code-2.1.287%2B-000" alt="Claude Code 2.1.287+"> <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-000" alt="MIT"></a>


You're wiring up a deploy with Claude, and it needs your Cloudflare account ID. So it tells you to "add it to your .env", and you go find the dashboard, find the field, open the file, paste, save. Or you're in a hurry and paste it straight into the chat, where it now lives in a transcript forever. Either way, Claude can cat .env whenever it likes.

With env, Claude asks with a card instead: what it needs, why, the steps to find it, and a link to the exact page. You paste the value and press Enter. Claude hears back CLOUDFLARE_ACCOUNT_ID is now set in .env and carries on.

The value went into the file. It never went into the conversation.

╭──────────────────────────────────────────────────────╮
│ Claude needs a value                                 │
│                                                      │
│ CLOUDFLARE_ACCOUNT_ID → .env                         │
│ Wrangler needs it to deploy the worker               │
│                                                      │
│ 1. Open the Cloudflare dashboard                     │
│ 2. Click ⋯ next to your account name                 │
│ 3. Click Copy account ID                             │
│                                                      │
│ https://dash.cloudflare.com   copy link              │
│ Looks like: 32-character hex                         │
│                                                      │
│ Paste ▸ ________________________________   save      │
│ ✓ looks right                                        │
│ skip for now                                         │
╰──────────────────────────────────────────────────────╯

Get started

/plugin marketplace add davekiss/mods
/plugin install env@davekiss

Then ask Claude for something that needs a key, or type /env to open the pane yourself.

What it's good at

It asks the way a teammate would

When Claude needs a value it calls mcp__env__request, and you get a card with the steps to find it, named by the labels on screen, plus the link to the page it lives on. If Claude knows what a valid value looks like, the card checks your paste as you type: ✓ looks right, or a red warning when you've copied the account name instead of the ID. Enter still saves, since you know better than a regex.

Skip it or close the pane, and Claude is told that too, so it never sits waiting on you.

"Set up the Stripe keys." · "I need a Cloudflare token for Workers AI." · "Fill in whatever .env.example has that I'm missing."

Claude never sees a value

Two layers keep values out of the conversation:

  1. The fence. Claude's Read, Edit, Write and Grep can't open .env* files. Bash commands that read them (cat .env, source .env, printenv) are refused, and the refusal points Claude to env's own tools. Templates like .env.example stay readable.
  2. The scrubber. Any value in your env files that's 8 characters or longer is replaced with [env:KEY] in every tool result, message and prompt before it's stored or sent. That catches the indirect leaks, like a script that prints process.env. The fence is best-effort; the scrubber is the guarantee.

Programs that load .env themselves, like npm run dev or your tests, run normally.

It still does the busywork

Claude can manage your env files without reading them:

ToolWhat it does
mcp__env__listLists keys and what each value looks like (kind, length, a known prefix like sk_live_), never the value
mcp__env__requestShows you the card above
mcp__env__generateWrites a random secret (auth secrets, signing keys) without returning it
mcp__env__copyCopies a value, or a whole file, to another env file, another git worktree, another folder, or another machine over ssh (box:~/app/.env), without reading it. Other folders and machines ask you once first.
mcp__env__removeComments a key out, so you can bring it back
mcp__env__pushRuns a hosting CLI (vercel, gh, wrangler, fly…) with {{KEY}} filled in from your env file, after you approve the command
mcp__env__pullRuns a hosting or secrets CLI (vercel env pull, doppler, op read…) and writes what it returns into your env file, reporting only which keys changed

"Rename CLOUDFLARE_API_TOKEN to CLOUDFLARE_AUTH_TOKEN." · "Copy the database URL into .env.test." · "Copy my .env.local into the new worktree." · "Copy .env.production from the staging box." · "Generate a NEXTAUTH_SECRET."

It talks to your host

Claude can send a value to Vercel, GitHub Actions, Cloudflare and the rest through the CLIs you're already logged into. It writes the command with a placeholder, you approve it, and env fills in the value and pipes it to the CLI's stdin:

Run `vercel env add STRIPE_SECRET_KEY production < "{{STRIPE_SECRET_KEY}}"`
with STRIPE_SECRET_KEY filled in from .env.local?

Only known hosting CLIs run (vercel, gh, wrangler, fly, netlify, railway, heroku, supabase, firebase, render, doppler, op, aws, gcloud, az), and any value that comes back in their output is redacted before Claude reads it.

It works the other way too. mcp__env__pull runs vercel env pull, doppler secrets download, heroku config or op read and merges the result into your env file, keeping your comments and order. A key you already set to something else is left alone unless you agree to replace it.

"Push the Stripe keys to Vercel production." · "Set the Cloudflare token as a GitHub Actions secret." · "Pull the dev env from Vercel." · "Get the Stripe key from 1Password."

It edits the file the way you wrote it

/env opens a pane with a tab for each .env* file in the project root. Values are masked (sk_live_••••4f2a), and each key has buttons to copy, edit, show or delete it. + add key adds a new one, and keys that .env.example has but your file doesn't are listed so you can fill them in with one click. A warning shows if the file isn't in .gitignore.

Comments, ordering and quoting stay as you wrote them. Only the line you change is rewritten.

It fits a narrow terminal

A pane that Claude opens on its own needs 144 columns. Below that, the card shows in the band above the prompt instead, and Claude tells you to paste it there. Type /env or press open /env pane whenever you want the full pane.

Limits

  • The paste field isn't masked, so a value is visible on your screen until you press Enter.
  • Values shorter than 8 characters, booleans and numbers aren't scrubbed.
  • Only the project root is scanned. Monorepo subfolders aren't covered yet.
  • Don't paste a secret into the chat box. A value only gets scrubbed once it's saved in an env file.
  • The pane draws in the terminal and the desktop app's Code tab. In the VS Code extension and claude -p, the fence, scrubber and tools still work, but there's no pane.

Development

claude plugin validate .
claude plugin test .
claude --plugin-dir "$PWD"   # load the mod from this checkout

To release, bump the version in .claude-plugin/plugin.json and the badge above, then push.

License

MIT

Source 8 files
hooks/register.tsx 997 lines
1import { atom, read, update } from 'claude-code'
2import type { ElementTable, EngineInterface, Register } from 'claude-code'
3
4import type { EnvEditing, EnvFit, EnvRequest } from '../types'
5import * as env from './dotenv'
6import { basename, bashReason, grepReason, isProtectedPath } from './guard'
7import * as pull from './pull'
8import * as push from './push'
9import * as remote from './remote'
10import * as worktree from './worktree'
11
12const PANE = 'env'
13const TOOL = 'mcp__env__'
14
15const files = atom({ plugin: 'env', key: 'files' } as const, [] as string[])
16const active = atom({ plugin: 'env', key: 'active' } as const, '')
17const editing = atom({ plugin: 'env', key: 'editing' } as const, null as EnvEditing | null)
18const revealed = atom({ plugin: 'env', key: 'revealed' } as const, null as string | null)
19const confirm = atom({ plugin: 'env', key: 'confirm' } as const, null as string | null)
20const request = atom({ plugin: 'env', key: 'request' } as const, null as EnvRequest | null)
21const fit = atom({ plugin: 'env', key: 'fit' } as const, null as EnvFit)
22const rev = atom({ plugin: 'env', key: 'rev' } as const, 0)
23const flash = atom({ plugin: 'env', key: 'flash' } as const, null as string | null)
24// The pane is open but the surface hasn't placed it (opened unasked on a
25// narrow terminal), so the request card draws above the prompt instead
26const isWaiting = atom({ plugin: 'env', key: 'isWaiting' } as const, false)
27// Hosts and folders outside the worktrees the user has let copy reach
28const allowed = atom({ plugin: 'env', key: 'allowed' } as const, [] as string[])
29
30const KEY_NAME = /^[A-Za-z_][A-Za-z0-9_.-]*$/
31
32const DENY =
33  'env: .env files are edited by the user in the /env pane, and their values never enter ' +
34  'this conversation. Use mcp__env__list to see keys and what each value looks like, ' +
35  'mcp__env__request to ask the user for a value, mcp__env__generate for a random secret, and ' +
36  'mcp__env__push and mcp__env__pull to send values to or fetch them from a hosting service through its CLI. ' +
37  'Programs that load .env (npm run dev, tests) still run normally.'
38
39type Engine = EngineInterface
40
41const WHERE = " An env file name in this project's root, or a path to one at the root of another of this repo's git worktrees."
42
43// Value -> key, for the scrubber. Rebuilt whenever an env file changes.
44let index: env.Index = []
45let signature = ''
46// Env files written in other worktrees this session, so the scrubber covers them too
47const elsewhere = new Set<string>()
48
49function rank(name: string): number {
50  if (env.isTemplate(name)) return 9
51  if (name === '.env') return 0
52  if (name === '.env.local') return 1
53  return 2
54}
55
56async function load($: Engine, file: string): Promise<env.Line[]> {
57  try {
58    return env.parse(await $.fs.read(file))
59  } catch {
60    return []
61  }
62}
63
64// Reads every env file in the project root, rebuilds the scrub index and
65// redraws the pane. Cheap enough to run on every change.
66async function refresh($: Engine): Promise<void> {
67  const listing = await $.fs.list().catch(() => [])
68  const names = listing
69    .filter(entry => entry.kind === 'file' && env.isEnvFile(entry.name))
70    .map(entry => entry.name)
71    .sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
72
73  const parsed: Record<string, env.Line[]> = {}
74  for (const name of [...names, ...elsewhere]) parsed[name] = await load($, name)
75  index = env.buildIndex(parsed)
76  signature = listing
77    .filter(entry => env.isEnvFile(entry.name))
78    .map(entry => `${entry.name}:${entry.mtimeMs}:${entry.size}`)
79    .join('|')
80
81  await update($, files, () => names)
82  await update($, active, current => (names.includes(current) ? current : (names[0] ?? '')))
83  await update($, rev, n => n + 1)
84}
85
86async function save($: Engine, file: string, lines: env.Line[]): Promise<void> {
87  await $.fs.write(file, env.serialize(lines))
88  if (file.includes('/')) elsewhere.add(file)
89  await refresh($)
90}
91
92async function defaultFile($: Engine): Promise<string> {
93  const names = await read($, files)
94  return names.includes('.env.local') ? '.env.local' : names.includes('.env') ? '.env' : '.env.local'
95}
96
97// An env file name in the project root, or a path to one at the root of
98// another of this repo's worktrees
99async function place($: Engine, value: unknown): Promise<worktree.Place | { error: string; outside?: string }> {
100  if (typeof value === 'string' && value.trim().startsWith('~/')) {
101    const home = await $.env.get('HOME')
102    if (home) value = `${home}${value.trim().slice(1)}`
103  }
104  if (typeof value !== 'string' || !value.includes('/')) return worktree.resolve(value, '', [])
105  const git = async (...args: string[]) => {
106    const ran = await $.process.run(['git', ...args]).catch(() => null)
107    return ran?.exitCode === 0 ? ran.stdout.trim() : ''
108  }
109  const root = await git('rev-parse', '--show-toplevel')
110  const prefix = await git('rev-parse', '--show-prefix')
111  const cwd = prefix ? `${root}/${prefix.replace(/\/$/, '')}` : root
112  return worktree.resolve(value, cwd, worktree.parseWorktrees(await git('worktree', 'list', '--porcelain')))
113}
114
115// Where copy reads or writes: a file place() accepts, a file in a folder
116// outside the worktrees, or host:path over ssh. The last two need the user's
117// say-so, once per folder or host.
118type Spot = worktree.Place & { host?: string }
119
120async function spot($: Engine, value: unknown): Promise<Spot | { error: string }> {
121  const far = remote.parse(value)
122  if (far && 'error' in far) return far
123  if (far) {
124    const label = `${far.host}:${far.path}`
125    const error = await allow($, far.host, `Let env copy env files to and from ${far.host} over ssh?`)
126    return error ? { error } : { ...far, label }
127  }
128  const near = await place($, value)
129  if (!('error' in near) || !near.outside) return near
130  const dir = near.outside.slice(0, near.outside.lastIndexOf('/')) || '/'
131  const error = await allow($, dir, `Let env copy env files to and from ${dir}? It is not one of this repo's worktrees.`)
132  return error ? { error } : { path: near.outside, label: near.outside }
133}
134
135async function allow($: Engine, where: string, question: string): Promise<string | undefined> {
136  if ((await read($, allowed)).includes(where)) return undefined
137  const yes = 'Allow'
138  const answer = await $.ui.ask(question, { header: 'env', options: [yes, "Don't allow"] }).catch(() => null)
139  if (answer !== yes) return `The user declined to let env reach ${where}.`
140  await update($, allowed, list => [...list, where])
141  return undefined
142}
143
144async function readSpot($: Engine, at: Spot): Promise<{ lines: env.Line[]; exists: boolean } | { error: string }> {
145  if (!at.host) return { lines: await load($, at.path), exists: await $.fs.exists(at.path) }
146  const ran = await ssh($, at, remote.reader({ host: at.host, path: at.path }))
147  if ('error' in ran) return ran
148  if (ran.exitCode === remote.MISSING) return { lines: [], exists: false }
149  return { lines: env.parse(ran.stdout), exists: true }
150}
151
152async function writeSpot($: Engine, at: Spot, lines: env.Line[]): Promise<string | undefined> {
153  if (!at.host) return void (await save($, at.path, lines))
154  const ran = await ssh($, at, remote.writer({ host: at.host, path: at.path }), env.serialize(lines))
155  return 'error' in ran ? ran.error : undefined
156}
157
158// BatchMode makes ssh fail instead of waiting on a password or host key prompt
159async function ssh($: Engine, at: Spot, argv: string[], stdin?: string) {
160  const help = `Ask the user to run \`! ssh ${at.host} true\` to check the connection, then try again.`
161  const ran = await $.process.run(argv, { stdin, timeoutMs: 60_000 }).catch((error: unknown) => ({ error: String(error) }))
162  if ('error' in ran) return { error: `ssh could not run: ${env.scrub(ran.error, index)}. ${help}` }
163  if (ran.exitCode !== 0 && ran.exitCode !== remote.MISSING) {
164    return { error: `ssh to ${at.host} exited ${ran.exitCode}, so nothing was copied. ${env.scrub(ran.stderr.trim(), index)}\n${help}` }
165  }
166  if (ran.isStdoutTruncated) return { error: `${at.label} is too large to copy.` }
167  return ran
168}
169
170// The file a tool names, or the default when it names none. A named file
171// that won't resolve is an error, never a quiet swap for the default.
172async function fileOf($: Engine, value: unknown): Promise<worktree.Place | { error: string }> {
173  if (value !== undefined) return place($, value)
174  const name = await defaultFile($)
175  return { path: name, label: name }
176}
177
178function fitOf(value: string, pattern: string | undefined): EnvFit {
179  if (value === '' || !pattern) return null
180  try {
181    return new RegExp(pattern).test(value.trim()) ? 'ok' : 'off'
182  } catch {
183    return null
184  }
185}
186
187async function isIgnored($: Engine, file: string): Promise<boolean> {
188  const text = await $.fs.read('.gitignore').catch(() => '')
189  return text.split(/\r?\n/).some(row => {
190    const pattern = row.trim().replace(/^\//, '')
191    if (pattern === '' || pattern.startsWith('#') || pattern.startsWith('!')) return false
192    const glob = new RegExp('^' + pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$')
193    return glob.test(file)
194  })
195}
196
197// Ends an open request without a value and tells Claude why, so it doesn't
198// sit waiting for a message that will never come
199async function abandon($: Engine, how: 'skipped' | 'closed the pane without setting'): Promise<void> {
200  const asked = await read($, request)
201  if (!asked) return
202  await update($, request, () => null)
203  await update($, fit, () => null)
204  void $.prompt.submit({
205    text: `[env] The user ${how} ${asked.key}, so it is still not set in ${asked.file}. Carry on without it, or ask what they'd like to do.`,
206  })
207}
208
209type Block = { type: string; [field: string]: unknown }
210
211function scrubBlock(block: Block): Block {
212  if (block.type === 'text' && typeof block.text === 'string') {
213    const text = env.scrub(block.text, index)
214    return text === block.text ? block : { ...block, text }
215  }
216  if (block.type === 'tool_result') {
217    if (typeof block.content === 'string') {
218      const content = env.scrub(block.content, index)
219      return content === block.content ? block : { ...block, content }
220    }
221    if (Array.isArray(block.content)) {
222      const content: Block[] = (block.content as Block[]).map(scrubBlock)
223      return content.every((part, i) => part === (block.content as unknown[])[i]) ? block : { ...block, content }
224    }
225  }
226  return block
227}
228
229async function store($: Engine, target: string, key: string, value: string): Promise<void> {
230  await save($, target, env.set(await load($, target), key, value))
231  await update($, editing, () => null)
232  await update($, flash, () => `Saved ${key} in ${target}`)
233  const wanted = await read($, request)
234  if (wanted && wanted.key === key && wanted.file === target) {
235    await update($, request, () => null)
236    await update($, fit, () => null)
237    void $.prompt.submit({ text: `[env] ${key} is now set in ${target}. Continue.` })
238  }
239}
240
241// The card Claude's request draws: what, why, where to get it, and the
242// field to paste into, readable at a glance. In the pane, or in the band
243// above the prompt while the pane waits for a wider terminal.
244async function requestCard($: Engine, ui: ElementTable<'terminal' | 'desktop'>, asked: EnvRequest, where: 'pane' | 'band') {
245  const { Box, Text, Button, Input, Markdown } = ui
246  const pasted = await read($, fit)
247  return (
248    <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginBottom={where === 'pane' ? 1 : 0}>
249      <Text bold color="yellow">
250        Claude needs a value
251      </Text>
252      <Box gap={1} marginTop={1}>
253        <Text bold>{asked.key}</Text>
254        <Text dimColor>→ {asked.file}</Text>
255      </Box>
256      {asked.reason !== '' && <Text wrap="wrap">{asked.reason}</Text>}
257
258      {asked.steps.length > 0 && (
259        <Box flexDirection="column" marginTop={1}>
260          {asked.steps.map((step, i) => (
261            <Box key={`step:${i}`} gap={1}>
262              <Text bold color="yellow">
263                {String(i + 1)}.
264              </Text>
265              <Text wrap="wrap">{step}</Text>
266            </Box>
267          ))}
268        </Box>
269      )}
270
271      {asked.url && (
272        <Box gap={1} marginTop={1}>
273          <Markdown text={`[${asked.url}](${asked.url})`} />
274          <Button
275            key="copy-url"
276            label="copy link"
277            plain
278            dimColor
279            onPress={press => void $.ui.copy({ text: asked.url ?? '', surface: press.surface })}
280          />
281        </Box>
282      )}
283      {asked.format && <Text dimColor>Looks like: {asked.format}</Text>}
284
285      <Box marginTop={1}>
286        <Input
287          key="request"
288          label="Paste ▸ "
289          placeholder={`${asked.key}, then Enter`}
290          submitLabel="save"
291          autoFocus
292          onInput={value => void update($, fit, () => fitOf(value, asked.pattern))}
293          onSubmit={value => void store($, asked.file, asked.key, value.trim())}
294        />
295      </Box>
296      {pasted === 'ok' && <Text color="green">✓ looks right</Text>}
297      {pasted === 'off' && <Text color="red">✗ doesn't look like {asked.format ?? 'the expected format'}; Enter still saves</Text>}
298      <Box gap={1} marginTop={1}>
299        <Button key="skip" label="skip for now" plain dimColor onPress={() => void abandon($, 'skipped')} />
300        {where === 'band' && (
301          <Button
302            key="open-pane"
303            label="open /env pane"
304            plain
305            dimColor
306            onPress={async () => {
307              const opened = await $.ui.open({ id: PANE, title: 'env', focus: true })
308              await update($, isWaiting, () => !opened.isPlaced)
309            }}
310          />
311        )}
312      </Box>
313      {where === 'band' && <Text dimColor>Click the field or press ctrl+x tab to paste.</Text>}
314    </Box>
315  )
316}
317
318export const register: Register = on => {
319  on('session.start', async ($, e, next) => {
320    await refresh($)
321
322    await $.command.register({
323      name: 'env',
324      description: 'Edit .env files without showing values to Claude',
325      immediate: true,
326    })
327
328    await $.tool.register({
329      name: 'list',
330      description:
331        "Lists the project's .env files and their keys, with what each value looks like (set or empty, " +
332        'kind, length, a known prefix such as sk_live_) but never the value itself, plus keys missing ' +
333        'compared with .env.example. Use this instead of reading .env files, which is blocked.',
334      inputSchema: {
335        type: 'object',
336        properties: { file: { type: 'string', description: 'One env file, e.g. .env.local. Default: all.' } },
337      },
338    })
339    await $.tool.register({
340      name: 'request',
341      description:
342        'Asks the user to paste the value of one env variable into a card in the /env pane. You never ' +
343        'see the value. The user may be moving fast, so make the card easy to act on: give the exact ' +
344        'steps to find the value (where to click, what the field is labelled), the URL of the page it ' +
345        'lives on, and what a valid value looks like. After calling this, stop and wait: you get a ' +
346        'message once the value is saved, skipped, or the pane is closed.',
347      inputSchema: {
348        type: 'object',
349        properties: {
350          key: { type: 'string', description: 'The variable name the code reads, e.g. CLOUDFLARE_ACCOUNT_ID' },
351          file: { type: 'string', description: 'Default .env.local, else .env.' + WHERE },
352          reason: { type: 'string', description: 'Why it is needed, in under 12 words' },
353          steps: {
354            type: 'array',
355            items: { type: 'string' },
356            description:
357              '2-5 short imperative steps, one action each, naming the exact labels on screen. ' +
358              'E.g. ["Open the Cloudflare dashboard", "Pick any domain", "Copy Account ID from the right sidebar"]',
359          },
360          url: { type: 'string', description: 'The https page where the value can be found or created' },
361          format: { type: 'string', description: 'What a valid value looks like, e.g. "32-character hex"' },
362          pattern: { type: 'string', description: 'Optional regex the value should match, to flag a bad paste' },
363        },
364        required: ['key', 'reason', 'steps'],
365      },
366    })
367    await $.tool.register({
368      name: 'generate',
369      description:
370        'Sets an env variable to a new random secret (session secrets, signing keys, webhook ' +
371        'secrets you control). The value is written to the file and never returned. Refuses to ' +
372        'replace an existing value unless overwrite is true.',
373      inputSchema: {
374        type: 'object',
375        properties: {
376          key: { type: 'string' },
377          file: { type: 'string', description: 'Default .env.local, else .env.' + WHERE },
378          bytes: { type: 'number', description: 'Random bytes, default 32' },
379          format: { type: 'string', enum: ['base64url', 'hex'] },
380          overwrite: { type: 'boolean' },
381        },
382        required: ['key'],
383      },
384    })
385    await $.tool.register({
386      name: 'copy',
387      description:
388        'Copies env values without reading them: one key (optionally renamed with as), or with no key ' +
389        "the whole file. from and to are env file names in this project's root (.env.local), paths " +
390        "to an env file at the root of another of this repo's git worktrees (../app-feature/.env.local), " +
391        'e.g. to set up a new worktree, or an env file on another machine over ssh, named as scp names it ' +
392        '(box:~/app/.env, deploy@box:/srv/app/.env.production). A path to any other folder, or another ' +
393        'machine, asks the user once to allow it. One side must be local. A whole-file copy into a file that does not exist yet copies it ' +
394        "as-is, comments included; into an existing file, keys the target already has with a different " +
395        'value are kept unless overwrite is true.',
396      inputSchema: {
397        type: 'object',
398        properties: {
399          key: { type: 'string', description: 'One key to copy. Omit to copy every key.' },
400          from: { type: 'string', description: 'An env file name, a path to one (~/ for the home folder), or host:path over ssh' },
401          to: { type: 'string', description: 'An env file name, a path to one (~/ for the home folder), or host:path over ssh' },
402          as: { type: 'string', description: 'Key name in the target file, with key. Default: same key.' },
403          overwrite: { type: 'boolean', description: 'Whole-file copy only: replace keys the target sets differently' },
404        },
405        required: ['from', 'to'],
406      },
407    })
408    await $.tool.register({
409      name: 'remove',
410      description:
411        'Removes a key from an env file by commenting it out, so the user can restore it. Ask the user before removing keys.',
412      inputSchema: {
413        type: 'object',
414        properties: { key: { type: 'string' }, file: { type: 'string', description: WHERE.trim() } },
415        required: ['key', 'file'],
416      },
417    })
418
419    await $.tool.register({
420      name: 'push',
421      description:
422        "Sends env values to a hosting service by running that service's own CLI, with {{KEY}} in argv " +
423        'or stdin replaced by the value from the env file. You never see the value, and the user ' +
424        'approves the command (shown with placeholders) before it runs. Prefer stdin, since arguments ' +
425        `show in the process list. Only these CLIs run: ${push.CLIS.join(', ')}. Examples: ` +
426        '{argv: ["vercel", "env", "add", "STRIPE_KEY", "production"], stdin: "{{STRIPE_KEY}}"}; ' +
427        '{argv: ["gh", "secret", "set", "STRIPE_KEY"], stdin: "{{STRIPE_KEY}}"}; ' +
428        '{argv: ["wrangler", "secret", "put", "STRIPE_KEY"], stdin: "{{STRIPE_KEY}}"}; ' +
429        '{argv: ["fly", "secrets", "import"], stdin: "STRIPE_KEY={{STRIPE_KEY}}"}. ' +
430        'Run one command per call. Commands that need no env value belong in Bash.',
431      inputSchema: {
432        type: 'object',
433        properties: {
434          argv: {
435            type: 'array',
436            items: { type: 'string' },
437            description: 'The command and its arguments, the CLI first. No shell: no pipes, quoting or $VARS.',
438          },
439          stdin: { type: 'string', description: 'Text written to the command\'s stdin, e.g. "{{STRIPE_KEY}}"' },
440          file: { type: 'string', description: 'The env file the values come from. Default .env.local, else .env.' + WHERE },
441        },
442        required: ['argv'],
443      },
444    })
445
446    await $.tool.register({
447      name: 'pull',
448      description:
449        "Fetches env values from a hosting or secrets service by running that service's own CLI, and " +
450        'writes them into an env file. You never see the values; you get back which keys were set. ' +
451        'Three shapes: the CLI prints KEY=value lines; the CLI writes a dotenv file, where ' +
452        `${pull.OUT} in argv stands for a temp file env reads back; or the CLI prints one value, named by key. ` +
453        'A key the file already has with a different value is kept unless overwrite is true, and then ' +
454        `the user is asked first. Only these CLIs run: ${push.CLIS.join(', ')}. Examples: ` +
455        `{argv: ["vercel", "env", "pull", "${pull.OUT}", "--environment=development", "--yes"]}; ` +
456        '{argv: ["doppler", "secrets", "download", "--no-file", "--format", "env"]}; ' +
457        '{argv: ["heroku", "config", "--shell", "-a", "my-app"]}; ' +
458        '{argv: ["op", "read", "op://Dev/Stripe/secret key"], key: "STRIPE_SECRET_KEY"}. ' +
459        'GitHub, Cloudflare and Fly secrets are write-only and cannot be pulled.',
460      inputSchema: {
461        type: 'object',
462        properties: {
463          argv: {
464            type: 'array',
465            items: { type: 'string' },
466            description: 'The command and its arguments, the CLI first. No shell: no pipes, quoting or $VARS.',
467          },
468          key: { type: 'string', description: 'When the CLI prints a single value: the key to store it under' },
469          keys: { type: 'array', items: { type: 'string' }, description: 'Only take these keys from KEY=value output' },
470          file: { type: 'string', description: 'The env file to write. Default .env.local, else .env.' + WHERE },
471          overwrite: { type: 'boolean', description: 'Replace keys the file already has with other values (the user is asked)' },
472        },
473        required: ['argv'],
474      },
475    })
476
477    // Notice edits made outside the pane (another editor, a script)
478    $.clock.every(2000, () => {
479      void $.fs.list().then(listing => {
480        const now = listing
481          .filter(entry => env.isEnvFile(entry.name))
482          .map(entry => `${entry.name}:${entry.mtimeMs}:${entry.size}`)
483          .join('|')
484        if (now !== signature) return refresh($)
485      })
486      // A waiting pane is placed once the terminal widens to its floor
487      void $.ui.panes().then(async panes => {
488        const pane = panes.find(p => p.id === PANE)
489        const waiting = pane !== undefined && !pane.isPlaced
490        if (waiting !== (await read($, isWaiting))) await update($, isWaiting, () => waiting)
491      })
492    })
493
494    return next(e)
495  })
496
497  on('command.run', { command: 'env' }, async $ => {
498    await refresh($)
499    const opened = await $.ui.open({ id: PANE, title: 'env', focus: true })
500    await update($, isWaiting, () => !opened.isPlaced)
501    return { text: 'Opened the env pane.' }
502  })
503
504  on('ui.close', async ($, e, next) => {
505    if (e.id === PANE) {
506      await update($, isWaiting, () => false)
507      if (e.origin.kind === 'person') await abandon($, 'closed the pane without setting')
508    }
509    return next(e)
510  })
511
512  // The fence: keep the built-in tools away from the raw files
513  on('tool.call', ($, e, next) => {
514    const tool = String(e.tool)
515    if (tool.startsWith(TOOL)) return next(e)
516    const input = e as unknown as Record<string, unknown>
517
518    if (['Read', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit'].includes(tool) && isProtectedPath(input.file_path)) {
519      return { deny: DENY }
520    }
521    if (tool === 'Grep') {
522      const reason = grepReason(input)
523      if (reason) return { deny: `${DENY} (Blocked because ${reason}.)` }
524    }
525    if (tool === 'Bash' && typeof input.command === 'string') {
526      const reason = bashReason(input.command)
527      if (reason) return { deny: `${DENY} (Blocked because ${reason}.)` }
528    }
529    return next(e)
530  })
531
532  // The backstop: any known value that reaches the conversation by any route
533  // is replaced with [env:KEY] before the row is stored or sent
534  on('session.append', ($, e, next) => {
535    if (index.length === 0) return next(e)
536    const content = e.message.content.map(scrubBlock)
537    const isChanged = content.some((block, i) => block !== e.message.content[i])
538    return isChanged ? next({ ...e, message: { ...e.message, content } }) : next(e)
539  })
540
541  on('session.send', ($, e, next) =>
542    index.length === 0 ? next(e) : next({ ...e, text: env.scrub(e.text, index) }),
543  )
544
545  on('tool.call', { tool: 'mcp__env__list' }, async ($, e) => {
546    const input = e as unknown as Record<string, unknown>
547    await refresh($)
548    const names = await read($, files)
549    const wanted = input.file === undefined ? names : names.filter(name => name === input.file)
550    if (wanted.length === 0) {
551      return { result: names.length === 0 ? 'No .env files in the project root.' : `No such file. Files: ${names.join(', ')}` }
552    }
553
554    const template = names.find(env.isTemplate)
555    const templateKeys = template ? env.entries(await load($, template)).map(entry => entry.key) : []
556    const out: string[] = []
557    for (const name of wanted) {
558      const list = env.entries(await load($, name))
559      out.push(`${name} (${list.length} keys${env.isTemplate(name) ? ', template' : ''})`)
560      for (const entry of list) {
561        const v = entry.value
562        const look = v === '' ? 'empty' : `${env.kind(v)}, ${v.length} chars, looks like ${env.shape(v)}`
563        out.push(`  ${entry.key}: ${look}`)
564      }
565      if (!env.isTemplate(name) && templateKeys.length > 0) {
566        const have = new Set(list.map(entry => entry.key))
567        const missing = templateKeys.filter(key => !have.has(key))
568        if (missing.length > 0) out.push(`  missing compared with ${template}: ${missing.join(', ')}`)
569      }
570    }
571    out.push('Values are hidden by design. Use mcp__env__request to have the user set one.')
572    return { result: out.join('\n') }
573  })
574
575  on('tool.call', { tool: 'mcp__env__request' }, async ($, e) => {
576    const input = e as unknown as Record<string, unknown>
577    const key = String(input.key ?? '')
578    if (!KEY_NAME.test(key)) return { result: `"${key}" is not a valid env key name.` }
579    const target = await fileOf($, input.file)
580    if ('error' in target) return { result: target.error }
581    const file = target.path
582    const text = (value: unknown, max: number) => (typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : undefined)
583    const steps = Array.isArray(input.steps) ? input.steps.map(step => String(step).slice(0, 160)).slice(0, 6) : []
584    const url = text(input.url, 300)
585
586    await update($, request, () => ({
587      key,
588      file,
589      reason: text(input.reason, 200) ?? '',
590      steps,
591      url: url && /^https?:\/\//.test(url) ? url : undefined,
592      format: text(input.format, 80),
593      pattern: text(input.pattern, 200),
594    }))
595    await update($, fit, () => null)
596    await update($, active, () => file)
597    await update($, editing, () => null)
598    // Opened by Claude, not the person, so a narrow terminal leaves the pane
599    // waiting undrawn; the card then shows in the band above the prompt
600    const opened = await $.ui.open({ id: PANE, title: 'env', focus: true })
601    await update($, isWaiting, () => !opened.isPlaced)
602    const wait = 'Stop here and wait; you will get a message once it is saved, skipped or the pane is closed.'
603    if (!opened.isPlaced) {
604      $.ui.toast(`Claude needs ${key}: paste it above the prompt`)
605      return {
606        result:
607          `The terminal is too narrow for the /env pane to open on its own, so the request for ${key} (${target.label}) ` +
608          `shows as a card above the prompt instead. Tell the user in one line to paste it there, or type /env ` +
609          `to open the full pane. ${wait}`,
610      }
611    }
612    $.ui.toast(`Claude needs ${key}`)
613    return { result: `Asked the user to set ${key} in ${target.label} in the /env pane. ${wait}` }
614  })
615
616  on('tool.call', { tool: 'mcp__env__generate' }, async ($, e) => {
617    const input = e as unknown as Record<string, unknown>
618    const key = String(input.key ?? '')
619    if (!KEY_NAME.test(key)) return { result: `"${key}" is not a valid env key name.` }
620    const target = await fileOf($, input.file)
621    if ('error' in target) return { result: target.error }
622    const file = target.path
623    const bytes = Math.min(128, Math.max(16, Number(input.bytes ?? 32) || 32))
624    const format = input.format === 'hex' ? 'hex' : 'base64url'
625    const lines = await load($, file)
626    if (env.get(lines, key) && input.overwrite !== true) {
627      return { result: `${key} already has a value in ${file}. Pass overwrite: true to replace it (confirm with the user first).` }
628    }
629    await save($, file, env.set(lines, key, env.randomSecret(bytes, format)))
630    $.ui.toast(`Claude generated ${key} in ${file}`)
631    return { result: `Set ${key} in ${file} to ${bytes} random bytes (${format}). The value is not shown.` }
632  })
633
634  on('tool.call', { tool: 'mcp__env__copy' }, async ($, e) => {
635    const input = e as unknown as Record<string, unknown>
636    if (remote.parse(input.from) && remote.parse(input.to)) {
637      return { result: 'from and to are both on other machines. Copy through a local env file instead, so the scrubber knows the values.' }
638    }
639    const to = await spot($, input.to)
640    if ('error' in to) return { result: to.error }
641    if (env.isTemplate(basename(to.path))) {
642      return { result: `${to.label} is a template, usually committed, so env won't copy values into it.` }
643    }
644    const from = await spot($, input.from)
645    if ('error' in from) return { result: from.error }
646    if (from.path === to.path && from.host === to.host) return { result: 'from and to are the same file.' }
647
648    const source = await readSpot($, from)
649    if ('error' in source) return { result: source.error }
650    const target = await readSpot($, to)
651    if ('error' in target) return { result: target.error }
652
653    if (input.key !== undefined) {
654      const key = String(input.key)
655      const as = String(input.as ?? key)
656      if (!KEY_NAME.test(as)) return { result: `"${as}" is not a valid env key name.` }
657      const value = env.get(source.lines, key)
658      if (value === undefined) return { result: `${key} is not set in ${from.label}.` }
659      const failed = await writeSpot($, to, env.set(target.lines, as, value))
660      if (failed) return { result: failed }
661      return { result: `Copied ${key} from ${from.label} to ${to.label}${as === key ? '' : ` as ${as}`}.` }
662    }
663
664    const keys = env.entries(source.lines).map(entry => entry.key)
665    if (keys.length === 0) return { result: `${from.label} has no keys to copy.` }
666    if (!target.exists) {
667      const failed = await writeSpot($, to, source.lines)
668      if (failed) return { result: failed }
669      $.ui.toast(`Copied ${from.label} to ${to.label}`)
670      return { result: `Copied ${from.label} to ${to.label} as-is: ${keys.join(', ')}. Values not shown.` }
671    }
672    const values = Object.fromEntries(env.entries(source.lines).map(entry => [entry.key, entry.value]))
673    const merged = pull.merge(target.lines, values, input.overwrite === true)
674    if (merged.added.length + merged.changed.length > 0) {
675      const failed = await writeSpot($, to, merged.lines)
676      if (failed) return { result: failed }
677    }
678    const report = [`Copied ${from.label} into ${to.label}, values not shown:`]
679    if (merged.added.length > 0) report.push(`  set: ${merged.added.join(', ')}`)
680    if (merged.changed.length > 0) report.push(`  replaced: ${merged.changed.join(', ')}`)
681    if (merged.same.length > 0) report.push(`  already matching: ${merged.same.join(', ')}`)
682    if (merged.kept.length > 0) {
683      report.push(`  kept the target's own value: ${merged.kept.join(', ')} (overwrite: true replaces them; ask the user first)`)
684    }
685    return { result: report.join('\n') }
686  })
687
688  on('tool.call', { tool: 'mcp__env__remove' }, async ($, e) => {
689    const input = e as unknown as Record<string, unknown>
690    const key = String(input.key ?? '')
691    const target = await place($, input.file)
692    if ('error' in target) return { result: target.error }
693    const file = target.path
694    const lines = await load($, file)
695    if (env.get(lines, key) === undefined) return { result: `${key} is not in ${file}.` }
696    await save($, file, env.commentOut(lines, key, `removed by Claude; uncomment to restore`))
697    return { result: `Commented out ${key} in ${file}.` }
698  })
699
700  on('tool.call', { tool: 'mcp__env__push' }, async ($, e) => {
701    const input = e as unknown as Record<string, unknown>
702    const plan = push.check(input.argv, input.stdin)
703    if ('error' in plan) return { result: plan.error }
704    const target = await fileOf($, input.file)
705    if ('error' in target) return { result: target.error }
706    const file = target.path
707    const cli = plan.argv[0] ?? ''
708
709    const lines = await load($, file)
710    const values: Record<string, string> = {}
711    for (const key of plan.keys) {
712      const value = env.get(lines, key)
713      if (value) values[key] = value
714    }
715    const missing = plan.keys.filter(key => values[key] === undefined)
716    if (missing.length > 0) {
717      return { result: `${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} not set in ${file}. Use mcp__env__request to have the user set ${missing.length === 1 ? 'it' : 'them'} first.` }
718    }
719
720    const command = push.shown(plan)
721    const yes = 'Run it'
722    const answer = await $.ui
723      .ask(`Run \`${command}\` with ${plan.keys.join(', ')} filled in from ${file}?`, {
724        header: 'env',
725        options: [yes, "Don't run it"],
726      })
727      .catch(() => null)
728    if (answer !== yes) {
729      const said = answer && answer !== "Don't run it" ? ` They said: ${env.scrub(answer, index)}` : ''
730      return { result: `The user did not approve \`${command}\`, so nothing ran.${said}` }
731    }
732
733    const ran = await $.process
734      .run(
735        plan.argv.map(arg => push.fill(arg, values)),
736        { stdin: plan.stdin === undefined ? undefined : push.fill(plan.stdin, values), timeoutMs: 120_000 },
737      )
738      .catch((error: unknown) => ({ error: push.redact(String(error), values) }))
739    if ('error' in ran) {
740      return { result: `\`${command}\` could not run: ${ran.error}. Is ${cli} installed and on PATH?` }
741    }
742
743    const clean = (text: string) => push.tail(push.redact(env.scrub(text, index), values))
744    const out = [`\`${command}\` exited ${ran.exitCode}.`]
745    if (ran.stdout.trim()) out.push(`stdout:\n${clean(ran.stdout)}`)
746    if (ran.stderr.trim()) out.push(`stderr:\n${clean(ran.stderr)}`)
747    if (ran.exitCode !== 0) {
748      out.push(`If ${cli} isn't logged in or linked, ask the user to run \`! ${cli} login\` (or link the project) and try again.`)
749    } else {
750      $.ui.toast(`Sent ${plan.keys.join(', ')} with ${cli}`)
751    }
752    return { result: out.join('\n') }
753  })
754
755  on('tool.call', { tool: 'mcp__env__pull' }, async ($, e) => {
756    const input = e as unknown as Record<string, unknown>
757    const plan = pull.check(input.argv, input.key, input.keys)
758    if ('error' in plan) return { result: plan.error }
759    const target = await fileOf($, input.file)
760    if ('error' in target) return { result: target.error }
761    const file = target.path
762    const cli = plan.argv[0] ?? ''
763    const command = push.shown({ argv: plan.argv, keys: [] })
764    const login = `If ${cli} isn't logged in or linked, ask the user to run \`! ${cli} login\` (or link the project) and try again.`
765
766    // A CLI that writes a file gets a fresh temp folder, removed afterwards
767    let dir: string | undefined
768    if (plan.usesFile) {
769      const made = await $.process.run(['mktemp', '-d']).catch(() => null)
770      dir = made?.exitCode === 0 ? made.stdout.trim() : undefined
771      if (!dir) return { result: 'Could not make a temp folder for the pulled file, so nothing ran.' }
772    }
773    const out = `${dir}/pulled.env`
774
775    try {
776      const ran = await $.process
777        .run(
778          plan.argv.map(arg => (arg === pull.OUT ? out : arg)),
779          { timeoutMs: 120_000 },
780        )
781        .catch((error: unknown) => ({ error: env.scrub(String(error), index) }))
782      if ('error' in ran) return { result: `\`${command}\` could not run: ${ran.error}. Is ${cli} installed and on PATH?` }
783
784      const text = dir ? String(await $.fs.read(out).catch(() => '')) : ran.stdout
785      const values = pull.incoming(plan, text)
786      const clean = (t: string) => push.tail(push.redact(env.scrub(t, index), values))
787      const stderr = ran.stderr.trim() ? `stderr:\n${clean(ran.stderr)}` : ''
788      if (ran.exitCode !== 0) {
789        return { result: [`\`${command}\` exited ${ran.exitCode}, so nothing was written.`, stderr, login].filter(Boolean).join('\n') }
790      }
791      if (Object.keys(values).length === 0) {
792        const wanted = plan.key ? 'a value' : plan.keys ? `any of ${plan.keys.join(', ')}` : 'any KEY=value lines'
793        return { result: [`\`${command}\` gave ${wanted}, so nothing was written.`, stderr].filter(Boolean).join('\n') }
794      }
795
796      const lines = await load($, file)
797      let overwrite = input.overwrite === true
798      const clash = pull.conflicts(lines, values)
799      if (overwrite && clash.length > 0) {
800        const yes = 'Replace them'
801        const answer = await $.ui
802          .ask(`Replace ${clash.join(', ')} in ${file} with the values from \`${command}\`?`, {
803            header: 'env',
804            options: [yes, 'Keep mine'],
805          })
806          .catch(() => null)
807        overwrite = answer === yes
808      }
809      const merged = pull.merge(lines, values, overwrite)
810      if (merged.added.length + merged.changed.length > 0) {
811        await save($, file, merged.lines)
812        $.ui.toast(`Pulled ${merged.added.length + merged.changed.length} keys into ${file} with ${cli}`)
813      }
814
815      const report = [`Ran \`${command}\`, values not shown. In ${file}:`]
816      if (merged.added.length > 0) report.push(`  set: ${merged.added.join(', ')}`)
817      if (merged.changed.length > 0) report.push(`  replaced: ${merged.changed.join(', ')}`)
818      if (merged.same.length > 0) report.push(`  already matching: ${merged.same.join(', ')}`)
819      if (merged.kept.length > 0) {
820        report.push(
821          `  kept the file's own value: ${merged.kept.join(', ')}` +
822            (input.overwrite === true ? ' (the user chose to keep them)' : ' (pass overwrite: true to replace; the user will be asked)'),
823        )
824      }
825      return { result: report.join('\n') }
826    } finally {
827      if (dir) await $.process.run(['rm', '-rf', dir]).catch(() => undefined)
828    }
829  })
830
831  // While the pane waits for a wider terminal, Claude's request shows here
832  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
833    if (e.surface !== 'terminal' && e.surface !== 'desktop') return next(e)
834    if (e.props.hasSurvey || !(await read($, isWaiting))) return next(e)
835    const asked = await read($, request)
836    if (!asked) return next(e)
837    // isWaiting trails the surface by up to a poll; ask the surface itself
838    // so the card leaves the moment the pane is placed
839    const pane = (await $.ui.panes()).find(p => p.id === PANE)
840    if (!pane || pane.isPlaced) return next(e)
841    return requestCard($, $.ui.resolve(e), asked, 'band')
842  })
843
844  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
845    if (e.surface !== 'terminal' && e.surface !== 'desktop') {
846      const { Text } = $.ui.resolve(e)
847      return <Text>Open a terminal or the desktop app to edit env files.</Text>
848    }
849    const ui = $.ui.resolve(e)
850    const { Box, Text, Button, Input } = ui
851
852    await read($, rev)
853    const names = await read($, files)
854    const file = await read($, active)
855    const edit = await read($, editing)
856    const shown = await read($, revealed)
857    const asked = await read($, request)
858    const pending = await read($, confirm)
859    const note = await read($, flash)
860
861    const lines = file ? await load($, file) : []
862    const list = env.entries(lines)
863    const template = names.find(env.isTemplate)
864    const isTemplate = env.isTemplate(file)
865    const missing =
866      template && !isTemplate
867        ? env.entries(await load($, template)).map(entry => entry.key).filter(key => !list.some(entry => entry.key === key))
868        : []
869    const isUnignored = file !== '' && !isTemplate && !(await isIgnored($, file))
870    const keyWidth = Math.min(32, Math.max(8, ...list.map(entry => entry.key.length)) + 2)
871
872    const say = (text: string | null) => update($, flash, () => text)
873
874    const card = asked && (await requestCard($, ui, asked, 'pane'))
875
876    const valueEditor = (key: string) => (
877      <Box flexDirection="column" marginBottom={1}>
878        <Input
879          key="value"
880          label={`${key} = `}
881          placeholder="paste the value, Enter saves"
882          submitLabel="save"
883          autoFocus
884          onSubmit={value => void store($, file, key, value)}
885        />
886        <Box gap={1}>
887          <Button key="gen" label="generate random" onPress={() => void store($, file, key, env.randomSecret(32, 'base64url'))} />
888          <Button key="cancel" label="cancel" onPress={() => void update($, editing, () => null)} />
889        </Box>
890      </Box>
891    )
892
893    const row = (entry: env.Entry) => {
894      const k = entry.key
895      if (edit && edit.file === file && edit.key === k) return valueEditor(k)
896      const isShown = shown === `${file}:${k}`
897      return (
898        <Box key={`row:${k}`} gap={1}>
899          <Box width={keyWidth} flexShrink={0}>
900            <Text bold wrap="truncate">{k}</Text>
901          </Box>
902          <Box flexGrow={1}>
903            <Text dimColor={!isShown} wrap="truncate">{isShown ? entry.value || '(empty)' : env.shape(entry.value, true)}</Text>
904          </Box>
905          <Button
906            key={`copy:${k}`}
907            label="copy"
908            plain
909            onPress={async press => {
910              const { isCopied } = await $.ui.copy({ text: entry.value, surface: press.surface })
911              await say(isCopied ? `Copied ${k}` : `Could not copy ${k}`)
912            }}
913          />
914          <Button key={`edit:${k}`} label="edit" plain onPress={() => void update($, editing, () => ({ file, key: k }))} />
915          <Button
916            key={`show:${k}`}
917            label={isShown ? 'hide' : 'show'}
918            plain
919            onPress={() => void update($, revealed, now => (now === `${file}:${k}` ? null : `${file}:${k}`))}
920          />
921          {pending === `${file}:${k}` ? (
922            <Button
923              key={`really:${k}`}
924              label="really delete?"
925              variant="primary"
926              onPress={async () => {
927                await save($, file, env.remove(await load($, file), k))
928                await update($, confirm, () => null)
929                await say(`Deleted ${k} from ${file}`)
930              }}
931            />
932          ) : (
933            <Button key={`del:${k}`} label="del" plain dimColor onPress={() => void update($, confirm, () => `${file}:${k}`)} />
934          )}
935        </Box>
936      )
937    }
938
939    const isNewKey = edit !== null && edit.file === file && edit.key !== null && !list.some(entry => entry.key === edit.key)
940
941    return (
942      <Box flexDirection="column">
943        {card}
944
945        <Box gap={1} flexWrap="wrap" marginBottom={1}>
946          {names.map(name => (
947            <Button
948              key={`file:${name}`}
949              label={name}
950              variant={name === file ? 'primary' : undefined}
951              dimColor={name !== file}
952              onPress={() => void update($, active, () => name)}
953            />
954          ))}
955          {!names.includes('.env.local') && (
956            <Button key="create" label="+ .env.local" plain dimColor onPress={() => void save($, '.env.local', [])} />
957          )}
958        </Box>
959
960        {isUnignored && <Text color="red">{file} is not in .gitignore</Text>}
961        {note && <Text dimColor>{note}</Text>}
962        {names.length === 0 && <Text dimColor>No .env files in the project root yet.</Text>}
963
964        {list.map(row)}
965        {isNewKey && edit?.key && valueEditor(edit.key)}
966
967        {edit && edit.file === file && edit.key === null ? (
968          <Input
969            key="name"
970            label="New key: "
971            placeholder="NAME, Enter to continue"
972            autoFocus
973            onSubmit={name => {
974              const key = name.trim()
975              if (KEY_NAME.test(key)) void update($, editing, () => ({ file, key }))
976              else void say(`"${key}" is not a valid key name`)
977            }}
978          />
979        ) : (
980          file !== '' && <Button key="add" label="+ add key" plain onPress={() => void update($, editing, () => ({ file, key: null }))} />
981        )}
982
983        {missing.length > 0 && (
984          <Box flexDirection="column" marginTop={1}>
985            <Text dimColor>Missing compared with {template}:</Text>
986            <Box gap={1} flexWrap="wrap">
987              {missing.map(key => (
988                <Button key={`fill:${key}`} label={key} plain dimColor onPress={() => void update($, editing, () => ({ file, key }))} />
989              ))}
990            </Box>
991          </Box>
992        )}
993      </Box>
994    )
995  })
996}
997
hooks/dotenv.ts 189 lines
1// A .env parser that keeps the file as written: comments, blank lines, order
2// and quoting survive a round trip, and only the entries we change are redrawn.
3
4export type Raw = { kind: 'raw'; raw: string }
5export type Entry = { kind: 'entry'; key: string; value: string; prefix: string; raw: string }
6export type Line = Raw | Entry
7
8const ASSIGN = /^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s?(.*)$/
9const BARE = /^[A-Za-z0-9_\-.,:/@+=%~]*$/
10
11export function parse(text: string): Line[] {
12  const rows = text.split(/\r?\n/)
13  const lines: Line[] = []
14
15  for (let i = 0; i < rows.length; i++) {
16    const row = rows[i] ?? ''
17    const match = ASSIGN.exec(row)
18    if (!match) {
19      lines.push({ kind: 'raw', raw: row })
20      continue
21    }
22
23    const [, exported = '', key = '', rest = ''] = match
24    const quote = rest.trimStart()[0]
25    let value: string
26    let raw = row
27
28    if (quote === '"' || quote === "'" || quote === '`') {
29      // A quoted value may run over several lines until its closing quote
30      let body = rest.trimStart().slice(1)
31      let end = closing(body, quote)
32      let j = i
33      while (end < 0 && j + 1 < rows.length) {
34        j += 1
35        body += '\n' + (rows[j] ?? '')
36        end = closing(body, quote)
37      }
38      if (end < 0) {
39        // Never closed: keep the line as it stands rather than swallow the file
40        lines.push({ kind: 'raw', raw: row })
41        continue
42      }
43      raw = rows.slice(i, j + 1).join('\n')
44      i = j
45      value = body.slice(0, end)
46      if (quote === '"') {
47        value = value.replace(/\\([nr"\\])/g, (_, c: string) => (c === 'n' ? '\n' : c === 'r' ? '\r' : c))
48      }
49    } else {
50      value = rest.replace(/\s+#.*$/, '').trim()
51    }
52
53    lines.push({ kind: 'entry', key, value, prefix: exported, raw })
54  }
55
56  return lines
57}
58
59function closing(body: string, quote: string): number {
60  for (let k = 0; k < body.length; k++) {
61    if (quote === '"' && body[k] === '\\') {
62      k += 1
63    } else if (body[k] === quote) {
64      return k
65    }
66  }
67  return -1
68}
69
70export function quote(value: string): string {
71  if (BARE.test(value)) return value
72  if (!value.includes("'") && !value.includes('\n')) return `'${value}'`
73  return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`
74}
75
76export function serialize(lines: Line[]): string {
77  return lines.map(line => line.raw).join('\n')
78}
79
80export function entries(lines: Line[]): Entry[] {
81  // dotenv takes the last of a repeated key, so the list does too
82  const byKey = new Map<string, Entry>()
83  for (const line of lines) {
84    if (line.kind === 'entry') {
85      byKey.delete(line.key)
86      byKey.set(line.key, line)
87    }
88  }
89  return [...byKey.values()]
90}
91
92export function get(lines: Line[], key: string): string | undefined {
93  return entries(lines).find(entry => entry.key === key)?.value
94}
95
96export function set(lines: Line[], key: string, value: string): Line[] {
97  const at = lines.findLastIndex(line => line.kind === 'entry' && line.key === key)
98  if (at >= 0) {
99    const old = lines[at] as Entry
100    const next: Entry = { ...old, value, raw: `${old.prefix}${key}=${quote(value)}` }
101    return lines.map((line, i) => (i === at ? next : line))
102  }
103
104  const added: Entry = { kind: 'entry', key, value, prefix: '', raw: `${key}=${quote(value)}` }
105  const last = lines[lines.length - 1]
106  // Keep the file's trailing newline after the new line
107  if (last?.kind === 'raw' && last.raw === '') {
108    return [...lines.slice(0, -1), added, last]
109  }
110  return [...lines, added, { kind: 'raw', raw: '' }]
111}
112
113export function remove(lines: Line[], key: string): Line[] {
114  return lines.filter(line => !(line.kind === 'entry' && line.key === key))
115}
116
117export function commentOut(lines: Line[], key: string, note: string): Line[] {
118  return lines.map(line =>
119    line.kind === 'entry' && line.key === key
120      ? { kind: 'raw', raw: `# ${note}\n` + line.raw.split('\n').map(row => `# ${row}`).join('\n') }
121      : line,
122  )
123}
124
125export function isEnvFile(name: string): boolean {
126  return /^\.env(\.[\w.-]+)?$/.test(name)
127}
128
129export function isTemplate(name: string): boolean {
130  return /^\.env\.(example|sample|template|defaults|dist)$/.test(name)
131}
132
133// What a value looks like, without saying what it is. `showTail` adds the
134// last four characters, for the person's screen only.
135export function shape(value: string, showTail = false): string {
136  if (value === '') return '(empty)'
137  const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(value)
138  const prefix =
139    scheme?.[0] ??
140    /^(sk|pk|rk|whsec|ghp|gho|ghs|github_pat|xox[abpr]|sk-ant|sk-proj|re|AKIA)[_-]((live|test)[_-])?/i.exec(value)?.[0] ??
141    (value.startsWith('eyJ') ? 'eyJ' : '')
142  const tail = showTail && value.length > 12 ? value.slice(-4) : ''
143  return `${prefix}${'•'.repeat(prefix || tail ? 4 : 8)}${tail}`
144}
145
146export function kind(value: string): string {
147  if (value === '') return 'empty'
148  if (/^(true|false)$/i.test(value)) return 'boolean'
149  if (/^-?\d+(\.\d+)?$/.test(value)) return 'number'
150  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return `url (${value.split(':')[0]})`
151  if (/^eyJ[\w-]+\.[\w-]+\.[\w-]*$/.test(value)) return 'jwt'
152  if (/^[0-9a-f]+$/i.test(value)) return 'hex'
153  return 'string'
154}
155
156export function isSecretish(value: string): boolean {
157  return value.length >= 8 && !/^(true|false|-?\d+(\.\d+)?)$/i.test(value)
158}
159
160// Longest first, so a value inside another is never cut out of it
161export type Index = ReadonlyArray<readonly [value: string, key: string]>
162
163export function buildIndex(files: Record<string, Line[]>): Index {
164  const seen = new Map<string, string>()
165  for (const [file, lines] of Object.entries(files)) {
166    if (isTemplate(file)) continue
167    for (const entry of entries(lines)) {
168      if (isSecretish(entry.value)) seen.set(entry.value, entry.key)
169    }
170  }
171  return [...seen].sort((a, b) => b[0].length - a[0].length)
172}
173
174export function scrub(text: string, index: Index): string {
175  let out = text
176  for (const [value, key] of index) {
177    if (out.includes(value)) out = out.split(value).join(`[env:${key}]`)
178  }
179  return out
180}
181
182export function randomSecret(bytes: number, format: 'base64url' | 'hex'): string {
183  const buf = crypto.getRandomValues(new Uint8Array(bytes))
184  if (format === 'hex') return [...buf].map(b => b.toString(16).padStart(2, '0')).join('')
185  let bin = ''
186  for (const b of buf) bin += String.fromCharCode(b)
187  return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
188}
189
hooks/guard.ts 57 lines
1import { isEnvFile, isTemplate } from './dotenv'
2
3// Best effort: the scrubber in register.tsx is what actually keeps values out
4// of the conversation. This only stops the obvious ways of reading them.
5
6const ENV_TOKEN = /(?:^|[\s'"=/<>|;&(])(\.env(?:\.[\w.-]+)?)(?=$|[\s'";|&)<>])/g
7const HARMLESS = /^\s*(ls|stat|test|\[|git\s+(status|check-ignore|ls-files))\b/
8const DUMPS_ENV = /(?:^|[;&|(]\s*|\$\(\s*)(printenv\b|env\s*(?:$|[|;&>)])|export\s+-p\b|set\s*(?:$|[|;&>]))/
9// A shell or interpreter runs its quoted arguments as code, so those stay checked
10const RUNS_CODE = /(?:^|[\s;&|(])(?:sh|bash|zsh|fish|dash|eval|node|deno|bun|python[\d.]*|ruby|perl|php|osascript)\b/
11const QUOTED = /"(?:[^"\\]|\\.)*"|'[^']*'/g
12
13export function basename(path: string): string {
14  return path.split(/[\\/]/).pop() ?? path
15}
16
17export function isProtectedPath(path: unknown): boolean {
18  if (typeof path !== 'string') return false
19  const name = basename(path)
20  return isEnvFile(name) && !isTemplate(name)
21}
22
23// Text that only mentions a file name: heredoc bodies, commit messages, lines
24// appended to .gitignore, and quoted sentences (a PR body, a prompt handed to
25// another agent). Without this, writing a README that says ".env" or running
26// `echo .env >> .gitignore` would be refused. A quoted argument counts as a
27// sentence when it has a space and no command substitution in it.
28function withoutProse(command: string): string {
29  const code = command
30    .replace(/<<-?\s*(['"]?)(\w+)\1[^\n]*\n[\s\S]*?\n\s*\2[ \t]*(?=\n|$)/g, '<<heredoc')
31    .replace(/(\bgit\s+commit\b[^;&|\n]*?\s-m\s*)("(?:[^"\\]|\\.)*"|'[^']*')/g, '$1msg')
32    .replace(/\b(echo|printf)\b[^;&|\n]*>>?\s*\S*\.gitignore\b/g, 'gitignore-edit')
33  if (RUNS_CODE.test(code)) return code
34  return code.replace(QUOTED, quoted => (/\s/.test(quoted) && !/\$\(|`/.test(quoted) ? '"prose"' : quoted))
35}
36
37export function bashReason(command: string): string | undefined {
38  const code = withoutProse(command)
39  if (DUMPS_ENV.test(code)) return 'it prints the environment'
40  // Each command in a chain on its own, so `cd app && git check-ignore .env`
41  // passes while `ls && cat .env` doesn't
42  for (const segment of code.split(/&&|\|\||[;|\n]/)) {
43    if (HARMLESS.test(segment)) continue
44    for (const match of segment.matchAll(ENV_TOKEN)) {
45      const name = match[1] ?? ''
46      if (!isTemplate(name)) return `it touches ${name}`
47    }
48  }
49  return undefined
50}
51
52export function grepReason(input: Record<string, unknown>): string | undefined {
53  if (isProtectedPath(input.path)) return `it searches ${input.path}`
54  if (typeof input.glob === 'string' && /(^|[/{,])\.env/.test(input.glob)) return 'its glob includes .env files'
55  return undefined
56}
57
hooks/pull.ts 77 lines
1// mcp__env__pull runs a hosting or secrets CLI (vercel, doppler, op...) and
2// writes what it prints into an env file, so values come down from the
3// service without passing through the conversation. The reverse of push.
4
5import * as env from './dotenv'
6import { CLIS, keysIn } from './push'
7
8// Stands for a fresh temp file, for CLIs that write a file rather than print
9// (`vercel env pull {{@file}}`). The @ keeps it from naming a real key.
10export const OUT = '{{@file}}'
11
12export type Plan = { argv: string[]; key?: string; keys?: string[]; usesFile: boolean }
13
14const KEY_NAME = /^[A-Za-z_][A-Za-z0-9_.-]*$/
15
16export function check(argv: unknown, key: unknown, keys: unknown): Plan | { error: string } {
17  if (!Array.isArray(argv) || argv.length === 0 || argv.length > 64 || !argv.every(arg => typeof arg === 'string')) {
18    return { error: 'argv must be a non-empty list of strings, the CLI first.' }
19  }
20  const cli = argv[0] as string
21  if (!CLIS.includes(cli)) {
22    return { error: `env only runs hosting CLIs, by bare name: ${CLIS.join(', ')}. "${cli}" is not one of them.` }
23  }
24  if (keysIn(argv.slice(1)).length > 0) {
25    return { error: 'pull does not fill in {{KEY}} placeholders; only push sends values out.' }
26  }
27  if (key !== undefined && (typeof key !== 'string' || !KEY_NAME.test(key))) return { error: `"${key}" is not a valid env key name.` }
28  if (keys !== undefined && (!Array.isArray(keys) || !keys.every(k => typeof k === 'string' && KEY_NAME.test(k)))) {
29    return { error: 'keys must be a list of env key names.' }
30  }
31  const usesFile = argv.includes(OUT)
32  if (usesFile && key !== undefined) return { error: `Use either ${OUT} (a file of KEY=value lines) or key (one printed value), not both.` }
33  return { argv: argv as string[], key, keys: keys as string[] | undefined, usesFile }
34}
35
36// What the CLI gave: one value it printed, or the KEY=value lines it printed
37// or wrote. `op read` and friends end the value with a newline; drop just that.
38export function incoming(plan: Plan, text: string): Record<string, string> {
39  if (plan.key) {
40    const value = text.replace(/\r?\n$/, '')
41    return value === '' ? {} : { [plan.key]: value }
42  }
43  const values: Record<string, string> = {}
44  for (const entry of env.entries(env.parse(text))) {
45    if (!plan.keys || plan.keys.includes(entry.key)) values[entry.key] = entry.value
46  }
47  return values
48}
49
50export type Merge = { lines: env.Line[]; added: string[]; changed: string[]; same: string[]; kept: string[] }
51
52// A key the file already has with another value is kept unless overwrite is
53// set: the local value may be the one the user means to use
54export function merge(lines: env.Line[], values: Record<string, string>, overwrite: boolean): Merge {
55  const out: Merge = { lines, added: [], changed: [], same: [], kept: [] }
56  for (const [key, value] of Object.entries(values)) {
57    const now = env.get(out.lines, key)
58    if (now === value) out.same.push(key)
59    else if (now !== undefined && now !== '' && !overwrite) out.kept.push(key)
60    else {
61      ;(now === undefined || now === '' ? out.added : out.changed).push(key)
62      out.lines = env.set(out.lines, key, value)
63    }
64  }
65  return out
66}
67
68// Keys the file would lose its own value for, so the user is asked first
69export function conflicts(lines: env.Line[], values: Record<string, string>): string[] {
70  return Object.entries(values)
71    .filter(([key, value]) => {
72      const now = env.get(lines, key)
73      return now !== undefined && now !== '' && now !== value
74    })
75    .map(([key]) => key)
76}
77
hooks/push.ts 79 lines
1// mcp__env__push runs a hosting provider's own CLI (vercel, gh, wrangler...)
2// with values from an env file filled in for {{KEY}} placeholders, so a
3// secret reaches the service without passing through the conversation.
4// The CLIs already hold the user's login; env only fills in the blanks.
5
6// Only these run, so a filled-in value can't be handed to curl or a script.
7// Bare names, looked up on PATH like any shell would.
8export const CLIS = [
9  'aws',
10  'az',
11  'doppler',
12  'firebase',
13  'fly',
14  'flyctl',
15  'gcloud',
16  'gh',
17  'heroku',
18  'netlify',
19  'op',
20  'railway',
21  'render',
22  'supabase',
23  'vercel',
24  'wrangler',
25]
26
27const PLACEHOLDER = /\{\{([A-Za-z_][A-Za-z0-9_.-]*)\}\}/g
28
29export type Plan = { argv: string[]; stdin?: string; keys: string[] }
30
31export function keysIn(texts: string[]): string[] {
32  const keys = new Set<string>()
33  for (const text of texts) for (const match of text.matchAll(PLACEHOLDER)) keys.add(match[1] ?? '')
34  return [...keys]
35}
36
37export function check(argv: unknown, stdin: unknown): Plan | { error: string } {
38  if (!Array.isArray(argv) || argv.length === 0 || argv.length > 64 || !argv.every(arg => typeof arg === 'string')) {
39    return { error: 'argv must be a non-empty list of strings, the CLI first.' }
40  }
41  if (stdin !== undefined && typeof stdin !== 'string') return { error: 'stdin must be a string.' }
42  const cli = argv[0] as string
43  if (!CLIS.includes(cli)) {
44    return { error: `env only runs hosting CLIs, by bare name: ${CLIS.join(', ')}. "${cli}" is not one of them.` }
45  }
46  const keys = keysIn([...argv.slice(1), stdin ?? ''])
47  if (keys.length === 0) {
48    return { error: 'Nothing in argv or stdin names a {{KEY}}, so no env value is needed. Run the command with Bash instead.' }
49  }
50  return { argv: argv as string[], stdin, keys }
51}
52
53export function fill(text: string, values: Record<string, string>): string {
54  return text.replace(PLACEHOLDER, (whole, key: string) => values[key] ?? whole)
55}
56
57// Belt and braces over the scrubber, which skips values under 8 characters:
58// whatever was filled in comes back out of the CLI's output by name
59export function redact(text: string, values: Record<string, string>): string {
60  const known = Object.entries(values)
61    .filter(([, value]) => value.length >= 3)
62    .sort(([, a], [, b]) => b.length - a.length)
63  return known.reduce((out, [key, value]) => out.split(value).join(`[env:${key}]`), text)
64}
65
66// The command as the user is asked to approve it: placeholders, never values
67export function shown(plan: Plan): string {
68  const words = plan.argv.map(arg => (/^[\w@%+=:,./{}-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`))
69  if (plan.stdin === undefined) return words.join(' ')
70  // Spelled out rather than `< ...`, which reads as a file redirect
71  const stdin = /^[^\s"'\\]+$/.test(plan.stdin) ? plan.stdin : JSON.stringify(plan.stdin)
72  return `${words.join(' ')} (stdin: ${stdin})`
73}
74
75export function tail(text: string, max = 1500): string {
76  const trimmed = text.trim()
77  return trimmed.length <= max ? trimmed : `…${trimmed.slice(-max)}`
78}
79
hooks/remote.ts 48 lines
1// Env files on another machine, named the way scp names them (box:~/app/.env).
2// env only ever runs two fixed commands there over ssh: one prints the file,
3// one replaces it with what env sends on stdin. The path is quoted, so it
4// can't smuggle in a command of its own.
5
6import { isEnvFile } from './dotenv'
7
8export type Remote = { host: string; path: string }
9
10// [user@]host, never starting with `-`, so ssh can't read it as an option
11const HOST = /^(?:[A-Za-z0-9_][A-Za-z0-9._-]*@)?[A-Za-z0-9][A-Za-z0-9._-]*$/
12
13// Exit status of the read command when the file isn't there
14export const MISSING = 3
15
16// undefined when the value isn't host:path at all, so it's a local file
17export function parse(value: unknown): Remote | { error: string } | undefined {
18  if (typeof value !== 'string') return undefined
19  const raw = value.trim()
20  const colon = raw.indexOf(':')
21  if (colon <= 0) return undefined
22  const host = raw.slice(0, colon)
23  const path = raw.slice(colon + 1)
24  if (host.includes('/') || !HOST.test(host)) return undefined
25  if (/[\n\r\0]/.test(path) || !isEnvFile(path.slice(path.lastIndexOf('/') + 1))) {
26    return { error: `"${path}" on ${host} is not an env file.` }
27  }
28  return { host, path }
29}
30
31// Single quotes, keeping a leading ~/ outside them so the remote shell expands it
32export function quote(path: string): string {
33  const home = path.startsWith('~/') ? '~/' : ''
34  return `${home}'${path.slice(home.length).replaceAll("'", `'\\''`)}'`
35}
36
37const ssh = (host: string, command: string) => ['ssh', '-o', 'BatchMode=yes', host, command]
38
39export function reader({ host, path }: Remote): string[] {
40  const file = quote(path)
41  return ssh(host, `if [ -e ${file} ]; then cat -- ${file}; else exit ${MISSING}; fi`)
42}
43
44// A file env creates is readable by its owner only
45export function writer({ host, path }: Remote): string[] {
46  return ssh(host, `umask 077 && cat > ${quote(path)}`)
47}
48
hooks/worktree.ts 48 lines
1// Env files in this repo's other git worktrees, so mcp__env__copy can seed a
2// new worktree's .env.local from the main checkout. Only the root of a
3// worktree `git worktree list` names counts: anywhere else, a copied value
4// could land where the fence doesn't look.
5
6import { isEnvFile } from './dotenv'
7
8export function parseWorktrees(porcelain: string): string[] {
9  return porcelain
10    .split('\n')
11    .filter(line => line.startsWith('worktree '))
12    .map(line => line.slice('worktree '.length).trim())
13}
14
15// Resolves `.` and `..` without touching the disk
16export function normalize(path: string, base: string): string {
17  const parts: string[] = []
18  for (const part of (path.startsWith('/') ? path : `${base}/${path}`).split('/')) {
19    if (part === '' || part === '.') continue
20    if (part === '..') parts.pop()
21    else parts.push(part)
22  }
23  return `/${parts.join('/')}`
24}
25
26export type Place = { path: string; label: string }
27
28// A bare name is a file in the session's own project root, as before. A path
29// must end in an env file name and sit at the root of a known worktree.
30// A path that is fine except for sitting outside every worktree carries
31// `outside`, so copy can ask the user about that folder instead
32export function resolve(value: unknown, cwd: string, worktrees: string[]): Place | { error: string; outside?: string } {
33  if (typeof value !== 'string' || value.trim() === '') return { error: 'Name an env file by its file name, or by a path to one in another worktree.' }
34  const raw = value.trim()
35  if (!raw.includes('/')) {
36    return isEnvFile(raw) ? { path: raw, label: raw } : { error: `"${raw}" is not an env file name.` }
37  }
38  const full = normalize(raw, cwd)
39  const name = full.slice(full.lastIndexOf('/') + 1)
40  const dir = full.slice(0, full.lastIndexOf('/')) || '/'
41  if (!isEnvFile(name)) return { error: `"${raw}" is not an env file.` }
42  if (!worktrees.includes(dir)) {
43    const known = worktrees.length > 0 ? ` Worktrees: ${worktrees.join(', ')}` : ''
44    return { error: `${dir} is not the root of one of this repo's git worktrees, so env won't write there.${known}`, outside: full }
45  }
46  return { path: full, label: dir === cwd ? name : full }
47}
48
types/index.d.ts 30 lines
1export type EnvEditing = { file: string; key: string | null }
2export type EnvRequest = {
3  key: string
4  file: string
5  reason: string
6  steps: string[]
7  url?: string
8  format?: string
9  pattern?: string
10}
11export type EnvFit = 'ok' | 'off' | null
12
13declare module 'claude-code' {
14  interface PluginState {
15    env: {
16      files: string[]
17      active: string
18      editing: EnvEditing | null
19      revealed: string | null
20      confirm: string | null
21      request: EnvRequest | null
22      fit: EnvFit
23      rev: number
24      flash: string | null
25      isWaiting: boolean
26      allowed: string[]
27    }
28  }
29}
30