@faberon/chat 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sevren
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # Faberon Chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The chat interface of [Faberon](https://github.com/sevren-ai/faberon), an autonomous ML research harness.
4
+
5
+ Faberon Chat is a [Pi](https://github.com/earendil-works/pi-coding-agent) extension for operating Faberon campaigns from a chat session: draft a research plan conversationally, submit it, watch proposals and judgments stream in live, inject ideas mid-run, and cancel campaigns. Every write goes through the brain's HTTP API; the chat interface proposes, the brain decides.
6
+
7
+ The brain ships separately as [faberon](https://pypi.org/project/faberon/) on PyPI and provides the `faberon` CLI, which covers the same operations from a shell.
8
+
9
+ ## Install
10
+
11
+ Requires a running Faberon brain and the Pi CLI.
12
+
13
+ ```bash
14
+ pi install npm:@faberon/chat
15
+ ```
16
+
17
+ ## Documentation
18
+
19
+ Install guides, quickstart, runbooks, and design docs live in the [repo](https://github.com/sevren-ai/faberon).
20
+
21
+ ## Status
22
+
23
+ Early beta: expect rough edges and breaking changes.
24
+
25
+ ## License
26
+
27
+ MIT
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `faberon-chat`: start the Pi chat interface (@earendil-works/pi-coding-agent)
4
+ * without going through npx. This exists because `npx pi` can silently
5
+ * resolve to the unrelated `pi` package on npm (it prints digits of pi) when
6
+ * no local `pi` binary is installed. Forwards every argument unchanged.
7
+ *
8
+ * This file must stay plain CommonJS JavaScript: it is the package's "bin"
9
+ * entry and runs before any build step exists.
10
+ */
11
+ "use strict";
12
+
13
+ const { spawnSync } = require("node:child_process");
14
+ const fs = require("node:fs");
15
+ const path = require("node:path");
16
+
17
+ function fail(lines) {
18
+ for (const line of lines) console.error(`faberon-chat: ${line}`);
19
+ process.exit(1);
20
+ }
21
+
22
+ let piPkgDir;
23
+ try {
24
+ const piPkgJson = require.resolve(
25
+ "@earendil-works/pi-coding-agent/package.json",
26
+ { paths: [__dirname] },
27
+ );
28
+ piPkgDir = path.dirname(piPkgJson);
29
+ } catch {
30
+ fail([
31
+ "the Pi CLI (@earendil-works/pi-coding-agent) is not installed next to this shim.",
32
+ "Fix: cd packages/chat && npm ci --legacy-peer-deps",
33
+ ]);
34
+ }
35
+
36
+ // Load the extension from this repo when invoked through a git checkout's
37
+ // npm bin shims (`npm --prefix packages/chat ...`). From an installed Pi
38
+ // package, Pi already loads the extension listed in package.json, so `-e`
39
+ // would load it twice.
40
+ const extension = path.resolve(__dirname, "..", "src", "index.ts");
41
+ const fromCheckout = fs.existsSync(
42
+ path.resolve(__dirname, "..", "..", "..", "AGENTS.md"),
43
+ );
44
+ const passthrough = fromCheckout ? ["-e", extension] : [];
45
+
46
+ let entry;
47
+ try {
48
+ const pkg = require(path.join(piPkgDir, "package.json"));
49
+ const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin && pkg.bin.pi;
50
+ if (!bin) throw new Error("no bin.pi entry");
51
+ entry = path.join(piPkgDir, bin);
52
+ } catch (err) {
53
+ fail([`could not locate the Pi CLI entry point: ${err.message}`]);
54
+ }
55
+
56
+ const result = spawnSync(
57
+ process.execPath,
58
+ [entry, ...passthrough, ...process.argv.slice(2)],
59
+ { stdio: "inherit" },
60
+ );
61
+
62
+ if (result.error) {
63
+ fail([`failed to launch the Pi CLI: ${result.error.message}`]);
64
+ }
65
+ if (result.signal) {
66
+ process.kill(process.pid, result.signal);
67
+ }
68
+ process.exit(result.status ?? 1);
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@faberon/chat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Faberon Chat: a Pi extension for drafting plans and operating campaigns",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/sevren-ai/faberon.git",
9
+ "directory": "packages/chat"
10
+ },
11
+ "homepage": "https://github.com/sevren-ai/faberon",
12
+ "bugs": "https://github.com/sevren-ai/faberon/issues",
13
+ "type": "module",
14
+ "bin": {
15
+ "faberon-chat": "bin/faberon-chat.js"
16
+ },
17
+ "files": [
18
+ "bin",
19
+ "src"
20
+ ],
21
+ "keywords": [
22
+ "pi-package"
23
+ ],
24
+ "engines": {
25
+ "node": ">=22.19"
26
+ },
27
+ "pi": {
28
+ "extensions": [
29
+ "./src/index.ts"
30
+ ]
31
+ },
32
+ "scripts": {
33
+ "typecheck": "tsc --noEmit",
34
+ "format": "prettier --write .",
35
+ "format:check": "prettier --check .",
36
+ "lint": "tsc --noEmit",
37
+ "test": "vitest run"
38
+ },
39
+ "peerDependencies": {
40
+ "@earendil-works/pi-coding-agent": "^1.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "@earendil-works/pi-coding-agent": "1.0.0",
44
+ "@types/node": "^22.19.0",
45
+ "prettier": "^3.5.0",
46
+ "typebox": "^1.3.27",
47
+ "typescript": "^5.9.0",
48
+ "vitest": "^4.0.0"
49
+ }
50
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Thin typed HTTP client for the v0 API.
3
+ *
4
+ * Reads the base URL and bearer token from the shared config file written
5
+ * by `faberon init`.
6
+ */
7
+
8
+ import { configPath, readConfigFile } from "./config.js";
9
+ import type {
10
+ ApiErrorBody,
11
+ CampaignCreate,
12
+ CampaignCreated,
13
+ CampaignInfo,
14
+ FaberonEvent,
15
+ StatusResponse,
16
+ } from "./types.js";
17
+
18
+ export interface ClientConfig {
19
+ baseUrl: string;
20
+ token: string;
21
+ }
22
+
23
+ /** Resolve the client config from the Faberon config file. */
24
+ export function loadClientConfig(
25
+ env: NodeJS.ProcessEnv = process.env,
26
+ ): ClientConfig {
27
+ const file = readConfigFile(configPath(env));
28
+ const token = file.api_token;
29
+ if (!token) {
30
+ throw new Error(
31
+ `No API token in ${configPath(env)}. Faberon Chat talks to the API ` +
32
+ "over an authenticated channel; run `faberon init` to set one up.",
33
+ );
34
+ }
35
+ // api_url wins; otherwise derive from host and port, which the file must
36
+ // carry (defaults exist only to write the file, never to read it).
37
+ const derived =
38
+ file.host !== undefined && file.port !== undefined
39
+ ? `http://${file.host}:${file.port}`
40
+ : undefined;
41
+ const baseUrl = (file.api_url ?? derived)?.replace(/\/+$/, "");
42
+ if (!baseUrl) {
43
+ throw new Error(
44
+ `No api_url (or host/port) in ${configPath(env)}: run \`faberon init\`.`,
45
+ );
46
+ }
47
+ return { baseUrl, token };
48
+ }
49
+
50
+ export class ApiError extends Error {
51
+ constructor(
52
+ public readonly status: number,
53
+ message: string,
54
+ ) {
55
+ super(message);
56
+ this.name = "ApiError";
57
+ }
58
+ }
59
+
60
+ export class FaberonClient {
61
+ constructor(private readonly config: ClientConfig) {}
62
+
63
+ static fromConfig(env: NodeJS.ProcessEnv = process.env): FaberonClient {
64
+ return new FaberonClient(loadClientConfig(env));
65
+ }
66
+
67
+ private async request<T>(path: string, init?: RequestInit): Promise<T> {
68
+ const url = `${this.config.baseUrl}${path}`;
69
+ let res: Response;
70
+ try {
71
+ res = await fetch(url, {
72
+ ...init,
73
+ headers: {
74
+ Authorization: `Bearer ${this.config.token}`,
75
+ ...init?.headers,
76
+ },
77
+ });
78
+ } catch (err) {
79
+ const cause = err instanceof Error ? err.message : String(err);
80
+ throw new Error(
81
+ `Cannot reach Faberon at ${this.config.baseUrl}: ${cause}. ` +
82
+ "Is `faberon serve` running?",
83
+ );
84
+ }
85
+ if (!res.ok) {
86
+ let detail = res.statusText;
87
+ try {
88
+ const body = (await res.json()) as ApiErrorBody;
89
+ if (body.detail) detail = body.detail;
90
+ } catch {
91
+ // Non-JSON error body; keep the status text.
92
+ }
93
+ throw new ApiError(res.status, detail);
94
+ }
95
+ return (await res.json()) as T;
96
+ }
97
+
98
+ /** GET /v0/campaigns: all campaigns with live status, oldest first. */
99
+ listCampaigns(): Promise<CampaignInfo[]> {
100
+ return this.request<CampaignInfo[]>("/v0/campaigns");
101
+ }
102
+
103
+ /** GET /v0/campaigns/{id}: one campaign's record and live status. */
104
+ getCampaign(campaignId: string): Promise<CampaignInfo> {
105
+ return this.request<CampaignInfo>(`/v0/campaigns/${campaignId}`);
106
+ }
107
+
108
+ /** POST /v0/campaigns: submit a new campaign from a research plan. */
109
+ createCampaign(body: CampaignCreate): Promise<CampaignCreated> {
110
+ return this.request<CampaignCreated>("/v0/campaigns", {
111
+ method: "POST",
112
+ headers: { "Content-Type": "application/json" },
113
+ body: JSON.stringify(body),
114
+ });
115
+ }
116
+
117
+ /** POST /v0/campaigns/{id}/cancel: request cancellation of an active campaign. */
118
+ cancelCampaign(campaignId: string, reason: string): Promise<StatusResponse> {
119
+ return this.request<StatusResponse>(`/v0/campaigns/${campaignId}/cancel`, {
120
+ method: "POST",
121
+ headers: { "Content-Type": "application/json" },
122
+ body: JSON.stringify({ reason }),
123
+ });
124
+ }
125
+
126
+ /** POST /v0/campaigns/{id}/ideas: inject an advisory idea into an active campaign. */
127
+ injectIdea(
128
+ campaignId: string,
129
+ text: string,
130
+ reason: string,
131
+ ): Promise<StatusResponse> {
132
+ return this.request<StatusResponse>(`/v0/campaigns/${campaignId}/ideas`, {
133
+ method: "POST",
134
+ headers: { "Content-Type": "application/json" },
135
+ body: JSON.stringify({ text, reason }),
136
+ });
137
+ }
138
+
139
+ /** POST /v0/campaigns/{id}/resume: resume a pending campaign from its last checkpoint. */
140
+ resumeCampaign(campaignId: string): Promise<StatusResponse> {
141
+ return this.request<StatusResponse>(`/v0/campaigns/${campaignId}/resume`, {
142
+ method: "POST",
143
+ });
144
+ }
145
+
146
+ /** GET /v0/campaigns/{id}/events.jsonl: bounded snapshot of the campaign's ledger. */
147
+ async getEvents(campaignId: string, after = 0): Promise<FaberonEvent[]> {
148
+ const text = await this.requestText(
149
+ `/v0/campaigns/${campaignId}/events.jsonl?after=${after}`,
150
+ );
151
+ return text
152
+ .split("\n")
153
+ .filter((line) => line.length > 0)
154
+ .map((line) => JSON.parse(line) as FaberonEvent);
155
+ }
156
+
157
+ private async requestText(path: string, init?: RequestInit): Promise<string> {
158
+ const url = `${this.config.baseUrl}${path}`;
159
+ let res: Response;
160
+ try {
161
+ res = await fetch(url, {
162
+ ...init,
163
+ headers: {
164
+ Authorization: `Bearer ${this.config.token}`,
165
+ ...init?.headers,
166
+ },
167
+ });
168
+ } catch (err) {
169
+ const cause = err instanceof Error ? err.message : String(err);
170
+ throw new Error(
171
+ `Cannot reach Faberon at ${this.config.baseUrl}: ${cause}. ` +
172
+ "Is `faberon serve` running?",
173
+ );
174
+ }
175
+ if (!res.ok) {
176
+ let detail = res.statusText;
177
+ try {
178
+ const body = (await res.json()) as ApiErrorBody;
179
+ if (body.detail) detail = body.detail;
180
+ } catch {
181
+ // Non-JSON error body; keep the status text.
182
+ }
183
+ throw new ApiError(res.status, detail);
184
+ }
185
+ return res.text();
186
+ }
187
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Reader for the shared Faberon config file (`faberon init` writes it).
3
+ *
4
+ * The clients only need the top-level scalars.
5
+ * The `[env]` section is server-side only.
6
+ */
7
+
8
+ import { readFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { join } from "node:path";
11
+
12
+ /** The config file path: `$FABERON_CONFIG` or the default location. */
13
+ export function configPath(env: NodeJS.ProcessEnv = process.env): string {
14
+ return (
15
+ env.FABERON_CONFIG ?? join(homedir(), ".config", "faberon", "config.toml")
16
+ );
17
+ }
18
+
19
+ /** Top-level scalar entries from the config file; empty when absent. */
20
+ export function readConfigFile(path: string): Record<string, string> {
21
+ let text: string;
22
+ try {
23
+ text = readFileSync(path, "utf8");
24
+ } catch {
25
+ return {};
26
+ }
27
+ const values: Record<string, string> = {};
28
+ for (const line of text.split("\n")) {
29
+ const trimmed = line.trim();
30
+ if (trimmed.startsWith("[")) break;
31
+ const match =
32
+ /^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|(\d+))\s*(?:#.*)?$/.exec(
33
+ trimmed,
34
+ );
35
+ const [, key, str, int] = match ?? [];
36
+ const value = str ?? int;
37
+ if (key !== undefined && value !== undefined) values[key] = value;
38
+ }
39
+ return values;
40
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * v0 API wire shapes, mirroring the Pydantic models. They are hand-maintained for now
3
+ * but will be automatically generated later through an OpenAPI spec later.
4
+ */
5
+
6
+ export interface ResearchPlan {
7
+ goal: string;
8
+ command: string;
9
+ target_file: string;
10
+ metric: string;
11
+ baseline: number;
12
+ budget_gpu_hours: number;
13
+ max_experiments: number;
14
+ max_concurrency: number;
15
+ walltime: number;
16
+ stop_conditions: string[];
17
+ }
18
+
19
+ export type CampaignStatus = "active" | "ended" | "died";
20
+
21
+ export interface Campaign {
22
+ campaign_id: string;
23
+ workflow_id: string;
24
+ plan: ResearchPlan;
25
+ repo_path: string;
26
+ poll_interval_seconds: number;
27
+ created_at: string;
28
+ }
29
+
30
+ export interface CampaignInfo {
31
+ campaign: Campaign;
32
+ status: CampaignStatus;
33
+ stop_reason?: string | null;
34
+ }
35
+
36
+ /** POST /v0/campaigns body. */
37
+ export interface CampaignCreate {
38
+ campaign_id: string;
39
+ plan: ResearchPlan;
40
+ repo_path: string;
41
+ poll_interval_seconds: number;
42
+ }
43
+
44
+ /** POST /v0/campaigns result: new campaign ID and DBOS workflow ID. */
45
+ export interface CampaignCreated {
46
+ campaign_id: string;
47
+ workflow_id: string;
48
+ }
49
+
50
+ /** Status body returned by the write endpoints. */
51
+ export interface StatusResponse {
52
+ campaign_id: string;
53
+ status: string;
54
+ }
55
+
56
+ /** Ledger event record, one line of the campaign's event log. */
57
+ export interface FaberonEvent {
58
+ seq: number | null;
59
+ ts: string;
60
+ campaign_id: string;
61
+ actor: "agent" | "human";
62
+ type: string;
63
+ reason: string;
64
+ payload: Record<string, unknown>;
65
+ }
66
+
67
+ /** FastAPI error body shape. */
68
+ export interface ApiErrorBody {
69
+ detail?: string;
70
+ }
package/src/index.ts ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Faberon Chat: a Pi extension for drafting plans and steering campaigns.
3
+ *
4
+ * The extension exposes each v0 API operation as a Pi tool (for the
5
+ * model to call in conversation) plus a matching slash command (for the human
6
+ * to invoke directly). `faberon serve` stays CLI-only: it starts the server
7
+ * the chat interface talks to.
8
+ */
9
+
10
+ import { readFile } from "node:fs/promises";
11
+ import { randomUUID } from "node:crypto";
12
+ import { resolve } from "node:path";
13
+ import type {
14
+ ExtensionAPI,
15
+ ExtensionCommandContext,
16
+ } from "@earendil-works/pi-coding-agent";
17
+ import { FaberonClient } from "./api/client.js";
18
+ import type { ResearchPlan } from "./api/types.js";
19
+ import { campaignEventsTool, formatEvents } from "./tools/campaign-events.js";
20
+ import { cancelCampaignTool } from "./tools/cancel-campaign.js";
21
+ import { createCampaignTool, formatCreated } from "./tools/create-campaign.js";
22
+ import { injectIdeaTool } from "./tools/inject-idea.js";
23
+ import { formatCampaigns, listCampaignsTool } from "./tools/list-campaigns.js";
24
+ import { resumeCampaignTool } from "./tools/resume-campaign.js";
25
+ import { formatCampaign, showCampaignTool } from "./tools/show-campaign.js";
26
+
27
+ /** Notify with the outcome of an operation the human invoked. */
28
+ async function notify(
29
+ ctx: ExtensionCommandContext,
30
+ operation: Promise<string>,
31
+ ): Promise<void> {
32
+ try {
33
+ ctx.ui.notify(await operation, "info");
34
+ } catch (err) {
35
+ const message = err instanceof Error ? err.message : String(err);
36
+ ctx.ui.notify(message, "error");
37
+ }
38
+ }
39
+
40
+ /** Prompt until the human enters a non-empty value. */
41
+ async function promptNonEmpty(
42
+ ctx: ExtensionCommandContext,
43
+ title: string,
44
+ placeholder?: string,
45
+ ): Promise<string | undefined> {
46
+ for (;;) {
47
+ const value = await ctx.ui.input(title, placeholder);
48
+ if (value === undefined) {
49
+ return undefined;
50
+ }
51
+ const trimmed = value.trim();
52
+ if (trimmed.length > 0) {
53
+ return trimmed;
54
+ }
55
+ ctx.ui.notify(`${title} must not be empty`, "warning");
56
+ }
57
+ }
58
+
59
+ export default function faberonChat(pi: ExtensionAPI): void {
60
+ const client = FaberonClient.fromConfig();
61
+
62
+ pi.registerTool(listCampaignsTool(client));
63
+ pi.registerTool(showCampaignTool(client));
64
+ pi.registerTool(campaignEventsTool(client));
65
+ pi.registerTool(createCampaignTool(client));
66
+ pi.registerTool(cancelCampaignTool(client));
67
+ pi.registerTool(injectIdeaTool(client));
68
+ pi.registerTool(resumeCampaignTool(client));
69
+
70
+ pi.registerCommand("faberon-list", {
71
+ description: "List Faberon campaigns with live status",
72
+ handler: async (_args, ctx) => {
73
+ await notify(
74
+ ctx,
75
+ client.listCampaigns().then((infos) => formatCampaigns(infos)),
76
+ );
77
+ },
78
+ });
79
+
80
+ pi.registerCommand("faberon-show", {
81
+ description: "Show one Faberon campaign's status and plan",
82
+ getArgumentCompletions: () => null,
83
+ handler: async (args, ctx) => {
84
+ const campaignId =
85
+ args.trim() || (await promptNonEmpty(ctx, "Campaign ID"));
86
+ if (!campaignId) return;
87
+ await notify(
88
+ ctx,
89
+ client.getCampaign(campaignId).then((info) => formatCampaign(info)),
90
+ );
91
+ },
92
+ });
93
+
94
+ pi.registerCommand("faberon-events", {
95
+ description: "Print a Faberon campaign's ledger. --verbose adds payloads.",
96
+ getArgumentCompletions: () => null,
97
+ handler: async (args, ctx) => {
98
+ const tokens = args.split(/\s+/).filter((t) => t.length > 0);
99
+ const verbose = tokens.includes("--verbose") || tokens.includes("-v");
100
+ const positional = tokens.filter((t) => !t.startsWith("-"));
101
+ const campaignId =
102
+ positional[0] ?? (await promptNonEmpty(ctx, "Campaign ID"));
103
+ if (!campaignId) return;
104
+ await notify(
105
+ ctx,
106
+ client
107
+ .getEvents(campaignId)
108
+ .then((events) => formatEvents(events, verbose)),
109
+ );
110
+ },
111
+ });
112
+
113
+ pi.registerCommand("faberon-create", {
114
+ description:
115
+ "Submit a new Faberon campaign: /faberon-create <plan.json> [repo-path]",
116
+ getArgumentCompletions: () => null,
117
+ handler: async (args, ctx) => {
118
+ const tokens = args.split(/\s+/).filter((t) => t.length > 0);
119
+ const planPath =
120
+ tokens[0] ?? (await promptNonEmpty(ctx, "Plan JSON file"));
121
+ if (!planPath) return;
122
+ const repoPath = tokens[1] ?? ctx.cwd;
123
+ await notify(ctx, createFromFile(ctx, client, planPath, repoPath));
124
+ },
125
+ });
126
+
127
+ pi.registerCommand("faberon-cancel", {
128
+ description: "Request cancellation of an active Faberon campaign",
129
+ getArgumentCompletions: () => null,
130
+ handler: async (args, ctx) => {
131
+ const tokens = args.split(/\s+/).filter((t) => t.length > 0);
132
+ const campaignId =
133
+ tokens[0] ?? (await promptNonEmpty(ctx, "Campaign ID"));
134
+ if (!campaignId) return;
135
+ const reason =
136
+ tokens.slice(1).join(" ").trim() ||
137
+ (await promptNonEmpty(ctx, "Reason to cancel"));
138
+ if (!reason) return;
139
+ await notify(
140
+ ctx,
141
+ client.cancelCampaign(campaignId, reason).then((r) => r.status),
142
+ );
143
+ },
144
+ });
145
+
146
+ pi.registerCommand("faberon-idea", {
147
+ description:
148
+ "Inject an advisory idea into an active Faberon campaign: " +
149
+ "/faberon-idea <campaign-id> <idea text>",
150
+ getArgumentCompletions: () => null,
151
+ handler: async (args, ctx) => {
152
+ const tokens = args.split(/\s+/).filter((t) => t.length > 0);
153
+ const campaignId =
154
+ tokens[0] ?? (await promptNonEmpty(ctx, "Campaign ID"));
155
+ if (!campaignId) return;
156
+ const text =
157
+ tokens.slice(1).join(" ").trim() || (await promptNonEmpty(ctx, "Idea"));
158
+ if (!text) return;
159
+ const reason = await promptNonEmpty(ctx, "Reason for the idea");
160
+ if (!reason) return;
161
+ await notify(
162
+ ctx,
163
+ client.injectIdea(campaignId, text, reason).then((r) => r.status),
164
+ );
165
+ },
166
+ });
167
+
168
+ pi.registerCommand("faberon-resume", {
169
+ description: "Resume a pending Faberon campaign from its last checkpoint",
170
+ getArgumentCompletions: () => null,
171
+ handler: async (args, ctx) => {
172
+ const campaignId =
173
+ args.trim() || (await promptNonEmpty(ctx, "Campaign ID"));
174
+ if (!campaignId) return;
175
+ await notify(
176
+ ctx,
177
+ client.resumeCampaign(campaignId).then((r) => r.status),
178
+ );
179
+ },
180
+ });
181
+ }
182
+
183
+ /** Read a plan JSON file and submit it through the create path. */
184
+ async function createFromFile(
185
+ ctx: ExtensionCommandContext,
186
+ client: FaberonClient,
187
+ planPath: string,
188
+ repoPath: string,
189
+ ): Promise<string> {
190
+ const raw = await readFile(resolve(ctx.cwd, planPath), "utf8");
191
+ const plan = JSON.parse(raw) as ResearchPlan;
192
+ const created = await client.createCampaign({
193
+ campaign_id: randomUUID(),
194
+ plan,
195
+ repo_path: resolve(ctx.cwd, repoPath),
196
+ poll_interval_seconds: 30,
197
+ });
198
+ return formatCreated(created);
199
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * `faberon_campaign_events` tool: read a campaign's ledger.
3
+ */
4
+
5
+ import { Type } from "typebox";
6
+ import { defineTool } from "@earendil-works/pi-coding-agent";
7
+ import type { FaberonClient } from "../api/client.js";
8
+ import type { FaberonEvent } from "../api/types.js";
9
+
10
+ /**
11
+ * Render one event as a human-readable line
12
+ */
13
+ export function formatEvent(event: FaberonEvent, verbose = false): string {
14
+ const ts = event.ts.slice(0, 19).replace("T", " ") + "Z";
15
+ let line = `${ts} ${event.actor.padEnd(5)} ${event.type.padEnd(28)} ${event.reason}`;
16
+ if (verbose && Object.keys(event.payload).length > 0) {
17
+ line += `\n${" ".repeat(20)} ${JSON.stringify(event.payload)}`;
18
+ }
19
+ return line;
20
+ }
21
+
22
+ /**
23
+ * Render a bounded ledger read for both the tool result and the slash command.
24
+ */
25
+ export function formatEvents(events: FaberonEvent[], verbose = false): string {
26
+ if (events.length === 0) {
27
+ return "No events yet.";
28
+ }
29
+ return events.map((event) => formatEvent(event, verbose)).join("\n");
30
+ }
31
+
32
+ export function campaignEventsTool(client: FaberonClient) {
33
+ return defineTool({
34
+ name: "faberon_campaign_events",
35
+ label: "Read a Faberon campaign's ledger",
36
+ description:
37
+ "Read the event ledger of one Faberon campaign: proposals, " +
38
+ "completions, judgments, budget burn. Pass `after` with the last seen " +
39
+ "sequence number to page in only newer events.",
40
+ promptSnippet: "Read a Faberon campaign's event ledger",
41
+ parameters: Type.Object({
42
+ campaign_id: Type.String({
43
+ description: "Campaign UUID.",
44
+ }),
45
+ after: Type.Optional(
46
+ Type.Integer({
47
+ description: "Only events after this ledger sequence number.",
48
+ default: 0,
49
+ minimum: 0,
50
+ }),
51
+ ),
52
+ verbose: Type.Optional(
53
+ Type.Boolean({
54
+ description: "Include event payloads.",
55
+ default: false,
56
+ }),
57
+ ),
58
+ }),
59
+ annotations: { readOnlyHint: true },
60
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
61
+ const events = await client.getEvents(
62
+ params.campaign_id,
63
+ params.after ?? 0,
64
+ );
65
+ return {
66
+ content: [{ type: "text", text: formatEvents(events, params.verbose) }],
67
+ details: { events },
68
+ };
69
+ },
70
+ });
71
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `faberon_cancel_campaign` tool: request cancellation of an active campaign.
3
+ */
4
+
5
+ import { Type } from "typebox";
6
+ import { defineTool } from "@earendil-works/pi-coding-agent";
7
+ import type { FaberonClient } from "../api/client.js";
8
+
9
+ export function cancelCampaignTool(client: FaberonClient) {
10
+ return defineTool({
11
+ name: "faberon_cancel_campaign",
12
+ label: "Cancel a Faberon campaign",
13
+ description:
14
+ "Request cancellation of an active Faberon campaign. " +
15
+ "Requires a human-given reason.",
16
+ promptSnippet: "Cancel an active Faberon campaign",
17
+ parameters: Type.Object({
18
+ campaign_id: Type.String({
19
+ description: "Campaign UUID.",
20
+ }),
21
+ reason: Type.String({
22
+ description: "Why the campaign is cancelled. Recorded in the ledger.",
23
+ minLength: 1,
24
+ }),
25
+ }),
26
+ annotations: { destructiveHint: true, idempotentHint: true },
27
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
28
+ const result = await client.cancelCampaign(
29
+ params.campaign_id,
30
+ params.reason,
31
+ );
32
+ return {
33
+ content: [{ type: "text", text: result.status }],
34
+ details: result,
35
+ };
36
+ },
37
+ });
38
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * `faberon_create_campaign` tool: submit a new campaign from a research plan.
3
+ */
4
+
5
+ import { randomUUID } from "node:crypto";
6
+ import { Type } from "typebox";
7
+ import { defineTool } from "@earendil-works/pi-coding-agent";
8
+ import type { FaberonClient } from "../api/client.js";
9
+ import type { CampaignCreated } from "../api/types.js";
10
+
11
+ /**
12
+ * Render a created campaign for both the tool result and the slash command.
13
+ */
14
+ export function formatCreated(created: CampaignCreated): string {
15
+ return `campaign: ${created.campaign_id}\nworkflow: ${created.workflow_id}`;
16
+ }
17
+
18
+ const planSchema = Type.Object({
19
+ goal: Type.String({
20
+ description: "What the campaign tries to achieve.",
21
+ minLength: 1,
22
+ }),
23
+ command: Type.String({
24
+ description: "Training command each experiment runs.",
25
+ minLength: 1,
26
+ }),
27
+ target_file: Type.String({
28
+ description:
29
+ "Path of the Python file the proposer edits, relative to the repo root, " +
30
+ "e.g. 'train.py'.",
31
+ minLength: 1,
32
+ }),
33
+ metric: Type.String({
34
+ description:
35
+ "Name of the metric under optimization, e.g. 'val_bpb'. The job log must " +
36
+ "print a line naming it followed by a float, e.g. 'val_bpb: 1.10'.",
37
+ minLength: 1,
38
+ }),
39
+ baseline: Type.Number({
40
+ description: "Metric value of the starting commit.",
41
+ }),
42
+ budget_gpu_hours: Type.Number({
43
+ description: "Total GPU-hour budget.",
44
+ exclusiveMinimum: 0,
45
+ }),
46
+ max_experiments: Type.Integer({
47
+ description: "Maximum number of experiments.",
48
+ minimum: 1,
49
+ }),
50
+ max_concurrency: Type.Optional(
51
+ Type.Integer({
52
+ description: "Maximum parallel jobs.",
53
+ default: 1,
54
+ minimum: 1,
55
+ }),
56
+ ),
57
+ walltime: Type.Integer({
58
+ description: "Per-job walltime in minutes.",
59
+ exclusiveMinimum: 0,
60
+ }),
61
+ stop_conditions: Type.Array(Type.String(), {
62
+ description: "Conditions under which the campaign stops early.",
63
+ minItems: 1,
64
+ }),
65
+ });
66
+
67
+ export function createCampaignTool(client: FaberonClient) {
68
+ return defineTool({
69
+ name: "faberon_create_campaign",
70
+ label: "Create a Faberon campaign",
71
+ description:
72
+ "Submit a new Faberon campaign from a research plan. The plan is " +
73
+ "validated upon submission.",
74
+ promptSnippet: "Submit a new Faberon campaign from a research plan",
75
+ parameters: Type.Object({
76
+ plan: planSchema,
77
+ repo_path: Type.String({
78
+ description: "Path to the target repo on the shared filesystem.",
79
+ minLength: 1,
80
+ }),
81
+ poll_interval_seconds: Type.Optional(
82
+ Type.Number({
83
+ description: "Poll interval in seconds.",
84
+ default: 30,
85
+ exclusiveMinimum: 0,
86
+ }),
87
+ ),
88
+ }),
89
+ annotations: {},
90
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
91
+ const created = await client.createCampaign({
92
+ campaign_id: randomUUID(),
93
+ plan: { max_concurrency: 1, ...params.plan },
94
+ repo_path: params.repo_path,
95
+ poll_interval_seconds: params.poll_interval_seconds ?? 30,
96
+ });
97
+ return {
98
+ content: [{ type: "text", text: formatCreated(created) }],
99
+ details: created,
100
+ };
101
+ },
102
+ });
103
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * `faberon_inject_idea` tool: inject an advisory idea into an active campaign.
3
+ */
4
+
5
+ import { Type } from "typebox";
6
+ import { defineTool } from "@earendil-works/pi-coding-agent";
7
+ import type { FaberonClient } from "../api/client.js";
8
+
9
+ export function injectIdeaTool(client: FaberonClient) {
10
+ return defineTool({
11
+ name: "faberon_inject_idea",
12
+ label: "Inject an idea into a Faberon campaign",
13
+ description:
14
+ "Inject a human idea into an active Faberon campaign. The idea lands " +
15
+ "in the ledger as idea.injected and the proposer weighs it at its next " +
16
+ "decision boundary. Advisory only: nothing forces execution.",
17
+ promptSnippet: "Inject an advisory idea into an active Faberon campaign",
18
+ parameters: Type.Object({
19
+ campaign_id: Type.String({
20
+ description: "Campaign UUID.",
21
+ }),
22
+ text: Type.String({
23
+ description: "The idea itself, read by the proposer.",
24
+ minLength: 1,
25
+ }),
26
+ reason: Type.String({
27
+ description: "Why the idea is injected. Recorded in the ledger.",
28
+ minLength: 1,
29
+ }),
30
+ }),
31
+ annotations: { idempotentHint: false },
32
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
33
+ const result = await client.injectIdea(
34
+ params.campaign_id,
35
+ params.text,
36
+ params.reason,
37
+ );
38
+ return {
39
+ content: [{ type: "text", text: result.status }],
40
+ details: result,
41
+ };
42
+ },
43
+ });
44
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * `faberon_list_campaigns` tool: list campaigns with live status.
3
+ */
4
+
5
+ import { Type } from "typebox";
6
+ import { defineTool } from "@earendil-works/pi-coding-agent";
7
+ import type { FaberonClient } from "../api/client.js";
8
+ import type { CampaignInfo } from "../api/types.js";
9
+
10
+ /**
11
+ * Render campaign rows for both the tool result and the slash command.
12
+ */
13
+ export function formatCampaigns(infos: CampaignInfo[]): string {
14
+ if (infos.length === 0) {
15
+ return "No campaigns yet.";
16
+ }
17
+ const pad = (s: string, n: number) => s.padEnd(n, " ");
18
+ const header = `${pad("ID", 36)} ${pad("CREATED", 16)} ${pad("STATUS", 6)} ${pad("METRIC", 12)} REPO`;
19
+ const lines = infos.map((info) => {
20
+ const c = info.campaign;
21
+ const created = c.created_at.slice(0, 16).replace("T", " ");
22
+ return `${c.campaign_id} ${created} ${pad(info.status, 6)} ${pad(c.plan.metric, 12)} ${c.repo_path}`;
23
+ });
24
+ return [header, ...lines].join("\n");
25
+ }
26
+
27
+ export function listCampaignsTool(client: FaberonClient) {
28
+ return defineTool({
29
+ name: "faberon_list_campaigns",
30
+ label: "List Faberon campaigns",
31
+ description:
32
+ "List all Faberon research campaigns with their live status (active, " +
33
+ "ended, died), creation time, repo path, and metric. Oldest first.",
34
+ promptSnippet: "List Faberon campaigns and their live status",
35
+ parameters: Type.Object({}),
36
+ annotations: { readOnlyHint: true },
37
+ async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
38
+ const infos = await client.listCampaigns();
39
+ return {
40
+ content: [{ type: "text", text: formatCampaigns(infos) }],
41
+ details: { campaigns: infos },
42
+ };
43
+ },
44
+ });
45
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `faberon_resume_campaign` tool: resume a pending campaign.
3
+ */
4
+
5
+ import { Type } from "typebox";
6
+ import { defineTool } from "@earendil-works/pi-coding-agent";
7
+ import type { FaberonClient } from "../api/client.js";
8
+
9
+ export function resumeCampaignTool(client: FaberonClient) {
10
+ return defineTool({
11
+ name: "faberon_resume_campaign",
12
+ label: "Resume a Faberon campaign",
13
+ description:
14
+ "Resume a pending Faberon campaign's workflow from its last " +
15
+ "checkpoint, for example after Faberon was restarted with recovery " +
16
+ "disabled.",
17
+ promptSnippet: "Resume a pending Faberon campaign",
18
+ parameters: Type.Object({
19
+ campaign_id: Type.String({
20
+ description: "Campaign UUID.",
21
+ }),
22
+ }),
23
+ annotations: { idempotentHint: true },
24
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
25
+ const result = await client.resumeCampaign(params.campaign_id);
26
+ return {
27
+ content: [{ type: "text", text: result.status }],
28
+ details: result,
29
+ };
30
+ },
31
+ });
32
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * `faberon_show_campaign` tool: show one campaign's status and plan.
3
+ */
4
+
5
+ import { Type } from "typebox";
6
+ import { defineTool } from "@earendil-works/pi-coding-agent";
7
+ import type { FaberonClient } from "../api/client.js";
8
+ import type { CampaignInfo } from "../api/types.js";
9
+
10
+ /**
11
+ * Render one campaign for both the tool result and the slash command.
12
+ */
13
+ export function formatCampaign(info: CampaignInfo): string {
14
+ const campaign = info.campaign;
15
+ const created = campaign.created_at.slice(0, 16).replace("T", " ");
16
+ const lines = [
17
+ `campaign: ${campaign.campaign_id}`,
18
+ `created: ${created}`,
19
+ `repo: ${campaign.repo_path}`,
20
+ `goal: ${campaign.plan.goal}`,
21
+ `metric: ${campaign.plan.metric}`,
22
+ `budget: ${campaign.plan.budget_gpu_hours} gpu-hours`,
23
+ `max exp: ${campaign.plan.max_experiments}`,
24
+ `status: ${info.status}`,
25
+ ];
26
+ if (info.stop_reason != null) {
27
+ lines.push(`reason: ${info.stop_reason}`);
28
+ }
29
+ return lines.join("\n");
30
+ }
31
+
32
+ export function showCampaignTool(client: FaberonClient) {
33
+ return defineTool({
34
+ name: "faberon_show_campaign",
35
+ label: "Show one Faberon campaign",
36
+ description:
37
+ "Show one Faberon campaign's live status and research plan: goal, " +
38
+ "metric, budget, experiment limit, and stop reason when it has ended.",
39
+ promptSnippet: "Show one Faberon campaign's status and plan",
40
+ parameters: Type.Object({
41
+ campaign_id: Type.String({
42
+ description: "Campaign UUID.",
43
+ }),
44
+ }),
45
+ annotations: { readOnlyHint: true },
46
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
47
+ const info = await client.getCampaign(params.campaign_id);
48
+ return {
49
+ content: [{ type: "text", text: formatCampaign(info) }],
50
+ details: { campaign: info },
51
+ };
52
+ },
53
+ });
54
+ }