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,186 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/agent-runner.ts (MIT).
2
+ import { readFileSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
4
+ import { homedir } from "node:os";
5
+
6
+ export function extensionCanonicalName(extPath: string): string {
7
+ if (extPath.startsWith('builtin:')) return extPath.slice('builtin:'.length).toLowerCase();
8
+ if (extPath.startsWith('<inline:')) return extPath.slice('<inline:'.length, -1).toLowerCase();
9
+ const base = basename(extPath);
10
+ const name = base === "index.ts" || base === "index.js"
11
+ ? basename(dirname(extPath))
12
+ : base.replace(/\.(ts|js)$/, "");
13
+ return name.toLowerCase();
14
+ }
15
+
16
+ /**
17
+ * The unscoped, lowercased npm short name of the pi package that DECLARES
18
+ * `extPath` as an extension entry — or undefined if the entry doesn't belong to
19
+ * such a package.
20
+ *
21
+ * Climbs from the entry's directory looking for the package that owns it, and
22
+ * stays strictly within that package's tree by stopping at two structural
23
+ * boundaries — no hardcoded depth:
24
+ * - the FIRST `package.json` found (the package root); the entry's own
25
+ * manifest always sits at the root, above the entry, below any node_modules.
26
+ * - a `node_modules` directory: a package never spans one (it's where OTHER
27
+ * packages live), so reaching it means we've climbed out of the package —
28
+ * stop before reading a consumer's or parent package's manifest.
29
+ * The name is then taken only when that root's `pi.extensions` manifest declares
30
+ * this entry, either as the file itself or as a directory containing it (pi
31
+ * expands `"./dist"` to `dist/index.js`). That "declares this entry" check is
32
+ * deliberate: co-located test fixtures can share an ancestor manifest with the
33
+ * suite entry. A looser rule would misattribute those fixtures to `pi-suite`
34
+ * and exclude them as if they were a second suite instance.
35
+ */
36
+ function extensionPackageName(extPath: string): string | undefined {
37
+ // `builtin:<name>` names no file; climbing from it would read the process cwd's manifest.
38
+ if (extPath.startsWith("builtin:") || extPath.startsWith('<')) return undefined;
39
+ const entry = resolve(extPath);
40
+ let dir = dirname(extPath);
41
+ for (;;) {
42
+ // Climbing into node_modules means we've left the owning package's tree.
43
+ if (basename(dir) === "node_modules") return undefined;
44
+ let pkg: { name?: unknown; pi?: { extensions?: unknown } };
45
+ try {
46
+ pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
47
+ } catch (error) {
48
+ // No manifest means keep looking; a broken manifest or an I/O failure is actionable.
49
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
50
+ const parent = dirname(dir);
51
+ if (parent === dir) return undefined; // walked to the filesystem root
52
+ dir = parent;
53
+ continue;
54
+ }
55
+ // First package.json wins — it's the package root; decide here.
56
+ const entries = pkg.pi?.extensions;
57
+ if (
58
+ typeof pkg.name === "string" &&
59
+ Array.isArray(entries) &&
60
+ entries.some((e) => {
61
+ if (typeof e !== "string") return false;
62
+ // A declaration may name a directory (`"./dist"`) that pi resolves to
63
+ // `dist/index.js`, so an entry belongs to this package when it equals the
64
+ // declaration or lives underneath it. The `${sep}` boundary keeps that
65
+ // prefix test platform-correct (`dist-v2` never matches `"./dist"`).
66
+ const declared = resolve(dir, e);
67
+ return declared === entry || entry.startsWith(`${declared}${sep}`);
68
+ })
69
+ ) {
70
+ const short = pkg.name.startsWith("@") ? pkg.name.slice(pkg.name.indexOf("/") + 1) : pkg.name;
71
+ return short.toLowerCase();
72
+ }
73
+ return undefined;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * All names an extension answers to for allowlist matching (lowercased): its
79
+ * path-derived {@link extensionCanonicalName} plus, when a pi package manifest
80
+ * declares this entry, that package's unscoped short name (`@scope/foo` → `foo`).
81
+ * Without the package name, an extension installed via
82
+ * `pi.extensions: ["./src/index.ts"]` would only match as `src` (the source
83
+ * directory). The path-derived name is kept, so it still matches too.
84
+ */
85
+ export function extensionCanonicalNames(extPath: string): string[] {
86
+ const canonical = extensionCanonicalName(extPath);
87
+ const pkg = extensionPackageName(extPath);
88
+ return pkg && pkg !== canonical ? [canonical, pkg] : [canonical];
89
+ }
90
+
91
+ /**
92
+ * Classify `extensions: string[]` frontmatter entries for the loader-level filter.
93
+ *
94
+ * An entry is a PATH iff it contains a path separator or starts with `~`; otherwise
95
+ * it is a NAME. `"*"` sets the wildcard flag (keep all default-discovered extensions).
96
+ *
97
+ * Path entries are resolved (`~` expanded, made absolute against `cwd`) into `paths`
98
+ * — and their canonical name is also added to `names`. The loader override matches
99
+ * everything by canonical name, so path-loaded extensions are matched via their name
100
+ * rather than their post-staging `Extension.path`.
101
+ */
102
+ export function parseExtensionsSpec(
103
+ entries: string[],
104
+ cwd: string,
105
+ ): { names: Set<string>; paths: string[]; wildcard: boolean } {
106
+ const names = new Set<string>();
107
+ const paths: string[] = [];
108
+ let wildcard = false;
109
+ for (const entry of entries) {
110
+ if (!entry) continue;
111
+ if (entry === "*") {
112
+ wildcard = true;
113
+ continue;
114
+ }
115
+ const isPathEntry = entry.includes("/") || entry.includes("\\") || entry.startsWith("~");
116
+ if (!isPathEntry) {
117
+ names.add(entry.toLowerCase());
118
+ continue;
119
+ }
120
+ let p = entry;
121
+ if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) {
122
+ p = homedir() + p.slice(1);
123
+ }
124
+ const abs = isAbsolute(p) ? p : resolve(cwd, p);
125
+ paths.push(abs);
126
+ names.add(extensionCanonicalName(abs));
127
+ }
128
+ return { names, paths, wildcard };
129
+ }
130
+
131
+ /**
132
+ * Parse raw `ext:` selector strings (from the `tools:` CSV) into the set of
133
+ * extension names to keep loaded and a per-extension tool-narrowing map.
134
+ *
135
+ * `ext:foo` → `extNames` has `foo`, no narrowing entry (all of foo's tools).
136
+ * `ext:foo/bar` → `extNames` has `foo`, `narrowing.foo` has `bar` (only `bar`).
137
+ * A name lands in `narrowing` only when a `/tool` form is seen, so a bare
138
+ * `ext:foo` alongside `ext:foo/bar` leaves narrowing in effect (narrowing wins).
139
+ * The split is on the first `/`; extension canonical names never contain `/`.
140
+ */
141
+ export function parseExtSelectors(entries: string[]): {
142
+ extNames: Set<string>;
143
+ narrowing: Map<string, Set<string>>;
144
+ } {
145
+ const extNames = new Set<string>();
146
+ const narrowing = new Map<string, Set<string>>();
147
+ for (const raw of entries) {
148
+ if (!raw) continue;
149
+ const body = raw.slice("ext:".length);
150
+ const slash = body.indexOf("/");
151
+ // Extension name matches case-insensitively (matches the loader-side canonical
152
+ // name). Tool names are case-preserved — they're matched against pi-mono's
153
+ // registered identifiers, which are case-sensitive.
154
+ const name = (slash === -1 ? body : body.slice(0, slash)).trim().toLowerCase();
155
+ if (!name) continue;
156
+ extNames.add(name);
157
+ if (slash === -1) continue;
158
+ const tool = body.slice(slash + 1).trim();
159
+ if (!tool) continue;
160
+ let set = narrowing.get(name);
161
+ if (!set) {
162
+ set = new Set();
163
+ narrowing.set(name, set);
164
+ }
165
+ set.add(tool);
166
+ }
167
+ return { extNames, narrowing };
168
+ }
169
+
170
+ /** pi's MCP resource tools, which it counts as MCP tools alongside `mcp__<server>__<tool>`. */
171
+ const MCP_RESOURCE_TOOL_NAMES = new Set(["list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"]);
172
+
173
+ /** The tools that reach `codemode`/`deferred` MCP tools: neither is declared to the model. */
174
+ export const MCP_BRIDGE_TOOL_NAMES = new Set(["codemode", "tool_search"]);
175
+
176
+ export const isMcpToolName = (name: string) => name.startsWith("mcp__") || MCP_RESOURCE_TOOL_NAMES.has(name);
177
+
178
+ /** Whether `name` matches one of the `tools:` `mcp__` entries: an exact name or a `*` pattern. */
179
+ export function matchesToolPattern(name: string, patterns: readonly string[]): boolean {
180
+ return patterns.some((p) =>
181
+ p.includes("*")
182
+ ? new RegExp(`^${p.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`).test(name)
183
+ : p === name,
184
+ );
185
+ }
186
+
@@ -0,0 +1,20 @@
1
+ import type { SettingsManager } from '@earendil-works/pi-coding-agent';
2
+ import type { Execution } from './types.ts';
3
+
4
+ const RETRY = /upstream|interrupted|timed out|timeout|network|connection|socket hang up|ECONNRESET|fetch failed|overloaded|\b(?:429|5(?:\d{2}|xx))\b/i;
5
+ const EXCLUDE = /quota|billing|balance|usage limit|insufficient|unauthorized|\b(?:401|403)\b/i;
6
+
7
+ /** Keep the provider error separate from other diagnostics in the run's error field. */
8
+ export class ModelRequestError extends Error {
9
+ constructor(readonly requestError: string, readonly retry: ReturnType<SettingsManager['getRetrySettings']>, diagnostics: string[] = []) {
10
+ super([...diagnostics, requestError].join('; '));
11
+ }
12
+ }
13
+
14
+ export function retryable(error: ModelRequestError): boolean {
15
+ return error.retry.enabled && RETRY.test(error.requestError) && !EXCLUDE.test(error.requestError);
16
+ }
17
+
18
+ export function retrySuffix(run?: Execution): string | undefined {
19
+ if (run?.record.state === 'queued' && run.retry) return ` · retry ${run.retry.attempt}/${run.retry.max}`;
20
+ }
@@ -0,0 +1,62 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/cross-extension-rpc.ts (MIT).
2
+ // Model resolution and ownership are supplied by the suite's existing session scope.
3
+ import { isTopLevelAgent, type AgentRecord } from '../types.ts';
4
+
5
+ export interface EventBus {
6
+ on(event: string, handler: (data: unknown) => void): () => void;
7
+ emit(event: string, data: unknown): void;
8
+ }
9
+ export type RpcReply<T = void> = { success: true; data?: T } | { success: false; error: string };
10
+ export const PROTOCOL_VERSION = 2;
11
+ export interface RpcDeps {
12
+ events: EventBus;
13
+ spawn(type: string, prompt: string, options: unknown): Promise<{ id: string }>;
14
+ getRecord(id: string): AgentRecord | undefined;
15
+ stop(id: string): Promise<void>;
16
+ consume(id: string): boolean;
17
+ steer(id: string, message: string): Promise<void>;
18
+ }
19
+
20
+ function handleRpc<P extends { requestId: string }>(events: EventBus, channel: string,
21
+ fn: (params: P) => unknown | Promise<unknown>): () => void {
22
+ return events.on(channel, async raw => {
23
+ const params = raw as P;
24
+ try {
25
+ if (typeof params?.requestId !== 'string' || !params.requestId.trim()) throw new Error('Invalid requestId. Resend with a non-empty string.');
26
+ const data = await fn(params);
27
+ const reply: RpcReply<unknown> = { success: true };
28
+ if (data !== undefined) reply.data = data;
29
+ events.emit(`${channel}:reply:${params.requestId}`, reply);
30
+ } catch (error) {
31
+ events.emit(`${channel}:reply:${params?.requestId}`, { success: false, error: error instanceof Error ? error.message : String(error) });
32
+ }
33
+ });
34
+ }
35
+
36
+ export function registerRpcHandlers(deps: RpcDeps): () => void {
37
+ const { events } = deps;
38
+ const assertOwned = (id: string): AgentRecord => {
39
+ const record = deps.getRecord(id);
40
+ if (!record) throw new Error('Agent not found. Use an agent ID from this session and branch.');
41
+ if (!isTopLevelAgent(record)) throw new Error('Agent is owned by another agent or workflow. Use a top-level agent ID.');
42
+ return record;
43
+ };
44
+ const unsubscribers = [
45
+ handleRpc(events, 'subagents:rpc:ping', () => ({ version: PROTOCOL_VERSION })),
46
+ handleRpc<{ requestId: string; type: string; prompt: string; options?: unknown }>(events, 'subagents:rpc:spawn', params =>
47
+ deps.spawn(params.type, params.prompt, params.options)),
48
+ handleRpc<{ requestId: string; agentId: string }>(events, 'subagents:rpc:stop', ({ agentId }) => {
49
+ assertOwned(agentId); return deps.stop(agentId);
50
+ }),
51
+ handleRpc<{ requestId: string; agentId: string }>(events, 'subagents:rpc:consume', ({ agentId }) => {
52
+ // Keep consumption synchronous so completion listeners can prevent the notice from being queued.
53
+ assertOwned(agentId);
54
+ if (!deps.consume(agentId)) throw new Error('Agent has not settled. Consume after subagents:completed or subagents:failed.');
55
+ }),
56
+ handleRpc<{ requestId: string; agentId: string; message: unknown }>(events, 'subagents:rpc:steer', ({ agentId, message }) => {
57
+ if (typeof message !== 'string' || !message.trim()) throw new Error('Invalid steer message. Resend with a non-empty string.');
58
+ assertOwned(agentId); return deps.steer(agentId, message);
59
+ }),
60
+ ];
61
+ return () => { for (const unsubscribe of unsubscribers) unsubscribe(); };
62
+ }
@@ -0,0 +1,73 @@
1
+ // Session gating/lifecycle adapted from @tintinweb/pi-subagents 0.23.0 src/index.ts (MIT).
2
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
3
+ import type { SessionBinding } from '../../runtime/binding.ts';
4
+ import type { SuiteConfig } from '../../runtime/config.ts';
5
+ import type { AgentsModule } from '../index.ts';
6
+ import { active, isTopLevelAgent, type AgentRecord } from '../types.ts';
7
+ import { registerRpcHandlers } from './handlers.ts';
8
+ import { normalizeSpawn } from './options.ts';
9
+
10
+ const statusOf = (record: AgentRecord) => record.state === 'completed' ? 'completed' : record.state === 'failed' ? 'error'
11
+ : record.state === 'limited' ? 'aborted' : record.state === 'queued' ? 'queued' : record.state === 'stopped' ? 'stopped' : 'running';
12
+
13
+ export class AgentRpc {
14
+ private unsubscribe?: () => void;
15
+ constructor(private pi: ExtensionAPI, private binding: SessionBinding, private agents: AgentsModule, private config: () => SuiteConfig) {}
16
+ bind(): void {
17
+ if (this.unsubscribe || !this.binding.current) return;
18
+ const { pi, agents, binding } = this, manager = agents.manager;
19
+ const find = (id: string) => {
20
+ const current = binding.current;
21
+ if (!current) return;
22
+ // Look up only this session/branch, while retaining nested records for an explicit refusal.
23
+ return manager.records().filter(record => record.id === id && record.ownerSessionId === current.sessionId
24
+ && (record.anchorEntryId === null || current.ctx.sessionManager.getBranch().some(entry => entry.id === record.anchorEntryId)))
25
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.runId.localeCompare(a.runId))[0];
26
+ };
27
+ const offRpc = registerRpcHandlers({ events: pi.events,
28
+ spawn: async (type, prompt, raw) => {
29
+ const captured = binding.current;
30
+ if (!captured) throw new Error('No active session. Wait for subagents:ready before spawning.');
31
+ const { request, options } = normalizeSpawn(type, prompt, raw);
32
+ const run = await agents.admit().start(request, agents.scope(captured.ctx), this.config(), undefined, options);
33
+ await manager.awaitStartup(run);
34
+ return { id: run.record.id };
35
+ },
36
+ getRecord: find,
37
+ stop: async id => {
38
+ const record = find(id)!;
39
+ if (!active(record.state)) throw new Error('Agent is not running. Pass the ID of an active agent to stop.');
40
+ await manager.stop(id, record.runId);
41
+ },
42
+ consume: id => {
43
+ const record = find(id)!;
44
+ const run = manager.runs.get(record.runId);
45
+ if (active(record.state) || run && !run.settled) return false;
46
+ agents.consume({ id, runId: record.runId, state: record.state, summary: '', settled: true });
47
+ return true;
48
+ },
49
+ steer: async (id, message) => {
50
+ const record = find(id)!;
51
+ const run = manager.runs.get(record.runId);
52
+ if (!run || run.settled || !active(record.state)) throw new Error('Agent is not running. Use spawn to start new work.');
53
+ await manager.send(id, message, agents.scope(binding.current!.ctx), this.config());
54
+ },
55
+ });
56
+ const offEvents = manager.subscribeEvents((kind, run, details) => {
57
+ const current = binding.current, record = manager.view(run);
58
+ if (!current || record.ownerSessionId !== current.sessionId) return;
59
+ if (record.anchorEntryId !== null && !current.ctx.sessionManager.getBranch().some(entry => entry.id === record.anchorEntryId)) return;
60
+ if (kind !== 'usage' && !isTopLevelAgent(record)) return;
61
+ const tokens = record.usage?.tokens;
62
+ pi.events.emit(`subagents:${kind}`, { id: record.id, runId: record.runId, type: record.type,
63
+ description: record.description ?? record.name, status: statusOf(record), isBackground: record.background,
64
+ result: record.result, error: record.error, toolUses: record.toolUses, durationMs: record.elapsedMs,
65
+ ...(tokens ? { tokens: { input: tokens.input, output: tokens.output, total: tokens.input + tokens.output } } : {}),
66
+ ...(kind === 'usage' ? { model: record.model, thinking: record.thinking, depth: record.ancestors.length + 1,
67
+ ...(record.parentAgentId ? { parentAgentId: record.parentAgentId } : {}), ...(record.workflowId ? { workflowId: record.workflowId } : {}) } : {}), ...details });
68
+ });
69
+ this.unsubscribe = () => { offRpc(); offEvents(); };
70
+ pi.events.emit('subagents:ready', {});
71
+ }
72
+ detach(): void { this.unsubscribe?.(); this.unsubscribe = undefined; }
73
+ }
@@ -0,0 +1,44 @@
1
+ // Spawn names/normalization adapted from @tintinweb/pi-subagents 0.23.0 src/cross-extension-rpc.ts (MIT).
2
+ // Validate at the RPC boundary so misspelled options cannot silently change a run.
3
+ import { statSync } from 'node:fs';
4
+ import { isAbsolute } from 'node:path';
5
+ import { Type, type Static } from 'typebox';
6
+ import { Check, Errors } from 'typebox/value';
7
+ import { thinkingSchema } from '../schema.ts';
8
+ import type { StartAgent, StartOptions } from '../types.ts';
9
+
10
+ const schema = Type.Object({
11
+ description: Type.Optional(Type.String()), name: Type.Optional(Type.String()),
12
+ model: Type.Optional(Type.Union([Type.String({ minLength: 1 }), Type.Null(),
13
+ Type.Object({ provider: Type.String({ minLength: 1 }), id: Type.String({ minLength: 1 }) })])),
14
+ maxTurns: Type.Optional(Type.Integer({ minimum: 0 })), isolated: Type.Optional(Type.Boolean()),
15
+ inheritContext: Type.Optional(Type.Boolean()), thinkingLevel: Type.Optional(thinkingSchema),
16
+ isBackground: Type.Optional(Type.Boolean()), bypassQueue: Type.Optional(Type.Boolean()),
17
+ cwd: Type.Optional(Type.Union([Type.String(), Type.Null()])), signal: Type.Optional(Type.Any()),
18
+ structuredOutput: Type.Optional(Type.Any()), onSpawned: Type.Optional(Type.Any()),
19
+ onQueued: Type.Optional(Type.Any()), onCompaction: Type.Optional(Type.Any()),
20
+ }, { additionalProperties: false });
21
+
22
+ export function normalizeSpawn(type: unknown, prompt: unknown, raw: unknown): { request: StartAgent; options: StartOptions } {
23
+ if (typeof type !== 'string' || !type.trim()) throw new Error('Invalid agent type. Resend with a non-empty type string.');
24
+ if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('Invalid agent prompt. Resend with a non-empty prompt string.');
25
+ const value = raw ?? {};
26
+ if (!Check(schema, value)) throw new Error(`Invalid spawn options: ${[...Errors(schema, value)].map(error => `${error.instancePath}: ${error.message}`).join('; ')}. Correct the listed fields and retry.`);
27
+ const o = value as Static<typeof schema>;
28
+ for (const key of ['onSpawned', 'onQueued', 'onCompaction'] as const) {
29
+ if (o[key] !== undefined && typeof o[key] !== 'function') throw new Error(`SpawnOptions.${key} is not a function. Pass a function or omit it.`);
30
+ }
31
+ if (o.signal !== undefined && !(o.signal instanceof AbortSignal)) throw new Error('SpawnOptions.signal is not an AbortSignal. Pass an AbortSignal or omit it.');
32
+ if (o.structuredOutput !== undefined && (!o.structuredOutput || o.structuredOutput.schema?.type !== 'object' || typeof o.structuredOutput.check !== 'function')) {
33
+ throw new Error('Invalid SpawnOptions.structuredOutput. Pass an object schema with a check(value) function, or omit it.');
34
+ }
35
+ if (o.cwd != null) {
36
+ if (!isAbsolute(o.cwd)) throw new Error(`SpawnOptions.cwd is not absolute: "${o.cwd}". Pass an absolute path or omit cwd.`);
37
+ if (!statSync(o.cwd).isDirectory()) throw new Error(`SpawnOptions.cwd is not a directory: "${o.cwd}". Pass an existing directory or omit cwd.`);
38
+ }
39
+ const model = o.model == null ? undefined : typeof o.model === 'string' ? o.model : `${o.model.provider}/${o.model.id}`;
40
+ return { request: { type, prompt, name: o.name, model, maxTurns: o.maxTurns, isolated: o.isolated,
41
+ inheritContext: o.inheritContext, thinking: o.thinkingLevel, background: o.isBackground ?? false },
42
+ options: { description: o.description, bypassQueue: o.bypassQueue, cwd: o.cwd ?? undefined, signal: o.signal,
43
+ structuredOutput: o.structuredOutput, onSpawned: o.onSpawned, onQueued: o.onQueued, onCompaction: o.onCompaction, detached: true } };
44
+ }
@@ -0,0 +1,16 @@
1
+ import type { AgentRecord } from './types.ts';
2
+
3
+ // Keep the browser's representative in the same order as manager.get(id).
4
+ export const compareRunRecency = (a: AgentRecord, b: AgentRecord): number =>
5
+ b.createdAt.localeCompare(a.createdAt) || b.runId.localeCompare(a.runId);
6
+
7
+ export function groupAgentRuns(records: Iterable<AgentRecord>): Map<string, AgentRecord[]> {
8
+ const groups = new Map<string, AgentRecord[]>();
9
+ for (const record of records) {
10
+ const runs = groups.get(record.id);
11
+ if (runs) runs.push(record);
12
+ else groups.set(record.id, [record]);
13
+ }
14
+ for (const runs of groups.values()) runs.sort(compareRunRecency);
15
+ return groups;
16
+ }
@@ -0,0 +1,131 @@
1
+ // Same-process SDK lifecycle adapted from @tintinweb/pi-subagents 0.23.0 src/agent-runner.ts (MIT).
2
+ import { createAgentSession, getAgentDir, SessionManager, type ExtensionFactory } from '@earendil-works/pi-coding-agent';
3
+ import type { AgentEventKind, Execution } from './types.ts';
4
+ import { AGENT_ENTRY, resultText } from './records.ts';
5
+ import { childResources } from './resources/loader.ts';
6
+ import { resourcePath } from './resources/paths.ts';
7
+ import { installExtensionToolScope } from './resources/scope.ts';
8
+ import { createStructuredCapture, createStructuredOutputTool, structuredRetryPrompt } from './output/tool.ts';
9
+ import { sanitizeText } from '../runtime/text.ts';
10
+ import { createChildSession } from './session.ts';
11
+ import { parentModelRuntime } from './models.ts';
12
+ import { ModelRequestError } from './retry.ts';
13
+
14
+ export async function executeAgent(run: Execution, factory: ExtensionFactory, changed: () => void,
15
+ emitEvent: (kind: AgentEventKind, details?: Record<string, unknown>) => void): Promise<void> {
16
+ const { record, parent } = run, agentDir = getAgentDir();
17
+ // Queued runs can survive reload. Check the registry captured at launch before loading resources.
18
+ const modelRuntime = parentModelRuntime(parent.ctx);
19
+ const { settingsManager, loader, scope } = await childResources(run, factory);
20
+ if (run.controller.signal.aborted) return;
21
+ const manager = run.sessionManager ?? (record.sessionFile ? SessionManager.open(record.sessionFile)
22
+ : record.persisted ? createChildSession(record.cwd, parent.ctx.sessionManager.getSessionFile(),
23
+ run.type.sessionDir === undefined ? undefined : resourcePath(run.type.sessionDir, record.cwd)) : SessionManager.inMemory(record.cwd));
24
+ const capture = createStructuredCapture();
25
+ const { session, extensionsResult } = await createAgentSession({ cwd: record.cwd, agentDir, sessionManager: manager,
26
+ settingsManager, resourceLoader: loader, modelRuntime, model: run.model, thinkingLevel: record.thinking,
27
+ excludeTools: run.type.excludeTools,
28
+ customTools: run.options.structuredOutput ? [createStructuredOutputTool(run.options.structuredOutput, capture)] : undefined });
29
+ run.session = session; run.sessionManager = manager; record.sessionFile = manager.getSessionFile();
30
+ // Creation awaits SDK/resource startup. An individual edit accepted during that await must
31
+ // reach the first request even when the SDK was initially constructed with the earlier value.
32
+ if (session.model?.provider !== run.model.provider || session.model?.id !== run.model.id) await session.setModel(run.model, { persist: false });
33
+ session.setThinkingLevel(record.thinking, { persist: false });
34
+ record.thinking = session.thinkingLevel;
35
+ session.setSessionName(`${record.name} · ${record.id}`);
36
+ const errors: string[] = extensionsResult.errors.map(error => `${error.path}: ${error.error}`);
37
+ await session.bindExtensions({ mode: 'print', onError: error => { errors.push(error.error); } });
38
+ if (errors.length) throw new Error(errors.join('; '));
39
+ installExtensionToolScope(session, scope);
40
+ const extensionRunner = session.extensionRunner;
41
+ run.renderers = new Map();
42
+ for (const tool of session.getAllTools()) {
43
+ const renderer = extensionRunner.resolveToolRenderers(tool.name, () => session.getToolDefinition(tool.name));
44
+ if (renderer) run.renderers.set(tool.name, renderer);
45
+ }
46
+ // Retained transcripts can still resolve the child's extensions after the session closes.
47
+ run.customRenderers = {
48
+ getMessageRenderer: extensionRunner.getMessageRenderer.bind(extensionRunner),
49
+ getEntryRenderer: extensionRunner.getEntryRenderer.bind(extensionRunner),
50
+ };
51
+ run.liveResults = new Map();
52
+ const before = session.getSessionStats();
53
+ const updateUsage = () => {
54
+ const usage = session.getSessionStats(); record.usage = { tokens: Object.fromEntries(Object.entries(usage.tokens)
55
+ .map(([key, value]) => [key, value - before.tokens[key as keyof typeof before.tokens]])) as typeof usage.tokens, cost: usage.cost - before.cost };
56
+ record.contextUsage = usage.contextUsage;
57
+ };
58
+ const inflight = new Map<string, string>();
59
+ let turns = 0;
60
+ const unsubscribe = session.subscribe(event => {
61
+ if (event.type === 'entry_appended' && event.entry.type === 'custom' && event.entry.customType === AGENT_ENTRY) return;
62
+ // SDK message_end precedes persistence and ordinary messages emit no entry_appended.
63
+ // Tool start and turn end run after persistence, so stats include billed messages.
64
+ if (event.type === 'tool_execution_start' || event.type === 'turn_end' || event.type === 'entry_appended'
65
+ && (event.entry.type === 'usage' || (event.entry.type === 'compaction' || event.entry.type === 'branch_summary') && event.entry.usage)) updateUsage();
66
+ if (event.type === 'message_update') run.streamingEntry = { type: 'message', id: `stream:${record.runId}`, parentId: manager.getLeafId(), timestamp: new Date(event.message.timestamp).toISOString(), message: event.message };
67
+ else if (event.type === 'message_end') run.streamingEntry = undefined;
68
+ if (event.type === 'tool_execution_update') run.liveResults!.set(event.toolCallId, { type: 'message', id: `stream:${event.toolCallId}`, parentId: manager.getLeafId(), timestamp: new Date().toISOString(),
69
+ message: { role: 'toolResult', toolCallId: event.toolCallId, toolName: event.toolName, ...event.partialResult, isError: false, timestamp: Date.now() } });
70
+ else if (event.type === 'tool_execution_end') run.liveResults!.delete(event.toolCallId);
71
+ if (event.type === 'turn_start') {
72
+ turns++;
73
+ record.turns = turns; record.activity = 'Generating response';
74
+ if (run.maxTurns && turns > run.maxTurns) { record.state = 'limited'; run.controller.abort(); }
75
+ }
76
+ if (event.type === 'tool_execution_start') {
77
+ record.toolUses = (record.toolUses ?? 0) + 1;
78
+ const args = sanitizeText(JSON.stringify(event.args)).replace(/\s+/g, ' ');
79
+ inflight.set(event.toolCallId, `tool ${event.toolName} ${args.length > 180 ? `${args.slice(0, 177)}...` : args}`);
80
+ }
81
+ if (event.type === 'tool_execution_end') inflight.delete(event.toolCallId);
82
+ // Concurrent calls end independently; one completed call must not hide the others.
83
+ if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') record.activity = [...inflight.values()].join(' · ') || 'Generating response';
84
+ if (event.type === 'agent_settled' && event.aborted) run.controller.abort();
85
+ if (event.type === 'message_end' && event.message.role === 'assistant') emitEvent('usage', { usage: event.message.usage });
86
+ if (event.type === 'compaction_end' && event.result && !event.aborted) {
87
+ updateUsage();
88
+ record.compactionCount = (record.compactionCount ?? 0) + 1;
89
+ const info = { reason: event.reason, tokensBefore: event.result.tokensBefore, compactionCount: record.compactionCount };
90
+ run.options.onCompaction?.(info); emitEvent('compacted', info);
91
+ }
92
+ record.lastUpdateAt = new Date().toISOString();
93
+ record.sessionFile = manager.getSessionFile();
94
+ changed();
95
+ });
96
+ const abort = () => { void session.abort(); };
97
+ run.controller.signal.addEventListener('abort', abort, { once: true });
98
+ let requestError: string | undefined;
99
+ const prompt = async (message: string) => {
100
+ await session.prompt(message, { source: 'extension' });
101
+ const last = manager.getBranch().findLast(entry => entry.type === 'message' && entry.message.role === 'assistant');
102
+ if (last?.type === 'message' && last.message.role === 'assistant' && last.message.stopReason === 'error') {
103
+ requestError = last.message.errorMessage ?? 'Model request failed. Check the configured model and provider before retrying.';
104
+ }
105
+ };
106
+ try {
107
+ if (!run.controller.signal.aborted) {
108
+ record.state = 'running'; emitEvent('started'); changed();
109
+ await prompt(`${run.inheritedContext ?? ''}${record.prompt}`);
110
+ // Leave unsubmitted messages on the run so its replacement can still deliver them.
111
+ while (requestError === undefined && !run.controller.signal.aborted && run.pendingMessages.length) await prompt(run.pendingMessages.shift()!);
112
+ // The SDK cannot force a tool call; prompt once more rather than treating prose as structured output.
113
+ if (requestError === undefined && run.options.structuredOutput && !capture.json && !run.controller.signal.aborted) {
114
+ record.structuredRetried = true;
115
+ await prompt(structuredRetryPrompt(capture));
116
+ }
117
+ }
118
+ const entries = manager.getBranch();
119
+ record.result = resultText(entries); record.endLeafId = manager.getLeafId();
120
+ updateUsage();
121
+ if (requestError !== undefined) throw new ModelRequestError(requestError, settingsManager.getRetrySettings(), errors);
122
+ if (run.options.structuredOutput && !run.controller.signal.aborted) {
123
+ if (capture.json === undefined) errors.push(capture.lastError ?? 'Agent did not report StructuredOutput. Retry with a task that asks it to call StructuredOutput.');
124
+ else { record.structuredJson = capture.json; record.result = capture.json; }
125
+ }
126
+ if (errors.length) throw new Error(errors.join('; '));
127
+ } finally {
128
+ record.activity = undefined;
129
+ unsubscribe(); run.controller.signal.removeEventListener('abort', abort);
130
+ }
131
+ }
@@ -0,0 +1,40 @@
1
+ import { loadConfig } from '../runtime/config.ts';
2
+ import { acquireOwner, ownerBusy, type OwnerHandle } from '../runtime/owner.ts';
3
+ import { acquireRuntime } from '../jobs/runtime.ts';
4
+ import { AgentManager } from './manager.ts';
5
+ import { getAgentDir } from '@earendil-works/pi-coding-agent';
6
+
7
+ import { AGENT_OWNER, existingAgentRuntime, WORKFLOW_OWNER } from './registry.ts';
8
+
9
+ /**
10
+ * Reload changes listeners; existing SDK sessions and queued runs keep their owner. The start
11
+ * callback closes over this module load's config loader and child stack, so an owner from an
12
+ * earlier load is replaced once idle (see runtime/owner.ts).
13
+ */
14
+ export function agentRuntime(): OwnerHandle<AgentManager> {
15
+ const agentDir = getAgentDir();
16
+ return acquireOwner(AGENT_OWNER, 'subagents', agentDir, () => {
17
+ const runtime = acquireRuntime(agentDir);
18
+ let execution: Promise<readonly [typeof import('./runner.ts'), typeof import('./child.ts')]> | undefined;
19
+ const manager: AgentManager = new AgentManager(async run => {
20
+ // Resolve ordinary child settings when its slot starts. Workflow continuation
21
+ // fixes its original config; resources and tools must read the same snapshot.
22
+ if (!run.record.workflowId) run.config = loadConfig(run.configCwd);
23
+ // Concurrent first starts share one load; Jiti must finish shared dependencies in order.
24
+ execution ??= (async () => [await import('./runner.ts'), await import('./child.ts')] as const)();
25
+ const [{ executeAgent }, { childSuite }] = await execution;
26
+ return executeAgent(run, pi => childSuite(pi, run, manager), manager.changed,
27
+ (kind, details) => manager.event(kind, run, details));
28
+ }, async ids => {
29
+ if (runtime.mode !== 'active') throw new Error(`Cannot stop agent jobs: ${runtime.reason}`);
30
+ return (await runtime.manager.stopCreatedBy(ids)).map(({ job }) => ({ id: job.id, state: job.state, cleanup: job.cleanup.state }));
31
+ });
32
+ return manager;
33
+ // A running workflow drives this owner; closing it would fail the workflow's next agent.
34
+ }, { dependants: () => ownerBusy(WORKFLOW_OWNER, agentDir) });
35
+ }
36
+
37
+ /** Query only: quit must not create an owner when agent tools are disabled. */
38
+ export function quitExistingAgentRuntime(agentDir: string): Promise<void> | undefined {
39
+ return existingAgentRuntime(agentDir)?.shutdown();
40
+ }