@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,196 @@
1
+ // Daily NDJSON debug log for support and post-mortems.
2
+ //
3
+ // One file per local day: <dir>/YYYY-MM-DD.ndjson, one JSON record per line.
4
+ // Everything the extension logs (driver lifecycle, bridge traffic, round
5
+ // trips, turn outcomes, /agy commands) lands here so a broken session can be
6
+ // replayed from disk instead of from a user's memory. Users attach the last
7
+ // days' files when reporting issues.
8
+ //
9
+ // Hard rules (learned from the pi-token-cost-ledger writer):
10
+ // - Never throw, never await in the hot path. Logging must never disrupt
11
+ // a turn; a broken/unwritable dir is swallowed.
12
+ // - One appendFile per record: O_APPEND keeps single-line writes atomic,
13
+ // so two pi tabs sharing the dir stay line-consistent.
14
+ // - No secrets, no prompt content: values of secret-shaped keys are
15
+ // redacted wholesale, secret-shaped material inside string values
16
+ // (stderr tails, error messages) is scrubbed, and long strings are
17
+ // truncated before they reach disk.
18
+ // - Retention: files older than `retentionDays` are pruned once per
19
+ // process, so the dir cannot grow unbounded.
20
+ // - Volume tiers: default installs write ONLY errors — routine logging
21
+ // costs the disk nothing. Warns surface as UI toasts instead (the
22
+ // extension wraps this logger); AGY_DEBUG=1 restores the full trail
23
+ // (debug/info/warn/error).
24
+
25
+ import { appendFile, mkdir, readdir, unlink } from "node:fs/promises";
26
+ import path from "node:path";
27
+ import { redactText } from "./redact.js";
28
+
29
+ export type LogLevel = "debug" | "info" | "warn" | "error";
30
+
31
+ export interface DailyLoggerOptions {
32
+ /** Target directory (created on first write). */
33
+ dir: string;
34
+ /** Files older than this many days are pruned once per process. Default 14. */
35
+ retentionDays?: number;
36
+ /** Verbose gate. When false (default), only error-level records land on
37
+ * disk; debug/info/warn are dropped so regular users write nothing
38
+ * routine. AGY_DEBUG=1 (or this option) restores the full trail. */
39
+ debug?: boolean;
40
+ /** Injectable clock for tests. */
41
+ now?: () => Date;
42
+ }
43
+
44
+ export interface DailyLogger {
45
+ log(event: string, data?: unknown, level?: LogLevel): void;
46
+ /** Resolves when every queued write settled (tests, shutdown). */
47
+ flush(): Promise<void>;
48
+ readonly dir: string;
49
+ /** Path of the file the next record lands in (doctor display). */
50
+ todayPath(): string;
51
+ }
52
+
53
+ /** Local-date key, lexicographically sortable: 2026-02-05. */
54
+ function dayKey(d: Date): string {
55
+ const p = (n: number) => String(n).padStart(2, "0");
56
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
57
+ }
58
+
59
+ const MAX_STRING = 2000;
60
+ const MAX_DEPTH = 6;
61
+ /** Cap for one serialized line: keeps the O_APPEND atomic-write guarantee
62
+ * honest for PIPE_BUF-sized writes even when many capped fields combine. */
63
+ const MAX_RECORD = 4000;
64
+ // Key-name redaction. `headers` is included wholesale: MCP server configs
65
+ // carry auth material under headers[] ({name, value} pairs) and the token
66
+ // lives in `value`, which a name-only regex would miss.
67
+ const SECRET_KEY = /token|secret|password|passphrase|authorization|api[-_]?key|cookie|headers/i;
68
+
69
+ /** Redact secret-shaped keys wholesale, scrub secrets embedded in string
70
+ * values, and cap runaway strings before disk. */
71
+ function scrub(value: unknown, depth: number): unknown {
72
+ if (value === null || value === undefined) return value;
73
+ if (value instanceof Error) {
74
+ // message goes through the string branch: errors are the main carrier of
75
+ // subprocess stderr text (the exact leak class this scrubber exists for).
76
+ return {
77
+ name: value.name,
78
+ message: scrub(value.message, depth),
79
+ stack: scrub(value.stack, depth),
80
+ };
81
+ }
82
+ if (typeof value === "string") {
83
+ // Value scan first, truncate second: a cut token could lose the tail
84
+ // characters the pattern needs to match.
85
+ const clean = redactText(value);
86
+ return clean.length > MAX_STRING ? clean.slice(0, MAX_STRING) + "…(truncated)" : clean;
87
+ }
88
+ if (typeof value === "number" || typeof value === "boolean") return value;
89
+ if (depth >= MAX_DEPTH) return "(depth limit)";
90
+ if (Array.isArray(value)) return value.slice(0, 50).map((v) => scrub(v, depth + 1));
91
+ if (typeof value === "object") {
92
+ const out: Record<string, unknown> = {};
93
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
94
+ out[k] = SECRET_KEY.test(k) ? "[redacted]" : scrub(v, depth + 1);
95
+ }
96
+ return out;
97
+ }
98
+ return String(value);
99
+ }
100
+
101
+ /** Matches the truthy set used across the extension's env parsing. */
102
+ function isEnvTruthy(v: string | undefined): boolean {
103
+ return v !== undefined && ["1", "true", "on"].includes(v.toLowerCase());
104
+ }
105
+
106
+ export function createDailyLogger(opts: DailyLoggerOptions): DailyLogger {
107
+ const dir = opts.dir;
108
+ const retentionDays = opts.retentionDays ?? 14;
109
+ const verbose = opts.debug ?? isEnvTruthy(process.env.AGY_DEBUG);
110
+ const now = opts.now ?? (() => new Date());
111
+ // Serialized write chain: keeps day-rotation (mkdir + prune) ordered
112
+ // ahead of the records that triggered it. Volume is lifecycle-events
113
+ // low, so chaining costs nothing.
114
+ let chain: Promise<void> = Promise.resolve();
115
+ let ensuredDay = "";
116
+ let pruned = false;
117
+
118
+ async function prune(): Promise<void> {
119
+ if (pruned) return;
120
+ pruned = true;
121
+ const cutoff = dayKey(new Date(now().getTime() - retentionDays * 86_400_000));
122
+ const names = await readdir(dir).catch(() => [] as string[]);
123
+ for (const name of names) {
124
+ if (!name.endsWith(".ndjson")) continue;
125
+ if (name.slice(0, 10) >= cutoff) continue;
126
+ await unlink(path.join(dir, name)).catch(() => {
127
+ /* in use or gone: keep the rest */
128
+ });
129
+ }
130
+ }
131
+
132
+ function write(level: LogLevel, event: string, data: unknown): void {
133
+ const d = now();
134
+ const day = dayKey(d);
135
+ // Build the line outside the chain but guarded: scrub()/stringify run
136
+ // synchronously in log(), and a throwing getter in a future caller's
137
+ // data must not break the never-throw contract.
138
+ let line: string;
139
+ try {
140
+ const record: Record<string, unknown> = {
141
+ ts: d.toISOString(),
142
+ level,
143
+ event,
144
+ };
145
+ if (data !== undefined) record.data = scrub(data, 0);
146
+ line = JSON.stringify(record);
147
+ if (line.length > MAX_RECORD) {
148
+ record.data = `(record exceeded ${MAX_RECORD} bytes; payload dropped)`;
149
+ line = JSON.stringify(record);
150
+ }
151
+ line += "\n";
152
+ } catch {
153
+ line = `${JSON.stringify({ ts: d.toISOString(), level, event, data: "(unserializable)" })}\n`;
154
+ }
155
+ // Single chained task per record: an append failure retries ONCE inside
156
+ // the same task (day gate reset -> recursive mkdir rebuild -> append
157
+ // again). flush() therefore always waits past the retry, and a
158
+ // persistent failure costs at most two fs attempts, never a loop.
159
+ chain = chain.then(async () => {
160
+ try {
161
+ if (ensuredDay !== day) {
162
+ await mkdir(dir, { recursive: true });
163
+ ensuredDay = day;
164
+ await prune();
165
+ }
166
+ await appendFile(path.join(dir, `${day}.ndjson`), line, "utf8");
167
+ } catch {
168
+ try {
169
+ ensuredDay = "";
170
+ await mkdir(dir, { recursive: true });
171
+ ensuredDay = day;
172
+ await appendFile(path.join(dir, `${day}.ndjson`), line, "utf8");
173
+ } catch {
174
+ /* swallow: an unwritable dir must not disrupt the chat */
175
+ }
176
+ }
177
+ });
178
+ }
179
+
180
+ return {
181
+ log(event, data, level = "debug") {
182
+ // Volume gate: default installs write only errors so routine disk
183
+ // traffic is zero for regular users; the extension toasts warns
184
+ // instead. AGY_DEBUG=1 restores the full trail.
185
+ if (!verbose && level !== "error") return;
186
+ write(level, event, data);
187
+ },
188
+ flush() {
189
+ return chain.catch(() => {});
190
+ },
191
+ dir,
192
+ todayPath() {
193
+ return path.join(dir, `${dayKey(now())}.ndjson`);
194
+ },
195
+ };
196
+ }
@@ -0,0 +1,48 @@
1
+ // Process-wide FIFO lock for human-facing dialogs (confirm/editor/select).
2
+ //
3
+ // pi's interactive UI shows ONE extension dialog at a time; an overlapping
4
+ // ctx.ui.* dialog call REPLACES the live dialog and the replaced promise
5
+ // never settles, so parallel gated tool calls hang forever (or silently lose
6
+ // their prompt). Holding this lock around each dialog serializes them: the
7
+ // first renders, the rest appear in turn as each is answered.
8
+ //
9
+ // The lock is keyed via Symbol.for because ALL pi-* extensions run in the
10
+ // SAME pi process and must share one queue: a per-module lock would still let
11
+ // a dialog from one extension clobber a dialog from another in the same
12
+ // parallel tool-call batch.
13
+ const DIALOG_LOCK: unique symbol = Symbol.for("pi-me.dialog-lock");
14
+
15
+ interface DialogQueue {
16
+ tail: Promise<void>;
17
+ }
18
+
19
+ function dialogQueue(): DialogQueue {
20
+ const host = globalThis as typeof globalThis & Record<symbol, unknown>;
21
+ const existing = host[DIALOG_LOCK] as DialogQueue | undefined;
22
+ if (existing) return existing;
23
+ const created: DialogQueue = { tail: Promise.resolve() };
24
+ host[DIALOG_LOCK] = created;
25
+ return created;
26
+ }
27
+
28
+ /**
29
+ * Run `run` while holding the cross-extension dialog lock. FIFO: each caller
30
+ * chains onto the queue tail synchronously (before its first await), so call
31
+ * order is the order the dialogs appear. Released in a finally block, so one
32
+ * throwing dialog can never wedge the queue for the callers behind it.
33
+ * NOT reentrant: calling it inside a held `run` self-deadlocks.
34
+ */
35
+ export async function withDialogLock<T>(run: () => Promise<T>): Promise<T> {
36
+ const queue = dialogQueue();
37
+ const prev = queue.tail;
38
+ let release!: () => void;
39
+ queue.tail = new Promise<void>((resolve) => {
40
+ release = resolve;
41
+ });
42
+ await prev;
43
+ try {
44
+ return await run();
45
+ } finally {
46
+ release();
47
+ }
48
+ }
@@ -0,0 +1,207 @@
1
+ // G8: surface agy's file edits as a diff in pi's thinking stream.
2
+ //
3
+ // agy edits with its OWN native full-file tools (write_to_file on legacy
4
+ // builds; write_file {Path, Content} on agy 1.5.11+, both parsed by
5
+ // parseEditToolInput's field-shape regexes, not by tool name), inside a
6
+ // closed tool loop that lands changes on disk. pi's native colored diff viewer
7
+ // is unreachable for agy turns (it is part of the tool-call lifecycle, and the
8
+ // provider emits no toolCall blocks by design), so we compute a line-numbered
9
+ // diff ourselves and stream it as text through the thinking channel, reusing
10
+ // pi's own `generateDiffString` for an identical format.
11
+ //
12
+ // OLD content comes from git (the committed version), resolved PER FILE so
13
+ // nested repos / submodules / multi-repo workspaces each diff against their
14
+ // own HEAD. A turn-scoped cache makes multi-edit-same-file turns diff
15
+ // incrementally instead of cumulatively. Off-repo / untracked / binary files
16
+ // degrade to a one-line summary. See docs/PI-BRIDGE-GAPS.md (G8).
17
+
18
+ import { execFileSync } from "node:child_process";
19
+ import path from "node:path";
20
+ import { generateDiffString } from "@earendil-works/pi-coding-agent";
21
+
22
+ /** Maximum diff lines emitted for one edit before truncation. */
23
+ export const DEFAULT_MAX_DIFF_LINES = 100;
24
+
25
+ /** Injectable git operations so the pure logic is unit-testable without a
26
+ * real repo. `toplevel` returns null when the dir is not inside a git work
27
+ * tree; `showHead` returns null when the path is untracked / absent from HEAD. */
28
+ export interface GitOps {
29
+ toplevel(fileDir: string): string | null;
30
+ showHead(toplevel: string, relPath: string): string | null;
31
+ }
32
+
33
+ /** Default git ops via synchronous git CLI calls. Cheap; one process per call. */
34
+ export function createExecGitOps(): GitOps {
35
+ const run = (args: string[], cwd: string): string | null => {
36
+ try {
37
+ return execFileSync("git", args, {
38
+ cwd,
39
+ encoding: "utf-8",
40
+ stdio: ["ignore", "pipe", "ignore"],
41
+ });
42
+ } catch {
43
+ return null;
44
+ }
45
+ };
46
+ return {
47
+ toplevel: (fileDir) => {
48
+ const t = run(["rev-parse", "--show-toplevel"], fileDir);
49
+ return t ? t.trim() || null : null;
50
+ },
51
+ showHead: (toplevel, relPath) => run(["show", `HEAD:${relPath}`], toplevel),
52
+ };
53
+ }
54
+
55
+ export type EditDiffKind = "diff" | "summary" | "binary" | "none";
56
+
57
+ export interface EditDiffOutcome {
58
+ kind: EditDiffKind;
59
+ /** Text to append after the edit label in the thinking stream. Empty for
60
+ * `none` (nothing to show). */
61
+ text: string;
62
+ }
63
+
64
+ /** A parsed agy edit-tool invocation: a file path plus its full new content.
65
+ * Detected generically by key name so future agy edit-tool variants work
66
+ * without hardcoding tool names. */
67
+ export interface ParsedEdit {
68
+ /** File path as agy wrote it (absolute or cwd-relative). */
69
+ file: string;
70
+ content: string;
71
+ description?: string;
72
+ }
73
+
74
+ /** True if the string looks like binary (contains a NUL byte). Mirrors git's
75
+ * own heuristic; avoids feeding binary into the line differ. */
76
+ function isBinary(s: string): boolean {
77
+ return s.includes("\u0000");
78
+ }
79
+
80
+ /** Parse an agy tool-call inputJson into an edit if it carries both a
81
+ * file-path-like and a content-like string field. Returns null for non-edits
82
+ * (reads, greps, malformed JSON, missing fields). */
83
+ export function parseEditToolInput(inputJson: string): ParsedEdit | null {
84
+ if (!inputJson) return null;
85
+ let obj: Record<string, unknown>;
86
+ try {
87
+ obj = JSON.parse(inputJson);
88
+ } catch {
89
+ return null;
90
+ }
91
+ if (!obj || typeof obj !== "object") return null;
92
+ let file = "";
93
+ let content = "";
94
+ let description: string | undefined;
95
+ for (const [k, v] of Object.entries(obj)) {
96
+ if (typeof v !== "string") continue;
97
+ if (!file && /(^|_)?(file|path)$/i.test(k)) file = v;
98
+ else if (!content && /content|code/i.test(k)) content = v;
99
+ else if (!description && /description|toolaction|toolsummary/i.test(k)) description = v;
100
+ }
101
+ if (!file || !content) return null;
102
+ return { file, content, description };
103
+ }
104
+
105
+ /** Turn-scoped diff context. Holds the OLD-content cache (so the 2nd edit to
106
+ * the same file in a turn diffs against the 1st edit's result, not HEAD again)
107
+ * and a toplevel cache (one `rev-parse` per edited directory per turn).
108
+ * Create one fresh per turn so concurrent turns never share state. */
109
+ export class TurnDiffContext {
110
+ private readonly oldCache = new Map<string, string>();
111
+ private readonly toplevelCache = new Map<string, string | null>();
112
+ private readonly seenFiles = new Set<string>();
113
+
114
+ constructor(
115
+ private readonly git: GitOps,
116
+ private readonly maxDiffLines: number = DEFAULT_MAX_DIFF_LINES,
117
+ ) {}
118
+
119
+ /** Compute the diff (or summary) for one edit. `absFile` must be absolute. */
120
+ diffEdit(absFile: string, newContent: string): EditDiffOutcome {
121
+ // Binary short-circuit before any git work.
122
+ if (isBinary(newContent)) {
123
+ this.oldCache.set(absFile, newContent);
124
+ return { kind: "binary", text: "(binary file; diff skipped)" };
125
+ }
126
+
127
+ const dir = path.dirname(absFile);
128
+ let toplevel = this.toplevelCache.get(dir);
129
+ if (toplevel === undefined) {
130
+ toplevel = this.git.toplevel(dir);
131
+ this.toplevelCache.set(dir, toplevel);
132
+ }
133
+
134
+ // Not inside any git repo: no OLD baseline available without a pre-turn
135
+ // snapshot (approach C, deferred). Degrade to a one-line summary.
136
+ if (!toplevel) {
137
+ this.oldCache.set(absFile, newContent);
138
+ return {
139
+ kind: "summary",
140
+ text: `(${countLines(newContent)} lines; not in a git repo, no diff)`,
141
+ };
142
+ }
143
+
144
+ const relPath = path.relative(toplevel, absFile);
145
+ // File lives outside its resolved repo (e.g. agy edited something under a
146
+ // sibling tree). Treat like off-repo: summary, no diff.
147
+ if (relPath.startsWith("..")) {
148
+ this.oldCache.set(absFile, newContent);
149
+ return {
150
+ kind: "summary",
151
+ text: `(${countLines(newContent)} lines; outside the git repo, no diff)`,
152
+ };
153
+ }
154
+
155
+ // OLD baseline: the prior edit's result if we've seen this file this
156
+ // turn, else the committed version (untracked/new file -> empty string).
157
+ let oldContent: string;
158
+ if (this.seenFiles.has(absFile) && this.oldCache.has(absFile)) {
159
+ oldContent = this.oldCache.get(absFile) ?? "";
160
+ } else {
161
+ const committed = this.git.showHead(toplevel, relPath);
162
+ oldContent = committed ?? "";
163
+ }
164
+ this.seenFiles.add(absFile);
165
+ this.oldCache.set(absFile, newContent);
166
+
167
+ if (isBinary(oldContent)) {
168
+ return { kind: "binary", text: "(was binary; diff skipped)" };
169
+ }
170
+ if (oldContent === newContent) {
171
+ return { kind: "none", text: "" };
172
+ }
173
+
174
+ const { diff } = generateDiffString(oldContent, newContent);
175
+ return { kind: "diff", text: capLines(diff, this.maxDiffLines) };
176
+ }
177
+ }
178
+
179
+ function countLines(s: string): number {
180
+ if (s.length === 0) return 0;
181
+ return s.split("\n").length;
182
+ }
183
+
184
+ /** Truncate a diff to at most `max` lines, keeping the head and noting how many
185
+ * were dropped. A diff's changes are interspersed, so head-first is fine. */
186
+ function capLines(diff: string, max: number): string {
187
+ if (max <= 0) return diff;
188
+ const lines = diff.split("\n");
189
+ if (lines.length <= max) return diff;
190
+ const dropped = lines.length - max;
191
+ return `${lines.slice(0, max).join("\n")}\n[... ${dropped} more diff lines]`;
192
+ }
193
+
194
+ /** Format an in-memory before/after pair as a line-numbered diff with pi's
195
+ * own generateDiffString. No git subprocess: the ACP engine supplies
196
+ * oldText/newText directly in tool_call content[] (Gate C), so the provider
197
+ * renders the native diff without touching the repo. Exported for the
198
+ * provider; TurnDiffContext keeps the git-sourced path for stream-json. */
199
+ export function formatInlineDiff(
200
+ oldContent: string,
201
+ newContent: string,
202
+ maxDiffLines: number = DEFAULT_MAX_DIFF_LINES,
203
+ ): string {
204
+ if (oldContent === newContent) return "";
205
+ const { diff } = generateDiffString(oldContent, newContent);
206
+ return capLines(diff, maxDiffLines);
207
+ }
@@ -0,0 +1,168 @@
1
+ // Engine-agnostic turn-driver contract.
2
+ //
3
+ // Both turn engines (stream-json driver in `driver.ts`, ACP driver in
4
+ // `acp/driver.ts`) implement `TurnDriver`, and everything above them — the
5
+ // provider's stream loop, the G9 round-trip store, the extension wiring —
6
+ // depends on this interface only. Types live here so the stream module can be
7
+ // deleted (phase 4) without breaking imports.
8
+ //
9
+ // The ACP driver implements the same surface with protocol-native mechanics:
10
+ // no process recycle on profile drift, notification cancel with teardown
11
+ // fallback, and `session/load` resume. See docs/ACP-ADOPTION-PLAN.md section 9.
12
+
13
+ export type DriverState = "idle" | "starting" | "ready" | "running" | "dead";
14
+
15
+ export interface DriverProfile {
16
+ cwd: string;
17
+ model: string;
18
+ effort?: string;
19
+ mode: string;
20
+ skipPermissions: boolean;
21
+ /** Custom agy agent (stream-json `--agent`). ACP has no agent slot in the
22
+ * per-turn agent selection and ignores it; the /agy agent command refuses to set
23
+ * one while the ACP engine is active. */
24
+ agent?: string;
25
+ }
26
+
27
+ export interface DriverTurnRequest extends DriverProfile {
28
+ /** Existing conversation/session to resume. Stream-json: agy conversation id via
29
+ * `--conversation`. ACP: sessionId via `session/load` (falls back to
30
+ * `session/new` when the server no longer knows it). */
31
+ conversationId?: string | null;
32
+ prompt: string;
33
+ /** Image blocks riding with the prompt. ACP forwards them as typed
34
+ * content blocks (probe 2026-09-03: 64x64 two-tone PNG answered
35
+ * correctly); on stream-json the provider stages them to files, so the
36
+ * driver itself ignores this field. */
37
+ images?: Array<{ data: string; mimeType: string }>;
38
+ /** ACP only: pi-side context delivered as a native `embeddedContext`
39
+ * resource block instead of inline prompt text (G1 on ACP). Stream-json
40
+ * embeds the digest in the prompt string and ignores this. */
41
+ contextBlock?: { uri: string; text: string };
42
+ signal?: AbortSignal;
43
+ /** Overall turn cap in minutes (default 10). Fractional values are valid
44
+ * (tests use sub-minute caps). 0 disables the cap. */
45
+ timeoutMin?: number;
46
+ /** Stdout-inactivity cap in minutes (default 5). 0 disables the cap. */
47
+ inactivityMin?: number;
48
+ }
49
+
50
+ export type AgyUsage = {
51
+ input_tokens?: number;
52
+ output_tokens?: number;
53
+ thinking_tokens?: number;
54
+ cache_read_tokens?: number;
55
+ total_tokens?: number;
56
+ };
57
+
58
+ export type DriverActivity =
59
+ | { type: "text"; delta: string }
60
+ /** Stream-json emits a token count only; ACP carries the actual thought text in
61
+ * `delta`. The provider renders whichever is present. */
62
+ | { type: "thought"; tokens?: number; delta?: string }
63
+ | { type: "tool_start"; stepId?: number; name: string; args: Record<string, unknown>; mcpServer?: string; /** ACP only: the protocol toolCallId (stream-json carries numeric stepId instead). */ toolCallId?: string }
64
+ | {
65
+ type: "tool_done";
66
+ stepId?: number;
67
+ name: string;
68
+ args: Record<string, unknown>;
69
+ mcpServer?: string;
70
+ /** ACP only: the protocol toolCallId; pairs done/error with their start. */
71
+ toolCallId?: string;
72
+ output?: string;
73
+ durationSeconds?: number;
74
+ /** ACP only: the server's native edit diff from `tool_call`
75
+ * content[] ({type:"diff", path, oldText?, newText}). Stream-json never
76
+ * sets it; the provider renders it without any git subprocess. */
77
+ diff?: { path: string; oldText?: string; newText: string };
78
+ }
79
+ | { type: "tool_error"; stepId?: number; name: string; message: string; mcpServer?: string; toolCallId?: string }
80
+ | { type: "usage"; usage: AgyUsage }
81
+ /** Synthetic: injected by the provider when the MCP bridge receives a call
82
+ * (G9). Parks the turn: output is expected to stall while pi executes the
83
+ * tool, so the driver suspends its idle/overall timers. */
84
+ | { type: "bridge_call"; callId: string; name: string; args: Record<string, unknown> };
85
+
86
+ export interface TurnOutcome {
87
+ conversationId?: string;
88
+ status: "OK" | "ERROR" | "UNKNOWN";
89
+ response: string;
90
+ error?: string;
91
+ usage?: AgyUsage;
92
+ finished: boolean;
93
+ aborted: boolean;
94
+ /** The model demonstrably produced output this turn: an agent_response
95
+ * or tool step was observed, or the settled response/usage is non-empty.
96
+ * Stream-json sets it on every outcome; ACP leaves it undefined.
97
+ * false + status OK is agy's silent over-cap drop signature (issue #2:
98
+ * prompts past ~25KB are discarded with SUCCESS, no error). */
99
+ modelOutputSeen?: boolean;
100
+ /** Stream-json only: a result frame arrived for this turn. Undefined on
101
+ * ACP. A deadline kill or process exit before the result frame means the
102
+ * turn never committed. */
103
+ sawResult?: boolean;
104
+ /** Stream-json only: the turn ended via the overall/inactivity deadline
105
+ * guard (not a user abort, not a process crash). With sawResult false on
106
+ * a resumed conversation this marks the conversation as poisoned. */
107
+ deadline?: "timeout" | "stall";
108
+ }
109
+
110
+ export interface TurnHandle {
111
+ id: string;
112
+ /** Resolves when the turn settles (result event, exit, abort, recycle). */
113
+ outcome: Promise<TurnOutcome>;
114
+ /** Pull the next activity. Resolves null once the activity stream closes. */
115
+ next(): Promise<DriverActivity | null>;
116
+ /** Inject a synthetic activity (bridge inbox). No-op after settle. */
117
+ pushExternal(activity: DriverActivity): void;
118
+ }
119
+
120
+ export interface DriverSnapshot {
121
+ state: DriverState;
122
+ pid?: number;
123
+ conversationId?: string;
124
+ stats: {
125
+ spawns: number;
126
+ turns: number;
127
+ reused: number;
128
+ recycles: number;
129
+ lastRecycleReason?: string;
130
+ recycleReasons: Record<string, number>;
131
+ };
132
+ lifecycle: string[];
133
+ /** Present on ACP snapshots; absent on stream-json. */
134
+ engine?: "acp";
135
+ acp?: {
136
+ sessionId?: string;
137
+ prompts: number;
138
+ sessionsCreated: number;
139
+ sessionsLoaded: number;
140
+ kills: number;
141
+ serverVersion?: string;
142
+ /** Connections beyond the first this driver process made = server
143
+ * restarts (Gate D kills + stale-exit replacements). */
144
+ reconnects: number;
145
+ /** From the initialize handshake agentInfo block. */
146
+ agentName?: string;
147
+ agentTitle?: string;
148
+ /** Gate B watch: true once this server process sent usage/token fields
149
+ * in any session/update frame. /agy doctor surfaces it when true and
150
+ * stays silent otherwise. */
151
+ usageSeen: boolean;
152
+ };
153
+ }
154
+
155
+ /** The engine contract. Everything above the driver depends on this interface
156
+ * only; `StreamDriver` and `AcpDriver` both implement it. */
157
+ export interface TurnDriver {
158
+ readonly state: DriverState;
159
+ readonly activeHandle: TurnHandle | null;
160
+ run(request: DriverTurnRequest): Promise<TurnHandle>;
161
+ /** Re-attach to the active turn (pi toolUse continuation). */
162
+ reentry(): TurnHandle | null;
163
+ /** Resume turn timers after a parked G9 round-trip settles. */
164
+ kickIdle(): void;
165
+ set onTurnEnd(fn: ((outcome: TurnOutcome) => void) | undefined);
166
+ snapshot(): DriverSnapshot;
167
+ close(reason: "recycle" | "shutdown", cause?: string): Promise<void>;
168
+ }