@xzzpig/pi-subagents 0.1.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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,182 @@
1
+ import * as fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
7
+ import type { JsonSchemaObject } from "../../shared/types.ts";
8
+
9
+ export const STRUCTURED_OUTPUT_SCHEMA_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA";
10
+ export const STRUCTURED_OUTPUT_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";
11
+ export const MISSING_STRUCTURED_OUTPUT_CALL_ERROR = "Missing structured_output call; this step has outputSchema and must finish by calling structured_output.";
12
+
13
+ export interface StructuredOutputRuntime {
14
+ schema: JsonSchemaObject;
15
+ schemaPath: string;
16
+ outputPath: string;
17
+ }
18
+
19
+ const SCHEMA_MAP_KEYWORDS = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"] as const;
20
+ const SCHEMA_SINGLE_KEYWORDS = ["additionalItems", "additionalProperties", "contains", "not", "propertyNames", "if", "then", "else", "unevaluatedItems", "unevaluatedProperties", "contentSchema"] as const;
21
+ const SCHEMA_ARRAY_KEYWORDS = ["allOf", "anyOf", "oneOf", "prefixItems"] as const;
22
+
23
+ function rewriteLocalJsonPointerRefs(schema: unknown, pointerPrefix: string, inheritsWrapperResource = true): unknown {
24
+ if (typeof schema === "boolean" || !schema || typeof schema !== "object" || Array.isArray(schema)) return schema;
25
+ const source = schema as Record<string, unknown>;
26
+ const rewritten: Record<string, unknown> = { ...source };
27
+ const sharesWrapperResource = inheritsWrapperResource && typeof source.$id !== "string";
28
+ if (sharesWrapperResource) {
29
+ for (const keyword of ["$ref", "$dynamicRef", "$recursiveRef"] as const) {
30
+ const ref = source[keyword];
31
+ if (ref === "#") rewritten[keyword] = pointerPrefix;
32
+ else if (typeof ref === "string" && ref.startsWith("#/")) rewritten[keyword] = `${pointerPrefix}${ref.slice(1)}`;
33
+ }
34
+ }
35
+ for (const keyword of SCHEMA_MAP_KEYWORDS) {
36
+ const entries = source[keyword];
37
+ if (!entries || typeof entries !== "object" || Array.isArray(entries)) continue;
38
+ rewritten[keyword] = Object.fromEntries(Object.entries(entries).map(([name, nested]) => [
39
+ name,
40
+ rewriteLocalJsonPointerRefs(nested, pointerPrefix, sharesWrapperResource),
41
+ ]));
42
+ }
43
+ const items = source.items;
44
+ if (Array.isArray(items)) rewritten.items = items.map((nested) => rewriteLocalJsonPointerRefs(nested, pointerPrefix, sharesWrapperResource));
45
+ else if (items !== undefined) rewritten.items = rewriteLocalJsonPointerRefs(items, pointerPrefix, sharesWrapperResource);
46
+ for (const keyword of SCHEMA_SINGLE_KEYWORDS) {
47
+ if (source[keyword] !== undefined) rewritten[keyword] = rewriteLocalJsonPointerRefs(source[keyword], pointerPrefix, sharesWrapperResource);
48
+ }
49
+ for (const keyword of SCHEMA_ARRAY_KEYWORDS) {
50
+ if (Array.isArray(source[keyword])) rewritten[keyword] = source[keyword].map((nested) => rewriteLocalJsonPointerRefs(nested, pointerPrefix, sharesWrapperResource));
51
+ }
52
+ const dependencies = source.dependencies;
53
+ if (dependencies && typeof dependencies === "object" && !Array.isArray(dependencies)) {
54
+ rewritten.dependencies = Object.fromEntries(Object.entries(dependencies).map(([name, nested]) => [
55
+ name,
56
+ Array.isArray(nested) ? nested : rewriteLocalJsonPointerRefs(nested, pointerPrefix, sharesWrapperResource),
57
+ ]));
58
+ }
59
+ return rewritten;
60
+ }
61
+
62
+ export function createStructuredOutputToolParameters(schema: JsonSchemaObject): JsonSchemaObject {
63
+ return {
64
+ type: "object",
65
+ properties: { value: rewriteLocalJsonPointerRefs(schema, "#/properties/value") },
66
+ required: ["value"],
67
+ additionalProperties: false,
68
+ };
69
+ }
70
+
71
+ interface CompiledJsonSchema {
72
+ Check(value: unknown): boolean;
73
+ Errors(value: unknown): Iterable<{ instancePath?: string; message?: string }>;
74
+ }
75
+
76
+ type CompileJsonSchema = (schema: unknown) => CompiledJsonSchema;
77
+
78
+ let cachedCompile: Promise<CompileJsonSchema> | undefined;
79
+
80
+ export async function resolveCompileFromPackageRoot(packageRoot: string): Promise<CompileJsonSchema | undefined> {
81
+ const requireFromRoot = createRequire(path.join(packageRoot, "package.json"));
82
+ const resolved = requireFromRoot.resolve("typebox/compile");
83
+ const mod = (await import(pathToFileURL(resolved).href)) as { Compile?: unknown };
84
+ return typeof mod.Compile === "function" ? (mod.Compile as CompileJsonSchema) : undefined;
85
+ }
86
+
87
+ async function importCompile(): Promise<CompileJsonSchema> {
88
+ const failures: string[] = [];
89
+ try {
90
+ const mod = (await import("typebox/compile")) as { Compile?: unknown };
91
+ if (typeof mod.Compile === "function") return mod.Compile as CompileJsonSchema;
92
+ failures.push("typebox/compile did not export a Compile function");
93
+ } catch (error) {
94
+ failures.push(`direct import failed: ${error instanceof Error ? error.message : String(error)}`);
95
+ }
96
+ const packageRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV];
97
+ if (packageRoot) {
98
+ try {
99
+ const compile = await resolveCompileFromPackageRoot(packageRoot);
100
+ if (compile) return compile;
101
+ failures.push("Pi package root typebox/compile did not export a Compile function");
102
+ } catch (error) {
103
+ failures.push(`Pi package root import failed: ${error instanceof Error ? error.message : String(error)}`);
104
+ }
105
+ } else {
106
+ failures.push(`${PI_CODING_AGENT_PACKAGE_ROOT_ENV} is not set`);
107
+ }
108
+ throw new Error(`Cannot load typebox/compile for structured output validation (${failures.join("; ")})`);
109
+ }
110
+
111
+ function loadCompile(): Promise<CompileJsonSchema> {
112
+ if (!cachedCompile) {
113
+ cachedCompile = importCompile().catch((error) => {
114
+ cachedCompile = undefined;
115
+ throw error;
116
+ });
117
+ }
118
+ return cachedCompile;
119
+ }
120
+
121
+ export function assertJsonSchemaObject(schema: unknown, label = "outputSchema"): asserts schema is JsonSchemaObject {
122
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
123
+ throw new Error(`${label} must be a JSON Schema object.`);
124
+ }
125
+ }
126
+
127
+ export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string): StructuredOutputRuntime {
128
+ assertJsonSchemaObject(schema);
129
+ const rootDir = baseDir ?? os.tmpdir();
130
+ fs.mkdirSync(rootDir, { recursive: true });
131
+ const dir = fs.mkdtempSync(path.join(rootDir, "pi-subagent-structured-"));
132
+ const schemaPath = path.join(dir, "schema.json");
133
+ const outputPath = path.join(dir, "output.json");
134
+ fs.writeFileSync(schemaPath, JSON.stringify(schema), { mode: 0o600 });
135
+ return { schema, schemaPath, outputPath };
136
+ }
137
+
138
+ export async function validateStructuredOutputValue(schema: JsonSchemaObject, value: unknown): Promise<{ status: "valid" } | { status: "invalid"; message: string }> {
139
+ const compile = await loadCompile();
140
+ let validator: CompiledJsonSchema;
141
+ try {
142
+ validator = compile(schema);
143
+ } catch (error) {
144
+ return { status: "invalid", message: `invalid outputSchema: ${error instanceof Error ? error.message : String(error)}` };
145
+ }
146
+ if (validator.Check(value)) return { status: "valid" };
147
+ const errors = [...validator.Errors(value)]
148
+ .slice(0, 8)
149
+ .map((error) => {
150
+ const pathText = error.instancePath ? error.instancePath.replace(/^\//, "").replace(/\//g, ".") : "root";
151
+ return `${pathText}: ${error.message}`;
152
+ });
153
+ return { status: "invalid", message: errors.join("; ") || "schema validation failed" };
154
+ }
155
+
156
+ export async function readStructuredOutput(runtime: StructuredOutputRuntime): Promise<{ value?: unknown; error?: string }> {
157
+ if (!fs.existsSync(runtime.outputPath)) {
158
+ return { error: MISSING_STRUCTURED_OUTPUT_CALL_ERROR };
159
+ }
160
+ let value: unknown;
161
+ try {
162
+ value = JSON.parse(fs.readFileSync(runtime.outputPath, "utf-8"));
163
+ } catch (error) {
164
+ return { error: `Failed to read structured output: ${error instanceof Error ? error.message : String(error)}` };
165
+ }
166
+ try {
167
+ const validation = await validateStructuredOutputValue(runtime.schema, value);
168
+ if (validation.status === "invalid") return { error: `Structured output validation failed: ${validation.message}` };
169
+ } catch (error) {
170
+ return { error: `Failed to validate structured output: ${error instanceof Error ? error.message : String(error)}` };
171
+ }
172
+ return { value };
173
+ }
174
+
175
+ export function cleanupStructuredOutputRuntime(runtime: StructuredOutputRuntime | undefined): void {
176
+ if (!runtime) return;
177
+ try {
178
+ fs.rmSync(path.dirname(runtime.schemaPath), { recursive: true, force: true });
179
+ } catch {
180
+ // Best-effort temp cleanup.
181
+ }
182
+ }
@@ -0,0 +1,231 @@
1
+ import {
2
+ type ActivityState,
3
+ type ControlConfig,
4
+ type ControlEvent,
5
+ type ControlEventType,
6
+ type ControlNotificationChannel,
7
+ type ResolvedControlConfig,
8
+ } from "../../shared/types.ts";
9
+
10
+ const CONTROL_EVENT_TYPES: ControlEventType[] = ["active_long_running", "needs_attention"];
11
+ const CONTROL_NOTIFICATION_CHANNELS: ControlNotificationChannel[] = ["event", "async", "intercom"];
12
+ const DEFAULT_NOTIFY_ON: ControlEventType[] = ["active_long_running", "needs_attention"];
13
+
14
+ export const DEFAULT_CONTROL_CONFIG: ResolvedControlConfig = {
15
+ enabled: true,
16
+ needsAttentionAfterMs: 60_000,
17
+ activeNoticeAfterMs: 240_000,
18
+ failedToolAttemptsBeforeAttention: 3,
19
+ notifyOn: DEFAULT_NOTIFY_ON,
20
+ notifyChannels: CONTROL_NOTIFICATION_CHANNELS,
21
+ };
22
+
23
+ function parsePositiveInt(value: unknown): number | undefined {
24
+ if (typeof value !== "number") return undefined;
25
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) return undefined;
26
+ return value;
27
+ }
28
+
29
+ function parseControlList<T extends string>(value: unknown, allowed: readonly T[]): T[] | undefined {
30
+ if (!Array.isArray(value)) return undefined;
31
+ if (value.length === 0) return [];
32
+ const allowedSet = new Set(allowed);
33
+ const parsed = value.filter((entry): entry is T => typeof entry === "string" && allowedSet.has(entry as T));
34
+ return parsed.length > 0 ? Array.from(new Set(parsed)) : undefined;
35
+ }
36
+
37
+ export function resolveControlConfig(
38
+ globalConfig?: ControlConfig,
39
+ override?: ControlConfig,
40
+ ): ResolvedControlConfig {
41
+ const enabled = override?.enabled ?? globalConfig?.enabled ?? DEFAULT_CONTROL_CONFIG.enabled;
42
+ const needsAttentionAfterMs = parsePositiveInt(override?.needsAttentionAfterMs)
43
+ ?? parsePositiveInt(globalConfig?.needsAttentionAfterMs)
44
+ ?? DEFAULT_CONTROL_CONFIG.needsAttentionAfterMs;
45
+ const activeNoticeAfterMs = parsePositiveInt(override?.activeNoticeAfterMs)
46
+ ?? parsePositiveInt(globalConfig?.activeNoticeAfterMs)
47
+ ?? DEFAULT_CONTROL_CONFIG.activeNoticeAfterMs;
48
+ const activeNoticeAfterTurns = parsePositiveInt(override?.activeNoticeAfterTurns)
49
+ ?? parsePositiveInt(globalConfig?.activeNoticeAfterTurns);
50
+ const activeNoticeAfterTokens = parsePositiveInt(override?.activeNoticeAfterTokens)
51
+ ?? parsePositiveInt(globalConfig?.activeNoticeAfterTokens);
52
+ const failedToolAttemptsBeforeAttention = parsePositiveInt(override?.failedToolAttemptsBeforeAttention)
53
+ ?? parsePositiveInt(globalConfig?.failedToolAttemptsBeforeAttention)
54
+ ?? DEFAULT_CONTROL_CONFIG.failedToolAttemptsBeforeAttention;
55
+ const notifyOn = parseControlList(override?.notifyOn, CONTROL_EVENT_TYPES)
56
+ ?? parseControlList(globalConfig?.notifyOn, CONTROL_EVENT_TYPES)
57
+ ?? DEFAULT_CONTROL_CONFIG.notifyOn;
58
+ const notifyChannels = parseControlList(override?.notifyChannels, CONTROL_NOTIFICATION_CHANNELS)
59
+ ?? parseControlList(globalConfig?.notifyChannels, CONTROL_NOTIFICATION_CHANNELS)
60
+ ?? DEFAULT_CONTROL_CONFIG.notifyChannels;
61
+ return {
62
+ enabled,
63
+ needsAttentionAfterMs,
64
+ activeNoticeAfterMs,
65
+ activeNoticeAfterTurns,
66
+ activeNoticeAfterTokens,
67
+ failedToolAttemptsBeforeAttention,
68
+ notifyOn: [...notifyOn],
69
+ notifyChannels: [...notifyChannels],
70
+ };
71
+ }
72
+
73
+ export function deriveActivityState(input: {
74
+ config: ResolvedControlConfig;
75
+ startedAt: number;
76
+ lastActivityAt?: number;
77
+ currentTool?: string;
78
+ now?: number;
79
+ }): ActivityState | undefined {
80
+ if (!input.config.enabled || input.currentTool) return undefined;
81
+ const now = input.now ?? Date.now();
82
+ const lastActivity = input.lastActivityAt ?? input.startedAt;
83
+ const ageMs = Math.max(0, now - lastActivity);
84
+ return ageMs > input.config.needsAttentionAfterMs ? "needs_attention" : undefined;
85
+ }
86
+
87
+ export function buildControlEvent(input: {
88
+ type?: ControlEventType;
89
+ from?: ActivityState;
90
+ to: ActivityState;
91
+ runId: string;
92
+ agent: string;
93
+ index?: number;
94
+ ts?: number;
95
+ lastActivityAt?: number;
96
+ message?: string;
97
+ reason?: ControlEvent["reason"];
98
+ turns?: number;
99
+ tokens?: number;
100
+ toolCount?: number;
101
+ currentTool?: string;
102
+ currentToolDurationMs?: number;
103
+ currentPath?: string;
104
+ elapsedMs?: number;
105
+ recentFailureSummary?: string;
106
+ }): ControlEvent {
107
+ const ts = input.ts ?? Date.now();
108
+ const type = input.type ?? (input.to === "active_long_running" ? "active_long_running" : "needs_attention");
109
+ const elapsedMs = input.elapsedMs ?? (input.lastActivityAt ? Math.max(0, ts - input.lastActivityAt) : undefined);
110
+ const elapsedSeconds = elapsedMs !== undefined ? Math.floor(elapsedMs / 1000) : undefined;
111
+ const message = input.message ?? (type === "active_long_running"
112
+ ? `${input.agent} is still active but long-running`
113
+ : elapsedSeconds !== undefined
114
+ ? `${input.agent} needs attention (no observed activity for ${elapsedSeconds}s)`
115
+ : `${input.agent} needs attention`);
116
+ return {
117
+ type,
118
+ ...(input.from ? { from: input.from } : {}),
119
+ to: input.to,
120
+ ts,
121
+ runId: input.runId,
122
+ agent: input.agent,
123
+ ...(input.index !== undefined ? { index: input.index } : {}),
124
+ message,
125
+ reason: input.reason ?? (type === "active_long_running" ? "active_long_running" : "idle"),
126
+ ...(input.turns !== undefined ? { turns: input.turns } : {}),
127
+ ...(input.tokens !== undefined ? { tokens: input.tokens } : {}),
128
+ ...(input.toolCount !== undefined ? { toolCount: input.toolCount } : {}),
129
+ ...(input.currentTool ? { currentTool: input.currentTool } : {}),
130
+ ...(input.currentToolDurationMs !== undefined ? { currentToolDurationMs: input.currentToolDurationMs } : {}),
131
+ ...(input.currentPath ? { currentPath: input.currentPath } : {}),
132
+ ...(elapsedMs !== undefined ? { elapsedMs } : {}),
133
+ ...(input.recentFailureSummary ? { recentFailureSummary: input.recentFailureSummary } : {}),
134
+ };
135
+ }
136
+
137
+ export function shouldNotifyControlEvent(config: ResolvedControlConfig, event: ControlEvent): boolean {
138
+ return config.enabled && config.notifyOn.includes(event.type);
139
+ }
140
+
141
+ export function controlNotificationKey(event: ControlEvent, childIntercomTarget?: string): string {
142
+ const childKey = childIntercomTarget ?? (event.index !== undefined ? `${event.runId}:${event.index}` : event.runId);
143
+ return `${childKey}:${event.type}:${event.reason ?? "idle"}`;
144
+ }
145
+
146
+ export function claimControlNotification(config: ResolvedControlConfig, event: ControlEvent, seenKeys: Set<string>, childIntercomTarget?: string): boolean {
147
+ if (!shouldNotifyControlEvent(config, event)) return false;
148
+ const key = controlNotificationKey(event, childIntercomTarget);
149
+ if (seenKeys.has(key)) return false;
150
+ seenKeys.add(key);
151
+ return true;
152
+ }
153
+
154
+ function formatLongRunningFacts(event: ControlEvent): string | undefined {
155
+ const facts: string[] = [];
156
+ if (event.elapsedMs !== undefined) facts.push(`elapsed ${Math.floor(Math.max(0, event.elapsedMs) / 1000)}s`);
157
+ if (event.turns !== undefined) facts.push(`${event.turns} turns`);
158
+ if (event.tokens !== undefined) facts.push(`${event.tokens} tokens`);
159
+ if (event.toolCount !== undefined) facts.push(`${event.toolCount} tools`);
160
+ if (event.currentTool) facts.push(`tool ${event.currentTool}${event.currentToolDurationMs !== undefined ? ` ${Math.floor(Math.max(0, event.currentToolDurationMs) / 1000)}s` : ""}`);
161
+ if (event.currentPath) facts.push(`path ${event.currentPath}`);
162
+ return facts.length > 0 ? facts.join(" | ") : undefined;
163
+ }
164
+
165
+ export function formatControlNoticeMessage(event: ControlEvent, childIntercomTarget?: string): string {
166
+ const runTarget = event.runId;
167
+ if (event.reason === "completion_guard") {
168
+ return [
169
+ `Subagent failed: ${event.agent}`,
170
+ `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
171
+ `Signal: ${event.message}`,
172
+ "Next: read the output artifact or session from the subagent result, then retry with a more explicit implementation prompt or handle the fix directly.",
173
+ childIntercomTarget ? `Run intercom target (may be inactive): ${childIntercomTarget}` : undefined,
174
+ ].filter((line): line is string => Boolean(line)).join("\n");
175
+ }
176
+
177
+ const nudgeMessage = "What are you blocked on? Reply with the smallest next step or ask for a decision.";
178
+ const steerCommand = `subagent({ action: "steer", id: "${runTarget}", ${event.index !== undefined ? `index: ${event.index}, ` : ""}message: "${nudgeMessage}" })`;
179
+ const nestedResumeCommand = `subagent({ action: "resume", id: "${runTarget}", message: "${nudgeMessage}" })`;
180
+ if (event.type === "active_long_running") {
181
+ const facts = formatLongRunningFacts(event);
182
+ return [
183
+ `Subagent active but long-running: ${event.agent}`,
184
+ `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
185
+ `Signal: ${event.message}`,
186
+ facts ? `Facts: ${facts}` : undefined,
187
+ "Hint: Inspect status first. Use steer for a top-level live async child, routed resume for a live nested child, or resume to revive a paused/completed/failed child.",
188
+ `Top-level live async nudge: ${steerCommand}`,
189
+ `Routed live nested nudge: ${nestedResumeCommand}`,
190
+ childIntercomTarget ? `Direct intercom target: ${childIntercomTarget}` : undefined,
191
+ `Status: subagent({ action: "status", id: "${runTarget}" })`,
192
+ `Interrupt: subagent({ action: "interrupt", id: "${runTarget}" })`,
193
+ ].filter((line): line is string => Boolean(line)).join("\n");
194
+ }
195
+
196
+ const supervisorHint = event.reason === "supervisor_request"
197
+ ? "Supervisor request: reply to the pending request. If subagent_supervisor pending is empty, check intercom pending because an external intercom tool may own the request."
198
+ : undefined;
199
+ return [
200
+ `Subagent needs attention: ${event.agent}`,
201
+ `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
202
+ `Signal: ${event.message}`,
203
+ event.recentFailureSummary ? `Recent failures: ${event.recentFailureSummary}` : undefined,
204
+ supervisorHint,
205
+ "Hint: Inspect status first unless the run is clearly blocked. Use steer for a top-level live async child, routed resume for a live nested child, or resume to revive a paused/completed/failed child.",
206
+ `Top-level live async nudge: ${steerCommand}`,
207
+ `Routed live nested nudge: ${nestedResumeCommand}`,
208
+ childIntercomTarget ? `Direct intercom target: ${childIntercomTarget}` : undefined,
209
+ `Status: subagent({ action: "status", id: "${runTarget}" })`,
210
+ `Interrupt: subagent({ action: "interrupt", id: "${runTarget}" })`,
211
+ ].filter((line): line is string => Boolean(line)).join("\n");
212
+ }
213
+
214
+ export function formatControlIntercomMessage(event: ControlEvent, childIntercomTarget?: string): string {
215
+ const statusLabel = event.reason === "completion_guard"
216
+ ? "subagent failed"
217
+ : event.type === "active_long_running"
218
+ ? "subagent active but long-running"
219
+ : "subagent needs attention";
220
+ return [
221
+ statusLabel,
222
+ "",
223
+ event.reason === "completion_guard"
224
+ ? `${event.agent} failed in run ${event.runId}.`
225
+ : event.type === "active_long_running"
226
+ ? `${event.agent} is still active but long-running in run ${event.runId}.`
227
+ : `${event.agent} needs attention in run ${event.runId}.`,
228
+ "",
229
+ formatControlNoticeMessage(event, childIntercomTarget),
230
+ ].join("\n");
231
+ }