@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,24 @@
1
+ /**
2
+ * skill-loader.ts — Preload named skills.
3
+ *
4
+ * Roots, in precedence order:
5
+ * - <cwd>/.pi/skills (project, Pi's standard)
6
+ * - <cwd>/.agents/skills (project, cross-tool Agent Skills spec — https://agentskills.io)
7
+ * - getAgentDir()/skills (user, default ~/.pi/agent/skills — Pi's standard)
8
+ * - ~/.agents/skills (user, cross-tool Agent Skills spec)
9
+ * - ~/.pi/skills (legacy global, pre-Pi)
10
+ *
11
+ * Layout per root:
12
+ * - <root>/<name>.md (flat file at the top level)
13
+ * - <root>/.../<name>/SKILL.md (directory skill, may be nested — Pi's standard)
14
+ *
15
+ * Recursion skips dotfile entries and node_modules. A directory that itself contains
16
+ * SKILL.md is a skill — we don't descend into it (Pi: skills don't nest).
17
+ *
18
+ * Symlinks are rejected for security (deviation from Pi, which follows them).
19
+ */
20
+ export interface PreloadedSkill {
21
+ name: string;
22
+ content: string;
23
+ }
24
+ export declare function preloadSkills(skillNames: string[], cwd: string): PreloadedSkill[];
@@ -0,0 +1,93 @@
1
+ /**
2
+ * skill-loader.ts — Preload named skills.
3
+ *
4
+ * Roots, in precedence order:
5
+ * - <cwd>/.pi/skills (project, Pi's standard)
6
+ * - <cwd>/.agents/skills (project, cross-tool Agent Skills spec — https://agentskills.io)
7
+ * - getAgentDir()/skills (user, default ~/.pi/agent/skills — Pi's standard)
8
+ * - ~/.agents/skills (user, cross-tool Agent Skills spec)
9
+ * - ~/.pi/skills (legacy global, pre-Pi)
10
+ *
11
+ * Layout per root:
12
+ * - <root>/<name>.md (flat file at the top level)
13
+ * - <root>/.../<name>/SKILL.md (directory skill, may be nested — Pi's standard)
14
+ *
15
+ * Recursion skips dotfile entries and node_modules. A directory that itself contains
16
+ * SKILL.md is a skill — we don't descend into it (Pi: skills don't nest).
17
+ *
18
+ * Symlinks are rejected for security (deviation from Pi, which follows them).
19
+ */
20
+ import { existsSync, readdirSync } from "node:fs";
21
+ import { homedir } from "node:os";
22
+ import { join } from "node:path";
23
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
24
+ import { isSymlink, isUnsafeName, safeReadFile } from "./memory.js";
25
+ export function preloadSkills(skillNames, cwd) {
26
+ return skillNames.map((name) => ({ name, content: loadSkillContent(name, cwd) }));
27
+ }
28
+ function loadSkillContent(name, cwd) {
29
+ if (isUnsafeName(name)) {
30
+ return `(Skill "${name}" skipped: name contains path traversal characters)`;
31
+ }
32
+ const roots = [
33
+ join(cwd, ".pi", "skills"), // project — Pi standard
34
+ join(cwd, ".agents", "skills"), // project — Agent Skills spec
35
+ join(getAgentDir(), "skills"), // user — Pi standard
36
+ join(homedir(), ".agents", "skills"), // user — Agent Skills spec
37
+ join(homedir(), ".pi", "skills"), // legacy global, pre-Pi
38
+ ];
39
+ for (const root of roots) {
40
+ const content = findInRoot(root, name);
41
+ if (content !== undefined)
42
+ return content;
43
+ }
44
+ return `(Skill "${name}" not found in .pi/skills/, .agents/skills/, or global skill locations)`;
45
+ }
46
+ function findInRoot(root, name) {
47
+ if (isSymlink(root))
48
+ return undefined; // reject symlinked roots entirely
49
+ const flat = safeReadFile(join(root, `${name}.md`))?.trim();
50
+ if (flat !== undefined)
51
+ return flat;
52
+ return findSkillDirectory(root, name);
53
+ }
54
+ /** BFS under `root` for a directory named `name` containing `SKILL.md`. Pi-conforming filters. */
55
+ function findSkillDirectory(root, name) {
56
+ if (!existsSync(root))
57
+ return undefined;
58
+ const queue = [root];
59
+ while (queue.length > 0) {
60
+ const current = queue.shift();
61
+ if (current === undefined)
62
+ continue;
63
+ let entries;
64
+ try {
65
+ entries = readdirSync(current, { withFileTypes: true });
66
+ }
67
+ catch {
68
+ continue;
69
+ }
70
+ // Deterministic byte-order traversal — locale-independent.
71
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
72
+ for (const entry of entries) {
73
+ if (!entry.isDirectory())
74
+ continue;
75
+ if (entry.name.startsWith(".") || entry.name === "node_modules")
76
+ continue;
77
+ // Symlinked dirs already filtered by entry.isDirectory() — Dirent uses lstat semantics.
78
+ const path = join(current, entry.name);
79
+ const skillMd = join(path, "SKILL.md");
80
+ const isSkillDir = existsSync(skillMd);
81
+ if (isSkillDir) {
82
+ if (entry.name === name) {
83
+ const content = safeReadFile(skillMd)?.trim();
84
+ if (content !== undefined)
85
+ return content;
86
+ }
87
+ continue; // Pi rule: skills don't nest — don't descend into a skill dir
88
+ }
89
+ queue.push(path);
90
+ }
91
+ }
92
+ return undefined;
93
+ }
@@ -0,0 +1,30 @@
1
+ import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
2
+ import type { AgentSession, ExtensionContext, LoadExtensionsResult, SettingsManager } from "@earendil-works/pi-coding-agent";
3
+ export type RecoveryOwnership = "absent" | "present" | "unknown";
4
+ export interface StandalonePolicy {
5
+ model: string;
6
+ ownership(): RecoveryOwnership;
7
+ resolve(session: AgentSession, failed: {
8
+ provider: string;
9
+ id: string;
10
+ }): Model<Api> | undefined;
11
+ }
12
+ /** No package manager: remote/unresolved sources and unsupported layouts fail closed.
13
+ * Inspect both settings files (even disabled/untrusted entries), loaded/pre-filter
14
+ * identities, and local discovery roots. Never execute a resource to identify it.
15
+ */
16
+ export declare function inventoryRecoveryOwner(options: {
17
+ configCwd: string;
18
+ agentDir: string;
19
+ settingsManager: Pick<SettingsManager, "getGlobalSettings" | "getProjectSettings">;
20
+ loaded: Pick<LoadExtensionsResult, "extensions" | "errors">;
21
+ discovered?: Pick<LoadExtensionsResult, "extensions" | "errors">;
22
+ additionalPaths?: string[];
23
+ }): RecoveryOwnership;
24
+ /** A deny wins even when a provider also says retry, overload, or HTTP 500. */
25
+ export declare function isTransientProviderFailure(message: AssistantMessage | undefined): boolean;
26
+ export declare function resolveStandaloneModel(input: string, session: AgentSession, registry: ExtensionContext["modelRegistry"], configCwd: string, failed?: {
27
+ provider: string;
28
+ id: string;
29
+ } | undefined): Model<Api> | undefined;
30
+ export declare const STANDALONE_CONTINUATION = "Continue the existing task from the conversation above after the transient provider failure. Do not restart the task or repeat completed tool actions. Use the recorded tool results and finish the remaining work.";
@@ -0,0 +1,239 @@
1
+ /** Local-only evidence and policy for the optional, single-target child fallback. */
2
+ import { lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import { resolveModel } from "./model-resolver.js";
6
+ import { checkModelScope } from "./model-scope.js";
7
+ const OWNER = /(?:pi[-_]?)?fallback[-_]chains/i;
8
+ const LEGACY = /registerCommand\s*\(\s*["'`]fallback(?:["'`:\s-])/i;
9
+ /** No package manager: remote/unresolved sources and unsupported layouts fail closed.
10
+ * Inspect both settings files (even disabled/untrusted entries), loaded/pre-filter
11
+ * identities, and local discovery roots. Never execute a resource to identify it.
12
+ */
13
+ export function inventoryRecoveryOwner(options) {
14
+ let present = false;
15
+ let uncertain = false;
16
+ let remaining = 512;
17
+ const seen = new Set();
18
+ const evidence = (text) => { if (OWNER.test(text) || LEGACY.test(text))
19
+ present = true; };
20
+ const readJson = (path) => {
21
+ try {
22
+ const text = readFileSync(path, "utf8").replace(/^\uFEFF/, "");
23
+ const value = JSON.parse(text);
24
+ if (!value || typeof value !== "object" || Array.isArray(value))
25
+ throw new Error("Invalid inventory object");
26
+ return value;
27
+ }
28
+ catch (error) {
29
+ if (error.code !== "ENOENT")
30
+ uncertain = true;
31
+ return undefined;
32
+ }
33
+ };
34
+ const inspect = (path, optional = false) => {
35
+ evidence(path);
36
+ if (present)
37
+ return;
38
+ try {
39
+ // lstat distinguishes a genuinely absent optional root from a broken link.
40
+ lstatSync(path);
41
+ const real = realpathSync(path);
42
+ evidence(real);
43
+ if (seen.has(real))
44
+ return;
45
+ seen.add(real);
46
+ if (--remaining < 0) {
47
+ uncertain = true;
48
+ return;
49
+ }
50
+ const stats = statSync(real);
51
+ if (stats.isFile()) {
52
+ if (stats.size > 2 * 1024 * 1024) {
53
+ uncertain = true;
54
+ return;
55
+ }
56
+ evidence(readFileSync(real, "utf8"));
57
+ // Loaded paths can be aliased entrypoints (e.g. src/index.ts). Check
58
+ // the owning manifest too, stopping before another node_modules tree.
59
+ for (let dir = dirname(real); basename(dir) !== "node_modules"; dir = dirname(dir)) {
60
+ const pkg = readJson(join(dir, "package.json"));
61
+ if (pkg) {
62
+ if (typeof pkg.name === "string")
63
+ evidence(pkg.name);
64
+ break;
65
+ }
66
+ if (dirname(dir) === dir)
67
+ break;
68
+ }
69
+ return;
70
+ }
71
+ if (!stats.isDirectory()) {
72
+ uncertain = true;
73
+ return;
74
+ }
75
+ const pkg = readJson(join(real, "package.json"));
76
+ if (pkg) {
77
+ if (typeof pkg.name === "string")
78
+ evidence(pkg.name);
79
+ const pi = pkg.pi;
80
+ if (pi && typeof pi !== "object") {
81
+ uncertain = true;
82
+ return;
83
+ }
84
+ if (pi?.extensions !== undefined) {
85
+ inspectSources(pi.extensions, real);
86
+ return;
87
+ }
88
+ }
89
+ const entries = readdirSync(real, { withFileTypes: true });
90
+ const index = entries.find(e => e.name === "index.ts") ?? entries.find(e => e.name === "index.js");
91
+ if (index) {
92
+ inspect(join(real, index.name));
93
+ return;
94
+ }
95
+ // Superset of Pi's shallow discovery: also inspect package/convention
96
+ // directories, ignoring enable/disable filters so exclusion is not absence.
97
+ for (const entry of entries) {
98
+ if (entry.name.startsWith(".") || entry.name === "node_modules")
99
+ continue;
100
+ if (entry.isDirectory() || entry.isSymbolicLink() || /\.(ts|js)$/.test(entry.name))
101
+ inspect(join(real, entry.name));
102
+ }
103
+ }
104
+ catch (error) {
105
+ if (!optional || error.code !== "ENOENT")
106
+ uncertain = true;
107
+ else {
108
+ // A dangling optional symlink is not a missing directory.
109
+ try {
110
+ lstatSync(path);
111
+ uncertain = true;
112
+ }
113
+ catch (missing) {
114
+ if (missing.code !== "ENOENT")
115
+ uncertain = true;
116
+ }
117
+ }
118
+ }
119
+ };
120
+ const inspectSources = (value, base) => {
121
+ if (value === undefined)
122
+ return;
123
+ if (!Array.isArray(value)) {
124
+ uncertain = true;
125
+ return;
126
+ }
127
+ for (const entry of value) {
128
+ const source = typeof entry === "string" ? entry : entry?.source;
129
+ if (typeof source !== "string" || !source.trim()) {
130
+ uncertain = true;
131
+ continue;
132
+ }
133
+ evidence(source);
134
+ const path = source.trim().replace(/^[!+-]/, "");
135
+ if (path.startsWith("npm:")) {
136
+ // Pi's managed npm layout is documented and local. Do not call npm
137
+ // root/install (legacy global installs without this root are unknown).
138
+ const match = /^npm:((?:@[\w.-]+\/)?[\w.-]+)(?:@[^/]+)?$/.exec(path);
139
+ const name = match?.[1];
140
+ if (!name || name.split("/").some(part => part === "." || part === "..")) {
141
+ uncertain = true;
142
+ continue;
143
+ }
144
+ const root = join(base, "npm", "node_modules", name);
145
+ const pkg = readJson(join(root, "package.json"));
146
+ if (pkg?.name !== name)
147
+ uncertain = true;
148
+ inspect(root);
149
+ }
150
+ else if (/^(git:|https?:|ssh:|git@)/.test(path) || /[*?{}[\]]/.test(path)) {
151
+ uncertain = true; // Never resolve/install packages or guess a glob's completeness.
152
+ }
153
+ else {
154
+ inspect(resolve(base, path.startsWith("~/") || path.startsWith("~\\") ? homedir() + path.slice(1) : path));
155
+ }
156
+ }
157
+ };
158
+ try {
159
+ for (const result of [options.discovered, options.loaded]) {
160
+ if (!result)
161
+ continue;
162
+ for (const error of result.errors) {
163
+ evidence(error.path);
164
+ evidence(error.error);
165
+ uncertain = true;
166
+ }
167
+ for (const extension of result.extensions) {
168
+ evidence(extension.path);
169
+ if (extension.sourceInfo)
170
+ evidence(extension.sourceInfo.source);
171
+ if (extension.commands?.has("fallback"))
172
+ present = true;
173
+ inspect(extension.resolvedPath ?? extension.path);
174
+ }
175
+ }
176
+ for (const [base, settings] of [
177
+ [options.agentDir, options.settingsManager.getGlobalSettings()],
178
+ [join(options.configCwd, ".pi"), options.settingsManager.getProjectSettings()],
179
+ ]) {
180
+ // Raw settings detect load errors and entries hidden by trust/overrides.
181
+ for (const config of [settings, readJson(join(base, "settings.json"))]) {
182
+ if (!config)
183
+ continue;
184
+ inspectSources(config.packages, base);
185
+ inspectSources(config.extensions, base);
186
+ }
187
+ inspect(join(base, "extensions"), true);
188
+ // A retained legacy config is evidence, including enabled:false.
189
+ for (const name of ["fallback-chains.json", "pi-fallback-chains.json"]) {
190
+ try {
191
+ lstatSync(join(base, name));
192
+ present = true;
193
+ }
194
+ catch (error) {
195
+ if (error.code !== "ENOENT")
196
+ uncertain = true;
197
+ }
198
+ }
199
+ }
200
+ inspectSources(options.additionalPaths, options.configCwd);
201
+ }
202
+ catch {
203
+ uncertain = true;
204
+ }
205
+ if (present)
206
+ return "present";
207
+ return uncertain ? "unknown" : "absent";
208
+ }
209
+ /** A deny wins even when a provider also says retry, overload, or HTTP 500. */
210
+ export function isTransientProviderFailure(message) {
211
+ if (message?.stopReason !== "error" || !message.errorMessage)
212
+ return false;
213
+ const error = message.errorMessage;
214
+ if (/auth|api[ _-]?key|credential|permission|forbidden|access.denied|unauthori[sz]ed|\b40[123]\b|billing|payment|credit|quota|context|token.limit|too.many.tokens|prompt.too.long|safety|content.filter|policy|refus|cancel|abort|tool|invalid.request|bad.request|not.found|\b40[04]\b/i.test(error))
215
+ return false;
216
+ return /\b(?:408|429|500|502|503|504|529)\b|rate[ _-]?limit|too many requests|overload|temporar(?:y|ily).*(?:unavailable|failure)|service.unavailable|internal.(?:server|backend).error|\bECONNRESET\b|\bETIMEDOUT\b|socket hang up|connection (?:reset|closed)|(?:request|connection|gateway) timed? ?out/i.test(error);
217
+ }
218
+ export function resolveStandaloneModel(input, session, registry, configCwd, failed = session.model) {
219
+ const available = registry.getAvailable(); // authenticated snapshot; never getAll fallback
220
+ const requested = input.trim();
221
+ if (!requested)
222
+ return undefined;
223
+ const target = requested.includes("/")
224
+ ? available.find(m => `${m.provider}/${m.id}` === requested)
225
+ : resolveModel(requested, registry);
226
+ if (!target || typeof target === "string" || !available.some(m => m.provider === target.provider && m.id === target.id))
227
+ return undefined;
228
+ if (failed?.provider === target.provider && failed.id === target.id)
229
+ return undefined;
230
+ const scope = session.scopedModels;
231
+ if (!scope || (scope.length > 0 && !scope.some(({ model }) => model.provider === target.provider && model.id === target.id)))
232
+ return undefined;
233
+ // Automatic recovery is not the primary frontmatter pin exception.
234
+ if (checkModelScope({ model: target, cwd: configCwd, modelRegistry: registry,
235
+ callerSupplied: true, agentLabel: "standalone recovery", modelInput: requested }).kind !== "ok")
236
+ return undefined;
237
+ return target;
238
+ }
239
+ export const STANDALONE_CONTINUATION = "Continue the existing task from the conversation above after the transient provider failure. Do not restart the task or repeat completed tool actions. Use the recorded tool results and finish the remaining work.";
@@ -0,0 +1,61 @@
1
+ /**
2
+ * status-note.ts — Honest framing for an agent result: the parenthetical status
3
+ * note for a non-normal outcome, and the salvaged partial output of a failure.
4
+ *
5
+ * Lives here rather than in an index.ts closure because both entry points need
6
+ * it — the top-level tools and the nested delegation tools, which can't import
7
+ * from index.ts (that is the extension entry, and it already reaches these tools
8
+ * through agent-runner).
9
+ */
10
+ import type { AgentRecord } from "./types.ts";
11
+ /**
12
+ * Explicit parenthetical note for a non-normal terminal outcome, so the parent
13
+ * agent can't mistake partial output for a completed result. Empty string for a
14
+ * clean completion (and any unknown/non-terminal status).
15
+ *
16
+ * `stopped` (a human aborted it) is deliberately distinct from `aborted` (the
17
+ * turn limit was hit) — the parent should treat human intervention differently
18
+ * from a budget cutoff.
19
+ */
20
+ export declare function getStatusNote(status: string): string;
21
+ /**
22
+ * Foreground variant of `getStatusNote`. A foreground caller is in a different
23
+ * position from a background one, so it needs different text:
24
+ *
25
+ * - It already holds the agent's ENTIRE output inline, whereas the background
26
+ * notification carries a 500-char preview. So only here can we truthfully
27
+ * say there is nothing more to fetch — which is the whole point, because
28
+ * - it has no agent id. The id travels in the tool result's renderer
29
+ * `details`, which is never serialized to the model. A parent that reads
30
+ * "output may be partial" as "truncated, go retrieve the rest" therefore
31
+ * has nothing valid to call `get_subagent_result` with, and will invent an
32
+ * id (#174).
33
+ *
34
+ * Only the lead clause varies between the three, and each variation carries
35
+ * information: `wrapped up` vs `aborted` tells the parent whether the output is
36
+ * a considered final answer or a fragment, and `stopped` shouts because a human
37
+ * intervening outranks everything else in the string. Only `steered` hedges on
38
+ * completion — it was told to wrap up and did, so it may well have finished at
39
+ * the limit; an aborted run blew through its grace turns while still working,
40
+ * and `stopped` can only fire on a running agent, so neither ever delivered a
41
+ * final answer. Identical confidence gets identical wording: phrasing one fact
42
+ * two ways invites a hunt for a distinction that isn't there.
43
+ *
44
+ * Every clause is a statement about state, never an instruction to act, and
45
+ * `get_subagent_result` is never named — naming the tool we steer away from only
46
+ * raises its salience. Two instructions were tried here and cut: "re-spawn with
47
+ * a higher max_turns" (pushes a fresh multi-minute run to save one wasted tool
48
+ * call) and, on `stopped`, "ask before restarting it" (restates the lead, and
49
+ * presumes someone is present to ask — false under `pi -p`, in scheduled jobs,
50
+ * and in any background-driven run). Nothing here can measure whether wording
51
+ * improves parent behavior, so removing a false cue (which cannot induce new
52
+ * behavior) and adding an instruction (which can) are not equally safe bets.
53
+ * Don't add either back without a way to measure it.
54
+ */
55
+ export declare function getForegroundOutcomeNote(status: string): string;
56
+ /**
57
+ * Salvaged partial output of a failed run, as a labeled suffix for the error
58
+ * surfaces (or "" if the run produced nothing). `record.result` is bounded to
59
+ * the run's own turns, so this is never a stale earlier answer (#144).
60
+ */
61
+ export declare function partialOutputSuffix(record: AgentRecord): string;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * status-note.ts — Honest framing for an agent result: the parenthetical status
3
+ * note for a non-normal outcome, and the salvaged partial output of a failure.
4
+ *
5
+ * Lives here rather than in an index.ts closure because both entry points need
6
+ * it — the top-level tools and the nested delegation tools, which can't import
7
+ * from index.ts (that is the extension entry, and it already reaches these tools
8
+ * through agent-runner).
9
+ */
10
+ /**
11
+ * Explicit parenthetical note for a non-normal terminal outcome, so the parent
12
+ * agent can't mistake partial output for a completed result. Empty string for a
13
+ * clean completion (and any unknown/non-terminal status).
14
+ *
15
+ * `stopped` (a human aborted it) is deliberately distinct from `aborted` (the
16
+ * turn limit was hit) — the parent should treat human intervention differently
17
+ * from a budget cutoff.
18
+ */
19
+ export function getStatusNote(status) {
20
+ switch (status) {
21
+ case "stopped":
22
+ return " (STOPPED BY THE USER before completion — output is partial; the task was NOT finished)";
23
+ case "aborted":
24
+ return " (aborted — hit the turn limit before completion; output may be incomplete)";
25
+ case "steered":
26
+ return " (wrapped up at the turn limit — output may be partial)";
27
+ default:
28
+ return "";
29
+ }
30
+ }
31
+ /**
32
+ * Foreground variant of `getStatusNote`. A foreground caller is in a different
33
+ * position from a background one, so it needs different text:
34
+ *
35
+ * - It already holds the agent's ENTIRE output inline, whereas the background
36
+ * notification carries a 500-char preview. So only here can we truthfully
37
+ * say there is nothing more to fetch — which is the whole point, because
38
+ * - it has no agent id. The id travels in the tool result's renderer
39
+ * `details`, which is never serialized to the model. A parent that reads
40
+ * "output may be partial" as "truncated, go retrieve the rest" therefore
41
+ * has nothing valid to call `get_subagent_result` with, and will invent an
42
+ * id (#174).
43
+ *
44
+ * Only the lead clause varies between the three, and each variation carries
45
+ * information: `wrapped up` vs `aborted` tells the parent whether the output is
46
+ * a considered final answer or a fragment, and `stopped` shouts because a human
47
+ * intervening outranks everything else in the string. Only `steered` hedges on
48
+ * completion — it was told to wrap up and did, so it may well have finished at
49
+ * the limit; an aborted run blew through its grace turns while still working,
50
+ * and `stopped` can only fire on a running agent, so neither ever delivered a
51
+ * final answer. Identical confidence gets identical wording: phrasing one fact
52
+ * two ways invites a hunt for a distinction that isn't there.
53
+ *
54
+ * Every clause is a statement about state, never an instruction to act, and
55
+ * `get_subagent_result` is never named — naming the tool we steer away from only
56
+ * raises its salience. Two instructions were tried here and cut: "re-spawn with
57
+ * a higher max_turns" (pushes a fresh multi-minute run to save one wasted tool
58
+ * call) and, on `stopped`, "ask before restarting it" (restates the lead, and
59
+ * presumes someone is present to ask — false under `pi -p`, in scheduled jobs,
60
+ * and in any background-driven run). Nothing here can measure whether wording
61
+ * improves parent behavior, so removing a false cue (which cannot induce new
62
+ * behavior) and adding an instruction (which can) are not equally safe bets.
63
+ * Don't add either back without a way to measure it.
64
+ */
65
+ export function getForegroundOutcomeNote(status) {
66
+ switch (status) {
67
+ case "stopped":
68
+ return " (STOPPED BY THE USER — everything the agent produced is above; the task is unfinished)";
69
+ case "aborted":
70
+ return " (aborted at the turn limit — everything the agent produced is above; the task is unfinished)";
71
+ case "steered":
72
+ return " (wrapped up at the turn limit — everything the agent produced is above; the task may be unfinished)";
73
+ default:
74
+ return "";
75
+ }
76
+ }
77
+ /**
78
+ * Salvaged partial output of a failed run, as a labeled suffix for the error
79
+ * surfaces (or "" if the run produced nothing). `record.result` is bounded to
80
+ * the run's own turns, so this is never a stale earlier answer (#144).
81
+ */
82
+ export function partialOutputSuffix(record) {
83
+ const partial = record.result?.trim();
84
+ return partial ? `\n\nPartial output before the failure:\n${partial}` : "";
85
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * structured-output.ts — the synthetic tool behind `agent(prompt, { schema })`.
3
+ *
4
+ * A workflow script that passes a `schema` wants an *object* back, not prose it
5
+ * has to parse. Claude Code does this by giving the child a `StructuredOutput`
6
+ * tool whose input schema is the caller's schema, so the provider fills the
7
+ * fields, and returning the validated payload as the agent's result.
8
+ *
9
+ * We do the same, with one gap named up front: Claude Code *forces* the call,
10
+ * and we cannot. `toolChoice` exists in pi-ai's provider layer but is not
11
+ * plumbed through `AgentSession`, so an extension has no way to require a
12
+ * particular tool. What we have instead is three softer pressures —
13
+ *
14
+ * 1. `constrainedSampling`, so providers that support it hold the payload to
15
+ * the schema at sampling time;
16
+ * 2. the tool's description, snippet and guideline, which say the answer must
17
+ * come through this call;
18
+ * 3. validation here, answering a bad payload with `isError` so the model
19
+ * sees what was wrong and calls again inside the same run.
20
+ *
21
+ * — and, when all three fail, one more prompt from `runAgent`. See
22
+ * {@link structuredRetryPrompt}.
23
+ *
24
+ * The name matches Claude Code's exactly, so a ported prompt that mentions
25
+ * `StructuredOutput` is still telling the truth.
26
+ */
27
+ import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
28
+ import type { CompiledSchema } from "./workflow/json-schema.ts";
29
+ /**
30
+ * Deliberately NOT added to `SUBAGENT_TOOL_NAMES`: that list becomes
31
+ * `EXCLUDED_TOOL_NAMES`, which is exactly the denial this tool has to avoid.
32
+ * Nor to `BUILTIN_TOOL_NAMES` — it is ours to inject, never a name a user may
33
+ * ask for in an agent's `tools:` frontmatter.
34
+ */
35
+ export declare const STRUCTURED_OUTPUT_TOOL_NAME = "StructuredOutput";
36
+ /** What the child produced, filled in as the tool is called. */
37
+ export interface StructuredCapture {
38
+ /** The last payload that validated, canonicalised. Absent until one does. */
39
+ json?: string;
40
+ /** Why the most recent attempt was rejected, for the retry prompt. */
41
+ lastError?: string;
42
+ /** Whether the tool was called at all — "never tried" reads differently. */
43
+ called: boolean;
44
+ }
45
+ export declare function createStructuredCapture(): StructuredCapture;
46
+ /**
47
+ * Build the tool for one child.
48
+ *
49
+ * `capture` is the box the caller reads afterwards. It is passed in rather than
50
+ * returned so `runAgent` owns its lifetime and can consult it on every exit
51
+ * path, including the ones where the tool was never reached.
52
+ */
53
+ export declare function createStructuredOutputTool(compiled: CompiledSchema, capture: StructuredCapture): ToolDefinition;
54
+ /**
55
+ * The one extra prompt sent when a run ended with nothing captured.
56
+ *
57
+ * Distinguishes "never called it" from "called it wrongly" — the two need
58
+ * different corrections, and telling a model it got the shape wrong when it
59
+ * never answered at all sends it looking for a mistake it did not make.
60
+ */
61
+ export declare function structuredRetryPrompt(capture: StructuredCapture): string;