@marktrue/dsh-mobile-remote 3.2.4 → 3.3.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -342
- package/docs/03-api.md +147 -9
- package/docs/04-security.md +13 -8
- package/docs/09-compatibility.md +2 -2
- package/lib/endpoint-registry.js +12 -0
- package/lib/index.js +1362 -21
- package/package.json +2 -2
package/lib/index.js
CHANGED
|
@@ -794,6 +794,16 @@ const FILE_RANGE_CAPABILITIES = {
|
|
|
794
794
|
version: 1,
|
|
795
795
|
supported: true,
|
|
796
796
|
};
|
|
797
|
+
/**
|
|
798
|
+
* GitLab #16:文件下载的会话作用域能力位。
|
|
799
|
+
*
|
|
800
|
+
* 新 App 据此把 `/api/files` 从「绝对路径」切到「sessionId + cwd 相对路径」;
|
|
801
|
+
* 旧插件不下发该位时,App 回退旧绝对路径实现(行为与升级前一致,不会错读)。
|
|
802
|
+
*/
|
|
803
|
+
const FILES_CAPABILITIES = {
|
|
804
|
+
version: 1,
|
|
805
|
+
sessionRelative: true,
|
|
806
|
+
};
|
|
797
807
|
|
|
798
808
|
/**
|
|
799
809
|
* 轮次大纲能力(issue #25 二期):插件把宿主的 `turnOutline` 投影透出为移动端契约,
|
|
@@ -1684,6 +1694,70 @@ export function openVerifiedWorkspaceImage({
|
|
|
1684
1694
|
}
|
|
1685
1695
|
}
|
|
1686
1696
|
|
|
1697
|
+
/**
|
|
1698
|
+
* GitLab #16:打开并验证 `/m/api/files` 的目标文件,确保读取发生在**已校验的句柄**上。
|
|
1699
|
+
*
|
|
1700
|
+
* 安全模型(fail-closed):
|
|
1701
|
+
* - 只接受绝对 candidateLex,且实际路径必须落在 roots(realpath 后的允许根)之一;
|
|
1702
|
+
* - Linux 上以 `O_RDONLY|O_NOFOLLOW|O_NONBLOCK` 打开:末级符号链接被拒,设备/FIFO
|
|
1703
|
+
* 不会阻塞;`fstat` 必须是普通文件;再用 `/proc/self/fd/<fd>` 的真实路径复核,
|
|
1704
|
+
* 中间目录换链/读取前替换目标都无法逃出 roots;
|
|
1705
|
+
* - 无 procfs / 无 O_NOFOLLOW / 非 Linux → `503 files-unavailable`(不降级为路径读取)。
|
|
1706
|
+
*
|
|
1707
|
+
* 供 HTTP 端点与确定性平台/竞态测试共用;fs/platform 可注入。
|
|
1708
|
+
*/
|
|
1709
|
+
export function openVerifiedContainedFile({
|
|
1710
|
+
candidateLex,
|
|
1711
|
+
roots,
|
|
1712
|
+
platform = process.platform,
|
|
1713
|
+
fs = { existsSync, openSync, fstatSync, readlinkSync, closeSync, constants },
|
|
1714
|
+
}) {
|
|
1715
|
+
const inside = (parent, child) => {
|
|
1716
|
+
const rel = relative(parent, child);
|
|
1717
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
1718
|
+
};
|
|
1719
|
+
if (typeof candidateLex !== "string" || !isAbsolute(candidateLex)) {
|
|
1720
|
+
return { ok: false, status: 400, code: "bad-request" };
|
|
1721
|
+
}
|
|
1722
|
+
if (!Array.isArray(roots) || roots.length === 0) {
|
|
1723
|
+
return { ok: false, status: 403, code: "workspace-not-authorized" };
|
|
1724
|
+
}
|
|
1725
|
+
const procRoot = platform === "linux" ? "/proc/self/fd" : "";
|
|
1726
|
+
const noFollow = fs.constants?.O_NOFOLLOW;
|
|
1727
|
+
if (platform !== "linux" || noFollow === undefined || !procRoot || !fs.existsSync(procRoot)) {
|
|
1728
|
+
return { ok: false, status: 503, code: "files-unavailable" };
|
|
1729
|
+
}
|
|
1730
|
+
let fd = null;
|
|
1731
|
+
const fail = (status, code) => {
|
|
1732
|
+
if (fd !== null) {
|
|
1733
|
+
try { fs.closeSync(fd); } catch {}
|
|
1734
|
+
fd = null;
|
|
1735
|
+
}
|
|
1736
|
+
return { ok: false, status, code };
|
|
1737
|
+
};
|
|
1738
|
+
try {
|
|
1739
|
+
fd = fs.openSync(
|
|
1740
|
+
candidateLex,
|
|
1741
|
+
fs.constants.O_RDONLY | noFollow | (fs.constants.O_NONBLOCK ?? 0),
|
|
1742
|
+
);
|
|
1743
|
+
} catch (err) {
|
|
1744
|
+
if (err?.code === "ELOOP") return fail(403, "path-outside-workspace");
|
|
1745
|
+
if (err?.code === "EACCES" || err?.code === "EPERM") return fail(403, "file-forbidden");
|
|
1746
|
+
return fail(404, "file-not-found");
|
|
1747
|
+
}
|
|
1748
|
+
let stats;
|
|
1749
|
+
try { stats = fs.fstatSync(fd); } catch { return fail(404, "file-not-found"); }
|
|
1750
|
+
if (!stats.isFile()) return fail(400, "not-a-file");
|
|
1751
|
+
let actualPath;
|
|
1752
|
+
try { actualPath = fs.readlinkSync(`${procRoot}/${fd}`); } catch { return fail(503, "files-unavailable"); }
|
|
1753
|
+
actualPath = String(actualPath ?? "").replace(/ \(deleted\)$/, "");
|
|
1754
|
+
if (!isAbsolute(actualPath)) return fail(503, "files-unavailable");
|
|
1755
|
+
if (!roots.some((root) => inside(root, actualPath))) {
|
|
1756
|
+
return fail(403, "path-outside-workspace");
|
|
1757
|
+
}
|
|
1758
|
+
return { ok: true, fd, stats, actualPath };
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1687
1761
|
/** issue #98:工作区外图片的会话授权(仅内存、12h TTL、不可伪造、绑定 session)。 */
|
|
1688
1762
|
export function createWorkspaceImageConsentStore({ ttlMs = 12 * 60 * 60 * 1000, maxEntries = 512 } = {}) {
|
|
1689
1763
|
const entries = new Map();
|
|
@@ -3384,11 +3458,54 @@ function summarizeEventCoreBody(event, options = {}) {
|
|
|
3384
3458
|
...(typeof message.source?.kind === "string" && message.source.kind !== ""
|
|
3385
3459
|
? { sourceKind: message.source.kind }
|
|
3386
3460
|
: {}),
|
|
3461
|
+
// issue #144:当前会话消息索引只读投影。team-message / agent-message 的
|
|
3462
|
+
// 发送方信息只在来源对象里,但普通时间线不能因此显示内部对象;这里只透出
|
|
3463
|
+
// 发送方显示名/短 id 与团队邮箱 messageId(索引用它合并投递状态)。
|
|
3464
|
+
...(message.source?.kind === "team-message" && typeof message.source.senderName === "string"
|
|
3465
|
+
? { sourceSenderName: message.source.senderName }
|
|
3466
|
+
: {}),
|
|
3467
|
+
...(["team-message", "agent-message"].includes(message.source?.kind)
|
|
3468
|
+
&& typeof (message.source.senderId ?? message.source.senderSessionId) === "string"
|
|
3469
|
+
? { sourceSenderId: message.source.senderId ?? message.source.senderSessionId }
|
|
3470
|
+
: {}),
|
|
3471
|
+
...(message.source?.kind === "team-message" && typeof message.source.messageId === "string"
|
|
3472
|
+
? { sourceMessageId: message.source.messageId }
|
|
3473
|
+
: {}),
|
|
3387
3474
|
...(images.length ? { images } : {}),
|
|
3388
3475
|
...(files.length ? { files } : {}),
|
|
3389
3476
|
},
|
|
3390
3477
|
};
|
|
3391
3478
|
}
|
|
3479
|
+
// issue #144:消息索引的只读投影。team/message/* 仍是调试可见事件,
|
|
3480
|
+
// 普通时间线不渲染;这里只给 App 索引需要的发送方/接收方/正文/投递身份。
|
|
3481
|
+
case "team/message/queued": {
|
|
3482
|
+
const message = data?.message;
|
|
3483
|
+
if (!message || typeof message !== "object") return { seq, type };
|
|
3484
|
+
const text = blocksToText(message.content);
|
|
3485
|
+
return {
|
|
3486
|
+
seq,
|
|
3487
|
+
type,
|
|
3488
|
+
data: {
|
|
3489
|
+
...(typeof message.id === "string" ? { messageId: message.id } : {}),
|
|
3490
|
+
...(typeof message.senderId === "string" ? { senderId: message.senderId } : {}),
|
|
3491
|
+
...(typeof message.senderName === "string" ? { senderName: message.senderName } : {}),
|
|
3492
|
+
...(typeof message.targetId === "string" ? { targetId: message.targetId } : {}),
|
|
3493
|
+
text: clampText(text, 2000),
|
|
3494
|
+
},
|
|
3495
|
+
};
|
|
3496
|
+
}
|
|
3497
|
+
case "team/message/delivered": {
|
|
3498
|
+
const messageId = typeof data?.messageId === "string" ? data.messageId : undefined;
|
|
3499
|
+
if (messageId === undefined) return { seq, type };
|
|
3500
|
+
return {
|
|
3501
|
+
seq,
|
|
3502
|
+
type,
|
|
3503
|
+
data: {
|
|
3504
|
+
messageId,
|
|
3505
|
+
...(typeof data.targetId === "string" ? { targetId: data.targetId } : {}),
|
|
3506
|
+
},
|
|
3507
|
+
};
|
|
3508
|
+
}
|
|
3392
3509
|
case "assistant/message": {
|
|
3393
3510
|
const message = data.message;
|
|
3394
3511
|
// review:深层字段缺失守卫(message 缺失时返回空摘要而非 TypeError)
|
|
@@ -4381,6 +4498,569 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
4381
4498
|
canRestartHost: canRestart,
|
|
4382
4499
|
};
|
|
4383
4500
|
}
|
|
4501
|
+
// issue #145:插件清单/健康只读投影。
|
|
4502
|
+
//
|
|
4503
|
+
// 事实只来自宿主:`pluginManager.listBundles()` 给出 bundle 的版本/来源/启停/错误,
|
|
4504
|
+
// `pluginInventory.list()` 给出运行期 fiber 相位与失败诊断。App 不自行推断。
|
|
4505
|
+
// 旧宿主没有这些服务/方法时 supported=false(App 整页降级),不伪造空清单。
|
|
4506
|
+
function pluginInventorySource(bundle) {
|
|
4507
|
+
if (bundle?.official === true && bundle?.availability === "installation") {
|
|
4508
|
+
return { kind: "builtin", label: "内置" };
|
|
4509
|
+
}
|
|
4510
|
+
const spec = typeof bundle?.source === "string" ? bundle.source.trim() : "";
|
|
4511
|
+
if (spec === "") return { kind: "unknown", label: "未知" };
|
|
4512
|
+
if (/^(file:|link:)/i.test(spec)) return { kind: "local", label: "本地" };
|
|
4513
|
+
if (/^(git\+|git:|github:|gitlab:|bitbucket:|ssh:|https?:\/\/.*\.git(?:#|$))/i.test(spec)) {
|
|
4514
|
+
return { kind: "git", label: "Git" };
|
|
4515
|
+
}
|
|
4516
|
+
return { kind: "registry", label: "配置渠道" };
|
|
4517
|
+
}
|
|
4518
|
+
|
|
4519
|
+
function pluginInventoryCompatibility(bundle) {
|
|
4520
|
+
const error = bundle?.error;
|
|
4521
|
+
if (!error || error.code !== "incompatible-version") {
|
|
4522
|
+
// 宿主 listBundles 不提供兼容判定:没有 incompatible-version 证据时只能是“未知”,
|
|
4523
|
+
// 不能把“没报错”当成“兼容”(#145 P2:健康/兼容事实不伪造)。
|
|
4524
|
+
return { ok: null, state: "unknown", requirements: "" };
|
|
4525
|
+
}
|
|
4526
|
+
const parts = Array.isArray(error.incompatible)
|
|
4527
|
+
? error.incompatible.flatMap((item) => Object.entries(item?.requirements ?? {}).map(([key, value]) => `${key}: ${value}`))
|
|
4528
|
+
: [];
|
|
4529
|
+
return { ok: false, state: "incompatible", requirements: parts.slice(0, 4).join("; ") };
|
|
4530
|
+
}
|
|
4531
|
+
|
|
4532
|
+
/**
|
|
4533
|
+
* 只把宿主能证明的运行态投影成 `ok`:enabled 只是配置事实,不能冒充运行健康。
|
|
4534
|
+
*
|
|
4535
|
+
* - 任一行 failed → failed;宿主 error → failed;
|
|
4536
|
+
* - 没有运行期证据 / 行没有 entryId / entry 不在 runtime snapshot / fiberPhase=null → unknown;
|
|
4537
|
+
* - pending/loading/unloading → starting;
|
|
4538
|
+
* - 仅当**所有**行都 matched 且 active,才 ok。
|
|
4539
|
+
*/
|
|
4540
|
+
function pluginInventoryHealth(bundle, runtimeByEntryId, runtimeAvailable) {
|
|
4541
|
+
const error = bundle?.error && typeof bundle.error === "object" ? bundle.error : null;
|
|
4542
|
+
const enabled = bundle?.enabled === true;
|
|
4543
|
+
if (error) return { state: "failed", reasonCode: error.code ?? "operation-error" };
|
|
4544
|
+
if (!enabled) return { state: "disabled", reasonCode: "" };
|
|
4545
|
+
const rows = Array.isArray(bundle.rows) ? bundle.rows : [];
|
|
4546
|
+
if (rows.length === 0 || !runtimeAvailable) {
|
|
4547
|
+
return { state: "unknown", reasonCode: "runtime-unknown" };
|
|
4548
|
+
}
|
|
4549
|
+
const runtime = rows.map((row) => runtimeByEntryId.get(String(row?.entryId ?? "")));
|
|
4550
|
+
const missing = rows.some((row, index) => !row?.entryId || !runtime[index]);
|
|
4551
|
+
const phases = runtime.filter(Boolean).map((entry) => entry.fiberPhase);
|
|
4552
|
+
if (phases.includes("failed")) return { state: "failed", reasonCode: "runtime-start-failed" };
|
|
4553
|
+
if (missing) {
|
|
4554
|
+
// 部分行已 active、部分行没有运行证据:仍不能宣称整体健康。
|
|
4555
|
+
return { state: "unknown", reasonCode: "runtime-unknown" };
|
|
4556
|
+
}
|
|
4557
|
+
if (phases.some((phase) => phase === "pending" || phase === "loading" || phase === "unloading")) {
|
|
4558
|
+
return { state: "starting", reasonCode: "runtime-starting" };
|
|
4559
|
+
}
|
|
4560
|
+
if (phases.length > 0 && phases.every((phase) => phase === "active")) {
|
|
4561
|
+
return { state: "ok", reasonCode: "" };
|
|
4562
|
+
}
|
|
4563
|
+
return { state: "unknown", reasonCode: "runtime-unknown" };
|
|
4564
|
+
}
|
|
4565
|
+
|
|
4566
|
+
/** 把宿主 `listBundles()` 行投影成 App 可渲染的只读清单(不暴露内部诊断原文/路径)。 */
|
|
4567
|
+
function pluginInventoryFromBundles(bundles, runtimeByEntryId, runtimeAvailable = false) {
|
|
4568
|
+
const rows = Array.isArray(bundles) ? bundles : [];
|
|
4569
|
+
return rows
|
|
4570
|
+
.filter((bundle) => bundle && typeof bundle.name === "string" && (bundle.installed !== false || bundle.availability !== "missing"))
|
|
4571
|
+
.map((bundle) => {
|
|
4572
|
+
const compatibility = pluginInventoryCompatibility(bundle);
|
|
4573
|
+
// enabled 是配置启用事实;错误/健康另由 health/compatibility 表达。
|
|
4574
|
+
const enabled = bundle.enabled === true;
|
|
4575
|
+
const health = pluginInventoryHealth(bundle, runtimeByEntryId, runtimeAvailable);
|
|
4576
|
+
const version = typeof bundle.version === "string" ? bundle.version : "";
|
|
4577
|
+
return {
|
|
4578
|
+
id: bundle.name,
|
|
4579
|
+
name: bundle.name,
|
|
4580
|
+
title: bundle.meta?.title ?? null,
|
|
4581
|
+
description: typeof bundle.description === "string" ? bundle.description : null,
|
|
4582
|
+
packageName: bundle.name,
|
|
4583
|
+
version,
|
|
4584
|
+
source: pluginInventorySource(bundle),
|
|
4585
|
+
enabled,
|
|
4586
|
+
current: bundle.name === pluginPackageName,
|
|
4587
|
+
health,
|
|
4588
|
+
compatibility,
|
|
4589
|
+
// #146:只允许宿主已配置渠道的升级;不提供卸载/启停/重启。
|
|
4590
|
+
updateAvailable: null,
|
|
4591
|
+
updateKind: bundle.update === "registry" || bundle.update === "git" ? bundle.update : "",
|
|
4592
|
+
management: {
|
|
4593
|
+
readOnly: false,
|
|
4594
|
+
canUpdate: bundle.update === "registry",
|
|
4595
|
+
// #147:卸载/启停由宿主事务执行;readOnlyReason/不可移除时禁用并显示原因。
|
|
4596
|
+
canUninstall: bundle.removable === true && !bundle.readOnlyReason,
|
|
4597
|
+
canToggle: bundle.installed !== false && !bundle.readOnlyReason,
|
|
4598
|
+
canRestart: false,
|
|
4599
|
+
toggleReasonCode: bundle.readOnlyReason ?? (bundle.removable === false ? "not-removable" : ""),
|
|
4600
|
+
},
|
|
4601
|
+
};
|
|
4602
|
+
});
|
|
4603
|
+
}
|
|
4604
|
+
|
|
4605
|
+
/** 宿主清单里的“可安装”候选(仅配置渠道/内置 catalog 给出的 installTarget)。 */
|
|
4606
|
+
function pluginInstallableFromBundles(bundles) {
|
|
4607
|
+
return (Array.isArray(bundles) ? bundles : [])
|
|
4608
|
+
.filter((bundle) => bundle && typeof bundle.name === "string"
|
|
4609
|
+
&& bundle.installed !== true
|
|
4610
|
+
&& typeof bundle.installTarget?.spec === "string"
|
|
4611
|
+
&& bundle.installTarget.spec.trim() !== "")
|
|
4612
|
+
.map((bundle) => ({
|
|
4613
|
+
id: bundle.name,
|
|
4614
|
+
name: bundle.name,
|
|
4615
|
+
title: bundle.meta?.title ?? null,
|
|
4616
|
+
description: typeof bundle.description === "string" ? bundle.description : null,
|
|
4617
|
+
packageName: bundle.name,
|
|
4618
|
+
version: typeof bundle.installTarget.version === "string"
|
|
4619
|
+
? bundle.installTarget.version
|
|
4620
|
+
: typeof bundle.version === "string" ? bundle.version : "",
|
|
4621
|
+
source: { kind: "registry", label: "配置渠道" },
|
|
4622
|
+
installed: false,
|
|
4623
|
+
}));
|
|
4624
|
+
}
|
|
4625
|
+
|
|
4626
|
+
/** 独立 plugin entry(非 bundle-owned)→ 清单行;health 只按运行态证据。 */
|
|
4627
|
+
function pluginEntryHealth(entry) {
|
|
4628
|
+
if (entry?.enabled !== true) return { state: "disabled", reasonCode: "" };
|
|
4629
|
+
const phase = entry?.fiberPhase;
|
|
4630
|
+
if (phase === "failed") return { state: "failed", reasonCode: "runtime-start-failed" };
|
|
4631
|
+
if (phase === "active") return { state: "ok", reasonCode: "" };
|
|
4632
|
+
if (phase === "pending" || phase === "loading" || phase === "unloading") {
|
|
4633
|
+
return { state: "starting", reasonCode: "runtime-starting" };
|
|
4634
|
+
}
|
|
4635
|
+
return { state: "unknown", reasonCode: "runtime-unknown" };
|
|
4636
|
+
}
|
|
4637
|
+
|
|
4638
|
+
/**
|
|
4639
|
+
* 只补充未被 bundle 行覆盖的独立 entry。
|
|
4640
|
+
*
|
|
4641
|
+
* 去重必须按**精确 entryId**:同一 module 可被多个配置条目挂载(bundle-owned A +
|
|
4642
|
+
* independent B),按 moduleName 跳过会静默丢掉 B(即使 B failed)。没有可靠 ID 的
|
|
4643
|
+
* entry 无法安全去重:跳过并返回 `unresolved`,由调用方把清单标为 partial。
|
|
4644
|
+
*/
|
|
4645
|
+
function pluginEntriesNotInBundles(entries, coveredEntryIds) {
|
|
4646
|
+
const rows = [];
|
|
4647
|
+
let unresolved = 0;
|
|
4648
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
4649
|
+
const entryId = String(entry?.entryId ?? "").trim();
|
|
4650
|
+
const moduleName = String(entry?.moduleName ?? "");
|
|
4651
|
+
if (entryId === "") {
|
|
4652
|
+
unresolved += 1;
|
|
4653
|
+
continue;
|
|
4654
|
+
}
|
|
4655
|
+
if (coveredEntryIds.has(entryId)) continue;
|
|
4656
|
+
rows.push({
|
|
4657
|
+
id: entryId,
|
|
4658
|
+
name: moduleName || entryId,
|
|
4659
|
+
title: entry?.meta?.title ?? null,
|
|
4660
|
+
packageName: moduleName,
|
|
4661
|
+
version: "",
|
|
4662
|
+
source: { kind: "entry", label: "配置条目" },
|
|
4663
|
+
enabled: entry?.enabled === true,
|
|
4664
|
+
current: moduleName === pluginPackageName,
|
|
4665
|
+
health: pluginEntryHealth(entry),
|
|
4666
|
+
compatibility: { ok: null, state: "unknown", requirements: "" },
|
|
4667
|
+
updateAvailable: null,
|
|
4668
|
+
management: {
|
|
4669
|
+
readOnly: true,
|
|
4670
|
+
canUpdate: false,
|
|
4671
|
+
canUninstall: false,
|
|
4672
|
+
canToggle: false,
|
|
4673
|
+
canRestart: false,
|
|
4674
|
+
toggleReasonCode: "entry-managed-desktop",
|
|
4675
|
+
},
|
|
4676
|
+
independent: true,
|
|
4677
|
+
});
|
|
4678
|
+
}
|
|
4679
|
+
return { rows, unresolved };
|
|
4680
|
+
}
|
|
4681
|
+
|
|
4682
|
+
async function readHostPluginInventory() {
|
|
4683
|
+
let manager = null;
|
|
4684
|
+
try { manager = ctx.get?.("pluginManager") ?? null; } catch { manager = null; }
|
|
4685
|
+
let bundles = [];
|
|
4686
|
+
let bundlesAvailable = false;
|
|
4687
|
+
let bundlesMalformed = false;
|
|
4688
|
+
if (manager && typeof manager.listBundles === "function") {
|
|
4689
|
+
try {
|
|
4690
|
+
const listed = await manager.listBundles();
|
|
4691
|
+
if (Array.isArray(listed)) {
|
|
4692
|
+
bundles = listed;
|
|
4693
|
+
bundlesAvailable = true;
|
|
4694
|
+
} else {
|
|
4695
|
+
bundlesMalformed = true;
|
|
4696
|
+
}
|
|
4697
|
+
} catch {
|
|
4698
|
+
throw Object.assign(new Error("plugin-inventory-unavailable"), { httpStatus: 503, code: "plugin-inventory-unavailable" });
|
|
4699
|
+
}
|
|
4700
|
+
}
|
|
4701
|
+
const runtimeByEntryId = new Map();
|
|
4702
|
+
let runtimeEntries = [];
|
|
4703
|
+
let runtimeAvailable = false;
|
|
4704
|
+
let runtimeMalformed = false;
|
|
4705
|
+
let inventory = null;
|
|
4706
|
+
try { inventory = ctx.get?.("pluginInventory") ?? null; } catch { inventory = null; }
|
|
4707
|
+
if (inventory && typeof inventory.list === "function") {
|
|
4708
|
+
try {
|
|
4709
|
+
const snapshot = await inventory.list();
|
|
4710
|
+
if (snapshot && Array.isArray(snapshot.entries)) {
|
|
4711
|
+
runtimeEntries = snapshot.entries;
|
|
4712
|
+
runtimeAvailable = true;
|
|
4713
|
+
for (const entry of runtimeEntries) {
|
|
4714
|
+
runtimeByEntryId.set(String(entry?.entryId ?? ""), entry);
|
|
4715
|
+
}
|
|
4716
|
+
} else {
|
|
4717
|
+
runtimeMalformed = true;
|
|
4718
|
+
}
|
|
4719
|
+
} catch { /* 运行态不可得:supported=false,bundle 行 health=unknown,不冒充完整 */ }
|
|
4720
|
+
}
|
|
4721
|
+
const coveredEntryIds = new Set();
|
|
4722
|
+
const coveredModules = new Set();
|
|
4723
|
+
for (const bundle of bundles) {
|
|
4724
|
+
if (typeof bundle?.name === "string") coveredModules.add(bundle.name);
|
|
4725
|
+
for (const row of Array.isArray(bundle?.rows) ? bundle.rows : []) {
|
|
4726
|
+
if (row?.entryId) coveredEntryIds.add(String(row.entryId));
|
|
4727
|
+
if (row?.moduleName) coveredModules.add(String(row.moduleName));
|
|
4728
|
+
}
|
|
4729
|
+
}
|
|
4730
|
+
const extraEntries = pluginEntriesNotInBundles(runtimeEntries, coveredEntryIds);
|
|
4731
|
+
const complete = bundlesAvailable && runtimeAvailable && extraEntries.unresolved === 0;
|
|
4732
|
+
const plugins = [
|
|
4733
|
+
...pluginInventoryFromBundles(bundles, runtimeByEntryId, runtimeAvailable),
|
|
4734
|
+
...extraEntries.rows,
|
|
4735
|
+
];
|
|
4736
|
+
const reason = complete
|
|
4737
|
+
? ""
|
|
4738
|
+
: !bundlesAvailable
|
|
4739
|
+
? (bundlesMalformed ? "host-plugin-manager-malformed" : "host-plugin-manager-unavailable")
|
|
4740
|
+
: !runtimeAvailable
|
|
4741
|
+
? (runtimeMalformed ? "runtime-inventory-malformed" : "runtime-inventory-unavailable")
|
|
4742
|
+
: "entry-identity-missing";
|
|
4743
|
+
return {
|
|
4744
|
+
ok: true,
|
|
4745
|
+
supported: complete,
|
|
4746
|
+
complete,
|
|
4747
|
+
degraded: !complete,
|
|
4748
|
+
reason,
|
|
4749
|
+
host: { id: hostIdentity, pluginVersion: pluginVersion() },
|
|
4750
|
+
plugins,
|
|
4751
|
+
installable: bundlesAvailable ? pluginInstallableFromBundles(bundles) : [],
|
|
4752
|
+
};
|
|
4753
|
+
}
|
|
4754
|
+
|
|
4755
|
+
// ── #146:插件安装/升级(宿主事务;失败由宿主自动回滚) ──
|
|
4756
|
+
//
|
|
4757
|
+
// 事实与写操作都委托宿主 pluginManager:本插件只做参数校验、同插件互斥、
|
|
4758
|
+
// 进度投影与结果归一;不自行改 profile、不自行判定回滚成功。
|
|
4759
|
+
const pluginOperations = new Map();
|
|
4760
|
+
const PLUGIN_OPERATION_TTL_MS = 15 * 60 * 1000;
|
|
4761
|
+
const PLUGIN_INSTALL_STEPS = ["prepare", "install", "enable"];
|
|
4762
|
+
const PLUGIN_UPDATE_STEPS = ["check", "remove", "install", "restore"];
|
|
4763
|
+
const PLUGIN_UNINSTALL_STEPS = ["remove", "apply"];
|
|
4764
|
+
const PLUGIN_TOGGLE_STEPS = ["save", "apply"];
|
|
4765
|
+
|
|
4766
|
+
function prunePluginOperations() {
|
|
4767
|
+
const cutoff = Date.now() - PLUGIN_OPERATION_TTL_MS;
|
|
4768
|
+
for (const [opId, op] of pluginOperations) {
|
|
4769
|
+
if (op.finishedAt && op.finishedAt < cutoff) pluginOperations.delete(opId);
|
|
4770
|
+
}
|
|
4771
|
+
}
|
|
4772
|
+
|
|
4773
|
+
function publicPluginOperation(op) {
|
|
4774
|
+
return {
|
|
4775
|
+
opId: op.opId,
|
|
4776
|
+
action: op.action,
|
|
4777
|
+
name: op.name,
|
|
4778
|
+
targetVersion: op.targetVersion,
|
|
4779
|
+
status: op.status,
|
|
4780
|
+
phase: op.phase,
|
|
4781
|
+
steps: op.steps.map((step) => ({ key: step.key, state: step.state })),
|
|
4782
|
+
version: op.version,
|
|
4783
|
+
fromVersion: op.fromVersion,
|
|
4784
|
+
restartRequired: op.restartRequired,
|
|
4785
|
+
rolledBack: op.rolledBack,
|
|
4786
|
+
rollbackFailed: op.rollbackFailed,
|
|
4787
|
+
unchanged: op.unchanged,
|
|
4788
|
+
outcomeUnknown: op.outcomeUnknown,
|
|
4789
|
+
cancelled: op.cancelled,
|
|
4790
|
+
errorCode: op.errorCode,
|
|
4791
|
+
startedAt: op.startedAt,
|
|
4792
|
+
finishedAt: op.finishedAt,
|
|
4793
|
+
};
|
|
4794
|
+
}
|
|
4795
|
+
|
|
4796
|
+
function beginPluginOperation(action, name, targetVersion) {
|
|
4797
|
+
prunePluginOperations();
|
|
4798
|
+
for (const op of pluginOperations.values()) {
|
|
4799
|
+
if (op.status === "running" && op.name === name) {
|
|
4800
|
+
throw Object.assign(new Error("operation-in-progress"), { httpStatus: 409, code: "plugin-operation-in-progress" });
|
|
4801
|
+
}
|
|
4802
|
+
}
|
|
4803
|
+
const stepKeys = action === "install"
|
|
4804
|
+
? PLUGIN_INSTALL_STEPS
|
|
4805
|
+
: action === "update"
|
|
4806
|
+
? PLUGIN_UPDATE_STEPS
|
|
4807
|
+
: action === "uninstall"
|
|
4808
|
+
? PLUGIN_UNINSTALL_STEPS
|
|
4809
|
+
: PLUGIN_TOGGLE_STEPS;
|
|
4810
|
+
const steps = stepKeys.map((key) => ({ key, state: "pending" }));
|
|
4811
|
+
const op = {
|
|
4812
|
+
opId: newOperationId(),
|
|
4813
|
+
action,
|
|
4814
|
+
name,
|
|
4815
|
+
targetVersion: typeof targetVersion === "string" ? targetVersion : "",
|
|
4816
|
+
status: "running",
|
|
4817
|
+
phase: "",
|
|
4818
|
+
steps,
|
|
4819
|
+
version: "",
|
|
4820
|
+
fromVersion: "",
|
|
4821
|
+
restartRequired: false,
|
|
4822
|
+
rolledBack: false,
|
|
4823
|
+
rollbackFailed: false,
|
|
4824
|
+
unchanged: false,
|
|
4825
|
+
outcomeUnknown: false,
|
|
4826
|
+
cancelled: false,
|
|
4827
|
+
errorCode: "",
|
|
4828
|
+
startedAt: Date.now(),
|
|
4829
|
+
finishedAt: null,
|
|
4830
|
+
};
|
|
4831
|
+
pluginOperations.set(op.opId, op);
|
|
4832
|
+
return op;
|
|
4833
|
+
}
|
|
4834
|
+
|
|
4835
|
+
function markPluginOperationStep(op, key) {
|
|
4836
|
+
if (!key || !op || op.status !== "running") return;
|
|
4837
|
+
const index = op.steps.findIndex((step) => step.key === key);
|
|
4838
|
+
if (index < 0) return;
|
|
4839
|
+
op.phase = key;
|
|
4840
|
+
op.steps.forEach((step, i) => {
|
|
4841
|
+
if (i < index) step.state = "done";
|
|
4842
|
+
else if (i === index) step.state = "running";
|
|
4843
|
+
else if (step.state === "running") step.state = "pending";
|
|
4844
|
+
});
|
|
4845
|
+
}
|
|
4846
|
+
|
|
4847
|
+
function notePluginOperationProgress(payload) {
|
|
4848
|
+
const opId = String(payload?.requestId ?? "");
|
|
4849
|
+
if (!opId) return;
|
|
4850
|
+
const op = pluginOperations.get(opId);
|
|
4851
|
+
if (!op || op.status !== "running") return;
|
|
4852
|
+
if (op.action === "install") {
|
|
4853
|
+
if (payload.phase === "installing") markPluginOperationStep(op, "install");
|
|
4854
|
+
else if (payload.phase === "applying") markPluginOperationStep(op, "enable");
|
|
4855
|
+
return;
|
|
4856
|
+
}
|
|
4857
|
+
const step = payload?.step;
|
|
4858
|
+
if (step === "checking") markPluginOperationStep(op, "check");
|
|
4859
|
+
else if (step === "removing") markPluginOperationStep(op, "remove");
|
|
4860
|
+
else if (step === "installing") markPluginOperationStep(op, "install");
|
|
4861
|
+
else if (step === "restoring") markPluginOperationStep(op, "restore");
|
|
4862
|
+
}
|
|
4863
|
+
|
|
4864
|
+
function finishPluginOperation(op, action, result, error) {
|
|
4865
|
+
if (!op || op.status !== "running") return;
|
|
4866
|
+
op.finishedAt = Date.now();
|
|
4867
|
+
for (const step of op.steps) {
|
|
4868
|
+
if (step.state === "running") step.state = "done";
|
|
4869
|
+
else if (step.state === "pending") step.state = "skipped";
|
|
4870
|
+
}
|
|
4871
|
+
if (error) {
|
|
4872
|
+
op.status = "failed";
|
|
4873
|
+
op.errorCode = "host-exception";
|
|
4874
|
+
op.outcomeUnknown = true; // 异常逃逸:不能断言宿主是否已回滚
|
|
4875
|
+
return;
|
|
4876
|
+
}
|
|
4877
|
+
const change = action === "update" ? result?.result : result;
|
|
4878
|
+
const application = change?.application;
|
|
4879
|
+
const errorCode = change?.error?.code;
|
|
4880
|
+
if (action === "uninstall" || action === "toggle") {
|
|
4881
|
+
op.version = typeof change?.version === "string" ? change.version : "";
|
|
4882
|
+
if (application === "failed" || !application) {
|
|
4883
|
+
op.status = "failed";
|
|
4884
|
+
op.errorCode = errorCode || "operation-failed";
|
|
4885
|
+
// 卸载失败无法从结果断言是否留下半卸载;启停失败按宿主事务保持原状态。
|
|
4886
|
+
if (action === "uninstall") op.outcomeUnknown = true;
|
|
4887
|
+
else op.unchanged = true;
|
|
4888
|
+
} else if (application === "cancelled") {
|
|
4889
|
+
op.status = "cancelled";
|
|
4890
|
+
op.cancelled = true;
|
|
4891
|
+
} else {
|
|
4892
|
+
op.status = "succeeded";
|
|
4893
|
+
op.restartRequired = application === "restart-required";
|
|
4894
|
+
}
|
|
4895
|
+
return;
|
|
4896
|
+
}
|
|
4897
|
+
if (action === "install") {
|
|
4898
|
+
op.version = typeof change?.version === "string" ? change.version : "";
|
|
4899
|
+
if (application === "failed" || !application) {
|
|
4900
|
+
op.status = "failed";
|
|
4901
|
+
op.errorCode = errorCode || "operation-failed";
|
|
4902
|
+
op.rolledBack = Boolean(application === "failed"); // installBundle 文档:失败恢复 profile
|
|
4903
|
+
} else if (application === "cancelled") {
|
|
4904
|
+
op.status = "cancelled";
|
|
4905
|
+
op.cancelled = true;
|
|
4906
|
+
op.rolledBack = true;
|
|
4907
|
+
} else {
|
|
4908
|
+
op.status = "succeeded";
|
|
4909
|
+
op.restartRequired = application === "restart-required";
|
|
4910
|
+
}
|
|
4911
|
+
return;
|
|
4912
|
+
}
|
|
4913
|
+
op.fromVersion = typeof result?.from === "string" ? result.from : "";
|
|
4914
|
+
op.version = typeof result?.to === "string" ? result.to : (typeof change?.version === "string" ? change.version : "");
|
|
4915
|
+
if (result?.restore) {
|
|
4916
|
+
op.rolledBack = result.restore.application !== "failed";
|
|
4917
|
+
op.rollbackFailed = result.restore.application === "failed";
|
|
4918
|
+
}
|
|
4919
|
+
if (application === "failed" || !application) {
|
|
4920
|
+
op.status = "failed";
|
|
4921
|
+
op.errorCode = errorCode || "operation-failed";
|
|
4922
|
+
if (!result?.restore) op.unchanged = result?.step !== "install";
|
|
4923
|
+
} else if (application === "cancelled") {
|
|
4924
|
+
op.status = "cancelled";
|
|
4925
|
+
op.cancelled = true;
|
|
4926
|
+
if (!result?.restore) op.unchanged = result?.step !== "install";
|
|
4927
|
+
} else {
|
|
4928
|
+
op.status = "succeeded";
|
|
4929
|
+
op.restartRequired = application === "restart-required";
|
|
4930
|
+
}
|
|
4931
|
+
}
|
|
4932
|
+
|
|
4933
|
+
function pluginManagerService() {
|
|
4934
|
+
let manager = null;
|
|
4935
|
+
try { manager = ctx.get?.("pluginManager") ?? null; } catch { manager = null; }
|
|
4936
|
+
return manager && typeof manager === "object" ? manager : null;
|
|
4937
|
+
}
|
|
4938
|
+
|
|
4939
|
+
function hostRestartSupported() {
|
|
4940
|
+
try { return restartFormOf() !== "unsupported"; } catch { return false; }
|
|
4941
|
+
}
|
|
4942
|
+
|
|
4943
|
+
function restartPlanForHost() {
|
|
4944
|
+
const form = restartFormOf();
|
|
4945
|
+
return restartPlan({
|
|
4946
|
+
form,
|
|
4947
|
+
pid: process.pid,
|
|
4948
|
+
profile: process.env.DSH_PROFILE || "web",
|
|
4949
|
+
dshCommand: process.env.DSH_BIN || "dsh",
|
|
4950
|
+
respawnCommand,
|
|
4951
|
+
});
|
|
4952
|
+
}
|
|
4953
|
+
|
|
4954
|
+
async function startPluginInstall(name) {
|
|
4955
|
+
const manager = pluginManagerService();
|
|
4956
|
+
if (!manager || typeof manager.installBundle !== "function") {
|
|
4957
|
+
throw Object.assign(new Error("plugin-manager-unavailable"), { httpStatus: 409, code: "plugin-manager-unavailable" });
|
|
4958
|
+
}
|
|
4959
|
+
const bundles = await manager.listBundles();
|
|
4960
|
+
const candidate = pluginInstallableFromBundles(bundles).find((row) => row.name === name);
|
|
4961
|
+
if (!candidate) {
|
|
4962
|
+
throw Object.assign(new Error("not-installable"), { httpStatus: 400, code: "not-installable" });
|
|
4963
|
+
}
|
|
4964
|
+
const source = (Array.isArray(bundles) ? bundles : []).find((bundle) => bundle?.name === name);
|
|
4965
|
+
const spec = source?.installTarget?.spec;
|
|
4966
|
+
if (typeof spec !== "string" || spec.trim() === "") {
|
|
4967
|
+
throw Object.assign(new Error("not-installable"), { httpStatus: 400, code: "not-installable" });
|
|
4968
|
+
}
|
|
4969
|
+
const op = beginPluginOperation("install", name, candidate.version);
|
|
4970
|
+
(async () => {
|
|
4971
|
+
markPluginOperationStep(op, "prepare");
|
|
4972
|
+
try {
|
|
4973
|
+
const expectedVersion = typeof source?.installTarget?.version === "string" ? source.installTarget.version : "";
|
|
4974
|
+
const result = await manager.installBundle(spec, {
|
|
4975
|
+
requestId: op.opId,
|
|
4976
|
+
saveExact: true,
|
|
4977
|
+
...(expectedVersion ? { expected: { name, version: expectedVersion } } : {}),
|
|
4978
|
+
});
|
|
4979
|
+
finishPluginOperation(op, "install", result, null);
|
|
4980
|
+
} catch (error) {
|
|
4981
|
+
finishPluginOperation(op, "install", null, error);
|
|
4982
|
+
}
|
|
4983
|
+
})();
|
|
4984
|
+
return op;
|
|
4985
|
+
}
|
|
4986
|
+
|
|
4987
|
+
async function startPluginUpdate(name, version) {
|
|
4988
|
+
const manager = pluginManagerService();
|
|
4989
|
+
if (!manager || typeof manager.updateBundle !== "function") {
|
|
4990
|
+
throw Object.assign(new Error("plugin-manager-unavailable"), { httpStatus: 409, code: "plugin-manager-unavailable" });
|
|
4991
|
+
}
|
|
4992
|
+
const bundles = await manager.listBundles();
|
|
4993
|
+
const installed = (Array.isArray(bundles) ? bundles : []).find((bundle) => bundle?.name === name && bundle.installed !== false);
|
|
4994
|
+
if (!installed) {
|
|
4995
|
+
throw Object.assign(new Error("not-installed"), { httpStatus: 404, code: "plugin-not-installed" });
|
|
4996
|
+
}
|
|
4997
|
+
if (installed.update === "git") {
|
|
4998
|
+
throw Object.assign(new Error("git-update-desktop-required"), { httpStatus: 409, code: "git-update-desktop-required" });
|
|
4999
|
+
}
|
|
5000
|
+
if (installed.update !== "registry") {
|
|
5001
|
+
throw Object.assign(new Error("not-updatable"), { httpStatus: 409, code: "plugin-not-updatable" });
|
|
5002
|
+
}
|
|
5003
|
+
const op = beginPluginOperation("update", name, version);
|
|
5004
|
+
(async () => {
|
|
5005
|
+
markPluginOperationStep(op, "check");
|
|
5006
|
+
try {
|
|
5007
|
+
const result = await manager.updateBundle(name, version, { requestId: op.opId });
|
|
5008
|
+
finishPluginOperation(op, "update", result, null);
|
|
5009
|
+
} catch (error) {
|
|
5010
|
+
finishPluginOperation(op, "update", null, error);
|
|
5011
|
+
}
|
|
5012
|
+
})();
|
|
5013
|
+
return op;
|
|
5014
|
+
}
|
|
5015
|
+
|
|
5016
|
+
async function startPluginUninstall(name) {
|
|
5017
|
+
const manager = pluginManagerService();
|
|
5018
|
+
if (!manager || typeof manager.removeBundle !== "function") {
|
|
5019
|
+
throw Object.assign(new Error("plugin-manager-unavailable"), { httpStatus: 409, code: "plugin-manager-unavailable" });
|
|
5020
|
+
}
|
|
5021
|
+
const bundles = await manager.listBundles();
|
|
5022
|
+
const installed = (Array.isArray(bundles) ? bundles : []).find((bundle) => bundle?.name === name && bundle.installed !== false);
|
|
5023
|
+
if (!installed) throw Object.assign(new Error("not-installed"), { httpStatus: 404, code: "plugin-not-installed" });
|
|
5024
|
+
if (installed.readOnlyReason || installed.removable !== true) {
|
|
5025
|
+
throw Object.assign(new Error("not-removable"), { httpStatus: 409, code: installed.readOnlyReason ?? "plugin-not-removable" });
|
|
5026
|
+
}
|
|
5027
|
+
const op = beginPluginOperation("uninstall", name);
|
|
5028
|
+
(async () => {
|
|
5029
|
+
markPluginOperationStep(op, "remove");
|
|
5030
|
+
try {
|
|
5031
|
+
const result = await manager.removeBundle(name);
|
|
5032
|
+
finishPluginOperation(op, "uninstall", result, null);
|
|
5033
|
+
} catch (error) {
|
|
5034
|
+
finishPluginOperation(op, "uninstall", null, error);
|
|
5035
|
+
}
|
|
5036
|
+
})();
|
|
5037
|
+
return op;
|
|
5038
|
+
}
|
|
5039
|
+
|
|
5040
|
+
async function startPluginToggle(name, enabled) {
|
|
5041
|
+
const manager = pluginManagerService();
|
|
5042
|
+
if (!manager || typeof manager.setBundleEnabled !== "function") {
|
|
5043
|
+
throw Object.assign(new Error("plugin-manager-unavailable"), { httpStatus: 409, code: "plugin-manager-unavailable" });
|
|
5044
|
+
}
|
|
5045
|
+
const bundles = await manager.listBundles();
|
|
5046
|
+
const installed = (Array.isArray(bundles) ? bundles : []).find((bundle) => bundle?.name === name && bundle.installed !== false);
|
|
5047
|
+
if (!installed) throw Object.assign(new Error("not-installed"), { httpStatus: 404, code: "plugin-not-installed" });
|
|
5048
|
+
if (installed.readOnlyReason) {
|
|
5049
|
+
throw Object.assign(new Error("read-only"), { httpStatus: 409, code: installed.readOnlyReason });
|
|
5050
|
+
}
|
|
5051
|
+
const op = beginPluginOperation("toggle", name, enabled ? "on" : "off");
|
|
5052
|
+
(async () => {
|
|
5053
|
+
markPluginOperationStep(op, "save");
|
|
5054
|
+
try {
|
|
5055
|
+
const result = await manager.setBundleEnabled(name, enabled === true);
|
|
5056
|
+
finishPluginOperation(op, "toggle", result, null);
|
|
5057
|
+
} catch (error) {
|
|
5058
|
+
finishPluginOperation(op, "toggle", null, error);
|
|
5059
|
+
}
|
|
5060
|
+
})();
|
|
5061
|
+
return op;
|
|
5062
|
+
}
|
|
5063
|
+
|
|
4384
5064
|
/** 客户端视图参数:公开基址只取 actual endpoint 视图(W1;Host/trustedHosts 不能证明监听)。 */
|
|
4385
5065
|
function clientViewFor(_req) {
|
|
4386
5066
|
return {
|
|
@@ -7191,7 +7871,7 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
7191
7871
|
return;
|
|
7192
7872
|
}
|
|
7193
7873
|
if (!safeWrite(res, ": connected\n\n")) return;
|
|
7194
|
-
if (!safeWrite(res, `data: ${JSON.stringify({ type: "hello", serverTime: now, capabilities: { eventTimeline: EVENT_TIMELINE_CAPABILITIES, turnOutline: turnOutlineCapabilityOf(ctx), fileRange: FILE_RANGE_CAPABILITIES, turnTail: turnTailCapabilityOf(ctx), toolCards: toolCardsCapabilityOf(), hold: { version: 1, onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? DEFAULT_PENDING_TIMEOUT_MS) || 0), offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0) } } })}\n\n`)) return;
|
|
7874
|
+
if (!safeWrite(res, `data: ${JSON.stringify({ type: "hello", serverTime: now, capabilities: { eventTimeline: EVENT_TIMELINE_CAPABILITIES, turnOutline: turnOutlineCapabilityOf(ctx), fileRange: FILE_RANGE_CAPABILITIES, files: FILES_CAPABILITIES, turnTail: turnTailCapabilityOf(ctx), toolCards: toolCardsCapabilityOf(), hold: { version: 1, onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? DEFAULT_PENDING_TIMEOUT_MS) || 0), offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0) } } })}\n\n`)) return;
|
|
7195
7875
|
connections.add(res);
|
|
7196
7876
|
ctx.logger.info(`mobile-remote: SSE open id=${meta.id} age=0s idle=0s remote=${meta.clientIp || "-"} app=${meta.appVersion || "-"} reason=open`);
|
|
7197
7877
|
// 补发断线期间挂起的问询/审批(与 PC 端 GUI 连接时的 pending 回放一致;超 TTL 的僵尸帧先清掉)
|
|
@@ -7449,6 +8129,8 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
7449
8129
|
return undefined;
|
|
7450
8130
|
}
|
|
7451
8131
|
};
|
|
8132
|
+
// issue #142:团队开关在途集合(GET 报告 pending,POST 防并发重复提交)。
|
|
8133
|
+
const TEAM_PENDING = new Set();
|
|
7452
8134
|
const subagentsGeneration = () => {
|
|
7453
8135
|
const service = subagentsService();
|
|
7454
8136
|
return {
|
|
@@ -8059,6 +8741,8 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
8059
8741
|
toolCards: toolCardsCapabilityOf(),
|
|
8060
8742
|
// v3.2.3:普通文件下载支持 Range/HEAD/ETag(大文件续传 + 前缀预览)。
|
|
8061
8743
|
fileRange: FILE_RANGE_CAPABILITIES,
|
|
8744
|
+
// GitLab #16:文件下载支持 sessionId + cwd 相对路径(旧 App 忽略)。
|
|
8745
|
+
files: FILES_CAPABILITIES,
|
|
8062
8746
|
// v3.2.4(issue #55):手机端待办等待上限(仅供显示剩余时间,结算仍以服务端为准)。
|
|
8063
8747
|
hold: {
|
|
8064
8748
|
version: 1,
|
|
@@ -8153,6 +8837,179 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
8153
8837
|
}
|
|
8154
8838
|
|
|
8155
8839
|
|
|
8840
|
+
// ── #146:配置渠道安装/升级(宿主事务;失败由宿主自动回滚) ──
|
|
8841
|
+
if (rest === "/plugin-inventory/versions") {
|
|
8842
|
+
if (requireGet(method, res)) return;
|
|
8843
|
+
const name = (url.searchParams.get("name") ?? "").trim();
|
|
8844
|
+
if (name === "" || name.length > 200) return error(res, 400, "invalid-plugin-name");
|
|
8845
|
+
const manager = pluginManagerService();
|
|
8846
|
+
if (!manager || typeof manager.listVersions !== "function") return error(res, 409, "plugin-manager-unavailable");
|
|
8847
|
+
let installed;
|
|
8848
|
+
try {
|
|
8849
|
+
const bundles = await manager.listBundles();
|
|
8850
|
+
installed = (Array.isArray(bundles) ? bundles : []).find((bundle) => bundle?.name === name && bundle.installed !== false);
|
|
8851
|
+
} catch {
|
|
8852
|
+
return error(res, 503, "plugin-inventory-unavailable");
|
|
8853
|
+
}
|
|
8854
|
+
if (!installed) return error(res, 404, "plugin-not-installed");
|
|
8855
|
+
if (installed.update === "git") return error(res, 409, "git-update-desktop-required");
|
|
8856
|
+
if (installed.update !== "registry") return error(res, 409, "plugin-not-updatable");
|
|
8857
|
+
try {
|
|
8858
|
+
const list = await manager.listVersions(name);
|
|
8859
|
+
if (list?.status === "refused") {
|
|
8860
|
+
return sendJson(res, 200, { ok: true, supported: true, status: "refused", problem: list.problem, reason: list.reason });
|
|
8861
|
+
}
|
|
8862
|
+
return sendJson(res, 200, {
|
|
8863
|
+
ok: true,
|
|
8864
|
+
supported: true,
|
|
8865
|
+
status: "listed",
|
|
8866
|
+
name,
|
|
8867
|
+
installedVersion: typeof list?.installed === "string" ? list.installed : "",
|
|
8868
|
+
versions: (Array.isArray(list?.versions) ? list.versions : []).map((version) => ({
|
|
8869
|
+
version: String(version?.version ?? ""),
|
|
8870
|
+
prerelease: version?.prerelease === true,
|
|
8871
|
+
deprecated: typeof version?.deprecated === "string" ? version.deprecated : "",
|
|
8872
|
+
bundle: version?.bundle === true,
|
|
8873
|
+
incompatible: version?.incompatible
|
|
8874
|
+
? {
|
|
8875
|
+
requirements: Object.entries(version.incompatible.requirements ?? {})
|
|
8876
|
+
.map(([key, value]) => `${key}: ${value}`).slice(0, 4).join("; "),
|
|
8877
|
+
}
|
|
8878
|
+
: null,
|
|
8879
|
+
})),
|
|
8880
|
+
omitted: Number.isFinite(list?.omitted) ? list.omitted : 0,
|
|
8881
|
+
});
|
|
8882
|
+
} catch {
|
|
8883
|
+
return error(res, 503, "plugin-versions-unavailable");
|
|
8884
|
+
}
|
|
8885
|
+
}
|
|
8886
|
+
if (rest === "/plugin-inventory/install") {
|
|
8887
|
+
if (method !== "POST") return error(res, 405, "method-not-allowed");
|
|
8888
|
+
let body;
|
|
8889
|
+
try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
|
|
8890
|
+
catch { return error(res, 400, "bad-request", "body must be JSON"); }
|
|
8891
|
+
const name = typeof body?.name === "string" ? body.name.trim() : "";
|
|
8892
|
+
if (name === "" || name.length > 200) return error(res, 400, "invalid-plugin-name");
|
|
8893
|
+
try {
|
|
8894
|
+
const op = await startPluginInstall(name);
|
|
8895
|
+
return sendJson(res, 200, { ok: true, operation: publicPluginOperation(op) });
|
|
8896
|
+
} catch (e) {
|
|
8897
|
+
return error(res, Number(e?.httpStatus) || 503, e?.code || "plugin-install-failed");
|
|
8898
|
+
}
|
|
8899
|
+
}
|
|
8900
|
+
if (rest === "/plugin-inventory/update") {
|
|
8901
|
+
if (method !== "POST") return error(res, 405, "method-not-allowed");
|
|
8902
|
+
let body;
|
|
8903
|
+
try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
|
|
8904
|
+
catch { return error(res, 400, "bad-request", "body must be JSON"); }
|
|
8905
|
+
const name = typeof body?.name === "string" ? body.name.trim() : "";
|
|
8906
|
+
const version = typeof body?.version === "string" ? body.version.trim() : "";
|
|
8907
|
+
if (name === "" || name.length > 200) return error(res, 400, "invalid-plugin-name");
|
|
8908
|
+
if (version === "" || version.length > 100 || !/^[0-9A-Za-z][0-9A-Za-z.+_-]*$/.test(version)) return error(res, 400, "invalid-plugin-version");
|
|
8909
|
+
try {
|
|
8910
|
+
const op = await startPluginUpdate(name, version);
|
|
8911
|
+
return sendJson(res, 200, { ok: true, operation: publicPluginOperation(op) });
|
|
8912
|
+
} catch (e) {
|
|
8913
|
+
return error(res, Number(e?.httpStatus) || 503, e?.code || "plugin-update-failed");
|
|
8914
|
+
}
|
|
8915
|
+
}
|
|
8916
|
+
if (rest === "/plugin-inventory/uninstall") {
|
|
8917
|
+
if (method !== "POST") return error(res, 405, "method-not-allowed");
|
|
8918
|
+
let body;
|
|
8919
|
+
try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
|
|
8920
|
+
catch { return error(res, 400, "bad-request", "body must be JSON"); }
|
|
8921
|
+
const name = typeof body?.name === "string" ? body.name.trim() : "";
|
|
8922
|
+
if (name === "" || name.length > 200) return error(res, 400, "invalid-plugin-name");
|
|
8923
|
+
try {
|
|
8924
|
+
const op = await startPluginUninstall(name);
|
|
8925
|
+
return sendJson(res, 200, { ok: true, operation: publicPluginOperation(op) });
|
|
8926
|
+
} catch (e) {
|
|
8927
|
+
return error(res, Number(e?.httpStatus) || 503, e?.code || "plugin-uninstall-failed");
|
|
8928
|
+
}
|
|
8929
|
+
}
|
|
8930
|
+
if (rest === "/plugin-inventory/toggle") {
|
|
8931
|
+
if (method !== "POST") return error(res, 405, "method-not-allowed");
|
|
8932
|
+
let body;
|
|
8933
|
+
try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
|
|
8934
|
+
catch { return error(res, 400, "bad-request", "body must be JSON"); }
|
|
8935
|
+
const name = typeof body?.name === "string" ? body.name.trim() : "";
|
|
8936
|
+
if (name === "" || name.length > 200) return error(res, 400, "invalid-plugin-name");
|
|
8937
|
+
if (typeof body?.enabled !== "boolean") return error(res, 400, "invalid-plugin-enabled");
|
|
8938
|
+
try {
|
|
8939
|
+
const op = await startPluginToggle(name, body.enabled);
|
|
8940
|
+
return sendJson(res, 200, { ok: true, operation: publicPluginOperation(op) });
|
|
8941
|
+
} catch (e) {
|
|
8942
|
+
return error(res, Number(e?.httpStatus) || 503, e?.code || "plugin-toggle-failed");
|
|
8943
|
+
}
|
|
8944
|
+
}
|
|
8945
|
+
if (rest === "/plugin-inventory/restart") {
|
|
8946
|
+
if (method !== "POST") return error(res, 405, "method-not-allowed");
|
|
8947
|
+
let body;
|
|
8948
|
+
try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
|
|
8949
|
+
catch { return error(res, 400, "bad-request", "body must be JSON"); }
|
|
8950
|
+
if (body?.confirm !== true) return error(res, 400, "restart-confirmation-required");
|
|
8951
|
+
if (!hostRestartSupported()) return error(res, 409, "restart-unsupported");
|
|
8952
|
+
const plan = restartPlanForHost();
|
|
8953
|
+
if (!plan || plan.mode === "unsupported") return error(res, 409, "restart-unsupported");
|
|
8954
|
+
try {
|
|
8955
|
+
const restart = runtime.pluginManagement?.restart;
|
|
8956
|
+
const result = typeof restart === "function"
|
|
8957
|
+
? restart({ plan, pid: process.pid })
|
|
8958
|
+
: runRestart({ plan, pid: process.pid, delayMs: 1500 });
|
|
8959
|
+
if (!result?.ok) return error(res, 409, result?.error || "restart-spawn-failed");
|
|
8960
|
+
return sendJson(res, 200, { ok: true, accepted: true, mode: plan.mode });
|
|
8961
|
+
} catch {
|
|
8962
|
+
return error(res, 503, "restart-spawn-failed");
|
|
8963
|
+
}
|
|
8964
|
+
}
|
|
8965
|
+
if (rest === "/plugin-inventory/op") {
|
|
8966
|
+
if (requireGet(method, res)) return;
|
|
8967
|
+
prunePluginOperations();
|
|
8968
|
+
const opId = (url.searchParams.get("opId") ?? "").trim();
|
|
8969
|
+
if (opId === "" || opId.length > 200) return error(res, 400, "invalid-operation-id");
|
|
8970
|
+
const op = pluginOperations.get(opId);
|
|
8971
|
+
if (!op) return error(res, 404, "plugin-operation-not-found");
|
|
8972
|
+
return sendJson(res, 200, { ok: true, operation: publicPluginOperation(op) });
|
|
8973
|
+
}
|
|
8974
|
+
if (rest === "/plugin-inventory/op/cancel") {
|
|
8975
|
+
if (method !== "POST") return error(res, 405, "method-not-allowed");
|
|
8976
|
+
let body;
|
|
8977
|
+
try { const text = await readBody(req, 16 * 1024); body = text ? JSON.parse(text) : {}; }
|
|
8978
|
+
catch { return error(res, 400, "bad-request", "body must be JSON"); }
|
|
8979
|
+
const opId = typeof body?.opId === "string" ? body.opId.trim() : "";
|
|
8980
|
+
if (opId === "" || opId.length > 200) return error(res, 400, "invalid-operation-id");
|
|
8981
|
+
const op = pluginOperations.get(opId);
|
|
8982
|
+
if (!op) return error(res, 404, "plugin-operation-not-found");
|
|
8983
|
+
if (op.status !== "running") return sendJson(res, 200, { ok: true, cancel: "not-running", operation: publicPluginOperation(op) });
|
|
8984
|
+
if (op.action !== "install" && op.action !== "update") {
|
|
8985
|
+
return error(res, 409, "plugin-operation-not-cancellable");
|
|
8986
|
+
}
|
|
8987
|
+
const manager = pluginManagerService();
|
|
8988
|
+
if (!manager || typeof manager.cancelInstall !== "function") return error(res, 409, "plugin-manager-unavailable");
|
|
8989
|
+
try {
|
|
8990
|
+
const cancellation = await manager.cancelInstall(opId);
|
|
8991
|
+
return sendJson(res, 200, { ok: true, cancel: cancellation?.status ?? "unknown", operation: publicPluginOperation(op) });
|
|
8992
|
+
} catch {
|
|
8993
|
+
return error(res, 503, "plugin-operation-cancel-failed");
|
|
8994
|
+
}
|
|
8995
|
+
}
|
|
8996
|
+
|
|
8997
|
+
// issue #145:当前宿主插件清单/健康只读投影(无安装/升级/卸载/启停/重启入口)。
|
|
8998
|
+
if (rest === "/plugin-inventory") {
|
|
8999
|
+
if (method !== "GET" && method !== "HEAD") return error(res, 405, "method-not-allowed");
|
|
9000
|
+
try {
|
|
9001
|
+
const payload = await readHostPluginInventory();
|
|
9002
|
+
if (method === "HEAD") {
|
|
9003
|
+
res.writeHead(200, { "cache-control": "no-store" });
|
|
9004
|
+
res.end();
|
|
9005
|
+
return;
|
|
9006
|
+
}
|
|
9007
|
+
return sendJson(res, 200, payload);
|
|
9008
|
+
} catch (e) {
|
|
9009
|
+
return error(res, Number(e?.httpStatus) || 503, e?.code || "plugin-inventory-unavailable");
|
|
9010
|
+
}
|
|
9011
|
+
}
|
|
9012
|
+
|
|
8156
9013
|
// 只读 NPM 检查:旧 App GET 缓存命中立即返回;新 App POST 异步检查 + checkId 轮询。
|
|
8157
9014
|
// 不下载产物、不改 profile、不重启,也不返回半结果。
|
|
8158
9015
|
if (rest === "/plugin-update/check") {
|
|
@@ -8967,6 +9824,9 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
8967
9824
|
lastActivity: activityMap.get(r.header.id) ?? null,
|
|
8968
9825
|
lastMessageAt: messageTimeMap.get(r.header.id) ?? null,
|
|
8969
9826
|
...(header?.origin === "subagent" ? { origin: "subagent" } : {}),
|
|
9827
|
+
parentSessionId: typeof header?.parentSession === "string" && header.parentSession !== ""
|
|
9828
|
+
? header.parentSession
|
|
9829
|
+
: null,
|
|
8970
9830
|
...(typeof header?.parentSession === "string" && header.parentSession !== ""
|
|
8971
9831
|
? { parentSession: header.parentSession }
|
|
8972
9832
|
: {}),
|
|
@@ -8987,6 +9847,9 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
8987
9847
|
lastActivity: activityMap.get(session?.id) ?? null,
|
|
8988
9848
|
lastMessageAt: messageTimeMap.get(session?.id) ?? null,
|
|
8989
9849
|
...(h?.origin === "subagent" ? { origin: "subagent" } : {}),
|
|
9850
|
+
parentSessionId: typeof h?.parentSession === "string" && h.parentSession !== ""
|
|
9851
|
+
? h.parentSession
|
|
9852
|
+
: null,
|
|
8990
9853
|
...(typeof h?.parentSession === "string" && h.parentSession !== ""
|
|
8991
9854
|
? { parentSession: h.parentSession }
|
|
8992
9855
|
: {}),
|
|
@@ -10698,10 +11561,15 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
10698
11561
|
* 文件不可读时抛错,由调用方映射成各自的稳定错误码。
|
|
10699
11562
|
* @returns {true} 已写出响应(调用方仍应 return)。
|
|
10700
11563
|
*/
|
|
10701
|
-
const
|
|
10702
|
-
|
|
11564
|
+
const closeOpenedFile = (opened) => {
|
|
11565
|
+
if (!opened || opened.fd === null || opened.fd === undefined) return;
|
|
11566
|
+
try { closeSync(opened.fd); } catch {}
|
|
11567
|
+
opened.fd = null;
|
|
11568
|
+
};
|
|
11569
|
+
const serveFileBytes = (req, res, target, { method, opened = null }) => {
|
|
11570
|
+
const st = opened ? opened.stats : statSync(target);
|
|
10703
11571
|
if (!st.isFile()) throw Object.assign(new Error("not-a-file"), { code: "not-a-file" });
|
|
10704
|
-
const name = basename(target);
|
|
11572
|
+
const name = basename(opened ? opened.actualPath : target);
|
|
10705
11573
|
// 保留时间精度并纳入 ctime,避免同大小改写且恢复 mtime 后沿用旧断点。
|
|
10706
11574
|
const etag = `"${st.size.toString(16)}-${st.mtimeMs.toString(16)}-${st.ctimeMs.toString(16)}"`;
|
|
10707
11575
|
const lastModified = new Date(st.mtimeMs).toUTCString();
|
|
@@ -10709,6 +11577,7 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
10709
11577
|
if (ifNoneMatch(req, etag)) {
|
|
10710
11578
|
res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
|
|
10711
11579
|
res.end();
|
|
11580
|
+
closeOpenedFile(opened);
|
|
10712
11581
|
return true;
|
|
10713
11582
|
}
|
|
10714
11583
|
// 断点属于旧文件时从头返回,不能把旧前缀和新后缀拼在一起。
|
|
@@ -10725,6 +11594,7 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
10725
11594
|
connection: "close",
|
|
10726
11595
|
});
|
|
10727
11596
|
res.end();
|
|
11597
|
+
closeOpenedFile(opened);
|
|
10728
11598
|
return true;
|
|
10729
11599
|
}
|
|
10730
11600
|
const start = range ? range.start : 0;
|
|
@@ -10745,9 +11615,20 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
10745
11615
|
res.writeHead(range ? 206 : 200, headers);
|
|
10746
11616
|
if (method === "HEAD" || st.size === 0) {
|
|
10747
11617
|
res.end();
|
|
11618
|
+
closeOpenedFile(opened);
|
|
10748
11619
|
return true;
|
|
10749
11620
|
}
|
|
10750
|
-
|
|
11621
|
+
let source;
|
|
11622
|
+
try {
|
|
11623
|
+
source = opened
|
|
11624
|
+
? createReadStream(opened.actualPath, { fd: opened.fd, start, end, autoClose: true })
|
|
11625
|
+
: createReadStream(target, { start, end });
|
|
11626
|
+
// 句柄所有权移交给 ReadStream(autoClose);后续不再由这里 close。
|
|
11627
|
+
if (opened) opened.fd = null;
|
|
11628
|
+
} catch (err) {
|
|
11629
|
+
closeOpenedFile(opened);
|
|
11630
|
+
throw err;
|
|
11631
|
+
}
|
|
10751
11632
|
// 客户端取消/断开时销毁文件流,避免 fd 泄漏。
|
|
10752
11633
|
res.on("close", () => {
|
|
10753
11634
|
try {
|
|
@@ -10763,7 +11644,12 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
10763
11644
|
// 已销毁
|
|
10764
11645
|
}
|
|
10765
11646
|
});
|
|
10766
|
-
|
|
11647
|
+
try {
|
|
11648
|
+
source.pipe(res);
|
|
11649
|
+
} catch (err) {
|
|
11650
|
+
try { source.destroy(); } catch {}
|
|
11651
|
+
throw err;
|
|
11652
|
+
}
|
|
10767
11653
|
return true;
|
|
10768
11654
|
};
|
|
10769
11655
|
/** 非负整数查询参数;缺失/非法都返回 null(调用方按 400 处理)。 */
|
|
@@ -11154,14 +12040,80 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11154
12040
|
return;
|
|
11155
12041
|
}
|
|
11156
12042
|
if (rest === "/files" && (method === "GET" || method === "HEAD")) {
|
|
11157
|
-
const
|
|
11158
|
-
if (!
|
|
11159
|
-
|
|
12043
|
+
const rawPath = url.searchParams.get("path");
|
|
12044
|
+
if (!rawPath || rawPath === "") return error(res, 400, "bad-request", "missing path");
|
|
12045
|
+
if (rawPath.includes("\0")) return error(res, 400, "bad-request", "invalid path");
|
|
12046
|
+
const pathInside = (parent, child) => {
|
|
12047
|
+
const rel = relative(parent, child);
|
|
12048
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
12049
|
+
};
|
|
12050
|
+
const sessionId = (url.searchParams.get("sessionId") ?? "").trim();
|
|
12051
|
+
let roots = [];
|
|
12052
|
+
let candidateLex;
|
|
12053
|
+
if (sessionId !== "") {
|
|
12054
|
+
// GitLab #16:新客户端必须携带 sessionId;读取范围严格限定该会话当前 cwd。
|
|
12055
|
+
const agents = ctx.get("agents");
|
|
12056
|
+
const sessions = ctx.get("sessions");
|
|
12057
|
+
const liveSession = agents?.get?.(sessionId)?.session ?? sessions?.get?.(sessionId);
|
|
12058
|
+
let cwd = sessionCwdOf(liveSession);
|
|
12059
|
+
if (cwd === undefined) {
|
|
12060
|
+
// 休眠会话(持久化但未激活):从 sessionQuery 持久 header 解析 cwd,
|
|
12061
|
+
// 仍走同一 realpath/fd 守卫;不把“内存里没有”误判成任意路径。
|
|
12062
|
+
const sessionQuery = ctx.get("sessionQuery");
|
|
12063
|
+
if (!sessionQuery?.readSession) return error(res, 404, "session-not-found");
|
|
12064
|
+
const loaded = await loadDormantSession(sessionQuery, sessionId);
|
|
12065
|
+
if (loaded.notFound) return error(res, 404, "session-not-found");
|
|
12066
|
+
if (loaded.corrupt) return error(res, 500, "session-corrupt", "存储的会话存在但回放校验失败");
|
|
12067
|
+
if (loaded.failed) return error(res, 500, "session-read-failed", "会话存在但读取失败");
|
|
12068
|
+
cwd = loaded.snapshot?.session?.cwd ?? loaded.snapshot?.header?.cwd;
|
|
12069
|
+
}
|
|
12070
|
+
if (typeof cwd !== "string" || cwd === "") return error(res, 404, "workspace-not-found");
|
|
12071
|
+
let realCwd;
|
|
12072
|
+
try { realCwd = realpathSync(resolve(normalizeServerPath(cwd))); } catch { return error(res, 404, "workspace-not-found"); }
|
|
12073
|
+
const normalized = normalizeServerPath(rawPath);
|
|
12074
|
+
if ((process.platform !== "win32" && rawPath.includes("\\"))
|
|
12075
|
+
|| isAbsolute(normalized)
|
|
12076
|
+
|| /^[A-Za-z]:/.test(normalized)
|
|
12077
|
+
|| normalized.startsWith("//")) {
|
|
12078
|
+
return error(res, 403, "path-outside-workspace", "path must be relative to the session workspace");
|
|
12079
|
+
}
|
|
12080
|
+
const segments = normalized.split(/[\\/]+/);
|
|
12081
|
+
if (segments.some((segment) => segment === "" || segment === "." || segment === ".." || segment.includes(":"))) {
|
|
12082
|
+
return error(res, 403, "path-outside-workspace", "path must stay inside the session workspace");
|
|
12083
|
+
}
|
|
12084
|
+
candidateLex = resolve(realCwd, normalized);
|
|
12085
|
+
if (!pathInside(realCwd, candidateLex)) return error(res, 403, "path-outside-workspace");
|
|
12086
|
+
roots = [realCwd];
|
|
12087
|
+
} else {
|
|
12088
|
+
// 兼容旧 App:不带 sessionId 时只接受绝对路径,且必须落在已注册工作区(
|
|
12089
|
+
// 不再允许任意宿主路径)。新客户端应带 sessionId 以获得会话级收紧。
|
|
12090
|
+
const normalized = normalizeServerPath(rawPath);
|
|
12091
|
+
const isAbs = isAbsolute(normalized) || /^[A-Za-z]:[\\/]/.test(normalized) || normalized.startsWith("\\\\");
|
|
12092
|
+
if (!isAbs) return error(res, 400, "session-required", "sessionId is required for relative paths");
|
|
12093
|
+
if (normalized.split(/[\\/]+/).some((segment) => segment === "..")) return error(res, 403, "path-outside-workspace");
|
|
12094
|
+
candidateLex = resolve(normalized);
|
|
12095
|
+
const registry = ctx.get("workspaceRegistry");
|
|
12096
|
+
const listed = registry?.list?.();
|
|
12097
|
+
for (const entry of Array.isArray(listed) ? listed : []) {
|
|
12098
|
+
const root = entry?.path;
|
|
12099
|
+
if (typeof root !== "string" || root === "") continue;
|
|
12100
|
+
try { roots.push(realpathSync(resolve(normalizeServerPath(root)))); } catch {}
|
|
12101
|
+
}
|
|
12102
|
+
roots = [...new Set(roots)];
|
|
12103
|
+
if (roots.length === 0) return error(res, 403, "workspace-not-authorized");
|
|
12104
|
+
if (!roots.some((root) => pathInside(root, candidateLex))) return error(res, 403, "path-outside-workspace");
|
|
12105
|
+
}
|
|
12106
|
+
const opened = openVerifiedContainedFile({ candidateLex, roots });
|
|
12107
|
+
if (!opened.ok) return error(res, opened.status, opened.code);
|
|
11160
12108
|
try {
|
|
11161
|
-
serveFileBytes(req, res,
|
|
12109
|
+
serveFileBytes(req, res, opened.actualPath, { method, opened });
|
|
11162
12110
|
} catch (err) {
|
|
11163
|
-
|
|
11164
|
-
|
|
12111
|
+
closeOpenedFile(opened);
|
|
12112
|
+
if (!res.headersSent) {
|
|
12113
|
+
if (err?.code === "not-a-file") return error(res, 400, "not-a-file", "path is not a file");
|
|
12114
|
+
return error(res, 404, "file-not-found", "文件读取失败");
|
|
12115
|
+
}
|
|
12116
|
+
if (!res.destroyed) res.destroy();
|
|
11165
12117
|
}
|
|
11166
12118
|
return;
|
|
11167
12119
|
}
|
|
@@ -11267,6 +12219,244 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11267
12219
|
}
|
|
11268
12220
|
return;
|
|
11269
12221
|
}
|
|
12222
|
+
// ── issue #142:代理面板「团队」页(只读摘要 + 团队开关)────────────────
|
|
12223
|
+
const teamTaskSummary = (tasks) => {
|
|
12224
|
+
const list = Array.isArray(tasks) ? tasks.filter((task) => task?.status !== "deleted") : [];
|
|
12225
|
+
const completed = list.filter((task) => task.status === "completed").length;
|
|
12226
|
+
const inProgress = list.filter((task) => task.status === "in_progress").length;
|
|
12227
|
+
return {
|
|
12228
|
+
total: list.length,
|
|
12229
|
+
completed,
|
|
12230
|
+
inProgress,
|
|
12231
|
+
pending: Math.max(0, list.length - completed - inProgress),
|
|
12232
|
+
};
|
|
12233
|
+
};
|
|
12234
|
+
const teamStatusFor = async (sessionId, signal) => {
|
|
12235
|
+
const sessions = ctx.get("sessions");
|
|
12236
|
+
const agents = ctx.get("agents");
|
|
12237
|
+
const query = ctx.get("sessionQuery");
|
|
12238
|
+
const teamSvc = ctx.get("agentTeams");
|
|
12239
|
+
const subagentsSvc = ctx.get("subagents");
|
|
12240
|
+
let session = sessions?.get?.(sessionId);
|
|
12241
|
+
let events = null;
|
|
12242
|
+
let snapshot = null;
|
|
12243
|
+
if (!session) {
|
|
12244
|
+
if (!query?.readSession) return { notFound: true };
|
|
12245
|
+
const loaded = await loadDormantSession(query, sessionId);
|
|
12246
|
+
if (loaded.notFound) return { notFound: true };
|
|
12247
|
+
if (!loaded.ok) return { readFailed: true };
|
|
12248
|
+
snapshot = loaded.snapshot;
|
|
12249
|
+
events = snapshot?.events ?? [];
|
|
12250
|
+
}
|
|
12251
|
+
if (signal?.aborted) return { aborted: true };
|
|
12252
|
+
const header = session?.header ?? snapshot?.session?.header ?? snapshot?.header ?? {};
|
|
12253
|
+
const root = header?.origin !== "subagent";
|
|
12254
|
+
const agent = agents?.get?.(sessionId);
|
|
12255
|
+
const supported = typeof teamSvc?.isEnabled === "function" && typeof teamSvc?.setEnabled === "function";
|
|
12256
|
+
// #142 复审 P2:团队模式/任务只认宿主权威 projection(live agent +
|
|
12257
|
+
// agentTeams.isEnabled/listTasks)。休眠会话没有 Session 对象可投影,
|
|
12258
|
+
// 不手工折叠 team/mode & team/task——fork 的继承事件可能把父会话状态/任务
|
|
12259
|
+
// 误当本会话;不可得时 modeKnown/tasksAvailable=false,由 UI 显式降级。
|
|
12260
|
+
let enabled = false;
|
|
12261
|
+
let modeKnown = false;
|
|
12262
|
+
if (supported && agent) {
|
|
12263
|
+
try {
|
|
12264
|
+
enabled = teamSvc.isEnabled(agent) === true;
|
|
12265
|
+
modeKnown = true;
|
|
12266
|
+
} catch {
|
|
12267
|
+
modeKnown = false;
|
|
12268
|
+
}
|
|
12269
|
+
}
|
|
12270
|
+
let members = [];
|
|
12271
|
+
let membersAvailable = true;
|
|
12272
|
+
let membersDegraded = false;
|
|
12273
|
+
if (subagentsSvc) {
|
|
12274
|
+
let rows = null;
|
|
12275
|
+
try {
|
|
12276
|
+
if (typeof subagentsSvc.listDescendants === "function") {
|
|
12277
|
+
rows = await subagentsSvc.listDescendants(sessionId, signal);
|
|
12278
|
+
} else if (typeof subagentsSvc.listChildren === "function") {
|
|
12279
|
+
rows = await subagentsSvc.listChildren(sessionId, signal);
|
|
12280
|
+
membersDegraded = true;
|
|
12281
|
+
}
|
|
12282
|
+
} catch {
|
|
12283
|
+
rows = null;
|
|
12284
|
+
}
|
|
12285
|
+
if (signal?.aborted) return { aborted: true };
|
|
12286
|
+
if (Array.isArray(rows)) {
|
|
12287
|
+
members = rows.map((row) => {
|
|
12288
|
+
const id = typeof row?.id === "string" ? row.id : "";
|
|
12289
|
+
const diagnostic = row?.kind === "diagnostic";
|
|
12290
|
+
return {
|
|
12291
|
+
id,
|
|
12292
|
+
name: typeof row?.name === "string" && row.name !== "" ? row.name : null,
|
|
12293
|
+
title: typeof row?.label === "string" && row.label !== ""
|
|
12294
|
+
? row.label
|
|
12295
|
+
: (typeof row?.name === "string" && row.name !== "" ? row.name : id),
|
|
12296
|
+
sessionId: id,
|
|
12297
|
+
kind: diagnostic ? "diagnostic" : "child",
|
|
12298
|
+
status: diagnostic
|
|
12299
|
+
? (["unsupported", "corrupt", "unavailable"].includes(row?.reason) ? row.reason : "unavailable")
|
|
12300
|
+
: (agents?.get?.(id)?.status === "running" ? "running" : "inactive"),
|
|
12301
|
+
...(typeof row?.depth === "number" ? { depth: row.depth } : {}),
|
|
12302
|
+
...(typeof row?.parentId === "string" ? { parentSessionId: row.parentId } : {}),
|
|
12303
|
+
};
|
|
12304
|
+
}).filter((member) => member.id !== "");
|
|
12305
|
+
} else {
|
|
12306
|
+
membersAvailable = false;
|
|
12307
|
+
membersDegraded = true;
|
|
12308
|
+
}
|
|
12309
|
+
} else {
|
|
12310
|
+
membersAvailable = false;
|
|
12311
|
+
membersDegraded = true;
|
|
12312
|
+
}
|
|
12313
|
+
let tasks = [];
|
|
12314
|
+
let tasksAvailable = false;
|
|
12315
|
+
if (supported && agent && typeof teamSvc.listTasks === "function") {
|
|
12316
|
+
try {
|
|
12317
|
+
tasks = teamSvc.listTasks(agent) ?? [];
|
|
12318
|
+
tasksAvailable = true;
|
|
12319
|
+
} catch {
|
|
12320
|
+
tasks = [];
|
|
12321
|
+
tasksAvailable = false;
|
|
12322
|
+
}
|
|
12323
|
+
}
|
|
12324
|
+
if (signal?.aborted) return { aborted: true };
|
|
12325
|
+
let config = {};
|
|
12326
|
+
try {
|
|
12327
|
+
config = await readSessionConfig(sessionId);
|
|
12328
|
+
} catch {
|
|
12329
|
+
config = {};
|
|
12330
|
+
}
|
|
12331
|
+
const modelSelected = typeof config?.model === "string" && config.model !== "" &&
|
|
12332
|
+
typeof config?.provider === "string" && config.provider !== "";
|
|
12333
|
+
const pending = TEAM_PENDING.has(sessionId);
|
|
12334
|
+
// #142 复审 P2:锁的权威来源:
|
|
12335
|
+
// - header.locked 是宿主显式的锁事实(若提供);
|
|
12336
|
+
// - live agent 表示本进程持有该会话的 writer ownership,单写者保证
|
|
12337
|
+
// 此时不存在另一个 writer(因此可判定未锁);
|
|
12338
|
+
// - 休眠会话没有 Session/writer 可判定 → lockedKnown=false,禁用写操作,
|
|
12339
|
+
// 不伪称“未锁”。
|
|
12340
|
+
const headerLocked = typeof header?.locked === "boolean" ? header.locked : undefined;
|
|
12341
|
+
const lockedKnown = headerLocked !== undefined || !!agent;
|
|
12342
|
+
const locked = headerLocked === true;
|
|
12343
|
+
const unavailableReason = !supported
|
|
12344
|
+
? "team-unavailable"
|
|
12345
|
+
: !root
|
|
12346
|
+
? "team-root-required"
|
|
12347
|
+
: !lockedKnown
|
|
12348
|
+
? "team-lock-unknown"
|
|
12349
|
+
: locked
|
|
12350
|
+
? "team-locked"
|
|
12351
|
+
: !agent
|
|
12352
|
+
? "team-session-offline"
|
|
12353
|
+
: !modelSelected
|
|
12354
|
+
? "team-model-unselected"
|
|
12355
|
+
: pending
|
|
12356
|
+
? "team-pending"
|
|
12357
|
+
: null;
|
|
12358
|
+
const title = sessionTitleOf(session ?? { events: events ?? [] }) ?? shortSessionId(sessionId);
|
|
12359
|
+
return {
|
|
12360
|
+
sessionId,
|
|
12361
|
+
supported,
|
|
12362
|
+
root,
|
|
12363
|
+
agentLive: !!agent,
|
|
12364
|
+
enabled,
|
|
12365
|
+
modeKnown,
|
|
12366
|
+
modelSelected,
|
|
12367
|
+
pending,
|
|
12368
|
+
locked,
|
|
12369
|
+
lockedKnown,
|
|
12370
|
+
unavailableReason,
|
|
12371
|
+
canToggle: unavailableReason === null,
|
|
12372
|
+
lead: {
|
|
12373
|
+
id: sessionId,
|
|
12374
|
+
title,
|
|
12375
|
+
status: agent?.status === "running" ? "running" : "inactive",
|
|
12376
|
+
},
|
|
12377
|
+
members,
|
|
12378
|
+
membersAvailable,
|
|
12379
|
+
membersDegraded,
|
|
12380
|
+
tasks: teamTaskSummary(tasks),
|
|
12381
|
+
tasksAvailable,
|
|
12382
|
+
};
|
|
12383
|
+
};
|
|
12384
|
+
if (rest === "/team") {
|
|
12385
|
+
const sessionId = method === "GET" || method === "HEAD"
|
|
12386
|
+
? url.searchParams.get("sessionId")
|
|
12387
|
+
: null;
|
|
12388
|
+
if (method === "GET" || method === "HEAD") {
|
|
12389
|
+
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
12390
|
+
const signal = requestAbort(res);
|
|
12391
|
+
const status = await teamStatusFor(sessionId, signal);
|
|
12392
|
+
if (status.aborted) return;
|
|
12393
|
+
if (status.notFound) return error(res, 404, "session-not-found");
|
|
12394
|
+
if (status.readFailed) return error(res, 500, "session-read-failed");
|
|
12395
|
+
sendJson(res, 200, { ok: true, team: status });
|
|
12396
|
+
return;
|
|
12397
|
+
}
|
|
12398
|
+
if (method === "POST") {
|
|
12399
|
+
const body = await readJson(req, res);
|
|
12400
|
+
if (body === undefined) return;
|
|
12401
|
+
const target = typeof body?.sessionId === "string" ? body.sessionId : "";
|
|
12402
|
+
if (!target) return error(res, 400, "bad-request", "missing sessionId");
|
|
12403
|
+
if (typeof body?.enabled !== "boolean") return error(res, 400, "bad-request", "enabled must be boolean");
|
|
12404
|
+
const teamSvc = ctx.get("agentTeams");
|
|
12405
|
+
if (typeof teamSvc?.setEnabled !== "function") return error(res, 503, "team-unavailable");
|
|
12406
|
+
const sessions = ctx.get("sessions");
|
|
12407
|
+
const agents = ctx.get("agents");
|
|
12408
|
+
let session = sessions?.get?.(target);
|
|
12409
|
+
if (!session) {
|
|
12410
|
+
const query = ctx.get("sessionQuery");
|
|
12411
|
+
if (!query?.readSession) return error(res, 404, "session-not-found");
|
|
12412
|
+
const loaded = await loadDormantSession(query, target);
|
|
12413
|
+
if (loaded.notFound) return error(res, 404, "session-not-found");
|
|
12414
|
+
if (!loaded.ok) return error(res, 500, "session-read-failed");
|
|
12415
|
+
return error(res, 409, "team-session-offline", "当前会话未激活,请先在对话页发送一条消息再修改团队设置");
|
|
12416
|
+
}
|
|
12417
|
+
const header = session?.header ?? {};
|
|
12418
|
+
if (header?.origin === "subagent") return error(res, 409, "team-root-required");
|
|
12419
|
+
if (header?.locked === true) return error(res, 409, "team-locked");
|
|
12420
|
+
const agent = agents?.get?.(target);
|
|
12421
|
+
if (!agent) return error(res, 409, "team-session-offline", "当前会话未激活,请先在对话页发送一条消息再修改团队设置");
|
|
12422
|
+
if (TEAM_PENDING.has(target)) return error(res, 409, "team-pending");
|
|
12423
|
+
// #142 复审 P2:在 **await 之前**原子 claim,否则并发 POST 会同时越过
|
|
12424
|
+
// pending 检查、重复调用 setEnabled。整个配置读取/保存过程都在 finally 释放。
|
|
12425
|
+
TEAM_PENDING.add(target);
|
|
12426
|
+
try {
|
|
12427
|
+
let config = {};
|
|
12428
|
+
try {
|
|
12429
|
+
config = await readSessionConfig(target);
|
|
12430
|
+
} catch {
|
|
12431
|
+
config = {};
|
|
12432
|
+
}
|
|
12433
|
+
if (!(typeof config?.model === "string" && config.model !== "" && typeof config?.provider === "string" && config.provider !== "")) {
|
|
12434
|
+
return error(res, 409, "team-model-unselected", "请先在对话页选择模型和推理等级");
|
|
12435
|
+
}
|
|
12436
|
+
try {
|
|
12437
|
+
await teamSvc.setEnabled(agent, body.enabled);
|
|
12438
|
+
} catch (err) {
|
|
12439
|
+
ctx.logger.warn?.(`mobile-remote: team mode save failed (${target}): ${failureDetail(err)}`);
|
|
12440
|
+
if (err?.code === "TEAM_LEAD_REQUIRED") return error(res, 409, "team-root-required");
|
|
12441
|
+
// POST 的二次锁校验:即便 GET 时未锁,保存时 writer 被占用/lease
|
|
12442
|
+
// 失效也必须拒绝,不能只信客户端/旧 GET。
|
|
12443
|
+
if (err?.name === "SessionAlreadyOwnedError"
|
|
12444
|
+
|| err?.code === "session/writer-held"
|
|
12445
|
+
|| (typeof err?.message === "string" && err.message.includes("already owned"))) {
|
|
12446
|
+
return error(res, 409, "team-locked");
|
|
12447
|
+
}
|
|
12448
|
+
return error(res, 500, "team-save-failed", "无法确认智能体团队协作设置已保存,请重试");
|
|
12449
|
+
}
|
|
12450
|
+
} finally {
|
|
12451
|
+
TEAM_PENDING.delete(target);
|
|
12452
|
+
}
|
|
12453
|
+
const status = await teamStatusFor(target);
|
|
12454
|
+
if (status.notFound) return error(res, 404, "session-not-found");
|
|
12455
|
+
sendJson(res, 200, { ok: true, team: status });
|
|
12456
|
+
return;
|
|
12457
|
+
}
|
|
12458
|
+
return error(res, 405, "method-not-allowed");
|
|
12459
|
+
}
|
|
11270
12460
|
if (rest === "/subagents") {
|
|
11271
12461
|
if (requireGet(method, res)) return;
|
|
11272
12462
|
const parentSessionId = url.searchParams.get("parentSessionId");
|
|
@@ -11278,9 +12468,16 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11278
12468
|
// issue #20:与 /sessions 同一条全量枚举路径,宿主目录与持久化回退都接入请求取消。
|
|
11279
12469
|
const signal = requestAbort(res);
|
|
11280
12470
|
const parent = sessions?.get?.(parentSessionId);
|
|
11281
|
-
// issue #87:rc.2 用 listDescendants
|
|
12471
|
+
// issue #87:rc.2 用 listDescendants(递归全树);rc.1 回退 listChildren。
|
|
12472
|
+
// #140:直接透出整棵树(每行带 parentSessionId/depth/name),不再按 depth===1 收窄;
|
|
12473
|
+
// 旧代/降级路径没有 depth 时显式 multiLevelUnavailable,不伪造层级。
|
|
11282
12474
|
const hasDescendants = typeof subagentsSvc?.listDescendants === "function";
|
|
11283
12475
|
const hasChildren = typeof subagentsSvc?.listChildren === "function";
|
|
12476
|
+
let multiLevelUnavailable = false;
|
|
12477
|
+
// #140 复审 P2:记录实际目录来源。只有确认是 `listChildren` 直系路径时,
|
|
12478
|
+
// 才允许把请求根回填成行 parentSessionId;递归路径缺/非法父子边时输出 null。
|
|
12479
|
+
let catalogSource = null;
|
|
12480
|
+
let recursiveInvalidIds = new Set();
|
|
11284
12481
|
// 目录来源按优先级取——**两边能力都要保留**(issue #14/#17/#21):
|
|
11285
12482
|
// ① 宿主持久目录 `subagents.listChildren`:包含已释放子代理和 mode/label 元数据,
|
|
11286
12483
|
// 不要求父会话有活跃 Agent;
|
|
@@ -11289,19 +12486,61 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11289
12486
|
// 状态另取自活 agent(AgentStatus = idle | running);目录条目本身不带状态。
|
|
11290
12487
|
let catalogRows = null;
|
|
11291
12488
|
let catalogDegraded = false;
|
|
11292
|
-
// 决策 1(A):listDescendants
|
|
12489
|
+
// 决策 1(A,#140):listDescendants 返回整棵树,直接透出(不按 depth 收窄)。
|
|
11293
12490
|
if (hasDescendants) {
|
|
11294
12491
|
try {
|
|
11295
12492
|
const rows = await subagentsSvc.listDescendants(parentSessionId, signal);
|
|
11296
12493
|
if (signal.aborted) return;
|
|
11297
12494
|
if (Array.isArray(rows)) {
|
|
11298
|
-
|
|
11299
|
-
|
|
11300
|
-
|
|
11301
|
-
|
|
11302
|
-
|
|
11303
|
-
|
|
11304
|
-
|
|
12495
|
+
catalogSource = "descendants";
|
|
12496
|
+
catalogRows = rows.map((row) => ({
|
|
12497
|
+
...row,
|
|
12498
|
+
// rc.2 diagnostic 行没有 mode,只有 kind + reason;不要用 mode 判分支。
|
|
12499
|
+
diagnosticReason: row?.kind === "diagnostic" ? row.reason : undefined,
|
|
12500
|
+
}));
|
|
12501
|
+
// #140 复审 P2:递归路径不猜父子边。每行必须携带正整数 depth 与
|
|
12502
|
+
// 非空 parentId;depth=1 的 parent 必须是请求根,depth>1 的 parent
|
|
12503
|
+
// 必须是 depth-1 的已知行。任一无效 → 该行(及依赖它的后代)输出
|
|
12504
|
+
// null 字段,并在响应标 multiLevelUnavailable;负数/小数/缺 depth 同理。
|
|
12505
|
+
const byId = new Map();
|
|
12506
|
+
for (const row of catalogRows) {
|
|
12507
|
+
if (typeof row?.id === "string" && row.id !== "") byId.set(row.id, row);
|
|
12508
|
+
}
|
|
12509
|
+
const invalid = new Set();
|
|
12510
|
+
const isPositiveInt = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1;
|
|
12511
|
+
for (const row of catalogRows) {
|
|
12512
|
+
const id = row?.id;
|
|
12513
|
+
const depth = row?.depth;
|
|
12514
|
+
const parentId = row?.parentId;
|
|
12515
|
+
let ok = typeof id === "string" && id !== "" &&
|
|
12516
|
+
isPositiveInt(depth) &&
|
|
12517
|
+
typeof parentId === "string" && parentId !== "" && parentId !== id;
|
|
12518
|
+
if (ok && depth === 1) {
|
|
12519
|
+
ok = parentId === parentSessionId;
|
|
12520
|
+
} else if (ok) {
|
|
12521
|
+
const parent = byId.get(parentId);
|
|
12522
|
+
ok = !!parent && isPositiveInt(parent.depth) && parent.depth === depth - 1;
|
|
12523
|
+
}
|
|
12524
|
+
if (!ok && typeof id === "string" && id !== "") invalid.add(id);
|
|
12525
|
+
if (!ok && (typeof id !== "string" || id === "")) multiLevelUnavailable = true;
|
|
12526
|
+
}
|
|
12527
|
+
// 父行无效会连带整条链失效(缺 parentId 的 depth=2 行下的孙代理不得伪造挂根)。
|
|
12528
|
+
let changed = true;
|
|
12529
|
+
while (changed) {
|
|
12530
|
+
changed = false;
|
|
12531
|
+
for (const row of catalogRows) {
|
|
12532
|
+
const id = row?.id;
|
|
12533
|
+
if (typeof id !== "string" || id === "" || invalid.has(id)) continue;
|
|
12534
|
+
if (row?.parentId === parentSessionId) continue; // 根是请求会话,不在目录行里
|
|
12535
|
+
const parent = byId.get(row?.parentId);
|
|
12536
|
+
if (!parent || invalid.has(parent.id)) {
|
|
12537
|
+
invalid.add(id);
|
|
12538
|
+
changed = true;
|
|
12539
|
+
}
|
|
12540
|
+
}
|
|
12541
|
+
}
|
|
12542
|
+
recursiveInvalidIds = invalid;
|
|
12543
|
+
if (invalid.size > 0) multiLevelUnavailable = true;
|
|
11305
12544
|
}
|
|
11306
12545
|
} catch {
|
|
11307
12546
|
if (signal.aborted) return;
|
|
@@ -11309,6 +12548,9 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11309
12548
|
}
|
|
11310
12549
|
}
|
|
11311
12550
|
if (catalogRows === null && hasChildren) {
|
|
12551
|
+
// rc.1 只有直接子级:没有 depth/父子边,显式声明无法构建多层树。
|
|
12552
|
+
catalogSource = "children";
|
|
12553
|
+
multiLevelUnavailable = true;
|
|
11312
12554
|
try {
|
|
11313
12555
|
const rows = await subagentsSvc.listChildren(parentSessionId, signal);
|
|
11314
12556
|
if (signal.aborted) return;
|
|
@@ -11336,6 +12578,8 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11336
12578
|
} else if (!persisted.parentExists) {
|
|
11337
12579
|
return error(res, 404, "session-not-found"); // 会话确实不存在(与 develop 语义一致)
|
|
11338
12580
|
} else {
|
|
12581
|
+
catalogSource = "persisted";
|
|
12582
|
+
multiLevelUnavailable = true;
|
|
11339
12583
|
// 刻意**不取**其 `status`:那条路径写死 "inactive",会盖掉注册表的真实状态
|
|
11340
12584
|
catalogRows = persisted.entries.map((entry) => ({
|
|
11341
12585
|
id: entry.id,
|
|
@@ -11346,6 +12590,8 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11346
12590
|
}
|
|
11347
12591
|
}
|
|
11348
12592
|
if (catalogRows === null && (agent || parent)) {
|
|
12593
|
+
catalogSource = "registry";
|
|
12594
|
+
multiLevelUnavailable = true;
|
|
11349
12595
|
catalogRows = (sessions?.list?.() ?? [])
|
|
11350
12596
|
.map((session) => ({ session, header: session?.header ?? {} }))
|
|
11351
12597
|
.filter(({ header }) => header.origin === "subagent" && header.parentSession === parentSessionId)
|
|
@@ -11379,6 +12625,20 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11379
12625
|
return {
|
|
11380
12626
|
id, live, createdAt, label, rowTitle, liveTitle,
|
|
11381
12627
|
rowName: typeof row?.name === "string" && row.name !== "" ? row.name : undefined,
|
|
12628
|
+
// #140 复审 P2:递归路径只用宿主给的 parentId/depth(无效行输出 null,不猜);
|
|
12629
|
+
// 只有直系路径(listChildren/持久化/注册表)才回填请求根。
|
|
12630
|
+
parentSessionId: catalogSource === "descendants"
|
|
12631
|
+
? (recursiveInvalidIds.has(id)
|
|
12632
|
+
? null
|
|
12633
|
+
: (typeof row?.parentId === "string" && row.parentId !== "" ? row.parentId : null))
|
|
12634
|
+
: parentSessionId,
|
|
12635
|
+
depth: catalogSource === "descendants"
|
|
12636
|
+
? (recursiveInvalidIds.has(id)
|
|
12637
|
+
? null
|
|
12638
|
+
: (typeof row?.depth === "number" && Number.isInteger(row.depth) && row.depth >= 1
|
|
12639
|
+
? row.depth
|
|
12640
|
+
: null))
|
|
12641
|
+
: null,
|
|
11382
12642
|
isDiagnostic, diagnosticReason,
|
|
11383
12643
|
};
|
|
11384
12644
|
}).filter((row) => row.id !== "");
|
|
@@ -11395,6 +12655,10 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11395
12655
|
const entries = rows
|
|
11396
12656
|
.map((row) => ({
|
|
11397
12657
|
id: row.id,
|
|
12658
|
+
// #140:树契约字段(可空),UI 据此构建递归树;title/status 逻辑不变。
|
|
12659
|
+
name: row.rowName ?? null,
|
|
12660
|
+
depth: row.depth,
|
|
12661
|
+
parentSessionId: row.parentSessionId,
|
|
11398
12662
|
// issue #87:rc.2 diagnostic 用 kind==='diagnostic' 判定(无 mode 字段);
|
|
11399
12663
|
// reason 映射为三枚举 status:unsupported / corrupt / unavailable(决策 3 C)。
|
|
11400
12664
|
kind: row.isDiagnostic ? "diagnostic" : "child",
|
|
@@ -11420,10 +12684,82 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
11420
12684
|
parentAvailable: !!agent,
|
|
11421
12685
|
// 目录来源不可用时不谎称完整:客户端/诊断可据此区分"确实没有子代理"与"目录读不到"
|
|
11422
12686
|
...(catalogDegraded ? { catalogDegraded: true } : {}),
|
|
12687
|
+
// #140:rc.1/持久化/注册表回退没有 depth/父子边——显式降级,客户端不得伪造多层树。
|
|
12688
|
+
...(multiLevelUnavailable ? { multiLevelUnavailable: true } : {}),
|
|
11423
12689
|
subagents: entries,
|
|
11424
12690
|
});
|
|
11425
12691
|
return;
|
|
11426
12692
|
}
|
|
12693
|
+
if (rest === "/team/tasks") {
|
|
12694
|
+
if (requireGet(method, res)) return;
|
|
12695
|
+
const sessionId = url.searchParams.get("sessionId");
|
|
12696
|
+
if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
|
|
12697
|
+
const agents = ctx.get("agents");
|
|
12698
|
+
const sessions = ctx.get("sessions");
|
|
12699
|
+
const agent = agents?.get?.(sessionId);
|
|
12700
|
+
const session = agent?.session ?? sessions?.get?.(sessionId);
|
|
12701
|
+
if (!session) return error(res, 404, "session-not-found");
|
|
12702
|
+
const team = ctx.get("agentTeams");
|
|
12703
|
+
// 旧宿主没有 agentTeams 服务:明确声明不支持,不伪造空任务板。
|
|
12704
|
+
if (!team || typeof team.listTasks !== "function") {
|
|
12705
|
+
sendJson(res, 200, { ok: true, supported: false, tasks: [] });
|
|
12706
|
+
return;
|
|
12707
|
+
}
|
|
12708
|
+
if (!agent) {
|
|
12709
|
+
// 会话存在但当前没有活 agent:服务 API 需要 live caller,不能静默返回空任务。
|
|
12710
|
+
sendJson(res, 200, { ok: true, supported: true, enabled: false, tasks: [], unavailable: true });
|
|
12711
|
+
return;
|
|
12712
|
+
}
|
|
12713
|
+
let enabled = false;
|
|
12714
|
+
let failure;
|
|
12715
|
+
let rawTasks = [];
|
|
12716
|
+
try {
|
|
12717
|
+
enabled = team.isEnabled?.(agent) === true;
|
|
12718
|
+
rawTasks = enabled ? await Promise.resolve(team.listTasks(agent)) : [];
|
|
12719
|
+
} catch (err) {
|
|
12720
|
+
// 投影失败:保留 supported/enabled 事实,明确返回 failure,UI 不把“读不到”当成“没有任务”。
|
|
12721
|
+
// 复用统一脱敏:不把宿主绝对路径带进任务板错误文案。
|
|
12722
|
+
failure = failureDetail(err).slice(0, 300);
|
|
12723
|
+
rawTasks = [];
|
|
12724
|
+
}
|
|
12725
|
+
const STATUSES = new Set(["pending", "in_progress", "completed"]);
|
|
12726
|
+
const tasks = [];
|
|
12727
|
+
for (const raw of Array.isArray(rawTasks) ? rawTasks : []) {
|
|
12728
|
+
const id = typeof raw?.id === "string" ? raw.id : "";
|
|
12729
|
+
const subject = typeof raw?.subject === "string" ? raw.subject.trim() : "";
|
|
12730
|
+
const status = typeof raw?.status === "string" ? raw.status : "";
|
|
12731
|
+
// 已删除不显示;未知状态/坏记录不猜测,计入 failure 让 UI 显式降级。
|
|
12732
|
+
if (status === "deleted") continue;
|
|
12733
|
+
if (!id || !subject || !STATUSES.has(status)) {
|
|
12734
|
+
failure ??= "任务记录无效(缺少 id/subject 或未知状态)";
|
|
12735
|
+
continue;
|
|
12736
|
+
}
|
|
12737
|
+
const blockedBy = Array.isArray(raw.blockedBy)
|
|
12738
|
+
? [...new Set(raw.blockedBy.filter((value) => typeof value === "string" && value !== ""))]
|
|
12739
|
+
: [];
|
|
12740
|
+
tasks.push({
|
|
12741
|
+
id,
|
|
12742
|
+
subject,
|
|
12743
|
+
status,
|
|
12744
|
+
blockedBy,
|
|
12745
|
+
...(typeof raw.ownerId === "string" && raw.ownerId !== "" ? { ownerId: raw.ownerId } : {}),
|
|
12746
|
+
...(typeof raw.ownerName === "string" && raw.ownerName !== "" ? { ownerName: raw.ownerName } : {}),
|
|
12747
|
+
});
|
|
12748
|
+
}
|
|
12749
|
+
const byId = new Map(tasks.map((task) => [task.id, task]));
|
|
12750
|
+
for (const task of tasks) {
|
|
12751
|
+
// ready 由服务端推导(未完成 blocker 存在即 false),不把派生状态混入持久状态。
|
|
12752
|
+
task.ready = task.status === "pending" && task.blockedBy.every((id) => byId.get(id)?.status === "completed");
|
|
12753
|
+
}
|
|
12754
|
+
sendJson(res, 200, {
|
|
12755
|
+
ok: true,
|
|
12756
|
+
supported: true,
|
|
12757
|
+
enabled,
|
|
12758
|
+
tasks,
|
|
12759
|
+
...(failure === undefined ? {} : { failure }),
|
|
12760
|
+
});
|
|
12761
|
+
return;
|
|
12762
|
+
}
|
|
11427
12763
|
if (rest === "/subagents/interrupt") {
|
|
11428
12764
|
if (requirePost(method, res)) return;
|
|
11429
12765
|
const body = await readJson(req, res);
|
|
@@ -12690,6 +14026,9 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
12690
14026
|
] : [];
|
|
12691
14027
|
const unsubscribeSession = ctx.on("session/event", onSessionEvent);
|
|
12692
14028
|
const unsubscribeStatus = ctx.on("agent/status", onAgentStatus);
|
|
14029
|
+
// #146:宿主插件管理进度 → 本插件的操作快照(只按 requestId 匹配,不改宿主状态)。
|
|
14030
|
+
const unsubscribePluginInstall = ctx.on?.("plugin-manager/install-state", notePluginOperationProgress) ?? (() => {});
|
|
14031
|
+
const unsubscribePluginUpdate = ctx.on?.("plugin-manager/update-state", notePluginOperationProgress) ?? (() => {});
|
|
12693
14032
|
// v2.7.2 review(M3/M4):会话销毁 → 清理该会话全部跟踪状态(通知判定/活跃度/上下文/挂起帧)
|
|
12694
14033
|
const unsubscribeDisposed = ctx.on("agent/disposed", ({ agent }) => {
|
|
12695
14034
|
const sid = agentSessionId(agent);
|
|
@@ -12859,6 +14198,8 @@ export function apply(ctx, config, runtime = {}) {
|
|
|
12859
14198
|
lanPort = 0;
|
|
12860
14199
|
unsubscribeSession();
|
|
12861
14200
|
unsubscribeStatus();
|
|
14201
|
+
unsubscribePluginInstall?.();
|
|
14202
|
+
unsubscribePluginUpdate?.();
|
|
12862
14203
|
unsubscribeDisposed?.();
|
|
12863
14204
|
clearInterval(pruneTimer);
|
|
12864
14205
|
clearInterval(heldSweepTimer);
|