pi-famulus 0.2.1 → 0.2.2-beta.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.
@@ -0,0 +1,130 @@
1
+ /**
2
+ * TUI widgets for intercom message cards.
3
+ *
4
+ * Upstream baseline: pi-famulus @ 98183fb, plugin/pi — verbatim port of
5
+ * the plugin's ChatText/ChatCard renderers and text-measurement helpers.
6
+ */
7
+
8
+ /** Rough display width: CJK ideographs and wide chars count as 2. */
9
+ export function stringWidth(s: string): number {
10
+ let w = 0;
11
+ for (const ch of s) {
12
+ const cp = ch.codePointAt(0) ?? 0;
13
+ w += cp >= 0x2e80 ? 2 : 1;
14
+ }
15
+ return w;
16
+ }
17
+
18
+ /** Word-wrap one line, treating ANSI SGR sequences as zero-width. */
19
+ export function wrapAnsiLine(line: string, width: number): string[] {
20
+ if (stringWidth(line.replace(/\x1b\[[0-9;]*m/g, "")) <= width) return [line];
21
+ const tokens = line.match(/(\x1b\[[0-9;]*m|\s+|[^\s\x1b]+)/g) ?? [line];
22
+ const lines: string[] = [];
23
+ let cur = "";
24
+ let curWidth = 0;
25
+ const push = () => {
26
+ lines.push(cur.trimEnd());
27
+ cur = "";
28
+ curWidth = 0;
29
+ };
30
+ for (const token of tokens) {
31
+ if (token.startsWith("\x1b")) {
32
+ cur += token;
33
+ continue;
34
+ }
35
+ if (/^\s+$/.test(token)) {
36
+ if (cur && curWidth + 1 <= width) {
37
+ cur += " ";
38
+ curWidth += 1;
39
+ }
40
+ continue;
41
+ }
42
+ let piece = token;
43
+ let pieceWidth = stringWidth(piece);
44
+ if (curWidth > 0 && curWidth + pieceWidth > width) push();
45
+ while (pieceWidth > width) {
46
+ let cut = 0;
47
+ let cutWidth = 0;
48
+ for (const ch of piece) {
49
+ const w = stringWidth(ch);
50
+ if (cutWidth + w > width) break;
51
+ cutWidth += w;
52
+ cut += ch.length;
53
+ }
54
+ cur += piece.slice(0, cut);
55
+ push();
56
+ piece = piece.slice(cut);
57
+ pieceWidth = stringWidth(piece);
58
+ }
59
+ cur += piece;
60
+ curWidth += pieceWidth;
61
+ }
62
+ if (cur.trimEnd()) push();
63
+ return lines.length ? lines : [""];
64
+ }
65
+
66
+ /** Local wall-clock `YYYY-mm-dd HH:ss`. */
67
+ export function formatTimestamp(d: Date): string {
68
+ const p = (n: number) => String(n).padStart(2, "0");
69
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
70
+ }
71
+
72
+ /** Minimal Text component satisfying pi's Component contract; no pi-tui dependency. */
73
+ export class ChatText {
74
+ private text: string;
75
+ private paddingX: number;
76
+
77
+ constructor(text: string, paddingX = 1) {
78
+ this.text = text;
79
+ this.paddingX = paddingX;
80
+ }
81
+
82
+ invalidate(): void {}
83
+
84
+ render(width: number): string[] {
85
+ const padding = Math.min(this.paddingX, Math.max(0, Math.floor((width - 1) / 2)));
86
+ const pad = " ".repeat(padding);
87
+ const contentWidth = Math.max(1, width - padding * 2);
88
+ const out: string[] = [];
89
+ for (const line of this.text.split("\n")) {
90
+ for (const wrapped of wrapAnsiLine(line, contentWidth)) {
91
+ out.push(pad + wrapped);
92
+ }
93
+ }
94
+ return out;
95
+ }
96
+ }
97
+
98
+ /** Boxed card with a full-width background, matching pi's custom message look. */
99
+ export class ChatCard {
100
+ private header: string;
101
+ private body: string;
102
+ private bg: (text: string) => string;
103
+
104
+ constructor(header: string, body: string, bg: (text: string) => string) {
105
+ this.header = header;
106
+ this.body = body;
107
+ this.bg = bg;
108
+ }
109
+
110
+ invalidate(): void {}
111
+
112
+ render(width: number): string[] {
113
+ const px = 1;
114
+ const contentWidth = Math.max(1, width - px * 2);
115
+ const out: string[] = [this.bg(" ".repeat(width))];
116
+ const padLine = (s: string) => {
117
+ const visible = stringWidth(s.replace(/\x1b\[[0-9;]*m/g, ""));
118
+ return this.bg(" ".repeat(px) + s + " ".repeat(Math.max(0, width - px - visible)));
119
+ };
120
+ for (const line of `${this.header}\n${this.body}`.split("\n")) {
121
+ for (const wrapped of wrapAnsiLine(line, contentWidth)) {
122
+ out.push(padLine(wrapped));
123
+ }
124
+ }
125
+ out.push(this.bg(" ".repeat(width)));
126
+ // One transparent line below the card as extra bottom margin.
127
+ out.push("");
128
+ return out;
129
+ }
130
+ }
@@ -18,10 +18,11 @@ import { famulusPaths } from "./config";
18
18
  import { realClock, type Clock, type ClockTimer } from "./clock";
19
19
 
20
20
  const MAX_FRAME_BYTES = 4 * 1024 * 1024; // 4 MiB (§3.3)
21
- const EXTENSION_VERSION = "0.2.1";
21
+ const EXTENSION_VERSION = "0.2.2-beta.1";
22
22
  export { EXTENSION_VERSION };
23
- // 5: speaks per-kind agent admission and queued acquire.
24
- const PROTOCOL = 6;
23
+ // 6: hosted subagents. 7: the extension's messaging bridge (`intercom`
24
+ // request plus `intercom`/`intercom_reset` events).
25
+ const PROTOCOL = 7;
25
26
  const HELLO_TIMEOUT_MS = 5000;
26
27
  const RECONNECT_HELLO_TIMEOUT_MS = 25_000;
27
28
  const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
@@ -108,7 +109,14 @@ export interface MonitorOutputRecord {
108
109
 
109
110
  /** Server-pushed event (§3.3). Fields beyond `event` depend on the event kind. */
110
111
  export interface ManagerEvent {
111
- event: "task_started" | "output" | "task_exited" | "session_rebound" | string;
112
+ event:
113
+ | "task_started"
114
+ | "output"
115
+ | "task_exited"
116
+ | "session_rebound"
117
+ | "intercom"
118
+ | "intercom_reset"
119
+ | string;
112
120
  task_id?: string;
113
121
  kind?: string;
114
122
  command?: string;
@@ -126,6 +134,8 @@ export interface ManagerEvent {
126
134
  ts?: number;
127
135
  /** Set on task_started when the daemon recorded who asked for the task. */
128
136
  origin?: { via: string; child_id?: string; run_id?: string };
137
+ /** An intercom bridge frame (deliver/receipt/idle_notice) for this session. */
138
+ frame?: Record<string, unknown>;
129
139
  }
130
140
 
131
141
  export class ManagerError extends Error {
@@ -167,6 +177,17 @@ export interface ManagerStatusResponse {
167
177
  sessions: SessionInfo[];
168
178
  generation?: number;
169
179
  last_upgrade?: LastUpgrade | null;
180
+ /** The messaging bridge's relay link; absent from older managers. */
181
+ messaging?: MessagingStatus;
182
+ }
183
+
184
+ export interface MessagingStatus {
185
+ /** `connected`, `disconnected`, `local_only`, or `unavailable` (bridge not running). */
186
+ state: string;
187
+ /** `messaging.name`, or the hostname when it is unset. */
188
+ name: string;
189
+ /** Why the bridge is not running. */
190
+ error?: string;
170
191
  }
171
192
 
172
193
  export interface SessionInfo {
@@ -608,6 +629,19 @@ export class ManagerClient {
608
629
  });
609
630
  }
610
631
 
632
+ /** The extension's messaging bridge: one intercom client-protocol op
633
+ * (register/send/list/receipt/…). Protocol 7+; rejected by older managers. */
634
+ async intercom(op: Record<string, unknown>): Promise<Record<string, unknown>> {
635
+ if (this.protocolLevel_ < 7) {
636
+ throw new ManagerError(
637
+ "E_VERSION",
638
+ "this pi-famulus daemon does not serve cross-session messaging (protocol " +
639
+ `${this.protocolLevel_}; need 7). Restart pi so it starts the current daemon.`,
640
+ );
641
+ }
642
+ return this.request({ type: "intercom", op });
643
+ }
644
+
611
645
  /** Daemon status, including optional in-place upgrade metadata. */
612
646
  async status(): Promise<ManagerStatusResponse> {
613
647
  const res = await this.request({ type: "status" });
@@ -617,6 +651,9 @@ export class ManagerClient {
617
651
  ...(res.last_upgrade && typeof res.last_upgrade === "object"
618
652
  ? { last_upgrade: res.last_upgrade as LastUpgrade }
619
653
  : {}),
654
+ ...(res.messaging && typeof res.messaging === "object"
655
+ ? { messaging: res.messaging as MessagingStatus }
656
+ : {}),
620
657
  };
621
658
  }
622
659
 
@@ -29,6 +29,7 @@ const REGISTRATIONS = new Set<PropertyKey>([
29
29
  "registerShortcut",
30
30
  "registerFlag",
31
31
  "registerMessageRenderer",
32
+ "registerEntryRenderer",
32
33
  "registerProvider",
33
34
  ]);
34
35
 
@@ -51,8 +52,13 @@ export function createPiBinding(): PiBinding {
51
52
  let current: ExtensionAPI | null = null;
52
53
  let live = false;
53
54
 
54
- const call = (pi: ExtensionAPI, method: PropertyKey, args: unknown[]): unknown =>
55
- (Reflect.get(pi, method) as (...a: unknown[]) => unknown).apply(pi, args);
55
+ const call = (pi: ExtensionAPI, method: PropertyKey, args: unknown[]): unknown => {
56
+ const fn = Reflect.get(pi, method) as unknown;
57
+ // A host surface may not implement every registration kind (hosted
58
+ // child fakes, older pi); skipping beats crashing the replay.
59
+ if (typeof fn !== "function") return undefined;
60
+ return (fn as (...a: unknown[]) => unknown).apply(pi, args);
61
+ };
56
62
 
57
63
  const api = new Proxy({} as ExtensionAPI, {
58
64
  get(_target, key) {
@@ -37,7 +37,7 @@ interface HostingView {
37
37
  export function createHostedSessionFn(deps: HostedSessionDeps): CreateSessionFn {
38
38
  return async (req) => {
39
39
  const client = deps.getClient();
40
- if (!client || !client.isAvailable()) {
40
+ if (!client || !(await client.ensureAvailable())) {
41
41
  throw new Error("pi-famulus daemon is not connected; a subagent needs it to run pi --mode rpc.");
42
42
  }
43
43
  client.requireHostedProtocol();
@@ -1,12 +1,16 @@
1
1
  /**
2
- * /famulus — which pi-famulus binary this session uses and which versions run.
2
+ * /famulus — which pi-famulus binary this session uses, which versions run,
3
+ * whether messaging reaches its relay, and the settings pages.
3
4
  */
4
5
  import { execFile } from "node:child_process";
5
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
- import type { ManagerClient } from "../manager-client";
6
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
+ import type { ManagerClient, MessagingStatus } from "../manager-client";
8
+ import { SETTINGS_SECTIONS, listTheme, readConfigText, sectionPage, writeConfigText } from "./famulus-settings";
9
+ import { loadPiTui, truncateToWidth } from "./pi-tui-load";
7
10
 
8
11
  export interface FamulusCommandDeps {
9
12
  extensionVersion: string;
13
+ configPath: string;
10
14
  managerPath: string | null;
11
15
  /** Where the binary was looked for, shown when none was found. */
12
16
  describeSearch: () => string;
@@ -17,11 +21,28 @@ export interface FamulusCommandDeps {
17
21
 
18
22
  export interface FamulusInfo {
19
23
  extensionVersion: string;
24
+ configPath: string;
20
25
  managerPath: string | null;
21
26
  searched: string;
22
27
  binaryVersion: string | null;
23
28
  daemon: { version: string; pid: number } | null;
24
29
  daemonError: string;
30
+ /** Null when the manager is not connected or did not report it. */
31
+ messaging: MessagingStatus | null;
32
+ }
33
+
34
+ const RELAY_STATES: Record<string, string> = {
35
+ connected: "connected",
36
+ disconnected: "disconnected",
37
+ local_only: "local-only",
38
+ };
39
+
40
+ export function formatMessaging(info: FamulusInfo): string {
41
+ const m = info.messaging;
42
+ if (!m) return info.daemon ? "not reported by this manager" : "unknown (manager not connected)";
43
+ const state = RELAY_STATES[m.state];
44
+ if (!state) return `unavailable${m.error ? ` (${m.error})` : ""}`;
45
+ return m.name ? `${state} · name ${m.name}` : state;
25
46
  }
26
47
 
27
48
  export function formatFamulusInfo(info: FamulusInfo): string {
@@ -35,6 +56,8 @@ export function formatFamulusInfo(info: FamulusInfo): string {
35
56
  `pi-famulus extension ${info.extensionVersion}`,
36
57
  `CLI binary: ${binary}`,
37
58
  `Manager: ${manager}`,
59
+ `Messaging: ${formatMessaging(info)}`,
60
+ `Config: ${info.configPath}`,
38
61
  ].join("\n");
39
62
  }
40
63
 
@@ -48,24 +71,136 @@ export function readBinaryVersion(path: string): Promise<string | null> {
48
71
  });
49
72
  }
50
73
 
74
+ const STATUS_TIMEOUT_MS = 2000;
75
+
76
+ async function readMessaging(client: ManagerClient): Promise<MessagingStatus | null> {
77
+ let timer: ReturnType<typeof setTimeout> | undefined;
78
+ const timeout = new Promise<null>((resolve) => {
79
+ timer = setTimeout(() => resolve(null), STATUS_TIMEOUT_MS);
80
+ });
81
+ try {
82
+ const status = client.status().then((s) => s.messaging ?? null, () => null);
83
+ return await Promise.race([status, timeout]);
84
+ } finally {
85
+ clearTimeout(timer);
86
+ }
87
+ }
88
+
51
89
  export async function collectFamulusInfo(deps: FamulusCommandDeps): Promise<FamulusInfo> {
52
90
  const client = deps.getClient();
53
91
  const connected = client?.isAvailable() ?? false;
54
92
  return {
55
93
  extensionVersion: deps.extensionVersion,
94
+ configPath: deps.configPath,
56
95
  managerPath: deps.managerPath,
57
96
  searched: deps.managerPath ? "" : deps.describeSearch(),
58
97
  binaryVersion: deps.managerPath ? await (deps.binaryVersion ?? readBinaryVersion)(deps.managerPath) : null,
59
98
  daemon: connected ? client?.managerInfo() ?? null : null,
60
99
  daemonError: connected ? "" : client?.lastError() ?? "",
100
+ messaging: connected && client ? await readMessaging(client) : null,
61
101
  };
62
102
  }
63
103
 
104
+ type OverviewChoice = "edit-raw" | "reload" | undefined;
105
+
106
+ /** Status first, then one row per settings section and the two actions. */
107
+ function showOverview(ctx: ExtensionCommandContext, info: FamulusInfo, configPath: string): Promise<OverviewChoice> {
108
+ const piTui = loadPiTui();
109
+ if (!piTui) {
110
+ ctx.ui.notify(formatFamulusInfo(info), "info");
111
+ return Promise.resolve(undefined);
112
+ }
113
+ return ctx.ui.custom<OverviewChoice>((tui, theme, _kb, done) => {
114
+ let notice = "";
115
+ const deps = {
116
+ tui: piTui,
117
+ theme,
118
+ configPath,
119
+ requestRender: () => tui.requestRender(),
120
+ notice: (text: string, error = false) => {
121
+ notice = theme.fg(error ? "error" : "success", text);
122
+ },
123
+ };
124
+ const items = [
125
+ ...SETTINGS_SECTIONS.map((section) => ({
126
+ id: `section:${section.id}`,
127
+ label: section.label,
128
+ description: `${section.specs.length} settings · ${section.applies}`,
129
+ currentValue: "›",
130
+ submenu: (_current: string, close: (value?: string) => void) => sectionPage(deps, section, () => close()),
131
+ })),
132
+ {
133
+ id: "edit-raw",
134
+ label: "Edit config.json",
135
+ description: "The whole file in the editor, for webhook endpoints and anything not listed",
136
+ currentValue: "",
137
+ values: [""],
138
+ },
139
+ { id: "reload", label: "Reload extension", description: "Apply extension settings now", currentValue: "", values: [""] },
140
+ ];
141
+ const list = new piTui.SettingsList(
142
+ items,
143
+ 10,
144
+ listTheme(theme),
145
+ (id) => {
146
+ if (id === "edit-raw" || id === "reload") done(id);
147
+ },
148
+ () => done(undefined),
149
+ );
150
+ return {
151
+ render(width: number) {
152
+ const status = formatFamulusInfo(info).split("\n");
153
+ const lines = [theme.fg("accent", status[0]), ...status.slice(1).map((line) => {
154
+ const at = line.indexOf(": ");
155
+ return ` ${theme.fg("dim", line.slice(0, at + 1).padEnd(12))}${line.slice(at + 2)}`;
156
+ }), "", ...list.render(width)];
157
+ if (notice) lines.push("", notice);
158
+ return lines.map((line) => truncateToWidth(line, width));
159
+ },
160
+ invalidate: () => list.invalidate(),
161
+ handleInput(data: string) {
162
+ notice = "";
163
+ list.handleInput(data);
164
+ tui.requestRender();
165
+ },
166
+ };
167
+ });
168
+ }
169
+
64
170
  export function registerFamulusCommand(pi: ExtensionAPI, deps: FamulusCommandDeps): void {
65
171
  pi.registerCommand("famulus", {
66
- description: "Show the pi-famulus binary path and the manager and extension versions",
172
+ description: "Show pi-famulus status and manage its configuration",
67
173
  handler: async (_args, ctx) => {
68
- ctx.ui.notify(formatFamulusInfo(await collectFamulusInfo(deps)), "info");
174
+ if (!ctx.hasUI) {
175
+ ctx.ui.notify(formatFamulusInfo(await collectFamulusInfo(deps)), "info");
176
+ return;
177
+ }
178
+ while (true) {
179
+ const action = await showOverview(ctx, await collectFamulusInfo(deps), deps.configPath);
180
+ if (action === "reload") {
181
+ await ctx.reload();
182
+ return;
183
+ }
184
+ if (action !== "edit-raw") return;
185
+ let current: string;
186
+ try {
187
+ current = readConfigText(deps.configPath);
188
+ } catch (error) {
189
+ ctx.ui.notify(`Cannot read ${deps.configPath}: ${(error as Error).message}`, "error");
190
+ continue;
191
+ }
192
+ const edited = await ctx.ui.editor(`Edit ${deps.configPath}`, current);
193
+ if (edited === undefined) continue;
194
+ try {
195
+ writeConfigText(deps.configPath, edited);
196
+ ctx.ui.notify(
197
+ `Saved ${deps.configPath}. Reload the extension for extension settings; restart the manager daemon for messaging settings.`,
198
+ "info",
199
+ );
200
+ } catch (error) {
201
+ ctx.ui.notify(`Configuration was not saved: ${(error as Error).message}`, "error");
202
+ }
203
+ }
69
204
  },
70
205
  });
71
206
  }