dsh-devdock 2.0.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/host/index.js CHANGED
@@ -107,6 +107,25 @@ import {
107
107
  sortFindings,
108
108
  } from './review.js';
109
109
 
110
+ // DevDock 的 Cloudflare 模块(REST API v4:账号、Pages、Workers、Zones、部署)。
111
+ import {
112
+ verifyToken as verifyCfToken,
113
+ listAccounts as listCfAccounts,
114
+ listPagesProjects,
115
+ deletePagesProject,
116
+ createPagesProject,
117
+ listWorkers,
118
+ deleteWorker,
119
+ listZones,
120
+ cfOverview,
121
+ detectProjectKind,
122
+ collectUploadFiles,
123
+ createPagesDeployment,
124
+ resolveWorkerMain,
125
+ deployWorkerModule,
126
+ dashUrl,
127
+ } from './cloudflare.js';
128
+
110
129
  // Robust Service base class fallback: the same technique the reference plugin
111
130
  // uses, so this module can be imported (and exercised) outside a cordis host.
112
131
  let ServiceClass;
@@ -2080,6 +2099,77 @@ export class GithubLinkHost extends ServiceClass {
2080
2099
  }
2081
2100
  }
2082
2101
 
2102
+ /**
2103
+ * One `cloudflare` tool call. Every arm delegates to a method above, so the
2104
+ * model and the panel can never diverge (one operation, two callers).
2105
+ *
2106
+ * @param {object} args
2107
+ * @param {{resolvePath?: () => Promise<string>}} context
2108
+ * @returns {Promise<object>}
2109
+ */
2110
+ async cloudflareToolCall(args, context = {}) {
2111
+ const action = String(args?.action ?? '');
2112
+ const cwd = async () => {
2113
+ const explicit = optionalString(args?.path);
2114
+ if (explicit) return explicit;
2115
+ if (typeof context.resolvePath === 'function') {
2116
+ const resolved = await context.resolvePath();
2117
+ if (typeof resolved === 'string' && resolved !== '') return resolved;
2118
+ }
2119
+ return process.cwd();
2120
+ };
2121
+ switch (action) {
2122
+ case 'accounts': {
2123
+ const data = await this.cloudflareAccounts();
2124
+ return { action, ...data };
2125
+ }
2126
+ case 'overview': {
2127
+ const data = await this.cloudflareOverview();
2128
+ return { action, ...data };
2129
+ }
2130
+ case 'projects': {
2131
+ const data = await this.cloudflareProjects();
2132
+ return { action, ...data };
2133
+ }
2134
+ case 'workers': {
2135
+ const data = await this.cloudflareWorkers();
2136
+ return { action, ...data };
2137
+ }
2138
+ case 'zones': {
2139
+ const data = await this.cloudflareZones();
2140
+ return { action, ...data };
2141
+ }
2142
+ case 'detect': {
2143
+ const data = await this.cloudflareDetect({ path: await cwd() });
2144
+ return { action, ...data };
2145
+ }
2146
+ case 'deploy': {
2147
+ const data = await this.cloudflareDeploy({
2148
+ path: await cwd(),
2149
+ kind: optionalString(args?.kind),
2150
+ project: optionalString(args?.project),
2151
+ name: optionalString(args?.name),
2152
+ });
2153
+ return { action, ...data };
2154
+ }
2155
+ case 'review': {
2156
+ const data = await this.cloudflareReview({
2157
+ path: await cwd(),
2158
+ kind: optionalString(args?.kind),
2159
+ presetIds: Array.isArray(args?.presetIds) ? args.presetIds : [],
2160
+ customPrompt: optionalString(args?.customPrompt) ?? '',
2161
+ });
2162
+ return { action, ...data };
2163
+ }
2164
+ default:
2165
+ throw httpError(
2166
+ 400,
2167
+ 'BAD_REQUEST',
2168
+ `未知 action「${action}」;可用:accounts、overview、projects、workers、zones、detect、deploy、review。`,
2169
+ );
2170
+ }
2171
+ }
2172
+
2083
2173
  /* ---------------- repository information (languages + assets) ---------------- */
2084
2174
 
2085
2175
  /**
@@ -2704,9 +2794,17 @@ export class GithubLinkHost extends ServiceClass {
2704
2794
  cwd: dir,
2705
2795
  env: npmAuthEnv(account.token),
2706
2796
  });
2707
- const packed = mapPackResult(parsePackJson(result.stdout));
2797
+ // npm publish 的输出不是 pack 的 JSON 结构,别用 parsePackJson 解析。
2798
+ // 从 package.json 读回真实的 name/version,这是发布出去的确切值。
2799
+ let name = '';
2800
+ let version = '';
2801
+ try {
2802
+ const doc = JSON.parse(await readFile(path.join(dir, 'package.json'), 'utf8'));
2803
+ name = doc.name ?? '';
2804
+ version = doc.version ?? '';
2805
+ } catch { /* 读不到就用空值 */ }
2708
2806
  await this.#store.touchNpmAccount(account.id);
2709
- return { published: true, name: packed.name, version: packed.version };
2807
+ return { published: true, name, version };
2710
2808
  } catch (error) {
2711
2809
  const text = `${error.stderr || ''} ${error.message || ''}`;
2712
2810
  if (/EOTP|one-time password|two-factor/i.test(text)) {
@@ -3391,6 +3489,494 @@ export class GithubLinkHost extends ServiceClass {
3391
3489
  };
3392
3490
  }
3393
3491
 
3492
+ /* ---------------- Cloudflare module (CONTRACT §6) ---------------- */
3493
+
3494
+ /**
3495
+ * 当前 Cloudflare 账号(带令牌),缺失时给出可执行提示而不是空结果。
3496
+ * @returns {Promise<object>}
3497
+ */
3498
+ async #requireCloudflareAccount() {
3499
+ const account = await this.#store.activeCloudflareAccount();
3500
+ if (!account) {
3501
+ throw httpError(401, 'NO_ACCOUNT', '还没有登录 Cloudflare。请在 设置 › Cloudflare 中添加一个 API Token 或 Global API Key。');
3502
+ }
3503
+ return account;
3504
+ }
3505
+
3506
+ /**
3507
+ * 把一条已存账号折算成 Cloudflare 客户端要的凭据对象。
3508
+ * @param {object} account store 里的账号记录
3509
+ * @returns {{kind: string, token?: string, email?: string, key?: string}}
3510
+ */
3511
+ #cloudflareCredential(account) {
3512
+ if (account.authKind === 'global') {
3513
+ return { kind: 'global', email: account.email, key: account.token };
3514
+ }
3515
+ return { kind: 'token', token: account.token };
3516
+ }
3517
+
3518
+ /**
3519
+ * 当前账号的 accountId;账号存在但还没选账户时,自动列账户并取第一个。
3520
+ * @returns {Promise<{account: object, accountId: string}>}
3521
+ */
3522
+ async #cloudflareContext() {
3523
+ const account = await this.#requireCloudflareAccount();
3524
+ if (account.accountId !== '') {
3525
+ return { account, accountId: account.accountId };
3526
+ }
3527
+ const accounts = await listCfAccounts(this.#cloudflareCredential(account));
3528
+ if (accounts.length === 0) {
3529
+ throw httpError(400, 'NO_ACCOUNT', '这个 Cloudflare 凭据下没有可用的账户。');
3530
+ }
3531
+ const chosen = accounts[0];
3532
+ await this.#store.updateCloudflareAccount(account.id, {
3533
+ accountId: chosen.id,
3534
+ accountName: chosen.name,
3535
+ });
3536
+ return { account, accountId: chosen.id };
3537
+ }
3538
+
3539
+ /**
3540
+ * `GET /cf/accounts` — Cloudflare 账号列表(不带令牌)。
3541
+ * @returns {Promise<object>}
3542
+ */
3543
+ async cloudflareAccounts() {
3544
+ return this.#store.cloudflareAccounts();
3545
+ }
3546
+
3547
+ /**
3548
+ * `POST /cf/account` — 校验凭据后存储。
3549
+ *
3550
+ * 支持两种登录方式:
3551
+ * - `{ token }` —— API Token(cfut_ / cfat_ 或旧 40 位字母数字)
3552
+ * - `{ email, key }` —— Global API Key(cfk_ 或旧 37-45 位十六进制,全权限)
3553
+ *
3554
+ * @param {object} body `{ token?, email?, key?, authKind?, label? }`
3555
+ * @returns {Promise<object>}
3556
+ */
3557
+ async cloudflareAccountAdd(body) {
3558
+ const wantsGlobal = optionalString(body.key) !== undefined
3559
+ || String(body.authKind ?? '') === 'global';
3560
+
3561
+ let credential;
3562
+ if (wantsGlobal) {
3563
+ const email = requireString(body, 'email', 'Cloudflare 账户邮箱').trim();
3564
+ const key = requireString(body, 'key', 'Global API Key').trim();
3565
+ credential = { kind: 'global', email, key };
3566
+ } else {
3567
+ const token = requireString(body, 'token', 'Cloudflare API Token').trim();
3568
+ credential = { kind: 'token', token };
3569
+ }
3570
+
3571
+ const verified = await verifyCfToken(credential);
3572
+
3573
+ let accountName = '';
3574
+ let accountId = '';
3575
+ try {
3576
+ const accounts = await listCfAccounts(credential);
3577
+ if (accounts.length > 0) {
3578
+ accountId = accounts[0].id;
3579
+ accountName = accounts[0].name;
3580
+ }
3581
+ } catch { /* 账户列表失败不阻止登录;账号卡里仍可手动触发 */ }
3582
+
3583
+ const fallback = credential.kind === 'global'
3584
+ ? (verified.email || credential.email)
3585
+ : (accountName || 'Cloudflare 账号');
3586
+ const label = optionalString(body.label) ?? fallback;
3587
+
3588
+ return this.#store.saveCloudflareAccount({
3589
+ authKind: credential.kind,
3590
+ login: label,
3591
+ email: credential.kind === 'global' ? credential.email : '',
3592
+ token: credential.kind === 'global' ? credential.key : credential.token,
3593
+ accountId,
3594
+ accountName,
3595
+ });
3596
+ }
3597
+
3598
+ /**
3599
+ * `POST /cf/account/remove`.
3600
+ * @param {object} body `{ id }`
3601
+ * @returns {Promise<{removed: boolean}>}
3602
+ */
3603
+ async cloudflareAccountRemove(body) {
3604
+ const id = requireString(body, 'id', '账号 id');
3605
+ const removed = await this.#store.deleteCloudflareAccount(id);
3606
+ if (!removed) throw httpError(404, 'NOT_FOUND', '找不到这个 Cloudflare 账号,可能已被移除。');
3607
+ return { removed: true };
3608
+ }
3609
+
3610
+ /**
3611
+ * `POST /cf/account/active`.
3612
+ * @param {object} body `{ id }`
3613
+ * @returns {Promise<{activeId: string}>}
3614
+ */
3615
+ async cloudflareAccountActive(body) {
3616
+ const id = requireString(body, 'id', '账号 id');
3617
+ const ok = await this.#store.setActiveCloudflareAccount(id);
3618
+ if (!ok) throw httpError(404, 'NOT_FOUND', '找不到这个 Cloudflare 账号。');
3619
+ return { activeId: id };
3620
+ }
3621
+
3622
+ /**
3623
+ * `POST /cf/account/select` — 登录后选择 Cloudflare account。
3624
+ * @param {object} body `{ accountId, accountName }`
3625
+ * @returns {Promise<object>}
3626
+ */
3627
+ async cloudflareAccountSelect(body) {
3628
+ const account = await this.#requireCloudflareAccount();
3629
+ const accountId = requireString(body, 'accountId', 'Cloudflare 账户 id');
3630
+ return this.#store.updateCloudflareAccount(account.id, {
3631
+ accountId,
3632
+ accountName: optionalString(body.accountName) ?? '',
3633
+ });
3634
+ }
3635
+
3636
+ /**
3637
+ * `GET /cf/accounts/list` — 当前凭据可访问的 Cloudflare 账户(选择器用)。
3638
+ * @returns {Promise<object>}
3639
+ */
3640
+ async cloudflareAccountList() {
3641
+ const account = await this.#requireCloudflareAccount();
3642
+ const items = await listCfAccounts(this.#cloudflareCredential(account));
3643
+ return { items, activeAccountId: account.accountId };
3644
+ }
3645
+
3646
+ /**
3647
+ * `GET /cf/overview` — 设置页项目概览卡的数据源。
3648
+ * @returns {Promise<object>}
3649
+ */
3650
+ async cloudflareOverview() {
3651
+ const { account, accountId } = await this.#cloudflareContext();
3652
+ const result = await cfOverview(this.#cloudflareCredential(account), accountId);
3653
+ await this.#store.touchCloudflareAccount(account.id);
3654
+ return {
3655
+ accountId,
3656
+ accountName: account.accountName || accountId,
3657
+ ...result,
3658
+ };
3659
+ }
3660
+
3661
+ /**
3662
+ * `GET /cf/projects` — Pages 项目列表。
3663
+ * @returns {Promise<object>}
3664
+ */
3665
+ async cloudflareProjects() {
3666
+ const { account, accountId } = await this.#cloudflareContext();
3667
+ const items = await listPagesProjects(this.#cloudflareCredential(account), accountId);
3668
+ await this.#store.touchCloudflareAccount(account.id);
3669
+ return { items, accountId };
3670
+ }
3671
+
3672
+ /**
3673
+ * `POST /cf/projects/create`.
3674
+ * @param {object} body `{ name, productionBranch? }`
3675
+ * @returns {Promise<object>}
3676
+ */
3677
+ async cloudflareProjectCreate(body) {
3678
+ const { account, accountId } = await this.#cloudflareContext();
3679
+ const name = requireString(body, 'name', '项目名');
3680
+ const project = await createPagesProject(
3681
+ this.#cloudflareCredential(account),
3682
+ accountId,
3683
+ name,
3684
+ optionalString(body.productionBranch) ?? 'main',
3685
+ );
3686
+ await this.#store.touchCloudflareAccount(account.id);
3687
+ return { project };
3688
+ }
3689
+
3690
+ /**
3691
+ * `POST /cf/projects/delete` — 危险操作,需 `confirm: true`。
3692
+ * @param {object} body `{ name, confirm }`
3693
+ * @returns {Promise<{deleted: boolean}>}
3694
+ */
3695
+ async cloudflareProjectDelete(body) {
3696
+ const { account, accountId } = await this.#cloudflareContext();
3697
+ const name = requireString(body, 'name', '项目名');
3698
+ if (optionalBool(body.confirm, false) !== true) {
3699
+ throw httpError(
3700
+ 409,
3701
+ 'CONFLICT',
3702
+ `删除 Pages 项目 ${name} 会移除它的所有部署与域名绑定,无法撤销。请确认后再执行(confirm: true)。`,
3703
+ );
3704
+ }
3705
+ const result = await deletePagesProject(this.#cloudflareCredential(account), accountId, name);
3706
+ await this.#store.touchCloudflareAccount(account.id);
3707
+ return result;
3708
+ }
3709
+
3710
+ /**
3711
+ * `GET /cf/workers` — Workers 列表。
3712
+ * @returns {Promise<object>}
3713
+ */
3714
+ async cloudflareWorkers() {
3715
+ const { account, accountId } = await this.#cloudflareContext();
3716
+ const items = await listWorkers(this.#cloudflareCredential(account), accountId);
3717
+ await this.#store.touchCloudflareAccount(account.id);
3718
+ return { items, accountId };
3719
+ }
3720
+
3721
+ /**
3722
+ * `POST /cf/workers/delete` — 危险操作,需 `confirm: true`。
3723
+ * @param {object} body `{ name, confirm }`
3724
+ * @returns {Promise<{deleted: boolean}>}
3725
+ */
3726
+ async cloudflareWorkerDelete(body) {
3727
+ const { account, accountId } = await this.#cloudflareContext();
3728
+ const name = requireString(body, 'name', 'Worker 名');
3729
+ if (optionalBool(body.confirm, false) !== true) {
3730
+ throw httpError(
3731
+ 409,
3732
+ 'CONFLICT',
3733
+ `删除 Worker ${name} 会移除它的线上代码,无法撤销。请确认后再执行(confirm: true)。`,
3734
+ );
3735
+ }
3736
+ const result = await deleteWorker(this.#cloudflareCredential(account), accountId, name);
3737
+ await this.#store.touchCloudflareAccount(account.id);
3738
+ return result;
3739
+ }
3740
+
3741
+ /**
3742
+ * `GET /cf/zones` — 域名列表。
3743
+ * @returns {Promise<object>}
3744
+ */
3745
+ async cloudflareZones() {
3746
+ const { account, accountId } = await this.#cloudflareContext();
3747
+ const items = await listZones(this.#cloudflareCredential(account), accountId);
3748
+ await this.#store.touchCloudflareAccount(account.id);
3749
+ return { items, accountId };
3750
+ }
3751
+
3752
+ /**
3753
+ * `GET /cf/detect?path=` — 探测目录是 Pages 还是 Worker 项目。
3754
+ * @param {{path: string}} query
3755
+ * @returns {Promise<object>}
3756
+ */
3757
+ async cloudflareDetect(query) {
3758
+ const dir = requireString(query, 'path', '目录路径');
3759
+ const kind = await detectProjectKind(dir);
3760
+ return { kind };
3761
+ }
3762
+
3763
+ /**
3764
+ * `POST /cf/deploy` — 一键部署 Pages 或 Worker。
3765
+ *
3766
+ * @param {object} body `{ path, kind?, project?, name?, branch?, environment? }`
3767
+ * @returns {Promise<object>}
3768
+ */
3769
+ async cloudflareDeploy(body) {
3770
+ const dir = requireString(body, 'path', '目录路径');
3771
+ const { account, accountId } = await this.#cloudflareContext();
3772
+ const requestedKind = optionalString(body.kind);
3773
+ const detected = requestedKind ? { type: requestedKind, dir } : await detectProjectKind(dir);
3774
+
3775
+ if (!detected || (detected.type !== 'pages' && detected.type !== 'worker')) {
3776
+ throw httpError(
3777
+ 400,
3778
+ 'BAD_REQUEST',
3779
+ '这个目录既不是 Pages 静态产物(缺 dist/build/index.html),也不是 Worker 项目(缺 wrangler 配置)。'
3780
+ + '请先构建前端产物,或初始化 wrangler.toml 后再部署。',
3781
+ );
3782
+ }
3783
+
3784
+ if (detected.type === 'pages') {
3785
+ const project = optionalString(body.project);
3786
+ if (!project) {
3787
+ throw httpError(400, 'BAD_REQUEST', '部署 Pages 需要指定项目名(project),或先在面板里选择/新建一个项目。');
3788
+ }
3789
+ const deployment = await createPagesDeployment(
3790
+ this.#cloudflareCredential(account),
3791
+ accountId,
3792
+ project,
3793
+ { directory: detected.dir, branch: optionalString(body.branch) },
3794
+ );
3795
+ await this.#store.touchCloudflareAccount(account.id);
3796
+ return {
3797
+ kind: 'pages',
3798
+ project,
3799
+ deployment,
3800
+ dashUrl: dashUrl(accountId, `workers-and-pages/view/pages/${project}`),
3801
+ };
3802
+ }
3803
+
3804
+ const name = optionalString(body.name);
3805
+ if (!name) {
3806
+ throw httpError(400, 'BAD_REQUEST', '部署 Worker 需要指定 Worker 名(name)。');
3807
+ }
3808
+ const mainFile = await resolveWorkerMain(detected.dir);
3809
+ if (!mainFile) {
3810
+ throw httpError(400, 'BAD_REQUEST', '找不到 Worker 入口文件(wrangler 配置里的 main,或 src/index.js / index.js)。');
3811
+ }
3812
+ const { readFile } = await import('node:fs/promises');
3813
+ const { join } = await import('node:path');
3814
+ let bytes;
3815
+ try {
3816
+ bytes = await readFile(join(detected.dir, mainFile));
3817
+ } catch {
3818
+ throw httpError(400, 'BAD_REQUEST', `无法读取 Worker 入口文件 ${mainFile}。`);
3819
+ }
3820
+ const result = await deployWorkerModule(this.#cloudflareCredential(account), accountId, name, {
3821
+ mainFile,
3822
+ bytes,
3823
+ });
3824
+ await this.#store.touchCloudflareAccount(account.id);
3825
+ return {
3826
+ kind: 'worker',
3827
+ name,
3828
+ url: result.url,
3829
+ dashUrl: dashUrl(accountId, `workers/view/${name}`),
3830
+ };
3831
+ }
3832
+
3833
+ /**
3834
+ * `POST /cf/review` — 部署前审查(复用 review 引擎)。
3835
+ *
3836
+ * @param {object} body `{ path, kind?, presetIds?, customPrompt?, provider?, model?, reasoningEffort? }`
3837
+ * @returns {Promise<object>}
3838
+ */
3839
+ async cloudflareReview(body) {
3840
+ const dir = requireString(body, 'path', '目录路径');
3841
+ const requestedKind = optionalString(body.kind);
3842
+ const detected = requestedKind ? { type: requestedKind, dir } : await detectProjectKind(dir);
3843
+
3844
+ const files = [];
3845
+ const chunks = [];
3846
+ let truncated = false;
3847
+
3848
+ if (detected && detected.type === 'pages') {
3849
+ const collected = await collectUploadFiles(detected.dir);
3850
+ if (collected.exceeded) truncated = true;
3851
+ for (const row of collected.files) {
3852
+ if (/(^|\/)node_modules\//.test(row.path)) continue;
3853
+ let text = '';
3854
+ try {
3855
+ text = row.bytes.toString('utf8');
3856
+ } catch { text = ''; }
3857
+ if (text.includes('\u0000')) continue;
3858
+ files.push({ path: row.path });
3859
+ if (text !== '') chunks.push({ path: row.path, text: text.slice(0, MAX_FILE_BYTES) });
3860
+ }
3861
+ } else if (detected && detected.type === 'worker') {
3862
+ const mainFile = await resolveWorkerMain(detected.dir);
3863
+ if (mainFile) {
3864
+ try {
3865
+ const { readFile } = await import('node:fs/promises');
3866
+ const { join } = await import('node:path');
3867
+ const text = (await readFile(join(detected.dir, mainFile))).toString('utf8');
3868
+ files.push({ path: mainFile });
3869
+ chunks.push({ path: mainFile, text: text.slice(0, MAX_FILE_BYTES) });
3870
+ } catch { /* 读不到就跳过 */ }
3871
+ }
3872
+ } else {
3873
+ return {
3874
+ reviewId: `cfreview_${Date.now().toString(36)}`,
3875
+ scope: 'cloudflare',
3876
+ files: [],
3877
+ findings: [],
3878
+ summary: '这个目录不是可部署的 Pages / Worker 项目,无需审查。',
3879
+ degraded: true,
3880
+ };
3881
+ }
3882
+
3883
+ const ruleFindings = [];
3884
+ for (const chunk of chunks) {
3885
+ ruleFindings.push(...scanSecrets(chunk.text, { file: chunk.path }));
3886
+ }
3887
+ for (const row of files) {
3888
+ if (/^\.env($|\.)/.test(row.path)) {
3889
+ ruleFindings.push(normalizeFinding({
3890
+ severity: 'blocker',
3891
+ category: 'secrets',
3892
+ title: '产物里包含环境变量文件',
3893
+ detail: '.env 会被上传到公开的 Pages 站点,等于公开密钥。请从产物中移除 .env*,改用环境变量注入。',
3894
+ file: row.path,
3895
+ }));
3896
+ }
3897
+ }
3898
+
3899
+ const presetIds = Array.isArray(body.presetIds)
3900
+ ? body.presetIds.filter((id) => typeof id === 'string' && id !== '')
3901
+ : [];
3902
+ const stored = await this.#store.reviewPresets();
3903
+ const chosen = [
3904
+ ...BUILTIN_PRESETS.filter((preset) => presetIds.includes(preset.id)),
3905
+ ...stored.filter((preset) => presetIds.includes(preset.id)),
3906
+ ];
3907
+ const customPrompt = optionalString(body.customPrompt) ?? '';
3908
+ const llm = this.#llm();
3909
+ let provider = optionalString(body.provider);
3910
+ let model = optionalString(body.model);
3911
+ if (llm && (!provider || !model)) {
3912
+ try {
3913
+ const fallback = await this.reviewModels();
3914
+ if (fallback.default) {
3915
+ provider = provider ?? fallback.default.provider;
3916
+ model = model ?? fallback.default.model;
3917
+ }
3918
+ } catch { /* 保留调用方给的值 */ }
3919
+ }
3920
+
3921
+ let modelFindings = [];
3922
+ let summary = '';
3923
+ let usage;
3924
+ let degraded = false;
3925
+ if (chunks.length === 0) {
3926
+ summary = '没有可审查的文本内容。';
3927
+ } else if (!llm) {
3928
+ degraded = true;
3929
+ summary = '宿主未提供 llm 服务,本次只执行了规则检查(敏感信息扫描)。';
3930
+ } else if (!provider || !model) {
3931
+ degraded = true;
3932
+ summary = '未找到可用的模型,本次只执行了规则检查(敏感信息扫描)。';
3933
+ } else {
3934
+ const instructions = [
3935
+ ...chosen.map((preset) => `## ${preset.title}\n${preset.prompt}`),
3936
+ ...(customPrompt ? [`## 用户补充要求\n${customPrompt}`] : []),
3937
+ ].join('\n\n');
3938
+ const promptParts = [
3939
+ instructions,
3940
+ '## 审查范围',
3941
+ '这是即将部署到 Cloudflare 的文件内容(Pages 静态产物或 Worker 入口)。',
3942
+ `## 文件(${files.length} 个)`,
3943
+ files.map((row) => `- ${row.path}`).join('\n'),
3944
+ '## 内容',
3945
+ chunks.map((chunk) => `### ${chunk.path}\n\`\`\`\n${chunk.text}\n\`\`\``).join('\n\n'),
3946
+ ].filter(Boolean);
3947
+ try {
3948
+ const result = await runModelReview(llm, {
3949
+ provider,
3950
+ model,
3951
+ reasoningEffort: optionalString(body.reasoningEffort),
3952
+ prompt: promptParts.join('\n\n'),
3953
+ });
3954
+ modelFindings = result.findings.map(normalizeFinding);
3955
+ summary = result.summary;
3956
+ usage = result.usage;
3957
+ } catch (error) {
3958
+ degraded = true;
3959
+ summary = `模型审查失败(${String(error && error.message ? error.message : error)}),本次只执行了规则检查。`;
3960
+ }
3961
+ }
3962
+
3963
+ const findings = sortFindings([...ruleFindings, ...modelFindings]);
3964
+ if (summary === '') {
3965
+ summary = findings.length === 0 ? '未发现明显问题。' : `共发现 ${findings.length} 处需要关注的问题。`;
3966
+ }
3967
+ return {
3968
+ reviewId: `cfreview_${Date.now().toString(36)}`,
3969
+ scope: 'cloudflare',
3970
+ kind: detected?.type ?? null,
3971
+ files,
3972
+ findings,
3973
+ summary,
3974
+ usage,
3975
+ degraded,
3976
+ truncated,
3977
+ };
3978
+ }
3979
+
3394
3980
  /**
3395
3981
  * The host `llm` service, when this composition has one.
3396
3982
  * @returns {object|undefined}
@@ -3453,13 +4039,18 @@ export class GithubLinkHost extends ServiceClass {
3453
4039
  if (typeof ctx.inject === 'function') {
3454
4040
  ctx.inject(['tools'], (scoped) => {
3455
4041
  const disposeTool = registerTool(scoped, this);
3456
- if (disposeTool) {
4042
+ const disposeCfTool = registerCloudflareTool(scoped, this);
4043
+ const disposeAll = () => {
4044
+ try { if (typeof disposeCfTool === 'function') disposeCfTool(); } catch { /* gone */ }
4045
+ try { if (typeof disposeTool === 'function') disposeTool(); } catch { /* gone */ }
4046
+ };
4047
+ if (disposeTool || disposeCfTool) {
3457
4048
  if (typeof scoped.effect === 'function') {
3458
- scoped.effect(() => disposeTool, 'push: github_link tool');
4049
+ scoped.effect(() => disposeAll, 'push: github_link + cloudflare tools');
3459
4050
  } else {
3460
4051
  this.#stop = ((previous) => () => {
3461
4052
  try {
3462
- disposeTool();
4053
+ disposeAll();
3463
4054
  } finally {
3464
4055
  previous();
3465
4056
  }
@@ -3524,6 +4115,23 @@ function buildRoutes(host) {
3524
4115
  get('/npm/deps', async ({ query }) => ({
3525
4116
  data: await host.npmProjectDeps({ path: query('path') }),
3526
4117
  })),
4118
+ // §6 Cloudflare:账号、概览、Pages、Workers、Zones、部署与审查
4119
+ get('/cf/accounts', async () => ({ data: await host.cloudflareAccounts() })),
4120
+ post('/cf/account', async ({ body }) => ({ data: await host.cloudflareAccountAdd(body) })),
4121
+ post('/cf/account/remove', async ({ body }) => ({ data: await host.cloudflareAccountRemove(body) })),
4122
+ post('/cf/account/active', async ({ body }) => ({ data: await host.cloudflareAccountActive(body) })),
4123
+ post('/cf/account/select', async ({ body }) => ({ data: await host.cloudflareAccountSelect(body) })),
4124
+ get('/cf/accounts/list', async () => ({ data: await host.cloudflareAccountList() })),
4125
+ get('/cf/overview', async () => ({ data: await host.cloudflareOverview() })),
4126
+ get('/cf/projects', async () => ({ data: await host.cloudflareProjects() })),
4127
+ post('/cf/projects/create', async ({ body }) => ({ data: await host.cloudflareProjectCreate(body) })),
4128
+ post('/cf/projects/delete', async ({ body }) => ({ data: await host.cloudflareProjectDelete(body) })),
4129
+ get('/cf/workers', async () => ({ data: await host.cloudflareWorkers() })),
4130
+ post('/cf/workers/delete', async ({ body }) => ({ data: await host.cloudflareWorkerDelete(body) })),
4131
+ get('/cf/zones', async () => ({ data: await host.cloudflareZones() })),
4132
+ get('/cf/detect', async ({ query }) => ({ data: await host.cloudflareDetect({ path: query('path') }) })),
4133
+ post('/cf/deploy', async ({ body }) => ({ data: await host.cloudflareDeploy(body) })),
4134
+ post('/cf/review', async ({ body }) => ({ data: await host.cloudflareReview(body) })),
3527
4135
  get('/diagnostics', async () => ({ data: await host.diagnostics() })),
3528
4136
  post('/accounts/token', async ({ body }) => ({ data: await host.addTokenAccount(body) })),
3529
4137
  post('/accounts/device/start', async () => ({ data: await host.deviceStart() })),
@@ -3959,6 +4567,145 @@ function registerTool(ctx, host) {
3959
4567
  }
3960
4568
  }
3961
4569
 
4570
+ /* ------------------------------------------------------------------ */
4571
+ /* Cloudflare agent tool */
4572
+ /* ------------------------------------------------------------------ */
4573
+
4574
+ /** `cloudflare` 工具的参数 schema(只允许宿主支持的 JSON Schema 子集)。 */
4575
+ const CF_TOOL_PARAMETERS = {
4576
+ type: 'object',
4577
+ properties: {
4578
+ action: {
4579
+ type: 'string',
4580
+ enum: ['accounts', 'overview', 'projects', 'workers', 'zones', 'detect', 'deploy', 'review'],
4581
+ description: '要执行的操作:accounts(已登录 Cloudflare 账号)、overview(账户概览)、projects(Pages 项目)、workers(Workers 列表)、zones(域名)、detect(探测目录类型)、deploy(部署 Pages/Worker)、review(部署前审查)。',
4582
+ },
4583
+ path: {
4584
+ type: 'string',
4585
+ description: 'detect/deploy/review 时的目录绝对路径;省略则用当前会话工作目录。',
4586
+ },
4587
+ kind: {
4588
+ type: 'string',
4589
+ enum: ['pages', 'worker'],
4590
+ description: 'deploy/review 时指定部署类型;省略则自动探测。',
4591
+ },
4592
+ project: {
4593
+ type: 'string',
4594
+ description: 'deploy 时 Pages 项目名。',
4595
+ },
4596
+ name: {
4597
+ type: 'string',
4598
+ description: 'deploy 时 Worker 名。',
4599
+ },
4600
+ presetIds: {
4601
+ type: 'array',
4602
+ items: { type: 'string' },
4603
+ description: 'review 时要使用的内置审查项 id。',
4604
+ },
4605
+ customPrompt: {
4606
+ type: 'string',
4607
+ description: 'review 时的额外审查要求。',
4608
+ },
4609
+ },
4610
+ required: ['action'],
4611
+ };
4612
+
4613
+ /** `cloudflare` 工具输出 schema。 */
4614
+ const CF_TOOL_OUTPUT_SCHEMA = {
4615
+ type: 'object',
4616
+ additionalProperties: true,
4617
+ properties: {
4618
+ action: { type: 'string' },
4619
+ },
4620
+ };
4621
+
4622
+ /** 渲染 `cloudflare` 工具结果为模型读的文本。 */
4623
+ function renderCloudflareResult(value) {
4624
+ const action = String(value?.action ?? '');
4625
+ if (action === 'accounts') {
4626
+ const accounts = value.accounts ?? [];
4627
+ if (accounts.length === 0) return '【accounts】还没有登录任何 Cloudflare 账号。';
4628
+ return ['【accounts】']
4629
+ .concat(accounts.map((a) => ` ${a.login}${a.id === value.activeId ? '(当前)' : ''}${a.accountName ? ' · ' + a.accountName : ''}`))
4630
+ .join('\n');
4631
+ }
4632
+ if (action === 'overview') {
4633
+ const pages = value.pages?.count ?? 0;
4634
+ const workers = value.workers?.count ?? 0;
4635
+ const zones = value.zones?.count ?? 0;
4636
+ return `【overview】Pages 项目 ${pages} · Workers ${workers} · 域名 ${zones}`;
4637
+ }
4638
+ if (action === 'projects') {
4639
+ const items = value.items ?? [];
4640
+ if (items.length === 0) return '【projects】没有 Pages 项目。';
4641
+ return ['【projects】'].concat(items.map((p) => ` ${p.name}${p.latestUrl ? ' · ' + p.latestUrl : ''}`)).join('\n');
4642
+ }
4643
+ if (action === 'workers') {
4644
+ const items = value.items ?? [];
4645
+ if (items.length === 0) return '【workers】没有 Workers。';
4646
+ return ['【workers】'].concat(items.map((w) => ` ${w.name}`)).join('\n');
4647
+ }
4648
+ if (action === 'zones') {
4649
+ const items = value.items ?? [];
4650
+ if (items.length === 0) return '【zones】没有域名。';
4651
+ return ['【zones】'].concat(items.map((z) => ` ${z.name}(${z.status})`)).join('\n');
4652
+ }
4653
+ if (action === 'detect') {
4654
+ if (!value.kind) return '【detect】这个目录既不是 Pages 静态产物,也不是 Worker 项目。';
4655
+ return `【detect】检测为 ${value.kind === 'pages' ? 'Pages 静态站点' : 'Worker 项目'}。`;
4656
+ }
4657
+ if (action === 'deploy') {
4658
+ if (value.kind === 'pages') return `【deploy】Pages「${value.project}」部署完成:${value.deployment?.url || ''}`;
4659
+ if (value.kind === 'worker') return `【deploy】Worker「${value.name}」部署完成:${value.url || ''}`;
4660
+ }
4661
+ return JSON.stringify(value);
4662
+ }
4663
+
4664
+ function registerCloudflareTool(ctx, host) {
4665
+ const tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools;
4666
+ if (!tools || typeof tools.register !== 'function') return null;
4667
+
4668
+ const definition = {
4669
+ name: 'cloudflare',
4670
+ description:
4671
+ '操作当前账号的 Cloudflare 资源:查看已登录账号与账户概览(Pages 项目数 / Workers 数 / 域名数)、列出 Pages 项目、Workers 和域名,'
4672
+ + '以及探测目录类型、部署 Pages 静态站点或 Worker、部署前审查。'
4673
+ + '所有输出为中文文本。部署/审查默认作用于当前会话工作目录,需要别的目录时传绝对路径 path。'
4674
+ + 'API Token 或 Global API Key 由插件里已登录的当前账号提供,绝不写进代码或配置。',
4675
+ parameters: CF_TOOL_PARAMETERS,
4676
+ output: {
4677
+ schema: CF_TOOL_OUTPUT_SCHEMA,
4678
+ render: (_args, value) => [{ type: 'text', text: renderCloudflareResult(value) }],
4679
+ },
4680
+ timeoutMs: 200_000,
4681
+ isConcurrencySafe: () => false,
4682
+ async execute(args, exec) {
4683
+ exec?.signal?.throwIfAborted?.();
4684
+ const sessionCwd = exec?.agent?.session?.header?.cwd
4685
+ ?? exec?.agent?.session?.cwd
4686
+ ?? undefined;
4687
+ try {
4688
+ return await host.cloudflareToolCall(args ?? {}, {
4689
+ resolvePath: async () => (typeof sessionCwd === 'string' ? sessionCwd : process.cwd()),
4690
+ });
4691
+ } catch (error) {
4692
+ const wire = toWireError(error, (text) => redactSecrets(text));
4693
+ throw new Error(`[${wire.code}] ${wire.message}`);
4694
+ }
4695
+ },
4696
+ };
4697
+
4698
+ try {
4699
+ const dispose = tools.register(definition);
4700
+ return () => {
4701
+ if (typeof dispose === 'function') dispose();
4702
+ };
4703
+ } catch (error) {
4704
+ console?.warn?.(`dsh-push: cloudflare 工具注册失败:${error?.message ?? error}`);
4705
+ return null;
4706
+ }
4707
+ }
4708
+
3962
4709
  /** Resolve the git binary this host would use right now (diagnostics). */
3963
4710
  export function currentGitBinary(gitPath) {
3964
4711
  return resolveGitBinary(gitPath);