@herbertgao/pi-extensions 2026.11.17 → 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 (159) hide show
  1. package/CHANGELOG.md +25 -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 +12 -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/extensions/renderer/index.ts +7 -0
  64. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/agent-badge.ts +244 -0
  65. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +1 -1
  66. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +10 -3
  67. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +18 -0
  68. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  69. package/node_modules/@herbertgao/pi-inline-skill-commands/README.md +18 -0
  70. package/node_modules/@herbertgao/pi-inline-skill-commands/package.json +1 -1
  71. package/node_modules/@herbertgao/pi-inline-skill-commands/src/index.ts +80 -0
  72. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +320 -102
  73. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  74. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -30
  75. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  76. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  77. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  78. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  80. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +27 -13
  82. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  84. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +217 -41
  85. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  86. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  87. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -93
  88. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  89. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  90. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  91. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  92. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  93. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  94. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  95. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  96. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  97. package/node_modules/pi-commandcode-provider/README.md +3 -2
  98. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  99. package/node_modules/pi-commandcode-provider/package.json +4 -3
  100. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  101. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  102. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  103. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  104. package/package.json +12 -15
  105. package/node_modules/pi-antigravity/README.md +0 -298
  106. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  107. package/node_modules/pi-antigravity/package.json +0 -87
  108. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  109. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  110. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  111. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  112. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  113. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  114. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  115. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  116. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  117. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  118. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  119. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  120. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  121. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  122. package/node_modules/pi-antigravity/src/index.ts +0 -547
  123. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  124. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  125. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  126. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  127. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  128. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  129. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  130. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  131. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  132. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  133. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  134. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  135. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  136. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  137. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  138. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  139. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  140. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  141. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  142. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  143. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  144. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  145. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  146. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  147. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  148. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  149. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  150. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  151. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  152. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  153. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  154. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  155. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  156. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  157. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  158. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  159. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -0,0 +1,152 @@
1
+ // Settings manager for Antigravity's "Queued Messages" delivery strategy.
2
+ //
3
+ // In agy v1.2.14+, agy introduced the "Queued Messages" option:
4
+ // - "queue" (agy default): hold follow-up / steering messages until current turn ends
5
+ // - "send-immediately": interrupt the agent with follow-up / steering messages immediately
6
+ //
7
+ // Pi expects immediate message delivery / steering during interactive chat.
8
+ // Both engines share ~/.gemini/antigravity-cli/settings.json. Keep immediate
9
+ // steering as the default without changing an explicit user choice.
10
+
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+
15
+ export const QUEUED_MESSAGES_SEND_IMMEDIATELY = "send-immediately";
16
+
17
+ export function defaultCliSettingsPath(): string {
18
+ return path.join(os.homedir(), ".gemini", "antigravity-cli", "settings.json");
19
+ }
20
+
21
+ export interface EnsureFileResult {
22
+ path: string;
23
+ updated: boolean;
24
+ value: string;
25
+ error?: string;
26
+ }
27
+
28
+ export interface EnsureFileOptions {
29
+ defaultValue?: string;
30
+ onlyIfDirExists?: boolean;
31
+ }
32
+
33
+ /**
34
+ * Ensure `queuedMessages` is present in the specified settings.json file.
35
+ * If unset or empty, writes `send-immediately`.
36
+ *
37
+ * Safety guards:
38
+ * - If the file exists but has invalid JSON or is not an object, does NOT clobber; returns updated: false.
39
+ * - If the file already specifies a non-empty `queuedMessages`, leaves it untouched.
40
+ * - Resolves symlinks before writing to protect dotfiles managers.
41
+ * - Writes via temp file and atomic rename.
42
+ * - Traps any I/O exceptions so callers never crash on read-only or permission-denied files.
43
+ */
44
+ export function ensureQueuedMessagesInFile(
45
+ filePath: string,
46
+ opts: EnsureFileOptions | string = {},
47
+ ): EnsureFileResult {
48
+ const options: EnsureFileOptions =
49
+ typeof opts === "string" ? { defaultValue: opts } : opts;
50
+ const defaultValue = options.defaultValue ?? QUEUED_MESSAGES_SEND_IMMEDIATELY;
51
+ const onlyIfDirExists = options.onlyIfDirExists ?? false;
52
+
53
+ let resolvedPath = filePath;
54
+ try {
55
+ if (fs.existsSync(filePath)) {
56
+ resolvedPath = fs.realpathSync(filePath);
57
+ }
58
+ } catch {
59
+ // Keep original path if realpath fails
60
+ }
61
+
62
+ const dir = path.dirname(resolvedPath);
63
+ if (onlyIfDirExists && !fs.existsSync(dir)) {
64
+ return { path: resolvedPath, updated: false, value: "" };
65
+ }
66
+
67
+ let settings: Record<string, unknown> = {};
68
+ let fileExists = false;
69
+
70
+ try {
71
+ const raw = fs.readFileSync(resolvedPath, "utf8");
72
+ fileExists = true;
73
+ let parsed: unknown;
74
+ try {
75
+ parsed = JSON.parse(raw);
76
+ } catch (parseErr) {
77
+ // Malformed JSON: do NOT clobber the user's file.
78
+ return {
79
+ path: resolvedPath,
80
+ updated: false,
81
+ value: "",
82
+ error: `malformed JSON in ${resolvedPath}: ${String(parseErr)}`,
83
+ };
84
+ }
85
+
86
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
87
+ return {
88
+ path: resolvedPath,
89
+ updated: false,
90
+ value: "",
91
+ error: `settings in ${resolvedPath} is not a JSON object`,
92
+ };
93
+ }
94
+ settings = parsed as Record<string, unknown>;
95
+ } catch (err: unknown) {
96
+ const code = (err as { code?: string })?.code;
97
+ if (code !== "ENOENT") {
98
+ // Read error other than absent file (e.g. EACCES): do not overwrite.
99
+ return {
100
+ path: resolvedPath,
101
+ updated: false,
102
+ value: "",
103
+ error: `failed reading ${resolvedPath}: ${String(err)}`,
104
+ };
105
+ }
106
+ }
107
+
108
+ const current = settings.queuedMessages;
109
+ if (typeof current === "string" && current.trim().length > 0) {
110
+ return { path: resolvedPath, updated: false, value: current };
111
+ }
112
+
113
+ settings.queuedMessages = defaultValue;
114
+
115
+ let tmpPath = "";
116
+ try {
117
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
118
+ tmpPath = path.join(dir, `.${path.basename(resolvedPath)}.${process.pid}.${Date.now()}.tmp`);
119
+ fs.writeFileSync(tmpPath, `${JSON.stringify(settings, null, 2)}\n`, { mode: 0o600 });
120
+ fs.renameSync(tmpPath, resolvedPath);
121
+ return { path: resolvedPath, updated: true, value: defaultValue };
122
+ } catch (err) {
123
+ if (tmpPath) {
124
+ try {
125
+ fs.unlinkSync(tmpPath);
126
+ } catch {
127
+ /* ignore */
128
+ }
129
+ }
130
+ return {
131
+ path: resolvedPath,
132
+ updated: false,
133
+ value: "",
134
+ error: `failed writing ${resolvedPath}: ${String(err)}`,
135
+ };
136
+ }
137
+ }
138
+
139
+ export interface EnsureQueuedMessagesOptions {
140
+ cliSettingsPath?: string;
141
+ defaultValue?: string;
142
+ onlyIfDirExists?: boolean;
143
+ }
144
+
145
+ export function ensureQueuedMessagesDefaults(
146
+ opts: EnsureQueuedMessagesOptions = {},
147
+ ): EnsureFileResult {
148
+ return ensureQueuedMessagesInFile(opts.cliSettingsPath ?? defaultCliSettingsPath(), {
149
+ defaultValue: opts.defaultValue ?? QUEUED_MESSAGES_SEND_IMMEDIATELY,
150
+ onlyIfDirExists: opts.onlyIfDirExists ?? false,
151
+ });
152
+ }
@@ -0,0 +1,40 @@
1
+ // Quota-exhaustion notice detection (issue #16). agy streams the account's
2
+ // quota notice as plain agent text and ends the turn with end_turn, so the
3
+ // provider reclassifies the settled response into a pi error instead of a
4
+ // successful reply.
5
+ //
6
+ // The pi-side errorMessage wording is load-bearing: pi-ai's
7
+ // isRetryableAssistantError gates provider failover and classifies
8
+ // "quota exceeded" / "billing" wording as fail-fast (no router handoff), so
9
+ // the message must carry a retryable marker ("rate limit") while staying
10
+ // clear of every non-retryable pattern. The raw upstream notice is never
11
+ // echoed, so upstream copy drift cannot poison the classification.
12
+
13
+ /** Reset interval parsed from the notice, e.g. "153h38m14s". */
14
+ export interface QuotaNotice {
15
+ resetsIn?: string;
16
+ }
17
+
18
+ // Anchored at the start and length-capped so only a notice-shaped
19
+ // (near-)whole response reclassifies; a long answer that merely discusses
20
+ // quota must never match.
21
+ const NOTICE_PATTERN = /^\s*(?:⚠\s*)?(?:[a-z]+\s+)?quota\s+(?:reached|exhausted|exceeded|limit reached)/i;
22
+ const RESET_PATTERN = /resets?\s+in\s+((?:\d+h)?(?:\d+m)?(?:\d+s))/i;
23
+ const NOTICE_MAX_CHARS = 400;
24
+
25
+ /** Classify a settled driver response as a quota-exhaustion notice.
26
+ * Conservative by design: false negatives keep a normal reply, false
27
+ * positives would turn real answers into errors. */
28
+ export function detectQuotaNotice(response: string): QuotaNotice | undefined {
29
+ const trimmed = response.trim();
30
+ if (trimmed.length === 0 || trimmed.length > NOTICE_MAX_CHARS) return undefined;
31
+ if (!NOTICE_PATTERN.test(trimmed)) return undefined;
32
+ const resetsIn = RESET_PATTERN.exec(trimmed)?.[1];
33
+ return resetsIn ? { resetsIn } : {};
34
+ }
35
+
36
+ /** Retryable-classified pi errorMessage for a detected notice. */
37
+ export function quotaErrorMessage(notice: QuotaNotice): string {
38
+ const reset = notice.resetsIn ? `; resets in ${notice.resetsIn}` : "";
39
+ return `agy rate limit (ResourceExhausted): Antigravity quota exhausted${reset}`;
40
+ }
@@ -0,0 +1,27 @@
1
+ // Secret redaction for free text: stderr tails, error messages, log string
2
+ // values. Patterns ported from pi-antigravity-acp-provider's errors.redact
3
+ // (MIT). No length cap here on purpose: callers already bound their own
4
+ // output sizes (8192 stderr tails, MAX_STRING truncation), and a cap inside
5
+ // this function would silently shorten their output.
6
+
7
+ const SECRET_PATTERNS: Array<[RegExp, string]> = [
8
+ // API-key prefixes: Google (AIza), OpenAI-style (sk-), npm, GitHub. The
9
+ // left word-boundary stops mid-word matches ("desk-123456789012").
10
+ [/\b(?:AIza|sk-|npm_|gh[opurs]_)[A-Za-z0-9_-]{12,}/gu, "<redacted>"],
11
+ // Google OAuth tokens (access ya29., refresh 1//).
12
+ [/\b(?:ya29\.|1\/\/)[A-Za-z0-9._~+/-]{12,}/gu, "<redacted>"],
13
+ // Credential header values; the key text stays (useful context).
14
+ [/((?:authorization|cookie|set-cookie)\s*[:=]\s*(?:bearer\s+)?)[^\s,;]+/giu, "$1<redacted>"],
15
+ // Token-ish JSON fields; the key stays.
16
+ [
17
+ /((?:["']?(?:access_token|refresh_token|id_token|client_secret|api[-_]?key)["']?)\s*[:=]\s*["']?)[^"'\s,;&}]+/giu,
18
+ "$1<redacted>",
19
+ ],
20
+ ];
21
+
22
+ /** Replace secret-shaped material with `<redacted>`, preserving structure. */
23
+ export function redactText(text: string): string {
24
+ let out = text;
25
+ for (const [pattern, replacement] of SECRET_PATTERNS) out = out.replace(pattern, replacement);
26
+ return out;
27
+ }
@@ -0,0 +1,197 @@
1
+ // Persisted map: pi session key -> agy conversation id + last streamed step.
2
+ //
3
+ // agy holds its own conversation history in the DB keyed by conversation id.
4
+ // To resume a multi-turn pi conversation, we thread the same agy id across
5
+ // streamSimple calls and skip steps we already streamed last turn.
6
+ //
7
+ // The key is options.sessionId when pi provides it, else the cwd (single-
8
+ // conversation-per-process fallback). Stored at
9
+ // <agentDir>/antigravity-bridge/sessions.json with atomic rename.
10
+
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { bridgeDir } from "./config.js";
14
+
15
+ function defaultStorePath(): string {
16
+ return path.join(bridgeDir(), "sessions.json");
17
+ }
18
+
19
+ export interface AgySession {
20
+ conversationId: string;
21
+ lastStepIdx: number;
22
+ /** pi context.messages length captured at the start of the last agy turn.
23
+ * Used by the provider to compute a delta digest of pi-side context agy
24
+ * was not spawned for (compaction summaries, other-provider turns). 0 on a
25
+ * fresh or pre-watermark session. Optional for backward compat with older
26
+ * persisted sessions that predate the watermark. */
27
+ lastMessageCount?: number;
28
+ /** role:timestamp fingerprint of messages[lastMessageCount - 1] at write
29
+ * time. The provider compares it against the live boundary message: a
30
+ * mismatch (branch, fork, context-hook rewrite) resets the digest window
31
+ * to the full delta. Optional: absent on records predating the
32
+ * fingerprint, which the provider treats as a mismatch. */
33
+ digestBoundary?: string;
34
+ /** Compaction index already delivered in a previous digest, so the
35
+ * builder neither re-injects that summary nor restarts its window on
36
+ * it. Optional/absent when no compaction existed at write time. */
37
+ digestSummaryId?: string;
38
+ }
39
+
40
+ type StoreMap = Record<string, AgySession>;
41
+
42
+ /** Narrow untrusted parsed JSON into a clean StoreMap, validating each entry's
43
+ * shape instead of trusting the whole structure (the cast previously let a
44
+ * hand-edited or corrupt file plant wrong-typed fields into the cache).
45
+ * Drops any entry whose `conversationId` isn't a string; falls back to -1 when
46
+ * `lastStepIdx` is missing or not a finite number. Returns {} for non-object
47
+ * input. */
48
+ function narrowStoreMap(parsed: unknown): StoreMap {
49
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
50
+ const clean: StoreMap = {};
51
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
52
+ if (!value || typeof value !== "object") continue;
53
+ const conversationId = (value as { conversationId?: unknown }).conversationId;
54
+ if (typeof conversationId !== "string") continue;
55
+ const idx = (value as { lastStepIdx?: unknown }).lastStepIdx;
56
+ const mc = (value as { lastMessageCount?: unknown }).lastMessageCount;
57
+ const db = (value as { digestBoundary?: unknown }).digestBoundary;
58
+ const dci = (value as { digestSummaryId?: unknown }).digestSummaryId;
59
+ clean[key] = {
60
+ conversationId,
61
+ lastStepIdx: typeof idx === "number" && Number.isFinite(idx) ? idx : -1,
62
+ lastMessageCount: typeof mc === "number" && Number.isFinite(mc) ? mc : 0,
63
+ ...(typeof db === "string" ? { digestBoundary: db } : {}),
64
+ ...(typeof dci === "string" ? { digestSummaryId: dci } : {}),
65
+ };
66
+ }
67
+ return clean;
68
+ }
69
+
70
+ /** Atomic-write JSON session store. Writes are serialized through a promise
71
+ * chain so two concurrent turns can't interleave renames.
72
+ *
73
+ * Multi-process safety: persist() re-reads the file fresh and overlays only
74
+ * the keys this instance has dirtied since load, so two pi processes editing
75
+ * different sessions never clobber each other. (Whole-file overwrite from a
76
+ * stale in-memory snapshot was the previous behavior - last writer won.) */
77
+ export class SessionStore {
78
+ private readonly path: string;
79
+ private cache: StoreMap = {};
80
+ private readonly dirty = new Set<string>();
81
+ private readonly removed = new Set<string>();
82
+ private writeChain: Promise<void> = Promise.resolve();
83
+
84
+ constructor(storePath: string = defaultStorePath()) {
85
+ this.path = storePath;
86
+ this.load();
87
+ }
88
+
89
+ private load(): void {
90
+ try {
91
+ const raw = fs.readFileSync(this.path, "utf8");
92
+ this.cache = narrowStoreMap(JSON.parse(raw));
93
+ } catch {
94
+ // missing or corrupt - start empty. The first set() will create it.
95
+ this.cache = {};
96
+ }
97
+ }
98
+
99
+ get(key: string): AgySession | null {
100
+ const s = this.cache[key];
101
+ if (!s || typeof s.conversationId !== "string") return null;
102
+ return {
103
+ conversationId: s.conversationId,
104
+ lastStepIdx: s.lastStepIdx ?? -1,
105
+ lastMessageCount: s.lastMessageCount ?? 0,
106
+ ...(s.digestBoundary !== undefined ? { digestBoundary: s.digestBoundary } : {}),
107
+ ...(s.digestSummaryId !== undefined ? { digestSummaryId: s.digestSummaryId } : {}),
108
+ };
109
+ }
110
+
111
+ /** Update one session and persist atomically (temp file + rename). The
112
+ * write is queued; callers don't need to await it. */
113
+ set(key: string, session: AgySession): void {
114
+ this.cache[key] = session;
115
+ this.dirty.add(key);
116
+ this.removed.delete(key);
117
+ // Serialize through a chain so concurrent sets don't interleave renames.
118
+ this.writeChain = this.writeChain
119
+ .then(() => this.persist())
120
+ .catch(() => {
121
+ /* swallow; next set() retries */
122
+ });
123
+ }
124
+
125
+ /** Drop one session binding and persist the deletion. Used when the driver
126
+ * recreated the conversation under us: the record's watermark claims
127
+ * history the new conversation never saw, and its bound id keeps the
128
+ * sysPrompt gate closed. Dropping resets the watermark to 0 AND re-arms
129
+ * the gate on the next turn (issue #1). The write is queued. */
130
+ delete(key: string): void {
131
+ delete this.cache[key];
132
+ this.dirty.delete(key);
133
+ this.removed.add(key);
134
+ this.writeChain = this.writeChain
135
+ .then(() => this.persist())
136
+ .catch(() => {
137
+ /* swallow; next write retries */
138
+ });
139
+ }
140
+
141
+ private async persist(): Promise<void> {
142
+ const dir = path.dirname(this.path);
143
+ await fs.promises.mkdir(dir, { recursive: true });
144
+
145
+ // Re-read the current file so we merge against the latest on-disk state,
146
+ // not our possibly-stale in-memory snapshot. Overlay only OUR dirty keys
147
+ // so a concurrent process's writes to other keys survive.
148
+ let disk: StoreMap = {};
149
+ try {
150
+ const raw = await fs.promises.readFile(this.path, "utf8");
151
+ disk = narrowStoreMap(JSON.parse(raw));
152
+ } catch {
153
+ /* missing or corrupt - start from empty */
154
+ }
155
+ const merged: StoreMap = { ...disk };
156
+ for (const key of this.dirty) {
157
+ merged[key] = this.cache[key];
158
+ }
159
+ for (const key of this.removed) {
160
+ delete merged[key];
161
+ }
162
+
163
+ const tmp = `${this.path}.${process.pid}.tmp`;
164
+ await fs.promises.writeFile(tmp, JSON.stringify(merged, null, 2) + "\n", {
165
+ mode: 0o600,
166
+ });
167
+ await fs.promises.rename(tmp, this.path);
168
+ this.dirty.clear();
169
+ // Mirror dirty: once the deletion is durable, stop re-asserting it. A
170
+ // later unrelated persist must not destroy a record another process
171
+ // wrote for that key after our delete landed.
172
+ this.removed.clear();
173
+ }
174
+
175
+ /** Wipe all session bindings (forces fresh agy conversations on every
176
+ * active session). Used by the /agy clear command. */
177
+ clear(): void {
178
+ this.cache = {};
179
+ this.dirty.clear();
180
+ this.removed.clear();
181
+ this.writeChain = this.writeChain
182
+ .then(async () => {
183
+ const tmp = `${this.path}.${process.pid}.tmp`;
184
+ await fs.promises.mkdir(path.dirname(this.path), { recursive: true });
185
+ await fs.promises.writeFile(tmp, "{}\n", { mode: 0o600 });
186
+ await fs.promises.rename(tmp, this.path);
187
+ })
188
+ .catch(() => {
189
+ /* swallow; user can retry */
190
+ });
191
+ }
192
+
193
+ /** Count persisted session bindings (for status display). */
194
+ get size(): number {
195
+ return Object.keys(this.cache).length;
196
+ }
197
+ }
@@ -0,0 +1,207 @@
1
+ // pi Agent Skills catalog + activate_skill bridge.
2
+ //
3
+ // The MCP bridge exposes ONE `activate_skill` tool to agy whose JSON-schema
4
+ // enum is the catalog; the description carries each skill's one-liner so agy
5
+ // can tell when a skill applies. Calling it returns the full SKILL.md plus the
6
+ // bundled resource dir. Nothing is appended to the prompt: agy sees the
7
+ // catalog in tools/list on every spawn, including after pi compaction.
8
+
9
+ import fs from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
13
+
14
+ export const ACTIVATE_SKILL_TOOL_NAME = "activate_skill";
15
+
16
+ export interface SkillLite {
17
+ name: string;
18
+ description: string;
19
+ /** Absolute path to SKILL.md. */
20
+ filePath: string;
21
+ /** Absolute directory containing SKILL.md and bundled resources. */
22
+ dir: string;
23
+ }
24
+
25
+ /** Parse `name:` / `description:` out of SKILL.md frontmatter. Deliberately
26
+ * line-based, not YAML: multi-line block scalars (`description: >-`) keep
27
+ * only their first line. */
28
+ function parseFrontmatter(raw: string): { name?: string; description?: string } {
29
+ const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
30
+ if (!m) return {};
31
+ const out: { name?: string; description?: string } = {};
32
+ for (const line of m[1].split(/\r?\n/)) {
33
+ const name = line.match(/^name:\s*(.+)$/);
34
+ if (name && !out.name) out.name = name[1].trim();
35
+ const desc = line.match(/^description:\s*(.+)$/);
36
+ if (desc && !out.description) out.description = desc[1].trim();
37
+ }
38
+ return out;
39
+ }
40
+
41
+ // The rest of this module mirrors pi's own skill discovery (pi docs
42
+ // "docs/skills.md - Locations") so the bridge's activate_skill catalog
43
+ // matches the [Skills] list pi shows in its system prompt:
44
+ //
45
+ // - Global: <agentDir>/skills (pi style) and ~/.agents/skills (agents style,
46
+ // the cross-harness standard).
47
+ // - Project: <project>/.pi/skills (pi style; CONFIG_DIR_NAME, so rebranded
48
+ // distros relocate it) and .agents/skills in cwd + ancestors up
49
+ // to the git repo root (agents style).
50
+ // - Both styles discover every directory holding a SKILL.md, recursively;
51
+ // grouping folders (no SKILL.md) are descended into and a skill's contents
52
+ // are freeform (no descent past its SKILL.md).
53
+ // - pi style also treats root .md files as individual skills; agents style
54
+ // ignores root .md but picks up frontmatter .md files inside grouping
55
+ // folders.
56
+ // - Skills without a description are not loaded (same as pi).
57
+ // - Name collisions keep the first skill found, pi global dirs before
58
+ // project dirs.
59
+
60
+ export type SkillStyle = "pi" | "agents";
61
+
62
+ export interface SkillLocation {
63
+ dir: string;
64
+ style: SkillStyle;
65
+ }
66
+
67
+ const MAX_DEPTH = 16; // symlink-loop insurance; real catalogs nest 1-2 levels
68
+
69
+ export interface SkillScanOptions {
70
+ /** Project root: adds the project pi-skills dir and ancestor .agents/skills
71
+ * dirs (walked up to the git root). */
72
+ projectDir?: string;
73
+ /** HOME override for the cross-harness ~/.agents/skills dir (tests). */
74
+ home?: string;
75
+ /** pi agent dir override for pi's user skills dir (tests). */
76
+ agentDir?: string;
77
+ }
78
+
79
+ /** Ordered skill locations for a session, mirroring pi's own loader:
80
+ * <agentDir>/skills, then cross-harness ~/.agents/skills; with a projectDir
81
+ * also <project>/<CONFIG_DIR_NAME>/skills and each ancestor's .agents/skills. */
82
+ export function skillLocations(opts: SkillScanOptions = {}): SkillLocation[] {
83
+ const home = opts.home ?? os.homedir();
84
+ const agentDir = opts.agentDir ?? getAgentDir();
85
+ const out: SkillLocation[] = [
86
+ { dir: path.join(agentDir, "skills"), style: "pi" },
87
+ { dir: path.join(home, ".agents", "skills"), style: "agents" },
88
+ ];
89
+ if (!opts.projectDir) return out;
90
+ out.push({ dir: path.join(opts.projectDir, CONFIG_DIR_NAME, "skills"), style: "pi" });
91
+ let dir = path.resolve(opts.projectDir);
92
+ for (;;) {
93
+ out.push({ dir: path.join(dir, ".agents", "skills"), style: "agents" });
94
+ if (path.dirname(dir) === dir || fs.existsSync(path.join(dir, ".git"))) break;
95
+ dir = path.dirname(dir);
96
+ }
97
+ return out;
98
+ }
99
+
100
+ function readSkillFile(file: string, fallbackName: string): SkillLite | null {
101
+ let raw = "";
102
+ try {
103
+ // Strip a UTF-8 BOM so editors that add one do not break the `---` anchor.
104
+ raw = fs.readFileSync(file, "utf8").replace(/^\uFEFF/, "");
105
+ } catch {
106
+ return null;
107
+ }
108
+ const fm = parseFrontmatter(raw);
109
+ const description = (fm.description ?? "").trim();
110
+ // pi does not load skills without a description.
111
+ if (!description) return null;
112
+ return {
113
+ name: fm.name?.trim() || fallbackName,
114
+ description: description.replace(/\s+/g, " ").slice(0, 160),
115
+ filePath: file,
116
+ dir: path.dirname(file),
117
+ };
118
+ }
119
+
120
+ function scanLocation(loc: SkillLocation): SkillLite[] {
121
+ const walk = (dir: string, depth: number): SkillLite[] => {
122
+ if (depth > MAX_DEPTH) return [];
123
+ let entries: fs.Dirent[];
124
+ try {
125
+ entries = fs.readdirSync(dir, { withFileTypes: true });
126
+ } catch {
127
+ return [];
128
+ }
129
+ const found: SkillLite[] = [];
130
+ for (const entry of entries) {
131
+ // Hidden entries are harness internals (e.g. ~/.agents/skills/.system);
132
+ // pi's own [Skills] list never includes them.
133
+ if (entry.name.startsWith(".")) continue;
134
+ const full = path.join(dir, entry.name);
135
+ let isDir: boolean;
136
+ try {
137
+ isDir = entry.isDirectory() || (entry.isSymbolicLink() && fs.statSync(full).isDirectory());
138
+ } catch {
139
+ continue;
140
+ }
141
+ if (isDir) {
142
+ if (fs.existsSync(path.join(full, "SKILL.md"))) {
143
+ const skill = readSkillFile(path.join(full, "SKILL.md"), entry.name);
144
+ if (skill) found.push(skill);
145
+ } else {
146
+ found.push(...walk(full, depth + 1));
147
+ }
148
+ continue;
149
+ }
150
+ if (!entry.name.endsWith(".md") || entry.name === "SKILL.md") continue;
151
+ const standalone = loc.style === "pi" ? depth === 0 : depth > 0;
152
+ if (!standalone) continue;
153
+ const skill = readSkillFile(full, entry.name.replace(/\.md$/, ""));
154
+ if (skill) found.push(skill);
155
+ }
156
+ return found;
157
+ };
158
+ return walk(loc.dir, 0);
159
+ }
160
+
161
+ /** pi-faithful skill catalog: every skill pi itself would load, deduped by
162
+ * name (first wins). All roots are injectable for tests. */
163
+ export function scanSkills(opts: SkillScanOptions = {}): SkillLite[] {
164
+ const seen = new Set<string>();
165
+ const out: SkillLite[] = [];
166
+ for (const loc of skillLocations(opts)) {
167
+ for (const skill of scanLocation(loc)) {
168
+ if (seen.has(skill.name)) continue;
169
+ seen.add(skill.name);
170
+ out.push(skill);
171
+ }
172
+ }
173
+ return out;
174
+ }
175
+
176
+ export function findSkillByName(skills: SkillLite[], name: string): SkillLite | undefined {
177
+ return skills.find((s) => s.name === name);
178
+ }
179
+
180
+ /** One-liner list for the tool description: `- name: description`. */
181
+ export function catalogSummary(skills: SkillLite[]): string {
182
+ return skills.map((s) => `- ${s.name}: ${s.description}`).join("\n");
183
+ }
184
+
185
+ /** Full body handed to agy when it activates a skill. */
186
+ export function readSkillBody(skill: SkillLite): string {
187
+ try {
188
+ return fs.readFileSync(skill.filePath, "utf8");
189
+ } catch (err) {
190
+ return `failed to read skill: ${err instanceof Error ? err.message : String(err)}`;
191
+ }
192
+ }
193
+
194
+ /** JSON schema for the activate_skill bridge tool. */
195
+ export function activateSkillSchema(skills: SkillLite[]): Record<string, unknown> {
196
+ return {
197
+ type: "object",
198
+ properties: {
199
+ name: {
200
+ type: "string",
201
+ enum: skills.map((s) => s.name),
202
+ description: "Skill name from the catalog in this tool's description.",
203
+ },
204
+ },
205
+ required: ["name"],
206
+ };
207
+ }