@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,410 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
+ import type { Details } from "../shared/types.ts";
5
+ import {
6
+ MISSION_STATUSES,
7
+ type MissionArtifact,
8
+ type MissionArtifactKind,
9
+ type MissionReceipt,
10
+ type MissionReceiptKind,
11
+ type MissionReceiptStatus,
12
+ type MissionRecord,
13
+ type MissionRunMode,
14
+ type MissionStatus,
15
+ type MissionStoreConfig,
16
+ type MissionStoreLocation,
17
+ type MissionTokenBudget,
18
+ type MissionUpdateInput,
19
+ } from "./types.ts";
20
+ import { missionStatePath } from "./workflow-state.ts";
21
+ import {
22
+ createMission,
23
+ listGlobalMissions,
24
+ listMissions,
25
+ missionRecordPath,
26
+ readMission,
27
+ resolveMissionStoreLocation,
28
+ updateMission,
29
+ validateMissionId,
30
+ } from "./store.ts";
31
+
32
+ export const MISSION_ACTIONS = [
33
+ "mission.create",
34
+ "mission.list",
35
+ "mission.show",
36
+ "mission.update",
37
+ "mission.attach-run",
38
+ "mission.close",
39
+ ] as const;
40
+
41
+ export type MissionAction = typeof MISSION_ACTIONS[number];
42
+
43
+ export interface MissionLaunchInput {
44
+ title: string;
45
+ objective?: string;
46
+ goal?: true;
47
+ budget?: MissionTokenBudget;
48
+ labels?: string[];
49
+ }
50
+
51
+ export interface MissionUpdateToolInput {
52
+ title?: string;
53
+ objective?: string;
54
+ goal?: boolean | { paused: boolean };
55
+ budget?: MissionTokenBudget;
56
+ status?: MissionStatus;
57
+ summary?: string;
58
+ labels?: string[];
59
+ artifacts?: MissionArtifact[];
60
+ receipts?: Array<Omit<MissionReceipt, "createdAt">>;
61
+ decisions?: Array<{
62
+ title: string;
63
+ prompt?: string;
64
+ options?: string[];
65
+ recommendation?: string;
66
+ }>;
67
+ }
68
+
69
+ export interface MissionActionParams {
70
+ missionId?: string;
71
+ mission?: unknown;
72
+ missionUpdate?: unknown;
73
+ missionStatus?: string;
74
+ missionScope?: string;
75
+ id?: string;
76
+ runId?: string;
77
+ dir?: string;
78
+ runMode?: string;
79
+ runStatus?: string;
80
+ agent?: string;
81
+ summary?: string;
82
+ }
83
+
84
+ interface MissionActionContext {
85
+ cwd: string;
86
+ currentSessionId?: string;
87
+ config?: MissionStoreConfig;
88
+ agentDir?: string;
89
+ }
90
+
91
+ function textResult(text: string, details: Details): AgentToolResult<Details> {
92
+ return { content: [{ type: "text", text }], details };
93
+ }
94
+
95
+ function requireMissionId(params: MissionActionParams): string {
96
+ return validateMissionId(params.missionId, "missionId");
97
+ }
98
+
99
+ function validateStatus(value: unknown, label: string): MissionStatus {
100
+ if (typeof value !== "string" || !(MISSION_STATUSES as readonly string[]).includes(value)) {
101
+ throw new Error(`${label} must be one of ${MISSION_STATUSES.join(", ")}`);
102
+ }
103
+ return value as MissionStatus;
104
+ }
105
+
106
+ export function validateMissionLaunch(value: unknown): MissionLaunchInput {
107
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("mission must be an object");
108
+ const input = value as Record<string, unknown>;
109
+ for (const key of Object.keys(input)) {
110
+ if (key !== "title" && key !== "summary" && key !== "objective" && key !== "goal" && key !== "budget" && key !== "labels") throw new Error(`mission.${key} is unknown`);
111
+ }
112
+ if (input.title !== undefined && input.summary !== undefined) throw new Error("mission.title and mission.summary cannot both be set");
113
+ const title = input.title ?? input.summary;
114
+ if (typeof title !== "string" || !title.trim()) throw new Error("mission.title or mission.summary must be a non-empty string");
115
+ if (input.objective !== undefined && (typeof input.objective !== "string" || !input.objective.trim())) throw new Error("mission.objective must be a non-empty string");
116
+ if (input.goal !== undefined && input.goal !== true) throw new Error("mission.goal must be true when supplied");
117
+ const budget = input.budget;
118
+ if (budget !== undefined && (!budget || typeof budget !== "object" || Array.isArray(budget) || !Number.isSafeInteger((budget as { tokens?: unknown }).tokens) || ((budget as { tokens: number }).tokens < 1))) {
119
+ throw new Error("mission.budget.tokens must be a positive integer");
120
+ }
121
+ if (input.goal === true && budget === undefined) throw new Error("mission.budget is required when mission.goal is true");
122
+ if (input.labels !== undefined && (!Array.isArray(input.labels) || input.labels.some((label) => typeof label !== "string" || !label.trim()))) {
123
+ throw new Error("mission.labels must contain only non-empty strings");
124
+ }
125
+ return {
126
+ title: title.trim(),
127
+ ...(typeof input.objective === "string" ? { objective: input.objective.trim() } : {}),
128
+ ...(input.goal === true ? { goal: true as const } : {}),
129
+ ...(budget !== undefined ? { budget: { tokens: (budget as { tokens: number }).tokens } } : {}),
130
+ ...(input.labels !== undefined ? { labels: input.labels.map((label) => label.trim()) } : {}),
131
+ };
132
+ }
133
+
134
+ function validateArtifact(value: unknown, index: number): MissionArtifact {
135
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`missionUpdate.artifacts[${index}] must be an object`);
136
+ const input = value as Record<string, unknown>;
137
+ const kinds: MissionArtifactKind[] = ["status", "output", "patch", "manifest", "review", "note", "other"];
138
+ if (typeof input.kind !== "string" || !kinds.includes(input.kind as MissionArtifactKind)) throw new Error(`missionUpdate.artifacts[${index}].kind is invalid`);
139
+ if (typeof input.path !== "string" || !input.path.trim()) throw new Error(`missionUpdate.artifacts[${index}].path must be a non-empty string`);
140
+ if (input.description !== undefined && (typeof input.description !== "string" || !input.description.trim())) throw new Error(`missionUpdate.artifacts[${index}].description must be a non-empty string`);
141
+ return {
142
+ kind: input.kind as MissionArtifactKind,
143
+ path: input.path,
144
+ ...(typeof input.description === "string" ? { description: input.description } : {}),
145
+ };
146
+ }
147
+
148
+ function validateReceipt(value: unknown, index: number): Omit<MissionReceipt, "createdAt"> {
149
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`missionUpdate.receipts[${index}] must be an object`);
150
+ const input = value as Record<string, unknown>;
151
+ for (const key of Object.keys(input)) {
152
+ if (!['kind', 'status', 'title', 'url', 'description'].includes(key)) throw new Error(`missionUpdate.receipts[${index}].${key} is unknown`);
153
+ }
154
+ const kinds: MissionReceiptKind[] = ["pull_request", "ci", "deployment", "release"];
155
+ const statuses: MissionReceiptStatus[] = ["pending", "ready", "succeeded", "failed"];
156
+ if (typeof input.kind !== "string" || !kinds.includes(input.kind as MissionReceiptKind)) throw new Error(`missionUpdate.receipts[${index}].kind is invalid`);
157
+ if (typeof input.status !== "string" || !statuses.includes(input.status as MissionReceiptStatus)) throw new Error(`missionUpdate.receipts[${index}].status is invalid`);
158
+ for (const field of ["title", "url"] as const) {
159
+ if (typeof input[field] !== "string" || !input[field].trim()) throw new Error(`missionUpdate.receipts[${index}].${field} must be a non-empty string`);
160
+ }
161
+ try {
162
+ new URL(input.url as string);
163
+ } catch {
164
+ throw new Error(`missionUpdate.receipts[${index}].url must be an absolute URL`);
165
+ }
166
+ if (input.description !== undefined && (typeof input.description !== "string" || !input.description.trim())) throw new Error(`missionUpdate.receipts[${index}].description must be a non-empty string`);
167
+ return {
168
+ kind: input.kind as MissionReceiptKind,
169
+ status: input.status as MissionReceiptStatus,
170
+ title: (input.title as string).trim(),
171
+ url: (input.url as string).trim(),
172
+ ...(typeof input.description === "string" ? { description: input.description.trim() } : {}),
173
+ };
174
+ }
175
+
176
+ function validateMissionUpdate(value: unknown): MissionUpdateInput {
177
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("missionUpdate must be an object");
178
+ const input = value as Record<string, unknown>;
179
+ for (const key of Object.keys(input)) {
180
+ if (!["title", "objective", "goal", "budget", "status", "summary", "labels", "artifacts", "receipts", "decisions"].includes(key)) throw new Error(`missionUpdate.${key} is unknown`);
181
+ }
182
+ const update: MissionUpdateInput = {};
183
+ for (const field of ["title", "objective", "summary"] as const) {
184
+ const candidate = input[field];
185
+ if (candidate === undefined) continue;
186
+ if (typeof candidate !== "string" || !candidate.trim()) throw new Error(`missionUpdate.${field} must be a non-empty string`);
187
+ update[field] = candidate.trim();
188
+ }
189
+ if (input.goal !== undefined) {
190
+ if (typeof input.goal === "boolean") update.goal = input.goal ? { status: "active" } : false;
191
+ else {
192
+ if (!input.goal || typeof input.goal !== "object" || Array.isArray(input.goal) || typeof (input.goal as { paused?: unknown }).paused !== "boolean" || Object.keys(input.goal).some((key) => key !== "paused")) {
193
+ throw new Error("missionUpdate.goal must be boolean or { paused: boolean }");
194
+ }
195
+ update.goal = { status: (input.goal as { paused: boolean }).paused ? "paused" : "active" };
196
+ }
197
+ }
198
+ if (input.budget !== undefined) {
199
+ if (!input.budget || typeof input.budget !== "object" || Array.isArray(input.budget) || !Number.isSafeInteger((input.budget as { tokens?: unknown }).tokens) || (input.budget as { tokens: number }).tokens < 1) {
200
+ throw new Error("missionUpdate.budget.tokens must be a positive integer");
201
+ }
202
+ update.budget = { tokens: (input.budget as { tokens: number }).tokens };
203
+ }
204
+ if (input.status !== undefined) update.status = validateStatus(input.status, "missionUpdate.status");
205
+ if (input.labels !== undefined) {
206
+ if (!Array.isArray(input.labels) || input.labels.some((label) => typeof label !== "string" || !label.trim())) throw new Error("missionUpdate.labels must contain only non-empty strings");
207
+ update.labels = input.labels as string[];
208
+ }
209
+ if (input.artifacts !== undefined) {
210
+ if (!Array.isArray(input.artifacts)) throw new Error("missionUpdate.artifacts must be an array");
211
+ update.addArtifacts = input.artifacts.map(validateArtifact);
212
+ }
213
+ if (input.receipts !== undefined) {
214
+ if (!Array.isArray(input.receipts)) throw new Error("missionUpdate.receipts must be an array");
215
+ update.addReceipts = input.receipts.map(validateReceipt);
216
+ }
217
+ if (input.decisions !== undefined) {
218
+ if (!Array.isArray(input.decisions)) throw new Error("missionUpdate.decisions must be an array");
219
+ update.addDecisions = input.decisions.map((value, index) => {
220
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`missionUpdate.decisions[${index}] must be an object`);
221
+ const decision = value as Record<string, unknown>;
222
+ if (typeof decision.title !== "string" || !decision.title.trim()) throw new Error(`missionUpdate.decisions[${index}].title must be a non-empty string`);
223
+ if (decision.options !== undefined && (!Array.isArray(decision.options) || decision.options.some((option) => typeof option !== "string" || !option.trim()))) throw new Error(`missionUpdate.decisions[${index}].options must contain only non-empty strings`);
224
+ return {
225
+ title: decision.title.trim(),
226
+ ...(typeof decision.prompt === "string" && decision.prompt.trim() ? { prompt: decision.prompt } : {}),
227
+ ...(Array.isArray(decision.options) ? { options: decision.options as string[] } : {}),
228
+ ...(typeof decision.recommendation === "string" && decision.recommendation.trim() ? { recommendation: decision.recommendation } : {}),
229
+ };
230
+ });
231
+ }
232
+ if (Object.keys(update).length === 0) throw new Error("missionUpdate must include at least one supported field");
233
+ return update;
234
+ }
235
+
236
+ function refreshLinkedRunStatus(location: MissionStoreLocation, record: MissionRecord): { record: MissionRecord; warnings: string[] } {
237
+ const warnings: string[] = [];
238
+ const updates = record.runs.flatMap((run) => {
239
+ if (!run.asyncDir) return [];
240
+ const statusPath = path.join(run.asyncDir, "status.json");
241
+ if (!fs.existsSync(statusPath)) return [];
242
+ let status: unknown;
243
+ try {
244
+ status = JSON.parse(fs.readFileSync(statusPath, "utf-8"));
245
+ } catch (error) {
246
+ warnings.push(`Failed to read linked run status '${statusPath}': ${error instanceof Error ? error.message : String(error)}`);
247
+ return [];
248
+ }
249
+ if (!status || typeof status !== "object" || Array.isArray(status)) {
250
+ warnings.push(`Linked run status '${statusPath}' must be an object`);
251
+ return [];
252
+ }
253
+ const state = (status as { state?: unknown }).state;
254
+ if (typeof state !== "string" || !state.trim()) {
255
+ warnings.push(`Linked run status '${statusPath}' is missing state`);
256
+ return [];
257
+ }
258
+ if (state === run.status) return [];
259
+ return [{
260
+ ...run,
261
+ status: state,
262
+ ...(!["queued", "running"].includes(state) && !run.completedAt ? { completedAt: new Date().toISOString() } : {}),
263
+ }];
264
+ });
265
+ if (updates.length === 0) return { record, warnings };
266
+ const merged = record.runs.map((run) => updates.find((update) => update.runId === run.runId && update.childIndex === run.childIndex) ?? run);
267
+ const states = merged.map((run) => run.status);
268
+ const status: MissionStatus = record.status === "completed" || record.status === "failed" || record.status === "cancelled"
269
+ ? record.status
270
+ : record.goal && !states.some((state) => state === "queued" || state === "running" || state === "active")
271
+ ? "active"
272
+ : states.some((state) => state === "queued" || state === "running" || state === "active")
273
+ ? "active"
274
+ : states.some((state) => state === "paused")
275
+ ? "waiting"
276
+ : states.some((state) => state === "failed")
277
+ ? "failed"
278
+ : states.some((state) => state === "stopped" || state === "rejected" || state === "cancelled")
279
+ ? "cancelled"
280
+ : states.length > 0 && states.every((state) => state === "complete" || state === "completed")
281
+ ? "completed"
282
+ : record.status;
283
+ return { record: updateMission(location, record.id, { status, addRuns: updates }), warnings };
284
+ }
285
+
286
+ function formatMission(record: MissionRecord): string {
287
+ const lines = [
288
+ `Mission: ${record.id}`,
289
+ `Title: ${record.title}`,
290
+ `Status: ${record.status}`,
291
+ `Objective: ${record.objective}`,
292
+ `Updated: ${record.updatedAt}`,
293
+ ];
294
+ if (record.goal && record.budget) lines.push(`Goal mode: ${record.goal.status}`, `Budget: ${record.usage?.tokens ?? 0}/${record.budget.tokens} tokens`);
295
+ if (record.summary) lines.push(`Summary: ${record.summary}`);
296
+ if (record.labels?.length) lines.push(`Labels: ${record.labels.join(", ")}`);
297
+ if (record.runs.length) {
298
+ lines.push("Runs:");
299
+ for (const run of record.runs) lines.push(` ${run.runId} (${run.mode}${run.status ? `, ${run.status}` : ""})${run.asyncDir ? ` — ${run.asyncDir}` : ""}`);
300
+ }
301
+ if (record.decisions.length) {
302
+ lines.push("Decisions:");
303
+ for (const decision of record.decisions) lines.push(` ${decision.id}: ${decision.status} — ${decision.title}`);
304
+ }
305
+ if (record.artifacts.length) {
306
+ lines.push("Artifacts:");
307
+ for (const artifact of record.artifacts) lines.push(` ${artifact.kind}: ${artifact.path}`);
308
+ }
309
+ if (record.receipts.length) {
310
+ lines.push("Delivery receipts:");
311
+ for (const receipt of record.receipts) lines.push(` ${receipt.kind} (${receipt.status}): ${receipt.title} — ${receipt.url}`);
312
+ }
313
+ return lines.join("\n");
314
+ }
315
+
316
+ export function handleMissionAction(
317
+ action: MissionAction,
318
+ params: MissionActionParams,
319
+ ctx: MissionActionContext,
320
+ ): AgentToolResult<Details> {
321
+ const location = resolveMissionStoreLocation({
322
+ projectRoot: ctx.cwd,
323
+ ...(ctx.config ? { config: ctx.config } : {}),
324
+ ...(ctx.agentDir ? { agentDir: ctx.agentDir } : {}),
325
+ });
326
+ if (action === "mission.create") {
327
+ const mission = validateMissionLaunch(params.mission);
328
+ const record = createMission(location, {
329
+ title: mission.title,
330
+ objective: mission.objective ?? mission.title,
331
+ ...(mission.goal === true ? { goal: true as const } : {}),
332
+ ...(mission.budget ? { budget: mission.budget } : {}),
333
+ status: params.missionStatus ? validateStatus(params.missionStatus, "missionStatus") : "planned",
334
+ ...(mission.labels ? { labels: mission.labels } : {}),
335
+ ...(ctx.currentSessionId ? { ownerSessionId: ctx.currentSessionId } : {}),
336
+ }, new Date(), ctx.config?.retainTerminal);
337
+ return textResult(`Created mission ${record.id}: ${record.title}`, { mode: "management", results: [], missionId: record.id, missionPath: pathFor(record.id), mission: record });
338
+ }
339
+ if (action === "mission.list") {
340
+ if (params.missionScope !== undefined && params.missionScope !== "project" && params.missionScope !== "global") {
341
+ throw new Error("missionScope must be \"project\" or \"global\"");
342
+ }
343
+ if (params.missionScope === "global") {
344
+ const listed = listGlobalMissions(location.globalIndexDir);
345
+ const lines = listed.entries.length === 0
346
+ ? ["No indexed missions."]
347
+ : listed.entries.map((entry) => `${entry.missionId} ${entry.status}${entry.stale ? " [stale]" : ""} ${entry.title} ${entry.projectRoot}`);
348
+ if (listed.warnings.length) lines.push("", ...listed.warnings.map((warning) => `Warning: ${warning}`));
349
+ return textResult(lines.join("\n"), { mode: "management", results: [], missions: { globalEntries: listed.entries, warnings: listed.warnings } });
350
+ }
351
+ const listed = listMissions(location);
352
+ const lines = listed.records.length === 0
353
+ ? ["No project missions."]
354
+ : listed.records.map((record) => `${record.id} ${record.status} ${record.title} ${record.updatedAt}`);
355
+ if (listed.warnings.length) lines.push("", ...listed.warnings.map((warning) => `Warning: ${warning}`));
356
+ return textResult(lines.join("\n"), { mode: "management", results: [], missions: { records: listed.records, warnings: listed.warnings } });
357
+ }
358
+ if (action === "mission.show") {
359
+ const refreshed = refreshLinkedRunStatus(location, readMission(location, requireMissionId(params)));
360
+ const lines = [formatMission(refreshed.record), `State: ${missionStatePath(location, refreshed.record.id)}`];
361
+ if (refreshed.warnings.length) lines.push("", ...refreshed.warnings.map((warning) => `Warning: ${warning}`));
362
+ return textResult(lines.join("\n"), {
363
+ mode: "management",
364
+ results: [],
365
+ missionId: refreshed.record.id,
366
+ missionPath: pathFor(refreshed.record.id),
367
+ mission: refreshed.record,
368
+ missions: { warnings: refreshed.warnings },
369
+ });
370
+ }
371
+ if (action === "mission.update") {
372
+ const record = updateMission(location, requireMissionId(params), validateMissionUpdate(params.missionUpdate));
373
+ return textResult(`Updated mission ${record.id}.\n\n${formatMission(record)}`, { mode: "management", results: [], missionId: record.id, missionPath: pathFor(record.id), mission: record });
374
+ }
375
+ if (action === "mission.attach-run") {
376
+ const missionId = requireMissionId(params);
377
+ const runId = params.runId ?? params.id;
378
+ if (typeof runId !== "string" || !runId.trim()) throw new Error("mission.attach-run requires runId or id");
379
+ const rawMode = params.runMode ?? "external";
380
+ if (!["single", "parallel", "chain", "workflow", "scheduled", "external"].includes(rawMode)) throw new Error("runMode is invalid");
381
+ const mode = rawMode as MissionRunMode;
382
+ if (params.dir !== undefined && !params.dir.trim()) throw new Error("dir must be a non-empty string");
383
+ if (params.runStatus !== undefined && !params.runStatus.trim()) throw new Error("runStatus must be a non-empty string");
384
+ const record = updateMission(location, missionId, {
385
+ status: "active",
386
+ addRuns: [{
387
+ runId: runId.trim(),
388
+ mode,
389
+ ...(params.dir ? { asyncDir: params.dir } : {}),
390
+ ...(params.agent ? { agent: params.agent } : {}),
391
+ ...(params.runStatus ? { status: params.runStatus } : {}),
392
+ startedAt: new Date().toISOString(),
393
+ }],
394
+ });
395
+ return textResult(`Attached run ${runId} to mission ${record.id}.`, { mode: "management", results: [], missionId: record.id, missionPath: pathFor(record.id), mission: record });
396
+ }
397
+ const missionId = requireMissionId(params);
398
+ const status = params.missionStatus ?? "completed";
399
+ if (status !== "completed" && status !== "failed" && status !== "cancelled") throw new Error("mission.close missionStatus must be completed, failed, or cancelled");
400
+ if (params.summary !== undefined && !params.summary.trim()) throw new Error("summary must be a non-empty string");
401
+ const record = updateMission(location, missionId, {
402
+ status,
403
+ ...(params.summary !== undefined ? { summary: params.summary.trim() } : {}),
404
+ });
405
+ return textResult(`Closed mission ${record.id} as ${record.status}.`, { mode: "management", results: [], missionId: record.id, missionPath: pathFor(record.id), mission: record });
406
+
407
+ function pathFor(missionId: string): string {
408
+ return missionRecordPath(location, missionId);
409
+ }
410
+ }
@@ -0,0 +1,162 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { RetainedChild } from "../runs/background/retained-children.ts";
4
+ import type { ControlEvent } from "../shared/types.ts";
5
+ import { listMissions, readMission, updateMission } from "./store.ts";
6
+ import type { MissionRecord, MissionRunLink, MissionStoreLocation } from "./types.ts";
7
+ import { missionStatePath } from "./workflow-state.ts";
8
+
9
+ const TERMINAL_MISSION_STATUSES = new Set(["completed", "failed", "cancelled"]);
10
+ const ACTIVE_RUN_STATUSES = new Set(["queued", "running", "active"]);
11
+ const MAX_ACTION_LENGTH = 180;
12
+
13
+ export interface GoalContinuationNotice {
14
+ missionId: string;
15
+ message: string;
16
+ event: ControlEvent;
17
+ }
18
+
19
+ function bounded(value: string): string {
20
+ const normalized = value.replace(/\s+/g, " ").trim();
21
+ return normalized.length > MAX_ACTION_LENGTH ? `${normalized.slice(0, MAX_ACTION_LENGTH - 1)}…` : normalized;
22
+ }
23
+
24
+ function tokenUsage(value: unknown): number | undefined {
25
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
26
+ const total = (value as { total?: unknown }).total;
27
+ return Number.isSafeInteger(total) && (total as number) >= 0 ? total as number : undefined;
28
+ }
29
+
30
+ function readLinkedRun(run: MissionRunLink): MissionRunLink {
31
+ if (!run.asyncDir) return run;
32
+ const statusPath = path.join(run.asyncDir, "status.json");
33
+ if (!fs.existsSync(statusPath)) return run;
34
+ const status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as Record<string, unknown>;
35
+ if (typeof status.state !== "string" || !status.state.trim()) throw new Error(`Linked run status '${statusPath}' is missing state`);
36
+ const tokens = tokenUsage(status.totalTokens)
37
+ ?? (Array.isArray(status.steps)
38
+ ? status.steps.reduce((total, step) => {
39
+ if (!step || typeof step !== "object") return total;
40
+ return total + (tokenUsage((step as { tokens?: unknown }).tokens) ?? 0);
41
+ }, 0)
42
+ : undefined);
43
+ return {
44
+ ...run,
45
+ status: status.state,
46
+ ...(!ACTIVE_RUN_STATUSES.has(status.state) && !run.completedAt ? { completedAt: new Date().toISOString() } : {}),
47
+ ...(tokens !== undefined ? { usage: { tokens } } : {}),
48
+ };
49
+ }
50
+
51
+ function refreshGoalMission(location: MissionStoreLocation, record: MissionRecord): MissionRecord {
52
+ const runs = record.runs.map(readLinkedRun);
53
+ const changed = runs.some((run, index) => JSON.stringify(run) !== JSON.stringify(record.runs[index]));
54
+ if (!changed) return record;
55
+ const active = runs.some((run) => run.status && ACTIVE_RUN_STATUSES.has(run.status));
56
+ return updateMission(location, record.id, {
57
+ status: active ? "active" : record.goal ? "active" : record.status,
58
+ addRuns: runs,
59
+ });
60
+ }
61
+
62
+ function readyActionFromValue(value: unknown, pathLabel = "state", depth = 0): string | undefined {
63
+ if (depth > 8 || !value || typeof value !== "object") return undefined;
64
+ if (Array.isArray(value)) {
65
+ for (let index = 0; index < value.length; index += 1) {
66
+ const found = readyActionFromValue(value[index], `${pathLabel}[${index}]`, depth + 1);
67
+ if (found) return found;
68
+ }
69
+ return undefined;
70
+ }
71
+ const input = value as Record<string, unknown>;
72
+ for (const key of ["nextReadyAction", "nextAction"] as const) {
73
+ if (typeof input[key] === "string" && input[key].trim()) return bounded(input[key]);
74
+ }
75
+ if (input.status === "ready") {
76
+ for (const key of ["action", "task", "title", "summary"] as const) {
77
+ if (typeof input[key] === "string" && input[key].trim()) return bounded(input[key]);
78
+ }
79
+ return `Continue ready mission state at ${pathLabel}`;
80
+ }
81
+ for (const [key, child] of Object.entries(input)) {
82
+ const found = readyActionFromValue(child, `${pathLabel}.${key}`, depth + 1);
83
+ if (found) return found;
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ function missionStateAction(location: MissionStoreLocation, record: MissionRecord): string | undefined {
89
+ const statePath = missionStatePath(location, record.id);
90
+ if (fs.existsSync(statePath)) {
91
+ const action = readyActionFromValue(JSON.parse(fs.readFileSync(statePath, "utf-8")));
92
+ if (action) return action;
93
+ }
94
+ const decision = record.decisions.find((item) => item.status === "open");
95
+ if (decision) return bounded(decision.recommendation ?? `Resolve decision: ${decision.title}`);
96
+ return undefined;
97
+ }
98
+
99
+ function retainedResumeTarget(record: MissionRecord, retainedChildren: RetainedChild[]): RetainedChild | undefined {
100
+ const latestRun = record.runs.at(-1);
101
+ if (!latestRun) return undefined;
102
+ return retainedChildren.find((child) => child.runId === latestRun.runId || child.parentRunId === latestRun.runId);
103
+ }
104
+
105
+ function nextReadyAction(location: MissionStoreLocation, record: MissionRecord, retainedChildren: RetainedChild[]): string {
106
+ const stateAction = missionStateAction(location, record);
107
+ const latestRun = record.runs.at(-1);
108
+ const action = stateAction
109
+ ?? (latestRun?.status === "failed" || latestRun?.status === "paused"
110
+ ? `Inspect linked run ${latestRun.runId} and continue the mission`
111
+ : `Continue objective: ${record.objective}`);
112
+ const retained = retainedResumeTarget(record, retainedChildren);
113
+ return retained
114
+ ? `Resume retained child ${retained.runId} (${retained.agent}) for: ${bounded(action)}`
115
+ : bounded(action);
116
+ }
117
+
118
+ export function collectGoalContinuationNotices(input: {
119
+ location: MissionStoreLocation;
120
+ ownerSessionId: string;
121
+ retainedChildren: RetainedChild[];
122
+ turnId: number;
123
+ now?: number;
124
+ }): GoalContinuationNotice[] {
125
+ const notices: GoalContinuationNotice[] = [];
126
+ const seen = new Set<string>();
127
+ for (const listed of listMissions(input.location).records) {
128
+ if (listed.ownerSessionId !== input.ownerSessionId || !listed.goal || TERMINAL_MISSION_STATUSES.has(listed.status)) continue;
129
+ let record = refreshGoalMission(input.location, readMission(input.location, listed.id));
130
+ if (!record.goal || record.goal.status !== "active" || !record.budget) continue;
131
+ if ((record.usage?.tokens ?? 0) >= record.budget.tokens) {
132
+ record = updateMission(input.location, record.id, { usage: record.usage ?? { tokens: 0 } });
133
+ if (record.goal?.status === "budget-exhausted") continue;
134
+ }
135
+ if (record.runs.some((run) => run.status && ACTIVE_RUN_STATUSES.has(run.status))) continue;
136
+ if (seen.has(record.id) || !record.budget) continue;
137
+ seen.add(record.id);
138
+ const budget = record.budget.tokens;
139
+ const used = record.usage?.tokens ?? 0;
140
+ const remaining = Math.max(0, budget - used);
141
+ const message = [
142
+ `Goal mission needs attention: ${bounded(record.title)}`,
143
+ `Mission: ${record.id}`,
144
+ `Remaining budget: ${remaining} tokens (${used}/${budget} used)`,
145
+ `Next ready action: ${nextReadyAction(input.location, record, input.retainedChildren)}`,
146
+ ].join("\n");
147
+ notices.push({
148
+ missionId: record.id,
149
+ message,
150
+ event: {
151
+ type: "needs_attention",
152
+ to: "needs_attention",
153
+ ts: input.now ?? Date.now(),
154
+ runId: `goal-${record.id}-turn-${input.turnId}`,
155
+ agent: "goal mission",
156
+ message,
157
+ reason: "idle",
158
+ },
159
+ });
160
+ }
161
+ return notices;
162
+ }