@wkqco33/pi-remote-control 0.2.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wkqco33/pi-remote-control",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Remote control extension for pi coding agent: stream live sessions, steer/followUp prompts, and approve tool calls from a web relay server.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -48,7 +48,9 @@ function runThinking(host: BuiltinHost, level: string): CommandResult {
48
48
  return success(applied === next ? `Thinking level set to ${applied}.` : `Thinking level set to ${applied}; this model does not support ${next}.`);
49
49
  }
50
50
 
51
- export async function runBuiltinCommand(host: BuiltinHost, name: BuiltinCommandName, args: string): Promise<CommandResult> {
51
+ export type SessionCommandName = Exclude<BuiltinCommandName, "update" | "reload">;
52
+
53
+ export async function runBuiltinCommand(host: BuiltinHost, name: SessionCommandName, args: string): Promise<CommandResult> {
52
54
  try {
53
55
  if (name === "model") return await runModel(host, args);
54
56
  if (name === "thinking") return runThinking(host, args);
@@ -0,0 +1,69 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { DEFAULT_REMOTE_CONFIG, type RemoteControlConfig } from "../config.js";
3
+ import { Maintenance, type MaintenanceHost } from "./maintenance.js";
4
+
5
+ function setup(overrides: Partial<RemoteControlConfig> = {}, code = 0) {
6
+ const calls: string[] = [];
7
+ const state = { idle: true, now: 1_000 };
8
+ const host: MaintenanceHost = {
9
+ isIdle: () => state.idle,
10
+ now: () => state.now,
11
+ runPiUpdate: async (args) => {
12
+ calls.push(args.join(" "));
13
+ return { code, output: "log line" };
14
+ },
15
+ reload: () => void calls.push("reload"),
16
+ };
17
+ const maintenance = new Maintenance({ ...DEFAULT_REMOTE_CONFIG, remoteUpdate: "all", ...overrides }, host);
18
+ return { maintenance, calls, state };
19
+ }
20
+
21
+ describe("Maintenance", () => {
22
+ it("updates every extension only after confirmation", async () => {
23
+ const { maintenance, calls } = setup();
24
+ expect((await maintenance.update("a", "")).message).toContain("/update confirm");
25
+ expect(calls).toEqual([]);
26
+ expect((await maintenance.update("a", "confirm")).ok).toBe(true);
27
+ expect(calls).toEqual(["update --extensions --no-approve"]);
28
+ expect((await maintenance.update("a", "confirm")).ok).toBe(false);
29
+ });
30
+
31
+ it("limits the target to this package when asked or configured", async () => {
32
+ for (const [remoteUpdate, input] of [["all", "self"], ["self", ""]] as const) {
33
+ const { maintenance, calls } = setup({ remoteUpdate });
34
+ await maintenance.update("a", input);
35
+ await maintenance.update("a", `${input} confirm`.trim());
36
+ expect(calls).toEqual(["update npm:@wkqco33/pi-remote-control --no-approve"]);
37
+ }
38
+ });
39
+
40
+ it("rejects another client, a changed target, an expired request, and free-form arguments", async () => {
41
+ const { maintenance, calls, state } = setup();
42
+ await maintenance.update("a", "");
43
+ expect((await maintenance.update("b", "confirm")).ok).toBe(false);
44
+ await maintenance.update("a", "self");
45
+ expect((await maintenance.update("a", "confirm")).ok).toBe(false);
46
+ await maintenance.update("a", "");
47
+ state.now += 60_001;
48
+ expect((await maintenance.update("a", "confirm")).ok).toBe(false);
49
+ expect((await maintenance.update("a", "--force confirm")).ok).toBe(false);
50
+ expect(calls).toEqual([]);
51
+ });
52
+
53
+ it("is refused when disabled, restricted, or busy", async () => {
54
+ for (const overrides of [{ remoteUpdate: "off" }, { remoteToolPolicy: "read-only" }, { remoteToolPolicy: "no-tools" }] as const) {
55
+ const { maintenance } = setup(overrides);
56
+ expect((await maintenance.update("a", "")).ok).toBe(false);
57
+ expect(maintenance.prepareReload("").ok).toBe(false);
58
+ }
59
+ const busy = setup();
60
+ busy.state.idle = false;
61
+ expect(busy.maintenance.prepareReload("").ok).toBe(false);
62
+ });
63
+
64
+ it("reports a failed update", async () => {
65
+ const { maintenance } = setup({}, 1);
66
+ await maintenance.update("a", "");
67
+ expect(await maintenance.update("a", "confirm")).toMatchObject({ ok: false });
68
+ });
69
+ });
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Remote `/update` and `/reload`. Both change the code that pi runs, so they are
3
+ * off unless the user's own config enables them.
4
+ */
5
+
6
+ import type { RemoteControlConfig } from "../config.js";
7
+ import type { CommandResult } from "./command-handler.js";
8
+
9
+ export const SELF_PACKAGE_SOURCE = "npm:@wkqco33/pi-remote-control";
10
+ export const CONFIRM_WINDOW_MS = 60_000;
11
+ const MAX_OUTPUT_CHARS = 1_500;
12
+
13
+ export interface UpdateRun {
14
+ readonly code: number;
15
+ readonly output: string;
16
+ }
17
+
18
+ export interface MaintenanceHost {
19
+ isIdle(): boolean;
20
+ now(): number;
21
+ /** Runs the pi CLI with a fixed argument list, without a shell. */
22
+ runPiUpdate(args: readonly string[]): Promise<UpdateRun>;
23
+ reload(): void;
24
+ }
25
+
26
+ interface PendingUpdate {
27
+ readonly clientId: string;
28
+ readonly args: readonly string[];
29
+ readonly expiresAt: number;
30
+ }
31
+
32
+ const success = (message: string): CommandResult => ({ ok: true, message });
33
+ const failure = (message: string): CommandResult => ({ ok: false, message });
34
+
35
+ export function maintenanceRefusal(config: RemoteControlConfig, idle: boolean): string | null {
36
+ if (config.remoteUpdate === "off") {
37
+ return 'Remote updates are disabled. Set "remoteUpdate" to "self" or "all" in your user config on the pi machine.';
38
+ }
39
+ if (config.remoteToolPolicy !== "unrestricted") {
40
+ return `Remote updates are not allowed with the ${config.remoteToolPolicy} tool policy.`;
41
+ }
42
+ if (!idle) return "Wait for the current work to finish, or abort it, first.";
43
+ return null;
44
+ }
45
+
46
+ export class Maintenance {
47
+ private pending?: PendingUpdate;
48
+ private readonly config: RemoteControlConfig;
49
+ private readonly host: MaintenanceHost;
50
+
51
+ constructor(config: RemoteControlConfig, host: MaintenanceHost) {
52
+ this.config = config;
53
+ this.host = host;
54
+ }
55
+
56
+ /** `/update [self] [confirm]`. The first call only describes what would run. */
57
+ async update(clientId: string, input: string): Promise<CommandResult> {
58
+ const refusal = maintenanceRefusal(this.config, this.host.isIdle());
59
+ if (refusal) return failure(refusal);
60
+
61
+ const words = input.split(/\s+/).filter(Boolean);
62
+ const confirmed = words.at(-1) === "confirm";
63
+ const target = (confirmed ? words.slice(0, -1) : words).join(" ");
64
+ if (target !== "" && target !== "self") return failure("Usage: /update [self] [confirm]");
65
+
66
+ const everything = this.config.remoteUpdate === "all" && target === "";
67
+ // --no-approve keeps packages declared by the repository out of the update.
68
+ const args = ["update", ...(everything ? ["--extensions"] : [SELF_PACKAGE_SOURCE]), "--no-approve"];
69
+ const commandLine = `pi ${args.join(" ")}`;
70
+
71
+ if (!confirmed) {
72
+ this.pending = { clientId, args, expiresAt: this.host.now() + CONFIRM_WINDOW_MS };
73
+ const confirm = target ? "/update self confirm" : "/update confirm";
74
+ return success(`This will run \`${commandLine}\` on the pi machine. Send ${confirm} within 60 seconds.`);
75
+ }
76
+
77
+ const pending = this.pending;
78
+ this.pending = undefined;
79
+ if (!pending || pending.clientId !== clientId || pending.expiresAt < this.host.now() || pending.args.join() !== args.join()) {
80
+ return failure("Nothing to confirm. Send the update command again without confirm.");
81
+ }
82
+
83
+ const run = await this.host.runPiUpdate(args);
84
+ const output = run.output.trim().slice(-MAX_OUTPUT_CHARS);
85
+ if (run.code !== 0) return failure(`\`${commandLine}\` failed with exit code ${run.code}.\n${output}`);
86
+ return success(`\`${commandLine}\` finished.\n${output}\nSend /reload to load the updated extensions.`);
87
+ }
88
+
89
+ /** Validates a reload. The caller sends the result first, because reloading drops the connection. */
90
+ prepareReload(input: string): CommandResult {
91
+ const refusal = maintenanceRefusal(this.config, this.host.isIdle());
92
+ if (refusal) return failure(refusal);
93
+ if (input) return failure("Usage: /reload");
94
+ return success("Reloading pi. The session reconnects shortly; auto-approve and pairing start off again.");
95
+ }
96
+
97
+ reload(): void {
98
+ this.host.reload();
99
+ }
100
+ }
@@ -5,6 +5,7 @@ import { buildCommandCatalog, routeSlashInput, THINKING_LEVELS, type BuiltinComm
5
5
  import type { DeliverMode, PromptImage, WireEnvelope } from "../core/protocol.js";
6
6
  import { redactSecrets } from "../core/redact.js";
7
7
  import { runBuiltinCommand, type CommandResult } from "./command-handler.js";
8
+ import { Maintenance } from "./maintenance.js";
8
9
  import type { RemoteHost } from "./remote-bridge.js";
9
10
 
10
11
  export interface PromptRouterOptions {
@@ -18,12 +19,14 @@ export interface PromptRouterOptions {
18
19
  export class PromptRouter {
19
20
  private readonly options: PromptRouterOptions;
20
21
  private builtinRunning = false;
22
+ private readonly maintenance: Maintenance;
21
23
 
22
24
  constructor(options: PromptRouterOptions) {
23
25
  this.options = options;
26
+ this.maintenance = new Maintenance(options.config, options.host);
24
27
  }
25
28
 
26
- async submit(text: string, deliverAs?: DeliverMode, images?: readonly PromptImage[]): Promise<void> {
29
+ async submit(clientId: string, text: string, deliverAs?: DeliverMode, images?: readonly PromptImage[]): Promise<void> {
27
30
  const { host } = this.options;
28
31
  const route = routeSlashInput(text, text.startsWith("/") ? host.listCommands() : []);
29
32
  if (route.kind === "reject") {
@@ -31,7 +34,7 @@ export class PromptRouter {
31
34
  return;
32
35
  }
33
36
  if (route.kind === "builtin") {
34
- await this.runBuiltin(route.name, route.args, Boolean(images?.length));
37
+ await this.runBuiltin(clientId, route.name, route.args, Boolean(images?.length));
35
38
  return;
36
39
  }
37
40
  const validImages = this.acceptImages(images);
@@ -44,7 +47,8 @@ export class PromptRouter {
44
47
 
45
48
  sendCatalog(clientId: string): void {
46
49
  const { host } = this.options;
47
- const commands = buildCommandCatalog(host.listCommands()).map((command) =>
50
+ const maintenance = this.options.config.remoteUpdate !== "off";
51
+ const commands = buildCommandCatalog(host.listCommands(), { maintenance }).map((command) =>
48
52
  command.description ? { ...command, description: redactSecrets(command.description) } : command,
49
53
  );
50
54
  this.options.send({
@@ -56,7 +60,7 @@ export class PromptRouter {
56
60
  });
57
61
  }
58
62
 
59
- private async runBuiltin(name: BuiltinCommandName, args: string, hasImages: boolean): Promise<void> {
63
+ private async runBuiltin(clientId: string, name: BuiltinCommandName, args: string, hasImages: boolean): Promise<void> {
60
64
  if (hasImages) {
61
65
  this.emitResult(name, { ok: false, message: `/${name} does not accept images.` });
62
66
  return;
@@ -65,9 +69,21 @@ export class PromptRouter {
65
69
  this.emitResult(name, { ok: false, message: "Another command is still running." });
66
70
  return;
67
71
  }
72
+ if (name === "reload") {
73
+ const result = this.maintenance.prepareReload(args);
74
+ this.emitResult(name, result);
75
+ if (result.ok) this.maintenance.reload();
76
+ return;
77
+ }
68
78
  this.builtinRunning = true;
69
79
  try {
70
- this.emitResult(name, await runBuiltinCommand(this.options.host, name, args));
80
+ const result =
81
+ name === "update"
82
+ ? await this.maintenance.update(clientId, args)
83
+ : await runBuiltinCommand(this.options.host, name, args);
84
+ this.emitResult(name, result);
85
+ } catch (error) {
86
+ this.emitResult(name, { ok: false, message: `/${name} failed: ${error instanceof Error ? error.message : String(error)}` });
71
87
  } finally {
72
88
  this.builtinRunning = false;
73
89
  this.options.onCommandSettled();
@@ -3,7 +3,7 @@ import { DEFAULT_REMOTE_CONFIG } from "../config.js";
3
3
  import type { WireEnvelope } from "../core/protocol.js";
4
4
  import { RemoteBridge, type RemoteHost, type TransportSink } from "./remote-bridge.js";
5
5
 
6
- function makeHarness(requirePairing = true) {
6
+ function makeHarness(requirePairing = true, remoteUpdate: "off" | "self" | "all" = "off") {
7
7
  const sent: WireEnvelope[] = [];
8
8
  const notices: string[] = [];
9
9
  const prompts: Array<{ text: string; deliverAs?: string; expand?: boolean }> = [];
@@ -37,6 +37,11 @@ function makeHarness(requirePairing = true) {
37
37
  getThinkingLevel: () => "low",
38
38
  setThinkingLevel: (level) => void calls.push(`thinking ${level}`),
39
39
  compact: async (instructions) => void calls.push(`compact ${instructions ?? ""}`),
40
+ runPiUpdate: async (args) => {
41
+ calls.push(`pi ${args.join(" ")}`);
42
+ return { code: 0, output: "updated sk-ant-api03-1234567890abcdef" };
43
+ },
44
+ reload: () => void calls.push("reload"),
40
45
  abort: vi.fn(),
41
46
  notify: (text) => notices.push(text),
42
47
  getHistory: () => [{ role: "user", text: "hi" }],
@@ -45,7 +50,7 @@ function makeHarness(requirePairing = true) {
45
50
  random: () => randSeq[idx++ % randSeq.length] ?? 0,
46
51
  };
47
52
  const bridge = new RemoteBridge({
48
- config: { ...DEFAULT_REMOTE_CONFIG, requirePairing, approvalTimeoutMs: 5000 },
53
+ config: { ...DEFAULT_REMOTE_CONFIG, requirePairing, remoteUpdate, approvalTimeoutMs: 5000 },
49
54
  host,
50
55
  sink,
51
56
  });
@@ -153,6 +158,18 @@ describe("RemoteBridge", () => {
153
158
  expect(JSON.stringify(sent[0])).not.toContain('"remote"');
154
159
  });
155
160
 
161
+ it("runs update and reload from the web only when enabled", async () => {
162
+ for (const remoteUpdate of ["off", "all"] as const) {
163
+ const { bridge, sent, calls, prompts } = makeHarness(false, remoteUpdate);
164
+ for (const text of ["/update", "/update confirm", "/reload"]) {
165
+ await bridge.handleServerMessage({ type: "prompt.send", clientId: "web-1", text });
166
+ }
167
+ expect(calls).toEqual(remoteUpdate === "off" ? [] : ["pi update --extensions --no-approve", "reload"]);
168
+ expect(prompts).toEqual([]);
169
+ expect(JSON.stringify(sent)).not.toContain("1234567890abcdef");
170
+ }
171
+ });
172
+
156
173
  it("coalesces stream deltas and keeps them ahead of later frames", () => {
157
174
  vi.useFakeTimers();
158
175
  try {
@@ -11,9 +11,10 @@ import { redactSecrets } from "../core/redact.js";
11
11
  import type { ApprovalReason } from "../core/tool-policy.js";
12
12
  import type { ConnectionStatus, StatusSnapshot } from "../core/status.js";
13
13
  import type { BuiltinHost } from "./command-handler.js";
14
+ import type { MaintenanceHost } from "./maintenance.js";
14
15
  import { PromptRouter } from "./prompt-router.js";
15
16
 
16
- export interface RemoteHost extends BuiltinHost {
17
+ export interface RemoteHost extends BuiltinHost, MaintenanceHost {
17
18
  readonly sessionId: string;
18
19
  readonly sessionName?: string;
19
20
  readonly host: string;
@@ -183,7 +184,7 @@ export class RemoteBridge {
183
184
  return;
184
185
  case "prompt.send":
185
186
  if (!this.ensureTrusted(msg.clientId)) return;
186
- await this.prompts.submit(msg.text, msg.deliverAs, msg.images);
187
+ await this.prompts.submit(msg.clientId, msg.text, msg.deliverAs, msg.images);
187
188
  return;
188
189
  case "commands.request":
189
190
  if (!this.ensureTrusted(msg.clientId)) return;
@@ -29,6 +29,7 @@ export interface AgentHelloInfo {
29
29
  readonly state: AgentState;
30
30
  readonly requirePairing: boolean;
31
31
  readonly autoApprove?: boolean;
32
+ readonly extensionVersion?: string;
32
33
  }
33
34
 
34
35
  export interface WsClientOptions {
@@ -0,0 +1,41 @@
1
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
+ import { loadExtensionConfig } from "./config-loader.js";
6
+
7
+ describe("loadExtensionConfig", () => {
8
+ let root: string;
9
+ const write = async (path: string, body: object) => {
10
+ await mkdir(dirname(path), { recursive: true });
11
+ await writeFile(path, JSON.stringify(body));
12
+ };
13
+ const load = (projectTrusted: boolean, env: Record<string, string> = {}) =>
14
+ loadExtensionConfig({ cwd: join(root, "repo"), homeDir: join(root, "home"), configDirName: ".pi", projectTrusted, env });
15
+
16
+ beforeEach(async () => {
17
+ root = await mkdtemp(join(tmpdir(), "remote-config-"));
18
+ await write(join(root, "home/.pi/agent/remote-control.json"), { serverUrl: "wss://mine/ws/agent" });
19
+ await write(join(root, "repo/.pi/remote-control.json"), { serverUrl: "wss://theirs/ws/agent", requirePairing: true });
20
+ });
21
+ afterEach(() => rm(root, { recursive: true, force: true }));
22
+
23
+ it("does not apply an untrusted project file", async () => {
24
+ const { config, warnings } = await load(false);
25
+ expect(config).toMatchObject({ serverUrl: "wss://mine/ws/agent", requirePairing: false });
26
+ expect(warnings.join()).toContain("not trusted");
27
+ });
28
+
29
+ it("applies only the tightening values of a trusted project", async () => {
30
+ const { config, warnings } = await load(true);
31
+ expect(config).toMatchObject({ serverUrl: "wss://mine/ws/agent", requirePairing: true });
32
+ expect(warnings.join()).toContain("serverUrl");
33
+ });
34
+
35
+ it("reads only the file named by PI_REMOTE_CONFIG", async () => {
36
+ const path = join(root, "chosen.json");
37
+ await write(path, { serverUrl: "wss://chosen/ws/agent" });
38
+ const { config } = await load(true, { PI_REMOTE_CONFIG: path });
39
+ expect(config).toMatchObject({ serverUrl: "wss://chosen/ws/agent", requirePairing: false });
40
+ });
41
+ });
@@ -0,0 +1,71 @@
1
+ /** Reads the extension configuration files. */
2
+
3
+ import { readFile } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import {
6
+ applyProjectConfig,
7
+ parseRemoteConfig,
8
+ resolveRemoteConfig,
9
+ type ParsedConfigResult,
10
+ type RemoteControlConfig,
11
+ } from "./config.js";
12
+
13
+ export interface ConfigLoadOptions {
14
+ readonly cwd: string;
15
+ readonly homeDir: string;
16
+ /** pi's config directory name, ".pi". */
17
+ readonly configDirName: string;
18
+ readonly projectTrusted: boolean;
19
+ readonly env: Record<string, string | undefined>;
20
+ }
21
+
22
+ export interface LoadedConfig {
23
+ readonly config: RemoteControlConfig;
24
+ readonly warnings: string[];
25
+ }
26
+
27
+ /** Returns null when the file does not exist or cannot be used. */
28
+ async function readConfigFile(path: string, warnings: string[]): Promise<ParsedConfigResult | null> {
29
+ try {
30
+ const parsed = parseRemoteConfig(JSON.parse(await readFile(path, "utf8")) as unknown);
31
+ warnings.push(...parsed.warnings);
32
+ return parsed;
33
+ } catch (error) {
34
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
35
+ warnings.push(`config error (${path}): ${error instanceof Error ? error.message : String(error)}`);
36
+ }
37
+ return null;
38
+ }
39
+ }
40
+
41
+ export async function loadExtensionConfig(options: ConfigLoadOptions): Promise<LoadedConfig> {
42
+ const warnings: string[] = [];
43
+ // PI_REMOTE_CONFIG is chosen by the user, so it replaces both files.
44
+ const override = options.env.PI_REMOTE_CONFIG?.trim();
45
+ const userPath = override || join(options.homeDir, options.configDirName, "agent", "remote-control.json");
46
+ const userFile = await readConfigFile(userPath, warnings);
47
+ const config = resolveRemoteConfig(userFile?.config ?? {}, options.env);
48
+ if (override) return { config, warnings };
49
+
50
+ const projectPath = join(options.cwd, options.configDirName, "remote-control.json");
51
+ if (resolve(projectPath) === resolve(userPath)) return { config, warnings };
52
+ // The project file comes with the repository, which the user may not control.
53
+ const projectWarnings: string[] = [];
54
+ const projectFile = await readConfigFile(projectPath, projectWarnings);
55
+ if (!options.projectTrusted) {
56
+ if (projectFile || projectWarnings.length > 0) {
57
+ warnings.push(`ignored ${projectPath} because the project is not trusted`);
58
+ }
59
+ return { config, warnings };
60
+ }
61
+ warnings.push(...projectWarnings);
62
+ if (!projectFile) return { config, warnings };
63
+
64
+ const applied = applyProjectConfig(config, projectFile.config);
65
+ if (applied.ignored.length > 0) {
66
+ warnings.push(
67
+ `ignored in ${projectPath}: ${applied.ignored.join(", ")} (project config may only tighten security; set these in ${userPath})`,
68
+ );
69
+ }
70
+ return { config: applied.config, warnings };
71
+ }
package/src/config.ts CHANGED
@@ -16,6 +16,8 @@ export interface RemoteControlConfig {
16
16
  readonly remoteToolPolicy: RemoteToolPolicy;
17
17
  readonly remoteToolApproval: RemoteToolApproval;
18
18
  readonly approvalTimeoutMs: number;
19
+ /** Which extensions `/update` may update. Any value but "off" also allows `/reload`. */
20
+ readonly remoteUpdate: "off" | "self" | "all";
19
21
  readonly maxImageBytes: number;
20
22
  readonly maxImages: number;
21
23
  readonly reconnectBaseMs: number;
@@ -32,6 +34,7 @@ export const DEFAULT_REMOTE_CONFIG: RemoteControlConfig = {
32
34
  remoteToolPolicy: "unrestricted",
33
35
  remoteToolApproval: "off",
34
36
  approvalTimeoutMs: 60_000,
37
+ remoteUpdate: "off",
35
38
  maxImageBytes: 8 * 1024 * 1024,
36
39
  maxImages: 4,
37
40
  reconnectBaseMs: 1_000,
@@ -72,6 +75,9 @@ export function parseRemoteConfig(raw: unknown): ParsedConfigResult {
72
75
  if (obj.remoteToolApproval === "off" || obj.remoteToolApproval === "local" || obj.remoteToolApproval === "web") {
73
76
  out.remoteToolApproval = obj.remoteToolApproval;
74
77
  }
78
+ if (obj.remoteUpdate === "off" || obj.remoteUpdate === "self" || obj.remoteUpdate === "all") {
79
+ out.remoteUpdate = obj.remoteUpdate;
80
+ }
75
81
  if (typeof obj.approvalTimeoutMs === "number" && obj.approvalTimeoutMs >= 5_000 && obj.approvalTimeoutMs <= 300_000) {
76
82
  out.approvalTimeoutMs = obj.approvalTimeoutMs;
77
83
  }
@@ -96,6 +102,39 @@ export function resolveRemoteConfig(
96
102
  };
97
103
  }
98
104
 
105
+ const POLICY_STRICTNESS: Record<RemoteToolPolicy, number> = { unrestricted: 0, "read-only": 1, "no-tools": 2 };
106
+ // "local" needs someone at the terminal, so it is stricter than "web".
107
+ const APPROVAL_STRICTNESS: Record<RemoteToolApproval, number> = { off: 0, web: 1, local: 2 };
108
+
109
+ type ProjectRule<Key extends keyof RemoteControlConfig> = (
110
+ value: RemoteControlConfig[Key],
111
+ current: RemoteControlConfig[Key],
112
+ ) => boolean;
113
+
114
+ /** Keys a project may set, and when its value is at least as strict. All other keys belong to the user. */
115
+ const PROJECT_RULES: { readonly [Key in keyof RemoteControlConfig]?: ProjectRule<Key> } = {
116
+ requirePairing: (value, current) => value || !current,
117
+ remoteToolPolicy: (value, current) => POLICY_STRICTNESS[value] >= POLICY_STRICTNESS[current],
118
+ remoteToolApproval: (value, current) => APPROVAL_STRICTNESS[value] >= APPROVAL_STRICTNESS[current],
119
+ approvalTimeoutMs: (value, current) => value <= current,
120
+ pairingTtlMs: (value, current) => value <= current,
121
+ };
122
+
123
+ /** Layers a repository's config over the user's without letting it weaken or redirect anything. */
124
+ export function applyProjectConfig(
125
+ base: RemoteControlConfig,
126
+ project: Partial<RemoteControlConfig>,
127
+ ): { config: RemoteControlConfig; ignored: string[] } {
128
+ const accepted: Record<string, unknown> = {};
129
+ const ignored: string[] = [];
130
+ for (const key of Object.keys(project) as (keyof RemoteControlConfig)[]) {
131
+ const rule = PROJECT_RULES[key] as ((value: unknown, current: unknown) => boolean) | undefined;
132
+ if (rule?.(project[key], base[key])) accepted[key] = project[key];
133
+ else ignored.push(key);
134
+ }
135
+ return { config: { ...base, ...(accepted as Partial<RemoteControlConfig>) }, ignored };
136
+ }
137
+
99
138
  export function expandHomePath(filePath: string, homeDir: string): string {
100
139
  const trimmed = filePath.trim();
101
140
  if (trimmed === "~") return homeDir;
@@ -38,5 +38,6 @@ describe("routeSlashInput", () => {
38
38
  expect(buildCommandCatalog(commands).map((command) => command.name)).toEqual([
39
39
  "compact", "model", "thinking", "review", "skill:verify",
40
40
  ]);
41
+ expect(buildCommandCatalog([], { maintenance: true }).map((command) => command.name)).toContain("update");
41
42
  });
42
43
  });
@@ -9,7 +9,9 @@ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhi
9
9
 
10
10
  export const THINKING_LEVELS: readonly ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
11
11
 
12
- export type BuiltinCommandName = "compact" | "model" | "thinking";
12
+ export type BuiltinCommandName = "compact" | "model" | "thinking" | "update" | "reload";
13
+
14
+ const MAINTENANCE_COMMANDS: readonly BuiltinCommandName[] = ["update", "reload"];
13
15
 
14
16
  export interface CommandInfo {
15
17
  readonly name: string;
@@ -27,6 +29,8 @@ export const BUILTIN_COMMANDS: readonly (CatalogCommand & { readonly name: Built
27
29
  { name: "compact", source: "builtin", description: "Compact the session context [instructions]" },
28
30
  { name: "model", source: "builtin", description: "Show or change the model [provider/id]" },
29
31
  { name: "thinking", source: "builtin", description: "Show or change the thinking level [level]" },
32
+ { name: "update", source: "builtin", description: "Update pi extensions [self]" },
33
+ { name: "reload", source: "builtin", description: "Reload pi extensions, skills, and prompts" },
30
34
  ];
31
35
 
32
36
  export type SlashRoute =
@@ -69,12 +73,13 @@ export function routeSlashInput(text: string, commands: readonly CommandInfo[]):
69
73
  };
70
74
  }
71
75
 
72
- export function buildCommandCatalog(commands: readonly CommandInfo[]): CatalogCommand[] {
76
+ export function buildCommandCatalog(commands: readonly CommandInfo[], options: { maintenance?: boolean } = {}): CatalogCommand[] {
73
77
  const expandable = commands.flatMap((command): CatalogCommand[] => {
74
78
  if (command.source === "extension") return [];
75
79
  // Hide names that routing would reject or handle as a built-in.
76
80
  if (routeSlashInput(`/${command.name}`, commands).kind !== "expand") return [];
77
81
  return [{ name: command.name, source: command.source, ...(command.description ? { description: command.description } : {}) }];
78
82
  });
79
- return [...BUILTIN_COMMANDS, ...expandable];
83
+ const builtins = BUILTIN_COMMANDS.filter((command) => options.maintenance || !MAINTENANCE_COMMANDS.includes(command.name));
84
+ return [...builtins, ...expandable];
80
85
  }
package/src/index.test.ts CHANGED
@@ -19,7 +19,7 @@ describe("remoteControlExtension wiring", () => {
19
19
  } as unknown as ExtensionAPI;
20
20
 
21
21
  await remoteControlExtension(fakePi);
22
- expect(commands).toEqual(["remote"]);
22
+ expect(commands).toEqual(["remote", "remote-reload"]);
23
23
  expect(events).toContain("session_start");
24
24
  expect(events).toContain("session_shutdown");
25
25
  expect(events).toContain("message_update");
package/src/index.ts CHANGED
@@ -3,19 +3,18 @@
3
3
  * Thin adapter binding pi ExtensionAPI events to WsClient + RemoteBridge.
4
4
  */
5
5
 
6
+ import { readFileSync } from "node:fs";
6
7
  import { readFile, stat } from "node:fs/promises";
7
8
  import { homedir, hostname } from "node:os";
8
- import { join } from "node:path";
9
9
  import { CONFIG_DIR_NAME, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
10
10
  import { RemoteBridge, type RemoteHost } from "./client/remote-bridge.js";
11
11
  import { WsClient } from "./client/ws-client.js";
12
12
  import {
13
13
  expandHomePath,
14
- parseRemoteConfig,
15
14
  parseTokenFileContent,
16
- resolveRemoteConfig,
17
15
  type RemoteControlConfig,
18
16
  } from "./config.js";
17
+ import { loadExtensionConfig } from "./config-loader.js";
19
18
  import { buildWorkDigest, parseGitBranch, parseGitNumstat } from "./core/digest.js";
20
19
  import { buildHistorySnapshot, type RawSessionEntry } from "./core/history.js";
21
20
  import { formatFooterLabel, formatStatusReport } from "./core/status.js";
@@ -28,35 +27,19 @@ import {
28
27
  } from "./core/tool-policy.js";
29
28
 
30
29
  const EXTENSION_KEY = "remote-control";
30
+ const RELOAD_COMMAND = "remote-reload";
31
+ const UPDATE_TIMEOUT_MS = 5 * 60_000;
31
32
 
32
- async function loadExtensionConfig(cwd: string): Promise<{ config: RemoteControlConfig; warnings: string[] }> {
33
- const warnings: string[] = [];
34
- let merged: Partial<RemoteControlConfig> = {};
35
-
36
- const override = process.env.PI_REMOTE_CONFIG?.trim();
37
- const paths = override
38
- ? [override]
39
- : [
40
- join(homedir(), CONFIG_DIR_NAME, "agent", "remote-control.json"),
41
- join(cwd, CONFIG_DIR_NAME, "remote-control.json"),
42
- ];
43
-
44
- for (const path of paths) {
45
- try {
46
- const raw = await readFile(path, "utf8");
47
- const parsed = parseRemoteConfig(JSON.parse(raw) as unknown);
48
- warnings.push(...parsed.warnings);
49
- merged = { ...merged, ...parsed.config };
50
- } catch (error) {
51
- const code = (error as NodeJS.ErrnoException).code;
52
- if (code !== "ENOENT") {
53
- warnings.push(`config error (${path}): ${error instanceof Error ? error.message : String(error)}`);
54
- }
55
- }
33
+ /** Read at load time, so a reload reports the version that is actually running. */
34
+ function readExtensionVersion(): string | undefined {
35
+ try {
36
+ const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version?: string };
37
+ return manifest.version;
38
+ } catch {
39
+ return undefined;
56
40
  }
57
-
58
- return { config: resolveRemoteConfig(merged), warnings };
59
41
  }
42
+ const EXTENSION_VERSION = readExtensionVersion();
60
43
 
61
44
  async function loadServerToken(config: RemoteControlConfig, warnings: string[]): Promise<string> {
62
45
  const envToken = process.env[config.tokenEnv]?.trim();
@@ -155,9 +138,24 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
155
138
  },
156
139
  });
157
140
 
141
+ // Only a command context can reload. The relay reaches it through /reload,
142
+ // while other extension commands stay unavailable from the web.
143
+ pi.registerCommand(RELOAD_COMMAND, {
144
+ description: "Reload pi (used by the remote /reload command)",
145
+ handler: async (_args, ctx) => {
146
+ await ctx.reload();
147
+ },
148
+ });
149
+
158
150
  pi.on("session_start", async (_event, ctx) => {
159
151
  sessionCtx = ctx;
160
- const { config, warnings } = await loadExtensionConfig(ctx.cwd);
152
+ const { config, warnings } = await loadExtensionConfig({
153
+ cwd: ctx.cwd,
154
+ homeDir: homedir(),
155
+ configDirName: CONFIG_DIR_NAME,
156
+ projectTrusted: ctx.isProjectTrusted(),
157
+ env: process.env,
158
+ });
161
159
  await refreshBranch(ctx.cwd);
162
160
  const serverToken = await loadServerToken(config, warnings);
163
161
 
@@ -196,6 +194,12 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
196
194
  });
197
195
  }),
198
196
  isIdle: () => (sessionCtx ? sessionCtx.isIdle() : true),
197
+ async runPiUpdate(args) {
198
+ const result = await pi.exec("pi", [...args], { timeout: UPDATE_TIMEOUT_MS });
199
+ const output = [result.stdout, result.stderr].filter(Boolean).join("\n");
200
+ return { code: result.killed ? 124 : result.code, output };
201
+ },
202
+ reload: () => pi.sendUserMessage(`/${RELOAD_COMMAND}`, { expandPromptTemplates: true }),
199
203
  sendPrompt(text, options) {
200
204
  const content =
201
205
  options?.images && options.images.length > 0
@@ -269,6 +273,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
269
273
  state: host.isIdle() ? "idle" : "busy",
270
274
  requirePairing: config.requirePairing,
271
275
  autoApprove: bridge?.autoApprove ?? false,
276
+ ...(EXTENSION_VERSION ? { extensionVersion: EXTENSION_VERSION } : {}),
272
277
  }),
273
278
  onMessage: (msg) => {
274
279
  void bridge?.handleServerMessage(msg);
@@ -0,0 +1,52 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { applyProjectConfig, parseRemoteConfig, resolveRemoteConfig } from "./config.js";
3
+
4
+ const user = resolveRemoteConfig({ serverUrl: "wss://relay.example/ws/agent", remoteToolApproval: "web" }, {});
5
+ const apply = (project: unknown, base = user) => applyProjectConfig(base, parseRemoteConfig(project).config);
6
+
7
+ describe("applyProjectConfig", () => {
8
+ it("never lets a project choose the relay or the credentials", () => {
9
+ const { config, ignored } = apply({
10
+ serverUrl: "wss://other.example/ws/agent",
11
+ tokenEnv: "OTHER_SECRET",
12
+ tokenFile: "~/.ssh/id_ed25519",
13
+ remoteUpdate: "all",
14
+ });
15
+ expect(config).toEqual(user);
16
+ expect(ignored).toEqual(["serverUrl", "tokenEnv", "tokenFile", "remoteUpdate"]);
17
+ });
18
+
19
+ it("ignores values that would weaken the user's protection", () => {
20
+ const strict = { ...user, requirePairing: true, remoteToolPolicy: "read-only" as const, remoteToolApproval: "local" as const };
21
+ const { config, ignored } = apply(
22
+ {
23
+ requirePairing: false,
24
+ remoteToolPolicy: "unrestricted",
25
+ remoteToolApproval: "web",
26
+ approvalTimeoutMs: 300_000,
27
+ pairingTtlMs: 3_600_000,
28
+ },
29
+ strict,
30
+ );
31
+ expect(config).toEqual(strict);
32
+ expect(ignored).toHaveLength(5);
33
+ });
34
+
35
+ it("accepts stricter values", () => {
36
+ const { config, ignored } = apply({
37
+ requirePairing: true,
38
+ remoteToolPolicy: "no-tools",
39
+ remoteToolApproval: "local",
40
+ approvalTimeoutMs: 10_000,
41
+ pairingTtlMs: 20_000,
42
+ });
43
+ expect(config).toMatchObject({
44
+ requirePairing: true,
45
+ remoteToolPolicy: "no-tools",
46
+ remoteToolApproval: "local",
47
+ approvalTimeoutMs: 10_000,
48
+ pairingTtlMs: 20_000,
49
+ });
50
+ expect(ignored).toEqual([]);
51
+ });
52
+ });