pi-suite 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +108 -0
  161. package/src/runtime/responses/payload.ts +78 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,59 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { WAIT_ID_PATTERN, registerBoundTool } from '../runtime/tools.ts';
4
+ import { ToolError } from '../runtime/errors.ts';
5
+ import type { GoalManager } from "./manager.ts";
6
+
7
+ import { completeRenderers, blockedRenderers, waitRenderers } from './render.ts';
8
+
9
+ const goalId = Type.String({ minLength: 1, description: "The exact goalId from the latest Goal instruction" });
10
+ export function registerGoalTools(pi: ExtensionAPI, manager: GoalManager): void {
11
+ registerBoundTool(pi, {
12
+ name: "goal_complete",
13
+ ...completeRenderers, label: "Goal Complete", executionMode: "sequential",
14
+ description: "Mark the current goal complete after checking every original requirement. Do not complete partial or unverified work. Works while the goal runs, and in a user turn while it is paused. On an already completed goal it keeps the first summary.",
15
+ parameters: Type.Object({ goalId, summary: Type.String({ minLength: 1, maxLength: 4000, description: "Each requirement with the evidence that verifies it" }) }),
16
+ async execute(_id, params, signal, _update, ctx) {
17
+ if (!params.summary.trim()) throw new ToolError("INVALID_ARGS", "summary must list each requirement with its verification evidence", params.goalId);
18
+ const changed = await manager.complete(params.goalId, params.summary, ctx, signal);
19
+ const summary = manager.goal!.progress;
20
+ return { content: [{ type: "text", text: `${changed ? "Goal complete" : "Goal already completed"}: ${summary}` }],
21
+ details: { goalId: params.goalId, summary }, terminate: true };
22
+ },
23
+ }, 'initial');
24
+ registerBoundTool(pi, {
25
+ name: "goal_blocked",
26
+ ...blockedRenderers, label: "Goal Blocked", executionMode: "sequential",
27
+ description: "Pause the running goal because of an external blocker you cannot resolve that has repeated for at least 3 consecutive goal turns. Unfinished work and questions for the user are not blockers; ask questions with ask_user.",
28
+ parameters: Type.Object({ goalId, reason: Type.String({ minLength: 1, maxLength: 1000 }),
29
+ evidence: Type.String({ minLength: 1, maxLength: 4000 }), repeatedTurns: Type.Integer({ minimum: 3 }) }),
30
+ async execute(_id, params, signal, _update, ctx) {
31
+ if (!params.reason.trim() || !params.evidence.trim()) throw new ToolError("INVALID_ARGS", "reason and evidence must both be non-empty", params.goalId);
32
+ await manager.block(params.goalId, params.reason, params.evidence, ctx, signal);
33
+ return { content: [{ type: "text", text: `Goal paused: ${params.reason}` }], details: params, terminate: true };
34
+ },
35
+ }, 'initial');
36
+ registerBoundTool(pi, {
37
+ name: "goal_wait",
38
+ ...waitRenderers, label: "Goal Wait", executionMode: "sequential",
39
+ description: "Pause the running goal until external work you started (jobs, subagents, workflows) needs attention. Call it alone, and not for work you can do now. " +
40
+ "The goal resumes when the user sends a message, a direct subagent asks a question, or resumeAfterMs passes. " +
41
+ "With waitFor it also resumes when all listed IDs settle or a listed job emits a monitor event or hands-free update; without waitFor, any notification resumes it.",
42
+ parameters: Type.Object({ goalId, reason: Type.String({ minLength: 1, maxLength: 1000, description: "What the goal is waiting for" }),
43
+ waitFor: Type.Optional(Type.Array(Type.String({ pattern: WAIT_ID_PATTERN }), { minItems: 1, maxItems: 50,
44
+ description: "job_, agent_ or wf_ IDs. If all have already settled, the call returns without waiting." })),
45
+ resumeAfterMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 2147483647,
46
+ description: "Resume after this many milliseconds even if nothing else happens" })) }, { additionalProperties: false }),
47
+ async execute(_id, params, signal, _update, ctx) {
48
+ if (!params.reason.trim()) throw new ToolError("INVALID_ARGS", "reason must say what the goal is waiting for", params.goalId);
49
+ const { waiting, settled } = await manager.wait(params.goalId, params.reason, params.resumeAfterMs, ctx, params.waitFor, signal);
50
+ const note = settled.length ? `already settled: ${settled.join(", ")}` : undefined;
51
+ if (!waiting) {
52
+ return { content: [{ type: "text", text: `Not waiting: every waitFor object has already settled (${settled.join(", ")}). Read their results and continue.` }],
53
+ details: { ...params, waiting, settled } };
54
+ }
55
+ return { content: [{ type: "text", text: [`Goal waiting: ${params.reason}`, note].filter(Boolean).join("\n") }],
56
+ details: { ...params, waiting, settled }, terminate: true };
57
+ },
58
+ }, 'initial');
59
+ }
@@ -0,0 +1,39 @@
1
+ import type { SessionBinding } from '../runtime/binding.ts';
2
+ import type { WaitRegistry } from '../runtime/wait.ts';
3
+ import { ToolError } from '../runtime/errors.ts';
4
+ import type { Goal } from './state.ts';
5
+
6
+ /** Own only the deadline/subscription. GoalManager owns lifecycle, permission and persistence. */
7
+ export class GoalWaitResources {
8
+ private timer?: NodeJS.Timeout;
9
+ private watch?: () => void;
10
+ constructor(private binding: SessionBinding, private waits: WaitRegistry) {}
11
+ disarm(): void {
12
+ clearTimeout(this.timer); this.timer = undefined;
13
+ this.watch?.(); this.watch = undefined;
14
+ }
15
+ private done(ids: string[]): boolean {
16
+ // After restart history-only objects cannot settle in this process. Only those explicit
17
+ // registry errors release the wait; unexpected failures remain visible.
18
+ const states = ids.map(id => {
19
+ try { return this.waits.settlement(id); }
20
+ catch (error) { if (error instanceof ToolError) return undefined; throw error; }
21
+ });
22
+ return states.every(state => !state || state.settled) || states.some(state => state?.question);
23
+ }
24
+ arm(goal: Goal | undefined, wake: () => void): void {
25
+ this.disarm();
26
+ const captured = this.binding.current;
27
+ if (!captured || goal?.status !== 'active' || !goal.automatic || goal.waiting !== 'jobs') return;
28
+ const revision = goal.revision;
29
+ const resume = () => {
30
+ if (this.binding.isCurrent(captured) && goal.revision === revision && goal.status === 'active' && goal.automatic && goal.waiting === 'jobs') wake();
31
+ };
32
+ if (goal.resumeAt) this.timer = setTimeout(resume, Math.max(0, goal.resumeAt - Date.now()));
33
+ if (!goal.waitFor) return;
34
+ // Disabled modules have no active registry and cannot hold the goal indefinitely.
35
+ const ids = goal.waitFor.filter(id => this.waits.has(id));
36
+ if (this.done(ids)) { resume(); return; }
37
+ this.watch = this.waits.watch(ids, () => { if (this.done(ids)) resume(); });
38
+ }
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { registerCliPrompt } from './runtime/cli-prompt.ts';
3
+ import { registerSuiteRenderers } from './runtime/renderers.ts';
4
+ import { captureCustomRenderers } from './runtime/tools.ts';
5
+ import { JOB_SCREEN, jobScreenRenderer } from './jobs/render.ts';
6
+
7
+ export default function piSuite(host: ExtensionAPI): void {
8
+ const pi = captureCustomRenderers(host);
9
+ registerCliPrompt(pi);
10
+ registerSuiteRenderers(pi);
11
+ pi.registerMessageRenderer(JOB_SCREEN, jobScreenRenderer);
12
+ let activation: Promise<Awaited<ReturnType<typeof import('./runtime/suite.ts').createSuite>>> | undefined;
13
+ pi.on('session_start', async (event, ctx) => {
14
+ // Factories have no session cwd. One activation owns registration; session changes
15
+ // await that same activation and then rebind its modules under the fresh context.
16
+ activation ??= import('./runtime/suite.ts').then(({ createSuite }) => createSuite(pi, ctx));
17
+ const bind = await activation;
18
+ return bind(ctx, event.reason, event.previousSessionFile);
19
+ });
20
+ }
@@ -0,0 +1,87 @@
1
+ import { readFileSync, readdirSync } from 'node:fs';
2
+ import { errnoCode, type ProcessIdentity } from '../types.ts';
3
+ import type { Tracked } from './process.ts';
4
+
5
+ type Row = ProcessIdentity & { parentPid: number; groupId: number; state: string; ticks: bigint };
6
+ const same = (a: ProcessIdentity, b: ProcessIdentity) => a.pid === b.pid && a.createdAt === b.createdAt;
7
+ const running = (row: Row | undefined): row is Row => !!row && row.state !== 'Z' && row.state !== 'X';
8
+
9
+ function readProcess(pid: number): Row | undefined {
10
+ let stat: string;
11
+ try { stat = readFileSync(`/proc/${pid}/stat`, 'utf8'); }
12
+ catch (error) { if (errnoCode(error) === 'ENOENT' || errnoCode(error) === 'ESRCH') return; throw error; }
13
+ // comm can contain spaces and ')'; fields after its final ')' have fixed kernel positions.
14
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
15
+ const parentPid = Number(fields[1]), groupId = Number(fields[2]);
16
+ if (!fields[0] || !Number.isSafeInteger(parentPid) || !Number.isSafeInteger(groupId) || !/^\d+$/.test(fields[19] ?? '')) throw new Error(`Invalid /proc/${pid}/stat`);
17
+ const ticks = BigInt(fields[19]);
18
+ // The existing identity string carries exact boot-relative start ticks, never rounded wall time.
19
+ return { pid, createdAt: `linux:${ticks}`, parentPid, groupId, state: fields[0], ticks };
20
+ }
21
+ function snapshot(): Row[] {
22
+ return readdirSync('/proc').filter(name => /^\d+$/.test(name)).flatMap(name => {
23
+ const row = readProcess(Number(name)); return row ? [row] : [];
24
+ });
25
+ }
26
+ export function captureLinuxIdentity(run: Tracked): ProcessIdentity | undefined {
27
+ const row = readProcess(run.pid);
28
+ if (!row) return;
29
+ return run.rootIdentity = { pid: row.pid, createdAt: row.createdAt };
30
+ }
31
+ export function captureLinuxScope(run: Tracked): ProcessIdentity[] {
32
+ const rows = snapshot(), byPid = new Map(rows.map(row => [row.pid, row]));
33
+ const root = run.rootIdentity;
34
+ if (!root) throw new Error(`Linux root identity unavailable${run.identityError ? `: ${run.identityError}` : ''}`);
35
+ const first = byPid.get(root.pid), initial = !run.retainedScope?.length;
36
+ if (initial && (!first || !same(first, root))) throw new Error('Root exited before descendant capture; detached scope cannot be established');
37
+ const retained = run.retainedScope ??= [root];
38
+ const children = new Map<number, Row[]>();
39
+ for (const row of rows) { const list = children.get(row.parentPid) ?? []; list.push(row); children.set(row.parentPid, list); }
40
+ const selected = retained.flatMap(identity => { const row = byPid.get(identity.pid); return row && same(row, identity) ? [row] : []; });
41
+ const seen = new Set(selected.map(row => row.pid));
42
+ // The original group also owns reparented children and the PTY group pin. After the root
43
+ // exits, only a surviving captured member can establish that this is still the same group.
44
+ if (initial || selected.some(row => running(row) && row.groupId === run.pid)) {
45
+ for (const row of rows) if (row.groupId === run.pid && !seen.has(row.pid)) { selected.push(row); seen.add(row.pid); }
46
+ }
47
+ for (let index = 0; index < selected.length; index++) {
48
+ const parent = selected[index];
49
+ for (const child of children.get(parent.pid) ?? []) {
50
+ if (child.ticks >= parent.ticks && !seen.has(child.pid)) { selected.push(child); seen.add(child.pid); }
51
+ }
52
+ }
53
+ // Retain before signaling: parents may exit/reparent children, and sync quit can take over.
54
+ const captured = new Set(retained.map(identity => `${identity.pid}/${identity.createdAt}`));
55
+ for (const row of selected) if (!captured.has(`${row.pid}/${row.createdAt}`)) retained.push({ pid: row.pid, createdAt: row.createdAt });
56
+ return [...retained];
57
+ }
58
+ export function signalLinuxScope(scope: ProcessIdentity[], signal: NodeJS.Signals): void {
59
+ const rows = snapshot(), byPid = new Map(rows.map(row => [row.pid, row]));
60
+ const identities = new Map(scope.map(identity => [identity.pid, identity]));
61
+ const groups = new Map<number, Row[]>();
62
+ for (const row of rows) { const list = groups.get(row.groupId) ?? []; list.push(row); groups.set(row.groupId, list); }
63
+ const signalled = new Set<number>();
64
+ // Detached tool groups go first, leaving their ancestors alive until the captured leaves stop.
65
+ for (const identity of [...scope].reverse()) {
66
+ const row = byPid.get(identity.pid);
67
+ if (!running(row) || !same(row, identity) || signalled.has(row.groupId)) continue;
68
+ const current = readProcess(row.pid);
69
+ if (!running(current) || !same(current, identity)) continue;
70
+ const wholeGroup = current.groupId === row.groupId && groups.get(row.groupId)!.every(member => {
71
+ const owned = identities.get(member.pid); return owned && same(member, owned);
72
+ });
73
+ // A live identity anchors the group even after its leader exits; a reused leader PID alone
74
+ // never authorizes group signals. Mixed groups receive only verified individual signals.
75
+ try { process.kill(wholeGroup ? -row.groupId : row.pid, signal); }
76
+ catch (error) { if (errnoCode(error) !== 'ESRCH') throw error; }
77
+ if (wholeGroup) signalled.add(row.groupId);
78
+ }
79
+ }
80
+ export function linuxScopeAlive(scope: ProcessIdentity[]): boolean {
81
+ // PID 1 may leave zombies unreaped indefinitely; they cannot execute and need no further kill.
82
+ return scope.some(identity => { const row = readProcess(identity.pid); return running(row) && same(row, identity); });
83
+ }
84
+ export function linuxRootExited(run: Tracked): boolean {
85
+ const row = readProcess(run.pid);
86
+ return !!run.rootIdentity && (!running(row) || !same(row, run.rootIdentity));
87
+ }
@@ -0,0 +1,74 @@
1
+ // Adapted from pi-background-jobs 0.1.3 src/process.ts (MIT, third-party/licenses/pi-background-jobs.txt).
2
+ // pi-suite changes: stdin stays open for job_write; POSIX children lead their own process group;
3
+ // the result is the backend-neutral Tracked handle.
4
+ import { spawn } from 'node:child_process';
5
+ import { promises as fs } from 'node:fs';
6
+ import type { FileHandle } from 'node:fs/promises';
7
+ import { resolve, dirname } from 'node:path';
8
+ import { performance } from 'node:perf_hooks';
9
+ import type { ResolvedShellConfig } from '../terminal/shell.ts';
10
+ import { trackIdentity, type Tracked } from './process.ts';
11
+ import type { ExitObservation } from '../types.ts';
12
+
13
+ async function openOutput(path: string): Promise<FileHandle> {
14
+ const target = resolve(path);
15
+ for (let current = target; ; current = dirname(current)) {
16
+ try { if ((await fs.lstat(current)).isSymbolicLink()) throw new Error('Linked output path refused'); }
17
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
18
+ if (dirname(current) === current) break;
19
+ }
20
+ const parent = await fs.realpath(dirname(target));
21
+ const before = await fs.lstat(target).catch(error => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; throw error; });
22
+ if (before && (!before.isFile() || before.nlink !== 1 || before.size !== 0)) throw new Error('Output must be a unique empty regular file');
23
+ // No truncate before verification. Retain the verified descriptor through spawn.
24
+ const file = await fs.open(target, before ? 'r+' : 'wx', 0o600);
25
+ try {
26
+ const opened = await file.stat();
27
+ const current = await fs.lstat(target);
28
+ if (current.isSymbolicLink() || opened.nlink !== 1 || opened.dev !== current.dev || opened.ino !== current.ino ||
29
+ (before && (before.dev !== opened.dev || before.ino !== opened.ino)) || await fs.realpath(dirname(target)) !== parent) throw new Error('Output path changed during open');
30
+ return file;
31
+ } catch (error) { await file.close().catch(() => {}); throw error; }
32
+ }
33
+
34
+ export async function launchPipe(input: { command: string; cwd: string; shell: ResolvedShellConfig; stdoutPath: string; stderrPath: string }): Promise<Tracked> {
35
+ // Windows append-only handles fail in MSYS Bash builtins, so outputs are plain verified files.
36
+ const stdout = await openOutput(input.stdoutPath);
37
+ let stderr: FileHandle;
38
+ try { stderr = await openOutput(input.stderrPath); } catch (error) { await stdout.close().catch(() => {}); throw error; }
39
+ try {
40
+ const byStdin = input.shell.commandTransport === 'stdin';
41
+ const child = spawn(input.shell.shell, byStdin ? [...input.shell.args] : [...input.shell.args, input.command], {
42
+ cwd: input.cwd, env: { ...process.env }, windowsHide: true, detached: process.platform !== 'win32',
43
+ stdio: ['pipe', stdout.fd, stderr.fd],
44
+ });
45
+ const exit = Promise.withResolvers<ExitObservation>();
46
+ const started = Promise.withResolvers<void>();
47
+ let inputError: string | undefined;
48
+ const run: Tracked = {
49
+ pid: 0, spawnedAt: Date.now(), startedMonotonic: performance.now(), exited: exit.promise,
50
+ identity: Promise.resolve(undefined), knownResidual: false,
51
+ write(data) { if (!child.stdin?.writable) throw new Error('Job no longer accepts input'); child.stdin.write(data); },
52
+ endInput() { child.stdin?.end(); },
53
+ dispose() { child.stdin?.destroy(); },
54
+ };
55
+ const observe = (code: number | null, signal: string | null, error?: string) => {
56
+ if (run.exitObserved) return;
57
+ run.exitObserved = { code, signal, ...(error || inputError ? { error: error ?? inputError } : {}) };
58
+ exit.resolve(run.exitObserved);
59
+ };
60
+ child.once('exit', (code, signal) => observe(code, signal));
61
+ child.once('error', error => { observe(null, null, String(error)); started.reject(error); });
62
+ child.once('spawn', () => started.resolve());
63
+ child.stdin?.on('error', error => { inputError = String(error); });
64
+ // Legacy WSL bash reads its script from stdin; such shells cannot also receive job input.
65
+ if (byStdin) child.stdin?.end(input.command);
66
+ await started.promise;
67
+ run.pid = child.pid!;
68
+ trackIdentity(run);
69
+ return run;
70
+ } finally {
71
+ // The child holds its own descriptors; the parent copies are no longer needed.
72
+ await Promise.allSettled([stdout.close(), stderr.close()]);
73
+ }
74
+ }
@@ -0,0 +1,79 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { stopWindows, stopWindowsSync, captureIdentity } from './windows-tree.ts';
3
+ import { captureLinuxIdentity, captureLinuxScope, signalLinuxScope, linuxScopeAlive, linuxRootExited } from './linux-tree.ts';
4
+ import { errnoCode, LIMITS, type CleanupEvidence, type ExitObservation, type ProcessIdentity } from '../types.ts';
5
+ import type { PtyTerminalSession } from '../terminal/session.ts';
6
+
7
+ /**
8
+ * Backend-neutral handle for one launched job. Pipe and PTY backends fill it; stop and quit
9
+ * logic only depend on pid, exit observation and the platform tree/group primitives.
10
+ * On POSIX the root is always a process-group leader (detached pipe child or PTY session).
11
+ */
12
+ export type Tracked = {
13
+ pid: number; spawnedAt: number; startedMonotonic: number; exited: Promise<ExitObservation>; exitObserved?: ExitObservation;
14
+ identity: Promise<ProcessIdentity | undefined>; rootIdentity?: ProcessIdentity; identityError?: string; knownResidual: boolean;
15
+ retainedScope?: ProcessIdentity[]; cleanupDeadline?: number; cleanupSignal?: AbortSignal; identityController?: AbortController;
16
+ write(data: string): void; endInput?(): void; resize?(cols: number, rows: number): void;
17
+ terminal?: PtyTerminalSession; dispose(): void;
18
+ };
19
+
20
+ export function trackIdentity(run: Tracked): void {
21
+ // Linux tools can create their own sessions/groups; keep the root identity for tree capture.
22
+ if (process.platform === 'win32') run.identity = captureIdentity(run, Date.now());
23
+ else if (process.platform === 'linux') {
24
+ try { run.identity = Promise.resolve(captureLinuxIdentity(run)); }
25
+ catch (error) { run.identityError = String(error); }
26
+ }
27
+ }
28
+
29
+ function groupAlive(pid: number): boolean {
30
+ try { process.kill(-pid, 0); return true; }
31
+ catch (error) { if (errnoCode(error) === 'ESRCH') return false; throw error; }
32
+ }
33
+ function signalGroup(pid: number, signal: NodeJS.Signals): void {
34
+ try { process.kill(-pid, signal); }
35
+ catch (error) { if (errnoCode(error) !== 'ESRCH') throw error; }
36
+ }
37
+ async function stopPosix(run: Tracked, deadline: number): Promise<CleanupEvidence> {
38
+ const evidence: CleanupEvidence = { state: 'unconfirmed', scope: [{ pid: run.pid, createdAt: new Date(run.spawnedAt).toISOString() }], rootExited: !!run.exitObserved };
39
+ const linux = process.platform === 'linux';
40
+ const alive = () => linux ? linuxScopeAlive(evidence.scope) : groupAlive(run.pid);
41
+ const signal = (value: NodeJS.Signals) => linux ? signalLinuxScope(evidence.scope, value) : signalGroup(run.pid, value);
42
+ try {
43
+ if (linux) evidence.scope = captureLinuxScope(run);
44
+ signal('SIGTERM');
45
+ const graceEnd = Math.min(deadline, Date.now() + LIMITS.termGraceMs);
46
+ while (alive() && Date.now() < graceEnd) await sleep(25);
47
+ if (alive()) { if (linux) evidence.scope = captureLinuxScope(run); signal('SIGKILL'); }
48
+ while (alive() && Date.now() < deadline) await sleep(25);
49
+ if (!run.exitObserved) await Promise.race([run.exited, sleep(Math.max(0, deadline - Date.now()))]);
50
+ evidence.rootExited = !!run.exitObserved;
51
+ if (!alive() && evidence.rootExited && !run.knownResidual) evidence.state = 'managed_scope_confirmed';
52
+ else throw new Error('Managed process scope or root exit could not be confirmed before the deadline');
53
+ } catch (error) { evidence.rootExited = !!run.exitObserved; evidence.error = String(error); }
54
+ return evidence;
55
+ }
56
+ function stopPosixSync(run: Tracked, deadline: number): CleanupEvidence {
57
+ const evidence: CleanupEvidence = { state: 'unconfirmed', scope: [{ pid: run.pid, createdAt: new Date(run.spawnedAt).toISOString() }], rootExited: !!run.exitObserved };
58
+ try {
59
+ if (process.platform === 'linux') {
60
+ evidence.scope = captureLinuxScope(run); signalLinuxScope(evidence.scope, 'SIGKILL');
61
+ const wait = new Int32Array(new SharedArrayBuffer(4));
62
+ while (linuxScopeAlive(evidence.scope) && Date.now() < deadline) Atomics.wait(wait, 0, 0, 10);
63
+ evidence.rootExited = linuxRootExited(run);
64
+ if (!linuxScopeAlive(evidence.scope) && evidence.rootExited && !run.knownResidual) evidence.state = 'managed_scope_confirmed';
65
+ else throw new Error('Managed process scope could not be confirmed at exit');
66
+ } else { signalGroup(run.pid, 'SIGKILL'); if (!groupAlive(run.pid)) { evidence.state = 'managed_scope_confirmed'; evidence.rootExited = true; } }
67
+ }
68
+ catch (error) { evidence.error = String(error); }
69
+ return evidence;
70
+ }
71
+
72
+ export async function stopTracked(run: Tracked, deadline: number): Promise<CleanupEvidence> {
73
+ const evidence = process.platform === 'win32' ? await stopWindows(run, deadline) : await stopPosix(run, deadline);
74
+ run.dispose();
75
+ return evidence;
76
+ }
77
+ export function stopTrackedSync(run: Tracked, deadline: number): CleanupEvidence {
78
+ return process.platform === 'win32' ? stopWindowsSync(run, deadline) : stopPosixSync(run, deadline);
79
+ }
@@ -0,0 +1,45 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import { constants } from 'node:os';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { PtyTerminalSession } from '../terminal/session.ts';
5
+ import type { ResolvedShellConfig } from '../terminal/shell.ts';
6
+ import { trackIdentity, type Tracked } from './process.ts';
7
+ import type { ExitObservation } from '../types.ts';
8
+
9
+ const SIGNAL_NAMES = Object.fromEntries(Object.entries(constants.signals).map(([name, value]) => [value, name]));
10
+
11
+ /**
12
+ * PTY job: program bytes are appended to output.log in arrival order (the history source),
13
+ * while the headless terminal keeps the live screen for attach. Exit is reported only after
14
+ * the log stream has flushed, so a settled job never has a shorter log than its screen.
15
+ */
16
+ export async function launchPty(input: { command: string; cwd: string; shell: ResolvedShellConfig; outputPath: string; cols: number; rows: number }): Promise<Tracked> {
17
+ const log = createWriteStream(input.outputPath, { flags: 'a', mode: 0o600 });
18
+ const opened = Promise.withResolvers<void>();
19
+ log.once('open', () => opened.resolve()); log.once('error', opened.reject);
20
+ await opened.promise;
21
+ let logError: string | undefined;
22
+ log.on('error', error => { logError = String(error); });
23
+ let session: PtyTerminalSession;
24
+ try {
25
+ session = new PtyTerminalSession({ command: input.command, shellConfig: input.shell, cwd: input.cwd,
26
+ cols: input.cols, rows: input.rows, sink: data => log.write(data) });
27
+ } catch (error) { log.destroy(); throw error; }
28
+ const exit = Promise.withResolvers<ExitObservation>();
29
+ const run: Tracked = {
30
+ pid: session.pid, spawnedAt: Date.now(), startedMonotonic: performance.now(), exited: exit.promise,
31
+ identity: Promise.resolve(undefined), knownResidual: false, terminal: session,
32
+ write: data => session.write(data), resize: (cols, rows) => session.resize(cols, rows),
33
+ dispose: () => session.dispose(),
34
+ };
35
+ void session.exit.promise.then(({ exitCode, signal }) => {
36
+ const flushed = Promise.withResolvers<void>();
37
+ log.end(() => flushed.resolve());
38
+ return flushed.promise.then(() => {
39
+ run.exitObserved = { code: signal ? null : exitCode, signal: signal ? (SIGNAL_NAMES[signal] ?? String(signal)) : null, ...(logError ? { error: logError } : {}) };
40
+ exit.resolve(run.exitObserved);
41
+ });
42
+ });
43
+ trackIdentity(run);
44
+ return run;
45
+ }