@wkqco33/pi-remote-control 0.1.2 → 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.
@@ -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
@@ -24,6 +24,7 @@ import {
24
24
  needsApproval,
25
25
  remoteToolBlockReason,
26
26
  remoteToolDeclinedReason,
27
+ type ApprovalReason,
27
28
  } from "./core/tool-policy.js";
28
29
 
29
30
  const EXTENSION_KEY = "remote-control";
@@ -121,9 +122,9 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
121
122
  }
122
123
 
123
124
  pi.registerCommand("remote", {
124
- description: "Control pi-remote-control relay connection (status, disconnect, digest, help)",
125
+ description: "Control pi-remote-control relay connection (status, disconnect, digest, auto, help)",
125
126
  handler: async (args, ctx) => {
126
- const sub = args.trim().split(/\s+/)[0] || "status";
127
+ const [sub = "status", value] = args.trim().split(/\s+/).filter(Boolean);
127
128
  if (sub === "status" || sub === "doctor") {
128
129
  if (!bridge) {
129
130
  ctx.ui.notify("remote-control: not initialized.", "warning");
@@ -142,7 +143,15 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
142
143
  ctx.ui.notify("remote-control: digest pushed.", "info");
143
144
  return;
144
145
  }
145
- 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");
146
155
  },
147
156
  });
148
157
 
@@ -165,6 +174,27 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
165
174
  get model() {
166
175
  return ctx.model?.id;
167
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
+ }),
168
198
  isIdle: () => (sessionCtx ? sessionCtx.isIdle() : true),
169
199
  sendPrompt(text, options) {
170
200
  const content =
@@ -179,13 +209,12 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
179
209
  ]
180
210
  : text;
181
211
  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
- }
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
+ });
189
218
  } catch (error) {
190
219
  ctx.ui.notify(
191
220
  `[remote] failed to inject prompt: ${error instanceof Error ? error.message : String(error)}`,
@@ -201,7 +230,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
201
230
  getHistory: () => {
202
231
  try {
203
232
  const entries = ctx.sessionManager.getEntries() as unknown as RawSessionEntry[];
204
- return buildHistorySnapshot(entries);
233
+ return buildHistorySnapshot(entries, { busy: !ctx.isIdle() });
205
234
  } catch {
206
235
  return [];
207
236
  }
@@ -239,6 +268,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
239
268
  ...(host.model ? { model: host.model } : {}),
240
269
  state: host.isIdle() ? "idle" : "busy",
241
270
  requirePairing: config.requirePairing,
271
+ autoApprove: bridge?.autoApprove ?? false,
242
272
  }),
243
273
  onMessage: (msg) => {
244
274
  void bridge?.handleServerMessage(msg);
@@ -273,7 +303,7 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
273
303
 
274
304
  pi.on("before_agent_start", async (event, ctx) => {
275
305
  sessionCtx = ctx;
276
- lastPrompt = event.prompt;
306
+ if (event.messageType === "user") lastPrompt = event.prompt;
277
307
  });
278
308
 
279
309
  pi.on("agent_start", async (_event, ctx) => {
@@ -331,13 +361,16 @@ export default async function remoteControlExtension(pi: ExtensionAPI): Promise<
331
361
  if (!needsApproval(remoteToolApproval, event.toolName)) return undefined;
332
362
 
333
363
  let approved = false;
364
+ let declineReason: ApprovalReason | undefined;
334
365
  if (remoteToolApproval === "web") {
335
- 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;
336
369
  } else if (remoteToolApproval === "local") {
337
370
  approved = await ctx.ui.confirm("Remote tool call", `Allow '${event.toolName}' on remote turn?`);
338
371
  }
339
372
  if (approved) return undefined;
340
- return { block: true, reason: remoteToolDeclinedReason(event.toolName) };
373
+ return { block: true, reason: remoteToolDeclinedReason(event.toolName, declineReason) };
341
374
  });
342
375
 
343
376
  pi.on("agent_settled", async (_event, ctx) => {