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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 2.1.0

### Added

- `loopway setup`: an interactive walk through what loopway needs, safe to run again. It checks `gh` (and offers `gh auth login`), Claude Code, the bot user's token (checked against GitHub, saved to `~/.loopway/config.json` for you alone) and offers `.loopway/dev.md` and `review.md` here, for the repos you name. It only asks about what is missing and never overwrites a file. See [#556](https://github.com/craftmilldev/loopway/issues/556).

## 2.0.3

### Added
Expand Down
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ npm install && npm run build # Node 22+
gh auth login # loopway acts as whoever gh is logged in as
```

Or install the latest release: `npm install -g https://github.com/craftmilldev/loopway/releases/latest/download/loopway-cli.tgz`.
After installing, run `loopway setup` (see [Setup](#setup)). Or install the latest release: `npm install -g https://github.com/craftmilldev/loopway/releases/latest/download/loopway-cli.tgz`.

Make a directory to run it from, with a `.loopway/` folder holding one file per bot (`scratch/` inside the checkout is git-ignored):

Expand Down Expand Up @@ -55,6 +55,17 @@ To run it from a directory outside the checkout, `npm link -w @loopway/cli` puts

The first run starts now: it does not replay history. An issue or pull request from before that stays quiet until something happens to it; then, if it is open, it is reported as new, with only what happened since as updates, and its bots start threads. After that it remembers where it got to, so a restart prints nothing twice and picks up what happened while it was stopped.

## Setup

`loopway setup` is an interactive walk through what loopway needs, in a terminal (it refuses to run without one). Each step checks first and only asks about what is missing, so it is safe to run again on a machine that is already set up: it never overwrites a file you have, and the steps that can be left out say so.

1. **`gh`**, required. It must be installed and logged in; if it isn't logged in, setup offers to run `gh auth login` for you. It says who you are logged in as. Without a working login it stops.
2. **Claude Code**, which runs the sessions. It checks `claude --version`; if it isn't there, setup says where to get it and carries on.
3. **The bot user**, optional. If `~/.loopway/config.json` has a bot token, setup checks GitHub accepts it and says whose it is. Otherwise it asks for the token of a separate GitHub account (typed as dots, never printed), checks it, refuses your own account's (the bot would comment as you), and saves it as the `github` block with the account's login as `name` and its `users.noreply.github.com` address as `email`. The file is written for you alone (0600) and its other keys are kept. Skipping leaves sessions off.
4. **The bot files**, optional, one each for `.loopway/dev.md` and `.loopway/review.md` in the directory you ran it from. It asks which repos they should watch (guessing from `git remote origin`), warns about one `gh` can't see, and writes the files from the examples under [Bots](#bots-loopway). A file that is already there is left alone.

It ends by telling you to run `loopway` and assign an issue to yourself.

## Threads

A **thread** is one bot plus the subjects it tracks. The rules are in each bot's front matter (see below), and they are deterministic:
Expand Down
1 change: 1 addition & 0 deletions docs/developing.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ When CI passes on a push to `main` and `packages/cli` changed since the last `cl
| `tui-header.tsx`, `tui-theme.ts` | The header (version, poller status) and the pinned keys; the colors, taken from the billboard |
| `tui-log.ts` | The session log as turn blocks, one row per line, and the tool call sentences |
| `tui-input.tsx`, `tui-text.ts` | The chat text box (cursor, editing); the thread state and grouping, and the poller's status line |
| `setup.ts`, `setup-io.tsx` | `loopway setup`: the steps (gh, Claude Code, the bot token, the bot files), written against an `Io` interface so tests script the answers and the fake `exec` and `fetch` keep them off the machine and the network; and the real `Io`, one inline [Ink](https://github.com/vadimdemedev/ink) question at a time (`gh auth login` gets the terminal itself) |
| `format.ts` | The printed line, and `--json` |

`tools/init-scratch.mjs` (`npm run init-scratch`) is a plain Node script, outside the packages; `test/init-scratch.test.ts` runs it in a temp dir.
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@loopway/cli",
"version": "2.0.3",
"version": "2.1.0",
"private": true,
"license": "MIT",
"description": "loopway: polls GitHub and prints every new subject and every update to one you know.",
Expand Down
15 changes: 14 additions & 1 deletion packages/cli/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readFile } from "node:fs/promises";
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";

Expand Down Expand Up @@ -42,3 +42,16 @@ export async function loadAutoUpdate(home: string, env: NodeJS.ProcessEnv = proc
if (env.LOOPWAY_NO_UPDATE) return false;
return (await readConfig(home)).auto_update !== false;
}

/**
* Sets the `github` block of config.json and leaves every other key as it was. The file holds a token, so it is
* written for you alone (0600), in a folder made if need be.
*/
export async function saveGitHubConfig(home: string, github: GitHubConfig): Promise<void> {
const config = await readConfig(home);
const block = { ...(config.github as Record<string, unknown> | undefined), ...github };
await mkdir(home, { recursive: true });
const path = join(home, "config.json");
await writeFile(path, JSON.stringify({ ...config, github: block }, null, 2) + "\n", { mode: 0o600 });
await chmod(path, 0o600); // writeFile's mode only applies to a new file
}
24 changes: 24 additions & 0 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { loadAutoUpdate, loadGitHubConfig, loopwayHome, type GitHubConfig } from
import { formatJson, formatLine, formatThread, formatThreadJson, type LoopwayEvent } from "./format.js";
import { ghToken, GitHubSource } from "./github.js";
import { startMcp } from "./mcp.js";
import { inkIo, SetupCancelled } from "./setup-io.js";
import { runSetup } from "./setup.js";
import { Poller } from "./poller.js";
import { Sessions } from "./sessions.js";
import type { Subject } from "./source.js";
Expand All @@ -31,10 +33,15 @@ and every update to the ones it knows.

Usage: loopway [--no-tui] [--json] [--max N]
loopway threads [--json]
loopway setup

In a terminal it opens a TUI: the open threads and those closed in the last 3 days. Enter opens a thread, q quits.
With --no-tui, --json, or output that isn't a terminal, it prints a plain log instead.

\`loopway setup\` walks you through what loopway needs: gh logged in, Claude Code, the bot user's token (optional) and
.loopway/dev.md and review.md here (optional). It checks each first, only asks about what is missing, and never
overwrites a file.

Each new issue or pull request starts a thread for every bot whose rules ask for it (on: issue, on: pull_request),
and every update to it goes on the queue of the open threads that hold it. Each thread's queue goes to a Claude Code
session that acts as the bot user and talks back through loopway's own MCP tool. \`loopway threads\` lists the open
Expand Down Expand Up @@ -92,6 +99,23 @@ async function main(): Promise<number> {
}

const project = projectDir();
if (positionals[0] === "setup") {
if (!process.stdout.isTTY || !process.stdin.isTTY)
throw new Error("loopway setup asks questions: run it in a terminal.");
const io = inkIo();
try {
return await runSetup({ io, home: loopwayHome(), cwd: project });
} catch (err) {
if (err instanceof SetupCancelled) {
await io.close();
console.error("Cancelled: nothing more was changed.");
return 1;
}
throw err;
} finally {
await io.close();
}
}
if (positionals[0] === "threads") return listThreads(stateDir(loopwayHome(), project), values.json);
if (positionals.length > 0) throw new Error(`Unknown command "${positionals[0]}". Try loopway --help.`);

Expand Down
164 changes: 164 additions & 0 deletions packages/cli/src/setup-io.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import { Box, render, Static, Text, useInput } from "ink";
import { useEffect, useState } from "react";
import { runInherited, type Io } from "./setup.js";
import { editInput, emptyInput, InputLine, type InputState } from "./tui-input.js";
import { theme } from "./tui-theme.js";

const MARKS = { ok: "✓", warn: "!", fail: "✗" } as const;

/** What is being asked: a choice from a list, or a line of text (dots, for a secret). */
export type Question =
| { kind: "choose"; question: string; options: { value: string; label: string }[] }
| { kind: "text"; question: string; initial?: string; secret?: boolean };

/** The choices, as drawn: the one at `at` is marked. */
export function Choose({ question, options, at }: { question: string; options: { label: string }[]; at: number }) {
return (
<Box flexDirection="column">
<Text color={theme.land}>? {question}</Text>
{options.map((o, i) => (
<Text key={o.label} color={i === at ? theme.red : undefined}>
{i === at ? "❯ " : " "}
{o.label}
</Text>
))}
<Text dimColor>↑/↓ to move, Enter to choose</Text>
</Box>
);
}

/** The line being typed, as drawn: a secret shows as dots of the same length, so editing behaves as with text. */
export function Prompt({ question, input, secret }: { question: string; input: InputState; secret?: boolean }) {
const shown = secret ? { ...input, value: "•".repeat(input.value.length) } : input;
return (
<Box flexDirection="column">
<Text color={theme.land}>? {question}</Text>
<Box>
<Text color={theme.red}>❯ </Text>
<InputLine state={shown} width={Math.max(20, (process.stdout.columns ?? 80) - 4)} />
</Box>
</Box>
);
}

/** What the screen shows: the lines said so far, and the question being asked, if any. */
/** Ctrl-C at a question: setup stops, and says so. */
export class SetupCancelled extends Error {
constructor() {
super("Cancelled.");
}
}

class Store {
reject?: (err: Error) => void;
lines: { id: number; text: string }[] = [];
question?: Question;
answer?: (value: string) => void;
private listeners = new Set<() => void>();
subscribe(fn: () => void) {
this.listeners.add(fn);
return () => void this.listeners.delete(fn);
}
change(fn: () => void) {
fn();
for (const l of this.listeners) l();
}
/** A new array each time: `Static` only looks again when it gets a different one. */
say(text: string) {
this.change(() => (this.lines = [...this.lines, { id: this.lines.length, text }]));
}
}

/**
* One app for the whole walk, with one `useInput` for the whole of it. Questions that came and went each with their
* own `useInput` dropped the terminal out of raw mode between them, and a token typed then was echoed as plain text.
*/
function Screen({ store }: { store: Store }) {
const [, tick] = useState(0);
const [at, setAt] = useState(0);
const [input, setInput] = useState<InputState>(emptyInput);
useEffect(() => store.subscribe(() => tick((n) => n + 1)), [store]);
const q = store.question;
// A new question starts at its first choice, or its initial text.
useEffect(() => {
setAt(0);
const initial = q?.kind === "text" ? (q.initial ?? "") : "";
setInput({ value: initial, cursor: initial.length });
}, [q]);
useInput((typed, key) => {
if (key.ctrl && typed === "c") {
if (store.reject) store.reject(new SetupCancelled());
else process.exit(1); // between questions, while something is being checked
return;
}
if (!q || !store.answer) return;
if (q.kind === "choose") {
if (key.upArrow) setAt((i) => Math.max(0, i - 1));
else if (key.downArrow) setAt((i) => Math.min(q.options.length - 1, i + 1));
else if (key.return) store.answer(q.options[at]!.value);
} else if (key.return) store.answer(input.value);
else setInput((s) => editInput(s, typed, key));
});
return (
<>
<Static items={store.lines}>{(line) => <Text key={line.id}>{line.text}</Text>}</Static>
{q?.kind === "choose" && <Choose question={q.question} options={q.options} at={at} />}
{q?.kind === "text" && <Prompt question={q.question} input={input} secret={q.secret} />}
</>
);
}

/**
* The real terminal for `loopway setup`: Ink for the questions, with the lines said above them. `close` ends it.
*/
export function inkIo(): Io & { close: () => Promise<void> } {
let store = new Store();
let app: ReturnType<typeof render> | undefined;
// exitOnCtrlC off: Ink would unmount without settling the question, and setup would end quietly with code 0.
const open = () => (app ??= render(<Screen store={store} />, { exitOnCtrlC: false }));
const ask = (question: Question) => {
open();
return new Promise<string>((resolve, reject) => {
store.reject = reject;
store.change(() => {
store.question = question;
store.answer = (value) => {
// The answered question stays on screen as a line.
store.say(
`? ${question.question} ${question.kind === "text" && question.secret ? "•".repeat(value.length) : value}`,
);
store.change(() => {
store.question = undefined;
store.answer = undefined;
store.reject = undefined;
});
resolve(value);
};
});
});
};
const close = async () => {
const current = app;
app = undefined;
// Ink draws at most every ~30 ms: let the last lines said (the closing "Done.") reach the screen before it stops.
if (current) await new Promise((resolve) => setTimeout(resolve, 150));
current?.unmount();
await current?.waitUntilExit();
};
return {
say: (line, tone) => {
open();
store.say(tone ? `${MARKS[tone]} ${line}` : line);
},
choose: ((question, options) => ask({ kind: "choose", question, options })) as Io["choose"],
text: (question, initial) => ask({ kind: "text", question, initial }),
secret: (question) => ask({ kind: "text", question, secret: true }),
// gh auth login asks its own questions: give it the terminal, and start again after it, with a clean screen.
run: async (command, args) => {
await close();
store = new Store();
return runInherited(command, args);
},
close,
};
}
Loading
Loading