@operad-io/harness-pi 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/package.json +14 -6
- package/src/auth-file.ts +350 -0
- package/src/index.ts +394 -382
- package/src/login-protocol.ts +64 -0
- package/src/login-worker.ts +205 -0
- package/src/login.ts +395 -0
- package/src/model-list.ts +478 -0
- package/src/pi-install.ts +95 -64
- package/src/protocol.ts +86 -94
- package/src/worker.ts +301 -399
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The line protocol between `pi/login` and its child program (ADR 0023 D11).
|
|
3
|
+
* The hub writes one JSON per line to the child's stdin; the child writes one
|
|
4
|
+
* JSON per line to its stdout. The shapes carry only JSON; an abort signal and
|
|
5
|
+
* anything the person's value would echo stay out.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** How a provider can log in, as pi's own provider list declares it. */
|
|
9
|
+
export interface LoginProvider {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly name: string;
|
|
12
|
+
/** The API-key route, with pi's own name for it. */
|
|
13
|
+
readonly apiKey?: { readonly name: string } | undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A prompt pi's login flow puts to the person, without its abort signal. */
|
|
17
|
+
export type LoginPrompt =
|
|
18
|
+
| { readonly type: "text"; readonly message: string; readonly placeholder?: string }
|
|
19
|
+
| { readonly type: "secret"; readonly message: string; readonly placeholder?: string }
|
|
20
|
+
| {
|
|
21
|
+
readonly type: "select";
|
|
22
|
+
readonly message: string;
|
|
23
|
+
readonly options: readonly {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly label: string;
|
|
26
|
+
readonly description?: string;
|
|
27
|
+
}[];
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** A notice pi's login flow shows while it works, without its abort signal. */
|
|
31
|
+
export type LoginNotice =
|
|
32
|
+
| {
|
|
33
|
+
readonly type: "info";
|
|
34
|
+
readonly message: string;
|
|
35
|
+
readonly links?: readonly { readonly url: string; readonly label?: string }[];
|
|
36
|
+
}
|
|
37
|
+
| { readonly type: "progress"; readonly message: string };
|
|
38
|
+
|
|
39
|
+
/** What the hub writes to the child. */
|
|
40
|
+
export type LoginCommand =
|
|
41
|
+
| { readonly type: "login"; readonly provider: string; readonly auth: "api_key" }
|
|
42
|
+
| { readonly type: "answer"; readonly id: number; readonly value: string }
|
|
43
|
+
| { readonly type: "cancel" };
|
|
44
|
+
|
|
45
|
+
/** What the child writes to the hub, in order. */
|
|
46
|
+
export type LoginLine =
|
|
47
|
+
| { readonly type: "providers"; readonly providers: readonly LoginProvider[] }
|
|
48
|
+
| { readonly type: "prompt"; readonly id: number; readonly prompt: LoginPrompt }
|
|
49
|
+
| { readonly type: "notice"; readonly event: LoginNotice }
|
|
50
|
+
| { readonly type: "done"; readonly provider: string; readonly auth: "api_key" }
|
|
51
|
+
| { readonly type: "failed"; readonly message: string };
|
|
52
|
+
|
|
53
|
+
/** What the child is started with, as one argument. */
|
|
54
|
+
export interface LoginStart {
|
|
55
|
+
readonly authPath: string;
|
|
56
|
+
/** The custom models file, or null for none. */
|
|
57
|
+
readonly modelsPath: string | null;
|
|
58
|
+
/** The operad home, where operad's own pi may be installed. */
|
|
59
|
+
readonly home: string;
|
|
60
|
+
/** The pi command or package path the settings name. */
|
|
61
|
+
readonly command: string;
|
|
62
|
+
/** The cwd a relative pi command is resolved from. */
|
|
63
|
+
readonly cwd: string;
|
|
64
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pi login child (ADR 0023 D11). It is the only place a login imports the
|
|
3
|
+
* pi library; the hub starts it with one JSON argument and speaks the line
|
|
4
|
+
* protocol of `login-protocol.ts` on stdin and stdout. The credential goes to
|
|
5
|
+
* pi's own auth file, and nothing of it is written to stdout.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { createInterface } from "node:readline";
|
|
9
|
+
import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { messageOf } from "@operad-io/engine";
|
|
11
|
+
import { findPi, loadPi } from "./pi-install.ts";
|
|
12
|
+
import {
|
|
13
|
+
type LoginCommand,
|
|
14
|
+
type LoginLine,
|
|
15
|
+
type LoginNotice,
|
|
16
|
+
type LoginPrompt,
|
|
17
|
+
type LoginProvider,
|
|
18
|
+
type LoginStart,
|
|
19
|
+
} from "./login-protocol.ts";
|
|
20
|
+
|
|
21
|
+
/** How long the whole login may take; a started login aborts after this. */
|
|
22
|
+
export const LOGIN_TIMEOUT_MS = 300_000;
|
|
23
|
+
|
|
24
|
+
type AuthInteraction = Parameters<ModelRuntime["login"]>[2];
|
|
25
|
+
type AuthPrompt = Parameters<AuthInteraction["prompt"]>[0];
|
|
26
|
+
type AuthEvent = Parameters<AuthInteraction["notify"]>[0];
|
|
27
|
+
type Provider = ReturnType<ModelRuntime["getProviders"]>[number];
|
|
28
|
+
|
|
29
|
+
function write(line: LoginLine): void {
|
|
30
|
+
process.stdout.write(`${JSON.stringify(line)}\n`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function toPrompt(prompt: AuthPrompt): LoginPrompt {
|
|
34
|
+
switch (prompt.type) {
|
|
35
|
+
case "select":
|
|
36
|
+
return {
|
|
37
|
+
type: "select",
|
|
38
|
+
message: prompt.message,
|
|
39
|
+
options: prompt.options.map((option) => ({
|
|
40
|
+
id: option.id,
|
|
41
|
+
label: option.label,
|
|
42
|
+
...(option.description === undefined ? {} : { description: option.description }),
|
|
43
|
+
})),
|
|
44
|
+
};
|
|
45
|
+
case "secret":
|
|
46
|
+
case "text":
|
|
47
|
+
return {
|
|
48
|
+
type: prompt.type,
|
|
49
|
+
message: prompt.message,
|
|
50
|
+
...(prompt.placeholder === undefined ? {} : { placeholder: prompt.placeholder }),
|
|
51
|
+
};
|
|
52
|
+
default:
|
|
53
|
+
throw new Error(`unknown login prompt`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function toNotice(event: AuthEvent): LoginNotice {
|
|
58
|
+
switch (event.type) {
|
|
59
|
+
case "info":
|
|
60
|
+
return {
|
|
61
|
+
type: "info",
|
|
62
|
+
message: event.message,
|
|
63
|
+
...(event.links === undefined
|
|
64
|
+
? {}
|
|
65
|
+
: {
|
|
66
|
+
links: event.links.map((link) => ({
|
|
67
|
+
url: link.url,
|
|
68
|
+
...(link.label === undefined ? {} : { label: link.label }),
|
|
69
|
+
})),
|
|
70
|
+
}),
|
|
71
|
+
};
|
|
72
|
+
case "progress":
|
|
73
|
+
return { type: "progress", message: event.message };
|
|
74
|
+
default:
|
|
75
|
+
throw new Error(`unknown login notice`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function providersOf(runtime: ModelRuntime): readonly LoginProvider[] {
|
|
80
|
+
const providers: LoginProvider[] = [];
|
|
81
|
+
for (const provider of runtime.getProviders() as readonly Provider[]) {
|
|
82
|
+
const apiKey = provider.auth.apiKey;
|
|
83
|
+
if (apiKey?.login === undefined) continue;
|
|
84
|
+
providers.push({
|
|
85
|
+
id: provider.id,
|
|
86
|
+
name: provider.name,
|
|
87
|
+
apiKey: { name: apiKey.name },
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return providers;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function main(): Promise<void> {
|
|
94
|
+
const text = process.argv[2];
|
|
95
|
+
if (text === undefined) {
|
|
96
|
+
write({ type: "failed", message: "the login child was started without its input" });
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const start = JSON.parse(text) as LoginStart;
|
|
100
|
+
const install = findPi(start.command, { home: start.home, cwd: start.cwd });
|
|
101
|
+
const pi = await loadPi(install);
|
|
102
|
+
const runtime = await pi.ModelRuntime.create({
|
|
103
|
+
authPath: start.authPath,
|
|
104
|
+
...(start.modelsPath === null ? {} : { modelsPath: start.modelsPath }),
|
|
105
|
+
allowModelNetwork: false,
|
|
106
|
+
refreshOnCreate: false,
|
|
107
|
+
});
|
|
108
|
+
write({ type: "providers", providers: providersOf(runtime) });
|
|
109
|
+
|
|
110
|
+
const queued: LoginCommand[] = [];
|
|
111
|
+
let wake: (() => void) | undefined;
|
|
112
|
+
const terminal = createInterface({ input: process.stdin });
|
|
113
|
+
terminal.on("line", (line) => {
|
|
114
|
+
let command: LoginCommand;
|
|
115
|
+
try {
|
|
116
|
+
command = JSON.parse(line) as LoginCommand;
|
|
117
|
+
} catch {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
queued.push(command);
|
|
121
|
+
wake?.();
|
|
122
|
+
});
|
|
123
|
+
const nextCommand = async (): Promise<LoginCommand> => {
|
|
124
|
+
while (queued.length === 0) {
|
|
125
|
+
await new Promise<void>((resolve) => {
|
|
126
|
+
wake = resolve;
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
wake = undefined;
|
|
130
|
+
const found = queued.shift();
|
|
131
|
+
if (found === undefined) throw new Error("the login child lost its command queue");
|
|
132
|
+
return found;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const first = await nextCommand();
|
|
136
|
+
if (first.type !== "login" || first.auth !== "api_key") {
|
|
137
|
+
// No subscription (OAuth) login starts here (ADR 0023 D11).
|
|
138
|
+
write({ type: "failed", message: "the login child expected an API-key login command" });
|
|
139
|
+
terminal.close();
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const controller = new AbortController();
|
|
144
|
+
const timer = setTimeout(() => {
|
|
145
|
+
controller.abort(new Error("the login timed out"));
|
|
146
|
+
}, LOGIN_TIMEOUT_MS);
|
|
147
|
+
let nextId = 0;
|
|
148
|
+
const waiting = new Map<number, (value: string) => void>();
|
|
149
|
+
const interaction: AuthInteraction = {
|
|
150
|
+
signal: controller.signal,
|
|
151
|
+
prompt: async (prompt: AuthPrompt) => {
|
|
152
|
+
nextId += 1;
|
|
153
|
+
const id = nextId;
|
|
154
|
+
write({ type: "prompt", id, prompt: toPrompt(prompt) });
|
|
155
|
+
return await new Promise<string>((resolve, reject) => {
|
|
156
|
+
waiting.set(id, resolve);
|
|
157
|
+
prompt.signal?.addEventListener(
|
|
158
|
+
"abort",
|
|
159
|
+
() => {
|
|
160
|
+
waiting.delete(id);
|
|
161
|
+
reject(new Error("the prompt was closed"));
|
|
162
|
+
},
|
|
163
|
+
{ once: true },
|
|
164
|
+
);
|
|
165
|
+
});
|
|
166
|
+
},
|
|
167
|
+
notify: (event: AuthEvent) => {
|
|
168
|
+
write({ type: "notice", event: toNotice(event) });
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// Commands arrive while the login waits for a person or the callback.
|
|
173
|
+
const commands = (async () => {
|
|
174
|
+
for (;;) {
|
|
175
|
+
const command = await nextCommand();
|
|
176
|
+
if (command.type === "answer") {
|
|
177
|
+
const resolve = waiting.get(command.id);
|
|
178
|
+
waiting.delete(command.id);
|
|
179
|
+
resolve?.(command.value);
|
|
180
|
+
} else if (command.type === "cancel") {
|
|
181
|
+
controller.abort(new Error("the login was cancelled"));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
})();
|
|
185
|
+
commands.catch(() => undefined);
|
|
186
|
+
|
|
187
|
+
try {
|
|
188
|
+
await runtime.login(first.provider, first.auth, interaction);
|
|
189
|
+
await runtime.settleCredentialWrites();
|
|
190
|
+
write({ type: "done", provider: first.provider, auth: first.auth });
|
|
191
|
+
} catch (error) {
|
|
192
|
+
write({ type: "failed", message: messageOf(error) });
|
|
193
|
+
} finally {
|
|
194
|
+
clearTimeout(timer);
|
|
195
|
+
terminal.close();
|
|
196
|
+
process.exit(0);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
await main();
|
|
202
|
+
} catch (error) {
|
|
203
|
+
write({ type: "failed", message: messageOf(error) });
|
|
204
|
+
process.exit(1);
|
|
205
|
+
}
|
package/src/login.ts
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hub side of a pi API-key login (ADR 0023 D11). It starts the child of
|
|
3
|
+
* `login-worker.ts`, keeps its line protocol, and turns each prompt and notice
|
|
4
|
+
* into a question or a pending item through `ctx.ask` (ADR 0008). The pi
|
|
5
|
+
* library is never imported here.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
9
|
+
import { createInterface, type Interface } from "node:readline";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { chatgptLoginCommand } from "./pi-install.ts";
|
|
14
|
+
import {
|
|
15
|
+
isRecord,
|
|
16
|
+
messageOf,
|
|
17
|
+
type AskAnswer,
|
|
18
|
+
type ChoiceInfo,
|
|
19
|
+
type PluginStepResult,
|
|
20
|
+
type StepContext,
|
|
21
|
+
} from "@operad-io/engine";
|
|
22
|
+
import {
|
|
23
|
+
type LoginCommand,
|
|
24
|
+
type LoginLine,
|
|
25
|
+
type LoginNotice,
|
|
26
|
+
type LoginPrompt,
|
|
27
|
+
type LoginProvider,
|
|
28
|
+
type LoginStart,
|
|
29
|
+
} from "./login-protocol.ts";
|
|
30
|
+
|
|
31
|
+
/** The child program a login starts. */
|
|
32
|
+
export const LOGIN_WORKER_PATH = fileURLToPath(new URL("./login-worker.ts", import.meta.url));
|
|
33
|
+
|
|
34
|
+
/** How long the provider choice and the login itself may take (ADR 0023 D11). */
|
|
35
|
+
export const LOGIN_TIMEOUT_MS = 300_000;
|
|
36
|
+
|
|
37
|
+
/** How long the model choice after a finished login may take. */
|
|
38
|
+
export const MODEL_CHOICE_SECS = 300;
|
|
39
|
+
|
|
40
|
+
/** How much of the child's stderr a failure keeps. */
|
|
41
|
+
const STDERR_LINES = 20;
|
|
42
|
+
|
|
43
|
+
/** What the login step starts and reads. */
|
|
44
|
+
export interface LoginRunOptions {
|
|
45
|
+
/** The executable that runs the login child; defaults to the running Bun. */
|
|
46
|
+
readonly command: string;
|
|
47
|
+
/** Its arguments; defaults to the login worker. */
|
|
48
|
+
readonly args?: readonly string[] | undefined;
|
|
49
|
+
/** Test seam: the whole login timeout in milliseconds. */
|
|
50
|
+
readonly timeoutMs?: number | undefined;
|
|
51
|
+
/** The time now in milliseconds; defaults to `Date.now`. */
|
|
52
|
+
readonly now?: (() => number) | undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A failure that ends the login without a person's answer. */
|
|
56
|
+
class LoginFailure extends Error {
|
|
57
|
+
constructor(message: string) {
|
|
58
|
+
super(message);
|
|
59
|
+
this.name = "LoginFailure";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The line queue and the process of one login child. */
|
|
64
|
+
class LoginChild {
|
|
65
|
+
readonly #child: ChildProcessWithoutNullStreams;
|
|
66
|
+
readonly #terminal: Interface;
|
|
67
|
+
readonly #now: () => number;
|
|
68
|
+
readonly #deadline: number;
|
|
69
|
+
readonly #lines: LoginLine[] = [];
|
|
70
|
+
readonly #stderr: string[] = [];
|
|
71
|
+
#wake: (() => void) | undefined;
|
|
72
|
+
#status: "open" | "done" | "failed" | "exited" = "open";
|
|
73
|
+
#message: string | undefined;
|
|
74
|
+
|
|
75
|
+
constructor(child: ChildProcessWithoutNullStreams, now: () => number, deadline: number) {
|
|
76
|
+
this.#child = child;
|
|
77
|
+
this.#now = now;
|
|
78
|
+
this.#deadline = deadline;
|
|
79
|
+
this.#terminal = createInterface({ input: child.stdout });
|
|
80
|
+
this.#terminal.on("line", (line) => this.#take(line));
|
|
81
|
+
createInterface({ input: child.stderr }).on("line", (line) => {
|
|
82
|
+
if (line.length === 0) return;
|
|
83
|
+
this.#stderr.push(line);
|
|
84
|
+
if (this.#stderr.length > STDERR_LINES) this.#stderr.shift();
|
|
85
|
+
});
|
|
86
|
+
child.on("close", () => {
|
|
87
|
+
if (this.#status === "open") this.#status = "exited";
|
|
88
|
+
this.#wakeUp();
|
|
89
|
+
});
|
|
90
|
+
child.on("error", (error) => {
|
|
91
|
+
this.#status = "failed";
|
|
92
|
+
this.#message = this.#message ?? messageOf(error);
|
|
93
|
+
this.#wakeUp();
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
static start(options: LoginRunOptions, input: LoginStart): LoginChild {
|
|
98
|
+
const now = options.now ?? Date.now;
|
|
99
|
+
const deadline = now() + (options.timeoutMs ?? LOGIN_TIMEOUT_MS);
|
|
100
|
+
const args = options.args ?? [LOGIN_WORKER_PATH];
|
|
101
|
+
const child = spawn(options.command, [...args, JSON.stringify(input)], {
|
|
102
|
+
cwd: input.cwd,
|
|
103
|
+
// Three entries: stdin carries the commands, stdout the lines, stderr the
|
|
104
|
+
// diagnostics. An extra pipe is what Bun closes twice (AGENTS.md).
|
|
105
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
106
|
+
env: process.env,
|
|
107
|
+
});
|
|
108
|
+
return new LoginChild(child, now, deadline);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
get deadline(): number {
|
|
112
|
+
return this.#deadline;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
#take(line: string): void {
|
|
116
|
+
let parsed: LoginLine;
|
|
117
|
+
try {
|
|
118
|
+
parsed = JSON.parse(line) as LoginLine;
|
|
119
|
+
} catch {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (parsed.type === "done") {
|
|
123
|
+
this.#status = "done";
|
|
124
|
+
} else if (parsed.type === "failed") {
|
|
125
|
+
this.#status = "failed";
|
|
126
|
+
this.#message = parsed.message;
|
|
127
|
+
}
|
|
128
|
+
this.#lines.push(parsed);
|
|
129
|
+
this.#wakeUp();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
#wakeUp(): void {
|
|
133
|
+
this.#wake?.();
|
|
134
|
+
this.#wake = undefined;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
#failure(): string {
|
|
138
|
+
const details = this.#stderr.length === 0 ? "" : `: ${this.#stderr.join(" ")}`;
|
|
139
|
+
return this.#message === undefined ? `the login program ended before its answer${details}` : this.#message;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The next line, waiting no longer than the login's deadline. */
|
|
143
|
+
async next(): Promise<LoginLine> {
|
|
144
|
+
for (;;) {
|
|
145
|
+
const found = this.#lines.shift();
|
|
146
|
+
if (found !== undefined) return found;
|
|
147
|
+
if (this.#status !== "open") throw new LoginFailure(this.#failure());
|
|
148
|
+
const left = this.#deadline - this.#now();
|
|
149
|
+
if (left <= 0) throw new LoginFailure("the login timed out");
|
|
150
|
+
await new Promise<void>((resolveWait, rejectWait) => {
|
|
151
|
+
const timer = setTimeout(() => {
|
|
152
|
+
this.#wake = undefined;
|
|
153
|
+
rejectWait(new LoginFailure("the login timed out"));
|
|
154
|
+
}, left);
|
|
155
|
+
this.#wake = () => {
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
resolveWait();
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
send(command: LoginCommand): void {
|
|
164
|
+
if (this.#child.stdin.destroyed) return;
|
|
165
|
+
this.#child.stdin.write(`${JSON.stringify(command)}\n`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** While a question waits: whether the login still needs the person. */
|
|
169
|
+
recheck(): { readonly ask: boolean; readonly note?: string } {
|
|
170
|
+
if (this.#status === "open") return { ask: true };
|
|
171
|
+
if (this.#status === "done") return { ask: false, note: "the login finished in the browser" };
|
|
172
|
+
return { ask: false, note: this.#message ?? "the login ended" };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
stop(): void {
|
|
176
|
+
this.#terminal.close();
|
|
177
|
+
if (this.#status === "open") this.#child.kill();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** A route one provider offers in the login: always its API key. */
|
|
182
|
+
interface LoginRoute {
|
|
183
|
+
readonly provider: string;
|
|
184
|
+
readonly auth: "api_key";
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The label pi gives a route, which a client shows instead of the id. */
|
|
188
|
+
function routeLabel(provider: LoginProvider): string {
|
|
189
|
+
return provider.apiKey?.name ?? provider.name;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The routes operad's interface offers: the API-key login of every provider.
|
|
194
|
+
* No subscription (OAuth) login is offered, ChatGPT's included: a person runs
|
|
195
|
+
* pi's own `pi auth login openai-codex` for it (ADR 0023 D11).
|
|
196
|
+
*/
|
|
197
|
+
function routesOf(providers: readonly LoginProvider[]): readonly LoginRoute[] {
|
|
198
|
+
const routes: LoginRoute[] = [];
|
|
199
|
+
for (const provider of providers) {
|
|
200
|
+
if (provider.apiKey !== undefined) routes.push({ provider: provider.id, auth: "api_key" });
|
|
201
|
+
}
|
|
202
|
+
return routes;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function remainingSecs(deadline: number, now: () => number): number {
|
|
206
|
+
return Math.max(0, Math.ceil((deadline - now()) / 1000));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function failed(message: string): PluginStepResult {
|
|
210
|
+
return { result: "failed", data: { message } };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Expands a leading `~` to the user's home directory. */
|
|
214
|
+
function expandHome(path: string): string {
|
|
215
|
+
if (path === "~") return homedir();
|
|
216
|
+
if (path.startsWith("~/")) return join(homedir(), path.slice(2));
|
|
217
|
+
return isAbsolute(path) ? path : resolve(path);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Asks which provider route to take; undefined when the person stopped. */
|
|
221
|
+
async function chooseProvider(
|
|
222
|
+
ctx: StepContext,
|
|
223
|
+
providers: readonly LoginProvider[],
|
|
224
|
+
deadline: number,
|
|
225
|
+
now: () => number,
|
|
226
|
+
hint: string,
|
|
227
|
+
): Promise<LoginRoute | undefined> {
|
|
228
|
+
const routes = routesOf(providers);
|
|
229
|
+
if (routes.length === 0) throw new LoginFailure("no provider of pi can log in");
|
|
230
|
+
const byId = new Map(providers.map((provider) => [provider.id, provider]));
|
|
231
|
+
const choices = routes.map((route) => route.provider);
|
|
232
|
+
const choiceInfo: Record<string, ChoiceInfo> = {};
|
|
233
|
+
for (const route of routes) {
|
|
234
|
+
const provider = byId.get(route.provider);
|
|
235
|
+
if (provider === undefined) continue;
|
|
236
|
+
choiceInfo[route.provider] = { label: routeLabel(provider) };
|
|
237
|
+
}
|
|
238
|
+
const answer = await ctx.ask({
|
|
239
|
+
prompt: `Choose a provider to log in with. ${hint}`,
|
|
240
|
+
choices,
|
|
241
|
+
choiceInfo,
|
|
242
|
+
graceSecs: remainingSecs(deadline, now),
|
|
243
|
+
onTimeout: "reject_once",
|
|
244
|
+
});
|
|
245
|
+
if (answer.rejected === true || answer.choice === undefined) return undefined;
|
|
246
|
+
const route = routes.find((candidate) => candidate.provider === answer.choice);
|
|
247
|
+
return route;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** The text of a one-question form's answer, or undefined when none came. */
|
|
251
|
+
function answerText(answer: AskAnswer): string | undefined {
|
|
252
|
+
const found = answer.answers?.[0];
|
|
253
|
+
if (found === undefined || found.skipped === true) return undefined;
|
|
254
|
+
return typeof found.text === "string" && found.text.trim().length > 0 ? found.text : undefined;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The answer for one prompt, or undefined when the person stopped the login. */
|
|
258
|
+
async function answerPrompt(
|
|
259
|
+
ctx: StepContext,
|
|
260
|
+
child: LoginChild,
|
|
261
|
+
line: Extract<LoginLine, { type: "prompt" }>,
|
|
262
|
+
deadline: number,
|
|
263
|
+
now: () => number,
|
|
264
|
+
): Promise<string | undefined> {
|
|
265
|
+
const prompt: LoginPrompt = line.prompt;
|
|
266
|
+
const graceSecs = remainingSecs(deadline, now);
|
|
267
|
+
if (graceSecs <= 0) throw new LoginFailure("the login timed out");
|
|
268
|
+
if (prompt.type === "select") {
|
|
269
|
+
const choices = prompt.options.map((option) => option.id);
|
|
270
|
+
const choiceInfo: Record<string, ChoiceInfo> = {};
|
|
271
|
+
for (const option of prompt.options) {
|
|
272
|
+
choiceInfo[option.id] = {
|
|
273
|
+
label: option.label,
|
|
274
|
+
...(option.description === undefined ? {} : { hint: option.description }),
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
const answer = await ctx.ask({
|
|
278
|
+
prompt: prompt.message,
|
|
279
|
+
choices,
|
|
280
|
+
choiceInfo,
|
|
281
|
+
graceSecs,
|
|
282
|
+
onTimeout: "reject_once",
|
|
283
|
+
});
|
|
284
|
+
if (answer.rejected === true || answer.choice === undefined) return undefined;
|
|
285
|
+
return answer.choice;
|
|
286
|
+
}
|
|
287
|
+
if (prompt.type === "secret" || prompt.type === "text") {
|
|
288
|
+
const answer = await ctx.ask({
|
|
289
|
+
prompt: prompt.message,
|
|
290
|
+
questions: [
|
|
291
|
+
{
|
|
292
|
+
id: "value",
|
|
293
|
+
text: prompt.message,
|
|
294
|
+
freeText: true,
|
|
295
|
+
...(prompt.type === "secret" ? { secret: true as const } : {}),
|
|
296
|
+
},
|
|
297
|
+
],
|
|
298
|
+
graceSecs,
|
|
299
|
+
onTimeout: "reject_once",
|
|
300
|
+
recheck: () => child.recheck(),
|
|
301
|
+
});
|
|
302
|
+
if (answer.choice === "allow_once") return "";
|
|
303
|
+
if (answer.rejected === true) return undefined;
|
|
304
|
+
return answerText(answer);
|
|
305
|
+
}
|
|
306
|
+
return undefined;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** The model the person chose after the login; undefined when they stopped. */
|
|
310
|
+
async function chooseModel(
|
|
311
|
+
ctx: StepContext,
|
|
312
|
+
provider: string,
|
|
313
|
+
): Promise<string | undefined> {
|
|
314
|
+
const models = (await ctx.harnessModelsReady?.("pi")) ?? ctx.harnessModels?.("pi");
|
|
315
|
+
const ids = (models?.list ?? []).map((model) => (typeof model === "string" ? model : model.id));
|
|
316
|
+
const list = ids.filter((id) => id.startsWith(`${provider}/`));
|
|
317
|
+
if (list.length === 0) throw new LoginFailure(`pi lists no model for ${provider}`);
|
|
318
|
+
const preferred = models?.default;
|
|
319
|
+
const primary = preferred !== undefined && preferred !== null && list.includes(preferred) ? preferred : list[0];
|
|
320
|
+
const choiceInfo: Record<string, ChoiceInfo> = {};
|
|
321
|
+
if (primary !== undefined) choiceInfo[primary] = { role: "primary" };
|
|
322
|
+
const answer = await ctx.ask({
|
|
323
|
+
prompt: "Choose the model the bot uses.",
|
|
324
|
+
choices: list,
|
|
325
|
+
choiceInfo,
|
|
326
|
+
graceSecs: MODEL_CHOICE_SECS,
|
|
327
|
+
onTimeout: "reject_once",
|
|
328
|
+
});
|
|
329
|
+
if (answer.rejected === true || answer.choice === undefined) return undefined;
|
|
330
|
+
return list.includes(answer.choice) ? answer.choice : undefined;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* `pi/login`: asks for a provider and a model and hands the provider to the
|
|
335
|
+
* child that runs pi's login. The result is `done` with `{ provider, model }`
|
|
336
|
+
* or `failed` with `{ message }`.
|
|
337
|
+
*/
|
|
338
|
+
export async function runLoginStep(
|
|
339
|
+
ctx: StepContext,
|
|
340
|
+
options: LoginRunOptions,
|
|
341
|
+
): Promise<PluginStepResult> {
|
|
342
|
+
const now = options.now ?? Date.now;
|
|
343
|
+
const settings = ctx.settings;
|
|
344
|
+
const input: LoginStart = {
|
|
345
|
+
authPath: expandHome(
|
|
346
|
+
typeof settings.authPath === "string" && settings.authPath !== ""
|
|
347
|
+
? settings.authPath
|
|
348
|
+
: "~/.pi/agent/auth.json",
|
|
349
|
+
),
|
|
350
|
+
modelsPath:
|
|
351
|
+
typeof settings.modelsPath === "string" && settings.modelsPath !== ""
|
|
352
|
+
? expandHome(settings.modelsPath)
|
|
353
|
+
: join(homedir(), ".pi", "agent", "models.json"),
|
|
354
|
+
home: ctx.home,
|
|
355
|
+
command:
|
|
356
|
+
typeof settings.command === "string" && settings.command !== "" ? settings.command : "pi",
|
|
357
|
+
cwd: ctx.cwd,
|
|
358
|
+
};
|
|
359
|
+
let child: LoginChild;
|
|
360
|
+
try {
|
|
361
|
+
child = LoginChild.start(options, input);
|
|
362
|
+
} catch (error) {
|
|
363
|
+
return failed(messageOf(error));
|
|
364
|
+
}
|
|
365
|
+
try {
|
|
366
|
+
const first = await child.next();
|
|
367
|
+
if (first.type === "failed") return failed(first.message);
|
|
368
|
+
if (first.type !== "providers") {
|
|
369
|
+
return failed("the login program did not report its providers");
|
|
370
|
+
}
|
|
371
|
+
const hint = `For your ChatGPT plan, run \`${chatgptLoginCommand(input.command, { home: ctx.home, cwd: ctx.cwd })}\`; operad picks it up once it is done.`;
|
|
372
|
+
const route = await chooseProvider(ctx, first.providers, child.deadline, now, hint);
|
|
373
|
+
if (route === undefined) return failed("the login was cancelled");
|
|
374
|
+
child.send({ type: "login", provider: route.provider, auth: route.auth });
|
|
375
|
+
for (;;) {
|
|
376
|
+
const line = await child.next();
|
|
377
|
+
if (line.type === "done") break;
|
|
378
|
+
if (line.type === "failed") return failed(line.message);
|
|
379
|
+
if (line.type === "notice") continue;
|
|
380
|
+
if (line.type === "prompt") {
|
|
381
|
+
const answer = await answerPrompt(ctx, child, line, child.deadline, now);
|
|
382
|
+
if (answer === undefined) return failed("the login was cancelled");
|
|
383
|
+
if (answer !== "") child.send({ type: "answer", id: line.id, value: answer });
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
const model = await chooseModel(ctx, route.provider);
|
|
387
|
+
if (model === undefined) return failed("the login finished but no model was chosen");
|
|
388
|
+
return { result: "done", data: { provider: route.provider, model } };
|
|
389
|
+
} catch (error) {
|
|
390
|
+
if (error instanceof LoginFailure) return failed(error.message);
|
|
391
|
+
return failed(messageOf(error));
|
|
392
|
+
} finally {
|
|
393
|
+
child.stop();
|
|
394
|
+
}
|
|
395
|
+
}
|