@aiti-ai/aiti-attach-agent 0.1.9 → 0.1.11
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/AGENTS.md +1 -0
- package/README.md +2 -3
- package/README.zh-CN.md +2 -3
- package/index.ts +12 -2
- package/package.json +12 -3
- package/pi-tui/pi-web-bridge.ts +20 -1
- package/registration-guard.d.mts +21 -0
- package/registration-guard.mjs +196 -0
- package/registration-guard.test.mjs +299 -0
- package/tools/deploy.mjs +70 -16
package/AGENTS.md
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
## 大改回源码仓
|
|
15
15
|
- 源码仓:`extensions/aiti-attach-agent/`(git 管理,deploy 同步回本目录)
|
|
16
16
|
- 改完在源码仓跑 `node tools/deploy.mjs`(或仓库根 `node scripts/deploy-all.mjs --only aiti-attach-agent`)
|
|
17
|
+
- TUI 侧只有一个注册通道:settings.json `packages` 已含 `@aiti-ai/pi-web-bridge`(npm 或本地路径)时,deploy 只刷新包内 src/dist,不再写 `~/.pi/agent/extensions/pi-web-bridge/`(否则 pi 双份加载 → `Tool "aiti_*" conflicts`);运行期 `registration-guard.mjs` 再做一道自检(两入口加载时调用,非权威副本自动让位;`AITI_PLUGIN_DUP_FORCE=1` 可强制)
|
|
17
18
|
|
|
18
19
|
## 数据目录(数据分层:config / cache)
|
|
19
20
|
- `ctx.configDir` 根级 = 配置与关键小状态(aiti-configs 备份范围;小、珍贵、人可读)
|
package/README.md
CHANGED
|
@@ -6,10 +6,9 @@ English · [简体中文](./README.zh-CN.md)
|
|
|
6
6
|
|
|
7
7
|
## About aiti
|
|
8
8
|
|
|
9
|
-
This package is part of the **aiti** ecosystem — a personal AI development workbench powered by [pi](https://pi.dev): **aiti-agent** (a self-hosted web workbench built on the open-source [pi-web](https://github.com/aiti-ai/
|
|
9
|
+
This package is part of the **aiti** ecosystem — a personal AI development workbench powered by [pi](https://pi.dev): **aiti-agent** (a self-hosted web workbench built on the open-source [pi-web](https://github.com/aiti-ai/aiti-ai)) plus debug injection into mainstream dev tools (aiti-devtools) and a rich extension system.
|
|
10
10
|
|
|
11
|
-
- Workbench
|
|
12
|
-
- Ecosystem monorepo: <https://github.com/aiti-ai/aiti-ai>
|
|
11
|
+
- Workbench & monorepo: <https://github.com/aiti-ai/aiti-ai>
|
|
13
12
|
- Site: <https://aiti.pw>
|
|
14
13
|
|
|
15
14
|
Category: Multi-agent backends · Tags: `attach` · `socket` · `tui` · `session` · `multi-agent`
|
package/README.zh-CN.md
CHANGED
|
@@ -6,10 +6,9 @@
|
|
|
6
6
|
|
|
7
7
|
## 关于 aiti
|
|
8
8
|
|
|
9
|
-
本包是 **aiti** 生态的组成部分——以 [pi](https://pi.dev) 为引擎的个人 AI 开发工作台与本地调试注入生态:**aiti-agent**(自托管 Web 工作台,基于开源项目 [pi-web](https://github.com/aiti-ai/
|
|
9
|
+
本包是 **aiti** 生态的组成部分——以 [pi](https://pi.dev) 为引擎的个人 AI 开发工作台与本地调试注入生态:**aiti-agent**(自托管 Web 工作台,基于开源项目 [pi-web](https://github.com/aiti-ai/aiti-ai) 构建,浏览器为主操作面)+ 各开发工具内的调试注入(aiti-devtools)+ 丰富的扩展体系。
|
|
10
10
|
|
|
11
|
-
-
|
|
12
|
-
- 生态仓库: <https://github.com/aiti-ai/aiti-ai>
|
|
11
|
+
- 工作台 / 生态仓库(aiti-agent,基于 pi-web): <https://github.com/aiti-ai/aiti-ai>
|
|
13
12
|
- 官网: <https://aiti.pw>
|
|
14
13
|
|
|
15
14
|
分类: 多 agent 后端 · tags: `attach` · `socket` · `tui` · `session` · `multi-agent`
|
package/index.ts
CHANGED
|
@@ -30,7 +30,7 @@ interface SessionCapabilitiesLike extends Record<string, boolean> {}
|
|
|
30
30
|
|
|
31
31
|
import { findLiveBridgeEntry, readBridgeRegistry } from "./bridge-registry.ts";
|
|
32
32
|
import { createSessionRecycleApi } from "@aiti-ai/ext-shared/session-recycle";
|
|
33
|
-
import { hostToolAllowed, hostToolsAllowFeature, parseHostToolsAllow, readHostToolsAllow } from "@aiti-ai/ext-shared/host-tools-allow";
|
|
33
|
+
import { hostToolAllowed, hostToolsAllowFeature, parseHostToolsAllow, readHostToolsAllow, hostToolsAllowFeatureI18nEn } from "@aiti-ai/ext-shared/host-tools-allow";
|
|
34
34
|
|
|
35
35
|
interface Socket {
|
|
36
36
|
write(payload: string): boolean;
|
|
@@ -446,7 +446,7 @@ const recycleApi = createSessionRecycleApi({
|
|
|
446
446
|
export default {
|
|
447
447
|
id: "aiti-attach-agent",
|
|
448
448
|
name: "Session Attach (socket 附着后端)",
|
|
449
|
-
icon: "
|
|
449
|
+
icon: "icons/radio-dot.svg",
|
|
450
450
|
|
|
451
451
|
// G1:aiti_bridge_req 转发的桥工具白名单(缺省只读子集;* = 全量)
|
|
452
452
|
features: [hostToolsAllowFeature()],
|
|
@@ -460,6 +460,7 @@ export default {
|
|
|
460
460
|
},
|
|
461
461
|
en: {
|
|
462
462
|
"ext.displayName": "Attach Session Backend",
|
|
463
|
+
...hostToolsAllowFeatureI18nEn(),
|
|
463
464
|
},
|
|
464
465
|
},
|
|
465
466
|
},
|
|
@@ -471,6 +472,11 @@ export default {
|
|
|
471
472
|
type: string;
|
|
472
473
|
label: string;
|
|
473
474
|
maxCapabilities: SessionCapabilitiesLike;
|
|
475
|
+
/**
|
|
476
|
+
* createSession() only connects to an already-running TUI bridge and
|
|
477
|
+
* never spawns a process — read paths may attach live sessions.
|
|
478
|
+
*/
|
|
479
|
+
attachOnly?: boolean;
|
|
474
480
|
ownsFile?(sessionFile: string): Promise<boolean> | boolean;
|
|
475
481
|
createSession(options: { sessionId?: string; sessionFile?: string; cwd?: string; socketPath?: string }): Promise<AttachSessionHandle>;
|
|
476
482
|
}): string;
|
|
@@ -485,6 +491,10 @@ export default {
|
|
|
485
491
|
type: "attach",
|
|
486
492
|
label: "Attached agent (socket)",
|
|
487
493
|
maxCapabilities: new AttachSessionHandle("cap-probe", "/nonexistent").capabilities,
|
|
494
|
+
// Socket attach only: createSession connects to the TUI bridge's live socket
|
|
495
|
+
// and never starts a process, so read-only paths (opening a session) may
|
|
496
|
+
// attach a running session instead of falling back to disk.
|
|
497
|
+
attachOnly: true,
|
|
488
498
|
// 占用判定:查自家桥注册表(TUI 扩展写入;格式归本扩展所有)
|
|
489
499
|
// 占用判定:查自家桥注册表(TUI 扩展写入;格式归本扩展所有)
|
|
490
500
|
// ⚠️ 必须 await:findLiveBridgeEntry 返回 Promise,不 await 则
|
package/package.json
CHANGED
|
@@ -1,14 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiti-ai/aiti-attach-agent",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.11",
|
|
4
4
|
"description": "; supports full automation via environment variables (PI_WEB_BRIDGE_AUTO=1 auto-bridges any CLI session); followUp queue echo + image attachment passthrough + idle time",
|
|
5
|
+
"displayNameI18n": {
|
|
6
|
+
"en": "Attach Session Backend"
|
|
7
|
+
},
|
|
8
|
+
"descriptionI18n": {
|
|
9
|
+
"zh-CN": "Socket 附着已运行 agent 进程 —— 连接 pi TUI bridge;支持环境变量全自动(PI_WEB_BRIDGE_AUTO=1 任何 CLI 会话自动上桥);followUp 排队回显 + 图片附件透传 + 空闲超时退出"
|
|
10
|
+
},
|
|
5
11
|
"soul": "不抢方向盘——agent 已经在跑,附着上去看就好。",
|
|
12
|
+
"soulI18n": {
|
|
13
|
+
"en": "Don't grab the steering wheel — the agent is already running; attach to it and watch."
|
|
14
|
+
},
|
|
6
15
|
"aitiExtProtocol": "1.0",
|
|
7
16
|
"dependencies": {
|
|
8
|
-
"@aiti-ai/ext-shared": "^0.1.
|
|
17
|
+
"@aiti-ai/ext-shared": "^0.1.17"
|
|
9
18
|
},
|
|
10
19
|
"license": "MIT",
|
|
11
|
-
"contentHash": "
|
|
20
|
+
"contentHash": "0f0f6492cce809ff",
|
|
12
21
|
"repository": {
|
|
13
22
|
"type": "git",
|
|
14
23
|
"url": "git+https://github.com/aiti-ai/aiti-ai.git",
|
package/pi-tui/pi-web-bridge.ts
CHANGED
|
@@ -34,7 +34,14 @@
|
|
|
34
34
|
* - pi-web in-process agents (PI_WEB_CHILD_MARKER): never auto-bridge / never
|
|
35
35
|
* register /web (already inside the web).
|
|
36
36
|
*
|
|
37
|
-
* Install:
|
|
37
|
+
* Install: `pi install npm:@aiti-ai/pi-web-bridge` (or add the package dir to
|
|
38
|
+
* settings.json `packages`). Register it through ONE channel only — a package entry
|
|
39
|
+
* already loads both pi.extensions (this file + the aiti-devtools-pi.js bundle); also
|
|
40
|
+
* dropping a copy into ~/.pi/agent/extensions/ makes pi load everything twice
|
|
41
|
+
* ("Tool \"aiti_*\" conflicts with …", two /web bridges). aiti-attach-agent's
|
|
42
|
+
* tools/deploy.mjs detects the package entry and skips the legacy dir install, and at
|
|
43
|
+
* runtime registration-guard.mjs makes the non-authoritative copy stand down even when
|
|
44
|
+
* both copies are already present.
|
|
38
45
|
*/
|
|
39
46
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
40
47
|
import { createServer, type Server, type Socket } from "node:net";
|
|
@@ -44,6 +51,7 @@ import { spawn, type ChildProcess } from "node:child_process";
|
|
|
44
51
|
// Shared bridge registry module (same package ../bridge-registry.ts; deployed along
|
|
45
52
|
// with the directory when installed as a directory extension)
|
|
46
53
|
import { registerBridge, unregisterBridge, bridgeSocketName } from "../bridge-registry";
|
|
54
|
+
import { checkDuplicateRegistration } from "../registration-guard.mjs";
|
|
47
55
|
|
|
48
56
|
// ── Protocol constants (aligned with aiti-attach-agent) ────────────────────────────────
|
|
49
57
|
const FORWARDED_EVENTS = [
|
|
@@ -217,6 +225,17 @@ function openBrowser(url: string): void {
|
|
|
217
225
|
}
|
|
218
226
|
|
|
219
227
|
export default function (pi: ExtensionAPI) {
|
|
228
|
+
// ── Duplicate-load guard (load-time safe, no pi API) ──────────────────────────────
|
|
229
|
+
// pi can load this plugin twice (settings `packages` + the legacy extensions dir).
|
|
230
|
+
// The guard picks the authoritative copy from settings/fs, so the other copy — no
|
|
231
|
+
// matter which one pi loaded first — registers nothing here (no second /web command,
|
|
232
|
+
// no second auto-bridge socket). See registration-guard.mjs.
|
|
233
|
+
const duplicate = checkDuplicateRegistration({ selfUrl: import.meta.url });
|
|
234
|
+
if (duplicate.standDown) {
|
|
235
|
+
console.log("[pi-web-bridge] skipping duplicate load (" + duplicate.reason + ")");
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
|
|
220
239
|
// ── Auto-bridge mode (aiti fork, §5.4 + CLI full-auto) ────────────────────────────────
|
|
221
240
|
// Switch = PI_WEB_BRIDGE_AUTO=1; two kinds of automation depending on process identity:
|
|
222
241
|
// ① HEADLESS_AUTO (subagents): injected by the pi-web host (instrumentation.ts, spawn
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Type declarations for registration-guard.mjs (runtime module is plain ESM). */
|
|
2
|
+
|
|
3
|
+
export declare const PI_PLUGIN_NAMES: Set<string>;
|
|
4
|
+
export declare const GUARD_FORCE_ENV: string;
|
|
5
|
+
|
|
6
|
+
export declare function defaultSettingsFiles(opts?: { agentDir?: string; cwd?: string }): string[];
|
|
7
|
+
export declare function defaultAgentDir(env?: Record<string, string | undefined>): string;
|
|
8
|
+
export declare function npmSpecName(source: string): string;
|
|
9
|
+
export declare function resolvePluginRoot(fromPath: string): { dir: string; meta: Record<string, unknown> | null };
|
|
10
|
+
export declare function findPluginEntry(opts?: {
|
|
11
|
+
settingsFiles?: string[];
|
|
12
|
+
agentDir?: string;
|
|
13
|
+
}): { source: string; dir: string | null; settingsFile: string } | null;
|
|
14
|
+
export declare function isGeneratedLegacyDir(dir: string): boolean;
|
|
15
|
+
export declare function checkDuplicateRegistration(opts: {
|
|
16
|
+
selfUrl: string;
|
|
17
|
+
settingsFiles?: string[];
|
|
18
|
+
agentDir?: string;
|
|
19
|
+
force?: boolean;
|
|
20
|
+
env?: Record<string, string | undefined>;
|
|
21
|
+
}): { standDown: boolean; selfDir: string; winner: string | null; reason: string | null };
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* registration-guard — load-time duplicate-registration guard for the pi-web-bridge plugin.
|
|
3
|
+
*
|
|
4
|
+
* pi can load the same plugin through two independent channels:
|
|
5
|
+
* ① settings.json `packages[]` — npm specs or local dirs, loaded via the package's
|
|
6
|
+
* own `package.json` → `pi.extensions`;
|
|
7
|
+
* ② the agent extensions dir (~/.pi/agent/extensions/) — every entry there is scanned
|
|
8
|
+
* automatically (the legacy deploy target).
|
|
9
|
+
* Hitting both registers every tool twice ("Tool \"aiti_*\" conflicts with …") and starts
|
|
10
|
+
* two `/web` bridges.
|
|
11
|
+
*
|
|
12
|
+
* pi offers no load-time self-inspection: `pi.getAllTools()` / `pi.getMcpServers()` are
|
|
13
|
+
* throwing stubs until the runner binds (only `registerTool()` works while loading). So
|
|
14
|
+
* the decision is made from the filesystem + settings, which is safe at any time:
|
|
15
|
+
*
|
|
16
|
+
* authority 1: the first settings `packages` entry naming this plugin (settings order
|
|
17
|
+
* is the user's precedence order). Only that copy registers; every other
|
|
18
|
+
* copy stands down — regardless of which one pi loaded first.
|
|
19
|
+
* authority 2: no settings entry → a process-global marker picks the first copy that
|
|
20
|
+
* registers, so an unexplained duplicate (e.g. the same dir symlinked
|
|
21
|
+
* twice into extensions/) still yields a single registration.
|
|
22
|
+
*
|
|
23
|
+
* Both entry points of the plugin (the TUI `/web` bridge and the `aiti_*` connector
|
|
24
|
+
* bundle) call `checkDuplicateRegistration()` before registering anything.
|
|
25
|
+
*
|
|
26
|
+
* This module is dependency-free (Node builtins only) and is shipped in three places:
|
|
27
|
+
* the extension dir (jiti, plain ESM), the published package (`src/`), and inlined into
|
|
28
|
+
* the connector bundle by esbuild.
|
|
29
|
+
*/
|
|
30
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
31
|
+
import { homedir } from "node:os";
|
|
32
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
33
|
+
import { fileURLToPath } from "node:url";
|
|
34
|
+
|
|
35
|
+
/** Package names this plugin has been published/installed under. */
|
|
36
|
+
export const PI_PLUGIN_NAMES = new Set(["@aiti-ai/pi-web-bridge", "pi-web-bridge"]);
|
|
37
|
+
|
|
38
|
+
/** Set to 1 to load every copy anyway (debugging). AITI_PI_EXT_FORCE implies this. */
|
|
39
|
+
export const GUARD_FORCE_ENV = "AITI_PLUGIN_DUP_FORCE";
|
|
40
|
+
|
|
41
|
+
const MARKER = Symbol.for("aiti-ai/pi-web-bridge#registration");
|
|
42
|
+
|
|
43
|
+
/** Default settings files pi reads: agent scope, then project scope. */
|
|
44
|
+
export function defaultSettingsFiles({ agentDir, cwd = process.cwd() } = {}) {
|
|
45
|
+
return [join(agentDir, "settings.json"), join(cwd, ".pi", "settings.json")];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Resolve the pi agent dir the same way pi does (PI_CODING_AGENT_DIR wins). */
|
|
49
|
+
export function defaultAgentDir(env = process.env) {
|
|
50
|
+
return env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Strip the version suffix of an npm spec, keeping the leading scope `@`. */
|
|
54
|
+
export function npmSpecName(source) {
|
|
55
|
+
return source.slice("npm:".length).replace(/@[^@/]+$/, "");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function readJsonSafe(file) {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function realpathOrSelf(path) {
|
|
67
|
+
try {
|
|
68
|
+
return realpathSync(path);
|
|
69
|
+
} catch {
|
|
70
|
+
return path;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Walk up from a file until the plugin's own package.json (max a few levels; the
|
|
76
|
+
* connector bundle lives in `dist/`, the TUI bridge in `src/` or the extension dir).
|
|
77
|
+
* @returns {{ dir: string, meta: Record<string, unknown>|null }}
|
|
78
|
+
*/
|
|
79
|
+
export function resolvePluginRoot(fromPath) {
|
|
80
|
+
let dir = dirname(fromPath);
|
|
81
|
+
for (let i = 0; i < 4; i++) {
|
|
82
|
+
const meta = readJsonSafe(join(dir, "package.json"));
|
|
83
|
+
if (meta && PI_PLUGIN_NAMES.has(meta.name)) return { dir, meta };
|
|
84
|
+
const parent = dirname(dir);
|
|
85
|
+
if (parent === dir) break;
|
|
86
|
+
dir = parent;
|
|
87
|
+
}
|
|
88
|
+
return { dir: dirname(fromPath), meta: null };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Find the settings-level registration of this plugin.
|
|
93
|
+
* Stale entries (path gone / npm package not installed) are ignored so a dead settings
|
|
94
|
+
* entry cannot disable every copy.
|
|
95
|
+
* @returns {{ source: string, dir: string|null, settingsFile: string }|null}
|
|
96
|
+
*/
|
|
97
|
+
export function findPluginEntry({ settingsFiles, agentDir = defaultAgentDir() } = {}) {
|
|
98
|
+
for (const settingsFile of settingsFiles || []) {
|
|
99
|
+
const packages = readJsonSafe(settingsFile)?.packages;
|
|
100
|
+
if (!Array.isArray(packages)) continue;
|
|
101
|
+
for (const item of packages) {
|
|
102
|
+
const source = typeof item === "string" ? item : item?.source;
|
|
103
|
+
if (typeof source !== "string" || !source) continue;
|
|
104
|
+
if (source.startsWith("npm:")) {
|
|
105
|
+
const name = npmSpecName(source);
|
|
106
|
+
if (!PI_PLUGIN_NAMES.has(name)) continue;
|
|
107
|
+
if (!existsSync(join(agentDir, "npm", "node_modules", name, "package.json"))) continue;
|
|
108
|
+
return { source, dir: null, settingsFile };
|
|
109
|
+
}
|
|
110
|
+
// Relative entries are ambiguous: resolve next to the settings file, then against
|
|
111
|
+
// its parent (project root for <root>/.pi/settings.json), then against cwd.
|
|
112
|
+
const candidates = [...new Set([
|
|
113
|
+
resolve(dirname(settingsFile), source),
|
|
114
|
+
resolve(dirname(dirname(settingsFile)), source),
|
|
115
|
+
resolve(source),
|
|
116
|
+
])];
|
|
117
|
+
for (const dir of candidates) {
|
|
118
|
+
if (!existsSync(join(dir, "package.json"))) continue;
|
|
119
|
+
if (!PI_PLUGIN_NAMES.has(readJsonSafe(join(dir, "package.json"))?.name)) continue;
|
|
120
|
+
return { source, dir, settingsFile };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* True when `dir` is the artifact written by the legacy directory install (our own
|
|
129
|
+
* package.json shape, `private: true`) — only that kind is safe to move away.
|
|
130
|
+
*/
|
|
131
|
+
export function isGeneratedLegacyDir(dir) {
|
|
132
|
+
const meta = readJsonSafe(join(dir, "package.json"));
|
|
133
|
+
return !!meta && meta.private === true && PI_PLUGIN_NAMES.has(meta.name) && Array.isArray(meta.pi?.extensions);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function isNpmInstalledCopy(dir, agentDir) {
|
|
137
|
+
const root = join(agentDir, "npm", "node_modules");
|
|
138
|
+
return (dir + sep).startsWith(realpathOrSelf(root) + sep) || (dir + sep).startsWith(root + sep);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Decide whether this loaded copy must stand down because another copy is authoritative.
|
|
143
|
+
* @param {{ selfUrl: string, settingsFiles?: string[], agentDir?: string, force?: boolean,
|
|
144
|
+
* env?: Record<string, string|undefined> }} opts
|
|
145
|
+
* @returns {{ standDown: boolean, selfDir: string, winner: string|null, reason: string|null }}
|
|
146
|
+
*/
|
|
147
|
+
export function checkDuplicateRegistration(opts) {
|
|
148
|
+
const env = opts.env || process.env;
|
|
149
|
+
const agentDir = opts.agentDir || defaultAgentDir(env);
|
|
150
|
+
const self = resolvePluginRoot(fileURLToPath(opts.selfUrl));
|
|
151
|
+
const selfDir = realpathOrSelf(self.dir);
|
|
152
|
+
const settingsFiles = opts.settingsFiles || defaultSettingsFiles({ agentDir, cwd: process.cwd() });
|
|
153
|
+
const force = opts.force === true || env[GUARD_FORCE_ENV] === "1" || env.AITI_PI_EXT_FORCE === "1";
|
|
154
|
+
const result = { standDown: false, selfDir, winner: null, reason: null };
|
|
155
|
+
|
|
156
|
+
if (force) {
|
|
157
|
+
globalThis[MARKER] = { dir: selfDir };
|
|
158
|
+
return result;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const entry = findPluginEntry({ settingsFiles, agentDir });
|
|
162
|
+
// Settings authority only applies to a copy we can identify as this plugin's package
|
|
163
|
+
// (package.json name match). A standalone connector bundle (e.g. packages/aiti-devtools-pi/
|
|
164
|
+
// dist dropped in by hand) has no such manifest: blocking it on a package entry could
|
|
165
|
+
// leave the session with NO tools at all, which is worse than a duplicate — those copies
|
|
166
|
+
// fall through to the process marker below.
|
|
167
|
+
if (entry && self.meta) {
|
|
168
|
+
if (entry.dir) {
|
|
169
|
+
const winnerDir = realpathOrSelf(entry.dir);
|
|
170
|
+
result.winner = winnerDir;
|
|
171
|
+
if (winnerDir !== selfDir) {
|
|
172
|
+
result.standDown = true;
|
|
173
|
+
result.reason = `another copy is registered as the pi package (${winnerDir})`;
|
|
174
|
+
}
|
|
175
|
+
} else {
|
|
176
|
+
result.winner = entry.source;
|
|
177
|
+
if (!isNpmInstalledCopy(selfDir, agentDir)) {
|
|
178
|
+
result.standDown = true;
|
|
179
|
+
result.reason = `the plugin is installed from npm (${entry.source}); this copy is not that install`;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (result.standDown) return result;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Whatever happens above, only one copy may claim the process marker: a second copy that
|
|
186
|
+
// slipped through resolves to "already registered" instead of colliding tool names.
|
|
187
|
+
const occupant = globalThis[MARKER];
|
|
188
|
+
if (occupant && occupant.dir && occupant.dir !== selfDir && existsSync(occupant.dir)) {
|
|
189
|
+
result.standDown = true;
|
|
190
|
+
result.winner = occupant.dir;
|
|
191
|
+
result.reason = `the plugin is already loaded from ${occupant.dir}`;
|
|
192
|
+
return result;
|
|
193
|
+
}
|
|
194
|
+
globalThis[MARKER] = { dir: selfDir };
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
// Tests for the load-time duplicate-registration guard: pi must load the pi-web-bridge
|
|
2
|
+
// plugin (TUI /web bridge + aiti_* connector) through exactly one channel.
|
|
3
|
+
import { test, beforeEach } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import {
|
|
10
|
+
PI_PLUGIN_NAMES,
|
|
11
|
+
checkDuplicateRegistration,
|
|
12
|
+
defaultSettingsFiles,
|
|
13
|
+
findPluginEntry,
|
|
14
|
+
isGeneratedLegacyDir,
|
|
15
|
+
npmSpecName,
|
|
16
|
+
resolvePluginRoot,
|
|
17
|
+
} from "./registration-guard.mjs";
|
|
18
|
+
|
|
19
|
+
const MARKER = Symbol.for("aiti-ai/pi-web-bridge#registration");
|
|
20
|
+
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
delete globalThis[MARKER];
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function sandbox() {
|
|
26
|
+
const root = mkdtempSync(join(tmpdir(), "pi-registration-"));
|
|
27
|
+
return { root, cleanup: () => rmSync(root, { recursive: true, force: true }) };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function writeSettings(dir, packages) {
|
|
31
|
+
mkdirSync(dir, { recursive: true });
|
|
32
|
+
const file = join(dir, "settings.json");
|
|
33
|
+
writeFileSync(file, JSON.stringify({ packages }, null, 2));
|
|
34
|
+
return file;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Create a plugin dir; `layout` puts the entry file in src/ (package) or dist/ (bundle). */
|
|
38
|
+
function writePlugin(dir, { name = "@aiti-ai/pi-web-bridge", private: isPrivate = false, layout = "src" } = {}) {
|
|
39
|
+
mkdirSync(join(dir, layout), { recursive: true });
|
|
40
|
+
writeFileSync(
|
|
41
|
+
join(dir, "package.json"),
|
|
42
|
+
JSON.stringify({ name, private: isPrivate, pi: { extensions: ["./a.ts"] } }, null, 2),
|
|
43
|
+
);
|
|
44
|
+
const entry = join(dir, layout, layout === "dist" ? "aiti-devtools-pi.js" : "pi-web-bridge.ts");
|
|
45
|
+
writeFileSync(entry, "// entry\n");
|
|
46
|
+
return { dir, entry, selfUrl: pathToFileURL(entry).href };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function npmInstall(agentDir, { name = "@aiti-ai/pi-web-bridge" } = {}) {
|
|
50
|
+
const dir = join(agentDir, "npm", "node_modules", name);
|
|
51
|
+
const pkg = writePlugin(dir, { name });
|
|
52
|
+
return pkg;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
test("npm specs: version suffix stripped, scoped name kept", () => {
|
|
56
|
+
assert.equal(npmSpecName("npm:@aiti-ai/pi-web-bridge@0.1.2"), "@aiti-ai/pi-web-bridge");
|
|
57
|
+
assert.equal(npmSpecName("npm:@aiti-ai/pi-web-bridge"), "@aiti-ai/pi-web-bridge");
|
|
58
|
+
assert.equal(npmSpecName("npm:pi-web-bridge@1.0.0"), "pi-web-bridge");
|
|
59
|
+
assert.equal(npmSpecName("npm:@aiti-ai/pi-subagents@0.89.0-aiti.1"), "@aiti-ai/pi-subagents");
|
|
60
|
+
assert.ok(PI_PLUGIN_NAMES.has(npmSpecName("npm:@aiti-ai/pi-web-bridge@0.1.2")));
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("resolvePluginRoot finds the package root from src/, dist/ and unknown dirs", () => {
|
|
64
|
+
const box = sandbox();
|
|
65
|
+
try {
|
|
66
|
+
const pkg = writePlugin(join(box.root, "pkg"));
|
|
67
|
+
assert.equal(resolvePluginRoot(pkg.entry).dir, pkg.dir);
|
|
68
|
+
const bundled = writePlugin(join(box.root, "bundled"), { layout: "dist" });
|
|
69
|
+
assert.equal(resolvePluginRoot(bundled.entry).dir, bundled.dir);
|
|
70
|
+
const loose = join(box.root, "loose");
|
|
71
|
+
mkdirSync(loose, { recursive: true });
|
|
72
|
+
const strayFile = join(loose, "x.ts");
|
|
73
|
+
writeFileSync(strayFile, "// x\n");
|
|
74
|
+
assert.equal(resolvePluginRoot(strayFile).dir, loose);
|
|
75
|
+
assert.equal(resolvePluginRoot(strayFile).meta, null);
|
|
76
|
+
} finally {
|
|
77
|
+
box.cleanup();
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test("findPluginEntry: npm spec requires the installed package", () => {
|
|
82
|
+
const box = sandbox();
|
|
83
|
+
try {
|
|
84
|
+
const agentDir = join(box.root, "agent");
|
|
85
|
+
const settings = writeSettings(agentDir, ["npm:pi-mcp-adapter", "npm:@aiti-ai/pi-web-bridge@0.1.2"]);
|
|
86
|
+
assert.equal(findPluginEntry({ settingsFiles: [settings], agentDir }), null, "not installed → stale entry ignored");
|
|
87
|
+
npmInstall(agentDir);
|
|
88
|
+
const hit = findPluginEntry({ settingsFiles: [settings], agentDir });
|
|
89
|
+
assert.equal(hit?.source, "npm:@aiti-ai/pi-web-bridge@0.1.2");
|
|
90
|
+
assert.equal(hit?.dir, null);
|
|
91
|
+
} finally {
|
|
92
|
+
box.cleanup();
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test("findPluginEntry: local path, relative paths, stale paths", () => {
|
|
97
|
+
const box = sandbox();
|
|
98
|
+
try {
|
|
99
|
+
const agentDir = join(box.root, "agent");
|
|
100
|
+
const pkg = writePlugin(join(box.root, "repo", "pi-plugins", "pi-web-bridge"));
|
|
101
|
+
const settings = writeSettings(agentDir, [join(box.root, "gone"), pkg.dir]);
|
|
102
|
+
assert.equal(findPluginEntry({ settingsFiles: [settings], agentDir })?.dir, pkg.dir);
|
|
103
|
+
|
|
104
|
+
const projectDir = join(box.root, "project");
|
|
105
|
+
const local = writePlugin(join(projectDir, "pi-web-bridge"));
|
|
106
|
+
const files = defaultSettingsFiles({ agentDir, cwd: projectDir });
|
|
107
|
+
assert.deepEqual(files, [join(agentDir, "settings.json"), join(projectDir, ".pi", "settings.json")]);
|
|
108
|
+
writeSettings(join(projectDir, ".pi"), ["./pi-web-bridge"]);
|
|
109
|
+
// agent scope comes first: the repo entry still wins while it is listed there
|
|
110
|
+
assert.equal(findPluginEntry({ settingsFiles: files, agentDir })?.dir, pkg.dir);
|
|
111
|
+
writeSettings(agentDir, []);
|
|
112
|
+
const hit = findPluginEntry({ settingsFiles: files, agentDir });
|
|
113
|
+
assert.equal(hit?.dir, local.dir);
|
|
114
|
+
assert.equal(hit?.source, "./pi-web-bridge");
|
|
115
|
+
} finally {
|
|
116
|
+
box.cleanup();
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("unrelated packages never count", () => {
|
|
121
|
+
const box = sandbox();
|
|
122
|
+
try {
|
|
123
|
+
const agentDir = join(box.root, "agent");
|
|
124
|
+
const other = writePlugin(join(box.root, "other"), { name: "@aiti-ai/pi-devtools-pi" });
|
|
125
|
+
const settings = writeSettings(agentDir, [
|
|
126
|
+
"npm:pi-mcp-adapter",
|
|
127
|
+
"npm:@aiti-ai/pi-subagents@0.89.0-aiti.1",
|
|
128
|
+
other.dir,
|
|
129
|
+
join(box.root, "does-not-exist"),
|
|
130
|
+
]);
|
|
131
|
+
assert.equal(findPluginEntry({ settingsFiles: [settings], agentDir }), null);
|
|
132
|
+
} finally {
|
|
133
|
+
box.cleanup();
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test("only the deploy-generated legacy dir is considered safe to remove", () => {
|
|
138
|
+
const box = sandbox();
|
|
139
|
+
try {
|
|
140
|
+
const generated = writePlugin(join(box.root, "extensions", "pi-web-bridge"), { name: "pi-web-bridge", private: true });
|
|
141
|
+
assert.equal(isGeneratedLegacyDir(generated.dir), true);
|
|
142
|
+
const userOwned = writePlugin(join(box.root, "extensions", "my-ext"), { name: "my-ext" });
|
|
143
|
+
assert.equal(isGeneratedLegacyDir(userOwned.dir), false);
|
|
144
|
+
const published = writePlugin(join(box.root, "extensions", "copy"), { name: "@aiti-ai/pi-web-bridge" });
|
|
145
|
+
assert.equal(isGeneratedLegacyDir(published.dir), false, "a real (non-private) package dir must never be moved");
|
|
146
|
+
assert.equal(isGeneratedLegacyDir(join(box.root, "absent")), false);
|
|
147
|
+
} finally {
|
|
148
|
+
box.cleanup();
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("registered package copy registers; a second copy stands down", () => {
|
|
153
|
+
const box = sandbox();
|
|
154
|
+
try {
|
|
155
|
+
const agentDir = join(box.root, "agent");
|
|
156
|
+
const repo = writePlugin(join(box.root, "repo", "pi-plugins", "pi-web-bridge"));
|
|
157
|
+
const legacy = writePlugin(join(agentDir, "extensions", "pi-web-bridge"), { name: "pi-web-bridge", private: true });
|
|
158
|
+
const settingsFiles = [writeSettings(agentDir, [repo.dir])];
|
|
159
|
+
|
|
160
|
+
const winner = checkDuplicateRegistration({ selfUrl: repo.selfUrl, settingsFiles, agentDir, env: {} });
|
|
161
|
+
assert.equal(winner.standDown, false);
|
|
162
|
+
|
|
163
|
+
const loser = checkDuplicateRegistration({ selfUrl: legacy.selfUrl, settingsFiles, agentDir, env: {} });
|
|
164
|
+
assert.equal(loser.standDown, true);
|
|
165
|
+
assert.equal(loser.winner, repo.dir);
|
|
166
|
+
assert.match(loser.reason, /registered as the pi package/);
|
|
167
|
+
} finally {
|
|
168
|
+
box.cleanup();
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("settings order decides between two package copies (load order irrelevant)", () => {
|
|
173
|
+
const box = sandbox();
|
|
174
|
+
try {
|
|
175
|
+
const agentDir = join(box.root, "agent");
|
|
176
|
+
const first = writePlugin(join(box.root, "first"));
|
|
177
|
+
const second = writePlugin(join(box.root, "second"));
|
|
178
|
+
const settingsFiles = [writeSettings(agentDir, [first.dir, second.dir])];
|
|
179
|
+
|
|
180
|
+
assert.equal(checkDuplicateRegistration({ selfUrl: second.selfUrl, settingsFiles, agentDir, env: {} }).standDown, true);
|
|
181
|
+
assert.equal(checkDuplicateRegistration({ selfUrl: first.selfUrl, settingsFiles, agentDir, env: {} }).standDown, false);
|
|
182
|
+
} finally {
|
|
183
|
+
box.cleanup();
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("npm-installed copy wins over a stray dir; repo copy stands down", () => {
|
|
188
|
+
const box = sandbox();
|
|
189
|
+
try {
|
|
190
|
+
const agentDir = join(box.root, "agent");
|
|
191
|
+
const installed = npmInstall(agentDir);
|
|
192
|
+
const repo = writePlugin(join(box.root, "repo", "pi-plugins", "pi-web-bridge"));
|
|
193
|
+
const settingsFiles = [writeSettings(agentDir, ["npm:@aiti-ai/pi-web-bridge@0.1.2"])];
|
|
194
|
+
|
|
195
|
+
assert.equal(checkDuplicateRegistration({ selfUrl: installed.selfUrl, settingsFiles, agentDir, env: {} }).standDown, false);
|
|
196
|
+
const loser = checkDuplicateRegistration({ selfUrl: repo.selfUrl, settingsFiles, agentDir, env: {} });
|
|
197
|
+
assert.equal(loser.standDown, true);
|
|
198
|
+
assert.match(loser.reason, /installed from npm/);
|
|
199
|
+
} finally {
|
|
200
|
+
box.cleanup();
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
test("no settings entry: first loaded copy wins, a second copy stands down", () => {
|
|
205
|
+
const box = sandbox();
|
|
206
|
+
try {
|
|
207
|
+
const agentDir = join(box.root, "agent");
|
|
208
|
+
const a = writePlugin(join(agentDir, "extensions", "pi-web-bridge"), { name: "pi-web-bridge", private: true });
|
|
209
|
+
const b = writePlugin(join(box.root, "elsewhere"));
|
|
210
|
+
const settingsFiles = [writeSettings(agentDir, [])];
|
|
211
|
+
|
|
212
|
+
assert.equal(checkDuplicateRegistration({ selfUrl: a.selfUrl, settingsFiles, agentDir, env: {} }).standDown, false);
|
|
213
|
+
const second = checkDuplicateRegistration({ selfUrl: b.selfUrl, settingsFiles, agentDir, env: {} });
|
|
214
|
+
assert.equal(second.standDown, true);
|
|
215
|
+
assert.equal(second.winner, a.dir);
|
|
216
|
+
// same dir again (e.g. /reload) must stay allowed
|
|
217
|
+
assert.equal(checkDuplicateRegistration({ selfUrl: a.selfUrl, settingsFiles, agentDir, env: {} }).standDown, false);
|
|
218
|
+
} finally {
|
|
219
|
+
box.cleanup();
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
test("a standalone connector bundle (no own manifest) is never blocked by a package entry", () => {
|
|
224
|
+
const box = sandbox();
|
|
225
|
+
try {
|
|
226
|
+
const agentDir = join(box.root, "agent");
|
|
227
|
+
const repo = writePlugin(join(box.root, "repo", "pi-plugins", "pi-web-bridge"));
|
|
228
|
+
// packages/aiti-devtools-pi/dist style copy: unrelated package.json, name not ours
|
|
229
|
+
const standaloneDir = join(box.root, "repo", "packages", "aiti-devtools-pi");
|
|
230
|
+
mkdirSync(join(standaloneDir, "dist"), { recursive: true });
|
|
231
|
+
writeFileSync(join(standaloneDir, "package.json"), JSON.stringify({ name: "@aiti-ai/aiti-devtools-pi" }));
|
|
232
|
+
const standaloneFile = join(standaloneDir, "dist", "aiti-devtools-pi.js");
|
|
233
|
+
writeFileSync(standaloneFile, "// bundle\n");
|
|
234
|
+
const settingsFiles = [writeSettings(agentDir, [repo.dir])];
|
|
235
|
+
|
|
236
|
+
const r = checkDuplicateRegistration({
|
|
237
|
+
selfUrl: pathToFileURL(standaloneFile).href,
|
|
238
|
+
settingsFiles,
|
|
239
|
+
agentDir,
|
|
240
|
+
env: {},
|
|
241
|
+
});
|
|
242
|
+
assert.equal(r.standDown, false, "tools must never disappear because of a foreign manifest");
|
|
243
|
+
assert.equal(r.selfDir, join(standaloneDir, "dist"));
|
|
244
|
+
} finally {
|
|
245
|
+
box.cleanup();
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
test("marker still keeps a standalone bundle and a package copy to one registration", () => {
|
|
250
|
+
const box = sandbox();
|
|
251
|
+
try {
|
|
252
|
+
const agentDir = join(box.root, "agent");
|
|
253
|
+
const repo = writePlugin(join(box.root, "repo", "pi-plugins", "pi-web-bridge"));
|
|
254
|
+
const standaloneDir = join(box.root, "repo", "packages", "aiti-devtools-pi");
|
|
255
|
+
mkdirSync(join(standaloneDir, "dist"), { recursive: true });
|
|
256
|
+
writeFileSync(join(standaloneDir, "package.json"), JSON.stringify({ name: "@aiti-ai/aiti-devtools-pi" }));
|
|
257
|
+
const standaloneFile = join(standaloneDir, "dist", "aiti-devtools-pi.js");
|
|
258
|
+
writeFileSync(standaloneFile, "// bundle\n");
|
|
259
|
+
const settingsFiles = [writeSettings(agentDir, [repo.dir])];
|
|
260
|
+
|
|
261
|
+
const first = checkDuplicateRegistration({ selfUrl: pathToFileURL(standaloneFile).href, settingsFiles, agentDir, env: {} });
|
|
262
|
+
assert.equal(first.standDown, false);
|
|
263
|
+
const second = checkDuplicateRegistration({ selfUrl: repo.selfUrl, settingsFiles, agentDir, env: {} });
|
|
264
|
+
assert.equal(second.standDown, true, "the package copy defers to the already-registered bundle");
|
|
265
|
+
assert.match(second.reason, /already loaded from/);
|
|
266
|
+
} finally {
|
|
267
|
+
box.cleanup();
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
test("a dead owner directory does not block a later copy", () => {
|
|
272
|
+
const box = sandbox();
|
|
273
|
+
try {
|
|
274
|
+
const agentDir = join(box.root, "agent");
|
|
275
|
+
const gone = writePlugin(join(box.root, "gone"));
|
|
276
|
+
const live = writePlugin(join(box.root, "live"));
|
|
277
|
+
const settingsFiles = [writeSettings(agentDir, [])];
|
|
278
|
+
globalThis[MARKER] = { dir: gone.dir };
|
|
279
|
+
rmSync(gone.dir, { recursive: true, force: true });
|
|
280
|
+
assert.equal(checkDuplicateRegistration({ selfUrl: live.selfUrl, settingsFiles, agentDir, env: {} }).standDown, false);
|
|
281
|
+
} finally {
|
|
282
|
+
box.cleanup();
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
test("force env bypasses the guard", () => {
|
|
287
|
+
const box = sandbox();
|
|
288
|
+
try {
|
|
289
|
+
const agentDir = join(box.root, "agent");
|
|
290
|
+
const repo = writePlugin(join(box.root, "repo"));
|
|
291
|
+
const legacy = writePlugin(join(agentDir, "extensions", "pi-web-bridge"), { name: "pi-web-bridge", private: true });
|
|
292
|
+
const settingsFiles = [writeSettings(agentDir, [repo.dir])];
|
|
293
|
+
for (const env of [{ AITI_PLUGIN_DUP_FORCE: "1" }, { AITI_PI_EXT_FORCE: "1" }]) {
|
|
294
|
+
assert.equal(checkDuplicateRegistration({ selfUrl: legacy.selfUrl, settingsFiles, agentDir, env }).standDown, false);
|
|
295
|
+
}
|
|
296
|
+
} finally {
|
|
297
|
+
box.cleanup();
|
|
298
|
+
}
|
|
299
|
+
});
|
package/tools/deploy.mjs
CHANGED
|
@@ -8,6 +8,13 @@
|
|
|
8
8
|
* ├ index.ts = pi-tui/pi-web-bridge.ts(唯一源,替代旧三副本手工同步)
|
|
9
9
|
* ├ bridge-registry.ts 共享注册表
|
|
10
10
|
* └ aiti-devtools-pi.js 连接器 bundle(packages/aiti-devtools-pi esbuild 产物)
|
|
11
|
+
* ⚠ Only write this directory on machines WITHOUT a package-level registration:
|
|
12
|
+
* when settings.json `packages` already contains @aiti-ai/pi-web-bridge (an npm spec
|
|
13
|
+
* or a local dir such as /…/aiti-ai/pi-plugins/pi-web-bridge), pi loads the same
|
|
14
|
+
* plugin through the package's own pi.extensions — writing this dir too would
|
|
15
|
+
* register everything twice (pi reports `Tool "aiti_*" conflicts with …` and /web
|
|
16
|
+
* starts two bridges). In that case this script only refreshes the package's
|
|
17
|
+
* src/dist (sync-src) and moves a stale legacy dir out of the scan path.
|
|
11
18
|
* ② ~/.pi/web-dev/extensions/aiti-attach-agent/index.ts pi-web dev(重启 dev 生效)
|
|
12
19
|
* ③ ~/.pi/web/extensions/aiti-attach-agent/index.ts pi-web prod(重启 prod 生效)
|
|
13
20
|
* ④ ~/.pi/web{,-dev}/extensions/aiti-devtools/bridge-core.ts 桥核心(单例跨 reload,必须重启 pi-web)
|
|
@@ -22,15 +29,17 @@
|
|
|
22
29
|
* packages/aiti-devtools-core/src/bridge.ts 桥核心唯一源
|
|
23
30
|
* index.ts(本目录) pi-web 端 attach 后端唯一源
|
|
24
31
|
*/
|
|
25
|
-
import { resolve, dirname, join,
|
|
32
|
+
import { resolve, dirname, join, sep } from "node:path";
|
|
26
33
|
import { fileURLToPath } from "node:url";
|
|
27
|
-
import { copyFileSync, mkdirSync, existsSync,
|
|
34
|
+
import { copyFileSync, mkdirSync, existsSync, writeFileSync, renameSync, readFileSync } from "node:fs";
|
|
28
35
|
import { homedir } from "node:os";
|
|
36
|
+
import { execFileSync } from "node:child_process";
|
|
37
|
+
import { defaultSettingsFiles, findPluginEntry, isGeneratedLegacyDir } from "../registration-guard.mjs";
|
|
29
38
|
import { notifyReconcile } from "../../_shared/reconcile-deps.mjs";
|
|
30
39
|
|
|
31
40
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
32
|
-
const pkg = resolve(here, ".."); //
|
|
33
|
-
const repo = resolve(pkg, "..", ".."); // repo root
|
|
41
|
+
const pkg = resolve(here, ".."); // extensions/aiti-attach-agent
|
|
42
|
+
const repo = resolve(pkg, "..", ".."); // aiti-ai repo root
|
|
34
43
|
const coreBridge = resolve(repo, "packages", "aiti-devtools-core", "src", "bridge.ts");
|
|
35
44
|
const piPkg = resolve(repo, "packages", "aiti-devtools-pi");
|
|
36
45
|
const bundleSrc = resolve(piPkg, "dist", "aiti-devtools-pi.js");
|
|
@@ -41,6 +50,27 @@ const coreDirs = [join(agent, ".pi", "web-dev", "extensions", "aiti-devtools"),
|
|
|
41
50
|
|
|
42
51
|
const copy = (src, dest) => { mkdirSync(dirname(dest), { recursive: true }); copyFileSync(src, dest); console.log(" ✓ " + dest.replace(agent, "~")); };
|
|
43
52
|
|
|
53
|
+
// ── Single-registration guard (the TUI plugin must have exactly one source) ────────
|
|
54
|
+
// pi has two load channels: ① settings.json `packages[]` (npm specs or local dirs, loaded
|
|
55
|
+
// via the package's pi.extensions) and ② directories under ~/.pi/agent/extensions/ (scanned
|
|
56
|
+
// automatically). Hitting both registers the same /web bridge + aiti_* tools twice, so this
|
|
57
|
+
// script treats ① as authoritative when it is present. Detection is shared with the runtime
|
|
58
|
+
// guard (../registration-guard.mjs) that both entry points call at load time — this script
|
|
59
|
+
// additionally cleans up a stale legacy dir so users do not need to.
|
|
60
|
+
const piAgentDir = process.env.PI_CODING_AGENT_DIR || join(agent, ".pi", "agent");
|
|
61
|
+
const settingsFiles = defaultSettingsFiles({ agentDir: piAgentDir });
|
|
62
|
+
|
|
63
|
+
/** Refresh the registered local package view (src/ + dist/) so pi loads current code. */
|
|
64
|
+
function refreshPackageView(dir) {
|
|
65
|
+
const sync = join(dir, "tools", "sync-src.mjs");
|
|
66
|
+
if (!existsSync(sync)) return;
|
|
67
|
+
try {
|
|
68
|
+
execFileSync(process.execPath, [sync], { stdio: "inherit", cwd: dir });
|
|
69
|
+
} catch (e) {
|
|
70
|
+
console.log(" ⚠ 包内 src/dist 刷新失败(不影响部署,可手动跑 node tools/sync-src.mjs):" + String((e && e.message) || e));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
44
74
|
console.log("── aiti-attach-agent 部署 ──");
|
|
45
75
|
|
|
46
76
|
// 1) 连接器 bundle(esbuild:内联 core+agent,外置 pi SDK/typebox 由 jiti 提供)
|
|
@@ -49,21 +79,45 @@ if (process.argv.includes("--no-build")) {
|
|
|
49
79
|
console.log("① 跳过 bundle 构建(--no-build)");
|
|
50
80
|
} else {
|
|
51
81
|
console.log("① 构建连接器 bundle…");
|
|
52
|
-
const { execFileSync } = await import("node:child_process");
|
|
53
82
|
execFileSync(process.execPath, [resolve(piPkg, "tools", "build.mjs")], { stdio: "inherit", cwd: piPkg });
|
|
54
83
|
}
|
|
55
84
|
|
|
56
|
-
// 2) TUI
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
85
|
+
// 2) TUI plugin: with a package registration only refresh that package, else install the dir
|
|
86
|
+
const registered = findPluginEntry({ settingsFiles });
|
|
87
|
+
if (registered) {
|
|
88
|
+
console.log("② TUI 扩展:已由 pi 包注册(" + registered.source + ")— 跳过目录安装");
|
|
89
|
+
if (existsSync(tuiDir) && isGeneratedLegacyDir(tuiDir)) {
|
|
90
|
+
if (process.argv.includes("--keep-legacy-tui")) {
|
|
91
|
+
console.log(" ⚠ 旧目录仍存在(--keep-legacy-tui):会被 pi 当第二套扩展加载,工具名会冲突");
|
|
92
|
+
} else {
|
|
93
|
+
// Renaming inside the same extensions/ dir would still get scanned → move it out.
|
|
94
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
95
|
+
const backup = join(agent, ".pi", "agent", "legacy-extensions-backup", "pi-web-bridge-" + stamp);
|
|
96
|
+
mkdirSync(dirname(backup), { recursive: true });
|
|
97
|
+
renameSync(tuiDir, backup);
|
|
98
|
+
console.log(" ⚠ 移走重复注册的旧目录 → " + backup.replace(agent, "~"));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (registered.dir && (registered.dir + sep).startsWith(repo + sep)) refreshPackageView(registered.dir);
|
|
102
|
+
} else {
|
|
103
|
+
console.log("② TUI 扩展 → " + tuiDir.replace(agent, "~"));
|
|
104
|
+
mkdirSync(tuiDir, { recursive: true });
|
|
105
|
+
// The deployed dir is flat, so rewrite the two "../" imports of the source file.
|
|
106
|
+
const tuiEntry = readFileSync(resolve(pkg, "pi-tui", "pi-web-bridge.ts"), "utf8")
|
|
107
|
+
.replace(/from "\.\.\/bridge-registry"/g, 'from "./bridge-registry"')
|
|
108
|
+
.replace(/from "\.\.\/registration-guard\.mjs"/g, 'from "./registration-guard.mjs"');
|
|
109
|
+
writeFileSync(join(tuiDir, "index.ts"), tuiEntry);
|
|
110
|
+
console.log(" ✓ " + join(tuiDir, "index.ts").replace(agent, "~"));
|
|
111
|
+
copy(resolve(pkg, "bridge-registry.ts"), join(tuiDir, "bridge-registry.ts"));
|
|
112
|
+
copy(resolve(pkg, "registration-guard.mjs"), join(tuiDir, "registration-guard.mjs"));
|
|
113
|
+
copy(resolve(pkg, "registration-guard.d.mts"), join(tuiDir, "registration-guard.d.mts"));
|
|
114
|
+
copy(bundleSrc, join(tuiDir, "aiti-devtools-pi.js"));
|
|
115
|
+
// pi multi-entry manifest: index.ts (/web bridge) + aiti-devtools-pi.js (aiti_* connector)
|
|
116
|
+
writeFileSync(join(tuiDir, "package.json"), JSON.stringify({
|
|
117
|
+
name: "pi-web-bridge", private: true,
|
|
118
|
+
pi: { extensions: ["index.ts", "aiti-devtools-pi.js"] },
|
|
119
|
+
}, null, 2) + "\n");
|
|
120
|
+
}
|
|
67
121
|
|
|
68
122
|
// 3) pi-web 端 attach 后端(dev 必重启;prod 重启生效)
|
|
69
123
|
console.log("③ pi-web attach 后端…");
|