@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.
- package/CHANGELOG.md +12 -0
- package/README.md +3 -3
- package/THIRD_PARTY_NOTICES.md +2 -23
- package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
- package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
- package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
- package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
- package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
- package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
- package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
- package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
- package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
- package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
- package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
- package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
- package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
- package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
- package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
- package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
- package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
- package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
- package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
- package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
- package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
- package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
- package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
- package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
- package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
- package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
- package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
- package/node_modules/pi-commandcode-provider/README.md +3 -2
- package/node_modules/pi-commandcode-provider/index.ts +120 -13
- package/node_modules/pi-commandcode-provider/package.json +4 -3
- package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
- package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
- package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
- package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
- package/package.json +11 -14
- package/node_modules/pi-antigravity/README.md +0 -298
- package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
- package/node_modules/pi-antigravity/package.json +0 -87
- package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
- package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
- package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
- package/node_modules/pi-antigravity/src/client/client.ts +0 -602
- package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
- package/node_modules/pi-antigravity/src/client/index.ts +0 -2
- package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
- package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
- package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
- package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
- package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
- package/node_modules/pi-antigravity/src/image/image.ts +0 -427
- package/node_modules/pi-antigravity/src/image/index.ts +0 -1
- package/node_modules/pi-antigravity/src/image/native.ts +0 -69
- package/node_modules/pi-antigravity/src/index.ts +0 -547
- package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
- package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
- package/node_modules/pi-antigravity/src/models/index.ts +0 -3
- package/node_modules/pi-antigravity/src/models/models.ts +0 -647
- package/node_modules/pi-antigravity/src/search/index.ts +0 -1
- package/node_modules/pi-antigravity/src/search/search.ts +0 -967
- package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
- package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
- package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
- package/node_modules/pi-antigravity/src/types/index.ts +0 -2
- package/node_modules/pi-antigravity/src/types/types.ts +0 -329
- package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
- package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
- package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
- package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
- package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
- package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
- package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
- package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
- package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
- package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
- package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
- package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
- package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
- package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
- package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
- package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
- package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
- package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
- package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
- package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
- package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
- package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
- package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
- package/node_modules/pi-antigravity/tsconfig.json +0 -21
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
// Cleanup for the LEGACY pi.invokeTool local patch (removed in 1.3.0).
|
|
2
|
+
//
|
|
3
|
+
// Users who ran the old consent-gated patcher still carry pi.invokeTool in
|
|
4
|
+
// their installed pi dist/. It is inert (nothing calls it) and a pi
|
|
5
|
+
// update/reinstall wipes it, but it is a silent vendor modification. This
|
|
6
|
+
// module detects it and restores the original files from the versioned
|
|
7
|
+
// backup the patcher left behind - only on an explicit /agy patch-cleanup
|
|
8
|
+
// command. It never writes to the pi install on its own.
|
|
9
|
+
//
|
|
10
|
+
// Everything below (site table, sentinels, findPiRoot, version-guarded
|
|
11
|
+
// restore) is carried over verbatim from the deleted patcher so detection
|
|
12
|
+
// and restore stay byte-compatible with what users actually have on disk.
|
|
13
|
+
//
|
|
14
|
+
// Adds pi.invokeTool() at 6 sites in 4 compiled files under pi's dist/, plus
|
|
15
|
+
// (pi 0.84.3+) an entry redirect that swaps the bundled dist/bundle/cli.js
|
|
16
|
+
// for a shim loading the modular dist/cli.js. pi ships compiled (no src/);
|
|
17
|
+
// these are plain, sentinel-detectable text edits, so a runtime patcher can
|
|
18
|
+
// apply them durably and idempotently. This lets the bridge self-heal after a
|
|
19
|
+
// pi reinstall/update without manual re-patching.
|
|
20
|
+
//
|
|
21
|
+
// Activation: pi's core is native ESM, cached per process; /reload does NOT pick
|
|
22
|
+
// up these edits. A patched dist only takes effect on a FULL pi restart. The
|
|
23
|
+
// extension notifies the user accordingly (see extensions/index.ts).
|
|
24
|
+
//
|
|
25
|
+
// Hardening (peer-reviewed):
|
|
26
|
+
// - Two-phase apply: validate every anchor/sentinel BEFORE writing anything,
|
|
27
|
+
// so a missing anchor (version drift) aborts with zero files touched.
|
|
28
|
+
// - Facade (loader.js) is written LAST: a crashed/partial patch leaves
|
|
29
|
+
// hasInvokeTool() === false (safe degraded), never a half-wired chain.
|
|
30
|
+
// - Per-pid temp file + rename (atomic per file): no torn writes, no
|
|
31
|
+
// concurrent-launch race (mirrors mcp-server.ts writeBridgeMcpConfig).
|
|
32
|
+
// - Backups carry a VERSION stamp; restore refuses a version mismatch so it
|
|
33
|
+
// can never silently downgrade a newer pi's shipped core.
|
|
34
|
+
// - Actionable EACCES message for sudo-installed pi.
|
|
35
|
+
// - No jiti cache clear: pi 0.82.1 sets moduleCache:false (loader.js), so jiti
|
|
36
|
+
// never fs-caches; rm -rf /tmp/jiti is a no-op here.
|
|
37
|
+
|
|
38
|
+
import fs from "node:fs";
|
|
39
|
+
import path from "node:path";
|
|
40
|
+
import os from "node:os";
|
|
41
|
+
import { execSync } from "node:child_process";
|
|
42
|
+
import { fileURLToPath } from "node:url";
|
|
43
|
+
|
|
44
|
+
import { bridgeDir } from "./config.js";
|
|
45
|
+
|
|
46
|
+
const PACKAGE_NAME = "@earendil-works/pi-coding-agent";
|
|
47
|
+
|
|
48
|
+
export function patchBackupDir(): string {
|
|
49
|
+
return path.join(bridgeDir(), "pi-patch-backup");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** One insertion site in one compiled file. */
|
|
53
|
+
interface PatchSite {
|
|
54
|
+
/** Path relative to pi's dist/. */
|
|
55
|
+
file: string;
|
|
56
|
+
/** Unique existing text; insertion is placed immediately after it. */
|
|
57
|
+
anchor: string;
|
|
58
|
+
/** Text appended after the anchor (no leading newline; one is added). */
|
|
59
|
+
insertion: string;
|
|
60
|
+
/** Substring proving this site is already patched (idempotency guard). */
|
|
61
|
+
sentinel: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Write order is significant: facade (loader.js) MUST be last so a partial
|
|
65
|
+
// patch fails closed (hasInvokeTool reads the facade). Sites within a file are
|
|
66
|
+
// applied together in one atomic write.
|
|
67
|
+
const PATCH_FILES: Array<{ file: string; sites: PatchSite[] }> = [
|
|
68
|
+
{
|
|
69
|
+
file: "core/agent-session.js",
|
|
70
|
+
sites: [
|
|
71
|
+
{
|
|
72
|
+
file: "core/agent-session.js",
|
|
73
|
+
anchor:
|
|
74
|
+
" getToolDefinition(name) {\n return this._toolDefinitions.get(name)?.definition;\n }\n",
|
|
75
|
+
insertion: ` /**
|
|
76
|
+
* LOCAL PATCH (pi-antigravity-bridge): invoke a registered tool by name
|
|
77
|
+
* out-of-band and return its result. The tool wrapper synthesizes ctx via
|
|
78
|
+
* its ctxFactory when none is passed. Not upstream pi (yet).
|
|
79
|
+
*/
|
|
80
|
+
async invokeTool(name, args = {}, options = {}) {
|
|
81
|
+
const tool = this._toolRegistry.get(name);
|
|
82
|
+
if (!tool) {
|
|
83
|
+
throw new Error(\`invokeTool: tool "\${name}" not found in registry\`);
|
|
84
|
+
}
|
|
85
|
+
const toolCallId = options.toolCallId ?? \`invokeTool:\${name}:\${Date.now()}\`;
|
|
86
|
+
return tool.execute(toolCallId, args, options.signal ?? undefined, options.onUpdate);
|
|
87
|
+
}
|
|
88
|
+
`,
|
|
89
|
+
sentinel: "async invokeTool(name, args = {}, options = {}) {",
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
file: "core/agent-session.js",
|
|
93
|
+
anchor: " refreshTools: () => this._refreshToolRegistry(),\n",
|
|
94
|
+
insertion:
|
|
95
|
+
" invokeTool: (name, args, options) => this.invokeTool(name, args, options),\n",
|
|
96
|
+
sentinel:
|
|
97
|
+
"invokeTool: (name, args, options) => this.invokeTool(name, args, options),",
|
|
98
|
+
},
|
|
99
|
+
],
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
file: "core/extensions/runner.js",
|
|
103
|
+
sites: [
|
|
104
|
+
{
|
|
105
|
+
file: "core/extensions/runner.js",
|
|
106
|
+
anchor: " this.runtime.refreshTools = actions.refreshTools;\n",
|
|
107
|
+
insertion: " this.runtime.invokeTool = actions.invokeTool;\n",
|
|
108
|
+
sentinel: "this.runtime.invokeTool = actions.invokeTool;",
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
file: "core/extensions/runner.js",
|
|
112
|
+
anchor:
|
|
113
|
+
" getActiveTools() {\n this.assertActive();\n return this.runtime.getActiveTools();\n }\n",
|
|
114
|
+
insertion: ` invokeTool(name, args, options) {
|
|
115
|
+
this.assertActive();
|
|
116
|
+
return this.runtime.invokeTool(name, args, options);
|
|
117
|
+
}
|
|
118
|
+
`,
|
|
119
|
+
sentinel: "return this.runtime.invokeTool(name, args, options);",
|
|
120
|
+
},
|
|
121
|
+
],
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
file: "core/extensions/types.d.ts",
|
|
125
|
+
sites: [
|
|
126
|
+
{
|
|
127
|
+
file: "core/extensions/types.d.ts",
|
|
128
|
+
anchor: " getAllTools(): ToolInfo[];\n",
|
|
129
|
+
insertion: ` /**
|
|
130
|
+
* LOCAL PATCH (pi-antigravity-bridge): invoke a registered tool by name
|
|
131
|
+
* out-of-band and return { content, details, isError? }. ctx is synthesized.
|
|
132
|
+
*/
|
|
133
|
+
invokeTool(name: string, args?: Record<string, unknown>, options?: { toolCallId?: string; signal?: AbortSignal; onUpdate?: (update: unknown) => void }): Promise<{ content: unknown[]; details: unknown; isError?: boolean }>;
|
|
134
|
+
`,
|
|
135
|
+
sentinel: "invokeTool(name: string, args?: Record<string, unknown>",
|
|
136
|
+
},
|
|
137
|
+
],
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
// Facade. Written LAST on purpose (see file header).
|
|
141
|
+
file: "core/extensions/loader.js",
|
|
142
|
+
sites: [
|
|
143
|
+
{
|
|
144
|
+
file: "core/extensions/loader.js",
|
|
145
|
+
anchor:
|
|
146
|
+
" getAllTools() {\n assertActive();\n return runtime.getAllTools();\n },\n",
|
|
147
|
+
insertion: ` invokeTool(name, args, options) {
|
|
148
|
+
assertActive();
|
|
149
|
+
return runtime.invokeTool(name, args, options);
|
|
150
|
+
},
|
|
151
|
+
`,
|
|
152
|
+
sentinel: "return runtime.invokeTool(name, args, options);",
|
|
153
|
+
},
|
|
154
|
+
],
|
|
155
|
+
},
|
|
156
|
+
];
|
|
157
|
+
|
|
158
|
+
const ALL_SITES: PatchSite[] = PATCH_FILES.flatMap((f) => f.sites);
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Entry redirect (pi 0.84.3+). pi's bin now points at dist/bundle/cli.js, a
|
|
162
|
+
* bundled runtime with its own embedded core; text patches to dist/core/ never
|
|
163
|
+
* reach a process launched from the bundle. Fix: replace the tiny bundle entry
|
|
164
|
+
* with a shim that loads the still-shipped modular dist/cli.js, where the six
|
|
165
|
+
* insertion sites live. The file is absent on pre-bundle pi (bin already
|
|
166
|
+
* modular); apply, status, and restore skip it there.
|
|
167
|
+
*/
|
|
168
|
+
const ENTRY_REDIRECT = {
|
|
169
|
+
/** Path relative to pi's dist/. */
|
|
170
|
+
file: "bundle/cli.js",
|
|
171
|
+
/** Proves an unpatched file is the bundled entry (it imports hashed chunks). */
|
|
172
|
+
probe: "chunks/",
|
|
173
|
+
/** Proves the redirect is already applied. */
|
|
174
|
+
sentinel: 'import "../cli.js";',
|
|
175
|
+
/** Full replacement content. */
|
|
176
|
+
content: `#!/usr/bin/env node
|
|
177
|
+
// LOCAL PATCH (pi-antigravity-bridge): redirect pi's bundled entry to the
|
|
178
|
+
// modular runtime under dist/, where the invokeTool patch sites take effect.
|
|
179
|
+
// Restore via /agy patch restore. See docs/PI-INVOKETOOL-PATCH.md.
|
|
180
|
+
import "../cli.js";
|
|
181
|
+
`,
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
export interface PatchResult {
|
|
185
|
+
/** True when every required site is present (after this run). */
|
|
186
|
+
present: boolean;
|
|
187
|
+
/** True when >=1 file was actually written this run. */
|
|
188
|
+
patched: boolean;
|
|
189
|
+
/** True when all sites were already present and nothing was written. */
|
|
190
|
+
alreadyPresent: boolean;
|
|
191
|
+
root?: string;
|
|
192
|
+
version?: string;
|
|
193
|
+
changedFiles: string[];
|
|
194
|
+
backupDir?: string;
|
|
195
|
+
errors: string[];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export interface PatchStatus {
|
|
199
|
+
/** True when every sentinel is present across all files. */
|
|
200
|
+
present: boolean;
|
|
201
|
+
root?: string;
|
|
202
|
+
version?: string;
|
|
203
|
+
/** Site labels missing (by file). */
|
|
204
|
+
missing: string[];
|
|
205
|
+
/** Newest backup dir found, if any. */
|
|
206
|
+
backupDir?: string;
|
|
207
|
+
backupVersion?: string;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export interface RestoreResult {
|
|
211
|
+
ok: boolean;
|
|
212
|
+
restoredFiles: string[];
|
|
213
|
+
backupDir?: string;
|
|
214
|
+
reason?: string;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
type Logger = (s: string, d?: unknown) => void;
|
|
218
|
+
|
|
219
|
+
/** Read the installed pi version from a package root's package.json. */
|
|
220
|
+
function readVersion(root: string): string | undefined {
|
|
221
|
+
try {
|
|
222
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
223
|
+
if (pkg?.name === PACKAGE_NAME && typeof pkg.version === "string") return pkg.version;
|
|
224
|
+
} catch {
|
|
225
|
+
/* not a pi root */
|
|
226
|
+
}
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Verify a candidate is a real pi package root whose dist holds the target
|
|
231
|
+
* files. This is the safety net that makes multi-strategy root-finding safe:
|
|
232
|
+
* a wrong candidate (a sibling extension's decoy node_modules copy) fails here. */
|
|
233
|
+
function verifyRoot(root: string): { root: string; version: string } | null {
|
|
234
|
+
if (!root) return null;
|
|
235
|
+
const version = readVersion(root);
|
|
236
|
+
if (!version) return null;
|
|
237
|
+
// The anchor of site 1 is the most specific fingerprint of a real, unedited
|
|
238
|
+
// pi agent-session.js. Require its file to exist and contain it.
|
|
239
|
+
const probe = path.join(root, "dist", "core", "agent-session.js");
|
|
240
|
+
try {
|
|
241
|
+
const txt = fs.readFileSync(probe, "utf8");
|
|
242
|
+
// Accept either patched or unpatched: the getToolDefinition body is stable.
|
|
243
|
+
if (!txt.includes("getToolDefinition(name)")) return null;
|
|
244
|
+
} catch {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
// All target files must exist.
|
|
248
|
+
for (const f of PATCH_FILES) {
|
|
249
|
+
if (!fs.existsSync(path.join(root, "dist", f.file))) return null;
|
|
250
|
+
}
|
|
251
|
+
return { root, version };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Candidate from realpath(process.argv[1]) — the pi cli entry the OS launched.
|
|
255
|
+
* Most reliable signal for the RUNNING pi regardless of node_modules layout. */
|
|
256
|
+
function candidateFromArgv(): string | null {
|
|
257
|
+
try {
|
|
258
|
+
const launched = process.argv[1];
|
|
259
|
+
if (!launched) return null;
|
|
260
|
+
const real = fs.realpathSync(launched);
|
|
261
|
+
const dir = path.dirname(real);
|
|
262
|
+
if (path.basename(dir) === "dist") return path.dirname(dir);
|
|
263
|
+
// pi 0.84.3+ ships the bin entry at dist/bundle/cli.js.
|
|
264
|
+
if (path.basename(dir) === "bundle" && path.basename(path.dirname(dir)) === "dist") {
|
|
265
|
+
return path.dirname(path.dirname(dir));
|
|
266
|
+
}
|
|
267
|
+
return null;
|
|
268
|
+
} catch {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Candidate from import.meta.resolve — works in single-install (normal npm -g)
|
|
274
|
+
* layouts. NOTE: in a dev dual-install this resolves the LOCAL node_modules copy,
|
|
275
|
+
* not the running global pi; verifyRoot + the argv strategy keep it safe. */
|
|
276
|
+
function candidateFromResolve(): string | null {
|
|
277
|
+
try {
|
|
278
|
+
const url = import.meta.resolve(PACKAGE_NAME);
|
|
279
|
+
const mainFile = fileURLToPath(url); // .../dist/index.js
|
|
280
|
+
const dist = path.dirname(mainFile);
|
|
281
|
+
if (path.basename(dist) === "dist") return path.dirname(dist);
|
|
282
|
+
return null;
|
|
283
|
+
} catch {
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Candidate from `npm root -g`. */
|
|
289
|
+
function candidateFromNpmGlobal(): string | null {
|
|
290
|
+
try {
|
|
291
|
+
const root = execSync("npm root -g", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
292
|
+
return path.join(root, PACKAGE_NAME);
|
|
293
|
+
} catch {
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Candidates from well-known global install locations + env overrides. */
|
|
299
|
+
function candidateFromKnownPaths(): string[] {
|
|
300
|
+
const out: string[] = [];
|
|
301
|
+
if (process.env.PI_PACKAGE_ROOT) out.push(process.env.PI_PACKAGE_ROOT);
|
|
302
|
+
const home = os.homedir();
|
|
303
|
+
out.push(path.join(home, ".npm-global", "lib", "node_modules", PACKAGE_NAME));
|
|
304
|
+
out.push(path.join("/usr/local/lib/node_modules", PACKAGE_NAME));
|
|
305
|
+
out.push(path.join("/usr/lib/node_modules", PACKAGE_NAME));
|
|
306
|
+
if (process.env.NVM_DIR) {
|
|
307
|
+
out.push(path.join(process.env.NVM_DIR, "lib", "node_modules", PACKAGE_NAME));
|
|
308
|
+
}
|
|
309
|
+
return out;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Locate the running pi's package root. Verify-as-you-go and short-circuit on
|
|
313
|
+
* the first verified candidate, so the common case (argv already resolves)
|
|
314
|
+
* never spawns `npm root -g`. */
|
|
315
|
+
export function findPiRoot(): { root: string; version: string } | null {
|
|
316
|
+
const tried = new Set<string>();
|
|
317
|
+
const attempt = (cand: string | null): { root: string; version: string } | null => {
|
|
318
|
+
if (!cand || tried.has(cand)) return null;
|
|
319
|
+
tried.add(cand);
|
|
320
|
+
return verifyRoot(cand);
|
|
321
|
+
};
|
|
322
|
+
// Cheapest + most reliable first: the OS-launched pi entry.
|
|
323
|
+
let v = attempt(candidateFromArgv());
|
|
324
|
+
if (v) return v;
|
|
325
|
+
// ESM resolution (single-install layouts).
|
|
326
|
+
v = attempt(candidateFromResolve());
|
|
327
|
+
if (v) return v;
|
|
328
|
+
// Only now (argv + resolve both missed) pay for spawning npm.
|
|
329
|
+
v = attempt(candidateFromNpmGlobal());
|
|
330
|
+
if (v) return v;
|
|
331
|
+
// Known global locations + PI_PACKAGE_ROOT env override.
|
|
332
|
+
for (const k of candidateFromKnownPaths()) {
|
|
333
|
+
v = attempt(k);
|
|
334
|
+
if (v) return v;
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Whether every site's sentinel is already present. */
|
|
340
|
+
function siteMissing(content: string, site: PatchSite): boolean {
|
|
341
|
+
return !content.includes(site.sentinel);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Atomic write: per-pid tmp in the SAME dir (same filesystem) + rename.
|
|
345
|
+
* Preserves the destination's existing permission bits: the bundle entry is
|
|
346
|
+
* pi's bin target and must keep its execute bit through patch and restore.
|
|
347
|
+
* A destination that does not exist yet is created 0o644. */
|
|
348
|
+
function atomicWrite(filePath: string, content: string): void {
|
|
349
|
+
let mode = 0o644;
|
|
350
|
+
try {
|
|
351
|
+
mode = fs.statSync(filePath).mode & 0o777;
|
|
352
|
+
} catch {
|
|
353
|
+
/* destination absent: new file, plain default */
|
|
354
|
+
}
|
|
355
|
+
const tmp = `${filePath}.${process.pid}.tmp`;
|
|
356
|
+
fs.writeFileSync(tmp, content, { mode });
|
|
357
|
+
fs.chmodSync(tmp, mode);
|
|
358
|
+
fs.renameSync(tmp, filePath);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Persist the validated pre-write content into the backup dir, mirroring path.
|
|
362
|
+
* Backs up the in-memory `original` (NOT a fresh disk read) so a concurrent
|
|
363
|
+
* apply between phase-1 and phase-2 can never capture already-patched bytes. */
|
|
364
|
+
function backupOriginal(file: string, content: string, backupDir: string): void {
|
|
365
|
+
const dst = path.join(backupDir, file);
|
|
366
|
+
fs.mkdirSync(path.dirname(dst), { recursive: true });
|
|
367
|
+
fs.writeFileSync(dst, content);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Human-readable, actionable message for a write failure (sudo-global pi). */
|
|
371
|
+
function describeWriteError(err: unknown, root: string): string {
|
|
372
|
+
const code = (err as NodeJS.ErrnoException)?.code;
|
|
373
|
+
if (code === "EACCES" || code === "EPERM") {
|
|
374
|
+
return (
|
|
375
|
+
`permission denied writing under ${root}. pi was likely installed with sudo. ` +
|
|
376
|
+
`Fix: 'sudo chown -R "$(id -un)" "${root}"', or reinstall pi under a user-writable prefix ` +
|
|
377
|
+
`('npm config set prefix "${path.join(os.homedir(), ".npm-global")}"' then 'npm i -g ${PACKAGE_NAME}').`
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
return err instanceof Error ? err.message : String(err);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Find the best backup dir: an exact version match when `preferVersion` is
|
|
384
|
+
* given, else the newest by VERSION mtime. Multi-version backup dirs are
|
|
385
|
+
* normal (the old patcher re-applied across pi upgrades), so newest-by-mtime
|
|
386
|
+
* alone could pick a backup that cannot legally restore. */
|
|
387
|
+
function findNewestBackup(
|
|
388
|
+
base: string,
|
|
389
|
+
preferVersion?: string,
|
|
390
|
+
): { dir: string; version: string } | null {
|
|
391
|
+
let entries: string[];
|
|
392
|
+
try {
|
|
393
|
+
entries = fs.readdirSync(base);
|
|
394
|
+
} catch {
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
let best: { dir: string; version: string; mtime: number } | null = null;
|
|
398
|
+
for (const name of entries) {
|
|
399
|
+
const dir = path.join(base, name);
|
|
400
|
+
const verFile = path.join(dir, "VERSION");
|
|
401
|
+
try {
|
|
402
|
+
const stat = fs.statSync(verFile);
|
|
403
|
+
const manifest = JSON.parse(fs.readFileSync(verFile, "utf8"));
|
|
404
|
+
if (typeof manifest.version !== "string") continue;
|
|
405
|
+
if (preferVersion && manifest.version === preferVersion) {
|
|
406
|
+
return { dir, version: manifest.version };
|
|
407
|
+
}
|
|
408
|
+
if (!best || stat.mtimeMs > best.mtime) {
|
|
409
|
+
best = { dir, version: manifest.version, mtime: stat.mtimeMs };
|
|
410
|
+
}
|
|
411
|
+
} catch {
|
|
412
|
+
/* incomplete backup entry */
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return best ? { dir: best.dir, version: best.version } : null;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Shared options. root/backupBase are test seams (and let /agy patch target a
|
|
419
|
+
* specific install); production calls omit them and use auto-discovery. */
|
|
420
|
+
export interface PatchOpts {
|
|
421
|
+
root?: string;
|
|
422
|
+
backupBase?: string;
|
|
423
|
+
log?: Logger;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function resolveRoot(opts: { root?: string }): { root: string; version: string } | null {
|
|
427
|
+
return opts.root ? verifyRoot(opts.root) : findPiRoot();
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function backupBaseOf(opts: { backupBase?: string }): string {
|
|
431
|
+
return opts.backupBase ?? patchBackupDir();
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Report the current patch state without changing anything. */
|
|
435
|
+
export function patchStatus(opts: { root?: string; backupBase?: string } = {}): PatchStatus {
|
|
436
|
+
const root = resolveRoot(opts);
|
|
437
|
+
if (!root) {
|
|
438
|
+
return { present: false, missing: ["pi-root-not-found"] };
|
|
439
|
+
}
|
|
440
|
+
const missing: string[] = [];
|
|
441
|
+
for (const f of PATCH_FILES) {
|
|
442
|
+
let txt = "";
|
|
443
|
+
try {
|
|
444
|
+
txt = fs.readFileSync(path.join(root.root, "dist", f.file), "utf8");
|
|
445
|
+
} catch {
|
|
446
|
+
missing.push(f.file);
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
for (const site of f.sites) {
|
|
450
|
+
if (siteMissing(txt, site)) missing.push(`${f.file}:${site.sentinel.slice(0, 40)}`);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
// Entry redirect: required when the bundled entry exists (pi 0.84.3+).
|
|
454
|
+
const entryPath = path.join(root.root, "dist", ENTRY_REDIRECT.file);
|
|
455
|
+
if (fs.existsSync(entryPath)) {
|
|
456
|
+
const txt = fs.readFileSync(entryPath, "utf8");
|
|
457
|
+
if (!txt.includes(ENTRY_REDIRECT.sentinel)) missing.push(ENTRY_REDIRECT.file);
|
|
458
|
+
}
|
|
459
|
+
// Absent file = pre-bundle pi: the bin already points at the modular entry.
|
|
460
|
+
const backup = findNewestBackup(backupBaseOf(opts), root.version);
|
|
461
|
+
return {
|
|
462
|
+
present: missing.length === 0,
|
|
463
|
+
root: root.root,
|
|
464
|
+
version: root.version,
|
|
465
|
+
missing,
|
|
466
|
+
backupDir: backup?.dir,
|
|
467
|
+
backupVersion: backup?.version,
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** What session_start should do about the patch + MCP bridge, given the four
|
|
472
|
+
* observable signals. Pure so the matrix is unit-testable without a pi harness. */
|
|
473
|
+
export type PatchAction =
|
|
474
|
+
| { kind: "proceed" } // patch is live: start the MCP bridge
|
|
475
|
+
| { kind: "notify-restart" } // on disk but not live this process: tell user to restart
|
|
476
|
+
| { kind: "silent" } // user declined: do nothing, stay quiet
|
|
477
|
+
| { kind: "ask" } // missing + has UI: show the consent gate
|
|
478
|
+
| { kind: "headless-skip" }; // missing + no UI: log and skip (can't ask)
|
|
479
|
+
|
|
480
|
+
/** Decide the session_start patch action. Precedence:
|
|
481
|
+
* live > on-disk-needs-restart > declined > interactive-ask > headless-skip. */
|
|
482
|
+
export function restorePatch(opts: PatchOpts = {}): RestoreResult {
|
|
483
|
+
const log = opts.log ?? (() => {});
|
|
484
|
+
const found = resolveRoot(opts);
|
|
485
|
+
if (!found) {
|
|
486
|
+
return { ok: false, restoredFiles: [], reason: "could not locate the running pi package root to restore into." };
|
|
487
|
+
}
|
|
488
|
+
const { root, version } = found;
|
|
489
|
+
const backup = findNewestBackup(backupBaseOf(opts), found.version);
|
|
490
|
+
if (!backup) {
|
|
491
|
+
return { ok: false, restoredFiles: [], reason: "no backup found; nothing to restore." };
|
|
492
|
+
}
|
|
493
|
+
if (backup.version !== version) {
|
|
494
|
+
const msg =
|
|
495
|
+
`refusing restore: backup is from pi ${backup.version} but installed pi is ${version}. ` +
|
|
496
|
+
`Restoring across versions would downgrade pi's shipped core files. Delete the backup manually if intended.`;
|
|
497
|
+
log("restore-version-mismatch", { backup: backup.version, installed: version });
|
|
498
|
+
return { ok: false, restoredFiles: [], backupDir: backup.dir, reason: msg };
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const restoredFiles: string[] = [];
|
|
502
|
+
// Entry redirect restores last, mirroring apply order.
|
|
503
|
+
for (const rel of [...PATCH_FILES.map((f) => f.file), ENTRY_REDIRECT.file]) {
|
|
504
|
+
const src = path.join(backup.dir, rel);
|
|
505
|
+
const dst = path.join(root, "dist", rel);
|
|
506
|
+
if (!fs.existsSync(src)) continue;
|
|
507
|
+
try {
|
|
508
|
+
const content = fs.readFileSync(src, "utf8");
|
|
509
|
+
atomicWrite(dst, content);
|
|
510
|
+
restoredFiles.push(rel);
|
|
511
|
+
} catch (e) {
|
|
512
|
+
const msg = describeWriteError(e, root);
|
|
513
|
+
return { ok: false, restoredFiles, backupDir: backup.dir, reason: `failed restoring ${rel}: ${msg}` };
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
log("restore-done", { backupDir: backup.dir, count: restoredFiles.length });
|
|
517
|
+
return { ok: true, restoredFiles, backupDir: backup.dir };
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** Exposed for tests: the full site list (read-only view). */
|
|
521
|
+
export function listSites(): ReadonlyArray<Readonly<PatchSite>> {
|
|
522
|
+
return ALL_SITES;
|
|
523
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Fold state machine for bridge_poll_result display events: consecutive
|
|
2
|
+
// polls collapse into ONE counted transcript entry instead of one entry per
|
|
3
|
+
// poll (observed live 2026-10-21: 60 "Poll git_commit" entries from a single
|
|
4
|
+
// wait, all flushed in bursts when the parked round-trip resolved).
|
|
5
|
+
//
|
|
6
|
+
// Runs close on a target switch, on any non-poll display event, or at turn
|
|
7
|
+
// end; the caller persists each closed run as an "agy-poll-run" entry.
|
|
8
|
+
|
|
9
|
+
export interface PollRunData {
|
|
10
|
+
/** The pi tool the model kept polling, e.g. "git_commit". */
|
|
11
|
+
target: string;
|
|
12
|
+
count: number;
|
|
13
|
+
/** Strongest poll outcome seen: running < done < failed. Sticky so a
|
|
14
|
+
* still-running poll after a terminal one cannot downgrade the summary. */
|
|
15
|
+
state: "running" | "done" | "failed";
|
|
16
|
+
firstAt: string;
|
|
17
|
+
lastAt: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const STATE_RANK: Record<PollRunData["state"], number> = { running: 0, done: 1, failed: 2 };
|
|
21
|
+
|
|
22
|
+
export class PollRunFolder {
|
|
23
|
+
#run: PollRunData | undefined;
|
|
24
|
+
|
|
25
|
+
/** The open run, for a live status-line counter. */
|
|
26
|
+
get open(): PollRunData | undefined {
|
|
27
|
+
return this.#run;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Fold one poll event. Returns a run to persist when this poll switched
|
|
31
|
+
* targets away from the open run; the new poll always starts or extends
|
|
32
|
+
* a run, so callers append the return value BEFORE reading `open`. */
|
|
33
|
+
add(target: string, state: PollRunData["state"], at: Date): PollRunData | undefined {
|
|
34
|
+
let closed: PollRunData | undefined;
|
|
35
|
+
if (this.#run && this.#run.target !== target) closed = this.#close();
|
|
36
|
+
if (!this.#run) {
|
|
37
|
+
this.#run = { target, count: 0, state: "running", firstAt: at.toISOString(), lastAt: at.toISOString() };
|
|
38
|
+
}
|
|
39
|
+
this.#run.count += 1;
|
|
40
|
+
this.#run.lastAt = at.toISOString();
|
|
41
|
+
if (STATE_RANK[state] > STATE_RANK[this.#run.state]) this.#run.state = state;
|
|
42
|
+
return closed;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Close and return the open run, if any. Idempotent. */
|
|
46
|
+
flush(): PollRunData | undefined {
|
|
47
|
+
return this.#run ? this.#close() : undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
#close(): PollRunData {
|
|
51
|
+
const run = this.#run as PollRunData;
|
|
52
|
+
this.#run = undefined;
|
|
53
|
+
return run;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Stream-json prompt staging: user-attached image blocks cannot ride the CLI's
|
|
2
|
+
// text-only turn input, so they are staged to temp files and the prompt points
|
|
3
|
+
// the model at them. The model views them through the bridge read tool, whose
|
|
4
|
+
// tool-result image content the CLI's MCP client delivers (probe 2026-09-07).
|
|
5
|
+
// The ACP engine does not use this module: image blocks ride session/prompt
|
|
6
|
+
// natively.
|
|
7
|
+
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
|
|
12
|
+
export const STAGE_DIR_PREFIX = "pi-bridge-img-";
|
|
13
|
+
|
|
14
|
+
/** Retention for staged files: the model may re-read them on later turns of
|
|
15
|
+
* the same conversation, so sweeps cannot delete a dir this turn's prompt
|
|
16
|
+
* still references. */
|
|
17
|
+
export const STAGE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
18
|
+
|
|
19
|
+
export interface StagedImage {
|
|
20
|
+
data: string;
|
|
21
|
+
mimeType: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const EXT_BY_MIME: Record<string, string> = {
|
|
25
|
+
"image/png": ".png",
|
|
26
|
+
"image/jpeg": ".jpg",
|
|
27
|
+
"image/gif": ".gif",
|
|
28
|
+
"image/webp": ".webp",
|
|
29
|
+
"image/bmp": ".bmp",
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function sweepStale(root: string): void {
|
|
33
|
+
let entries: string[];
|
|
34
|
+
try {
|
|
35
|
+
entries = fs.readdirSync(root);
|
|
36
|
+
} catch {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const cutoff = Date.now() - STAGE_MAX_AGE_MS;
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
if (!entry.startsWith(STAGE_DIR_PREFIX)) continue;
|
|
42
|
+
const full = path.join(root, entry);
|
|
43
|
+
try {
|
|
44
|
+
// lstat: never follow a symlink planted at our prefix in a shared tmp.
|
|
45
|
+
if (!fs.lstatSync(full).isDirectory()) continue;
|
|
46
|
+
if (fs.statSync(full).mtimeMs < cutoff) fs.rmSync(full, { recursive: true, force: true });
|
|
47
|
+
} catch {
|
|
48
|
+
// Raced with another process's sweep or deletion: nothing to do.
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Write image blocks to a fresh staging dir under `root` (default the OS tmp
|
|
54
|
+
* dir). Returns null on any failure (including an empty/malformed payload):
|
|
55
|
+
* the turn then runs text-only instead of failing. */
|
|
56
|
+
export function stagePromptImages(
|
|
57
|
+
images: Array<StagedImage>,
|
|
58
|
+
root?: string,
|
|
59
|
+
): { dir: string; paths: string[] } | null {
|
|
60
|
+
const base = root ?? os.tmpdir();
|
|
61
|
+
let dir: string | null = null;
|
|
62
|
+
try {
|
|
63
|
+
sweepStale(base);
|
|
64
|
+
dir = fs.mkdtempSync(path.join(base, STAGE_DIR_PREFIX));
|
|
65
|
+
const paths = images.map((img, i) => {
|
|
66
|
+
const bytes = Buffer.from(img.data, "base64");
|
|
67
|
+
if (bytes.length === 0) throw new Error("empty image payload");
|
|
68
|
+
const ext = EXT_BY_MIME[img.mimeType] ?? ".bin";
|
|
69
|
+
const file = path.join(dir!, `image-${i + 1}${ext}`);
|
|
70
|
+
fs.writeFileSync(file, bytes, { mode: 0o600 });
|
|
71
|
+
return file;
|
|
72
|
+
});
|
|
73
|
+
return { dir, paths };
|
|
74
|
+
} catch {
|
|
75
|
+
// A mid-write failure must not leak a partial dir; the 24h sweep would
|
|
76
|
+
// reap it anyway, but the next staging call in this process is likely
|
|
77
|
+
// seconds away.
|
|
78
|
+
if (dir) {
|
|
79
|
+
try {
|
|
80
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
81
|
+
} catch {
|
|
82
|
+
// Sweep reaps it later.
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function buildImageNote(paths: string[]): string {
|
|
90
|
+
const list = paths.map((p) => `- ${p}`).join("\n");
|
|
91
|
+
return `[The user attached ${paths.length} image(s) to this message. They are staged at:\n${list}\nView them by calling the pi read tool on these exact paths; the image content is delivered to you directly.]`;
|
|
92
|
+
}
|