@aoshizuku/pi-subagent 0.0.0-stage → 0.1.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/src/result.ts ADDED
@@ -0,0 +1,226 @@
1
+ // Result handoff: truncation, result files, tag escaping and the <subagent-result> text (docs/05 §3-§4, docs/03 §4).
2
+
3
+ import { existsSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+
6
+ import type { AgentRecord } from "./manager.js";
7
+ import { NO_FINAL_REPORT, PARENT_INTERRUPTED, SESSION_ENDED, STOPPED_BY_PARENT, STOPPED_BY_USER } from "./run.js";
8
+
9
+ /**
10
+ * Rewrite fragments that would close an outer tag early (`</subagent-result`, `</subagent-notification`,
11
+ * `</agent>`, `</result>`) as `<\/…`. No full XML escaping: reports are mostly code.
12
+ */
13
+ export function escapeReport(text: string): string {
14
+ return text.replace(/<\/(subagent-result|subagent-notification|agent|result)(?=[\s>]|$)/gi, "<\\/$1");
15
+ }
16
+
17
+ export interface Truncated {
18
+ text: string;
19
+ truncated: boolean;
20
+ total: number;
21
+ }
22
+
23
+ /** Keep the beginning (reports lead with the conclusion); cut back to the last newline when there is one. */
24
+ export function truncateReport(text: string, max: number): Truncated {
25
+ if (text.length <= max) return { text, truncated: false, total: text.length };
26
+ const head = text.slice(0, max);
27
+ const newline = head.lastIndexOf("\n");
28
+ return { text: newline > 0 ? head.slice(0, newline) : head, truncated: true, total: text.length };
29
+ }
30
+
31
+ export function resultFileName(agentId: string): string {
32
+ return `${agentId}.result.md`;
33
+ }
34
+
35
+ /**
36
+ * Write the full report to `<dir>/<agentId>.result.md`. An existing file is kept as
37
+ * `<agentId>.result.<n>.md` with the next free n (a continued agent overwrites with its latest run).
38
+ */
39
+ export function writeResultFile(dir: string, agentId: string, text: string): string {
40
+ mkdirSync(dir, { recursive: true });
41
+ const path = join(dir, resultFileName(agentId));
42
+ if (existsSync(path)) {
43
+ let n = 1;
44
+ while (existsSync(join(dir, `${agentId}.result.${n}.md`))) n++;
45
+ renameSync(path, join(dir, `${agentId}.result.${n}.md`));
46
+ }
47
+ writeFileSync(path, text, "utf8");
48
+ return path;
49
+ }
50
+
51
+ export function formatDuration(ms: number): string {
52
+ const seconds = Math.max(0, Math.round(ms / 1000));
53
+ if (seconds < 60) return `${seconds}s`;
54
+ const minutes = Math.floor(seconds / 60);
55
+ if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
56
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
57
+ }
58
+
59
+ export function durationOf(record: Pick<AgentRecord, "startedAt" | "endedAt" | "createdAt">, now = Date.now()): number {
60
+ const start = record.startedAt ?? record.createdAt;
61
+ return (record.endedAt ?? now) - start;
62
+ }
63
+
64
+ /**
65
+ * What the parent should do next, by status (docs/03 §4.2). `continuable`: the transcript exists, so
66
+ * agent_send can resume the agent (not for an in-memory parent, docs/06 §6).
67
+ */
68
+ export function nextStep(record: Pick<AgentRecord, "status" | "reason">, continuable = false): string | undefined {
69
+ switch (record.status) {
70
+ case "failed":
71
+ return "Retry with a new agent call, or do the task yourself.";
72
+ case "max_turns":
73
+ return continuable
74
+ ? "The subagent ran out of turns. Continue it with agent_send if the partial report is useful, or split the task."
75
+ : "The subagent ran out of turns. Use the partial report if it is useful, or split the task into smaller agent calls.";
76
+ case "context_limit":
77
+ // Never continuable: a continuation would start with the context already past the limit.
78
+ return "The subagent filled its context window before writing a report. Use the partial report if it is useful, or split the task into smaller agent calls.";
79
+ case "aborted":
80
+ // The parent interrupted itself, stopped it with agent_stop, or the session is ending: nothing to add.
81
+ if (record.reason === PARENT_INTERRUPTED || record.reason === STOPPED_BY_PARENT || record.reason === SESSION_ENDED) return undefined;
82
+ return "The user stopped this subagent. Do not restart it unless the user asks.";
83
+ default:
84
+ return undefined;
85
+ }
86
+ }
87
+
88
+ /** agent_send can resume it: its transcript exists and its context stayed below the limit (docs/06 §6). */
89
+ export function isContinuable(record: Pick<AgentRecord, "contextLimited">, transcript: string | undefined): boolean {
90
+ return transcript !== undefined && !record.contextLimited;
91
+ }
92
+
93
+ export function followUpHint(agentId: string): string {
94
+ return `Use agent_send with agent_id "${agentId}" to ask this subagent a follow-up; it keeps its context.`;
95
+ }
96
+
97
+ export interface FormatOptions {
98
+ maxChars: number;
99
+ /** Full report file; mentioned only when the inline text was truncated. */
100
+ resultFile?: string;
101
+ /** Child transcript; omitted when the child never wrote one. Its presence makes the agent continuable (see isContinuable). */
102
+ transcript?: string;
103
+ now?: number;
104
+ }
105
+
106
+ export function formatResult(record: AgentRecord, options: FormatOptions): { text: string; truncated: boolean } {
107
+ const report = record.text ?? "";
108
+ const cut = truncateReport(report, options.maxChars);
109
+ const attrs = [
110
+ `agent-id="${record.agentId}"`,
111
+ `type="${record.type}"`,
112
+ `status="${record.status}"`,
113
+ `turns="${record.stats.turns}"`,
114
+ `tool-calls="${record.stats.toolCalls}"`,
115
+ `duration="${formatDuration(durationOf(record, options.now))}"`,
116
+ ];
117
+ const body: string[] = [];
118
+ if (record.status === "completed") {
119
+ body.push(escapeReport(cut.text) || NO_FINAL_REPORT);
120
+ } else {
121
+ body.push(`reason: ${record.reason ?? record.status}`);
122
+ body.push(cut.text ? `partial report:\n${escapeReport(cut.text)}` : `partial report: ${NO_FINAL_REPORT}`);
123
+ }
124
+
125
+ const lines = [`<subagent-result ${attrs.join(" ")}>`, ...body, "</subagent-result>"];
126
+ if (cut.truncated && options.resultFile) {
127
+ lines.push(`full report: ${options.resultFile} (truncated at ${cut.text.length} of ${cut.total} characters; read the file for the rest)`);
128
+ }
129
+ for (const note of record.notes) lines.push(`note: ${note}`);
130
+ if (options.transcript) lines.push(`transcript: ${options.transcript}`);
131
+ const continuable = isContinuable(record, options.transcript);
132
+ if (continuable && record.status === "completed") lines.push(followUpHint(record.agentId));
133
+ const next = nextStep(record, continuable);
134
+ if (next) lines.push(next);
135
+ return { text: lines.join("\n"), truncated: cut.truncated };
136
+ }
137
+
138
+ /** Immediate result of a background agent or agent_send call (docs/03 §4.3). */
139
+ export function formatStarted(record: Pick<AgentRecord, "agentId" | "type" | "description">, position: number, verb: "Started" | "Continuing" = "Started"): string {
140
+ const queuedVerb = verb === "Started" ? "Queued" : "Queued continuation of";
141
+ const first =
142
+ position > 0
143
+ ? `${queuedVerb} subagent ${record.agentId} (${record.type}, position ${position}): ${record.description}`
144
+ : `${verb} subagent ${record.agentId} (${record.type}): ${record.description}`;
145
+ return [
146
+ first,
147
+ "You will be notified with a <subagent-notification> message when it finishes. Do not poll; continue with other work or end your turn.",
148
+ ].join("\n");
149
+ }
150
+
151
+ export interface NotificationLimits {
152
+ /** Per agent (notifyMaxChars). */
153
+ perAgent: number;
154
+ /** Whole batch (notifyBatchMaxChars). */
155
+ batch: number;
156
+ }
157
+
158
+ export interface NotificationItem {
159
+ record: AgentRecord;
160
+ /** Whether agent_send can continue it (isContinuable). */
161
+ continuable: boolean;
162
+ }
163
+
164
+ /** One summary line per agent, worded per status (docs/06 §5.1). */
165
+ export function summaryLine(record: Pick<AgentRecord, "agentId" | "description" | "status" | "reason" | "maxTurns">): string {
166
+ const head = `Subagent ${record.agentId} "${record.description}"`;
167
+ switch (record.status) {
168
+ case "completed":
169
+ return `${head} completed.`;
170
+ case "failed":
171
+ return `${head} failed: ${trimPeriod(record.reason ?? "unknown error")}.`;
172
+ case "max_turns":
173
+ return `${head} ran out of turns${record.maxTurns ? ` (${record.maxTurns})` : ""}.`;
174
+ case "context_limit":
175
+ return `${head} filled its context window before writing a report.`;
176
+ case "aborted":
177
+ return record.reason === STOPPED_BY_USER ? `${head} was stopped by the user.` : `${head} was aborted: ${trimPeriod(record.reason ?? "aborted")}.`;
178
+ default:
179
+ return `${head} is ${record.status}.`;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The model-facing <subagent-notification> for a batch (docs/06 §5.1, docs/05 §3.2): each report is cut to
185
+ * `perAgent` characters; once the batch budget is spent, later agents get only their header and result file.
186
+ */
187
+ export function formatNotification(items: readonly NotificationItem[], limits: NotificationLimits, now = Date.now()): string {
188
+ let budget = limits.batch;
189
+ const blocks: string[] = [];
190
+ for (const { record } of items) {
191
+ const attrs = [
192
+ `agent-id="${record.agentId}"`,
193
+ `type="${record.type}"`,
194
+ `status="${record.status}"`,
195
+ `turns="${record.stats.turns}"`,
196
+ `tool-calls="${record.stats.toolCalls}"`,
197
+ `duration="${formatDuration(durationOf(record, now))}"`,
198
+ ];
199
+ const lines = [`<agent ${attrs.join(" ")}>`, `<description>${escapeXml(record.description)}</description>`];
200
+ if (record.status !== "completed" && record.reason) lines.push(`<reason>${escapeXml(record.reason)}</reason>`);
201
+ const report = record.text ?? "";
202
+ const cut = truncateReport(report, limits.perAgent);
203
+ const body = escapeReport(cut.text);
204
+ const fits = body.length <= budget;
205
+ if (fits) {
206
+ budget -= body.length;
207
+ lines.push("<result>", body || NO_FINAL_REPORT, "</result>");
208
+ }
209
+ if ((cut.truncated || !fits) && record.resultFile) lines.push(`<result-file>${escapeXml(record.resultFile)}</result-file>`);
210
+ for (const note of record.notes) lines.push(`<note>${escapeXml(note)}</note>`);
211
+ lines.push("</agent>");
212
+ blocks.push(lines.join("\n"));
213
+ }
214
+ const summaries = items.map(({ record }) => summaryLine(record));
215
+ const out = ["<subagent-notification>", ...blocks, "</subagent-notification>", "", ...summaries];
216
+ if (items.some((item) => item.continuable)) out.push("Use agent_send with an agent id to ask a follow-up; the subagent keeps its context.");
217
+ return out.join("\n");
218
+ }
219
+
220
+ function trimPeriod(text: string): string {
221
+ return text.replace(/[.\s]+$/, "");
222
+ }
223
+
224
+ function escapeXml(text: string): string {
225
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
226
+ }
package/src/run.ts ADDED
@@ -0,0 +1,204 @@
1
+ // One run of a child session: prompt -> judge the outcome -> extract the final report (docs/02 §7-§9).
2
+
3
+ import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
4
+
5
+ import type { ThinkingLevel } from "./config.js";
6
+ import type { ModelRef } from "./models.js";
7
+ import { CONTEXT_GRACE_TURNS, ChildObserver, type ContextUsageLike, type ProgressSnapshot } from "./observer.js";
8
+ import { CONTEXT_BUDGET_MESSAGE_TYPE, contextBudgetReminder, TURN_BUDGET_MESSAGE_TYPE, turnBudgetReminder } from "./prompts.js";
9
+ import type { AgentType } from "./types.js";
10
+
11
+ export type AgentStatus = "queued" | "running" | "completed" | "failed" | "aborted" | "max_turns" | "context_limit";
12
+ export type TerminalStatus = Exclude<AgentStatus, "queued" | "running">;
13
+
14
+ export const PARENT_INTERRUPTED = "parent interrupted";
15
+ export const SESSION_ENDED = "session ended";
16
+ /** agent_stop: the model stopped it, so it is not notified (docs/06 §5.2). */
17
+ export const STOPPED_BY_PARENT = "stopped by parent";
18
+ /** HUD focus mode, the detail overlay or the /agents list: the model is notified. */
19
+ export const STOPPED_BY_USER = "stopped by the user";
20
+ export const NO_FINAL_REPORT = "(no final report)";
21
+
22
+ /** The narrow view of a pi AgentSession that runs depend on; tests substitute a fake. */
23
+ export interface ChildSession {
24
+ readonly sessionFile: string | undefined;
25
+ /** provider/id the session actually uses, when it has a model. */
26
+ readonly model: string | undefined;
27
+ readonly messages: readonly unknown[];
28
+ /** AgentSession.getContextUsage: undefined when the model has no known context window. */
29
+ contextUsage(): ContextUsageLike | undefined;
30
+ subscribe(listener: (event: AgentSessionEvent) => void): () => void;
31
+ /** Sends the task as the first user message, verbatim (no prompt-template expansion). */
32
+ prompt(text: string): Promise<void>;
33
+ abort(): Promise<void>;
34
+ /** Context-only custom message delivered as steering (sendCustomMessage, deliverAs: "steer"). */
35
+ steer(customType: string, content: string): void;
36
+ /** A user message delivered after the current turn (AgentSession.steer): agent_send to a running agent. */
37
+ steerUser(text: string): Promise<void>;
38
+ dispose(): void;
39
+ }
40
+
41
+ export interface ChildSpec {
42
+ agentId: string;
43
+ description: string;
44
+ /** Effective type: config overrides and the Windows shell swap already applied. */
45
+ type: AgentType;
46
+ cwd: string;
47
+ model?: ModelRef;
48
+ thinking?: ThinkingLevel;
49
+ /** Directory for the child session file; undefined for an in-memory parent. */
50
+ sessionDir?: string;
51
+ parentSessionFile?: string;
52
+ /** agent_send to a finished agent: reopen this transcript instead of creating a new one (docs/06 §6). */
53
+ resumeFile?: string;
54
+ }
55
+
56
+ export interface ChildSessionFactory {
57
+ create(spec: ChildSpec): Promise<ChildSession>;
58
+ }
59
+
60
+ export interface RunOutcome {
61
+ status: TerminalStatus;
62
+ reason?: string;
63
+ /** Text of the final assistant message; empty when there is none. */
64
+ text: string;
65
+ notes: string[];
66
+ }
67
+
68
+ interface StopRequest {
69
+ status: "aborted" | "max_turns" | "context_limit";
70
+ reason: string;
71
+ }
72
+
73
+ export interface ChildRunOptions {
74
+ maxTurns: number;
75
+ /** Percent of the context window that starts the wrap-up (docs/02 §9); undefined: no context budget. */
76
+ contextLimit?: number;
77
+ cwd?: string;
78
+ onProgress?: (snapshot: ProgressSnapshot) => void;
79
+ }
80
+
81
+ export class ChildRun {
82
+ readonly observer: ChildObserver;
83
+ private stopRequest: StopRequest | undefined;
84
+
85
+ constructor(
86
+ private readonly session: ChildSession,
87
+ private readonly options: ChildRunOptions,
88
+ ) {
89
+ this.observer = new ChildObserver({
90
+ maxTurns: options.maxTurns,
91
+ contextLimit: options.contextLimit,
92
+ cwd: options.cwd,
93
+ onBudgetReminder: (left) => session.steer(TURN_BUDGET_MESSAGE_TYPE, turnBudgetReminder(left)),
94
+ onTurnLimit: () => void this.stop("max_turns", `ran out of turns (${options.maxTurns})`),
95
+ onContextReminder: (percent) => session.steer(CONTEXT_BUDGET_MESSAGE_TYPE, contextBudgetReminder(percent)),
96
+ onContextLimit: () =>
97
+ void this.stop(
98
+ "context_limit",
99
+ `still calling tools ${CONTEXT_GRACE_TURNS} turns after its context passed ${options.contextLimit}%`,
100
+ ),
101
+ onChange: () => options.onProgress?.(this.observer.snapshot()),
102
+ contextUsage: () => session.contextUsage(),
103
+ });
104
+ }
105
+
106
+ get stopped(): StopRequest | undefined {
107
+ return this.stopRequest;
108
+ }
109
+
110
+ /** First stop request wins; abort() waits for the session to become idle (agent-session.ts:2519). */
111
+ stop(status: StopRequest["status"], reason: string): Promise<void> {
112
+ this.stopRequest ??= { status, reason };
113
+ return this.session.abort();
114
+ }
115
+
116
+ async run(task: string, signal?: AbortSignal): Promise<RunOutcome> {
117
+ // abort() before the run starts has no effect, so check first (docs/02 §8).
118
+ if (signal?.aborted) return { status: "aborted", reason: PARENT_INTERRUPTED, text: "", notes: [] };
119
+ if (this.stopRequest) return { ...this.stopRequest, text: "", notes: [] };
120
+
121
+ const unsubscribe = this.session.subscribe((event) => {
122
+ this.observer.onEvent(event);
123
+ // A stop requested while prompt() was still in preflight was a no-op; repeat it once the run starts.
124
+ if (this.stopRequest && (event.type === "agent_start" || event.type === "turn_start")) void this.session.abort();
125
+ });
126
+ const onAbort = (): void => void this.stop("aborted", PARENT_INTERRUPTED);
127
+ signal?.addEventListener("abort", onAbort, { once: true });
128
+
129
+ // A resumed session (agent_send) already holds earlier runs; judge only what this run added.
130
+ const firstMessage = this.session.messages.length;
131
+ let thrown: unknown;
132
+ try {
133
+ await this.session.prompt(task);
134
+ } catch (error) {
135
+ thrown = error;
136
+ } finally {
137
+ signal?.removeEventListener("abort", onAbort);
138
+ unsubscribe();
139
+ }
140
+ return judge(this.session.messages.slice(firstMessage), this.stopRequest, thrown);
141
+ }
142
+ }
143
+
144
+ interface AssistantLike {
145
+ role: "assistant";
146
+ stopReason?: string;
147
+ errorMessage?: string;
148
+ content?: Array<{ type: string; text?: string }>;
149
+ }
150
+
151
+ function isAssistant(message: unknown): message is AssistantLike {
152
+ return typeof message === "object" && message !== null && (message as { role?: unknown }).role === "assistant";
153
+ }
154
+
155
+ export function assistantText(message: AssistantLike): string {
156
+ return (message.content ?? [])
157
+ .filter((part) => part.type === "text" && typeof part.text === "string")
158
+ .map((part) => part.text)
159
+ .join("")
160
+ .trim();
161
+ }
162
+
163
+ /**
164
+ * The final report: text of the last assistant message. Trailing aborted messages without text are skipped:
165
+ * they are stubs an abort leaves, not the model's last words. After a stop we requested (max_turns, context_limit,
166
+ * parent interrupted, shutdown) every empty trailing assistant message is such a stub, whatever its stopReason:
167
+ * a request aborted before it streamed can be recorded as "error" (seen with pi-ai's faux provider).
168
+ */
169
+ export function finalReport(messages: readonly unknown[], afterStop = false): string {
170
+ for (let i = messages.length - 1; i >= 0; i--) {
171
+ const message = messages[i];
172
+ if (!isAssistant(message)) continue;
173
+ const text = assistantText(message);
174
+ if (!text && (afterStop || message.stopReason === "aborted")) continue;
175
+ return text;
176
+ }
177
+ return "";
178
+ }
179
+
180
+ export function judge(messages: readonly unknown[], stopRequest: StopRequest | undefined, thrown: unknown): RunOutcome {
181
+ const text = finalReport(messages, stopRequest !== undefined);
182
+ if (stopRequest) return { status: stopRequest.status, reason: stopRequest.reason, text, notes: [] };
183
+ if (thrown !== undefined) return { status: "failed", reason: errorMessage(thrown), text, notes: [] };
184
+
185
+ const last = [...messages].reverse().find(isAssistant);
186
+ if (!last) return { status: "failed", reason: "the subagent produced no response", text, notes: [] };
187
+ switch (last.stopReason) {
188
+ case "stop":
189
+ return { status: "completed", text, notes: [] };
190
+ case "length":
191
+ return { status: "completed", text, notes: ["the final message hit the output token limit"] };
192
+ case "error":
193
+ // Provider errors are recorded on the message, not thrown.
194
+ return { status: "failed", reason: `provider error: ${last.errorMessage ?? "unknown error"}`, text, notes: [] };
195
+ case "aborted":
196
+ return { status: "aborted", reason: last.errorMessage ?? "aborted", text, notes: [] };
197
+ default:
198
+ return { status: "failed", reason: `unexpected stop reason: ${last.stopReason ?? "none"}`, text, notes: [] };
199
+ }
200
+ }
201
+
202
+ export function errorMessage(error: unknown): string {
203
+ return error instanceof Error ? error.message : String(error);
204
+ }
@@ -0,0 +1,140 @@
1
+ // Settings exposed to the /shizuku panel (pi-shizuku-settings): the scalar fields of pi-subagent.json. The
2
+ // per-type overrides (`types`) stay a hand-edited table; the panel only shows how many there are.
3
+
4
+ import { CONFIG_FILE_NAME, DEFAULT_CONFIG, parseConfig, saveConfigPatch, type SubagentConfig } from "./config.js";
5
+ import type { SetResult, SettingApplies, SettingItem, SettingValue } from "./shizuku-settings.js";
6
+
7
+ type IntKey = "maxConcurrent" | "resultMaxChars" | "notifyMaxChars" | "notifyBatchMaxChars" | "retentionDays";
8
+ type Key = IntKey | "confirmStop" | "childExtensions";
9
+
10
+ interface IntEntry {
11
+ key: IntKey;
12
+ label: string;
13
+ description: string;
14
+ /** parseConfig's lower bound. */
15
+ min: number;
16
+ /** Upper bound of the panel's ←→ only; parseConfig has none. */
17
+ max: number;
18
+ step: number;
19
+ applies: SettingApplies;
20
+ }
21
+
22
+ const INT_ENTRIES: readonly IntEntry[] = [
23
+ {
24
+ key: "maxConcurrent",
25
+ label: "Max concurrent",
26
+ description: "Agents running at the same time; further launches wait in the queue.",
27
+ min: 1,
28
+ max: 64,
29
+ step: 1,
30
+ applies: "live",
31
+ },
32
+ {
33
+ key: "resultMaxChars",
34
+ label: "Result max chars",
35
+ description: "Longest agent result handed back to the parent; the full text goes to a file.",
36
+ min: 1000,
37
+ max: 1_000_000,
38
+ step: 1000,
39
+ applies: "live",
40
+ },
41
+ {
42
+ key: "notifyMaxChars",
43
+ label: "Notify max chars",
44
+ description: "Longest result per agent in a background notification.",
45
+ min: 1000,
46
+ max: 1_000_000,
47
+ step: 1000,
48
+ applies: "live",
49
+ },
50
+ {
51
+ key: "notifyBatchMaxChars",
52
+ label: "Notify batch max chars",
53
+ description: "Longest background notification, all agents in it together.",
54
+ min: 1000,
55
+ max: 1_000_000,
56
+ step: 1000,
57
+ applies: "live",
58
+ },
59
+ {
60
+ key: "retentionDays",
61
+ label: "Retention days",
62
+ description: "Child sessions of other parent sessions older than this are deleted when a session starts.",
63
+ min: 1,
64
+ max: 3650,
65
+ step: 1,
66
+ applies: "new-session",
67
+ },
68
+ ];
69
+
70
+ export function settingsItems(config: SubagentConfig): SettingItem[] {
71
+ const overrides = Object.keys(config.types).length;
72
+ return [
73
+ ...INT_ENTRIES.map(
74
+ (entry): SettingItem => ({
75
+ id: entry.key,
76
+ kind: "int",
77
+ label: entry.label,
78
+ description: entry.description,
79
+ value: config[entry.key],
80
+ default: DEFAULT_CONFIG[entry.key],
81
+ min: entry.min,
82
+ max: entry.max,
83
+ step: entry.step,
84
+ applies: entry.applies,
85
+ }),
86
+ ),
87
+ {
88
+ id: "confirmStop",
89
+ kind: "bool",
90
+ label: "Confirm stop",
91
+ description: "x stops an agent only when pressed twice on it: the /agents list, the detail overlay, HUD focus mode.",
92
+ value: config.confirmStop,
93
+ default: DEFAULT_CONFIG.confirmStop,
94
+ applies: "live",
95
+ },
96
+ {
97
+ id: "childExtensions",
98
+ kind: "text",
99
+ label: "Child extensions",
100
+ description: "Extensions a child session may load: package names or paths, comma separated. Used by agents started afterwards.",
101
+ value: config.childExtensions.join(", "),
102
+ default: DEFAULT_CONFIG.childExtensions.join(", "),
103
+ placeholder: "pi-dsweb, …",
104
+ applies: "live",
105
+ },
106
+ {
107
+ id: "types",
108
+ kind: "info",
109
+ label: "Type overrides",
110
+ description: "Per-type model / thinking / max_turns / context_limit. Edit the file, then /agents reload.",
111
+ value: `${overrides} override${overrides === 1 ? "" : "s"} · edit ${CONFIG_FILE_NAME}`,
112
+ },
113
+ ];
114
+ }
115
+
116
+ function isKey(id: string): id is Key {
117
+ return id === "confirmStop" || id === "childExtensions" || INT_ENTRIES.some((entry) => entry.key === id);
118
+ }
119
+
120
+ /**
121
+ * Validate one value with parseConfig, save it into the file and hand the parsed field to `apply`, so the
122
+ * running session uses it at once.
123
+ */
124
+ export function setSetting(path: string, id: string, value: SettingValue, apply: (patch: Partial<SubagentConfig>) => void): SetResult {
125
+ if (!isKey(id)) return { ok: false, error: `unknown setting ${id}` };
126
+ let raw: unknown = value;
127
+ if (id === "childExtensions") {
128
+ if (typeof value !== "string") return { ok: false, error: "childExtensions must be text" };
129
+ raw = value.split(",").map((entry) => entry.trim()).filter(Boolean);
130
+ }
131
+ const parsed = parseConfig({ [id]: raw });
132
+ if (parsed.warnings.length > 0) return { ok: false, error: parsed.warnings.join("; ") };
133
+ try {
134
+ saveConfigPatch(path, { [id]: raw });
135
+ } catch (error) {
136
+ return { ok: false, error: `could not save ${path}: ${(error as Error).message}` };
137
+ }
138
+ apply({ [id]: parsed.config[id] });
139
+ return { ok: true };
140
+ }
@@ -0,0 +1,92 @@
1
+ // pi-shizuku-settings protocol, version 1 (pi-shizuku-settings/DESIGN.md §3).
2
+ //
3
+ // This file is copied verbatim into every plugin that exposes settings, as `src/shizuku-settings.ts`. The
4
+ // plugins stay independent packages: none of them depends on pi-shizuku-settings, and they work the same when
5
+ // it is not installed. Edit the copy in pi-shizuku-settings first, then copy it over; do not rewrite it per plugin.
6
+ //
7
+ // How it works: the /shizuku panel emits SETTINGS_CHANNEL on pi.events with a CollectRequest. pi's event bus
8
+ // calls listeners synchronously, so every plugin that called exposeSettings() hands its provider over before
9
+ // emit() returns. The provider is a live object: the panel reads items() on every render and calls set() to
10
+ // change a value. Validation, saving and applying stay in the plugin.
11
+
12
+ /** pi.events channel the panel emits to collect providers. */
13
+ export const SETTINGS_CHANNEL = "shizuku-settings:collect";
14
+ /** Bumped on an incompatible change; a provider for another version is ignored by the panel. */
15
+ export const SETTINGS_PROTOCOL = 1;
16
+
17
+ /**
18
+ * When a change takes effect.
19
+ * live: right away. reload: after /reload. new-session: from the next session (/new, resume). restart: after pi restarts.
20
+ */
21
+ export type SettingApplies = "live" | "reload" | "new-session" | "restart";
22
+
23
+ interface SettingBase {
24
+ /** Unique inside the provider; dotted paths are fine (`thinking.lines`). */
25
+ id: string;
26
+ /** Short English label (design_style.md §9). */
27
+ label: string;
28
+ /** One or two sentences, shown under the list for the selected row. */
29
+ description?: string;
30
+ /** Default: live. */
31
+ applies?: SettingApplies;
32
+ /** Set when something outside the file decides the value (an environment variable); the panel shows it read-only with this text. */
33
+ locked?: string;
34
+ }
35
+
36
+ export type SettingItem =
37
+ | (SettingBase & { kind: "bool"; value: boolean; default: boolean })
38
+ | (SettingBase & { kind: "enum"; value: string; default: string; values: readonly string[] })
39
+ | (SettingBase & { kind: "int"; value: number; default: number; min: number; max: number; step?: number })
40
+ /** Free text; the empty string means "not set" when the default is empty. */
41
+ | (SettingBase & { kind: "text"; value: string; default: string; placeholder?: string })
42
+ /** Read-only fact (a key is configured, where a file lives). */
43
+ | (SettingBase & { kind: "info"; value: string })
44
+ /** Opens another panel: the settings panel closes and puts `command` in the editor. */
45
+ | (SettingBase & { kind: "command"; command: string });
46
+
47
+ export type SettingValue = boolean | number | string;
48
+
49
+ export type SetResult = { ok: true; message?: string } | { ok: false; error: string };
50
+
51
+ export interface SettingsProvider {
52
+ /** Plugin name without the npm scope, e.g. `pi-bettertui`. Unique; a later registration with the same id replaces the earlier one. */
53
+ id: string;
54
+ /** Shown in the plugin list; usually the package name. */
55
+ title: string;
56
+ /** One line, shown next to the title. */
57
+ description?: string;
58
+ /** Where the values are saved, shown on the panel's top edge. */
59
+ file?: string;
60
+ /** Current items, read on every render. */
61
+ items(): readonly SettingItem[];
62
+ /** Validate, save and apply one value. The panel resets a value by passing the item's default. */
63
+ set(id: string, value: SettingValue): SetResult | Promise<SetResult>;
64
+ }
65
+
66
+ export interface CollectRequest {
67
+ protocol: number;
68
+ register(provider: SettingsProvider): void;
69
+ }
70
+
71
+ export function isCollectRequest(data: unknown): data is CollectRequest {
72
+ if (typeof data !== "object" || data === null) return false;
73
+ const request = data as Partial<CollectRequest>;
74
+ return request.protocol === SETTINGS_PROTOCOL && typeof request.register === "function";
75
+ }
76
+
77
+ interface SettingsHost {
78
+ events: { on(channel: string, handler: (data: unknown) => void): () => void };
79
+ on(event: "session_shutdown", handler: () => void): void;
80
+ }
81
+
82
+ /**
83
+ * Answer the panel's collect requests with `provider` until this extension runtime shuts down. pi builds a new
84
+ * runtime on /reload, /new and resume, and that runtime calls this again, so the panel never sees a stale one.
85
+ */
86
+ export function exposeSettings(pi: SettingsHost, provider: SettingsProvider): () => void {
87
+ const off = pi.events.on(SETTINGS_CHANNEL, (data) => {
88
+ if (isCollectRequest(data)) data.register(provider);
89
+ });
90
+ pi.on("session_shutdown", () => off());
91
+ return off;
92
+ }