@buyi1net/pi-toolkit 0.0.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.
Files changed (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +45 -0
  3. package/assembler.ts +127 -0
  4. package/config.ts +201 -0
  5. package/i18n.ts +693 -0
  6. package/index.ts +99 -0
  7. package/menu/items.ts +264 -0
  8. package/menu/panels.ts +91 -0
  9. package/menu/settings-list.ts +84 -0
  10. package/menu/theme.ts +31 -0
  11. package/menu/toolkit-menu.ts +139 -0
  12. package/module.ts +156 -0
  13. package/modules/eyes/chain.ts +173 -0
  14. package/modules/eyes/config.ts +319 -0
  15. package/modules/eyes/index.ts +161 -0
  16. package/modules/eyes/menu.ts +828 -0
  17. package/modules/eyes/pi-model-backend.ts +245 -0
  18. package/modules/eyes/resilience.ts +161 -0
  19. package/modules/eyes/vision-bridge.ts +232 -0
  20. package/modules/eyes/vision-cache.ts +86 -0
  21. package/modules/eyes/vision-json.ts +19 -0
  22. package/modules/eyes/vision-preprocess.ts +192 -0
  23. package/modules/eyes/vision-probe.ts +21 -0
  24. package/modules/eyes/vision-prompt.ts +90 -0
  25. package/modules/eyes/vision-tool.ts +59 -0
  26. package/modules/eyes/vision-types.ts +33 -0
  27. package/modules/index.ts +10 -0
  28. package/modules/subagents/agents/researcher.md +51 -0
  29. package/modules/subagents/agents/scout.md +40 -0
  30. package/modules/subagents/agents/worker.md +79 -0
  31. package/modules/subagents/config.json.example +6 -0
  32. package/modules/subagents/config.ts +144 -0
  33. package/modules/subagents/index.ts +91 -0
  34. package/modules/subagents/menu.ts +388 -0
  35. package/modules/subagents/src/activity.ts +511 -0
  36. package/modules/subagents/src/agents.ts +126 -0
  37. package/modules/subagents/src/command.ts +37 -0
  38. package/modules/subagents/src/dependencies.ts +246 -0
  39. package/modules/subagents/src/diagnostics.ts +13 -0
  40. package/modules/subagents/src/display.ts +94 -0
  41. package/modules/subagents/src/headless.ts +342 -0
  42. package/modules/subagents/src/herdr.ts +203 -0
  43. package/modules/subagents/src/index.ts +2798 -0
  44. package/modules/subagents/src/inspect-tool.ts +839 -0
  45. package/modules/subagents/src/launch-config.ts +196 -0
  46. package/modules/subagents/src/layout-budget.ts +26 -0
  47. package/modules/subagents/src/list-tool.ts +292 -0
  48. package/modules/subagents/src/message-tool.ts +808 -0
  49. package/modules/subagents/src/names.ts +17 -0
  50. package/modules/subagents/src/pane-layout.ts +49 -0
  51. package/modules/subagents/src/params.ts +145 -0
  52. package/modules/subagents/src/renderers.ts +181 -0
  53. package/modules/subagents/src/result.ts +43 -0
  54. package/modules/subagents/src/retention.ts +114 -0
  55. package/modules/subagents/src/route-error.ts +212 -0
  56. package/modules/subagents/src/routing.ts +235 -0
  57. package/modules/subagents/src/runtime-registry.ts +159 -0
  58. package/modules/subagents/src/session.ts +801 -0
  59. package/modules/subagents/src/status.ts +513 -0
  60. package/modules/subagents/src/stop-tool.ts +235 -0
  61. package/modules/subagents/src/subagent-done.ts +590 -0
  62. package/modules/subagents/src/subagent-tool.ts +1155 -0
  63. package/modules/subagents/src/surface.ts +355 -0
  64. package/modules/subagents/src/team-dispatch-tool.ts +219 -0
  65. package/modules/subagents/src/team.ts +232 -0
  66. package/modules/subagents/src/tmux.ts +210 -0
  67. package/modules/subagents/src/tools/safe-bash.ts +72 -0
  68. package/modules/subagents/src/types.ts +131 -0
  69. package/modules/tui/adapter/provider-usage.ts +143 -0
  70. package/modules/tui/config.ts +50 -0
  71. package/modules/tui/index.ts +120 -0
  72. package/modules/tui/kernel/pkg/shared/grok-subscription.ts +169 -0
  73. package/modules/tui/kernel/pkg/shared/official-subscription.ts +237 -0
  74. package/modules/tui/kernel/pkg/shared/provider-catalog.ts +367 -0
  75. package/modules/tui/kernel/pkg/shared/provider-contracts.ts +150 -0
  76. package/modules/tui/kernel/pkg/shared/provider-display.ts +55 -0
  77. package/modules/tui/kernel/pkg/shared/provider-parsers.ts +171 -0
  78. package/modules/tui/kernel/pkg/shared/volcengine.ts +191 -0
  79. package/modules/tui/kernel/pkg/shared/zhipu.ts +149 -0
  80. package/modules/tui/kernel/pkg/usage-core/index.ts +335 -0
  81. package/modules/tui/kernel/pkg/usage-core/provider-routes.ts +187 -0
  82. package/modules/tui/kernel/pkg/usage-node/index.ts +635 -0
  83. package/modules/tui/kernel/pkg/usage-node/provider-usage.ts +388 -0
  84. package/modules/tui/kernel/usage-core.ts +2 -0
  85. package/modules/tui/kernel/usage-node.ts +2 -0
  86. package/modules/tui/menu.ts +418 -0
  87. package/modules/tui/plugin/editor.ts +396 -0
  88. package/modules/tui/plugin/footer.ts +161 -0
  89. package/modules/tui/plugin/index.ts +30 -0
  90. package/modules/tui/plugin/lifecycle.ts +637 -0
  91. package/modules/tui/plugin/package-order.ts +169 -0
  92. package/modules/tui/plugin/screen-transition.ts +203 -0
  93. package/modules/tui/plugin/settings-config.ts +297 -0
  94. package/modules/tui/plugin/status-sources.ts +49 -0
  95. package/modules/tui/plugin/transition-gate.ts +261 -0
  96. package/modules/tui/renderer/custom-header.ts +157 -0
  97. package/modules/tui/renderer/editor.ts +70 -0
  98. package/modules/tui/renderer/header.ts +72 -0
  99. package/modules/tui/renderer/icons.ts +149 -0
  100. package/modules/tui/renderer/pi-installer-logo.ts +194 -0
  101. package/modules/tui/status/auto-compaction.ts +67 -0
  102. package/modules/tui/status/project-status.ts +655 -0
  103. package/modules/tui/status/provider-status.ts +120 -0
  104. package/modules/tui/status/runtime-status.ts +307 -0
  105. package/modules/tui/status/session-status.ts +325 -0
  106. package/modules/tui/status/status-config.ts +95 -0
  107. package/modules/tui/status/status-segments.ts +263 -0
  108. package/modules/tui/status/turn-telemetry.ts +466 -0
  109. package/modules/tui/themes/LICENSE.pi-themes-bundle +21 -0
  110. package/modules/tui/themes/UPSTREAM.md +7 -0
  111. package/modules/tui/themes/catppuccin-latte.json +80 -0
  112. package/modules/tui/themes/catppuccin-mocha.json +79 -0
  113. package/modules/tui/themes/crimson-noir.json +85 -0
  114. package/modules/tui/themes/dracula.json +79 -0
  115. package/modules/tui/themes/everforest-dark.json +85 -0
  116. package/modules/tui/themes/gruvbox-dark.json +85 -0
  117. package/modules/tui/themes/gruvbox-light.json +85 -0
  118. package/modules/tui/themes/matrix.json +85 -0
  119. package/modules/tui/themes/nord.json +85 -0
  120. package/modules/tui/themes/one-dark.json +85 -0
  121. package/modules/tui/themes/rose-pine-dawn.json +85 -0
  122. package/modules/tui/themes/rose-pine.json +85 -0
  123. package/modules/tui/themes/solarized-dark.json +85 -0
  124. package/modules/tui/themes/solarized-light.json +85 -0
  125. package/modules/tui/themes/tokyo-night-storm.json +79 -0
  126. package/modules/tui/themes/tokyo-night.json +79 -0
  127. package/package.json +28 -0
  128. package/services.ts +38 -0
  129. package/toolkit.ts +147 -0
@@ -0,0 +1,511 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ export type SubagentActivityPhase = "starting" | "active" | "waiting" | "done";
5
+ export type SubagentActivityScope = "agent" | "turn" | "provider" | "streaming" | "tool";
6
+
7
+ export type SubagentActivityEvent =
8
+ | "session_start"
9
+ | "input"
10
+ | "before_agent_start"
11
+ | "agent_start"
12
+ | "agent_end"
13
+ | "turn_start"
14
+ | "turn_end"
15
+ | "before_provider_request"
16
+ | "after_provider_response"
17
+ | "message_update"
18
+ | "tool_execution_start"
19
+ | "tool_call"
20
+ | "tool_execution_update"
21
+ | "tool_result"
22
+ | "tool_execution_end"
23
+ | "ask_question"
24
+ | "session_shutdown";
25
+
26
+ export interface SubagentActivityState {
27
+ version: 1;
28
+ runningChildId: string;
29
+ createdAt: number;
30
+ updatedAt: number;
31
+ sequence: number;
32
+ latestEvent: SubagentActivityEvent;
33
+ phase: SubagentActivityPhase;
34
+ agentActive: boolean;
35
+ turnActive: boolean;
36
+ providerActive: boolean;
37
+ toolActive: boolean;
38
+ activeScope?: SubagentActivityScope;
39
+ activeSince?: number;
40
+ waitingSince?: number;
41
+ turnIndex?: number;
42
+ messageEventType?: string;
43
+ toolCallId?: string;
44
+ toolName?: string;
45
+ toolStartedAt?: number;
46
+ toolEndedAt?: number;
47
+ }
48
+
49
+ export type ActivityReadResult =
50
+ | { ok: true; activity: SubagentActivityState }
51
+ | { ok: false; reason: "missing" | "invalid" | "wrong-id"; error?: string };
52
+
53
+ export type SubagentShutdownReason = "quit" | "reload" | "new" | "resume" | "fork";
54
+
55
+ export interface SubagentActivityRecorder {
56
+ sessionStart(): void;
57
+ input(): void;
58
+ beforeAgentStart(): void;
59
+ agentStart(): void;
60
+ agentEndWaiting(): void;
61
+ agentEndDone(): void;
62
+ turnStart(turnIndex?: number): void;
63
+ turnEnd(turnIndex?: number): void;
64
+ beforeProviderRequest(): void;
65
+ afterProviderResponse(): void;
66
+ messageUpdate(messageEventType?: string): void;
67
+ toolExecutionStart(toolCallId?: string, toolName?: string): void;
68
+ toolCall(toolCallId?: string, toolName?: string): void;
69
+ toolExecutionUpdate(toolCallId?: string, toolName?: string): void;
70
+ toolResult(toolCallId?: string, toolName?: string): void;
71
+ toolExecutionEnd(toolCallId?: string, toolName?: string): void;
72
+ askQuestion(): void;
73
+ sessionShutdown(reason: SubagentShutdownReason): void;
74
+ }
75
+
76
+ const ACTIVITY_UPDATE_THROTTLE_MS = 500;
77
+ const MAX_WRITE_FAILURES = 3;
78
+ const KNOWN_PHASES = new Set<SubagentActivityPhase>(["starting", "active", "waiting", "done"]);
79
+ const KNOWN_SCOPES = new Set<SubagentActivityScope>(["agent", "turn", "provider", "streaming", "tool"]);
80
+ const KNOWN_EVENTS = new Set<SubagentActivityEvent>([
81
+ "session_start",
82
+ "input",
83
+ "before_agent_start",
84
+ "agent_start",
85
+ "agent_end",
86
+ "turn_start",
87
+ "turn_end",
88
+ "before_provider_request",
89
+ "after_provider_response",
90
+ "message_update",
91
+ "tool_execution_start",
92
+ "tool_call",
93
+ "tool_execution_update",
94
+ "tool_result",
95
+ "tool_execution_end",
96
+ "ask_question",
97
+ "session_shutdown",
98
+ ]);
99
+ const MAX_ACTIVITY_STRING_LENGTH = 200;
100
+
101
+ export function getSubagentActivityFile(artifactDir: string, runningChildId: string): string {
102
+ return join(artifactDir, "subagent-activity", `${runningChildId}.json`);
103
+ }
104
+
105
+ function requireObject(value: unknown): Record<string, unknown> | null {
106
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return null;
107
+ return value as Record<string, unknown>;
108
+ }
109
+
110
+ function validateFiniteNumber(object: Record<string, unknown>, fieldName: string): string | null {
111
+ return Number.isFinite(object[fieldName]) ? null : `${fieldName} must be finite`;
112
+ }
113
+
114
+ function validateOptionalFiniteNumber(object: Record<string, unknown>, fieldName: string): string | null {
115
+ const value = object[fieldName];
116
+ return value == null || Number.isFinite(value) ? null : `${fieldName} must be finite when present`;
117
+ }
118
+
119
+ function validateInteger(object: Record<string, unknown>, fieldName: string): string | null {
120
+ return Number.isInteger(object[fieldName]) ? null : `${fieldName} must be an integer`;
121
+ }
122
+
123
+ function validateOptionalInteger(object: Record<string, unknown>, fieldName: string): string | null {
124
+ const value = object[fieldName];
125
+ return value == null || Number.isInteger(value) ? null : `${fieldName} must be an integer when present`;
126
+ }
127
+
128
+ function validateBoolean(object: Record<string, unknown>, fieldName: string): string | null {
129
+ return typeof object[fieldName] === "boolean" ? null : `${fieldName} must be a boolean`;
130
+ }
131
+
132
+ function validateOptionalActivityString(object: Record<string, unknown>, fieldName: string): string | null {
133
+ const value = object[fieldName];
134
+ if (value == null) return null;
135
+ if (typeof value !== "string") return `${fieldName} must be a string when present`;
136
+ if (/\r|\n/.test(value)) return `${fieldName} must not contain newlines`;
137
+ return value.length <= MAX_ACTIVITY_STRING_LENGTH ? null : `${fieldName} is too long`;
138
+ }
139
+
140
+ function invalidActivity(error: string): ActivityReadResult {
141
+ return { ok: false, reason: "invalid", error };
142
+ }
143
+
144
+ function validateActivity(value: unknown, expectedRunningChildId: string): ActivityReadResult {
145
+ const object = requireObject(value);
146
+ if (!object) return invalidActivity("activity must be an object");
147
+ if (object.version !== 1) return invalidActivity("unsupported activity version");
148
+ if (typeof object.runningChildId !== "string") return invalidActivity("runningChildId must be a string");
149
+ if (object.runningChildId !== expectedRunningChildId) return { ok: false, reason: "wrong-id" };
150
+ if (typeof object.latestEvent !== "string" || !KNOWN_EVENTS.has(object.latestEvent as SubagentActivityEvent)) {
151
+ return invalidActivity("unknown latestEvent");
152
+ }
153
+ if (typeof object.phase !== "string" || !KNOWN_PHASES.has(object.phase as SubagentActivityPhase)) {
154
+ return invalidActivity("unknown activity phase");
155
+ }
156
+ if (
157
+ object.activeScope != null &&
158
+ (typeof object.activeScope !== "string" || !KNOWN_SCOPES.has(object.activeScope as SubagentActivityScope))
159
+ ) {
160
+ return invalidActivity("unknown activeScope");
161
+ }
162
+
163
+ const validationError = [
164
+ validateFiniteNumber(object, "createdAt"),
165
+ validateFiniteNumber(object, "updatedAt"),
166
+ validateInteger(object, "sequence"),
167
+ validateBoolean(object, "agentActive"),
168
+ validateBoolean(object, "turnActive"),
169
+ validateBoolean(object, "providerActive"),
170
+ validateBoolean(object, "toolActive"),
171
+ validateOptionalFiniteNumber(object, "activeSince"),
172
+ validateOptionalFiniteNumber(object, "waitingSince"),
173
+ validateOptionalInteger(object, "turnIndex"),
174
+ validateOptionalFiniteNumber(object, "toolStartedAt"),
175
+ validateOptionalFiniteNumber(object, "toolEndedAt"),
176
+ validateOptionalActivityString(object, "messageEventType"),
177
+ validateOptionalActivityString(object, "toolCallId"),
178
+ validateOptionalActivityString(object, "toolName"),
179
+ ].find((error) => error != null);
180
+ if (validationError) return invalidActivity(validationError);
181
+
182
+ return { ok: true, activity: object as unknown as SubagentActivityState };
183
+ }
184
+
185
+ export function readSubagentActivityFile(
186
+ activityFile: string,
187
+ expectedRunningChildId: string,
188
+ ): ActivityReadResult {
189
+ if (!existsSync(activityFile)) return { ok: false, reason: "missing" };
190
+
191
+ let parsed: unknown;
192
+ try {
193
+ parsed = JSON.parse(readFileSync(activityFile, "utf8"));
194
+ } catch (error) {
195
+ const message = error instanceof Error ? error.message : String(error);
196
+ return { ok: false, reason: "invalid", error: message };
197
+ }
198
+
199
+ return validateActivity(parsed, expectedRunningChildId);
200
+ }
201
+
202
+ export function writeSubagentActivityFile(activityFile: string, activity: SubagentActivityState): void {
203
+ const dir = dirname(activityFile);
204
+ mkdirSync(dir, { recursive: true });
205
+ const tempFile = join(dir, `${activity.runningChildId}.json.${process.pid}.${activity.sequence}.tmp`);
206
+
207
+ try {
208
+ writeFileSync(tempFile, `${JSON.stringify(activity)}\n`, "utf8");
209
+ renameSync(tempFile, activityFile);
210
+ } catch (error) {
211
+ try {
212
+ unlinkSync(tempFile);
213
+ } catch (cleanupError) {
214
+ // Temp cleanup is best effort; preserve the original write/rename failure
215
+ void cleanupError;
216
+ }
217
+ throw error;
218
+ }
219
+ }
220
+
221
+ function createNoopRecorder(): SubagentActivityRecorder {
222
+ return {
223
+ sessionStart() {},
224
+ input() {},
225
+ beforeAgentStart() {},
226
+ agentStart() {},
227
+ agentEndWaiting() {},
228
+ agentEndDone() {},
229
+ turnStart() {},
230
+ turnEnd() {},
231
+ beforeProviderRequest() {},
232
+ afterProviderResponse() {},
233
+ messageUpdate() {},
234
+ toolExecutionStart() {},
235
+ toolCall() {},
236
+ toolExecutionUpdate() {},
237
+ toolResult() {},
238
+ toolExecutionEnd() {},
239
+ askQuestion() {},
240
+ sessionShutdown() {},
241
+ };
242
+ }
243
+
244
+ function clearActiveState(activity: SubagentActivityState): void {
245
+ activity.agentActive = false;
246
+ activity.turnActive = false;
247
+ activity.providerActive = false;
248
+ activity.toolActive = false;
249
+ delete activity.activeScope;
250
+ delete activity.activeSince;
251
+ }
252
+
253
+ function refreshActiveScope(activity: SubagentActivityState): void {
254
+ if (activity.toolActive) {
255
+ activity.phase = "active";
256
+ activity.activeScope = "tool";
257
+ return;
258
+ }
259
+ if (activity.providerActive) {
260
+ activity.phase = "active";
261
+ activity.activeScope = "provider";
262
+ return;
263
+ }
264
+ if (activity.turnActive) {
265
+ activity.phase = "active";
266
+ activity.activeScope = "turn";
267
+ return;
268
+ }
269
+ if (activity.agentActive) {
270
+ activity.phase = "active";
271
+ activity.activeScope = "agent";
272
+ return;
273
+ }
274
+ delete activity.activeScope;
275
+ delete activity.activeSince;
276
+ }
277
+
278
+ function markActive(
279
+ activity: SubagentActivityState,
280
+ scope: SubagentActivityScope,
281
+ now: number,
282
+ resetActiveSince = false,
283
+ ): void {
284
+ activity.phase = "active";
285
+ activity.activeScope = scope;
286
+ if (activity.activeSince == null || resetActiveSince) activity.activeSince = now;
287
+ delete activity.waitingSince;
288
+ }
289
+
290
+ export function createSubagentActivityRecorder(params: {
291
+ runningChildId?: string;
292
+ activityFile?: string;
293
+ now?: () => number;
294
+ }): SubagentActivityRecorder {
295
+ const runningChildId = params.runningChildId?.trim();
296
+ const activityFile = params.activityFile?.trim();
297
+ if (!runningChildId || !activityFile) return createNoopRecorder();
298
+
299
+ const now = params.now ?? (() => Date.now());
300
+ const createdAt = now();
301
+ const activity: SubagentActivityState = {
302
+ version: 1,
303
+ runningChildId,
304
+ createdAt,
305
+ updatedAt: createdAt,
306
+ sequence: 0,
307
+ latestEvent: "session_start",
308
+ phase: "starting",
309
+ agentActive: false,
310
+ turnActive: false,
311
+ providerActive: false,
312
+ toolActive: false,
313
+ };
314
+
315
+ let disabled = false;
316
+ let failureCount = 0;
317
+ let lastFlushAt = 0;
318
+ let pendingFlush: ReturnType<typeof setTimeout> | null = null;
319
+
320
+ function clearPendingFlush(): void {
321
+ if (!pendingFlush) return;
322
+ clearTimeout(pendingFlush);
323
+ pendingFlush = null;
324
+ }
325
+
326
+ function disable(): void {
327
+ disabled = true;
328
+ clearPendingFlush();
329
+ }
330
+
331
+ function flushNow(): void {
332
+ if (disabled || !activityFile) return;
333
+ try {
334
+ writeSubagentActivityFile(activityFile, activity);
335
+ lastFlushAt = now();
336
+ failureCount = 0;
337
+ } catch {
338
+ failureCount += 1;
339
+ if (failureCount >= MAX_WRITE_FAILURES) disable();
340
+ }
341
+ }
342
+
343
+ function scheduleFlush(): void {
344
+ if (disabled || pendingFlush) return;
345
+
346
+ const remainingMs = Math.max(0, ACTIVITY_UPDATE_THROTTLE_MS - (now() - lastFlushAt));
347
+ if (remainingMs === 0) {
348
+ flushNow();
349
+ return;
350
+ }
351
+
352
+ pendingFlush = setTimeout(() => {
353
+ pendingFlush = null;
354
+ flushNow();
355
+ }, remainingMs);
356
+ }
357
+
358
+ function record(
359
+ latestEvent: SubagentActivityEvent,
360
+ update: (current: SubagentActivityState, now: number) => void,
361
+ flush: "immediate" | "throttled",
362
+ ): void {
363
+ if (disabled) return;
364
+ if (flush === "immediate") clearPendingFlush();
365
+
366
+ const observedAt = now();
367
+ activity.latestEvent = latestEvent;
368
+ activity.updatedAt = observedAt;
369
+ activity.sequence += 1;
370
+ update(activity, observedAt);
371
+
372
+ if (flush === "immediate") flushNow();
373
+ else scheduleFlush();
374
+ }
375
+
376
+ function markDone(latestEvent: SubagentActivityEvent): void {
377
+ record(latestEvent, (current) => {
378
+ current.phase = "done";
379
+ clearActiveState(current);
380
+ delete current.waitingSince;
381
+ }, "immediate");
382
+ disable();
383
+ }
384
+
385
+ return {
386
+ sessionStart() {
387
+ record("session_start", (current) => {
388
+ current.phase = "starting";
389
+ clearActiveState(current);
390
+ delete current.waitingSince;
391
+ }, "immediate");
392
+ },
393
+ input() {
394
+ record("input", () => {}, "immediate");
395
+ },
396
+ beforeAgentStart() {
397
+ record("before_agent_start", (current, observedAt) => {
398
+ current.agentActive = true;
399
+ markActive(current, "agent", observedAt);
400
+ }, "immediate");
401
+ },
402
+ agentStart() {
403
+ record("agent_start", (current, observedAt) => {
404
+ current.agentActive = true;
405
+ markActive(current, "agent", observedAt);
406
+ }, "immediate");
407
+ },
408
+ agentEndWaiting() {
409
+ record("agent_end", (current, observedAt) => {
410
+ clearActiveState(current);
411
+ current.phase = "waiting";
412
+ current.waitingSince = observedAt;
413
+ }, "immediate");
414
+ },
415
+ agentEndDone() {
416
+ markDone("agent_end");
417
+ },
418
+ turnStart(turnIndex) {
419
+ record("turn_start", (current, observedAt) => {
420
+ current.agentActive = true;
421
+ current.turnActive = true;
422
+ if (turnIndex != null) current.turnIndex = turnIndex;
423
+ markActive(current, current.toolActive || current.providerActive ? current.activeScope ?? "turn" : "turn", observedAt);
424
+ }, "immediate");
425
+ },
426
+ turnEnd(turnIndex) {
427
+ record("turn_end", (current) => {
428
+ current.turnActive = false;
429
+ current.providerActive = false;
430
+ current.toolActive = false;
431
+ if (turnIndex != null) current.turnIndex = turnIndex;
432
+ refreshActiveScope(current);
433
+ }, "immediate");
434
+ },
435
+ beforeProviderRequest() {
436
+ record("before_provider_request", (current, observedAt) => {
437
+ current.providerActive = true;
438
+ markActive(current, "provider", observedAt, true);
439
+ }, "immediate");
440
+ },
441
+ afterProviderResponse() {
442
+ record("after_provider_response", (current) => {
443
+ current.providerActive = false;
444
+ refreshActiveScope(current);
445
+ }, "immediate");
446
+ },
447
+ messageUpdate(messageEventType) {
448
+ record("message_update", (current, observedAt) => {
449
+ current.agentActive = true;
450
+ current.turnActive = true;
451
+ current.messageEventType = messageEventType;
452
+ if (!current.toolActive) markActive(current, "streaming", observedAt);
453
+ }, "throttled");
454
+ },
455
+ toolExecutionStart(toolCallId, toolName) {
456
+ record("tool_execution_start", (current, observedAt) => {
457
+ current.toolActive = true;
458
+ current.toolCallId = toolCallId;
459
+ current.toolName = toolName;
460
+ current.toolStartedAt = observedAt;
461
+ markActive(current, "tool", observedAt, true);
462
+ }, "immediate");
463
+ },
464
+ toolCall(toolCallId, toolName) {
465
+ record("tool_call", (current, observedAt) => {
466
+ current.toolActive = true;
467
+ current.toolCallId = toolCallId ?? current.toolCallId;
468
+ current.toolName = toolName ?? current.toolName;
469
+ markActive(current, "tool", observedAt);
470
+ }, "immediate");
471
+ },
472
+ toolExecutionUpdate(toolCallId, toolName) {
473
+ record("tool_execution_update", (current, observedAt) => {
474
+ current.toolActive = true;
475
+ current.toolCallId = toolCallId ?? current.toolCallId;
476
+ current.toolName = toolName ?? current.toolName;
477
+ markActive(current, "tool", observedAt);
478
+ }, "throttled");
479
+ },
480
+ toolResult(toolCallId, toolName) {
481
+ record("tool_result", (current) => {
482
+ current.toolCallId = toolCallId ?? current.toolCallId;
483
+ current.toolName = toolName ?? current.toolName;
484
+ refreshActiveScope(current);
485
+ }, "immediate");
486
+ },
487
+ toolExecutionEnd(toolCallId, toolName) {
488
+ record("tool_execution_end", (current, observedAt) => {
489
+ current.toolActive = false;
490
+ current.toolCallId = toolCallId ?? current.toolCallId;
491
+ current.toolName = toolName ?? current.toolName;
492
+ current.toolEndedAt = observedAt;
493
+ refreshActiveScope(current);
494
+ }, "immediate");
495
+ },
496
+ askQuestion() {
497
+ // The subagent paused to ask the orchestrator a question. Park it in the
498
+ // "waiting" phase (do NOT disable the recorder) so the status widget shows
499
+ // it as waiting and recording resumes when the answer arrives.
500
+ record("ask_question", (current, observedAt) => {
501
+ clearActiveState(current);
502
+ current.phase = "waiting";
503
+ current.waitingSince = observedAt;
504
+ }, "immediate");
505
+ },
506
+ sessionShutdown(reason) {
507
+ if (reason === "quit") markDone("session_shutdown");
508
+ else disable();
509
+ },
510
+ };
511
+ }
@@ -0,0 +1,126 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ export type AgentSource = "package" | "global" | "project";
5
+ export type AgentSessionMode = "standalone" | "lineage-only" | "fork";
6
+
7
+ export interface AgentDefaults {
8
+ model?: string;
9
+ tools?: string;
10
+ skills?: string;
11
+ thinking?: string;
12
+ subagentAgents?: string[];
13
+ /** 持久成员的受限成员间直信 ACL:允许向这些成员名 team_send(空/缺省 = 无权限)。 */
14
+ peerSend?: string[];
15
+ autoExit?: boolean;
16
+ interactive?: boolean;
17
+ systemPromptMode?: "append" | "replace";
18
+ sessionMode?: AgentSessionMode;
19
+ cwd?: string;
20
+ body?: string;
21
+ disableModelInvocation?: boolean;
22
+ }
23
+
24
+ export interface AgentDefinition extends AgentDefaults {
25
+ name: string;
26
+ description?: string;
27
+ disableModelInvocation: boolean;
28
+ filePath: string;
29
+ }
30
+
31
+ export interface ListedAgentDefinition extends AgentDefinition {
32
+ source: AgentSource;
33
+ }
34
+
35
+ function getFrontmatterValue(frontmatter: string, key: string): string | undefined {
36
+ const match = frontmatter.match(new RegExp(`^${key}:\\s*(.+)$`, "m"));
37
+ return match ? match[1].trim() : undefined;
38
+ }
39
+
40
+ function parseOptionalBoolean(value: string | undefined): boolean | undefined {
41
+ return value != null ? value === "true" : undefined;
42
+ }
43
+
44
+ function parseCommaList(value: string | undefined): string[] | undefined {
45
+ if (value == null) return undefined;
46
+ const list = value.split(",").map((item) => item.trim()).filter(Boolean);
47
+ return list.length > 0 ? list : undefined;
48
+ }
49
+
50
+ function parseSessionMode(value: string | undefined): AgentSessionMode | undefined {
51
+ if (value === "standalone" || value === "lineage-only" || value === "fork") return value;
52
+ return undefined;
53
+ }
54
+
55
+ export function parseAgentDefinition(
56
+ content: string,
57
+ fallbackName: string,
58
+ filePath = fallbackName,
59
+ ): AgentDefinition | null {
60
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
61
+ if (!match) return null;
62
+
63
+ const frontmatter = match[1];
64
+ const body = content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n*/, "").trim();
65
+ const systemPromptMode = getFrontmatterValue(frontmatter, "system-prompt");
66
+
67
+ return {
68
+ name: getFrontmatterValue(frontmatter, "name") ?? fallbackName,
69
+ description: getFrontmatterValue(frontmatter, "description"),
70
+ model: getFrontmatterValue(frontmatter, "model"),
71
+ tools: getFrontmatterValue(frontmatter, "tools"),
72
+ systemPromptMode:
73
+ systemPromptMode === "replace" || systemPromptMode === "append" ? systemPromptMode : undefined,
74
+ skills: getFrontmatterValue(frontmatter, "skill") ?? getFrontmatterValue(frontmatter, "skills"),
75
+ thinking: getFrontmatterValue(frontmatter, "thinking"),
76
+ subagentAgents: parseCommaList(getFrontmatterValue(frontmatter, "subagent_agents")),
77
+ peerSend: parseCommaList(getFrontmatterValue(frontmatter, "peer-send")),
78
+ autoExit: parseOptionalBoolean(getFrontmatterValue(frontmatter, "auto-exit")),
79
+ interactive: parseOptionalBoolean(getFrontmatterValue(frontmatter, "interactive")),
80
+ sessionMode: parseSessionMode(getFrontmatterValue(frontmatter, "session-mode")),
81
+ cwd: getFrontmatterValue(frontmatter, "cwd"),
82
+ body: body || undefined,
83
+ disableModelInvocation:
84
+ getFrontmatterValue(frontmatter, "disable-model-invocation")?.toLowerCase() === "true",
85
+ filePath,
86
+ };
87
+ }
88
+
89
+ export interface AgentDiscoveryOptions {
90
+ bundledDir: string;
91
+ configDir: string;
92
+ projectDir: string;
93
+ allowlist?: Set<string> | null;
94
+ }
95
+
96
+ function discoverAll(options: AgentDiscoveryOptions): ListedAgentDefinition[] {
97
+ const agents = new Map<string, ListedAgentDefinition>();
98
+ const dirs: Array<{ path: string; source: AgentSource }> = [
99
+ { path: options.bundledDir, source: "package" },
100
+ { path: join(options.configDir, "agents"), source: "global" },
101
+ { path: join(options.projectDir, ".pi", "agents"), source: "project" },
102
+ ];
103
+
104
+ for (const { path: dir, source } of dirs) {
105
+ if (!existsSync(dir)) continue;
106
+ for (const file of readdirSync(dir).filter((entry) => entry.endsWith(".md"))) {
107
+ const filePath = join(dir, file);
108
+ const parsed = parseAgentDefinition(readFileSync(filePath, "utf8"), file.replace(/\.md$/, ""), filePath);
109
+ if (parsed) agents.set(parsed.name, { ...parsed, source });
110
+ }
111
+ }
112
+
113
+ return [...agents.values()];
114
+ }
115
+
116
+ export function discoverAgentDefinitions(options: AgentDiscoveryOptions): ListedAgentDefinition[] {
117
+ const all = discoverAll(options);
118
+ return options.allowlist ? all.filter((agent) => options.allowlist!.has(agent.name)) : all;
119
+ }
120
+
121
+ export function loadAgentDefaults(
122
+ agentName: string,
123
+ options: AgentDiscoveryOptions,
124
+ ): AgentDefinition | null {
125
+ return discoverAll(options).find((agent) => agent.name === agentName) ?? null;
126
+ }
@@ -0,0 +1,37 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { AgentDefaults } from "./agents.ts";
3
+
4
+ export function registerSubagentCommand(
5
+ pi: ExtensionAPI,
6
+ loadAgentDefaults: (agentName: string) => AgentDefaults | null,
7
+ ): void {
8
+ pi.registerCommand("subagent", {
9
+ description: "Spawn a subagent: /subagent <agent> <task>",
10
+ handler: async (args: string, ctx: ExtensionContext) => {
11
+ const trimmed = args.trim();
12
+ if (!trimmed) {
13
+ ctx.ui.notify("Usage: /subagent <agent> [task]", "warning");
14
+ return;
15
+ }
16
+
17
+ const spaceIndex = trimmed.indexOf(" ");
18
+ const agentName = spaceIndex === -1 ? trimmed : trimmed.slice(0, spaceIndex);
19
+ const task = spaceIndex === -1 ? "" : trimmed.slice(spaceIndex + 1).trim();
20
+
21
+ const defaults = loadAgentDefaults(agentName);
22
+ if (!defaults) {
23
+ ctx.ui.notify(
24
+ `Agent "${agentName}" not found in ~/.pi/agent/agents/ or .pi/agents/`,
25
+ "error",
26
+ );
27
+ return;
28
+ }
29
+
30
+ const taskText = task || `You are the ${agentName} agent. Wait for instructions.`;
31
+ const displayName = agentName[0].toUpperCase() + agentName.slice(1);
32
+ const toolCall =
33
+ `Use subagent with agent: "${agentName}", name: "${displayName}", task: ${JSON.stringify(taskText)}`;
34
+ pi.sendUserMessage(toolCall);
35
+ },
36
+ });
37
+ }