@aiti-ai/aiti-attach-agent 0.1.9 → 0.1.12
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 +73 -19
- package/dev-pack.mjs +0 -259
- package/reconcile-deps.mjs +0 -41
- package/reload-instances.mjs +0 -60
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.12",
|
|
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": "b5f3f409401499da",
|
|
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";
|
|
29
|
-
import {
|
|
36
|
+
import { execFileSync } from "node:child_process";
|
|
37
|
+
import { defaultSettingsFiles, findPluginEntry, isGeneratedLegacyDir } from "../registration-guard.mjs";
|
|
38
|
+
import { notifyReconcile } from "@aiti-ai/ext-shared/reconcile-deps";
|
|
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 后端…");
|
|
@@ -93,7 +147,7 @@ await notifyReconcile();
|
|
|
93
147
|
|
|
94
148
|
// ── 双实例热重载(basePath 双 env 按机器设值)——允许失败:服务未启动/共享模块缺失仅提示,不影响 deploy 退出码 ──
|
|
95
149
|
try {
|
|
96
|
-
const { reloadInstances } = await import("
|
|
150
|
+
const { reloadInstances } = await import("@aiti-ai/ext-shared/reload-instances");
|
|
97
151
|
await reloadInstances();
|
|
98
152
|
} catch (e) {
|
|
99
153
|
console.log("[deploy] 自动 reload 未执行(" + String((e && e.message) || e) + ")— 需手动 POST /api/extensions/reload");
|
|
@@ -101,7 +155,7 @@ try {
|
|
|
101
155
|
|
|
102
156
|
// ── dev-pack(方案 §3.2:源码+构建工具+AGENTS.md 直达部署目录,AI 可现场直改)——允许失败,不影响 deploy 退出码 ──
|
|
103
157
|
try {
|
|
104
|
-
const { packDevPack } = await import("
|
|
158
|
+
const { packDevPack } = await import("@aiti-ai/ext-shared/dev-pack");
|
|
105
159
|
packDevPack({ extRoot: resolve(import.meta.dirname, ".."), log: (m) => console.log("[deploy] " + m) });
|
|
106
160
|
} catch (e) {
|
|
107
161
|
console.log("[deploy] dev-pack 未执行(" + String((e && e.message) || e) + ")");
|
package/dev-pack.mjs
DELETED
|
@@ -1,259 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* pi-web-ext · dev-pack 共享实现(方案 §3.2 / M5:扩展 dev-pack——src + 构建工具 + AGENTS.md 直达部署目录)
|
|
3
|
-
*
|
|
4
|
-
* 目标:用户在 AI 窗对 AI 说「帮我改一下 xxx 扩展」时,AI 能在**部署目录**直接:
|
|
5
|
-
* 读 AGENTS.md → 改 src/ → node tools/build.mjs → curl reload → 浏览器生效,不等回开发机。
|
|
6
|
-
*
|
|
7
|
-
* 各扩展 tools/deploy.mjs 末尾统一追加一段(见本文件同级各 deploy.mjs 模式):
|
|
8
|
-
* const { packDevPack } = await import("../../_shared/dev-pack.mjs");
|
|
9
|
-
* packDevPack({ extRoot: <扩展源码根>, log: console.log });
|
|
10
|
-
*
|
|
11
|
-
* packDevPack 向每个已存在的部署目录(~/.pi/web{,-dev}/extensions/<extId>)写入:
|
|
12
|
-
* AGENTS.md 源码目录有则拷,无则由模板生成(§3.4)
|
|
13
|
-
* src/ client/src/**、根级服务端源码 *.ts/*.cjs/*.mjs、lib/(跳 vendor)、server/、sched/、worker-src/
|
|
14
|
-
* tools/build.mjs 现场构建入口(扩展自带则拷真身,否则生成 esbuild 默认版)
|
|
15
|
-
* tools/deploy.mjs 部署脚本本身(大改后回源码仓重部署的入口)
|
|
16
|
-
* package.json 含 aitiConfigs 声明与 build 脚本
|
|
17
|
-
* vite.config.ts 有则拷
|
|
18
|
-
*
|
|
19
|
-
* 幂等:重复部署整目录覆盖;允许失败:任何异常只 log 不影响 deploy 退出码(调用方 try/catch)。
|
|
20
|
-
*/
|
|
21
|
-
"use strict";
|
|
22
|
-
import { homedir } from "node:os";
|
|
23
|
-
import { join, resolve, dirname, basename, sep as pathSep } from "node:path";
|
|
24
|
-
import {
|
|
25
|
-
existsSync, readdirSync, statSync, mkdirSync, cpSync, rmSync, writeFileSync, readFileSync,
|
|
26
|
-
} from "node:fs";
|
|
27
|
-
|
|
28
|
-
// 根级服务端源码文件:拷进 src/(运行时平铺文件在部署根不动,宿主 loader 路径不变)
|
|
29
|
-
const ROOT_SRC_EXTS = new Set([".ts", ".tsx", ".cjs", ".mjs"]);
|
|
30
|
-
const ROOT_SRC_SKIP = new Set(["dist", "node_modules"]);
|
|
31
|
-
// 源码子目录:整目录拷(vendor 类大资产跳过——部署目录本就有运行时副本)
|
|
32
|
-
const SRC_DIRS = ["client/src", "server", "lib", "sched", "worker-src"];
|
|
33
|
-
const DIR_SKIP = new Set(["vendor", "__pycache__", "node_modules"]);
|
|
34
|
-
|
|
35
|
-
function copyTree(src, dest, skip) {
|
|
36
|
-
mkdirSync(dest, { recursive: true });
|
|
37
|
-
for (const en of readdirSync(src, { withFileTypes: true })) {
|
|
38
|
-
if (skip && skip.has(en.name)) continue;
|
|
39
|
-
const s = join(src, en.name), d = join(dest, en.name);
|
|
40
|
-
if (en.isDirectory()) copyTree(s, d, skip);
|
|
41
|
-
else if (en.isFile()) cpSync(s, d);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** AGENTS.md 默认模板(§3.4;扩展自带 AGENTS.md 则不走到这里)。供 CLI 批量生成源码目录版复用。 */
|
|
46
|
-
export function agentsMdTemplate(extId) {
|
|
47
|
-
return `# ${extId} 扩展(部署目录直改指南)
|
|
48
|
-
|
|
49
|
-
## 结构
|
|
50
|
-
- 运行时文件平铺在本目录根(index.ts / core.cjs …,宿主 loader 按相对路径加载——**禁手改运行时平铺文件**,改 src/ 再 build)
|
|
51
|
-
- \`src/\` 源码(client/src + 服务端 ts/cjs)· \`dist/\` 构建产物(禁手改)· \`tools/\` 构建/部署脚本
|
|
52
|
-
- npm 包形态的扩展:本目录 package.json 含 version 与 aitiConfigs 声明
|
|
53
|
-
|
|
54
|
-
## 小改现场流程(改文案/样式/小逻辑)
|
|
55
|
-
1. 改 \`src/\` 下对应源码
|
|
56
|
-
2. \`node tools/build.mjs\`(client 有构建产物的扩展;纯服务端改动跳过)
|
|
57
|
-
3. \`curl -X POST http://127.0.0.1:3001/api/extensions/reload\`(dev;prod 3002;外部经 nginx 带 basePath:/dev、/mac、/mdev、/win、/wdev → \`/xxx/api/extensions/reload\`)
|
|
58
|
-
4. 浏览器刷新页面验证
|
|
59
|
-
|
|
60
|
-
## 大改回源码仓
|
|
61
|
-
- 源码仓:\`extensions/${extId}/\`(git 管理,deploy 同步回本目录)
|
|
62
|
-
- 改完在源码仓跑 \`node tools/deploy.mjs\`(或仓库根 \`node scripts/deploy-all.mjs --only ${extId}\`)
|
|
63
|
-
|
|
64
|
-
## 数据目录(数据分层:config / cache)
|
|
65
|
-
- \`ctx.configDir\` 根级 = 配置与关键小状态(aiti-configs 备份范围;小、珍贵、人可读)
|
|
66
|
-
- \`ctx.cacheDir\`(= \`<configDir>/cache/\`)= 可删缓存:db/venv/日志/大文件;rm -rf 后扩展下次访问自动重建
|
|
67
|
-
- \`ctx.dataDir\` 已移除(访问即抛)——新代码禁用
|
|
68
|
-
- 本扩展白名单(永不为 cache 的配置文件)见 package.json \`aitiConfigs.configFiles\`
|
|
69
|
-
|
|
70
|
-
## 红线
|
|
71
|
-
- 禁轮询(setInterval 拉取);需要等待用事件/回调/SSE(桥的 SSE、aiti-event-bus topics)
|
|
72
|
-
- 禁重启生产服务(pi-web 3002 等 restart 须用户明确同意)
|
|
73
|
-
- 禁手改 dist/ 与运行时平铺文件;跨扩展通信走 ctx.services(禁 globalThis.__ext 直穿)
|
|
74
|
-
- 服务端:SQLite 一律 WAL + 分批小事务(批间 setImmediate 让步);禁 execFileSync 调 >1s 外部程序;>8MB 文件禁同步读
|
|
75
|
-
`;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** 默认 tools/build.mjs(esbuild 单包零配置;扩展自带 tools/build.mjs 则不走到这里)。 */
|
|
79
|
-
function buildMjsTemplate(extId, extRoot, clientOut, entryRel) {
|
|
80
|
-
// No hardcoded checkout path: candidates are resolved at run time (see repoCandidates below).
|
|
81
|
-
return `/**
|
|
82
|
-
* ${extId} · 现场构建入口(dev-pack 默认模板,esbuild 单包零配置)
|
|
83
|
-
* 用法:node tools/build.mjs
|
|
84
|
-
* 本文件由 dev-pack 生成;复杂构建(多入口/插件链)请参照 src/vite.config.ts 改写本文件或回源码仓构建。
|
|
85
|
-
*/
|
|
86
|
-
"use strict";
|
|
87
|
-
import { existsSync, readdirSync, constants as fsConstants, accessSync } from "node:fs";
|
|
88
|
-
import { join, resolve, dirname, basename, sep as pathSep } from "node:path";
|
|
89
|
-
import { fileURLToPath } from "node:url";
|
|
90
|
-
import { spawnSync } from "node:child_process";
|
|
91
|
-
|
|
92
|
-
const here = dirname(fileURLToPath(import.meta.url));
|
|
93
|
-
const extRoot = resolve(here, "..");
|
|
94
|
-
const clientOut = ${JSON.stringify(clientOut || "dist/client-bundle.mjs")};
|
|
95
|
-
const entryRel = ${JSON.stringify(entryRel || "")};
|
|
96
|
-
|
|
97
|
-
// esbuild 解析:部署目录 node_modules → 源码仓 node_modules(本机开发场景)→ PATH 上的 esbuild → npm exec 现拉。
|
|
98
|
-
// 注意:node_modules/esbuild/bin/esbuild 是原生二进制(ELF/Mach-O),必须直接执行(不能当 JS 跑)。
|
|
99
|
-
// Checkout roots are discovered by walking up from the extension dir (a root has node_modules/),
|
|
100
|
-
// plus AITI_REPO_ROOT when set — no machine-specific absolute paths baked into generated files.
|
|
101
|
-
function repoCandidates() {
|
|
102
|
-
const out = [];
|
|
103
|
-
if (process.env.AITI_REPO_ROOT) out.push(process.env.AITI_REPO_ROOT.split(pathSep).join("/") + "/node_modules/esbuild/bin/esbuild");
|
|
104
|
-
let d = extRoot;
|
|
105
|
-
for (let i = 0; i < 8; i++) {
|
|
106
|
-
out.push(d.split(pathSep).join("/") + "/node_modules/esbuild/bin/esbuild");
|
|
107
|
-
const up = dirname(d);
|
|
108
|
-
if (up === d) break;
|
|
109
|
-
d = up;
|
|
110
|
-
}
|
|
111
|
-
return out;
|
|
112
|
-
}
|
|
113
|
-
function findEsbuild() {
|
|
114
|
-
const home = (process.env.HOME || process.env.USERPROFILE || "").split(pathSep).join("/");
|
|
115
|
-
const candidates = [
|
|
116
|
-
extRoot + "/node_modules/esbuild/bin/esbuild",
|
|
117
|
-
...repoCandidates(),
|
|
118
|
-
];
|
|
119
|
-
for (const c of candidates) {
|
|
120
|
-
if (!existsSync(c)) continue;
|
|
121
|
-
try { accessSync(c, fsConstants.X_OK); return [c]; } catch (e) { /* 无执行位 → 下一个来源 */ }
|
|
122
|
-
}
|
|
123
|
-
const r = spawnSync("esbuild", ["--version"], { encoding: "utf8" });
|
|
124
|
-
if (r.status === 0) return ["esbuild"];
|
|
125
|
-
return ["npm", "exec", "--yes", "esbuild", "--"];
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function pickEntry() {
|
|
129
|
-
if (entryRel) return entryRel;
|
|
130
|
-
const srcDir = join(extRoot, "src", "client", "src");
|
|
131
|
-
if (!existsSync(srcDir)) throw new Error("找不到 client 源码目录 src/client/src");
|
|
132
|
-
for (const name of ["entry.tsx", "entry.ts", "entry.jsx", "entry.js", "index.tsx", "index.ts"]) {
|
|
133
|
-
if (existsSync(join(srcDir, name))) return "client/src/" + name;
|
|
134
|
-
}
|
|
135
|
-
const first = readdirSync(srcDir).find((f) => /\\.(tsx?|jsx?)$/.test(f));
|
|
136
|
-
if (!first) throw new Error("client/src 下没有可构建入口");
|
|
137
|
-
return "client/src/" + first;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// 服务端源码同步:src/ 根级文件(index.ts/core.cjs/package.json/vite.config.ts 等)→ 部署根
|
|
141
|
-
// (服务端没有构建产物——jiti 直接加载部署根文件;不 sync 则「改 src → reload」永远不生效)
|
|
142
|
-
import { readdirSync as _rd, copyFileSync as _cp, statSync as _st } from "node:fs";
|
|
143
|
-
const srcRoot = join(extRoot, "src");
|
|
144
|
-
if (existsSync(srcRoot)) {
|
|
145
|
-
for (const f of _rd(srcRoot)) {
|
|
146
|
-
const fp = join(srcRoot, f);
|
|
147
|
-
if (!_st(fp).isFile()) continue;
|
|
148
|
-
_cp(fp, join(extRoot, f));
|
|
149
|
-
}
|
|
150
|
-
console.log("[build] 服务端源码已从 src/ 同步到部署根");
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
const entry = pickEntry();
|
|
154
|
-
const args = [join(extRoot, "src", entry), "--bundle", "--format=esm",
|
|
155
|
-
"--outfile=" + join(extRoot, clientOut), "--jsx=automatic"];
|
|
156
|
-
// pi-web host-shim 委托(react → 本地 shim;jsx-runtime 同理)——与各扩展 vite.config 同款
|
|
157
|
-
const shim = join(extRoot, "src", "client", "src", "host-shim.ts");
|
|
158
|
-
const jsxRuntime = ["jsx-runtime.ts", "jsx-runtime.tsx", "jsx-dev-runtime.ts"].map((f) => join(extRoot, "src", "client", "src", f)).find(existsSync);
|
|
159
|
-
if (existsSync(shim)) args.push("--alias:react=" + shim);
|
|
160
|
-
if (jsxRuntime) args.push("--alias:react/jsx-runtime=" + jsxRuntime);
|
|
161
|
-
args.push("--log-level=info");
|
|
162
|
-
|
|
163
|
-
const [cmd, ...pre] = findEsbuild();
|
|
164
|
-
console.log("[build] esbuild:", cmd, ...pre);
|
|
165
|
-
const r = spawnSync(cmd, [...pre, ...args], { stdio: "inherit", cwd: extRoot });
|
|
166
|
-
if (r.status !== 0) { console.error("[build] 失败——可参照 src/vite.config.ts 调整本文件后重试,或回源码仓构建"); process.exit(r.status ?? 1); }
|
|
167
|
-
console.log("[build] ✓ " + clientOut + "(reload 后浏览器刷新生效)");
|
|
168
|
-
`;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* 主入口:向已存在的部署目录写 dev-pack。
|
|
173
|
-
* @param {object} opts
|
|
174
|
-
* @param {string} opts.extRoot 扩展源码根(pi-web-ext/<extId>)
|
|
175
|
-
* @param {string[]} [opts.targets] 显式部署目录;缺省 = ~/.pi/web{,-dev}/extensions/<extId>(存在的才写)
|
|
176
|
-
* @param {(m: string) => void} [opts.log]
|
|
177
|
-
*/
|
|
178
|
-
export function packDevPack(opts) {
|
|
179
|
-
const extRoot = resolve(opts.extRoot);
|
|
180
|
-
const extId = basename(extRoot);
|
|
181
|
-
const log = opts.log || (() => {});
|
|
182
|
-
const targets = (opts.targets || [
|
|
183
|
-
join(homedir(), ".pi", "web", "extensions", extId),
|
|
184
|
-
join(homedir(), ".pi", "web-dev", "extensions", extId),
|
|
185
|
-
]).filter((t) => existsSync(t));
|
|
186
|
-
if (!targets.length) return;
|
|
187
|
-
|
|
188
|
-
// 1) 打包源码到临时区(staging)→ 逐目标 cpSync(多部署目录零重复扫描)
|
|
189
|
-
const stage = join(extRoot, "dist", ".dev-pack-staging");
|
|
190
|
-
rmSync(stage, { recursive: true, force: true });
|
|
191
|
-
mkdirSync(stage, { recursive: true });
|
|
192
|
-
try {
|
|
193
|
-
// src/:根级源码文件 + 源码子目录
|
|
194
|
-
const srcDir = join(stage, "src");
|
|
195
|
-
mkdirSync(srcDir, { recursive: true });
|
|
196
|
-
for (const en of readdirSync(extRoot, { withFileTypes: true })) {
|
|
197
|
-
if (en.isDirectory()) continue;
|
|
198
|
-
if (ROOT_SRC_SKIP.has(en.name)) continue;
|
|
199
|
-
if (!ROOT_SRC_EXTS.has(en.name.slice(en.name.lastIndexOf(".") || 0)) && en.name !== "package.json") continue;
|
|
200
|
-
cpSync(join(extRoot, en.name), join(srcDir, en.name));
|
|
201
|
-
}
|
|
202
|
-
for (const d of SRC_DIRS) {
|
|
203
|
-
const s = join(extRoot, d);
|
|
204
|
-
if (!existsSync(s)) continue;
|
|
205
|
-
copyTree(s, join(srcDir, ...d.split("/")), DIR_SKIP);
|
|
206
|
-
}
|
|
207
|
-
for (const f of ["vite.config.ts", "package.json"]) {
|
|
208
|
-
if (existsSync(join(extRoot, f))) cpSync(join(extRoot, f), join(srcDir, f));
|
|
209
|
-
}
|
|
210
|
-
// tools/build.mjs:扩展自带拷真身,否则生成默认 esbuild 版
|
|
211
|
-
mkdirSync(join(stage, "tools"), { recursive: true });
|
|
212
|
-
if (existsSync(join(extRoot, "tools", "build.mjs"))) {
|
|
213
|
-
cpSync(join(extRoot, "tools", "build.mjs"), join(stage, "tools", "build.mjs"));
|
|
214
|
-
} else {
|
|
215
|
-
let clientOut = "";
|
|
216
|
-
try {
|
|
217
|
-
const pkg = JSON.parse(readFileSync(join(extRoot, "package.json"), "utf8"));
|
|
218
|
-
if (pkg.client && String(pkg.client).startsWith("dist/")) clientOut = pkg.client;
|
|
219
|
-
} catch (e) {}
|
|
220
|
-
if (!clientOut) {
|
|
221
|
-
// 回退:client 产物名常声明在 entry 的 client: "dist/<id>-client.mjs"(index.ts)——从 staging 的 src 里解析
|
|
222
|
-
try {
|
|
223
|
-
for (const f of readdirSync(srcDir)) {
|
|
224
|
-
if (!/\.tsx?$/.test(f)) continue;
|
|
225
|
-
const m = readFileSync(join(srcDir, f), "utf8").match(/client\s*:\s*["'`](dist\/[\w.-]+\.mjs)["'`]/);
|
|
226
|
-
if (m) { clientOut = m[1]; break; }
|
|
227
|
-
}
|
|
228
|
-
} catch (e) {}
|
|
229
|
-
}
|
|
230
|
-
writeFileSync(join(stage, "tools", "build.mjs"), buildMjsTemplate(extId, extRoot, clientOut, ""));
|
|
231
|
-
}
|
|
232
|
-
// tools/deploy.mjs 本身
|
|
233
|
-
if (existsSync(join(extRoot, "tools", "deploy.mjs"))) {
|
|
234
|
-
cpSync(join(extRoot, "tools", "deploy.mjs"), join(stage, "tools", "deploy.mjs"));
|
|
235
|
-
}
|
|
236
|
-
// AGENTS.md:自带优先,否则模板生成
|
|
237
|
-
if (existsSync(join(extRoot, "AGENTS.md"))) cpSync(join(extRoot, "AGENTS.md"), join(stage, "AGENTS.md"));
|
|
238
|
-
else writeFileSync(join(stage, "AGENTS.md"), agentsMdTemplate(extId));
|
|
239
|
-
|
|
240
|
-
// 1.5) _shared 依赖:部署 src 里的源码可能相对引用 ../../../_shared/*(源仓出仓路径)——
|
|
241
|
-
// 部署根放一份 _shared(小体量、纯源码),让现场 build 的模块解析与源仓一致
|
|
242
|
-
const sharedSrc = resolve(extRoot, "..", "_shared");
|
|
243
|
-
if (existsSync(sharedSrc)) {
|
|
244
|
-
const sharedStage = join(stage, "_shared");
|
|
245
|
-
copyTree(sharedSrc, sharedStage, DIR_SKIP);
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// 2) 落位(staging → 部署目录;package.json/vite.config.ts 双放:根级按 §3.2 结构,src 内供现场阅读)
|
|
249
|
-
for (const t of targets) {
|
|
250
|
-
cpSync(stage, t, { recursive: true });
|
|
251
|
-
for (const f of ["package.json", "vite.config.ts"]) {
|
|
252
|
-
if (existsSync(join(stage, f))) cpSync(join(stage, f), join(t, f));
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
log(`dev-pack → ${targets.map((t) => t.replace(homedir(), "~")).join(", ")}(AGENTS.md + src/ + tools/)`);
|
|
256
|
-
} finally {
|
|
257
|
-
rmSync(stage, { recursive: true, force: true });
|
|
258
|
-
}
|
|
259
|
-
}
|
package/reconcile-deps.mjs
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* _shared/reconcile-deps.mjs · 通知 pi-web 双实例对齐扩展共享依赖(各扩展 deploy.mjs 共用)
|
|
3
|
-
*
|
|
4
|
-
* 背景:扩展运行时依赖统一装进共享根 <webRoot>/node_modules(jiti 从扩展目录向上解析
|
|
5
|
-
* 自动命中;机制仿 pi 本体 npm: 包安装)。共享根的唯一写入方是 aiti-extman 的
|
|
6
|
-
* shared-deps reconcile——deploy.mjs 拷完文件后 POST 本通知即可,不在部署脚本里跑 npm。
|
|
7
|
-
*
|
|
8
|
-
* 用法(与 reload-instances 同款:允许失败,永不 throw、不影响 deploy 退出码):
|
|
9
|
-
* import { notifyReconcile } from "../../_shared/reconcile-deps.mjs";
|
|
10
|
-
* await notifyReconcile(); // 默认 "[deploy] " 前缀;建议在 reloadInstances() 之前调
|
|
11
|
-
*
|
|
12
|
-
* 失败无害:extman 在下一次 install/remove/reconcile-deps 时会自愈对齐;双实例各自
|
|
13
|
-
* reconcile 各自的 webRoot(~/.pi/web 与 ~/.pi/web-dev),互不相干。
|
|
14
|
-
*/
|
|
15
|
-
import { buildInstances } from "./reload-instances.mjs";
|
|
16
|
-
|
|
17
|
-
export async function notifyReconcile(prefix = "[deploy] ") {
|
|
18
|
-
for (const inst of buildInstances()) {
|
|
19
|
-
if (inst.base === null) {
|
|
20
|
-
console.log(`${prefix}reconcile ${inst.name} 跳过:basePath 非法`);
|
|
21
|
-
continue;
|
|
22
|
-
}
|
|
23
|
-
try {
|
|
24
|
-
const r = await fetch(inst.base + "/api/extensions/aiti-extman/ops", {
|
|
25
|
-
method: "POST",
|
|
26
|
-
headers: { "content-type": "application/json" },
|
|
27
|
-
body: JSON.stringify({ action: "reconcile-deps", source: "deploy" }),
|
|
28
|
-
});
|
|
29
|
-
const body = await r.json().catch(() => null);
|
|
30
|
-
const err = body && body.deps && body.deps.error;
|
|
31
|
-
if (r.ok && body && body.ok) {
|
|
32
|
-
console.log(`${prefix}reconcile ${inst.name} → ✓(${Object.keys(body.deps?.deps || {}).length} 个共享依赖)`);
|
|
33
|
-
} else {
|
|
34
|
-
console.log(`${prefix}reconcile ${inst.name} → HTTP ${r.status} ⚠${err ? " " + err : "(extman 未就绪?下次安装时自动对齐)"}`);
|
|
35
|
-
}
|
|
36
|
-
} catch (e) {
|
|
37
|
-
const cause = e && e.cause ? String(e.cause.code || e.cause.message || e.cause) : String((e && e.message) || e);
|
|
38
|
-
console.log(`${prefix}reconcile ${inst.name} 不可达(${cause})— 下次安装时自动对齐`);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}
|
package/reload-instances.mjs
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* _shared/reload-instances.mjs · pi-web 双实例热重载(各扩展 deploy.mjs 共用)
|
|
3
|
-
*
|
|
4
|
-
* dev 3001 / 生产 3002;端口可经 AITI_DEV_PORT / AITI_PROD_PORT 覆盖;
|
|
5
|
-
* basePath 双 env(AITI_DEV_BASE_PATH / AITI_PROD_BASE_PATH)按机器设值,
|
|
6
|
-
* 推荐值不带斜杠(48:dev 与 空;155:系统级 wdev 与 win)——git-bash 启动
|
|
7
|
-
* 原生程序时会把 / 开头的 env 值做 MSYS 路径转换(/wdev → D:/apps/Git/wdev)
|
|
8
|
-
* 致 URL 非法;不带斜杠则不触发转换。此处自动补 /(旧 /xxx 格式仍兼容),
|
|
9
|
-
* 兼容不了时提示 MSYS_NO_PATHCONV=1。
|
|
10
|
-
* 避免「server 端代码改了、实例没 reload 导致跑旧逻辑」。
|
|
11
|
-
*
|
|
12
|
-
* 用法(静态 import 或顶层 await import 均可):
|
|
13
|
-
* import { reloadInstances } from "../../_shared/reload-instances.mjs";
|
|
14
|
-
* await reloadInstances(); // 默认 "[deploy] " 前缀
|
|
15
|
-
*/
|
|
16
|
-
const BASE_PATH_RE = /^\/[A-Za-z0-9._-]*$/;
|
|
17
|
-
|
|
18
|
-
function buildInstance(name, portEnv, portDefault, pathEnv, pathDefault) {
|
|
19
|
-
const origin = `http://127.0.0.1:${process.env[portEnv] || portDefault}`;
|
|
20
|
-
const raw = process.env[pathEnv];
|
|
21
|
-
if (raw === undefined || raw === null || String(raw).trim() === "") return { name, base: origin + pathDefault };
|
|
22
|
-
// 自动补 /:wdev → /wdev(推荐无斜杠格式,MSYS 不转换);/wdev → /wdev(旧格式兼容)
|
|
23
|
-
const p = "/" + String(raw).trim().replace(/^\/+|\/+$/g, "");
|
|
24
|
-
if (BASE_PATH_RE.test(p)) return { name, base: origin + p };
|
|
25
|
-
return { name, base: null, raw };
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** 双实例清单(dev/prod 各 {name, base});reload-instances 与 reconcile-deps 等共用。 */
|
|
29
|
-
export function buildInstances() {
|
|
30
|
-
return [
|
|
31
|
-
buildInstance("dev", "AITI_DEV_PORT", 3001, "AITI_DEV_BASE_PATH", "/dev"),
|
|
32
|
-
buildInstance("prod", "AITI_PROD_PORT", 3002, "AITI_PROD_BASE_PATH", ""),
|
|
33
|
-
];
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export async function reloadInstances(prefix = "[deploy] ") {
|
|
37
|
-
// 批次合并(deploy-all 场景):子条目部署脚本被注入 PI_WEB_DEFER_RELOAD=1 时不各自 reload,
|
|
38
|
-
// 由 deploy-all 在全部条目完成后统一执行一轮(N 条目 × 2 实例 → 2 次 POST)。
|
|
39
|
-
// 避免批量部署时的 reload 风暴(2026-09-15 实测:65 条目逐个 reload 把 dev 实例打满)。
|
|
40
|
-
// 单独跑某个扩展 deploy.mjs 不带该 env → 行为不变(部署完立即 reload)。
|
|
41
|
-
if (process.env.PI_WEB_DEFER_RELOAD === "1") {
|
|
42
|
-
console.log(`${prefix}reload 已 defer(PI_WEB_DEFER_RELOAD=1,由 deploy-all 收尾统一执行)`);
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
// 允许失败:网络异常/非 2xx/服务未启动/env 非法一律只打提示,永不 throw——不影响 deploy 退出码
|
|
46
|
-
for (const inst of buildInstances()) {
|
|
47
|
-
if (inst.base === null) {
|
|
48
|
-
const msysHint = /[\\:]/.test(inst.raw) ? "——疑似 git-bash MSYS 路径转换,用 MSYS_NO_PATHCONV=1 前缀重跑" : "";
|
|
49
|
-
console.log(`${prefix}reload ${inst.name} 跳过:AITI_${inst.name.toUpperCase()}_BASE_PATH="${inst.raw}" 非法(须形如 /xxx 或留空)${msysHint}`);
|
|
50
|
-
continue;
|
|
51
|
-
}
|
|
52
|
-
try {
|
|
53
|
-
const r = await fetch(inst.base + "/api/extensions/reload", { method: "POST" });
|
|
54
|
-
console.log(`${prefix}reload ${inst.name} → HTTP ${r.status} ${r.ok ? "✓" : "⚠ 失败(请手动 POST /api/extensions/reload)"}`);
|
|
55
|
-
} catch (e) {
|
|
56
|
-
const cause = e && e.cause ? String(e.cause.code || e.cause.message || e.cause) : String((e && e.message) || e);
|
|
57
|
-
console.log(`${prefix}reload ${inst.name} 不可达(${cause})— 需手动 POST /api/extensions/reload`);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|