@eworkbase/plugin-ai-rules 0.4.1 → 0.4.3

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/dist/plugin.mjs CHANGED
@@ -2261,6 +2261,70 @@ const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
2261
2261
  });
2262
2262
  };
2263
2263
  });
2264
+ function discriminatorMap(def) {
2265
+ const map = /* @__PURE__ */ new Map();
2266
+ for (const option of def.options) {
2267
+ const values = option._zod.propValues?.[def.discriminator];
2268
+ if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
2269
+ for (const value of values) if (map.has(value)) {
2270
+ if (value !== void 0) throw new Error(`Duplicate discriminator value "${String(value)}"`);
2271
+ map.set(value, null);
2272
+ } else map.set(value, option);
2273
+ }
2274
+ return map;
2275
+ }
2276
+ const $ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
2277
+ def.inclusive = false;
2278
+ $ZodUnion.init(inst, def);
2279
+ const _super = inst._zod.parse;
2280
+ defineLazyInternal(inst, "propValues", (zod) => {
2281
+ const propValues = {};
2282
+ let undefinedCount = 0;
2283
+ for (const option of zod.def.options) {
2284
+ const pv = option._zod.propValues;
2285
+ if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);
2286
+ if (pv[zod.def.discriminator]?.has(void 0)) undefinedCount++;
2287
+ for (const [k, v] of Object.entries(pv)) {
2288
+ if (!Object.prototype.hasOwnProperty.call(propValues, k)) assignProp(propValues, k, /* @__PURE__ */ new Set());
2289
+ for (const val of v) propValues[k].add(val);
2290
+ }
2291
+ }
2292
+ if (!zod.def.unionFallback && undefinedCount > 1) propValues[zod.def.discriminator]?.delete(void 0);
2293
+ return propValues;
2294
+ });
2295
+ def.options.forEach((option, i) => {
2296
+ const propShape = rawShape(option._zod.def);
2297
+ if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) throw new Error(`Invalid discriminated union option at index "${i}"`);
2298
+ });
2299
+ const disc = cached(() => discriminatorMap(def));
2300
+ inst._zod.parse = (payload, ctx) => {
2301
+ const input = payload.value;
2302
+ if (!isObject$1(input)) {
2303
+ payload.issues.push({
2304
+ code: "invalid_type",
2305
+ expected: "object",
2306
+ input,
2307
+ inst
2308
+ });
2309
+ return payload;
2310
+ }
2311
+ const value = input?.[def.discriminator];
2312
+ const opt = disc.value.get(value);
2313
+ if (opt && (value !== void 0 || ctx.direction !== "backward")) return opt._zod.run(payload, ctx);
2314
+ if (def.unionFallback || ctx.direction === "backward") return _super(payload, ctx);
2315
+ payload.issues.push({
2316
+ code: "invalid_union",
2317
+ errors: [],
2318
+ note: "No matching discriminator",
2319
+ discriminator: def.discriminator,
2320
+ options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),
2321
+ input,
2322
+ path: [def.discriminator],
2323
+ inst
2324
+ });
2325
+ return payload;
2326
+ };
2327
+ });
2264
2328
  const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
2265
2329
  $ZodType.init(inst, def);
2266
2330
  inst._zod.parse = (payload, ctx) => {
@@ -5462,6 +5526,18 @@ function union(options, params) {
5462
5526
  ...normalizeParams(params)
5463
5527
  });
5464
5528
  }
5529
+ const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => {
5530
+ ZodUnion.init(inst, def);
5531
+ $ZodDiscriminatedUnion.init(inst, def);
5532
+ });
5533
+ function discriminatedUnion(discriminator, options, params) {
5534
+ return new ZodDiscriminatedUnion({
5535
+ type: "union",
5536
+ options,
5537
+ discriminator,
5538
+ ...normalizeParams(params)
5539
+ });
5540
+ }
5465
5541
  const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
5466
5542
  $ZodIntersection.init(inst, def);
5467
5543
  ZodType.init(inst, def);
@@ -5814,6 +5890,16 @@ let PluginCommandTransaction = /* @__PURE__ */ function(PluginCommandTransaction
5814
5890
  PluginCommandTransaction["ProjectMutation"] = "projectMutation";
5815
5891
  return PluginCommandTransaction;
5816
5892
  }({});
5893
+ let PluginViewLayout = /* @__PURE__ */ function(PluginViewLayout) {
5894
+ PluginViewLayout["Content"] = "content";
5895
+ PluginViewLayout["Fill"] = "fill";
5896
+ return PluginViewLayout;
5897
+ }({});
5898
+ let PluginProcessOutputMode = /* @__PURE__ */ function(PluginProcessOutputMode) {
5899
+ PluginProcessOutputMode["Log"] = "log";
5900
+ PluginProcessOutputMode["Content"] = "content";
5901
+ return PluginProcessOutputMode;
5902
+ }({});
5817
5903
  let PluginSharedChangeKind = /* @__PURE__ */ function(PluginSharedChangeKind) {
5818
5904
  PluginSharedChangeKind["None"] = "none";
5819
5905
  PluginSharedChangeKind["Files"] = "files";
@@ -5984,6 +6070,30 @@ object({
5984
6070
  execution: executionIdentitySchema.nullish(),
5985
6071
  context: executionContextSchema.optional()
5986
6072
  });
6073
+ /** Serializable opt-in for workflow nodes and the result fields a condition may read. */
6074
+ const name = string().trim().min(1).max(120);
6075
+ const fieldKey = string().regex(/^[A-Za-z][A-Za-z0-9_]{0,63}$/).refine((key) => ![
6076
+ "constructor",
6077
+ "prototype",
6078
+ "__proto__"
6079
+ ].includes(key));
6080
+ const outputField = discriminatedUnion("type", [
6081
+ object({
6082
+ type: literal("boolean"),
6083
+ label: name
6084
+ }).strict(),
6085
+ object({
6086
+ type: literal("number"),
6087
+ label: name,
6088
+ unit: name.optional()
6089
+ }).strict(),
6090
+ object({
6091
+ type: literal("enum"),
6092
+ label: name,
6093
+ values: array(name).min(1).max(64)
6094
+ }).strict()
6095
+ ]);
6096
+ union([literal(true), object({ outputs: record(fieldKey, outputField).refine((fields) => Object.keys(fields).length <= 32) }).strict()]);
5987
6097
  //#endregion
5988
6098
  //#region ../plugin-sdk/dist/markdown-link-C-qw7xuN.js
5989
6099
  const MAXIMUM_LINK_LENGTH = 4096;
@@ -8284,6 +8394,15 @@ const MAXIMUM_OUTPUT_FILES = 1024;
8284
8394
  const MAXIMUM_JOURNAL_BYTES = 67108864;
8285
8395
  const JOURNAL_FILE = "injection-journal.json";
8286
8396
  const JOURNAL_TEMPORARY_FILE = `${JOURNAL_FILE}.tmp`;
8397
+ const RECOVERY_CLIENT_PATHS = [
8398
+ "AGENTS.md",
8399
+ "CLAUDE.md",
8400
+ ".mcp.json",
8401
+ ".codex/config.toml"
8402
+ ];
8403
+ const RECOVERY_MCP_KEYS = ["mcpServers", "mcp_servers"];
8404
+ const RECOVERY_DIRECTORY_PREFIX = "injection-recovery-";
8405
+ const RECOVERY_CLIENT_SNAPSHOT_FILE = "clients.json";
8287
8406
  const FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set([
8288
8407
  ".",
8289
8408
  "..",
@@ -8300,18 +8419,123 @@ const JOURNAL_SCHEMA = object({
8300
8419
  root: string(),
8301
8420
  files: array(tuple([string(), array(MANAGED_FILE_SCHEMA).min(1).max(2)])).max(MAXIMUM_OUTPUT_FILES)
8302
8421
  }).strict();
8422
+ /** 可通过重新同步恢复的客户端内容冲突,不包括路径或归属记录校验失败。 */
8423
+ var InjectionConflictError = class extends Error {
8424
+ path;
8425
+ constructor(relativePath, cause) {
8426
+ super(cause?.message ?? `规则不会覆盖或撤销已被修改的文件:${relativePath}`, { cause });
8427
+ this.path = relativePath;
8428
+ }
8429
+ };
8303
8430
  var InjectionWriter = class {
8304
8431
  root;
8305
8432
  #stateRoot;
8306
8433
  #managed = /* @__PURE__ */ new Map();
8434
+ #isLoaded = false;
8307
8435
  constructor(root, stateDirectory) {
8308
8436
  this.root = realpathSync(root);
8309
8437
  this.#stateRoot = stateDirectory ? realpathSync(stateDirectory()) : null;
8310
- if (this.#stateRoot) this.#load();
8438
+ this.#isLoaded = this.#load() === null;
8439
+ }
8440
+ /** 在可交互的生命周期内恢复归属,取消与失败均保留文件供原入口重试。 */
8441
+ async prepare(invocation) {
8442
+ const stateRoot = this.#stateRoot;
8443
+ if (this.#isLoaded || !stateRoot) return;
8444
+ const recovery = this.#load();
8445
+ if (!recovery) {
8446
+ this.#isLoaded = true;
8447
+ return;
8448
+ }
8449
+ const paths = recovery.managed ? [...recovery.managed.keys()] : RECOVERY_CLIENT_PATHS;
8450
+ const files = new Map(paths.map((relativePath) => [relativePath, readSafeFile(this.root, relativePath)]));
8451
+ const snapshots = JSON.stringify({
8452
+ root: this.root,
8453
+ files: [...files]
8454
+ });
8455
+ const replacement = recovery.managed ? "恢复会替换旧注入及受管文件中的本地修改。" : "归属记录已不可用,恢复会重建会话规则并重置这些客户端文件的 MCP 连接,包含手动添加的连接。";
8456
+ if (Buffer.byteLength(snapshots) > MAXIMUM_JOURNAL_BYTES) throw new Error("规则客户端备份超过大小上限,恢复已停止,现有文件已保留。");
8457
+ const { confirmed } = await invocation.services.prompt.ask({
8458
+ name: "confirmed",
8459
+ type: "confirm",
8460
+ purpose: "approval",
8461
+ default: false,
8462
+ title: "恢复本机规则上下文",
8463
+ submitLabel: "备份并恢复",
8464
+ message: `${recovery.message}是否备份现有文件并按当前工作区重新生成规则?`,
8465
+ details: `${replacement}其他文件保持原样。原文件和归属记录保存在本机插件私有目录,可供恢复。\n\n涉及文件:\n${paths.join("\n")}`
8466
+ });
8467
+ invocation.signal.throwIfAborted();
8468
+ if (confirmed !== true) throw new Error("已取消规则上下文恢复,现有文件已保留。点击“重试此插件”可重新确认恢复。");
8469
+ const journalPath = safeFilePath(stateRoot, JOURNAL_FILE);
8470
+ if ((lstatSync(journalPath, { throwIfNoEntry: false }) ? readFileSync(journalPath, "utf8") : null) !== recovery.content || [...files].some(([relativePath, content]) => readSafeFile(this.root, relativePath) !== content)) throw new Error("规则文件或归属记录在确认期间已变化,恢复已停止。请重试此插件重新核对。");
8471
+ const backupRoot = mkdtempSync(path.join(stateRoot, RECOVERY_DIRECTORY_PREFIX));
8472
+ writeSafeFile({
8473
+ root: backupRoot,
8474
+ relativePath: JOURNAL_FILE,
8475
+ content: recovery.content ?? "null\n"
8476
+ });
8477
+ writeSafeFile({
8478
+ root: backupRoot,
8479
+ relativePath: RECOVERY_CLIENT_SNAPSHOT_FILE,
8480
+ content: snapshots
8481
+ });
8482
+ const managed = /* @__PURE__ */ new Map();
8483
+ files.forEach((content, relativePath) => {
8484
+ if (content === null) return;
8485
+ const previous = recovery.managed?.get(relativePath)?.at(-1);
8486
+ const before = previous ? previous.before : recoveryBaseline(relativePath, content);
8487
+ managed.set(relativePath, [{
8488
+ before,
8489
+ after: content
8490
+ }]);
8491
+ });
8492
+ this.#save(managed);
8493
+ this.#managed = managed;
8494
+ this.#isLoaded = true;
8495
+ invocation.services.store.setState({ injectionRecoveryBackup: backupRoot });
8496
+ invocation.services.toast.show("本机规则归属已恢复,正在继续生成当前工作区的规则。", "info");
8497
+ invocation.report?.({
8498
+ success: true,
8499
+ summary: "已备份并恢复本机规则归属。",
8500
+ warnings: [`恢复备份:${backupRoot}`]
8501
+ });
8311
8502
  }
8312
8503
  get paths() {
8313
8504
  return [...this.#managed.keys()];
8314
8505
  }
8506
+ get conflicts() {
8507
+ return this.paths.flatMap((relativePath) => {
8508
+ const current = readSafeFile(this.root, relativePath);
8509
+ try {
8510
+ this.#restore(relativePath);
8511
+ return [];
8512
+ } catch (error) {
8513
+ if (!(error instanceof InjectionConflictError)) throw error;
8514
+ return [{
8515
+ path: relativePath,
8516
+ revision: fileRevision(relativePath, current)
8517
+ }];
8518
+ }
8519
+ });
8520
+ }
8521
+ /** 确认的冲突文件只在临时目录回到原基线,生成成功前不改动工作区。 */
8522
+ prepareSynchronization(overwriteFiles) {
8523
+ const before = new Map(this.paths.map((relativePath) => [relativePath, readSafeFile(this.root, relativePath)]));
8524
+ const confirmed = /* @__PURE__ */ new Set();
8525
+ for (const file of overwriteFiles) {
8526
+ if (!before.has(file.path) || confirmed.has(file.path) || fileRevision(file.path, before.get(file.path) ?? null) !== file.revision) throw new Error("客户端文件已变化,请刷新状态后重新确认强制覆盖。");
8527
+ confirmed.add(file.path);
8528
+ }
8529
+ return {
8530
+ before,
8531
+ baselines: new Map(this.paths.map((relativePath) => {
8532
+ if (!confirmed.has(relativePath)) return [relativePath, this.baseline(relativePath)];
8533
+ const managed = this.#managed.get(relativePath)?.at(-1);
8534
+ if (!managed) throw new Error(`客户端文件没有可恢复的归属记录:${relativePath}`);
8535
+ return [relativePath, managed.before];
8536
+ }))
8537
+ };
8538
+ }
8315
8539
  /** 返回去除旧注入后的当前内容,保留注入以外的用户编辑。 */
8316
8540
  baseline(relativePath) {
8317
8541
  return this.#restore(relativePath).content;
@@ -8327,13 +8551,17 @@ var InjectionWriter = class {
8327
8551
  });
8328
8552
  }
8329
8553
  /** 在写入之前验证全部文件;失败时恢复本次实际写入前的内容。 */
8330
- apply(fragments) {
8331
- const desired = /* @__PURE__ */ new Map();
8554
+ apply(fragments, synchronization) {
8555
+ for (const [relativePath, before] of synchronization?.before ?? []) if (readSafeFile(this.root, relativePath) !== before) throw new Error(`客户端文件在同步期间又有修改,已停止覆盖并保留当前内容:${relativePath}`);
8556
+ const desired = new Map(synchronization?.baselines);
8332
8557
  const nextManaged = /* @__PURE__ */ new Map();
8333
8558
  const pendingManaged = /* @__PURE__ */ new Map();
8334
8559
  const paths = /* @__PURE__ */ new Set([...this.#managed.keys(), ...fragments.keys()]);
8335
8560
  for (const relativePath of paths) {
8336
- const { content: before, managed } = this.#restore(relativePath);
8561
+ const { content: before, managed } = synchronization?.baselines.has(relativePath) ? {
8562
+ content: synchronization.baselines.get(relativePath) ?? null,
8563
+ managed: this.#managed.get(relativePath)?.at(-1)
8564
+ } : this.#restore(relativePath);
8337
8565
  const fragment = fragments.get(relativePath);
8338
8566
  const after = fragment === void 0 ? before : mergeContent({
8339
8567
  relativePath,
@@ -8401,32 +8629,54 @@ var InjectionWriter = class {
8401
8629
  managed
8402
8630
  });
8403
8631
  } catch (error) {
8404
- failure = error instanceof Error ? error : conflict(relativePath);
8632
+ failure = error instanceof Error ? new InjectionConflictError(relativePath, error) : conflict(relativePath);
8405
8633
  }
8406
8634
  }
8407
8635
  const first = restored[0];
8408
8636
  if (first && restored.every(({ content }) => content === first.content)) return first;
8409
- if (first) throw new Error(`规则注入恢复未完成:${relativePath} 在中断写入后又有改动,无法安全确认归属。请检查该文件后重试;现有内容已保留。`);
8637
+ if (first) throw new InjectionConflictError(relativePath, /* @__PURE__ */ new Error(`规则注入恢复未完成:${relativePath} 在中断写入后又有改动,无法安全确认归属。请检查该文件后重试;现有内容已保留。`));
8410
8638
  throw failure;
8411
8639
  }
8412
8640
  #load() {
8413
- if (!this.#stateRoot) return;
8641
+ if (!this.#stateRoot) return null;
8414
8642
  const filePath = safeFilePath(this.#stateRoot, JOURNAL_FILE);
8415
8643
  const metadata = lstatSync(filePath, { throwIfNoEntry: false });
8416
- if (!metadata) return;
8644
+ if (!metadata) return [...INSTRUCTION_FILES].some((relativePath) => {
8645
+ const content = readSafeFile(this.root, relativePath);
8646
+ return content?.includes(BLOCK_START) || content?.includes(BLOCK_END);
8647
+ }) ? {
8648
+ content: null,
8649
+ managed: null,
8650
+ message: "客户端保留了旧规则注入,但本机归属记录已缺失。"
8651
+ } : null;
8417
8652
  if (!metadata.isFile() || metadata.size > MAXIMUM_JOURNAL_BYTES) throw new Error("规则注入归属记录不是有效文件;请检查规则插件的私有存储后重试。");
8653
+ const content = readFileSync(filePath, "utf8");
8418
8654
  let stored;
8419
8655
  try {
8420
- stored = JSON.parse(readFileSync(filePath, "utf8"));
8421
- } catch (error) {
8422
- throw new Error("无法读取规则注入归属记录;已保留客户端文件,请检查规则插件的私有存储后重试。", { cause: error });
8656
+ stored = JSON.parse(content);
8657
+ } catch {
8658
+ return {
8659
+ content,
8660
+ managed: null,
8661
+ message: "本机规则归属记录无法解析。"
8662
+ };
8423
8663
  }
8424
8664
  const parsed = JOURNAL_SCHEMA.safeParse(stored);
8425
- if (!parsed.success || parsed.data.root !== this.root) throw new Error("规则注入归属记录无效或不属于当前工作区;已保留客户端文件,请检查私有存储后重试。");
8665
+ if (!parsed.success) return {
8666
+ content,
8667
+ managed: null,
8668
+ message: "本机规则归属记录格式已失效。"
8669
+ };
8426
8670
  const managed = new Map(parsed.data.files);
8427
8671
  if (managed.size !== parsed.data.files.length) throw new Error("规则注入归属记录含重复文件,已保留客户端文件。");
8428
8672
  managed.forEach((_candidates, relativePath) => safeFilePath(this.root, relativePath));
8673
+ if (parsed.data.root !== this.root) return {
8674
+ content,
8675
+ managed,
8676
+ message: "项目目录已变化,旧规则归属记录仍绑定原目录。"
8677
+ };
8429
8678
  this.#managed = managed;
8679
+ return null;
8430
8680
  }
8431
8681
  #save(managed) {
8432
8682
  if (!this.#stateRoot) return;
@@ -8447,6 +8697,29 @@ var InjectionWriter = class {
8447
8697
  }
8448
8698
  }
8449
8699
  };
8700
+ /** 重建时仅移除已确认要替换的会话区块与 MCP 配置,保留其他客户端设置。 */
8701
+ function recoveryBaseline(relativePath, content) {
8702
+ if (INSTRUCTION_FILES.has(path.posix.basename(relativePath))) {
8703
+ const start = content.indexOf(BLOCK_START);
8704
+ const end = content.indexOf(BLOCK_END, start);
8705
+ if (start < 0 && end < 0) return content;
8706
+ if (start < 0 || end < start || content.indexOf(BLOCK_START, start + 30) >= 0 || content.indexOf(BLOCK_END, end + 28) >= 0) return null;
8707
+ const prefix = content.slice(0, start);
8708
+ const suffix = content.slice(end + 28);
8709
+ return (prefix.endsWith("\n\n") ? prefix.slice(0, -2) : prefix) + (suffix.startsWith("\n") ? suffix.slice(1) : suffix);
8710
+ }
8711
+ try {
8712
+ const document = { ...parseDocument$1(relativePath, content) };
8713
+ RECOVERY_MCP_KEYS.forEach((key) => delete document[key]);
8714
+ return formatDocument({
8715
+ relativePath,
8716
+ previous: content,
8717
+ document
8718
+ });
8719
+ } catch {
8720
+ return null;
8721
+ }
8722
+ }
8450
8723
  /** 只接受源树或客户端树内的相对路径,不跟随符号链接。 */
8451
8724
  function safeFilePath(root, relativePath) {
8452
8725
  if (lstatSync(root).isSymbolicLink()) throw new Error("规则输出根目录不能是符号链接。");
@@ -8670,7 +8943,10 @@ function isObject(value) {
8670
8943
  return value !== null && typeof value === "object" && !Array.isArray(value);
8671
8944
  }
8672
8945
  function conflict(relativePath) {
8673
- return /* @__PURE__ */ new Error(`规则不会覆盖或撤销已被修改的文件:${relativePath}`);
8946
+ return new InjectionConflictError(relativePath);
8947
+ }
8948
+ function fileRevision(relativePath, content) {
8949
+ return createHash("sha256").update(JSON.stringify([relativePath, content])).digest("hex");
8674
8950
  }
8675
8951
  //#endregion
8676
8952
  //#region src/injection.ts
@@ -8721,6 +8997,7 @@ var InjectionService = class {
8721
8997
  #options;
8722
8998
  #writer;
8723
8999
  #requests = /* @__PURE__ */ new Map();
9000
+ #pendingRequests = /* @__PURE__ */ new Map();
8724
9001
  #fragments = /* @__PURE__ */ new Map();
8725
9002
  #targets = [];
8726
9003
  #pending = null;
@@ -8742,9 +9019,11 @@ var InjectionService = class {
8742
9019
  }
8743
9020
  }
8744
9021
  status(identity) {
8745
- const requests = [...this.#requests.values()].filter((request) => !identity || key(request) === key(identity));
9022
+ const requests = [...new Map([...this.#requests, ...this.#pendingRequests]).values()].filter((request) => !identity || key(request) === key(identity));
9023
+ const pending = requests.some((request) => this.#pendingRequests.has(key(request)));
8746
9024
  return {
8747
- injected: requests.length > 0 && this.#writer.isApplied(),
9025
+ injected: requests.length > 0 && !pending && this.#writer.isApplied(),
9026
+ pending,
8748
9027
  injections: requests.map(({ pluginId, id, files, mcpServers }) => ({
8749
9028
  pluginId,
8750
9029
  id,
@@ -8764,6 +9043,7 @@ var InjectionService = class {
8764
9043
  summary: "AI 上下文注入未完成。"
8765
9044
  });
8766
9045
  if (isDeepStrictEqual(this.#requests.get(key(request)), request) && isDeepStrictEqual(this.#targets, this.#options.targets()) && this.#writer.isApplied()) {
9046
+ this.#pendingRequests.delete(key(request));
8767
9047
  invocation.report?.({
8768
9048
  ...details,
8769
9049
  success: true,
@@ -8771,10 +9051,15 @@ var InjectionService = class {
8771
9051
  });
8772
9052
  return this.status(request);
8773
9053
  }
8774
- const requests = new Map(this.#requests);
9054
+ const requests = new Map([...this.#requests, ...this.#pendingRequests]);
8775
9055
  requests.set(key(request), request);
8776
9056
  if (requests.size > MAXIMUM_INJECTIONS) throw new Error("当前会话的规则注入数量过多。");
8777
- await this.#update(requests, invocation);
9057
+ try {
9058
+ await this.#update(requests, invocation);
9059
+ } catch (error) {
9060
+ if (error instanceof InjectionConflictError && this.#writer.paths.includes(error.path) && !invocation.signal.aborted) this.#pendingRequests.set(key(request), request);
9061
+ throw error;
9062
+ }
8778
9063
  invocation.report?.({
8779
9064
  ...details,
8780
9065
  success: true,
@@ -8789,9 +9074,10 @@ var InjectionService = class {
8789
9074
  const requests = new Map(this.#requests);
8790
9075
  const request = requests.get(key(identity));
8791
9076
  if (!request) {
9077
+ const wasPending = this.#pendingRequests.delete(key(identity));
8792
9078
  invocation.report?.({
8793
9079
  success: true,
8794
- summary: `注入 ${key(identity)} 不存在,无需撤销。`
9080
+ summary: wasPending ? `已取消待恢复注入:${key(identity)}。` : `注入 ${key(identity)} 不存在,无需撤销。`
8795
9081
  });
8796
9082
  return this.status(identity);
8797
9083
  }
@@ -8803,6 +9089,7 @@ var InjectionService = class {
8803
9089
  });
8804
9090
  requests.delete(key(identity));
8805
9091
  await this.#update(requests, invocation);
9092
+ this.#pendingRequests.delete(key(identity));
8806
9093
  invocation.report?.({
8807
9094
  ...details,
8808
9095
  success: true,
@@ -8816,6 +9103,7 @@ var InjectionService = class {
8816
9103
  return this.run(async () => {
8817
9104
  this.#writer.cleanup();
8818
9105
  this.#requests.clear();
9106
+ this.#pendingRequests.clear();
8819
9107
  this.#fragments.clear();
8820
9108
  this.#targets = [];
8821
9109
  });
@@ -8831,13 +9119,19 @@ var InjectionService = class {
8831
9119
  if (this.#requests.size && targets.some((target) => !SUPPORTED_TARGETS.has(target))) throw new Error("存在动态注入时,仅支持选择 Codex CLI 和 Claude Code。");
8832
9120
  }
8833
9121
  /** 团队规则同步在基线文件上执行,完成后重新覆盖本会话的动态内容。 */
8834
- async synchronize(operation, invocation) {
9122
+ async synchronize(operation, { invocation, overwriteFiles = [] }) {
8835
9123
  return this.run(async () => {
9124
+ await this.#writer.prepare(invocation);
9125
+ if (overwriteFiles.length) return this.#synchronizeOverwrite(operation, {
9126
+ invocation,
9127
+ overwriteFiles
9128
+ });
8836
9129
  this.#writer.apply(/* @__PURE__ */ new Map());
8837
9130
  try {
8838
- return await operation();
9131
+ return await operation(this.#options.workspaceRoot);
8839
9132
  } finally {
8840
- if (this.#requests.size && !invocation.signal.aborted && !isDeepStrictEqual(this.#targets, this.#options.targets())) await this.#update(this.#requests, invocation);
9133
+ const targetsChanged = this.#requests.size > 0 && !isDeepStrictEqual(this.#targets, this.#options.targets());
9134
+ if ((this.#pendingRequests.size > 0 || targetsChanged) && !invocation.signal.aborted) await this.#update(new Map([...this.#requests, ...this.#pendingRequests]), invocation);
8841
9135
  else this.#writer.apply(this.#fragments);
8842
9136
  }
8843
9137
  }, invocation.signal);
@@ -8845,6 +9139,9 @@ var InjectionService = class {
8845
9139
  get paths() {
8846
9140
  return this.#writer.paths;
8847
9141
  }
9142
+ get conflicts() {
9143
+ return this.#writer.conflicts;
9144
+ }
8848
9145
  baseline(relativePath) {
8849
9146
  return this.#writer.baseline(relativePath);
8850
9147
  }
@@ -8853,6 +9150,45 @@ var InjectionService = class {
8853
9150
  new InjectionWriter(outputRoot).apply(this.#fragments);
8854
9151
  }
8855
9152
  async #update(requests, invocation) {
9153
+ const fragments = await this.#generate(requests, invocation);
9154
+ invocation.signal.throwIfAborted();
9155
+ await this.#writer.prepare(invocation);
9156
+ this.#writer.apply(fragments);
9157
+ this.#requests = new Map(requests);
9158
+ requests.forEach((_request, identity) => this.#pendingRequests.delete(identity));
9159
+ this.#fragments = fragments;
9160
+ this.#targets = [...this.#options.targets()];
9161
+ }
9162
+ async #synchronizeOverwrite(operation, { invocation, overwriteFiles = [] }) {
9163
+ const files = this.#writer.prepareSynchronization(overwriteFiles);
9164
+ const temporaryRoot = mkdtempSync(path.join(os.tmpdir(), "workbase-ai-sync-"));
9165
+ try {
9166
+ writeFileBatch(temporaryRoot, files.baselines);
9167
+ const result = await operation(temporaryRoot);
9168
+ if (!result.success) return result;
9169
+ const requests = new Map([...this.#requests, ...this.#pendingRequests]);
9170
+ const targets = this.#options.targets();
9171
+ const fragments = this.#pendingRequests.size > 0 || !isDeepStrictEqual(this.#targets, targets) ? await this.#generate(requests, invocation) : this.#fragments;
9172
+ const baselines = new Map([...files.before.keys()].map((relativePath) => [relativePath, null]));
9173
+ readOutputFiles(temporaryRoot).forEach((content, relativePath) => baselines.set(relativePath, content));
9174
+ invocation.signal.throwIfAborted();
9175
+ this.#writer.apply(fragments, {
9176
+ before: files.before,
9177
+ baselines
9178
+ });
9179
+ this.#requests = requests;
9180
+ this.#pendingRequests.clear();
9181
+ this.#fragments = new Map(fragments);
9182
+ this.#targets = [...targets];
9183
+ return result;
9184
+ } finally {
9185
+ rmSync(temporaryRoot, {
9186
+ recursive: true,
9187
+ force: true
9188
+ });
9189
+ }
9190
+ }
9191
+ async #generate(requests, invocation) {
8856
9192
  const targets = this.#options.targets();
8857
9193
  if (requests.size && targets.some((target) => !SUPPORTED_TARGETS.has(target))) throw new Error("动态注入当前支持 Codex CLI 和 Claude Code,请在规则中选择对应客户端。");
8858
9194
  const temporaryRoot = mkdtempSync(path.join(os.tmpdir(), "workbase-ai-inject-"));
@@ -8872,11 +9208,7 @@ var InjectionService = class {
8872
9208
  }
8873
9209
  const fragments = readOutputFiles(outputRoot);
8874
9210
  if (requests.size && !fragments.size) throw new Error("Rulesync 未生成注入文件,请检查源文件格式及目标客户端。");
8875
- invocation.signal.throwIfAborted();
8876
- this.#writer.apply(fragments);
8877
- this.#requests = new Map(requests);
8878
- this.#fragments = fragments;
8879
- this.#targets = [...targets];
9211
+ return fragments;
8880
9212
  } finally {
8881
9213
  rmSync(temporaryRoot, {
8882
9214
  recursive: true,
@@ -15640,6 +15972,8 @@ const resourceImportSchema = object({ directory: string().min(1).max(4096) }).st
15640
15972
  /** Reads and edits canonical Rulesync sources; client generation remains in the plugin. */
15641
15973
  const WORKFLOW_PLUGIN_ID = "ai-workflows";
15642
15974
  const WORKFLOW_SKILL_REFERENCES_STATUS_ID = "skill.references";
15975
+ const GIT_PROGRAM = "git";
15976
+ const GIT_INSPECTION_TIMEOUT_MILLISECONDS = 15e3;
15643
15977
  function registerResources(context, hooks) {
15644
15978
  const root = context.project.root;
15645
15979
  const catalog = () => ({ resources: resourceDocuments(root).map(({ files, ...summary }) => ({
@@ -15650,7 +15984,70 @@ function registerResources(context, hooks) {
15650
15984
  id: "resources",
15651
15985
  label: "资源",
15652
15986
  description: "只读列出项目规则、技能和 MCP。",
15653
- resolve: catalog
15987
+ resolve: async (_input, invocation) => {
15988
+ const current = catalog();
15989
+ if (!current.resources.length) return current;
15990
+ const sourcePaths = (resource) => resource.kind === "mcp" ? [mcpSource(root).path] : resource.paths;
15991
+ const paths = [...new Set(current.resources.flatMap(sourcePaths))];
15992
+ const inspect = (argumentsList) => resourceGitOutput(invocation, {
15993
+ program: GIT_PROGRAM,
15994
+ currentDirectory: root,
15995
+ arguments: argumentsList
15996
+ });
15997
+ try {
15998
+ const upstream = (await inspect([
15999
+ "rev-parse",
16000
+ "--verify",
16001
+ "@{upstream}"
16002
+ ])).trim();
16003
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(upstream)) throw new Error("团队同步记录不可用。");
16004
+ const [publishedOutput, changedOutput] = await Promise.all([inspect([
16005
+ "ls-tree",
16006
+ "-r",
16007
+ "--name-only",
16008
+ "-z",
16009
+ upstream,
16010
+ "--",
16011
+ ...paths
16012
+ ]), inspect([
16013
+ "diff",
16014
+ "--relative",
16015
+ "--name-only",
16016
+ "-z",
16017
+ "--no-renames",
16018
+ upstream,
16019
+ "--",
16020
+ ...paths
16021
+ ])]);
16022
+ const published = new Set(publishedOutput.split("\0"));
16023
+ const changed = new Set(changedOutput.split("\0"));
16024
+ return { resources: current.resources.map((resource) => {
16025
+ const sources = sourcePaths(resource);
16026
+ if (sources.every((source) => !published.has(source))) return {
16027
+ ...resource,
16028
+ publicationStatus: "local"
16029
+ };
16030
+ if (sources.some((source) => !published.has(source) || changed.has(source))) return {
16031
+ ...resource,
16032
+ publicationStatus: "pending"
16033
+ };
16034
+ return {
16035
+ ...resource,
16036
+ publicationStatus: "synced"
16037
+ };
16038
+ }) };
16039
+ } catch (failure) {
16040
+ invocation.signal.throwIfAborted();
16041
+ context.logger.warn("无法核对资源的团队同步状态。", failure);
16042
+ return {
16043
+ resources: current.resources.map((resource) => ({
16044
+ ...resource,
16045
+ publicationStatus: "unknown"
16046
+ })),
16047
+ publicationWarning: "暂时无法核对团队同步状态,资源仍可查看。请刷新列表重试。"
16048
+ };
16049
+ }
16050
+ }
15654
16051
  });
15655
16052
  hooks.registerStatus({
15656
16053
  id: "resource",
@@ -15773,6 +16170,20 @@ function resourceDocuments(root) {
15773
16170
  });
15774
16171
  return documents.sort((left, right) => `${left.kind}/${left.id}`.localeCompare(`${right.kind}/${right.id}`));
15775
16172
  }
16173
+ /** 与资源目录共用规则条目标识,概览只枚举文件。 */
16174
+ function countProjectRules(root) {
16175
+ return directoryEntries(root, "rules").filter(({ entry }) => entry.isFile()).length;
16176
+ }
16177
+ async function resourceGitOutput(invocation, options) {
16178
+ const result = await invocation.process.run({
16179
+ ...options,
16180
+ outputMode: PluginProcessOutputMode.Content,
16181
+ timeoutMilliseconds: GIT_INSPECTION_TIMEOUT_MILLISECONDS,
16182
+ environment: { GIT_OPTIONAL_LOCKS: "0" }
16183
+ }, invocation.signal);
16184
+ if (result.failed || result.timedOut || result.wasCancelled || result.standardOutputTruncated !== false) throw new Error("无法完整读取资源的团队同步状态。");
16185
+ return result.standardOutput;
16186
+ }
15776
16187
  function document(identity, contents) {
15777
16188
  const files = [...contents].sort(([left], [right]) => left.localeCompare(right)).map(([path, content]) => ({
15778
16189
  path,
@@ -15924,16 +16335,7 @@ function importSkill(context, directory) {
15924
16335
  }
15925
16336
  function directoryResources(root, kind) {
15926
16337
  const documents = [];
15927
- const directory = safeFilePath(root, `rules/.rulesync/${kind}`);
15928
- if (!existsSync(directory)) return [];
15929
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
15930
- const id = kind === "skills" ? entry.name : entry.name.replace(/\.md$/, "");
15931
- if (!resourceIdentitySchema.safeParse({
15932
- kind,
15933
- id
15934
- }).success) continue;
15935
- if (kind !== "skills" && !entry.name.endsWith(".md")) continue;
15936
- const source = `rules/.rulesync/${kind}/${entry.name}`;
16338
+ for (const { entry, id, source } of directoryEntries(root, kind)) {
15937
16339
  const target = safeFilePath(root, source);
15938
16340
  const contents = kind === "skills" && entry.isDirectory() ? new Map([...readOutputFiles(target)].map(([file, content]) => [`${source}/${file}`, content])) : /* @__PURE__ */ new Map([[source, readSafeFile(root, source)]]);
15939
16341
  if (kind === "skills" && !contents.has(`${source}/SKILL.md`)) continue;
@@ -15944,6 +16346,23 @@ function directoryResources(root, kind) {
15944
16346
  }
15945
16347
  return documents;
15946
16348
  }
16349
+ function directoryEntries(root, kind) {
16350
+ const prefix = `rules/.rulesync/${kind}`;
16351
+ const directory = safeFilePath(root, prefix);
16352
+ if (!existsSync(directory)) return [];
16353
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
16354
+ if (kind !== "skills" && !entry.name.endsWith(".md")) return [];
16355
+ const id = kind === "skills" ? entry.name : entry.name.slice(0, -3);
16356
+ return resourceIdentitySchema.safeParse({
16357
+ kind,
16358
+ id
16359
+ }).success ? [{
16360
+ entry,
16361
+ id,
16362
+ source: `${prefix}/${entry.name}`
16363
+ }] : [];
16364
+ });
16365
+ }
15947
16366
  //#endregion
15948
16367
  //#region src/rulesync.ts
15949
16368
  /** Rulesync generation, preview, synchronization and result normalization. */
@@ -16002,7 +16421,8 @@ async function generateRules({ config, features: requestedFeatures, invocation,
16002
16421
  });
16003
16422
  }
16004
16423
  async function previewRules({ injections, ...options }) {
16005
- if (!injections.status().injections.length) return generateRules(options);
16424
+ const injectionStatus = injections.status();
16425
+ if (!injectionStatus.injections.length) return generateRules(options);
16006
16426
  const preview = await generateRules({
16007
16427
  ...options,
16008
16428
  mode: "preview"
@@ -16026,7 +16446,7 @@ async function previewRules({ injections, ...options }) {
16026
16446
  if (!generated.success) return generated;
16027
16447
  injections.applyTo(temporaryRoot);
16028
16448
  const outputs = readOutputFiles(temporaryRoot);
16029
- const hasDiff = [...outputs].filter(([relativePath, content]) => readSafeFile(workspaceRoot, relativePath) !== content).length > 0;
16449
+ const hasDiff = [...outputs].filter(([relativePath, content]) => readSafeFile(workspaceRoot, relativePath) !== content).length > 0 || injectionStatus.pending;
16030
16450
  const details = isRecord(preview.details) && isRecord(preview.details.data) ? preview.details.data : {};
16031
16451
  const features = isRecord(details.features) ? details.features : {};
16032
16452
  const success = options.mode !== "check" || !hasDiff;
@@ -16036,6 +16456,7 @@ async function previewRules({ injections, ...options }) {
16036
16456
  success,
16037
16457
  standardOutput: "",
16038
16458
  standardError: success ? "" : "客户端文件与团队规则及当前动态注入不一致。",
16459
+ warnings: injectionStatus.pending ? [...preview.warnings, "仍有会话注入等待恢复,请执行同步以恢复客户端能力。"] : preview.warnings,
16039
16460
  details: {
16040
16461
  success,
16041
16462
  data: {
@@ -16241,6 +16662,10 @@ const CONFIGURATION_INPUT_SCHEMA = object({
16241
16662
  features: array(string().trim().min(1)).min(1),
16242
16663
  targets: array(string().trim().min(1)).min(1)
16243
16664
  }).strict();
16665
+ const SYNC_INPUT_SCHEMA = object({ overwriteFiles: array(object({
16666
+ path: string().min(1).max(240),
16667
+ revision: string().regex(/^[a-f0-9]{64}$/)
16668
+ }).strict()).max(1024).optional() }).strict().default({});
16244
16669
  var plugin_default = definePlugin({
16245
16670
  id: PLUGIN_ID,
16246
16671
  title: "规则",
@@ -16336,10 +16761,13 @@ var plugin_default = definePlugin({
16336
16761
  }));
16337
16762
  }
16338
16763
  });
16339
- const status = () => buildStatus({
16340
- config,
16341
- paths,
16342
- state: context.services.store.getState()
16764
+ const status = () => ({
16765
+ ...buildStatus({
16766
+ config,
16767
+ paths,
16768
+ state: context.services.store.getState()
16769
+ }),
16770
+ conflicts: injections.conflicts
16343
16771
  });
16344
16772
  const record = (result, invocation) => {
16345
16773
  invocation?.report?.({
@@ -16371,14 +16799,20 @@ var plugin_default = definePlugin({
16371
16799
  paths,
16372
16800
  injections
16373
16801
  }), invocation.signal), invocation);
16374
- const runSynchronization = async ({ initializationResult, invocation, operation, sourceArguments }) => record(await injections.synchronize(() => synchronizeRules({
16802
+ const runSynchronization = async ({ initializationResult, invocation, operation, overwriteFiles, sourceArguments }) => record(await injections.synchronize((workspaceRoot) => synchronizeRules({
16375
16803
  config,
16376
16804
  initializationResult,
16377
16805
  invocation,
16378
16806
  operation,
16379
- paths,
16807
+ paths: {
16808
+ ...paths,
16809
+ workspaceRoot
16810
+ },
16380
16811
  sourceArguments
16381
- }), invocation), invocation);
16812
+ }), {
16813
+ invocation,
16814
+ overwriteFiles
16815
+ }), invocation);
16382
16816
  const initialize = async (invocation) => {
16383
16817
  mkdirSync(paths.sourceRoot, { recursive: true });
16384
16818
  mkdirSync(safeFilePath(context.project.root, "rules/.rulesync"), { recursive: true });
@@ -16583,14 +17017,17 @@ var plugin_default = definePlugin({
16583
17017
  hooks.registerCommand({
16584
17018
  effect: PluginCommandEffect.LongRunning,
16585
17019
  id: "sync",
17020
+ input: SYNC_INPUT_SCHEMA,
16586
17021
  title: "同步规则",
16587
17022
  description: "组装 Rules、MCP、Commands、Subagents 和 Skills 并写入当前 Workspace。",
16588
17023
  transaction: PluginCommandTransaction.ProjectMutation,
16589
17024
  plan: () => ({ kind: PluginSharedChangeKind.None }),
16590
- run: async (_input, invocation) => {
17025
+ run: async (input, invocation) => {
17026
+ const { overwriteFiles } = SYNC_INPUT_SCHEMA.parse(input);
16591
17027
  const result = await runSynchronization({
16592
17028
  invocation,
16593
- operation: "sync"
17029
+ operation: "sync",
17030
+ overwriteFiles
16594
17031
  });
16595
17032
  requireSuccessfulOperation(result);
16596
17033
  return {
@@ -16648,7 +17085,21 @@ var plugin_default = definePlugin({
16648
17085
  description: "诊断、预览并同步当前 Workspace 的 AI 客户端上下文。",
16649
17086
  entry: "dist/ui/index.html",
16650
17087
  id: "workspace",
17088
+ overviewCard: {
17089
+ icon: "list-checks",
17090
+ order: 30,
17091
+ tone: "yellow",
17092
+ resolve: () => {
17093
+ const configured = isConfigured(paths);
17094
+ return {
17095
+ status: configured ? "ready" : "warning",
17096
+ value: `${countProjectRules(context.project.root)} 条规则`,
17097
+ ...!configured && { detail: "待配置" }
17098
+ };
17099
+ }
17100
+ },
16651
17101
  slot: "workspace.tab",
17102
+ layout: PluginViewLayout.Fill,
16652
17103
  handlers: createMarkdownHandlers({ root: rulesRoot })
16653
17104
  });
16654
17105
  }