@selesai/code 0.1.5 → 0.1.6

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 (142) hide show
  1. package/dist/config.d.ts +21 -4
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +71 -4
  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/extensions/pi-intercom/LICENSE +21 -0
  16. package/dist/extensions/pi-intercom/README.md +484 -0
  17. package/dist/extensions/pi-intercom/broker/broker.ts +345 -0
  18. package/dist/extensions/pi-intercom/broker/client.ts +535 -0
  19. package/dist/extensions/pi-intercom/broker/framing.ts +57 -0
  20. package/dist/extensions/pi-intercom/broker/paths.ts +20 -0
  21. package/dist/extensions/pi-intercom/broker/spawn.ts +307 -0
  22. package/dist/extensions/pi-intercom/config.ts +108 -0
  23. package/dist/extensions/pi-intercom/index.ts +1778 -0
  24. package/dist/extensions/pi-intercom/package.json +38 -0
  25. package/dist/extensions/pi-intercom/reply-tracker.ts +102 -0
  26. package/dist/extensions/pi-intercom/skills/pi-intercom/SKILL.md +512 -0
  27. package/dist/extensions/pi-intercom/types.ts +46 -0
  28. package/dist/extensions/pi-intercom/ui/compose.ts +139 -0
  29. package/dist/extensions/pi-intercom/ui/inline-message.ts +76 -0
  30. package/dist/extensions/pi-intercom/ui/session-list.ts +162 -0
  31. package/dist/extensions/pi-rewind-hook/README.md +245 -0
  32. package/dist/extensions/pi-rewind-hook/index.ts +1445 -0
  33. package/dist/extensions/pi-rewind-hook/package.json +29 -0
  34. package/dist/extensions/pi-subagents/README.md +1290 -0
  35. package/dist/extensions/pi-subagents/agents/context-builder.md +46 -0
  36. package/dist/extensions/pi-subagents/agents/delegate.md +12 -0
  37. package/dist/extensions/pi-subagents/agents/oracle.md +73 -0
  38. package/dist/extensions/pi-subagents/agents/planner.md +55 -0
  39. package/dist/extensions/pi-subagents/agents/researcher.md +52 -0
  40. package/dist/extensions/pi-subagents/agents/reviewer.md +79 -0
  41. package/dist/extensions/pi-subagents/agents/scout.md +50 -0
  42. package/dist/extensions/pi-subagents/agents/worker.md +55 -0
  43. package/dist/extensions/pi-subagents/package.json +83 -0
  44. package/dist/extensions/pi-subagents/prompts/gather-context-and-clarify.md +13 -0
  45. package/dist/extensions/pi-subagents/prompts/parallel-cleanup.md +59 -0
  46. package/dist/extensions/pi-subagents/prompts/parallel-context-build.md +55 -0
  47. package/dist/extensions/pi-subagents/prompts/parallel-handoff-plan.md +61 -0
  48. package/dist/extensions/pi-subagents/prompts/parallel-research.md +50 -0
  49. package/dist/extensions/pi-subagents/prompts/parallel-review.md +54 -0
  50. package/dist/extensions/pi-subagents/prompts/review-loop.md +41 -0
  51. package/dist/extensions/pi-subagents/skills/pi-subagents/SKILL.md +855 -0
  52. package/dist/extensions/pi-subagents/src/agents/agent-management.ts +875 -0
  53. package/dist/extensions/pi-subagents/src/agents/agent-scope.ts +6 -0
  54. package/dist/extensions/pi-subagents/src/agents/agent-selection.ts +25 -0
  55. package/dist/extensions/pi-subagents/src/agents/agent-serializer.ts +110 -0
  56. package/dist/extensions/pi-subagents/src/agents/agents.ts +1379 -0
  57. package/dist/extensions/pi-subagents/src/agents/chain-serializer.ts +252 -0
  58. package/dist/extensions/pi-subagents/src/agents/frontmatter.ts +93 -0
  59. package/dist/extensions/pi-subagents/src/agents/identity.ts +30 -0
  60. package/dist/extensions/pi-subagents/src/agents/proactive-skills.ts +191 -0
  61. package/dist/extensions/pi-subagents/src/agents/skills.ts +729 -0
  62. package/dist/extensions/pi-subagents/src/extension/config.ts +16 -0
  63. package/dist/extensions/pi-subagents/src/extension/control-notices.ts +92 -0
  64. package/dist/extensions/pi-subagents/src/extension/doctor.ts +220 -0
  65. package/dist/extensions/pi-subagents/src/extension/fanout-child.ts +171 -0
  66. package/dist/extensions/pi-subagents/src/extension/index.ts +627 -0
  67. package/dist/extensions/pi-subagents/src/extension/schemas.ts +265 -0
  68. package/dist/extensions/pi-subagents/src/intercom/intercom-bridge.ts +412 -0
  69. package/dist/extensions/pi-subagents/src/intercom/result-intercom.ts +377 -0
  70. package/dist/extensions/pi-subagents/src/profiles/profiles.ts +637 -0
  71. package/dist/extensions/pi-subagents/src/runs/background/async-execution.ts +916 -0
  72. package/dist/extensions/pi-subagents/src/runs/background/async-job-tracker.ts +355 -0
  73. package/dist/extensions/pi-subagents/src/runs/background/async-resume.ts +391 -0
  74. package/dist/extensions/pi-subagents/src/runs/background/async-status.ts +338 -0
  75. package/dist/extensions/pi-subagents/src/runs/background/chain-append.ts +282 -0
  76. package/dist/extensions/pi-subagents/src/runs/background/chain-root-attachment.ts +161 -0
  77. package/dist/extensions/pi-subagents/src/runs/background/completion-dedupe.ts +63 -0
  78. package/dist/extensions/pi-subagents/src/runs/background/control-channel.ts +177 -0
  79. package/dist/extensions/pi-subagents/src/runs/background/notify.ts +108 -0
  80. package/dist/extensions/pi-subagents/src/runs/background/parallel-groups.ts +45 -0
  81. package/dist/extensions/pi-subagents/src/runs/background/result-watcher.ts +316 -0
  82. package/dist/extensions/pi-subagents/src/runs/background/run-id-resolver.ts +83 -0
  83. package/dist/extensions/pi-subagents/src/runs/background/run-status.ts +273 -0
  84. package/dist/extensions/pi-subagents/src/runs/background/stale-run-reconciler.ts +341 -0
  85. package/dist/extensions/pi-subagents/src/runs/background/subagent-runner.ts +2458 -0
  86. package/dist/extensions/pi-subagents/src/runs/background/top-level-async.ts +13 -0
  87. package/dist/extensions/pi-subagents/src/runs/foreground/chain-clarify.ts +1333 -0
  88. package/dist/extensions/pi-subagents/src/runs/foreground/chain-execution.ts +1217 -0
  89. package/dist/extensions/pi-subagents/src/runs/foreground/execution.ts +1092 -0
  90. package/dist/extensions/pi-subagents/src/runs/foreground/subagent-executor.ts +3125 -0
  91. package/dist/extensions/pi-subagents/src/runs/shared/acceptance.ts +856 -0
  92. package/dist/extensions/pi-subagents/src/runs/shared/chain-outputs.ts +116 -0
  93. package/dist/extensions/pi-subagents/src/runs/shared/completion-guard.ts +147 -0
  94. package/dist/extensions/pi-subagents/src/runs/shared/dynamic-fanout.ts +295 -0
  95. package/dist/extensions/pi-subagents/src/runs/shared/long-running-guard.ts +175 -0
  96. package/dist/extensions/pi-subagents/src/runs/shared/mcp-direct-tool-allowlist.ts +365 -0
  97. package/dist/extensions/pi-subagents/src/runs/shared/model-fallback.ts +141 -0
  98. package/dist/extensions/pi-subagents/src/runs/shared/nested-events.ts +819 -0
  99. package/dist/extensions/pi-subagents/src/runs/shared/nested-path.ts +52 -0
  100. package/dist/extensions/pi-subagents/src/runs/shared/nested-render.ts +115 -0
  101. package/dist/extensions/pi-subagents/src/runs/shared/parallel-utils.ts +149 -0
  102. package/dist/extensions/pi-subagents/src/runs/shared/pi-args.ts +240 -0
  103. package/dist/extensions/pi-subagents/src/runs/shared/pi-spawn.ts +115 -0
  104. package/dist/extensions/pi-subagents/src/runs/shared/run-history.ts +60 -0
  105. package/dist/extensions/pi-subagents/src/runs/shared/single-output.ts +178 -0
  106. package/dist/extensions/pi-subagents/src/runs/shared/structured-output.ts +77 -0
  107. package/dist/extensions/pi-subagents/src/runs/shared/subagent-control.ts +223 -0
  108. package/dist/extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.ts +222 -0
  109. package/dist/extensions/pi-subagents/src/runs/shared/workflow-graph.ts +206 -0
  110. package/dist/extensions/pi-subagents/src/runs/shared/worktree.ts +577 -0
  111. package/dist/extensions/pi-subagents/src/shared/artifacts.ts +98 -0
  112. package/dist/extensions/pi-subagents/src/shared/atomic-json.ts +73 -0
  113. package/dist/extensions/pi-subagents/src/shared/file-coalescer.ts +40 -0
  114. package/dist/extensions/pi-subagents/src/shared/fork-context.ts +76 -0
  115. package/dist/extensions/pi-subagents/src/shared/formatters.ts +133 -0
  116. package/dist/extensions/pi-subagents/src/shared/jsonl-writer.ts +81 -0
  117. package/dist/extensions/pi-subagents/src/shared/model-info.ts +78 -0
  118. package/dist/extensions/pi-subagents/src/shared/post-exit-stdio-guard.ts +85 -0
  119. package/dist/extensions/pi-subagents/src/shared/session-identity.ts +10 -0
  120. package/dist/extensions/pi-subagents/src/shared/session-tokens.ts +44 -0
  121. package/dist/extensions/pi-subagents/src/shared/settings.ts +448 -0
  122. package/dist/extensions/pi-subagents/src/shared/status-format.ts +49 -0
  123. package/dist/extensions/pi-subagents/src/shared/types.ts +1064 -0
  124. package/dist/extensions/pi-subagents/src/shared/utils.ts +469 -0
  125. package/dist/extensions/pi-subagents/src/slash/prompt-template-bridge.ts +420 -0
  126. package/dist/extensions/pi-subagents/src/slash/slash-bridge.ts +176 -0
  127. package/dist/extensions/pi-subagents/src/slash/slash-commands.ts +1165 -0
  128. package/dist/extensions/pi-subagents/src/slash/slash-live-state.ts +292 -0
  129. package/dist/extensions/pi-subagents/src/tui/render-helpers.ts +80 -0
  130. package/dist/extensions/pi-subagents/src/tui/render.ts +1728 -0
  131. package/dist/extensions/quick.ts +630 -0
  132. package/dist/modes/index.d.ts +1 -1
  133. package/dist/modes/index.d.ts.map +1 -1
  134. package/dist/modes/index.js.map +1 -1
  135. package/dist/modes/rpc/rpc-mode.d.ts +1 -1
  136. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  137. package/dist/modes/rpc/rpc-mode.js +4 -3
  138. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  139. package/dist/modes/rpc/rpc-types.d.ts +3 -2
  140. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  141. package/dist/modes/rpc/rpc-types.js.map +1 -1
  142. package/package.json +1 -1
@@ -0,0 +1,161 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { AcceptanceLedger, AsyncStatus, ModelAttempt } from "../../shared/types.ts";
4
+ import { readStatus } from "../../shared/utils.ts";
5
+
6
+ export interface ImportedAsyncRoot {
7
+ runId: string;
8
+ asyncDir: string;
9
+ resultPath: string;
10
+ index: number;
11
+ }
12
+
13
+ export interface ImportedAsyncRootResult {
14
+ agent: string;
15
+ output: string;
16
+ success: boolean;
17
+ exitCode: number;
18
+ error?: string;
19
+ sessionFile?: string;
20
+ intercomTarget?: string;
21
+ model?: string;
22
+ attemptedModels?: string[];
23
+ modelAttempts?: ModelAttempt[];
24
+ structuredOutput?: unknown;
25
+ structuredOutputPath?: string;
26
+ structuredOutputSchemaPath?: string;
27
+ acceptance?: AcceptanceLedger;
28
+ }
29
+
30
+ interface AsyncResultFile {
31
+ state?: string;
32
+ success?: boolean;
33
+ summary?: string;
34
+ results?: Array<{
35
+ agent?: string;
36
+ output?: string;
37
+ error?: string;
38
+ success?: boolean;
39
+ sessionFile?: string;
40
+ intercomTarget?: string;
41
+ model?: string;
42
+ attemptedModels?: string[];
43
+ modelAttempts?: ModelAttempt[];
44
+ structuredOutput?: unknown;
45
+ structuredOutputPath?: string;
46
+ structuredOutputSchemaPath?: string;
47
+ acceptance?: AcceptanceLedger;
48
+ }>;
49
+ }
50
+
51
+ const TERMINAL_STATES = new Set(["complete", "failed", "paused"]);
52
+ const TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "paused"]);
53
+
54
+ function readResultFile(resultPath: string): AsyncResultFile | undefined {
55
+ try {
56
+ return JSON.parse(fs.readFileSync(resultPath, "utf-8")) as AsyncResultFile;
57
+ } catch (error) {
58
+ if (typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT") {
59
+ return undefined;
60
+ }
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ function selectedStatusStep(status: AsyncStatus | null, index: number): NonNullable<AsyncStatus["steps"]>[number] | undefined {
66
+ return status?.steps?.[index];
67
+ }
68
+
69
+ function isTerminalStatus(status: AsyncStatus | null, index: number): boolean {
70
+ if (!status) return false;
71
+ const step = selectedStatusStep(status, index);
72
+ if (step && TERMINAL_STEP_STATUSES.has(step.status)) return true;
73
+ return TERMINAL_STATES.has(status.state);
74
+ }
75
+
76
+ function resultState(result: AsyncResultFile | undefined, child: NonNullable<AsyncResultFile["results"]>[number] | undefined): "complete" | "failed" | "paused" | undefined {
77
+ if (!result) return undefined;
78
+ if (child?.success === true) return "complete";
79
+ if (child?.success === false) return result.state === "paused" ? "paused" : "failed";
80
+ if (result.state === "complete" || result.state === "failed" || result.state === "paused") return result.state;
81
+ if (result.success === true) return "complete";
82
+ if (result.success === false) return "failed";
83
+ return undefined;
84
+ }
85
+
86
+ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus, step: NonNullable<AsyncStatus["steps"]>[number] | undefined): ImportedAsyncRootResult {
87
+ const agent = step?.agent ?? status.steps?.[root.index]?.agent ?? "subagent";
88
+ const message = step?.error ?? status.error ?? `Attached async root ${root.runId} ended without a result file at ${root.resultPath}.`;
89
+ return {
90
+ agent,
91
+ output: message,
92
+ success: false,
93
+ exitCode: 1,
94
+ error: message,
95
+ ...(step?.sessionFile ?? status.sessionFile ? { sessionFile: step?.sessionFile ?? status.sessionFile } : {}),
96
+ ...(step?.model ? { model: step.model } : {}),
97
+ ...(step?.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
98
+ ...(step?.modelAttempts ? { modelAttempts: step.modelAttempts } : {}),
99
+ ...(step?.structuredOutput !== undefined ? { structuredOutput: step.structuredOutput } : {}),
100
+ ...(step?.structuredOutputPath ? { structuredOutputPath: step.structuredOutputPath } : {}),
101
+ ...(step?.structuredOutputSchemaPath ? { structuredOutputSchemaPath: step.structuredOutputSchemaPath } : {}),
102
+ ...(step?.acceptance ? { acceptance: step.acceptance } : {}),
103
+ };
104
+ }
105
+
106
+ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null, result: AsyncResultFile): ImportedAsyncRootResult {
107
+ const child = result.results?.[root.index];
108
+ const step = selectedStatusStep(status, root.index);
109
+ const state = resultState(result, child);
110
+ const agent = child?.agent ?? step?.agent ?? status?.steps?.[root.index]?.agent ?? "subagent";
111
+ const output = child?.output ?? result.summary ?? "";
112
+ const success = state === "complete";
113
+ const error = child?.error ?? (success ? undefined : result.summary ?? status?.error ?? `Attached async root ${root.runId} did not complete successfully.`);
114
+ return {
115
+ agent,
116
+ output: success ? output : (output || error || ""),
117
+ success,
118
+ exitCode: success ? 0 : 1,
119
+ ...(error ? { error } : {}),
120
+ ...(child?.sessionFile ?? step?.sessionFile ?? status?.sessionFile ? { sessionFile: child?.sessionFile ?? step?.sessionFile ?? status?.sessionFile } : {}),
121
+ ...(child?.intercomTarget ? { intercomTarget: child.intercomTarget } : {}),
122
+ ...(child?.model ?? step?.model ? { model: child?.model ?? step?.model } : {}),
123
+ ...(child?.attemptedModels ?? step?.attemptedModels ? { attemptedModels: child?.attemptedModels ?? step?.attemptedModels } : {}),
124
+ ...(child?.modelAttempts ?? step?.modelAttempts ? { modelAttempts: child?.modelAttempts ?? step?.modelAttempts } : {}),
125
+ ...(child?.structuredOutput !== undefined ? { structuredOutput: child.structuredOutput } : step?.structuredOutput !== undefined ? { structuredOutput: step.structuredOutput } : {}),
126
+ ...(child?.structuredOutputPath ?? step?.structuredOutputPath ? { structuredOutputPath: child?.structuredOutputPath ?? step?.structuredOutputPath } : {}),
127
+ ...(child?.structuredOutputSchemaPath ?? step?.structuredOutputSchemaPath ? { structuredOutputSchemaPath: child?.structuredOutputSchemaPath ?? step?.structuredOutputSchemaPath } : {}),
128
+ ...(child?.acceptance ?? step?.acceptance ? { acceptance: child?.acceptance ?? step?.acceptance } : {}),
129
+ };
130
+ }
131
+
132
+ export async function waitForImportedAsyncRoot(
133
+ root: ImportedAsyncRoot,
134
+ options: { pollIntervalMs?: number; terminalResultGraceMs?: number; now?: () => number } = {},
135
+ ): Promise<ImportedAsyncRootResult> {
136
+ const pollIntervalMs = options.pollIntervalMs ?? 500;
137
+ const terminalResultGraceMs = options.terminalResultGraceMs ?? 1_000;
138
+ const now = options.now ?? Date.now;
139
+ let terminalSince: number | undefined;
140
+ for (;;) {
141
+ const status = readStatus(root.asyncDir);
142
+ const result = readResultFile(root.resultPath);
143
+ if (result) return buildImportedResult(root, status, result);
144
+ if (isTerminalStatus(status, root.index)) {
145
+ terminalSince ??= now();
146
+ if (now() - terminalSince >= terminalResultGraceMs) {
147
+ return outputFromTerminalStatus(root, status!, selectedStatusStep(status, root.index));
148
+ }
149
+ } else {
150
+ terminalSince = undefined;
151
+ }
152
+ if (!status && !fs.existsSync(root.asyncDir)) {
153
+ throw new Error(`Attached async root '${root.runId}' directory does not exist: ${root.asyncDir}`);
154
+ }
155
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
156
+ }
157
+ }
158
+
159
+ export function resolveAsyncRootResultPath(resultsDir: string, runId: string): string {
160
+ return path.join(resultsDir, `${runId}.json`);
161
+ }
@@ -0,0 +1,63 @@
1
+ interface CompletionDataLike {
2
+ id?: unknown;
3
+ agent?: unknown;
4
+ timestamp?: unknown;
5
+ sessionId?: unknown;
6
+ taskIndex?: unknown;
7
+ totalTasks?: unknown;
8
+ success?: unknown;
9
+ }
10
+
11
+ function asNonEmptyString(value: unknown): string | undefined {
12
+ if (typeof value !== "string") return undefined;
13
+ const trimmed = value.trim();
14
+ return trimmed.length > 0 ? trimmed : undefined;
15
+ }
16
+
17
+ function asFiniteNumber(value: unknown): number | undefined {
18
+ if (typeof value !== "number") return undefined;
19
+ return Number.isFinite(value) ? value : undefined;
20
+ }
21
+
22
+ export function buildCompletionKey(data: CompletionDataLike, fallback: string): string {
23
+ const id = asNonEmptyString(data.id);
24
+ if (id) return `id:${id}`;
25
+ const sessionId = asNonEmptyString(data.sessionId) ?? "no-session";
26
+ const agent = asNonEmptyString(data.agent) ?? "unknown";
27
+ const timestamp = asFiniteNumber(data.timestamp);
28
+ const taskIndex = asFiniteNumber(data.taskIndex);
29
+ const totalTasks = asFiniteNumber(data.totalTasks);
30
+ const success = typeof data.success === "boolean" ? (data.success ? "1" : "0") : "?";
31
+ return [
32
+ "meta",
33
+ sessionId,
34
+ agent,
35
+ timestamp !== undefined ? String(timestamp) : "no-ts",
36
+ taskIndex !== undefined ? String(taskIndex) : "-",
37
+ totalTasks !== undefined ? String(totalTasks) : "-",
38
+ success,
39
+ fallback,
40
+ ].join(":");
41
+ }
42
+
43
+ function pruneSeenMap(seen: Map<string, number>, now: number, ttlMs: number): void {
44
+ for (const [key, ts] of seen.entries()) {
45
+ if (now - ts > ttlMs) seen.delete(key);
46
+ }
47
+ }
48
+
49
+ export function markSeenWithTtl(seen: Map<string, number>, key: string, now: number, ttlMs: number): boolean {
50
+ pruneSeenMap(seen, now, ttlMs);
51
+ if (seen.has(key)) return true;
52
+ seen.set(key, now);
53
+ return false;
54
+ }
55
+
56
+ export function getGlobalSeenMap(storeKey: string): Map<string, number> {
57
+ const globalStore = globalThis as Record<string, unknown>;
58
+ const existing = globalStore[storeKey];
59
+ if (existing instanceof Map) return existing as Map<string, number>;
60
+ const map = new Map<string, number>();
61
+ globalStore[storeKey] = map;
62
+ return map;
63
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Cross-OS control channel for async subagent runs.
3
+ *
4
+ * Background runs are detached OS processes. The original control path delivered
5
+ * an interrupt with `process.kill(pid, SIGUSR2|SIGBREAK)`, but Windows cannot
6
+ * deliver those signals cross-process via `process.kill` and throws `ENOSYS`,
7
+ * which left async runs uninterruptible (no stop, no live steer) on Windows.
8
+ *
9
+ * This module adds a portable, file-based control inbox inside the run directory.
10
+ * The parent drops an interrupt request file; the runner watches the inbox and
11
+ * routes the request into its existing graceful `interruptRunner()` (pause +
12
+ * resumable), identically on every platform. The OS signal is kept only as an
13
+ * opportunistic fast-path; its failure is non-fatal because the file inbox is
14
+ * authoritative.
15
+ */
16
+
17
+ import * as fs from "node:fs";
18
+ import * as path from "node:path";
19
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
20
+ import { POLL_INTERVAL_MS } from "../../shared/types.ts";
21
+
22
+ /**
23
+ * Opportunistic fast-path interrupt signal. On Unix `SIGUSR2` is trapped by the
24
+ * runner; on Windows `process.kill(pid, "SIGBREAK")` is not deliverable
25
+ * cross-process and throws `ENOSYS`, so the file inbox below is the real channel.
26
+ */
27
+ export const INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
28
+
29
+ export type ControlChannelFs = Pick<typeof fs, "mkdirSync" | "existsSync" | "rmSync" | "watch">;
30
+ export type ControlChannelTimers = { setInterval: typeof setInterval; clearInterval: typeof clearInterval };
31
+ type KillFn = (pid: number, signal?: NodeJS.Signals | 0) => unknown;
32
+
33
+ export interface InterruptRequest {
34
+ type: "interrupt";
35
+ ts?: number;
36
+ source?: string;
37
+ reason?: string;
38
+ }
39
+
40
+ /** Control inbox directory inside an async run dir. */
41
+ export function controlInboxDir(asyncDir: string): string {
42
+ return path.join(asyncDir, "control");
43
+ }
44
+
45
+ /** Path of the portable interrupt request file. */
46
+ export function interruptRequestPath(asyncDir: string): string {
47
+ return path.join(controlInboxDir(asyncDir), "interrupt.json");
48
+ }
49
+
50
+ /**
51
+ * Parent side: drop a portable interrupt request the runner's inbox watcher will
52
+ * pick up regardless of OS. Written atomically (temp + rename), dir auto-created.
53
+ */
54
+ export function requestAsyncInterrupt(
55
+ asyncDir: string,
56
+ payload: Omit<InterruptRequest, "type"> = {},
57
+ deps: { now?: () => number } = {},
58
+ ): string {
59
+ const requestPath = interruptRequestPath(asyncDir);
60
+ const request: InterruptRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type: "interrupt" };
61
+ writeAtomicJson(requestPath, request);
62
+ return requestPath;
63
+ }
64
+
65
+ /**
66
+ * Runner side: consume a pending interrupt request. Idempotent — removes the file
67
+ * so each distinct request fires exactly once. Returns whether one was pending.
68
+ */
69
+ export function consumeInterruptRequest(
70
+ asyncDir: string,
71
+ fsImpl: Pick<typeof fs, "existsSync" | "rmSync"> = fs,
72
+ ): boolean {
73
+ const requestPath = interruptRequestPath(asyncDir);
74
+ if (!fsImpl.existsSync(requestPath)) return false;
75
+ try {
76
+ fsImpl.rmSync(requestPath, { force: true, recursive: true });
77
+ } catch {
78
+ // Already removed by a concurrent check — still counts as consumed.
79
+ }
80
+ return true;
81
+ }
82
+
83
+ /**
84
+ * Parent side: portable interrupt = authoritative file request + best-effort OS
85
+ * signal. The signal is only a latency optimization on Unix; ENOSYS on Windows
86
+ * is swallowed because the file inbox is authoritative there. Other signal
87
+ * failures are surfaced because they usually mean the runner is not alive to
88
+ * consume the request.
89
+ */
90
+ export function deliverInterruptRequest(input: {
91
+ asyncDir: string;
92
+ pid?: number;
93
+ kill?: KillFn;
94
+ signal?: NodeJS.Signals;
95
+ now?: () => number;
96
+ source?: string;
97
+ }): void {
98
+ const requestPath = requestAsyncInterrupt(input.asyncDir, input.source ? { source: input.source } : {}, { now: input.now });
99
+ if (typeof input.pid === "number" && input.pid > 0) {
100
+ try {
101
+ (input.kill ?? process.kill)(input.pid, input.signal ?? INTERRUPT_SIGNAL);
102
+ } catch (error) {
103
+ if ((error as NodeJS.ErrnoException | undefined)?.code === "ENOSYS") {
104
+ // File inbox is authoritative when custom cross-process signals are unavailable.
105
+ return;
106
+ }
107
+ try {
108
+ fs.rmSync(requestPath, { force: true });
109
+ } catch {
110
+ // Best effort cleanup; the caller still gets the signal failure.
111
+ }
112
+ throw error;
113
+ }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Runner side: watch the control inbox and route interrupt requests into
119
+ * `onInterrupt`. Uses `fs.watch` when available plus an interval poll as a
120
+ * portable safety net (covers filesystems/platforms where `fs.watch` is
121
+ * unreliable). Fires once per distinct request. Returns a disposer.
122
+ */
123
+ export function watchAsyncControlInbox(
124
+ asyncDir: string,
125
+ opts: {
126
+ onInterrupt: () => void;
127
+ pollIntervalMs?: number;
128
+ fs?: ControlChannelFs;
129
+ timers?: ControlChannelTimers;
130
+ },
131
+ ): () => void {
132
+ const fsImpl = opts.fs ?? fs;
133
+ const timers = opts.timers ?? { setInterval, clearInterval };
134
+ const dir = controlInboxDir(asyncDir);
135
+ try {
136
+ fsImpl.mkdirSync(dir, { recursive: true });
137
+ } catch {
138
+ // Best effort — the poll/watch below tolerates a missing dir.
139
+ }
140
+
141
+ let disposed = false;
142
+ const check = (): void => {
143
+ if (disposed) return;
144
+ try {
145
+ if (consumeInterruptRequest(asyncDir, fsImpl)) opts.onInterrupt();
146
+ } catch {
147
+ // Never let inbox errors crash the runner.
148
+ }
149
+ };
150
+
151
+ // Handle a request that may have arrived before the watcher started.
152
+ check();
153
+
154
+ let watcher: fs.FSWatcher | undefined;
155
+ try {
156
+ watcher = fsImpl.watch(dir, () => check());
157
+ watcher.on?.("error", () => {
158
+ // fs.watch can emit on transient FS errors; the interval poll keeps us live.
159
+ });
160
+ } catch {
161
+ watcher = undefined;
162
+ }
163
+
164
+ const interval = timers.setInterval(check, opts.pollIntervalMs ?? POLL_INTERVAL_MS);
165
+ interval.unref?.();
166
+
167
+ return () => {
168
+ if (disposed) return;
169
+ disposed = true;
170
+ try {
171
+ watcher?.close();
172
+ } catch {
173
+ // ignore
174
+ }
175
+ timers.clearInterval(interval);
176
+ };
177
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Subagent completion notifications.
3
+ */
4
+
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import { buildCompletionKey, getGlobalSeenMap, markSeenWithTtl } from "./completion-dedupe.ts";
7
+ import { SUBAGENT_ASYNC_COMPLETE_EVENT } from "../../shared/types.ts";
8
+
9
+ interface ChainStepResult {
10
+ agent: string;
11
+ output: string;
12
+ success: boolean;
13
+ }
14
+
15
+ export interface SubagentNotifyDetails {
16
+ agent: string;
17
+ status: "completed" | "failed" | "paused";
18
+ taskInfo?: string;
19
+ resultPreview: string;
20
+ durationMs?: number;
21
+ sessionLabel?: string;
22
+ sessionValue?: string;
23
+ }
24
+
25
+ interface SubagentResult {
26
+ id: string | null;
27
+ agent: string | null;
28
+ success: boolean;
29
+ summary: string;
30
+ exitCode?: number;
31
+ state?: string;
32
+ timestamp: number;
33
+ durationMs?: number;
34
+ sessionFile?: string;
35
+ shareUrl?: string;
36
+ gistUrl?: string;
37
+ shareError?: string;
38
+ results?: ChainStepResult[];
39
+ taskIndex?: number;
40
+ totalTasks?: number;
41
+ }
42
+
43
+ export default function registerSubagentNotify(pi: ExtensionAPI): void {
44
+ const unsubscribeStoreKey = "__pi_subagents_notify_unsubscribe__";
45
+ const globalStore = globalThis as Record<string, unknown>;
46
+ const previousUnsubscribe = globalStore[unsubscribeStoreKey];
47
+ if (typeof previousUnsubscribe === "function") {
48
+ try {
49
+ previousUnsubscribe();
50
+ } catch {
51
+ // Best effort cleanup for stale handlers from an older reload.
52
+ }
53
+ }
54
+
55
+ const seen = getGlobalSeenMap("__pi_subagents_notify_seen__");
56
+ const ttlMs = 10 * 60 * 1000;
57
+
58
+ const handleComplete = (data: unknown) => {
59
+ const result = data as SubagentResult;
60
+ const now = Date.now();
61
+ const key = buildCompletionKey(result, "notify");
62
+ if (markSeenWithTtl(seen, key, now, ttlMs)) return;
63
+
64
+ const agent = result.agent ?? "unknown";
65
+ const summary = typeof result.summary === "string" ? result.summary : "";
66
+ const paused = !result.success && (
67
+ result.exitCode === 0
68
+ || result.state === "paused"
69
+ || summary.startsWith("Paused after interrupt.")
70
+ );
71
+ const status = paused ? "paused" : result.success ? "completed" : "failed";
72
+
73
+ const taskInfo =
74
+ result.taskIndex !== undefined && result.totalTasks !== undefined
75
+ ? ` (${result.taskIndex + 1}/${result.totalTasks})`
76
+ : "";
77
+
78
+ const sessionLine = result.shareUrl
79
+ ? `Session: ${result.shareUrl}`
80
+ : result.shareError
81
+ ? `Session share error: ${result.shareError}`
82
+ : result.sessionFile
83
+ ? `Session file: ${result.sessionFile}`
84
+ : undefined;
85
+
86
+ const displaySummary = summary.trim() ? summary : "(no output)";
87
+ const content = [
88
+ `Background task ${status}: **${agent}**${taskInfo}`,
89
+ "",
90
+ displaySummary,
91
+ sessionLine ? "" : undefined,
92
+ sessionLine,
93
+ ]
94
+ .filter((line) => line !== undefined)
95
+ .join("\n");
96
+
97
+ pi.sendMessage(
98
+ {
99
+ customType: "subagent-notify",
100
+ content,
101
+ display: true,
102
+ },
103
+ { triggerTurn: true },
104
+ );
105
+ };
106
+
107
+ globalStore[unsubscribeStoreKey] = pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, handleComplete);
108
+ }
@@ -0,0 +1,45 @@
1
+ import type { AsyncParallelGroupStatus } from "../../shared/types.ts";
2
+
3
+ function isValidParallelGroup(group: unknown, stepCount: number, chainStepCount: number): group is AsyncParallelGroupStatus {
4
+ if (typeof group !== "object" || group === null) return false;
5
+ const { start, count, stepIndex } = group as Partial<AsyncParallelGroupStatus>;
6
+ return typeof start === "number"
7
+ && typeof count === "number"
8
+ && typeof stepIndex === "number"
9
+ && Number.isInteger(start)
10
+ && Number.isInteger(count)
11
+ && Number.isInteger(stepIndex)
12
+ && start >= 0
13
+ && count > 0
14
+ && stepIndex >= 0
15
+ && stepIndex < chainStepCount
16
+ && start + count <= stepCount;
17
+ }
18
+
19
+ export function normalizeParallelGroups(groups: unknown, stepCount: number, chainStepCount: number): AsyncParallelGroupStatus[] {
20
+ if (!Array.isArray(groups)) return [];
21
+ return groups
22
+ .filter((group): group is AsyncParallelGroupStatus => isValidParallelGroup(group, stepCount, chainStepCount))
23
+ .sort((left, right) => left.stepIndex - right.stepIndex || left.start - right.start);
24
+ }
25
+
26
+ export function flatToLogicalStepIndex(flatIndex: number, chainStepCount: number, groups: AsyncParallelGroupStatus[]): number {
27
+ let logicalIndex = 0;
28
+ let cursor = 0;
29
+ for (const group of groups) {
30
+ while (cursor < group.start && logicalIndex < chainStepCount) {
31
+ if (cursor === flatIndex) return logicalIndex;
32
+ cursor++;
33
+ logicalIndex++;
34
+ }
35
+ if (flatIndex >= group.start && flatIndex < group.start + group.count) return group.stepIndex;
36
+ cursor = group.start + group.count;
37
+ logicalIndex = group.stepIndex + 1;
38
+ }
39
+ while (cursor <= flatIndex && logicalIndex < chainStepCount) {
40
+ if (cursor === flatIndex) return logicalIndex;
41
+ cursor++;
42
+ logicalIndex++;
43
+ }
44
+ return Math.max(0, chainStepCount - 1);
45
+ }