@operad-io/bot 0.1.1 → 0.3.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/src/login.ts ADDED
@@ -0,0 +1,226 @@
1
+ /**
2
+ * The login of a bot's agent (ADR 0030 D14). A bot whose agent can log in and
3
+ * is not signed in gets one standing pending item; the `login` action starts a
4
+ * short flow whose one step calls the harness's own login step and writes the
5
+ * model the person chose into the bot's existing `model` setting.
6
+ */
7
+
8
+ import { randomUUID } from "node:crypto";
9
+ import {
10
+ defineFlow,
11
+ isRecord,
12
+ messageOf,
13
+ type ActionTypeDefinition,
14
+ type JsonValue,
15
+ type PluginStepResult,
16
+ type StandingContext,
17
+ type StandingItem,
18
+ type StepContext,
19
+ } from "@operad-io/engine";
20
+ import { BOT_TYPE, BotError, readBots } from "./bot.ts";
21
+ import { updateBotsFile, validateBots } from "./proposals.ts";
22
+
23
+ /** The step that runs the agent's login and writes the chosen model. */
24
+ export const LOGIN_STEP = "bot/login";
25
+
26
+ /** The event an action sends to start the login flow. */
27
+ export const LOGIN_EVENT = "login";
28
+
29
+ /** The source of that event; the bot plugin owns the login, not a client. */
30
+ export const LOGIN_SOURCE = "bot";
31
+
32
+ /**
33
+ * The harness whose login a bot uses: the agent it names when that agent
34
+ * offers a login step, else the one loaded harness that offers one. Undefined
35
+ * when the bot names none and none or several harnesses can log in.
36
+ */
37
+ export function loginHarness(
38
+ named: unknown,
39
+ loaded: readonly string[],
40
+ canLogin: ((harness: string) => boolean) | undefined,
41
+ ): string | undefined {
42
+ if (typeof named === "string" && named.length > 0) {
43
+ if (!loaded.includes(named)) return undefined;
44
+ return canLogin === undefined || canLogin(named) ? named : undefined;
45
+ }
46
+ const able = loaded.filter((name) => canLogin?.(name) ?? false);
47
+ return able.length === 1 ? able[0] : undefined;
48
+ }
49
+
50
+ /**
51
+ * The bot whose login runs `agent`'s own login: `default` first, then the
52
+ * others by name. Undefined when no bot would log in to that agent.
53
+ */
54
+ export function loginBotFor(
55
+ agent: string,
56
+ bots: Readonly<Record<string, unknown>>,
57
+ loaded: readonly string[],
58
+ canLogin: ((harness: string) => boolean) | undefined,
59
+ ): string | undefined {
60
+ return Object.keys(bots)
61
+ .sort((a, b) => (a === "default" ? -1 : b === "default" ? 1 : a.localeCompare(b)))
62
+ .find((name) => {
63
+ const entry = bots[name];
64
+ return loginHarness(isRecord(entry) ? entry.harness : undefined, loaded, canLogin) === agent;
65
+ });
66
+ }
67
+
68
+ /** True when a loaded plugin declares the login step of `harness`. */
69
+ function stepCanLogin(
70
+ stepLoaded: ((use: string) => boolean) | undefined,
71
+ ): ((harness: string) => boolean) | undefined {
72
+ return stepLoaded === undefined ? undefined : (harness) => stepLoaded(`${harness}/login`);
73
+ }
74
+
75
+ /** The one line a failed login gives. */
76
+ function failed(message: string): PluginStepResult {
77
+ return { result: "failed", data: { message } };
78
+ }
79
+
80
+ /** Runs `<agent>/login`, then writes the model it returns into the bot's settings. */
81
+ export async function runLogin(ctx: StepContext, _params: unknown): Promise<PluginStepResult> {
82
+ const object = ctx.object;
83
+ if (object === undefined || object.type !== BOT_TYPE) {
84
+ return failed("the login needs a bot");
85
+ }
86
+ const harness = loginHarness(object.data.harness, ctx.harnesses, stepCanLogin(ctx.stepLoaded));
87
+ if (harness === undefined) {
88
+ return failed(
89
+ "no agent of this bot has a login here; set the bot's agent, or log in with the agent yourself",
90
+ );
91
+ }
92
+ if (ctx.runStep === undefined) {
93
+ return failed("this host cannot run a login");
94
+ }
95
+ let login: PluginStepResult;
96
+ try {
97
+ login = await ctx.runStep(`${harness}/login`, { bot: object.id }, {
98
+ runId: ctx.runId,
99
+ object: ctx.object,
100
+ cwd: ctx.cwd,
101
+ signal: ctx.signal,
102
+ access: ctx.access,
103
+ flow: ctx.flow,
104
+ trigger: ctx.trigger,
105
+ });
106
+ } catch (error) {
107
+ return failed(messageOf(error));
108
+ }
109
+ if (login.result !== "done") {
110
+ const message = login.data?.message;
111
+ return failed(
112
+ typeof message === "string" && message.length > 0 ? message : `the ${harness} login did not finish`,
113
+ );
114
+ }
115
+ const model = login.data?.model;
116
+ if (typeof model !== "string" || model.length === 0) {
117
+ return failed(`the ${harness} login returned no model`);
118
+ }
119
+ try {
120
+ await updateBotsFile(ctx.home, (bots) => {
121
+ const current = bots[object.id];
122
+ const raw: Record<string, unknown> = isRecord(current) ? current : {};
123
+ // A bot that names no agent now uses the one that logged in; otherwise
124
+ // the model would belong to an agent its chats do not use.
125
+ const named = typeof raw.harness === "string" && raw.harness.length > 0;
126
+ const next = {
127
+ ...bots,
128
+ [object.id]: { ...raw, model, ...(named ? {} : { harness }) } as JsonValue,
129
+ };
130
+ validateBots(next);
131
+ return next;
132
+ });
133
+ } catch (error) {
134
+ return failed(messageOf(error));
135
+ }
136
+ return { result: "done", data: { agent: harness, model } };
137
+ }
138
+
139
+ /** The flow a person's login starts: the step, then the matching end. */
140
+ export const loginFlow = defineFlow({
141
+ name: "bot:login",
142
+ entry: "login",
143
+ steps: [
144
+ {
145
+ id: "login",
146
+ kind: "plugin",
147
+ params: { use: LOGIN_STEP, params: {} },
148
+ replay: "unsafe",
149
+ next: { done: "done", failed: "failed", interrupted: "failed" },
150
+ },
151
+ { id: "done", kind: "end", params: { status: "done" }, replay: "safe" },
152
+ { id: "failed", kind: "end", params: { status: "failed" }, replay: "safe" },
153
+ ],
154
+ });
155
+
156
+ /**
157
+ * The action on a bot that starts the login flow. It sends one event; the
158
+ * plugin's rule starts `bot:login` on the bot the event names.
159
+ */
160
+ export const loginAction: ActionTypeDefinition = {
161
+ name: "login",
162
+ on: BOT_TYPE,
163
+ // A bot with no model has nothing to do before logging in; after a login,
164
+ // chatting is what a person most likely wants.
165
+ rank: (state) => (state.model === null || state.model === undefined ? -1 : 0),
166
+ when: (state, env) =>
167
+ state.removed !== true &&
168
+ loginHarness(
169
+ state.harness,
170
+ env.harnesses ?? [],
171
+ env.stepLoaded === undefined ? undefined : (harness) => env.stepLoaded?.(`${harness}/login`) === true,
172
+ ) !== undefined,
173
+ async why(object, env) {
174
+ if (object.data.removed === true) return `bot ${object.id} is no longer in the settings`;
175
+ if ((env.harnesses ?? []).length === 0) return `bot ${object.id}: no agent is loaded to log in with`;
176
+ return undefined;
177
+ },
178
+ async run(ctx) {
179
+ if (ctx.emit === undefined) {
180
+ throw new BotError("this host cannot start a login");
181
+ }
182
+ const active = await ctx.runLookup?.active(`${BOT_TYPE}:${ctx.object.id}`);
183
+ if (active?.some((run) => run.flow === "bot:login") === true) {
184
+ return "a login is already waiting";
185
+ }
186
+ const harness =
187
+ loginHarness(
188
+ ctx.object.data.harness,
189
+ ctx.harnesses,
190
+ ctx.stepLoaded === undefined
191
+ ? undefined
192
+ : (name) => ctx.stepLoaded?.(`${name}/login`) === true,
193
+ ) ?? (ctx.harnesses.length === 1 ? ctx.harnesses[0] : undefined);
194
+ if (harness === undefined) {
195
+ throw new BotError("this bot names no agent to log in with");
196
+ }
197
+ await ctx.emit({
198
+ source: LOGIN_SOURCE,
199
+ type: LOGIN_EVENT,
200
+ key: randomUUID(),
201
+ object: `${BOT_TYPE}:${ctx.object.id}`,
202
+ summary: `login ${harness}`,
203
+ });
204
+ return "logging in";
205
+ },
206
+ };
207
+
208
+ /** The bots whose agent can log in and is not signed in. */
209
+ export async function loginItems(ctx: StandingContext): Promise<readonly StandingItem[]> {
210
+ const loaded = ctx.harnesses ?? ctx.loaded;
211
+ const canLogin = stepCanLogin(ctx.stepLoaded);
212
+ const items: StandingItem[] = [];
213
+ for (const [name, settings] of Object.entries(readBots(ctx.home, ctx.settings))) {
214
+ const harness = loginHarness(settings.harness, loaded, canLogin);
215
+ if (harness === undefined) continue;
216
+ const active = await ctx.runLookup?.active(`${BOT_TYPE}:${name}`);
217
+ if (active?.some((run) => run.flow === "bot:login") === true) continue;
218
+ if ((await ctx.signedIn?.(harness)) !== false) continue;
219
+ items.push({
220
+ id: `login:${name}`,
221
+ prompt: `bot "${name}" is not logged in to a model`,
222
+ object: { type: BOT_TYPE, id: name },
223
+ });
224
+ }
225
+ return items;
226
+ }
@@ -15,7 +15,7 @@ import {
15
15
  type JsonValue,
16
16
  type ObjectStore,
17
17
  } from "@operad-io/engine";
18
- import { BotError, accessFor, readBots, resolveBot, type McpServerSettings } from "./bot.ts";
18
+ import { BotError, readBots, resolveBot, type McpServerSettings } from "./bot.ts";
19
19
  import { baseEnvironment, probeServer } from "./mcp-client.ts";
20
20
  import {
21
21
  commandLine,
@@ -76,7 +76,7 @@ export async function proposeMcp(
76
76
  const pinned = packageOfCommand(registration.command, registration.args);
77
77
  const resolved = resolveBot(home, bot, written);
78
78
  // The bot's access profile applies to starting the server, as it does to any command of the bot.
79
- const verdict = match(accessFor(home, written), {
79
+ const verdict = match(resolved.access, {
80
80
  tool: "bash",
81
81
  input: { command: commandLine(registration.command, registration.args) },
82
82
  cwd: resolved.cwd,