chore(vendor): import pi 0.85.1
Imported as a linear vendor commit so forge rebases do not replay the upstream root tree. git-subtree-dir: third_party/pi git-subtree-split: d981de1229ef899957bbe968bc8dcda02a21f477
This commit is contained in:
16
third_party/pi/packages/coding-agent/src/cli/experimental/cli.ts
vendored
Normal file
16
third_party/pi/packages/coding-agent/src/cli/experimental/cli.ts
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Command } from "./command.ts";
|
||||
import { type ClientCommandContext, clientCommand } from "./commands/client.ts";
|
||||
import { type ServerCommandContext, serverCommand } from "./commands/server.ts";
|
||||
|
||||
interface ExperimentalCommandGroup {
|
||||
readonly command: "experimental";
|
||||
}
|
||||
|
||||
export type CliContext = ServerCommandContext & ClientCommandContext;
|
||||
|
||||
const experimentalCommand = new Command<ExperimentalCommandGroup, CliContext>("experimental").build(() => ({
|
||||
ok: false,
|
||||
errors: ["Expected experimental command: server or client"],
|
||||
}));
|
||||
|
||||
export const cli = experimentalCommand.command(serverCommand).command(clientCommand);
|
||||
106
third_party/pi/packages/coding-agent/src/cli/experimental/command-options.ts
vendored
Normal file
106
third_party/pi/packages/coding-agent/src/cli/experimental/command-options.ts
vendored
Normal file
@@ -0,0 +1,106 @@
|
||||
import { posix } from "node:path";
|
||||
import { isServerId, type ServerId } from "@earendil-works/pi-protocol";
|
||||
import { type ParsedCommandInput, stringOption, valueOption } from "./command.ts";
|
||||
|
||||
export type AuthInput =
|
||||
| { readonly type: "token"; readonly token: string }
|
||||
| { readonly type: "file"; readonly path: string };
|
||||
|
||||
interface UnixTransportAddress {
|
||||
readonly transport: "unix";
|
||||
readonly path: string;
|
||||
}
|
||||
|
||||
interface RadiusTransportAddress {
|
||||
readonly transport: "radius";
|
||||
readonly serverId: ServerId;
|
||||
}
|
||||
|
||||
export type TransportAddress = UnixTransportAddress | RadiusTransportAddress;
|
||||
|
||||
export const authTokenOption = stringOption("--auth-token");
|
||||
export const authTokenFileOption = stringOption("--auth-token-file");
|
||||
|
||||
function parseAuthInput(options: { readonly authToken?: string; readonly authTokenFile?: string }): {
|
||||
auth?: AuthInput;
|
||||
errors: string[];
|
||||
} {
|
||||
if (options.authToken !== undefined && options.authTokenFile !== undefined) {
|
||||
return { errors: ["--auth-token and --auth-token-file are mutually exclusive"] };
|
||||
}
|
||||
if (options.authToken !== undefined) {
|
||||
return { auth: { type: "token", token: options.authToken }, errors: [] };
|
||||
}
|
||||
if (options.authTokenFile !== undefined) {
|
||||
return { auth: { type: "file", path: options.authTokenFile }, errors: [] };
|
||||
}
|
||||
return { errors: [] };
|
||||
}
|
||||
|
||||
function parseTransportAddress(value: string): { address?: TransportAddress; error?: string } {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return { error: `Invalid --connect address "${value}"` };
|
||||
}
|
||||
if (url.protocol === "radius:") {
|
||||
if (
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.port ||
|
||||
(url.pathname !== "" && url.pathname !== "/") ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
value !== `radius://${url.hostname}${url.pathname}`
|
||||
) {
|
||||
return { error: `Invalid --connect address "${value}"` };
|
||||
}
|
||||
const serverId = url.hostname;
|
||||
if (!isServerId(serverId)) {
|
||||
return { error: "Radius transport address requires a lowercase UUIDv4 server ID" };
|
||||
}
|
||||
return { address: { transport: "radius", serverId } };
|
||||
}
|
||||
if (url.protocol !== "unix:") return { error: `Unsupported --connect transport "${url.protocol}"` };
|
||||
if (url.hostname || url.port || url.username || url.password) {
|
||||
return { error: "Unix transport address must not include an authority" };
|
||||
}
|
||||
if (
|
||||
!value.startsWith("unix:///") ||
|
||||
value.startsWith("unix:////") ||
|
||||
value.includes("?") ||
|
||||
value.includes("#") ||
|
||||
url.href !== value
|
||||
) {
|
||||
return { error: `Invalid --connect address "${value}"` };
|
||||
}
|
||||
let path: string;
|
||||
try {
|
||||
path = decodeURIComponent(url.pathname);
|
||||
} catch {
|
||||
return { error: `Invalid --connect address "${value}"` };
|
||||
}
|
||||
if (path.includes("\0")) return { error: `Invalid --connect address "${value}"` };
|
||||
if (!posix.isAbsolute(path)) return { error: "Unix transport address requires an absolute path" };
|
||||
return { address: { transport: "unix", path } };
|
||||
}
|
||||
|
||||
export const connectOption = valueOption("--connect", (value) => {
|
||||
const result = parseTransportAddress(value);
|
||||
return result.address
|
||||
? { ok: true, value: result.address }
|
||||
: { ok: false, error: result.error ?? `Invalid --connect address "${value}"` };
|
||||
});
|
||||
|
||||
export function parseAuth(input: ParsedCommandInput): { auth?: AuthInput; errors: string[] } {
|
||||
return parseAuthInput({
|
||||
authToken: input.value(authTokenOption),
|
||||
authTokenFile: input.value(authTokenFileOption),
|
||||
});
|
||||
}
|
||||
|
||||
export function unsupportedOptions(command: string, input: ParsedCommandInput): string[] {
|
||||
if (input.remainingArgs.length === 0) return [];
|
||||
return [`The experimental ${command} command does not support existing CLI options yet`];
|
||||
}
|
||||
225
third_party/pi/packages/coding-agent/src/cli/experimental/command.ts
vendored
Normal file
225
third_party/pi/packages/coding-agent/src/cli/experimental/command.ts
vendored
Normal file
@@ -0,0 +1,225 @@
|
||||
export interface NamedCommandInvocation {
|
||||
readonly command: string;
|
||||
}
|
||||
|
||||
export type CommandParseResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =
|
||||
| { readonly ok: true; readonly command: TInvocation }
|
||||
| { readonly ok: false; readonly errors: readonly string[] };
|
||||
|
||||
export type CommandExecutionResult<TInvocation extends NamedCommandInvocation = NamedCommandInvocation> =
|
||||
| { readonly ok: true; readonly command: TInvocation }
|
||||
| { readonly ok: false; readonly errors: readonly string[] };
|
||||
|
||||
export type CommandOptionParseResult<TValue> =
|
||||
| { readonly ok: true; readonly value: TValue }
|
||||
| { readonly ok: false; readonly error: string };
|
||||
|
||||
export interface CommandOption<TValue> {
|
||||
readonly name: `-${string}`;
|
||||
readonly flag?: boolean;
|
||||
readonly repeatable?: boolean;
|
||||
parse(value: string): CommandOptionParseResult<TValue>;
|
||||
}
|
||||
|
||||
export function valueOption<TValue>(
|
||||
name: `-${string}`,
|
||||
parse: (value: string) => CommandOptionParseResult<TValue>,
|
||||
options: { readonly repeatable?: boolean } = {},
|
||||
): CommandOption<TValue> {
|
||||
return { name, parse, ...options };
|
||||
}
|
||||
|
||||
export function stringOption(
|
||||
name: `-${string}`,
|
||||
options: { readonly repeatable?: boolean } = {},
|
||||
): CommandOption<string> {
|
||||
return valueOption(name, (value) => ({ ok: true, value }), options);
|
||||
}
|
||||
|
||||
export function flagOption(name: `-${string}`): CommandOption<boolean> {
|
||||
return { name, flag: true, parse: () => ({ ok: true, value: true }) };
|
||||
}
|
||||
|
||||
export interface ParsedCommandInput {
|
||||
readonly remainingArgs: readonly string[];
|
||||
value<TValue>(option: CommandOption<TValue>): TValue | undefined;
|
||||
values<TValue>(option: CommandOption<TValue>): readonly TValue[];
|
||||
}
|
||||
|
||||
export type CommandBuildResult<TInvocation extends NamedCommandInvocation> =
|
||||
| { readonly ok: true; readonly command: TInvocation }
|
||||
| { readonly ok: false; readonly errors: readonly string[] };
|
||||
|
||||
interface MutableParsedCommandInput {
|
||||
readonly values: Map<string, unknown[]>;
|
||||
readonly remainingArgs: string[];
|
||||
readonly errors: string[];
|
||||
}
|
||||
|
||||
type CommandBuilder<TInvocation extends NamedCommandInvocation> = (
|
||||
input: ParsedCommandInput,
|
||||
) => CommandBuildResult<TInvocation>;
|
||||
|
||||
type CommandAction<TInvocation extends NamedCommandInvocation, TContext> = (
|
||||
command: TInvocation,
|
||||
context: TContext,
|
||||
) => void | Promise<void>;
|
||||
|
||||
interface RegisteredCommand {
|
||||
parse(argv: readonly string[]): CommandParseResult;
|
||||
execute(argv: readonly string[], context: unknown): Promise<CommandExecutionResult>;
|
||||
}
|
||||
|
||||
export class Command<
|
||||
TOwnInvocation extends NamedCommandInvocation,
|
||||
TContext,
|
||||
TInvocation extends NamedCommandInvocation = TOwnInvocation,
|
||||
> {
|
||||
readonly name: string;
|
||||
private readonly options = new Map<string, CommandOption<unknown>>();
|
||||
private readonly subcommands = new Map<string, RegisteredCommand>();
|
||||
private builder?: CommandBuilder<TOwnInvocation>;
|
||||
private commandAction?: CommandAction<TOwnInvocation, TContext>;
|
||||
|
||||
constructor(name: string) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
option<TValue>(option: CommandOption<TValue>): this {
|
||||
if (this.options.has(option.name)) {
|
||||
throw new Error(`Option ${option.name} is already registered for ${this.name}`);
|
||||
}
|
||||
this.options.set(option.name, option);
|
||||
return this;
|
||||
}
|
||||
|
||||
build(builder: CommandBuilder<TOwnInvocation>): this {
|
||||
this.builder = builder;
|
||||
return this;
|
||||
}
|
||||
|
||||
action(action: CommandAction<TOwnInvocation, TContext>): this {
|
||||
this.commandAction = action;
|
||||
return this;
|
||||
}
|
||||
|
||||
command<
|
||||
TSubcommandOwnInvocation extends NamedCommandInvocation,
|
||||
TSubcommandContext,
|
||||
TSubcommandInvocation extends NamedCommandInvocation,
|
||||
>(
|
||||
command: Command<TSubcommandOwnInvocation, TSubcommandContext, TSubcommandInvocation>,
|
||||
): Command<TOwnInvocation, TContext & TSubcommandContext, TInvocation | TSubcommandInvocation> {
|
||||
if (this.subcommands.has(command.name)) throw new Error(`Command ${command.name} is already registered`);
|
||||
this.subcommands.set(command.name, {
|
||||
parse: (argv) => command.parse(argv),
|
||||
execute: (argv, context) => command.execute(argv, context as TSubcommandContext),
|
||||
});
|
||||
return this as unknown as Command<
|
||||
TOwnInvocation,
|
||||
TContext & TSubcommandContext,
|
||||
TInvocation | TSubcommandInvocation
|
||||
>;
|
||||
}
|
||||
|
||||
parse(argv: readonly string[]): CommandParseResult<TInvocation> {
|
||||
const selected = this.select(argv);
|
||||
if (selected) return selected.command.parse(selected.argv) as CommandParseResult<TInvocation>;
|
||||
return this.parseOwn(argv) as CommandParseResult<TInvocation>;
|
||||
}
|
||||
|
||||
async execute(argv: readonly string[], context: TContext): Promise<CommandExecutionResult<TInvocation>> {
|
||||
const selected = this.select(argv);
|
||||
if (selected) {
|
||||
return selected.command.execute(selected.argv, context) as Promise<CommandExecutionResult<TInvocation>>;
|
||||
}
|
||||
|
||||
const parsed = this.parseOwn(argv);
|
||||
if (!parsed.ok) return parsed;
|
||||
if (!this.commandAction) throw new Error(`Command ${this.name} does not define an action`);
|
||||
await this.commandAction(parsed.command, context);
|
||||
return { ok: true, command: parsed.command as unknown as TInvocation };
|
||||
}
|
||||
|
||||
private select(argv: readonly string[]): { command: RegisteredCommand; argv: readonly string[] } | undefined {
|
||||
const candidate = argv[0];
|
||||
if (candidate === undefined) return undefined;
|
||||
const command = this.subcommands.get(candidate);
|
||||
return command ? { command, argv: argv.slice(1) } : undefined;
|
||||
}
|
||||
|
||||
private parseOwn(argv: readonly string[]): CommandParseResult<TOwnInvocation> {
|
||||
if (!this.builder) throw new Error(`Command ${this.name} does not define a builder`);
|
||||
const parsed = this.parseOptions(argv);
|
||||
const input: ParsedCommandInput = {
|
||||
remainingArgs: parsed.remainingArgs,
|
||||
value: <TValue>(option: CommandOption<TValue>) => parsed.values.get(option.name)?.[0] as TValue | undefined,
|
||||
values: <TValue>(option: CommandOption<TValue>) => (parsed.values.get(option.name) ?? []) as readonly TValue[],
|
||||
};
|
||||
const built = this.builder(input);
|
||||
const errors = [...parsed.errors, ...(built.ok ? [] : built.errors)];
|
||||
if (errors.length > 0) return { ok: false, errors };
|
||||
if (!built.ok) throw new Error(`Command ${this.name} failed without an error`);
|
||||
return { ok: true, command: built.command };
|
||||
}
|
||||
|
||||
private parseOptions(argv: readonly string[]): MutableParsedCommandInput {
|
||||
const parsed: MutableParsedCommandInput = {
|
||||
values: new Map(),
|
||||
remainingArgs: [],
|
||||
errors: [],
|
||||
};
|
||||
for (let index = 0; index < argv.length; index++) {
|
||||
const argument = argv[index]!;
|
||||
if (argument === "--") {
|
||||
parsed.remainingArgs.push(...argv.slice(index));
|
||||
break;
|
||||
}
|
||||
|
||||
const equals = argument.indexOf("=");
|
||||
const name = equals === -1 ? argument : argument.slice(0, equals);
|
||||
const option = this.options.get(name);
|
||||
if (!option) {
|
||||
parsed.remainingArgs.push(...argv.slice(index));
|
||||
break;
|
||||
}
|
||||
|
||||
let value: string;
|
||||
if (option.flag === true) {
|
||||
if (equals !== -1) {
|
||||
parsed.errors.push(`${name} does not take a value`);
|
||||
continue;
|
||||
}
|
||||
value = "";
|
||||
} else {
|
||||
let candidate = equals === -1 ? undefined : argument.slice(equals + 1);
|
||||
if (candidate === undefined) {
|
||||
const next = argv[index + 1];
|
||||
if (next !== undefined && !next.startsWith("-")) {
|
||||
candidate = next;
|
||||
index++;
|
||||
}
|
||||
}
|
||||
if (candidate === undefined || candidate === "") {
|
||||
parsed.errors.push(`${name} requires a value`);
|
||||
continue;
|
||||
}
|
||||
value = candidate;
|
||||
}
|
||||
|
||||
const values = parsed.values.get(name) ?? [];
|
||||
if (values.length > 0 && option.repeatable !== true) {
|
||||
parsed.errors.push(`${name} may only be specified once`);
|
||||
continue;
|
||||
}
|
||||
const result = option.parse(value);
|
||||
if (!result.ok) {
|
||||
parsed.errors.push(result.error);
|
||||
continue;
|
||||
}
|
||||
values.push(result.value);
|
||||
parsed.values.set(name, values);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
91
third_party/pi/packages/coding-agent/src/cli/experimental/commands/client.ts
vendored
Normal file
91
third_party/pi/packages/coding-agent/src/cli/experimental/commands/client.ts
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
import { Command, flagOption, stringOption } from "../command.ts";
|
||||
import {
|
||||
type AuthInput,
|
||||
authTokenFileOption,
|
||||
authTokenOption,
|
||||
connectOption,
|
||||
parseAuth,
|
||||
type TransportAddress,
|
||||
unsupportedOptions,
|
||||
} from "../command-options.ts";
|
||||
|
||||
export interface ClientCommand {
|
||||
readonly command: "client";
|
||||
readonly auth?: AuthInput;
|
||||
readonly connect?: TransportAddress;
|
||||
readonly sessionId?: string;
|
||||
readonly continue?: boolean;
|
||||
readonly resume?: boolean;
|
||||
readonly provider?: string;
|
||||
readonly model?: string;
|
||||
readonly pluginPackages?: readonly string[];
|
||||
readonly prompt?: string;
|
||||
}
|
||||
|
||||
export interface ClientCommandContext {
|
||||
runClient(command: ClientCommand): void | Promise<void>;
|
||||
}
|
||||
|
||||
const sessionIdOption = stringOption("--session-id");
|
||||
const continueOption = flagOption("--continue");
|
||||
const continueShortOption = flagOption("-c");
|
||||
const resumeOption = flagOption("--resume");
|
||||
const resumeShortOption = flagOption("-r");
|
||||
const providerOption = stringOption("--provider");
|
||||
const modelOption = stringOption("--model");
|
||||
const pluginPackageOption = stringOption("-e", { repeatable: true });
|
||||
|
||||
export const clientCommand = new Command<ClientCommand, ClientCommandContext>("client")
|
||||
.option(connectOption)
|
||||
.option(sessionIdOption)
|
||||
.option(continueOption)
|
||||
.option(continueShortOption)
|
||||
.option(resumeOption)
|
||||
.option(resumeShortOption)
|
||||
.option(providerOption)
|
||||
.option(modelOption)
|
||||
.option(pluginPackageOption)
|
||||
.option(authTokenOption)
|
||||
.option(authTokenFileOption)
|
||||
.build((input) => {
|
||||
const { auth, errors: authErrors } = parseAuth(input);
|
||||
const connect = input.value(connectOption);
|
||||
const sessionId = input.value(sessionIdOption);
|
||||
const shouldContinue = input.value(continueOption) === true || input.value(continueShortOption) === true;
|
||||
const shouldResume = input.value(resumeOption) === true || input.value(resumeShortOption) === true;
|
||||
const provider = input.value(providerOption);
|
||||
const model = input.value(modelOption);
|
||||
const pluginPackages = input.values(pluginPackageOption);
|
||||
const promptArgs = input.remainingArgs[0] === "--" ? input.remainingArgs.slice(1) : input.remainingArgs;
|
||||
const prompt =
|
||||
promptArgs.length === 1 &&
|
||||
(input.remainingArgs[0] === "--" || !promptArgs[0]!.startsWith("-")) &&
|
||||
promptArgs[0]!.length > 0
|
||||
? promptArgs[0]
|
||||
: undefined;
|
||||
const modelErrors = provider !== undefined && model === undefined ? ["--provider requires --model"] : [];
|
||||
const sessionSelectionErrors =
|
||||
[sessionId !== undefined, shouldContinue, shouldResume].filter(Boolean).length > 1
|
||||
? ["--session-id, --continue, and --resume are mutually exclusive"]
|
||||
: [];
|
||||
const unsupportedErrors =
|
||||
input.remainingArgs.length === 0 || prompt !== undefined ? [] : unsupportedOptions("client", input);
|
||||
const errors = [...authErrors, ...modelErrors, ...sessionSelectionErrors, ...unsupportedErrors];
|
||||
if (errors.length > 0) return { ok: false, errors };
|
||||
return {
|
||||
ok: true,
|
||||
command: {
|
||||
command: "client",
|
||||
...(auth === undefined ? {} : { auth }),
|
||||
...(connect === undefined ? {} : { connect }),
|
||||
...(sessionId === undefined ? {} : { sessionId }),
|
||||
...(shouldContinue ? { continue: true } : {}),
|
||||
...(shouldResume ? { resume: true } : {}),
|
||||
...(provider === undefined ? {} : { provider }),
|
||||
...(model === undefined ? {} : { model }),
|
||||
...(pluginPackages.length === 0 ? {} : { pluginPackages }),
|
||||
...(prompt === undefined ? {} : { prompt }),
|
||||
},
|
||||
};
|
||||
})
|
||||
.action((command, context) => context.runClient(command));
|
||||
66
third_party/pi/packages/coding-agent/src/cli/experimental/commands/server.ts
vendored
Normal file
66
third_party/pi/packages/coding-agent/src/cli/experimental/commands/server.ts
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
import { isServerId, type ServerId } from "@earendil-works/pi-protocol";
|
||||
import { Command, stringOption, valueOption } from "../command.ts";
|
||||
import {
|
||||
type AuthInput,
|
||||
authTokenFileOption,
|
||||
authTokenOption,
|
||||
parseAuth,
|
||||
unsupportedOptions,
|
||||
} from "../command-options.ts";
|
||||
|
||||
export interface ServerCommand {
|
||||
readonly command: "server";
|
||||
readonly auth?: AuthInput;
|
||||
readonly provider?: string;
|
||||
readonly model?: string;
|
||||
readonly pluginPackages?: readonly string[];
|
||||
readonly serverId?: ServerId;
|
||||
readonly sessionDir?: string;
|
||||
}
|
||||
|
||||
export interface ServerCommandContext {
|
||||
runServer(command: ServerCommand): void | Promise<void>;
|
||||
}
|
||||
|
||||
const serverIdOption = valueOption("--server-id", (value) =>
|
||||
isServerId(value)
|
||||
? { ok: true, value }
|
||||
: { ok: false, error: `Invalid --server-id "${value}"; expected a lowercase UUIDv4` },
|
||||
);
|
||||
const sessionDirOption = stringOption("--session-dir");
|
||||
const providerOption = stringOption("--provider");
|
||||
const modelOption = stringOption("--model");
|
||||
const pluginPackageOption = stringOption("-e", { repeatable: true });
|
||||
|
||||
export const serverCommand = new Command<ServerCommand, ServerCommandContext>("server")
|
||||
.option(serverIdOption)
|
||||
.option(sessionDirOption)
|
||||
.option(providerOption)
|
||||
.option(modelOption)
|
||||
.option(pluginPackageOption)
|
||||
.option(authTokenOption)
|
||||
.option(authTokenFileOption)
|
||||
.build((input) => {
|
||||
const { auth, errors: authErrors } = parseAuth(input);
|
||||
const serverId = input.value(serverIdOption);
|
||||
const sessionDir = input.value(sessionDirOption);
|
||||
const provider = input.value(providerOption);
|
||||
const model = input.value(modelOption);
|
||||
const pluginPackages = input.values(pluginPackageOption);
|
||||
const modelErrors = provider !== undefined && model === undefined ? ["--provider requires --model"] : [];
|
||||
const errors = [...authErrors, ...modelErrors, ...unsupportedOptions("server", input)];
|
||||
if (errors.length > 0) return { ok: false, errors };
|
||||
return {
|
||||
ok: true,
|
||||
command: {
|
||||
command: "server",
|
||||
...(auth === undefined ? {} : { auth }),
|
||||
...(provider === undefined ? {} : { provider }),
|
||||
...(model === undefined ? {} : { model }),
|
||||
...(pluginPackages.length === 0 ? {} : { pluginPackages }),
|
||||
...(serverId === undefined ? {} : { serverId }),
|
||||
...(sessionDir === undefined ? {} : { sessionDir }),
|
||||
},
|
||||
};
|
||||
})
|
||||
.action((command, context) => context.runServer(command));
|
||||
Reference in New Issue
Block a user