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
2 changes: 2 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ jobs:
timeout-minutes: 15
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.4.2
Expand Down
9 changes: 8 additions & 1 deletion src/cli/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,14 @@ export async function doctor(deps: DoctorDeps): Promise<number> {
deps.out.line(`${level.padEnd(6)}${text}`);
};
await checkAgent(deps, say);
const apps = deps.store.apps();
let apps: AppRecord[];
try {
apps = deps.store.apps();
} catch (error) {
// A locked or unreachable keychain, or an unreadable credentials.json: the store says which.
say("FAIL", (error as Error).message);
return 1;
}
if (apps.length === 0) say("warn", "No apps connected. Run: tether connect <app-url>");
for (const app of apps) await checkApp(deps, app, say);
return failed ? 1 : 0;
Expand Down
49 changes: 44 additions & 5 deletions src/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ async function connect(ctx: Context, value: string): Promise<number> {
ctx.out.line("Waiting for approval...");
const approved = await pollPairing(ctx, client, started);
ctx.secrets.add(approved.credential);
const where = ctx.store.saveApp({
const { where, warning } = ctx.store.saveApp({
origin,
name: client.app.name,
device: approved.device,
Expand All @@ -203,6 +203,7 @@ async function connect(ctx: Context, value: string): Promise<number> {
`Connected to ${client.app.name} as "${approved.account.name}" (device "${approved.device.name}").`,
);
ctx.out.line(`The device credential is in ${where}.`);
if (warning) ctx.err.line(warning);
ctx.out.line(`If that is not your account, run: tether disconnect ${origin}`);
return 0;
}
Expand Down Expand Up @@ -253,9 +254,7 @@ async function pollOnce(

async function start(ctx: Context, args: string[]): Promise<number> {
const concurrency = parseCount(args, "concurrency", 1, 16);
ctx.store.moveToKeychain();
const records = ctx.store.apps();
if (records.length === 0) throw new Error("No apps connected. Run: tether connect <app-url>");
const records = connectedApps(ctx);
const running = ctx.store.runState();
if (running && isAlive(running.pid)) {
throw new Error(`Tether is already running (pid ${running.pid}).`);
Expand All @@ -279,7 +278,47 @@ async function start(ctx: Context, args: string[]): Promise<number> {
agentVersion,
signal,
});
return worker.run(records);
const trimming = trimServiceLog(ctx);
try {
return await worker.run(records);
} finally {
clearInterval(trimming);
}
}

/** How often a running `tether start` checks the size of the service log. */
const SERVICE_LOG_CHECK_MS = 10 * 60_000;

/**
* Keeps service.log, which the background service writes, under its size limit: now and every
* ten minutes. Not on Windows, where cmd's `>>` keeps writing at its old offset after a cut.
*/
function trimServiceLog(ctx: Context): NodeJS.Timeout | undefined {
if ((ctx.io.platform ?? process.platform) === "win32") return undefined;
const trim = () => {
try {
ctx.store.trimServiceLog();
} catch (error) {
ctx.err.line(`Could not trim the service log: ${(error as Error).message}`);
}
};
trim();
const timer = setInterval(trim, SERVICE_LOG_CHECK_MS);
timer.unref();
return timer;
}

/**
* The apps to run, after moving file credentials into the keychain; warns about each one the
* keychain refused once its credential is known to the redactor.
*/
function connectedApps(ctx: Context): AppRecord[] {
const refused = ctx.store.moveToKeychain();
const records = ctx.store.apps();
for (const record of records) ctx.secrets.add(record.credential);
for (const warning of refused) ctx.err.line(warning);
if (records.length === 0) throw new Error("No apps connected. Run: tether connect <app-url>");
return records;
}

/** The command's only option, `--<name> <n>`, a whole number from 1 to `max`; no positionals. */
Expand Down
32 changes: 22 additions & 10 deletions src/cli/service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import type { Run } from "../client/run.ts";
import type { Ran, Run } from "../client/run.ts";

/** What a background service runs and where its files go; built once from the CLI's context. */
export interface ServiceSpec {
Expand Down Expand Up @@ -53,14 +53,19 @@ export function thisProgram(execPath: string, argv: string[]): string[] {

class ServiceError extends Error {}

function failure(done: Ran, what: string): ServiceError {
const detail = done.stderr.trim() || done.stdout.trim() || `exit ${done.status ?? "timeout"}`;
return new ServiceError(`${what} failed: ${detail.slice(0, 500)}`);
}

function must(run: Run, command: string, args: string[], what: string): void {
const done = run(command, args);
if (done.status !== 0) {
const detail = done.stderr.trim() || done.stdout.trim() || `exit ${done.status ?? "timeout"}`;
throw new ServiceError(`${what} failed: ${detail.slice(0, 500)}`);
}
if (done.status !== 0) throw failure(done, what);
}

/** How often `bootstrap` is tried, a second apart, while an old agent is still booting out. */
const BOOTSTRAP_TRIES = 10;

function writePrivate(path: string, content: string | Buffer): void {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content, { mode: 0o600 });
Expand Down Expand Up @@ -130,12 +135,21 @@ export const launchd: ServiceManager = {
kind: "launchd",
install(spec, run) {
const target = `gui/${spec.uid}`;
// launchd would create the log readable by everyone; create it first, readable by the user.
// launchd would create the log readable by everyone; create it first, readable by the user,
// and take back a log an older install left readable by everyone.
const log = join(spec.home, "service.log");
if (!existsSync(log)) writePrivate(log, "");
if (existsSync(log)) chmodSync(log, 0o600);
else writePrivate(log, "");
writePrivate(launchdPlistPath(spec), launchdPlist(spec));
run("launchctl", ["bootout", `${target}/${launchdLabel(spec)}`]);
must(run, "launchctl", ["bootstrap", target, launchdPlistPath(spec)], "launchctl bootstrap");
// bootout returns before a running agent has stopped, and bootstrap fails until it has.
for (let tries = 1; ; tries += 1) {
const done = run("launchctl", ["bootstrap", target, launchdPlistPath(spec)]);
if (done.status === 0) return;
if (tries === BOOTSTRAP_TRIES) throw failure(done, "launchctl bootstrap");
// Through the same runner as launchctl, so a test's runner does not wait.
run("sleep", ["1"]);
}
},
uninstall(spec, run) {
run("launchctl", ["bootout", `gui/${spec.uid}/${launchdLabel(spec)}`]);
Expand Down Expand Up @@ -168,8 +182,6 @@ export function systemdUnit(spec: ServiceSpec): string {
.join("\n");
return `[Unit]
Description=Tether: runs connected apps' tasks with Claude Code
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
Expand Down
47 changes: 33 additions & 14 deletions src/client/keychain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ export interface Keychain {
readonly name: string;
/** The secret, or undefined when the keychain does not hold one; throws KeychainUnavailable. */
get(origin: string): string | undefined;
/** False when the keychain refused the secret: the caller keeps it somewhere else. */
set(origin: string, secret: string): boolean;
/**
* Stores the secret; returns why the keychain refused it, or undefined once it holds it. A
* refused secret is the caller's to keep somewhere else. The reason never holds the secret.
*/
set(origin: string, secret: string): string | undefined;
delete(origin: string): void;
}

Expand All @@ -20,6 +23,18 @@ function quoted(value: string): string | undefined {

const MAC_NOT_FOUND = 44;

/** Why a write that the tool accepted still failed: it does not give the same secret back. */
function readBack(keychain: Keychain, origin: string, secret: string): string | undefined {
try {
return keychain.get(origin) === secret
? undefined
: `${keychain.name} did not give the credential back`;
} catch (error) {
if (error instanceof KeychainUnavailable) return error.message;
throw error;
}
}

/** The macOS login keychain through `/usr/bin/security`; `service` names this Tether home's items. */
export function macKeychain(service: string, exec: Run = run): Keychain {
const keychain: Keychain = {
Expand All @@ -35,15 +50,15 @@ export function macKeychain(service: string, exec: Run = run): Keychain {
set: (origin, secret) => {
const account = quoted(origin);
const password = quoted(secret);
if (!account || !password) return false;
if (!account || !password) {
return "the origin or credential holds a character `security -i` cannot take";
}
// `security -i` reads its commands from stdin, which keeps the secret out of argv.
const line = `add-generic-password -U -s ${service} -a ${account} -l ${quoted(`Tether ${origin}`)} -w ${password}\n`;
if (exec("security", ["-i"], line).status !== 0) return false;
try {
return keychain.get(origin) === secret;
} catch {
return false;
}
const done = exec("security", ["-i"], line);
// Only the status: security may echo the command line, and with it the secret.
if (done.status !== 0) return `security exited ${done.status ?? "timeout"}`;
return readBack(keychain, origin, secret);
},
delete: (origin) => {
exec("security", ["delete-generic-password", "-s", service, "-a", origin]);
Expand All @@ -68,12 +83,16 @@ export function secretToolKeychain(service: string, exec: Run = run): Keychain {
},
set: (origin, secret) => {
const args = ["store", `--label=Tether ${origin}`, ...attributes(origin)];
if (exec("secret-tool", args, secret).status !== 0) return false;
try {
return keychain.get(origin) === secret;
} catch {
return false;
const done = exec("secret-tool", args, secret);
if (done.status !== 0) {
// The secret went only to stdin, which secret-tool does not echo; its stderr says why.
const why = done.stderr
.trim()
.replace(/\n[\s\S]*/, "")
.slice(0, 200);
return `secret-tool exited ${done.status ?? "timeout"}${why ? `: ${why}` : ""}`;
}
return readBack(keychain, origin, secret);
},
delete: (origin) => {
exec("secret-tool", ["clear", ...attributes(origin)]);
Expand Down
72 changes: 62 additions & 10 deletions src/client/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ export interface TaskLogEntry {

const TASK_LOG_KEEP = 1000;
const TASK_LOG_TRIM_BYTES = 1_000_000;
/** The longest title, in characters, the task log keeps: the app sets it, so it is not trusted. */
const TASK_LOG_TITLE_MAX = 200;
/** Past this size the service log is cut to about its last SERVICE_LOG_KEEP_BYTES. */
const SERVICE_LOG_MAX_BYTES = 5_000_000;
const SERVICE_LOG_KEEP_BYTES = 1_000_000;

/** Whether the file's last byte is not a newline; false for a missing or empty file. */
function endsTorn(file: string): boolean {
Expand Down Expand Up @@ -168,22 +173,41 @@ export class Store {
return { ...record, credential };
}

/** Saves the app; returns where its credential went (the keychain's name or the file's path). */
saveApp(record: AppRecord): string {
/**
* Saves the app. `where` names the place its credential went: the keychain or the file. A
* `warning` says the keychain refused it and why; with no keychain at all the file is the place.
*/
saveApp(record: AppRecord): { where: string; warning?: string } {
const others = this.stored().filter((app) => app.origin !== record.origin);
const { credential, ...rest } = record;
if (this.#keychain?.set(record.origin, credential)) {
const refused = this.#keychain?.set(record.origin, credential);
if (this.#keychain && refused === undefined) {
this.write("credentials.json", { apps: [...others, { ...rest, credential_in: "keychain" }] });
return this.#keychain.name;
return { where: this.#keychain.name };
}
this.write("credentials.json", { apps: [...others, record] });
return this.path("credentials.json");
const where = this.path("credentials.json");
if (!this.#keychain) return { where };
const name = this.#keychain.name.replace(/^./, (first) => first.toUpperCase());
return {
where,
warning: `${name} refused the credential for ${record.origin} (${refused}), so it is in ${where}, readable only by you.`,
};
}

/** Moves credentials an older Tether, or a refused keychain, left in the file into the keychain. */
moveToKeychain(): void {
if (!this.#keychain) return;
for (const app of this.stored()) if ("credential" in app) this.saveApp(app);
/**
* Moves credentials an older Tether, or a refused keychain, left in the file into the keychain;
* returns a warning for each one the keychain refuses again.
*/
moveToKeychain(): string[] {
if (!this.#keychain) return [];
const warnings: string[] = [];
for (const app of this.stored()) {
if (!("credential" in app)) continue;
const { warning } = this.saveApp(app);
if (warning) warnings.push(warning);
}
return warnings;
}

removeApp(origin: string): void {
Expand Down Expand Up @@ -222,7 +246,8 @@ export class Store {
const file = this.path("tasks.jsonl");
// A crash mid-append leaves a line without its newline; start on a fresh line after it.
const torn = endsTorn(file) ? "\n" : "";
appendFileSync(file, `${torn}${JSON.stringify(entry)}\n`, { mode: 0o600 });
const title = Array.from(entry.title).slice(0, TASK_LOG_TITLE_MAX).join("");
appendFileSync(file, `${torn}${JSON.stringify({ ...entry, title })}\n`, { mode: 0o600 });
if (statSync(file).size > TASK_LOG_TRIM_BYTES) {
const kept = this.taskLog(TASK_LOG_KEEP).map((entry) => JSON.stringify(entry));
const temp = this.path(`.tasks.jsonl.${process.pid}.tmp`);
Expand All @@ -231,6 +256,33 @@ export class Store {
}
}

/**
* Cuts service.log to its last lines once it passes about 5 MB. The file is rewritten in place,
* not renamed: launchd and the Windows `>>` redirect append, so the running service keeps
* writing at the new end of the same file.
*/
trimServiceLog(): void {
const file = this.path("service.log");
let size: number;
try {
size = statSync(file).size;
} catch {
return;
}
if (size <= SERVICE_LOG_MAX_BYTES) return;
const tail = Buffer.alloc(SERVICE_LOG_KEEP_BYTES);
const fd = openSync(file, "r");
try {
readSync(fd, tail, 0, tail.length, size - tail.length);
} finally {
closeSync(fd);
}
// Start on a whole line: the first one in the tail is most likely cut.
const kept = tail.subarray(tail.indexOf(0x0a) + 1);
writeFileSync(file, kept, { mode: 0o600 });
chmodSync(file, 0o600);
}

/** The last `limit` finished tasks, oldest first; a line that does not parse is skipped. */
taskLog(limit: number): TaskLogEntry[] {
let text: string;
Expand Down
28 changes: 17 additions & 11 deletions src/client/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,20 +298,26 @@ export class Worker {
ended,
});
const settled = done
.then((result) => {
log(result.costUsd, result.ended);
return result.costUsd === undefined ? reservation : result.costUsd;
})
.catch((error: unknown) => {
this.#opts.log.line(`${record.name} ${claim.task.id} ${(error as Error).message}`);
log(undefined, "error");
return reservation;
})
.then((spent) => {
.then(
(result) => result,
(error: unknown) => {
this.#opts.log.line(`${record.name} ${claim.task.id} ${(error as Error).message}`);
return { costUsd: undefined, ended: "error" };
},
)
.then(({ costUsd, ended }) => {
this.#reserved.set(record.origin, (this.#reserved.get(record.origin) ?? 0) - reservation);
this.#opts.store.addUsage(localDate(new Date()), record.origin, { tasks: 0, usd: spent });
this.#running.delete(key);
this.#slots.give();
try {
log(costUsd, ended);
} catch (error) {
this.#opts.log.line(
`${record.name} ${claim.task.id} could not be written to the task log: ${(error as Error).message}`,
);
}
const spent = costUsd === undefined ? reservation : costUsd;
this.#opts.store.addUsage(localDate(new Date()), record.origin, { tasks: 0, usd: spent });
this.publish();
});
this.#running.set(key, {
Expand Down
Loading
Loading