@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,401 @@
1
+ import { Buffer } from "node:buffer";
2
+ import type { ProtocolOutputLimit } from "../../shared/types.ts";
3
+
4
+ export type { ProtocolOutputLimit } from "../../shared/types.ts";
5
+
6
+ export const MAX_CHILD_PENDING_LINE_BYTES = 16 * 1024 * 1024;
7
+ export const MAX_CHILD_STDERR_BYTES = 128 * 1024;
8
+ const MAX_PROTOCOL_DIAGNOSTIC_BYTES = 4096;
9
+ const MAX_PROJECTED_JSON_DEPTH = 256;
10
+
11
+ export interface OversizedLineProjection {
12
+ push(chunk: Buffer): boolean;
13
+ finish(): string | undefined;
14
+ }
15
+
16
+ export interface OversizedLineProjector {
17
+ accepts(prefix: string): boolean;
18
+ create(): OversizedLineProjection;
19
+ }
20
+
21
+ type JsonContainer =
22
+ | { type: "array"; state: "value-or-end" | "value" | "comma-or-end" }
23
+ | { type: "object"; state: "key-or-end" | "key" | "colon" | "value" | "comma-or-end"; key?: string };
24
+
25
+ type JsonToken =
26
+ | { type: "string"; role: "key" | "value"; value: string; capture: boolean; escape: boolean; unicodeDigits: number; unicodeValue: string }
27
+ | { type: "literal"; expected: string; index: number; value: boolean | null }
28
+ | { type: "number"; phase: "minus" | "zero" | "int" | "dot" | "frac" | "exp" | "exp-sign" | "exp-digits" };
29
+
30
+ function createPiAggregateProjection(): OversizedLineProjection {
31
+ const decoder = new TextDecoder("utf-8", { fatal: true });
32
+ const stack: JsonContainer[] = [];
33
+ let rootState: "value" | "end" = "value";
34
+ let token: JsonToken | undefined;
35
+ let valid = true;
36
+ let eventType: string | undefined;
37
+ let willRetry: boolean | undefined;
38
+
39
+ const parent = (): JsonContainer | undefined => stack.at(-1);
40
+ const isTopLevelField = (key: string | undefined): boolean => stack.length === 1 && parent()?.type === "object" && (key === "type" || key === "willRetry");
41
+
42
+ const completeValue = (value?: string | boolean | null): void => {
43
+ const container = parent();
44
+ if (!container) {
45
+ rootState = "end";
46
+ return;
47
+ }
48
+ if (container.type === "object") {
49
+ if (stack.length === 1 && container.key === "type" && typeof value === "string") eventType = value;
50
+ if (stack.length === 1 && container.key === "willRetry" && typeof value === "boolean") willRetry = value;
51
+ container.key = undefined;
52
+ container.state = "comma-or-end";
53
+ } else container.state = "comma-or-end";
54
+ };
55
+
56
+ const startValue = (char: string): boolean => {
57
+ const container = parent();
58
+ const key = container?.type === "object" ? container.key : undefined;
59
+ if (isTopLevelField(key)) {
60
+ if (key === "type") eventType = undefined;
61
+ else willRetry = undefined;
62
+ }
63
+ if (char === "{" || char === "[") {
64
+ if (stack.length >= MAX_PROJECTED_JSON_DEPTH) return false;
65
+ stack.push(char === "{" ? { type: "object", state: "key-or-end" } : { type: "array", state: "value-or-end" });
66
+ return true;
67
+ }
68
+ if (char === '"') {
69
+ token = { type: "string", role: "value", value: "", capture: key === "type" && stack.length === 1, escape: false, unicodeDigits: 0, unicodeValue: "" };
70
+ return true;
71
+ }
72
+ if (char === "t") token = { type: "literal", expected: "true", index: 1, value: true };
73
+ else if (char === "f") token = { type: "literal", expected: "false", index: 1, value: false };
74
+ else if (char === "n") token = { type: "literal", expected: "null", index: 1, value: null };
75
+ else if (char === "-") token = { type: "number", phase: "minus" };
76
+ else if (char === "0") token = { type: "number", phase: "zero" };
77
+ else if (char >= "1" && char <= "9") token = { type: "number", phase: "int" };
78
+ else return false;
79
+ return true;
80
+ };
81
+
82
+ const closeContainer = (): true => {
83
+ stack.pop();
84
+ completeValue();
85
+ return true;
86
+ };
87
+
88
+ const processChar = (char: string): boolean => {
89
+ if (token?.type === "string") {
90
+ if (token.unicodeDigits > 0) {
91
+ if (!/[0-9a-fA-F]/.test(char)) return false;
92
+ token.unicodeValue += char;
93
+ token.unicodeDigits--;
94
+ if (token.unicodeDigits === 0 && token.capture) {
95
+ if (token.value.length >= 64) return false;
96
+ token.value += String.fromCharCode(Number.parseInt(token.unicodeValue, 16));
97
+ }
98
+ return true;
99
+ }
100
+ if (token.escape) {
101
+ token.escape = false;
102
+ if (char === "u") { token.unicodeDigits = 4; token.unicodeValue = ""; return true; }
103
+ if (!'"\\/bfnrt'.includes(char)) return false;
104
+ if (token.capture) {
105
+ if (token.value.length >= 64) return false;
106
+ token.value += ({ b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" } as Record<string, string>)[char] ?? char;
107
+ }
108
+ return true;
109
+ }
110
+ if (char === "\\") { token.escape = true; return true; }
111
+ if (char === '"') {
112
+ const finished = token;
113
+ token = undefined;
114
+ if (finished.role === "key") {
115
+ const container = parent();
116
+ if (!container || container.type !== "object") return false;
117
+ container.key = finished.value;
118
+ container.state = "colon";
119
+ } else completeValue(finished.capture ? finished.value : undefined);
120
+ return true;
121
+ }
122
+ if (char.charCodeAt(0) < 0x20) return false;
123
+ if (token.capture) {
124
+ if (token.value.length >= 64) return false;
125
+ token.value += char;
126
+ }
127
+ return true;
128
+ }
129
+ if (token?.type === "literal") {
130
+ if (char !== token.expected[token.index]) return false;
131
+ token.index++;
132
+ if (token.index === token.expected.length) {
133
+ const value = token.value;
134
+ token = undefined;
135
+ completeValue(value);
136
+ }
137
+ return true;
138
+ }
139
+ if (token?.type === "number") {
140
+ const phase = token.phase;
141
+ if (phase === "minus") {
142
+ if (char === "0") token.phase = "zero";
143
+ else if (char >= "1" && char <= "9") token.phase = "int";
144
+ else return false;
145
+ return true;
146
+ }
147
+ if (phase === "zero" || phase === "int") {
148
+ if (char >= "0" && char <= "9") { if (phase === "zero") return false; return true; }
149
+ if (char === ".") { token.phase = "dot"; return true; }
150
+ if (char === "e" || char === "E") { token.phase = "exp"; return true; }
151
+ } else if (phase === "dot") {
152
+ if (char >= "0" && char <= "9") { token.phase = "frac"; return true; }
153
+ return false;
154
+ } else if (phase === "frac") {
155
+ if (char >= "0" && char <= "9") return true;
156
+ if (char === "e" || char === "E") { token.phase = "exp"; return true; }
157
+ } else if (phase === "exp") {
158
+ if (char === "+" || char === "-") { token.phase = "exp-sign"; return true; }
159
+ if (char >= "0" && char <= "9") { token.phase = "exp-digits"; return true; }
160
+ return false;
161
+ } else if (phase === "exp-sign") {
162
+ if (char >= "0" && char <= "9") { token.phase = "exp-digits"; return true; }
163
+ return false;
164
+ } else if (phase === "exp-digits" && char >= "0" && char <= "9") return true;
165
+ if (!["zero", "int", "frac", "exp-digits"].includes(phase)) return false;
166
+ token = undefined;
167
+ completeValue();
168
+ return processChar(char);
169
+ }
170
+ if (char === " " || char === "\t" || char === "\r" || char === "\n") return true;
171
+ const container = parent();
172
+ if (!container) return rootState === "value" ? startValue(char) : false;
173
+ if (container.type === "object") {
174
+ if (container.state === "key-or-end" || container.state === "key") {
175
+ if (char === "}" && container.state === "key-or-end") return closeContainer();
176
+ if (char !== '"') return false;
177
+ token = { type: "string", role: "key", value: "", capture: stack.length === 1, escape: false, unicodeDigits: 0, unicodeValue: "" };
178
+ return true;
179
+ }
180
+ if (container.state === "colon") {
181
+ if (char !== ":") return false;
182
+ container.state = "value";
183
+ return true;
184
+ }
185
+ if (container.state === "value") return startValue(char);
186
+ if (char === ",") { container.state = "key"; return true; }
187
+ if (char === "}") return closeContainer();
188
+ return false;
189
+ }
190
+ if (container.state === "value-or-end" || container.state === "value") {
191
+ if (char === "]" && container.state === "value-or-end") return closeContainer();
192
+ return startValue(char);
193
+ }
194
+ if (char === ",") { container.state = "value"; return true; }
195
+ if (char === "]") return closeContainer();
196
+ return false;
197
+ };
198
+
199
+ const processText = (text: string): boolean => {
200
+ for (const char of text) if (!processChar(char)) return false;
201
+ return true;
202
+ };
203
+
204
+ return {
205
+ push(chunk) {
206
+ if (!valid) return false;
207
+ try { valid = processText(decoder.decode(chunk, { stream: true })); }
208
+ catch { valid = false; }
209
+ return valid;
210
+ },
211
+ finish() {
212
+ try { valid = valid && processText(decoder.decode()); }
213
+ catch { valid = false; }
214
+ if (token?.type === "number" && ["zero", "int", "frac", "exp-digits"].includes(token.phase)) {
215
+ token = undefined;
216
+ completeValue();
217
+ }
218
+ if (!valid || token || stack.length !== 0 || rootState !== "end") return undefined;
219
+ if (eventType === "turn_end") return '{"type":"turn_end"}';
220
+ if (eventType === "agent_end" && typeof willRetry === "boolean") return JSON.stringify({ type: "agent_end", willRetry });
221
+ return undefined;
222
+ },
223
+ };
224
+ }
225
+
226
+ /**
227
+ * Pi JSON mode emits granular message/tool events followed by aggregate
228
+ * `turn_end` and `agent_end` events that duplicate those payloads. Parallel
229
+ * image reads can make one aggregate record exceed the child line limit even
230
+ * though every granular event was valid. Replace only syntactically valid,
231
+ * redundant records with the lifecycle fields the runners consume.
232
+ */
233
+ export const PI_AGGREGATE_EVENT_PROJECTOR: OversizedLineProjector = {
234
+ accepts(prefix) {
235
+ return prefix.startsWith('{"type":"turn_end"') || prefix.startsWith('{"type":"agent_end"');
236
+ },
237
+ create: createPiAggregateProjection,
238
+ };
239
+
240
+ export function formatProtocolOutputLimit(limit: ProtocolOutputLimit): string {
241
+ return `${limit.code}: child ${limit.stream} line exceeded ${limit.limitBytes} bytes (observed at least ${limit.observedBytes} bytes without a newline).`;
242
+ }
243
+
244
+ export function createBoundedLineReader(options: {
245
+ stream?: "stdout" | "stderr";
246
+ maxPendingLineBytes?: number;
247
+ oversizedLineProjector?: OversizedLineProjector;
248
+ onLine: (line: string) => void;
249
+ onLimit: (limit: ProtocolOutputLimit) => void;
250
+ }): {
251
+ push(chunk: Buffer | string): void;
252
+ end(): void;
253
+ exceeded(): boolean;
254
+ } {
255
+ const maxPendingLineBytes = options.maxPendingLineBytes ?? MAX_CHILD_PENDING_LINE_BYTES;
256
+ if (!Number.isInteger(maxPendingLineBytes) || maxPendingLineBytes < 1) {
257
+ throw new Error("maxPendingLineBytes must be a positive integer.");
258
+ }
259
+ let pending: Buffer[] = [];
260
+ let pendingBytes = 0;
261
+ let projectedPrefix: Buffer<ArrayBufferLike> = Buffer.alloc(0);
262
+ let projectedTail: Buffer<ArrayBufferLike> = Buffer.alloc(0);
263
+ let projectedBytes = 0;
264
+ let projection: OversizedLineProjection | undefined;
265
+ let projectingOversizedLine = false;
266
+ let limitExceeded = false;
267
+
268
+ const diagnosticTail = (prior: Buffer, segment: Buffer): Buffer => {
269
+ const tailFromSegment = segment.subarray(Math.max(0, segment.length - MAX_PROTOCOL_DIAGNOSTIC_BYTES));
270
+ return tailFromSegment.length === MAX_PROTOCOL_DIAGNOSTIC_BYTES
271
+ ? tailFromSegment
272
+ : Buffer.concat([prior.subarray(Math.max(0, prior.length - (MAX_PROTOCOL_DIAGNOSTIC_BYTES - tailFromSegment.length))), tailFromSegment]);
273
+ };
274
+
275
+ const failLimit = (observedBytes: number, prefix: Buffer, tail: Buffer): false => {
276
+ limitExceeded = true;
277
+ pending = [];
278
+ pendingBytes = 0;
279
+ projectingOversizedLine = false;
280
+ projection = undefined;
281
+ projectedPrefix = Buffer.alloc(0);
282
+ projectedTail = Buffer.alloc(0);
283
+ projectedBytes = 0;
284
+ options.onLimit({
285
+ code: "protocol_output_limit",
286
+ stream: options.stream ?? "stdout",
287
+ limitBytes: maxPendingLineBytes,
288
+ observedBytes,
289
+ diagnosticPrefix: prefix.toString("utf8"),
290
+ diagnosticTail: tail.toString("utf8"),
291
+ });
292
+ return false;
293
+ };
294
+
295
+ const finishLine = (): void => {
296
+ if (projectingOversizedLine) {
297
+ const projected = projection?.finish();
298
+ if (projected === undefined) {
299
+ failLimit(projectedBytes, projectedPrefix, projectedTail);
300
+ } else {
301
+ options.onLine(projected);
302
+ }
303
+ } else if (pendingBytes > 0) {
304
+ options.onLine(Buffer.concat(pending, pendingBytes).toString("utf8"));
305
+ }
306
+ pending = [];
307
+ pendingBytes = 0;
308
+ projectingOversizedLine = false;
309
+ projection = undefined;
310
+ projectedPrefix = Buffer.alloc(0);
311
+ projectedTail = Buffer.alloc(0);
312
+ projectedBytes = 0;
313
+ };
314
+
315
+ const append = (segment: Buffer): boolean => {
316
+ if (segment.length === 0) return true;
317
+ if (projectingOversizedLine) {
318
+ projectedBytes += segment.length;
319
+ projectedTail = diagnosticTail(projectedTail, segment);
320
+ return projection?.push(segment) === true || failLimit(projectedBytes, projectedPrefix, projectedTail);
321
+ }
322
+ const observedBytes = pendingBytes + segment.length;
323
+ if (observedBytes > maxPendingLineBytes) {
324
+ const prior = pendingBytes > 0 ? Buffer.concat(pending, pendingBytes) : Buffer.alloc(0);
325
+ const prefixFromPrior = prior.subarray(0, MAX_PROTOCOL_DIAGNOSTIC_BYTES);
326
+ const prefix = prefixFromPrior.length === MAX_PROTOCOL_DIAGNOSTIC_BYTES
327
+ ? prefixFromPrior
328
+ : Buffer.concat([prefixFromPrior, segment.subarray(0, MAX_PROTOCOL_DIAGNOSTIC_BYTES - prefixFromPrior.length)]);
329
+ const tail = diagnosticTail(prior, segment);
330
+ if (options.oversizedLineProjector?.accepts(prefix.toString("utf8"))) {
331
+ const candidate = options.oversizedLineProjector.create();
332
+ if (!candidate.push(prior) || !candidate.push(segment)) return failLimit(observedBytes, prefix, tail);
333
+ pending = [];
334
+ pendingBytes = 0;
335
+ projectingOversizedLine = true;
336
+ projection = candidate;
337
+ projectedPrefix = prefix;
338
+ projectedTail = tail;
339
+ projectedBytes = observedBytes;
340
+ return true;
341
+ }
342
+ return failLimit(observedBytes, prefix, tail);
343
+ }
344
+ pending.push(segment);
345
+ pendingBytes = observedBytes;
346
+ return true;
347
+ };
348
+
349
+ return {
350
+ push(chunk) {
351
+ if (limitExceeded) return;
352
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
353
+ let start = 0;
354
+ for (let index = 0; index < bytes.length; index++) {
355
+ if (bytes[index] !== 0x0a) continue;
356
+ if (!append(bytes.subarray(start, index))) return;
357
+ finishLine();
358
+ if (limitExceeded) return;
359
+ start = index + 1;
360
+ }
361
+ append(bytes.subarray(start));
362
+ },
363
+ end() {
364
+ if (!limitExceeded) finishLine();
365
+ },
366
+ exceeded: () => limitExceeded,
367
+ };
368
+ }
369
+
370
+ function trimToUtf8Boundary(buffer: Buffer, maxBytes: number): Buffer {
371
+ if (buffer.length <= maxBytes) return buffer;
372
+ let start = buffer.length - maxBytes;
373
+ while (start < buffer.length && (buffer[start]! & 0xc0) === 0x80) start++;
374
+ return buffer.subarray(start);
375
+ }
376
+
377
+ export function createBoundedByteTail(maxBytes = MAX_CHILD_STDERR_BYTES): {
378
+ push(chunk: Buffer | string): void;
379
+ text(): string;
380
+ byteLength(): number;
381
+ } {
382
+ if (!Number.isInteger(maxBytes) || maxBytes < 1) throw new Error("maxBytes must be a positive integer.");
383
+ let tail: Buffer<ArrayBufferLike> = Buffer.alloc(0);
384
+ return {
385
+ push(chunk) {
386
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
387
+ tail = trimToUtf8Boundary(Buffer.concat([tail, bytes]), maxBytes);
388
+ },
389
+ text: () => tail.toString("utf8"),
390
+ byteLength: () => tail.length,
391
+ };
392
+ }
393
+
394
+ export type ChildLifecycleAction = "start-drain" | "cancel-drain" | "none";
395
+
396
+ export function projectChildLifecycle(event: { type?: string; willRetry?: unknown }, terminalAssistantStop = false): ChildLifecycleAction {
397
+ if (event.type === "agent_end" && event.willRetry === true) return "cancel-drain";
398
+ if (event.type === "agent_settled") return "start-drain";
399
+ if (terminalAssistantStop) return "start-drain";
400
+ return "none";
401
+ }
@@ -0,0 +1,95 @@
1
+ import type { Message } from "@earendil-works/pi-ai";
2
+ import { isMutatingTool } from "./long-running-guard.ts";
3
+ import { expectsImplementationMutation } from "./task-intent.ts";
4
+
5
+ export { expectsImplementationMutation };
6
+
7
+ const READ_ONLY_BUILTIN_TOOLS = new Set([
8
+ "read",
9
+ "grep",
10
+ "find",
11
+ "ls",
12
+ "web_search",
13
+ "fetch_content",
14
+ "get_search_content",
15
+ "intercom",
16
+ "contact_supervisor",
17
+ ]);
18
+
19
+ // Cursor native edit/write often land as thinking traces (inactive_trace /
20
+ // transcript_trace) rather than toolCall parts when native tool replay is off
21
+ // or the tool is inactive in context. Match pi-cursor-sdk display labels.
22
+ const CURSOR_FILE_MUTATION_THINKING =
23
+ /(?:^|\n)\s*Cursor (?:edit|write)\s*:/i;
24
+
25
+ interface CompletionMutationGuardInput {
26
+ agent: string;
27
+ task: string;
28
+ messages: Message[];
29
+ tools?: string[];
30
+ mcpDirectTools?: string[];
31
+ }
32
+
33
+ interface CompletionMutationGuardResult {
34
+ expectedMutation: boolean;
35
+ attemptedMutation: boolean;
36
+ triggered: boolean;
37
+ }
38
+
39
+ export function hasMutationToolCapability(tools: string[] | undefined, mcpDirectTools: string[] | undefined): boolean {
40
+ if ((mcpDirectTools?.length ?? 0) > 0) return true;
41
+ if (tools === undefined) return true;
42
+ return !tools.every((tool) => READ_ONLY_BUILTIN_TOOLS.has(tool));
43
+ }
44
+
45
+ function hasCheckpointMutationEvidence(message: Message): boolean {
46
+ const record = message as unknown as {
47
+ role?: string;
48
+ type?: string;
49
+ customType?: unknown;
50
+ data?: unknown;
51
+ details?: unknown;
52
+ };
53
+ if ((record.role !== "custom" && record.type !== "custom") || record.customType !== "pi-checkpoint") return false;
54
+ const details = typeof record.details === "object" && record.details !== null && !Array.isArray(record.details)
55
+ ? record.details as Record<string, unknown>
56
+ : undefined;
57
+ const data = typeof record.data === "object" && record.data !== null && !Array.isArray(record.data)
58
+ ? record.data as Record<string, unknown>
59
+ : typeof details?.beforeCommit === "string" || typeof details?.afterCommit === "string"
60
+ ? details
61
+ : details?.data && typeof details.data === "object" && !Array.isArray(details.data)
62
+ ? details.data as Record<string, unknown>
63
+ : undefined;
64
+ return typeof data?.beforeCommit === "string"
65
+ && typeof data.afterCommit === "string"
66
+ && data.beforeCommit !== data.afterCommit;
67
+ }
68
+
69
+ export function hasMutationToolCall(messages: Message[]): boolean {
70
+ for (const message of messages) {
71
+ if (hasCheckpointMutationEvidence(message)) return true;
72
+ if (message.role !== "assistant") continue;
73
+ for (const part of message.content) {
74
+ if (part.type === "thinking" && CURSOR_FILE_MUTATION_THINKING.test(part.thinking)) return true;
75
+ if (part.type !== "toolCall") continue;
76
+ const args = typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments)
77
+ ? part.arguments as Record<string, unknown>
78
+ : {};
79
+ if (isMutatingTool(part.name, args)) return true;
80
+ }
81
+ }
82
+ return false;
83
+ }
84
+
85
+ export function evaluateCompletionMutationGuard(input: CompletionMutationGuardInput): CompletionMutationGuardResult {
86
+ const expectedMutation = hasMutationToolCapability(input.tools, input.mcpDirectTools)
87
+ ? expectsImplementationMutation(input.agent, input.task)
88
+ : false;
89
+ const attemptedMutation = hasMutationToolCall(input.messages);
90
+ return {
91
+ expectedMutation,
92
+ attemptedMutation,
93
+ triggered: expectedMutation && !attemptedMutation,
94
+ };
95
+ }
@@ -0,0 +1,44 @@
1
+ export type ContextMode = "fresh" | "fork";
2
+ export type ContextSummary = ContextMode | "mixed";
3
+
4
+ export function isContextMode(value: unknown): value is ContextMode {
5
+ return value === "fresh" || value === "fork";
6
+ }
7
+
8
+ export function isContextSummary(value: unknown): value is ContextSummary {
9
+ return isContextMode(value) || value === "mixed";
10
+ }
11
+
12
+ export function summarizeContextModes(modes: Array<ContextMode | undefined>): ContextSummary | undefined {
13
+ const resolved = modes.filter(isContextMode);
14
+ if (resolved.length === 0) return undefined;
15
+ const first = resolved[0]!;
16
+ return resolved.every((mode) => mode === first) ? first : "mixed";
17
+ }
18
+
19
+ export function contextModeLabel(mode: ContextMode | ContextSummary | undefined): string {
20
+ if (mode === "fork") return "[fork]";
21
+ if (mode === "fresh") return "[fresh]";
22
+ if (mode === "mixed") return "[mixed]";
23
+ return "";
24
+ }
25
+
26
+ export function contextModeBadge(
27
+ theme: { fg(name: string, text: string): string },
28
+ mode: ContextMode | ContextSummary | undefined,
29
+ ): string {
30
+ const label = contextModeLabel(mode);
31
+ if (!label) return "";
32
+ if (mode === "fork") return theme.fg("warning", ` ${label}`);
33
+ return theme.fg("dim", ` ${label}`);
34
+ }
35
+
36
+ export function contextModePrefix(
37
+ theme: { fg(name: string, text: string): string },
38
+ mode: ContextMode | ContextSummary | undefined,
39
+ ): string {
40
+ const label = contextModeLabel(mode);
41
+ if (!label) return "";
42
+ if (mode === "fork") return `${theme.fg("warning", label)} `;
43
+ return `${theme.fg("dim", label)} `;
44
+ }