@wkqco33/pi-remote-control 0.1.2 → 0.2.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,80 @@
1
+ /**
2
+ * Pure routing for slash commands typed in the web UI.
3
+ *
4
+ * Extension commands are never dispatched: pi runs their handlers without the
5
+ * `input` and `tool_call` events, so remote tool policy could not apply to them.
6
+ */
7
+
8
+ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
9
+
10
+ export const THINKING_LEVELS: readonly ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
11
+
12
+ export type BuiltinCommandName = "compact" | "model" | "thinking";
13
+
14
+ export interface CommandInfo {
15
+ readonly name: string;
16
+ readonly description?: string;
17
+ readonly source: "extension" | "prompt" | "skill";
18
+ }
19
+
20
+ export interface CatalogCommand {
21
+ readonly name: string;
22
+ readonly description?: string;
23
+ readonly source: "builtin" | "prompt" | "skill";
24
+ }
25
+
26
+ export const BUILTIN_COMMANDS: readonly (CatalogCommand & { readonly name: BuiltinCommandName })[] = [
27
+ { name: "compact", source: "builtin", description: "Compact the session context [instructions]" },
28
+ { name: "model", source: "builtin", description: "Show or change the model [provider/id]" },
29
+ { name: "thinking", source: "builtin", description: "Show or change the thinking level [level]" },
30
+ ];
31
+
32
+ export type SlashRoute =
33
+ /** Ordinary prompt text, delivered without any expansion. */
34
+ | { readonly kind: "plain"; readonly text: string }
35
+ /** Prompt template or skill that pi expands into a prompt. */
36
+ | { readonly kind: "expand"; readonly name: string; readonly text: string }
37
+ | { readonly kind: "builtin"; readonly name: BuiltinCommandName; readonly args: string }
38
+ | { readonly kind: "reject"; readonly name: string; readonly reason: string };
39
+
40
+ function isExtensionCommand(command: CommandInfo, name: string): boolean {
41
+ if (command.source !== "extension") return false;
42
+ // pi suffixes duplicate names, for example "review:1".
43
+ return command.name === name || (command.name.startsWith(`${name}:`) && /^\d+$/.test(command.name.slice(name.length + 1)));
44
+ }
45
+
46
+ export function routeSlashInput(text: string, commands: readonly CommandInfo[]): SlashRoute {
47
+ if (!text.startsWith("/")) return { kind: "plain", text };
48
+ // "//..." is the escape for text that really starts with a slash.
49
+ if (text.startsWith("//")) return { kind: "plain", text: text.slice(1) };
50
+
51
+ const match = /^\/(\S*)\s*([\s\S]*)$/.exec(text);
52
+ const name = match?.[1] ?? "";
53
+ // A second slash means a file path, not a command.
54
+ if (!name || name.includes("/")) return { kind: "plain", text };
55
+
56
+ const builtin = BUILTIN_COMMANDS.find((command) => command.name === name);
57
+ if (builtin) return { kind: "builtin", name: builtin.name, args: (match?.[2] ?? "").trim() };
58
+
59
+ if (commands.some((command) => isExtensionCommand(command, name))) {
60
+ return { kind: "reject", name, reason: `/${name} is an extension command, which cannot be run from the web.` };
61
+ }
62
+ if (commands.some((command) => command.name === name && command.source !== "extension")) {
63
+ return { kind: "expand", name, text };
64
+ }
65
+ return {
66
+ kind: "reject",
67
+ name,
68
+ reason: `/${name} is not a command available from the web. To send it as text, start with "//".`,
69
+ };
70
+ }
71
+
72
+ export function buildCommandCatalog(commands: readonly CommandInfo[]): CatalogCommand[] {
73
+ const expandable = commands.flatMap((command): CatalogCommand[] => {
74
+ if (command.source === "extension") return [];
75
+ // Hide names that routing would reject or handle as a built-in.
76
+ if (routeSlashInput(`/${command.name}`, commands).kind !== "expand") return [];
77
+ return [{ name: command.name, source: command.source, ...(command.description ? { description: command.description } : {}) }];
78
+ });
79
+ return [...BUILTIN_COMMANDS, ...expandable];
80
+ }
@@ -16,3 +16,38 @@ describe("buildHistorySnapshot", () => {
16
16
  expect(out[1]?.text).toBe("done");
17
17
  });
18
18
  });
19
+
20
+ describe("buildHistorySnapshot tool calls", () => {
21
+ const call = (id: string, text = "") => ({
22
+ type: "message",
23
+ message: {
24
+ role: "assistant",
25
+ content: [
26
+ ...(text ? [{ type: "text", text }] : []),
27
+ { type: "toolCall", id, name: "bash", arguments: { command: "echo secret-command" } },
28
+ ],
29
+ },
30
+ });
31
+ const result = (toolCallId: string, isError = false) => ({
32
+ type: "message",
33
+ message: { role: "toolResult", toolCallId, toolName: "bash", isError, durationMs: 12, content: "secret output" },
34
+ });
35
+ const user = (content: string) => ({ type: "message", message: { role: "user", content } });
36
+
37
+ it("restores call states in order without arguments or output", () => {
38
+ const entries = [user("go"), call("a", "first"), result("a"), call("b"), result("b", true), call("c"), user("next"), call("d")];
39
+ const out = buildHistorySnapshot(entries, { busy: true });
40
+ expect(out.map((item) => (item.role === "tool" ? `${item.toolCallId}:${item.status}` : item.text))).toEqual([
41
+ "go", "first", "a:done", "b:failed", "c:interrupted", "next", "d:running",
42
+ ]);
43
+ expect(out[2]).toMatchObject({ role: "tool", text: "bash", durationMs: 12 });
44
+ expect(JSON.stringify(out)).not.toContain("secret");
45
+ expect(buildHistorySnapshot(entries).at(-1)).toMatchObject({ status: "interrupted" });
46
+ });
47
+
48
+ it("bounds messages and tool calls separately", () => {
49
+ const entries = [user("old"), user("kept"), call("a"), call("b"), call("c"), user("last")];
50
+ const out = buildHistorySnapshot(entries, { maxItems: 2, maxToolItems: 2 });
51
+ expect(out.map((item) => (item.role === "tool" ? item.toolCallId : item.text))).toEqual(["kept", "b", "c", "last"]);
52
+ });
53
+ });
@@ -1,14 +1,16 @@
1
1
  /**
2
2
  * Pure history snapshot extraction from pi session entries.
3
- * Applies secret redaction and size bounds.
3
+ * Applies secret redaction and size bounds. Tool arguments and results are never included.
4
4
  */
5
5
 
6
- import type { HistoryItem } from "./protocol.js";
6
+ import type { HistoryItem, HistoryToolStatus } from "./protocol.js";
7
7
  import { redactSecrets } from "./redact.js";
8
8
 
9
9
  export interface RawMessageContentPart {
10
10
  readonly type?: string;
11
11
  readonly text?: string;
12
+ readonly id?: string;
13
+ readonly name?: string;
12
14
  }
13
15
 
14
16
  export interface RawSessionEntry {
@@ -17,49 +19,98 @@ export interface RawSessionEntry {
17
19
  readonly message?: {
18
20
  readonly role?: string;
19
21
  readonly content?: unknown;
22
+ readonly toolCallId?: string;
23
+ readonly isError?: boolean;
24
+ readonly durationMs?: number;
20
25
  };
21
26
  }
22
27
 
28
+ export interface HistoryOptions {
29
+ /** Maximum number of user and assistant messages. */
30
+ readonly maxItems?: number;
31
+ readonly maxItemChars?: number;
32
+ readonly maxToolItems?: number;
33
+ /** Whether the agent is working, so a tool call without a result may still be running. */
34
+ readonly busy?: boolean;
35
+ }
36
+
37
+ type ToolItem = Extract<HistoryItem, { role: "tool" }>;
38
+ type MutableToolItem = { -readonly [Key in keyof ToolItem]: ToolItem[Key] };
39
+
40
+ function contentParts(content: unknown): RawMessageContentPart[] {
41
+ if (typeof content === "string") return [{ type: "text", text: content }];
42
+ if (!Array.isArray(content)) return [];
43
+ return content.filter((part): part is RawMessageContentPart => typeof part === "object" && part !== null);
44
+ }
45
+
23
46
  export function extractTextContent(content: unknown): string {
24
- if (typeof content === "string") return content;
25
- if (!Array.isArray(content)) return "";
26
- const parts: string[] = [];
27
- for (const part of content) {
28
- if (typeof part === "object" && part !== null) {
29
- const record = part as RawMessageContentPart;
30
- if (record.type === "text" && typeof record.text === "string" && record.text.length > 0) {
31
- parts.push(record.text);
32
- }
33
- }
34
- }
35
- return parts.join("\n");
47
+ return contentParts(content)
48
+ .flatMap((part) => (part.type === "text" && typeof part.text === "string" && part.text ? [part.text] : []))
49
+ .join("\n");
36
50
  }
37
51
 
38
- export function buildHistorySnapshot(
39
- entries: readonly RawSessionEntry[],
40
- options: { maxItems?: number; maxItemChars?: number } = {},
41
- ): HistoryItem[] {
52
+ export function buildHistorySnapshot(entries: readonly RawSessionEntry[], options: HistoryOptions = {}): HistoryItem[] {
42
53
  const maxItems = options.maxItems ?? 40;
43
54
  const maxItemChars = options.maxItemChars ?? 4000;
55
+ const maxToolItems = options.maxToolItems ?? 100;
44
56
  const items: HistoryItem[] = [];
57
+ const unresolved = new Map<string, MutableToolItem>();
58
+
59
+ const settleUnresolved = (status: HistoryToolStatus): void => {
60
+ for (const item of unresolved.values()) item.status = status;
61
+ unresolved.clear();
62
+ };
45
63
 
46
64
  for (const entry of entries) {
47
65
  if (entry.type !== "message" || !entry.message) continue;
48
- const role = entry.message.role;
66
+ const { role, content, toolCallId, isError, durationMs } = entry.message;
67
+ if (role === "toolResult") {
68
+ const call = toolCallId ? unresolved.get(toolCallId) : undefined;
69
+ if (!call || !toolCallId) continue;
70
+ call.status = isError ? "failed" : "done";
71
+ if (typeof durationMs === "number") call.durationMs = durationMs;
72
+ unresolved.delete(toolCallId);
73
+ continue;
74
+ }
49
75
  if (role !== "user" && role !== "assistant") continue;
50
- const rawText = extractTextContent(entry.message.content).trim();
51
- if (!rawText) continue;
76
+ // A new prompt means earlier calls without a result never finished.
77
+ if (role === "user") settleUnresolved("interrupted");
52
78
 
53
- const redacted = redactSecrets(rawText);
54
- const text = redacted.length > maxItemChars ? `${redacted.slice(0, maxItemChars - 1)}…` : redacted;
55
79
  const parsedTs = entry.timestamp ? Date.parse(entry.timestamp) : Number.NaN;
56
- items.push({
57
- role,
58
- text,
59
- ...(Number.isFinite(parsedTs) ? { ts: parsedTs } : {}),
60
- });
80
+ const ts = Number.isFinite(parsedTs) ? { ts: parsedTs } : {};
81
+ const rawText = extractTextContent(content).trim();
82
+ if (rawText) {
83
+ const redacted = redactSecrets(rawText);
84
+ const text = redacted.length > maxItemChars ? `${redacted.slice(0, maxItemChars - 1)}…` : redacted;
85
+ items.push({ role, text, ...ts });
86
+ }
87
+ if (role !== "assistant") continue;
88
+ for (const part of contentParts(content)) {
89
+ if (part.type !== "toolCall" || !part.id || !part.name) continue;
90
+ const item: MutableToolItem = { role: "tool", text: part.name, toolCallId: part.id, status: "running", ...ts };
91
+ items.push(item);
92
+ unresolved.set(part.id, item);
93
+ }
61
94
  }
95
+ if (!options.busy) settleUnresolved("interrupted");
62
96
 
63
- if (items.length <= maxItems) return items;
64
- return items.slice(items.length - maxItems);
97
+ return boundHistory(items, maxItems, maxToolItems);
98
+ }
99
+
100
+ /** Bounds messages and tool calls separately so tool-heavy turns keep the conversation. */
101
+ function boundHistory(items: readonly HistoryItem[], maxItems: number, maxToolItems: number): HistoryItem[] {
102
+ let messages = 0;
103
+ let tools = 0;
104
+ const kept: HistoryItem[] = [];
105
+ for (let i = items.length - 1; i >= 0 && messages < maxItems; i--) {
106
+ const item = items[i] as HistoryItem;
107
+ if (item.role === "tool") {
108
+ if (tools >= maxToolItems) continue;
109
+ tools += 1;
110
+ } else {
111
+ messages += 1;
112
+ }
113
+ kept.push(item);
114
+ }
115
+ return kept.reverse();
65
116
  }
@@ -13,11 +13,19 @@ export interface PromptImage {
13
13
  readonly data: string;
14
14
  }
15
15
 
16
- export interface HistoryItem {
17
- readonly role: "user" | "assistant" | "system";
18
- readonly text: string;
19
- readonly ts?: number;
20
- }
16
+ export type HistoryToolStatus = "running" | "done" | "failed" | "interrupted";
17
+
18
+ export type HistoryItem =
19
+ | { readonly role: "user" | "assistant" | "system"; readonly text: string; readonly ts?: number }
20
+ | {
21
+ readonly role: "tool";
22
+ /** Tool name. */
23
+ readonly text: string;
24
+ readonly toolCallId: string;
25
+ readonly status: HistoryToolStatus;
26
+ readonly durationMs?: number;
27
+ readonly ts?: number;
28
+ };
21
29
 
22
30
  export interface WireEnvelope<T = unknown> {
23
31
  readonly type: string;
@@ -48,10 +56,11 @@ export interface ApprovalResponsePayload {
48
56
 
49
57
  export interface HistoryRequestPayload {
50
58
  readonly clientId?: string;
59
+ readonly pairStatusOnly?: boolean;
51
60
  }
52
61
 
53
62
  export type ServerInboundMessage =
54
- | { readonly type: "history.request"; readonly clientId?: string }
63
+ | ({ readonly type: "history.request" } & HistoryRequestPayload)
55
64
  | { readonly type: "pair.submit"; readonly clientId: string; readonly code: string }
56
65
  | {
57
66
  readonly type: "prompt.send";
@@ -62,7 +71,9 @@ export type ServerInboundMessage =
62
71
  }
63
72
  | { readonly type: "turn.abort"; readonly clientId: string }
64
73
  | { readonly type: "approval.response"; readonly clientId: string; readonly requestId: string; readonly approved: boolean }
74
+ | { readonly type: "approval.mode"; readonly clientId: string; readonly autoApprove: boolean }
65
75
  | { readonly type: "digest.request"; readonly clientId: string }
76
+ | { readonly type: "commands.request"; readonly clientId: string }
66
77
  | { readonly type: "ping" }
67
78
  | { readonly type: "pong" }
68
79
  | { readonly type: "error"; readonly code: string; readonly message: string };
@@ -90,7 +101,11 @@ export function parseServerEnvelope(raw: string): ServerInboundMessage | null {
90
101
  return { type: "pong" };
91
102
  case "history.request": {
92
103
  const reqClient = typeof payload.clientId === "string" ? payload.clientId : clientId || undefined;
93
- return reqClient === undefined ? { type: "history.request" } : { type: "history.request", clientId: reqClient };
104
+ return {
105
+ type: "history.request",
106
+ ...(reqClient ? { clientId: reqClient } : {}),
107
+ ...(payload.pairStatusOnly === true ? { pairStatusOnly: true } : {}),
108
+ };
94
109
  }
95
110
  case "pair.submit":
96
111
  if (!clientId || typeof payload.code !== "string") return null;
@@ -113,6 +128,11 @@ export function parseServerEnvelope(raw: string): ServerInboundMessage | null {
113
128
  case "approval.response":
114
129
  if (!clientId || typeof payload.requestId !== "string" || typeof payload.approved !== "boolean") return null;
115
130
  return { type: "approval.response", clientId, requestId: payload.requestId, approved: payload.approved };
131
+ case "approval.mode":
132
+ if (!clientId || typeof payload.autoApprove !== "boolean") return null;
133
+ return { type: "approval.mode", clientId, autoApprove: payload.autoApprove };
134
+ case "commands.request":
135
+ return clientId ? { type: "commands.request", clientId } : null;
116
136
  case "digest.request":
117
137
  return clientId ? { type: "digest.request", clientId } : null;
118
138
  case "error":
@@ -13,6 +13,7 @@ describe("status", () => {
13
13
  pendingPairings: 0,
14
14
  remoteToolPolicy: "unrestricted",
15
15
  remoteToolApproval: "web",
16
+ autoApprove: false,
16
17
  });
17
18
  expect(report).toContain("pi-remote-control status: connected");
18
19
  expect(report).toContain("toolPolicy: unrestricted (approval: web)");
@@ -12,6 +12,7 @@ export interface StatusSnapshot {
12
12
  readonly pendingPairings: number;
13
13
  readonly remoteToolPolicy: string;
14
14
  readonly remoteToolApproval: string;
15
+ readonly autoApprove: boolean;
15
16
  readonly lastError?: string;
16
17
  }
17
18
 
@@ -32,6 +33,7 @@ export function formatStatusReport(s: StatusSnapshot): string {
32
33
  `- trustedClients: ${s.trustedClients}`,
33
34
  `- pendingPairings: ${s.pendingPairings}`,
34
35
  `- toolPolicy: ${s.remoteToolPolicy} (approval: ${s.remoteToolApproval})`,
36
+ `- autoApprove: ${s.autoApprove ? "on" : "off"}`,
35
37
  ];
36
38
  if (s.lastError) lines.push(`- lastError: ${s.lastError}`);
37
39
  return lines.join("\n");
@@ -25,6 +25,15 @@ export function remoteToolBlockReason(policy: RemoteToolPolicy, toolName: string
25
25
  return `Tool '${toolName}' is blocked for remote turns (read-only policy).`;
26
26
  }
27
27
 
28
- export function remoteToolDeclinedReason(toolName: string): string {
28
+ export type ApprovalReason = "user" | "auto" | "timeout" | "cancelled";
29
+
30
+ export function remoteToolDeclinedReason(toolName: string, reason?: ApprovalReason): string {
31
+ if (reason === "user") return `Remote tool '${toolName}' was declined by the user.`;
32
+ if (reason === "timeout") {
33
+ return `Remote tool '${toolName}' was not run: no approval response before the timeout (the command itself did not run).`;
34
+ }
35
+ if (reason === "cancelled") {
36
+ return `Remote tool '${toolName}' was not run: the approval was cancelled (relay disconnected or access revoked).`;
37
+ }
29
38
  return `Remote tool '${toolName}' was declined or timed out.`;
30
39
  }
package/src/index.ts CHANGED
@@ -5,17 +5,15 @@
5
5
 
6
6
  import { readFile, stat } from "node:fs/promises";
7
7
  import { homedir, hostname } from "node:os";
8
- import { join } from "node:path";
9
8
  import { CONFIG_DIR_NAME, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
10
9
  import { RemoteBridge, type RemoteHost } from "./client/remote-bridge.js";
11
10
  import { WsClient } from "./client/ws-client.js";
12
11
  import {
13
12
  expandHomePath,
14
- parseRemoteConfig,
15
13
  parseTokenFileContent,
16
- resolveRemoteConfig,
17
14
  type RemoteControlConfig,
18
15
  } from "./config.js";
16
+ import { loadExtensionConfig } from "./config-loader.js";
19
17
  import { buildWorkDigest, parseGitBranch, parseGitNumstat } from "./core/digest.js";
20
18
  import { buildHistorySnapshot, type RawSessionEntry } from "./core/history.js";
21
19
  import { formatFooterLabel, formatStatusReport } from "./core/status.js";
@@ -24,39 +22,11 @@ import {
24
22
  needsApproval,
25
23
  remoteToolBlockReason,
26
24
  remoteToolDeclinedReason,
25
+ type ApprovalReason,
27
26
  } from "./core/tool-policy.js";
28
27
 
29
28
  const EXTENSION_KEY = "remote-control";
30
29
 
31
- async function loadExtensionConfig(cwd: string): Promise<{ config: RemoteControlConfig; warnings: string[] }> {
32
- const warnings: string[] = [];
33
- let merged: Partial<RemoteControlConfig> = {};
34
-
35
- const override = process.env.PI_REMOTE_CONFIG?.trim();
36
- const paths = override
37
- ? [override]
38
- : [
39
- join(homedir(), CONFIG_DIR_NAME, "agent", "remote-control.json"),
40
- join(cwd, CONFIG_DIR_NAME, "remote-control.json"),
41
- ];
42
-
43
- for (const path of paths) {
44
- try {
45
- const raw = await readFile(path, "utf8");
46
- const parsed = parseRemoteConfig(JSON.parse(raw) as unknown);
47
- warnings.push(...parsed.warnings);
48
- merged = { ...merged, ...parsed.config };
49
- } catch (error) {
50
- const code = (error as NodeJS.ErrnoException).code;
51
- if (code !== "ENOENT") {
52
- warnings.push(`config error (${path}): ${error instanceof Error ? error.message : String(error)}`);
53
- }
54
- }
55
- }
56
-
57
- return { config: resolveRemoteConfig(merged), warnings };
58
- }
59
-
60
30
  async function loadServerToken(config: RemoteControlConfig, warnings: string[]): Promise<string> {
61
31
  const envToken = process.env[config.tokenEnv]?.trim();
62
32
  if (envToken) {
@@ -121,9 +91,9 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
121
91
  }
122
92
 
123
93
  pi.registerCommand("remote", {
124
- description: "Control pi-remote-control relay connection (status, disconnect, digest, help)",
94
+ description: "Control pi-remote-control relay connection (status, disconnect, digest, auto, help)",
125
95
  handler: async (args, ctx) => {
126
- const sub = args.trim().split(/\s+/)[0] || "status";
96
+ const [sub = "status", value] = args.trim().split(/\s+/).filter(Boolean);
127
97
  if (sub === "status" || sub === "doctor") {
128
98
  if (!bridge) {
129
99
  ctx.ui.notify("remote-control: not initialized.", "warning");
@@ -142,13 +112,27 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
142
112
  ctx.ui.notify("remote-control: digest pushed.", "info");
143
113
  return;
144
114
  }
145
- ctx.ui.notify("Usage: /remote [status|doctor|digest|disconnect]", "info");
115
+ if (sub === "auto" && (value === "on" || value === "off")) {
116
+ if (!bridge) {
117
+ ctx.ui.notify("remote-control: not initialized.", "warning");
118
+ return;
119
+ }
120
+ bridge.setAutoApprove(value === "on", "local terminal");
121
+ return;
122
+ }
123
+ ctx.ui.notify("Usage: /remote [status|doctor|digest|disconnect|auto on|auto off]", "info");
146
124
  },
147
125
  });
148
126
 
149
127
  pi.on("session_start", async (_event, ctx) => {
150
128
  sessionCtx = ctx;
151
- const { config, warnings } = await loadExtensionConfig(ctx.cwd);
129
+ const { config, warnings } = await loadExtensionConfig({
130
+ cwd: ctx.cwd,
131
+ homeDir: homedir(),
132
+ configDirName: CONFIG_DIR_NAME,
133
+ projectTrusted: ctx.isProjectTrusted(),
134
+ env: process.env,
135
+ });
152
136
  await refreshBranch(ctx.cwd);
153
137
  const serverToken = await loadServerToken(config, warnings);
154
138
 
@@ -165,6 +149,27 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
165
149
  get model() {
166
150
  return ctx.model?.id;
167
151
  },
152
+ listCommands: () => pi.getCommands(),
153
+ listModels: () => ctx.modelRegistry.getAvailable().map((model) => `${model.provider}/${model.id}`),
154
+ async setModel(reference) {
155
+ const available = ctx.modelRegistry.getAvailable();
156
+ const exact = available.filter((model) => `${model.provider}/${model.id}` === reference);
157
+ const matches = exact.length > 0 ? exact : available.filter((model) => model.id === reference);
158
+ const [model] = matches;
159
+ if (!model) return "not_found";
160
+ if (matches.length > 1) return "ambiguous";
161
+ return (await pi.setModel(model)) ? "ok" : "no_auth";
162
+ },
163
+ getThinkingLevel: () => pi.getThinkingLevel(),
164
+ setThinkingLevel: (level) => pi.setThinkingLevel(level),
165
+ compact: (instructions) =>
166
+ new Promise<void>((resolve, reject) => {
167
+ (sessionCtx ?? ctx).compact({
168
+ ...(instructions ? { customInstructions: instructions } : {}),
169
+ onComplete: () => resolve(),
170
+ onError: reject,
171
+ });
172
+ }),
168
173
  isIdle: () => (sessionCtx ? sessionCtx.isIdle() : true),
169
174
  sendPrompt(text, options) {
170
175
  const content =
@@ -179,13 +184,12 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
179
184
  ]
180
185
  : text;
181
186
  try {
182
- if (options?.deliverAs) {
183
- pi.sendUserMessage(content, { deliverAs: options.deliverAs });
184
- } else if (sessionCtx && !sessionCtx.isIdle()) {
185
- pi.sendUserMessage(content, { deliverAs: "followUp" });
186
- } else {
187
- pi.sendUserMessage(content);
188
- }
187
+ const deliverAs =
188
+ options?.deliverAs ?? (sessionCtx && !sessionCtx.isIdle() ? ("followUp" as const) : undefined);
189
+ pi.sendUserMessage(content, {
190
+ ...(deliverAs ? { deliverAs } : {}),
191
+ ...(options?.expandPromptTemplates ? { expandPromptTemplates: true } : {}),
192
+ });
189
193
  } catch (error) {
190
194
  ctx.ui.notify(
191
195
  `[remote] failed to inject prompt: ${error instanceof Error ? error.message : String(error)}`,
@@ -201,7 +205,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
201
205
  getHistory: () => {
202
206
  try {
203
207
  const entries = ctx.sessionManager.getEntries() as unknown as RawSessionEntry[];
204
- return buildHistorySnapshot(entries);
208
+ return buildHistorySnapshot(entries, { busy: !ctx.isIdle() });
205
209
  } catch {
206
210
  return [];
207
211
  }
@@ -239,6 +243,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
239
243
  ...(host.model ? { model: host.model } : {}),
240
244
  state: host.isIdle() ? "idle" : "busy",
241
245
  requirePairing: config.requirePairing,
246
+ autoApprove: bridge?.autoApprove ?? false,
242
247
  }),
243
248
  onMessage: (msg) => {
244
249
  void bridge?.handleServerMessage(msg);
@@ -273,7 +278,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
273
278
 
274
279
  pi.on("before_agent_start", async (event, ctx) => {
275
280
  sessionCtx = ctx;
276
- lastPrompt = event.prompt;
281
+ if (event.messageType === "user") lastPrompt = event.prompt;
277
282
  });
278
283
 
279
284
  pi.on("agent_start", async (_event, ctx) => {
@@ -331,13 +336,16 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
331
336
  if (!needsApproval(remoteToolApproval, event.toolName)) return undefined;
332
337
 
333
338
  let approved = false;
339
+ let declineReason: ApprovalReason | undefined;
334
340
  if (remoteToolApproval === "web") {
335
- approved = await bridge.requestWebApproval(event.toolCallId, event.toolName);
341
+ const outcome = await bridge.requestWebApproval(event.toolCallId, event.toolName);
342
+ approved = outcome.approved;
343
+ declineReason = outcome.reason;
336
344
  } else if (remoteToolApproval === "local") {
337
345
  approved = await ctx.ui.confirm("Remote tool call", `Allow '${event.toolName}' on remote turn?`);
338
346
  }
339
347
  if (approved) return undefined;
340
- return { block: true, reason: remoteToolDeclinedReason(event.toolName) };
348
+ return { block: true, reason: remoteToolDeclinedReason(event.toolName, declineReason) };
341
349
  });
342
350
 
343
351
  pi.on("agent_settled", async (_event, ctx) => {
@@ -0,0 +1,51 @@
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
+ });
14
+ expect(config).toEqual(user);
15
+ expect(ignored).toEqual(["serverUrl", "tokenEnv", "tokenFile"]);
16
+ });
17
+
18
+ it("ignores values that would weaken the user's protection", () => {
19
+ const strict = { ...user, requirePairing: true, remoteToolPolicy: "read-only" as const, remoteToolApproval: "local" as const };
20
+ const { config, ignored } = apply(
21
+ {
22
+ requirePairing: false,
23
+ remoteToolPolicy: "unrestricted",
24
+ remoteToolApproval: "web",
25
+ approvalTimeoutMs: 300_000,
26
+ pairingTtlMs: 3_600_000,
27
+ },
28
+ strict,
29
+ );
30
+ expect(config).toEqual(strict);
31
+ expect(ignored).toHaveLength(5);
32
+ });
33
+
34
+ it("accepts stricter values", () => {
35
+ const { config, ignored } = apply({
36
+ requirePairing: true,
37
+ remoteToolPolicy: "no-tools",
38
+ remoteToolApproval: "local",
39
+ approvalTimeoutMs: 10_000,
40
+ pairingTtlMs: 20_000,
41
+ });
42
+ expect(config).toMatchObject({
43
+ requirePairing: true,
44
+ remoteToolPolicy: "no-tools",
45
+ remoteToolApproval: "local",
46
+ approvalTimeoutMs: 10_000,
47
+ pairingTtlMs: 20_000,
48
+ });
49
+ expect(ignored).toEqual([]);
50
+ });
51
+ });