@actiondock/builder 2.15.0 → 2.16.0

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.
@@ -8,15 +8,8 @@ import type { SelectionPlan } from "./types.js";
8
8
  * 按需加载业务实现;跨包外部 Action 不混入本包源码,依赖调用继续经 Host 路由;
9
9
  * - 入口路径以产物包根目录为基准(import.meta.dirname),不依赖调用者当前工作目录。
10
10
  */
11
- export declare function generateNodeHostEntrySource(plan: SelectionPlan | undefined, options?: {
12
- localPackages: Array<{
13
- packageId: string;
14
- relativeRoot: string;
15
- }>;
16
- }): string;
11
+ export declare function generateNodeHostEntrySource(plan: SelectionPlan): string;
17
12
  /**
18
13
  * 生成轻量监督父进程脚本源码(负责参数解析、诊断日志限流、退出码管理与标准输出隔离)。
19
14
  */
20
- export declare function generateNodeSupervisorEntrySource(plan: Pick<SelectionPlan, "packageId" | "version" | "description">, options?: {
21
- multiPackage?: boolean;
22
- }): string;
15
+ export declare function generateNodeSupervisorEntrySource(plan: SelectionPlan): string;
@@ -1,5 +1,4 @@
1
1
  import { STANDALONE_ASYNC_UNSUPPORTED } from "@actiondock/core";
2
- import { BuilderError } from "./errors.js";
3
2
  import { serializePlanManifest } from "./manifest.js";
4
3
  /**
5
4
  * 生成 Host 子进程入口脚本源码(负责运行 ActionDockHost,通过 Node IPC 暴露 Target)。
@@ -10,49 +9,24 @@ import { serializePlanManifest } from "./manifest.js";
10
9
  * 按需加载业务实现;跨包外部 Action 不混入本包源码,依赖调用继续经 Host 路由;
11
10
  * - 入口路径以产物包根目录为基准(import.meta.dirname),不依赖调用者当前工作目录。
12
11
  */
13
- export function generateNodeHostEntrySource(plan, options) {
12
+ export function generateNodeHostEntrySource(plan) {
14
13
  // 复用 SelectionPlan 的清单序列化单一事实源(含包内动作筛选与 Schema 字段映射),
15
14
  // 不单独复制一份 Schema 字段映射
16
- if (!options && !plan)
17
- throw new BuilderError("A plan or explicit local packages are required for the Host entry");
18
- const manifestActions = options ? undefined : serializePlanManifest(plan).actions;
19
- const packageEntries = options
20
- ? options.localPackages.map((pkg) => `{
21
- packageRoot: resolve(packageRoot, ${JSON.stringify(pkg.relativeRoot)}),
22
- projectConfig: loadLocalConfig(${JSON.stringify(pkg.packageId)}, ${JSON.stringify(pkg.relativeRoot)}),
23
- dataDir,
24
- configOverrides,
25
- }`).join(",\n")
26
- : `{
27
- packageRoot, dataDir, configOverrides,
28
- projectConfig: ${JSON.stringify({
29
- id: plan.packageId, name: plan.packageName, version: plan.version,
30
- description: plan.description || "", config: plan.configDefs || {}, actions: manifestActions,
31
- })},
32
- }`;
15
+ const manifestActions = serializePlanManifest(plan).actions;
33
16
  return `#!/usr/bin/env node
34
17
  // AUTO-GENERATED HOST ENTRYPOINT BY ACTIONDOCK BUILDER. DO NOT EDIT.
35
- import { resolve } from "node:path";
36
18
  import {
37
- loadProjectConfig,
38
19
  createActionDock,
39
20
  createNodePlatform,
40
- validateLocalSkillPackages,
41
21
  } from "@actiondock/core";
42
22
  import { serveParentIpc } from "@actiondock/core/server";
43
23
 
44
24
  // 产物包根目录:以入口文件自身位置为基准,不依赖调用者当前工作目录
45
25
  const packageRoot = import.meta.dirname;
46
- ${options ? `function loadLocalConfig(expectedId, relativeRoot) {
47
- const config = loadProjectConfig(resolve(packageRoot, relativeRoot));
48
- if (config.id !== expectedId) throw new Error("Local package ID mismatch: expected " + expectedId + ", found " + config.id);
49
- return config;
50
- }` : ""}
51
26
 
52
27
  let dataDir;
53
28
  const configOverrides = {};
54
29
  const args = process.argv.slice(2);
55
- const commandArgs = [];
56
30
  for (let i = 0; i < args.length; i++) {
57
31
  if (args[i] === "--data-dir" && i + 1 < args.length) {
58
32
  dataDir = args[++i];
@@ -66,28 +40,33 @@ for (let i = 0; i < args.length; i++) {
66
40
  const raw = args[i].slice(9);
67
41
  const [k, ...v] = raw.split("=");
68
42
  if (k) configOverrides[k] = v.join("=");
69
- } else {
70
- commandArgs.push(args[i]);
71
43
  }
72
44
  }
73
45
 
74
46
  // 复用既有命令分发结果确定访问性质:发现命令(list/describe/show)为旁观初始化,
75
47
  // 不创建数据库、不取目录锁、不收割遗留运行记录;执行与写入命令为持有者初始化
76
- const command = commandArgs.find((a) => !a.startsWith("-")) || "";
48
+ const command = args.find((a) => !a.startsWith("-")) || "";
77
49
  const DISCOVERY_COMMANDS = new Set(["list", "describe", "show"]);
78
50
  const recoverOrphans = DISCOVERY_COMMANDS.has(command) ? false : undefined;
79
51
 
80
- const localPackages = [${packageEntries}];
81
- validateLocalSkillPackages(localPackages.map((p) => ({
82
- packageId: p.projectConfig.id,
83
- packageRoot: p.packageRoot,
84
- projectConfig: p.projectConfig,
85
- })));
86
-
87
52
  const service = await createActionDock({
88
53
  dataDir,
89
54
  ...(recoverOrphans === false ? { recoverOrphans: false } : {}),
90
- packages: localPackages,
55
+ packages: [
56
+ {
57
+ packageRoot,
58
+ dataDir,
59
+ configOverrides,
60
+ projectConfig: {
61
+ id: ${JSON.stringify(plan.packageId)},
62
+ name: ${JSON.stringify(plan.packageName)},
63
+ version: ${JSON.stringify(plan.version)},
64
+ description: ${JSON.stringify(plan.description || "")},
65
+ config: ${JSON.stringify(plan.configDefs || {})},
66
+ actions: ${JSON.stringify(manifestActions)},
67
+ },
68
+ },
69
+ ],
91
70
  platform: createNodePlatform({ dataDir }),
92
71
  autoLoadCurrentProject: false,
93
72
  scanLinkedPackages: false,
@@ -98,7 +77,7 @@ await serveParentIpc(service);
98
77
  /**
99
78
  * 生成轻量监督父进程脚本源码(负责参数解析、诊断日志限流、退出码管理与标准输出隔离)。
100
79
  */
101
- export function generateNodeSupervisorEntrySource(plan, options) {
80
+ export function generateNodeSupervisorEntrySource(plan) {
102
81
  return `#!/usr/bin/env node
103
82
  // AUTO-GENERATED SUPERVISOR ENTRYPOINT BY ACTIONDOCK BUILDER. DO NOT EDIT.
104
83
  import { spawn } from "node:child_process";
@@ -162,8 +141,8 @@ if (argv.includes("-h") || argv.includes("--help") || argv[0] === "help") {
162
141
  console.log(" <cmd> run <id> [--input '<json>'] Execute action with JSON input");
163
142
  console.log(" <cmd> run <id> [--stdin-field <field>] [-- <assignments...>]");
164
143
  console.log(" Bind raw stdin text to an input field");
165
- ${options?.multiPackage ? 'console.log(" Multi-package config/state management is unavailable; use --config overrides.");'
166
- : 'console.log(" <cmd> config list/get/set/delete Manage package configuration");\n console.log(" <cmd> state list/get/set/delete Manage shared state store");'}
144
+ console.log(" <cmd> config list/get/set/delete Manage package configuration");
145
+ console.log(" <cmd> state list/get/set/delete Manage shared state store");
167
146
  console.log("\\nGlobal options:");
168
147
  console.log(" --data-dir <path> Custom runtime database directory");
169
148
  console.log(" --config <KEY=val> Temporary config override");
@@ -212,7 +191,6 @@ const dispatcher = new StandaloneDispatcher({
212
191
  version: METADATA.version,
213
192
  description: METADATA.description,
214
193
  service,
215
- multiPackage: ${JSON.stringify(options?.multiPackage === true)},
216
194
  });
217
195
 
218
196
  try {
@@ -3,7 +3,7 @@ import type { CompositeSkillExportOptions, CompositeSkillExportResult, SkillExpo
3
3
  * 复合套件导出装配层。
4
4
  *
5
5
  * 职责:将多个包聚合为一个统一的复合技能目录(mini-workspace 形态),
6
- * 保留各子包 npm 依赖并生成复合根 package.json,并生成或复用复合 SKILL.md。
6
+ * 聚合各子包依赖生成复合根 package.json,并生成或复用复合 SKILL.md。
7
7
  */
8
8
  /** 子包导出回调:由 SkillExporter 注入自身导出能力,避免模块间循环依赖 */
9
9
  export type SubpackageExporter = (options: SkillExporterOptions) => Promise<SkillExportResult>;
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, } from "node:fs";
1
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
2
2
  import { basename, dirname, join, resolve } from "node:path";
3
3
  import { loadProjectConfig, } from "@actiondock/core";
4
4
  import { getPackageSlug, loadManifest, loadPlaybooks, } from "@actiondock/core/project";
@@ -6,10 +6,9 @@ import { generateCompositeSkillMd, RUNTIME_REFERENCE_REL_PATH } from "./skill/in
6
6
  import { writeRuntimeReferenceFile } from "./export-source.js";
7
7
  import { BuilderError } from "./errors.js";
8
8
  import { collectRelativeFiles, getInternalDependencyVersion, replaceDirAtomic } from "./fs-utils.js";
9
- import { allocatePackageDirName } from "./manifest.js";
10
- import { createSourcePackageGraph } from "./source-graph.js";
11
- import { generateNodeHostEntrySource, generateNodeSupervisorEntrySource } from "./entry-generators.js";
12
- import { findExistingCompositeSkillMd, resolveCustomSkillDeclaration, appendLocalExecutionContract, } from "./skill-md.js";
9
+ import { allocatePackageDirName, sanitizeExportDependencies } from "./manifest.js";
10
+ import { SelectionPlanner } from "./planner.js";
11
+ import { findExistingCompositeSkillMd, resolveCustomSkillDeclaration, } from "./skill-md.js";
13
12
  import { createArchive, resolveArchiveFormat } from "./export-archive.js";
14
13
  /**
15
14
  * 执行复合模式导出:将多个包聚合为一个统一的复合技能目录。
@@ -39,36 +38,30 @@ export async function exportCompositeImpl(options, exportSubpackage) {
39
38
  mkdirSync(packagesDestDir, { recursive: true });
40
39
  }
41
40
  const packageInfos = [];
42
- const localPackages = [];
43
41
  const packageSummaries = [];
44
42
  let existingSkillPath;
45
43
  try {
46
- const packageGraph = skillMdOnly ? undefined : options.packageGraph ?? createSourcePackageGraph(options.projectRoots);
47
- const effectiveRoots = skillMdOnly
48
- ? new Set(options.projectRoots.map((root) => resolve(root)))
49
- : new Set(Array.from(packageGraph.packages.values(), (pkg) => pkg.root));
50
- const usedDirNames = new Set();
51
- const usedNpmNames = new Set();
52
- const sourceNpmNames = new Map();
53
- if (!skillMdOnly) {
54
- // 先保留全部真实 npm 名,缺省名不得覆盖尚未导出的兄弟包身份。
55
- for (const projectRoot of effectiveRoots) {
56
- const pkgJsonPath = join(projectRoot, "package.json");
57
- const name = existsSync(pkgJsonPath) ? readWorkspacePackageName(pkgJsonPath) : undefined;
58
- sourceNpmNames.set(projectRoot, name);
59
- if (name) {
60
- if (usedNpmNames.has(name)) {
61
- throw new BuilderError(`Duplicate npm workspace package name '${name}'.`, "DUPLICATE_WORKSPACE_PACKAGE_NAME");
44
+ // 收集并展开所有包含在依赖闭包中的外部项目根目录,确保 bundle 整包携带齐全部依赖
45
+ const effectiveRoots = new Set();
46
+ for (const r of options.projectRoots) {
47
+ effectiveRoots.add(resolve(r));
48
+ if (!skillMdOnly) {
49
+ try {
50
+ const p = SelectionPlanner.plan({ projectRoot: r });
51
+ if (p.externalProjectRoots) {
52
+ for (const extRoot of p.externalProjectRoots) {
53
+ effectiveRoots.add(resolve(extRoot));
54
+ }
62
55
  }
63
- usedNpmNames.add(name);
56
+ }
57
+ catch {
58
+ // 忽略规划解析异常,由主循环处理
64
59
  }
65
60
  }
66
61
  }
62
+ const usedDirNames = new Set();
67
63
  for (const projectRoot of effectiveRoots) {
68
- const graphManifest = packageGraph && Array.from(packageGraph.packages.values()).find((p) => resolve(p.root) === resolve(projectRoot))?.manifest;
69
- const config = graphManifest
70
- ? { ...graphManifest, name: graphManifest.name || graphManifest.id, version: graphManifest.version || "0.1.0" }
71
- : loadProjectConfig(projectRoot);
64
+ const config = loadProjectConfig(projectRoot);
72
65
  let pkgSlug;
73
66
  if (skillMdOnly) {
74
67
  // 就地生成:规程链接基于工作区实际子目录名
@@ -78,49 +71,34 @@ export async function exportCompositeImpl(options, exportSubpackage) {
78
71
  // 目录名分配统一复用 manifest 的 allocatePackageDirName,回退后仍冲突会追加数字后缀
79
72
  pkgSlug = allocatePackageDirName(usedDirNames, config.id);
80
73
  }
81
- let defaultPackageName;
82
- if (!skillMdOnly && !sourceNpmNames.get(projectRoot)) {
83
- const baseName = normalizeNpmPackageName(pkgSlug);
84
- let candidate = baseName;
85
- let suffix = 2;
86
- while (usedNpmNames.has(candidate))
87
- candidate = `${baseName}-${suffix++}`;
88
- defaultPackageName = candidate;
89
- usedNpmNames.add(candidate);
90
- }
91
74
  let actionIds;
92
- let playbooks;
75
+ let playbookIds;
93
76
  let manifest;
94
77
  if (skillMdOnly) {
95
78
  // 仅生成 SKILL.md:直接读取清单获取 Action 契约描述,不拷贝子包产物
96
79
  manifest = loadManifest(projectRoot);
97
80
  actionIds = manifest?.actions ? Object.keys(manifest.actions) : [];
98
- playbooks = loadPlaybooks(projectRoot, config.playbooksDir);
81
+ playbookIds = Array.from(loadPlaybooks(projectRoot, config.playbooksDir).keys());
99
82
  }
100
83
  else {
101
84
  const destPkgDir = join(packagesDestDir, pkgSlug);
102
85
  const singleExport = await exportSubpackage({
103
86
  projectRoot,
104
- packageGraph,
105
- config,
106
- manifest: graphManifest || undefined,
107
87
  outDir: destPkgDir,
108
88
  archive: false,
109
89
  skipSkillMd: true,
110
90
  mode: "source",
111
91
  _isSubpackage: true,
112
- defaultPackageName,
113
92
  });
114
- manifest = loadManifest(destPkgDir);
93
+ manifest = loadManifest(destPkgDir) || loadManifest(projectRoot);
115
94
  actionIds = singleExport.actions;
116
- playbooks = loadPlaybooks(destPkgDir, manifest?.playbooksDir, manifest);
95
+ playbookIds = singleExport.playbooks;
117
96
  }
118
- const playbookIds = Array.from(playbooks.keys());
97
+ const playbooks = loadPlaybooks(projectRoot, config.playbooksDir);
119
98
  const actionEntries = actionIds.map((actId) => ({
120
99
  id: actId,
121
100
  description: manifest?.actions?.[actId]?.description,
122
101
  }));
123
- localPackages.push({ packageId: config.id, relativeRoot: `packages/${pkgSlug}` });
124
102
  packageInfos.push({
125
103
  config,
126
104
  actions: actionEntries,
@@ -140,7 +118,6 @@ export async function exportCompositeImpl(options, exportSubpackage) {
140
118
  const compositeSkillMd = generateCompositeSkillMd(options.bundleName, description, packageInfos, {
141
119
  customSections: customDeclaration?.sections,
142
120
  packagesBaseDir: skillMdOnly ? "." : "packages",
143
- invocationStyle: skillMdOnly ? "global-ad" : "source-ad",
144
121
  });
145
122
  if (skillMdOnly) {
146
123
  // 就地仅重生成 SKILL.md:始终重新生成(忽略已有 SKILL.md 复用逻辑),不产出完整套件目录
@@ -176,10 +153,9 @@ export async function exportCompositeImpl(options, exportSubpackage) {
176
153
  }
177
154
  if (existingSkillPath) {
178
155
  const destSkillMdPath = join(stagingDir, "SKILL.md");
179
- writeFileSync(destSkillMdPath, readFileSync(existingSkillPath, "utf-8"), "utf-8");
180
- appendLocalExecutionContract(destSkillMdPath, packageInfos.map((p) => ({
181
- packageId: p.config.id, actions: p.actions,
182
- })));
156
+ if (resolve(existingSkillPath) !== resolve(destSkillMdPath)) {
157
+ copyFileSync(existingSkillPath, destSkillMdPath);
158
+ }
183
159
  }
184
160
  else {
185
161
  writeFileSync(join(stagingDir, "SKILL.md"), compositeSkillMd, "utf-8");
@@ -188,19 +164,11 @@ export async function exportCompositeImpl(options, exportSubpackage) {
188
164
  dependencyStepLabel: "安装复合技能聚合依赖",
189
165
  relinkStepLabel: "完成安装后重新链接复合技能",
190
166
  compositeLinkNote: true,
191
- invocationStyle: "source-ad",
192
- entryRelPath: 'node "<skill_root>/entry.mjs"',
167
+ invocationStyle: "global-ad",
193
168
  });
194
169
  }
195
- if (packagesDestDir) {
196
- assertUniqueWorkspacePackageNames(packagesDestDir);
197
- }
198
- // npm workspaces 保留各包依赖约束,根目录仅声明入口运行依赖。
199
- writeCompositePkgJson(stagingDir, bundleSlug, options);
200
- const entryMetadata = { packageId: options.bundleName, version: "0.1.0", description };
201
- writeFileSync(join(stagingDir, "entry.mjs"), generateNodeSupervisorEntrySource(entryMetadata, { multiPackage: true }), "utf-8");
202
- // Host 生成仍复用单包生成器,但源码包元数据只从自身相对路径读取。
203
- writeFileSync(join(stagingDir, "entry-host.js"), generateNodeHostEntrySource(undefined, { localPackages }), "utf-8");
170
+ // 聚合所有子包依赖生成复合根目录 package.json
171
+ writeCompositePkgJson(stagingDir, packagesDestDir, packageInfos, bundleSlug, options);
204
172
  // 原子替换目标复合技能目录
205
173
  await replaceDirAtomic(stagingDir, targetSkillDir);
206
174
  }
@@ -227,77 +195,35 @@ export async function exportCompositeImpl(options, exportSubpackage) {
227
195
  };
228
196
  }
229
197
  /**
230
- * 复合根目录声明入口运行依赖,业务依赖保留在各工作区包中,由 npm 安装解析。
198
+ * 复合套件聚合各子包依赖并生成复合根目录 package.json。
199
+ * 依赖清洗统一复用 manifest 的 sanitizeExportDependencies 单一入口,与单包导出口径一致。
231
200
  */
232
- function writeCompositePkgJson(stagingDir, bundleSlug, options) {
233
- // 子包保留各自依赖约束,由 npm workspaces 正常安装与多版本解析,不聚合覆盖。
234
- const runtimeDeps = {
235
- "@actiondock/core": getInternalDependencyVersion(),
201
+ function writeCompositePkgJson(stagingDir, packagesDestDir, packageInfos, bundleSlug, options) {
202
+ const aggregatedDeps = {
236
203
  "@actiondock/sdk": getInternalDependencyVersion(),
237
204
  };
205
+ for (const info of packageInfos) {
206
+ const pkgJsonPath = join(packagesDestDir, info.packageDir, "package.json");
207
+ if (existsSync(pkgJsonPath)) {
208
+ try {
209
+ const parsed = JSON.parse(readFileSync(pkgJsonPath, "utf-8"));
210
+ Object.assign(aggregatedDeps, sanitizeExportDependencies(join(packagesDestDir, info.packageDir), parsed.dependencies, "exported skill packages", false));
211
+ }
212
+ catch (err) {
213
+ if (err instanceof BuilderError)
214
+ throw err;
215
+ // 复合导出缺依赖影响面大:读文件与解析失败必须显式报错,严禁静默吞掉导致聚合依赖缺失
216
+ throw new BuilderError(`Failed to read or parse package.json of exported subpackage '${info.packageDir}' (${pkgJsonPath}): ${err instanceof Error ? err.message : String(err)}`);
217
+ }
218
+ }
219
+ }
238
220
  const compositePkg = {
239
221
  name: `${bundleSlug}-composite-skill`,
240
222
  version: "0.1.0",
241
223
  description: options.description || `Composite Skill suite: ${options.bundleName}`,
242
224
  type: "module",
243
225
  workspaces: ["packages/*"],
244
- dependencies: runtimeDeps,
226
+ dependencies: aggregatedDeps,
245
227
  };
246
228
  writeFileSync(join(stagingDir, "package.json"), JSON.stringify(compositePkg, null, 2) + "\n", "utf-8");
247
229
  }
248
- /**
249
- * 规范化包目录标识为合法 npm 包名(小写字母、数字、连字符、下划线与点号)。
250
- */
251
- function normalizeNpmPackageName(name) {
252
- const normalized = name
253
- .trim()
254
- .toLowerCase()
255
- .replace(/[^a-z0-9-_.]/g, "-")
256
- .replace(/^[._]+/, "");
257
- return normalized || "package";
258
- }
259
- /** 工作区清单读取失败必须透明报告,只有缺省 name 才允许自动分配。 */
260
- function readWorkspacePackageName(path) {
261
- const raw = readFileSync(path, "utf-8");
262
- let parsed;
263
- try {
264
- parsed = JSON.parse(raw);
265
- }
266
- catch (err) {
267
- throw new BuilderError(`Invalid package.json at '${path}': ${String(err)}`, "INVALID_PACKAGE_JSON");
268
- }
269
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
270
- throw new BuilderError(`Invalid package.json at '${path}': expected an object.`, "INVALID_PACKAGE_JSON");
271
- }
272
- const name = parsed.name;
273
- if (name === undefined || name === "")
274
- return undefined;
275
- if (typeof name !== "string" || !name.trim() || name !== name.trim()) {
276
- throw new BuilderError(`Invalid npm workspace package name at '${path}'.`, "INVALID_PACKAGE_JSON");
277
- }
278
- return name;
279
- }
280
- /**
281
- * 校验复合暂存目录中所有子包导出的 package.json.name 唯一性。
282
- * 若已有真实 npm 名确实冲突,在发布产物前明确抛出 BuilderError。
283
- */
284
- function assertUniqueWorkspacePackageNames(packagesDir) {
285
- const seenNames = new Map();
286
- const entries = readdirSync(packagesDir, { withFileTypes: true });
287
- for (const entry of entries) {
288
- if (!entry.isDirectory())
289
- continue;
290
- const pkgJsonPath = join(packagesDir, entry.name, "package.json");
291
- if (!existsSync(pkgJsonPath))
292
- continue;
293
- const name = readWorkspacePackageName(pkgJsonPath);
294
- if (!name) {
295
- throw new BuilderError(`Missing npm workspace package name at '${pkgJsonPath}'.`, "INVALID_PACKAGE_JSON");
296
- }
297
- const existing = seenNames.get(name);
298
- if (existing) {
299
- throw new BuilderError(`Duplicate npm workspace package name '${name}' found in packages/${existing} and packages/${entry.name}.`, "DUPLICATE_WORKSPACE_PACKAGE_NAME");
300
- }
301
- seenNames.set(name, entry.name);
302
- }
303
- }
@@ -1,11 +1,8 @@
1
1
  import { copyFileSync, existsSync, readFileSync, writeFileSync, } from "node:fs";
2
2
  import { basename, dirname, join } from "node:path";
3
3
  import { mkdirSync } from "node:fs";
4
- import { generateNodeHostEntrySource, generateNodeSupervisorEntrySource } from "./entry-generators.js";
5
- import { appendLocalExecutionContract } from "./skill-md.js";
6
4
  import { generateSourceSkillMd } from "./skill/index.js";
7
5
  import { RUNTIME_REFERENCE_REL_PATH, renderRuntimeReferenceContent, } from "./skill/templates.js";
8
- import { loadManifest } from "@actiondock/core/project";
9
6
  import { BuilderError } from "./errors.js";
10
7
  import { getInternalDependencyVersion } from "./fs-utils.js";
11
8
  import { assertValidManifestActionIds, sanitizeExportDependencies, serializePlanManifest, } from "./manifest.js";
@@ -24,24 +21,18 @@ export function stageSourceSkill(root, skillDir, plan, options, pkgSlug) {
24
21
  const actionsDir = plan.actionsDir || "actions";
25
22
  const playbooksDir = plan.playbooksDir || "playbooks";
26
23
  const configForTemplates = buildConfigForTemplates(plan, actionsDir, playbooksDir);
27
- const usedExistingSkillMd = writeSkillMd(root, skillDir, { skipSkillMd: options.skipSkillMd, skillMdPath: options.skillMdPath, pkgSlug }, () => generateSourceSkillMd(configForTemplates, plan.actions.filter((a) => !a.isExternal), plan.playbooks));
24
+ const usedExistingSkillMd = writeSkillMd(root, skillDir, { skipSkillMd: options.skipSkillMd, skillMdPath: options.skillMdPath, pkgSlug }, () => generateSourceSkillMd(configForTemplates, plan.actions, plan.playbooks));
28
25
  // 导出精简后的 actiondock.json 项目配置(项目元数据与清单的单一事实源)
29
26
  const exportedConfig = serializePlanManifest(plan, {
30
27
  omitEmptyConfig: true,
31
28
  includeDirs: { actionsDir, playbooksDir },
32
29
  });
33
- const originalManifest = options.manifest || loadManifest(root);
34
- if (originalManifest?.dependencies)
35
- exportedConfig.dependencies = originalManifest.dependencies;
36
- const packageUses = originalManifest?.uses;
37
- if (packageUses)
38
- exportedConfig.uses = packageUses;
39
30
  if (exportedConfig.actions && typeof exportedConfig.actions === "object") {
40
31
  assertValidManifestActionIds(exportedConfig.actions);
41
32
  }
42
33
  writeFileSync(join(skillDir, "actiondock.json"), JSON.stringify(exportedConfig, null, 2) + "\n", "utf-8");
43
34
  // 导出 package.json
44
- writeSourceSkillPkgJson(root, skillDir, plan, pkgSlug, options);
35
+ writeSourceSkillPkgJson(root, skillDir, plan, pkgSlug);
45
36
  // 拷贝 tsconfig.json(若存在)
46
37
  const tsconfigPath = join(root, "tsconfig.json");
47
38
  if (existsSync(tsconfigPath)) {
@@ -51,27 +42,13 @@ export function stageSourceSkill(root, skillDir, plan, options, pkgSlug) {
51
42
  copyPlanEntries(skillDir, plan, {
52
43
  playbookRelPath: (pb) => join(playbooksDir, basename(pb.filePath)),
53
44
  });
54
- if (!options._isSubpackage) {
55
- for (const name of ["entry.mjs", "entry-host.js"]) {
56
- if (existsSync(join(skillDir, name))) {
57
- throw new BuilderError(`Source Skill entry conflict: '${name}' is reserved for the local runtime entry; refusing to overwrite a declared file.`, "SOURCE_ENTRY_CONFLICT");
58
- }
59
- }
60
- writeFileSync(join(skillDir, "entry.mjs"), generateNodeSupervisorEntrySource(plan), "utf-8");
61
- writeFileSync(join(skillDir, "entry-host.js"), generateNodeHostEntrySource(undefined, {
62
- localPackages: [{ packageId: plan.packageId, relativeRoot: "." }],
63
- }), "utf-8");
64
- if (usedExistingSkillMd)
65
- appendLocalExecutionContract(join(skillDir, "SKILL.md"), [plan]);
66
- }
67
45
  // 声明资产拷贝完成后再物化默认运行参考文件:仅在使用自动模板时生成;
68
46
  // 与项目声明资产同路径冲突时报错不覆盖(拷贝在前,冲突检测能真实命中)
69
47
  if (usedExistingSkillMd === undefined && !options.skipSkillMd) {
70
48
  writeRuntimeReferenceFile(skillDir, {
71
49
  dependencyStepLabel: "安装技能源码依赖",
72
50
  relinkStepLabel: "完成安装后重新链接本技能",
73
- invocationStyle: "source-ad",
74
- entryRelPath: 'node "<skill_root>/entry.mjs"',
51
+ invocationStyle: "global-ad",
75
52
  });
76
53
  }
77
54
  return usedExistingSkillMd;
@@ -88,16 +65,15 @@ export function writeRuntimeReferenceFile(destDir, options) {
88
65
  mkdirSync(dirname(referencePath), { recursive: true });
89
66
  writeFileSync(referencePath, renderRuntimeReferenceContent(options), "utf-8");
90
67
  }
91
- function writeSourceSkillPkgJson(root, skillDir, plan, pkgSlug, options) {
68
+ function writeSourceSkillPkgJson(root, skillDir, plan, pkgSlug) {
92
69
  let exportedPkg;
93
- const fallbackName = options?.defaultPackageName || pkgSlug;
94
70
  const projectPkgPath = join(root, "package.json");
95
71
  if (existsSync(projectPkgPath)) {
96
72
  try {
97
73
  const raw = readFileSync(projectPkgPath, "utf-8");
98
74
  const parsed = JSON.parse(raw);
99
75
  exportedPkg = {
100
- name: parsed.name || fallbackName,
76
+ name: parsed.name || pkgSlug,
101
77
  version: plan.version || parsed.version || "0.1.0",
102
78
  description: plan.description || parsed.description,
103
79
  type: "module",
@@ -108,13 +84,12 @@ function writeSourceSkillPkgJson(root, skillDir, plan, pkgSlug, options) {
108
84
  if (err instanceof BuilderError) {
109
85
  throw err;
110
86
  }
111
- exportedPkg = fallbackSkillPkg(plan, fallbackName);
87
+ exportedPkg = fallbackSkillPkg(plan, pkgSlug);
112
88
  }
113
89
  }
114
90
  else {
115
- exportedPkg = fallbackSkillPkg(plan, fallbackName);
91
+ exportedPkg = fallbackSkillPkg(plan, pkgSlug);
116
92
  }
117
- exportedPkg.dependencies["@actiondock/core"] ??= getInternalDependencyVersion();
118
93
  writeFileSync(join(skillDir, "package.json"), JSON.stringify(exportedPkg, null, 2) + "\n", "utf-8");
119
94
  }
120
95
  /** 无 package.json 或解析失败时的兜底导出描述 */
package/dist/exporter.js CHANGED
@@ -1,11 +1,9 @@
1
1
  import { existsSync, mkdirSync, rmSync } from "node:fs";
2
2
  import { basename, dirname, join, resolve } from "node:path";
3
- import { getPackageSlug, loadManifest } from "@actiondock/core/project";
3
+ import { getPackageSlug } from "@actiondock/core/project";
4
4
  import { BuilderError } from "./errors.js";
5
5
  import { replaceDirAtomic } from "./fs-utils.js";
6
6
  import { collectRelativeFiles } from "./fs-utils.js";
7
- import { createSourcePackageGraph } from "./source-graph.js";
8
- import { deriveEffectivePackageGraph } from "./derived-graph.js";
9
7
  import { SelectionPlanner } from "./planner.js";
10
8
  import { isOwnAction } from "./types.js";
11
9
  import { createArchive, resolveArchiveFormat } from "./export-archive.js";
@@ -28,35 +26,8 @@ export class SkillExporter {
28
26
  async export(options) {
29
27
  const root = resolve(options.projectRoot);
30
28
  const mode = options.mode === "node" ? "node" : "source";
31
- // 共享图、规划与源码清单使用同一有效声明;显式 manifest 不从磁盘继承依赖。
32
- if (mode === "source" && (options.config || options.manifest)) {
33
- const graphNode = options.packageGraph && Array.from(options.packageGraph.packages.values()).find((p) => resolve(p.root) === root);
34
- const baseManifest = options.manifest || graphNode?.manifest || loadManifest(root) || {};
35
- const manifest = {
36
- ...baseManifest,
37
- ...options.config,
38
- ...options.manifest,
39
- // 保持既有 config 元数据优先级;动作、dependencies、uses 使用有效清单声明。
40
- ...Object.fromEntries([
41
- "id", "name", "version", "description", "config", "actionsDir", "playbooksDir",
42
- ].map((key) => [key, options.config?.[key]]).filter(([, value]) => value !== undefined)),
43
- };
44
- options = {
45
- ...options,
46
- manifest,
47
- config: { ...manifest, name: manifest.name || manifest.id, version: manifest.version || "0.1.0" },
48
- };
49
- }
50
29
  // 调用 SelectionPlanner 执行声明式构建规划
51
- const packageGraph = mode === "source" && options.packageGraph
52
- ? deriveEffectivePackageGraph(options.packageGraph, root, options.manifest)
53
- : options.packageGraph ?? (mode === "source" ? createSourcePackageGraph([root], options.manifest) : undefined);
54
- options = {
55
- ...options,
56
- packageGraph,
57
- };
58
30
  const plan = SelectionPlanner.plan({
59
- packageGraph,
60
31
  projectRoot: root,
61
32
  config: options.config,
62
33
  manifest: options.manifest,
@@ -68,7 +39,7 @@ export class SkillExporter {
68
39
  const defaultFolderName = `${pkgSlug}-skill`;
69
40
  const defaultSkillDir = join(root, "dist", defaultFolderName);
70
41
  const targetSkillDir = resolve(options.outDir || defaultSkillDir);
71
- const hasExternalDeps = Boolean((packageGraph && packageGraph.packages.size > 1) || (plan.externalProjectRoots && plan.externalProjectRoots.length > 0));
42
+ const hasExternalDeps = Boolean(plan.externalProjectRoots && plan.externalProjectRoots.length > 0);
72
43
  // 单包源码导出若依赖闭包含外部包,导成 mini-workspace 形态(packages/ 下带齐依赖包),和 bundle 统一成一个交付形状
73
44
  // 该复合分支会展开全部依赖包,无法保留调用方传入的 actions/playbooks 过滤选项;
74
45
  // 静默丢弃过滤会导致产物全量导出,必须显式拒绝并给出调整指引(CLI 侧已有 roots>1 守卫,此处补齐 composite 分支守卫)
@@ -79,9 +50,8 @@ export class SkillExporter {
79
50
  throw new BuilderError("Filtering options (--actions, --playbook) cannot be combined with a source export whose dependency closure spans external linked packages (composite mini-workspace output). Remove the filtering options to export the full closure, or adjust the 'uses' declarations so the closure stays within a single package.", "FILTERS_UNSUPPORTED_FOR_COMPOSITE");
80
51
  }
81
52
  if (willUseComposite) {
82
- const allProjectRoots = Array.from(new Set([root, ...Array.from(packageGraph.packages.values(), (p) => p.root)]));
53
+ const allProjectRoots = Array.from(new Set([root, ...plan.externalProjectRoots]));
83
54
  const compositeRes = await this.exportComposite({
84
- packageGraph,
85
55
  bundleName: plan.packageName || plan.packageId,
86
56
  projectRoots: allProjectRoots,
87
57
  outDir: targetSkillDir,