@selesai/code 0.1.5 → 0.1.7

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 (143) hide show
  1. package/dist/config.d.ts +23 -4
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +100 -5
  4. package/dist/config.js.map +1 -1
  5. package/dist/core/package-manager.d.ts +1 -0
  6. package/dist/core/package-manager.d.ts.map +1 -1
  7. package/dist/core/package-manager.js +6 -1
  8. package/dist/core/package-manager.js.map +1 -1
  9. package/dist/core/resource-loader.d.ts.map +1 -1
  10. package/dist/core/resource-loader.js +3 -2
  11. package/dist/core/resource-loader.js.map +1 -1
  12. package/dist/core/settings-manager.d.ts +1 -0
  13. package/dist/core/settings-manager.d.ts.map +1 -1
  14. package/dist/core/settings-manager.js.map +1 -1
  15. package/dist/defaults/settings.json +2 -4
  16. package/dist/extensions/pi-intercom/LICENSE +21 -0
  17. package/dist/extensions/pi-intercom/README.md +484 -0
  18. package/dist/extensions/pi-intercom/broker/broker.ts +345 -0
  19. package/dist/extensions/pi-intercom/broker/client.ts +535 -0
  20. package/dist/extensions/pi-intercom/broker/framing.ts +57 -0
  21. package/dist/extensions/pi-intercom/broker/paths.ts +20 -0
  22. package/dist/extensions/pi-intercom/broker/spawn.ts +307 -0
  23. package/dist/extensions/pi-intercom/config.ts +108 -0
  24. package/dist/extensions/pi-intercom/index.ts +1778 -0
  25. package/dist/extensions/pi-intercom/package.json +38 -0
  26. package/dist/extensions/pi-intercom/reply-tracker.ts +102 -0
  27. package/dist/extensions/pi-intercom/skills/pi-intercom/SKILL.md +512 -0
  28. package/dist/extensions/pi-intercom/types.ts +46 -0
  29. package/dist/extensions/pi-intercom/ui/compose.ts +139 -0
  30. package/dist/extensions/pi-intercom/ui/inline-message.ts +76 -0
  31. package/dist/extensions/pi-intercom/ui/session-list.ts +162 -0
  32. package/dist/extensions/pi-rewind-hook/README.md +245 -0
  33. package/dist/extensions/pi-rewind-hook/index.ts +1445 -0
  34. package/dist/extensions/pi-rewind-hook/package.json +29 -0
  35. package/dist/extensions/pi-subagents/README.md +1290 -0
  36. package/dist/extensions/pi-subagents/agents/context-builder.md +46 -0
  37. package/dist/extensions/pi-subagents/agents/delegate.md +12 -0
  38. package/dist/extensions/pi-subagents/agents/oracle.md +73 -0
  39. package/dist/extensions/pi-subagents/agents/planner.md +55 -0
  40. package/dist/extensions/pi-subagents/agents/researcher.md +52 -0
  41. package/dist/extensions/pi-subagents/agents/reviewer.md +79 -0
  42. package/dist/extensions/pi-subagents/agents/scout.md +50 -0
  43. package/dist/extensions/pi-subagents/agents/worker.md +55 -0
  44. package/dist/extensions/pi-subagents/package.json +83 -0
  45. package/dist/extensions/pi-subagents/prompts/gather-context-and-clarify.md +13 -0
  46. package/dist/extensions/pi-subagents/prompts/parallel-cleanup.md +59 -0
  47. package/dist/extensions/pi-subagents/prompts/parallel-context-build.md +55 -0
  48. package/dist/extensions/pi-subagents/prompts/parallel-handoff-plan.md +61 -0
  49. package/dist/extensions/pi-subagents/prompts/parallel-research.md +50 -0
  50. package/dist/extensions/pi-subagents/prompts/parallel-review.md +54 -0
  51. package/dist/extensions/pi-subagents/prompts/review-loop.md +41 -0
  52. package/dist/extensions/pi-subagents/skills/pi-subagents/SKILL.md +855 -0
  53. package/dist/extensions/pi-subagents/src/agents/agent-management.ts +875 -0
  54. package/dist/extensions/pi-subagents/src/agents/agent-scope.ts +6 -0
  55. package/dist/extensions/pi-subagents/src/agents/agent-selection.ts +25 -0
  56. package/dist/extensions/pi-subagents/src/agents/agent-serializer.ts +110 -0
  57. package/dist/extensions/pi-subagents/src/agents/agents.ts +1379 -0
  58. package/dist/extensions/pi-subagents/src/agents/chain-serializer.ts +252 -0
  59. package/dist/extensions/pi-subagents/src/agents/frontmatter.ts +93 -0
  60. package/dist/extensions/pi-subagents/src/agents/identity.ts +30 -0
  61. package/dist/extensions/pi-subagents/src/agents/proactive-skills.ts +191 -0
  62. package/dist/extensions/pi-subagents/src/agents/skills.ts +729 -0
  63. package/dist/extensions/pi-subagents/src/extension/config.ts +16 -0
  64. package/dist/extensions/pi-subagents/src/extension/control-notices.ts +92 -0
  65. package/dist/extensions/pi-subagents/src/extension/doctor.ts +220 -0
  66. package/dist/extensions/pi-subagents/src/extension/fanout-child.ts +171 -0
  67. package/dist/extensions/pi-subagents/src/extension/index.ts +627 -0
  68. package/dist/extensions/pi-subagents/src/extension/schemas.ts +265 -0
  69. package/dist/extensions/pi-subagents/src/intercom/intercom-bridge.ts +412 -0
  70. package/dist/extensions/pi-subagents/src/intercom/result-intercom.ts +377 -0
  71. package/dist/extensions/pi-subagents/src/profiles/profiles.ts +637 -0
  72. package/dist/extensions/pi-subagents/src/runs/background/async-execution.ts +916 -0
  73. package/dist/extensions/pi-subagents/src/runs/background/async-job-tracker.ts +355 -0
  74. package/dist/extensions/pi-subagents/src/runs/background/async-resume.ts +391 -0
  75. package/dist/extensions/pi-subagents/src/runs/background/async-status.ts +338 -0
  76. package/dist/extensions/pi-subagents/src/runs/background/chain-append.ts +282 -0
  77. package/dist/extensions/pi-subagents/src/runs/background/chain-root-attachment.ts +161 -0
  78. package/dist/extensions/pi-subagents/src/runs/background/completion-dedupe.ts +63 -0
  79. package/dist/extensions/pi-subagents/src/runs/background/control-channel.ts +177 -0
  80. package/dist/extensions/pi-subagents/src/runs/background/notify.ts +108 -0
  81. package/dist/extensions/pi-subagents/src/runs/background/parallel-groups.ts +45 -0
  82. package/dist/extensions/pi-subagents/src/runs/background/result-watcher.ts +316 -0
  83. package/dist/extensions/pi-subagents/src/runs/background/run-id-resolver.ts +83 -0
  84. package/dist/extensions/pi-subagents/src/runs/background/run-status.ts +273 -0
  85. package/dist/extensions/pi-subagents/src/runs/background/stale-run-reconciler.ts +341 -0
  86. package/dist/extensions/pi-subagents/src/runs/background/subagent-runner.ts +2458 -0
  87. package/dist/extensions/pi-subagents/src/runs/background/top-level-async.ts +13 -0
  88. package/dist/extensions/pi-subagents/src/runs/foreground/chain-clarify.ts +1333 -0
  89. package/dist/extensions/pi-subagents/src/runs/foreground/chain-execution.ts +1217 -0
  90. package/dist/extensions/pi-subagents/src/runs/foreground/execution.ts +1092 -0
  91. package/dist/extensions/pi-subagents/src/runs/foreground/subagent-executor.ts +3125 -0
  92. package/dist/extensions/pi-subagents/src/runs/shared/acceptance.ts +856 -0
  93. package/dist/extensions/pi-subagents/src/runs/shared/chain-outputs.ts +116 -0
  94. package/dist/extensions/pi-subagents/src/runs/shared/completion-guard.ts +147 -0
  95. package/dist/extensions/pi-subagents/src/runs/shared/dynamic-fanout.ts +295 -0
  96. package/dist/extensions/pi-subagents/src/runs/shared/long-running-guard.ts +175 -0
  97. package/dist/extensions/pi-subagents/src/runs/shared/mcp-direct-tool-allowlist.ts +365 -0
  98. package/dist/extensions/pi-subagents/src/runs/shared/model-fallback.ts +141 -0
  99. package/dist/extensions/pi-subagents/src/runs/shared/nested-events.ts +819 -0
  100. package/dist/extensions/pi-subagents/src/runs/shared/nested-path.ts +52 -0
  101. package/dist/extensions/pi-subagents/src/runs/shared/nested-render.ts +115 -0
  102. package/dist/extensions/pi-subagents/src/runs/shared/parallel-utils.ts +149 -0
  103. package/dist/extensions/pi-subagents/src/runs/shared/pi-args.ts +240 -0
  104. package/dist/extensions/pi-subagents/src/runs/shared/pi-spawn.ts +115 -0
  105. package/dist/extensions/pi-subagents/src/runs/shared/run-history.ts +60 -0
  106. package/dist/extensions/pi-subagents/src/runs/shared/single-output.ts +178 -0
  107. package/dist/extensions/pi-subagents/src/runs/shared/structured-output.ts +77 -0
  108. package/dist/extensions/pi-subagents/src/runs/shared/subagent-control.ts +223 -0
  109. package/dist/extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.ts +222 -0
  110. package/dist/extensions/pi-subagents/src/runs/shared/workflow-graph.ts +206 -0
  111. package/dist/extensions/pi-subagents/src/runs/shared/worktree.ts +577 -0
  112. package/dist/extensions/pi-subagents/src/shared/artifacts.ts +98 -0
  113. package/dist/extensions/pi-subagents/src/shared/atomic-json.ts +73 -0
  114. package/dist/extensions/pi-subagents/src/shared/file-coalescer.ts +40 -0
  115. package/dist/extensions/pi-subagents/src/shared/fork-context.ts +76 -0
  116. package/dist/extensions/pi-subagents/src/shared/formatters.ts +133 -0
  117. package/dist/extensions/pi-subagents/src/shared/jsonl-writer.ts +81 -0
  118. package/dist/extensions/pi-subagents/src/shared/model-info.ts +78 -0
  119. package/dist/extensions/pi-subagents/src/shared/post-exit-stdio-guard.ts +85 -0
  120. package/dist/extensions/pi-subagents/src/shared/session-identity.ts +10 -0
  121. package/dist/extensions/pi-subagents/src/shared/session-tokens.ts +44 -0
  122. package/dist/extensions/pi-subagents/src/shared/settings.ts +448 -0
  123. package/dist/extensions/pi-subagents/src/shared/status-format.ts +49 -0
  124. package/dist/extensions/pi-subagents/src/shared/types.ts +1064 -0
  125. package/dist/extensions/pi-subagents/src/shared/utils.ts +469 -0
  126. package/dist/extensions/pi-subagents/src/slash/prompt-template-bridge.ts +420 -0
  127. package/dist/extensions/pi-subagents/src/slash/slash-bridge.ts +176 -0
  128. package/dist/extensions/pi-subagents/src/slash/slash-commands.ts +1165 -0
  129. package/dist/extensions/pi-subagents/src/slash/slash-live-state.ts +292 -0
  130. package/dist/extensions/pi-subagents/src/tui/render-helpers.ts +80 -0
  131. package/dist/extensions/pi-subagents/src/tui/render.ts +1728 -0
  132. package/dist/extensions/quick.ts +630 -0
  133. package/dist/modes/index.d.ts +1 -1
  134. package/dist/modes/index.d.ts.map +1 -1
  135. package/dist/modes/index.js.map +1 -1
  136. package/dist/modes/rpc/rpc-mode.d.ts +1 -1
  137. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  138. package/dist/modes/rpc/rpc-mode.js +4 -3
  139. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  140. package/dist/modes/rpc/rpc-types.d.ts +3 -2
  141. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  142. package/dist/modes/rpc/rpc-types.js.map +1 -1
  143. package/package.json +1 -1
@@ -0,0 +1,16 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExtensionConfig } from "../shared/types.ts";
4
+ import { getAgentDir } from "../shared/utils.ts";
5
+
6
+ export function loadConfig(): ExtensionConfig {
7
+ const configPath = path.join(getAgentDir(), "extensions", "subagent", "config.json");
8
+ try {
9
+ if (fs.existsSync(configPath)) {
10
+ return JSON.parse(fs.readFileSync(configPath, "utf-8")) as ExtensionConfig;
11
+ }
12
+ } catch (error) {
13
+ console.error(`Failed to load subagent config from '${configPath}':`, error);
14
+ }
15
+ return {};
16
+ }
@@ -0,0 +1,92 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { controlNotificationKey, formatControlNoticeMessage } from "../runs/shared/subagent-control.ts";
3
+ import type { ControlEvent, SubagentState } from "../shared/types.ts";
4
+
5
+ export const SUBAGENT_CONTROL_MESSAGE_TYPE = "subagent_control_notice";
6
+
7
+ export interface SubagentControlMessageDetails {
8
+ event: ControlEvent;
9
+ source?: "foreground" | "async";
10
+ asyncDir?: string;
11
+ childIntercomTarget?: string;
12
+ noticeText?: string;
13
+ }
14
+
15
+ export function controlNoticeTarget(details: SubagentControlMessageDetails): string | undefined {
16
+ return details.childIntercomTarget;
17
+ }
18
+
19
+ export function formatSubagentControlNotice(details: SubagentControlMessageDetails, content?: string): string {
20
+ return details.noticeText ?? content ?? formatControlNoticeMessage(details.event, controlNoticeTarget(details));
21
+ }
22
+
23
+ function noticeTimerKey(details: SubagentControlMessageDetails): string {
24
+ const childIntercomTarget = controlNoticeTarget(details);
25
+ return `${details.event.runId}:${controlNotificationKey(details.event, childIntercomTarget)}`;
26
+ }
27
+
28
+ export function clearPendingForegroundControlNotices(state: SubagentState, runId?: string): void {
29
+ const pending = state.pendingForegroundControlNotices;
30
+ if (!pending) return;
31
+ for (const [key, timer] of pending) {
32
+ if (runId !== undefined && !key.startsWith(`${runId}:`)) continue;
33
+ clearTimeout(timer);
34
+ pending.delete(key);
35
+ }
36
+ }
37
+
38
+ function deliverControlNotice(input: {
39
+ pi: Pick<ExtensionAPI, "sendMessage">;
40
+ visibleControlNotices: Set<string>;
41
+ details: SubagentControlMessageDetails;
42
+ }): void {
43
+ const childIntercomTarget = controlNoticeTarget(input.details);
44
+ const key = controlNotificationKey(input.details.event, childIntercomTarget);
45
+ if (input.visibleControlNotices.has(key)) return;
46
+ input.visibleControlNotices.add(key);
47
+ const noticeText = input.details.noticeText ?? formatControlNoticeMessage(input.details.event, childIntercomTarget);
48
+ input.pi.sendMessage(
49
+ {
50
+ customType: SUBAGENT_CONTROL_MESSAGE_TYPE,
51
+ content: noticeText,
52
+ display: true,
53
+ details: { ...input.details, childIntercomTarget, noticeText },
54
+ },
55
+ { triggerTurn: input.details.source !== "foreground" },
56
+ );
57
+ }
58
+
59
+ function isForegroundNoticeStillActionable(state: SubagentState, details: SubagentControlMessageDetails): boolean {
60
+ const control = state.foregroundControls.get(details.event.runId);
61
+ if (!control) return false;
62
+ if (control.currentAgent && control.currentAgent !== details.event.agent) return false;
63
+ if (details.event.index !== undefined && control.currentIndex !== details.event.index) return false;
64
+ return control.currentActivityState === "needs_attention";
65
+ }
66
+
67
+ export function handleSubagentControlNotice(input: {
68
+ pi: Pick<ExtensionAPI, "sendMessage">;
69
+ state: SubagentState;
70
+ visibleControlNotices: Set<string>;
71
+ details: SubagentControlMessageDetails;
72
+ foregroundDelayMs?: number;
73
+ }): void {
74
+ if (!input.details?.event || input.details.event.type === "active_long_running") return;
75
+ if (input.details.source !== "foreground") {
76
+ deliverControlNotice(input);
77
+ return;
78
+ }
79
+
80
+ const pending = input.state.pendingForegroundControlNotices ?? new Map<string, ReturnType<typeof setTimeout>>();
81
+ input.state.pendingForegroundControlNotices = pending;
82
+ const timerKey = noticeTimerKey(input.details);
83
+ const existing = pending.get(timerKey);
84
+ if (existing) clearTimeout(existing);
85
+ const timer = setTimeout(() => {
86
+ pending.delete(timerKey);
87
+ if (!isForegroundNoticeStillActionable(input.state, input.details)) return;
88
+ deliverControlNotice(input);
89
+ }, input.foregroundDelayMs ?? 1000);
90
+ timer.unref?.();
91
+ pending.set(timerKey, timer);
92
+ }
@@ -0,0 +1,220 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { discoverAgentsAll, type AgentSource } from "../agents/agents.ts";
4
+ import { isAsyncAvailable } from "../runs/background/async-execution.ts";
5
+ import { diagnoseIntercomBridge, type IntercomBridgeDiagnostic } from "../intercom/intercom-bridge.ts";
6
+ import { discoverAvailableSkills, type SkillSource } from "../agents/skills.ts";
7
+ import {
8
+ ASYNC_DIR,
9
+ CHAIN_RUNS_DIR,
10
+ RESULTS_DIR,
11
+ TEMP_ROOT_DIR,
12
+ type ExtensionConfig,
13
+ type SubagentState,
14
+ } from "../shared/types.ts";
15
+
16
+ interface DoctorPaths {
17
+ tempRootDir: string;
18
+ asyncDir: string;
19
+ resultsDir: string;
20
+ chainRunsDir: string;
21
+ }
22
+
23
+ interface DoctorDeps {
24
+ isAsyncAvailable: () => boolean;
25
+ discoverAgentsAll: typeof discoverAgentsAll;
26
+ discoverAvailableSkills: typeof discoverAvailableSkills;
27
+ diagnoseIntercomBridge: typeof diagnoseIntercomBridge;
28
+ }
29
+
30
+ interface DoctorReportInput {
31
+ cwd: string;
32
+ config: ExtensionConfig;
33
+ state: SubagentState;
34
+ context?: "fresh" | "fork";
35
+ requestedSessionDir?: string;
36
+ currentSessionFile?: string | null;
37
+ currentSessionId?: string | null;
38
+ orchestratorTarget?: string;
39
+ sessionError?: string;
40
+ expandTilde?: (value: string) => string;
41
+ paths?: DoctorPaths;
42
+ deps?: Partial<DoctorDeps>;
43
+ }
44
+
45
+ const DEFAULT_PATHS: DoctorPaths = {
46
+ tempRootDir: TEMP_ROOT_DIR,
47
+ asyncDir: ASYNC_DIR,
48
+ resultsDir: RESULTS_DIR,
49
+ chainRunsDir: CHAIN_RUNS_DIR,
50
+ };
51
+
52
+ const DEFAULT_DEPS: DoctorDeps = {
53
+ isAsyncAvailable,
54
+ discoverAgentsAll,
55
+ discoverAvailableSkills,
56
+ diagnoseIntercomBridge,
57
+ };
58
+
59
+ function errorText(error: unknown): string {
60
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
61
+ }
62
+
63
+ function lineFromCheck(label: string, check: () => string): string {
64
+ try {
65
+ return check();
66
+ } catch (error) {
67
+ return `- ${label}: failed — ${errorText(error)}`;
68
+ }
69
+ }
70
+
71
+ function formatExistingDirectory(label: string, dirPath: string): string {
72
+ try {
73
+ if (!fs.existsSync(dirPath)) return `- ${label}: missing (${dirPath})`;
74
+ const stats = fs.statSync(dirPath);
75
+ if (!stats.isDirectory()) throw new Error(`not a directory: ${dirPath}`);
76
+ fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
77
+ return `- ${label}: ok (${dirPath})`;
78
+ } catch (error) {
79
+ return `- ${label}: failed (${dirPath}) — ${errorText(error)}`;
80
+ }
81
+ }
82
+
83
+ function formatSourceCounts(counts: Record<AgentSource, number>): string {
84
+ return `builtin ${counts.builtin}, package ${counts.package}, user ${counts.user}, project ${counts.project}`;
85
+ }
86
+
87
+ function formatSkillSourceCounts(skills: Array<{ source: SkillSource }>): string {
88
+ const counts = new Map<SkillSource, number>();
89
+ for (const skill of skills) counts.set(skill.source, (counts.get(skill.source) ?? 0) + 1);
90
+ const ordered: SkillSource[] = [
91
+ "project",
92
+ "project-settings",
93
+ "project-package",
94
+ "user",
95
+ "user-settings",
96
+ "user-package",
97
+ "extension",
98
+ "builtin",
99
+ "unknown",
100
+ ];
101
+ const parts = ordered
102
+ .map((source) => `${source} ${counts.get(source) ?? 0}`)
103
+ .filter((part) => !part.endsWith(" 0"));
104
+ return parts.length > 0 ? parts.join(", ") : "none";
105
+ }
106
+
107
+ function formatConfiguredSessionDir(input: DoctorReportInput): string {
108
+ if (input.requestedSessionDir) {
109
+ return path.resolve(input.expandTilde?.(input.requestedSessionDir) ?? input.requestedSessionDir);
110
+ }
111
+ if (input.config.defaultSessionDir) {
112
+ return path.resolve(input.expandTilde?.(input.config.defaultSessionDir) ?? input.config.defaultSessionDir);
113
+ }
114
+ return "not configured";
115
+ }
116
+
117
+ function formatSessionLines(input: DoctorReportInput): string[] {
118
+ const sessionFile = input.currentSessionFile ?? null;
119
+ const lines = [
120
+ lineFromCheck("configured session dir", () => `- configured session dir: ${formatConfiguredSessionDir(input)}`),
121
+ `- current session file: ${sessionFile ?? "not available"}`,
122
+ `- current session dir: ${sessionFile ? path.dirname(sessionFile) : "not available"}`,
123
+ `- current session id: ${input.currentSessionId ?? input.state.currentSessionId ?? "not available"}`,
124
+ ];
125
+ if (input.sessionError) lines.push(`- session manager: failed — ${input.sessionError}`);
126
+ return lines;
127
+ }
128
+
129
+ function formatDiscovery(input: DoctorReportInput, deps: DoctorDeps): string[] {
130
+ return [
131
+ lineFromCheck("agents/chains", () => {
132
+ const discovered = deps.discoverAgentsAll(input.cwd);
133
+ const agentCounts = {
134
+ builtin: discovered.builtin.length,
135
+ package: discovered.package?.length ?? 0,
136
+ user: discovered.user.length,
137
+ project: discovered.project.length,
138
+ };
139
+ const chainCounts = discovered.chains.reduce<Record<AgentSource, number>>((counts, chain) => {
140
+ counts[chain.source] += 1;
141
+ return counts;
142
+ }, { builtin: 0, package: 0, user: 0, project: 0 });
143
+ return [
144
+ `- agents: total ${agentCounts.builtin + agentCounts.package + agentCounts.user + agentCounts.project} (${formatSourceCounts(agentCounts)})`,
145
+ `- chains: total ${discovered.chains.length} (${formatSourceCounts(chainCounts)})`,
146
+ ].join("\n");
147
+ }),
148
+ lineFromCheck("skills", () => {
149
+ const skills = deps.discoverAvailableSkills(input.cwd);
150
+ return `- skills: total ${skills.length} (${formatSkillSourceCounts(skills)})`;
151
+ }),
152
+ ];
153
+ }
154
+
155
+ function formatIntercomDiagnostic(diagnostic: IntercomBridgeDiagnostic, context: "fresh" | "fork" | undefined): string[] {
156
+ const lines = [
157
+ `- bridge: ${diagnostic.active ? "active" : "inactive"}${diagnostic.reason ? ` (${diagnostic.reason})` : ""}`,
158
+ `- mode: ${diagnostic.mode}; context: ${context ?? "unspecified"}`,
159
+ `- orchestrator target: ${diagnostic.orchestratorTarget ?? "not available"}`,
160
+ `- pi-intercom: ${diagnostic.piIntercomAvailable ? "available" : "unavailable"} at ${diagnostic.extensionDir}`,
161
+ ];
162
+ if (diagnostic.configPath && diagnostic.intercomConfigEnabled !== undefined) {
163
+ lines.push(`- intercom config: ${diagnostic.intercomConfigEnabled === false ? "disabled" : "enabled or absent"} (${diagnostic.configPath})`);
164
+ }
165
+ if (diagnostic.intercomConfigError) {
166
+ lines.push(`- intercom config warning: ${diagnostic.intercomConfigError}; runtime assumes enabled`);
167
+ }
168
+ return lines;
169
+ }
170
+
171
+ function formatPermissionSystemSection(): string[] {
172
+ const lines: string[] = [];
173
+ const parentSession = process.env["PI_SUBAGENT_PARENT_SESSION"] ?? "";
174
+ const trimmed = parentSession.trim();
175
+ if (trimmed) {
176
+ lines.push(`- parent session: set (${trimmed})`);
177
+ } else {
178
+ lines.push("- parent session: not set — ask forwarding from subprocess children will not reach a parent UI");
179
+ }
180
+ const isChild = process.env["PI_SUBAGENT_CHILD"] === "1";
181
+ lines.push(`- subagent process: ${isChild ? "yes (PI_SUBAGENT_CHILD=1)" : "no"}`);
182
+ // Whether pi-permission-system is installed and where it stores config is
183
+ // outside pi-subagents' control, so we only report the forwarding signal we
184
+ // own. Run `pi list` to confirm the permission extension is installed.
185
+ return lines;
186
+ }
187
+
188
+ export function buildDoctorReport(input: DoctorReportInput): string {
189
+ const paths = input.paths ?? DEFAULT_PATHS;
190
+ const deps = { ...DEFAULT_DEPS, ...input.deps };
191
+ const lines = [
192
+ "Subagents doctor report",
193
+ "",
194
+ "Runtime",
195
+ `- cwd: ${input.cwd}`,
196
+ lineFromCheck("async support", () => `- async support: ${deps.isAsyncAvailable() ? "available" : "unavailable"}`),
197
+ ...formatSessionLines(input),
198
+ "",
199
+ "Filesystem",
200
+ formatExistingDirectory("temp root", paths.tempRootDir),
201
+ formatExistingDirectory("async runs", paths.asyncDir),
202
+ formatExistingDirectory("results", paths.resultsDir),
203
+ formatExistingDirectory("chain runs", paths.chainRunsDir),
204
+ "",
205
+ "Discovery",
206
+ ...formatDiscovery(input, deps),
207
+ "",
208
+ "Permission system",
209
+ ...formatPermissionSystemSection(),
210
+ "",
211
+ "Intercom bridge",
212
+ ...lineFromCheck("intercom bridge", () => formatIntercomDiagnostic(deps.diagnoseIntercomBridge({
213
+ config: input.config.intercomBridge,
214
+ context: input.context,
215
+ orchestratorTarget: input.orchestratorTarget,
216
+ cwd: input.cwd,
217
+ }), input.context).join("\n")).split("\n"),
218
+ ];
219
+ return lines.join("\n");
220
+ }
@@ -0,0 +1,171 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
5
+ import { discoverAgents } from "../agents/agents.ts";
6
+ import { getArtifactsDir } from "../shared/artifacts.ts";
7
+ import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
8
+ import { SUBAGENT_CHILD_ENV, SUBAGENT_FANOUT_CHILD_ENV } from "../runs/shared/pi-args.ts";
9
+ import { readNestedControlRequests, resolveNestedRouteFromEnv, writeNestedControlResult } from "../runs/shared/nested-events.ts";
10
+ import { deliverSubagentIntercomMessageEvent } from "../intercom/result-intercom.ts";
11
+ import { resolveSubagentIntercomTarget } from "../intercom/intercom-bridge.ts";
12
+ import { SubagentParams } from "./schemas.ts";
13
+ import { loadConfig } from "./config.ts";
14
+ import { type Details, type SubagentState } from "../shared/types.ts";
15
+
16
+ function getSubagentSessionRoot(parentSessionFile: string | null): string {
17
+ if (parentSessionFile) {
18
+ const baseName = path.basename(parentSessionFile, ".jsonl");
19
+ const sessionsDir = path.dirname(parentSessionFile);
20
+ return path.join(sessionsDir, baseName);
21
+ }
22
+ return fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-session-"));
23
+ }
24
+
25
+ function expandTilde(p: string): string {
26
+ return p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
27
+ }
28
+
29
+ function createChildSafeState(): SubagentState {
30
+ return {
31
+ baseCwd: "",
32
+ currentSessionId: null,
33
+ subagentInProgress: false,
34
+ asyncJobs: new Map(),
35
+ foregroundRuns: new Map(),
36
+ foregroundControls: new Map(),
37
+ lastForegroundControlId: null,
38
+ pendingForegroundControlNotices: new Map(),
39
+ cleanupTimers: new Map(),
40
+ lastUiContext: null,
41
+ poller: null,
42
+ completionSeen: new Map(),
43
+ watcher: null,
44
+ watcherRestartTimer: null,
45
+ resultFileCoalescer: {
46
+ schedule: () => false,
47
+ clear: () => {},
48
+ },
49
+ };
50
+ }
51
+
52
+ function startNestedControlInboxListener(pi: ExtensionAPI, state: SubagentState): NodeJS.Timeout | undefined {
53
+ let route;
54
+ try {
55
+ route = resolveNestedRouteFromEnv();
56
+ } catch {
57
+ return undefined;
58
+ }
59
+ if (!route) return undefined;
60
+ const seen = new Set<string>();
61
+ const inFlight = new Set<string>();
62
+ const pendingResults = new Map<string, Parameters<typeof writeNestedControlResult>[1]>();
63
+ const timer = setInterval(() => {
64
+ try {
65
+ for (const request of readNestedControlRequests(route)) {
66
+ if (seen.has(request.requestId) || inFlight.has(request.requestId)) continue;
67
+ inFlight.add(request.requestId);
68
+ void (async () => {
69
+ try {
70
+ let result = pendingResults.get(request.requestId);
71
+ if (!result) {
72
+ let ok = false;
73
+ let message = "Control request failed.";
74
+ try {
75
+ const control = state.foregroundControls.get(request.targetRunId);
76
+ if (!control) {
77
+ message = `Nested run ${request.targetRunId} is not active in this fanout child.`;
78
+ } else if (request.action === "interrupt") {
79
+ ok = control.interrupt?.() === true;
80
+ message = ok
81
+ ? `Interrupt requested for nested run ${request.targetRunId}.`
82
+ : `Nested run ${request.targetRunId} has no active child step to interrupt.`;
83
+ } else if (!request.message?.trim()) {
84
+ message = "Nested resume requires message.";
85
+ } else if (!control.currentAgent) {
86
+ message = `Nested run ${request.targetRunId} has no active child message route.`;
87
+ } else {
88
+ const index = control.currentIndex ?? 0;
89
+ const target = resolveSubagentIntercomTarget(request.targetRunId, control.currentAgent, index);
90
+ ok = await deliverSubagentIntercomMessageEvent(
91
+ pi.events,
92
+ target,
93
+ `Follow-up for nested run ${request.targetRunId} (${control.currentAgent}):\n\n${request.message.trim()}`,
94
+ 500,
95
+ { source: "nested-resume", runId: request.targetRunId, agent: control.currentAgent, index },
96
+ );
97
+ message = ok
98
+ ? `Delivered follow-up to live nested run ${request.targetRunId}.`
99
+ : `Nested child intercom target is not registered: ${target}`;
100
+ }
101
+ } catch (error) {
102
+ message = error instanceof Error ? error.message : String(error);
103
+ }
104
+ result = { ts: Date.now(), requestId: request.requestId, targetRunId: request.targetRunId, ok, message };
105
+ }
106
+ try {
107
+ writeNestedControlResult(route, result);
108
+ } catch (error) {
109
+ pendingResults.set(request.requestId, result);
110
+ console.error(`Failed to write nested control result for request '${request.requestId}' targeting '${request.targetRunId}' via inbox '${route.controlInbox}'; keeping request for retry:`, error);
111
+ return;
112
+ }
113
+ pendingResults.delete(request.requestId);
114
+ seen.add(request.requestId);
115
+ try { fs.unlinkSync(request.filePath); } catch {}
116
+ } finally {
117
+ inFlight.delete(request.requestId);
118
+ }
119
+ })();
120
+ }
121
+ } catch (error) {
122
+ console.error(`Failed to poll nested control inbox '${route.controlInbox}' for root '${route.rootRunId}':`, error);
123
+ }
124
+ }, 200);
125
+ timer.unref?.();
126
+ return timer;
127
+ }
128
+
129
+ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI): void {
130
+ if (process.env[SUBAGENT_CHILD_ENV] !== "1" || process.env[SUBAGENT_FANOUT_CHILD_ENV] !== "1") return;
131
+
132
+ const globalStore = globalThis as Record<string, unknown>;
133
+ const registeredKey = "__piSubagentFanoutChildRegisteredApis";
134
+ const registeredApis = globalStore[registeredKey] instanceof WeakSet
135
+ ? globalStore[registeredKey] as WeakSet<ExtensionAPI>
136
+ : new WeakSet<ExtensionAPI>();
137
+ globalStore[registeredKey] = registeredApis;
138
+ if (registeredApis.has(pi)) return;
139
+ registeredApis.add(pi);
140
+
141
+ const config = loadConfig();
142
+ const state = createChildSafeState();
143
+ const executor = createSubagentExecutor({
144
+ pi,
145
+ state,
146
+ config,
147
+ asyncByDefault: config.asyncByDefault === true,
148
+ tempArtifactsDir: getArtifactsDir(null),
149
+ getSubagentSessionRoot,
150
+ expandTilde,
151
+ discoverAgents,
152
+ allowMutatingManagementActions: false,
153
+ });
154
+
155
+ const tool: ToolDefinition<typeof SubagentParams, Details> = {
156
+ name: "subagent",
157
+ label: "Subagent",
158
+ description: [
159
+ "Delegate to subagents from child-safe fanout mode.",
160
+ "Allowed management/control actions: list, get, status, interrupt, resume, append-step, doctor.",
161
+ "Agent config mutation actions create, update, and delete are blocked in this mode.",
162
+ ].join("\n"),
163
+ parameters: SubagentParams,
164
+ execute(id, params, signal, onUpdate, ctx) {
165
+ return executor.execute(id, params as SubagentParamsLike, signal, onUpdate, ctx);
166
+ },
167
+ };
168
+
169
+ pi.registerTool(tool);
170
+ startNestedControlInboxListener(pi, state);
171
+ }