Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,23 @@ jobs:

- name: Unit tests
run: npm run test --workspaces

windows-agent-setup:
runs-on: windows-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- name: Setup Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 22
cache: npm
- name: Install dependencies
run: npm ci --ignore-scripts
- name: Build
run: npm run build --workspaces
- name: Windows launcher smoke
run: npm exec --workspace packages/cli -- vitest run tests/agent-setup-windows.test.ts
68 changes: 68 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,74 @@

CLI-native affiliate tracking. Connect Stripe, track commissions, manage partners -- all from your terminal.

## AI agent setup

From the project root, preview the local installation before applying it:

```bash
affitor agent setup --client claude_code --dry-run --json
affitor agent setup --client claude_code --yes
affitor doctor --client claude_code --json
```

Choose `claude_code`, `cursor`, or `codex`; repeat `--client` for more than one.
Without a selection, an interactive terminal asks, with nothing selected by default.
Noninteractive runs require `--yes` and a selection. Inside an agent, setup can only
configure that agent. `--dry-run` writes nothing. Without confirmation, setup exits1.

Claude Code uses project `.mcp.json`; Cursor uses `.cursor/mcp.json`. Existing
unrelated settings are preserved. Existing file bytes are backed up under
`.affitor/backups/` before replacement, with mode0600; generated `.gitignore`
entries exclude backups and `.affitor/.env`. Updates use atomic replacement and
read-back, rolling back prior writes on failure. Backups and their local ignore
guard are kept on failure so a restored root `.gitignore` cannot expose them.
An existing backup guard must contain only `*`; negation or extra rules are refused.
Credential and backup ignore rules are appended at the end of both the root
`.gitignore` and `.affitor/.gitignore`, preserving earlier custom rules while
overriding negations. Existing files are backed up before changing them.
A concurrent edit is preserved;
inspect the files and private backups before retrying. This protects ordinary
local edits, not a hostile process racing filesystem operations.

The generated `.affitor/agent-mcp.cjs` launcher starts pinned `@affitor/mcp@0.2.2`
from this project's absolute directory. No credential is embedded in an agent
config, launcher, or skill. The launcher reads inherited `AFFITOR_API_KEY`, then
this project's `.affitor/.env` (created by `affitor init`). It never reads the user
login token in `~/.affitor/credentials.json`. If `onboard` wrote a key to your root
`.env`, provide it privately as `AFFITOR_API_KEY` when starting the agent instead.
It removes inherited API URL overrides regardless of their casing and uses the
production API. It disables sale/refund tools even when the parent
environment has `AFFITOR_MCP_WRITE=1`. Other tools still include tracking and
synthetic verification; approve those actions separately.

A recovery skill is installed in `.claude/skills/affitor/` or `.cursor/skills/affitor/`.
Codex gets `.agents/skills/affitor/` and a printed `codex mcp add` command; setup
does not edit its TOML config or run that command. Review it, then run it yourself.
If you move the project, run setup again to update absolute paths. The printed
command uses POSIX shell quoting on macOS/Linux. On Windows, no shell command
is generated: add the MCP in Codex settings using `command: "node"` and the exact
absolute path from the preview's `entry.args` as one argument. Do not paste POSIX
commands into cmd.exe.

**Installed is not verified.** Successful setup returns `needs_human` (exit0).
`doctor` is read-only and static: it does not start an agent, connect to the API,
or prove the key works. It returns `aligned`/`stale`/`missing`/`manual`/`invalid`
per client and `present_unverified`/`missing` for credentials. With no selection,
doctor checks existing JSON client configs; an agent caller checks itself.
Exit0 means all selected static checks align and a credential is present;
otherwise exit1. Restart the agent and ask it to call `affitor_readiness`, checking
the program identity before integration. Only report the readiness checks that pass.

Doctor and the launcher use the same credential parser: empty, duplicate and
interpolated assignments fail closed. An explicit nonempty environment value
takes precedence and is validated without reading a file. On Windows, the
launcher runs `npx.cmd` through `cmd.exe` with a constant command; project paths
and credentials are passed through `cwd`/environment, outside shell text.

This local installer uses an existing program key. Per-agent key issuance,
pairing, connection telemetry, and the dashboard Agents page are separate work;
this command does not claim to create or verify an agent connection.

## Quick Start

```bash
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { registerSetupCommand } from "./commands/setup-stripe.js";
import { registerStatusCommand } from "./commands/status.js";
import { registerTestCommand } from "./commands/test.js";
import { registerProgramsCommand } from "./commands/programs.js";
import { registerAgentCommands } from "./commands/agent.js";

// Read the version from package.json at runtime so `affitor --version` never
// drifts from the published package version (dist/cli.js → ../package.json).
Expand Down Expand Up @@ -72,5 +73,6 @@ registerSetupCommand(program);
registerStatusCommand(program);
registerTestCommand(program);
registerProgramsCommand(program);
registerAgentCommands(program);

program.parse();
82 changes: 82 additions & 0 deletions packages/cli/src/commands/agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import type { Command } from "commander";
import { checkbox, confirm } from "@inquirer/prompts";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { CLIENTS, applySetup, callerClient, doctor, planSetup, selectedClients } from "../lib/agent-setup.js";
import { getFlags } from "../lib/flags.js";

interface SetupOptions { client?: string[]; dryRun?: boolean; yes?: boolean }

export function registerAgentCommands(program: Command) {
program.command("agent").description("Configure an AI coding agent for this project")
.command("setup")
.description("Preview and install project-scoped MCP configuration and an Affitor skill")
.option("--client <name>", "claude_code, cursor or codex (repeat to select)", (value: string, prior: string[]) => [...prior, value], [])
.option("--dry-run", "Show the plan without writing files")
.option("--yes", "Apply the selected client's plan")
.action(async (opts: SetupOptions, cmd: Command) => {
const flags = getFlags(cmd);
try {
let clients = selectedClients(opts.client ?? [], process.env);
const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY && !flags.noInteractive && !flags.json);
if (!clients.length && interactive && !opts.dryRun) {
clients = selectedClients(await checkbox({
message: "Which agents should get Affitor in this project?",
choices: CLIENTS.map(value => ({ value, name: `${value}${existsSync(join(process.cwd(), value === "claude_code" ? ".claude" : value === "cursor" ? ".cursor" : ".agents")) ? " (project directory found)" : ""}`, checked: false })),
}), process.env);
}
const plan = planSetup(process.cwd(), clients);
// Never serialize plan.actions.content: existing configs can contain
// unrelated credentials that must stay local, including in a dry-run.
const preview = {
project: plan.project, clients, caller: callerClient(process.env) ?? null,
entry: plan.entry, mcpVersion: plan.mcpVersion,
actions: plan.actions.map(({ path, operation, backup }) => ({ path, operation, backup })),
manual: plan.manual,
};
let status = opts.dryRun ? "planned" : "needs_confirmation";
if (!flags.json) process.stdout.write(JSON.stringify(preview, null, 2) + "\n");
let approved = Boolean(opts.yes || flags.autoConfirm);
if (!opts.dryRun && clients.length && !approved && interactive) {
approved = await confirm({ message: "Apply this plan? Existing files are backed up first.", default: false });
}
if (!opts.dryRun && approved && clients.length) {
applySetup(plan);
status = "needs_human";
}
const next = !clients.length
? "Select --client claude_code, cursor or codex. Detected agents are not selected automatically."
: status === "needs_confirmation"
? "Review the plan, then run affitor agent setup --client <name> --yes."
: "Installed is not verified. Configure the program key privately as AFFITOR_API_KEY or in .affitor/.env; restart the selected agent, then ask it to call affitor_readiness. For Codex, first follow the printed manual configuration instructions.";
if (flags.json) process.stdout.write(JSON.stringify({ status, ...preview, next }) + "\n");
else process.stdout.write(`${status}\n${next}\n`);
process.exitCode = status === "needs_confirmation" || (!clients.length && !opts.dryRun) ? 1 : 0;
} catch (error) {
// Expected installer errors contain only fixed messages and relative
// client paths. Do not print arbitrary fs/JSON/credential exceptions.
const message = error instanceof Error && /^(Unknown client|An agent can only|\.mcp\.json |\.cursor\/mcp\.json |Setup failed|A setup file|Unsafe setup|Setup target)/.test(error.message)
? error.message : "Agent setup could not finish. Check the project paths and run a fresh dry-run.";
process.stdout.write(JSON.stringify({ status: "error", message }) + "\n");
process.exitCode = 1;
}
});

program.command("doctor").description("Read-only static check of local agent configuration; does not verify a running session")
.option("--client <name>", "Check one client (repeat to select)", (value: string, prior: string[]) => [...prior, value], [])
.action((opts: SetupOptions, cmd: Command) => {
try {
const clients = selectedClients(opts.client ?? [], process.env);
const configured = CLIENTS.filter(client => client !== "codex" && existsSync(join(process.cwd(), client === "claude_code" ? ".mcp.json" : ".cursor/mcp.json")));
const results = doctor(process.cwd(), clients.length ? clients : configured.length ? configured : ["claude_code", "cursor"]);
const healthy = results.every(result => result.status === "aligned" && result.credential === "present_unverified");
const result = { status: healthy ? "aligned" : "needs_attention", mode: "static", clients: results, next: "Restart the selected agent and call affitor_readiness. Static checks do not prove a live connection or integration readiness." };
if (getFlags(cmd).json) process.stdout.write(JSON.stringify(result) + "\n");
else process.stdout.write(JSON.stringify(result, null, 2) + "\n");
process.exitCode = healthy ? 0 : 1;
} catch {
process.stdout.write(JSON.stringify({ status: "error", message: "Doctor could not check the selected client. Use claude_code, cursor or codex." }) + "\n");
process.exitCode = 1;
}
});
}
77 changes: 77 additions & 0 deletions packages/cli/src/lib/agent-launcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Kept as a standalone CommonJS file in the customer's project: a client can
// start it from any directory, without putting a credential in its MCP config.
export const MCP_VERSION = "0.2.2";

/** Shared by doctor and the generated launcher; never evaluates an env file. */
export function parseProgramCredential(envKey: unknown, readText: () => string | null): string | null {
const valid = (value: string) => /^[A-Za-z0-9_-]+$/.test(value);
if (typeof envKey === "string" && envKey !== "") return valid(envKey) ? envKey : null;
try {
const text = readText();
if (text === null) return null;
const assignments = text.split(/\r?\n/).filter(line => /^\s*(?:export\s+)?AFFITOR_API_KEY\s*=/.test(line));
if (assignments.length !== 1) return null;
let value = assignments[0].replace(/^\s*(?:export\s+)?AFFITOR_API_KEY\s*=\s*/, "").trim();
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
return valid(value) ? value : null;
} catch { return null; }
}

export const AGENT_LAUNCHER = `// Generated by affitor agent setup. Contains no credentials.
const { readFileSync, lstatSync } = require('node:fs');
const { join, resolve } = require('node:path');
const { spawn } = require('node:child_process');
const project = resolve(__dirname, '..');
const parseProgramCredential = ${parseProgramCredential.toString()};
const key = parseProgramCredential(process.env.AFFITOR_API_KEY, () => {
const path = join(__dirname, '.env');
const stat = lstatSync(path);
if (!stat.isFile() || stat.isSymbolicLink()) return null;
return readFileSync(path, 'utf8');
});
if (!key) {
process.stderr.write('Affitor: set AFFITOR_API_KEY or configure this project with affitor init. No agent call was made.\\n');
process.exit(1);
}
// Setup never opts into the sale/refund tools, including through inherited env.
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) =>
!['AFFITOR_API_URL', 'AFFITOR_API_KEY', 'AFFITOR_MCP_WRITE'].includes(name.toUpperCase())));
env.AFFITOR_API_KEY = key;
env.AFFITOR_MCP_WRITE = '0';
// Windows batch files require cmd.exe. The command contains constants only:
// project paths and credentials travel through cwd/env, never shell text.
const windows = process.platform === 'win32';
const command = windows ? (process.env.ComSpec || 'cmd.exe') : 'npx';
const args = windows ? ['/d', '/s', '/c', 'npx.cmd -y @affitor/mcp@${MCP_VERSION}'] : ['-y', '@affitor/mcp@${MCP_VERSION}'];
const child = spawn(command, args, { cwd: project, env, stdio: 'inherit', shell: false, windowsHide: true });
child.on('error', () => { process.stderr.write('Affitor: could not start the pinned MCP. Check Node.js, npm and network access.\\n'); process.exitCode = 1; });
child.on('exit', (code, signal) => { process.exitCode = signal ? 1 : (code ?? 1); });
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));
`;

export const AGENT_SKILL = `---
name: affitor
description: Check Affitor affiliate integration readiness and follow its integration runbook.
metadata:
version: "1"
---

# Affitor

Connect only when this project needs Affitor. Follow https://affitor.com/docs/skill.md
and the founder's optional context. Detect the framework and payment provider first.
Never print, copy into a prompt, or commit credentials. Never treat a user login token
as a program key. Do not add a second sale writer when Stripe Connect may record sales.

Installed, signed in, and verified are different states. After restarting the client,
call affitor_readiness and check the program identity before changing this project.
Only describe checks that actually passed. A static doctor cannot prove a live session.
Do not run sale/refund tools. Ask before running synthetic verification or other writes.

| Problem | Next step |
| --- | --- |
| Missing or stale local files | Run affitor agent setup --dry-run --json, show the plan, then apply the selected client after approval. |
| Files aligned, tools absent | Restart the selected agent, then call affitor_readiness. |
| Credential missing or rejected | Configure AFFITOR_API_KEY privately for this program. Never paste the key into chat. |
| Readiness fails | Report the failed checks and follow the runbook; do not claim integration is verified. |
`;
Loading
Loading