@herbertgao/pi-extensions 2026.11.18 → 2026.11.19

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 (151) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +2 -23
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
  5. package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
  10. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
  11. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
  12. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
  13. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
  14. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
  15. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
  16. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
  17. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
  18. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
  19. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
  20. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
  21. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
  22. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
  23. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
  24. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
  25. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
  26. package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
  27. package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
  28. package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
  29. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
  30. package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
  31. package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
  32. package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
  33. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
  34. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
  35. package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
  36. package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
  37. package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
  38. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
  39. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
  40. package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
  41. package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
  42. package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
  43. package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
  44. package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
  45. package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
  46. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
  47. package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
  48. package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
  49. package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
  50. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
  51. package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
  52. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
  53. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
  54. package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
  55. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
  56. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
  57. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
  58. package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
  59. package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
  60. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  61. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
  62. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
  63. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  64. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
  65. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  66. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
  67. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  68. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  69. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  70. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  71. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  72. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  73. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
  74. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  75. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  76. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
  77. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  78. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
  80. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  82. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  84. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  85. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  86. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  87. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  88. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  89. package/node_modules/pi-commandcode-provider/README.md +3 -2
  90. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  91. package/node_modules/pi-commandcode-provider/package.json +4 -3
  92. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  93. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  94. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  95. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  96. package/package.json +11 -14
  97. package/node_modules/pi-antigravity/README.md +0 -298
  98. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  99. package/node_modules/pi-antigravity/package.json +0 -87
  100. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  101. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  102. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  103. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  104. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  105. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  106. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  107. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  108. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  109. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  110. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  111. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  112. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  113. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  114. package/node_modules/pi-antigravity/src/index.ts +0 -547
  115. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  116. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  117. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  118. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  119. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  120. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  121. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  122. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  123. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  124. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  125. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  126. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  127. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  128. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  129. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  130. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  131. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  132. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  133. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  134. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  135. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  136. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  137. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  138. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  139. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  140. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  141. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  142. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  143. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  144. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  145. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  146. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  147. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  148. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  149. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  150. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  151. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -0,0 +1,161 @@
1
+ // agy stream-json NDJSON event types + parser.
2
+ //
3
+ // `agy --input-format stream-json --output-format stream-json` emits one JSON
4
+ // object per line on stdout: `init` (conversation binding), `step_update`
5
+ // (user_input / agent_response / checkpoint / tool steps), `result` (terminal).
6
+ // Shapes captured from live output. Unknown event kinds parse as
7
+ // {kind:"unknown"} so a future agy release degrades instead of crashing the
8
+ // reader loop.
9
+
10
+ export interface AgyUsage {
11
+ input_tokens?: number;
12
+ output_tokens?: number;
13
+ thinking_tokens?: number;
14
+ cache_read_tokens?: number;
15
+ total_tokens?: number;
16
+ }
17
+
18
+ export type AgyStepState = "ACTIVE" | "DONE" | "ERROR" | string;
19
+ export type AgyStepType = "user_input" | "checkpoint" | "agent_response" | "tool" | (string & {});
20
+
21
+ export interface AgyToolInfo {
22
+ name?: string;
23
+ parameters?: Record<string, unknown>;
24
+ [key: string]: unknown;
25
+ }
26
+
27
+ export interface AgyStepUpdate {
28
+ step_index?: number;
29
+ state?: AgyStepState;
30
+ step_type?: AgyStepType;
31
+ conversation_id?: string;
32
+ tool_name?: string;
33
+ tool_info?: AgyToolInfo;
34
+ response_text?: string;
35
+ /** Live agy (1.1.13+): agent_response deltas arrive here, not in response_text. */
36
+ text_delta?: string;
37
+ thought_text?: string;
38
+ thinking_tokens?: number;
39
+ thinking_signature?: string;
40
+ duration_seconds?: number;
41
+ error_message?: string;
42
+ usage?: AgyUsage;
43
+ [key: string]: unknown;
44
+ }
45
+
46
+ export interface AgyResult {
47
+ status?: string;
48
+ response?: string;
49
+ error?: string;
50
+ usage?: AgyUsage;
51
+ conversation_id?: string;
52
+ [key: string]: unknown;
53
+ }
54
+
55
+ export type ParsedAgyEvent =
56
+ | { kind: "init"; conversationId?: string; usage?: AgyUsage }
57
+ | { kind: "step"; step: AgyStepUpdate }
58
+ | { kind: "result"; result: AgyResult }
59
+ | { kind: "unknown"; raw: unknown };
60
+
61
+ /** Parse one stdout line. Never throws; bad JSON / non-objects become "unknown". */
62
+ export function parseAgyLine(line: string): ParsedAgyEvent {
63
+ const trimmed = line.trim();
64
+ if (!trimmed) return { kind: "unknown", raw: null };
65
+ let obj: unknown;
66
+ try {
67
+ obj = JSON.parse(trimmed);
68
+ } catch {
69
+ return { kind: "unknown", raw: trimmed.slice(0, 200) };
70
+ }
71
+ if (typeof obj !== "object" || obj === null) return { kind: "unknown", raw: obj };
72
+ const rec = obj as Record<string, unknown>;
73
+ if (rec.event === "init" && typeof rec.init === "object" && rec.init !== null) {
74
+ const init = rec.init as Record<string, unknown>;
75
+ return {
76
+ kind: "init",
77
+ conversationId:
78
+ typeof init.conversation_id === "string" ? init.conversation_id : undefined,
79
+ usage: isUsage(init.usage) ? init.usage : undefined,
80
+ };
81
+ }
82
+ if (rec.event === "step_update" && typeof rec.step_update === "object" && rec.step_update !== null) {
83
+ return { kind: "step", step: rec.step_update as AgyStepUpdate };
84
+ }
85
+ if (rec.event === "result" && typeof rec.result === "object" && rec.result !== null) {
86
+ return { kind: "result", result: rec.result as AgyResult };
87
+ }
88
+ // Tolerate top-level shorthand: some agy builds put the payload at the root.
89
+ if (rec.event === "init") {
90
+ return {
91
+ kind: "init",
92
+ conversationId: typeof rec.conversation_id === "string" ? rec.conversation_id : undefined,
93
+ usage: isUsage(rec.usage) ? (rec.usage as AgyUsage) : undefined,
94
+ };
95
+ }
96
+ if (typeof rec.step_type === "string") return { kind: "step", step: rec as AgyStepUpdate };
97
+ if (typeof rec.status === "string") return { kind: "result", result: rec as AgyResult };
98
+ return { kind: "unknown", raw: obj };
99
+ }
100
+
101
+ function isUsage(u: unknown): u is AgyUsage {
102
+ return typeof u === "object" && u !== null;
103
+ }
104
+
105
+ /** Map agy usage onto pi-ai's Usage (cost stays zero: subscription quota). */
106
+ export function toPiUsage(
107
+ u: AgyUsage | undefined,
108
+ piUsage: {
109
+ input: number;
110
+ output: number;
111
+ cacheRead: number;
112
+ cacheWrite: number;
113
+ totalTokens: number;
114
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
115
+ },
116
+ ): void {
117
+ if (!u) return;
118
+ piUsage.input = u.input_tokens ?? piUsage.input;
119
+ piUsage.output = u.output_tokens ?? piUsage.output;
120
+ piUsage.cacheRead = u.cache_read_tokens ?? piUsage.cacheRead;
121
+ piUsage.totalTokens = u.total_tokens ?? piUsage.input + piUsage.output;
122
+ }
123
+
124
+ /**
125
+ * Prevent pi-ai's silent-overflow detector (`isContextOverflow` Case 2) from
126
+ * false-triggering on multi-inference billing sums.
127
+ *
128
+ * In multi-step turns (several tool inferences inside one prompt), agy sums
129
+ * `input_tokens` and `cache_read_tokens` across every inference. `AcpDriver`
130
+ * keeps those billing fields while replacing `total_tokens` with single-turn
131
+ * context occupancy (issue #12). However, pi-ai's `isContextOverflow` ignores
132
+ * `totalTokens` and checks `usage.input + usage.cacheRead > contextWindow` on
133
+ * `stopReason === "stop"`, which triggers emergency overflow compaction at a
134
+ * fraction of the real context window.
135
+ *
136
+ * When live occupancy (`totalTokens`) fits inside `contextWindow` but
137
+ * `input + cacheRead` exceeds it, scale `input` and `cacheRead` proportionally
138
+ * to fit within the single-turn input budget (preserving the cache-hit ratio).
139
+ * Normal turns (`input + cacheRead <= contextWindow`) and genuine silent
140
+ * overflows (`totalTokens > contextWindow`) are left untouched.
141
+ */
142
+ export function clampOverflowUsage(
143
+ usage: { input: number; output: number; cacheRead: number; totalTokens: number },
144
+ contextWindow: number | undefined,
145
+ ): void {
146
+ if (contextWindow === undefined || !Number.isFinite(contextWindow) || contextWindow <= 0) return;
147
+ if (!Number.isFinite(usage.totalTokens) || usage.totalTokens <= 0) return;
148
+ if (usage.totalTokens > contextWindow) return;
149
+ if (!Number.isFinite(usage.input) || !Number.isFinite(usage.cacheRead)) return;
150
+ if (usage.input < 0 || usage.cacheRead < 0) return;
151
+ const rawInput = usage.input + usage.cacheRead;
152
+ if (rawInput <= contextWindow) return;
153
+
154
+ const target =
155
+ Number.isFinite(usage.output) && usage.output >= 0 && usage.output < usage.totalTokens
156
+ ? usage.totalTokens - usage.output
157
+ : usage.totalTokens;
158
+ const scaledInput = Math.min(target, Math.max(0, Math.round((usage.input / rawInput) * target)));
159
+ usage.input = scaledInput;
160
+ usage.cacheRead = target - scaledInput;
161
+ }
@@ -0,0 +1,180 @@
1
+ // Stream Delta Sanitizer:
2
+ // Google Antigravity injects asynchronous background task notifications into
3
+ // the active LLM context formatted as:
4
+ // The following is a <SYSTEM_MESSAGE> not actually sent by the user...
5
+ // <SYSTEM_MESSAGE>
6
+ // [Message] timestamp=... sender=... content=...
7
+ // </SYSTEM_MESSAGE>
8
+ //
9
+ // Models (notably Gemini 3.8 Flash) frequently regurgitate or echo this preamble
10
+ // verbatim as an assistant text response before proceeding with tools or answer.
11
+ //
12
+ // StreamSanitizer buffers and strips these blocks statefully across streaming
13
+ // deltas so they never leak into the user's transcript.
14
+
15
+ export const START_MARKER = "The following is a <SYSTEM_MESSAGE>";
16
+ export const END_MARKER = "</SYSTEM_MESSAGE>";
17
+
18
+ export const SYSTEM_MESSAGE_RE =
19
+ /(?:\r?\n)?The following is a <SYSTEM_MESSAGE>[\s\S]*?<\/SYSTEM_MESSAGE>(?:\r?\n)?/g;
20
+
21
+ /** Non-streaming sanitization for full text strings (result bodies, parked turns, transcripts). */
22
+ export function sanitizeSystemMessage(text: string): string {
23
+ if (!text) return "";
24
+ return text.replace(SYSTEM_MESSAGE_RE, "");
25
+ }
26
+
27
+ /** Stateful streaming sanitizer that inspects and suppresses <SYSTEM_MESSAGE> blocks across chunks. */
28
+ export class StreamSanitizer {
29
+ #buffer = "";
30
+ #suppressing = false;
31
+ #suppressedAcc = "";
32
+ #emittedAny = false;
33
+
34
+ /**
35
+ * Feed an incoming chunk of streamed text.
36
+ * Returns the sanitized delta to emit downstream (empty string if suppressed or buffering).
37
+ */
38
+ push(chunk: string): string {
39
+ if (!chunk) return "";
40
+ this.#buffer += chunk;
41
+ let out = "";
42
+
43
+ while (this.#buffer.length > 0) {
44
+ if (!this.#suppressing) {
45
+ const startIdx = this.#buffer.indexOf(START_MARKER);
46
+ if (startIdx !== -1) {
47
+ // There is a start marker in the buffer.
48
+ if (startIdx > 0) {
49
+ const before = this.#buffer.slice(0, startIdx);
50
+ if (!this.#emittedAny && before.trim() === "") {
51
+ // Discard leading padding before initial system message.
52
+ } else {
53
+ // Strip at most one trailing newline right before the block.
54
+ const trimmedBefore = before.replace(/\r?\n$/, "");
55
+ if (trimmedBefore.length > 0) {
56
+ out += trimmedBefore;
57
+ this.#emittedAny = true;
58
+ }
59
+ }
60
+ }
61
+ this.#buffer = this.#buffer.slice(startIdx + START_MARKER.length);
62
+ this.#suppressing = true;
63
+ this.#suppressedAcc = START_MARKER;
64
+ continue;
65
+ }
66
+
67
+ // START_MARKER is not yet in the buffer.
68
+ // Check if the tail of buffer matches a prefix of START_MARKER.
69
+ const maxOverlap = Math.min(this.#buffer.length, START_MARKER.length - 1);
70
+ let overlapLen = 0;
71
+ for (let len = maxOverlap; len > 0; len--) {
72
+ if (START_MARKER.startsWith(this.#buffer.slice(-len))) {
73
+ overlapLen = len;
74
+ break;
75
+ }
76
+ }
77
+
78
+ if (overlapLen > 0) {
79
+ const safeLen = this.#buffer.length - overlapLen;
80
+ if (safeLen > 0) {
81
+ out += this.#buffer.slice(0, safeLen);
82
+ this.#emittedAny = true;
83
+ this.#buffer = this.#buffer.slice(safeLen);
84
+ }
85
+ // Keep overlapLen in buffer to see if next chunk completes the marker.
86
+ break;
87
+ } else {
88
+ out += this.#buffer;
89
+ this.#emittedAny = true;
90
+ this.#buffer = "";
91
+ break;
92
+ }
93
+ } else {
94
+ // Suppressing inside <SYSTEM_MESSAGE>...</SYSTEM_MESSAGE>
95
+ const endIdx = this.#buffer.indexOf(END_MARKER);
96
+ if (endIdx !== -1) {
97
+ let afterEnd = endIdx + END_MARKER.length;
98
+ if (!this.#emittedAny) {
99
+ // Discard all leading newlines before the first real content.
100
+ while (
101
+ afterEnd < this.#buffer.length &&
102
+ (this.#buffer[afterEnd] === "\r" || this.#buffer[afterEnd] === "\n")
103
+ ) {
104
+ afterEnd++;
105
+ }
106
+ } else {
107
+ // Consume trailing newlines after </SYSTEM_MESSAGE> to preserve paragraph spacing.
108
+ if (this.#buffer.startsWith("\r\n\r\n", afterEnd)) {
109
+ afterEnd += 4;
110
+ } else if (this.#buffer.startsWith("\n\n", afterEnd)) {
111
+ afterEnd += 2;
112
+ } else if (this.#buffer.startsWith("\r\n", afterEnd)) {
113
+ afterEnd += 2;
114
+ } else if (this.#buffer.startsWith("\n", afterEnd)) {
115
+ afterEnd += 1;
116
+ }
117
+ }
118
+ this.#buffer = this.#buffer.slice(afterEnd);
119
+ this.#suppressing = false;
120
+ this.#suppressedAcc = "";
121
+ continue;
122
+ }
123
+
124
+ // END_MARKER not yet encountered. Check if tail matches prefix of END_MARKER.
125
+ const maxOverlap = Math.min(this.#buffer.length, END_MARKER.length - 1);
126
+ let overlapLen = 0;
127
+ for (let len = maxOverlap; len > 0; len--) {
128
+ if (END_MARKER.startsWith(this.#buffer.slice(-len))) {
129
+ overlapLen = len;
130
+ break;
131
+ }
132
+ }
133
+
134
+ if (overlapLen > 0) {
135
+ this.#suppressedAcc += this.#buffer.slice(0, -overlapLen);
136
+ this.#buffer = this.#buffer.slice(-overlapLen);
137
+ } else {
138
+ this.#suppressedAcc += this.#buffer;
139
+ this.#buffer = "";
140
+ }
141
+ break;
142
+ }
143
+ }
144
+
145
+ return out;
146
+ }
147
+
148
+ /** Flush remaining buffered text when stream ends. */
149
+ flush(): string {
150
+ if (this.#suppressing) {
151
+ const unclosed = this.#suppressedAcc + this.#buffer;
152
+ this.#buffer = "";
153
+ this.#suppressedAcc = "";
154
+ this.#suppressing = false;
155
+ if (unclosed.length > 0) {
156
+ this.#emittedAny = true;
157
+ }
158
+ return unclosed;
159
+ }
160
+ const remaining = this.#buffer;
161
+ this.#buffer = "";
162
+ if (remaining.length > 0) {
163
+ this.#emittedAny = true;
164
+ }
165
+ return remaining;
166
+ }
167
+
168
+ /** Peek at non-suppressed buffer contents without consuming them. */
169
+ peek(): string {
170
+ return this.#suppressing ? "" : this.#buffer;
171
+ }
172
+
173
+ /** Reset state. */
174
+ reset(): void {
175
+ this.#buffer = "";
176
+ this.#suppressedAcc = "";
177
+ this.#suppressing = false;
178
+ this.#emittedAny = false;
179
+ }
180
+ }
@@ -0,0 +1,245 @@
1
+ // In-memory subagent roster, folded from driver activities.
2
+ //
3
+ // agy has no read-only subcommand for live subagent state, so the only
4
+ // zero-token source is the turn stream: subagent spawns arrive as ordinary
5
+ // tool steps (invoke_subagent, run_subagent, define_subagent,
6
+ // browser_subagent), send_message addresses a spawned agent, and
7
+ // manage_subagents carries lifecycle actions. The roster folds
8
+ // DriverActivity — the engine-agnostic contract both turn engines emit — so
9
+ // stream-json (stepId-keyed) and ACP (toolCallId-keyed) feed one roster.
10
+ //
11
+ // Accepted heuristic limits (telemetry only, never persisted — agy's own
12
+ // conversation database remains the durable record):
13
+ // - send_message routes to the FIRST entry with the matching agent name
14
+ // regardless of status, so a message after a name is reused may credit a
15
+ // stale entry.
16
+ // - manage_subagents kill marks ALL running entries killed; the target arg
17
+ // is ignored because its shape is not stable across agy builds.
18
+ // - Parallel spawns with the same agent name are separate entries, but
19
+ // name-based routing cannot tell them apart.
20
+
21
+ import type { DriverActivity } from "./driver-types.js";
22
+
23
+ /** Tools whose start opens a roster entry and whose done/error closes it. */
24
+ const SPAWN_TOOLS = new Set(["invoke_subagent", "run_subagent", "browser_subagent"]);
25
+ /** Tools addressed at an already-spawned agent. */
26
+ const MESSAGE_TOOLS = new Set(["send_message"]);
27
+ /** Tools carrying lifecycle actions (kill/stop/...). */
28
+ const MANAGE_TOOLS = new Set(["manage_subagents"]);
29
+
30
+ /** Arg keys that plausibly name the target agent (their casing varies). */
31
+ const NAME_ARG_KEYS = /^(name|subagent|subagent_name|agent|agent_name|type|recipient|role|to)$/i;
32
+ /** Arg keys plausibly holding a manage_subagents lifecycle action. */
33
+ const ACTION_ARG_KEYS = /^(action|command|operation|op)$/i;
34
+ const DETAIL_MAX = 120;
35
+
36
+ export interface SubagentEntry {
37
+ /** Stable fold key: `s:<stepId>` on stream-json, `n:<seq>` on ACP. */
38
+ key: string;
39
+ name: string;
40
+ status: "running" | "done" | "error" | "killed";
41
+ spawnedAtMs: number;
42
+ lastActivityMs: number;
43
+ /** send_message count since spawn. */
44
+ messages: number;
45
+ /** First non-name string arg, truncated — usually the task text. */
46
+ detail: string;
47
+ error?: string;
48
+ }
49
+
50
+ function truncate(value: string): string {
51
+ return value.length > DETAIL_MAX ? `${value.slice(0, DETAIL_MAX)}…` : value;
52
+ }
53
+
54
+ /** First string arg whose key plausibly names the agent. */
55
+ function subagentNameFromArgs(args: Record<string, unknown>): string {
56
+ for (const [k, v] of Object.entries(args)) {
57
+ if (NAME_ARG_KEYS.test(k) && typeof v === "string" && v.trim()) return truncate(v.trim());
58
+ }
59
+ return "subagent";
60
+ }
61
+
62
+ /** First string arg that is not the name — the task text, when agy passes one. */
63
+ function detailFromArgs(args: Record<string, unknown>): string {
64
+ for (const [k, v] of Object.entries(args)) {
65
+ if (!NAME_ARG_KEYS.test(k) && typeof v === "string" && v.trim()) return truncate(v.trim());
66
+ }
67
+ return "";
68
+ }
69
+
70
+ interface ExtractedSpawn {
71
+ name: string;
72
+ detail: string;
73
+ }
74
+
75
+ function extractSpawnsFromArgs(args: Record<string, unknown>): ExtractedSpawn[] {
76
+ const raw = args.Subagents ?? args.subagents;
77
+ if (Array.isArray(raw) && raw.length > 0) {
78
+ const out: ExtractedSpawn[] = [];
79
+ for (const item of raw) {
80
+ if (item && typeof item === "object") {
81
+ const rec = item as Record<string, unknown>;
82
+ const name =
83
+ (typeof rec.Role === "string" && rec.Role.trim()) ||
84
+ (typeof rec.role === "string" && rec.role.trim()) ||
85
+ (typeof rec.TypeName === "string" && rec.TypeName.trim()) ||
86
+ (typeof rec.type_name === "string" && rec.type_name.trim()) ||
87
+ (typeof rec.name === "string" && rec.name.trim()) ||
88
+ "subagent";
89
+ const detail =
90
+ (typeof rec.Prompt === "string" && rec.Prompt.trim()) ||
91
+ (typeof rec.prompt === "string" && rec.prompt.trim()) ||
92
+ (typeof rec.task === "string" && rec.task.trim()) ||
93
+ "";
94
+ out.push({ name: truncate(name), detail: truncate(detail) });
95
+ }
96
+ }
97
+ if (out.length > 0) return out;
98
+ }
99
+ return [{ name: subagentNameFromArgs(args), detail: detailFromArgs(args) }];
100
+ }
101
+
102
+ function manageActionIsKill(args: Record<string, unknown>): boolean {
103
+ for (const [k, v] of Object.entries(args)) {
104
+ if (ACTION_ARG_KEYS.test(k) && typeof v === "string" && /kill|stop|terminate|cancel/i.test(v))
105
+ return true;
106
+ }
107
+ return false;
108
+ }
109
+
110
+ export class SubagentRoster {
111
+ #entries = new Map<string, SubagentEntry>();
112
+ #acpSeq = 0;
113
+
114
+ /** Fold key precedence: ACP toolCallId (stable protocol id), stream-json
115
+ * numeric stepId, then a process-local sequence for hypothetical engines
116
+ * with neither. */
117
+ #keyFor(activity: Extract<DriverActivity, { type: "tool_start" }>): string {
118
+ if (activity.toolCallId !== undefined) return `t:${activity.toolCallId}`;
119
+ if (activity.stepId !== undefined) return `s:${activity.stepId}`;
120
+ return `n:${this.#acpSeq++}`;
121
+ }
122
+
123
+ #entriesFor(activity: Extract<DriverActivity, { type: "tool_done" | "tool_error" }>): SubagentEntry[] {
124
+ const baseKey =
125
+ activity.toolCallId !== undefined
126
+ ? `t:${activity.toolCallId}`
127
+ : activity.stepId !== undefined
128
+ ? `s:${activity.stepId}`
129
+ : undefined;
130
+ if (baseKey !== undefined) {
131
+ const matched: SubagentEntry[] = [];
132
+ for (const [k, v] of this.#entries) {
133
+ if (k === baseKey || k.startsWith(`${baseKey}:`)) matched.push(v);
134
+ }
135
+ return matched;
136
+ }
137
+ for (const entry of this.#entries.values()) {
138
+ if (entry.status === "running") return [entry];
139
+ }
140
+ return [];
141
+ }
142
+
143
+ /** Fold one driver activity. Non-tool activities are ignored; unknown
144
+ * tool names are other features' business. Never throws: roster
145
+ * bookkeeping must not be able to fail a turn. */
146
+ fold(activity: DriverActivity): void {
147
+ try {
148
+ this.#fold(activity);
149
+ } catch {
150
+ /* roster is best-effort telemetry */
151
+ }
152
+ }
153
+
154
+ #fold(activity: DriverActivity): void {
155
+ if (activity.type === "tool_start") {
156
+ if (SPAWN_TOOLS.has(activity.name)) {
157
+ const baseKey = this.#keyFor(activity);
158
+ const spawns = extractSpawnsFromArgs(activity.args);
159
+ const now = Date.now();
160
+ for (let i = 0; i < spawns.length; i++) {
161
+ const key = spawns.length === 1 ? baseKey : `${baseKey}:${i}`;
162
+ this.#entries.set(key, {
163
+ key,
164
+ name: spawns[i]!.name,
165
+ status: "running",
166
+ spawnedAtMs: now,
167
+ lastActivityMs: now,
168
+ messages: 0,
169
+ detail: spawns[i]!.detail,
170
+ });
171
+ }
172
+ return;
173
+ }
174
+ if (MESSAGE_TOOLS.has(activity.name)) {
175
+ const entry = this.#entryByName(subagentNameFromArgs(activity.args));
176
+ if (entry) {
177
+ entry.messages += 1;
178
+ entry.lastActivityMs = Date.now();
179
+ }
180
+ return;
181
+ }
182
+ if (MANAGE_TOOLS.has(activity.name) && manageActionIsKill(activity.args)) {
183
+ const now = Date.now();
184
+ for (const entry of this.#entries.values()) {
185
+ if (entry.status === "running") {
186
+ entry.status = "killed";
187
+ entry.lastActivityMs = now;
188
+ }
189
+ }
190
+ }
191
+ return;
192
+ }
193
+ if (activity.type === "tool_done" || activity.type === "tool_error") {
194
+ const entries = this.#entriesFor(activity);
195
+ if (entries.length === 0) return;
196
+ const now = Date.now();
197
+ for (const entry of entries) {
198
+ entry.lastActivityMs = now;
199
+ if (activity.type === "tool_error") {
200
+ entry.status = "error";
201
+ entry.error = truncate(activity.message);
202
+ } else if (entry.status === "running") {
203
+ entry.status = "done";
204
+ }
205
+ }
206
+ }
207
+ }
208
+
209
+ #entryByName(name: string, ...statuses: SubagentEntry["status"][]): SubagentEntry | undefined {
210
+ for (const entry of this.#entries.values()) {
211
+ if (entry.name === name && (statuses.length === 0 || statuses.includes(entry.status)))
212
+ return entry;
213
+ }
214
+ return undefined;
215
+ }
216
+
217
+ /** Entries in spawn order (Map preserves insertion). */
218
+ snapshot(): SubagentEntry[] {
219
+ return [...this.#entries.values()];
220
+ }
221
+
222
+ /** Live wire for status surfaces. */
223
+ runningCount(): number {
224
+ let n = 0;
225
+ for (const entry of this.#entries.values()) if (entry.status === "running") n += 1;
226
+ return n;
227
+ }
228
+ }
229
+
230
+ export function formatSubagentRoster(entries: SubagentEntry[]): string {
231
+ const running = entries.filter((e) => e.status === "running").length;
232
+ const lines = [`antigravity subagents: ${entries.length} tracked, ${running} running`];
233
+ for (const entry of entries) {
234
+ const secs = Math.max(0, Math.round((Date.now() - entry.spawnedAtMs) / 1000));
235
+ const dur = secs >= 60 ? `${Math.floor(secs / 60)}m${String(secs % 60).padStart(2, "0")}s` : `${secs}s`;
236
+ const parts = [
237
+ `${entry.name} · ${entry.status} · ${dur}`,
238
+ entry.messages > 0 ? `${entry.messages} msg` : undefined,
239
+ entry.detail || undefined,
240
+ entry.error ? `error: ${entry.error}` : undefined,
241
+ ].filter((p): p is string => p !== undefined);
242
+ lines.push(`- ${parts.join(" · ")}`);
243
+ }
244
+ return lines.join("\n");
245
+ }