@wkqco33/pi-remote-control 0.1.1 → 0.2.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.
@@ -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
@@ -3,13 +3,19 @@
3
3
  * Thin adapter binding pi ExtensionAPI events to WsClient + RemoteBridge.
4
4
  */
5
5
 
6
- import { readFile } from "node:fs/promises";
6
+ import { readFile, stat } from "node:fs/promises";
7
7
  import { homedir, hostname } from "node:os";
8
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
- import { parseRemoteConfig, resolveRemoteConfig, type RemoteControlConfig } from "./config.js";
12
+ import {
13
+ expandHomePath,
14
+ parseRemoteConfig,
15
+ parseTokenFileContent,
16
+ resolveRemoteConfig,
17
+ type RemoteControlConfig,
18
+ } from "./config.js";
13
19
  import { buildWorkDigest, parseGitBranch, parseGitNumstat } from "./core/digest.js";
14
20
  import { buildHistorySnapshot, type RawSessionEntry } from "./core/history.js";
15
21
  import { formatFooterLabel, formatStatusReport } from "./core/status.js";
@@ -18,6 +24,7 @@ import {
18
24
  needsApproval,
19
25
  remoteToolBlockReason,
20
26
  remoteToolDeclinedReason,
27
+ type ApprovalReason,
21
28
  } from "./core/tool-policy.js";
22
29
 
23
30
  const EXTENSION_KEY = "remote-control";
@@ -51,6 +58,33 @@ async function loadExtensionConfig(cwd: string): Promise<{ config: RemoteControl
51
58
  return { config: resolveRemoteConfig(merged), warnings };
52
59
  }
53
60
 
61
+ async function loadServerToken(config: RemoteControlConfig, warnings: string[]): Promise<string> {
62
+ const envToken = process.env[config.tokenEnv]?.trim();
63
+ if (envToken) {
64
+ return envToken;
65
+ }
66
+ if (!config.tokenFile) {
67
+ return "";
68
+ }
69
+ const resolvedPath = expandHomePath(config.tokenFile, homedir());
70
+ try {
71
+ if (process.platform !== "win32") {
72
+ const info = await stat(resolvedPath);
73
+ if ((info.mode & 0o077) !== 0) {
74
+ warnings.push(`tokenFile (${resolvedPath}) should have 0600 permissions`);
75
+ }
76
+ }
77
+ const raw = await readFile(resolvedPath, "utf8");
78
+ return parseTokenFileContent(raw);
79
+ } catch (error) {
80
+ const code = (error as NodeJS.ErrnoException).code;
81
+ if (code !== "ENOENT") {
82
+ warnings.push(`tokenFile error (${resolvedPath}): ${error instanceof Error ? error.message : String(error)}`);
83
+ }
84
+ return "";
85
+ }
86
+ }
87
+
54
88
  export default async function remoteControlExtension(pi: ExtensionAPI): Promise<void> {
55
89
  let sessionCtx: ExtensionContext | null = null;
56
90
  let wsClient: WsClient | null = null;
@@ -88,9 +122,9 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
88
122
  }
89
123
 
90
124
  pi.registerCommand("remote", {
91
- description: "Control pi-remote-control relay connection (status, disconnect, digest, help)",
125
+ description: "Control pi-remote-control relay connection (status, disconnect, digest, auto, help)",
92
126
  handler: async (args, ctx) => {
93
- const sub = args.trim().split(/\s+/)[0] || "status";
127
+ const [sub = "status", value] = args.trim().split(/\s+/).filter(Boolean);
94
128
  if (sub === "status" || sub === "doctor") {
95
129
  if (!bridge) {
96
130
  ctx.ui.notify("remote-control: not initialized.", "warning");
@@ -109,7 +143,15 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
109
143
  ctx.ui.notify("remote-control: digest pushed.", "info");
110
144
  return;
111
145
  }
112
- ctx.ui.notify("Usage: /remote [status|doctor|digest|disconnect]", "info");
146
+ if (sub === "auto" && (value === "on" || value === "off")) {
147
+ if (!bridge) {
148
+ ctx.ui.notify("remote-control: not initialized.", "warning");
149
+ return;
150
+ }
151
+ bridge.setAutoApprove(value === "on", "local terminal");
152
+ return;
153
+ }
154
+ ctx.ui.notify("Usage: /remote [status|doctor|digest|disconnect|auto on|auto off]", "info");
113
155
  },
114
156
  });
115
157
 
@@ -117,7 +159,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
117
159
  sessionCtx = ctx;
118
160
  const { config, warnings } = await loadExtensionConfig(ctx.cwd);
119
161
  await refreshBranch(ctx.cwd);
120
- const serverToken = process.env[config.tokenEnv]?.trim() ?? "";
162
+ const serverToken = await loadServerToken(config, warnings);
121
163
 
122
164
  const host: RemoteHost = {
123
165
  sessionId: getSessionId(ctx),
@@ -132,6 +174,27 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
132
174
  get model() {
133
175
  return ctx.model?.id;
134
176
  },
177
+ listCommands: () => pi.getCommands(),
178
+ listModels: () => ctx.modelRegistry.getAvailable().map((model) => `${model.provider}/${model.id}`),
179
+ async setModel(reference) {
180
+ const available = ctx.modelRegistry.getAvailable();
181
+ const exact = available.filter((model) => `${model.provider}/${model.id}` === reference);
182
+ const matches = exact.length > 0 ? exact : available.filter((model) => model.id === reference);
183
+ const [model] = matches;
184
+ if (!model) return "not_found";
185
+ if (matches.length > 1) return "ambiguous";
186
+ return (await pi.setModel(model)) ? "ok" : "no_auth";
187
+ },
188
+ getThinkingLevel: () => pi.getThinkingLevel(),
189
+ setThinkingLevel: (level) => pi.setThinkingLevel(level),
190
+ compact: (instructions) =>
191
+ new Promise<void>((resolve, reject) => {
192
+ (sessionCtx ?? ctx).compact({
193
+ ...(instructions ? { customInstructions: instructions } : {}),
194
+ onComplete: () => resolve(),
195
+ onError: reject,
196
+ });
197
+ }),
135
198
  isIdle: () => (sessionCtx ? sessionCtx.isIdle() : true),
136
199
  sendPrompt(text, options) {
137
200
  const content =
@@ -146,13 +209,12 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
146
209
  ]
147
210
  : text;
148
211
  try {
149
- if (options?.deliverAs) {
150
- pi.sendUserMessage(content, { deliverAs: options.deliverAs });
151
- } else if (sessionCtx && !sessionCtx.isIdle()) {
152
- pi.sendUserMessage(content, { deliverAs: "followUp" });
153
- } else {
154
- pi.sendUserMessage(content);
155
- }
212
+ const deliverAs =
213
+ options?.deliverAs ?? (sessionCtx && !sessionCtx.isIdle() ? ("followUp" as const) : undefined);
214
+ pi.sendUserMessage(content, {
215
+ ...(deliverAs ? { deliverAs } : {}),
216
+ ...(options?.expandPromptTemplates ? { expandPromptTemplates: true } : {}),
217
+ });
156
218
  } catch (error) {
157
219
  ctx.ui.notify(
158
220
  `[remote] failed to inject prompt: ${error instanceof Error ? error.message : String(error)}`,
@@ -168,7 +230,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
168
230
  getHistory: () => {
169
231
  try {
170
232
  const entries = ctx.sessionManager.getEntries() as unknown as RawSessionEntry[];
171
- return buildHistorySnapshot(entries);
233
+ return buildHistorySnapshot(entries, { busy: !ctx.isIdle() });
172
234
  } catch {
173
235
  return [];
174
236
  }
@@ -206,6 +268,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
206
268
  ...(host.model ? { model: host.model } : {}),
207
269
  state: host.isIdle() ? "idle" : "busy",
208
270
  requirePairing: config.requirePairing,
271
+ autoApprove: bridge?.autoApprove ?? false,
209
272
  }),
210
273
  onMessage: (msg) => {
211
274
  void bridge?.handleServerMessage(msg);
@@ -240,7 +303,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
240
303
 
241
304
  pi.on("before_agent_start", async (event, ctx) => {
242
305
  sessionCtx = ctx;
243
- lastPrompt = event.prompt;
306
+ if (event.messageType === "user") lastPrompt = event.prompt;
244
307
  });
245
308
 
246
309
  pi.on("agent_start", async (_event, ctx) => {
@@ -298,13 +361,16 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
298
361
  if (!needsApproval(remoteToolApproval, event.toolName)) return undefined;
299
362
 
300
363
  let approved = false;
364
+ let declineReason: ApprovalReason | undefined;
301
365
  if (remoteToolApproval === "web") {
302
- approved = await bridge.requestWebApproval(event.toolCallId, event.toolName);
366
+ const outcome = await bridge.requestWebApproval(event.toolCallId, event.toolName);
367
+ approved = outcome.approved;
368
+ declineReason = outcome.reason;
303
369
  } else if (remoteToolApproval === "local") {
304
370
  approved = await ctx.ui.confirm("Remote tool call", `Allow '${event.toolName}' on remote turn?`);
305
371
  }
306
372
  if (approved) return undefined;
307
- return { block: true, reason: remoteToolDeclinedReason(event.toolName) };
373
+ return { block: true, reason: remoteToolDeclinedReason(event.toolName, declineReason) };
308
374
  });
309
375
 
310
376
  pi.on("agent_settled", async (_event, ctx) => {