@wkqco33/pi-remote-control 0.2.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/package.json +1 -1
- package/src/client/command-handler.ts +3 -1
- package/src/client/maintenance.test.ts +69 -0
- package/src/client/maintenance.ts +100 -0
- package/src/client/prompt-router.ts +21 -5
- package/src/client/remote-bridge.test.ts +19 -2
- package/src/client/remote-bridge.ts +3 -2
- package/src/client/ws-client.ts +1 -0
- package/src/config.ts +6 -0
- package/src/core/commands.test.ts +1 -0
- package/src/core/commands.ts +8 -3
- package/src/index.test.ts +1 -1
- package/src/index.ts +30 -0
- package/src/project-config.test.ts +2 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wkqco33/pi-remote-control",
|
|
3
|
-
"version": "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
|
|
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
|
|
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
|
-
|
|
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;
|
package/src/client/ws-client.ts
CHANGED
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
|
}
|
|
@@ -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
|
});
|
package/src/core/commands.ts
CHANGED
|
@@ -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
|
-
|
|
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,6 +3,7 @@
|
|
|
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
9
|
import { CONFIG_DIR_NAME, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
@@ -26,6 +27,19 @@ import {
|
|
|
26
27
|
} from "./core/tool-policy.js";
|
|
27
28
|
|
|
28
29
|
const EXTENSION_KEY = "remote-control";
|
|
30
|
+
const RELOAD_COMMAND = "remote-reload";
|
|
31
|
+
const UPDATE_TIMEOUT_MS = 5 * 60_000;
|
|
32
|
+
|
|
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;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const EXTENSION_VERSION = readExtensionVersion();
|
|
29
43
|
|
|
30
44
|
async function loadServerToken(config: RemoteControlConfig, warnings: string[]): Promise<string> {
|
|
31
45
|
const envToken = process.env[config.tokenEnv]?.trim();
|
|
@@ -124,6 +138,15 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
|
|
|
124
138
|
},
|
|
125
139
|
});
|
|
126
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
|
+
|
|
127
150
|
pi.on("session_start", async (_event, ctx) => {
|
|
128
151
|
sessionCtx = ctx;
|
|
129
152
|
const { config, warnings } = await loadExtensionConfig({
|
|
@@ -171,6 +194,12 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
|
|
|
171
194
|
});
|
|
172
195
|
}),
|
|
173
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 }),
|
|
174
203
|
sendPrompt(text, options) {
|
|
175
204
|
const content =
|
|
176
205
|
options?.images && options.images.length > 0
|
|
@@ -244,6 +273,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
|
|
|
244
273
|
state: host.isIdle() ? "idle" : "busy",
|
|
245
274
|
requirePairing: config.requirePairing,
|
|
246
275
|
autoApprove: bridge?.autoApprove ?? false,
|
|
276
|
+
...(EXTENSION_VERSION ? { extensionVersion: EXTENSION_VERSION } : {}),
|
|
247
277
|
}),
|
|
248
278
|
onMessage: (msg) => {
|
|
249
279
|
void bridge?.handleServerMessage(msg);
|
|
@@ -10,9 +10,10 @@ describe("applyProjectConfig", () => {
|
|
|
10
10
|
serverUrl: "wss://other.example/ws/agent",
|
|
11
11
|
tokenEnv: "OTHER_SECRET",
|
|
12
12
|
tokenFile: "~/.ssh/id_ed25519",
|
|
13
|
+
remoteUpdate: "all",
|
|
13
14
|
});
|
|
14
15
|
expect(config).toEqual(user);
|
|
15
|
-
expect(ignored).toEqual(["serverUrl", "tokenEnv", "tokenFile"]);
|
|
16
|
+
expect(ignored).toEqual(["serverUrl", "tokenEnv", "tokenFile", "remoteUpdate"]);
|
|
16
17
|
});
|
|
17
18
|
|
|
18
19
|
it("ignores values that would weaken the user's protection", () => {
|